public class Transaction extends ChildMessage implements Serializable
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.
Modifier and Type | Class and 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.
|
Message.LazyParseException
Modifier and Type | Field and Description |
---|---|
static int |
LOCKTIME_THRESHOLD
Threshold for lockTime: below this value it is interpreted as block number, otherwise as timestamp.
|
static int |
MAX_STANDARD_TX_SIZE
How many bytes a transaction can be before it won't be relayed anymore.
|
static Coin |
MIN_NONDUST_OUTPUT
Any standard (ie pay-to-address) output smaller than this value (in satoshis) will most likely be rejected by the network.
|
static Coin |
REFERENCE_DEFAULT_MIN_TX_FEE
If fee is lower than this value (in satoshis), a default reference client will treat it as if there were no fee.
|
static byte |
SIGHASH_ANYONECANPAY_VALUE |
static Comparator<Transaction> |
SORT_TX_BY_HEIGHT
A comparator that can be used to sort transactions by their chain height.
|
static Comparator<Transaction> |
SORT_TX_BY_UPDATE_TIME
A comparator that can be used to sort transactions by their updateTime field.
|
parent
checksum, cursor, length, MAX_SIZE, offset, params, parsed, parseLazy, parseRetain, payload, protocolVersion, recached, UNKNOWN_LENGTH
Constructor and Description |
---|
Transaction(NetworkParameters params) |
Transaction(NetworkParameters params,
byte[] payloadBytes)
Creates a transaction from the given serialized bytes, eg, from a block or a tx network message.
|
Transaction(NetworkParameters params,
byte[] payload,
int offset)
Creates a transaction by reading payload starting from offset bytes in.
|
Transaction(NetworkParameters params,
byte[] payload,
int offset,
Message parent,
boolean parseLazy,
boolean parseRetain,
int length)
Creates a transaction by reading payload starting from offset bytes in.
|
Transaction(NetworkParameters params,
byte[] payload,
Message parent,
boolean parseLazy,
boolean parseRetain,
int length)
Creates a transaction by reading payload starting from offset bytes in.
|
Modifier and Type | Method and Description |
---|---|
void |
addBlockAppearance(Sha256Hash blockHash,
int relativityOffset) |
TransactionInput |
addInput(Sha256Hash spendTxHash,
long outputIndex,
Script script)
Adds an input directly, 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,
ECKey sigKey)
Same as
addSignedInput(TransactionOutPoint, org.bitcoinj.script.Script, ECKey, org.bitcoinj.core.Transaction.SigHash, boolean)
but defaults to Transaction.SigHash.ALL and "false" for the anyoneCanPay flag. |
TransactionInput |
addSignedInput(TransactionOutPoint prevOut,
Script scriptPubKey,
ECKey sigKey,
Transaction.SigHash sigHash,
boolean anyoneCanPay)
Adds a new and fully signed input for the given parameters.
|
TransactionInput |
addSignedInput(TransactionOutput output,
ECKey signingKey)
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 signingKey,
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(OutputStream stream)
Serializes this message to the provided stream.
|
protected static int |
calcLength(byte[] buf,
int offset) |
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,
Script redeemScript,
Transaction.SigHash hashType,
boolean anyoneCanPay)
Calculates a signature that is valid for being inserted into the input at the given position.
|
void |
clearInputs()
Removes all the inputs from this transaction.
|
void |
clearOutputs()
Removes all the inputs from this transaction.
|
boolean |
equals(Object o) |
Date |
estimateLockTime(AbstractBlockChain chain)
Returns either the lock time as a date, if it was specified in seconds, or an estimate based on the time in
the current head block if it was specified as a block time.
|
Map<Sha256Hash,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() |
ExchangeRate |
getExchangeRate()
Getter for
exchangeRate . |
Coin |
getFee()
The transaction fee is the difference of the value of all inputs and the value of all outputs.
|
Sha256Hash |
getHash()
Returns the transaction hash as you see them in the block explorer.
|
String |
getHashAsString() |
TransactionInput |
getInput(int index) |
List<TransactionInput> |
getInputs()
Returns an unmodifiable view of all inputs.
|
long |
getLockTime()
Transactions can have an associated lock time, specified either as a block height or in seconds since the
UNIX epoch.
|
String |
getMemo()
Returns the transaction
memo . |
int |
getOptimalEncodingMessageSize() |
TransactionOutput |
getOutput(int index) |
List<TransactionOutput> |
getOutputs()
Returns an unmodifiable view of all outputs.
|
Transaction.Purpose |
getPurpose()
Returns the purpose for which this transaction was created.
|
int |
getSigOpCount()
Gets the count of regular SigOps in this transactions
|
Date |
getUpdateTime()
Returns the earliest time at which the transaction was seen (broadcast or included into the chain),
or the epoch if that information isn't available.
|
Coin |
getValue(TransactionBag wallet)
Returns the difference of
getValueSentFromMe(TransactionBag) and getValueSentToMe(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() |
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.
|
boolean |
hasConfidence()
Check if the transaction has a known confidence
|
int |
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 0
|
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.
|
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.
|
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 |
isEveryOutputSpent()
Returns true if every output is marked as spent.
|
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 |
isMature()
A transaction is mature if it is either a building coinbase tx that is as deep or deeper than the required coinbase depth, or a non-coinbase tx.
|
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
|
protected void |
parseLite()
Perform the most minimal parse possible to calculate the length of the message payload.
|
static long |
parseLockTimeStr(String lockTimeStr)
Parses the string either as a whole number of blocks, or if it contains slashes as a YYYY/MM/DD format date
and returns the lock time in wire format.
|
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 for
exchangeRate . |
void |
setLockTime(long lockTime)
Transactions can have an associated lock time, specified either as a block height or in seconds since the
UNIX epoch.
|
void |
setMemo(String memo)
Set the transaction
memo . |
void |
setPurpose(Transaction.Purpose purpose)
Marks the transaction as being created for the given purpose.
|
void |
setUpdateTime(Date updatedAt) |
void |
shuffleOutputs()
Randomly re-orders the transaction outputs: good for privacy
|
String |
toString() |
String |
toString(AbstractBlockChain chain)
A human readable version of the transaction useful for debugging.
|
protected void |
unCache()
To be called before any change of internal values including any setters.
|
void |
verify()
Checks the transaction contents for sanity, in ways that can be done in a standalone manner.
|
adjustLength, adjustLength, setParent
bitcoinSerialize, bitcoinSerialize, ensureParsed, getMessageSize, getParams, isCached, isParsed, isRecached, maybeParse, unsafeBitcoinSerialize
public static final Comparator<Transaction> SORT_TX_BY_UPDATE_TIME
public static final Comparator<Transaction> SORT_TX_BY_HEIGHT
public static final int LOCKTIME_THRESHOLD
public static final int MAX_STANDARD_TX_SIZE
public static final Coin REFERENCE_DEFAULT_MIN_TX_FEE
public static final Coin MIN_NONDUST_OUTPUT
TransactionOutput.getMinNonDustValue(Coin)
. Currently it's 5460 satoshis.public static final byte SIGHASH_ANYONECANPAY_VALUE
public Transaction(NetworkParameters params)
public Transaction(NetworkParameters params, byte[] payloadBytes) throws ProtocolException
ProtocolException
public Transaction(NetworkParameters params, byte[] payload, int offset) throws ProtocolException
ProtocolException
public Transaction(NetworkParameters params, byte[] payload, int offset, @Nullable Message parent, boolean parseLazy, boolean parseRetain, int length) throws ProtocolException
params
- NetworkParameters object.payload
- Bitcoin protocol formatted byte array containing message content.offset
- The location of the first payload byte within the array.parseLazy
- Whether to perform a full parse immediately or delay until a read is requested.parseRetain
- Whether to retain the backing byte array for quick reserialization.
If true and the backing byte array is invalidated due to modification of a field then
the cached bytes may be repopulated and retained if the message is serialized again in the future.length
- The length of message if known. Usually this is provided when deserializing of the wire
as the length will be provided as part of the header. If unknown then set to Message.UNKNOWN_LENGTHProtocolException
public Transaction(NetworkParameters params, byte[] payload, @Nullable Message parent, boolean parseLazy, boolean parseRetain, int length) throws ProtocolException
ProtocolException
public Sha256Hash getHash()
public String getHashAsString()
public Coin getValueSentToMe(TransactionBag transactionBag)
@Nullable public Map<Sha256Hash,Integer> getAppearsInHashes()
public boolean isPending()
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.
block
- The StoredBlock
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.public void addBlockAppearance(Sha256Hash blockHash, int relativityOffset)
public Coin getValueSentFromMe(TransactionBag wallet) throws ScriptException
ScriptException
public Coin getValue(TransactionBag wallet) throws ScriptException
getValueSentFromMe(TransactionBag)
and getValueSentToMe(TransactionBag)
.ScriptException
public Coin getFee()
public boolean isEveryOutputSpent()
public boolean isAnyOutputSpent()
public boolean isEveryOwnedOutputSpent(TransactionBag transactionBag)
public Date getUpdateTime()
public void setUpdateTime(Date updatedAt)
protected void unCache()
Message
unCache
in class ChildMessage
protected void parseLite() throws ProtocolException
Message
parseLite
in class Message
ProtocolException
protected static int calcLength(byte[] buf, int offset)
public int getOptimalEncodingMessageSize()
public boolean isCoinBase()
public boolean isMature()
public String toString(@Nullable AbstractBlockChain chain)
chain
- If provided, will be used to estimate lock times (if set). Can be null.public void clearInputs()
public TransactionInput addInput(TransactionOutput from)
public TransactionInput addInput(TransactionInput input)
public TransactionInput addInput(Sha256Hash spendTxHash, long outputIndex, Script script)
public TransactionInput addSignedInput(TransactionOutPoint prevOut, Script scriptPubKey, ECKey sigKey, Transaction.SigHash sigHash, boolean anyoneCanPay) throws ScriptException
ScriptException
- if the scriptPubKey is not a pay to address or pay to pubkey script.public TransactionInput addSignedInput(TransactionOutPoint prevOut, Script scriptPubKey, ECKey sigKey) throws ScriptException
addSignedInput(TransactionOutPoint, org.bitcoinj.script.Script, ECKey, org.bitcoinj.core.Transaction.SigHash, boolean)
but defaults to Transaction.SigHash.ALL
and "false" for the anyoneCanPay flag. This is normally what you want.ScriptException
public TransactionInput addSignedInput(TransactionOutput output, ECKey signingKey)
public TransactionInput addSignedInput(TransactionOutput output, ECKey signingKey, Transaction.SigHash sigHash, boolean anyoneCanPay)
public void clearOutputs()
public TransactionOutput addOutput(TransactionOutput to)
public TransactionOutput addOutput(Coin value, Address address)
public TransactionOutput addOutput(Coin value, ECKey pubkey)
public TransactionOutput addOutput(Coin value, Script script)
public TransactionSignature calculateSignature(int inputIndex, ECKey key, byte[] redeemScript, Transaction.SigHash hashType, boolean anyoneCanPay)
hashForSignature(int, byte[], org.bitcoinj.core.Transaction.SigHash, boolean)
followed by ECKey.sign(Sha256Hash)
and then returning a new TransactionSignature
. The key
must be usable for signing as-is: if the key is encrypted it must be decrypted first external to this method.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 satisified, or the P2SH redeem script.hashType
- Signing mode, see the enum for documentation.anyoneCanPay
- Signing mode, see the SigHash enum for documentation.public TransactionSignature calculateSignature(int inputIndex, ECKey key, Script redeemScript, Transaction.SigHash hashType, boolean anyoneCanPay)
hashForSignature(int, byte[], org.bitcoinj.core.Transaction.SigHash, boolean)
followed by ECKey.sign(Sha256Hash)
and then returning a new TransactionSignature
.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 satisified, or the P2SH redeem script.hashType
- Signing mode, see the enum for documentation.anyoneCanPay
- Signing mode, see the SigHash enum for documentation.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.
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.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.
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.public Sha256Hash hashForSignature(int inputIndex, byte[] connectedScript, byte sigHashType)
protected void bitcoinSerializeToStream(OutputStream stream) throws IOException
Message
IOException
public long getLockTime()
public void setLockTime(long lockTime)
public long getVersion()
public List<TransactionInput> getInputs()
public List<TransactionOutput> getOutputs()
public 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.
transactionBag
- The wallet that controls addresses and watches scripts.public void shuffleOutputs()
public TransactionInput getInput(int index)
public TransactionOutput getOutput(int index)
public TransactionConfidence getConfidence()
public boolean hasConfidence()
public int getSigOpCount() throws ScriptException
ScriptException
public void verify() 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:
VerificationException
public boolean isTimeLocked()
A transaction is time locked if at least one of its inputs is non-final and it has a lock time
To check if this transaction is final at a given height and time, see isFinal(int, long)
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 the Satoshi client and will need to be re-activated before this functionality is useful.
public static long parseLockTimeStr(String lockTimeStr) throws ParseException
ParseException
public Date estimateLockTime(AbstractBlockChain chain)
public Transaction.Purpose getPurpose()
Transaction.Purpose
for more
information on the point of this field and what it can be.public void setPurpose(Transaction.Purpose purpose)
Transaction.Purpose
for more
information on the point of this field and what it can be.@Nullable public ExchangeRate getExchangeRate()
exchangeRate
.public void setExchangeRate(ExchangeRate exchangeRate)
exchangeRate
.Copyright © 2014. All rights reserved.