public class Wallet extends BaseTaggableObject implements NewBestBlockListener, TransactionReceivedInBlockListener, PeerFilterProvider, KeyBag, TransactionBag, ReorganizeListener
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 (eg due to a block chain sync). See
autosaveToFile(File, long, TimeUnit, WalletFiles.Listener)
for more information about this.
Modifier and Type | Class and Description |
---|---|
static class |
Wallet.BalanceType
It's possible to calculate a wallets balance from multiple points of view.
|
static class |
Wallet.CompletionException
Class of exceptions thrown in
completeTx(SendRequest) . |
static class |
Wallet.CouldNotAdjustDownwards
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 |
Wallet.DustySendRequested
Thrown if the resultant transaction would violate the dust rules (an output that's too small to be worthwhile).
|
static class |
Wallet.ExceededMaxTransactionSize
Thrown if the resultant transaction is too big for Bitcoin to process.
|
static class |
Wallet.MissingSigsMode
Enumerates possible resolutions for missing signatures.
|
static class |
Wallet.MultipleOpReturnRequested
Thrown if there is more than one OP_RETURN output for the resultant transaction.
|
static class |
Wallet.SendResult
A SendResult is returned to you as part of sending coins to a recipient.
|
Modifier and Type | Field and Description |
---|---|
protected CoinSelector |
coinSelector |
protected Context |
context |
protected java.util.concurrent.locks.ReentrantLock |
keyChainGroupLock |
protected java.util.concurrent.locks.ReentrantLock |
lock |
protected java.util.HashSet<TransactionOutput> |
myUnspents |
protected NetworkParameters |
params |
protected java.util.Map<Sha256Hash,Transaction> |
transactions |
protected WalletFiles |
vFileManager |
protected TransactionBroadcaster |
vTransactionBroadcaster |
tags
Constructor and Description |
---|
Wallet(Context context)
Deprecated.
Use
#createDeterministic(Context, ScriptType) |
Wallet(NetworkParameters params)
Deprecated.
Use
#createDeterministic(NetworkParameters, ScriptType) |
Wallet(NetworkParameters params,
KeyChainGroup keyChainGroup) |
Modifier and Type | Method and Description |
---|---|
void |
addAndActivateHDChain(DeterministicKeyChain chain)
Add a pre-configured keychain to the wallet.
|
void |
addChangeEventListener(java.util.concurrent.Executor executor,
WalletChangeEventListener listener)
Adds an event listener object.
|
void |
addChangeEventListener(WalletChangeEventListener listener)
Adds an event listener object.
|
void |
addCoinsReceivedEventListener(java.util.concurrent.Executor executor,
WalletCoinsReceivedEventListener listener)
Adds an event listener object called when coins are received.
|
void |
addCoinsReceivedEventListener(WalletCoinsReceivedEventListener listener)
Adds an event listener object called when coins are received.
|
void |
addCoinsSentEventListener(java.util.concurrent.Executor executor,
WalletCoinsSentEventListener listener)
Adds an event listener object called when coins are sent.
|
void |
addCoinsSentEventListener(WalletCoinsSentEventListener listener)
Adds an event listener object called when coins are sent.
|
void |
addExtension(WalletExtension extension)
By providing an object implementing the
WalletExtension interface, you can save and load arbitrary
additional data that will be stored with the wallet. |
void |
addKeyChainEventListener(java.util.concurrent.Executor executor,
KeyChainEventListener listener)
Adds an event listener object.
|
void |
addKeyChainEventListener(KeyChainEventListener listener)
Adds an event listener object.
|
WalletExtension |
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(java.util.concurrent.Executor executor,
WalletReorganizeEventListener listener)
Adds an event listener object.
|
void |
addReorganizeEventListener(WalletReorganizeEventListener listener)
Adds an event listener object.
|
void |
addScriptChangeEventListener(java.util.concurrent.Executor executor,
ScriptsChangeEventListener listener)
Adds an event listener object.
|
void |
addScriptsChangeEventListener(ScriptsChangeEventListener listener)
Adds an event listener object.
|
void |
addTransactionConfidenceEventListener(java.util.concurrent.Executor executor,
TransactionConfidenceEventListener listener)
Adds an event listener object.
|
void |
addTransactionConfidenceEventListener(TransactionConfidenceEventListener listener)
Adds an event listener object.
|
void |
addTransactionSigner(TransactionSigner signer)
Adds given transaction signer to the list of signers.
|
void |
addWalletTransaction(WalletTransaction wtx)
Adds a transaction that has been associated with a particular wallet pool.
|
boolean |
addWatchedAddress(Address address)
Same as
addWatchedAddress(Address, long) with the current time as the creation time. |
boolean |
addWatchedAddress(Address address,
long creationTime)
Adds the given address to the wallet to be watched.
|
int |
addWatchedAddresses(java.util.List<Address> addresses,
long creationTime)
Adds the given address to the wallet to be watched.
|
int |
addWatchedScripts(java.util.List<Script> scripts)
Adds the given output scripts to the wallet to be watched.
|
void |
allowSpendingUnconfirmedTransactions()
Convenience wrapper for
setCoinSelector(Wallet.AllowUnconfirmedCoinSelector.get()) . |
WalletFiles |
autosaveToFile(java.io.File f,
long delayTime,
java.util.concurrent.TimeUnit timeUnit,
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 |
beginBloomFilterCalculation()
Called on all registered filter providers before getBloomFilterElementCount and getBloomFilter are called.
|
java.util.List<TransactionOutput> |
calculateAllSpendCandidates()
Returns a list of the outputs that can potentially be spent, i.e.
|
java.util.List<TransactionOutput> |
calculateAllSpendCandidates(boolean excludeImmatureCoinbases,
boolean excludeUnsignable)
Returns a list of all outputs that are being tracked by this wallet either from the
UTXOProvider
(in this case the existence or not of private keys is ignored), or the wallets internal storage (the default)
taking into account the flags. |
protected java.util.LinkedList<TransactionOutput> |
calculateAllSpendCandidatesFromUTXOProvider(boolean excludeImmatureCoinbases)
Returns the spendable candidates from the
UTXOProvider 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,
org.bouncycastle.crypto.params.KeyParameter currentAesKey,
org.bouncycastle.crypto.params.KeyParameter newAesKey)
Changes wallet AES encryption key, this is atomic operation.
|
void |
changeEncryptionPassword(java.lang.CharSequence currentPassword,
java.lang.CharSequence newPassword)
Changes wallet encryption password, this is atomic operation.
|
boolean |
checkAESKey(org.bouncycastle.crypto.params.KeyParameter aesKey)
Check whether the AES key can decrypt the first encrypted key in the wallet.
|
boolean |
checkForFilterExhaustion(FilteredBlock block)
Used by
Peer to decide whether or not to discard this block and any blocks building upon it, in case
the Bloom filter used to request them may be exhausted, that is, not have sufficient keys in the deterministic
sequence within it to reliably find relevant transactions. |
boolean |
checkPassword(java.lang.CharSequence password)
Check whether the password can decrypt the first key in the wallet.
|
void |
cleanup()
Clean up the wallet.
|
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(NetworkParameters params)
Creates a new, empty wallet with just a basic keychain and no transactions.
|
static Wallet |
createDeterministic(Context context,
Script.ScriptType outputScriptType)
Creates a new, empty wallet with a randomly chosen seed and no transactions.
|
static Wallet |
createDeterministic(NetworkParameters params,
Script.ScriptType outputScriptType)
Creates a new, empty wallet with a randomly chosen seed and no transactions.
|
Transaction |
createSend(Address address,
Coin value)
Statelessly creates a transaction that sends the given value to address.
|
Address |
currentAddress(KeyChain.KeyPurpose purpose)
Returns address for a
currentKey(KeyChain.KeyPurpose) |
Address |
currentChangeAddress()
Returns the address used for change outputs.
|
DeterministicKey |
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 is
KeyChain.KeyPurpose.RECEIVE_FUNDS . |
Address |
currentReceiveAddress()
An alias for calling
currentAddress(KeyChain.KeyPurpose) with
KeyChain.KeyPurpose.RECEIVE_FUNDS as the parameter. |
DeterministicKey |
currentReceiveKey()
An alias for calling
currentKey(KeyChain.KeyPurpose) with
KeyChain.KeyPurpose.RECEIVE_FUNDS as the parameter. |
void |
decrypt(java.lang.CharSequence password)
Decrypt the wallet with the wallets keyCrypter and password.
|
void |
decrypt(org.bouncycastle.crypto.params.KeyParameter aesKey)
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.
|
com.google.common.util.concurrent.ListenableFuture<java.util.List<Transaction>> |
doMaintenance(KeyChainGroupStructure structure,
org.bouncycastle.crypto.params.KeyParameter 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.
|
com.google.common.util.concurrent.ListenableFuture<java.util.List<Transaction>> |
doMaintenance(org.bouncycastle.crypto.params.KeyParameter 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.
|
void |
encrypt(java.lang.CharSequence password)
Convenience wrapper around
encrypt(KeyCrypter,
org.bouncycastle.crypto.params.KeyParameter) which uses the default Scrypt key derivation algorithm and
parameters to derive a key from the given password. |
void |
encrypt(KeyCrypter keyCrypter,
org.bouncycastle.crypto.params.KeyParameter aesKey)
Encrypt the wallet using the KeyCrypter and the AES key.
|
void |
endBloomFilterCalculation() |
ECKey |
findKeyFromAddress(Address address)
Locates a keypair from the wallet given the corresponding address.
|
ECKey |
findKeyFromPubHash(byte[] pubKeyHash)
Deprecated.
Use
#findKeyFromPubKeyHash(byte[], ScriptType) |
ECKey |
findKeyFromPubKey(byte[] pubKey)
Locates a keypair from the basicKeyChain given the raw public key bytes.
|
ECKey |
findKeyFromPubKeyHash(byte[] pubKeyHash,
Script.ScriptType scriptType)
Locates a keypair from the basicKeyChain given the hash of the public key.
|
RedeemData |
findRedeemDataFromScriptHash(byte[] payToScriptHash)
Locates a redeem data (redeem script and keys) from the keyChainGroup given the hash of the script.
|
Address |
freshAddress(KeyChain.KeyPurpose purpose)
Returns address for a
freshKey(KeyChain.KeyPurpose) |
DeterministicKey |
freshKey(KeyChain.KeyPurpose purpose)
Returns a key that has not been returned by this method before (fresh).
|
java.util.List<DeterministicKey> |
freshKeys(KeyChain.KeyPurpose purpose,
int numberOfKeys)
Returns a key/s that has not been returned by this method before (fresh).
|
Address |
freshReceiveAddress()
An alias for calling
freshAddress(KeyChain.KeyPurpose) with
KeyChain.KeyPurpose.RECEIVE_FUNDS as the parameter. |
Address |
freshReceiveAddress(Script.ScriptType scriptType)
Returns a fresh receive address for a given
Script.ScriptType . |
DeterministicKey |
freshReceiveKey()
An alias for calling
freshKey(KeyChain.KeyPurpose) with
KeyChain.KeyPurpose.RECEIVE_FUNDS as the parameter. |
static Wallet |
fromKeys(NetworkParameters params,
java.util.List<ECKey> keys)
Deprecated.
Use
createBasic(NetworkParameters) , then importKeys(List) . |
static Wallet |
fromMasterKey(NetworkParameters params,
DeterministicKey masterKey,
Script.ScriptType outputScriptType,
ChildNumber accountNumber)
Creates a wallet that tracks payments to and from the HD key hierarchy rooted by the given spending key.
|
static Wallet |
fromSeed(NetworkParameters params,
DeterministicSeed seed)
Deprecated.
Use
#fromSeed(NetworkParameters, DeterministicSeed, ScriptType, KeyChainGroupStructure) |
static Wallet |
fromSeed(NetworkParameters params,
DeterministicSeed seed,
com.google.common.collect.ImmutableList<ChildNumber> accountPath)
Deprecated.
Use
#fromSeed(NetworkParameters, DeterministicSeed, ScriptType, ImmutableList) |
static Wallet |
fromSeed(NetworkParameters params,
DeterministicSeed seed,
Script.ScriptType outputScriptType) |
static Wallet |
fromSeed(NetworkParameters params,
DeterministicSeed seed,
Script.ScriptType outputScriptType,
com.google.common.collect.ImmutableList<ChildNumber> accountPath) |
static Wallet |
fromSeed(NetworkParameters params,
DeterministicSeed seed,
Script.ScriptType outputScriptType,
KeyChainGroupStructure structure) |
static Wallet |
fromSpendingKey(NetworkParameters params,
DeterministicKey spendKey)
Deprecated.
Use
#fromSpendingKey(NetworkParameters, DeterministicKey, ScriptType) |
static Wallet |
fromSpendingKey(NetworkParameters params,
DeterministicKey spendKey,
Script.ScriptType outputScriptType)
Creates a wallet that tracks payments to and from the HD key hierarchy rooted by the given spending key.
|
static Wallet |
fromSpendingKeyB58(NetworkParameters params,
java.lang.String spendingKeyB58,
long creationTimeSeconds)
Creates a wallet that tracks payments to and from the HD key hierarchy rooted by the given spending key.
|
static Wallet |
fromWatchingKey(NetworkParameters params,
DeterministicKey watchKey)
Deprecated.
Use
#fromWatchingKey(NetworkParameters, DeterministicKey, ScriptType) |
static Wallet |
fromWatchingKey(NetworkParameters params,
DeterministicKey watchKey,
Script.ScriptType outputScriptType)
Creates a wallet that tracks payments to and from the HD key hierarchy rooted by the given watching key.
|
static Wallet |
fromWatchingKeyB58(NetworkParameters params,
java.lang.String watchKeyB58,
long creationTimeSeconds)
Creates a wallet that tracks payments to and from the HD key hierarchy rooted by the given watching key.
|
DeterministicKeyChain |
getActiveKeyChain()
Gets the default active keychain via
KeyChainGroup.getActiveKeyChain() . |
java.util.List<DeterministicKeyChain> |
getActiveKeyChains()
Gets the active keychains via
KeyChainGroup.getActiveKeyChains(long) . |
Coin |
getBalance()
Returns the AVAILABLE balance of this wallet.
|
Coin |
getBalance(CoinSelector selector)
Returns the balance that would be considered spendable by the given coin selector, including watched outputs
(i.e.
|
Coin |
getBalance(Wallet.BalanceType balanceType)
Returns the balance of this wallet as calculated by the provided balanceType.
|
com.google.common.util.concurrent.ListenableFuture<Coin> |
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.
|
BloomFilter |
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.
|
BloomFilter |
getBloomFilter(int size,
double falsePositiveRate,
long 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 |
getBloomFilterElementCount()
Returns the number of distinct data items (note: NOT keys) that will be inserted into a bloom filter, when it
is constructed.
|
CoinSelector |
getCoinSelector()
Returns the
CoinSelector object which controls which outputs can be spent by this wallet. |
Context |
getContext()
Returns the API context that this wallet was created with.
|
java.lang.String |
getDescription()
Get the description of the wallet.
|
long |
getEarliestKeyCreationTime()
Returns the earliest creation time of keys or watched scripts in this wallet, in seconds since the epoch, ie the min
of
ECKey.getCreationTimeSeconds() . |
Protos.Wallet.EncryptionType |
getEncryptionType()
Get the type of encryption used for this wallet.
|
java.util.Map<java.lang.String,WalletExtension> |
getExtensions()
Returns a snapshot of all registered extension objects.
|
java.util.List<ECKey> |
getImportedKeys()
Returns a list of the non-deterministic keys that have been imported into the wallet, or the empty list if none.
|
java.util.List<Address> |
getIssuedReceiveAddresses()
Returns only the addresses that have been issued by
freshReceiveKey() , freshReceiveAddress() ,
currentReceiveKey() or currentReceiveAddress() . |
java.util.List<ECKey> |
getIssuedReceiveKeys()
Returns only the keys that have been issued by
freshReceiveKey() , freshReceiveAddress() ,
currentReceiveKey() or currentReceiveAddress() . |
DeterministicKey |
getKeyByPath(java.util.List<ChildNumber> path)
Returns a key for the given HD path, assuming it's already been derived.
|
int |
getKeyChainGroupCombinedKeyLookaheadEpochs() |
int |
getKeyChainGroupLookaheadSize()
See
DeterministicKeyChain.setLookaheadSize(int) for more info on this. |
int |
getKeyChainGroupLookaheadThreshold()
See
DeterministicKeyChain.setLookaheadThreshold(int) for more info on this. |
int |
getKeyChainGroupSize()
Returns the number of keys in the key chain group, including lookahead keys.
|
DeterministicSeed |
getKeyChainSeed()
Returns the immutable seed for the current active HD chain.
|
KeyCrypter |
getKeyCrypter()
Get the wallet's KeyCrypter, or null if the wallet is not encrypted.
|
java.util.Date |
getKeyRotationTime()
Returns the key rotation time, or null if unconfigured.
|
Sha256Hash |
getLastBlockSeenHash()
Returns the hash of the last seen best-chain block, or null if the wallet is too old to store this data.
|
int |
getLastBlockSeenHeight()
Returns the height of the last seen best-chain block.
|
java.util.Date |
getLastBlockSeenTime()
Returns a
Date representing the time extracted from the last best seen block header. |
long |
getLastBlockSeenTimeSecs()
Returns the UNIX time in seconds since the epoch extracted from the last best seen block header.
|
NetworkParameters |
getNetworkParameters() |
NetworkParameters |
getParams()
Returns the parameters this wallet was created with.
|
java.util.Collection<Transaction> |
getPendingTransactions()
Returns an immutable view of the transactions currently waiting for network confirmations.
|
int |
getPoolSize(WalletTransaction.Pool pool) |
java.util.List<Transaction> |
getRecentTransactions(int numTransactions,
boolean includeDead)
Returns an list of N transactions, ordered by increasing age.
|
RiskAnalysis.Analyzer |
getRiskAnalyzer()
Gets the current
RiskAnalysis implementation. |
protected java.util.List<UTXO> |
getStoredOutputsFromUTXOProvider()
Get all the
UTXO 's from the UTXOProvider based on keys that the
wallet contains. |
Coin |
getTotalReceived()
Returns the amount of bitcoin ever received via output.
|
Coin |
getTotalSent()
Returns the amount of bitcoin ever sent via output.
|
Transaction |
getTransaction(Sha256Hash hash)
Returns a transaction object given its hash, if it exists in this wallet, or null otherwise.
|
java.util.Map<Sha256Hash,Transaction> |
getTransactionPool(WalletTransaction.Pool pool)
Returns transactions from a specific pool.
|
java.util.Set<Transaction> |
getTransactions(boolean includeDead)
Returns a set of all transactions in the wallet.
|
java.util.List<Transaction> |
getTransactionsByTime()
Returns all non-dead, active transactions ordered by recency.
|
java.util.List<TransactionSigner> |
getTransactionSigners() |
java.util.List<TransactionOutput> |
getUnspents()
Returns a copy of the internal unspent outputs list
|
UTXOProvider |
getUTXOProvider()
Get the
UTXOProvider . |
int |
getVersion()
Get the version of the Wallet.
|
java.lang.Iterable<WalletTransaction> |
getWalletTransactions()
Returns a set of all WalletTransactions in the wallet.
|
java.util.List<Address> |
getWatchedAddresses()
Returns all addresses watched by this wallet.
|
java.util.List<TransactionOutput> |
getWatchedOutputs(boolean excludeImmatureCoinbases)
Returns all the outputs that match addresses or scripts added via
addWatchedAddress(Address) or
addWatchedScripts(java.util.List) . |
java.util.List<Script> |
getWatchedScripts()
Returns a snapshot of the watched scripts.
|
DeterministicKey |
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.
|
boolean |
hasKey(ECKey key)
Returns true if the given key is in the wallet, false otherwise.
|
boolean |
importKey(ECKey key)
Imports the given ECKey to the wallet.
|
int |
importKeys(java.util.List<ECKey> keys)
Imports the given keys to the wallet.
|
int |
importKeysAndEncrypt(java.util.List<ECKey> keys,
java.lang.CharSequence password)
Takes a list of keys and a password, then encrypts and imports them in one step using the current keycrypter.
|
int |
importKeysAndEncrypt(java.util.List<ECKey> keys,
org.bouncycastle.crypto.params.KeyParameter aesKey)
Takes a list of keys and an AES key, then encrypts and imports them in one step using the current keycrypter.
|
boolean |
isAcceptRiskyTransactions()
See
setAcceptRiskyTransactions(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 |
isConsistent()
Returns if this wallet is structurally consistent, so e.g.
|
void |
isConsistentOrThrow()
Variant of
isConsistent() that throws an IllegalStateException describing the first
inconsistency. |
boolean |
isDeterministicUpgradeRequired()
Deprecated.
Use
#isDeterministicUpgradeRequired(ScriptType) |
boolean |
isDeterministicUpgradeRequired(Script.ScriptType outputScriptType)
Returns true if the wallet contains random keys and no HD chains, in which case you should call
#upgradeToDeterministic(ScriptType, KeyParameter) before attempting to do anything
that would require a new address or key. |
boolean |
isEncrypted()
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 |
isPendingTransactionRelevant(Transaction tx)
This method is used by a
Peer to find out if a transaction that has been announced is interesting,
that is, whether we should bother downloading its dependencies and exploring the transaction to decide how
risky it is. |
boolean |
isPubKeyHashMine(byte[] pubKeyHash)
Deprecated.
Use
#isPubKeyHashMine(byte[], ScriptType) |
boolean |
isPubKeyHashMine(byte[] pubKeyHash,
Script.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 |
isRequiringUpdateAllBloomFilter()
If we are watching any scripts, the bloom filter must update on peers whenever an output is
identified.
|
boolean |
isTransactionRelevant(Transaction tx)
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,
java.util.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 |
isWatching()
Returns whether this wallet consists entirely of watching keys (unencrypted keys with no private part).
|
static Wallet |
loadFromFile(java.io.File file,
WalletExtension... walletExtensions)
Returns a wallet deserialized from the given file.
|
static Wallet |
loadFromFileStream(java.io.InputStream stream,
WalletExtension... walletExtensions)
Returns a wallet deserialized from the given input stream and wallet extensions.
|
boolean |
maybeCommitTx(Transaction tx)
Calls
commitTx(org.bitcoinj.core.Transaction) if tx is not already in the pending pool |
protected void |
maybeQueueOnWalletChanged() |
void |
notifyNewBestBlock(StoredBlock block)
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 (the reorganize(StoredBlock, List, List) method will
call this one in that case). |
boolean |
notifyTransactionIsInBlock(Sha256Hash txHash,
StoredBlock block,
AbstractBlockChain.NewBlockType blockType,
int relativityOffset)
Called by the
BlockChain when we receive a new filtered block that contains a transactions previously
received by a call to receivePending(org.bitcoinj.core.Transaction, java.util.List<org.bitcoinj.core.Transaction>, boolean) . |
boolean |
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 |
queueOnReorganize() |
protected void |
queueOnScriptsChanged(java.util.List<Script> scripts,
boolean isAddingScripts) |
void |
receiveFromBlock(Transaction tx,
StoredBlock block,
AbstractBlockChain.NewBlockType blockType,
int relativityOffset)
Called by the
BlockChain when we receive a new block that sends coins to one of our addresses or
spends coins from one of our addresses (note that a single transaction can do both). |
void |
receivePending(Transaction tx,
java.util.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,
java.util.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 |
removeChangeEventListener(WalletChangeEventListener listener)
Removes the given event listener object.
|
boolean |
removeCoinsReceivedEventListener(WalletCoinsReceivedEventListener listener)
Removes the given event listener object.
|
boolean |
removeCoinsSentEventListener(WalletCoinsSentEventListener listener)
Removes the given event listener object.
|
boolean |
removeKey(ECKey key)
Removes the given key from the basicKeyChain.
|
boolean |
removeKeyChainEventListener(KeyChainEventListener listener)
Removes the given event listener object.
|
boolean |
removeReorganizeEventListener(WalletReorganizeEventListener listener)
Removes the given event listener object.
|
boolean |
removeScriptChangeEventListener(ScriptsChangeEventListener listener)
Removes the given event listener object.
|
boolean |
removeTransactionConfidenceEventListener(TransactionConfidenceEventListener listener)
Removes the given event listener object.
|
boolean |
removeWatchedAddress(Address address)
Removes the given output scripts from the wallet that were being watched.
|
boolean |
removeWatchedAddresses(java.util.List<Address> addresses)
Removes the given output scripts from the wallet that were being watched.
|
boolean |
removeWatchedScripts(java.util.List<Script> scripts)
Removes the given output scripts from the wallet that were being watched.
|
void |
reorganize(StoredBlock splitPoint,
java.util.List<StoredBlock> oldBlocks,
java.util.List<StoredBlock> newBlocks)
Don't call this directly.
|
void |
reset()
Prepares the wallet for a blockchain replay.
|
protected void |
saveLater()
Requests an asynchronous save on a background thread
|
protected void |
saveNow()
If auto saving is enabled, do an immediate sync write to disk ignoring any delays.
|
void |
saveToFile(java.io.File f)
Uses protobuf serialization to save the wallet to the given file.
|
void |
saveToFile(java.io.File temp,
java.io.File destFile)
Saves the wallet first to the given temp file, then renames to the dest file.
|
void |
saveToFileStream(java.io.OutputStream f)
Uses protobuf serialization to save the wallet to the given file stream.
|
Transaction |
sendCoins(Peer peer,
SendRequest request)
Sends coins to the given address, via the given
Peer . |
Wallet.SendResult |
sendCoins(SendRequest request)
Satisfies the given
SendRequest using the default transaction broadcaster configured either via
PeerGroup.addWallet(Wallet) or directly with setTransactionBroadcaster(TransactionBroadcaster) . |
Wallet.SendResult |
sendCoins(TransactionBroadcaster broadcaster,
Address to,
Coin value)
Sends coins to the given address, via the given
PeerGroup . |
Wallet.SendResult |
sendCoins(TransactionBroadcaster broadcaster,
SendRequest request)
Sends coins according to the given request, via the given
TransactionBroadcaster . |
Transaction |
sendCoinsOffline(SendRequest request)
Sends coins to the given address but does not broadcast the resulting pending transaction.
|
java.util.List<Protos.Key> |
serializeKeyChainGroupToProtobuf()
Internal use only.
|
void |
setAcceptRiskyTransactions(boolean acceptRiskyTransactions)
Whether or not the wallet will ignore pending transactions that fail the selected
RiskAnalysis . |
void |
setCoinSelector(CoinSelector coinSelector)
A coin selector is responsible for choosing which outputs to spend when creating transactions.
|
void |
setDescription(java.lang.String description)
Set the description of the wallet.
|
void |
setKeyRotationTime(java.util.Date time)
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(long unixTimeSeconds)
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 |
setLastBlockSeenHash(Sha256Hash lastBlockSeenHash) |
void |
setLastBlockSeenHeight(int lastBlockSeenHeight) |
void |
setLastBlockSeenTimeSecs(long timeSecs) |
void |
setRiskAnalyzer(RiskAnalysis.Analyzer analyzer)
Sets the
RiskAnalysis implementation to use for deciding whether received pending transactions are risky
or not. |
void |
setTag(java.lang.String tag,
com.google.protobuf.ByteString value)
Associates the given immutable byte array with the string tag.
|
void |
setTransactionBroadcaster(TransactionBroadcaster broadcaster)
Specifies that the given
TransactionBroadcaster , typically a PeerGroup , should be used for
sending transactions to the Bitcoin network by default. |
void |
setUTXOProvider(UTXOProvider provider)
Set the
UTXOProvider . |
void |
setVersion(int version)
Set the version number of the wallet.
|
void |
shutdownAutosaveAndWait()
Disables auto-saving, after it had been enabled with
autosaveToFile(File, long, TimeUnit, WalletFiles.Listener)
before. |
void |
signTransaction(SendRequest req)
Given a send request containing transaction, attempts to sign it's inputs.
|
java.lang.String |
toString() |
java.lang.String |
toString(boolean includePrivateKeys,
boolean includeTransactions,
boolean includeExtensions,
AbstractBlockChain chain)
Deprecated.
|
java.lang.String |
toString(boolean includeLookahead,
boolean includePrivateKeys,
org.bouncycastle.crypto.params.KeyParameter aesKey,
boolean includeTransactions,
boolean includeExtensions,
AbstractBlockChain chain)
Formats the wallet as a human readable piece of text.
|
java.lang.String |
toString(boolean includePrivateKeys,
org.bouncycastle.crypto.params.KeyParameter aesKey,
boolean includeTransactions,
boolean includeExtensions,
AbstractBlockChain chain)
Deprecated.
|
void |
upgradeToDeterministic(org.bouncycastle.crypto.params.KeyParameter aesKey)
Deprecated.
Use
#upgradeToDeterministic(ScriptType, KeyParameter) |
void |
upgradeToDeterministic(Script.ScriptType outputScriptType,
KeyChainGroupStructure structure,
org.bouncycastle.crypto.params.KeyParameter aesKey)
Upgrades the wallet to be deterministic (BIP32).
|
void |
upgradeToDeterministic(Script.ScriptType outputScriptType,
org.bouncycastle.crypto.params.KeyParameter aesKey)
Upgrades the wallet to be deterministic (BIP32).
|
getTag, getTags, maybeGetTag
protected final java.util.concurrent.locks.ReentrantLock lock
protected final java.util.concurrent.locks.ReentrantLock keyChainGroupLock
protected final java.util.Map<Sha256Hash,Transaction> transactions
protected final java.util.HashSet<TransactionOutput> myUnspents
protected final Context context
protected final NetworkParameters params
protected volatile WalletFiles vFileManager
protected volatile TransactionBroadcaster vTransactionBroadcaster
protected CoinSelector coinSelector
@Deprecated public Wallet(NetworkParameters params)
#createDeterministic(NetworkParameters, ScriptType)
loadFromFile(java.io.File, org.bitcoinj.wallet.WalletExtension...)
.params
- network parameters@Deprecated public Wallet(Context context)
#createDeterministic(Context, ScriptType)
loadFromFile(java.io.File, org.bitcoinj.wallet.WalletExtension...)
.public Wallet(NetworkParameters params, KeyChainGroup keyChainGroup)
public static Wallet createDeterministic(NetworkParameters params, Script.ScriptType outputScriptType)
loadFromFile(java.io.File, org.bitcoinj.wallet.WalletExtension...)
.params
- network parametersoutputScriptType
- type of addresses (aka output scripts) to generate for receivingpublic static Wallet createDeterministic(Context context, Script.ScriptType outputScriptType)
loadFromFile(java.io.File, org.bitcoinj.wallet.WalletExtension...)
.outputScriptType
- type of addresses (aka output scripts) to generate for receivingpublic static Wallet createBasic(NetworkParameters params)
params
- network parameterspublic static Wallet fromSeed(NetworkParameters params, DeterministicSeed seed, Script.ScriptType outputScriptType)
params
- network parametersseed
- deterministic seedoutputScriptType
- type of addresses (aka output scripts) to generate for receivingpublic static Wallet fromSeed(NetworkParameters params, DeterministicSeed seed, Script.ScriptType outputScriptType, KeyChainGroupStructure structure)
params
- network parametersseed
- deterministic seedoutputScriptType
- type of addresses (aka output scripts) to generate for receivingstructure
- structure for your wallet@Deprecated public static Wallet fromSeed(NetworkParameters params, DeterministicSeed seed)
#fromSeed(NetworkParameters, DeterministicSeed, ScriptType, KeyChainGroupStructure)
params
- network parametersseed
- deterministic seed0 hardened path
public static Wallet fromSeed(NetworkParameters params, DeterministicSeed seed, Script.ScriptType outputScriptType, com.google.common.collect.ImmutableList<ChildNumber> accountPath)
params
- network parametersseed
- deterministic seedoutputScriptType
- type of addresses (aka output scripts) to generate for receivingaccountPath
- account path to generate receiving addresses on@Deprecated public static Wallet fromSeed(NetworkParameters params, DeterministicSeed seed, com.google.common.collect.ImmutableList<ChildNumber> accountPath)
#fromSeed(NetworkParameters, DeterministicSeed, ScriptType, ImmutableList)
params
- network parametersseed
- deterministic seedaccountPath
- account pathpublic static Wallet fromWatchingKey(NetworkParameters params, DeterministicKey watchKey, Script.ScriptType outputScriptType)
DeterministicKeyChain.getWatchingKey()
.@Deprecated public static Wallet fromWatchingKey(NetworkParameters params, DeterministicKey watchKey)
#fromWatchingKey(NetworkParameters, DeterministicKey, ScriptType)
DeterministicKeyChain.getWatchingKey()
.public static Wallet fromWatchingKeyB58(NetworkParameters params, java.lang.String watchKeyB58, long creationTimeSeconds)
DeterministicHierarchy.BIP32_STANDARDISATION_TIME_SECS
.public static Wallet fromSpendingKey(NetworkParameters params, DeterministicKey spendKey, Script.ScriptType outputScriptType)
DeterministicKeyChain.getWatchingKey()
. This wallet can also spend.@Deprecated public static Wallet fromSpendingKey(NetworkParameters params, DeterministicKey spendKey)
#fromSpendingKey(NetworkParameters, DeterministicKey, ScriptType)
DeterministicKeyChain.getWatchingKey()
. This wallet can also spend.public static Wallet fromSpendingKeyB58(NetworkParameters params, java.lang.String spendingKeyB58, long creationTimeSeconds)
DeterministicHierarchy.BIP32_STANDARDISATION_TIME_SECS
.public static Wallet fromMasterKey(NetworkParameters params, DeterministicKey masterKey, Script.ScriptType outputScriptType, ChildNumber accountNumber)
DeterministicKeyChain.getWatchingKey()
.@Deprecated public static Wallet fromKeys(NetworkParameters params, java.util.List<ECKey> keys)
createBasic(NetworkParameters)
, then importKeys(List)
.public NetworkParameters getNetworkParameters()
public java.util.List<DeterministicKeyChain> getActiveKeyChains()
KeyChainGroup.getActiveKeyChains(long)
.public DeterministicKeyChain getActiveKeyChain()
KeyChainGroup.getActiveKeyChain()
.public final void addTransactionSigner(TransactionSigner signer)
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
public java.util.List<TransactionSigner> getTransactionSigners()
public DeterministicKey currentKey(KeyChain.KeyPurpose purpose)
KeyChain.KeyPurpose.RECEIVE_FUNDS
. The returned key is stable until
it's actually seen in a pending or confirmed transaction, at which point this method will start returning
a different key (for each purpose independently).public DeterministicKey currentReceiveKey()
currentKey(KeyChain.KeyPurpose)
with
KeyChain.KeyPurpose.RECEIVE_FUNDS
as the parameter.public Address currentAddress(KeyChain.KeyPurpose purpose)
currentKey(KeyChain.KeyPurpose)
public Address currentReceiveAddress()
currentAddress(KeyChain.KeyPurpose)
with
KeyChain.KeyPurpose.RECEIVE_FUNDS
as the parameter.public DeterministicKey freshKey(KeyChain.KeyPurpose purpose)
DeterministicKeyChain
. When the parameter is
KeyChain.KeyPurpose.RECEIVE_FUNDS
the returned key is suitable for being put
into a receive coins wizard type UI. You should use this when the user is definitely going to hand this key out
to someone who wishes to send money.public java.util.List<DeterministicKey> freshKeys(KeyChain.KeyPurpose purpose, int numberOfKeys)
DeterministicKeyChain
. When the parameter is
KeyChain.KeyPurpose.RECEIVE_FUNDS
the returned key is suitable for being put
into a receive coins wizard type UI. You should use this when the user is definitely going to hand this key/s out
to someone who wishes to send money.public DeterministicKey freshReceiveKey()
freshKey(KeyChain.KeyPurpose)
with
KeyChain.KeyPurpose.RECEIVE_FUNDS
as the parameter.public Address freshAddress(KeyChain.KeyPurpose purpose)
freshKey(KeyChain.KeyPurpose)
public Address freshReceiveAddress()
freshAddress(KeyChain.KeyPurpose)
with
KeyChain.KeyPurpose.RECEIVE_FUNDS
as the parameter.public Address freshReceiveAddress(Script.ScriptType scriptType)
Returns a fresh receive address for a given Script.ScriptType
.
This method is meant for when you really need a fallback address. Normally, you should be
using freshAddress(KeyChain.KeyPurpose)
or
currentAddress(KeyChain.KeyPurpose)
.
public java.util.List<ECKey> getIssuedReceiveKeys()
freshReceiveKey()
, freshReceiveAddress()
,
currentReceiveKey()
or currentReceiveAddress()
.public java.util.List<Address> getIssuedReceiveAddresses()
freshReceiveKey()
, freshReceiveAddress()
,
currentReceiveKey()
or currentReceiveAddress()
.@Deprecated public void upgradeToDeterministic(@Nullable org.bouncycastle.crypto.params.KeyParameter aesKey)
#upgradeToDeterministic(ScriptType, KeyParameter)
public void upgradeToDeterministic(Script.ScriptType outputScriptType, @Nullable org.bouncycastle.crypto.params.KeyParameter aesKey) throws DeterministicUpgradeRequiresPassword
public void upgradeToDeterministic(Script.ScriptType outputScriptType, KeyChainGroupStructure structure, @Nullable org.bouncycastle.crypto.params.KeyParameter aesKey) throws DeterministicUpgradeRequiresPassword
@Deprecated public boolean isDeterministicUpgradeRequired()
#isDeterministicUpgradeRequired(ScriptType)
public boolean isDeterministicUpgradeRequired(Script.ScriptType outputScriptType)
#upgradeToDeterministic(ScriptType, KeyParameter)
before attempting to do anything
that would require a new address or key.public java.util.List<Script> getWatchedScripts()
public boolean removeKey(ECKey key)
public int getKeyChainGroupSize()
public int getKeyChainGroupCombinedKeyLookaheadEpochs()
public java.util.List<ECKey> getImportedKeys()
public Address currentChangeAddress()
public boolean importKey(ECKey key)
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.
public int importKeys(java.util.List<ECKey> keys)
autosaveToFile(File, long, TimeUnit, WalletFiles.Listener)
has been called, triggers an auto save bypassing the normal coalescing delay and event handlers.
Returns the number of keys added, after duplicates are ignored. The onKeyAdded event will be called for each key
in the list that was not already present.public int importKeysAndEncrypt(java.util.List<ECKey> keys, java.lang.CharSequence password)
public int importKeysAndEncrypt(java.util.List<ECKey> keys, org.bouncycastle.crypto.params.KeyParameter aesKey)
public void addAndActivateHDChain(DeterministicKeyChain chain)
MarriedKeyChain chain = MarriedKeyChain.builder()
.random(new SecureRandom())
.followingKeys(followingKeys)
.threshold(2).build();
wallet.addAndActivateHDChain(chain);
public int getKeyChainGroupLookaheadSize()
DeterministicKeyChain.setLookaheadSize(int)
for more info on this.public int getKeyChainGroupLookaheadThreshold()
DeterministicKeyChain.setLookaheadThreshold(int)
for more info on this.public DeterministicKey getWatchingKey()
public boolean isWatching()
java.lang.IllegalStateException
- if there are no keys, or if there is a mix between watching and non-watching keys.public boolean isAddressWatched(Address address)
public boolean addWatchedAddress(Address address)
addWatchedAddress(Address, long)
with the current time as the creation time.public boolean addWatchedAddress(Address address, long creationTime)
getWatchedOutputs(boolean)
.creationTime
- creation time in seconds since the epoch, for scanning the blockchainpublic int addWatchedAddresses(java.util.List<Address> addresses, long creationTime)
getWatchedOutputs(boolean)
.public int addWatchedScripts(java.util.List<Script> scripts)
getWatchedOutputs(boolean)
.
If a script is already being watched, the object is replaced with the one in the given list. As Script
equality is defined in terms of program bytes only this lets you update metadata such as creation time. Note that
you should be careful not to add scripts with a creation time of zero (the default!) because otherwise it will
disable the important wallet checkpointing optimisation.public boolean removeWatchedAddress(Address address)
public boolean removeWatchedAddresses(java.util.List<Address> addresses)
public boolean removeWatchedScripts(java.util.List<Script> scripts)
public java.util.List<Address> getWatchedAddresses()
@Deprecated public ECKey findKeyFromPubHash(byte[] pubKeyHash)
#findKeyFromPubKeyHash(byte[], ScriptType)
@Nullable public ECKey findKeyFromPubKeyHash(byte[] pubKeyHash, @Nullable Script.ScriptType scriptType)
findKeyFromPubKeyHash
in interface KeyBag
pubKeyHash
- hash of the keypair to look forscriptType
- only look for given usage (currently Script.ScriptType#P2PKH
or
Script.ScriptType#P2WPKH
) or null
if we don't carepublic boolean hasKey(ECKey key)
public boolean isAddressMine(Address address)
@Deprecated public boolean isPubKeyHashMine(byte[] pubKeyHash)
#isPubKeyHashMine(byte[], ScriptType)
public boolean isPubKeyHashMine(byte[] pubKeyHash, @Nullable Script.ScriptType scriptType)
TransactionBag
isPubKeyHashMine
in interface TransactionBag
pubKeyHash
- hash of the public key to look forscriptType
- only look for given usage (currently Script.ScriptType#P2PKH
or Script.ScriptType#P2WPKH
) or null
if we don't carepublic boolean isWatchedScript(Script script)
TransactionBag
isWatchedScript
in interface TransactionBag
public ECKey findKeyFromAddress(Address address)
@Nullable public ECKey findKeyFromPubKey(byte[] pubKey)
findKeyFromPubKey
in interface KeyBag
public boolean isPubKeyMine(byte[] pubKey)
TransactionBag
isPubKeyMine
in interface TransactionBag
@Nullable public RedeemData findRedeemDataFromScriptHash(byte[] payToScriptHash)
findRedeemDataFromScriptHash
in interface KeyBag
public boolean isPayToScriptHashMine(byte[] payToScriptHash)
TransactionBag
isPayToScriptHashMine
in interface TransactionBag
public DeterministicSeed getKeyChainSeed()
ECKey.MissingPrivateKeyException
- if the seed is unavailable (watching wallet)public DeterministicKey getKeyByPath(java.util.List<ChildNumber> path)
public void encrypt(java.lang.CharSequence password)
encrypt(KeyCrypter,
org.bouncycastle.crypto.params.KeyParameter)
which uses the default Scrypt key derivation algorithm and
parameters to derive a key from the given password.public void encrypt(KeyCrypter keyCrypter, org.bouncycastle.crypto.params.KeyParameter aesKey)
KeyCrypterScrypt
.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)KeyCrypterException
- Thrown if the wallet encryption fails. If so, the wallet state is unchanged.public void decrypt(java.lang.CharSequence password)
KeyCrypterException
- Thrown if the wallet decryption fails. If so, the wallet state is unchanged.public void decrypt(org.bouncycastle.crypto.params.KeyParameter aesKey)
aesKey
- AES key to use (normally created using KeyCrypter#deriveKey and cached as it is time consuming to create from a password)KeyCrypterException
- Thrown if the wallet decryption fails. If so, the wallet state is unchanged.public boolean checkPassword(java.lang.CharSequence password)
java.lang.IllegalStateException
- if the wallet is not encrypted.public boolean checkAESKey(org.bouncycastle.crypto.params.KeyParameter aesKey)
@Nullable public KeyCrypter getKeyCrypter()
public Protos.Wallet.EncryptionType getEncryptionType()
public boolean isEncrypted()
public void changeEncryptionPassword(java.lang.CharSequence currentPassword, java.lang.CharSequence newPassword)
public void changeEncryptionKey(KeyCrypter keyCrypter, org.bouncycastle.crypto.params.KeyParameter currentAesKey, org.bouncycastle.crypto.params.KeyParameter newAesKey)
public java.util.List<Protos.Key> serializeKeyChainGroupToProtobuf()
public void saveToFile(java.io.File temp, java.io.File destFile) throws java.io.IOException
java.io.IOException
public void saveToFile(java.io.File f) throws java.io.IOException
WalletProtobufSerializer
. Writes out first to a temporary file in the same directory and then renames
once written.java.io.IOException
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, the DefaultRiskAnalysis
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.
public boolean isAcceptRiskyTransactions()
setAcceptRiskyTransactions(boolean)
for an explanation of this property.public void setRiskAnalyzer(RiskAnalysis.Analyzer analyzer)
RiskAnalysis
implementation to use for deciding whether received pending transactions are risky
or not. If the analyzer says a transaction is risky, by default it will be dropped. You can customize this
behaviour with setAcceptRiskyTransactions(boolean)
.public RiskAnalysis.Analyzer getRiskAnalyzer()
RiskAnalysis
implementation. The default is DefaultRiskAnalysis
.public WalletFiles autosaveToFile(java.io.File f, long delayTime, java.util.concurrent.TimeUnit timeUnit, @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.
If delayTime is set, a background thread will be created and the wallet will only be saved to
disk every so many time units. If no changes have occurred for the given time period, nothing will be written.
In this way disk IO can be rate limited. It's a good idea to set this as otherwise the wallet can change very
frequently, eg if there are a lot of transactions in it or during block sync, and there will be a lot of redundant
writes. Note that when a new key is added, that always results in an immediate save regardless of
delayTime. 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. If a delay greater than 0 was specified, it will be called on a background thread with the wallet locked when an auto-save occurs. If delay is zero or you do something that always triggers an immediate save, like adding a key, the event listener will be invoked on the calling threads.
f
- The destination file to save to.delayTime
- How many time units to wait until saving the wallet on a background thread.timeUnit
- the unit of measurement for delayTime.eventListener
- callback to be informed when the auto-save thread does things, or nullpublic void shutdownAutosaveAndWait()
Disables auto-saving, after it had been enabled with
autosaveToFile(File, long, TimeUnit, WalletFiles.Listener)
before. This method blocks until finished.
protected void saveLater()
protected void saveNow()
public void saveToFileStream(java.io.OutputStream f) throws java.io.IOException
WalletProtobufSerializer
.java.io.IOException
public NetworkParameters getParams()
public Context getContext()
public static Wallet loadFromFile(java.io.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[])
}
file
- the wallet file to readwalletExtensions
- extensions possibly added to the wallet.UnreadableWalletException
public boolean isConsistent()
public void isConsistentOrThrow() throws java.lang.IllegalStateException
isConsistent()
that throws an IllegalStateException
describing the first
inconsistency.java.lang.IllegalStateException
public static Wallet loadFromFileStream(java.io.InputStream stream, @Nullable WalletExtension... walletExtensions) throws UnreadableWalletException
UnreadableWalletException
public boolean notifyTransactionIsInBlock(Sha256Hash txHash, StoredBlock block, AbstractBlockChain.NewBlockType blockType, int relativityOffset) throws VerificationException
BlockChain
when we receive a new filtered block that contains a transactions previously
received by a call to receivePending(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!
notifyTransactionIsInBlock
in interface TransactionReceivedInBlockListener
VerificationException
public void receivePending(Transaction tx, @Nullable java.util.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 the
isPendingTransactionRelevant(Transaction)
sanity-check to keep track of transactions that are not
spendable or spend our coins. This can be useful when you want to keep track of transaction confidence on
arbitrary transactions. Note that transactions added in this way will still be relayed to peers and appear in
transaction lists like any other pending transaction (even when not relevant).
VerificationException
public boolean isTransactionRisky(Transaction tx, @Nullable java.util.List<Transaction> dependencies)
isAcceptRiskyTransactions()
. Risky transactions yield a logged warning. If you
want to know the reason why a transaction is risky, create an instance of the RiskAnalysis
yourself
using the factory returned by getRiskAnalyzer()
and use it directly.public void receivePending(Transaction tx, @Nullable java.util.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.
VerificationException
public boolean isPendingTransactionRelevant(Transaction tx) throws ScriptException
Peer
to find out if a transaction that has been announced is interesting,
that is, whether we should bother downloading its dependencies and exploring the transaction to decide how
risky it is. If this method returns true then receivePending(Transaction, List)
will soon be called with the transactions dependencies as well.ScriptException
public boolean isTransactionRelevant(Transaction tx) throws ScriptException
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.
ScriptException
public void receiveFromBlock(Transaction tx, StoredBlock block, AbstractBlockChain.NewBlockType blockType, int relativityOffset) throws VerificationException
BlockChain
when we receive a new block that sends coins to one of our addresses or
spends coins from one of our addresses (note that a single transaction can do both).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!
receiveFromBlock
in interface TransactionReceivedInBlockListener
VerificationException
public void notifyNewBestBlock(StoredBlock block) throws VerificationException
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 (the reorganize(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.
notifyNewBestBlock
in interface NewBestBlockListener
VerificationException
public boolean maybeCommitTx(Transaction tx) throws VerificationException
commitTx(org.bitcoinj.core.Transaction)
if tx is not already in the pending poolVerificationException
public void commitTx(Transaction tx) throws VerificationException
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:
Triggers an auto save.
VerificationException
public void addChangeEventListener(WalletChangeEventListener listener)
public void addChangeEventListener(java.util.concurrent.Executor executor, WalletChangeEventListener listener)
public void addCoinsReceivedEventListener(WalletCoinsReceivedEventListener listener)
public void addCoinsReceivedEventListener(java.util.concurrent.Executor executor, WalletCoinsReceivedEventListener listener)
public void addCoinsSentEventListener(WalletCoinsSentEventListener listener)
public void addCoinsSentEventListener(java.util.concurrent.Executor executor, WalletCoinsSentEventListener listener)
public void addKeyChainEventListener(KeyChainEventListener listener)
public void addKeyChainEventListener(java.util.concurrent.Executor executor, KeyChainEventListener listener)
public void addReorganizeEventListener(WalletReorganizeEventListener listener)
public void addReorganizeEventListener(java.util.concurrent.Executor executor, WalletReorganizeEventListener listener)
public void addScriptsChangeEventListener(ScriptsChangeEventListener listener)
public void addScriptChangeEventListener(java.util.concurrent.Executor executor, ScriptsChangeEventListener listener)
public void addTransactionConfidenceEventListener(TransactionConfidenceEventListener listener)
public void addTransactionConfidenceEventListener(java.util.concurrent.Executor executor, TransactionConfidenceEventListener listener)
public boolean removeChangeEventListener(WalletChangeEventListener listener)
public boolean removeCoinsReceivedEventListener(WalletCoinsReceivedEventListener listener)
public boolean removeCoinsSentEventListener(WalletCoinsSentEventListener listener)
public boolean removeKeyChainEventListener(KeyChainEventListener listener)
public boolean removeReorganizeEventListener(WalletReorganizeEventListener listener)
public boolean removeScriptChangeEventListener(ScriptsChangeEventListener listener)
public boolean removeTransactionConfidenceEventListener(TransactionConfidenceEventListener listener)
protected void maybeQueueOnWalletChanged()
protected void queueOnCoinsReceived(Transaction tx, Coin balance, Coin newBalance)
protected void queueOnCoinsSent(Transaction tx, Coin prevBalance, Coin newBalance)
protected void queueOnReorganize()
protected void queueOnScriptsChanged(java.util.List<Script> scripts, boolean isAddingScripts)
public java.util.Set<Transaction> getTransactions(boolean includeDead)
includeDead
- If true, transactions that were overridden by a double spend are included.public java.lang.Iterable<WalletTransaction> getWalletTransactions()
public void addWalletTransaction(WalletTransaction wtx)
WalletProtobufSerializer
class. It isn't normally useful for
applications. It does not trigger auto saving.public java.util.List<Transaction> getTransactionsByTime()
public java.util.List<Transaction> getRecentTransactions(int numTransactions, boolean includeDead)
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 (eg if backed by a database).
@Nullable public Transaction getTransaction(Sha256Hash hash)
public java.util.Map<Sha256Hash,Transaction> getTransactionPool(WalletTransaction.Pool pool)
TransactionBag
getTransactionPool
in interface TransactionBag
public void reset()
WalletChangeEventListener.onWalletChanged(org.bitcoinj.wallet.Wallet)
will
be fired.public void clearTransactions(int fromHeight)
public java.util.List<TransactionOutput> getWatchedOutputs(boolean excludeImmatureCoinbases)
addWatchedAddress(Address)
or
addWatchedScripts(java.util.List)
.excludeImmatureCoinbases
- Whether to ignore outputs that are unspendable due to being immature.public void cleanup()
public int getPoolSize(WalletTransaction.Pool pool)
public boolean poolContainsTxHash(WalletTransaction.Pool pool, Sha256Hash txHash)
public java.util.List<TransactionOutput> getUnspents()
public java.lang.String toString()
toString
in class java.lang.Object
@Deprecated public java.lang.String toString(boolean includePrivateKeys, boolean includeTransactions, boolean includeExtensions, @Nullable AbstractBlockChain chain)
toString(boolean, boolean, KeyParameter, boolean, boolean, AbstractBlockChain)
instead.@Deprecated public java.lang.String toString(boolean includePrivateKeys, @Nullable org.bouncycastle.crypto.params.KeyParameter aesKey, boolean includeTransactions, boolean includeExtensions, @Nullable AbstractBlockChain chain)
toString(boolean, boolean, KeyParameter, boolean, boolean, AbstractBlockChain)
instead.public java.lang.String toString(boolean includeLookahead, boolean includePrivateKeys, @Nullable org.bouncycastle.crypto.params.KeyParameter aesKey, boolean includeTransactions, boolean includeExtensions, @Nullable AbstractBlockChain chain)
includeLookahead
- Wether 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 timelocked transactions.public java.util.Collection<Transaction> getPendingTransactions()
public long getEarliestKeyCreationTime()
ECKey.getCreationTimeSeconds()
. This can return zero if at least one key does
not have that data (was created before key timestamping was implemented).
This method is most often used in conjunction with PeerGroup.setFastCatchupTimeSecs(long)
in order to
optimize chain download for new users of wallet apps. Backwards compatibility notice: if you get zero 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, the current time is returned.
getEarliestKeyCreationTime
in interface PeerFilterProvider
@Nullable public Sha256Hash getLastBlockSeenHash()
public void setLastBlockSeenHash(@Nullable Sha256Hash lastBlockSeenHash)
public void setLastBlockSeenHeight(int lastBlockSeenHeight)
public void setLastBlockSeenTimeSecs(long timeSecs)
public long getLastBlockSeenTimeSecs()
@Nullable public java.util.Date getLastBlockSeenTime()
Date
representing the time extracted from the last best seen block header. 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 null.public int getLastBlockSeenHeight()
public int getVersion()
public void setVersion(int version)
getVersion()
.public void setDescription(java.lang.String description)
public java.lang.String getDescription()
setDescription(String)
public Coin getBalance()
Wallet.BalanceType.AVAILABLE
for details on what this
means.public Coin getBalance(Wallet.BalanceType balanceType)
public Coin getBalance(CoinSelector selector)
public com.google.common.util.concurrent.ListenableFuture<Coin> 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. 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.
public Coin getTotalReceived()
public Coin getTotalSent()
public Transaction createSend(Address address, Coin value) throws InsufficientMoneyException
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 by completeTx(SendRequest)
and returning the requests transaction object.
Note that this means a fee may be automatically added if required, if you want more control over the process,
just do those two steps yourself.
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 Transaction.MIN_NONDUST_OUTPUT
or the transaction
will almost certainly be rejected by the network as dust.
address
- The Bitcoin address to send the money to.value
- How much currency to send.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.public Transaction sendCoinsOffline(SendRequest request) throws InsufficientMoneyException
PeerGroup
or Peer
the transaction will be
announced to the network. The given SendRequest
is completed first using
completeTx(SendRequest)
to make it valid.InsufficientMoneyException
- if the request could not be completed due to not enough balance.java.lang.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.public Wallet.SendResult sendCoins(TransactionBroadcaster broadcaster, Address to, Coin value) throws InsufficientMoneyException
Sends coins to the given address, via the given PeerGroup
. Change is returned to
currentChangeAddress()
. 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 Transaction.MIN_NONDUST_OUTPUT
or the transaction will
almost certainly be rejected by the network as dust.
broadcaster
- a TransactionBroadcaster
to use to send the transactions out.to
- Which address to send coins to.value
- How much value to send.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.public Wallet.SendResult sendCoins(TransactionBroadcaster broadcaster, SendRequest request) throws InsufficientMoneyException
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.
broadcaster
- the target to use for broadcast.request
- the SendRequest that describes what to do, get one using static methods on SendRequest itself.InsufficientMoneyException
- if the request could not be completed due to not enough balance.java.lang.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.public Wallet.SendResult sendCoins(SendRequest request) throws InsufficientMoneyException
SendRequest
using the default transaction broadcaster configured either via
PeerGroup.addWallet(Wallet)
or directly with setTransactionBroadcaster(TransactionBroadcaster)
.request
- the SendRequest that describes what to do, get one using static methods on SendRequest itself.java.lang.IllegalStateException
- if no transaction broadcaster has been configured.InsufficientMoneyException
- if the request could not be completed due to not enough balance.java.lang.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.public Transaction sendCoins(Peer peer, SendRequest request) throws InsufficientMoneyException
Peer
. Change is returned to currentChangeAddress()
.
If an exception is thrown by PeerSocketHandler.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.Transaction
that was created or null if there was insufficient balance to send the coins.InsufficientMoneyException
- if the request could not be completed due to not enough balance.java.lang.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.public void completeTx(SendRequest req) throws InsufficientMoneyException
req
- a SendRequest that contains the incomplete transaction and details for how to make it valid.InsufficientMoneyException
- if the request could not be completed due to not enough balance.java.lang.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.public void signTransaction(SendRequest req)
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.
public java.util.List<TransactionOutput> calculateAllSpendCandidates()
public java.util.List<TransactionOutput> calculateAllSpendCandidates(boolean excludeImmatureCoinbases, boolean excludeUnsignable)
UTXOProvider
(in this case the existence or not of private keys is ignored), or the wallets internal storage (the default)
taking into account the flags.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.public boolean canSignFor(Script script)
protected java.util.LinkedList<TransactionOutput> calculateAllSpendCandidatesFromUTXOProvider(boolean excludeImmatureCoinbases)
UTXOProvider
based on keys that the wallet contains.protected java.util.List<UTXO> getStoredOutputsFromUTXOProvider() throws UTXOProviderException
UTXO
's from the UTXOProvider
based on keys that the
wallet contains.UTXOProviderException
public CoinSelector getCoinSelector()
CoinSelector
object which controls which outputs can be spent by this wallet.public void setCoinSelector(CoinSelector coinSelector)
SendRequest.coinSelector
.public void allowSpendingUnconfirmedTransactions()
setCoinSelector(Wallet.AllowUnconfirmedCoinSelector.get())
. If this method
is called on the wallet then transactions will be used for spending regardless of their confidence. This can
be dangerous - only use this if you absolutely know what you're doing!@Nullable public UTXOProvider getUTXOProvider()
UTXOProvider
.public void setUTXOProvider(@Nullable UTXOProvider provider)
UTXOProvider
.
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.
public void reorganize(StoredBlock splitPoint, java.util.List<StoredBlock> oldBlocks, java.util.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.
reorganize
in interface ReorganizeListener
VerificationException
public void beginBloomFilterCalculation()
PeerFilterProvider
beginBloomFilterCalculation
in interface PeerFilterProvider
public void endBloomFilterCalculation()
endBloomFilterCalculation
in interface PeerFilterProvider
public int getBloomFilterElementCount()
getBloomFilterElementCount
in interface PeerFilterProvider
public boolean isRequiringUpdateAllBloomFilter()
isRequiringUpdateAllBloomFilter
in interface PeerFilterProvider
public BloomFilter getBloomFilter(double falsePositiveRate)
BloomFilter
for a brief explanation of anonymity when using filters.public BloomFilter getBloomFilter(int size, double falsePositiveRate, long 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. 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.BloomFilter(int, double, long, BloomFilter.BloomUpdate)
for a brief explanation of anonymity when using bloom
filters.
getBloomFilter
in interface PeerFilterProvider
public boolean checkForFilterExhaustion(FilteredBlock block)
Peer
to decide whether or not to discard this block and any blocks building upon it, in case
the Bloom filter used to request them may be exhausted, that is, not have sufficient keys in the deterministic
sequence within it to reliably find relevant transactions.public void addExtension(WalletExtension extension)
WalletExtension
interface, you can save and load arbitrary
additional data that will be stored with the wallet. Each extension is identified by an ID, so attempting to
add the same extension twice (or two different objects that use the same ID) will throw an IllegalStateException.public WalletExtension addOrGetExistingExtension(WalletExtension extension)
public void addOrUpdateExtension(WalletExtension extension)
public java.util.Map<java.lang.String,WalletExtension> getExtensions()
public void deserializeExtension(WalletExtension extension, byte[] data) throws java.lang.Exception
java.lang.Exception
public void setTag(java.lang.String tag, com.google.protobuf.ByteString value)
TaggableObject
setTag
in interface TaggableObject
setTag
in class BaseTaggableObject
public void setTransactionBroadcaster(@Nullable TransactionBroadcaster broadcaster)
Specifies that the given TransactionBroadcaster
, typically a PeerGroup
, should be used for
sending transactions to the Bitcoin network by default. Some sendCoins methods let you specify a broadcaster
explicitly, in that case, they don't use this broadcaster. If null is specified then the wallet won't attempt
to broadcast transactions itself.
You don't normally need to call this. A PeerGroup
will automatically set itself as the wallets
broadcaster when you use PeerGroup.addWallet(Wallet)
. A wallet can use the broadcaster when you ask
it to send money, but in future also at other times to implement various features that may require asynchronous
re-organisation of the wallet contents on the block chain. For instance, in future the wallet may choose to
optimise itself to reduce fees or improve privacy.
public void setKeyRotationTime(@Nullable java.util.Date time)
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(KeyParameter, 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.
public void setKeyRotationTime(long unixTimeSeconds)
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 0
as the argument.
Once set up, calling doMaintenance(KeyParameter, 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.
@Nullable public java.util.Date getKeyRotationTime()
setKeyRotationTime(Date)
for a description
of the field.public boolean isKeyRotating(ECKey key)
public com.google.common.util.concurrent.ListenableFuture<java.util.List<Transaction>> doMaintenance(@Nullable org.bouncycastle.crypto.params.KeyParameter aesKey, boolean signAndSend) throws DeterministicUpgradeRequiresPassword
aesKey
- the users password, if any.signAndSend
- if true, send the transactions via the tx broadcaster and return them, if false just return them.DeterministicUpgradeRequiresPassword
- if key rotation requires the users password.public com.google.common.util.concurrent.ListenableFuture<java.util.List<Transaction>> doMaintenance(KeyChainGroupStructure structure, @Nullable org.bouncycastle.crypto.params.KeyParameter aesKey, boolean signAndSend) throws DeterministicUpgradeRequiresPassword
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.DeterministicUpgradeRequiresPassword
- if key rotation requires the users password.