target
stringlengths
20
113k
src_fm
stringlengths
11
86.3k
src_fm_fc
stringlengths
21
86.4k
src_fm_fc_co
stringlengths
30
86.4k
src_fm_fc_ms
stringlengths
31
126k
src_fm_fc_ms_ff
stringlengths
32
126k
@Test public void reset() { sendMoneyToWallet(AbstractBlockChain.NewBlockType.BEST_CHAIN, COIN, myAddress); assertNotEquals(Coin.ZERO, wallet.getBalance(Wallet.BalanceType.ESTIMATED)); assertNotEquals(0, wallet.getTransactions(false).size()); assertNotEquals(0, wallet.getUnspents().size()); wallet.reset(); assertEquals(Coin.ZERO, wallet.getBalance(Wallet.BalanceType.ESTIMATED)); assertEquals(0, wallet.getTransactions(false).size()); assertEquals(0, wallet.getUnspents().size()); }
public void reset() { lock.lock(); try { clearTransactions(); lastBlockSeenHash = null; lastBlockSeenHeight = -1; lastBlockSeenTimeSecs = 0; saveLater(); maybeQueueOnWalletChanged(); } finally { lock.unlock(); } }
Wallet extends BaseTaggableObject implements NewBestBlockListener, TransactionReceivedInBlockListener, PeerFilterProvider, KeyBag, TransactionBag, ReorganizeListener { public void reset() { lock.lock(); try { clearTransactions(); lastBlockSeenHash = null; lastBlockSeenHeight = -1; lastBlockSeenTimeSecs = 0; saveLater(); maybeQueueOnWalletChanged(); } finally { lock.unlock(); } } }
Wallet extends BaseTaggableObject implements NewBestBlockListener, TransactionReceivedInBlockListener, PeerFilterProvider, KeyBag, TransactionBag, ReorganizeListener { public void reset() { lock.lock(); try { clearTransactions(); lastBlockSeenHash = null; lastBlockSeenHeight = -1; lastBlockSeenTimeSecs = 0; saveLater(); maybeQueueOnWalletChanged(); } finally { lock.unlock(); } } Wallet(NetworkParameters params); Wallet(Context context); Wallet(NetworkParameters params, KeyChainGroup keyChainGroup); private Wallet(Context context, KeyChainGroup keyChainGroup); }
Wallet extends BaseTaggableObject implements NewBestBlockListener, TransactionReceivedInBlockListener, PeerFilterProvider, KeyBag, TransactionBag, ReorganizeListener { public void reset() { lock.lock(); try { clearTransactions(); lastBlockSeenHash = null; lastBlockSeenHeight = -1; lastBlockSeenTimeSecs = 0; saveLater(); maybeQueueOnWalletChanged(); } finally { lock.unlock(); } } Wallet(NetworkParameters params); Wallet(Context context); Wallet(NetworkParameters params, KeyChainGroup keyChainGroup); private Wallet(Context context, KeyChainGroup keyChainGroup); static Wallet fromSeed(NetworkParameters params, DeterministicSeed seed); static Wallet fromWatchingKey(NetworkParameters params, DeterministicKey watchKey); static Wallet fromWatchingKeyB58(NetworkParameters params, String watchKeyB58, long creationTimeSeconds); static Wallet fromKeys(NetworkParameters params, List<ECKey> keys); NetworkParameters getNetworkParameters(); DeterministicKeyChain getActiveKeyChain(); final void addTransactionSigner(TransactionSigner signer); List<TransactionSigner> getTransactionSigners(); DeterministicKey currentKey(KeyChain.KeyPurpose purpose); DeterministicKey currentReceiveKey(); Address currentAddress(KeyChain.KeyPurpose purpose); Address currentReceiveAddress(); DeterministicKey freshKey(KeyChain.KeyPurpose purpose); List<DeterministicKey> freshKeys(KeyChain.KeyPurpose purpose, int numberOfKeys); DeterministicKey freshReceiveKey(); Address freshAddress(KeyChain.KeyPurpose purpose); Address freshReceiveAddress(); List<ECKey> getIssuedReceiveKeys(); List<Address> getIssuedReceiveAddresses(); void upgradeToDeterministic(@Nullable KeyParameter aesKey); boolean isDeterministicUpgradeRequired(); List<Script> getWatchedScripts(); boolean removeKey(ECKey key); int getKeyChainGroupSize(); @VisibleForTesting int getKeyChainGroupCombinedKeyLookaheadEpochs(); List<ECKey> getImportedKeys(); Address currentChangeAddress(); Address getChangeAddress(); @Deprecated boolean addKey(ECKey key); boolean importKey(ECKey key); @Deprecated int addKeys(List<ECKey> keys); int importKeys(final List<ECKey> keys); int importKeysAndEncrypt(final List<ECKey> keys, CharSequence password); int importKeysAndEncrypt(final List<ECKey> keys, KeyParameter aesKey); void addAndActivateHDChain(DeterministicKeyChain chain); void setKeyChainGroupLookaheadSize(int lookaheadSize); int getKeyChainGroupLookaheadSize(); void setKeyChainGroupLookaheadThreshold(int num); int getKeyChainGroupLookaheadThreshold(); DeterministicKey getWatchingKey(); boolean isWatching(); boolean isAddressWatched(Address address); boolean addWatchedAddress(final Address address); boolean addWatchedAddress(final Address address, long creationTime); int addWatchedAddresses(final List<Address> addresses, long creationTime); int addWatchedScripts(final List<Script> scripts); boolean removeWatchedAddress(final Address address); boolean removeWatchedAddresses(final List<Address> addresses); boolean removeWatchedScripts(final List<Script> scripts); List<Address> getWatchedAddresses(); @Override @Nullable ECKey findKeyFromPubHash(byte[] pubkeyHash); boolean hasKey(ECKey key); @Override boolean isPubKeyHashMine(byte[] pubkeyHash); @Override boolean isWatchedScript(Script script); @Override @Nullable ECKey findKeyFromPubKey(byte[] pubkey); @Override boolean isPubKeyMine(byte[] pubkey); @Nullable @Override RedeemData findRedeemDataFromScriptHash(byte[] payToScriptHash); @Override boolean isPayToScriptHashMine(byte[] payToScriptHash); DeterministicSeed getKeyChainSeed(); DeterministicKey getKeyByPath(List<ChildNumber> path); void encrypt(CharSequence password); void encrypt(KeyCrypter keyCrypter, KeyParameter aesKey); void decrypt(CharSequence password); void decrypt(KeyParameter aesKey); boolean checkPassword(CharSequence password); boolean checkAESKey(KeyParameter aesKey); @Nullable KeyCrypter getKeyCrypter(); EncryptionType getEncryptionType(); boolean isEncrypted(); void changeEncryptionPassword(CharSequence currentPassword, CharSequence newPassword); void changeEncryptionKey(KeyCrypter keyCrypter, KeyParameter currentAesKey, KeyParameter newAesKey); List<Protos.Key> serializeKeyChainGroupToProtobuf(); void saveToFile(File temp, File destFile); void saveToFile(File f); void setAcceptRiskyTransactions(boolean acceptRiskyTransactions); boolean isAcceptRiskyTransactions(); void setRiskAnalyzer(RiskAnalysis.Analyzer analyzer); RiskAnalysis.Analyzer getRiskAnalyzer(); WalletFiles autosaveToFile(File f, long delayTime, TimeUnit timeUnit, @Nullable WalletFiles.Listener eventListener); void shutdownAutosaveAndWait(); void saveToFileStream(OutputStream f); NetworkParameters getParams(); Context getContext(); static Wallet loadFromFile(File file, @Nullable WalletExtension... walletExtensions); boolean isConsistent(); void isConsistentOrThrow(); static Wallet loadFromFileStream(InputStream stream, @Nullable WalletExtension... walletExtensions); @Override boolean notifyTransactionIsInBlock(Sha256Hash txHash, StoredBlock block, BlockChain.NewBlockType blockType, int relativityOffset); void receivePending(Transaction tx, @Nullable List<Transaction> dependencies, boolean overrideIsRelevant); boolean isTransactionRisky(Transaction tx, @Nullable List<Transaction> dependencies); void receivePending(Transaction tx, @Nullable List<Transaction> dependencies); boolean isPendingTransactionRelevant(Transaction tx); boolean isTransactionRelevant(Transaction tx); @Override void receiveFromBlock(Transaction tx, StoredBlock block, BlockChain.NewBlockType blockType, int relativityOffset); @Override void notifyNewBestBlock(StoredBlock block); boolean maybeCommitTx(Transaction tx); void commitTx(Transaction tx); void addEventListener(WalletEventListener listener); @Deprecated void addEventListener(WalletEventListener listener, Executor executor); void addChangeEventListener(WalletChangeEventListener listener); void addChangeEventListener(Executor executor, WalletChangeEventListener listener); void addCoinsReceivedEventListener(WalletCoinsReceivedEventListener listener); void addCoinsReceivedEventListener(Executor executor, WalletCoinsReceivedEventListener listener); void addCoinsSentEventListener(WalletCoinsSentEventListener listener); void addCoinsSentEventListener(Executor executor, WalletCoinsSentEventListener listener); void addKeyChainEventListener(KeyChainEventListener listener); void addKeyChainEventListener(Executor executor, KeyChainEventListener listener); void addReorganizeEventListener(WalletReorganizeEventListener listener); void addReorganizeEventListener(Executor executor, WalletReorganizeEventListener listener); void addScriptsChangeEventListener(ScriptsChangeEventListener listener); void addScriptChangeEventListener(Executor executor, ScriptsChangeEventListener listener); void addTransactionConfidenceEventListener(TransactionConfidenceEventListener listener); void addTransactionConfidenceEventListener(Executor executor, TransactionConfidenceEventListener listener); @Deprecated boolean removeEventListener(WalletEventListener listener); boolean removeChangeEventListener(WalletChangeEventListener listener); boolean removeCoinsReceivedEventListener(WalletCoinsReceivedEventListener listener); boolean removeCoinsSentEventListener(WalletCoinsSentEventListener listener); boolean removeKeyChainEventListener(KeyChainEventListener listener); boolean removeReorganizeEventListener(WalletReorganizeEventListener listener); boolean removeScriptChangeEventListener(ScriptsChangeEventListener listener); boolean removeTransactionConfidenceEventListener(TransactionConfidenceEventListener listener); Set<Transaction> getTransactions(boolean includeDead); Iterable<WalletTransaction> getWalletTransactions(); void addWalletTransaction(WalletTransaction wtx); List<Transaction> getTransactionsByTime(); List<Transaction> getRecentTransactions(int numTransactions, boolean includeDead); @Nullable Transaction getTransaction(Sha256Hash hash); @Override Map<Sha256Hash, Transaction> getTransactionPool(Pool pool); void reset(); void clearTransactions(int fromHeight); List<TransactionOutput> getWatchedOutputs(boolean excludeImmatureCoinbases); void cleanup(); @VisibleForTesting int getPoolSize(WalletTransaction.Pool pool); @VisibleForTesting boolean poolContainsTxHash(final WalletTransaction.Pool pool, final Sha256Hash txHash); List<TransactionOutput> getUnspents(); @Override String toString(); String toString(boolean includePrivateKeys, boolean includeTransactions, boolean includeExtensions, @Nullable AbstractBlockChain chain); Collection<Transaction> getPendingTransactions(); @Override long getEarliestKeyCreationTime(); @Nullable Sha256Hash getLastBlockSeenHash(); void setLastBlockSeenHash(@Nullable Sha256Hash lastBlockSeenHash); void setLastBlockSeenHeight(int lastBlockSeenHeight); void setLastBlockSeenTimeSecs(long timeSecs); long getLastBlockSeenTimeSecs(); @Nullable Date getLastBlockSeenTime(); int getLastBlockSeenHeight(); int getVersion(); void setVersion(int version); void setDescription(String description); String getDescription(); @Deprecated Coin getWatchedBalance(); @Deprecated Coin getWatchedBalance(CoinSelector selector); Coin getBalance(); Coin getBalance(BalanceType balanceType); Coin getBalance(CoinSelector selector); ListenableFuture<Coin> getBalanceFuture(final Coin value, final BalanceType type); Coin getTotalReceived(); Coin getTotalSent(); Transaction createSend(Address address, Coin value); Transaction sendCoinsOffline(SendRequest request); SendResult sendCoins(TransactionBroadcaster broadcaster, Address to, Coin value); SendResult sendCoins(TransactionBroadcaster broadcaster, Address to, Coin value, boolean useforkId); SendResult sendCoins(TransactionBroadcaster broadcaster, SendRequest request); SendResult sendCoins(SendRequest request); Transaction sendCoins(Peer peer, SendRequest request); void completeTx(SendRequest req); void signTransaction(SendRequest req); List<TransactionOutput> calculateAllSpendCandidates(); @Deprecated List<TransactionOutput> calculateAllSpendCandidates(boolean excludeImmatureCoinbases); List<TransactionOutput> calculateAllSpendCandidates(boolean excludeImmatureCoinbases, boolean excludeUnsignable); boolean canSignFor(Script script); CoinSelector getCoinSelector(); void setCoinSelector(CoinSelector coinSelector); void allowSpendingUnconfirmedTransactions(); @Nullable UTXOProvider getUTXOProvider(); void setUTXOProvider(@Nullable UTXOProvider provider); @Override void reorganize(StoredBlock splitPoint, List<StoredBlock> oldBlocks, List<StoredBlock> newBlocks); @Override void beginBloomFilterCalculation(); @Override @GuardedBy("keyChainGroupLock") void endBloomFilterCalculation(); @Override int getBloomFilterElementCount(); @Override boolean isRequiringUpdateAllBloomFilter(); BloomFilter getBloomFilter(double falsePositiveRate); @Override @GuardedBy("keyChainGroupLock") BloomFilter getBloomFilter(int size, double falsePositiveRate, long nTweak); boolean checkForFilterExhaustion(FilteredBlock block); void addExtension(WalletExtension extension); WalletExtension addOrGetExistingExtension(WalletExtension extension); void addOrUpdateExtension(WalletExtension extension); Map<String, WalletExtension> getExtensions(); void deserializeExtension(WalletExtension extension, byte[] data); @Override void setTag(String tag, ByteString value); FeeCalculation calculateFee(SendRequest req, Coin value, List<TransactionInput> originalInputs, boolean needAtLeastReferenceFee, List<TransactionOutput> candidates); void setTransactionBroadcaster(@Nullable org.bitcoinj.core.TransactionBroadcaster broadcaster); void setKeyRotationTime(Date time); @Nullable Date getKeyRotationTime(); void setKeyRotationTime(long unixTimeSeconds); boolean isKeyRotating(ECKey key); @Deprecated ListenableFuture<List<Transaction>> maybeDoMaintenance(@Nullable KeyParameter aesKey, boolean andSend); ListenableFuture<List<Transaction>> doMaintenance(@Nullable KeyParameter aesKey, boolean signAndSend); }
Wallet extends BaseTaggableObject implements NewBestBlockListener, TransactionReceivedInBlockListener, PeerFilterProvider, KeyBag, TransactionBag, ReorganizeListener { public void reset() { lock.lock(); try { clearTransactions(); lastBlockSeenHash = null; lastBlockSeenHeight = -1; lastBlockSeenTimeSecs = 0; saveLater(); maybeQueueOnWalletChanged(); } finally { lock.unlock(); } } Wallet(NetworkParameters params); Wallet(Context context); Wallet(NetworkParameters params, KeyChainGroup keyChainGroup); private Wallet(Context context, KeyChainGroup keyChainGroup); static Wallet fromSeed(NetworkParameters params, DeterministicSeed seed); static Wallet fromWatchingKey(NetworkParameters params, DeterministicKey watchKey); static Wallet fromWatchingKeyB58(NetworkParameters params, String watchKeyB58, long creationTimeSeconds); static Wallet fromKeys(NetworkParameters params, List<ECKey> keys); NetworkParameters getNetworkParameters(); DeterministicKeyChain getActiveKeyChain(); final void addTransactionSigner(TransactionSigner signer); List<TransactionSigner> getTransactionSigners(); DeterministicKey currentKey(KeyChain.KeyPurpose purpose); DeterministicKey currentReceiveKey(); Address currentAddress(KeyChain.KeyPurpose purpose); Address currentReceiveAddress(); DeterministicKey freshKey(KeyChain.KeyPurpose purpose); List<DeterministicKey> freshKeys(KeyChain.KeyPurpose purpose, int numberOfKeys); DeterministicKey freshReceiveKey(); Address freshAddress(KeyChain.KeyPurpose purpose); Address freshReceiveAddress(); List<ECKey> getIssuedReceiveKeys(); List<Address> getIssuedReceiveAddresses(); void upgradeToDeterministic(@Nullable KeyParameter aesKey); boolean isDeterministicUpgradeRequired(); List<Script> getWatchedScripts(); boolean removeKey(ECKey key); int getKeyChainGroupSize(); @VisibleForTesting int getKeyChainGroupCombinedKeyLookaheadEpochs(); List<ECKey> getImportedKeys(); Address currentChangeAddress(); Address getChangeAddress(); @Deprecated boolean addKey(ECKey key); boolean importKey(ECKey key); @Deprecated int addKeys(List<ECKey> keys); int importKeys(final List<ECKey> keys); int importKeysAndEncrypt(final List<ECKey> keys, CharSequence password); int importKeysAndEncrypt(final List<ECKey> keys, KeyParameter aesKey); void addAndActivateHDChain(DeterministicKeyChain chain); void setKeyChainGroupLookaheadSize(int lookaheadSize); int getKeyChainGroupLookaheadSize(); void setKeyChainGroupLookaheadThreshold(int num); int getKeyChainGroupLookaheadThreshold(); DeterministicKey getWatchingKey(); boolean isWatching(); boolean isAddressWatched(Address address); boolean addWatchedAddress(final Address address); boolean addWatchedAddress(final Address address, long creationTime); int addWatchedAddresses(final List<Address> addresses, long creationTime); int addWatchedScripts(final List<Script> scripts); boolean removeWatchedAddress(final Address address); boolean removeWatchedAddresses(final List<Address> addresses); boolean removeWatchedScripts(final List<Script> scripts); List<Address> getWatchedAddresses(); @Override @Nullable ECKey findKeyFromPubHash(byte[] pubkeyHash); boolean hasKey(ECKey key); @Override boolean isPubKeyHashMine(byte[] pubkeyHash); @Override boolean isWatchedScript(Script script); @Override @Nullable ECKey findKeyFromPubKey(byte[] pubkey); @Override boolean isPubKeyMine(byte[] pubkey); @Nullable @Override RedeemData findRedeemDataFromScriptHash(byte[] payToScriptHash); @Override boolean isPayToScriptHashMine(byte[] payToScriptHash); DeterministicSeed getKeyChainSeed(); DeterministicKey getKeyByPath(List<ChildNumber> path); void encrypt(CharSequence password); void encrypt(KeyCrypter keyCrypter, KeyParameter aesKey); void decrypt(CharSequence password); void decrypt(KeyParameter aesKey); boolean checkPassword(CharSequence password); boolean checkAESKey(KeyParameter aesKey); @Nullable KeyCrypter getKeyCrypter(); EncryptionType getEncryptionType(); boolean isEncrypted(); void changeEncryptionPassword(CharSequence currentPassword, CharSequence newPassword); void changeEncryptionKey(KeyCrypter keyCrypter, KeyParameter currentAesKey, KeyParameter newAesKey); List<Protos.Key> serializeKeyChainGroupToProtobuf(); void saveToFile(File temp, File destFile); void saveToFile(File f); void setAcceptRiskyTransactions(boolean acceptRiskyTransactions); boolean isAcceptRiskyTransactions(); void setRiskAnalyzer(RiskAnalysis.Analyzer analyzer); RiskAnalysis.Analyzer getRiskAnalyzer(); WalletFiles autosaveToFile(File f, long delayTime, TimeUnit timeUnit, @Nullable WalletFiles.Listener eventListener); void shutdownAutosaveAndWait(); void saveToFileStream(OutputStream f); NetworkParameters getParams(); Context getContext(); static Wallet loadFromFile(File file, @Nullable WalletExtension... walletExtensions); boolean isConsistent(); void isConsistentOrThrow(); static Wallet loadFromFileStream(InputStream stream, @Nullable WalletExtension... walletExtensions); @Override boolean notifyTransactionIsInBlock(Sha256Hash txHash, StoredBlock block, BlockChain.NewBlockType blockType, int relativityOffset); void receivePending(Transaction tx, @Nullable List<Transaction> dependencies, boolean overrideIsRelevant); boolean isTransactionRisky(Transaction tx, @Nullable List<Transaction> dependencies); void receivePending(Transaction tx, @Nullable List<Transaction> dependencies); boolean isPendingTransactionRelevant(Transaction tx); boolean isTransactionRelevant(Transaction tx); @Override void receiveFromBlock(Transaction tx, StoredBlock block, BlockChain.NewBlockType blockType, int relativityOffset); @Override void notifyNewBestBlock(StoredBlock block); boolean maybeCommitTx(Transaction tx); void commitTx(Transaction tx); void addEventListener(WalletEventListener listener); @Deprecated void addEventListener(WalletEventListener listener, Executor executor); void addChangeEventListener(WalletChangeEventListener listener); void addChangeEventListener(Executor executor, WalletChangeEventListener listener); void addCoinsReceivedEventListener(WalletCoinsReceivedEventListener listener); void addCoinsReceivedEventListener(Executor executor, WalletCoinsReceivedEventListener listener); void addCoinsSentEventListener(WalletCoinsSentEventListener listener); void addCoinsSentEventListener(Executor executor, WalletCoinsSentEventListener listener); void addKeyChainEventListener(KeyChainEventListener listener); void addKeyChainEventListener(Executor executor, KeyChainEventListener listener); void addReorganizeEventListener(WalletReorganizeEventListener listener); void addReorganizeEventListener(Executor executor, WalletReorganizeEventListener listener); void addScriptsChangeEventListener(ScriptsChangeEventListener listener); void addScriptChangeEventListener(Executor executor, ScriptsChangeEventListener listener); void addTransactionConfidenceEventListener(TransactionConfidenceEventListener listener); void addTransactionConfidenceEventListener(Executor executor, TransactionConfidenceEventListener listener); @Deprecated boolean removeEventListener(WalletEventListener listener); boolean removeChangeEventListener(WalletChangeEventListener listener); boolean removeCoinsReceivedEventListener(WalletCoinsReceivedEventListener listener); boolean removeCoinsSentEventListener(WalletCoinsSentEventListener listener); boolean removeKeyChainEventListener(KeyChainEventListener listener); boolean removeReorganizeEventListener(WalletReorganizeEventListener listener); boolean removeScriptChangeEventListener(ScriptsChangeEventListener listener); boolean removeTransactionConfidenceEventListener(TransactionConfidenceEventListener listener); Set<Transaction> getTransactions(boolean includeDead); Iterable<WalletTransaction> getWalletTransactions(); void addWalletTransaction(WalletTransaction wtx); List<Transaction> getTransactionsByTime(); List<Transaction> getRecentTransactions(int numTransactions, boolean includeDead); @Nullable Transaction getTransaction(Sha256Hash hash); @Override Map<Sha256Hash, Transaction> getTransactionPool(Pool pool); void reset(); void clearTransactions(int fromHeight); List<TransactionOutput> getWatchedOutputs(boolean excludeImmatureCoinbases); void cleanup(); @VisibleForTesting int getPoolSize(WalletTransaction.Pool pool); @VisibleForTesting boolean poolContainsTxHash(final WalletTransaction.Pool pool, final Sha256Hash txHash); List<TransactionOutput> getUnspents(); @Override String toString(); String toString(boolean includePrivateKeys, boolean includeTransactions, boolean includeExtensions, @Nullable AbstractBlockChain chain); Collection<Transaction> getPendingTransactions(); @Override long getEarliestKeyCreationTime(); @Nullable Sha256Hash getLastBlockSeenHash(); void setLastBlockSeenHash(@Nullable Sha256Hash lastBlockSeenHash); void setLastBlockSeenHeight(int lastBlockSeenHeight); void setLastBlockSeenTimeSecs(long timeSecs); long getLastBlockSeenTimeSecs(); @Nullable Date getLastBlockSeenTime(); int getLastBlockSeenHeight(); int getVersion(); void setVersion(int version); void setDescription(String description); String getDescription(); @Deprecated Coin getWatchedBalance(); @Deprecated Coin getWatchedBalance(CoinSelector selector); Coin getBalance(); Coin getBalance(BalanceType balanceType); Coin getBalance(CoinSelector selector); ListenableFuture<Coin> getBalanceFuture(final Coin value, final BalanceType type); Coin getTotalReceived(); Coin getTotalSent(); Transaction createSend(Address address, Coin value); Transaction sendCoinsOffline(SendRequest request); SendResult sendCoins(TransactionBroadcaster broadcaster, Address to, Coin value); SendResult sendCoins(TransactionBroadcaster broadcaster, Address to, Coin value, boolean useforkId); SendResult sendCoins(TransactionBroadcaster broadcaster, SendRequest request); SendResult sendCoins(SendRequest request); Transaction sendCoins(Peer peer, SendRequest request); void completeTx(SendRequest req); void signTransaction(SendRequest req); List<TransactionOutput> calculateAllSpendCandidates(); @Deprecated List<TransactionOutput> calculateAllSpendCandidates(boolean excludeImmatureCoinbases); List<TransactionOutput> calculateAllSpendCandidates(boolean excludeImmatureCoinbases, boolean excludeUnsignable); boolean canSignFor(Script script); CoinSelector getCoinSelector(); void setCoinSelector(CoinSelector coinSelector); void allowSpendingUnconfirmedTransactions(); @Nullable UTXOProvider getUTXOProvider(); void setUTXOProvider(@Nullable UTXOProvider provider); @Override void reorganize(StoredBlock splitPoint, List<StoredBlock> oldBlocks, List<StoredBlock> newBlocks); @Override void beginBloomFilterCalculation(); @Override @GuardedBy("keyChainGroupLock") void endBloomFilterCalculation(); @Override int getBloomFilterElementCount(); @Override boolean isRequiringUpdateAllBloomFilter(); BloomFilter getBloomFilter(double falsePositiveRate); @Override @GuardedBy("keyChainGroupLock") BloomFilter getBloomFilter(int size, double falsePositiveRate, long nTweak); boolean checkForFilterExhaustion(FilteredBlock block); void addExtension(WalletExtension extension); WalletExtension addOrGetExistingExtension(WalletExtension extension); void addOrUpdateExtension(WalletExtension extension); Map<String, WalletExtension> getExtensions(); void deserializeExtension(WalletExtension extension, byte[] data); @Override void setTag(String tag, ByteString value); FeeCalculation calculateFee(SendRequest req, Coin value, List<TransactionInput> originalInputs, boolean needAtLeastReferenceFee, List<TransactionOutput> candidates); void setTransactionBroadcaster(@Nullable org.bitcoinj.core.TransactionBroadcaster broadcaster); void setKeyRotationTime(Date time); @Nullable Date getKeyRotationTime(); void setKeyRotationTime(long unixTimeSeconds); boolean isKeyRotating(ECKey key); @Deprecated ListenableFuture<List<Transaction>> maybeDoMaintenance(@Nullable KeyParameter aesKey, boolean andSend); ListenableFuture<List<Transaction>> doMaintenance(@Nullable KeyParameter aesKey, boolean signAndSend); }
@Test public void getKeys() throws Exception { chain.getKey(KeyChain.KeyPurpose.RECEIVE_FUNDS); chain.getKey(KeyChain.KeyPurpose.CHANGE); chain.maybeLookAhead(); assertEquals(2, chain.getKeys(false).size()); }
@Override public List<DeterministicKey> getKeys(KeyPurpose purpose, int numberOfKeys) { checkArgument(numberOfKeys > 0); lock.lock(); try { DeterministicKey parentKey; int index; switch (purpose) { case RECEIVE_FUNDS: case REFUND: issuedExternalKeys += numberOfKeys; index = issuedExternalKeys; parentKey = externalParentKey; break; case AUTHENTICATION: case CHANGE: issuedInternalKeys += numberOfKeys; index = issuedInternalKeys; parentKey = internalParentKey; break; default: throw new UnsupportedOperationException(); } List<DeterministicKey> lookahead = maybeLookAhead(parentKey, index, 0, 0); basicKeyChain.importKeys(lookahead); List<DeterministicKey> keys = new ArrayList<DeterministicKey>(numberOfKeys); for (int i = 0; i < numberOfKeys; i++) { ImmutableList<ChildNumber> path = HDUtils.append(parentKey.getPath(), new ChildNumber(index - numberOfKeys + i, false)); DeterministicKey k = hierarchy.get(path, false, false); checkForBitFlip(k); keys.add(k); } return keys; } finally { lock.unlock(); } }
DeterministicKeyChain implements EncryptableKeyChain { @Override public List<DeterministicKey> getKeys(KeyPurpose purpose, int numberOfKeys) { checkArgument(numberOfKeys > 0); lock.lock(); try { DeterministicKey parentKey; int index; switch (purpose) { case RECEIVE_FUNDS: case REFUND: issuedExternalKeys += numberOfKeys; index = issuedExternalKeys; parentKey = externalParentKey; break; case AUTHENTICATION: case CHANGE: issuedInternalKeys += numberOfKeys; index = issuedInternalKeys; parentKey = internalParentKey; break; default: throw new UnsupportedOperationException(); } List<DeterministicKey> lookahead = maybeLookAhead(parentKey, index, 0, 0); basicKeyChain.importKeys(lookahead); List<DeterministicKey> keys = new ArrayList<DeterministicKey>(numberOfKeys); for (int i = 0; i < numberOfKeys; i++) { ImmutableList<ChildNumber> path = HDUtils.append(parentKey.getPath(), new ChildNumber(index - numberOfKeys + i, false)); DeterministicKey k = hierarchy.get(path, false, false); checkForBitFlip(k); keys.add(k); } return keys; } finally { lock.unlock(); } } }
DeterministicKeyChain implements EncryptableKeyChain { @Override public List<DeterministicKey> getKeys(KeyPurpose purpose, int numberOfKeys) { checkArgument(numberOfKeys > 0); lock.lock(); try { DeterministicKey parentKey; int index; switch (purpose) { case RECEIVE_FUNDS: case REFUND: issuedExternalKeys += numberOfKeys; index = issuedExternalKeys; parentKey = externalParentKey; break; case AUTHENTICATION: case CHANGE: issuedInternalKeys += numberOfKeys; index = issuedInternalKeys; parentKey = internalParentKey; break; default: throw new UnsupportedOperationException(); } List<DeterministicKey> lookahead = maybeLookAhead(parentKey, index, 0, 0); basicKeyChain.importKeys(lookahead); List<DeterministicKey> keys = new ArrayList<DeterministicKey>(numberOfKeys); for (int i = 0; i < numberOfKeys; i++) { ImmutableList<ChildNumber> path = HDUtils.append(parentKey.getPath(), new ChildNumber(index - numberOfKeys + i, false)); DeterministicKey k = hierarchy.get(path, false, false); checkForBitFlip(k); keys.add(k); } return keys; } finally { lock.unlock(); } } DeterministicKeyChain(SecureRandom random); DeterministicKeyChain(SecureRandom random, int bits); DeterministicKeyChain(SecureRandom random, int bits, String passphrase, long seedCreationTimeSecs); DeterministicKeyChain(byte[] entropy, String passphrase, long seedCreationTimeSecs); protected DeterministicKeyChain(DeterministicSeed seed); DeterministicKeyChain(DeterministicKey watchingKey); protected DeterministicKeyChain(DeterministicKey watchKey, boolean isFollowing); protected DeterministicKeyChain(DeterministicSeed seed, @Nullable KeyCrypter crypter); protected DeterministicKeyChain(KeyCrypter crypter, KeyParameter aesKey, DeterministicKeyChain chain); }
DeterministicKeyChain implements EncryptableKeyChain { @Override public List<DeterministicKey> getKeys(KeyPurpose purpose, int numberOfKeys) { checkArgument(numberOfKeys > 0); lock.lock(); try { DeterministicKey parentKey; int index; switch (purpose) { case RECEIVE_FUNDS: case REFUND: issuedExternalKeys += numberOfKeys; index = issuedExternalKeys; parentKey = externalParentKey; break; case AUTHENTICATION: case CHANGE: issuedInternalKeys += numberOfKeys; index = issuedInternalKeys; parentKey = internalParentKey; break; default: throw new UnsupportedOperationException(); } List<DeterministicKey> lookahead = maybeLookAhead(parentKey, index, 0, 0); basicKeyChain.importKeys(lookahead); List<DeterministicKey> keys = new ArrayList<DeterministicKey>(numberOfKeys); for (int i = 0; i < numberOfKeys; i++) { ImmutableList<ChildNumber> path = HDUtils.append(parentKey.getPath(), new ChildNumber(index - numberOfKeys + i, false)); DeterministicKey k = hierarchy.get(path, false, false); checkForBitFlip(k); keys.add(k); } return keys; } finally { lock.unlock(); } } DeterministicKeyChain(SecureRandom random); DeterministicKeyChain(SecureRandom random, int bits); DeterministicKeyChain(SecureRandom random, int bits, String passphrase, long seedCreationTimeSecs); DeterministicKeyChain(byte[] entropy, String passphrase, long seedCreationTimeSecs); protected DeterministicKeyChain(DeterministicSeed seed); DeterministicKeyChain(DeterministicKey watchingKey); protected DeterministicKeyChain(DeterministicKey watchKey, boolean isFollowing); protected DeterministicKeyChain(DeterministicSeed seed, @Nullable KeyCrypter crypter); protected DeterministicKeyChain(KeyCrypter crypter, KeyParameter aesKey, DeterministicKeyChain chain); static Builder<?> builder(); static DeterministicKeyChain watchAndFollow(DeterministicKey watchKey); static DeterministicKeyChain watch(DeterministicKey accountKey); @Override DeterministicKey getKey(KeyPurpose purpose); @Override List<DeterministicKey> getKeys(KeyPurpose purpose, int numberOfKeys); DeterministicKey markKeyAsUsed(DeterministicKey k); DeterministicKey findKeyFromPubHash(byte[] pubkeyHash); DeterministicKey findKeyFromPubKey(byte[] pubkey); @Nullable DeterministicKey markPubHashAsUsed(byte[] pubkeyHash); @Nullable DeterministicKey markPubKeyAsUsed(byte[] pubkey); @Override boolean hasKey(ECKey key); DeterministicKey getKeyByPath(List<ChildNumber> path, boolean create); DeterministicKey getWatchingKey(); boolean isWatching(); @Override int numKeys(); int numLeafKeysIssued(); @Override long getEarliestKeyCreationTime(); @Override void addEventListener(KeyChainEventListener listener); @Override void addEventListener(KeyChainEventListener listener, Executor executor); @Override boolean removeEventListener(KeyChainEventListener listener); @Nullable List<String> getMnemonicCode(); boolean isFollowing(); @Override List<Protos.Key> serializeToProtobuf(); static List<DeterministicKeyChain> fromProtobuf(List<Protos.Key> keys, @Nullable KeyCrypter crypter, KeyChainFactory factory); @Override DeterministicKeyChain toEncrypted(CharSequence password); @Override DeterministicKeyChain toEncrypted(KeyCrypter keyCrypter, KeyParameter aesKey); @Override DeterministicKeyChain toDecrypted(CharSequence password); @Override DeterministicKeyChain toDecrypted(KeyParameter aesKey); @Override boolean checkPassword(CharSequence password); @Override boolean checkAESKey(KeyParameter aesKey); @Nullable @Override KeyCrypter getKeyCrypter(); @Override int numBloomFilterEntries(); @Override BloomFilter getFilter(int size, double falsePositiveRate, long tweak); int getLookaheadSize(); void setLookaheadSize(int lookaheadSize); void setLookaheadThreshold(int num); int getLookaheadThreshold(); void maybeLookAhead(); void maybeLookAheadScripts(); int getIssuedExternalKeys(); int getIssuedInternalKeys(); @Nullable DeterministicSeed getSeed(); List<ECKey> getIssuedReceiveKeys(); List<DeterministicKey> getLeafKeys(); int getKeyLookaheadEpoch(); boolean isMarried(); RedeemData getRedeemData(DeterministicKey followedKey); Script freshOutputScript(KeyPurpose purpose); String toString(boolean includePrivateKeys, NetworkParameters params); void setSigsRequiredToSpend(int sigsRequiredToSpend); int getSigsRequiredToSpend(); @Nullable RedeemData findRedeemDataByScriptHash(ByteString bytes); }
DeterministicKeyChain implements EncryptableKeyChain { @Override public List<DeterministicKey> getKeys(KeyPurpose purpose, int numberOfKeys) { checkArgument(numberOfKeys > 0); lock.lock(); try { DeterministicKey parentKey; int index; switch (purpose) { case RECEIVE_FUNDS: case REFUND: issuedExternalKeys += numberOfKeys; index = issuedExternalKeys; parentKey = externalParentKey; break; case AUTHENTICATION: case CHANGE: issuedInternalKeys += numberOfKeys; index = issuedInternalKeys; parentKey = internalParentKey; break; default: throw new UnsupportedOperationException(); } List<DeterministicKey> lookahead = maybeLookAhead(parentKey, index, 0, 0); basicKeyChain.importKeys(lookahead); List<DeterministicKey> keys = new ArrayList<DeterministicKey>(numberOfKeys); for (int i = 0; i < numberOfKeys; i++) { ImmutableList<ChildNumber> path = HDUtils.append(parentKey.getPath(), new ChildNumber(index - numberOfKeys + i, false)); DeterministicKey k = hierarchy.get(path, false, false); checkForBitFlip(k); keys.add(k); } return keys; } finally { lock.unlock(); } } DeterministicKeyChain(SecureRandom random); DeterministicKeyChain(SecureRandom random, int bits); DeterministicKeyChain(SecureRandom random, int bits, String passphrase, long seedCreationTimeSecs); DeterministicKeyChain(byte[] entropy, String passphrase, long seedCreationTimeSecs); protected DeterministicKeyChain(DeterministicSeed seed); DeterministicKeyChain(DeterministicKey watchingKey); protected DeterministicKeyChain(DeterministicKey watchKey, boolean isFollowing); protected DeterministicKeyChain(DeterministicSeed seed, @Nullable KeyCrypter crypter); protected DeterministicKeyChain(KeyCrypter crypter, KeyParameter aesKey, DeterministicKeyChain chain); static Builder<?> builder(); static DeterministicKeyChain watchAndFollow(DeterministicKey watchKey); static DeterministicKeyChain watch(DeterministicKey accountKey); @Override DeterministicKey getKey(KeyPurpose purpose); @Override List<DeterministicKey> getKeys(KeyPurpose purpose, int numberOfKeys); DeterministicKey markKeyAsUsed(DeterministicKey k); DeterministicKey findKeyFromPubHash(byte[] pubkeyHash); DeterministicKey findKeyFromPubKey(byte[] pubkey); @Nullable DeterministicKey markPubHashAsUsed(byte[] pubkeyHash); @Nullable DeterministicKey markPubKeyAsUsed(byte[] pubkey); @Override boolean hasKey(ECKey key); DeterministicKey getKeyByPath(List<ChildNumber> path, boolean create); DeterministicKey getWatchingKey(); boolean isWatching(); @Override int numKeys(); int numLeafKeysIssued(); @Override long getEarliestKeyCreationTime(); @Override void addEventListener(KeyChainEventListener listener); @Override void addEventListener(KeyChainEventListener listener, Executor executor); @Override boolean removeEventListener(KeyChainEventListener listener); @Nullable List<String> getMnemonicCode(); boolean isFollowing(); @Override List<Protos.Key> serializeToProtobuf(); static List<DeterministicKeyChain> fromProtobuf(List<Protos.Key> keys, @Nullable KeyCrypter crypter, KeyChainFactory factory); @Override DeterministicKeyChain toEncrypted(CharSequence password); @Override DeterministicKeyChain toEncrypted(KeyCrypter keyCrypter, KeyParameter aesKey); @Override DeterministicKeyChain toDecrypted(CharSequence password); @Override DeterministicKeyChain toDecrypted(KeyParameter aesKey); @Override boolean checkPassword(CharSequence password); @Override boolean checkAESKey(KeyParameter aesKey); @Nullable @Override KeyCrypter getKeyCrypter(); @Override int numBloomFilterEntries(); @Override BloomFilter getFilter(int size, double falsePositiveRate, long tweak); int getLookaheadSize(); void setLookaheadSize(int lookaheadSize); void setLookaheadThreshold(int num); int getLookaheadThreshold(); void maybeLookAhead(); void maybeLookAheadScripts(); int getIssuedExternalKeys(); int getIssuedInternalKeys(); @Nullable DeterministicSeed getSeed(); List<ECKey> getIssuedReceiveKeys(); List<DeterministicKey> getLeafKeys(); int getKeyLookaheadEpoch(); boolean isMarried(); RedeemData getRedeemData(DeterministicKey followedKey); Script freshOutputScript(KeyPurpose purpose); String toString(boolean includePrivateKeys, NetworkParameters params); void setSigsRequiredToSpend(int sigsRequiredToSpend); int getSigsRequiredToSpend(); @Nullable RedeemData findRedeemDataByScriptHash(ByteString bytes); static final String DEFAULT_PASSPHRASE_FOR_MNEMONIC; static final ImmutableList<ChildNumber> ACCOUNT_ZERO_PATH; static final ImmutableList<ChildNumber> EXTERNAL_SUBPATH; static final ImmutableList<ChildNumber> INTERNAL_SUBPATH; static final ImmutableList<ChildNumber> EXTERNAL_PATH; static final ImmutableList<ChildNumber> INTERNAL_PATH; static final ImmutableList<ChildNumber> BIP44_ACCOUNT_ZERO_PATH; }
@Test public void selfCreatedAreNotRisky() { Transaction tx = new Transaction(PARAMS); tx.addInput(PARAMS.getGenesisBlock().getTransactions().get(0).getOutput(0)).setSequenceNumber(1); tx.addOutput(COIN, key1); tx.setLockTime(TIMESTAMP + 86400); { DefaultRiskAnalysis analysis = DefaultRiskAnalysis.FACTORY.create(wallet, tx, NO_DEPS); assertEquals(RiskAnalysis.Result.NON_FINAL, analysis.analyze()); } tx.getConfidence().setSource(TransactionConfidence.Source.SELF); { DefaultRiskAnalysis analysis = DefaultRiskAnalysis.FACTORY.create(wallet, tx, NO_DEPS); assertEquals(RiskAnalysis.Result.OK, analysis.analyze()); } }
@Override public Result analyze() { checkState(!analyzed); analyzed = true; Result result = analyzeIsFinal(); if (result != null && result != Result.OK) return result; return analyzeIsStandard(); }
DefaultRiskAnalysis implements RiskAnalysis { @Override public Result analyze() { checkState(!analyzed); analyzed = true; Result result = analyzeIsFinal(); if (result != null && result != Result.OK) return result; return analyzeIsStandard(); } }
DefaultRiskAnalysis implements RiskAnalysis { @Override public Result analyze() { checkState(!analyzed); analyzed = true; Result result = analyzeIsFinal(); if (result != null && result != Result.OK) return result; return analyzeIsStandard(); } private DefaultRiskAnalysis(Wallet wallet, Transaction tx, List<Transaction> dependencies); }
DefaultRiskAnalysis implements RiskAnalysis { @Override public Result analyze() { checkState(!analyzed); analyzed = true; Result result = analyzeIsFinal(); if (result != null && result != Result.OK) return result; return analyzeIsStandard(); } private DefaultRiskAnalysis(Wallet wallet, Transaction tx, List<Transaction> dependencies); @Override Result analyze(); static RuleViolation isStandard(Transaction tx); static RuleViolation isOutputStandard(TransactionOutput output); static RuleViolation isInputStandard(TransactionInput input); static RuleViolation isInputSignedWithForkId(TransactionInput input, boolean requireForkId); @Nullable Transaction getNonStandard(); @Nullable Transaction getNonFinal(); @Override String toString(); }
DefaultRiskAnalysis implements RiskAnalysis { @Override public Result analyze() { checkState(!analyzed); analyzed = true; Result result = analyzeIsFinal(); if (result != null && result != Result.OK) return result; return analyzeIsStandard(); } private DefaultRiskAnalysis(Wallet wallet, Transaction tx, List<Transaction> dependencies); @Override Result analyze(); static RuleViolation isStandard(Transaction tx); static RuleViolation isOutputStandard(TransactionOutput output); static RuleViolation isInputStandard(TransactionInput input); static RuleViolation isInputSignedWithForkId(TransactionInput input, boolean requireForkId); @Nullable Transaction getNonStandard(); @Nullable Transaction getNonFinal(); @Override String toString(); static final Coin MIN_ANALYSIS_NONDUST_OUTPUT; static Analyzer FACTORY; }
@Test public void nonStandardDust() { Transaction standardTx = new Transaction(PARAMS); standardTx.addInput(PARAMS.getGenesisBlock().getTransactions().get(0).getOutput(0)); standardTx.addOutput(COIN, key1); assertEquals(RiskAnalysis.Result.OK, DefaultRiskAnalysis.FACTORY.create(wallet, standardTx, NO_DEPS).analyze()); Transaction dustTx = new Transaction(PARAMS); dustTx.addInput(PARAMS.getGenesisBlock().getTransactions().get(0).getOutput(0)); dustTx.addOutput(Coin.SATOSHI, key1); assertEquals(RiskAnalysis.Result.NON_STANDARD, DefaultRiskAnalysis.FACTORY.create(wallet, dustTx, NO_DEPS).analyze()); Transaction edgeCaseTx = new Transaction(PARAMS); edgeCaseTx.addInput(PARAMS.getGenesisBlock().getTransactions().get(0).getOutput(0)); edgeCaseTx.addOutput(DefaultRiskAnalysis.MIN_ANALYSIS_NONDUST_OUTPUT, key1); assertEquals(RiskAnalysis.Result.OK, DefaultRiskAnalysis.FACTORY.create(wallet, edgeCaseTx, NO_DEPS).analyze()); }
@Override public Result analyze() { checkState(!analyzed); analyzed = true; Result result = analyzeIsFinal(); if (result != null && result != Result.OK) return result; return analyzeIsStandard(); }
DefaultRiskAnalysis implements RiskAnalysis { @Override public Result analyze() { checkState(!analyzed); analyzed = true; Result result = analyzeIsFinal(); if (result != null && result != Result.OK) return result; return analyzeIsStandard(); } }
DefaultRiskAnalysis implements RiskAnalysis { @Override public Result analyze() { checkState(!analyzed); analyzed = true; Result result = analyzeIsFinal(); if (result != null && result != Result.OK) return result; return analyzeIsStandard(); } private DefaultRiskAnalysis(Wallet wallet, Transaction tx, List<Transaction> dependencies); }
DefaultRiskAnalysis implements RiskAnalysis { @Override public Result analyze() { checkState(!analyzed); analyzed = true; Result result = analyzeIsFinal(); if (result != null && result != Result.OK) return result; return analyzeIsStandard(); } private DefaultRiskAnalysis(Wallet wallet, Transaction tx, List<Transaction> dependencies); @Override Result analyze(); static RuleViolation isStandard(Transaction tx); static RuleViolation isOutputStandard(TransactionOutput output); static RuleViolation isInputStandard(TransactionInput input); static RuleViolation isInputSignedWithForkId(TransactionInput input, boolean requireForkId); @Nullable Transaction getNonStandard(); @Nullable Transaction getNonFinal(); @Override String toString(); }
DefaultRiskAnalysis implements RiskAnalysis { @Override public Result analyze() { checkState(!analyzed); analyzed = true; Result result = analyzeIsFinal(); if (result != null && result != Result.OK) return result; return analyzeIsStandard(); } private DefaultRiskAnalysis(Wallet wallet, Transaction tx, List<Transaction> dependencies); @Override Result analyze(); static RuleViolation isStandard(Transaction tx); static RuleViolation isOutputStandard(TransactionOutput output); static RuleViolation isInputStandard(TransactionInput input); static RuleViolation isInputSignedWithForkId(TransactionInput input, boolean requireForkId); @Nullable Transaction getNonStandard(); @Nullable Transaction getNonFinal(); @Override String toString(); static final Coin MIN_ANALYSIS_NONDUST_OUTPUT; static Analyzer FACTORY; }
@Test public void nonShortestPossiblePushData() { ScriptChunk nonStandardChunk = new ScriptChunk(OP_PUSHDATA1, new byte[75]); byte[] nonStandardScript = new ScriptBuilder().addChunk(nonStandardChunk).build().getProgram(); Transaction tx = new Transaction(PARAMS); assertEquals(DefaultRiskAnalysis.RuleViolation.NONE, DefaultRiskAnalysis.isStandard(tx)); tx.addInput(new TransactionInput(PARAMS, null, nonStandardScript)); assertEquals(DefaultRiskAnalysis.RuleViolation.SHORTEST_POSSIBLE_PUSHDATA, DefaultRiskAnalysis.isStandard(tx)); tx.clearInputs(); assertEquals(DefaultRiskAnalysis.RuleViolation.NONE, DefaultRiskAnalysis.isStandard(tx)); tx.addOutput(new TransactionOutput(PARAMS, null, COIN, nonStandardScript)); assertEquals(DefaultRiskAnalysis.RuleViolation.SHORTEST_POSSIBLE_PUSHDATA, DefaultRiskAnalysis.isStandard(tx)); }
public static RuleViolation isStandard(Transaction tx) { if (tx.getVersion() > 2 || tx.getVersion() < 1) { log.warn("TX considered non-standard due to unknown version number {}", tx.getVersion()); return RuleViolation.VERSION; } final List<TransactionOutput> outputs = tx.getOutputs(); for (int i = 0; i < outputs.size(); i++) { TransactionOutput output = outputs.get(i); RuleViolation violation = isOutputStandard(output); if (violation != RuleViolation.NONE) { log.warn("TX considered non-standard due to output {} violating rule {}", i, violation); return violation; } } final List<TransactionInput> inputs = tx.getInputs(); for (int i = 0; i < inputs.size(); i++) { TransactionInput input = inputs.get(i); RuleViolation violation = isInputStandard(input); if (violation != RuleViolation.NONE) { log.warn("TX considered non-standard due to input {} violating rule {}", i, violation); return violation; } } return RuleViolation.NONE; }
DefaultRiskAnalysis implements RiskAnalysis { public static RuleViolation isStandard(Transaction tx) { if (tx.getVersion() > 2 || tx.getVersion() < 1) { log.warn("TX considered non-standard due to unknown version number {}", tx.getVersion()); return RuleViolation.VERSION; } final List<TransactionOutput> outputs = tx.getOutputs(); for (int i = 0; i < outputs.size(); i++) { TransactionOutput output = outputs.get(i); RuleViolation violation = isOutputStandard(output); if (violation != RuleViolation.NONE) { log.warn("TX considered non-standard due to output {} violating rule {}", i, violation); return violation; } } final List<TransactionInput> inputs = tx.getInputs(); for (int i = 0; i < inputs.size(); i++) { TransactionInput input = inputs.get(i); RuleViolation violation = isInputStandard(input); if (violation != RuleViolation.NONE) { log.warn("TX considered non-standard due to input {} violating rule {}", i, violation); return violation; } } return RuleViolation.NONE; } }
DefaultRiskAnalysis implements RiskAnalysis { public static RuleViolation isStandard(Transaction tx) { if (tx.getVersion() > 2 || tx.getVersion() < 1) { log.warn("TX considered non-standard due to unknown version number {}", tx.getVersion()); return RuleViolation.VERSION; } final List<TransactionOutput> outputs = tx.getOutputs(); for (int i = 0; i < outputs.size(); i++) { TransactionOutput output = outputs.get(i); RuleViolation violation = isOutputStandard(output); if (violation != RuleViolation.NONE) { log.warn("TX considered non-standard due to output {} violating rule {}", i, violation); return violation; } } final List<TransactionInput> inputs = tx.getInputs(); for (int i = 0; i < inputs.size(); i++) { TransactionInput input = inputs.get(i); RuleViolation violation = isInputStandard(input); if (violation != RuleViolation.NONE) { log.warn("TX considered non-standard due to input {} violating rule {}", i, violation); return violation; } } return RuleViolation.NONE; } private DefaultRiskAnalysis(Wallet wallet, Transaction tx, List<Transaction> dependencies); }
DefaultRiskAnalysis implements RiskAnalysis { public static RuleViolation isStandard(Transaction tx) { if (tx.getVersion() > 2 || tx.getVersion() < 1) { log.warn("TX considered non-standard due to unknown version number {}", tx.getVersion()); return RuleViolation.VERSION; } final List<TransactionOutput> outputs = tx.getOutputs(); for (int i = 0; i < outputs.size(); i++) { TransactionOutput output = outputs.get(i); RuleViolation violation = isOutputStandard(output); if (violation != RuleViolation.NONE) { log.warn("TX considered non-standard due to output {} violating rule {}", i, violation); return violation; } } final List<TransactionInput> inputs = tx.getInputs(); for (int i = 0; i < inputs.size(); i++) { TransactionInput input = inputs.get(i); RuleViolation violation = isInputStandard(input); if (violation != RuleViolation.NONE) { log.warn("TX considered non-standard due to input {} violating rule {}", i, violation); return violation; } } return RuleViolation.NONE; } private DefaultRiskAnalysis(Wallet wallet, Transaction tx, List<Transaction> dependencies); @Override Result analyze(); static RuleViolation isStandard(Transaction tx); static RuleViolation isOutputStandard(TransactionOutput output); static RuleViolation isInputStandard(TransactionInput input); static RuleViolation isInputSignedWithForkId(TransactionInput input, boolean requireForkId); @Nullable Transaction getNonStandard(); @Nullable Transaction getNonFinal(); @Override String toString(); }
DefaultRiskAnalysis implements RiskAnalysis { public static RuleViolation isStandard(Transaction tx) { if (tx.getVersion() > 2 || tx.getVersion() < 1) { log.warn("TX considered non-standard due to unknown version number {}", tx.getVersion()); return RuleViolation.VERSION; } final List<TransactionOutput> outputs = tx.getOutputs(); for (int i = 0; i < outputs.size(); i++) { TransactionOutput output = outputs.get(i); RuleViolation violation = isOutputStandard(output); if (violation != RuleViolation.NONE) { log.warn("TX considered non-standard due to output {} violating rule {}", i, violation); return violation; } } final List<TransactionInput> inputs = tx.getInputs(); for (int i = 0; i < inputs.size(); i++) { TransactionInput input = inputs.get(i); RuleViolation violation = isInputStandard(input); if (violation != RuleViolation.NONE) { log.warn("TX considered non-standard due to input {} violating rule {}", i, violation); return violation; } } return RuleViolation.NONE; } private DefaultRiskAnalysis(Wallet wallet, Transaction tx, List<Transaction> dependencies); @Override Result analyze(); static RuleViolation isStandard(Transaction tx); static RuleViolation isOutputStandard(TransactionOutput output); static RuleViolation isInputStandard(TransactionInput input); static RuleViolation isInputSignedWithForkId(TransactionInput input, boolean requireForkId); @Nullable Transaction getNonStandard(); @Nullable Transaction getNonFinal(); @Override String toString(); static final Coin MIN_ANALYSIS_NONDUST_OUTPUT; static Analyzer FACTORY; }
@Test public void canonicalSignature() { TransactionSignature sig = TransactionSignature.dummy(); Script scriptOk = ScriptBuilder.createInputScript(sig); assertEquals(RuleViolation.NONE, DefaultRiskAnalysis.isInputStandard(new TransactionInput(PARAMS, null, scriptOk.getProgram()))); byte[] sigBytes = sig.encodeToBitcoin(); Script scriptUncanonicalEncoding = new ScriptBuilder().data(Arrays.copyOf(sigBytes, sigBytes.length + 1)) .build(); assertEquals(RuleViolation.SIGNATURE_CANONICAL_ENCODING, DefaultRiskAnalysis.isInputStandard(new TransactionInput(PARAMS, null, scriptUncanonicalEncoding .getProgram()))); }
public static RuleViolation isInputStandard(TransactionInput input) { for (ScriptChunk chunk : input.getScriptSig().getChunks()) { if (chunk.data != null && !chunk.isShortestPossiblePushData()) return RuleViolation.SHORTEST_POSSIBLE_PUSHDATA; if (chunk.isPushData()) { ECDSASignature signature; try { signature = ECKey.ECDSASignature.decodeFromDER(chunk.data); } catch (RuntimeException x) { signature = null; } if (signature != null) { if (!TransactionSignature.isEncodingCanonical(chunk.data)) return RuleViolation.SIGNATURE_CANONICAL_ENCODING; if (!signature.isCanonical()) return RuleViolation.SIGNATURE_CANONICAL_ENCODING; } } } return RuleViolation.NONE; }
DefaultRiskAnalysis implements RiskAnalysis { public static RuleViolation isInputStandard(TransactionInput input) { for (ScriptChunk chunk : input.getScriptSig().getChunks()) { if (chunk.data != null && !chunk.isShortestPossiblePushData()) return RuleViolation.SHORTEST_POSSIBLE_PUSHDATA; if (chunk.isPushData()) { ECDSASignature signature; try { signature = ECKey.ECDSASignature.decodeFromDER(chunk.data); } catch (RuntimeException x) { signature = null; } if (signature != null) { if (!TransactionSignature.isEncodingCanonical(chunk.data)) return RuleViolation.SIGNATURE_CANONICAL_ENCODING; if (!signature.isCanonical()) return RuleViolation.SIGNATURE_CANONICAL_ENCODING; } } } return RuleViolation.NONE; } }
DefaultRiskAnalysis implements RiskAnalysis { public static RuleViolation isInputStandard(TransactionInput input) { for (ScriptChunk chunk : input.getScriptSig().getChunks()) { if (chunk.data != null && !chunk.isShortestPossiblePushData()) return RuleViolation.SHORTEST_POSSIBLE_PUSHDATA; if (chunk.isPushData()) { ECDSASignature signature; try { signature = ECKey.ECDSASignature.decodeFromDER(chunk.data); } catch (RuntimeException x) { signature = null; } if (signature != null) { if (!TransactionSignature.isEncodingCanonical(chunk.data)) return RuleViolation.SIGNATURE_CANONICAL_ENCODING; if (!signature.isCanonical()) return RuleViolation.SIGNATURE_CANONICAL_ENCODING; } } } return RuleViolation.NONE; } private DefaultRiskAnalysis(Wallet wallet, Transaction tx, List<Transaction> dependencies); }
DefaultRiskAnalysis implements RiskAnalysis { public static RuleViolation isInputStandard(TransactionInput input) { for (ScriptChunk chunk : input.getScriptSig().getChunks()) { if (chunk.data != null && !chunk.isShortestPossiblePushData()) return RuleViolation.SHORTEST_POSSIBLE_PUSHDATA; if (chunk.isPushData()) { ECDSASignature signature; try { signature = ECKey.ECDSASignature.decodeFromDER(chunk.data); } catch (RuntimeException x) { signature = null; } if (signature != null) { if (!TransactionSignature.isEncodingCanonical(chunk.data)) return RuleViolation.SIGNATURE_CANONICAL_ENCODING; if (!signature.isCanonical()) return RuleViolation.SIGNATURE_CANONICAL_ENCODING; } } } return RuleViolation.NONE; } private DefaultRiskAnalysis(Wallet wallet, Transaction tx, List<Transaction> dependencies); @Override Result analyze(); static RuleViolation isStandard(Transaction tx); static RuleViolation isOutputStandard(TransactionOutput output); static RuleViolation isInputStandard(TransactionInput input); static RuleViolation isInputSignedWithForkId(TransactionInput input, boolean requireForkId); @Nullable Transaction getNonStandard(); @Nullable Transaction getNonFinal(); @Override String toString(); }
DefaultRiskAnalysis implements RiskAnalysis { public static RuleViolation isInputStandard(TransactionInput input) { for (ScriptChunk chunk : input.getScriptSig().getChunks()) { if (chunk.data != null && !chunk.isShortestPossiblePushData()) return RuleViolation.SHORTEST_POSSIBLE_PUSHDATA; if (chunk.isPushData()) { ECDSASignature signature; try { signature = ECKey.ECDSASignature.decodeFromDER(chunk.data); } catch (RuntimeException x) { signature = null; } if (signature != null) { if (!TransactionSignature.isEncodingCanonical(chunk.data)) return RuleViolation.SIGNATURE_CANONICAL_ENCODING; if (!signature.isCanonical()) return RuleViolation.SIGNATURE_CANONICAL_ENCODING; } } } return RuleViolation.NONE; } private DefaultRiskAnalysis(Wallet wallet, Transaction tx, List<Transaction> dependencies); @Override Result analyze(); static RuleViolation isStandard(Transaction tx); static RuleViolation isOutputStandard(TransactionOutput output); static RuleViolation isInputStandard(TransactionInput input); static RuleViolation isInputSignedWithForkId(TransactionInput input, boolean requireForkId); @Nullable Transaction getNonStandard(); @Nullable Transaction getNonFinal(); @Override String toString(); static final Coin MIN_ANALYSIS_NONDUST_OUTPUT; static Analyzer FACTORY; }
@Test public void standardOutputs() throws Exception { Transaction tx = new Transaction(PARAMS); tx.addInput(PARAMS.getGenesisBlock().getTransactions().get(0).getOutput(0)); tx.addOutput(Coin.CENT, ScriptBuilder.createOutputScript(key1.toAddress(PARAMS))); tx.addOutput(Coin.CENT, ScriptBuilder.createOutputScript(key1)); tx.addOutput(Coin.CENT, ScriptBuilder.createOutputScript(key1)); ImmutableList<ECKey> keys = ImmutableList.of(key1, new ECKey()); tx.addOutput(Coin.CENT, ScriptBuilder.createMultiSigOutputScript(1, keys)); tx.addOutput(Coin.CENT, ScriptBuilder.createMultiSigOutputScript(2, keys)); tx.addOutput(Coin.CENT, ScriptBuilder.createP2SHOutputScript(1, keys)); tx.addOutput(Coin.CENT, ScriptBuilder.createOpReturnScript("hi there".getBytes())); assertEquals(RiskAnalysis.Result.OK, DefaultRiskAnalysis.FACTORY.create(wallet, tx, NO_DEPS).analyze()); }
@Override public Result analyze() { checkState(!analyzed); analyzed = true; Result result = analyzeIsFinal(); if (result != null && result != Result.OK) return result; return analyzeIsStandard(); }
DefaultRiskAnalysis implements RiskAnalysis { @Override public Result analyze() { checkState(!analyzed); analyzed = true; Result result = analyzeIsFinal(); if (result != null && result != Result.OK) return result; return analyzeIsStandard(); } }
DefaultRiskAnalysis implements RiskAnalysis { @Override public Result analyze() { checkState(!analyzed); analyzed = true; Result result = analyzeIsFinal(); if (result != null && result != Result.OK) return result; return analyzeIsStandard(); } private DefaultRiskAnalysis(Wallet wallet, Transaction tx, List<Transaction> dependencies); }
DefaultRiskAnalysis implements RiskAnalysis { @Override public Result analyze() { checkState(!analyzed); analyzed = true; Result result = analyzeIsFinal(); if (result != null && result != Result.OK) return result; return analyzeIsStandard(); } private DefaultRiskAnalysis(Wallet wallet, Transaction tx, List<Transaction> dependencies); @Override Result analyze(); static RuleViolation isStandard(Transaction tx); static RuleViolation isOutputStandard(TransactionOutput output); static RuleViolation isInputStandard(TransactionInput input); static RuleViolation isInputSignedWithForkId(TransactionInput input, boolean requireForkId); @Nullable Transaction getNonStandard(); @Nullable Transaction getNonFinal(); @Override String toString(); }
DefaultRiskAnalysis implements RiskAnalysis { @Override public Result analyze() { checkState(!analyzed); analyzed = true; Result result = analyzeIsFinal(); if (result != null && result != Result.OK) return result; return analyzeIsStandard(); } private DefaultRiskAnalysis(Wallet wallet, Transaction tx, List<Transaction> dependencies); @Override Result analyze(); static RuleViolation isStandard(Transaction tx); static RuleViolation isOutputStandard(TransactionOutput output); static RuleViolation isInputStandard(TransactionInput input); static RuleViolation isInputSignedWithForkId(TransactionInput input, boolean requireForkId); @Nullable Transaction getNonStandard(); @Nullable Transaction getNonFinal(); @Override String toString(); static final Coin MIN_ANALYSIS_NONDUST_OUTPUT; static Analyzer FACTORY; }
@Test public void testP2SHOutputScript() throws Exception { Address p2shAddress = Address.fromBase58(MainNetParams.get(), "35b9vsyH1KoFT5a5KtrKusaCcPLkiSo1tU"); assertTrue(ScriptBuilder.createOutputScript(p2shAddress).isPayToScriptHash()); }
public boolean isPayToScriptHash() { byte[] program = getProgram(); return program.length == 23 && (program[0] & 0xff) == OP_HASH160 && (program[1] & 0xff) == 0x14 && (program[22] & 0xff) == OP_EQUAL; }
Script { public boolean isPayToScriptHash() { byte[] program = getProgram(); return program.length == 23 && (program[0] & 0xff) == OP_HASH160 && (program[1] & 0xff) == 0x14 && (program[22] & 0xff) == OP_EQUAL; } }
Script { public boolean isPayToScriptHash() { byte[] program = getProgram(); return program.length == 23 && (program[0] & 0xff) == OP_HASH160 && (program[1] & 0xff) == 0x14 && (program[22] & 0xff) == OP_EQUAL; } private Script(); Script(List<ScriptChunk> chunks); Script(byte[] programBytes); Script(byte[] programBytes, long creationTimeSeconds); }
Script { public boolean isPayToScriptHash() { byte[] program = getProgram(); return program.length == 23 && (program[0] & 0xff) == OP_HASH160 && (program[1] & 0xff) == 0x14 && (program[22] & 0xff) == OP_EQUAL; } private Script(); Script(List<ScriptChunk> chunks); Script(byte[] programBytes); Script(byte[] programBytes, long creationTimeSeconds); long getCreationTimeSeconds(); void setCreationTimeSeconds(long creationTimeSeconds); @Override String toString(); byte[] getProgram(); List<ScriptChunk> getChunks(); boolean isSentToRawPubKey(); boolean isSentToAddress(); @Deprecated boolean isSentToP2SH(); byte[] getPubKeyHash(); byte[] getPubKey(); byte[] getCLTVPaymentChannelSenderPubKey(); byte[] getCLTVPaymentChannelRecipientPubKey(); BigInteger getCLTVPaymentChannelExpiry(); @Deprecated Address getFromAddress(NetworkParameters params); Address getToAddress(NetworkParameters params); Address getToAddress(NetworkParameters params, boolean forcePayToPubKey); static void writeBytes(OutputStream os, byte[] buf); static byte[] createMultiSigOutputScript(int threshold, List<ECKey> pubkeys); static byte[] createInputScript(byte[] signature, byte[] pubkey); static byte[] createInputScript(byte[] signature); Script createEmptyInputScript(@Nullable ECKey key, @Nullable Script redeemScript); Script getScriptSigWithSignature(Script scriptSig, byte[] sigBytes, int index); int getSigInsertionIndex(Sha256Hash hash, ECKey signingKey); List<ECKey> getPubKeys(); static int getSigOpCount(byte[] program); static long getP2SHSigOpCount(byte[] scriptSig); int getNumberOfSignaturesRequiredToSpend(); int getNumberOfBytesRequiredToSpend(@Nullable ECKey pubKey, @Nullable Script redeemScript); boolean isPayToScriptHash(); boolean isSentToMultiSig(); boolean isSentToCLTVPaymentChannel(); static byte[] removeAllInstancesOf(byte[] inputScript, byte[] chunkToRemove); static byte[] removeAllInstancesOfOp(byte[] inputScript, int opCode); boolean isOpReturn(); @Deprecated static void executeScript(@Nullable Transaction txContainingThis, long index, Script script, LinkedList<byte[]> stack, boolean enforceNullDummy); @Deprecated static void executeScript(@Nullable Transaction txContainingThis, long index, Script script, LinkedList<byte[]> stack, Set<VerifyFlag> verifyFlags); static void executeScript(@Nullable Transaction txContainingThis, long index, Script script, LinkedList<byte[]> stack, Coin value, Set<VerifyFlag> verifyFlags); @Deprecated void correctlySpends(Transaction txContainingThis, long scriptSigIndex, Script scriptPubKey); @Deprecated void correctlySpends(Transaction txContainingThis, long scriptSigIndex, Script scriptPubKey, Set<VerifyFlag> verifyFlags); void correctlySpends(Transaction txContainingThis, long scriptSigIndex, Script scriptPubKey, Coin value, Set<VerifyFlag> verifyFlags); ScriptType getScriptType(); @Override boolean equals(Object o); @Override int hashCode(); }
Script { public boolean isPayToScriptHash() { byte[] program = getProgram(); return program.length == 23 && (program[0] & 0xff) == OP_HASH160 && (program[1] & 0xff) == 0x14 && (program[22] & 0xff) == OP_EQUAL; } private Script(); Script(List<ScriptChunk> chunks); Script(byte[] programBytes); Script(byte[] programBytes, long creationTimeSeconds); long getCreationTimeSeconds(); void setCreationTimeSeconds(long creationTimeSeconds); @Override String toString(); byte[] getProgram(); List<ScriptChunk> getChunks(); boolean isSentToRawPubKey(); boolean isSentToAddress(); @Deprecated boolean isSentToP2SH(); byte[] getPubKeyHash(); byte[] getPubKey(); byte[] getCLTVPaymentChannelSenderPubKey(); byte[] getCLTVPaymentChannelRecipientPubKey(); BigInteger getCLTVPaymentChannelExpiry(); @Deprecated Address getFromAddress(NetworkParameters params); Address getToAddress(NetworkParameters params); Address getToAddress(NetworkParameters params, boolean forcePayToPubKey); static void writeBytes(OutputStream os, byte[] buf); static byte[] createMultiSigOutputScript(int threshold, List<ECKey> pubkeys); static byte[] createInputScript(byte[] signature, byte[] pubkey); static byte[] createInputScript(byte[] signature); Script createEmptyInputScript(@Nullable ECKey key, @Nullable Script redeemScript); Script getScriptSigWithSignature(Script scriptSig, byte[] sigBytes, int index); int getSigInsertionIndex(Sha256Hash hash, ECKey signingKey); List<ECKey> getPubKeys(); static int getSigOpCount(byte[] program); static long getP2SHSigOpCount(byte[] scriptSig); int getNumberOfSignaturesRequiredToSpend(); int getNumberOfBytesRequiredToSpend(@Nullable ECKey pubKey, @Nullable Script redeemScript); boolean isPayToScriptHash(); boolean isSentToMultiSig(); boolean isSentToCLTVPaymentChannel(); static byte[] removeAllInstancesOf(byte[] inputScript, byte[] chunkToRemove); static byte[] removeAllInstancesOfOp(byte[] inputScript, int opCode); boolean isOpReturn(); @Deprecated static void executeScript(@Nullable Transaction txContainingThis, long index, Script script, LinkedList<byte[]> stack, boolean enforceNullDummy); @Deprecated static void executeScript(@Nullable Transaction txContainingThis, long index, Script script, LinkedList<byte[]> stack, Set<VerifyFlag> verifyFlags); static void executeScript(@Nullable Transaction txContainingThis, long index, Script script, LinkedList<byte[]> stack, Coin value, Set<VerifyFlag> verifyFlags); @Deprecated void correctlySpends(Transaction txContainingThis, long scriptSigIndex, Script scriptPubKey); @Deprecated void correctlySpends(Transaction txContainingThis, long scriptSigIndex, Script scriptPubKey, Set<VerifyFlag> verifyFlags); void correctlySpends(Transaction txContainingThis, long scriptSigIndex, Script scriptPubKey, Coin value, Set<VerifyFlag> verifyFlags); ScriptType getScriptType(); @Override boolean equals(Object o); @Override int hashCode(); static final EnumSet<VerifyFlag> ALL_VERIFY_FLAGS; static final long MAX_SCRIPT_ELEMENT_SIZE; static final int SIG_SIZE; static final int MAX_P2SH_SIGOPS; }
@Test public void testIp() throws Exception { byte[] bytes = HEX.decode("41043e96222332ea7848323c08116dddafbfa917b8e37f0bdf63841628267148588a09a43540942d58d49717ad3fabfe14978cf4f0a8b84d2435dad16e9aa4d7f935ac"); Script s = new Script(bytes); assertTrue(s.isSentToRawPubKey()); }
public boolean isSentToRawPubKey() { return chunks.size() == 2 && chunks.get(1).equalsOpCode(OP_CHECKSIG) && !chunks.get(0).isOpCode() && chunks.get(0).data.length > 1; }
Script { public boolean isSentToRawPubKey() { return chunks.size() == 2 && chunks.get(1).equalsOpCode(OP_CHECKSIG) && !chunks.get(0).isOpCode() && chunks.get(0).data.length > 1; } }
Script { public boolean isSentToRawPubKey() { return chunks.size() == 2 && chunks.get(1).equalsOpCode(OP_CHECKSIG) && !chunks.get(0).isOpCode() && chunks.get(0).data.length > 1; } private Script(); Script(List<ScriptChunk> chunks); Script(byte[] programBytes); Script(byte[] programBytes, long creationTimeSeconds); }
Script { public boolean isSentToRawPubKey() { return chunks.size() == 2 && chunks.get(1).equalsOpCode(OP_CHECKSIG) && !chunks.get(0).isOpCode() && chunks.get(0).data.length > 1; } private Script(); Script(List<ScriptChunk> chunks); Script(byte[] programBytes); Script(byte[] programBytes, long creationTimeSeconds); long getCreationTimeSeconds(); void setCreationTimeSeconds(long creationTimeSeconds); @Override String toString(); byte[] getProgram(); List<ScriptChunk> getChunks(); boolean isSentToRawPubKey(); boolean isSentToAddress(); @Deprecated boolean isSentToP2SH(); byte[] getPubKeyHash(); byte[] getPubKey(); byte[] getCLTVPaymentChannelSenderPubKey(); byte[] getCLTVPaymentChannelRecipientPubKey(); BigInteger getCLTVPaymentChannelExpiry(); @Deprecated Address getFromAddress(NetworkParameters params); Address getToAddress(NetworkParameters params); Address getToAddress(NetworkParameters params, boolean forcePayToPubKey); static void writeBytes(OutputStream os, byte[] buf); static byte[] createMultiSigOutputScript(int threshold, List<ECKey> pubkeys); static byte[] createInputScript(byte[] signature, byte[] pubkey); static byte[] createInputScript(byte[] signature); Script createEmptyInputScript(@Nullable ECKey key, @Nullable Script redeemScript); Script getScriptSigWithSignature(Script scriptSig, byte[] sigBytes, int index); int getSigInsertionIndex(Sha256Hash hash, ECKey signingKey); List<ECKey> getPubKeys(); static int getSigOpCount(byte[] program); static long getP2SHSigOpCount(byte[] scriptSig); int getNumberOfSignaturesRequiredToSpend(); int getNumberOfBytesRequiredToSpend(@Nullable ECKey pubKey, @Nullable Script redeemScript); boolean isPayToScriptHash(); boolean isSentToMultiSig(); boolean isSentToCLTVPaymentChannel(); static byte[] removeAllInstancesOf(byte[] inputScript, byte[] chunkToRemove); static byte[] removeAllInstancesOfOp(byte[] inputScript, int opCode); boolean isOpReturn(); @Deprecated static void executeScript(@Nullable Transaction txContainingThis, long index, Script script, LinkedList<byte[]> stack, boolean enforceNullDummy); @Deprecated static void executeScript(@Nullable Transaction txContainingThis, long index, Script script, LinkedList<byte[]> stack, Set<VerifyFlag> verifyFlags); static void executeScript(@Nullable Transaction txContainingThis, long index, Script script, LinkedList<byte[]> stack, Coin value, Set<VerifyFlag> verifyFlags); @Deprecated void correctlySpends(Transaction txContainingThis, long scriptSigIndex, Script scriptPubKey); @Deprecated void correctlySpends(Transaction txContainingThis, long scriptSigIndex, Script scriptPubKey, Set<VerifyFlag> verifyFlags); void correctlySpends(Transaction txContainingThis, long scriptSigIndex, Script scriptPubKey, Coin value, Set<VerifyFlag> verifyFlags); ScriptType getScriptType(); @Override boolean equals(Object o); @Override int hashCode(); }
Script { public boolean isSentToRawPubKey() { return chunks.size() == 2 && chunks.get(1).equalsOpCode(OP_CHECKSIG) && !chunks.get(0).isOpCode() && chunks.get(0).data.length > 1; } private Script(); Script(List<ScriptChunk> chunks); Script(byte[] programBytes); Script(byte[] programBytes, long creationTimeSeconds); long getCreationTimeSeconds(); void setCreationTimeSeconds(long creationTimeSeconds); @Override String toString(); byte[] getProgram(); List<ScriptChunk> getChunks(); boolean isSentToRawPubKey(); boolean isSentToAddress(); @Deprecated boolean isSentToP2SH(); byte[] getPubKeyHash(); byte[] getPubKey(); byte[] getCLTVPaymentChannelSenderPubKey(); byte[] getCLTVPaymentChannelRecipientPubKey(); BigInteger getCLTVPaymentChannelExpiry(); @Deprecated Address getFromAddress(NetworkParameters params); Address getToAddress(NetworkParameters params); Address getToAddress(NetworkParameters params, boolean forcePayToPubKey); static void writeBytes(OutputStream os, byte[] buf); static byte[] createMultiSigOutputScript(int threshold, List<ECKey> pubkeys); static byte[] createInputScript(byte[] signature, byte[] pubkey); static byte[] createInputScript(byte[] signature); Script createEmptyInputScript(@Nullable ECKey key, @Nullable Script redeemScript); Script getScriptSigWithSignature(Script scriptSig, byte[] sigBytes, int index); int getSigInsertionIndex(Sha256Hash hash, ECKey signingKey); List<ECKey> getPubKeys(); static int getSigOpCount(byte[] program); static long getP2SHSigOpCount(byte[] scriptSig); int getNumberOfSignaturesRequiredToSpend(); int getNumberOfBytesRequiredToSpend(@Nullable ECKey pubKey, @Nullable Script redeemScript); boolean isPayToScriptHash(); boolean isSentToMultiSig(); boolean isSentToCLTVPaymentChannel(); static byte[] removeAllInstancesOf(byte[] inputScript, byte[] chunkToRemove); static byte[] removeAllInstancesOfOp(byte[] inputScript, int opCode); boolean isOpReturn(); @Deprecated static void executeScript(@Nullable Transaction txContainingThis, long index, Script script, LinkedList<byte[]> stack, boolean enforceNullDummy); @Deprecated static void executeScript(@Nullable Transaction txContainingThis, long index, Script script, LinkedList<byte[]> stack, Set<VerifyFlag> verifyFlags); static void executeScript(@Nullable Transaction txContainingThis, long index, Script script, LinkedList<byte[]> stack, Coin value, Set<VerifyFlag> verifyFlags); @Deprecated void correctlySpends(Transaction txContainingThis, long scriptSigIndex, Script scriptPubKey); @Deprecated void correctlySpends(Transaction txContainingThis, long scriptSigIndex, Script scriptPubKey, Set<VerifyFlag> verifyFlags); void correctlySpends(Transaction txContainingThis, long scriptSigIndex, Script scriptPubKey, Coin value, Set<VerifyFlag> verifyFlags); ScriptType getScriptType(); @Override boolean equals(Object o); @Override int hashCode(); static final EnumSet<VerifyFlag> ALL_VERIFY_FLAGS; static final long MAX_SCRIPT_ELEMENT_SIZE; static final int SIG_SIZE; static final int MAX_P2SH_SIGOPS; }
@Test public void testOp0() { Transaction tx = new Transaction(PARAMS); tx.addInput(new TransactionInput(PARAMS, tx, new byte[] {})); Script script = new ScriptBuilder().smallNum(0).build(); LinkedList<byte[]> stack = new LinkedList<byte[]>(); Script.executeScript(tx, 0, script, stack, Script.ALL_VERIFY_FLAGS); assertEquals("OP_0 push length", 0, stack.get(0).length); }
@Deprecated public static void executeScript(@Nullable Transaction txContainingThis, long index, Script script, LinkedList<byte[]> stack, boolean enforceNullDummy) throws ScriptException { final EnumSet<VerifyFlag> flags = enforceNullDummy ? EnumSet.of(VerifyFlag.NULLDUMMY) : EnumSet.noneOf(VerifyFlag.class); executeScript(txContainingThis, index, script, stack, Coin.ZERO, flags); }
Script { @Deprecated public static void executeScript(@Nullable Transaction txContainingThis, long index, Script script, LinkedList<byte[]> stack, boolean enforceNullDummy) throws ScriptException { final EnumSet<VerifyFlag> flags = enforceNullDummy ? EnumSet.of(VerifyFlag.NULLDUMMY) : EnumSet.noneOf(VerifyFlag.class); executeScript(txContainingThis, index, script, stack, Coin.ZERO, flags); } }
Script { @Deprecated public static void executeScript(@Nullable Transaction txContainingThis, long index, Script script, LinkedList<byte[]> stack, boolean enforceNullDummy) throws ScriptException { final EnumSet<VerifyFlag> flags = enforceNullDummy ? EnumSet.of(VerifyFlag.NULLDUMMY) : EnumSet.noneOf(VerifyFlag.class); executeScript(txContainingThis, index, script, stack, Coin.ZERO, flags); } private Script(); Script(List<ScriptChunk> chunks); Script(byte[] programBytes); Script(byte[] programBytes, long creationTimeSeconds); }
Script { @Deprecated public static void executeScript(@Nullable Transaction txContainingThis, long index, Script script, LinkedList<byte[]> stack, boolean enforceNullDummy) throws ScriptException { final EnumSet<VerifyFlag> flags = enforceNullDummy ? EnumSet.of(VerifyFlag.NULLDUMMY) : EnumSet.noneOf(VerifyFlag.class); executeScript(txContainingThis, index, script, stack, Coin.ZERO, flags); } private Script(); Script(List<ScriptChunk> chunks); Script(byte[] programBytes); Script(byte[] programBytes, long creationTimeSeconds); long getCreationTimeSeconds(); void setCreationTimeSeconds(long creationTimeSeconds); @Override String toString(); byte[] getProgram(); List<ScriptChunk> getChunks(); boolean isSentToRawPubKey(); boolean isSentToAddress(); @Deprecated boolean isSentToP2SH(); byte[] getPubKeyHash(); byte[] getPubKey(); byte[] getCLTVPaymentChannelSenderPubKey(); byte[] getCLTVPaymentChannelRecipientPubKey(); BigInteger getCLTVPaymentChannelExpiry(); @Deprecated Address getFromAddress(NetworkParameters params); Address getToAddress(NetworkParameters params); Address getToAddress(NetworkParameters params, boolean forcePayToPubKey); static void writeBytes(OutputStream os, byte[] buf); static byte[] createMultiSigOutputScript(int threshold, List<ECKey> pubkeys); static byte[] createInputScript(byte[] signature, byte[] pubkey); static byte[] createInputScript(byte[] signature); Script createEmptyInputScript(@Nullable ECKey key, @Nullable Script redeemScript); Script getScriptSigWithSignature(Script scriptSig, byte[] sigBytes, int index); int getSigInsertionIndex(Sha256Hash hash, ECKey signingKey); List<ECKey> getPubKeys(); static int getSigOpCount(byte[] program); static long getP2SHSigOpCount(byte[] scriptSig); int getNumberOfSignaturesRequiredToSpend(); int getNumberOfBytesRequiredToSpend(@Nullable ECKey pubKey, @Nullable Script redeemScript); boolean isPayToScriptHash(); boolean isSentToMultiSig(); boolean isSentToCLTVPaymentChannel(); static byte[] removeAllInstancesOf(byte[] inputScript, byte[] chunkToRemove); static byte[] removeAllInstancesOfOp(byte[] inputScript, int opCode); boolean isOpReturn(); @Deprecated static void executeScript(@Nullable Transaction txContainingThis, long index, Script script, LinkedList<byte[]> stack, boolean enforceNullDummy); @Deprecated static void executeScript(@Nullable Transaction txContainingThis, long index, Script script, LinkedList<byte[]> stack, Set<VerifyFlag> verifyFlags); static void executeScript(@Nullable Transaction txContainingThis, long index, Script script, LinkedList<byte[]> stack, Coin value, Set<VerifyFlag> verifyFlags); @Deprecated void correctlySpends(Transaction txContainingThis, long scriptSigIndex, Script scriptPubKey); @Deprecated void correctlySpends(Transaction txContainingThis, long scriptSigIndex, Script scriptPubKey, Set<VerifyFlag> verifyFlags); void correctlySpends(Transaction txContainingThis, long scriptSigIndex, Script scriptPubKey, Coin value, Set<VerifyFlag> verifyFlags); ScriptType getScriptType(); @Override boolean equals(Object o); @Override int hashCode(); }
Script { @Deprecated public static void executeScript(@Nullable Transaction txContainingThis, long index, Script script, LinkedList<byte[]> stack, boolean enforceNullDummy) throws ScriptException { final EnumSet<VerifyFlag> flags = enforceNullDummy ? EnumSet.of(VerifyFlag.NULLDUMMY) : EnumSet.noneOf(VerifyFlag.class); executeScript(txContainingThis, index, script, stack, Coin.ZERO, flags); } private Script(); Script(List<ScriptChunk> chunks); Script(byte[] programBytes); Script(byte[] programBytes, long creationTimeSeconds); long getCreationTimeSeconds(); void setCreationTimeSeconds(long creationTimeSeconds); @Override String toString(); byte[] getProgram(); List<ScriptChunk> getChunks(); boolean isSentToRawPubKey(); boolean isSentToAddress(); @Deprecated boolean isSentToP2SH(); byte[] getPubKeyHash(); byte[] getPubKey(); byte[] getCLTVPaymentChannelSenderPubKey(); byte[] getCLTVPaymentChannelRecipientPubKey(); BigInteger getCLTVPaymentChannelExpiry(); @Deprecated Address getFromAddress(NetworkParameters params); Address getToAddress(NetworkParameters params); Address getToAddress(NetworkParameters params, boolean forcePayToPubKey); static void writeBytes(OutputStream os, byte[] buf); static byte[] createMultiSigOutputScript(int threshold, List<ECKey> pubkeys); static byte[] createInputScript(byte[] signature, byte[] pubkey); static byte[] createInputScript(byte[] signature); Script createEmptyInputScript(@Nullable ECKey key, @Nullable Script redeemScript); Script getScriptSigWithSignature(Script scriptSig, byte[] sigBytes, int index); int getSigInsertionIndex(Sha256Hash hash, ECKey signingKey); List<ECKey> getPubKeys(); static int getSigOpCount(byte[] program); static long getP2SHSigOpCount(byte[] scriptSig); int getNumberOfSignaturesRequiredToSpend(); int getNumberOfBytesRequiredToSpend(@Nullable ECKey pubKey, @Nullable Script redeemScript); boolean isPayToScriptHash(); boolean isSentToMultiSig(); boolean isSentToCLTVPaymentChannel(); static byte[] removeAllInstancesOf(byte[] inputScript, byte[] chunkToRemove); static byte[] removeAllInstancesOfOp(byte[] inputScript, int opCode); boolean isOpReturn(); @Deprecated static void executeScript(@Nullable Transaction txContainingThis, long index, Script script, LinkedList<byte[]> stack, boolean enforceNullDummy); @Deprecated static void executeScript(@Nullable Transaction txContainingThis, long index, Script script, LinkedList<byte[]> stack, Set<VerifyFlag> verifyFlags); static void executeScript(@Nullable Transaction txContainingThis, long index, Script script, LinkedList<byte[]> stack, Coin value, Set<VerifyFlag> verifyFlags); @Deprecated void correctlySpends(Transaction txContainingThis, long scriptSigIndex, Script scriptPubKey); @Deprecated void correctlySpends(Transaction txContainingThis, long scriptSigIndex, Script scriptPubKey, Set<VerifyFlag> verifyFlags); void correctlySpends(Transaction txContainingThis, long scriptSigIndex, Script scriptPubKey, Coin value, Set<VerifyFlag> verifyFlags); ScriptType getScriptType(); @Override boolean equals(Object o); @Override int hashCode(); static final EnumSet<VerifyFlag> ALL_VERIFY_FLAGS; static final long MAX_SCRIPT_ELEMENT_SIZE; static final int SIG_SIZE; static final int MAX_P2SH_SIGOPS; }
@Test public void dataDrivenValidScripts() throws Exception { JsonNode json = new ObjectMapper().readTree(new InputStreamReader(getClass().getResourceAsStream( "script_valid.json"), Charsets.UTF_8)); for (JsonNode test : json) { Script scriptSig = parseScriptString(test.get(0).asText()); Script scriptPubKey = parseScriptString(test.get(1).asText()); Set<VerifyFlag> verifyFlags = parseVerifyFlags(test.get(2).asText()); try { scriptSig.correctlySpends(new Transaction(PARAMS), 0, scriptPubKey, verifyFlags); } catch (ScriptException e) { System.err.println(test); System.err.flush(); throw e; } } }
@Deprecated public void correctlySpends(Transaction txContainingThis, long scriptSigIndex, Script scriptPubKey) throws ScriptException { correctlySpends(txContainingThis, scriptSigIndex, scriptPubKey, Coin.ZERO, ALL_VERIFY_FLAGS); }
Script { @Deprecated public void correctlySpends(Transaction txContainingThis, long scriptSigIndex, Script scriptPubKey) throws ScriptException { correctlySpends(txContainingThis, scriptSigIndex, scriptPubKey, Coin.ZERO, ALL_VERIFY_FLAGS); } }
Script { @Deprecated public void correctlySpends(Transaction txContainingThis, long scriptSigIndex, Script scriptPubKey) throws ScriptException { correctlySpends(txContainingThis, scriptSigIndex, scriptPubKey, Coin.ZERO, ALL_VERIFY_FLAGS); } private Script(); Script(List<ScriptChunk> chunks); Script(byte[] programBytes); Script(byte[] programBytes, long creationTimeSeconds); }
Script { @Deprecated public void correctlySpends(Transaction txContainingThis, long scriptSigIndex, Script scriptPubKey) throws ScriptException { correctlySpends(txContainingThis, scriptSigIndex, scriptPubKey, Coin.ZERO, ALL_VERIFY_FLAGS); } private Script(); Script(List<ScriptChunk> chunks); Script(byte[] programBytes); Script(byte[] programBytes, long creationTimeSeconds); long getCreationTimeSeconds(); void setCreationTimeSeconds(long creationTimeSeconds); @Override String toString(); byte[] getProgram(); List<ScriptChunk> getChunks(); boolean isSentToRawPubKey(); boolean isSentToAddress(); @Deprecated boolean isSentToP2SH(); byte[] getPubKeyHash(); byte[] getPubKey(); byte[] getCLTVPaymentChannelSenderPubKey(); byte[] getCLTVPaymentChannelRecipientPubKey(); BigInteger getCLTVPaymentChannelExpiry(); @Deprecated Address getFromAddress(NetworkParameters params); Address getToAddress(NetworkParameters params); Address getToAddress(NetworkParameters params, boolean forcePayToPubKey); static void writeBytes(OutputStream os, byte[] buf); static byte[] createMultiSigOutputScript(int threshold, List<ECKey> pubkeys); static byte[] createInputScript(byte[] signature, byte[] pubkey); static byte[] createInputScript(byte[] signature); Script createEmptyInputScript(@Nullable ECKey key, @Nullable Script redeemScript); Script getScriptSigWithSignature(Script scriptSig, byte[] sigBytes, int index); int getSigInsertionIndex(Sha256Hash hash, ECKey signingKey); List<ECKey> getPubKeys(); static int getSigOpCount(byte[] program); static long getP2SHSigOpCount(byte[] scriptSig); int getNumberOfSignaturesRequiredToSpend(); int getNumberOfBytesRequiredToSpend(@Nullable ECKey pubKey, @Nullable Script redeemScript); boolean isPayToScriptHash(); boolean isSentToMultiSig(); boolean isSentToCLTVPaymentChannel(); static byte[] removeAllInstancesOf(byte[] inputScript, byte[] chunkToRemove); static byte[] removeAllInstancesOfOp(byte[] inputScript, int opCode); boolean isOpReturn(); @Deprecated static void executeScript(@Nullable Transaction txContainingThis, long index, Script script, LinkedList<byte[]> stack, boolean enforceNullDummy); @Deprecated static void executeScript(@Nullable Transaction txContainingThis, long index, Script script, LinkedList<byte[]> stack, Set<VerifyFlag> verifyFlags); static void executeScript(@Nullable Transaction txContainingThis, long index, Script script, LinkedList<byte[]> stack, Coin value, Set<VerifyFlag> verifyFlags); @Deprecated void correctlySpends(Transaction txContainingThis, long scriptSigIndex, Script scriptPubKey); @Deprecated void correctlySpends(Transaction txContainingThis, long scriptSigIndex, Script scriptPubKey, Set<VerifyFlag> verifyFlags); void correctlySpends(Transaction txContainingThis, long scriptSigIndex, Script scriptPubKey, Coin value, Set<VerifyFlag> verifyFlags); ScriptType getScriptType(); @Override boolean equals(Object o); @Override int hashCode(); }
Script { @Deprecated public void correctlySpends(Transaction txContainingThis, long scriptSigIndex, Script scriptPubKey) throws ScriptException { correctlySpends(txContainingThis, scriptSigIndex, scriptPubKey, Coin.ZERO, ALL_VERIFY_FLAGS); } private Script(); Script(List<ScriptChunk> chunks); Script(byte[] programBytes); Script(byte[] programBytes, long creationTimeSeconds); long getCreationTimeSeconds(); void setCreationTimeSeconds(long creationTimeSeconds); @Override String toString(); byte[] getProgram(); List<ScriptChunk> getChunks(); boolean isSentToRawPubKey(); boolean isSentToAddress(); @Deprecated boolean isSentToP2SH(); byte[] getPubKeyHash(); byte[] getPubKey(); byte[] getCLTVPaymentChannelSenderPubKey(); byte[] getCLTVPaymentChannelRecipientPubKey(); BigInteger getCLTVPaymentChannelExpiry(); @Deprecated Address getFromAddress(NetworkParameters params); Address getToAddress(NetworkParameters params); Address getToAddress(NetworkParameters params, boolean forcePayToPubKey); static void writeBytes(OutputStream os, byte[] buf); static byte[] createMultiSigOutputScript(int threshold, List<ECKey> pubkeys); static byte[] createInputScript(byte[] signature, byte[] pubkey); static byte[] createInputScript(byte[] signature); Script createEmptyInputScript(@Nullable ECKey key, @Nullable Script redeemScript); Script getScriptSigWithSignature(Script scriptSig, byte[] sigBytes, int index); int getSigInsertionIndex(Sha256Hash hash, ECKey signingKey); List<ECKey> getPubKeys(); static int getSigOpCount(byte[] program); static long getP2SHSigOpCount(byte[] scriptSig); int getNumberOfSignaturesRequiredToSpend(); int getNumberOfBytesRequiredToSpend(@Nullable ECKey pubKey, @Nullable Script redeemScript); boolean isPayToScriptHash(); boolean isSentToMultiSig(); boolean isSentToCLTVPaymentChannel(); static byte[] removeAllInstancesOf(byte[] inputScript, byte[] chunkToRemove); static byte[] removeAllInstancesOfOp(byte[] inputScript, int opCode); boolean isOpReturn(); @Deprecated static void executeScript(@Nullable Transaction txContainingThis, long index, Script script, LinkedList<byte[]> stack, boolean enforceNullDummy); @Deprecated static void executeScript(@Nullable Transaction txContainingThis, long index, Script script, LinkedList<byte[]> stack, Set<VerifyFlag> verifyFlags); static void executeScript(@Nullable Transaction txContainingThis, long index, Script script, LinkedList<byte[]> stack, Coin value, Set<VerifyFlag> verifyFlags); @Deprecated void correctlySpends(Transaction txContainingThis, long scriptSigIndex, Script scriptPubKey); @Deprecated void correctlySpends(Transaction txContainingThis, long scriptSigIndex, Script scriptPubKey, Set<VerifyFlag> verifyFlags); void correctlySpends(Transaction txContainingThis, long scriptSigIndex, Script scriptPubKey, Coin value, Set<VerifyFlag> verifyFlags); ScriptType getScriptType(); @Override boolean equals(Object o); @Override int hashCode(); static final EnumSet<VerifyFlag> ALL_VERIFY_FLAGS; static final long MAX_SCRIPT_ELEMENT_SIZE; static final int SIG_SIZE; static final int MAX_P2SH_SIGOPS; }
@Test public void dataDrivenInvalidScripts() throws Exception { JsonNode json = new ObjectMapper().readTree(new InputStreamReader(getClass().getResourceAsStream( "script_invalid.json"), Charsets.UTF_8)); for (JsonNode test : json) { try { Script scriptSig = parseScriptString(test.get(0).asText()); Script scriptPubKey = parseScriptString(test.get(1).asText()); Set<VerifyFlag> verifyFlags = parseVerifyFlags(test.get(2).asText()); scriptSig.correctlySpends(new Transaction(PARAMS), 0, scriptPubKey, verifyFlags); System.err.println(test); System.err.flush(); fail(); } catch (VerificationException e) { } } }
@Deprecated public void correctlySpends(Transaction txContainingThis, long scriptSigIndex, Script scriptPubKey) throws ScriptException { correctlySpends(txContainingThis, scriptSigIndex, scriptPubKey, Coin.ZERO, ALL_VERIFY_FLAGS); }
Script { @Deprecated public void correctlySpends(Transaction txContainingThis, long scriptSigIndex, Script scriptPubKey) throws ScriptException { correctlySpends(txContainingThis, scriptSigIndex, scriptPubKey, Coin.ZERO, ALL_VERIFY_FLAGS); } }
Script { @Deprecated public void correctlySpends(Transaction txContainingThis, long scriptSigIndex, Script scriptPubKey) throws ScriptException { correctlySpends(txContainingThis, scriptSigIndex, scriptPubKey, Coin.ZERO, ALL_VERIFY_FLAGS); } private Script(); Script(List<ScriptChunk> chunks); Script(byte[] programBytes); Script(byte[] programBytes, long creationTimeSeconds); }
Script { @Deprecated public void correctlySpends(Transaction txContainingThis, long scriptSigIndex, Script scriptPubKey) throws ScriptException { correctlySpends(txContainingThis, scriptSigIndex, scriptPubKey, Coin.ZERO, ALL_VERIFY_FLAGS); } private Script(); Script(List<ScriptChunk> chunks); Script(byte[] programBytes); Script(byte[] programBytes, long creationTimeSeconds); long getCreationTimeSeconds(); void setCreationTimeSeconds(long creationTimeSeconds); @Override String toString(); byte[] getProgram(); List<ScriptChunk> getChunks(); boolean isSentToRawPubKey(); boolean isSentToAddress(); @Deprecated boolean isSentToP2SH(); byte[] getPubKeyHash(); byte[] getPubKey(); byte[] getCLTVPaymentChannelSenderPubKey(); byte[] getCLTVPaymentChannelRecipientPubKey(); BigInteger getCLTVPaymentChannelExpiry(); @Deprecated Address getFromAddress(NetworkParameters params); Address getToAddress(NetworkParameters params); Address getToAddress(NetworkParameters params, boolean forcePayToPubKey); static void writeBytes(OutputStream os, byte[] buf); static byte[] createMultiSigOutputScript(int threshold, List<ECKey> pubkeys); static byte[] createInputScript(byte[] signature, byte[] pubkey); static byte[] createInputScript(byte[] signature); Script createEmptyInputScript(@Nullable ECKey key, @Nullable Script redeemScript); Script getScriptSigWithSignature(Script scriptSig, byte[] sigBytes, int index); int getSigInsertionIndex(Sha256Hash hash, ECKey signingKey); List<ECKey> getPubKeys(); static int getSigOpCount(byte[] program); static long getP2SHSigOpCount(byte[] scriptSig); int getNumberOfSignaturesRequiredToSpend(); int getNumberOfBytesRequiredToSpend(@Nullable ECKey pubKey, @Nullable Script redeemScript); boolean isPayToScriptHash(); boolean isSentToMultiSig(); boolean isSentToCLTVPaymentChannel(); static byte[] removeAllInstancesOf(byte[] inputScript, byte[] chunkToRemove); static byte[] removeAllInstancesOfOp(byte[] inputScript, int opCode); boolean isOpReturn(); @Deprecated static void executeScript(@Nullable Transaction txContainingThis, long index, Script script, LinkedList<byte[]> stack, boolean enforceNullDummy); @Deprecated static void executeScript(@Nullable Transaction txContainingThis, long index, Script script, LinkedList<byte[]> stack, Set<VerifyFlag> verifyFlags); static void executeScript(@Nullable Transaction txContainingThis, long index, Script script, LinkedList<byte[]> stack, Coin value, Set<VerifyFlag> verifyFlags); @Deprecated void correctlySpends(Transaction txContainingThis, long scriptSigIndex, Script scriptPubKey); @Deprecated void correctlySpends(Transaction txContainingThis, long scriptSigIndex, Script scriptPubKey, Set<VerifyFlag> verifyFlags); void correctlySpends(Transaction txContainingThis, long scriptSigIndex, Script scriptPubKey, Coin value, Set<VerifyFlag> verifyFlags); ScriptType getScriptType(); @Override boolean equals(Object o); @Override int hashCode(); }
Script { @Deprecated public void correctlySpends(Transaction txContainingThis, long scriptSigIndex, Script scriptPubKey) throws ScriptException { correctlySpends(txContainingThis, scriptSigIndex, scriptPubKey, Coin.ZERO, ALL_VERIFY_FLAGS); } private Script(); Script(List<ScriptChunk> chunks); Script(byte[] programBytes); Script(byte[] programBytes, long creationTimeSeconds); long getCreationTimeSeconds(); void setCreationTimeSeconds(long creationTimeSeconds); @Override String toString(); byte[] getProgram(); List<ScriptChunk> getChunks(); boolean isSentToRawPubKey(); boolean isSentToAddress(); @Deprecated boolean isSentToP2SH(); byte[] getPubKeyHash(); byte[] getPubKey(); byte[] getCLTVPaymentChannelSenderPubKey(); byte[] getCLTVPaymentChannelRecipientPubKey(); BigInteger getCLTVPaymentChannelExpiry(); @Deprecated Address getFromAddress(NetworkParameters params); Address getToAddress(NetworkParameters params); Address getToAddress(NetworkParameters params, boolean forcePayToPubKey); static void writeBytes(OutputStream os, byte[] buf); static byte[] createMultiSigOutputScript(int threshold, List<ECKey> pubkeys); static byte[] createInputScript(byte[] signature, byte[] pubkey); static byte[] createInputScript(byte[] signature); Script createEmptyInputScript(@Nullable ECKey key, @Nullable Script redeemScript); Script getScriptSigWithSignature(Script scriptSig, byte[] sigBytes, int index); int getSigInsertionIndex(Sha256Hash hash, ECKey signingKey); List<ECKey> getPubKeys(); static int getSigOpCount(byte[] program); static long getP2SHSigOpCount(byte[] scriptSig); int getNumberOfSignaturesRequiredToSpend(); int getNumberOfBytesRequiredToSpend(@Nullable ECKey pubKey, @Nullable Script redeemScript); boolean isPayToScriptHash(); boolean isSentToMultiSig(); boolean isSentToCLTVPaymentChannel(); static byte[] removeAllInstancesOf(byte[] inputScript, byte[] chunkToRemove); static byte[] removeAllInstancesOfOp(byte[] inputScript, int opCode); boolean isOpReturn(); @Deprecated static void executeScript(@Nullable Transaction txContainingThis, long index, Script script, LinkedList<byte[]> stack, boolean enforceNullDummy); @Deprecated static void executeScript(@Nullable Transaction txContainingThis, long index, Script script, LinkedList<byte[]> stack, Set<VerifyFlag> verifyFlags); static void executeScript(@Nullable Transaction txContainingThis, long index, Script script, LinkedList<byte[]> stack, Coin value, Set<VerifyFlag> verifyFlags); @Deprecated void correctlySpends(Transaction txContainingThis, long scriptSigIndex, Script scriptPubKey); @Deprecated void correctlySpends(Transaction txContainingThis, long scriptSigIndex, Script scriptPubKey, Set<VerifyFlag> verifyFlags); void correctlySpends(Transaction txContainingThis, long scriptSigIndex, Script scriptPubKey, Coin value, Set<VerifyFlag> verifyFlags); ScriptType getScriptType(); @Override boolean equals(Object o); @Override int hashCode(); static final EnumSet<VerifyFlag> ALL_VERIFY_FLAGS; static final long MAX_SCRIPT_ELEMENT_SIZE; static final int SIG_SIZE; static final int MAX_P2SH_SIGOPS; }
@Test public void dataDrivenValidTransactions() throws Exception { JsonNode json = new ObjectMapper().readTree(new InputStreamReader(getClass().getResourceAsStream( "tx_valid.json"), Charsets.UTF_8)); for (JsonNode test : json) { if (test.isArray() && test.size() == 1 && test.get(0).isTextual()) continue; Transaction transaction = null; try { Map<TransactionOutPoint, Script> scriptPubKeys = parseScriptPubKeys(test.get(0)); transaction = PARAMS.getDefaultSerializer().makeTransaction(HEX.decode(test.get(1).asText().toLowerCase())); transaction.verify(); Set<VerifyFlag> verifyFlags = parseVerifyFlags(test.get(2).asText()); for (int i = 0; i < transaction.getInputs().size(); i++) { TransactionInput input = transaction.getInputs().get(i); if (input.getOutpoint().getIndex() == 0xffffffffL) input.getOutpoint().setIndex(-1); assertTrue(scriptPubKeys.containsKey(input.getOutpoint())); input.getScriptSig().correctlySpends(transaction, i, scriptPubKeys.get(input.getOutpoint()), verifyFlags); } } catch (Exception e) { System.err.println(test); if (transaction != null) System.err.println(transaction); throw e; } } }
@Deprecated public void correctlySpends(Transaction txContainingThis, long scriptSigIndex, Script scriptPubKey) throws ScriptException { correctlySpends(txContainingThis, scriptSigIndex, scriptPubKey, Coin.ZERO, ALL_VERIFY_FLAGS); }
Script { @Deprecated public void correctlySpends(Transaction txContainingThis, long scriptSigIndex, Script scriptPubKey) throws ScriptException { correctlySpends(txContainingThis, scriptSigIndex, scriptPubKey, Coin.ZERO, ALL_VERIFY_FLAGS); } }
Script { @Deprecated public void correctlySpends(Transaction txContainingThis, long scriptSigIndex, Script scriptPubKey) throws ScriptException { correctlySpends(txContainingThis, scriptSigIndex, scriptPubKey, Coin.ZERO, ALL_VERIFY_FLAGS); } private Script(); Script(List<ScriptChunk> chunks); Script(byte[] programBytes); Script(byte[] programBytes, long creationTimeSeconds); }
Script { @Deprecated public void correctlySpends(Transaction txContainingThis, long scriptSigIndex, Script scriptPubKey) throws ScriptException { correctlySpends(txContainingThis, scriptSigIndex, scriptPubKey, Coin.ZERO, ALL_VERIFY_FLAGS); } private Script(); Script(List<ScriptChunk> chunks); Script(byte[] programBytes); Script(byte[] programBytes, long creationTimeSeconds); long getCreationTimeSeconds(); void setCreationTimeSeconds(long creationTimeSeconds); @Override String toString(); byte[] getProgram(); List<ScriptChunk> getChunks(); boolean isSentToRawPubKey(); boolean isSentToAddress(); @Deprecated boolean isSentToP2SH(); byte[] getPubKeyHash(); byte[] getPubKey(); byte[] getCLTVPaymentChannelSenderPubKey(); byte[] getCLTVPaymentChannelRecipientPubKey(); BigInteger getCLTVPaymentChannelExpiry(); @Deprecated Address getFromAddress(NetworkParameters params); Address getToAddress(NetworkParameters params); Address getToAddress(NetworkParameters params, boolean forcePayToPubKey); static void writeBytes(OutputStream os, byte[] buf); static byte[] createMultiSigOutputScript(int threshold, List<ECKey> pubkeys); static byte[] createInputScript(byte[] signature, byte[] pubkey); static byte[] createInputScript(byte[] signature); Script createEmptyInputScript(@Nullable ECKey key, @Nullable Script redeemScript); Script getScriptSigWithSignature(Script scriptSig, byte[] sigBytes, int index); int getSigInsertionIndex(Sha256Hash hash, ECKey signingKey); List<ECKey> getPubKeys(); static int getSigOpCount(byte[] program); static long getP2SHSigOpCount(byte[] scriptSig); int getNumberOfSignaturesRequiredToSpend(); int getNumberOfBytesRequiredToSpend(@Nullable ECKey pubKey, @Nullable Script redeemScript); boolean isPayToScriptHash(); boolean isSentToMultiSig(); boolean isSentToCLTVPaymentChannel(); static byte[] removeAllInstancesOf(byte[] inputScript, byte[] chunkToRemove); static byte[] removeAllInstancesOfOp(byte[] inputScript, int opCode); boolean isOpReturn(); @Deprecated static void executeScript(@Nullable Transaction txContainingThis, long index, Script script, LinkedList<byte[]> stack, boolean enforceNullDummy); @Deprecated static void executeScript(@Nullable Transaction txContainingThis, long index, Script script, LinkedList<byte[]> stack, Set<VerifyFlag> verifyFlags); static void executeScript(@Nullable Transaction txContainingThis, long index, Script script, LinkedList<byte[]> stack, Coin value, Set<VerifyFlag> verifyFlags); @Deprecated void correctlySpends(Transaction txContainingThis, long scriptSigIndex, Script scriptPubKey); @Deprecated void correctlySpends(Transaction txContainingThis, long scriptSigIndex, Script scriptPubKey, Set<VerifyFlag> verifyFlags); void correctlySpends(Transaction txContainingThis, long scriptSigIndex, Script scriptPubKey, Coin value, Set<VerifyFlag> verifyFlags); ScriptType getScriptType(); @Override boolean equals(Object o); @Override int hashCode(); }
Script { @Deprecated public void correctlySpends(Transaction txContainingThis, long scriptSigIndex, Script scriptPubKey) throws ScriptException { correctlySpends(txContainingThis, scriptSigIndex, scriptPubKey, Coin.ZERO, ALL_VERIFY_FLAGS); } private Script(); Script(List<ScriptChunk> chunks); Script(byte[] programBytes); Script(byte[] programBytes, long creationTimeSeconds); long getCreationTimeSeconds(); void setCreationTimeSeconds(long creationTimeSeconds); @Override String toString(); byte[] getProgram(); List<ScriptChunk> getChunks(); boolean isSentToRawPubKey(); boolean isSentToAddress(); @Deprecated boolean isSentToP2SH(); byte[] getPubKeyHash(); byte[] getPubKey(); byte[] getCLTVPaymentChannelSenderPubKey(); byte[] getCLTVPaymentChannelRecipientPubKey(); BigInteger getCLTVPaymentChannelExpiry(); @Deprecated Address getFromAddress(NetworkParameters params); Address getToAddress(NetworkParameters params); Address getToAddress(NetworkParameters params, boolean forcePayToPubKey); static void writeBytes(OutputStream os, byte[] buf); static byte[] createMultiSigOutputScript(int threshold, List<ECKey> pubkeys); static byte[] createInputScript(byte[] signature, byte[] pubkey); static byte[] createInputScript(byte[] signature); Script createEmptyInputScript(@Nullable ECKey key, @Nullable Script redeemScript); Script getScriptSigWithSignature(Script scriptSig, byte[] sigBytes, int index); int getSigInsertionIndex(Sha256Hash hash, ECKey signingKey); List<ECKey> getPubKeys(); static int getSigOpCount(byte[] program); static long getP2SHSigOpCount(byte[] scriptSig); int getNumberOfSignaturesRequiredToSpend(); int getNumberOfBytesRequiredToSpend(@Nullable ECKey pubKey, @Nullable Script redeemScript); boolean isPayToScriptHash(); boolean isSentToMultiSig(); boolean isSentToCLTVPaymentChannel(); static byte[] removeAllInstancesOf(byte[] inputScript, byte[] chunkToRemove); static byte[] removeAllInstancesOfOp(byte[] inputScript, int opCode); boolean isOpReturn(); @Deprecated static void executeScript(@Nullable Transaction txContainingThis, long index, Script script, LinkedList<byte[]> stack, boolean enforceNullDummy); @Deprecated static void executeScript(@Nullable Transaction txContainingThis, long index, Script script, LinkedList<byte[]> stack, Set<VerifyFlag> verifyFlags); static void executeScript(@Nullable Transaction txContainingThis, long index, Script script, LinkedList<byte[]> stack, Coin value, Set<VerifyFlag> verifyFlags); @Deprecated void correctlySpends(Transaction txContainingThis, long scriptSigIndex, Script scriptPubKey); @Deprecated void correctlySpends(Transaction txContainingThis, long scriptSigIndex, Script scriptPubKey, Set<VerifyFlag> verifyFlags); void correctlySpends(Transaction txContainingThis, long scriptSigIndex, Script scriptPubKey, Coin value, Set<VerifyFlag> verifyFlags); ScriptType getScriptType(); @Override boolean equals(Object o); @Override int hashCode(); static final EnumSet<VerifyFlag> ALL_VERIFY_FLAGS; static final long MAX_SCRIPT_ELEMENT_SIZE; static final int SIG_SIZE; static final int MAX_P2SH_SIGOPS; }
@Test public void dataDrivenInvalidTransactions() throws Exception { JsonNode json = new ObjectMapper().readTree(new InputStreamReader(getClass().getResourceAsStream( "tx_invalid.json"), Charsets.UTF_8)); for (JsonNode test : json) { if (test.isArray() && test.size() == 1 && test.get(0).isTextual()) continue; Map<TransactionOutPoint, Script> scriptPubKeys = parseScriptPubKeys(test.get(0)); Transaction transaction = PARAMS.getDefaultSerializer().makeTransaction(HEX.decode(test.get(1).asText().toLowerCase())); Set<VerifyFlag> verifyFlags = parseVerifyFlags(test.get(2).asText()); boolean valid = true; try { transaction.verify(); } catch (VerificationException e) { valid = false; } HashSet<TransactionOutPoint> set = new HashSet<TransactionOutPoint>(); for (TransactionInput input : transaction.getInputs()) { if (set.contains(input.getOutpoint())) valid = false; set.add(input.getOutpoint()); } for (int i = 0; i < transaction.getInputs().size() && valid; i++) { TransactionInput input = transaction.getInputs().get(i); assertTrue(scriptPubKeys.containsKey(input.getOutpoint())); try { input.getScriptSig().correctlySpends(transaction, i, scriptPubKeys.get(input.getOutpoint()), verifyFlags); } catch (VerificationException e) { valid = false; } } if (valid) fail(); } }
@Deprecated public void correctlySpends(Transaction txContainingThis, long scriptSigIndex, Script scriptPubKey) throws ScriptException { correctlySpends(txContainingThis, scriptSigIndex, scriptPubKey, Coin.ZERO, ALL_VERIFY_FLAGS); }
Script { @Deprecated public void correctlySpends(Transaction txContainingThis, long scriptSigIndex, Script scriptPubKey) throws ScriptException { correctlySpends(txContainingThis, scriptSigIndex, scriptPubKey, Coin.ZERO, ALL_VERIFY_FLAGS); } }
Script { @Deprecated public void correctlySpends(Transaction txContainingThis, long scriptSigIndex, Script scriptPubKey) throws ScriptException { correctlySpends(txContainingThis, scriptSigIndex, scriptPubKey, Coin.ZERO, ALL_VERIFY_FLAGS); } private Script(); Script(List<ScriptChunk> chunks); Script(byte[] programBytes); Script(byte[] programBytes, long creationTimeSeconds); }
Script { @Deprecated public void correctlySpends(Transaction txContainingThis, long scriptSigIndex, Script scriptPubKey) throws ScriptException { correctlySpends(txContainingThis, scriptSigIndex, scriptPubKey, Coin.ZERO, ALL_VERIFY_FLAGS); } private Script(); Script(List<ScriptChunk> chunks); Script(byte[] programBytes); Script(byte[] programBytes, long creationTimeSeconds); long getCreationTimeSeconds(); void setCreationTimeSeconds(long creationTimeSeconds); @Override String toString(); byte[] getProgram(); List<ScriptChunk> getChunks(); boolean isSentToRawPubKey(); boolean isSentToAddress(); @Deprecated boolean isSentToP2SH(); byte[] getPubKeyHash(); byte[] getPubKey(); byte[] getCLTVPaymentChannelSenderPubKey(); byte[] getCLTVPaymentChannelRecipientPubKey(); BigInteger getCLTVPaymentChannelExpiry(); @Deprecated Address getFromAddress(NetworkParameters params); Address getToAddress(NetworkParameters params); Address getToAddress(NetworkParameters params, boolean forcePayToPubKey); static void writeBytes(OutputStream os, byte[] buf); static byte[] createMultiSigOutputScript(int threshold, List<ECKey> pubkeys); static byte[] createInputScript(byte[] signature, byte[] pubkey); static byte[] createInputScript(byte[] signature); Script createEmptyInputScript(@Nullable ECKey key, @Nullable Script redeemScript); Script getScriptSigWithSignature(Script scriptSig, byte[] sigBytes, int index); int getSigInsertionIndex(Sha256Hash hash, ECKey signingKey); List<ECKey> getPubKeys(); static int getSigOpCount(byte[] program); static long getP2SHSigOpCount(byte[] scriptSig); int getNumberOfSignaturesRequiredToSpend(); int getNumberOfBytesRequiredToSpend(@Nullable ECKey pubKey, @Nullable Script redeemScript); boolean isPayToScriptHash(); boolean isSentToMultiSig(); boolean isSentToCLTVPaymentChannel(); static byte[] removeAllInstancesOf(byte[] inputScript, byte[] chunkToRemove); static byte[] removeAllInstancesOfOp(byte[] inputScript, int opCode); boolean isOpReturn(); @Deprecated static void executeScript(@Nullable Transaction txContainingThis, long index, Script script, LinkedList<byte[]> stack, boolean enforceNullDummy); @Deprecated static void executeScript(@Nullable Transaction txContainingThis, long index, Script script, LinkedList<byte[]> stack, Set<VerifyFlag> verifyFlags); static void executeScript(@Nullable Transaction txContainingThis, long index, Script script, LinkedList<byte[]> stack, Coin value, Set<VerifyFlag> verifyFlags); @Deprecated void correctlySpends(Transaction txContainingThis, long scriptSigIndex, Script scriptPubKey); @Deprecated void correctlySpends(Transaction txContainingThis, long scriptSigIndex, Script scriptPubKey, Set<VerifyFlag> verifyFlags); void correctlySpends(Transaction txContainingThis, long scriptSigIndex, Script scriptPubKey, Coin value, Set<VerifyFlag> verifyFlags); ScriptType getScriptType(); @Override boolean equals(Object o); @Override int hashCode(); }
Script { @Deprecated public void correctlySpends(Transaction txContainingThis, long scriptSigIndex, Script scriptPubKey) throws ScriptException { correctlySpends(txContainingThis, scriptSigIndex, scriptPubKey, Coin.ZERO, ALL_VERIFY_FLAGS); } private Script(); Script(List<ScriptChunk> chunks); Script(byte[] programBytes); Script(byte[] programBytes, long creationTimeSeconds); long getCreationTimeSeconds(); void setCreationTimeSeconds(long creationTimeSeconds); @Override String toString(); byte[] getProgram(); List<ScriptChunk> getChunks(); boolean isSentToRawPubKey(); boolean isSentToAddress(); @Deprecated boolean isSentToP2SH(); byte[] getPubKeyHash(); byte[] getPubKey(); byte[] getCLTVPaymentChannelSenderPubKey(); byte[] getCLTVPaymentChannelRecipientPubKey(); BigInteger getCLTVPaymentChannelExpiry(); @Deprecated Address getFromAddress(NetworkParameters params); Address getToAddress(NetworkParameters params); Address getToAddress(NetworkParameters params, boolean forcePayToPubKey); static void writeBytes(OutputStream os, byte[] buf); static byte[] createMultiSigOutputScript(int threshold, List<ECKey> pubkeys); static byte[] createInputScript(byte[] signature, byte[] pubkey); static byte[] createInputScript(byte[] signature); Script createEmptyInputScript(@Nullable ECKey key, @Nullable Script redeemScript); Script getScriptSigWithSignature(Script scriptSig, byte[] sigBytes, int index); int getSigInsertionIndex(Sha256Hash hash, ECKey signingKey); List<ECKey> getPubKeys(); static int getSigOpCount(byte[] program); static long getP2SHSigOpCount(byte[] scriptSig); int getNumberOfSignaturesRequiredToSpend(); int getNumberOfBytesRequiredToSpend(@Nullable ECKey pubKey, @Nullable Script redeemScript); boolean isPayToScriptHash(); boolean isSentToMultiSig(); boolean isSentToCLTVPaymentChannel(); static byte[] removeAllInstancesOf(byte[] inputScript, byte[] chunkToRemove); static byte[] removeAllInstancesOfOp(byte[] inputScript, int opCode); boolean isOpReturn(); @Deprecated static void executeScript(@Nullable Transaction txContainingThis, long index, Script script, LinkedList<byte[]> stack, boolean enforceNullDummy); @Deprecated static void executeScript(@Nullable Transaction txContainingThis, long index, Script script, LinkedList<byte[]> stack, Set<VerifyFlag> verifyFlags); static void executeScript(@Nullable Transaction txContainingThis, long index, Script script, LinkedList<byte[]> stack, Coin value, Set<VerifyFlag> verifyFlags); @Deprecated void correctlySpends(Transaction txContainingThis, long scriptSigIndex, Script scriptPubKey); @Deprecated void correctlySpends(Transaction txContainingThis, long scriptSigIndex, Script scriptPubKey, Set<VerifyFlag> verifyFlags); void correctlySpends(Transaction txContainingThis, long scriptSigIndex, Script scriptPubKey, Coin value, Set<VerifyFlag> verifyFlags); ScriptType getScriptType(); @Override boolean equals(Object o); @Override int hashCode(); static final EnumSet<VerifyFlag> ALL_VERIFY_FLAGS; static final long MAX_SCRIPT_ELEMENT_SIZE; static final int SIG_SIZE; static final int MAX_P2SH_SIGOPS; }
@Test public void testCLTVPaymentChannelOutput() { Script script = ScriptBuilder.createCLTVPaymentChannelOutput(BigInteger.valueOf(20), new ECKey(), new ECKey()); assertTrue("script is locktime-verify", script.isSentToCLTVPaymentChannel()); }
public boolean isSentToCLTVPaymentChannel() { if (chunks.size() != 10) return false; if (!chunks.get(0).equalsOpCode(OP_IF)) return false; if (!chunks.get(2).equalsOpCode(OP_CHECKSIGVERIFY)) return false; if (!chunks.get(3).equalsOpCode(OP_ELSE)) return false; if (!chunks.get(5).equalsOpCode(OP_CHECKLOCKTIMEVERIFY)) return false; if (!chunks.get(6).equalsOpCode(OP_DROP)) return false; if (!chunks.get(7).equalsOpCode(OP_ENDIF)) return false; if (!chunks.get(9).equalsOpCode(OP_CHECKSIG)) return false; return true; }
Script { public boolean isSentToCLTVPaymentChannel() { if (chunks.size() != 10) return false; if (!chunks.get(0).equalsOpCode(OP_IF)) return false; if (!chunks.get(2).equalsOpCode(OP_CHECKSIGVERIFY)) return false; if (!chunks.get(3).equalsOpCode(OP_ELSE)) return false; if (!chunks.get(5).equalsOpCode(OP_CHECKLOCKTIMEVERIFY)) return false; if (!chunks.get(6).equalsOpCode(OP_DROP)) return false; if (!chunks.get(7).equalsOpCode(OP_ENDIF)) return false; if (!chunks.get(9).equalsOpCode(OP_CHECKSIG)) return false; return true; } }
Script { public boolean isSentToCLTVPaymentChannel() { if (chunks.size() != 10) return false; if (!chunks.get(0).equalsOpCode(OP_IF)) return false; if (!chunks.get(2).equalsOpCode(OP_CHECKSIGVERIFY)) return false; if (!chunks.get(3).equalsOpCode(OP_ELSE)) return false; if (!chunks.get(5).equalsOpCode(OP_CHECKLOCKTIMEVERIFY)) return false; if (!chunks.get(6).equalsOpCode(OP_DROP)) return false; if (!chunks.get(7).equalsOpCode(OP_ENDIF)) return false; if (!chunks.get(9).equalsOpCode(OP_CHECKSIG)) return false; return true; } private Script(); Script(List<ScriptChunk> chunks); Script(byte[] programBytes); Script(byte[] programBytes, long creationTimeSeconds); }
Script { public boolean isSentToCLTVPaymentChannel() { if (chunks.size() != 10) return false; if (!chunks.get(0).equalsOpCode(OP_IF)) return false; if (!chunks.get(2).equalsOpCode(OP_CHECKSIGVERIFY)) return false; if (!chunks.get(3).equalsOpCode(OP_ELSE)) return false; if (!chunks.get(5).equalsOpCode(OP_CHECKLOCKTIMEVERIFY)) return false; if (!chunks.get(6).equalsOpCode(OP_DROP)) return false; if (!chunks.get(7).equalsOpCode(OP_ENDIF)) return false; if (!chunks.get(9).equalsOpCode(OP_CHECKSIG)) return false; return true; } private Script(); Script(List<ScriptChunk> chunks); Script(byte[] programBytes); Script(byte[] programBytes, long creationTimeSeconds); long getCreationTimeSeconds(); void setCreationTimeSeconds(long creationTimeSeconds); @Override String toString(); byte[] getProgram(); List<ScriptChunk> getChunks(); boolean isSentToRawPubKey(); boolean isSentToAddress(); @Deprecated boolean isSentToP2SH(); byte[] getPubKeyHash(); byte[] getPubKey(); byte[] getCLTVPaymentChannelSenderPubKey(); byte[] getCLTVPaymentChannelRecipientPubKey(); BigInteger getCLTVPaymentChannelExpiry(); @Deprecated Address getFromAddress(NetworkParameters params); Address getToAddress(NetworkParameters params); Address getToAddress(NetworkParameters params, boolean forcePayToPubKey); static void writeBytes(OutputStream os, byte[] buf); static byte[] createMultiSigOutputScript(int threshold, List<ECKey> pubkeys); static byte[] createInputScript(byte[] signature, byte[] pubkey); static byte[] createInputScript(byte[] signature); Script createEmptyInputScript(@Nullable ECKey key, @Nullable Script redeemScript); Script getScriptSigWithSignature(Script scriptSig, byte[] sigBytes, int index); int getSigInsertionIndex(Sha256Hash hash, ECKey signingKey); List<ECKey> getPubKeys(); static int getSigOpCount(byte[] program); static long getP2SHSigOpCount(byte[] scriptSig); int getNumberOfSignaturesRequiredToSpend(); int getNumberOfBytesRequiredToSpend(@Nullable ECKey pubKey, @Nullable Script redeemScript); boolean isPayToScriptHash(); boolean isSentToMultiSig(); boolean isSentToCLTVPaymentChannel(); static byte[] removeAllInstancesOf(byte[] inputScript, byte[] chunkToRemove); static byte[] removeAllInstancesOfOp(byte[] inputScript, int opCode); boolean isOpReturn(); @Deprecated static void executeScript(@Nullable Transaction txContainingThis, long index, Script script, LinkedList<byte[]> stack, boolean enforceNullDummy); @Deprecated static void executeScript(@Nullable Transaction txContainingThis, long index, Script script, LinkedList<byte[]> stack, Set<VerifyFlag> verifyFlags); static void executeScript(@Nullable Transaction txContainingThis, long index, Script script, LinkedList<byte[]> stack, Coin value, Set<VerifyFlag> verifyFlags); @Deprecated void correctlySpends(Transaction txContainingThis, long scriptSigIndex, Script scriptPubKey); @Deprecated void correctlySpends(Transaction txContainingThis, long scriptSigIndex, Script scriptPubKey, Set<VerifyFlag> verifyFlags); void correctlySpends(Transaction txContainingThis, long scriptSigIndex, Script scriptPubKey, Coin value, Set<VerifyFlag> verifyFlags); ScriptType getScriptType(); @Override boolean equals(Object o); @Override int hashCode(); }
Script { public boolean isSentToCLTVPaymentChannel() { if (chunks.size() != 10) return false; if (!chunks.get(0).equalsOpCode(OP_IF)) return false; if (!chunks.get(2).equalsOpCode(OP_CHECKSIGVERIFY)) return false; if (!chunks.get(3).equalsOpCode(OP_ELSE)) return false; if (!chunks.get(5).equalsOpCode(OP_CHECKLOCKTIMEVERIFY)) return false; if (!chunks.get(6).equalsOpCode(OP_DROP)) return false; if (!chunks.get(7).equalsOpCode(OP_ENDIF)) return false; if (!chunks.get(9).equalsOpCode(OP_CHECKSIG)) return false; return true; } private Script(); Script(List<ScriptChunk> chunks); Script(byte[] programBytes); Script(byte[] programBytes, long creationTimeSeconds); long getCreationTimeSeconds(); void setCreationTimeSeconds(long creationTimeSeconds); @Override String toString(); byte[] getProgram(); List<ScriptChunk> getChunks(); boolean isSentToRawPubKey(); boolean isSentToAddress(); @Deprecated boolean isSentToP2SH(); byte[] getPubKeyHash(); byte[] getPubKey(); byte[] getCLTVPaymentChannelSenderPubKey(); byte[] getCLTVPaymentChannelRecipientPubKey(); BigInteger getCLTVPaymentChannelExpiry(); @Deprecated Address getFromAddress(NetworkParameters params); Address getToAddress(NetworkParameters params); Address getToAddress(NetworkParameters params, boolean forcePayToPubKey); static void writeBytes(OutputStream os, byte[] buf); static byte[] createMultiSigOutputScript(int threshold, List<ECKey> pubkeys); static byte[] createInputScript(byte[] signature, byte[] pubkey); static byte[] createInputScript(byte[] signature); Script createEmptyInputScript(@Nullable ECKey key, @Nullable Script redeemScript); Script getScriptSigWithSignature(Script scriptSig, byte[] sigBytes, int index); int getSigInsertionIndex(Sha256Hash hash, ECKey signingKey); List<ECKey> getPubKeys(); static int getSigOpCount(byte[] program); static long getP2SHSigOpCount(byte[] scriptSig); int getNumberOfSignaturesRequiredToSpend(); int getNumberOfBytesRequiredToSpend(@Nullable ECKey pubKey, @Nullable Script redeemScript); boolean isPayToScriptHash(); boolean isSentToMultiSig(); boolean isSentToCLTVPaymentChannel(); static byte[] removeAllInstancesOf(byte[] inputScript, byte[] chunkToRemove); static byte[] removeAllInstancesOfOp(byte[] inputScript, int opCode); boolean isOpReturn(); @Deprecated static void executeScript(@Nullable Transaction txContainingThis, long index, Script script, LinkedList<byte[]> stack, boolean enforceNullDummy); @Deprecated static void executeScript(@Nullable Transaction txContainingThis, long index, Script script, LinkedList<byte[]> stack, Set<VerifyFlag> verifyFlags); static void executeScript(@Nullable Transaction txContainingThis, long index, Script script, LinkedList<byte[]> stack, Coin value, Set<VerifyFlag> verifyFlags); @Deprecated void correctlySpends(Transaction txContainingThis, long scriptSigIndex, Script scriptPubKey); @Deprecated void correctlySpends(Transaction txContainingThis, long scriptSigIndex, Script scriptPubKey, Set<VerifyFlag> verifyFlags); void correctlySpends(Transaction txContainingThis, long scriptSigIndex, Script scriptPubKey, Coin value, Set<VerifyFlag> verifyFlags); ScriptType getScriptType(); @Override boolean equals(Object o); @Override int hashCode(); static final EnumSet<VerifyFlag> ALL_VERIFY_FLAGS; static final long MAX_SCRIPT_ELEMENT_SIZE; static final int SIG_SIZE; static final int MAX_P2SH_SIGOPS; }
@Test public void getToAddress() throws Exception { ECKey toKey = new ECKey(); Address toAddress = toKey.toAddress(PARAMS); assertEquals(toAddress, ScriptBuilder.createOutputScript(toKey).getToAddress(PARAMS, true)); assertEquals(toAddress, ScriptBuilder.createOutputScript(toAddress).getToAddress(PARAMS, true)); Script p2shScript = ScriptBuilder.createP2SHOutputScript(new byte[20]); Address scriptAddress = Address.fromP2SHScript(PARAMS, p2shScript); assertEquals(scriptAddress, p2shScript.getToAddress(PARAMS, true)); }
public Address getToAddress(NetworkParameters params) throws ScriptException { return getToAddress(params, false); }
Script { public Address getToAddress(NetworkParameters params) throws ScriptException { return getToAddress(params, false); } }
Script { public Address getToAddress(NetworkParameters params) throws ScriptException { return getToAddress(params, false); } private Script(); Script(List<ScriptChunk> chunks); Script(byte[] programBytes); Script(byte[] programBytes, long creationTimeSeconds); }
Script { public Address getToAddress(NetworkParameters params) throws ScriptException { return getToAddress(params, false); } private Script(); Script(List<ScriptChunk> chunks); Script(byte[] programBytes); Script(byte[] programBytes, long creationTimeSeconds); long getCreationTimeSeconds(); void setCreationTimeSeconds(long creationTimeSeconds); @Override String toString(); byte[] getProgram(); List<ScriptChunk> getChunks(); boolean isSentToRawPubKey(); boolean isSentToAddress(); @Deprecated boolean isSentToP2SH(); byte[] getPubKeyHash(); byte[] getPubKey(); byte[] getCLTVPaymentChannelSenderPubKey(); byte[] getCLTVPaymentChannelRecipientPubKey(); BigInteger getCLTVPaymentChannelExpiry(); @Deprecated Address getFromAddress(NetworkParameters params); Address getToAddress(NetworkParameters params); Address getToAddress(NetworkParameters params, boolean forcePayToPubKey); static void writeBytes(OutputStream os, byte[] buf); static byte[] createMultiSigOutputScript(int threshold, List<ECKey> pubkeys); static byte[] createInputScript(byte[] signature, byte[] pubkey); static byte[] createInputScript(byte[] signature); Script createEmptyInputScript(@Nullable ECKey key, @Nullable Script redeemScript); Script getScriptSigWithSignature(Script scriptSig, byte[] sigBytes, int index); int getSigInsertionIndex(Sha256Hash hash, ECKey signingKey); List<ECKey> getPubKeys(); static int getSigOpCount(byte[] program); static long getP2SHSigOpCount(byte[] scriptSig); int getNumberOfSignaturesRequiredToSpend(); int getNumberOfBytesRequiredToSpend(@Nullable ECKey pubKey, @Nullable Script redeemScript); boolean isPayToScriptHash(); boolean isSentToMultiSig(); boolean isSentToCLTVPaymentChannel(); static byte[] removeAllInstancesOf(byte[] inputScript, byte[] chunkToRemove); static byte[] removeAllInstancesOfOp(byte[] inputScript, int opCode); boolean isOpReturn(); @Deprecated static void executeScript(@Nullable Transaction txContainingThis, long index, Script script, LinkedList<byte[]> stack, boolean enforceNullDummy); @Deprecated static void executeScript(@Nullable Transaction txContainingThis, long index, Script script, LinkedList<byte[]> stack, Set<VerifyFlag> verifyFlags); static void executeScript(@Nullable Transaction txContainingThis, long index, Script script, LinkedList<byte[]> stack, Coin value, Set<VerifyFlag> verifyFlags); @Deprecated void correctlySpends(Transaction txContainingThis, long scriptSigIndex, Script scriptPubKey); @Deprecated void correctlySpends(Transaction txContainingThis, long scriptSigIndex, Script scriptPubKey, Set<VerifyFlag> verifyFlags); void correctlySpends(Transaction txContainingThis, long scriptSigIndex, Script scriptPubKey, Coin value, Set<VerifyFlag> verifyFlags); ScriptType getScriptType(); @Override boolean equals(Object o); @Override int hashCode(); }
Script { public Address getToAddress(NetworkParameters params) throws ScriptException { return getToAddress(params, false); } private Script(); Script(List<ScriptChunk> chunks); Script(byte[] programBytes); Script(byte[] programBytes, long creationTimeSeconds); long getCreationTimeSeconds(); void setCreationTimeSeconds(long creationTimeSeconds); @Override String toString(); byte[] getProgram(); List<ScriptChunk> getChunks(); boolean isSentToRawPubKey(); boolean isSentToAddress(); @Deprecated boolean isSentToP2SH(); byte[] getPubKeyHash(); byte[] getPubKey(); byte[] getCLTVPaymentChannelSenderPubKey(); byte[] getCLTVPaymentChannelRecipientPubKey(); BigInteger getCLTVPaymentChannelExpiry(); @Deprecated Address getFromAddress(NetworkParameters params); Address getToAddress(NetworkParameters params); Address getToAddress(NetworkParameters params, boolean forcePayToPubKey); static void writeBytes(OutputStream os, byte[] buf); static byte[] createMultiSigOutputScript(int threshold, List<ECKey> pubkeys); static byte[] createInputScript(byte[] signature, byte[] pubkey); static byte[] createInputScript(byte[] signature); Script createEmptyInputScript(@Nullable ECKey key, @Nullable Script redeemScript); Script getScriptSigWithSignature(Script scriptSig, byte[] sigBytes, int index); int getSigInsertionIndex(Sha256Hash hash, ECKey signingKey); List<ECKey> getPubKeys(); static int getSigOpCount(byte[] program); static long getP2SHSigOpCount(byte[] scriptSig); int getNumberOfSignaturesRequiredToSpend(); int getNumberOfBytesRequiredToSpend(@Nullable ECKey pubKey, @Nullable Script redeemScript); boolean isPayToScriptHash(); boolean isSentToMultiSig(); boolean isSentToCLTVPaymentChannel(); static byte[] removeAllInstancesOf(byte[] inputScript, byte[] chunkToRemove); static byte[] removeAllInstancesOfOp(byte[] inputScript, int opCode); boolean isOpReturn(); @Deprecated static void executeScript(@Nullable Transaction txContainingThis, long index, Script script, LinkedList<byte[]> stack, boolean enforceNullDummy); @Deprecated static void executeScript(@Nullable Transaction txContainingThis, long index, Script script, LinkedList<byte[]> stack, Set<VerifyFlag> verifyFlags); static void executeScript(@Nullable Transaction txContainingThis, long index, Script script, LinkedList<byte[]> stack, Coin value, Set<VerifyFlag> verifyFlags); @Deprecated void correctlySpends(Transaction txContainingThis, long scriptSigIndex, Script scriptPubKey); @Deprecated void correctlySpends(Transaction txContainingThis, long scriptSigIndex, Script scriptPubKey, Set<VerifyFlag> verifyFlags); void correctlySpends(Transaction txContainingThis, long scriptSigIndex, Script scriptPubKey, Coin value, Set<VerifyFlag> verifyFlags); ScriptType getScriptType(); @Override boolean equals(Object o); @Override int hashCode(); static final EnumSet<VerifyFlag> ALL_VERIFY_FLAGS; static final long MAX_SCRIPT_ELEMENT_SIZE; static final int SIG_SIZE; static final int MAX_P2SH_SIGOPS; }
@Test(expected = ScriptException.class) public void getToAddressNoPubKey() throws Exception { ScriptBuilder.createOutputScript(new ECKey()).getToAddress(PARAMS, false); }
public Address getToAddress(NetworkParameters params) throws ScriptException { return getToAddress(params, false); }
Script { public Address getToAddress(NetworkParameters params) throws ScriptException { return getToAddress(params, false); } }
Script { public Address getToAddress(NetworkParameters params) throws ScriptException { return getToAddress(params, false); } private Script(); Script(List<ScriptChunk> chunks); Script(byte[] programBytes); Script(byte[] programBytes, long creationTimeSeconds); }
Script { public Address getToAddress(NetworkParameters params) throws ScriptException { return getToAddress(params, false); } private Script(); Script(List<ScriptChunk> chunks); Script(byte[] programBytes); Script(byte[] programBytes, long creationTimeSeconds); long getCreationTimeSeconds(); void setCreationTimeSeconds(long creationTimeSeconds); @Override String toString(); byte[] getProgram(); List<ScriptChunk> getChunks(); boolean isSentToRawPubKey(); boolean isSentToAddress(); @Deprecated boolean isSentToP2SH(); byte[] getPubKeyHash(); byte[] getPubKey(); byte[] getCLTVPaymentChannelSenderPubKey(); byte[] getCLTVPaymentChannelRecipientPubKey(); BigInteger getCLTVPaymentChannelExpiry(); @Deprecated Address getFromAddress(NetworkParameters params); Address getToAddress(NetworkParameters params); Address getToAddress(NetworkParameters params, boolean forcePayToPubKey); static void writeBytes(OutputStream os, byte[] buf); static byte[] createMultiSigOutputScript(int threshold, List<ECKey> pubkeys); static byte[] createInputScript(byte[] signature, byte[] pubkey); static byte[] createInputScript(byte[] signature); Script createEmptyInputScript(@Nullable ECKey key, @Nullable Script redeemScript); Script getScriptSigWithSignature(Script scriptSig, byte[] sigBytes, int index); int getSigInsertionIndex(Sha256Hash hash, ECKey signingKey); List<ECKey> getPubKeys(); static int getSigOpCount(byte[] program); static long getP2SHSigOpCount(byte[] scriptSig); int getNumberOfSignaturesRequiredToSpend(); int getNumberOfBytesRequiredToSpend(@Nullable ECKey pubKey, @Nullable Script redeemScript); boolean isPayToScriptHash(); boolean isSentToMultiSig(); boolean isSentToCLTVPaymentChannel(); static byte[] removeAllInstancesOf(byte[] inputScript, byte[] chunkToRemove); static byte[] removeAllInstancesOfOp(byte[] inputScript, int opCode); boolean isOpReturn(); @Deprecated static void executeScript(@Nullable Transaction txContainingThis, long index, Script script, LinkedList<byte[]> stack, boolean enforceNullDummy); @Deprecated static void executeScript(@Nullable Transaction txContainingThis, long index, Script script, LinkedList<byte[]> stack, Set<VerifyFlag> verifyFlags); static void executeScript(@Nullable Transaction txContainingThis, long index, Script script, LinkedList<byte[]> stack, Coin value, Set<VerifyFlag> verifyFlags); @Deprecated void correctlySpends(Transaction txContainingThis, long scriptSigIndex, Script scriptPubKey); @Deprecated void correctlySpends(Transaction txContainingThis, long scriptSigIndex, Script scriptPubKey, Set<VerifyFlag> verifyFlags); void correctlySpends(Transaction txContainingThis, long scriptSigIndex, Script scriptPubKey, Coin value, Set<VerifyFlag> verifyFlags); ScriptType getScriptType(); @Override boolean equals(Object o); @Override int hashCode(); }
Script { public Address getToAddress(NetworkParameters params) throws ScriptException { return getToAddress(params, false); } private Script(); Script(List<ScriptChunk> chunks); Script(byte[] programBytes); Script(byte[] programBytes, long creationTimeSeconds); long getCreationTimeSeconds(); void setCreationTimeSeconds(long creationTimeSeconds); @Override String toString(); byte[] getProgram(); List<ScriptChunk> getChunks(); boolean isSentToRawPubKey(); boolean isSentToAddress(); @Deprecated boolean isSentToP2SH(); byte[] getPubKeyHash(); byte[] getPubKey(); byte[] getCLTVPaymentChannelSenderPubKey(); byte[] getCLTVPaymentChannelRecipientPubKey(); BigInteger getCLTVPaymentChannelExpiry(); @Deprecated Address getFromAddress(NetworkParameters params); Address getToAddress(NetworkParameters params); Address getToAddress(NetworkParameters params, boolean forcePayToPubKey); static void writeBytes(OutputStream os, byte[] buf); static byte[] createMultiSigOutputScript(int threshold, List<ECKey> pubkeys); static byte[] createInputScript(byte[] signature, byte[] pubkey); static byte[] createInputScript(byte[] signature); Script createEmptyInputScript(@Nullable ECKey key, @Nullable Script redeemScript); Script getScriptSigWithSignature(Script scriptSig, byte[] sigBytes, int index); int getSigInsertionIndex(Sha256Hash hash, ECKey signingKey); List<ECKey> getPubKeys(); static int getSigOpCount(byte[] program); static long getP2SHSigOpCount(byte[] scriptSig); int getNumberOfSignaturesRequiredToSpend(); int getNumberOfBytesRequiredToSpend(@Nullable ECKey pubKey, @Nullable Script redeemScript); boolean isPayToScriptHash(); boolean isSentToMultiSig(); boolean isSentToCLTVPaymentChannel(); static byte[] removeAllInstancesOf(byte[] inputScript, byte[] chunkToRemove); static byte[] removeAllInstancesOfOp(byte[] inputScript, int opCode); boolean isOpReturn(); @Deprecated static void executeScript(@Nullable Transaction txContainingThis, long index, Script script, LinkedList<byte[]> stack, boolean enforceNullDummy); @Deprecated static void executeScript(@Nullable Transaction txContainingThis, long index, Script script, LinkedList<byte[]> stack, Set<VerifyFlag> verifyFlags); static void executeScript(@Nullable Transaction txContainingThis, long index, Script script, LinkedList<byte[]> stack, Coin value, Set<VerifyFlag> verifyFlags); @Deprecated void correctlySpends(Transaction txContainingThis, long scriptSigIndex, Script scriptPubKey); @Deprecated void correctlySpends(Transaction txContainingThis, long scriptSigIndex, Script scriptPubKey, Set<VerifyFlag> verifyFlags); void correctlySpends(Transaction txContainingThis, long scriptSigIndex, Script scriptPubKey, Coin value, Set<VerifyFlag> verifyFlags); ScriptType getScriptType(); @Override boolean equals(Object o); @Override int hashCode(); static final EnumSet<VerifyFlag> ALL_VERIFY_FLAGS; static final long MAX_SCRIPT_ELEMENT_SIZE; static final int SIG_SIZE; static final int MAX_P2SH_SIGOPS; }
@Test public void numberBuilderZero() { final ScriptBuilder builder = new ScriptBuilder(); builder.number(0); assertArrayEquals(new byte[] { 0x00 }, builder.build().getProgram()); }
public byte[] getProgram() { try { if (program != null) return Arrays.copyOf(program, program.length); ByteArrayOutputStream bos = new ByteArrayOutputStream(); for (ScriptChunk chunk : chunks) { chunk.write(bos); } program = bos.toByteArray(); return program; } catch (IOException e) { throw new RuntimeException(e); } }
Script { public byte[] getProgram() { try { if (program != null) return Arrays.copyOf(program, program.length); ByteArrayOutputStream bos = new ByteArrayOutputStream(); for (ScriptChunk chunk : chunks) { chunk.write(bos); } program = bos.toByteArray(); return program; } catch (IOException e) { throw new RuntimeException(e); } } }
Script { public byte[] getProgram() { try { if (program != null) return Arrays.copyOf(program, program.length); ByteArrayOutputStream bos = new ByteArrayOutputStream(); for (ScriptChunk chunk : chunks) { chunk.write(bos); } program = bos.toByteArray(); return program; } catch (IOException e) { throw new RuntimeException(e); } } private Script(); Script(List<ScriptChunk> chunks); Script(byte[] programBytes); Script(byte[] programBytes, long creationTimeSeconds); }
Script { public byte[] getProgram() { try { if (program != null) return Arrays.copyOf(program, program.length); ByteArrayOutputStream bos = new ByteArrayOutputStream(); for (ScriptChunk chunk : chunks) { chunk.write(bos); } program = bos.toByteArray(); return program; } catch (IOException e) { throw new RuntimeException(e); } } private Script(); Script(List<ScriptChunk> chunks); Script(byte[] programBytes); Script(byte[] programBytes, long creationTimeSeconds); long getCreationTimeSeconds(); void setCreationTimeSeconds(long creationTimeSeconds); @Override String toString(); byte[] getProgram(); List<ScriptChunk> getChunks(); boolean isSentToRawPubKey(); boolean isSentToAddress(); @Deprecated boolean isSentToP2SH(); byte[] getPubKeyHash(); byte[] getPubKey(); byte[] getCLTVPaymentChannelSenderPubKey(); byte[] getCLTVPaymentChannelRecipientPubKey(); BigInteger getCLTVPaymentChannelExpiry(); @Deprecated Address getFromAddress(NetworkParameters params); Address getToAddress(NetworkParameters params); Address getToAddress(NetworkParameters params, boolean forcePayToPubKey); static void writeBytes(OutputStream os, byte[] buf); static byte[] createMultiSigOutputScript(int threshold, List<ECKey> pubkeys); static byte[] createInputScript(byte[] signature, byte[] pubkey); static byte[] createInputScript(byte[] signature); Script createEmptyInputScript(@Nullable ECKey key, @Nullable Script redeemScript); Script getScriptSigWithSignature(Script scriptSig, byte[] sigBytes, int index); int getSigInsertionIndex(Sha256Hash hash, ECKey signingKey); List<ECKey> getPubKeys(); static int getSigOpCount(byte[] program); static long getP2SHSigOpCount(byte[] scriptSig); int getNumberOfSignaturesRequiredToSpend(); int getNumberOfBytesRequiredToSpend(@Nullable ECKey pubKey, @Nullable Script redeemScript); boolean isPayToScriptHash(); boolean isSentToMultiSig(); boolean isSentToCLTVPaymentChannel(); static byte[] removeAllInstancesOf(byte[] inputScript, byte[] chunkToRemove); static byte[] removeAllInstancesOfOp(byte[] inputScript, int opCode); boolean isOpReturn(); @Deprecated static void executeScript(@Nullable Transaction txContainingThis, long index, Script script, LinkedList<byte[]> stack, boolean enforceNullDummy); @Deprecated static void executeScript(@Nullable Transaction txContainingThis, long index, Script script, LinkedList<byte[]> stack, Set<VerifyFlag> verifyFlags); static void executeScript(@Nullable Transaction txContainingThis, long index, Script script, LinkedList<byte[]> stack, Coin value, Set<VerifyFlag> verifyFlags); @Deprecated void correctlySpends(Transaction txContainingThis, long scriptSigIndex, Script scriptPubKey); @Deprecated void correctlySpends(Transaction txContainingThis, long scriptSigIndex, Script scriptPubKey, Set<VerifyFlag> verifyFlags); void correctlySpends(Transaction txContainingThis, long scriptSigIndex, Script scriptPubKey, Coin value, Set<VerifyFlag> verifyFlags); ScriptType getScriptType(); @Override boolean equals(Object o); @Override int hashCode(); }
Script { public byte[] getProgram() { try { if (program != null) return Arrays.copyOf(program, program.length); ByteArrayOutputStream bos = new ByteArrayOutputStream(); for (ScriptChunk chunk : chunks) { chunk.write(bos); } program = bos.toByteArray(); return program; } catch (IOException e) { throw new RuntimeException(e); } } private Script(); Script(List<ScriptChunk> chunks); Script(byte[] programBytes); Script(byte[] programBytes, long creationTimeSeconds); long getCreationTimeSeconds(); void setCreationTimeSeconds(long creationTimeSeconds); @Override String toString(); byte[] getProgram(); List<ScriptChunk> getChunks(); boolean isSentToRawPubKey(); boolean isSentToAddress(); @Deprecated boolean isSentToP2SH(); byte[] getPubKeyHash(); byte[] getPubKey(); byte[] getCLTVPaymentChannelSenderPubKey(); byte[] getCLTVPaymentChannelRecipientPubKey(); BigInteger getCLTVPaymentChannelExpiry(); @Deprecated Address getFromAddress(NetworkParameters params); Address getToAddress(NetworkParameters params); Address getToAddress(NetworkParameters params, boolean forcePayToPubKey); static void writeBytes(OutputStream os, byte[] buf); static byte[] createMultiSigOutputScript(int threshold, List<ECKey> pubkeys); static byte[] createInputScript(byte[] signature, byte[] pubkey); static byte[] createInputScript(byte[] signature); Script createEmptyInputScript(@Nullable ECKey key, @Nullable Script redeemScript); Script getScriptSigWithSignature(Script scriptSig, byte[] sigBytes, int index); int getSigInsertionIndex(Sha256Hash hash, ECKey signingKey); List<ECKey> getPubKeys(); static int getSigOpCount(byte[] program); static long getP2SHSigOpCount(byte[] scriptSig); int getNumberOfSignaturesRequiredToSpend(); int getNumberOfBytesRequiredToSpend(@Nullable ECKey pubKey, @Nullable Script redeemScript); boolean isPayToScriptHash(); boolean isSentToMultiSig(); boolean isSentToCLTVPaymentChannel(); static byte[] removeAllInstancesOf(byte[] inputScript, byte[] chunkToRemove); static byte[] removeAllInstancesOfOp(byte[] inputScript, int opCode); boolean isOpReturn(); @Deprecated static void executeScript(@Nullable Transaction txContainingThis, long index, Script script, LinkedList<byte[]> stack, boolean enforceNullDummy); @Deprecated static void executeScript(@Nullable Transaction txContainingThis, long index, Script script, LinkedList<byte[]> stack, Set<VerifyFlag> verifyFlags); static void executeScript(@Nullable Transaction txContainingThis, long index, Script script, LinkedList<byte[]> stack, Coin value, Set<VerifyFlag> verifyFlags); @Deprecated void correctlySpends(Transaction txContainingThis, long scriptSigIndex, Script scriptPubKey); @Deprecated void correctlySpends(Transaction txContainingThis, long scriptSigIndex, Script scriptPubKey, Set<VerifyFlag> verifyFlags); void correctlySpends(Transaction txContainingThis, long scriptSigIndex, Script scriptPubKey, Coin value, Set<VerifyFlag> verifyFlags); ScriptType getScriptType(); @Override boolean equals(Object o); @Override int hashCode(); static final EnumSet<VerifyFlag> ALL_VERIFY_FLAGS; static final long MAX_SCRIPT_ELEMENT_SIZE; static final int SIG_SIZE; static final int MAX_P2SH_SIGOPS; }
@Test public void numberBuilderPositiveOpCode() { final ScriptBuilder builder = new ScriptBuilder(); builder.number(5); assertArrayEquals(new byte[] { 0x55 }, builder.build().getProgram()); }
public byte[] getProgram() { try { if (program != null) return Arrays.copyOf(program, program.length); ByteArrayOutputStream bos = new ByteArrayOutputStream(); for (ScriptChunk chunk : chunks) { chunk.write(bos); } program = bos.toByteArray(); return program; } catch (IOException e) { throw new RuntimeException(e); } }
Script { public byte[] getProgram() { try { if (program != null) return Arrays.copyOf(program, program.length); ByteArrayOutputStream bos = new ByteArrayOutputStream(); for (ScriptChunk chunk : chunks) { chunk.write(bos); } program = bos.toByteArray(); return program; } catch (IOException e) { throw new RuntimeException(e); } } }
Script { public byte[] getProgram() { try { if (program != null) return Arrays.copyOf(program, program.length); ByteArrayOutputStream bos = new ByteArrayOutputStream(); for (ScriptChunk chunk : chunks) { chunk.write(bos); } program = bos.toByteArray(); return program; } catch (IOException e) { throw new RuntimeException(e); } } private Script(); Script(List<ScriptChunk> chunks); Script(byte[] programBytes); Script(byte[] programBytes, long creationTimeSeconds); }
Script { public byte[] getProgram() { try { if (program != null) return Arrays.copyOf(program, program.length); ByteArrayOutputStream bos = new ByteArrayOutputStream(); for (ScriptChunk chunk : chunks) { chunk.write(bos); } program = bos.toByteArray(); return program; } catch (IOException e) { throw new RuntimeException(e); } } private Script(); Script(List<ScriptChunk> chunks); Script(byte[] programBytes); Script(byte[] programBytes, long creationTimeSeconds); long getCreationTimeSeconds(); void setCreationTimeSeconds(long creationTimeSeconds); @Override String toString(); byte[] getProgram(); List<ScriptChunk> getChunks(); boolean isSentToRawPubKey(); boolean isSentToAddress(); @Deprecated boolean isSentToP2SH(); byte[] getPubKeyHash(); byte[] getPubKey(); byte[] getCLTVPaymentChannelSenderPubKey(); byte[] getCLTVPaymentChannelRecipientPubKey(); BigInteger getCLTVPaymentChannelExpiry(); @Deprecated Address getFromAddress(NetworkParameters params); Address getToAddress(NetworkParameters params); Address getToAddress(NetworkParameters params, boolean forcePayToPubKey); static void writeBytes(OutputStream os, byte[] buf); static byte[] createMultiSigOutputScript(int threshold, List<ECKey> pubkeys); static byte[] createInputScript(byte[] signature, byte[] pubkey); static byte[] createInputScript(byte[] signature); Script createEmptyInputScript(@Nullable ECKey key, @Nullable Script redeemScript); Script getScriptSigWithSignature(Script scriptSig, byte[] sigBytes, int index); int getSigInsertionIndex(Sha256Hash hash, ECKey signingKey); List<ECKey> getPubKeys(); static int getSigOpCount(byte[] program); static long getP2SHSigOpCount(byte[] scriptSig); int getNumberOfSignaturesRequiredToSpend(); int getNumberOfBytesRequiredToSpend(@Nullable ECKey pubKey, @Nullable Script redeemScript); boolean isPayToScriptHash(); boolean isSentToMultiSig(); boolean isSentToCLTVPaymentChannel(); static byte[] removeAllInstancesOf(byte[] inputScript, byte[] chunkToRemove); static byte[] removeAllInstancesOfOp(byte[] inputScript, int opCode); boolean isOpReturn(); @Deprecated static void executeScript(@Nullable Transaction txContainingThis, long index, Script script, LinkedList<byte[]> stack, boolean enforceNullDummy); @Deprecated static void executeScript(@Nullable Transaction txContainingThis, long index, Script script, LinkedList<byte[]> stack, Set<VerifyFlag> verifyFlags); static void executeScript(@Nullable Transaction txContainingThis, long index, Script script, LinkedList<byte[]> stack, Coin value, Set<VerifyFlag> verifyFlags); @Deprecated void correctlySpends(Transaction txContainingThis, long scriptSigIndex, Script scriptPubKey); @Deprecated void correctlySpends(Transaction txContainingThis, long scriptSigIndex, Script scriptPubKey, Set<VerifyFlag> verifyFlags); void correctlySpends(Transaction txContainingThis, long scriptSigIndex, Script scriptPubKey, Coin value, Set<VerifyFlag> verifyFlags); ScriptType getScriptType(); @Override boolean equals(Object o); @Override int hashCode(); }
Script { public byte[] getProgram() { try { if (program != null) return Arrays.copyOf(program, program.length); ByteArrayOutputStream bos = new ByteArrayOutputStream(); for (ScriptChunk chunk : chunks) { chunk.write(bos); } program = bos.toByteArray(); return program; } catch (IOException e) { throw new RuntimeException(e); } } private Script(); Script(List<ScriptChunk> chunks); Script(byte[] programBytes); Script(byte[] programBytes, long creationTimeSeconds); long getCreationTimeSeconds(); void setCreationTimeSeconds(long creationTimeSeconds); @Override String toString(); byte[] getProgram(); List<ScriptChunk> getChunks(); boolean isSentToRawPubKey(); boolean isSentToAddress(); @Deprecated boolean isSentToP2SH(); byte[] getPubKeyHash(); byte[] getPubKey(); byte[] getCLTVPaymentChannelSenderPubKey(); byte[] getCLTVPaymentChannelRecipientPubKey(); BigInteger getCLTVPaymentChannelExpiry(); @Deprecated Address getFromAddress(NetworkParameters params); Address getToAddress(NetworkParameters params); Address getToAddress(NetworkParameters params, boolean forcePayToPubKey); static void writeBytes(OutputStream os, byte[] buf); static byte[] createMultiSigOutputScript(int threshold, List<ECKey> pubkeys); static byte[] createInputScript(byte[] signature, byte[] pubkey); static byte[] createInputScript(byte[] signature); Script createEmptyInputScript(@Nullable ECKey key, @Nullable Script redeemScript); Script getScriptSigWithSignature(Script scriptSig, byte[] sigBytes, int index); int getSigInsertionIndex(Sha256Hash hash, ECKey signingKey); List<ECKey> getPubKeys(); static int getSigOpCount(byte[] program); static long getP2SHSigOpCount(byte[] scriptSig); int getNumberOfSignaturesRequiredToSpend(); int getNumberOfBytesRequiredToSpend(@Nullable ECKey pubKey, @Nullable Script redeemScript); boolean isPayToScriptHash(); boolean isSentToMultiSig(); boolean isSentToCLTVPaymentChannel(); static byte[] removeAllInstancesOf(byte[] inputScript, byte[] chunkToRemove); static byte[] removeAllInstancesOfOp(byte[] inputScript, int opCode); boolean isOpReturn(); @Deprecated static void executeScript(@Nullable Transaction txContainingThis, long index, Script script, LinkedList<byte[]> stack, boolean enforceNullDummy); @Deprecated static void executeScript(@Nullable Transaction txContainingThis, long index, Script script, LinkedList<byte[]> stack, Set<VerifyFlag> verifyFlags); static void executeScript(@Nullable Transaction txContainingThis, long index, Script script, LinkedList<byte[]> stack, Coin value, Set<VerifyFlag> verifyFlags); @Deprecated void correctlySpends(Transaction txContainingThis, long scriptSigIndex, Script scriptPubKey); @Deprecated void correctlySpends(Transaction txContainingThis, long scriptSigIndex, Script scriptPubKey, Set<VerifyFlag> verifyFlags); void correctlySpends(Transaction txContainingThis, long scriptSigIndex, Script scriptPubKey, Coin value, Set<VerifyFlag> verifyFlags); ScriptType getScriptType(); @Override boolean equals(Object o); @Override int hashCode(); static final EnumSet<VerifyFlag> ALL_VERIFY_FLAGS; static final long MAX_SCRIPT_ELEMENT_SIZE; static final int SIG_SIZE; static final int MAX_P2SH_SIGOPS; }
@Test public void numberBuilderBigNum() { ScriptBuilder builder = new ScriptBuilder(); builder.number(0x524a); assertArrayEquals(new byte[] { 0x02, 0x4a, 0x52 }, builder.build().getProgram()); builder = new ScriptBuilder(); builder.number(0x110011); assertEquals(4, builder.build().getProgram().length); builder = new ScriptBuilder(); builder.number(0x8000); assertArrayEquals(new byte[] { 0x03, 0x00, (byte) 0x80, 0x00 }, builder.build().getProgram()); }
public byte[] getProgram() { try { if (program != null) return Arrays.copyOf(program, program.length); ByteArrayOutputStream bos = new ByteArrayOutputStream(); for (ScriptChunk chunk : chunks) { chunk.write(bos); } program = bos.toByteArray(); return program; } catch (IOException e) { throw new RuntimeException(e); } }
Script { public byte[] getProgram() { try { if (program != null) return Arrays.copyOf(program, program.length); ByteArrayOutputStream bos = new ByteArrayOutputStream(); for (ScriptChunk chunk : chunks) { chunk.write(bos); } program = bos.toByteArray(); return program; } catch (IOException e) { throw new RuntimeException(e); } } }
Script { public byte[] getProgram() { try { if (program != null) return Arrays.copyOf(program, program.length); ByteArrayOutputStream bos = new ByteArrayOutputStream(); for (ScriptChunk chunk : chunks) { chunk.write(bos); } program = bos.toByteArray(); return program; } catch (IOException e) { throw new RuntimeException(e); } } private Script(); Script(List<ScriptChunk> chunks); Script(byte[] programBytes); Script(byte[] programBytes, long creationTimeSeconds); }
Script { public byte[] getProgram() { try { if (program != null) return Arrays.copyOf(program, program.length); ByteArrayOutputStream bos = new ByteArrayOutputStream(); for (ScriptChunk chunk : chunks) { chunk.write(bos); } program = bos.toByteArray(); return program; } catch (IOException e) { throw new RuntimeException(e); } } private Script(); Script(List<ScriptChunk> chunks); Script(byte[] programBytes); Script(byte[] programBytes, long creationTimeSeconds); long getCreationTimeSeconds(); void setCreationTimeSeconds(long creationTimeSeconds); @Override String toString(); byte[] getProgram(); List<ScriptChunk> getChunks(); boolean isSentToRawPubKey(); boolean isSentToAddress(); @Deprecated boolean isSentToP2SH(); byte[] getPubKeyHash(); byte[] getPubKey(); byte[] getCLTVPaymentChannelSenderPubKey(); byte[] getCLTVPaymentChannelRecipientPubKey(); BigInteger getCLTVPaymentChannelExpiry(); @Deprecated Address getFromAddress(NetworkParameters params); Address getToAddress(NetworkParameters params); Address getToAddress(NetworkParameters params, boolean forcePayToPubKey); static void writeBytes(OutputStream os, byte[] buf); static byte[] createMultiSigOutputScript(int threshold, List<ECKey> pubkeys); static byte[] createInputScript(byte[] signature, byte[] pubkey); static byte[] createInputScript(byte[] signature); Script createEmptyInputScript(@Nullable ECKey key, @Nullable Script redeemScript); Script getScriptSigWithSignature(Script scriptSig, byte[] sigBytes, int index); int getSigInsertionIndex(Sha256Hash hash, ECKey signingKey); List<ECKey> getPubKeys(); static int getSigOpCount(byte[] program); static long getP2SHSigOpCount(byte[] scriptSig); int getNumberOfSignaturesRequiredToSpend(); int getNumberOfBytesRequiredToSpend(@Nullable ECKey pubKey, @Nullable Script redeemScript); boolean isPayToScriptHash(); boolean isSentToMultiSig(); boolean isSentToCLTVPaymentChannel(); static byte[] removeAllInstancesOf(byte[] inputScript, byte[] chunkToRemove); static byte[] removeAllInstancesOfOp(byte[] inputScript, int opCode); boolean isOpReturn(); @Deprecated static void executeScript(@Nullable Transaction txContainingThis, long index, Script script, LinkedList<byte[]> stack, boolean enforceNullDummy); @Deprecated static void executeScript(@Nullable Transaction txContainingThis, long index, Script script, LinkedList<byte[]> stack, Set<VerifyFlag> verifyFlags); static void executeScript(@Nullable Transaction txContainingThis, long index, Script script, LinkedList<byte[]> stack, Coin value, Set<VerifyFlag> verifyFlags); @Deprecated void correctlySpends(Transaction txContainingThis, long scriptSigIndex, Script scriptPubKey); @Deprecated void correctlySpends(Transaction txContainingThis, long scriptSigIndex, Script scriptPubKey, Set<VerifyFlag> verifyFlags); void correctlySpends(Transaction txContainingThis, long scriptSigIndex, Script scriptPubKey, Coin value, Set<VerifyFlag> verifyFlags); ScriptType getScriptType(); @Override boolean equals(Object o); @Override int hashCode(); }
Script { public byte[] getProgram() { try { if (program != null) return Arrays.copyOf(program, program.length); ByteArrayOutputStream bos = new ByteArrayOutputStream(); for (ScriptChunk chunk : chunks) { chunk.write(bos); } program = bos.toByteArray(); return program; } catch (IOException e) { throw new RuntimeException(e); } } private Script(); Script(List<ScriptChunk> chunks); Script(byte[] programBytes); Script(byte[] programBytes, long creationTimeSeconds); long getCreationTimeSeconds(); void setCreationTimeSeconds(long creationTimeSeconds); @Override String toString(); byte[] getProgram(); List<ScriptChunk> getChunks(); boolean isSentToRawPubKey(); boolean isSentToAddress(); @Deprecated boolean isSentToP2SH(); byte[] getPubKeyHash(); byte[] getPubKey(); byte[] getCLTVPaymentChannelSenderPubKey(); byte[] getCLTVPaymentChannelRecipientPubKey(); BigInteger getCLTVPaymentChannelExpiry(); @Deprecated Address getFromAddress(NetworkParameters params); Address getToAddress(NetworkParameters params); Address getToAddress(NetworkParameters params, boolean forcePayToPubKey); static void writeBytes(OutputStream os, byte[] buf); static byte[] createMultiSigOutputScript(int threshold, List<ECKey> pubkeys); static byte[] createInputScript(byte[] signature, byte[] pubkey); static byte[] createInputScript(byte[] signature); Script createEmptyInputScript(@Nullable ECKey key, @Nullable Script redeemScript); Script getScriptSigWithSignature(Script scriptSig, byte[] sigBytes, int index); int getSigInsertionIndex(Sha256Hash hash, ECKey signingKey); List<ECKey> getPubKeys(); static int getSigOpCount(byte[] program); static long getP2SHSigOpCount(byte[] scriptSig); int getNumberOfSignaturesRequiredToSpend(); int getNumberOfBytesRequiredToSpend(@Nullable ECKey pubKey, @Nullable Script redeemScript); boolean isPayToScriptHash(); boolean isSentToMultiSig(); boolean isSentToCLTVPaymentChannel(); static byte[] removeAllInstancesOf(byte[] inputScript, byte[] chunkToRemove); static byte[] removeAllInstancesOfOp(byte[] inputScript, int opCode); boolean isOpReturn(); @Deprecated static void executeScript(@Nullable Transaction txContainingThis, long index, Script script, LinkedList<byte[]> stack, boolean enforceNullDummy); @Deprecated static void executeScript(@Nullable Transaction txContainingThis, long index, Script script, LinkedList<byte[]> stack, Set<VerifyFlag> verifyFlags); static void executeScript(@Nullable Transaction txContainingThis, long index, Script script, LinkedList<byte[]> stack, Coin value, Set<VerifyFlag> verifyFlags); @Deprecated void correctlySpends(Transaction txContainingThis, long scriptSigIndex, Script scriptPubKey); @Deprecated void correctlySpends(Transaction txContainingThis, long scriptSigIndex, Script scriptPubKey, Set<VerifyFlag> verifyFlags); void correctlySpends(Transaction txContainingThis, long scriptSigIndex, Script scriptPubKey, Coin value, Set<VerifyFlag> verifyFlags); ScriptType getScriptType(); @Override boolean equals(Object o); @Override int hashCode(); static final EnumSet<VerifyFlag> ALL_VERIFY_FLAGS; static final long MAX_SCRIPT_ELEMENT_SIZE; static final int SIG_SIZE; static final int MAX_P2SH_SIGOPS; }
@Test public void numberBuilderNegative() { final ScriptBuilder builder = new ScriptBuilder(); builder.number(-5); assertArrayEquals(new byte[] { 0x01, ((byte) 133) }, builder.build().getProgram()); }
public byte[] getProgram() { try { if (program != null) return Arrays.copyOf(program, program.length); ByteArrayOutputStream bos = new ByteArrayOutputStream(); for (ScriptChunk chunk : chunks) { chunk.write(bos); } program = bos.toByteArray(); return program; } catch (IOException e) { throw new RuntimeException(e); } }
Script { public byte[] getProgram() { try { if (program != null) return Arrays.copyOf(program, program.length); ByteArrayOutputStream bos = new ByteArrayOutputStream(); for (ScriptChunk chunk : chunks) { chunk.write(bos); } program = bos.toByteArray(); return program; } catch (IOException e) { throw new RuntimeException(e); } } }
Script { public byte[] getProgram() { try { if (program != null) return Arrays.copyOf(program, program.length); ByteArrayOutputStream bos = new ByteArrayOutputStream(); for (ScriptChunk chunk : chunks) { chunk.write(bos); } program = bos.toByteArray(); return program; } catch (IOException e) { throw new RuntimeException(e); } } private Script(); Script(List<ScriptChunk> chunks); Script(byte[] programBytes); Script(byte[] programBytes, long creationTimeSeconds); }
Script { public byte[] getProgram() { try { if (program != null) return Arrays.copyOf(program, program.length); ByteArrayOutputStream bos = new ByteArrayOutputStream(); for (ScriptChunk chunk : chunks) { chunk.write(bos); } program = bos.toByteArray(); return program; } catch (IOException e) { throw new RuntimeException(e); } } private Script(); Script(List<ScriptChunk> chunks); Script(byte[] programBytes); Script(byte[] programBytes, long creationTimeSeconds); long getCreationTimeSeconds(); void setCreationTimeSeconds(long creationTimeSeconds); @Override String toString(); byte[] getProgram(); List<ScriptChunk> getChunks(); boolean isSentToRawPubKey(); boolean isSentToAddress(); @Deprecated boolean isSentToP2SH(); byte[] getPubKeyHash(); byte[] getPubKey(); byte[] getCLTVPaymentChannelSenderPubKey(); byte[] getCLTVPaymentChannelRecipientPubKey(); BigInteger getCLTVPaymentChannelExpiry(); @Deprecated Address getFromAddress(NetworkParameters params); Address getToAddress(NetworkParameters params); Address getToAddress(NetworkParameters params, boolean forcePayToPubKey); static void writeBytes(OutputStream os, byte[] buf); static byte[] createMultiSigOutputScript(int threshold, List<ECKey> pubkeys); static byte[] createInputScript(byte[] signature, byte[] pubkey); static byte[] createInputScript(byte[] signature); Script createEmptyInputScript(@Nullable ECKey key, @Nullable Script redeemScript); Script getScriptSigWithSignature(Script scriptSig, byte[] sigBytes, int index); int getSigInsertionIndex(Sha256Hash hash, ECKey signingKey); List<ECKey> getPubKeys(); static int getSigOpCount(byte[] program); static long getP2SHSigOpCount(byte[] scriptSig); int getNumberOfSignaturesRequiredToSpend(); int getNumberOfBytesRequiredToSpend(@Nullable ECKey pubKey, @Nullable Script redeemScript); boolean isPayToScriptHash(); boolean isSentToMultiSig(); boolean isSentToCLTVPaymentChannel(); static byte[] removeAllInstancesOf(byte[] inputScript, byte[] chunkToRemove); static byte[] removeAllInstancesOfOp(byte[] inputScript, int opCode); boolean isOpReturn(); @Deprecated static void executeScript(@Nullable Transaction txContainingThis, long index, Script script, LinkedList<byte[]> stack, boolean enforceNullDummy); @Deprecated static void executeScript(@Nullable Transaction txContainingThis, long index, Script script, LinkedList<byte[]> stack, Set<VerifyFlag> verifyFlags); static void executeScript(@Nullable Transaction txContainingThis, long index, Script script, LinkedList<byte[]> stack, Coin value, Set<VerifyFlag> verifyFlags); @Deprecated void correctlySpends(Transaction txContainingThis, long scriptSigIndex, Script scriptPubKey); @Deprecated void correctlySpends(Transaction txContainingThis, long scriptSigIndex, Script scriptPubKey, Set<VerifyFlag> verifyFlags); void correctlySpends(Transaction txContainingThis, long scriptSigIndex, Script scriptPubKey, Coin value, Set<VerifyFlag> verifyFlags); ScriptType getScriptType(); @Override boolean equals(Object o); @Override int hashCode(); }
Script { public byte[] getProgram() { try { if (program != null) return Arrays.copyOf(program, program.length); ByteArrayOutputStream bos = new ByteArrayOutputStream(); for (ScriptChunk chunk : chunks) { chunk.write(bos); } program = bos.toByteArray(); return program; } catch (IOException e) { throw new RuntimeException(e); } } private Script(); Script(List<ScriptChunk> chunks); Script(byte[] programBytes); Script(byte[] programBytes, long creationTimeSeconds); long getCreationTimeSeconds(); void setCreationTimeSeconds(long creationTimeSeconds); @Override String toString(); byte[] getProgram(); List<ScriptChunk> getChunks(); boolean isSentToRawPubKey(); boolean isSentToAddress(); @Deprecated boolean isSentToP2SH(); byte[] getPubKeyHash(); byte[] getPubKey(); byte[] getCLTVPaymentChannelSenderPubKey(); byte[] getCLTVPaymentChannelRecipientPubKey(); BigInteger getCLTVPaymentChannelExpiry(); @Deprecated Address getFromAddress(NetworkParameters params); Address getToAddress(NetworkParameters params); Address getToAddress(NetworkParameters params, boolean forcePayToPubKey); static void writeBytes(OutputStream os, byte[] buf); static byte[] createMultiSigOutputScript(int threshold, List<ECKey> pubkeys); static byte[] createInputScript(byte[] signature, byte[] pubkey); static byte[] createInputScript(byte[] signature); Script createEmptyInputScript(@Nullable ECKey key, @Nullable Script redeemScript); Script getScriptSigWithSignature(Script scriptSig, byte[] sigBytes, int index); int getSigInsertionIndex(Sha256Hash hash, ECKey signingKey); List<ECKey> getPubKeys(); static int getSigOpCount(byte[] program); static long getP2SHSigOpCount(byte[] scriptSig); int getNumberOfSignaturesRequiredToSpend(); int getNumberOfBytesRequiredToSpend(@Nullable ECKey pubKey, @Nullable Script redeemScript); boolean isPayToScriptHash(); boolean isSentToMultiSig(); boolean isSentToCLTVPaymentChannel(); static byte[] removeAllInstancesOf(byte[] inputScript, byte[] chunkToRemove); static byte[] removeAllInstancesOfOp(byte[] inputScript, int opCode); boolean isOpReturn(); @Deprecated static void executeScript(@Nullable Transaction txContainingThis, long index, Script script, LinkedList<byte[]> stack, boolean enforceNullDummy); @Deprecated static void executeScript(@Nullable Transaction txContainingThis, long index, Script script, LinkedList<byte[]> stack, Set<VerifyFlag> verifyFlags); static void executeScript(@Nullable Transaction txContainingThis, long index, Script script, LinkedList<byte[]> stack, Coin value, Set<VerifyFlag> verifyFlags); @Deprecated void correctlySpends(Transaction txContainingThis, long scriptSigIndex, Script scriptPubKey); @Deprecated void correctlySpends(Transaction txContainingThis, long scriptSigIndex, Script scriptPubKey, Set<VerifyFlag> verifyFlags); void correctlySpends(Transaction txContainingThis, long scriptSigIndex, Script scriptPubKey, Coin value, Set<VerifyFlag> verifyFlags); ScriptType getScriptType(); @Override boolean equals(Object o); @Override int hashCode(); static final EnumSet<VerifyFlag> ALL_VERIFY_FLAGS; static final long MAX_SCRIPT_ELEMENT_SIZE; static final int SIG_SIZE; static final int MAX_P2SH_SIGOPS; }
@Test public void numberBuilder16() { ScriptBuilder builder = new ScriptBuilder(); builder.number(15).number(16).number(17); builder.number(0, 17).number(1, 16).number(2, 15); Script script = builder.build(); assertEquals("PUSHDATA(1)[11] 16 15 15 16 PUSHDATA(1)[11]", script.toString()); }
@Override public String toString() { return Utils.join(chunks); }
Script { @Override public String toString() { return Utils.join(chunks); } }
Script { @Override public String toString() { return Utils.join(chunks); } private Script(); Script(List<ScriptChunk> chunks); Script(byte[] programBytes); Script(byte[] programBytes, long creationTimeSeconds); }
Script { @Override public String toString() { return Utils.join(chunks); } private Script(); Script(List<ScriptChunk> chunks); Script(byte[] programBytes); Script(byte[] programBytes, long creationTimeSeconds); long getCreationTimeSeconds(); void setCreationTimeSeconds(long creationTimeSeconds); @Override String toString(); byte[] getProgram(); List<ScriptChunk> getChunks(); boolean isSentToRawPubKey(); boolean isSentToAddress(); @Deprecated boolean isSentToP2SH(); byte[] getPubKeyHash(); byte[] getPubKey(); byte[] getCLTVPaymentChannelSenderPubKey(); byte[] getCLTVPaymentChannelRecipientPubKey(); BigInteger getCLTVPaymentChannelExpiry(); @Deprecated Address getFromAddress(NetworkParameters params); Address getToAddress(NetworkParameters params); Address getToAddress(NetworkParameters params, boolean forcePayToPubKey); static void writeBytes(OutputStream os, byte[] buf); static byte[] createMultiSigOutputScript(int threshold, List<ECKey> pubkeys); static byte[] createInputScript(byte[] signature, byte[] pubkey); static byte[] createInputScript(byte[] signature); Script createEmptyInputScript(@Nullable ECKey key, @Nullable Script redeemScript); Script getScriptSigWithSignature(Script scriptSig, byte[] sigBytes, int index); int getSigInsertionIndex(Sha256Hash hash, ECKey signingKey); List<ECKey> getPubKeys(); static int getSigOpCount(byte[] program); static long getP2SHSigOpCount(byte[] scriptSig); int getNumberOfSignaturesRequiredToSpend(); int getNumberOfBytesRequiredToSpend(@Nullable ECKey pubKey, @Nullable Script redeemScript); boolean isPayToScriptHash(); boolean isSentToMultiSig(); boolean isSentToCLTVPaymentChannel(); static byte[] removeAllInstancesOf(byte[] inputScript, byte[] chunkToRemove); static byte[] removeAllInstancesOfOp(byte[] inputScript, int opCode); boolean isOpReturn(); @Deprecated static void executeScript(@Nullable Transaction txContainingThis, long index, Script script, LinkedList<byte[]> stack, boolean enforceNullDummy); @Deprecated static void executeScript(@Nullable Transaction txContainingThis, long index, Script script, LinkedList<byte[]> stack, Set<VerifyFlag> verifyFlags); static void executeScript(@Nullable Transaction txContainingThis, long index, Script script, LinkedList<byte[]> stack, Coin value, Set<VerifyFlag> verifyFlags); @Deprecated void correctlySpends(Transaction txContainingThis, long scriptSigIndex, Script scriptPubKey); @Deprecated void correctlySpends(Transaction txContainingThis, long scriptSigIndex, Script scriptPubKey, Set<VerifyFlag> verifyFlags); void correctlySpends(Transaction txContainingThis, long scriptSigIndex, Script scriptPubKey, Coin value, Set<VerifyFlag> verifyFlags); ScriptType getScriptType(); @Override boolean equals(Object o); @Override int hashCode(); }
Script { @Override public String toString() { return Utils.join(chunks); } private Script(); Script(List<ScriptChunk> chunks); Script(byte[] programBytes); Script(byte[] programBytes, long creationTimeSeconds); long getCreationTimeSeconds(); void setCreationTimeSeconds(long creationTimeSeconds); @Override String toString(); byte[] getProgram(); List<ScriptChunk> getChunks(); boolean isSentToRawPubKey(); boolean isSentToAddress(); @Deprecated boolean isSentToP2SH(); byte[] getPubKeyHash(); byte[] getPubKey(); byte[] getCLTVPaymentChannelSenderPubKey(); byte[] getCLTVPaymentChannelRecipientPubKey(); BigInteger getCLTVPaymentChannelExpiry(); @Deprecated Address getFromAddress(NetworkParameters params); Address getToAddress(NetworkParameters params); Address getToAddress(NetworkParameters params, boolean forcePayToPubKey); static void writeBytes(OutputStream os, byte[] buf); static byte[] createMultiSigOutputScript(int threshold, List<ECKey> pubkeys); static byte[] createInputScript(byte[] signature, byte[] pubkey); static byte[] createInputScript(byte[] signature); Script createEmptyInputScript(@Nullable ECKey key, @Nullable Script redeemScript); Script getScriptSigWithSignature(Script scriptSig, byte[] sigBytes, int index); int getSigInsertionIndex(Sha256Hash hash, ECKey signingKey); List<ECKey> getPubKeys(); static int getSigOpCount(byte[] program); static long getP2SHSigOpCount(byte[] scriptSig); int getNumberOfSignaturesRequiredToSpend(); int getNumberOfBytesRequiredToSpend(@Nullable ECKey pubKey, @Nullable Script redeemScript); boolean isPayToScriptHash(); boolean isSentToMultiSig(); boolean isSentToCLTVPaymentChannel(); static byte[] removeAllInstancesOf(byte[] inputScript, byte[] chunkToRemove); static byte[] removeAllInstancesOfOp(byte[] inputScript, int opCode); boolean isOpReturn(); @Deprecated static void executeScript(@Nullable Transaction txContainingThis, long index, Script script, LinkedList<byte[]> stack, boolean enforceNullDummy); @Deprecated static void executeScript(@Nullable Transaction txContainingThis, long index, Script script, LinkedList<byte[]> stack, Set<VerifyFlag> verifyFlags); static void executeScript(@Nullable Transaction txContainingThis, long index, Script script, LinkedList<byte[]> stack, Coin value, Set<VerifyFlag> verifyFlags); @Deprecated void correctlySpends(Transaction txContainingThis, long scriptSigIndex, Script scriptPubKey); @Deprecated void correctlySpends(Transaction txContainingThis, long scriptSigIndex, Script scriptPubKey, Set<VerifyFlag> verifyFlags); void correctlySpends(Transaction txContainingThis, long scriptSigIndex, Script scriptPubKey, Coin value, Set<VerifyFlag> verifyFlags); ScriptType getScriptType(); @Override boolean equals(Object o); @Override int hashCode(); static final EnumSet<VerifyFlag> ALL_VERIFY_FLAGS; static final long MAX_SCRIPT_ELEMENT_SIZE; static final int SIG_SIZE; static final int MAX_P2SH_SIGOPS; }
@Test public void shouldSendClientVersionOnChannelOpen() throws Exception { PaymentChannelClient dut = new PaymentChannelClient(wallet, ecKey, maxValue, serverHash, connection, versionSelector); connection.sendToServer(capture(clientVersionCapture)); EasyMock.expect(wallet.getExtensions()).andReturn(new HashMap<String, WalletExtension>()); replay(connection, wallet); dut.connectionOpen(); assertClientVersion(defaultTimeWindow); }
@Override public void connectionOpen() { lock.lock(); try { connectionOpen = true; StoredPaymentChannelClientStates channels = (StoredPaymentChannelClientStates) wallet.getExtensions().get(StoredPaymentChannelClientStates.EXTENSION_ID); if (channels != null) storedChannel = channels.getUsableChannelForServerID(serverId); step = InitStep.WAITING_FOR_VERSION_NEGOTIATION; Protos.ClientVersion.Builder versionNegotiationBuilder = Protos.ClientVersion.newBuilder() .setMajor(versionSelector.getRequestedMajorVersion()) .setMinor(versionSelector.getRequestedMinorVersion()) .setTimeWindowSecs(timeWindow); if (storedChannel != null) { versionNegotiationBuilder.setPreviousChannelContractHash(ByteString.copyFrom(storedChannel.contract.getHash().getBytes())); log.info("Begun version handshake, attempting to reopen channel with contract hash {}", storedChannel.contract.getHash()); } else log.info("Begun version handshake creating new channel"); conn.sendToServer(Protos.TwoWayChannelMessage.newBuilder() .setType(Protos.TwoWayChannelMessage.MessageType.CLIENT_VERSION) .setClientVersion(versionNegotiationBuilder) .build()); } finally { lock.unlock(); } }
PaymentChannelClient implements IPaymentChannelClient { @Override public void connectionOpen() { lock.lock(); try { connectionOpen = true; StoredPaymentChannelClientStates channels = (StoredPaymentChannelClientStates) wallet.getExtensions().get(StoredPaymentChannelClientStates.EXTENSION_ID); if (channels != null) storedChannel = channels.getUsableChannelForServerID(serverId); step = InitStep.WAITING_FOR_VERSION_NEGOTIATION; Protos.ClientVersion.Builder versionNegotiationBuilder = Protos.ClientVersion.newBuilder() .setMajor(versionSelector.getRequestedMajorVersion()) .setMinor(versionSelector.getRequestedMinorVersion()) .setTimeWindowSecs(timeWindow); if (storedChannel != null) { versionNegotiationBuilder.setPreviousChannelContractHash(ByteString.copyFrom(storedChannel.contract.getHash().getBytes())); log.info("Begun version handshake, attempting to reopen channel with contract hash {}", storedChannel.contract.getHash()); } else log.info("Begun version handshake creating new channel"); conn.sendToServer(Protos.TwoWayChannelMessage.newBuilder() .setType(Protos.TwoWayChannelMessage.MessageType.CLIENT_VERSION) .setClientVersion(versionNegotiationBuilder) .build()); } finally { lock.unlock(); } } }
PaymentChannelClient implements IPaymentChannelClient { @Override public void connectionOpen() { lock.lock(); try { connectionOpen = true; StoredPaymentChannelClientStates channels = (StoredPaymentChannelClientStates) wallet.getExtensions().get(StoredPaymentChannelClientStates.EXTENSION_ID); if (channels != null) storedChannel = channels.getUsableChannelForServerID(serverId); step = InitStep.WAITING_FOR_VERSION_NEGOTIATION; Protos.ClientVersion.Builder versionNegotiationBuilder = Protos.ClientVersion.newBuilder() .setMajor(versionSelector.getRequestedMajorVersion()) .setMinor(versionSelector.getRequestedMinorVersion()) .setTimeWindowSecs(timeWindow); if (storedChannel != null) { versionNegotiationBuilder.setPreviousChannelContractHash(ByteString.copyFrom(storedChannel.contract.getHash().getBytes())); log.info("Begun version handshake, attempting to reopen channel with contract hash {}", storedChannel.contract.getHash()); } else log.info("Begun version handshake creating new channel"); conn.sendToServer(Protos.TwoWayChannelMessage.newBuilder() .setType(Protos.TwoWayChannelMessage.MessageType.CLIENT_VERSION) .setClientVersion(versionNegotiationBuilder) .build()); } finally { lock.unlock(); } } PaymentChannelClient(Wallet wallet, ECKey myKey, Coin maxValue, Sha256Hash serverId, ClientConnection conn); PaymentChannelClient(Wallet wallet, ECKey myKey, Coin maxValue, Sha256Hash serverId, ClientConnection conn, VersionSelector versionSelector); PaymentChannelClient(Wallet wallet, ECKey myKey, Coin maxValue, Sha256Hash serverId, long timeWindow, @Nullable KeyParameter userKeySetup, ClientConnection conn); PaymentChannelClient(Wallet wallet, ECKey myKey, Coin maxValue, Sha256Hash serverId, long timeWindow, @Nullable KeyParameter userKeySetup, ClientConnection conn, VersionSelector versionSelector); }
PaymentChannelClient implements IPaymentChannelClient { @Override public void connectionOpen() { lock.lock(); try { connectionOpen = true; StoredPaymentChannelClientStates channels = (StoredPaymentChannelClientStates) wallet.getExtensions().get(StoredPaymentChannelClientStates.EXTENSION_ID); if (channels != null) storedChannel = channels.getUsableChannelForServerID(serverId); step = InitStep.WAITING_FOR_VERSION_NEGOTIATION; Protos.ClientVersion.Builder versionNegotiationBuilder = Protos.ClientVersion.newBuilder() .setMajor(versionSelector.getRequestedMajorVersion()) .setMinor(versionSelector.getRequestedMinorVersion()) .setTimeWindowSecs(timeWindow); if (storedChannel != null) { versionNegotiationBuilder.setPreviousChannelContractHash(ByteString.copyFrom(storedChannel.contract.getHash().getBytes())); log.info("Begun version handshake, attempting to reopen channel with contract hash {}", storedChannel.contract.getHash()); } else log.info("Begun version handshake creating new channel"); conn.sendToServer(Protos.TwoWayChannelMessage.newBuilder() .setType(Protos.TwoWayChannelMessage.MessageType.CLIENT_VERSION) .setClientVersion(versionNegotiationBuilder) .build()); } finally { lock.unlock(); } } PaymentChannelClient(Wallet wallet, ECKey myKey, Coin maxValue, Sha256Hash serverId, ClientConnection conn); PaymentChannelClient(Wallet wallet, ECKey myKey, Coin maxValue, Sha256Hash serverId, ClientConnection conn, VersionSelector versionSelector); PaymentChannelClient(Wallet wallet, ECKey myKey, Coin maxValue, Sha256Hash serverId, long timeWindow, @Nullable KeyParameter userKeySetup, ClientConnection conn); PaymentChannelClient(Wallet wallet, ECKey myKey, Coin maxValue, Sha256Hash serverId, long timeWindow, @Nullable KeyParameter userKeySetup, ClientConnection conn, VersionSelector versionSelector); Coin getMissing(); @Override void receiveMessage(Protos.TwoWayChannelMessage msg); @Override void connectionClosed(); @Override void settle(); @Override void connectionOpen(); PaymentChannelClientState state(); ListenableFuture<PaymentIncrementAck> incrementPayment(Coin size); @Override ListenableFuture<PaymentIncrementAck> incrementPayment(Coin size, @Nullable ByteString info, @Nullable KeyParameter userKey); }
PaymentChannelClient implements IPaymentChannelClient { @Override public void connectionOpen() { lock.lock(); try { connectionOpen = true; StoredPaymentChannelClientStates channels = (StoredPaymentChannelClientStates) wallet.getExtensions().get(StoredPaymentChannelClientStates.EXTENSION_ID); if (channels != null) storedChannel = channels.getUsableChannelForServerID(serverId); step = InitStep.WAITING_FOR_VERSION_NEGOTIATION; Protos.ClientVersion.Builder versionNegotiationBuilder = Protos.ClientVersion.newBuilder() .setMajor(versionSelector.getRequestedMajorVersion()) .setMinor(versionSelector.getRequestedMinorVersion()) .setTimeWindowSecs(timeWindow); if (storedChannel != null) { versionNegotiationBuilder.setPreviousChannelContractHash(ByteString.copyFrom(storedChannel.contract.getHash().getBytes())); log.info("Begun version handshake, attempting to reopen channel with contract hash {}", storedChannel.contract.getHash()); } else log.info("Begun version handshake creating new channel"); conn.sendToServer(Protos.TwoWayChannelMessage.newBuilder() .setType(Protos.TwoWayChannelMessage.MessageType.CLIENT_VERSION) .setClientVersion(versionNegotiationBuilder) .build()); } finally { lock.unlock(); } } PaymentChannelClient(Wallet wallet, ECKey myKey, Coin maxValue, Sha256Hash serverId, ClientConnection conn); PaymentChannelClient(Wallet wallet, ECKey myKey, Coin maxValue, Sha256Hash serverId, ClientConnection conn, VersionSelector versionSelector); PaymentChannelClient(Wallet wallet, ECKey myKey, Coin maxValue, Sha256Hash serverId, long timeWindow, @Nullable KeyParameter userKeySetup, ClientConnection conn); PaymentChannelClient(Wallet wallet, ECKey myKey, Coin maxValue, Sha256Hash serverId, long timeWindow, @Nullable KeyParameter userKeySetup, ClientConnection conn, VersionSelector versionSelector); Coin getMissing(); @Override void receiveMessage(Protos.TwoWayChannelMessage msg); @Override void connectionClosed(); @Override void settle(); @Override void connectionOpen(); PaymentChannelClientState state(); ListenableFuture<PaymentIncrementAck> incrementPayment(Coin size); @Override ListenableFuture<PaymentIncrementAck> incrementPayment(Coin size, @Nullable ByteString info, @Nullable KeyParameter userKey); static final long DEFAULT_TIME_WINDOW; }
@Test public void shouldSendTimeWindowInClientVersion() throws Exception { long timeWindow = 4000; KeyParameter userKey = null; PaymentChannelClient dut = new PaymentChannelClient(wallet, ecKey, maxValue, serverHash, timeWindow, userKey, connection, versionSelector); connection.sendToServer(capture(clientVersionCapture)); EasyMock.expect(wallet.getExtensions()).andReturn(new HashMap<String, WalletExtension>()); replay(connection, wallet); dut.connectionOpen(); assertClientVersion(4000); }
@Override public void connectionOpen() { lock.lock(); try { connectionOpen = true; StoredPaymentChannelClientStates channels = (StoredPaymentChannelClientStates) wallet.getExtensions().get(StoredPaymentChannelClientStates.EXTENSION_ID); if (channels != null) storedChannel = channels.getUsableChannelForServerID(serverId); step = InitStep.WAITING_FOR_VERSION_NEGOTIATION; Protos.ClientVersion.Builder versionNegotiationBuilder = Protos.ClientVersion.newBuilder() .setMajor(versionSelector.getRequestedMajorVersion()) .setMinor(versionSelector.getRequestedMinorVersion()) .setTimeWindowSecs(timeWindow); if (storedChannel != null) { versionNegotiationBuilder.setPreviousChannelContractHash(ByteString.copyFrom(storedChannel.contract.getHash().getBytes())); log.info("Begun version handshake, attempting to reopen channel with contract hash {}", storedChannel.contract.getHash()); } else log.info("Begun version handshake creating new channel"); conn.sendToServer(Protos.TwoWayChannelMessage.newBuilder() .setType(Protos.TwoWayChannelMessage.MessageType.CLIENT_VERSION) .setClientVersion(versionNegotiationBuilder) .build()); } finally { lock.unlock(); } }
PaymentChannelClient implements IPaymentChannelClient { @Override public void connectionOpen() { lock.lock(); try { connectionOpen = true; StoredPaymentChannelClientStates channels = (StoredPaymentChannelClientStates) wallet.getExtensions().get(StoredPaymentChannelClientStates.EXTENSION_ID); if (channels != null) storedChannel = channels.getUsableChannelForServerID(serverId); step = InitStep.WAITING_FOR_VERSION_NEGOTIATION; Protos.ClientVersion.Builder versionNegotiationBuilder = Protos.ClientVersion.newBuilder() .setMajor(versionSelector.getRequestedMajorVersion()) .setMinor(versionSelector.getRequestedMinorVersion()) .setTimeWindowSecs(timeWindow); if (storedChannel != null) { versionNegotiationBuilder.setPreviousChannelContractHash(ByteString.copyFrom(storedChannel.contract.getHash().getBytes())); log.info("Begun version handshake, attempting to reopen channel with contract hash {}", storedChannel.contract.getHash()); } else log.info("Begun version handshake creating new channel"); conn.sendToServer(Protos.TwoWayChannelMessage.newBuilder() .setType(Protos.TwoWayChannelMessage.MessageType.CLIENT_VERSION) .setClientVersion(versionNegotiationBuilder) .build()); } finally { lock.unlock(); } } }
PaymentChannelClient implements IPaymentChannelClient { @Override public void connectionOpen() { lock.lock(); try { connectionOpen = true; StoredPaymentChannelClientStates channels = (StoredPaymentChannelClientStates) wallet.getExtensions().get(StoredPaymentChannelClientStates.EXTENSION_ID); if (channels != null) storedChannel = channels.getUsableChannelForServerID(serverId); step = InitStep.WAITING_FOR_VERSION_NEGOTIATION; Protos.ClientVersion.Builder versionNegotiationBuilder = Protos.ClientVersion.newBuilder() .setMajor(versionSelector.getRequestedMajorVersion()) .setMinor(versionSelector.getRequestedMinorVersion()) .setTimeWindowSecs(timeWindow); if (storedChannel != null) { versionNegotiationBuilder.setPreviousChannelContractHash(ByteString.copyFrom(storedChannel.contract.getHash().getBytes())); log.info("Begun version handshake, attempting to reopen channel with contract hash {}", storedChannel.contract.getHash()); } else log.info("Begun version handshake creating new channel"); conn.sendToServer(Protos.TwoWayChannelMessage.newBuilder() .setType(Protos.TwoWayChannelMessage.MessageType.CLIENT_VERSION) .setClientVersion(versionNegotiationBuilder) .build()); } finally { lock.unlock(); } } PaymentChannelClient(Wallet wallet, ECKey myKey, Coin maxValue, Sha256Hash serverId, ClientConnection conn); PaymentChannelClient(Wallet wallet, ECKey myKey, Coin maxValue, Sha256Hash serverId, ClientConnection conn, VersionSelector versionSelector); PaymentChannelClient(Wallet wallet, ECKey myKey, Coin maxValue, Sha256Hash serverId, long timeWindow, @Nullable KeyParameter userKeySetup, ClientConnection conn); PaymentChannelClient(Wallet wallet, ECKey myKey, Coin maxValue, Sha256Hash serverId, long timeWindow, @Nullable KeyParameter userKeySetup, ClientConnection conn, VersionSelector versionSelector); }
PaymentChannelClient implements IPaymentChannelClient { @Override public void connectionOpen() { lock.lock(); try { connectionOpen = true; StoredPaymentChannelClientStates channels = (StoredPaymentChannelClientStates) wallet.getExtensions().get(StoredPaymentChannelClientStates.EXTENSION_ID); if (channels != null) storedChannel = channels.getUsableChannelForServerID(serverId); step = InitStep.WAITING_FOR_VERSION_NEGOTIATION; Protos.ClientVersion.Builder versionNegotiationBuilder = Protos.ClientVersion.newBuilder() .setMajor(versionSelector.getRequestedMajorVersion()) .setMinor(versionSelector.getRequestedMinorVersion()) .setTimeWindowSecs(timeWindow); if (storedChannel != null) { versionNegotiationBuilder.setPreviousChannelContractHash(ByteString.copyFrom(storedChannel.contract.getHash().getBytes())); log.info("Begun version handshake, attempting to reopen channel with contract hash {}", storedChannel.contract.getHash()); } else log.info("Begun version handshake creating new channel"); conn.sendToServer(Protos.TwoWayChannelMessage.newBuilder() .setType(Protos.TwoWayChannelMessage.MessageType.CLIENT_VERSION) .setClientVersion(versionNegotiationBuilder) .build()); } finally { lock.unlock(); } } PaymentChannelClient(Wallet wallet, ECKey myKey, Coin maxValue, Sha256Hash serverId, ClientConnection conn); PaymentChannelClient(Wallet wallet, ECKey myKey, Coin maxValue, Sha256Hash serverId, ClientConnection conn, VersionSelector versionSelector); PaymentChannelClient(Wallet wallet, ECKey myKey, Coin maxValue, Sha256Hash serverId, long timeWindow, @Nullable KeyParameter userKeySetup, ClientConnection conn); PaymentChannelClient(Wallet wallet, ECKey myKey, Coin maxValue, Sha256Hash serverId, long timeWindow, @Nullable KeyParameter userKeySetup, ClientConnection conn, VersionSelector versionSelector); Coin getMissing(); @Override void receiveMessage(Protos.TwoWayChannelMessage msg); @Override void connectionClosed(); @Override void settle(); @Override void connectionOpen(); PaymentChannelClientState state(); ListenableFuture<PaymentIncrementAck> incrementPayment(Coin size); @Override ListenableFuture<PaymentIncrementAck> incrementPayment(Coin size, @Nullable ByteString info, @Nullable KeyParameter userKey); }
PaymentChannelClient implements IPaymentChannelClient { @Override public void connectionOpen() { lock.lock(); try { connectionOpen = true; StoredPaymentChannelClientStates channels = (StoredPaymentChannelClientStates) wallet.getExtensions().get(StoredPaymentChannelClientStates.EXTENSION_ID); if (channels != null) storedChannel = channels.getUsableChannelForServerID(serverId); step = InitStep.WAITING_FOR_VERSION_NEGOTIATION; Protos.ClientVersion.Builder versionNegotiationBuilder = Protos.ClientVersion.newBuilder() .setMajor(versionSelector.getRequestedMajorVersion()) .setMinor(versionSelector.getRequestedMinorVersion()) .setTimeWindowSecs(timeWindow); if (storedChannel != null) { versionNegotiationBuilder.setPreviousChannelContractHash(ByteString.copyFrom(storedChannel.contract.getHash().getBytes())); log.info("Begun version handshake, attempting to reopen channel with contract hash {}", storedChannel.contract.getHash()); } else log.info("Begun version handshake creating new channel"); conn.sendToServer(Protos.TwoWayChannelMessage.newBuilder() .setType(Protos.TwoWayChannelMessage.MessageType.CLIENT_VERSION) .setClientVersion(versionNegotiationBuilder) .build()); } finally { lock.unlock(); } } PaymentChannelClient(Wallet wallet, ECKey myKey, Coin maxValue, Sha256Hash serverId, ClientConnection conn); PaymentChannelClient(Wallet wallet, ECKey myKey, Coin maxValue, Sha256Hash serverId, ClientConnection conn, VersionSelector versionSelector); PaymentChannelClient(Wallet wallet, ECKey myKey, Coin maxValue, Sha256Hash serverId, long timeWindow, @Nullable KeyParameter userKeySetup, ClientConnection conn); PaymentChannelClient(Wallet wallet, ECKey myKey, Coin maxValue, Sha256Hash serverId, long timeWindow, @Nullable KeyParameter userKeySetup, ClientConnection conn, VersionSelector versionSelector); Coin getMissing(); @Override void receiveMessage(Protos.TwoWayChannelMessage msg); @Override void connectionClosed(); @Override void settle(); @Override void connectionOpen(); PaymentChannelClientState state(); ListenableFuture<PaymentIncrementAck> incrementPayment(Coin size); @Override ListenableFuture<PaymentIncrementAck> incrementPayment(Coin size, @Nullable ByteString info, @Nullable KeyParameter userKey); static final long DEFAULT_TIME_WINDOW; }
@Test @Ignore public void getPeer_one() throws Exception{ SeedPeers seedPeers = new SeedPeers(MainNetParams.get()); assertThat(seedPeers.getPeer(), notNullValue()); }
@Nullable public InetSocketAddress getPeer() throws PeerDiscoveryException { try { return nextPeer(); } catch (UnknownHostException e) { throw new PeerDiscoveryException(e); } }
SeedPeers implements PeerDiscovery { @Nullable public InetSocketAddress getPeer() throws PeerDiscoveryException { try { return nextPeer(); } catch (UnknownHostException e) { throw new PeerDiscoveryException(e); } } }
SeedPeers implements PeerDiscovery { @Nullable public InetSocketAddress getPeer() throws PeerDiscoveryException { try { return nextPeer(); } catch (UnknownHostException e) { throw new PeerDiscoveryException(e); } } SeedPeers(NetworkParameters params); SeedPeers(int[] seedAddrs, NetworkParameters params); }
SeedPeers implements PeerDiscovery { @Nullable public InetSocketAddress getPeer() throws PeerDiscoveryException { try { return nextPeer(); } catch (UnknownHostException e) { throw new PeerDiscoveryException(e); } } SeedPeers(NetworkParameters params); SeedPeers(int[] seedAddrs, NetworkParameters params); @Nullable InetSocketAddress getPeer(); @Override InetSocketAddress[] getPeers(long services, long timeoutValue, TimeUnit timeoutUnit); @Override void shutdown(); }
SeedPeers implements PeerDiscovery { @Nullable public InetSocketAddress getPeer() throws PeerDiscoveryException { try { return nextPeer(); } catch (UnknownHostException e) { throw new PeerDiscoveryException(e); } } SeedPeers(NetworkParameters params); SeedPeers(int[] seedAddrs, NetworkParameters params); @Nullable InetSocketAddress getPeer(); @Override InetSocketAddress[] getPeers(long services, long timeoutValue, TimeUnit timeoutUnit); @Override void shutdown(); }
@Test @Ignore public void getPeer_all() throws Exception{ SeedPeers seedPeers = new SeedPeers(MainNetParams.get()); for (int i = 0; i < MainNetParams.get().getAddrSeeds().length; ++i) { assertThat("Failed on index: "+i, seedPeers.getPeer(), notNullValue()); } assertThat(seedPeers.getPeer(), equalTo(null)); }
@Nullable public InetSocketAddress getPeer() throws PeerDiscoveryException { try { return nextPeer(); } catch (UnknownHostException e) { throw new PeerDiscoveryException(e); } }
SeedPeers implements PeerDiscovery { @Nullable public InetSocketAddress getPeer() throws PeerDiscoveryException { try { return nextPeer(); } catch (UnknownHostException e) { throw new PeerDiscoveryException(e); } } }
SeedPeers implements PeerDiscovery { @Nullable public InetSocketAddress getPeer() throws PeerDiscoveryException { try { return nextPeer(); } catch (UnknownHostException e) { throw new PeerDiscoveryException(e); } } SeedPeers(NetworkParameters params); SeedPeers(int[] seedAddrs, NetworkParameters params); }
SeedPeers implements PeerDiscovery { @Nullable public InetSocketAddress getPeer() throws PeerDiscoveryException { try { return nextPeer(); } catch (UnknownHostException e) { throw new PeerDiscoveryException(e); } } SeedPeers(NetworkParameters params); SeedPeers(int[] seedAddrs, NetworkParameters params); @Nullable InetSocketAddress getPeer(); @Override InetSocketAddress[] getPeers(long services, long timeoutValue, TimeUnit timeoutUnit); @Override void shutdown(); }
SeedPeers implements PeerDiscovery { @Nullable public InetSocketAddress getPeer() throws PeerDiscoveryException { try { return nextPeer(); } catch (UnknownHostException e) { throw new PeerDiscoveryException(e); } } SeedPeers(NetworkParameters params); SeedPeers(int[] seedAddrs, NetworkParameters params); @Nullable InetSocketAddress getPeer(); @Override InetSocketAddress[] getPeers(long services, long timeoutValue, TimeUnit timeoutUnit); @Override void shutdown(); }
@Test @Ignore public void getPeers_length() throws Exception{ SeedPeers seedPeers = new SeedPeers(MainNetParams.get()); InetSocketAddress[] addresses = seedPeers.getPeers(0, 0, TimeUnit.SECONDS); assertThat(addresses.length, equalTo(MainNetParams.get().getAddrSeeds().length)); }
@Override public InetSocketAddress[] getPeers(long services, long timeoutValue, TimeUnit timeoutUnit) throws PeerDiscoveryException { if (services != 0) throw new PeerDiscoveryException("Pre-determined peers cannot be filtered by services: " + services); try { return allPeers(); } catch (UnknownHostException e) { throw new PeerDiscoveryException(e); } }
SeedPeers implements PeerDiscovery { @Override public InetSocketAddress[] getPeers(long services, long timeoutValue, TimeUnit timeoutUnit) throws PeerDiscoveryException { if (services != 0) throw new PeerDiscoveryException("Pre-determined peers cannot be filtered by services: " + services); try { return allPeers(); } catch (UnknownHostException e) { throw new PeerDiscoveryException(e); } } }
SeedPeers implements PeerDiscovery { @Override public InetSocketAddress[] getPeers(long services, long timeoutValue, TimeUnit timeoutUnit) throws PeerDiscoveryException { if (services != 0) throw new PeerDiscoveryException("Pre-determined peers cannot be filtered by services: " + services); try { return allPeers(); } catch (UnknownHostException e) { throw new PeerDiscoveryException(e); } } SeedPeers(NetworkParameters params); SeedPeers(int[] seedAddrs, NetworkParameters params); }
SeedPeers implements PeerDiscovery { @Override public InetSocketAddress[] getPeers(long services, long timeoutValue, TimeUnit timeoutUnit) throws PeerDiscoveryException { if (services != 0) throw new PeerDiscoveryException("Pre-determined peers cannot be filtered by services: " + services); try { return allPeers(); } catch (UnknownHostException e) { throw new PeerDiscoveryException(e); } } SeedPeers(NetworkParameters params); SeedPeers(int[] seedAddrs, NetworkParameters params); @Nullable InetSocketAddress getPeer(); @Override InetSocketAddress[] getPeers(long services, long timeoutValue, TimeUnit timeoutUnit); @Override void shutdown(); }
SeedPeers implements PeerDiscovery { @Override public InetSocketAddress[] getPeers(long services, long timeoutValue, TimeUnit timeoutUnit) throws PeerDiscoveryException { if (services != 0) throw new PeerDiscoveryException("Pre-determined peers cannot be filtered by services: " + services); try { return allPeers(); } catch (UnknownHostException e) { throw new PeerDiscoveryException(e); } } SeedPeers(NetworkParameters params); SeedPeers(int[] seedAddrs, NetworkParameters params); @Nullable InetSocketAddress getPeer(); @Override InetSocketAddress[] getPeers(long services, long timeoutValue, TimeUnit timeoutUnit); @Override void shutdown(); }
@Test public void testInitialize() throws BlockStoreException { final BlockStore blockStore = new MemoryBlockStore(PARAMS); final BlockChain chain = new BlockChain(PARAMS, blockStore); long timeSeconds = 1231006505; StoredBlock chainHead = null; for (int height = 0; height < PARAMS.getMajorityWindow(); height++) { chainHead = FakeTxBuilder.createFakeBlock(blockStore, 2, timeSeconds, height).storedBlock; assertEquals(2, chainHead.getHeader().getVersion()); timeSeconds += 60; } VersionTally instance = new VersionTally(PARAMS); instance.initialize(blockStore, chainHead); assertEquals(PARAMS.getMajorityWindow(), instance.getCountAtOrAbove(2).intValue()); }
public void initialize(final BlockStore blockStore, final StoredBlock chainHead) throws BlockStoreException { StoredBlock versionBlock = chainHead; final Stack<Long> versions = new Stack<Long>(); versions.push(versionBlock.getHeader().getVersion()); for (int headOffset = 0; headOffset < versionWindow.length; headOffset++) { versionBlock = versionBlock.getPrev(blockStore); if (null == versionBlock) { break; } versions.push(versionBlock.getHeader().getVersion()); } while (!versions.isEmpty()) { add(versions.pop()); } }
VersionTally { public void initialize(final BlockStore blockStore, final StoredBlock chainHead) throws BlockStoreException { StoredBlock versionBlock = chainHead; final Stack<Long> versions = new Stack<Long>(); versions.push(versionBlock.getHeader().getVersion()); for (int headOffset = 0; headOffset < versionWindow.length; headOffset++) { versionBlock = versionBlock.getPrev(blockStore); if (null == versionBlock) { break; } versions.push(versionBlock.getHeader().getVersion()); } while (!versions.isEmpty()) { add(versions.pop()); } } }
VersionTally { public void initialize(final BlockStore blockStore, final StoredBlock chainHead) throws BlockStoreException { StoredBlock versionBlock = chainHead; final Stack<Long> versions = new Stack<Long>(); versions.push(versionBlock.getHeader().getVersion()); for (int headOffset = 0; headOffset < versionWindow.length; headOffset++) { versionBlock = versionBlock.getPrev(blockStore); if (null == versionBlock) { break; } versions.push(versionBlock.getHeader().getVersion()); } while (!versions.isEmpty()) { add(versions.pop()); } } VersionTally(final NetworkParameters params); }
VersionTally { public void initialize(final BlockStore blockStore, final StoredBlock chainHead) throws BlockStoreException { StoredBlock versionBlock = chainHead; final Stack<Long> versions = new Stack<Long>(); versions.push(versionBlock.getHeader().getVersion()); for (int headOffset = 0; headOffset < versionWindow.length; headOffset++) { versionBlock = versionBlock.getPrev(blockStore); if (null == versionBlock) { break; } versions.push(versionBlock.getHeader().getVersion()); } while (!versions.isEmpty()) { add(versions.pop()); } } VersionTally(final NetworkParameters params); void add(final long version); Integer getCountAtOrAbove(final long version); void initialize(final BlockStore blockStore, final StoredBlock chainHead); int size(); }
VersionTally { public void initialize(final BlockStore blockStore, final StoredBlock chainHead) throws BlockStoreException { StoredBlock versionBlock = chainHead; final Stack<Long> versions = new Stack<Long>(); versions.push(versionBlock.getHeader().getVersion()); for (int headOffset = 0; headOffset < versionWindow.length; headOffset++) { versionBlock = versionBlock.getPrev(blockStore); if (null == versionBlock) { break; } versions.push(versionBlock.getHeader().getVersion()); } while (!versions.isEmpty()) { add(versions.pop()); } } VersionTally(final NetworkParameters params); void add(final long version); Integer getCountAtOrAbove(final long version); void initialize(final BlockStore blockStore, final StoredBlock chainHead); int size(); }
@Test public void testInQueue() { PriorityQueue<ExponentialBackoff> queue = new PriorityQueue<ExponentialBackoff>(); ExponentialBackoff backoff1 = new ExponentialBackoff(params); backoff.trackFailure(); backoff.trackFailure(); backoff1.trackFailure(); backoff1.trackFailure(); backoff1.trackFailure(); queue.offer(backoff); queue.offer(backoff1); assertEquals(queue.poll(), backoff); assertEquals(queue.peek(), backoff1); queue.offer(backoff); assertEquals(queue.poll(), backoff); }
public void trackFailure() { retryTime = Utils.currentTimeMillis() + (long)backoff; backoff = Math.min(backoff * params.multiplier, params.maximum); }
ExponentialBackoff implements Comparable<ExponentialBackoff> { public void trackFailure() { retryTime = Utils.currentTimeMillis() + (long)backoff; backoff = Math.min(backoff * params.multiplier, params.maximum); } }
ExponentialBackoff implements Comparable<ExponentialBackoff> { public void trackFailure() { retryTime = Utils.currentTimeMillis() + (long)backoff; backoff = Math.min(backoff * params.multiplier, params.maximum); } ExponentialBackoff(Params params); }
ExponentialBackoff implements Comparable<ExponentialBackoff> { public void trackFailure() { retryTime = Utils.currentTimeMillis() + (long)backoff; backoff = Math.min(backoff * params.multiplier, params.maximum); } ExponentialBackoff(Params params); final void trackSuccess(); void trackFailure(); long getRetryTime(); @Override int compareTo(ExponentialBackoff other); @Override String toString(); }
ExponentialBackoff implements Comparable<ExponentialBackoff> { public void trackFailure() { retryTime = Utils.currentTimeMillis() + (long)backoff; backoff = Math.min(backoff * params.multiplier, params.maximum); } ExponentialBackoff(Params params); final void trackSuccess(); void trackFailure(); long getRetryTime(); @Override int compareTo(ExponentialBackoff other); @Override String toString(); static final int DEFAULT_INITIAL_MILLIS; static final float DEFAULT_MULTIPLIER; static final int DEFAULT_MAXIMUM_MILLIS; }
@Test public void repeatOptionalDecimals() { assertEquals("0.00000001", formatRepeat(SATOSHI, 2, 4)); assertEquals("0.00000010", formatRepeat(SATOSHI.multiply(10), 2, 4)); assertEquals("0.01", formatRepeat(CENT, 2, 4)); assertEquals("0.10", formatRepeat(CENT.multiply(10), 2, 4)); assertEquals("0", formatRepeat(SATOSHI, 2, 2)); assertEquals("0", formatRepeat(SATOSHI.multiply(10), 2, 2)); assertEquals("0.01", formatRepeat(CENT, 2, 2)); assertEquals("0.10", formatRepeat(CENT.multiply(10), 2, 2)); assertEquals("0", formatRepeat(CENT, 2, 0)); assertEquals("0", formatRepeat(CENT.multiply(10), 2, 0)); }
public MonetaryFormat repeatOptionalDecimals(int decimals, int repetitions) { checkArgument(repetitions >= 0); List<Integer> decimalGroups = new ArrayList<Integer>(repetitions); for (int i = 0; i < repetitions; i++) decimalGroups.add(decimals); return new MonetaryFormat(negativeSign, positiveSign, zeroDigit, decimalMark, minDecimals, decimalGroups, shift, roundingMode, codes, codeSeparator, codePrefixed); }
MonetaryFormat { public MonetaryFormat repeatOptionalDecimals(int decimals, int repetitions) { checkArgument(repetitions >= 0); List<Integer> decimalGroups = new ArrayList<Integer>(repetitions); for (int i = 0; i < repetitions; i++) decimalGroups.add(decimals); return new MonetaryFormat(negativeSign, positiveSign, zeroDigit, decimalMark, minDecimals, decimalGroups, shift, roundingMode, codes, codeSeparator, codePrefixed); } }
MonetaryFormat { public MonetaryFormat repeatOptionalDecimals(int decimals, int repetitions) { checkArgument(repetitions >= 0); List<Integer> decimalGroups = new ArrayList<Integer>(repetitions); for (int i = 0; i < repetitions; i++) decimalGroups.add(decimals); return new MonetaryFormat(negativeSign, positiveSign, zeroDigit, decimalMark, minDecimals, decimalGroups, shift, roundingMode, codes, codeSeparator, codePrefixed); } MonetaryFormat(); private MonetaryFormat(char negativeSign, char positiveSign, char zeroDigit, char decimalMark, int minDecimals, List<Integer> decimalGroups, int shift, RoundingMode roundingMode, String[] codes, char codeSeparator, boolean codePrefixed); }
MonetaryFormat { public MonetaryFormat repeatOptionalDecimals(int decimals, int repetitions) { checkArgument(repetitions >= 0); List<Integer> decimalGroups = new ArrayList<Integer>(repetitions); for (int i = 0; i < repetitions; i++) decimalGroups.add(decimals); return new MonetaryFormat(negativeSign, positiveSign, zeroDigit, decimalMark, minDecimals, decimalGroups, shift, roundingMode, codes, codeSeparator, codePrefixed); } MonetaryFormat(); private MonetaryFormat(char negativeSign, char positiveSign, char zeroDigit, char decimalMark, int minDecimals, List<Integer> decimalGroups, int shift, RoundingMode roundingMode, String[] codes, char codeSeparator, boolean codePrefixed); MonetaryFormat negativeSign(char negativeSign); MonetaryFormat positiveSign(char positiveSign); MonetaryFormat digits(char zeroDigit); MonetaryFormat decimalMark(char decimalMark); MonetaryFormat minDecimals(int minDecimals); MonetaryFormat optionalDecimals(int... groups); MonetaryFormat repeatOptionalDecimals(int decimals, int repetitions); MonetaryFormat shift(int shift); MonetaryFormat roundingMode(RoundingMode roundingMode); MonetaryFormat noCode(); MonetaryFormat code(int codeShift, String code); MonetaryFormat codeSeparator(char codeSeparator); MonetaryFormat prefixCode(); MonetaryFormat postfixCode(); MonetaryFormat withLocale(Locale locale); CharSequence format(Monetary monetary); Coin parse(String str); Fiat parseFiat(String currencyCode, String str); String code(); }
MonetaryFormat { public MonetaryFormat repeatOptionalDecimals(int decimals, int repetitions) { checkArgument(repetitions >= 0); List<Integer> decimalGroups = new ArrayList<Integer>(repetitions); for (int i = 0; i < repetitions; i++) decimalGroups.add(decimals); return new MonetaryFormat(negativeSign, positiveSign, zeroDigit, decimalMark, minDecimals, decimalGroups, shift, roundingMode, codes, codeSeparator, codePrefixed); } MonetaryFormat(); private MonetaryFormat(char negativeSign, char positiveSign, char zeroDigit, char decimalMark, int minDecimals, List<Integer> decimalGroups, int shift, RoundingMode roundingMode, String[] codes, char codeSeparator, boolean codePrefixed); MonetaryFormat negativeSign(char negativeSign); MonetaryFormat positiveSign(char positiveSign); MonetaryFormat digits(char zeroDigit); MonetaryFormat decimalMark(char decimalMark); MonetaryFormat minDecimals(int minDecimals); MonetaryFormat optionalDecimals(int... groups); MonetaryFormat repeatOptionalDecimals(int decimals, int repetitions); MonetaryFormat shift(int shift); MonetaryFormat roundingMode(RoundingMode roundingMode); MonetaryFormat noCode(); MonetaryFormat code(int codeShift, String code); MonetaryFormat codeSeparator(char codeSeparator); MonetaryFormat prefixCode(); MonetaryFormat postfixCode(); MonetaryFormat withLocale(Locale locale); CharSequence format(Monetary monetary); Coin parse(String str); Fiat parseFiat(String currencyCode, String str); String code(); static final MonetaryFormat BTC; static final MonetaryFormat MBTC; static final MonetaryFormat UBTC; static final MonetaryFormat FIAT; static final String CODE_BTC; static final String CODE_MBTC; static final String CODE_UBTC; static final int MAX_DECIMALS; }
@Test public void standardCodes() throws Exception { assertEquals("BCH 0.00", MonetaryFormat.BTC.format(Coin.ZERO).toString()); assertEquals("mBCH 0.00", MonetaryFormat.MBTC.format(Coin.ZERO).toString()); assertEquals("µBCH 0", MonetaryFormat.UBTC.format(Coin.ZERO).toString()); }
public CharSequence format(Monetary monetary) { int maxDecimals = minDecimals; if (decimalGroups != null) for (int group : decimalGroups) maxDecimals += group; int smallestUnitExponent = monetary.smallestUnitExponent(); checkState(maxDecimals <= smallestUnitExponent, "The maximum possible number of decimals (%s) cannot exceed %s.", maxDecimals, smallestUnitExponent); long satoshis = Math.abs(monetary.getValue()); long precisionDivisor = checkedPow(10, smallestUnitExponent - shift - maxDecimals); satoshis = checkedMultiply(divide(satoshis, precisionDivisor, roundingMode), precisionDivisor); long shiftDivisor = checkedPow(10, smallestUnitExponent - shift); long numbers = satoshis / shiftDivisor; long decimals = satoshis % shiftDivisor; String decimalsStr = String.format(Locale.US, "%0" + (smallestUnitExponent - shift) + "d", decimals); StringBuilder str = new StringBuilder(decimalsStr); while (str.length() > minDecimals && str.charAt(str.length() - 1) == '0') str.setLength(str.length() - 1); int i = minDecimals; if (decimalGroups != null) { for (int group : decimalGroups) { if (str.length() > i && str.length() < i + group) { while (str.length() < i + group) str.append('0'); break; } i += group; } } if (str.length() > 0) str.insert(0, decimalMark); str.insert(0, numbers); if (monetary.getValue() < 0) str.insert(0, negativeSign); else if (positiveSign != 0) str.insert(0, positiveSign); if (codes != null) { if (codePrefixed) { str.insert(0, codeSeparator); str.insert(0, code()); } else { str.append(codeSeparator); str.append(code()); } } if (zeroDigit != '0') { int offset = zeroDigit - '0'; for (int d = 0; d < str.length(); d++) { char c = str.charAt(d); if (Character.isDigit(c)) str.setCharAt(d, (char) (c + offset)); } } return str; }
MonetaryFormat { public CharSequence format(Monetary monetary) { int maxDecimals = minDecimals; if (decimalGroups != null) for (int group : decimalGroups) maxDecimals += group; int smallestUnitExponent = monetary.smallestUnitExponent(); checkState(maxDecimals <= smallestUnitExponent, "The maximum possible number of decimals (%s) cannot exceed %s.", maxDecimals, smallestUnitExponent); long satoshis = Math.abs(monetary.getValue()); long precisionDivisor = checkedPow(10, smallestUnitExponent - shift - maxDecimals); satoshis = checkedMultiply(divide(satoshis, precisionDivisor, roundingMode), precisionDivisor); long shiftDivisor = checkedPow(10, smallestUnitExponent - shift); long numbers = satoshis / shiftDivisor; long decimals = satoshis % shiftDivisor; String decimalsStr = String.format(Locale.US, "%0" + (smallestUnitExponent - shift) + "d", decimals); StringBuilder str = new StringBuilder(decimalsStr); while (str.length() > minDecimals && str.charAt(str.length() - 1) == '0') str.setLength(str.length() - 1); int i = minDecimals; if (decimalGroups != null) { for (int group : decimalGroups) { if (str.length() > i && str.length() < i + group) { while (str.length() < i + group) str.append('0'); break; } i += group; } } if (str.length() > 0) str.insert(0, decimalMark); str.insert(0, numbers); if (monetary.getValue() < 0) str.insert(0, negativeSign); else if (positiveSign != 0) str.insert(0, positiveSign); if (codes != null) { if (codePrefixed) { str.insert(0, codeSeparator); str.insert(0, code()); } else { str.append(codeSeparator); str.append(code()); } } if (zeroDigit != '0') { int offset = zeroDigit - '0'; for (int d = 0; d < str.length(); d++) { char c = str.charAt(d); if (Character.isDigit(c)) str.setCharAt(d, (char) (c + offset)); } } return str; } }
MonetaryFormat { public CharSequence format(Monetary monetary) { int maxDecimals = minDecimals; if (decimalGroups != null) for (int group : decimalGroups) maxDecimals += group; int smallestUnitExponent = monetary.smallestUnitExponent(); checkState(maxDecimals <= smallestUnitExponent, "The maximum possible number of decimals (%s) cannot exceed %s.", maxDecimals, smallestUnitExponent); long satoshis = Math.abs(monetary.getValue()); long precisionDivisor = checkedPow(10, smallestUnitExponent - shift - maxDecimals); satoshis = checkedMultiply(divide(satoshis, precisionDivisor, roundingMode), precisionDivisor); long shiftDivisor = checkedPow(10, smallestUnitExponent - shift); long numbers = satoshis / shiftDivisor; long decimals = satoshis % shiftDivisor; String decimalsStr = String.format(Locale.US, "%0" + (smallestUnitExponent - shift) + "d", decimals); StringBuilder str = new StringBuilder(decimalsStr); while (str.length() > minDecimals && str.charAt(str.length() - 1) == '0') str.setLength(str.length() - 1); int i = minDecimals; if (decimalGroups != null) { for (int group : decimalGroups) { if (str.length() > i && str.length() < i + group) { while (str.length() < i + group) str.append('0'); break; } i += group; } } if (str.length() > 0) str.insert(0, decimalMark); str.insert(0, numbers); if (monetary.getValue() < 0) str.insert(0, negativeSign); else if (positiveSign != 0) str.insert(0, positiveSign); if (codes != null) { if (codePrefixed) { str.insert(0, codeSeparator); str.insert(0, code()); } else { str.append(codeSeparator); str.append(code()); } } if (zeroDigit != '0') { int offset = zeroDigit - '0'; for (int d = 0; d < str.length(); d++) { char c = str.charAt(d); if (Character.isDigit(c)) str.setCharAt(d, (char) (c + offset)); } } return str; } MonetaryFormat(); private MonetaryFormat(char negativeSign, char positiveSign, char zeroDigit, char decimalMark, int minDecimals, List<Integer> decimalGroups, int shift, RoundingMode roundingMode, String[] codes, char codeSeparator, boolean codePrefixed); }
MonetaryFormat { public CharSequence format(Monetary monetary) { int maxDecimals = minDecimals; if (decimalGroups != null) for (int group : decimalGroups) maxDecimals += group; int smallestUnitExponent = monetary.smallestUnitExponent(); checkState(maxDecimals <= smallestUnitExponent, "The maximum possible number of decimals (%s) cannot exceed %s.", maxDecimals, smallestUnitExponent); long satoshis = Math.abs(monetary.getValue()); long precisionDivisor = checkedPow(10, smallestUnitExponent - shift - maxDecimals); satoshis = checkedMultiply(divide(satoshis, precisionDivisor, roundingMode), precisionDivisor); long shiftDivisor = checkedPow(10, smallestUnitExponent - shift); long numbers = satoshis / shiftDivisor; long decimals = satoshis % shiftDivisor; String decimalsStr = String.format(Locale.US, "%0" + (smallestUnitExponent - shift) + "d", decimals); StringBuilder str = new StringBuilder(decimalsStr); while (str.length() > minDecimals && str.charAt(str.length() - 1) == '0') str.setLength(str.length() - 1); int i = minDecimals; if (decimalGroups != null) { for (int group : decimalGroups) { if (str.length() > i && str.length() < i + group) { while (str.length() < i + group) str.append('0'); break; } i += group; } } if (str.length() > 0) str.insert(0, decimalMark); str.insert(0, numbers); if (monetary.getValue() < 0) str.insert(0, negativeSign); else if (positiveSign != 0) str.insert(0, positiveSign); if (codes != null) { if (codePrefixed) { str.insert(0, codeSeparator); str.insert(0, code()); } else { str.append(codeSeparator); str.append(code()); } } if (zeroDigit != '0') { int offset = zeroDigit - '0'; for (int d = 0; d < str.length(); d++) { char c = str.charAt(d); if (Character.isDigit(c)) str.setCharAt(d, (char) (c + offset)); } } return str; } MonetaryFormat(); private MonetaryFormat(char negativeSign, char positiveSign, char zeroDigit, char decimalMark, int minDecimals, List<Integer> decimalGroups, int shift, RoundingMode roundingMode, String[] codes, char codeSeparator, boolean codePrefixed); MonetaryFormat negativeSign(char negativeSign); MonetaryFormat positiveSign(char positiveSign); MonetaryFormat digits(char zeroDigit); MonetaryFormat decimalMark(char decimalMark); MonetaryFormat minDecimals(int minDecimals); MonetaryFormat optionalDecimals(int... groups); MonetaryFormat repeatOptionalDecimals(int decimals, int repetitions); MonetaryFormat shift(int shift); MonetaryFormat roundingMode(RoundingMode roundingMode); MonetaryFormat noCode(); MonetaryFormat code(int codeShift, String code); MonetaryFormat codeSeparator(char codeSeparator); MonetaryFormat prefixCode(); MonetaryFormat postfixCode(); MonetaryFormat withLocale(Locale locale); CharSequence format(Monetary monetary); Coin parse(String str); Fiat parseFiat(String currencyCode, String str); String code(); }
MonetaryFormat { public CharSequence format(Monetary monetary) { int maxDecimals = minDecimals; if (decimalGroups != null) for (int group : decimalGroups) maxDecimals += group; int smallestUnitExponent = monetary.smallestUnitExponent(); checkState(maxDecimals <= smallestUnitExponent, "The maximum possible number of decimals (%s) cannot exceed %s.", maxDecimals, smallestUnitExponent); long satoshis = Math.abs(monetary.getValue()); long precisionDivisor = checkedPow(10, smallestUnitExponent - shift - maxDecimals); satoshis = checkedMultiply(divide(satoshis, precisionDivisor, roundingMode), precisionDivisor); long shiftDivisor = checkedPow(10, smallestUnitExponent - shift); long numbers = satoshis / shiftDivisor; long decimals = satoshis % shiftDivisor; String decimalsStr = String.format(Locale.US, "%0" + (smallestUnitExponent - shift) + "d", decimals); StringBuilder str = new StringBuilder(decimalsStr); while (str.length() > minDecimals && str.charAt(str.length() - 1) == '0') str.setLength(str.length() - 1); int i = minDecimals; if (decimalGroups != null) { for (int group : decimalGroups) { if (str.length() > i && str.length() < i + group) { while (str.length() < i + group) str.append('0'); break; } i += group; } } if (str.length() > 0) str.insert(0, decimalMark); str.insert(0, numbers); if (monetary.getValue() < 0) str.insert(0, negativeSign); else if (positiveSign != 0) str.insert(0, positiveSign); if (codes != null) { if (codePrefixed) { str.insert(0, codeSeparator); str.insert(0, code()); } else { str.append(codeSeparator); str.append(code()); } } if (zeroDigit != '0') { int offset = zeroDigit - '0'; for (int d = 0; d < str.length(); d++) { char c = str.charAt(d); if (Character.isDigit(c)) str.setCharAt(d, (char) (c + offset)); } } return str; } MonetaryFormat(); private MonetaryFormat(char negativeSign, char positiveSign, char zeroDigit, char decimalMark, int minDecimals, List<Integer> decimalGroups, int shift, RoundingMode roundingMode, String[] codes, char codeSeparator, boolean codePrefixed); MonetaryFormat negativeSign(char negativeSign); MonetaryFormat positiveSign(char positiveSign); MonetaryFormat digits(char zeroDigit); MonetaryFormat decimalMark(char decimalMark); MonetaryFormat minDecimals(int minDecimals); MonetaryFormat optionalDecimals(int... groups); MonetaryFormat repeatOptionalDecimals(int decimals, int repetitions); MonetaryFormat shift(int shift); MonetaryFormat roundingMode(RoundingMode roundingMode); MonetaryFormat noCode(); MonetaryFormat code(int codeShift, String code); MonetaryFormat codeSeparator(char codeSeparator); MonetaryFormat prefixCode(); MonetaryFormat postfixCode(); MonetaryFormat withLocale(Locale locale); CharSequence format(Monetary monetary); Coin parse(String str); Fiat parseFiat(String currencyCode, String str); String code(); static final MonetaryFormat BTC; static final MonetaryFormat MBTC; static final MonetaryFormat UBTC; static final MonetaryFormat FIAT; static final String CODE_BTC; static final String CODE_MBTC; static final String CODE_UBTC; static final int MAX_DECIMALS; }
@Test public void noCode() throws Exception { assertEquals("0", MonetaryFormat.UBTC.noCode().shift(0).format(Coin.ZERO).toString()); assertEquals("dBCH 0", MonetaryFormat.UBTC.noCode().code(1, "dBCH").shift(1).format(Coin.ZERO).toString()); }
public MonetaryFormat noCode() { if (codes == null) return this; else return new MonetaryFormat(negativeSign, positiveSign, zeroDigit, decimalMark, minDecimals, decimalGroups, shift, roundingMode, null, codeSeparator, codePrefixed); }
MonetaryFormat { public MonetaryFormat noCode() { if (codes == null) return this; else return new MonetaryFormat(negativeSign, positiveSign, zeroDigit, decimalMark, minDecimals, decimalGroups, shift, roundingMode, null, codeSeparator, codePrefixed); } }
MonetaryFormat { public MonetaryFormat noCode() { if (codes == null) return this; else return new MonetaryFormat(negativeSign, positiveSign, zeroDigit, decimalMark, minDecimals, decimalGroups, shift, roundingMode, null, codeSeparator, codePrefixed); } MonetaryFormat(); private MonetaryFormat(char negativeSign, char positiveSign, char zeroDigit, char decimalMark, int minDecimals, List<Integer> decimalGroups, int shift, RoundingMode roundingMode, String[] codes, char codeSeparator, boolean codePrefixed); }
MonetaryFormat { public MonetaryFormat noCode() { if (codes == null) return this; else return new MonetaryFormat(negativeSign, positiveSign, zeroDigit, decimalMark, minDecimals, decimalGroups, shift, roundingMode, null, codeSeparator, codePrefixed); } MonetaryFormat(); private MonetaryFormat(char negativeSign, char positiveSign, char zeroDigit, char decimalMark, int minDecimals, List<Integer> decimalGroups, int shift, RoundingMode roundingMode, String[] codes, char codeSeparator, boolean codePrefixed); MonetaryFormat negativeSign(char negativeSign); MonetaryFormat positiveSign(char positiveSign); MonetaryFormat digits(char zeroDigit); MonetaryFormat decimalMark(char decimalMark); MonetaryFormat minDecimals(int minDecimals); MonetaryFormat optionalDecimals(int... groups); MonetaryFormat repeatOptionalDecimals(int decimals, int repetitions); MonetaryFormat shift(int shift); MonetaryFormat roundingMode(RoundingMode roundingMode); MonetaryFormat noCode(); MonetaryFormat code(int codeShift, String code); MonetaryFormat codeSeparator(char codeSeparator); MonetaryFormat prefixCode(); MonetaryFormat postfixCode(); MonetaryFormat withLocale(Locale locale); CharSequence format(Monetary monetary); Coin parse(String str); Fiat parseFiat(String currencyCode, String str); String code(); }
MonetaryFormat { public MonetaryFormat noCode() { if (codes == null) return this; else return new MonetaryFormat(negativeSign, positiveSign, zeroDigit, decimalMark, minDecimals, decimalGroups, shift, roundingMode, null, codeSeparator, codePrefixed); } MonetaryFormat(); private MonetaryFormat(char negativeSign, char positiveSign, char zeroDigit, char decimalMark, int minDecimals, List<Integer> decimalGroups, int shift, RoundingMode roundingMode, String[] codes, char codeSeparator, boolean codePrefixed); MonetaryFormat negativeSign(char negativeSign); MonetaryFormat positiveSign(char positiveSign); MonetaryFormat digits(char zeroDigit); MonetaryFormat decimalMark(char decimalMark); MonetaryFormat minDecimals(int minDecimals); MonetaryFormat optionalDecimals(int... groups); MonetaryFormat repeatOptionalDecimals(int decimals, int repetitions); MonetaryFormat shift(int shift); MonetaryFormat roundingMode(RoundingMode roundingMode); MonetaryFormat noCode(); MonetaryFormat code(int codeShift, String code); MonetaryFormat codeSeparator(char codeSeparator); MonetaryFormat prefixCode(); MonetaryFormat postfixCode(); MonetaryFormat withLocale(Locale locale); CharSequence format(Monetary monetary); Coin parse(String str); Fiat parseFiat(String currencyCode, String str); String code(); static final MonetaryFormat BTC; static final MonetaryFormat MBTC; static final MonetaryFormat UBTC; static final MonetaryFormat FIAT; static final String CODE_BTC; static final String CODE_MBTC; static final String CODE_UBTC; static final int MAX_DECIMALS; }
@Test public void codeSeparator() throws Exception { assertEquals("BCH@0.00", MonetaryFormat.BTC.codeSeparator('@').format(Coin.ZERO).toString()); }
public MonetaryFormat codeSeparator(char codeSeparator) { checkArgument(!Character.isDigit(codeSeparator)); checkArgument(codeSeparator > 0); if (codeSeparator == this.codeSeparator) return this; else return new MonetaryFormat(negativeSign, positiveSign, zeroDigit, decimalMark, minDecimals, decimalGroups, shift, roundingMode, codes, codeSeparator, codePrefixed); }
MonetaryFormat { public MonetaryFormat codeSeparator(char codeSeparator) { checkArgument(!Character.isDigit(codeSeparator)); checkArgument(codeSeparator > 0); if (codeSeparator == this.codeSeparator) return this; else return new MonetaryFormat(negativeSign, positiveSign, zeroDigit, decimalMark, minDecimals, decimalGroups, shift, roundingMode, codes, codeSeparator, codePrefixed); } }
MonetaryFormat { public MonetaryFormat codeSeparator(char codeSeparator) { checkArgument(!Character.isDigit(codeSeparator)); checkArgument(codeSeparator > 0); if (codeSeparator == this.codeSeparator) return this; else return new MonetaryFormat(negativeSign, positiveSign, zeroDigit, decimalMark, minDecimals, decimalGroups, shift, roundingMode, codes, codeSeparator, codePrefixed); } MonetaryFormat(); private MonetaryFormat(char negativeSign, char positiveSign, char zeroDigit, char decimalMark, int minDecimals, List<Integer> decimalGroups, int shift, RoundingMode roundingMode, String[] codes, char codeSeparator, boolean codePrefixed); }
MonetaryFormat { public MonetaryFormat codeSeparator(char codeSeparator) { checkArgument(!Character.isDigit(codeSeparator)); checkArgument(codeSeparator > 0); if (codeSeparator == this.codeSeparator) return this; else return new MonetaryFormat(negativeSign, positiveSign, zeroDigit, decimalMark, minDecimals, decimalGroups, shift, roundingMode, codes, codeSeparator, codePrefixed); } MonetaryFormat(); private MonetaryFormat(char negativeSign, char positiveSign, char zeroDigit, char decimalMark, int minDecimals, List<Integer> decimalGroups, int shift, RoundingMode roundingMode, String[] codes, char codeSeparator, boolean codePrefixed); MonetaryFormat negativeSign(char negativeSign); MonetaryFormat positiveSign(char positiveSign); MonetaryFormat digits(char zeroDigit); MonetaryFormat decimalMark(char decimalMark); MonetaryFormat minDecimals(int minDecimals); MonetaryFormat optionalDecimals(int... groups); MonetaryFormat repeatOptionalDecimals(int decimals, int repetitions); MonetaryFormat shift(int shift); MonetaryFormat roundingMode(RoundingMode roundingMode); MonetaryFormat noCode(); MonetaryFormat code(int codeShift, String code); MonetaryFormat codeSeparator(char codeSeparator); MonetaryFormat prefixCode(); MonetaryFormat postfixCode(); MonetaryFormat withLocale(Locale locale); CharSequence format(Monetary monetary); Coin parse(String str); Fiat parseFiat(String currencyCode, String str); String code(); }
MonetaryFormat { public MonetaryFormat codeSeparator(char codeSeparator) { checkArgument(!Character.isDigit(codeSeparator)); checkArgument(codeSeparator > 0); if (codeSeparator == this.codeSeparator) return this; else return new MonetaryFormat(negativeSign, positiveSign, zeroDigit, decimalMark, minDecimals, decimalGroups, shift, roundingMode, codes, codeSeparator, codePrefixed); } MonetaryFormat(); private MonetaryFormat(char negativeSign, char positiveSign, char zeroDigit, char decimalMark, int minDecimals, List<Integer> decimalGroups, int shift, RoundingMode roundingMode, String[] codes, char codeSeparator, boolean codePrefixed); MonetaryFormat negativeSign(char negativeSign); MonetaryFormat positiveSign(char positiveSign); MonetaryFormat digits(char zeroDigit); MonetaryFormat decimalMark(char decimalMark); MonetaryFormat minDecimals(int minDecimals); MonetaryFormat optionalDecimals(int... groups); MonetaryFormat repeatOptionalDecimals(int decimals, int repetitions); MonetaryFormat shift(int shift); MonetaryFormat roundingMode(RoundingMode roundingMode); MonetaryFormat noCode(); MonetaryFormat code(int codeShift, String code); MonetaryFormat codeSeparator(char codeSeparator); MonetaryFormat prefixCode(); MonetaryFormat postfixCode(); MonetaryFormat withLocale(Locale locale); CharSequence format(Monetary monetary); Coin parse(String str); Fiat parseFiat(String currencyCode, String str); String code(); static final MonetaryFormat BTC; static final MonetaryFormat MBTC; static final MonetaryFormat UBTC; static final MonetaryFormat FIAT; static final String CODE_BTC; static final String CODE_MBTC; static final String CODE_UBTC; static final int MAX_DECIMALS; }
@Test public void testMultiSigOutputToString() throws Exception { sendMoneyToWallet(AbstractBlockChain.NewBlockType.BEST_CHAIN, Coin.COIN); ECKey myKey = new ECKey(); this.wallet.importKey(myKey); ECKey otherKey = new ECKey(); Transaction multiSigTransaction = new Transaction(PARAMS); ImmutableList<ECKey> keys = ImmutableList.of(myKey, otherKey); Script scriptPubKey = ScriptBuilder.createMultiSigOutputScript(2, keys); multiSigTransaction.addOutput(Coin.COIN, scriptPubKey); SendRequest req = SendRequest.forTx(multiSigTransaction); this.wallet.completeTx(req); TransactionOutput multiSigTransactionOutput = multiSigTransaction.getOutput(0); assertThat(multiSigTransactionOutput.toString(), CoreMatchers.containsString("CHECKMULTISIG")); }
@Override public String toString() { try { Script script = getScriptPubKey(); StringBuilder buf = new StringBuilder("TxOut of "); buf.append(Coin.valueOf(value).toFriendlyString()); if (script.isSentToAddress() || script.isPayToScriptHash()) buf.append(" to ").append(script.getToAddress(params)); else if (script.isSentToRawPubKey()) buf.append(" to pubkey ").append(Utils.HEX.encode(script.getPubKey())); else if (script.isSentToMultiSig()) buf.append(" to multisig"); else buf.append(" (unknown type)"); buf.append(" script:").append(script); return buf.toString(); } catch (ScriptException e) { throw new RuntimeException(e); } }
TransactionOutput extends ChildMessage { @Override public String toString() { try { Script script = getScriptPubKey(); StringBuilder buf = new StringBuilder("TxOut of "); buf.append(Coin.valueOf(value).toFriendlyString()); if (script.isSentToAddress() || script.isPayToScriptHash()) buf.append(" to ").append(script.getToAddress(params)); else if (script.isSentToRawPubKey()) buf.append(" to pubkey ").append(Utils.HEX.encode(script.getPubKey())); else if (script.isSentToMultiSig()) buf.append(" to multisig"); else buf.append(" (unknown type)"); buf.append(" script:").append(script); return buf.toString(); } catch (ScriptException e) { throw new RuntimeException(e); } } }
TransactionOutput extends ChildMessage { @Override public String toString() { try { Script script = getScriptPubKey(); StringBuilder buf = new StringBuilder("TxOut of "); buf.append(Coin.valueOf(value).toFriendlyString()); if (script.isSentToAddress() || script.isPayToScriptHash()) buf.append(" to ").append(script.getToAddress(params)); else if (script.isSentToRawPubKey()) buf.append(" to pubkey ").append(Utils.HEX.encode(script.getPubKey())); else if (script.isSentToMultiSig()) buf.append(" to multisig"); else buf.append(" (unknown type)"); buf.append(" script:").append(script); return buf.toString(); } catch (ScriptException e) { throw new RuntimeException(e); } } TransactionOutput(NetworkParameters params, @Nullable Transaction parent, byte[] payload, int offset); TransactionOutput(NetworkParameters params, @Nullable Transaction parent, byte[] payload, int offset, MessageSerializer serializer); TransactionOutput(NetworkParameters params, @Nullable Transaction parent, Coin value, Address to); TransactionOutput(NetworkParameters params, @Nullable Transaction parent, Coin value, ECKey to); TransactionOutput(NetworkParameters params, @Nullable Transaction parent, Coin value, byte[] scriptBytes); }
TransactionOutput extends ChildMessage { @Override public String toString() { try { Script script = getScriptPubKey(); StringBuilder buf = new StringBuilder("TxOut of "); buf.append(Coin.valueOf(value).toFriendlyString()); if (script.isSentToAddress() || script.isPayToScriptHash()) buf.append(" to ").append(script.getToAddress(params)); else if (script.isSentToRawPubKey()) buf.append(" to pubkey ").append(Utils.HEX.encode(script.getPubKey())); else if (script.isSentToMultiSig()) buf.append(" to multisig"); else buf.append(" (unknown type)"); buf.append(" script:").append(script); return buf.toString(); } catch (ScriptException e) { throw new RuntimeException(e); } } TransactionOutput(NetworkParameters params, @Nullable Transaction parent, byte[] payload, int offset); TransactionOutput(NetworkParameters params, @Nullable Transaction parent, byte[] payload, int offset, MessageSerializer serializer); TransactionOutput(NetworkParameters params, @Nullable Transaction parent, Coin value, Address to); TransactionOutput(NetworkParameters params, @Nullable Transaction parent, Coin value, ECKey to); TransactionOutput(NetworkParameters params, @Nullable Transaction parent, Coin value, byte[] scriptBytes); Script getScriptPubKey(); @Nullable Address getAddressFromP2PKHScript(NetworkParameters networkParameters); @Nullable Address getAddressFromP2SH(NetworkParameters networkParameters); Coin getValue(); void setValue(Coin value); int getIndex(); boolean isDust(); Coin getMinNonDustValue(Coin feePerKb); Coin getMinNonDustValue(); void markAsSpent(TransactionInput input); void markAsUnspent(); boolean isAvailableForSpending(); byte[] getScriptBytes(); boolean isMineOrWatched(TransactionBag transactionBag); boolean isWatched(TransactionBag transactionBag); boolean isMine(TransactionBag transactionBag); @Override String toString(); @Nullable TransactionInput getSpentBy(); @Nullable Transaction getParentTransaction(); @Nullable Sha256Hash getParentTransactionHash(); int getParentTransactionDepthInBlocks(); TransactionOutPoint getOutPointFor(); TransactionOutput duplicateDetached(); @Override boolean equals(Object o); @Override int hashCode(); }
TransactionOutput extends ChildMessage { @Override public String toString() { try { Script script = getScriptPubKey(); StringBuilder buf = new StringBuilder("TxOut of "); buf.append(Coin.valueOf(value).toFriendlyString()); if (script.isSentToAddress() || script.isPayToScriptHash()) buf.append(" to ").append(script.getToAddress(params)); else if (script.isSentToRawPubKey()) buf.append(" to pubkey ").append(Utils.HEX.encode(script.getPubKey())); else if (script.isSentToMultiSig()) buf.append(" to multisig"); else buf.append(" (unknown type)"); buf.append(" script:").append(script); return buf.toString(); } catch (ScriptException e) { throw new RuntimeException(e); } } TransactionOutput(NetworkParameters params, @Nullable Transaction parent, byte[] payload, int offset); TransactionOutput(NetworkParameters params, @Nullable Transaction parent, byte[] payload, int offset, MessageSerializer serializer); TransactionOutput(NetworkParameters params, @Nullable Transaction parent, Coin value, Address to); TransactionOutput(NetworkParameters params, @Nullable Transaction parent, Coin value, ECKey to); TransactionOutput(NetworkParameters params, @Nullable Transaction parent, Coin value, byte[] scriptBytes); Script getScriptPubKey(); @Nullable Address getAddressFromP2PKHScript(NetworkParameters networkParameters); @Nullable Address getAddressFromP2SH(NetworkParameters networkParameters); Coin getValue(); void setValue(Coin value); int getIndex(); boolean isDust(); Coin getMinNonDustValue(Coin feePerKb); Coin getMinNonDustValue(); void markAsSpent(TransactionInput input); void markAsUnspent(); boolean isAvailableForSpending(); byte[] getScriptBytes(); boolean isMineOrWatched(TransactionBag transactionBag); boolean isWatched(TransactionBag transactionBag); boolean isMine(TransactionBag transactionBag); @Override String toString(); @Nullable TransactionInput getSpentBy(); @Nullable Transaction getParentTransaction(); @Nullable Sha256Hash getParentTransactionHash(); int getParentTransactionDepthInBlocks(); TransactionOutPoint getOutPointFor(); TransactionOutput duplicateDetached(); @Override boolean equals(Object o); @Override int hashCode(); }
@Test public void getMinNonDustValue() throws Exception { TransactionOutput payToAddressOutput = new TransactionOutput(PARAMS, null, Coin.COIN, myAddress); assertEquals(Transaction.MIN_NONDUST_OUTPUT, payToAddressOutput.getMinNonDustValue()); }
public Coin getMinNonDustValue(Coin feePerKb) { final long size = this.unsafeBitcoinSerialize().length + 148; return feePerKb.multiply(size).divide(1000); }
TransactionOutput extends ChildMessage { public Coin getMinNonDustValue(Coin feePerKb) { final long size = this.unsafeBitcoinSerialize().length + 148; return feePerKb.multiply(size).divide(1000); } }
TransactionOutput extends ChildMessage { public Coin getMinNonDustValue(Coin feePerKb) { final long size = this.unsafeBitcoinSerialize().length + 148; return feePerKb.multiply(size).divide(1000); } TransactionOutput(NetworkParameters params, @Nullable Transaction parent, byte[] payload, int offset); TransactionOutput(NetworkParameters params, @Nullable Transaction parent, byte[] payload, int offset, MessageSerializer serializer); TransactionOutput(NetworkParameters params, @Nullable Transaction parent, Coin value, Address to); TransactionOutput(NetworkParameters params, @Nullable Transaction parent, Coin value, ECKey to); TransactionOutput(NetworkParameters params, @Nullable Transaction parent, Coin value, byte[] scriptBytes); }
TransactionOutput extends ChildMessage { public Coin getMinNonDustValue(Coin feePerKb) { final long size = this.unsafeBitcoinSerialize().length + 148; return feePerKb.multiply(size).divide(1000); } TransactionOutput(NetworkParameters params, @Nullable Transaction parent, byte[] payload, int offset); TransactionOutput(NetworkParameters params, @Nullable Transaction parent, byte[] payload, int offset, MessageSerializer serializer); TransactionOutput(NetworkParameters params, @Nullable Transaction parent, Coin value, Address to); TransactionOutput(NetworkParameters params, @Nullable Transaction parent, Coin value, ECKey to); TransactionOutput(NetworkParameters params, @Nullable Transaction parent, Coin value, byte[] scriptBytes); Script getScriptPubKey(); @Nullable Address getAddressFromP2PKHScript(NetworkParameters networkParameters); @Nullable Address getAddressFromP2SH(NetworkParameters networkParameters); Coin getValue(); void setValue(Coin value); int getIndex(); boolean isDust(); Coin getMinNonDustValue(Coin feePerKb); Coin getMinNonDustValue(); void markAsSpent(TransactionInput input); void markAsUnspent(); boolean isAvailableForSpending(); byte[] getScriptBytes(); boolean isMineOrWatched(TransactionBag transactionBag); boolean isWatched(TransactionBag transactionBag); boolean isMine(TransactionBag transactionBag); @Override String toString(); @Nullable TransactionInput getSpentBy(); @Nullable Transaction getParentTransaction(); @Nullable Sha256Hash getParentTransactionHash(); int getParentTransactionDepthInBlocks(); TransactionOutPoint getOutPointFor(); TransactionOutput duplicateDetached(); @Override boolean equals(Object o); @Override int hashCode(); }
TransactionOutput extends ChildMessage { public Coin getMinNonDustValue(Coin feePerKb) { final long size = this.unsafeBitcoinSerialize().length + 148; return feePerKb.multiply(size).divide(1000); } TransactionOutput(NetworkParameters params, @Nullable Transaction parent, byte[] payload, int offset); TransactionOutput(NetworkParameters params, @Nullable Transaction parent, byte[] payload, int offset, MessageSerializer serializer); TransactionOutput(NetworkParameters params, @Nullable Transaction parent, Coin value, Address to); TransactionOutput(NetworkParameters params, @Nullable Transaction parent, Coin value, ECKey to); TransactionOutput(NetworkParameters params, @Nullable Transaction parent, Coin value, byte[] scriptBytes); Script getScriptPubKey(); @Nullable Address getAddressFromP2PKHScript(NetworkParameters networkParameters); @Nullable Address getAddressFromP2SH(NetworkParameters networkParameters); Coin getValue(); void setValue(Coin value); int getIndex(); boolean isDust(); Coin getMinNonDustValue(Coin feePerKb); Coin getMinNonDustValue(); void markAsSpent(TransactionInput input); void markAsUnspent(); boolean isAvailableForSpending(); byte[] getScriptBytes(); boolean isMineOrWatched(TransactionBag transactionBag); boolean isWatched(TransactionBag transactionBag); boolean isMine(TransactionBag transactionBag); @Override String toString(); @Nullable TransactionInput getSpentBy(); @Nullable Transaction getParentTransaction(); @Nullable Sha256Hash getParentTransactionHash(); int getParentTransactionDepthInBlocks(); TransactionOutPoint getOutPointFor(); TransactionOutput duplicateDetached(); @Override boolean equals(Object o); @Override int hashCode(); }
@Test public void stringification() throws Exception { Address a = new Address(testParams, HEX.decode("fda79a24e50ff70ff42f7d89585da5bd19d9e5cc")); assertEquals("n4eA2nbYqErp7H6jebchxAN59DmNpksexv", a.toString()); assertFalse(a.isP2SHAddress()); Address b = new Address(mainParams, HEX.decode("4a22c3c4cbb31e4d03b15550636762bda0baf85a")); assertEquals("17kzeh4N8g49GFvdDzSf8PjaPfyoD1MndL", b.toString()); assertFalse(b.isP2SHAddress()); }
public boolean isP2SHAddress() { final NetworkParameters parameters = getParameters(); return parameters != null && this.version == parameters.p2shHeader; }
Address extends VersionedChecksummedBytes { public boolean isP2SHAddress() { final NetworkParameters parameters = getParameters(); return parameters != null && this.version == parameters.p2shHeader; } }
Address extends VersionedChecksummedBytes { public boolean isP2SHAddress() { final NetworkParameters parameters = getParameters(); return parameters != null && this.version == parameters.p2shHeader; } Address(NetworkParameters params, int version, byte[] hash160); Address(NetworkParameters params, byte[] hash160); @Deprecated Address(@Nullable NetworkParameters params, String address); }
Address extends VersionedChecksummedBytes { public boolean isP2SHAddress() { final NetworkParameters parameters = getParameters(); return parameters != null && this.version == parameters.p2shHeader; } Address(NetworkParameters params, int version, byte[] hash160); Address(NetworkParameters params, byte[] hash160); @Deprecated Address(@Nullable NetworkParameters params, String address); static Address fromP2SHHash(NetworkParameters params, byte[] hash160); static Address fromP2SHScript(NetworkParameters params, Script scriptPubKey); static Address fromBase58(@Nullable NetworkParameters params, String base58); byte[] getHash160(); boolean isP2SHAddress(); NetworkParameters getParameters(); static NetworkParameters getParametersFromAddress(String address); @Override Address clone(); }
Address extends VersionedChecksummedBytes { public boolean isP2SHAddress() { final NetworkParameters parameters = getParameters(); return parameters != null && this.version == parameters.p2shHeader; } Address(NetworkParameters params, int version, byte[] hash160); Address(NetworkParameters params, byte[] hash160); @Deprecated Address(@Nullable NetworkParameters params, String address); static Address fromP2SHHash(NetworkParameters params, byte[] hash160); static Address fromP2SHScript(NetworkParameters params, Script scriptPubKey); static Address fromBase58(@Nullable NetworkParameters params, String base58); byte[] getHash160(); boolean isP2SHAddress(); NetworkParameters getParameters(); static NetworkParameters getParametersFromAddress(String address); @Override Address clone(); static final int LENGTH; }
@Test public void errorPaths() { try { Address.fromBase58(testParams, "this is not a valid address!"); fail(); } catch (WrongNetworkException e) { fail(); } catch (AddressFormatException e) { } try { Address.fromBase58(testParams, ""); fail(); } catch (WrongNetworkException e) { fail(); } catch (AddressFormatException e) { } try { Address.fromBase58(testParams, "17kzeh4N8g49GFvdDzSf8PjaPfyoD1MndL"); fail(); } catch (WrongNetworkException e) { assertEquals(e.verCode, MainNetParams.get().getAddressHeader()); assertTrue(Arrays.equals(e.acceptableVersions, TestNet3Params.get().getAcceptableAddressCodes())); } catch (AddressFormatException e) { fail(); } }
public static Address fromBase58(@Nullable NetworkParameters params, String base58) throws AddressFormatException { return new Address(params, base58); }
Address extends VersionedChecksummedBytes { public static Address fromBase58(@Nullable NetworkParameters params, String base58) throws AddressFormatException { return new Address(params, base58); } }
Address extends VersionedChecksummedBytes { public static Address fromBase58(@Nullable NetworkParameters params, String base58) throws AddressFormatException { return new Address(params, base58); } Address(NetworkParameters params, int version, byte[] hash160); Address(NetworkParameters params, byte[] hash160); @Deprecated Address(@Nullable NetworkParameters params, String address); }
Address extends VersionedChecksummedBytes { public static Address fromBase58(@Nullable NetworkParameters params, String base58) throws AddressFormatException { return new Address(params, base58); } Address(NetworkParameters params, int version, byte[] hash160); Address(NetworkParameters params, byte[] hash160); @Deprecated Address(@Nullable NetworkParameters params, String address); static Address fromP2SHHash(NetworkParameters params, byte[] hash160); static Address fromP2SHScript(NetworkParameters params, Script scriptPubKey); static Address fromBase58(@Nullable NetworkParameters params, String base58); byte[] getHash160(); boolean isP2SHAddress(); NetworkParameters getParameters(); static NetworkParameters getParametersFromAddress(String address); @Override Address clone(); }
Address extends VersionedChecksummedBytes { public static Address fromBase58(@Nullable NetworkParameters params, String base58) throws AddressFormatException { return new Address(params, base58); } Address(NetworkParameters params, int version, byte[] hash160); Address(NetworkParameters params, byte[] hash160); @Deprecated Address(@Nullable NetworkParameters params, String address); static Address fromP2SHHash(NetworkParameters params, byte[] hash160); static Address fromP2SHScript(NetworkParameters params, Script scriptPubKey); static Address fromBase58(@Nullable NetworkParameters params, String base58); byte[] getHash160(); boolean isP2SHAddress(); NetworkParameters getParameters(); static NetworkParameters getParametersFromAddress(String address); @Override Address clone(); static final int LENGTH; }
@Test public void getNetwork() throws Exception { NetworkParameters params = Address.getParametersFromAddress("17kzeh4N8g49GFvdDzSf8PjaPfyoD1MndL"); assertEquals(MainNetParams.get().getId(), params.getId()); params = Address.getParametersFromAddress("n4eA2nbYqErp7H6jebchxAN59DmNpksexv"); assertEquals(TestNet3Params.get().getId(), params.getId()); }
public static NetworkParameters getParametersFromAddress(String address) throws AddressFormatException { try { return Address.fromBase58(null, address).getParameters(); } catch (WrongNetworkException e) { throw new RuntimeException(e); } }
Address extends VersionedChecksummedBytes { public static NetworkParameters getParametersFromAddress(String address) throws AddressFormatException { try { return Address.fromBase58(null, address).getParameters(); } catch (WrongNetworkException e) { throw new RuntimeException(e); } } }
Address extends VersionedChecksummedBytes { public static NetworkParameters getParametersFromAddress(String address) throws AddressFormatException { try { return Address.fromBase58(null, address).getParameters(); } catch (WrongNetworkException e) { throw new RuntimeException(e); } } Address(NetworkParameters params, int version, byte[] hash160); Address(NetworkParameters params, byte[] hash160); @Deprecated Address(@Nullable NetworkParameters params, String address); }
Address extends VersionedChecksummedBytes { public static NetworkParameters getParametersFromAddress(String address) throws AddressFormatException { try { return Address.fromBase58(null, address).getParameters(); } catch (WrongNetworkException e) { throw new RuntimeException(e); } } Address(NetworkParameters params, int version, byte[] hash160); Address(NetworkParameters params, byte[] hash160); @Deprecated Address(@Nullable NetworkParameters params, String address); static Address fromP2SHHash(NetworkParameters params, byte[] hash160); static Address fromP2SHScript(NetworkParameters params, Script scriptPubKey); static Address fromBase58(@Nullable NetworkParameters params, String base58); byte[] getHash160(); boolean isP2SHAddress(); NetworkParameters getParameters(); static NetworkParameters getParametersFromAddress(String address); @Override Address clone(); }
Address extends VersionedChecksummedBytes { public static NetworkParameters getParametersFromAddress(String address) throws AddressFormatException { try { return Address.fromBase58(null, address).getParameters(); } catch (WrongNetworkException e) { throw new RuntimeException(e); } } Address(NetworkParameters params, int version, byte[] hash160); Address(NetworkParameters params, byte[] hash160); @Deprecated Address(@Nullable NetworkParameters params, String address); static Address fromP2SHHash(NetworkParameters params, byte[] hash160); static Address fromP2SHScript(NetworkParameters params, Script scriptPubKey); static Address fromBase58(@Nullable NetworkParameters params, String base58); byte[] getHash160(); boolean isP2SHAddress(); NetworkParameters getParameters(); static NetworkParameters getParametersFromAddress(String address); @Override Address clone(); static final int LENGTH; }
@Test public void getAltNetwork() throws Exception { class AltNetwork extends MainNetParams { AltNetwork() { super(); id = "alt.network"; addressHeader = 48; p2shHeader = 5; acceptableAddressCodes = new int[] { addressHeader, p2shHeader }; } } AltNetwork altNetwork = new AltNetwork(); Networks.register(altNetwork); NetworkParameters params = Address.getParametersFromAddress("LLxSnHLN2CYyzB5eWTR9K9rS9uWtbTQFb6"); assertEquals(altNetwork.getId(), params.getId()); params = Address.getParametersFromAddress("17kzeh4N8g49GFvdDzSf8PjaPfyoD1MndL"); assertEquals(MainNetParams.get().getId(), params.getId()); Networks.unregister(altNetwork); try { Address.getParametersFromAddress("LLxSnHLN2CYyzB5eWTR9K9rS9uWtbTQFb6"); fail(); } catch (AddressFormatException e) { } }
public static NetworkParameters getParametersFromAddress(String address) throws AddressFormatException { try { return Address.fromBase58(null, address).getParameters(); } catch (WrongNetworkException e) { throw new RuntimeException(e); } }
Address extends VersionedChecksummedBytes { public static NetworkParameters getParametersFromAddress(String address) throws AddressFormatException { try { return Address.fromBase58(null, address).getParameters(); } catch (WrongNetworkException e) { throw new RuntimeException(e); } } }
Address extends VersionedChecksummedBytes { public static NetworkParameters getParametersFromAddress(String address) throws AddressFormatException { try { return Address.fromBase58(null, address).getParameters(); } catch (WrongNetworkException e) { throw new RuntimeException(e); } } Address(NetworkParameters params, int version, byte[] hash160); Address(NetworkParameters params, byte[] hash160); @Deprecated Address(@Nullable NetworkParameters params, String address); }
Address extends VersionedChecksummedBytes { public static NetworkParameters getParametersFromAddress(String address) throws AddressFormatException { try { return Address.fromBase58(null, address).getParameters(); } catch (WrongNetworkException e) { throw new RuntimeException(e); } } Address(NetworkParameters params, int version, byte[] hash160); Address(NetworkParameters params, byte[] hash160); @Deprecated Address(@Nullable NetworkParameters params, String address); static Address fromP2SHHash(NetworkParameters params, byte[] hash160); static Address fromP2SHScript(NetworkParameters params, Script scriptPubKey); static Address fromBase58(@Nullable NetworkParameters params, String base58); byte[] getHash160(); boolean isP2SHAddress(); NetworkParameters getParameters(); static NetworkParameters getParametersFromAddress(String address); @Override Address clone(); }
Address extends VersionedChecksummedBytes { public static NetworkParameters getParametersFromAddress(String address) throws AddressFormatException { try { return Address.fromBase58(null, address).getParameters(); } catch (WrongNetworkException e) { throw new RuntimeException(e); } } Address(NetworkParameters params, int version, byte[] hash160); Address(NetworkParameters params, byte[] hash160); @Deprecated Address(@Nullable NetworkParameters params, String address); static Address fromP2SHHash(NetworkParameters params, byte[] hash160); static Address fromP2SHScript(NetworkParameters params, Script scriptPubKey); static Address fromBase58(@Nullable NetworkParameters params, String base58); byte[] getHash160(); boolean isP2SHAddress(); NetworkParameters getParameters(); static NetworkParameters getParametersFromAddress(String address); @Override Address clone(); static final int LENGTH; }
@Test public void cloning() throws Exception { Address a = new Address(testParams, HEX.decode("fda79a24e50ff70ff42f7d89585da5bd19d9e5cc")); Address b = a.clone(); assertEquals(a, b); assertNotSame(a, b); }
@Override public Address clone() throws CloneNotSupportedException { return (Address) super.clone(); }
Address extends VersionedChecksummedBytes { @Override public Address clone() throws CloneNotSupportedException { return (Address) super.clone(); } }
Address extends VersionedChecksummedBytes { @Override public Address clone() throws CloneNotSupportedException { return (Address) super.clone(); } Address(NetworkParameters params, int version, byte[] hash160); Address(NetworkParameters params, byte[] hash160); @Deprecated Address(@Nullable NetworkParameters params, String address); }
Address extends VersionedChecksummedBytes { @Override public Address clone() throws CloneNotSupportedException { return (Address) super.clone(); } Address(NetworkParameters params, int version, byte[] hash160); Address(NetworkParameters params, byte[] hash160); @Deprecated Address(@Nullable NetworkParameters params, String address); static Address fromP2SHHash(NetworkParameters params, byte[] hash160); static Address fromP2SHScript(NetworkParameters params, Script scriptPubKey); static Address fromBase58(@Nullable NetworkParameters params, String base58); byte[] getHash160(); boolean isP2SHAddress(); NetworkParameters getParameters(); static NetworkParameters getParametersFromAddress(String address); @Override Address clone(); }
Address extends VersionedChecksummedBytes { @Override public Address clone() throws CloneNotSupportedException { return (Address) super.clone(); } Address(NetworkParameters params, int version, byte[] hash160); Address(NetworkParameters params, byte[] hash160); @Deprecated Address(@Nullable NetworkParameters params, String address); static Address fromP2SHHash(NetworkParameters params, byte[] hash160); static Address fromP2SHScript(NetworkParameters params, Script scriptPubKey); static Address fromBase58(@Nullable NetworkParameters params, String base58); byte[] getHash160(); boolean isP2SHAddress(); NetworkParameters getParameters(); static NetworkParameters getParametersFromAddress(String address); @Override Address clone(); static final int LENGTH; }
@Test public void roundtripBase58() throws Exception { String base58 = "17kzeh4N8g49GFvdDzSf8PjaPfyoD1MndL"; assertEquals(base58, Address.fromBase58(null, base58).toBase58()); }
public static Address fromBase58(@Nullable NetworkParameters params, String base58) throws AddressFormatException { return new Address(params, base58); }
Address extends VersionedChecksummedBytes { public static Address fromBase58(@Nullable NetworkParameters params, String base58) throws AddressFormatException { return new Address(params, base58); } }
Address extends VersionedChecksummedBytes { public static Address fromBase58(@Nullable NetworkParameters params, String base58) throws AddressFormatException { return new Address(params, base58); } Address(NetworkParameters params, int version, byte[] hash160); Address(NetworkParameters params, byte[] hash160); @Deprecated Address(@Nullable NetworkParameters params, String address); }
Address extends VersionedChecksummedBytes { public static Address fromBase58(@Nullable NetworkParameters params, String base58) throws AddressFormatException { return new Address(params, base58); } Address(NetworkParameters params, int version, byte[] hash160); Address(NetworkParameters params, byte[] hash160); @Deprecated Address(@Nullable NetworkParameters params, String address); static Address fromP2SHHash(NetworkParameters params, byte[] hash160); static Address fromP2SHScript(NetworkParameters params, Script scriptPubKey); static Address fromBase58(@Nullable NetworkParameters params, String base58); byte[] getHash160(); boolean isP2SHAddress(); NetworkParameters getParameters(); static NetworkParameters getParametersFromAddress(String address); @Override Address clone(); }
Address extends VersionedChecksummedBytes { public static Address fromBase58(@Nullable NetworkParameters params, String base58) throws AddressFormatException { return new Address(params, base58); } Address(NetworkParameters params, int version, byte[] hash160); Address(NetworkParameters params, byte[] hash160); @Deprecated Address(@Nullable NetworkParameters params, String address); static Address fromP2SHHash(NetworkParameters params, byte[] hash160); static Address fromP2SHScript(NetworkParameters params, Script scriptPubKey); static Address fromBase58(@Nullable NetworkParameters params, String base58); byte[] getHash160(); boolean isP2SHAddress(); NetworkParameters getParameters(); static NetworkParameters getParametersFromAddress(String address); @Override Address clone(); static final int LENGTH; }
@Test public void comparisonLessThan() throws Exception { Address a = Address.fromBase58(mainParams, "1Dorian4RoXcnBv9hnQ4Y2C1an6NJ4UrjX"); Address b = Address.fromBase58(mainParams, "1EXoDusjGwvnjZUyKkxZ4UHEf77z6A5S4P"); int result = a.compareTo(b); assertTrue(result < 0); }
public static Address fromBase58(@Nullable NetworkParameters params, String base58) throws AddressFormatException { return new Address(params, base58); }
Address extends VersionedChecksummedBytes { public static Address fromBase58(@Nullable NetworkParameters params, String base58) throws AddressFormatException { return new Address(params, base58); } }
Address extends VersionedChecksummedBytes { public static Address fromBase58(@Nullable NetworkParameters params, String base58) throws AddressFormatException { return new Address(params, base58); } Address(NetworkParameters params, int version, byte[] hash160); Address(NetworkParameters params, byte[] hash160); @Deprecated Address(@Nullable NetworkParameters params, String address); }
Address extends VersionedChecksummedBytes { public static Address fromBase58(@Nullable NetworkParameters params, String base58) throws AddressFormatException { return new Address(params, base58); } Address(NetworkParameters params, int version, byte[] hash160); Address(NetworkParameters params, byte[] hash160); @Deprecated Address(@Nullable NetworkParameters params, String address); static Address fromP2SHHash(NetworkParameters params, byte[] hash160); static Address fromP2SHScript(NetworkParameters params, Script scriptPubKey); static Address fromBase58(@Nullable NetworkParameters params, String base58); byte[] getHash160(); boolean isP2SHAddress(); NetworkParameters getParameters(); static NetworkParameters getParametersFromAddress(String address); @Override Address clone(); }
Address extends VersionedChecksummedBytes { public static Address fromBase58(@Nullable NetworkParameters params, String base58) throws AddressFormatException { return new Address(params, base58); } Address(NetworkParameters params, int version, byte[] hash160); Address(NetworkParameters params, byte[] hash160); @Deprecated Address(@Nullable NetworkParameters params, String address); static Address fromP2SHHash(NetworkParameters params, byte[] hash160); static Address fromP2SHScript(NetworkParameters params, Script scriptPubKey); static Address fromBase58(@Nullable NetworkParameters params, String base58); byte[] getHash160(); boolean isP2SHAddress(); NetworkParameters getParameters(); static NetworkParameters getParametersFromAddress(String address); @Override Address clone(); static final int LENGTH; }
@Test public void comparisonGreaterThan() throws Exception { Address a = Address.fromBase58(mainParams, "1EXoDusjGwvnjZUyKkxZ4UHEf77z6A5S4P"); Address b = Address.fromBase58(mainParams, "1Dorian4RoXcnBv9hnQ4Y2C1an6NJ4UrjX"); int result = a.compareTo(b); assertTrue(result > 0); }
public static Address fromBase58(@Nullable NetworkParameters params, String base58) throws AddressFormatException { return new Address(params, base58); }
Address extends VersionedChecksummedBytes { public static Address fromBase58(@Nullable NetworkParameters params, String base58) throws AddressFormatException { return new Address(params, base58); } }
Address extends VersionedChecksummedBytes { public static Address fromBase58(@Nullable NetworkParameters params, String base58) throws AddressFormatException { return new Address(params, base58); } Address(NetworkParameters params, int version, byte[] hash160); Address(NetworkParameters params, byte[] hash160); @Deprecated Address(@Nullable NetworkParameters params, String address); }
Address extends VersionedChecksummedBytes { public static Address fromBase58(@Nullable NetworkParameters params, String base58) throws AddressFormatException { return new Address(params, base58); } Address(NetworkParameters params, int version, byte[] hash160); Address(NetworkParameters params, byte[] hash160); @Deprecated Address(@Nullable NetworkParameters params, String address); static Address fromP2SHHash(NetworkParameters params, byte[] hash160); static Address fromP2SHScript(NetworkParameters params, Script scriptPubKey); static Address fromBase58(@Nullable NetworkParameters params, String base58); byte[] getHash160(); boolean isP2SHAddress(); NetworkParameters getParameters(); static NetworkParameters getParametersFromAddress(String address); @Override Address clone(); }
Address extends VersionedChecksummedBytes { public static Address fromBase58(@Nullable NetworkParameters params, String base58) throws AddressFormatException { return new Address(params, base58); } Address(NetworkParameters params, int version, byte[] hash160); Address(NetworkParameters params, byte[] hash160); @Deprecated Address(@Nullable NetworkParameters params, String address); static Address fromP2SHHash(NetworkParameters params, byte[] hash160); static Address fromP2SHScript(NetworkParameters params, Script scriptPubKey); static Address fromBase58(@Nullable NetworkParameters params, String base58); byte[] getHash160(); boolean isP2SHAddress(); NetworkParameters getParameters(); static NetworkParameters getParametersFromAddress(String address); @Override Address clone(); static final int LENGTH; }
@Test public void comparisonBytesVsString() throws Exception { Address a = Address.fromBase58(mainParams, "1Dorian4RoXcnBv9hnQ4Y2C1an6NJ4UrjX"); Address b = Address.fromBase58(mainParams, "1EXoDusjGwvnjZUyKkxZ4UHEf77z6A5S4P"); int resultBytes = a.compareTo(b); int resultsString = a.toString().compareTo(b.toString()); assertTrue( resultBytes < 0 ); assertTrue( resultsString < 0 ); }
public static Address fromBase58(@Nullable NetworkParameters params, String base58) throws AddressFormatException { return new Address(params, base58); }
Address extends VersionedChecksummedBytes { public static Address fromBase58(@Nullable NetworkParameters params, String base58) throws AddressFormatException { return new Address(params, base58); } }
Address extends VersionedChecksummedBytes { public static Address fromBase58(@Nullable NetworkParameters params, String base58) throws AddressFormatException { return new Address(params, base58); } Address(NetworkParameters params, int version, byte[] hash160); Address(NetworkParameters params, byte[] hash160); @Deprecated Address(@Nullable NetworkParameters params, String address); }
Address extends VersionedChecksummedBytes { public static Address fromBase58(@Nullable NetworkParameters params, String base58) throws AddressFormatException { return new Address(params, base58); } Address(NetworkParameters params, int version, byte[] hash160); Address(NetworkParameters params, byte[] hash160); @Deprecated Address(@Nullable NetworkParameters params, String address); static Address fromP2SHHash(NetworkParameters params, byte[] hash160); static Address fromP2SHScript(NetworkParameters params, Script scriptPubKey); static Address fromBase58(@Nullable NetworkParameters params, String base58); byte[] getHash160(); boolean isP2SHAddress(); NetworkParameters getParameters(); static NetworkParameters getParametersFromAddress(String address); @Override Address clone(); }
Address extends VersionedChecksummedBytes { public static Address fromBase58(@Nullable NetworkParameters params, String base58) throws AddressFormatException { return new Address(params, base58); } Address(NetworkParameters params, int version, byte[] hash160); Address(NetworkParameters params, byte[] hash160); @Deprecated Address(@Nullable NetworkParameters params, String address); static Address fromP2SHHash(NetworkParameters params, byte[] hash160); static Address fromP2SHScript(NetworkParameters params, Script scriptPubKey); static Address fromBase58(@Nullable NetworkParameters params, String base58); byte[] getHash160(); boolean isP2SHAddress(); NetworkParameters getParameters(); static NetworkParameters getParametersFromAddress(String address); @Override Address clone(); static final int LENGTH; }