repo
stringlengths
1
191
file
stringlengths
23
351
code
stringlengths
0
5.32M
file_length
int64
0
5.32M
avg_line_length
float64
0
2.9k
max_line_length
int64
0
288k
extension_type
stringclasses
1 value
bitcoinj
bitcoinj-master/core/src/main/java/org/bitcoinj/wallet/package-info.java
/* * Copyright by the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * Classes that support the {@link org.bitcoinj.wallet.Wallet}, which knows how to find and save transactions relevant to * a set of keys or scripts, calculate balances, and spend money: the wallet has many features and can be extended * in various ways, please refer to the website for documentation on how to use it. */ package org.bitcoinj.wallet;
971
43.181818
121
java
bitcoinj
bitcoinj-master/core/src/main/java/org/bitcoinj/wallet/KeyChain.java
/* * Copyright 2013 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.bitcoinj.wallet; import org.bitcoinj.core.BloomFilter; import org.bitcoinj.crypto.ECKey; import org.bitcoinj.wallet.listeners.KeyChainEventListener; import java.time.Instant; import java.util.List; import java.util.concurrent.Executor; /** * <p>A KeyChain is a class that stores a collection of keys for a {@link Wallet}. Key chains * are expected to be able to look up keys given a hash (i.e. address) or pubkey bytes, and provide keys on request * for a given purpose. They can inform event listeners about new keys being added.</p> * * <p>However it is important to understand what this interface does <i>not</i> provide. It cannot encrypt or decrypt * keys, for instance you need an implementor of {@link EncryptableKeyChain}. It cannot have keys imported into it, * that you to use a method of a specific key chain instance, such as {@link BasicKeyChain}. The reason for these * restrictions is to support key chains that may be handled by external hardware or software, or which are derived * deterministically from a seed (and thus the notion of importing a key is meaningless).</p> */ public interface KeyChain { /** Returns true if the given key is in the chain. */ boolean hasKey(ECKey key); enum KeyPurpose { RECEIVE_FUNDS, CHANGE, REFUND, AUTHENTICATION } /** Obtains a number of key/s intended for the given purpose. The chain may create new key/s, derive, or re-use an old one. */ List<? extends ECKey> getKeys(KeyPurpose purpose, int numberOfKeys); /** Obtains a key intended for the given purpose. The chain may create a new key, derive one, or re-use an old one. */ ECKey getKey(KeyPurpose purpose); /** * Return a list of keys serialized to the bitcoinj protobuf format. * @return list of keys (treat as unmodifiable list) */ List<Protos.Key> serializeToProtobuf(); /** Adds a listener for events that are run when keys are added, on the user thread. */ void addEventListener(KeyChainEventListener listener); /** Adds a listener for events that are run when keys are added, on the given executor. */ void addEventListener(KeyChainEventListener listener, Executor executor); /** Removes a listener for events that are run when keys are added. */ boolean removeEventListener(KeyChainEventListener listener); /** Returns the number of keys this key chain manages. */ int numKeys(); /** * Returns the number of elements this chain wishes to insert into the Bloom filter. The size passed to * {@link #getFilter(int, double, int)} should be at least this large. */ int numBloomFilterEntries(); /** * Returns the earliest creation time of keys in this chain. * @return earliest creation times of keys in this chain, * {@link Instant#EPOCH} if at least one time is unknown, * {@link Instant#MAX} if no keys in this chain */ Instant earliestKeyCreationTime(); /** @deprecated use {@link #earliestKeyCreationTime()} */ @Deprecated default long getEarliestKeyCreationTime() { Instant earliestKeyCreationTime = earliestKeyCreationTime(); return earliestKeyCreationTime.equals(Instant.MAX) ? Long.MAX_VALUE : earliestKeyCreationTime.getEpochSecond(); } /** * <p>Gets a bloom filter that contains all of the public keys from this chain, and which will provide the given * false-positive rate if it has size elements. Keep in mind that you will get 2 elements in the bloom filter for * each key in the key chain, for the public key and the hash of the public key (address form). For this reason * size should be <i>at least</i> 2x the result of {@link #numKeys()}.</p> * * <p>This is used to generate a {@link BloomFilter} which can be {@link BloomFilter#merge(BloomFilter)}d with * another. It could also be used if you have a specific target for the filter's size.</p> * * <p>See the docs for {@link BloomFilter#BloomFilter(int, double, int)} for a brief * explanation of anonymity when using bloom filters, and for the meaning of these parameters.</p> */ BloomFilter getFilter(int size, double falsePositiveRate, int tweak); }
4,851
43.925926
130
java
bitcoinj
bitcoinj-master/core/src/main/java/org/bitcoinj/wallet/AllowUnconfirmedCoinSelector.java
/* * Copyright by the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.bitcoinj.wallet; import org.bitcoinj.core.Transaction; /** * This coin selector will select any transaction at all, regardless of where it came from or whether it was * confirmed yet. However immature coinbases will not be included (would be a protocol violation). */ public class AllowUnconfirmedCoinSelector extends DefaultCoinSelector { @Override protected boolean shouldSelect(Transaction tx) { return true; } public static CoinSelector get() { return new AllowUnconfirmedCoinSelector(); } }
1,164
32.285714
108
java
bitcoinj
bitcoinj-master/core/src/main/java/org/bitcoinj/wallet/WalletProtobufSerializer.java
/* * Copyright 2012 Google Inc. * Copyright 2014 Andreas Schildbach * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.bitcoinj.wallet; import com.google.protobuf.ByteString; import com.google.protobuf.CodedInputStream; import com.google.protobuf.CodedOutputStream; import com.google.protobuf.WireFormat; import org.bitcoinj.base.BitcoinNetwork; import org.bitcoinj.base.Coin; import org.bitcoinj.base.Network; import org.bitcoinj.core.LockTime; import org.bitcoinj.core.NetworkParameters; import org.bitcoinj.core.PeerAddress; import org.bitcoinj.base.Sha256Hash; import org.bitcoinj.core.Services; import org.bitcoinj.core.Transaction; import org.bitcoinj.core.TransactionConfidence; import org.bitcoinj.core.TransactionConfidence.ConfidenceType; import org.bitcoinj.core.TransactionInput; import org.bitcoinj.core.TransactionOutPoint; import org.bitcoinj.core.TransactionOutput; import org.bitcoinj.core.TransactionWitness; import org.bitcoinj.crypto.KeyCrypter; import org.bitcoinj.crypto.KeyCrypterScrypt; import org.bitcoinj.params.BitcoinNetworkParams; import org.bitcoinj.script.Script; import org.bitcoinj.script.ScriptException; import org.bitcoinj.utils.ExchangeRate; import org.bitcoinj.base.utils.Fiat; import org.bitcoinj.wallet.Protos.Wallet.EncryptionType; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.annotation.Nullable; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.math.BigInteger; import java.net.InetAddress; import java.net.UnknownHostException; import java.time.Instant; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Objects; import java.util.Optional; /** * Serialize and de-serialize a wallet to a byte stream containing a * <a href="https://developers.google.com/protocol-buffers/docs/overview">protocol buffer</a>. Protocol buffers are * a data interchange format developed by Google with an efficient binary representation, a type safe specification * language and compilers that generate code to work with those data structures for many languages. Protocol buffers * can have their format evolved over time: conceptually they represent data using (tag, length, value) tuples. The * format is defined by the {@code wallet.proto} file in the bitcoinj source distribution. * <p> * The most common operations are writeWallet and readWallet, which do * the obvious operations on Output/InputStreams. You can use a {@link ByteArrayInputStream} and equivalent * {@link ByteArrayOutputStream} if you'd like byte arrays instead. The protocol buffer can also be manipulated * in its object form if you'd like to modify the flattened data structure before serialization to binary. * <p> * You can extend the wallet format with additional fields specific to your application if you want, but make sure * to either put the extra data in the provided extension areas, or select tag numbers that are unlikely to be used * by anyone else. * * @author Miron Cuperman * @author Andreas Schildbach */ public class WalletProtobufSerializer { private static final Logger log = LoggerFactory.getLogger(WalletProtobufSerializer.class); /** Current version used for serializing wallets. A version higher than this is considered from the future. */ public static final int CURRENT_WALLET_VERSION = Protos.Wallet.getDefaultInstance().getVersion(); // 512 MB private static final int WALLET_SIZE_LIMIT = 512 * 1024 * 1024; // Used for de-serialization protected Map<ByteString, Transaction> txMap; private boolean requireMandatoryExtensions = true; private boolean requireAllExtensionsKnown = false; private int walletWriteBufferSize = CodedOutputStream.DEFAULT_BUFFER_SIZE; @FunctionalInterface public interface WalletFactory { Wallet create(Network network, KeyChainGroup keyChainGroup); @Deprecated default Wallet create(NetworkParameters params, KeyChainGroup keyChainGroup) { return create(params.network(), keyChainGroup); } WalletFactory DEFAULT = Wallet::new; } private final WalletFactory factory; private KeyChainFactory keyChainFactory; public WalletProtobufSerializer() { this(WalletFactory.DEFAULT); } public WalletProtobufSerializer(WalletFactory factory) { txMap = new HashMap<>(); this.factory = factory; this.keyChainFactory = new DefaultKeyChainFactory(); } public void setKeyChainFactory(KeyChainFactory keyChainFactory) { this.keyChainFactory = keyChainFactory; } /** * If this property is set to false, then unknown mandatory extensions will be ignored instead of causing load * errors. You should only use this if you know exactly what you are doing, as the extension data will NOT be * round-tripped, possibly resulting in a corrupted wallet if you save it back out again. */ public void setRequireMandatoryExtensions(boolean value) { requireMandatoryExtensions = value; } /** * If this property is set to true, the wallet will fail to load if any found extensions are unknown.. */ public void setRequireAllExtensionsKnown(boolean value) { requireAllExtensionsKnown = value; } /** * Change buffer size for writing wallet to output stream. Default is {@link com.google.protobuf.CodedOutputStream#DEFAULT_BUFFER_SIZE} * @param walletWriteBufferSize - buffer size in bytes */ public void setWalletWriteBufferSize(int walletWriteBufferSize) { this.walletWriteBufferSize = walletWriteBufferSize; } /** * Formats the given wallet (transactions and keys) to the given output stream in protocol buffer format.<p> * * Equivalent to {@code walletToProto(wallet).writeTo(output);} */ public void writeWallet(Wallet wallet, OutputStream output) throws IOException { Protos.Wallet walletProto = walletToProto(wallet); final CodedOutputStream codedOutput = CodedOutputStream.newInstance(output, this.walletWriteBufferSize); walletProto.writeTo(codedOutput); codedOutput.flush(); } /** * Returns the given wallet formatted as text. The text format is that used by protocol buffers and * it is designed more for debugging than storage. It is not well specified and wallets are largely binary data * structures anyway, consisting as they do of keys (large random numbers) and {@link Transaction}s which also * mostly contain keys and hashes. */ public String walletToText(Wallet wallet) { Protos.Wallet walletProto = walletToProto(wallet); return walletProto.toString(); } /** * Converts the given wallet to the object representation of the protocol buffers. This can be modified, or * additional data fields set, before serialization takes place. */ public Protos.Wallet walletToProto(Wallet wallet) { Protos.Wallet.Builder walletBuilder = Protos.Wallet.newBuilder(); walletBuilder.setNetworkIdentifier(wallet.network().id()); if (wallet.getDescription() != null) { walletBuilder.setDescription(wallet.getDescription()); } for (WalletTransaction wtx : wallet.getWalletTransactions()) { Protos.Transaction txProto = makeTxProto(wtx); walletBuilder.addTransaction(txProto); } walletBuilder.addAllKey(wallet.serializeKeyChainGroupToProtobufInternal()); for (Script script : wallet.getWatchedScripts()) { Protos.Script protoScript = Protos.Script.newBuilder() .setProgram(ByteString.copyFrom(script.program())) .setCreationTimestamp(script.creationTime().orElse(Instant.EPOCH).toEpochMilli()) .build(); walletBuilder.addWatchedScript(protoScript); } // Populate the lastSeenBlockHash field. Sha256Hash lastSeenBlockHash = wallet.getLastBlockSeenHash(); if (lastSeenBlockHash != null) { walletBuilder.setLastSeenBlockHash(hashToByteString(lastSeenBlockHash)); walletBuilder.setLastSeenBlockHeight(wallet.getLastBlockSeenHeight()); } wallet.lastBlockSeenTime().ifPresent( time -> walletBuilder.setLastSeenBlockTimeSecs(time.getEpochSecond())); // Populate the scrypt parameters. KeyCrypter keyCrypter = wallet.getKeyCrypter(); if (keyCrypter == null) { // The wallet is unencrypted. walletBuilder.setEncryptionType(EncryptionType.UNENCRYPTED); } else { // The wallet is encrypted. walletBuilder.setEncryptionType(keyCrypter.getUnderstoodEncryptionType()); if (keyCrypter instanceof KeyCrypterScrypt) { KeyCrypterScrypt keyCrypterScrypt = (KeyCrypterScrypt) keyCrypter; walletBuilder.setEncryptionParameters(keyCrypterScrypt.getScryptParameters()); } else { // Some other form of encryption has been specified that we do not know how to persist. throw new RuntimeException("The wallet has encryption of type '" + keyCrypter.getUnderstoodEncryptionType() + "' but this WalletProtobufSerializer does not know how to persist this."); } } Optional<Instant> keyRotationTime = wallet.keyRotationTime(); if (keyRotationTime.isPresent()) { long timeSecs = keyRotationTime.get().getEpochSecond(); walletBuilder.setKeyRotationTime(timeSecs); } populateExtensions(wallet, walletBuilder); for (Map.Entry<String, ByteString> entry : wallet.getTags().entrySet()) { Protos.Tag.Builder tag = Protos.Tag.newBuilder().setTag(entry.getKey()).setData(entry.getValue()); walletBuilder.addTags(tag); } // Populate the wallet version. walletBuilder.setVersion(wallet.getVersion()); return walletBuilder.build(); } private static void populateExtensions(Wallet wallet, Protos.Wallet.Builder walletBuilder) { for (WalletExtension extension : wallet.getExtensions().values()) { Protos.Extension.Builder proto = Protos.Extension.newBuilder(); proto.setId(extension.getWalletExtensionID()); proto.setMandatory(extension.isWalletExtensionMandatory()); proto.setData(ByteString.copyFrom(extension.serializeWalletExtension())); walletBuilder.addExtension(proto); } } private static Protos.Transaction makeTxProto(WalletTransaction wtx) { Transaction tx = wtx.getTransaction(); Protos.Transaction.Builder txBuilder = Protos.Transaction.newBuilder(); txBuilder.setPool(getProtoPool(wtx)) .setHash(hashToByteString(tx.getTxId())) .setVersion((int) tx.getVersion()); tx.updateTime().ifPresent( time -> txBuilder.setUpdatedAt(time.toEpochMilli())); LockTime locktime = tx.lockTime(); if (locktime.isSet()) { txBuilder.setLockTime((int) locktime.rawValue()); } // Handle inputs. for (TransactionInput input : tx.getInputs()) { Protos.TransactionInput.Builder inputBuilder = Protos.TransactionInput.newBuilder() .setScriptBytes(ByteString.copyFrom(input.getScriptBytes())) .setTransactionOutPointHash(hashToByteString(input.getOutpoint().hash())) .setTransactionOutPointIndex((int) input.getOutpoint().index()); if (input.hasSequence()) inputBuilder.setSequence((int) input.getSequenceNumber()); if (input.getValue() != null) inputBuilder.setValue(input.getValue().value); if (input.hasWitness()) { TransactionWitness witness = input.getWitness(); Protos.ScriptWitness.Builder witnessBuilder = Protos.ScriptWitness.newBuilder(); int pushCount = witness.getPushCount(); for (int i = 0; i < pushCount; i++) witnessBuilder.addData(ByteString.copyFrom(witness.getPush(i))); inputBuilder.setWitness(witnessBuilder); } txBuilder.addTransactionInput(inputBuilder); } // Handle outputs. for (TransactionOutput output : tx.getOutputs()) { Protos.TransactionOutput.Builder outputBuilder = Protos.TransactionOutput.newBuilder() .setScriptBytes(ByteString.copyFrom(output.getScriptBytes())) .setValue(output.getValue().value); final TransactionInput spentBy = output.getSpentBy(); if (spentBy != null) { Sha256Hash spendingHash = spentBy.getParentTransaction().getTxId(); outputBuilder.setSpentByTransactionHash(hashToByteString(spendingHash)) .setSpentByTransactionIndex(spentBy.getIndex()); } txBuilder.addTransactionOutput(outputBuilder); } // Handle which blocks tx was seen in. final Map<Sha256Hash, Integer> appearsInHashes = tx.getAppearsInHashes(); if (appearsInHashes != null) { for (Map.Entry<Sha256Hash, Integer> entry : appearsInHashes.entrySet()) { txBuilder.addBlockHash(hashToByteString(entry.getKey())); txBuilder.addBlockRelativityOffsets(entry.getValue()); } } if (tx.hasConfidence()) { TransactionConfidence confidence = tx.getConfidence(); Protos.TransactionConfidence.Builder confidenceBuilder = Protos.TransactionConfidence.newBuilder(); writeConfidence(txBuilder, confidence, confidenceBuilder); } Protos.Transaction.Purpose purpose; switch (tx.getPurpose()) { case UNKNOWN: purpose = Protos.Transaction.Purpose.UNKNOWN; break; case USER_PAYMENT: purpose = Protos.Transaction.Purpose.USER_PAYMENT; break; case KEY_ROTATION: purpose = Protos.Transaction.Purpose.KEY_ROTATION; break; case ASSURANCE_CONTRACT_CLAIM: purpose = Protos.Transaction.Purpose.ASSURANCE_CONTRACT_CLAIM; break; case ASSURANCE_CONTRACT_PLEDGE: purpose = Protos.Transaction.Purpose.ASSURANCE_CONTRACT_PLEDGE; break; case ASSURANCE_CONTRACT_STUB: purpose = Protos.Transaction.Purpose.ASSURANCE_CONTRACT_STUB; break; case RAISE_FEE: purpose = Protos.Transaction.Purpose.RAISE_FEE; break; default: throw new RuntimeException("New tx purpose serialization not implemented."); } txBuilder.setPurpose(purpose); ExchangeRate exchangeRate = tx.getExchangeRate(); if (exchangeRate != null) { Protos.ExchangeRate.Builder exchangeRateBuilder = Protos.ExchangeRate.newBuilder() .setCoinValue(exchangeRate.coin.value).setFiatValue(exchangeRate.fiat.value) .setFiatCurrencyCode(exchangeRate.fiat.currencyCode); txBuilder.setExchangeRate(exchangeRateBuilder); } if (tx.getMemo() != null) txBuilder.setMemo(tx.getMemo()); return txBuilder.build(); } private static Protos.Transaction.Pool getProtoPool(WalletTransaction wtx) { switch (wtx.getPool()) { case UNSPENT: return Protos.Transaction.Pool.UNSPENT; case SPENT: return Protos.Transaction.Pool.SPENT; case DEAD: return Protos.Transaction.Pool.DEAD; case PENDING: return Protos.Transaction.Pool.PENDING; default: throw new RuntimeException("Unreachable"); } } private static void writeConfidence(Protos.Transaction.Builder txBuilder, TransactionConfidence confidence, Protos.TransactionConfidence.Builder confidenceBuilder) { synchronized (confidence) { confidenceBuilder.setType(Protos.TransactionConfidence.Type.forNumber(confidence.getConfidenceType().getValue())); if (confidence.getConfidenceType() == ConfidenceType.BUILDING) { confidenceBuilder.setAppearedAtHeight(confidence.getAppearedAtChainHeight()); confidenceBuilder.setDepth(confidence.getDepthInBlocks()); } if (confidence.getConfidenceType() == ConfidenceType.DEAD) { // Copy in the overriding transaction, if available. // (A dead coinbase transaction has no overriding transaction). if (confidence.getOverridingTransaction() != null) { Sha256Hash overridingHash = confidence.getOverridingTransaction().getTxId(); confidenceBuilder.setOverridingTransaction(hashToByteString(overridingHash)); } } TransactionConfidence.Source source = confidence.getSource(); switch (source) { case SELF: confidenceBuilder.setSource(Protos.TransactionConfidence.Source.SOURCE_SELF); break; case NETWORK: confidenceBuilder.setSource(Protos.TransactionConfidence.Source.SOURCE_NETWORK); break; case UNKNOWN: // Fall through. default: confidenceBuilder.setSource(Protos.TransactionConfidence.Source.SOURCE_UNKNOWN); break; } } for (PeerAddress address : confidence.getBroadcastBy()) { Protos.PeerAddress proto = Protos.PeerAddress.newBuilder() .setIpAddress(ByteString.copyFrom(address.getAddr().getAddress())) .setPort(address.getPort()) .setServices(address.getServices().bits()) .build(); confidenceBuilder.addBroadcastBy(proto); } confidence.lastBroadcastTime().ifPresent( lastBroadcastTime -> confidenceBuilder.setLastBroadcastedAt(lastBroadcastTime.toEpochMilli()) ); txBuilder.setConfidence(confidenceBuilder); } public static ByteString hashToByteString(Sha256Hash hash) { return ByteString.copyFrom(hash.getBytes()); } public static Sha256Hash byteStringToHash(ByteString bs) { return Sha256Hash.wrap(bs.toByteArray()); } /** * <p>Loads wallet data from the given protocol buffer and inserts it into the given Wallet object. This is primarily * useful when you wish to pre-register extension objects. Note that if loading fails the provided Wallet object * may be in an indeterminate state and should be thrown away.</p> * * <p>A wallet can be unreadable for various reasons, such as inability to open the file, corrupt data, internally * inconsistent data, a wallet extension marked as mandatory that cannot be handled and so on. You should always * handle {@link UnreadableWalletException} and communicate failure to the user in an appropriate manner.</p> * * @throws UnreadableWalletException thrown in various error conditions (see description). */ public Wallet readWallet(InputStream input, @Nullable WalletExtension... walletExtensions) throws UnreadableWalletException { return readWallet(input, false, walletExtensions); } /** * <p>Loads wallet data from the given protocol buffer and inserts it into the given Wallet object. This is primarily * useful when you wish to pre-register extension objects. Note that if loading fails the provided Wallet object * may be in an indeterminate state and should be thrown away. Do not simply call this method again on the same * Wallet object with {@code forceReset} set {@code true}. It won't work.</p> * * <p>If {@code forceReset} is {@code true}, then no transactions are loaded from the wallet, and it is configured * to replay transactions from the blockchain (as if the wallet had been loaded and {@link Wallet#reset()} * had been called immediately thereafter). * * <p>A wallet can be unreadable for various reasons, such as inability to open the file, corrupt data, internally * inconsistent data, a wallet extension marked as mandatory that cannot be handled and so on. You should always * handle {@link UnreadableWalletException} and communicate failure to the user in an appropriate manner.</p> * * @throws UnreadableWalletException thrown in various error conditions (see description). */ public Wallet readWallet(InputStream input, boolean forceReset, @Nullable WalletExtension[] extensions) throws UnreadableWalletException { try { Protos.Wallet walletProto = parseToProto(input); final String paramsID = walletProto.getNetworkIdentifier(); Network network = BitcoinNetwork.fromIdString(paramsID).orElseThrow(() -> new UnreadableWalletException("Unknown network parameters ID " + paramsID)); return readWallet(network, extensions, walletProto, forceReset); } catch (IOException | IllegalArgumentException | IllegalStateException e) { throw new UnreadableWalletException("Could not parse input stream to protobuf", e); } } /** * <p>Loads wallet data from the given protocol buffer and inserts it into the given Wallet object. This is primarily * useful when you wish to pre-register extension objects. Note that if loading fails the provided Wallet object * may be in an indeterminate state and should be thrown away.</p> * * <p>A wallet can be unreadable for various reasons, such as inability to open the file, corrupt data, internally * inconsistent data, a wallet extension marked as mandatory that cannot be handled and so on. You should always * handle {@link UnreadableWalletException} and communicate failure to the user in an appropriate manner.</p> * * @throws UnreadableWalletException thrown in various error conditions (see description). */ public Wallet readWallet(Network network, @Nullable WalletExtension[] extensions, Protos.Wallet walletProto) throws UnreadableWalletException { return readWallet(network, extensions, walletProto, false); } /** @deprecated use {@link #readWallet(Network, WalletExtension[], Protos.Wallet)} */ @Deprecated public Wallet readWallet(NetworkParameters params, @Nullable WalletExtension[] extensions, Protos.Wallet walletProto) throws UnreadableWalletException { return readWallet(params.network(), extensions, walletProto); } /** * <p>Loads wallet data from the given protocol buffer and inserts it into the given Wallet object. This is primarily * useful when you wish to pre-register extension objects. Note that if loading fails the provided Wallet object * may be in an indeterminate state and should be thrown away. Do not simply call this method again on the same * Wallet object with {@code forceReset} set {@code true}. It won't work.</p> * * <p>If {@code forceReset} is {@code true}, then no transactions are loaded from the wallet, and it is configured * to replay transactions from the blockchain (as if the wallet had been loaded and {@link Wallet#reset()} * had been called immediately thereafter). * * <p>A wallet can be unreadable for various reasons, such as inability to open the file, corrupt data, internally * inconsistent data, a wallet extension marked as mandatory that cannot be handled and so on. You should always * handle {@link UnreadableWalletException} and communicate failure to the user in an appropriate manner.</p> * * @throws UnreadableWalletException thrown in various error conditions (see description). */ public Wallet readWallet(Network network, @Nullable WalletExtension[] extensions, Protos.Wallet walletProto, boolean forceReset) throws UnreadableWalletException { if (walletProto.getVersion() > CURRENT_WALLET_VERSION) throw new UnreadableWalletException.FutureVersion(); if (!walletProto.getNetworkIdentifier().equals(network.id())) throw new UnreadableWalletException.WrongNetwork(); // Read the scrypt parameters that specify how encryption and decryption is performed. KeyChainGroup keyChainGroup; if (walletProto.hasEncryptionParameters()) { Protos.ScryptParameters encryptionParameters = walletProto.getEncryptionParameters(); final KeyCrypterScrypt keyCrypter = new KeyCrypterScrypt(encryptionParameters); keyChainGroup = KeyChainGroup.fromProtobufEncrypted(network, walletProto.getKeyList(), keyCrypter, keyChainFactory); } else { keyChainGroup = KeyChainGroup.fromProtobufUnencrypted(network, walletProto.getKeyList(), keyChainFactory); } Wallet wallet = factory.create(network, keyChainGroup); List<Script> scripts = new ArrayList<>(); for (Protos.Script protoScript : walletProto.getWatchedScriptList()) { try { long creationTimestamp = protoScript.getCreationTimestamp(); byte[] programBytes = protoScript.getProgram().toByteArray(); Script script; if (creationTimestamp > 0) script = Script.parse(programBytes, Instant.ofEpochMilli(creationTimestamp)); else script = Script.parse(programBytes); scripts.add(script); } catch (ScriptException e) { throw new UnreadableWalletException("Unparseable script in wallet"); } } wallet.addWatchedScripts(scripts); if (walletProto.hasDescription()) { wallet.setDescription(walletProto.getDescription()); } if (forceReset) { // Should mirror Wallet.reset() wallet.setLastBlockSeenHash(null); wallet.setLastBlockSeenHeight(-1); wallet.clearLastBlockSeenTime(); } else { // Read all transactions and insert into the txMap. for (Protos.Transaction txProto : walletProto.getTransactionList()) { readTransaction(txProto); } // Update transaction outputs to point to inputs that spend them for (Protos.Transaction txProto : walletProto.getTransactionList()) { WalletTransaction wtx = connectTransactionOutputs(txProto); wallet.addWalletTransaction(wtx); } // Update the lastBlockSeenHash. if (!walletProto.hasLastSeenBlockHash()) { wallet.setLastBlockSeenHash(null); } else { wallet.setLastBlockSeenHash(byteStringToHash(walletProto.getLastSeenBlockHash())); } if (!walletProto.hasLastSeenBlockHeight()) { wallet.setLastBlockSeenHeight(-1); } else { wallet.setLastBlockSeenHeight(walletProto.getLastSeenBlockHeight()); } // Will default to zero if not present. wallet.setLastBlockSeenTime(Instant.ofEpochSecond(walletProto.getLastSeenBlockTimeSecs())); if (walletProto.hasKeyRotationTime()) { wallet.setKeyRotationTime(Instant.ofEpochSecond(walletProto.getKeyRotationTime())); } } loadExtensions(wallet, extensions != null ? extensions : new WalletExtension[0], walletProto); for (Protos.Tag tag : walletProto.getTagsList()) { wallet.setTag(tag.getTag(), tag.getData()); } if (walletProto.hasVersion()) { wallet.setVersion(walletProto.getVersion()); } // Make sure the object can be re-used to read another wallet without corruption. txMap.clear(); return wallet; } /** @deprecated use {@link #readWallet(Network, WalletExtension[], Protos.Wallet, boolean)} */ @Deprecated public Wallet readWallet(NetworkParameters params, @Nullable WalletExtension[] extensions, Protos.Wallet walletProto, boolean forceReset) throws UnreadableWalletException { return readWallet(params.network(), extensions, walletProto, forceReset); } private void loadExtensions(Wallet wallet, WalletExtension[] extensionsList, Protos.Wallet walletProto) throws UnreadableWalletException { final Map<String, WalletExtension> extensions = new HashMap<>(); for (WalletExtension e : extensionsList) extensions.put(e.getWalletExtensionID(), e); // The Wallet object, if subclassed, might have added some extensions to itself already. In that case, don't // expect them to be passed in, just fetch them here and don't re-add. extensions.putAll(wallet.getExtensions()); for (Protos.Extension extProto : walletProto.getExtensionList()) { String id = extProto.getId(); WalletExtension extension = extensions.get(id); if (extension == null) { if (extProto.getMandatory()) { if (requireMandatoryExtensions) throw new UnreadableWalletException("Unknown mandatory extension in wallet: " + id); else log.error("Unknown extension in wallet {}, ignoring", id); } else if (requireAllExtensionsKnown) { throw new UnreadableWalletException("Unknown extension in wallet: " + id); } } else { log.info("Loading wallet extension {}", id); try { wallet.deserializeExtension(extension, extProto.getData().toByteArray()); } catch (Exception e) { if (extProto.getMandatory() && requireMandatoryExtensions) { log.error("Error whilst reading mandatory extension {}, failing to read wallet", id); throw new UnreadableWalletException("Could not parse mandatory extension in wallet: " + id); } else if (requireAllExtensionsKnown) { log.error("Error whilst reading extension {}, failing to read wallet", id); throw new UnreadableWalletException("Could not parse extension in wallet: " + id); } else { log.warn("Error whilst reading extension {}, ignoring extension", id, e); } } } } } /** * Returns the loaded protocol buffer from the given byte stream. You normally want * {@link Wallet#loadFromFile(File, WalletExtension...)} instead - this method is designed for low level * work involving the wallet file format itself. */ public static Protos.Wallet parseToProto(InputStream input) throws IOException { CodedInputStream codedInput = CodedInputStream.newInstance(input); codedInput.setSizeLimit(WALLET_SIZE_LIMIT); return Protos.Wallet.parseFrom(codedInput); } private void readTransaction(Protos.Transaction txProto) throws UnreadableWalletException { Transaction tx = new Transaction(); tx.setVersion(txProto.getVersion()); if (txProto.hasUpdatedAt()) { long updatedAt = txProto.getUpdatedAt(); if (updatedAt > 0) tx.setUpdateTime(Instant.ofEpochMilli(updatedAt)); else tx.clearUpdateTime(); } for (Protos.TransactionOutput outputProto : txProto.getTransactionOutputList()) { Coin value = Coin.valueOf(outputProto.getValue()); byte[] scriptBytes = outputProto.getScriptBytes().toByteArray(); TransactionOutput output = new TransactionOutput(tx, value, scriptBytes); tx.addOutput(output); } for (Protos.TransactionInput inputProto : txProto.getTransactionInputList()) { byte[] scriptBytes = inputProto.getScriptBytes().toByteArray(); TransactionOutPoint outpoint = new TransactionOutPoint( inputProto.getTransactionOutPointIndex() & 0xFFFFFFFFL, byteStringToHash(inputProto.getTransactionOutPointHash()) ); Coin value = inputProto.hasValue() ? Coin.valueOf(inputProto.getValue()) : null; TransactionInput input = new TransactionInput(tx, scriptBytes, outpoint, value); if (inputProto.hasSequence()) input.setSequenceNumber(0xffffffffL & inputProto.getSequence()); if (inputProto.hasWitness()) { Protos.ScriptWitness witnessProto = inputProto.getWitness(); if (witnessProto.getDataCount() > 0) { List<byte[]> pushes = new ArrayList<>(witnessProto.getDataCount()); for (int j = 0; j < witnessProto.getDataCount(); j++) pushes.add(witnessProto.getData(j).toByteArray()); input.setWitness(TransactionWitness.of(pushes)); } } tx.addInput(input); } for (int i = 0; i < txProto.getBlockHashCount(); i++) { ByteString blockHash = txProto.getBlockHash(i); int relativityOffset = 0; if (txProto.getBlockRelativityOffsetsCount() > 0) relativityOffset = txProto.getBlockRelativityOffsets(i); tx.addBlockAppearance(byteStringToHash(blockHash), relativityOffset); } if (txProto.hasLockTime()) { tx.setLockTime(0xffffffffL & txProto.getLockTime()); } if (txProto.hasPurpose()) { switch (txProto.getPurpose()) { case UNKNOWN: tx.setPurpose(Transaction.Purpose.UNKNOWN); break; case USER_PAYMENT: tx.setPurpose(Transaction.Purpose.USER_PAYMENT); break; case KEY_ROTATION: tx.setPurpose(Transaction.Purpose.KEY_ROTATION); break; case ASSURANCE_CONTRACT_CLAIM: tx.setPurpose(Transaction.Purpose.ASSURANCE_CONTRACT_CLAIM); break; case ASSURANCE_CONTRACT_PLEDGE: tx.setPurpose(Transaction.Purpose.ASSURANCE_CONTRACT_PLEDGE); break; case ASSURANCE_CONTRACT_STUB: tx.setPurpose(Transaction.Purpose.ASSURANCE_CONTRACT_STUB); break; case RAISE_FEE: tx.setPurpose(Transaction.Purpose.RAISE_FEE); break; default: throw new RuntimeException("New purpose serialization not implemented"); } } else { // Old wallet: assume a user payment as that's the only reason a new tx would have been created back then. tx.setPurpose(Transaction.Purpose.USER_PAYMENT); } if (txProto.hasExchangeRate()) { Protos.ExchangeRate exchangeRateProto = txProto.getExchangeRate(); tx.setExchangeRate(new ExchangeRate(Coin.valueOf(exchangeRateProto.getCoinValue()), Fiat.valueOf( exchangeRateProto.getFiatCurrencyCode(), exchangeRateProto.getFiatValue()))); } if (txProto.hasMemo()) tx.setMemo(txProto.getMemo()); // Transaction should now be complete. Sha256Hash protoHash = byteStringToHash(txProto.getHash()); if (!tx.getTxId().equals(protoHash)) throw new UnreadableWalletException(String.format(Locale.US, "Transaction did not deserialize completely: %s vs %s", tx.getTxId(), protoHash)); if (txMap.containsKey(txProto.getHash())) throw new UnreadableWalletException("Wallet contained duplicate transaction " + byteStringToHash(txProto.getHash())); txMap.put(txProto.getHash(), tx); } private WalletTransaction connectTransactionOutputs(final org.bitcoinj.wallet.Protos.Transaction txProto) throws UnreadableWalletException { Transaction tx = txMap.get(txProto.getHash()); final WalletTransaction.Pool pool; switch (txProto.getPool()) { case DEAD: pool = WalletTransaction.Pool.DEAD; break; case PENDING: pool = WalletTransaction.Pool.PENDING; break; case SPENT: pool = WalletTransaction.Pool.SPENT; break; case UNSPENT: pool = WalletTransaction.Pool.UNSPENT; break; // Upgrade old wallets: inactive pool has been merged with the pending pool. // Remove this some time after 0.9 is old and everyone has upgraded. // There should not be any spent outputs in this tx as old wallets would not allow them to be spent // in this state. case INACTIVE: case PENDING_INACTIVE: pool = WalletTransaction.Pool.PENDING; break; default: throw new UnreadableWalletException("Unknown transaction pool: " + txProto.getPool()); } for (int i = 0 ; i < tx.getOutputs().size() ; i++) { TransactionOutput output = tx.getOutput(i); final Protos.TransactionOutput transactionOutput = txProto.getTransactionOutput(i); if (transactionOutput.hasSpentByTransactionHash()) { final ByteString spentByTransactionHash = transactionOutput.getSpentByTransactionHash(); Transaction spendingTx = txMap.get(spentByTransactionHash); if (spendingTx == null) { throw new UnreadableWalletException(String.format(Locale.US, "Could not connect %s to %s", tx.getTxId(), byteStringToHash(spentByTransactionHash))); } final int spendingIndex = transactionOutput.getSpentByTransactionIndex(); TransactionInput input = Objects.requireNonNull(spendingTx.getInput(spendingIndex)); input.connect(output); } } if (txProto.hasConfidence()) { Protos.TransactionConfidence confidenceProto = txProto.getConfidence(); TransactionConfidence confidence = tx.getConfidence(); readConfidence(tx, confidenceProto, confidence); } return new WalletTransaction(pool, tx); } private void readConfidence(final Transaction tx, final Protos.TransactionConfidence confidenceProto, final TransactionConfidence confidence) throws UnreadableWalletException { // We are lenient here because tx confidence is not an essential part of the wallet. // If the tx has an unknown type of confidence, ignore. if (!confidenceProto.hasType()) { log.warn("Unknown confidence type for tx {}", tx.getTxId()); return; } ConfidenceType confidenceType; switch (confidenceProto.getType()) { case BUILDING: confidenceType = ConfidenceType.BUILDING; break; case DEAD: confidenceType = ConfidenceType.DEAD; break; // These two are equivalent (must be able to read old wallets). case NOT_IN_BEST_CHAIN: confidenceType = ConfidenceType.PENDING; break; case PENDING: confidenceType = ConfidenceType.PENDING; break; case IN_CONFLICT: confidenceType = ConfidenceType.IN_CONFLICT; break; case UNKNOWN: // Fall through. default: confidenceType = ConfidenceType.UNKNOWN; break; } confidence.setConfidenceType(confidenceType); if (confidenceProto.hasAppearedAtHeight()) { if (confidence.getConfidenceType() != ConfidenceType.BUILDING) { log.warn("Have appearedAtHeight but not BUILDING for tx {}", tx.getTxId()); return; } confidence.setAppearedAtChainHeight(confidenceProto.getAppearedAtHeight()); } if (confidenceProto.hasDepth()) { if (confidence.getConfidenceType() != ConfidenceType.BUILDING) { log.warn("Have depth but not BUILDING for tx {}", tx.getTxId()); return; } confidence.setDepthInBlocks(confidenceProto.getDepth()); } if (confidenceProto.hasOverridingTransaction()) { if (confidence.getConfidenceType() != ConfidenceType.DEAD) { log.warn("Have overridingTransaction but not OVERRIDDEN for tx {}", tx.getTxId()); return; } Transaction overridingTransaction = txMap.get(confidenceProto.getOverridingTransaction()); if (overridingTransaction == null) { log.warn("Have overridingTransaction that is not in wallet for tx {}", tx.getTxId()); return; } confidence.setOverridingTransaction(overridingTransaction); } for (Protos.PeerAddress proto : confidenceProto.getBroadcastByList()) { InetAddress ip; try { ip = InetAddress.getByAddress(proto.getIpAddress().toByteArray()); } catch (UnknownHostException e) { throw new UnreadableWalletException("Peer IP address does not have the right length", e); } int port = proto.getPort(); Services services = Services.of(proto.getServices()); PeerAddress address = PeerAddress.inet(ip, port, services, Instant.EPOCH); confidence.markBroadcastBy(address); } if (confidenceProto.hasLastBroadcastedAt()) confidence.setLastBroadcastTime(Instant.ofEpochMilli(confidenceProto.getLastBroadcastedAt())); switch (confidenceProto.getSource()) { case SOURCE_SELF: confidence.setSource(TransactionConfidence.Source.SELF); break; case SOURCE_NETWORK: confidence.setSource(TransactionConfidence.Source.NETWORK); break; case SOURCE_UNKNOWN: // Fall through. default: confidence.setSource(TransactionConfidence.Source.UNKNOWN); break; } } /** * Cheap test to see if input stream is a wallet. This checks for a magic value at the beginning of the stream. * * @param is * input stream to test * @return true if input stream is a wallet */ public static boolean isWallet(InputStream is) { try { final CodedInputStream cis = CodedInputStream.newInstance(is); final int tag = cis.readTag(); final int field = WireFormat.getTagFieldNumber(tag); if (field != 1) // network_identifier return false; final String network = cis.readString(); return BitcoinNetworkParams.fromID(network) != null; } catch (IOException x) { return false; } } }
43,733
49.211251
200
java
bitcoinj
bitcoinj-master/core/src/main/java/org/bitcoinj/wallet/Protos.java
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: wallet.proto package org.bitcoinj.wallet; public final class Protos { private Protos() {} public static void registerAllExtensions( com.google.protobuf.ExtensionRegistryLite registry) { } public interface PeerAddressOrBuilder extends // @@protoc_insertion_point(interface_extends:wallet.PeerAddress) com.google.protobuf.MessageLiteOrBuilder { /** * <code>required bytes ip_address = 1;</code> * @return Whether the ipAddress field is set. */ boolean hasIpAddress(); /** * <code>required bytes ip_address = 1;</code> * @return The ipAddress. */ com.google.protobuf.ByteString getIpAddress(); /** * <code>required uint32 port = 2;</code> * @return Whether the port field is set. */ boolean hasPort(); /** * <code>required uint32 port = 2;</code> * @return The port. */ int getPort(); /** * <code>required uint64 services = 3;</code> * @return Whether the services field is set. */ boolean hasServices(); /** * <code>required uint64 services = 3;</code> * @return The services. */ long getServices(); } /** * Protobuf type {@code wallet.PeerAddress} */ public static final class PeerAddress extends com.google.protobuf.GeneratedMessageLite< PeerAddress, PeerAddress.Builder> implements // @@protoc_insertion_point(message_implements:wallet.PeerAddress) PeerAddressOrBuilder { private PeerAddress() { ipAddress_ = com.google.protobuf.ByteString.EMPTY; } private int bitField0_; public static final int IP_ADDRESS_FIELD_NUMBER = 1; private com.google.protobuf.ByteString ipAddress_; /** * <code>required bytes ip_address = 1;</code> * @return Whether the ipAddress field is set. */ @java.lang.Override public boolean hasIpAddress() { return ((bitField0_ & 0x00000001) != 0); } /** * <code>required bytes ip_address = 1;</code> * @return The ipAddress. */ @java.lang.Override public com.google.protobuf.ByteString getIpAddress() { return ipAddress_; } /** * <code>required bytes ip_address = 1;</code> * @param value The ipAddress to set. */ private void setIpAddress(com.google.protobuf.ByteString value) { java.lang.Class<?> valueClass = value.getClass(); bitField0_ |= 0x00000001; ipAddress_ = value; } /** * <code>required bytes ip_address = 1;</code> */ private void clearIpAddress() { bitField0_ = (bitField0_ & ~0x00000001); ipAddress_ = getDefaultInstance().getIpAddress(); } public static final int PORT_FIELD_NUMBER = 2; private int port_; /** * <code>required uint32 port = 2;</code> * @return Whether the port field is set. */ @java.lang.Override public boolean hasPort() { return ((bitField0_ & 0x00000002) != 0); } /** * <code>required uint32 port = 2;</code> * @return The port. */ @java.lang.Override public int getPort() { return port_; } /** * <code>required uint32 port = 2;</code> * @param value The port to set. */ private void setPort(int value) { bitField0_ |= 0x00000002; port_ = value; } /** * <code>required uint32 port = 2;</code> */ private void clearPort() { bitField0_ = (bitField0_ & ~0x00000002); port_ = 0; } public static final int SERVICES_FIELD_NUMBER = 3; private long services_; /** * <code>required uint64 services = 3;</code> * @return Whether the services field is set. */ @java.lang.Override public boolean hasServices() { return ((bitField0_ & 0x00000004) != 0); } /** * <code>required uint64 services = 3;</code> * @return The services. */ @java.lang.Override public long getServices() { return services_; } /** * <code>required uint64 services = 3;</code> * @param value The services to set. */ private void setServices(long value) { bitField0_ |= 0x00000004; services_ = value; } /** * <code>required uint64 services = 3;</code> */ private void clearServices() { bitField0_ = (bitField0_ & ~0x00000004); services_ = 0L; } public static org.bitcoinj.wallet.Protos.PeerAddress parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return com.google.protobuf.GeneratedMessageLite.parseFrom( DEFAULT_INSTANCE, data); } public static org.bitcoinj.wallet.Protos.PeerAddress parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return com.google.protobuf.GeneratedMessageLite.parseFrom( DEFAULT_INSTANCE, data, extensionRegistry); } public static org.bitcoinj.wallet.Protos.PeerAddress parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return com.google.protobuf.GeneratedMessageLite.parseFrom( DEFAULT_INSTANCE, data); } public static org.bitcoinj.wallet.Protos.PeerAddress parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return com.google.protobuf.GeneratedMessageLite.parseFrom( DEFAULT_INSTANCE, data, extensionRegistry); } public static org.bitcoinj.wallet.Protos.PeerAddress parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return com.google.protobuf.GeneratedMessageLite.parseFrom( DEFAULT_INSTANCE, data); } public static org.bitcoinj.wallet.Protos.PeerAddress parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return com.google.protobuf.GeneratedMessageLite.parseFrom( DEFAULT_INSTANCE, data, extensionRegistry); } public static org.bitcoinj.wallet.Protos.PeerAddress parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageLite.parseFrom( DEFAULT_INSTANCE, input); } public static org.bitcoinj.wallet.Protos.PeerAddress parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageLite.parseFrom( DEFAULT_INSTANCE, input, extensionRegistry); } public static org.bitcoinj.wallet.Protos.PeerAddress parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return parseDelimitedFrom(DEFAULT_INSTANCE, input); } public static org.bitcoinj.wallet.Protos.PeerAddress parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return parseDelimitedFrom(DEFAULT_INSTANCE, input, extensionRegistry); } public static org.bitcoinj.wallet.Protos.PeerAddress parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageLite.parseFrom( DEFAULT_INSTANCE, input); } public static org.bitcoinj.wallet.Protos.PeerAddress parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageLite.parseFrom( DEFAULT_INSTANCE, input, extensionRegistry); } public static Builder newBuilder() { return (Builder) DEFAULT_INSTANCE.createBuilder(); } public static Builder newBuilder(org.bitcoinj.wallet.Protos.PeerAddress prototype) { return (Builder) DEFAULT_INSTANCE.createBuilder(prototype); } /** * Protobuf type {@code wallet.PeerAddress} */ public static final class Builder extends com.google.protobuf.GeneratedMessageLite.Builder< org.bitcoinj.wallet.Protos.PeerAddress, Builder> implements // @@protoc_insertion_point(builder_implements:wallet.PeerAddress) org.bitcoinj.wallet.Protos.PeerAddressOrBuilder { // Construct using org.bitcoinj.wallet.Protos.PeerAddress.newBuilder() private Builder() { super(DEFAULT_INSTANCE); } /** * <code>required bytes ip_address = 1;</code> * @return Whether the ipAddress field is set. */ @java.lang.Override public boolean hasIpAddress() { return instance.hasIpAddress(); } /** * <code>required bytes ip_address = 1;</code> * @return The ipAddress. */ @java.lang.Override public com.google.protobuf.ByteString getIpAddress() { return instance.getIpAddress(); } /** * <code>required bytes ip_address = 1;</code> * @param value The ipAddress to set. * @return This builder for chaining. */ public Builder setIpAddress(com.google.protobuf.ByteString value) { copyOnWrite(); instance.setIpAddress(value); return this; } /** * <code>required bytes ip_address = 1;</code> * @return This builder for chaining. */ public Builder clearIpAddress() { copyOnWrite(); instance.clearIpAddress(); return this; } /** * <code>required uint32 port = 2;</code> * @return Whether the port field is set. */ @java.lang.Override public boolean hasPort() { return instance.hasPort(); } /** * <code>required uint32 port = 2;</code> * @return The port. */ @java.lang.Override public int getPort() { return instance.getPort(); } /** * <code>required uint32 port = 2;</code> * @param value The port to set. * @return This builder for chaining. */ public Builder setPort(int value) { copyOnWrite(); instance.setPort(value); return this; } /** * <code>required uint32 port = 2;</code> * @return This builder for chaining. */ public Builder clearPort() { copyOnWrite(); instance.clearPort(); return this; } /** * <code>required uint64 services = 3;</code> * @return Whether the services field is set. */ @java.lang.Override public boolean hasServices() { return instance.hasServices(); } /** * <code>required uint64 services = 3;</code> * @return The services. */ @java.lang.Override public long getServices() { return instance.getServices(); } /** * <code>required uint64 services = 3;</code> * @param value The services to set. * @return This builder for chaining. */ public Builder setServices(long value) { copyOnWrite(); instance.setServices(value); return this; } /** * <code>required uint64 services = 3;</code> * @return This builder for chaining. */ public Builder clearServices() { copyOnWrite(); instance.clearServices(); return this; } // @@protoc_insertion_point(builder_scope:wallet.PeerAddress) } private byte memoizedIsInitialized = 2; @java.lang.Override @java.lang.SuppressWarnings({"unchecked", "fallthrough"}) protected final java.lang.Object dynamicMethod( com.google.protobuf.GeneratedMessageLite.MethodToInvoke method, java.lang.Object arg0, java.lang.Object arg1) { switch (method) { case NEW_MUTABLE_INSTANCE: { return new org.bitcoinj.wallet.Protos.PeerAddress(); } case NEW_BUILDER: { return new Builder(); } case BUILD_MESSAGE_INFO: { java.lang.Object[] objects = new java.lang.Object[] { "bitField0_", "ipAddress_", "port_", "services_", }; java.lang.String info = "\u0001\u0003\u0000\u0001\u0001\u0003\u0003\u0000\u0000\u0003\u0001\u150a\u0000\u0002" + "\u150b\u0001\u0003\u1503\u0002"; return newMessageInfo(DEFAULT_INSTANCE, info, objects); } // fall through case GET_DEFAULT_INSTANCE: { return DEFAULT_INSTANCE; } case GET_PARSER: { com.google.protobuf.Parser<org.bitcoinj.wallet.Protos.PeerAddress> parser = PARSER; if (parser == null) { synchronized (org.bitcoinj.wallet.Protos.PeerAddress.class) { parser = PARSER; if (parser == null) { parser = new DefaultInstanceBasedParser<org.bitcoinj.wallet.Protos.PeerAddress>( DEFAULT_INSTANCE); PARSER = parser; } } } return parser; } case GET_MEMOIZED_IS_INITIALIZED: { return memoizedIsInitialized; } case SET_MEMOIZED_IS_INITIALIZED: { memoizedIsInitialized = (byte) (arg0 == null ? 0 : 1); return null; } } throw new UnsupportedOperationException(); } // @@protoc_insertion_point(class_scope:wallet.PeerAddress) private static final org.bitcoinj.wallet.Protos.PeerAddress DEFAULT_INSTANCE; static { PeerAddress defaultInstance = new PeerAddress(); // New instances are implicitly immutable so no need to make // immutable. DEFAULT_INSTANCE = defaultInstance; com.google.protobuf.GeneratedMessageLite.registerDefaultInstance( PeerAddress.class, defaultInstance); } public static org.bitcoinj.wallet.Protos.PeerAddress getDefaultInstance() { return DEFAULT_INSTANCE; } private static volatile com.google.protobuf.Parser<PeerAddress> PARSER; public static com.google.protobuf.Parser<PeerAddress> parser() { return DEFAULT_INSTANCE.getParserForType(); } } public interface EncryptedDataOrBuilder extends // @@protoc_insertion_point(interface_extends:wallet.EncryptedData) com.google.protobuf.MessageLiteOrBuilder { /** * <pre> * The initialisation vector for the AES encryption (16 bytes) * </pre> * * <code>required bytes initialisation_vector = 1;</code> * @return Whether the initialisationVector field is set. */ boolean hasInitialisationVector(); /** * <pre> * The initialisation vector for the AES encryption (16 bytes) * </pre> * * <code>required bytes initialisation_vector = 1;</code> * @return The initialisationVector. */ com.google.protobuf.ByteString getInitialisationVector(); /** * <pre> * The encrypted private key * </pre> * * <code>required bytes encrypted_private_key = 2;</code> * @return Whether the encryptedPrivateKey field is set. */ boolean hasEncryptedPrivateKey(); /** * <pre> * The encrypted private key * </pre> * * <code>required bytes encrypted_private_key = 2;</code> * @return The encryptedPrivateKey. */ com.google.protobuf.ByteString getEncryptedPrivateKey(); } /** * Protobuf type {@code wallet.EncryptedData} */ public static final class EncryptedData extends com.google.protobuf.GeneratedMessageLite< EncryptedData, EncryptedData.Builder> implements // @@protoc_insertion_point(message_implements:wallet.EncryptedData) EncryptedDataOrBuilder { private EncryptedData() { initialisationVector_ = com.google.protobuf.ByteString.EMPTY; encryptedPrivateKey_ = com.google.protobuf.ByteString.EMPTY; } private int bitField0_; public static final int INITIALISATION_VECTOR_FIELD_NUMBER = 1; private com.google.protobuf.ByteString initialisationVector_; /** * <pre> * The initialisation vector for the AES encryption (16 bytes) * </pre> * * <code>required bytes initialisation_vector = 1;</code> * @return Whether the initialisationVector field is set. */ @java.lang.Override public boolean hasInitialisationVector() { return ((bitField0_ & 0x00000001) != 0); } /** * <pre> * The initialisation vector for the AES encryption (16 bytes) * </pre> * * <code>required bytes initialisation_vector = 1;</code> * @return The initialisationVector. */ @java.lang.Override public com.google.protobuf.ByteString getInitialisationVector() { return initialisationVector_; } /** * <pre> * The initialisation vector for the AES encryption (16 bytes) * </pre> * * <code>required bytes initialisation_vector = 1;</code> * @param value The initialisationVector to set. */ private void setInitialisationVector(com.google.protobuf.ByteString value) { java.lang.Class<?> valueClass = value.getClass(); bitField0_ |= 0x00000001; initialisationVector_ = value; } /** * <pre> * The initialisation vector for the AES encryption (16 bytes) * </pre> * * <code>required bytes initialisation_vector = 1;</code> */ private void clearInitialisationVector() { bitField0_ = (bitField0_ & ~0x00000001); initialisationVector_ = getDefaultInstance().getInitialisationVector(); } public static final int ENCRYPTED_PRIVATE_KEY_FIELD_NUMBER = 2; private com.google.protobuf.ByteString encryptedPrivateKey_; /** * <pre> * The encrypted private key * </pre> * * <code>required bytes encrypted_private_key = 2;</code> * @return Whether the encryptedPrivateKey field is set. */ @java.lang.Override public boolean hasEncryptedPrivateKey() { return ((bitField0_ & 0x00000002) != 0); } /** * <pre> * The encrypted private key * </pre> * * <code>required bytes encrypted_private_key = 2;</code> * @return The encryptedPrivateKey. */ @java.lang.Override public com.google.protobuf.ByteString getEncryptedPrivateKey() { return encryptedPrivateKey_; } /** * <pre> * The encrypted private key * </pre> * * <code>required bytes encrypted_private_key = 2;</code> * @param value The encryptedPrivateKey to set. */ private void setEncryptedPrivateKey(com.google.protobuf.ByteString value) { java.lang.Class<?> valueClass = value.getClass(); bitField0_ |= 0x00000002; encryptedPrivateKey_ = value; } /** * <pre> * The encrypted private key * </pre> * * <code>required bytes encrypted_private_key = 2;</code> */ private void clearEncryptedPrivateKey() { bitField0_ = (bitField0_ & ~0x00000002); encryptedPrivateKey_ = getDefaultInstance().getEncryptedPrivateKey(); } public static org.bitcoinj.wallet.Protos.EncryptedData parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return com.google.protobuf.GeneratedMessageLite.parseFrom( DEFAULT_INSTANCE, data); } public static org.bitcoinj.wallet.Protos.EncryptedData parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return com.google.protobuf.GeneratedMessageLite.parseFrom( DEFAULT_INSTANCE, data, extensionRegistry); } public static org.bitcoinj.wallet.Protos.EncryptedData parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return com.google.protobuf.GeneratedMessageLite.parseFrom( DEFAULT_INSTANCE, data); } public static org.bitcoinj.wallet.Protos.EncryptedData parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return com.google.protobuf.GeneratedMessageLite.parseFrom( DEFAULT_INSTANCE, data, extensionRegistry); } public static org.bitcoinj.wallet.Protos.EncryptedData parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return com.google.protobuf.GeneratedMessageLite.parseFrom( DEFAULT_INSTANCE, data); } public static org.bitcoinj.wallet.Protos.EncryptedData parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return com.google.protobuf.GeneratedMessageLite.parseFrom( DEFAULT_INSTANCE, data, extensionRegistry); } public static org.bitcoinj.wallet.Protos.EncryptedData parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageLite.parseFrom( DEFAULT_INSTANCE, input); } public static org.bitcoinj.wallet.Protos.EncryptedData parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageLite.parseFrom( DEFAULT_INSTANCE, input, extensionRegistry); } public static org.bitcoinj.wallet.Protos.EncryptedData parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return parseDelimitedFrom(DEFAULT_INSTANCE, input); } public static org.bitcoinj.wallet.Protos.EncryptedData parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return parseDelimitedFrom(DEFAULT_INSTANCE, input, extensionRegistry); } public static org.bitcoinj.wallet.Protos.EncryptedData parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageLite.parseFrom( DEFAULT_INSTANCE, input); } public static org.bitcoinj.wallet.Protos.EncryptedData parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageLite.parseFrom( DEFAULT_INSTANCE, input, extensionRegistry); } public static Builder newBuilder() { return (Builder) DEFAULT_INSTANCE.createBuilder(); } public static Builder newBuilder(org.bitcoinj.wallet.Protos.EncryptedData prototype) { return (Builder) DEFAULT_INSTANCE.createBuilder(prototype); } /** * Protobuf type {@code wallet.EncryptedData} */ public static final class Builder extends com.google.protobuf.GeneratedMessageLite.Builder< org.bitcoinj.wallet.Protos.EncryptedData, Builder> implements // @@protoc_insertion_point(builder_implements:wallet.EncryptedData) org.bitcoinj.wallet.Protos.EncryptedDataOrBuilder { // Construct using org.bitcoinj.wallet.Protos.EncryptedData.newBuilder() private Builder() { super(DEFAULT_INSTANCE); } /** * <pre> * The initialisation vector for the AES encryption (16 bytes) * </pre> * * <code>required bytes initialisation_vector = 1;</code> * @return Whether the initialisationVector field is set. */ @java.lang.Override public boolean hasInitialisationVector() { return instance.hasInitialisationVector(); } /** * <pre> * The initialisation vector for the AES encryption (16 bytes) * </pre> * * <code>required bytes initialisation_vector = 1;</code> * @return The initialisationVector. */ @java.lang.Override public com.google.protobuf.ByteString getInitialisationVector() { return instance.getInitialisationVector(); } /** * <pre> * The initialisation vector for the AES encryption (16 bytes) * </pre> * * <code>required bytes initialisation_vector = 1;</code> * @param value The initialisationVector to set. * @return This builder for chaining. */ public Builder setInitialisationVector(com.google.protobuf.ByteString value) { copyOnWrite(); instance.setInitialisationVector(value); return this; } /** * <pre> * The initialisation vector for the AES encryption (16 bytes) * </pre> * * <code>required bytes initialisation_vector = 1;</code> * @return This builder for chaining. */ public Builder clearInitialisationVector() { copyOnWrite(); instance.clearInitialisationVector(); return this; } /** * <pre> * The encrypted private key * </pre> * * <code>required bytes encrypted_private_key = 2;</code> * @return Whether the encryptedPrivateKey field is set. */ @java.lang.Override public boolean hasEncryptedPrivateKey() { return instance.hasEncryptedPrivateKey(); } /** * <pre> * The encrypted private key * </pre> * * <code>required bytes encrypted_private_key = 2;</code> * @return The encryptedPrivateKey. */ @java.lang.Override public com.google.protobuf.ByteString getEncryptedPrivateKey() { return instance.getEncryptedPrivateKey(); } /** * <pre> * The encrypted private key * </pre> * * <code>required bytes encrypted_private_key = 2;</code> * @param value The encryptedPrivateKey to set. * @return This builder for chaining. */ public Builder setEncryptedPrivateKey(com.google.protobuf.ByteString value) { copyOnWrite(); instance.setEncryptedPrivateKey(value); return this; } /** * <pre> * The encrypted private key * </pre> * * <code>required bytes encrypted_private_key = 2;</code> * @return This builder for chaining. */ public Builder clearEncryptedPrivateKey() { copyOnWrite(); instance.clearEncryptedPrivateKey(); return this; } // @@protoc_insertion_point(builder_scope:wallet.EncryptedData) } private byte memoizedIsInitialized = 2; @java.lang.Override @java.lang.SuppressWarnings({"unchecked", "fallthrough"}) protected final java.lang.Object dynamicMethod( com.google.protobuf.GeneratedMessageLite.MethodToInvoke method, java.lang.Object arg0, java.lang.Object arg1) { switch (method) { case NEW_MUTABLE_INSTANCE: { return new org.bitcoinj.wallet.Protos.EncryptedData(); } case NEW_BUILDER: { return new Builder(); } case BUILD_MESSAGE_INFO: { java.lang.Object[] objects = new java.lang.Object[] { "bitField0_", "initialisationVector_", "encryptedPrivateKey_", }; java.lang.String info = "\u0001\u0002\u0000\u0001\u0001\u0002\u0002\u0000\u0000\u0002\u0001\u150a\u0000\u0002" + "\u150a\u0001"; return newMessageInfo(DEFAULT_INSTANCE, info, objects); } // fall through case GET_DEFAULT_INSTANCE: { return DEFAULT_INSTANCE; } case GET_PARSER: { com.google.protobuf.Parser<org.bitcoinj.wallet.Protos.EncryptedData> parser = PARSER; if (parser == null) { synchronized (org.bitcoinj.wallet.Protos.EncryptedData.class) { parser = PARSER; if (parser == null) { parser = new DefaultInstanceBasedParser<org.bitcoinj.wallet.Protos.EncryptedData>( DEFAULT_INSTANCE); PARSER = parser; } } } return parser; } case GET_MEMOIZED_IS_INITIALIZED: { return memoizedIsInitialized; } case SET_MEMOIZED_IS_INITIALIZED: { memoizedIsInitialized = (byte) (arg0 == null ? 0 : 1); return null; } } throw new UnsupportedOperationException(); } // @@protoc_insertion_point(class_scope:wallet.EncryptedData) private static final org.bitcoinj.wallet.Protos.EncryptedData DEFAULT_INSTANCE; static { EncryptedData defaultInstance = new EncryptedData(); // New instances are implicitly immutable so no need to make // immutable. DEFAULT_INSTANCE = defaultInstance; com.google.protobuf.GeneratedMessageLite.registerDefaultInstance( EncryptedData.class, defaultInstance); } public static org.bitcoinj.wallet.Protos.EncryptedData getDefaultInstance() { return DEFAULT_INSTANCE; } private static volatile com.google.protobuf.Parser<EncryptedData> PARSER; public static com.google.protobuf.Parser<EncryptedData> parser() { return DEFAULT_INSTANCE.getParserForType(); } } public interface DeterministicKeyOrBuilder extends // @@protoc_insertion_point(interface_extends:wallet.DeterministicKey) com.google.protobuf.MessageLiteOrBuilder { /** * <pre> * Random data that allows us to extend a key. Without this, we can't figure out the next key in the chain and * should just treat it as a regular ORIGINAL type key. * </pre> * * <code>required bytes chain_code = 1;</code> * @return Whether the chainCode field is set. */ boolean hasChainCode(); /** * <pre> * Random data that allows us to extend a key. Without this, we can't figure out the next key in the chain and * should just treat it as a regular ORIGINAL type key. * </pre> * * <code>required bytes chain_code = 1;</code> * @return The chainCode. */ com.google.protobuf.ByteString getChainCode(); /** * <pre> * The path through the key tree. Each number is encoded in the standard form: high bit set for private derivation * and high bit unset for public derivation. * </pre> * * <code>repeated uint32 path = 2;</code> * @return A list containing the path. */ java.util.List<java.lang.Integer> getPathList(); /** * <pre> * The path through the key tree. Each number is encoded in the standard form: high bit set for private derivation * and high bit unset for public derivation. * </pre> * * <code>repeated uint32 path = 2;</code> * @return The count of path. */ int getPathCount(); /** * <pre> * The path through the key tree. Each number is encoded in the standard form: high bit set for private derivation * and high bit unset for public derivation. * </pre> * * <code>repeated uint32 path = 2;</code> * @param index The index of the element to return. * @return The path at the given index. */ int getPath(int index); /** * <pre> * How many children of this key have been issued, that is, given to the user when they requested a fresh key? * For the parents of keys being handed out, this is always less than the true number of children: the difference is * called the lookahead zone. These keys are put into Bloom filters so we can spot transactions made by clones of * this wallet - for instance when restoring from backup or if the seed was shared between devices. * * If this field is missing it means we're not issuing subkeys of this key to users. * </pre> * * <code>optional uint32 issued_subkeys = 3;</code> * @return Whether the issuedSubkeys field is set. */ boolean hasIssuedSubkeys(); /** * <pre> * How many children of this key have been issued, that is, given to the user when they requested a fresh key? * For the parents of keys being handed out, this is always less than the true number of children: the difference is * called the lookahead zone. These keys are put into Bloom filters so we can spot transactions made by clones of * this wallet - for instance when restoring from backup or if the seed was shared between devices. * * If this field is missing it means we're not issuing subkeys of this key to users. * </pre> * * <code>optional uint32 issued_subkeys = 3;</code> * @return The issuedSubkeys. */ int getIssuedSubkeys(); /** * <code>optional uint32 lookahead_size = 4;</code> * @return Whether the lookaheadSize field is set. */ boolean hasLookaheadSize(); /** * <code>optional uint32 lookahead_size = 4;</code> * @return The lookaheadSize. */ int getLookaheadSize(); /** * <pre> ** * Flag indicating that this key is a root of a following chain. This chain is following the next non-following chain. * Following/followed chains concept was used for married keychains, where the set of keys combined together to produce * a single P2SH multisignature address. It is currently unused, but this flag is preserved. * </pre> * * <code>optional bool isFollowing = 5;</code> * @return Whether the isFollowing field is set. */ boolean hasIsFollowing(); /** * <pre> ** * Flag indicating that this key is a root of a following chain. This chain is following the next non-following chain. * Following/followed chains concept was used for married keychains, where the set of keys combined together to produce * a single P2SH multisignature address. It is currently unused, but this flag is preserved. * </pre> * * <code>optional bool isFollowing = 5;</code> * @return The isFollowing. */ boolean getIsFollowing(); /** * <pre> * Number of signatures required to spend. This field was needed only for married keychains to reconstruct KeyChain * and represents the N value from N-of-M CHECKMULTISIG script. It is currently unused, but this number is preserved. * For regular single keychains it will always be 1. * </pre> * * <code>optional uint32 sigsRequiredToSpend = 6 [default = 1];</code> * @return Whether the sigsRequiredToSpend field is set. */ boolean hasSigsRequiredToSpend(); /** * <pre> * Number of signatures required to spend. This field was needed only for married keychains to reconstruct KeyChain * and represents the N value from N-of-M CHECKMULTISIG script. It is currently unused, but this number is preserved. * For regular single keychains it will always be 1. * </pre> * * <code>optional uint32 sigsRequiredToSpend = 6 [default = 1];</code> * @return The sigsRequiredToSpend. */ int getSigsRequiredToSpend(); } /** * <pre> ** * Data attached to a Key message that defines the data needed by the BIP32 deterministic key hierarchy algorithm. * </pre> * * Protobuf type {@code wallet.DeterministicKey} */ public static final class DeterministicKey extends com.google.protobuf.GeneratedMessageLite< DeterministicKey, DeterministicKey.Builder> implements // @@protoc_insertion_point(message_implements:wallet.DeterministicKey) DeterministicKeyOrBuilder { private DeterministicKey() { chainCode_ = com.google.protobuf.ByteString.EMPTY; path_ = emptyIntList(); sigsRequiredToSpend_ = 1; } private int bitField0_; public static final int CHAIN_CODE_FIELD_NUMBER = 1; private com.google.protobuf.ByteString chainCode_; /** * <pre> * Random data that allows us to extend a key. Without this, we can't figure out the next key in the chain and * should just treat it as a regular ORIGINAL type key. * </pre> * * <code>required bytes chain_code = 1;</code> * @return Whether the chainCode field is set. */ @java.lang.Override public boolean hasChainCode() { return ((bitField0_ & 0x00000001) != 0); } /** * <pre> * Random data that allows us to extend a key. Without this, we can't figure out the next key in the chain and * should just treat it as a regular ORIGINAL type key. * </pre> * * <code>required bytes chain_code = 1;</code> * @return The chainCode. */ @java.lang.Override public com.google.protobuf.ByteString getChainCode() { return chainCode_; } /** * <pre> * Random data that allows us to extend a key. Without this, we can't figure out the next key in the chain and * should just treat it as a regular ORIGINAL type key. * </pre> * * <code>required bytes chain_code = 1;</code> * @param value The chainCode to set. */ private void setChainCode(com.google.protobuf.ByteString value) { java.lang.Class<?> valueClass = value.getClass(); bitField0_ |= 0x00000001; chainCode_ = value; } /** * <pre> * Random data that allows us to extend a key. Without this, we can't figure out the next key in the chain and * should just treat it as a regular ORIGINAL type key. * </pre> * * <code>required bytes chain_code = 1;</code> */ private void clearChainCode() { bitField0_ = (bitField0_ & ~0x00000001); chainCode_ = getDefaultInstance().getChainCode(); } public static final int PATH_FIELD_NUMBER = 2; private com.google.protobuf.Internal.IntList path_; /** * <pre> * The path through the key tree. Each number is encoded in the standard form: high bit set for private derivation * and high bit unset for public derivation. * </pre> * * <code>repeated uint32 path = 2;</code> * @return A list containing the path. */ @java.lang.Override public java.util.List<java.lang.Integer> getPathList() { return path_; } /** * <pre> * The path through the key tree. Each number is encoded in the standard form: high bit set for private derivation * and high bit unset for public derivation. * </pre> * * <code>repeated uint32 path = 2;</code> * @return The count of path. */ @java.lang.Override public int getPathCount() { return path_.size(); } /** * <pre> * The path through the key tree. Each number is encoded in the standard form: high bit set for private derivation * and high bit unset for public derivation. * </pre> * * <code>repeated uint32 path = 2;</code> * @param index The index of the element to return. * @return The path at the given index. */ @java.lang.Override public int getPath(int index) { return path_.getInt(index); } private void ensurePathIsMutable() { com.google.protobuf.Internal.IntList tmp = path_; if (!tmp.isModifiable()) { path_ = com.google.protobuf.GeneratedMessageLite.mutableCopy(tmp); } } /** * <pre> * The path through the key tree. Each number is encoded in the standard form: high bit set for private derivation * and high bit unset for public derivation. * </pre> * * <code>repeated uint32 path = 2;</code> * @param index The index to set the value at. * @param value The path to set. */ private void setPath( int index, int value) { ensurePathIsMutable(); path_.setInt(index, value); } /** * <pre> * The path through the key tree. Each number is encoded in the standard form: high bit set for private derivation * and high bit unset for public derivation. * </pre> * * <code>repeated uint32 path = 2;</code> * @param value The path to add. */ private void addPath(int value) { ensurePathIsMutable(); path_.addInt(value); } /** * <pre> * The path through the key tree. Each number is encoded in the standard form: high bit set for private derivation * and high bit unset for public derivation. * </pre> * * <code>repeated uint32 path = 2;</code> * @param values The path to add. */ private void addAllPath( java.lang.Iterable<? extends java.lang.Integer> values) { ensurePathIsMutable(); com.google.protobuf.AbstractMessageLite.addAll( values, path_); } /** * <pre> * The path through the key tree. Each number is encoded in the standard form: high bit set for private derivation * and high bit unset for public derivation. * </pre> * * <code>repeated uint32 path = 2;</code> */ private void clearPath() { path_ = emptyIntList(); } public static final int ISSUED_SUBKEYS_FIELD_NUMBER = 3; private int issuedSubkeys_; /** * <pre> * How many children of this key have been issued, that is, given to the user when they requested a fresh key? * For the parents of keys being handed out, this is always less than the true number of children: the difference is * called the lookahead zone. These keys are put into Bloom filters so we can spot transactions made by clones of * this wallet - for instance when restoring from backup or if the seed was shared between devices. * * If this field is missing it means we're not issuing subkeys of this key to users. * </pre> * * <code>optional uint32 issued_subkeys = 3;</code> * @return Whether the issuedSubkeys field is set. */ @java.lang.Override public boolean hasIssuedSubkeys() { return ((bitField0_ & 0x00000002) != 0); } /** * <pre> * How many children of this key have been issued, that is, given to the user when they requested a fresh key? * For the parents of keys being handed out, this is always less than the true number of children: the difference is * called the lookahead zone. These keys are put into Bloom filters so we can spot transactions made by clones of * this wallet - for instance when restoring from backup or if the seed was shared between devices. * * If this field is missing it means we're not issuing subkeys of this key to users. * </pre> * * <code>optional uint32 issued_subkeys = 3;</code> * @return The issuedSubkeys. */ @java.lang.Override public int getIssuedSubkeys() { return issuedSubkeys_; } /** * <pre> * How many children of this key have been issued, that is, given to the user when they requested a fresh key? * For the parents of keys being handed out, this is always less than the true number of children: the difference is * called the lookahead zone. These keys are put into Bloom filters so we can spot transactions made by clones of * this wallet - for instance when restoring from backup or if the seed was shared between devices. * * If this field is missing it means we're not issuing subkeys of this key to users. * </pre> * * <code>optional uint32 issued_subkeys = 3;</code> * @param value The issuedSubkeys to set. */ private void setIssuedSubkeys(int value) { bitField0_ |= 0x00000002; issuedSubkeys_ = value; } /** * <pre> * How many children of this key have been issued, that is, given to the user when they requested a fresh key? * For the parents of keys being handed out, this is always less than the true number of children: the difference is * called the lookahead zone. These keys are put into Bloom filters so we can spot transactions made by clones of * this wallet - for instance when restoring from backup or if the seed was shared between devices. * * If this field is missing it means we're not issuing subkeys of this key to users. * </pre> * * <code>optional uint32 issued_subkeys = 3;</code> */ private void clearIssuedSubkeys() { bitField0_ = (bitField0_ & ~0x00000002); issuedSubkeys_ = 0; } public static final int LOOKAHEAD_SIZE_FIELD_NUMBER = 4; private int lookaheadSize_; /** * <code>optional uint32 lookahead_size = 4;</code> * @return Whether the lookaheadSize field is set. */ @java.lang.Override public boolean hasLookaheadSize() { return ((bitField0_ & 0x00000004) != 0); } /** * <code>optional uint32 lookahead_size = 4;</code> * @return The lookaheadSize. */ @java.lang.Override public int getLookaheadSize() { return lookaheadSize_; } /** * <code>optional uint32 lookahead_size = 4;</code> * @param value The lookaheadSize to set. */ private void setLookaheadSize(int value) { bitField0_ |= 0x00000004; lookaheadSize_ = value; } /** * <code>optional uint32 lookahead_size = 4;</code> */ private void clearLookaheadSize() { bitField0_ = (bitField0_ & ~0x00000004); lookaheadSize_ = 0; } public static final int ISFOLLOWING_FIELD_NUMBER = 5; private boolean isFollowing_; /** * <pre> ** * Flag indicating that this key is a root of a following chain. This chain is following the next non-following chain. * Following/followed chains concept was used for married keychains, where the set of keys combined together to produce * a single P2SH multisignature address. It is currently unused, but this flag is preserved. * </pre> * * <code>optional bool isFollowing = 5;</code> * @return Whether the isFollowing field is set. */ @java.lang.Override public boolean hasIsFollowing() { return ((bitField0_ & 0x00000008) != 0); } /** * <pre> ** * Flag indicating that this key is a root of a following chain. This chain is following the next non-following chain. * Following/followed chains concept was used for married keychains, where the set of keys combined together to produce * a single P2SH multisignature address. It is currently unused, but this flag is preserved. * </pre> * * <code>optional bool isFollowing = 5;</code> * @return The isFollowing. */ @java.lang.Override public boolean getIsFollowing() { return isFollowing_; } /** * <pre> ** * Flag indicating that this key is a root of a following chain. This chain is following the next non-following chain. * Following/followed chains concept was used for married keychains, where the set of keys combined together to produce * a single P2SH multisignature address. It is currently unused, but this flag is preserved. * </pre> * * <code>optional bool isFollowing = 5;</code> * @param value The isFollowing to set. */ private void setIsFollowing(boolean value) { bitField0_ |= 0x00000008; isFollowing_ = value; } /** * <pre> ** * Flag indicating that this key is a root of a following chain. This chain is following the next non-following chain. * Following/followed chains concept was used for married keychains, where the set of keys combined together to produce * a single P2SH multisignature address. It is currently unused, but this flag is preserved. * </pre> * * <code>optional bool isFollowing = 5;</code> */ private void clearIsFollowing() { bitField0_ = (bitField0_ & ~0x00000008); isFollowing_ = false; } public static final int SIGSREQUIREDTOSPEND_FIELD_NUMBER = 6; private int sigsRequiredToSpend_; /** * <pre> * Number of signatures required to spend. This field was needed only for married keychains to reconstruct KeyChain * and represents the N value from N-of-M CHECKMULTISIG script. It is currently unused, but this number is preserved. * For regular single keychains it will always be 1. * </pre> * * <code>optional uint32 sigsRequiredToSpend = 6 [default = 1];</code> * @return Whether the sigsRequiredToSpend field is set. */ @java.lang.Override public boolean hasSigsRequiredToSpend() { return ((bitField0_ & 0x00000010) != 0); } /** * <pre> * Number of signatures required to spend. This field was needed only for married keychains to reconstruct KeyChain * and represents the N value from N-of-M CHECKMULTISIG script. It is currently unused, but this number is preserved. * For regular single keychains it will always be 1. * </pre> * * <code>optional uint32 sigsRequiredToSpend = 6 [default = 1];</code> * @return The sigsRequiredToSpend. */ @java.lang.Override public int getSigsRequiredToSpend() { return sigsRequiredToSpend_; } /** * <pre> * Number of signatures required to spend. This field was needed only for married keychains to reconstruct KeyChain * and represents the N value from N-of-M CHECKMULTISIG script. It is currently unused, but this number is preserved. * For regular single keychains it will always be 1. * </pre> * * <code>optional uint32 sigsRequiredToSpend = 6 [default = 1];</code> * @param value The sigsRequiredToSpend to set. */ private void setSigsRequiredToSpend(int value) { bitField0_ |= 0x00000010; sigsRequiredToSpend_ = value; } /** * <pre> * Number of signatures required to spend. This field was needed only for married keychains to reconstruct KeyChain * and represents the N value from N-of-M CHECKMULTISIG script. It is currently unused, but this number is preserved. * For regular single keychains it will always be 1. * </pre> * * <code>optional uint32 sigsRequiredToSpend = 6 [default = 1];</code> */ private void clearSigsRequiredToSpend() { bitField0_ = (bitField0_ & ~0x00000010); sigsRequiredToSpend_ = 1; } public static org.bitcoinj.wallet.Protos.DeterministicKey parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return com.google.protobuf.GeneratedMessageLite.parseFrom( DEFAULT_INSTANCE, data); } public static org.bitcoinj.wallet.Protos.DeterministicKey parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return com.google.protobuf.GeneratedMessageLite.parseFrom( DEFAULT_INSTANCE, data, extensionRegistry); } public static org.bitcoinj.wallet.Protos.DeterministicKey parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return com.google.protobuf.GeneratedMessageLite.parseFrom( DEFAULT_INSTANCE, data); } public static org.bitcoinj.wallet.Protos.DeterministicKey parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return com.google.protobuf.GeneratedMessageLite.parseFrom( DEFAULT_INSTANCE, data, extensionRegistry); } public static org.bitcoinj.wallet.Protos.DeterministicKey parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return com.google.protobuf.GeneratedMessageLite.parseFrom( DEFAULT_INSTANCE, data); } public static org.bitcoinj.wallet.Protos.DeterministicKey parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return com.google.protobuf.GeneratedMessageLite.parseFrom( DEFAULT_INSTANCE, data, extensionRegistry); } public static org.bitcoinj.wallet.Protos.DeterministicKey parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageLite.parseFrom( DEFAULT_INSTANCE, input); } public static org.bitcoinj.wallet.Protos.DeterministicKey parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageLite.parseFrom( DEFAULT_INSTANCE, input, extensionRegistry); } public static org.bitcoinj.wallet.Protos.DeterministicKey parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return parseDelimitedFrom(DEFAULT_INSTANCE, input); } public static org.bitcoinj.wallet.Protos.DeterministicKey parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return parseDelimitedFrom(DEFAULT_INSTANCE, input, extensionRegistry); } public static org.bitcoinj.wallet.Protos.DeterministicKey parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageLite.parseFrom( DEFAULT_INSTANCE, input); } public static org.bitcoinj.wallet.Protos.DeterministicKey parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageLite.parseFrom( DEFAULT_INSTANCE, input, extensionRegistry); } public static Builder newBuilder() { return (Builder) DEFAULT_INSTANCE.createBuilder(); } public static Builder newBuilder(org.bitcoinj.wallet.Protos.DeterministicKey prototype) { return (Builder) DEFAULT_INSTANCE.createBuilder(prototype); } /** * <pre> ** * Data attached to a Key message that defines the data needed by the BIP32 deterministic key hierarchy algorithm. * </pre> * * Protobuf type {@code wallet.DeterministicKey} */ public static final class Builder extends com.google.protobuf.GeneratedMessageLite.Builder< org.bitcoinj.wallet.Protos.DeterministicKey, Builder> implements // @@protoc_insertion_point(builder_implements:wallet.DeterministicKey) org.bitcoinj.wallet.Protos.DeterministicKeyOrBuilder { // Construct using org.bitcoinj.wallet.Protos.DeterministicKey.newBuilder() private Builder() { super(DEFAULT_INSTANCE); } /** * <pre> * Random data that allows us to extend a key. Without this, we can't figure out the next key in the chain and * should just treat it as a regular ORIGINAL type key. * </pre> * * <code>required bytes chain_code = 1;</code> * @return Whether the chainCode field is set. */ @java.lang.Override public boolean hasChainCode() { return instance.hasChainCode(); } /** * <pre> * Random data that allows us to extend a key. Without this, we can't figure out the next key in the chain and * should just treat it as a regular ORIGINAL type key. * </pre> * * <code>required bytes chain_code = 1;</code> * @return The chainCode. */ @java.lang.Override public com.google.protobuf.ByteString getChainCode() { return instance.getChainCode(); } /** * <pre> * Random data that allows us to extend a key. Without this, we can't figure out the next key in the chain and * should just treat it as a regular ORIGINAL type key. * </pre> * * <code>required bytes chain_code = 1;</code> * @param value The chainCode to set. * @return This builder for chaining. */ public Builder setChainCode(com.google.protobuf.ByteString value) { copyOnWrite(); instance.setChainCode(value); return this; } /** * <pre> * Random data that allows us to extend a key. Without this, we can't figure out the next key in the chain and * should just treat it as a regular ORIGINAL type key. * </pre> * * <code>required bytes chain_code = 1;</code> * @return This builder for chaining. */ public Builder clearChainCode() { copyOnWrite(); instance.clearChainCode(); return this; } /** * <pre> * The path through the key tree. Each number is encoded in the standard form: high bit set for private derivation * and high bit unset for public derivation. * </pre> * * <code>repeated uint32 path = 2;</code> * @return A list containing the path. */ @java.lang.Override public java.util.List<java.lang.Integer> getPathList() { return java.util.Collections.unmodifiableList( instance.getPathList()); } /** * <pre> * The path through the key tree. Each number is encoded in the standard form: high bit set for private derivation * and high bit unset for public derivation. * </pre> * * <code>repeated uint32 path = 2;</code> * @return The count of path. */ @java.lang.Override public int getPathCount() { return instance.getPathCount(); } /** * <pre> * The path through the key tree. Each number is encoded in the standard form: high bit set for private derivation * and high bit unset for public derivation. * </pre> * * <code>repeated uint32 path = 2;</code> * @param index The index of the element to return. * @return The path at the given index. */ @java.lang.Override public int getPath(int index) { return instance.getPath(index); } /** * <pre> * The path through the key tree. Each number is encoded in the standard form: high bit set for private derivation * and high bit unset for public derivation. * </pre> * * <code>repeated uint32 path = 2;</code> * @param value The path to set. * @return This builder for chaining. */ public Builder setPath( int index, int value) { copyOnWrite(); instance.setPath(index, value); return this; } /** * <pre> * The path through the key tree. Each number is encoded in the standard form: high bit set for private derivation * and high bit unset for public derivation. * </pre> * * <code>repeated uint32 path = 2;</code> * @param value The path to add. * @return This builder for chaining. */ public Builder addPath(int value) { copyOnWrite(); instance.addPath(value); return this; } /** * <pre> * The path through the key tree. Each number is encoded in the standard form: high bit set for private derivation * and high bit unset for public derivation. * </pre> * * <code>repeated uint32 path = 2;</code> * @param values The path to add. * @return This builder for chaining. */ public Builder addAllPath( java.lang.Iterable<? extends java.lang.Integer> values) { copyOnWrite(); instance.addAllPath(values); return this; } /** * <pre> * The path through the key tree. Each number is encoded in the standard form: high bit set for private derivation * and high bit unset for public derivation. * </pre> * * <code>repeated uint32 path = 2;</code> * @return This builder for chaining. */ public Builder clearPath() { copyOnWrite(); instance.clearPath(); return this; } /** * <pre> * How many children of this key have been issued, that is, given to the user when they requested a fresh key? * For the parents of keys being handed out, this is always less than the true number of children: the difference is * called the lookahead zone. These keys are put into Bloom filters so we can spot transactions made by clones of * this wallet - for instance when restoring from backup or if the seed was shared between devices. * * If this field is missing it means we're not issuing subkeys of this key to users. * </pre> * * <code>optional uint32 issued_subkeys = 3;</code> * @return Whether the issuedSubkeys field is set. */ @java.lang.Override public boolean hasIssuedSubkeys() { return instance.hasIssuedSubkeys(); } /** * <pre> * How many children of this key have been issued, that is, given to the user when they requested a fresh key? * For the parents of keys being handed out, this is always less than the true number of children: the difference is * called the lookahead zone. These keys are put into Bloom filters so we can spot transactions made by clones of * this wallet - for instance when restoring from backup or if the seed was shared between devices. * * If this field is missing it means we're not issuing subkeys of this key to users. * </pre> * * <code>optional uint32 issued_subkeys = 3;</code> * @return The issuedSubkeys. */ @java.lang.Override public int getIssuedSubkeys() { return instance.getIssuedSubkeys(); } /** * <pre> * How many children of this key have been issued, that is, given to the user when they requested a fresh key? * For the parents of keys being handed out, this is always less than the true number of children: the difference is * called the lookahead zone. These keys are put into Bloom filters so we can spot transactions made by clones of * this wallet - for instance when restoring from backup or if the seed was shared between devices. * * If this field is missing it means we're not issuing subkeys of this key to users. * </pre> * * <code>optional uint32 issued_subkeys = 3;</code> * @param value The issuedSubkeys to set. * @return This builder for chaining. */ public Builder setIssuedSubkeys(int value) { copyOnWrite(); instance.setIssuedSubkeys(value); return this; } /** * <pre> * How many children of this key have been issued, that is, given to the user when they requested a fresh key? * For the parents of keys being handed out, this is always less than the true number of children: the difference is * called the lookahead zone. These keys are put into Bloom filters so we can spot transactions made by clones of * this wallet - for instance when restoring from backup or if the seed was shared between devices. * * If this field is missing it means we're not issuing subkeys of this key to users. * </pre> * * <code>optional uint32 issued_subkeys = 3;</code> * @return This builder for chaining. */ public Builder clearIssuedSubkeys() { copyOnWrite(); instance.clearIssuedSubkeys(); return this; } /** * <code>optional uint32 lookahead_size = 4;</code> * @return Whether the lookaheadSize field is set. */ @java.lang.Override public boolean hasLookaheadSize() { return instance.hasLookaheadSize(); } /** * <code>optional uint32 lookahead_size = 4;</code> * @return The lookaheadSize. */ @java.lang.Override public int getLookaheadSize() { return instance.getLookaheadSize(); } /** * <code>optional uint32 lookahead_size = 4;</code> * @param value The lookaheadSize to set. * @return This builder for chaining. */ public Builder setLookaheadSize(int value) { copyOnWrite(); instance.setLookaheadSize(value); return this; } /** * <code>optional uint32 lookahead_size = 4;</code> * @return This builder for chaining. */ public Builder clearLookaheadSize() { copyOnWrite(); instance.clearLookaheadSize(); return this; } /** * <pre> ** * Flag indicating that this key is a root of a following chain. This chain is following the next non-following chain. * Following/followed chains concept was used for married keychains, where the set of keys combined together to produce * a single P2SH multisignature address. It is currently unused, but this flag is preserved. * </pre> * * <code>optional bool isFollowing = 5;</code> * @return Whether the isFollowing field is set. */ @java.lang.Override public boolean hasIsFollowing() { return instance.hasIsFollowing(); } /** * <pre> ** * Flag indicating that this key is a root of a following chain. This chain is following the next non-following chain. * Following/followed chains concept was used for married keychains, where the set of keys combined together to produce * a single P2SH multisignature address. It is currently unused, but this flag is preserved. * </pre> * * <code>optional bool isFollowing = 5;</code> * @return The isFollowing. */ @java.lang.Override public boolean getIsFollowing() { return instance.getIsFollowing(); } /** * <pre> ** * Flag indicating that this key is a root of a following chain. This chain is following the next non-following chain. * Following/followed chains concept was used for married keychains, where the set of keys combined together to produce * a single P2SH multisignature address. It is currently unused, but this flag is preserved. * </pre> * * <code>optional bool isFollowing = 5;</code> * @param value The isFollowing to set. * @return This builder for chaining. */ public Builder setIsFollowing(boolean value) { copyOnWrite(); instance.setIsFollowing(value); return this; } /** * <pre> ** * Flag indicating that this key is a root of a following chain. This chain is following the next non-following chain. * Following/followed chains concept was used for married keychains, where the set of keys combined together to produce * a single P2SH multisignature address. It is currently unused, but this flag is preserved. * </pre> * * <code>optional bool isFollowing = 5;</code> * @return This builder for chaining. */ public Builder clearIsFollowing() { copyOnWrite(); instance.clearIsFollowing(); return this; } /** * <pre> * Number of signatures required to spend. This field was needed only for married keychains to reconstruct KeyChain * and represents the N value from N-of-M CHECKMULTISIG script. It is currently unused, but this number is preserved. * For regular single keychains it will always be 1. * </pre> * * <code>optional uint32 sigsRequiredToSpend = 6 [default = 1];</code> * @return Whether the sigsRequiredToSpend field is set. */ @java.lang.Override public boolean hasSigsRequiredToSpend() { return instance.hasSigsRequiredToSpend(); } /** * <pre> * Number of signatures required to spend. This field was needed only for married keychains to reconstruct KeyChain * and represents the N value from N-of-M CHECKMULTISIG script. It is currently unused, but this number is preserved. * For regular single keychains it will always be 1. * </pre> * * <code>optional uint32 sigsRequiredToSpend = 6 [default = 1];</code> * @return The sigsRequiredToSpend. */ @java.lang.Override public int getSigsRequiredToSpend() { return instance.getSigsRequiredToSpend(); } /** * <pre> * Number of signatures required to spend. This field was needed only for married keychains to reconstruct KeyChain * and represents the N value from N-of-M CHECKMULTISIG script. It is currently unused, but this number is preserved. * For regular single keychains it will always be 1. * </pre> * * <code>optional uint32 sigsRequiredToSpend = 6 [default = 1];</code> * @param value The sigsRequiredToSpend to set. * @return This builder for chaining. */ public Builder setSigsRequiredToSpend(int value) { copyOnWrite(); instance.setSigsRequiredToSpend(value); return this; } /** * <pre> * Number of signatures required to spend. This field was needed only for married keychains to reconstruct KeyChain * and represents the N value from N-of-M CHECKMULTISIG script. It is currently unused, but this number is preserved. * For regular single keychains it will always be 1. * </pre> * * <code>optional uint32 sigsRequiredToSpend = 6 [default = 1];</code> * @return This builder for chaining. */ public Builder clearSigsRequiredToSpend() { copyOnWrite(); instance.clearSigsRequiredToSpend(); return this; } // @@protoc_insertion_point(builder_scope:wallet.DeterministicKey) } private byte memoizedIsInitialized = 2; @java.lang.Override @java.lang.SuppressWarnings({"unchecked", "fallthrough"}) protected final java.lang.Object dynamicMethod( com.google.protobuf.GeneratedMessageLite.MethodToInvoke method, java.lang.Object arg0, java.lang.Object arg1) { switch (method) { case NEW_MUTABLE_INSTANCE: { return new org.bitcoinj.wallet.Protos.DeterministicKey(); } case NEW_BUILDER: { return new Builder(); } case BUILD_MESSAGE_INFO: { java.lang.Object[] objects = new java.lang.Object[] { "bitField0_", "chainCode_", "path_", "issuedSubkeys_", "lookaheadSize_", "isFollowing_", "sigsRequiredToSpend_", }; java.lang.String info = "\u0001\u0006\u0000\u0001\u0001\u0006\u0006\u0000\u0001\u0001\u0001\u150a\u0000\u0002" + "\u001d\u0003\u100b\u0001\u0004\u100b\u0002\u0005\u1007\u0003\u0006\u100b\u0004"; return newMessageInfo(DEFAULT_INSTANCE, info, objects); } // fall through case GET_DEFAULT_INSTANCE: { return DEFAULT_INSTANCE; } case GET_PARSER: { com.google.protobuf.Parser<org.bitcoinj.wallet.Protos.DeterministicKey> parser = PARSER; if (parser == null) { synchronized (org.bitcoinj.wallet.Protos.DeterministicKey.class) { parser = PARSER; if (parser == null) { parser = new DefaultInstanceBasedParser<org.bitcoinj.wallet.Protos.DeterministicKey>( DEFAULT_INSTANCE); PARSER = parser; } } } return parser; } case GET_MEMOIZED_IS_INITIALIZED: { return memoizedIsInitialized; } case SET_MEMOIZED_IS_INITIALIZED: { memoizedIsInitialized = (byte) (arg0 == null ? 0 : 1); return null; } } throw new UnsupportedOperationException(); } // @@protoc_insertion_point(class_scope:wallet.DeterministicKey) private static final org.bitcoinj.wallet.Protos.DeterministicKey DEFAULT_INSTANCE; static { DeterministicKey defaultInstance = new DeterministicKey(); // New instances are implicitly immutable so no need to make // immutable. DEFAULT_INSTANCE = defaultInstance; com.google.protobuf.GeneratedMessageLite.registerDefaultInstance( DeterministicKey.class, defaultInstance); } public static org.bitcoinj.wallet.Protos.DeterministicKey getDefaultInstance() { return DEFAULT_INSTANCE; } private static volatile com.google.protobuf.Parser<DeterministicKey> PARSER; public static com.google.protobuf.Parser<DeterministicKey> parser() { return DEFAULT_INSTANCE.getParserForType(); } } public interface KeyOrBuilder extends // @@protoc_insertion_point(interface_extends:wallet.Key) com.google.protobuf.MessageLiteOrBuilder { /** * <code>required .wallet.Key.Type type = 1;</code> * @return Whether the type field is set. */ boolean hasType(); /** * <code>required .wallet.Key.Type type = 1;</code> * @return The type. */ org.bitcoinj.wallet.Protos.Key.Type getType(); /** * <pre> * Either the private EC key bytes (without any ASN.1 wrapping), or the deterministic root seed. * If the secret is encrypted, or this is a "watching entry" then this is missing. * </pre> * * <code>optional bytes secret_bytes = 2;</code> * @return Whether the secretBytes field is set. */ boolean hasSecretBytes(); /** * <pre> * Either the private EC key bytes (without any ASN.1 wrapping), or the deterministic root seed. * If the secret is encrypted, or this is a "watching entry" then this is missing. * </pre> * * <code>optional bytes secret_bytes = 2;</code> * @return The secretBytes. */ com.google.protobuf.ByteString getSecretBytes(); /** * <pre> * If the secret data is encrypted, then secret_bytes is missing and this field is set. * </pre> * * <code>optional .wallet.EncryptedData encrypted_data = 6;</code> * @return Whether the encryptedData field is set. */ boolean hasEncryptedData(); /** * <pre> * If the secret data is encrypted, then secret_bytes is missing and this field is set. * </pre> * * <code>optional .wallet.EncryptedData encrypted_data = 6;</code> * @return The encryptedData. */ org.bitcoinj.wallet.Protos.EncryptedData getEncryptedData(); /** * <pre> * The public EC key derived from the private key. We allow both to be stored to avoid mobile clients having to * do lots of slow EC math on startup. For DETERMINISTIC_MNEMONIC entries this is missing. * </pre> * * <code>optional bytes public_key = 3;</code> * @return Whether the publicKey field is set. */ boolean hasPublicKey(); /** * <pre> * The public EC key derived from the private key. We allow both to be stored to avoid mobile clients having to * do lots of slow EC math on startup. For DETERMINISTIC_MNEMONIC entries this is missing. * </pre> * * <code>optional bytes public_key = 3;</code> * @return The publicKey. */ com.google.protobuf.ByteString getPublicKey(); /** * <pre> * User-provided label associated with the key. * </pre> * * <code>optional string label = 4;</code> * @return Whether the label field is set. */ boolean hasLabel(); /** * <pre> * User-provided label associated with the key. * </pre> * * <code>optional string label = 4;</code> * @return The label. */ java.lang.String getLabel(); /** * <pre> * User-provided label associated with the key. * </pre> * * <code>optional string label = 4;</code> * @return The bytes for label. */ com.google.protobuf.ByteString getLabelBytes(); /** * <pre> * Timestamp stored as millis since epoch. Useful for skipping block bodies before this point. The reason it's * optional is that keys derived from a parent don't have this data. * </pre> * * <code>optional int64 creation_timestamp = 5;</code> * @return Whether the creationTimestamp field is set. */ boolean hasCreationTimestamp(); /** * <pre> * Timestamp stored as millis since epoch. Useful for skipping block bodies before this point. The reason it's * optional is that keys derived from a parent don't have this data. * </pre> * * <code>optional int64 creation_timestamp = 5;</code> * @return The creationTimestamp. */ long getCreationTimestamp(); /** * <code>optional .wallet.DeterministicKey deterministic_key = 7;</code> * @return Whether the deterministicKey field is set. */ boolean hasDeterministicKey(); /** * <code>optional .wallet.DeterministicKey deterministic_key = 7;</code> * @return The deterministicKey. */ org.bitcoinj.wallet.Protos.DeterministicKey getDeterministicKey(); /** * <pre> * The seed for a deterministic key hierarchy. Derived from the mnemonic, * but cached here for quick startup. Only applicable to a DETERMINISTIC_MNEMONIC key entry. * </pre> * * <code>optional bytes deterministic_seed = 8;</code> * @return Whether the deterministicSeed field is set. */ boolean hasDeterministicSeed(); /** * <pre> * The seed for a deterministic key hierarchy. Derived from the mnemonic, * but cached here for quick startup. Only applicable to a DETERMINISTIC_MNEMONIC key entry. * </pre> * * <code>optional bytes deterministic_seed = 8;</code> * @return The deterministicSeed. */ com.google.protobuf.ByteString getDeterministicSeed(); /** * <pre> * Encrypted version of the seed * </pre> * * <code>optional .wallet.EncryptedData encrypted_deterministic_seed = 9;</code> * @return Whether the encryptedDeterministicSeed field is set. */ boolean hasEncryptedDeterministicSeed(); /** * <pre> * Encrypted version of the seed * </pre> * * <code>optional .wallet.EncryptedData encrypted_deterministic_seed = 9;</code> * @return The encryptedDeterministicSeed. */ org.bitcoinj.wallet.Protos.EncryptedData getEncryptedDeterministicSeed(); /** * <pre> * The path to the root. Only applicable to a DETERMINISTIC_MNEMONIC key entry. * </pre> * * <code>repeated uint32 account_path = 10 [packed = true];</code> * @return A list containing the accountPath. */ java.util.List<java.lang.Integer> getAccountPathList(); /** * <pre> * The path to the root. Only applicable to a DETERMINISTIC_MNEMONIC key entry. * </pre> * * <code>repeated uint32 account_path = 10 [packed = true];</code> * @return The count of accountPath. */ int getAccountPathCount(); /** * <pre> * The path to the root. Only applicable to a DETERMINISTIC_MNEMONIC key entry. * </pre> * * <code>repeated uint32 account_path = 10 [packed = true];</code> * @param index The index of the element to return. * @return The accountPath at the given index. */ int getAccountPath(int index); /** * <pre> * Type of addresses (aka output scripts) to generate for receiving. * </pre> * * <code>optional .wallet.Key.OutputScriptType output_script_type = 11;</code> * @return Whether the outputScriptType field is set. */ boolean hasOutputScriptType(); /** * <pre> * Type of addresses (aka output scripts) to generate for receiving. * </pre> * * <code>optional .wallet.Key.OutputScriptType output_script_type = 11;</code> * @return The outputScriptType. */ org.bitcoinj.wallet.Protos.Key.OutputScriptType getOutputScriptType(); } /** * <pre> ** * A key used to control Bitcoin spending. * * Either the private key, the public key or both may be present. It is recommended that * if the private key is provided that the public key is provided too because deriving it is slow. * * If only the public key is provided, the key can only be used to watch the blockchain and verify * transactions, and not for spending. * </pre> * * Protobuf type {@code wallet.Key} */ public static final class Key extends com.google.protobuf.GeneratedMessageLite< Key, Key.Builder> implements // @@protoc_insertion_point(message_implements:wallet.Key) KeyOrBuilder { private Key() { type_ = 1; secretBytes_ = com.google.protobuf.ByteString.EMPTY; publicKey_ = com.google.protobuf.ByteString.EMPTY; label_ = ""; deterministicSeed_ = com.google.protobuf.ByteString.EMPTY; accountPath_ = emptyIntList(); outputScriptType_ = 1; } /** * Protobuf enum {@code wallet.Key.Type} */ public enum Type implements com.google.protobuf.Internal.EnumLite { /** * <pre> ** Unencrypted - Original bitcoin secp256k1 curve * </pre> * * <code>ORIGINAL = 1;</code> */ ORIGINAL(1), /** * <pre> ** Encrypted with Scrypt and AES - Original bitcoin secp256k1 curve * </pre> * * <code>ENCRYPTED_SCRYPT_AES = 2;</code> */ ENCRYPTED_SCRYPT_AES(2), /** * <pre> ** * Not really a key, but rather contains the mnemonic phrase for a deterministic key hierarchy in the private_key field. * The label and public_key fields are missing. Creation timestamp will exist. * </pre> * * <code>DETERMINISTIC_MNEMONIC = 3;</code> */ DETERMINISTIC_MNEMONIC(3), /** * <pre> ** * A key that was derived deterministically. Note that the root seed that created it may NOT be present in the * wallet, for the case of watching wallets. A deterministic key may or may not have the private key bytes present. * However the public key bytes and the deterministic_key field are guaranteed to exist. In a wallet where there * is a path from this key up to a key that has (possibly encrypted) private bytes, it's expected that the private * key can be rederived on the fly. * </pre> * * <code>DETERMINISTIC_KEY = 4;</code> */ DETERMINISTIC_KEY(4), ; /** * <pre> ** Unencrypted - Original bitcoin secp256k1 curve * </pre> * * <code>ORIGINAL = 1;</code> */ public static final int ORIGINAL_VALUE = 1; /** * <pre> ** Encrypted with Scrypt and AES - Original bitcoin secp256k1 curve * </pre> * * <code>ENCRYPTED_SCRYPT_AES = 2;</code> */ public static final int ENCRYPTED_SCRYPT_AES_VALUE = 2; /** * <pre> ** * Not really a key, but rather contains the mnemonic phrase for a deterministic key hierarchy in the private_key field. * The label and public_key fields are missing. Creation timestamp will exist. * </pre> * * <code>DETERMINISTIC_MNEMONIC = 3;</code> */ public static final int DETERMINISTIC_MNEMONIC_VALUE = 3; /** * <pre> ** * A key that was derived deterministically. Note that the root seed that created it may NOT be present in the * wallet, for the case of watching wallets. A deterministic key may or may not have the private key bytes present. * However the public key bytes and the deterministic_key field are guaranteed to exist. In a wallet where there * is a path from this key up to a key that has (possibly encrypted) private bytes, it's expected that the private * key can be rederived on the fly. * </pre> * * <code>DETERMINISTIC_KEY = 4;</code> */ public static final int DETERMINISTIC_KEY_VALUE = 4; @java.lang.Override public final int getNumber() { return value; } /** * @param value The number of the enum to look for. * @return The enum associated with the given number. * @deprecated Use {@link #forNumber(int)} instead. */ @java.lang.Deprecated public static Type valueOf(int value) { return forNumber(value); } public static Type forNumber(int value) { switch (value) { case 1: return ORIGINAL; case 2: return ENCRYPTED_SCRYPT_AES; case 3: return DETERMINISTIC_MNEMONIC; case 4: return DETERMINISTIC_KEY; default: return null; } } public static com.google.protobuf.Internal.EnumLiteMap<Type> internalGetValueMap() { return internalValueMap; } private static final com.google.protobuf.Internal.EnumLiteMap< Type> internalValueMap = new com.google.protobuf.Internal.EnumLiteMap<Type>() { @java.lang.Override public Type findValueByNumber(int number) { return Type.forNumber(number); } }; public static com.google.protobuf.Internal.EnumVerifier internalGetVerifier() { return TypeVerifier.INSTANCE; } private static final class TypeVerifier implements com.google.protobuf.Internal.EnumVerifier { static final com.google.protobuf.Internal.EnumVerifier INSTANCE = new TypeVerifier(); @java.lang.Override public boolean isInRange(int number) { return Type.forNumber(number) != null; } }; private final int value; private Type(int value) { this.value = value; } // @@protoc_insertion_point(enum_scope:wallet.Key.Type) } /** * Protobuf enum {@code wallet.Key.OutputScriptType} */ public enum OutputScriptType implements com.google.protobuf.Internal.EnumLite { /** * <code>P2PKH = 1;</code> */ P2PKH(1), /** * <code>P2WPKH = 2;</code> */ P2WPKH(2), ; /** * <code>P2PKH = 1;</code> */ public static final int P2PKH_VALUE = 1; /** * <code>P2WPKH = 2;</code> */ public static final int P2WPKH_VALUE = 2; @java.lang.Override public final int getNumber() { return value; } /** * @param value The number of the enum to look for. * @return The enum associated with the given number. * @deprecated Use {@link #forNumber(int)} instead. */ @java.lang.Deprecated public static OutputScriptType valueOf(int value) { return forNumber(value); } public static OutputScriptType forNumber(int value) { switch (value) { case 1: return P2PKH; case 2: return P2WPKH; default: return null; } } public static com.google.protobuf.Internal.EnumLiteMap<OutputScriptType> internalGetValueMap() { return internalValueMap; } private static final com.google.protobuf.Internal.EnumLiteMap< OutputScriptType> internalValueMap = new com.google.protobuf.Internal.EnumLiteMap<OutputScriptType>() { @java.lang.Override public OutputScriptType findValueByNumber(int number) { return OutputScriptType.forNumber(number); } }; public static com.google.protobuf.Internal.EnumVerifier internalGetVerifier() { return OutputScriptTypeVerifier.INSTANCE; } private static final class OutputScriptTypeVerifier implements com.google.protobuf.Internal.EnumVerifier { static final com.google.protobuf.Internal.EnumVerifier INSTANCE = new OutputScriptTypeVerifier(); @java.lang.Override public boolean isInRange(int number) { return OutputScriptType.forNumber(number) != null; } }; private final int value; private OutputScriptType(int value) { this.value = value; } // @@protoc_insertion_point(enum_scope:wallet.Key.OutputScriptType) } private int bitField0_; public static final int TYPE_FIELD_NUMBER = 1; private int type_; /** * <code>required .wallet.Key.Type type = 1;</code> * @return Whether the type field is set. */ @java.lang.Override public boolean hasType() { return ((bitField0_ & 0x00000001) != 0); } /** * <code>required .wallet.Key.Type type = 1;</code> * @return The type. */ @java.lang.Override public org.bitcoinj.wallet.Protos.Key.Type getType() { org.bitcoinj.wallet.Protos.Key.Type result = org.bitcoinj.wallet.Protos.Key.Type.forNumber(type_); return result == null ? org.bitcoinj.wallet.Protos.Key.Type.ORIGINAL : result; } /** * <code>required .wallet.Key.Type type = 1;</code> * @param value The type to set. */ private void setType(org.bitcoinj.wallet.Protos.Key.Type value) { type_ = value.getNumber(); bitField0_ |= 0x00000001; } /** * <code>required .wallet.Key.Type type = 1;</code> */ private void clearType() { bitField0_ = (bitField0_ & ~0x00000001); type_ = 1; } public static final int SECRET_BYTES_FIELD_NUMBER = 2; private com.google.protobuf.ByteString secretBytes_; /** * <pre> * Either the private EC key bytes (without any ASN.1 wrapping), or the deterministic root seed. * If the secret is encrypted, or this is a "watching entry" then this is missing. * </pre> * * <code>optional bytes secret_bytes = 2;</code> * @return Whether the secretBytes field is set. */ @java.lang.Override public boolean hasSecretBytes() { return ((bitField0_ & 0x00000002) != 0); } /** * <pre> * Either the private EC key bytes (without any ASN.1 wrapping), or the deterministic root seed. * If the secret is encrypted, or this is a "watching entry" then this is missing. * </pre> * * <code>optional bytes secret_bytes = 2;</code> * @return The secretBytes. */ @java.lang.Override public com.google.protobuf.ByteString getSecretBytes() { return secretBytes_; } /** * <pre> * Either the private EC key bytes (without any ASN.1 wrapping), or the deterministic root seed. * If the secret is encrypted, or this is a "watching entry" then this is missing. * </pre> * * <code>optional bytes secret_bytes = 2;</code> * @param value The secretBytes to set. */ private void setSecretBytes(com.google.protobuf.ByteString value) { java.lang.Class<?> valueClass = value.getClass(); bitField0_ |= 0x00000002; secretBytes_ = value; } /** * <pre> * Either the private EC key bytes (without any ASN.1 wrapping), or the deterministic root seed. * If the secret is encrypted, or this is a "watching entry" then this is missing. * </pre> * * <code>optional bytes secret_bytes = 2;</code> */ private void clearSecretBytes() { bitField0_ = (bitField0_ & ~0x00000002); secretBytes_ = getDefaultInstance().getSecretBytes(); } public static final int ENCRYPTED_DATA_FIELD_NUMBER = 6; private org.bitcoinj.wallet.Protos.EncryptedData encryptedData_; /** * <pre> * If the secret data is encrypted, then secret_bytes is missing and this field is set. * </pre> * * <code>optional .wallet.EncryptedData encrypted_data = 6;</code> */ @java.lang.Override public boolean hasEncryptedData() { return ((bitField0_ & 0x00000004) != 0); } /** * <pre> * If the secret data is encrypted, then secret_bytes is missing and this field is set. * </pre> * * <code>optional .wallet.EncryptedData encrypted_data = 6;</code> */ @java.lang.Override public org.bitcoinj.wallet.Protos.EncryptedData getEncryptedData() { return encryptedData_ == null ? org.bitcoinj.wallet.Protos.EncryptedData.getDefaultInstance() : encryptedData_; } /** * <pre> * If the secret data is encrypted, then secret_bytes is missing and this field is set. * </pre> * * <code>optional .wallet.EncryptedData encrypted_data = 6;</code> */ private void setEncryptedData(org.bitcoinj.wallet.Protos.EncryptedData value) { value.getClass(); encryptedData_ = value; bitField0_ |= 0x00000004; } /** * <pre> * If the secret data is encrypted, then secret_bytes is missing and this field is set. * </pre> * * <code>optional .wallet.EncryptedData encrypted_data = 6;</code> */ @java.lang.SuppressWarnings({"ReferenceEquality"}) private void mergeEncryptedData(org.bitcoinj.wallet.Protos.EncryptedData value) { value.getClass(); if (encryptedData_ != null && encryptedData_ != org.bitcoinj.wallet.Protos.EncryptedData.getDefaultInstance()) { encryptedData_ = org.bitcoinj.wallet.Protos.EncryptedData.newBuilder(encryptedData_).mergeFrom(value).buildPartial(); } else { encryptedData_ = value; } bitField0_ |= 0x00000004; } /** * <pre> * If the secret data is encrypted, then secret_bytes is missing and this field is set. * </pre> * * <code>optional .wallet.EncryptedData encrypted_data = 6;</code> */ private void clearEncryptedData() { encryptedData_ = null; bitField0_ = (bitField0_ & ~0x00000004); } public static final int PUBLIC_KEY_FIELD_NUMBER = 3; private com.google.protobuf.ByteString publicKey_; /** * <pre> * The public EC key derived from the private key. We allow both to be stored to avoid mobile clients having to * do lots of slow EC math on startup. For DETERMINISTIC_MNEMONIC entries this is missing. * </pre> * * <code>optional bytes public_key = 3;</code> * @return Whether the publicKey field is set. */ @java.lang.Override public boolean hasPublicKey() { return ((bitField0_ & 0x00000008) != 0); } /** * <pre> * The public EC key derived from the private key. We allow both to be stored to avoid mobile clients having to * do lots of slow EC math on startup. For DETERMINISTIC_MNEMONIC entries this is missing. * </pre> * * <code>optional bytes public_key = 3;</code> * @return The publicKey. */ @java.lang.Override public com.google.protobuf.ByteString getPublicKey() { return publicKey_; } /** * <pre> * The public EC key derived from the private key. We allow both to be stored to avoid mobile clients having to * do lots of slow EC math on startup. For DETERMINISTIC_MNEMONIC entries this is missing. * </pre> * * <code>optional bytes public_key = 3;</code> * @param value The publicKey to set. */ private void setPublicKey(com.google.protobuf.ByteString value) { java.lang.Class<?> valueClass = value.getClass(); bitField0_ |= 0x00000008; publicKey_ = value; } /** * <pre> * The public EC key derived from the private key. We allow both to be stored to avoid mobile clients having to * do lots of slow EC math on startup. For DETERMINISTIC_MNEMONIC entries this is missing. * </pre> * * <code>optional bytes public_key = 3;</code> */ private void clearPublicKey() { bitField0_ = (bitField0_ & ~0x00000008); publicKey_ = getDefaultInstance().getPublicKey(); } public static final int LABEL_FIELD_NUMBER = 4; private java.lang.String label_; /** * <pre> * User-provided label associated with the key. * </pre> * * <code>optional string label = 4;</code> * @return Whether the label field is set. */ @java.lang.Override public boolean hasLabel() { return ((bitField0_ & 0x00000010) != 0); } /** * <pre> * User-provided label associated with the key. * </pre> * * <code>optional string label = 4;</code> * @return The label. */ @java.lang.Override public java.lang.String getLabel() { return label_; } /** * <pre> * User-provided label associated with the key. * </pre> * * <code>optional string label = 4;</code> * @return The bytes for label. */ @java.lang.Override public com.google.protobuf.ByteString getLabelBytes() { return com.google.protobuf.ByteString.copyFromUtf8(label_); } /** * <pre> * User-provided label associated with the key. * </pre> * * <code>optional string label = 4;</code> * @param value The label to set. */ private void setLabel( java.lang.String value) { java.lang.Class<?> valueClass = value.getClass(); bitField0_ |= 0x00000010; label_ = value; } /** * <pre> * User-provided label associated with the key. * </pre> * * <code>optional string label = 4;</code> */ private void clearLabel() { bitField0_ = (bitField0_ & ~0x00000010); label_ = getDefaultInstance().getLabel(); } /** * <pre> * User-provided label associated with the key. * </pre> * * <code>optional string label = 4;</code> * @param value The bytes for label to set. */ private void setLabelBytes( com.google.protobuf.ByteString value) { label_ = value.toStringUtf8(); bitField0_ |= 0x00000010; } public static final int CREATION_TIMESTAMP_FIELD_NUMBER = 5; private long creationTimestamp_; /** * <pre> * Timestamp stored as millis since epoch. Useful for skipping block bodies before this point. The reason it's * optional is that keys derived from a parent don't have this data. * </pre> * * <code>optional int64 creation_timestamp = 5;</code> * @return Whether the creationTimestamp field is set. */ @java.lang.Override public boolean hasCreationTimestamp() { return ((bitField0_ & 0x00000020) != 0); } /** * <pre> * Timestamp stored as millis since epoch. Useful for skipping block bodies before this point. The reason it's * optional is that keys derived from a parent don't have this data. * </pre> * * <code>optional int64 creation_timestamp = 5;</code> * @return The creationTimestamp. */ @java.lang.Override public long getCreationTimestamp() { return creationTimestamp_; } /** * <pre> * Timestamp stored as millis since epoch. Useful for skipping block bodies before this point. The reason it's * optional is that keys derived from a parent don't have this data. * </pre> * * <code>optional int64 creation_timestamp = 5;</code> * @param value The creationTimestamp to set. */ private void setCreationTimestamp(long value) { bitField0_ |= 0x00000020; creationTimestamp_ = value; } /** * <pre> * Timestamp stored as millis since epoch. Useful for skipping block bodies before this point. The reason it's * optional is that keys derived from a parent don't have this data. * </pre> * * <code>optional int64 creation_timestamp = 5;</code> */ private void clearCreationTimestamp() { bitField0_ = (bitField0_ & ~0x00000020); creationTimestamp_ = 0L; } public static final int DETERMINISTIC_KEY_FIELD_NUMBER = 7; private org.bitcoinj.wallet.Protos.DeterministicKey deterministicKey_; /** * <code>optional .wallet.DeterministicKey deterministic_key = 7;</code> */ @java.lang.Override public boolean hasDeterministicKey() { return ((bitField0_ & 0x00000040) != 0); } /** * <code>optional .wallet.DeterministicKey deterministic_key = 7;</code> */ @java.lang.Override public org.bitcoinj.wallet.Protos.DeterministicKey getDeterministicKey() { return deterministicKey_ == null ? org.bitcoinj.wallet.Protos.DeterministicKey.getDefaultInstance() : deterministicKey_; } /** * <code>optional .wallet.DeterministicKey deterministic_key = 7;</code> */ private void setDeterministicKey(org.bitcoinj.wallet.Protos.DeterministicKey value) { value.getClass(); deterministicKey_ = value; bitField0_ |= 0x00000040; } /** * <code>optional .wallet.DeterministicKey deterministic_key = 7;</code> */ @java.lang.SuppressWarnings({"ReferenceEquality"}) private void mergeDeterministicKey(org.bitcoinj.wallet.Protos.DeterministicKey value) { value.getClass(); if (deterministicKey_ != null && deterministicKey_ != org.bitcoinj.wallet.Protos.DeterministicKey.getDefaultInstance()) { deterministicKey_ = org.bitcoinj.wallet.Protos.DeterministicKey.newBuilder(deterministicKey_).mergeFrom(value).buildPartial(); } else { deterministicKey_ = value; } bitField0_ |= 0x00000040; } /** * <code>optional .wallet.DeterministicKey deterministic_key = 7;</code> */ private void clearDeterministicKey() { deterministicKey_ = null; bitField0_ = (bitField0_ & ~0x00000040); } public static final int DETERMINISTIC_SEED_FIELD_NUMBER = 8; private com.google.protobuf.ByteString deterministicSeed_; /** * <pre> * The seed for a deterministic key hierarchy. Derived from the mnemonic, * but cached here for quick startup. Only applicable to a DETERMINISTIC_MNEMONIC key entry. * </pre> * * <code>optional bytes deterministic_seed = 8;</code> * @return Whether the deterministicSeed field is set. */ @java.lang.Override public boolean hasDeterministicSeed() { return ((bitField0_ & 0x00000080) != 0); } /** * <pre> * The seed for a deterministic key hierarchy. Derived from the mnemonic, * but cached here for quick startup. Only applicable to a DETERMINISTIC_MNEMONIC key entry. * </pre> * * <code>optional bytes deterministic_seed = 8;</code> * @return The deterministicSeed. */ @java.lang.Override public com.google.protobuf.ByteString getDeterministicSeed() { return deterministicSeed_; } /** * <pre> * The seed for a deterministic key hierarchy. Derived from the mnemonic, * but cached here for quick startup. Only applicable to a DETERMINISTIC_MNEMONIC key entry. * </pre> * * <code>optional bytes deterministic_seed = 8;</code> * @param value The deterministicSeed to set. */ private void setDeterministicSeed(com.google.protobuf.ByteString value) { java.lang.Class<?> valueClass = value.getClass(); bitField0_ |= 0x00000080; deterministicSeed_ = value; } /** * <pre> * The seed for a deterministic key hierarchy. Derived from the mnemonic, * but cached here for quick startup. Only applicable to a DETERMINISTIC_MNEMONIC key entry. * </pre> * * <code>optional bytes deterministic_seed = 8;</code> */ private void clearDeterministicSeed() { bitField0_ = (bitField0_ & ~0x00000080); deterministicSeed_ = getDefaultInstance().getDeterministicSeed(); } public static final int ENCRYPTED_DETERMINISTIC_SEED_FIELD_NUMBER = 9; private org.bitcoinj.wallet.Protos.EncryptedData encryptedDeterministicSeed_; /** * <pre> * Encrypted version of the seed * </pre> * * <code>optional .wallet.EncryptedData encrypted_deterministic_seed = 9;</code> */ @java.lang.Override public boolean hasEncryptedDeterministicSeed() { return ((bitField0_ & 0x00000100) != 0); } /** * <pre> * Encrypted version of the seed * </pre> * * <code>optional .wallet.EncryptedData encrypted_deterministic_seed = 9;</code> */ @java.lang.Override public org.bitcoinj.wallet.Protos.EncryptedData getEncryptedDeterministicSeed() { return encryptedDeterministicSeed_ == null ? org.bitcoinj.wallet.Protos.EncryptedData.getDefaultInstance() : encryptedDeterministicSeed_; } /** * <pre> * Encrypted version of the seed * </pre> * * <code>optional .wallet.EncryptedData encrypted_deterministic_seed = 9;</code> */ private void setEncryptedDeterministicSeed(org.bitcoinj.wallet.Protos.EncryptedData value) { value.getClass(); encryptedDeterministicSeed_ = value; bitField0_ |= 0x00000100; } /** * <pre> * Encrypted version of the seed * </pre> * * <code>optional .wallet.EncryptedData encrypted_deterministic_seed = 9;</code> */ @java.lang.SuppressWarnings({"ReferenceEquality"}) private void mergeEncryptedDeterministicSeed(org.bitcoinj.wallet.Protos.EncryptedData value) { value.getClass(); if (encryptedDeterministicSeed_ != null && encryptedDeterministicSeed_ != org.bitcoinj.wallet.Protos.EncryptedData.getDefaultInstance()) { encryptedDeterministicSeed_ = org.bitcoinj.wallet.Protos.EncryptedData.newBuilder(encryptedDeterministicSeed_).mergeFrom(value).buildPartial(); } else { encryptedDeterministicSeed_ = value; } bitField0_ |= 0x00000100; } /** * <pre> * Encrypted version of the seed * </pre> * * <code>optional .wallet.EncryptedData encrypted_deterministic_seed = 9;</code> */ private void clearEncryptedDeterministicSeed() { encryptedDeterministicSeed_ = null; bitField0_ = (bitField0_ & ~0x00000100); } public static final int ACCOUNT_PATH_FIELD_NUMBER = 10; private com.google.protobuf.Internal.IntList accountPath_; /** * <pre> * The path to the root. Only applicable to a DETERMINISTIC_MNEMONIC key entry. * </pre> * * <code>repeated uint32 account_path = 10 [packed = true];</code> * @return A list containing the accountPath. */ @java.lang.Override public java.util.List<java.lang.Integer> getAccountPathList() { return accountPath_; } /** * <pre> * The path to the root. Only applicable to a DETERMINISTIC_MNEMONIC key entry. * </pre> * * <code>repeated uint32 account_path = 10 [packed = true];</code> * @return The count of accountPath. */ @java.lang.Override public int getAccountPathCount() { return accountPath_.size(); } /** * <pre> * The path to the root. Only applicable to a DETERMINISTIC_MNEMONIC key entry. * </pre> * * <code>repeated uint32 account_path = 10 [packed = true];</code> * @param index The index of the element to return. * @return The accountPath at the given index. */ @java.lang.Override public int getAccountPath(int index) { return accountPath_.getInt(index); } private int accountPathMemoizedSerializedSize = -1; private void ensureAccountPathIsMutable() { com.google.protobuf.Internal.IntList tmp = accountPath_; if (!tmp.isModifiable()) { accountPath_ = com.google.protobuf.GeneratedMessageLite.mutableCopy(tmp); } } /** * <pre> * The path to the root. Only applicable to a DETERMINISTIC_MNEMONIC key entry. * </pre> * * <code>repeated uint32 account_path = 10 [packed = true];</code> * @param index The index to set the value at. * @param value The accountPath to set. */ private void setAccountPath( int index, int value) { ensureAccountPathIsMutable(); accountPath_.setInt(index, value); } /** * <pre> * The path to the root. Only applicable to a DETERMINISTIC_MNEMONIC key entry. * </pre> * * <code>repeated uint32 account_path = 10 [packed = true];</code> * @param value The accountPath to add. */ private void addAccountPath(int value) { ensureAccountPathIsMutable(); accountPath_.addInt(value); } /** * <pre> * The path to the root. Only applicable to a DETERMINISTIC_MNEMONIC key entry. * </pre> * * <code>repeated uint32 account_path = 10 [packed = true];</code> * @param values The accountPath to add. */ private void addAllAccountPath( java.lang.Iterable<? extends java.lang.Integer> values) { ensureAccountPathIsMutable(); com.google.protobuf.AbstractMessageLite.addAll( values, accountPath_); } /** * <pre> * The path to the root. Only applicable to a DETERMINISTIC_MNEMONIC key entry. * </pre> * * <code>repeated uint32 account_path = 10 [packed = true];</code> */ private void clearAccountPath() { accountPath_ = emptyIntList(); } public static final int OUTPUT_SCRIPT_TYPE_FIELD_NUMBER = 11; private int outputScriptType_; /** * <pre> * Type of addresses (aka output scripts) to generate for receiving. * </pre> * * <code>optional .wallet.Key.OutputScriptType output_script_type = 11;</code> * @return Whether the outputScriptType field is set. */ @java.lang.Override public boolean hasOutputScriptType() { return ((bitField0_ & 0x00000200) != 0); } /** * <pre> * Type of addresses (aka output scripts) to generate for receiving. * </pre> * * <code>optional .wallet.Key.OutputScriptType output_script_type = 11;</code> * @return The outputScriptType. */ @java.lang.Override public org.bitcoinj.wallet.Protos.Key.OutputScriptType getOutputScriptType() { org.bitcoinj.wallet.Protos.Key.OutputScriptType result = org.bitcoinj.wallet.Protos.Key.OutputScriptType.forNumber(outputScriptType_); return result == null ? org.bitcoinj.wallet.Protos.Key.OutputScriptType.P2PKH : result; } /** * <pre> * Type of addresses (aka output scripts) to generate for receiving. * </pre> * * <code>optional .wallet.Key.OutputScriptType output_script_type = 11;</code> * @param value The outputScriptType to set. */ private void setOutputScriptType(org.bitcoinj.wallet.Protos.Key.OutputScriptType value) { outputScriptType_ = value.getNumber(); bitField0_ |= 0x00000200; } /** * <pre> * Type of addresses (aka output scripts) to generate for receiving. * </pre> * * <code>optional .wallet.Key.OutputScriptType output_script_type = 11;</code> */ private void clearOutputScriptType() { bitField0_ = (bitField0_ & ~0x00000200); outputScriptType_ = 1; } public static org.bitcoinj.wallet.Protos.Key parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return com.google.protobuf.GeneratedMessageLite.parseFrom( DEFAULT_INSTANCE, data); } public static org.bitcoinj.wallet.Protos.Key parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return com.google.protobuf.GeneratedMessageLite.parseFrom( DEFAULT_INSTANCE, data, extensionRegistry); } public static org.bitcoinj.wallet.Protos.Key parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return com.google.protobuf.GeneratedMessageLite.parseFrom( DEFAULT_INSTANCE, data); } public static org.bitcoinj.wallet.Protos.Key parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return com.google.protobuf.GeneratedMessageLite.parseFrom( DEFAULT_INSTANCE, data, extensionRegistry); } public static org.bitcoinj.wallet.Protos.Key parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return com.google.protobuf.GeneratedMessageLite.parseFrom( DEFAULT_INSTANCE, data); } public static org.bitcoinj.wallet.Protos.Key parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return com.google.protobuf.GeneratedMessageLite.parseFrom( DEFAULT_INSTANCE, data, extensionRegistry); } public static org.bitcoinj.wallet.Protos.Key parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageLite.parseFrom( DEFAULT_INSTANCE, input); } public static org.bitcoinj.wallet.Protos.Key parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageLite.parseFrom( DEFAULT_INSTANCE, input, extensionRegistry); } public static org.bitcoinj.wallet.Protos.Key parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return parseDelimitedFrom(DEFAULT_INSTANCE, input); } public static org.bitcoinj.wallet.Protos.Key parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return parseDelimitedFrom(DEFAULT_INSTANCE, input, extensionRegistry); } public static org.bitcoinj.wallet.Protos.Key parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageLite.parseFrom( DEFAULT_INSTANCE, input); } public static org.bitcoinj.wallet.Protos.Key parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageLite.parseFrom( DEFAULT_INSTANCE, input, extensionRegistry); } public static Builder newBuilder() { return (Builder) DEFAULT_INSTANCE.createBuilder(); } public static Builder newBuilder(org.bitcoinj.wallet.Protos.Key prototype) { return (Builder) DEFAULT_INSTANCE.createBuilder(prototype); } /** * <pre> ** * A key used to control Bitcoin spending. * * Either the private key, the public key or both may be present. It is recommended that * if the private key is provided that the public key is provided too because deriving it is slow. * * If only the public key is provided, the key can only be used to watch the blockchain and verify * transactions, and not for spending. * </pre> * * Protobuf type {@code wallet.Key} */ public static final class Builder extends com.google.protobuf.GeneratedMessageLite.Builder< org.bitcoinj.wallet.Protos.Key, Builder> implements // @@protoc_insertion_point(builder_implements:wallet.Key) org.bitcoinj.wallet.Protos.KeyOrBuilder { // Construct using org.bitcoinj.wallet.Protos.Key.newBuilder() private Builder() { super(DEFAULT_INSTANCE); } /** * <code>required .wallet.Key.Type type = 1;</code> * @return Whether the type field is set. */ @java.lang.Override public boolean hasType() { return instance.hasType(); } /** * <code>required .wallet.Key.Type type = 1;</code> * @return The type. */ @java.lang.Override public org.bitcoinj.wallet.Protos.Key.Type getType() { return instance.getType(); } /** * <code>required .wallet.Key.Type type = 1;</code> * @param value The enum numeric value on the wire for type to set. * @return This builder for chaining. */ public Builder setType(org.bitcoinj.wallet.Protos.Key.Type value) { copyOnWrite(); instance.setType(value); return this; } /** * <code>required .wallet.Key.Type type = 1;</code> * @return This builder for chaining. */ public Builder clearType() { copyOnWrite(); instance.clearType(); return this; } /** * <pre> * Either the private EC key bytes (without any ASN.1 wrapping), or the deterministic root seed. * If the secret is encrypted, or this is a "watching entry" then this is missing. * </pre> * * <code>optional bytes secret_bytes = 2;</code> * @return Whether the secretBytes field is set. */ @java.lang.Override public boolean hasSecretBytes() { return instance.hasSecretBytes(); } /** * <pre> * Either the private EC key bytes (without any ASN.1 wrapping), or the deterministic root seed. * If the secret is encrypted, or this is a "watching entry" then this is missing. * </pre> * * <code>optional bytes secret_bytes = 2;</code> * @return The secretBytes. */ @java.lang.Override public com.google.protobuf.ByteString getSecretBytes() { return instance.getSecretBytes(); } /** * <pre> * Either the private EC key bytes (without any ASN.1 wrapping), or the deterministic root seed. * If the secret is encrypted, or this is a "watching entry" then this is missing. * </pre> * * <code>optional bytes secret_bytes = 2;</code> * @param value The secretBytes to set. * @return This builder for chaining. */ public Builder setSecretBytes(com.google.protobuf.ByteString value) { copyOnWrite(); instance.setSecretBytes(value); return this; } /** * <pre> * Either the private EC key bytes (without any ASN.1 wrapping), or the deterministic root seed. * If the secret is encrypted, or this is a "watching entry" then this is missing. * </pre> * * <code>optional bytes secret_bytes = 2;</code> * @return This builder for chaining. */ public Builder clearSecretBytes() { copyOnWrite(); instance.clearSecretBytes(); return this; } /** * <pre> * If the secret data is encrypted, then secret_bytes is missing and this field is set. * </pre> * * <code>optional .wallet.EncryptedData encrypted_data = 6;</code> */ @java.lang.Override public boolean hasEncryptedData() { return instance.hasEncryptedData(); } /** * <pre> * If the secret data is encrypted, then secret_bytes is missing and this field is set. * </pre> * * <code>optional .wallet.EncryptedData encrypted_data = 6;</code> */ @java.lang.Override public org.bitcoinj.wallet.Protos.EncryptedData getEncryptedData() { return instance.getEncryptedData(); } /** * <pre> * If the secret data is encrypted, then secret_bytes is missing and this field is set. * </pre> * * <code>optional .wallet.EncryptedData encrypted_data = 6;</code> */ public Builder setEncryptedData(org.bitcoinj.wallet.Protos.EncryptedData value) { copyOnWrite(); instance.setEncryptedData(value); return this; } /** * <pre> * If the secret data is encrypted, then secret_bytes is missing and this field is set. * </pre> * * <code>optional .wallet.EncryptedData encrypted_data = 6;</code> */ public Builder setEncryptedData( org.bitcoinj.wallet.Protos.EncryptedData.Builder builderForValue) { copyOnWrite(); instance.setEncryptedData(builderForValue.build()); return this; } /** * <pre> * If the secret data is encrypted, then secret_bytes is missing and this field is set. * </pre> * * <code>optional .wallet.EncryptedData encrypted_data = 6;</code> */ public Builder mergeEncryptedData(org.bitcoinj.wallet.Protos.EncryptedData value) { copyOnWrite(); instance.mergeEncryptedData(value); return this; } /** * <pre> * If the secret data is encrypted, then secret_bytes is missing and this field is set. * </pre> * * <code>optional .wallet.EncryptedData encrypted_data = 6;</code> */ public Builder clearEncryptedData() { copyOnWrite(); instance.clearEncryptedData(); return this; } /** * <pre> * The public EC key derived from the private key. We allow both to be stored to avoid mobile clients having to * do lots of slow EC math on startup. For DETERMINISTIC_MNEMONIC entries this is missing. * </pre> * * <code>optional bytes public_key = 3;</code> * @return Whether the publicKey field is set. */ @java.lang.Override public boolean hasPublicKey() { return instance.hasPublicKey(); } /** * <pre> * The public EC key derived from the private key. We allow both to be stored to avoid mobile clients having to * do lots of slow EC math on startup. For DETERMINISTIC_MNEMONIC entries this is missing. * </pre> * * <code>optional bytes public_key = 3;</code> * @return The publicKey. */ @java.lang.Override public com.google.protobuf.ByteString getPublicKey() { return instance.getPublicKey(); } /** * <pre> * The public EC key derived from the private key. We allow both to be stored to avoid mobile clients having to * do lots of slow EC math on startup. For DETERMINISTIC_MNEMONIC entries this is missing. * </pre> * * <code>optional bytes public_key = 3;</code> * @param value The publicKey to set. * @return This builder for chaining. */ public Builder setPublicKey(com.google.protobuf.ByteString value) { copyOnWrite(); instance.setPublicKey(value); return this; } /** * <pre> * The public EC key derived from the private key. We allow both to be stored to avoid mobile clients having to * do lots of slow EC math on startup. For DETERMINISTIC_MNEMONIC entries this is missing. * </pre> * * <code>optional bytes public_key = 3;</code> * @return This builder for chaining. */ public Builder clearPublicKey() { copyOnWrite(); instance.clearPublicKey(); return this; } /** * <pre> * User-provided label associated with the key. * </pre> * * <code>optional string label = 4;</code> * @return Whether the label field is set. */ @java.lang.Override public boolean hasLabel() { return instance.hasLabel(); } /** * <pre> * User-provided label associated with the key. * </pre> * * <code>optional string label = 4;</code> * @return The label. */ @java.lang.Override public java.lang.String getLabel() { return instance.getLabel(); } /** * <pre> * User-provided label associated with the key. * </pre> * * <code>optional string label = 4;</code> * @return The bytes for label. */ @java.lang.Override public com.google.protobuf.ByteString getLabelBytes() { return instance.getLabelBytes(); } /** * <pre> * User-provided label associated with the key. * </pre> * * <code>optional string label = 4;</code> * @param value The label to set. * @return This builder for chaining. */ public Builder setLabel( java.lang.String value) { copyOnWrite(); instance.setLabel(value); return this; } /** * <pre> * User-provided label associated with the key. * </pre> * * <code>optional string label = 4;</code> * @return This builder for chaining. */ public Builder clearLabel() { copyOnWrite(); instance.clearLabel(); return this; } /** * <pre> * User-provided label associated with the key. * </pre> * * <code>optional string label = 4;</code> * @param value The bytes for label to set. * @return This builder for chaining. */ public Builder setLabelBytes( com.google.protobuf.ByteString value) { copyOnWrite(); instance.setLabelBytes(value); return this; } /** * <pre> * Timestamp stored as millis since epoch. Useful for skipping block bodies before this point. The reason it's * optional is that keys derived from a parent don't have this data. * </pre> * * <code>optional int64 creation_timestamp = 5;</code> * @return Whether the creationTimestamp field is set. */ @java.lang.Override public boolean hasCreationTimestamp() { return instance.hasCreationTimestamp(); } /** * <pre> * Timestamp stored as millis since epoch. Useful for skipping block bodies before this point. The reason it's * optional is that keys derived from a parent don't have this data. * </pre> * * <code>optional int64 creation_timestamp = 5;</code> * @return The creationTimestamp. */ @java.lang.Override public long getCreationTimestamp() { return instance.getCreationTimestamp(); } /** * <pre> * Timestamp stored as millis since epoch. Useful for skipping block bodies before this point. The reason it's * optional is that keys derived from a parent don't have this data. * </pre> * * <code>optional int64 creation_timestamp = 5;</code> * @param value The creationTimestamp to set. * @return This builder for chaining. */ public Builder setCreationTimestamp(long value) { copyOnWrite(); instance.setCreationTimestamp(value); return this; } /** * <pre> * Timestamp stored as millis since epoch. Useful for skipping block bodies before this point. The reason it's * optional is that keys derived from a parent don't have this data. * </pre> * * <code>optional int64 creation_timestamp = 5;</code> * @return This builder for chaining. */ public Builder clearCreationTimestamp() { copyOnWrite(); instance.clearCreationTimestamp(); return this; } /** * <code>optional .wallet.DeterministicKey deterministic_key = 7;</code> */ @java.lang.Override public boolean hasDeterministicKey() { return instance.hasDeterministicKey(); } /** * <code>optional .wallet.DeterministicKey deterministic_key = 7;</code> */ @java.lang.Override public org.bitcoinj.wallet.Protos.DeterministicKey getDeterministicKey() { return instance.getDeterministicKey(); } /** * <code>optional .wallet.DeterministicKey deterministic_key = 7;</code> */ public Builder setDeterministicKey(org.bitcoinj.wallet.Protos.DeterministicKey value) { copyOnWrite(); instance.setDeterministicKey(value); return this; } /** * <code>optional .wallet.DeterministicKey deterministic_key = 7;</code> */ public Builder setDeterministicKey( org.bitcoinj.wallet.Protos.DeterministicKey.Builder builderForValue) { copyOnWrite(); instance.setDeterministicKey(builderForValue.build()); return this; } /** * <code>optional .wallet.DeterministicKey deterministic_key = 7;</code> */ public Builder mergeDeterministicKey(org.bitcoinj.wallet.Protos.DeterministicKey value) { copyOnWrite(); instance.mergeDeterministicKey(value); return this; } /** * <code>optional .wallet.DeterministicKey deterministic_key = 7;</code> */ public Builder clearDeterministicKey() { copyOnWrite(); instance.clearDeterministicKey(); return this; } /** * <pre> * The seed for a deterministic key hierarchy. Derived from the mnemonic, * but cached here for quick startup. Only applicable to a DETERMINISTIC_MNEMONIC key entry. * </pre> * * <code>optional bytes deterministic_seed = 8;</code> * @return Whether the deterministicSeed field is set. */ @java.lang.Override public boolean hasDeterministicSeed() { return instance.hasDeterministicSeed(); } /** * <pre> * The seed for a deterministic key hierarchy. Derived from the mnemonic, * but cached here for quick startup. Only applicable to a DETERMINISTIC_MNEMONIC key entry. * </pre> * * <code>optional bytes deterministic_seed = 8;</code> * @return The deterministicSeed. */ @java.lang.Override public com.google.protobuf.ByteString getDeterministicSeed() { return instance.getDeterministicSeed(); } /** * <pre> * The seed for a deterministic key hierarchy. Derived from the mnemonic, * but cached here for quick startup. Only applicable to a DETERMINISTIC_MNEMONIC key entry. * </pre> * * <code>optional bytes deterministic_seed = 8;</code> * @param value The deterministicSeed to set. * @return This builder for chaining. */ public Builder setDeterministicSeed(com.google.protobuf.ByteString value) { copyOnWrite(); instance.setDeterministicSeed(value); return this; } /** * <pre> * The seed for a deterministic key hierarchy. Derived from the mnemonic, * but cached here for quick startup. Only applicable to a DETERMINISTIC_MNEMONIC key entry. * </pre> * * <code>optional bytes deterministic_seed = 8;</code> * @return This builder for chaining. */ public Builder clearDeterministicSeed() { copyOnWrite(); instance.clearDeterministicSeed(); return this; } /** * <pre> * Encrypted version of the seed * </pre> * * <code>optional .wallet.EncryptedData encrypted_deterministic_seed = 9;</code> */ @java.lang.Override public boolean hasEncryptedDeterministicSeed() { return instance.hasEncryptedDeterministicSeed(); } /** * <pre> * Encrypted version of the seed * </pre> * * <code>optional .wallet.EncryptedData encrypted_deterministic_seed = 9;</code> */ @java.lang.Override public org.bitcoinj.wallet.Protos.EncryptedData getEncryptedDeterministicSeed() { return instance.getEncryptedDeterministicSeed(); } /** * <pre> * Encrypted version of the seed * </pre> * * <code>optional .wallet.EncryptedData encrypted_deterministic_seed = 9;</code> */ public Builder setEncryptedDeterministicSeed(org.bitcoinj.wallet.Protos.EncryptedData value) { copyOnWrite(); instance.setEncryptedDeterministicSeed(value); return this; } /** * <pre> * Encrypted version of the seed * </pre> * * <code>optional .wallet.EncryptedData encrypted_deterministic_seed = 9;</code> */ public Builder setEncryptedDeterministicSeed( org.bitcoinj.wallet.Protos.EncryptedData.Builder builderForValue) { copyOnWrite(); instance.setEncryptedDeterministicSeed(builderForValue.build()); return this; } /** * <pre> * Encrypted version of the seed * </pre> * * <code>optional .wallet.EncryptedData encrypted_deterministic_seed = 9;</code> */ public Builder mergeEncryptedDeterministicSeed(org.bitcoinj.wallet.Protos.EncryptedData value) { copyOnWrite(); instance.mergeEncryptedDeterministicSeed(value); return this; } /** * <pre> * Encrypted version of the seed * </pre> * * <code>optional .wallet.EncryptedData encrypted_deterministic_seed = 9;</code> */ public Builder clearEncryptedDeterministicSeed() { copyOnWrite(); instance.clearEncryptedDeterministicSeed(); return this; } /** * <pre> * The path to the root. Only applicable to a DETERMINISTIC_MNEMONIC key entry. * </pre> * * <code>repeated uint32 account_path = 10 [packed = true];</code> * @return A list containing the accountPath. */ @java.lang.Override public java.util.List<java.lang.Integer> getAccountPathList() { return java.util.Collections.unmodifiableList( instance.getAccountPathList()); } /** * <pre> * The path to the root. Only applicable to a DETERMINISTIC_MNEMONIC key entry. * </pre> * * <code>repeated uint32 account_path = 10 [packed = true];</code> * @return The count of accountPath. */ @java.lang.Override public int getAccountPathCount() { return instance.getAccountPathCount(); } /** * <pre> * The path to the root. Only applicable to a DETERMINISTIC_MNEMONIC key entry. * </pre> * * <code>repeated uint32 account_path = 10 [packed = true];</code> * @param index The index of the element to return. * @return The accountPath at the given index. */ @java.lang.Override public int getAccountPath(int index) { return instance.getAccountPath(index); } /** * <pre> * The path to the root. Only applicable to a DETERMINISTIC_MNEMONIC key entry. * </pre> * * <code>repeated uint32 account_path = 10 [packed = true];</code> * @param value The accountPath to set. * @return This builder for chaining. */ public Builder setAccountPath( int index, int value) { copyOnWrite(); instance.setAccountPath(index, value); return this; } /** * <pre> * The path to the root. Only applicable to a DETERMINISTIC_MNEMONIC key entry. * </pre> * * <code>repeated uint32 account_path = 10 [packed = true];</code> * @param value The accountPath to add. * @return This builder for chaining. */ public Builder addAccountPath(int value) { copyOnWrite(); instance.addAccountPath(value); return this; } /** * <pre> * The path to the root. Only applicable to a DETERMINISTIC_MNEMONIC key entry. * </pre> * * <code>repeated uint32 account_path = 10 [packed = true];</code> * @param values The accountPath to add. * @return This builder for chaining. */ public Builder addAllAccountPath( java.lang.Iterable<? extends java.lang.Integer> values) { copyOnWrite(); instance.addAllAccountPath(values); return this; } /** * <pre> * The path to the root. Only applicable to a DETERMINISTIC_MNEMONIC key entry. * </pre> * * <code>repeated uint32 account_path = 10 [packed = true];</code> * @return This builder for chaining. */ public Builder clearAccountPath() { copyOnWrite(); instance.clearAccountPath(); return this; } /** * <pre> * Type of addresses (aka output scripts) to generate for receiving. * </pre> * * <code>optional .wallet.Key.OutputScriptType output_script_type = 11;</code> * @return Whether the outputScriptType field is set. */ @java.lang.Override public boolean hasOutputScriptType() { return instance.hasOutputScriptType(); } /** * <pre> * Type of addresses (aka output scripts) to generate for receiving. * </pre> * * <code>optional .wallet.Key.OutputScriptType output_script_type = 11;</code> * @return The outputScriptType. */ @java.lang.Override public org.bitcoinj.wallet.Protos.Key.OutputScriptType getOutputScriptType() { return instance.getOutputScriptType(); } /** * <pre> * Type of addresses (aka output scripts) to generate for receiving. * </pre> * * <code>optional .wallet.Key.OutputScriptType output_script_type = 11;</code> * @param value The enum numeric value on the wire for outputScriptType to set. * @return This builder for chaining. */ public Builder setOutputScriptType(org.bitcoinj.wallet.Protos.Key.OutputScriptType value) { copyOnWrite(); instance.setOutputScriptType(value); return this; } /** * <pre> * Type of addresses (aka output scripts) to generate for receiving. * </pre> * * <code>optional .wallet.Key.OutputScriptType output_script_type = 11;</code> * @return This builder for chaining. */ public Builder clearOutputScriptType() { copyOnWrite(); instance.clearOutputScriptType(); return this; } // @@protoc_insertion_point(builder_scope:wallet.Key) } private byte memoizedIsInitialized = 2; @java.lang.Override @java.lang.SuppressWarnings({"unchecked", "fallthrough"}) protected final java.lang.Object dynamicMethod( com.google.protobuf.GeneratedMessageLite.MethodToInvoke method, java.lang.Object arg0, java.lang.Object arg1) { switch (method) { case NEW_MUTABLE_INSTANCE: { return new org.bitcoinj.wallet.Protos.Key(); } case NEW_BUILDER: { return new Builder(); } case BUILD_MESSAGE_INFO: { java.lang.Object[] objects = new java.lang.Object[] { "bitField0_", "type_", org.bitcoinj.wallet.Protos.Key.Type.internalGetVerifier(), "secretBytes_", "publicKey_", "label_", "creationTimestamp_", "encryptedData_", "deterministicKey_", "deterministicSeed_", "encryptedDeterministicSeed_", "accountPath_", "outputScriptType_", org.bitcoinj.wallet.Protos.Key.OutputScriptType.internalGetVerifier(), }; java.lang.String info = "\u0001\u000b\u0000\u0001\u0001\u000b\u000b\u0000\u0001\u0004\u0001\u150c\u0000\u0002" + "\u100a\u0001\u0003\u100a\u0003\u0004\u1008\u0004\u0005\u1002\u0005\u0006\u1409\u0002" + "\u0007\u1409\u0006\b\u100a\u0007\t\u1409\b\n+\u000b\u100c\t"; return newMessageInfo(DEFAULT_INSTANCE, info, objects); } // fall through case GET_DEFAULT_INSTANCE: { return DEFAULT_INSTANCE; } case GET_PARSER: { com.google.protobuf.Parser<org.bitcoinj.wallet.Protos.Key> parser = PARSER; if (parser == null) { synchronized (org.bitcoinj.wallet.Protos.Key.class) { parser = PARSER; if (parser == null) { parser = new DefaultInstanceBasedParser<org.bitcoinj.wallet.Protos.Key>( DEFAULT_INSTANCE); PARSER = parser; } } } return parser; } case GET_MEMOIZED_IS_INITIALIZED: { return memoizedIsInitialized; } case SET_MEMOIZED_IS_INITIALIZED: { memoizedIsInitialized = (byte) (arg0 == null ? 0 : 1); return null; } } throw new UnsupportedOperationException(); } // @@protoc_insertion_point(class_scope:wallet.Key) private static final org.bitcoinj.wallet.Protos.Key DEFAULT_INSTANCE; static { Key defaultInstance = new Key(); // New instances are implicitly immutable so no need to make // immutable. DEFAULT_INSTANCE = defaultInstance; com.google.protobuf.GeneratedMessageLite.registerDefaultInstance( Key.class, defaultInstance); } public static org.bitcoinj.wallet.Protos.Key getDefaultInstance() { return DEFAULT_INSTANCE; } private static volatile com.google.protobuf.Parser<Key> PARSER; public static com.google.protobuf.Parser<Key> parser() { return DEFAULT_INSTANCE.getParserForType(); } } public interface ScriptOrBuilder extends // @@protoc_insertion_point(interface_extends:wallet.Script) com.google.protobuf.MessageLiteOrBuilder { /** * <code>required bytes program = 1;</code> * @return Whether the program field is set. */ boolean hasProgram(); /** * <code>required bytes program = 1;</code> * @return The program. */ com.google.protobuf.ByteString getProgram(); /** * <pre> * Timestamp stored as millis since epoch. Useful for skipping block bodies before this point * when watching for scripts on the blockchain. * </pre> * * <code>required int64 creation_timestamp = 2;</code> * @return Whether the creationTimestamp field is set. */ boolean hasCreationTimestamp(); /** * <pre> * Timestamp stored as millis since epoch. Useful for skipping block bodies before this point * when watching for scripts on the blockchain. * </pre> * * <code>required int64 creation_timestamp = 2;</code> * @return The creationTimestamp. */ long getCreationTimestamp(); } /** * Protobuf type {@code wallet.Script} */ public static final class Script extends com.google.protobuf.GeneratedMessageLite< Script, Script.Builder> implements // @@protoc_insertion_point(message_implements:wallet.Script) ScriptOrBuilder { private Script() { program_ = com.google.protobuf.ByteString.EMPTY; } private int bitField0_; public static final int PROGRAM_FIELD_NUMBER = 1; private com.google.protobuf.ByteString program_; /** * <code>required bytes program = 1;</code> * @return Whether the program field is set. */ @java.lang.Override public boolean hasProgram() { return ((bitField0_ & 0x00000001) != 0); } /** * <code>required bytes program = 1;</code> * @return The program. */ @java.lang.Override public com.google.protobuf.ByteString getProgram() { return program_; } /** * <code>required bytes program = 1;</code> * @param value The program to set. */ private void setProgram(com.google.protobuf.ByteString value) { java.lang.Class<?> valueClass = value.getClass(); bitField0_ |= 0x00000001; program_ = value; } /** * <code>required bytes program = 1;</code> */ private void clearProgram() { bitField0_ = (bitField0_ & ~0x00000001); program_ = getDefaultInstance().getProgram(); } public static final int CREATION_TIMESTAMP_FIELD_NUMBER = 2; private long creationTimestamp_; /** * <pre> * Timestamp stored as millis since epoch. Useful for skipping block bodies before this point * when watching for scripts on the blockchain. * </pre> * * <code>required int64 creation_timestamp = 2;</code> * @return Whether the creationTimestamp field is set. */ @java.lang.Override public boolean hasCreationTimestamp() { return ((bitField0_ & 0x00000002) != 0); } /** * <pre> * Timestamp stored as millis since epoch. Useful for skipping block bodies before this point * when watching for scripts on the blockchain. * </pre> * * <code>required int64 creation_timestamp = 2;</code> * @return The creationTimestamp. */ @java.lang.Override public long getCreationTimestamp() { return creationTimestamp_; } /** * <pre> * Timestamp stored as millis since epoch. Useful for skipping block bodies before this point * when watching for scripts on the blockchain. * </pre> * * <code>required int64 creation_timestamp = 2;</code> * @param value The creationTimestamp to set. */ private void setCreationTimestamp(long value) { bitField0_ |= 0x00000002; creationTimestamp_ = value; } /** * <pre> * Timestamp stored as millis since epoch. Useful for skipping block bodies before this point * when watching for scripts on the blockchain. * </pre> * * <code>required int64 creation_timestamp = 2;</code> */ private void clearCreationTimestamp() { bitField0_ = (bitField0_ & ~0x00000002); creationTimestamp_ = 0L; } public static org.bitcoinj.wallet.Protos.Script parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return com.google.protobuf.GeneratedMessageLite.parseFrom( DEFAULT_INSTANCE, data); } public static org.bitcoinj.wallet.Protos.Script parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return com.google.protobuf.GeneratedMessageLite.parseFrom( DEFAULT_INSTANCE, data, extensionRegistry); } public static org.bitcoinj.wallet.Protos.Script parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return com.google.protobuf.GeneratedMessageLite.parseFrom( DEFAULT_INSTANCE, data); } public static org.bitcoinj.wallet.Protos.Script parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return com.google.protobuf.GeneratedMessageLite.parseFrom( DEFAULT_INSTANCE, data, extensionRegistry); } public static org.bitcoinj.wallet.Protos.Script parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return com.google.protobuf.GeneratedMessageLite.parseFrom( DEFAULT_INSTANCE, data); } public static org.bitcoinj.wallet.Protos.Script parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return com.google.protobuf.GeneratedMessageLite.parseFrom( DEFAULT_INSTANCE, data, extensionRegistry); } public static org.bitcoinj.wallet.Protos.Script parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageLite.parseFrom( DEFAULT_INSTANCE, input); } public static org.bitcoinj.wallet.Protos.Script parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageLite.parseFrom( DEFAULT_INSTANCE, input, extensionRegistry); } public static org.bitcoinj.wallet.Protos.Script parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return parseDelimitedFrom(DEFAULT_INSTANCE, input); } public static org.bitcoinj.wallet.Protos.Script parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return parseDelimitedFrom(DEFAULT_INSTANCE, input, extensionRegistry); } public static org.bitcoinj.wallet.Protos.Script parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageLite.parseFrom( DEFAULT_INSTANCE, input); } public static org.bitcoinj.wallet.Protos.Script parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageLite.parseFrom( DEFAULT_INSTANCE, input, extensionRegistry); } public static Builder newBuilder() { return (Builder) DEFAULT_INSTANCE.createBuilder(); } public static Builder newBuilder(org.bitcoinj.wallet.Protos.Script prototype) { return (Builder) DEFAULT_INSTANCE.createBuilder(prototype); } /** * Protobuf type {@code wallet.Script} */ public static final class Builder extends com.google.protobuf.GeneratedMessageLite.Builder< org.bitcoinj.wallet.Protos.Script, Builder> implements // @@protoc_insertion_point(builder_implements:wallet.Script) org.bitcoinj.wallet.Protos.ScriptOrBuilder { // Construct using org.bitcoinj.wallet.Protos.Script.newBuilder() private Builder() { super(DEFAULT_INSTANCE); } /** * <code>required bytes program = 1;</code> * @return Whether the program field is set. */ @java.lang.Override public boolean hasProgram() { return instance.hasProgram(); } /** * <code>required bytes program = 1;</code> * @return The program. */ @java.lang.Override public com.google.protobuf.ByteString getProgram() { return instance.getProgram(); } /** * <code>required bytes program = 1;</code> * @param value The program to set. * @return This builder for chaining. */ public Builder setProgram(com.google.protobuf.ByteString value) { copyOnWrite(); instance.setProgram(value); return this; } /** * <code>required bytes program = 1;</code> * @return This builder for chaining. */ public Builder clearProgram() { copyOnWrite(); instance.clearProgram(); return this; } /** * <pre> * Timestamp stored as millis since epoch. Useful for skipping block bodies before this point * when watching for scripts on the blockchain. * </pre> * * <code>required int64 creation_timestamp = 2;</code> * @return Whether the creationTimestamp field is set. */ @java.lang.Override public boolean hasCreationTimestamp() { return instance.hasCreationTimestamp(); } /** * <pre> * Timestamp stored as millis since epoch. Useful for skipping block bodies before this point * when watching for scripts on the blockchain. * </pre> * * <code>required int64 creation_timestamp = 2;</code> * @return The creationTimestamp. */ @java.lang.Override public long getCreationTimestamp() { return instance.getCreationTimestamp(); } /** * <pre> * Timestamp stored as millis since epoch. Useful for skipping block bodies before this point * when watching for scripts on the blockchain. * </pre> * * <code>required int64 creation_timestamp = 2;</code> * @param value The creationTimestamp to set. * @return This builder for chaining. */ public Builder setCreationTimestamp(long value) { copyOnWrite(); instance.setCreationTimestamp(value); return this; } /** * <pre> * Timestamp stored as millis since epoch. Useful for skipping block bodies before this point * when watching for scripts on the blockchain. * </pre> * * <code>required int64 creation_timestamp = 2;</code> * @return This builder for chaining. */ public Builder clearCreationTimestamp() { copyOnWrite(); instance.clearCreationTimestamp(); return this; } // @@protoc_insertion_point(builder_scope:wallet.Script) } private byte memoizedIsInitialized = 2; @java.lang.Override @java.lang.SuppressWarnings({"unchecked", "fallthrough"}) protected final java.lang.Object dynamicMethod( com.google.protobuf.GeneratedMessageLite.MethodToInvoke method, java.lang.Object arg0, java.lang.Object arg1) { switch (method) { case NEW_MUTABLE_INSTANCE: { return new org.bitcoinj.wallet.Protos.Script(); } case NEW_BUILDER: { return new Builder(); } case BUILD_MESSAGE_INFO: { java.lang.Object[] objects = new java.lang.Object[] { "bitField0_", "program_", "creationTimestamp_", }; java.lang.String info = "\u0001\u0002\u0000\u0001\u0001\u0002\u0002\u0000\u0000\u0002\u0001\u150a\u0000\u0002" + "\u1502\u0001"; return newMessageInfo(DEFAULT_INSTANCE, info, objects); } // fall through case GET_DEFAULT_INSTANCE: { return DEFAULT_INSTANCE; } case GET_PARSER: { com.google.protobuf.Parser<org.bitcoinj.wallet.Protos.Script> parser = PARSER; if (parser == null) { synchronized (org.bitcoinj.wallet.Protos.Script.class) { parser = PARSER; if (parser == null) { parser = new DefaultInstanceBasedParser<org.bitcoinj.wallet.Protos.Script>( DEFAULT_INSTANCE); PARSER = parser; } } } return parser; } case GET_MEMOIZED_IS_INITIALIZED: { return memoizedIsInitialized; } case SET_MEMOIZED_IS_INITIALIZED: { memoizedIsInitialized = (byte) (arg0 == null ? 0 : 1); return null; } } throw new UnsupportedOperationException(); } // @@protoc_insertion_point(class_scope:wallet.Script) private static final org.bitcoinj.wallet.Protos.Script DEFAULT_INSTANCE; static { Script defaultInstance = new Script(); // New instances are implicitly immutable so no need to make // immutable. DEFAULT_INSTANCE = defaultInstance; com.google.protobuf.GeneratedMessageLite.registerDefaultInstance( Script.class, defaultInstance); } public static org.bitcoinj.wallet.Protos.Script getDefaultInstance() { return DEFAULT_INSTANCE; } private static volatile com.google.protobuf.Parser<Script> PARSER; public static com.google.protobuf.Parser<Script> parser() { return DEFAULT_INSTANCE.getParserForType(); } } public interface ScriptWitnessOrBuilder extends // @@protoc_insertion_point(interface_extends:wallet.ScriptWitness) com.google.protobuf.MessageLiteOrBuilder { /** * <code>repeated bytes data = 1;</code> * @return A list containing the data. */ java.util.List<com.google.protobuf.ByteString> getDataList(); /** * <code>repeated bytes data = 1;</code> * @return The count of data. */ int getDataCount(); /** * <code>repeated bytes data = 1;</code> * @param index The index of the element to return. * @return The data at the given index. */ com.google.protobuf.ByteString getData(int index); } /** * Protobuf type {@code wallet.ScriptWitness} */ public static final class ScriptWitness extends com.google.protobuf.GeneratedMessageLite< ScriptWitness, ScriptWitness.Builder> implements // @@protoc_insertion_point(message_implements:wallet.ScriptWitness) ScriptWitnessOrBuilder { private ScriptWitness() { data_ = emptyProtobufList(); } public static final int DATA_FIELD_NUMBER = 1; private com.google.protobuf.Internal.ProtobufList<com.google.protobuf.ByteString> data_; /** * <code>repeated bytes data = 1;</code> * @return A list containing the data. */ @java.lang.Override public java.util.List<com.google.protobuf.ByteString> getDataList() { return data_; } /** * <code>repeated bytes data = 1;</code> * @return The count of data. */ @java.lang.Override public int getDataCount() { return data_.size(); } /** * <code>repeated bytes data = 1;</code> * @param index The index of the element to return. * @return The data at the given index. */ @java.lang.Override public com.google.protobuf.ByteString getData(int index) { return data_.get(index); } private void ensureDataIsMutable() { com.google.protobuf.Internal.ProtobufList<com.google.protobuf.ByteString> tmp = data_; if (!tmp.isModifiable()) { data_ = com.google.protobuf.GeneratedMessageLite.mutableCopy(tmp); } } /** * <code>repeated bytes data = 1;</code> * @param index The index to set the value at. * @param value The data to set. */ private void setData( int index, com.google.protobuf.ByteString value) { java.lang.Class<?> valueClass = value.getClass(); ensureDataIsMutable(); data_.set(index, value); } /** * <code>repeated bytes data = 1;</code> * @param value The data to add. */ private void addData(com.google.protobuf.ByteString value) { java.lang.Class<?> valueClass = value.getClass(); ensureDataIsMutable(); data_.add(value); } /** * <code>repeated bytes data = 1;</code> * @param values The data to add. */ private void addAllData( java.lang.Iterable<? extends com.google.protobuf.ByteString> values) { ensureDataIsMutable(); com.google.protobuf.AbstractMessageLite.addAll( values, data_); } /** * <code>repeated bytes data = 1;</code> */ private void clearData() { data_ = emptyProtobufList(); } public static org.bitcoinj.wallet.Protos.ScriptWitness parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return com.google.protobuf.GeneratedMessageLite.parseFrom( DEFAULT_INSTANCE, data); } public static org.bitcoinj.wallet.Protos.ScriptWitness parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return com.google.protobuf.GeneratedMessageLite.parseFrom( DEFAULT_INSTANCE, data, extensionRegistry); } public static org.bitcoinj.wallet.Protos.ScriptWitness parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return com.google.protobuf.GeneratedMessageLite.parseFrom( DEFAULT_INSTANCE, data); } public static org.bitcoinj.wallet.Protos.ScriptWitness parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return com.google.protobuf.GeneratedMessageLite.parseFrom( DEFAULT_INSTANCE, data, extensionRegistry); } public static org.bitcoinj.wallet.Protos.ScriptWitness parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return com.google.protobuf.GeneratedMessageLite.parseFrom( DEFAULT_INSTANCE, data); } public static org.bitcoinj.wallet.Protos.ScriptWitness parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return com.google.protobuf.GeneratedMessageLite.parseFrom( DEFAULT_INSTANCE, data, extensionRegistry); } public static org.bitcoinj.wallet.Protos.ScriptWitness parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageLite.parseFrom( DEFAULT_INSTANCE, input); } public static org.bitcoinj.wallet.Protos.ScriptWitness parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageLite.parseFrom( DEFAULT_INSTANCE, input, extensionRegistry); } public static org.bitcoinj.wallet.Protos.ScriptWitness parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return parseDelimitedFrom(DEFAULT_INSTANCE, input); } public static org.bitcoinj.wallet.Protos.ScriptWitness parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return parseDelimitedFrom(DEFAULT_INSTANCE, input, extensionRegistry); } public static org.bitcoinj.wallet.Protos.ScriptWitness parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageLite.parseFrom( DEFAULT_INSTANCE, input); } public static org.bitcoinj.wallet.Protos.ScriptWitness parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageLite.parseFrom( DEFAULT_INSTANCE, input, extensionRegistry); } public static Builder newBuilder() { return (Builder) DEFAULT_INSTANCE.createBuilder(); } public static Builder newBuilder(org.bitcoinj.wallet.Protos.ScriptWitness prototype) { return (Builder) DEFAULT_INSTANCE.createBuilder(prototype); } /** * Protobuf type {@code wallet.ScriptWitness} */ public static final class Builder extends com.google.protobuf.GeneratedMessageLite.Builder< org.bitcoinj.wallet.Protos.ScriptWitness, Builder> implements // @@protoc_insertion_point(builder_implements:wallet.ScriptWitness) org.bitcoinj.wallet.Protos.ScriptWitnessOrBuilder { // Construct using org.bitcoinj.wallet.Protos.ScriptWitness.newBuilder() private Builder() { super(DEFAULT_INSTANCE); } /** * <code>repeated bytes data = 1;</code> * @return A list containing the data. */ @java.lang.Override public java.util.List<com.google.protobuf.ByteString> getDataList() { return java.util.Collections.unmodifiableList( instance.getDataList()); } /** * <code>repeated bytes data = 1;</code> * @return The count of data. */ @java.lang.Override public int getDataCount() { return instance.getDataCount(); } /** * <code>repeated bytes data = 1;</code> * @param index The index of the element to return. * @return The data at the given index. */ @java.lang.Override public com.google.protobuf.ByteString getData(int index) { return instance.getData(index); } /** * <code>repeated bytes data = 1;</code> * @param value The data to set. * @return This builder for chaining. */ public Builder setData( int index, com.google.protobuf.ByteString value) { copyOnWrite(); instance.setData(index, value); return this; } /** * <code>repeated bytes data = 1;</code> * @param value The data to add. * @return This builder for chaining. */ public Builder addData(com.google.protobuf.ByteString value) { copyOnWrite(); instance.addData(value); return this; } /** * <code>repeated bytes data = 1;</code> * @param values The data to add. * @return This builder for chaining. */ public Builder addAllData( java.lang.Iterable<? extends com.google.protobuf.ByteString> values) { copyOnWrite(); instance.addAllData(values); return this; } /** * <code>repeated bytes data = 1;</code> * @return This builder for chaining. */ public Builder clearData() { copyOnWrite(); instance.clearData(); return this; } // @@protoc_insertion_point(builder_scope:wallet.ScriptWitness) } @java.lang.Override @java.lang.SuppressWarnings({"unchecked", "fallthrough"}) protected final java.lang.Object dynamicMethod( com.google.protobuf.GeneratedMessageLite.MethodToInvoke method, java.lang.Object arg0, java.lang.Object arg1) { switch (method) { case NEW_MUTABLE_INSTANCE: { return new org.bitcoinj.wallet.Protos.ScriptWitness(); } case NEW_BUILDER: { return new Builder(); } case BUILD_MESSAGE_INFO: { java.lang.Object[] objects = new java.lang.Object[] { "data_", }; java.lang.String info = "\u0001\u0001\u0000\u0000\u0001\u0001\u0001\u0000\u0001\u0000\u0001\u001c"; return newMessageInfo(DEFAULT_INSTANCE, info, objects); } // fall through case GET_DEFAULT_INSTANCE: { return DEFAULT_INSTANCE; } case GET_PARSER: { com.google.protobuf.Parser<org.bitcoinj.wallet.Protos.ScriptWitness> parser = PARSER; if (parser == null) { synchronized (org.bitcoinj.wallet.Protos.ScriptWitness.class) { parser = PARSER; if (parser == null) { parser = new DefaultInstanceBasedParser<org.bitcoinj.wallet.Protos.ScriptWitness>( DEFAULT_INSTANCE); PARSER = parser; } } } return parser; } case GET_MEMOIZED_IS_INITIALIZED: { return (byte) 1; } case SET_MEMOIZED_IS_INITIALIZED: { return null; } } throw new UnsupportedOperationException(); } // @@protoc_insertion_point(class_scope:wallet.ScriptWitness) private static final org.bitcoinj.wallet.Protos.ScriptWitness DEFAULT_INSTANCE; static { ScriptWitness defaultInstance = new ScriptWitness(); // New instances are implicitly immutable so no need to make // immutable. DEFAULT_INSTANCE = defaultInstance; com.google.protobuf.GeneratedMessageLite.registerDefaultInstance( ScriptWitness.class, defaultInstance); } public static org.bitcoinj.wallet.Protos.ScriptWitness getDefaultInstance() { return DEFAULT_INSTANCE; } private static volatile com.google.protobuf.Parser<ScriptWitness> PARSER; public static com.google.protobuf.Parser<ScriptWitness> parser() { return DEFAULT_INSTANCE.getParserForType(); } } public interface TransactionInputOrBuilder extends // @@protoc_insertion_point(interface_extends:wallet.TransactionInput) com.google.protobuf.MessageLiteOrBuilder { /** * <pre> * Hash of the transaction this input is using. * </pre> * * <code>required bytes transaction_out_point_hash = 1;</code> * @return Whether the transactionOutPointHash field is set. */ boolean hasTransactionOutPointHash(); /** * <pre> * Hash of the transaction this input is using. * </pre> * * <code>required bytes transaction_out_point_hash = 1;</code> * @return The transactionOutPointHash. */ com.google.protobuf.ByteString getTransactionOutPointHash(); /** * <pre> * Index of transaction output used by this input. * </pre> * * <code>required uint32 transaction_out_point_index = 2;</code> * @return Whether the transactionOutPointIndex field is set. */ boolean hasTransactionOutPointIndex(); /** * <pre> * Index of transaction output used by this input. * </pre> * * <code>required uint32 transaction_out_point_index = 2;</code> * @return The transactionOutPointIndex. */ int getTransactionOutPointIndex(); /** * <pre> * Script that contains the signatures/pubkeys. * </pre> * * <code>required bytes script_bytes = 3;</code> * @return Whether the scriptBytes field is set. */ boolean hasScriptBytes(); /** * <pre> * Script that contains the signatures/pubkeys. * </pre> * * <code>required bytes script_bytes = 3;</code> * @return The scriptBytes. */ com.google.protobuf.ByteString getScriptBytes(); /** * <pre> * Sequence number. * </pre> * * <code>optional uint32 sequence = 4;</code> * @return Whether the sequence field is set. */ boolean hasSequence(); /** * <pre> * Sequence number. * </pre> * * <code>optional uint32 sequence = 4;</code> * @return The sequence. */ int getSequence(); /** * <pre> * Value of connected output, if known * </pre> * * <code>optional int64 value = 5;</code> * @return Whether the value field is set. */ boolean hasValue(); /** * <pre> * Value of connected output, if known * </pre> * * <code>optional int64 value = 5;</code> * @return The value. */ long getValue(); /** * <pre> * script witness * </pre> * * <code>optional .wallet.ScriptWitness witness = 6;</code> * @return Whether the witness field is set. */ boolean hasWitness(); /** * <pre> * script witness * </pre> * * <code>optional .wallet.ScriptWitness witness = 6;</code> * @return The witness. */ org.bitcoinj.wallet.Protos.ScriptWitness getWitness(); } /** * Protobuf type {@code wallet.TransactionInput} */ public static final class TransactionInput extends com.google.protobuf.GeneratedMessageLite< TransactionInput, TransactionInput.Builder> implements // @@protoc_insertion_point(message_implements:wallet.TransactionInput) TransactionInputOrBuilder { private TransactionInput() { transactionOutPointHash_ = com.google.protobuf.ByteString.EMPTY; scriptBytes_ = com.google.protobuf.ByteString.EMPTY; } private int bitField0_; public static final int TRANSACTION_OUT_POINT_HASH_FIELD_NUMBER = 1; private com.google.protobuf.ByteString transactionOutPointHash_; /** * <pre> * Hash of the transaction this input is using. * </pre> * * <code>required bytes transaction_out_point_hash = 1;</code> * @return Whether the transactionOutPointHash field is set. */ @java.lang.Override public boolean hasTransactionOutPointHash() { return ((bitField0_ & 0x00000001) != 0); } /** * <pre> * Hash of the transaction this input is using. * </pre> * * <code>required bytes transaction_out_point_hash = 1;</code> * @return The transactionOutPointHash. */ @java.lang.Override public com.google.protobuf.ByteString getTransactionOutPointHash() { return transactionOutPointHash_; } /** * <pre> * Hash of the transaction this input is using. * </pre> * * <code>required bytes transaction_out_point_hash = 1;</code> * @param value The transactionOutPointHash to set. */ private void setTransactionOutPointHash(com.google.protobuf.ByteString value) { java.lang.Class<?> valueClass = value.getClass(); bitField0_ |= 0x00000001; transactionOutPointHash_ = value; } /** * <pre> * Hash of the transaction this input is using. * </pre> * * <code>required bytes transaction_out_point_hash = 1;</code> */ private void clearTransactionOutPointHash() { bitField0_ = (bitField0_ & ~0x00000001); transactionOutPointHash_ = getDefaultInstance().getTransactionOutPointHash(); } public static final int TRANSACTION_OUT_POINT_INDEX_FIELD_NUMBER = 2; private int transactionOutPointIndex_; /** * <pre> * Index of transaction output used by this input. * </pre> * * <code>required uint32 transaction_out_point_index = 2;</code> * @return Whether the transactionOutPointIndex field is set. */ @java.lang.Override public boolean hasTransactionOutPointIndex() { return ((bitField0_ & 0x00000002) != 0); } /** * <pre> * Index of transaction output used by this input. * </pre> * * <code>required uint32 transaction_out_point_index = 2;</code> * @return The transactionOutPointIndex. */ @java.lang.Override public int getTransactionOutPointIndex() { return transactionOutPointIndex_; } /** * <pre> * Index of transaction output used by this input. * </pre> * * <code>required uint32 transaction_out_point_index = 2;</code> * @param value The transactionOutPointIndex to set. */ private void setTransactionOutPointIndex(int value) { bitField0_ |= 0x00000002; transactionOutPointIndex_ = value; } /** * <pre> * Index of transaction output used by this input. * </pre> * * <code>required uint32 transaction_out_point_index = 2;</code> */ private void clearTransactionOutPointIndex() { bitField0_ = (bitField0_ & ~0x00000002); transactionOutPointIndex_ = 0; } public static final int SCRIPT_BYTES_FIELD_NUMBER = 3; private com.google.protobuf.ByteString scriptBytes_; /** * <pre> * Script that contains the signatures/pubkeys. * </pre> * * <code>required bytes script_bytes = 3;</code> * @return Whether the scriptBytes field is set. */ @java.lang.Override public boolean hasScriptBytes() { return ((bitField0_ & 0x00000004) != 0); } /** * <pre> * Script that contains the signatures/pubkeys. * </pre> * * <code>required bytes script_bytes = 3;</code> * @return The scriptBytes. */ @java.lang.Override public com.google.protobuf.ByteString getScriptBytes() { return scriptBytes_; } /** * <pre> * Script that contains the signatures/pubkeys. * </pre> * * <code>required bytes script_bytes = 3;</code> * @param value The scriptBytes to set. */ private void setScriptBytes(com.google.protobuf.ByteString value) { java.lang.Class<?> valueClass = value.getClass(); bitField0_ |= 0x00000004; scriptBytes_ = value; } /** * <pre> * Script that contains the signatures/pubkeys. * </pre> * * <code>required bytes script_bytes = 3;</code> */ private void clearScriptBytes() { bitField0_ = (bitField0_ & ~0x00000004); scriptBytes_ = getDefaultInstance().getScriptBytes(); } public static final int SEQUENCE_FIELD_NUMBER = 4; private int sequence_; /** * <pre> * Sequence number. * </pre> * * <code>optional uint32 sequence = 4;</code> * @return Whether the sequence field is set. */ @java.lang.Override public boolean hasSequence() { return ((bitField0_ & 0x00000008) != 0); } /** * <pre> * Sequence number. * </pre> * * <code>optional uint32 sequence = 4;</code> * @return The sequence. */ @java.lang.Override public int getSequence() { return sequence_; } /** * <pre> * Sequence number. * </pre> * * <code>optional uint32 sequence = 4;</code> * @param value The sequence to set. */ private void setSequence(int value) { bitField0_ |= 0x00000008; sequence_ = value; } /** * <pre> * Sequence number. * </pre> * * <code>optional uint32 sequence = 4;</code> */ private void clearSequence() { bitField0_ = (bitField0_ & ~0x00000008); sequence_ = 0; } public static final int VALUE_FIELD_NUMBER = 5; private long value_; /** * <pre> * Value of connected output, if known * </pre> * * <code>optional int64 value = 5;</code> * @return Whether the value field is set. */ @java.lang.Override public boolean hasValue() { return ((bitField0_ & 0x00000010) != 0); } /** * <pre> * Value of connected output, if known * </pre> * * <code>optional int64 value = 5;</code> * @return The value. */ @java.lang.Override public long getValue() { return value_; } /** * <pre> * Value of connected output, if known * </pre> * * <code>optional int64 value = 5;</code> * @param value The value to set. */ private void setValue(long value) { bitField0_ |= 0x00000010; value_ = value; } /** * <pre> * Value of connected output, if known * </pre> * * <code>optional int64 value = 5;</code> */ private void clearValue() { bitField0_ = (bitField0_ & ~0x00000010); value_ = 0L; } public static final int WITNESS_FIELD_NUMBER = 6; private org.bitcoinj.wallet.Protos.ScriptWitness witness_; /** * <pre> * script witness * </pre> * * <code>optional .wallet.ScriptWitness witness = 6;</code> */ @java.lang.Override public boolean hasWitness() { return ((bitField0_ & 0x00000020) != 0); } /** * <pre> * script witness * </pre> * * <code>optional .wallet.ScriptWitness witness = 6;</code> */ @java.lang.Override public org.bitcoinj.wallet.Protos.ScriptWitness getWitness() { return witness_ == null ? org.bitcoinj.wallet.Protos.ScriptWitness.getDefaultInstance() : witness_; } /** * <pre> * script witness * </pre> * * <code>optional .wallet.ScriptWitness witness = 6;</code> */ private void setWitness(org.bitcoinj.wallet.Protos.ScriptWitness value) { value.getClass(); witness_ = value; bitField0_ |= 0x00000020; } /** * <pre> * script witness * </pre> * * <code>optional .wallet.ScriptWitness witness = 6;</code> */ @java.lang.SuppressWarnings({"ReferenceEquality"}) private void mergeWitness(org.bitcoinj.wallet.Protos.ScriptWitness value) { value.getClass(); if (witness_ != null && witness_ != org.bitcoinj.wallet.Protos.ScriptWitness.getDefaultInstance()) { witness_ = org.bitcoinj.wallet.Protos.ScriptWitness.newBuilder(witness_).mergeFrom(value).buildPartial(); } else { witness_ = value; } bitField0_ |= 0x00000020; } /** * <pre> * script witness * </pre> * * <code>optional .wallet.ScriptWitness witness = 6;</code> */ private void clearWitness() { witness_ = null; bitField0_ = (bitField0_ & ~0x00000020); } public static org.bitcoinj.wallet.Protos.TransactionInput parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return com.google.protobuf.GeneratedMessageLite.parseFrom( DEFAULT_INSTANCE, data); } public static org.bitcoinj.wallet.Protos.TransactionInput parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return com.google.protobuf.GeneratedMessageLite.parseFrom( DEFAULT_INSTANCE, data, extensionRegistry); } public static org.bitcoinj.wallet.Protos.TransactionInput parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return com.google.protobuf.GeneratedMessageLite.parseFrom( DEFAULT_INSTANCE, data); } public static org.bitcoinj.wallet.Protos.TransactionInput parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return com.google.protobuf.GeneratedMessageLite.parseFrom( DEFAULT_INSTANCE, data, extensionRegistry); } public static org.bitcoinj.wallet.Protos.TransactionInput parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return com.google.protobuf.GeneratedMessageLite.parseFrom( DEFAULT_INSTANCE, data); } public static org.bitcoinj.wallet.Protos.TransactionInput parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return com.google.protobuf.GeneratedMessageLite.parseFrom( DEFAULT_INSTANCE, data, extensionRegistry); } public static org.bitcoinj.wallet.Protos.TransactionInput parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageLite.parseFrom( DEFAULT_INSTANCE, input); } public static org.bitcoinj.wallet.Protos.TransactionInput parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageLite.parseFrom( DEFAULT_INSTANCE, input, extensionRegistry); } public static org.bitcoinj.wallet.Protos.TransactionInput parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return parseDelimitedFrom(DEFAULT_INSTANCE, input); } public static org.bitcoinj.wallet.Protos.TransactionInput parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return parseDelimitedFrom(DEFAULT_INSTANCE, input, extensionRegistry); } public static org.bitcoinj.wallet.Protos.TransactionInput parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageLite.parseFrom( DEFAULT_INSTANCE, input); } public static org.bitcoinj.wallet.Protos.TransactionInput parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageLite.parseFrom( DEFAULT_INSTANCE, input, extensionRegistry); } public static Builder newBuilder() { return (Builder) DEFAULT_INSTANCE.createBuilder(); } public static Builder newBuilder(org.bitcoinj.wallet.Protos.TransactionInput prototype) { return (Builder) DEFAULT_INSTANCE.createBuilder(prototype); } /** * Protobuf type {@code wallet.TransactionInput} */ public static final class Builder extends com.google.protobuf.GeneratedMessageLite.Builder< org.bitcoinj.wallet.Protos.TransactionInput, Builder> implements // @@protoc_insertion_point(builder_implements:wallet.TransactionInput) org.bitcoinj.wallet.Protos.TransactionInputOrBuilder { // Construct using org.bitcoinj.wallet.Protos.TransactionInput.newBuilder() private Builder() { super(DEFAULT_INSTANCE); } /** * <pre> * Hash of the transaction this input is using. * </pre> * * <code>required bytes transaction_out_point_hash = 1;</code> * @return Whether the transactionOutPointHash field is set. */ @java.lang.Override public boolean hasTransactionOutPointHash() { return instance.hasTransactionOutPointHash(); } /** * <pre> * Hash of the transaction this input is using. * </pre> * * <code>required bytes transaction_out_point_hash = 1;</code> * @return The transactionOutPointHash. */ @java.lang.Override public com.google.protobuf.ByteString getTransactionOutPointHash() { return instance.getTransactionOutPointHash(); } /** * <pre> * Hash of the transaction this input is using. * </pre> * * <code>required bytes transaction_out_point_hash = 1;</code> * @param value The transactionOutPointHash to set. * @return This builder for chaining. */ public Builder setTransactionOutPointHash(com.google.protobuf.ByteString value) { copyOnWrite(); instance.setTransactionOutPointHash(value); return this; } /** * <pre> * Hash of the transaction this input is using. * </pre> * * <code>required bytes transaction_out_point_hash = 1;</code> * @return This builder for chaining. */ public Builder clearTransactionOutPointHash() { copyOnWrite(); instance.clearTransactionOutPointHash(); return this; } /** * <pre> * Index of transaction output used by this input. * </pre> * * <code>required uint32 transaction_out_point_index = 2;</code> * @return Whether the transactionOutPointIndex field is set. */ @java.lang.Override public boolean hasTransactionOutPointIndex() { return instance.hasTransactionOutPointIndex(); } /** * <pre> * Index of transaction output used by this input. * </pre> * * <code>required uint32 transaction_out_point_index = 2;</code> * @return The transactionOutPointIndex. */ @java.lang.Override public int getTransactionOutPointIndex() { return instance.getTransactionOutPointIndex(); } /** * <pre> * Index of transaction output used by this input. * </pre> * * <code>required uint32 transaction_out_point_index = 2;</code> * @param value The transactionOutPointIndex to set. * @return This builder for chaining. */ public Builder setTransactionOutPointIndex(int value) { copyOnWrite(); instance.setTransactionOutPointIndex(value); return this; } /** * <pre> * Index of transaction output used by this input. * </pre> * * <code>required uint32 transaction_out_point_index = 2;</code> * @return This builder for chaining. */ public Builder clearTransactionOutPointIndex() { copyOnWrite(); instance.clearTransactionOutPointIndex(); return this; } /** * <pre> * Script that contains the signatures/pubkeys. * </pre> * * <code>required bytes script_bytes = 3;</code> * @return Whether the scriptBytes field is set. */ @java.lang.Override public boolean hasScriptBytes() { return instance.hasScriptBytes(); } /** * <pre> * Script that contains the signatures/pubkeys. * </pre> * * <code>required bytes script_bytes = 3;</code> * @return The scriptBytes. */ @java.lang.Override public com.google.protobuf.ByteString getScriptBytes() { return instance.getScriptBytes(); } /** * <pre> * Script that contains the signatures/pubkeys. * </pre> * * <code>required bytes script_bytes = 3;</code> * @param value The scriptBytes to set. * @return This builder for chaining. */ public Builder setScriptBytes(com.google.protobuf.ByteString value) { copyOnWrite(); instance.setScriptBytes(value); return this; } /** * <pre> * Script that contains the signatures/pubkeys. * </pre> * * <code>required bytes script_bytes = 3;</code> * @return This builder for chaining. */ public Builder clearScriptBytes() { copyOnWrite(); instance.clearScriptBytes(); return this; } /** * <pre> * Sequence number. * </pre> * * <code>optional uint32 sequence = 4;</code> * @return Whether the sequence field is set. */ @java.lang.Override public boolean hasSequence() { return instance.hasSequence(); } /** * <pre> * Sequence number. * </pre> * * <code>optional uint32 sequence = 4;</code> * @return The sequence. */ @java.lang.Override public int getSequence() { return instance.getSequence(); } /** * <pre> * Sequence number. * </pre> * * <code>optional uint32 sequence = 4;</code> * @param value The sequence to set. * @return This builder for chaining. */ public Builder setSequence(int value) { copyOnWrite(); instance.setSequence(value); return this; } /** * <pre> * Sequence number. * </pre> * * <code>optional uint32 sequence = 4;</code> * @return This builder for chaining. */ public Builder clearSequence() { copyOnWrite(); instance.clearSequence(); return this; } /** * <pre> * Value of connected output, if known * </pre> * * <code>optional int64 value = 5;</code> * @return Whether the value field is set. */ @java.lang.Override public boolean hasValue() { return instance.hasValue(); } /** * <pre> * Value of connected output, if known * </pre> * * <code>optional int64 value = 5;</code> * @return The value. */ @java.lang.Override public long getValue() { return instance.getValue(); } /** * <pre> * Value of connected output, if known * </pre> * * <code>optional int64 value = 5;</code> * @param value The value to set. * @return This builder for chaining. */ public Builder setValue(long value) { copyOnWrite(); instance.setValue(value); return this; } /** * <pre> * Value of connected output, if known * </pre> * * <code>optional int64 value = 5;</code> * @return This builder for chaining. */ public Builder clearValue() { copyOnWrite(); instance.clearValue(); return this; } /** * <pre> * script witness * </pre> * * <code>optional .wallet.ScriptWitness witness = 6;</code> */ @java.lang.Override public boolean hasWitness() { return instance.hasWitness(); } /** * <pre> * script witness * </pre> * * <code>optional .wallet.ScriptWitness witness = 6;</code> */ @java.lang.Override public org.bitcoinj.wallet.Protos.ScriptWitness getWitness() { return instance.getWitness(); } /** * <pre> * script witness * </pre> * * <code>optional .wallet.ScriptWitness witness = 6;</code> */ public Builder setWitness(org.bitcoinj.wallet.Protos.ScriptWitness value) { copyOnWrite(); instance.setWitness(value); return this; } /** * <pre> * script witness * </pre> * * <code>optional .wallet.ScriptWitness witness = 6;</code> */ public Builder setWitness( org.bitcoinj.wallet.Protos.ScriptWitness.Builder builderForValue) { copyOnWrite(); instance.setWitness(builderForValue.build()); return this; } /** * <pre> * script witness * </pre> * * <code>optional .wallet.ScriptWitness witness = 6;</code> */ public Builder mergeWitness(org.bitcoinj.wallet.Protos.ScriptWitness value) { copyOnWrite(); instance.mergeWitness(value); return this; } /** * <pre> * script witness * </pre> * * <code>optional .wallet.ScriptWitness witness = 6;</code> */ public Builder clearWitness() { copyOnWrite(); instance.clearWitness(); return this; } // @@protoc_insertion_point(builder_scope:wallet.TransactionInput) } private byte memoizedIsInitialized = 2; @java.lang.Override @java.lang.SuppressWarnings({"unchecked", "fallthrough"}) protected final java.lang.Object dynamicMethod( com.google.protobuf.GeneratedMessageLite.MethodToInvoke method, java.lang.Object arg0, java.lang.Object arg1) { switch (method) { case NEW_MUTABLE_INSTANCE: { return new org.bitcoinj.wallet.Protos.TransactionInput(); } case NEW_BUILDER: { return new Builder(); } case BUILD_MESSAGE_INFO: { java.lang.Object[] objects = new java.lang.Object[] { "bitField0_", "transactionOutPointHash_", "transactionOutPointIndex_", "scriptBytes_", "sequence_", "value_", "witness_", }; java.lang.String info = "\u0001\u0006\u0000\u0001\u0001\u0006\u0006\u0000\u0000\u0003\u0001\u150a\u0000\u0002" + "\u150b\u0001\u0003\u150a\u0002\u0004\u100b\u0003\u0005\u1002\u0004\u0006\u1009\u0005" + ""; return newMessageInfo(DEFAULT_INSTANCE, info, objects); } // fall through case GET_DEFAULT_INSTANCE: { return DEFAULT_INSTANCE; } case GET_PARSER: { com.google.protobuf.Parser<org.bitcoinj.wallet.Protos.TransactionInput> parser = PARSER; if (parser == null) { synchronized (org.bitcoinj.wallet.Protos.TransactionInput.class) { parser = PARSER; if (parser == null) { parser = new DefaultInstanceBasedParser<org.bitcoinj.wallet.Protos.TransactionInput>( DEFAULT_INSTANCE); PARSER = parser; } } } return parser; } case GET_MEMOIZED_IS_INITIALIZED: { return memoizedIsInitialized; } case SET_MEMOIZED_IS_INITIALIZED: { memoizedIsInitialized = (byte) (arg0 == null ? 0 : 1); return null; } } throw new UnsupportedOperationException(); } // @@protoc_insertion_point(class_scope:wallet.TransactionInput) private static final org.bitcoinj.wallet.Protos.TransactionInput DEFAULT_INSTANCE; static { TransactionInput defaultInstance = new TransactionInput(); // New instances are implicitly immutable so no need to make // immutable. DEFAULT_INSTANCE = defaultInstance; com.google.protobuf.GeneratedMessageLite.registerDefaultInstance( TransactionInput.class, defaultInstance); } public static org.bitcoinj.wallet.Protos.TransactionInput getDefaultInstance() { return DEFAULT_INSTANCE; } private static volatile com.google.protobuf.Parser<TransactionInput> PARSER; public static com.google.protobuf.Parser<TransactionInput> parser() { return DEFAULT_INSTANCE.getParserForType(); } } public interface TransactionOutputOrBuilder extends // @@protoc_insertion_point(interface_extends:wallet.TransactionOutput) com.google.protobuf.MessageLiteOrBuilder { /** * <code>required int64 value = 1;</code> * @return Whether the value field is set. */ boolean hasValue(); /** * <code>required int64 value = 1;</code> * @return The value. */ long getValue(); /** * <pre> * script of transaction output * </pre> * * <code>required bytes script_bytes = 2;</code> * @return Whether the scriptBytes field is set. */ boolean hasScriptBytes(); /** * <pre> * script of transaction output * </pre> * * <code>required bytes script_bytes = 2;</code> * @return The scriptBytes. */ com.google.protobuf.ByteString getScriptBytes(); /** * <pre> * If spent, the hash of the transaction doing the spend. * </pre> * * <code>optional bytes spent_by_transaction_hash = 3;</code> * @return Whether the spentByTransactionHash field is set. */ boolean hasSpentByTransactionHash(); /** * <pre> * If spent, the hash of the transaction doing the spend. * </pre> * * <code>optional bytes spent_by_transaction_hash = 3;</code> * @return The spentByTransactionHash. */ com.google.protobuf.ByteString getSpentByTransactionHash(); /** * <pre> * If spent, the index of the transaction input of the transaction doing the spend. * </pre> * * <code>optional int32 spent_by_transaction_index = 4;</code> * @return Whether the spentByTransactionIndex field is set. */ boolean hasSpentByTransactionIndex(); /** * <pre> * If spent, the index of the transaction input of the transaction doing the spend. * </pre> * * <code>optional int32 spent_by_transaction_index = 4;</code> * @return The spentByTransactionIndex. */ int getSpentByTransactionIndex(); } /** * Protobuf type {@code wallet.TransactionOutput} */ public static final class TransactionOutput extends com.google.protobuf.GeneratedMessageLite< TransactionOutput, TransactionOutput.Builder> implements // @@protoc_insertion_point(message_implements:wallet.TransactionOutput) TransactionOutputOrBuilder { private TransactionOutput() { scriptBytes_ = com.google.protobuf.ByteString.EMPTY; spentByTransactionHash_ = com.google.protobuf.ByteString.EMPTY; } private int bitField0_; public static final int VALUE_FIELD_NUMBER = 1; private long value_; /** * <code>required int64 value = 1;</code> * @return Whether the value field is set. */ @java.lang.Override public boolean hasValue() { return ((bitField0_ & 0x00000001) != 0); } /** * <code>required int64 value = 1;</code> * @return The value. */ @java.lang.Override public long getValue() { return value_; } /** * <code>required int64 value = 1;</code> * @param value The value to set. */ private void setValue(long value) { bitField0_ |= 0x00000001; value_ = value; } /** * <code>required int64 value = 1;</code> */ private void clearValue() { bitField0_ = (bitField0_ & ~0x00000001); value_ = 0L; } public static final int SCRIPT_BYTES_FIELD_NUMBER = 2; private com.google.protobuf.ByteString scriptBytes_; /** * <pre> * script of transaction output * </pre> * * <code>required bytes script_bytes = 2;</code> * @return Whether the scriptBytes field is set. */ @java.lang.Override public boolean hasScriptBytes() { return ((bitField0_ & 0x00000002) != 0); } /** * <pre> * script of transaction output * </pre> * * <code>required bytes script_bytes = 2;</code> * @return The scriptBytes. */ @java.lang.Override public com.google.protobuf.ByteString getScriptBytes() { return scriptBytes_; } /** * <pre> * script of transaction output * </pre> * * <code>required bytes script_bytes = 2;</code> * @param value The scriptBytes to set. */ private void setScriptBytes(com.google.protobuf.ByteString value) { java.lang.Class<?> valueClass = value.getClass(); bitField0_ |= 0x00000002; scriptBytes_ = value; } /** * <pre> * script of transaction output * </pre> * * <code>required bytes script_bytes = 2;</code> */ private void clearScriptBytes() { bitField0_ = (bitField0_ & ~0x00000002); scriptBytes_ = getDefaultInstance().getScriptBytes(); } public static final int SPENT_BY_TRANSACTION_HASH_FIELD_NUMBER = 3; private com.google.protobuf.ByteString spentByTransactionHash_; /** * <pre> * If spent, the hash of the transaction doing the spend. * </pre> * * <code>optional bytes spent_by_transaction_hash = 3;</code> * @return Whether the spentByTransactionHash field is set. */ @java.lang.Override public boolean hasSpentByTransactionHash() { return ((bitField0_ & 0x00000004) != 0); } /** * <pre> * If spent, the hash of the transaction doing the spend. * </pre> * * <code>optional bytes spent_by_transaction_hash = 3;</code> * @return The spentByTransactionHash. */ @java.lang.Override public com.google.protobuf.ByteString getSpentByTransactionHash() { return spentByTransactionHash_; } /** * <pre> * If spent, the hash of the transaction doing the spend. * </pre> * * <code>optional bytes spent_by_transaction_hash = 3;</code> * @param value The spentByTransactionHash to set. */ private void setSpentByTransactionHash(com.google.protobuf.ByteString value) { java.lang.Class<?> valueClass = value.getClass(); bitField0_ |= 0x00000004; spentByTransactionHash_ = value; } /** * <pre> * If spent, the hash of the transaction doing the spend. * </pre> * * <code>optional bytes spent_by_transaction_hash = 3;</code> */ private void clearSpentByTransactionHash() { bitField0_ = (bitField0_ & ~0x00000004); spentByTransactionHash_ = getDefaultInstance().getSpentByTransactionHash(); } public static final int SPENT_BY_TRANSACTION_INDEX_FIELD_NUMBER = 4; private int spentByTransactionIndex_; /** * <pre> * If spent, the index of the transaction input of the transaction doing the spend. * </pre> * * <code>optional int32 spent_by_transaction_index = 4;</code> * @return Whether the spentByTransactionIndex field is set. */ @java.lang.Override public boolean hasSpentByTransactionIndex() { return ((bitField0_ & 0x00000008) != 0); } /** * <pre> * If spent, the index of the transaction input of the transaction doing the spend. * </pre> * * <code>optional int32 spent_by_transaction_index = 4;</code> * @return The spentByTransactionIndex. */ @java.lang.Override public int getSpentByTransactionIndex() { return spentByTransactionIndex_; } /** * <pre> * If spent, the index of the transaction input of the transaction doing the spend. * </pre> * * <code>optional int32 spent_by_transaction_index = 4;</code> * @param value The spentByTransactionIndex to set. */ private void setSpentByTransactionIndex(int value) { bitField0_ |= 0x00000008; spentByTransactionIndex_ = value; } /** * <pre> * If spent, the index of the transaction input of the transaction doing the spend. * </pre> * * <code>optional int32 spent_by_transaction_index = 4;</code> */ private void clearSpentByTransactionIndex() { bitField0_ = (bitField0_ & ~0x00000008); spentByTransactionIndex_ = 0; } public static org.bitcoinj.wallet.Protos.TransactionOutput parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return com.google.protobuf.GeneratedMessageLite.parseFrom( DEFAULT_INSTANCE, data); } public static org.bitcoinj.wallet.Protos.TransactionOutput parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return com.google.protobuf.GeneratedMessageLite.parseFrom( DEFAULT_INSTANCE, data, extensionRegistry); } public static org.bitcoinj.wallet.Protos.TransactionOutput parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return com.google.protobuf.GeneratedMessageLite.parseFrom( DEFAULT_INSTANCE, data); } public static org.bitcoinj.wallet.Protos.TransactionOutput parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return com.google.protobuf.GeneratedMessageLite.parseFrom( DEFAULT_INSTANCE, data, extensionRegistry); } public static org.bitcoinj.wallet.Protos.TransactionOutput parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return com.google.protobuf.GeneratedMessageLite.parseFrom( DEFAULT_INSTANCE, data); } public static org.bitcoinj.wallet.Protos.TransactionOutput parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return com.google.protobuf.GeneratedMessageLite.parseFrom( DEFAULT_INSTANCE, data, extensionRegistry); } public static org.bitcoinj.wallet.Protos.TransactionOutput parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageLite.parseFrom( DEFAULT_INSTANCE, input); } public static org.bitcoinj.wallet.Protos.TransactionOutput parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageLite.parseFrom( DEFAULT_INSTANCE, input, extensionRegistry); } public static org.bitcoinj.wallet.Protos.TransactionOutput parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return parseDelimitedFrom(DEFAULT_INSTANCE, input); } public static org.bitcoinj.wallet.Protos.TransactionOutput parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return parseDelimitedFrom(DEFAULT_INSTANCE, input, extensionRegistry); } public static org.bitcoinj.wallet.Protos.TransactionOutput parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageLite.parseFrom( DEFAULT_INSTANCE, input); } public static org.bitcoinj.wallet.Protos.TransactionOutput parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageLite.parseFrom( DEFAULT_INSTANCE, input, extensionRegistry); } public static Builder newBuilder() { return (Builder) DEFAULT_INSTANCE.createBuilder(); } public static Builder newBuilder(org.bitcoinj.wallet.Protos.TransactionOutput prototype) { return (Builder) DEFAULT_INSTANCE.createBuilder(prototype); } /** * Protobuf type {@code wallet.TransactionOutput} */ public static final class Builder extends com.google.protobuf.GeneratedMessageLite.Builder< org.bitcoinj.wallet.Protos.TransactionOutput, Builder> implements // @@protoc_insertion_point(builder_implements:wallet.TransactionOutput) org.bitcoinj.wallet.Protos.TransactionOutputOrBuilder { // Construct using org.bitcoinj.wallet.Protos.TransactionOutput.newBuilder() private Builder() { super(DEFAULT_INSTANCE); } /** * <code>required int64 value = 1;</code> * @return Whether the value field is set. */ @java.lang.Override public boolean hasValue() { return instance.hasValue(); } /** * <code>required int64 value = 1;</code> * @return The value. */ @java.lang.Override public long getValue() { return instance.getValue(); } /** * <code>required int64 value = 1;</code> * @param value The value to set. * @return This builder for chaining. */ public Builder setValue(long value) { copyOnWrite(); instance.setValue(value); return this; } /** * <code>required int64 value = 1;</code> * @return This builder for chaining. */ public Builder clearValue() { copyOnWrite(); instance.clearValue(); return this; } /** * <pre> * script of transaction output * </pre> * * <code>required bytes script_bytes = 2;</code> * @return Whether the scriptBytes field is set. */ @java.lang.Override public boolean hasScriptBytes() { return instance.hasScriptBytes(); } /** * <pre> * script of transaction output * </pre> * * <code>required bytes script_bytes = 2;</code> * @return The scriptBytes. */ @java.lang.Override public com.google.protobuf.ByteString getScriptBytes() { return instance.getScriptBytes(); } /** * <pre> * script of transaction output * </pre> * * <code>required bytes script_bytes = 2;</code> * @param value The scriptBytes to set. * @return This builder for chaining. */ public Builder setScriptBytes(com.google.protobuf.ByteString value) { copyOnWrite(); instance.setScriptBytes(value); return this; } /** * <pre> * script of transaction output * </pre> * * <code>required bytes script_bytes = 2;</code> * @return This builder for chaining. */ public Builder clearScriptBytes() { copyOnWrite(); instance.clearScriptBytes(); return this; } /** * <pre> * If spent, the hash of the transaction doing the spend. * </pre> * * <code>optional bytes spent_by_transaction_hash = 3;</code> * @return Whether the spentByTransactionHash field is set. */ @java.lang.Override public boolean hasSpentByTransactionHash() { return instance.hasSpentByTransactionHash(); } /** * <pre> * If spent, the hash of the transaction doing the spend. * </pre> * * <code>optional bytes spent_by_transaction_hash = 3;</code> * @return The spentByTransactionHash. */ @java.lang.Override public com.google.protobuf.ByteString getSpentByTransactionHash() { return instance.getSpentByTransactionHash(); } /** * <pre> * If spent, the hash of the transaction doing the spend. * </pre> * * <code>optional bytes spent_by_transaction_hash = 3;</code> * @param value The spentByTransactionHash to set. * @return This builder for chaining. */ public Builder setSpentByTransactionHash(com.google.protobuf.ByteString value) { copyOnWrite(); instance.setSpentByTransactionHash(value); return this; } /** * <pre> * If spent, the hash of the transaction doing the spend. * </pre> * * <code>optional bytes spent_by_transaction_hash = 3;</code> * @return This builder for chaining. */ public Builder clearSpentByTransactionHash() { copyOnWrite(); instance.clearSpentByTransactionHash(); return this; } /** * <pre> * If spent, the index of the transaction input of the transaction doing the spend. * </pre> * * <code>optional int32 spent_by_transaction_index = 4;</code> * @return Whether the spentByTransactionIndex field is set. */ @java.lang.Override public boolean hasSpentByTransactionIndex() { return instance.hasSpentByTransactionIndex(); } /** * <pre> * If spent, the index of the transaction input of the transaction doing the spend. * </pre> * * <code>optional int32 spent_by_transaction_index = 4;</code> * @return The spentByTransactionIndex. */ @java.lang.Override public int getSpentByTransactionIndex() { return instance.getSpentByTransactionIndex(); } /** * <pre> * If spent, the index of the transaction input of the transaction doing the spend. * </pre> * * <code>optional int32 spent_by_transaction_index = 4;</code> * @param value The spentByTransactionIndex to set. * @return This builder for chaining. */ public Builder setSpentByTransactionIndex(int value) { copyOnWrite(); instance.setSpentByTransactionIndex(value); return this; } /** * <pre> * If spent, the index of the transaction input of the transaction doing the spend. * </pre> * * <code>optional int32 spent_by_transaction_index = 4;</code> * @return This builder for chaining. */ public Builder clearSpentByTransactionIndex() { copyOnWrite(); instance.clearSpentByTransactionIndex(); return this; } // @@protoc_insertion_point(builder_scope:wallet.TransactionOutput) } private byte memoizedIsInitialized = 2; @java.lang.Override @java.lang.SuppressWarnings({"unchecked", "fallthrough"}) protected final java.lang.Object dynamicMethod( com.google.protobuf.GeneratedMessageLite.MethodToInvoke method, java.lang.Object arg0, java.lang.Object arg1) { switch (method) { case NEW_MUTABLE_INSTANCE: { return new org.bitcoinj.wallet.Protos.TransactionOutput(); } case NEW_BUILDER: { return new Builder(); } case BUILD_MESSAGE_INFO: { java.lang.Object[] objects = new java.lang.Object[] { "bitField0_", "value_", "scriptBytes_", "spentByTransactionHash_", "spentByTransactionIndex_", }; java.lang.String info = "\u0001\u0004\u0000\u0001\u0001\u0004\u0004\u0000\u0000\u0002\u0001\u1502\u0000\u0002" + "\u150a\u0001\u0003\u100a\u0002\u0004\u1004\u0003"; return newMessageInfo(DEFAULT_INSTANCE, info, objects); } // fall through case GET_DEFAULT_INSTANCE: { return DEFAULT_INSTANCE; } case GET_PARSER: { com.google.protobuf.Parser<org.bitcoinj.wallet.Protos.TransactionOutput> parser = PARSER; if (parser == null) { synchronized (org.bitcoinj.wallet.Protos.TransactionOutput.class) { parser = PARSER; if (parser == null) { parser = new DefaultInstanceBasedParser<org.bitcoinj.wallet.Protos.TransactionOutput>( DEFAULT_INSTANCE); PARSER = parser; } } } return parser; } case GET_MEMOIZED_IS_INITIALIZED: { return memoizedIsInitialized; } case SET_MEMOIZED_IS_INITIALIZED: { memoizedIsInitialized = (byte) (arg0 == null ? 0 : 1); return null; } } throw new UnsupportedOperationException(); } // @@protoc_insertion_point(class_scope:wallet.TransactionOutput) private static final org.bitcoinj.wallet.Protos.TransactionOutput DEFAULT_INSTANCE; static { TransactionOutput defaultInstance = new TransactionOutput(); // New instances are implicitly immutable so no need to make // immutable. DEFAULT_INSTANCE = defaultInstance; com.google.protobuf.GeneratedMessageLite.registerDefaultInstance( TransactionOutput.class, defaultInstance); } public static org.bitcoinj.wallet.Protos.TransactionOutput getDefaultInstance() { return DEFAULT_INSTANCE; } private static volatile com.google.protobuf.Parser<TransactionOutput> PARSER; public static com.google.protobuf.Parser<TransactionOutput> parser() { return DEFAULT_INSTANCE.getParserForType(); } } public interface TransactionConfidenceOrBuilder extends // @@protoc_insertion_point(interface_extends:wallet.TransactionConfidence) com.google.protobuf.MessageLiteOrBuilder { /** * <pre> * This is optional in case we add confidence types to prevent parse errors - backwards compatible. * </pre> * * <code>optional .wallet.TransactionConfidence.Type type = 1;</code> * @return Whether the type field is set. */ boolean hasType(); /** * <pre> * This is optional in case we add confidence types to prevent parse errors - backwards compatible. * </pre> * * <code>optional .wallet.TransactionConfidence.Type type = 1;</code> * @return The type. */ org.bitcoinj.wallet.Protos.TransactionConfidence.Type getType(); /** * <pre> * If type == BUILDING then this is the chain height at which the transaction was included. * </pre> * * <code>optional int32 appeared_at_height = 2;</code> * @return Whether the appearedAtHeight field is set. */ boolean hasAppearedAtHeight(); /** * <pre> * If type == BUILDING then this is the chain height at which the transaction was included. * </pre> * * <code>optional int32 appeared_at_height = 2;</code> * @return The appearedAtHeight. */ int getAppearedAtHeight(); /** * <pre> * If set, hash of the transaction that double spent this one into oblivion. A transaction can be double spent by * multiple transactions in the case of several inputs being re-spent by several transactions but we don't * bother to track them all, just the first. This only makes sense if type = DEAD. * </pre> * * <code>optional bytes overriding_transaction = 3;</code> * @return Whether the overridingTransaction field is set. */ boolean hasOverridingTransaction(); /** * <pre> * If set, hash of the transaction that double spent this one into oblivion. A transaction can be double spent by * multiple transactions in the case of several inputs being re-spent by several transactions but we don't * bother to track them all, just the first. This only makes sense if type = DEAD. * </pre> * * <code>optional bytes overriding_transaction = 3;</code> * @return The overridingTransaction. */ com.google.protobuf.ByteString getOverridingTransaction(); /** * <pre> * If type == BUILDING then this is the depth of the transaction in the blockchain. * Zero confirmations: depth = 0, one confirmation: depth = 1 etc. * </pre> * * <code>optional int32 depth = 4;</code> * @return Whether the depth field is set. */ boolean hasDepth(); /** * <pre> * If type == BUILDING then this is the depth of the transaction in the blockchain. * Zero confirmations: depth = 0, one confirmation: depth = 1 etc. * </pre> * * <code>optional int32 depth = 4;</code> * @return The depth. */ int getDepth(); /** * <code>repeated .wallet.PeerAddress broadcast_by = 6;</code> */ java.util.List<org.bitcoinj.wallet.Protos.PeerAddress> getBroadcastByList(); /** * <code>repeated .wallet.PeerAddress broadcast_by = 6;</code> */ org.bitcoinj.wallet.Protos.PeerAddress getBroadcastBy(int index); /** * <code>repeated .wallet.PeerAddress broadcast_by = 6;</code> */ int getBroadcastByCount(); /** * <pre> * Millis since epoch the transaction was last announced to us. * </pre> * * <code>optional int64 last_broadcasted_at = 8;</code> * @return Whether the lastBroadcastedAt field is set. */ boolean hasLastBroadcastedAt(); /** * <pre> * Millis since epoch the transaction was last announced to us. * </pre> * * <code>optional int64 last_broadcasted_at = 8;</code> * @return The lastBroadcastedAt. */ long getLastBroadcastedAt(); /** * <code>optional .wallet.TransactionConfidence.Source source = 7;</code> * @return Whether the source field is set. */ boolean hasSource(); /** * <code>optional .wallet.TransactionConfidence.Source source = 7;</code> * @return The source. */ org.bitcoinj.wallet.Protos.TransactionConfidence.Source getSource(); } /** * <pre> ** * A description of the confidence we have that a transaction cannot be reversed in the future. * * Parsing should be lenient, since this could change for different applications yet we should * maintain backward compatibility. * </pre> * * Protobuf type {@code wallet.TransactionConfidence} */ public static final class TransactionConfidence extends com.google.protobuf.GeneratedMessageLite< TransactionConfidence, TransactionConfidence.Builder> implements // @@protoc_insertion_point(message_implements:wallet.TransactionConfidence) TransactionConfidenceOrBuilder { private TransactionConfidence() { overridingTransaction_ = com.google.protobuf.ByteString.EMPTY; broadcastBy_ = emptyProtobufList(); } /** * Protobuf enum {@code wallet.TransactionConfidence.Type} */ public enum Type implements com.google.protobuf.Internal.EnumLite { /** * <pre> * See TransactionConfidence.java for a more thorough explanation of these types. * </pre> * * <code>UNKNOWN = 0;</code> */ UNKNOWN(0), /** * <pre> * In best chain. If and only if appeared_at_height is present. * </pre> * * <code>BUILDING = 1;</code> */ BUILDING(1), /** * <pre> * Unconfirmed and sitting in the networks memory pools, waiting to be included in the chain. * </pre> * * <code>PENDING = 2;</code> */ PENDING(2), /** * <pre> * Deprecated: equivalent to PENDING. * </pre> * * <code>NOT_IN_BEST_CHAIN = 3;</code> */ NOT_IN_BEST_CHAIN(3), /** * <pre> * Either if overriding_transaction is present or transaction is dead coinbase. * </pre> * * <code>DEAD = 4;</code> */ DEAD(4), /** * <pre> * There is another transaction spending one of this transaction inputs. * </pre> * * <code>IN_CONFLICT = 5;</code> */ IN_CONFLICT(5), ; /** * <pre> * See TransactionConfidence.java for a more thorough explanation of these types. * </pre> * * <code>UNKNOWN = 0;</code> */ public static final int UNKNOWN_VALUE = 0; /** * <pre> * In best chain. If and only if appeared_at_height is present. * </pre> * * <code>BUILDING = 1;</code> */ public static final int BUILDING_VALUE = 1; /** * <pre> * Unconfirmed and sitting in the networks memory pools, waiting to be included in the chain. * </pre> * * <code>PENDING = 2;</code> */ public static final int PENDING_VALUE = 2; /** * <pre> * Deprecated: equivalent to PENDING. * </pre> * * <code>NOT_IN_BEST_CHAIN = 3;</code> */ public static final int NOT_IN_BEST_CHAIN_VALUE = 3; /** * <pre> * Either if overriding_transaction is present or transaction is dead coinbase. * </pre> * * <code>DEAD = 4;</code> */ public static final int DEAD_VALUE = 4; /** * <pre> * There is another transaction spending one of this transaction inputs. * </pre> * * <code>IN_CONFLICT = 5;</code> */ public static final int IN_CONFLICT_VALUE = 5; @java.lang.Override public final int getNumber() { return value; } /** * @param value The number of the enum to look for. * @return The enum associated with the given number. * @deprecated Use {@link #forNumber(int)} instead. */ @java.lang.Deprecated public static Type valueOf(int value) { return forNumber(value); } public static Type forNumber(int value) { switch (value) { case 0: return UNKNOWN; case 1: return BUILDING; case 2: return PENDING; case 3: return NOT_IN_BEST_CHAIN; case 4: return DEAD; case 5: return IN_CONFLICT; default: return null; } } public static com.google.protobuf.Internal.EnumLiteMap<Type> internalGetValueMap() { return internalValueMap; } private static final com.google.protobuf.Internal.EnumLiteMap< Type> internalValueMap = new com.google.protobuf.Internal.EnumLiteMap<Type>() { @java.lang.Override public Type findValueByNumber(int number) { return Type.forNumber(number); } }; public static com.google.protobuf.Internal.EnumVerifier internalGetVerifier() { return TypeVerifier.INSTANCE; } private static final class TypeVerifier implements com.google.protobuf.Internal.EnumVerifier { static final com.google.protobuf.Internal.EnumVerifier INSTANCE = new TypeVerifier(); @java.lang.Override public boolean isInRange(int number) { return Type.forNumber(number) != null; } }; private final int value; private Type(int value) { this.value = value; } // @@protoc_insertion_point(enum_scope:wallet.TransactionConfidence.Type) } /** * <pre> * Where did we get this transaction from? Knowing the source may help us to risk analyze pending transactions. * </pre> * * Protobuf enum {@code wallet.TransactionConfidence.Source} */ public enum Source implements com.google.protobuf.Internal.EnumLite { /** * <pre> * We don't know where it came from, or this is a wallet from the future. * </pre> * * <code>SOURCE_UNKNOWN = 0;</code> */ SOURCE_UNKNOWN(0), /** * <pre> * We received it from a network broadcast. This is the normal way to get payments. * </pre> * * <code>SOURCE_NETWORK = 1;</code> */ SOURCE_NETWORK(1), /** * <pre> * We made it ourselves, so we know it should be valid. * </pre> * * <code>SOURCE_SELF = 2;</code> */ SOURCE_SELF(2), ; /** * <pre> * We don't know where it came from, or this is a wallet from the future. * </pre> * * <code>SOURCE_UNKNOWN = 0;</code> */ public static final int SOURCE_UNKNOWN_VALUE = 0; /** * <pre> * We received it from a network broadcast. This is the normal way to get payments. * </pre> * * <code>SOURCE_NETWORK = 1;</code> */ public static final int SOURCE_NETWORK_VALUE = 1; /** * <pre> * We made it ourselves, so we know it should be valid. * </pre> * * <code>SOURCE_SELF = 2;</code> */ public static final int SOURCE_SELF_VALUE = 2; @java.lang.Override public final int getNumber() { return value; } /** * @param value The number of the enum to look for. * @return The enum associated with the given number. * @deprecated Use {@link #forNumber(int)} instead. */ @java.lang.Deprecated public static Source valueOf(int value) { return forNumber(value); } public static Source forNumber(int value) { switch (value) { case 0: return SOURCE_UNKNOWN; case 1: return SOURCE_NETWORK; case 2: return SOURCE_SELF; default: return null; } } public static com.google.protobuf.Internal.EnumLiteMap<Source> internalGetValueMap() { return internalValueMap; } private static final com.google.protobuf.Internal.EnumLiteMap< Source> internalValueMap = new com.google.protobuf.Internal.EnumLiteMap<Source>() { @java.lang.Override public Source findValueByNumber(int number) { return Source.forNumber(number); } }; public static com.google.protobuf.Internal.EnumVerifier internalGetVerifier() { return SourceVerifier.INSTANCE; } private static final class SourceVerifier implements com.google.protobuf.Internal.EnumVerifier { static final com.google.protobuf.Internal.EnumVerifier INSTANCE = new SourceVerifier(); @java.lang.Override public boolean isInRange(int number) { return Source.forNumber(number) != null; } }; private final int value; private Source(int value) { this.value = value; } // @@protoc_insertion_point(enum_scope:wallet.TransactionConfidence.Source) } private int bitField0_; public static final int TYPE_FIELD_NUMBER = 1; private int type_; /** * <pre> * This is optional in case we add confidence types to prevent parse errors - backwards compatible. * </pre> * * <code>optional .wallet.TransactionConfidence.Type type = 1;</code> * @return Whether the type field is set. */ @java.lang.Override public boolean hasType() { return ((bitField0_ & 0x00000001) != 0); } /** * <pre> * This is optional in case we add confidence types to prevent parse errors - backwards compatible. * </pre> * * <code>optional .wallet.TransactionConfidence.Type type = 1;</code> * @return The type. */ @java.lang.Override public org.bitcoinj.wallet.Protos.TransactionConfidence.Type getType() { org.bitcoinj.wallet.Protos.TransactionConfidence.Type result = org.bitcoinj.wallet.Protos.TransactionConfidence.Type.forNumber(type_); return result == null ? org.bitcoinj.wallet.Protos.TransactionConfidence.Type.UNKNOWN : result; } /** * <pre> * This is optional in case we add confidence types to prevent parse errors - backwards compatible. * </pre> * * <code>optional .wallet.TransactionConfidence.Type type = 1;</code> * @param value The type to set. */ private void setType(org.bitcoinj.wallet.Protos.TransactionConfidence.Type value) { type_ = value.getNumber(); bitField0_ |= 0x00000001; } /** * <pre> * This is optional in case we add confidence types to prevent parse errors - backwards compatible. * </pre> * * <code>optional .wallet.TransactionConfidence.Type type = 1;</code> */ private void clearType() { bitField0_ = (bitField0_ & ~0x00000001); type_ = 0; } public static final int APPEARED_AT_HEIGHT_FIELD_NUMBER = 2; private int appearedAtHeight_; /** * <pre> * If type == BUILDING then this is the chain height at which the transaction was included. * </pre> * * <code>optional int32 appeared_at_height = 2;</code> * @return Whether the appearedAtHeight field is set. */ @java.lang.Override public boolean hasAppearedAtHeight() { return ((bitField0_ & 0x00000002) != 0); } /** * <pre> * If type == BUILDING then this is the chain height at which the transaction was included. * </pre> * * <code>optional int32 appeared_at_height = 2;</code> * @return The appearedAtHeight. */ @java.lang.Override public int getAppearedAtHeight() { return appearedAtHeight_; } /** * <pre> * If type == BUILDING then this is the chain height at which the transaction was included. * </pre> * * <code>optional int32 appeared_at_height = 2;</code> * @param value The appearedAtHeight to set. */ private void setAppearedAtHeight(int value) { bitField0_ |= 0x00000002; appearedAtHeight_ = value; } /** * <pre> * If type == BUILDING then this is the chain height at which the transaction was included. * </pre> * * <code>optional int32 appeared_at_height = 2;</code> */ private void clearAppearedAtHeight() { bitField0_ = (bitField0_ & ~0x00000002); appearedAtHeight_ = 0; } public static final int OVERRIDING_TRANSACTION_FIELD_NUMBER = 3; private com.google.protobuf.ByteString overridingTransaction_; /** * <pre> * If set, hash of the transaction that double spent this one into oblivion. A transaction can be double spent by * multiple transactions in the case of several inputs being re-spent by several transactions but we don't * bother to track them all, just the first. This only makes sense if type = DEAD. * </pre> * * <code>optional bytes overriding_transaction = 3;</code> * @return Whether the overridingTransaction field is set. */ @java.lang.Override public boolean hasOverridingTransaction() { return ((bitField0_ & 0x00000004) != 0); } /** * <pre> * If set, hash of the transaction that double spent this one into oblivion. A transaction can be double spent by * multiple transactions in the case of several inputs being re-spent by several transactions but we don't * bother to track them all, just the first. This only makes sense if type = DEAD. * </pre> * * <code>optional bytes overriding_transaction = 3;</code> * @return The overridingTransaction. */ @java.lang.Override public com.google.protobuf.ByteString getOverridingTransaction() { return overridingTransaction_; } /** * <pre> * If set, hash of the transaction that double spent this one into oblivion. A transaction can be double spent by * multiple transactions in the case of several inputs being re-spent by several transactions but we don't * bother to track them all, just the first. This only makes sense if type = DEAD. * </pre> * * <code>optional bytes overriding_transaction = 3;</code> * @param value The overridingTransaction to set. */ private void setOverridingTransaction(com.google.protobuf.ByteString value) { java.lang.Class<?> valueClass = value.getClass(); bitField0_ |= 0x00000004; overridingTransaction_ = value; } /** * <pre> * If set, hash of the transaction that double spent this one into oblivion. A transaction can be double spent by * multiple transactions in the case of several inputs being re-spent by several transactions but we don't * bother to track them all, just the first. This only makes sense if type = DEAD. * </pre> * * <code>optional bytes overriding_transaction = 3;</code> */ private void clearOverridingTransaction() { bitField0_ = (bitField0_ & ~0x00000004); overridingTransaction_ = getDefaultInstance().getOverridingTransaction(); } public static final int DEPTH_FIELD_NUMBER = 4; private int depth_; /** * <pre> * If type == BUILDING then this is the depth of the transaction in the blockchain. * Zero confirmations: depth = 0, one confirmation: depth = 1 etc. * </pre> * * <code>optional int32 depth = 4;</code> * @return Whether the depth field is set. */ @java.lang.Override public boolean hasDepth() { return ((bitField0_ & 0x00000008) != 0); } /** * <pre> * If type == BUILDING then this is the depth of the transaction in the blockchain. * Zero confirmations: depth = 0, one confirmation: depth = 1 etc. * </pre> * * <code>optional int32 depth = 4;</code> * @return The depth. */ @java.lang.Override public int getDepth() { return depth_; } /** * <pre> * If type == BUILDING then this is the depth of the transaction in the blockchain. * Zero confirmations: depth = 0, one confirmation: depth = 1 etc. * </pre> * * <code>optional int32 depth = 4;</code> * @param value The depth to set. */ private void setDepth(int value) { bitField0_ |= 0x00000008; depth_ = value; } /** * <pre> * If type == BUILDING then this is the depth of the transaction in the blockchain. * Zero confirmations: depth = 0, one confirmation: depth = 1 etc. * </pre> * * <code>optional int32 depth = 4;</code> */ private void clearDepth() { bitField0_ = (bitField0_ & ~0x00000008); depth_ = 0; } public static final int BROADCAST_BY_FIELD_NUMBER = 6; private com.google.protobuf.Internal.ProtobufList<org.bitcoinj.wallet.Protos.PeerAddress> broadcastBy_; /** * <code>repeated .wallet.PeerAddress broadcast_by = 6;</code> */ @java.lang.Override public java.util.List<org.bitcoinj.wallet.Protos.PeerAddress> getBroadcastByList() { return broadcastBy_; } /** * <code>repeated .wallet.PeerAddress broadcast_by = 6;</code> */ public java.util.List<? extends org.bitcoinj.wallet.Protos.PeerAddressOrBuilder> getBroadcastByOrBuilderList() { return broadcastBy_; } /** * <code>repeated .wallet.PeerAddress broadcast_by = 6;</code> */ @java.lang.Override public int getBroadcastByCount() { return broadcastBy_.size(); } /** * <code>repeated .wallet.PeerAddress broadcast_by = 6;</code> */ @java.lang.Override public org.bitcoinj.wallet.Protos.PeerAddress getBroadcastBy(int index) { return broadcastBy_.get(index); } /** * <code>repeated .wallet.PeerAddress broadcast_by = 6;</code> */ public org.bitcoinj.wallet.Protos.PeerAddressOrBuilder getBroadcastByOrBuilder( int index) { return broadcastBy_.get(index); } private void ensureBroadcastByIsMutable() { com.google.protobuf.Internal.ProtobufList<org.bitcoinj.wallet.Protos.PeerAddress> tmp = broadcastBy_; if (!tmp.isModifiable()) { broadcastBy_ = com.google.protobuf.GeneratedMessageLite.mutableCopy(tmp); } } /** * <code>repeated .wallet.PeerAddress broadcast_by = 6;</code> */ private void setBroadcastBy( int index, org.bitcoinj.wallet.Protos.PeerAddress value) { value.getClass(); ensureBroadcastByIsMutable(); broadcastBy_.set(index, value); } /** * <code>repeated .wallet.PeerAddress broadcast_by = 6;</code> */ private void addBroadcastBy(org.bitcoinj.wallet.Protos.PeerAddress value) { value.getClass(); ensureBroadcastByIsMutable(); broadcastBy_.add(value); } /** * <code>repeated .wallet.PeerAddress broadcast_by = 6;</code> */ private void addBroadcastBy( int index, org.bitcoinj.wallet.Protos.PeerAddress value) { value.getClass(); ensureBroadcastByIsMutable(); broadcastBy_.add(index, value); } /** * <code>repeated .wallet.PeerAddress broadcast_by = 6;</code> */ private void addAllBroadcastBy( java.lang.Iterable<? extends org.bitcoinj.wallet.Protos.PeerAddress> values) { ensureBroadcastByIsMutable(); com.google.protobuf.AbstractMessageLite.addAll( values, broadcastBy_); } /** * <code>repeated .wallet.PeerAddress broadcast_by = 6;</code> */ private void clearBroadcastBy() { broadcastBy_ = emptyProtobufList(); } /** * <code>repeated .wallet.PeerAddress broadcast_by = 6;</code> */ private void removeBroadcastBy(int index) { ensureBroadcastByIsMutable(); broadcastBy_.remove(index); } public static final int LAST_BROADCASTED_AT_FIELD_NUMBER = 8; private long lastBroadcastedAt_; /** * <pre> * Millis since epoch the transaction was last announced to us. * </pre> * * <code>optional int64 last_broadcasted_at = 8;</code> * @return Whether the lastBroadcastedAt field is set. */ @java.lang.Override public boolean hasLastBroadcastedAt() { return ((bitField0_ & 0x00000010) != 0); } /** * <pre> * Millis since epoch the transaction was last announced to us. * </pre> * * <code>optional int64 last_broadcasted_at = 8;</code> * @return The lastBroadcastedAt. */ @java.lang.Override public long getLastBroadcastedAt() { return lastBroadcastedAt_; } /** * <pre> * Millis since epoch the transaction was last announced to us. * </pre> * * <code>optional int64 last_broadcasted_at = 8;</code> * @param value The lastBroadcastedAt to set. */ private void setLastBroadcastedAt(long value) { bitField0_ |= 0x00000010; lastBroadcastedAt_ = value; } /** * <pre> * Millis since epoch the transaction was last announced to us. * </pre> * * <code>optional int64 last_broadcasted_at = 8;</code> */ private void clearLastBroadcastedAt() { bitField0_ = (bitField0_ & ~0x00000010); lastBroadcastedAt_ = 0L; } public static final int SOURCE_FIELD_NUMBER = 7; private int source_; /** * <code>optional .wallet.TransactionConfidence.Source source = 7;</code> * @return Whether the source field is set. */ @java.lang.Override public boolean hasSource() { return ((bitField0_ & 0x00000020) != 0); } /** * <code>optional .wallet.TransactionConfidence.Source source = 7;</code> * @return The source. */ @java.lang.Override public org.bitcoinj.wallet.Protos.TransactionConfidence.Source getSource() { org.bitcoinj.wallet.Protos.TransactionConfidence.Source result = org.bitcoinj.wallet.Protos.TransactionConfidence.Source.forNumber(source_); return result == null ? org.bitcoinj.wallet.Protos.TransactionConfidence.Source.SOURCE_UNKNOWN : result; } /** * <code>optional .wallet.TransactionConfidence.Source source = 7;</code> * @param value The source to set. */ private void setSource(org.bitcoinj.wallet.Protos.TransactionConfidence.Source value) { source_ = value.getNumber(); bitField0_ |= 0x00000020; } /** * <code>optional .wallet.TransactionConfidence.Source source = 7;</code> */ private void clearSource() { bitField0_ = (bitField0_ & ~0x00000020); source_ = 0; } public static org.bitcoinj.wallet.Protos.TransactionConfidence parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return com.google.protobuf.GeneratedMessageLite.parseFrom( DEFAULT_INSTANCE, data); } public static org.bitcoinj.wallet.Protos.TransactionConfidence parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return com.google.protobuf.GeneratedMessageLite.parseFrom( DEFAULT_INSTANCE, data, extensionRegistry); } public static org.bitcoinj.wallet.Protos.TransactionConfidence parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return com.google.protobuf.GeneratedMessageLite.parseFrom( DEFAULT_INSTANCE, data); } public static org.bitcoinj.wallet.Protos.TransactionConfidence parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return com.google.protobuf.GeneratedMessageLite.parseFrom( DEFAULT_INSTANCE, data, extensionRegistry); } public static org.bitcoinj.wallet.Protos.TransactionConfidence parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return com.google.protobuf.GeneratedMessageLite.parseFrom( DEFAULT_INSTANCE, data); } public static org.bitcoinj.wallet.Protos.TransactionConfidence parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return com.google.protobuf.GeneratedMessageLite.parseFrom( DEFAULT_INSTANCE, data, extensionRegistry); } public static org.bitcoinj.wallet.Protos.TransactionConfidence parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageLite.parseFrom( DEFAULT_INSTANCE, input); } public static org.bitcoinj.wallet.Protos.TransactionConfidence parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageLite.parseFrom( DEFAULT_INSTANCE, input, extensionRegistry); } public static org.bitcoinj.wallet.Protos.TransactionConfidence parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return parseDelimitedFrom(DEFAULT_INSTANCE, input); } public static org.bitcoinj.wallet.Protos.TransactionConfidence parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return parseDelimitedFrom(DEFAULT_INSTANCE, input, extensionRegistry); } public static org.bitcoinj.wallet.Protos.TransactionConfidence parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageLite.parseFrom( DEFAULT_INSTANCE, input); } public static org.bitcoinj.wallet.Protos.TransactionConfidence parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageLite.parseFrom( DEFAULT_INSTANCE, input, extensionRegistry); } public static Builder newBuilder() { return (Builder) DEFAULT_INSTANCE.createBuilder(); } public static Builder newBuilder(org.bitcoinj.wallet.Protos.TransactionConfidence prototype) { return (Builder) DEFAULT_INSTANCE.createBuilder(prototype); } /** * <pre> ** * A description of the confidence we have that a transaction cannot be reversed in the future. * * Parsing should be lenient, since this could change for different applications yet we should * maintain backward compatibility. * </pre> * * Protobuf type {@code wallet.TransactionConfidence} */ public static final class Builder extends com.google.protobuf.GeneratedMessageLite.Builder< org.bitcoinj.wallet.Protos.TransactionConfidence, Builder> implements // @@protoc_insertion_point(builder_implements:wallet.TransactionConfidence) org.bitcoinj.wallet.Protos.TransactionConfidenceOrBuilder { // Construct using org.bitcoinj.wallet.Protos.TransactionConfidence.newBuilder() private Builder() { super(DEFAULT_INSTANCE); } /** * <pre> * This is optional in case we add confidence types to prevent parse errors - backwards compatible. * </pre> * * <code>optional .wallet.TransactionConfidence.Type type = 1;</code> * @return Whether the type field is set. */ @java.lang.Override public boolean hasType() { return instance.hasType(); } /** * <pre> * This is optional in case we add confidence types to prevent parse errors - backwards compatible. * </pre> * * <code>optional .wallet.TransactionConfidence.Type type = 1;</code> * @return The type. */ @java.lang.Override public org.bitcoinj.wallet.Protos.TransactionConfidence.Type getType() { return instance.getType(); } /** * <pre> * This is optional in case we add confidence types to prevent parse errors - backwards compatible. * </pre> * * <code>optional .wallet.TransactionConfidence.Type type = 1;</code> * @param value The enum numeric value on the wire for type to set. * @return This builder for chaining. */ public Builder setType(org.bitcoinj.wallet.Protos.TransactionConfidence.Type value) { copyOnWrite(); instance.setType(value); return this; } /** * <pre> * This is optional in case we add confidence types to prevent parse errors - backwards compatible. * </pre> * * <code>optional .wallet.TransactionConfidence.Type type = 1;</code> * @return This builder for chaining. */ public Builder clearType() { copyOnWrite(); instance.clearType(); return this; } /** * <pre> * If type == BUILDING then this is the chain height at which the transaction was included. * </pre> * * <code>optional int32 appeared_at_height = 2;</code> * @return Whether the appearedAtHeight field is set. */ @java.lang.Override public boolean hasAppearedAtHeight() { return instance.hasAppearedAtHeight(); } /** * <pre> * If type == BUILDING then this is the chain height at which the transaction was included. * </pre> * * <code>optional int32 appeared_at_height = 2;</code> * @return The appearedAtHeight. */ @java.lang.Override public int getAppearedAtHeight() { return instance.getAppearedAtHeight(); } /** * <pre> * If type == BUILDING then this is the chain height at which the transaction was included. * </pre> * * <code>optional int32 appeared_at_height = 2;</code> * @param value The appearedAtHeight to set. * @return This builder for chaining. */ public Builder setAppearedAtHeight(int value) { copyOnWrite(); instance.setAppearedAtHeight(value); return this; } /** * <pre> * If type == BUILDING then this is the chain height at which the transaction was included. * </pre> * * <code>optional int32 appeared_at_height = 2;</code> * @return This builder for chaining. */ public Builder clearAppearedAtHeight() { copyOnWrite(); instance.clearAppearedAtHeight(); return this; } /** * <pre> * If set, hash of the transaction that double spent this one into oblivion. A transaction can be double spent by * multiple transactions in the case of several inputs being re-spent by several transactions but we don't * bother to track them all, just the first. This only makes sense if type = DEAD. * </pre> * * <code>optional bytes overriding_transaction = 3;</code> * @return Whether the overridingTransaction field is set. */ @java.lang.Override public boolean hasOverridingTransaction() { return instance.hasOverridingTransaction(); } /** * <pre> * If set, hash of the transaction that double spent this one into oblivion. A transaction can be double spent by * multiple transactions in the case of several inputs being re-spent by several transactions but we don't * bother to track them all, just the first. This only makes sense if type = DEAD. * </pre> * * <code>optional bytes overriding_transaction = 3;</code> * @return The overridingTransaction. */ @java.lang.Override public com.google.protobuf.ByteString getOverridingTransaction() { return instance.getOverridingTransaction(); } /** * <pre> * If set, hash of the transaction that double spent this one into oblivion. A transaction can be double spent by * multiple transactions in the case of several inputs being re-spent by several transactions but we don't * bother to track them all, just the first. This only makes sense if type = DEAD. * </pre> * * <code>optional bytes overriding_transaction = 3;</code> * @param value The overridingTransaction to set. * @return This builder for chaining. */ public Builder setOverridingTransaction(com.google.protobuf.ByteString value) { copyOnWrite(); instance.setOverridingTransaction(value); return this; } /** * <pre> * If set, hash of the transaction that double spent this one into oblivion. A transaction can be double spent by * multiple transactions in the case of several inputs being re-spent by several transactions but we don't * bother to track them all, just the first. This only makes sense if type = DEAD. * </pre> * * <code>optional bytes overriding_transaction = 3;</code> * @return This builder for chaining. */ public Builder clearOverridingTransaction() { copyOnWrite(); instance.clearOverridingTransaction(); return this; } /** * <pre> * If type == BUILDING then this is the depth of the transaction in the blockchain. * Zero confirmations: depth = 0, one confirmation: depth = 1 etc. * </pre> * * <code>optional int32 depth = 4;</code> * @return Whether the depth field is set. */ @java.lang.Override public boolean hasDepth() { return instance.hasDepth(); } /** * <pre> * If type == BUILDING then this is the depth of the transaction in the blockchain. * Zero confirmations: depth = 0, one confirmation: depth = 1 etc. * </pre> * * <code>optional int32 depth = 4;</code> * @return The depth. */ @java.lang.Override public int getDepth() { return instance.getDepth(); } /** * <pre> * If type == BUILDING then this is the depth of the transaction in the blockchain. * Zero confirmations: depth = 0, one confirmation: depth = 1 etc. * </pre> * * <code>optional int32 depth = 4;</code> * @param value The depth to set. * @return This builder for chaining. */ public Builder setDepth(int value) { copyOnWrite(); instance.setDepth(value); return this; } /** * <pre> * If type == BUILDING then this is the depth of the transaction in the blockchain. * Zero confirmations: depth = 0, one confirmation: depth = 1 etc. * </pre> * * <code>optional int32 depth = 4;</code> * @return This builder for chaining. */ public Builder clearDepth() { copyOnWrite(); instance.clearDepth(); return this; } /** * <code>repeated .wallet.PeerAddress broadcast_by = 6;</code> */ @java.lang.Override public java.util.List<org.bitcoinj.wallet.Protos.PeerAddress> getBroadcastByList() { return java.util.Collections.unmodifiableList( instance.getBroadcastByList()); } /** * <code>repeated .wallet.PeerAddress broadcast_by = 6;</code> */ @java.lang.Override public int getBroadcastByCount() { return instance.getBroadcastByCount(); }/** * <code>repeated .wallet.PeerAddress broadcast_by = 6;</code> */ @java.lang.Override public org.bitcoinj.wallet.Protos.PeerAddress getBroadcastBy(int index) { return instance.getBroadcastBy(index); } /** * <code>repeated .wallet.PeerAddress broadcast_by = 6;</code> */ public Builder setBroadcastBy( int index, org.bitcoinj.wallet.Protos.PeerAddress value) { copyOnWrite(); instance.setBroadcastBy(index, value); return this; } /** * <code>repeated .wallet.PeerAddress broadcast_by = 6;</code> */ public Builder setBroadcastBy( int index, org.bitcoinj.wallet.Protos.PeerAddress.Builder builderForValue) { copyOnWrite(); instance.setBroadcastBy(index, builderForValue.build()); return this; } /** * <code>repeated .wallet.PeerAddress broadcast_by = 6;</code> */ public Builder addBroadcastBy(org.bitcoinj.wallet.Protos.PeerAddress value) { copyOnWrite(); instance.addBroadcastBy(value); return this; } /** * <code>repeated .wallet.PeerAddress broadcast_by = 6;</code> */ public Builder addBroadcastBy( int index, org.bitcoinj.wallet.Protos.PeerAddress value) { copyOnWrite(); instance.addBroadcastBy(index, value); return this; } /** * <code>repeated .wallet.PeerAddress broadcast_by = 6;</code> */ public Builder addBroadcastBy( org.bitcoinj.wallet.Protos.PeerAddress.Builder builderForValue) { copyOnWrite(); instance.addBroadcastBy(builderForValue.build()); return this; } /** * <code>repeated .wallet.PeerAddress broadcast_by = 6;</code> */ public Builder addBroadcastBy( int index, org.bitcoinj.wallet.Protos.PeerAddress.Builder builderForValue) { copyOnWrite(); instance.addBroadcastBy(index, builderForValue.build()); return this; } /** * <code>repeated .wallet.PeerAddress broadcast_by = 6;</code> */ public Builder addAllBroadcastBy( java.lang.Iterable<? extends org.bitcoinj.wallet.Protos.PeerAddress> values) { copyOnWrite(); instance.addAllBroadcastBy(values); return this; } /** * <code>repeated .wallet.PeerAddress broadcast_by = 6;</code> */ public Builder clearBroadcastBy() { copyOnWrite(); instance.clearBroadcastBy(); return this; } /** * <code>repeated .wallet.PeerAddress broadcast_by = 6;</code> */ public Builder removeBroadcastBy(int index) { copyOnWrite(); instance.removeBroadcastBy(index); return this; } /** * <pre> * Millis since epoch the transaction was last announced to us. * </pre> * * <code>optional int64 last_broadcasted_at = 8;</code> * @return Whether the lastBroadcastedAt field is set. */ @java.lang.Override public boolean hasLastBroadcastedAt() { return instance.hasLastBroadcastedAt(); } /** * <pre> * Millis since epoch the transaction was last announced to us. * </pre> * * <code>optional int64 last_broadcasted_at = 8;</code> * @return The lastBroadcastedAt. */ @java.lang.Override public long getLastBroadcastedAt() { return instance.getLastBroadcastedAt(); } /** * <pre> * Millis since epoch the transaction was last announced to us. * </pre> * * <code>optional int64 last_broadcasted_at = 8;</code> * @param value The lastBroadcastedAt to set. * @return This builder for chaining. */ public Builder setLastBroadcastedAt(long value) { copyOnWrite(); instance.setLastBroadcastedAt(value); return this; } /** * <pre> * Millis since epoch the transaction was last announced to us. * </pre> * * <code>optional int64 last_broadcasted_at = 8;</code> * @return This builder for chaining. */ public Builder clearLastBroadcastedAt() { copyOnWrite(); instance.clearLastBroadcastedAt(); return this; } /** * <code>optional .wallet.TransactionConfidence.Source source = 7;</code> * @return Whether the source field is set. */ @java.lang.Override public boolean hasSource() { return instance.hasSource(); } /** * <code>optional .wallet.TransactionConfidence.Source source = 7;</code> * @return The source. */ @java.lang.Override public org.bitcoinj.wallet.Protos.TransactionConfidence.Source getSource() { return instance.getSource(); } /** * <code>optional .wallet.TransactionConfidence.Source source = 7;</code> * @param value The enum numeric value on the wire for source to set. * @return This builder for chaining. */ public Builder setSource(org.bitcoinj.wallet.Protos.TransactionConfidence.Source value) { copyOnWrite(); instance.setSource(value); return this; } /** * <code>optional .wallet.TransactionConfidence.Source source = 7;</code> * @return This builder for chaining. */ public Builder clearSource() { copyOnWrite(); instance.clearSource(); return this; } // @@protoc_insertion_point(builder_scope:wallet.TransactionConfidence) } private byte memoizedIsInitialized = 2; @java.lang.Override @java.lang.SuppressWarnings({"unchecked", "fallthrough"}) protected final java.lang.Object dynamicMethod( com.google.protobuf.GeneratedMessageLite.MethodToInvoke method, java.lang.Object arg0, java.lang.Object arg1) { switch (method) { case NEW_MUTABLE_INSTANCE: { return new org.bitcoinj.wallet.Protos.TransactionConfidence(); } case NEW_BUILDER: { return new Builder(); } case BUILD_MESSAGE_INFO: { java.lang.Object[] objects = new java.lang.Object[] { "bitField0_", "type_", org.bitcoinj.wallet.Protos.TransactionConfidence.Type.internalGetVerifier(), "appearedAtHeight_", "overridingTransaction_", "depth_", "broadcastBy_", org.bitcoinj.wallet.Protos.PeerAddress.class, "source_", org.bitcoinj.wallet.Protos.TransactionConfidence.Source.internalGetVerifier(), "lastBroadcastedAt_", }; java.lang.String info = "\u0001\u0007\u0000\u0001\u0001\b\u0007\u0000\u0001\u0001\u0001\u100c\u0000\u0002" + "\u1004\u0001\u0003\u100a\u0002\u0004\u1004\u0003\u0006\u041b\u0007\u100c\u0005\b" + "\u1002\u0004"; return newMessageInfo(DEFAULT_INSTANCE, info, objects); } // fall through case GET_DEFAULT_INSTANCE: { return DEFAULT_INSTANCE; } case GET_PARSER: { com.google.protobuf.Parser<org.bitcoinj.wallet.Protos.TransactionConfidence> parser = PARSER; if (parser == null) { synchronized (org.bitcoinj.wallet.Protos.TransactionConfidence.class) { parser = PARSER; if (parser == null) { parser = new DefaultInstanceBasedParser<org.bitcoinj.wallet.Protos.TransactionConfidence>( DEFAULT_INSTANCE); PARSER = parser; } } } return parser; } case GET_MEMOIZED_IS_INITIALIZED: { return memoizedIsInitialized; } case SET_MEMOIZED_IS_INITIALIZED: { memoizedIsInitialized = (byte) (arg0 == null ? 0 : 1); return null; } } throw new UnsupportedOperationException(); } // @@protoc_insertion_point(class_scope:wallet.TransactionConfidence) private static final org.bitcoinj.wallet.Protos.TransactionConfidence DEFAULT_INSTANCE; static { TransactionConfidence defaultInstance = new TransactionConfidence(); // New instances are implicitly immutable so no need to make // immutable. DEFAULT_INSTANCE = defaultInstance; com.google.protobuf.GeneratedMessageLite.registerDefaultInstance( TransactionConfidence.class, defaultInstance); } public static org.bitcoinj.wallet.Protos.TransactionConfidence getDefaultInstance() { return DEFAULT_INSTANCE; } private static volatile com.google.protobuf.Parser<TransactionConfidence> PARSER; public static com.google.protobuf.Parser<TransactionConfidence> parser() { return DEFAULT_INSTANCE.getParserForType(); } } public interface TransactionOrBuilder extends // @@protoc_insertion_point(interface_extends:wallet.Transaction) com.google.protobuf.MessageLiteOrBuilder { /** * <pre> * See Wallet.java for detailed description of pool semantics * </pre> * * <code>required int32 version = 1;</code> * @return Whether the version field is set. */ boolean hasVersion(); /** * <pre> * See Wallet.java for detailed description of pool semantics * </pre> * * <code>required int32 version = 1;</code> * @return The version. */ int getVersion(); /** * <code>required bytes hash = 2;</code> * @return Whether the hash field is set. */ boolean hasHash(); /** * <code>required bytes hash = 2;</code> * @return The hash. */ com.google.protobuf.ByteString getHash(); /** * <pre> * If pool is not present, that means either: * - This Transaction is either not in a wallet at all (the proto is re-used elsewhere) * - Or it is stored but for other purposes, for example, because it is the overriding transaction of a double spend. * - Or the Pool enum got a new value which your software is too old to parse. * </pre> * * <code>optional .wallet.Transaction.Pool pool = 3;</code> * @return Whether the pool field is set. */ boolean hasPool(); /** * <pre> * If pool is not present, that means either: * - This Transaction is either not in a wallet at all (the proto is re-used elsewhere) * - Or it is stored but for other purposes, for example, because it is the overriding transaction of a double spend. * - Or the Pool enum got a new value which your software is too old to parse. * </pre> * * <code>optional .wallet.Transaction.Pool pool = 3;</code> * @return The pool. */ org.bitcoinj.wallet.Protos.Transaction.Pool getPool(); /** * <pre> * The nLockTime field is useful for contracts. * </pre> * * <code>optional uint32 lock_time = 4;</code> * @return Whether the lockTime field is set. */ boolean hasLockTime(); /** * <pre> * The nLockTime field is useful for contracts. * </pre> * * <code>optional uint32 lock_time = 4;</code> * @return The lockTime. */ int getLockTime(); /** * <pre> * millis since epoch the transaction was last updated * </pre> * * <code>optional int64 updated_at = 5;</code> * @return Whether the updatedAt field is set. */ boolean hasUpdatedAt(); /** * <pre> * millis since epoch the transaction was last updated * </pre> * * <code>optional int64 updated_at = 5;</code> * @return The updatedAt. */ long getUpdatedAt(); /** * <code>repeated .wallet.TransactionInput transaction_input = 6;</code> */ java.util.List<org.bitcoinj.wallet.Protos.TransactionInput> getTransactionInputList(); /** * <code>repeated .wallet.TransactionInput transaction_input = 6;</code> */ org.bitcoinj.wallet.Protos.TransactionInput getTransactionInput(int index); /** * <code>repeated .wallet.TransactionInput transaction_input = 6;</code> */ int getTransactionInputCount(); /** * <code>repeated .wallet.TransactionOutput transaction_output = 7;</code> */ java.util.List<org.bitcoinj.wallet.Protos.TransactionOutput> getTransactionOutputList(); /** * <code>repeated .wallet.TransactionOutput transaction_output = 7;</code> */ org.bitcoinj.wallet.Protos.TransactionOutput getTransactionOutput(int index); /** * <code>repeated .wallet.TransactionOutput transaction_output = 7;</code> */ int getTransactionOutputCount(); /** * <pre> * A list of blocks in which the transaction has been observed (on any chain). Also, a number used to disambiguate * ordering within a block. * </pre> * * <code>repeated bytes block_hash = 8;</code> * @return A list containing the blockHash. */ java.util.List<com.google.protobuf.ByteString> getBlockHashList(); /** * <pre> * A list of blocks in which the transaction has been observed (on any chain). Also, a number used to disambiguate * ordering within a block. * </pre> * * <code>repeated bytes block_hash = 8;</code> * @return The count of blockHash. */ int getBlockHashCount(); /** * <pre> * A list of blocks in which the transaction has been observed (on any chain). Also, a number used to disambiguate * ordering within a block. * </pre> * * <code>repeated bytes block_hash = 8;</code> * @param index The index of the element to return. * @return The blockHash at the given index. */ com.google.protobuf.ByteString getBlockHash(int index); /** * <code>repeated int32 block_relativity_offsets = 11;</code> * @return A list containing the blockRelativityOffsets. */ java.util.List<java.lang.Integer> getBlockRelativityOffsetsList(); /** * <code>repeated int32 block_relativity_offsets = 11;</code> * @return The count of blockRelativityOffsets. */ int getBlockRelativityOffsetsCount(); /** * <code>repeated int32 block_relativity_offsets = 11;</code> * @param index The index of the element to return. * @return The blockRelativityOffsets at the given index. */ int getBlockRelativityOffsets(int index); /** * <pre> * Data describing where the transaction is in the chain. * </pre> * * <code>optional .wallet.TransactionConfidence confidence = 9;</code> * @return Whether the confidence field is set. */ boolean hasConfidence(); /** * <pre> * Data describing where the transaction is in the chain. * </pre> * * <code>optional .wallet.TransactionConfidence confidence = 9;</code> * @return The confidence. */ org.bitcoinj.wallet.Protos.TransactionConfidence getConfidence(); /** * <code>optional .wallet.Transaction.Purpose purpose = 10 [default = UNKNOWN];</code> * @return Whether the purpose field is set. */ boolean hasPurpose(); /** * <code>optional .wallet.Transaction.Purpose purpose = 10 [default = UNKNOWN];</code> * @return The purpose. */ org.bitcoinj.wallet.Protos.Transaction.Purpose getPurpose(); /** * <pre> * Exchange rate that was valid when the transaction was sent. * </pre> * * <code>optional .wallet.ExchangeRate exchange_rate = 12;</code> * @return Whether the exchangeRate field is set. */ boolean hasExchangeRate(); /** * <pre> * Exchange rate that was valid when the transaction was sent. * </pre> * * <code>optional .wallet.ExchangeRate exchange_rate = 12;</code> * @return The exchangeRate. */ org.bitcoinj.wallet.Protos.ExchangeRate getExchangeRate(); /** * <pre> * Memo of the transaction. It can be used to record the memo of the payment request that initiated the * transaction. * </pre> * * <code>optional string memo = 13;</code> * @return Whether the memo field is set. */ boolean hasMemo(); /** * <pre> * Memo of the transaction. It can be used to record the memo of the payment request that initiated the * transaction. * </pre> * * <code>optional string memo = 13;</code> * @return The memo. */ java.lang.String getMemo(); /** * <pre> * Memo of the transaction. It can be used to record the memo of the payment request that initiated the * transaction. * </pre> * * <code>optional string memo = 13;</code> * @return The bytes for memo. */ com.google.protobuf.ByteString getMemoBytes(); } /** * Protobuf type {@code wallet.Transaction} */ public static final class Transaction extends com.google.protobuf.GeneratedMessageLite< Transaction, Transaction.Builder> implements // @@protoc_insertion_point(message_implements:wallet.Transaction) TransactionOrBuilder { private Transaction() { hash_ = com.google.protobuf.ByteString.EMPTY; pool_ = 4; transactionInput_ = emptyProtobufList(); transactionOutput_ = emptyProtobufList(); blockHash_ = emptyProtobufList(); blockRelativityOffsets_ = emptyIntList(); memo_ = ""; } /** * <pre> ** * This is a bitfield oriented enum, with the following bits: * * bit 0 - spent * bit 1 - appears in alt chain * bit 2 - appears in best chain * bit 3 - double-spent * bit 4 - pending (we would like the tx to go into the best chain) * * Not all combinations are interesting, just the ones actually used in the enum. * </pre> * * Protobuf enum {@code wallet.Transaction.Pool} */ public enum Pool implements com.google.protobuf.Internal.EnumLite { /** * <pre> * In best chain, not all outputs spent * </pre> * * <code>UNSPENT = 4;</code> */ UNSPENT(4), /** * <pre> * In best chain, all outputs spent * </pre> * * <code>SPENT = 5;</code> */ SPENT(5), /** * <pre> * In non-best chain, not our transaction * </pre> * * <code>INACTIVE = 2;</code> */ INACTIVE(2), /** * <pre> * Double-spent by a transaction in the best chain * </pre> * * <code>DEAD = 10;</code> */ DEAD(10), /** * <pre> * Our transaction, not in any chain * </pre> * * <code>PENDING = 16;</code> */ PENDING(16), /** * <pre> * In non-best chain, our transaction * </pre> * * <code>PENDING_INACTIVE = 18;</code> */ PENDING_INACTIVE(18), ; /** * <pre> * In best chain, not all outputs spent * </pre> * * <code>UNSPENT = 4;</code> */ public static final int UNSPENT_VALUE = 4; /** * <pre> * In best chain, all outputs spent * </pre> * * <code>SPENT = 5;</code> */ public static final int SPENT_VALUE = 5; /** * <pre> * In non-best chain, not our transaction * </pre> * * <code>INACTIVE = 2;</code> */ public static final int INACTIVE_VALUE = 2; /** * <pre> * Double-spent by a transaction in the best chain * </pre> * * <code>DEAD = 10;</code> */ public static final int DEAD_VALUE = 10; /** * <pre> * Our transaction, not in any chain * </pre> * * <code>PENDING = 16;</code> */ public static final int PENDING_VALUE = 16; /** * <pre> * In non-best chain, our transaction * </pre> * * <code>PENDING_INACTIVE = 18;</code> */ public static final int PENDING_INACTIVE_VALUE = 18; @java.lang.Override public final int getNumber() { return value; } /** * @param value The number of the enum to look for. * @return The enum associated with the given number. * @deprecated Use {@link #forNumber(int)} instead. */ @java.lang.Deprecated public static Pool valueOf(int value) { return forNumber(value); } public static Pool forNumber(int value) { switch (value) { case 4: return UNSPENT; case 5: return SPENT; case 2: return INACTIVE; case 10: return DEAD; case 16: return PENDING; case 18: return PENDING_INACTIVE; default: return null; } } public static com.google.protobuf.Internal.EnumLiteMap<Pool> internalGetValueMap() { return internalValueMap; } private static final com.google.protobuf.Internal.EnumLiteMap< Pool> internalValueMap = new com.google.protobuf.Internal.EnumLiteMap<Pool>() { @java.lang.Override public Pool findValueByNumber(int number) { return Pool.forNumber(number); } }; public static com.google.protobuf.Internal.EnumVerifier internalGetVerifier() { return PoolVerifier.INSTANCE; } private static final class PoolVerifier implements com.google.protobuf.Internal.EnumVerifier { static final com.google.protobuf.Internal.EnumVerifier INSTANCE = new PoolVerifier(); @java.lang.Override public boolean isInRange(int number) { return Pool.forNumber(number) != null; } }; private final int value; private Pool(int value) { this.value = value; } // @@protoc_insertion_point(enum_scope:wallet.Transaction.Pool) } /** * <pre> * For what purpose the transaction was created. * </pre> * * Protobuf enum {@code wallet.Transaction.Purpose} */ public enum Purpose implements com.google.protobuf.Internal.EnumLite { /** * <pre> * Old wallets or the purpose genuinely is a mystery (e.g. imported from some external source). * </pre> * * <code>UNKNOWN = 0;</code> */ UNKNOWN(0), /** * <pre> * Created in response to a user request for payment. This is the normal case. * </pre> * * <code>USER_PAYMENT = 1;</code> */ USER_PAYMENT(1), /** * <pre> * Created automatically to move money from rotated keys. * </pre> * * <code>KEY_ROTATION = 2;</code> */ KEY_ROTATION(2), /** * <pre> * Stuff used by Lighthouse. * </pre> * * <code>ASSURANCE_CONTRACT_CLAIM = 3;</code> */ ASSURANCE_CONTRACT_CLAIM(3), /** * <code>ASSURANCE_CONTRACT_PLEDGE = 4;</code> */ ASSURANCE_CONTRACT_PLEDGE(4), /** * <code>ASSURANCE_CONTRACT_STUB = 5;</code> */ ASSURANCE_CONTRACT_STUB(5), /** * <pre> * Raise fee, e.g. child-pays-for-parent. * </pre> * * <code>RAISE_FEE = 6;</code> */ RAISE_FEE(6), ; /** * <pre> * Old wallets or the purpose genuinely is a mystery (e.g. imported from some external source). * </pre> * * <code>UNKNOWN = 0;</code> */ public static final int UNKNOWN_VALUE = 0; /** * <pre> * Created in response to a user request for payment. This is the normal case. * </pre> * * <code>USER_PAYMENT = 1;</code> */ public static final int USER_PAYMENT_VALUE = 1; /** * <pre> * Created automatically to move money from rotated keys. * </pre> * * <code>KEY_ROTATION = 2;</code> */ public static final int KEY_ROTATION_VALUE = 2; /** * <pre> * Stuff used by Lighthouse. * </pre> * * <code>ASSURANCE_CONTRACT_CLAIM = 3;</code> */ public static final int ASSURANCE_CONTRACT_CLAIM_VALUE = 3; /** * <code>ASSURANCE_CONTRACT_PLEDGE = 4;</code> */ public static final int ASSURANCE_CONTRACT_PLEDGE_VALUE = 4; /** * <code>ASSURANCE_CONTRACT_STUB = 5;</code> */ public static final int ASSURANCE_CONTRACT_STUB_VALUE = 5; /** * <pre> * Raise fee, e.g. child-pays-for-parent. * </pre> * * <code>RAISE_FEE = 6;</code> */ public static final int RAISE_FEE_VALUE = 6; @java.lang.Override public final int getNumber() { return value; } /** * @param value The number of the enum to look for. * @return The enum associated with the given number. * @deprecated Use {@link #forNumber(int)} instead. */ @java.lang.Deprecated public static Purpose valueOf(int value) { return forNumber(value); } public static Purpose forNumber(int value) { switch (value) { case 0: return UNKNOWN; case 1: return USER_PAYMENT; case 2: return KEY_ROTATION; case 3: return ASSURANCE_CONTRACT_CLAIM; case 4: return ASSURANCE_CONTRACT_PLEDGE; case 5: return ASSURANCE_CONTRACT_STUB; case 6: return RAISE_FEE; default: return null; } } public static com.google.protobuf.Internal.EnumLiteMap<Purpose> internalGetValueMap() { return internalValueMap; } private static final com.google.protobuf.Internal.EnumLiteMap< Purpose> internalValueMap = new com.google.protobuf.Internal.EnumLiteMap<Purpose>() { @java.lang.Override public Purpose findValueByNumber(int number) { return Purpose.forNumber(number); } }; public static com.google.protobuf.Internal.EnumVerifier internalGetVerifier() { return PurposeVerifier.INSTANCE; } private static final class PurposeVerifier implements com.google.protobuf.Internal.EnumVerifier { static final com.google.protobuf.Internal.EnumVerifier INSTANCE = new PurposeVerifier(); @java.lang.Override public boolean isInRange(int number) { return Purpose.forNumber(number) != null; } }; private final int value; private Purpose(int value) { this.value = value; } // @@protoc_insertion_point(enum_scope:wallet.Transaction.Purpose) } private int bitField0_; public static final int VERSION_FIELD_NUMBER = 1; private int version_; /** * <pre> * See Wallet.java for detailed description of pool semantics * </pre> * * <code>required int32 version = 1;</code> * @return Whether the version field is set. */ @java.lang.Override public boolean hasVersion() { return ((bitField0_ & 0x00000001) != 0); } /** * <pre> * See Wallet.java for detailed description of pool semantics * </pre> * * <code>required int32 version = 1;</code> * @return The version. */ @java.lang.Override public int getVersion() { return version_; } /** * <pre> * See Wallet.java for detailed description of pool semantics * </pre> * * <code>required int32 version = 1;</code> * @param value The version to set. */ private void setVersion(int value) { bitField0_ |= 0x00000001; version_ = value; } /** * <pre> * See Wallet.java for detailed description of pool semantics * </pre> * * <code>required int32 version = 1;</code> */ private void clearVersion() { bitField0_ = (bitField0_ & ~0x00000001); version_ = 0; } public static final int HASH_FIELD_NUMBER = 2; private com.google.protobuf.ByteString hash_; /** * <code>required bytes hash = 2;</code> * @return Whether the hash field is set. */ @java.lang.Override public boolean hasHash() { return ((bitField0_ & 0x00000002) != 0); } /** * <code>required bytes hash = 2;</code> * @return The hash. */ @java.lang.Override public com.google.protobuf.ByteString getHash() { return hash_; } /** * <code>required bytes hash = 2;</code> * @param value The hash to set. */ private void setHash(com.google.protobuf.ByteString value) { java.lang.Class<?> valueClass = value.getClass(); bitField0_ |= 0x00000002; hash_ = value; } /** * <code>required bytes hash = 2;</code> */ private void clearHash() { bitField0_ = (bitField0_ & ~0x00000002); hash_ = getDefaultInstance().getHash(); } public static final int POOL_FIELD_NUMBER = 3; private int pool_; /** * <pre> * If pool is not present, that means either: * - This Transaction is either not in a wallet at all (the proto is re-used elsewhere) * - Or it is stored but for other purposes, for example, because it is the overriding transaction of a double spend. * - Or the Pool enum got a new value which your software is too old to parse. * </pre> * * <code>optional .wallet.Transaction.Pool pool = 3;</code> * @return Whether the pool field is set. */ @java.lang.Override public boolean hasPool() { return ((bitField0_ & 0x00000004) != 0); } /** * <pre> * If pool is not present, that means either: * - This Transaction is either not in a wallet at all (the proto is re-used elsewhere) * - Or it is stored but for other purposes, for example, because it is the overriding transaction of a double spend. * - Or the Pool enum got a new value which your software is too old to parse. * </pre> * * <code>optional .wallet.Transaction.Pool pool = 3;</code> * @return The pool. */ @java.lang.Override public org.bitcoinj.wallet.Protos.Transaction.Pool getPool() { org.bitcoinj.wallet.Protos.Transaction.Pool result = org.bitcoinj.wallet.Protos.Transaction.Pool.forNumber(pool_); return result == null ? org.bitcoinj.wallet.Protos.Transaction.Pool.UNSPENT : result; } /** * <pre> * If pool is not present, that means either: * - This Transaction is either not in a wallet at all (the proto is re-used elsewhere) * - Or it is stored but for other purposes, for example, because it is the overriding transaction of a double spend. * - Or the Pool enum got a new value which your software is too old to parse. * </pre> * * <code>optional .wallet.Transaction.Pool pool = 3;</code> * @param value The pool to set. */ private void setPool(org.bitcoinj.wallet.Protos.Transaction.Pool value) { pool_ = value.getNumber(); bitField0_ |= 0x00000004; } /** * <pre> * If pool is not present, that means either: * - This Transaction is either not in a wallet at all (the proto is re-used elsewhere) * - Or it is stored but for other purposes, for example, because it is the overriding transaction of a double spend. * - Or the Pool enum got a new value which your software is too old to parse. * </pre> * * <code>optional .wallet.Transaction.Pool pool = 3;</code> */ private void clearPool() { bitField0_ = (bitField0_ & ~0x00000004); pool_ = 4; } public static final int LOCK_TIME_FIELD_NUMBER = 4; private int lockTime_; /** * <pre> * The nLockTime field is useful for contracts. * </pre> * * <code>optional uint32 lock_time = 4;</code> * @return Whether the lockTime field is set. */ @java.lang.Override public boolean hasLockTime() { return ((bitField0_ & 0x00000008) != 0); } /** * <pre> * The nLockTime field is useful for contracts. * </pre> * * <code>optional uint32 lock_time = 4;</code> * @return The lockTime. */ @java.lang.Override public int getLockTime() { return lockTime_; } /** * <pre> * The nLockTime field is useful for contracts. * </pre> * * <code>optional uint32 lock_time = 4;</code> * @param value The lockTime to set. */ private void setLockTime(int value) { bitField0_ |= 0x00000008; lockTime_ = value; } /** * <pre> * The nLockTime field is useful for contracts. * </pre> * * <code>optional uint32 lock_time = 4;</code> */ private void clearLockTime() { bitField0_ = (bitField0_ & ~0x00000008); lockTime_ = 0; } public static final int UPDATED_AT_FIELD_NUMBER = 5; private long updatedAt_; /** * <pre> * millis since epoch the transaction was last updated * </pre> * * <code>optional int64 updated_at = 5;</code> * @return Whether the updatedAt field is set. */ @java.lang.Override public boolean hasUpdatedAt() { return ((bitField0_ & 0x00000010) != 0); } /** * <pre> * millis since epoch the transaction was last updated * </pre> * * <code>optional int64 updated_at = 5;</code> * @return The updatedAt. */ @java.lang.Override public long getUpdatedAt() { return updatedAt_; } /** * <pre> * millis since epoch the transaction was last updated * </pre> * * <code>optional int64 updated_at = 5;</code> * @param value The updatedAt to set. */ private void setUpdatedAt(long value) { bitField0_ |= 0x00000010; updatedAt_ = value; } /** * <pre> * millis since epoch the transaction was last updated * </pre> * * <code>optional int64 updated_at = 5;</code> */ private void clearUpdatedAt() { bitField0_ = (bitField0_ & ~0x00000010); updatedAt_ = 0L; } public static final int TRANSACTION_INPUT_FIELD_NUMBER = 6; private com.google.protobuf.Internal.ProtobufList<org.bitcoinj.wallet.Protos.TransactionInput> transactionInput_; /** * <code>repeated .wallet.TransactionInput transaction_input = 6;</code> */ @java.lang.Override public java.util.List<org.bitcoinj.wallet.Protos.TransactionInput> getTransactionInputList() { return transactionInput_; } /** * <code>repeated .wallet.TransactionInput transaction_input = 6;</code> */ public java.util.List<? extends org.bitcoinj.wallet.Protos.TransactionInputOrBuilder> getTransactionInputOrBuilderList() { return transactionInput_; } /** * <code>repeated .wallet.TransactionInput transaction_input = 6;</code> */ @java.lang.Override public int getTransactionInputCount() { return transactionInput_.size(); } /** * <code>repeated .wallet.TransactionInput transaction_input = 6;</code> */ @java.lang.Override public org.bitcoinj.wallet.Protos.TransactionInput getTransactionInput(int index) { return transactionInput_.get(index); } /** * <code>repeated .wallet.TransactionInput transaction_input = 6;</code> */ public org.bitcoinj.wallet.Protos.TransactionInputOrBuilder getTransactionInputOrBuilder( int index) { return transactionInput_.get(index); } private void ensureTransactionInputIsMutable() { com.google.protobuf.Internal.ProtobufList<org.bitcoinj.wallet.Protos.TransactionInput> tmp = transactionInput_; if (!tmp.isModifiable()) { transactionInput_ = com.google.protobuf.GeneratedMessageLite.mutableCopy(tmp); } } /** * <code>repeated .wallet.TransactionInput transaction_input = 6;</code> */ private void setTransactionInput( int index, org.bitcoinj.wallet.Protos.TransactionInput value) { value.getClass(); ensureTransactionInputIsMutable(); transactionInput_.set(index, value); } /** * <code>repeated .wallet.TransactionInput transaction_input = 6;</code> */ private void addTransactionInput(org.bitcoinj.wallet.Protos.TransactionInput value) { value.getClass(); ensureTransactionInputIsMutable(); transactionInput_.add(value); } /** * <code>repeated .wallet.TransactionInput transaction_input = 6;</code> */ private void addTransactionInput( int index, org.bitcoinj.wallet.Protos.TransactionInput value) { value.getClass(); ensureTransactionInputIsMutable(); transactionInput_.add(index, value); } /** * <code>repeated .wallet.TransactionInput transaction_input = 6;</code> */ private void addAllTransactionInput( java.lang.Iterable<? extends org.bitcoinj.wallet.Protos.TransactionInput> values) { ensureTransactionInputIsMutable(); com.google.protobuf.AbstractMessageLite.addAll( values, transactionInput_); } /** * <code>repeated .wallet.TransactionInput transaction_input = 6;</code> */ private void clearTransactionInput() { transactionInput_ = emptyProtobufList(); } /** * <code>repeated .wallet.TransactionInput transaction_input = 6;</code> */ private void removeTransactionInput(int index) { ensureTransactionInputIsMutable(); transactionInput_.remove(index); } public static final int TRANSACTION_OUTPUT_FIELD_NUMBER = 7; private com.google.protobuf.Internal.ProtobufList<org.bitcoinj.wallet.Protos.TransactionOutput> transactionOutput_; /** * <code>repeated .wallet.TransactionOutput transaction_output = 7;</code> */ @java.lang.Override public java.util.List<org.bitcoinj.wallet.Protos.TransactionOutput> getTransactionOutputList() { return transactionOutput_; } /** * <code>repeated .wallet.TransactionOutput transaction_output = 7;</code> */ public java.util.List<? extends org.bitcoinj.wallet.Protos.TransactionOutputOrBuilder> getTransactionOutputOrBuilderList() { return transactionOutput_; } /** * <code>repeated .wallet.TransactionOutput transaction_output = 7;</code> */ @java.lang.Override public int getTransactionOutputCount() { return transactionOutput_.size(); } /** * <code>repeated .wallet.TransactionOutput transaction_output = 7;</code> */ @java.lang.Override public org.bitcoinj.wallet.Protos.TransactionOutput getTransactionOutput(int index) { return transactionOutput_.get(index); } /** * <code>repeated .wallet.TransactionOutput transaction_output = 7;</code> */ public org.bitcoinj.wallet.Protos.TransactionOutputOrBuilder getTransactionOutputOrBuilder( int index) { return transactionOutput_.get(index); } private void ensureTransactionOutputIsMutable() { com.google.protobuf.Internal.ProtobufList<org.bitcoinj.wallet.Protos.TransactionOutput> tmp = transactionOutput_; if (!tmp.isModifiable()) { transactionOutput_ = com.google.protobuf.GeneratedMessageLite.mutableCopy(tmp); } } /** * <code>repeated .wallet.TransactionOutput transaction_output = 7;</code> */ private void setTransactionOutput( int index, org.bitcoinj.wallet.Protos.TransactionOutput value) { value.getClass(); ensureTransactionOutputIsMutable(); transactionOutput_.set(index, value); } /** * <code>repeated .wallet.TransactionOutput transaction_output = 7;</code> */ private void addTransactionOutput(org.bitcoinj.wallet.Protos.TransactionOutput value) { value.getClass(); ensureTransactionOutputIsMutable(); transactionOutput_.add(value); } /** * <code>repeated .wallet.TransactionOutput transaction_output = 7;</code> */ private void addTransactionOutput( int index, org.bitcoinj.wallet.Protos.TransactionOutput value) { value.getClass(); ensureTransactionOutputIsMutable(); transactionOutput_.add(index, value); } /** * <code>repeated .wallet.TransactionOutput transaction_output = 7;</code> */ private void addAllTransactionOutput( java.lang.Iterable<? extends org.bitcoinj.wallet.Protos.TransactionOutput> values) { ensureTransactionOutputIsMutable(); com.google.protobuf.AbstractMessageLite.addAll( values, transactionOutput_); } /** * <code>repeated .wallet.TransactionOutput transaction_output = 7;</code> */ private void clearTransactionOutput() { transactionOutput_ = emptyProtobufList(); } /** * <code>repeated .wallet.TransactionOutput transaction_output = 7;</code> */ private void removeTransactionOutput(int index) { ensureTransactionOutputIsMutable(); transactionOutput_.remove(index); } public static final int BLOCK_HASH_FIELD_NUMBER = 8; private com.google.protobuf.Internal.ProtobufList<com.google.protobuf.ByteString> blockHash_; /** * <pre> * A list of blocks in which the transaction has been observed (on any chain). Also, a number used to disambiguate * ordering within a block. * </pre> * * <code>repeated bytes block_hash = 8;</code> * @return A list containing the blockHash. */ @java.lang.Override public java.util.List<com.google.protobuf.ByteString> getBlockHashList() { return blockHash_; } /** * <pre> * A list of blocks in which the transaction has been observed (on any chain). Also, a number used to disambiguate * ordering within a block. * </pre> * * <code>repeated bytes block_hash = 8;</code> * @return The count of blockHash. */ @java.lang.Override public int getBlockHashCount() { return blockHash_.size(); } /** * <pre> * A list of blocks in which the transaction has been observed (on any chain). Also, a number used to disambiguate * ordering within a block. * </pre> * * <code>repeated bytes block_hash = 8;</code> * @param index The index of the element to return. * @return The blockHash at the given index. */ @java.lang.Override public com.google.protobuf.ByteString getBlockHash(int index) { return blockHash_.get(index); } private void ensureBlockHashIsMutable() { com.google.protobuf.Internal.ProtobufList<com.google.protobuf.ByteString> tmp = blockHash_; if (!tmp.isModifiable()) { blockHash_ = com.google.protobuf.GeneratedMessageLite.mutableCopy(tmp); } } /** * <pre> * A list of blocks in which the transaction has been observed (on any chain). Also, a number used to disambiguate * ordering within a block. * </pre> * * <code>repeated bytes block_hash = 8;</code> * @param index The index to set the value at. * @param value The blockHash to set. */ private void setBlockHash( int index, com.google.protobuf.ByteString value) { java.lang.Class<?> valueClass = value.getClass(); ensureBlockHashIsMutable(); blockHash_.set(index, value); } /** * <pre> * A list of blocks in which the transaction has been observed (on any chain). Also, a number used to disambiguate * ordering within a block. * </pre> * * <code>repeated bytes block_hash = 8;</code> * @param value The blockHash to add. */ private void addBlockHash(com.google.protobuf.ByteString value) { java.lang.Class<?> valueClass = value.getClass(); ensureBlockHashIsMutable(); blockHash_.add(value); } /** * <pre> * A list of blocks in which the transaction has been observed (on any chain). Also, a number used to disambiguate * ordering within a block. * </pre> * * <code>repeated bytes block_hash = 8;</code> * @param values The blockHash to add. */ private void addAllBlockHash( java.lang.Iterable<? extends com.google.protobuf.ByteString> values) { ensureBlockHashIsMutable(); com.google.protobuf.AbstractMessageLite.addAll( values, blockHash_); } /** * <pre> * A list of blocks in which the transaction has been observed (on any chain). Also, a number used to disambiguate * ordering within a block. * </pre> * * <code>repeated bytes block_hash = 8;</code> */ private void clearBlockHash() { blockHash_ = emptyProtobufList(); } public static final int BLOCK_RELATIVITY_OFFSETS_FIELD_NUMBER = 11; private com.google.protobuf.Internal.IntList blockRelativityOffsets_; /** * <code>repeated int32 block_relativity_offsets = 11;</code> * @return A list containing the blockRelativityOffsets. */ @java.lang.Override public java.util.List<java.lang.Integer> getBlockRelativityOffsetsList() { return blockRelativityOffsets_; } /** * <code>repeated int32 block_relativity_offsets = 11;</code> * @return The count of blockRelativityOffsets. */ @java.lang.Override public int getBlockRelativityOffsetsCount() { return blockRelativityOffsets_.size(); } /** * <code>repeated int32 block_relativity_offsets = 11;</code> * @param index The index of the element to return. * @return The blockRelativityOffsets at the given index. */ @java.lang.Override public int getBlockRelativityOffsets(int index) { return blockRelativityOffsets_.getInt(index); } private void ensureBlockRelativityOffsetsIsMutable() { com.google.protobuf.Internal.IntList tmp = blockRelativityOffsets_; if (!tmp.isModifiable()) { blockRelativityOffsets_ = com.google.protobuf.GeneratedMessageLite.mutableCopy(tmp); } } /** * <code>repeated int32 block_relativity_offsets = 11;</code> * @param index The index to set the value at. * @param value The blockRelativityOffsets to set. */ private void setBlockRelativityOffsets( int index, int value) { ensureBlockRelativityOffsetsIsMutable(); blockRelativityOffsets_.setInt(index, value); } /** * <code>repeated int32 block_relativity_offsets = 11;</code> * @param value The blockRelativityOffsets to add. */ private void addBlockRelativityOffsets(int value) { ensureBlockRelativityOffsetsIsMutable(); blockRelativityOffsets_.addInt(value); } /** * <code>repeated int32 block_relativity_offsets = 11;</code> * @param values The blockRelativityOffsets to add. */ private void addAllBlockRelativityOffsets( java.lang.Iterable<? extends java.lang.Integer> values) { ensureBlockRelativityOffsetsIsMutable(); com.google.protobuf.AbstractMessageLite.addAll( values, blockRelativityOffsets_); } /** * <code>repeated int32 block_relativity_offsets = 11;</code> */ private void clearBlockRelativityOffsets() { blockRelativityOffsets_ = emptyIntList(); } public static final int CONFIDENCE_FIELD_NUMBER = 9; private org.bitcoinj.wallet.Protos.TransactionConfidence confidence_; /** * <pre> * Data describing where the transaction is in the chain. * </pre> * * <code>optional .wallet.TransactionConfidence confidence = 9;</code> */ @java.lang.Override public boolean hasConfidence() { return ((bitField0_ & 0x00000020) != 0); } /** * <pre> * Data describing where the transaction is in the chain. * </pre> * * <code>optional .wallet.TransactionConfidence confidence = 9;</code> */ @java.lang.Override public org.bitcoinj.wallet.Protos.TransactionConfidence getConfidence() { return confidence_ == null ? org.bitcoinj.wallet.Protos.TransactionConfidence.getDefaultInstance() : confidence_; } /** * <pre> * Data describing where the transaction is in the chain. * </pre> * * <code>optional .wallet.TransactionConfidence confidence = 9;</code> */ private void setConfidence(org.bitcoinj.wallet.Protos.TransactionConfidence value) { value.getClass(); confidence_ = value; bitField0_ |= 0x00000020; } /** * <pre> * Data describing where the transaction is in the chain. * </pre> * * <code>optional .wallet.TransactionConfidence confidence = 9;</code> */ @java.lang.SuppressWarnings({"ReferenceEquality"}) private void mergeConfidence(org.bitcoinj.wallet.Protos.TransactionConfidence value) { value.getClass(); if (confidence_ != null && confidence_ != org.bitcoinj.wallet.Protos.TransactionConfidence.getDefaultInstance()) { confidence_ = org.bitcoinj.wallet.Protos.TransactionConfidence.newBuilder(confidence_).mergeFrom(value).buildPartial(); } else { confidence_ = value; } bitField0_ |= 0x00000020; } /** * <pre> * Data describing where the transaction is in the chain. * </pre> * * <code>optional .wallet.TransactionConfidence confidence = 9;</code> */ private void clearConfidence() { confidence_ = null; bitField0_ = (bitField0_ & ~0x00000020); } public static final int PURPOSE_FIELD_NUMBER = 10; private int purpose_; /** * <code>optional .wallet.Transaction.Purpose purpose = 10 [default = UNKNOWN];</code> * @return Whether the purpose field is set. */ @java.lang.Override public boolean hasPurpose() { return ((bitField0_ & 0x00000040) != 0); } /** * <code>optional .wallet.Transaction.Purpose purpose = 10 [default = UNKNOWN];</code> * @return The purpose. */ @java.lang.Override public org.bitcoinj.wallet.Protos.Transaction.Purpose getPurpose() { org.bitcoinj.wallet.Protos.Transaction.Purpose result = org.bitcoinj.wallet.Protos.Transaction.Purpose.forNumber(purpose_); return result == null ? org.bitcoinj.wallet.Protos.Transaction.Purpose.UNKNOWN : result; } /** * <code>optional .wallet.Transaction.Purpose purpose = 10 [default = UNKNOWN];</code> * @param value The purpose to set. */ private void setPurpose(org.bitcoinj.wallet.Protos.Transaction.Purpose value) { purpose_ = value.getNumber(); bitField0_ |= 0x00000040; } /** * <code>optional .wallet.Transaction.Purpose purpose = 10 [default = UNKNOWN];</code> */ private void clearPurpose() { bitField0_ = (bitField0_ & ~0x00000040); purpose_ = 0; } public static final int EXCHANGE_RATE_FIELD_NUMBER = 12; private org.bitcoinj.wallet.Protos.ExchangeRate exchangeRate_; /** * <pre> * Exchange rate that was valid when the transaction was sent. * </pre> * * <code>optional .wallet.ExchangeRate exchange_rate = 12;</code> */ @java.lang.Override public boolean hasExchangeRate() { return ((bitField0_ & 0x00000080) != 0); } /** * <pre> * Exchange rate that was valid when the transaction was sent. * </pre> * * <code>optional .wallet.ExchangeRate exchange_rate = 12;</code> */ @java.lang.Override public org.bitcoinj.wallet.Protos.ExchangeRate getExchangeRate() { return exchangeRate_ == null ? org.bitcoinj.wallet.Protos.ExchangeRate.getDefaultInstance() : exchangeRate_; } /** * <pre> * Exchange rate that was valid when the transaction was sent. * </pre> * * <code>optional .wallet.ExchangeRate exchange_rate = 12;</code> */ private void setExchangeRate(org.bitcoinj.wallet.Protos.ExchangeRate value) { value.getClass(); exchangeRate_ = value; bitField0_ |= 0x00000080; } /** * <pre> * Exchange rate that was valid when the transaction was sent. * </pre> * * <code>optional .wallet.ExchangeRate exchange_rate = 12;</code> */ @java.lang.SuppressWarnings({"ReferenceEquality"}) private void mergeExchangeRate(org.bitcoinj.wallet.Protos.ExchangeRate value) { value.getClass(); if (exchangeRate_ != null && exchangeRate_ != org.bitcoinj.wallet.Protos.ExchangeRate.getDefaultInstance()) { exchangeRate_ = org.bitcoinj.wallet.Protos.ExchangeRate.newBuilder(exchangeRate_).mergeFrom(value).buildPartial(); } else { exchangeRate_ = value; } bitField0_ |= 0x00000080; } /** * <pre> * Exchange rate that was valid when the transaction was sent. * </pre> * * <code>optional .wallet.ExchangeRate exchange_rate = 12;</code> */ private void clearExchangeRate() { exchangeRate_ = null; bitField0_ = (bitField0_ & ~0x00000080); } public static final int MEMO_FIELD_NUMBER = 13; private java.lang.String memo_; /** * <pre> * Memo of the transaction. It can be used to record the memo of the payment request that initiated the * transaction. * </pre> * * <code>optional string memo = 13;</code> * @return Whether the memo field is set. */ @java.lang.Override public boolean hasMemo() { return ((bitField0_ & 0x00000100) != 0); } /** * <pre> * Memo of the transaction. It can be used to record the memo of the payment request that initiated the * transaction. * </pre> * * <code>optional string memo = 13;</code> * @return The memo. */ @java.lang.Override public java.lang.String getMemo() { return memo_; } /** * <pre> * Memo of the transaction. It can be used to record the memo of the payment request that initiated the * transaction. * </pre> * * <code>optional string memo = 13;</code> * @return The bytes for memo. */ @java.lang.Override public com.google.protobuf.ByteString getMemoBytes() { return com.google.protobuf.ByteString.copyFromUtf8(memo_); } /** * <pre> * Memo of the transaction. It can be used to record the memo of the payment request that initiated the * transaction. * </pre> * * <code>optional string memo = 13;</code> * @param value The memo to set. */ private void setMemo( java.lang.String value) { java.lang.Class<?> valueClass = value.getClass(); bitField0_ |= 0x00000100; memo_ = value; } /** * <pre> * Memo of the transaction. It can be used to record the memo of the payment request that initiated the * transaction. * </pre> * * <code>optional string memo = 13;</code> */ private void clearMemo() { bitField0_ = (bitField0_ & ~0x00000100); memo_ = getDefaultInstance().getMemo(); } /** * <pre> * Memo of the transaction. It can be used to record the memo of the payment request that initiated the * transaction. * </pre> * * <code>optional string memo = 13;</code> * @param value The bytes for memo to set. */ private void setMemoBytes( com.google.protobuf.ByteString value) { memo_ = value.toStringUtf8(); bitField0_ |= 0x00000100; } public static org.bitcoinj.wallet.Protos.Transaction parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return com.google.protobuf.GeneratedMessageLite.parseFrom( DEFAULT_INSTANCE, data); } public static org.bitcoinj.wallet.Protos.Transaction parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return com.google.protobuf.GeneratedMessageLite.parseFrom( DEFAULT_INSTANCE, data, extensionRegistry); } public static org.bitcoinj.wallet.Protos.Transaction parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return com.google.protobuf.GeneratedMessageLite.parseFrom( DEFAULT_INSTANCE, data); } public static org.bitcoinj.wallet.Protos.Transaction parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return com.google.protobuf.GeneratedMessageLite.parseFrom( DEFAULT_INSTANCE, data, extensionRegistry); } public static org.bitcoinj.wallet.Protos.Transaction parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return com.google.protobuf.GeneratedMessageLite.parseFrom( DEFAULT_INSTANCE, data); } public static org.bitcoinj.wallet.Protos.Transaction parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return com.google.protobuf.GeneratedMessageLite.parseFrom( DEFAULT_INSTANCE, data, extensionRegistry); } public static org.bitcoinj.wallet.Protos.Transaction parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageLite.parseFrom( DEFAULT_INSTANCE, input); } public static org.bitcoinj.wallet.Protos.Transaction parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageLite.parseFrom( DEFAULT_INSTANCE, input, extensionRegistry); } public static org.bitcoinj.wallet.Protos.Transaction parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return parseDelimitedFrom(DEFAULT_INSTANCE, input); } public static org.bitcoinj.wallet.Protos.Transaction parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return parseDelimitedFrom(DEFAULT_INSTANCE, input, extensionRegistry); } public static org.bitcoinj.wallet.Protos.Transaction parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageLite.parseFrom( DEFAULT_INSTANCE, input); } public static org.bitcoinj.wallet.Protos.Transaction parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageLite.parseFrom( DEFAULT_INSTANCE, input, extensionRegistry); } public static Builder newBuilder() { return (Builder) DEFAULT_INSTANCE.createBuilder(); } public static Builder newBuilder(org.bitcoinj.wallet.Protos.Transaction prototype) { return (Builder) DEFAULT_INSTANCE.createBuilder(prototype); } /** * Protobuf type {@code wallet.Transaction} */ public static final class Builder extends com.google.protobuf.GeneratedMessageLite.Builder< org.bitcoinj.wallet.Protos.Transaction, Builder> implements // @@protoc_insertion_point(builder_implements:wallet.Transaction) org.bitcoinj.wallet.Protos.TransactionOrBuilder { // Construct using org.bitcoinj.wallet.Protos.Transaction.newBuilder() private Builder() { super(DEFAULT_INSTANCE); } /** * <pre> * See Wallet.java for detailed description of pool semantics * </pre> * * <code>required int32 version = 1;</code> * @return Whether the version field is set. */ @java.lang.Override public boolean hasVersion() { return instance.hasVersion(); } /** * <pre> * See Wallet.java for detailed description of pool semantics * </pre> * * <code>required int32 version = 1;</code> * @return The version. */ @java.lang.Override public int getVersion() { return instance.getVersion(); } /** * <pre> * See Wallet.java for detailed description of pool semantics * </pre> * * <code>required int32 version = 1;</code> * @param value The version to set. * @return This builder for chaining. */ public Builder setVersion(int value) { copyOnWrite(); instance.setVersion(value); return this; } /** * <pre> * See Wallet.java for detailed description of pool semantics * </pre> * * <code>required int32 version = 1;</code> * @return This builder for chaining. */ public Builder clearVersion() { copyOnWrite(); instance.clearVersion(); return this; } /** * <code>required bytes hash = 2;</code> * @return Whether the hash field is set. */ @java.lang.Override public boolean hasHash() { return instance.hasHash(); } /** * <code>required bytes hash = 2;</code> * @return The hash. */ @java.lang.Override public com.google.protobuf.ByteString getHash() { return instance.getHash(); } /** * <code>required bytes hash = 2;</code> * @param value The hash to set. * @return This builder for chaining. */ public Builder setHash(com.google.protobuf.ByteString value) { copyOnWrite(); instance.setHash(value); return this; } /** * <code>required bytes hash = 2;</code> * @return This builder for chaining. */ public Builder clearHash() { copyOnWrite(); instance.clearHash(); return this; } /** * <pre> * If pool is not present, that means either: * - This Transaction is either not in a wallet at all (the proto is re-used elsewhere) * - Or it is stored but for other purposes, for example, because it is the overriding transaction of a double spend. * - Or the Pool enum got a new value which your software is too old to parse. * </pre> * * <code>optional .wallet.Transaction.Pool pool = 3;</code> * @return Whether the pool field is set. */ @java.lang.Override public boolean hasPool() { return instance.hasPool(); } /** * <pre> * If pool is not present, that means either: * - This Transaction is either not in a wallet at all (the proto is re-used elsewhere) * - Or it is stored but for other purposes, for example, because it is the overriding transaction of a double spend. * - Or the Pool enum got a new value which your software is too old to parse. * </pre> * * <code>optional .wallet.Transaction.Pool pool = 3;</code> * @return The pool. */ @java.lang.Override public org.bitcoinj.wallet.Protos.Transaction.Pool getPool() { return instance.getPool(); } /** * <pre> * If pool is not present, that means either: * - This Transaction is either not in a wallet at all (the proto is re-used elsewhere) * - Or it is stored but for other purposes, for example, because it is the overriding transaction of a double spend. * - Or the Pool enum got a new value which your software is too old to parse. * </pre> * * <code>optional .wallet.Transaction.Pool pool = 3;</code> * @param value The enum numeric value on the wire for pool to set. * @return This builder for chaining. */ public Builder setPool(org.bitcoinj.wallet.Protos.Transaction.Pool value) { copyOnWrite(); instance.setPool(value); return this; } /** * <pre> * If pool is not present, that means either: * - This Transaction is either not in a wallet at all (the proto is re-used elsewhere) * - Or it is stored but for other purposes, for example, because it is the overriding transaction of a double spend. * - Or the Pool enum got a new value which your software is too old to parse. * </pre> * * <code>optional .wallet.Transaction.Pool pool = 3;</code> * @return This builder for chaining. */ public Builder clearPool() { copyOnWrite(); instance.clearPool(); return this; } /** * <pre> * The nLockTime field is useful for contracts. * </pre> * * <code>optional uint32 lock_time = 4;</code> * @return Whether the lockTime field is set. */ @java.lang.Override public boolean hasLockTime() { return instance.hasLockTime(); } /** * <pre> * The nLockTime field is useful for contracts. * </pre> * * <code>optional uint32 lock_time = 4;</code> * @return The lockTime. */ @java.lang.Override public int getLockTime() { return instance.getLockTime(); } /** * <pre> * The nLockTime field is useful for contracts. * </pre> * * <code>optional uint32 lock_time = 4;</code> * @param value The lockTime to set. * @return This builder for chaining. */ public Builder setLockTime(int value) { copyOnWrite(); instance.setLockTime(value); return this; } /** * <pre> * The nLockTime field is useful for contracts. * </pre> * * <code>optional uint32 lock_time = 4;</code> * @return This builder for chaining. */ public Builder clearLockTime() { copyOnWrite(); instance.clearLockTime(); return this; } /** * <pre> * millis since epoch the transaction was last updated * </pre> * * <code>optional int64 updated_at = 5;</code> * @return Whether the updatedAt field is set. */ @java.lang.Override public boolean hasUpdatedAt() { return instance.hasUpdatedAt(); } /** * <pre> * millis since epoch the transaction was last updated * </pre> * * <code>optional int64 updated_at = 5;</code> * @return The updatedAt. */ @java.lang.Override public long getUpdatedAt() { return instance.getUpdatedAt(); } /** * <pre> * millis since epoch the transaction was last updated * </pre> * * <code>optional int64 updated_at = 5;</code> * @param value The updatedAt to set. * @return This builder for chaining. */ public Builder setUpdatedAt(long value) { copyOnWrite(); instance.setUpdatedAt(value); return this; } /** * <pre> * millis since epoch the transaction was last updated * </pre> * * <code>optional int64 updated_at = 5;</code> * @return This builder for chaining. */ public Builder clearUpdatedAt() { copyOnWrite(); instance.clearUpdatedAt(); return this; } /** * <code>repeated .wallet.TransactionInput transaction_input = 6;</code> */ @java.lang.Override public java.util.List<org.bitcoinj.wallet.Protos.TransactionInput> getTransactionInputList() { return java.util.Collections.unmodifiableList( instance.getTransactionInputList()); } /** * <code>repeated .wallet.TransactionInput transaction_input = 6;</code> */ @java.lang.Override public int getTransactionInputCount() { return instance.getTransactionInputCount(); }/** * <code>repeated .wallet.TransactionInput transaction_input = 6;</code> */ @java.lang.Override public org.bitcoinj.wallet.Protos.TransactionInput getTransactionInput(int index) { return instance.getTransactionInput(index); } /** * <code>repeated .wallet.TransactionInput transaction_input = 6;</code> */ public Builder setTransactionInput( int index, org.bitcoinj.wallet.Protos.TransactionInput value) { copyOnWrite(); instance.setTransactionInput(index, value); return this; } /** * <code>repeated .wallet.TransactionInput transaction_input = 6;</code> */ public Builder setTransactionInput( int index, org.bitcoinj.wallet.Protos.TransactionInput.Builder builderForValue) { copyOnWrite(); instance.setTransactionInput(index, builderForValue.build()); return this; } /** * <code>repeated .wallet.TransactionInput transaction_input = 6;</code> */ public Builder addTransactionInput(org.bitcoinj.wallet.Protos.TransactionInput value) { copyOnWrite(); instance.addTransactionInput(value); return this; } /** * <code>repeated .wallet.TransactionInput transaction_input = 6;</code> */ public Builder addTransactionInput( int index, org.bitcoinj.wallet.Protos.TransactionInput value) { copyOnWrite(); instance.addTransactionInput(index, value); return this; } /** * <code>repeated .wallet.TransactionInput transaction_input = 6;</code> */ public Builder addTransactionInput( org.bitcoinj.wallet.Protos.TransactionInput.Builder builderForValue) { copyOnWrite(); instance.addTransactionInput(builderForValue.build()); return this; } /** * <code>repeated .wallet.TransactionInput transaction_input = 6;</code> */ public Builder addTransactionInput( int index, org.bitcoinj.wallet.Protos.TransactionInput.Builder builderForValue) { copyOnWrite(); instance.addTransactionInput(index, builderForValue.build()); return this; } /** * <code>repeated .wallet.TransactionInput transaction_input = 6;</code> */ public Builder addAllTransactionInput( java.lang.Iterable<? extends org.bitcoinj.wallet.Protos.TransactionInput> values) { copyOnWrite(); instance.addAllTransactionInput(values); return this; } /** * <code>repeated .wallet.TransactionInput transaction_input = 6;</code> */ public Builder clearTransactionInput() { copyOnWrite(); instance.clearTransactionInput(); return this; } /** * <code>repeated .wallet.TransactionInput transaction_input = 6;</code> */ public Builder removeTransactionInput(int index) { copyOnWrite(); instance.removeTransactionInput(index); return this; } /** * <code>repeated .wallet.TransactionOutput transaction_output = 7;</code> */ @java.lang.Override public java.util.List<org.bitcoinj.wallet.Protos.TransactionOutput> getTransactionOutputList() { return java.util.Collections.unmodifiableList( instance.getTransactionOutputList()); } /** * <code>repeated .wallet.TransactionOutput transaction_output = 7;</code> */ @java.lang.Override public int getTransactionOutputCount() { return instance.getTransactionOutputCount(); }/** * <code>repeated .wallet.TransactionOutput transaction_output = 7;</code> */ @java.lang.Override public org.bitcoinj.wallet.Protos.TransactionOutput getTransactionOutput(int index) { return instance.getTransactionOutput(index); } /** * <code>repeated .wallet.TransactionOutput transaction_output = 7;</code> */ public Builder setTransactionOutput( int index, org.bitcoinj.wallet.Protos.TransactionOutput value) { copyOnWrite(); instance.setTransactionOutput(index, value); return this; } /** * <code>repeated .wallet.TransactionOutput transaction_output = 7;</code> */ public Builder setTransactionOutput( int index, org.bitcoinj.wallet.Protos.TransactionOutput.Builder builderForValue) { copyOnWrite(); instance.setTransactionOutput(index, builderForValue.build()); return this; } /** * <code>repeated .wallet.TransactionOutput transaction_output = 7;</code> */ public Builder addTransactionOutput(org.bitcoinj.wallet.Protos.TransactionOutput value) { copyOnWrite(); instance.addTransactionOutput(value); return this; } /** * <code>repeated .wallet.TransactionOutput transaction_output = 7;</code> */ public Builder addTransactionOutput( int index, org.bitcoinj.wallet.Protos.TransactionOutput value) { copyOnWrite(); instance.addTransactionOutput(index, value); return this; } /** * <code>repeated .wallet.TransactionOutput transaction_output = 7;</code> */ public Builder addTransactionOutput( org.bitcoinj.wallet.Protos.TransactionOutput.Builder builderForValue) { copyOnWrite(); instance.addTransactionOutput(builderForValue.build()); return this; } /** * <code>repeated .wallet.TransactionOutput transaction_output = 7;</code> */ public Builder addTransactionOutput( int index, org.bitcoinj.wallet.Protos.TransactionOutput.Builder builderForValue) { copyOnWrite(); instance.addTransactionOutput(index, builderForValue.build()); return this; } /** * <code>repeated .wallet.TransactionOutput transaction_output = 7;</code> */ public Builder addAllTransactionOutput( java.lang.Iterable<? extends org.bitcoinj.wallet.Protos.TransactionOutput> values) { copyOnWrite(); instance.addAllTransactionOutput(values); return this; } /** * <code>repeated .wallet.TransactionOutput transaction_output = 7;</code> */ public Builder clearTransactionOutput() { copyOnWrite(); instance.clearTransactionOutput(); return this; } /** * <code>repeated .wallet.TransactionOutput transaction_output = 7;</code> */ public Builder removeTransactionOutput(int index) { copyOnWrite(); instance.removeTransactionOutput(index); return this; } /** * <pre> * A list of blocks in which the transaction has been observed (on any chain). Also, a number used to disambiguate * ordering within a block. * </pre> * * <code>repeated bytes block_hash = 8;</code> * @return A list containing the blockHash. */ @java.lang.Override public java.util.List<com.google.protobuf.ByteString> getBlockHashList() { return java.util.Collections.unmodifiableList( instance.getBlockHashList()); } /** * <pre> * A list of blocks in which the transaction has been observed (on any chain). Also, a number used to disambiguate * ordering within a block. * </pre> * * <code>repeated bytes block_hash = 8;</code> * @return The count of blockHash. */ @java.lang.Override public int getBlockHashCount() { return instance.getBlockHashCount(); } /** * <pre> * A list of blocks in which the transaction has been observed (on any chain). Also, a number used to disambiguate * ordering within a block. * </pre> * * <code>repeated bytes block_hash = 8;</code> * @param index The index of the element to return. * @return The blockHash at the given index. */ @java.lang.Override public com.google.protobuf.ByteString getBlockHash(int index) { return instance.getBlockHash(index); } /** * <pre> * A list of blocks in which the transaction has been observed (on any chain). Also, a number used to disambiguate * ordering within a block. * </pre> * * <code>repeated bytes block_hash = 8;</code> * @param value The blockHash to set. * @return This builder for chaining. */ public Builder setBlockHash( int index, com.google.protobuf.ByteString value) { copyOnWrite(); instance.setBlockHash(index, value); return this; } /** * <pre> * A list of blocks in which the transaction has been observed (on any chain). Also, a number used to disambiguate * ordering within a block. * </pre> * * <code>repeated bytes block_hash = 8;</code> * @param value The blockHash to add. * @return This builder for chaining. */ public Builder addBlockHash(com.google.protobuf.ByteString value) { copyOnWrite(); instance.addBlockHash(value); return this; } /** * <pre> * A list of blocks in which the transaction has been observed (on any chain). Also, a number used to disambiguate * ordering within a block. * </pre> * * <code>repeated bytes block_hash = 8;</code> * @param values The blockHash to add. * @return This builder for chaining. */ public Builder addAllBlockHash( java.lang.Iterable<? extends com.google.protobuf.ByteString> values) { copyOnWrite(); instance.addAllBlockHash(values); return this; } /** * <pre> * A list of blocks in which the transaction has been observed (on any chain). Also, a number used to disambiguate * ordering within a block. * </pre> * * <code>repeated bytes block_hash = 8;</code> * @return This builder for chaining. */ public Builder clearBlockHash() { copyOnWrite(); instance.clearBlockHash(); return this; } /** * <code>repeated int32 block_relativity_offsets = 11;</code> * @return A list containing the blockRelativityOffsets. */ @java.lang.Override public java.util.List<java.lang.Integer> getBlockRelativityOffsetsList() { return java.util.Collections.unmodifiableList( instance.getBlockRelativityOffsetsList()); } /** * <code>repeated int32 block_relativity_offsets = 11;</code> * @return The count of blockRelativityOffsets. */ @java.lang.Override public int getBlockRelativityOffsetsCount() { return instance.getBlockRelativityOffsetsCount(); } /** * <code>repeated int32 block_relativity_offsets = 11;</code> * @param index The index of the element to return. * @return The blockRelativityOffsets at the given index. */ @java.lang.Override public int getBlockRelativityOffsets(int index) { return instance.getBlockRelativityOffsets(index); } /** * <code>repeated int32 block_relativity_offsets = 11;</code> * @param value The blockRelativityOffsets to set. * @return This builder for chaining. */ public Builder setBlockRelativityOffsets( int index, int value) { copyOnWrite(); instance.setBlockRelativityOffsets(index, value); return this; } /** * <code>repeated int32 block_relativity_offsets = 11;</code> * @param value The blockRelativityOffsets to add. * @return This builder for chaining. */ public Builder addBlockRelativityOffsets(int value) { copyOnWrite(); instance.addBlockRelativityOffsets(value); return this; } /** * <code>repeated int32 block_relativity_offsets = 11;</code> * @param values The blockRelativityOffsets to add. * @return This builder for chaining. */ public Builder addAllBlockRelativityOffsets( java.lang.Iterable<? extends java.lang.Integer> values) { copyOnWrite(); instance.addAllBlockRelativityOffsets(values); return this; } /** * <code>repeated int32 block_relativity_offsets = 11;</code> * @return This builder for chaining. */ public Builder clearBlockRelativityOffsets() { copyOnWrite(); instance.clearBlockRelativityOffsets(); return this; } /** * <pre> * Data describing where the transaction is in the chain. * </pre> * * <code>optional .wallet.TransactionConfidence confidence = 9;</code> */ @java.lang.Override public boolean hasConfidence() { return instance.hasConfidence(); } /** * <pre> * Data describing where the transaction is in the chain. * </pre> * * <code>optional .wallet.TransactionConfidence confidence = 9;</code> */ @java.lang.Override public org.bitcoinj.wallet.Protos.TransactionConfidence getConfidence() { return instance.getConfidence(); } /** * <pre> * Data describing where the transaction is in the chain. * </pre> * * <code>optional .wallet.TransactionConfidence confidence = 9;</code> */ public Builder setConfidence(org.bitcoinj.wallet.Protos.TransactionConfidence value) { copyOnWrite(); instance.setConfidence(value); return this; } /** * <pre> * Data describing where the transaction is in the chain. * </pre> * * <code>optional .wallet.TransactionConfidence confidence = 9;</code> */ public Builder setConfidence( org.bitcoinj.wallet.Protos.TransactionConfidence.Builder builderForValue) { copyOnWrite(); instance.setConfidence(builderForValue.build()); return this; } /** * <pre> * Data describing where the transaction is in the chain. * </pre> * * <code>optional .wallet.TransactionConfidence confidence = 9;</code> */ public Builder mergeConfidence(org.bitcoinj.wallet.Protos.TransactionConfidence value) { copyOnWrite(); instance.mergeConfidence(value); return this; } /** * <pre> * Data describing where the transaction is in the chain. * </pre> * * <code>optional .wallet.TransactionConfidence confidence = 9;</code> */ public Builder clearConfidence() { copyOnWrite(); instance.clearConfidence(); return this; } /** * <code>optional .wallet.Transaction.Purpose purpose = 10 [default = UNKNOWN];</code> * @return Whether the purpose field is set. */ @java.lang.Override public boolean hasPurpose() { return instance.hasPurpose(); } /** * <code>optional .wallet.Transaction.Purpose purpose = 10 [default = UNKNOWN];</code> * @return The purpose. */ @java.lang.Override public org.bitcoinj.wallet.Protos.Transaction.Purpose getPurpose() { return instance.getPurpose(); } /** * <code>optional .wallet.Transaction.Purpose purpose = 10 [default = UNKNOWN];</code> * @param value The enum numeric value on the wire for purpose to set. * @return This builder for chaining. */ public Builder setPurpose(org.bitcoinj.wallet.Protos.Transaction.Purpose value) { copyOnWrite(); instance.setPurpose(value); return this; } /** * <code>optional .wallet.Transaction.Purpose purpose = 10 [default = UNKNOWN];</code> * @return This builder for chaining. */ public Builder clearPurpose() { copyOnWrite(); instance.clearPurpose(); return this; } /** * <pre> * Exchange rate that was valid when the transaction was sent. * </pre> * * <code>optional .wallet.ExchangeRate exchange_rate = 12;</code> */ @java.lang.Override public boolean hasExchangeRate() { return instance.hasExchangeRate(); } /** * <pre> * Exchange rate that was valid when the transaction was sent. * </pre> * * <code>optional .wallet.ExchangeRate exchange_rate = 12;</code> */ @java.lang.Override public org.bitcoinj.wallet.Protos.ExchangeRate getExchangeRate() { return instance.getExchangeRate(); } /** * <pre> * Exchange rate that was valid when the transaction was sent. * </pre> * * <code>optional .wallet.ExchangeRate exchange_rate = 12;</code> */ public Builder setExchangeRate(org.bitcoinj.wallet.Protos.ExchangeRate value) { copyOnWrite(); instance.setExchangeRate(value); return this; } /** * <pre> * Exchange rate that was valid when the transaction was sent. * </pre> * * <code>optional .wallet.ExchangeRate exchange_rate = 12;</code> */ public Builder setExchangeRate( org.bitcoinj.wallet.Protos.ExchangeRate.Builder builderForValue) { copyOnWrite(); instance.setExchangeRate(builderForValue.build()); return this; } /** * <pre> * Exchange rate that was valid when the transaction was sent. * </pre> * * <code>optional .wallet.ExchangeRate exchange_rate = 12;</code> */ public Builder mergeExchangeRate(org.bitcoinj.wallet.Protos.ExchangeRate value) { copyOnWrite(); instance.mergeExchangeRate(value); return this; } /** * <pre> * Exchange rate that was valid when the transaction was sent. * </pre> * * <code>optional .wallet.ExchangeRate exchange_rate = 12;</code> */ public Builder clearExchangeRate() { copyOnWrite(); instance.clearExchangeRate(); return this; } /** * <pre> * Memo of the transaction. It can be used to record the memo of the payment request that initiated the * transaction. * </pre> * * <code>optional string memo = 13;</code> * @return Whether the memo field is set. */ @java.lang.Override public boolean hasMemo() { return instance.hasMemo(); } /** * <pre> * Memo of the transaction. It can be used to record the memo of the payment request that initiated the * transaction. * </pre> * * <code>optional string memo = 13;</code> * @return The memo. */ @java.lang.Override public java.lang.String getMemo() { return instance.getMemo(); } /** * <pre> * Memo of the transaction. It can be used to record the memo of the payment request that initiated the * transaction. * </pre> * * <code>optional string memo = 13;</code> * @return The bytes for memo. */ @java.lang.Override public com.google.protobuf.ByteString getMemoBytes() { return instance.getMemoBytes(); } /** * <pre> * Memo of the transaction. It can be used to record the memo of the payment request that initiated the * transaction. * </pre> * * <code>optional string memo = 13;</code> * @param value The memo to set. * @return This builder for chaining. */ public Builder setMemo( java.lang.String value) { copyOnWrite(); instance.setMemo(value); return this; } /** * <pre> * Memo of the transaction. It can be used to record the memo of the payment request that initiated the * transaction. * </pre> * * <code>optional string memo = 13;</code> * @return This builder for chaining. */ public Builder clearMemo() { copyOnWrite(); instance.clearMemo(); return this; } /** * <pre> * Memo of the transaction. It can be used to record the memo of the payment request that initiated the * transaction. * </pre> * * <code>optional string memo = 13;</code> * @param value The bytes for memo to set. * @return This builder for chaining. */ public Builder setMemoBytes( com.google.protobuf.ByteString value) { copyOnWrite(); instance.setMemoBytes(value); return this; } // @@protoc_insertion_point(builder_scope:wallet.Transaction) } private byte memoizedIsInitialized = 2; @java.lang.Override @java.lang.SuppressWarnings({"unchecked", "fallthrough"}) protected final java.lang.Object dynamicMethod( com.google.protobuf.GeneratedMessageLite.MethodToInvoke method, java.lang.Object arg0, java.lang.Object arg1) { switch (method) { case NEW_MUTABLE_INSTANCE: { return new org.bitcoinj.wallet.Protos.Transaction(); } case NEW_BUILDER: { return new Builder(); } case BUILD_MESSAGE_INFO: { java.lang.Object[] objects = new java.lang.Object[] { "bitField0_", "version_", "hash_", "pool_", org.bitcoinj.wallet.Protos.Transaction.Pool.internalGetVerifier(), "lockTime_", "updatedAt_", "transactionInput_", org.bitcoinj.wallet.Protos.TransactionInput.class, "transactionOutput_", org.bitcoinj.wallet.Protos.TransactionOutput.class, "blockHash_", "confidence_", "purpose_", org.bitcoinj.wallet.Protos.Transaction.Purpose.internalGetVerifier(), "blockRelativityOffsets_", "exchangeRate_", "memo_", }; java.lang.String info = "\u0001\r\u0000\u0001\u0001\r\r\u0000\u0004\u0006\u0001\u1504\u0000\u0002\u150a\u0001" + "\u0003\u100c\u0002\u0004\u100b\u0003\u0005\u1002\u0004\u0006\u041b\u0007\u041b\b" + "\u001c\t\u1409\u0005\n\u100c\u0006\u000b\u0016\f\u1409\u0007\r\u1008\b"; return newMessageInfo(DEFAULT_INSTANCE, info, objects); } // fall through case GET_DEFAULT_INSTANCE: { return DEFAULT_INSTANCE; } case GET_PARSER: { com.google.protobuf.Parser<org.bitcoinj.wallet.Protos.Transaction> parser = PARSER; if (parser == null) { synchronized (org.bitcoinj.wallet.Protos.Transaction.class) { parser = PARSER; if (parser == null) { parser = new DefaultInstanceBasedParser<org.bitcoinj.wallet.Protos.Transaction>( DEFAULT_INSTANCE); PARSER = parser; } } } return parser; } case GET_MEMOIZED_IS_INITIALIZED: { return memoizedIsInitialized; } case SET_MEMOIZED_IS_INITIALIZED: { memoizedIsInitialized = (byte) (arg0 == null ? 0 : 1); return null; } } throw new UnsupportedOperationException(); } // @@protoc_insertion_point(class_scope:wallet.Transaction) private static final org.bitcoinj.wallet.Protos.Transaction DEFAULT_INSTANCE; static { Transaction defaultInstance = new Transaction(); // New instances are implicitly immutable so no need to make // immutable. DEFAULT_INSTANCE = defaultInstance; com.google.protobuf.GeneratedMessageLite.registerDefaultInstance( Transaction.class, defaultInstance); } public static org.bitcoinj.wallet.Protos.Transaction getDefaultInstance() { return DEFAULT_INSTANCE; } private static volatile com.google.protobuf.Parser<Transaction> PARSER; public static com.google.protobuf.Parser<Transaction> parser() { return DEFAULT_INSTANCE.getParserForType(); } } public interface ScryptParametersOrBuilder extends // @@protoc_insertion_point(interface_extends:wallet.ScryptParameters) com.google.protobuf.MessageLiteOrBuilder { /** * <pre> * Salt to use in generation of the wallet password (8 bytes) * </pre> * * <code>required bytes salt = 1;</code> * @return Whether the salt field is set. */ boolean hasSalt(); /** * <pre> * Salt to use in generation of the wallet password (8 bytes) * </pre> * * <code>required bytes salt = 1;</code> * @return The salt. */ com.google.protobuf.ByteString getSalt(); /** * <pre> * CPU/ memory cost parameter * </pre> * * <code>optional int64 n = 2 [default = 16384];</code> * @return Whether the n field is set. */ boolean hasN(); /** * <pre> * CPU/ memory cost parameter * </pre> * * <code>optional int64 n = 2 [default = 16384];</code> * @return The n. */ long getN(); /** * <pre> * Block size parameter * </pre> * * <code>optional int32 r = 3 [default = 8];</code> * @return Whether the r field is set. */ boolean hasR(); /** * <pre> * Block size parameter * </pre> * * <code>optional int32 r = 3 [default = 8];</code> * @return The r. */ int getR(); /** * <pre> * Parallelisation parameter * </pre> * * <code>optional int32 p = 4 [default = 1];</code> * @return Whether the p field is set. */ boolean hasP(); /** * <pre> * Parallelisation parameter * </pre> * * <code>optional int32 p = 4 [default = 1];</code> * @return The p. */ int getP(); } /** * <pre> ** The parameters used in the scrypt key derivation function. * The default values are taken from http://www.tarsnap.com/scrypt/scrypt-slides.pdf. * They can be increased - n is the number of iterations performed and * r and p can be used to tweak the algorithm - see: * http://stackoverflow.com/questions/11126315/what-are-optimal-scrypt-work-factors * </pre> * * Protobuf type {@code wallet.ScryptParameters} */ public static final class ScryptParameters extends com.google.protobuf.GeneratedMessageLite< ScryptParameters, ScryptParameters.Builder> implements // @@protoc_insertion_point(message_implements:wallet.ScryptParameters) ScryptParametersOrBuilder { private ScryptParameters() { salt_ = com.google.protobuf.ByteString.EMPTY; n_ = 16384L; r_ = 8; p_ = 1; } private int bitField0_; public static final int SALT_FIELD_NUMBER = 1; private com.google.protobuf.ByteString salt_; /** * <pre> * Salt to use in generation of the wallet password (8 bytes) * </pre> * * <code>required bytes salt = 1;</code> * @return Whether the salt field is set. */ @java.lang.Override public boolean hasSalt() { return ((bitField0_ & 0x00000001) != 0); } /** * <pre> * Salt to use in generation of the wallet password (8 bytes) * </pre> * * <code>required bytes salt = 1;</code> * @return The salt. */ @java.lang.Override public com.google.protobuf.ByteString getSalt() { return salt_; } /** * <pre> * Salt to use in generation of the wallet password (8 bytes) * </pre> * * <code>required bytes salt = 1;</code> * @param value The salt to set. */ private void setSalt(com.google.protobuf.ByteString value) { java.lang.Class<?> valueClass = value.getClass(); bitField0_ |= 0x00000001; salt_ = value; } /** * <pre> * Salt to use in generation of the wallet password (8 bytes) * </pre> * * <code>required bytes salt = 1;</code> */ private void clearSalt() { bitField0_ = (bitField0_ & ~0x00000001); salt_ = getDefaultInstance().getSalt(); } public static final int N_FIELD_NUMBER = 2; private long n_; /** * <pre> * CPU/ memory cost parameter * </pre> * * <code>optional int64 n = 2 [default = 16384];</code> * @return Whether the n field is set. */ @java.lang.Override public boolean hasN() { return ((bitField0_ & 0x00000002) != 0); } /** * <pre> * CPU/ memory cost parameter * </pre> * * <code>optional int64 n = 2 [default = 16384];</code> * @return The n. */ @java.lang.Override public long getN() { return n_; } /** * <pre> * CPU/ memory cost parameter * </pre> * * <code>optional int64 n = 2 [default = 16384];</code> * @param value The n to set. */ private void setN(long value) { bitField0_ |= 0x00000002; n_ = value; } /** * <pre> * CPU/ memory cost parameter * </pre> * * <code>optional int64 n = 2 [default = 16384];</code> */ private void clearN() { bitField0_ = (bitField0_ & ~0x00000002); n_ = 16384L; } public static final int R_FIELD_NUMBER = 3; private int r_; /** * <pre> * Block size parameter * </pre> * * <code>optional int32 r = 3 [default = 8];</code> * @return Whether the r field is set. */ @java.lang.Override public boolean hasR() { return ((bitField0_ & 0x00000004) != 0); } /** * <pre> * Block size parameter * </pre> * * <code>optional int32 r = 3 [default = 8];</code> * @return The r. */ @java.lang.Override public int getR() { return r_; } /** * <pre> * Block size parameter * </pre> * * <code>optional int32 r = 3 [default = 8];</code> * @param value The r to set. */ private void setR(int value) { bitField0_ |= 0x00000004; r_ = value; } /** * <pre> * Block size parameter * </pre> * * <code>optional int32 r = 3 [default = 8];</code> */ private void clearR() { bitField0_ = (bitField0_ & ~0x00000004); r_ = 8; } public static final int P_FIELD_NUMBER = 4; private int p_; /** * <pre> * Parallelisation parameter * </pre> * * <code>optional int32 p = 4 [default = 1];</code> * @return Whether the p field is set. */ @java.lang.Override public boolean hasP() { return ((bitField0_ & 0x00000008) != 0); } /** * <pre> * Parallelisation parameter * </pre> * * <code>optional int32 p = 4 [default = 1];</code> * @return The p. */ @java.lang.Override public int getP() { return p_; } /** * <pre> * Parallelisation parameter * </pre> * * <code>optional int32 p = 4 [default = 1];</code> * @param value The p to set. */ private void setP(int value) { bitField0_ |= 0x00000008; p_ = value; } /** * <pre> * Parallelisation parameter * </pre> * * <code>optional int32 p = 4 [default = 1];</code> */ private void clearP() { bitField0_ = (bitField0_ & ~0x00000008); p_ = 1; } public static org.bitcoinj.wallet.Protos.ScryptParameters parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return com.google.protobuf.GeneratedMessageLite.parseFrom( DEFAULT_INSTANCE, data); } public static org.bitcoinj.wallet.Protos.ScryptParameters parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return com.google.protobuf.GeneratedMessageLite.parseFrom( DEFAULT_INSTANCE, data, extensionRegistry); } public static org.bitcoinj.wallet.Protos.ScryptParameters parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return com.google.protobuf.GeneratedMessageLite.parseFrom( DEFAULT_INSTANCE, data); } public static org.bitcoinj.wallet.Protos.ScryptParameters parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return com.google.protobuf.GeneratedMessageLite.parseFrom( DEFAULT_INSTANCE, data, extensionRegistry); } public static org.bitcoinj.wallet.Protos.ScryptParameters parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return com.google.protobuf.GeneratedMessageLite.parseFrom( DEFAULT_INSTANCE, data); } public static org.bitcoinj.wallet.Protos.ScryptParameters parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return com.google.protobuf.GeneratedMessageLite.parseFrom( DEFAULT_INSTANCE, data, extensionRegistry); } public static org.bitcoinj.wallet.Protos.ScryptParameters parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageLite.parseFrom( DEFAULT_INSTANCE, input); } public static org.bitcoinj.wallet.Protos.ScryptParameters parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageLite.parseFrom( DEFAULT_INSTANCE, input, extensionRegistry); } public static org.bitcoinj.wallet.Protos.ScryptParameters parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return parseDelimitedFrom(DEFAULT_INSTANCE, input); } public static org.bitcoinj.wallet.Protos.ScryptParameters parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return parseDelimitedFrom(DEFAULT_INSTANCE, input, extensionRegistry); } public static org.bitcoinj.wallet.Protos.ScryptParameters parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageLite.parseFrom( DEFAULT_INSTANCE, input); } public static org.bitcoinj.wallet.Protos.ScryptParameters parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageLite.parseFrom( DEFAULT_INSTANCE, input, extensionRegistry); } public static Builder newBuilder() { return (Builder) DEFAULT_INSTANCE.createBuilder(); } public static Builder newBuilder(org.bitcoinj.wallet.Protos.ScryptParameters prototype) { return (Builder) DEFAULT_INSTANCE.createBuilder(prototype); } /** * <pre> ** The parameters used in the scrypt key derivation function. * The default values are taken from http://www.tarsnap.com/scrypt/scrypt-slides.pdf. * They can be increased - n is the number of iterations performed and * r and p can be used to tweak the algorithm - see: * http://stackoverflow.com/questions/11126315/what-are-optimal-scrypt-work-factors * </pre> * * Protobuf type {@code wallet.ScryptParameters} */ public static final class Builder extends com.google.protobuf.GeneratedMessageLite.Builder< org.bitcoinj.wallet.Protos.ScryptParameters, Builder> implements // @@protoc_insertion_point(builder_implements:wallet.ScryptParameters) org.bitcoinj.wallet.Protos.ScryptParametersOrBuilder { // Construct using org.bitcoinj.wallet.Protos.ScryptParameters.newBuilder() private Builder() { super(DEFAULT_INSTANCE); } /** * <pre> * Salt to use in generation of the wallet password (8 bytes) * </pre> * * <code>required bytes salt = 1;</code> * @return Whether the salt field is set. */ @java.lang.Override public boolean hasSalt() { return instance.hasSalt(); } /** * <pre> * Salt to use in generation of the wallet password (8 bytes) * </pre> * * <code>required bytes salt = 1;</code> * @return The salt. */ @java.lang.Override public com.google.protobuf.ByteString getSalt() { return instance.getSalt(); } /** * <pre> * Salt to use in generation of the wallet password (8 bytes) * </pre> * * <code>required bytes salt = 1;</code> * @param value The salt to set. * @return This builder for chaining. */ public Builder setSalt(com.google.protobuf.ByteString value) { copyOnWrite(); instance.setSalt(value); return this; } /** * <pre> * Salt to use in generation of the wallet password (8 bytes) * </pre> * * <code>required bytes salt = 1;</code> * @return This builder for chaining. */ public Builder clearSalt() { copyOnWrite(); instance.clearSalt(); return this; } /** * <pre> * CPU/ memory cost parameter * </pre> * * <code>optional int64 n = 2 [default = 16384];</code> * @return Whether the n field is set. */ @java.lang.Override public boolean hasN() { return instance.hasN(); } /** * <pre> * CPU/ memory cost parameter * </pre> * * <code>optional int64 n = 2 [default = 16384];</code> * @return The n. */ @java.lang.Override public long getN() { return instance.getN(); } /** * <pre> * CPU/ memory cost parameter * </pre> * * <code>optional int64 n = 2 [default = 16384];</code> * @param value The n to set. * @return This builder for chaining. */ public Builder setN(long value) { copyOnWrite(); instance.setN(value); return this; } /** * <pre> * CPU/ memory cost parameter * </pre> * * <code>optional int64 n = 2 [default = 16384];</code> * @return This builder for chaining. */ public Builder clearN() { copyOnWrite(); instance.clearN(); return this; } /** * <pre> * Block size parameter * </pre> * * <code>optional int32 r = 3 [default = 8];</code> * @return Whether the r field is set. */ @java.lang.Override public boolean hasR() { return instance.hasR(); } /** * <pre> * Block size parameter * </pre> * * <code>optional int32 r = 3 [default = 8];</code> * @return The r. */ @java.lang.Override public int getR() { return instance.getR(); } /** * <pre> * Block size parameter * </pre> * * <code>optional int32 r = 3 [default = 8];</code> * @param value The r to set. * @return This builder for chaining. */ public Builder setR(int value) { copyOnWrite(); instance.setR(value); return this; } /** * <pre> * Block size parameter * </pre> * * <code>optional int32 r = 3 [default = 8];</code> * @return This builder for chaining. */ public Builder clearR() { copyOnWrite(); instance.clearR(); return this; } /** * <pre> * Parallelisation parameter * </pre> * * <code>optional int32 p = 4 [default = 1];</code> * @return Whether the p field is set. */ @java.lang.Override public boolean hasP() { return instance.hasP(); } /** * <pre> * Parallelisation parameter * </pre> * * <code>optional int32 p = 4 [default = 1];</code> * @return The p. */ @java.lang.Override public int getP() { return instance.getP(); } /** * <pre> * Parallelisation parameter * </pre> * * <code>optional int32 p = 4 [default = 1];</code> * @param value The p to set. * @return This builder for chaining. */ public Builder setP(int value) { copyOnWrite(); instance.setP(value); return this; } /** * <pre> * Parallelisation parameter * </pre> * * <code>optional int32 p = 4 [default = 1];</code> * @return This builder for chaining. */ public Builder clearP() { copyOnWrite(); instance.clearP(); return this; } // @@protoc_insertion_point(builder_scope:wallet.ScryptParameters) } private byte memoizedIsInitialized = 2; @java.lang.Override @java.lang.SuppressWarnings({"unchecked", "fallthrough"}) protected final java.lang.Object dynamicMethod( com.google.protobuf.GeneratedMessageLite.MethodToInvoke method, java.lang.Object arg0, java.lang.Object arg1) { switch (method) { case NEW_MUTABLE_INSTANCE: { return new org.bitcoinj.wallet.Protos.ScryptParameters(); } case NEW_BUILDER: { return new Builder(); } case BUILD_MESSAGE_INFO: { java.lang.Object[] objects = new java.lang.Object[] { "bitField0_", "salt_", "n_", "r_", "p_", }; java.lang.String info = "\u0001\u0004\u0000\u0001\u0001\u0004\u0004\u0000\u0000\u0001\u0001\u150a\u0000\u0002" + "\u1002\u0001\u0003\u1004\u0002\u0004\u1004\u0003"; return newMessageInfo(DEFAULT_INSTANCE, info, objects); } // fall through case GET_DEFAULT_INSTANCE: { return DEFAULT_INSTANCE; } case GET_PARSER: { com.google.protobuf.Parser<org.bitcoinj.wallet.Protos.ScryptParameters> parser = PARSER; if (parser == null) { synchronized (org.bitcoinj.wallet.Protos.ScryptParameters.class) { parser = PARSER; if (parser == null) { parser = new DefaultInstanceBasedParser<org.bitcoinj.wallet.Protos.ScryptParameters>( DEFAULT_INSTANCE); PARSER = parser; } } } return parser; } case GET_MEMOIZED_IS_INITIALIZED: { return memoizedIsInitialized; } case SET_MEMOIZED_IS_INITIALIZED: { memoizedIsInitialized = (byte) (arg0 == null ? 0 : 1); return null; } } throw new UnsupportedOperationException(); } // @@protoc_insertion_point(class_scope:wallet.ScryptParameters) private static final org.bitcoinj.wallet.Protos.ScryptParameters DEFAULT_INSTANCE; static { ScryptParameters defaultInstance = new ScryptParameters(); // New instances are implicitly immutable so no need to make // immutable. DEFAULT_INSTANCE = defaultInstance; com.google.protobuf.GeneratedMessageLite.registerDefaultInstance( ScryptParameters.class, defaultInstance); } public static org.bitcoinj.wallet.Protos.ScryptParameters getDefaultInstance() { return DEFAULT_INSTANCE; } private static volatile com.google.protobuf.Parser<ScryptParameters> PARSER; public static com.google.protobuf.Parser<ScryptParameters> parser() { return DEFAULT_INSTANCE.getParserForType(); } } public interface ExtensionOrBuilder extends // @@protoc_insertion_point(interface_extends:wallet.Extension) com.google.protobuf.MessageLiteOrBuilder { /** * <pre> * like org.whatever.foo.bar * </pre> * * <code>required string id = 1;</code> * @return Whether the id field is set. */ boolean hasId(); /** * <pre> * like org.whatever.foo.bar * </pre> * * <code>required string id = 1;</code> * @return The id. */ java.lang.String getId(); /** * <pre> * like org.whatever.foo.bar * </pre> * * <code>required string id = 1;</code> * @return The bytes for id. */ com.google.protobuf.ByteString getIdBytes(); /** * <code>required bytes data = 2;</code> * @return Whether the data field is set. */ boolean hasData(); /** * <code>required bytes data = 2;</code> * @return The data. */ com.google.protobuf.ByteString getData(); /** * <pre> * If we do not understand a mandatory extension, abort to prevent data loss. * For example, this could be applied to a new type of holding, such as a contract, where * dropping of an extension in a read/write cycle could cause loss of value. * </pre> * * <code>required bool mandatory = 3;</code> * @return Whether the mandatory field is set. */ boolean hasMandatory(); /** * <pre> * If we do not understand a mandatory extension, abort to prevent data loss. * For example, this could be applied to a new type of holding, such as a contract, where * dropping of an extension in a read/write cycle could cause loss of value. * </pre> * * <code>required bool mandatory = 3;</code> * @return The mandatory. */ boolean getMandatory(); } /** * <pre> ** An extension to the wallet * </pre> * * Protobuf type {@code wallet.Extension} */ public static final class Extension extends com.google.protobuf.GeneratedMessageLite< Extension, Extension.Builder> implements // @@protoc_insertion_point(message_implements:wallet.Extension) ExtensionOrBuilder { private Extension() { id_ = ""; data_ = com.google.protobuf.ByteString.EMPTY; } private int bitField0_; public static final int ID_FIELD_NUMBER = 1; private java.lang.String id_; /** * <pre> * like org.whatever.foo.bar * </pre> * * <code>required string id = 1;</code> * @return Whether the id field is set. */ @java.lang.Override public boolean hasId() { return ((bitField0_ & 0x00000001) != 0); } /** * <pre> * like org.whatever.foo.bar * </pre> * * <code>required string id = 1;</code> * @return The id. */ @java.lang.Override public java.lang.String getId() { return id_; } /** * <pre> * like org.whatever.foo.bar * </pre> * * <code>required string id = 1;</code> * @return The bytes for id. */ @java.lang.Override public com.google.protobuf.ByteString getIdBytes() { return com.google.protobuf.ByteString.copyFromUtf8(id_); } /** * <pre> * like org.whatever.foo.bar * </pre> * * <code>required string id = 1;</code> * @param value The id to set. */ private void setId( java.lang.String value) { java.lang.Class<?> valueClass = value.getClass(); bitField0_ |= 0x00000001; id_ = value; } /** * <pre> * like org.whatever.foo.bar * </pre> * * <code>required string id = 1;</code> */ private void clearId() { bitField0_ = (bitField0_ & ~0x00000001); id_ = getDefaultInstance().getId(); } /** * <pre> * like org.whatever.foo.bar * </pre> * * <code>required string id = 1;</code> * @param value The bytes for id to set. */ private void setIdBytes( com.google.protobuf.ByteString value) { id_ = value.toStringUtf8(); bitField0_ |= 0x00000001; } public static final int DATA_FIELD_NUMBER = 2; private com.google.protobuf.ByteString data_; /** * <code>required bytes data = 2;</code> * @return Whether the data field is set. */ @java.lang.Override public boolean hasData() { return ((bitField0_ & 0x00000002) != 0); } /** * <code>required bytes data = 2;</code> * @return The data. */ @java.lang.Override public com.google.protobuf.ByteString getData() { return data_; } /** * <code>required bytes data = 2;</code> * @param value The data to set. */ private void setData(com.google.protobuf.ByteString value) { java.lang.Class<?> valueClass = value.getClass(); bitField0_ |= 0x00000002; data_ = value; } /** * <code>required bytes data = 2;</code> */ private void clearData() { bitField0_ = (bitField0_ & ~0x00000002); data_ = getDefaultInstance().getData(); } public static final int MANDATORY_FIELD_NUMBER = 3; private boolean mandatory_; /** * <pre> * If we do not understand a mandatory extension, abort to prevent data loss. * For example, this could be applied to a new type of holding, such as a contract, where * dropping of an extension in a read/write cycle could cause loss of value. * </pre> * * <code>required bool mandatory = 3;</code> * @return Whether the mandatory field is set. */ @java.lang.Override public boolean hasMandatory() { return ((bitField0_ & 0x00000004) != 0); } /** * <pre> * If we do not understand a mandatory extension, abort to prevent data loss. * For example, this could be applied to a new type of holding, such as a contract, where * dropping of an extension in a read/write cycle could cause loss of value. * </pre> * * <code>required bool mandatory = 3;</code> * @return The mandatory. */ @java.lang.Override public boolean getMandatory() { return mandatory_; } /** * <pre> * If we do not understand a mandatory extension, abort to prevent data loss. * For example, this could be applied to a new type of holding, such as a contract, where * dropping of an extension in a read/write cycle could cause loss of value. * </pre> * * <code>required bool mandatory = 3;</code> * @param value The mandatory to set. */ private void setMandatory(boolean value) { bitField0_ |= 0x00000004; mandatory_ = value; } /** * <pre> * If we do not understand a mandatory extension, abort to prevent data loss. * For example, this could be applied to a new type of holding, such as a contract, where * dropping of an extension in a read/write cycle could cause loss of value. * </pre> * * <code>required bool mandatory = 3;</code> */ private void clearMandatory() { bitField0_ = (bitField0_ & ~0x00000004); mandatory_ = false; } public static org.bitcoinj.wallet.Protos.Extension parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return com.google.protobuf.GeneratedMessageLite.parseFrom( DEFAULT_INSTANCE, data); } public static org.bitcoinj.wallet.Protos.Extension parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return com.google.protobuf.GeneratedMessageLite.parseFrom( DEFAULT_INSTANCE, data, extensionRegistry); } public static org.bitcoinj.wallet.Protos.Extension parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return com.google.protobuf.GeneratedMessageLite.parseFrom( DEFAULT_INSTANCE, data); } public static org.bitcoinj.wallet.Protos.Extension parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return com.google.protobuf.GeneratedMessageLite.parseFrom( DEFAULT_INSTANCE, data, extensionRegistry); } public static org.bitcoinj.wallet.Protos.Extension parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return com.google.protobuf.GeneratedMessageLite.parseFrom( DEFAULT_INSTANCE, data); } public static org.bitcoinj.wallet.Protos.Extension parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return com.google.protobuf.GeneratedMessageLite.parseFrom( DEFAULT_INSTANCE, data, extensionRegistry); } public static org.bitcoinj.wallet.Protos.Extension parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageLite.parseFrom( DEFAULT_INSTANCE, input); } public static org.bitcoinj.wallet.Protos.Extension parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageLite.parseFrom( DEFAULT_INSTANCE, input, extensionRegistry); } public static org.bitcoinj.wallet.Protos.Extension parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return parseDelimitedFrom(DEFAULT_INSTANCE, input); } public static org.bitcoinj.wallet.Protos.Extension parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return parseDelimitedFrom(DEFAULT_INSTANCE, input, extensionRegistry); } public static org.bitcoinj.wallet.Protos.Extension parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageLite.parseFrom( DEFAULT_INSTANCE, input); } public static org.bitcoinj.wallet.Protos.Extension parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageLite.parseFrom( DEFAULT_INSTANCE, input, extensionRegistry); } public static Builder newBuilder() { return (Builder) DEFAULT_INSTANCE.createBuilder(); } public static Builder newBuilder(org.bitcoinj.wallet.Protos.Extension prototype) { return (Builder) DEFAULT_INSTANCE.createBuilder(prototype); } /** * <pre> ** An extension to the wallet * </pre> * * Protobuf type {@code wallet.Extension} */ public static final class Builder extends com.google.protobuf.GeneratedMessageLite.Builder< org.bitcoinj.wallet.Protos.Extension, Builder> implements // @@protoc_insertion_point(builder_implements:wallet.Extension) org.bitcoinj.wallet.Protos.ExtensionOrBuilder { // Construct using org.bitcoinj.wallet.Protos.Extension.newBuilder() private Builder() { super(DEFAULT_INSTANCE); } /** * <pre> * like org.whatever.foo.bar * </pre> * * <code>required string id = 1;</code> * @return Whether the id field is set. */ @java.lang.Override public boolean hasId() { return instance.hasId(); } /** * <pre> * like org.whatever.foo.bar * </pre> * * <code>required string id = 1;</code> * @return The id. */ @java.lang.Override public java.lang.String getId() { return instance.getId(); } /** * <pre> * like org.whatever.foo.bar * </pre> * * <code>required string id = 1;</code> * @return The bytes for id. */ @java.lang.Override public com.google.protobuf.ByteString getIdBytes() { return instance.getIdBytes(); } /** * <pre> * like org.whatever.foo.bar * </pre> * * <code>required string id = 1;</code> * @param value The id to set. * @return This builder for chaining. */ public Builder setId( java.lang.String value) { copyOnWrite(); instance.setId(value); return this; } /** * <pre> * like org.whatever.foo.bar * </pre> * * <code>required string id = 1;</code> * @return This builder for chaining. */ public Builder clearId() { copyOnWrite(); instance.clearId(); return this; } /** * <pre> * like org.whatever.foo.bar * </pre> * * <code>required string id = 1;</code> * @param value The bytes for id to set. * @return This builder for chaining. */ public Builder setIdBytes( com.google.protobuf.ByteString value) { copyOnWrite(); instance.setIdBytes(value); return this; } /** * <code>required bytes data = 2;</code> * @return Whether the data field is set. */ @java.lang.Override public boolean hasData() { return instance.hasData(); } /** * <code>required bytes data = 2;</code> * @return The data. */ @java.lang.Override public com.google.protobuf.ByteString getData() { return instance.getData(); } /** * <code>required bytes data = 2;</code> * @param value The data to set. * @return This builder for chaining. */ public Builder setData(com.google.protobuf.ByteString value) { copyOnWrite(); instance.setData(value); return this; } /** * <code>required bytes data = 2;</code> * @return This builder for chaining. */ public Builder clearData() { copyOnWrite(); instance.clearData(); return this; } /** * <pre> * If we do not understand a mandatory extension, abort to prevent data loss. * For example, this could be applied to a new type of holding, such as a contract, where * dropping of an extension in a read/write cycle could cause loss of value. * </pre> * * <code>required bool mandatory = 3;</code> * @return Whether the mandatory field is set. */ @java.lang.Override public boolean hasMandatory() { return instance.hasMandatory(); } /** * <pre> * If we do not understand a mandatory extension, abort to prevent data loss. * For example, this could be applied to a new type of holding, such as a contract, where * dropping of an extension in a read/write cycle could cause loss of value. * </pre> * * <code>required bool mandatory = 3;</code> * @return The mandatory. */ @java.lang.Override public boolean getMandatory() { return instance.getMandatory(); } /** * <pre> * If we do not understand a mandatory extension, abort to prevent data loss. * For example, this could be applied to a new type of holding, such as a contract, where * dropping of an extension in a read/write cycle could cause loss of value. * </pre> * * <code>required bool mandatory = 3;</code> * @param value The mandatory to set. * @return This builder for chaining. */ public Builder setMandatory(boolean value) { copyOnWrite(); instance.setMandatory(value); return this; } /** * <pre> * If we do not understand a mandatory extension, abort to prevent data loss. * For example, this could be applied to a new type of holding, such as a contract, where * dropping of an extension in a read/write cycle could cause loss of value. * </pre> * * <code>required bool mandatory = 3;</code> * @return This builder for chaining. */ public Builder clearMandatory() { copyOnWrite(); instance.clearMandatory(); return this; } // @@protoc_insertion_point(builder_scope:wallet.Extension) } private byte memoizedIsInitialized = 2; @java.lang.Override @java.lang.SuppressWarnings({"unchecked", "fallthrough"}) protected final java.lang.Object dynamicMethod( com.google.protobuf.GeneratedMessageLite.MethodToInvoke method, java.lang.Object arg0, java.lang.Object arg1) { switch (method) { case NEW_MUTABLE_INSTANCE: { return new org.bitcoinj.wallet.Protos.Extension(); } case NEW_BUILDER: { return new Builder(); } case BUILD_MESSAGE_INFO: { java.lang.Object[] objects = new java.lang.Object[] { "bitField0_", "id_", "data_", "mandatory_", }; java.lang.String info = "\u0001\u0003\u0000\u0001\u0001\u0003\u0003\u0000\u0000\u0003\u0001\u1508\u0000\u0002" + "\u150a\u0001\u0003\u1507\u0002"; return newMessageInfo(DEFAULT_INSTANCE, info, objects); } // fall through case GET_DEFAULT_INSTANCE: { return DEFAULT_INSTANCE; } case GET_PARSER: { com.google.protobuf.Parser<org.bitcoinj.wallet.Protos.Extension> parser = PARSER; if (parser == null) { synchronized (org.bitcoinj.wallet.Protos.Extension.class) { parser = PARSER; if (parser == null) { parser = new DefaultInstanceBasedParser<org.bitcoinj.wallet.Protos.Extension>( DEFAULT_INSTANCE); PARSER = parser; } } } return parser; } case GET_MEMOIZED_IS_INITIALIZED: { return memoizedIsInitialized; } case SET_MEMOIZED_IS_INITIALIZED: { memoizedIsInitialized = (byte) (arg0 == null ? 0 : 1); return null; } } throw new UnsupportedOperationException(); } // @@protoc_insertion_point(class_scope:wallet.Extension) private static final org.bitcoinj.wallet.Protos.Extension DEFAULT_INSTANCE; static { Extension defaultInstance = new Extension(); // New instances are implicitly immutable so no need to make // immutable. DEFAULT_INSTANCE = defaultInstance; com.google.protobuf.GeneratedMessageLite.registerDefaultInstance( Extension.class, defaultInstance); } public static org.bitcoinj.wallet.Protos.Extension getDefaultInstance() { return DEFAULT_INSTANCE; } private static volatile com.google.protobuf.Parser<Extension> PARSER; public static com.google.protobuf.Parser<Extension> parser() { return DEFAULT_INSTANCE.getParserForType(); } } public interface TagOrBuilder extends // @@protoc_insertion_point(interface_extends:wallet.Tag) com.google.protobuf.MessageLiteOrBuilder { /** * <code>required string tag = 1;</code> * @return Whether the tag field is set. */ boolean hasTag(); /** * <code>required string tag = 1;</code> * @return The tag. */ java.lang.String getTag(); /** * <code>required string tag = 1;</code> * @return The bytes for tag. */ com.google.protobuf.ByteString getTagBytes(); /** * <code>required bytes data = 2;</code> * @return Whether the data field is set. */ boolean hasData(); /** * <code>required bytes data = 2;</code> * @return The data. */ com.google.protobuf.ByteString getData(); } /** * <pre> ** * A simple key-&gt;value mapping that has no interpreted content at all. A bit like the extensions mechanism except * an extension is keyed by the ID of a piece of code that's loaded with the given data, and has the concept of * being mandatory if that code isn't found. Whereas this is just a blind key/value store. * </pre> * * Protobuf type {@code wallet.Tag} */ public static final class Tag extends com.google.protobuf.GeneratedMessageLite< Tag, Tag.Builder> implements // @@protoc_insertion_point(message_implements:wallet.Tag) TagOrBuilder { private Tag() { tag_ = ""; data_ = com.google.protobuf.ByteString.EMPTY; } private int bitField0_; public static final int TAG_FIELD_NUMBER = 1; private java.lang.String tag_; /** * <code>required string tag = 1;</code> * @return Whether the tag field is set. */ @java.lang.Override public boolean hasTag() { return ((bitField0_ & 0x00000001) != 0); } /** * <code>required string tag = 1;</code> * @return The tag. */ @java.lang.Override public java.lang.String getTag() { return tag_; } /** * <code>required string tag = 1;</code> * @return The bytes for tag. */ @java.lang.Override public com.google.protobuf.ByteString getTagBytes() { return com.google.protobuf.ByteString.copyFromUtf8(tag_); } /** * <code>required string tag = 1;</code> * @param value The tag to set. */ private void setTag( java.lang.String value) { java.lang.Class<?> valueClass = value.getClass(); bitField0_ |= 0x00000001; tag_ = value; } /** * <code>required string tag = 1;</code> */ private void clearTag() { bitField0_ = (bitField0_ & ~0x00000001); tag_ = getDefaultInstance().getTag(); } /** * <code>required string tag = 1;</code> * @param value The bytes for tag to set. */ private void setTagBytes( com.google.protobuf.ByteString value) { tag_ = value.toStringUtf8(); bitField0_ |= 0x00000001; } public static final int DATA_FIELD_NUMBER = 2; private com.google.protobuf.ByteString data_; /** * <code>required bytes data = 2;</code> * @return Whether the data field is set. */ @java.lang.Override public boolean hasData() { return ((bitField0_ & 0x00000002) != 0); } /** * <code>required bytes data = 2;</code> * @return The data. */ @java.lang.Override public com.google.protobuf.ByteString getData() { return data_; } /** * <code>required bytes data = 2;</code> * @param value The data to set. */ private void setData(com.google.protobuf.ByteString value) { java.lang.Class<?> valueClass = value.getClass(); bitField0_ |= 0x00000002; data_ = value; } /** * <code>required bytes data = 2;</code> */ private void clearData() { bitField0_ = (bitField0_ & ~0x00000002); data_ = getDefaultInstance().getData(); } public static org.bitcoinj.wallet.Protos.Tag parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return com.google.protobuf.GeneratedMessageLite.parseFrom( DEFAULT_INSTANCE, data); } public static org.bitcoinj.wallet.Protos.Tag parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return com.google.protobuf.GeneratedMessageLite.parseFrom( DEFAULT_INSTANCE, data, extensionRegistry); } public static org.bitcoinj.wallet.Protos.Tag parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return com.google.protobuf.GeneratedMessageLite.parseFrom( DEFAULT_INSTANCE, data); } public static org.bitcoinj.wallet.Protos.Tag parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return com.google.protobuf.GeneratedMessageLite.parseFrom( DEFAULT_INSTANCE, data, extensionRegistry); } public static org.bitcoinj.wallet.Protos.Tag parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return com.google.protobuf.GeneratedMessageLite.parseFrom( DEFAULT_INSTANCE, data); } public static org.bitcoinj.wallet.Protos.Tag parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return com.google.protobuf.GeneratedMessageLite.parseFrom( DEFAULT_INSTANCE, data, extensionRegistry); } public static org.bitcoinj.wallet.Protos.Tag parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageLite.parseFrom( DEFAULT_INSTANCE, input); } public static org.bitcoinj.wallet.Protos.Tag parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageLite.parseFrom( DEFAULT_INSTANCE, input, extensionRegistry); } public static org.bitcoinj.wallet.Protos.Tag parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return parseDelimitedFrom(DEFAULT_INSTANCE, input); } public static org.bitcoinj.wallet.Protos.Tag parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return parseDelimitedFrom(DEFAULT_INSTANCE, input, extensionRegistry); } public static org.bitcoinj.wallet.Protos.Tag parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageLite.parseFrom( DEFAULT_INSTANCE, input); } public static org.bitcoinj.wallet.Protos.Tag parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageLite.parseFrom( DEFAULT_INSTANCE, input, extensionRegistry); } public static Builder newBuilder() { return (Builder) DEFAULT_INSTANCE.createBuilder(); } public static Builder newBuilder(org.bitcoinj.wallet.Protos.Tag prototype) { return (Builder) DEFAULT_INSTANCE.createBuilder(prototype); } /** * <pre> ** * A simple key-&gt;value mapping that has no interpreted content at all. A bit like the extensions mechanism except * an extension is keyed by the ID of a piece of code that's loaded with the given data, and has the concept of * being mandatory if that code isn't found. Whereas this is just a blind key/value store. * </pre> * * Protobuf type {@code wallet.Tag} */ public static final class Builder extends com.google.protobuf.GeneratedMessageLite.Builder< org.bitcoinj.wallet.Protos.Tag, Builder> implements // @@protoc_insertion_point(builder_implements:wallet.Tag) org.bitcoinj.wallet.Protos.TagOrBuilder { // Construct using org.bitcoinj.wallet.Protos.Tag.newBuilder() private Builder() { super(DEFAULT_INSTANCE); } /** * <code>required string tag = 1;</code> * @return Whether the tag field is set. */ @java.lang.Override public boolean hasTag() { return instance.hasTag(); } /** * <code>required string tag = 1;</code> * @return The tag. */ @java.lang.Override public java.lang.String getTag() { return instance.getTag(); } /** * <code>required string tag = 1;</code> * @return The bytes for tag. */ @java.lang.Override public com.google.protobuf.ByteString getTagBytes() { return instance.getTagBytes(); } /** * <code>required string tag = 1;</code> * @param value The tag to set. * @return This builder for chaining. */ public Builder setTag( java.lang.String value) { copyOnWrite(); instance.setTag(value); return this; } /** * <code>required string tag = 1;</code> * @return This builder for chaining. */ public Builder clearTag() { copyOnWrite(); instance.clearTag(); return this; } /** * <code>required string tag = 1;</code> * @param value The bytes for tag to set. * @return This builder for chaining. */ public Builder setTagBytes( com.google.protobuf.ByteString value) { copyOnWrite(); instance.setTagBytes(value); return this; } /** * <code>required bytes data = 2;</code> * @return Whether the data field is set. */ @java.lang.Override public boolean hasData() { return instance.hasData(); } /** * <code>required bytes data = 2;</code> * @return The data. */ @java.lang.Override public com.google.protobuf.ByteString getData() { return instance.getData(); } /** * <code>required bytes data = 2;</code> * @param value The data to set. * @return This builder for chaining. */ public Builder setData(com.google.protobuf.ByteString value) { copyOnWrite(); instance.setData(value); return this; } /** * <code>required bytes data = 2;</code> * @return This builder for chaining. */ public Builder clearData() { copyOnWrite(); instance.clearData(); return this; } // @@protoc_insertion_point(builder_scope:wallet.Tag) } private byte memoizedIsInitialized = 2; @java.lang.Override @java.lang.SuppressWarnings({"unchecked", "fallthrough"}) protected final java.lang.Object dynamicMethod( com.google.protobuf.GeneratedMessageLite.MethodToInvoke method, java.lang.Object arg0, java.lang.Object arg1) { switch (method) { case NEW_MUTABLE_INSTANCE: { return new org.bitcoinj.wallet.Protos.Tag(); } case NEW_BUILDER: { return new Builder(); } case BUILD_MESSAGE_INFO: { java.lang.Object[] objects = new java.lang.Object[] { "bitField0_", "tag_", "data_", }; java.lang.String info = "\u0001\u0002\u0000\u0001\u0001\u0002\u0002\u0000\u0000\u0002\u0001\u1508\u0000\u0002" + "\u150a\u0001"; return newMessageInfo(DEFAULT_INSTANCE, info, objects); } // fall through case GET_DEFAULT_INSTANCE: { return DEFAULT_INSTANCE; } case GET_PARSER: { com.google.protobuf.Parser<org.bitcoinj.wallet.Protos.Tag> parser = PARSER; if (parser == null) { synchronized (org.bitcoinj.wallet.Protos.Tag.class) { parser = PARSER; if (parser == null) { parser = new DefaultInstanceBasedParser<org.bitcoinj.wallet.Protos.Tag>( DEFAULT_INSTANCE); PARSER = parser; } } } return parser; } case GET_MEMOIZED_IS_INITIALIZED: { return memoizedIsInitialized; } case SET_MEMOIZED_IS_INITIALIZED: { memoizedIsInitialized = (byte) (arg0 == null ? 0 : 1); return null; } } throw new UnsupportedOperationException(); } // @@protoc_insertion_point(class_scope:wallet.Tag) private static final org.bitcoinj.wallet.Protos.Tag DEFAULT_INSTANCE; static { Tag defaultInstance = new Tag(); // New instances are implicitly immutable so no need to make // immutable. DEFAULT_INSTANCE = defaultInstance; com.google.protobuf.GeneratedMessageLite.registerDefaultInstance( Tag.class, defaultInstance); } public static org.bitcoinj.wallet.Protos.Tag getDefaultInstance() { return DEFAULT_INSTANCE; } private static volatile com.google.protobuf.Parser<Tag> PARSER; public static com.google.protobuf.Parser<Tag> parser() { return DEFAULT_INSTANCE.getParserForType(); } } public interface WalletOrBuilder extends // @@protoc_insertion_point(interface_extends:wallet.Wallet) com.google.protobuf.MessageLiteOrBuilder { /** * <pre> * the network used by this wallet * </pre> * * <code>required string network_identifier = 1;</code> * @return Whether the networkIdentifier field is set. */ boolean hasNetworkIdentifier(); /** * <pre> * the network used by this wallet * </pre> * * <code>required string network_identifier = 1;</code> * @return The networkIdentifier. */ java.lang.String getNetworkIdentifier(); /** * <pre> * the network used by this wallet * </pre> * * <code>required string network_identifier = 1;</code> * @return The bytes for networkIdentifier. */ com.google.protobuf.ByteString getNetworkIdentifierBytes(); /** * <pre> * The SHA256 hash of the head of the best chain seen by this wallet. * </pre> * * <code>optional bytes last_seen_block_hash = 2;</code> * @return Whether the lastSeenBlockHash field is set. */ boolean hasLastSeenBlockHash(); /** * <pre> * The SHA256 hash of the head of the best chain seen by this wallet. * </pre> * * <code>optional bytes last_seen_block_hash = 2;</code> * @return The lastSeenBlockHash. */ com.google.protobuf.ByteString getLastSeenBlockHash(); /** * <pre> * The height in the chain of the last seen block. * </pre> * * <code>optional uint32 last_seen_block_height = 12;</code> * @return Whether the lastSeenBlockHeight field is set. */ boolean hasLastSeenBlockHeight(); /** * <pre> * The height in the chain of the last seen block. * </pre> * * <code>optional uint32 last_seen_block_height = 12;</code> * @return The lastSeenBlockHeight. */ int getLastSeenBlockHeight(); /** * <code>optional int64 last_seen_block_time_secs = 14;</code> * @return Whether the lastSeenBlockTimeSecs field is set. */ boolean hasLastSeenBlockTimeSecs(); /** * <code>optional int64 last_seen_block_time_secs = 14;</code> * @return The lastSeenBlockTimeSecs. */ long getLastSeenBlockTimeSecs(); /** * <code>repeated .wallet.Key key = 3;</code> */ java.util.List<org.bitcoinj.wallet.Protos.Key> getKeyList(); /** * <code>repeated .wallet.Key key = 3;</code> */ org.bitcoinj.wallet.Protos.Key getKey(int index); /** * <code>repeated .wallet.Key key = 3;</code> */ int getKeyCount(); /** * <code>repeated .wallet.Transaction transaction = 4;</code> */ java.util.List<org.bitcoinj.wallet.Protos.Transaction> getTransactionList(); /** * <code>repeated .wallet.Transaction transaction = 4;</code> */ org.bitcoinj.wallet.Protos.Transaction getTransaction(int index); /** * <code>repeated .wallet.Transaction transaction = 4;</code> */ int getTransactionCount(); /** * <code>repeated .wallet.Script watched_script = 15;</code> */ java.util.List<org.bitcoinj.wallet.Protos.Script> getWatchedScriptList(); /** * <code>repeated .wallet.Script watched_script = 15;</code> */ org.bitcoinj.wallet.Protos.Script getWatchedScript(int index); /** * <code>repeated .wallet.Script watched_script = 15;</code> */ int getWatchedScriptCount(); /** * <code>optional .wallet.Wallet.EncryptionType encryption_type = 5 [default = UNENCRYPTED];</code> * @return Whether the encryptionType field is set. */ boolean hasEncryptionType(); /** * <code>optional .wallet.Wallet.EncryptionType encryption_type = 5 [default = UNENCRYPTED];</code> * @return The encryptionType. */ org.bitcoinj.wallet.Protos.Wallet.EncryptionType getEncryptionType(); /** * <code>optional .wallet.ScryptParameters encryption_parameters = 6;</code> * @return Whether the encryptionParameters field is set. */ boolean hasEncryptionParameters(); /** * <code>optional .wallet.ScryptParameters encryption_parameters = 6;</code> * @return The encryptionParameters. */ org.bitcoinj.wallet.Protos.ScryptParameters getEncryptionParameters(); /** * <pre> * The version number of the wallet - used to detect wallets that were produced in the future * (i.e. the wallet may contain some future format this protobuf or parser code does not know about). * A version that's higher than the default is considered from the future. * </pre> * * <code>optional int32 version = 7 [default = 1];</code> * @return Whether the version field is set. */ boolean hasVersion(); /** * <pre> * The version number of the wallet - used to detect wallets that were produced in the future * (i.e. the wallet may contain some future format this protobuf or parser code does not know about). * A version that's higher than the default is considered from the future. * </pre> * * <code>optional int32 version = 7 [default = 1];</code> * @return The version. */ int getVersion(); /** * <code>repeated .wallet.Extension extension = 10;</code> */ java.util.List<org.bitcoinj.wallet.Protos.Extension> getExtensionList(); /** * <code>repeated .wallet.Extension extension = 10;</code> */ org.bitcoinj.wallet.Protos.Extension getExtension(int index); /** * <code>repeated .wallet.Extension extension = 10;</code> */ int getExtensionCount(); /** * <pre> * A UTF8 encoded text description of the wallet that is intended for end user provided text. * </pre> * * <code>optional string description = 11;</code> * @return Whether the description field is set. */ boolean hasDescription(); /** * <pre> * A UTF8 encoded text description of the wallet that is intended for end user provided text. * </pre> * * <code>optional string description = 11;</code> * @return The description. */ java.lang.String getDescription(); /** * <pre> * A UTF8 encoded text description of the wallet that is intended for end user provided text. * </pre> * * <code>optional string description = 11;</code> * @return The bytes for description. */ com.google.protobuf.ByteString getDescriptionBytes(); /** * <pre> * UNIX time in seconds since the epoch. If set, then any keys created before this date are assumed to be no longer * wanted. Money sent to them will be re-spent automatically to the first key that was created after this time. It * can be used to recover a compromised wallet, or just as part of preventative defence-in-depth measures. * </pre> * * <code>optional uint64 key_rotation_time = 13;</code> * @return Whether the keyRotationTime field is set. */ boolean hasKeyRotationTime(); /** * <pre> * UNIX time in seconds since the epoch. If set, then any keys created before this date are assumed to be no longer * wanted. Money sent to them will be re-spent automatically to the first key that was created after this time. It * can be used to recover a compromised wallet, or just as part of preventative defence-in-depth measures. * </pre> * * <code>optional uint64 key_rotation_time = 13;</code> * @return The keyRotationTime. */ long getKeyRotationTime(); /** * <code>repeated .wallet.Tag tags = 16;</code> */ java.util.List<org.bitcoinj.wallet.Protos.Tag> getTagsList(); /** * <code>repeated .wallet.Tag tags = 16;</code> */ org.bitcoinj.wallet.Protos.Tag getTags(int index); /** * <code>repeated .wallet.Tag tags = 16;</code> */ int getTagsCount(); } /** * <pre> ** A bitcoin wallet * </pre> * * Protobuf type {@code wallet.Wallet} */ public static final class Wallet extends com.google.protobuf.GeneratedMessageLite< Wallet, Wallet.Builder> implements // @@protoc_insertion_point(message_implements:wallet.Wallet) WalletOrBuilder { private Wallet() { networkIdentifier_ = ""; lastSeenBlockHash_ = com.google.protobuf.ByteString.EMPTY; key_ = emptyProtobufList(); transaction_ = emptyProtobufList(); watchedScript_ = emptyProtobufList(); encryptionType_ = 1; version_ = 1; extension_ = emptyProtobufList(); description_ = ""; tags_ = emptyProtobufList(); } /** * <pre> ** * The encryption type of the wallet. * * The encryption type is UNENCRYPTED for wallets where the wallet does not support encryption - wallets prior to * encryption support are grandfathered in as this wallet type. * When a wallet is ENCRYPTED_SCRYPT_AES the keys are either encrypted with the wallet password or are unencrypted. * </pre> * * Protobuf enum {@code wallet.Wallet.EncryptionType} */ public enum EncryptionType implements com.google.protobuf.Internal.EnumLite { /** * <pre> * All keys in the wallet are unencrypted * </pre> * * <code>UNENCRYPTED = 1;</code> */ UNENCRYPTED(1), /** * <pre> * All keys are encrypted with a passphrase based KDF of scrypt and AES encryption * </pre> * * <code>ENCRYPTED_SCRYPT_AES = 2;</code> */ ENCRYPTED_SCRYPT_AES(2), ; /** * <pre> * All keys in the wallet are unencrypted * </pre> * * <code>UNENCRYPTED = 1;</code> */ public static final int UNENCRYPTED_VALUE = 1; /** * <pre> * All keys are encrypted with a passphrase based KDF of scrypt and AES encryption * </pre> * * <code>ENCRYPTED_SCRYPT_AES = 2;</code> */ public static final int ENCRYPTED_SCRYPT_AES_VALUE = 2; @java.lang.Override public final int getNumber() { return value; } /** * @param value The number of the enum to look for. * @return The enum associated with the given number. * @deprecated Use {@link #forNumber(int)} instead. */ @java.lang.Deprecated public static EncryptionType valueOf(int value) { return forNumber(value); } public static EncryptionType forNumber(int value) { switch (value) { case 1: return UNENCRYPTED; case 2: return ENCRYPTED_SCRYPT_AES; default: return null; } } public static com.google.protobuf.Internal.EnumLiteMap<EncryptionType> internalGetValueMap() { return internalValueMap; } private static final com.google.protobuf.Internal.EnumLiteMap< EncryptionType> internalValueMap = new com.google.protobuf.Internal.EnumLiteMap<EncryptionType>() { @java.lang.Override public EncryptionType findValueByNumber(int number) { return EncryptionType.forNumber(number); } }; public static com.google.protobuf.Internal.EnumVerifier internalGetVerifier() { return EncryptionTypeVerifier.INSTANCE; } private static final class EncryptionTypeVerifier implements com.google.protobuf.Internal.EnumVerifier { static final com.google.protobuf.Internal.EnumVerifier INSTANCE = new EncryptionTypeVerifier(); @java.lang.Override public boolean isInRange(int number) { return EncryptionType.forNumber(number) != null; } }; private final int value; private EncryptionType(int value) { this.value = value; } // @@protoc_insertion_point(enum_scope:wallet.Wallet.EncryptionType) } private int bitField0_; public static final int NETWORK_IDENTIFIER_FIELD_NUMBER = 1; private java.lang.String networkIdentifier_; /** * <pre> * the network used by this wallet * </pre> * * <code>required string network_identifier = 1;</code> * @return Whether the networkIdentifier field is set. */ @java.lang.Override public boolean hasNetworkIdentifier() { return ((bitField0_ & 0x00000001) != 0); } /** * <pre> * the network used by this wallet * </pre> * * <code>required string network_identifier = 1;</code> * @return The networkIdentifier. */ @java.lang.Override public java.lang.String getNetworkIdentifier() { return networkIdentifier_; } /** * <pre> * the network used by this wallet * </pre> * * <code>required string network_identifier = 1;</code> * @return The bytes for networkIdentifier. */ @java.lang.Override public com.google.protobuf.ByteString getNetworkIdentifierBytes() { return com.google.protobuf.ByteString.copyFromUtf8(networkIdentifier_); } /** * <pre> * the network used by this wallet * </pre> * * <code>required string network_identifier = 1;</code> * @param value The networkIdentifier to set. */ private void setNetworkIdentifier( java.lang.String value) { java.lang.Class<?> valueClass = value.getClass(); bitField0_ |= 0x00000001; networkIdentifier_ = value; } /** * <pre> * the network used by this wallet * </pre> * * <code>required string network_identifier = 1;</code> */ private void clearNetworkIdentifier() { bitField0_ = (bitField0_ & ~0x00000001); networkIdentifier_ = getDefaultInstance().getNetworkIdentifier(); } /** * <pre> * the network used by this wallet * </pre> * * <code>required string network_identifier = 1;</code> * @param value The bytes for networkIdentifier to set. */ private void setNetworkIdentifierBytes( com.google.protobuf.ByteString value) { networkIdentifier_ = value.toStringUtf8(); bitField0_ |= 0x00000001; } public static final int LAST_SEEN_BLOCK_HASH_FIELD_NUMBER = 2; private com.google.protobuf.ByteString lastSeenBlockHash_; /** * <pre> * The SHA256 hash of the head of the best chain seen by this wallet. * </pre> * * <code>optional bytes last_seen_block_hash = 2;</code> * @return Whether the lastSeenBlockHash field is set. */ @java.lang.Override public boolean hasLastSeenBlockHash() { return ((bitField0_ & 0x00000002) != 0); } /** * <pre> * The SHA256 hash of the head of the best chain seen by this wallet. * </pre> * * <code>optional bytes last_seen_block_hash = 2;</code> * @return The lastSeenBlockHash. */ @java.lang.Override public com.google.protobuf.ByteString getLastSeenBlockHash() { return lastSeenBlockHash_; } /** * <pre> * The SHA256 hash of the head of the best chain seen by this wallet. * </pre> * * <code>optional bytes last_seen_block_hash = 2;</code> * @param value The lastSeenBlockHash to set. */ private void setLastSeenBlockHash(com.google.protobuf.ByteString value) { java.lang.Class<?> valueClass = value.getClass(); bitField0_ |= 0x00000002; lastSeenBlockHash_ = value; } /** * <pre> * The SHA256 hash of the head of the best chain seen by this wallet. * </pre> * * <code>optional bytes last_seen_block_hash = 2;</code> */ private void clearLastSeenBlockHash() { bitField0_ = (bitField0_ & ~0x00000002); lastSeenBlockHash_ = getDefaultInstance().getLastSeenBlockHash(); } public static final int LAST_SEEN_BLOCK_HEIGHT_FIELD_NUMBER = 12; private int lastSeenBlockHeight_; /** * <pre> * The height in the chain of the last seen block. * </pre> * * <code>optional uint32 last_seen_block_height = 12;</code> * @return Whether the lastSeenBlockHeight field is set. */ @java.lang.Override public boolean hasLastSeenBlockHeight() { return ((bitField0_ & 0x00000004) != 0); } /** * <pre> * The height in the chain of the last seen block. * </pre> * * <code>optional uint32 last_seen_block_height = 12;</code> * @return The lastSeenBlockHeight. */ @java.lang.Override public int getLastSeenBlockHeight() { return lastSeenBlockHeight_; } /** * <pre> * The height in the chain of the last seen block. * </pre> * * <code>optional uint32 last_seen_block_height = 12;</code> * @param value The lastSeenBlockHeight to set. */ private void setLastSeenBlockHeight(int value) { bitField0_ |= 0x00000004; lastSeenBlockHeight_ = value; } /** * <pre> * The height in the chain of the last seen block. * </pre> * * <code>optional uint32 last_seen_block_height = 12;</code> */ private void clearLastSeenBlockHeight() { bitField0_ = (bitField0_ & ~0x00000004); lastSeenBlockHeight_ = 0; } public static final int LAST_SEEN_BLOCK_TIME_SECS_FIELD_NUMBER = 14; private long lastSeenBlockTimeSecs_; /** * <code>optional int64 last_seen_block_time_secs = 14;</code> * @return Whether the lastSeenBlockTimeSecs field is set. */ @java.lang.Override public boolean hasLastSeenBlockTimeSecs() { return ((bitField0_ & 0x00000008) != 0); } /** * <code>optional int64 last_seen_block_time_secs = 14;</code> * @return The lastSeenBlockTimeSecs. */ @java.lang.Override public long getLastSeenBlockTimeSecs() { return lastSeenBlockTimeSecs_; } /** * <code>optional int64 last_seen_block_time_secs = 14;</code> * @param value The lastSeenBlockTimeSecs to set. */ private void setLastSeenBlockTimeSecs(long value) { bitField0_ |= 0x00000008; lastSeenBlockTimeSecs_ = value; } /** * <code>optional int64 last_seen_block_time_secs = 14;</code> */ private void clearLastSeenBlockTimeSecs() { bitField0_ = (bitField0_ & ~0x00000008); lastSeenBlockTimeSecs_ = 0L; } public static final int KEY_FIELD_NUMBER = 3; private com.google.protobuf.Internal.ProtobufList<org.bitcoinj.wallet.Protos.Key> key_; /** * <code>repeated .wallet.Key key = 3;</code> */ @java.lang.Override public java.util.List<org.bitcoinj.wallet.Protos.Key> getKeyList() { return key_; } /** * <code>repeated .wallet.Key key = 3;</code> */ public java.util.List<? extends org.bitcoinj.wallet.Protos.KeyOrBuilder> getKeyOrBuilderList() { return key_; } /** * <code>repeated .wallet.Key key = 3;</code> */ @java.lang.Override public int getKeyCount() { return key_.size(); } /** * <code>repeated .wallet.Key key = 3;</code> */ @java.lang.Override public org.bitcoinj.wallet.Protos.Key getKey(int index) { return key_.get(index); } /** * <code>repeated .wallet.Key key = 3;</code> */ public org.bitcoinj.wallet.Protos.KeyOrBuilder getKeyOrBuilder( int index) { return key_.get(index); } private void ensureKeyIsMutable() { com.google.protobuf.Internal.ProtobufList<org.bitcoinj.wallet.Protos.Key> tmp = key_; if (!tmp.isModifiable()) { key_ = com.google.protobuf.GeneratedMessageLite.mutableCopy(tmp); } } /** * <code>repeated .wallet.Key key = 3;</code> */ private void setKey( int index, org.bitcoinj.wallet.Protos.Key value) { value.getClass(); ensureKeyIsMutable(); key_.set(index, value); } /** * <code>repeated .wallet.Key key = 3;</code> */ private void addKey(org.bitcoinj.wallet.Protos.Key value) { value.getClass(); ensureKeyIsMutable(); key_.add(value); } /** * <code>repeated .wallet.Key key = 3;</code> */ private void addKey( int index, org.bitcoinj.wallet.Protos.Key value) { value.getClass(); ensureKeyIsMutable(); key_.add(index, value); } /** * <code>repeated .wallet.Key key = 3;</code> */ private void addAllKey( java.lang.Iterable<? extends org.bitcoinj.wallet.Protos.Key> values) { ensureKeyIsMutable(); com.google.protobuf.AbstractMessageLite.addAll( values, key_); } /** * <code>repeated .wallet.Key key = 3;</code> */ private void clearKey() { key_ = emptyProtobufList(); } /** * <code>repeated .wallet.Key key = 3;</code> */ private void removeKey(int index) { ensureKeyIsMutable(); key_.remove(index); } public static final int TRANSACTION_FIELD_NUMBER = 4; private com.google.protobuf.Internal.ProtobufList<org.bitcoinj.wallet.Protos.Transaction> transaction_; /** * <code>repeated .wallet.Transaction transaction = 4;</code> */ @java.lang.Override public java.util.List<org.bitcoinj.wallet.Protos.Transaction> getTransactionList() { return transaction_; } /** * <code>repeated .wallet.Transaction transaction = 4;</code> */ public java.util.List<? extends org.bitcoinj.wallet.Protos.TransactionOrBuilder> getTransactionOrBuilderList() { return transaction_; } /** * <code>repeated .wallet.Transaction transaction = 4;</code> */ @java.lang.Override public int getTransactionCount() { return transaction_.size(); } /** * <code>repeated .wallet.Transaction transaction = 4;</code> */ @java.lang.Override public org.bitcoinj.wallet.Protos.Transaction getTransaction(int index) { return transaction_.get(index); } /** * <code>repeated .wallet.Transaction transaction = 4;</code> */ public org.bitcoinj.wallet.Protos.TransactionOrBuilder getTransactionOrBuilder( int index) { return transaction_.get(index); } private void ensureTransactionIsMutable() { com.google.protobuf.Internal.ProtobufList<org.bitcoinj.wallet.Protos.Transaction> tmp = transaction_; if (!tmp.isModifiable()) { transaction_ = com.google.protobuf.GeneratedMessageLite.mutableCopy(tmp); } } /** * <code>repeated .wallet.Transaction transaction = 4;</code> */ private void setTransaction( int index, org.bitcoinj.wallet.Protos.Transaction value) { value.getClass(); ensureTransactionIsMutable(); transaction_.set(index, value); } /** * <code>repeated .wallet.Transaction transaction = 4;</code> */ private void addTransaction(org.bitcoinj.wallet.Protos.Transaction value) { value.getClass(); ensureTransactionIsMutable(); transaction_.add(value); } /** * <code>repeated .wallet.Transaction transaction = 4;</code> */ private void addTransaction( int index, org.bitcoinj.wallet.Protos.Transaction value) { value.getClass(); ensureTransactionIsMutable(); transaction_.add(index, value); } /** * <code>repeated .wallet.Transaction transaction = 4;</code> */ private void addAllTransaction( java.lang.Iterable<? extends org.bitcoinj.wallet.Protos.Transaction> values) { ensureTransactionIsMutable(); com.google.protobuf.AbstractMessageLite.addAll( values, transaction_); } /** * <code>repeated .wallet.Transaction transaction = 4;</code> */ private void clearTransaction() { transaction_ = emptyProtobufList(); } /** * <code>repeated .wallet.Transaction transaction = 4;</code> */ private void removeTransaction(int index) { ensureTransactionIsMutable(); transaction_.remove(index); } public static final int WATCHED_SCRIPT_FIELD_NUMBER = 15; private com.google.protobuf.Internal.ProtobufList<org.bitcoinj.wallet.Protos.Script> watchedScript_; /** * <code>repeated .wallet.Script watched_script = 15;</code> */ @java.lang.Override public java.util.List<org.bitcoinj.wallet.Protos.Script> getWatchedScriptList() { return watchedScript_; } /** * <code>repeated .wallet.Script watched_script = 15;</code> */ public java.util.List<? extends org.bitcoinj.wallet.Protos.ScriptOrBuilder> getWatchedScriptOrBuilderList() { return watchedScript_; } /** * <code>repeated .wallet.Script watched_script = 15;</code> */ @java.lang.Override public int getWatchedScriptCount() { return watchedScript_.size(); } /** * <code>repeated .wallet.Script watched_script = 15;</code> */ @java.lang.Override public org.bitcoinj.wallet.Protos.Script getWatchedScript(int index) { return watchedScript_.get(index); } /** * <code>repeated .wallet.Script watched_script = 15;</code> */ public org.bitcoinj.wallet.Protos.ScriptOrBuilder getWatchedScriptOrBuilder( int index) { return watchedScript_.get(index); } private void ensureWatchedScriptIsMutable() { com.google.protobuf.Internal.ProtobufList<org.bitcoinj.wallet.Protos.Script> tmp = watchedScript_; if (!tmp.isModifiable()) { watchedScript_ = com.google.protobuf.GeneratedMessageLite.mutableCopy(tmp); } } /** * <code>repeated .wallet.Script watched_script = 15;</code> */ private void setWatchedScript( int index, org.bitcoinj.wallet.Protos.Script value) { value.getClass(); ensureWatchedScriptIsMutable(); watchedScript_.set(index, value); } /** * <code>repeated .wallet.Script watched_script = 15;</code> */ private void addWatchedScript(org.bitcoinj.wallet.Protos.Script value) { value.getClass(); ensureWatchedScriptIsMutable(); watchedScript_.add(value); } /** * <code>repeated .wallet.Script watched_script = 15;</code> */ private void addWatchedScript( int index, org.bitcoinj.wallet.Protos.Script value) { value.getClass(); ensureWatchedScriptIsMutable(); watchedScript_.add(index, value); } /** * <code>repeated .wallet.Script watched_script = 15;</code> */ private void addAllWatchedScript( java.lang.Iterable<? extends org.bitcoinj.wallet.Protos.Script> values) { ensureWatchedScriptIsMutable(); com.google.protobuf.AbstractMessageLite.addAll( values, watchedScript_); } /** * <code>repeated .wallet.Script watched_script = 15;</code> */ private void clearWatchedScript() { watchedScript_ = emptyProtobufList(); } /** * <code>repeated .wallet.Script watched_script = 15;</code> */ private void removeWatchedScript(int index) { ensureWatchedScriptIsMutable(); watchedScript_.remove(index); } public static final int ENCRYPTION_TYPE_FIELD_NUMBER = 5; private int encryptionType_; /** * <code>optional .wallet.Wallet.EncryptionType encryption_type = 5 [default = UNENCRYPTED];</code> * @return Whether the encryptionType field is set. */ @java.lang.Override public boolean hasEncryptionType() { return ((bitField0_ & 0x00000010) != 0); } /** * <code>optional .wallet.Wallet.EncryptionType encryption_type = 5 [default = UNENCRYPTED];</code> * @return The encryptionType. */ @java.lang.Override public org.bitcoinj.wallet.Protos.Wallet.EncryptionType getEncryptionType() { org.bitcoinj.wallet.Protos.Wallet.EncryptionType result = org.bitcoinj.wallet.Protos.Wallet.EncryptionType.forNumber(encryptionType_); return result == null ? org.bitcoinj.wallet.Protos.Wallet.EncryptionType.UNENCRYPTED : result; } /** * <code>optional .wallet.Wallet.EncryptionType encryption_type = 5 [default = UNENCRYPTED];</code> * @param value The encryptionType to set. */ private void setEncryptionType(org.bitcoinj.wallet.Protos.Wallet.EncryptionType value) { encryptionType_ = value.getNumber(); bitField0_ |= 0x00000010; } /** * <code>optional .wallet.Wallet.EncryptionType encryption_type = 5 [default = UNENCRYPTED];</code> */ private void clearEncryptionType() { bitField0_ = (bitField0_ & ~0x00000010); encryptionType_ = 1; } public static final int ENCRYPTION_PARAMETERS_FIELD_NUMBER = 6; private org.bitcoinj.wallet.Protos.ScryptParameters encryptionParameters_; /** * <code>optional .wallet.ScryptParameters encryption_parameters = 6;</code> */ @java.lang.Override public boolean hasEncryptionParameters() { return ((bitField0_ & 0x00000020) != 0); } /** * <code>optional .wallet.ScryptParameters encryption_parameters = 6;</code> */ @java.lang.Override public org.bitcoinj.wallet.Protos.ScryptParameters getEncryptionParameters() { return encryptionParameters_ == null ? org.bitcoinj.wallet.Protos.ScryptParameters.getDefaultInstance() : encryptionParameters_; } /** * <code>optional .wallet.ScryptParameters encryption_parameters = 6;</code> */ private void setEncryptionParameters(org.bitcoinj.wallet.Protos.ScryptParameters value) { value.getClass(); encryptionParameters_ = value; bitField0_ |= 0x00000020; } /** * <code>optional .wallet.ScryptParameters encryption_parameters = 6;</code> */ @java.lang.SuppressWarnings({"ReferenceEquality"}) private void mergeEncryptionParameters(org.bitcoinj.wallet.Protos.ScryptParameters value) { value.getClass(); if (encryptionParameters_ != null && encryptionParameters_ != org.bitcoinj.wallet.Protos.ScryptParameters.getDefaultInstance()) { encryptionParameters_ = org.bitcoinj.wallet.Protos.ScryptParameters.newBuilder(encryptionParameters_).mergeFrom(value).buildPartial(); } else { encryptionParameters_ = value; } bitField0_ |= 0x00000020; } /** * <code>optional .wallet.ScryptParameters encryption_parameters = 6;</code> */ private void clearEncryptionParameters() { encryptionParameters_ = null; bitField0_ = (bitField0_ & ~0x00000020); } public static final int VERSION_FIELD_NUMBER = 7; private int version_; /** * <pre> * The version number of the wallet - used to detect wallets that were produced in the future * (i.e. the wallet may contain some future format this protobuf or parser code does not know about). * A version that's higher than the default is considered from the future. * </pre> * * <code>optional int32 version = 7 [default = 1];</code> * @return Whether the version field is set. */ @java.lang.Override public boolean hasVersion() { return ((bitField0_ & 0x00000040) != 0); } /** * <pre> * The version number of the wallet - used to detect wallets that were produced in the future * (i.e. the wallet may contain some future format this protobuf or parser code does not know about). * A version that's higher than the default is considered from the future. * </pre> * * <code>optional int32 version = 7 [default = 1];</code> * @return The version. */ @java.lang.Override public int getVersion() { return version_; } /** * <pre> * The version number of the wallet - used to detect wallets that were produced in the future * (i.e. the wallet may contain some future format this protobuf or parser code does not know about). * A version that's higher than the default is considered from the future. * </pre> * * <code>optional int32 version = 7 [default = 1];</code> * @param value The version to set. */ private void setVersion(int value) { bitField0_ |= 0x00000040; version_ = value; } /** * <pre> * The version number of the wallet - used to detect wallets that were produced in the future * (i.e. the wallet may contain some future format this protobuf or parser code does not know about). * A version that's higher than the default is considered from the future. * </pre> * * <code>optional int32 version = 7 [default = 1];</code> */ private void clearVersion() { bitField0_ = (bitField0_ & ~0x00000040); version_ = 1; } public static final int EXTENSION_FIELD_NUMBER = 10; private com.google.protobuf.Internal.ProtobufList<org.bitcoinj.wallet.Protos.Extension> extension_; /** * <code>repeated .wallet.Extension extension = 10;</code> */ @java.lang.Override public java.util.List<org.bitcoinj.wallet.Protos.Extension> getExtensionList() { return extension_; } /** * <code>repeated .wallet.Extension extension = 10;</code> */ public java.util.List<? extends org.bitcoinj.wallet.Protos.ExtensionOrBuilder> getExtensionOrBuilderList() { return extension_; } /** * <code>repeated .wallet.Extension extension = 10;</code> */ @java.lang.Override public int getExtensionCount() { return extension_.size(); } /** * <code>repeated .wallet.Extension extension = 10;</code> */ @java.lang.Override public org.bitcoinj.wallet.Protos.Extension getExtension(int index) { return extension_.get(index); } /** * <code>repeated .wallet.Extension extension = 10;</code> */ public org.bitcoinj.wallet.Protos.ExtensionOrBuilder getExtensionOrBuilder( int index) { return extension_.get(index); } private void ensureExtensionIsMutable() { com.google.protobuf.Internal.ProtobufList<org.bitcoinj.wallet.Protos.Extension> tmp = extension_; if (!tmp.isModifiable()) { extension_ = com.google.protobuf.GeneratedMessageLite.mutableCopy(tmp); } } /** * <code>repeated .wallet.Extension extension = 10;</code> */ private void setExtension( int index, org.bitcoinj.wallet.Protos.Extension value) { value.getClass(); ensureExtensionIsMutable(); extension_.set(index, value); } /** * <code>repeated .wallet.Extension extension = 10;</code> */ private void addExtension(org.bitcoinj.wallet.Protos.Extension value) { value.getClass(); ensureExtensionIsMutable(); extension_.add(value); } /** * <code>repeated .wallet.Extension extension = 10;</code> */ private void addExtension( int index, org.bitcoinj.wallet.Protos.Extension value) { value.getClass(); ensureExtensionIsMutable(); extension_.add(index, value); } /** * <code>repeated .wallet.Extension extension = 10;</code> */ private void addAllExtension( java.lang.Iterable<? extends org.bitcoinj.wallet.Protos.Extension> values) { ensureExtensionIsMutable(); com.google.protobuf.AbstractMessageLite.addAll( values, extension_); } /** * <code>repeated .wallet.Extension extension = 10;</code> */ private void clearExtension() { extension_ = emptyProtobufList(); } /** * <code>repeated .wallet.Extension extension = 10;</code> */ private void removeExtension(int index) { ensureExtensionIsMutable(); extension_.remove(index); } public static final int DESCRIPTION_FIELD_NUMBER = 11; private java.lang.String description_; /** * <pre> * A UTF8 encoded text description of the wallet that is intended for end user provided text. * </pre> * * <code>optional string description = 11;</code> * @return Whether the description field is set. */ @java.lang.Override public boolean hasDescription() { return ((bitField0_ & 0x00000080) != 0); } /** * <pre> * A UTF8 encoded text description of the wallet that is intended for end user provided text. * </pre> * * <code>optional string description = 11;</code> * @return The description. */ @java.lang.Override public java.lang.String getDescription() { return description_; } /** * <pre> * A UTF8 encoded text description of the wallet that is intended for end user provided text. * </pre> * * <code>optional string description = 11;</code> * @return The bytes for description. */ @java.lang.Override public com.google.protobuf.ByteString getDescriptionBytes() { return com.google.protobuf.ByteString.copyFromUtf8(description_); } /** * <pre> * A UTF8 encoded text description of the wallet that is intended for end user provided text. * </pre> * * <code>optional string description = 11;</code> * @param value The description to set. */ private void setDescription( java.lang.String value) { java.lang.Class<?> valueClass = value.getClass(); bitField0_ |= 0x00000080; description_ = value; } /** * <pre> * A UTF8 encoded text description of the wallet that is intended for end user provided text. * </pre> * * <code>optional string description = 11;</code> */ private void clearDescription() { bitField0_ = (bitField0_ & ~0x00000080); description_ = getDefaultInstance().getDescription(); } /** * <pre> * A UTF8 encoded text description of the wallet that is intended for end user provided text. * </pre> * * <code>optional string description = 11;</code> * @param value The bytes for description to set. */ private void setDescriptionBytes( com.google.protobuf.ByteString value) { description_ = value.toStringUtf8(); bitField0_ |= 0x00000080; } public static final int KEY_ROTATION_TIME_FIELD_NUMBER = 13; private long keyRotationTime_; /** * <pre> * UNIX time in seconds since the epoch. If set, then any keys created before this date are assumed to be no longer * wanted. Money sent to them will be re-spent automatically to the first key that was created after this time. It * can be used to recover a compromised wallet, or just as part of preventative defence-in-depth measures. * </pre> * * <code>optional uint64 key_rotation_time = 13;</code> * @return Whether the keyRotationTime field is set. */ @java.lang.Override public boolean hasKeyRotationTime() { return ((bitField0_ & 0x00000100) != 0); } /** * <pre> * UNIX time in seconds since the epoch. If set, then any keys created before this date are assumed to be no longer * wanted. Money sent to them will be re-spent automatically to the first key that was created after this time. It * can be used to recover a compromised wallet, or just as part of preventative defence-in-depth measures. * </pre> * * <code>optional uint64 key_rotation_time = 13;</code> * @return The keyRotationTime. */ @java.lang.Override public long getKeyRotationTime() { return keyRotationTime_; } /** * <pre> * UNIX time in seconds since the epoch. If set, then any keys created before this date are assumed to be no longer * wanted. Money sent to them will be re-spent automatically to the first key that was created after this time. It * can be used to recover a compromised wallet, or just as part of preventative defence-in-depth measures. * </pre> * * <code>optional uint64 key_rotation_time = 13;</code> * @param value The keyRotationTime to set. */ private void setKeyRotationTime(long value) { bitField0_ |= 0x00000100; keyRotationTime_ = value; } /** * <pre> * UNIX time in seconds since the epoch. If set, then any keys created before this date are assumed to be no longer * wanted. Money sent to them will be re-spent automatically to the first key that was created after this time. It * can be used to recover a compromised wallet, or just as part of preventative defence-in-depth measures. * </pre> * * <code>optional uint64 key_rotation_time = 13;</code> */ private void clearKeyRotationTime() { bitField0_ = (bitField0_ & ~0x00000100); keyRotationTime_ = 0L; } public static final int TAGS_FIELD_NUMBER = 16; private com.google.protobuf.Internal.ProtobufList<org.bitcoinj.wallet.Protos.Tag> tags_; /** * <code>repeated .wallet.Tag tags = 16;</code> */ @java.lang.Override public java.util.List<org.bitcoinj.wallet.Protos.Tag> getTagsList() { return tags_; } /** * <code>repeated .wallet.Tag tags = 16;</code> */ public java.util.List<? extends org.bitcoinj.wallet.Protos.TagOrBuilder> getTagsOrBuilderList() { return tags_; } /** * <code>repeated .wallet.Tag tags = 16;</code> */ @java.lang.Override public int getTagsCount() { return tags_.size(); } /** * <code>repeated .wallet.Tag tags = 16;</code> */ @java.lang.Override public org.bitcoinj.wallet.Protos.Tag getTags(int index) { return tags_.get(index); } /** * <code>repeated .wallet.Tag tags = 16;</code> */ public org.bitcoinj.wallet.Protos.TagOrBuilder getTagsOrBuilder( int index) { return tags_.get(index); } private void ensureTagsIsMutable() { com.google.protobuf.Internal.ProtobufList<org.bitcoinj.wallet.Protos.Tag> tmp = tags_; if (!tmp.isModifiable()) { tags_ = com.google.protobuf.GeneratedMessageLite.mutableCopy(tmp); } } /** * <code>repeated .wallet.Tag tags = 16;</code> */ private void setTags( int index, org.bitcoinj.wallet.Protos.Tag value) { value.getClass(); ensureTagsIsMutable(); tags_.set(index, value); } /** * <code>repeated .wallet.Tag tags = 16;</code> */ private void addTags(org.bitcoinj.wallet.Protos.Tag value) { value.getClass(); ensureTagsIsMutable(); tags_.add(value); } /** * <code>repeated .wallet.Tag tags = 16;</code> */ private void addTags( int index, org.bitcoinj.wallet.Protos.Tag value) { value.getClass(); ensureTagsIsMutable(); tags_.add(index, value); } /** * <code>repeated .wallet.Tag tags = 16;</code> */ private void addAllTags( java.lang.Iterable<? extends org.bitcoinj.wallet.Protos.Tag> values) { ensureTagsIsMutable(); com.google.protobuf.AbstractMessageLite.addAll( values, tags_); } /** * <code>repeated .wallet.Tag tags = 16;</code> */ private void clearTags() { tags_ = emptyProtobufList(); } /** * <code>repeated .wallet.Tag tags = 16;</code> */ private void removeTags(int index) { ensureTagsIsMutable(); tags_.remove(index); } public static org.bitcoinj.wallet.Protos.Wallet parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return com.google.protobuf.GeneratedMessageLite.parseFrom( DEFAULT_INSTANCE, data); } public static org.bitcoinj.wallet.Protos.Wallet parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return com.google.protobuf.GeneratedMessageLite.parseFrom( DEFAULT_INSTANCE, data, extensionRegistry); } public static org.bitcoinj.wallet.Protos.Wallet parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return com.google.protobuf.GeneratedMessageLite.parseFrom( DEFAULT_INSTANCE, data); } public static org.bitcoinj.wallet.Protos.Wallet parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return com.google.protobuf.GeneratedMessageLite.parseFrom( DEFAULT_INSTANCE, data, extensionRegistry); } public static org.bitcoinj.wallet.Protos.Wallet parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return com.google.protobuf.GeneratedMessageLite.parseFrom( DEFAULT_INSTANCE, data); } public static org.bitcoinj.wallet.Protos.Wallet parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return com.google.protobuf.GeneratedMessageLite.parseFrom( DEFAULT_INSTANCE, data, extensionRegistry); } public static org.bitcoinj.wallet.Protos.Wallet parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageLite.parseFrom( DEFAULT_INSTANCE, input); } public static org.bitcoinj.wallet.Protos.Wallet parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageLite.parseFrom( DEFAULT_INSTANCE, input, extensionRegistry); } public static org.bitcoinj.wallet.Protos.Wallet parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return parseDelimitedFrom(DEFAULT_INSTANCE, input); } public static org.bitcoinj.wallet.Protos.Wallet parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return parseDelimitedFrom(DEFAULT_INSTANCE, input, extensionRegistry); } public static org.bitcoinj.wallet.Protos.Wallet parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageLite.parseFrom( DEFAULT_INSTANCE, input); } public static org.bitcoinj.wallet.Protos.Wallet parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageLite.parseFrom( DEFAULT_INSTANCE, input, extensionRegistry); } public static Builder newBuilder() { return (Builder) DEFAULT_INSTANCE.createBuilder(); } public static Builder newBuilder(org.bitcoinj.wallet.Protos.Wallet prototype) { return (Builder) DEFAULT_INSTANCE.createBuilder(prototype); } /** * <pre> ** A bitcoin wallet * </pre> * * Protobuf type {@code wallet.Wallet} */ public static final class Builder extends com.google.protobuf.GeneratedMessageLite.Builder< org.bitcoinj.wallet.Protos.Wallet, Builder> implements // @@protoc_insertion_point(builder_implements:wallet.Wallet) org.bitcoinj.wallet.Protos.WalletOrBuilder { // Construct using org.bitcoinj.wallet.Protos.Wallet.newBuilder() private Builder() { super(DEFAULT_INSTANCE); } /** * <pre> * the network used by this wallet * </pre> * * <code>required string network_identifier = 1;</code> * @return Whether the networkIdentifier field is set. */ @java.lang.Override public boolean hasNetworkIdentifier() { return instance.hasNetworkIdentifier(); } /** * <pre> * the network used by this wallet * </pre> * * <code>required string network_identifier = 1;</code> * @return The networkIdentifier. */ @java.lang.Override public java.lang.String getNetworkIdentifier() { return instance.getNetworkIdentifier(); } /** * <pre> * the network used by this wallet * </pre> * * <code>required string network_identifier = 1;</code> * @return The bytes for networkIdentifier. */ @java.lang.Override public com.google.protobuf.ByteString getNetworkIdentifierBytes() { return instance.getNetworkIdentifierBytes(); } /** * <pre> * the network used by this wallet * </pre> * * <code>required string network_identifier = 1;</code> * @param value The networkIdentifier to set. * @return This builder for chaining. */ public Builder setNetworkIdentifier( java.lang.String value) { copyOnWrite(); instance.setNetworkIdentifier(value); return this; } /** * <pre> * the network used by this wallet * </pre> * * <code>required string network_identifier = 1;</code> * @return This builder for chaining. */ public Builder clearNetworkIdentifier() { copyOnWrite(); instance.clearNetworkIdentifier(); return this; } /** * <pre> * the network used by this wallet * </pre> * * <code>required string network_identifier = 1;</code> * @param value The bytes for networkIdentifier to set. * @return This builder for chaining. */ public Builder setNetworkIdentifierBytes( com.google.protobuf.ByteString value) { copyOnWrite(); instance.setNetworkIdentifierBytes(value); return this; } /** * <pre> * The SHA256 hash of the head of the best chain seen by this wallet. * </pre> * * <code>optional bytes last_seen_block_hash = 2;</code> * @return Whether the lastSeenBlockHash field is set. */ @java.lang.Override public boolean hasLastSeenBlockHash() { return instance.hasLastSeenBlockHash(); } /** * <pre> * The SHA256 hash of the head of the best chain seen by this wallet. * </pre> * * <code>optional bytes last_seen_block_hash = 2;</code> * @return The lastSeenBlockHash. */ @java.lang.Override public com.google.protobuf.ByteString getLastSeenBlockHash() { return instance.getLastSeenBlockHash(); } /** * <pre> * The SHA256 hash of the head of the best chain seen by this wallet. * </pre> * * <code>optional bytes last_seen_block_hash = 2;</code> * @param value The lastSeenBlockHash to set. * @return This builder for chaining. */ public Builder setLastSeenBlockHash(com.google.protobuf.ByteString value) { copyOnWrite(); instance.setLastSeenBlockHash(value); return this; } /** * <pre> * The SHA256 hash of the head of the best chain seen by this wallet. * </pre> * * <code>optional bytes last_seen_block_hash = 2;</code> * @return This builder for chaining. */ public Builder clearLastSeenBlockHash() { copyOnWrite(); instance.clearLastSeenBlockHash(); return this; } /** * <pre> * The height in the chain of the last seen block. * </pre> * * <code>optional uint32 last_seen_block_height = 12;</code> * @return Whether the lastSeenBlockHeight field is set. */ @java.lang.Override public boolean hasLastSeenBlockHeight() { return instance.hasLastSeenBlockHeight(); } /** * <pre> * The height in the chain of the last seen block. * </pre> * * <code>optional uint32 last_seen_block_height = 12;</code> * @return The lastSeenBlockHeight. */ @java.lang.Override public int getLastSeenBlockHeight() { return instance.getLastSeenBlockHeight(); } /** * <pre> * The height in the chain of the last seen block. * </pre> * * <code>optional uint32 last_seen_block_height = 12;</code> * @param value The lastSeenBlockHeight to set. * @return This builder for chaining. */ public Builder setLastSeenBlockHeight(int value) { copyOnWrite(); instance.setLastSeenBlockHeight(value); return this; } /** * <pre> * The height in the chain of the last seen block. * </pre> * * <code>optional uint32 last_seen_block_height = 12;</code> * @return This builder for chaining. */ public Builder clearLastSeenBlockHeight() { copyOnWrite(); instance.clearLastSeenBlockHeight(); return this; } /** * <code>optional int64 last_seen_block_time_secs = 14;</code> * @return Whether the lastSeenBlockTimeSecs field is set. */ @java.lang.Override public boolean hasLastSeenBlockTimeSecs() { return instance.hasLastSeenBlockTimeSecs(); } /** * <code>optional int64 last_seen_block_time_secs = 14;</code> * @return The lastSeenBlockTimeSecs. */ @java.lang.Override public long getLastSeenBlockTimeSecs() { return instance.getLastSeenBlockTimeSecs(); } /** * <code>optional int64 last_seen_block_time_secs = 14;</code> * @param value The lastSeenBlockTimeSecs to set. * @return This builder for chaining. */ public Builder setLastSeenBlockTimeSecs(long value) { copyOnWrite(); instance.setLastSeenBlockTimeSecs(value); return this; } /** * <code>optional int64 last_seen_block_time_secs = 14;</code> * @return This builder for chaining. */ public Builder clearLastSeenBlockTimeSecs() { copyOnWrite(); instance.clearLastSeenBlockTimeSecs(); return this; } /** * <code>repeated .wallet.Key key = 3;</code> */ @java.lang.Override public java.util.List<org.bitcoinj.wallet.Protos.Key> getKeyList() { return java.util.Collections.unmodifiableList( instance.getKeyList()); } /** * <code>repeated .wallet.Key key = 3;</code> */ @java.lang.Override public int getKeyCount() { return instance.getKeyCount(); }/** * <code>repeated .wallet.Key key = 3;</code> */ @java.lang.Override public org.bitcoinj.wallet.Protos.Key getKey(int index) { return instance.getKey(index); } /** * <code>repeated .wallet.Key key = 3;</code> */ public Builder setKey( int index, org.bitcoinj.wallet.Protos.Key value) { copyOnWrite(); instance.setKey(index, value); return this; } /** * <code>repeated .wallet.Key key = 3;</code> */ public Builder setKey( int index, org.bitcoinj.wallet.Protos.Key.Builder builderForValue) { copyOnWrite(); instance.setKey(index, builderForValue.build()); return this; } /** * <code>repeated .wallet.Key key = 3;</code> */ public Builder addKey(org.bitcoinj.wallet.Protos.Key value) { copyOnWrite(); instance.addKey(value); return this; } /** * <code>repeated .wallet.Key key = 3;</code> */ public Builder addKey( int index, org.bitcoinj.wallet.Protos.Key value) { copyOnWrite(); instance.addKey(index, value); return this; } /** * <code>repeated .wallet.Key key = 3;</code> */ public Builder addKey( org.bitcoinj.wallet.Protos.Key.Builder builderForValue) { copyOnWrite(); instance.addKey(builderForValue.build()); return this; } /** * <code>repeated .wallet.Key key = 3;</code> */ public Builder addKey( int index, org.bitcoinj.wallet.Protos.Key.Builder builderForValue) { copyOnWrite(); instance.addKey(index, builderForValue.build()); return this; } /** * <code>repeated .wallet.Key key = 3;</code> */ public Builder addAllKey( java.lang.Iterable<? extends org.bitcoinj.wallet.Protos.Key> values) { copyOnWrite(); instance.addAllKey(values); return this; } /** * <code>repeated .wallet.Key key = 3;</code> */ public Builder clearKey() { copyOnWrite(); instance.clearKey(); return this; } /** * <code>repeated .wallet.Key key = 3;</code> */ public Builder removeKey(int index) { copyOnWrite(); instance.removeKey(index); return this; } /** * <code>repeated .wallet.Transaction transaction = 4;</code> */ @java.lang.Override public java.util.List<org.bitcoinj.wallet.Protos.Transaction> getTransactionList() { return java.util.Collections.unmodifiableList( instance.getTransactionList()); } /** * <code>repeated .wallet.Transaction transaction = 4;</code> */ @java.lang.Override public int getTransactionCount() { return instance.getTransactionCount(); }/** * <code>repeated .wallet.Transaction transaction = 4;</code> */ @java.lang.Override public org.bitcoinj.wallet.Protos.Transaction getTransaction(int index) { return instance.getTransaction(index); } /** * <code>repeated .wallet.Transaction transaction = 4;</code> */ public Builder setTransaction( int index, org.bitcoinj.wallet.Protos.Transaction value) { copyOnWrite(); instance.setTransaction(index, value); return this; } /** * <code>repeated .wallet.Transaction transaction = 4;</code> */ public Builder setTransaction( int index, org.bitcoinj.wallet.Protos.Transaction.Builder builderForValue) { copyOnWrite(); instance.setTransaction(index, builderForValue.build()); return this; } /** * <code>repeated .wallet.Transaction transaction = 4;</code> */ public Builder addTransaction(org.bitcoinj.wallet.Protos.Transaction value) { copyOnWrite(); instance.addTransaction(value); return this; } /** * <code>repeated .wallet.Transaction transaction = 4;</code> */ public Builder addTransaction( int index, org.bitcoinj.wallet.Protos.Transaction value) { copyOnWrite(); instance.addTransaction(index, value); return this; } /** * <code>repeated .wallet.Transaction transaction = 4;</code> */ public Builder addTransaction( org.bitcoinj.wallet.Protos.Transaction.Builder builderForValue) { copyOnWrite(); instance.addTransaction(builderForValue.build()); return this; } /** * <code>repeated .wallet.Transaction transaction = 4;</code> */ public Builder addTransaction( int index, org.bitcoinj.wallet.Protos.Transaction.Builder builderForValue) { copyOnWrite(); instance.addTransaction(index, builderForValue.build()); return this; } /** * <code>repeated .wallet.Transaction transaction = 4;</code> */ public Builder addAllTransaction( java.lang.Iterable<? extends org.bitcoinj.wallet.Protos.Transaction> values) { copyOnWrite(); instance.addAllTransaction(values); return this; } /** * <code>repeated .wallet.Transaction transaction = 4;</code> */ public Builder clearTransaction() { copyOnWrite(); instance.clearTransaction(); return this; } /** * <code>repeated .wallet.Transaction transaction = 4;</code> */ public Builder removeTransaction(int index) { copyOnWrite(); instance.removeTransaction(index); return this; } /** * <code>repeated .wallet.Script watched_script = 15;</code> */ @java.lang.Override public java.util.List<org.bitcoinj.wallet.Protos.Script> getWatchedScriptList() { return java.util.Collections.unmodifiableList( instance.getWatchedScriptList()); } /** * <code>repeated .wallet.Script watched_script = 15;</code> */ @java.lang.Override public int getWatchedScriptCount() { return instance.getWatchedScriptCount(); }/** * <code>repeated .wallet.Script watched_script = 15;</code> */ @java.lang.Override public org.bitcoinj.wallet.Protos.Script getWatchedScript(int index) { return instance.getWatchedScript(index); } /** * <code>repeated .wallet.Script watched_script = 15;</code> */ public Builder setWatchedScript( int index, org.bitcoinj.wallet.Protos.Script value) { copyOnWrite(); instance.setWatchedScript(index, value); return this; } /** * <code>repeated .wallet.Script watched_script = 15;</code> */ public Builder setWatchedScript( int index, org.bitcoinj.wallet.Protos.Script.Builder builderForValue) { copyOnWrite(); instance.setWatchedScript(index, builderForValue.build()); return this; } /** * <code>repeated .wallet.Script watched_script = 15;</code> */ public Builder addWatchedScript(org.bitcoinj.wallet.Protos.Script value) { copyOnWrite(); instance.addWatchedScript(value); return this; } /** * <code>repeated .wallet.Script watched_script = 15;</code> */ public Builder addWatchedScript( int index, org.bitcoinj.wallet.Protos.Script value) { copyOnWrite(); instance.addWatchedScript(index, value); return this; } /** * <code>repeated .wallet.Script watched_script = 15;</code> */ public Builder addWatchedScript( org.bitcoinj.wallet.Protos.Script.Builder builderForValue) { copyOnWrite(); instance.addWatchedScript(builderForValue.build()); return this; } /** * <code>repeated .wallet.Script watched_script = 15;</code> */ public Builder addWatchedScript( int index, org.bitcoinj.wallet.Protos.Script.Builder builderForValue) { copyOnWrite(); instance.addWatchedScript(index, builderForValue.build()); return this; } /** * <code>repeated .wallet.Script watched_script = 15;</code> */ public Builder addAllWatchedScript( java.lang.Iterable<? extends org.bitcoinj.wallet.Protos.Script> values) { copyOnWrite(); instance.addAllWatchedScript(values); return this; } /** * <code>repeated .wallet.Script watched_script = 15;</code> */ public Builder clearWatchedScript() { copyOnWrite(); instance.clearWatchedScript(); return this; } /** * <code>repeated .wallet.Script watched_script = 15;</code> */ public Builder removeWatchedScript(int index) { copyOnWrite(); instance.removeWatchedScript(index); return this; } /** * <code>optional .wallet.Wallet.EncryptionType encryption_type = 5 [default = UNENCRYPTED];</code> * @return Whether the encryptionType field is set. */ @java.lang.Override public boolean hasEncryptionType() { return instance.hasEncryptionType(); } /** * <code>optional .wallet.Wallet.EncryptionType encryption_type = 5 [default = UNENCRYPTED];</code> * @return The encryptionType. */ @java.lang.Override public org.bitcoinj.wallet.Protos.Wallet.EncryptionType getEncryptionType() { return instance.getEncryptionType(); } /** * <code>optional .wallet.Wallet.EncryptionType encryption_type = 5 [default = UNENCRYPTED];</code> * @param value The enum numeric value on the wire for encryptionType to set. * @return This builder for chaining. */ public Builder setEncryptionType(org.bitcoinj.wallet.Protos.Wallet.EncryptionType value) { copyOnWrite(); instance.setEncryptionType(value); return this; } /** * <code>optional .wallet.Wallet.EncryptionType encryption_type = 5 [default = UNENCRYPTED];</code> * @return This builder for chaining. */ public Builder clearEncryptionType() { copyOnWrite(); instance.clearEncryptionType(); return this; } /** * <code>optional .wallet.ScryptParameters encryption_parameters = 6;</code> */ @java.lang.Override public boolean hasEncryptionParameters() { return instance.hasEncryptionParameters(); } /** * <code>optional .wallet.ScryptParameters encryption_parameters = 6;</code> */ @java.lang.Override public org.bitcoinj.wallet.Protos.ScryptParameters getEncryptionParameters() { return instance.getEncryptionParameters(); } /** * <code>optional .wallet.ScryptParameters encryption_parameters = 6;</code> */ public Builder setEncryptionParameters(org.bitcoinj.wallet.Protos.ScryptParameters value) { copyOnWrite(); instance.setEncryptionParameters(value); return this; } /** * <code>optional .wallet.ScryptParameters encryption_parameters = 6;</code> */ public Builder setEncryptionParameters( org.bitcoinj.wallet.Protos.ScryptParameters.Builder builderForValue) { copyOnWrite(); instance.setEncryptionParameters(builderForValue.build()); return this; } /** * <code>optional .wallet.ScryptParameters encryption_parameters = 6;</code> */ public Builder mergeEncryptionParameters(org.bitcoinj.wallet.Protos.ScryptParameters value) { copyOnWrite(); instance.mergeEncryptionParameters(value); return this; } /** * <code>optional .wallet.ScryptParameters encryption_parameters = 6;</code> */ public Builder clearEncryptionParameters() { copyOnWrite(); instance.clearEncryptionParameters(); return this; } /** * <pre> * The version number of the wallet - used to detect wallets that were produced in the future * (i.e. the wallet may contain some future format this protobuf or parser code does not know about). * A version that's higher than the default is considered from the future. * </pre> * * <code>optional int32 version = 7 [default = 1];</code> * @return Whether the version field is set. */ @java.lang.Override public boolean hasVersion() { return instance.hasVersion(); } /** * <pre> * The version number of the wallet - used to detect wallets that were produced in the future * (i.e. the wallet may contain some future format this protobuf or parser code does not know about). * A version that's higher than the default is considered from the future. * </pre> * * <code>optional int32 version = 7 [default = 1];</code> * @return The version. */ @java.lang.Override public int getVersion() { return instance.getVersion(); } /** * <pre> * The version number of the wallet - used to detect wallets that were produced in the future * (i.e. the wallet may contain some future format this protobuf or parser code does not know about). * A version that's higher than the default is considered from the future. * </pre> * * <code>optional int32 version = 7 [default = 1];</code> * @param value The version to set. * @return This builder for chaining. */ public Builder setVersion(int value) { copyOnWrite(); instance.setVersion(value); return this; } /** * <pre> * The version number of the wallet - used to detect wallets that were produced in the future * (i.e. the wallet may contain some future format this protobuf or parser code does not know about). * A version that's higher than the default is considered from the future. * </pre> * * <code>optional int32 version = 7 [default = 1];</code> * @return This builder for chaining. */ public Builder clearVersion() { copyOnWrite(); instance.clearVersion(); return this; } /** * <code>repeated .wallet.Extension extension = 10;</code> */ @java.lang.Override public java.util.List<org.bitcoinj.wallet.Protos.Extension> getExtensionList() { return java.util.Collections.unmodifiableList( instance.getExtensionList()); } /** * <code>repeated .wallet.Extension extension = 10;</code> */ @java.lang.Override public int getExtensionCount() { return instance.getExtensionCount(); }/** * <code>repeated .wallet.Extension extension = 10;</code> */ @java.lang.Override public org.bitcoinj.wallet.Protos.Extension getExtension(int index) { return instance.getExtension(index); } /** * <code>repeated .wallet.Extension extension = 10;</code> */ public Builder setExtension( int index, org.bitcoinj.wallet.Protos.Extension value) { copyOnWrite(); instance.setExtension(index, value); return this; } /** * <code>repeated .wallet.Extension extension = 10;</code> */ public Builder setExtension( int index, org.bitcoinj.wallet.Protos.Extension.Builder builderForValue) { copyOnWrite(); instance.setExtension(index, builderForValue.build()); return this; } /** * <code>repeated .wallet.Extension extension = 10;</code> */ public Builder addExtension(org.bitcoinj.wallet.Protos.Extension value) { copyOnWrite(); instance.addExtension(value); return this; } /** * <code>repeated .wallet.Extension extension = 10;</code> */ public Builder addExtension( int index, org.bitcoinj.wallet.Protos.Extension value) { copyOnWrite(); instance.addExtension(index, value); return this; } /** * <code>repeated .wallet.Extension extension = 10;</code> */ public Builder addExtension( org.bitcoinj.wallet.Protos.Extension.Builder builderForValue) { copyOnWrite(); instance.addExtension(builderForValue.build()); return this; } /** * <code>repeated .wallet.Extension extension = 10;</code> */ public Builder addExtension( int index, org.bitcoinj.wallet.Protos.Extension.Builder builderForValue) { copyOnWrite(); instance.addExtension(index, builderForValue.build()); return this; } /** * <code>repeated .wallet.Extension extension = 10;</code> */ public Builder addAllExtension( java.lang.Iterable<? extends org.bitcoinj.wallet.Protos.Extension> values) { copyOnWrite(); instance.addAllExtension(values); return this; } /** * <code>repeated .wallet.Extension extension = 10;</code> */ public Builder clearExtension() { copyOnWrite(); instance.clearExtension(); return this; } /** * <code>repeated .wallet.Extension extension = 10;</code> */ public Builder removeExtension(int index) { copyOnWrite(); instance.removeExtension(index); return this; } /** * <pre> * A UTF8 encoded text description of the wallet that is intended for end user provided text. * </pre> * * <code>optional string description = 11;</code> * @return Whether the description field is set. */ @java.lang.Override public boolean hasDescription() { return instance.hasDescription(); } /** * <pre> * A UTF8 encoded text description of the wallet that is intended for end user provided text. * </pre> * * <code>optional string description = 11;</code> * @return The description. */ @java.lang.Override public java.lang.String getDescription() { return instance.getDescription(); } /** * <pre> * A UTF8 encoded text description of the wallet that is intended for end user provided text. * </pre> * * <code>optional string description = 11;</code> * @return The bytes for description. */ @java.lang.Override public com.google.protobuf.ByteString getDescriptionBytes() { return instance.getDescriptionBytes(); } /** * <pre> * A UTF8 encoded text description of the wallet that is intended for end user provided text. * </pre> * * <code>optional string description = 11;</code> * @param value The description to set. * @return This builder for chaining. */ public Builder setDescription( java.lang.String value) { copyOnWrite(); instance.setDescription(value); return this; } /** * <pre> * A UTF8 encoded text description of the wallet that is intended for end user provided text. * </pre> * * <code>optional string description = 11;</code> * @return This builder for chaining. */ public Builder clearDescription() { copyOnWrite(); instance.clearDescription(); return this; } /** * <pre> * A UTF8 encoded text description of the wallet that is intended for end user provided text. * </pre> * * <code>optional string description = 11;</code> * @param value The bytes for description to set. * @return This builder for chaining. */ public Builder setDescriptionBytes( com.google.protobuf.ByteString value) { copyOnWrite(); instance.setDescriptionBytes(value); return this; } /** * <pre> * UNIX time in seconds since the epoch. If set, then any keys created before this date are assumed to be no longer * wanted. Money sent to them will be re-spent automatically to the first key that was created after this time. It * can be used to recover a compromised wallet, or just as part of preventative defence-in-depth measures. * </pre> * * <code>optional uint64 key_rotation_time = 13;</code> * @return Whether the keyRotationTime field is set. */ @java.lang.Override public boolean hasKeyRotationTime() { return instance.hasKeyRotationTime(); } /** * <pre> * UNIX time in seconds since the epoch. If set, then any keys created before this date are assumed to be no longer * wanted. Money sent to them will be re-spent automatically to the first key that was created after this time. It * can be used to recover a compromised wallet, or just as part of preventative defence-in-depth measures. * </pre> * * <code>optional uint64 key_rotation_time = 13;</code> * @return The keyRotationTime. */ @java.lang.Override public long getKeyRotationTime() { return instance.getKeyRotationTime(); } /** * <pre> * UNIX time in seconds since the epoch. If set, then any keys created before this date are assumed to be no longer * wanted. Money sent to them will be re-spent automatically to the first key that was created after this time. It * can be used to recover a compromised wallet, or just as part of preventative defence-in-depth measures. * </pre> * * <code>optional uint64 key_rotation_time = 13;</code> * @param value The keyRotationTime to set. * @return This builder for chaining. */ public Builder setKeyRotationTime(long value) { copyOnWrite(); instance.setKeyRotationTime(value); return this; } /** * <pre> * UNIX time in seconds since the epoch. If set, then any keys created before this date are assumed to be no longer * wanted. Money sent to them will be re-spent automatically to the first key that was created after this time. It * can be used to recover a compromised wallet, or just as part of preventative defence-in-depth measures. * </pre> * * <code>optional uint64 key_rotation_time = 13;</code> * @return This builder for chaining. */ public Builder clearKeyRotationTime() { copyOnWrite(); instance.clearKeyRotationTime(); return this; } /** * <code>repeated .wallet.Tag tags = 16;</code> */ @java.lang.Override public java.util.List<org.bitcoinj.wallet.Protos.Tag> getTagsList() { return java.util.Collections.unmodifiableList( instance.getTagsList()); } /** * <code>repeated .wallet.Tag tags = 16;</code> */ @java.lang.Override public int getTagsCount() { return instance.getTagsCount(); }/** * <code>repeated .wallet.Tag tags = 16;</code> */ @java.lang.Override public org.bitcoinj.wallet.Protos.Tag getTags(int index) { return instance.getTags(index); } /** * <code>repeated .wallet.Tag tags = 16;</code> */ public Builder setTags( int index, org.bitcoinj.wallet.Protos.Tag value) { copyOnWrite(); instance.setTags(index, value); return this; } /** * <code>repeated .wallet.Tag tags = 16;</code> */ public Builder setTags( int index, org.bitcoinj.wallet.Protos.Tag.Builder builderForValue) { copyOnWrite(); instance.setTags(index, builderForValue.build()); return this; } /** * <code>repeated .wallet.Tag tags = 16;</code> */ public Builder addTags(org.bitcoinj.wallet.Protos.Tag value) { copyOnWrite(); instance.addTags(value); return this; } /** * <code>repeated .wallet.Tag tags = 16;</code> */ public Builder addTags( int index, org.bitcoinj.wallet.Protos.Tag value) { copyOnWrite(); instance.addTags(index, value); return this; } /** * <code>repeated .wallet.Tag tags = 16;</code> */ public Builder addTags( org.bitcoinj.wallet.Protos.Tag.Builder builderForValue) { copyOnWrite(); instance.addTags(builderForValue.build()); return this; } /** * <code>repeated .wallet.Tag tags = 16;</code> */ public Builder addTags( int index, org.bitcoinj.wallet.Protos.Tag.Builder builderForValue) { copyOnWrite(); instance.addTags(index, builderForValue.build()); return this; } /** * <code>repeated .wallet.Tag tags = 16;</code> */ public Builder addAllTags( java.lang.Iterable<? extends org.bitcoinj.wallet.Protos.Tag> values) { copyOnWrite(); instance.addAllTags(values); return this; } /** * <code>repeated .wallet.Tag tags = 16;</code> */ public Builder clearTags() { copyOnWrite(); instance.clearTags(); return this; } /** * <code>repeated .wallet.Tag tags = 16;</code> */ public Builder removeTags(int index) { copyOnWrite(); instance.removeTags(index); return this; } // @@protoc_insertion_point(builder_scope:wallet.Wallet) } private byte memoizedIsInitialized = 2; @java.lang.Override @java.lang.SuppressWarnings({"unchecked", "fallthrough"}) protected final java.lang.Object dynamicMethod( com.google.protobuf.GeneratedMessageLite.MethodToInvoke method, java.lang.Object arg0, java.lang.Object arg1) { switch (method) { case NEW_MUTABLE_INSTANCE: { return new org.bitcoinj.wallet.Protos.Wallet(); } case NEW_BUILDER: { return new Builder(); } case BUILD_MESSAGE_INFO: { java.lang.Object[] objects = new java.lang.Object[] { "bitField0_", "networkIdentifier_", "lastSeenBlockHash_", "key_", org.bitcoinj.wallet.Protos.Key.class, "transaction_", org.bitcoinj.wallet.Protos.Transaction.class, "encryptionType_", org.bitcoinj.wallet.Protos.Wallet.EncryptionType.internalGetVerifier(), "encryptionParameters_", "version_", "extension_", org.bitcoinj.wallet.Protos.Extension.class, "description_", "lastSeenBlockHeight_", "keyRotationTime_", "lastSeenBlockTimeSecs_", "watchedScript_", org.bitcoinj.wallet.Protos.Script.class, "tags_", org.bitcoinj.wallet.Protos.Tag.class, }; java.lang.String info = "\u0001\u000e\u0000\u0001\u0001\u0010\u000e\u0000\u0005\u0007\u0001\u1508\u0000\u0002" + "\u100a\u0001\u0003\u041b\u0004\u041b\u0005\u100c\u0004\u0006\u1409\u0005\u0007\u1004" + "\u0006\n\u041b\u000b\u1008\u0007\f\u100b\u0002\r\u1003\b\u000e\u1002\u0003\u000f" + "\u041b\u0010\u041b"; return newMessageInfo(DEFAULT_INSTANCE, info, objects); } // fall through case GET_DEFAULT_INSTANCE: { return DEFAULT_INSTANCE; } case GET_PARSER: { com.google.protobuf.Parser<org.bitcoinj.wallet.Protos.Wallet> parser = PARSER; if (parser == null) { synchronized (org.bitcoinj.wallet.Protos.Wallet.class) { parser = PARSER; if (parser == null) { parser = new DefaultInstanceBasedParser<org.bitcoinj.wallet.Protos.Wallet>( DEFAULT_INSTANCE); PARSER = parser; } } } return parser; } case GET_MEMOIZED_IS_INITIALIZED: { return memoizedIsInitialized; } case SET_MEMOIZED_IS_INITIALIZED: { memoizedIsInitialized = (byte) (arg0 == null ? 0 : 1); return null; } } throw new UnsupportedOperationException(); } // @@protoc_insertion_point(class_scope:wallet.Wallet) private static final org.bitcoinj.wallet.Protos.Wallet DEFAULT_INSTANCE; static { Wallet defaultInstance = new Wallet(); // New instances are implicitly immutable so no need to make // immutable. DEFAULT_INSTANCE = defaultInstance; com.google.protobuf.GeneratedMessageLite.registerDefaultInstance( Wallet.class, defaultInstance); } public static org.bitcoinj.wallet.Protos.Wallet getDefaultInstance() { return DEFAULT_INSTANCE; } private static volatile com.google.protobuf.Parser<Wallet> PARSER; public static com.google.protobuf.Parser<Wallet> parser() { return DEFAULT_INSTANCE.getParserForType(); } } public interface ExchangeRateOrBuilder extends // @@protoc_insertion_point(interface_extends:wallet.ExchangeRate) com.google.protobuf.MessageLiteOrBuilder { /** * <pre> * This much of satoshis (1E-8 fractions)… * </pre> * * <code>required int64 coin_value = 1;</code> * @return Whether the coinValue field is set. */ boolean hasCoinValue(); /** * <pre> * This much of satoshis (1E-8 fractions)… * </pre> * * <code>required int64 coin_value = 1;</code> * @return The coinValue. */ long getCoinValue(); /** * <pre> * …is worth this much of fiat (1E-4 fractions). * </pre> * * <code>required int64 fiat_value = 2;</code> * @return Whether the fiatValue field is set. */ boolean hasFiatValue(); /** * <pre> * …is worth this much of fiat (1E-4 fractions). * </pre> * * <code>required int64 fiat_value = 2;</code> * @return The fiatValue. */ long getFiatValue(); /** * <pre> * ISO 4217 currency code (if available) of the fiat currency. * </pre> * * <code>required string fiat_currency_code = 3;</code> * @return Whether the fiatCurrencyCode field is set. */ boolean hasFiatCurrencyCode(); /** * <pre> * ISO 4217 currency code (if available) of the fiat currency. * </pre> * * <code>required string fiat_currency_code = 3;</code> * @return The fiatCurrencyCode. */ java.lang.String getFiatCurrencyCode(); /** * <pre> * ISO 4217 currency code (if available) of the fiat currency. * </pre> * * <code>required string fiat_currency_code = 3;</code> * @return The bytes for fiatCurrencyCode. */ com.google.protobuf.ByteString getFiatCurrencyCodeBytes(); } /** * <pre> ** An exchange rate between Bitcoin and some fiat currency. * </pre> * * Protobuf type {@code wallet.ExchangeRate} */ public static final class ExchangeRate extends com.google.protobuf.GeneratedMessageLite< ExchangeRate, ExchangeRate.Builder> implements // @@protoc_insertion_point(message_implements:wallet.ExchangeRate) ExchangeRateOrBuilder { private ExchangeRate() { fiatCurrencyCode_ = ""; } private int bitField0_; public static final int COIN_VALUE_FIELD_NUMBER = 1; private long coinValue_; /** * <pre> * This much of satoshis (1E-8 fractions)… * </pre> * * <code>required int64 coin_value = 1;</code> * @return Whether the coinValue field is set. */ @java.lang.Override public boolean hasCoinValue() { return ((bitField0_ & 0x00000001) != 0); } /** * <pre> * This much of satoshis (1E-8 fractions)… * </pre> * * <code>required int64 coin_value = 1;</code> * @return The coinValue. */ @java.lang.Override public long getCoinValue() { return coinValue_; } /** * <pre> * This much of satoshis (1E-8 fractions)… * </pre> * * <code>required int64 coin_value = 1;</code> * @param value The coinValue to set. */ private void setCoinValue(long value) { bitField0_ |= 0x00000001; coinValue_ = value; } /** * <pre> * This much of satoshis (1E-8 fractions)… * </pre> * * <code>required int64 coin_value = 1;</code> */ private void clearCoinValue() { bitField0_ = (bitField0_ & ~0x00000001); coinValue_ = 0L; } public static final int FIAT_VALUE_FIELD_NUMBER = 2; private long fiatValue_; /** * <pre> * …is worth this much of fiat (1E-4 fractions). * </pre> * * <code>required int64 fiat_value = 2;</code> * @return Whether the fiatValue field is set. */ @java.lang.Override public boolean hasFiatValue() { return ((bitField0_ & 0x00000002) != 0); } /** * <pre> * …is worth this much of fiat (1E-4 fractions). * </pre> * * <code>required int64 fiat_value = 2;</code> * @return The fiatValue. */ @java.lang.Override public long getFiatValue() { return fiatValue_; } /** * <pre> * …is worth this much of fiat (1E-4 fractions). * </pre> * * <code>required int64 fiat_value = 2;</code> * @param value The fiatValue to set. */ private void setFiatValue(long value) { bitField0_ |= 0x00000002; fiatValue_ = value; } /** * <pre> * …is worth this much of fiat (1E-4 fractions). * </pre> * * <code>required int64 fiat_value = 2;</code> */ private void clearFiatValue() { bitField0_ = (bitField0_ & ~0x00000002); fiatValue_ = 0L; } public static final int FIAT_CURRENCY_CODE_FIELD_NUMBER = 3; private java.lang.String fiatCurrencyCode_; /** * <pre> * ISO 4217 currency code (if available) of the fiat currency. * </pre> * * <code>required string fiat_currency_code = 3;</code> * @return Whether the fiatCurrencyCode field is set. */ @java.lang.Override public boolean hasFiatCurrencyCode() { return ((bitField0_ & 0x00000004) != 0); } /** * <pre> * ISO 4217 currency code (if available) of the fiat currency. * </pre> * * <code>required string fiat_currency_code = 3;</code> * @return The fiatCurrencyCode. */ @java.lang.Override public java.lang.String getFiatCurrencyCode() { return fiatCurrencyCode_; } /** * <pre> * ISO 4217 currency code (if available) of the fiat currency. * </pre> * * <code>required string fiat_currency_code = 3;</code> * @return The bytes for fiatCurrencyCode. */ @java.lang.Override public com.google.protobuf.ByteString getFiatCurrencyCodeBytes() { return com.google.protobuf.ByteString.copyFromUtf8(fiatCurrencyCode_); } /** * <pre> * ISO 4217 currency code (if available) of the fiat currency. * </pre> * * <code>required string fiat_currency_code = 3;</code> * @param value The fiatCurrencyCode to set. */ private void setFiatCurrencyCode( java.lang.String value) { java.lang.Class<?> valueClass = value.getClass(); bitField0_ |= 0x00000004; fiatCurrencyCode_ = value; } /** * <pre> * ISO 4217 currency code (if available) of the fiat currency. * </pre> * * <code>required string fiat_currency_code = 3;</code> */ private void clearFiatCurrencyCode() { bitField0_ = (bitField0_ & ~0x00000004); fiatCurrencyCode_ = getDefaultInstance().getFiatCurrencyCode(); } /** * <pre> * ISO 4217 currency code (if available) of the fiat currency. * </pre> * * <code>required string fiat_currency_code = 3;</code> * @param value The bytes for fiatCurrencyCode to set. */ private void setFiatCurrencyCodeBytes( com.google.protobuf.ByteString value) { fiatCurrencyCode_ = value.toStringUtf8(); bitField0_ |= 0x00000004; } public static org.bitcoinj.wallet.Protos.ExchangeRate parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return com.google.protobuf.GeneratedMessageLite.parseFrom( DEFAULT_INSTANCE, data); } public static org.bitcoinj.wallet.Protos.ExchangeRate parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return com.google.protobuf.GeneratedMessageLite.parseFrom( DEFAULT_INSTANCE, data, extensionRegistry); } public static org.bitcoinj.wallet.Protos.ExchangeRate parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return com.google.protobuf.GeneratedMessageLite.parseFrom( DEFAULT_INSTANCE, data); } public static org.bitcoinj.wallet.Protos.ExchangeRate parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return com.google.protobuf.GeneratedMessageLite.parseFrom( DEFAULT_INSTANCE, data, extensionRegistry); } public static org.bitcoinj.wallet.Protos.ExchangeRate parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return com.google.protobuf.GeneratedMessageLite.parseFrom( DEFAULT_INSTANCE, data); } public static org.bitcoinj.wallet.Protos.ExchangeRate parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return com.google.protobuf.GeneratedMessageLite.parseFrom( DEFAULT_INSTANCE, data, extensionRegistry); } public static org.bitcoinj.wallet.Protos.ExchangeRate parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageLite.parseFrom( DEFAULT_INSTANCE, input); } public static org.bitcoinj.wallet.Protos.ExchangeRate parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageLite.parseFrom( DEFAULT_INSTANCE, input, extensionRegistry); } public static org.bitcoinj.wallet.Protos.ExchangeRate parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return parseDelimitedFrom(DEFAULT_INSTANCE, input); } public static org.bitcoinj.wallet.Protos.ExchangeRate parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return parseDelimitedFrom(DEFAULT_INSTANCE, input, extensionRegistry); } public static org.bitcoinj.wallet.Protos.ExchangeRate parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageLite.parseFrom( DEFAULT_INSTANCE, input); } public static org.bitcoinj.wallet.Protos.ExchangeRate parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageLite.parseFrom( DEFAULT_INSTANCE, input, extensionRegistry); } public static Builder newBuilder() { return (Builder) DEFAULT_INSTANCE.createBuilder(); } public static Builder newBuilder(org.bitcoinj.wallet.Protos.ExchangeRate prototype) { return (Builder) DEFAULT_INSTANCE.createBuilder(prototype); } /** * <pre> ** An exchange rate between Bitcoin and some fiat currency. * </pre> * * Protobuf type {@code wallet.ExchangeRate} */ public static final class Builder extends com.google.protobuf.GeneratedMessageLite.Builder< org.bitcoinj.wallet.Protos.ExchangeRate, Builder> implements // @@protoc_insertion_point(builder_implements:wallet.ExchangeRate) org.bitcoinj.wallet.Protos.ExchangeRateOrBuilder { // Construct using org.bitcoinj.wallet.Protos.ExchangeRate.newBuilder() private Builder() { super(DEFAULT_INSTANCE); } /** * <pre> * This much of satoshis (1E-8 fractions)… * </pre> * * <code>required int64 coin_value = 1;</code> * @return Whether the coinValue field is set. */ @java.lang.Override public boolean hasCoinValue() { return instance.hasCoinValue(); } /** * <pre> * This much of satoshis (1E-8 fractions)… * </pre> * * <code>required int64 coin_value = 1;</code> * @return The coinValue. */ @java.lang.Override public long getCoinValue() { return instance.getCoinValue(); } /** * <pre> * This much of satoshis (1E-8 fractions)… * </pre> * * <code>required int64 coin_value = 1;</code> * @param value The coinValue to set. * @return This builder for chaining. */ public Builder setCoinValue(long value) { copyOnWrite(); instance.setCoinValue(value); return this; } /** * <pre> * This much of satoshis (1E-8 fractions)… * </pre> * * <code>required int64 coin_value = 1;</code> * @return This builder for chaining. */ public Builder clearCoinValue() { copyOnWrite(); instance.clearCoinValue(); return this; } /** * <pre> * …is worth this much of fiat (1E-4 fractions). * </pre> * * <code>required int64 fiat_value = 2;</code> * @return Whether the fiatValue field is set. */ @java.lang.Override public boolean hasFiatValue() { return instance.hasFiatValue(); } /** * <pre> * …is worth this much of fiat (1E-4 fractions). * </pre> * * <code>required int64 fiat_value = 2;</code> * @return The fiatValue. */ @java.lang.Override public long getFiatValue() { return instance.getFiatValue(); } /** * <pre> * …is worth this much of fiat (1E-4 fractions). * </pre> * * <code>required int64 fiat_value = 2;</code> * @param value The fiatValue to set. * @return This builder for chaining. */ public Builder setFiatValue(long value) { copyOnWrite(); instance.setFiatValue(value); return this; } /** * <pre> * …is worth this much of fiat (1E-4 fractions). * </pre> * * <code>required int64 fiat_value = 2;</code> * @return This builder for chaining. */ public Builder clearFiatValue() { copyOnWrite(); instance.clearFiatValue(); return this; } /** * <pre> * ISO 4217 currency code (if available) of the fiat currency. * </pre> * * <code>required string fiat_currency_code = 3;</code> * @return Whether the fiatCurrencyCode field is set. */ @java.lang.Override public boolean hasFiatCurrencyCode() { return instance.hasFiatCurrencyCode(); } /** * <pre> * ISO 4217 currency code (if available) of the fiat currency. * </pre> * * <code>required string fiat_currency_code = 3;</code> * @return The fiatCurrencyCode. */ @java.lang.Override public java.lang.String getFiatCurrencyCode() { return instance.getFiatCurrencyCode(); } /** * <pre> * ISO 4217 currency code (if available) of the fiat currency. * </pre> * * <code>required string fiat_currency_code = 3;</code> * @return The bytes for fiatCurrencyCode. */ @java.lang.Override public com.google.protobuf.ByteString getFiatCurrencyCodeBytes() { return instance.getFiatCurrencyCodeBytes(); } /** * <pre> * ISO 4217 currency code (if available) of the fiat currency. * </pre> * * <code>required string fiat_currency_code = 3;</code> * @param value The fiatCurrencyCode to set. * @return This builder for chaining. */ public Builder setFiatCurrencyCode( java.lang.String value) { copyOnWrite(); instance.setFiatCurrencyCode(value); return this; } /** * <pre> * ISO 4217 currency code (if available) of the fiat currency. * </pre> * * <code>required string fiat_currency_code = 3;</code> * @return This builder for chaining. */ public Builder clearFiatCurrencyCode() { copyOnWrite(); instance.clearFiatCurrencyCode(); return this; } /** * <pre> * ISO 4217 currency code (if available) of the fiat currency. * </pre> * * <code>required string fiat_currency_code = 3;</code> * @param value The bytes for fiatCurrencyCode to set. * @return This builder for chaining. */ public Builder setFiatCurrencyCodeBytes( com.google.protobuf.ByteString value) { copyOnWrite(); instance.setFiatCurrencyCodeBytes(value); return this; } // @@protoc_insertion_point(builder_scope:wallet.ExchangeRate) } private byte memoizedIsInitialized = 2; @java.lang.Override @java.lang.SuppressWarnings({"unchecked", "fallthrough"}) protected final java.lang.Object dynamicMethod( com.google.protobuf.GeneratedMessageLite.MethodToInvoke method, java.lang.Object arg0, java.lang.Object arg1) { switch (method) { case NEW_MUTABLE_INSTANCE: { return new org.bitcoinj.wallet.Protos.ExchangeRate(); } case NEW_BUILDER: { return new Builder(); } case BUILD_MESSAGE_INFO: { java.lang.Object[] objects = new java.lang.Object[] { "bitField0_", "coinValue_", "fiatValue_", "fiatCurrencyCode_", }; java.lang.String info = "\u0001\u0003\u0000\u0001\u0001\u0003\u0003\u0000\u0000\u0003\u0001\u1502\u0000\u0002" + "\u1502\u0001\u0003\u1508\u0002"; return newMessageInfo(DEFAULT_INSTANCE, info, objects); } // fall through case GET_DEFAULT_INSTANCE: { return DEFAULT_INSTANCE; } case GET_PARSER: { com.google.protobuf.Parser<org.bitcoinj.wallet.Protos.ExchangeRate> parser = PARSER; if (parser == null) { synchronized (org.bitcoinj.wallet.Protos.ExchangeRate.class) { parser = PARSER; if (parser == null) { parser = new DefaultInstanceBasedParser<org.bitcoinj.wallet.Protos.ExchangeRate>( DEFAULT_INSTANCE); PARSER = parser; } } } return parser; } case GET_MEMOIZED_IS_INITIALIZED: { return memoizedIsInitialized; } case SET_MEMOIZED_IS_INITIALIZED: { memoizedIsInitialized = (byte) (arg0 == null ? 0 : 1); return null; } } throw new UnsupportedOperationException(); } // @@protoc_insertion_point(class_scope:wallet.ExchangeRate) private static final org.bitcoinj.wallet.Protos.ExchangeRate DEFAULT_INSTANCE; static { ExchangeRate defaultInstance = new ExchangeRate(); // New instances are implicitly immutable so no need to make // immutable. DEFAULT_INSTANCE = defaultInstance; com.google.protobuf.GeneratedMessageLite.registerDefaultInstance( ExchangeRate.class, defaultInstance); } public static org.bitcoinj.wallet.Protos.ExchangeRate getDefaultInstance() { return DEFAULT_INSTANCE; } private static volatile com.google.protobuf.Parser<ExchangeRate> PARSER; public static com.google.protobuf.Parser<ExchangeRate> parser() { return DEFAULT_INSTANCE.getParserForType(); } } static { } // @@protoc_insertion_point(outer_class_scope) }
511,169
32.425096
146
java
bitcoinj
bitcoinj-master/core/src/main/java/org/bitcoinj/wallet/DecryptingKeyBag.java
/* * Copyright 2014 The bitcoinj authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.bitcoinj.wallet; import org.bitcoinj.base.ScriptType; import org.bitcoinj.crypto.AesKey; import org.bitcoinj.crypto.ECKey; import javax.annotation.Nullable; import java.util.ArrayList; import java.util.List; import java.util.Objects; /** * A DecryptingKeyBag filters a pre-existing key bag, decrypting keys as they are requested using the provided * AES key. If the keys are encrypted and no AES key provided, {@link ECKey.KeyIsEncryptedException} * will be thrown. */ public class DecryptingKeyBag implements KeyBag { protected final KeyBag target; protected final AesKey aesKey; public DecryptingKeyBag(KeyBag target, @Nullable AesKey aesKey) { this.target = Objects.requireNonNull(target); this.aesKey = aesKey; } @Nullable private ECKey maybeDecrypt(ECKey key) { if (key == null) return null; else if (key.isEncrypted()) { if (aesKey == null) throw new ECKey.KeyIsEncryptedException(); return key.decrypt(aesKey); } else { return key; } } private RedeemData maybeDecrypt(RedeemData redeemData) { List<ECKey> decryptedKeys = new ArrayList<>(); for (ECKey key : redeemData.keys) { decryptedKeys.add(maybeDecrypt(key)); } return RedeemData.of(decryptedKeys, redeemData.redeemScript); } @Nullable @Override public ECKey findKeyFromPubKeyHash(byte[] pubKeyHash, @Nullable ScriptType scriptType) { return maybeDecrypt(target.findKeyFromPubKeyHash(pubKeyHash, scriptType)); } @Nullable @Override public ECKey findKeyFromPubKey(byte[] pubKey) { return maybeDecrypt(target.findKeyFromPubKey(pubKey)); } @Nullable @Override public RedeemData findRedeemDataFromScriptHash(byte[] scriptHash) { return maybeDecrypt(target.findRedeemDataFromScriptHash(scriptHash)); } }
2,554
30.54321
110
java
bitcoinj
bitcoinj-master/core/src/main/java/org/bitcoinj/wallet/DeterministicUpgradeRequiredException.java
/* * Copyright by the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.bitcoinj.wallet; /** * Indicates that an attempt was made to use HD wallet features on a wallet that was deserialized from an old, * pre-HD random wallet without calling upgradeToDeterministic() beforehand. */ public class DeterministicUpgradeRequiredException extends RuntimeException {}
919
37.333333
110
java
bitcoinj
bitcoinj-master/core/src/main/java/org/bitcoinj/wallet/RiskAnalysis.java
/* * Copyright 2013 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.bitcoinj.wallet; import org.bitcoinj.core.Transaction; import java.util.List; /** * <p>A RiskAnalysis represents an analysis of how likely it is that a transaction (and its dependencies) represents a * possible double spending attack. The wallet will create these to decide whether or not to accept a pending * transaction. Look at {@link DefaultRiskAnalysis} to see what is currently considered risky.</p> * * <p>The intention here is that implementing classes can expose more information and detail about the result, for * app developers. The core code needs only to know whether it's OK or not.</p> * * <p>A factory interface is provided. The wallet will use this to analyze new pending transactions.</p> */ public interface RiskAnalysis { enum Result { OK, NON_FINAL, NON_STANDARD } Result analyze(); interface Analyzer { RiskAnalysis create(Wallet wallet, Transaction tx, List<Transaction> dependencies); } }
1,587
33.521739
118
java
bitcoinj
bitcoinj-master/core/src/main/java/org/bitcoinj/wallet/DefaultRiskAnalysis.java
/* * Copyright 2013 Google Inc. * Copyright 2014 Andreas Schildbach * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.bitcoinj.wallet; import org.bitcoinj.base.BitcoinNetwork; import org.bitcoinj.crypto.ECKey; import org.bitcoinj.crypto.ECKey.ECDSASignature; import org.bitcoinj.crypto.SignatureDecodeException; import org.bitcoinj.core.Transaction; import org.bitcoinj.core.TransactionConfidence; import org.bitcoinj.core.TransactionInput; import org.bitcoinj.core.TransactionOutput; import org.bitcoinj.crypto.TransactionSignature; import org.bitcoinj.script.ScriptChunk; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.annotation.Nullable; import java.time.Instant; import java.util.List; import java.util.Optional; import static org.bitcoinj.base.internal.Preconditions.checkState; /** * <p>The default risk analysis. Currently, it only is concerned with whether a tx/dependency is non-final or not, and * whether a tx/dependency violates the dust rules. Outside of specialised protocols you should not encounter non-final * transactions.</p> */ public class DefaultRiskAnalysis implements RiskAnalysis { private static final Logger log = LoggerFactory.getLogger(DefaultRiskAnalysis.class); protected final Transaction tx; protected final List<Transaction> dependencies; @Nullable protected final Wallet wallet; private Transaction nonStandard; protected Transaction nonFinal; protected boolean analyzed; private DefaultRiskAnalysis(Wallet wallet, Transaction tx, List<Transaction> dependencies) { this.tx = tx; this.dependencies = dependencies; this.wallet = wallet; } @Override public Result analyze() { checkState(!analyzed); analyzed = true; Result result = analyzeIsFinal(); if (result != null && result != Result.OK) return result; return analyzeIsStandard(); } @Nullable private Result analyzeIsFinal() { // Transactions we create ourselves are, by definition, not at risk of double spending against us. if (tx.getConfidence().getSource() == TransactionConfidence.Source.SELF) return Result.OK; // We consider transactions that opt into replace-by-fee at risk of double spending. if (tx.isOptInFullRBF()) { nonFinal = tx; return Result.NON_FINAL; } // Relative time-locked transactions are risky too. We can't check the locks because usually we don't know the // spent outputs (to know when they were created). if (tx.hasRelativeLockTime()) { nonFinal = tx; return Result.NON_FINAL; } if (wallet == null) return null; final int height = wallet.getLastBlockSeenHeight(); final Optional<Instant> time = wallet.lastBlockSeenTime(); if (!time.isPresent()) return null; // If the transaction has a lock time specified in blocks, we consider that if the tx would become final in the // next block it is not risky (as it would confirm normally). final int adjustedHeight = height + 1; final long timeSecs = time.get().getEpochSecond(); if (!tx.isFinal(adjustedHeight, timeSecs)) { nonFinal = tx; return Result.NON_FINAL; } for (Transaction dep : dependencies) { if (!dep.isFinal(adjustedHeight, timeSecs)) { nonFinal = dep; return Result.NON_FINAL; } } return Result.OK; } /** * The reason a transaction is considered non-standard, returned by * {@link #isStandard(Transaction)}. */ public enum RuleViolation { NONE, VERSION, DUST, SHORTEST_POSSIBLE_PUSHDATA, NONEMPTY_STACK, // Not yet implemented (for post 0.12) SIGNATURE_CANONICAL_ENCODING } /** * <p>Checks if a transaction is considered "standard" by Bitcoin Core's IsStandardTx and AreInputsStandard * functions.</p> * * <p>Note that this method currently only implements a minimum of checks. More to be added later.</p> */ public static RuleViolation isStandard(Transaction tx) { // TODO: Finish this function off. 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; } /** * Checks the output to see if the script violates a standardness rule. Not complete. */ public static RuleViolation isOutputStandard(TransactionOutput output) { if (output.isDust()) return RuleViolation.DUST; for (ScriptChunk chunk : output.getScriptPubKey().chunks()) { if (chunk.isPushData() && !chunk.isShortestPossiblePushData()) return RuleViolation.SHORTEST_POSSIBLE_PUSHDATA; } return RuleViolation.NONE; } /** Checks if the given input passes some of the AreInputsStandard checks. Not complete. */ public static RuleViolation isInputStandard(TransactionInput input) { for (ScriptChunk chunk : input.getScriptSig().chunks()) { if (chunk.data != null && !chunk.isShortestPossiblePushData()) return RuleViolation.SHORTEST_POSSIBLE_PUSHDATA; if (chunk.isPushData()) { ECDSASignature signature; try { signature = ECKey.ECDSASignature.decodeFromDER(chunk.data); } catch (SignatureDecodeException x) { // Doesn't look like a signature. 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 Result analyzeIsStandard() { // The IsStandard rules don't apply on testnet, because they're just a safety mechanism and we don't want to // crush innovation with valueless test coins. if (wallet != null && wallet.network() != BitcoinNetwork.MAINNET) return Result.OK; RuleViolation ruleViolation = isStandard(tx); if (ruleViolation != RuleViolation.NONE) { nonStandard = tx; return Result.NON_STANDARD; } for (Transaction dep : dependencies) { ruleViolation = isStandard(dep); if (ruleViolation != RuleViolation.NONE) { nonStandard = dep; return Result.NON_STANDARD; } } return Result.OK; } /** Returns the transaction that was found to be non-standard, or null. */ @Nullable public Transaction getNonStandard() { return nonStandard; } /** Returns the transaction that was found to be non-final, or null. */ @Nullable public Transaction getNonFinal() { return nonFinal; } @Override public String toString() { if (!analyzed) return "Pending risk analysis for " + tx.getTxId(); else if (nonFinal != null) return "Risky due to non-finality of " + nonFinal.getTxId(); else if (nonStandard != null) return "Risky due to non-standard tx " + nonStandard.getTxId(); else return "Non-risky"; } public static class Analyzer implements RiskAnalysis.Analyzer { @Override public DefaultRiskAnalysis create(Wallet wallet, Transaction tx, List<Transaction> dependencies) { return new DefaultRiskAnalysis(wallet, tx, dependencies); } } public static Analyzer FACTORY = new Analyzer(); }
9,487
35.076046
119
java
bitcoinj
bitcoinj-master/core/src/main/java/org/bitcoinj/wallet/EncryptableKeyChain.java
/* * Copyright 2013 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.bitcoinj.wallet; import org.bitcoinj.crypto.AesKey; import org.bitcoinj.crypto.KeyCrypter; import org.bitcoinj.crypto.KeyCrypterException; import org.bitcoinj.crypto.KeyCrypterScrypt; import javax.annotation.Nullable; /** * An encryptable key chain is a key-chain that can be encrypted with a user-provided password or AES key. */ public interface EncryptableKeyChain extends KeyChain { /** * Takes the given password, which should be strong, derives a key from it and then invokes * {@link #toEncrypted(KeyCrypter, AesKey)} with * {@link KeyCrypterScrypt} as the crypter. * * @return The derived key, in case you wish to cache it for future use. */ EncryptableKeyChain toEncrypted(CharSequence password); /** * Returns a new keychain holding identical/cloned keys to this chain, but encrypted under the given key. * Old keys and keychains remain valid and so you should ensure you don't accidentally hold references to them. */ EncryptableKeyChain toEncrypted(KeyCrypter keyCrypter, AesKey aesKey); /** * Decrypts the key chain with the given password. See {@link #toDecrypted(AesKey)} * for details. */ EncryptableKeyChain toDecrypted(CharSequence password); /** * Decrypt the key chain with the given AES key and whatever {@link KeyCrypter} is already set. Note that if you * just want to spend money from an encrypted wallet, don't decrypt the whole thing first. Instead, set the * {@link SendRequest#aesKey} field before asking the wallet to build the send. * * @param aesKey AES key to use (normally created using KeyCrypter#deriveKey and cached as it is time consuming to * create from a password) * @throws KeyCrypterException Thrown if the wallet decryption fails. If so, the wallet state is unchanged. */ EncryptableKeyChain toDecrypted(AesKey aesKey); boolean checkPassword(CharSequence password); boolean checkAESKey(AesKey aesKey); /** Returns the key crypter used by this key chain, or null if it's not encrypted. */ @Nullable KeyCrypter getKeyCrypter(); }
2,754
38.927536
118
java
bitcoinj
bitcoinj-master/core/src/main/java/org/bitcoinj/wallet/KeyChainGroupStructure.java
/* * Copyright by the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.bitcoinj.wallet; import org.bitcoinj.base.BitcoinNetwork; import org.bitcoinj.base.Network; import org.bitcoinj.base.ScriptType; import org.bitcoinj.core.NetworkParameters; import org.bitcoinj.crypto.ChildNumber; import org.bitcoinj.crypto.HDPath; /** * Defines a structure for hierarchical deterministic wallets. * <p> * Use {@link KeyChainGroupStructure#BIP32} for BIP-32 wallets and {@link KeyChainGroupStructure#BIP43} for * BIP-43-family wallets. * <p> * <b>bitcoinj</b> BIP-32 wallets use {@link DeterministicKeyChain#ACCOUNT_ZERO_PATH} for {@link ScriptType#P2PKH} * and {@link DeterministicKeyChain#ACCOUNT_ONE_PATH} for {@link ScriptType#P2WPKH} * <p> * BIP-43-family wallets structured via {@link KeyChainGroupStructure} will always use account number zero. Currently, * only BIP-44 (P2PKH) and BIP-84 (P2WPKH) are supported. */ public interface KeyChainGroupStructure { /** * Map desired output script type to an account path. * Default to MainNet, BIP-32 Keychains use the same path for MainNet and TestNet * @param outputScriptType the script/address type * @return account path * @deprecated Use {@link #accountPathFor(ScriptType, Network)} or {@link #accountPathFor(ScriptType, NetworkParameters)} */ @Deprecated default HDPath accountPathFor(ScriptType outputScriptType) { return accountPathFor(outputScriptType, BitcoinNetwork.MAINNET); } /** * Map desired output script type and network to an account path * @param outputScriptType output script type (purpose) * @param network network/coin type * @return The HD Path: purpose / coinType / accountIndex */ HDPath accountPathFor(ScriptType outputScriptType, Network network); /** * Map desired output script type and network to an account path * @param outputScriptType output script type (purpose) * @param networkParameters network/coin type * @return The HD Path: purpose / coinType / accountIndex * @deprecated use {@link #accountPathFor(ScriptType, Network)} */ @Deprecated default HDPath accountPathFor(ScriptType outputScriptType, NetworkParameters networkParameters) { return accountPathFor(outputScriptType, networkParameters.network()); } /** * Original <b>bitcoinj</b> {@link KeyChainGroupStructure} implementation. Based on BIP32 "Wallet structure". * For this structure {@code network} is ignored */ KeyChainGroupStructure BIP32 = (outputScriptType, network) -> { // network is ignored if (outputScriptType == null || outputScriptType == ScriptType.P2PKH) return DeterministicKeyChain.ACCOUNT_ZERO_PATH; else if (outputScriptType == ScriptType.P2WPKH) return DeterministicKeyChain.ACCOUNT_ONE_PATH; else throw new IllegalArgumentException(outputScriptType.toString()); }; /** * {@link KeyChainGroupStructure} implementation for BIP-43 family structures. * Currently, BIP-44 and BIP-84 are supported. Account number is hard-coded to zero. */ KeyChainGroupStructure BIP43 = (outputScriptType, network) -> purpose(outputScriptType).extend(coinType(network), account(0)); /** * Default {@link KeyChainGroupStructure} implementation. Alias for {@link KeyChainGroupStructure#BIP32} * @deprecated Use {@link #BIP32} for BIP-32 */ @Deprecated KeyChainGroupStructure DEFAULT = BIP32; /** * Return the (root) path containing "purpose" for the specified scriptType * @param scriptType script/address type * @return An HDPath with a BIP44 "purpose" entry */ static HDPath purpose(ScriptType scriptType) { if (scriptType == null || scriptType == ScriptType.P2PKH) { return HDPath.BIP44_PARENT; } else if (scriptType == ScriptType.P2WPKH) { return HDPath.BIP84_PARENT; } else { throw new IllegalArgumentException(scriptType.toString()); } } /** * Return coin type path component for a network id * @param network network id string, eg. {@link BitcoinNetwork#ID_MAINNET} */ static ChildNumber coinType(Network network) { if (!(network instanceof BitcoinNetwork)) { throw new IllegalArgumentException("coinType: Unknown network"); } switch ((BitcoinNetwork) network) { case MAINNET: return ChildNumber.COINTYPE_BTC; case TESTNET: return ChildNumber.COINTYPE_TBTC; case REGTEST: return ChildNumber.COINTYPE_TBTC; default: throw new IllegalArgumentException("coinType: Unknown network"); } } /** * Return path component for an account * @param accountIndex account index * @return A hardened path component */ static ChildNumber account(int accountIndex) { return new ChildNumber(accountIndex, true); } }
5,649
37.965517
125
java
bitcoinj
bitcoinj-master/core/src/main/java/org/bitcoinj/wallet/KeyTimeCoinSelector.java
/* * Copyright 2013 Google Inc. * Copyright 2019 Andreas Schildbach * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.bitcoinj.wallet; import org.bitcoinj.base.Coin; import org.bitcoinj.base.ScriptType; import org.bitcoinj.crypto.ECKey; import org.bitcoinj.core.Transaction; import org.bitcoinj.core.TransactionConfidence; import org.bitcoinj.core.TransactionOutput; import org.bitcoinj.script.Script; import org.bitcoinj.script.ScriptException; import org.bitcoinj.script.ScriptPattern; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.time.Instant; import java.util.LinkedList; import java.util.List; import java.util.Objects; /** * A coin selector that takes all coins assigned to keys created before the given timestamp. * Used as part of the implementation of {@link Wallet#setKeyRotationTime(java.time.Instant)}. */ public class KeyTimeCoinSelector implements CoinSelector { private static final Logger log = LoggerFactory.getLogger(KeyTimeCoinSelector.class); /** A number of inputs chosen to avoid hitting {@link Transaction#MAX_STANDARD_TX_SIZE} */ public static final int MAX_SIMULTANEOUS_INPUTS = 600; private final Instant time; private final Wallet wallet; private final boolean ignorePending; public KeyTimeCoinSelector(Wallet wallet, Instant time, boolean ignorePending) { this.time = Objects.requireNonNull(time); this.wallet = wallet; this.ignorePending = ignorePending; } /** @deprecated use {@link #KeyTimeCoinSelector(Wallet, Instant, boolean)} */ @Deprecated public KeyTimeCoinSelector(Wallet wallet, long timeSecs, boolean ignorePending) { this(wallet, Instant.ofEpochSecond(timeSecs), ignorePending); } @Override public CoinSelection select(Coin target, List<TransactionOutput> candidates) { try { LinkedList<TransactionOutput> gathered = new LinkedList<>(); for (TransactionOutput output : candidates) { if (ignorePending && !isConfirmed(output)) continue; // Find the key that controls output, assuming it's a regular P2PK or P2PKH output. // We ignore any other kind of exotic output on the assumption we can't spend it ourselves. final Script scriptPubKey = output.getScriptPubKey(); ECKey controllingKey; if (ScriptPattern.isP2PK(scriptPubKey)) { controllingKey = wallet.findKeyFromPubKey(ScriptPattern.extractKeyFromP2PK(scriptPubKey)); } else if (ScriptPattern.isP2PKH(scriptPubKey)) { controllingKey = wallet.findKeyFromPubKeyHash(ScriptPattern.extractHashFromP2PKH(scriptPubKey), ScriptType.P2PKH); } else if (ScriptPattern.isP2WPKH(scriptPubKey)) { controllingKey = wallet.findKeyFromPubKeyHash(ScriptPattern.extractHashFromP2WH(scriptPubKey), ScriptType.P2WPKH); } else { log.info("Skipping tx output {} because it's not of simple form.", output); continue; } Objects.requireNonNull(controllingKey, "Coin selector given output as candidate for which we lack the key"); if (controllingKey.creationTime().orElse(Instant.EPOCH).compareTo(time) >= 0) continue; // It's older than the cutoff time so select. gathered.push(output); if (gathered.size() >= MAX_SIMULTANEOUS_INPUTS) { log.warn("Reached {} inputs, going further would yield a tx that is too large, stopping here.", gathered.size()); break; } } return new CoinSelection(gathered); } catch (ScriptException e) { throw new RuntimeException(e); // We should never have problems understanding scripts in our wallet. } } private boolean isConfirmed(TransactionOutput output) { return output.getParentTransaction().getConfidence().getConfidenceType().equals(TransactionConfidence.ConfidenceType.BUILDING); } }
4,661
44.262136
135
java
bitcoinj
bitcoinj-master/core/src/main/java/org/bitcoinj/wallet/BasicKeyChain.java
/* * Copyright 2013 Google Inc. * Copyright 2019 Andreas Schildbach * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.bitcoinj.wallet; import com.google.protobuf.ByteString; import org.bitcoinj.base.Network; import org.bitcoinj.crypto.AesKey; import org.bitcoinj.core.BloomFilter; import org.bitcoinj.crypto.ECKey; import org.bitcoinj.core.NetworkParameters; import org.bitcoinj.crypto.EncryptableItem; import org.bitcoinj.crypto.EncryptedData; import org.bitcoinj.crypto.KeyCrypter; import org.bitcoinj.crypto.KeyCrypterException; import org.bitcoinj.crypto.KeyCrypterScrypt; import org.bitcoinj.utils.ListenerRegistration; import org.bitcoinj.utils.Threading; import org.bitcoinj.wallet.listeners.KeyChainEventListener; import javax.annotation.Nullable; import java.time.Instant; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.LinkedHashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Optional; import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.Executor; import java.util.concurrent.locks.ReentrantLock; import java.util.stream.Collectors; import static org.bitcoinj.base.internal.Preconditions.checkArgument; import static org.bitcoinj.base.internal.Preconditions.checkState; /** * A {@link KeyChain} that implements the simplest model possible: it can have keys imported into it, and just acts as * a dumb bag of keys. It will, left to its own devices, always return the same key for usage by the wallet, although * it will automatically add one to itself if it's empty or if encryption is requested. */ public class BasicKeyChain implements EncryptableKeyChain { private final ReentrantLock lock = Threading.lock(BasicKeyChain.class); // Maps used to let us quickly look up a key given data we find in transactions or the block chain. private final LinkedHashMap<ByteString, ECKey> hashToKeys; private final LinkedHashMap<ByteString, ECKey> pubkeyToKeys; @Nullable private final KeyCrypter keyCrypter; private boolean isWatching; private final CopyOnWriteArrayList<ListenerRegistration<KeyChainEventListener>> listeners; public BasicKeyChain() { this(null); } public BasicKeyChain(@Nullable KeyCrypter crypter) { this.keyCrypter = crypter; hashToKeys = new LinkedHashMap<>(); pubkeyToKeys = new LinkedHashMap<>(); listeners = new CopyOnWriteArrayList<>(); } /** Returns the {@link KeyCrypter} in use or null if the key chain is not encrypted. */ @Override @Nullable public KeyCrypter getKeyCrypter() { lock.lock(); try { return keyCrypter; } finally { lock.unlock(); } } @Override public ECKey getKey(@Nullable KeyPurpose ignored) { lock.lock(); try { if (hashToKeys.isEmpty()) { checkState(keyCrypter == null); // We will refuse to encrypt an empty key chain. final ECKey key = new ECKey(); importKeyLocked(key); queueOnKeysAdded(Collections.singletonList(key)); } return hashToKeys.values().iterator().next(); } finally { lock.unlock(); } } @Override public List<ECKey> getKeys(@Nullable KeyPurpose purpose, int numberOfKeys) { checkArgument(numberOfKeys > 0); lock.lock(); try { if (hashToKeys.size() < numberOfKeys) { checkState(keyCrypter == null); List<ECKey> keys = new ArrayList<>(); for (int i = 0; i < numberOfKeys - hashToKeys.size(); i++) { keys.add(new ECKey()); } List<ECKey> immutableKeys = Collections.unmodifiableList(keys); importKeysLocked(immutableKeys); queueOnKeysAdded(immutableKeys); } List<ECKey> keysToReturn = new ArrayList<>(); int count = 0; while (hashToKeys.values().iterator().hasNext() && numberOfKeys != count) { keysToReturn.add(hashToKeys.values().iterator().next()); count++; } return keysToReturn; } finally { lock.unlock(); } } /** Returns a copy of the list of keys that this chain is managing. */ public List<ECKey> getKeys() { lock.lock(); try { return new ArrayList<>(hashToKeys.values()); } finally { lock.unlock(); } } public int importKeys(ECKey... keys) { return importKeys(Collections.unmodifiableList(Arrays.asList(keys))); } public int importKeys(List<? extends ECKey> keys) { lock.lock(); try { // Check that if we're encrypted, the keys are all encrypted, and if we're not, that none are. // We are NOT checking that the actual password matches here because we don't have access to the password at // this point: if you screw up and import keys with mismatched passwords, you lose! So make sure the // password is checked first. for (ECKey key : keys) { checkKeyEncryptionStateMatches(key); } List<ECKey> actuallyAdded = new ArrayList<>(keys.size()); for (final ECKey key : keys) { if (hasKey(key)) continue; actuallyAdded.add(key); importKeyLocked(key); } if (actuallyAdded.size() > 0) queueOnKeysAdded(actuallyAdded); return actuallyAdded.size(); } finally { lock.unlock(); } } private void checkKeyEncryptionStateMatches(ECKey key) { if (keyCrypter == null && key.isEncrypted()) throw new KeyCrypterException("Key is encrypted but chain is not"); else if (keyCrypter != null && !key.isEncrypted()) throw new KeyCrypterException("Key is not encrypted but chain is"); else if (keyCrypter != null && key.getKeyCrypter() != null && !key.getKeyCrypter().equals(keyCrypter)) throw new KeyCrypterException("Key encrypted under different parameters to chain"); } private void importKeyLocked(ECKey key) { if (hashToKeys.isEmpty()) { isWatching = key.isWatching(); } else { if (key.isWatching() && !isWatching) throw new IllegalArgumentException("Key is watching but chain is not"); if (!key.isWatching() && isWatching) throw new IllegalArgumentException("Key is not watching but chain is"); } ECKey previousKey = pubkeyToKeys.put(ByteString.copyFrom(key.getPubKey()), key); hashToKeys.put(ByteString.copyFrom(key.getPubKeyHash()), key); checkState(previousKey == null); } private void importKeysLocked(List<ECKey> keys) { for (ECKey key : keys) { importKeyLocked(key); } } /** * Imports a key to the key chain. If key is present in the key chain, ignore it. */ public void importKey(ECKey key) { lock.lock(); try { checkKeyEncryptionStateMatches(key); if (hasKey(key)) return; importKeyLocked(key); queueOnKeysAdded(Collections.singletonList(key)); } finally { lock.unlock(); } } public ECKey findKeyFromPubHash(byte[] pubKeyHash) { lock.lock(); try { return hashToKeys.get(ByteString.copyFrom(pubKeyHash)); } finally { lock.unlock(); } } public ECKey findKeyFromPubKey(byte[] pubKey) { lock.lock(); try { return pubkeyToKeys.get(ByteString.copyFrom(pubKey)); } finally { lock.unlock(); } } @Override public boolean hasKey(ECKey key) { return findKeyFromPubKey(key.getPubKey()) != null; } @Override public int numKeys() { return pubkeyToKeys.size(); } /** Whether this basic key chain is empty, full of regular (usable for signing) keys, or full of watching keys. */ public enum State { EMPTY, WATCHING, REGULAR } /** * Returns whether this chain consists of pubkey only (watching) keys, regular keys (usable for signing), or * has no keys in it yet at all (thus we cannot tell). */ public State isWatching() { lock.lock(); try { if (hashToKeys.isEmpty()) return State.EMPTY; return isWatching ? State.WATCHING : State.REGULAR; } finally { lock.unlock(); } } /** * Removes the given key from the keychain. Be very careful with this - losing a private key <b>destroys the * money associated with it</b>. * @return Whether the key was removed or not. */ public boolean removeKey(ECKey key) { lock.lock(); try { boolean a = hashToKeys.remove(ByteString.copyFrom(key.getPubKeyHash())) != null; boolean b = pubkeyToKeys.remove(ByteString.copyFrom(key.getPubKey())) != null; checkState(a == b); // Should be in both maps or neither. return a; } finally { lock.unlock(); } } /** * Returns the earliest creation time of keys in this chain. * @return earliest creation times of keys in this chain, * {@link Instant#EPOCH} if at least one time is unknown, * {@link Instant#MAX} if no keys in this chain */ @Override public Instant earliestKeyCreationTime() { lock.lock(); try { return hashToKeys.values().stream() .map(key -> key.creationTime().orElse(Instant.EPOCH)) .min(Instant::compareTo) .orElse(Instant.MAX); } finally { lock.unlock(); } } public List<ListenerRegistration<KeyChainEventListener>> getListeners() { return new ArrayList<>(listeners); } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // // Serialization support // /////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /** * Serialize to a map of {@code Protos.Key.Builder} * <p>Returns a {@link LinkedHashMap} which preserves iteration order. * @return A map (treat as unmodifiable) */ Map<ECKey, Protos.Key.Builder> serializeToEditableProtobufs() { // Both hashToKeys and the returned map are LinkedHashMap to preserve order return hashToKeys.values().stream() .collect(Collectors.toMap(ecKey -> ecKey, // key is ECKey ecKey -> toProtoKeyBuilder(ecKey), // value is Builder (oldVal, newVal) -> newVal, // if duplicate key, overwrite oldVal with newVal LinkedHashMap::new)); // Use LinkedHashMap to preserve element order } // Create a Protos.Key.Builder from an ECKey private static Protos.Key.Builder toProtoKeyBuilder(ECKey ecKey) { Protos.Key.Builder protoKey = serializeEncryptableItem(ecKey); protoKey.setPublicKey(ByteString.copyFrom(ecKey.getPubKey())); return protoKey; } /** * Serialize to a list of keys * @return list of keys (treat as unmodifiable list, will change in future release) */ @Override public List<Protos.Key> serializeToProtobuf() { // TODO: Return unmodifiable list return serializeToEditableProtobufs().values().stream() .map(Protos.Key.Builder::build) .collect(Collectors.toList()); } /*package*/ static Protos.Key.Builder serializeEncryptableItem(EncryptableItem item) { Protos.Key.Builder proto = Protos.Key.newBuilder(); item.creationTime().ifPresent(creationTime -> proto.setCreationTimestamp(creationTime.toEpochMilli())); if (item.isEncrypted() && item.getEncryptedData() != null) { // The encrypted data can be missing for an "encrypted" key in the case of a deterministic wallet for // which the leaf keys chain to an encrypted parent and rederive their private keys on the fly. In that // case the caller in DeterministicKeyChain will take care of setting the type. EncryptedData data = item.getEncryptedData(); proto.setEncryptedData(proto.getEncryptedData().toBuilder() .setEncryptedPrivateKey(ByteString.copyFrom(data.encryptedBytes)) .setInitialisationVector(ByteString.copyFrom(data.initialisationVector))); // We don't allow mixing of encryption types at the moment. checkState(item.getEncryptionType() == Protos.Wallet.EncryptionType.ENCRYPTED_SCRYPT_AES); proto.setType(Protos.Key.Type.ENCRYPTED_SCRYPT_AES); } else { final byte[] secret = item.getSecretBytes(); // The secret might be missing in the case of a watching wallet, or a key for which the private key // is expected to be rederived on the fly from its parent. if (secret != null) proto.setSecretBytes(ByteString.copyFrom(secret)); proto.setType(Protos.Key.Type.ORIGINAL); } return proto; } /** * Returns a new BasicKeyChain that contains all basic, ORIGINAL type keys extracted from the list. Unrecognised * key types are ignored. */ public static BasicKeyChain fromProtobufUnencrypted(List<Protos.Key> keys) throws UnreadableWalletException { BasicKeyChain chain = new BasicKeyChain(); chain.deserializeFromProtobuf(keys); return chain; } /** * Returns a new BasicKeyChain that contains all basic, ORIGINAL type keys and also any encrypted keys extracted * from the list. Unrecognised key types are ignored. * @throws org.bitcoinj.wallet.UnreadableWalletException.BadPassword if the password doesn't seem to match * @throws org.bitcoinj.wallet.UnreadableWalletException if the data structures are corrupted/inconsistent */ public static BasicKeyChain fromProtobufEncrypted(List<Protos.Key> keys, KeyCrypter crypter) throws UnreadableWalletException { BasicKeyChain chain = new BasicKeyChain(Objects.requireNonNull(crypter)); chain.deserializeFromProtobuf(keys); return chain; } private void deserializeFromProtobuf(List<Protos.Key> keys) throws UnreadableWalletException { lock.lock(); try { checkState(hashToKeys.isEmpty(), () -> "tried to deserialize into a non-empty chain"); for (Protos.Key key : keys) { if (key.getType() != Protos.Key.Type.ORIGINAL && key.getType() != Protos.Key.Type.ENCRYPTED_SCRYPT_AES) continue; boolean encrypted = key.getType() == Protos.Key.Type.ENCRYPTED_SCRYPT_AES; byte[] priv = key.hasSecretBytes() ? key.getSecretBytes().toByteArray() : null; if (!key.hasPublicKey()) throw new UnreadableWalletException("Public key missing"); byte[] pub = key.getPublicKey().toByteArray(); ECKey ecKey; if (encrypted) { checkState(keyCrypter != null, () -> "this wallet is encrypted but encrypt() was not called prior to deserialization"); if (!key.hasEncryptedData()) throw new UnreadableWalletException("Encrypted private key data missing"); Protos.EncryptedData proto = key.getEncryptedData(); EncryptedData e = new EncryptedData(proto.getInitialisationVector().toByteArray(), proto.getEncryptedPrivateKey().toByteArray()); ecKey = ECKey.fromEncrypted(e, keyCrypter, pub); } else { if (priv != null) ecKey = ECKey.fromPrivateAndPrecalculatedPublic(priv, pub); else ecKey = ECKey.fromPublicOnly(pub); } ecKey.setCreationTime(Instant.ofEpochMilli(key.getCreationTimestamp())); importKeyLocked(ecKey); } } finally { lock.unlock(); } } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // // Event listener support // /////////////////////////////////////////////////////////////////////////////////////////////////////////////////// @Override public void addEventListener(KeyChainEventListener listener) { addEventListener(listener, Threading.USER_THREAD); } @Override public void addEventListener(KeyChainEventListener listener, Executor executor) { addEventListener(new ListenerRegistration<>(listener, executor)); } /* package private */ void addEventListener(ListenerRegistration<KeyChainEventListener> listener) { listeners.add(listener); } @Override public boolean removeEventListener(KeyChainEventListener listener) { return ListenerRegistration.removeFromList(listener, listeners); } private void queueOnKeysAdded(final List<ECKey> keys) { checkState(lock.isHeldByCurrentThread()); for (final ListenerRegistration<KeyChainEventListener> registration : listeners) { registration.executor.execute(() -> registration.listener.onKeysAdded(keys)); } } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // // Encryption support // /////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /** * Convenience wrapper around {@link #toEncrypted(KeyCrypter, * AesKey)} which uses the default Scrypt key derivation algorithm and * parameters, derives a key from the given password and returns the created key. */ @Override public BasicKeyChain toEncrypted(CharSequence password) { Objects.requireNonNull(password); checkArgument(password.length() > 0); KeyCrypter scrypt = new KeyCrypterScrypt(); AesKey derivedKey = scrypt.deriveKey(password); return toEncrypted(scrypt, derivedKey); } /** * Encrypt the wallet using the KeyCrypter and the AES key. A good default KeyCrypter to use is * {@link KeyCrypterScrypt}. * * @param keyCrypter The KeyCrypter that specifies how to encrypt/ decrypt a key * @param aesKey AES key to use (normally created using KeyCrypter#deriveKey and cached as it is time consuming * to create from a password) * @throws KeyCrypterException Thrown if the wallet encryption fails. If so, the wallet state is unchanged. */ @Override public BasicKeyChain toEncrypted(KeyCrypter keyCrypter, AesKey aesKey) { lock.lock(); try { Objects.requireNonNull(keyCrypter); checkState(this.keyCrypter == null, () -> "key chain is already encrypted"); BasicKeyChain encrypted = new BasicKeyChain(keyCrypter); for (ECKey key : hashToKeys.values()) { ECKey encryptedKey = key.encrypt(keyCrypter, aesKey); // Check that the encrypted key can be successfully decrypted. // This is done as it is a critical failure if the private key cannot be decrypted successfully // (all bitcoin controlled by that private key is lost forever). // For a correctly constructed keyCrypter the encryption should always be reversible so it is just // being as cautious as possible. if (!ECKey.encryptionIsReversible(key, encryptedKey, keyCrypter, aesKey)) throw new KeyCrypterException("The key " + key.toString() + " cannot be successfully decrypted after encryption so aborting wallet encryption."); encrypted.importKeyLocked(encryptedKey); } for (ListenerRegistration<KeyChainEventListener> listener : listeners) { encrypted.addEventListener(listener); } return encrypted; } finally { lock.unlock(); } } @Override public BasicKeyChain toDecrypted(CharSequence password) { Objects.requireNonNull(keyCrypter, "Wallet is already decrypted"); AesKey aesKey = keyCrypter.deriveKey(password); return toDecrypted(aesKey); } @Override public BasicKeyChain toDecrypted(AesKey aesKey) { lock.lock(); try { checkState(keyCrypter != null, () -> "wallet is already decrypted"); // Do an up-front check. if (numKeys() > 0 && !checkAESKey(aesKey)) throw new KeyCrypterException("Password/key was incorrect."); BasicKeyChain decrypted = new BasicKeyChain(); for (ECKey key : hashToKeys.values()) { decrypted.importKeyLocked(key.decrypt(aesKey)); } for (ListenerRegistration<KeyChainEventListener> listener : listeners) { decrypted.addEventListener(listener); } return decrypted; } finally { lock.unlock(); } } /** * Returns whether the given password is correct for this key chain. * @throws IllegalStateException if the chain is not encrypted at all. */ @Override public boolean checkPassword(CharSequence password) { Objects.requireNonNull(password); checkState(keyCrypter != null, () -> "key chain not encrypted"); return checkAESKey(keyCrypter.deriveKey(password)); } /** * Check whether the AES key can decrypt the first encrypted key in the wallet. * * @return true if AES key supplied can decrypt the first encrypted private key in the wallet, false otherwise. */ @Override public boolean checkAESKey(AesKey aesKey) { lock.lock(); try { // If no keys then cannot decrypt. if (hashToKeys.isEmpty()) return false; checkState(keyCrypter != null, () -> "key chain is not encrypted"); // Find the first encrypted key in the wallet. ECKey first = null; for (ECKey key : hashToKeys.values()) { if (key.isEncrypted()) { first = key; break; } } checkState(first != null, () -> "no encrypted keys in the wallet"); try { ECKey rebornKey = first.decrypt(aesKey); return Arrays.equals(first.getPubKey(), rebornKey.getPubKey()); } catch (KeyCrypterException e) { // The AES key supplied is incorrect. return false; } } finally { lock.unlock(); } } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // // Bloom filtering support // /////////////////////////////////////////////////////////////////////////////////////////////////////////////////// @Override public BloomFilter getFilter(int size, double falsePositiveRate, int tweak) { lock.lock(); try { BloomFilter filter = new BloomFilter(size, falsePositiveRate, tweak); for (ECKey key : hashToKeys.values()) filter.insert(key); return filter; } finally { lock.unlock(); } } @Override public int numBloomFilterEntries() { return numKeys() * 2; } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // // Key rotation support // /////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /** Returns the first ECKey created after the given time, or empty if there is none. */ public Optional<ECKey> findOldestKeyAfter(Instant time) { lock.lock(); try { ECKey oldest = null; for (ECKey key : hashToKeys.values()) { Instant keyTime = key.creationTime().orElse(Instant.EPOCH); if (keyTime.isAfter(time)) { if (oldest == null || oldest.creationTime().orElse(Instant.EPOCH).isAfter(keyTime)) oldest = key; } } return Optional.ofNullable(oldest); } finally { lock.unlock(); } } /** @deprecated use {@link #findOldestKeyAfter(Instant)} */ @Nullable @Deprecated public ECKey findOldestKeyAfter(long timeSecs) { return findOldestKeyAfter(Instant.ofEpochSecond(timeSecs)).orElse(null); } /** Returns a list of all ECKeys created after the given time. */ public List<ECKey> findKeysBefore(Instant time) { lock.lock(); try { List<ECKey> results = new LinkedList<>(); for (ECKey key : hashToKeys.values()) { Instant keyTime = key.creationTime().orElse(Instant.EPOCH); if (keyTime.isBefore(time)) { results.add(key); } } return results; } finally { lock.unlock(); } } /** @deprecated use {@link #findKeysBefore(Instant)} */ @Deprecated public List<ECKey> findKeysBefore(long timeSecs) { return findKeysBefore(Instant.ofEpochSecond(timeSecs)); } public String toString(boolean includePrivateKeys, @Nullable AesKey aesKey, Network network) { final StringBuilder builder = new StringBuilder(); List<ECKey> keys = getKeys(); Collections.sort(keys, ECKey.AGE_COMPARATOR); for (ECKey key : keys) key.formatKeyWithAddress(includePrivateKeys, aesKey, builder, network, null, "imported"); return builder.toString(); } /** @deprecated use {@link #toString(boolean, AesKey, Network)} */ @Deprecated public String toString(boolean includePrivateKeys, @Nullable AesKey aesKey, NetworkParameters params) { return toString(includePrivateKeys, aesKey, params.network()); } }
27,508
38.467719
165
java
bitcoinj
bitcoinj-master/core/src/main/java/org/bitcoinj/wallet/AllRandomKeysRotating.java
/* * Copyright by the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.bitcoinj.wallet; /** * Indicates that an attempt was made to upgrade a random wallet to deterministic, but there were no non-rotating * random keys to use as source material for the seed. Add a non-compromised key first! */ public class AllRandomKeysRotating extends RuntimeException {}
918
37.291667
113
java
bitcoinj
bitcoinj-master/core/src/main/java/org/bitcoinj/wallet/KeyChainFactory.java
/* * Copyright 2014 devrandom * Copyright 2019 Andreas Schildbach * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.bitcoinj.wallet; import org.bitcoinj.base.ScriptType; import org.bitcoinj.crypto.ChildNumber; import org.bitcoinj.crypto.DeterministicKey; import org.bitcoinj.crypto.KeyCrypter; import java.util.List; import static org.bitcoinj.base.internal.Preconditions.check; /** * Factory interface for creation keychains while de-serializing a wallet. */ public interface KeyChainFactory { /** * Make a keychain (but not a watching one) with the specified account path * * @param seed the seed * @param crypter the encrypted/decrypter * @param outputScriptType type of addresses (aka output scripts) to generate for receiving * @param accountPath account path to generate receiving addresses on */ DeterministicKeyChain makeKeyChain(DeterministicSeed seed, KeyCrypter crypter, ScriptType outputScriptType, List<ChildNumber> accountPath); /** @deprecated use {@link #makeKeyChain(DeterministicSeed, KeyCrypter, ScriptType, List)} */ @Deprecated default DeterministicKeyChain makeKeyChain(DeterministicSeed seed, KeyCrypter crypter, boolean isMarried, ScriptType outputScriptType, List<ChildNumber> accountPath) { check(!isMarried, () -> { throw new UnsupportedOperationException("married wallets not supported"); }); return makeKeyChain(seed, crypter, outputScriptType, accountPath); } /** * Make a watching keychain. * * <p>isMarried and isFollowingKey must not be true at the same time. * * @param accountKey the account extended public key * @param outputScriptType type of addresses (aka output scripts) to generate for watching */ DeterministicKeyChain makeWatchingKeyChain(DeterministicKey accountKey, ScriptType outputScriptType) throws UnreadableWalletException; /** @deprecated use {@link #makeWatchingKeyChain(DeterministicKey, ScriptType)} */ @Deprecated default DeterministicKeyChain makeWatchingKeyChain(DeterministicKey accountKey, boolean isFollowingKey, boolean isMarried, ScriptType outputScriptType) throws UnreadableWalletException { check(!isMarried && !isFollowingKey, () -> { throw new UnsupportedOperationException("married wallets not supported"); }); return makeWatchingKeyChain(accountKey, outputScriptType); } /** * Make a spending keychain. * * <p>isMarried and isFollowingKey must not be true at the same time. * * @param accountKey the account extended public key * @param outputScriptType type of addresses (aka output scripts) to generate for spending */ DeterministicKeyChain makeSpendingKeyChain(DeterministicKey accountKey, ScriptType outputScriptType) throws UnreadableWalletException; /** @deprecated use {@link #makeSpendingKeyChain(DeterministicKey, ScriptType)} */ @Deprecated default DeterministicKeyChain makeSpendingKeyChain(DeterministicKey accountKey, boolean isMarried, ScriptType outputScriptType) throws UnreadableWalletException { check(!isMarried, () -> { throw new UnsupportedOperationException("married wallets not supported"); }); return makeSpendingKeyChain(accountKey, outputScriptType); } }
4,098
44.544444
130
java
bitcoinj
bitcoinj-master/core/src/main/java/org/bitcoinj/wallet/SendRequest.java
/* * Copyright 2013 Google Inc. * Copyright 2014 Andreas Schildbach * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.bitcoinj.wallet; import com.google.common.base.MoreObjects; import org.bitcoin.protocols.payments.Protos.PaymentDetails; import org.bitcoinj.base.Address; import org.bitcoinj.base.Coin; import org.bitcoinj.crypto.AesKey; import org.bitcoinj.core.Context; import org.bitcoinj.crypto.ECKey; import org.bitcoinj.core.NetworkParameters; import org.bitcoinj.core.Transaction; import org.bitcoinj.core.TransactionOutput; import org.bitcoinj.utils.ExchangeRate; import org.bitcoinj.wallet.KeyChain.KeyPurpose; import org.bitcoinj.wallet.Wallet.MissingSigsMode; import java.util.Objects; /** * A SendRequest gives the wallet information about precisely how to send money to a recipient or set of recipients. * Static methods are provided to help you create SendRequests and there are a few helper methods on the wallet that * just simplify the most common use cases. You may wish to customize a SendRequest if you want to attach a fee or * modify the change address. */ public class SendRequest { /** * <p>A transaction, probably incomplete, that describes the outline of what you want to do. This typically will * mean it has some outputs to the intended destinations, but no inputs or change address (and therefore no * fees) - the wallet will calculate all that for you and update tx later.</p> * * <p>Be careful when adding outputs that you check the min output value * ({@link TransactionOutput#getMinNonDustValue(Coin)}) to avoid the whole transaction being rejected * because one output is dust.</p> * * <p>If there are already inputs to the transaction, make sure their out point has a connected output, * otherwise their value will be added to fee. Also ensure they are either signed or are spendable by a wallet * key, otherwise the behavior of {@link Wallet#completeTx(SendRequest)} is undefined (likely * RuntimeException).</p> */ public final Transaction tx; /** * When emptyWallet is set, all coins selected by the coin selector are sent to the first output in tx * (its value is ignored and set to {@link Wallet#getBalance()} - the fees required * for the transaction). Any additional outputs are removed. */ public boolean emptyWallet = false; /** * "Change" means the difference between the value gathered by a transactions inputs (the size of which you * don't really control as it depends on who sent you money), and the value being sent somewhere else. The * change address should be selected from this wallet, normally. <b>If null this will be chosen for you.</b> */ public Address changeAddress = null; /** * <p>A transaction can have a fee attached, which is defined as the difference between the input values * and output values. Any value taken in that is not provided to an output can be claimed by a miner. This * is how mining is incentivized in later years of the Bitcoin system when inflation drops. It also provides * a way for people to prioritize their transactions over others and is used as a way to make denial of service * attacks expensive.</p> * * <p>This is a dynamic fee (in satoshis) which will be added to the transaction for each virtual kilobyte in size * including the first. This is useful as as miners usually sort pending transactions by their fee per unit size * when choosing which transactions to add to a block. Note that, to keep this equivalent to Bitcoin Core * definition, a virtual kilobyte is defined as 1000 virtual bytes, not 1024.</p> */ public Coin feePerKb = Context.get().getFeePerKb(); public void setFeePerVkb(Coin feePerVkb) { this.feePerKb = feePerVkb; } /** * <p>Requires that there be enough fee for a default Bitcoin Core to at least relay the transaction. * (ie ensure the transaction will not be outright rejected by the network). Defaults to true, you should * only set this to false if you know what you're doing.</p> * * <p>Note that this does not enforce certain fee rules that only apply to transactions which are larger than * 26,000 bytes. If you get a transaction which is that large, you should set a feePerKb of at least * {@link Transaction#REFERENCE_DEFAULT_MIN_TX_FEE}.</p> */ public boolean ensureMinRequiredFee = Context.get().isEnsureMinRequiredFee(); /** * If true (the default), the inputs will be signed. */ public boolean signInputs = true; /** * The AES key to use to decrypt the private keys before signing. * If null then no decryption will be performed and if decryption is required an exception will be thrown. * You can get this from a password by doing wallet.getKeyCrypter().deriveKey(password). */ public AesKey aesKey = null; /** * If not null, the {@link CoinSelector} to use instead of the wallets default. Coin selectors are * responsible for choosing which transaction outputs (coins) in a wallet to use given the desired send value * amount. */ public CoinSelector coinSelector = null; /** * Shortcut for {@code req.coinSelector = AllowUnconfirmedCoinSelector.get();}. */ public void allowUnconfirmed() { coinSelector = AllowUnconfirmedCoinSelector.get(); } /** * If true (the default), the outputs will be shuffled during completion to randomize the location of the change * output, if any. This is normally what you want for privacy reasons but in unit tests it can be annoying * so it can be disabled here. */ public boolean shuffleOutputs = true; /** * Specifies what to do with missing signatures left after completing this request. Default strategy is to * throw an exception on missing signature ({@link MissingSigsMode#THROW}). * @see MissingSigsMode */ public MissingSigsMode missingSigsMode = MissingSigsMode.THROW; /** * If not null, this exchange rate is recorded with the transaction during completion. */ public ExchangeRate exchangeRate = null; /** * If not null, this memo is recorded with the transaction during completion. It can be used to record the memo * of the payment request that initiated the transaction. */ public String memo = null; /** * If false (default value), tx fee is paid by the sender If true, tx fee is paid by the recipient/s. If there is * more than one recipient, the tx fee is split equally between them regardless of output value and size. */ public boolean recipientsPayFees = false; // Tracks if this has been passed to wallet.completeTx already: just a safety check. boolean completed; private SendRequest(Transaction transaction) { tx = transaction; } /** * <p>Creates a new SendRequest to the given address for the given value.</p> * * <p>Be careful to check the output's value is reasonable using * {@link TransactionOutput#getMinNonDustValue(Coin)} afterwards or you risk having the transaction * rejected by the network.</p> */ public static SendRequest to(Address destination, Coin value) { Transaction tx = new Transaction(); tx.addOutput(value, destination); return new SendRequest(tx); } /** * <p>Creates a new SendRequest to the given pubkey for the given value.</p> * * <p>Be careful to check the output's value is reasonable using * {@link TransactionOutput#getMinNonDustValue(Coin)} afterwards or you risk having the transaction * rejected by the network. Note that using {@link SendRequest#to(Address, Coin)} will result * in a smaller output, and thus the ability to use a smaller output value without rejection.</p> */ public static SendRequest to(ECKey destination, Coin value) { Transaction tx = new Transaction(); tx.addOutput(value, destination); return new SendRequest(tx); } /** @deprecated use {@link #to(ECKey, Coin)} */ @Deprecated public static SendRequest to(NetworkParameters params, ECKey destination, Coin value) { return to(destination, value); } /** Simply wraps a pre-built incomplete transaction provided by you. */ public static SendRequest forTx(Transaction tx) { return new SendRequest(tx); } public static SendRequest emptyWallet(Address destination) { Transaction tx = new Transaction(); tx.addOutput(Coin.ZERO, destination); SendRequest req = new SendRequest(tx); req.emptyWallet = true; return req; } /** * Construct a SendRequest for a CPFP (child-pays-for-parent) transaction. The resulting transaction is already * completed, so you should directly proceed to signing and broadcasting/committing the transaction. CPFP is * currently only supported by a few miners, so use with care. */ public static SendRequest childPaysForParent(Wallet wallet, Transaction parentTransaction, Coin feeRaise) { TransactionOutput outputToSpend = null; for (final TransactionOutput output : parentTransaction.getOutputs()) { if (output.isMine(wallet) && output.isAvailableForSpending() && output.getValue().isGreaterThan(feeRaise)) { outputToSpend = output; break; } } // TODO spend another confirmed output of own wallet if needed Objects.requireNonNull(outputToSpend, "Can't find adequately sized output that spends to us"); final Transaction tx = new Transaction(); tx.addInput(outputToSpend); tx.addOutput(outputToSpend.getValue().subtract(feeRaise), wallet.freshAddress(KeyPurpose.CHANGE)); tx.setPurpose(Transaction.Purpose.RAISE_FEE); final SendRequest req = forTx(tx); req.completed = true; return req; } /** Copy data from payment request. */ public SendRequest fromPaymentDetails(PaymentDetails paymentDetails) { if (paymentDetails.hasMemo()) this.memo = paymentDetails.getMemo(); return this; } @Override public String toString() { // print only the user-settable fields MoreObjects.ToStringHelper helper = MoreObjects.toStringHelper(this).omitNullValues(); helper.add("emptyWallet", emptyWallet); helper.add("changeAddress", changeAddress); helper.add("feePerKb", feePerKb); helper.add("ensureMinRequiredFee", ensureMinRequiredFee); helper.add("signInputs", signInputs); helper.add("aesKey", aesKey != null ? "set" : null); // careful to not leak the key helper.add("coinSelector", coinSelector); helper.add("shuffleOutputs", shuffleOutputs); helper.add("recipientsPayFees", recipientsPayFees); return helper.toString(); } }
11,573
43.344828
118
java
bitcoinj
bitcoinj-master/core/src/main/java/org/bitcoinj/wallet/Wallet.java
/* * Copyright 2013 Google Inc. * Copyright 2014 Andreas Schildbach * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.bitcoinj.wallet; import com.google.common.annotations.VisibleForTesting; import com.google.common.collect.ArrayListMultimap; import com.google.common.collect.Iterables; import com.google.common.math.IntMath; import com.google.protobuf.ByteString; import net.jcip.annotations.GuardedBy; import org.bitcoinj.base.BitcoinNetwork; import org.bitcoinj.base.Network; import org.bitcoinj.base.exceptions.AddressFormatException; import org.bitcoinj.base.internal.ByteUtils; import org.bitcoinj.base.internal.PlatformUtils; import org.bitcoinj.base.internal.TimeUtils; import org.bitcoinj.base.internal.StreamUtils; import org.bitcoinj.crypto.AesKey; import org.bitcoinj.core.AbstractBlockChain; import org.bitcoinj.base.Address; import org.bitcoinj.base.Base58; import org.bitcoinj.base.AddressParser; import org.bitcoinj.core.BlockChain; import org.bitcoinj.core.BloomFilter; import org.bitcoinj.base.Coin; import org.bitcoinj.core.Context; import org.bitcoinj.base.DefaultAddressParser; import org.bitcoinj.crypto.ECKey; import org.bitcoinj.core.FilteredBlock; import org.bitcoinj.core.InsufficientMoneyException; import org.bitcoinj.base.LegacyAddress; import org.bitcoinj.core.Message; import org.bitcoinj.core.NetworkParameters; import org.bitcoinj.core.Peer; import org.bitcoinj.core.PeerFilterProvider; import org.bitcoinj.core.PeerGroup; import org.bitcoinj.base.Sha256Hash; import org.bitcoinj.core.StoredBlock; import org.bitcoinj.core.Transaction; import org.bitcoinj.core.TransactionBag; import org.bitcoinj.core.TransactionBroadcast; import org.bitcoinj.core.TransactionBroadcaster; import org.bitcoinj.core.TransactionConfidence; import org.bitcoinj.core.TransactionConfidence.ConfidenceType; import org.bitcoinj.core.TransactionConfidence.Listener; import org.bitcoinj.core.TransactionInput; import org.bitcoinj.core.TransactionOutPoint; import org.bitcoinj.core.TransactionOutput; import org.bitcoinj.core.UTXO; import org.bitcoinj.core.UTXOProvider; import org.bitcoinj.core.UTXOProviderException; import org.bitcoinj.core.VerificationException; import org.bitcoinj.core.listeners.NewBestBlockListener; import org.bitcoinj.core.listeners.ReorganizeListener; import org.bitcoinj.core.listeners.TransactionConfidenceEventListener; import org.bitcoinj.core.listeners.TransactionReceivedInBlockListener; import org.bitcoinj.crypto.ChildNumber; import org.bitcoinj.crypto.DeterministicHierarchy; import org.bitcoinj.crypto.DeterministicKey; import org.bitcoinj.crypto.HDKeyDerivation; import org.bitcoinj.crypto.KeyCrypter; import org.bitcoinj.crypto.KeyCrypterException; import org.bitcoinj.crypto.KeyCrypterScrypt; import org.bitcoinj.script.Script; import org.bitcoinj.base.ScriptType; import org.bitcoinj.script.ScriptBuilder; import org.bitcoinj.script.ScriptChunk; import org.bitcoinj.script.ScriptException; import org.bitcoinj.script.ScriptPattern; import org.bitcoinj.signers.LocalTransactionSigner; import org.bitcoinj.signers.MissingSigResolutionSigner; import org.bitcoinj.signers.TransactionSigner; import org.bitcoinj.utils.BaseTaggableObject; import org.bitcoinj.base.internal.FutureUtils; import org.bitcoinj.utils.ListenableCompletableFuture; import org.bitcoinj.utils.ListenerRegistration; import org.bitcoinj.utils.Threading; import org.bitcoinj.wallet.Protos.Wallet.EncryptionType; import org.bitcoinj.wallet.WalletTransaction.Pool; import org.bitcoinj.wallet.listeners.CurrentKeyChangeEventListener; import org.bitcoinj.wallet.listeners.KeyChainEventListener; import org.bitcoinj.wallet.listeners.ScriptsChangeEventListener; import org.bitcoinj.wallet.listeners.WalletChangeEventListener; import org.bitcoinj.wallet.listeners.WalletCoinsReceivedEventListener; import org.bitcoinj.wallet.listeners.WalletCoinsSentEventListener; import org.bitcoinj.wallet.listeners.WalletReorganizeEventListener; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.annotation.Nullable; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.math.BigInteger; import java.math.RoundingMode; import java.nio.ByteBuffer; import java.time.Duration; import java.time.Instant; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.Date; import java.util.EnumSet; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Optional; import java.util.Random; import java.util.Set; import java.util.TreeSet; import java.util.concurrent.CompletableFuture; import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.Executor; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.locks.ReentrantLock; import static org.bitcoinj.base.internal.Preconditions.checkArgument; import static org.bitcoinj.base.internal.Preconditions.checkState; // To do list: // // - Take all wallet-relevant data out of Transaction and put it into WalletTransaction. Make Transaction immutable. // - Only store relevant transaction outputs, don't bother storing the rest of the data. Big RAM saving. // - Split block chain and tx output tracking into a superclass that doesn't have any key or spending related code. // - Simplify how transactions are tracked and stored: in particular, have the wallet maintain positioning information // for transactions independent of the transactions themselves, so the timeline can be walked without having to // process and sort every single transaction. // - Split data persistence out into a backend class and make the wallet transactional, so we can store a wallet // in a database not just in RAM. // - Make clearing of transactions able to only rewind the wallet a certain distance instead of all blocks. // - Make it scale: // - eliminate all the algorithms with quadratic complexity (or worse) // - don't require everything to be held in RAM at once // - consider allowing eviction of no longer re-orgable transactions or keys that were used up // // Finally, find more ways to break the class up and decompose it. Currently every time we move code out, other code // fills up the lines saved! /** * <p>A Wallet stores keys and a record of transactions that send and receive value from those keys. Using these, * it is able to create new transactions that spend the recorded transactions, and this is the fundamental operation * of the Bitcoin protocol.</p> * * <p>To learn more about this class, read <b><a href="https://bitcoinj.github.io/working-with-the-wallet"> * working with the wallet.</a></b></p> * * <p>To fill up a Wallet with transactions, you need to use it in combination with a {@link BlockChain} and various * other objects, see the <a href="https://bitcoinj.github.io/getting-started">Getting started</a> tutorial * on the website to learn more about how to set everything up.</p> * * <p>Wallets can be serialized using protocol buffers. You need to save the wallet whenever it changes, there is an * auto-save feature that simplifies this for you although you're still responsible for manually triggering a save when * your app is about to quit because the auto-save feature waits a moment before actually committing to disk to avoid IO * thrashing when the wallet is changing very fast (eg due to a block chain sync). See * {@link Wallet#autosaveToFile(File, long, TimeUnit, WalletFiles.Listener)} * for more information about this.</p> */ public class Wallet extends BaseTaggableObject implements NewBestBlockListener, TransactionReceivedInBlockListener, PeerFilterProvider, KeyBag, TransactionBag, ReorganizeListener, AddressParser.Strict { private static final Logger log = LoggerFactory.getLogger(Wallet.class); private static final AddressParser addressParser = new DefaultAddressParser(); // Ordering: lock > keyChainGroupLock. KeyChainGroup is protected separately to allow fast querying of current receive address // even if the wallet itself is busy e.g. saving or processing a big reorg. Useful for reducing UI latency. protected final ReentrantLock lock = Threading.lock(Wallet.class); protected final ReentrantLock keyChainGroupLock = Threading.lock("Wallet-KeyChainGroup lock"); private static final int MINIMUM_BLOOM_DATA_LENGTH = 8; // The various pools below give quick access to wallet-relevant transactions by the state they're in: // // Pending: Transactions that didn't make it into the best chain yet. Pending transactions can be killed if a // double spend against them appears in the best chain, in which case they move to the dead pool. // If a double spend appears in the pending state as well, we update the confidence type // of all txns in conflict to IN_CONFLICT and wait for the miners to resolve the race. // Unspent: Transactions that appeared in the best chain and have outputs we can spend. Note that we store the // entire transaction in memory even though for spending purposes we only really need the outputs, the // reason being that this simplifies handling of re-orgs. It would be worth fixing this in future. // Spent: Transactions that appeared in the best chain but don't have any spendable outputs. They're stored here // for history browsing/auditing reasons only and in future will probably be flushed out to some other // kind of cold storage or just removed. // Dead: Transactions that we believe will never confirm get moved here, out of pending. Note that Bitcoin // Core has no notion of dead-ness: the assumption is that double spends won't happen so there's no // need to notify the user about them. We take a more pessimistic approach and try to track the fact that // transactions have been double spent so applications can do something intelligent (cancel orders, show // to the user in the UI, etc). A transaction can leave dead and move into spent/unspent if there is a // re-org to a chain that doesn't include the double spend. private final Map<Sha256Hash, Transaction> pending; private final Map<Sha256Hash, Transaction> unspent; private final Map<Sha256Hash, Transaction> spent; private final Map<Sha256Hash, Transaction> dead; // All transactions together. protected final Map<Sha256Hash, Transaction> transactions; // All the TransactionOutput objects that we could spend (ignoring whether we have the private key or not). // Used to speed up various calculations. protected final HashSet<TransactionOutput> myUnspents = new HashSet<>(); // Transactions that were dropped by the risk analysis system. These are not in any pools and not serialized // to disk. We have to keep them around because if we ignore a tx because we think it will never confirm, but // then it actually does confirm and does so within the same network session, remote peers will not resend us // the tx data along with the Bloom filtered block, as they know we already received it once before // (so it would be wasteful to repeat). Thus we keep them around here for a while. If we drop our network // connections then the remote peers will forget that we were sent the tx data previously and send it again // when relaying a filtered merkleblock. private final LinkedHashMap<Sha256Hash, Transaction> riskDropped = new LinkedHashMap<Sha256Hash, Transaction>() { @Override protected boolean removeEldestEntry(Map.Entry<Sha256Hash, Transaction> eldest) { return size() > 1000; } }; // The key chain group is not thread safe, and generally the whole hierarchy of objects should not be mutated // outside the wallet lock. So don't expose this object directly via any accessors! @GuardedBy("keyChainGroupLock") private final KeyChainGroup keyChainGroup; // A list of scripts watched by this wallet. @GuardedBy("keyChainGroupLock") private final Set<Script> watchedScripts; protected final Network network; protected final NetworkParameters params; @Nullable private Sha256Hash lastBlockSeenHash; private int lastBlockSeenHeight; @Nullable private Instant lastBlockSeenTime; private final List<ListenerRegistration<WalletChangeEventListener>> changeListeners = new CopyOnWriteArrayList<>(); private final List<ListenerRegistration<WalletCoinsReceivedEventListener>> coinsReceivedListeners = new CopyOnWriteArrayList<>(); private final List<ListenerRegistration<WalletCoinsSentEventListener>> coinsSentListeners = new CopyOnWriteArrayList<>(); private final List<ListenerRegistration<WalletReorganizeEventListener>> reorganizeListeners = new CopyOnWriteArrayList<>(); private final List<ListenerRegistration<ScriptsChangeEventListener>> scriptsChangeListeners = new CopyOnWriteArrayList<>(); private final List<ListenerRegistration<TransactionConfidenceEventListener>> transactionConfidenceListeners = new CopyOnWriteArrayList<>(); // A listener that relays confidence changes from the transaction confidence object to the wallet event listener, // as a convenience to API users so they don't have to register on every transaction themselves. private TransactionConfidence.Listener txConfidenceListener; // If a TX hash appears in this set then notifyNewBestBlock will ignore it, as its confidence was already set up // in receive() via Transaction.setBlockAppearance(). As the BlockChain always calls notifyNewBestBlock even if // it sent transactions to the wallet, without this we'd double count. private HashSet<Sha256Hash> ignoreNextNewBlock; // Whether to ignore pending transactions that are considered risky by the configured risk analyzer. private boolean acceptRiskyTransactions; // Object that performs risk analysis of pending transactions. We might reject transactions that seem like // a high risk of being a double spending attack. private RiskAnalysis.Analyzer riskAnalyzer = DefaultRiskAnalysis.FACTORY; // Stuff for notifying transaction objects that we changed their confidences. The purpose of this is to avoid // spuriously sending lots of repeated notifications to listeners that API users aren't really interested in as a // side effect of how the code is written (e.g. during re-orgs confidence data gets adjusted multiple times). private int onWalletChangedSuppressions; private boolean insideReorg; private final Map<Transaction, TransactionConfidence.Listener.ChangeReason> confidenceChanged; protected volatile WalletFiles vFileManager; // Object that is used to send transactions asynchronously when the wallet requires it. protected volatile TransactionBroadcaster vTransactionBroadcaster; // Money controlled by keys created before this time will be automatically respent to a key // that was created after it. Useful when you believe some keys have been compromised. // Null means no key rotation is configured. @Nullable private volatile Instant vKeyRotationTime = null; protected final CoinSelector coinSelector; // The wallet version. This is an int that can be used to track breaking changes in the wallet format. // You can also use it to detect wallets that come from the future (ie they contain features you // do not know how to deal with). private int version; // User-provided description that may help people keep track of what a wallet is for. private String description; // Stores objects that know how to serialize/unserialize themselves to byte streams and whether they're mandatory // or not. The string key comes from the extension itself. private final HashMap<String, WalletExtension> extensions; // Objects that perform transaction signing. Applied subsequently one after another @GuardedBy("lock") private final List<TransactionSigner> signers; // If this is set then the wallet selects spendable candidate outputs from a UTXO provider. @Nullable private volatile UTXOProvider vUTXOProvider; /** * Creates a new, empty wallet with a randomly chosen seed and no transactions. Make sure to provide for sufficient * backup! Any keys will be derived from the seed. If you want to restore a wallet from disk instead, see * {@link #loadFromFile}. * @param network network wallet will operate on * @param outputScriptType type of addresses (aka output scripts) to generate for receiving * @return A new empty wallet */ public static Wallet createDeterministic(Network network, ScriptType outputScriptType) { return createDeterministic(network, outputScriptType, KeyChainGroupStructure.BIP32); } /** * @deprecated use {@link #createDeterministic(Network, ScriptType)} */ @Deprecated public static Wallet createDeterministic(NetworkParameters params, ScriptType outputScriptType) { return createDeterministic(params.network(), outputScriptType); } /** * Creates a new, empty wallet with a randomly chosen seed and no transactions. Make sure to provide for sufficient * backup! Any keys will be derived from the seed. If you want to restore a wallet from disk instead, see * {@link #loadFromFile}. * @param network network wallet will operate on * @param outputScriptType type of addresses (aka output scripts) to generate for receiving * @param keyChainGroupStructure structure (e.g. BIP32 or BIP43) * @return A new empty wallet */ public static Wallet createDeterministic(Network network, ScriptType outputScriptType, KeyChainGroupStructure keyChainGroupStructure) { return new Wallet(network, KeyChainGroup.builder(network, keyChainGroupStructure).fromRandom(outputScriptType).build()); } /** * @deprecated use {@link Wallet#createDeterministic(Network, ScriptType, KeyChainGroupStructure)} */ @Deprecated public static Wallet createDeterministic(NetworkParameters params, ScriptType outputScriptType, KeyChainGroupStructure keyChainGroupStructure) { return new Wallet(params.network(), KeyChainGroup.builder(params.network(), keyChainGroupStructure).fromRandom(outputScriptType).build()); } /** * Creates a new, empty wallet with just a basic keychain and no transactions. No deterministic chains will be created * automatically. This is meant for when you just want to import a few keys and operate on them. * @param network network wallet will operate on */ public static Wallet createBasic(Network network) { return new Wallet(network, KeyChainGroup.createBasic(network)); } /** * @deprecated use {@link #createBasic(Network)} */ @Deprecated public static Wallet createBasic(NetworkParameters params) { return createBasic(params.network()); } /** * @param network network wallet will operate on * @param seed deterministic seed * @param outputScriptType type of addresses (aka output scripts) to generate for receiving * @return a wallet from a deterministic seed with a default account path */ public static Wallet fromSeed(Network network, DeterministicSeed seed, ScriptType outputScriptType) { return fromSeed(network, seed, outputScriptType, KeyChainGroupStructure.BIP32); } /** * @deprecated use {@link #fromSeed(Network, DeterministicSeed, ScriptType)} */ @Deprecated public static Wallet fromSeed(NetworkParameters params, DeterministicSeed seed, ScriptType outputScriptType) { return fromSeed(params.network(), seed, outputScriptType); } /** * @param network network wallet will operate on * @param seed deterministic seed * @param outputScriptType type of addresses (aka output scripts) to generate for receiving * @param structure structure for your wallet * @return a wallet from a deterministic seed with a default account path */ public static Wallet fromSeed(Network network, DeterministicSeed seed, ScriptType outputScriptType, KeyChainGroupStructure structure) { return new Wallet(network, KeyChainGroup.builder(network, structure).fromSeed(seed, outputScriptType).build()); } /** * @deprecated use {@link #fromSeed(Network, DeterministicSeed, ScriptType, KeyChainGroupStructure)} */ @Deprecated public static Wallet fromSeed(NetworkParameters params, DeterministicSeed seed, ScriptType outputScriptType, KeyChainGroupStructure structure) { return fromSeed(params.network(), seed, outputScriptType, structure); } /** * @param network network wallet will operate on * @param seed deterministic seed * @param outputScriptType type of addresses (aka output scripts) to generate for receiving * @param accountPath account path to generate receiving addresses on * @return an instance of a wallet from a deterministic seed. */ public static Wallet fromSeed(Network network, DeterministicSeed seed, ScriptType outputScriptType, List<ChildNumber> accountPath) { DeterministicKeyChain chain = DeterministicKeyChain.builder().seed(seed).outputScriptType(outputScriptType) .accountPath(accountPath).build(); return new Wallet(network, KeyChainGroup.builder(network).addChain(chain).build()); } /** * @deprecated use {@link #fromSeed(Network, DeterministicSeed, ScriptType, List)} */ @Deprecated public static Wallet fromSeed(NetworkParameters params, DeterministicSeed seed, ScriptType outputScriptType, List<ChildNumber> accountPath) { return fromSeed(params.network(), seed, outputScriptType, accountPath); } /** * Creates a wallet that tracks payments to and from the HD key hierarchy rooted by the given watching key. This HAS * to be an account key as returned by {@link DeterministicKeyChain#getWatchingKey()}. */ public static Wallet fromWatchingKey(Network network, DeterministicKey watchKey, ScriptType outputScriptType) { DeterministicKeyChain chain = DeterministicKeyChain.builder().watch(watchKey).outputScriptType(outputScriptType) .build(); return new Wallet(network, KeyChainGroup.builder(network).addChain(chain).build()); } /** * @deprecated use {@link #fromWatchingKey(Network, DeterministicKey, ScriptType)} */ @Deprecated public static Wallet fromWatchingKey(NetworkParameters params, DeterministicKey watchKey, ScriptType outputScriptType) { return fromWatchingKey(params.network(), watchKey, outputScriptType); } /** * Creates a wallet that tracks payments to and from the HD key hierarchy rooted by the given watching key. The * account path is specified. * @param network network wallet will operate on * @param watchKeyB58 The key in base58 notation * @param creationTime creation time of the key (if unknown use {@link #fromWatchingKeyB58(Network, String)} * @return a new wallet */ public static Wallet fromWatchingKeyB58(Network network, String watchKeyB58, Instant creationTime) { final DeterministicKey watchKey = DeterministicKey.deserializeB58(null, watchKeyB58, network); watchKey.setCreationTime(creationTime); return fromWatchingKey(network, watchKey, outputScriptTypeFromB58(NetworkParameters.of(network), watchKeyB58)); } /** * @deprecated use {@link #fromWatchingKeyB58(Network, String, Instant)} */ @Deprecated public static Wallet fromWatchingKeyB58(NetworkParameters params, String watchKeyB58, Instant creationTime) { return fromWatchingKeyB58(params.network(), watchKeyB58, creationTime); } /** * Creates a wallet that tracks payments to and from the HD key hierarchy rooted by the given watching key. The * account path is specified. The key's creation time will be set to {@link DeterministicHierarchy#BIP32_STANDARDISATION_TIME} * @param network network wallet will operate on * @param watchKeyB58 The key in base58 notation * @return a new wallet */ public static Wallet fromWatchingKeyB58(Network network, String watchKeyB58) { return fromWatchingKeyB58(network, watchKeyB58, DeterministicHierarchy.BIP32_STANDARDISATION_TIME); } /** * @deprecated use {@link #fromWatchingKeyB58(Network, String)} */ @Deprecated public static Wallet fromWatchingKeyB58(NetworkParameters params, String watchKeyB58) { return fromWatchingKeyB58(params.network(), watchKeyB58); } /** * @deprecated Use {@link #fromWatchingKeyB58(Network, String, Instant)} or {@link #fromWatchingKeyB58(Network, String)} */ @Deprecated public static Wallet fromWatchingKeyB58(NetworkParameters params, String watchKeyB58, long creationTimeSeconds) { return (creationTimeSeconds == 0) ? fromWatchingKeyB58(params.network(), watchKeyB58) : fromWatchingKeyB58(params.network(), watchKeyB58, Instant.ofEpochSecond(creationTimeSeconds)); } /** * Creates a wallet that tracks payments to and from the HD key hierarchy rooted by the given spending key. This HAS * to be an account key as returned by {@link DeterministicKeyChain#getWatchingKey()}. This wallet can also spend. * @param network network wallet will operate on */ public static Wallet fromSpendingKey(Network network, DeterministicKey spendKey, ScriptType outputScriptType) { DeterministicKeyChain chain = DeterministicKeyChain.builder().spend(spendKey).outputScriptType(outputScriptType) .build(); return new Wallet(network, KeyChainGroup.builder(network).addChain(chain).build()); } /** * @deprecated use {@link #fromSpendingKey(Network, DeterministicKey, ScriptType)} */ @Deprecated public static Wallet fromSpendingKey(NetworkParameters params, DeterministicKey spendKey, ScriptType outputScriptType) { DeterministicKeyChain chain = DeterministicKeyChain.builder().spend(spendKey).outputScriptType(outputScriptType) .build(); return new Wallet(params.network(), KeyChainGroup.builder(params.network()).addChain(chain).build()); } /** * Creates a wallet that tracks payments to and from the HD key hierarchy rooted by the given spending key. * @param network network wallet will operate on * @param spendingKeyB58 The key in base58 notation * @param creationTime creation time of the key (if unknown use {@link #fromWatchingKeyB58(Network, String)} * @return a new wallet */ public static Wallet fromSpendingKeyB58(Network network, String spendingKeyB58, Instant creationTime) { final DeterministicKey spendKey = DeterministicKey.deserializeB58(null, spendingKeyB58, network); spendKey.setCreationTime(creationTime); return fromSpendingKey(network, spendKey, outputScriptTypeFromB58(NetworkParameters.of(network), spendingKeyB58)); } /** * @deprecated use {@link #fromWatchingKeyB58(Network, String, Instant)} */ @Deprecated public static Wallet fromSpendingKeyB58(NetworkParameters params, String spendingKeyB58, Instant creationTime) { return fromWatchingKeyB58(params.network(), spendingKeyB58, creationTime); } /** * Creates a wallet that tracks payments to and from the HD key hierarchy rooted by the given spending key. * The key's creation time will be set to {@link DeterministicHierarchy#BIP32_STANDARDISATION_TIME}. * @param network network wallet will operate on * @param spendingKeyB58 The key in base58 notation * @return a new wallet */ public static Wallet fromSpendingKeyB58(Network network, String spendingKeyB58) { return fromSpendingKeyB58(network, spendingKeyB58, DeterministicHierarchy.BIP32_STANDARDISATION_TIME); } /** * @deprecated use {@link #fromSpendingKeyB58(Network, String)} */ @Deprecated public static Wallet fromSpendingKeyB58(NetworkParameters params, String spendingKeyB58) { return fromSpendingKeyB58(params.network(), spendingKeyB58); } /** * @deprecated Use {@link #fromSpendingKeyB58(Network, String, Instant)} or {@link #fromSpendingKeyB58(Network, String)} */ @Deprecated public static Wallet fromSpendingKeyB58(NetworkParameters params, String spendingKeyB58, long creationTimeSeconds) { return (creationTimeSeconds == 0) ? fromSpendingKeyB58(params.network(), spendingKeyB58) : fromSpendingKeyB58(params.network(), spendingKeyB58, Instant.ofEpochSecond(creationTimeSeconds)); } /** * Creates a wallet that tracks payments to and from the HD key hierarchy rooted by the given spending key. This HAS * to be an account key as returned by {@link DeterministicKeyChain#getWatchingKey()}. * @param network network wallet will operate on */ public static Wallet fromMasterKey(Network network, DeterministicKey masterKey, ScriptType outputScriptType, ChildNumber accountNumber) { DeterministicKey accountKey = HDKeyDerivation.deriveChildKey(masterKey, accountNumber); accountKey = accountKey.dropParent(); Optional<Instant> creationTime = masterKey.creationTime(); if (creationTime.isPresent()) accountKey.setCreationTime(creationTime.get()); else accountKey.clearCreationTime(); DeterministicKeyChain chain = DeterministicKeyChain.builder().spend(accountKey) .outputScriptType(outputScriptType).build(); return new Wallet(network, KeyChainGroup.builder(network).addChain(chain).build()); } /** * @deprecated use {@link #fromMasterKey(Network, DeterministicKey, ScriptType, ChildNumber)} */ @Deprecated public static Wallet fromMasterKey(NetworkParameters params, DeterministicKey masterKey, ScriptType outputScriptType, ChildNumber accountNumber) { return fromMasterKey(params.network(), masterKey, outputScriptType, accountNumber); } private static ScriptType outputScriptTypeFromB58(NetworkParameters params, String base58) { int header = ByteBuffer.wrap(Base58.decodeChecked(base58)).getInt(); if (header == params.getBip32HeaderP2PKHpub() || header == params.getBip32HeaderP2PKHpriv()) return ScriptType.P2PKH; else if (header == params.getBip32HeaderP2WPKHpub() || header == params.getBip32HeaderP2WPKHpriv()) return ScriptType.P2WPKH; else throw new IllegalArgumentException(base58.substring(0, 4)); } /** * Creates a new, empty wallet with a randomly chosen seed and no transactions. Make sure to provide for sufficient * backup! Any keys will be derived from the seed. If you want to restore a wallet from disk instead, see * {@link #loadFromFile}. * @param network network wallet will operate on * @param keyChainGroup keychain group to manage keychains */ public Wallet(Network network, KeyChainGroup keyChainGroup) { this.network = Objects.requireNonNull(network); this.params = NetworkParameters.of(network); this.coinSelector = DefaultCoinSelector.get(network); this.keyChainGroup = Objects.requireNonNull(keyChainGroup); watchedScripts = new HashSet<>(); unspent = new HashMap<>(); spent = new HashMap<>(); pending = new HashMap<>(); dead = new HashMap<>(); transactions = new HashMap<>(); extensions = new HashMap<>(); // Use a linked hash map to ensure ordering of event listeners is correct. confidenceChanged = new LinkedHashMap<>(); signers = new ArrayList<>(); addTransactionSigner(new LocalTransactionSigner()); createTransientState(); } /** * @deprecated use {@link Wallet(NetworkParameters, KeyChainGroup)} */ @Deprecated public Wallet(NetworkParameters params, KeyChainGroup keyChainGroup) { this(params.network(), keyChainGroup); } private void createTransientState() { ignoreNextNewBlock = new HashSet<>(); txConfidenceListener = (confidence, reason) -> { // This will run on the user code thread so we shouldn't do anything too complicated here. // We only want to queue a wallet changed event and auto-save if the number of peers announcing // the transaction has changed, as that confidence change is made by the networking code which // doesn't necessarily know at that point which wallets contain which transactions, so it's up // to us to listen for that. Other types of confidence changes (type, etc) are triggered by us, // so we'll queue up a wallet change event in other parts of the code. if (reason == Listener.ChangeReason.SEEN_PEERS) { lock.lock(); try { checkBalanceFuturesLocked(); Transaction tx = getTransaction(confidence.getTransactionHash()); queueOnTransactionConfidenceChanged(tx); maybeQueueOnWalletChanged(); } finally { lock.unlock(); } } }; acceptRiskyTransactions = false; } public Network network() { return network; } public NetworkParameters getNetworkParameters() { return params; } /** * Parse an address string using all formats this wallet knows about for the wallet's network type * @param addressString Address string to parse * @return A validated address * @throws AddressFormatException if invalid string */ @Override public Address parseAddress(String addressString) throws AddressFormatException { return addressParser.parseAddress(addressString, network); } /** * Gets the active keychains via {@link KeyChainGroup#getActiveKeyChains(long)}. */ public List<DeterministicKeyChain> getActiveKeyChains() { keyChainGroupLock.lock(); try { Instant keyRotationTime = vKeyRotationTime; return keyChainGroup.getActiveKeyChains(keyRotationTime); } finally { keyChainGroupLock.unlock(); } } /** * Gets the default active keychain via {@link KeyChainGroup#getActiveKeyChain()}. */ public DeterministicKeyChain getActiveKeyChain() { keyChainGroupLock.lock(); try { return keyChainGroup.getActiveKeyChain(); } finally { keyChainGroupLock.unlock(); } } /** * <p>Adds given transaction signer to the list of signers. It will be added to the end of the signers list, so if * this wallet already has some signers added, given signer will be executed after all of them.</p> * <p>Transaction signer should be fully initialized before adding to the wallet, otherwise {@link IllegalStateException} * will be thrown</p> */ public final void addTransactionSigner(TransactionSigner signer) { lock.lock(); try { if (signer.isReady()) signers.add(signer); else throw new IllegalStateException("Signer instance is not ready to be added into Wallet: " + signer.getClass()); } finally { lock.unlock(); } } public List<TransactionSigner> getTransactionSigners() { lock.lock(); try { return Collections.unmodifiableList(signers); } finally { lock.unlock(); } } // *************************************************************************************************************** //region Key Management /** * Returns a key that hasn't been seen in a transaction yet, and which is suitable for displaying in a wallet * user interface as "a convenient key to receive funds on" when the purpose parameter is * {@link KeyChain.KeyPurpose#RECEIVE_FUNDS}. The returned key is stable until * it's actually seen in a pending or confirmed transaction, at which point this method will start returning * a different key (for each purpose independently). */ public DeterministicKey currentKey(KeyChain.KeyPurpose purpose) { keyChainGroupLock.lock(); try { return keyChainGroup.currentKey(purpose); } finally { keyChainGroupLock.unlock(); } } /** * An alias for calling {@link #currentKey(KeyChain.KeyPurpose)} with * {@link KeyChain.KeyPurpose#RECEIVE_FUNDS} as the parameter. */ public DeterministicKey currentReceiveKey() { return currentKey(KeyChain.KeyPurpose.RECEIVE_FUNDS); } /** * Returns address for a {@link #currentKey(KeyChain.KeyPurpose)} */ public Address currentAddress(KeyChain.KeyPurpose purpose) { keyChainGroupLock.lock(); try { return keyChainGroup.currentAddress(purpose); } finally { keyChainGroupLock.unlock(); } } /** * An alias for calling {@link #currentAddress(KeyChain.KeyPurpose)} with * {@link KeyChain.KeyPurpose#RECEIVE_FUNDS} as the parameter. */ public Address currentReceiveAddress() { return currentAddress(KeyChain.KeyPurpose.RECEIVE_FUNDS); } /** * Returns a key that has not been returned by this method before (fresh). You can think of this as being * a newly created key, although the notion of "create" is not really valid for a * {@link DeterministicKeyChain}. When the parameter is * {@link KeyChain.KeyPurpose#RECEIVE_FUNDS} the returned key is suitable for being put * into a receive coins wizard type UI. You should use this when the user is definitely going to hand this key out * to someone who wishes to send money. */ public DeterministicKey freshKey(KeyChain.KeyPurpose purpose) { return freshKeys(purpose, 1).get(0); } /** * Returns a key/s that has not been returned by this method before (fresh). You can think of this as being * a newly created key/s, although the notion of "create" is not really valid for a * {@link DeterministicKeyChain}. When the parameter is * {@link KeyChain.KeyPurpose#RECEIVE_FUNDS} the returned key is suitable for being put * into a receive coins wizard type UI. You should use this when the user is definitely going to hand this key/s out * to someone who wishes to send money. */ public List<DeterministicKey> freshKeys(KeyChain.KeyPurpose purpose, int numberOfKeys) { List<DeterministicKey> keys; keyChainGroupLock.lock(); try { keys = keyChainGroup.freshKeys(purpose, numberOfKeys); } finally { keyChainGroupLock.unlock(); } // Do we really need an immediate hard save? Arguably all this is doing is saving the 'current' key // and that's not quite so important, so we could coalesce for more performance. saveNow(); return keys; } /** * An alias for calling {@link #freshKey(KeyChain.KeyPurpose)} with * {@link KeyChain.KeyPurpose#RECEIVE_FUNDS} as the parameter. */ public DeterministicKey freshReceiveKey() { return freshKey(KeyChain.KeyPurpose.RECEIVE_FUNDS); } /** * Returns address for a {@link #freshKey(KeyChain.KeyPurpose)} */ public Address freshAddress(KeyChain.KeyPurpose purpose) { Address address; keyChainGroupLock.lock(); try { address = keyChainGroup.freshAddress(purpose); } finally { keyChainGroupLock.unlock(); } saveNow(); return address; } /** * An alias for calling {@link #freshAddress(KeyChain.KeyPurpose)} with * {@link KeyChain.KeyPurpose#RECEIVE_FUNDS} as the parameter. */ public Address freshReceiveAddress() { return freshAddress(KeyChain.KeyPurpose.RECEIVE_FUNDS); } /** * <p>Returns a fresh receive address for a given {@link ScriptType}.</p> * <p>This method is meant for when you really need a fallback address. Normally, you should be * using {@link #freshAddress(KeyChain.KeyPurpose)} or * {@link #currentAddress(KeyChain.KeyPurpose)}.</p> */ public Address freshReceiveAddress(ScriptType scriptType) { Address address; keyChainGroupLock.lock(); try { Instant keyRotationTime = vKeyRotationTime; address = keyChainGroup.freshAddress(KeyChain.KeyPurpose.RECEIVE_FUNDS, scriptType, keyRotationTime); } finally { keyChainGroupLock.unlock(); } saveNow(); return address; } /** * Returns only the keys that have been issued by {@link #freshReceiveKey()}, {@link #freshReceiveAddress()}, * {@link #currentReceiveKey()} or {@link #currentReceiveAddress()}. */ public List<ECKey> getIssuedReceiveKeys() { keyChainGroupLock.lock(); try { List<ECKey> keys = new LinkedList<>(); Instant keyRotationTime = vKeyRotationTime; for (final DeterministicKeyChain chain : keyChainGroup.getActiveKeyChains(keyRotationTime)) keys.addAll(chain.getIssuedReceiveKeys()); return keys; } finally { keyChainGroupLock.unlock(); } } /** * Returns only the addresses that have been issued by {@link #freshReceiveKey()}, {@link #freshReceiveAddress()}, * {@link #currentReceiveKey()} or {@link #currentReceiveAddress()}. */ public List<Address> getIssuedReceiveAddresses() { keyChainGroupLock.lock(); try { List<Address> addresses = new ArrayList<>(); Instant keyRotationTime = vKeyRotationTime; for (final DeterministicKeyChain chain : keyChainGroup.getActiveKeyChains(keyRotationTime)) { ScriptType outputScriptType = chain.getOutputScriptType(); for (ECKey key : chain.getIssuedReceiveKeys()) addresses.add(key.toAddress(outputScriptType, network())); } return addresses; } finally { keyChainGroupLock.unlock(); } } /** * Upgrades the wallet to be deterministic (BIP32). You should call this, possibly providing the users encryption * key, after loading a wallet produced by previous versions of bitcoinj. If the wallet is encrypted the key * <b>must</b> be provided, due to the way the seed is derived deterministically from private key bytes: failing * to do this will result in an exception being thrown. For non-encrypted wallets, the upgrade will be done for * you automatically the first time a new key is requested (this happens when spending due to the change address). */ public void upgradeToDeterministic(ScriptType outputScriptType, @Nullable AesKey aesKey) throws DeterministicUpgradeRequiresPassword { upgradeToDeterministic(outputScriptType, KeyChainGroupStructure.BIP32, aesKey); } /** * Upgrades the wallet to be deterministic (BIP32). You should call this, possibly providing the users encryption * key, after loading a wallet produced by previous versions of bitcoinj. If the wallet is encrypted the key * <b>must</b> be provided, due to the way the seed is derived deterministically from private key bytes: failing * to do this will result in an exception being thrown. For non-encrypted wallets, the upgrade will be done for * you automatically the first time a new key is requested (this happens when spending due to the change address). */ public void upgradeToDeterministic(ScriptType outputScriptType, KeyChainGroupStructure structure, @Nullable AesKey aesKey) throws DeterministicUpgradeRequiresPassword { keyChainGroupLock.lock(); try { Instant keyRotationTime = vKeyRotationTime; keyChainGroup.upgradeToDeterministic(outputScriptType, structure, keyRotationTime, aesKey); } finally { keyChainGroupLock.unlock(); } } /** * Returns true if the wallet contains random keys and no HD chains, in which case you should call * {@link #upgradeToDeterministic(ScriptType, AesKey)} before attempting to do anything * that would require a new address or key. */ public boolean isDeterministicUpgradeRequired(ScriptType outputScriptType) { keyChainGroupLock.lock(); try { Instant keyRotationTime = vKeyRotationTime; return keyChainGroup.isDeterministicUpgradeRequired(outputScriptType, keyRotationTime); } finally { keyChainGroupLock.unlock(); } } /** * Returns a snapshot of the watched scripts. This view is not live. */ public List<Script> getWatchedScripts() { keyChainGroupLock.lock(); try { return new ArrayList<>(watchedScripts); } finally { keyChainGroupLock.unlock(); } } /** * Removes the given key from the basicKeyChain. Be very careful with this - losing a private key <b>destroys the * money associated with it</b>. * @return Whether the key was removed or not. */ public boolean removeKey(ECKey key) { keyChainGroupLock.lock(); try { return keyChainGroup.removeImportedKey(key); } finally { keyChainGroupLock.unlock(); } } /** * Returns the number of keys in the key chain group, including lookahead keys. */ public int getKeyChainGroupSize() { keyChainGroupLock.lock(); try { return keyChainGroup.numKeys(); } finally { keyChainGroupLock.unlock(); } } @VisibleForTesting public int getKeyChainGroupCombinedKeyLookaheadEpochs() { keyChainGroupLock.lock(); try { return keyChainGroup.getCombinedKeyLookaheadEpochs(); } finally { keyChainGroupLock.unlock(); } } /** * Returns a list of the non-deterministic keys that have been imported into the wallet, or the empty list if none. */ public List<ECKey> getImportedKeys() { keyChainGroupLock.lock(); try { return keyChainGroup.getImportedKeys(); } finally { keyChainGroupLock.unlock(); } } /** Returns the address used for change outputs. Note: this will probably go away in future. */ public Address currentChangeAddress() { return currentAddress(KeyChain.KeyPurpose.CHANGE); } /** * <p>Imports the given ECKey to the wallet.</p> * * <p>If the wallet is configured to auto save to a file, triggers a save immediately. Runs the onKeysAdded event * handler. If the key already exists in the wallet, does nothing and returns false.</p> */ public boolean importKey(ECKey key) { return importKeys(Collections.singletonList(key)) == 1; } /** * Imports the given keys to the wallet. * If {@link Wallet#autosaveToFile(File, long, TimeUnit, WalletFiles.Listener)} * has been called, triggers an auto save bypassing the normal coalescing delay and event handlers. * Returns the number of keys added, after duplicates are ignored. The onKeyAdded event will be called for each key * in the list that was not already present. */ public int importKeys(final List<ECKey> keys) { // API usage check. checkNoDeterministicKeys(keys); int result; keyChainGroupLock.lock(); try { result = keyChainGroup.importKeys(keys); } finally { keyChainGroupLock.unlock(); } saveNow(); return result; } private void checkNoDeterministicKeys(List<ECKey> keys) { // Watch out for someone doing wallet.importKey(wallet.freshReceiveKey()); or equivalent: we never tested this. for (ECKey key : keys) if (key instanceof DeterministicKey) throw new IllegalArgumentException("Cannot import HD keys back into the wallet"); } /** Takes a list of keys and a password, then encrypts and imports them in one step using the current keycrypter. */ public int importKeysAndEncrypt(final List<ECKey> keys, CharSequence password) { keyChainGroupLock.lock(); try { Objects.requireNonNull(getKeyCrypter(), "Wallet is not encrypted"); return importKeysAndEncrypt(keys, getKeyCrypter().deriveKey(password)); } finally { keyChainGroupLock.unlock(); } } /** Takes a list of keys and an AES key, then encrypts and imports them in one step using the current keycrypter. */ public int importKeysAndEncrypt(final List<ECKey> keys, AesKey aesKey) { keyChainGroupLock.lock(); try { checkNoDeterministicKeys(keys); return keyChainGroup.importKeysAndEncrypt(keys, aesKey); } finally { keyChainGroupLock.unlock(); } } /** * Add a pre-configured keychain to the wallet. Useful for setting up a complex keychain, * such as for a married wallet (which is not supported any more). */ public void addAndActivateHDChain(DeterministicKeyChain chain) { keyChainGroupLock.lock(); try { keyChainGroup.addAndActivateHDChain(chain); } finally { keyChainGroupLock.unlock(); } } /** See {@link DeterministicKeyChain#setLookaheadSize(int)} for more info on this. */ public int getKeyChainGroupLookaheadSize() { keyChainGroupLock.lock(); try { return keyChainGroup.getLookaheadSize(); } finally { keyChainGroupLock.unlock(); } } /** See {@link DeterministicKeyChain#setLookaheadThreshold(int)} for more info on this. */ public int getKeyChainGroupLookaheadThreshold() { keyChainGroupLock.lock(); try { return keyChainGroup.getLookaheadThreshold(); } finally { keyChainGroupLock.unlock(); } } /** * Returns a public-only DeterministicKey that can be used to set up a watching wallet: that is, a wallet that * can import transactions from the block chain just as the normal wallet can, but which cannot spend. Watching * wallets are very useful for things like web servers that accept payments. This key corresponds to the account * zero key in the recommended BIP32 hierarchy. */ public DeterministicKey getWatchingKey() { keyChainGroupLock.lock(); try { return keyChainGroup.getActiveKeyChain().getWatchingKey(); } finally { keyChainGroupLock.unlock(); } } /** * Returns whether this wallet consists entirely of watching keys (unencrypted keys with no private part). Mixed * wallets are forbidden. * * @throws IllegalStateException * if there are no keys, or if there is a mix between watching and non-watching keys. */ public boolean isWatching() { keyChainGroupLock.lock(); try { return keyChainGroup.isWatching(); } finally { keyChainGroupLock.unlock(); } } /** * Return true if we are watching this address. */ public boolean isAddressWatched(Address address) { Script script = ScriptBuilder.createOutputScript(address); return isWatchedScript(script); } /** * Same as {@link #addWatchedAddress(Address, long)} with the current time as the creation time. */ public boolean addWatchedAddress(final Address address) { Instant now = TimeUtils.currentTime(); return addWatchedAddresses(Collections.singletonList(address), now) == 1; } /** * Adds the given address to the wallet to be watched. Outputs can be retrieved by {@link #getWatchedOutputs(boolean)}. * * @param creationTime creation time, for scanning the blockchain * @return whether the address was added successfully (not already present) */ public boolean addWatchedAddress(final Address address, Instant creationTime) { return addWatchedAddresses(Collections.singletonList(address), creationTime) == 1; } /** @deprecated use {@link #addWatchedAddress(Address, Instant)} or {@link #addWatchedAddress(Address)} */ @Deprecated public boolean addWatchedAddress(final Address address, long creationTime) { return creationTime > 0 ? addWatchedAddress(address, Instant.ofEpochSecond(creationTime)) : addWatchedAddress(address); } /** * Adds the given addresses to the wallet to be watched. Outputs can be retrieved * by {@link #getWatchedOutputs(boolean)}. * @param addresses addresses to be watched * @param creationTime creation time of the addresses * @return how many addresses were added successfully */ public int addWatchedAddresses(final List<Address> addresses, Instant creationTime) { List<Script> scripts = new ArrayList<>(); for (Address address : addresses) { Script script = ScriptBuilder.createOutputScript(address, creationTime); scripts.add(script); } return addWatchedScripts(scripts); } /** * Adds the given addresses to the wallet to be watched. Outputs can be retrieved * by {@link #getWatchedOutputs(boolean)}. Use this if the creation time of the addresses is unknown. * @param addresses addresses to be watched * @return how many addresses were added successfully */ public int addWatchedAddresses(final List<Address> addresses) { List<Script> scripts = new ArrayList<>(); for (Address address : addresses) { Script script = ScriptBuilder.createOutputScript(address); scripts.add(script); } return addWatchedScripts(scripts); } /** @deprecated use {@link #addWatchedAddresses(List, Instant)} or {@link #addWatchedAddresses(List)} */ @Deprecated public int addWatchedAddresses(final List<Address> addresses, long creationTime) { return creationTime > 0 ? addWatchedAddresses(addresses, creationTime) : addWatchedAddresses(addresses); } /** * Adds the given output scripts to the wallet to be watched. Outputs can be retrieved by {@link #getWatchedOutputs(boolean)}. * If a script is already being watched, the object is replaced with the one in the given list. As {@link Script} * equality is defined in terms of program bytes only this lets you update metadata such as creation time. Note that * you should be careful not to add scripts with a creation time of zero (the default!) because otherwise it will * disable the important wallet checkpointing optimisation. * * @return how many scripts were added successfully */ public int addWatchedScripts(final List<Script> scripts) { int added = 0; keyChainGroupLock.lock(); try { for (final Script script : scripts) { // Script.equals/hashCode() only takes into account the program bytes, so this step lets the user replace // a script in the wallet with an incorrect creation time. if (watchedScripts.contains(script)) watchedScripts.remove(script); if (!script.creationTime().isPresent()) log.warn("Adding a script to the wallet with a creation time of zero, this will disable the checkpointing optimization! {}", script); watchedScripts.add(script); added++; } } finally { keyChainGroupLock.unlock(); } if (added > 0) { queueOnScriptsChanged(scripts, true); saveNow(); } return added; } /** * Removes the given output scripts from the wallet that were being watched. * * @return true if successful */ public boolean removeWatchedAddress(final Address address) { return removeWatchedAddresses(Collections.singletonList(address)); } /** * Removes the given output scripts from the wallet that were being watched. * * @return true if successful */ public boolean removeWatchedAddresses(final List<Address> addresses) { List<Script> scripts = new ArrayList<>(); for (Address address : addresses) { Script script = ScriptBuilder.createOutputScript(address); scripts.add(script); } return removeWatchedScripts(scripts); } /** * Removes the given output scripts from the wallet that were being watched. * * @return true if successful */ public boolean removeWatchedScripts(final List<Script> scripts) { lock.lock(); try { for (final Script script : scripts) { if (!watchedScripts.contains(script)) continue; watchedScripts.remove(script); } queueOnScriptsChanged(scripts, false); saveNow(); return true; } finally { lock.unlock(); } } /** * Returns all addresses watched by this wallet. */ public List<Address> getWatchedAddresses() { keyChainGroupLock.lock(); try { List<Address> addresses = new LinkedList<>(); for (Script script : watchedScripts) if (ScriptPattern.isP2PKH(script)) addresses.add(script.getToAddress(network)); return addresses; } finally { keyChainGroupLock.unlock(); } } /** * Locates a keypair from the basicKeyChain given the hash of the public key. This is needed when finding out which * key we need to use to redeem a transaction output. * * @return ECKey object or null if no such key was found. */ @Override @Nullable public ECKey findKeyFromPubKeyHash(byte[] pubKeyHash, @Nullable ScriptType scriptType) { keyChainGroupLock.lock(); try { return keyChainGroup.findKeyFromPubKeyHash(pubKeyHash, scriptType); } finally { keyChainGroupLock.unlock(); } } /** Returns true if the given key is in the wallet, false otherwise. Currently an O(N) operation. */ public boolean hasKey(ECKey key) { keyChainGroupLock.lock(); try { return keyChainGroup.hasKey(key); } finally { keyChainGroupLock.unlock(); } } /** * Returns true if the address is belongs to this wallet. */ public boolean isAddressMine(Address address) { final ScriptType scriptType = address.getOutputScriptType(); if (scriptType == ScriptType.P2PKH || scriptType == ScriptType.P2WPKH) return isPubKeyHashMine(address.getHash(), scriptType); else if (scriptType == ScriptType.P2SH) return isPayToScriptHashMine(address.getHash()); else if (scriptType == ScriptType.P2WSH || scriptType == ScriptType.P2TR) return false; else throw new IllegalArgumentException(address.toString()); } @Override public boolean isPubKeyHashMine(byte[] pubKeyHash, @Nullable ScriptType scriptType) { return findKeyFromPubKeyHash(pubKeyHash, scriptType) != null; } @Override public boolean isWatchedScript(Script script) { keyChainGroupLock.lock(); try { return watchedScripts.contains(script); } finally { keyChainGroupLock.unlock(); } } /** * Locates a keypair from the wallet given the corresponding address. * @return ECKey or null if no such key was found. */ public ECKey findKeyFromAddress(Address address) { final ScriptType scriptType = address.getOutputScriptType(); if (scriptType == ScriptType.P2PKH || scriptType == ScriptType.P2WPKH) return findKeyFromPubKeyHash(address.getHash(), scriptType); else return null; } /** * Locates a keypair from the basicKeyChain given the raw public key bytes. * @return ECKey or null if no such key was found. */ @Override @Nullable public ECKey findKeyFromPubKey(byte[] pubKey) { keyChainGroupLock.lock(); try { return keyChainGroup.findKeyFromPubKey(pubKey); } finally { keyChainGroupLock.unlock(); } } @Override public boolean isPubKeyMine(byte[] pubKey) { return findKeyFromPubKey(pubKey) != null; } /** * Locates a redeem data (redeem script and keys) from the keyChainGroup given the hash of the script. * Returns RedeemData object or null if no such data was found. */ @Nullable @Override public RedeemData findRedeemDataFromScriptHash(byte[] payToScriptHash) { keyChainGroupLock.lock(); try { return keyChainGroup.findRedeemDataFromScriptHash(payToScriptHash); } finally { keyChainGroupLock.unlock(); } } @Override public boolean isPayToScriptHashMine(byte[] payToScriptHash) { return findRedeemDataFromScriptHash(payToScriptHash) != null; } /** * Marks all keys used in the transaction output as used in the wallet. * See {@link DeterministicKeyChain#markKeyAsUsed(DeterministicKey)} for more info on this. */ private void markKeysAsUsed(Transaction tx) { keyChainGroupLock.lock(); try { for (TransactionOutput o : tx.getOutputs()) { try { Script script = o.getScriptPubKey(); if (ScriptPattern.isP2PK(script)) { byte[] pubkey = ScriptPattern.extractKeyFromP2PK(script); keyChainGroup.markPubKeyAsUsed(pubkey); } else if (ScriptPattern.isP2PKH(script)) { byte[] pubkeyHash = ScriptPattern.extractHashFromP2PKH(script); keyChainGroup.markPubKeyHashAsUsed(pubkeyHash); } else if (ScriptPattern.isP2SH(script)) { LegacyAddress a = LegacyAddress.fromScriptHash(network(), ScriptPattern.extractHashFromP2SH(script)); keyChainGroup.markP2SHAddressAsUsed(a); } else if (ScriptPattern.isP2WH(script)) { byte[] pubkeyHash = ScriptPattern.extractHashFromP2WH(script); keyChainGroup.markPubKeyHashAsUsed(pubkeyHash); } } catch (ScriptException e) { // Just means we didn't understand the output of this transaction: ignore it. log.info("Could not parse tx output script: {}", e.toString()); } } } finally { keyChainGroupLock.unlock(); } } /** * Returns the immutable seed for the current active HD chain. * @throws ECKey.MissingPrivateKeyException if the seed is unavailable (watching wallet) */ public DeterministicSeed getKeyChainSeed() { keyChainGroupLock.lock(); try { DeterministicSeed seed = keyChainGroup.getActiveKeyChain().getSeed(); if (seed == null) throw new ECKey.MissingPrivateKeyException(); return seed; } finally { keyChainGroupLock.unlock(); } } /** * Returns a key for the given HD path, assuming it's already been derived. You normally shouldn't use this: * use currentReceiveKey/freshReceiveKey instead. */ public DeterministicKey getKeyByPath(List<ChildNumber> path) { keyChainGroupLock.lock(); try { return keyChainGroup.getActiveKeyChain().getKeyByPath(path, false); } finally { keyChainGroupLock.unlock(); } } /** * Convenience wrapper around {@link Wallet#encrypt(KeyCrypter, * AesKey)} which uses the default Scrypt key derivation algorithm and * parameters to derive a key from the given password. */ public void encrypt(CharSequence password) { keyChainGroupLock.lock(); try { final KeyCrypterScrypt scrypt = new KeyCrypterScrypt(); keyChainGroup.encrypt(scrypt, scrypt.deriveKey(password)); } finally { keyChainGroupLock.unlock(); } saveNow(); } /** * Encrypt the wallet using the KeyCrypter and the AES key. A good default KeyCrypter to use is * {@link KeyCrypterScrypt}. * * @param keyCrypter The KeyCrypter that specifies how to encrypt/ decrypt a key * @param aesKey AES key to use (normally created using KeyCrypter#deriveKey and cached as it is time consuming to create from a password) * @throws KeyCrypterException Thrown if the wallet encryption fails. If so, the wallet state is unchanged. */ public void encrypt(KeyCrypter keyCrypter, AesKey aesKey) { keyChainGroupLock.lock(); try { keyChainGroup.encrypt(keyCrypter, aesKey); } finally { keyChainGroupLock.unlock(); } saveNow(); } /** * Decrypt the wallet with the wallets keyCrypter and password. * @throws BadWalletEncryptionKeyException Thrown if the given password is wrong. If so, the wallet state is unchanged. * @throws KeyCrypterException Thrown if the wallet decryption fails. If so, the wallet state is unchanged. */ public void decrypt(CharSequence password) throws BadWalletEncryptionKeyException { keyChainGroupLock.lock(); try { final KeyCrypter crypter = keyChainGroup.getKeyCrypter(); checkState(crypter != null, () -> "not encrypted"); keyChainGroup.decrypt(crypter.deriveKey(password)); } catch (KeyCrypterException.InvalidCipherText | KeyCrypterException.PublicPrivateMismatch e) { throw new BadWalletEncryptionKeyException(e); } finally { keyChainGroupLock.unlock(); } saveNow(); } /** * Decrypt the wallet with the wallets keyCrypter and AES key. * * @param aesKey AES key to use (normally created using KeyCrypter#deriveKey and cached as it is time consuming to create from a password) * @throws BadWalletEncryptionKeyException Thrown if the given aesKey is wrong. If so, the wallet state is unchanged. * @throws KeyCrypterException Thrown if the wallet decryption fails. If so, the wallet state is unchanged. */ public void decrypt(AesKey aesKey) throws BadWalletEncryptionKeyException { keyChainGroupLock.lock(); try { keyChainGroup.decrypt(aesKey); } catch (KeyCrypterException.InvalidCipherText | KeyCrypterException.PublicPrivateMismatch e) { throw new BadWalletEncryptionKeyException(e); } finally { keyChainGroupLock.unlock(); } saveNow(); } /** * Check whether the password can decrypt the first key in the wallet. * This can be used to check the validity of an entered password. * * @return boolean true if password supplied can decrypt the first private key in the wallet, false otherwise. * @throws IllegalStateException if the wallet is not encrypted. */ public boolean checkPassword(CharSequence password) { keyChainGroupLock.lock(); try { return keyChainGroup.checkPassword(password); } finally { keyChainGroupLock.unlock(); } } /** * Check whether the AES key can decrypt the first encrypted key in the wallet. * * @return boolean true if AES key supplied can decrypt the first encrypted private key in the wallet, false otherwise. */ public boolean checkAESKey(AesKey aesKey) { keyChainGroupLock.lock(); try { return keyChainGroup.checkAESKey(aesKey); } finally { keyChainGroupLock.unlock(); } } /** * Get the wallet's KeyCrypter, or null if the wallet is not encrypted. * (Used in encrypting/ decrypting an ECKey). */ @Nullable public KeyCrypter getKeyCrypter() { keyChainGroupLock.lock(); try { return keyChainGroup.getKeyCrypter(); } finally { keyChainGroupLock.unlock(); } } /** * Get the type of encryption used for this wallet. * * (This is a convenience method - the encryption type is actually stored in the keyCrypter). */ public EncryptionType getEncryptionType() { keyChainGroupLock.lock(); try { KeyCrypter crypter = keyChainGroup.getKeyCrypter(); if (crypter != null) return crypter.getUnderstoodEncryptionType(); else return EncryptionType.UNENCRYPTED; } finally { keyChainGroupLock.unlock(); } } /** Returns true if the wallet is encrypted using any scheme, false if not. */ public boolean isEncrypted() { return getEncryptionType() != EncryptionType.UNENCRYPTED; } /** * Changes wallet encryption password, this is atomic operation. * @throws BadWalletEncryptionKeyException Thrown if the given currentPassword is wrong. If so, the wallet state is unchanged. * @throws KeyCrypterException Thrown if the wallet decryption fails. If so, the wallet state is unchanged. */ public void changeEncryptionPassword(CharSequence currentPassword, CharSequence newPassword) throws BadWalletEncryptionKeyException { keyChainGroupLock.lock(); try { decrypt(currentPassword); encrypt(newPassword); } finally { keyChainGroupLock.unlock(); } } /** * Changes wallet AES encryption key, this is atomic operation. * @throws BadWalletEncryptionKeyException Thrown if the given currentAesKey is wrong. If so, the wallet state is unchanged. * @throws KeyCrypterException Thrown if the wallet decryption fails. If so, the wallet state is unchanged. */ public void changeEncryptionKey(KeyCrypter keyCrypter, AesKey currentAesKey, AesKey newAesKey) throws BadWalletEncryptionKeyException { keyChainGroupLock.lock(); try { decrypt(currentAesKey); encrypt(keyCrypter, newAesKey); } finally { keyChainGroupLock.unlock(); } } //endregion // *************************************************************************************************************** //region Serialization support @Deprecated public List<Protos.Key> serializeKeyChainGroupToProtobuf() { return serializeKeyChainGroupToProtobufInternal(); } /** Internal use only. */ List<Protos.Key> serializeKeyChainGroupToProtobufInternal() { keyChainGroupLock.lock(); try { return keyChainGroup.serializeToProtobuf(); } finally { keyChainGroupLock.unlock(); } } /** * Saves the wallet first to the given temporary file, then renames to the destination file. This is done to make * the save an atomic operation. * * @param tempFile temporary file to use for saving the wallet * @param destFile file to save the wallet to * @throws FileNotFoundException if directory doesn't exist * @throws IOException if an error occurs while saving */ public void saveToFile(File tempFile, File destFile) throws IOException { File tempParentFile = tempFile.getParentFile(); if (!tempParentFile.exists()) { throw new FileNotFoundException(tempParentFile.getPath() + " (wallet directory not found)"); } File destParentFile = destFile.getParentFile(); if (!destParentFile.exists()) { throw new FileNotFoundException(destParentFile.getPath() + " (wallet directory not found)"); } FileOutputStream stream = null; lock.lock(); try { stream = new FileOutputStream(tempFile); saveToFileStream(stream); // Attempt to force the bits to hit the disk. In reality the OS or hard disk itself may still decide // to not write through to physical media for at least a few seconds, but this is the best we can do. stream.flush(); stream.getFD().sync(); stream.close(); stream = null; if (PlatformUtils.isWindows()) { // Work around an issue on Windows whereby you can't rename over existing files. File canonical = destFile.getCanonicalFile(); if (canonical.exists() && !canonical.delete()) throw new IOException("Failed to delete canonical wallet file for replacement with autosave"); if (tempFile.renameTo(canonical)) return; // else fall through. throw new IOException("Failed to rename " + tempFile + " to " + canonical); } else if (!tempFile.renameTo(destFile)) { throw new IOException("Failed to rename " + tempFile + " to " + destFile); } } catch (RuntimeException e) { log.error("Failed whilst saving wallet", e); throw e; } finally { lock.unlock(); if (stream != null) { stream.close(); } if (tempFile.exists()) { log.warn("Temp file still exists after failed save."); } } } /** * Uses protobuf serialization to save the wallet to the given file. To learn more about this file format, see * {@link WalletProtobufSerializer}. Writes out first to a temporary file in the same directory and then renames * once written. * @param f File to save wallet * @throws FileNotFoundException if directory doesn't exist * @throws IOException if an error occurs while saving */ public void saveToFile(File f) throws IOException { File directory = f.getAbsoluteFile().getParentFile(); if (!directory.exists()) { throw new FileNotFoundException(directory.getPath() + " (wallet directory not found)"); } File temp = File.createTempFile("wallet", null, directory); saveToFile(temp, f); } /** * <p>Whether or not the wallet will ignore pending transactions that fail the selected * {@link RiskAnalysis}. By default, if a transaction is considered risky then it won't enter the wallet * and won't trigger any event listeners. If you set this property to true, then all transactions will * be allowed in regardless of risk. For example, the {@link DefaultRiskAnalysis} checks for non-finality of * transactions.</p> * * <p>Note that this property is not serialized. You have to set it each time a Wallet object is constructed, * even if it's loaded from a protocol buffer.</p> */ public void setAcceptRiskyTransactions(boolean acceptRiskyTransactions) { lock.lock(); try { this.acceptRiskyTransactions = acceptRiskyTransactions; } finally { lock.unlock(); } } /** * See {@link Wallet#setAcceptRiskyTransactions(boolean)} for an explanation of this property. */ public boolean isAcceptRiskyTransactions() { lock.lock(); try { return acceptRiskyTransactions; } finally { lock.unlock(); } } /** * Sets the {@link RiskAnalysis} implementation to use for deciding whether received pending transactions are risky * or not. If the analyzer says a transaction is risky, by default it will be dropped. You can customize this * behaviour with {@link #setAcceptRiskyTransactions(boolean)}. */ public void setRiskAnalyzer(RiskAnalysis.Analyzer analyzer) { lock.lock(); try { this.riskAnalyzer = Objects.requireNonNull(analyzer); } finally { lock.unlock(); } } /** * Gets the current {@link RiskAnalysis} implementation. The default is {@link DefaultRiskAnalysis}. */ public RiskAnalysis.Analyzer getRiskAnalyzer() { lock.lock(); try { return riskAnalyzer; } finally { lock.unlock(); } } /** * <p>Sets up the wallet to auto-save itself to the given file, using temp files with atomic renames to ensure * consistency. After connecting to a file, you no longer need to save the wallet manually, it will do it * whenever necessary. Protocol buffer serialization will be used.</p> * * <p>A background thread will be created and the wallet will only be saved to * disk every periodically. If no changes have occurred for the given time period, nothing will be written. * In this way disk IO can be rate limited. It's a good idea to set this as otherwise the wallet can change very * frequently, eg if there are a lot of transactions in it or during block sync, and there will be a lot of redundant * writes. Note that when a new key is added, that always results in an immediate save regardless of * delayTime. <b>You should still save the wallet manually using {@link Wallet#saveToFile(File)} when your program * is about to shut down as the JVM will not wait for the background thread.</b></p> * * <p>An event listener can be provided. It will be called on a background thread * with the wallet locked when an auto-save occurs.</p> * * @param f The destination file to save to. * @param delay How much time to wait until saving the wallet on a background thread. * @param eventListener callback to be informed when the auto-save thread does things, or null */ public WalletFiles autosaveToFile(File f, Duration delay, @Nullable WalletFiles.Listener eventListener) { lock.lock(); try { checkState(vFileManager == null, () -> "already auto saving this wallet"); WalletFiles manager = new WalletFiles(this, f, delay); if (eventListener != null) manager.setListener(eventListener); vFileManager = manager; return manager; } finally { lock.unlock(); } } /** @deprecated use {@link #autosaveToFile(File, Duration, WalletFiles.Listener)} */ @Deprecated public WalletFiles autosaveToFile(File f, long delayTime, TimeUnit timeUnit, @Nullable WalletFiles.Listener eventListener) { return autosaveToFile(f, Duration.ofMillis(timeUnit.toMillis(delayTime)), eventListener); } /** * <p> * Disables auto-saving, after it had been enabled with * {@link Wallet#autosaveToFile(File, long, TimeUnit, WalletFiles.Listener)} * before. This method blocks until finished. * </p> */ public void shutdownAutosaveAndWait() { lock.lock(); try { WalletFiles files = vFileManager; vFileManager = null; checkState(files != null, () -> "auto saving not enabled"); files.shutdownAndWait(); } finally { lock.unlock(); } } /** Requests an asynchronous save on a background thread */ protected void saveLater() { WalletFiles files = vFileManager; if (files != null) files.saveLater(); } /** If auto saving is enabled, do an immediate sync write to disk ignoring any delays. */ protected void saveNow() { WalletFiles files = vFileManager; if (files != null) { try { files.saveNow(); // This calls back into saveToFile(). } catch (IOException e) { // Can't really do much at this point, just let the API user know. log.error("Failed to save wallet to disk!", e); Thread.UncaughtExceptionHandler handler = Threading.uncaughtExceptionHandler; if (handler != null) handler.uncaughtException(Thread.currentThread(), e); } } } /** * Uses protobuf serialization to save the wallet to the given file stream. To learn more about this file format, see * {@link WalletProtobufSerializer}. */ public void saveToFileStream(OutputStream f) throws IOException { lock.lock(); try { new WalletProtobufSerializer().writeWallet(this, f); } finally { lock.unlock(); } } /** Returns the parameters this wallet was created with. */ public NetworkParameters getParams() { return params; } /** * Returns a wallet deserialized from the given file. Extensions previously saved with the wallet can be * deserialized by calling @{@link WalletExtension#deserializeWalletExtension(Wallet, byte[])}} * * @param file the wallet file to read * @param walletExtensions extensions possibly added to the wallet. * @return The Wallet * @throws UnreadableWalletException if there was a problem loading or parsing the file */ public static Wallet loadFromFile(File file, @Nullable WalletExtension... walletExtensions) throws UnreadableWalletException { return loadFromFile(file, WalletProtobufSerializer.WalletFactory.DEFAULT, false, false, walletExtensions); } /** * Returns a wallet deserialized from the given file. Extensions previously saved with the wallet can be * deserialized by calling @{@link WalletExtension#deserializeWalletExtension(Wallet, byte[])}} * * @param file the wallet file to read * @param factory wallet factory * @param forceReset force a reset of the wallet * @param ignoreMandatoryExtensions if true, mandatory extensions will be ignored instead of causing load errors (not recommended) * @param walletExtensions extensions possibly added to the wallet. * @return The Wallet * @throws UnreadableWalletException if there was a problem loading or parsing the file */ public static Wallet loadFromFile(File file, WalletProtobufSerializer.WalletFactory factory, boolean forceReset, boolean ignoreMandatoryExtensions, @Nullable WalletExtension... walletExtensions) throws UnreadableWalletException { try (FileInputStream stream = new FileInputStream(file)) { return loadFromFileStream(stream, factory, forceReset, ignoreMandatoryExtensions, walletExtensions); } catch (IOException e) { throw new UnreadableWalletException("Could not open file", e); } } /** * Returns if this wallet is structurally consistent, so e.g. no duplicate transactions. First inconsistency and a * dump of the wallet will be logged. */ public boolean isConsistent() { try { isConsistentOrThrow(); return true; } catch (IllegalStateException x) { log.error(x.getMessage()); try { log.error(toString()); } catch (RuntimeException x2) { log.error("Printing inconsistent wallet failed", x2); } return false; } } /** * Variant of {@link Wallet#isConsistent()} that throws an {@link IllegalStateException} describing the first * inconsistency. */ public void isConsistentOrThrow() throws IllegalStateException { lock.lock(); try { Set<Transaction> transactions = getTransactions(true); Set<Sha256Hash> hashes = new HashSet<>(); for (Transaction tx : transactions) { hashes.add(tx.getTxId()); } int size1 = transactions.size(); if (size1 != hashes.size()) { throw new IllegalStateException("Two transactions with same hash"); } int size2 = unspent.size() + spent.size() + pending.size() + dead.size(); if (size1 != size2) { throw new IllegalStateException("Inconsistent wallet sizes: " + size1 + ", " + size2); } for (Transaction tx : unspent.values()) { if (!isTxConsistent(tx, false)) { throw new IllegalStateException("Inconsistent unspent tx: " + tx.getTxId()); } } for (Transaction tx : spent.values()) { if (!isTxConsistent(tx, true)) { throw new IllegalStateException("Inconsistent spent tx: " + tx.getTxId()); } } } finally { lock.unlock(); } } /* * If isSpent - check that all my outputs spent, otherwise check that there at least * one unspent. */ @VisibleForTesting boolean isTxConsistent(final Transaction tx, final boolean isSpent) { boolean isActuallySpent = true; for (TransactionOutput o : tx.getOutputs()) { if (o.isAvailableForSpending()) { if (o.isMineOrWatched(this)) isActuallySpent = false; if (o.getSpentBy() != null) { log.error("isAvailableForSpending != spentBy"); return false; } } else { if (o.getSpentBy() == null) { log.error("isAvailableForSpending != spentBy"); return false; } } } return isActuallySpent == isSpent; } /** * Returns a wallet deserialized from the given input stream and wallet extensions. * @param stream An open InputStream containing a ProtoBuf Wallet * @param walletExtensions extensions possibly added to the wallet. * @return The Wallet * @throws UnreadableWalletException if there was a problem reading or parsing the stream */ public static Wallet loadFromFileStream(InputStream stream, @Nullable WalletExtension... walletExtensions) throws UnreadableWalletException { return loadFromFileStream(stream, WalletProtobufSerializer.WalletFactory.DEFAULT, false, false, walletExtensions); } /** * Returns a wallet deserialized from the given input stream and wallet extensions. * @param stream An open InputStream containing a ProtoBuf Wallet * @param factory wallet factory * @param forceReset if true, configure wallet to replay transactions from the blockchain * @param ignoreMandatoryExtensions if true, mandatory extensions will be ignored instead of causing load errors (not recommended) * @param walletExtensions extensions possibly added to the wallet. * @return The Wallet * @throws UnreadableWalletException if there was a problem reading or parsing the stream */ public static Wallet loadFromFileStream(InputStream stream, WalletProtobufSerializer.WalletFactory factory, boolean forceReset, boolean ignoreMandatoryExtensions, @Nullable WalletExtension... walletExtensions) throws UnreadableWalletException { WalletProtobufSerializer loader = new WalletProtobufSerializer(factory); if (ignoreMandatoryExtensions) { loader.setRequireMandatoryExtensions(false); } Wallet wallet = loader.readWallet(stream, forceReset, walletExtensions); if (!wallet.isConsistent()) { log.error("Loaded an inconsistent wallet"); } return wallet; } //endregion // *************************************************************************************************************** //region Inbound transaction reception and processing /** * Called by the {@link BlockChain} when we receive a new filtered block that contains a transactions previously * received by a call to {@link #receivePending}.<p> * * This is necessary for the internal book-keeping Wallet does. When a transaction is received that sends us * coins it is added to a pool so we can use it later to create spends. When a transaction is received that * consumes outputs they are marked as spent so they won't be used in future.<p> * * A transaction that spends our own coins can be received either because a spend we created was accepted by the * network and thus made it into a block, or because our keys are being shared between multiple instances and * some other node spent the coins instead. We still have to know about that to avoid accidentally trying to * double spend.<p> * * A transaction may be received multiple times if is included into blocks in parallel chains. The blockType * parameter describes whether the containing block is on the main/best chain or whether it's on a presently * inactive side chain. We must still record these transactions and the blocks they appear in because a future * block might change which chain is best causing a reorganize. A re-org can totally change our balance! */ @Override public boolean notifyTransactionIsInBlock(Sha256Hash txHash, StoredBlock block, BlockChain.NewBlockType blockType, int relativityOffset) throws VerificationException { lock.lock(); try { Transaction tx = transactions.get(txHash); if (tx == null) { tx = riskDropped.get(txHash); if (tx != null) { // If this happens our risk analysis is probably wrong and should be improved. log.info("Risk analysis dropped tx {} but was included in block anyway", tx.getTxId()); } else { // False positive that was broadcast to us and ignored by us because it was irrelevant to our keys. return false; } } receive(tx, block, blockType, relativityOffset); return true; } finally { lock.unlock(); } } /** * <p>Called when we have found a transaction (via network broadcast or otherwise) that is relevant to this wallet * and want to record it. Note that we <b>cannot verify these transactions at all</b>, they may spend fictional * coins or be otherwise invalid. They are useful to inform the user about coins they can expect to receive soon, * and if you trust the sender of the transaction you can choose to assume they are in fact valid and will not * be double spent as an optimization.</p> * * <p>This is the same as {@link Wallet#receivePending(Transaction, List)} but allows you to override the * {@link Wallet#isPendingTransactionRelevant(Transaction)} sanity-check to keep track of transactions that are not * spendable or spend our coins. This can be useful when you want to keep track of transaction confidence on * arbitrary transactions. Note that transactions added in this way will still be relayed to peers and appear in * transaction lists like any other pending transaction (even when not relevant).</p> */ public void receivePending(Transaction tx, @Nullable List<Transaction> dependencies, boolean overrideIsRelevant) throws VerificationException { // Can run in a peer thread. This method will only be called if a prior call to isPendingTransactionRelevant // returned true, so we already know by this point that it sends coins to or from our wallet, or is a double // spend against one of our other pending transactions. lock.lock(); try { Transaction.verify(network, tx); // Ignore it if we already know about this transaction. Receiving a pending transaction never moves it // between pools. EnumSet<Pool> containingPools = getContainingPools(tx); if (!containingPools.equals(EnumSet.noneOf(Pool.class))) { log.debug("Received tx we already saw in a block or created ourselves: " + tx.getTxId()); return; } // Repeat the check of relevancy here, even though the caller may have already done so - this is to avoid // race conditions where receivePending may be being called in parallel. if (!overrideIsRelevant && !isPendingTransactionRelevant(tx)) return; if (isTransactionRisky(tx, dependencies) && !acceptRiskyTransactions) { // isTransactionRisky already logged the reason. // Clone transaction to avoid multiple wallets pointing to the same transaction. This can happen when // two wallets depend on the same transaction. Transaction cloneTx = params.getDefaultSerializer().makeTransaction(ByteBuffer.wrap(tx.serialize())); cloneTx.setPurpose(tx.getPurpose()); Optional<Instant> updateTime = tx.updateTime(); if (updateTime.isPresent()) cloneTx.setUpdateTime(updateTime.get()); else cloneTx.clearUpdateTime(); riskDropped.put(cloneTx.getTxId(), cloneTx); log.warn("There are now {} risk dropped transactions being kept in memory", riskDropped.size()); return; } Coin valueSentToMe = tx.getValueSentToMe(this); Coin valueSentFromMe = tx.getValueSentFromMe(this); if (log.isInfoEnabled()) log.info("Received a pending transaction {} that spends {} from our own wallet, and sends us {}", tx.getTxId(), valueSentFromMe.toFriendlyString(), valueSentToMe.toFriendlyString()); if (tx.getConfidence().getSource().equals(TransactionConfidence.Source.UNKNOWN)) { log.warn("Wallet received transaction with an unknown source. Consider tagging it!"); } // Clone transaction to avoid multiple wallets pointing to the same transaction. This can happen when // two wallets depend on the same transaction. Transaction cloneTx = params.getDefaultSerializer().makeTransaction(ByteBuffer.wrap(tx.serialize())); cloneTx.setPurpose(tx.getPurpose()); Optional<Instant> updateTime = tx.updateTime(); if (updateTime.isPresent()) cloneTx.setUpdateTime(updateTime.get()); else cloneTx.clearUpdateTime(); // If this tx spends any of our unspent outputs, mark them as spent now, then add to the pending pool. This // ensures that if some other client that has our keys broadcasts a spend we stay in sync. Also updates the // timestamp on the transaction and registers/runs event listeners. commitTx(cloneTx); } finally { lock.unlock(); } // maybeRotateKeys() will ignore pending transactions so we don't bother calling it here (see the comments // in that function for an explanation of why). } /** * Given a transaction and an optional list of dependencies (recursive/flattened), returns true if the given * transaction would be rejected by the analyzer, or false otherwise. The result of this call is independent * of the value of {@link #isAcceptRiskyTransactions()}. Risky transactions yield a logged warning. If you * want to know the reason why a transaction is risky, create an instance of the {@link RiskAnalysis} yourself * using the factory returned by {@link #getRiskAnalyzer()} and use it directly. */ public boolean isTransactionRisky(Transaction tx, @Nullable List<Transaction> dependencies) { lock.lock(); try { if (dependencies == null) dependencies = Collections.emptyList(); RiskAnalysis analysis = riskAnalyzer.create(this, tx, dependencies); RiskAnalysis.Result result = analysis.analyze(); if (result != RiskAnalysis.Result.OK) { log.warn("Pending transaction was considered risky: {}\n{}", analysis, tx); return true; } return false; } finally { lock.unlock(); } } /** * <p>Called when we have found a transaction (via network broadcast or otherwise) that is relevant to this wallet * and want to record it. Note that we <b>cannot verify these transactions at all</b>, they may spend fictional * coins or be otherwise invalid. They are useful to inform the user about coins they can expect to receive soon, * and if you trust the sender of the transaction you can choose to assume they are in fact valid and will not * be double spent as an optimization.</p> * * <p>Before this method is called, {@link Wallet#isPendingTransactionRelevant(Transaction)} should have been * called to decide whether the wallet cares about the transaction - if it does, then this method expects the * transaction and any dependencies it has which are still in the memory pool.</p> */ public void receivePending(Transaction tx, @Nullable List<Transaction> dependencies) throws VerificationException { receivePending(tx, dependencies, false); } /** * This method is used by a {@link Peer} to find out if a transaction that has been announced is interesting, * that is, whether we should bother downloading its dependencies and exploring the transaction to decide how * risky it is. If this method returns true then {@link Wallet#receivePending(Transaction, List)} * will soon be called with the transactions dependencies as well. */ public boolean isPendingTransactionRelevant(Transaction tx) throws ScriptException { lock.lock(); try { // Ignore it if we already know about this transaction. Receiving a pending transaction never moves it // between pools. EnumSet<Pool> containingPools = getContainingPools(tx); if (!containingPools.equals(EnumSet.noneOf(Pool.class))) { log.debug("Received tx we already saw in a block or created ourselves: " + tx.getTxId()); return false; } // We only care about transactions that: // - Send us coins // - Spend our coins // - Double spend a tx in our wallet if (!isTransactionRelevant(tx)) { log.debug("Received tx that isn't relevant to this wallet, discarding."); return false; } return true; } finally { lock.unlock(); } } /** * <p>Returns true if the given transaction sends coins to any of our keys, or has inputs spending any of our outputs, * and also returns true if tx has inputs that are spending outputs which are * not ours but which are spent by pending transactions.</p> * * <p>Note that if the tx has inputs containing one of our keys, but the connected transaction is not in the wallet, * it will not be considered relevant.</p> */ public boolean isTransactionRelevant(Transaction tx) throws ScriptException { lock.lock(); try { return tx.getValueSentFromMe(this).signum() > 0 || tx.getValueSentToMe(this).signum() > 0 || !findDoubleSpendsAgainst(tx, transactions).isEmpty(); } finally { lock.unlock(); } } /** * Determine if a transaction is <i>mature</i>. A coinbase transaction is <i>mature</i> if it has been confirmed at least * {@link NetworkParameters#getSpendableCoinbaseDepth()} times. On {@link BitcoinNetwork#MAINNET} this value is {@code 100}. * For purposes of this method, non-coinbase transactions are also considered <i>mature</i>. * @param tx the transaction to evaluate * @return {@code true} if it is a mature coinbase transaction or if it is not a coinbase transaction */ public boolean isTransactionMature(Transaction tx) { return !tx.isCoinBase() || tx.getConfidence().getDepthInBlocks() >= params.getSpendableCoinbaseDepth(); } /** * Finds transactions in the specified candidates that double spend "tx". Not a general check, but it can work even if * the double spent inputs are not ours. * @return The set of transactions that double spend "tx". */ private Set<Transaction> findDoubleSpendsAgainst(Transaction tx, Map<Sha256Hash, Transaction> candidates) { checkState(lock.isHeldByCurrentThread()); if (tx.isCoinBase()) return new HashSet<>(); // Compile a set of outpoints that are spent by tx. HashSet<TransactionOutPoint> outpoints = new HashSet<>(); for (TransactionInput input : tx.getInputs()) { outpoints.add(input.getOutpoint()); } // Now for each pending transaction, see if it shares any outpoints with this tx. Set<Transaction> doubleSpendTxns = new HashSet<>(); for (Transaction p : candidates.values()) { if (p.equals(tx)) continue; for (TransactionInput input : p.getInputs()) { // This relies on the fact that TransactionOutPoint equality is defined at the protocol not object // level - outpoints from two different inputs that point to the same output compare the same. TransactionOutPoint outpoint = input.getOutpoint(); if (outpoints.contains(outpoint)) { // It does, it's a double spend against the candidates, which makes it relevant. doubleSpendTxns.add(p); } } } return doubleSpendTxns; } /** * Adds to txSet all the txns in txPool spending outputs of txns in txSet, * and all txns spending the outputs of those txns, recursively. */ void addTransactionsDependingOn(Set<Transaction> txSet, Set<Transaction> txPool) { Map<Sha256Hash, Transaction> txQueue = new LinkedHashMap<>(); for (Transaction tx : txSet) { txQueue.put(tx.getTxId(), tx); } while(!txQueue.isEmpty()) { Transaction tx = txQueue.remove(txQueue.keySet().iterator().next()); for (Transaction anotherTx : txPool) { if (anotherTx.equals(tx)) continue; for (TransactionInput input : anotherTx.getInputs()) { if (input.getOutpoint().hash().equals(tx.getTxId())) { if (txQueue.get(anotherTx.getTxId()) == null) { txQueue.put(anotherTx.getTxId(), anotherTx); txSet.add(anotherTx); } } } } } } /** * Called by the {@link BlockChain} when we receive a new block that sends coins to one of our addresses or * spends coins from one of our addresses (note that a single transaction can do both).<p> * * This is necessary for the internal book-keeping Wallet does. When a transaction is received that sends us * coins it is added to a pool so we can use it later to create spends. When a transaction is received that * consumes outputs they are marked as spent so they won't be used in future.<p> * * A transaction that spends our own coins can be received either because a spend we created was accepted by the * network and thus made it into a block, or because our keys are being shared between multiple instances and * some other node spent the coins instead. We still have to know about that to avoid accidentally trying to * double spend.<p> * * A transaction may be received multiple times if is included into blocks in parallel chains. The blockType * parameter describes whether the containing block is on the main/best chain or whether it's on a presently * inactive side chain. We must still record these transactions and the blocks they appear in because a future * block might change which chain is best causing a reorganize. A re-org can totally change our balance! */ @Override public void receiveFromBlock(Transaction tx, StoredBlock block, BlockChain.NewBlockType blockType, int relativityOffset) throws VerificationException { lock.lock(); try { if (!isTransactionRelevant(tx)) return; receive(tx, block, blockType, relativityOffset); } finally { lock.unlock(); } } // Whether to do a saveNow or saveLater when we are notified of the next best block. private boolean hardSaveOnNextBlock = false; private void receive(Transaction tx, StoredBlock block, BlockChain.NewBlockType blockType, int relativityOffset) throws VerificationException { // Runs in a peer thread. checkState(lock.isHeldByCurrentThread()); Coin prevBalance = getBalance(); Sha256Hash txHash = tx.getTxId(); boolean bestChain = blockType == BlockChain.NewBlockType.BEST_CHAIN; boolean sideChain = blockType == BlockChain.NewBlockType.SIDE_CHAIN; Coin valueSentFromMe = tx.getValueSentFromMe(this); Coin valueSentToMe = tx.getValueSentToMe(this); Coin valueDifference = valueSentToMe.subtract(valueSentFromMe); log.info("Received tx{} for {}: {} [{}] in block {}", sideChain ? " on a side chain" : "", valueDifference.toFriendlyString(), tx.getTxId(), relativityOffset, block != null ? block.getHeader().getHash() : "(unit test)"); // Inform the key chains that the issued keys were observed in a transaction, so they know to // calculate more keys for the next Bloom filters. markKeysAsUsed(tx); onWalletChangedSuppressions++; // If this transaction is already in the wallet we may need to move it into a different pool. At the very // least we need to ensure we're manipulating the canonical object rather than a duplicate. { Transaction tmp = transactions.get(tx.getTxId()); if (tmp != null) tx = tmp; } boolean wasPending = pending.remove(txHash) != null; if (wasPending) log.info(" <-pending"); if (bestChain) { boolean wasDead = dead.remove(txHash) != null; if (wasDead) log.info(" <-dead"); if (wasPending) { // Was pending and is now confirmed. Disconnect the outputs in case we spent any already: they will be // re-connected by processTxFromBestChain below. for (TransactionOutput output : tx.getOutputs()) { final TransactionInput spentBy = output.getSpentBy(); if (spentBy != null) { checkState(myUnspents.add(output)); spentBy.disconnect(); } } } processTxFromBestChain(tx, wasPending || wasDead); } else { checkState(sideChain); // Transactions that appear in a side chain will have that appearance recorded below - we assume that // some miners are also trying to include the transaction into the current best chain too, so let's treat // it as pending, except we don't need to do any risk analysis on it. if (wasPending) { // Just put it back in without touching the connections or confidence. addWalletTransaction(Pool.PENDING, tx); log.info(" ->pending"); } else { // Ignore the case where a tx appears on a side chain at the same time as the best chain (this is // quite normal and expected). Sha256Hash hash = tx.getTxId(); if (!unspent.containsKey(hash) && !spent.containsKey(hash) && !dead.containsKey(hash)) { // Otherwise put it (possibly back) into pending. // Committing it updates the spent flags and inserts into the pool as well. commitTx(tx); } } } if (block != null) { // Mark the tx as appearing in this block so we can find it later after a re-org. This also tells the tx // confidence object about the block and sets its depth appropriately. tx.setBlockAppearance(block, bestChain, relativityOffset); if (bestChain) { // Don't notify this tx of work done in notifyNewBestBlock which will be called immediately after // this method has been called by BlockChain for all relevant transactions. Otherwise we'd double // count. ignoreNextNewBlock.add(txHash); // When a tx is received from the best chain, if other txns that spend this tx are IN_CONFLICT, // change its confidence to PENDING (Unless they are also spending other txns IN_CONFLICT). // Consider dependency chains. Set<Transaction> currentTxDependencies = new HashSet<>(); currentTxDependencies.add(tx); addTransactionsDependingOn(currentTxDependencies, getTransactions(true)); currentTxDependencies.remove(tx); List<Transaction> currentTxDependenciesSorted = sortTxnsByDependency(currentTxDependencies); for (Transaction txDependency : currentTxDependenciesSorted) { if (txDependency.getConfidence().getConfidenceType().equals(ConfidenceType.IN_CONFLICT)) { if (isNotSpendingTxnsInConfidenceType(txDependency, ConfidenceType.IN_CONFLICT)) { txDependency.getConfidence().setConfidenceType(ConfidenceType.PENDING); confidenceChanged.put(txDependency, TransactionConfidence.Listener.ChangeReason.TYPE); } } } } } onWalletChangedSuppressions--; // Side chains don't affect confidence. if (bestChain) { // notifyNewBestBlock will be invoked next and will then call maybeQueueOnWalletChanged for us. confidenceChanged.put(tx, TransactionConfidence.Listener.ChangeReason.TYPE); } else { maybeQueueOnWalletChanged(); } // Inform anyone interested that we have received or sent coins but only if: // - This is not due to a re-org. // - The coins appeared on the best chain. // - We did in fact receive some new money. // - We have not already informed the user about the coins when we received the tx broadcast, or for our // own spends. If users want to know when a broadcast tx becomes confirmed, they need to use tx confidence // listeners. if (!insideReorg && bestChain) { Coin newBalance = getBalance(); // This is slow. log.info("Balance is now: " + newBalance.toFriendlyString()); if (!wasPending) { int diff = valueDifference.signum(); // We pick one callback based on the value difference, though a tx can of course both send and receive // coins from the wallet. if (diff > 0) { queueOnCoinsReceived(tx, prevBalance, newBalance); } else if (diff < 0) { queueOnCoinsSent(tx, prevBalance, newBalance); } } checkBalanceFuturesLocked(); } informConfidenceListenersIfNotReorganizing(); isConsistentOrThrow(); // Optimization for the case where a block has tons of relevant transactions. saveLater(); hardSaveOnNextBlock = true; } /** Finds if tx is NOT spending other txns which are in the specified confidence type */ private boolean isNotSpendingTxnsInConfidenceType(Transaction tx, ConfidenceType confidenceType) { for (TransactionInput txInput : tx.getInputs()) { Transaction connectedTx = this.getTransaction(txInput.getOutpoint().hash()); if (connectedTx != null && connectedTx.getConfidence().getConfidenceType().equals(confidenceType)) { return false; } } return true; } /** * Creates and returns a new List with the same txns as inputSet * but txns are sorted by depencency (a topological sort). * If tx B spends tx A, then tx A should be before tx B on the returned List. * Several invocations to this method with the same inputSet could result in lists with txns in different order, * as there is no guarantee on the order of the returned txns besides what was already stated. */ List<Transaction> sortTxnsByDependency(Set<Transaction> inputSet) { List<Transaction> result = new ArrayList<>(inputSet); for (int i = 0; i < result.size()-1; i++) { boolean txAtISpendsOtherTxInTheList; do { txAtISpendsOtherTxInTheList = false; for (int j = i+1; j < result.size(); j++) { if (spends(result.get(i), result.get(j))) { Transaction transactionAtI = result.remove(i); result.add(j, transactionAtI); txAtISpendsOtherTxInTheList = true; break; } } } while (txAtISpendsOtherTxInTheList); } return result; } /** Finds whether txA spends txB */ boolean spends(Transaction txA, Transaction txB) { for (TransactionInput txInput : txA.getInputs()) { if (txInput.getOutpoint().hash().equals(txB.getTxId())) { return true; } } return false; } private void informConfidenceListenersIfNotReorganizing() { if (insideReorg) return; for (Map.Entry<Transaction, TransactionConfidence.Listener.ChangeReason> entry : confidenceChanged.entrySet()) { final Transaction tx = entry.getKey(); tx.getConfidence().queueListeners(entry.getValue()); queueOnTransactionConfidenceChanged(tx); } confidenceChanged.clear(); } /** * <p>Called by the {@link BlockChain} when a new block on the best chain is seen, AFTER relevant wallet * transactions are extracted and sent to us UNLESS the new block caused a re-org, in which case this will * not be called (the {@link Wallet#reorganize(StoredBlock, List, List)} method will * call this one in that case).</p> * <p>Used to update confidence data in each transaction and last seen block hash. Triggers auto saving. * Invokes the onWalletChanged event listener if there were any affected transactions.</p> */ @Override public void notifyNewBestBlock(StoredBlock block) throws VerificationException { // Check to see if this block has been seen before. Sha256Hash newBlockHash = block.getHeader().getHash(); if (newBlockHash.equals(getLastBlockSeenHash())) return; lock.lock(); try { // Store the new block hash. setLastBlockSeenHash(newBlockHash); setLastBlockSeenHeight(block.getHeight()); setLastBlockSeenTime(block.getHeader().time()); // Notify all the BUILDING transactions of the new block. // This is so that they can update their depth. Set<Transaction> transactions = getTransactions(true); for (Transaction tx : transactions) { if (ignoreNextNewBlock.contains(tx.getTxId())) { // tx was already processed in receive() due to it appearing in this block, so we don't want to // increment the tx confidence depth twice, it'd result in miscounting. ignoreNextNewBlock.remove(tx.getTxId()); } else { TransactionConfidence confidence = tx.getConfidence(); if (confidence.getConfidenceType() == ConfidenceType.BUILDING) { // Erase the set of seen peers once the tx is so deep that it seems unlikely to ever go // pending again. We could clear this data the moment a tx is seen in the block chain, but // in cases where the chain re-orgs, this would mean that wallets would perceive a newly // pending tx has zero confidence at all, which would not be right: we expect it to be // included once again. We could have a separate was-in-chain-and-now-isn't confidence type // but this way is backwards compatible with existing software, and the new state probably // wouldn't mean anything different to just remembering peers anyway. if (confidence.incrementDepthInBlocks() > Context.getOrCreate().getEventHorizon()) confidence.clearBroadcastBy(); confidenceChanged.put(tx, TransactionConfidence.Listener.ChangeReason.DEPTH); } } } informConfidenceListenersIfNotReorganizing(); maybeQueueOnWalletChanged(); if (hardSaveOnNextBlock) { saveNow(); hardSaveOnNextBlock = false; } else { // Coalesce writes to avoid throttling on disk access when catching up with the chain. saveLater(); } } finally { lock.unlock(); } } /** * Handle when a transaction becomes newly active on the best chain, either due to receiving a new block or a * re-org. Places the tx into the right pool, handles coinbase transactions, handles double-spends and so on. */ private void processTxFromBestChain(Transaction tx, boolean forceAddToPool) throws VerificationException { checkState(lock.isHeldByCurrentThread()); checkState(!pending.containsKey(tx.getTxId())); // This TX may spend our existing outputs even though it was not pending. This can happen in unit // tests, if keys are moved between wallets, if we're catching up to the chain given only a set of keys, // or if a dead coinbase transaction has moved back onto the best chain. boolean isDeadCoinbase = tx.isCoinBase() && dead.containsKey(tx.getTxId()); if (isDeadCoinbase) { // There is a dead coinbase tx being received on the best chain. A coinbase tx is made dead when it moves // to a side chain but it can be switched back on a reorg and resurrected back to spent or unspent. // So take it out of the dead pool. Note that we don't resurrect dependent transactions here, even though // we could. Bitcoin Core nodes on the network have deleted the dependent transactions from their mempools // entirely by this point. We could and maybe should rebroadcast them so the network remembers and tries // to confirm them again. But this is a deeply unusual edge case that due to the maturity rule should never // happen in practice, thus for simplicities sake we ignore it here. log.info(" coinbase tx <-dead: confidence {}", tx.getTxId(), tx.getConfidence().getConfidenceType().name()); dead.remove(tx.getTxId()); } // Update tx and other unspent/pending transactions by connecting inputs/outputs. updateForSpends(tx, true); // Now make sure it ends up in the right pool. Also, handle the case where this TX is double-spending // against our pending transactions. Note that a tx may double spend our pending transactions and also send // us money/spend our money. boolean hasOutputsToMe = tx.getValueSentToMe(this).signum() > 0; boolean hasOutputsFromMe = false; if (hasOutputsToMe) { // Needs to go into either unspent or spent (if the outputs were already spent by a pending tx). if (tx.isEveryOwnedOutputSpent(this)) { log.info(" tx {} ->spent (by pending)", tx.getTxId()); addWalletTransaction(Pool.SPENT, tx); } else { log.info(" tx {} ->unspent", tx.getTxId()); addWalletTransaction(Pool.UNSPENT, tx); } } else if (tx.getValueSentFromMe(this).signum() > 0) { hasOutputsFromMe = true; // Didn't send us any money, but did spend some. Keep it around for record keeping purposes. log.info(" tx {} ->spent", tx.getTxId()); addWalletTransaction(Pool.SPENT, tx); } else if (forceAddToPool) { // Was manually added to pending, so we should keep it to notify the user of confidence information log.info(" tx {} ->spent (manually added)", tx.getTxId()); addWalletTransaction(Pool.SPENT, tx); } // Kill txns in conflict with this tx Set<Transaction> doubleSpendTxns = findDoubleSpendsAgainst(tx, pending); if (!doubleSpendTxns.isEmpty()) { // no need to addTransactionsDependingOn(doubleSpendTxns) because killTxns() already kills dependencies; killTxns(doubleSpendTxns, tx); } if (!hasOutputsToMe && !hasOutputsFromMe && !forceAddToPool && !findDoubleSpendsAgainst(tx, transactions).isEmpty()) { // disconnect irrelevant inputs (otherwise might cause protobuf serialization issue) for (TransactionInput input : tx.getInputs()) { TransactionOutput output = input.getConnectedOutput(); if (output != null && !output.isMineOrWatched(this)) { input.disconnect(); } } } } /** * <p>Updates the wallet by checking if this TX spends any of our outputs, and marking them as spent if so. If * fromChain is true, also checks to see if any pending transaction spends outputs of this transaction and marks * the spent flags appropriately.</p> * * <p>It can be called in two contexts. One is when we receive a transaction on the best chain but it wasn't pending, * this most commonly happens when we have a set of keys but the wallet transactions were wiped and we are catching * up with the block chain. It can also happen if a block includes a transaction we never saw at broadcast time. * If this tx double spends, it takes precedence over our pending transactions and the pending tx goes dead.</p> * * <p>The other context it can be called is from {@link Wallet#receivePending(Transaction, List)}, * ie we saw a tx be broadcast or one was submitted directly that spends our own coins. If this tx double spends * it does NOT take precedence because the winner will be resolved by the miners - we assume that our version will * win, if we are wrong then when a block appears the tx will go dead.</p> * * @param tx The transaction which is being updated. * @param fromChain If true, the tx appeared on the current best chain, if false it was pending. */ private void updateForSpends(Transaction tx, boolean fromChain) throws VerificationException { checkState(lock.isHeldByCurrentThread()); if (fromChain) checkState(!pending.containsKey(tx.getTxId())); for (TransactionInput input : tx.getInputs()) { TransactionInput.ConnectionResult result = input.connect(unspent, TransactionInput.ConnectMode.ABORT_ON_CONFLICT); if (result == TransactionInput.ConnectionResult.NO_SUCH_TX) { // Not found in the unspent map. Try again with the spent map. result = input.connect(spent, TransactionInput.ConnectMode.ABORT_ON_CONFLICT); if (result == TransactionInput.ConnectionResult.NO_SUCH_TX) { // Not found in the unspent and spent maps. Try again with the pending map. result = input.connect(pending, TransactionInput.ConnectMode.ABORT_ON_CONFLICT); if (result == TransactionInput.ConnectionResult.NO_SUCH_TX) { // Doesn't spend any of our outputs or is coinbase. continue; } } } TransactionOutput output = Objects.requireNonNull(input.getConnectedOutput()); if (result == TransactionInput.ConnectionResult.ALREADY_SPENT) { if (fromChain) { // Can be: // (1) We already marked this output as spent when we saw the pending transaction (most likely). // Now it's being confirmed of course, we cannot mark it as spent again. // (2) A double spend from chain: this will be handled later by findDoubleSpendsAgainst()/killTxns(). // // In any case, nothing to do here. } else { // We saw two pending transactions that double spend each other. We don't know which will win. // This can happen in the case of bad network nodes that mutate transactions. Do a hex dump // so the exact nature of the mutation can be examined. log.warn("Saw two pending transactions double spend each other"); log.warn(" offending input is input {}", tx.getInputs().indexOf(input)); log.warn("{}: {}", tx.getTxId(), ByteUtils.formatHex(tx.serialize())); Transaction other = output.getSpentBy().getParentTransaction(); log.warn("{}: {}", other.getTxId(), ByteUtils.formatHex(other.serialize())); } } else if (result == TransactionInput.ConnectionResult.SUCCESS) { // Otherwise we saw a transaction spend our coins, but we didn't try and spend them ourselves yet. // The outputs are already marked as spent by the connect call above, so check if there are any more for // us to use. Move if not. Transaction connected = Objects.requireNonNull(input.getConnectedTransaction()); log.info(" marked {} as spent by {}", input.getOutpoint(), tx.getTxId()); maybeMovePool(connected, "prevtx"); // Just because it's connected doesn't mean it's actually ours: sometimes we have total visibility. if (output.isMineOrWatched(this)) { checkState(myUnspents.remove(output)); } } } // Now check each output and see if there is a pending transaction which spends it. This shouldn't normally // ever occur because we expect transactions to arrive in temporal order, but this assumption can be violated // when we receive a pending transaction from the mempool that is relevant to us, which spends coins that we // didn't see arrive on the best chain yet. For instance, because of a chain replay or because of our keys were // used by another wallet somewhere else. Also, unconfirmed transactions can arrive from the mempool in more or // less random order. for (Transaction pendingTx : pending.values()) { for (TransactionInput input : pendingTx.getInputs()) { TransactionInput.ConnectionResult result = input.connect(tx, TransactionInput.ConnectMode.ABORT_ON_CONFLICT); if (fromChain) { // This TX is supposed to have just appeared on the best chain, so its outputs should not be marked // as spent yet. If they are, it means something is happening out of order. checkState(result != TransactionInput.ConnectionResult.ALREADY_SPENT); } if (result == TransactionInput.ConnectionResult.SUCCESS) { log.info("Connected pending tx input {}:{}", pendingTx.getTxId(), pendingTx.getInputs().indexOf(input)); // The unspents map might not have it if we never saw this tx until it was included in the chain // and thus becomes spent the moment we become aware of it. if (myUnspents.remove(input.getConnectedOutput())) log.info("Removed from UNSPENTS: {}", input.getConnectedOutput()); } } } if (!fromChain) { maybeMovePool(tx, "pendingtx"); } else { // If the transactions outputs are now all spent, it will be moved into the spent pool by the // processTxFromBestChain method. } } // Updates the wallet when a double spend occurs. overridingTx can be null for the case of coinbases private void killTxns(Set<Transaction> txnsToKill, @Nullable Transaction overridingTx) { LinkedList<Transaction> work = new LinkedList<>(txnsToKill); while (!work.isEmpty()) { final Transaction tx = work.poll(); log.warn("TX {} killed{}", tx.getTxId(), overridingTx != null ? " by " + overridingTx.getTxId() : ""); log.warn("Disconnecting each input and moving connected transactions."); // TX could be pending (finney attack), or in unspent/spent (coinbase killed by reorg). pending.remove(tx.getTxId()); unspent.remove(tx.getTxId()); spent.remove(tx.getTxId()); addWalletTransaction(Pool.DEAD, tx); for (TransactionInput deadInput : tx.getInputs()) { Transaction connected = deadInput.getConnectedTransaction(); if (connected == null) continue; if (connected.getConfidence().getConfidenceType() != ConfidenceType.DEAD && deadInput.getConnectedOutput().getSpentBy() != null && deadInput.getConnectedOutput().getSpentBy().equals(deadInput)) { checkState(myUnspents.add(deadInput.getConnectedOutput())); log.info("Added to UNSPENTS: {} in {}", deadInput.getConnectedOutput(), deadInput.getConnectedOutput().getParentTransaction().getTxId()); } deadInput.disconnect(); maybeMovePool(connected, "kill"); } tx.getConfidence().setOverridingTransaction(overridingTx); confidenceChanged.put(tx, TransactionConfidence.Listener.ChangeReason.TYPE); // Now kill any transactions we have that depended on this one. for (TransactionOutput deadOutput : tx.getOutputs()) { if (myUnspents.remove(deadOutput)) log.info("XX Removed from UNSPENTS: {}", deadOutput); TransactionInput connected = deadOutput.getSpentBy(); if (connected == null) continue; final Transaction parentTransaction = connected.getParentTransaction(); log.info("This death invalidated dependent tx {}", parentTransaction.getTxId()); work.push(parentTransaction); } } if (overridingTx == null) return; log.warn("Now attempting to connect the inputs of the overriding transaction."); for (TransactionInput input : overridingTx.getInputs()) { TransactionInput.ConnectionResult result = input.connect(unspent, TransactionInput.ConnectMode.DISCONNECT_ON_CONFLICT); if (result == TransactionInput.ConnectionResult.SUCCESS) { maybeMovePool(input.getConnectedTransaction(), "kill"); myUnspents.remove(input.getConnectedOutput()); log.info("Removing from UNSPENTS: {}", input.getConnectedOutput()); } else { result = input.connect(spent, TransactionInput.ConnectMode.DISCONNECT_ON_CONFLICT); if (result == TransactionInput.ConnectionResult.SUCCESS) { maybeMovePool(input.getConnectedTransaction(), "kill"); myUnspents.remove(input.getConnectedOutput()); log.info("Removing from UNSPENTS: {}", input.getConnectedOutput()); } } } } /** * If the transactions outputs are all marked as spent, and it's in the unspent map, move it. * If the owned transactions outputs are not all marked as spent, and it's in the spent map, move it. */ private void maybeMovePool(Transaction tx, String context) { checkState(lock.isHeldByCurrentThread()); if (tx.isEveryOwnedOutputSpent(this)) { // There's nothing left I can spend in this transaction. if (unspent.remove(tx.getTxId()) != null) { if (log.isInfoEnabled()) { log.info(" {} {} <-unspent ->spent", tx.getTxId(), context); } spent.put(tx.getTxId(), tx); } } else { if (spent.remove(tx.getTxId()) != null) { if (log.isInfoEnabled()) { log.info(" {} {} <-spent ->unspent", tx.getTxId(), context); } unspent.put(tx.getTxId(), tx); } } } /** * Updates the wallet with the given transaction: puts it into the pending pool, sets the spent flags and runs * the onCoinsSent/onCoinsReceived event listener. * <p> * Triggers an auto save (if enabled.) * <p> * Unlike {@link Wallet#commitTx} this method does not throw an exception if the transaction * was already added to the wallet, instead it will return {@code false} * * @param tx transaction to commit * @return true if the tx was added to the wallet, or false if it was already in the pending pool * @throws VerificationException If transaction fails to verify */ public boolean maybeCommitTx(Transaction tx) throws VerificationException { Transaction.verify(network, tx); lock.lock(); try { if (pending.containsKey(tx.getTxId())) return false; log.info("commitTx of {}", tx.getTxId()); Coin balance = getBalance(); tx.setUpdateTime(TimeUtils.currentTime()); // Put any outputs that are sending money back to us into the unspents map, and calculate their total value. Coin valueSentToMe = Coin.ZERO; for (TransactionOutput o : tx.getOutputs()) { if (!o.isMineOrWatched(this)) continue; valueSentToMe = valueSentToMe.add(o.getValue()); } // Mark the outputs we're spending as spent so we won't try and use them in future creations. This will also // move any transactions that are now fully spent to the spent map so we can skip them when creating future // spends. updateForSpends(tx, false); Set<Transaction> doubleSpendPendingTxns = findDoubleSpendsAgainst(tx, pending); Set<Transaction> doubleSpendUnspentTxns = findDoubleSpendsAgainst(tx, unspent); Set<Transaction> doubleSpendSpentTxns = findDoubleSpendsAgainst(tx, spent); if (!doubleSpendUnspentTxns.isEmpty() || !doubleSpendSpentTxns.isEmpty() || !isNotSpendingTxnsInConfidenceType(tx, ConfidenceType.DEAD)) { // tx is a double spend against a tx already in the best chain or spends outputs of a DEAD tx. // Add tx to the dead pool and schedule confidence listener notifications. log.info("->dead: {}", tx.getTxId()); tx.getConfidence().setConfidenceType(ConfidenceType.DEAD); confidenceChanged.put(tx, TransactionConfidence.Listener.ChangeReason.TYPE); addWalletTransaction(Pool.DEAD, tx); } else if (!doubleSpendPendingTxns.isEmpty() || !isNotSpendingTxnsInConfidenceType(tx, ConfidenceType.IN_CONFLICT)) { // tx is a double spend against a pending tx or spends outputs of a tx already IN_CONFLICT. // Add tx to the pending pool. Update the confidence type of tx, the txns in conflict with tx and all // their dependencies to IN_CONFLICT and schedule confidence listener notifications. log.info("->pending (IN_CONFLICT): {}", tx.getTxId()); addWalletTransaction(Pool.PENDING, tx); doubleSpendPendingTxns.add(tx); addTransactionsDependingOn(doubleSpendPendingTxns, getTransactions(true)); for (Transaction doubleSpendTx : doubleSpendPendingTxns) { doubleSpendTx.getConfidence().setConfidenceType(ConfidenceType.IN_CONFLICT); confidenceChanged.put(doubleSpendTx, TransactionConfidence.Listener.ChangeReason.TYPE); } } else { // No conflict detected. // Add to the pending pool and schedule confidence listener notifications. log.info("->pending: {}", tx.getTxId()); tx.getConfidence().setConfidenceType(ConfidenceType.PENDING); confidenceChanged.put(tx, TransactionConfidence.Listener.ChangeReason.TYPE); addWalletTransaction(Pool.PENDING, tx); } if (log.isInfoEnabled()) log.info("Estimated balance is now: {}", getBalance(BalanceType.ESTIMATED).toFriendlyString()); // Mark any keys used in the outputs as "used", this allows wallet UI's to auto-advance the current key // they are showing to the user in qr codes etc. markKeysAsUsed(tx); try { Coin valueSentFromMe = tx.getValueSentFromMe(this); Coin newBalance = balance.add(valueSentToMe).subtract(valueSentFromMe); if (valueSentToMe.signum() > 0) { checkBalanceFuturesLocked(); queueOnCoinsReceived(tx, balance, newBalance); } if (valueSentFromMe.signum() > 0) queueOnCoinsSent(tx, balance, newBalance); maybeQueueOnWalletChanged(); } catch (ScriptException e) { // Cannot happen as we just created this transaction ourselves. throw new RuntimeException(e); } isConsistentOrThrow(); informConfidenceListenersIfNotReorganizing(); saveNow(); } finally { lock.unlock(); } return true; } /** * Updates the wallet with the given transaction: puts it into the pending pool, sets the spent flags and runs * the onCoinsSent/onCoinsReceived event listener. Used in two situations: * <ol> * <li>When we have just successfully transmitted the tx we created to the network.</li> * <li>When we receive a pending transaction that didn't appear in the chain yet, and we did not create it.</li> * </ol> * Triggers an auto save (if enabled.) * <p> * Unlike {@link Wallet#maybeCommitTx} {@code commitTx} throws an exception if the transaction * was already added to the wallet. * * @param tx transaction to commit * @throws VerificationException if transaction was already in the pending pool */ public void commitTx(Transaction tx) throws VerificationException { checkArgument(maybeCommitTx(tx), () -> "commitTx called on the same transaction twice"); } //endregion // *************************************************************************************************************** //region Event listeners /** * Adds an event listener object. Methods on this object are called when something interesting happens, * like receiving money. Runs the listener methods in the user thread. */ public void addChangeEventListener(WalletChangeEventListener listener) { addChangeEventListener(Threading.USER_THREAD, listener); } /** * Adds an event listener object. Methods on this object are called when something interesting happens, * like receiving money. The listener is executed by the given executor. */ public void addChangeEventListener(Executor executor, WalletChangeEventListener listener) { // This is thread safe, so we don't need to take the lock. changeListeners.add(new ListenerRegistration<>(listener, executor)); } /** * Adds an event listener object called when coins are received. * Runs the listener methods in the user thread. */ public void addCoinsReceivedEventListener(WalletCoinsReceivedEventListener listener) { addCoinsReceivedEventListener(Threading.USER_THREAD, listener); } /** * Adds an event listener object called when coins are received. * The listener is executed by the given executor. */ public void addCoinsReceivedEventListener(Executor executor, WalletCoinsReceivedEventListener listener) { // This is thread safe, so we don't need to take the lock. coinsReceivedListeners.add(new ListenerRegistration<>(listener, executor)); } /** * Adds an event listener object called when coins are sent. * Runs the listener methods in the user thread. */ public void addCoinsSentEventListener(WalletCoinsSentEventListener listener) { addCoinsSentEventListener(Threading.USER_THREAD, listener); } /** * Adds an event listener object called when coins are sent. * The listener is executed by the given executor. */ public void addCoinsSentEventListener(Executor executor, WalletCoinsSentEventListener listener) { // This is thread safe, so we don't need to take the lock. coinsSentListeners.add(new ListenerRegistration<>(listener, executor)); } /** * Adds an event listener object. Methods on this object are called when keys are * added. The listener is executed in the user thread. */ public void addKeyChainEventListener(KeyChainEventListener listener) { keyChainGroup.addEventListener(listener, Threading.USER_THREAD); } /** * Adds an event listener object. Methods on this object are called when keys are * added. The listener is executed by the given executor. */ public void addKeyChainEventListener(Executor executor, KeyChainEventListener listener) { keyChainGroup.addEventListener(listener, executor); } /** * Adds an event listener object. Methods on this object are called when a current key and/or address * changes. The listener is executed in the user thread. */ public void addCurrentKeyChangeEventListener(CurrentKeyChangeEventListener listener) { keyChainGroup.addCurrentKeyChangeEventListener(listener); } /** * Adds an event listener object. Methods on this object are called when a current key and/or address * changes. The listener is executed by the given executor. */ public void addCurrentKeyChangeEventListener(Executor executor, CurrentKeyChangeEventListener listener) { keyChainGroup.addCurrentKeyChangeEventListener(listener, executor); } /** * Adds an event listener object. Methods on this object are called when something interesting happens, * like receiving money. Runs the listener methods in the user thread. */ public void addReorganizeEventListener(WalletReorganizeEventListener listener) { addReorganizeEventListener(Threading.USER_THREAD, listener); } /** * Adds an event listener object. Methods on this object are called when something interesting happens, * like receiving money. The listener is executed by the given executor. */ public void addReorganizeEventListener(Executor executor, WalletReorganizeEventListener listener) { // This is thread safe, so we don't need to take the lock. reorganizeListeners.add(new ListenerRegistration<>(listener, executor)); } /** * Adds an event listener object. Methods on this object are called when scripts * watched by this wallet change. Runs the listener methods in the user thread. */ public void addScriptsChangeEventListener(ScriptsChangeEventListener listener) { addScriptsChangeEventListener(Threading.USER_THREAD, listener); } /** * Adds an event listener object. Methods on this object are called when scripts * watched by this wallet change. The listener is executed by the given executor. */ public void addScriptsChangeEventListener(Executor executor, ScriptsChangeEventListener listener) { // This is thread safe, so we don't need to take the lock. scriptsChangeListeners.add(new ListenerRegistration<>(listener, executor)); } /** * Adds an event listener object. Methods on this object are called when confidence * of a transaction changes. Runs the listener methods in the user thread. */ public void addTransactionConfidenceEventListener(TransactionConfidenceEventListener listener) { addTransactionConfidenceEventListener(Threading.USER_THREAD, listener); } /** * Adds an event listener object. Methods on this object are called when confidence * of a transaction changes. The listener is executed by the given executor. */ public void addTransactionConfidenceEventListener(Executor executor, TransactionConfidenceEventListener listener) { // This is thread safe, so we don't need to take the lock. transactionConfidenceListeners.add(new ListenerRegistration<>(listener, executor)); } /** * Removes the given event listener object. Returns true if the listener was removed, false if that listener * was never added. */ public boolean removeChangeEventListener(WalletChangeEventListener listener) { return ListenerRegistration.removeFromList(listener, changeListeners); } /** * Removes the given event listener object. Returns true if the listener was removed, false if that listener * was never added. */ public boolean removeCoinsReceivedEventListener(WalletCoinsReceivedEventListener listener) { return ListenerRegistration.removeFromList(listener, coinsReceivedListeners); } /** * Removes the given event listener object. Returns true if the listener was removed, false if that listener * was never added. */ public boolean removeCoinsSentEventListener(WalletCoinsSentEventListener listener) { return ListenerRegistration.removeFromList(listener, coinsSentListeners); } /** * Removes the given event listener object. Returns true if the listener was removed, false if that listener * was never added. */ public boolean removeKeyChainEventListener(KeyChainEventListener listener) { return keyChainGroup.removeEventListener(listener); } /** * Removes the given event listener object. Returns true if the listener was removed, false if that * listener was never added. */ public boolean removeCurrentKeyChangeEventListener(CurrentKeyChangeEventListener listener) { return keyChainGroup.removeCurrentKeyChangeEventListener(listener); } /** * Removes the given event listener object. Returns true if the listener was removed, false if that listener * was never added. */ public boolean removeReorganizeEventListener(WalletReorganizeEventListener listener) { return ListenerRegistration.removeFromList(listener, reorganizeListeners); } /** * Removes the given event listener object. Returns true if the listener was removed, false if that listener * was never added. */ public boolean removeScriptsChangeEventListener(ScriptsChangeEventListener listener) { return ListenerRegistration.removeFromList(listener, scriptsChangeListeners); } /** * Removes the given event listener object. Returns true if the listener was removed, false if that listener * was never added. */ public boolean removeTransactionConfidenceEventListener(TransactionConfidenceEventListener listener) { return ListenerRegistration.removeFromList(listener, transactionConfidenceListeners); } private void queueOnTransactionConfidenceChanged(final Transaction tx) { checkState(lock.isHeldByCurrentThread()); for (final ListenerRegistration<TransactionConfidenceEventListener> registration : transactionConfidenceListeners) { if (registration.executor == Threading.SAME_THREAD) { registration.listener.onTransactionConfidenceChanged(this, tx); } else { registration.executor.execute(() -> registration.listener.onTransactionConfidenceChanged(Wallet.this, tx)); } } } protected void maybeQueueOnWalletChanged() { // Don't invoke the callback in some circumstances, eg, whilst we are re-organizing or fiddling with // transactions due to a new block arriving. It will be called later instead. checkState(lock.isHeldByCurrentThread()); checkState(onWalletChangedSuppressions >= 0); if (onWalletChangedSuppressions > 0) return; for (final ListenerRegistration<WalletChangeEventListener> registration : changeListeners) { registration.executor.execute(() -> registration.listener.onWalletChanged(Wallet.this)); } } protected void queueOnCoinsReceived(final Transaction tx, final Coin balance, final Coin newBalance) { checkState(lock.isHeldByCurrentThread()); for (final ListenerRegistration<WalletCoinsReceivedEventListener> registration : coinsReceivedListeners) { registration.executor.execute(() -> registration.listener.onCoinsReceived(Wallet.this, tx, balance, newBalance)); } } protected void queueOnCoinsSent(final Transaction tx, final Coin prevBalance, final Coin newBalance) { checkState(lock.isHeldByCurrentThread()); for (final ListenerRegistration<WalletCoinsSentEventListener> registration : coinsSentListeners) { registration.executor.execute(() -> registration.listener.onCoinsSent(Wallet.this, tx, prevBalance, newBalance)); } } protected void queueOnReorganize() { checkState(lock.isHeldByCurrentThread()); checkState(insideReorg); for (final ListenerRegistration<WalletReorganizeEventListener> registration : reorganizeListeners) { registration.executor.execute(() -> registration.listener.onReorganize(Wallet.this)); } } protected void queueOnScriptsChanged(final List<Script> scripts, final boolean isAddingScripts) { for (final ListenerRegistration<ScriptsChangeEventListener> registration : scriptsChangeListeners) { registration.executor.execute(() -> registration.listener.onScriptsChanged(Wallet.this, scripts, isAddingScripts)); } } //endregion // *************************************************************************************************************** //region Vending transactions and other internal state /** * Returns a set of all transactions in the wallet. * @param includeDead If true, transactions that were overridden by a double spend are included. */ public Set<Transaction> getTransactions(boolean includeDead) { lock.lock(); try { Set<Transaction> all = new HashSet<>(); all.addAll(unspent.values()); all.addAll(spent.values()); all.addAll(pending.values()); if (includeDead) all.addAll(dead.values()); return all; } finally { lock.unlock(); } } /** * Returns a set of all WalletTransactions in the wallet. */ public Iterable<WalletTransaction> getWalletTransactions() { lock.lock(); try { Set<WalletTransaction> all = new HashSet<>(); addWalletTransactionsToSet(all, Pool.UNSPENT, unspent.values()); addWalletTransactionsToSet(all, Pool.SPENT, spent.values()); addWalletTransactionsToSet(all, Pool.DEAD, dead.values()); addWalletTransactionsToSet(all, Pool.PENDING, pending.values()); return all; } finally { lock.unlock(); } } private static void addWalletTransactionsToSet(Set<WalletTransaction> txns, Pool poolType, Collection<Transaction> pool) { for (Transaction tx : pool) { txns.add(new WalletTransaction(poolType, tx)); } } /** * Adds a transaction that has been associated with a particular wallet pool. This is intended for usage by * deserialization code, such as the {@link WalletProtobufSerializer} class. It isn't normally useful for * applications. It does not trigger auto saving. */ public void addWalletTransaction(WalletTransaction wtx) { lock.lock(); try { addWalletTransaction(wtx.getPool(), wtx.getTransaction()); } finally { lock.unlock(); } } /** * Adds the given transaction to the given pools and registers a confidence change listener on it. */ private void addWalletTransaction(Pool pool, Transaction tx) { checkState(lock.isHeldByCurrentThread()); transactions.put(tx.getTxId(), tx); switch (pool) { case UNSPENT: checkState(unspent.put(tx.getTxId(), tx) == null); break; case SPENT: checkState(spent.put(tx.getTxId(), tx) == null); break; case PENDING: checkState(pending.put(tx.getTxId(), tx) == null); break; case DEAD: checkState(dead.put(tx.getTxId(), tx) == null); break; default: throw new RuntimeException("Unknown wallet transaction type " + pool); } if (pool == Pool.UNSPENT || pool == Pool.PENDING) { for (TransactionOutput output : tx.getOutputs()) { if (output.isAvailableForSpending() && output.isMineOrWatched(this)) myUnspents.add(output); } } // This is safe even if the listener has been added before, as TransactionConfidence ignores duplicate // registration requests. That makes the code in the wallet simpler. tx.getConfidence().addEventListener(Threading.SAME_THREAD, txConfidenceListener); } /** * Returns all non-dead, active transactions ordered by recency. */ public List<Transaction> getTransactionsByTime() { return getRecentTransactions(0, false); } /** * <p>Returns an list of N transactions, ordered by increasing age. Transactions on side chains are not included. * Dead transactions (overridden by double spends) are optionally included.</p> * <p>Note: the current implementation is O(num transactions in wallet). Regardless of how many transactions are * requested, the cost is always the same. In future, requesting smaller numbers of transactions may be faster * depending on how the wallet is implemented (eg if backed by a database).</p> */ public List<Transaction> getRecentTransactions(int numTransactions, boolean includeDead) { lock.lock(); try { checkArgument(numTransactions >= 0); // Firstly, put all transactions into an array. int size = unspent.size() + spent.size() + pending.size(); if (numTransactions > size || numTransactions == 0) { numTransactions = size; } List<Transaction> all = new ArrayList<>(getTransactions(includeDead)); // Order by update time. Collections.sort(all, Transaction.SORT_TX_BY_UPDATE_TIME); if (numTransactions == all.size()) { return all; } else { all.subList(numTransactions, all.size()).clear(); return all; } } finally { lock.unlock(); } } /** * Returns a transaction object given its hash, if it exists in this wallet, or null otherwise. */ @Nullable public Transaction getTransaction(Sha256Hash hash) { lock.lock(); try { return transactions.get(hash); } finally { lock.unlock(); } } @Override public Map<Sha256Hash, Transaction> getTransactionPool(Pool pool) { lock.lock(); try { switch (pool) { case UNSPENT: return unspent; case SPENT: return spent; case PENDING: return pending; case DEAD: return dead; default: throw new RuntimeException("Unknown wallet transaction type " + pool); } } finally { lock.unlock(); } } /** * Prepares the wallet for a blockchain replay. Removes all transactions (as they would get in the way of the * replay) and makes the wallet think it has never seen a block. {@link WalletChangeEventListener#onWalletChanged} will * be fired. */ public void reset() { lock.lock(); try { clearTransactions(); lastBlockSeenHash = null; lastBlockSeenHeight = -1; // Magic value for 'never'. lastBlockSeenTime = null; saveLater(); maybeQueueOnWalletChanged(); } finally { lock.unlock(); } } /** * Deletes transactions which appeared above the given block height from the wallet, but does not touch the keys. * This is useful if you have some keys and wish to replay the block chain into the wallet in order to pick them up. * Triggers auto saving. */ public void clearTransactions(int fromHeight) { lock.lock(); try { if (fromHeight == 0) { clearTransactions(); saveLater(); } else { throw new UnsupportedOperationException(); } } finally { lock.unlock(); } } private void clearTransactions() { unspent.clear(); spent.clear(); pending.clear(); dead.clear(); transactions.clear(); myUnspents.clear(); } /** * Returns all the outputs that match addresses or scripts added via {@link #addWatchedAddress(Address)} or * {@link #addWatchedScripts(java.util.List)}. * @param excludeImmatureCoinbases Whether to ignore outputs that are unspendable due to being immature. */ public List<TransactionOutput> getWatchedOutputs(boolean excludeImmatureCoinbases) { lock.lock(); keyChainGroupLock.lock(); try { List<TransactionOutput> candidates = new LinkedList<>(); for (Transaction tx : Iterables.concat(unspent.values(), pending.values())) { if (excludeImmatureCoinbases && !isTransactionMature(tx)) continue; for (TransactionOutput output : tx.getOutputs()) { if (!output.isAvailableForSpending()) continue; try { Script scriptPubKey = output.getScriptPubKey(); if (!watchedScripts.contains(scriptPubKey)) continue; candidates.add(output); } catch (ScriptException e) { // Ignore } } } return candidates; } finally { keyChainGroupLock.unlock(); lock.unlock(); } } /** * Clean up the wallet. Currently, it only removes risky pending transaction from the wallet and only if their * outputs have not been spent. */ public void cleanup() { lock.lock(); try { boolean dirty = false; for (Iterator<Transaction> i = pending.values().iterator(); i.hasNext();) { Transaction tx = i.next(); if (isTransactionRisky(tx, null) && !acceptRiskyTransactions) { log.debug("Found risky transaction {} in wallet during cleanup.", tx.getTxId()); if (!tx.isAnyOutputSpent()) { // Sync myUnspents with the change. for (TransactionInput input : tx.getInputs()) { TransactionOutput output = input.getConnectedOutput(); if (output == null) continue; if (output.isMineOrWatched(this)) checkState(myUnspents.add(output)); input.disconnect(); } for (TransactionOutput output : tx.getOutputs()) myUnspents.remove(output); i.remove(); transactions.remove(tx.getTxId()); dirty = true; log.info("Removed transaction {} from pending pool during cleanup.", tx.getTxId()); } else { log.info( "Cannot remove transaction {} from pending pool during cleanup, as it's already spent partially.", tx.getTxId()); } } } if (dirty) { isConsistentOrThrow(); saveLater(); if (log.isInfoEnabled()) log.info("Estimated balance is now: {}", getBalance(BalanceType.ESTIMATED).toFriendlyString()); } } finally { lock.unlock(); } } EnumSet<Pool> getContainingPools(Transaction tx) { lock.lock(); try { EnumSet<Pool> result = EnumSet.noneOf(Pool.class); Sha256Hash txHash = tx.getTxId(); if (unspent.containsKey(txHash)) { result.add(Pool.UNSPENT); } if (spent.containsKey(txHash)) { result.add(Pool.SPENT); } if (pending.containsKey(txHash)) { result.add(Pool.PENDING); } if (dead.containsKey(txHash)) { result.add(Pool.DEAD); } return result; } finally { lock.unlock(); } } @VisibleForTesting public int getPoolSize(WalletTransaction.Pool pool) { lock.lock(); try { switch (pool) { case UNSPENT: return unspent.size(); case SPENT: return spent.size(); case PENDING: return pending.size(); case DEAD: return dead.size(); } throw new RuntimeException("Unreachable"); } finally { lock.unlock(); } } @VisibleForTesting public boolean poolContainsTxHash(final WalletTransaction.Pool pool, final Sha256Hash txHash) { lock.lock(); try { switch (pool) { case UNSPENT: return unspent.containsKey(txHash); case SPENT: return spent.containsKey(txHash); case PENDING: return pending.containsKey(txHash); case DEAD: return dead.containsKey(txHash); } throw new RuntimeException("Unreachable"); } finally { lock.unlock(); } } /** Returns a copy of the internal unspent outputs list */ public List<TransactionOutput> getUnspents() { lock.lock(); try { return new ArrayList<>(myUnspents); } finally { lock.unlock(); } } @Override public String toString() { return toString(false, false, null, true, true, null); } /** * Formats the wallet as a human-readable piece of text. Intended for debugging, the format is not meant to be * stable or human-readable. * @param includeLookahead Whether lookahead keys should be included. * @param includePrivateKeys Whether raw private key data should be included. * @param aesKey for decrypting private key data for if the wallet is encrypted. * @param includeTransactions Whether to print transaction data. * @param includeExtensions Whether to print extension data. * @param chain If set, will be used to estimate lock times for block time-locked transactions. * @return Human-readable wallet debugging information */ public String toString(boolean includeLookahead, boolean includePrivateKeys, @Nullable AesKey aesKey, boolean includeTransactions, boolean includeExtensions, @Nullable AbstractBlockChain chain) { lock.lock(); keyChainGroupLock.lock(); try { StringBuilder builder = new StringBuilder("Wallet\n"); if (includePrivateKeys) builder.append(" WARNING: includes private keys!\n"); builder.append("Balances:\n"); for (BalanceType balanceType : BalanceType.values()) builder.append(" ").append(getBalance(balanceType).toFriendlyString()).append(' ').append(balanceType) .append('\n'); builder.append("Transactions:\n"); builder.append(" ").append(pending.size()).append(" pending\n"); builder.append(" ").append(unspent.size()).append(" unspent\n"); builder.append(" ").append(spent.size()).append(" spent\n"); builder.append(" ").append(dead.size()).append(" dead\n"); builder.append("Last seen best block: ").append(getLastBlockSeenHeight()).append(" (") .append(lastBlockSeenTime() .map(instant -> TimeUtils.dateTimeFormat(instant)) .orElse("time unknown")) .append("): ").append(getLastBlockSeenHash()).append('\n'); final KeyCrypter crypter = keyChainGroup.getKeyCrypter(); if (crypter != null) builder.append("Encryption: ").append(crypter).append('\n'); if (isWatching()) builder.append("Wallet is watching.\n"); // Do the keys. builder.append("\nKeys:\n"); builder.append("Earliest creation time: ").append(TimeUtils.dateTimeFormat(earliestKeyCreationTime())) .append('\n'); final Optional<Instant> keyRotationTime = keyRotationTime(); if (keyRotationTime.isPresent()) builder.append("Key rotation time: ").append(TimeUtils.dateTimeFormat(keyRotationTime.get())).append('\n'); builder.append(keyChainGroup.toString(includeLookahead, includePrivateKeys, aesKey)); if (!watchedScripts.isEmpty()) { builder.append("\nWatched scripts:\n"); for (Script script : watchedScripts) { builder.append(" ").append(script).append("\n"); } } if (includeTransactions) { // Print the transactions themselves if (pending.size() > 0) { builder.append("\n>>> PENDING:\n"); toStringHelper(builder, pending, chain, Transaction.SORT_TX_BY_UPDATE_TIME); } if (unspent.size() > 0) { builder.append("\n>>> UNSPENT:\n"); toStringHelper(builder, unspent, chain, Transaction.SORT_TX_BY_HEIGHT); } if (spent.size() > 0) { builder.append("\n>>> SPENT:\n"); toStringHelper(builder, spent, chain, Transaction.SORT_TX_BY_HEIGHT); } if (dead.size() > 0) { builder.append("\n>>> DEAD:\n"); toStringHelper(builder, dead, chain, Transaction.SORT_TX_BY_UPDATE_TIME); } } if (includeExtensions && extensions.size() > 0) { builder.append("\n>>> EXTENSIONS:\n"); for (WalletExtension extension : extensions.values()) { builder.append(extension).append("\n\n"); } } return builder.toString(); } finally { keyChainGroupLock.unlock(); lock.unlock(); } } private void toStringHelper(StringBuilder builder, Map<Sha256Hash, Transaction> transactionMap, @Nullable AbstractBlockChain chain, @Nullable Comparator<Transaction> sortOrder) { checkState(lock.isHeldByCurrentThread()); final Collection<Transaction> txns; if (sortOrder != null) { txns = new TreeSet<>(sortOrder); txns.addAll(transactionMap.values()); } else { txns = transactionMap.values(); } for (Transaction tx : txns) { try { builder.append(tx.getValue(this).toFriendlyString()); builder.append(" total value (sends "); builder.append(tx.getValueSentFromMe(this).toFriendlyString()); builder.append(" and receives "); builder.append(tx.getValueSentToMe(this).toFriendlyString()); builder.append(")\n"); } catch (ScriptException e) { // Ignore and don't print this line. } if (tx.hasConfidence()) builder.append(" confidence: ").append(tx.getConfidence()).append('\n'); builder.append(tx.toString(chain, network(), " ")); } } /** * Returns an immutable view of the transactions currently waiting for network confirmations. */ public Collection<Transaction> getPendingTransactions() { lock.lock(); try { return Collections.unmodifiableCollection(pending.values()); } finally { lock.unlock(); } } /** * Returns the earliest creation time of keys or watched scripts in this wallet, ie the min * of {@link ECKey#creationTime()}. This can return {@link Instant#EPOCH} if at least one key does * not have that data (e.g. is an imported key with unknown timestamp). <p> * * This method is most often used in conjunction with {@link PeerGroup#setFastCatchupTime(Instant)} in order to * optimize chain download for new users of wallet apps. Backwards compatibility notice: if you get {@link Instant#EPOCH} from this * method, you can instead use the time of the first release of your software, as it's guaranteed no users will * have wallets pre-dating this time. <p> * * If there are no keys in the wallet, {@link Instant#MAX} is returned. * * @return earliest creation times of keys in this wallet, * {@link Instant#EPOCH} if at least one time is unknown, * {@link Instant#MAX} if no keys in this wallet */ @Override public Instant earliestKeyCreationTime() { keyChainGroupLock.lock(); try { Instant earliestTime = keyChainGroup.earliestKeyCreationTime(); for (Script script : watchedScripts) earliestTime = TimeUtils.earlier(script.creationTime().orElse(Instant.EPOCH), earliestTime); return earliestTime; } finally { keyChainGroupLock.unlock(); } } /** Returns the hash of the last seen best-chain block, or null if the wallet is too old to store this data. */ @Nullable public Sha256Hash getLastBlockSeenHash() { lock.lock(); try { return lastBlockSeenHash; } finally { lock.unlock(); } } public void setLastBlockSeenHash(@Nullable Sha256Hash lastBlockSeenHash) { lock.lock(); try { this.lastBlockSeenHash = lastBlockSeenHash; } finally { lock.unlock(); } } public void setLastBlockSeenHeight(int lastBlockSeenHeight) { lock.lock(); try { this.lastBlockSeenHeight = lastBlockSeenHeight; } finally { lock.unlock(); } } public void setLastBlockSeenTime(Instant time) { lock.lock(); try { lastBlockSeenTime = Objects.requireNonNull(time); } finally { lock.unlock(); } } public void clearLastBlockSeenTime() { lock.lock(); try { lastBlockSeenTime = null; } finally { lock.unlock(); } } /** @deprecated use {@link #setLastBlockSeenTime(Instant)} or {@link #clearLastBlockSeenTime()} */ @Deprecated public void setLastBlockSeenTimeSecs(long timeSecs) { checkArgument(timeSecs > 0); setLastBlockSeenTime(Instant.ofEpochSecond(timeSecs)); } /** * Returns time extracted from the last best seen block header, or empty. This timestamp * is <b>not</b> the local time at which the block was first observed by this application but rather what the block * (i.e. miner) self declares. It is allowed to have some significant drift from the real time at which the block * was found, although most miners do use accurate times. If this wallet is old and does not have a recorded * time then this method returns zero. */ public Optional<Instant> lastBlockSeenTime() { lock.lock(); try { return Optional.ofNullable(lastBlockSeenTime); } finally { lock.unlock(); } } /** @deprecated use {@link #lastBlockSeenTime()} */ @Deprecated public long getLastBlockSeenTimeSecs() { return lastBlockSeenTime().map(Instant::getEpochSecond).orElse((long) 0); } /** @deprecated use {@link #lastBlockSeenTime()} */ @Deprecated @Nullable public Date getLastBlockSeenTime() { return lastBlockSeenTime().map(Date::from).orElse(null); } /** * Returns the height of the last seen best-chain block. Can be 0 if a wallet is brand new or -1 if the wallet * is old and doesn't have that data. */ public int getLastBlockSeenHeight() { lock.lock(); try { return lastBlockSeenHeight; } finally { lock.unlock(); } } /** * Get the version of the Wallet. * This is an int you can use to indicate which versions of wallets your code understands, * and which come from the future (and hence cannot be safely loaded). */ public int getVersion() { return version; } /** * Set the version number of the wallet. See {@link Wallet#getVersion()}. */ public void setVersion(int version) { this.version = version; } /** * Set the description of the wallet. * This is a Unicode encoding string typically entered by the user as descriptive text for the wallet. */ public void setDescription(String description) { this.description = description; } /** * Get the description of the wallet. See {@link Wallet#setDescription(String)} */ public String getDescription() { return description; } //endregion // *************************************************************************************************************** //region Balance and balance futures /** * <p>It's possible to calculate a wallets balance from multiple points of view. This enum selects which * {@link #getBalance(BalanceType)} should use.</p> * * <p>Consider a real-world example: you buy a snack costing $5 but you only have a $10 bill. At the start you have * $10 viewed from every possible angle. After you order the snack you hand over your $10 bill. From the * perspective of your wallet you have zero dollars (AVAILABLE). But you know in a few seconds the shopkeeper * will give you back $5 change so most people in practice would say they have $5 (ESTIMATED).</p> * * <p>The fact that the wallet can track transactions which are not spendable by itself ("watching wallets") adds * another type of balance to the mix. Although the wallet won't do this by default, advanced use cases that * override the relevancy checks can end up with a mix of spendable and unspendable transactions.</p> */ public enum BalanceType { /** * Balance calculated assuming all pending transactions are in fact included into the best chain by miners. * This includes the value of immature coinbase transactions. */ ESTIMATED, /** * Balance that could be safely used to create new spends, if we had all the needed private keys. This is * whatever the default coin selector would make available, which by default means transaction outputs with at * least 1 confirmation and pending transactions created by our own wallet which have been propagated across * the network. Whether we <i>actually</i> have the private keys or not is irrelevant for this balance type. */ AVAILABLE, /** Same as ESTIMATED but only for outputs we have the private keys for and can sign ourselves. */ ESTIMATED_SPENDABLE, /** Same as AVAILABLE but only for outputs we have the private keys for and can sign ourselves. */ AVAILABLE_SPENDABLE } /** * Returns the AVAILABLE balance of this wallet. See {@link BalanceType#AVAILABLE} for details on what this * means. */ public Coin getBalance() { return getBalance(BalanceType.AVAILABLE); } /** * Returns the balance of this wallet as calculated by the provided balanceType. */ public Coin getBalance(BalanceType balanceType) { lock.lock(); try { if (balanceType == BalanceType.AVAILABLE || balanceType == BalanceType.AVAILABLE_SPENDABLE) { List<TransactionOutput> candidates = calculateAllSpendCandidates(true, balanceType == BalanceType.AVAILABLE_SPENDABLE); CoinSelection selection = coinSelector.select(BitcoinNetwork.MAX_MONEY, candidates); return selection.totalValue(); } else if (balanceType == BalanceType.ESTIMATED || balanceType == BalanceType.ESTIMATED_SPENDABLE) { List<TransactionOutput> all = calculateAllSpendCandidates(false, balanceType == BalanceType.ESTIMATED_SPENDABLE); Coin value = Coin.ZERO; for (TransactionOutput out : all) value = value.add(out.getValue()); return value; } else { throw new AssertionError("Unknown balance type"); // Unreachable. } } finally { lock.unlock(); } } /** * Returns the balance that would be considered spendable by the given coin selector, including watched outputs * (i.e. balance includes outputs we don't have the private keys for). Just asks it to select as many coins as * possible and returns the total. */ public Coin getBalance(CoinSelector selector) { lock.lock(); try { Objects.requireNonNull(selector); List<TransactionOutput> candidates = calculateAllSpendCandidates(true, false); CoinSelection selection = selector.select((Coin) network.maxMoney(), candidates); return selection.totalValue(); } finally { lock.unlock(); } } private static class BalanceFutureRequest { public final CompletableFuture<Coin> future; public final Coin value; public final BalanceType type; private BalanceFutureRequest(CompletableFuture<Coin> future, Coin value, BalanceType type) { this.future = future; this.value = value; this.type = type; } } @GuardedBy("lock") private final List<BalanceFutureRequest> balanceFutureRequests = new LinkedList<>(); /** * <p>Returns a future that will complete when the balance of the given type has becom equal or larger to the given * value. If the wallet already has a large enough balance the future is returned in a pre-completed state. Note * that this method is not blocking, if you want to actually wait immediately, you have to call .get() on * the result.</p> * * <p>Also note that by the time the future completes, the wallet may have changed yet again if something else * is going on in parallel, so you should treat the returned balance as advisory and be prepared for sending * money to fail! Finally please be aware that any listeners on the future will run either on the calling thread * if it completes immediately, or eventually on a background thread if the balance is not yet at the right * level. If you do something that means you know the balance should be sufficient to trigger the future, * you can use {@link Threading#waitForUserCode()} to block until the future had a * chance to be updated.</p> */ public ListenableCompletableFuture<Coin> getBalanceFuture(final Coin value, final BalanceType type) { lock.lock(); try { final CompletableFuture<Coin> future = new CompletableFuture<>(); final Coin current = getBalance(type); if (current.compareTo(value) >= 0) { // Already have enough. future.complete(current); } else { // Will be checked later in checkBalanceFutures. We don't just add an event listener for ourselves // here so that running getBalanceFuture().get() in the user code thread works - generally we must // avoid giving the user back futures that require the user code thread to be free. balanceFutureRequests.add(new BalanceFutureRequest(future, value, type)); } return ListenableCompletableFuture.of(future); } finally { lock.unlock(); } } // Runs any balance futures in the user code thread. @SuppressWarnings("FieldAccessNotGuarded") private void checkBalanceFuturesLocked() { checkState(lock.isHeldByCurrentThread()); balanceFutureRequests.forEach(req -> { Coin current = getBalance(req.type); // This could be slow for lots of futures. if (current.compareTo(req.value) >= 0) { // Found one that's finished. // Don't run any user-provided future listeners with our lock held. Threading.USER_THREAD.execute(() -> req.future.complete(current)); } }); balanceFutureRequests.removeIf(req -> req.future.isDone()); } /** * Returns the amount of bitcoin ever received via output. <b>This is not the balance!</b> If an output spends from a * transaction whose inputs are also to our wallet, the input amounts are deducted from the outputs contribution, with a minimum of zero * contribution. The idea behind this is we avoid double counting money sent to us. * @return the total amount of satoshis received, regardless of whether it was spent or not. */ public Coin getTotalReceived() { Coin total = Coin.ZERO; // Include outputs to us if they were not just change outputs, ie the inputs to us summed to less // than the outputs to us. for (Transaction tx: transactions.values()) { Coin txTotal = Coin.ZERO; for (TransactionOutput output : tx.getOutputs()) { if (output.isMine(this)) { txTotal = txTotal.add(output.getValue()); } } for (TransactionInput in : tx.getInputs()) { TransactionOutput prevOut = in.getConnectedOutput(); if (prevOut != null && prevOut.isMine(this)) { txTotal = txTotal.subtract(prevOut.getValue()); } } if (txTotal.isPositive()) { total = total.add(txTotal); } } return total; } /** * Returns the amount of bitcoin ever sent via output. If an output is sent to our own wallet, because of change or * rotating keys or whatever, we do not count it. If the wallet was * involved in a shared transaction, i.e. there is some input to the transaction that we don't have the key for, then * we multiply the sum of the output values by the proportion of satoshi coming in to our inputs. Essentially we treat * inputs as pooling into the transaction, becoming fungible and being equally distributed to all outputs. * @return the total amount of satoshis sent by us */ public Coin getTotalSent() { Coin total = Coin.ZERO; for (Transaction tx: transactions.values()) { // Count spent outputs to only if they were not to us. This means we don't count change outputs. Coin txOutputTotal = Coin.ZERO; for (TransactionOutput out : tx.getOutputs()) { if (out.isMine(this) == false) { txOutputTotal = txOutputTotal.add(out.getValue()); } } // Count the input values to us Coin txOwnedInputsTotal = Coin.ZERO; for (TransactionInput in : tx.getInputs()) { TransactionOutput prevOut = in.getConnectedOutput(); if (prevOut != null && prevOut.isMine(this)) { txOwnedInputsTotal = txOwnedInputsTotal.add(prevOut.getValue()); } } // If there is an input that isn't from us, i.e. this is a shared transaction Coin txInputsTotal = tx.getInputSum(); if (!txOwnedInputsTotal.equals(txInputsTotal)) { // multiply our output total by the appropriate proportion to account for the inputs that we don't own BigInteger txOutputTotalNum = new BigInteger(txOutputTotal.toString()); txOutputTotalNum = txOutputTotalNum.multiply(new BigInteger(txOwnedInputsTotal.toString())); txOutputTotalNum = txOutputTotalNum.divide(new BigInteger(txInputsTotal.toString())); txOutputTotal = Coin.valueOf(txOutputTotalNum.longValue()); } total = total.add(txOutputTotal); } return total; } //endregion // *************************************************************************************************************** //region Creating and sending transactions /** A SendResult is returned to you as part of sending coins to a recipient. */ public static class SendResult { /** * The Bitcoin transaction message that moves the money. * @deprecated Use {@link #transaction()} */ @Deprecated public final Transaction tx; /** * A future that will complete once the tx message has been successfully broadcast to the network. This is just the result of calling broadcast.future() * @deprecated Use {@link #awaitRelayed()} */ @Deprecated public final ListenableCompletableFuture<Transaction> broadcastComplete; /** * The broadcast object returned by the linked TransactionBroadcaster * @deprecated Use {@link #getBroadcast()} */ @Deprecated public final TransactionBroadcast broadcast; /** * @deprecated Use {@link #SendResult(TransactionBroadcast)} */ @Deprecated public SendResult(Transaction tx, TransactionBroadcast broadcast) { this(broadcast); } public SendResult(TransactionBroadcast broadcast) { this.tx = broadcast.transaction(); this.broadcast = broadcast; this.broadcastComplete = ListenableCompletableFuture.of(broadcast.awaitRelayed().thenApply(TransactionBroadcast::transaction)); } public Transaction transaction() { return broadcast.transaction(); } public TransactionBroadcast getBroadcast() { return broadcast; } public CompletableFuture<TransactionBroadcast> awaitRelayed() { return broadcast.awaitRelayed(); } } /** * Enumerates possible resolutions for missing signatures. */ public enum MissingSigsMode { /** Input script will have OP_0 instead of missing signatures */ USE_OP_ZERO, /** * Missing signatures will be replaced by dummy sigs. This is useful when you'd like to know the fee for * a transaction without knowing the user's password, as fee depends on size. */ USE_DUMMY_SIG, /** * If signature is missing, {@link TransactionSigner.MissingSignatureException} * will be thrown for P2SH and {@link ECKey.MissingPrivateKeyException} for other tx types. */ THROW } /** * <p>Statelessly creates a transaction that sends the given value to address. The change is sent to * {@link Wallet#currentChangeAddress()}, so you must have added at least one key.</p> * * <p>If you just want to send money quickly, you probably want * {@link Wallet#sendCoins(TransactionBroadcaster, Address, Coin)} instead. That will create the sending * transaction, commit to the wallet and broadcast it to the network all in one go. This method is lower level * and lets you see the proposed transaction before anything is done with it.</p> * * <p>This is a helper method that is equivalent to using {@link SendRequest#to(Address, Coin)} * followed by {@link Wallet#completeTx(SendRequest)} and returning the requests transaction object. * Note that this means a fee may be automatically added if required, if you want more control over the process, * just do those two steps yourself.</p> * * <p>IMPORTANT: This method does NOT update the wallet. If you call createSend again you may get two transactions * that spend the same coins. You have to call {@link Wallet#commitTx(Transaction)} on the created transaction to * prevent this, but that should only occur once the transaction has been accepted by the network. This implies * you cannot have more than one outstanding sending tx at once.</p> * * <p>You MUST ensure that the value is not smaller than {@link TransactionOutput#getMinNonDustValue()} or the transaction * will almost certainly be rejected by the network as dust.</p> * * @param address The Bitcoin address to send the money to. * @param value How much currency to send. * @return either the created Transaction or null if there are insufficient coins. * @throws InsufficientMoneyException if the request could not be completed due to not enough balance. * @throws DustySendRequested if the resultant transaction would violate the dust rules. * @throws CouldNotAdjustDownwards if emptying the wallet was requested and the output can't be shrunk for fees without violating a protocol rule. * @throws ExceededMaxTransactionSize if the resultant transaction is too big for Bitcoin to process. * @throws MultipleOpReturnRequested if there is more than one OP_RETURN output for the resultant transaction. * @throws BadWalletEncryptionKeyException if the supplied {@link SendRequest#aesKey} is wrong. */ public Transaction createSend(Address address, Coin value) throws InsufficientMoneyException, BadWalletEncryptionKeyException { return createSend(address, value, false); } /** * <p>Statelessly creates a transaction that sends the given value to address. The change is sent to * {@link Wallet#currentChangeAddress()}, so you must have added at least one key.</p> * * <p>If you just want to send money quickly, you probably want * {@link Wallet#sendCoins(TransactionBroadcaster, Address, Coin)} instead. That will create the sending * transaction, commit to the wallet and broadcast it to the network all in one go. This method is lower level * and lets you see the proposed transaction before anything is done with it.</p> * * <p>This is a helper method that is equivalent to using {@link SendRequest#to(Address, Coin)} * followed by {@link Wallet#completeTx(SendRequest)} and returning the requests transaction object. * Note that this means a fee may be automatically added if required, if you want more control over the process, * just do those two steps yourself.</p> * * <p>IMPORTANT: This method does NOT update the wallet. If you call createSend again you may get two transactions * that spend the same coins. You have to call {@link Wallet#commitTx(Transaction)} on the created transaction to * prevent this, but that should only occur once the transaction has been accepted by the network. This implies * you cannot have more than one outstanding sending tx at once.</p> * * <p>You MUST ensure that the value is not smaller than {@link TransactionOutput#getMinNonDustValue()} or the transaction * will almost certainly be rejected by the network as dust.</p> * * @param address The Bitcoin address to send the money to. * @param value How much currency to send. * @param allowUnconfirmed Wether to allow spending unconfirmed outputs. * @return either the created Transaction or null if there are insufficient coins. * @throws InsufficientMoneyException if the request could not be completed due to not enough balance. * @throws DustySendRequested if the resultant transaction would violate the dust rules. * @throws CouldNotAdjustDownwards if emptying the wallet was requested and the output can't be shrunk for fees without violating a protocol rule. * @throws ExceededMaxTransactionSize if the resultant transaction is too big for Bitcoin to process. * @throws MultipleOpReturnRequested if there is more than one OP_RETURN output for the resultant transaction. * @throws BadWalletEncryptionKeyException if the supplied {@link SendRequest#aesKey} is wrong. */ public Transaction createSend(Address address, Coin value, boolean allowUnconfirmed) throws InsufficientMoneyException, BadWalletEncryptionKeyException { SendRequest req = SendRequest.to(address, value); if (allowUnconfirmed) req.allowUnconfirmed(); completeTx(req); return req.tx; } /** * Sends coins to the given address but does not broadcast the resulting pending transaction. It is still stored * in the wallet, so when the wallet is added to a {@link PeerGroup} or {@link Peer} the transaction will be * announced to the network. The given {@link SendRequest} is completed first using * {@link Wallet#completeTx(SendRequest)} to make it valid. * * @return the Transaction that was created * @throws InsufficientMoneyException if the request could not be completed due to not enough balance. * @throws IllegalArgumentException if you try and complete the same SendRequest twice * @throws DustySendRequested if the resultant transaction would violate the dust rules. * @throws CouldNotAdjustDownwards if emptying the wallet was requested and the output can't be shrunk for fees without violating a protocol rule. * @throws ExceededMaxTransactionSize if the resultant transaction is too big for Bitcoin to process. * @throws MultipleOpReturnRequested if there is more than one OP_RETURN output for the resultant transaction. * @throws BadWalletEncryptionKeyException if the supplied {@link SendRequest#aesKey} is wrong. */ public Transaction sendCoinsOffline(SendRequest request) throws InsufficientMoneyException, BadWalletEncryptionKeyException { lock.lock(); try { completeTx(request); commitTx(request.tx); return request.tx; } finally { lock.unlock(); } } /** * <p>Sends coins to the given address, via the given {@link PeerGroup}. Change is returned to * {@link Wallet#currentChangeAddress()}. Note that a fee may be automatically added if one may be required for the * transaction to be confirmed.</p> * * <p>The returned object provides both the transaction, and a future that can be used to learn when the broadcast * is complete. Complete means, if the PeerGroup is limited to only one connection, when it was written out to * the socket. Otherwise when the transaction is written out and we heard it back from a different peer.</p> * * <p>Note that the sending transaction is committed to the wallet immediately, not when the transaction is * successfully broadcast. This means that even if the network hasn't heard about your transaction you won't be * able to spend those same coins again.</p> * * <p>You MUST ensure that value is not smaller than {@link TransactionOutput#getMinNonDustValue()} or the transaction will * almost certainly be rejected by the network as dust.</p> * * @param broadcaster a {@link TransactionBroadcaster} to use to send the transactions out. * @param to Which address to send coins to. * @param value How much value to send. * @return An object containing the transaction that was created, and a future for the broadcast of it. * @throws InsufficientMoneyException if the request could not be completed due to not enough balance. * @throws DustySendRequested if the resultant transaction would violate the dust rules. * @throws CouldNotAdjustDownwards if emptying the wallet was requested and the output can't be shrunk for fees without violating a protocol rule. * @throws ExceededMaxTransactionSize if the resultant transaction is too big for Bitcoin to process. * @throws MultipleOpReturnRequested if there is more than one OP_RETURN output for the resultant transaction. * @throws BadWalletEncryptionKeyException if the supplied {@link SendRequest#aesKey} is wrong. */ public SendResult sendCoins(TransactionBroadcaster broadcaster, Address to, Coin value) throws InsufficientMoneyException, BadWalletEncryptionKeyException { SendRequest request = SendRequest.to(to, value); return sendCoins(broadcaster, request); } /** * <p>Sends coins according to the given request, via the given {@link TransactionBroadcaster}.</p> * * <p>The returned object provides both the transaction, and a future that can be used to learn when the broadcast * is complete. Complete means, if the PeerGroup is limited to only one connection, when it was written out to * the socket. Otherwise when the transaction is written out and we heard it back from a different peer.</p> * * <p>Note that the sending transaction is committed to the wallet immediately, not when the transaction is * successfully broadcast. This means that even if the network hasn't heard about your transaction you won't be * able to spend those same coins again.</p> * * @param broadcaster the target to use for broadcast. * @param request the SendRequest that describes what to do, get one using static methods on SendRequest itself. * @return An object containing the transaction that was created, and a future for the broadcast of it. * @throws InsufficientMoneyException if the request could not be completed due to not enough balance. * @throws IllegalArgumentException if you try and complete the same SendRequest twice * @throws DustySendRequested if the resultant transaction would violate the dust rules. * @throws CouldNotAdjustDownwards if emptying the wallet was requested and the output can't be shrunk for fees without violating a protocol rule. * @throws ExceededMaxTransactionSize if the resultant transaction is too big for Bitcoin to process. * @throws MultipleOpReturnRequested if there is more than one OP_RETURN output for the resultant transaction. * @throws BadWalletEncryptionKeyException if the supplied {@link SendRequest#aesKey} is wrong. */ public SendResult sendCoins(TransactionBroadcaster broadcaster, SendRequest request) throws InsufficientMoneyException, BadWalletEncryptionKeyException { // Should not be locked here, as we're going to call into the broadcaster and that might want to hold its // own lock. sendCoinsOffline handles everything that needs to be locked. checkState(!lock.isHeldByCurrentThread()); // Commit the TX to the wallet immediately so the spent coins won't be reused. // TODO: We should probably allow the request to specify tx commit only after the network has accepted it. Transaction tx = sendCoinsOffline(request); SendResult result = new SendResult(broadcaster.broadcastTransaction(tx)); // The tx has been committed to the pending pool by this point (via sendCoinsOffline -> commitTx), so it has // a txConfidenceListener registered. Once the tx is broadcast the peers will update the memory pool with the // count of seen peers, the memory pool will update the transaction confidence object, that will invoke the // txConfidenceListener which will in turn invoke the wallets event listener onTransactionConfidenceChanged // method. return result; } /** * Satisfies the given {@link SendRequest} using the default transaction broadcaster configured either via * {@link PeerGroup#addWallet(Wallet)} or directly with {@link #setTransactionBroadcaster(TransactionBroadcaster)}. * * @param request the SendRequest that describes what to do, get one using static methods on SendRequest itself. * @return An object containing the transaction that was created, and a future for the broadcast of it. * @throws IllegalStateException if no transaction broadcaster has been configured. * @throws InsufficientMoneyException if the request could not be completed due to not enough balance. * @throws IllegalArgumentException if you try and complete the same SendRequest twice * @throws DustySendRequested if the resultant transaction would violate the dust rules. * @throws CouldNotAdjustDownwards if emptying the wallet was requested and the output can't be shrunk for fees without violating a protocol rule. * @throws ExceededMaxTransactionSize if the resultant transaction is too big for Bitcoin to process. * @throws MultipleOpReturnRequested if there is more than one OP_RETURN output for the resultant transaction. * @throws BadWalletEncryptionKeyException if the supplied {@link SendRequest#aesKey} is wrong. */ public SendResult sendCoins(SendRequest request) throws InsufficientMoneyException, BadWalletEncryptionKeyException { TransactionBroadcaster broadcaster = vTransactionBroadcaster; checkState(broadcaster != null, () -> "no transaction broadcaster is configured"); return sendCoins(broadcaster, request); } /** * Sends coins to the given address, via the given {@link Peer}. Change is returned to {@link Wallet#currentChangeAddress()}. * If an exception is thrown by {@link Peer#sendMessage(Message)} the transaction is still committed, so the * pending transaction must be broadcast <b>by you</b> at some other time. Note that a fee may be automatically added * if one may be required for the transaction to be confirmed. * * @return The {@link Transaction} that was created or null if there was insufficient balance to send the coins. * @throws InsufficientMoneyException if the request could not be completed due to not enough balance. * @throws IllegalArgumentException if you try and complete the same SendRequest twice * @throws DustySendRequested if the resultant transaction would violate the dust rules. * @throws CouldNotAdjustDownwards if emptying the wallet was requested and the output can't be shrunk for fees without violating a protocol rule. * @throws ExceededMaxTransactionSize if the resultant transaction is too big for Bitcoin to process. * @throws MultipleOpReturnRequested if there is more than one OP_RETURN output for the resultant transaction. * @throws BadWalletEncryptionKeyException if the supplied {@link SendRequest#aesKey} is wrong. */ public Transaction sendCoins(Peer peer, SendRequest request) throws InsufficientMoneyException, BadWalletEncryptionKeyException { Transaction tx = sendCoinsOffline(request); peer.sendMessage(tx); return tx; } /** * Initiate sending the transaction in a {@link SendRequest}. Calls {@link Wallet#sendCoins(SendRequest)} which * performs the following significant operations internally: * <ol> * <li>{@link Wallet#completeTx(SendRequest)} -- calculate change and sign</li> * <li>{@link Wallet#commitTx(Transaction)} -- puts the transaction in the {@code Wallet}'s pending pool</li> * <li>{@link org.bitcoinj.core.TransactionBroadcaster#broadcastTransaction(Transaction)} typically implemented by {@link org.bitcoinj.core.PeerGroup#broadcastTransaction(Transaction)} -- queues requests to send the transaction to a single remote {@code Peer}</li> * </ol> * This method will <i>complete</i> and return a {@link TransactionBroadcast} when the send to the remote peer occurs (is buffered.) * The broadcast process includes the following steps: * <ol> * <li>Wait until enough {@link org.bitcoinj.core.Peer}s are connected.</li> * <li>Broadcast (buffer for send) the transaction to a single remote {@link org.bitcoinj.core.Peer}</li> * <li>Mark {@link TransactionBroadcast#awaitSent()} as complete</li> * <li>Wait for a number of remote peers to confirm they have received the broadcast</li> * <li>Mark {@link TransactionBroadcast#future()} as complete</li> * </ol> * @param sendRequest transaction to send * @return A future for the transaction broadcast */ public CompletableFuture<TransactionBroadcast> sendTransaction(SendRequest sendRequest) { try { // Complete successfully when the transaction has been sent (or buffered, at least) to peers. return sendCoins(sendRequest).broadcast.awaitSent(); } catch (KeyCrypterException | InsufficientMoneyException e) { // We should never try to send more coins than we have, if we do we get an InsufficientMoneyException return FutureUtils.failedFuture(e); } } /** * Wait for at least 1 confirmation on a transaction. * @param tx the transaction we are waiting for * @return a future for an object that contains transaction confidence information */ public CompletableFuture<TransactionConfidence> waitForConfirmation(Transaction tx) { return waitForConfirmations(tx, 1); } /** * Wait for a required number of confirmations on a transaction. * @param tx the transaction we are waiting for * @param requiredConfirmations the minimum required confirmations before completing * @return a future for an object that contains transaction confidence information */ public CompletableFuture<TransactionConfidence> waitForConfirmations(Transaction tx, int requiredConfirmations) { return tx.getConfidence().getDepthFuture(requiredConfirmations); } /** * Class of exceptions thrown in {@link Wallet#completeTx(SendRequest)}. */ public static class CompletionException extends RuntimeException { public CompletionException() { super(); } public CompletionException(Throwable throwable) { super(throwable); } } /** * Thrown if the resultant transaction would violate the dust rules (an output that's too small to be worthwhile). */ public static class DustySendRequested extends CompletionException {} /** * Thrown if there is more than one OP_RETURN output for the resultant transaction. */ public static class MultipleOpReturnRequested extends CompletionException {} /** * Thrown when we were trying to empty the wallet, and the total amount of money we were trying to empty after * being reduced for the fee was smaller than the min payment. Note that the missing field will be null in this * case. */ public static class CouldNotAdjustDownwards extends CompletionException {} /** * Thrown if the resultant transaction is too big for Bitcoin to process. Try breaking up the amounts of value. */ public static class ExceededMaxTransactionSize extends CompletionException {} /** * Thrown if the private keys and seed of this wallet cannot be decrypted due to the supplied encryption * key or password being wrong. */ public static class BadWalletEncryptionKeyException extends CompletionException { public BadWalletEncryptionKeyException(Throwable throwable) { super(throwable); } } /** * Given a spend request containing an incomplete transaction, makes it valid by adding outputs and signed inputs * according to the instructions in the request. The transaction in the request is modified by this method. * * @param req a SendRequest that contains the incomplete transaction and details for how to make it valid. * @throws InsufficientMoneyException if the request could not be completed due to not enough balance. * @throws IllegalArgumentException if you try and complete the same SendRequest twice * @throws DustySendRequested if the resultant transaction would violate the dust rules. * @throws CouldNotAdjustDownwards if emptying the wallet was requested and the output can't be shrunk for fees without violating a protocol rule. * @throws ExceededMaxTransactionSize if the resultant transaction is too big for Bitcoin to process. * @throws MultipleOpReturnRequested if there is more than one OP_RETURN output for the resultant transaction. * @throws BadWalletEncryptionKeyException if the supplied {@link SendRequest#aesKey} is wrong. */ public void completeTx(SendRequest req) throws InsufficientMoneyException, BadWalletEncryptionKeyException { lock.lock(); try { checkArgument(!req.completed, () -> "given SendRequest has already been completed"); log.info("Completing send tx with {} outputs totalling {} and a fee of {}/vkB", req.tx.getOutputs().size(), req.tx.getOutputSum().toFriendlyString(), req.feePerKb.toFriendlyString()); // Calculate a list of ALL potential candidates for spending and then ask a coin selector to provide us // with the actual outputs that'll be used to gather the required amount of value. In this way, users // can customize coin selection policies. The call below will ignore immature coinbases and outputs // we don't have the keys for. List<TransactionOutput> prelimCandidates = calculateAllSpendCandidates(true, req.missingSigsMode == MissingSigsMode.THROW); // Connect (add a value amount) unconnected inputs List<TransactionInput> inputs = connectInputs(prelimCandidates, req.tx.getInputs()); req.tx.clearInputs(); inputs.forEach(req.tx::addInput); // Warn if there are remaining unconnected inputs whose value we do not know // TODO: Consider throwing if there are inputs that we don't have a value for if (req.tx.getInputs().stream() .map(TransactionInput::getValue) .anyMatch(Objects::isNull)) log.warn("SendRequest transaction already has inputs but we don't know how much they are worth - they will be added to fee."); // If any inputs have already been added, we don't need to get their value from wallet Coin totalInput = req.tx.getInputSum(); // Calculate the amount of value we need to import. Coin valueNeeded = req.tx.getOutputSum().subtract(totalInput); // Enforce the OP_RETURN limit if (req.tx.getOutputs().stream() .filter(o -> ScriptPattern.isOpReturn(o.getScriptPubKey())) .count() > 1) // Only 1 OP_RETURN per transaction allowed. throw new MultipleOpReturnRequested(); // Check for dusty sends if (req.ensureMinRequiredFee && !req.emptyWallet) { // Min fee checking is handled later for emptyWallet. if (req.tx.getOutputs().stream().anyMatch(TransactionOutput::isDust)) throw new DustySendRequested(); } // Filter out candidates that are already included in the transaction inputs List<TransactionOutput> candidates = prelimCandidates.stream() .filter(output -> alreadyIncluded(req.tx.getInputs(), output)) .collect(StreamUtils.toUnmodifiableList()); CoinSelection bestCoinSelection; TransactionOutput bestChangeOutput = null; List<Coin> updatedOutputValues = null; if (!req.emptyWallet) { // This can throw InsufficientMoneyException. FeeCalculation feeCalculation = calculateFee(req, valueNeeded, req.ensureMinRequiredFee, candidates); bestCoinSelection = feeCalculation.bestCoinSelection; bestChangeOutput = feeCalculation.bestChangeOutput; updatedOutputValues = feeCalculation.updatedOutputValues; } else { // We're being asked to empty the wallet. What this means is ensuring "tx" has only a single output // of the total value we can currently spend as determined by the selector, and then subtracting the fee. checkState(req.tx.getOutputs().size() == 1, () -> "empty wallet TX must have a single output only"); CoinSelector selector = req.coinSelector == null ? coinSelector : req.coinSelector; bestCoinSelection = selector.select((Coin) network.maxMoney(), candidates); candidates = null; // Selector took ownership and might have changed candidates. Don't access again. req.tx.getOutput(0).setValue(bestCoinSelection.totalValue()); log.info(" emptying {}", bestCoinSelection.totalValue().toFriendlyString()); } bestCoinSelection.outputs() .forEach(req.tx::addInput); if (req.emptyWallet) { if (!adjustOutputDownwardsForFee(req.tx, bestCoinSelection, req.feePerKb, req.ensureMinRequiredFee)) throw new CouldNotAdjustDownwards(); } if (updatedOutputValues != null) { for (int i = 0; i < updatedOutputValues.size(); i++) { req.tx.getOutput(i).setValue(updatedOutputValues.get(i)); } } if (bestChangeOutput != null) { req.tx.addOutput(bestChangeOutput); log.info(" with {} change", bestChangeOutput.getValue().toFriendlyString()); } // Now shuffle the outputs to obfuscate which is the change. if (req.shuffleOutputs) req.tx.shuffleOutputs(); // Now sign the inputs, thus proving that we are entitled to redeem the connected outputs. if (req.signInputs) signTransaction(req); // Check size. final int size = req.tx.serialize().length; if (size > Transaction.MAX_STANDARD_TX_SIZE) throw new ExceededMaxTransactionSize(); // Label the transaction as being self created. We can use this later to spend its change output even before // the transaction is confirmed. We deliberately won't bother notifying listeners here as there's not much // point - the user isn't interested in a confidence transition they made themselves. req.tx.getConfidence().setSource(TransactionConfidence.Source.SELF); // Label the transaction as being a user requested payment. This can be used to render GUI wallet // transaction lists more appropriately, especially when the wallet starts to generate transactions itself // for internal purposes. req.tx.setPurpose(Transaction.Purpose.USER_PAYMENT); // Record the exchange rate that was valid when the transaction was completed. req.tx.setExchangeRate(req.exchangeRate); req.tx.setMemo(req.memo); req.completed = true; log.info(" completed: {}", req.tx); } finally { lock.unlock(); } } /** * Connect unconnected inputs with outputs from the wallet * @param candidates A list of spend candidates from a Wallet * @param inputs a list of possibly unconnected/unvalued inputs (e.g. from a spend request) * @return a list of the same inputs, but connected/valued if not previously valued and found in wallet */ @VisibleForTesting static List<TransactionInput> connectInputs(List<TransactionOutput> candidates, List<TransactionInput> inputs) { return inputs.stream() .map(in -> candidates.stream() .filter(utxo -> utxo.getOutPointFor().equals(in.getOutpoint())) .findFirst() .map(o -> new TransactionInput(o.getParentTransaction(), o.getScriptPubKey().program(), o.getOutPointFor(), o.getValue())) .orElse(in)) .collect(StreamUtils.toUnmodifiableList()); } /** * Is a UTXO already included (to be spent) in a list of transaction inputs? * @param inputs the list of inputs to check * @param output the transaction output * @return true if it is already included, false otherwise */ private boolean alreadyIncluded(List<TransactionInput> inputs, TransactionOutput output) { return inputs.stream().noneMatch(i -> i.getOutpoint().equals(output.getOutPointFor())); } /** * <p>Given a send request containing transaction, attempts to sign it's inputs. This method expects transaction * to have all necessary inputs connected or they will be ignored.</p> * <p>Actual signing is done by pluggable {@link #signers} and it's not guaranteed that * transaction will be complete in the end.</p> * @throws BadWalletEncryptionKeyException if the supplied {@link SendRequest#aesKey} is wrong. */ public void signTransaction(SendRequest req) throws BadWalletEncryptionKeyException { lock.lock(); try { Transaction tx = req.tx; List<TransactionInput> inputs = tx.getInputs(); List<TransactionOutput> outputs = tx.getOutputs(); checkState(inputs.size() > 0); checkState(outputs.size() > 0); KeyBag maybeDecryptingKeyBag = new DecryptingKeyBag(this, req.aesKey); int numInputs = tx.getInputs().size(); for (int i = 0; i < numInputs; i++) { TransactionInput txIn = tx.getInput(i); TransactionOutput connectedOutput = txIn.getConnectedOutput(); if (connectedOutput == null) { // Missing connected output, assuming already signed. continue; } Script scriptPubKey = connectedOutput.getScriptPubKey(); try { // We assume if its already signed, its hopefully got a SIGHASH type that will not invalidate when // we sign missing pieces (to check this would require either assuming any signatures are signing // standard output types or a way to get processed signatures out of script execution) txIn.getScriptSig().correctlySpends(tx, i, txIn.getWitness(), connectedOutput.getValue(), connectedOutput.getScriptPubKey(), Script.ALL_VERIFY_FLAGS); log.warn("Input {} already correctly spends output, assuming SIGHASH type used will be safe and skipping signing.", i); continue; } catch (ScriptException e) { log.debug("Input contained an incorrect signature", e); // Expected. } RedeemData redeemData = txIn.getConnectedRedeemData(maybeDecryptingKeyBag); Objects.requireNonNull(redeemData, () -> "Transaction exists in wallet that we cannot redeem: " + txIn.getOutpoint().hash()); txIn.setScriptSig(scriptPubKey.createEmptyInputScript(redeemData.keys.get(0), redeemData.redeemScript)); } TransactionSigner.ProposedTransaction proposal = new TransactionSigner.ProposedTransaction(tx); for (TransactionSigner signer : signers) { if (!signer.signInputs(proposal, maybeDecryptingKeyBag)) log.info("{} returned false for the tx", signer.getClass().getName()); } // resolve missing sigs if any new MissingSigResolutionSigner(req.missingSigsMode).signInputs(proposal, maybeDecryptingKeyBag); } catch (KeyCrypterException.InvalidCipherText | KeyCrypterException.PublicPrivateMismatch e) { throw new BadWalletEncryptionKeyException(e); } finally { lock.unlock(); } } /** * Reduce the value of the first output of a transaction to pay the given feePerKb as appropriate for its size. * If ensureMinRequiredFee is true, feePerKb is set to at least {@link Transaction#REFERENCE_DEFAULT_MIN_TX_FEE}. */ private boolean adjustOutputDownwardsForFee(Transaction tx, CoinSelection coinSelection, Coin feePerKb, boolean ensureMinRequiredFee) { if (ensureMinRequiredFee && feePerKb.compareTo(Transaction.REFERENCE_DEFAULT_MIN_TX_FEE) < 0) feePerKb = Transaction.REFERENCE_DEFAULT_MIN_TX_FEE; final int vsize = tx.getVsize() + estimateVirtualBytesForSigning(coinSelection); Coin fee = feePerKb.multiply(vsize).divide(1000); TransactionOutput output = tx.getOutput(0); output.setValue(output.getValue().subtract(fee)); return !output.isDust(); } /** * Returns a list of the outputs that can potentially be spent, i.e. that we have the keys for and are unspent * according to our knowledge of the block chain. */ public List<TransactionOutput> calculateAllSpendCandidates() { return calculateAllSpendCandidates(true, true); } /** * Returns a list of all outputs that are being tracked by this wallet either from the {@link UTXOProvider} * (in this case the existence or not of private keys is ignored), or the wallets internal storage (the default) * taking into account the flags. * * @param excludeImmatureCoinbases Whether to ignore coinbase outputs that we will be able to spend in future once they mature. * @param excludeUnsignable Whether to ignore outputs that we are tracking but don't have the keys to sign for. */ public List<TransactionOutput> calculateAllSpendCandidates(boolean excludeImmatureCoinbases, boolean excludeUnsignable) { lock.lock(); try { List<TransactionOutput> candidates; if (vUTXOProvider == null) { candidates = myUnspents.stream() .filter(output -> (!excludeUnsignable || canSignFor(output.getScriptPubKey())) && (!excludeImmatureCoinbases || isTransactionMature(output.getParentTransaction()))) .collect(StreamUtils.toUnmodifiableList()); } else { candidates = calculateAllSpendCandidatesFromUTXOProvider(excludeImmatureCoinbases); } return candidates; } finally { lock.unlock(); } } /** * Returns true if this wallet has at least one of the private keys needed to sign for this scriptPubKey. Returns * false if the form of the script is not known or if the script is OP_RETURN. */ public boolean canSignFor(Script script) { if (ScriptPattern.isP2PK(script)) { byte[] pubkey = ScriptPattern.extractKeyFromP2PK(script); ECKey key = findKeyFromPubKey(pubkey); return key != null && (key.isEncrypted() || key.hasPrivKey()); } else if (ScriptPattern.isP2SH(script)) { RedeemData data = findRedeemDataFromScriptHash(ScriptPattern.extractHashFromP2SH(script)); return data != null && canSignFor(data.redeemScript); } else if (ScriptPattern.isP2PKH(script)) { ECKey key = findKeyFromPubKeyHash(ScriptPattern.extractHashFromP2PKH(script), ScriptType.P2PKH); return key != null && (key.isEncrypted() || key.hasPrivKey()); } else if (ScriptPattern.isP2WPKH(script)) { ECKey key = findKeyFromPubKeyHash(ScriptPattern.extractHashFromP2WH(script), ScriptType.P2WPKH); return key != null && (key.isEncrypted() || key.hasPrivKey()) && key.isCompressed(); } else if (ScriptPattern.isSentToMultisig(script)) { for (ECKey pubkey : script.getPubKeys()) { ECKey key = findKeyFromPubKey(pubkey.getPubKey()); if (key != null && (key.isEncrypted() || key.hasPrivKey())) return true; } } return false; } /** * Returns the spendable candidates from the {@link UTXOProvider} based on keys that the wallet contains. * @return The list of candidates. */ protected List<TransactionOutput> calculateAllSpendCandidatesFromUTXOProvider(boolean excludeImmatureCoinbases) { checkState(lock.isHeldByCurrentThread()); UTXOProvider utxoProvider = Objects.requireNonNull(vUTXOProvider, "No UTXO provider has been set"); List<TransactionOutput> candidates = new LinkedList<>(); try { int chainHeight = utxoProvider.getChainHeadHeight(); for (UTXO output : getStoredOutputsFromUTXOProvider()) { boolean coinbase = output.isCoinbase(); int depth = chainHeight - output.getHeight() + 1; // the current depth of the output (1 = same as head). // Do not try and spend coinbases that were mined too recently, the protocol forbids it. if (!excludeImmatureCoinbases || !coinbase || depth >= params.getSpendableCoinbaseDepth()) { candidates.add(new FreeStandingTransactionOutput(output, chainHeight)); } } } catch (UTXOProviderException e) { throw new RuntimeException("UTXO provider error", e); } // We need to handle the pending transactions that we know about. for (Transaction tx : pending.values()) { // Remove the spent outputs. for (TransactionInput input : tx.getInputs()) { if (input.getConnectedOutput().isMine(this)) { candidates.remove(input.getConnectedOutput()); } } // Add change outputs. Do not try and spend coinbases that were mined too recently, the protocol forbids it. if (!excludeImmatureCoinbases || isTransactionMature(tx)) { for (TransactionOutput output : tx.getOutputs()) { if (output.isAvailableForSpending() && output.isMine(this)) { candidates.add(output); } } } } return candidates; } /** * Get all the {@link UTXO}'s from the {@link UTXOProvider} based on keys that the * wallet contains. * @return The list of stored outputs. */ protected List<UTXO> getStoredOutputsFromUTXOProvider() throws UTXOProviderException { UTXOProvider utxoProvider = Objects.requireNonNull(vUTXOProvider, "No UTXO provider has been set"); List<UTXO> candidates = new ArrayList<>(); List<ECKey> keys = getImportedKeys(); keys.addAll(getActiveKeyChain().getLeafKeys()); candidates.addAll(utxoProvider.getOpenTransactionOutputs(keys)); return candidates; } /** Returns the default {@link CoinSelector} object that is used by this wallet if no custom selector is specified. */ public CoinSelector getCoinSelector() { lock.lock(); try { return coinSelector; } finally { lock.unlock(); } } /** * Get the {@link UTXOProvider}. * @return The UTXO provider. */ @Nullable public UTXOProvider getUTXOProvider() { lock.lock(); try { return vUTXOProvider; } finally { lock.unlock(); } } /** * Set the {@link UTXOProvider}. * * <p>The wallet will query the provider for spendable candidates, i.e. outputs controlled exclusively * by private keys contained in the wallet.</p> * * <p>Note that the associated provider must be reattached after a wallet is loaded from disk. * The association is not serialized.</p> */ public void setUTXOProvider(@Nullable UTXOProvider provider) { lock.lock(); try { checkArgument(provider == null || provider.network() == network); this.vUTXOProvider = provider; } finally { lock.unlock(); } } //endregion // *************************************************************************************************************** /** * A custom {@link TransactionOutput} that is freestanding. This contains all the information * required for spending without actually having all the linked data (i.e parent tx). * */ private static class FreeStandingTransactionOutput extends TransactionOutput { private final UTXO output; private final int chainHeight; /** * Construct a freestanding Transaction Output. * @param output The stored output (freestanding). */ public FreeStandingTransactionOutput(UTXO output, int chainHeight) { super(null, output.getValue(), output.getScript().program()); this.output = output; this.chainHeight = chainHeight; } /** * Get the {@link UTXO}. * @return The stored output. */ public UTXO getUTXO() { return output; } /** * Get the depth withing the chain of the parent tx, depth is 1 if it the output height is the height of * the latest block. * @return The depth. */ @Override public int getParentTransactionDepthInBlocks() { return chainHeight - output.getHeight() + 1; } @Override public int getIndex() { return (int) output.getIndex(); } @Override public Sha256Hash getParentTransactionHash() { return output.getHash(); } } // *************************************************************************************************************** private static class TxOffsetPair implements Comparable<TxOffsetPair> { public final Transaction tx; public final int offset; public TxOffsetPair(Transaction tx, int offset) { this.tx = tx; this.offset = offset; } @Override public int compareTo(TxOffsetPair o) { // note that in this implementation compareTo() is not consistent with equals() return Integer.compare(offset, o.offset); } } //region Reorganisations /** * <p>Don't call this directly. It's not intended for API users.</p> * * <p>Called by the {@link BlockChain} when the best chain (representing total work done) has changed. This can * cause the number of confirmations of a transaction to go higher, lower, drop to zero and can even result in * a transaction going dead (will never confirm) due to a double spend.</p> * * <p>The oldBlocks/newBlocks lists are ordered height-wise from top first to bottom last.</p> */ @Override public void reorganize(StoredBlock splitPoint, List<StoredBlock> oldBlocks, List<StoredBlock> newBlocks) throws VerificationException { lock.lock(); try { // This runs on any peer thread with the block chain locked. // // The reorganize functionality of the wallet is tested in ChainSplitTest.java // // receive() has been called on the block that is triggering the re-org before this is called, with type // of SIDE_CHAIN. // // Note that this code assumes blocks are not invalid - if blocks contain duplicated transactions, // transactions that double spend etc then we can calculate the incorrect result. This could open up // obscure DoS attacks if someone successfully mines a throwaway invalid block and feeds it to us, just // to try and corrupt the internal data structures. We should try harder to avoid this but it's tricky // because there are so many ways the block can be invalid. // Avoid spuriously informing the user of wallet/tx confidence changes whilst we're re-organizing. checkState(confidenceChanged.size() == 0); checkState(!insideReorg); insideReorg = true; checkState(onWalletChangedSuppressions == 0); onWalletChangedSuppressions++; // Map block hash to transactions that appear in it. We ensure that the map values are sorted according // to their relative position within those blocks. ArrayListMultimap<Sha256Hash, TxOffsetPair> mapBlockTx = ArrayListMultimap.create(); for (Transaction tx : getTransactions(true)) { Map<Sha256Hash, Integer> appearsIn = tx.getAppearsInHashes(); if (appearsIn == null) continue; // Pending. for (Map.Entry<Sha256Hash, Integer> block : appearsIn.entrySet()) mapBlockTx.put(block.getKey(), new TxOffsetPair(tx, block.getValue())); } for (Sha256Hash blockHash : mapBlockTx.keySet()) Collections.sort(mapBlockTx.get(blockHash)); List<Sha256Hash> oldBlockHashes = new ArrayList<>(oldBlocks.size()); log.info("Old part of chain (top to bottom):"); for (StoredBlock b : oldBlocks) { log.info(" {}", b.getHeader().getHashAsString()); oldBlockHashes.add(b.getHeader().getHash()); } log.info("New part of chain (top to bottom):"); for (StoredBlock b : newBlocks) { log.info(" {}", b.getHeader().getHashAsString()); } Collections.reverse(newBlocks); // Need bottom-to-top but we get top-to-bottom. // For each block in the old chain, disconnect the transactions in reverse order. List<Transaction> oldChainTxns = new LinkedList<>(); for (Sha256Hash blockHash : oldBlockHashes) { for (TxOffsetPair pair : mapBlockTx.get(blockHash)) { Transaction tx = pair.tx; final Sha256Hash txHash = tx.getTxId(); if (tx.isCoinBase()) { // All the transactions that we have in our wallet which spent this coinbase are now invalid // and will never confirm. Hopefully this should never happen - that's the point of the maturity // rule that forbids spending of coinbase transactions for 100 blocks. // // This could be recursive, although of course because we don't have the full transaction // graph we can never reliably kill all transactions we might have that were rooted in // this coinbase tx. Some can just go pending forever, like the Bitcoin Core. However we // can do our best. log.warn("Coinbase killed by re-org: {}", tx.getTxId()); killTxns(Collections.singleton(tx), null); } else { for (TransactionOutput output : tx.getOutputs()) { TransactionInput input = output.getSpentBy(); if (input != null) { if (output.isMineOrWatched(this)) checkState(myUnspents.add(output)); input.disconnect(); } } oldChainTxns.add(tx); unspent.remove(txHash); spent.remove(txHash); checkState(!pending.containsKey(txHash)); checkState(!dead.containsKey(txHash)); } } } // Put all the disconnected transactions back into the pending pool and re-connect them. for (Transaction tx : oldChainTxns) { // Coinbase transactions on the old part of the chain are dead for good and won't come back unless // there's another re-org. if (tx.isCoinBase()) continue; log.info(" ->pending {}", tx.getTxId()); tx.getConfidence().setConfidenceType(ConfidenceType.PENDING); // Wipe height/depth/work data. confidenceChanged.put(tx, TransactionConfidence.Listener.ChangeReason.TYPE); addWalletTransaction(Pool.PENDING, tx); updateForSpends(tx, false); } // Note that dead transactions stay dead. Consider a chain that Finney attacks T1 and replaces it with // T2, so we move T1 into the dead pool. If there's now a re-org to a chain that doesn't include T2, it // doesn't matter - the miners deleted T1 from their mempool, will resurrect T2 and put that into the // mempool and so T1 is still seen as a losing double spend. // The old blocks have contributed to the depth for all the transactions in the // wallet that are in blocks up to and including the chain split block. // The total depth is calculated here and then subtracted from the appropriate transactions. int depthToSubtract = oldBlocks.size(); log.info("depthToSubtract = " + depthToSubtract); // Remove depthToSubtract from all transactions in the wallet except for pending. subtractDepth(depthToSubtract, spent.values()); subtractDepth(depthToSubtract, unspent.values()); subtractDepth(depthToSubtract, dead.values()); // The effective last seen block is now the split point so set the lastSeenBlockHash. setLastBlockSeenHash(splitPoint.getHeader().getHash()); // For each block in the new chain, work forwards calling receive() and notifyNewBestBlock(). // This will pull them back out of the pending pool, or if the tx didn't appear in the old chain and // does appear in the new chain, will treat it as such and possibly kill pending transactions that // conflict. for (StoredBlock block : newBlocks) { log.info("Replaying block {}", block.getHeader().getHashAsString()); for (TxOffsetPair pair : mapBlockTx.get(block.getHeader().getHash())) { log.info(" tx {}", pair.tx.getTxId()); try { receive(pair.tx, block, BlockChain.NewBlockType.BEST_CHAIN, pair.offset); } catch (ScriptException e) { throw new RuntimeException(e); // Cannot happen as these blocks were already verified. } } notifyNewBestBlock(block); } isConsistentOrThrow(); final Coin balance = getBalance(); log.info("post-reorg balance is {}", balance.toFriendlyString()); // Inform event listeners that a re-org took place. queueOnReorganize(); insideReorg = false; onWalletChangedSuppressions--; maybeQueueOnWalletChanged(); checkBalanceFuturesLocked(); informConfidenceListenersIfNotReorganizing(); saveLater(); } finally { lock.unlock(); } } /** * Subtract the supplied depth from the given transactions. */ private void subtractDepth(int depthToSubtract, Collection<Transaction> transactions) { for (Transaction tx : transactions) { if (tx.getConfidence().getConfidenceType() == ConfidenceType.BUILDING) { tx.getConfidence().setDepthInBlocks(tx.getConfidence().getDepthInBlocks() - depthToSubtract); confidenceChanged.put(tx, TransactionConfidence.Listener.ChangeReason.DEPTH); } } } //endregion /******************************************************************************************************************/ //region Bloom filtering private final List<TransactionOutPoint> bloomOutPoints = new ArrayList<>(); // Used to track whether we must automatically begin/end a filter calculation and calc outpoints/take the locks. private final AtomicInteger bloomFilterGuard = new AtomicInteger(0); @Override public void beginBloomFilterCalculation() { if (bloomFilterGuard.incrementAndGet() > 1) return; lock.lock(); keyChainGroupLock.lock(); //noinspection FieldAccessNotGuarded calcBloomOutPointsLocked(); } private void calcBloomOutPointsLocked() { // TODO: This could be done once and then kept up to date. bloomOutPoints.clear(); Set<Transaction> all = new HashSet<>(); all.addAll(unspent.values()); all.addAll(spent.values()); all.addAll(pending.values()); for (Transaction tx : all) { for (TransactionOutput out : tx.getOutputs()) { try { if (isTxOutputBloomFilterable(out)) bloomOutPoints.add(out.getOutPointFor()); } catch (ScriptException e) { // If it is ours, we parsed the script correctly, so this shouldn't happen. throw new RuntimeException(e); } } } } @Override @GuardedBy("keyChainGroupLock") public void endBloomFilterCalculation() { if (bloomFilterGuard.decrementAndGet() > 0) return; bloomOutPoints.clear(); keyChainGroupLock.unlock(); lock.unlock(); } /** * Returns the number of distinct data items (note: NOT keys) that will be inserted into a bloom filter, when it * is constructed. */ @Override public int getBloomFilterElementCount() { beginBloomFilterCalculation(); try { int size = bloomOutPoints.size(); size += keyChainGroup.getBloomFilterElementCount(); // Some scripts may have more than one bloom element. That should normally be okay, because under-counting // just increases false-positive rate. size += watchedScripts.size(); return size; } finally { endBloomFilterCalculation(); } } /** * Gets a bloom filter that contains all of the public keys from this wallet, and which will provide the given * false-positive rate. See the docs for {@link BloomFilter} for a brief explanation of anonymity when using filters. */ public BloomFilter getBloomFilter(double falsePositiveRate) { beginBloomFilterCalculation(); try { return getBloomFilter(getBloomFilterElementCount(), falsePositiveRate, new Random().nextInt()); } finally { endBloomFilterCalculation(); } } /** * <p>Gets a bloom filter that contains all of the public keys from this wallet, and which will provide the given * false-positive rate if it has size elements. Keep in mind that you will get 2 elements in the bloom filter for * each key in the wallet, for the public key and the hash of the public key (address form).</p> * * <p>This is used to generate a BloomFilter which can be {@link BloomFilter#merge(BloomFilter)}d with another. * It could also be used if you have a specific target for the filter's size.</p> * * <p>See the docs for {@link BloomFilter#BloomFilter(int, double, int, BloomFilter.BloomUpdate)} for a brief explanation of anonymity when using bloom * filters.</p> */ @Override @GuardedBy("keyChainGroupLock") public BloomFilter getBloomFilter(int size, double falsePositiveRate, int nTweak) { beginBloomFilterCalculation(); try { BloomFilter filter = keyChainGroup.getBloomFilter(size, falsePositiveRate, nTweak); for (Script script : watchedScripts) { for (ScriptChunk chunk : script.chunks()) { // Only add long (at least 64 bit) data to the bloom filter. // If any long constants become popular in scripts, we will need logic // here to exclude them. if (!chunk.isOpCode() && (chunk.data != null) && chunk.data.length >= MINIMUM_BLOOM_DATA_LENGTH) { filter.insert(chunk.data); } } } for (TransactionOutPoint point : bloomOutPoints) filter.insert(point); return filter; } finally { endBloomFilterCalculation(); } } // Returns true if the output is one that won't be selected by a data element matching in the scriptSig. private boolean isTxOutputBloomFilterable(TransactionOutput out) { Script script = out.getScriptPubKey(); boolean isScriptTypeSupported = ScriptPattern.isP2PK(script) || ScriptPattern.isP2SH(script) || ScriptPattern.isP2WPKH(script) || ScriptPattern.isP2WSH(script); return (isScriptTypeSupported && out.isMine(this)) || watchedScripts.contains(script); } /** * Used by {@link Peer} to decide whether or not to discard this block and any blocks building upon it, in case * the Bloom filter used to request them may be exhausted, that is, not have sufficient keys in the deterministic * sequence within it to reliably find relevant transactions. */ public boolean checkForFilterExhaustion(FilteredBlock block) { keyChainGroupLock.lock(); try { if (!keyChainGroup.supportsDeterministicChains()) return false; int epoch = keyChainGroup.getCombinedKeyLookaheadEpochs(); for (Transaction tx : block.getAssociatedTransactions().values()) { markKeysAsUsed(tx); } int newEpoch = keyChainGroup.getCombinedKeyLookaheadEpochs(); checkState(newEpoch >= epoch); // If the key lookahead epoch has advanced, there was a call to addKeys and the PeerGroup already has a // pending request to recalculate the filter queued up on another thread. The calling Peer should abandon // block at this point and await a new filter before restarting the download. return newEpoch > epoch; } finally { keyChainGroupLock.unlock(); } } //endregion // *************************************************************************************************************** //region Extensions to the wallet format. /** * By providing an object implementing the {@link WalletExtension} interface, you can save and load arbitrary * additional data that will be stored with the wallet. Each extension is identified by an ID, so attempting to * add the same extension twice (or two different objects that use the same ID) will throw an IllegalStateException. */ public void addExtension(WalletExtension extension) { String id = Objects.requireNonNull(extension).getWalletExtensionID(); lock.lock(); try { if (extensions.containsKey(id)) throw new IllegalStateException("Cannot add two extensions with the same ID: " + id); extensions.put(id, extension); saveNow(); } finally { lock.unlock(); } } /** * Atomically adds extension or returns an existing extension if there is one with the same id already present. */ public WalletExtension addOrGetExistingExtension(WalletExtension extension) { String id = Objects.requireNonNull(extension).getWalletExtensionID(); lock.lock(); try { WalletExtension previousExtension = extensions.get(id); if (previousExtension != null) return previousExtension; extensions.put(id, extension); saveNow(); return extension; } finally { lock.unlock(); } } /** * Either adds extension as a new extension or replaces the existing extension if one already exists with the same * id. This also triggers wallet auto-saving, so may be useful even when called with the same extension as is * already present. */ public void addOrUpdateExtension(WalletExtension extension) { String id = Objects.requireNonNull(extension).getWalletExtensionID(); lock.lock(); try { extensions.put(id, extension); saveNow(); } finally { lock.unlock(); } } /** Returns a snapshot of all registered extension objects. The extensions themselves are not copied. */ public Map<String, WalletExtension> getExtensions() { lock.lock(); try { return Collections.unmodifiableMap(new HashMap<>(extensions)); } finally { lock.unlock(); } } /** * Deserialize the wallet extension with the supplied data and then install it, replacing any existing extension * that may have existed with the same ID. If an exception is thrown then the extension is removed from the wallet, * if already present. */ public void deserializeExtension(WalletExtension extension, byte[] data) throws Exception { lock.lock(); keyChainGroupLock.lock(); try { // This method exists partly to establish a lock ordering of wallet > extension. extension.deserializeWalletExtension(this, data); extensions.put(extension.getWalletExtensionID(), extension); } catch (Throwable throwable) { log.error("Error during extension deserialization", throwable); extensions.remove(extension.getWalletExtensionID()); throw throwable; } finally { keyChainGroupLock.unlock(); lock.unlock(); } } /** * @deprecated Applications should use another mechanism to persist application state information */ @Override public void setTag(String tag, ByteString value) { super.setTag(tag, value); saveNow(); } //endregion /******************************************************************************************************************/ private static class FeeCalculation { // Selected UTXOs to spend public CoinSelection bestCoinSelection; // Change output (may be null if no change) public TransactionOutput bestChangeOutput; // List of output values adjusted downwards when recipients pay fees (may be null if no adjustment needed). public List<Coin> updatedOutputValues; } //region Fee calculation code private FeeCalculation calculateFee(SendRequest req, Coin value, boolean needAtLeastReferenceFee, List<TransactionOutput> candidates) throws InsufficientMoneyException { checkState(lock.isHeldByCurrentThread()); FeeCalculation result; Coin fee = Coin.ZERO; while (true) { result = new FeeCalculation(); Transaction tx = new Transaction(); addSuppliedInputs(tx, req.tx.getInputs()); Coin valueNeeded = req.recipientsPayFees ? value : value.add(fee); if (req.recipientsPayFees) { result.updatedOutputValues = new ArrayList<>(); } for (int i = 0; i < req.tx.getOutputs().size(); i++) { TransactionOutput output = TransactionOutput.read( ByteBuffer.wrap(req.tx.getOutput(i).serialize()), tx); if (req.recipientsPayFees) { // Subtract fee equally from each selected recipient output.setValue(output.getValue().subtract(fee.divide(req.tx.getOutputs().size()))); // first receiver pays the remainder not divisible by output count if (i == 0) { output.setValue( output.getValue().subtract(fee.divideAndRemainder(req.tx.getOutputs().size())[1])); // Subtract fee equally from each selected recipient } result.updatedOutputValues.add(output.getValue()); if (output.getMinNonDustValue().isGreaterThan(output.getValue())) { throw new CouldNotAdjustDownwards(); } } tx.addOutput(output); } CoinSelector selector = req.coinSelector == null ? coinSelector : req.coinSelector; // selector is allowed to modify candidates list. CoinSelection selection = selector.select(valueNeeded, new LinkedList<>(candidates)); result.bestCoinSelection = selection; // Can we afford this? if (selection.totalValue().compareTo(valueNeeded) < 0) { Coin valueMissing = valueNeeded.subtract(selection.totalValue()); throw new InsufficientMoneyException(valueMissing); } Coin change = selection.totalValue().subtract(valueNeeded); if (change.isGreaterThan(Coin.ZERO)) { // The value of the inputs is greater than what we want to send. Just like in real life then, // we need to take back some coins ... this is called "change". Add another output that sends the change // back to us. The address comes either from the request or currentChangeAddress() as a default. Address changeAddress = (req.changeAddress != null) ? req.changeAddress : currentChangeAddress(); TransactionOutput changeOutput = new TransactionOutput(tx, change, changeAddress); if (req.recipientsPayFees && changeOutput.isDust()) { // We do not move dust-change to fees, because the sender would end up paying more than requested. // This would be against the purpose of the all-inclusive feature. // So instead we raise the change and deduct from the first recipient. Coin missingToNotBeDust = changeOutput.getMinNonDustValue().subtract(changeOutput.getValue()); changeOutput.setValue(changeOutput.getValue().add(missingToNotBeDust)); TransactionOutput firstOutput = tx.getOutput(0); firstOutput.setValue(firstOutput.getValue().subtract(missingToNotBeDust)); result.updatedOutputValues.set(0, firstOutput.getValue()); if (firstOutput.isDust()) { throw new CouldNotAdjustDownwards(); } } if (changeOutput.isDust()) { // Never create dust outputs; if we would, just // add the dust to the fee. // Oscar comment: This seems like a way to make the condition below "if // (!fee.isLessThan(feeNeeded))" to become true. // This is a non-easy to understand way to do that. // Maybe there are other effects I am missing fee = fee.add(changeOutput.getValue()); } else { tx.addOutput(changeOutput); result.bestChangeOutput = changeOutput; } } for (TransactionOutput selectedOutput : selection.outputs()) { TransactionInput input = tx.addInput(selectedOutput); // If the scriptBytes don't default to none, our size calculations will be thrown off. checkState(input.getScriptBytes().length == 0); checkState(!input.hasWitness()); } Coin feePerKb = (needAtLeastReferenceFee && req.feePerKb.compareTo(Transaction.REFERENCE_DEFAULT_MIN_TX_FEE) < 0) ? Transaction.REFERENCE_DEFAULT_MIN_TX_FEE : req.feePerKb; final int vsize = tx.getVsize() + estimateVirtualBytesForSigning(selection); Coin feeNeeded = feePerKb.multiply(vsize).divide(1000); if (!fee.isLessThan(feeNeeded)) { // Done, enough fee included. break; } // Include more fee and try again. fee = feeNeeded; } return result; } private void addSuppliedInputs(Transaction tx, List<TransactionInput> originalInputs) { for (TransactionInput input : originalInputs) tx.addInput(TransactionInput.read(ByteBuffer.wrap(input.bitcoinSerialize()), tx)); } private int estimateVirtualBytesForSigning(CoinSelection selection) { int vsize = 0; for (TransactionOutput output : selection.outputs()) { try { Script script = output.getScriptPubKey(); ECKey key = null; Script redeemScript = null; if (ScriptPattern.isP2PKH(script)) { key = findKeyFromPubKeyHash(ScriptPattern.extractHashFromP2PKH(script), ScriptType.P2PKH); Objects.requireNonNull(key, "Coin selection includes unspendable outputs"); vsize += script.getNumberOfBytesRequiredToSpend(key, redeemScript); } else if (ScriptPattern.isP2WPKH(script)) { key = findKeyFromPubKeyHash(ScriptPattern.extractHashFromP2WH(script), ScriptType.P2WPKH); Objects.requireNonNull(key, "Coin selection includes unspendable outputs"); vsize += IntMath.divide(script.getNumberOfBytesRequiredToSpend(key, redeemScript), 4, RoundingMode.CEILING); // round up } else if (ScriptPattern.isP2SH(script)) { redeemScript = findRedeemDataFromScriptHash(ScriptPattern.extractHashFromP2SH(script)).redeemScript; Objects.requireNonNull(redeemScript, "Coin selection includes unspendable outputs"); vsize += script.getNumberOfBytesRequiredToSpend(key, redeemScript); } else { vsize += script.getNumberOfBytesRequiredToSpend(key, redeemScript); } } catch (ScriptException e) { // If this happens it means an output script in a wallet tx could not be understood. That should never // happen, if it does it means the wallet has got into an inconsistent state. throw new IllegalStateException(e); } } return vsize; } //endregion // *************************************************************************************************************** //region Wallet maintenance transactions // Wallet maintenance transactions. These transactions may not be directly connected to a payment the user is // making. They may be instead key rotation transactions for when old keys are suspected to be compromised, // de/re-fragmentation transactions for when our output sizes are inappropriate or suboptimal, privacy transactions // and so on. Because these transactions may require user intervention in some way (e.g. entering their password) // the wallet application is expected to poll the Wallet class to get SendRequests. Ideally security systems like // hardware wallets or risk analysis providers are programmed to auto-approve transactions that send from our own // keys back to our own keys. /** * <p>Specifies that the given {@link TransactionBroadcaster}, typically a {@link PeerGroup}, should be used for * sending transactions to the Bitcoin network by default. Some sendCoins methods let you specify a broadcaster * explicitly, in that case, they don't use this broadcaster. If null is specified then the wallet won't attempt * to broadcast transactions itself.</p> * * <p>You don't normally need to call this. A {@link PeerGroup} will automatically set itself as the wallets * broadcaster when you use {@link PeerGroup#addWallet(Wallet)}. A wallet can use the broadcaster when you ask * it to send money, but in future also at other times to implement various features that may require asynchronous * re-organisation of the wallet contents on the block chain. For instance, in future the wallet may choose to * optimise itself to reduce fees or improve privacy.</p> */ public void setTransactionBroadcaster(@Nullable org.bitcoinj.core.TransactionBroadcaster broadcaster) { Transaction[] toBroadcast = {}; lock.lock(); try { if (vTransactionBroadcaster == broadcaster) return; vTransactionBroadcaster = broadcaster; if (broadcaster == null) return; toBroadcast = pending.values().toArray(toBroadcast); } finally { lock.unlock(); } // Now use it to upload any pending transactions we have that are marked as not being seen by any peers yet. // Don't hold the wallet lock whilst doing this, so if the broadcaster accesses the wallet at some point there // is no inversion. for (Transaction tx : toBroadcast) { ConfidenceType confidenceType = tx.getConfidence().getConfidenceType(); checkState(confidenceType == ConfidenceType.PENDING || confidenceType == ConfidenceType.IN_CONFLICT, () -> "Tx " + tx.getTxId() + ": expected PENDING or IN_CONFLICT, was " + confidenceType); // Re-broadcast even if it's marked as already seen for two reasons // 1) Old wallets may have transactions marked as broadcast by 1 peer when in reality the network // never saw it, due to bugs. // 2) It can't really hurt. log.info("New broadcaster so uploading waiting tx {}", tx.getTxId()); broadcaster.broadcastTransaction(tx); } } /** * <p> * When a key rotation time is set, any money controlled by keys created before the given timestamp T will be * respent to any key that was created after T. This can be used to recover from a situation where a set of keys is * believed to be compromised. The rotation time is persisted to the wallet. You can stop key rotation by calling * this method again with {@code null} as the argument. * </p> * * <p> * Once set up, calling {@link #doMaintenance(AesKey, boolean)} will create and possibly send rotation * transactions: but it won't be done automatically (because you might have to ask for the users password). This may * need to be repeated regularly in case new coins keep coming in on rotating addresses/keys. * </p> * * <p> * The given time cannot be in the future. * </p> * @param keyRotationTime rotate any keys created before this time, or null for no rotation */ public void setKeyRotationTime(@Nullable Instant keyRotationTime) { checkArgument(keyRotationTime == null || keyRotationTime.compareTo(TimeUtils.currentTime()) <= 0, () -> "given time cannot be in the future: " + TimeUtils.dateTimeFormat(keyRotationTime)); vKeyRotationTime = keyRotationTime; saveNow(); } /** @deprecated use {@link #setKeyRotationTime(Instant)} */ @Deprecated public void setKeyRotationTime(long timeSecs) { if (timeSecs == 0) setKeyRotationTime((Instant) null); else setKeyRotationTime(Instant.ofEpochSecond(timeSecs)); } /** @deprecated use {@link #setKeyRotationTime(Instant)} */ @Deprecated public void setKeyRotationTime(@Nullable Date time) { if (time == null) setKeyRotationTime((Instant) null); else setKeyRotationTime(Instant.ofEpochMilli(time.getTime())); } /** * Returns the key rotation time, or empty if unconfigured. See {@link #setKeyRotationTime(Instant)} for a description * of the field. */ public Optional<Instant> keyRotationTime() { return Optional.ofNullable(vKeyRotationTime); } /** @deprecated use {@link #keyRotationTime()} */ @Deprecated public @Nullable Date getKeyRotationTime() { Instant keyRotationTime = vKeyRotationTime; if (keyRotationTime != null) return Date.from(keyRotationTime); else return null; } /** Returns whether the keys creation time is before the key rotation time, if one was set. */ public boolean isKeyRotating(ECKey key) { Instant keyRotationTime = vKeyRotationTime; return keyRotationTime != null && key.creationTime().orElse(Instant.EPOCH).isBefore(keyRotationTime); } /** * A wallet app should call this from time to time in order to let the wallet craft and send transactions needed * to re-organise coins internally. A good time to call this would be after receiving coins for an unencrypted * wallet, or after sending money for an encrypted wallet. If you have an encrypted wallet and just want to know * if some maintenance needs doing, call this method with andSend set to false and look at the returned list of * transactions. Maintenance might also include internal changes that involve some processing or work but * which don't require making transactions - these will happen automatically unless the password is required * in which case an exception will be thrown. * @param aesKey the users password, if any. * @param signAndSend if true, send the transactions via the tx broadcaster and return them, if false just return them. * * @return A list of transactions that the wallet just made/will make for internal maintenance. Might be empty. * @throws org.bitcoinj.wallet.DeterministicUpgradeRequiresPassword if key rotation requires the users password. */ public ListenableCompletableFuture<List<Transaction>> doMaintenance(@Nullable AesKey aesKey, boolean signAndSend) throws DeterministicUpgradeRequiresPassword { return doMaintenance(KeyChainGroupStructure.BIP32, aesKey, signAndSend); } /** * A wallet app should call this from time to time in order to let the wallet craft and send transactions needed * to re-organise coins internally. A good time to call this would be after receiving coins for an unencrypted * wallet, or after sending money for an encrypted wallet. If you have an encrypted wallet and just want to know * if some maintenance needs doing, call this method with andSend set to false and look at the returned list of * transactions. Maintenance might also include internal changes that involve some processing or work but * which don't require making transactions - these will happen automatically unless the password is required * in which case an exception will be thrown. * @param structure to derive the account path from if a new seed needs to be created * @param aesKey the users password, if any. * @param signAndSend if true, send the transactions via the tx broadcaster and return them, if false just return them. * * @return A list of transactions that the wallet just made/will make for internal maintenance. Might be empty. * @throws org.bitcoinj.wallet.DeterministicUpgradeRequiresPassword if key rotation requires the users password. */ public ListenableCompletableFuture<List<Transaction>> doMaintenance(KeyChainGroupStructure structure, @Nullable AesKey aesKey, boolean signAndSend) throws DeterministicUpgradeRequiresPassword { List<Transaction> txns; lock.lock(); keyChainGroupLock.lock(); try { txns = maybeRotateKeys(structure, aesKey, signAndSend); if (!signAndSend) return ListenableCompletableFuture.completedFuture(txns); } finally { keyChainGroupLock.unlock(); lock.unlock(); } checkState(!lock.isHeldByCurrentThread()); List<CompletableFuture<Transaction>> futures = new ArrayList<>(txns.size()); TransactionBroadcaster broadcaster = vTransactionBroadcaster; for (Transaction tx : txns) { try { final CompletableFuture<Transaction> future = broadcaster.broadcastTransaction(tx) .awaitRelayed() .thenApply(TransactionBroadcast::transaction); futures.add(future); future.whenComplete((transaction, throwable) -> { if (transaction != null) { log.info("Successfully broadcast key rotation tx: {}", transaction); } else { log.error("Failed to broadcast key rotation tx", throwable); } }); } catch (Exception e) { log.error("Failed to broadcast rekey tx", e); } } return ListenableCompletableFuture.of(FutureUtils.allAsList(futures)); } // Checks to see if any coins are controlled by rotating keys and if so, spends them. @GuardedBy("keyChainGroupLock") private List<Transaction> maybeRotateKeys(KeyChainGroupStructure structure, @Nullable AesKey aesKey, boolean sign) throws DeterministicUpgradeRequiresPassword { checkState(lock.isHeldByCurrentThread()); checkState(keyChainGroupLock.isHeldByCurrentThread()); List<Transaction> results = new LinkedList<>(); // TODO: Handle chain replays here. Instant keyRotationTime = vKeyRotationTime; if (keyRotationTime == null) return results; // Nothing to do. // We might have to create a new HD hierarchy if the previous ones are now rotating. boolean allChainsRotating = true; ScriptType preferredScriptType = ScriptType.P2PKH; if (keyChainGroup.supportsDeterministicChains()) { for (DeterministicKeyChain chain : keyChainGroup.getDeterministicKeyChains()) { if (chain.earliestKeyCreationTime().compareTo(keyRotationTime) >= 0) allChainsRotating = false; else preferredScriptType = chain.getOutputScriptType(); } } if (allChainsRotating) { try { if (keyChainGroup.getImportedKeys().isEmpty()) { log.info( "All deterministic chains are currently rotating and we have no random keys, creating fresh {} chain: backup required after this.", preferredScriptType); KeyChainGroup newChains = KeyChainGroup.builder(network, structure).fromRandom(preferredScriptType) .build(); if (keyChainGroup.isEncrypted()) { if (aesKey == null) throw new DeterministicUpgradeRequiresPassword(); KeyCrypter keyCrypter = keyChainGroup.getKeyCrypter(); keyChainGroup.decrypt(aesKey); keyChainGroup.mergeActiveKeyChains(newChains, keyRotationTime); keyChainGroup.encrypt(keyCrypter, aesKey); } else { keyChainGroup.mergeActiveKeyChains(newChains, keyRotationTime); } } else { log.info( "All deterministic chains are currently rotating, creating a new {} one from the next oldest non-rotating key material...", preferredScriptType); keyChainGroup.upgradeToDeterministic(preferredScriptType, structure, keyRotationTime, aesKey); log.info("...upgraded to HD again, based on next best oldest key."); } } catch (AllRandomKeysRotating rotating) { log.info( "No non-rotating random keys available, generating entirely new {} tree: backup required after this.", preferredScriptType); KeyChainGroup newChains = KeyChainGroup.builder(network, structure).fromRandom(preferredScriptType) .build(); if (keyChainGroup.isEncrypted()) { if (aesKey == null) throw new DeterministicUpgradeRequiresPassword(); KeyCrypter keyCrypter = keyChainGroup.getKeyCrypter(); keyChainGroup.decrypt(aesKey); keyChainGroup.mergeActiveKeyChains(newChains, keyRotationTime); keyChainGroup.encrypt(keyCrypter, aesKey); } else { keyChainGroup.mergeActiveKeyChains(newChains, keyRotationTime); } } saveNow(); } // Because transactions are size limited, we might not be able to re-key the entire wallet in one go. So // loop around here until we no longer produce transactions with the max number of inputs. That means we're // fully done, at least for now (we may still get more transactions later and this method will be reinvoked). Transaction tx; do { tx = rekeyOneBatch(keyRotationTime, aesKey, results, sign); if (tx != null) results.add(tx); } while (tx != null && tx.getInputs().size() == KeyTimeCoinSelector.MAX_SIMULTANEOUS_INPUTS); return results; } @Nullable private Transaction rekeyOneBatch(Instant time, @Nullable AesKey aesKey, List<Transaction> others, boolean sign) { lock.lock(); try { // Build the transaction using some custom logic for our special needs. Last parameter to // KeyTimeCoinSelector is whether to ignore pending transactions or not. // // We ignore pending outputs because trying to rotate these is basically racing an attacker, and // we're quite likely to lose and create stuck double spends. Also, some users who have 0.9 wallets // have already got stuck double spends in their wallet due to the Bloom-filtering block reordering // bug that was fixed in 0.10, thus, making a re-key transaction depend on those would cause it to // never confirm at all. CoinSelector keyTimeSelector = new KeyTimeCoinSelector(this, time, true); FilteringCoinSelector selector = new FilteringCoinSelector(keyTimeSelector); for (Transaction other : others) selector.excludeOutputsSpentBy(other); // TODO: Make this use the standard SendRequest. CoinSelection toMove = selector.select(Coin.ZERO, calculateAllSpendCandidates()); if (toMove.totalValue().equals(Coin.ZERO)) return null; // Nothing to do. Transaction rekeyTx = new Transaction(); for (TransactionOutput output : toMove.outputs()) { rekeyTx.addInput(output); } // When not signing, don't waste addresses. rekeyTx.addOutput(toMove.totalValue(), sign ? freshReceiveAddress() : currentReceiveAddress()); if (!adjustOutputDownwardsForFee(rekeyTx, toMove, Transaction.DEFAULT_TX_FEE, true)) { log.error("Failed to adjust rekey tx for fees."); return null; } rekeyTx.getConfidence().setSource(TransactionConfidence.Source.SELF); rekeyTx.setPurpose(Transaction.Purpose.KEY_ROTATION); SendRequest req = SendRequest.forTx(rekeyTx); req.aesKey = aesKey; if (sign) signTransaction(req); // KeyTimeCoinSelector should never select enough inputs to push us oversize. checkState(rekeyTx.serialize().length < Transaction.MAX_STANDARD_TX_SIZE); return rekeyTx; } catch (VerificationException e) { throw new RuntimeException(e); // Cannot happen. } finally { lock.unlock(); } } //endregion }
282,437
47.00102
272
java
bitcoinj
bitcoinj-master/core/src/main/java/org/bitcoinj/wallet/DeterministicKeyChain.java
/* * Copyright by the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.bitcoinj.wallet; import com.google.common.base.MoreObjects; import com.google.protobuf.ByteString; import org.bitcoinj.base.Network; import org.bitcoinj.base.ScriptType; import org.bitcoinj.base.internal.Stopwatch; import org.bitcoinj.base.internal.TimeUtils; import org.bitcoinj.crypto.AesKey; import org.bitcoinj.base.internal.ByteUtils; import org.bitcoinj.base.internal.StreamUtils; import org.bitcoinj.core.BloomFilter; import org.bitcoinj.crypto.ECKey; import org.bitcoinj.core.NetworkParameters; import org.bitcoinj.base.internal.InternalUtils; import org.bitcoinj.crypto.ChildNumber; import org.bitcoinj.crypto.DeterministicHierarchy; import org.bitcoinj.crypto.DeterministicKey; import org.bitcoinj.crypto.EncryptedData; import org.bitcoinj.crypto.HDKeyDerivation; import org.bitcoinj.crypto.HDPath; import org.bitcoinj.crypto.KeyCrypter; import org.bitcoinj.crypto.KeyCrypterException; import org.bitcoinj.crypto.KeyCrypterScrypt; import org.bitcoinj.crypto.LazyECPoint; import org.bitcoinj.crypto.MnemonicCode; import org.bitcoinj.script.Script; import org.bitcoinj.utils.ListenerRegistration; import org.bitcoinj.utils.Threading; import org.bitcoinj.wallet.listeners.KeyChainEventListener; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.annotation.Nullable; import java.math.BigInteger; import java.security.SecureRandom; import java.time.Instant; import java.util.ArrayList; import java.util.Arrays; import java.util.LinkedList; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Objects; import java.util.Optional; import java.util.concurrent.Executor; import java.util.concurrent.locks.ReentrantLock; import java.util.function.Predicate; import java.util.stream.Stream; import static org.bitcoinj.base.internal.Preconditions.checkArgument; import static org.bitcoinj.base.internal.Preconditions.checkState; /** * <p>A deterministic key chain is a {@link KeyChain} that uses the * <a href="https://github.com/bitcoin/bips/blob/master/bip-0032.mediawiki">BIP 32 standard</a>, as implemented by * {@link DeterministicHierarchy}, to derive all the keys in the keychain from a master seed. * This type of wallet is extremely convenient and flexible. Although backing up full wallet files is always a good * idea, to recover money only the root seed needs to be preserved and that is a number small enough that it can be * written down on paper or, when represented using a BIP 39 {@link MnemonicCode}, * dictated over the phone (possibly even memorized).</p> * * <p>Deterministic key chains have other advantages: parts of the key tree can be selectively revealed to allow * for auditing, and new public keys can be generated without access to the private keys, yielding a highly secure * configuration for web servers which can accept payments into a wallet but not spend from them. This does not work * quite how you would expect due to a quirk of elliptic curve mathematics and the techniques used to deal with it. * A watching wallet is not instantiated using the public part of the master key as you may imagine. Instead, you * need to take the account key (first child of the master key) and provide the public part of that to the watching * wallet instead. You can do this by calling {@link #getWatchingKey()} and then serializing it with * {@link DeterministicKey#serializePubB58(Network)}. The resulting "xpub..." string encodes * sufficient information about the account key to create a watching chain via * {@link DeterministicKey#deserializeB58(DeterministicKey, String, Network)} * (with null as the first parameter) and then * {@link Builder#watch(DeterministicKey)}.</p> * * <p>This class builds on {@link DeterministicHierarchy} and * {@link DeterministicKey} by adding support for serialization to and from protobufs, * and encryption of parts of the key tree. Internally it arranges itself as per the BIP 32 spec, with the seed being * used to derive a master key, which is then used to derive an account key, the account key is used to derive two * child keys called the <i>internal</i> and <i>external</i> parent keys (for change and handing out addresses respectively) * and finally the actual leaf keys that users use hanging off the end. The leaf keys are special in that they don't * internally store the private part at all, instead choosing to rederive the private key from the parent when * needed for signing. This simplifies the design for encrypted key chains.</p> * * <p>The key chain manages a <i>lookahead zone</i>. This zone is required because when scanning the chain, you don't * know exactly which keys might receive payments. The user may have handed out several addresses and received payments * on them, but for latency reasons the block chain is requested from remote peers in bulk, meaning you must * "look ahead" when calculating keys to put in the Bloom filter. The default lookahead zone is 100 keys, meaning if * the user hands out more than 100 addresses and receives payment on them before the chain is next scanned, some * transactions might be missed. 100 is a reasonable choice for consumer wallets running on CPU constrained devices. * For industrial wallets that are receiving keys all the time, a higher value is more appropriate. Ideally DKC and the * wallet would know how to adjust this value automatically, but that's not implemented at the moment.</p> * * <p>In fact the real size of the lookahead zone is larger than requested, by default, it's one third larger. This * is because the act of deriving new keys means recalculating the Bloom filters and this is an expensive operation. * Thus, to ensure we don't have to recalculate on every single new key/address requested or seen we add more buffer * space and only extend the lookahead zone when that buffer is exhausted. For example with a lookahead zone of 100 * keys, you can request 33 keys before more keys will be calculated and the Bloom filter rebuilt and rebroadcast. * But even when you are requesting the 33rd key, you will still be looking 100 keys ahead. * </p> * * @author Andreas Schildbach */ public class DeterministicKeyChain implements EncryptableKeyChain { private static final Logger log = LoggerFactory.getLogger(DeterministicKeyChain.class); protected final ReentrantLock lock = Threading.lock(DeterministicKeyChain.class); public static final String DEFAULT_PASSPHRASE_FOR_MNEMONIC = ""; private DeterministicHierarchy hierarchy; @Nullable private DeterministicKey rootKey; @Nullable private final DeterministicSeed seed; private final ScriptType outputScriptType; private final HDPath accountPath; // Paths through the key tree. External keys are ones that are communicated to other parties. Internal keys are // keys created for change addresses, coinbases, mixing, etc - anything that isn't communicated. The distinction // is somewhat arbitrary but can be useful for audits. The first number is the "account number" but we don't use // that feature yet. In future we might hand out different accounts for cases where we wish to hand payers // a payment request that can generate lots of addresses independently. // The account path may be overridden by subclasses. // m / 0' public static final HDPath ACCOUNT_ZERO_PATH = HDPath.M(ChildNumber.ZERO_HARDENED); // m / 1' public static final HDPath ACCOUNT_ONE_PATH = HDPath.M(ChildNumber.ONE_HARDENED); // m / 44' / 0' / 0' public static final HDPath BIP44_ACCOUNT_ZERO_PATH = HDPath.M(new ChildNumber(44, true)) .extend(ChildNumber.ZERO_HARDENED, ChildNumber.ZERO_HARDENED); public static final HDPath EXTERNAL_SUBPATH = HDPath.M(ChildNumber.ZERO); public static final HDPath INTERNAL_SUBPATH = HDPath.M(ChildNumber.ONE); // We try to ensure we have at least this many keys ready and waiting to be handed out via getKey(). // See docs for getLookaheadSize() for more info on what this is for. The -1 value means it hasn't been calculated // yet. For new chains it's set to whatever the default is, unless overridden by setLookaheadSize. For deserialized // chains, it will be calculated on demand from the number of loaded keys. private static final int LAZY_CALCULATE_LOOKAHEAD = -1; protected int lookaheadSize = 100; // The lookahead threshold causes us to batch up creation of new keys to minimize the frequency of Bloom filter // regenerations, which are expensive and will (in future) trigger chain download stalls/retries. One third // is an efficiency tradeoff. protected int lookaheadThreshold = calcDefaultLookaheadThreshold(); private int calcDefaultLookaheadThreshold() { return lookaheadSize / 3; } // The parent keys for external keys (handed out to other people) and internal keys (used for change addresses). private DeterministicKey externalParentKey, internalParentKey; // How many keys on each path have actually been used. This may be fewer than the number that have been deserialized // or held in memory, because of the lookahead zone. private int issuedExternalKeys, issuedInternalKeys; // A counter that is incremented each time a key in the lookahead threshold zone is marked as used and lookahead // is triggered. The Wallet/KCG reads these counters and combines them so it can tell the Peer whether to throw // away the current block (and any future blocks in the same download batch) and restart chain sync once a new // filter has been calculated. This field isn't persisted to the wallet as it's only relevant within a network // session. private int keyLookaheadEpoch; // We simplify by wrapping a basic key chain and that way we get some functionality like key lookup and event // listeners "for free". All keys in the key tree appear here, even if they aren't meant to be used for receiving // money. private final BasicKeyChain basicKeyChain; // If set this chain is following another chain. Was used in a married KeyChainGroup. private boolean isFollowing; // holds a number of signatures required to spend. It's the N from N-of-M CHECKMULTISIG script for P2SH transactions // and always 1 for other transaction types. Was used in a married KeyChainGroup. private int sigsRequiredToSpend = 1; public static class Builder<T extends Builder<T>> { protected SecureRandom random; protected int bits = DeterministicSeed.DEFAULT_SEED_ENTROPY_BITS; protected String passphrase; @Nullable protected Instant creationTime = null; protected byte[] entropy; protected DeterministicSeed seed; protected ScriptType outputScriptType = ScriptType.P2PKH; protected DeterministicKey watchingKey = null; protected DeterministicKey spendingKey = null; protected HDPath accountPath = null; protected Builder() { } @SuppressWarnings("unchecked") protected T self() { return (T)this; } /** * Creates a deterministic key chain starting from the given entropy. All keys yielded by this chain will be the same * if the starting entropy is the same. You should provide the creation time for the * chain: this lets us know from what part of the chain we can expect to see derived keys appear. * @param entropy entropy to create the chain with * @param creationTime creation time for the chain */ public T entropy(byte[] entropy, Instant creationTime) { this.entropy = entropy; this.creationTime = Objects.requireNonNull(creationTime); return self(); } /** @deprecated use {@link #entropy(byte[], Instant)} */ @Deprecated public T entropy(byte[] entropy, long creationTimeSecs) { checkArgument(creationTimeSecs > 0); return entropy(entropy, Instant.ofEpochSecond(creationTimeSecs)); } /** * Creates a deterministic key chain starting from the given seed. All keys yielded by this chain will be the same * if the starting seed is the same. */ public T seed(DeterministicSeed seed) { this.seed = seed; return self(); } /** * Generates a new key chain with entropy selected randomly from the given {@link SecureRandom} * object and of the requested size in bits. The derived seed is further protected with a user selected passphrase * (see BIP 39). * @param random the random number generator - use new SecureRandom(). * @param bits The number of bits of entropy to use when generating entropy. Either 128 (default), 192 or 256. */ public T random(SecureRandom random, int bits) { this.random = random; this.bits = bits; return self(); } /** * Generates a new key chain with 128 bits of entropy selected randomly from the given {@link SecureRandom} * object. The derived seed is further protected with a user selected passphrase * (see BIP 39). * @param random the random number generator - use new SecureRandom(). */ public T random(SecureRandom random) { this.random = random; return self(); } /** * Creates a key chain that watches the given account key. */ public T watch(DeterministicKey accountKey) { checkState(accountPath == null, () -> "either watch or accountPath"); this.watchingKey = accountKey; return self(); } /** * Creates a key chain that can spend from the given account key. */ public T spend(DeterministicKey accountKey) { checkState(accountPath == null, () -> "either spend or accountPath"); this.spendingKey = accountKey; return self(); } public T outputScriptType(ScriptType outputScriptType) { this.outputScriptType = outputScriptType; return self(); } /** The passphrase to use with the generated mnemonic, or null if you would like to use the default empty string. Currently must be the empty string. */ public T passphrase(String passphrase) { // FIXME support non-empty passphrase this.passphrase = passphrase; return self(); } /** * Use an account path other than the default {@link DeterministicKeyChain#ACCOUNT_ZERO_PATH}. */ public T accountPath(List<ChildNumber> accountPath) { checkState(watchingKey == null, () -> "either watch or accountPath"); this.accountPath = HDPath.M(Objects.requireNonNull(accountPath)); return self(); } public DeterministicKeyChain build() { checkState(passphrase == null || seed == null, () -> "passphrase must not be specified with seed"); if (accountPath == null) accountPath = ACCOUNT_ZERO_PATH; if (random != null) // Default passphrase to "" if not specified return new DeterministicKeyChain(DeterministicSeed.ofRandom(random, bits, getPassphrase()), null, outputScriptType, accountPath); else if (entropy != null) return new DeterministicKeyChain(DeterministicSeed.ofEntropy(entropy, getPassphrase(), creationTime), null, outputScriptType, accountPath); else if (seed != null) return new DeterministicKeyChain(seed, null, outputScriptType, accountPath); else if (watchingKey != null) return new DeterministicKeyChain(watchingKey, false, true, outputScriptType); else if (spendingKey != null) return new DeterministicKeyChain(spendingKey, false, false, outputScriptType); else throw new IllegalStateException(); } protected String getPassphrase() { return passphrase != null ? passphrase : DEFAULT_PASSPHRASE_FOR_MNEMONIC; } } public static Builder<?> builder() { return new Builder<>(); } /** * <p> * Creates a deterministic key chain from a watched or spendable account key. If {@code isWatching} flag is set, * then creates a deterministic key chain that watches the given (public only) root key. You can use this to * calculate balances and generally follow along, but spending is not possible with such a chain. If it is not set, * then this creates a deterministic key chain that allows spending. If {@code isFollowing} flag is set(only allowed * if {@code isWatching} is set) then this keychain follows some other keychain. In a married wallet following * keychain represents "spouse's" keychain. * </p> * * <p> * This constructor is not stable across releases! If you need a stable API, use {@link #builder()} to use a * {@link Builder}. * </p> */ public DeterministicKeyChain(DeterministicKey key, boolean isFollowing, boolean isWatching, ScriptType outputScriptType) { if (isWatching) checkArgument(key.isPubKeyOnly(), () -> "private subtrees not currently supported for watching keys: if you got this key from DKC.getWatchingKey() then use .dropPrivate().dropParent() on it first"); else checkArgument(key.hasPrivKey(), () -> "private subtrees are required"); checkArgument(isWatching || !isFollowing, () -> "can only follow a key that is watched"); basicKeyChain = new BasicKeyChain(); this.seed = null; this.rootKey = null; basicKeyChain.importKey(key); hierarchy = new DeterministicHierarchy(key); this.accountPath = key.getPath(); this.outputScriptType = outputScriptType; initializeHierarchyUnencrypted(); this.isFollowing = isFollowing; } /** * <p> * Creates a deterministic key chain with an encrypted deterministic seed using the provided account path. Using * {@link KeyCrypter KeyCrypter} to decrypt. * </p> * * <p> * This constructor is not stable across releases! If you need a stable API, use {@link #builder()} to use a * {@link Builder}. * </p> */ protected DeterministicKeyChain(DeterministicSeed seed, @Nullable KeyCrypter crypter, ScriptType outputScriptType, List<ChildNumber> accountPath) { checkArgument(outputScriptType == null || outputScriptType == ScriptType.P2PKH || outputScriptType == ScriptType.P2WPKH, () -> "only P2PKH or P2WPKH allowed"); this.outputScriptType = outputScriptType != null ? outputScriptType : ScriptType.P2PKH; this.accountPath = HDPath.M(accountPath); this.seed = seed; basicKeyChain = new BasicKeyChain(crypter); if (!seed.isEncrypted()) { rootKey = HDKeyDerivation.createMasterPrivateKey(Objects.requireNonNull(seed.getSeedBytes())); Optional<Instant> creationTime = seed.creationTime(); if (creationTime.isPresent()) rootKey.setCreationTime(creationTime.get()); else rootKey.clearCreationTime(); basicKeyChain.importKey(rootKey); hierarchy = new DeterministicHierarchy(rootKey); for (HDPath path : getAccountPath().ancestors(true)) { basicKeyChain.importKey(hierarchy.get(path, false, true)); } initializeHierarchyUnencrypted(); } // Else... // We can't initialize ourselves with just an encrypted seed, so we expected deserialization code to do the // rest of the setup (loading the root key). } /** * For use in encryption when {@link #toEncrypted(KeyCrypter, AesKey)} is called, so that * subclasses can override that method and create an instance of the right class. * * See also {@link #makeKeyChainFromSeed(DeterministicSeed, List, ScriptType)} */ protected DeterministicKeyChain(KeyCrypter crypter, AesKey aesKey, DeterministicKeyChain chain) { // Can't encrypt a watching chain. Objects.requireNonNull(chain.rootKey); Objects.requireNonNull(chain.seed); checkArgument(!chain.rootKey.isEncrypted(), () -> "chain already encrypted"); this.accountPath = chain.getAccountPath(); this.outputScriptType = chain.outputScriptType; this.issuedExternalKeys = chain.issuedExternalKeys; this.issuedInternalKeys = chain.issuedInternalKeys; this.lookaheadSize = chain.lookaheadSize; this.lookaheadThreshold = chain.lookaheadThreshold; this.seed = chain.seed.encrypt(crypter, aesKey); basicKeyChain = new BasicKeyChain(crypter); // The first number is the "account number" but we don't use that feature. rootKey = chain.rootKey.encrypt(crypter, aesKey, null); hierarchy = new DeterministicHierarchy(rootKey); basicKeyChain.importKey(rootKey); for (HDPath path : getAccountPath().ancestors()) { encryptNonLeaf(aesKey, chain, rootKey, path); } DeterministicKey account = encryptNonLeaf(aesKey, chain, rootKey, getAccountPath()); externalParentKey = encryptNonLeaf(aesKey, chain, account, getAccountPath().extend(EXTERNAL_SUBPATH)); internalParentKey = encryptNonLeaf(aesKey, chain, account, getAccountPath().extend(INTERNAL_SUBPATH)); // Now copy the (pubkey only) leaf keys across to avoid rederiving them. The private key bytes are missing // anyway so there's nothing to encrypt. for (DeterministicKey key : chain.getLeafKeys()) { putKey(cloneKey(hierarchy, key)); } for (ListenerRegistration<KeyChainEventListener> listener : chain.basicKeyChain.getListeners()) { basicKeyChain.addEventListener(listener); } } public HDPath getAccountPath() { return accountPath; } public ScriptType getOutputScriptType() { return outputScriptType; } private DeterministicKey encryptNonLeaf(AesKey aesKey, DeterministicKeyChain chain, DeterministicKey parent, List<ChildNumber> path) { DeterministicKey key = chain.hierarchy.get(path, false, false); key = key.encrypt(Objects.requireNonNull(basicKeyChain.getKeyCrypter()), aesKey, parent); putKey(key); return key; } // Derives the account path keys and inserts them into the basic key chain. This is important to preserve their // order for serialization, amongst other things. private void initializeHierarchyUnencrypted() { externalParentKey = hierarchy.deriveChild(getAccountPath(), false, false, ChildNumber.ZERO); internalParentKey = hierarchy.deriveChild(getAccountPath(), false, false, ChildNumber.ONE); basicKeyChain.importKey(externalParentKey); basicKeyChain.importKey(internalParentKey); } /** Returns a freshly derived key that has not been returned by this method before. */ @Override public DeterministicKey getKey(KeyPurpose purpose) { return getKeys(purpose, 1).get(0); } /** Returns freshly derived key/s that have not been returned by this method before. */ @Override public List<DeterministicKey> getKeys(KeyPurpose purpose, int numberOfKeys) { checkArgument(numberOfKeys > 0); lock.lock(); try { DeterministicKey parentKey; int index; switch (purpose) { // Map both REFUND and RECEIVE_KEYS to the same branch for now. Refunds are a feature of the BIP 70 // payment protocol. Later we may wish to map it to a different branch (in a new wallet version?). // This would allow a watching wallet to only be able to see inbound payments, but not change // (i.e. spends) or refunds. Might be useful for auditing ... 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(); } // Optimization: potentially do a very quick key generation for just the number of keys we need if we // didn't already create them, ignoring the configured lookahead size. This ensures we'll be able to // retrieve the keys in the following loop, but if we're totally fresh and didn't get a chance to // calculate the lookahead keys yet, this will not block waiting to calculate 100+ EC point multiplies. // On slow/crappy Android phones looking ahead 100 keys can take ~5 seconds but the OS will kill us // if we block for just one second on the UI thread. Because UI threads may need an address in order // to render the screen, we need getKeys to be fast even if the wallet is totally brand new and lookahead // didn't happen yet. // // It's safe to do this because when a network thread tries to calculate a Bloom filter, we'll go ahead // and calculate the full lookahead zone there, so network requests will always use the right amount. List<DeterministicKey> lookahead = maybeLookAhead(parentKey, index, 0, 0); putKeys(lookahead); List<DeterministicKey> keys = new ArrayList<>(numberOfKeys); for (int i = 0; i < numberOfKeys; i++) { HDPath path = parentKey.getPath().extend(new ChildNumber(index - numberOfKeys + i, false)); DeterministicKey k = hierarchy.get(path, false, false); // Just a last minute sanity check before we hand the key out to the app for usage. This isn't inspired // by any real problem reports from bitcoinj users, but I've heard of cases via the grapevine of // places that lost money due to bitflips causing addresses to not match keys. Of course in an // environment with flaky RAM there's no real way to always win: bitflips could be introduced at any // other layer. But as we're potentially retrieving from long term storage here, check anyway. checkForBitFlip(k); keys.add(k); } return keys; } finally { lock.unlock(); } } private void putKey(DeterministicKey key) { hierarchy.putKey(key); basicKeyChain.importKey(key); } private void putKeys(List<DeterministicKey> keys) { hierarchy.putKeys(keys); basicKeyChain.importKeys(keys); } // Clone key to new hierarchy. private static DeterministicKey cloneKey(DeterministicHierarchy hierarchy, DeterministicKey key) { DeterministicKey parent = hierarchy.get(Objects.requireNonNull(key.getParent()).getPath(), false, false); return new DeterministicKey(key.dropPrivateBytes(), parent); } private void checkForBitFlip(DeterministicKey k) { DeterministicKey parent = Objects.requireNonNull(k.getParent()); byte[] rederived = HDKeyDerivation.deriveChildKeyBytesFromPublic(parent, k.getChildNumber(), HDKeyDerivation.PublicDeriveMode.WITH_INVERSION).keyBytes; byte[] actual = k.getPubKey(); if (!Arrays.equals(rederived, actual)) throw new IllegalStateException(String.format(Locale.US, "Bit-flip check failed: %s vs %s", Arrays.toString(rederived), Arrays.toString(actual))); } /** * Mark the DeterministicKey as used. * Also correct the issued{Internal|External}Keys counter, because all lower children seem to be requested already. * If the counter was updated, we also might trigger lookahead. */ public DeterministicKey markKeyAsUsed(DeterministicKey k) { int numChildren = k.getChildNumber().i() + 1; if (k.getParent() == internalParentKey) { if (issuedInternalKeys < numChildren) { issuedInternalKeys = numChildren; maybeLookAhead(); } } else if (k.getParent() == externalParentKey) { if (issuedExternalKeys < numChildren) { issuedExternalKeys = numChildren; maybeLookAhead(); } } return k; } public DeterministicKey findKeyFromPubHash(byte[] pubkeyHash) { lock.lock(); try { return (DeterministicKey) basicKeyChain.findKeyFromPubHash(pubkeyHash); } finally { lock.unlock(); } } public DeterministicKey findKeyFromPubKey(byte[] pubkey) { lock.lock(); try { return (DeterministicKey) basicKeyChain.findKeyFromPubKey(pubkey); } finally { lock.unlock(); } } /** * Mark the DeterministicKeys as used, if they match the pubkeyHash * See {@link DeterministicKeyChain#markKeyAsUsed(DeterministicKey)} for more info on this. */ @Nullable public DeterministicKey markPubHashAsUsed(byte[] pubkeyHash) { lock.lock(); try { DeterministicKey k = (DeterministicKey) basicKeyChain.findKeyFromPubHash(pubkeyHash); if (k != null) markKeyAsUsed(k); return k; } finally { lock.unlock(); } } /** * Mark the DeterministicKeys as used, if they match the pubkey * See {@link DeterministicKeyChain#markKeyAsUsed(DeterministicKey)} for more info on this. */ @Nullable public DeterministicKey markPubKeyAsUsed(byte[] pubkey) { lock.lock(); try { DeterministicKey k = (DeterministicKey) basicKeyChain.findKeyFromPubKey(pubkey); if (k != null) markKeyAsUsed(k); return k; } finally { lock.unlock(); } } @Override public boolean hasKey(ECKey key) { lock.lock(); try { return basicKeyChain.hasKey(key); } finally { lock.unlock(); } } /** Returns the deterministic key for the given absolute path in the hierarchy. */ protected DeterministicKey getKeyByPath(ChildNumber... path) { return getKeyByPath(HDPath.M(Arrays.asList(path))); } /** Returns the deterministic key for the given absolute path in the hierarchy. */ protected DeterministicKey getKeyByPath(List<ChildNumber> path) { return getKeyByPath(path, false); } /** Returns the deterministic key for the given absolute path in the hierarchy, optionally creating it */ public DeterministicKey getKeyByPath(List<ChildNumber> path, boolean create) { return hierarchy.get(path, false, create); } @Nullable public DeterministicKey getRootKey() { return rootKey; } /** * <p>An alias for {@code getKeyByPath(getAccountPath())}.</p> * * <p>Use this when you would like to create a watching key chain that follows this one, but can't spend money from it. * The returned key can be serialized and then passed into {@link Builder#watch(DeterministicKey)} * on another system to watch the hierarchy.</p> * * <p>Note that the returned key is not pubkey only unless this key chain already is: the returned key can still * be used for signing etc if the private key bytes are available.</p> */ public DeterministicKey getWatchingKey() { return getKeyByPath(getAccountPath()); } /** Returns true if this chain is watch only, meaning it has public keys but no private key. */ public boolean isWatching() { return getWatchingKey().isWatching(); } @Override public int numKeys() { // We need to return here the total number of keys including the lookahead zone, not the number of keys we // have issued via getKey/freshReceiveKey. lock.lock(); try { maybeLookAhead(); return basicKeyChain.numKeys(); } finally { lock.unlock(); } } /** * Returns number of leaf keys used including both internal and external paths. This may be fewer than the number * that have been deserialized or held in memory, because of the lookahead zone. */ public int numLeafKeysIssued() { lock.lock(); try { return issuedExternalKeys + issuedInternalKeys; } finally { lock.unlock(); } } @Override public Instant earliestKeyCreationTime() { return (seed != null ? seed.creationTime() : getWatchingKey().creationTime() ).orElse(Instant.EPOCH); } @Override public void addEventListener(KeyChainEventListener listener) { basicKeyChain.addEventListener(listener); } @Override public void addEventListener(KeyChainEventListener listener, Executor executor) { basicKeyChain.addEventListener(listener, executor); } @Override public boolean removeEventListener(KeyChainEventListener listener) { return basicKeyChain.removeEventListener(listener); } /** Returns a list of words that represent the seed or null if this chain is a watching chain. */ @Nullable public List<String> getMnemonicCode() { if (seed == null) return null; lock.lock(); try { return seed.getMnemonicCode(); } finally { lock.unlock(); } } /** * Return true if this keychain is following another keychain */ public boolean isFollowing() { return isFollowing; } ////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // // Serialization support // ////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /** * Serialize to a list of keys * @return A list of keys (treat as unmodifiable list, will change in future release) */ @Override public List<Protos.Key> serializeToProtobuf() { lock.lock(); try { // TODO: return unmodifiable list return serializeMyselfToProtobuf(); } finally { lock.unlock(); } } /** * Serialize to a list of keys. Does not use {@code lock}, expects caller to provide locking. * @return A list of keys (treat as unmodifiable list, will change in future release) */ protected List<Protos.Key> serializeMyselfToProtobuf() { // Most of the serialization work is delegated to the basic key chain, which will serialize the bulk of the // data (handling encryption along the way), and letting us patch it up with the extra data we care about. LinkedList<Protos.Key> entries = new LinkedList<>(); if (seed != null) { Protos.Key.Builder mnemonicEntry = BasicKeyChain.serializeEncryptableItem(seed); mnemonicEntry.setType(Protos.Key.Type.DETERMINISTIC_MNEMONIC); serializeSeedEncryptableItem(seed, mnemonicEntry); for (ChildNumber childNumber : getAccountPath()) { mnemonicEntry.addAccountPath(childNumber.i()); } entries.add(mnemonicEntry.build()); } Map<ECKey, Protos.Key.Builder> keys = basicKeyChain.serializeToEditableProtobufs(); for (Map.Entry<ECKey, Protos.Key.Builder> entry : keys.entrySet()) { DeterministicKey key = (DeterministicKey) entry.getKey(); Protos.Key.Builder proto = entry.getValue(); proto.setType(Protos.Key.Type.DETERMINISTIC_KEY); final Protos.DeterministicKey.Builder detKey = proto.getDeterministicKey().toBuilder(); detKey.setChainCode(ByteString.copyFrom(key.getChainCode())); for (ChildNumber num : key.getPath()) detKey.addPath(num.i()); if (key.equals(externalParentKey)) { detKey.setIssuedSubkeys(issuedExternalKeys); detKey.setLookaheadSize(lookaheadSize); detKey.setSigsRequiredToSpend(getSigsRequiredToSpend()); } else if (key.equals(internalParentKey)) { detKey.setIssuedSubkeys(issuedInternalKeys); detKey.setLookaheadSize(lookaheadSize); detKey.setSigsRequiredToSpend(getSigsRequiredToSpend()); } // Flag the very first key of following keychain. if (entries.isEmpty() && isFollowing()) { detKey.setIsFollowing(true); } proto.setDeterministicKey(detKey); if (key.getParent() != null) { // HD keys inherit the timestamp of their parent if they have one, so no need to serialize it. proto.clearCreationTimestamp(); } else { proto.setOutputScriptType(Protos.Key.OutputScriptType.valueOf(outputScriptType.name())); } entries.add(proto.build()); } // TODO: return unmodifiable list return entries; } static List<DeterministicKeyChain> fromProtobuf(List<Protos.Key> keys, @Nullable KeyCrypter crypter) throws UnreadableWalletException { return fromProtobuf(keys, crypter, new DefaultKeyChainFactory()); } /** * Returns all the key chains found in the given list of keys. Typically there will only be one, but in the case of * key rotation it can happen that there are multiple chains found. */ public static List<DeterministicKeyChain> fromProtobuf(List<Protos.Key> keys, @Nullable KeyCrypter crypter, KeyChainFactory factory) throws UnreadableWalletException { List<DeterministicKeyChain> chains = new LinkedList<>(); DeterministicSeed seed = null; DeterministicKeyChain chain = null; int lookaheadSize = -1; int sigsRequiredToSpend = 1; HDPath accountPath = HDPath.M(); ScriptType outputScriptType = ScriptType.P2PKH; for (Protos.Key key : keys) { final Protos.Key.Type t = key.getType(); if (t == Protos.Key.Type.DETERMINISTIC_MNEMONIC) { accountPath = deserializeAccountPath(key.getAccountPathList()); if (chain != null) { addChain(chains, chain, lookaheadSize, sigsRequiredToSpend); chain = null; } Instant seedCreationTime = Instant.ofEpochMilli(key.getCreationTimestamp()); String passphrase = DEFAULT_PASSPHRASE_FOR_MNEMONIC; // FIXME allow non-empty passphrase if (key.hasSecretBytes()) { if (key.hasEncryptedDeterministicSeed()) throw new UnreadableWalletException("Malformed key proto: " + key); byte[] seedBytes = null; if (key.hasDeterministicSeed()) { seedBytes = key.getDeterministicSeed().toByteArray(); } seed = new DeterministicSeed(key.getSecretBytes().toStringUtf8(), seedBytes, passphrase, seedCreationTime); } else if (key.hasEncryptedData()) { if (key.hasDeterministicSeed()) throw new UnreadableWalletException("Malformed key proto: " + key); EncryptedData data = new EncryptedData(key.getEncryptedData().getInitialisationVector().toByteArray(), key.getEncryptedData().getEncryptedPrivateKey().toByteArray()); EncryptedData encryptedSeedBytes = null; if (key.hasEncryptedDeterministicSeed()) { Protos.EncryptedData encryptedSeed = key.getEncryptedDeterministicSeed(); encryptedSeedBytes = new EncryptedData(encryptedSeed.getInitialisationVector().toByteArray(), encryptedSeed.getEncryptedPrivateKey().toByteArray()); } seed = new DeterministicSeed(data, encryptedSeedBytes, seedCreationTime); } else { throw new UnreadableWalletException("Malformed key proto: " + key); } if (log.isDebugEnabled()) log.debug("Deserializing: DETERMINISTIC_MNEMONIC: {}", seed); } else if (t == Protos.Key.Type.DETERMINISTIC_KEY) { if (!key.hasDeterministicKey()) throw new UnreadableWalletException("Deterministic key missing extra data: " + key); byte[] chainCode = key.getDeterministicKey().getChainCode().toByteArray(); // Deserialize the public key and path. LazyECPoint pubkey = new LazyECPoint(ECKey.CURVE.getCurve(), key.getPublicKey().toByteArray()); // Deserialize the path through the tree. final HDPath path = HDPath.deserialize(key.getDeterministicKey().getPathList()); if (key.hasOutputScriptType()) outputScriptType = ScriptType.valueOf(key.getOutputScriptType().name()); // Possibly create the chain, if we didn't already do so yet. boolean isWatchingAccountKey = false; boolean isFollowingKey = false; boolean isSpendingKey = false; // save previous chain if any if the key is marked as following. Current key and the next ones are to be // placed in new following key chain if (key.getDeterministicKey().getIsFollowing()) { if (chain != null) { addChain(chains, chain, lookaheadSize, sigsRequiredToSpend); chain = null; seed = null; } isFollowingKey = true; } if (chain == null) { // If this has a private key but no seed, then all we know is the spending key H if (seed == null && key.hasSecretBytes()) { DeterministicKey accountKey = new DeterministicKey(path, chainCode, pubkey, ByteUtils.bytesToBigInteger(key.getSecretBytes().toByteArray()), null); accountKey.setCreationTime(Instant.ofEpochMilli(key.getCreationTimestamp())); chain = factory.makeSpendingKeyChain(accountKey, outputScriptType); isSpendingKey = true; } else if (seed == null) { DeterministicKey accountKey = new DeterministicKey(path, chainCode, pubkey, null, null); accountKey.setCreationTime(Instant.ofEpochMilli(key.getCreationTimestamp())); chain = factory.makeWatchingKeyChain(accountKey, outputScriptType); isWatchingAccountKey = true; } else { chain = factory.makeKeyChain(seed, crypter, outputScriptType, accountPath); chain.lookaheadSize = LAZY_CALCULATE_LOOKAHEAD; // If the seed is encrypted, then the chain is incomplete at this point. However, we will load // it up below as we parse in the keys. We just need to check at the end that we've loaded // everything afterwards. } } // Find the parent key assuming this is not the root key, and not an account key for a watching chain. DeterministicKey parent = null; if (!path.isEmpty() && !isWatchingAccountKey && !isSpendingKey) { parent = chain.hierarchy.get(path.parent(), false, false); } DeterministicKey detkey; if (key.hasSecretBytes()) { // Not encrypted: private key is available. final BigInteger priv = ByteUtils.bytesToBigInteger(key.getSecretBytes().toByteArray()); detkey = new DeterministicKey(path, chainCode, pubkey, priv, parent); } else { if (key.hasEncryptedData()) { Protos.EncryptedData proto = key.getEncryptedData(); EncryptedData data = new EncryptedData(proto.getInitialisationVector().toByteArray(), proto.getEncryptedPrivateKey().toByteArray()); Objects.requireNonNull(crypter, "Encountered an encrypted key but no key crypter provided"); detkey = new DeterministicKey(path, chainCode, crypter, pubkey, data, parent); } else { // No secret key bytes and key is not encrypted: either a watching key or private key bytes // will be rederived on the fly from the parent. detkey = new DeterministicKey(path, chainCode, pubkey, null, parent); } } if (key.hasCreationTimestamp()) detkey.setCreationTime(Instant.ofEpochMilli(key.getCreationTimestamp())); if (log.isDebugEnabled()) log.debug("Deserializing: DETERMINISTIC_KEY: {}", detkey); if (!isWatchingAccountKey) { // If the non-encrypted case, the non-leaf keys (account, internal, external) have already // been rederived and inserted at this point. In the encrypted case though, // we can't rederive and we must reinsert, potentially building the hierarchy object // if need be. if (path.isEmpty()) { // Master key. if (chain.rootKey == null) { chain.rootKey = detkey; chain.hierarchy = new DeterministicHierarchy(detkey); } } else if ((path.size() == chain.getAccountPath().size() + 1) || isSpendingKey) { // Constant 0 is used for external chain and constant 1 for internal chain // (also known as change addresses). https://github.com/bitcoin/bips/blob/master/bip-0044.mediawiki if (detkey.getChildNumber().num() == 0) { // External chain is used for addresses that are meant to be visible outside of the wallet // (e.g. for receiving payments). chain.externalParentKey = detkey; chain.issuedExternalKeys = key.getDeterministicKey().getIssuedSubkeys(); lookaheadSize = Math.max(lookaheadSize, key.getDeterministicKey().getLookaheadSize()); sigsRequiredToSpend = key.getDeterministicKey().getSigsRequiredToSpend(); } else if (detkey.getChildNumber().num() == 1) { // Internal chain is used for addresses which are not meant to be visible outside of the // wallet and is used for return transaction change. chain.internalParentKey = detkey; chain.issuedInternalKeys = key.getDeterministicKey().getIssuedSubkeys(); } } } chain.putKey(detkey); } } if (chain != null) { addChain(chains, chain, lookaheadSize, sigsRequiredToSpend); } return chains; } private static void addChain(List<DeterministicKeyChain> chains, DeterministicKeyChain chain, int lookaheadSize, int sigsRequiredToSpend) { checkState(lookaheadSize >= 0); chain.setLookaheadSize(lookaheadSize); chain.setSigsRequiredToSpend(sigsRequiredToSpend); chain.maybeLookAhead(); chains.add(chain); } private static HDPath deserializeAccountPath(List<Integer> integerList) { HDPath path = HDPath.deserialize(integerList); return path.isEmpty() ? ACCOUNT_ZERO_PATH : path; } ////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // // Encryption support // ////////////////////////////////////////////////////////////////////////////////////////////////////////////////// @Override public DeterministicKeyChain toEncrypted(CharSequence password) { Objects.requireNonNull(password); checkArgument(password.length() > 0); checkState(seed != null, () -> "attempt to encrypt a watching chain"); checkState(!seed.isEncrypted()); KeyCrypter scrypt = new KeyCrypterScrypt(); AesKey derivedKey = scrypt.deriveKey(password); return toEncrypted(scrypt, derivedKey); } @Override public DeterministicKeyChain toEncrypted(KeyCrypter keyCrypter, AesKey aesKey) { return new DeterministicKeyChain(keyCrypter, aesKey, this); } @Override public DeterministicKeyChain toDecrypted(CharSequence password) { Objects.requireNonNull(password); checkArgument(password.length() > 0); KeyCrypter crypter = getKeyCrypter(); checkState(crypter != null, () -> "chain not encrypted"); AesKey derivedKey = crypter.deriveKey(password); return toDecrypted(derivedKey); } @Override public DeterministicKeyChain toDecrypted(AesKey aesKey) { checkState(getKeyCrypter() != null, () -> "key chain not encrypted"); checkState(seed != null, () -> "can't decrypt a watching chain"); checkState(seed.isEncrypted()); String passphrase = DEFAULT_PASSPHRASE_FOR_MNEMONIC; // FIXME allow non-empty passphrase DeterministicSeed decSeed = seed.decrypt(getKeyCrypter(), passphrase, aesKey); DeterministicKeyChain chain = makeKeyChainFromSeed(decSeed, getAccountPath(), outputScriptType); // Now double check that the keys match to catch the case where the key is wrong but padding didn't catch it. if (!chain.getWatchingKey().getPubKeyPoint().equals(getWatchingKey().getPubKeyPoint())) throw new KeyCrypterException.PublicPrivateMismatch("Provided AES key is wrong"); chain.lookaheadSize = lookaheadSize; // Now copy the (pubkey only) leaf keys across to avoid rederiving them. The private key bytes are missing // anyway so there's nothing to decrypt. for (DeterministicKey key : getLeafKeys()) { checkState(key.isEncrypted()); chain.putKey(cloneKey(chain.hierarchy, key)); } chain.issuedExternalKeys = issuedExternalKeys; chain.issuedInternalKeys = issuedInternalKeys; for (ListenerRegistration<KeyChainEventListener> listener : basicKeyChain.getListeners()) { chain.basicKeyChain.addEventListener(listener); } return chain; } /** * Factory method to create a key chain from a seed. * Subclasses should override this to create an instance of the subclass instead of a plain DKC. * This is used in encryption/decryption. */ protected DeterministicKeyChain makeKeyChainFromSeed(DeterministicSeed seed, List<ChildNumber> accountPath, ScriptType outputScriptType) { return new DeterministicKeyChain(seed, null, outputScriptType, accountPath); } @Override public boolean checkPassword(CharSequence password) { Objects.requireNonNull(password); checkState(getKeyCrypter() != null, () -> "key chain not encrypted"); return checkAESKey(getKeyCrypter().deriveKey(password)); } @Override public boolean checkAESKey(AesKey aesKey) { checkState(rootKey != null, () -> "can't check password for a watching chain"); Objects.requireNonNull(aesKey); checkState(getKeyCrypter() != null, () -> "key chain not encrypted"); try { return rootKey.decrypt(aesKey).getPubKeyPoint().equals(rootKey.getPubKeyPoint()); } catch (KeyCrypterException e) { return false; } } @Nullable @Override public KeyCrypter getKeyCrypter() { return basicKeyChain.getKeyCrypter(); } ////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // // Bloom filtering support // ////////////////////////////////////////////////////////////////////////////////////////////////////////////////// @Override public int numBloomFilterEntries() { return numKeys() * 2; } @Override public BloomFilter getFilter(int size, double falsePositiveRate, int tweak) { lock.lock(); try { checkArgument(size >= numBloomFilterEntries()); maybeLookAhead(); return basicKeyChain.getFilter(size, falsePositiveRate, tweak); } finally { lock.unlock(); } } /** * <p>The number of public keys we should pre-generate on each path before they are requested by the app. This is * required so that when scanning through the chain given only a seed, we can give enough keys to the remote node * via the Bloom filter such that we see transactions that are "from the future", for example transactions created * by a different app that's sharing the same seed, or transactions we made before but we're replaying the chain * given just the seed. The default is 100.</p> */ public int getLookaheadSize() { lock.lock(); try { return lookaheadSize; } finally { lock.unlock(); } } /** * Sets a new lookahead size. See {@link #getLookaheadSize()} for details on what this is. Setting a new size * that's larger than the current size will return immediately and the new size will only take effect next time * a fresh filter is requested (e.g. due to a new peer being connected). So you should set this before starting * to sync the chain, if you want to modify it. If you haven't modified the lookahead threshold manually then * it will be automatically set to be a third of the new size. */ public void setLookaheadSize(int lookaheadSize) { lock.lock(); try { boolean readjustThreshold = this.lookaheadThreshold == calcDefaultLookaheadThreshold(); this.lookaheadSize = lookaheadSize; if (readjustThreshold) this.lookaheadThreshold = calcDefaultLookaheadThreshold(); } finally { lock.unlock(); } } /** * Sets the threshold for the key pre-generation. This is used to avoid adding new keys and thus * re-calculating Bloom filters every time a new key is calculated. Without a lookahead threshold, every time we * received a relevant transaction we'd extend the lookahead zone and generate a new filter, which is inefficient. */ public void setLookaheadThreshold(int num) { lock.lock(); try { if (num >= lookaheadSize) throw new IllegalArgumentException("Threshold larger or equal to the lookaheadSize"); this.lookaheadThreshold = num; } finally { lock.unlock(); } } /** * Gets the threshold for the key pre-generation. See {@link #setLookaheadThreshold(int)} for details on what this * is. The default is a third of the lookahead size (100 / 3 == 33). If you don't modify it explicitly then this * value will always be one third of the lookahead size. */ public int getLookaheadThreshold() { lock.lock(); try { if (lookaheadThreshold >= lookaheadSize) return 0; return lookaheadThreshold; } finally { lock.unlock(); } } /** * Pre-generate enough keys to reach the lookahead size. You can call this if you need to explicitly invoke * the lookahead procedure, but it's normally unnecessary as it will be done automatically when needed. */ public void maybeLookAhead() { lock.lock(); try { List<DeterministicKey> keys = concatLists( maybeLookAhead(externalParentKey, issuedExternalKeys), maybeLookAhead(internalParentKey, issuedInternalKeys)); if (!keys.isEmpty()) { keyLookaheadEpoch++; // Batch add all keys at once so there's only one event listener invocation, as this will be listened to // by the wallet and used to rebuild/broadcast the Bloom filter. That's expensive so we don't want to do // it more often than necessary. putKeys(keys); } } finally { lock.unlock(); } } private <T> List<T> concatLists(List<T> list1, List<T> list2) { return Stream.concat(list1.stream(), list2.stream()) .collect(StreamUtils.toUnmodifiableList()); } private List<DeterministicKey> maybeLookAhead(DeterministicKey parent, int issued) { checkState(lock.isHeldByCurrentThread()); return maybeLookAhead(parent, issued, getLookaheadSize(), getLookaheadThreshold()); } /** * Pre-generate enough keys to reach the lookahead size, but only if there are more than the lookaheadThreshold to * be generated, so that the Bloom filter does not have to be regenerated that often. * <p> * Although this method reads fields, it has no side effects and simply returns a list of keys. This * means the caller is responsible for adding them to the hierarchy and keychain. * @param parent parent key * @param issued number of keys already issued * @param lookaheadSize target lookahead * @param lookaheadThreshold lookahead threshold * @return unmodifiable list of keys (typically the caller must insert them into the hierarchy and basic keychain) */ private List<DeterministicKey> maybeLookAhead(DeterministicKey parent, int issued, int lookaheadSize, int lookaheadThreshold) { checkState(lock.isHeldByCurrentThread()); final int numChildren = hierarchy.getNumChildren(parent.getPath()); final int needed = issued + lookaheadSize + lookaheadThreshold - numChildren; final int limit = (needed > lookaheadThreshold) ? needed : 0; log.info("{} keys needed for {} = {} issued + {} lookahead size + {} lookahead threshold - {} num children", limit, parent.getPathAsString(), issued, lookaheadSize, lookaheadThreshold, numChildren); Stopwatch watch = Stopwatch.start(); List<DeterministicKey> result = HDKeyDerivation.generate(parent, numChildren) .limit(limit) .map(DeterministicKey::dropPrivateBytes) .collect(StreamUtils.toUnmodifiableList()); log.info("Took {}", watch); return result; } /** Housekeeping call to call when lookahead might be needed. Normally called automatically by KeychainGroup. */ public void maybeLookAheadScripts() { } /** * Returns number of keys used on external path. This may be fewer than the number that have been deserialized * or held in memory, because of the lookahead zone. */ public int getIssuedExternalKeys() { lock.lock(); try { return issuedExternalKeys; } finally { lock.unlock(); } } /** * Returns number of keys used on internal path. This may be fewer than the number that have been deserialized * or held in memory, because of the lookahead zone. */ public int getIssuedInternalKeys() { lock.lock(); try { return issuedInternalKeys; } finally { lock.unlock(); } } /** Returns the seed or null if this chain is a watching chain. */ @Nullable public DeterministicSeed getSeed() { lock.lock(); try { return seed; } finally { lock.unlock(); } } /** * Return a subset list of keys * For internal usage only * @param includeLookahead if true include all keys, if false don't include lookahead keys * @param includeParents if true, include parent keys. If false, leaf keys only * @return Unmodifiable list of keys */ /* package */ List<DeterministicKey> getKeys(boolean includeLookahead, boolean includeParents) { return getKeys(filterKeys(includeLookahead, includeParents)); } /** * Return a filter predicate for a stream (list) of keys * @param includeLookahead if true include all keys, if false don't include lookahead keys * @param includeParents if true, include parent keys. If false, leaf keys only * @return A filter predicate that filters according to the parameters */ private Predicate<DeterministicKey> filterKeys(boolean includeLookahead, boolean includeParents) { Predicate<DeterministicKey> keyFilter; if (!includeLookahead) { int treeSize = internalParentKey.getPath().size(); keyFilter = key -> { DeterministicKey parent = key.getParent(); return !( (!includeParents && parent == null) || (!includeParents && key.getPath().size() <= treeSize) || (internalParentKey.equals(parent) && key.getChildNumber().i() >= issuedInternalKeys) || (externalParentKey.equals(parent) && key.getChildNumber().i() >= issuedExternalKeys) ); }; } else { // TODO includeParents is ignored here keyFilter = key -> true; } return keyFilter; } /** * Return a filtered subset of keys * @param keyFilter filtering predicate * @return Unmodifiable list of keys */ private List<DeterministicKey> getKeys(Predicate<DeterministicKey> keyFilter) { return basicKeyChain.getKeys().stream() .map(key -> (DeterministicKey) key) .filter(keyFilter) .collect(StreamUtils.toUnmodifiableList()); } /** * Returns only the external keys that have been issued by this chain, lookahead not included. * @return Unmodifiable list of keys */ public List<DeterministicKey> getIssuedReceiveKeys() { return getKeys( filterKeys(false, false) .and(key -> externalParentKey.equals(key.getParent())) // keys with parent == externalParentKey ); } /** * Returns leaf keys issued by this chain (including lookahead zone) * @return Unmodifiable list of keys */ public List<DeterministicKey> getLeafKeys() { return getKeys(key -> key.getPath().size() == getAccountPath().size() + 2); // leaf keys only } /*package*/ static void serializeSeedEncryptableItem(DeterministicSeed seed, Protos.Key.Builder proto) { // The seed can be missing if we have not derived it yet from the mnemonic. // This will not normally happen once all the wallets are on the latest code that caches // the seed. if (seed.isEncrypted() && seed.getEncryptedSeedData() != null) { EncryptedData data = seed.getEncryptedSeedData(); proto.setEncryptedDeterministicSeed(proto.getEncryptedDeterministicSeed().toBuilder() .setEncryptedPrivateKey(ByteString.copyFrom(data.encryptedBytes)) .setInitialisationVector(ByteString.copyFrom(data.initialisationVector))); // We don't allow mixing of encryption types at the moment. checkState(seed.getEncryptionType() == Protos.Wallet.EncryptionType.ENCRYPTED_SCRYPT_AES); } else { final byte[] secret = seed.getSeedBytes(); if (secret != null) proto.setDeterministicSeed(ByteString.copyFrom(secret)); } } /** * Returns a counter that is incremented each time new keys are generated due to lookahead. Used by the network * code to learn whether to discard the current block and await calculation of a new filter. */ public int getKeyLookaheadEpoch() { lock.lock(); try { return keyLookaheadEpoch; } finally { lock.unlock(); } } /** Get redeem data for a key. Only applicable to married keychains. */ public RedeemData getRedeemData(DeterministicKey followedKey) { throw new UnsupportedOperationException(); } /** Create a new key and return the matching output script. Only applicable to married keychains. */ public Script freshOutputScript(KeyPurpose purpose) { throw new UnsupportedOperationException(); } @Override public String toString() { MoreObjects.ToStringHelper helper = MoreObjects.toStringHelper(this).omitNullValues(); helper.addValue(outputScriptType); helper.add("accountPath", accountPath); helper.add("lookaheadSize", lookaheadSize); helper.add("lookaheadThreshold", lookaheadThreshold); if (isFollowing) helper.addValue("following"); return helper.toString(); } public String toString(boolean includeLookahead, boolean includePrivateKeys, @Nullable AesKey aesKey, Network network) { final DeterministicKey watchingKey = getWatchingKey(); final StringBuilder builder = new StringBuilder(); if (seed != null) { if (includePrivateKeys) { DeterministicSeed decryptedSeed = seed.isEncrypted() ? seed.decrypt(getKeyCrypter(), DEFAULT_PASSPHRASE_FOR_MNEMONIC, aesKey) : seed; final List<String> words = decryptedSeed.getMnemonicCode(); builder.append("Seed as words: ").append(InternalUtils.SPACE_JOINER.join(words)).append('\n'); builder.append("Seed as hex: ").append(decryptedSeed.toHexString()).append('\n'); } else { if (seed.isEncrypted()) builder.append("Seed is encrypted\n"); } builder.append("Seed birthday: "); Optional<Instant> seedCreationTime = seed.creationTime(); if (seedCreationTime.isPresent()) builder.append(seedCreationTime.get().getEpochSecond()).append(" [") .append(TimeUtils.dateTimeFormat(seedCreationTime.get())).append("]"); else builder.append("unknown"); builder.append("\n"); } else { builder.append("Key birthday: "); Optional<Instant> watchingKeyCreationTime = watchingKey.creationTime(); if (watchingKeyCreationTime.isPresent()) builder.append(watchingKeyCreationTime.get().getEpochSecond()).append(" [") .append(TimeUtils.dateTimeFormat(watchingKeyCreationTime.get())).append("]"); else builder.append("unknown"); builder.append("\n"); } builder.append("Ouput script type: ").append(outputScriptType).append('\n'); builder.append("Key to watch: ").append(watchingKey.serializePubB58(network, outputScriptType)) .append('\n'); builder.append("Lookahead siz/thr: ").append(lookaheadSize).append('/').append(lookaheadThreshold).append('\n'); formatAddresses(includeLookahead, includePrivateKeys, aesKey, network, builder); return builder.toString(); } /** @deprecated use {@link #toString(boolean, boolean, AesKey, Network)} */ @Deprecated public String toString(boolean includeLookahead, boolean includePrivateKeys, @Nullable AesKey aesKey, NetworkParameters params) { return toString(includeLookahead, includePrivateKeys, aesKey, params.network()); } protected void formatAddresses(boolean includeLookahead, boolean includePrivateKeys, @Nullable AesKey aesKey, Network network, StringBuilder builder) { for (DeterministicKey key : getKeys(includeLookahead, true)) { String comment = null; if (key.equals(getRootKey())) comment = "root"; else if (key.equals(getWatchingKey())) comment = "account"; else if (key.equals(internalParentKey)) comment = "internal"; else if (key.equals(externalParentKey)) comment = "external"; else if (internalParentKey.equals(key.getParent()) && key.getChildNumber().i() >= issuedInternalKeys) comment = "*"; else if (externalParentKey.equals(key.getParent()) && key.getChildNumber().i() >= issuedExternalKeys) comment = "*"; key.formatKeyWithAddress(includePrivateKeys, aesKey, builder, network, outputScriptType, comment); } } /** The number of signatures required to spend coins received by this keychain. */ public void setSigsRequiredToSpend(int sigsRequiredToSpend) { this.sigsRequiredToSpend = sigsRequiredToSpend; } /** * Returns the number of signatures required to spend transactions for this KeyChain. It's the N from * N-of-M CHECKMULTISIG script for P2SH transactions and always 1 for other transaction types. */ public int getSigsRequiredToSpend() { return sigsRequiredToSpend; } /** Returns the redeem script by its hash or null if this keychain did not generate the script. */ @Nullable public RedeemData findRedeemDataByScriptHash(ByteString bytes) { return null; } }
71,799
46.361478
178
java
bitcoinj
bitcoinj-master/core/src/main/java/org/bitcoinj/wallet/DeterministicUpgradeRequiresPassword.java
/* * Copyright by the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.bitcoinj.wallet; /** * Indicates that the pre-HD random wallet is encrypted, so you should try the upgrade again after getting the * users password. This is required because HD wallets are upgraded from random using the private key bytes of * the oldest non-rotating key, in order to make the upgrade process itself deterministic. */ public class DeterministicUpgradeRequiresPassword extends RuntimeException {}
1,043
40.76
110
java
bitcoinj
bitcoinj-master/core/src/main/java/org/bitcoinj/wallet/WalletFiles.java
/* * Copyright 2013 Google Inc. * Copyright 2014 Andreas Schildbach * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.bitcoinj.wallet; import org.bitcoinj.base.internal.Stopwatch; import org.bitcoinj.base.internal.TimeUtils; import org.bitcoinj.utils.ContextPropagatingThreadFactory; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.annotation.Nonnull; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.sql.Time; import java.time.Duration; import java.time.Instant; import java.util.Date; import java.util.Objects; import java.util.concurrent.Callable; import java.util.concurrent.ScheduledThreadPoolExecutor; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; /** * A class that handles atomic and optionally delayed writing of the wallet file to disk. In future: backups too. * It can be useful to delay writing of a wallet file to disk on slow devices where disk and serialization overhead * can come to dominate the chain processing speed, i.e. on Android phones. By coalescing writes and doing serialization * and disk IO on a background thread performance can be improved. */ public class WalletFiles { private static final Logger log = LoggerFactory.getLogger(WalletFiles.class); private final Wallet wallet; private final ScheduledThreadPoolExecutor executor; private final File file; private final AtomicBoolean savePending; private final Duration delay; private final Callable<Void> saver; private volatile Listener vListener; /** * Implementors can do pre/post treatment of the wallet file. Useful for adjusting permissions and other things. */ public interface Listener { /** * Called on the auto-save thread when a new temporary file is created but before the wallet data is saved * to it. If you want to do something here like adjust permissions, go ahead and do so. */ void onBeforeAutoSave(File tempFile); /** * Called on the auto-save thread after the newly created temporary file has been filled with data and renamed. */ void onAfterAutoSave(File newlySavedFile); } /** * Initialize atomic and optionally delayed writing of the wallet file to disk. Note the initial wallet state isn't * saved automatically. The {@link Wallet} calls {@link #saveNow()} or {@link #saveLater()} as wallet state changes, * depending on the urgency of the changes. */ public WalletFiles(final Wallet wallet, File file, Duration delay) { // An executor that starts up threads when needed and shuts them down later. this.executor = new ScheduledThreadPoolExecutor(1, new ContextPropagatingThreadFactory("Wallet autosave thread", Thread.MIN_PRIORITY)); this.executor.setKeepAliveTime(5, TimeUnit.SECONDS); this.executor.allowCoreThreadTimeOut(true); this.executor.setExecuteExistingDelayedTasksAfterShutdownPolicy(false); this.wallet = Objects.requireNonNull(wallet); // File must only be accessed from the auto-save executor from now on, to avoid simultaneous access. this.file = Objects.requireNonNull(file); this.savePending = new AtomicBoolean(); this.delay = Objects.requireNonNull(delay); this.saver = () -> { // Runs in an auto save thread. if (!savePending.getAndSet(false)) { // Some other scheduled request already beat us to it. return null; } log.info("Background saving wallet; last seen block is height {}, date {}, hash {}", wallet.getLastBlockSeenHeight(), wallet.lastBlockSeenTime() .map(time -> TimeUtils.dateTimeFormat(time)) .orElse("unknown"), wallet.getLastBlockSeenHash()); saveNowInternal(); return null; }; } /** @deprecated use {@link #WalletFiles(Wallet, File, Duration)} */ @Deprecated public WalletFiles(final Wallet wallet, File file, long delayTime, TimeUnit timeUnit) { this(wallet, file, Duration.ofMillis(timeUnit.toMillis(delayTime))); } /** Get the {@link Wallet} this {@link WalletFiles} is managing. */ public Wallet getWallet() { return wallet; } /** * The given listener will be called on the autosave thread before and after the wallet is saved to disk. */ public void setListener(@Nonnull Listener listener) { this.vListener = Objects.requireNonNull(listener); } /** Actually write the wallet file to disk, using an atomic rename when possible. Runs on the current thread. */ public void saveNow() throws IOException { // Can be called by any thread. However the wallet is locked whilst saving, so we can have two saves in flight // but they will serialize (using different temp files). if (executor.isShutdown()) return; log.info("Saving wallet; last seen block is height {}, date {}, hash {}", wallet.getLastBlockSeenHeight(), wallet.lastBlockSeenTime() .map(time -> TimeUtils.dateTimeFormat(time)) .orElse("unknown"), wallet.getLastBlockSeenHash()); saveNowInternal(); } private void saveNowInternal() throws IOException { Stopwatch watch = Stopwatch.start(); File directory = file.getAbsoluteFile().getParentFile(); if (!directory.exists()) { throw new FileNotFoundException(directory.getPath() + " (wallet directory not found)"); } File temp = File.createTempFile("wallet", null, directory); final Listener listener = vListener; if (listener != null) listener.onBeforeAutoSave(temp); wallet.saveToFile(temp, file); if (listener != null) listener.onAfterAutoSave(file); log.info("Save completed in {}", watch); } /** Queues up a save in the background. Useful for not very important wallet changes. */ public void saveLater() { if (executor.isShutdown() || savePending.getAndSet(true)) return; // Already pending. executor.schedule(saver, delay.toMillis(), TimeUnit.MILLISECONDS); } /** Shut down auto-saving. */ public void shutdownAndWait() { executor.shutdown(); try { executor.awaitTermination(Long.MAX_VALUE, TimeUnit.DAYS); // forever } catch (InterruptedException x) { throw new RuntimeException(x); } } }
7,239
40.849711
143
java
bitcoinj
bitcoinj-master/core/src/main/java/org/bitcoinj/wallet/KeyBag.java
/* * Copyright 2014 The bitcoinj authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.bitcoinj.wallet; import org.bitcoinj.base.ScriptType; import org.bitcoinj.crypto.ECKey; import javax.annotation.Nullable; /** * A KeyBag is simply an object that can map public keys, their 160-bit hashes and script hashes to ECKey * and {@link RedeemData} objects. */ public interface KeyBag { /** * Locates a keypair from the keychain given the hash of the public key, and (optionally) by usage for a specific * script type. This is needed when finding out which key we need to use to redeem a transaction output. * * @param pubKeyHash * hash of the keypair to look for * @param scriptType * only look for given usage (currently {@link ScriptType#P2PKH} or * {@link ScriptType#P2WPKH}) or {@code null} if we don't care * @return found key or null if no such key was found. */ @Nullable ECKey findKeyFromPubKeyHash(byte[] pubKeyHash, @Nullable ScriptType scriptType); /** * Locates a keypair from the keychain given the raw public key bytes. * * @return ECKey or null if no such key was found. */ @Nullable ECKey findKeyFromPubKey(byte[] pubKey); /** * Locates a redeem data (redeem script and keys) from the keychain given the hash of the script. * This is needed when finding out which key and script we need to use to locally sign a P2SH transaction input. * It is assumed that wallet should not have more than one private key for a single P2SH tx for security reasons. * * Returns RedeemData object or null if no such data was found. */ @Nullable RedeemData findRedeemDataFromScriptHash(byte[] scriptHash); }
2,308
36.241935
117
java
bitcoinj
bitcoinj-master/core/src/main/java/org/bitcoinj/wallet/DefaultKeyChainFactory.java
/* * Copyright 2014 devrandom * Copyright 2019 Andreas Schildbach * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.bitcoinj.wallet; import org.bitcoinj.base.ScriptType; import org.bitcoinj.crypto.ChildNumber; import org.bitcoinj.crypto.DeterministicKey; import org.bitcoinj.crypto.KeyCrypter; import java.util.List; /** * Default factory for creating keychains while de-serializing. */ public class DefaultKeyChainFactory implements KeyChainFactory { @Override public DeterministicKeyChain makeKeyChain(DeterministicSeed seed, KeyCrypter crypter, ScriptType outputScriptType, List<ChildNumber> accountPath) { return new DeterministicKeyChain(seed, crypter, outputScriptType, accountPath); } @Override public DeterministicKeyChain makeWatchingKeyChain(DeterministicKey accountKey, ScriptType outputScriptType) throws UnreadableWalletException { return DeterministicKeyChain.builder().watch(accountKey).outputScriptType(outputScriptType).build(); } @Override public DeterministicKeyChain makeSpendingKeyChain(DeterministicKey accountKey, ScriptType outputScriptType) throws UnreadableWalletException { return DeterministicKeyChain.builder().spend(accountKey).outputScriptType(outputScriptType).build(); } }
1,953
38.877551
117
java
bitcoinj
bitcoinj-master/core/src/main/java/org/bitcoinj/wallet/WalletTransaction.java
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.bitcoinj.wallet; import org.bitcoinj.core.Transaction; import java.util.Objects; /** * Stores data about a transaction that is only relevant to the {@link Wallet} class. */ public class WalletTransaction { public enum Pool { UNSPENT, // unspent in best chain SPENT, // spent in best chain DEAD, // double-spend in alt chain PENDING, // a pending tx we would like to go into the best chain } private final Transaction transaction; private final Pool pool; public WalletTransaction(Pool pool, Transaction transaction) { this.pool = Objects.requireNonNull(pool); this.transaction = transaction; } public Transaction getTransaction() { return transaction; } public Pool getPool() { return pool; } }
1,423
27.48
85
java
bitcoinj
bitcoinj-master/core/src/main/java/org/bitcoinj/wallet/UnreadableWalletException.java
/* * Copyright by the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.bitcoinj.wallet; /** * Thrown by the {@link WalletProtobufSerializer} when the serialized protocol buffer is either corrupted, * internally inconsistent or appears to be from the future. */ public class UnreadableWalletException extends Exception { public UnreadableWalletException(String s) { super(s); } public UnreadableWalletException(String s, Throwable t) { super(s, t); } public static class BadPassword extends UnreadableWalletException { public BadPassword() { super("Password incorrect"); } } public static class FutureVersion extends UnreadableWalletException { public FutureVersion() { super("Unknown wallet version from the future."); } } public static class WrongNetwork extends UnreadableWalletException { public WrongNetwork() { super("Mismatched network ID"); } } }
1,537
31.041667
106
java
bitcoinj
bitcoinj-master/core/src/main/java/org/bitcoinj/wallet/FilteringCoinSelector.java
/* * Copyright 2014 the bitcoinj authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.bitcoinj.wallet; import org.bitcoinj.base.Coin; import org.bitcoinj.core.Transaction; import org.bitcoinj.core.TransactionInput; import org.bitcoinj.core.TransactionOutPoint; import org.bitcoinj.core.TransactionOutput; import java.util.HashSet; import java.util.Iterator; import java.util.List; /** * A filtering coin selector delegates to another coin selector, but won't select outputs spent by the given transactions. */ public class FilteringCoinSelector implements CoinSelector { protected CoinSelector delegate; protected HashSet<TransactionOutPoint> spent = new HashSet<>(); public FilteringCoinSelector(CoinSelector delegate) { this.delegate = delegate; } public void excludeOutputsSpentBy(Transaction tx) { for (TransactionInput input : tx.getInputs()) { spent.add(input.getOutpoint()); } } @Override public CoinSelection select(Coin target, List<TransactionOutput> candidates) { Iterator<TransactionOutput> iter = candidates.iterator(); while (iter.hasNext()) { TransactionOutput output = iter.next(); if (spent.contains(output.getOutPointFor())) iter.remove(); } return delegate.select(target, candidates); } }
1,875
32.5
122
java
bitcoinj
bitcoinj-master/core/src/main/java/org/bitcoinj/wallet/CoinSelector.java
/* * Copyright by the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.bitcoinj.wallet; import org.bitcoinj.base.Coin; import org.bitcoinj.core.TransactionOutput; import java.util.List; /** * A CoinSelector is responsible for picking some outputs to spend, from the list of all possible outputs. It * allows you to customize the policies for creation of transactions to suit your needs. The select operation * may return a {@link CoinSelection} that has a valueGathered lower than the requested target, if there's not * enough money in the wallet. */ public interface CoinSelector { /** * Creates a CoinSelection that tries to meet the target amount of value. The candidates list is given to * this call and can be edited freely. See the docs for CoinSelection to learn more, or look a the implementation * of {@link DefaultCoinSelector}. */ CoinSelection select(Coin target, List<TransactionOutput> candidates); }
1,506
38.657895
117
java
bitcoinj
bitcoinj-master/core/src/main/java/org/bitcoinj/wallet/KeyChainGroup.java
/* * Copyright 2014 Mike Hearn * Copyright 2014 Andreas Schildbach * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.bitcoinj.wallet; import com.google.protobuf.ByteString; import org.bitcoinj.base.BitcoinNetwork; import org.bitcoinj.base.Address; import org.bitcoinj.base.Network; import org.bitcoinj.base.internal.TimeUtils; import org.bitcoinj.crypto.AesKey; import org.bitcoinj.core.BloomFilter; import org.bitcoinj.crypto.ECKey; import org.bitcoinj.base.LegacyAddress; import org.bitcoinj.core.NetworkParameters; import org.bitcoinj.crypto.ChildNumber; import org.bitcoinj.crypto.DeterministicKey; import org.bitcoinj.crypto.KeyCrypter; import org.bitcoinj.crypto.KeyCrypterScrypt; import org.bitcoinj.script.Script; import org.bitcoinj.base.ScriptType; import org.bitcoinj.script.ScriptBuilder; import org.bitcoinj.script.ScriptPattern; import org.bitcoinj.utils.ListenerRegistration; import org.bitcoinj.utils.Threading; import org.bitcoinj.wallet.listeners.CurrentKeyChangeEventListener; import org.bitcoinj.wallet.listeners.KeyChainEventListener; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.annotation.Nullable; import java.security.SecureRandom; import java.time.Instant; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.EnumMap; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.Executor; import java.util.stream.Collectors; import java.util.stream.Stream; import static org.bitcoinj.base.internal.Preconditions.checkArgument; import static org.bitcoinj.base.internal.Preconditions.checkState; /** * <p>A KeyChainGroup is used by the {@link Wallet} and manages: a {@link BasicKeyChain} object * (which will normally be empty), and zero or more {@link DeterministicKeyChain}s. The last added * deterministic keychain is always the default active keychain, that's the one we normally derive keys and * addresses from.</p> * * <p>There can be active keychains for each output script type. However this class almost entirely only works on * the default active keychain (see {@link #getActiveKeyChain()}). The other active keychains * (see {@link #getActiveKeyChain(ScriptType, long)}) are meant as fallback for if a sender doesn't understand a * certain new script type (e.g. P2WPKH which comes with the new Bech32 address format). Active keychains * share the same seed, so that upgrading the wallet * (see {@link #upgradeToDeterministic(ScriptType, KeyChainGroupStructure, long, AesKey)}) to understand * a new script type doesn't require a fresh backup.</p> * * <p>If a key rotation time is set, it may be necessary to add a new DeterministicKeyChain with a fresh seed * and also preserve the old one, so funds can be swept from the rotating keys. In this case, there may be * more than one deterministic chain. The latest chain is called the active chain and is where new keys are served * from.</p> * * <p>The wallet delegates most key management tasks to this class. It is <b>not</b> thread safe and requires external * locking, i.e. by the wallet lock. The group then in turn delegates most operations to the key chain objects, * combining their responses together when necessary.</p> * * <p>Deterministic key chains have a concept of a lookahead size and threshold. Please see the discussion in the * class docs for {@link DeterministicKeyChain} for more information on this topic.</p> */ public class KeyChainGroup implements KeyBag { /** * Builder for {@link KeyChainGroup}. Use {@link KeyChainGroup#builder(Network)} to acquire an instance. */ public static class Builder { private final Network network; private final KeyChainGroupStructure structure; private final List<DeterministicKeyChain> chains = new LinkedList<>(); private int lookaheadSize = -1, lookaheadThreshold = -1; private Builder(Network network, KeyChainGroupStructure structure) { this.network = network; this.structure = structure; } /** * <p>Add chain from a random source.</p> * <p>In the case of P2PKH, just a P2PKH chain is created and activated which is then the default chain for fresh * addresses. It can be upgraded to P2WPKH later.</p> * <p>In the case of P2WPKH, both a P2PKH and a P2WPKH chain are created and activated, the latter being the default * chain. This behaviour will likely be changed with bitcoinj 0.16 such that only a P2WPKH chain is created and * activated.</p> * @param outputScriptType type of addresses (aka output scripts) to generate for receiving */ public Builder fromRandom(ScriptType outputScriptType) { DeterministicSeed seed = DeterministicSeed.ofRandom(new SecureRandom(), DeterministicSeed.DEFAULT_SEED_ENTROPY_BITS, ""); fromSeed(seed, outputScriptType); return this; } /** * <p>Add chain from a given seed.</p> * <p>In the case of P2PKH, just a P2PKH chain is created and activated which is then the default chain for fresh * addresses. It can be upgraded to P2WPKH later.</p> * <p>In the case of P2WPKH, both a P2PKH and a P2WPKH chain are created and activated, the latter being the default * chain. This behaviour will likely be changed with bitcoinj 0.16 such that only a P2WPKH chain is created and * activated.</p> * @param seed deterministic seed to derive all keys from * @param outputScriptType type of addresses (aka output scripts) to generate for receiving */ public Builder fromSeed(DeterministicSeed seed, ScriptType outputScriptType) { if (outputScriptType == ScriptType.P2PKH) { DeterministicKeyChain chain = DeterministicKeyChain.builder().seed(seed) .outputScriptType(ScriptType.P2PKH) .accountPath(structure.accountPathFor(ScriptType.P2PKH, network)).build(); this.chains.clear(); this.chains.add(chain); } else if (outputScriptType == ScriptType.P2WPKH) { DeterministicKeyChain fallbackChain = DeterministicKeyChain.builder().seed(seed) .outputScriptType(ScriptType.P2PKH) .accountPath(structure.accountPathFor(ScriptType.P2PKH, network)).build(); DeterministicKeyChain defaultChain = DeterministicKeyChain.builder().seed(seed) .outputScriptType(ScriptType.P2WPKH) .accountPath(structure.accountPathFor(ScriptType.P2WPKH, network)).build(); this.chains.clear(); this.chains.add(fallbackChain); this.chains.add(defaultChain); } else { throw new IllegalArgumentException(outputScriptType.toString()); } return this; } /** * <p>Add chain from a given account key.</p> * <p>In the case of P2PKH, just a P2PKH chain is created and activated which is then the default chain for fresh * addresses. It can be upgraded to P2WPKH later.</p> * <p>In the case of P2WPKH, both a P2PKH and a P2WPKH chain are created and activated, the latter being the default * chain. This behaviour will likely be changed with bitcoinj 0.16 such that only a P2WPKH chain is created and * activated.</p> * @param accountKey deterministic account key to derive all keys from * @param outputScriptType type of addresses (aka output scripts) to generate for receiving */ public Builder fromKey(DeterministicKey accountKey, ScriptType outputScriptType) { if (outputScriptType == ScriptType.P2PKH) { DeterministicKeyChain chain = DeterministicKeyChain.builder().spend(accountKey) .outputScriptType(ScriptType.P2PKH) .accountPath(structure.accountPathFor(ScriptType.P2PKH, network)).build(); this.chains.clear(); this.chains.add(chain); } else if (outputScriptType == ScriptType.P2WPKH) { DeterministicKeyChain fallbackChain = DeterministicKeyChain.builder().spend(accountKey) .outputScriptType(ScriptType.P2PKH) .accountPath(structure.accountPathFor(ScriptType.P2PKH, network)).build(); DeterministicKeyChain defaultChain = DeterministicKeyChain.builder().spend(accountKey) .outputScriptType(ScriptType.P2WPKH) .accountPath(structure.accountPathFor(ScriptType.P2WPKH, network)).build(); this.chains.clear(); this.chains.add(fallbackChain); this.chains.add(defaultChain); } else { throw new IllegalArgumentException(outputScriptType.toString()); } return this; } /** * Add a single chain. * @param chain to add */ public Builder addChain(DeterministicKeyChain chain) { this.chains.add(chain); return this; } /** * Add multiple chains. * @param chains to add */ public Builder chains(List<DeterministicKeyChain> chains) { this.chains.clear(); this.chains.addAll(chains); return this; } /** * Set a custom lookahead size for all deterministic chains * @param lookaheadSize lookahead size */ public Builder lookaheadSize(int lookaheadSize) { this.lookaheadSize = lookaheadSize; return this; } /** * Set a custom lookahead threshold for all deterministic chains * @param lookaheadThreshold lookahead threshold */ public Builder lookaheadThreshold(int lookaheadThreshold) { this.lookaheadThreshold = lookaheadThreshold; return this; } public KeyChainGroup build() { return new KeyChainGroup(network, null, chains, lookaheadSize, lookaheadThreshold, null, null); } } private static final Logger log = LoggerFactory.getLogger(KeyChainGroup.class); private BasicKeyChain basic; private final Network network; // Keychains for deterministically derived keys. protected final @Nullable LinkedList<DeterministicKeyChain> chains; // currentKeys is used for normal, non-multisig/married wallets. currentAddresses is used when we're handing out // P2SH addresses. They're mutually exclusive. private final EnumMap<KeyChain.KeyPurpose, DeterministicKey> currentKeys; private final EnumMap<KeyChain.KeyPurpose, Address> currentAddresses; @Nullable private KeyCrypter keyCrypter; private int lookaheadSize = -1; private int lookaheadThreshold = -1; private final CopyOnWriteArrayList<ListenerRegistration<CurrentKeyChangeEventListener>> currentKeyChangeListeners = new CopyOnWriteArrayList<>(); /** Creates a keychain group with just a basic chain. No deterministic chains will be created automatically. */ public static KeyChainGroup createBasic(Network network) { return new KeyChainGroup(network, new BasicKeyChain(), null, -1, -1, null, null); } /** @deprecated use {@link #createBasic(Network)} */ @Deprecated public static KeyChainGroup createBasic(NetworkParameters params) { return createBasic(params.network()); } public static KeyChainGroup.Builder builder(Network network) { return new Builder(network, KeyChainGroupStructure.BIP32); } /** @deprecated use {@link #builder(Network)} */ @Deprecated public static KeyChainGroup.Builder builder(NetworkParameters params) { return builder(params.network()); } public static KeyChainGroup.Builder builder(Network network, KeyChainGroupStructure structure) { return new Builder(network, structure); } /** @deprecated use {@link #builder(Network, KeyChainGroupStructure)} */ @Deprecated public static KeyChainGroup.Builder builder(NetworkParameters params, KeyChainGroupStructure structure) { return builder(params.network(), structure); } private KeyChainGroup(Network network, @Nullable BasicKeyChain basicKeyChain, @Nullable List<DeterministicKeyChain> chains, int lookaheadSize, int lookaheadThreshold, @Nullable EnumMap<KeyChain.KeyPurpose, DeterministicKey> currentKeys, @Nullable KeyCrypter crypter) { this.network = network; this.basic = basicKeyChain == null ? new BasicKeyChain() : basicKeyChain; if (chains != null) { if (lookaheadSize > -1) this.lookaheadSize = lookaheadSize; if (lookaheadThreshold > -1) this.lookaheadThreshold = lookaheadThreshold; this.chains = new LinkedList<>(chains); for (DeterministicKeyChain chain : this.chains) { if (this.lookaheadSize > -1) chain.setLookaheadSize(this.lookaheadSize); if (this.lookaheadThreshold > -1) chain.setLookaheadThreshold(this.lookaheadThreshold); } } else { this.chains = null; } this.keyCrypter = crypter; this.currentKeys = currentKeys == null ? new EnumMap<KeyChain.KeyPurpose, DeterministicKey>(KeyChain.KeyPurpose.class) : currentKeys; this.currentAddresses = new EnumMap<>(KeyChain.KeyPurpose.class); } /** * Are any deterministic keychains supported? * @return true if it contains any deterministic keychain */ public boolean supportsDeterministicChains() { return chains != null; } /** * @return true if it contains any deterministic keychain * @deprecated Use {@link #supportsDeterministicChains()} */ @Deprecated public boolean isSupportsDeterministicChains() { return supportsDeterministicChains(); } // This keeps married redeem data in sync with the number of keys issued private void maybeLookaheadScripts() { for (DeterministicKeyChain chain : chains) { chain.maybeLookAheadScripts(); } } /** * Adds an HD chain to the chains list, and make it the default chain (from which keys are issued). * Useful for adding a complex pre-configured keychain, such as a married wallet. */ public void addAndActivateHDChain(DeterministicKeyChain chain) { checkState(supportsDeterministicChains(), () -> "doesn't support deterministic chains"); log.info("Activating a new HD chain: {}", chain); for (ListenerRegistration<KeyChainEventListener> registration : basic.getListeners()) chain.addEventListener(registration.listener, registration.executor); if (lookaheadSize >= 0) chain.setLookaheadSize(lookaheadSize); if (lookaheadThreshold >= 0) chain.setLookaheadThreshold(lookaheadThreshold); chains.add(chain); currentKeys.clear(); currentAddresses.clear(); queueOnCurrentKeyChanged(); } /** * Returns a key that hasn't been seen in a transaction yet, and which is suitable for displaying in a wallet * user interface as "a convenient key to receive funds on" when the purpose parameter is * {@link KeyChain.KeyPurpose#RECEIVE_FUNDS}. The returned key is stable until * it's actually seen in a pending or confirmed transaction, at which point this method will start returning * a different key (for each purpose independently). */ public DeterministicKey currentKey(KeyChain.KeyPurpose purpose) { DeterministicKeyChain chain = getActiveKeyChain(); DeterministicKey current = currentKeys.get(purpose); if (current == null) { current = freshKey(purpose); currentKeys.put(purpose, current); } return current; } /** * Returns address for a {@link #currentKey(KeyChain.KeyPurpose)} */ public Address currentAddress(KeyChain.KeyPurpose purpose) { DeterministicKeyChain chain = getActiveKeyChain(); ScriptType outputScriptType = chain.getOutputScriptType(); if (outputScriptType == ScriptType.P2PKH || outputScriptType == ScriptType.P2WPKH) { return currentKey(purpose).toAddress(outputScriptType, network); } else { throw new IllegalStateException(chain.getOutputScriptType().toString()); } } /** * Returns a key that has not been returned by this method before (fresh). You can think of this as being * a newly created key, although the notion of "create" is not really valid for a * {@link DeterministicKeyChain}. When the parameter is * {@link KeyChain.KeyPurpose#RECEIVE_FUNDS} the returned key is suitable for being put * into a receive coins wizard type UI. You should use this when the user is definitely going to hand this key out * to someone who wishes to send money. * <p>This method is not supposed to be used for married keychains and will throw UnsupportedOperationException if * the active chain is married. * For married keychains use {@link #freshAddress(KeyChain.KeyPurpose)} * to get a proper P2SH address</p> */ public DeterministicKey freshKey(KeyChain.KeyPurpose purpose) { return freshKeys(purpose, 1).get(0); } /** * Returns a key/s that have not been returned by this method before (fresh). You can think of this as being * newly created key/s, although the notion of "create" is not really valid for a * {@link DeterministicKeyChain}. When the parameter is * {@link KeyChain.KeyPurpose#RECEIVE_FUNDS} the returned key is suitable for being put * into a receive coins wizard type UI. You should use this when the user is definitely going to hand this key out * to someone who wishes to send money. */ public List<DeterministicKey> freshKeys(KeyChain.KeyPurpose purpose, int numberOfKeys) { DeterministicKeyChain chain = getActiveKeyChain(); return chain.getKeys(purpose, numberOfKeys); // Always returns the next key along the key chain. } /** * <p>Returns a fresh address for a given {@link KeyChain.KeyPurpose} and of a given * {@link ScriptType}.</p> * <p>This method is meant for when you really need a fallback address. Normally, you should be * using {@link #freshAddress(KeyChain.KeyPurpose)} or * {@link #currentAddress(KeyChain.KeyPurpose)}.</p> */ public Address freshAddress(KeyChain.KeyPurpose purpose, ScriptType outputScriptType, @Nullable Instant keyRotationTime) { DeterministicKeyChain chain = getActiveKeyChain(outputScriptType, keyRotationTime); return chain.getKey(purpose).toAddress(outputScriptType, network); } /** @deprecated use {@link #freshAddress(KeyChain.KeyPurpose, ScriptType, Instant)} */ @Deprecated public Address freshAddress(KeyChain.KeyPurpose purpose, ScriptType outputScriptType, long keyRotationTimeSecs) { Instant keyRotationTime = keyRotationTimeSecs > 0 ? Instant.ofEpochSecond(keyRotationTimeSecs) : null; return freshAddress(purpose, outputScriptType, keyRotationTime); } /** * Returns address for a {@link #freshKey(KeyChain.KeyPurpose)} */ public Address freshAddress(KeyChain.KeyPurpose purpose) { DeterministicKeyChain chain = getActiveKeyChain(); ScriptType outputScriptType = chain.getOutputScriptType(); if (outputScriptType == ScriptType.P2PKH || outputScriptType == ScriptType.P2WPKH) { return freshKey(purpose).toAddress(outputScriptType, network); } else { throw new IllegalStateException(chain.getOutputScriptType().toString()); } } /** * Returns the key chains that are used for generation of fresh/current keys, in the order of how they * were added. The default active chain will come last in the list. * @param keyRotationTime key rotation to take into account */ public List<DeterministicKeyChain> getActiveKeyChains(@Nullable Instant keyRotationTime) { checkState(supportsDeterministicChains(), () -> "doesn't support deterministic chains"); List<DeterministicKeyChain> activeChains = new LinkedList<>(); for (DeterministicKeyChain chain : chains) if (keyRotationTime == null || chain.earliestKeyCreationTime().compareTo(keyRotationTime) >= 0) activeChains.add(chain); return activeChains; } /** @deprecated use {@link #getActiveKeyChains(Instant)} */ @Deprecated public List<DeterministicKeyChain> getActiveKeyChains(long keyRotationTimeSecs) { Instant keyRotationTime = keyRotationTimeSecs > 0 ? Instant.ofEpochSecond(keyRotationTimeSecs) : null; return getActiveKeyChains(keyRotationTime); } /** * Returns the key chain that's used for generation of fresh/current keys of the given type. If it's not the default * type and no active chain for this type exists, {@code null} is returned. No upgrade or downgrade is tried. */ public final DeterministicKeyChain getActiveKeyChain(ScriptType outputScriptType, Instant keyRotationTime) { checkState(supportsDeterministicChains(), () -> "doesn't support deterministic chains"); List<DeterministicKeyChain> chainsReversed = new ArrayList<>(chains); Collections.reverse(chainsReversed); for (DeterministicKeyChain chain : chainsReversed) if (chain.getOutputScriptType() == outputScriptType && (keyRotationTime == null || chain.earliestKeyCreationTime().compareTo(keyRotationTime) >= 0)) return chain; return null; } /** @deprecated use {@link #getActiveKeyChain(ScriptType, Instant)} */ @Deprecated public final DeterministicKeyChain getActiveKeyChain(ScriptType outputScriptType, long keyRotationTimeSecs) { Instant keyRotationTime = keyRotationTimeSecs > 0 ? Instant.ofEpochSecond(keyRotationTimeSecs) : null; return getActiveKeyChain(outputScriptType, keyRotationTime); } /** * Returns the key chain that's used for generation of default fresh/current keys. This is always the newest * deterministic chain. If no deterministic chain is present but imported keys instead, a deterministic upgrate is * tried. */ public final DeterministicKeyChain getActiveKeyChain() { checkState(supportsDeterministicChains(), () -> "doesn't support deterministic chains"); if (chains.isEmpty()) throw new DeterministicUpgradeRequiredException(); return chains.get(chains.size() - 1); } /** * Merge all active chains from the given keychain group into this keychain group. */ public final void mergeActiveKeyChains(KeyChainGroup from, Instant keyRotationTime) { checkArgument(isEncrypted() == from.isEncrypted(), () -> "encrypted and non-encrypted keychains cannot be mixed"); for (DeterministicKeyChain chain : from.getActiveKeyChains(keyRotationTime)) addAndActivateHDChain(chain); } /** @deprecated use {@link #mergeActiveKeyChains(KeyChainGroup, Instant)} */ @Deprecated public final void mergeActiveKeyChains(KeyChainGroup from, long keyRotationTimeSecs) { Instant keyRotationTime = keyRotationTimeSecs > 0 ? Instant.ofEpochSecond(keyRotationTimeSecs) : null; mergeActiveKeyChains(from, keyRotationTime); } /** * Gets the current lookahead size being used for ALL deterministic key chains. See * {@link DeterministicKeyChain#setLookaheadSize(int)} * for more information. */ public int getLookaheadSize() { checkState(supportsDeterministicChains(), () -> "doesn't support deterministic chains"); if (lookaheadSize == -1) return getActiveKeyChain().getLookaheadSize(); else return lookaheadSize; } /** * Gets the current lookahead threshold being used for ALL deterministic key chains. See * {@link DeterministicKeyChain#setLookaheadThreshold(int)} * for more information. */ public int getLookaheadThreshold() { checkState(supportsDeterministicChains(), () -> "doesn't support deterministic chains"); if (lookaheadThreshold == -1) return getActiveKeyChain().getLookaheadThreshold(); else return lookaheadThreshold; } /** Imports the given keys into the basic chain, creating it if necessary. */ public int importKeys(List<ECKey> keys) { return basic.importKeys(keys); } /** Imports the given keys into the basic chain, creating it if necessary. */ public int importKeys(ECKey... keys) { return importKeys(Collections.unmodifiableList(Arrays.asList(keys))); } public boolean checkPassword(CharSequence password) { checkState(keyCrypter != null, () -> "not encrypted"); return checkAESKey(keyCrypter.deriveKey(password)); } public boolean checkAESKey(AesKey aesKey) { checkState(keyCrypter != null, () -> "not encrypted"); if (basic.numKeys() > 0) return basic.checkAESKey(aesKey); return getActiveKeyChain().checkAESKey(aesKey); } /** Imports the given unencrypted keys into the basic chain, encrypting them along the way with the given key. */ public int importKeysAndEncrypt(final List<ECKey> keys, AesKey aesKey) { // TODO: Firstly check if the aes key can decrypt any of the existing keys successfully. checkState(keyCrypter != null, () -> "not encrypted"); LinkedList<ECKey> encryptedKeys = new LinkedList<>(); for (ECKey key : keys) { if (key.isEncrypted()) throw new IllegalArgumentException("Cannot provide already encrypted keys"); encryptedKeys.add(key.encrypt(keyCrypter, aesKey)); } return importKeys(encryptedKeys); } @Override @Nullable public RedeemData findRedeemDataFromScriptHash(byte[] scriptHash) { if (chains != null) { // Iterate in reverse order, since the active keychain is the one most likely to have the hit for (Iterator<DeterministicKeyChain> iter = chains.descendingIterator(); iter.hasNext();) { DeterministicKeyChain chain = iter.next(); RedeemData redeemData = chain.findRedeemDataByScriptHash(ByteString.copyFrom(scriptHash)); if (redeemData != null) return redeemData; } } return null; } public void markP2SHAddressAsUsed(LegacyAddress address) { checkArgument(address.getOutputScriptType() == ScriptType.P2SH); RedeemData data = findRedeemDataFromScriptHash(address.getHash()); if (data == null) return; // Not our P2SH address. for (ECKey key : data.keys) { for (DeterministicKeyChain chain : chains) { DeterministicKey k = chain.findKeyFromPubKey(key.getPubKey()); if (k == null) continue; chain.markKeyAsUsed(k); maybeMarkCurrentAddressAsUsed(address); } } } @Nullable @Override public ECKey findKeyFromPubKeyHash(byte[] pubKeyHash, @Nullable ScriptType scriptType) { ECKey result; // BasicKeyChain can mix output script types. if ((result = basic.findKeyFromPubHash(pubKeyHash)) != null) return result; if (chains != null) { for (DeterministicKeyChain chain : chains) { // This check limits DeterministicKeyChain to specific output script usage. if (scriptType != null && scriptType != chain.getOutputScriptType()) continue; if ((result = chain.findKeyFromPubHash(pubKeyHash)) != null) return result; } } return null; } /** * Mark the DeterministicKeys as used, if they match the pubKeyHash * See {@link DeterministicKeyChain#markKeyAsUsed(DeterministicKey)} for more info on this. */ public void markPubKeyHashAsUsed(byte[] pubKeyHash) { if (chains != null) { for (DeterministicKeyChain chain : chains) { DeterministicKey key; if ((key = chain.markPubHashAsUsed(pubKeyHash)) != null) { maybeMarkCurrentKeyAsUsed(key); return; } } } } /** If the given P2SH address is "current", advance it to a new one. */ private void maybeMarkCurrentAddressAsUsed(LegacyAddress address) { checkArgument(address.getOutputScriptType() == ScriptType.P2SH); for (Map.Entry<KeyChain.KeyPurpose, Address> entry : currentAddresses.entrySet()) { if (entry.getValue() != null && entry.getValue().equals(address)) { log.info("Marking P2SH address as used: {}", address); currentAddresses.put(entry.getKey(), freshAddress(entry.getKey())); queueOnCurrentKeyChanged(); return; } } } /** If the given key is "current", advance the current key to a new one. */ private void maybeMarkCurrentKeyAsUsed(DeterministicKey key) { // It's OK for currentKeys to be empty here: it means we're a married wallet and the key may be a part of a // rotating chain. for (Map.Entry<KeyChain.KeyPurpose, DeterministicKey> entry : currentKeys.entrySet()) { if (entry.getValue() != null && entry.getValue().equals(key)) { log.info("Marking key as used: {}", key); currentKeys.put(entry.getKey(), freshKey(entry.getKey())); queueOnCurrentKeyChanged(); return; } } } public boolean hasKey(ECKey key) { if (basic.hasKey(key)) return true; if (chains != null) for (DeterministicKeyChain chain : chains) if (chain.hasKey(key)) return true; return false; } @Nullable @Override public ECKey findKeyFromPubKey(byte[] pubKey) { ECKey result; if ((result = basic.findKeyFromPubKey(pubKey)) != null) return result; if (chains != null) for (DeterministicKeyChain chain : chains) if ((result = chain.findKeyFromPubKey(pubKey)) != null) return result; return null; } /** * Mark the DeterministicKeys as used, if they match the pubkey * See {@link DeterministicKeyChain#markKeyAsUsed(DeterministicKey)} for more info on this. */ public void markPubKeyAsUsed(byte[] pubkey) { if (chains != null) { for (DeterministicKeyChain chain : chains) { DeterministicKey key; if ((key = chain.markPubKeyAsUsed(pubkey)) != null) { maybeMarkCurrentKeyAsUsed(key); return; } } } } /** Returns the number of keys managed by this group, including the lookahead buffers. */ public int numKeys() { int result = basic.numKeys(); if (chains != null) for (DeterministicKeyChain chain : chains) result += chain.numKeys(); return result; } /** * Removes a key that was imported into the basic key chain. You cannot remove deterministic keys. * @throws java.lang.IllegalArgumentException if the key is deterministic. */ public boolean removeImportedKey(ECKey key) { Objects.requireNonNull(key); checkArgument(!(key instanceof DeterministicKey)); return basic.removeKey(key); } /** * Encrypt the keys in the group using the KeyCrypter and the AES key. A good default KeyCrypter to use is * {@link KeyCrypterScrypt}. * * @throws org.bitcoinj.crypto.KeyCrypterException Thrown if the wallet encryption fails for some reason, * leaving the group unchanged. * @throws DeterministicUpgradeRequiredException Thrown if there are random keys but no HD chain. */ public void encrypt(KeyCrypter keyCrypter, AesKey aesKey) { Objects.requireNonNull(keyCrypter); Objects.requireNonNull(aesKey); checkState((chains != null && !chains.isEmpty()) || basic.numKeys() != 0, () -> "can't encrypt entirely empty wallet"); BasicKeyChain newBasic = basic.toEncrypted(keyCrypter, aesKey); List<DeterministicKeyChain> newChains = new ArrayList<>(); if (chains != null) { for (DeterministicKeyChain chain : chains) newChains.add(chain.toEncrypted(keyCrypter, aesKey)); } // Code below this point must be exception safe. this.keyCrypter = keyCrypter; this.basic = newBasic; if (chains != null) { this.chains.clear(); this.chains.addAll(newChains); } } /** * Decrypt the keys in the group using the previously given key crypter and the AES key. A good default * KeyCrypter to use is {@link KeyCrypterScrypt}. * * @throws org.bitcoinj.crypto.KeyCrypterException Thrown if the wallet decryption fails for some reason, leaving the group unchanged. */ public void decrypt(AesKey aesKey) { Objects.requireNonNull(aesKey); BasicKeyChain newBasic = basic.toDecrypted(aesKey); if (chains != null) { List<DeterministicKeyChain> newChains = new ArrayList<>(chains.size()); for (DeterministicKeyChain chain : chains) newChains.add(chain.toDecrypted(aesKey)); // Code below this point must be exception safe. this.chains.clear(); this.chains.addAll(newChains); } this.basic = newBasic; this.keyCrypter = null; } /** Returns true if the group is encrypted. */ public boolean isEncrypted() { return keyCrypter != null; } /** * Returns whether this chain has only watching keys (unencrypted keys with no private part). Mixed chains are * forbidden. * * @throws IllegalStateException if there are no keys, or if there is a mix between watching and non-watching keys. */ public boolean isWatching() { BasicKeyChain.State basicState = basic.isWatching(); BasicKeyChain.State activeState = BasicKeyChain.State.EMPTY; if (chains != null && !chains.isEmpty()) { if (getActiveKeyChain().isWatching()) activeState = BasicKeyChain.State.WATCHING; else activeState = BasicKeyChain.State.REGULAR; } if (basicState == BasicKeyChain.State.EMPTY) { if (activeState == BasicKeyChain.State.EMPTY) throw new IllegalStateException("Empty key chain group: cannot answer isWatching() query"); return activeState == BasicKeyChain.State.WATCHING; } else if (activeState == BasicKeyChain.State.EMPTY) return basicState == BasicKeyChain.State.WATCHING; else { if (activeState != basicState) throw new IllegalStateException("Mix of watching and non-watching keys in wallet"); return activeState == BasicKeyChain.State.WATCHING; } } /** Returns the key crypter or null if the group is not encrypted. */ @Nullable public KeyCrypter getKeyCrypter() { return keyCrypter; } /** * Returns a list of the non-deterministic keys that have been imported into the wallet, or the empty list if none. */ public List<ECKey> getImportedKeys() { return basic.getKeys(); } /** * Gets the earliest time for which full block must be downloaded. * @return earliest creation times of keys in this group, * {@link Instant#EPOCH} if at least one time is unknown, * {@link Instant#MAX} if no keys in this group */ public Instant earliestKeyCreationTime() { return TimeUtils.earlier(basic.earliestKeyCreationTime(), getEarliestChainsCreationTime()); } /** @deprecated use {@link #earliestKeyCreationTime()} */ @Deprecated public long getEarliestKeyCreationTime() { Instant earliestKeyCreationTime = earliestKeyCreationTime(); return earliestKeyCreationTime.equals(Instant.MAX) ? Long.MAX_VALUE : earliestKeyCreationTime.getEpochSecond(); } private Instant getEarliestChainsCreationTime() { return chains == null ? Instant.MAX : chains.stream() .map(DeterministicKeyChain::earliestKeyCreationTime) .min(Instant::compareTo) .orElse(Instant.MAX); } public int getBloomFilterElementCount() { int result = basic.numBloomFilterEntries(); if (chains != null) for (DeterministicKeyChain chain : chains) result += chain.numBloomFilterEntries(); return result; } public BloomFilter getBloomFilter(int size, double falsePositiveRate, int nTweak) { BloomFilter filter = new BloomFilter(size, falsePositiveRate, nTweak); if (basic.numKeys() > 0) filter.merge(basic.getFilter(size, falsePositiveRate, nTweak)); if (chains != null) for (DeterministicKeyChain chain : chains) filter.merge(chain.getFilter(size, falsePositiveRate, nTweak)); return filter; } public boolean isRequiringUpdateAllBloomFilter() { throw new UnsupportedOperationException(); // Unused. } /** Adds a listener for events that are run when keys are added, on the user thread. */ public void addEventListener(KeyChainEventListener listener) { addEventListener(listener, Threading.USER_THREAD); } /** Adds a listener for events that are run when keys are added, on the given executor. */ public void addEventListener(KeyChainEventListener listener, Executor executor) { Objects.requireNonNull(listener); Objects.requireNonNull(executor); basic.addEventListener(listener, executor); if (chains != null) for (DeterministicKeyChain chain : chains) chain.addEventListener(listener, executor); } /** Removes a listener for events that are run when keys are added. */ public boolean removeEventListener(KeyChainEventListener listener) { Objects.requireNonNull(listener); if (chains != null) for (DeterministicKeyChain chain : chains) chain.removeEventListener(listener); return basic.removeEventListener(listener); } /** Removes a listener for events that are run when a current key and/or address changes. */ public void addCurrentKeyChangeEventListener(CurrentKeyChangeEventListener listener) { addCurrentKeyChangeEventListener(listener, Threading.USER_THREAD); } /** * Adds a listener for events that are run when a current key and/or address changes, on the given * executor. */ public void addCurrentKeyChangeEventListener(CurrentKeyChangeEventListener listener, Executor executor) { Objects.requireNonNull(listener); currentKeyChangeListeners.add(new ListenerRegistration<>(listener, executor)); } /** Removes a listener for events that are run when a current key and/or address changes. */ public boolean removeCurrentKeyChangeEventListener(CurrentKeyChangeEventListener listener) { Objects.requireNonNull(listener); return ListenerRegistration.removeFromList(listener, currentKeyChangeListeners); } private void queueOnCurrentKeyChanged() { for (final ListenerRegistration<CurrentKeyChangeEventListener> registration : currentKeyChangeListeners) { registration.executor.execute(registration.listener::onCurrentKeyChanged); } } /** * Return a list of key protobufs obtained by merging the chains. * @return a list of key protobufs (treat as unmodifiable, will change in future release) */ public List<Protos.Key> serializeToProtobuf() { Stream<Protos.Key> basicStream = (basic != null) ? basic.serializeToProtobuf().stream() : Stream.empty(); Stream<Protos.Key> chainsStream = (chains != null) ? chains.stream().flatMap(chain -> chain.serializeToProtobuf().stream()) : Stream.empty(); return Stream.concat(basicStream, chainsStream) .collect(Collectors.toList()); } static KeyChainGroup fromProtobufUnencrypted(Network network, List<Protos.Key> keys) throws UnreadableWalletException { return fromProtobufUnencrypted(network, keys, new DefaultKeyChainFactory()); } public static KeyChainGroup fromProtobufUnencrypted(Network network, List<Protos.Key> keys, KeyChainFactory factory) throws UnreadableWalletException { BasicKeyChain basicKeyChain = BasicKeyChain.fromProtobufUnencrypted(keys); List<DeterministicKeyChain> chains = DeterministicKeyChain.fromProtobuf(keys, null, factory); int lookaheadSize = -1, lookaheadThreshold = -1; EnumMap<KeyChain.KeyPurpose, DeterministicKey> currentKeys = null; if (!chains.isEmpty()) { DeterministicKeyChain activeChain = chains.get(chains.size() - 1); lookaheadSize = activeChain.getLookaheadSize(); lookaheadThreshold = activeChain.getLookaheadThreshold(); currentKeys = createCurrentKeysMap(chains); } return new KeyChainGroup(network, basicKeyChain, chains, lookaheadSize, lookaheadThreshold, currentKeys, null); } static KeyChainGroup fromProtobufEncrypted(Network network, List<Protos.Key> keys, KeyCrypter crypter) throws UnreadableWalletException { return fromProtobufEncrypted(network, keys, crypter, new DefaultKeyChainFactory()); } public static KeyChainGroup fromProtobufEncrypted(Network network, List<Protos.Key> keys, KeyCrypter crypter, KeyChainFactory factory) throws UnreadableWalletException { Objects.requireNonNull(crypter); BasicKeyChain basicKeyChain = BasicKeyChain.fromProtobufEncrypted(keys, crypter); List<DeterministicKeyChain> chains = DeterministicKeyChain.fromProtobuf(keys, crypter, factory); int lookaheadSize = -1, lookaheadThreshold = -1; EnumMap<KeyChain.KeyPurpose, DeterministicKey> currentKeys = null; if (!chains.isEmpty()) { DeterministicKeyChain activeChain = chains.get(chains.size() - 1); lookaheadSize = activeChain.getLookaheadSize(); lookaheadThreshold = activeChain.getLookaheadThreshold(); currentKeys = createCurrentKeysMap(chains); } return new KeyChainGroup(network, basicKeyChain, chains, lookaheadSize, lookaheadThreshold, currentKeys, crypter); } /** * <p>This method will upgrade the wallet along the following path: {@code Basic --> P2PKH --> P2WPKH}</p> * <p>It won't skip any steps in that upgrade path because the user might be restoring from a backup and * still expects money on the P2PKH chain.</p> * <p>It will extract and reuse the seed from the current wallet, so that a fresh backup isn't required * after upgrading. If coming from a basic chain containing only random keys this means it will pick the * oldest non-rotating private key as a seed.</p> * <p>Note that for upgrading an encrypted wallet, the decryption key is needed. In future, we could skip * that requirement for a {@code P2PKH --> P2WPKH} upgrade and just clone the encryped seed, but currently * the key is needed even for that.</p> * * @param preferredScriptType desired script type for the active keychain * @param structure keychain group structure to derive an account path from * @param keyRotationTime If non-empty, time for which keys created before this are assumed to be * compromised or weak, those keys will not be used for deterministic upgrade. * @param aesKey If non-null, the encryption key the keychain is encrypted under. If the keychain is encrypted * and this is not supplied, an exception is thrown letting you know you should ask the user for * their password, turn it into a key, and then try again. * @throws java.lang.IllegalStateException if there is already a deterministic key chain present or if there are * no random keys (i.e. this is not an upgrade scenario), or if aesKey is * provided but the wallet is not encrypted. * @throws java.lang.IllegalArgumentException if the rotation time specified excludes all keys. * @throws DeterministicUpgradeRequiresPassword if the key chain group is encrypted * and you should provide the users encryption key. */ public void upgradeToDeterministic(ScriptType preferredScriptType, KeyChainGroupStructure structure, @Nullable Instant keyRotationTime, @Nullable AesKey aesKey) throws DeterministicUpgradeRequiresPassword { checkState(supportsDeterministicChains(), () -> "doesn't support deterministic chains"); Objects.requireNonNull(structure); if (!isDeterministicUpgradeRequired(preferredScriptType, keyRotationTime)) return; // Nothing to do. // P2PKH --> P2WPKH upgrade if (preferredScriptType == ScriptType.P2WPKH && getActiveKeyChain(ScriptType.P2WPKH, keyRotationTime) == null) { DeterministicSeed seed = getActiveKeyChain(ScriptType.P2PKH, keyRotationTime).getSeed(); boolean seedWasEncrypted = seed.isEncrypted(); if (seedWasEncrypted) { if (aesKey == null) throw new DeterministicUpgradeRequiresPassword(); seed = seed.decrypt(keyCrypter, "", aesKey); } log.info("Upgrading from P2PKH to P2WPKH deterministic keychain. Using seed: {}", seed); DeterministicKeyChain chain = DeterministicKeyChain.builder().seed(seed) .outputScriptType(ScriptType.P2WPKH) .accountPath(structure.accountPathFor(ScriptType.P2WPKH, BitcoinNetwork.MAINNET)).build(); if (seedWasEncrypted) chain = chain.toEncrypted(Objects.requireNonNull(keyCrypter), aesKey); addAndActivateHDChain(chain); } } /** @deprecated use {@link #upgradeToDeterministic(ScriptType, KeyChainGroupStructure, Instant, AesKey)} */ @Deprecated public void upgradeToDeterministic(ScriptType preferredScriptType, KeyChainGroupStructure structure, long keyRotationTimeSecs, @Nullable AesKey aesKey) { Instant keyRotationTime = keyRotationTimeSecs > 0 ? Instant.ofEpochSecond(keyRotationTimeSecs) : null; upgradeToDeterministic(preferredScriptType, structure, keyRotationTime, aesKey); } /** * Returns true if a call to {@link #upgradeToDeterministic(ScriptType, KeyChainGroupStructure, long, AesKey)} is required * in order to have an active deterministic keychain of the desired script type. */ public boolean isDeterministicUpgradeRequired(ScriptType preferredScriptType, @Nullable Instant keyRotationTime) { if (!supportsDeterministicChains()) return false; if (getActiveKeyChain(preferredScriptType, keyRotationTime) == null) return true; return false; } /** @deprecated use {@link #isDeterministicUpgradeRequired(ScriptType, Instant)} */ @Deprecated public boolean isDeterministicUpgradeRequired(ScriptType preferredScriptType, long keyRotationTimeSecs) { Instant keyRotationTime = keyRotationTimeSecs > 0 ? Instant.ofEpochSecond(keyRotationTimeSecs) : null; return isDeterministicUpgradeRequired(preferredScriptType, keyRotationTime); } private static EnumMap<KeyChain.KeyPurpose, DeterministicKey> createCurrentKeysMap(List<DeterministicKeyChain> chains) { DeterministicKeyChain activeChain = chains.get(chains.size() - 1); EnumMap<KeyChain.KeyPurpose, DeterministicKey> currentKeys = new EnumMap<>(KeyChain.KeyPurpose.class); // assuming that only RECEIVE and CHANGE keys are being used at the moment, we will treat latest issued external key // as current RECEIVE key and latest issued internal key as CHANGE key. This should be changed as soon as other // kinds of KeyPurpose are introduced. if (activeChain.getIssuedExternalKeys() > 0) { DeterministicKey currentExternalKey = activeChain.getKeyByPath( activeChain.getAccountPath() .extend(DeterministicKeyChain.EXTERNAL_SUBPATH) .extend(new ChildNumber(activeChain.getIssuedExternalKeys() - 1))); currentKeys.put(KeyChain.KeyPurpose.RECEIVE_FUNDS, currentExternalKey); } if (activeChain.getIssuedInternalKeys() > 0) { DeterministicKey currentInternalKey = activeChain.getKeyByPath( activeChain.getAccountPath() .extend(DeterministicKeyChain.INTERNAL_SUBPATH) .extend(new ChildNumber(activeChain.getIssuedInternalKeys() - 1))); currentKeys.put(KeyChain.KeyPurpose.CHANGE, currentInternalKey); } return currentKeys; } public String toString(boolean includeLookahead, boolean includePrivateKeys, @Nullable AesKey aesKey) { final StringBuilder builder = new StringBuilder(); if (basic != null) builder.append(basic.toString(includePrivateKeys, aesKey, network)); if (chains != null) for (DeterministicKeyChain chain : chains) builder.append(chain.toString(includeLookahead, includePrivateKeys, aesKey, network)).append('\n'); return builder.toString(); } /** Returns a copy of the current list of chains. */ public List<DeterministicKeyChain> getDeterministicKeyChains() { checkState(supportsDeterministicChains(), () -> "doesn't support deterministic chains"); return new ArrayList<>(chains); } /** * Returns a counter that increases (by an arbitrary amount) each time new keys have been calculated due to * lookahead and thus the Bloom filter that was previously calculated has become stale. */ public int getCombinedKeyLookaheadEpochs() { checkState(supportsDeterministicChains(), () -> "doesn't support deterministic chains"); int epoch = 0; for (DeterministicKeyChain chain : chains) epoch += chain.getKeyLookaheadEpoch(); return epoch; } }
52,408
46.08805
173
java
bitcoinj
bitcoinj-master/core/src/main/java/org/bitcoinj/wallet/RedeemData.java
/* * Copyright 2014 Kosta Korenkov * Copyright 2019 Andreas Schildbach * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.bitcoinj.wallet; import com.google.common.base.MoreObjects; import org.bitcoinj.crypto.ECKey; import org.bitcoinj.script.Script; import org.bitcoinj.script.ScriptPattern; import java.util.ArrayList; import java.util.Collections; import java.util.List; import static org.bitcoinj.base.internal.Preconditions.checkArgument; /** * This class aggregates data required to spend transaction output. * * For P2PKH and P2PK transactions it will have only a single key and CHECKSIG program as redeemScript. * For multisignature transactions there will be multiple keys one of which will be a full key and the rest are watch only, * redeem script will be a CHECKMULTISIG program. Keys will be sorted in the same order they appear in * a program (lexicographical order). */ public class RedeemData { public final Script redeemScript; public final List<ECKey> keys; private RedeemData(List<ECKey> keys, Script redeemScript) { this.redeemScript = redeemScript; List<ECKey> sortedKeys = new ArrayList<>(keys); Collections.sort(sortedKeys, ECKey.PUBKEY_COMPARATOR); this.keys = sortedKeys; } public static RedeemData of(List<ECKey> keys, Script redeemScript) { return new RedeemData(keys, redeemScript); } /** * Creates RedeemData for P2PKH, P2WPKH or P2PK input. Provided key is a single private key needed * to spend such inputs. */ public static RedeemData of(ECKey key, Script redeemScript) { checkArgument(ScriptPattern.isP2PKH(redeemScript) || ScriptPattern.isP2WPKH(redeemScript) || ScriptPattern.isP2PK(redeemScript)); return key != null ? new RedeemData(Collections.singletonList(key), redeemScript) : null; } /** * Returns the first key that has private bytes */ public ECKey getFullKey() { for (ECKey key : keys) if (key.hasPrivKey()) return key; return null; } @Override public String toString() { final MoreObjects.ToStringHelper helper = MoreObjects.toStringHelper(this).omitNullValues(); helper.add("redeemScript", redeemScript); helper.add("keys", keys); return helper.toString(); } }
2,882
34.158537
123
java
bitcoinj
bitcoinj-master/core/src/main/java/org/bitcoinj/wallet/WalletExtension.java
/* * Copyright 2013 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.bitcoinj.wallet; /** * <p>An object implementing this interface can be added to a {@link Wallet} and provide arbitrary byte arrays that will * be serialized alongside the wallet. Extensions can be mandatory, in which case applications that don't know how to * read the given data will refuse to load the wallet at all. Extensions identify themselves with a string ID that * should use a Java-style reverse DNS identifier to avoid being mixed up with other kinds of extension. To use an * extension, add an object that implements this interface to the wallet using {@link Wallet#addExtension(WalletExtension)} * before you load it (to read existing data) and ensure it's present when the wallet is save (to write the data).</p> * * <p>Note that extensions are singletons - you cannot add two objects that provide the same ID to the same wallet.</p> */ public interface WalletExtension { /** Returns a Java package/class style name used to disambiguate this extension from others. */ String getWalletExtensionID(); /** * If this returns true, the mandatory flag is set when the wallet is serialized and attempts to load it without * the extension being in the wallet will throw an exception. This method should not change its result during * the objects lifetime. */ boolean isWalletExtensionMandatory(); /** Returns bytes that will be saved in the wallet. */ byte[] serializeWalletExtension(); /** Loads the contents of this object from the wallet. */ void deserializeWalletExtension(Wallet containingWallet, byte[] data) throws Exception; }
2,212
48.177778
123
java
bitcoinj
bitcoinj-master/core/src/main/java/org/bitcoinj/wallet/listeners/ScriptsChangeEventListener.java
/* * Copyright 2013 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.bitcoinj.wallet.listeners; import org.bitcoinj.script.Script; import org.bitcoinj.wallet.Wallet; import java.util.List; /** * <p>Implementors are called when the contents of the wallet changes, for instance due to receiving/sending money * or a block chain re-organize.</p> */ public interface ScriptsChangeEventListener { /** * Called whenever a new watched script is added to the wallet. * * @param isAddingScripts will be true if added scripts, false if removed scripts. */ void onScriptsChanged(Wallet wallet, List<Script> scripts, boolean isAddingScripts); }
1,205
32.5
114
java
bitcoinj
bitcoinj-master/core/src/main/java/org/bitcoinj/wallet/listeners/WalletReorganizeEventListener.java
/* * Copyright 2013 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.bitcoinj.wallet.listeners; import org.bitcoinj.wallet.Wallet; /** * <p>Implementors are called when the wallet is reorganized.</p> */ public interface WalletReorganizeEventListener { // TODO: Finish onReorganize to be more useful. /** * <p>This is called when a block is received that triggers a block chain re-organization.</p> * * <p>A re-organize means that the consensus (chain) of the network has diverged and now changed from what we * believed it was previously. Usually this won't matter because the new consensus will include all our old * transactions assuming we are playing by the rules. However it's theoretically possible for our balance to * change in arbitrary ways, most likely, we could lose some money we thought we had.</p> * * <p>It is safe to use methods of wallet whilst inside this callback.</p> */ void onReorganize(Wallet wallet); }
1,527
39.210526
113
java
bitcoinj
bitcoinj-master/core/src/main/java/org/bitcoinj/wallet/listeners/AbstractKeyChainEventListener.java
/* * Copyright by the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.bitcoinj.wallet.listeners; import org.bitcoinj.crypto.ECKey; import java.util.List; public class AbstractKeyChainEventListener implements KeyChainEventListener { @Override public void onKeysAdded(List<ECKey> keys) { } }
861
29.785714
77
java
bitcoinj
bitcoinj-master/core/src/main/java/org/bitcoinj/wallet/listeners/WalletChangeEventListener.java
/* * Copyright 2013 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.bitcoinj.wallet.listeners; import org.bitcoinj.wallet.Wallet; /** * <p>Implementors are called when the contents of the wallet changes, for instance due to receiving/sending money * or a block chain re-organize.</p> */ public interface WalletChangeEventListener { /** * <p>Designed for GUI applications to refresh their transaction lists. This callback is invoked in the following * situations:</p> * * <ol> * <li>A new block is received (and thus building transactions got more confidence)</li> * <li>A pending transaction is received</li> * <li>A pending transaction changes confidence due to some non-new-block related event, such as being * announced by more peers or by a double-spend conflict being observed.</li> * <li>A re-organize occurs. Call occurs only if the re-org modified any of our transactions.</li> * <li>A new spend is committed to the wallet.</li> * <li>The wallet is reset and all transactions removed.<li> * </ol> * * <p>When this is called you can refresh the UI contents from the wallet contents. It's more efficient to use * this rather than onTransactionConfidenceChanged() + onReorganize() because you only get one callback per block * rather than one per transaction per block. Note that this is <b>not</b> called when a key is added. </p> */ void onWalletChanged(Wallet wallet); }
2,045
43.478261
117
java
bitcoinj
bitcoinj-master/core/src/main/java/org/bitcoinj/wallet/listeners/CurrentKeyChangeEventListener.java
/* * Copyright by the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.bitcoinj.wallet.listeners; import org.bitcoinj.wallet.KeyChainGroup; public interface CurrentKeyChangeEventListener { /** * Called by {@link KeyChainGroup} whenever a current key and/or address changes. */ void onCurrentKeyChanged(); }
881
31.666667
85
java
bitcoinj
bitcoinj-master/core/src/main/java/org/bitcoinj/wallet/listeners/WalletCoinsSentEventListener.java
/* * Copyright 2013 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.bitcoinj.wallet.listeners; import org.bitcoinj.base.Coin; import org.bitcoinj.core.Transaction; import org.bitcoinj.wallet.Wallet; /** * <p>Implementors are called when the contents of the wallet changes, for instance due to receiving/sending money * or a block chain re-organize.</p> */ public interface WalletCoinsSentEventListener { /** * This is called when a transaction is seen that sends coins <b>from</b> this wallet, either * because it was broadcast across the network or because a block was received. This may at first glance seem * useless, because in the common case you already know about such transactions because you created them with * the Wallets createSend/sendCoins methods. However when you have a wallet containing only keys, and you wish * to replay the block chain to fill it with transactions, it's useful to find out when a transaction is discovered * that sends coins from the wallet.<p> * * It's safe to modify the wallet from inside this callback, but if you're replaying the block chain you should * be careful to avoid such modifications. Otherwise your changes may be overridden by new data from the chain. * * @param wallet The wallet object that this callback relates to (that sent the coins). * @param tx The transaction that sent the coins to someone else. * @param prevBalance The wallets balance before this transaction was seen. * @param newBalance The wallets balance after this transaction was seen. This is the 'estimated' balance. */ void onCoinsSent(Wallet wallet, Transaction tx, Coin prevBalance, Coin newBalance); }
2,278
47.489362
119
java
bitcoinj
bitcoinj-master/core/src/main/java/org/bitcoinj/wallet/listeners/KeyChainEventListener.java
/* * Copyright 2013 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.bitcoinj.wallet.listeners; import org.bitcoinj.crypto.ECKey; import org.bitcoinj.wallet.KeyChain; import java.util.List; public interface KeyChainEventListener { /** * Called whenever a new key is added to the key chain, whether that be via an explicit addition or due to some * other automatic derivation. See the documentation for your {@link KeyChain} implementation for details on what * can trigger this event. */ void onKeysAdded(List<ECKey> keys); }
1,095
33.25
117
java
bitcoinj
bitcoinj-master/core/src/main/java/org/bitcoinj/wallet/listeners/WalletCoinsReceivedEventListener.java
/* * Copyright 2013 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.bitcoinj.wallet.listeners; import org.bitcoinj.base.Coin; import org.bitcoinj.core.Transaction; import org.bitcoinj.core.TransactionConfidence; import org.bitcoinj.wallet.Wallet; /** * <p>Implementors are called when the contents of the wallet changes, for instance due to receiving/sending money * or a block chain re-organize.</p> */ public interface WalletCoinsReceivedEventListener { /** * This is called when a transaction is seen that sends coins <b>to</b> this wallet, either because it * was broadcast across the network or because a block was received. If a transaction is seen when it was broadcast, * onCoinsReceived won't be called again when a block containing it is received. If you want to know when such a * transaction receives its first confirmation, register a {@link TransactionConfidence} event listener using * the object retrieved via {@link Transaction#getConfidence()}. It's safe to modify the * wallet in this callback, for example, by spending the transaction just received. * * @param wallet The wallet object that received the coins * @param tx The transaction which sent us the coins. * @param prevBalance Balance before the coins were received. * @param newBalance Current balance of the wallet. This is the 'estimated' balance. */ void onCoinsReceived(Wallet wallet, Transaction tx, Coin prevBalance, Coin newBalance); }
2,048
45.568182
120
java
bitcoinj
bitcoinj-master/core/src/main/java/org/bitcoinj/jni/NativeWalletCoinsSentEventListener.java
/* * Copyright 2013 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.bitcoinj.jni; import org.bitcoinj.base.Coin; import org.bitcoinj.core.Transaction; import org.bitcoinj.wallet.Wallet; import org.bitcoinj.wallet.listeners.WalletCoinsSentEventListener; /** * An event listener that relays events to a native C++ object. A pointer to that object is stored in * this class using JNI on the native side, thus several instances of this can point to different actual * native implementations. * @deprecated See https://github.com/bitcoinj/bitcoinj/issues/2465 */ @Deprecated public class NativeWalletCoinsSentEventListener implements WalletCoinsSentEventListener { public long ptr; @Override public native void onCoinsSent(Wallet wallet, Transaction tx, Coin prevBalance, Coin newBalance); }
1,346
35.405405
104
java
bitcoinj
bitcoinj-master/core/src/main/java/org/bitcoinj/jni/NativeKeyChainEventListener.java
/* * Copyright 2013 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.bitcoinj.jni; import org.bitcoinj.crypto.ECKey; import org.bitcoinj.wallet.listeners.KeyChainEventListener; import java.util.List; /** * An event listener that relays events to a native C++ object. A pointer to that object is stored in * this class using JNI on the native side, thus several instances of this can point to different actual * native implementations. * @deprecated See https://github.com/bitcoinj/bitcoinj/issues/2465 */ @Deprecated public class NativeKeyChainEventListener implements KeyChainEventListener { public long ptr; @Override public native void onKeysAdded(List<ECKey> keys); }
1,231
32.297297
104
java
bitcoinj
bitcoinj-master/core/src/main/java/org/bitcoinj/jni/NativeTransactionConfidenceListener.java
/* * Copyright 2013 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.bitcoinj.jni; import org.bitcoinj.core.TransactionConfidence; /** * An event listener that relays events to a native C++ object. A pointer to that object is stored in * this class using JNI on the native side, thus several instances of this can point to different actual * native implementations. * @deprecated See https://github.com/bitcoinj/bitcoinj/issues/2465 */ @Deprecated public class NativeTransactionConfidenceListener implements TransactionConfidence.Listener { public long ptr; @Override public native void onConfidenceChanged(TransactionConfidence confidence, ChangeReason reason); }
1,223
35
104
java
bitcoinj
bitcoinj-master/core/src/main/java/org/bitcoinj/jni/NativeWalletChangeEventListener.java
/* * Copyright 2013 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.bitcoinj.jni; import org.bitcoinj.wallet.Wallet; import org.bitcoinj.wallet.listeners.WalletChangeEventListener; /** * An event listener that relays events to a native C++ object. A pointer to that object is stored in * this class using JNI on the native side, thus several instances of this can point to different actual * native implementations. * @deprecated See https://github.com/bitcoinj/bitcoinj/issues/2465 */ @Deprecated public class NativeWalletChangeEventListener implements WalletChangeEventListener { public long ptr; @Override public native void onWalletChanged(Wallet wallet); }
1,221
33.914286
104
java
bitcoinj
bitcoinj-master/core/src/main/java/org/bitcoinj/jni/NativeScriptsChangeEventListener.java
/* * Copyright 2013 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.bitcoinj.jni; import org.bitcoinj.script.Script; import org.bitcoinj.wallet.Wallet; import org.bitcoinj.wallet.listeners.ScriptsChangeEventListener; import java.util.List; /** * An event listener that relays events to a native C++ object. A pointer to that object is stored in * this class using JNI on the native side, thus several instances of this can point to different actual * native implementations. * @deprecated See https://github.com/bitcoinj/bitcoinj/issues/2465 */ @Deprecated public class NativeScriptsChangeEventListener implements ScriptsChangeEventListener { public long ptr; @Override public native void onScriptsChanged(Wallet wallet, List<Script> scripts, boolean isAddingScripts); }
1,331
34.052632
104
java
bitcoinj
bitcoinj-master/core/src/main/java/org/bitcoinj/jni/NativeWalletCoinsReceivedEventListener.java
/* * Copyright 2013 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.bitcoinj.jni; import org.bitcoinj.base.Coin; import org.bitcoinj.core.Transaction; import org.bitcoinj.wallet.Wallet; import org.bitcoinj.wallet.listeners.WalletCoinsReceivedEventListener; /** * An event listener that relays events to a native C++ object. A pointer to that object is stored in * this class using JNI on the native side, thus several instances of this can point to different actual * native implementations. * @deprecated See https://github.com/bitcoinj/bitcoinj/issues/2465 */ @Deprecated public class NativeWalletCoinsReceivedEventListener implements WalletCoinsReceivedEventListener { public long ptr; @Override public native void onCoinsReceived(Wallet wallet, Transaction tx, Coin prevBalance, Coin newBalance); }
1,362
35.837838
105
java
bitcoinj
bitcoinj-master/core/src/main/java/org/bitcoinj/jni/NativeFutureCallback.java
/* * Copyright 2013 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.bitcoinj.jni; import com.google.common.util.concurrent.FutureCallback; /** * An event listener that relays events to a native C++ object. A pointer to that object is stored in * this class using JNI on the native side, thus several instances of this can point to different actual * native implementations. * @deprecated See https://github.com/bitcoinj/bitcoinj/issues/2465 */ @Deprecated public class NativeFutureCallback implements FutureCallback { public long ptr; @Override public native void onSuccess(Object o); @Override public native void onFailure(Throwable throwable); }
1,216
31.891892
104
java
bitcoinj
bitcoinj-master/core/src/main/java/org/bitcoinj/jni/NativeWalletReorganizeEventListener.java
/* * Copyright 2013 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.bitcoinj.jni; import org.bitcoinj.wallet.Wallet; import org.bitcoinj.wallet.listeners.WalletReorganizeEventListener; /** * An event listener that relays events to a native C++ object. A pointer to that object is stored in * this class using JNI on the native side, thus several instances of this can point to different actual * native implementations. * @deprecated See https://github.com/bitcoinj/bitcoinj/issues/2465 */ @Deprecated public class NativeWalletReorganizeEventListener implements WalletReorganizeEventListener { public long ptr; @Override public native void onReorganize(Wallet wallet); }
1,230
34.171429
104
java
bitcoinj
bitcoinj-master/core/src/main/java/org/bitcoinj/jni/NativeBlockChainListener.java
/* * Copyright 2013 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.bitcoinj.jni; import org.bitcoinj.core.BlockChain; import org.bitcoinj.base.Sha256Hash; import org.bitcoinj.core.StoredBlock; import org.bitcoinj.core.Transaction; import org.bitcoinj.core.VerificationException; import org.bitcoinj.core.listeners.NewBestBlockListener; import org.bitcoinj.core.listeners.ReorganizeListener; import org.bitcoinj.core.listeners.TransactionReceivedInBlockListener; import java.util.List; /** * An event listener that relays events to a native C++ object. A pointer to that object is stored in * this class using JNI on the native side, thus several instances of this can point to different actual * native implementations. * @deprecated See https://github.com/bitcoinj/bitcoinj/issues/2465 */ @Deprecated public class NativeBlockChainListener implements NewBestBlockListener, ReorganizeListener, TransactionReceivedInBlockListener { public long ptr; @Override public native void notifyNewBestBlock(StoredBlock block) throws VerificationException; @Override public native void reorganize(StoredBlock splitPoint, List<StoredBlock> oldBlocks, List<StoredBlock> newBlocks) throws VerificationException; @Override public native void receiveFromBlock(Transaction tx, StoredBlock block, BlockChain.NewBlockType blockType, int relativityOffset) throws VerificationException; @Override public native boolean notifyTransactionIsInBlock(Sha256Hash txHash, StoredBlock block, BlockChain.NewBlockType blockType, int relativityOffset) throws VerificationException; }
2,231
40.333333
145
java
bitcoinj
bitcoinj-master/core/src/main/java/org/bitcoinj/jni/NativeTransactionConfidenceEventListener.java
/* * Copyright 2013 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.bitcoinj.jni; import org.bitcoinj.core.Transaction; import org.bitcoinj.core.listeners.TransactionConfidenceEventListener; import org.bitcoinj.wallet.Wallet; /** * An event listener that relays events to a native C++ object. A pointer to that object is stored in * this class using JNI on the native side, thus several instances of this can point to different actual * native implementations. * @deprecated See https://github.com/bitcoinj/bitcoinj/issues/2465 */ @Deprecated public class NativeTransactionConfidenceEventListener implements TransactionConfidenceEventListener { public long ptr; @Override public native void onTransactionConfidenceChanged(Wallet wallet, Transaction tx); }
1,315
35.555556
104
java
bitcoinj
bitcoinj-master/core/src/main/java/org/bitcoinj/params/BitcoinNetworkParams.java
/* * Copyright 2013 Google Inc. * Copyright 2015 Andreas Schildbach * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.bitcoinj.params; import org.bitcoinj.base.BitcoinNetwork; import org.bitcoinj.base.internal.Stopwatch; import org.bitcoinj.base.internal.TimeUtils; import org.bitcoinj.base.internal.ByteUtils; import org.bitcoinj.core.BitcoinSerializer; import org.bitcoinj.core.Block; import org.bitcoinj.base.Coin; import org.bitcoinj.core.NetworkParameters; import org.bitcoinj.base.Sha256Hash; import org.bitcoinj.core.ProtocolVersion; import org.bitcoinj.core.StoredBlock; import org.bitcoinj.core.VerificationException; import org.bitcoinj.protocols.payments.PaymentProtocol; import org.bitcoinj.store.BlockStore; import org.bitcoinj.store.BlockStoreException; import org.bitcoinj.base.utils.MonetaryFormat; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.annotation.Nullable; import java.math.BigInteger; import java.time.Duration; import java.time.Instant; import java.time.temporal.Temporal; import java.time.temporal.TemporalUnit; import java.util.concurrent.TimeUnit; import static org.bitcoinj.base.internal.Preconditions.checkState; /** * Parameters for Bitcoin-like networks. */ public abstract class BitcoinNetworkParams extends NetworkParameters { /** * Scheme part for Bitcoin URIs. * @deprecated Use {@link BitcoinNetwork#BITCOIN_SCHEME} */ @Deprecated public static final String BITCOIN_SCHEME = BitcoinNetwork.BITCOIN_SCHEME; /** * Block reward halving interval (number of blocks) */ public static final int REWARD_HALVING_INTERVAL = 210_000; private static final Logger log = LoggerFactory.getLogger(BitcoinNetworkParams.class); /** lazy-initialized by the first call to {@link NetworkParameters#getGenesisBlock()} */ protected Block genesisBlock; /** * No-args constructor */ public BitcoinNetworkParams(BitcoinNetwork network) { super(network); interval = INTERVAL; subsidyDecreaseBlockCount = REWARD_HALVING_INTERVAL; } /** * Return network parameters for a network id * @param id the network id * @return the network parameters for the given string ID or NULL if not recognized */ @Nullable public static BitcoinNetworkParams fromID(String id) { if (id.equals(BitcoinNetwork.ID_MAINNET)) { return MainNetParams.get(); } else if (id.equals(BitcoinNetwork.ID_TESTNET)) { return TestNet3Params.get(); } else if (id.equals(BitcoinNetwork.ID_SIGNET)) { return SigNetParams.get(); } else if (id.equals(BitcoinNetwork.ID_REGTEST)) { return RegTestParams.get(); } else { return null; } } /** * Return network parameters for a {@link BitcoinNetwork} enum * @param network the network * @return the network parameters for the given string ID * @throws IllegalArgumentException if unknown network */ public static BitcoinNetworkParams of(BitcoinNetwork network) { switch (network) { case MAINNET: return MainNetParams.get(); case TESTNET: return TestNet3Params.get(); case SIGNET: return SigNetParams.get(); case REGTEST: return RegTestParams.get(); default: throw new IllegalArgumentException("Unknown network"); } } /** * @return the payment protocol network id string * @deprecated Use {@link PaymentProtocol#protocolIdFromParams(NetworkParameters)} */ @Deprecated public String getPaymentProtocolId() { return PaymentProtocol.protocolIdFromParams(this); } /** * Checks if we are at a reward halving point. * @param previousHeight The height of the previous stored block * @return If this is a reward halving point */ public final boolean isRewardHalvingPoint(final int previousHeight) { return ((previousHeight + 1) % REWARD_HALVING_INTERVAL) == 0; } /** * <p>A utility method that calculates how much new Bitcoin would be created by the block at the given height. * The inflation of Bitcoin is predictable and drops roughly every 4 years (210,000 blocks). At the dawn of * the system it was 50 coins per block, in late 2012 it went to 25 coins per block, and so on. The size of * a coinbase transaction is inflation plus fees.</p> * * <p>The half-life is controlled by {@link NetworkParameters#getSubsidyDecreaseBlockCount()}.</p> * * @param height the height of the block to calculate inflation for * @return block reward (inflation) for specified block */ public Coin getBlockInflation(int height) { return Coin.FIFTY_COINS.shiftRight(height / getSubsidyDecreaseBlockCount()); } /** * Checks if we are at a difficulty transition point. * @param previousHeight The height of the previous stored block * @return If this is a difficulty transition point */ public final boolean isDifficultyTransitionPoint(final int previousHeight) { return ((previousHeight + 1) % this.getInterval()) == 0; } @Override public void checkDifficultyTransitions(final StoredBlock storedPrev, final Block nextBlock, final BlockStore blockStore) throws VerificationException, BlockStoreException { final Block prev = storedPrev.getHeader(); // Is this supposed to be a difficulty transition point? if (!isDifficultyTransitionPoint(storedPrev.getHeight())) { // No ... so check the difficulty didn't actually change. if (nextBlock.getDifficultyTarget() != prev.getDifficultyTarget()) throw new VerificationException("Unexpected change in difficulty at height " + storedPrev.getHeight() + ": " + Long.toHexString(nextBlock.getDifficultyTarget()) + " vs " + Long.toHexString(prev.getDifficultyTarget())); return; } // We need to find a block far back in the chain. It's OK that this is expensive because it only occurs every // two weeks after the initial block chain download. Stopwatch watch = Stopwatch.start(); Sha256Hash hash = prev.getHash(); StoredBlock cursor = null; final int interval = this.getInterval(); for (int i = 0; i < interval; i++) { cursor = blockStore.get(hash); if (cursor == null) { // This should never happen. If it does, it means we are following an incorrect or busted chain. throw new VerificationException( "Difficulty transition point but we did not find a way back to the last transition point. Not found: " + hash); } hash = cursor.getHeader().getPrevBlockHash(); } checkState(cursor != null && isDifficultyTransitionPoint(cursor.getHeight() - 1), () -> "didn't arrive at a transition point"); watch.stop(); if (watch.elapsed().toMillis() > 50) log.info("Difficulty transition traversal took {}", watch); Block blockIntervalAgo = cursor.getHeader(); int timespan = (int) (prev.getTimeSeconds() - blockIntervalAgo.getTimeSeconds()); // Limit the adjustment step. final int targetTimespan = this.getTargetTimespan(); if (timespan < targetTimespan / 4) timespan = targetTimespan / 4; if (timespan > targetTimespan * 4) timespan = targetTimespan * 4; BigInteger newTarget = ByteUtils.decodeCompactBits(prev.getDifficultyTarget()); newTarget = newTarget.multiply(BigInteger.valueOf(timespan)); newTarget = newTarget.divide(BigInteger.valueOf(targetTimespan)); BigInteger maxTarget = this.getMaxTarget(); if (newTarget.compareTo(maxTarget) > 0) { log.info("Difficulty hit proof of work limit: {} vs {}", Long.toHexString(ByteUtils.encodeCompactBits(newTarget)), Long.toHexString(ByteUtils.encodeCompactBits(maxTarget))); newTarget = maxTarget; } int accuracyBytes = (int) (nextBlock.getDifficultyTarget() >>> 24) - 3; long receivedTargetCompact = nextBlock.getDifficultyTarget(); // The calculated difficulty is to a higher precision than received, so reduce here. BigInteger mask = BigInteger.valueOf(0xFFFFFFL).shiftLeft(accuracyBytes * 8); newTarget = newTarget.and(mask); long newTargetCompact = ByteUtils.encodeCompactBits(newTarget); if (newTargetCompact != receivedTargetCompact) throw new VerificationException("Network provided difficulty bits do not match what was calculated: " + Long.toHexString(newTargetCompact) + " vs " + Long.toHexString(receivedTargetCompact)); } @Override @Deprecated public Coin getMaxMoney() { return BitcoinNetwork.MAX_MONEY; } /** * @deprecated Get one another way or construct your own {@link MonetaryFormat} as needed. */ @Override @Deprecated public MonetaryFormat getMonetaryFormat() { return new MonetaryFormat(); } @Override public BitcoinSerializer getSerializer() { return new BitcoinSerializer(this); } @Override @Deprecated public String getUriScheme() { return BitcoinNetwork.BITCOIN_SCHEME; } @Override @Deprecated public boolean hasMaxMoney() { return network().hasMaxMoney(); } }
10,237
37.488722
135
java
bitcoinj
bitcoinj-master/core/src/main/java/org/bitcoinj/params/package-info.java
/* * Copyright by the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * Network parameters encapsulate some of the differences between different Bitcoin networks such as the main * network, the testnet, regtest mode, unit testing params and so on. */ package org.bitcoinj.params;
830
38.571429
109
java
bitcoinj
bitcoinj-master/core/src/main/java/org/bitcoinj/params/TestNet3Params.java
/* * Copyright 2013 Google Inc. * Copyright 2014 Andreas Schildbach * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.bitcoinj.params; import org.bitcoinj.base.BitcoinNetwork; import org.bitcoinj.base.internal.ByteUtils; import org.bitcoinj.core.Block; import org.bitcoinj.core.NetworkParameters; import org.bitcoinj.base.Sha256Hash; import org.bitcoinj.core.StoredBlock; import org.bitcoinj.core.VerificationException; import org.bitcoinj.store.BlockStore; import org.bitcoinj.store.BlockStoreException; import java.math.BigInteger; import java.time.Instant; import static org.bitcoinj.base.internal.Preconditions.checkState; /** * Parameters for the testnet, a separate public instance of Bitcoin that has relaxed rules suitable for development * and testing of applications and new Bitcoin versions. */ public class TestNet3Params extends BitcoinNetworkParams { public static final int TESTNET_MAJORITY_WINDOW = 100; public static final int TESTNET_MAJORITY_REJECT_BLOCK_OUTDATED = 75; public static final int TESTNET_MAJORITY_ENFORCE_BLOCK_UPGRADE = 51; private static final long GENESIS_TIME = 1296688602; private static final long GENESIS_NONCE = 414098458; private static final Sha256Hash GENESIS_HASH = Sha256Hash.wrap("000000000933ea01ad0ee984209779baaec3ced90fa3f408719526f8d77f4943"); public TestNet3Params() { super(BitcoinNetwork.TESTNET); targetTimespan = TARGET_TIMESPAN; maxTarget = ByteUtils.decodeCompactBits(Block.STANDARD_MAX_DIFFICULTY_TARGET); port = 18333; packetMagic = 0x0b110907; dumpedPrivateKeyHeader = 239; addressHeader = 111; p2shHeader = 196; segwitAddressHrp = "tb"; spendableCoinbaseDepth = 100; bip32HeaderP2PKHpub = 0x043587cf; // The 4 byte header that serializes in base58 to "tpub". bip32HeaderP2PKHpriv = 0x04358394; // The 4 byte header that serializes in base58 to "tprv" bip32HeaderP2WPKHpub = 0x045f1cf6; // The 4 byte header that serializes in base58 to "vpub". bip32HeaderP2WPKHpriv = 0x045f18bc; // The 4 byte header that serializes in base58 to "vprv" majorityEnforceBlockUpgrade = TESTNET_MAJORITY_ENFORCE_BLOCK_UPGRADE; majorityRejectBlockOutdated = TESTNET_MAJORITY_REJECT_BLOCK_OUTDATED; majorityWindow = TESTNET_MAJORITY_WINDOW; dnsSeeds = new String[] { "testnet-seed.bitcoin.jonasschnelli.ch", // Jonas Schnelli "seed.tbtc.petertodd.org", // Peter Todd "seed.testnet.bitcoin.sprovoost.nl", // Sjors Provoost "testnet-seed.bluematt.me", // Matt Corallo }; addrSeeds = null; } private static TestNet3Params instance; public static synchronized TestNet3Params get() { if (instance == null) { instance = new TestNet3Params(); } return instance; } @Override public Block getGenesisBlock() { synchronized (GENESIS_HASH) { if (genesisBlock == null) { genesisBlock = Block.createGenesis(); genesisBlock.setDifficultyTarget(Block.STANDARD_MAX_DIFFICULTY_TARGET); genesisBlock.setTime(Instant.ofEpochSecond(GENESIS_TIME)); genesisBlock.setNonce(GENESIS_NONCE); checkState(genesisBlock.getHash().equals(GENESIS_HASH), () -> "invalid genesis hash"); } } return genesisBlock; } // February 16th 2012 private static final Instant testnetDiffDate = Instant.ofEpochMilli(1329264000000L); @Override public void checkDifficultyTransitions(final StoredBlock storedPrev, final Block nextBlock, final BlockStore blockStore) throws VerificationException, BlockStoreException { if (!isDifficultyTransitionPoint(storedPrev.getHeight()) && nextBlock.time().isAfter(testnetDiffDate)) { Block prev = storedPrev.getHeader(); // After 15th February 2012 the rules on the testnet change to avoid people running up the difficulty // and then leaving, making it too hard to mine a block. On non-difficulty transition points, easy // blocks are allowed if there has been a span of 20 minutes without one. final long timeDelta = nextBlock.getTimeSeconds() - prev.getTimeSeconds(); // There is an integer underflow bug in bitcoin-qt that means mindiff blocks are accepted when time // goes backwards. if (timeDelta >= 0 && timeDelta <= NetworkParameters.TARGET_SPACING * 2) { // Walk backwards until we find a block that doesn't have the easiest proof of work, then check // that difficulty is equal to that one. StoredBlock cursor = storedPrev; while (!cursor.getHeader().equals(getGenesisBlock()) && cursor.getHeight() % getInterval() != 0 && cursor.getHeader().getDifficultyTargetAsInteger().equals(getMaxTarget())) cursor = cursor.getPrev(blockStore); BigInteger cursorTarget = cursor.getHeader().getDifficultyTargetAsInteger(); BigInteger newTarget = nextBlock.getDifficultyTargetAsInteger(); if (!cursorTarget.equals(newTarget)) throw new VerificationException("Testnet block transition that is not allowed: " + Long.toHexString(cursor.getHeader().getDifficultyTarget()) + " vs " + Long.toHexString(nextBlock.getDifficultyTarget())); } } else { super.checkDifficultyTransitions(storedPrev, nextBlock, blockStore); } } }
6,323
45.160584
135
java
bitcoinj
bitcoinj-master/core/src/main/java/org/bitcoinj/params/MainNetParams.java
/* * Copyright 2013 Google Inc. * Copyright 2015 Andreas Schildbach * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.bitcoinj.params; import org.bitcoinj.base.BitcoinNetwork; import org.bitcoinj.base.internal.ByteUtils; import org.bitcoinj.core.Block; import org.bitcoinj.base.Sha256Hash; import java.time.Instant; import static org.bitcoinj.base.internal.Preconditions.checkState; /** * Parameters for the main production network on which people trade goods and services. */ public class MainNetParams extends BitcoinNetworkParams { public static final int MAINNET_MAJORITY_WINDOW = 1000; public static final int MAINNET_MAJORITY_REJECT_BLOCK_OUTDATED = 950; public static final int MAINNET_MAJORITY_ENFORCE_BLOCK_UPGRADE = 750; private static final long GENESIS_TIME = 1231006505; private static final long GENESIS_NONCE = 2083236893; private static final Sha256Hash GENESIS_HASH = Sha256Hash.wrap("000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f"); public MainNetParams() { super(BitcoinNetwork.MAINNET); targetTimespan = TARGET_TIMESPAN; maxTarget = ByteUtils.decodeCompactBits(Block.STANDARD_MAX_DIFFICULTY_TARGET); port = 8333; packetMagic = 0xf9beb4d9; dumpedPrivateKeyHeader = 128; addressHeader = 0; p2shHeader = 5; segwitAddressHrp = "bc"; spendableCoinbaseDepth = 100; bip32HeaderP2PKHpub = 0x0488b21e; // The 4 byte header that serializes in base58 to "xpub". bip32HeaderP2PKHpriv = 0x0488ade4; // The 4 byte header that serializes in base58 to "xprv" bip32HeaderP2WPKHpub = 0x04b24746; // The 4 byte header that serializes in base58 to "zpub". bip32HeaderP2WPKHpriv = 0x04b2430c; // The 4 byte header that serializes in base58 to "zprv" majorityEnforceBlockUpgrade = MAINNET_MAJORITY_ENFORCE_BLOCK_UPGRADE; majorityRejectBlockOutdated = MAINNET_MAJORITY_REJECT_BLOCK_OUTDATED; majorityWindow = MAINNET_MAJORITY_WINDOW; // This contains (at a minimum) the blocks which are not BIP30 compliant. BIP30 changed how duplicate // transactions are handled. Duplicated transactions could occur in the case where a coinbase had the same // extraNonce and the same outputs but appeared at different heights, and greatly complicated re-org handling. // Having these here simplifies block connection logic considerably. checkpoints.put(91722, Sha256Hash.wrap("00000000000271a2dc26e7667f8419f2e15416dc6955e5a6c6cdf3f2574dd08e")); checkpoints.put(91812, Sha256Hash.wrap("00000000000af0aed4792b1acee3d966af36cf5def14935db8de83d6f9306f2f")); checkpoints.put(91842, Sha256Hash.wrap("00000000000a4d0a398161ffc163c503763b1f4360639393e0e4c8e300e0caec")); checkpoints.put(91880, Sha256Hash.wrap("00000000000743f190a18c5577a3c2d2a1f610ae9601ac046a38084ccb7cd721")); checkpoints.put(200000, Sha256Hash.wrap("000000000000034a7dedef4a161fa058a2d67a173a90155f3a2fe6fc132e0ebf")); dnsSeeds = new String[] { "seed.bitcoin.sipa.be", // Pieter Wuille "dnsseed.bluematt.me", // Matt Corallo "dnsseed.bitcoin.dashjr.org", // Luke Dashjr "seed.bitcoinstats.com", // Chris Decker "seed.bitcoin.jonasschnelli.ch",// Jonas Schnelli "seed.btc.petertodd.org", // Peter Todd "seed.bitcoin.sprovoost.nl", // Sjors Provoost "dnsseed.emzy.de", // Stephan Oeste "seed.bitcoin.wiz.biz", // Jason Maurice }; // These are in big-endian format, which is what the SeedPeers code expects. // Updated Apr. 11th 2019 addrSeeds = new int[] { // seed.bitcoin.sipa.be 0x117c7e18, 0x12641955, 0x1870652e, 0x1dfec3b9, 0x4a330834, 0x5b53382d, 0x77abaca3, 0x09e3d36c, 0xa0a4e1d4, 0xa275d9c7, 0xa280bc4b, 0xa50d1b76, 0x0a5f84cb, 0xa86cd5bd, 0xb3f427ba, 0xc6fc4cd0, 0xc73c19b9, 0xd905d85f, 0xd919f9ad, 0xda3fc312, 0xdc4ca5b9, 0xe38ef05b, 0xedce8e57, 0xf68ad23e, 0xfb3b9c59, // dnsseed.bluematt.me 0x1061d85f, 0x2d5325b0, 0x3505ef91, 0x4c42b14c, 0x623cce72, 0x067e4428, 0x6b47e32e, 0x6e47e32e, 0x87aed35f, 0x96fe3234, 0xac81419f, 0xb6f9bb25, 0xc9ddb4b9, 0xcbd8aca3, 0xd55c09b0, 0xd5640618, 0xdaa9144e, 0xdfb99088, 0xe0339650, 0xeb8221af, 0xfcbfd75b, // dnsseed.bitcoin.dashjr.org 0x028ea62e, 0x2cf968be, 0x2d9cf023, 0x3bedb812, 0x40373745, 0x40aa9850, 0x42504a28, 0x50b8f655, 0x5a86e548, 0x6d79f459, 0x70681b41, 0x74a8cf1f, 0x779233d4, 0x8b2380b2, 0x9dcc342f, 0xa331b5ad, 0xa95b4c90, 0xb05ff750, 0x0bfde3d4, 0x0c15c136, 0xd3912552, 0xd56ce69d, 0xd8af5454, 0xfce48068, // seed.bitcoinstats.com 0x10c23a35, 0x1168b223, 0x11ae871f, 0x14ddce34, 0x018ce3d5, 0x1b242934, 0x20bcf754, 0x33954d33, 0x355609b0, 0x39fd202f, 0x4df35e2f, 0x4f23f22b, 0x5707f862, 0x8602bdce, 0x8e09703e, 0x90009ede, 0x9ffb125b, 0xa33c4c90, 0xa9c4ec57, 0xaa2d5097, 0xae52fb94, 0x00ed2636, 0xedf5649f, 0x0f41a6bc, 0xfe03cf22, // seed.bitcoin.jonasschnelli.ch 0x23159dd8, 0x368fea55, 0x50bd4031, 0x5395de6c, 0x05c6902f, 0x60c09350, 0x66d6d168, 0x70d90337, 0x7a549ac3, 0x9012d552, 0x94a60f33, 0xa490ff36, 0xb030d552, 0xb0729450, 0xb12b4c4a, 0x0b7e7e60, 0xc4f84b2f, 0xc533f42f, 0xc8f60ec2, 0xc9d1bab9, 0xd329cb74, 0xe4b26ab4, 0xe70e5db0, 0xec072034, // seed.btc.petertodd.org 0x10ac1242, 0x131c4a79, 0x1477da47, 0x2899ec63, 0x45660451, 0x4b1b0050, 0x6931d0c2, 0x070ed85f, 0x806a9950, 0x80b0d522, 0x810d2bc1, 0x829d3b8b, 0x848bdfb0, 0x87a5e52e, 0x9664bb25, 0xa021a6df, 0x0a5f8548, 0x0a66c752, 0xaaf5b64f, 0xabba464a, 0xc5df4165, 0xe8c5efd5, 0xfa08d01f, // seed.bitcoin.sprovoost.nl 0x14420418, 0x1efdd990, 0x32ded23a, 0x364e1e54, 0x3981d262, 0x39ae6ed3, 0x5143a699, 0x68f861cb, 0x6f229e23, 0x6fe45d8e, 0x77db09b0, 0x7a1cd85f, 0x8dd03b8b, 0x92aec9c3, 0xa2debb23, 0xa47dee50, 0xb3566bb4, 0xcb1845b9, 0xcd51c253, 0xd541574d, 0xe0cba936, 0xfb2c26d0, // dnsseed.emzy.de 0x16e0d7b9, 0x1719c2b9, 0x1edfd04a, 0x287eff2d, 0x28f54e3e, 0x3574c1bc, 0x36f1b4cf, 0x3932571b, 0x3d6f9bbc, 0x4458aa3a, 0x4dd2cf52, 0x05483e97, 0x559caed5, 0x59496251, 0x66d432c6, 0x7501f7c7, 0x7775599f, 0x8e0ea28b, 0x8f3d0d9d, 0x902695de, 0xa6ada27b, 0xbb00875b, 0xbc26c979, 0xd1a2c58a, 0xf6d33b8b, 0xf9d95947, }; } private static MainNetParams instance; public static synchronized MainNetParams get() { if (instance == null) { instance = new MainNetParams(); } return instance; } @Override public Block getGenesisBlock() { synchronized (GENESIS_HASH) { if (genesisBlock == null) { genesisBlock = Block.createGenesis(); genesisBlock.setDifficultyTarget(Block.STANDARD_MAX_DIFFICULTY_TARGET); genesisBlock.setTime(Instant.ofEpochSecond(GENESIS_TIME)); genesisBlock.setNonce(GENESIS_NONCE); checkState(genesisBlock.getHash().equals(GENESIS_HASH), () -> "invalid genesis hash"); } } return genesisBlock; } }
8,181
54.659864
135
java
bitcoinj
bitcoinj-master/core/src/main/java/org/bitcoinj/params/Networks.java
/* * Copyright 2014 Giannis Dzegoutanis * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.bitcoinj.params; import org.bitcoinj.base.Network; import org.bitcoinj.base.SegwitAddress; import org.bitcoinj.core.NetworkParameters; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashSet; import java.util.Optional; import java.util.Set; /** * Utility class that holds all the registered {@link NetworkParameters} types used for address auto discovery. * By default only {@link MainNetParams} and {@link TestNet3Params} are used. If you want to use {@link RegTestParams} * or {@link UnitTestParams} use {@code register} and then {@code unregister} the {@code TestNet3Params} as they don't * have their own Base58 version/type code (although for {@link SegwitAddress} the human-readable * parts for RegTest and TestNet are different.) */ public class Networks { /** Registered networks */ private static Set<NetworkParameters> networks = unmodifiableSet(TestNet3Params.get(), MainNetParams.get()); public static Set<NetworkParameters> get() { return networks; } /** * Find a {@link NetworkParameters} for a {@link Network} * @param network The network to find (convert) * @return Matching params if one was registered */ public static Optional<NetworkParameters> find(Network network) { return networks.stream() .filter(p -> p.getId().equals(network.id())) .findFirst(); } /** * Register a single network type by adding it to the {@code Set}. * * @param network Network to register/add. */ public static void register(NetworkParameters network) { register(Collections.singleton(network)); } /** * Register a collection of additional network types by adding them * to the {@code Set}. * * @param networks Networks to register/add. */ public static void register(Collection<NetworkParameters> networks) { Networks.networks = combinedSet(Networks.networks, networks); } /** * Unregister a network type. * * @param network Network type to unregister/remove. */ public static void unregister(NetworkParameters network) { Networks.networks = removeFromSet(networks, network); } // Create an unmodifiable set of NetworkParameters from an array/varargs private static Set<NetworkParameters> unmodifiableSet(NetworkParameters... ts) { return Collections.unmodifiableSet(new HashSet<>(Arrays.asList(ts))); } // Create an unmodifiable set by combining two collections private static <T> Set<T> combinedSet(Collection<T> a, Collection<T> b) { Set<T> tempSet = new HashSet<>(a); tempSet.addAll(b); return Collections.unmodifiableSet(tempSet); } // Create a new unmodifiable set by removing an item from an existing set private static <T> Set<T> removeFromSet(Set<T> set, T item) { Set<T> tempSet = new HashSet<>(set); tempSet.remove(item); return Collections.unmodifiableSet(tempSet); } }
3,676
34.699029
118
java
bitcoinj
bitcoinj-master/core/src/main/java/org/bitcoinj/params/SigNetParams.java
/* * Copyright by the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.bitcoinj.params; import org.bitcoinj.base.BitcoinNetwork; import org.bitcoinj.base.internal.ByteUtils; import org.bitcoinj.core.Block; import org.bitcoinj.base.Sha256Hash; import java.time.Instant; import static org.bitcoinj.base.internal.Preconditions.checkState; /** * <p>Parameters for the signet, a separate public instance of Bitcoin that has relaxed rules suitable for development * and testing of applications and new Bitcoin versions.</p> * <p>See <a href="https://github.com/bitcoin/bips/blob/master/bip-0325.mediawiki">BIP325</a> */ public class SigNetParams extends BitcoinNetworkParams { public static final int TESTNET_MAJORITY_WINDOW = 100; public static final int TESTNET_MAJORITY_REJECT_BLOCK_OUTDATED = 75; public static final int TESTNET_MAJORITY_ENFORCE_BLOCK_UPGRADE = 51; private static final long GENESIS_DIFFICULTY = 0x1e0377ae; private static final long GENESIS_TIME = 1598918400; private static final long GENESIS_NONCE = 52613770; private static final Sha256Hash GENESIS_HASH = Sha256Hash.wrap("00000008819873e925422c1ff0f99f7cc9bbb232af63a077a480a3633bee1ef6"); public SigNetParams() { super(BitcoinNetwork.SIGNET); targetTimespan = TARGET_TIMESPAN; maxTarget = ByteUtils.decodeCompactBits(Block.EASIEST_DIFFICULTY_TARGET); port = 38333; packetMagic = 0x0a03cf40; dumpedPrivateKeyHeader = 239; addressHeader = 0x6f; p2shHeader = 196; segwitAddressHrp = "tb"; spendableCoinbaseDepth = 100; bip32HeaderP2PKHpub = 0x043587cf; // The 4 byte header that serializes in base58 to "tpub". bip32HeaderP2PKHpriv = 0x04358394; // The 4 byte header that serializes in base58 to "tprv" bip32HeaderP2WPKHpub = bip32HeaderP2PKHpub; bip32HeaderP2WPKHpriv = bip32HeaderP2PKHpriv; majorityEnforceBlockUpgrade = TESTNET_MAJORITY_ENFORCE_BLOCK_UPGRADE; majorityRejectBlockOutdated = TESTNET_MAJORITY_REJECT_BLOCK_OUTDATED; majorityWindow = TESTNET_MAJORITY_WINDOW; dnsSeeds = new String[] { "seed.signet.bitcoin.sprovoost.nl", }; addrSeeds = null; } private static SigNetParams instance; public static synchronized SigNetParams get() { if (instance == null) { instance = new SigNetParams(); } return instance; } @Override public Block getGenesisBlock() { synchronized (GENESIS_HASH) { if (genesisBlock == null) { genesisBlock = Block.createGenesis(); genesisBlock.setDifficultyTarget(GENESIS_DIFFICULTY); genesisBlock.setTime(Instant.ofEpochSecond(GENESIS_TIME)); genesisBlock.setNonce(GENESIS_NONCE); checkState(genesisBlock.getHash().equals(GENESIS_HASH), () -> "invalid genesis hash"); } } return genesisBlock; } }
3,589
37.602151
135
java
bitcoinj
bitcoinj-master/core/src/main/java/org/bitcoinj/params/RegTestParams.java
/* * Copyright 2013 Google Inc. * Copyright 2018 Andreas Schildbach * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.bitcoinj.params; import org.bitcoinj.base.BitcoinNetwork; import org.bitcoinj.base.internal.ByteUtils; import org.bitcoinj.core.Block; import org.bitcoinj.base.Sha256Hash; import java.time.Instant; import static org.bitcoinj.base.internal.Preconditions.checkState; /** * Network parameters for the regression test mode of bitcoind in which all blocks are trivially solvable. */ public class RegTestParams extends BitcoinNetworkParams { private static final long GENESIS_TIME = 1296688602; private static final long GENESIS_NONCE = 2; private static final Sha256Hash GENESIS_HASH = Sha256Hash.wrap("0f9188f13cb7b2c71f2a335e3a4fc328bf5beb436012afca590b1a11466e2206"); public RegTestParams() { super(BitcoinNetwork.REGTEST); targetTimespan = TARGET_TIMESPAN; maxTarget = ByteUtils.decodeCompactBits(Block.EASIEST_DIFFICULTY_TARGET); // Difficulty adjustments are disabled for regtest. // By setting the block interval for difficulty adjustments to Integer.MAX_VALUE we make sure difficulty never // changes. interval = Integer.MAX_VALUE; subsidyDecreaseBlockCount = 150; port = 18444; packetMagic = 0xfabfb5da; dumpedPrivateKeyHeader = 239; addressHeader = 111; p2shHeader = 196; segwitAddressHrp = "bcrt"; spendableCoinbaseDepth = 100; bip32HeaderP2PKHpub = 0x043587cf; // The 4 byte header that serializes in base58 to "tpub". bip32HeaderP2PKHpriv = 0x04358394; // The 4 byte header that serializes in base58 to "tprv" bip32HeaderP2WPKHpub = 0x045f1cf6; // The 4 byte header that serializes in base58 to "vpub". bip32HeaderP2WPKHpriv = 0x045f18bc; // The 4 byte header that serializes in base58 to "vprv" majorityEnforceBlockUpgrade = MainNetParams.MAINNET_MAJORITY_ENFORCE_BLOCK_UPGRADE; majorityRejectBlockOutdated = MainNetParams.MAINNET_MAJORITY_REJECT_BLOCK_OUTDATED; majorityWindow = MainNetParams.MAINNET_MAJORITY_WINDOW; dnsSeeds = null; addrSeeds = null; } @Override public boolean allowEmptyPeerChain() { return true; } private static RegTestParams instance; public static synchronized RegTestParams get() { if (instance == null) { instance = new RegTestParams(); } return instance; } @Override public Block getGenesisBlock() { synchronized (GENESIS_HASH) { if (genesisBlock == null) { genesisBlock = Block.createGenesis(); genesisBlock.setDifficultyTarget(Block.EASIEST_DIFFICULTY_TARGET); genesisBlock.setTime(Instant.ofEpochSecond(GENESIS_TIME)); genesisBlock.setNonce(GENESIS_NONCE); checkState(genesisBlock.getHash().equals(GENESIS_HASH), () -> "invalid genesis hash"); } } return genesisBlock; } }
3,615
36.666667
135
java
bitcoinj
bitcoinj-master/core/src/main/java/org/bitcoinj/params/UnitTestParams.java
/* * Copyright 2013 Google Inc. * Copyright 2019 Andreas Schildbach * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.bitcoinj.params; import org.bitcoinj.base.BitcoinNetwork; import org.bitcoinj.base.internal.TimeUtils; import org.bitcoinj.base.internal.ByteUtils; import org.bitcoinj.core.Block; /** * Network parameters used by the bitcoinj unit tests (and potentially your own). This lets you solve a block using * {@link Block#solve()} by setting difficulty to the easiest possible. */ public class UnitTestParams extends BitcoinNetworkParams { public static final int UNITNET_MAJORITY_WINDOW = 8; public static final int TESTNET_MAJORITY_REJECT_BLOCK_OUTDATED = 6; public static final int TESTNET_MAJORITY_ENFORCE_BLOCK_UPGRADE = 4; public UnitTestParams() { // Unit Test Params are BY DEFINITION on the Bitcoin TEST network (i.e. not REGTEST or SIGNET) // This means that tests that run against UnitTestParams expect TEST network behavior. super(BitcoinNetwork.TESTNET); targetTimespan = 200000000; // 6 years. Just a very big number. maxTarget = ByteUtils.decodeCompactBits(Block.EASIEST_DIFFICULTY_TARGET); interval = 10; subsidyDecreaseBlockCount = 100; port = 18333; packetMagic = 0x0b110907; dumpedPrivateKeyHeader = 239; addressHeader = 111; p2shHeader = 196; segwitAddressHrp = "tb"; spendableCoinbaseDepth = 5; bip32HeaderP2PKHpub = 0x043587cf; // The 4 byte header that serializes in base58 to "tpub". bip32HeaderP2PKHpriv = 0x04358394; // The 4 byte header that serializes in base58 to "tprv" bip32HeaderP2WPKHpub = 0x045f1cf6; // The 4 byte header that serializes in base58 to "vpub". bip32HeaderP2WPKHpriv = 0x045f18bc; // The 4 byte header that serializes in base58 to "vprv" majorityEnforceBlockUpgrade = 3; majorityRejectBlockOutdated = 4; majorityWindow = 7; dnsSeeds = null; addrSeeds = null; } private static UnitTestParams instance; public static synchronized UnitTestParams get() { if (instance == null) { instance = new UnitTestParams(); } return instance; } @Override public Block getGenesisBlock() { synchronized (this) { if (genesisBlock == null) { genesisBlock = Block.createGenesis(); genesisBlock.setDifficultyTarget(Block.EASIEST_DIFFICULTY_TARGET); genesisBlock.setTime(TimeUtils.currentTime()); } } return genesisBlock; } }
3,160
36.630952
115
java
bitcoinj
bitcoinj-master/core/src/main/java/org/bitcoinj/uri/package-info.java
/* * Copyright by the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * Parsing and handling of bitcoin: textual URIs as found in qr codes and web links. */ package org.bitcoinj.uri;
732
35.65
84
java
bitcoinj
bitcoinj-master/core/src/main/java/org/bitcoinj/uri/OptionalFieldValidationException.java
/* * Copyright by the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.bitcoinj.uri; /** * <p>Exception to provide the following to {@link BitcoinURI}:</p> * <ul> * <li>Provision of parsing error messages</li> * </ul> * <p>This exception occurs when an optional field is detected (under the Bitcoin URI scheme) and fails * to pass the associated test (such as {@code amount} not being a valid number).</p> * * @since 0.3.0 *   */ public class OptionalFieldValidationException extends BitcoinURIParseException { public OptionalFieldValidationException(String s) { super(s); } public OptionalFieldValidationException(String s, Throwable throwable) { super(s, throwable); } }
1,280
31.025
103
java
bitcoinj
bitcoinj-master/core/src/main/java/org/bitcoinj/uri/BitcoinURI.java
/* * Copyright 2012, 2014 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.bitcoinj.uri; import org.bitcoinj.base.BitcoinNetwork; import org.bitcoinj.base.Network; import org.bitcoinj.base.exceptions.AddressFormatException; import org.bitcoinj.base.Coin; import org.bitcoinj.base.Address; import org.bitcoinj.base.DefaultAddressParser; import org.bitcoinj.core.NetworkParameters; import javax.annotation.Nonnull; import javax.annotation.Nullable; import java.io.UnsupportedEncodingException; import java.net.URI; import java.net.URISyntaxException; import java.net.URLDecoder; import java.util.ArrayList; import java.util.Collections; import java.util.LinkedHashMap; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Objects; /** * <p>Provides a standard implementation of a Bitcoin URI with support for the following:</p> * * <ul> * <li>URLEncoded URIs (as passed in by IE on the command line)</li> * <li>BIP21 names (including the "req-" prefix handling requirements)</li> * </ul> * * <h2>Accepted formats</h2> * * <p>The following input forms are accepted:</p> * * <ul> * <li>{@code bitcoin:<address>}</li> * <li>{@code bitcoin:<address>?<name1>=<value1>&<name2>=<value2>} with multiple * additional name/value pairs</li> * </ul> * * <p>The name/value pairs are processed as follows.</p> * <ol> * <li>URL encoding is stripped and treated as UTF-8</li> * <li>names prefixed with {@code req-} are treated as required and if unknown or conflicting cause a parse exception</li> * <li>Unknown names not prefixed with {@code req-} are added to a Map, accessible by parameter name</li> * <li>Known names not prefixed with {@code req-} are processed unless they are malformed</li> * </ol> * * <p>The following names are known and have the following formats:</p> * <ul> * <li>{@code amount} decimal value to 8 dp (e.g. 0.12345678) <b>Note that the * exponent notation is not supported any more</b></li> * <li>{@code label} any URL encoded alphanumeric</li> * <li>{@code message} any URL encoded alphanumeric</li> * </ul> * * @author Andreas Schildbach (initial code) * @author Jim Burton (enhancements for MultiBit) * @author Gary Rowe (BIP21 support) * @see <a href="https://github.com/bitcoin/bips/blob/master/bip-0021.mediawiki">BIP 0021</a> */ public class BitcoinURI { // Not worth turning into an enum public static final String FIELD_MESSAGE = "message"; public static final String FIELD_LABEL = "label"; public static final String FIELD_AMOUNT = "amount"; public static final String FIELD_ADDRESS = "address"; public static final String FIELD_PAYMENT_REQUEST_URL = "r"; /** * URI Scheme for Bitcoin network. * @deprecated Use {@link BitcoinNetwork#BITCOIN_SCHEME}. */ @Deprecated public static final String BITCOIN_SCHEME = BitcoinNetwork.BITCOIN_SCHEME; private static final String ENCODED_SPACE_CHARACTER = "%20"; private static final String AMPERSAND_SEPARATOR = "&"; private static final String QUESTION_MARK_SEPARATOR = "?"; /** * Contains all the parameters in the order in which they were processed */ private final Map<String, Object> parameterMap = new LinkedHashMap<>(); /** * Constructs a new BitcoinURI from the given string. Can be for any network. * * @param uri The raw URI data to be parsed (see class comments for accepted formats) * @throws BitcoinURIParseException if the URI is not syntactically or semantically valid. */ public static BitcoinURI of(String uri) throws BitcoinURIParseException { // TODO: Discover (via Service Loader mechanism) the correct Network from the URI string return new BitcoinURI(uri, null); } /** * Constructs a new object by trying to parse the input as a valid Bitcoin URI. * * @param uri The raw URI data to be parsed (see class comments for accepted formats) * @param network The network the URI is from * @throws BitcoinURIParseException If the input fails Bitcoin URI syntax and semantic checks. */ public static BitcoinURI of(String uri, @Nonnull Network network) throws BitcoinURIParseException { return new BitcoinURI(uri, Objects.requireNonNull(network)); } /** * Constructs a new object by trying to parse the input as a valid Bitcoin URI. * * @param params The network parameters that determine which network the URI is from, or null if you don't have * any expectation about what network the URI is for and wish to check yourself. * @param input The raw URI data to be parsed (see class comments for accepted formats) * * @throws BitcoinURIParseException If the input fails Bitcoin URI syntax and semantic checks. * @deprecated Use {@link BitcoinURI#of(String, Network)} or {@link BitcoinURI#of(String)} */ @Deprecated public BitcoinURI(@Nullable NetworkParameters params, String input) throws BitcoinURIParseException { this(input, params != null ? params.network() : null); } private BitcoinURI(String input, @Nullable Network network) throws BitcoinURIParseException { Objects.requireNonNull(input); String scheme = network != null ? network.uriScheme() : BitcoinNetwork.BITCOIN_SCHEME; // Attempt to form the URI (fail fast syntax checking to official standards). URI uri; try { uri = new URI(input); } catch (URISyntaxException e) { throw new BitcoinURIParseException("Bad URI syntax", e); } // URI is formed as bitcoin:<address>?<query parameters> // blockchain.info generates URIs of non-BIP compliant form bitcoin://address?.... // We support both until Ben fixes his code. // Remove the bitcoin scheme. // (Note: getSchemeSpecificPart() is not used as it unescapes the label and parse then fails. // For instance with : bitcoin:129mVqKUmJ9uwPxKJBnNdABbuaaNfho4Ha?amount=0.06&label=Tom%20%26%20Jerry // the & (%26) in Tom and Jerry gets interpreted as a separator and the label then gets parsed // as 'Tom ' instead of 'Tom & Jerry') String blockchainInfoScheme = scheme + "://"; String correctScheme = scheme + ":"; String schemeSpecificPart; final String inputLc = input.toLowerCase(Locale.US); if (inputLc.startsWith(blockchainInfoScheme)) { schemeSpecificPart = input.substring(blockchainInfoScheme.length()); } else if (inputLc.startsWith(correctScheme)) { schemeSpecificPart = input.substring(correctScheme.length()); } else { throw new BitcoinURIParseException("Unsupported URI scheme: " + uri.getScheme()); } // Split off the address from the rest of the query parameters. String[] addressSplitTokens = schemeSpecificPart.split("\\?", 2); if (addressSplitTokens.length == 0) throw new BitcoinURIParseException("No data found after the bitcoin: prefix"); String addressToken = addressSplitTokens[0]; // may be empty! String[] nameValuePairTokens; if (addressSplitTokens.length == 1) { // Only an address is specified - use an empty '<name>=<value>' token array. nameValuePairTokens = new String[] {}; } else { // Split into '<name>=<value>' tokens. nameValuePairTokens = addressSplitTokens[1].split("&"); } // Attempt to parse the rest of the URI parameters. parseParameters(nameValuePairTokens); if (!addressToken.isEmpty()) { // Attempt to parse the addressToken as a Bitcoin address for this network try { DefaultAddressParser addressParser = new DefaultAddressParser(); Address address = network != null ? addressParser.parseAddress(addressToken, network) : addressParser.parseAddressAnyNetwork(addressToken); putWithValidation(FIELD_ADDRESS, address); } catch (final AddressFormatException e) { throw new BitcoinURIParseException("Bad address", e); } } if (addressToken.isEmpty() && getPaymentRequestUrl() == null) { throw new BitcoinURIParseException("No address and no r= parameter found"); } } /** * @param nameValuePairTokens The tokens representing the name value pairs (assumed to be * separated by '=' e.g. 'amount=0.2') */ private void parseParameters(String[] nameValuePairTokens) throws BitcoinURIParseException { // Attempt to decode the rest of the tokens into a parameter map. for (String nameValuePairToken : nameValuePairTokens) { final int sepIndex = nameValuePairToken.indexOf('='); if (sepIndex == -1) throw new BitcoinURIParseException("Malformed Bitcoin URI - no separator in '" + nameValuePairToken + "'"); if (sepIndex == 0) throw new BitcoinURIParseException("Malformed Bitcoin URI - empty name '" + nameValuePairToken + "'"); final String nameToken = nameValuePairToken.substring(0, sepIndex).toLowerCase(Locale.ENGLISH); final String valueToken = nameValuePairToken.substring(sepIndex + 1); // Parse the amount. if (FIELD_AMOUNT.equals(nameToken)) { // Decode the amount (contains an optional decimal component to 8dp). try { Coin amount = Coin.parseCoin(valueToken); if (amount.signum() < 0) throw new OptionalFieldValidationException("negative amount not allowed: " + valueToken); putWithValidation(FIELD_AMOUNT, amount); } catch (IllegalArgumentException e) { throw new OptionalFieldValidationException("not a valid amount: " + valueToken, e); } } else { if (nameToken.startsWith("req-")) { // A required parameter that we do not know about. throw new RequiredFieldValidationException("'" + nameToken + "' is required but not known, this URI is not valid"); } else { // Known fields and unknown parameters that are optional. try { if (valueToken.length() > 0) putWithValidation(nameToken, URLDecoder.decode(valueToken, "UTF-8")); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); // can't happen } } } } // Note to the future: when you want to implement 'req-expires' have a look at commit 410a53791841 // which had it in. } /** * Put the value against the key in the map checking for duplication. This avoids address field overwrite etc. * * @param key The key for the map * @param value The value to store */ private void putWithValidation(String key, Object value) throws BitcoinURIParseException { if (parameterMap.containsKey(key)) { throw new BitcoinURIParseException(String.format(Locale.US, "'%s' is duplicated, URI is invalid", key)); } else { parameterMap.put(key, value); } } /** * The Bitcoin address from the URI, if one was present. It's possible to have Bitcoin URI's with no address if a * r= payment protocol parameter is specified, though this form is not recommended as older wallets can't understand * it. */ @Nullable public Address getAddress() { return (Address) parameterMap.get(FIELD_ADDRESS); } /** * @return The amount name encoded using a pure integer value based at * 10,000,000 units is 1 BTC. May be null if no amount is specified */ public Coin getAmount() { return (Coin) parameterMap.get(FIELD_AMOUNT); } /** * @return The label from the URI. */ public String getLabel() { return (String) parameterMap.get(FIELD_LABEL); } /** * @return The message from the URI. */ public String getMessage() { return (String) parameterMap.get(FIELD_MESSAGE); } /** * @return The URL where a payment request (as specified in BIP 70) may * be fetched. */ public final String getPaymentRequestUrl() { return (String) parameterMap.get(FIELD_PAYMENT_REQUEST_URL); } /** * Returns the URLs where a payment request (as specified in BIP 70) may be fetched. The first URL is the main URL, * all subsequent URLs are fallbacks. */ public List<String> getPaymentRequestUrls() { ArrayList<String> urls = new ArrayList<>(); while (true) { int i = urls.size(); String paramName = FIELD_PAYMENT_REQUEST_URL + (i > 0 ? Integer.toString(i) : ""); String url = (String) parameterMap.get(paramName); if (url == null) break; urls.add(url); } Collections.reverse(urls); return urls; } /** * @param name The name of the parameter * @return The parameter value, or null if not present */ public Object getParameterByName(String name) { return parameterMap.get(name); } @Override public String toString() { StringBuilder builder = new StringBuilder("BitcoinURI["); boolean first = true; for (Map.Entry<String, Object> entry : parameterMap.entrySet()) { if (first) { first = false; } else { builder.append(","); } builder.append("'").append(entry.getKey()).append("'=").append("'").append(entry.getValue()).append("'"); } builder.append("]"); return builder.toString(); } /** * Simple Bitcoin URI builder using known good fields. * * @param address The Bitcoin address * @param amount The amount * @param label A label * @param message A message * @return A String containing the Bitcoin URI */ public static String convertToBitcoinURI(Address address, Coin amount, String label, String message) { return convertToBitcoinURI(address.network(), address.toString(), amount, label, message); } /** * Simple Bitcoin URI builder using known good fields. * * @param params The network parameters that determine which network the URI * is for. * @param address The Bitcoin address * @param amount The amount * @param label A label * @param message A message * @return A String containing the Bitcoin URI * @deprecated Use {@link #convertToBitcoinURI(Network, String, Coin, String, String)} */ @Deprecated public static String convertToBitcoinURI(NetworkParameters params, String address, @Nullable Coin amount, @Nullable String label, @Nullable String message) { return convertToBitcoinURI(params.network(), address, amount, label, message); } /** * Simple Bitcoin URI builder using known good fields. * * @param network The network the URI is for. * @param address The Bitcoin address * @param amount The amount * @param label A label * @param message A message * @return A String containing the Bitcoin URI */ public static String convertToBitcoinURI(Network network, String address, @Nullable Coin amount, @Nullable String label, @Nullable String message) { Objects.requireNonNull(network); Objects.requireNonNull(address); if (amount != null && amount.signum() < 0) { throw new IllegalArgumentException("Coin must be positive"); } StringBuilder builder = new StringBuilder(); String scheme = network.uriScheme(); builder.append(scheme).append(":").append(address); boolean questionMarkHasBeenOutput = false; if (amount != null) { builder.append(QUESTION_MARK_SEPARATOR).append(FIELD_AMOUNT).append("="); builder.append(amount.toPlainString()); questionMarkHasBeenOutput = true; } if (label != null && !"".equals(label)) { if (questionMarkHasBeenOutput) { builder.append(AMPERSAND_SEPARATOR); } else { builder.append(QUESTION_MARK_SEPARATOR); questionMarkHasBeenOutput = true; } builder.append(FIELD_LABEL).append("=").append(encodeURLString(label)); } if (message != null && !"".equals(message)) { if (questionMarkHasBeenOutput) { builder.append(AMPERSAND_SEPARATOR); } else { builder.append(QUESTION_MARK_SEPARATOR); } builder.append(FIELD_MESSAGE).append("=").append(encodeURLString(message)); } return builder.toString(); } /** * Encode a string using URL encoding * * @param stringToEncode The string to URL encode */ static String encodeURLString(String stringToEncode) { try { return java.net.URLEncoder.encode(stringToEncode, "UTF-8").replace("+", ENCODED_SPACE_CHARACTER); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); // can't happen } } }
18,508
39.679121
135
java
bitcoinj
bitcoinj-master/core/src/main/java/org/bitcoinj/uri/BitcoinURIParseException.java
/* * Copyright 2012 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.bitcoinj.uri; /** * <p>Exception to provide the following to {@link BitcoinURI}:</p> * <ul> * <li>Provision of parsing error messages</li> * </ul> * <p>This base exception acts as a general failure mode not attributable to a specific cause (other than * that reported in the exception message). Since this is in English, it may not be worth reporting directly * to the user other than as part of a "general failure to parse" response.</p> */ public class BitcoinURIParseException extends Exception { public BitcoinURIParseException(String s) { super(s); } public BitcoinURIParseException(String s, Throwable throwable) { super(s, throwable); } }
1,315
34.567568
108
java
bitcoinj
bitcoinj-master/core/src/main/java/org/bitcoinj/uri/RequiredFieldValidationException.java
/* * Copyright by the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.bitcoinj.uri; /** * <p>Exception to provide the following to {@link BitcoinURI}:</p> * <ul> * <li>Provision of parsing error messages</li> * </ul> * <p>This exception occurs when a required field is detected (under the BIP21 rules) and fails * to pass the associated test (such as {@code req-expires} being out of date), or the required field is unknown * to this version of the client in which case it should fail for security reasons.</p> * * @since 0.3.0 *   */ public class RequiredFieldValidationException extends BitcoinURIParseException { public RequiredFieldValidationException(String s) { super(s); } public RequiredFieldValidationException(String s, Throwable throwable) { super(s, throwable); } }
1,387
32.853659
112
java
bitcoinj
bitcoinj-master/core/src/main/java/org/bitcoinj/protocols/package-info.java
/* * Copyright by the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * High level protocols that build on top of Bitcoin go here: we have the payment protocol for sending transactions * from sender to receiver with metadata, and a micropayment channels implementation. */ package org.bitcoinj.protocols;
855
39.761905
115
java
bitcoinj
bitcoinj-master/core/src/main/java/org/bitcoinj/protocols/payments/package-info.java
/* * Copyright by the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * The BIP70 payment protocol wraps Bitcoin transactions and adds various useful features like memos, refund addresses * and authentication. */ package org.bitcoinj.protocols.payments;
804
37.333333
118
java
bitcoinj
bitcoinj-master/core/src/main/java/org/bitcoinj/protocols/payments/PaymentProtocolException.java
/* * Copyright 2013 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.bitcoinj.protocols.payments; import java.security.cert.X509Certificate; import java.util.List; public class PaymentProtocolException extends Exception { public PaymentProtocolException(String msg) { super(msg); } public PaymentProtocolException(Exception e) { super(e); } public static class Expired extends PaymentProtocolException { public Expired(String msg) { super(msg); } } public static class InvalidPaymentRequestURL extends PaymentProtocolException { public InvalidPaymentRequestURL(String msg) { super(msg); } public InvalidPaymentRequestURL(Exception e) { super(e); } } public static class InvalidPaymentURL extends PaymentProtocolException { public InvalidPaymentURL(Exception e) { super(e); } public InvalidPaymentURL(String msg) { super(msg); } } public static class InvalidOutputs extends PaymentProtocolException { public InvalidOutputs(String msg) { super(msg); } } public static class InvalidVersion extends PaymentProtocolException { public InvalidVersion(String msg) { super(msg); } } public static class InvalidNetwork extends PaymentProtocolException { public InvalidNetwork(String msg) { super(msg); } } public static class InvalidPkiType extends PaymentProtocolException { public InvalidPkiType(String msg) { super(msg); } } public static class InvalidPkiData extends PaymentProtocolException { public InvalidPkiData(String msg) { super(msg); } public InvalidPkiData(Exception e) { super(e); } } public static class PkiVerificationException extends PaymentProtocolException { public List<X509Certificate> certificates; public PkiVerificationException(String msg) { super(msg); } public PkiVerificationException(Exception e) { super(e); } public PkiVerificationException(Exception e, List<X509Certificate> certificates) { super(e); this.certificates = certificates; } } }
2,936
26.194444
90
java
bitcoinj
bitcoinj-master/core/src/main/java/org/bitcoinj/protocols/payments/PaymentProtocol.java
/* * Copyright 2013 Google Inc. * Copyright 2014 Andreas Schildbach * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.bitcoinj.protocols.payments; import com.google.common.base.MoreObjects; import com.google.protobuf.ByteString; import com.google.protobuf.InvalidProtocolBufferException; import org.bitcoin.protocols.payments.Protos; import org.bitcoinj.base.Address; import org.bitcoinj.base.Coin; import org.bitcoinj.base.internal.TimeUtils; import org.bitcoinj.core.NetworkParameters; import org.bitcoinj.core.Transaction; import org.bitcoinj.crypto.X509Utils; import org.bitcoinj.params.BitcoinNetworkParams; import org.bitcoinj.params.MainNetParams; import org.bitcoinj.params.RegTestParams; import org.bitcoinj.params.SigNetParams; import org.bitcoinj.params.TestNet3Params; import org.bitcoinj.params.UnitTestParams; import org.bitcoinj.script.ScriptBuilder; import javax.annotation.Nullable; import java.nio.ByteBuffer; import java.security.GeneralSecurityException; import java.security.InvalidAlgorithmParameterException; import java.security.InvalidKeyException; import java.security.KeyStore; import java.security.KeyStoreException; import java.security.NoSuchAlgorithmException; import java.security.PrivateKey; import java.security.PublicKey; import java.security.Signature; import java.security.SignatureException; import java.security.cert.CertPath; import java.security.cert.CertPathValidator; import java.security.cert.CertPathValidatorException; import java.security.cert.Certificate; import java.security.cert.CertificateException; import java.security.cert.CertificateFactory; import java.security.cert.CertificateParsingException; import java.security.cert.PKIXCertPathValidatorResult; import java.security.cert.PKIXParameters; import java.security.cert.TrustAnchor; import java.security.cert.X509Certificate; import java.util.ArrayList; import java.util.Collections; import java.util.List; /** * <p>Utility methods and constants for working with <a href="https://github.com/bitcoin/bips/blob/master/bip-0070.mediawiki"> * BIP 70 aka the payment protocol</a>. These are low level wrappers around the protocol buffers. If you're implementing * a wallet app, look at {@link PaymentSession} for a higher level API that should simplify working with the protocol.</p> * * <p>BIP 70 defines a binary, protobuf based protocol that runs directly between sender and receiver of funds. Payment * protocol data does not flow over the Bitcoin P2P network or enter the block chain. It's instead for data that is only * of interest to the parties involved but isn't otherwise needed for consensus.</p> */ public class PaymentProtocol { // MIME types as defined in BIP71. public static final String MIMETYPE_PAYMENTREQUEST = "application/bitcoin-paymentrequest"; public static final String MIMETYPE_PAYMENT = "application/bitcoin-payment"; public static final String MIMETYPE_PAYMENTACK = "application/bitcoin-paymentack"; /** The string used by the payment protocol to represent the main net. */ public static final String PAYMENT_PROTOCOL_ID_MAINNET = "main"; /** The string used by the payment protocol to represent the test net. */ public static final String PAYMENT_PROTOCOL_ID_TESTNET = "test"; /** The string used by the payment protocol to represent signet (note that this is non-standard). */ public static final String PAYMENT_PROTOCOL_ID_SIGNET = "signet"; /** The string used by the payment protocol to represent unit testing (note that this is non-standard). */ public static final String PAYMENT_PROTOCOL_ID_UNIT_TESTS = "unittest"; public static final String PAYMENT_PROTOCOL_ID_REGTEST = "regtest"; /** * Create a payment request with one standard pay to address output. You may want to sign the request using * {@link #signPaymentRequest}. Use {@link Protos.PaymentRequest.Builder#build} to get the actual payment * request. * * @param params network parameters * @param amount amount of coins to request, or null * @param toAddress address to request coins to * @param memo arbitrary, user readable memo, or null if none * @param paymentUrl URL to send payment message to, or null if none * @param merchantData arbitrary merchant data, or null if none * @return created payment request, in its builder form */ public static Protos.PaymentRequest.Builder createPaymentRequest(NetworkParameters params, @Nullable Coin amount, Address toAddress, @Nullable String memo, @Nullable String paymentUrl, @Nullable byte[] merchantData) { return createPaymentRequest(params, Collections.singletonList(createPayToAddressOutput(amount, toAddress)), memo, paymentUrl, merchantData); } /** * Create a payment request. You may want to sign the request using {@link #signPaymentRequest}. Use * {@link Protos.PaymentRequest.Builder#build} to get the actual payment request. * * @param params network parameters * @param outputs list of outputs to request coins to * @param memo arbitrary, user readable memo, or null if none * @param paymentUrl URL to send payment message to, or null if none * @param merchantData arbitrary merchant data, or null if none * @return created payment request, in its builder form */ public static Protos.PaymentRequest.Builder createPaymentRequest(NetworkParameters params, List<Protos.Output> outputs, @Nullable String memo, @Nullable String paymentUrl, @Nullable byte[] merchantData) { final Protos.PaymentDetails.Builder paymentDetails = Protos.PaymentDetails.newBuilder(); paymentDetails.setNetwork(protocolIdFromParams(params)); for (Protos.Output output : outputs) paymentDetails.addOutputs(output); if (memo != null) paymentDetails.setMemo(memo); if (paymentUrl != null) paymentDetails.setPaymentUrl(paymentUrl); if (merchantData != null) paymentDetails.setMerchantData(ByteString.copyFrom(merchantData)); paymentDetails.setTime(TimeUtils.currentTime().getEpochSecond()); final Protos.PaymentRequest.Builder paymentRequest = Protos.PaymentRequest.newBuilder(); paymentRequest.setSerializedPaymentDetails(paymentDetails.build().toByteString()); return paymentRequest; } /** * Parse a payment request. * * @param paymentRequest payment request to parse * @return instance of {@link PaymentSession}, used as a value object * @throws PaymentProtocolException */ public static PaymentSession parsePaymentRequest(Protos.PaymentRequest paymentRequest) throws PaymentProtocolException { return new PaymentSession(paymentRequest, false, null); } /** * Sign the provided payment request. * * @param paymentRequest Payment request to sign, in its builder form. * @param certificateChain Certificate chain to send with the payment request, ordered from client certificate to root * certificate. The root certificate itself may be omitted. * @param privateKey The key to sign with. Must match the public key from the first certificate of the certificate chain. */ public static void signPaymentRequest(Protos.PaymentRequest.Builder paymentRequest, X509Certificate[] certificateChain, PrivateKey privateKey) { try { final Protos.X509Certificates.Builder certificates = Protos.X509Certificates.newBuilder(); for (final Certificate certificate : certificateChain) certificates.addCertificate(ByteString.copyFrom(certificate.getEncoded())); paymentRequest.setPkiType("x509+sha256"); paymentRequest.setPkiData(certificates.build().toByteString()); paymentRequest.setSignature(ByteString.EMPTY); final Protos.PaymentRequest paymentRequestToSign = paymentRequest.build(); final String algorithm; if ("RSA".equalsIgnoreCase(privateKey.getAlgorithm())) algorithm = "SHA256withRSA"; else throw new IllegalStateException(privateKey.getAlgorithm()); final Signature signature = Signature.getInstance(algorithm); signature.initSign(privateKey); signature.update(paymentRequestToSign.toByteArray()); paymentRequest.setSignature(ByteString.copyFrom(signature.sign())); } catch (final GeneralSecurityException x) { // Should never happen so don't make users have to think about it. throw new RuntimeException(x); } } /** * Uses the provided PKI method to find the corresponding public key and verify the provided signature. * * @param paymentRequest Payment request to verify. * @param trustStore KeyStore of trusted root certificate authorities. * @return verification data, or null if no PKI method was specified in the {@link Protos.PaymentRequest}. * @throws PaymentProtocolException if payment request could not be verified. */ @Nullable public static PkiVerificationData verifyPaymentRequestPki(Protos.PaymentRequest paymentRequest, KeyStore trustStore) throws PaymentProtocolException { List<X509Certificate> certs = null; try { final String pkiType = paymentRequest.getPkiType(); if ("none".equals(pkiType)) // Nothing to verify. Everything is fine. Move along. return null; String algorithm; if ("x509+sha256".equals(pkiType)) algorithm = "SHA256withRSA"; else if ("x509+sha1".equals(pkiType)) algorithm = "SHA1withRSA"; else throw new PaymentProtocolException.InvalidPkiType("Unsupported PKI type: " + pkiType); Protos.X509Certificates protoCerts = Protos.X509Certificates.parseFrom(paymentRequest.getPkiData()); if (protoCerts.getCertificateCount() == 0) throw new PaymentProtocolException.InvalidPkiData("No certificates provided in message: server config error"); // Parse the certs and turn into a certificate chain object. Cert factories can parse both DER and base64. // The ordering of certificates is defined by the payment protocol spec to be the same as what the Java // crypto API requires - convenient! CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509"); certs = new ArrayList<>(); for (ByteString bytes : protoCerts.getCertificateList()) certs.add((X509Certificate) certificateFactory.generateCertificate(bytes.newInput())); CertPath path = certificateFactory.generateCertPath(certs); // Retrieves the most-trusted CAs from keystore. PKIXParameters params = new PKIXParameters(trustStore); // Revocation not supported in the current version. params.setRevocationEnabled(false); // Now verify the certificate chain is correct and trusted. This let's us get an identity linked pubkey. CertPathValidator validator = CertPathValidator.getInstance("PKIX"); PKIXCertPathValidatorResult result = (PKIXCertPathValidatorResult) validator.validate(path, params); PublicKey publicKey = result.getPublicKey(); // OK, we got an identity, now check it was used to sign this message. Signature signature = Signature.getInstance(algorithm); // Note that we don't use signature.initVerify(certs.get(0)) here despite it being the most obvious // way to set it up, because we don't care about the constraints specified on the certificates: any // cert that links a key to a domain name or other identity will do for us. signature.initVerify(publicKey); Protos.PaymentRequest.Builder reqToCheck = paymentRequest.toBuilder(); reqToCheck.setSignature(ByteString.EMPTY); signature.update(reqToCheck.build().toByteArray()); if (!signature.verify(paymentRequest.getSignature().toByteArray())) throw new PaymentProtocolException.PkiVerificationException("Invalid signature, this payment request is not valid."); // Signature verifies, get the names from the identity we just verified for presentation to the user. final X509Certificate cert = certs.get(0); String displayName = X509Utils.getDisplayNameFromCertificate(cert, true); if (displayName == null) throw new PaymentProtocolException.PkiVerificationException("Could not extract name from certificate"); // Everything is peachy. Return some useful data to the caller. return new PkiVerificationData(displayName, publicKey, result.getTrustAnchor()); } catch (InvalidProtocolBufferException e) { // Data structures are malformed. throw new PaymentProtocolException.InvalidPkiData(e); } catch (CertificateException | SignatureException | InvalidKeyException e) { // CertificateException: The X.509 certificate data didn't parse correctly. // SignatureException: Something went wrong during hashing (yes, despite the name, this does not mean the sig was invalid). // InvalidKeyException: Shouldn't happen if the certs verified correctly. throw new PaymentProtocolException.PkiVerificationException(e); } catch (NoSuchAlgorithmException | KeyStoreException | InvalidAlgorithmParameterException e) { // NoSuchAlgorithmException: Should never happen so don't make users have to think about it. PKIX is always present. throw new RuntimeException(e); } catch (CertPathValidatorException e) { // The certificate chain isn't known or trusted, probably, the server is using an SSL root we don't // know about and the user needs to upgrade to a new version of the software (or import a root cert). throw new PaymentProtocolException.PkiVerificationException(e, certs); } } /** * Information about the X.509 signature's issuer and subject. */ public static class PkiVerificationData { /** Display name of the payment requestor, could be a domain name, email address, legal name, etc */ public final String displayName; /** SSL public key that was used to sign. */ public final PublicKey merchantSigningKey; /** Object representing the CA that verified the merchant's ID */ public final TrustAnchor rootAuthority; /** String representing the display name of the CA that verified the merchant's ID */ public final String rootAuthorityName; private PkiVerificationData(@Nullable String displayName, PublicKey merchantSigningKey, TrustAnchor rootAuthority) throws PaymentProtocolException.PkiVerificationException { try { this.displayName = displayName; this.merchantSigningKey = merchantSigningKey; this.rootAuthority = rootAuthority; this.rootAuthorityName = X509Utils.getDisplayNameFromCertificate(rootAuthority.getTrustedCert(), true); } catch (CertificateParsingException x) { throw new PaymentProtocolException.PkiVerificationException(x); } } @Override public String toString() { return MoreObjects.toStringHelper(this) .add("displayName", displayName) .add("rootAuthorityName", rootAuthorityName) .add("merchantSigningKey", merchantSigningKey) .add("rootAuthority", rootAuthority) .toString(); } } /** * Create a payment message with one standard pay to address output. * * @param transactions one or more transactions that satisfy the requested outputs. * @param refundAmount amount of coins to request as a refund, or null if no refund. * @param refundAddress address to refund coins to * @param memo arbitrary, user readable memo, or null if none * @param merchantData arbitrary merchant data, or null if none * @return created payment message */ public static Protos.Payment createPaymentMessage(List<Transaction> transactions, @Nullable Coin refundAmount, @Nullable Address refundAddress, @Nullable String memo, @Nullable byte[] merchantData) { if (refundAddress != null) { if (refundAmount == null) throw new IllegalArgumentException("Specify refund amount if refund address is specified."); return createPaymentMessage(transactions, Collections.singletonList(createPayToAddressOutput(refundAmount, refundAddress)), memo, merchantData); } else { return createPaymentMessage(transactions, null, memo, merchantData); } } /** * Create a payment message. This wraps up transaction data along with anything else useful for making a payment. * * @param transactions transactions to include with the payment message * @param refundOutputs list of outputs to refund coins to, or null * @param memo arbitrary, user readable memo, or null if none * @param merchantData arbitrary merchant data, or null if none * @return created payment message */ public static Protos.Payment createPaymentMessage(List<Transaction> transactions, @Nullable List<Protos.Output> refundOutputs, @Nullable String memo, @Nullable byte[] merchantData) { Protos.Payment.Builder builder = Protos.Payment.newBuilder(); for (Transaction transaction : transactions) { builder.addTransactions(ByteString.copyFrom(transaction.serialize())); } if (refundOutputs != null) { for (Protos.Output output : refundOutputs) builder.addRefundTo(output); } if (memo != null) builder.setMemo(memo); if (merchantData != null) builder.setMerchantData(ByteString.copyFrom(merchantData)); return builder.build(); } /** * Parse transactions from payment message. * * @param params network parameters (needed for transaction deserialization) * @param paymentMessage payment message to parse * @return list of transactions */ public static List<Transaction> parseTransactionsFromPaymentMessage(NetworkParameters params, Protos.Payment paymentMessage) { final List<Transaction> transactions = new ArrayList<>(paymentMessage.getTransactionsCount()); for (final ByteString transaction : paymentMessage.getTransactionsList()) transactions.add(params.getDefaultSerializer().makeTransaction(ByteBuffer.wrap(transaction.toByteArray()))); return transactions; } /** * Message returned by the merchant in response to a Payment message. */ public static class Ack { @Nullable private final String memo; Ack(@Nullable String memo) { this.memo = memo; } /** * Returns the memo included by the merchant in the payment ack. This message is typically displayed to the user * as a notification (e.g. "Your payment was received and is being processed"). If none was provided, returns * null. */ @Nullable public String getMemo() { return memo; } } /** * Create a payment ack. * * @param paymentMessage payment message to send with the ack * @param memo arbitrary, user readable memo, or null if none * @return created payment ack */ public static Protos.PaymentACK createPaymentAck(Protos.Payment paymentMessage, @Nullable String memo) { final Protos.PaymentACK.Builder builder = Protos.PaymentACK.newBuilder(); builder.setPayment(paymentMessage); if (memo != null) builder.setMemo(memo); return builder.build(); } /** * Parse payment ack into an object. */ public static Ack parsePaymentAck(Protos.PaymentACK paymentAck) { final String memo = paymentAck.hasMemo() ? paymentAck.getMemo() : null; return new Ack(memo); } /** * Create a standard pay to address output for usage in {@link #createPaymentRequest} and * {@link #createPaymentMessage}. * * @param amount amount to pay, or null * @param address address to pay to * @return output */ public static Protos.Output createPayToAddressOutput(@Nullable Coin amount, Address address) { Protos.Output.Builder output = Protos.Output.newBuilder(); if (amount != null) { final NetworkParameters params = NetworkParameters.of(address.network()); if (params.network().exceedsMaxMoney(amount)) throw new IllegalArgumentException("Amount too big: " + amount); output.setAmount(amount.value); } else { output.setAmount(0); } output.setScript(ByteString.copyFrom(ScriptBuilder.createOutputScript(address).program())); return output.build(); } /** * Return network parameters for a paymentProtocol ID string * @param pmtProtocolId paymentProtocol ID string * @return network parameters for the given string paymentProtocolID or NULL if not recognized */ @Nullable public static BitcoinNetworkParams paramsFromPmtProtocolID(String pmtProtocolId) { if (pmtProtocolId.equals(PAYMENT_PROTOCOL_ID_MAINNET)) { return MainNetParams.get(); } else if (pmtProtocolId.equals(PAYMENT_PROTOCOL_ID_TESTNET)) { return TestNet3Params.get(); } else if (pmtProtocolId.equals(PAYMENT_PROTOCOL_ID_SIGNET)) { return SigNetParams.get(); } else if (pmtProtocolId.equals(PAYMENT_PROTOCOL_ID_REGTEST)) { return RegTestParams.get(); } else if (pmtProtocolId.equals(PAYMENT_PROTOCOL_ID_UNIT_TESTS)) { return UnitTestParams.get(); } else { return null; } } public static String protocolIdFromParams(NetworkParameters params) { if (params instanceof MainNetParams) { return PAYMENT_PROTOCOL_ID_MAINNET; } else if (params instanceof TestNet3Params) { return PAYMENT_PROTOCOL_ID_TESTNET; } else if (params instanceof SigNetParams) { return PAYMENT_PROTOCOL_ID_SIGNET; } else if (params instanceof RegTestParams) { return PAYMENT_PROTOCOL_ID_REGTEST; } else if (params instanceof UnitTestParams) { return PAYMENT_PROTOCOL_ID_UNIT_TESTS; } else { throw new IllegalArgumentException("Unknown network"); } } /** * Value object to hold amount/script pairs. */ public static class Output { @Nullable public final Coin amount; public final byte[] scriptData; public Output(@Nullable Coin amount, byte[] scriptData) { this.amount = amount; this.scriptData = scriptData; } } }
24,077
47.939024
135
java
bitcoinj
bitcoinj-master/core/src/main/java/org/bitcoinj/protocols/payments/PaymentSession.java
/* * Copyright by the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.bitcoinj.protocols.payments; import com.google.common.annotations.VisibleForTesting; import com.google.protobuf.InvalidProtocolBufferException; import org.bitcoin.protocols.payments.Protos; import org.bitcoinj.base.Address; import org.bitcoinj.base.Coin; import org.bitcoinj.base.internal.TimeUtils; import org.bitcoinj.core.NetworkParameters; import org.bitcoinj.core.Transaction; import org.bitcoinj.core.TransactionOutput; import org.bitcoinj.crypto.TrustStoreLoader; import org.bitcoinj.params.MainNetParams; import org.bitcoinj.protocols.payments.PaymentProtocol.PkiVerificationData; import org.bitcoinj.uri.BitcoinURI; import org.bitcoinj.base.internal.FutureUtils; import org.bitcoinj.utils.ListenableCompletableFuture; import org.bitcoinj.utils.Threading; import org.bitcoinj.wallet.SendRequest; import javax.annotation.Nullable; import java.io.DataOutputStream; import java.io.IOException; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URI; import java.net.URISyntaxException; import java.net.URL; import java.security.KeyStoreException; import java.time.Instant; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Optional; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutorService; /** * <p>Provides a standard implementation of the Payment Protocol (BIP 0070)</p> * * <p>A PaymentSession can be initialized from one of the following:</p> * * <ul> * <li>A {@link BitcoinURI} object that conforms to BIP 0072</li> * <li>A url where the {@link Protos.PaymentRequest} can be fetched</li> * <li>Directly with a {@link Protos.PaymentRequest} object</li> * </ul> * * <p>If initialized with a BitcoinURI or a url, a network request is made for the payment request object and a * {@link ListenableCompletableFuture} is returned that will be notified with the PaymentSession object after it is downloaded.</p> * * <p>Once the PaymentSession is initialized, typically a wallet application will prompt the user to confirm that the * amount and recipient are correct, perform any additional steps, and then construct a list of transactions to pass to * the sendPayment method.</p> * * <p>Call sendPayment with a list of transactions that will be broadcast. A {@link Protos.Payment} message will be sent * to the merchant if a payment url is provided in the PaymentRequest. NOTE: sendPayment does NOT broadcast the * transactions to the bitcoin network. Instead it returns a ListenableCompletableFuture that will be notified when a * {@link Protos.PaymentACK} is received from the merchant. Typically a wallet will show the message to the user * as a confirmation message that the payment is now "processing" or that an error occurred, and then broadcast the * tx itself later if needed.</p> * * @see <a href="https://github.com/bitcoin/bips/blob/master/bip-0070.mediawiki">BIP 0070</a> */ public class PaymentSession { private final static ExecutorService executor = Threading.THREAD_POOL; private NetworkParameters params; private Protos.PaymentRequest paymentRequest; private Protos.PaymentDetails paymentDetails; private Coin totalValue = Coin.ZERO; /** * Stores the calculated PKI verification data, or null if none is available. * Only valid after the session is created with the verifyPki parameter set to true. */ @Nullable public final PkiVerificationData pkiVerificationData; /** * <p>Returns a future that will be notified with a PaymentSession object after it is fetched using the provided uri. * uri is a BIP-72-style BitcoinURI object that specifies where the {@link Protos.PaymentRequest} object may * be fetched in the r= parameter.</p> * * <p>If the payment request object specifies a PKI method, then the system trust store will be used to verify * the signature provided by the payment request. An exception is thrown by the future if the signature cannot * be verified.</p> */ public static ListenableCompletableFuture<PaymentSession> createFromBitcoinUri(final BitcoinURI uri) throws PaymentProtocolException { return createFromBitcoinUri(uri, true, null); } /** * Returns a future that will be notified with a PaymentSession object after it is fetched using the provided uri. * uri is a BIP-72-style BitcoinURI object that specifies where the {@link Protos.PaymentRequest} object may * be fetched in the r= parameter. * If verifyPki is specified and the payment request object specifies a PKI method, then the system trust store will * be used to verify the signature provided by the payment request. An exception is thrown by the future if the * signature cannot be verified. */ public static ListenableCompletableFuture<PaymentSession> createFromBitcoinUri(final BitcoinURI uri, final boolean verifyPki) throws PaymentProtocolException { return createFromBitcoinUri(uri, verifyPki, null); } /** * Returns a future that will be notified with a PaymentSession object after it is fetched using the provided uri. * uri is a BIP-72-style BitcoinURI object that specifies where the {@link Protos.PaymentRequest} object may * be fetched in the r= parameter. * If verifyPki is specified and the payment request object specifies a PKI method, then the system trust store will * be used to verify the signature provided by the payment request. An exception is thrown by the future if the * signature cannot be verified. * If trustStoreLoader is null, the system default trust store is used. */ public static ListenableCompletableFuture<PaymentSession> createFromBitcoinUri(final BitcoinURI uri, final boolean verifyPki, @Nullable final TrustStoreLoader trustStoreLoader) throws PaymentProtocolException { String url = uri.getPaymentRequestUrl(); if (url == null) throw new PaymentProtocolException.InvalidPaymentRequestURL("No payment request URL (r= parameter) in BitcoinURI " + uri); try { return ListenableCompletableFuture.of(fetchPaymentRequest(new URI(url), verifyPki, trustStoreLoader)); } catch (URISyntaxException e) { throw new PaymentProtocolException.InvalidPaymentRequestURL(e); } } /** * Returns a future that will be notified with a PaymentSession object after it is fetched using the provided url. * url is an address where the {@link Protos.PaymentRequest} object may be fetched. * If verifyPki is specified and the payment request object specifies a PKI method, then the system trust store will * be used to verify the signature provided by the payment request. An exception is thrown by the future if the * signature cannot be verified. */ public static ListenableCompletableFuture<PaymentSession> createFromUrl(final String url) throws PaymentProtocolException { return createFromUrl(url, true, null); } /** * Returns a future that will be notified with a PaymentSession object after it is fetched using the provided url. * url is an address where the {@link Protos.PaymentRequest} object may be fetched. * If the payment request object specifies a PKI method, then the system trust store will * be used to verify the signature provided by the payment request. An exception is thrown by the future if the * signature cannot be verified. */ public static ListenableCompletableFuture<PaymentSession> createFromUrl(final String url, final boolean verifyPki) throws PaymentProtocolException { return createFromUrl(url, verifyPki, null); } /** * Returns a future that will be notified with a PaymentSession object after it is fetched using the provided url. * url is an address where the {@link Protos.PaymentRequest} object may be fetched. * If the payment request object specifies a PKI method, then the system trust store will * be used to verify the signature provided by the payment request. An exception is thrown by the future if the * signature cannot be verified. * If trustStoreLoader is null, the system default trust store is used. */ public static ListenableCompletableFuture<PaymentSession> createFromUrl(final String url, final boolean verifyPki, @Nullable final TrustStoreLoader trustStoreLoader) throws PaymentProtocolException { if (url == null) throw new PaymentProtocolException.InvalidPaymentRequestURL("null paymentRequestUrl"); try { return ListenableCompletableFuture.of(fetchPaymentRequest(new URI(url), verifyPki, trustStoreLoader)); } catch(URISyntaxException e) { throw new PaymentProtocolException.InvalidPaymentRequestURL(e); } } private static CompletableFuture<PaymentSession> fetchPaymentRequest(final URI uri, final boolean verifyPki, @Nullable final TrustStoreLoader trustStoreLoader) { return CompletableFuture.supplyAsync((FutureUtils.ThrowingSupplier<PaymentSession>) () -> { HttpURLConnection connection = (HttpURLConnection)uri.toURL().openConnection(); connection.setRequestProperty("Accept", PaymentProtocol.MIMETYPE_PAYMENTREQUEST); connection.setUseCaches(false); Protos.PaymentRequest paymentRequest = Protos.PaymentRequest.parseFrom(connection.getInputStream()); return new PaymentSession(paymentRequest, verifyPki, trustStoreLoader); }, executor); } /** * Creates a PaymentSession from the provided {@link Protos.PaymentRequest}. * Verifies PKI by default. */ public PaymentSession(Protos.PaymentRequest request) throws PaymentProtocolException { this(request, true, null); } /** * Creates a PaymentSession from the provided {@link Protos.PaymentRequest}. * If verifyPki is true, also validates the signature and throws an exception if it fails. */ public PaymentSession(Protos.PaymentRequest request, boolean verifyPki) throws PaymentProtocolException { this(request, verifyPki, null); } /** * Creates a PaymentSession from the provided {@link Protos.PaymentRequest}. * If verifyPki is true, also validates the signature and throws an exception if it fails. * If trustStoreLoader is null, the system default trust store is used. */ public PaymentSession(Protos.PaymentRequest request, boolean verifyPki, @Nullable final TrustStoreLoader trustStoreLoader) throws PaymentProtocolException { TrustStoreLoader nonNullTrustStoreLoader = trustStoreLoader != null ? trustStoreLoader : new TrustStoreLoader.DefaultTrustStoreLoader(); parsePaymentRequest(request); if (verifyPki) { try { pkiVerificationData = PaymentProtocol.verifyPaymentRequestPki(request, nonNullTrustStoreLoader.getKeyStore()); } catch (IOException | KeyStoreException x) { throw new PaymentProtocolException(x); } } else { pkiVerificationData = null; } } /** * Returns the outputs of the payment request. */ public List<PaymentProtocol.Output> getOutputs() { List<PaymentProtocol.Output> outputs = new ArrayList<>(paymentDetails.getOutputsCount()); for (Protos.Output output : paymentDetails.getOutputsList()) { Coin amount = output.hasAmount() ? Coin.valueOf(output.getAmount()) : null; outputs.add(new PaymentProtocol.Output(amount, output.getScript().toByteArray())); } return outputs; } /** * Returns the memo included by the merchant in the payment request, or null if not found. */ @Nullable public String getMemo() { if (paymentDetails.hasMemo()) return paymentDetails.getMemo(); else return null; } /** * Returns the total amount of bitcoins requested. */ public Coin getValue() { return totalValue; } /** * Returns the time that the payment request was generated. */ public Instant time() { return Instant.ofEpochSecond(paymentDetails.getTime()); } /** @deprecated use {@link #time()} */ @Deprecated public Date getDate() { return Date.from(time()); } /** * Returns the expires time of the payment request, or empty if none. */ public Optional<Instant> expires() { if (paymentDetails.hasExpires()) return Optional.of(Instant.ofEpochSecond(paymentDetails.getExpires())); else return Optional.empty(); } /** @deprecated use {@link #expires()} */ @Nullable @Deprecated public Date getExpires() { return expires() .map(Date::from) .orElse(null); } /** * This should always be called before attempting to call sendPayment. */ public boolean isExpired() { return expires() .map(time -> TimeUtils.currentTime().isAfter(time)) .orElse(false); } /** * Returns the payment url where the Payment message should be sent. * Returns null if no payment url was provided in the PaymentRequest. */ @Nullable public String getPaymentUrl() { if (paymentDetails.hasPaymentUrl()) return paymentDetails.getPaymentUrl(); return null; } /** * Returns the merchant data included by the merchant in the payment request, or null if none. */ @Nullable public byte[] getMerchantData() { if (paymentDetails.hasMerchantData()) return paymentDetails.getMerchantData().toByteArray(); else return null; } /** * Returns a {@link SendRequest} suitable for broadcasting to the network. */ public SendRequest getSendRequest() { Transaction tx = new Transaction(); for (Protos.Output output : paymentDetails.getOutputsList()) tx.addOutput(new TransactionOutput(tx, Coin.valueOf(output.getAmount()), output.getScript().toByteArray())); return SendRequest.forTx(tx).fromPaymentDetails(paymentDetails); } /** * Generates a Payment message and sends the payment to the merchant who sent the PaymentRequest. * Provide transactions built by the wallet. * NOTE: This does not broadcast the transactions to the bitcoin network, it merely sends a Payment message to the * merchant confirming the payment. * Returns an object wrapping PaymentACK once received. * If the PaymentRequest did not specify a payment_url, completes exceptionally. * @param txns list of transactions to be included with the Payment message. * @param refundAddr will be used by the merchant to send money back if there was a problem. * @param memo is a message to include in the payment message sent to the merchant. * @return a future for the PaymentACK */ public ListenableCompletableFuture<PaymentProtocol.Ack> sendPayment(List<Transaction> txns, @Nullable Address refundAddr, @Nullable String memo) { Protos.Payment payment = null; try { payment = getPayment(txns, refundAddr, memo); } catch (IOException e) { return ListenableCompletableFuture.failedFuture(e); } if (payment == null) return ListenableCompletableFuture.failedFuture(new PaymentProtocolException.InvalidPaymentRequestURL("Missing Payment URL")); if (isExpired()) return ListenableCompletableFuture.failedFuture(new PaymentProtocolException.Expired("PaymentRequest is expired")); URL url; try { url = new URL(paymentDetails.getPaymentUrl()); } catch (MalformedURLException e) { return ListenableCompletableFuture.failedFuture(new PaymentProtocolException.InvalidPaymentURL(e)); } return ListenableCompletableFuture.of(sendPayment(url, payment)); } /** * Generates a Payment message based on the information in the PaymentRequest. * Provide transactions built by the wallet. * @param txns list of transactions to be included with the Payment message. * @param refundAddr will be used by the merchant to send money back if there was a problem. * @param memo is a message to include in the payment message sent to the merchant. * @return Payment message or null (if the PaymentRequest did not specify a payment_url) */ @Nullable public Protos.Payment getPayment(List<Transaction> txns, @Nullable Address refundAddr, @Nullable String memo) throws IOException { if (paymentDetails.hasPaymentUrl()) { return PaymentProtocol.createPaymentMessage(txns, totalValue, refundAddr, memo, getMerchantData()); } else { return null; } } @VisibleForTesting protected CompletableFuture<PaymentProtocol.Ack> sendPayment(final URL url, final Protos.Payment payment) { return CompletableFuture.supplyAsync((FutureUtils.ThrowingSupplier<PaymentProtocol.Ack>) () -> { HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("POST"); connection.setRequestProperty("Content-Type", PaymentProtocol.MIMETYPE_PAYMENT); connection.setRequestProperty("Accept", PaymentProtocol.MIMETYPE_PAYMENTACK); connection.setRequestProperty("Content-Length", Integer.toString(payment.getSerializedSize())); connection.setUseCaches(false); connection.setDoInput(true); connection.setDoOutput(true); // Send request. DataOutputStream outStream = new DataOutputStream(connection.getOutputStream()); payment.writeTo(outStream); outStream.flush(); outStream.close(); // Get response. Protos.PaymentACK paymentAck = Protos.PaymentACK.parseFrom(connection.getInputStream()); return PaymentProtocol.parsePaymentAck(paymentAck); }, executor); } private void parsePaymentRequest(Protos.PaymentRequest request) throws PaymentProtocolException { try { if (request == null) throw new PaymentProtocolException("request cannot be null"); if (request.getPaymentDetailsVersion() != 1) throw new PaymentProtocolException.InvalidVersion("Version 1 required. Received version " + request.getPaymentDetailsVersion()); paymentRequest = request; if (!request.hasSerializedPaymentDetails()) throw new PaymentProtocolException("No PaymentDetails"); paymentDetails = Protos.PaymentDetails.newBuilder().mergeFrom(request.getSerializedPaymentDetails()).build(); if (paymentDetails == null) throw new PaymentProtocolException("Invalid PaymentDetails"); if (!paymentDetails.hasNetwork()) params = MainNetParams.get(); else params = PaymentProtocol.paramsFromPmtProtocolID(paymentDetails.getNetwork()); if (params == null) throw new PaymentProtocolException.InvalidNetwork("Invalid network " + paymentDetails.getNetwork()); if (paymentDetails.getOutputsCount() < 1) throw new PaymentProtocolException.InvalidOutputs("No outputs"); for (Protos.Output output : paymentDetails.getOutputsList()) { if (output.hasAmount()) totalValue = totalValue.add(Coin.valueOf(output.getAmount())); } // This won't ever happen in practice. It would only happen if the user provided outputs // that are obviously invalid. Still, we don't want to silently overflow. if (params.network().exceedsMaxMoney(totalValue)) throw new PaymentProtocolException.InvalidOutputs("The outputs are way too big."); } catch (InvalidProtocolBufferException e) { throw new PaymentProtocolException(e); } } /** Returns the value of pkiVerificationData or null if it wasn't verified at construction time. */ @Nullable public PkiVerificationData verifyPki() { return pkiVerificationData; } /** Gets the params as read from the PaymentRequest.network field: main is the default if missing. */ public NetworkParameters getNetworkParameters() { return params; } /** Returns the protobuf that this object was instantiated with. */ public Protos.PaymentRequest getPaymentRequest() { return paymentRequest; } /** Returns the protobuf that describes the payment to be made. */ public Protos.PaymentDetails getPaymentDetails() { return paymentDetails; } }
21,608
46.388158
180
java
bitcoinj
bitcoinj-master/core/src/main/java/org/bitcoinj/store/package-info.java
/* * Copyright by the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * Block stores persist blockchain data downloaded from remote peers. There is an SPV block store which preserves a ring * buffer of headers on disk and is suitable for lightweight user wallets, a store that can calculate a full indexed * UTXO set (i.e. it can query address balances), and a memory only store useful for unit tests. */ package org.bitcoinj.store;
985
41.869565
120
java
bitcoinj
bitcoinj-master/core/src/main/java/org/bitcoinj/store/BlockStore.java
/* * Copyright 2011 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.bitcoinj.store; import org.bitcoinj.core.BlockChain; import org.bitcoinj.base.Sha256Hash; import org.bitcoinj.core.StoredBlock; /** * An implementor of BlockStore saves StoredBlock objects to disk. Different implementations store them in * different ways. An in-memory implementation (MemoryBlockStore) exists for unit testing but real apps will want to * use implementations that save to disk.<p> * * A BlockStore is a map of hashes to StoredBlock. The hash is the double digest of the Bitcoin serialization * of the block header, <b>not</b> the header with the extra data as well.<p> * * BlockStores are thread safe. */ public interface BlockStore { /** * Saves the given block header+extra data. The key isn't specified explicitly as it can be calculated from the * StoredBlock directly. Can throw if there is a problem with the underlying storage layer such as running out of * disk space. */ void put(StoredBlock block) throws BlockStoreException; /** * Returns the StoredBlock given a hash. The returned values block.getHash() method will be equal to the * parameter. If no such block is found, returns null. */ StoredBlock get(Sha256Hash hash) throws BlockStoreException; /** * Returns the {@link StoredBlock} that represents the top of the chain of greatest total work. Note that this * can be arbitrarily expensive, you probably should use {@link BlockChain#getChainHead()} * or perhaps {@link BlockChain#getBestChainHeight()} which will run in constant time and * not take any heavyweight locks. */ StoredBlock getChainHead() throws BlockStoreException; /** * Sets the {@link StoredBlock} that represents the top of the chain of greatest total work. */ void setChainHead(StoredBlock chainHead) throws BlockStoreException; /** Closes the store. */ void close() throws BlockStoreException; }
2,536
39.269841
117
java
bitcoinj
bitcoinj-master/core/src/main/java/org/bitcoinj/store/ChainFileLockedException.java
/* * Copyright by the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.bitcoinj.store; /** * Thrown by {@link SPVBlockStore} when the process cannot gain exclusive access to the chain file. */ public class ChainFileLockedException extends BlockStoreException { public ChainFileLockedException(String message) { super(message); } public ChainFileLockedException(Throwable t) { super(t); } }
981
30.677419
99
java
bitcoinj
bitcoinj-master/core/src/main/java/org/bitcoinj/store/BlockStoreException.java
/* * Copyright 2011 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.bitcoinj.store; /** * Thrown when something goes wrong with storing a block. Examples: out of disk space. */ public class BlockStoreException extends Exception { public BlockStoreException(String message) { super(message); } public BlockStoreException(Throwable t) { super(t); } public BlockStoreException(String message, Throwable t) { super(message, t); } }
1,020
28.171429
86
java
bitcoinj
bitcoinj-master/core/src/main/java/org/bitcoinj/store/FullPrunedBlockStore.java
/* * Copyright 2012 Matt Corallo. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.bitcoinj.store; import org.bitcoinj.base.Sha256Hash; import org.bitcoinj.core.StoredBlock; import org.bitcoinj.core.StoredUndoableBlock; import org.bitcoinj.core.UTXO; import org.bitcoinj.core.UTXOProvider; /** * <p>An implementor of FullPrunedBlockStore saves StoredBlock objects to some storage mechanism.</p> * * <p>In addition to keeping track of a chain using {@link StoredBlock}s, it should also keep track of a second * copy of the chain which holds {@link StoredUndoableBlock}s. In this way, an application can perform a * headers-only initial sync and then use that information to more efficiently download a locally verified * full copy of the block chain.</p> * * <p>A FullPrunedBlockStore should function well as a standard {@link BlockStore} and then be able to * trivially switch to being used as a FullPrunedBlockStore.</p> * * <p>It should store the {@link StoredUndoableBlock}s of a number of recent blocks before verifiedHead.height and * all those after verifiedHead.height. * It is advisable to store any {@link StoredUndoableBlock} which has a {@code height > verifiedHead.height - N}. * Because N determines the memory usage, it is recommended that N be customizable. N should be chosen such that * re-orgs beyond that point are vanishingly unlikely, for example, a few thousand blocks is a reasonable choice.</p> * * <p>It must store the {@link StoredBlock} of all blocks.</p> * * <p>A FullPrunedBlockStore contains a map of hashes to [Full]StoredBlock. The hash is the double digest of the * Bitcoin serialization of the block header, <b>not</b> the header with the extra data as well.</p> * * <p>A FullPrunedBlockStore also contains a map of hash+index to UTXO. Again, the hash is * a standard Bitcoin double-SHA256 hash of the transaction.</p> * * <p>FullPrunedBlockStores are thread safe.</p> */ public interface FullPrunedBlockStore extends BlockStore, UTXOProvider { /** * <p>Saves the given {@link StoredUndoableBlock} and {@link StoredBlock}. Calculates keys from the {@link StoredBlock}</p> * * <p>Though not required for proper function of a FullPrunedBlockStore, any user of a FullPrunedBlockStore should ensure * that a StoredUndoableBlock for each block up to the fully verified chain head has been added to this block store using * this function (not put(StoredBlock)), so that the ability to perform reorgs is maintained.</p> * * @throws BlockStoreException if there is a problem with the underlying storage layer, such as running out of disk space. */ void put(StoredBlock storedBlock, StoredUndoableBlock undoableBlock) throws BlockStoreException; /** * Returns the StoredBlock that was added as a StoredUndoableBlock given a hash. The returned values block.getHash() * method will be equal to the parameter. If no such block is found, returns null. */ StoredBlock getOnceUndoableStoredBlock(Sha256Hash hash) throws BlockStoreException; /** * Returns a {@link StoredUndoableBlock} whose block.getHash() method will be equal to the parameter. If no such * block is found, returns null. Note that this may return null more often than get(Sha256Hash hash) as not all * {@link StoredBlock}s have a {@link StoredUndoableBlock} copy stored as well. */ StoredUndoableBlock getUndoBlock(Sha256Hash hash) throws BlockStoreException; /** * Gets a {@link UTXO} with the given hash and index, or null if none is found */ UTXO getTransactionOutput(Sha256Hash hash, long index) throws BlockStoreException; /** * Adds a {@link UTXO} to the list of unspent TransactionOutputs */ void addUnspentTransactionOutput(UTXO out) throws BlockStoreException; /** * Removes a {@link UTXO} from the list of unspent TransactionOutputs * Note that the coinbase of the genesis block should NEVER be spendable and thus never in the list. * @throws BlockStoreException if there is an underlying storage issue, or out was not in the list. */ void removeUnspentTransactionOutput(UTXO out) throws BlockStoreException; /** * True if this store has any unspent outputs from a transaction with a hash equal to the first parameter * @param numOutputs the number of outputs the given transaction has */ boolean hasUnspentOutputs(Sha256Hash hash, int numOutputs) throws BlockStoreException; /** * Returns the {@link StoredBlock} that represents the top of the chain of greatest total work that has * been fully verified and the point in the chain at which the unspent transaction output set in this * store represents. */ StoredBlock getVerifiedChainHead() throws BlockStoreException; /** * Sets the {@link StoredBlock} that represents the top of the chain of greatest total work that has been * fully verified. It should generally be set after a batch of updates to the transaction unspent output set, * before a call to commitDatabaseBatchWrite. * * If chainHead has a greater height than the non-verified chain head (ie that set with * {@link BlockStore#setChainHead}) the non-verified chain head should be set to the one set here. * In this way a class using a FullPrunedBlockStore only in full-verification mode can ignore the regular * {@link BlockStore} functions implemented as a part of a FullPrunedBlockStore. */ void setVerifiedChainHead(StoredBlock chainHead) throws BlockStoreException; /** * <p>Begins/Commits/Aborts a database transaction.</p> * * <p>If abortDatabaseBatchWrite() is called by the same thread that called beginDatabaseBatchWrite(), * any data writes between this call and abortDatabaseBatchWrite() made by the same thread * should be discarded.</p> * * <p>Furthermore, any data written after a call to beginDatabaseBatchWrite() should not be readable * by any other threads until commitDatabaseBatchWrite() has been called by this thread. * Multiple calls to beginDatabaseBatchWrite() in any given thread should be ignored and treated as one call.</p> */ void beginDatabaseBatchWrite() throws BlockStoreException; void commitDatabaseBatchWrite() throws BlockStoreException; void abortDatabaseBatchWrite() throws BlockStoreException; }
6,982
50.725926
127
java
bitcoinj
bitcoinj-master/core/src/main/java/org/bitcoinj/store/MemoryFullPrunedBlockStore.java
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.bitcoinj.store; import org.bitcoinj.base.Network; import org.bitcoinj.base.ScriptType; import org.bitcoinj.base.Address; import org.bitcoinj.crypto.ECKey; import org.bitcoinj.core.NetworkParameters; import org.bitcoinj.base.Sha256Hash; import org.bitcoinj.core.StoredBlock; import org.bitcoinj.core.StoredUndoableBlock; import org.bitcoinj.core.Transaction; import org.bitcoinj.core.TransactionOutPoint; import org.bitcoinj.core.UTXO; import org.bitcoinj.core.UTXOProviderException; import org.bitcoinj.core.VerificationException; import javax.annotation.Nullable; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Set; /** * Used as a key for memory map (to avoid having to think about NetworkParameters, * which is required for {@link TransactionOutPoint} */ class StoredTransactionOutPoint { /** Hash of the transaction to which we refer. */ Sha256Hash hash; /** Which output of that transaction we are talking about. */ long index; StoredTransactionOutPoint(Sha256Hash hash, long index) { this.hash = hash; this.index = index; } StoredTransactionOutPoint(UTXO out) { this.hash = out.getHash(); this.index = out.getIndex(); } /** * The hash of the transaction to which we refer */ Sha256Hash getHash() { return hash; } /** * The index of the output in transaction to which we refer */ long getIndex() { return index; } @Override public int hashCode() { return Objects.hash(getIndex(), getHash()); } @Override public String toString() { return "Stored transaction out point: " + hash + ":" + index; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; StoredTransactionOutPoint other = (StoredTransactionOutPoint) o; return getIndex() == other.getIndex() && Objects.equals(getHash(), other.getHash()); } } /** * A HashMap<KeyType, ValueType> that is DB transaction-aware * This class is not thread-safe. */ class TransactionalHashMap<KeyType, ValueType> { ThreadLocal<HashMap<KeyType, ValueType>> tempMap; ThreadLocal<HashSet<KeyType>> tempSetRemoved; private ThreadLocal<Boolean> inTransaction; HashMap<KeyType, ValueType> map; public TransactionalHashMap() { tempMap = new ThreadLocal<>(); tempSetRemoved = new ThreadLocal<>(); inTransaction = new ThreadLocal<>(); map = new HashMap<>(); } public void beginDatabaseBatchWrite() { inTransaction.set(true); } public void commitDatabaseBatchWrite() { if (tempSetRemoved.get() != null) for(KeyType key : tempSetRemoved.get()) map.remove(key); if (tempMap.get() != null) for (Map.Entry<KeyType, ValueType> entry : tempMap.get().entrySet()) map.put(entry.getKey(), entry.getValue()); abortDatabaseBatchWrite(); } public void abortDatabaseBatchWrite() { inTransaction.set(false); tempSetRemoved.remove(); tempMap.remove(); } @Nullable public ValueType get(KeyType key) { if (Boolean.TRUE.equals(inTransaction.get())) { if (tempMap.get() != null) { ValueType value = tempMap.get().get(key); if (value != null) return value; } if (tempSetRemoved.get() != null && tempSetRemoved.get().contains(key)) return null; } return map.get(key); } public List<ValueType> values() { List<ValueType> valueTypes = new ArrayList<>(); for (KeyType keyType : map.keySet()) { valueTypes.add(get(keyType)); } return valueTypes; } public void put(KeyType key, ValueType value) { if (Boolean.TRUE.equals(inTransaction.get())) { if (tempSetRemoved.get() != null) tempSetRemoved.get().remove(key); if (tempMap.get() == null) tempMap.set(new HashMap<KeyType, ValueType>()); tempMap.get().put(key, value); }else{ map.put(key, value); } } @Nullable public ValueType remove(KeyType key) { if (Boolean.TRUE.equals(inTransaction.get())) { ValueType retVal = map.get(key); if (retVal != null) { if (tempSetRemoved.get() == null) tempSetRemoved.set(new HashSet<KeyType>()); tempSetRemoved.get().add(key); } if (tempMap.get() != null) { ValueType tempVal = tempMap.get().remove(key); if (tempVal != null) return tempVal; } return retVal; }else{ return map.remove(key); } } } /** * A Map with multiple key types that is DB per-thread-transaction-aware. * However, this class is not thread-safe. * @param <UniqueKeyType> is a key that must be unique per object * @param <MultiKeyType> is a key that can have multiple values */ class TransactionalMultiKeyHashMap<UniqueKeyType, MultiKeyType, ValueType> { TransactionalHashMap<UniqueKeyType, ValueType> mapValues; HashMap<MultiKeyType, Set<UniqueKeyType>> mapKeys; public TransactionalMultiKeyHashMap() { mapValues = new TransactionalHashMap<>(); mapKeys = new HashMap<>(); } public void BeginTransaction() { mapValues.beginDatabaseBatchWrite(); } public void CommitTransaction() { mapValues.commitDatabaseBatchWrite(); } public void AbortTransaction() { mapValues.abortDatabaseBatchWrite(); } @Nullable public ValueType get(UniqueKeyType key) { return mapValues.get(key); } public void put(UniqueKeyType uniqueKey, MultiKeyType multiKey, ValueType value) { mapValues.put(uniqueKey, value); Set<UniqueKeyType> set = mapKeys.get(multiKey); if (set == null) { set = new HashSet<>(); set.add(uniqueKey); mapKeys.put(multiKey, set); }else{ set.add(uniqueKey); } } @Nullable public ValueType removeByUniqueKey(UniqueKeyType key) { return mapValues.remove(key); } public void removeByMultiKey(MultiKeyType key) { Set<UniqueKeyType> set = mapKeys.remove(key); if (set != null) for (UniqueKeyType uniqueKey : set) removeByUniqueKey(uniqueKey); } } /** * Keeps {@link StoredBlock}s, {@link StoredUndoableBlock}s and {@link UTXO}s in memory. * Used primarily for unit testing. */ public class MemoryFullPrunedBlockStore implements FullPrunedBlockStore { protected static class StoredBlockAndWasUndoableFlag { public StoredBlock block; public boolean wasUndoable; public StoredBlockAndWasUndoableFlag(StoredBlock block, boolean wasUndoable) { this.block = block; this.wasUndoable = wasUndoable; } } private TransactionalHashMap<Sha256Hash, StoredBlockAndWasUndoableFlag> blockMap; private TransactionalMultiKeyHashMap<Sha256Hash, Integer, StoredUndoableBlock> fullBlockMap; //TODO: Use something more suited to remove-heavy use? private TransactionalHashMap<StoredTransactionOutPoint, UTXO> transactionOutputMap; private StoredBlock chainHead; private StoredBlock verifiedChainHead; private int fullStoreDepth; private NetworkParameters params; /** * Set up the MemoryFullPrunedBlockStore * @param params The network parameters of this block store - used to get genesis block * @param fullStoreDepth The depth of blocks to keep FullStoredBlocks instead of StoredBlocks */ public MemoryFullPrunedBlockStore(NetworkParameters params, int fullStoreDepth) { blockMap = new TransactionalHashMap<>(); fullBlockMap = new TransactionalMultiKeyHashMap<>(); transactionOutputMap = new TransactionalHashMap<>(); this.fullStoreDepth = fullStoreDepth > 0 ? fullStoreDepth : 1; // Insert the genesis block. try { StoredBlock storedGenesisHeader = new StoredBlock(params.getGenesisBlock().cloneAsHeader(), params.getGenesisBlock().getWork(), 0); // The coinbase in the genesis block is not spendable List<Transaction> genesisTransactions = new LinkedList<>(); StoredUndoableBlock storedGenesis = new StoredUndoableBlock(params.getGenesisBlock().getHash(), genesisTransactions); put(storedGenesisHeader, storedGenesis); setChainHead(storedGenesisHeader); setVerifiedChainHead(storedGenesisHeader); this.params = params; } catch (BlockStoreException | VerificationException e) { throw new RuntimeException(e); // Cannot happen. } } @Override public synchronized void put(StoredBlock block) throws BlockStoreException { Objects.requireNonNull(blockMap, "MemoryFullPrunedBlockStore is closed"); Sha256Hash hash = block.getHeader().getHash(); blockMap.put(hash, new StoredBlockAndWasUndoableFlag(block, false)); } @Override public synchronized final void put(StoredBlock storedBlock, StoredUndoableBlock undoableBlock) throws BlockStoreException { Objects.requireNonNull(blockMap, "MemoryFullPrunedBlockStore is closed"); Sha256Hash hash = storedBlock.getHeader().getHash(); fullBlockMap.put(hash, storedBlock.getHeight(), undoableBlock); blockMap.put(hash, new StoredBlockAndWasUndoableFlag(storedBlock, true)); } @Override @Nullable public synchronized StoredBlock get(Sha256Hash hash) throws BlockStoreException { Objects.requireNonNull(blockMap, "MemoryFullPrunedBlockStore is closed"); StoredBlockAndWasUndoableFlag storedBlock = blockMap.get(hash); return storedBlock == null ? null : storedBlock.block; } @Override @Nullable public synchronized StoredBlock getOnceUndoableStoredBlock(Sha256Hash hash) throws BlockStoreException { Objects.requireNonNull(blockMap, "MemoryFullPrunedBlockStore is closed"); StoredBlockAndWasUndoableFlag storedBlock = blockMap.get(hash); return (storedBlock != null && storedBlock.wasUndoable) ? storedBlock.block : null; } @Override @Nullable public synchronized StoredUndoableBlock getUndoBlock(Sha256Hash hash) throws BlockStoreException { Objects.requireNonNull(fullBlockMap, "MemoryFullPrunedBlockStore is closed"); return fullBlockMap.get(hash); } @Override public synchronized StoredBlock getChainHead() throws BlockStoreException { Objects.requireNonNull(blockMap, "MemoryFullPrunedBlockStore is closed"); return chainHead; } @Override public synchronized final void setChainHead(StoredBlock chainHead) throws BlockStoreException { Objects.requireNonNull(blockMap, "MemoryFullPrunedBlockStore is closed"); this.chainHead = chainHead; } @Override public synchronized StoredBlock getVerifiedChainHead() throws BlockStoreException { Objects.requireNonNull(blockMap, "MemoryFullPrunedBlockStore is closed"); return verifiedChainHead; } @Override public synchronized final void setVerifiedChainHead(StoredBlock chainHead) throws BlockStoreException { Objects.requireNonNull(blockMap, "MemoryFullPrunedBlockStore is closed"); this.verifiedChainHead = chainHead; if (this.chainHead.getHeight() < chainHead.getHeight()) setChainHead(chainHead); // Potential leak here if not all blocks get setChainHead'd // Though the FullPrunedBlockStore allows for this, the current AbstractBlockChain will not do it. fullBlockMap.removeByMultiKey(chainHead.getHeight() - fullStoreDepth); } @Override public void close() { blockMap = null; fullBlockMap = null; transactionOutputMap = null; } @Override @Nullable public synchronized UTXO getTransactionOutput(Sha256Hash hash, long index) throws BlockStoreException { Objects.requireNonNull(transactionOutputMap, "MemoryFullPrunedBlockStore is closed"); return transactionOutputMap.get(new StoredTransactionOutPoint(hash, index)); } @Override public synchronized void addUnspentTransactionOutput(UTXO out) throws BlockStoreException { Objects.requireNonNull(transactionOutputMap, "MemoryFullPrunedBlockStore is closed"); transactionOutputMap.put(new StoredTransactionOutPoint(out), out); } @Override public synchronized void removeUnspentTransactionOutput(UTXO out) throws BlockStoreException { Objects.requireNonNull(transactionOutputMap, "MemoryFullPrunedBlockStore is closed"); if (transactionOutputMap.remove(new StoredTransactionOutPoint(out)) == null) throw new BlockStoreException("Tried to remove a UTXO from MemoryFullPrunedBlockStore that it didn't have!"); } @Override public synchronized void beginDatabaseBatchWrite() throws BlockStoreException { blockMap.beginDatabaseBatchWrite(); fullBlockMap.BeginTransaction(); transactionOutputMap.beginDatabaseBatchWrite(); } @Override public synchronized void commitDatabaseBatchWrite() throws BlockStoreException { blockMap.commitDatabaseBatchWrite(); fullBlockMap.CommitTransaction(); transactionOutputMap.commitDatabaseBatchWrite(); } @Override public synchronized void abortDatabaseBatchWrite() throws BlockStoreException { blockMap.abortDatabaseBatchWrite(); fullBlockMap.AbortTransaction(); transactionOutputMap.abortDatabaseBatchWrite(); } @Override public synchronized boolean hasUnspentOutputs(Sha256Hash hash, int numOutputs) throws BlockStoreException { for (int i = 0; i < numOutputs; i++) if (getTransactionOutput(hash, i) != null) return true; return false; } @Override public Network network() { return params.network(); } @Override public int getChainHeadHeight() throws UTXOProviderException { try { return getVerifiedChainHead().getHeight(); } catch (BlockStoreException e) { throw new UTXOProviderException(e); } } @Override public List<UTXO> getOpenTransactionOutputs(List<ECKey> keys) throws UTXOProviderException { // This is *NOT* optimal: We go through all the outputs and select the ones we are looking for. // If someone uses this store for production then they have a lot more to worry about than an inefficient impl :) List<UTXO> foundOutputs = new ArrayList<>(); List<UTXO> outputsList = transactionOutputMap.values(); for (UTXO output : outputsList) { for (ECKey key : keys) { // TODO switch to pubKeyHash in order to support native segwit addresses Address address = key.toAddress(ScriptType.P2PKH, params.network()); if (output.getAddress().equals(address.toString())) { foundOutputs.add(output); } } } return foundOutputs; } }
16,270
35.482063
143
java
bitcoinj
bitcoinj-master/core/src/main/java/org/bitcoinj/store/SPVBlockStore.java
/* * Copyright 2013 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.bitcoinj.store; import org.bitcoinj.core.Block; import org.bitcoinj.core.NetworkParameters; import org.bitcoinj.core.ProtocolException; import org.bitcoinj.base.Sha256Hash; import org.bitcoinj.core.StoredBlock; import org.bitcoinj.utils.Threading; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.annotation.Nullable; import java.io.File; import java.io.IOException; import java.io.RandomAccessFile; import java.nio.Buffer; import java.nio.ByteBuffer; import java.nio.MappedByteBuffer; import java.nio.channels.FileChannel; import java.nio.channels.FileLock; import java.nio.charset.StandardCharsets; import java.util.Arrays; import java.util.LinkedHashMap; import java.util.Map; import java.util.Objects; import java.util.concurrent.locks.ReentrantLock; import static org.bitcoinj.base.internal.Preconditions.checkArgument; import static org.bitcoinj.base.internal.Preconditions.checkState; // TODO: Lose the mmap in this class. There are too many platform bugs that require odd workarounds. /** * An SPVBlockStore holds a limited number of block headers in a memory mapped ring buffer. With such a store, you * may not be able to process very deep re-orgs and could be disconnected from the chain (requiring a replay), * but as they are virtually unheard of this is not a significant risk. */ public class SPVBlockStore implements BlockStore { private static final Logger log = LoggerFactory.getLogger(SPVBlockStore.class); protected final ReentrantLock lock = Threading.lock(SPVBlockStore.class); /** The default number of headers that will be stored in the ring buffer. */ public static final int DEFAULT_CAPACITY = 10000; public static final String HEADER_MAGIC = "SPVB"; protected volatile MappedByteBuffer buffer; protected final NetworkParameters params; // The entire ring-buffer is mmapped and accessing it should be as fast as accessing regular memory once it's // faulted in. Unfortunately, in theory practice and theory are the same. In practice they aren't. // // MMapping a file in Java does not give us a byte[] as you may expect but rather a ByteBuffer, and whilst on // the OpenJDK/Oracle JVM calls into the get() methods are compiled down to inlined native code on Android each // get() call is actually a full-blown JNI method under the hood, meaning it's unbelievably slow. The caches // below let us stay in the JIT-compiled Java world without expensive JNI transitions and make a 10x difference! protected LinkedHashMap<Sha256Hash, StoredBlock> blockCache = new LinkedHashMap<Sha256Hash, StoredBlock>() { @Override protected boolean removeEldestEntry(Map.Entry<Sha256Hash, StoredBlock> entry) { return size() > 2050; // Slightly more than the difficulty transition period. } }; // Use a separate cache to track get() misses. This is to efficiently handle the case of an unconnected block // during chain download. Each new block will do a get() on the unconnected block so if we haven't seen it yet we // must efficiently respond. // // We don't care about the value in this cache. It is always notFoundMarker. Unfortunately LinkedHashSet does not // provide the removeEldestEntry control. private static final Object NOT_FOUND_MARKER = new Object(); protected LinkedHashMap<Sha256Hash, Object> notFoundCache = new LinkedHashMap<Sha256Hash, Object>() { @Override protected boolean removeEldestEntry(Map.Entry<Sha256Hash, Object> entry) { return size() > 100; // This was chosen arbitrarily. } }; // Used to stop other applications/processes from opening the store. protected FileLock fileLock = null; protected RandomAccessFile randomAccessFile = null; private int fileLength; /** * Creates and initializes an SPV block store that can hold {@link #DEFAULT_CAPACITY} block headers. Will create the * given file if it's missing. This operation will block on disk. * @param file file to use for the block store * @throws BlockStoreException if something goes wrong */ public SPVBlockStore(NetworkParameters params, File file) throws BlockStoreException { this(params, file, DEFAULT_CAPACITY, false); } /** * Creates and initializes an SPV block store that can hold a given amount of blocks. Will create the given file if * it's missing. This operation will block on disk. * @param file file to use for the block store * @param capacity custom capacity in number of block headers * @param grow wether or not to migrate an existing block store of different capacity * @throws BlockStoreException if something goes wrong */ public SPVBlockStore(NetworkParameters params, File file, int capacity, boolean grow) throws BlockStoreException { Objects.requireNonNull(file); this.params = Objects.requireNonNull(params); checkArgument(capacity > 0); try { boolean exists = file.exists(); // Set up the backing file. randomAccessFile = new RandomAccessFile(file, "rw"); fileLength = getFileSize(capacity); if (!exists) { log.info("Creating new SPV block chain file " + file); randomAccessFile.setLength(fileLength); } else { final long currentLength = randomAccessFile.length(); if (currentLength != fileLength) { if ((currentLength - FILE_PROLOGUE_BYTES) % RECORD_SIZE != 0) throw new BlockStoreException( "File size on disk indicates this is not a block store: " + currentLength); else if (!grow) throw new BlockStoreException("File size on disk does not match expected size: " + currentLength + " vs " + fileLength); else if (fileLength < randomAccessFile.length()) throw new BlockStoreException( "Shrinking is unsupported: " + currentLength + " vs " + fileLength); else randomAccessFile.setLength(fileLength); } } FileChannel channel = randomAccessFile.getChannel(); fileLock = channel.tryLock(); if (fileLock == null) throw new ChainFileLockedException("Store file is already locked by another process"); // Map it into memory read/write. The kernel will take care of flushing writes to disk at the most // efficient times, which may mean that until the map is deallocated the data on disk is randomly // inconsistent. However the only process accessing it is us, via this mapping, so our own view will // always be correct. Once we establish the mmap the underlying file and channel can go away. Note that // the details of mmapping vary between platforms. buffer = channel.map(FileChannel.MapMode.READ_WRITE, 0, fileLength); // Check or initialize the header bytes to ensure we don't try to open some random file. if (exists) { byte[] header = new byte[4]; buffer.get(header); if (!new String(header, StandardCharsets.US_ASCII).equals(HEADER_MAGIC)) throw new BlockStoreException("Header bytes do not equal " + HEADER_MAGIC); } else { initNewStore(params.getGenesisBlock()); } } catch (Exception e) { try { if (randomAccessFile != null) randomAccessFile.close(); } catch (IOException e2) { throw new BlockStoreException(e2); } throw new BlockStoreException(e); } } private void initNewStore(Block genesisBlock) throws Exception { byte[] header; header = HEADER_MAGIC.getBytes(StandardCharsets.US_ASCII); buffer.put(header); // Insert the genesis block. lock.lock(); try { setRingCursor(buffer, FILE_PROLOGUE_BYTES); } finally { lock.unlock(); } StoredBlock storedGenesis = new StoredBlock(genesisBlock.cloneAsHeader(), genesisBlock.getWork(), 0); put(storedGenesis); setChainHead(storedGenesis); } /** Returns the size in bytes of the file that is used to store the chain with the current parameters. */ public static int getFileSize(int capacity) { return RECORD_SIZE * capacity + FILE_PROLOGUE_BYTES /* extra kilobyte for stuff */; } @Override public void put(StoredBlock block) throws BlockStoreException { final MappedByteBuffer buffer = this.buffer; if (buffer == null) throw new BlockStoreException("Store closed"); lock.lock(); try { int cursor = getRingCursor(buffer); if (cursor == fileLength) { // Wrapped around. cursor = FILE_PROLOGUE_BYTES; } ((Buffer) buffer).position(cursor); Sha256Hash hash = block.getHeader().getHash(); notFoundCache.remove(hash); buffer.put(hash.getBytes()); block.serializeCompact(buffer); setRingCursor(buffer, buffer.position()); blockCache.put(hash, block); } finally { lock.unlock(); } } @Override @Nullable public StoredBlock get(Sha256Hash hash) throws BlockStoreException { final MappedByteBuffer buffer = this.buffer; if (buffer == null) throw new BlockStoreException("Store closed"); lock.lock(); try { StoredBlock cacheHit = blockCache.get(hash); if (cacheHit != null) return cacheHit; if (notFoundCache.get(hash) != null) return null; // Starting from the current tip of the ring work backwards until we have either found the block or // wrapped around. int cursor = getRingCursor(buffer); final int startingPoint = cursor; final byte[] targetHashBytes = hash.getBytes(); byte[] scratch = new byte[32]; do { cursor -= RECORD_SIZE; if (cursor < FILE_PROLOGUE_BYTES) { // We hit the start, so wrap around. cursor = fileLength - RECORD_SIZE; } // Cursor is now at the start of the next record to check, so read the hash and compare it. ((Buffer) buffer).position(cursor); buffer.get(scratch); if (Arrays.equals(scratch, targetHashBytes)) { // Found the target. StoredBlock storedBlock = StoredBlock.deserializeCompact(buffer); blockCache.put(hash, storedBlock); return storedBlock; } } while (cursor != startingPoint); // Not found. notFoundCache.put(hash, NOT_FOUND_MARKER); return null; } catch (ProtocolException e) { throw new RuntimeException(e); // Cannot happen. } finally { lock.unlock(); } } protected StoredBlock lastChainHead = null; @Override public StoredBlock getChainHead() throws BlockStoreException { final MappedByteBuffer buffer = this.buffer; if (buffer == null) throw new BlockStoreException("Store closed"); lock.lock(); try { if (lastChainHead == null) { byte[] headHash = new byte[32]; ((Buffer) buffer).position(8); buffer.get(headHash); Sha256Hash hash = Sha256Hash.wrap(headHash); StoredBlock block = get(hash); if (block == null) throw new BlockStoreException("Corrupted block store: could not find chain head: " + hash); lastChainHead = block; } return lastChainHead; } finally { lock.unlock(); } } @Override public void setChainHead(StoredBlock chainHead) throws BlockStoreException { final MappedByteBuffer buffer = this.buffer; if (buffer == null) throw new BlockStoreException("Store closed"); lock.lock(); try { lastChainHead = chainHead; byte[] headHash = chainHead.getHeader().getHash().getBytes(); ((Buffer) buffer).position(8); buffer.put(headHash); } finally { lock.unlock(); } } @Override public void close() throws BlockStoreException { try { buffer.force(); buffer = null; // Allow it to be GCd and the underlying file mapping to go away. fileLock.release(); randomAccessFile.close(); blockCache.clear(); } catch (IOException e) { throw new BlockStoreException(e); } } protected static final int RECORD_SIZE = 32 /* hash */ + StoredBlock.COMPACT_SERIALIZED_SIZE; // File format: // 4 header bytes = "SPVB" // 4 cursor bytes, which indicate the offset from the first kb where the next block header should be written. // 32 bytes for the hash of the chain head // // For each header (128 bytes) // 32 bytes hash of the header // 12 bytes of chain work // 4 bytes of height // 80 bytes of block header data protected static final int FILE_PROLOGUE_BYTES = 1024; /** Returns the offset from the file start where the latest block should be written (end of prev block). */ private int getRingCursor(ByteBuffer buffer) { int c = buffer.getInt(4); checkState(c >= FILE_PROLOGUE_BYTES, () -> "integer overflow"); return c; } private void setRingCursor(ByteBuffer buffer, int newCursor) { checkArgument(newCursor >= 0); buffer.putInt(4, newCursor); } public void clear() throws Exception { lock.lock(); try { // Clear caches blockCache.clear(); notFoundCache.clear(); // Clear file content ((Buffer) buffer).position(0); long fileLength = randomAccessFile.length(); for (int i = 0; i < fileLength; i++) { buffer.put((byte)0); } // Initialize store again ((Buffer) buffer).position(0); initNewStore(params.getGenesisBlock()); } finally { lock.unlock(); } } }
15,339
42.089888
120
java
bitcoinj
bitcoinj-master/core/src/main/java/org/bitcoinj/store/MemoryBlockStore.java
/* * Copyright 2011 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.bitcoinj.store; import org.bitcoinj.core.Block; import org.bitcoinj.base.Sha256Hash; import org.bitcoinj.core.StoredBlock; import org.bitcoinj.core.VerificationException; import java.util.LinkedHashMap; import java.util.Map; /** * Keeps {@link StoredBlock}s in memory. Used primarily for unit testing. */ public class MemoryBlockStore implements BlockStore { private LinkedHashMap<Sha256Hash, StoredBlock> blockMap = new LinkedHashMap<Sha256Hash, StoredBlock>() { @Override protected boolean removeEldestEntry(Map.Entry<Sha256Hash, StoredBlock> eldest) { return blockMap.size() > 5000; } }; private StoredBlock chainHead; public MemoryBlockStore(Block genesisBlock) { try { Block genesisHeader = genesisBlock.cloneAsHeader(); StoredBlock storedGenesis = new StoredBlock(genesisHeader, genesisHeader.getWork(), 0); put(storedGenesis); setChainHead(storedGenesis); } catch (BlockStoreException | VerificationException e) { throw new RuntimeException(e); // Cannot happen. } } @Override public synchronized final void put(StoredBlock block) throws BlockStoreException { if (blockMap == null) throw new BlockStoreException("MemoryBlockStore is closed"); Sha256Hash hash = block.getHeader().getHash(); blockMap.put(hash, block); } @Override public synchronized StoredBlock get(Sha256Hash hash) throws BlockStoreException { if (blockMap == null) throw new BlockStoreException("MemoryBlockStore is closed"); return blockMap.get(hash); } @Override public StoredBlock getChainHead() throws BlockStoreException { if (blockMap == null) throw new BlockStoreException("MemoryBlockStore is closed"); return chainHead; } @Override public final void setChainHead(StoredBlock chainHead) throws BlockStoreException { if (blockMap == null) throw new BlockStoreException("MemoryBlockStore is closed"); this.chainHead = chainHead; } @Override public void close() { blockMap = null; } }
2,768
33.6125
108
java
bitcoinj
bitcoinj-master/core/src/main/java/org/bitcoinj/base/package-info.java
/* * Copyright by the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * The {@code base} package provides foundational types for <b>bitcoinj</b>. These types must have * minimal dependencies. The criteria for allowed dependencies for {@code base} types are: * <ul> * <li>No dependencies on other packages of bitcoinj</li> * <li>No API dependencies on external libraries other than the core JDK and {@code slf4j-api}</li> * </ul> * <p> * <b>Temporary exception:</b> In the 0.17 release, we are allowing some dependencies on other packages, e.g. to * {@link org.bitcoinj.core.NetworkParameters} or to Guava <i>provided</i> that those references are in <b>deprecated</b> methods. * This smooths migration by allowing users to, for example, replace {@code import org.bitcoinj.core.Address} with * {@code import org.bitcoinj.base.Address} as first step of conversion and then remove usages of the deprecated methods * of {@code Address} in a second step. * <p> * The base package makes bitcoinj more modular as it breaks circular dependencies between existing packages and provides * a "zero-dependency" foundation for the other packages. In a future release {@code base} will be * split into a separate JAR/module (tentatively {@code bitcoinj-base}.) */ package org.bitcoinj.base;
1,849
50.388889
130
java
bitcoinj
bitcoinj-master/core/src/main/java/org/bitcoinj/base/Coin.java
/* * Copyright 2014 Andreas Schildbach * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.bitcoinj.base; import org.bitcoinj.base.utils.MonetaryFormat; import java.math.BigDecimal; import java.nio.BufferOverflowException; import java.nio.BufferUnderflowException; import java.nio.ByteBuffer; import java.nio.ByteOrder; import static org.bitcoinj.base.internal.Preconditions.checkArgument; /** * Represents a monetary Bitcoin value. This class is immutable and should be treated as a Java <a href="https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/lang/doc-files/ValueBased.html#Value-basedClasses">Value-based class</a>. * We recommend using the {@code Coin} class wherever possible to represent Bitcoin monetary values. If you have existing * code that uses other numeric types and need to convert there are conversion methods. * <p> * Internally {@code Coin} is implemented as a {@code long} (see {@link #value}) that represents a number of <a href="https://en.bitcoin.it/wiki/Satoshi_(unit)">satoshis</a>. It * can also be considered a <a href="https://en.wikipedia.org/wiki/Fixed-point_arithmetic">fixed-point</a> number of <a href="https://en.bitcoin.it/wiki/Units">bitcoins</a>. * <p> * To create a {@code Coin} from an integer number of satoshis, use {@link #ofSat(long)}. To convert to a {@code long} number * of satoshis use {@link #toSat()}. (You can also use {@link #valueOf(long)}, {@link #getValue()} or {@link #value}.) * <p> * To create a {@code Coin} from a decimal number of bitcoins, use {@link #ofBtc(BigDecimal)}. To convert to a {@link BigDecimal} * of bitcoins use {@link #toBtc()}. (Performing fixed-point <a href="https://en.wikipedia.org/wiki/Fixed-point_arithmetic#Conversion_to_and_from_floating-point">conversion</a>, these methods essentially multiply or divide by {@code Coin.COIN.toSat()}.) * <p> * <b>Never ever</b> use {@code float} or {@code double} to represent monetary values. */ public final class Coin implements Monetary, Comparable<Coin> { /** * Number of decimals for one Bitcoin. This constant is useful for quick adapting to other coins because a lot of * constants derive from it. */ public static final int SMALLEST_UNIT_EXPONENT = 8; /** * The number of satoshis equal to one bitcoin. */ private static final long COIN_VALUE = 100_000_000; /** * Zero Bitcoins. */ public static final Coin ZERO = new Coin(0); /** * One Bitcoin. */ public static final Coin COIN = Coin.valueOf(COIN_VALUE); /** * 0.01 Bitcoins. This unit is not really used much. */ public static final Coin CENT = COIN.divide(100); /** * 0.001 Bitcoins, also known as 1 mBTC. */ public static final Coin MILLICOIN = COIN.divide(1000); /** * 0.000001 Bitcoins, also known as 1 µBTC or 1 uBTC. */ public static final Coin MICROCOIN = MILLICOIN.divide(1000); /** * A satoshi is the smallest unit that can be transferred. 100 million of them fit into a Bitcoin. */ public static final Coin SATOSHI = Coin.valueOf(1); public static final Coin FIFTY_COINS = COIN.multiply(50); /** * Represents a monetary value of minus one satoshi. */ public static final Coin NEGATIVE_SATOSHI = Coin.valueOf(-1); /** Number of bytes to store this amount. */ public static final int BYTES = 8; /** * The number of satoshis of this monetary value. */ public final long value; private Coin(final long satoshis) { this.value = satoshis; } /** * Create a {@code Coin} from a long integer number of satoshis. * * @param satoshis number of satoshis * @return {@code Coin} object containing value in satoshis */ public static Coin valueOf(final long satoshis) { // Avoid allocating a new object for Coins of value zero return satoshis == 0 ? Coin.ZERO : new Coin(satoshis); } /** * Read a Coin amount from the given buffer as 8 bytes in little-endian order. * * @param buf buffer to read from * @return read amount * @throws BufferUnderflowException if the read value extends beyond the remaining bytes of the buffer */ public static Coin read(ByteBuffer buf) throws BufferUnderflowException { return valueOf(buf.order(ByteOrder.LITTLE_ENDIAN).getLong()); } @Override public int smallestUnitExponent() { return SMALLEST_UNIT_EXPONENT; } /** * Returns the number of satoshis of this monetary value. */ @Override public long getValue() { return value; } /** * Create a {@code Coin} from an amount expressed in "the way humans are used to". * * @param coins Number of bitcoins * @param cents Number of bitcents (0.01 bitcoin) * @return {@code Coin} object containing value in satoshis */ public static Coin valueOf(final int coins, final int cents) { checkArgument(cents < 100, () -> "cents nust be below 100: " + cents); checkArgument(cents >= 0, () -> "cents cannot be negative: " + cents); checkArgument(coins >= 0, () -> "coins cannot be negative: " + cents); final Coin coin = COIN.multiply(coins).add(CENT.multiply(cents)); return coin; } /** * Convert a decimal amount of BTC into satoshis. * * @param coins number of coins * @return number of satoshis * @throws ArithmeticException if value has too much precision or will not fit in a long */ public static long btcToSatoshi(BigDecimal coins) throws ArithmeticException { return coins.movePointRight(SMALLEST_UNIT_EXPONENT).longValueExact(); } /** * Convert an amount in satoshis to an amount in BTC. * * @param satoshis number of satoshis * @return number of bitcoins (in BTC) */ public static BigDecimal satoshiToBtc(long satoshis) { return new BigDecimal(satoshis).movePointLeft(SMALLEST_UNIT_EXPONENT); } /** * Create a {@code Coin} from a decimal amount of BTC. * * @param coins number of coins (in BTC) * @return {@code Coin} object containing value in satoshis * @throws ArithmeticException if value has too much precision or will not fit in a long */ public static Coin ofBtc(BigDecimal coins) throws ArithmeticException { return Coin.valueOf(btcToSatoshi(coins)); } /** * Create a {@code Coin} from a long integer number of satoshis. * * @param satoshis number of satoshis * @return {@code Coin} object containing value in satoshis */ public static Coin ofSat(long satoshis) { return Coin.valueOf(satoshis); } /** * Create a {@code Coin} by parsing a {@code String} amount expressed in "the way humans are used to". * * @param str string in a format understood by {@link BigDecimal#BigDecimal(String)}, for example "0", "1", "0.10", * * "1.23E3", "1234.5E-5". * @return {@code Coin} object containing value in satoshis * @throws IllegalArgumentException * if you try to specify fractional satoshis, or a value out of range. */ public static Coin parseCoin(final String str) { try { long satoshis = btcToSatoshi(new BigDecimal(str)); return Coin.valueOf(satoshis); } catch (ArithmeticException e) { throw new IllegalArgumentException(e); // Repackage exception to honor method contract } } /** * Create a {@code Coin} by parsing a {@code String} amount expressed in "the way humans are used to". * The amount is cut to satoshi precision. * * @param str string in a format understood by {@link BigDecimal#BigDecimal(String)}, for example "0", "1", "0.10", * * "1.23E3", "1234.5E-5". * @return {@code Coin} object containing value in satoshis * @throws IllegalArgumentException * if you try to specify a value out of range. */ public static Coin parseCoinInexact(final String str) { try { long satoshis = new BigDecimal(str).movePointRight(SMALLEST_UNIT_EXPONENT).longValue(); return Coin.valueOf(satoshis); } catch (ArithmeticException e) { throw new IllegalArgumentException(e); // Repackage exception to honor method contract } } public Coin add(final Coin value) { return Coin.valueOf(Math.addExact(this.value, value.value)); } /** Alias for add */ public Coin plus(final Coin value) { return add(value); } public Coin subtract(final Coin value) { return Coin.valueOf(Math.subtractExact(this.value, value.value)); } /** Alias for subtract */ public Coin minus(final Coin value) { return subtract(value); } public Coin multiply(final long factor) { return Coin.valueOf(Math.multiplyExact(this.value, factor)); } /** Alias for multiply */ public Coin times(final long factor) { return multiply(factor); } /** Alias for multiply */ public Coin times(final int factor) { return multiply(factor); } public Coin divide(final long divisor) { return Coin.valueOf(this.value / divisor); } /** Alias for divide */ public Coin div(final long divisor) { return divide(divisor); } /** Alias for divide */ public Coin div(final int divisor) { return divide(divisor); } public Coin[] divideAndRemainder(final long divisor) { return new Coin[] { Coin.valueOf(this.value / divisor), Coin.valueOf(this.value % divisor) }; } public long divide(final Coin divisor) { return this.value / divisor.value; } /** * Returns true if and only if this instance represents a monetary value greater than zero, * otherwise false. */ public boolean isPositive() { return signum() == 1; } /** * Returns true if and only if this instance represents a monetary value less than zero, * otherwise false. */ public boolean isNegative() { return signum() == -1; } /** * Returns true if and only if this instance represents zero monetary value, * otherwise false. */ public boolean isZero() { return signum() == 0; } /** * Returns true if the monetary value represented by this instance is greater than that * of the given other Coin, otherwise false. */ public boolean isGreaterThan(Coin other) { return compareTo(other) > 0; } /** * Returns true if the monetary value represented by this instance is less than that * of the given other Coin, otherwise false. */ public boolean isLessThan(Coin other) { return compareTo(other) < 0; } public Coin shiftLeft(final int n) { return Coin.valueOf(this.value << n); } public Coin shiftRight(final int n) { return Coin.valueOf(this.value >> n); } @Override public int signum() { if (this.value == 0) return 0; return this.value < 0 ? -1 : 1; } public Coin negate() { return Coin.valueOf(-this.value); } /** * Returns the number of satoshis of this monetary value. It's deprecated in favour of accessing {@link #value} * directly. */ public long longValue() { return this.value; } /** * Convert to number of satoshis * * @return decimal number of satoshis */ public long toSat() { return this.value; } /** * Convert to number of bitcoin (in BTC) * * @return decimal number of bitcoin (in BTC) */ public BigDecimal toBtc() { return satoshiToBtc(this.value); } /** * Write the amount into the given buffer as 8 bytes in little-endian order. * * @param buf buffer to write into * @return the buffer * @throws BufferOverflowException if the value doesn't fit the remaining buffer */ public ByteBuffer write(ByteBuffer buf) throws BufferOverflowException { return buf.order(ByteOrder.LITTLE_ENDIAN).putLong(this.value); } /** * Allocates a byte array and serializes the amount. * * @return serialized amount */ public byte[] serialize() { ByteBuffer buf = ByteBuffer.allocate(BYTES); return write(buf).array(); } private static final MonetaryFormat FRIENDLY_FORMAT = MonetaryFormat.BTC.minDecimals(2).repeatOptionalDecimals(1, 6).postfixCode(); /** * Returns the value as a 0.12 type string. More digits after the decimal place will be used * if necessary, but two will always be present. */ public String toFriendlyString() { return FRIENDLY_FORMAT.format(this).toString(); } private static final MonetaryFormat PLAIN_FORMAT = MonetaryFormat.BTC.minDecimals(0).repeatOptionalDecimals(1, 8).noCode(); /** * <p> * Returns the value as a plain string denominated in BTC. * The result is unformatted with no trailing zeroes. * For instance, a value of 150000 satoshis gives an output string of "0.0015" BTC * </p> */ public String toPlainString() { return PLAIN_FORMAT.format(this).toString(); } @Override public String toString() { return Long.toString(value); } @Override public boolean equals(final Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; return this.value == ((Coin)o).value; } @Override public int hashCode() { return (int) this.value; } @Override public int compareTo(final Coin other) { return Long.compare(this.value, other.value); } }
14,450
31.768707
253
java
bitcoinj
bitcoinj-master/core/src/main/java/org/bitcoinj/base/Bech32.java
/* * Copyright 2018 Coinomi Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.bitcoinj.base; import org.bitcoinj.base.exceptions.AddressFormatException; import javax.annotation.Nullable; import java.util.Arrays; import java.util.Locale; import static org.bitcoinj.base.internal.Preconditions.checkArgument; /** * Implementation of the Bech32 encoding. * <p>See <a href="https://github.com/bitcoin/bips/blob/master/bip-0350.mediawiki">BIP350</a> and * <a href="https://github.com/bitcoin/bips/blob/master/bip-0173.mediawiki">BIP173</a> for details. */ public class Bech32 { /** The Bech32 character set for encoding. */ private static final String CHARSET = "qpzry9x8gf2tvdw0s3jn54khce6mua7l"; /** The Bech32 character set for decoding. */ private static final byte[] CHARSET_REV = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 15, -1, 10, 17, 21, 20, 26, 30, 7, 5, -1, -1, -1, -1, -1, -1, -1, 29, -1, 24, 13, 25, 9, 8, 23, -1, 18, 22, 31, 27, 19, -1, 1, 0, 3, 16, 11, 28, 12, 14, 6, 4, 2, -1, -1, -1, -1, -1, -1, 29, -1, 24, 13, 25, 9, 8, 23, -1, 18, 22, 31, 27, 19, -1, 1, 0, 3, 16, 11, 28, 12, 14, 6, 4, 2, -1, -1, -1, -1, -1 }; private static final int BECH32_CONST = 1; private static final int BECH32M_CONST = 0x2bc830a3; /** * Enumeration of known Bech32 encoding format types: Bech32 and Bech32m. */ public enum Encoding { BECH32, BECH32M } /** * Bech32 decoded data in 5-bit byte format. Typically, the result of {@link #decode(String)}. */ public static class Bech32Data { public final Encoding encoding; public final String hrp; public final byte[] data; private Bech32Data(final Encoding encoding, final String hrp, final byte[] data) { this.encoding = encoding; this.hrp = hrp; this.data = data; } } /** Find the polynomial with value coefficients mod the generator as 30-bit. */ private static int polymod(final byte[] values) { int c = 1; for (byte v_i: values) { int c0 = (c >>> 25) & 0xff; c = ((c & 0x1ffffff) << 5) ^ (v_i & 0xff); if ((c0 & 1) != 0) c ^= 0x3b6a57b2; if ((c0 & 2) != 0) c ^= 0x26508e6d; if ((c0 & 4) != 0) c ^= 0x1ea119fa; if ((c0 & 8) != 0) c ^= 0x3d4233dd; if ((c0 & 16) != 0) c ^= 0x2a1462b3; } return c; } /** Expand a HRP for use in checksum computation. */ private static byte[] expandHrp(final String hrp) { int hrpLength = hrp.length(); byte ret[] = new byte[hrpLength * 2 + 1]; for (int i = 0; i < hrpLength; ++i) { int c = hrp.charAt(i) & 0x7f; // Limit to standard 7-bit ASCII ret[i] = (byte) ((c >>> 5) & 0x07); ret[i + hrpLength + 1] = (byte) (c & 0x1f); } ret[hrpLength] = 0; return ret; } /** Verify a checksum. */ private static @Nullable Encoding verifyChecksum(final String hrp, final byte[] values) { byte[] hrpExpanded = expandHrp(hrp); byte[] combined = new byte[hrpExpanded.length + values.length]; System.arraycopy(hrpExpanded, 0, combined, 0, hrpExpanded.length); System.arraycopy(values, 0, combined, hrpExpanded.length, values.length); final int check = polymod(combined); if (check == BECH32_CONST) return Encoding.BECH32; else if (check == BECH32M_CONST) return Encoding.BECH32M; else return null; } /** Create a checksum. */ private static byte[] createChecksum(final Encoding encoding, final String hrp, final byte[] values) { byte[] hrpExpanded = expandHrp(hrp); byte[] enc = new byte[hrpExpanded.length + values.length + 6]; System.arraycopy(hrpExpanded, 0, enc, 0, hrpExpanded.length); System.arraycopy(values, 0, enc, hrpExpanded.length, values.length); int mod = polymod(enc) ^ (encoding == Encoding.BECH32 ? BECH32_CONST : BECH32M_CONST); byte[] ret = new byte[6]; for (int i = 0; i < 6; ++i) { ret[i] = (byte) ((mod >>> (5 * (5 - i))) & 31); } return ret; } /** Encode a Bech32 string. */ public static String encode(final Bech32Data bech32) { return encode(bech32.encoding, bech32.hrp, bech32.data); } /** Encode a Bech32 string. */ public static String encode(Encoding encoding, final String hrp, final byte[] values) { checkArgument(hrp.length() >= 1, () -> "human-readable part is too short: " + hrp.length()); checkArgument(hrp.length() <= 83, () -> "human-readable part is too long: " + hrp.length()); String lcHrp = hrp.toLowerCase(Locale.ROOT); byte[] checksum = createChecksum(encoding, lcHrp, values); byte[] combined = new byte[values.length + checksum.length]; System.arraycopy(values, 0, combined, 0, values.length); System.arraycopy(checksum, 0, combined, values.length, checksum.length); StringBuilder sb = new StringBuilder(lcHrp.length() + 1 + combined.length); sb.append(lcHrp); sb.append('1'); for (byte b : combined) { sb.append(CHARSET.charAt(b)); } return sb.toString(); } /** Decode a Bech32 string. */ public static Bech32Data decode(final String str) throws AddressFormatException { boolean lower = false, upper = false; if (str.length() < 8) throw new AddressFormatException.InvalidDataLength("Input too short: " + str.length()); if (str.length() > 90) throw new AddressFormatException.InvalidDataLength("Input too long: " + str.length()); for (int i = 0; i < str.length(); ++i) { char c = str.charAt(i); if (c < 33 || c > 126) throw new AddressFormatException.InvalidCharacter(c, i); if (c >= 'a' && c <= 'z') { if (upper) throw new AddressFormatException.InvalidCharacter(c, i); lower = true; } if (c >= 'A' && c <= 'Z') { if (lower) throw new AddressFormatException.InvalidCharacter(c, i); upper = true; } } final int pos = str.lastIndexOf('1'); if (pos < 1) throw new AddressFormatException.InvalidPrefix("Missing human-readable part"); final int dataPartLength = str.length() - 1 - pos; if (dataPartLength < 6) throw new AddressFormatException.InvalidDataLength("Data part too short: " + dataPartLength); byte[] values = new byte[dataPartLength]; for (int i = 0; i < dataPartLength; ++i) { char c = str.charAt(i + pos + 1); if (CHARSET_REV[c] == -1) throw new AddressFormatException.InvalidCharacter(c, i + pos + 1); values[i] = CHARSET_REV[c]; } String hrp = str.substring(0, pos).toLowerCase(Locale.ROOT); Encoding encoding = verifyChecksum(hrp, values); if (encoding == null) throw new AddressFormatException.InvalidChecksum(); return new Bech32Data(encoding, hrp, Arrays.copyOfRange(values, 0, values.length - 6)); } }
8,045
41.571429
125
java
bitcoinj
bitcoinj-master/core/src/main/java/org/bitcoinj/base/AddressParser.java
/* * Copyright by the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.bitcoinj.base; import org.bitcoinj.base.exceptions.AddressFormatException; /** * Interface for parsing and validating address strings. */ public interface AddressParser { /** * Parse an address that could be for any network * @param addressString string representation of address * @return A validated address object * @throws AddressFormatException invalid address string */ Address parseAddressAnyNetwork(String addressString) throws AddressFormatException; /** * Parse an address and validate for specified network * @param addressString string representation of address * @param network the network the address string must represent * @return A validated address object * @throws AddressFormatException invalid address string or not valid for specified network */ Address parseAddress(String addressString, Network network) throws AddressFormatException; /** * Functional interface for strict parsing. It takes a single parameter, like {@link AddressParser#parseAddressAnyNetwork(String)} * but is used in a context where a specific {@link Network} has been specified. This interface may be * implemented by creating a partial application of ({@link AddressParser#parseAddress(String, Network)} providing * a fixed value for {@link Network}. */ @FunctionalInterface interface Strict { /** * Parse an address in a strict context (e.g. the network must be valid) * @param addressString string representation of address * @return A validated address object * @throws AddressFormatException invalid address string or not valid for network (provided by context) */ Address parseAddress(String addressString) throws AddressFormatException; } }
2,446
40.474576
134
java
bitcoinj
bitcoinj-master/core/src/main/java/org/bitcoinj/base/Network.java
/* * Copyright by the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.bitcoinj.base; /** * Interface for a generic Bitcoin-like cryptocurrency network. See {@link BitcoinNetwork} for the Bitcoin implementation. */ public interface Network { /** * The dot-seperated string id for this network. For example {@code "org.bitcoin.production"} * @return String ID for network */ String id(); /** * Header byte of base58 encoded legacy P2PKH addresses for this network. * @return header byte as an {@code int}. * @see LegacyAddress.AddressHeader */ int legacyAddressHeader(); /** * Header byte of base58 encoded legacy P2SH addresses for this network. * @return header byte as an {@code int}. * @see LegacyAddress.P2SHHeader */ int legacyP2SHHeader(); /** * Human-readable part (HRP) of bech32 encoded segwit addresses for this network. * @return HRP (lowercase) */ String segwitAddressHrp(); /** * The URI scheme for this network. See {@link BitcoinNetwork#uriScheme()}. * @return The URI scheme for this network */ String uriScheme(); /** * Does this network have a fixed maximum number of coins * @return {@code true} if this network has a fixed maximum number of coins */ boolean hasMaxMoney(); /** * Maximum number of coins for this network as a {@link Monetary} value. * Where not applicable, a very large number of coins is returned instead (e.g. the main coin issue for Dogecoin). * @return Maximum number of coins for this network */ Monetary maxMoney(); /** * Check if an amount exceeds the maximum allowed for a network (if the network has one) * @param monetary A monetary amount * @return true if too big, false if an allowed amount */ boolean exceedsMaxMoney(Monetary monetary); }
2,457
31.773333
122
java
bitcoinj
bitcoinj-master/core/src/main/java/org/bitcoinj/base/LegacyAddress.java
/* * Copyright 2011 Google Inc. * Copyright 2014 Giannis Dzegoutanis * Copyright 2015 Andreas Schildbach * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.bitcoinj.base; import org.bitcoinj.base.exceptions.AddressFormatException; import org.bitcoinj.base.internal.ByteUtils; import org.bitcoinj.crypto.ECKey; import org.bitcoinj.core.NetworkParameters; import javax.annotation.Nonnull; import javax.annotation.Nullable; import java.util.Arrays; import java.util.Comparator; import java.util.EnumSet; import java.util.Objects; import java.util.stream.Stream; import static org.bitcoinj.base.BitcoinNetwork.*; /** * <p>A Bitcoin address looks like 1MsScoe2fTJoq4ZPdQgqyhgWeoNamYPevy and is derived from an elliptic curve public key * plus a set of network parameters. Not to be confused with a {@link org.bitcoinj.core.PeerAddress} * or {@link org.bitcoinj.core.AddressMessage} which are about network (TCP) addresses.</p> * * <p>A standard address is built by taking the RIPE-MD160 hash of the public key bytes, with a version prefix and a * checksum suffix, then encoding it textually as base58. The version prefix is used to both denote the network for * which the address is valid (see {@link NetworkParameters}, and also to indicate how the bytes inside the address * should be interpreted. Whilst almost all addresses today are hashes of public keys, another (currently unsupported * type) can contain a hash of a script instead.</p> */ public class LegacyAddress implements Address { /** * An address is a RIPEMD160 hash of a public key, therefore is always 160 bits or 20 bytes. */ public static final int LENGTH = 20; protected final Network network; protected final byte[] bytes; /** True if P2SH, false if P2PKH. */ public final boolean p2sh; /** * Private constructor. Use {@link #fromBase58(String, Network)}, * {@link #fromPubKeyHash(Network, byte[])}, {@link #fromScriptHash(Network, byte[])} or * {@link ECKey#toAddress(ScriptType, Network)}. * * @param network * network this address is valid for * @param p2sh * true if hash160 is hash of a script, false if it is hash of a pubkey * @param hash160 * 20-byte hash of pubkey or script */ private LegacyAddress(Network network, boolean p2sh, byte[] hash160) throws AddressFormatException { this.network = normalizeNetwork(Objects.requireNonNull(network)); this.bytes = Objects.requireNonNull(hash160); if (hash160.length != 20) throw new AddressFormatException.InvalidDataLength( "Legacy addresses are 20 byte (160 bit) hashes, but got: " + hash160.length); this.p2sh = p2sh; } private static Network normalizeNetwork(Network network) { // LegacyAddress does not distinguish between the different testnet types, normalize to TESTNET if (network instanceof BitcoinNetwork) { BitcoinNetwork bitcoinNetwork = (BitcoinNetwork) network; if (bitcoinNetwork == BitcoinNetwork.SIGNET || bitcoinNetwork == BitcoinNetwork.REGTEST) { return BitcoinNetwork.TESTNET; } } return network; } /** * Construct a {@link LegacyAddress} that represents the given pubkey hash. The resulting address will be a P2PKH type of * address. * * @param params * network this address is valid for * @param hash160 * 20-byte pubkey hash * @return constructed address * @deprecated Use {@link #fromPubKeyHash(Network, byte[])} */ @Deprecated public static LegacyAddress fromPubKeyHash(NetworkParameters params, byte[] hash160) throws AddressFormatException { return fromPubKeyHash(params.network(), hash160); } /** * Construct a {@link LegacyAddress} that represents the given pubkey hash. The resulting address will be a P2PKH type of * address. * * @param network network this address is valid for * @param hash160 20-byte pubkey hash * @return constructed address */ public static LegacyAddress fromPubKeyHash(Network network, byte[] hash160) throws AddressFormatException { return new LegacyAddress(network, false, hash160); } /** * Construct a {@link LegacyAddress} that represents the public part of the given {@link ECKey}. Note that an address is * derived from a hash of the public key and is not the public key itself. * * @param params * network this address is valid for * @param key * only the public part is used * @return constructed address * @deprecated Use {@link ECKey#toAddress(ScriptType, Network)} */ @Deprecated public static LegacyAddress fromKey(NetworkParameters params, ECKey key) { return (LegacyAddress) key.toAddress(ScriptType.P2PKH, params.network()); } /** * Construct a {@link LegacyAddress} that represents the given P2SH script hash. * * @param params * network this address is valid for * @param hash160 * P2SH script hash * @return constructed address * @deprecated Use {@link #fromScriptHash(Network, byte[])} */ @Deprecated public static LegacyAddress fromScriptHash(NetworkParameters params, byte[] hash160) throws AddressFormatException { return fromScriptHash(params.network(), hash160); } /** * Construct a {@link LegacyAddress} that represents the given P2SH script hash. * * @param network network this address is valid for * @param hash160 P2SH script hash * @return constructed address */ public static LegacyAddress fromScriptHash(Network network, byte[] hash160) throws AddressFormatException { return new LegacyAddress(network, true, hash160); } /** * Construct a {@link LegacyAddress} from its base58 form. * * @param params * expected network this address is valid for, or null if if the network should be derived from the * base58 * @param base58 * base58-encoded textual form of the address * @throws AddressFormatException * if the given base58 doesn't parse or the checksum is invalid * @throws AddressFormatException.WrongNetwork * if the given address is valid but for a different chain (eg testnet vs mainnet) * @deprecated Use {@link #fromBase58(String, Network)} */ @Deprecated public static LegacyAddress fromBase58(@Nullable NetworkParameters params, String base58) throws AddressFormatException, AddressFormatException.WrongNetwork { AddressParser parser = DefaultAddressParser.fromNetworks(); return (LegacyAddress) ((params != null) ? parser.parseAddress(base58, params.network()) : parser.parseAddressAnyNetwork(base58)); } /** * Construct a {@link LegacyAddress} from its base58 form. * * @param base58 base58-encoded textual form of the address * @param network expected network this address is valid for * @throws AddressFormatException if the given base58 doesn't parse or the checksum is invalid * @throws AddressFormatException.WrongNetwork if the given address is valid but for a different chain (eg testnet vs mainnet) */ public static LegacyAddress fromBase58(String base58, @Nonnull Network network) throws AddressFormatException, AddressFormatException.WrongNetwork { byte[] versionAndDataBytes = Base58.decodeChecked(base58); int version = versionAndDataBytes[0] & 0xFF; byte[] bytes = Arrays.copyOfRange(versionAndDataBytes, 1, versionAndDataBytes.length); if (version == network.legacyAddressHeader()) return new LegacyAddress(network, false, bytes); else if (version == network.legacyP2SHHeader()) return new LegacyAddress(network, true, bytes); throw new AddressFormatException.WrongNetwork(version); } /** * Get the network this address works on. Use of {@link BitcoinNetwork} is preferred to use of {@link NetworkParameters} * when you need to know what network an address is for. * @return the Network. */ @Override public Network network() { return network; } /** * Get the version header of an address. This is the first byte of a base58 encoded address. * * @return version header as one byte */ public int getVersion() { return p2sh ? network.legacyP2SHHeader() : network.legacyAddressHeader(); } /** * Returns the base58-encoded textual form, including version and checksum bytes. * * @return textual form */ public String toBase58() { return Base58.encodeChecked(getVersion(), bytes); } /** The (big endian) 20 byte hash that is the core of a Bitcoin address. */ @Override public byte[] getHash() { return bytes; } /** * Get the type of output script that will be used for sending to the address. This is either * {@link ScriptType#P2PKH} or {@link ScriptType#P2SH}. * * @return type of output script */ @Override public ScriptType getOutputScriptType() { return p2sh ? ScriptType.P2SH : ScriptType.P2PKH; } /** * Given an address, examines the version byte and attempts to find a matching NetworkParameters. If you aren't sure * which network the address is intended for (eg, it was provided by a user), you can use this to decide if it is * compatible with the current wallet. * * @return network the address is valid for * @throws AddressFormatException if the given base58 doesn't parse or the checksum is invalid */ @Deprecated public static NetworkParameters getParametersFromAddress(String address) throws AddressFormatException { return NetworkParameters.fromAddress(DefaultAddressParser.fromNetworks().parseAddressAnyNetwork(address)); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; LegacyAddress other = (LegacyAddress) o; return this.network == other.network && Arrays.equals(this.bytes, other.bytes) && this.p2sh == other.p2sh; } @Override public int hashCode() { return Objects.hash(network, Arrays.hashCode(bytes), p2sh); } @Override public String toString() { return toBase58(); } // Comparator for LegacyAddress, left argument must be LegacyAddress, right argument can be any Address private static final Comparator<Address> LEGACY_ADDRESS_COMPARATOR = Address.PARTIAL_ADDRESS_COMPARATOR .thenComparingInt(a -> ((LegacyAddress) a).getVersion()) // Then compare Legacy address version byte .thenComparing(a -> ((LegacyAddress) a).bytes, ByteUtils.arrayUnsignedComparator()); // Then compare Legacy bytes /** * {@inheritDoc} * * @param o other {@code Address} object * @return comparison result */ @Override public int compareTo(Address o) { return LEGACY_ADDRESS_COMPARATOR.compare(this, o); } /** * Address header of legacy P2PKH addresses for standard Bitcoin networks. */ public enum AddressHeader { X0(0, MAINNET), X111(111, TESTNET, REGTEST), X6F(0x6f, SIGNET); private final int headerByte; private final EnumSet<BitcoinNetwork> networks; /** * @param network network to find enum for * @return the corresponding enum */ public static AddressHeader ofNetwork(BitcoinNetwork network) { return Stream.of(AddressHeader.values()) .filter(header -> header.networks.contains(network)) .findFirst() .orElseThrow(IllegalStateException::new); } AddressHeader(int headerByte, BitcoinNetwork first, BitcoinNetwork... rest) { this.headerByte = headerByte; this.networks = EnumSet.of(first, rest); } public int headerByte() { return headerByte; } } /** * Address header of legacy P2SH addresses for standard Bitcoin networks. */ public enum P2SHHeader { X5(5, MAINNET), X196(196, TESTNET, SIGNET, REGTEST); private final int headerByte; private final EnumSet<BitcoinNetwork> networks; /** * @param network network to find enum for * @return the corresponding enum */ public static P2SHHeader ofNetwork(BitcoinNetwork network) { return Stream.of(P2SHHeader.values()) .filter(header -> header.networks.contains(network)) .findFirst() .orElseThrow(IllegalStateException::new); } P2SHHeader(int headerByte, BitcoinNetwork first, BitcoinNetwork... rest) { this.headerByte = headerByte; this.networks = EnumSet.of(first, rest); } public int headerByte() { return headerByte; } } }
13,947
37.744444
130
java
bitcoinj
bitcoinj-master/core/src/main/java/org/bitcoinj/base/DefaultAddressParser.java
/* * Copyright by the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.bitcoinj.base; import org.bitcoinj.base.exceptions.AddressFormatException; import org.bitcoinj.base.internal.StreamUtils; import org.bitcoinj.core.NetworkParameters; import org.bitcoinj.params.Networks; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; /** * Address parser that knows about the address types supported by bitcoinj core and is configurable * with additional network types. */ public class DefaultAddressParser implements AddressParser { // Networks to try when parsing segwit addresses public static final List<Network> DEFAULT_NETWORKS_SEGWIT = unmodifiableList( BitcoinNetwork.MAINNET, BitcoinNetwork.TESTNET, BitcoinNetwork.REGTEST); // Networks to try when parsing legacy (base58) addresses public static final List<Network> DEFAULT_NETWORKS_LEGACY = unmodifiableList( BitcoinNetwork.MAINNET, BitcoinNetwork.TESTNET); // Networks to search when parsing segwit addresses private final List<Network> segwitNetworks; // Networks to search when parsing base58 addresses private final List<Network> base58Networks; /** * DefaultAddressParser with default network lists */ public DefaultAddressParser() { this(DEFAULT_NETWORKS_SEGWIT, DEFAULT_NETWORKS_LEGACY); } /** * Use this constructor if you have a custom list of networks to use when parsing addresses * @param segwitNetworks Networks to search when parsing segwit addresses * @param base58Networks Networks to search when parsing base58 addresses */ public DefaultAddressParser(List<Network> segwitNetworks, List<Network> base58Networks) { this.segwitNetworks = segwitNetworks; this.base58Networks = base58Networks; } /** * Dynamically create a new AddressParser using a snapshot of currently configured networks * from Networks.get(). * @return A backward-compatible parser */ @Deprecated public static DefaultAddressParser fromNetworks() { List<Network> nets = Networks.get().stream() .map(NetworkParameters::network) .collect(StreamUtils.toUnmodifiableList()); return new DefaultAddressParser(nets, nets); } @Override public Address parseAddressAnyNetwork(String addressString) throws AddressFormatException { try { return parseBase58AnyNetwork(addressString); } catch (AddressFormatException.WrongNetwork x) { throw x; } catch (AddressFormatException x) { try { return parseBech32AnyNetwork(addressString); } catch (AddressFormatException.WrongNetwork x2) { throw x; } catch (AddressFormatException x2) { //throw new AddressFormatException(addressString); throw x2; } } } @Override public Address parseAddress(String addressString, Network network) throws AddressFormatException { try { return LegacyAddress.fromBase58(addressString, network); } catch (AddressFormatException.WrongNetwork x) { throw x; } catch (AddressFormatException x) { try { return SegwitAddress.fromBech32(addressString, network); } catch (AddressFormatException.WrongNetwork x2) { throw x; } catch (AddressFormatException x2) { throw new AddressFormatException(addressString); } } } /** * Construct a {@link SegwitAddress} from its textual form. * * @param bech32 bech32-encoded textual form of the address * @return constructed address * @throws AddressFormatException if something about the given bech32 address isn't right */ private SegwitAddress parseBech32AnyNetwork(String bech32) throws AddressFormatException { String hrp = Bech32.decode(bech32).hrp; return segwitNetworks.stream() .filter(n -> hrp.equals(n.segwitAddressHrp())) .findFirst() .map(n -> SegwitAddress.fromBech32(bech32, n)) .orElseThrow(() -> new AddressFormatException.InvalidPrefix("No network found for " + bech32)); } /** * Construct a {@link LegacyAddress} from its base58 form. * * @param base58 base58-encoded textual form of the address * @throws AddressFormatException if the given base58 doesn't parse or the checksum is invalid * @throws AddressFormatException.WrongNetwork if the given address is valid but for a different chain (eg testnet vs mainnet) */ private LegacyAddress parseBase58AnyNetwork(String base58) throws AddressFormatException, AddressFormatException.WrongNetwork { int version = Base58.decodeChecked(base58)[0] & 0xFF; return base58Networks.stream() .filter(n -> version == n.legacyAddressHeader() || version == n.legacyP2SHHeader()) .findFirst() .map(n -> LegacyAddress.fromBase58(base58, n)) .orElseThrow(() -> new AddressFormatException.InvalidPrefix("No network found for " + base58)); } // Create an unmodifiable set of NetworkParameters from an array/varargs private static List<Network> unmodifiableList(Network... ts) { return Collections.unmodifiableList(new ArrayList<>(Arrays.asList(ts))); } }
6,422
40.43871
130
java
bitcoinj
bitcoinj-master/core/src/main/java/org/bitcoinj/base/Base58.java
/* * Copyright 2011 Google Inc. * Copyright 2018 Andreas Schildbach * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.bitcoinj.base; import org.bitcoinj.base.exceptions.AddressFormatException; import org.bitcoinj.base.internal.ByteUtils; import java.math.BigInteger; import java.util.Arrays; /** * Base58 is a way to encode Bitcoin addresses (or arbitrary data) as alphanumeric strings. * <p> * Note that this is not the same base58 as used by Flickr, which you may find referenced around the Internet. * <p> * You may want to consider working with {@code org.bitcoinj.core.EncodedPrivateKey} instead, which * adds support for testing the prefix and suffix bytes commonly found in addresses. * <p> * Satoshi explains: why base-58 instead of standard base-64 encoding? * <ul> * <li>Don't want 0OIl characters that look the same in some fonts and * could be used to create visually identical looking account numbers.</li> * <li>A string with non-alphanumeric characters is not as easily accepted as an account number.</li> * <li>E-mail usually won't line-break if there's no punctuation to break at.</li> * <li>Doubleclicking selects the whole number as one word if it's all alphanumeric.</li> * </ul> * <p> * However, note that the encoding/decoding runs in O(n&sup2;) time, so it is not useful for large data. * <p> * The basic idea of the encoding is to treat the data bytes as a large number represented using * base-256 digits, convert the number to be represented using base-58 digits, preserve the exact * number of leading zeros (which are otherwise lost during the mathematical operations on the * numbers), and finally represent the resulting base-58 digits as alphanumeric ASCII characters. */ public class Base58 { public static final char[] ALPHABET = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz".toCharArray(); private static final char ENCODED_ZERO = ALPHABET[0]; private static final int[] INDEXES = new int[128]; static { Arrays.fill(INDEXES, -1); for (int i = 0; i < ALPHABET.length; i++) { INDEXES[ALPHABET[i]] = i; } } /** * Encodes the given bytes as a base58 string (no checksum is appended). * * @param input the bytes to encode * @return the base58-encoded string */ public static String encode(byte[] input) { if (input.length == 0) { return ""; } // Count leading zeros. int zeros = 0; while (zeros < input.length && input[zeros] == 0) { ++zeros; } // Convert base-256 digits to base-58 digits (plus conversion to ASCII characters) input = Arrays.copyOf(input, input.length); // since we modify it in-place char[] encoded = new char[input.length * 2]; // upper bound int outputStart = encoded.length; for (int inputStart = zeros; inputStart < input.length; ) { encoded[--outputStart] = ALPHABET[divmod(input, inputStart, 256, 58)]; if (input[inputStart] == 0) { ++inputStart; // optimization - skip leading zeros } } // Preserve exactly as many leading encoded zeros in output as there were leading zeros in input. while (outputStart < encoded.length && encoded[outputStart] == ENCODED_ZERO) { ++outputStart; } while (--zeros >= 0) { encoded[--outputStart] = ENCODED_ZERO; } // Return encoded string (including encoded leading zeros). return new String(encoded, outputStart, encoded.length - outputStart); } /** * Encodes the given version and bytes as a base58 string. A checksum is appended. * * @param version the version to encode * @param payload the bytes to encode, e.g. pubkey hash * @return the base58-encoded string */ public static String encodeChecked(int version, byte[] payload) { if (version < 0 || version > 255) throw new IllegalArgumentException("Version not in range."); // A stringified buffer is: // 1 byte version + data bytes + 4 bytes check code (a truncated hash) byte[] addressBytes = new byte[1 + payload.length + 4]; addressBytes[0] = (byte) version; System.arraycopy(payload, 0, addressBytes, 1, payload.length); byte[] checksum = Sha256Hash.hashTwice(addressBytes, 0, payload.length + 1); System.arraycopy(checksum, 0, addressBytes, payload.length + 1, 4); return Base58.encode(addressBytes); } /** * Decodes the given base58 string into the original data bytes. * * @param input the base58-encoded string to decode * @return the decoded data bytes * @throws AddressFormatException if the given string is not a valid base58 string */ public static byte[] decode(String input) throws AddressFormatException { if (input.length() == 0) { return new byte[0]; } // Convert the base58-encoded ASCII chars to a base58 byte sequence (base58 digits). byte[] input58 = new byte[input.length()]; for (int i = 0; i < input.length(); ++i) { char c = input.charAt(i); int digit = c < 128 ? INDEXES[c] : -1; if (digit < 0) { throw new AddressFormatException.InvalidCharacter(c, i); } input58[i] = (byte) digit; } // Count leading zeros. int zeros = 0; while (zeros < input58.length && input58[zeros] == 0) { ++zeros; } // Convert base-58 digits to base-256 digits. byte[] decoded = new byte[input.length()]; int outputStart = decoded.length; for (int inputStart = zeros; inputStart < input58.length; ) { decoded[--outputStart] = divmod(input58, inputStart, 58, 256); if (input58[inputStart] == 0) { ++inputStart; // optimization - skip leading zeros } } // Ignore extra leading zeroes that were added during the calculation. while (outputStart < decoded.length && decoded[outputStart] == 0) { ++outputStart; } // Return decoded data (including original number of leading zeros). return Arrays.copyOfRange(decoded, outputStart - zeros, decoded.length); } public static BigInteger decodeToBigInteger(String input) throws AddressFormatException { return ByteUtils.bytesToBigInteger(decode(input)); } /** * Decodes the given base58 string into the original data bytes, using the checksum in the * last 4 bytes of the decoded data to verify that the rest are correct. The checksum is * removed from the returned data. * * @param input the base58-encoded string to decode (which should include the checksum) * @throws AddressFormatException if the input is not base 58 or the checksum does not validate. */ public static byte[] decodeChecked(String input) throws AddressFormatException { byte[] decoded = decode(input); if (decoded.length < 4) throw new AddressFormatException.InvalidDataLength("Input too short: " + decoded.length); byte[] data = Arrays.copyOfRange(decoded, 0, decoded.length - 4); byte[] checksum = Arrays.copyOfRange(decoded, decoded.length - 4, decoded.length); byte[] actualChecksum = Arrays.copyOfRange(Sha256Hash.hashTwice(data), 0, 4); if (!Arrays.equals(checksum, actualChecksum)) throw new AddressFormatException.InvalidChecksum(); return data; } /** * Divides a number, represented as an array of bytes each containing a single digit * in the specified base, by the given divisor. The given number is modified in-place * to contain the quotient, and the return value is the remainder. * * @param number the number to divide * @param firstDigit the index within the array of the first non-zero digit * (this is used for optimization by skipping the leading zeros) * @param base the base in which the number's digits are represented (up to 256) * @param divisor the number to divide by (up to 256) * @return the remainder of the division operation */ private static byte divmod(byte[] number, int firstDigit, int base, int divisor) { // this is just long division which accounts for the base of the input digits int remainder = 0; for (int i = firstDigit; i < number.length; i++) { int digit = (int) number[i] & 0xFF; int temp = remainder * base + digit; number[i] = (byte) (temp / divisor); remainder = temp % divisor; } return (byte) remainder; } }
9,344
43.712919
117
java
bitcoinj
bitcoinj-master/core/src/main/java/org/bitcoinj/base/SegwitAddress.java
/* * Copyright by the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.bitcoinj.base; import org.bitcoinj.base.exceptions.AddressFormatException; import org.bitcoinj.base.internal.ByteUtils; import org.bitcoinj.crypto.ECKey; import org.bitcoinj.core.NetworkParameters; import javax.annotation.Nonnull; import javax.annotation.Nullable; import java.io.ByteArrayOutputStream; import java.util.Arrays; import java.util.Comparator; import java.util.EnumSet; import java.util.Objects; import java.util.Optional; import java.util.stream.Stream; import static org.bitcoinj.base.BitcoinNetwork.*; /** * <p>Implementation of native segwit addresses. They are composed of two parts:</p> * * <ul> * <li>A human-readable part (HRP) which is a string the specifies the network. See * {@link SegwitAddress.SegwitHrp}.</li> * <li>A data part, containing the witness version (encoded as an OP_N operator) and program (encoded by re-arranging * bits into groups of 5).</li> * </ul> * * <p>See <a href="https://github.com/bitcoin/bips/blob/master/bip-0350.mediawiki">BIP350</a> and * <a href="https://github.com/bitcoin/bips/blob/master/bip-0173.mediawiki">BIP173</a> for details.</p> * * <p>However, you don't need to care about the internals. Use {@link #fromBech32(String, Network)}, * {@link #fromHash(org.bitcoinj.base.Network, byte[])} or {@link ECKey#toAddress(ScriptType, Network)} * to construct a native segwit address.</p> */ public class SegwitAddress implements Address { public static final int WITNESS_PROGRAM_LENGTH_PKH = 20; public static final int WITNESS_PROGRAM_LENGTH_SH = 32; public static final int WITNESS_PROGRAM_LENGTH_TR = 32; public static final int WITNESS_PROGRAM_MIN_LENGTH = 2; public static final int WITNESS_PROGRAM_MAX_LENGTH = 40; /** * Human-readable part (HRP) of Segwit addresses for standard Bitcoin networks. * <p> * See <a href="https://github.com/bitcoin/bips/blob/master/bip-0173.mediawiki#user-content-Segwit_address_format">BIP 173 definition of {@code bc} and {@code tb} HRPs</a> and * <a href="https://github.com/bitcoin/bitcoin/issues/12314">Bitcoin Core Issue 1234 - discussion of {@code bcrt} HRP</a> for details. */ public enum SegwitHrp { BC(MAINNET), TB(TESTNET, SIGNET), BCRT(REGTEST); private final EnumSet<BitcoinNetwork> networks; SegwitHrp(BitcoinNetwork n) { networks = EnumSet.of(n); } SegwitHrp(BitcoinNetwork n1, BitcoinNetwork n2) { networks = EnumSet.of(n1, n2); } /** * Get the HRP in lowercase. To get uppercase, use {@link SegwitHrp#name()} * @return HRP in lowercase. */ public String toString() { return name().toLowerCase(); } /** * @param hrp uppercase or lowercase HRP * @return the corresponding enum * @throws IllegalArgumentException if unknown string */ public static SegwitHrp of(String hrp) { return SegwitHrp.valueOf(hrp.toUpperCase()); } /** * @param hrp uppercase or lowercase HRP * @return Optional containing the corresponding enum or empty if not found */ public static Optional<SegwitHrp> find(String hrp) { try { return Optional.of(SegwitHrp.of(hrp)); } catch(IllegalArgumentException iae) { return Optional.empty(); } } /** * @param network network enum * @return the corresponding enum */ public static SegwitHrp ofNetwork(BitcoinNetwork network) { return Stream.of(SegwitHrp.values()) .filter(hrp -> hrp.networks.contains(network)) .findFirst() .orElseThrow(IllegalStateException::new); } } protected final Network network; protected final short witnessVersion; protected final byte[] witnessProgram; // In 8-bits per byte format private static Network normalizeNetwork(Network network) { // SegwitAddress does not distinguish between the SIGNET and TESTNET, normalize to TESTNET if (network instanceof BitcoinNetwork) { BitcoinNetwork bitcoinNetwork = (BitcoinNetwork) network; if (bitcoinNetwork == BitcoinNetwork.SIGNET) { return BitcoinNetwork.TESTNET; } } return network; } private static byte[] encode8to5(byte[] data) { return convertBits(data, 0, data.length, 8, 5, true); } private static byte[] decode5to8(byte[] data) { return convertBits(data, 0, data.length, 5, 8, false); } /** * Private constructor. Use {@link #fromBech32(String, Network)}, * {@link #fromHash(Network, byte[])} or {@link ECKey#toAddress(ScriptType, Network)}. * * @param network * network this address is valid for * @param witnessVersion * version number between 0 and 16 * @param witnessProgram * hash of pubkey, pubkey or script (depending on version) (8-bits per byte) * @throws AddressFormatException * if any of the sanity checks fail */ private SegwitAddress(Network network, int witnessVersion, byte[] witnessProgram) throws AddressFormatException { if (witnessVersion < 0 || witnessVersion > 16) throw new AddressFormatException("Invalid script version: " + witnessVersion); if (witnessProgram.length < WITNESS_PROGRAM_MIN_LENGTH || witnessProgram.length > WITNESS_PROGRAM_MAX_LENGTH) throw new AddressFormatException.InvalidDataLength("Invalid length: " + witnessProgram.length); // Check script length for version 0: // BIP 141: // "If the version byte is 0, but the witness program is neither 20 nor 32 bytes, the script must fail." // In other words: coins sent to addresses with other lengths will become unspendable. if (witnessVersion == 0 && witnessProgram.length != WITNESS_PROGRAM_LENGTH_PKH && witnessProgram.length != WITNESS_PROGRAM_LENGTH_SH) throw new AddressFormatException.InvalidDataLength( "Invalid length for address version 0: " + witnessProgram.length); // Check script length for version 1: // BIP 341: // "A Taproot output is a native SegWit output (see BIP141) with version number 1, and a 32-byte // witness program. Any other outputs, including version 1 outputs with lengths other than 32 bytes, // or P2SH-wrapped version 1 outputs, remain unencumbered." // In other words: other lengths are not valid Taproot scripts but coins sent there won't be // unspendable, quite the contrary, they will be anyone-can-spend. (Not that easy spendable, because still // not-standard outputs and therefore not relayed, but a willing miner could easily spend them.) // Rationale for still restricting length here: creating anyone-can-spend Taproot addresses is probably // not that what callers expect. if (witnessVersion == 1 && witnessProgram.length != WITNESS_PROGRAM_LENGTH_TR) throw new AddressFormatException.InvalidDataLength( "Invalid length for address version 1: " + witnessProgram.length); this.network = normalizeNetwork(Objects.requireNonNull(network)); this.witnessVersion = (short) witnessVersion; this.witnessProgram = Objects.requireNonNull(witnessProgram); } /** * Returns the witness version in decoded form. Only versions 0 and 1 are in use right now. * * @return witness version, between 0 and 16 */ public int getWitnessVersion() { return witnessVersion; } /** * Returns the witness program in decoded form. * * @return witness program */ public byte[] getWitnessProgram() { // no version byte return witnessProgram; } @Override public byte[] getHash() { return getWitnessProgram(); } /** * Get the type of output script that will be used for sending to the address. This is either * {@link ScriptType#P2WPKH} or {@link ScriptType#P2WSH}. * * @return type of output script */ @Override public ScriptType getOutputScriptType() { int version = getWitnessVersion(); if (version == 0) { int programLength = getWitnessProgram().length; if (programLength == WITNESS_PROGRAM_LENGTH_PKH) return ScriptType.P2WPKH; if (programLength == WITNESS_PROGRAM_LENGTH_SH) return ScriptType.P2WSH; throw new IllegalStateException(); // cannot happen } else if (version == 1) { int programLength = getWitnessProgram().length; if (programLength == WITNESS_PROGRAM_LENGTH_TR) return ScriptType.P2TR; throw new IllegalStateException(); // cannot happen } throw new IllegalStateException("cannot handle: " + version); } @Override public String toString() { return toBech32(); } /** * Construct a {@link SegwitAddress} from its textual form. * * @param params * expected network this address is valid for, or null if the network should be derived from the bech32 * @param bech32 * bech32-encoded textual form of the address * @return constructed address * @throws AddressFormatException * if something about the given bech32 address isn't right * @deprecated Use {@link AddressParser#parseAddress(String, Network)} or {@link AddressParser#parseAddressAnyNetwork(String)} */ @Deprecated public static SegwitAddress fromBech32(@Nullable NetworkParameters params, String bech32) throws AddressFormatException { AddressParser parser = DefaultAddressParser.fromNetworks(); return (SegwitAddress) (params != null ? parser.parseAddress(bech32, params.network()) : parser.parseAddressAnyNetwork(bech32) ); } /** * Construct a {@link SegwitAddress} from its textual form. * * @param bech32 bech32-encoded textual form of the address * @param network expected network this address is valid for * @return constructed address * @throws AddressFormatException if something about the given bech32 address isn't right */ public static SegwitAddress fromBech32(String bech32, @Nonnull Network network) throws AddressFormatException { Bech32.Bech32Data bechData = Bech32.decode(bech32); if (bechData.hrp.equals(network.segwitAddressHrp())) return fromBechData(network, bechData); throw new AddressFormatException.WrongNetwork(bechData.hrp); } private static SegwitAddress fromBechData(Network network, Bech32.Bech32Data bechData) { if (bechData.data.length < 1) { throw new AddressFormatException.InvalidDataLength("invalid address length (0)"); } final int witnessVersion = bechData.data[0]; byte[] witnessProgram = decode5to8(trimVersion(bechData.data)); final SegwitAddress address = new SegwitAddress(network, witnessVersion, witnessProgram); if ((witnessVersion == 0 && bechData.encoding != Bech32.Encoding.BECH32) || (witnessVersion != 0 && bechData.encoding != Bech32.Encoding.BECH32M)) throw new AddressFormatException.UnexpectedWitnessVersion("Unexpected witness version: " + witnessVersion); return address; } /** * Construct a {@link SegwitAddress} that represents the given hash, which is either a pubkey hash or a script hash. * The resulting address will be either a P2WPKH or a P2WSH type of address. * * @param params * network this address is valid for * @param hash * 20-byte pubkey hash or 32-byte script hash * @return constructed address * @deprecated Use {@link #fromHash(Network, byte[])} */ @Deprecated public static SegwitAddress fromHash(NetworkParameters params, byte[] hash) { return fromHash(params.network(), hash); } /** * Construct a {@link SegwitAddress} that represents the given hash, which is either a pubkey hash or a script hash. * The resulting address will be either a P2WPKH or a P2WSH type of address. * * @param network network this address is valid for * @param hash 20-byte pubkey hash or 32-byte script hash * @return constructed address */ public static SegwitAddress fromHash(Network network, byte[] hash) { return new SegwitAddress(network, 0, hash); } /** * Construct a {@link SegwitAddress} that represents the given program, which is either a pubkey, a pubkey hash * or a script hash – depending on the script version. The resulting address will be either a P2WPKH, a P2WSH or * a P2TR type of address. * * @param params * network this address is valid for * @param witnessVersion * version number between 0 and 16 * @param witnessProgram * version dependent witness program * @return constructed address * @deprecated Use {@link #fromProgram(Network, int, byte[])} */ @Deprecated public static SegwitAddress fromProgram(NetworkParameters params, int witnessVersion, byte[] witnessProgram) { return fromProgram(params.network(), witnessVersion, witnessProgram); } /** * Construct a {@link SegwitAddress} that represents the given program, which is either a pubkey, a pubkey hash * or a script hash – depending on the script version. The resulting address will be either a P2WPKH, a P2WSH or * a P2TR type of address. * * @param network network this address is valid for * @param witnessVersion version number between 0 and 16 * @param witnessProgram version dependent witness program * @return constructed address */ public static SegwitAddress fromProgram(Network network, int witnessVersion, byte[] witnessProgram) { return new SegwitAddress(network, witnessVersion, witnessProgram); } /** * Construct a {@link SegwitAddress} that represents the public part of the given {@link ECKey}. Note that an * address is derived from a hash of the public key and is not the public key itself. * * @param params * network this address is valid for * @param key * only the public part is used * @return constructed address * @deprecated Use {@link ECKey#toAddress(ScriptType, org.bitcoinj.base.Network)} */ @Deprecated public static SegwitAddress fromKey(NetworkParameters params, ECKey key) { return (SegwitAddress) key.toAddress(ScriptType.P2WPKH, params.network()); } /** * Get the network this address works on. Use of {@link BitcoinNetwork} is preferred to use of {@link NetworkParameters} * when you need to know what network an address is for. * @return the Network. */ @Override public Network network() { return network; } @Override public int hashCode() { return Objects.hash(network, witnessVersion, Arrays.hashCode(witnessProgram)); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; SegwitAddress other = (SegwitAddress) o; return this.network == other.network && witnessVersion == other.witnessVersion && Arrays.equals(this.witnessProgram, other.witnessProgram); } /** * Returns the textual form of the address. * * @return textual form encoded in bech32 */ public String toBech32() { Bech32.Encoding encoding = (witnessVersion == 0) ? Bech32.Encoding.BECH32 : Bech32.Encoding.BECH32M; return Bech32.encode(encoding, network.segwitAddressHrp(), appendVersion(witnessVersion, encode8to5(witnessProgram))); } // Trim the version byte and return the witness program only private static byte[] trimVersion(byte[] data) { byte[] program = new byte[data.length - 1]; System.arraycopy(data, 1, program, 0, program.length); return program; } // concatenate the witnessVersion and witnessProgram private static byte[] appendVersion(short version, byte[] program) { byte[] data = new byte[program.length + 1]; data[0] = (byte) version; System.arraycopy(program, 0, data, 1, program.length); return data; } /** * Helper for re-arranging bits into groups. */ private static byte[] convertBits(final byte[] in, final int inStart, final int inLen, final int fromBits, final int toBits, final boolean pad) throws AddressFormatException { int acc = 0; int bits = 0; ByteArrayOutputStream out = new ByteArrayOutputStream(64); final int maxv = (1 << toBits) - 1; final int max_acc = (1 << (fromBits + toBits - 1)) - 1; for (int i = 0; i < inLen; i++) { int value = in[i + inStart] & 0xff; if ((value >>> fromBits) != 0) { throw new AddressFormatException( String.format("Input value '%X' exceeds '%d' bit size", value, fromBits)); } acc = ((acc << fromBits) | value) & max_acc; bits += fromBits; while (bits >= toBits) { bits -= toBits; out.write((acc >>> bits) & maxv); } } if (pad) { if (bits > 0) out.write((acc << (toBits - bits)) & maxv); } else if (bits >= fromBits || ((acc << (toBits - bits)) & maxv) != 0) { throw new AddressFormatException("Could not convert bits, invalid padding"); } return out.toByteArray(); } // Comparator for SegwitAddress, left argument must be SegwitAddress, right argument can be any Address private static final Comparator<Address> SEGWIT_ADDRESS_COMPARATOR = Address.PARTIAL_ADDRESS_COMPARATOR .thenComparing(a -> ((SegwitAddress) a).witnessVersion) .thenComparing(a -> ((SegwitAddress) a).witnessProgram, ByteUtils.arrayUnsignedComparator()); // Then compare Segwit bytes /** * {@inheritDoc} * * @param o other {@code Address} object * @return comparison result */ @Override public int compareTo(Address o) { return SEGWIT_ADDRESS_COMPARATOR.compare(this, o); } }
19,444
40.460554
179
java
bitcoinj
bitcoinj-master/core/src/main/java/org/bitcoinj/base/Sha256Hash.java
/* * Copyright 2011 Google Inc. * Copyright 2014 Andreas Schildbach * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.bitcoinj.base; import org.bitcoinj.base.internal.ByteUtils; import java.io.File; import java.io.IOException; import java.math.BigInteger; import java.nio.BufferOverflowException; import java.nio.BufferUnderflowException; import java.nio.ByteBuffer; import java.nio.file.Files; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.Arrays; import static org.bitcoinj.base.internal.Preconditions.checkArgument; /** * A {@code Sha256Hash} wraps a {@code byte[]} so that {@link #equals} and {@link #hashCode} work correctly, allowing it to be used as a key in a * map. It also checks that the {@code length} is correct (equal to {@link #LENGTH}) and provides a bit more type safety. * <p> * Given that {@code Sha256Hash} instances can be created using {@link #wrapReversed(byte[])} or {@link #twiceOf(byte[])} or by wrapping raw bytes, there is no guarantee that if two {@code Sha256Hash} instances are found equal (via {@link #equals(Object)}) that their preimages would be the same (even in the absence of a hash collision.) */ public class Sha256Hash implements Comparable<Sha256Hash> { public static final int LENGTH = 32; // bytes public static final Sha256Hash ZERO_HASH = wrap(new byte[LENGTH]); private final byte[] bytes; private Sha256Hash(byte[] rawHashBytes) { checkArgument(rawHashBytes.length == LENGTH, () -> "length must be " + LENGTH + ": " + rawHashBytes.length); this.bytes = rawHashBytes; } /** * Creates a new instance that wraps the given hash value. * * @param rawHashBytes the raw hash bytes to wrap * @return a new instance * @throws IllegalArgumentException if the given array length is not exactly 32 */ public static Sha256Hash wrap(byte[] rawHashBytes) { return new Sha256Hash(rawHashBytes); } /** * Creates a new instance that wraps the given hash value (represented as a hex string). * * @param hexString a hash value represented as a hex string * @return a new instance * @throws IllegalArgumentException if the given string is not a valid * hex string, or if it does not represent exactly 32 bytes */ public static Sha256Hash wrap(String hexString) { return wrap(ByteUtils.parseHex(hexString)); } /** * Creates a new instance that wraps the given hash value, but with byte order reversed. * * @param rawHashBytes the raw hash bytes to wrap * @return a new instance * @throws IllegalArgumentException if the given array length is not exactly 32 */ public static Sha256Hash wrapReversed(byte[] rawHashBytes) { return wrap(ByteUtils.reverseBytes(rawHashBytes)); } /** * Create a new instance by reading from the given buffer. * * @param buf buffer to read from * @return a new instance * @throws BufferUnderflowException if the read hash extends beyond the remaining bytes of the buffer */ public static Sha256Hash read(ByteBuffer buf) throws BufferUnderflowException { byte[] b = new byte[32]; buf.get(b); // we have to flip it around, as on the wire it's in little endian return Sha256Hash.wrapReversed(b); } /** * Creates a new instance containing the calculated (one-time) hash of the given bytes. * * @param contents the bytes on which the hash value is calculated * @return a new instance containing the calculated (one-time) hash */ public static Sha256Hash of(byte[] contents) { return wrap(hash(contents)); } /** * Creates a new instance containing the hash of the calculated hash of the given bytes. * * @param contents the bytes on which the hash value is calculated * @return a new instance containing the calculated (two-time) hash */ public static Sha256Hash twiceOf(byte[] contents) { return wrap(hashTwice(contents)); } /** * Creates a new instance containing the hash of the calculated hash of the given bytes. * * @param content1 first bytes on which the hash value is calculated * @param content2 second bytes on which the hash value is calculated * @return a new instance containing the calculated (two-time) hash */ public static Sha256Hash twiceOf(byte[] content1, byte[] content2) { return wrap(hashTwice(content1, content2)); } /** * Creates a new instance containing the calculated (one-time) hash of the given file's contents. * * The file contents are read fully into memory, so this method should only be used with small files. * * @param file the file on which the hash value is calculated * @return a new instance containing the calculated (one-time) hash * @throws IOException if an error occurs while reading the file */ public static Sha256Hash of(File file) throws IOException { return of(Files.readAllBytes(file.toPath())); } /** * Returns a new SHA-256 MessageDigest instance. * * This is a convenience method which wraps the checked * exception that can never occur with a RuntimeException. * * @return a new SHA-256 MessageDigest instance */ public static MessageDigest newDigest() { try { return MessageDigest.getInstance("SHA-256"); } catch (NoSuchAlgorithmException e) { throw new RuntimeException(e); // Can't happen. } } /** * Calculates the SHA-256 hash of the given bytes. * * @param input the bytes to hash * @return the hash (in big-endian order) */ public static byte[] hash(byte[] input) { return hash(input, 0, input.length); } /** * Calculates the SHA-256 hash of the given byte range. * * @param input the array containing the bytes to hash * @param offset the offset within the array of the bytes to hash * @param length the number of bytes to hash * @return the hash (in big-endian order) */ public static byte[] hash(byte[] input, int offset, int length) { MessageDigest digest = newDigest(); digest.update(input, offset, length); return digest.digest(); } /** * Calculates the SHA-256 hash of the given bytes, * and then hashes the resulting hash again. * * @param input the bytes to hash * @return the double-hash (in big-endian order) */ public static byte[] hashTwice(byte[] input) { return hashTwice(input, 0, input.length); } /** * Calculates the hash of hash on the given chunks of bytes. This is equivalent to concatenating the two * chunks and then passing the result to {@link #hashTwice(byte[])}. */ public static byte[] hashTwice(byte[] input1, byte[] input2) { MessageDigest digest = newDigest(); digest.update(input1); digest.update(input2); return digest.digest(digest.digest()); } /** * Calculates the SHA-256 hash of the given byte range, * and then hashes the resulting hash again. * * @param input the array containing the bytes to hash * @param offset the offset within the array of the bytes to hash * @param length the number of bytes to hash * @return the double-hash (in big-endian order) */ public static byte[] hashTwice(byte[] input, int offset, int length) { MessageDigest digest = newDigest(); digest.update(input, offset, length); return digest.digest(digest.digest()); } /** * Calculates the hash of hash on the given byte ranges. This is equivalent to * concatenating the two ranges and then passing the result to {@link #hashTwice(byte[])}. */ public static byte[] hashTwice(byte[] input1, int offset1, int length1, byte[] input2, int offset2, int length2) { MessageDigest digest = newDigest(); digest.update(input1, offset1, length1); digest.update(input2, offset2, length2); return digest.digest(digest.digest()); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; return Arrays.equals(bytes, ((Sha256Hash)o).bytes); } /** * Returns the last four bytes of the wrapped hash. This should be unique enough to be a suitable hash code even for * blocks, where the goal is to try and get the first bytes to be zeros (i.e. the value as a big integer lower * than the target value). */ @Override public int hashCode() { // use the last 4 bytes, not the first 4 which are often zeros in Bitcoin return ByteBuffer.wrap(bytes).getInt(LENGTH - Integer.BYTES); } @Override public String toString() { return ByteUtils.formatHex(bytes); } /** * Returns the bytes interpreted as a positive integer. */ public BigInteger toBigInteger() { return ByteUtils.bytesToBigInteger(bytes); } /** * Returns the internal byte array, without defensively copying. Therefore do NOT modify the returned array. */ public byte[] getBytes() { return bytes; } /** * Allocates a byte array and writes the hash into it, in reversed order. * * @return byte array containing the hash */ public byte[] serialize() { return ByteUtils.reverseBytes(bytes); } /** * Write hash into the given buffer. * * @param buf buffer to write into * @return the buffer * @throws BufferOverflowException if the hash doesn't fit the remaining buffer */ public ByteBuffer write(ByteBuffer buf) throws BufferOverflowException { // we have to flip it around, as on the wire it's in little endian buf.put(serialize()); return buf; } @Override public int compareTo(final Sha256Hash other) { for (int i = LENGTH - 1; i >= 0; i--) { final int thisByte = this.bytes[i] & 0xff; final int otherByte = other.bytes[i] & 0xff; if (thisByte > otherByte) return 1; if (thisByte < otherByte) return -1; } return 0; } }
11,036
35.068627
338
java
bitcoinj
bitcoinj-master/core/src/main/java/org/bitcoinj/base/Monetary.java
/* * Copyright 2014 Andreas Schildbach * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.bitcoinj.base; /** * Classes implementing this interface represent a monetary value, such as a Bitcoin or fiat amount. */ public interface Monetary { /** * Returns the absolute value of exponent of the value of a "smallest unit" in scientific notation. For Bitcoin, a * satoshi is worth 1E-8 so this would be 8. */ int smallestUnitExponent(); /** * Returns the number of "smallest units" of this monetary value. For Bitcoin, this would be the number of satoshis. */ long getValue(); int signum(); }
1,164
30.486486
120
java
bitcoinj
bitcoinj-master/core/src/main/java/org/bitcoinj/base/Address.java
/* * Copyright by the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.bitcoinj.base; import org.bitcoinj.base.exceptions.AddressFormatException; import org.bitcoinj.crypto.ECKey; import org.bitcoinj.core.NetworkParameters; import javax.annotation.Nullable; import java.util.Comparator; /** * Interface for addresses, e.g. native segwit addresses ({@link SegwitAddress}) or legacy addresses ({@link LegacyAddress}). * <p> * Use an implementation of {@link AddressParser#parseAddress(String, Network)} to conveniently construct any kind of address from its textual * form. */ public interface Address extends Comparable<Address> { /** * Construct an address from its textual form. * * @param params the expected network this address is valid for, or null if the network should be derived from the * textual form * @param str the textual form of the address, such as "17kzeh4N8g49GFvdDzSf8PjaPfyoD1MndL" or * "bc1qw508d6qejxtdg4y5r3zarvary0c5xw7kv8f3t4" * @return constructed address * @throws AddressFormatException * if the given string doesn't parse or the checksum is invalid * @throws AddressFormatException.WrongNetwork * if the given string is valid but not for the expected network (eg testnet vs mainnet) * @deprecated Use {@link org.bitcoinj.wallet.Wallet#parseAddress(String)} or {@link AddressParser#parseAddress(String, Network)} */ @Deprecated static Address fromString(@Nullable NetworkParameters params, String str) throws AddressFormatException { AddressParser addressParser = DefaultAddressParser.fromNetworks(); return (params != null) ? addressParser.parseAddress(str, params.network()) : addressParser.parseAddressAnyNetwork(str); } /** * Construct an {@link Address} that represents the public part of the given {@link ECKey}. * * @param params * network this address is valid for * @param key * only the public part is used * @param outputScriptType * script type the address should use * @return constructed address * @deprecated Use {@link ECKey#toAddress(ScriptType, Network)} */ @Deprecated static Address fromKey(final NetworkParameters params, final ECKey key, final ScriptType outputScriptType) { return key.toAddress(outputScriptType, params.network()); } /** * @return network this data is valid for * @deprecated Use {@link #network()} */ @Deprecated default NetworkParameters getParameters() { return NetworkParameters.of(network()); } /** * Get either the public key hash or script hash that is encoded in the address. * * @return hash that is encoded in the address */ byte[] getHash(); /** * Get the type of output script that will be used for sending to the address. * * @return type of output script */ ScriptType getOutputScriptType(); /** * Comparison field order for addresses is: * <ol> * <li>{@link Network#id()}</li> * <li>Legacy vs. Segwit</li> * <li>(Legacy only) Version byte</li> * <li>remaining {@code bytes}</li> * </ol> * <p> * Implementations use {@link Address#PARTIAL_ADDRESS_COMPARATOR} for tests 1 and 2. * * @param o other {@code Address} object * @return comparison result */ @Override int compareTo(Address o); /** * Get the network this address works on. Use of {@link BitcoinNetwork} is preferred to use of {@link NetworkParameters} * when you need to know what network an address is for. * @return the Network. */ Network network(); /** * Comparator for the first two comparison fields in {@code Address} comparisons, see {@link Address#compareTo(Address)}. * Used by {@link LegacyAddress#compareTo(Address)} and {@link SegwitAddress#compareTo(Address)}. * For use by implementing classes only. */ Comparator<Address> PARTIAL_ADDRESS_COMPARATOR = Comparator .comparing((Address a) -> a.network().id()) // First compare network .thenComparing(Address::compareTypes); // Then compare address type (subclass) /* private */ static int compareTypes(Address a, Address b) { if (a instanceof LegacyAddress && b instanceof SegwitAddress) { return -1; // Legacy addresses (starting with 1 or 3) come before Segwit addresses. } else if (a instanceof SegwitAddress && b instanceof LegacyAddress) { return 1; } else { return 0; // Both are the same type: additional `thenComparing()` lambda(s) for that type must finish the comparison } } }
5,422
37.735714
142
java
bitcoinj
bitcoinj-master/core/src/main/java/org/bitcoinj/base/ScriptType.java
/* * Copyright by the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.bitcoinj.base; import java.util.Arrays; import java.util.Optional; /** * Supported Bitcoin script types and their <i>script identifier strings</i>. The <i>script identifier string</i> for a {@code ScriptType} * is the "human-readable identifier string" of a <i>Script Expression</i> as defined in * <a href="https://github.com/bitcoin/bips/blob/master/bip-0380.mediawiki">BIP 380</a>. * Only the subset of identifier strings defined in * <a href="https://github.com/bitcoin/bips/blob/master/bip-0381.mediawiki">BIP 381</a> and * <a href="https://github.com/bitcoin/bips/blob/master/bip-0382.mediawiki">BIP 382</a> map to valid {@code ScriptType} instances. * @see <a href="https://github.com/bitcoin/bips/blob/master/bip-0380.mediawiki">BIP 380: Output Script Descriptors General Operation</a> * @see <a href="https://github.com/bitcoin/bips/blob/master/bip-0381.mediawiki">BIP 381: Non-Segwit Output Script Descriptors</a> * @see <a href="https://github.com/bitcoin/bips/blob/master/bip-0382.mediawiki">BIP 382: Segwit Output Script Descriptors</a> */ public enum ScriptType { P2PKH("pkh", 1), // pay to pubkey hash (aka pay to address) P2PK("pk", 2), // pay to pubkey P2SH("sh", 3), // pay to script hash P2WPKH("wpkh", 4), // pay to witness pubkey hash P2WSH("wsh", 5), // pay to witness script hash P2TR("tr", 6); // pay to taproot private final String scriptIdentifierString; /** * @deprecated Use {@link #numericId()} or better yet use {@link #id()} to get a script identifier string */ @Deprecated public final int id; /** * @param id script identifier string * @param numericId numeric id for (temporary?) backward-compatibility */ ScriptType(String id, int numericId) { this.scriptIdentifierString = id; this.id = numericId; } /** * Use this method to create a {@code ScriptType} from a known good <i>script identifier string</i>. * @param id A script identifier string * @return the script type * @throws IllegalArgumentException if unknown/invalid script identifier string */ public static ScriptType of(String id) { return find(id) .orElseThrow(() -> new IllegalArgumentException("Unknown ScriptType ID")); } /** * Use this method to create a {@code ScriptType} from a <i>script identifier string</i> that should be * validated. * @param id A script identifier string * @return A {@code ScriptType}-containing {@code Optional} or {@link Optional#empty()} */ public static Optional<ScriptType> find(String id) { return Arrays.stream(values()) .filter(v -> v.id().equals(id)) .findFirst(); } /** * Return the <i>script identifier string</i> for this {@code ScriptType}. * <p> * Be careful: the {@link #id()} method returns a different type and value than what is in the {@code deprecated} {@link #id} field. * @return A <i>script identifier string</i> */ public String id() { return scriptIdentifierString; } /** * This is deprecated. But less deprecated than accessing the {@link #id} field directly. * @return A numeric ID * @deprecated Using {@link #id()} to get a script identifier string is preferred. */ @Deprecated public int numericId() { return id; } }
4,058
39.188119
138
java
bitcoinj
bitcoinj-master/core/src/main/java/org/bitcoinj/base/VarInt.java
/* * Copyright 2011 Google Inc. * Copyright 2021 Andreas Schildbach * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.bitcoinj.base; import java.nio.BufferOverflowException; import java.nio.BufferUnderflowException; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.util.Objects; import static org.bitcoinj.base.internal.Preconditions.check; /** * A variable-length encoded unsigned integer using Satoshi's encoding (a.k.a. "CompactSize"). */ public class VarInt { private final long value; private final int originallyEncodedSize; private static final int SIZE_BYTE = Byte.BYTES; // 1 data byte private static final int SIZE_SHORT = Byte.BYTES + Short.BYTES; // 1 marker + 2 data bytes private static final int SIZE_INT = Byte.BYTES + Integer.BYTES; // 1 marker + 4 data bytes private static final int SIZE_LONG = Byte.BYTES + Long.BYTES; // 1 marker + 8 data bytes /** * Constructs a new VarInt with the given unsigned long value. * * @param value the unsigned long value (beware widening conversion of negatives!) */ public static VarInt of(long value) { return new VarInt(value, sizeOf(value)); } /** * Constructs a new VarInt with the value parsed from the specified offset of the given buffer. * * @param buf the buffer containing the value * @param offset the offset of the value * @throws ArrayIndexOutOfBoundsException if offset points outside of the buffer, or * if the value doesn't fit the remaining buffer */ public static VarInt ofBytes(byte[] buf, int offset) throws ArrayIndexOutOfBoundsException { check(offset >= 0 && offset < buf.length, () -> new ArrayIndexOutOfBoundsException(offset)); return read(ByteBuffer.wrap(buf, offset, buf.length - offset)); } /** * Constructs a new VarInt by reading from the given buffer. * * @param buf buffer to read from * @throws BufferUnderflowException if the read value extends beyond the remaining bytes of the buffer */ public static VarInt read(ByteBuffer buf) throws BufferUnderflowException { buf.order(ByteOrder.LITTLE_ENDIAN); int first = Byte.toUnsignedInt(buf.get()); long value; int originallyEncodedSize; if (first < 253) { value = first; originallyEncodedSize = SIZE_BYTE; } else if (first == 253) { value = Short.toUnsignedInt(buf.getShort()); originallyEncodedSize = SIZE_SHORT; } else if (first == 254) { value = Integer.toUnsignedLong(buf.getInt()); originallyEncodedSize = SIZE_INT; } else { value = buf.getLong(); originallyEncodedSize = SIZE_LONG; } return new VarInt(value, originallyEncodedSize); } private VarInt(long value, int originallyEncodedSize) { this.value = value; this.originallyEncodedSize = originallyEncodedSize; } /** @deprecated use {@link #of(long)} */ @Deprecated public VarInt(long value) { this.value = value; originallyEncodedSize = getSizeInBytes(); } /** @deprecated use {@link #ofBytes(byte[], int)} */ @Deprecated public VarInt(byte[] buf, int offset) { VarInt copy = read(ByteBuffer.wrap(buf, offset, buf.length)); value = copy.value; originallyEncodedSize = copy.originallyEncodedSize; } /** * Gets the value as a long. For values greater than {@link Long#MAX_VALUE} the returned long * will be negative. It is still to be interpreted as an unsigned value. * * @return value as a long */ public long longValue() { return value; } /** * Determine if the value would fit an int, i.e. it is in the range of {@code 0} to {@link Integer#MAX_VALUE}. * If this is true, it's safe to call {@link #intValue()}. * * @return true if the value fits an int, false otherwise */ public boolean fitsInt() { return value >= 0 && value <= Integer.MAX_VALUE; } /** * Gets the value as an unsigned int in the range of {@code 0} to {@link Integer#MAX_VALUE}. * * @return value as an unsigned int * @throws ArithmeticException if the value doesn't fit an int */ public int intValue() throws ArithmeticException { check(fitsInt(), () -> new ArithmeticException("value too large for an int: " + Long.toUnsignedString(value))); return (int) value; } /** * Returns the original number of bytes used to encode the value if it was * deserialized from a byte array, or the minimum encoded size if it was not. */ public int getOriginalSizeInBytes() { return originallyEncodedSize; } /** * Returns the minimum encoded size of the value. */ public final int getSizeInBytes() { return sizeOf(value); } /** * Returns the minimum encoded size of the given unsigned long value. * * @param value the unsigned long value (beware widening conversion of negatives!) */ public static int sizeOf(long value) { // if negative, it's actually a very large unsigned long value if (value < 0) return SIZE_LONG; if (value < 253) return SIZE_BYTE; if (value <= 0xFFFFL) return SIZE_SHORT; if (value <= 0xFFFFFFFFL) return SIZE_INT; return SIZE_LONG; } /** * Allocates a byte array and serializes the value into its minimal representation. * * @return the minimal encoded bytes of the value */ public byte[] serialize() { ByteBuffer buf = ByteBuffer.allocate(sizeOf(value)); return write(buf).array(); } /** * Write encoded value into the given buffer. * * @param buf buffer to write into * @return the buffer * @throws BufferOverflowException if the value doesn't fit the remaining buffer */ public ByteBuffer write(ByteBuffer buf) throws BufferOverflowException { buf.order(ByteOrder.LITTLE_ENDIAN); switch (sizeOf(value)) { case 1: buf.put((byte) value); break; case 3: buf.put((byte) 253); buf.putShort((short) value); break; case 5: buf.put((byte) 254); buf.putInt((int) value); break; default: buf.put((byte) 255); buf.putLong(value); break; } return buf; } @Override public String toString() { return Long.toUnsignedString(value); } @Override public boolean equals(Object o) { // originallyEncodedSize is not considered on purpose if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; return value == ((VarInt) o).value; } @Override public int hashCode() { return Objects.hash(value); } }
7,674
32.662281
114
java
bitcoinj
bitcoinj-master/core/src/main/java/org/bitcoinj/base/BitcoinNetwork.java
/* * Copyright by the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.bitcoinj.base; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Optional; import java.util.stream.Stream; import static org.bitcoinj.base.Coin.COIN; /** * A convenient {@code enum} representation of a Bitcoin network. * <p> * Note that the name of each {@code enum} constant is defined in <i>uppercase</i> as is the convention in Java. * However, the <q>canonical</q> representation in <b>bitcoinj</b> for user-facing display and input * of Bitcoin network names is <i>lowercase</i> (e.g. as a command-line parameter.) * Implementations should use the {@link #toString()} method for output and the {@link #fromString(String)} * method for input of network values. */ public enum BitcoinNetwork implements Network { /** The main Bitcoin network, known as {@code "mainnet"}, with {@code id} string {@code "org.bitcoin.production"} */ MAINNET("org.bitcoin.production", "main", "prod"), /** The Bitcoin test network, known as {@code "testnet"}, with {@code id} string {@code "org.bitcoin.test"} */ TESTNET("org.bitcoin.test", "test"), /** The Bitcoin signature-based test network, known as {@code "signet"}, with {@code id} string {@code "org.bitcoin.signet"} */ SIGNET("org.bitcoin.signet", "sig"), /** A local Bitcoin regression test network, known as {@code "regtest"}, with {@code id} string {@code "org.bitcoin.regtest"} */ REGTEST("org.bitcoin.regtest"); /** * Scheme part for Bitcoin URIs. */ public static final String BITCOIN_SCHEME = "bitcoin"; /** * The maximum number of coins to be generated */ private static final long MAX_COINS = 21_000_000; /** * The maximum money to be generated */ public static final Coin MAX_MONEY = COIN.multiply(MAX_COINS); /** The ID string for the main, production network where people trade things. */ public static final String ID_MAINNET = MAINNET.id(); /** The ID string for the testnet. */ public static final String ID_TESTNET = TESTNET.id(); /** The ID string for the signet. */ public static final String ID_SIGNET = SIGNET.id(); /** The ID string for regtest mode. */ public static final String ID_REGTEST = REGTEST.id(); private final String id; // All supported names for this BitcoinNetwork private final List<String> allNames; // Maps from names and alternateNames to BitcoinNetwork private static final Map<String, BitcoinNetwork> stringToEnum = mergedNameMap(); BitcoinNetwork(String networkId, String... alternateNames) { this.id = networkId; this.allNames = combine(this.toString(), alternateNames); } /** * Return the canonical, lowercase, user-facing {@code String} for an {@code enum}. * It is the lowercase value of {@link #name()} and can be displayed to the user, used * as a command-line parameter, etc. * <dl> * <dt>{@link #MAINNET}</dt> * <dd>{@code mainnet}</dd> * <dt>{@link #TESTNET}</dt> * <dd>{@code testnet}</dd> * <dt>{@link #SIGNET}</dt> * <dd>{@code signet}</dd> * <dt>{@link #REGTEST}</dt> * <dd>{@code regtest}</dd> * </dl> * @return canonical lowercase name for this Bitcoin network */ @Override public String toString() { return name().toLowerCase(Locale.ROOT); } /** * Return the network ID string as defined by (these were previously defined in {@code NetworkParameters}) * <dl> * <dt>{@link #MAINNET}</dt> * <dd>{@code org.bitcoin.production}</dd> * <dt>{@link #TESTNET}</dt> * <dd>{@code org.bitcoin.test}</dd> * <dt>{@link #SIGNET}</dt> * <dd>{@code org.bitcoin.signet}</dd> * <dt>{@link #REGTEST}</dt> * <dd>{@code org.bitcoin.regtest}</dd> * </dl> * * @return The network ID string */ @Override public String id() { return id; } /** * Header byte of base58 encoded legacy P2PKH addresses for this network. * @return header byte as an {@code int}. * @see LegacyAddress.AddressHeader */ public int legacyAddressHeader() { return LegacyAddress.AddressHeader.ofNetwork(this).headerByte(); } /** * Header byte of base58 encoded legacy P2SH addresses for this network. * @return header byte as an {@code int}. * @see LegacyAddress.P2SHHeader */ public int legacyP2SHHeader() { return LegacyAddress.P2SHHeader.ofNetwork(this).headerByte(); } /** * Return the standard Bech32 {@link org.bitcoinj.base.SegwitAddress.SegwitHrp} (as a {@code String}) for * this network. * @return The HRP as a (lowercase) string. */ public String segwitAddressHrp() { return SegwitAddress.SegwitHrp.ofNetwork(this).toString(); } /** * The URI scheme for Bitcoin. * @see <a href="https://github.com/bitcoin/bips/blob/master/bip-0021.mediawiki">BIP 0021</a> * @return string containing the URI scheme */ @Override public String uriScheme() { return BITCOIN_SCHEME; } @Override public boolean hasMaxMoney() { return true; } @Override public Coin maxMoney() { return MAX_MONEY; } @Override public boolean exceedsMaxMoney(Monetary amount) { if (amount instanceof Coin) { return ((Coin) amount).compareTo(MAX_MONEY) > 0; } else { throw new IllegalArgumentException("amount must be a Coin type"); } } /** * Find the {@code BitcoinNetwork} from a name string, e.g. "mainnet", "testnet" or "signet". * A number of common alternate names are allowed too, e.g. "main" or "prod". * @param nameString A name string * @return An {@code Optional} containing the matching enum or empty */ public static Optional<BitcoinNetwork> fromString(String nameString) { return Optional.ofNullable(stringToEnum.get(nameString)); } /** * Find the {@code BitcoinNetwork} from an ID String * @param idString specifies the network * @return An {@code Optional} containing the matching enum or empty */ public static Optional<BitcoinNetwork> fromIdString(String idString) { return Arrays.stream(values()) .filter(n -> n.id.equals(idString)) .findFirst(); } // Create a Map that maps name Strings to networks for all instances private static Map<String, BitcoinNetwork> mergedNameMap() { return Stream.of(values()) .collect(HashMap::new, // Supply HashMaps as mutable containers BitcoinNetwork::accumulateNames, // Accumulate one network into hashmap Map::putAll); // Combine two containers } // Add allNames for this Network as keys to a map that can be used to find it private static void accumulateNames(Map<String, BitcoinNetwork> map, BitcoinNetwork net) { net.allNames.forEach(name -> map.put(name, net)); } // Combine a String and an array of String and return as an unmodifiable list private static List<String> combine(String canonical, String[] alternateNames) { List<String> temp = new ArrayList<>(); temp.add(canonical); temp.addAll(Arrays.asList(alternateNames)); return Collections.unmodifiableList(temp); } }
8,251
35.513274
133
java
bitcoinj
bitcoinj-master/core/src/main/java/org/bitcoinj/base/exceptions/AddressFormatException.java
/* * Copyright 2011 Google Inc. * Copyright 2015 Andreas Schildbach * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.bitcoinj.base.exceptions; import org.bitcoinj.base.Base58; import org.bitcoinj.base.Bech32; @SuppressWarnings("serial") public class AddressFormatException extends IllegalArgumentException { public AddressFormatException() { super(); } public AddressFormatException(String message) { super(message); } /** * This exception is thrown by {@link Base58}, {@link Bech32} and the {@code EncodedPrivateKey} hierarchy of * classes when you try to decode data and a character isn't valid. You shouldn't allow the user to proceed in this * case. */ public static class InvalidCharacter extends AddressFormatException { public final char character; public final int position; public InvalidCharacter(char character, int position) { super("Invalid character '" + Character.toString(character) + "' at position " + position); this.character = character; this.position = position; } } /** * This exception is thrown by {@link Base58}, {@link Bech32} and the {@code EncodedPrivateKey} hierarchy of * classes when you try to decode data and the data isn't of the right size. You shouldn't allow the user to proceed * in this case. */ public static class InvalidDataLength extends AddressFormatException { public InvalidDataLength() { super(); } public InvalidDataLength(String message) { super(message); } } /** * This exception is thrown by {@link Base58}, {@link Bech32} and the {@code EncodedPrivateKey} hierarchy of * classes when you try to decode data and the checksum isn't valid. You shouldn't allow the user to proceed in this * case. */ public static class InvalidChecksum extends AddressFormatException { public InvalidChecksum() { super("Checksum does not validate"); } public InvalidChecksum(String message) { super(message); } } /** * This exception is thrown by {@code SegwitAddress} when you try to decode data and the witness version doesn't * match the Bech32 encoding as per BIP350. You shouldn't allow the user to proceed in this case. */ public static class UnexpectedWitnessVersion extends AddressFormatException { public UnexpectedWitnessVersion() { super("Unexpected witness version"); } public UnexpectedWitnessVersion(String message) { super(message); } } /** * This exception is thrown by the {@code EncodedPrivateKey} hierarchy of classes when you try and decode an * address or private key with an invalid prefix (version header or human-readable part). You shouldn't allow the * user to proceed in this case. */ public static class InvalidPrefix extends AddressFormatException { public InvalidPrefix() { super(); } public InvalidPrefix(String message) { super(message); } } /** * This exception is thrown by the {@code EncodedPrivateKey} hierarchy of classes when you try and decode an * address with a prefix (version header or human-readable part) that used by another network (usually: mainnet vs * testnet). You shouldn't allow the user to proceed in this case as they are trying to send money across different * chains, an operation that is guaranteed to destroy the money. */ public static class WrongNetwork extends InvalidPrefix { public WrongNetwork(int versionHeader) { super("Version code of address did not match acceptable versions for network: " + versionHeader); } public WrongNetwork(String hrp) { super("human-readable part of address did not match acceptable HRPs for network: " + hrp); } } }
4,557
35.758065
120
java
bitcoinj
bitcoinj-master/core/src/main/java/org/bitcoinj/base/utils/Fiat.java
/* * Copyright 2014 Andreas Schildbach * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.bitcoinj.base.utils; import org.bitcoinj.base.Coin; import org.bitcoinj.base.Monetary; import java.math.BigDecimal; import java.util.Objects; import static org.bitcoinj.base.internal.Preconditions.checkArgument; /** * Represents a monetary fiat value. It was decided to not fold this into {@link Coin} because of type * safety. Fiat values always come with an attached currency code. * * This class is immutable. */ public final class Fiat implements Monetary, Comparable<Fiat> { /** * The absolute value of exponent of the value of a "smallest unit" in scientific notation. We picked 4 rather than * 2, because in financial applications it's common to use sub-cent precision. */ public static final int SMALLEST_UNIT_EXPONENT = 4; /** * The number of smallest units of this monetary value. */ public final long value; public final String currencyCode; private Fiat(final String currencyCode, final long value) { this.value = value; this.currencyCode = currencyCode; } public static Fiat valueOf(final String currencyCode, final long value) { return new Fiat(currencyCode, value); } @Override public int smallestUnitExponent() { return SMALLEST_UNIT_EXPONENT; } /** * Returns the number of "smallest units" of this monetary value. */ @Override public long getValue() { return value; } public String getCurrencyCode() { return currencyCode; } /** * <p>Parses an amount expressed in the way humans are used to.</p> * <p>This takes string in a format understood by {@link BigDecimal#BigDecimal(String)}, for example "0", "1", "0.10", * "1.23E3", "1234.5E-5".</p> * * @throws IllegalArgumentException * if you try to specify more than 4 digits after the comma, or a value out of range. */ public static Fiat parseFiat(final String currencyCode, final String str) { try { long val = new BigDecimal(str).movePointRight(SMALLEST_UNIT_EXPONENT).longValueExact(); return Fiat.valueOf(currencyCode, val); } catch (ArithmeticException e) { throw new IllegalArgumentException(e); } } /** * <p>Parses an amount expressed in the way humans are used to. The amount is cut to 4 digits after the comma.</p> * <p>This takes string in a format understood by {@link BigDecimal#BigDecimal(String)}, for example "0", "1", "0.10", * "1.23E3", "1234.5E-5".</p> * * @throws IllegalArgumentException * if you try to specify a value out of range. */ public static Fiat parseFiatInexact(final String currencyCode, final String str) { try { long val = new BigDecimal(str).movePointRight(SMALLEST_UNIT_EXPONENT).longValue(); return Fiat.valueOf(currencyCode, val); } catch (ArithmeticException e) { throw new IllegalArgumentException(e); } } public Fiat add(final Fiat value) { checkArgument(value.currencyCode.equals(currencyCode), () -> "values to add must be of same currency: " + value.currencyCode + " vs " + currencyCode); return new Fiat(currencyCode, Math.addExact(this.value, value.value)); } public Fiat subtract(final Fiat value) { checkArgument(value.currencyCode.equals(currencyCode), () -> "values to substract must be of same currency: " + value.currencyCode + " vs " + currencyCode); return new Fiat(currencyCode, Math.subtractExact(this.value, value.value)); } public Fiat multiply(final long factor) { return new Fiat(currencyCode, Math.multiplyExact(this.value, factor)); } public Fiat divide(final long divisor) { return new Fiat(currencyCode, this.value / divisor); } public Fiat[] divideAndRemainder(final long divisor) { return new Fiat[] { new Fiat(currencyCode, this.value / divisor), new Fiat(currencyCode, this.value % divisor) }; } public long divide(final Fiat divisor) { checkArgument(divisor.currencyCode.equals(currencyCode), () -> "values to divide must be of same currency: " + divisor.currencyCode + " vs " + currencyCode); return this.value / divisor.value; } /** * Returns true if and only if this instance represents a monetary value greater than zero, otherwise false. */ public boolean isPositive() { return signum() == 1; } /** * Returns true if and only if this instance represents a monetary value less than zero, otherwise false. */ public boolean isNegative() { return signum() == -1; } /** * Returns true if and only if this instance represents zero monetary value, otherwise false. */ public boolean isZero() { return signum() == 0; } /** * Returns true if the monetary value represented by this instance is greater than that of the given other Fiat, * otherwise false. */ public boolean isGreaterThan(Fiat other) { return compareTo(other) > 0; } /** * Returns true if the monetary value represented by this instance is less than that of the given other Fiat, * otherwise false. */ public boolean isLessThan(Fiat other) { return compareTo(other) < 0; } @Override public int signum() { if (this.value == 0) return 0; return this.value < 0 ? -1 : 1; } public Fiat negate() { return new Fiat(currencyCode, -this.value); } /** * Returns the number of "smallest units" of this monetary value. It's deprecated in favour of accessing {@link #value} * directly. */ public long longValue() { return this.value; } private static final MonetaryFormat FRIENDLY_FORMAT = MonetaryFormat.FIAT.postfixCode(); /** * Returns the value as a 0.12 type string. More digits after the decimal place will be used if necessary, but two * will always be present. */ public String toFriendlyString() { return FRIENDLY_FORMAT.code(0, currencyCode).format(this).toString(); } private static final MonetaryFormat PLAIN_FORMAT = MonetaryFormat.FIAT.minDecimals(0).repeatOptionalDecimals(1, 4).noCode(); /** * <p> * Returns the value as a plain string. The result is unformatted with no trailing zeroes. For * instance, a value of 150000 "smallest units" gives an output string of "0.0015". * </p> */ public String toPlainString() { return PLAIN_FORMAT.format(this).toString(); } @Override public String toString() { return Long.toString(value); } @Override public boolean equals(final Object o) { if (o == this) return true; if (o == null || o.getClass() != getClass()) return false; final Fiat other = (Fiat) o; return this.value == other.value && this.currencyCode.equals(other.currencyCode); } @Override public int hashCode() { return Objects.hash(value, currencyCode); } @Override public int compareTo(final Fiat other) { if (!this.currencyCode.equals(other.currencyCode)) return this.currencyCode.compareTo(other.currencyCode); return Long.compare(this.value, other.value); } }
8,048
32.5375
128
java
bitcoinj
bitcoinj-master/core/src/main/java/org/bitcoinj/base/utils/MonetaryFormat.java
/* * Copyright 2014 Andreas Schildbach * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.bitcoinj.base.utils; import org.bitcoinj.base.Coin; import org.bitcoinj.base.Monetary; import java.math.BigDecimal; import java.math.RoundingMode; import java.text.DecimalFormatSymbols; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Locale; import java.util.Objects; import static org.bitcoinj.base.internal.Preconditions.checkArgument; import static org.bitcoinj.base.internal.Preconditions.checkState; /** * <p> * Utility for formatting and parsing coin values to and from human-readable form. * </p> * * <p> * MonetaryFormat instances are immutable. Invoking a configuration method has no effect on the receiving instance; you * must store and use the new instance it returns, instead. Instances are thread safe, so they may be stored safely as * static constants. * </p> */ public final class MonetaryFormat { /** Standard format for the BTC denomination. */ public static final MonetaryFormat BTC = new MonetaryFormat().shift(0).minDecimals(2).repeatOptionalDecimals(2, 3); /** Standard format for the mBTC denomination. */ public static final MonetaryFormat MBTC = new MonetaryFormat().shift(3).minDecimals(2).optionalDecimals(2); /** Standard format for the µBTC denomination. */ public static final MonetaryFormat UBTC = new MonetaryFormat().shift(6).minDecimals(0).optionalDecimals(2); /** Standard format for the satoshi denomination. */ public static final MonetaryFormat SAT = new MonetaryFormat().shift(8).minDecimals(0).optionalDecimals(0); /** Standard format for fiat amounts. */ public static final MonetaryFormat FIAT = new MonetaryFormat().shift(0).minDecimals(2).repeatOptionalDecimals(2, 1); /** Currency code for base 1 Bitcoin. */ public static final String CODE_BTC = "BTC"; /** Currency code for base 1/1000 Bitcoin. */ public static final String CODE_MBTC = "mBTC"; /** Currency code for base 1/1000000 Bitcoin. */ public static final String CODE_UBTC = "µBTC"; /** Currency code for base 1 satoshi. */ public static final String CODE_SAT = "sat"; /** Currency symbol for base 1 Bitcoin. */ public static final String SYMBOL_BTC = "\u20bf"; /** Currency symbol for base 1/1000 Bitcoin. */ public static final String SYMBOL_MBTC = "m" + SYMBOL_BTC; /** Currency symbol for base 1/1000000 Bitcoin. */ public static final String SYMBOL_UBTC = "µ" + SYMBOL_BTC; /** Currency symbol for base 1 satoshi. */ public static final String SYMBOL_SAT = "\u0219"; public static final int MAX_DECIMALS = 8; private final char negativeSign; private final char positiveSign; private final char zeroDigit; private final char decimalMark; private final int minDecimals; private final List<Integer> decimalGroups; private final int shift; private final RoundingMode roundingMode; private final String[] codes; private final char codeSeparator; private final boolean codePrefixed; private static final String DECIMALS_PADDING = "0000000000000000"; // a few more than necessary for Bitcoin /** * Set character to prefix negative values. */ public MonetaryFormat negativeSign(char negativeSign) { checkArgument(!Character.isDigit(negativeSign), () -> "negativeSign can't be digit: " + negativeSign); checkArgument(negativeSign > 0, () -> "negativeSign must be positive: " + negativeSign); if (negativeSign == this.negativeSign) return this; else return new MonetaryFormat(negativeSign, positiveSign, zeroDigit, decimalMark, minDecimals, decimalGroups, shift, roundingMode, codes, codeSeparator, codePrefixed); } /** * Set character to prefix positive values. A zero value means no sign is used in this case. For parsing, a missing * sign will always be interpreted as if the positive sign was used. */ public MonetaryFormat positiveSign(char positiveSign) { checkArgument(!Character.isDigit(positiveSign), () -> "positiveSign can't be digit: " + positiveSign); if (positiveSign == this.positiveSign) return this; else return new MonetaryFormat(negativeSign, positiveSign, zeroDigit, decimalMark, minDecimals, decimalGroups, shift, roundingMode, codes, codeSeparator, codePrefixed); } /** * Set character range to use for representing digits. It starts with the specified character representing zero. */ public MonetaryFormat digits(char zeroDigit) { if (zeroDigit == this.zeroDigit) return this; else return new MonetaryFormat(negativeSign, positiveSign, zeroDigit, decimalMark, minDecimals, decimalGroups, shift, roundingMode, codes, codeSeparator, codePrefixed); } /** * Set character to use as the decimal mark. If the formatted value does not have any decimals, no decimal mark is * used either. */ public MonetaryFormat decimalMark(char decimalMark) { checkArgument(!Character.isDigit(decimalMark), () -> "decimalMark can't be digit: " + decimalMark); checkArgument(decimalMark > 0, () -> "decimalMark must be positive: " + decimalMark); if (decimalMark == this.decimalMark) return this; else return new MonetaryFormat(negativeSign, positiveSign, zeroDigit, decimalMark, minDecimals, decimalGroups, shift, roundingMode, codes, codeSeparator, codePrefixed); } /** * Set minimum number of decimals to use for formatting. If the value precision exceeds all decimals specified * (including additional decimals specified by {@link #optionalDecimals(int...)} or * {@link #repeatOptionalDecimals(int, int)}), the value will be rounded. This configuration is not relevant for * parsing. */ public MonetaryFormat minDecimals(int minDecimals) { if (minDecimals == this.minDecimals) return this; else return new MonetaryFormat(negativeSign, positiveSign, zeroDigit, decimalMark, minDecimals, decimalGroups, shift, roundingMode, codes, codeSeparator, codePrefixed); } /** * <p> * Set additional groups of decimals to use after the minimum decimals, if they are useful for expressing precision. * Each value is a number of decimals in that group. If the value precision exceeds all decimals specified * (including minimum decimals), the value will be rounded. This configuration is not relevant for parsing. * </p> * * <p> * For example, if you pass {@code 4,2} it will add four decimals to your formatted string if needed, and then add * another two decimals if needed. At this point, rather than adding further decimals the value will be rounded. * </p> * * @param groups * any number numbers of decimals, one for each group */ public MonetaryFormat optionalDecimals(int... groups) { List<Integer> decimalGroups = new ArrayList<>(groups.length); for (int group : groups) decimalGroups.add(group); return new MonetaryFormat(negativeSign, positiveSign, zeroDigit, decimalMark, minDecimals, decimalGroups, shift, roundingMode, codes, codeSeparator, codePrefixed); } /** * <p> * Set repeated additional groups of decimals to use after the minimum decimals, if they are useful for expressing * precision. If the value precision exceeds all decimals specified (including minimum decimals), the value will be * rounded. This configuration is not relevant for parsing. * </p> * * <p> * For example, if you pass {@code 1,8} it will up to eight decimals to your formatted string if needed. After * these have been used up, rather than adding further decimals the value will be rounded. * </p> * * @param decimals * value of the group to be repeated * @param repetitions * number of repetitions */ public MonetaryFormat repeatOptionalDecimals(int decimals, int repetitions) { checkArgument(repetitions >= 0, () -> "repetitions cannot be negative: " + repetitions); List<Integer> decimalGroups = new ArrayList<>(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); } /** * Set number of digits to shift the decimal separator to the right, coming from the standard BTC notation that was * common pre-2014. Note this will change the currency code if enabled. */ public MonetaryFormat shift(int shift) { if (shift == this.shift) return this; else return new MonetaryFormat(negativeSign, positiveSign, zeroDigit, decimalMark, minDecimals, decimalGroups, shift, roundingMode, codes, codeSeparator, codePrefixed); } /** * Set rounding mode to use when it becomes necessary. */ public MonetaryFormat roundingMode(RoundingMode roundingMode) { if (roundingMode == this.roundingMode) return this; else return new MonetaryFormat(negativeSign, positiveSign, zeroDigit, decimalMark, minDecimals, decimalGroups, shift, roundingMode, codes, codeSeparator, codePrefixed); } /** * Don't display currency code when formatting. This configuration is not relevant for parsing. */ public MonetaryFormat noCode() { if (codes == null) return this; else return new MonetaryFormat(negativeSign, positiveSign, zeroDigit, decimalMark, minDecimals, decimalGroups, shift, roundingMode, null, codeSeparator, codePrefixed); } /** * Configure currency code for given decimal separator shift. This configuration is not relevant for parsing. * * @param codeShift * decimal separator shift, see {@link #shift} * @param code * currency code */ public MonetaryFormat code(int codeShift, String code) { checkArgument(codeShift >= 0, () -> "codeShift cannot be negative: " + codeShift); final String[] codes = null == this.codes ? new String[MAX_DECIMALS] : Arrays.copyOf(this.codes, this.codes.length); codes[codeShift] = code; return new MonetaryFormat(negativeSign, positiveSign, zeroDigit, decimalMark, minDecimals, decimalGroups, shift, roundingMode, codes, codeSeparator, codePrefixed); } /** * Separator between currency code and formatted value. This configuration is not relevant for parsing. */ public MonetaryFormat codeSeparator(char codeSeparator) { checkArgument(!Character.isDigit(codeSeparator), () -> "codeSeparator can't be digit: " + codeSeparator); checkArgument(codeSeparator > 0, () -> "codeSeparator must be positive: " + codeSeparator); if (codeSeparator == this.codeSeparator) return this; else return new MonetaryFormat(negativeSign, positiveSign, zeroDigit, decimalMark, minDecimals, decimalGroups, shift, roundingMode, codes, codeSeparator, codePrefixed); } /** * Prefix formatted output by currency code. This configuration is not relevant for parsing. */ public MonetaryFormat prefixCode() { if (codePrefixed) return this; else return new MonetaryFormat(negativeSign, positiveSign, zeroDigit, decimalMark, minDecimals, decimalGroups, shift, roundingMode, codes, codeSeparator, true); } /** * Postfix formatted output with currency code. This configuration is not relevant for parsing. */ public MonetaryFormat postfixCode() { if (!codePrefixed) return this; else return new MonetaryFormat(negativeSign, positiveSign, zeroDigit, decimalMark, minDecimals, decimalGroups, shift, roundingMode, codes, codeSeparator, false); } /** * Configure this instance with values from a {@link Locale}. */ public MonetaryFormat withLocale(Locale locale) { DecimalFormatSymbols dfs = new DecimalFormatSymbols(locale); char negativeSign = dfs.getMinusSign(); char zeroDigit = dfs.getZeroDigit(); char decimalMark = dfs.getMonetaryDecimalSeparator(); return new MonetaryFormat(negativeSign, positiveSign, zeroDigit, decimalMark, minDecimals, decimalGroups, shift, roundingMode, codes, codeSeparator, codePrefixed); } /** * Construct a MonetaryFormat with the default configuration. */ public MonetaryFormat() { this(false); } /** * Construct a MonetaryFormat with the default configuration. * * @param useSymbol use unicode symbols instead of the BTC and sat codes */ public MonetaryFormat(boolean useSymbol) { // defaults this.negativeSign = '-'; this.positiveSign = 0; // none this.zeroDigit = '0'; this.decimalMark = '.'; this.minDecimals = 2; this.decimalGroups = null; this.shift = 0; this.roundingMode = RoundingMode.HALF_UP; this.codes = new String[MAX_DECIMALS + 1]; this.codes[0] = useSymbol ? SYMBOL_BTC : CODE_BTC; this.codes[3] = useSymbol ? SYMBOL_MBTC : CODE_MBTC; this.codes[6] = useSymbol ? SYMBOL_UBTC : CODE_UBTC; this.codes[8] = useSymbol ? SYMBOL_SAT : CODE_SAT; this.codeSeparator = ' '; this.codePrefixed = true; } 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) { this.negativeSign = negativeSign; this.positiveSign = positiveSign; this.zeroDigit = zeroDigit; this.decimalMark = decimalMark; this.minDecimals = minDecimals; this.decimalGroups = decimalGroups; this.shift = shift; this.roundingMode = roundingMode; this.codes = codes; this.codeSeparator = codeSeparator; this.codePrefixed = codePrefixed; } /** * Format the given monetary value to a human-readable form. */ public CharSequence format(Monetary monetary) { // determine maximum number of decimals that can be visible in the formatted string // (if all decimal groups were to be used) int max = minDecimals; if (decimalGroups != null) for (int group : decimalGroups) max += group; final int maxVisibleDecimals = max; int smallestUnitExponent = monetary.smallestUnitExponent(); checkState(maxVisibleDecimals <= smallestUnitExponent, () -> "maxVisibleDecimals cannot exceed " + smallestUnitExponent + ": " + maxVisibleDecimals); // convert to decimal long satoshis = Math.abs(monetary.getValue()); int decimalShift = smallestUnitExponent - shift; DecimalNumber decimal = satoshisToDecimal(satoshis, roundingMode, decimalShift, maxVisibleDecimals); long numbers = decimal.numbers; long decimals = decimal.decimals; // formatting String decimalsStr = decimalShift > 0 ? String.format(Locale.US, "%0" + Integer.toString(decimalShift) + "d", decimals) : ""; StringBuilder str = new StringBuilder(decimalsStr); while (str.length() > minDecimals && str.charAt(str.length() - 1) == '0') str.setLength(str.length() - 1); // trim trailing zero 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()); } } // Convert to non-arabic digits. 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; } /** * Convert a long number of satoshis to a decimal number of BTC * @param satoshis number of satoshis * @param roundingMode rounding mode * @param decimalShift the number of places to move the decimal point to the left, * coming from smallest unit (e.g. satoshi) * @param maxVisibleDecimals the maximum number of decimals that can be visible in the formatted string * @return private class with two longs */ private static DecimalNumber satoshisToDecimal(long satoshis, RoundingMode roundingMode, int decimalShift, int maxVisibleDecimals) { BigDecimal decimalSats = BigDecimal.valueOf(satoshis); // shift the decimal point decimalSats = decimalSats.movePointLeft(decimalShift); // discard unwanted precision and round accordingly decimalSats = decimalSats.setScale(maxVisibleDecimals, roundingMode); // separate decimals from the number BigDecimal[] separated = decimalSats.divideAndRemainder(BigDecimal.ONE); return new DecimalNumber( separated[0].longValue(), separated[1].movePointRight(decimalShift).longValue() ); } private static class DecimalNumber { final long numbers; final long decimals; private DecimalNumber(long numbers, long decimals) { this.numbers = numbers; this.decimals = decimals; } } /** * Parse a human-readable coin value to a {@link Coin} instance. * * @throws NumberFormatException * if the string cannot be parsed for some reason */ public Coin parse(String str) throws NumberFormatException { return Coin.valueOf(parseValue(str, Coin.SMALLEST_UNIT_EXPONENT)); } /** * Parse a human-readable fiat value to a {@link Fiat} instance. * * @throws NumberFormatException * if the string cannot be parsed for some reason */ public Fiat parseFiat(String currencyCode, String str) throws NumberFormatException { return Fiat.valueOf(currencyCode, parseValue(str, Fiat.SMALLEST_UNIT_EXPONENT)); } private long parseValue(String str, int smallestUnitExponent) { checkState(DECIMALS_PADDING.length() >= smallestUnitExponent, () -> "smallestUnitExponent can't be higher than " + DECIMALS_PADDING.length() + ": " + smallestUnitExponent); if (str.isEmpty()) throw new NumberFormatException("empty string"); char first = str.charAt(0); if (first == negativeSign || first == positiveSign) str = str.substring(1); String numbers; String decimals; int decimalMarkIndex = str.indexOf(decimalMark); if (decimalMarkIndex != -1) { numbers = str.substring(0, decimalMarkIndex); decimals = (str + DECIMALS_PADDING).substring(decimalMarkIndex + 1); if (decimals.indexOf(decimalMark) != -1) throw new NumberFormatException("more than one decimal mark"); } else { numbers = str; decimals = DECIMALS_PADDING; } String satoshis = numbers + decimals.substring(0, smallestUnitExponent - shift); for (char c : satoshis.toCharArray()) if (!Character.isDigit(c)) throw new NumberFormatException("illegal character: " + c); long value = Long.parseLong(satoshis); // Non-arabic digits allowed here. if (first == negativeSign) value = -value; return value; } /** * Get currency code that will be used for current shift. */ public String code() { if (codes == null) return null; if (codes[shift] == null) throw new NumberFormatException("missing code for shift: " + shift); return codes[shift]; } /** * Two formats are equal if they have the same parameters. */ @Override public boolean equals(final Object o) { if (o == this) return true; if (o == null || o.getClass() != getClass()) return false; final MonetaryFormat other = (MonetaryFormat) o; if (!Objects.equals(this.negativeSign, other.negativeSign)) return false; if (!Objects.equals(this.positiveSign, other.positiveSign)) return false; if (!Objects.equals(this.zeroDigit, other.zeroDigit)) return false; if (!Objects.equals(this.decimalMark, other.decimalMark)) return false; if (!Objects.equals(this.minDecimals, other.minDecimals)) return false; if (!Objects.equals(this.decimalGroups, other.decimalGroups)) return false; if (!Objects.equals(this.shift, other.shift)) return false; if (!Objects.equals(this.roundingMode, other.roundingMode)) return false; if (!Arrays.equals(this.codes, other.codes)) return false; if (!Objects.equals(this.codeSeparator, other.codeSeparator)) return false; if (!Objects.equals(this.codePrefixed, other.codePrefixed)) return false; return true; } @Override public int hashCode() { return Objects.hash(negativeSign, positiveSign, zeroDigit, decimalMark, minDecimals, decimalGroups, shift, roundingMode, Arrays.hashCode(codes), codeSeparator, codePrefixed); } }
23,637
40.837168
120
java
bitcoinj
bitcoinj-master/core/src/main/java/org/bitcoinj/base/internal/ByteUtils.java
/* * Copyright by the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.bitcoinj.base.internal; import com.google.common.io.BaseEncoding; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.math.BigInteger; import java.nio.BufferOverflowException; import java.nio.BufferUnderflowException; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.util.Comparator; import static org.bitcoinj.base.internal.Preconditions.check; import static org.bitcoinj.base.internal.Preconditions.checkArgument; /** * Utility methods for bit, byte, and integer manipulation and conversion. Most of these were moved here * from {@code org.bitcoinj.core.Utils}. */ public class ByteUtils { /** Maximum unsigned value that can be expressed by 16 bits. */ public static final int MAX_UNSIGNED_SHORT = Short.toUnsignedInt((short) -1); /** Maximum unsigned value that can be expressed by 32 bits. */ public static final long MAX_UNSIGNED_INTEGER = Integer.toUnsignedLong(-1); /** * Hex encoding used throughout the framework. Use with ByteUtils.formatHex(byte[]) or ByteUtils.parseHex(CharSequence). * @deprecated Use {@link ByteUtils#hexFormat} or {@link ByteUtils#parseHex(String)} or other available * options. */ @Deprecated public static final BaseEncoding HEX = BaseEncoding.base16().lowerCase(); // 00000001, 00000010, 00000100, 00001000, ... private static final int[] bitMask = {0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80}; // This should be functionally equivalent to a subset of JDK 17 HexFormat.of() private static final HexFormat hexFormat = new HexFormat(); public static String formatHex(byte[] bytes) { return hexFormat.formatHex(bytes); } public static byte[] parseHex(String string) { return hexFormat.parseHex(string); } /** * <p> * The regular {@link BigInteger#toByteArray()} includes the sign bit of the number and * might result in an extra byte addition. This method removes this extra byte. * </p> * <p> * Assuming only positive numbers, it's possible to discriminate if an extra byte * is added by checking if the first element of the array is 0 (0000_0000). * Due to the minimal representation provided by BigInteger, it means that the bit sign * is the least significant bit 0000_000<b>0</b> . * Otherwise the representation is not minimal. * For example, if the sign bit is 0000_00<b>0</b>0, then the representation is not minimal due to the rightmost zero. * </p> * This is the antagonist to {@link #bytesToBigInteger(byte[])}. * @param b the integer to format into a byte array * @param numBytes the desired size of the resulting byte array * @return numBytes byte long array. */ public static byte[] bigIntegerToBytes(BigInteger b, int numBytes) { checkArgument(b.signum() >= 0, () -> "b must be positive or zero: " + b); checkArgument(numBytes > 0, () -> "numBytes must be positive: " + numBytes); byte[] src = b.toByteArray(); byte[] dest = new byte[numBytes]; boolean isFirstByteOnlyForSign = src[0] == 0; int length = isFirstByteOnlyForSign ? src.length - 1 : src.length; checkArgument(length <= numBytes, () -> "The given number does not fit in " + numBytes); int srcPos = isFirstByteOnlyForSign ? 1 : 0; int destPos = numBytes - length; System.arraycopy(src, srcPos, dest, destPos, length); return dest; } /** * Converts an array of bytes into a positive BigInteger. This is the antagonist to * {@link #bigIntegerToBytes(BigInteger, int)}. * * @param bytes to convert into a BigInteger * @return the converted BigInteger */ public static BigInteger bytesToBigInteger(byte[] bytes) { return new BigInteger(1, bytes); } /** * Write a 16-bit integer to a given buffer in little-endian format. * <p> * The value is expected as an unsigned {@code int} as per the Java Unsigned Integer API. * * @param val value to be written * @param buf buffer to be written into * @return the buffer * @throws BufferOverflowException if the value doesn't fit the remaining buffer */ public static ByteBuffer writeInt16LE(int val, ByteBuffer buf) throws BufferOverflowException { checkArgument(val >= 0 && val <= MAX_UNSIGNED_SHORT, () -> "value out of range: " + val); return buf.order(ByteOrder.LITTLE_ENDIAN).putShort((short) val); } /** * Write a 16-bit integer to a given byte array in little-endian format, starting at a given offset. * <p> * The value is expected as an unsigned {@code int} as per the Java Unsigned Integer API. * * @param val value to be written * @param out buffer to be written into * @param offset offset into the buffer * @throws ArrayIndexOutOfBoundsException if offset points outside of the buffer, or * if the value doesn't fit the remaining buffer */ public static void writeInt16LE(int val, byte[] out, int offset) throws ArrayIndexOutOfBoundsException { check(offset >= 0 && offset <= out.length - 2, () -> new ArrayIndexOutOfBoundsException(offset)); writeInt16LE(val, ByteBuffer.wrap(out, offset, out.length - offset)); } /** * Write a 16-bit integer to a given buffer in big-endian format. * <p> * The value is expected as an unsigned {@code int} as per the Java Unsigned Integer API. * * @param val value to be written * @param buf buffer to be written into * @return the buffer * @throws BufferOverflowException if the value doesn't fit the remaining buffer */ public static ByteBuffer writeInt16BE(int val, ByteBuffer buf) throws BufferOverflowException { checkArgument(val >= 0 && val <= MAX_UNSIGNED_SHORT, () -> "value out of range: " + val); return buf.order(ByteOrder.BIG_ENDIAN).putShort((short) val); } /** * Write a 16-bit integer to a given byte array in big-endian format, starting at a given offset. * <p> * The value is expected as an unsigned {@code int} as per the Java Unsigned Integer API. * * @param val value to be written * @param out buffer to be written into * @param offset offset into the buffer * @throws ArrayIndexOutOfBoundsException if offset points outside of the buffer, or * if the value doesn't fit the remaining buffer */ public static void writeInt16BE(int val, byte[] out, int offset) throws ArrayIndexOutOfBoundsException { check(offset >= 0 && offset <= out.length - 2, () -> new ArrayIndexOutOfBoundsException(offset)); writeInt16BE(val, ByteBuffer.wrap(out, offset, out.length - offset)); } /** * Write a 32-bit integer to a given buffer in little-endian format. * <p> * The value is expected as a signed or unsigned {@code int}. If you've got an unsigned {@code long} as per the * Java Unsigned Integer API, use {@link #writeInt32LE(long, ByteBuffer)}. * * @param val value to be written * @param buf buffer to be written into * @return the buffer * @throws BufferOverflowException if the value doesn't fit the remaining buffer */ public static ByteBuffer writeInt32LE(int val, ByteBuffer buf) throws BufferOverflowException { return buf.order(ByteOrder.LITTLE_ENDIAN).putInt(val); } /** * Write a 32-bit integer to a given buffer in little-endian format. * <p> * The value is expected as an unsigned {@code long} as per the Java Unsigned Integer API. * * @param val value to be written * @param buf buffer to be written into * @return the buffer * @throws BufferOverflowException if the value doesn't fit the remaining buffer */ public static ByteBuffer writeInt32LE(long val, ByteBuffer buf) throws BufferOverflowException { checkArgument(val >= 0 && val <= MAX_UNSIGNED_INTEGER, () -> "value out of range: " + val); return buf.order(ByteOrder.LITTLE_ENDIAN).putInt((int) val); } /** * Write a 32-bit integer to a given byte array in little-endian format, starting at a given offset. * <p> * The value is expected as an unsigned {@code long} as per the Java Unsigned Integer API. * * @param val value to be written * @param out buffer to be written into * @param offset offset into the buffer * @throws ArrayIndexOutOfBoundsException if offset points outside of the buffer, or * if the value doesn't fit the remaining buffer */ public static void writeInt32LE(long val, byte[] out, int offset) throws ArrayIndexOutOfBoundsException { check(offset >= 0 && offset <= out.length - 4, () -> new ArrayIndexOutOfBoundsException(offset)); writeInt32LE(val, ByteBuffer.wrap(out, offset, out.length - offset)); } /** * Write a 32-bit integer to a given buffer in big-endian format. * <p> * The value is expected as an unsigned {@code long} as per the Java Unsigned Integer API. * * @param val value to be written * @param buf buffer to be written into * @return the buffer * @throws BufferOverflowException if the value doesn't fit the remaining buffer */ public static ByteBuffer writeInt32BE(long val, ByteBuffer buf) throws BufferOverflowException { checkArgument(val >= 0 && val <= MAX_UNSIGNED_INTEGER, () -> "value out of range: " + val); return buf.order(ByteOrder.BIG_ENDIAN).putInt((int) val); } /** * Write a 32-bit integer to a given buffer in big-endian format. * <p> * The value is expected as a signed or unsigned {@code int}. If you've got an unsigned {@code long} as per the * Java Unsigned Integer API, use {@link #writeInt32BE(long, ByteBuffer)}. * * @param val value to be written * @param buf buffer to be written into * @return the buffer * @throws BufferOverflowException if the value doesn't fit the remaining buffer */ public static ByteBuffer writeInt32BE(int val, ByteBuffer buf) throws BufferOverflowException { return buf.order(ByteOrder.BIG_ENDIAN).putInt((int) val); } /** * Write a 32-bit integer to a given byte array in big-endian format, starting at a given offset. * <p> * The value is expected as an unsigned {@code long} as per the Java Unsigned Integer API. * * @param val value to be written * @param out buffer to be written into * @param offset offset into the buffer * @throws ArrayIndexOutOfBoundsException if offset points outside of the buffer, or * if the value doesn't fit the remaining buffer */ public static void writeInt32BE(long val, byte[] out, int offset) throws ArrayIndexOutOfBoundsException { check(offset >= 0 && offset <= out.length - 4, () -> new ArrayIndexOutOfBoundsException(offset)); writeInt32BE(val, ByteBuffer.wrap(out, offset, out.length - offset)); } /** * Write a 32-bit integer to a given byte array in big-endian format, starting at a given offset. * <p> * The value is expected as a signed or unsigned {@code int}. If you've got an unsigned {@code long} as per the * Java Unsigned Integer API, use {@link #writeInt32BE(long, byte[], int)}. * * @param val value to be written * @param out buffer to be written into * @param offset offset into the buffer * @throws ArrayIndexOutOfBoundsException if offset points outside of the buffer, or * if the value doesn't fit the remaining buffer */ public static void writeInt32BE(int val, byte[] out, int offset) throws ArrayIndexOutOfBoundsException { writeInt32BE(val, ByteBuffer.wrap(out, offset, out.length - offset)); } /** * Write a 64-bit integer to a given buffer in little-endian format. * <p> * The value is expected as a signed or unsigned {@code long}. * * @param val value to be written * @param buf buffer to be written into * @return the buffer * @throws BufferOverflowException if the value doesn't fit the remaining buffer */ public static ByteBuffer writeInt64LE(long val, ByteBuffer buf) throws BufferOverflowException { return buf.order(ByteOrder.LITTLE_ENDIAN).putLong(val); } /** * Write a 64-bit integer to a given byte array in little-endian format, starting at a given offset. * <p> * The value is expected as a signed or unsigned {@code long}. * * @param val value to be written * @param out buffer to be written into * @param offset offset into the buffer * @throws ArrayIndexOutOfBoundsException if offset points outside of the buffer, or * if the value doesn't fit the remaining buffer */ public static void writeInt64LE(long val, byte[] out, int offset) throws ArrayIndexOutOfBoundsException { check(offset >= 0 && offset <= out.length + 8, () -> new ArrayIndexOutOfBoundsException(offset)); writeInt64LE(val, ByteBuffer.wrap(out, offset, out.length - offset)); } /** * Write a 16-bit integer to a given output stream in little-endian format. * <p> * The value is expected as an unsigned {@code int} as per the Java Unsigned Integer API. * * @param val value to be written * @param stream strean to be written into * @throws IOException if an I/O error occurs */ public static void writeInt16LE(int val, OutputStream stream) throws IOException { byte[] buf = new byte[2]; writeInt16LE(val, ByteBuffer.wrap(buf)); stream.write(buf); } /** * Write a 16-bit integer to a given output stream in big-endian format. * <p> * The value is expected as an unsigned {@code int} as per the Java Unsigned Integer API. * * @param val value to be written * @param stream strean to be written into * @throws IOException if an I/O error occurs */ public static void writeInt16BE(int val, OutputStream stream) throws IOException { byte[] buf = new byte[2]; writeInt16BE(val, ByteBuffer.wrap(buf)); stream.write(buf); } /** * Write a 32-bit integer to a given output stream in little-endian format. * <p> * The value is expected as a signed or unsigned {@code int}. If you've got an unsigned {@code long} as per the * Java Unsigned Integer API, use {@link #writeInt32LE(long, OutputStream)}. * * @param val value to be written * @param stream stream to be written into * @throws IOException if an I/O error occurs */ public static void writeInt32LE(int val, OutputStream stream) throws IOException { byte[] buf = new byte[4]; writeInt32LE(val, ByteBuffer.wrap(buf)); stream.write(buf); } /** * Write a 32-bit integer to a given output stream in little-endian format. * <p> * The value is expected as an unsigned {@code long} as per the Java Unsigned Integer API. * * @param val value to be written * @param stream strean to be written into * @throws IOException if an I/O error occurs */ public static void writeInt32LE(long val, OutputStream stream) throws IOException { byte[] buf = new byte[4]; writeInt32LE(val, ByteBuffer.wrap(buf)); stream.write(buf); } /** * Write a 32-bit integer to a given output stream in big-endian format. * <p> * The value is expected as an unsigned {@code long} as per the Java Unsigned Integer API. * * @param val value to be written * @param stream strean to be written into * @throws IOException if an I/O error occurs */ public static void writeInt32BE(long val, OutputStream stream) throws IOException { byte[] buf = new byte[4]; writeInt32BE(val, ByteBuffer.wrap(buf)); stream.write(buf); } /** * Write a 32-bit integer to a given output stream in big-endian format. * <p> * The value is expected as a signed or unsigned {@code int}. * * @param val value to be written * @param stream strean to be written into * @throws IOException if an I/O error occurs */ public static void writeInt32BE(int val, OutputStream stream) throws IOException { byte[] buf = new byte[4]; writeInt32BE(val, ByteBuffer.wrap(buf)); stream.write(buf); } /** * Write a 64-bit integer to a given output stream in little-endian format. * <p> * The value is expected as a signed or unsigned {@code long}. * * @param val value to be written * @param stream strean to be written into * @throws IOException if an I/O error occurs */ public static void writeInt64LE(long val, OutputStream stream) throws IOException { byte[] buf = new byte[8]; writeInt64LE(val, ByteBuffer.wrap(buf)); stream.write(buf); } /** * Write a 64-bit integer to a given output stream in little-endian format. * <p> * The value is expected as an unsigned {@link BigInteger}. * * @param val value to be written * @param stream strean to be written into * @throws IOException if an I/O error occurs */ public static void writeInt64LE(BigInteger val, OutputStream stream) throws IOException { byte[] bytes = val.toByteArray(); if (bytes.length > 8) { throw new RuntimeException("Input too large to encode into a uint64"); } bytes = reverseBytes(bytes); stream.write(bytes); if (bytes.length < 8) { for (int i = 0; i < 8 - bytes.length; i++) stream.write(0); } } /** * Read 2 bytes from the buffer as unsigned 16-bit integer in little endian format. * @param buf buffer to be read from * @throws BufferUnderflowException if the read value extends beyond the remaining bytes of the buffer */ public static int readUint16(ByteBuffer buf) throws BufferUnderflowException { return Short.toUnsignedInt(buf.order(ByteOrder.LITTLE_ENDIAN).getShort()); } /** * Read 2 bytes from the byte array (starting at the offset) as unsigned 16-bit integer in little endian format. * @param bytes buffer to be read from * @param offset offset into the buffer * @throws ArrayIndexOutOfBoundsException if offset points outside of the buffer, or * if the read value extends beyond the remaining bytes of the buffer */ public static int readUint16(byte[] bytes, int offset) throws ArrayIndexOutOfBoundsException { check(offset >= 0 && offset <= bytes.length - 2, () -> new ArrayIndexOutOfBoundsException(offset)); return readUint16(ByteBuffer.wrap(bytes, offset, bytes.length - offset)); } /** * Read 2 bytes from the buffer as unsigned 16-bit integer in big endian format. * @param buf buffer to be read from * @throws BufferUnderflowException if the read value extends beyond the remaining bytes of the buffer */ public static int readUint16BE(ByteBuffer buf) throws BufferUnderflowException { return Short.toUnsignedInt(buf.order(ByteOrder.BIG_ENDIAN).getShort()); } /** * Read 2 bytes from the byte array (starting at the offset) as unsigned 16-bit integer in big endian format. * @param bytes buffer to be read from * @param offset offset into the buffer * @throws ArrayIndexOutOfBoundsException if offset points outside of the buffer, or * if the read value extends beyond the remaining bytes of the buffer */ public static int readUint16BE(byte[] bytes, int offset) throws ArrayIndexOutOfBoundsException { check(offset >= 0 && offset <= bytes.length - 2, () -> new ArrayIndexOutOfBoundsException(offset)); return readUint16BE(ByteBuffer.wrap(bytes, offset, bytes.length - offset)); } /** * Read 4 bytes from the buffer as unsigned 32-bit integer in little endian format. * @param buf buffer to be read from * @throws BufferUnderflowException if the read value extends beyond the remaining bytes of the buffer */ public static long readUint32(ByteBuffer buf) throws BufferUnderflowException { return Integer.toUnsignedLong(buf.order(ByteOrder.LITTLE_ENDIAN).getInt()); } /** * Read 4 bytes from the byte array (starting at the offset) as signed 32-bit integer in little endian format. * @param buf buffer to be read from * @return read integer * @throws BufferUnderflowException if the read value extends beyond the remaining bytes of the buffer */ public static int readInt32(ByteBuffer buf) throws BufferUnderflowException { return buf.order(ByteOrder.LITTLE_ENDIAN).getInt(); } /** * Read 4 bytes from the byte array (starting at the offset) as unsigned 32-bit integer in little endian format. * @param bytes buffer to be read from * @param offset offset into the buffer * @throws ArrayIndexOutOfBoundsException if offset points outside of the buffer, or * if the read value extends beyond the remaining bytes of the buffer */ public static long readUint32(byte[] bytes, int offset) throws ArrayIndexOutOfBoundsException { check(offset >= 0 && offset <= bytes.length - 4, () -> new ArrayIndexOutOfBoundsException(offset)); return readUint32(ByteBuffer.wrap(bytes, offset, bytes.length - offset)); } /** * Read 4 bytes from the buffer as unsigned 32-bit integer in big endian format. * @param buf buffer to be read from * @throws BufferUnderflowException if the read value extends beyond the remaining bytes of the buffer */ public static long readUint32BE(ByteBuffer buf) throws BufferUnderflowException { return Integer.toUnsignedLong(buf.order(ByteOrder.BIG_ENDIAN).getInt()); } /** * Read 4 bytes from the byte array (starting at the offset) as unsigned 32-bit integer in big endian format. * @param bytes buffer to be read from * @param offset offset into the buffer * @throws ArrayIndexOutOfBoundsException if offset points outside of the buffer, or * if the read value extends beyond the remaining bytes of the buffer */ public static long readUint32BE(byte[] bytes, int offset) throws ArrayIndexOutOfBoundsException { check(offset >= 0 && offset <= bytes.length - 4, () -> new ArrayIndexOutOfBoundsException(offset)); return readUint32BE(ByteBuffer.wrap(bytes, offset, bytes.length - offset)); } /** * Read 8 bytes from the buffer as signed 64-bit integer in little endian format. * @param buf buffer to be read from * @throws BufferUnderflowException if the read value extends beyond the remaining bytes of the buffer */ public static long readInt64(ByteBuffer buf) throws BufferUnderflowException { return buf.order(ByteOrder.LITTLE_ENDIAN).getLong(); } /** * Read 8 bytes from the byte array (starting at the offset) as signed 64-bit integer in little endian format. * @param bytes buffer to be read from * @param offset offset into the buffer * @throws ArrayIndexOutOfBoundsException if offset points outside of the buffer, or * if the read value extends beyond the remaining bytes of the buffer */ public static long readInt64(byte[] bytes, int offset) throws ArrayIndexOutOfBoundsException { check(offset >= 0 && offset <= bytes.length - 8, () -> new ArrayIndexOutOfBoundsException(offset)); return readInt64(ByteBuffer.wrap(bytes, offset, bytes.length - offset)); } /** * Read 2 bytes from the stream as unsigned 16-bit integer in little endian format. * @param is stream to be read from */ public static int readUint16(InputStream is) { byte[] buf = new byte[2]; try { is.read(buf); return readUint16(ByteBuffer.wrap(buf)); } catch (IOException x) { throw new RuntimeException(x); } } /** * Read 4 bytes from the stream as unsigned 32-bit integer in little endian format. * @param is stream to be read from */ public static long readUint32(InputStream is) { byte[] buf = new byte[4]; try { is.read(buf); return readUint32(ByteBuffer.wrap(buf)); } catch (IOException x) { throw new RuntimeException(x); } } /** * Returns a copy of the given byte array in reverse order. */ public static byte[] reverseBytes(byte[] bytes) { // We could use the XOR trick here but it's easier to understand if we don't. If we find this is really a // performance issue the matter can be revisited. byte[] buf = new byte[bytes.length]; for (int i = 0; i < bytes.length; i++) buf[i] = bytes[bytes.length - 1 - i]; return buf; } /** * MPI encoded numbers are produced by the OpenSSL BN_bn2mpi function. They consist of * a 4 byte big endian length field, followed by the stated number of bytes representing * the number in big endian format (with a sign bit). * @param hasLength can be set to false if the given array is missing the 4 byte length field */ public static BigInteger decodeMPI(byte[] mpi, boolean hasLength) { byte[] buf; if (hasLength) { int length = (int) readUint32BE(mpi, 0); buf = new byte[length]; System.arraycopy(mpi, 4, buf, 0, length); } else buf = mpi; if (buf.length == 0) return BigInteger.ZERO; boolean isNegative = (buf[0] & 0x80) == 0x80; if (isNegative) buf[0] &= 0x7f; BigInteger result = new BigInteger(buf); return isNegative ? result.negate() : result; } /** * MPI encoded numbers are produced by the OpenSSL BN_bn2mpi function. They consist of * a 4 byte big endian length field, followed by the stated number of bytes representing * the number in big endian format (with a sign bit). * @param includeLength indicates whether the 4 byte length field should be included */ public static byte[] encodeMPI(BigInteger value, boolean includeLength) { if (value.equals(BigInteger.ZERO)) { if (!includeLength) return new byte[] {}; else return new byte[] {0x00, 0x00, 0x00, 0x00}; } boolean isNegative = value.signum() < 0; if (isNegative) value = value.negate(); byte[] array = value.toByteArray(); int length = array.length; if ((array[0] & 0x80) == 0x80) length++; if (includeLength) { byte[] result = new byte[length + 4]; System.arraycopy(array, 0, result, length - array.length + 3, array.length); writeInt32BE(length, result, 0); if (isNegative) result[4] |= 0x80; return result; } else { byte[] result; if (length != array.length) { result = new byte[length]; System.arraycopy(array, 0, result, 1, array.length); }else result = array; if (isNegative) result[0] |= 0x80; return result; } } /** * <p>The "compact" format is a representation of a whole number N using an unsigned 32 bit number similar to a * floating point format. The most significant 8 bits are the unsigned exponent of base 256. This exponent can * be thought of as "number of bytes of N". The lower 23 bits are the mantissa. Bit number 24 (0x800000) represents * the sign of N. Therefore, N = (-1^sign) * mantissa * 256^(exponent-3).</p> * * <p>Satoshi's original implementation used BN_bn2mpi() and BN_mpi2bn(). MPI uses the most significant bit of the * first byte as sign. Thus 0x1234560000 is compact 0x05123456 and 0xc0de000000 is compact 0x0600c0de. Compact * 0x05c0de00 would be -0x40de000000.</p> * * <p>Bitcoin only uses this "compact" format for encoding difficulty targets, which are unsigned 256bit quantities. * Thus, all the complexities of the sign bit and using base 256 are probably an implementation accident.</p> */ public static BigInteger decodeCompactBits(long compact) { int size = ((int) (compact >> 24)) & 0xFF; byte[] bytes = new byte[4 + size]; bytes[3] = (byte) size; if (size >= 1) bytes[4] = (byte) ((compact >> 16) & 0xFF); if (size >= 2) bytes[5] = (byte) ((compact >> 8) & 0xFF); if (size >= 3) bytes[6] = (byte) (compact & 0xFF); return decodeMPI(bytes, true); } /** * @see #decodeCompactBits(long) */ public static long encodeCompactBits(BigInteger value) { long result; int size = value.toByteArray().length; if (size <= 3) result = value.longValue() << 8 * (3 - size); else result = value.shiftRight(8 * (size - 3)).longValue(); // The 0x00800000 bit denotes the sign. // Thus, if it is already set, divide the mantissa by 256 and increase the exponent. if ((result & 0x00800000L) != 0) { result >>= 8; size++; } result |= (long) size << 24; result |= value.signum() == -1 ? 0x00800000 : 0; return result; } /** Checks if the given bit is set in data, using little endian (not the same as Java native big endian) */ public static boolean checkBitLE(byte[] data, int index) { return (data[index >>> 3] & bitMask[7 & index]) != 0; } /** Sets the given bit in data to one, using little endian (not the same as Java native big endian) */ public static void setBitLE(byte[] data, int index) { data[index >>> 3] |= bitMask[7 & index]; } /** * Provides a byte array comparator. * @return A comparator for byte[] */ public static Comparator<byte[]> arrayUnsignedComparator() { return ARRAY_UNSIGNED_COMPARATOR; } // In Java 9, this can be replaced with Arrays.compareUnsigned() private static final Comparator<byte[]> ARRAY_UNSIGNED_COMPARATOR = (a, b) -> { int minLength = Math.min(a.length, b.length); for (int i = 0; i < minLength; i++) { int result = compareUnsigned(a[i], b[i]); if (result != 0) { return result; } } return a.length - b.length; }; private static int compareUnsigned(byte a, byte b) { return Byte.toUnsignedInt(a) - Byte.toUnsignedInt(b); } }
32,247
42.227882
124
java
bitcoinj
bitcoinj-master/core/src/main/java/org/bitcoinj/base/internal/Preconditions.java
/* * Copyright by the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.bitcoinj.base.internal; import java.util.function.Supplier; public class Preconditions { /** * Ensures the truth of an expression involving one or more parameters to the calling method. * @param expression a boolean expression * @throws IllegalArgumentException if {@code expression} is false */ public static void checkArgument(boolean expression) { check(expression, IllegalArgumentException::new); } /** * Ensures the truth of an expression involving one or more parameters to the calling method. * @param expression a boolean expression * @param messageSupplier supplier of the detail message to be used in the event that a IllegalArgumentException is thrown * @throws IllegalArgumentException if {@code expression} is false */ public static void checkArgument(boolean expression, Supplier<String> messageSupplier) { check(expression, () -> new IllegalArgumentException(messageSupplier.get())); } /** * Ensures the truth of an expression involving the state of the calling instance, but not * involving any parameters to the calling method. * @param expression a boolean expression * @throws IllegalStateException if {@code expression} is false */ public static void checkState(boolean expression) { check(expression, IllegalStateException::new); } /** * Ensures the truth of an expression involving the state of the calling instance, but not * involving any parameters to the calling method. * @param expression a boolean expression * @param messageSupplier supplier of the detail message to be used in the event that a IllegalStateException is thrown * @throws IllegalStateException if {@code expression} is false */ public static void checkState(boolean expression, Supplier<String> messageSupplier) { check(expression, () -> new IllegalStateException(messageSupplier.get())); } /** * Ensures the truth of an expression, throwing a custom exception if untrue. * @param expression a boolean expression * @param exceptionSupplier supplier of the exception to be thrown * @throws X if {@code expression} is false */ public static <X extends Throwable> void check(boolean expression, Supplier<? extends X> exceptionSupplier) throws X { if (!expression) throw exceptionSupplier.get(); } }
3,059
40.917808
126
java
bitcoinj
bitcoinj-master/core/src/main/java/org/bitcoinj/base/internal/InternalUtils.java
/* * Copyright by the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.bitcoinj.base.internal; import java.util.Arrays; import java.util.List; import java.util.Objects; import java.util.stream.Collectors; /** * Utilities for internal use only. */ public class InternalUtils { /** * A functional interface for joining {@link String}s or {@code Object}s via {@link Object#toString()} using * a pre-configured delimiter. * <p> * In previous versions of <b>bitcoinj</b> this functionality was provided by Guava's {@code Joiner}. */ @FunctionalInterface public interface Joiner { /** * @param objects A list of objects to join (after calling {@link Object#toString()}) * The components joined into a single {@code String} separated by the pre-configured delimiter. */ String join(List<?> objects); } /** * A functional interface for splitting {@link String}s using a pre-configured regular expression. * <p> * In previous versions of <b>bitcoinj</b> this functionality was provided by Guava's {@code Splitter}. */ @FunctionalInterface public interface Splitter { /** * @param string The {@code String} to split * @return A list of split {@code String components} */ List<String> splitToList(String string); } /** * Return a lambda for joining {@code String}s or {@code Object}s via {@link Object#toString()}. * @param delimiter The delimiter used to join the {@code String} components * @return A {@code Joiner} (lambda) instance */ public static Joiner joiner(String delimiter) { return list -> list.stream() .map(Object::toString) .collect(Collectors.joining(delimiter)); } /** * Return a lambda for splitting a string into components * @param regex regular expression used to split components * @return A {@code Splitter} (lambda) instance */ public static Splitter splitter(String regex) { return s -> Arrays.asList(s.split(regex)); } /** * A {@link Joiner} for joining strings into a single string delimited by a space character. */ public static final Joiner SPACE_JOINER = joiner(" "); /** * A {@link Splitter} for splitting a string into components by whitespace. */ public static final Splitter WHITESPACE_SPLITTER = splitter("\\s+"); /** * Join strings with ", " skipping nulls * @param strings varargs strings * @return A joined string */ public static String commaJoin(String... strings) { return Arrays.stream(strings).filter(Objects::nonNull).collect(Collectors.joining(", ")); } }
3,307
33.103093
112
java
bitcoinj
bitcoinj-master/core/src/main/java/org/bitcoinj/base/internal/PlatformUtils.java
/* * Copyright by the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.bitcoinj.base.internal; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Locale; /** * Utilities for determining platform information (OS and runtime) */ public class PlatformUtils { private static final Logger log = LoggerFactory.getLogger(PlatformUtils.class); public enum Runtime { ANDROID, OPENJDK, ORACLE_JAVA } public enum OS { LINUX, WINDOWS, MAC_OS } public static Runtime runtime = null; public static OS os = null; static { String runtimeProp = System.getProperty("java.runtime.name", "").toLowerCase(Locale.US); if (runtimeProp.equals("")) PlatformUtils.runtime = null; else if (runtimeProp.contains("android")) PlatformUtils.runtime = PlatformUtils.Runtime.ANDROID; else if (runtimeProp.contains("openjdk")) PlatformUtils.runtime = PlatformUtils.Runtime.OPENJDK; else if (runtimeProp.contains("java(tm) se")) PlatformUtils.runtime = PlatformUtils.Runtime.ORACLE_JAVA; else log.info("Unknown java.runtime.name '{}'", runtimeProp); String osProp = System.getProperty("os.name", "").toLowerCase(Locale.US); if (osProp.equals("")) PlatformUtils.os = null; else if (osProp.contains("linux")) PlatformUtils.os = PlatformUtils.OS.LINUX; else if (osProp.contains("win")) PlatformUtils.os = PlatformUtils.OS.WINDOWS; else if (osProp.contains("mac")) PlatformUtils.os = PlatformUtils.OS.MAC_OS; else log.info("Unknown os.name '{}'", runtimeProp); } public static boolean isAndroidRuntime() { return runtime == Runtime.ANDROID; } public static boolean isOpenJDKRuntime() { return runtime == Runtime.OPENJDK; } public static boolean isOracleJavaRuntime() { return runtime == Runtime.ORACLE_JAVA; } public static boolean isLinux() { return os == OS.LINUX; } public static boolean isWindows() { return os == OS.WINDOWS; } public static boolean isMac() { return os == OS.MAC_OS; } }
2,809
30.222222
96
java
bitcoinj
bitcoinj-master/core/src/main/java/org/bitcoinj/base/internal/ByteArray.java
/* * Copyright by the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.bitcoinj.base.internal; import java.util.Arrays; /** * An effectively-immutable byte array. */ public class ByteArray implements Comparable<ByteArray> { protected final byte[] bytes; /** * Wrapper for a {@code byte[]} * @param bytes byte data to wrap */ public ByteArray(byte[] bytes) { // Make defensive copy, so we are effectively immutable this.bytes = new byte[bytes.length]; System.arraycopy(bytes, 0, this.bytes, 0, bytes.length); } /** * @return the key bytes */ public byte[] bytes() { return bytes; } /** * @return the bytes as a hex-formatted string */ public String formatHex() { return ByteUtils.formatHex(bytes); } /** * {@inheritDoc} * @return {@inheritDoc} */ @Override public int hashCode() { return Arrays.hashCode(bytes); } /** * {@inheritDoc} * @param o {@inheritDoc} * @return {@inheritDoc} */ @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; ByteArray other = (ByteArray) o; return Arrays.equals(this.bytes, other.bytes); } /** * {@inheritDoc} * <p>For {@link ByteArray} this is a byte-by-byte, unsigned comparison. * @param o {@inheritDoc} * @return {@inheritDoc} */ @Override public int compareTo(ByteArray o) { return ByteUtils.arrayUnsignedComparator().compare(bytes, o.bytes); } }
2,195
25.142857
76
java
bitcoinj
bitcoinj-master/core/src/main/java/org/bitcoinj/base/internal/HexFormat.java
/* * Copyright by the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.bitcoinj.base.internal; /** * This class implements a subset of the functionality of the {@code HexFormat} class available in Java 17 and later. * Its behavior is the same as an instance of Java 17 {@code HexFormat} created with {@code HexFormat.of()}. * It is an internal class to support {@link ByteUtils} and may be removed in the future * when and if we have a Java 17 baseline. * <p>Thanks to this <a href="https://www.baeldung.com/java-byte-arrays-hex-strings">Baeldung article</a>. */ public class HexFormat { public String formatHex(byte[] bytes) { StringBuilder stringBuilder = new StringBuilder(bytes.length * 2); for (byte aByte : bytes) { stringBuilder.append(byteToHex(aByte)); } return stringBuilder.toString(); } public byte[] parseHex(String hexString) { if (hexString.length() % 2 == 1) { throw new IllegalArgumentException("Invalid hexadecimal String supplied."); } byte[] bytes = new byte[hexString.length() / 2]; for (int i = 0; i < hexString.length(); i += 2) { bytes[i / 2] = hexToByte(hexString.substring(i, i + 2)); } return bytes; } private String byteToHex(byte num) { char[] hexDigits = new char[2]; hexDigits[0] = Character.forDigit((num >> 4) & 0xF, 16); hexDigits[1] = Character.forDigit((num & 0xF), 16); return new String(hexDigits); } private byte hexToByte(String hexString) { int firstDigit = toDigit(hexString.charAt(0)); int secondDigit = toDigit(hexString.charAt(1)); return (byte) ((firstDigit << 4) + secondDigit); } private int toDigit(char hexChar) { int digit = Character.digit(hexChar, 16); if (digit == -1) { throw new IllegalArgumentException("Invalid Hexadecimal Character: "+ hexChar); } return digit; } }
2,546
37.014925
117
java
bitcoinj
bitcoinj-master/core/src/main/java/org/bitcoinj/base/internal/Stopwatch.java
package org.bitcoinj.base.internal; /* * Copyright by the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import java.time.Duration; import java.time.Instant; import java.time.temporal.ChronoUnit; import java.time.temporal.Temporal; import java.time.temporal.TemporalAmount; import java.time.temporal.TemporalUnit; import java.util.Arrays; import java.util.List; import static org.bitcoinj.base.internal.Preconditions.checkArgument; /** * A tool for measuring time, mainly for log messages. Note this class isn't affected by the mock clock of * {@link TimeUtils}. */ public class Stopwatch implements TemporalAmount { private final Instant startTime; private Instant stopTime = null; /** * Start a newly created stopwatch. * * @return the stopwatch that was just started */ public static Stopwatch start() { return new Stopwatch(); } private Stopwatch() { this.startTime = Instant.now(); } /** * Stops the stopwatch, if it is running. * * @return the stopwatch that is stopped */ public Stopwatch stop() { if (isRunning()) stopTime = Instant.now(); return this; } /** * Returns true if the stopwatch is running. * * @return true if the stopwatch is running, false otherwise */ public boolean isRunning() { return stopTime == null; } /** * Gets the elapsed time on the watch. This doesn't stop the watch. * * @return elapsed time */ public Duration elapsed() { return Duration.between(startTime, isRunning() ? Instant.now() : stopTime); } @Override public long get(TemporalUnit temporalUnit) { checkArgument(temporalUnit.equals(ChronoUnit.MILLIS), () -> "unsupported temporal unit: " + temporalUnit); return elapsed().toMillis(); } @Override public List<TemporalUnit> getUnits() { return Arrays.asList(ChronoUnit.MILLIS); } @Override public Temporal addTo(Temporal temporal) { return temporal.plus(elapsed()); } @Override public Temporal subtractFrom(Temporal temporal) { return temporal.minus(elapsed()); } @Override public String toString() { return elapsed().toMillis() + " ms"; } }
2,844
26.095238
114
java
bitcoinj
bitcoinj-master/core/src/main/java/org/bitcoinj/base/internal/StreamUtils.java
/* * Copyright by the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.bitcoinj.base.internal; import java.util.Collections; import java.util.List; import java.util.stream.Collector; import java.util.stream.Collectors; import java.util.stream.Stream; /** * Stream Utilities. Bitcoinj is moving towards functional-style programming, immutable data structures, and * unmodifiable lists. Since we are currently limited to Java 8, this class contains utility methods that can simplify * code in many places. */ public class StreamUtils { /** * Return a collector that collects a {@link Stream} into an unmodifiable list. * <p> * Java 10 provides {@code Collectors.toUnmodifiableList()} and Java 16 provides {@code Stream.toList()}. * If those are not available, use this utility method. */ public static <T> Collector<T, ?, List<T>> toUnmodifiableList() { return Collectors.collectingAndThen(Collectors.toList(), Collections::unmodifiableList); } }
1,549
36.804878
118
java
bitcoinj
bitcoinj-master/core/src/main/java/org/bitcoinj/base/internal/TimeUtils.java
/* * Copyright by the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.bitcoinj.base.internal; import java.time.Clock; import java.time.Duration; import java.time.Instant; import java.time.format.DateTimeFormatter; import java.util.TimeZone; /** * Utilities for time and mock time. */ public class TimeUtils { private static final TimeZone UTC = TimeZone.getTimeZone("UTC"); // Clock to be used for the return value of now() and currentTime() variants private static volatile Clock clock = Clock.systemUTC(); /** * Sets the mock clock to the current time as a fixed instant. */ public static void setMockClock() { setMockClock(Instant.now()); } /** * Sets the mock clock to a fixed instant. * @param fixedInstant a fixed instant */ public static void setMockClock(Instant fixedInstant) { clock = Clock.fixed(fixedInstant, UTC.toZoneId()); } /** * Rolls an already set mock clock by the given duration. * @param delta amount to roll the mock clock, can be negative * @throws IllegalStateException if the mock clock isn't set */ public static void rollMockClock(Duration delta) { if (clock.equals(Clock.systemUTC())) throw new IllegalStateException("You need to use setMockClock() first."); setMockClock(clock.instant().plus(delta)); } /** * Clears the mock clock and causes time to tick again. */ public static void clearMockClock() { clock = Clock.systemUTC(); } /** * Returns the current time as an Instant, or a mocked out equivalent. */ public static Instant currentTime() { return Instant.now(clock); } /** * Returns elapsed time between given start and current time as a Duration. * <p> * Note that this method is affected by the mock clock. If you want to raise real debug data use {@link Stopwatch}. */ public static Duration elapsedTime(Instant start) { return Duration.between(start, currentTime()); } /** * Determines the earlier of two instants. */ public static Instant earlier(Instant time1, Instant time2) { return time1.isBefore(time2) ? time1 : time2; } /** * Determines the later of two instants. */ public static Instant later(Instant time1, Instant time2) { return time1.isAfter(time2) ? time1 : time2; } /** * Determines the longest of two durations. */ public static Duration longest(Duration duration1, Duration duration2) { return duration1.compareTo(duration2) > 0 ? duration1 : duration2; } /** * Formats a given date+time value to an ISO 8601 string. * @param time date and time to format */ public static String dateTimeFormat(Instant time) { return DateTimeFormatter.ISO_INSTANT.format(time); } }
3,455
30.135135
119
java