Class Transaction
- java.lang.Object
-
- org.bitcoinj.core.BaseMessage
-
- org.bitcoinj.core.Transaction
-
- All Implemented Interfaces:
Message
public class Transaction extends BaseMessage
A transaction represents the movement of coins from some addresses to some other addresses. It can also represent the minting of new coins. A Transaction object corresponds to the equivalent in the Bitcoin C++ implementation.
Transactions are the fundamental atoms of Bitcoin and have many powerful features. Read "Working with transactions" in the documentation to learn more about how to use this class.
All Bitcoin transactions are at risk of being reversed, though the risk is much less than with traditional payment systems. Transactions have confidence levels, which help you decide whether to trust a transaction or not. Whether to trust a transaction is something that needs to be decided on a case by case basis - a rule that makes sense for selling MP3s might not make sense for selling cars, or accepting payments from a family member. If you are building a wallet, how to present confidence to your users is something to consider carefully.
Instances of this class are not safe for use by multiple threads.
-
-
Nested Class Summary
Nested Classes Modifier and Type Class Description static class
Transaction.Purpose
This enum describes the underlying reason the transaction was created.static class
Transaction.SigHash
These constants are a part of a scriptSig signature on the inputs.
-
Field Summary
Fields Modifier and Type Field Description static Coin
DEFAULT_TX_FEE
If using this feePerKb, transactions will get confirmed within the next couple of blocks.static int
LOCKTIME_THRESHOLD
Deprecated.static int
MAX_STANDARD_TX_SIZE
How many bytes a transaction can be before it won't be relayed anymore.static Coin
REFERENCE_DEFAULT_MIN_TX_FEE
If feePerKb is lower than this, Bitcoin Core will treat it as if there were no fee.static int
SERIALIZE_TRANSACTION_NO_WITNESS
When this bit is set in protocolVersion, do not include witness.static byte
SIGHASH_ANYONECANPAY_VALUE
Deprecated.Instead use SigHash.ANYONECANPAY.value or SigHash.ANYONECANPAY.byteValue() as appropriate.static java.util.Comparator<Transaction>
SORT_TX_BY_HEIGHT
A comparator that can be used to sort transactions by their chain height.static java.util.Comparator<Transaction>
SORT_TX_BY_UPDATE_TIME
A comparator that can be used to sort transactions by their updateTime field.
-
Constructor Summary
Constructors Constructor Description Transaction()
-
Method Summary
All Methods Static Methods Instance Methods Concrete Methods Deprecated Methods Modifier and Type Method Description void
addBlockAppearance(Sha256Hash blockHash, int relativityOffset)
TransactionInput
addInput(Sha256Hash spendTxHash, long outputIndex, Script script)
Creates and adds an input to this transaction, with no checking that it's valid.TransactionInput
addInput(TransactionInput input)
Adds an input directly, with no checking that it's valid.TransactionInput
addInput(TransactionOutput from)
Adds an input to this transaction that imports value from the given output.TransactionOutput
addOutput(Coin value, Address address)
Creates an output based on the given address and value, adds it to this transaction, and returns the new output.TransactionOutput
addOutput(Coin value, ECKey pubkey)
Creates an output that pays to the given pubkey directly (no address) with the given value, adds it to this transaction, and returns the new output.TransactionOutput
addOutput(Coin value, Script script)
Creates an output that pays to the given script.TransactionOutput
addOutput(TransactionOutput to)
Adds the given output to this transaction.TransactionInput
addSignedInput(TransactionOutPoint prevOut, Script scriptPubKey, Coin amount, ECKey sigKey)
Adds a new and fully signed input for the given parameters.TransactionInput
addSignedInput(TransactionOutPoint prevOut, Script scriptPubKey, Coin amount, ECKey sigKey, Transaction.SigHash sigHash, boolean anyoneCanPay)
Adds a new and fully signed input for the given parameters.TransactionInput
addSignedInput(TransactionOutPoint prevOut, Script scriptPubKey, ECKey sigKey)
Deprecated.TransactionInput
addSignedInput(TransactionOutPoint prevOut, Script scriptPubKey, ECKey sigKey, Transaction.SigHash sigHash, boolean anyoneCanPay)
TransactionInput
addSignedInput(TransactionOutput output, ECKey sigKey)
Adds an input that points to the given output and contains a valid signature for it, calculated using the signing key.TransactionInput
addSignedInput(TransactionOutput output, ECKey sigKey, Transaction.SigHash sigHash, boolean anyoneCanPay)
Adds an input that points to the given output and contains a valid signature for it, calculated using the signing key.protected void
bitcoinSerializeToStream(java.io.OutputStream stream)
Serializes this message to the provided stream.protected void
bitcoinSerializeToStream(java.io.OutputStream stream, boolean useSegwit)
Serialize according to BIP144 or the classic format, depending on if segwit is desired.TransactionSignature
calculateSignature(int inputIndex, ECKey key, byte[] redeemScript, Transaction.SigHash hashType, boolean anyoneCanPay)
Calculates a signature that is valid for being inserted into the input at the given position.TransactionSignature
calculateSignature(int inputIndex, ECKey key, AesKey aesKey, byte[] redeemScript, Transaction.SigHash hashType, boolean anyoneCanPay)
Calculates a signature that is valid for being inserted into the input at the given position.TransactionSignature
calculateSignature(int inputIndex, ECKey key, AesKey aesKey, Script redeemScript, Transaction.SigHash hashType, boolean anyoneCanPay)
Calculates a signature that is valid for being inserted into the input at the given position.TransactionSignature
calculateSignature(int inputIndex, ECKey key, Script redeemScript, Transaction.SigHash hashType, boolean anyoneCanPay)
Calculates a signature that is valid for being inserted into the input at the given position.TransactionSignature
calculateWitnessSignature(int inputIndex, ECKey key, byte[] scriptCode, Coin value, Transaction.SigHash hashType, boolean anyoneCanPay)
TransactionSignature
calculateWitnessSignature(int inputIndex, ECKey key, AesKey aesKey, byte[] scriptCode, Coin value, Transaction.SigHash hashType, boolean anyoneCanPay)
TransactionSignature
calculateWitnessSignature(int inputIndex, ECKey key, AesKey aesKey, Script scriptCode, Coin value, Transaction.SigHash hashType, boolean anyoneCanPay)
TransactionSignature
calculateWitnessSignature(int inputIndex, ECKey key, Script scriptCode, Coin value, Transaction.SigHash hashType, boolean anyoneCanPay)
void
checkCoinBaseHeight(int height)
Check block height is in coinbase input script, for use after BIP 34 enforcement is enabled.void
clearInputs()
Removes all the inputs from this transaction.void
clearOutputs()
Removes all the outputs from this transaction.void
clearUpdateTime()
Clears the update time of this transaction.static Transaction
coinbase()
Constructs an incomplete coinbase transaction with a minimal input script and no outputs.static Transaction
coinbase(byte[] inputScriptBytes)
Constructs an incomplete coinbase transaction with given bytes for the input script and no outputs.boolean
equals(java.lang.Object o)
java.util.Date
estimateLockTime(AbstractBlockChain chain)
Deprecated.java.time.Instant
estimateUnlockTime(AbstractBlockChain chain)
Returns either the lock time, if it was specified as a timestamp, or an estimate based on the time in the current head block if it was specified as a block height.Sha256Hash
findWitnessCommitment()
Loops the outputs of a coinbase transaction to locate the witness commitment.java.util.Map<Sha256Hash,java.lang.Integer>
getAppearsInHashes()
Returns a map of block [hashes] which contain the transaction mapped to relativity counters, or null if this transaction doesn't have that data because it's not stored in the wallet or because it has never appeared in a block.TransactionConfidence
getConfidence()
Returns the confidence object for this transaction from theTxConfidenceTable
referenced by the implicitContext
.TransactionConfidence
getConfidence(Context context)
Returns the confidence object for this transaction from theTxConfidenceTable
referenced by the givenContext
.TransactionConfidence
getConfidence(TxConfidenceTable table)
Returns the confidence object for this transaction from theTxConfidenceTable
ExchangeRate
getExchangeRate()
Getter forexchangeRate
.Coin
getFee()
The transaction fee is the difference of the value of all inputs and the value of all outputs.TransactionInput
getInput(long index)
Same as getInputs().get(index).java.util.List<TransactionInput>
getInputs()
Returns an unmodifiable view of all inputs.Coin
getInputSum()
Gets the sum of all transaction inputs, regardless of who owns them.long
getLockTime()
Deprecated.uselockTime()
java.lang.String
getMemo()
Returns the transactionmemo
.int
getMessageSizeForPriorityCalc()
The priority (coin age) calculation doesn't use the regular message size, but rather one adjusted downwards for the number of inputs.TransactionOutput
getOutput(long index)
Same as getOutputs().get(index)TransactionOutput
getOutput(TransactionOutPoint outpoint)
Gets the output the gihven outpoint is referring to.java.util.List<TransactionOutput>
getOutputs()
Returns an unmodifiable view of all outputs.Coin
getOutputSum()
Gets the sum of the outputs of the transaction.Transaction.Purpose
getPurpose()
Returns the purpose for which this transaction was created.int
getSigOpCount()
Gets the count of regular SigOps in this transactionsSha256Hash
getTxId()
Returns the transaction id as you see them in block explorers.java.util.Date
getUpdateTime()
Deprecated.useupdateTime()
Coin
getValue(TransactionBag wallet)
Returns the difference ofgetValueSentToMe(TransactionBag)
andgetValueSentFromMe(TransactionBag)
.Coin
getValueSentFromMe(TransactionBag wallet)
Calculates the sum of the inputs that are spending coins with keys in the wallet.Coin
getValueSentToMe(TransactionBag transactionBag)
Calculates the sum of the outputs that are sending coins to a key in the wallet.long
getVersion()
int
getVsize()
Gets the virtual transaction size as defined in BIP141.java.util.List<TransactionOutput>
getWalletOutputs(TransactionBag transactionBag)
Returns the list of transacion outputs, whether spent or unspent, that match a wallet by address or that are watched by a wallet, i.e., transaction outputs whose script's address is controlled by the wallet and transaction outputs whose script is watched by the wallet.int
getWeight()
Gets the transaction weight as defined in BIP141.Sha256Hash
getWTxId()
Returns the witness transaction id (aka witness id) as per BIP144.boolean
hasConfidence()
Check if the transaction has a known confidenceint
hashCode()
Sha256Hash
hashForSignature(int inputIndex, byte[] connectedScript, byte sigHashType)
This is required for signatures which use a sigHashType which cannot be represented using SigHash and anyoneCanPay See transaction c99c49da4c38af669dea436d3e73780dfdb6c1ecf9958baa52960e8baee30e73, which has sigHashType 0Sha256Hash
hashForSignature(int inputIndex, byte[] redeemScript, Transaction.SigHash type, boolean anyoneCanPay)
Calculates a signature hash, that is, a hash of a simplified form of the transaction.Sha256Hash
hashForSignature(int inputIndex, Script redeemScript, Transaction.SigHash type, boolean anyoneCanPay)
Calculates a signature hash, that is, a hash of a simplified form of the transaction.Sha256Hash
hashForWitnessSignature(int inputIndex, byte[] scriptCode, Coin prevValue, byte sigHashType)
Sha256Hash
hashForWitnessSignature(int inputIndex, byte[] scriptCode, Coin prevValue, Transaction.SigHash type, boolean anyoneCanPay)
Sha256Hash
hashForWitnessSignature(int inputIndex, Script scriptCode, Coin prevValue, Transaction.SigHash type, boolean anyoneCanPay)
Calculates a signature hash, that is, a hash of a simplified form of the transaction.boolean
hasRelativeLockTime()
A transaction has a relative lock time (BIP 68) if it is version 2 or higher and at least one of its inputs has itsTransactionInput.SEQUENCE_LOCKTIME_DISABLE_FLAG
cleared.boolean
hasWitnesses()
boolean
isAnyOutputSpent()
Returns true if any of the outputs is marked as spent.boolean
isCoinBase()
A coinbase transaction is one that creates a new coin.boolean
isEveryOwnedOutputSpent(TransactionBag transactionBag)
Returns false if this transaction has at least one output that is owned by the given wallet and unspent, true otherwise.boolean
isFinal(int height, long blockTimeSeconds)
Returns true if this transaction is considered finalized and can be placed in a block.boolean
isOptInFullRBF()
Returns whether this transaction will opt into the full replace-by-fee semantics.boolean
isPending()
Convenience wrapper around getConfidence().getConfidenceType()boolean
isTimeLocked()
A transaction is time-locked if at least one of its inputs is non-final and it has a lock time.LockTime
lockTime()
Transactions can have an associated lock time, specified either as a block height or as a timestamp (in seconds since epoch).int
messageSize()
Return the size of the serialized message.static Transaction
read(java.nio.ByteBuffer payload)
Deserialize this message from a given payload.static Transaction
read(java.nio.ByteBuffer payload, int protocolVersion)
Deserialize this message from a given payload, according to BIP144 or the classic format, depending on if the transaction is segwit or not.void
setBlockAppearance(StoredBlock block, boolean bestChain, int relativityOffset)
Puts the given block in the internal set of blocks in which this transaction appears.void
setExchangeRate(ExchangeRate exchangeRate)
Setter forexchangeRate
.void
setLockTime(long lockTime)
Transactions can have an associated lock time, specified either as a block height or as a timestamp (in seconds since epoch).void
setMemo(java.lang.String memo)
Set the transactionmemo
.void
setPurpose(Transaction.Purpose purpose)
Marks the transaction as being created for the given purpose.void
setUpdateTime(java.time.Instant updateTime)
Sets the update time of this transaction.void
setUpdateTime(java.util.Date updateTime)
Deprecated.void
setVersion(int version)
void
shuffleOutputs()
Randomly re-orders the transaction outputs: good for privacyjava.lang.String
toString()
java.lang.String
toString(AbstractBlockChain chain, Network network)
A human-readable version of the transaction useful for debugging.java.lang.String
toString(AbstractBlockChain chain, Network network, java.lang.CharSequence indent)
A human-readable version of the transaction useful for debugging.java.util.Optional<java.time.Instant>
updateTime()
Returns the earliest time at which the transaction was seen (broadcast or included into the chain), or empty if that information isn't available.static void
verify(Network network, Transaction tx)
Checks the transaction contents for sanity, in ways that can be done in a standalone manner.static void
verify(NetworkParameters params, Transaction tx)
Deprecated.-
Methods inherited from class org.bitcoinj.core.BaseMessage
serialize
-
Methods inherited from class java.lang.Object
clone, finalize, getClass, notify, notifyAll, wait, wait, wait
-
Methods inherited from interface org.bitcoinj.core.Message
bitcoinSerialize, getMessageSize, unsafeBitcoinSerialize
-
-
-
-
Field Detail
-
SORT_TX_BY_UPDATE_TIME
public static final java.util.Comparator<Transaction> SORT_TX_BY_UPDATE_TIME
A comparator that can be used to sort transactions by their updateTime field. The ordering goes from most recent into the past. Transactions with an unknown update time will go to the end.
-
SORT_TX_BY_HEIGHT
public static final java.util.Comparator<Transaction> SORT_TX_BY_HEIGHT
A comparator that can be used to sort transactions by their chain height. Unconfirmed transactions will go to the end.
-
SERIALIZE_TRANSACTION_NO_WITNESS
public static final int SERIALIZE_TRANSACTION_NO_WITNESS
When this bit is set in protocolVersion, do not include witness. The actual value is the same as in Bitcoin Core for consistency.- See Also:
- Constant Field Values
-
LOCKTIME_THRESHOLD
@Deprecated public static final int LOCKTIME_THRESHOLD
Deprecated.- See Also:
- Constant Field Values
-
MAX_STANDARD_TX_SIZE
public static final int MAX_STANDARD_TX_SIZE
How many bytes a transaction can be before it won't be relayed anymore. Currently 100kb.- See Also:
- Constant Field Values
-
REFERENCE_DEFAULT_MIN_TX_FEE
public static final Coin REFERENCE_DEFAULT_MIN_TX_FEE
If feePerKb is lower than this, Bitcoin Core will treat it as if there were no fee.
-
DEFAULT_TX_FEE
public static final Coin DEFAULT_TX_FEE
If using this feePerKb, transactions will get confirmed within the next couple of blocks. This should be adjusted from time to time. Last adjustment: February 2017.
-
SIGHASH_ANYONECANPAY_VALUE
public static final byte SIGHASH_ANYONECANPAY_VALUE
Deprecated.Instead use SigHash.ANYONECANPAY.value or SigHash.ANYONECANPAY.byteValue() as appropriate.- See Also:
- Constant Field Values
-
-
Method Detail
-
coinbase
public static Transaction coinbase()
Constructs an incomplete coinbase transaction with a minimal input script and no outputs.- Returns:
- coinbase transaction
-
coinbase
public static Transaction coinbase(byte[] inputScriptBytes)
Constructs an incomplete coinbase transaction with given bytes for the input script and no outputs.- Parameters:
inputScriptBytes
- arbitrary bytes for the coinbase input- Returns:
- coinbase transaction
-
read
public static Transaction read(java.nio.ByteBuffer payload) throws java.nio.BufferUnderflowException, ProtocolException
Deserialize this message from a given payload.- Parameters:
payload
- payload to deserialize from- Returns:
- read message
- Throws:
java.nio.BufferUnderflowException
- if the read message extends beyond the remaining bytes of the payloadProtocolException
-
read
public static Transaction read(java.nio.ByteBuffer payload, int protocolVersion) throws java.nio.BufferUnderflowException, ProtocolException
Deserialize this message from a given payload, according to BIP144 or the classic format, depending on if the transaction is segwit or not.- Parameters:
payload
- payload to deserialize fromprotocolVersion
- protocol version to use for deserialization- Returns:
- read message
- Throws:
java.nio.BufferUnderflowException
- if the read message extends beyond the remaining bytes of the payloadProtocolException
-
getTxId
public Sha256Hash getTxId()
Returns the transaction id as you see them in block explorers. It is used as a reference by transaction inputs via outpoints.
-
getWTxId
public Sha256Hash getWTxId()
Returns the witness transaction id (aka witness id) as per BIP144. For transactions without witness, this is the same asgetTxId()
.
-
getWeight
public int getWeight()
Gets the transaction weight as defined in BIP141.
-
getVsize
public int getVsize()
Gets the virtual transaction size as defined in BIP141.
-
getInputSum
public Coin getInputSum()
Gets the sum of all transaction inputs, regardless of who owns them.Warning: Inputs with
null
TransactionInput.getValue()
are silently skipped. Before completing or signing a transaction you should verify that there are no inputs withnull
values.- Returns:
- The sum of all inputs with non-null values.
-
getValueSentToMe
public Coin getValueSentToMe(TransactionBag transactionBag)
Calculates the sum of the outputs that are sending coins to a key in the wallet.
-
getAppearsInHashes
@Nullable public java.util.Map<Sha256Hash,java.lang.Integer> getAppearsInHashes()
Returns a map of block [hashes] which contain the transaction mapped to relativity counters, or null if this transaction doesn't have that data because it's not stored in the wallet or because it has never appeared in a block.
-
isPending
public boolean isPending()
Convenience wrapper around getConfidence().getConfidenceType()- Returns:
- true if this transaction hasn't been seen in any block yet.
-
setBlockAppearance
public void setBlockAppearance(StoredBlock block, boolean bestChain, int relativityOffset)
Puts the given block in the internal set of blocks in which this transaction appears. This is used by the wallet to ensure transactions that appear on side chains are recorded properly even though the block stores do not save the transaction data at all.
If there is a re-org this will be called once for each block that was previously seen, to update which block is the best chain. The best chain block is guaranteed to be called last. So this must be idempotent.
Sets updatedAt to be the earliest valid block time where this tx was seen.
- Parameters:
block
- TheStoredBlock
in which the transaction has appeared.bestChain
- whether to set the updatedAt timestamp from the block header (only if not already set)relativityOffset
- A number that disambiguates the order of transactions within a block.
-
addBlockAppearance
public void addBlockAppearance(Sha256Hash blockHash, int relativityOffset)
-
getValueSentFromMe
public Coin getValueSentFromMe(TransactionBag wallet) throws ScriptException
Calculates the sum of the inputs that are spending coins with keys in the wallet. This requires the transactions sending coins to those keys to be in the wallet. This method will not attempt to download the blocks containing the input transactions if the key is in the wallet but the transactions are not.- Returns:
- sum of the inputs that are spending coins with keys in the wallet
- Throws:
ScriptException
-
getOutputSum
public Coin getOutputSum()
Gets the sum of the outputs of the transaction. If the outputs are less than the inputs, it does not count the fee.- Returns:
- the sum of the outputs regardless of who owns them.
-
getValue
public Coin getValue(TransactionBag wallet) throws ScriptException
Returns the difference ofgetValueSentToMe(TransactionBag)
andgetValueSentFromMe(TransactionBag)
.- Throws:
ScriptException
-
getFee
public Coin getFee()
The transaction fee is the difference of the value of all inputs and the value of all outputs. Currently, the fee can only be determined for transactions created by us.- Returns:
- fee, or null if it cannot be determined
-
isAnyOutputSpent
public boolean isAnyOutputSpent()
Returns true if any of the outputs is marked as spent.
-
isEveryOwnedOutputSpent
public boolean isEveryOwnedOutputSpent(TransactionBag transactionBag)
Returns false if this transaction has at least one output that is owned by the given wallet and unspent, true otherwise.
-
updateTime
public java.util.Optional<java.time.Instant> updateTime()
Returns the earliest time at which the transaction was seen (broadcast or included into the chain), or empty if that information isn't available.
-
getUpdateTime
@Deprecated public java.util.Date getUpdateTime()
Deprecated.useupdateTime()
-
setUpdateTime
public void setUpdateTime(java.time.Instant updateTime)
Sets the update time of this transaction.- Parameters:
updateTime
- update time
-
clearUpdateTime
public void clearUpdateTime()
Clears the update time of this transaction.
-
setUpdateTime
@Deprecated public void setUpdateTime(java.util.Date updateTime)
Deprecated.
-
hasWitnesses
public boolean hasWitnesses()
- Returns:
- true of the transaction has any witnesses in any of its inputs
-
getMessageSizeForPriorityCalc
public int getMessageSizeForPriorityCalc()
The priority (coin age) calculation doesn't use the regular message size, but rather one adjusted downwards for the number of inputs. The goal is to incentivise cleaning up the UTXO set with free transactions, if one can do so.
-
isCoinBase
public boolean isCoinBase()
A coinbase transaction is one that creates a new coin. They are the first transaction in each block and their value is determined by a formula that all implementations of Bitcoin share. In 2011 the value of a coinbase transaction is 50 coins, but in future it will be less. A coinbase transaction is defined not only by its position in a block but by the data in the inputs.
-
toString
public java.lang.String toString()
- Overrides:
toString
in classjava.lang.Object
-
toString
public java.lang.String toString(@Nullable AbstractBlockChain chain, @Nullable Network network)
A human-readable version of the transaction useful for debugging. The format is not guaranteed to be stable.- Parameters:
chain
- if provided, will be used to estimate lock times (if set)network
- if provided, network for output scripts converted to addresses
-
toString
public java.lang.String toString(@Nullable AbstractBlockChain chain, @Nullable Network network, java.lang.CharSequence indent)
A human-readable version of the transaction useful for debugging. The format is not guaranteed to be stable.- Parameters:
chain
- if provided, will be used to estimate lock times (if set)network
- if provided, network for output scripts converted to addressesindent
- characters that will be prepended to each line of the output
-
clearInputs
public void clearInputs()
Removes all the inputs from this transaction. Note that this also invalidates the length attribute
-
addInput
public TransactionInput addInput(TransactionOutput from)
Adds an input to this transaction that imports value from the given output. Note that this input is not complete and after every input is added withaddInput(TransactionInput)
and every output is added withaddOutput(TransactionOutput)
, aTransactionSigner
must be used to finalize the transaction and finish the inputs off. Otherwise it won't be accepted by the network.- Returns:
- the newly created input.
-
addInput
public TransactionInput addInput(TransactionInput input)
Adds an input directly, with no checking that it's valid.- Returns:
- the new input.
-
addInput
public TransactionInput addInput(Sha256Hash spendTxHash, long outputIndex, Script script)
Creates and adds an input to this transaction, with no checking that it's valid.- Returns:
- the newly created input.
-
addSignedInput
public TransactionInput addSignedInput(TransactionOutPoint prevOut, Script scriptPubKey, Coin amount, ECKey sigKey, Transaction.SigHash sigHash, boolean anyoneCanPay) throws ScriptException
Adds a new and fully signed input for the given parameters. Note that this method is not thread safe and requires external synchronization. Please refer to general documentation on Bitcoin scripting and contracts to understand the values of sigHash and anyoneCanPay: otherwise you can use the other form of this method that sets them to typical defaults.- Parameters:
prevOut
- A reference to the output being spentscriptPubKey
- The scriptPubKey of the outputamount
- The amount of the output (which is part of the signature hash for segwit)sigKey
- The signing keysigHash
- enum specifying how the transaction hash is calculatedanyoneCanPay
- anyone-can-pay hashing- Returns:
- The newly created input
- Throws:
ScriptException
- if the scriptPubKey is something we don't know how to sign.
-
addSignedInput
@Deprecated public TransactionInput addSignedInput(TransactionOutPoint prevOut, Script scriptPubKey, ECKey sigKey, Transaction.SigHash sigHash, boolean anyoneCanPay) throws ScriptException
- Parameters:
prevOut
- A reference to the output being spentscriptPubKey
- The scriptPubKey of the outputsigKey
- The signing keysigHash
- enum specifying how the transaction hash is calculatedanyoneCanPay
- anyone-can-pay hashing- Returns:
- The newly created input
- Throws:
ScriptException
- if the scriptPubKey is something we don't know how to sign.
-
addSignedInput
public TransactionInput addSignedInput(TransactionOutPoint prevOut, Script scriptPubKey, Coin amount, ECKey sigKey) throws ScriptException
Adds a new and fully signed input for the given parameters. Note that this method is not thread safe and requires external synchronization. Defaults toTransaction.SigHash.ALL
and "false" for the anyoneCanPay flag. This is normally what you want.- Parameters:
prevOut
- A reference to the output being spentscriptPubKey
- The scriptPubKey of the outputamount
- The amount of the output (which is part of the signature hash for segwit)sigKey
- The signing key- Returns:
- The newly created input
- Throws:
ScriptException
- if the scriptPubKey is something we don't know how to sign.
-
addSignedInput
@Deprecated public TransactionInput addSignedInput(TransactionOutPoint prevOut, Script scriptPubKey, ECKey sigKey) throws ScriptException
Deprecated.- Parameters:
prevOut
- A reference to the output being spentscriptPubKey
- The scriptPubKey of the outputsigKey
- The signing key- Returns:
- The newly created input
- Throws:
ScriptException
- if the scriptPubKey is something we don't know how to sign.
-
addSignedInput
public TransactionInput addSignedInput(TransactionOutput output, ECKey sigKey)
Adds an input that points to the given output and contains a valid signature for it, calculated using the signing key. Defaults toTransaction.SigHash.ALL
and "false" for the anyoneCanPay flag. This is normally what you want.- Parameters:
output
- output to sign and use as inputsigKey
- The signing key- Returns:
- The newly created input
-
addSignedInput
public TransactionInput addSignedInput(TransactionOutput output, ECKey sigKey, Transaction.SigHash sigHash, boolean anyoneCanPay)
Adds an input that points to the given output and contains a valid signature for it, calculated using the signing key.- Parameters:
output
- output to sign and use as inputsigKey
- The signing keysigHash
- enum specifying how the transaction hash is calculatedanyoneCanPay
- anyone-can-pay hashing- Returns:
- The newly created input
- See Also:
addSignedInput(TransactionOutPoint, Script, Coin, ECKey, SigHash, boolean)
-
clearOutputs
public void clearOutputs()
Removes all the outputs from this transaction. Note that this also invalidates the length attribute
-
addOutput
public TransactionOutput addOutput(TransactionOutput to)
Adds the given output to this transaction. The output must be completely initialized. Returns the given output.
-
addOutput
public TransactionOutput addOutput(Coin value, Address address)
Creates an output based on the given address and value, adds it to this transaction, and returns the new output.
-
addOutput
public TransactionOutput addOutput(Coin value, ECKey pubkey)
Creates an output that pays to the given pubkey directly (no address) with the given value, adds it to this transaction, and returns the new output.
-
addOutput
public TransactionOutput addOutput(Coin value, Script script)
Creates an output that pays to the given script. The address and key forms are specialisations of this method, you won't normally need to use it unless you're doing unusual things.
-
calculateSignature
public TransactionSignature calculateSignature(int inputIndex, ECKey key, byte[] redeemScript, Transaction.SigHash hashType, boolean anyoneCanPay)
Calculates a signature that is valid for being inserted into the input at the given position. This is simply a wrapper around callinghashForSignature(int, byte[], Transaction.SigHash, boolean)
followed byECKey.sign(Sha256Hash)
and then returning a newTransactionSignature
. The key must be usable for signing as-is: if the key is encrypted it must be decrypted first external to this method.- Parameters:
inputIndex
- Which input to calculate the signature for, as an index.key
- The private key used to calculate the signature.redeemScript
- Byte-exact contents of the scriptPubKey that is being satisfied, or the P2SH redeem script.hashType
- Signing mode, see the enum for documentation.anyoneCanPay
- Signing mode, see the SigHash enum for documentation.- Returns:
- A newly calculated signature object that wraps the r, s and sighash components.
-
calculateSignature
public TransactionSignature calculateSignature(int inputIndex, ECKey key, Script redeemScript, Transaction.SigHash hashType, boolean anyoneCanPay)
Calculates a signature that is valid for being inserted into the input at the given position. This is simply a wrapper around callinghashForSignature(int, byte[], Transaction.SigHash, boolean)
followed byECKey.sign(Sha256Hash)
and then returning a newTransactionSignature
.- Parameters:
inputIndex
- Which input to calculate the signature for, as an index.key
- The private key used to calculate the signature.redeemScript
- The scriptPubKey that is being satisfied, or the P2SH redeem script.hashType
- Signing mode, see the enum for documentation.anyoneCanPay
- Signing mode, see the SigHash enum for documentation.- Returns:
- A newly calculated signature object that wraps the r, s and sighash components.
-
calculateSignature
public TransactionSignature calculateSignature(int inputIndex, ECKey key, @Nullable AesKey aesKey, byte[] redeemScript, Transaction.SigHash hashType, boolean anyoneCanPay)
Calculates a signature that is valid for being inserted into the input at the given position. This is simply a wrapper around callinghashForSignature(int, byte[], Transaction.SigHash, boolean)
followed byECKey.sign(Sha256Hash)
and then returning a newTransactionSignature
. The key must be usable for signing as-is: if the key is encrypted it must be decrypted first external to this method.- Parameters:
inputIndex
- Which input to calculate the signature for, as an index.key
- The private key used to calculate the signature.aesKey
- The AES key to use for decryption of the private key. If null then no decryption is required.redeemScript
- Byte-exact contents of the scriptPubKey that is being satisfied, or the P2SH redeem script.hashType
- Signing mode, see the enum for documentation.anyoneCanPay
- Signing mode, see the SigHash enum for documentation.- Returns:
- A newly calculated signature object that wraps the r, s and sighash components.
-
calculateSignature
public TransactionSignature calculateSignature(int inputIndex, ECKey key, @Nullable AesKey aesKey, Script redeemScript, Transaction.SigHash hashType, boolean anyoneCanPay)
Calculates a signature that is valid for being inserted into the input at the given position. This is simply a wrapper around callinghashForSignature(int, byte[], Transaction.SigHash, boolean)
followed byECKey.sign(Sha256Hash)
and then returning a newTransactionSignature
.- Parameters:
inputIndex
- Which input to calculate the signature for, as an index.key
- The private key used to calculate the signature.aesKey
- The AES key to use for decryption of the private key. If null then no decryption is required.redeemScript
- The scriptPubKey that is being satisfied, or the P2SH redeem script.hashType
- Signing mode, see the enum for documentation.anyoneCanPay
- Signing mode, see the SigHash enum for documentation.- Returns:
- A newly calculated signature object that wraps the r, s and sighash components.
-
hashForSignature
public Sha256Hash hashForSignature(int inputIndex, byte[] redeemScript, Transaction.SigHash type, boolean anyoneCanPay)
Calculates a signature hash, that is, a hash of a simplified form of the transaction. How exactly the transaction is simplified is specified by the type and anyoneCanPay parameters.
This is a low level API and when using the regular
Wallet
class you don't have to call this yourself. When working with more complex transaction types and contracts, it can be necessary. When signing a P2SH output the redeemScript should be the script encoded into the scriptSig field, for normal transactions, it's the scriptPubKey of the output you're signing for.- Parameters:
inputIndex
- input the signature is being calculated for. Tx signatures are always relative to an input.redeemScript
- the bytes that should be in the given input during signing.type
- Should be SigHash.ALLanyoneCanPay
- should be false.
-
hashForSignature
public Sha256Hash hashForSignature(int inputIndex, Script redeemScript, Transaction.SigHash type, boolean anyoneCanPay)
Calculates a signature hash, that is, a hash of a simplified form of the transaction. How exactly the transaction is simplified is specified by the type and anyoneCanPay parameters.
This is a low level API and when using the regular
Wallet
class you don't have to call this yourself. When working with more complex transaction types and contracts, it can be necessary. When signing a P2SH output the redeemScript should be the script encoded into the scriptSig field, for normal transactions, it's the scriptPubKey of the output you're signing for.- Parameters:
inputIndex
- input the signature is being calculated for. Tx signatures are always relative to an input.redeemScript
- the script that should be in the given input during signing.type
- Should be SigHash.ALLanyoneCanPay
- should be false.
-
hashForSignature
public Sha256Hash hashForSignature(int inputIndex, byte[] connectedScript, byte sigHashType)
This is required for signatures which use a sigHashType which cannot be represented using SigHash and anyoneCanPay See transaction c99c49da4c38af669dea436d3e73780dfdb6c1ecf9958baa52960e8baee30e73, which has sigHashType 0
-
calculateWitnessSignature
public TransactionSignature calculateWitnessSignature(int inputIndex, ECKey key, byte[] scriptCode, Coin value, Transaction.SigHash hashType, boolean anyoneCanPay)
-
calculateWitnessSignature
public TransactionSignature calculateWitnessSignature(int inputIndex, ECKey key, Script scriptCode, Coin value, Transaction.SigHash hashType, boolean anyoneCanPay)
-
calculateWitnessSignature
public TransactionSignature calculateWitnessSignature(int inputIndex, ECKey key, @Nullable AesKey aesKey, byte[] scriptCode, Coin value, Transaction.SigHash hashType, boolean anyoneCanPay)
-
calculateWitnessSignature
public TransactionSignature calculateWitnessSignature(int inputIndex, ECKey key, @Nullable AesKey aesKey, Script scriptCode, Coin value, Transaction.SigHash hashType, boolean anyoneCanPay)
-
hashForWitnessSignature
public Sha256Hash hashForWitnessSignature(int inputIndex, byte[] scriptCode, Coin prevValue, Transaction.SigHash type, boolean anyoneCanPay)
-
hashForWitnessSignature
public Sha256Hash hashForWitnessSignature(int inputIndex, Script scriptCode, Coin prevValue, Transaction.SigHash type, boolean anyoneCanPay)
Calculates a signature hash, that is, a hash of a simplified form of the transaction. How exactly the transaction is simplified is specified by the type and anyoneCanPay parameters.
This is a low level API and when using the regular
Wallet
class you don't have to call this yourself. When working with more complex transaction types and contracts, it can be necessary. When signing a Witness output the scriptCode should be the script encoded into the scriptSig field, for normal transactions, it's the scriptPubKey of the output you're signing for. (See BIP143: https://github.com/bitcoin/bips/blob/master/bip-0143.mediawiki)- Parameters:
inputIndex
- input the signature is being calculated for. Tx signatures are always relative to an input.scriptCode
- the script that should be in the given input during signing.prevValue
- the value of the coin being spenttype
- Should be SigHash.ALLanyoneCanPay
- should be false.
-
hashForWitnessSignature
public Sha256Hash hashForWitnessSignature(int inputIndex, byte[] scriptCode, Coin prevValue, byte sigHashType)
-
messageSize
public int messageSize()
Description copied from class:BaseMessage
Return the size of the serialized message. Note that if the message was deserialized from a payload, this size can differ from the size of the original payload.- Specified by:
messageSize
in interfaceMessage
- Overrides:
messageSize
in classBaseMessage
- Returns:
- size of this object when serialized (in bytes)
-
bitcoinSerializeToStream
protected void bitcoinSerializeToStream(java.io.OutputStream stream) throws java.io.IOException
Description copied from class:BaseMessage
Serializes this message to the provided stream. If you just want the raw bytes use bitcoinSerialize().- Specified by:
bitcoinSerializeToStream
in classBaseMessage
- Throws:
java.io.IOException
-
bitcoinSerializeToStream
protected void bitcoinSerializeToStream(java.io.OutputStream stream, boolean useSegwit) throws java.io.IOException
Serialize according to BIP144 or the classic format, depending on if segwit is desired.- Throws:
java.io.IOException
-
lockTime
public LockTime lockTime()
Transactions can have an associated lock time, specified either as a block height or as a timestamp (in seconds since epoch). A transaction is not allowed to be confirmed by miners until the lock time is reached, and since Bitcoin 0.8+ a transaction that did not end its lock period (non final) is considered to be non standard and won't be relayed or included in the memory pool either.- Returns:
- lock time, wrapped in a
LockTime
-
getLockTime
@Deprecated public long getLockTime()
Deprecated.uselockTime()
-
setLockTime
public void setLockTime(long lockTime)
Transactions can have an associated lock time, specified either as a block height or as a timestamp (in seconds since epoch). A transaction is not allowed to be confirmed by miners until the lock time is reached, and since Bitcoin 0.8+ a transaction that did not end its lock period (non final) is considered to be non standard and won't be relayed or included in the memory pool either.
-
getVersion
public long getVersion()
-
setVersion
public void setVersion(int version)
-
getInputs
public java.util.List<TransactionInput> getInputs()
Returns an unmodifiable view of all inputs.
-
getOutputs
public java.util.List<TransactionOutput> getOutputs()
Returns an unmodifiable view of all outputs.
-
getWalletOutputs
public java.util.List<TransactionOutput> getWalletOutputs(TransactionBag transactionBag)
Returns the list of transacion outputs, whether spent or unspent, that match a wallet by address or that are watched by a wallet, i.e., transaction outputs whose script's address is controlled by the wallet and transaction outputs whose script is watched by the wallet.
- Parameters:
transactionBag
- The wallet that controls addresses and watches scripts.- Returns:
- linked list of outputs relevant to the wallet in this transaction
-
shuffleOutputs
public void shuffleOutputs()
Randomly re-orders the transaction outputs: good for privacy
-
getInput
public TransactionInput getInput(long index)
Same as getInputs().get(index).
-
getOutput
public TransactionOutput getOutput(long index)
Same as getOutputs().get(index)
-
getOutput
public TransactionOutput getOutput(TransactionOutPoint outpoint)
Gets the output the gihven outpoint is referring to. Note the output must belong to this transaction, or else anIllegalArgumentException
will occur.- Parameters:
outpoint
- outpoint referring to the output to get- Returns:
- output referred to by the given outpoint
-
getConfidence
public TransactionConfidence getConfidence()
Returns the confidence object for this transaction from theTxConfidenceTable
referenced by the implicitContext
.
-
getConfidence
public TransactionConfidence getConfidence(Context context)
Returns the confidence object for this transaction from theTxConfidenceTable
referenced by the givenContext
.
-
getConfidence
public TransactionConfidence getConfidence(TxConfidenceTable table)
Returns the confidence object for this transaction from theTxConfidenceTable
-
hasConfidence
public boolean hasConfidence()
Check if the transaction has a known confidence
-
equals
public boolean equals(java.lang.Object o)
- Overrides:
equals
in classjava.lang.Object
-
hashCode
public int hashCode()
- Overrides:
hashCode
in classjava.lang.Object
-
getSigOpCount
public int getSigOpCount() throws ScriptException
Gets the count of regular SigOps in this transactions- Throws:
ScriptException
-
checkCoinBaseHeight
public void checkCoinBaseHeight(int height) throws VerificationException
Check block height is in coinbase input script, for use after BIP 34 enforcement is enabled.- Throws:
VerificationException
-
findWitnessCommitment
public Sha256Hash findWitnessCommitment()
Loops the outputs of a coinbase transaction to locate the witness commitment.
-
isTimeLocked
public boolean isTimeLocked()
A transaction is time-locked if at least one of its inputs is non-final and it has a lock time. A transaction can also have a relative lock time which this method doesn't tell. Use
hasRelativeLockTime()
to find out.To check if this transaction is final at a given height and time, see
isFinal(int, long)
-
hasRelativeLockTime
public boolean hasRelativeLockTime()
A transaction has a relative lock time (BIP 68) if it is version 2 or higher and at least one of its inputs has itsTransactionInput.SEQUENCE_LOCKTIME_DISABLE_FLAG
cleared.
-
isOptInFullRBF
public boolean isOptInFullRBF()
Returns whether this transaction will opt into the full replace-by-fee semantics.
-
isFinal
public boolean isFinal(int height, long blockTimeSeconds)
Returns true if this transaction is considered finalized and can be placed in a block. Non-finalized transactions won't be included by miners and can be replaced with newer versions using sequence numbers. This is useful in certain types of contracts, such as micropayment channels.
Note that currently the replacement feature is disabled in Bitcoin Core and will need to be re-activated before this functionality is useful.
-
estimateUnlockTime
public java.time.Instant estimateUnlockTime(AbstractBlockChain chain)
Returns either the lock time, if it was specified as a timestamp, or an estimate based on the time in the current head block if it was specified as a block height.
-
estimateLockTime
@Deprecated public java.util.Date estimateLockTime(AbstractBlockChain chain)
Deprecated.
-
getPurpose
public Transaction.Purpose getPurpose()
Returns the purpose for which this transaction was created. See the javadoc forTransaction.Purpose
for more information on the point of this field and what it can be.
-
setPurpose
public void setPurpose(Transaction.Purpose purpose)
Marks the transaction as being created for the given purpose. See the javadoc forTransaction.Purpose
for more information on the point of this field and what it can be.
-
getExchangeRate
@Nullable public ExchangeRate getExchangeRate()
Getter forexchangeRate
.
-
setExchangeRate
public void setExchangeRate(ExchangeRate exchangeRate)
Setter forexchangeRate
.
-
getMemo
@Nullable public java.lang.String getMemo()
Returns the transactionmemo
.
-
setMemo
public void setMemo(java.lang.String memo)
Set the transactionmemo
. It can be used to record the memo of the payment request that initiated the transaction.
-
verify
public static void verify(Network network, Transaction tx) throws VerificationException
Checks the transaction contents for sanity, in ways that can be done in a standalone manner. Does not perform all checks on a transaction such as whether the inputs are already spent. Specifically this method verifies:
- That there is at least one input and output.
- That the serialized size is not larger than the max block size.
- That no outputs have negative value.
- That the outputs do not sum to larger than the max allowed quantity of coin in the system.
- If the tx is a coinbase tx, the coinbase scriptSig size is within range. Otherwise that there are no coinbase inputs in the tx.
- Parameters:
network
- network for the verification rulestx
- transaction to verify- Throws:
VerificationException
- if at least one of the rules is violated
-
verify
@Deprecated public static void verify(NetworkParameters params, Transaction tx) throws VerificationException
Deprecated.- Throws:
VerificationException
-
-