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.
This commit is contained in:
Olaoluwa Osuntokun 2016-10-13 12:56:12 -07:00
parent 6950f39a70
commit 9c01665307
No known key found for this signature in database
GPG key ID: 9CC5B105D03521A2

22
tx.go
View file

@ -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 {