Class Wallet
- All Implemented Interfaces:
AddressParser
,NewBestBlockListener
,ReorganizeListener
,TransactionReceivedInBlockListener
,PeerFilterProvider
,TransactionBag
,TaggableObject
,KeyBag
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.
To learn more about this class, read working with the wallet.
To fill up a Wallet with transactions, you need to use it in combination with a BlockChain
and various
other objects, see the Getting started tutorial
on the website to learn more about how to set everything up.
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 (e.g. due to a block chain sync). See
autosaveToFile(File, long, TimeUnit, WalletFiles.Listener)
for more information about this.
-
Nested Class Summary
Modifier and TypeClassDescriptionstatic class
Thrown if the private keys and seed of this wallet cannot be decrypted due to the supplied encryption key or password being wrong.static enum
It's possible to calculate a wallets balance from multiple points of view.static class
Class of exceptions thrown incompleteTx(SendRequest)
.static class
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.static class
Thrown if the resultant transaction would violate the dust rules (an output that's too small to be worthwhile).static class
Thrown if the resultant transaction is too big for Bitcoin to process.static enum
Enumerates possible resolutions for missing signatures.static class
Thrown if there is more than one OP_RETURN output for the resultant transaction.static class
A SendResult is returned to you as part of sending coins to a recipient.Nested classes/interfaces inherited from interface org.bitcoinj.base.AddressParser
AddressParser.AddressParserProvider
-
Field Summary
Modifier and TypeFieldDescriptionprotected final CoinSelector
protected final ReentrantLock
protected final ReentrantLock
protected final Set<TransactionOutput>
protected final Network
protected final NetworkParameters
protected final Map<Sha256Hash,
Transaction> protected WalletFiles
protected TransactionBroadcaster
Fields inherited from class org.bitcoinj.utils.BaseTaggableObject
tags
-
Constructor Summary
ConstructorDescriptionWallet
(Network network, KeyChainGroup keyChainGroup) Creates a new, empty wallet with no transactions.Wallet
(NetworkParameters params, KeyChainGroup keyChainGroup) Deprecated. -
Method Summary
Modifier and TypeMethodDescriptionvoid
Add a pre-configured keychain to the wallet.void
addChangeEventListener
(Executor executor, WalletChangeEventListener listener) Adds an event listener object.void
Adds an event listener object.void
addCoinsReceivedEventListener
(Executor executor, WalletCoinsReceivedEventListener listener) Adds an event listener object called when coins are received.void
Adds an event listener object called when coins are received.void
addCoinsSentEventListener
(Executor executor, WalletCoinsSentEventListener listener) Adds an event listener object called when coins are sent.void
Adds an event listener object called when coins are sent.void
addCurrentKeyChangeEventListener
(Executor executor, CurrentKeyChangeEventListener listener) Adds an event listener object.void
Adds an event listener object.void
addExtension
(WalletExtension extension) By providing an object implementing theWalletExtension
interface, you can save and load arbitrary additional data that will be stored with the wallet.void
addKeyChainEventListener
(Executor executor, KeyChainEventListener listener) Adds an event listener object.void
Adds an event listener object.addOrGetExistingExtension
(WalletExtension extension) Atomically adds extension or returns an existing extension if there is one with the same id already present.void
addOrUpdateExtension
(WalletExtension extension) Either adds extension as a new extension or replaces the existing extension if one already exists with the same id.void
addReorganizeEventListener
(Executor executor, WalletReorganizeEventListener listener) Adds an event listener object.void
Adds an event listener object.void
addScriptsChangeEventListener
(Executor executor, ScriptsChangeEventListener listener) Adds an event listener object.void
Adds an event listener object.void
addTransactionConfidenceEventListener
(Executor executor, TransactionConfidenceEventListener listener) Adds an event listener object.void
Adds an event listener object.final void
Adds given transaction signer to the list of signers.void
Adds a transaction that has been associated with a particular wallet pool.boolean
addWatchedAddress
(Address address) Same asaddWatchedAddress(Address, long)
with the current time as the creation time.boolean
addWatchedAddress
(Address address, long creationTime) Deprecated.boolean
addWatchedAddress
(Address address, Instant creationTime) Adds the given address to the wallet to be watched.int
addWatchedAddresses
(List<Address> addresses) Adds the given addresses to the wallet to be watched.int
addWatchedAddresses
(List<Address> addresses, long creationTime) Deprecated.int
addWatchedAddresses
(List<Address> addresses, Instant creationTime) Adds the given addresses to the wallet to be watched.int
addWatchedScripts
(List<Script> scripts) Adds the given output scripts to the wallet to be watched.autosaveToFile
(File f, long delayTime, TimeUnit timeUnit, WalletFiles.Listener eventListener) Deprecated.autosaveToFile
(File f, Duration delay, WalletFiles.Listener eventListener) Sets up the wallet to auto-save itself to the given file, using temp files with atomic renames to ensure consistency.void
Called on all registered filter providers beforePeerFilterProvider.getBloomFilterElementCount()
andPeerFilterProvider.getBloomFilter(int, double, int)
are called.Returns a list of the outputs that can potentially be spent, i.e.calculateAllSpendCandidates
(boolean excludeImmatureCoinbases, boolean excludeUnsignable) Returns a list of all outputs that are being tracked by this wallet either from theUTXOProvider
(in this case the existence or not of private keys is ignored), or the wallets internal storage (the default) taking into account the flags.protected List<TransactionOutput>
calculateAllSpendCandidatesFromUTXOProvider
(boolean excludeImmatureCoinbases) Returns the spendable candidates from theUTXOProvider
based on keys that the wallet contains.boolean
canSignFor
(Script script) Returns true if this wallet has at least one of the private keys needed to sign for this scriptPubKey.void
changeEncryptionKey
(KeyCrypter keyCrypter, AesKey currentAesKey, AesKey newAesKey) Changes wallet AES encryption key, this is atomic operation.void
changeEncryptionPassword
(CharSequence currentPassword, CharSequence newPassword) Changes wallet encryption password, this is atomic operation.boolean
checkAESKey
(AesKey aesKey) Check whether the AES key can decrypt the first encrypted key in the wallet.boolean
Used byPeer
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.boolean
checkPassword
(CharSequence password) Check whether the password can decrypt the first key in the wallet.void
cleanup()
Clean up the wallet.void
void
clearTransactions
(int fromHeight) Deletes transactions which appeared above the given block height from the wallet, but does not touch the keys.void
commitTx
(Transaction 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.void
completeTx
(SendRequest req) Given a spend request containing an incomplete transaction, makes it valid by adding outputs and signed inputs according to the instructions in the request.static Wallet
createBasic
(Network network) Creates a new, empty wallet with just a basic keychain and no transactions.static Wallet
createBasic
(NetworkParameters params) Deprecated.static Wallet
createDeterministic
(Network network, ScriptType outputScriptType) Creates a new, empty wallet with a randomly chosen seed and no transactions.static Wallet
createDeterministic
(Network network, ScriptType outputScriptType, KeyChainGroupStructure keyChainGroupStructure) Creates a new, empty wallet with a randomly chosen seed and no transactions.static Wallet
createDeterministic
(NetworkParameters params, ScriptType outputScriptType) Deprecated.static Wallet
createDeterministic
(NetworkParameters params, ScriptType outputScriptType, KeyChainGroupStructure keyChainGroupStructure) Deprecated.createSend
(Address address, Coin value) Statelessly creates a transaction that sends the given value to address.createSend
(Address address, Coin value, boolean allowUnconfirmed) Statelessly creates a transaction that sends the given value to address.currentAddress
(KeyChain.KeyPurpose purpose) Returns address for acurrentKey(KeyChain.KeyPurpose)
Returns the address used for change outputs.currentKey
(KeyChain.KeyPurpose purpose) 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 isKeyChain.KeyPurpose.RECEIVE_FUNDS
.An alias for callingcurrentAddress(KeyChain.KeyPurpose)
withKeyChain.KeyPurpose.RECEIVE_FUNDS
as the parameter.An alias for callingcurrentKey(KeyChain.KeyPurpose)
withKeyChain.KeyPurpose.RECEIVE_FUNDS
as the parameter.void
decrypt
(CharSequence password) Decrypt the wallet with the wallets keyCrypter and password.void
Decrypt the wallet with the wallets keyCrypter and AES key.void
deserializeExtension
(WalletExtension extension, byte[] data) Deserialize the wallet extension with the supplied data and then install it, replacing any existing extension that may have existed with the same ID.doMaintenance
(AesKey aesKey, boolean 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.doMaintenance
(KeyChainGroupStructure structure, AesKey aesKey, boolean 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.Returns the earliest creation time of keys or watched scripts in this wallet, ie the min ofECKey.getCreationTime()
.void
encrypt
(CharSequence password) Convenience wrapper aroundencrypt(KeyCrypter, AesKey)
which uses the default Scrypt key derivation algorithm and parameters to derive a key from the given password.void
encrypt
(KeyCrypter keyCrypter, AesKey aesKey) Encrypt the wallet using the KeyCrypter and the AES key.void
findKeyFromAddress
(Address address) Locates a keypair from the wallet given the corresponding address.findKeyFromPubKey
(byte[] pubKey) Locates a keypair from the basicKeyChain given the raw public key bytes.findKeyFromPubKeyHash
(byte[] pubKeyHash, ScriptType scriptType) Locates a keypair from the basicKeyChain given the hash of the public key.findRedeemDataFromScriptHash
(byte[] payToScriptHash) Locates a redeem data (redeem script and keys) from the keyChainGroup given the hash of the script.freshAddress
(KeyChain.KeyPurpose purpose) Returns address for afreshKey(KeyChain.KeyPurpose)
freshKey
(KeyChain.KeyPurpose purpose) Returns a key that has not been returned by this method before (fresh).freshKeys
(KeyChain.KeyPurpose purpose, int numberOfKeys) Returns a key/s that has not been returned by this method before (fresh).An alias for callingfreshAddress(KeyChain.KeyPurpose)
withKeyChain.KeyPurpose.RECEIVE_FUNDS
as the parameter.freshReceiveAddress
(ScriptType scriptType) Returns a fresh receive address for a givenScriptType
.An alias for callingfreshKey(KeyChain.KeyPurpose)
withKeyChain.KeyPurpose.RECEIVE_FUNDS
as the parameter.static Wallet
fromMasterKey
(Network network, DeterministicKey masterKey, ScriptType outputScriptType, ChildNumber accountNumber) Creates a spending wallet that tracks payments to and from a BIP32-style HD key hierarchy rooted bymasterKey
andaccountNumber
.static Wallet
fromMasterKey
(NetworkParameters params, DeterministicKey masterKey, ScriptType outputScriptType, ChildNumber accountNumber) static Wallet
fromSeed
(Network network, DeterministicSeed seed, ScriptType outputScriptType) static Wallet
fromSeed
(Network network, DeterministicSeed seed, ScriptType outputScriptType, List<ChildNumber> accountPath) static Wallet
fromSeed
(Network network, DeterministicSeed seed, ScriptType outputScriptType, KeyChainGroupStructure structure) static Wallet
fromSeed
(NetworkParameters params, DeterministicSeed seed, ScriptType outputScriptType) Deprecated.static Wallet
fromSeed
(NetworkParameters params, DeterministicSeed seed, ScriptType outputScriptType, List<ChildNumber> accountPath) Deprecated.static Wallet
fromSeed
(NetworkParameters params, DeterministicSeed seed, ScriptType outputScriptType, KeyChainGroupStructure structure) static Wallet
fromSpendingKey
(Network network, DeterministicKey spendKey, ScriptType outputScriptType) Creates a wallet that tracks payments to and from the HD key hierarchy rooted by the given spending key.static Wallet
fromSpendingKey
(NetworkParameters params, DeterministicKey spendKey, ScriptType outputScriptType) Deprecated.static Wallet
fromSpendingKeyB58
(Network network, String spendingKeyB58) Creates a wallet that tracks payments to and from the HD key hierarchy rooted by the given spending key.static Wallet
fromSpendingKeyB58
(Network network, String spendingKeyB58, Instant creationTime) Creates a wallet that tracks payments to and from the HD key hierarchy rooted by the given spending key.static Wallet
fromSpendingKeyB58
(NetworkParameters params, String spendingKeyB58) Deprecated.static Wallet
fromSpendingKeyB58
(NetworkParameters params, String spendingKeyB58, long creationTimeSeconds) Deprecated.static Wallet
fromSpendingKeyB58
(NetworkParameters params, String spendingKeyB58, Instant creationTime) Deprecated.static Wallet
fromWatchingKey
(Network network, DeterministicKey watchKey, ScriptType outputScriptType) Creates a wallet that tracks payments to and from the HD key hierarchy rooted by the given watching key.static Wallet
fromWatchingKey
(NetworkParameters params, DeterministicKey watchKey, ScriptType outputScriptType) Deprecated.static Wallet
fromWatchingKeyB58
(Network network, String watchKeyB58) Creates a wallet that tracks payments to and from the HD key hierarchy rooted by the given watching key.static Wallet
fromWatchingKeyB58
(Network network, String watchKeyB58, Instant creationTime) Creates a wallet that tracks payments to and from the HD key hierarchy rooted by the given watching key.static Wallet
fromWatchingKeyB58
(NetworkParameters params, String watchKeyB58) Deprecated.static Wallet
fromWatchingKeyB58
(NetworkParameters params, String watchKeyB58, long creationTimeSeconds) Deprecated.static Wallet
fromWatchingKeyB58
(NetworkParameters params, String watchKeyB58, Instant creationTime) Deprecated.Gets the default active keychain viaKeyChainGroup.getActiveKeyChain()
.Gets the active keychains viaKeyChainGroup.getActiveKeyChains(Instant)
.Returns the AVAILABLE balance of this wallet.getBalance
(CoinSelector selector) Returns the balance that would be considered spendable by the given coin selector, including watched outputs (i.e.getBalance
(Wallet.BalanceType balanceType) Returns the balance of this wallet as calculated by the provided balanceType.getBalanceFuture
(Coin value, Wallet.BalanceType type) Returns a future that will complete when the balance of the given type has becom equal or larger to the given value.getBloomFilter
(double falsePositiveRate) Gets a bloom filter that contains all of the public keys from this wallet, and which will provide the given false-positive rate.getBloomFilter
(int size, double falsePositiveRate, int nTweak) 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.int
Returns the number of distinct data items (note: NOT keys) that will be inserted into a bloom filter, when it is constructed.Returns the defaultCoinSelector
object that is used by this wallet if no custom selector is specified.Get the description of the wallet.org.bitcoinj.protobuf.wallet.Protos.Wallet.EncryptionType
Get the type of encryption used for this wallet.Returns a snapshot of all registered extension objects.Returns a list of the non-deterministic keys that have been imported into the wallet, or the empty list if none.Returns only the addresses that have been issued byfreshReceiveKey()
,freshReceiveAddress()
,currentReceiveKey()
orcurrentReceiveAddress()
.Returns only the keys that have been issued byfreshReceiveKey()
,freshReceiveAddress()
,currentReceiveKey()
orcurrentReceiveAddress()
.getKeyByPath
(List<ChildNumber> path) Returns a key for the given HD path, assuming it's already been derived.int
int
SeeDeterministicKeyChain.setLookaheadSize(int)
for more info on this.int
SeeDeterministicKeyChain.setLookaheadThreshold(int)
for more info on this.int
Returns the number of keys in the key chain group, including lookahead keys.Returns the immutable seed for the current active HD chain.Get the wallet's KeyCrypter, or null if the wallet is not encrypted.Deprecated.Returns the hash of the last seen best-chain block, or null if the wallet is too old to store this data.int
Returns the height of the last seen best-chain block.Deprecated.long
Deprecated.Deprecated.Usenetwork()
Deprecated.Usenetwork()
Returns an immutable view of the transactions currently waiting for network confirmations.int
getRecentTransactions
(int numTransactions, boolean includeDead) Returns an list of N transactions, ordered by increasing age.Gets the currentRiskAnalysis
implementation.Get all theUTXO
's from theUTXOProvider
based on keys that the wallet contains.Returns the amount of bitcoin ever received via output.Returns the amount of bitcoin ever sent via output.getTransaction
(Sha256Hash hash) Returns a transaction object given its hash, if it exists in this wallet, or null otherwise.Returns transactions from a specific pool.getTransactions
(boolean includeDead) Returns a set of all transactions in the wallet.Returns all non-dead, active transactions ordered by recency.Returns a copy of the internal unspent outputs listGet theUTXOProvider
.int
Get the version of the Wallet.Returns a set of all WalletTransactions in the wallet.Returns all addresses watched by this wallet.getWatchedOutputs
(boolean excludeImmatureCoinbases) Returns all the outputs that match addresses or scripts added viaaddWatchedAddress(Address)
oraddWatchedScripts(java.util.List)
.Returns a snapshot of the watched scripts.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.boolean
Returns true if the given key is in the wallet, false otherwise.boolean
Imports the given ECKey to the wallet.int
importKeys
(List<ECKey> keys) Imports the given keys to the wallet.int
importKeysAndEncrypt
(List<ECKey> keys, CharSequence password) Takes a list of keys and a password, then encrypts and imports them in one step using the current keycrypter.int
importKeysAndEncrypt
(List<ECKey> keys, AesKey aesKey) Takes a list of keys and an AES key, then encrypts and imports them in one step using the current keycrypter.boolean
SeesetAcceptRiskyTransactions(boolean)
for an explanation of this property.boolean
isAddressMine
(Address address) Returns true if the address is belongs to this wallet.boolean
isAddressWatched
(Address address) Return true if we are watching this address.boolean
Returns if this wallet is structurally consistent, so e.g.void
Variant ofisConsistent()
that throws anIllegalStateException
describing the first inconsistency.boolean
isDeterministicUpgradeRequired
(ScriptType outputScriptType) Returns true if the wallet contains random keys and no HD chains, in which case you should callupgradeToDeterministic(ScriptType, AesKey)
before attempting to do anything that would require a new address or key.boolean
Returns true if the wallet is encrypted using any scheme, false if not.boolean
isKeyRotating
(ECKey key) Returns whether the keys creation time is before the key rotation time, if one was set.boolean
isPayToScriptHashMine
(byte[] payToScriptHash) Returns true if this wallet knows the script corresponding to the given hash.boolean
This method is used by aPeer
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.boolean
isPubKeyHashMine
(byte[] pubKeyHash, ScriptType scriptType) Look for a public key which hashes to the given hash and (optionally) is used for a specific script type.boolean
isPubKeyMine
(byte[] pubKey) Returns true if this wallet contains a keypair with the given public key.boolean
Determine if a transaction is mature.boolean
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.boolean
isTransactionRisky
(Transaction tx, List<Transaction> dependencies) 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.boolean
isWatchedScript
(Script script) Returns true if this wallet is watching transactions for outputs with the script.boolean
Returns whether this wallet consists entirely of watching keys (unencrypted keys with no private part).Returns the key rotation time, or empty if unconfigured.Returns time extracted from the last best seen block header, or empty.static Wallet
loadFromFile
(File file, WalletExtension... walletExtensions) Returns a wallet deserialized from the given file.static Wallet
loadFromFile
(File file, WalletProtobufSerializer.WalletFactory factory, boolean forceReset, boolean ignoreMandatoryExtensions, WalletExtension... walletExtensions) Returns a wallet deserialized from the given file.static Wallet
loadFromFileStream
(InputStream stream, WalletExtension... walletExtensions) Returns a wallet deserialized from the given input stream and wallet extensions.static Wallet
loadFromFileStream
(InputStream stream, WalletProtobufSerializer.WalletFactory factory, boolean forceReset, boolean ignoreMandatoryExtensions, WalletExtension... walletExtensions) Returns a wallet deserialized from the given input stream and wallet extensions.boolean
Updates the wallet with the given transaction: puts it into the pending pool, sets the spent flags and runs the onCoinsSent/onCoinsReceived event listener.protected void
network()
void
notifyNewBestBlock
(StoredBlock block) Called by theBlockChain
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 (thereorganize(StoredBlock, List, List)
method will call this one in that case).boolean
notifyTransactionIsInBlock
(Sha256Hash txHash, StoredBlock block, AbstractBlockChain.NewBlockType blockType, int relativityOffset) Called by theBlockChain
when we receive a new filtered block that contains a transactions previously received by a call toreceivePending(org.bitcoinj.core.Transaction, java.util.List<org.bitcoinj.core.Transaction>, boolean)
.parseAddress
(String addressString) Parse an address string using all formats this wallet knows about for the wallet's network typeboolean
poolContainsTxHash
(WalletTransaction.Pool pool, Sha256Hash txHash) protected void
queueOnCoinsReceived
(Transaction tx, Coin balance, Coin newBalance) protected void
queueOnCoinsSent
(Transaction tx, Coin prevBalance, Coin newBalance) protected void
protected void
queueOnScriptsChanged
(List<Script> scripts, boolean isAddingScripts) void
receiveFromBlock
(Transaction tx, StoredBlock block, AbstractBlockChain.NewBlockType blockType, int relativityOffset) Called by theBlockChain
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).void
receivePending
(Transaction tx, List<Transaction> dependencies) Called when we have found a transaction (via network broadcast or otherwise) that is relevant to this wallet and want to record it.void
receivePending
(Transaction tx, List<Transaction> dependencies, boolean overrideIsRelevant) Called when we have found a transaction (via network broadcast or otherwise) that is relevant to this wallet and want to record it.boolean
Removes the given event listener object.boolean
Removes the given event listener object.boolean
Removes the given event listener object.boolean
Removes the given event listener object.boolean
Removes the given key from the basicKeyChain.boolean
Removes the given event listener object.boolean
Removes the given event listener object.boolean
Removes the given event listener object.boolean
Removes the given event listener object.boolean
removeWatchedAddress
(Address address) Removes the given output scripts from the wallet that were being watched.boolean
removeWatchedAddresses
(List<Address> addresses) Removes the given output scripts from the wallet that were being watched.boolean
removeWatchedScripts
(List<Script> scripts) Removes the given output scripts from the wallet that were being watched.void
reorganize
(StoredBlock splitPoint, List<StoredBlock> oldBlocks, List<StoredBlock> newBlocks) Don't call this directly.void
reset()
Prepares the wallet for a blockchain replay.protected void
Requests an asynchronous save on a background threadprotected void
saveNow()
If auto saving is enabled, do an immediate sync write to disk ignoring any delays.void
saveToFile
(File f) Uses protobuf serialization to save the wallet to the given file.void
saveToFile
(File tempFile, File destFile) Saves the wallet first to the given temporary file, then renames to the destination file.void
Uses protobuf serialization to save the wallet to the given file stream.sendCoins
(Peer peer, SendRequest request) Sends coins to the given address, via the givenPeer
.sendCoins
(TransactionBroadcaster broadcaster, Address to, Coin value) Sends coins to the given address, via the givenPeerGroup
.sendCoins
(TransactionBroadcaster broadcaster, SendRequest request) Sends coins according to the given request, via the givenTransactionBroadcaster
.sendCoins
(SendRequest request) Satisfies the givenSendRequest
using the default transaction broadcaster configured either viaPeerGroup.addWallet(Wallet)
or directly withsetTransactionBroadcaster(TransactionBroadcaster)
.sendCoinsOffline
(SendRequest request) Sends coins to the given address but does not broadcast the resulting pending transaction.sendTransaction
(SendRequest sendRequest) Initiate sending the transaction in aSendRequest
.List<org.bitcoinj.protobuf.wallet.Protos.Key>
Deprecated.void
setAcceptRiskyTransactions
(boolean acceptRiskyTransactions) Whether or not the wallet will ignore pending transactions that fail the selectedRiskAnalysis
.void
setDescription
(String description) Set the description of the wallet.void
setKeyRotationTime
(long timeSecs) Deprecated.void
setKeyRotationTime
(Instant keyRotationTime) 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.void
setKeyRotationTime
(Date time) Deprecated.void
setLastBlockSeenHash
(Sha256Hash lastBlockSeenHash) void
setLastBlockSeenHeight
(int lastBlockSeenHeight) void
setLastBlockSeenTime
(Instant time) void
setLastBlockSeenTimeSecs
(long timeSecs) Deprecated.void
setRiskAnalyzer
(RiskAnalysis.Analyzer analyzer) Sets theRiskAnalysis
implementation to use for deciding whether received pending transactions are risky or not.void
Deprecated.Applications should use another mechanism to persist application state informationvoid
setTransactionBroadcaster
(TransactionBroadcaster broadcaster) Specifies that the givenTransactionBroadcaster
, typically aPeerGroup
, should be used for sending transactions to the Bitcoin network by default.void
setUTXOProvider
(UTXOProvider provider) Set theUTXOProvider
.void
setVersion
(int version) Set the version number of the wallet.void
Disables auto-saving, after it had been enabled withautosaveToFile(File, long, TimeUnit, WalletFiles.Listener)
before.void
Given a send request containing transaction, attempts to sign it's inputs.toString()
toString
(boolean includeLookahead, boolean includePrivateKeys, AesKey aesKey, boolean includeTransactions, boolean includeExtensions, AbstractBlockChain chain) Formats the wallet as a human-readable piece of text.void
upgradeToDeterministic
(ScriptType outputScriptType, AesKey aesKey) Upgrades the wallet to be deterministic (BIP32).void
upgradeToDeterministic
(ScriptType outputScriptType, KeyChainGroupStructure structure, AesKey aesKey) Upgrades the wallet to be deterministic (BIP32).Wait for at least 1 confirmation on a transaction.waitForConfirmations
(Transaction tx, int requiredConfirmations) Wait for a required number of confirmations on a transaction.Methods inherited from class org.bitcoinj.utils.BaseTaggableObject
getTag, getTags, maybeGetTag
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait
Methods inherited from interface org.bitcoinj.core.PeerFilterProvider
getEarliestKeyCreationTime
-
Field Details
-
lock
-
keyChainGroupLock
-
transactions
-
myUnspents
-
network
-
params
-
vFileManager
-
vTransactionBroadcaster
-
coinSelector
-
-
Constructor Details
-
Wallet
Creates a new, empty wallet with no transactions. If you haven't already done so, make sure to provide for sufficient backup of the keys in theKeyChainGroup
. To restore a wallet from disk instead, seeloadFromFile(java.io.File, org.bitcoinj.wallet.WalletExtension...)
.- Parameters:
network
- network wallet will operate onkeyChainGroup
- keychain group to manage keychains
-
Wallet
-
-
Method Details
-
createDeterministic
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, seeloadFromFile(java.io.File, org.bitcoinj.wallet.WalletExtension...)
.- Parameters:
network
- network wallet will operate onoutputScriptType
- type of addresses (aka output scripts) to generate for receiving- Returns:
- A new empty wallet
-
createDeterministic
@Deprecated public static Wallet createDeterministic(NetworkParameters params, ScriptType outputScriptType) Deprecated. -
createDeterministic
public static Wallet createDeterministic(Network network, ScriptType outputScriptType, KeyChainGroupStructure keyChainGroupStructure) 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, seeloadFromFile(java.io.File, org.bitcoinj.wallet.WalletExtension...)
.- Parameters:
network
- network wallet will operate onoutputScriptType
- type of addresses (aka output scripts) to generate for receivingkeyChainGroupStructure
- structure (e.g. BIP32 or BIP43)- Returns:
- A new empty wallet
-
createDeterministic
@Deprecated public static Wallet createDeterministic(NetworkParameters params, ScriptType outputScriptType, KeyChainGroupStructure keyChainGroupStructure) Deprecated. -
createBasic
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.- Parameters:
network
- network wallet will operate on
-
createBasic
Deprecated. -
fromSeed
- Parameters:
network
- network wallet will operate onseed
- deterministic seedoutputScriptType
- type of addresses (aka output scripts) to generate for receiving- Returns:
- a wallet from a deterministic seed with a default account path
-
fromSeed
@Deprecated public static Wallet fromSeed(NetworkParameters params, DeterministicSeed seed, ScriptType outputScriptType) Deprecated. -
fromSeed
public static Wallet fromSeed(Network network, DeterministicSeed seed, ScriptType outputScriptType, KeyChainGroupStructure structure) - Parameters:
network
- network wallet will operate onseed
- deterministic seedoutputScriptType
- type of addresses (aka output scripts) to generate for receivingstructure
- structure for your wallet- Returns:
- a wallet from a deterministic seed with a default account path
-
fromSeed
@Deprecated public static Wallet fromSeed(NetworkParameters params, DeterministicSeed seed, ScriptType outputScriptType, KeyChainGroupStructure structure) -
fromSeed
public static Wallet fromSeed(Network network, DeterministicSeed seed, ScriptType outputScriptType, List<ChildNumber> accountPath) - Parameters:
network
- network wallet will operate onseed
- deterministic seedoutputScriptType
- type of addresses (aka output scripts) to generate for receivingaccountPath
- account path to generate receiving addresses on- Returns:
- an instance of a wallet from a deterministic seed.
-
fromSeed
@Deprecated public static Wallet fromSeed(NetworkParameters params, DeterministicSeed seed, ScriptType outputScriptType, List<ChildNumber> accountPath) Deprecated. -
fromWatchingKey
public static Wallet fromWatchingKey(Network network, DeterministicKey watchKey, ScriptType outputScriptType) 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 byDeterministicKeyChain.getWatchingKey()
. -
fromWatchingKey
@Deprecated public static Wallet fromWatchingKey(NetworkParameters params, DeterministicKey watchKey, ScriptType outputScriptType) Deprecated. -
fromWatchingKeyB58
Creates a wallet that tracks payments to and from the HD key hierarchy rooted by the given watching key. The account path is specified.- Parameters:
network
- network wallet will operate onwatchKeyB58
- The key in base58 notationcreationTime
- creation time of the key (if unknown usefromWatchingKeyB58(Network, String)
- Returns:
- a new wallet
-
fromWatchingKeyB58
@Deprecated public static Wallet fromWatchingKeyB58(NetworkParameters params, String watchKeyB58, Instant creationTime) Deprecated. -
fromWatchingKeyB58
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 toDeterministicHierarchy.BIP32_STANDARDISATION_TIME
- Parameters:
network
- network wallet will operate onwatchKeyB58
- The key in base58 notation- Returns:
- a new wallet
-
fromWatchingKeyB58
Deprecated. -
fromWatchingKeyB58
@Deprecated public static Wallet fromWatchingKeyB58(NetworkParameters params, String watchKeyB58, long creationTimeSeconds) Deprecated. -
fromSpendingKey
public static Wallet fromSpendingKey(Network network, DeterministicKey spendKey, ScriptType outputScriptType) 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 byDeterministicKeyChain.getWatchingKey()
. This wallet can also spend.- Parameters:
network
- network wallet will operate on
-
fromSpendingKey
@Deprecated public static Wallet fromSpendingKey(NetworkParameters params, DeterministicKey spendKey, ScriptType outputScriptType) Deprecated. -
fromSpendingKeyB58
public static Wallet fromSpendingKeyB58(Network network, String spendingKeyB58, Instant creationTime) Creates a wallet that tracks payments to and from the HD key hierarchy rooted by the given spending key.- Parameters:
network
- network wallet will operate onspendingKeyB58
- The key in base58 notationcreationTime
- creation time of the key (if unknown usefromWatchingKeyB58(Network, String)
- Returns:
- a new wallet
-
fromSpendingKeyB58
@Deprecated public static Wallet fromSpendingKeyB58(NetworkParameters params, String spendingKeyB58, Instant creationTime) Deprecated. -
fromSpendingKeyB58
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 toDeterministicHierarchy.BIP32_STANDARDISATION_TIME
.- Parameters:
network
- network wallet will operate onspendingKeyB58
- The key in base58 notation- Returns:
- a new wallet
-
fromSpendingKeyB58
@Deprecated public static Wallet fromSpendingKeyB58(NetworkParameters params, String spendingKeyB58) Deprecated. -
fromSpendingKeyB58
@Deprecated public static Wallet fromSpendingKeyB58(NetworkParameters params, String spendingKeyB58, long creationTimeSeconds) Deprecated. -
fromMasterKey
public static Wallet fromMasterKey(Network network, DeterministicKey masterKey, ScriptType outputScriptType, ChildNumber accountNumber) Creates a spending wallet that tracks payments to and from a BIP32-style HD key hierarchy rooted bymasterKey
andaccountNumber
. The account path must be directly below the master key as in BIP-32.This method should not be used for BIP-43 compliant wallets or accounts not of the form
m/accountNumber'
.This wallet will not store the
masterKey
, only the account key.- Parameters:
network
- network the wallet will operate onmasterKey
- root private key (e.g. pathm
)outputScriptType
- type of addresses (aka output scripts) to generate for receivingaccountNumber
- account number to append, resulting in an account path ofm/accountNumber'
- Returns:
- newly created Wallet object
-
fromMasterKey
@Deprecated public static Wallet fromMasterKey(NetworkParameters params, DeterministicKey masterKey, ScriptType outputScriptType, ChildNumber accountNumber) -
network
-
getNetworkParameters
Deprecated.Usenetwork()
-
parseAddress
Parse an address string using all formats this wallet knows about for the wallet's network type- Specified by:
parseAddress
in interfaceAddressParser
- Parameters:
addressString
- Address string to parse- Returns:
- A validated address
- Throws:
AddressFormatException
- if invalid string
-
getActiveKeyChains
Gets the active keychains viaKeyChainGroup.getActiveKeyChains(Instant)
. -
getActiveKeyChain
Gets the default active keychain viaKeyChainGroup.getActiveKeyChain()
. -
addTransactionSigner
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.
Transaction signer should be fully initialized before adding to the wallet, otherwise
IllegalStateException
will be thrown -
getTransactionSigners
-
currentKey
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 isKeyChain.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). -
currentReceiveKey
An alias for callingcurrentKey(KeyChain.KeyPurpose)
withKeyChain.KeyPurpose.RECEIVE_FUNDS
as the parameter. -
currentAddress
Returns address for acurrentKey(KeyChain.KeyPurpose)
-
currentReceiveAddress
An alias for callingcurrentAddress(KeyChain.KeyPurpose)
withKeyChain.KeyPurpose.RECEIVE_FUNDS
as the parameter. -
freshKey
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 aDeterministicKeyChain
. When the parameter isKeyChain.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. -
freshKeys
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 aDeterministicKeyChain
. When the parameter isKeyChain.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. -
freshReceiveKey
An alias for callingfreshKey(KeyChain.KeyPurpose)
withKeyChain.KeyPurpose.RECEIVE_FUNDS
as the parameter. -
freshAddress
Returns address for afreshKey(KeyChain.KeyPurpose)
-
freshReceiveAddress
An alias for callingfreshAddress(KeyChain.KeyPurpose)
withKeyChain.KeyPurpose.RECEIVE_FUNDS
as the parameter. -
freshReceiveAddress
Returns a fresh receive address for a given
ScriptType
.This method is meant for when you really need a fallback address. Normally, you should be using
freshAddress(KeyChain.KeyPurpose)
orcurrentAddress(KeyChain.KeyPurpose)
. -
getIssuedReceiveKeys
Returns only the keys that have been issued byfreshReceiveKey()
,freshReceiveAddress()
,currentReceiveKey()
orcurrentReceiveAddress()
. -
getIssuedReceiveAddresses
Returns only the addresses that have been issued byfreshReceiveKey()
,freshReceiveAddress()
,currentReceiveKey()
orcurrentReceiveAddress()
. -
upgradeToDeterministic
public void upgradeToDeterministic(ScriptType outputScriptType, @Nullable AesKey aesKey) throws DeterministicUpgradeRequiresPassword 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 must 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). -
upgradeToDeterministic
public void upgradeToDeterministic(ScriptType outputScriptType, KeyChainGroupStructure structure, @Nullable AesKey aesKey) throws DeterministicUpgradeRequiresPassword 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 must 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). -
isDeterministicUpgradeRequired
Returns true if the wallet contains random keys and no HD chains, in which case you should callupgradeToDeterministic(ScriptType, AesKey)
before attempting to do anything that would require a new address or key. -
getWatchedScripts
Returns a snapshot of the watched scripts. This view is not live. -
removeKey
Removes the given key from the basicKeyChain. Be very careful with this - losing a private key destroys the money associated with it.- Returns:
- Whether the key was removed or not.
-
getKeyChainGroupSize
public int getKeyChainGroupSize()Returns the number of keys in the key chain group, including lookahead keys. -
getKeyChainGroupCombinedKeyLookaheadEpochs
public int getKeyChainGroupCombinedKeyLookaheadEpochs() -
getImportedKeys
Returns a list of the non-deterministic keys that have been imported into the wallet, or the empty list if none. -
currentChangeAddress
Returns the address used for change outputs. Note: this will probably go away in future. -
importKey
Imports the given ECKey to the wallet.
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.
-
importKeys
Imports the given keys to the wallet. IfautosaveToFile(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. -
importKeysAndEncrypt
Takes a list of keys and a password, then encrypts and imports them in one step using the current keycrypter. -
importKeysAndEncrypt
Takes a list of keys and an AES key, then encrypts and imports them in one step using the current keycrypter. -
addAndActivateHDChain
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). -
getKeyChainGroupLookaheadSize
public int getKeyChainGroupLookaheadSize()SeeDeterministicKeyChain.setLookaheadSize(int)
for more info on this. -
getKeyChainGroupLookaheadThreshold
public int getKeyChainGroupLookaheadThreshold()SeeDeterministicKeyChain.setLookaheadThreshold(int)
for more info on this. -
getWatchingKey
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. -
isWatching
public boolean isWatching()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.
-
isAddressWatched
Return true if we are watching this address. -
addWatchedAddress
Same asaddWatchedAddress(Address, long)
with the current time as the creation time. -
addWatchedAddress
Adds the given address to the wallet to be watched. Outputs can be retrieved bygetWatchedOutputs(boolean)
.- Parameters:
creationTime
- creation time, for scanning the blockchain- Returns:
- whether the address was added successfully (not already present)
-
addWatchedAddress
Deprecated. -
addWatchedAddresses
Adds the given addresses to the wallet to be watched. Outputs can be retrieved bygetWatchedOutputs(boolean)
.- Parameters:
addresses
- addresses to be watchedcreationTime
- creation time of the addresses- Returns:
- how many addresses were added successfully
-
addWatchedAddresses
Adds the given addresses to the wallet to be watched. Outputs can be retrieved bygetWatchedOutputs(boolean)
. Use this if the creation time of the addresses is unknown.- Parameters:
addresses
- addresses to be watched- Returns:
- how many addresses were added successfully
-
addWatchedAddresses
Deprecated. -
addWatchedScripts
Adds the given output scripts to the wallet to be watched. Outputs can be retrieved bygetWatchedOutputs(boolean)
. If a script is already being watched, the object is replaced with the one in the given list. AsScript
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.- Returns:
- how many scripts were added successfully
-
removeWatchedAddress
Removes the given output scripts from the wallet that were being watched.- Returns:
- true if successful
-
removeWatchedAddresses
Removes the given output scripts from the wallet that were being watched.- Returns:
- true if successful
-
removeWatchedScripts
Removes the given output scripts from the wallet that were being watched.- Returns:
- true if successful
-
getWatchedAddresses
Returns all addresses watched by this wallet. -
findKeyFromPubKeyHash
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.- Specified by:
findKeyFromPubKeyHash
in interfaceKeyBag
- Parameters:
pubKeyHash
- hash of the keypair to look forscriptType
- only look for given usage (currentlyScriptType.P2PKH
orScriptType.P2WPKH
) ornull
if we don't care- Returns:
- ECKey object or null if no such key was found.
-
hasKey
Returns true if the given key is in the wallet, false otherwise. Currently an O(N) operation. -
isAddressMine
Returns true if the address is belongs to this wallet. -
isPubKeyHashMine
Description copied from interface:TransactionBag
Look for a public key which hashes to the given hash and (optionally) is used for a specific script type.- Specified by:
isPubKeyHashMine
in interfaceTransactionBag
- Parameters:
pubKeyHash
- hash of the public key to look forscriptType
- only look for given usage (currentlyScriptType.P2PKH
orScriptType.P2WPKH
) ornull
if we don't care- Returns:
- true if hash was found
-
isWatchedScript
Description copied from interface:TransactionBag
Returns true if this wallet is watching transactions for outputs with the script.- Specified by:
isWatchedScript
in interfaceTransactionBag
-
findKeyFromAddress
Locates a keypair from the wallet given the corresponding address.- Returns:
- ECKey or null if no such key was found.
-
findKeyFromPubKey
Locates a keypair from the basicKeyChain given the raw public key bytes.- Specified by:
findKeyFromPubKey
in interfaceKeyBag
- Returns:
- ECKey or null if no such key was found.
-
isPubKeyMine
public boolean isPubKeyMine(byte[] pubKey) Description copied from interface:TransactionBag
Returns true if this wallet contains a keypair with the given public key.- Specified by:
isPubKeyMine
in interfaceTransactionBag
-
findRedeemDataFromScriptHash
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.- Specified by:
findRedeemDataFromScriptHash
in interfaceKeyBag
-
isPayToScriptHashMine
public boolean isPayToScriptHashMine(byte[] payToScriptHash) Description copied from interface:TransactionBag
Returns true if this wallet knows the script corresponding to the given hash.- Specified by:
isPayToScriptHashMine
in interfaceTransactionBag
-
getKeyChainSeed
Returns the immutable seed for the current active HD chain.- Throws:
ECKey.MissingPrivateKeyException
- if the seed is unavailable (watching wallet)
-
getKeyByPath
Returns a key for the given HD path, assuming it's already been derived. You normally shouldn't use this: use currentReceiveKey/freshReceiveKey instead. -
encrypt
Convenience wrapper aroundencrypt(KeyCrypter, AesKey)
which uses the default Scrypt key derivation algorithm and parameters to derive a key from the given password. -
encrypt
Encrypt the wallet using the KeyCrypter and the AES key. A good default KeyCrypter to use isKeyCrypterScrypt
.- Parameters:
keyCrypter
- The KeyCrypter that specifies how to encrypt/ decrypt a keyaesKey
- 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.
-
decrypt
Decrypt the wallet with the wallets keyCrypter and password.- Throws:
Wallet.BadWalletEncryptionKeyException
- Thrown if the given password is wrong. If so, the wallet state is unchanged.KeyCrypterException
- Thrown if the wallet decryption fails. If so, the wallet state is unchanged.
-
decrypt
Decrypt the wallet with the wallets keyCrypter and AES key.- Parameters:
aesKey
- AES key to use (normally created using KeyCrypter#deriveKey and cached as it is time consuming to create from a password)- Throws:
Wallet.BadWalletEncryptionKeyException
- Thrown if the given aesKey is wrong. If so, the wallet state is unchanged.KeyCrypterException
- Thrown if the wallet decryption fails. If so, the wallet state is unchanged.
-
checkPassword
Check whether the password can decrypt the first key in the wallet. This can be used to check the validity of an entered password.- Returns:
- boolean true if password supplied can decrypt the first private key in the wallet, false otherwise.
- Throws:
IllegalStateException
- if the wallet is not encrypted.
-
checkAESKey
Check whether the AES key can decrypt the first encrypted key in the wallet.- Returns:
- boolean true if AES key supplied can decrypt the first encrypted private key in the wallet, false otherwise.
-
getKeyCrypter
Get the wallet's KeyCrypter, or null if the wallet is not encrypted. (Used in encrypting/ decrypting an ECKey). -
getEncryptionType
public org.bitcoinj.protobuf.wallet.Protos.Wallet.EncryptionType getEncryptionType()Get the type of encryption used for this wallet. (This is a convenience method - the encryption type is actually stored in the keyCrypter). -
isEncrypted
public boolean isEncrypted()Returns true if the wallet is encrypted using any scheme, false if not. -
changeEncryptionPassword
public void changeEncryptionPassword(CharSequence currentPassword, CharSequence newPassword) throws Wallet.BadWalletEncryptionKeyException Changes wallet encryption password, this is atomic operation.- Throws:
Wallet.BadWalletEncryptionKeyException
- Thrown if the given currentPassword is wrong. If so, the wallet state is unchanged.KeyCrypterException
- Thrown if the wallet decryption fails. If so, the wallet state is unchanged.
-
changeEncryptionKey
public void changeEncryptionKey(KeyCrypter keyCrypter, AesKey currentAesKey, AesKey newAesKey) throws Wallet.BadWalletEncryptionKeyException Changes wallet AES encryption key, this is atomic operation.- Throws:
Wallet.BadWalletEncryptionKeyException
- Thrown if the given currentAesKey is wrong. If so, the wallet state is unchanged.KeyCrypterException
- Thrown if the wallet decryption fails. If so, the wallet state is unchanged.
-
serializeKeyChainGroupToProtobuf
Deprecated. -
saveToFile
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.- Parameters:
tempFile
- temporary file to use for saving the walletdestFile
- file to save the wallet to- Throws:
FileNotFoundException
- if directory doesn't existIOException
- if an error occurs while saving
-
saveToFile
Uses protobuf serialization to save the wallet to the given file. To learn more about this file format, seeWalletProtobufSerializer
. Writes out first to a temporary file in the same directory and then renames once written.- Parameters:
f
- File to save wallet- Throws:
FileNotFoundException
- if directory doesn't existIOException
- if an error occurs while saving
-
setAcceptRiskyTransactions
public void setAcceptRiskyTransactions(boolean acceptRiskyTransactions) Whether or not the wallet will ignore pending transactions that fail the selected
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, theDefaultRiskAnalysis
checks for non-finality of transactions.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.
-
isAcceptRiskyTransactions
public boolean isAcceptRiskyTransactions()SeesetAcceptRiskyTransactions(boolean)
for an explanation of this property. -
setRiskAnalyzer
Sets theRiskAnalysis
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 withsetAcceptRiskyTransactions(boolean)
. -
getRiskAnalyzer
Gets the currentRiskAnalysis
implementation. The default isDefaultRiskAnalysis
. -
autosaveToFile
public WalletFiles autosaveToFile(File f, Duration delay, @Nullable WalletFiles.Listener eventListener) 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.
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, e.g. 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. You should still save the wallet manually using
saveToFile(File)
when your program is about to shut down as the JVM will not wait for the background thread.An event listener can be provided. It will be called on a background thread with the wallet locked when an auto-save occurs.
- Parameters:
f
- The destination file to save to.delay
- How much time to wait until saving the wallet on a background thread.eventListener
- callback to be informed when the auto-save thread does things, or null
-
autosaveToFile
@Deprecated public WalletFiles autosaveToFile(File f, long delayTime, TimeUnit timeUnit, @Nullable WalletFiles.Listener eventListener) Deprecated. -
shutdownAutosaveAndWait
public void shutdownAutosaveAndWait()Disables auto-saving, after it had been enabled with
autosaveToFile(File, long, TimeUnit, WalletFiles.Listener)
before. This method blocks until finished. -
saveLater
protected void saveLater()Requests an asynchronous save on a background thread -
saveNow
protected void saveNow()If auto saving is enabled, do an immediate sync write to disk ignoring any delays. -
saveToFileStream
Uses protobuf serialization to save the wallet to the given file stream. To learn more about this file format, seeWalletProtobufSerializer
.- Throws:
IOException
-
getParams
Deprecated.Usenetwork()
Returns the parameters this wallet was created with. -
loadFromFile
public static Wallet loadFromFile(File file, @Nullable WalletExtension... walletExtensions) throws UnreadableWalletException Returns a wallet deserialized from the given file. Extensions previously saved with the wallet can be deserialized by calling @WalletExtension.deserializeWalletExtension(Wallet, byte[])
}- Parameters:
file
- the wallet file to readwalletExtensions
- extensions possibly added to the wallet.- Returns:
- The Wallet
- Throws:
UnreadableWalletException
- if there was a problem loading or parsing the file
-
loadFromFile
public static Wallet loadFromFile(File file, WalletProtobufSerializer.WalletFactory factory, boolean forceReset, boolean ignoreMandatoryExtensions, @Nullable WalletExtension... walletExtensions) throws UnreadableWalletException Returns a wallet deserialized from the given file. Extensions previously saved with the wallet can be deserialized by calling @WalletExtension.deserializeWalletExtension(Wallet, byte[])
}- Parameters:
file
- the wallet file to readfactory
- wallet factoryforceReset
- force a reset of the walletignoreMandatoryExtensions
- if true, mandatory extensions will be ignored instead of causing load errors (not recommended)walletExtensions
- extensions possibly added to the wallet.- Returns:
- The Wallet
- Throws:
UnreadableWalletException
- if there was a problem loading or parsing the file
-
isConsistent
public boolean isConsistent()Returns if this wallet is structurally consistent, so e.g. no duplicate transactions. First inconsistency and a dump of the wallet will be logged. -
isConsistentOrThrow
Variant ofisConsistent()
that throws anIllegalStateException
describing the first inconsistency.- Throws:
IllegalStateException
-
loadFromFileStream
public static Wallet loadFromFileStream(InputStream stream, @Nullable WalletExtension... walletExtensions) throws UnreadableWalletException Returns a wallet deserialized from the given input stream and wallet extensions.- Parameters:
stream
- An open InputStream containing a ProtoBuf WalletwalletExtensions
- extensions possibly added to the wallet.- Returns:
- The Wallet
- Throws:
UnreadableWalletException
- if there was a problem reading or parsing the stream
-
loadFromFileStream
public static Wallet loadFromFileStream(InputStream stream, WalletProtobufSerializer.WalletFactory factory, boolean forceReset, boolean ignoreMandatoryExtensions, @Nullable WalletExtension... walletExtensions) throws UnreadableWalletException Returns a wallet deserialized from the given input stream and wallet extensions.- Parameters:
stream
- An open InputStream containing a ProtoBuf Walletfactory
- wallet factoryforceReset
- if true, configure wallet to replay transactions from the blockchainignoreMandatoryExtensions
- if true, mandatory extensions will be ignored instead of causing load errors (not recommended)walletExtensions
- extensions possibly added to the wallet.- Returns:
- The Wallet
- Throws:
UnreadableWalletException
- if there was a problem reading or parsing the stream
-
notifyTransactionIsInBlock
public boolean notifyTransactionIsInBlock(Sha256Hash txHash, StoredBlock block, AbstractBlockChain.NewBlockType blockType, int relativityOffset) throws VerificationException Called by theBlockChain
when we receive a new filtered block that contains a transactions previously received by a call toreceivePending(org.bitcoinj.core.Transaction, java.util.List<org.bitcoinj.core.Transaction>, boolean)
.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.
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.
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!
- Specified by:
notifyTransactionIsInBlock
in interfaceTransactionReceivedInBlockListener
- Returns:
- whether the transaction is known about i.e. was considered relevant previously.
- Throws:
VerificationException
-
receivePending
public void receivePending(Transaction tx, @Nullable List<Transaction> dependencies, boolean overrideIsRelevant) throws VerificationException 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 cannot verify these transactions at all, 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.
This is the same as
receivePending(Transaction, List)
but allows you to override theisPendingTransactionRelevant(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).- Throws:
VerificationException
-
isTransactionRisky
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 ofisAcceptRiskyTransactions()
. Risky transactions yield a logged warning. If you want to know the reason why a transaction is risky, create an instance of theRiskAnalysis
yourself using the factory returned bygetRiskAnalyzer()
and use it directly. -
receivePending
public void receivePending(Transaction tx, @Nullable List<Transaction> dependencies) throws VerificationException 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 cannot verify these transactions at all, 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.
Before this method is called,
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.- Throws:
VerificationException
-
isPendingTransactionRelevant
This method is used by aPeer
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 thenreceivePending(Transaction, List)
will soon be called with the transactions dependencies as well.- Throws:
ScriptException
-
isTransactionRelevant
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.
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.
- Throws:
ScriptException
-
isTransactionMature
Determine if a transaction is mature. A coinbase transaction is mature if it has been confirmed at leastNetworkParameters.getSpendableCoinbaseDepth()
times. OnBitcoinNetwork.MAINNET
this value is100
. For purposes of this method, non-coinbase transactions are also considered mature.- Parameters:
tx
- the transaction to evaluate- Returns:
true
if it is a mature coinbase transaction or if it is not a coinbase transaction
-
receiveFromBlock
public void receiveFromBlock(Transaction tx, StoredBlock block, AbstractBlockChain.NewBlockType blockType, int relativityOffset) throws VerificationException Called by theBlockChain
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).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.
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.
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!
- Specified by:
receiveFromBlock
in interfaceTransactionReceivedInBlockListener
- Throws:
VerificationException
-
notifyNewBestBlock
Called by the
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 (thereorganize(StoredBlock, List, List)
method will call this one in that case).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.
- Specified by:
notifyNewBestBlock
in interfaceNewBestBlockListener
- Throws:
VerificationException
-
maybeCommitTx
Updates the wallet with the given transaction: puts it into the pending pool, sets the spent flags and runs the onCoinsSent/onCoinsReceived event listener.Triggers an auto save (if enabled.)
Unlike
commitTx(org.bitcoinj.core.Transaction)
this method does not throw an exception if the transaction was already added to the wallet, instead it will returnfalse
- Parameters:
tx
- transaction to commit- Returns:
- 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
-
commitTx
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:- When we have just successfully transmitted the tx we created to the network.
- When we receive a pending transaction that didn't appear in the chain yet, and we did not create it.
Unlike
maybeCommitTx(org.bitcoinj.core.Transaction)
commitTx
throws an exception if the transaction was already added to the wallet.- Parameters:
tx
- transaction to commit- Throws:
VerificationException
- if transaction was already in the pending pool
-
addChangeEventListener
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. -
addChangeEventListener
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. -
addCoinsReceivedEventListener
Adds an event listener object called when coins are received. Runs the listener methods in the user thread. -
addCoinsReceivedEventListener
public void addCoinsReceivedEventListener(Executor executor, WalletCoinsReceivedEventListener listener) Adds an event listener object called when coins are received. The listener is executed by the given executor. -
addCoinsSentEventListener
Adds an event listener object called when coins are sent. Runs the listener methods in the user thread. -
addCoinsSentEventListener
Adds an event listener object called when coins are sent. The listener is executed by the given executor. -
addKeyChainEventListener
Adds an event listener object. Methods on this object are called when keys are added. The listener is executed in the user thread. -
addKeyChainEventListener
Adds an event listener object. Methods on this object are called when keys are added. The listener is executed by the given executor. -
addCurrentKeyChangeEventListener
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. -
addCurrentKeyChangeEventListener
public void addCurrentKeyChangeEventListener(Executor executor, CurrentKeyChangeEventListener 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. -
addReorganizeEventListener
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. -
addReorganizeEventListener
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. -
addScriptsChangeEventListener
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. -
addScriptsChangeEventListener
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. -
addTransactionConfidenceEventListener
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. -
addTransactionConfidenceEventListener
public void addTransactionConfidenceEventListener(Executor executor, TransactionConfidenceEventListener 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. -
removeChangeEventListener
Removes the given event listener object. Returns true if the listener was removed, false if that listener was never added. -
removeCoinsReceivedEventListener
Removes the given event listener object. Returns true if the listener was removed, false if that listener was never added. -
removeCoinsSentEventListener
Removes the given event listener object. Returns true if the listener was removed, false if that listener was never added. -
removeKeyChainEventListener
Removes the given event listener object. Returns true if the listener was removed, false if that listener was never added. -
removeCurrentKeyChangeEventListener
Removes the given event listener object. Returns true if the listener was removed, false if that listener was never added. -
removeReorganizeEventListener
Removes the given event listener object. Returns true if the listener was removed, false if that listener was never added. -
removeScriptsChangeEventListener
Removes the given event listener object. Returns true if the listener was removed, false if that listener was never added. -
removeTransactionConfidenceEventListener
public boolean removeTransactionConfidenceEventListener(TransactionConfidenceEventListener listener) Removes the given event listener object. Returns true if the listener was removed, false if that listener was never added. -
maybeQueueOnWalletChanged
protected void maybeQueueOnWalletChanged() -
queueOnCoinsReceived
-
queueOnCoinsSent
-
queueOnReorganize
protected void queueOnReorganize() -
queueOnScriptsChanged
-
getTransactions
Returns a set of all transactions in the wallet.- Parameters:
includeDead
- If true, transactions that were overridden by a double spend are included.
-
getWalletTransactions
Returns a set of all WalletTransactions in the wallet. -
addWalletTransaction
Adds a transaction that has been associated with a particular wallet pool. This is intended for usage by deserialization code, such as theWalletProtobufSerializer
class. It isn't normally useful for applications. It does not trigger auto saving. -
getTransactionsByTime
Returns all non-dead, active transactions ordered by recency. -
getRecentTransactions
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.
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 (e.g. if backed by a database).
-
getTransaction
Returns a transaction object given its hash, if it exists in this wallet, or null otherwise. -
getTransactionPool
Description copied from interface:TransactionBag
Returns transactions from a specific pool.- Specified by:
getTransactionPool
in interfaceTransactionBag
-
reset
public void reset()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.WalletChangeEventListener.onWalletChanged(org.bitcoinj.wallet.Wallet)
will be fired. -
clearTransactions
public void clearTransactions(int fromHeight) 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. -
getWatchedOutputs
Returns all the outputs that match addresses or scripts added viaaddWatchedAddress(Address)
oraddWatchedScripts(java.util.List)
.- Parameters:
excludeImmatureCoinbases
- Whether to ignore outputs that are unspendable due to being immature.
-
cleanup
public void cleanup()Clean up the wallet. Currently, it only removes risky pending transaction from the wallet and only if their outputs have not been spent. -
getPoolSize
-
poolContainsTxHash
-
getUnspents
Returns a copy of the internal unspent outputs list -
toString
-
toString
public String toString(boolean includeLookahead, boolean includePrivateKeys, @Nullable AesKey aesKey, boolean includeTransactions, boolean includeExtensions, @Nullable AbstractBlockChain chain) Formats the wallet as a human-readable piece of text. Intended for debugging, the format is not meant to be stable or human-readable.- Parameters:
includeLookahead
- Whether lookahead keys should be included.includePrivateKeys
- Whether raw private key data should be included.aesKey
- for decrypting private key data for if the wallet is encrypted.includeTransactions
- Whether to print transaction data.includeExtensions
- Whether to print extension data.chain
- If set, will be used to estimate lock times for block time-locked transactions.- Returns:
- Human-readable wallet debugging information
-
getPendingTransactions
Returns an immutable view of the transactions currently waiting for network confirmations. -
earliestKeyCreationTime
Returns the earliest creation time of keys or watched scripts in this wallet, ie the min ofECKey.getCreationTime()
. This can returnInstant.EPOCH
if at least one key does not have that data (e.g. is an imported key with unknown timestamp).This method is most often used in conjunction with
PeerGroup.setFastCatchupTime(Instant)
in order to optimize chain download for new users of wallet apps. Backwards compatibility notice: if you getInstant.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.If there are no keys in the wallet,
Instant.MAX
is returned.- Specified by:
earliestKeyCreationTime
in interfacePeerFilterProvider
- Returns:
- earliest creation times of keys in this wallet,
Instant.EPOCH
if at least one time is unknown,Instant.MAX
if no keys in this wallet
-
getLastBlockSeenHash
Returns the hash of the last seen best-chain block, or null if the wallet is too old to store this data. -
setLastBlockSeenHash
-
setLastBlockSeenHeight
public void setLastBlockSeenHeight(int lastBlockSeenHeight) -
setLastBlockSeenTime
-
clearLastBlockSeenTime
public void clearLastBlockSeenTime() -
setLastBlockSeenTimeSecs
Deprecated. -
lastBlockSeenTime
Returns time extracted from the last best seen block header, or empty. This timestamp is not 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. -
getLastBlockSeenTimeSecs
Deprecated. -
getLastBlockSeenTime
Deprecated. -
getLastBlockSeenHeight
public int getLastBlockSeenHeight()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. -
getVersion
public int getVersion()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). -
setVersion
public void setVersion(int version) Set the version number of the wallet. SeegetVersion()
. -
setDescription
Set the description of the wallet. This is a Unicode encoding string typically entered by the user as descriptive text for the wallet. -
getDescription
Get the description of the wallet. SeesetDescription(String)
-
getBalance
Returns the AVAILABLE balance of this wallet. SeeWallet.BalanceType.AVAILABLE
for details on what this means. -
getBalance
Returns the balance of this wallet as calculated by the provided balanceType. -
getBalance
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. -
getBalanceFuture
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.
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
Threading.waitForUserCode()
to block until the future had a chance to be updated. -
getTotalReceived
Returns the amount of bitcoin ever received via output. This is not the balance! 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.- Returns:
- the total amount of satoshis received, regardless of whether it was spent or not.
-
getTotalSent
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.- Returns:
- the total amount of satoshis sent by us
-
createSend
public Transaction createSend(Address address, Coin value) throws InsufficientMoneyException, Wallet.CompletionException Statelessly creates a transaction that sends the given value to address. The change is sent to
currentChangeAddress()
, so you must have added at least one key.If you just want to send money quickly, you probably want
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.This is a helper method that is equivalent to using
SendRequest.to(Address, Coin)
followed bycompleteTx(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.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
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.You MUST ensure that the value is not smaller than
TransactionOutput.getMinNonDustValue()
or the transaction will almost certainly be rejected by the network as dust.- Parameters:
address
- The Bitcoin address to send the money to.value
- How much currency to send.- Returns:
- 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.Wallet.DustySendRequested
- if the resultant transaction would violate the dust rules.Wallet.CouldNotAdjustDownwards
- if emptying the wallet was requested and the output can't be shrunk for fees without violating a protocol rule.Wallet.ExceededMaxTransactionSize
- if the resultant transaction is too big for Bitcoin to process.Wallet.MultipleOpReturnRequested
- if there is more than one OP_RETURN output for the resultant transaction.Wallet.BadWalletEncryptionKeyException
- if the suppliedSendRequest.aesKey
is wrong.Wallet.CompletionException
-
createSend
public Transaction createSend(Address address, Coin value, boolean allowUnconfirmed) throws InsufficientMoneyException, Wallet.CompletionException Statelessly creates a transaction that sends the given value to address. The change is sent to
currentChangeAddress()
, so you must have added at least one key.If you just want to send money quickly, you probably want
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.This is a helper method that is equivalent to using
SendRequest.to(Address, Coin)
followed bycompleteTx(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.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
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.You MUST ensure that the value is not smaller than
TransactionOutput.getMinNonDustValue()
or the transaction will almost certainly be rejected by the network as dust.- Parameters:
address
- The Bitcoin address to send the money to.value
- How much currency to send.allowUnconfirmed
- Whether to allow spending unconfirmed outputs.- Returns:
- 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.Wallet.DustySendRequested
- if the resultant transaction would violate the dust rules.Wallet.CouldNotAdjustDownwards
- if emptying the wallet was requested and the output can't be shrunk for fees without violating a protocol rule.Wallet.ExceededMaxTransactionSize
- if the resultant transaction is too big for Bitcoin to process.Wallet.MultipleOpReturnRequested
- if there is more than one OP_RETURN output for the resultant transaction.Wallet.BadWalletEncryptionKeyException
- if the suppliedSendRequest.aesKey
is wrong.Wallet.CompletionException
-
sendCoinsOffline
public Transaction sendCoinsOffline(SendRequest request) throws InsufficientMoneyException, Wallet.CompletionException 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 aPeerGroup
orPeer
the transaction will be announced to the network. The givenSendRequest
is completed first usingcompleteTx(SendRequest)
to make it valid.- Returns:
- the Transaction that was created
- Throws:
InsufficientMoneyException
- if the request could not be completed due to not enough balance.IllegalArgumentException
- if you try and complete the same SendRequest twiceWallet.DustySendRequested
- if the resultant transaction would violate the dust rules.Wallet.CouldNotAdjustDownwards
- if emptying the wallet was requested and the output can't be shrunk for fees without violating a protocol rule.Wallet.ExceededMaxTransactionSize
- if the resultant transaction is too big for Bitcoin to process.Wallet.MultipleOpReturnRequested
- if there is more than one OP_RETURN output for the resultant transaction.Wallet.BadWalletEncryptionKeyException
- if the suppliedSendRequest.aesKey
is wrong.Wallet.CompletionException
-
sendCoins
public Wallet.SendResult sendCoins(TransactionBroadcaster broadcaster, Address to, Coin value) throws InsufficientMoneyException, Wallet.CompletionException Sends coins to the given address, via the given
PeerGroup
. Change is returned tocurrentChangeAddress()
. Note that a fee may be automatically added if one may be required for the transaction to be confirmed.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.
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.
You MUST ensure that value is not smaller than
TransactionOutput.getMinNonDustValue()
or the transaction will almost certainly be rejected by the network as dust.- Parameters:
broadcaster
- aTransactionBroadcaster
to use to send the transactions out.to
- Which address to send coins to.value
- How much value to send.- Returns:
- 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.Wallet.DustySendRequested
- if the resultant transaction would violate the dust rules.Wallet.CouldNotAdjustDownwards
- if emptying the wallet was requested and the output can't be shrunk for fees without violating a protocol rule.Wallet.ExceededMaxTransactionSize
- if the resultant transaction is too big for Bitcoin to process.Wallet.MultipleOpReturnRequested
- if there is more than one OP_RETURN output for the resultant transaction.Wallet.BadWalletEncryptionKeyException
- if the suppliedSendRequest.aesKey
is wrong.Wallet.CompletionException
-
sendCoins
public Wallet.SendResult sendCoins(TransactionBroadcaster broadcaster, SendRequest request) throws InsufficientMoneyException, Wallet.CompletionException Sends coins according to the given request, via the given
TransactionBroadcaster
.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.
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.
- Parameters:
broadcaster
- the target to use for broadcast.request
- the SendRequest that describes what to do, get one using static methods on SendRequest itself.- Returns:
- 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.IllegalArgumentException
- if you try and complete the same SendRequest twiceWallet.DustySendRequested
- if the resultant transaction would violate the dust rules.Wallet.CouldNotAdjustDownwards
- if emptying the wallet was requested and the output can't be shrunk for fees without violating a protocol rule.Wallet.ExceededMaxTransactionSize
- if the resultant transaction is too big for Bitcoin to process.Wallet.MultipleOpReturnRequested
- if there is more than one OP_RETURN output for the resultant transaction.Wallet.BadWalletEncryptionKeyException
- if the suppliedSendRequest.aesKey
is wrong.Wallet.CompletionException
-
sendCoins
public Wallet.SendResult sendCoins(SendRequest request) throws InsufficientMoneyException, Wallet.CompletionException Satisfies the givenSendRequest
using the default transaction broadcaster configured either viaPeerGroup.addWallet(Wallet)
or directly withsetTransactionBroadcaster(TransactionBroadcaster)
.- Parameters:
request
- the SendRequest that describes what to do, get one using static methods on SendRequest itself.- Returns:
- 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.InsufficientMoneyException
- if the request could not be completed due to not enough balance.IllegalArgumentException
- if you try and complete the same SendRequest twiceWallet.DustySendRequested
- if the resultant transaction would violate the dust rules.Wallet.CouldNotAdjustDownwards
- if emptying the wallet was requested and the output can't be shrunk for fees without violating a protocol rule.Wallet.ExceededMaxTransactionSize
- if the resultant transaction is too big for Bitcoin to process.Wallet.MultipleOpReturnRequested
- if there is more than one OP_RETURN output for the resultant transaction.Wallet.BadWalletEncryptionKeyException
- if the suppliedSendRequest.aesKey
is wrong.Wallet.CompletionException
-
sendCoins
public Transaction sendCoins(Peer peer, SendRequest request) throws InsufficientMoneyException, Wallet.CompletionException Sends coins to the given address, via the givenPeer
. Change is returned tocurrentChangeAddress()
. If an exception is thrown byPeerSocketHandler.sendMessage(Message)
the transaction is still committed, so the pending transaction must be broadcast by you at some other time. Note that a fee may be automatically added if one may be required for the transaction to be confirmed.- Returns:
- The
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.IllegalArgumentException
- if you try and complete the same SendRequest twiceWallet.DustySendRequested
- if the resultant transaction would violate the dust rules.Wallet.CouldNotAdjustDownwards
- if emptying the wallet was requested and the output can't be shrunk for fees without violating a protocol rule.Wallet.ExceededMaxTransactionSize
- if the resultant transaction is too big for Bitcoin to process.Wallet.MultipleOpReturnRequested
- if there is more than one OP_RETURN output for the resultant transaction.Wallet.BadWalletEncryptionKeyException
- if the suppliedSendRequest.aesKey
is wrong.Wallet.CompletionException
-
sendTransaction
Initiate sending the transaction in aSendRequest
. CallssendCoins(SendRequest)
which performs the following significant operations internally:completeTx(SendRequest)
-- calculate change and signcommitTx(Transaction)
-- puts the transaction in theWallet
's pending poolTransactionBroadcaster.broadcastTransaction(Transaction)
typically implemented byPeerGroup.broadcastTransaction(Transaction)
-- queues requests to send the transaction to a single remotePeer
TransactionBroadcast
when the send to the remote peer occurs (is buffered.) The broadcast process includes the following steps:- Wait until enough
Peer
s are connected. - Broadcast (buffer for send) the transaction to a single remote
Peer
- Mark
TransactionBroadcast.awaitSent()
as complete - Wait for a number of remote peers to confirm they have received the broadcast
- Mark
TransactionBroadcast.awaitRelayed()
as complete
- Parameters:
sendRequest
- transaction to send- Returns:
- A future for the transaction broadcast
-
waitForConfirmation
Wait for at least 1 confirmation on a transaction.- Parameters:
tx
- the transaction we are waiting for- Returns:
- a future for an object that contains transaction confidence information
-
waitForConfirmations
public CompletableFuture<TransactionConfidence> waitForConfirmations(Transaction tx, int requiredConfirmations) Wait for a required number of confirmations on a transaction.- Parameters:
tx
- the transaction we are waiting forrequiredConfirmations
- the minimum required confirmations before completing- Returns:
- a future for an object that contains transaction confidence information
-
completeTx
public void completeTx(SendRequest req) throws InsufficientMoneyException, Wallet.CompletionException 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.- Parameters:
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.IllegalArgumentException
- if you try and complete the same SendRequest twiceWallet.DustySendRequested
- if the resultant transaction would violate the dust rules.Wallet.CouldNotAdjustDownwards
- if emptying the wallet was requested and the output can't be shrunk for fees without violating a protocol rule.Wallet.ExceededMaxTransactionSize
- if the resultant transaction is too big for Bitcoin to process.Wallet.MultipleOpReturnRequested
- if there is more than one OP_RETURN output for the resultant transaction.Wallet.BadWalletEncryptionKeyException
- if the suppliedSendRequest.aesKey
is wrong.Wallet.CompletionException
-
signTransaction
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.
Actual signing is done by pluggable
signers
and it's not guaranteed that transaction will be complete in the end.- Throws:
Wallet.BadWalletEncryptionKeyException
- if the suppliedSendRequest.aesKey
is wrong.
-
calculateAllSpendCandidates
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. -
calculateAllSpendCandidates
public List<TransactionOutput> calculateAllSpendCandidates(boolean excludeImmatureCoinbases, boolean excludeUnsignable) Returns a list of all outputs that are being tracked by this wallet either from theUTXOProvider
(in this case the existence or not of private keys is ignored), or the wallets internal storage (the default) taking into account the flags.- Parameters:
excludeImmatureCoinbases
- Whether to ignore coinbase outputs that we will be able to spend in future once they mature.excludeUnsignable
- Whether to ignore outputs that we are tracking but don't have the keys to sign for.
-
canSignFor
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. -
calculateAllSpendCandidatesFromUTXOProvider
protected List<TransactionOutput> calculateAllSpendCandidatesFromUTXOProvider(boolean excludeImmatureCoinbases) Returns the spendable candidates from theUTXOProvider
based on keys that the wallet contains.- Returns:
- The list of candidates.
-
getStoredOutputsFromUTXOProvider
Get all theUTXO
's from theUTXOProvider
based on keys that the wallet contains.- Returns:
- The list of stored outputs.
- Throws:
UTXOProviderException
-
getCoinSelector
Returns the defaultCoinSelector
object that is used by this wallet if no custom selector is specified. -
getUTXOProvider
Get theUTXOProvider
.- Returns:
- The UTXO provider.
-
setUTXOProvider
Set theUTXOProvider
.The wallet will query the provider for spendable candidates, i.e. outputs controlled exclusively by private keys contained in the wallet.
Note that the associated provider must be reattached after a wallet is loaded from disk. The association is not serialized.
-
reorganize
public void reorganize(StoredBlock splitPoint, List<StoredBlock> oldBlocks, List<StoredBlock> newBlocks) throws VerificationException Don't call this directly. It's not intended for API users.
Called by the
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.The oldBlocks/newBlocks lists are ordered height-wise from top first to bottom last.
- Specified by:
reorganize
in interfaceReorganizeListener
- Throws:
VerificationException
-
beginBloomFilterCalculation
public void beginBloomFilterCalculation()Description copied from interface:PeerFilterProvider
Called on all registered filter providers beforePeerFilterProvider.getBloomFilterElementCount()
andPeerFilterProvider.getBloomFilter(int, double, int)
are called. Once called, the provider should ensure that the items it will want to insert into the filter don't change. The reason is that all providers will have their element counts queried, and then a filter big enough for all of them will be specified. So the provider must use consistent state. There is guaranteed to be a matching call toPeerFilterProvider.endBloomFilterCalculation()
that can be used to e.g. unlock a lock.- Specified by:
beginBloomFilterCalculation
in interfacePeerFilterProvider
-
endBloomFilterCalculation
public void endBloomFilterCalculation()Description copied from interface:PeerFilterProvider
- Specified by:
endBloomFilterCalculation
in interfacePeerFilterProvider
-
getBloomFilterElementCount
public int getBloomFilterElementCount()Returns the number of distinct data items (note: NOT keys) that will be inserted into a bloom filter, when it is constructed.- Specified by:
getBloomFilterElementCount
in interfacePeerFilterProvider
-
getBloomFilter
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 forBloomFilter
for a brief explanation of anonymity when using filters. -
getBloomFilter
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).
This is used to generate a BloomFilter which can be
BloomFilter.merge(BloomFilter)
d with another. It could also be used if you have a specific target for the filter's size.See the docs for
BloomFilter(int, double, int, BloomFilter.BloomUpdate)
for a brief explanation of anonymity when using bloom filters.- Specified by:
getBloomFilter
in interfacePeerFilterProvider
-
checkForFilterExhaustion
Used byPeer
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. -
addExtension
By providing an object implementing theWalletExtension
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. -
addOrGetExistingExtension
Atomically adds extension or returns an existing extension if there is one with the same id already present. -
addOrUpdateExtension
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. -
getExtensions
Returns a snapshot of all registered extension objects. The extensions themselves are not copied. -
deserializeExtension
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.- Throws:
Exception
-
setTag
Deprecated.Applications should use another mechanism to persist application state informationDescription copied from interface:TaggableObject
Associates the given immutable byte array with the string tag. See the docs for TaggableObject to learn more.- Specified by:
setTag
in interfaceTaggableObject
- Overrides:
setTag
in classBaseTaggableObject
-
setTransactionBroadcaster
Specifies that the given
TransactionBroadcaster
, typically aPeerGroup
, 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.You don't normally need to call this. A
PeerGroup
will automatically set itself as the wallets broadcaster when you usePeerGroup.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. -
setKeyRotationTime
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
null
as the argument.Once set up, calling
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.The given time cannot be in the future.
- Parameters:
keyRotationTime
- rotate any keys created before this time, or null for no rotation
-
setKeyRotationTime
Deprecated. -
setKeyRotationTime
Deprecated. -
keyRotationTime
Returns the key rotation time, or empty if unconfigured. SeesetKeyRotationTime(Instant)
for a description of the field. -
getKeyRotationTime
Deprecated. -
isKeyRotating
Returns whether the keys creation time is before the key rotation time, if one was set. -
doMaintenance
public ListenableCompletableFuture<List<Transaction>> doMaintenance(@Nullable AesKey aesKey, boolean signAndSend) throws DeterministicUpgradeRequiresPassword 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.- Parameters:
aesKey
- the users password, if any.signAndSend
- if true, send the transactions via the tx broadcaster and return them, if false just return them.- Returns:
- A list of transactions that the wallet just made/will make for internal maintenance. Might be empty.
- Throws:
DeterministicUpgradeRequiresPassword
- if key rotation requires the users password.
-
doMaintenance
public ListenableCompletableFuture<List<Transaction>> doMaintenance(KeyChainGroupStructure structure, @Nullable AesKey aesKey, boolean signAndSend) throws DeterministicUpgradeRequiresPassword 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.- Parameters:
structure
- to derive the account path from if a new seed needs to be createdaesKey
- the users password, if any.signAndSend
- if true, send the transactions via the tx broadcaster and return them, if false just return them.- Returns:
- A list of transactions that the wallet just made/will make for internal maintenance. Might be empty.
- Throws:
DeterministicUpgradeRequiresPassword
- if key rotation requires the users password.
-
Wallet(org.bitcoinj.core.NetworkParameters,org.bitcoinj.wallet.KeyChainGroup)