From b975d617c426c186749d4abb3623c6ea161082fe Mon Sep 17 00:00:00 2001 From: Calvin Kim Date: Sat, 6 May 2023 01:18:03 +0900 Subject: [PATCH] wire, btcutil, main: Use DoubleHashRaw for TxHash and WitnessHash DoubleHashRaw is able to save on the allocation made by the msgtx serialization by directly serializing onto the sha256 digest. This results in massive amounts of memory savings in allocations during the initial block download. --- btcutil/go.mod | 2 ++ btcutil/psbt/go.mod | 2 ++ go.mod | 4 +++- wire/msgtx.go | 13 ++----------- 4 files changed, 9 insertions(+), 12 deletions(-) diff --git a/btcutil/go.mod b/btcutil/go.mod index b03318a461e..fe92b3e5a0e 100644 --- a/btcutil/go.mod +++ b/btcutil/go.mod @@ -14,3 +14,5 @@ require ( ) replace github.com/btcsuite/btcd => ../ + +replace github.com/btcsuite/btcd/chaincfg/chainhash => ../chaincfg/chainhash diff --git a/btcutil/psbt/go.mod b/btcutil/psbt/go.mod index 80f57fc1b33..c9c59396ccf 100644 --- a/btcutil/psbt/go.mod +++ b/btcutil/psbt/go.mod @@ -24,3 +24,5 @@ require ( replace github.com/btcsuite/btcd/btcutil => ../ replace github.com/btcsuite/btcd => ../.. + +replace github.com/btcsuite/btcd/chaincfg/chainhash => ../../chaincfg/chainhash diff --git a/go.mod b/go.mod index 4a05d30857a..de5e9ab310b 100644 --- a/go.mod +++ b/go.mod @@ -31,6 +31,8 @@ require ( replace github.com/btcsuite/btcd/btcutil => ./btcutil +replace github.com/btcsuite/btcd/chaincfg/chainhash => ./chaincfg/chainhash + // The retract statements below fixes an accidental push of the tags of a btcd // fork. retract ( @@ -63,4 +65,4 @@ retract ( v0.13.0-beta ) -go 1.17 +go 1.18 diff --git a/wire/msgtx.go b/wire/msgtx.go index 7705504cc8f..d2b52dba24c 100644 --- a/wire/msgtx.go +++ b/wire/msgtx.go @@ -5,7 +5,6 @@ package wire import ( - "bytes" "errors" "fmt" "io" @@ -357,13 +356,7 @@ func (msg *MsgTx) AddTxOut(to *TxOut) { // TxHash generates the Hash for the transaction. func (msg *MsgTx) TxHash() chainhash.Hash { - // Encode the transaction and calculate double sha256 on the result. - // Ignore the error returns since the only way the encode could fail - // is being out of memory or due to nil pointers, both of which would - // cause a run-time panic. - buf := bytes.NewBuffer(make([]byte, 0, msg.SerializeSizeStripped())) - _ = msg.SerializeNoWitness(buf) - return chainhash.DoubleHashH(buf.Bytes()) + return chainhash.DoubleHashRaw(msg.SerializeNoWitness) } // WitnessHash generates the hash of the transaction serialized according to @@ -373,9 +366,7 @@ func (msg *MsgTx) TxHash() chainhash.Hash { // is the same as its txid. func (msg *MsgTx) WitnessHash() chainhash.Hash { if msg.HasWitness() { - buf := bytes.NewBuffer(make([]byte, 0, msg.SerializeSize())) - _ = msg.Serialize(buf) - return chainhash.DoubleHashH(buf.Bytes()) + return chainhash.DoubleHashRaw(msg.Serialize) } return msg.TxHash()