Skip to content

Commit

Permalink
wire, btcutil, main: Use DoubleHashRaw for TxHash and WitnessHash
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
kcalvinalvin committed Nov 6, 2023
1 parent 375f79d commit b975d61
Show file tree
Hide file tree
Showing 4 changed files with 9 additions and 12 deletions.
2 changes: 2 additions & 0 deletions btcutil/go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -14,3 +14,5 @@ require (
)

replace github.com/btcsuite/btcd => ../

replace github.com/btcsuite/btcd/chaincfg/chainhash => ../chaincfg/chainhash
2 changes: 2 additions & 0 deletions btcutil/psbt/go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -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
4 changes: 3 additions & 1 deletion go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -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 (
Expand Down Expand Up @@ -63,4 +65,4 @@ retract (
v0.13.0-beta
)

go 1.17
go 1.18
13 changes: 2 additions & 11 deletions wire/msgtx.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@
package wire

import (
"bytes"
"errors"
"fmt"
"io"
Expand Down Expand Up @@ -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
Expand All @@ -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()
Expand Down

0 comments on commit b975d61

Please sign in to comment.