diff --git a/tx.go b/tx.go index d8b3a94..7399ca0 100644 --- a/tx.go +++ b/tx.go @@ -22,9 +22,10 @@ const TxIndexUnknown = -1 // transaction on its first access so subsequent accesses don't have to repeat // the relatively expensive hashing operations. type Tx struct { - msgTx *wire.MsgTx // Underlying MsgTx - txHash *chainhash.Hash // Cached transaction hash - txIndex int // Position within a block or TxIndexUnknown + msgTx *wire.MsgTx // Underlying MsgTx + txHash *chainhash.Hash // Cached transaction hash + txHashWitness *chainhash.Hash // Cached transaction witness hash + txIndex int // Position within a block or TxIndexUnknown } // MsgTx returns the underlying wire.MsgTx for the transaction. @@ -48,6 +49,21 @@ func (t *Tx) Hash() *chainhash.Hash { return &hash } +// WitnessHash returns the witness hash (wtxid) of the transaction. This is +// equivalent to calling WitnessHash on the underlying wire.MsgTx, however it +// caches the result so subsequent calls are more efficient. +func (t *Tx) WitnessHash() *chainhash.Hash { + // Return the cached hash if it has already been generated. + if t.txHashWitness != nil { + return t.txHashWitness + } + + // Cache the hash and return it. + hash := t.msgTx.WitnessHash() + t.txHashWitness = &hash + return &hash +} + // Index returns the saved index of the transaction within a block. This value // will be TxIndexUnknown if it hasn't already explicitly been set. func (t *Tx) Index() int {