├── .gitignore ├── LICENSE ├── README ├── README.md ├── REASON.md ├── bitherj ├── .gitignore ├── build.gradle ├── proguard-rules.pro └── src │ ├── main │ └── java │ │ └── net │ │ └── bither │ │ └── bitherj │ │ ├── AbstractApp.java │ │ ├── BitherjSettings.java │ │ ├── ISetting.java │ │ ├── NotificationService.java │ │ ├── api │ │ ├── BitherErrorApi.java │ │ ├── BitherMytransactionsApi.java │ │ ├── BitherTrustManager.java │ │ ├── BlockChainDownloadSpvApi.java │ │ ├── BlockChainGetLatestBlockApi.java │ │ ├── BlockChainMytransactionsApi.java │ │ ├── ConnectHttps.java │ │ ├── CookieFactory.java │ │ ├── CreateHDMAddressApi.java │ │ ├── DownloadFile.java │ │ ├── DownloadSpvApi.java │ │ ├── GetBlockCountApi.java │ │ ├── GetCookieApi.java │ │ ├── GetExchangeDepthApi.java │ │ ├── GetExchangeTickerApi.java │ │ ├── GetExchangeTrendApi.java │ │ ├── GetHDMBIdRandomApi.java │ │ ├── GetInSignaturesApi.java │ │ ├── GetKlineApi.java │ │ ├── PushTxThirdParty.java │ │ ├── RecoveryHDMApi.java │ │ ├── SignatureHDMApi.java │ │ ├── TrustCert.java │ │ ├── UploadAvatarApi.java │ │ ├── UploadHDMBidApi.java │ │ └── http │ │ │ ├── BaseHttpResponse.java │ │ │ ├── BaseHttpsResponse.java │ │ │ ├── BitherUrl.java │ │ │ ├── Http400Exception.java │ │ │ ├── Http404Exception.java │ │ │ ├── Http500Exception.java │ │ │ ├── HttpAuthException.java │ │ │ ├── HttpException.java │ │ │ ├── HttpGetResponse.java │ │ │ ├── HttpNoConnectException.java │ │ │ ├── HttpPostResponse.java │ │ │ ├── HttpRefusedException.java │ │ │ ├── HttpRequestException.java │ │ │ ├── HttpServerException.java │ │ │ ├── HttpSetting.java │ │ │ ├── HttpsGetResponse.java │ │ │ └── HttpsPostResponse.java │ │ ├── core │ │ ├── AbstractHD.java │ │ ├── Address.java │ │ ├── AddressManager.java │ │ ├── Block.java │ │ ├── BlockChain.java │ │ ├── BloomFilter.java │ │ ├── DesktopHDMAddress.java │ │ ├── DesktopHDMKeychain.java │ │ ├── EnterpriseHDMAddress.java │ │ ├── EnterpriseHDMKeychain.java │ │ ├── EnterpriseHDMSeed.java │ │ ├── EnterpriseHDMTxSignaturePool.java │ │ ├── HDAccount.java │ │ ├── HDAccountCold.java │ │ ├── HDMAddress.java │ │ ├── HDMBId.java │ │ ├── HDMKeychain.java │ │ ├── In.java │ │ ├── Out.java │ │ ├── OutPoint.java │ │ ├── Peer.java │ │ ├── PeerManager.java │ │ ├── Tx.java │ │ ├── TxBuilder.java │ │ ├── UnSignTransaction.java │ │ └── Version.java │ │ ├── crypto │ │ ├── DumpedPrivateKey.java │ │ ├── ECKey.java │ │ ├── EncryptedData.java │ │ ├── EncryptedPrivateKey.java │ │ ├── KeyCrypter.java │ │ ├── KeyCrypterException.java │ │ ├── KeyCrypterScrypt.java │ │ ├── NativeSecp256k1.java │ │ ├── PasswordSeed.java │ │ ├── SecureCharSequence.java │ │ ├── TransactionSignature.java │ │ ├── bip38 │ │ │ ├── Bip38.java │ │ │ ├── Bip38Util.java │ │ │ └── Rijndael.java │ │ ├── hd │ │ │ ├── ChildNumber.java │ │ │ ├── DeterministicKey.java │ │ │ ├── HDDerivationException.java │ │ │ ├── HDKeyDerivation.java │ │ │ └── HDUtils.java │ │ └── mnemonic │ │ │ ├── MnemonicCode.java │ │ │ ├── MnemonicException.java │ │ │ └── PBKDF2SHA512.java │ │ ├── db │ │ ├── AbstractDb.java │ │ ├── IAddressProvider.java │ │ ├── IBlockProvider.java │ │ ├── IDesktopAddressProvider.java │ │ ├── IDesktopTxProvider.java │ │ ├── IEnterpriseHDMProvider.java │ │ ├── IHDAccountAddressProvider.java │ │ ├── IHDAccountProvider.java │ │ ├── IPeerProvider.java │ │ ├── ITxProvider.java │ │ └── imp │ │ │ ├── AbstractAddressProvider.java │ │ │ ├── AbstractBlockProvider.java │ │ │ ├── AbstractHDAccountAddressProvider.java │ │ │ ├── AbstractHDAccountProvider.java │ │ │ ├── AbstractPeerProvider.java │ │ │ ├── AbstractProvider.java │ │ │ ├── AbstractTxProvider.java │ │ │ └── base │ │ │ ├── ICursor.java │ │ │ ├── IDb.java │ │ │ └── IProvider.java │ │ ├── delegate │ │ ├── HDMHotAdd.java │ │ ├── HDMSingular.java │ │ ├── IPasswordGetter.java │ │ └── IPasswordGetterDelegate.java │ │ ├── exception │ │ ├── AddressFormatException.java │ │ ├── BlockStoreException.java │ │ ├── PasswordException.java │ │ ├── ProtocolException.java │ │ ├── ScriptException.java │ │ ├── TxBuilderException.java │ │ └── VerificationException.java │ │ ├── factory │ │ ├── ImportHDSeed.java │ │ └── ImportPrivateKey.java │ │ ├── message │ │ ├── AddressMessage.java │ │ ├── AlertMessage.java │ │ ├── BitcoinSerializer.java │ │ ├── BlockMessage.java │ │ ├── ChildMessage.java │ │ ├── EmptyMessage.java │ │ ├── FilteredBlockMessage.java │ │ ├── GetAddrMessage.java │ │ ├── GetBlocksMessage.java │ │ ├── GetDataMessage.java │ │ ├── GetHeadersMessage.java │ │ ├── HeadersMessage.java │ │ ├── InventoryMessage.java │ │ ├── ListMessage.java │ │ ├── MemoryPoolMessage.java │ │ ├── Message.java │ │ ├── NotFoundMessage.java │ │ ├── PartialMerkleTree.java │ │ ├── PeerAddress.java │ │ ├── PingMessage.java │ │ ├── PongMessage.java │ │ ├── RejectMessage.java │ │ ├── UnknownMessage.java │ │ ├── VersionAck.java │ │ └── VersionMessage.java │ │ ├── net │ │ ├── AbstractTimeoutHandler.java │ │ ├── ClientConnectionManager.java │ │ ├── ConnectionHandler.java │ │ ├── MessageWriteTarget.java │ │ ├── NioClientManager.java │ │ ├── PeerSocketHandler.java │ │ └── StreamParser.java │ │ ├── qrcode │ │ ├── QRCodeEnodeUtil.java │ │ ├── QRCodeTransportPage.java │ │ ├── QRCodeTxTransport.java │ │ ├── QRCodeUtil.java │ │ └── SaltForQRCode.java │ │ ├── runnable │ │ └── EditPasswordThread.java │ │ ├── script │ │ ├── Script.java │ │ ├── ScriptBuilder.java │ │ ├── ScriptChunk.java │ │ └── ScriptOpCodes.java │ │ └── utils │ │ ├── Base58.java │ │ ├── Base64.java │ │ ├── BlockUtil.java │ │ ├── CharSequenceUtil.java │ │ ├── DnsDiscovery.java │ │ ├── DynamicWire.java │ │ ├── GenericUtils.java │ │ ├── InventoryItem.java │ │ ├── PrivateKeyUtil.java │ │ ├── Sha256Hash.java │ │ ├── Threading.java │ │ ├── TransactionsUtil.java │ │ ├── UnitUtil.java │ │ ├── UnsafeByteArrayOutputStream.java │ │ ├── UpgradeAddressUtil.java │ │ ├── Utils.java │ │ └── VarInt.java │ └── test │ ├── java │ └── net │ │ └── bither │ │ └── bitherj │ │ ├── core │ │ ├── AddressTest.java │ │ ├── BlockTest.java │ │ ├── HDMIdTest.java │ │ ├── MultisigAddressTest.java │ │ ├── PeerManagerTest.java │ │ ├── StringTest.java │ │ ├── TestImplAbstractApp.java │ │ ├── TxTest.java │ │ ├── UtilsTest.java │ │ └── https │ │ │ └── HttpsTest.java │ │ ├── crypto │ │ ├── Bip38Test.java │ │ ├── ECKeyTest.java │ │ ├── KeyCrypterScryptTest.java │ │ ├── MultisigTest.java │ │ ├── PasswordSeedTest.java │ │ ├── hd │ │ │ └── HDDerivationTest.java │ │ └── mnemonic │ │ │ └── MnemonicCodeTest.java │ │ └── script │ │ ├── ScriptChunkTest.java │ │ └── ScriptTest.java │ └── resources │ └── net │ └── bither │ └── bitherj │ ├── core │ └── https │ │ └── bithertruststore.jks │ ├── crypto │ └── mnemonic │ │ └── wordlist │ │ └── english.txt │ └── script │ ├── script_invalid.json │ ├── script_valid.json │ ├── tx_invalid.json │ └── tx_valid.json ├── doc └── REASON.SecureCharSequence.md ├── gradle.properties ├── scripts ├── cert2keystore_bks.sh └── cert2keystore_jks.sh └── settings.gradle /.gitignore: -------------------------------------------------------------------------------- 1 | */target/* 2 | */bin/* 3 | */gen/* 4 | */.classpath 5 | */.settings/* 6 | */.idea/* 7 | .idea/* 8 | .gradle/* 9 | */classes/* 10 | *.iml 11 | *.class 12 | */build/* 13 | build/* 14 | gradle/wrapper/* 15 | gradlew* 16 | local.properties -------------------------------------------------------------------------------- /README: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bither/bitherj/1dff0be6b7622ffc8d1a12f157c76b11ed2e9ef0/README -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | Bitherj 2 | ======= 3 | Bitherj is a Bitcoin Library for android. 4 | 5 | There is also an [iOS version](https://github.com/bither/bitheri). 6 | 7 | We use Bitherj in our Bither Wallet which alse open source on github [bither-android](https://github.com/bither/bither-android). 8 | 9 | ## Feature 10 | 11 | * Complete Bitcoin Protocol (SPV) 12 | * SQLite 13 | * Seperated TXs & Private Keys 14 | 15 | 16 | ## Donation 17 | 18 | Donate : 1BitherUnNvB2NsfxMnbS35kS3DTPr7PW5 19 | 20 | ## Website 21 | 22 | [Bither.net](http://bither.net) 23 | -------------------------------------------------------------------------------- /bitherj/.gitignore: -------------------------------------------------------------------------------- 1 | /build 2 | -------------------------------------------------------------------------------- /bitherj/build.gradle: -------------------------------------------------------------------------------- 1 | apply plugin: 'java' 2 | 3 | sourceCompatibility = 1.5 4 | 5 | repositories { 6 | mavenLocal() 7 | mavenCentral() 8 | // jcenter() 9 | } 10 | 11 | dependencies { 12 | compile fileTree(dir: 'libs', include: ['*.jar']) 13 | compile 'org.json:json:20140107@jar' 14 | compile 'com.google.guava:guava:13.0.1@jar' 15 | compile 'com.google.code.findbugs:jsr305:2.0.1@jar' 16 | 17 | compile 'com.lambdaworks:scrypt:1.4.0@jar' 18 | compile 'org.slf4j:slf4j-api:1.7.7' 19 | compile 'com.madgag.spongycastle:core:1.51.0.0' 20 | 21 | compile 'org.apache.httpcomponents:httpclient:4.2.1@jar' 22 | compile 'org.apache.httpcomponents:httpmime:4.1@jar' 23 | compile 'org.apache.httpcomponents:httpcore:4.3.2@jar' 24 | compile 'org.apache.james:apache-mime4j-core:0.7.1@jar' 25 | 26 | testCompile group: 'junit', name: 'junit', version: '4.11' 27 | testCompile fileTree(dir: 'libs', include: ['*.jar']) 28 | testCompile 'org.json:json:20140107@jar' 29 | testCompile 'com.google.guava:guava:13.0.1@jar' 30 | testCompile 'com.google.code.findbugs:jsr305:2.0.1@jar' 31 | 32 | testCompile 'com.lambdaworks:scrypt:1.4.0@jar' 33 | testCompile 'org.slf4j:slf4j-api:1.7.7' 34 | testCompile 'com.madgag.spongycastle:core:1.51.0.0' 35 | testCompile 'org.apache.httpcomponents:httpclient:4.2.1@jar' 36 | testCompile 'org.apache.httpcomponents:httpmime:4.1@jar' 37 | testCompile 'org.apache.httpcomponents:httpcore:4.3.2@jar' 38 | testCompile 'org.apache.james:apache-mime4j-core:0.7.1@jar' 39 | testCompile 'ch.qos.logback:logback-classic:1.0.9@jar' 40 | testCompile 'ch.qos.logback:logback-core:1.0.9@jar' 41 | testCompile 'commons-logging:commons-logging:1.2@jar' 42 | } 43 | 44 | -------------------------------------------------------------------------------- /bitherj/proguard-rules.pro: -------------------------------------------------------------------------------- 1 | # Add project specific ProGuard rules here. 2 | # By default, the flags in this file are appended to flags specified 3 | # in /Users/nn/Documents/android-sdk-macosx/tools/proguard/proguard-android.txt 4 | # You can edit the include path and order by changing the proguardFiles 5 | # directive in build.gradle. 6 | # 7 | # For more details, see 8 | # http://developer.android.com/guide/developing/tools/proguard.html 9 | 10 | # Add any project specific keep options here: 11 | 12 | # If your project uses WebView with JS, uncomment the following 13 | # and specify the fully qualified class name to the JavaScript interface 14 | # class: 15 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview { 16 | # public *; 17 | #} 18 | -------------------------------------------------------------------------------- /bitherj/src/main/java/net/bither/bitherj/AbstractApp.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2014 http://Bither.net 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package net.bither.bitherj; 18 | 19 | import net.bither.bitherj.api.TrustCert; 20 | 21 | public abstract class AbstractApp { 22 | public static NotificationService notificationService; 23 | public static ISetting bitherjSetting; 24 | public static TrustCert trustCert; 25 | 26 | public static boolean addressIsReady = false; 27 | 28 | public void construct() { 29 | bitherjSetting = initSetting(); 30 | notificationService = initNotification(); 31 | trustCert = initTrustCert(); 32 | } 33 | 34 | protected abstract TrustCert initTrustCert(); 35 | 36 | protected abstract ISetting initSetting(); 37 | 38 | protected abstract NotificationService initNotification(); 39 | } 40 | -------------------------------------------------------------------------------- /bitherj/src/main/java/net/bither/bitherj/ISetting.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2014 http://Bither.net 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package net.bither.bitherj; 18 | 19 | import net.bither.bitherj.qrcode.QRCodeUtil; 20 | 21 | import org.apache.http.client.CookieStore; 22 | 23 | import java.io.File; 24 | 25 | public abstract class ISetting { 26 | 27 | private static final int HDM_ADDRESS_PER_SEED_COUNT_LIMIT = 100; 28 | private static final int HDM_ADDRESS_PER_SEED_PREPARE_COUNT = 100; 29 | private static final int WATCH_ONLY_ADDRESS_COUNT_LIMIT = 150; 30 | private static final int PRIVATE_KEY_OF_HOT_COUNT_LIMIT = 50; 31 | 32 | public abstract BitherjSettings.AppMode getAppMode(); 33 | 34 | public abstract boolean getBitherjDoneSyncFromSpv(); 35 | 36 | public abstract void setBitherjDoneSyncFromSpv(boolean isDone); 37 | 38 | public abstract boolean getDownloadSpvFinish(); 39 | 40 | public abstract void setDownloadSpvFinish(boolean finish); 41 | 42 | public abstract QRCodeUtil.QRQuality getQRQuality(); 43 | 44 | public abstract BitherjSettings.TransactionFeeMode getTransactionFeeMode(); 45 | 46 | public abstract BitherjSettings.ApiConfig getApiConfig(); 47 | 48 | public abstract File getPrivateDir(String dirName); 49 | 50 | public abstract boolean isApplicationRunInForeground(); 51 | 52 | public abstract CookieStore getCookieStore(); 53 | 54 | public int hdmAddressPerSeedCount() { 55 | return HDM_ADDRESS_PER_SEED_COUNT_LIMIT; 56 | } 57 | 58 | public int hdmAddressPerSeedPrepareCount() { 59 | return HDM_ADDRESS_PER_SEED_PREPARE_COUNT; 60 | } 61 | 62 | public int watchOnlyAddressCountLimit() { 63 | return WATCH_ONLY_ADDRESS_COUNT_LIMIT; 64 | } 65 | 66 | public int privateKeyOfHotCountLimit() { 67 | return PRIVATE_KEY_OF_HOT_COUNT_LIMIT; 68 | } 69 | 70 | } 71 | -------------------------------------------------------------------------------- /bitherj/src/main/java/net/bither/bitherj/NotificationService.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2014 http://Bither.net 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package net.bither.bitherj; 17 | 18 | import net.bither.bitherj.core.Tx; 19 | 20 | public interface NotificationService { 21 | 22 | void sendBroadcastSyncSPVFinished(boolean isFinished); 23 | 24 | void removeBroadcastSyncSPVFinished(); 25 | 26 | void sendBroadcastGetSpvBlockComplete(boolean isComplete); 27 | 28 | void sendLastBlockChange(); 29 | 30 | void notificatTx(String address, Tx tx, Tx.TxNotificationType txNotificationType, 31 | long deltaBalance); 32 | 33 | void sendBroadcastPeerState(int numPeers); 34 | 35 | void removeBroadcastPeerState(); 36 | 37 | void sendBroadcastAddressLoadCompleteState(); 38 | 39 | void removeAddressLoadCompleteState(); 40 | 41 | void sendConnectedChangeBroadcast(String connectedChangeBroadcast, boolean isConnected); 42 | 43 | void sendBroadcastProgressState(double value); 44 | 45 | void removeProgressState(); 46 | } 47 | -------------------------------------------------------------------------------- /bitherj/src/main/java/net/bither/bitherj/api/BitherErrorApi.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2014 http://Bither.net 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package net.bither.bitherj.api; 18 | 19 | import net.bither.bitherj.api.http.BitherUrl; 20 | import net.bither.bitherj.api.http.HttpPostResponse; 21 | import net.bither.bitherj.utils.Utils; 22 | 23 | import org.apache.http.HttpEntity; 24 | import org.apache.http.NameValuePair; 25 | import org.apache.http.client.entity.UrlEncodedFormEntity; 26 | import org.apache.http.message.BasicNameValuePair; 27 | import org.apache.http.protocol.HTTP; 28 | 29 | import java.util.ArrayList; 30 | import java.util.List; 31 | 32 | public class BitherErrorApi extends HttpPostResponse { 33 | 34 | private static String ERROR_MSG = "error_msg"; 35 | private String mErrorMsg; 36 | 37 | public BitherErrorApi(String errorMsg) { 38 | this.mErrorMsg = errorMsg; 39 | setUrl(BitherUrl.BITHER_ERROR_API); 40 | } 41 | 42 | @Override 43 | public HttpEntity getHttpEntity() throws Exception { 44 | List params = new ArrayList(); 45 | if (!Utils.isEmpty(this.mErrorMsg)) { 46 | params.add(new BasicNameValuePair(ERROR_MSG, this.mErrorMsg.trim())); 47 | } 48 | return new UrlEncodedFormEntity(params, HTTP.UTF_8); 49 | } 50 | 51 | @Override 52 | public void setResult(String response) throws Exception { 53 | 54 | } 55 | 56 | } 57 | -------------------------------------------------------------------------------- /bitherj/src/main/java/net/bither/bitherj/api/BitherMytransactionsApi.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2014 http://Bither.net 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package net.bither.bitherj.api; 18 | 19 | import net.bither.bitherj.api.http.BitherUrl; 20 | import net.bither.bitherj.api.http.HttpGetResponse; 21 | import net.bither.bitherj.utils.Utils; 22 | 23 | 24 | public class BitherMytransactionsApi extends HttpGetResponse { 25 | public static final int bitherWebType = 0; 26 | public static final int blockChainWebType = 1; 27 | 28 | public BitherMytransactionsApi(String address) { 29 | this(address, 1); 30 | } 31 | 32 | public BitherMytransactionsApi(String address, int page) { 33 | String url = Utils.format(BitherUrl.BITHER_Q_MYTRANSACTIONS, 34 | address); 35 | if (page > 0) { 36 | url = url + "/p/" + page; 37 | } 38 | setUrl(url); 39 | } 40 | 41 | @Override 42 | public void setResult(String response) throws Exception { 43 | this.result = response; 44 | } 45 | 46 | } 47 | -------------------------------------------------------------------------------- /bitherj/src/main/java/net/bither/bitherj/api/BlockChainDownloadSpvApi.java: -------------------------------------------------------------------------------- 1 | package net.bither.bitherj.api; 2 | 3 | import net.bither.bitherj.api.http.BitherUrl; 4 | import net.bither.bitherj.api.http.HttpGetResponse; 5 | import net.bither.bitherj.api.http.HttpsGetResponse; 6 | import net.bither.bitherj.core.Block; 7 | import net.bither.bitherj.utils.BlockUtil; 8 | import net.bither.bitherj.utils.Utils; 9 | 10 | import org.json.JSONArray; 11 | import org.json.JSONObject; 12 | import org.json.JSONString; 13 | 14 | 15 | public class BlockChainDownloadSpvApi extends HttpsGetResponse { 16 | public BlockChainDownloadSpvApi (int height){ 17 | String url = Utils.format(BitherUrl.BLOCKCHAIN_INFO_GET_SPVBLOCK_API, height); 18 | setUrl(url); 19 | } 20 | 21 | @Override 22 | public void setResult(String response) throws Exception { 23 | JSONObject jsonObject = new JSONObject(response); 24 | JSONArray jsonArray = jsonObject.getJSONArray("blocks"); 25 | JSONObject jsonObject1 = (JSONObject) jsonArray.get(0); 26 | this.result = BlockUtil.formatStoreBlockFromBlockChainInfo(jsonObject1); 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /bitherj/src/main/java/net/bither/bitherj/api/BlockChainGetLatestBlockApi.java: -------------------------------------------------------------------------------- 1 | package net.bither.bitherj.api; 2 | 3 | import net.bither.bitherj.api.http.BitherUrl; 4 | import net.bither.bitherj.api.http.HttpGetResponse; 5 | import net.bither.bitherj.api.http.HttpsGetResponse; 6 | import net.bither.bitherj.core.Block; 7 | import net.bither.bitherj.utils.BlockUtil; 8 | 9 | import org.json.JSONObject; 10 | 11 | public class BlockChainGetLatestBlockApi extends HttpsGetResponse { 12 | public BlockChainGetLatestBlockApi(){ 13 | setUrl(BitherUrl.BLOCKCHAIN_INFO_GET_LASTST_BLOCK); 14 | } 15 | 16 | @Override 17 | public void setResult(String response) throws Exception { 18 | JSONObject jsonObject = new JSONObject(response); 19 | this.result = BlockUtil.getLatestBlockHeight(jsonObject); 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /bitherj/src/main/java/net/bither/bitherj/api/BlockChainMytransactionsApi.java: -------------------------------------------------------------------------------- 1 | package net.bither.bitherj.api; 2 | 3 | import net.bither.bitherj.api.http.BitherUrl; 4 | import net.bither.bitherj.api.http.HttpsGetResponse; 5 | import net.bither.bitherj.utils.Utils; 6 | 7 | /** 8 | * Created by zhangbo on 16/1/9. 9 | */ 10 | public class BlockChainMytransactionsApi extends HttpsGetResponse { 11 | 12 | @Override 13 | public void setResult(String response) throws Exception { 14 | this.result = response; 15 | } 16 | 17 | public BlockChainMytransactionsApi(String address) { 18 | String url = Utils.format(BitherUrl.BITHER_BC_GET_BY_ADDRESS, address); 19 | setUrl(url); 20 | } 21 | 22 | public BlockChainMytransactionsApi() { 23 | setUrl(BitherUrl.BITHER_BC_LATEST_BLOCK); 24 | } 25 | 26 | public BlockChainMytransactionsApi(int txIndex) { 27 | String url = String.format(BitherUrl.BITHER_BC_TX_INDEX, txIndex); 28 | setUrl(url); 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /bitherj/src/main/java/net/bither/bitherj/api/CookieFactory.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2014 http://Bither.net 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package net.bither.bitherj.api; 18 | 19 | import net.bither.bitherj.AbstractApp; 20 | 21 | import org.apache.http.client.CookieStore; 22 | 23 | public class CookieFactory { 24 | 25 | private static boolean isRunning = false; 26 | //private static final Logger log = LoggerFactory.getLogger(CookieFactory.class); 27 | 28 | private CookieFactory() { 29 | 30 | } 31 | 32 | public synchronized static boolean initCookie() { 33 | boolean success = true; 34 | isRunning = true; 35 | CookieStore cookieStore = AbstractApp.bitherjSetting.getCookieStore(); 36 | if (cookieStore.getCookies() == null 37 | || cookieStore.getCookies().size() == 0) { 38 | try { 39 | GetCookieApi getCookieApi = new GetCookieApi(); 40 | getCookieApi.handleHttpPost(); 41 | // log.debug("getCookieApi"); 42 | } catch (Exception e) { 43 | success = false; 44 | e.printStackTrace(); 45 | } 46 | } 47 | isRunning = false; 48 | return success; 49 | 50 | } 51 | 52 | public static boolean isRunning() { 53 | return isRunning; 54 | } 55 | 56 | } 57 | -------------------------------------------------------------------------------- /bitherj/src/main/java/net/bither/bitherj/api/DownloadSpvApi.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2014 http://Bither.net 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package net.bither.bitherj.api; 18 | 19 | import net.bither.bitherj.api.http.BitherUrl; 20 | import net.bither.bitherj.api.http.HttpGetResponse; 21 | import net.bither.bitherj.core.Block; 22 | import net.bither.bitherj.utils.BlockUtil; 23 | import net.bither.bitherj.utils.Utils; 24 | 25 | import org.apache.http.HttpResponse; 26 | import org.apache.http.client.methods.HttpGet; 27 | import org.json.JSONArray; 28 | import org.json.JSONObject; 29 | 30 | public class DownloadSpvApi extends HttpGetResponse { 31 | 32 | public DownloadSpvApi() { 33 | setUrl(BitherUrl.BITHER_GET_ONE_SPVBLOCK_API); 34 | } 35 | 36 | @Override 37 | public void setResult(String response) throws Exception { 38 | JSONObject jsonObject = new JSONObject(response); 39 | this.result = BlockUtil.formatStoredBlock(jsonObject); 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /bitherj/src/main/java/net/bither/bitherj/api/GetBlockCountApi.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2014 http://Bither.net 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package net.bither.bitherj.api; 18 | 19 | import net.bither.bitherj.api.http.BitherUrl; 20 | import net.bither.bitherj.api.http.HttpGetResponse; 21 | 22 | public class GetBlockCountApi extends HttpGetResponse { 23 | 24 | public GetBlockCountApi() { 25 | setUrl(BitherUrl.BITHER_Q_GETBLOCK_COUNT_URL); 26 | 27 | } 28 | 29 | @Override 30 | public void setResult(String response) throws Exception { 31 | this.result = Long.valueOf(response); 32 | 33 | } 34 | 35 | } 36 | -------------------------------------------------------------------------------- /bitherj/src/main/java/net/bither/bitherj/api/GetCookieApi.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2014 http://Bither.net 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package net.bither.bitherj.api; 18 | 19 | import net.bither.bitherj.api.http.BitherUrl; 20 | import net.bither.bitherj.api.http.HttpPostResponse; 21 | import net.bither.bitherj.api.http.HttpSetting.HttpType; 22 | 23 | import org.apache.http.HttpEntity; 24 | import org.apache.http.NameValuePair; 25 | import org.apache.http.client.entity.UrlEncodedFormEntity; 26 | import org.apache.http.message.BasicNameValuePair; 27 | import org.apache.http.protocol.HTTP; 28 | 29 | import java.util.ArrayList; 30 | import java.util.List; 31 | 32 | public class GetCookieApi extends HttpPostResponse { 33 | 34 | private static final String TIME_STRING = "ts"; 35 | 36 | public GetCookieApi() { 37 | setUrl(BitherUrl.BITHER_GET_COOKIE_URL); 38 | setHttpType(HttpType.GetBitherCookie); 39 | } 40 | 41 | @Override 42 | public void setResult(String response) throws Exception { 43 | this.result = response; 44 | 45 | } 46 | 47 | @Override 48 | public HttpEntity getHttpEntity() throws Exception { 49 | long time = System.currentTimeMillis(); 50 | time = time / 1000 * 1000 + 215; 51 | List params = new ArrayList(); 52 | params.add(new BasicNameValuePair(TIME_STRING, Long.toString(time))); 53 | return new UrlEncodedFormEntity(params, HTTP.UTF_8); 54 | 55 | } 56 | 57 | } 58 | -------------------------------------------------------------------------------- /bitherj/src/main/java/net/bither/bitherj/api/GetExchangeDepthApi.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2014 http://Bither.net 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package net.bither.bitherj.api; 18 | 19 | import net.bither.bitherj.BitherjSettings; 20 | import net.bither.bitherj.api.http.BitherUrl; 21 | import net.bither.bitherj.api.http.HttpGetResponse; 22 | import net.bither.bitherj.utils.Utils; 23 | 24 | public class GetExchangeDepthApi extends HttpGetResponse { 25 | 26 | 27 | public GetExchangeDepthApi(BitherjSettings.MarketType marketType) { 28 | 29 | String url = Utils.format(BitherUrl.BITHER_DEPTH_URL, 30 | BitherjSettings.getMarketValue(marketType)); 31 | setUrl(url); 32 | } 33 | 34 | @Override 35 | public void setResult(String response) throws Exception { 36 | this.result = response; 37 | } 38 | 39 | } 40 | -------------------------------------------------------------------------------- /bitherj/src/main/java/net/bither/bitherj/api/GetExchangeTickerApi.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2014 http://Bither.net 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package net.bither.bitherj.api; 18 | 19 | import net.bither.bitherj.api.http.BitherUrl; 20 | import net.bither.bitherj.api.http.HttpGetResponse; 21 | 22 | import org.json.JSONObject; 23 | 24 | public class GetExchangeTickerApi extends HttpGetResponse { 25 | 26 | private static final String CURRENCY_RATE = "currency_rate"; 27 | private static final String CURRENCIES_RATE = "currencies_rate"; 28 | 29 | private double mCurrencyRate; 30 | private JSONObject mCurrenciesRate; 31 | 32 | public GetExchangeTickerApi() { 33 | setUrl(BitherUrl.BITHER_EXCHANGE_TICKER); 34 | } 35 | 36 | @Override 37 | public void setResult(String response) throws Exception { 38 | JSONObject json = new JSONObject(response); 39 | 40 | this.mCurrencyRate = json.getDouble(CURRENCY_RATE); 41 | this.mCurrenciesRate = json.getJSONObject(CURRENCIES_RATE); 42 | this.result = response;// Ticker.formatList(json); 43 | } 44 | 45 | public double getCurrencyRate() { 46 | return mCurrencyRate; 47 | } 48 | 49 | public JSONObject getCurrenciesRate() { 50 | return mCurrenciesRate; 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /bitherj/src/main/java/net/bither/bitherj/api/GetExchangeTrendApi.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2014 http://Bither.net 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package net.bither.bitherj.api; 18 | 19 | 20 | import net.bither.bitherj.BitherjSettings; 21 | import net.bither.bitherj.api.http.BitherUrl; 22 | import net.bither.bitherj.api.http.HttpGetResponse; 23 | import net.bither.bitherj.utils.Utils; 24 | 25 | public class GetExchangeTrendApi extends HttpGetResponse { 26 | 27 | public GetExchangeTrendApi(BitherjSettings.MarketType marketType) { 28 | String url = Utils.format(BitherUrl.BITHER_TREND_URL, 29 | BitherjSettings.getMarketValue(marketType)); 30 | setUrl(url); 31 | 32 | } 33 | 34 | @Override 35 | public void setResult(String response) throws Exception { 36 | 37 | this.result = response; 38 | } 39 | 40 | } 41 | -------------------------------------------------------------------------------- /bitherj/src/main/java/net/bither/bitherj/api/GetHDMBIdRandomApi.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2014 http://Bither.net 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package net.bither.bitherj.api; 18 | 19 | import net.bither.bitherj.api.http.BitherUrl; 20 | import net.bither.bitherj.api.http.HttpsGetResponse; 21 | import net.bither.bitherj.utils.Utils; 22 | 23 | import org.slf4j.Logger; 24 | import org.slf4j.LoggerFactory; 25 | 26 | public class GetHDMBIdRandomApi extends HttpsGetResponse { 27 | private static final Logger log = LoggerFactory.getLogger(GetHDMBIdRandomApi.class); 28 | 29 | public GetHDMBIdRandomApi(String address) { 30 | String url = Utils.format(BitherUrl.BITHER_HDM_PASSWORD, address); 31 | setUrl(url); 32 | } 33 | 34 | public void setResult(String response) throws Exception { 35 | this.result = Long.valueOf(response); 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /bitherj/src/main/java/net/bither/bitherj/api/GetInSignaturesApi.java: -------------------------------------------------------------------------------- 1 | /* 2 | * 3 | * * Copyright 2014 http://Bither.net 4 | * * 5 | * * Licensed under the Apache License, Version 2.0 (the "License"); 6 | * * you may not use this file except in compliance with the License. 7 | * * You may obtain a copy of the License at 8 | * * 9 | * * http://www.apache.org/licenses/LICENSE-2.0 10 | * * 11 | * * Unless required by applicable law or agreed to in writing, software 12 | * * distributed under the License is distributed on an "AS IS" BASIS, 13 | * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * * See the License for the specific language governing permissions and 15 | * * limitations under the License. 16 | * 17 | */ 18 | 19 | package net.bither.bitherj.api; 20 | 21 | import net.bither.bitherj.api.http.BitherUrl; 22 | import net.bither.bitherj.api.http.HttpGetResponse; 23 | import net.bither.bitherj.utils.Utils; 24 | 25 | public class GetInSignaturesApi extends HttpGetResponse { 26 | 27 | public GetInSignaturesApi(String address, int fromBlock) { 28 | String url = Utils.format(BitherUrl.BITHER_IN_SIGNATURES_API, address, fromBlock); 29 | setUrl(url); 30 | } 31 | 32 | @Override 33 | public void setResult(String response) throws Exception { 34 | this.result = response; 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /bitherj/src/main/java/net/bither/bitherj/api/GetKlineApi.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2014 http://Bither.net 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package net.bither.bitherj.api; 18 | 19 | import net.bither.bitherj.BitherjSettings; 20 | import net.bither.bitherj.api.http.BitherUrl; 21 | import net.bither.bitherj.api.http.HttpGetResponse; 22 | import net.bither.bitherj.utils.Utils; 23 | 24 | public class GetKlineApi extends HttpGetResponse { 25 | 26 | 27 | public GetKlineApi(BitherjSettings.MarketType marketType, BitherjSettings.KlineTimeType klineTimeType) { 28 | 29 | String url = Utils.format(BitherUrl.BITHER_KLINE_URL, 30 | BitherjSettings.getMarketValue(marketType), klineTimeType.getValue()); 31 | setUrl(url); 32 | 33 | } 34 | 35 | @Override 36 | public void setResult(String response) throws Exception { 37 | this.result = response; 38 | 39 | } 40 | 41 | } 42 | -------------------------------------------------------------------------------- /bitherj/src/main/java/net/bither/bitherj/api/RecoveryHDMApi.java: -------------------------------------------------------------------------------- 1 | package net.bither.bitherj.api; 2 | 3 | import net.bither.bitherj.api.http.BitherUrl; 4 | import net.bither.bitherj.api.http.HttpSetting; 5 | import net.bither.bitherj.api.http.HttpsPostResponse; 6 | import net.bither.bitherj.core.HDMAddress; 7 | import net.bither.bitherj.utils.Utils; 8 | 9 | import org.json.JSONObject; 10 | 11 | import java.util.ArrayList; 12 | import java.util.HashMap; 13 | import java.util.List; 14 | import java.util.Map; 15 | 16 | public class RecoveryHDMApi extends HttpsPostResponse> { 17 | private byte[] signature; 18 | private byte[] password; 19 | 20 | public RecoveryHDMApi(String address, byte[] signature, byte[] password) { 21 | String url = Utils.format(BitherUrl.BITHER_REVOCERY_HDM, address); 22 | setUrl(url); 23 | this.signature = signature; 24 | this.password = password; 25 | 26 | 27 | } 28 | 29 | @Override 30 | public Map getParams() throws Exception { 31 | Map params = new HashMap(); 32 | params.put(HttpSetting.PASSWORD, Utils.base64Encode(this.password)); 33 | params.put(HttpSetting.SIGNATURE, Utils.base64Encode(this.signature)); 34 | return params; 35 | } 36 | 37 | @Override 38 | public void setResult(String response) throws Exception { 39 | JSONObject json = new JSONObject(response); 40 | this.result = new ArrayList(); 41 | List pubHots = new ArrayList(); 42 | List pubColds = new ArrayList(); 43 | List pubService = new ArrayList(); 44 | if (!json.isNull(HttpSetting.PUB_HOT)) { 45 | String pubHotString = json.getString(HttpSetting.PUB_HOT); 46 | pubHots = Utils.decodeServiceResult(pubHotString); 47 | } 48 | if (!json.isNull(HttpSetting.PUB_COLD)) { 49 | String pubColdString = json.getString(HttpSetting.PUB_COLD); 50 | pubColds = Utils.decodeServiceResult(pubColdString); 51 | } 52 | if (!json.isNull(HttpSetting.PUB_SERVER)) { 53 | String pubServiceString = json.getString(HttpSetting.PUB_SERVER); 54 | pubService = Utils.decodeServiceResult(pubServiceString); 55 | } 56 | 57 | for (int i = 0; i < pubHots.size(); i++) { 58 | HDMAddress.Pubs pubs = new HDMAddress.Pubs(pubHots.get(i), pubColds.get(i), pubService.get(i), i); 59 | this.result.add(pubs); 60 | } 61 | 62 | } 63 | } 64 | -------------------------------------------------------------------------------- /bitherj/src/main/java/net/bither/bitherj/api/SignatureHDMApi.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2014 http://Bither.net 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package net.bither.bitherj.api; 18 | 19 | import net.bither.bitherj.api.http.BitherUrl; 20 | import net.bither.bitherj.api.http.HttpSetting; 21 | import net.bither.bitherj.api.http.HttpsPostResponse; 22 | import net.bither.bitherj.utils.Utils; 23 | 24 | import org.slf4j.Logger; 25 | import org.slf4j.LoggerFactory; 26 | 27 | import java.util.HashMap; 28 | import java.util.List; 29 | import java.util.Map; 30 | 31 | public class SignatureHDMApi extends HttpsPostResponse> { 32 | private byte[] password; 33 | private List unSigns; 34 | private static final Logger log = LoggerFactory.getLogger(SignatureHDMApi.class); 35 | 36 | public SignatureHDMApi(String address, int index, byte[] password, List unSigns) { 37 | String url = Utils.format(BitherUrl.BITHER_HDM_SIGNATURE, address, index); 38 | setUrl(url); 39 | this.password = password; 40 | this.unSigns = unSigns; 41 | 42 | } 43 | 44 | @Override 45 | public Map getParams() throws Exception { 46 | Map params = new HashMap(); 47 | params.put(HttpSetting.PASSWORD, Utils.base64Encode(password)); 48 | params.put(HttpSetting.UNSIGN, Utils.encodeBytesForService(unSigns)); 49 | return params; 50 | } 51 | 52 | 53 | @Override 54 | public void setResult(String response) throws Exception { 55 | log.info("SignatureHDMApi:" + response); 56 | this.result = Utils.decodeServiceResult(response); 57 | } 58 | } -------------------------------------------------------------------------------- /bitherj/src/main/java/net/bither/bitherj/api/TrustCert.java: -------------------------------------------------------------------------------- 1 | /* 2 | * 3 | * * Copyright 2014 http://Bither.net 4 | * * 5 | * * Licensed under the Apache License, Version 2.0 (the "License"); 6 | * * you may not use this file except in compliance with the License. 7 | * * You may obtain a copy of the License at 8 | * * 9 | * * http://www.apache.org/licenses/LICENSE-2.0 10 | * * 11 | * * Unless required by applicable law or agreed to in writing, software 12 | * * distributed under the License is distributed on an "AS IS" BASIS, 13 | * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * * See the License for the specific language governing permissions and 15 | * * limitations under the License. 16 | * 17 | */ 18 | 19 | package net.bither.bitherj.api; 20 | 21 | import java.io.IOException; 22 | import java.io.InputStream; 23 | import java.security.KeyStore; 24 | import java.security.KeyStoreException; 25 | import java.security.NoSuchAlgorithmException; 26 | import java.security.cert.CertificateException; 27 | 28 | /** 29 | * Created by songchenwen on 15/1/23. 30 | */ 31 | public class TrustCert { 32 | private InputStream input; 33 | private char[] password; 34 | private String type; 35 | 36 | private TrustCert() { 37 | 38 | } 39 | 40 | public TrustCert(InputStream input, char[] password, String type) { 41 | this.input = input; 42 | this.password = password; 43 | this.type = type; 44 | } 45 | 46 | public KeyStore getKeyStore() throws KeyStoreException, CertificateException, 47 | NoSuchAlgorithmException, IOException { 48 | KeyStore localTrustStore = KeyStore.getInstance(type); 49 | if (localTrustStore == null) { 50 | return null; 51 | } 52 | try { 53 | localTrustStore.load(input, password); 54 | } finally { 55 | input.close(); 56 | } 57 | return localTrustStore; 58 | } 59 | } 60 | -------------------------------------------------------------------------------- /bitherj/src/main/java/net/bither/bitherj/api/UploadAvatarApi.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2014 http://Bither.net 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | 18 | package net.bither.bitherj.api; 19 | 20 | 21 | import net.bither.bitherj.api.http.BitherUrl; 22 | import net.bither.bitherj.api.http.HttpPostResponse; 23 | 24 | import org.apache.http.HttpEntity; 25 | import org.apache.http.entity.mime.HttpMultipartMode; 26 | import org.apache.http.entity.mime.MultipartEntity; 27 | import org.apache.http.entity.mime.content.FileBody; 28 | 29 | import java.io.File; 30 | 31 | public class UploadAvatarApi extends HttpPostResponse { 32 | 33 | private final String FILE_KEY = "file"; 34 | 35 | private File mFile; 36 | 37 | public UploadAvatarApi(File file) { 38 | this.mFile = file; 39 | setUrl(BitherUrl.BITHER_UPLOAD_AVATAR); 40 | } 41 | 42 | @Override 43 | public HttpEntity getHttpEntity() throws Exception { 44 | MultipartEntity multipartEntity = new MultipartEntity( 45 | HttpMultipartMode.BROWSER_COMPATIBLE); 46 | multipartEntity.addPart(FILE_KEY, new FileBody(this.mFile)); 47 | return multipartEntity; 48 | } 49 | 50 | @Override 51 | public void setResult(String response) throws Exception { 52 | this.result = response; 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /bitherj/src/main/java/net/bither/bitherj/api/UploadHDMBidApi.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2014 http://Bither.net 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package net.bither.bitherj.api; 18 | 19 | import net.bither.bitherj.api.http.BitherUrl; 20 | import net.bither.bitherj.api.http.HttpSetting; 21 | import net.bither.bitherj.api.http.HttpsPostResponse; 22 | import net.bither.bitherj.utils.Utils; 23 | 24 | import org.json.JSONObject; 25 | 26 | import java.util.HashMap; 27 | import java.util.Map; 28 | 29 | public class UploadHDMBidApi extends HttpsPostResponse { 30 | 31 | private byte[] signature; 32 | private byte[] password; 33 | private String hotAddress; 34 | 35 | public UploadHDMBidApi(String address, String hotAddress, byte[] signature, byte[] password) { 36 | String url = Utils.format(BitherUrl.BITHER_HDM_PASSWORD, address); 37 | setUrl(url); 38 | this.signature = signature; 39 | this.password = password; 40 | this.hotAddress = hotAddress; 41 | 42 | } 43 | 44 | @Override 45 | public Map getParams() throws Exception { 46 | Map params = new HashMap(); 47 | params.put(HttpSetting.PASSWORD, Utils.base64Encode(this.password)); 48 | params.put(HttpSetting.SIGNATURE, Utils.base64Encode(this.signature)); 49 | params.put(HttpSetting.HOT_ADDRESS, this.hotAddress); 50 | return params; 51 | } 52 | 53 | @Override 54 | public void setResult(String response) throws Exception { 55 | this.result = false; 56 | JSONObject json = new JSONObject(response); 57 | if (!json.isNull(HttpSetting.RESULT)) { 58 | this.result = Utils.compareString(json.getString(HttpSetting.RESULT) 59 | , HttpSetting.STATUS_OK); 60 | } 61 | 62 | } 63 | } 64 | -------------------------------------------------------------------------------- /bitherj/src/main/java/net/bither/bitherj/api/http/BaseHttpsResponse.java: -------------------------------------------------------------------------------- 1 | package net.bither.bitherj.api.http; 2 | 3 | import net.bither.bitherj.AbstractApp; 4 | import net.bither.bitherj.api.ConnectHttps; 5 | 6 | import java.io.BufferedReader; 7 | import java.io.IOException; 8 | import java.io.InputStream; 9 | import java.io.InputStreamReader; 10 | 11 | public abstract class BaseHttpsResponse { 12 | private static boolean isTrust = false; 13 | protected T result; 14 | private String mUrl; 15 | 16 | 17 | public T getResult() { 18 | return result; 19 | } 20 | 21 | public abstract void setResult(String response) throws Exception; 22 | 23 | protected synchronized void trustCerts() { 24 | if (!isTrust) { 25 | ConnectHttps.trustCerts(AbstractApp.trustCert); 26 | isTrust = true; 27 | } 28 | 29 | } 30 | 31 | protected String getUrl() { 32 | return mUrl; 33 | } 34 | 35 | protected void setUrl(String url) { 36 | this.mUrl = url; 37 | } 38 | 39 | protected String getStringFromIn(InputStream in) throws IOException { 40 | BufferedReader rd = new BufferedReader(new InputStreamReader(in, 41 | HttpSetting.REQUEST_ENCODING)); 42 | String tempLine = rd.readLine(); 43 | StringBuffer tempStr = new StringBuffer(); 44 | String crlf = System.getProperty("line.separator"); 45 | while (tempLine != null) { 46 | tempStr.append(tempLine); 47 | tempStr.append(crlf); 48 | tempLine = rd.readLine(); 49 | } 50 | rd.close(); 51 | 52 | return tempStr.toString(); 53 | } 54 | 55 | 56 | } 57 | -------------------------------------------------------------------------------- /bitherj/src/main/java/net/bither/bitherj/api/http/Http400Exception.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2014 http://Bither.net 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package net.bither.bitherj.api.http; 18 | 19 | public class Http400Exception extends HttpException { 20 | private static final long serialVersionUID = 1L; 21 | private int errorCode; 22 | 23 | public Http400Exception(Exception cause) { 24 | super(cause); 25 | } 26 | 27 | public Http400Exception(int errorCode, String msg) { 28 | super(msg); 29 | this.errorCode = errorCode; 30 | } 31 | 32 | public Http400Exception(String msg, Exception cause, int statusCode) { 33 | super(msg, cause, statusCode); 34 | 35 | } 36 | 37 | public Http400Exception(String msg, Exception cause) { 38 | super(msg, cause); 39 | } 40 | 41 | public Http400Exception(String msg) { 42 | super(msg); 43 | } 44 | 45 | public int getErrorCode() { 46 | return errorCode; 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /bitherj/src/main/java/net/bither/bitherj/api/http/Http404Exception.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2014 http://Bither.net 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package net.bither.bitherj.api.http; 18 | 19 | public class Http404Exception extends HttpException { 20 | 21 | private static final long serialVersionUID = 1L; 22 | 23 | public Http404Exception(Exception cause) { 24 | super(cause); 25 | } 26 | 27 | public Http404Exception(String msg, int statusCode) { 28 | super(msg, statusCode); 29 | } 30 | 31 | public Http404Exception(String msg, Exception cause, int statusCode) { 32 | super(msg, cause, statusCode); 33 | 34 | } 35 | 36 | public Http404Exception(String msg, Exception cause) { 37 | super(msg, cause); 38 | } 39 | 40 | public Http404Exception(String msg) { 41 | super(msg); 42 | } 43 | 44 | } 45 | -------------------------------------------------------------------------------- /bitherj/src/main/java/net/bither/bitherj/api/http/Http500Exception.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2014 http://Bither.net 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package net.bither.bitherj.api.http; 18 | 19 | public class Http500Exception extends HttpException { 20 | private static final long serialVersionUID = 1L; 21 | 22 | public Http500Exception(Exception cause) { 23 | super(cause); 24 | } 25 | 26 | public Http500Exception(String msg, int statusCode) { 27 | super(msg, statusCode); 28 | } 29 | 30 | public Http500Exception(String msg, Exception cause, int statusCode) { 31 | super(msg, cause, statusCode); 32 | 33 | } 34 | 35 | public Http500Exception(String msg, Exception cause) { 36 | super(msg, cause); 37 | } 38 | 39 | public Http500Exception(String msg) { 40 | super(msg); 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /bitherj/src/main/java/net/bither/bitherj/api/http/HttpAuthException.java: -------------------------------------------------------------------------------- 1 | /* * Copyright 2014 http://Bither.net * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.bither.bitherj.api.http; public class HttpAuthException extends HttpRefusedException { /** * */ private static final long serialVersionUID = 1L; public HttpAuthException(String msg, int statusCode) { super(msg, statusCode); } public HttpAuthException(String msg, Exception cause, int statusCode) { super(msg, cause, statusCode); } public HttpAuthException(String msg, Exception cause) { super(msg, cause); } public HttpAuthException(String msg) { super(msg); } } -------------------------------------------------------------------------------- /bitherj/src/main/java/net/bither/bitherj/api/http/HttpException.java: -------------------------------------------------------------------------------- 1 | /* * Copyright 2014 http://Bither.net * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.bither.bitherj.api.http; /** * http statusCode not 200 deal with access to the network(http),other don't * need */ public class HttpException extends Exception { private static final long serialVersionUID = 1L; private int statusCode = -1; public HttpException(String msg) { super(msg); } public HttpException(Exception cause) { super(cause); } public HttpException(String msg, int statusCode) { super(msg); this.statusCode = statusCode; } public HttpException(String msg, Exception cause) { super(msg, cause); } public HttpException(String msg, Exception cause, int statusCode) { super(msg, cause); this.statusCode = statusCode; } public HttpException(int statusCode) { this.statusCode = statusCode; } public int getStatusCode() { return this.statusCode; } } -------------------------------------------------------------------------------- /bitherj/src/main/java/net/bither/bitherj/api/http/HttpGetResponse.java: -------------------------------------------------------------------------------- 1 | /* * Copyright 2014 http://Bither.net * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.bither.bitherj.api.http; import org.apache.http.HttpResponse; import org.apache.http.client.methods.HttpGet; public abstract class HttpGetResponse extends BaseHttpResponse { public void handleHttpGet() throws Exception { setHttpClient(); try { HttpGet httpGet = new HttpGet(getUrl()); httpGet.setHeader("Accept", "application/json"); HttpResponse httpResponse = getHttpClient().execute(httpGet); String response = getReponse(httpResponse); setResult(response); } catch (Exception e) { throw e; } finally { getHttpClient().getConnectionManager().shutdown(); } } } -------------------------------------------------------------------------------- /bitherj/src/main/java/net/bither/bitherj/api/http/HttpNoConnectException.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2014 http://Bither.net 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package net.bither.bitherj.api.http; 18 | 19 | public class HttpNoConnectException extends HttpException { 20 | private static final long serialVersionUID = 1L; 21 | private String refuseError; 22 | 23 | public HttpNoConnectException(String msg, int statusCode) { 24 | super(msg, statusCode); 25 | 26 | } 27 | 28 | public HttpNoConnectException(String msg, Exception cause, int statusCode) { 29 | super(msg, cause, statusCode); 30 | 31 | } 32 | 33 | public HttpNoConnectException(String msg, Exception cause) { 34 | super(msg, cause); 35 | 36 | } 37 | 38 | public HttpNoConnectException(String msg) { 39 | super(msg); 40 | 41 | } 42 | 43 | public String getRefuseError() { 44 | return refuseError; 45 | } 46 | 47 | public HttpNoConnectException setRefuseError(String refuseError) { 48 | this.refuseError = refuseError; 49 | return this; 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /bitherj/src/main/java/net/bither/bitherj/api/http/HttpPostResponse.java: -------------------------------------------------------------------------------- 1 | /* * Copyright 2014 http://Bither.net * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.bither.bitherj.api.http; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.client.methods.HttpPost; public abstract class HttpPostResponse extends BaseHttpResponse { public void handleHttpPost() throws Exception { setHttpClient(); try { HttpPost httpPost = new HttpPost(getUrl()); httpPost.setHeader("Accept", "application/json"); httpPost.setEntity(getHttpEntity()); HttpResponse httpResponse = getHttpClient().execute(httpPost); String response = getReponse(httpResponse); setResult(response); } catch (Exception e) { throw e; } finally { getHttpClient().getConnectionManager().shutdown(); } } public abstract HttpEntity getHttpEntity() throws Exception; } -------------------------------------------------------------------------------- /bitherj/src/main/java/net/bither/bitherj/api/http/HttpRefusedException.java: -------------------------------------------------------------------------------- 1 | /* * Copyright 2014 http://Bither.net * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.bither.bitherj.api.http; /** * the statusCode of http is 403,server refuse request * * @author jjz */ public class HttpRefusedException extends HttpException { /** * */ private static final long serialVersionUID = 1L; private String refuseError; public HttpRefusedException(String msg, int statusCode) { super(msg, statusCode); } public HttpRefusedException(String msg, Exception cause, int statusCode) { super(msg, cause, statusCode); } public HttpRefusedException(String msg, Exception cause) { super(msg, cause); } public HttpRefusedException(String msg) { super(msg); } public String getRefuseError() { return refuseError; } public HttpRefusedException setRefuseError(String refuseError) { this.refuseError = refuseError; return this; } } -------------------------------------------------------------------------------- /bitherj/src/main/java/net/bither/bitherj/api/http/HttpRequestException.java: -------------------------------------------------------------------------------- 1 | /* * Copyright 2014 http://Bither.net * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.bither.bitherj.api.http; /** * http statusCode is not 200,Not_modified :304, bad_request:400 not_found:400 * not_acceptable:406 */ public class HttpRequestException extends HttpException { private static final long serialVersionUID = 1L; public HttpRequestException(String msg, int statusCode) { super(msg, statusCode); } public HttpRequestException(String msg, Exception cause, int statusCode) { super(msg, cause, statusCode); } public HttpRequestException(String msg, Exception cause) { super(msg, cause); } public HttpRequestException(String msg) { super(msg); } public HttpRequestException(Exception cause) { super(cause); } } -------------------------------------------------------------------------------- /bitherj/src/main/java/net/bither/bitherj/api/http/HttpServerException.java: -------------------------------------------------------------------------------- 1 | /* * Copyright 2014 http://Bither.net * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.bither.bitherj.api.http; /** * http statusCode is not 200 ,internal_server_error:500, bad_gateway:502 * service_unavailable:503 * * @author jjz */ public class HttpServerException extends HttpException { /** * */ private static final long serialVersionUID = 1L; public HttpServerException(String msg, int statusCode) { super(msg, statusCode); } public HttpServerException(String msg, Exception cause, int statusCode) { super(msg, cause, statusCode); } public HttpServerException(String msg, Exception cause) { super(msg, cause); } public HttpServerException(String msg) { super(msg); } public HttpServerException(Exception cause) { super(cause); } } -------------------------------------------------------------------------------- /bitherj/src/main/java/net/bither/bitherj/api/http/HttpSetting.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2014 http://Bither.net 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package net.bither.bitherj.api.http; 18 | 19 | public class HttpSetting { 20 | /** 21 | * HTTP_CONNECTION_TIMEOUT: Set the timeout in milliseconds until a 22 | * connection is established. The default value is zero, that means the 23 | * timeout is not used. 24 | */ 25 | public static final int HTTP_CONNECTION_TIMEOUT = 10 * 1000; 26 | public static String REQUEST_ENCODING = "utf-8"; 27 | /** 28 | * HTTP_SO_TIMEOUT: Set the default socket timeout (SO_TIMEOUT). in 29 | * milliseconds which is the timeout for waiting for data. 30 | */ 31 | public static final int HTTP_SO_TIMEOUT = 80 * 1000; 32 | 33 | 34 | // enum 35 | public enum HttpType { 36 | BitherApi, OtherApi, GetBitherCookie 37 | } 38 | 39 | public static final String PASSWORD = "password"; 40 | public static final String SIGNATURE = "signature"; 41 | public static final String HOT_ADDRESS = "hot_address"; 42 | 43 | public static final String PUB_HOT = "pub_hot"; 44 | public static final String PUB_COLD = "pub_cold"; 45 | public static final String PUB_SERVER = "pub_server"; 46 | public static final String START = "start"; 47 | public static final String END = "end"; 48 | public static final String UNSIGN = "unsign"; 49 | public static final String RESULT = "result"; 50 | public static final String STATUS_OK = "ok"; 51 | 52 | public static final int HDMBIdIsAlready = 1001; 53 | public static final int MessageSignatureIsWrong = 1002; 54 | public static final int HDMBIdShouldBindToAnAddress = 1003; 55 | public static final int HDMBidIsNotExist = 1004; 56 | public static final int PasswordWrong = 1005; 57 | public static final int PubKeyIsExists = 1006; 58 | public static final int SignatureFailed = 1007; 59 | 60 | public static final int HDSeedIsNotExist = 2001; 61 | public static final int ServiceSignatureFailed = 2002; 62 | 63 | } 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | -------------------------------------------------------------------------------- /bitherj/src/main/java/net/bither/bitherj/api/http/HttpsGetResponse.java: -------------------------------------------------------------------------------- 1 | package net.bither.bitherj.api.http; 2 | 3 | import java.io.IOException; 4 | import java.net.URL; 5 | 6 | import javax.net.ssl.HttpsURLConnection; 7 | 8 | public abstract class HttpsGetResponse extends BaseHttpsResponse { 9 | 10 | public void handleHttpGet() throws Exception { 11 | trustCerts(); 12 | URL url; 13 | HttpsURLConnection con = null; 14 | try { 15 | 16 | url = new URL(getUrl()); 17 | con = (HttpsURLConnection) url.openConnection(); 18 | con.setRequestMethod("GET"); 19 | System.setProperty("sun.net.client.defaultConnectTimeout", String 20 | .valueOf(HttpSetting.HTTP_CONNECTION_TIMEOUT)); 21 | System.setProperty("sun.net.client.defaultReadTimeout", String 22 | .valueOf(HttpSetting.HTTP_SO_TIMEOUT)); 23 | StringBuffer out = new StringBuffer(); 24 | byte[] b = new byte[4096]; 25 | for (int n; (n = con.getInputStream().read(b)) != -1; ) { 26 | out.append(new String(b, 0, n)); 27 | } 28 | setResult(out.toString()); 29 | } catch (IOException e) { 30 | if (con.getResponseCode() != 200) { 31 | String str = getStringFromIn(con.getErrorStream()); 32 | throw new HttpException(con.getResponseCode() + "," + str); 33 | } else { 34 | throw e; 35 | } 36 | } finally { 37 | if (con != null) { 38 | con.disconnect(); 39 | } 40 | } 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /bitherj/src/main/java/net/bither/bitherj/api/http/HttpsPostResponse.java: -------------------------------------------------------------------------------- 1 | package net.bither.bitherj.api.http; 2 | 3 | import org.json.JSONObject; 4 | 5 | import java.io.IOException; 6 | import java.io.InputStream; 7 | import java.net.URL; 8 | import java.net.URLEncoder; 9 | import java.util.Iterator; 10 | import java.util.Map; 11 | 12 | import javax.net.ssl.HttpsURLConnection; 13 | 14 | public abstract class HttpsPostResponse extends BaseHttpsResponse { 15 | 16 | public void handleHttpPost() throws Exception { 17 | trustCerts(); 18 | HttpsURLConnection con = null; 19 | String responseContent = null; 20 | try { 21 | StringBuffer params = new StringBuffer(); 22 | for (Iterator iter = getParams().entrySet().iterator(); iter 23 | .hasNext(); ) { 24 | Map.Entry element = (Map.Entry) iter.next(); 25 | params.append(element.getKey().toString()); 26 | params.append("="); 27 | params.append(URLEncoder.encode(element.getValue().toString(), 28 | HttpSetting.REQUEST_ENCODING)); 29 | params.append("&"); 30 | } 31 | 32 | if (params.length() > 0) { 33 | params = params.deleteCharAt(params.length() - 1); 34 | } 35 | 36 | URL url = new URL(getUrl()); 37 | con = (HttpsURLConnection) url.openConnection(); 38 | con.setRequestMethod("POST"); 39 | System.setProperty("sun.net.client.defaultConnectTimeout", String 40 | .valueOf(HttpSetting.HTTP_CONNECTION_TIMEOUT)); 41 | System.setProperty("sun.net.client.defaultReadTimeout", String 42 | .valueOf(HttpSetting.HTTP_SO_TIMEOUT)); 43 | 44 | con.setDoOutput(true); 45 | byte[] b = params.toString().getBytes(); 46 | con.getOutputStream().write(b, 0, b.length); 47 | con.getOutputStream().flush(); 48 | con.getOutputStream().close(); 49 | 50 | InputStream in = con.getInputStream(); 51 | responseContent = getStringFromIn(in); 52 | 53 | in.close(); 54 | } catch (IOException e) { 55 | e.printStackTrace(); 56 | if (con.getResponseCode() == 400) { 57 | String str = getStringFromIn(con.getErrorStream()); 58 | JSONObject json = new JSONObject(str); 59 | Iterator it = json.keys(); 60 | if (it.hasNext()) { 61 | String key = (String) it.next(); 62 | String value = json.getString(key); 63 | throw new Http400Exception(Integer.valueOf(key), value); 64 | } 65 | } else if (con.getResponseCode() != 200) { 66 | String str = getStringFromIn(con.getErrorStream()); 67 | throw new HttpException(con.getResponseCode() + "," + str); 68 | } else { 69 | throw e; 70 | } 71 | } finally { 72 | if (con != null) { 73 | con.disconnect(); 74 | } 75 | } 76 | setResult(responseContent); 77 | } 78 | 79 | 80 | public abstract Map getParams() throws Exception; 81 | } 82 | -------------------------------------------------------------------------------- /bitherj/src/main/java/net/bither/bitherj/core/EnterpriseHDMAddress.java: -------------------------------------------------------------------------------- 1 | /* 2 | * 3 | * * Copyright 2014 http://Bither.net 4 | * * 5 | * * Licensed under the Apache License, Version 2.0 (the "License"); 6 | * * you may not use this file except in compliance with the License. 7 | * * You may obtain a copy of the License at 8 | * * 9 | * * http://www.apache.org/licenses/LICENSE-2.0 10 | * * 11 | * * Unless required by applicable law or agreed to in writing, software 12 | * * distributed under the License is distributed on an "AS IS" BASIS, 13 | * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * * See the License for the specific language governing permissions and 15 | * * limitations under the License. 16 | * 17 | */ 18 | 19 | package net.bither.bitherj.core; 20 | 21 | import net.bither.bitherj.db.AbstractDb; 22 | import net.bither.bitherj.script.Script; 23 | import net.bither.bitherj.script.ScriptBuilder; 24 | import net.bither.bitherj.utils.Utils; 25 | 26 | import java.util.ArrayList; 27 | import java.util.List; 28 | 29 | /** 30 | * Created by songchenwen on 15/6/2. 31 | */ 32 | public class EnterpriseHDMAddress extends Address { 33 | 34 | private EnterpriseHDMKeychain keychain; 35 | private Pubs pubs; 36 | 37 | public EnterpriseHDMAddress(Pubs pubs, EnterpriseHDMKeychain keychain, boolean isSyncComplete) { 38 | this(pubs, pubs.getAddress(), keychain, isSyncComplete); 39 | } 40 | 41 | public EnterpriseHDMAddress(Pubs pubs, String address, EnterpriseHDMKeychain keychain, 42 | boolean isSyncComplete) { 43 | super(address, pubs.getMultiSigScript().getProgram(), pubs.index, isSyncComplete, false, 44 | false, null); 45 | this.pubs = pubs; 46 | this.keychain = keychain; 47 | } 48 | 49 | 50 | public EnterpriseHDMKeychain getKeychain() { 51 | return keychain; 52 | } 53 | 54 | public int getIndex() { 55 | return pubs.index; 56 | } 57 | 58 | public List getPubkeys() { 59 | return pubs.pubs; 60 | } 61 | 62 | public int pubCount() { 63 | return keychain.pubCount(); 64 | } 65 | 66 | public int threshold() { 67 | return keychain.threshold(); 68 | } 69 | 70 | @Override 71 | public boolean isHDM() { 72 | return true; 73 | } 74 | 75 | @Override 76 | public String getFullEncryptPrivKey() { 77 | throw new RuntimeException("hdm address can't get encrypted private key"); 78 | } 79 | 80 | @Override 81 | public void updateSyncComplete() { 82 | AbstractDb.enterpriseHDMProvider.updateSyncComplete(EnterpriseHDMAddress.this); 83 | } 84 | 85 | public static final class Pubs { 86 | 87 | public ArrayList pubs; 88 | public int index; 89 | public int threshold; 90 | 91 | public Pubs(int index, int threshold, List pubs) { 92 | this.index = index; 93 | this.threshold = threshold; 94 | this.pubs = new ArrayList(); 95 | this.pubs.addAll(pubs); 96 | } 97 | 98 | public Pubs(int index, int threshold) { 99 | this.index = index; 100 | this.threshold = threshold; 101 | pubs = new ArrayList(); 102 | } 103 | 104 | public void addPub(byte[] pub) { 105 | pubs.add(pub); 106 | } 107 | 108 | public Script getMultiSigScript() { 109 | return ScriptBuilder.createMultiSigOutputScript(threshold, pubs); 110 | } 111 | 112 | public String getAddress() { 113 | return Utils.toP2SHAddress(Utils.sha256hash160(getMultiSigScript().getProgram())); 114 | } 115 | } 116 | } 117 | -------------------------------------------------------------------------------- /bitherj/src/main/java/net/bither/bitherj/core/OutPoint.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2014 http://Bither.net 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package net.bither.bitherj.core; 18 | 19 | import com.google.common.primitives.Ints; 20 | 21 | import java.util.Arrays; 22 | 23 | import javax.annotation.Nonnull; 24 | 25 | public class OutPoint implements Comparable { 26 | private byte[] txHash; 27 | private int outSn; 28 | private byte[] bytes; 29 | 30 | public OutPoint(byte[] txHash, int outSn) { 31 | this.txHash = txHash; 32 | this.outSn = outSn; 33 | this.bytes = new byte[In.OUTPOINT_MESSAGE_LENGTH]; 34 | System.arraycopy(this.txHash, 0, this.bytes, 0, this.txHash.length); 35 | System.arraycopy(Ints.toByteArray(this.outSn), 0, this.bytes, this.txHash.length 36 | , In.OUTPOINT_MESSAGE_LENGTH - this.txHash.length); 37 | } 38 | 39 | @Override 40 | public boolean equals(Object other) { 41 | if (!(other instanceof OutPoint)) return false; 42 | OutPoint otherOutPoint = (OutPoint) other; 43 | return Arrays.equals(this.txHash, otherOutPoint.txHash) && this.outSn == otherOutPoint.outSn; 44 | } 45 | 46 | @Override 47 | public int hashCode() { 48 | return Arrays.hashCode(this.bytes); 49 | } 50 | 51 | @Override 52 | public int compareTo(@Nonnull OutPoint other) { 53 | if (!Arrays.equals(this.txHash, other.txHash) || this.outSn != other.outSn) { 54 | if (Arrays.equals(this.txHash, other.txHash)) { 55 | return this.outSn - other.outSn; 56 | } else { 57 | return Arrays.hashCode(this.txHash) - Arrays.hashCode(other.txHash); 58 | } 59 | } else { 60 | return 0; 61 | } 62 | } 63 | 64 | public int getOutSn() { 65 | return this.outSn; 66 | } 67 | 68 | public byte[] getTxHash() { 69 | return this.txHash; 70 | } 71 | } 72 | -------------------------------------------------------------------------------- /bitherj/src/main/java/net/bither/bitherj/core/UnSignTransaction.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2014 http://Bither.net 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package net.bither.bitherj.core; 18 | 19 | import net.bither.bitherj.utils.Utils; 20 | 21 | import java.io.Serializable; 22 | 23 | public class UnSignTransaction implements Serializable { 24 | 25 | /** 26 | * 27 | */ 28 | private static final long serialVersionUID = 1L; 29 | 30 | public UnSignTransaction(Tx tx, String address) { 31 | this.mTx = tx; 32 | this.mAddress = address; 33 | } 34 | 35 | private Tx mTx; 36 | 37 | private String mAddress; 38 | 39 | public Tx getTx() { 40 | return mTx; 41 | } 42 | 43 | public void setTx(Tx mTx) { 44 | this.mTx = mTx; 45 | } 46 | 47 | public String getAddress() { 48 | return mAddress; 49 | } 50 | 51 | public void setAddress(String mAddress) { 52 | this.mAddress = mAddress; 53 | } 54 | 55 | @Override 56 | public boolean equals(Object o) { 57 | if (o instanceof UnSignTransaction) { 58 | UnSignTransaction unSignTransaction = (UnSignTransaction) o; 59 | return Utils.compareString(getAddress(), 60 | unSignTransaction.getAddress()); 61 | } 62 | return super.equals(o); 63 | } 64 | 65 | } 66 | -------------------------------------------------------------------------------- /bitherj/src/main/java/net/bither/bitherj/core/Version.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2014 http://Bither.net 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package net.bither.bitherj.core; 18 | 19 | public class Version { 20 | public static final String version = "1.6.0"; 21 | public static final String name = "Bitherj"; 22 | } 23 | -------------------------------------------------------------------------------- /bitherj/src/main/java/net/bither/bitherj/crypto/KeyCrypter.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2013 Jim Burton. 3 | *

4 | * Licensed under the MIT license (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | *

8 | * http://opensource.org/licenses/mit-license.php 9 | *

10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package net.bither.bitherj.crypto; 17 | 18 | //import org.bitcoinj.wallet.Protos.Wallet.EncryptionType; 19 | 20 | import org.spongycastle.crypto.params.KeyParameter; 21 | 22 | import java.io.Serializable; 23 | 24 | /** 25 | *

A KeyCrypter can be used to encrypt and decrypt a message. The sequence of events to encrypt and then decrypt 26 | * a message are as follows:

27 | *

28 | *

(1) Ask the user for a password. deriveKey() is then called to create an KeyParameter. This contains the AES 29 | * key that will be used for encryption.

30 | *

(2) Encrypt the message using encrypt(), providing the message bytes and the KeyParameter from (1). This returns 31 | * an EncryptedPrivateKey which contains the encryptedPrivateKey bytes and an initialisation vector.

32 | *

(3) To decrypt an EncryptedPrivateKey, repeat step (1) to get a KeyParameter, then call decrypt().

33 | *

34 | *

There can be different algorithms used for encryption/ decryption so the getUnderstoodEncryptionType is used 35 | * to determine whether any given KeyCrypter can understand the type of encrypted data you have.

36 | */ 37 | public interface KeyCrypter extends Serializable { 38 | 39 | /** 40 | * Return the EncryptionType enum value which denotes the type of encryption/ decryption that this KeyCrypter 41 | * can understand. 42 | */ 43 | // public EncryptionType getUnderstoodEncryptionType(); 44 | 45 | /** 46 | * Create a KeyParameter (which typically contains an AES key) 47 | * 48 | * @param password 49 | * @return KeyParameter The KeyParameter which typically contains the AES key to use for encrypting and decrypting 50 | * @throws KeyCrypterException 51 | */ 52 | public KeyParameter deriveKey(CharSequence password) throws KeyCrypterException; 53 | 54 | /** 55 | * Decrypt the provided encrypted bytes, converting them into unencrypted bytes. 56 | * 57 | * @throws KeyCrypterException if decryption was unsuccessful. 58 | */ 59 | public byte[] decrypt(EncryptedPrivateKey encryptedBytesToDecode, KeyParameter aesKey) throws KeyCrypterException; 60 | 61 | /** 62 | * Encrypt the supplied bytes, converting them into ciphertext. 63 | * 64 | * @return encryptedPrivateKey An encryptedPrivateKey containing the encrypted bytes and an initialisation vector. 65 | * @throws KeyCrypterException if encryption was unsuccessful 66 | */ 67 | public EncryptedPrivateKey encrypt(byte[] plainBytes, KeyParameter aesKey) throws KeyCrypterException; 68 | } 69 | -------------------------------------------------------------------------------- /bitherj/src/main/java/net/bither/bitherj/crypto/KeyCrypterException.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2013 Jim Burton. 3 | * Copyright 2014 Andreas Schildbach 4 | *

5 | * Licensed under the MIT license (the "License"); 6 | * you may not use this file except in compliance with the License. 7 | * You may obtain a copy of the License at 8 | *

9 | * http://opensource.org/licenses/mit-license.php 10 | *

11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | */ 17 | package net.bither.bitherj.crypto; 18 | 19 | /** 20 | *

Exception to provide the following to {@link }:

21 | *
    22 | *
  • Provision of encryption / decryption exception
  • 23 | *
24 | *

This base exception acts as a general failure mode not attributable to a specific cause (other than 25 | * that reported in the exception message). Since this is in English, it may not be worth reporting directly 26 | * to the user other than as part of a "general failure to parse" response.

27 | */ 28 | public class KeyCrypterException extends RuntimeException { 29 | private static final long serialVersionUID = -4441989608332681377L; 30 | 31 | public KeyCrypterException(String s) { 32 | super(s); 33 | } 34 | 35 | public KeyCrypterException(String s, Throwable throwable) { 36 | super(s, throwable); 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /bitherj/src/main/java/net/bither/bitherj/crypto/NativeSecp256k1.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2013 Google Inc. 3 | *

4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | *

8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | *

10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package net.bither.bitherj.crypto; 18 | 19 | import com.google.common.base.Preconditions; 20 | 21 | import java.nio.ByteBuffer; 22 | import java.nio.ByteOrder; 23 | 24 | 25 | /** 26 | *

This class holds native methods to handle ECDSA verification.

27 | *

28 | *

You can find an example library that can be used for this at https://github.com/sipa/secp256k1

29 | *

30 | *

To build secp256k1 for use with bitcoinj, run `./configure` and `make libjavasecp256k1.so` then copy 31 | * libjavasecp256k1.so to your system library path or point the JVM to the folder containing it with -Djava.library.path 32 | *

33 | */ 34 | public class NativeSecp256k1 { 35 | public static boolean enabled = false; 36 | 37 | static { 38 | try { 39 | System.loadLibrary("javasecp256k1"); 40 | } catch (UnsatisfiedLinkError e) { 41 | enabled = false; 42 | } 43 | } 44 | 45 | private static ThreadLocal nativeECDSABuffer = new ThreadLocal(); 46 | 47 | /** 48 | * Verifies the given secp256k1 signature in native code. 49 | * Calling when enabled == false is undefined (probably library not loaded) 50 | * 51 | * @param data The data which was signed, must be exactly 32 bytes 52 | * @param signature The signature 53 | * @param pub The public key which did the signing 54 | */ 55 | public static boolean verify(byte[] data, byte[] signature, byte[] pub) { 56 | Preconditions.checkArgument(data.length == 32 && signature.length <= 520 && pub.length <= 520); 57 | 58 | ByteBuffer byteBuff = nativeECDSABuffer.get(); 59 | if (byteBuff == null) { 60 | byteBuff = ByteBuffer.allocateDirect(32 + 8 + 520 + 520); 61 | byteBuff.order(ByteOrder.nativeOrder()); 62 | nativeECDSABuffer.set(byteBuff); 63 | } 64 | byteBuff.rewind(); 65 | byteBuff.put(data); 66 | byteBuff.putInt(signature.length); 67 | byteBuff.putInt(pub.length); 68 | byteBuff.put(signature); 69 | byteBuff.put(pub); 70 | return secp256k1_ecdsa_verify(byteBuff) == 1; 71 | } 72 | 73 | /** 74 | * @param byteBuff signature format is byte[32] data, 75 | * native-endian int signatureLength, native-endian int pubkeyLength, 76 | * byte[signatureLength] signature, byte[pubkeyLength] pub 77 | * @returns 1 for valid signature, anything else for invalid 78 | */ 79 | private static native int secp256k1_ecdsa_verify(ByteBuffer byteBuff); 80 | } 81 | -------------------------------------------------------------------------------- /bitherj/src/main/java/net/bither/bitherj/crypto/PasswordSeed.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2014 http://Bither.net 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package net.bither.bitherj.crypto; 18 | 19 | 20 | import net.bither.bitherj.db.AbstractDb; 21 | import net.bither.bitherj.exception.AddressFormatException; 22 | import net.bither.bitherj.qrcode.QRCodeUtil; 23 | import net.bither.bitherj.utils.Base58; 24 | import net.bither.bitherj.utils.PrivateKeyUtil; 25 | import net.bither.bitherj.utils.Utils; 26 | 27 | 28 | public class PasswordSeed { 29 | private String address; 30 | private String keyStr; 31 | 32 | public PasswordSeed(String str) { 33 | int indexOfSplit = QRCodeUtil.indexOfOfPasswordSeed(str); 34 | this.address = QRCodeUtil.getAddressFromPasswordSeed(str); 35 | this.keyStr = str.substring(indexOfSplit + 1); 36 | } 37 | 38 | 39 | public PasswordSeed(String address, String encryptedKey) { 40 | this.address = address; 41 | this.keyStr = encryptedKey; 42 | } 43 | 44 | public boolean checkPassword(CharSequence password) { 45 | ECKey ecKey = PrivateKeyUtil.getECKeyFromSingleString(keyStr, password); 46 | String ecKeyAddress; 47 | if (ecKey == null) { 48 | return false; 49 | } else { 50 | ecKeyAddress = ecKey.toAddress(); 51 | ecKey.clearPrivateKey(); 52 | } 53 | return Utils.compareString(this.address, 54 | ecKeyAddress); 55 | 56 | } 57 | 58 | public boolean changePassword(CharSequence oldPassword, CharSequence newPassword) { 59 | keyStr = PrivateKeyUtil.changePassword(keyStr, oldPassword, newPassword); 60 | return !Utils.isEmpty(keyStr); 61 | 62 | } 63 | 64 | public ECKey getECKey(CharSequence password) { 65 | return PrivateKeyUtil.getECKeyFromSingleString(keyStr, password); 66 | } 67 | 68 | public String getAddress() { 69 | return this.address; 70 | } 71 | 72 | public String getKeyStr() { 73 | return this.keyStr; 74 | } 75 | 76 | 77 | public String toPasswordSeedString() { 78 | try { 79 | String passwordSeedString = Base58.bas58ToHexWithAddress(this.address) + QRCodeUtil.QR_CODE_SPLIT 80 | + QRCodeUtil.getNewVersionEncryptPrivKey(this.keyStr); 81 | return passwordSeedString; 82 | } catch (AddressFormatException e) { 83 | throw new RuntimeException("passwordSeed address is format error ," + this.address); 84 | 85 | } 86 | 87 | } 88 | 89 | public static boolean hasPasswordSeed() { 90 | return AbstractDb.addressProvider.hasPasswordSeed(); 91 | } 92 | 93 | public static PasswordSeed getPasswordSeed() { 94 | return AbstractDb.addressProvider.getPasswordSeed(); 95 | } 96 | 97 | } 98 | -------------------------------------------------------------------------------- /bitherj/src/main/java/net/bither/bitherj/crypto/SecureCharSequence.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2014 http://Bither.net 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package net.bither.bitherj.crypto; 18 | 19 | 20 | import java.security.SecureRandom; 21 | import java.util.Arrays; 22 | 23 | public class SecureCharSequence implements CharSequence { 24 | private char[] chars; 25 | 26 | public SecureCharSequence(CharSequence charSequence) { 27 | this(charSequence, 0, charSequence.length()); 28 | } 29 | 30 | public SecureCharSequence(char[] chars) { 31 | wipe(); 32 | this.chars = chars; 33 | } 34 | 35 | private SecureCharSequence(CharSequence charSequence, int start, int end) { 36 | // pulled from http://stackoverflow.com/a/15844273 37 | wipe(); 38 | int length = end - start; 39 | chars = new char[length]; 40 | for (int i = start; 41 | i < end; 42 | i++) { 43 | chars[i - start] = charSequence.charAt(i); 44 | } 45 | } 46 | 47 | public void wipe() { 48 | if (chars != null) { 49 | Arrays.fill(chars, ' '); 50 | SecureRandom r = new SecureRandom(); 51 | byte[] bytes = new byte[chars.length]; 52 | r.nextBytes(bytes); 53 | for (int i = 0; 54 | i < chars.length; 55 | i++) { 56 | chars[i] = (char) bytes[i]; 57 | } 58 | Arrays.fill(chars, ' '); 59 | } 60 | } 61 | 62 | protected void finalize() { 63 | wipe(); 64 | } 65 | 66 | @Override 67 | public int length() { 68 | if (chars != null) { 69 | return chars.length; 70 | } 71 | return 0; 72 | } 73 | 74 | @Override 75 | public char charAt(int index) { 76 | if (chars != null) { 77 | return chars[index]; 78 | } 79 | return 0; 80 | } 81 | 82 | @Override 83 | public String toString() { 84 | return String.valueOf(this.chars); 85 | } 86 | 87 | @Override 88 | public boolean equals(Object o) { 89 | if (o instanceof SecureCharSequence) { 90 | return Arrays.equals(chars, ((SecureCharSequence) o).chars); 91 | } 92 | return false; 93 | } 94 | 95 | @Override 96 | public CharSequence subSequence(int start, int end) { 97 | SecureCharSequence s = new SecureCharSequence(this, start, end); 98 | return s; 99 | } 100 | } 101 | -------------------------------------------------------------------------------- /bitherj/src/main/java/net/bither/bitherj/crypto/hd/ChildNumber.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2013 Matija Mazi. 3 | *

4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | *

8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | *

10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package net.bither.bitherj.crypto.hd; 18 | 19 | /** 20 | *

This is just a wrapper for the i (child number) as per BIP 32 with a boolean getter for the most significant bit 21 | * and a getter for the actual 0-based child number. A {@link List} of these forms a path through a 22 | * {@link DeterministicHierarchy}. This class is immutable. 23 | */ 24 | public class ChildNumber { 25 | /** 26 | * The bit that's set in the child number to indicate whether this key is "hardened". Given a hardened key, it is 27 | * not possible to derive a child public key if you know only the hardened public key. With a non-hardened key this 28 | * is possible, so you can derive trees of public keys given only a public parent, but the downside is that it's 29 | * possible to leak private keys if you disclose a parent public key and a child private key (elliptic curve maths 30 | * allows you to work upwards). 31 | */ 32 | public static final int HARDENED_BIT = 0x80000000; 33 | 34 | public static final ChildNumber ZERO = new ChildNumber(0); 35 | public static final ChildNumber ONE = new ChildNumber(1); 36 | public static final ChildNumber ZERO_HARDENED = new ChildNumber(0, true); 37 | 38 | /** 39 | * Integer i as per BIP 32 spec, including the MSB denoting derivation type (0 = public, 1 = private) * 40 | */ 41 | private final int i; 42 | 43 | public ChildNumber(int childNumber, boolean isHardened) { 44 | if (hasHardenedBit(childNumber)) 45 | throw new IllegalArgumentException("Most significant bit is reserved and shouldn't be set: " + childNumber); 46 | i = isHardened ? (childNumber | HARDENED_BIT) : childNumber; 47 | } 48 | 49 | public ChildNumber(int i) { 50 | this.i = i; 51 | } 52 | 53 | /** 54 | * Returns the uint32 encoded form of the path element, including the most significant bit. 55 | */ 56 | public int getI() { 57 | return i; 58 | } 59 | 60 | /** 61 | * Returns the uint32 encoded form of the path element, including the most significant bit. 62 | */ 63 | public int i() { 64 | return i; 65 | } 66 | 67 | public boolean isHardened() { 68 | return hasHardenedBit(i); 69 | } 70 | 71 | private static boolean hasHardenedBit(int a) { 72 | return (a & HARDENED_BIT) != 0; 73 | } 74 | 75 | /** 76 | * Returns the child number without the hardening bit set (i.e. index in that part of the tree). 77 | */ 78 | public int num() { 79 | return i & (~HARDENED_BIT); 80 | } 81 | 82 | @Override 83 | public String toString() { 84 | return String.format("%d%s", num(), isHardened() ? "H" : ""); 85 | } 86 | 87 | @Override 88 | public boolean equals(Object o) { 89 | if (this == o) return true; 90 | if (o == null || getClass() != o.getClass()) return false; 91 | ChildNumber other = (ChildNumber) o; 92 | return i == other.i; 93 | } 94 | 95 | @Override 96 | public int hashCode() { 97 | return i; 98 | } 99 | } 100 | -------------------------------------------------------------------------------- /bitherj/src/main/java/net/bither/bitherj/crypto/hd/HDDerivationException.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2013 Matija Mazi. 3 | *

4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | *

8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | *

10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package net.bither.bitherj.crypto.hd; 18 | 19 | public class HDDerivationException extends RuntimeException { 20 | public HDDerivationException(String message) { 21 | super(message); 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /bitherj/src/main/java/net/bither/bitherj/crypto/mnemonic/MnemonicException.java: -------------------------------------------------------------------------------- 1 | /* 2 | * 3 | * * Copyright 2014 http://Bither.net 4 | * * 5 | * * Licensed under the Apache License, Version 2.0 (the "License"); 6 | * * you may not use this file except in compliance with the License. 7 | * * You may obtain a copy of the License at 8 | * * 9 | * * http://www.apache.org/licenses/LICENSE-2.0 10 | * * 11 | * * Unless required by applicable law or agreed to in writing, software 12 | * * distributed under the License is distributed on an "AS IS" BASIS, 13 | * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * * See the License for the specific language governing permissions and 15 | * * limitations under the License. 16 | * 17 | */ 18 | 19 | package net.bither.bitherj.crypto.mnemonic; 20 | 21 | /** 22 | * Exceptions thrown by the MnemonicCode module. 23 | */ 24 | @SuppressWarnings("serial") 25 | public class MnemonicException extends Exception { 26 | public MnemonicException() { 27 | super(); 28 | } 29 | 30 | public MnemonicException(String msg) { 31 | super(msg); 32 | } 33 | 34 | /** 35 | * Thrown when an argument to MnemonicCode is the wrong length. 36 | */ 37 | public static class MnemonicLengthException extends MnemonicException { 38 | public MnemonicLengthException(String msg) { 39 | super(msg); 40 | } 41 | } 42 | 43 | /** 44 | * Thrown when a list of MnemonicCode words fails the checksum check. 45 | */ 46 | public static class MnemonicChecksumException extends MnemonicException { 47 | public MnemonicChecksumException() { 48 | super(); 49 | } 50 | } 51 | 52 | /** 53 | * Thrown when a word is encountered which is not in the MnemonicCode's word list. 54 | */ 55 | public static class MnemonicWordException extends MnemonicException { 56 | /** 57 | * Contains the word that was not found in the word list. 58 | */ 59 | public final String badWord; 60 | 61 | public MnemonicWordException(String badWord) { 62 | super(); 63 | this.badWord = badWord; 64 | } 65 | } 66 | } 67 | -------------------------------------------------------------------------------- /bitherj/src/main/java/net/bither/bitherj/db/IAddressProvider.java: -------------------------------------------------------------------------------- 1 | package net.bither.bitherj.db; 2 | 3 | import net.bither.bitherj.core.Address; 4 | import net.bither.bitherj.core.HDMAddress; 5 | import net.bither.bitherj.core.HDMBId; 6 | import net.bither.bitherj.core.HDMKeychain; 7 | import net.bither.bitherj.crypto.PasswordSeed; 8 | import net.bither.bitherj.db.imp.base.IDb; 9 | 10 | import java.util.List; 11 | import java.util.Map; 12 | 13 | import javax.annotation.Nullable; 14 | 15 | public interface IAddressProvider { 16 | // password 17 | boolean changePassword(CharSequence oldPassword, CharSequence newPassword); 18 | 19 | PasswordSeed getPasswordSeed(); 20 | 21 | boolean hasPasswordSeed(); 22 | 23 | // hdm 24 | List getHDSeeds(); 25 | 26 | String getEncryptMnemonicSeed(int hdSeedId); 27 | 28 | String getEncryptHDSeed(int hdSeedId); 29 | 30 | 31 | void updateEncrypttMnmonicSeed(int hdSeedId, String encryptMnmonicSeed); 32 | 33 | boolean isHDSeedFromXRandom(int hdSeedId); 34 | 35 | String getHDMFristAddress(int hdSeedId); 36 | 37 | String getSingularModeBackup(int hdSeedId); 38 | 39 | void setSingularModeBackup(int hdSeedId, String singularModeBackup); 40 | 41 | int addHDKey(String encryptedMnemonicSeed, String encryptHdSeed, String firstAddress, boolean isXrandom, String addressOfPS); 42 | 43 | int addEnterpriseHDKey(String encryptedMnemonicSeed, String encryptHdSeed, String firstAddress, boolean isXrandom, String addressOfPS); 44 | HDMBId getHDMBId(); 45 | 46 | 47 | void addAndUpdateHDMBId(HDMBId bitherId, String addressOfPS); 48 | 49 | 50 | List getHDMAddressInUse(HDMKeychain keychain); 51 | 52 | void prepareHDMAddresses(int hdSeedId, List pubs); 53 | 54 | List getUncompletedHDMAddressPubs(int hdSeedId, int count); 55 | 56 | int maxHDMAddressPubIndex(int hdSeedId);//including completed and uncompleted 57 | 58 | void recoverHDMAddresses(int hdSeedId, List addresses); 59 | 60 | 61 | void completeHDMAddresses(int hdSeedId, List addresses); 62 | 63 | void setHDMPubsRemote(int hdSeedId, int index, byte[] remote); 64 | 65 | int uncompletedHDMAddressCount(int hdSeedId); 66 | 67 | void syncComplete(int hdSeedId, int hdSeedIndex); 68 | 69 | 70 | //normal 71 | List

getAddresses(); 72 | 73 | String getEncryptPrivateKey(String address); 74 | 75 | void addAddress(Address address); 76 | 77 | void updatePrivateKey(String address, String encryptPriv); 78 | 79 | void removeWatchOnlyAddress(Address address); 80 | 81 | void trashPrivKeyAddress(Address address); 82 | 83 | void restorePrivKeyAddress(Address address); 84 | 85 | void updateSyncComplete(Address address); 86 | 87 | // alias 88 | Map getAliases(); 89 | 90 | void updateAlias(String address, @Nullable String alias); 91 | 92 | //vanity_len 93 | Map getVanitylens(); 94 | 95 | void updateVaitylen(String address, int vanitylen); 96 | 97 | 98 | } 99 | -------------------------------------------------------------------------------- /bitherj/src/main/java/net/bither/bitherj/db/IBlockProvider.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2014 http://Bither.net 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package net.bither.bitherj.db; 18 | 19 | 20 | import net.bither.bitherj.core.Block; 21 | 22 | import java.util.List; 23 | 24 | public interface IBlockProvider { 25 | 26 | List getAllBlocks(); 27 | 28 | List getBlocksFrom(int blockNo); 29 | 30 | List getLimitBlocks(int limit); 31 | 32 | int getBlockCount(); 33 | 34 | Block getLastBlock(); 35 | 36 | Block getLastOrphanBlock(); 37 | 38 | Block getBlock(byte[] blockHash); 39 | 40 | Block getOrphanBlockByPrevHash(byte[] prevHash); 41 | 42 | Block getMainChainBlock(byte[] blockHash); 43 | 44 | // List exists(List blockHashes); 45 | 46 | void addBlocks(List blockItemList); 47 | 48 | void addBlock(Block item); 49 | 50 | void updateBlock(byte[] blockHash, boolean isMain); 51 | 52 | void removeBlock(byte[] blockHash); 53 | 54 | void cleanOldBlock(); 55 | 56 | 57 | } 58 | -------------------------------------------------------------------------------- /bitherj/src/main/java/net/bither/bitherj/db/IDesktopAddressProvider.java: -------------------------------------------------------------------------------- 1 | /* 2 | * 3 | * Copyright 2014 http://Bither.net 4 | * 5 | * Licensed under the Apache License, Version 2.0 (the "License"); 6 | * you may not use this file except in compliance with the License. 7 | * You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | * / 17 | */ 18 | 19 | package net.bither.bitherj.db; 20 | 21 | import java.util.List; 22 | 23 | public interface IDesktopAddressProvider { 24 | 25 | int addHDKey(String encryptedMnemonicSeed, String encryptHdSeed, 26 | String firstAddress, boolean isXrandom, String addressOfPS 27 | , byte[] externalPub, byte[] internalPub); 28 | 29 | void addHDMPub(List externalPubs, List internalPubs); 30 | 31 | List getExternalPubs(); 32 | 33 | List getInternalPubs(); 34 | 35 | boolean isHDSeedFromXRandom(int hdSeedId); 36 | 37 | String getEncryptMnemonicSeed(int hdSeedId); 38 | 39 | String getEncryptHDSeed(int hdSeedId); 40 | 41 | String getHDMFristAddress(int hdSeedId); 42 | 43 | List getDesktopKeyChainSeed(); 44 | } 45 | -------------------------------------------------------------------------------- /bitherj/src/main/java/net/bither/bitherj/db/IDesktopTxProvider.java: -------------------------------------------------------------------------------- 1 | /* 2 | * 3 | * Copyright 2014 http://Bither.net 4 | * 5 | * Licensed under the Apache License, Version 2.0 (the "License"); 6 | * you may not use this file except in compliance with the License. 7 | * You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | * / 17 | */ 18 | 19 | package net.bither.bitherj.db; 20 | 21 | import net.bither.bitherj.core.AbstractHD; 22 | import net.bither.bitherj.core.DesktopHDMAddress; 23 | import net.bither.bitherj.core.DesktopHDMKeychain; 24 | import net.bither.bitherj.core.HDMAddress; 25 | import net.bither.bitherj.core.In; 26 | import net.bither.bitherj.core.Out; 27 | import net.bither.bitherj.core.Tx; 28 | 29 | import java.util.HashSet; 30 | import java.util.List; 31 | 32 | /** 33 | * Created by nn on 15/6/15. 34 | */ 35 | public interface IDesktopTxProvider { 36 | void addAddress(List address); 37 | 38 | int maxHDMAddressPubIndex(); 39 | 40 | String externalAddress(); 41 | 42 | boolean hasAddress(); 43 | 44 | long getHDAccountConfirmedBanlance(int hdSeedId); 45 | 46 | HashSet getBelongAccountAddresses(List addressList); 47 | 48 | void updateIssuedIndex(AbstractHD.PathType pathType, int index); 49 | 50 | int issuedIndex(AbstractHD.PathType pathType); 51 | 52 | int allGeneratedAddressCount(AbstractHD.PathType pathType); 53 | 54 | void updateSyncdForIndex(AbstractHD.PathType pathType, int index); 55 | 56 | void updateSyncdComplete(DesktopHDMAddress address); 57 | 58 | List getHDAccountUnconfirmedTx(); 59 | 60 | List getPubs(AbstractHD.PathType pathType); 61 | 62 | int getUnspendOutCountByHDAccountWithPath(int hdAccountId, AbstractHD.PathType pathType); 63 | 64 | List getUnspendOutByHDAccountWithPath(int hdAccountId, AbstractHD.PathType pathType); 65 | 66 | DesktopHDMAddress addressForPath(DesktopHDMKeychain keychain, AbstractHD.PathType type, int index); 67 | 68 | List getSigningAddressesForInputs(DesktopHDMKeychain keychain, List inList); 69 | 70 | List belongAccount(DesktopHDMKeychain keychain, List addresses); 71 | 72 | List getUnspendOutByHDAccount(int hdAccountId); 73 | 74 | int unSyncedAddressCount(); 75 | } 76 | -------------------------------------------------------------------------------- /bitherj/src/main/java/net/bither/bitherj/db/IEnterpriseHDMProvider.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2014 http://Bither.net 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package net.bither.bitherj.db; 18 | 19 | import net.bither.bitherj.core.EnterpriseHDMAddress; 20 | import net.bither.bitherj.core.EnterpriseHDMKeychain; 21 | 22 | import java.util.List; 23 | 24 | public interface IEnterpriseHDMProvider { 25 | 26 | 27 | String getEnterpriseEncryptMnemonicSeed(int hdSeedId); 28 | 29 | String getEnterpriseEncryptHDSeed(int hdSeedId); 30 | 31 | String getEnterpriseHDFristAddress(int hdSeedId); 32 | 33 | boolean isEnterpriseHDMSeedFromXRandom(int hdSeedId); 34 | 35 | void addEnterpriseHDMAddress(List enterpriseHDMAddressList); 36 | 37 | List getEnterpriseHDMAddress(EnterpriseHDMKeychain keychain); 38 | 39 | void addMultiSignSet(int n, int m); 40 | 41 | void updateSyncComplete(EnterpriseHDMAddress enterpriseHDMAddress); 42 | 43 | List getEnterpriseHDMKeychainIds(); 44 | 45 | int getEnterpriseHDMSeedId(); 46 | 47 | int getPubCount(); 48 | 49 | int getThreshold(); 50 | } 51 | -------------------------------------------------------------------------------- /bitherj/src/main/java/net/bither/bitherj/db/IHDAccountAddressProvider.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2014 http://Bither.net 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | 18 | package net.bither.bitherj.db; 19 | 20 | import net.bither.bitherj.core.AbstractHD; 21 | import net.bither.bitherj.core.HDAccount; 22 | import net.bither.bitherj.core.In; 23 | import net.bither.bitherj.core.Out; 24 | import net.bither.bitherj.core.Tx; 25 | 26 | import java.util.HashSet; 27 | import java.util.List; 28 | 29 | public interface IHDAccountAddressProvider { 30 | 31 | 32 | void addAddress(List hdAccountAddresses); 33 | 34 | int issuedIndex(int hdAccountId, AbstractHD.PathType pathType); 35 | 36 | int allGeneratedAddressCount(int hdAccountId, AbstractHD.PathType pathType); 37 | 38 | void updateIssuedIndex(int hdAccountId, AbstractHD.PathType pathType, int index); 39 | 40 | String externalAddress(int hdAccountId); 41 | 42 | 43 | HashSet getBelongAccountAddresses(int hdAccountId, List addressList); 44 | HashSet getBelongAccountAddresses(List addressList); 45 | Tx updateOutHDAccountId(Tx tx); 46 | int getRelatedAddressCnt(List addresses); 47 | List getRelatedHDAccountIdList(List addresses); 48 | 49 | 50 | HDAccount.HDAccountAddress addressForPath(int hdAccountId, AbstractHD.PathType type, int index); 51 | 52 | List getPubs(int hdAccountId, AbstractHD.PathType pathType); 53 | 54 | List belongAccount(int hdAccountId, List addresses); 55 | 56 | void updateSyncdComplete(int hdAccountId, HDAccount.HDAccountAddress address); 57 | 58 | void setSyncedNotComplete(); 59 | 60 | int unSyncedAddressCount(int hdAccountId); 61 | 62 | void updateSyncedForIndex(int hdAccountId, AbstractHD.PathType pathType, int index); 63 | 64 | List getSigningAddressesForInputs(int hdAccountId, List inList); 65 | 66 | int hdAccountTxCount(int hdAccountId); 67 | 68 | long getHDAccountConfirmedBalance(int hdAccountId); 69 | 70 | List getHDAccountUnconfirmedTx(int hdAccountId); 71 | 72 | long sentFromAccount(int hdAccountId, byte[] txHash); 73 | 74 | List getTxAndDetailByHDAccount(int hdAccountId, int page); 75 | 76 | List getTxAndDetailByHDAccount(int hdAccountId); 77 | 78 | List getUnspendOutByHDAccount(int hdAccountId); 79 | 80 | List getRecentlyTxsByAccount(int hdAccountId, int greaterThanBlockNo, int limit); 81 | 82 | int getUnspendOutCountByHDAccountWithPath(int hdAccountId, AbstractHD.PathType pathType); 83 | 84 | List getUnspendOutByHDAccountWithPath(int hdAccountId, AbstractHD.PathType pathType); 85 | 86 | int getUnconfirmedSpentOutCountByHDAccountWithPath(int hdAccountId, AbstractHD.PathType 87 | pathType); 88 | 89 | List getUnconfirmedSpentOutByHDAccountWithPath(int hdAccountId, AbstractHD.PathType pathType); 90 | 91 | boolean requestNewReceivingAddress(int hdAccountId); 92 | } 93 | -------------------------------------------------------------------------------- /bitherj/src/main/java/net/bither/bitherj/db/IHDAccountProvider.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2014 http://Bither.net 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package net.bither.bitherj.db; 18 | 19 | import java.util.List; 20 | 21 | public interface IHDAccountProvider { 22 | 23 | int addHDAccount(String encryptedMnemonicSeed, String encryptSeed 24 | , String firstAddress, boolean isXrandom, String addressOfPS 25 | , byte[] externalPub, byte[] internalPub); 26 | 27 | int addMonitoredHDAccount(String firstAddress, boolean isXrandom, byte[] externalPub, byte[] internalPub); 28 | 29 | boolean hasMnemonicSeed(int hdAccountId); 30 | 31 | String getHDFirstAddress(int hdSeedId); 32 | 33 | byte[] getExternalPub(int hdSeedId); 34 | 35 | byte[] getInternalPub(int hdSeedId); 36 | 37 | String getHDAccountEncryptSeed(int hdSeedId); 38 | 39 | String getHDAccountEncryptMnemonicSeed(int hdSeedId); 40 | 41 | boolean hdAccountIsXRandom(int seedId); 42 | 43 | List getHDAccountSeeds(); 44 | 45 | boolean isPubExist(byte[] externalPub, byte[] internalPub); 46 | } 47 | -------------------------------------------------------------------------------- /bitherj/src/main/java/net/bither/bitherj/db/IPeerProvider.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2014 http://Bither.net 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package net.bither.bitherj.db; 18 | 19 | import net.bither.bitherj.core.Peer; 20 | 21 | import java.net.InetAddress; 22 | import java.util.ArrayList; 23 | import java.util.List; 24 | 25 | public interface IPeerProvider { 26 | 27 | // ArrayList exists(ArrayList peerAddresses); 28 | 29 | void addPeers(List items); 30 | 31 | void removePeer(InetAddress address); 32 | 33 | void connectSucceed(InetAddress address); 34 | 35 | List getPeersWithLimit(int limit); 36 | 37 | void cleanPeers(); 38 | 39 | void recreate(); 40 | } 41 | -------------------------------------------------------------------------------- /bitherj/src/main/java/net/bither/bitherj/db/ITxProvider.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2014 http://Bither.net 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package net.bither.bitherj.db; 18 | 19 | import net.bither.bitherj.core.In; 20 | import net.bither.bitherj.core.Out; 21 | import net.bither.bitherj.core.Tx; 22 | import net.bither.bitherj.utils.Sha256Hash; 23 | 24 | import java.util.HashMap; 25 | import java.util.List; 26 | 27 | public interface ITxProvider { 28 | List getTxAndDetailByAddress(String address); 29 | 30 | List getTxAndDetailByAddress(String address, int page); 31 | 32 | List getPublishedTxs(); 33 | 34 | Tx getTxDetailByTxHash(byte[] txHash); 35 | 36 | long sentFromAddress(byte[] txHash, String address); 37 | 38 | boolean isExist(byte[] txHash); 39 | 40 | void add(Tx txItem); 41 | 42 | void addTxs(List txItems); 43 | 44 | void remove(byte[] txHash); 45 | 46 | 47 | boolean isAddressContainsTx(String address, Tx txItem); 48 | 49 | boolean isTxDoubleSpendWithConfirmedTx(Tx tx); 50 | 51 | List getInAddresses(Tx tx); 52 | 53 | 54 | void confirmTx(int blockNo, List txHashes); 55 | 56 | void unConfirmTxByBlockNo(int blockNo); 57 | 58 | List getUnspendTxWithAddress(String address); 59 | 60 | // List getUnspendOutWithAddress(String address); 61 | 62 | // for calculate balance 63 | long getConfirmedBalanceWithAddress(String address); 64 | 65 | List getUnconfirmedTxWithAddress(String address); 66 | 67 | int txCount(String address); 68 | 69 | long totalReceive(String address); 70 | 71 | void txSentBySelfHasSaw(byte[] txHash); 72 | 73 | List getOuts(); 74 | 75 | // List getRelatedIn(String address); 76 | 77 | List getRecentlyTxsByAddress(String address, int greateThanBlockNo, int limit); 78 | 79 | // do not check tx 's dependency fo now 80 | // HashMap getTxDependencies(Tx txItem); 81 | 82 | // complete in signature 83 | void completeInSignature(List ins); 84 | 85 | int needCompleteInSignature(String address); 86 | 87 | byte[] isIdentify(Tx tx); 88 | 89 | void clearAllTx(); 90 | } 91 | -------------------------------------------------------------------------------- /bitherj/src/main/java/net/bither/bitherj/db/imp/AbstractProvider.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2014 http://Bither.net 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package net.bither.bitherj.db.imp; 18 | 19 | import com.google.common.base.Function; 20 | 21 | import net.bither.bitherj.db.imp.base.ICursor; 22 | import net.bither.bitherj.db.imp.base.IDb; 23 | import net.bither.bitherj.db.imp.base.IProvider; 24 | 25 | public abstract class AbstractProvider implements IProvider { 26 | @Override 27 | public void execUpdate(String sql, String[] params) { 28 | this.getWriteDb().execUpdate(sql, params); 29 | } 30 | 31 | @Override 32 | public void execQueryOneRecord(String sql, String[] params, Function func) { 33 | this.getReadDb().execQueryOneRecord(sql, params, func); 34 | } 35 | 36 | @Override 37 | public void execQueryLoop(String sql, String[] params, Function func) { 38 | this.getReadDb().execQueryLoop(sql, params, func); 39 | } 40 | 41 | @Override 42 | public void execUpdate(IDb db, String sql, String[] params) { 43 | db.execUpdate(sql, params); 44 | } 45 | 46 | @Override 47 | public void execQueryOneRecord(IDb db, String sql, String[] params, Function func) { 48 | db.execQueryOneRecord(sql, params, func); 49 | } 50 | 51 | @Override 52 | public void execQueryLoop(IDb db, String sql, String[] params, Function func) { 53 | db.execQueryLoop(sql, params, func); 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /bitherj/src/main/java/net/bither/bitherj/db/imp/base/ICursor.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2014 http://Bither.net 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package net.bither.bitherj.db.imp.base; 18 | 19 | public interface ICursor { 20 | int getCount(); 21 | 22 | // int getPosition(); 23 | 24 | // boolean move(int var1); 25 | 26 | // boolean moveToPosition(int var1); 27 | // 28 | // boolean moveToFirst(); 29 | // 30 | // boolean moveToLast(); 31 | 32 | boolean moveToNext(); 33 | 34 | // boolean moveToPrevious(); 35 | 36 | // boolean isFirst(); 37 | // 38 | // boolean isLast(); 39 | // 40 | // boolean isBeforeFirst(); 41 | // 42 | // boolean isAfterLast(); 43 | 44 | int getColumnIndex(String var1); 45 | 46 | int getColumnIndexOrThrow(String var1) throws IllegalArgumentException; 47 | 48 | // String getColumnName(int var1); 49 | // 50 | // String[] getColumnNames(); 51 | // 52 | // int getColumnCount(); 53 | 54 | byte[] getBlob(int var1); 55 | 56 | String getString(int var1); 57 | 58 | short getShort(int var1); 59 | 60 | int getInt(int var1); 61 | 62 | long getLong(int var1); 63 | 64 | float getFloat(int var1); 65 | 66 | double getDouble(int var1); 67 | 68 | int getType(int var1); 69 | 70 | boolean isNull(int var1); 71 | 72 | void close(); 73 | 74 | boolean isClosed(); 75 | } 76 | -------------------------------------------------------------------------------- /bitherj/src/main/java/net/bither/bitherj/db/imp/base/IDb.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2014 http://Bither.net 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package net.bither.bitherj.db.imp.base; 18 | 19 | import com.google.common.base.Function; 20 | 21 | public interface IDb { 22 | void beginTransaction(); 23 | void endTransaction(); 24 | void close(); 25 | 26 | void execUpdate(String sql, String[] params); 27 | void execQueryOneRecord(String sql, String[] params, Function func); 28 | void execQueryLoop(String sql, String[] params, Function func); 29 | } 30 | -------------------------------------------------------------------------------- /bitherj/src/main/java/net/bither/bitherj/db/imp/base/IProvider.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2014 http://Bither.net 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package net.bither.bitherj.db.imp.base; 18 | 19 | import com.google.common.base.Function; 20 | 21 | public interface IProvider { 22 | IDb getReadDb(); 23 | IDb getWriteDb(); 24 | 25 | void execUpdate(String sql, String[] params); 26 | void execQueryOneRecord(String sql, String[] params, Function func); 27 | void execQueryLoop(String sql, String[] params, Function func); 28 | 29 | void execUpdate(IDb db, String sql, String[] params); 30 | void execQueryOneRecord(IDb db, String sql, String[] params, Function func); 31 | void execQueryLoop(IDb db, String sql, String[] params, Function func); 32 | } 33 | -------------------------------------------------------------------------------- /bitherj/src/main/java/net/bither/bitherj/delegate/HDMHotAdd.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2014 http://Bither.net 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package net.bither.bitherj.delegate; 18 | 19 | import net.bither.bitherj.core.AddressManager; 20 | import net.bither.bitherj.core.HDMAddress; 21 | import net.bither.bitherj.core.HDMBId; 22 | import net.bither.bitherj.core.HDMKeychain; 23 | import net.bither.bitherj.crypto.hd.DeterministicKey; 24 | import net.bither.bitherj.crypto.hd.HDKeyDerivation; 25 | import net.bither.bitherj.utils.Utils; 26 | 27 | import java.util.Arrays; 28 | import java.util.List; 29 | 30 | public abstract class HDMHotAdd implements IPasswordGetterDelegate { 31 | public interface IHDMHotAddDelegate { 32 | public void moveToCold(boolean anim); 33 | 34 | public void moveToServer(boolean anim); 35 | 36 | public void moveToFinal(boolean isFinal); 37 | 38 | public void callScanCold(); 39 | 40 | public void callServerQRCode(); 41 | 42 | public void callKeychainHotUEntropy(); 43 | 44 | } 45 | 46 | 47 | public static interface IGenerateHDMKeyChain { 48 | public abstract void generateHDMKeyChain(HDMKeychain hdmKeychain); 49 | 50 | public abstract void beginCompleteAddress(); 51 | 52 | public abstract void completeAddrees(List hdmAddresses); 53 | 54 | 55 | } 56 | 57 | 58 | protected IHDMHotAddDelegate delegate; 59 | protected IPasswordGetter passwordGetter; 60 | 61 | protected boolean isServerClicked = false; 62 | 63 | protected HDMBId hdmBid; 64 | 65 | protected byte[] coldRoot; 66 | 67 | public boolean hdmKeychainLimit; 68 | 69 | public HDMSingular singular; 70 | 71 | public HDMHotAdd(IHDMHotAddDelegate delegate) { 72 | this.delegate = delegate; 73 | hdmKeychainLimit = AddressManager.isHDMKeychainLimit(); 74 | 75 | } 76 | 77 | public abstract void hotClick(); 78 | 79 | public abstract void coldClick(); 80 | 81 | public abstract void scanColdResult(String result); 82 | 83 | public abstract void serverQRCode(final String result); 84 | 85 | public abstract void serviceClick(); 86 | 87 | public abstract void xrandomResult(); 88 | 89 | public void initHDMBidFromColdRoot() { 90 | if (hdmBid != null) { 91 | return; 92 | } 93 | DeterministicKey root = HDKeyDerivation.createMasterPubKeyFromExtendedBytes(Arrays.copyOf 94 | (coldRoot, coldRoot.length)); 95 | DeterministicKey key = root.deriveSoftened(0); 96 | String address = Utils.toAddress(key.getPubKeyHash()); 97 | root.wipe(); 98 | key.wipe(); 99 | hdmBid = new HDMBId(address); 100 | } 101 | 102 | 103 | public void wipe() { 104 | if (passwordGetter != null) { 105 | passwordGetter.wipe(); 106 | } 107 | if (coldRoot != null) { 108 | Utils.wipeBytes(coldRoot); 109 | } 110 | } 111 | 112 | 113 | } 114 | 115 | -------------------------------------------------------------------------------- /bitherj/src/main/java/net/bither/bitherj/delegate/IPasswordGetter.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2014 http://Bither.net 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package net.bither.bitherj.delegate; 18 | 19 | import net.bither.bitherj.crypto.SecureCharSequence; 20 | 21 | /** 22 | * Created by nn on 15/2/15. 23 | */ 24 | public interface IPasswordGetter { 25 | 26 | public void setPassword(SecureCharSequence password); 27 | 28 | public boolean hasPassword(); 29 | 30 | public SecureCharSequence getPassword(); 31 | 32 | public void wipe(); 33 | } 34 | -------------------------------------------------------------------------------- /bitherj/src/main/java/net/bither/bitherj/delegate/IPasswordGetterDelegate.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2014 http://Bither.net 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package net.bither.bitherj.delegate; 18 | 19 | public interface IPasswordGetterDelegate { 20 | 21 | public void beforePasswordDialogShow(); 22 | 23 | public void afterPasswordDialogDismiss(); 24 | } -------------------------------------------------------------------------------- /bitherj/src/main/java/net/bither/bitherj/exception/AddressFormatException.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2011 Google Inc. 3 | *

4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | *

8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | *

10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package net.bither.bitherj.exception; 18 | 19 | @SuppressWarnings("serial") 20 | public class AddressFormatException extends Exception { 21 | public AddressFormatException() { 22 | super(); 23 | } 24 | 25 | public AddressFormatException(String message) { 26 | super(message); 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /bitherj/src/main/java/net/bither/bitherj/exception/BlockStoreException.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2011 Google Inc. 3 | *

4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | *

8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | *

10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package net.bither.bitherj.exception; 18 | 19 | /** 20 | * Thrown when something goes wrong with storing a block. Examples: out of disk space. 21 | */ 22 | public class BlockStoreException extends Exception { 23 | public BlockStoreException(String message) { 24 | super(message); 25 | } 26 | 27 | public BlockStoreException(Throwable t) { 28 | super(t); 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /bitherj/src/main/java/net/bither/bitherj/exception/PasswordException.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2014 http://Bither.net 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package net.bither.bitherj.exception; 18 | 19 | public class PasswordException extends RuntimeException { 20 | public PasswordException(String msg) { 21 | super(msg); 22 | } 23 | 24 | public PasswordException(Exception e) { 25 | super(e); 26 | } 27 | 28 | public PasswordException(String msg, Throwable t) { 29 | super(msg, t); 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /bitherj/src/main/java/net/bither/bitherj/exception/ProtocolException.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2011 Google Inc. 3 | *

4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | *

8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | *

10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package net.bither.bitherj.exception; 18 | 19 | @SuppressWarnings("serial") 20 | public class ProtocolException extends VerificationException { 21 | 22 | public ProtocolException(String msg) { 23 | super(msg); 24 | } 25 | 26 | public ProtocolException(Exception e) { 27 | super(e); 28 | } 29 | 30 | public ProtocolException(String msg, Exception e) { 31 | super(msg, e); 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /bitherj/src/main/java/net/bither/bitherj/exception/ScriptException.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2011 Google Inc. 3 | *

4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | *

8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | *

10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package net.bither.bitherj.exception; 18 | 19 | @SuppressWarnings("serial") 20 | public class ScriptException extends VerificationException { 21 | 22 | public ScriptException(String msg) { 23 | super(msg); 24 | } 25 | 26 | public ScriptException(String msg, Exception e) { 27 | super(msg, e); 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /bitherj/src/main/java/net/bither/bitherj/exception/VerificationException.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2011 Google Inc. 3 | *

4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | *

8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | *

10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package net.bither.bitherj.exception; 18 | 19 | @SuppressWarnings("serial") 20 | public class VerificationException extends RuntimeException { 21 | public VerificationException(String msg) { 22 | super(msg); 23 | } 24 | 25 | public VerificationException(Exception e) { 26 | super(e); 27 | } 28 | 29 | public VerificationException(String msg, Throwable t) { 30 | super(msg, t); 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /bitherj/src/main/java/net/bither/bitherj/message/ChildMessage.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2011 Steve Coughlan. 3 | *

4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | *

8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | *

10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package net.bither.bitherj.message; 17 | 18 | import net.bither.bitherj.exception.ProtocolException; 19 | 20 | import javax.annotation.Nullable; 21 | 22 | /** 23 | * Represents a Message type that can be contained within another Message. ChildMessages that have a cached 24 | * backing byte array need to invalidate their parent's caches as well as their own if they are modified. 25 | * 26 | * @author git 27 | */ 28 | public abstract class ChildMessage extends Message { 29 | private static final long serialVersionUID = -7657113383624517931L; 30 | 31 | @Nullable 32 | private Message parent; 33 | 34 | protected ChildMessage() { 35 | } 36 | 37 | // public ChildMessage() { 38 | // super(); 39 | // } 40 | 41 | public ChildMessage(byte[] msg, int offset, int protocolVersion) throws ProtocolException { 42 | super(msg, offset, protocolVersion); 43 | } 44 | 45 | public ChildMessage(byte[] msg, int offset, int protocolVersion, int length) throws ProtocolException { 46 | super(msg, offset, protocolVersion, length); 47 | } 48 | 49 | public ChildMessage(byte[] msg, int offset, int protocolVersion, Message parent, int length) throws ProtocolException { 50 | super(msg, offset, protocolVersion, length); 51 | this.parent = parent; 52 | } 53 | 54 | public ChildMessage(byte[] msg, int offset) throws ProtocolException { 55 | super(msg, offset); 56 | } 57 | 58 | public ChildMessage(byte[] msg, int offset, @Nullable Message parent, int length) 59 | throws ProtocolException { 60 | super(msg, offset, length); 61 | this.parent = parent; 62 | } 63 | 64 | public void setParent(@Nullable Message parent) { 65 | if (this.parent != null && this.parent != parent && parent != null) { 66 | // After old parent is unlinked it won't be able to receive notice if this ChildMessage 67 | // changes internally. To be safe we invalidate the parent cache to ensure it rebuilds 68 | // manually on serialization. 69 | // this.parent.unCache(); 70 | } 71 | this.parent = parent; 72 | } 73 | 74 | protected void adjustLength(int adjustment) { 75 | adjustLength(0, adjustment); 76 | } 77 | 78 | protected void adjustLength(int newArraySize, int adjustment) { 79 | super.adjustLength(newArraySize, adjustment); 80 | if (parent != null) 81 | parent.adjustLength(newArraySize, adjustment); 82 | } 83 | 84 | } 85 | -------------------------------------------------------------------------------- /bitherj/src/main/java/net/bither/bitherj/message/EmptyMessage.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2011 Steve Coughlan. 3 | *

4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | *

8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | *

10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package net.bither.bitherj.message; 17 | 18 | import net.bither.bitherj.exception.ProtocolException; 19 | 20 | import java.io.IOException; 21 | import java.io.OutputStream; 22 | 23 | /** 24 | * Parent class for header only messages that don't have a payload. 25 | * Currently this includes getaddr, ping, verack as well as the special bitcoinj class UnknownMessage 26 | * 27 | * @author git 28 | */ 29 | public abstract class EmptyMessage extends Message { 30 | private static final long serialVersionUID = 8240801253854151802L; 31 | 32 | public EmptyMessage() { 33 | length = 0; 34 | } 35 | 36 | // public EmptyMessage() { 37 | // super(); 38 | // length = 0; 39 | // } 40 | 41 | public EmptyMessage(byte[] msg, int offset) throws ProtocolException { 42 | super(msg, offset, 0); 43 | length = 0; 44 | } 45 | 46 | @Override 47 | final protected void bitcoinSerializeToStream(OutputStream stream) throws IOException { 48 | } 49 | 50 | @Override 51 | public int getMessageSize() { 52 | return 0; 53 | } 54 | 55 | /* (non-Javadoc) 56 | * @see Message#parse() 57 | */ 58 | @Override 59 | protected void parse() throws ProtocolException { 60 | } 61 | 62 | /* (non-Javadoc) 63 | * @see Message#bitcoinSerialize() 64 | */ 65 | @Override 66 | public byte[] bitcoinSerialize() { 67 | return new byte[0]; 68 | } 69 | 70 | 71 | } 72 | -------------------------------------------------------------------------------- /bitherj/src/main/java/net/bither/bitherj/message/GetAddrMessage.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2011 Google Inc. 3 | *

4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | *

8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | *

10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package net.bither.bitherj.message; 18 | 19 | /** 20 | * Represents the "getaddr" P2P protocol message, which requests network {@link AddressMessage}s from a peer. Not to 21 | * be confused with {@link } which is sort of like an account number. 22 | */ 23 | public class GetAddrMessage extends EmptyMessage { 24 | private static final long serialVersionUID = 6204437624599661503L; 25 | 26 | public GetAddrMessage() { 27 | super(); 28 | } 29 | 30 | } 31 | -------------------------------------------------------------------------------- /bitherj/src/main/java/net/bither/bitherj/message/GetDataMessage.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2011 Google Inc. 3 | *

4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | *

8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | *

10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package net.bither.bitherj.message; 18 | 19 | import net.bither.bitherj.exception.ProtocolException; 20 | import net.bither.bitherj.utils.InventoryItem; 21 | 22 | /** 23 | * Represents the "getdata" P2P network message, which requests the contents of blocks or transactions given their 24 | * hashes. 25 | */ 26 | public class GetDataMessage extends ListMessage { 27 | private static final long serialVersionUID = 2754681589501709887L; 28 | 29 | public GetDataMessage(byte[] payloadBytes) throws ProtocolException { 30 | super(payloadBytes); 31 | } 32 | 33 | /** 34 | * Deserializes a 'getdata' message. 35 | * // * @param params NetworkParameters object. 36 | * 37 | * @param msg Bitcoin protocol formatted byte array containing message content. 38 | * If true and the backing byte array is invalidated due to modification of a field then 39 | * the cached bytes may be repopulated and retained if the message is serialized again in the future. 40 | * @param length The length of message if known. Usually this is provided when deserializing of the wire 41 | * as the length will be provided as part of the header. If unknown then set to Message.UNKNOWN_LENGTH 42 | * @throws net.bither.bitherj.exception.ProtocolException 43 | */ 44 | public GetDataMessage(byte[] msg, int length) 45 | throws ProtocolException { 46 | super(msg, length); 47 | } 48 | 49 | public GetDataMessage() { 50 | super(); 51 | } 52 | 53 | public void addTransaction(byte[] hash) { 54 | addItem(new InventoryItem(InventoryItem.Type.Transaction, hash)); 55 | } 56 | 57 | public void addBlock(byte[] hash) { 58 | addItem(new InventoryItem(InventoryItem.Type.Block, hash)); 59 | } 60 | 61 | public void addFilteredBlock(byte[] hash) { 62 | addItem(new InventoryItem(InventoryItem.Type.FilteredBlock, hash)); 63 | } 64 | } 65 | -------------------------------------------------------------------------------- /bitherj/src/main/java/net/bither/bitherj/message/GetHeadersMessage.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2011 Google Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package net.bither.bitherj.message; 18 | 19 | import net.bither.bitherj.exception.ProtocolException; 20 | 21 | import java.util.List; 22 | 23 | /** 24 | * The "getheaders" command is structurally identical to "getblocks", but has different meaning. On receiving this 25 | * message a Bitcoin node returns matching blocks up to the limit, but without the bodies. It is useful as an 26 | * optimization: when your wallet does not contain any keys created before a particular time, you don't have to download 27 | * the bodies for those blocks because you know there are no relevant transactions. 28 | */ 29 | public class GetHeadersMessage extends GetBlocksMessage { 30 | public GetHeadersMessage(List locator, byte[] stopHash) { 31 | super(locator, stopHash); 32 | } 33 | 34 | public GetHeadersMessage(byte[] msg) throws ProtocolException { 35 | super(msg); 36 | } 37 | 38 | @Override 39 | public String toString() { 40 | StringBuffer b = new StringBuffer(); 41 | b.append("getheaders: "); 42 | for (byte[] hash : locator) { 43 | b.append(hash.toString()); 44 | b.append(" "); 45 | } 46 | return b.toString(); 47 | } 48 | 49 | /** 50 | * Compares two getheaders messages. Note that even though they are structurally identical a GetHeadersMessage 51 | * will not compare equal to a GetBlocksMessage containing the same data. 52 | */ 53 | @Override 54 | public boolean equals(Object o) { 55 | if (o == null || o.getClass() != getClass()) return false; 56 | GetHeadersMessage other = (GetHeadersMessage) o; 57 | return (other.version == version && 58 | locator.size() == other.locator.size() && locator.containsAll(other.locator) && 59 | stopHash.equals(other.stopHash)); 60 | } 61 | 62 | @Override 63 | public int hashCode() { 64 | int hashCode = (int) version ^ "getheaders".hashCode(); 65 | for (byte[] aLocator : locator) hashCode ^= aLocator.hashCode(); 66 | hashCode ^= stopHash.hashCode(); 67 | return hashCode; 68 | } 69 | } 70 | -------------------------------------------------------------------------------- /bitherj/src/main/java/net/bither/bitherj/message/InventoryMessage.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2011 Google Inc. 3 | *

4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | *

8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | *

10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package net.bither.bitherj.message; 18 | 19 | import net.bither.bitherj.core.Block; 20 | import net.bither.bitherj.core.Tx; 21 | import net.bither.bitherj.exception.ProtocolException; 22 | import net.bither.bitherj.utils.InventoryItem; 23 | 24 | import static com.google.common.base.Preconditions.checkArgument; 25 | 26 | /** 27 | *

Represents the "inv" P2P network message. An inv contains a list of hashes of either blocks or transactions. It's 28 | * a bandwidth optimization - on receiving some data, a (fully validating) peer sends every connected peer an inv 29 | * containing the hash of what it saw. It'll only transmit the full thing if a peer asks for it with a 30 | * {@link GetDataMessage}.

31 | */ 32 | public class InventoryMessage extends ListMessage { 33 | private static final long serialVersionUID = -7050246551646107066L; 34 | 35 | public InventoryMessage(byte[] bytes) throws ProtocolException { 36 | super(bytes); 37 | } 38 | 39 | /** 40 | * Deserializes an 'inv' message. 41 | * // * @param params NetworkParameters object. 42 | * 43 | * @param msg Bitcoin protocol formatted byte array containing message content. 44 | * If true and the backing byte array is invalidated due to modification of a field then 45 | * the cached bytes may be repopulated and retained if the message is serialized again in the future. 46 | * @param length The length of message if known. Usually this is provided when deserializing of the wire 47 | * as the length will be provided as part of the header. If unknown then set to Message.UNKNOWN_LENGTH 48 | * @throws ProtocolException 49 | */ 50 | public InventoryMessage(byte[] msg, int length) 51 | throws ProtocolException { 52 | super(msg, length); 53 | } 54 | 55 | public InventoryMessage() { 56 | super(); 57 | } 58 | 59 | public void addBlock(Block block) { 60 | addItem(new InventoryItem(InventoryItem.Type.Block, block.getBlockHash())); 61 | } 62 | 63 | public void addTransaction(Tx tx) { 64 | addItem(new InventoryItem(InventoryItem.Type.Transaction, tx.getTxHash())); 65 | } 66 | 67 | /** 68 | * Creates a new inv message for the given transactions. 69 | */ 70 | public static InventoryMessage with(Tx... txns) { 71 | checkArgument(txns.length > 0); 72 | InventoryMessage result = new InventoryMessage(); 73 | for (Tx tx : txns) 74 | result.addTransaction(tx); 75 | return result; 76 | } 77 | } 78 | -------------------------------------------------------------------------------- /bitherj/src/main/java/net/bither/bitherj/message/MemoryPoolMessage.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2012 Google Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package net.bither.bitherj.message; 18 | 19 | import net.bither.bitherj.exception.ProtocolException; 20 | 21 | import java.io.IOException; 22 | import java.io.OutputStream; 23 | 24 | /** 25 | * The "mempool" message asks a remote peer to announce all transactions in its memory pool, possibly restricted by 26 | * any Bloom filter set on the connection. The list of transaction hashes comes back in an inv message. Note that 27 | * this is different to the {@link } object which doesn't try to keep track of all pending transactions, 28 | * it's just a holding area for transactions that a part of the app may find interesting. The mempool message has 29 | * no fields. 30 | */ 31 | public class MemoryPoolMessage extends Message { 32 | @Override 33 | protected void parse() throws ProtocolException { 34 | } 35 | 36 | @Override 37 | protected void bitcoinSerializeToStream(OutputStream stream) throws IOException { 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /bitherj/src/main/java/net/bither/bitherj/message/NotFoundMessage.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2012 Google Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package net.bither.bitherj.message; 18 | 19 | import net.bither.bitherj.exception.ProtocolException; 20 | import net.bither.bitherj.utils.InventoryItem; 21 | 22 | import java.util.ArrayList; 23 | import java.util.List; 24 | 25 | /** 26 | * Sent by a peer when a getdata request doesn't find the requested data in the mempool. It has the same format 27 | * as an inventory message and lists the hashes of the missing items. 28 | */ 29 | public class NotFoundMessage extends InventoryMessage { 30 | public static int MIN_PROTOCOL_VERSION = 70001; 31 | 32 | public NotFoundMessage() { 33 | super(); 34 | } 35 | 36 | public NotFoundMessage(byte[] payloadBytes) throws ProtocolException { 37 | super(payloadBytes); 38 | } 39 | 40 | public NotFoundMessage(List items) { 41 | super(); 42 | this.items = new ArrayList(items); 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /bitherj/src/main/java/net/bither/bitherj/message/PingMessage.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2011 Noa Resare 3 | *

4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | *

8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | *

10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package net.bither.bitherj.message; 18 | 19 | import net.bither.bitherj.exception.ProtocolException; 20 | import net.bither.bitherj.utils.Utils; 21 | 22 | import java.io.IOException; 23 | import java.io.OutputStream; 24 | 25 | public class PingMessage extends Message { 26 | private long nonce; 27 | private boolean hasNonce; 28 | 29 | public PingMessage(byte[] payloadBytes) throws ProtocolException { 30 | super(payloadBytes, 0); 31 | } 32 | 33 | /** 34 | * Create a Ping with a nonce value. 35 | * Only use this if the remote node has a protocol version > 60000 36 | */ 37 | public PingMessage(long nonce) { 38 | this.nonce = nonce; 39 | this.hasNonce = true; 40 | } 41 | 42 | /** 43 | * Create a Ping without a nonce value. 44 | * Only use this if the remote node has a protocol version <= 60000 45 | */ 46 | public PingMessage() { 47 | this.hasNonce = false; 48 | } 49 | 50 | public void bitcoinSerializeToStream(OutputStream stream) throws IOException { 51 | if (hasNonce) 52 | Utils.int64ToByteStreamLE(nonce, stream); 53 | } 54 | 55 | @Override 56 | protected void parse() throws ProtocolException { 57 | try { 58 | nonce = readInt64(); 59 | hasNonce = true; 60 | } catch (ProtocolException e) { 61 | hasNonce = false; 62 | } 63 | length = hasNonce ? 8 : 0; 64 | } 65 | 66 | public boolean hasNonce() { 67 | return hasNonce; 68 | } 69 | 70 | public long getNonce() { 71 | return nonce; 72 | } 73 | } 74 | -------------------------------------------------------------------------------- /bitherj/src/main/java/net/bither/bitherj/message/PongMessage.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2012 Matt Corallo 3 | *

4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | *

8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | *

10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package net.bither.bitherj.message; 18 | 19 | import net.bither.bitherj.exception.ProtocolException; 20 | import net.bither.bitherj.utils.Utils; 21 | 22 | import java.io.IOException; 23 | import java.io.OutputStream; 24 | 25 | public class PongMessage extends Message { 26 | /** 27 | * The smallest protocol version that supports the pong response (BIP 31). Anything beyond version 60000. 28 | */ 29 | public static final int MIN_PROTOCOL_VERSION = 60001; 30 | 31 | private long nonce; 32 | 33 | public PongMessage(byte[] payloadBytes) throws ProtocolException { 34 | super(payloadBytes, 0); 35 | } 36 | 37 | /** 38 | * Create a Pong with a nonce value. 39 | * Only use this if the remote node has a protocol version > 60000 40 | */ 41 | public PongMessage(long nonce) { 42 | this.nonce = nonce; 43 | } 44 | 45 | @Override 46 | protected void parse() throws ProtocolException { 47 | nonce = readInt64(); 48 | length = 8; 49 | } 50 | 51 | public void bitcoinSerializeToStream(OutputStream stream) throws IOException { 52 | Utils.int64ToByteStreamLE(nonce, stream); 53 | } 54 | 55 | // @Override 56 | // protected void parseLite() { 57 | // } 58 | 59 | public long getNonce() { 60 | return nonce; 61 | } 62 | } 63 | -------------------------------------------------------------------------------- /bitherj/src/main/java/net/bither/bitherj/message/UnknownMessage.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2011 Google Inc. 3 | *

4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | *

8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | *

10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package net.bither.bitherj.message; 18 | 19 | import net.bither.bitherj.exception.ProtocolException; 20 | import net.bither.bitherj.utils.Utils; 21 | 22 | public class UnknownMessage extends EmptyMessage { 23 | private static final long serialVersionUID = 3614705938207918775L; 24 | private String name; 25 | 26 | public UnknownMessage(String name, byte[] payloadBytes) throws ProtocolException { 27 | super(payloadBytes, 0); 28 | this.name = name; 29 | } 30 | 31 | public String toString() { 32 | return "Unknown message [" + name + "]: " + (bytes == null ? "" : Utils.bytesToHexString(bytes)); 33 | } 34 | 35 | } 36 | -------------------------------------------------------------------------------- /bitherj/src/main/java/net/bither/bitherj/message/VersionAck.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2011 Noa Resare. 3 | *

4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | *

8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | *

10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package net.bither.bitherj.message; 18 | 19 | /** 20 | * The verack message, sent by a client accepting the version message they 21 | * received from their peer. 22 | */ 23 | public class VersionAck extends EmptyMessage { 24 | public VersionAck() { 25 | } 26 | 27 | // this is needed by the BitcoinSerializer 28 | public VersionAck(byte[] payload) { 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /bitherj/src/main/java/net/bither/bitherj/net/AbstractTimeoutHandler.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2013 Google Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package net.bither.bitherj.net; 18 | 19 | import java.util.Timer; 20 | import java.util.TimerTask; 21 | 22 | /** 23 | *

A base class which provides basic support for socket timeouts. It is used instead of integrating timeouts into the 24 | * NIO select thread both for simplicity and to keep code shared between NIO and blocking sockets as much as possible. 25 | *

26 | */ 27 | public abstract class AbstractTimeoutHandler { 28 | // TimerTask and timeout value which are added to a timer to kill the connection on timeout 29 | private TimerTask timeoutTask; 30 | private long timeoutMillis = 0; 31 | private boolean timeoutEnabled = true; 32 | 33 | // A timer which manages expiring channels as their timeouts occur (if configured). 34 | private static final Timer timeoutTimer = new Timer("AbstractTimeoutHandler timeouts", true); 35 | 36 | /** 37 | *

Enables or disables the timeout entirely. This may be useful if you want to store the timeout value but wish 38 | * to temporarily disable/enable timeouts.

39 | *

40 | *

The default is for timeoutEnabled to be true but timeoutMillis to be set to 0 (ie disabled).

41 | *

42 | *

This call will reset the current progress towards the timeout.

43 | */ 44 | public synchronized void setTimeoutEnabled(boolean timeoutEnabled) { 45 | this.timeoutEnabled = timeoutEnabled; 46 | resetTimeout(); 47 | } 48 | 49 | /** 50 | *

Sets the receive timeout to the given number of milliseconds, automatically killing the connection if no 51 | * messages are received for this long

52 | *

53 | *

A timeout of 0 is interpreted as no timeout.

54 | *

55 | *

The default is for timeoutEnabled to be true but timeoutMillis to be set to 0 (ie disabled).

56 | *

57 | *

This call will reset the current progress towards the timeout.

58 | */ 59 | public synchronized void setSocketTimeout(int timeoutMillis) { 60 | this.timeoutMillis = timeoutMillis; 61 | resetTimeout(); 62 | } 63 | 64 | /** 65 | * Resets the current progress towards timeout to 0. 66 | */ 67 | protected synchronized void resetTimeout() { 68 | if (timeoutTask != null) 69 | timeoutTask.cancel(); 70 | if (timeoutMillis == 0 || !timeoutEnabled) 71 | return; 72 | timeoutTask = new TimerTask() { 73 | @Override 74 | public void run() { 75 | timeoutOccurred(); 76 | } 77 | }; 78 | timeoutTimer.schedule(timeoutTask, timeoutMillis); 79 | } 80 | 81 | protected abstract void timeoutOccurred(); 82 | } 83 | -------------------------------------------------------------------------------- /bitherj/src/main/java/net/bither/bitherj/net/ClientConnectionManager.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2013 Google Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package net.bither.bitherj.net; 18 | 19 | import com.google.common.util.concurrent.Service; 20 | 21 | import java.net.SocketAddress; 22 | 23 | /** 24 | *

A generic interface for an object which keeps track of a set of open client connections, 25 | * creates new ones and 26 | * ensures they are serviced properly.

27 | *

28 | *

When the service is {@link com.google.common.util.concurrent.Service#stop()}ed, 29 | * all connections will be closed and 30 | * the appropriate connectionClosed() calls must be made.

31 | */ 32 | public interface ClientConnectionManager extends Service { 33 | /** 34 | * Creates a new connection to the given address, with the given parser used to handle 35 | * incoming data. 36 | */ 37 | void openConnection(SocketAddress serverAddress, StreamParser parser); 38 | 39 | /** 40 | * Gets the number of connected peers 41 | */ 42 | int getConnectedClientCount(); 43 | 44 | /** 45 | * Closes n peer connections 46 | */ 47 | void closeConnections(int n); 48 | } 49 | -------------------------------------------------------------------------------- /bitherj/src/main/java/net/bither/bitherj/net/MessageWriteTarget.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2013 Google Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package net.bither.bitherj.net; 18 | 19 | import java.io.IOException; 20 | 21 | /** 22 | * A target to which messages can be written/connection can be closed 23 | */ 24 | public interface MessageWriteTarget { 25 | /** 26 | * Writes the given bytes to the remote server. 27 | */ 28 | void writeBytes(byte[] message) throws IOException; 29 | 30 | /** 31 | * Closes the connection to the server, triggering the {@link StreamParser#connectionClosed()} 32 | * event on the network-handling thread where all callbacks occur. 33 | */ 34 | void closeConnection(); 35 | } 36 | -------------------------------------------------------------------------------- /bitherj/src/main/java/net/bither/bitherj/net/StreamParser.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2013 Google Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package net.bither.bitherj.net; 18 | 19 | import java.nio.ByteBuffer; 20 | 21 | /** 22 | * A generic handler which is used in {@link NioClientManager} to handle incoming 23 | * data streams. 24 | */ 25 | public interface StreamParser { 26 | /** 27 | * Called when the connection socket is closed 28 | */ 29 | void connectionClosed(); 30 | 31 | /** 32 | * Called when the connection socket is first opened 33 | */ 34 | void connectionOpened(); 35 | 36 | /** 37 | *

Called when new bytes are available from the remote end. This should only ever be called by the single 38 | * writeTarget associated with any given StreamParser, multiple callers will likely confuse implementations.

39 | *

40 | * Implementers/callers must follow the following conventions exactly: 41 | *

    42 | *
  • buff will start with its limit set to the position we can read to and its position set to the location we 43 | * will start reading at (always 0)
  • 44 | *
  • May read more than one message (recursively) if there are enough bytes available
  • 45 | *
  • Uses some internal buffering to store message which are larger (incl their length prefix) than buff's 46 | * capacity(), ie it is up to this method to ensure we dont run out of buffer space to decode the next message. 47 | *
  • 48 | *
  • buff will end with its limit the same as it was previously, and its position set to the position up to which 49 | * bytes have been read (the same as its return value)
  • 50 | *
  • buff must be at least the size of a Bitcoin header (incl magic bytes).
  • 51 | *
52 | * 53 | * @return The amount of bytes consumed which should not be provided again 54 | */ 55 | int receiveBytes(ByteBuffer buff) throws Exception; 56 | 57 | /** 58 | * Called when this parser is attached to an upstream write target (ie a low-level connection handler). This 59 | * writeTarget should be stored and used to close the connection or write data to the socket. 60 | */ 61 | void setWriteTarget(MessageWriteTarget writeTarget); 62 | 63 | /** 64 | * Returns the maximum message size of a message on the socket. This is used in calculating size of buffers to 65 | * allocate. 66 | */ 67 | int getMaxMessageSize(); 68 | } 69 | -------------------------------------------------------------------------------- /bitherj/src/main/java/net/bither/bitherj/qrcode/QRCodeTransportPage.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2014 http://Bither.net 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package net.bither.bitherj.qrcode; 18 | 19 | 20 | import net.bither.bitherj.utils.Utils; 21 | 22 | import java.util.List; 23 | 24 | public class QRCodeTransportPage { 25 | private int mCurrentPage; 26 | private int mSumPage; 27 | private String mContent; 28 | 29 | public int getCurrentPage() { 30 | return mCurrentPage; 31 | } 32 | 33 | public void setCurrentPage(int mCurrentPage) { 34 | this.mCurrentPage = mCurrentPage; 35 | } 36 | 37 | public int getSumPage() { 38 | return mSumPage; 39 | } 40 | 41 | public void setSumPage(int mSumPage) { 42 | this.mSumPage = mSumPage; 43 | } 44 | 45 | public String getContent() { 46 | return mContent; 47 | } 48 | 49 | public void setContent(String mContent) { 50 | this.mContent = mContent; 51 | } 52 | 53 | public static String qrCodeTransportToString( 54 | List qrCodeTransportPages) { 55 | String transportString = ""; 56 | for (QRCodeTransportPage qCodetTransportPage : qrCodeTransportPages) { 57 | if (!Utils.isEmpty(qCodetTransportPage.getContent())) { 58 | transportString = transportString 59 | + qCodetTransportPage.getContent(); 60 | } 61 | } 62 | return QRCodeUtil.decodeQrCodeString(transportString); 63 | } 64 | 65 | public static QRCodeTransportPage formatQrCodeTransport(String text) { 66 | if (!QRCodeUtil.verifyBitherQRCode(text)) { 67 | return null; 68 | } 69 | QRCodeTransportPage qrCodetTransportPage = new QRCodeTransportPage(); 70 | String[] strArray = QRCodeUtil.splitString(text); 71 | if (Utils.isInteger(strArray[0]) && Utils.isInteger(strArray[1])) { 72 | int length = strArray[0].length() + strArray[1].length() + 2; 73 | qrCodetTransportPage.setSumPage(Integer.valueOf(strArray[0]) + 1); 74 | qrCodetTransportPage.setCurrentPage(Integer.valueOf(strArray[1])); 75 | qrCodetTransportPage.setContent(text.substring(length)); 76 | } else { 77 | qrCodetTransportPage.setContent(text); 78 | } 79 | return qrCodetTransportPage; 80 | } 81 | 82 | 83 | } 84 | -------------------------------------------------------------------------------- /bitherj/src/main/java/net/bither/bitherj/qrcode/SaltForQRCode.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2014 http://Bither.net 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package net.bither.bitherj.qrcode; 18 | 19 | import net.bither.bitherj.crypto.KeyCrypterScrypt; 20 | 21 | public class SaltForQRCode { 22 | 23 | public static final int IS_COMPRESSED_FLAG = 1; 24 | public static final int IS_FROMXRANDOM_FLAG = 2; 25 | 26 | private byte[] salt; 27 | private boolean isFromXRandom = false; 28 | private boolean isCompressed = true; 29 | private byte[] qrCodeSalt; 30 | 31 | public SaltForQRCode(byte[] qrCodeSalt) { 32 | 33 | this.qrCodeSalt = qrCodeSalt; 34 | salt = new byte[KeyCrypterScrypt.SALT_LENGTH]; 35 | isCompressed = true; 36 | isFromXRandom = false; 37 | if (qrCodeSalt.length == KeyCrypterScrypt.SALT_LENGTH) { 38 | salt = qrCodeSalt; 39 | } else { 40 | System.arraycopy(qrCodeSalt, 1, salt, 0, salt.length); 41 | isCompressed = (((int) qrCodeSalt[0]) & IS_COMPRESSED_FLAG) == IS_COMPRESSED_FLAG; 42 | isFromXRandom = (((int) qrCodeSalt[0]) & IS_FROMXRANDOM_FLAG) == IS_FROMXRANDOM_FLAG; 43 | } 44 | } 45 | 46 | public SaltForQRCode(byte[] salt, boolean isCompressed, boolean isFromXRandom) { 47 | this.salt = salt; 48 | this.isFromXRandom = isFromXRandom; 49 | this.isCompressed = isCompressed; 50 | qrCodeSalt = new byte[KeyCrypterScrypt.SALT_LENGTH + 1]; 51 | if (salt.length == KeyCrypterScrypt.SALT_LENGTH) { 52 | int flag = 0; 53 | if (isCompressed) { 54 | flag += IS_COMPRESSED_FLAG; 55 | } 56 | if (isFromXRandom) { 57 | flag += IS_FROMXRANDOM_FLAG; 58 | } 59 | qrCodeSalt[0] = (byte) flag; 60 | System.arraycopy(salt, 0, qrCodeSalt, 1, salt.length); 61 | 62 | } else { 63 | System.arraycopy(salt, 0, qrCodeSalt, 0, salt.length); 64 | } 65 | 66 | } 67 | 68 | public byte[] getSalt() { 69 | return salt; 70 | } 71 | 72 | public boolean isFromXRandom() { 73 | return isFromXRandom; 74 | } 75 | 76 | public boolean isCompressed() { 77 | return isCompressed; 78 | } 79 | 80 | public byte[] getQrCodeSalt() { 81 | return qrCodeSalt; 82 | } 83 | 84 | } 85 | -------------------------------------------------------------------------------- /bitherj/src/main/java/net/bither/bitherj/runnable/EditPasswordThread.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2014 http://Bither.net 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package net.bither.bitherj.runnable; 18 | 19 | import net.bither.bitherj.crypto.SecureCharSequence; 20 | import net.bither.bitherj.db.AbstractDb; 21 | 22 | public class EditPasswordThread extends Thread { 23 | 24 | 25 | public static interface EditPasswordListener { 26 | public void onSuccess(); 27 | 28 | public void onFailed(); 29 | 30 | } 31 | 32 | private SecureCharSequence oldPassword; 33 | private SecureCharSequence newPassword; 34 | private EditPasswordListener listener; 35 | 36 | public EditPasswordThread(SecureCharSequence oldPassword, SecureCharSequence newPassword, 37 | EditPasswordListener listener) { 38 | this.oldPassword = oldPassword; 39 | this.newPassword = newPassword; 40 | this.listener = listener; 41 | } 42 | 43 | @Override 44 | public void run() { 45 | final boolean result = editPassword(oldPassword, newPassword); 46 | oldPassword.wipe(); 47 | newPassword.wipe(); 48 | if (listener != null) { 49 | if (result) { 50 | listener.onSuccess(); 51 | } else { 52 | listener.onFailed(); 53 | } 54 | } 55 | 56 | } 57 | 58 | public boolean editPassword(SecureCharSequence oldPassword, SecureCharSequence newPassword) { 59 | try { 60 | return AbstractDb.addressProvider.changePassword(oldPassword, newPassword); 61 | } catch (Exception e) { 62 | e.printStackTrace(); 63 | return false; 64 | } 65 | } 66 | 67 | } 68 | -------------------------------------------------------------------------------- /bitherj/src/main/java/net/bither/bitherj/utils/CharSequenceUtil.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2014 http://Bither.net 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package net.bither.bitherj.utils; 18 | 19 | public class CharSequenceUtil { 20 | 21 | public static int getRating(CharSequence password) { 22 | if (password == null || password.length() < 6) { 23 | return 0; 24 | } 25 | int strength = 0; 26 | if (password.length() > 9) { 27 | strength++; 28 | } 29 | int digitCount = getDigitCount(password); 30 | int symbolCount = getSymbolCount(password); 31 | boolean upperAndLower = bothUpperAndLower(password); 32 | if (digitCount > 0 && digitCount != password.length()) { 33 | strength++; 34 | } 35 | if (symbolCount > 0 && symbolCount != password.length()) { 36 | strength++; 37 | } 38 | if (upperAndLower) { 39 | strength++; 40 | } 41 | return strength; 42 | } 43 | 44 | private static boolean bothUpperAndLower(CharSequence password) { 45 | if (password == null || password.length() == 0) { 46 | return false; 47 | } 48 | boolean upper = false; 49 | boolean lower = false; 50 | int length = password.length(); 51 | for (int i = 0; 52 | i < length; 53 | i++) { 54 | char c = password.charAt(i); 55 | if (!upper) { 56 | upper = Character.isUpperCase(c); 57 | } 58 | if (!lower) { 59 | lower = Character.isLowerCase(c); 60 | } 61 | if (upper && lower) { 62 | break; 63 | } 64 | } 65 | return upper && lower; 66 | } 67 | 68 | private static int getDigitCount(CharSequence password) { 69 | if (password == null || password.length() == 0) { 70 | return 0; 71 | } 72 | int numDigits = 0; 73 | int length = password.length(); 74 | for (int i = 0; 75 | i < length; 76 | i++) { 77 | if (Character.isDigit(password.charAt(i))) { 78 | numDigits++; 79 | } 80 | } 81 | return numDigits; 82 | } 83 | 84 | private static int getSymbolCount(CharSequence password) { 85 | if (password == null || password.length() == 0) { 86 | return 0; 87 | } 88 | int numSymbol = 0; 89 | int length = password.length(); 90 | for (int i = 0; 91 | i < length; 92 | i++) { 93 | char c = password.charAt(i); 94 | if (!Character.isLetter(c) && !Character.isDigit(c)) { 95 | numSymbol++; 96 | } 97 | } 98 | return numSymbol; 99 | } 100 | } 101 | -------------------------------------------------------------------------------- /bitherj/src/main/java/net/bither/bitherj/utils/DynamicWire.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2014 http://Bither.net 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | 18 | package net.bither.bitherj.utils; 19 | 20 | public interface DynamicWire { 21 | V get(); 22 | } 23 | -------------------------------------------------------------------------------- /bitherj/src/main/java/net/bither/bitherj/utils/InventoryItem.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2011 Google Inc. 3 | *

4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | *

8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | *

10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package net.bither.bitherj.utils; 18 | 19 | import java.util.Arrays; 20 | 21 | public class InventoryItem { 22 | 23 | /** 24 | * 4 byte uint32 type field + 32 byte hash 25 | */ 26 | public static final int MESSAGE_LENGTH = 36; 27 | 28 | public enum Type { 29 | Error, 30 | Transaction, 31 | Block, 32 | FilteredBlock 33 | } 34 | 35 | public final Type type; 36 | public final byte[] hash; 37 | 38 | public InventoryItem(Type type, byte[] hash) { 39 | this.type = type; 40 | this.hash = hash; 41 | } 42 | 43 | 44 | public String toString() { 45 | return type.toString() + ": " + hash; 46 | } 47 | 48 | public int hashCode() { 49 | return hash.hashCode() + type.ordinal(); 50 | } 51 | 52 | public boolean equals(Object o) { 53 | return o instanceof InventoryItem && 54 | ((InventoryItem) o).type == this.type && Arrays.equals(((InventoryItem) o).hash, 55 | this.hash); 56 | } 57 | } 58 | -------------------------------------------------------------------------------- /bitherj/src/main/java/net/bither/bitherj/utils/UnitUtil.java: -------------------------------------------------------------------------------- 1 | /* 2 | * 3 | * * Copyright 2014 http://Bither.net 4 | * * 5 | * * Licensed under the Apache License, Version 2.0 (the "License"); 6 | * * you may not use this file except in compliance with the License. 7 | * * You may obtain a copy of the License at 8 | * * 9 | * * http://www.apache.org/licenses/LICENSE-2.0 10 | * * 11 | * * Unless required by applicable law or agreed to in writing, software 12 | * * distributed under the License is distributed on an "AS IS" BASIS, 13 | * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * * See the License for the specific language governing permissions and 15 | * * limitations under the License. 16 | * 17 | */ 18 | 19 | package net.bither.bitherj.utils; 20 | 21 | /** 22 | * Created by songchenwen on 14-11-12. 23 | */ 24 | public class UnitUtil { 25 | public static enum BitcoinUnit { 26 | BTC(100000000), bits(100); 27 | 28 | public long satoshis; 29 | 30 | BitcoinUnit(long satoshis) { 31 | this.satoshis = satoshis; 32 | } 33 | } 34 | 35 | public static String formatValue(final long value, BitcoinUnit unit) { 36 | String sign = value < 0 ? "-" : ""; 37 | long absValue = Math.abs(value); 38 | long coins = absValue / unit.satoshis; 39 | long satoshis = absValue % unit.satoshis; 40 | String strCoins = Long.toString(coins); 41 | String strSatoshis = ""; 42 | strSatoshis = Long.toString(satoshis + unit.satoshis); 43 | strSatoshis = strSatoshis.substring(1, strSatoshis.length()); 44 | if (unit.satoshis > Math.pow(10, 2)) { 45 | strSatoshis = strSatoshis.replaceFirst("[0]{1," + Integer.toString((int) Math.floor 46 | (Math.log10(unit.satoshis) - 2)) + "}$", ""); 47 | } 48 | return sign + strCoins + (strSatoshis.length() > 0 ? "." : "") + strSatoshis; 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /bitherj/src/test/java/net/bither/bitherj/core/AddressTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2014 http://Bither.net 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package net.bither.bitherj.core; 18 | 19 | import net.bither.bitherj.crypto.DumpedPrivateKey; 20 | import net.bither.bitherj.crypto.ECKey; 21 | import net.bither.bitherj.exception.AddressFormatException; 22 | 23 | import org.junit.Test; 24 | 25 | import static org.junit.Assert.*; 26 | 27 | public class AddressTest { 28 | @Test 29 | public void testAddress() { 30 | try { 31 | DumpedPrivateKey dumpedPrivateKey = new DumpedPrivateKey("L4rK1yDtCWekvXuE6oXD9jCYfFNV2cWRpVuPLBcCU2z8TrisoyY1"); 32 | ECKey ecKey = dumpedPrivateKey.getKey(); 33 | String addressStr = ecKey.toAddress(); 34 | assertEquals(ecKey.toAddress(), "1F3sAm6ZtwLAUnj7d38pGFxtP3RVEvtsbV"); 35 | } catch (AddressFormatException e) { 36 | e.printStackTrace(); 37 | } 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /bitherj/src/test/java/net/bither/bitherj/core/BlockTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2014 http://Bither.net 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package net.bither.bitherj.core; 18 | 19 | import net.bither.bitherj.db.AbstractDb; 20 | import net.bither.bitherj.utils.Utils; 21 | 22 | import org.junit.Test; 23 | 24 | import java.util.Arrays; 25 | 26 | import static org.junit.Assert.assertEquals; 27 | import static org.junit.Assert.assertTrue; 28 | 29 | public class BlockTest { 30 | @Test 31 | public void testText() { 32 | assertEquals("", ""); 33 | Block block = new Block(2, "00000000000000003711b624fbde8c77d4c7e25334cfa8bc176b7248ca67b24b", "d1ce608b0e83f5b0c134d27ea6952fc55bc68b5ccf0490bbb47ea1906a7075d0", 1407474112 34 | , 406305378, 2798738616L, 314496); 35 | String str = Utils.bytesToHexString(Utils.reverseBytes(block.getBlockHash())); 36 | assertEquals("000000000000000030e597a72386c512d830b08ecc70b254f46033fd06f2bf93", str); 37 | 38 | AbstractDb.blockProvider.addBlock(block); 39 | Block testBlock = AbstractDb.blockProvider. 40 | getBlock(Utils.reverseBytes(Utils.hexStringToByteArray( 41 | "000000000000000030e597a72386c512d830b08ecc70b254f46033fd06f2bf93"))); 42 | 43 | assertEquals(Utils.bytesToHexString(testBlock.getBlockHash()), Utils.bytesToHexString(block.getBlockHash())); 44 | } 45 | 46 | @Test 47 | public void testBlockConstructor() { 48 | Block block = new Block(1, "0000000000000000000000000000000000000000000000000000000000000000" 49 | , "4a5e1e4baab89f3a32518a88c31bc87f618f76673e2cc77ab2127b7afdeda33b", 1231006505 50 | , 486604799, 2083236893, 0); 51 | byte[] expectBlockHash = Utils.reverseBytes(Utils.hexStringToByteArray("000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f")); 52 | assertTrue(Arrays.equals(block.getBlockHash(), expectBlockHash)); 53 | Block block1 = new Block(block.bitcoinSerialize()); 54 | assertTrue(Arrays.equals(block1.getBlockHash(), expectBlockHash)); 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /bitherj/src/test/java/net/bither/bitherj/core/MultisigAddressTest.java: -------------------------------------------------------------------------------- 1 | package net.bither.bitherj.core; 2 | 3 | import net.bither.bitherj.utils.Utils; 4 | 5 | import org.junit.Test; 6 | 7 | import static org.junit.Assert.assertArrayEquals; 8 | import static org.junit.Assert.assertEquals; 9 | 10 | /** 11 | * Created by songchenwen on 15/1/6. 12 | */ 13 | public class MultisigAddressTest { 14 | // first test case comes from https://gist.github.com/gavinandresen/3966071 15 | TestCase[] cases = new TestCase[]{ 16 | new TestCase(new HDMAddress.Pubs( 17 | Utils.hexStringToByteArray("0491bba2510912a5bd37da1fb5b1673010e43d2c6d812c514e91bfa9f2eb129e1c183329db55bd868e209aac2fbc02cb33d98fe74bf23f0c235d6126b1d8334f86"), 18 | Utils.hexStringToByteArray("04865c40293a680cb9c020e7b1e106d8c1916d3cef99aa431a56d253e69256dac09ef122b1a986818a7cb624532f062c1d1f8722084861c5c3291ccffef4ec6874"), 19 | Utils.hexStringToByteArray("048d2455d2403e08708fc1f556002f1b6cd83f992d085097f9974ab08a28838f07896fbab08f39495e15fa6fad6edbfb1e754e35fa1c7844c41f322a1863d46213"), 20 | 0), 21 | "3QJmV3qfvL9SuYo34YihAf3sRCW3qSinyC", 22 | "52410491bba2510912a5bd37da1fb5b1673010e43d2c6d812c514e91bfa9f2eb129e1c183329db55bd868e209aac2fbc02cb33d98fe74bf23f0c235d6126b1d8334f864104865c40293a680cb9c020e7b1e106d8c1916d3cef99aa431a56d253e69256dac09ef122b1a986818a7cb624532f062c1d1f8722084861c5c3291ccffef4ec687441048d2455d2403e08708fc1f556002f1b6cd83f992d085097f9974ab08a28838f07896fbab08f39495e15fa6fad6edbfb1e754e35fa1c7844c41f322a1863d4621353ae") 23 | }; 24 | 25 | @Test 26 | public void testMultisigAddress() { 27 | for (int i = 0; i < cases.length; i++) { 28 | TestCase c = cases[i]; 29 | assertArrayEquals("script program not match", c.script, c.pubs.getMultiSigScript().getProgram()); 30 | System.out.println("\nscript program match: " + Utils.bytesToHexString(c.script)); 31 | String a = c.pubs.getAddress(); 32 | assertEquals("address not match", a, c.address); 33 | System.out.println("\naddress match: " + a); 34 | } 35 | } 36 | 37 | private static final class TestCase { 38 | HDMAddress.Pubs pubs; 39 | String address; 40 | byte[] script; 41 | 42 | TestCase(HDMAddress.Pubs pubs, String address, String script) { 43 | this.pubs = pubs; 44 | this.address = address; 45 | this.script = Utils.hexStringToByteArray(script); 46 | } 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /bitherj/src/test/java/net/bither/bitherj/core/PeerManagerTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2014 http://Bither.net 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package net.bither.bitherj.core; 18 | 19 | import org.junit.Test; 20 | 21 | public class PeerManagerTest { 22 | 23 | @Test 24 | public void testNormal() throws InterruptedException { 25 | Block block = new Block(2, "00000000000000000ee9b585e0a707347d7c80f3a905f48fa32d448917335366", "4d60e37c7086096e85c11324d70112e61e74fc38a5c5153587a0271fd22b65c5", 1400928750 26 | , 409544770l, 4079278699l, 302400); 27 | BlockChain.getInstance().addSPVBlock(block); 28 | PeerManager.instance().start(); 29 | 30 | while (true) { 31 | Thread.sleep(1000); 32 | } 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /bitherj/src/test/java/net/bither/bitherj/core/StringTest.java: -------------------------------------------------------------------------------- 1 | package net.bither.bitherj.core; 2 | 3 | import net.bither.bitherj.qrcode.QRCodeUtil; 4 | 5 | import org.junit.Test; 6 | 7 | /** 8 | * Created by nn on 15/1/23. 9 | */ 10 | public class StringTest { 11 | @Test 12 | public void testString() { 13 | boolean result = 14 | QRCodeUtil.verifyBitherQRCode("-E0B56EB20152755D3287BEBAAB612BB4049E736A44301729D878D54CA0912DF84F88BBDBE7330CA412FF700991BE8FE1/989A374A3B0F301808654DCD6264F368/01f120397c1017c628"); 15 | if (result) { 16 | 17 | } else { 18 | 19 | } 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /bitherj/src/test/java/net/bither/bitherj/core/TestImplAbstractApp.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2014 http://Bither.net 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package net.bither.bitherj.core; 18 | 19 | import net.bither.bitherj.AbstractApp; 20 | import net.bither.bitherj.BitherjSettings; 21 | import net.bither.bitherj.ISetting; 22 | import net.bither.bitherj.NotificationService; 23 | import net.bither.bitherj.api.TrustCert; 24 | import net.bither.bitherj.qrcode.QRCodeUtil; 25 | 26 | import org.apache.http.client.CookieStore; 27 | import org.apache.http.impl.client.BasicCookieStore; 28 | 29 | import java.io.File; 30 | 31 | public class TestImplAbstractApp extends AbstractApp { 32 | private CookieStore cookieStore = new BasicCookieStore(); 33 | 34 | @Override 35 | public TrustCert initTrustCert() { 36 | return null; 37 | } 38 | 39 | @Override 40 | public ISetting initSetting() { 41 | return new ISetting() { 42 | @Override 43 | public BitherjSettings.AppMode getAppMode() { 44 | return BitherjSettings.AppMode.HOT; 45 | } 46 | 47 | @Override 48 | public boolean getBitherjDoneSyncFromSpv() { 49 | return true; 50 | } 51 | 52 | @Override 53 | public void setBitherjDoneSyncFromSpv(boolean isDone) { 54 | // AppSharedPreference.getInstance().setBitherjDoneSyncFromSpv(isDone); 55 | } 56 | 57 | @Override 58 | public BitherjSettings.TransactionFeeMode getTransactionFeeMode() { 59 | return BitherjSettings.TransactionFeeMode.Low; 60 | } 61 | 62 | @Override 63 | public File getPrivateDir(String dirName) { 64 | File file = new File("test/wallet"); 65 | if (!file.exists()) { 66 | file.mkdirs(); 67 | } 68 | return file; 69 | } 70 | 71 | @Override 72 | public boolean isApplicationRunInForeground() { 73 | 74 | return true; 75 | } 76 | 77 | @Override 78 | public QRCodeUtil.QRQuality getQRQuality() { 79 | return QRCodeUtil.QRQuality.Normal; 80 | } 81 | 82 | @Override 83 | public boolean getDownloadSpvFinish() { 84 | return true; 85 | } 86 | 87 | @Override 88 | public void setDownloadSpvFinish(boolean finish) { 89 | // AppSharedPreference.getInstance().setDownloadSpvFinish(finish); 90 | } 91 | 92 | @Override 93 | public CookieStore getCookieStore() { 94 | return cookieStore; 95 | } 96 | 97 | 98 | }; 99 | } 100 | 101 | @Override 102 | public NotificationService initNotification() { 103 | return null; 104 | } 105 | } 106 | -------------------------------------------------------------------------------- /bitherj/src/test/java/net/bither/bitherj/core/TxTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2014 http://Bither.net 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package net.bither.bitherj.core; 18 | 19 | import net.bither.bitherj.db.AbstractDb; 20 | import net.bither.bitherj.utils.Utils; 21 | 22 | import org.junit.Test; 23 | 24 | import java.util.Arrays; 25 | import java.util.Date; 26 | 27 | import static org.junit.Assert.*; 28 | 29 | public class TxTest { 30 | @Test 31 | public void testDb() { 32 | Tx tx = new Tx(); 33 | byte[] txHash = Utils.reverseBytes( 34 | Utils.hexStringToByteArray("f8a8335594d4c883f367e003cb3832015640f24714b48bd21cf6fbe84a617dfe")); 35 | tx.setTxHash(Utils.reverseBytes( 36 | Utils.hexStringToByteArray("f8a8335594d4c883f367e003cb3832015640f24714b48bd21cf6fbe84a617dfe"))); 37 | tx.setBlockNo(304942); 38 | tx.setTxTime((int) new Date().getTime() / 1000); 39 | tx.setTxVer(1); 40 | In inPut = new In(); 41 | inPut.setPrevTxHash(Utils.reverseBytes( 42 | Utils.hexStringToByteArray("d7f4efff7aeaffc1630dd3653e923a233fd463f9dc7dd4f97bb5cbf0cf99e56a"))); 43 | inPut.setInSn(0); 44 | inPut.setTxHash(txHash); 45 | inPut.setInSequence(1); 46 | inPut.setInSignature(txHash); 47 | 48 | tx.addInput(inPut); 49 | Out out = new Out(); 50 | out.setTxHash(txHash); 51 | out.setOutSn(0); 52 | out.setOutValue(3400); 53 | out.setOutScript(Utils.hexStringToByteArray("76a914abceaddc7d791f749671c17dfa36e9b17a4b055588ac")); 54 | out.setOutStatus(Out.OutStatus.spent); 55 | out.setOutAddress("test"); 56 | tx.addOutput(out); 57 | AbstractDb.txProvider.add(tx); 58 | Tx testTx = AbstractDb.txProvider.getTxDetailByTxHash(txHash); 59 | assertEquals(Utils.bytesToHexString(tx.getTxHash()), Utils.bytesToHexString(testTx.getTxHash())); 60 | } 61 | 62 | @Test 63 | public void testConstructor() { 64 | byte[] rawTx = Utils.hexStringToByteArray("0100000001bdc0141fe3e5c2223a6d26a95acbf791042d93f9d9b8b38f133bf7adb5c1e293010000006a47304402202214770c0f5a9261190337273219a108132a4bc987c745db8dd6daded34b0dcb0220573de1d973166024b8342d6b6fef2a864a06cceee6aee13a910e5d8df465ed2a01210382b259804ad8d88b96a23222e24dd5a130d39588e78960c9e9b48a5b49943649ffffffff02a0860100000000001976a91479a7bf0bba8359561d4dab457042d7b632d5e64188ac605b0300000000001976a914b036c529faeca8040232cc4bd5918e709e90c4ff88ac00000000"); 65 | Tx tx = new Tx(rawTx); 66 | byte[] txBytes = tx.bitcoinSerialize(); 67 | assertTrue(Arrays.equals(rawTx, txBytes)); 68 | byte[] exceptTxHash = Utils.reverseBytes(Utils.hexStringToByteArray("584985ca8a9ed57987da36ea3d13fe05a7c498f2098ddeb6c8d0f3214067640c")); 69 | byte[] txHash = tx.getTxHash(); 70 | for (Out out : tx.getOuts()) { 71 | String outAddress = out.getOutAddress(); 72 | } 73 | assertTrue(Arrays.equals(exceptTxHash, txHash)); 74 | } 75 | } 76 | -------------------------------------------------------------------------------- /bitherj/src/test/java/net/bither/bitherj/core/UtilsTest.java: -------------------------------------------------------------------------------- 1 | package net.bither.bitherj.core; 2 | 3 | import net.bither.bitherj.utils.Utils; 4 | 5 | import org.junit.Test; 6 | 7 | import static org.junit.Assert.assertFalse; 8 | import static org.junit.Assert.assertTrue; 9 | 10 | public class UtilsTest { 11 | @Test 12 | public void testPassword() { 13 | String password = "0aA`~!@#$%^&*()_-+={}[]|:;\\\"'<>,.?/"; 14 | boolean validP = Utils.validPassword(password); 15 | assertTrue(validP); 16 | password = "ASDF简繁"; 17 | assertFalse(Utils.validPassword(password)); 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /bitherj/src/test/java/net/bither/bitherj/core/https/HttpsTest.java: -------------------------------------------------------------------------------- 1 | package net.bither.bitherj.core.https; 2 | 3 | import net.bither.bitherj.api.ConnectHttps; 4 | import net.bither.bitherj.api.TrustCert; 5 | 6 | import org.junit.Test; 7 | 8 | import java.io.FileNotFoundException; 9 | import java.io.IOException; 10 | import java.io.InputStream; 11 | 12 | public class HttpsTest { 13 | private static final String TrustStorePath = "bithertruststore.jks"; 14 | private static final String TrustStorePassword = "bither"; 15 | 16 | @Test 17 | public void testCreateHDAddress() throws Exception { 18 | trust(); 19 | try { 20 | String getRespon = ConnectHttps.httpGet("https://hdm.bither.net/api/v1/1C6FiRktL3UPd4sywhyU5CYSeLdKhvHxhR/hdm/password"); 21 | System.out.println(getRespon); 22 | } catch (IOException e) { 23 | e.printStackTrace(); 24 | } 25 | } 26 | 27 | public static final void trust() throws FileNotFoundException { 28 | InputStream stream = HttpsTest.class.getResourceAsStream(TrustStorePath); 29 | if (stream == null) { 30 | throw new FileNotFoundException(TrustStorePath); 31 | } 32 | ConnectHttps.trustCerts(new TrustCert(stream, TrustStorePassword.toCharArray(), "jks")); 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /bitherj/src/test/java/net/bither/bitherj/crypto/MultisigTest.java: -------------------------------------------------------------------------------- 1 | package net.bither.bitherj.crypto; 2 | 3 | import net.bither.bitherj.script.Script; 4 | import net.bither.bitherj.script.ScriptBuilder; 5 | import net.bither.bitherj.utils.Utils; 6 | 7 | import org.junit.Test; 8 | 9 | import java.util.ArrayList; 10 | import java.util.List; 11 | 12 | import static org.junit.Assert.assertEquals; 13 | 14 | /** 15 | * Created by zhouqi on 15/1/8. 16 | */ 17 | public class MultisigTest { 18 | @Test 19 | public void testAddress() { 20 | String pubHot = "026e3f39cd82606a3aa0d9c8194cf516b98ee51c1107e6c7f334cde22b5059e928"; 21 | String pubCold = "034d490441de1cc4a8f1e7192083583c16e513b3b550c8410500db7853fd1fa5fe"; 22 | String pubRemote = "0255b72bc52dfa0ffc40742b1a3eb01858714341c1f72bc1f8fdc731098323e96e"; 23 | String address = "3K2Cbzxfoxey8cbq1w2YutLzhvxByxvNxy"; 24 | 25 | ECKey keyHot = new ECKey(null, Utils.hexStringToByteArray(pubHot)); 26 | ECKey keyCold = new ECKey(null, Utils.hexStringToByteArray(pubCold)); 27 | ECKey keyRemote = new ECKey(null, Utils.hexStringToByteArray(pubRemote)); 28 | List pubKeyList = new ArrayList(); 29 | pubKeyList.add(keyHot.getPubKey()); 30 | pubKeyList.add(keyCold.getPubKey()); 31 | pubKeyList.add(keyRemote.getPubKey()); 32 | 33 | Script script = ScriptBuilder.createMultiSigOutputScript(2, pubKeyList); 34 | String multisigAddress = Utils.toP2SHAddress(Utils.sha256hash160(script.getProgram())); 35 | 36 | assertEquals(address, multisigAddress); 37 | 38 | pubHot = "033dc6dcf7d90cb8f4ee3adbc87bf55c700d6c32a74800af6de6e1af57f46bfc41"; 39 | pubCold = "025ed1f76ae3fc0cb84782131594020e885a060daf9f55c199fdb299e7169779b9"; 40 | pubRemote = "0378b509c95fd7aa30dc82c4bbe8b84dcb8bb7d7224d891cce7ccf454c79527b5d"; 41 | address = "3ELN8yYSGoz4fTy8HSbfgLRoDWBU6p9zev"; 42 | 43 | keyHot = new ECKey(null, Utils.hexStringToByteArray(pubHot)); 44 | keyCold = new ECKey(null, Utils.hexStringToByteArray(pubCold)); 45 | keyRemote = new ECKey(null, Utils.hexStringToByteArray(pubRemote)); 46 | pubKeyList = new ArrayList(); 47 | pubKeyList.add(keyHot.getPubKey()); 48 | pubKeyList.add(keyCold.getPubKey()); 49 | pubKeyList.add(keyRemote.getPubKey()); 50 | 51 | script = ScriptBuilder.createMultiSigOutputScript(2, pubKeyList); 52 | multisigAddress = Utils.toP2SHAddress(Utils.sha256hash160(script.getProgram())); 53 | 54 | assertEquals(address, multisigAddress); 55 | 56 | pubHot = "03d29143a6b76d393075d620df9cf80bbb5eaceb2e2b57e5cc4704a6eb3c125a8d"; 57 | pubCold = "03f7d2d484d903fa498d6069009e77ed9ad0842947a7a58441f9406a4728ae2240"; 58 | pubRemote = "02a5fc2584b879fa5a7b04e67d7ab8abb3b08d7981f9f24b03e9353355162c2e04"; 59 | address = "34RgHSRfg3P7FSk3YBbcWnHaMWxapMtrWf"; 60 | 61 | keyHot = new ECKey(null, Utils.hexStringToByteArray(pubHot)); 62 | keyCold = new ECKey(null, Utils.hexStringToByteArray(pubCold)); 63 | keyRemote = new ECKey(null, Utils.hexStringToByteArray(pubRemote)); 64 | pubKeyList = new ArrayList(); 65 | pubKeyList.add(keyHot.getPubKey()); 66 | pubKeyList.add(keyCold.getPubKey()); 67 | pubKeyList.add(keyRemote.getPubKey()); 68 | 69 | script = ScriptBuilder.createMultiSigOutputScript(2, pubKeyList); 70 | multisigAddress = Utils.toP2SHAddress(Utils.sha256hash160(script.getProgram())); 71 | 72 | assertEquals(address, multisigAddress); 73 | } 74 | } 75 | -------------------------------------------------------------------------------- /bitherj/src/test/java/net/bither/bitherj/crypto/PasswordSeedTest.java: -------------------------------------------------------------------------------- 1 | package net.bither.bitherj.crypto; 2 | 3 | import org.junit.Test; 4 | 5 | public class PasswordSeedTest { 6 | 7 | @Test 8 | public void testPasswordTest() { 9 | String keyString = "0077b3dad72529632b0728128cba3e70edea7b047b/548BA5896EBFF2DEB66E8D697987222E9B3C7AEE0C6B7580235FCEE1FD3D1119408EB3927DED776F56231AD0FE8AB912/DBE9FAE06805DB4E91C7448B1F7A26F1/014f626c0177990ca5"; 10 | PasswordSeed passwordSeed = new PasswordSeed(keyString); 11 | boolean reslut = passwordSeed.checkPassword("123456"); 12 | if (reslut) { 13 | System.out.println("checkPassword pass"); 14 | } else { 15 | System.out.println("checkPassword no pass"); 16 | } 17 | 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /bitherj/src/test/java/net/bither/bitherj/script/ScriptChunkTest.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2014 Andreas Schildbach 3 | *

4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | *

8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | *

10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package net.bither.bitherj.script; 18 | 19 | import org.junit.Test; 20 | 21 | import static net.bither.bitherj.script.ScriptOpCodes.OP_PUSHDATA1; 22 | import static net.bither.bitherj.script.ScriptOpCodes.OP_PUSHDATA2; 23 | import static net.bither.bitherj.script.ScriptOpCodes.OP_PUSHDATA4; 24 | import static org.junit.Assert.*; 25 | 26 | public class ScriptChunkTest { 27 | 28 | @Test 29 | public void testShortestPossibleDataPush() { 30 | assertTrue("empty push", new ScriptBuilder().data(new byte[0]).build().getChunks().get(0) 31 | .isShortestPossiblePushData()); 32 | 33 | for (byte i = -1; i < 127; i++) 34 | assertTrue("push of single byte " + i, new ScriptBuilder().data(new byte[]{i}).build().getChunks() 35 | .get(0).isShortestPossiblePushData()); 36 | 37 | for (int len = 2; len < Script.MAX_SCRIPT_ELEMENT_SIZE; len++) 38 | assertTrue("push of " + len + " bytes", new ScriptBuilder().data(new byte[len]).build().getChunks().get(0) 39 | .isShortestPossiblePushData()); 40 | 41 | // non-standard chunks 42 | for (byte i = 1; i <= 16; i++) 43 | assertFalse("push of smallnum " + i, new ScriptChunk(1, new byte[]{i}).isShortestPossiblePushData()); 44 | assertFalse("push of 75 bytes", new ScriptChunk(OP_PUSHDATA1, new byte[75]).isShortestPossiblePushData()); 45 | assertFalse("push of 255 bytes", new ScriptChunk(OP_PUSHDATA2, new byte[255]).isShortestPossiblePushData()); 46 | assertFalse("push of 65535 bytes", new ScriptChunk(OP_PUSHDATA4, new byte[65535]).isShortestPossiblePushData()); 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /bitherj/src/test/resources/net/bither/bitherj/core/https/bithertruststore.jks: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bither/bitherj/1dff0be6b7622ffc8d1a12f157c76b11ed2e9ef0/bitherj/src/test/resources/net/bither/bitherj/core/https/bithertruststore.jks -------------------------------------------------------------------------------- /doc/REASON.SecureCharSequence.md: -------------------------------------------------------------------------------- 1 | # "Sensitive" Information in Memory 2 | 3 | The informations are different! 4 | Although we can transform both the bitcoin private key and the transaction data to pure text, they are totally different. The private key is vital, and we should keep it safe as possible as we can, but the transaction data does not matter. 5 | 6 | So we should use and store the informations in different ways and security levels, even in memory. 7 | 8 | For example, in Java, we usually write codes like this: 9 | String password = "bither.net"; 10 | 11 | After finish using the password, we can also set the password to other value or even null. 12 | password = "8btc.com"; 13 | password = null; 14 | 15 | Normally these codes are ok in many circumstance. But when we want to store "sensitive" informations (private keys, passwords...), String is not a safe choice, because : 16 | > Objects of type String are immutable, i.e., there are no methods defined that allow you to change (overwrite) or zero out the contents of a String after usage. This feature makes [String objects unsuitable for storing security sensitive information such as user passwords](http://docs.oracle.com/javase/1.5.0/docs/guide/security/jce/JCERefGuide.html#PBEEx). 17 | 18 | That means, although you can set the password to any values ("bitcoin.org", "bitcointalk.org"....), all strings ("bither.net", "8btc.com", "bitcoin.org", "bitcointalk.org") will stay in memory. 19 | 20 | Normally it is not so "dangerous", because it is difficult to "steal" information from your memory. Unless you faced another incident like "OpenSSL HeartBleed". Hackers may use this kind of flaws to steal data from your memory. If there are "sensitive" information in those data (e.g. private keys), BOOM! 21 | 22 | "Normally it's ok, the odds are rare" is not the reason of writing insecured codes. 23 | 24 | What is the correct way to do such things? 25 | 26 | You should use `CharSequence` (`Char Array`), and after finish using the sensitive information, using loop to overwirte the content (e.g. blank or random value). The lifecycle of the "sensitive" information should be as short as possible. 27 | 28 | If you have read some source codes of Java or Android, now you may know why they use `CharSequence` (`Char Array`) instead of String in many places (e.g. `EditText`). 29 | 30 | You can take a look at our implementation of CharSequence for further understanding the correct method to use and store the sensitive informations: [SecureCharSequence](https://github.com/bither/bitherj/blob/master/bitherj/src/main/java/net/bither/bitherj/crypto/SecureCharSequence.java) 31 | 32 | The advantage of using SecureCharSequence is : even when next "OpenSSL HeartBleed" happens, your bitcoins are still a little bit safer than others. 33 | 34 | We had posted issues for the following projects : 35 | * blockchain.info : https://github.com/blockchain/My-Wallet-Android/issues/10 36 | * Bitcoin Wallet : https://github.com/schildbach/bitcoin-wallet/issues/179 37 | * Mycelium : https://github.com/mycelium-com/wallet/issues/135 38 | -------------------------------------------------------------------------------- /gradle.properties: -------------------------------------------------------------------------------- 1 | # Project-wide Gradle settings. 2 | 3 | # IDE (e.g. Android Studio) users: 4 | # Settings specified in this file will override any Gradle settings 5 | # configured through the IDE. 6 | 7 | # For more details on how to configure your build environment visit 8 | # http://www.gradle.org/docs/current/userguide/build_environment.html 9 | 10 | # Specifies the JVM arguments used for the daemon process. 11 | # The setting is particularly useful for tweaking memory settings. 12 | # Default value: -Xmx10248m -XX:MaxPermSize=256m 13 | # org.gradle.jvmargs=-Xmx2048m -XX:MaxPermSize=512m -XX:+HeapDumpOnOutOfMemoryError -Dfile.encoding=UTF-8 14 | 15 | # When configured, Gradle will run in incubating parallel mode. 16 | # This option should only be used with decoupled projects. More details, visit 17 | # http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects 18 | # org.gradle.parallel=true -------------------------------------------------------------------------------- /scripts/cert2keystore_bks.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | if [ -z $1 ]; then 4 | echo "Usage: cert2keystore_bks.sh " 5 | exit 1 6 | fi 7 | 8 | CACERT=$1 9 | PASS=$2 10 | BCJAR=bcprov-jdk15on-146.jar 11 | 12 | TRUSTSTORE=bithertruststore.bks 13 | ALIAS=`openssl x509 -inform PEM -subject_hash -noout -in $CACERT` 14 | 15 | if [ -f $TRUSTSTORE ]; then 16 | rm $TRUSTSTORE || exit 1 17 | fi 18 | 19 | echo "Adding certificate to $TRUSTSTORE..." 20 | keytool -import -v -trustcacerts -alias $ALIAS \ 21 | -file $CACERT \ 22 | -keystore $TRUSTSTORE -storetype BKS \ 23 | -providerclass org.bouncycastle.jce.provider.BouncyCastleProvider \ 24 | -providerpath $BCJAR \ 25 | -storepass $PASS 26 | 27 | echo "" 28 | echo "Added '$CACERT' with alias '$ALIAS' to $TRUSTSTORE..." 29 | 30 | -------------------------------------------------------------------------------- /scripts/cert2keystore_jks.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | if [ -z $1 ]; then 4 | echo "Usage: cert2keystore_jks.sh " 5 | exit 1 6 | fi 7 | 8 | CACERT=$1 9 | PASS=$2 10 | 11 | TRUSTSTORE=bithertruststore.jks 12 | ALIAS=`openssl x509 -inform PEM -subject_hash -noout -in $CACERT` 13 | 14 | if [ -f $TRUSTSTORE ]; then 15 | rm $TRUSTSTORE || exit 1 16 | fi 17 | 18 | echo "Adding certificate to $TRUSTSTORE..." 19 | keytool -import -v -trustcacerts -alias $ALIAS \ 20 | -file $CACERT \ 21 | -keystore $TRUSTSTORE \ 22 | -storepass $PASS 23 | 24 | echo "" 25 | echo "Added '$CACERT' with alias '$ALIAS' to $TRUSTSTORE..." 26 | 27 | -------------------------------------------------------------------------------- /settings.gradle: -------------------------------------------------------------------------------- 1 | include ':bitherj' 2 | 3 | --------------------------------------------------------------------------------