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

16
tx.go
View file

@ -24,6 +24,7 @@ const TxIndexUnknown = -1
type Tx struct { type Tx struct {
msgTx *wire.MsgTx // Underlying MsgTx msgTx *wire.MsgTx // Underlying MsgTx
txHash *chainhash.Hash // Cached transaction hash txHash *chainhash.Hash // Cached transaction hash
txHashWitness *chainhash.Hash // Cached transaction witness hash
txIndex int // Position within a block or TxIndexUnknown txIndex int // Position within a block or TxIndexUnknown
} }
@ -48,6 +49,21 @@ func (t *Tx) Hash() *chainhash.Hash {
return &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 // Index returns the saved index of the transaction within a block. This value
// will be TxIndexUnknown if it hasn't already explicitly been set. // will be TxIndexUnknown if it hasn't already explicitly been set.
func (t *Tx) Index() int { func (t *Tx) Index() int {