From 9c01665307d451c2ecfae2645050e67c21ba0dd8 Mon Sep 17 00:00:00 2001 From: Olaoluwa Osuntokun Date: Thu, 13 Oct 2016 12:56:12 -0700 Subject: [PATCH] add new WitnessHash method to Tx This commit adds a new method to btcutil.Tx which implements a memoized equivalent to the `Hash` method but for the newly defined `wtxid. --- tx.go | 22 +++++++++++++++++++--- 1 file changed, 19 insertions(+), 3 deletions(-) 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 {