Skip to content

Commit

Permalink
chainhash: Add DoubleHashRaw
Browse files Browse the repository at this point in the history
DoubleHashRaw provides a simple function for doing double hashes.  Since
it uses the digest instead of making the caller allocate a byte slice, it
can be more memory efficient vs other double hash functions.
  • Loading branch information
kcalvinalvin committed Nov 6, 2023
1 parent d15dd71 commit 375f79d
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 1 deletion.
26 changes: 25 additions & 1 deletion chaincfg/chainhash/hashfuncs.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,10 @@

package chainhash

import "crypto/sha256"
import (
"crypto/sha256"
"io"
)

// HashB calculates hash(b) and returns the resulting bytes.
func HashB(b []byte) []byte {
Expand All @@ -31,3 +34,24 @@ func DoubleHashH(b []byte) Hash {
first := sha256.Sum256(b)
return Hash(sha256.Sum256(first[:]))
}

// DoubleHashRaw calculates hash(hash(w)) where w is the resulting bytes from
// the given serialize function and returns the resulting bytes as a Hash.
func DoubleHashRaw(serialize func(w io.Writer) error) Hash {
// Encode the transaction into the hash. 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.
h := sha256.New()
_ = serialize(h)

// This buf is here because Sum() will append the result to the passed
// in byte slice. Pre-allocating here saves an allocation on the second
// hash as we can reuse it. This allocation also does not escape to the
// heap, saving an allocation.
buf := make([]byte, 0, HashSize)
first := h.Sum(buf)
h.Reset()
h.Write(first)
res := h.Sum(buf)
return *(*Hash)(res)
}
17 changes: 17 additions & 0 deletions chaincfg/chainhash/hashfuncs_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ package chainhash

import (
"fmt"
"io"
"testing"
)

Expand Down Expand Up @@ -133,4 +134,20 @@ func TestDoubleHashFuncs(t *testing.T) {
continue
}
}

// Ensure the hash function which accepts a hash.Hash returns the expected
// result when given a hash.Hash that is of type SHA256.
for _, test := range tests {
serialize := func(w io.Writer) error {
w.Write([]byte(test.in))
return nil
}
hash := DoubleHashRaw(serialize)
h := fmt.Sprintf("%x", hash[:])
if h != test.out {
t.Errorf("DoubleHashRaw(%q) = %s, want %s", test.in, h,
test.out)
continue
}
}
}

0 comments on commit 375f79d

Please sign in to comment.