hashfuncs.go raw

   1  // Copyright (c) 2015 The Decred developers
   2  // Copyright (c) 2016-2017 The btcsuite developers
   3  // Use of this source code is governed by an ISC
   4  // license that can be found in the LICENSE file.
   5  
   6  package chainhash
   7  
   8  import (
   9  	"crypto/sha256"
  10  	"io"
  11  )
  12  
  13  // HashB calculates hash(b) and returns the resulting bytes.
  14  func HashB(b []byte) []byte {
  15  	hash := sha256.Sum256(b)
  16  	return hash[:]
  17  }
  18  
  19  // HashH calculates hash(b) and returns the resulting bytes as a Hash.
  20  func HashH(b []byte) Hash {
  21  	return Hash(sha256.Sum256(b))
  22  }
  23  
  24  // DoubleHashB calculates hash(hash(b)) and returns the resulting bytes.
  25  func DoubleHashB(b []byte) []byte {
  26  	first := sha256.Sum256(b)
  27  	second := sha256.Sum256(first[:])
  28  	return second[:]
  29  }
  30  
  31  // DoubleHashH calculates hash(hash(b)) and returns the resulting bytes as a
  32  // Hash.
  33  func DoubleHashH(b []byte) Hash {
  34  	first := sha256.Sum256(b)
  35  	return Hash(sha256.Sum256(first[:]))
  36  }
  37  
  38  // DoubleHashRaw calculates hash(hash(w)) where w is the resulting bytes from
  39  // the given serialize function and returns the resulting bytes as a Hash.
  40  func DoubleHashRaw(serialize func(w io.Writer) error) Hash {
  41  	// Encode the transaction into the hash.  Ignore the error returns
  42  	// since the only way the encode could fail is being out of memory
  43  	// or due to nil pointers, both of which would cause a run-time panic.
  44  	h := sha256.New()
  45  	_ = serialize(h)
  46  
  47  	// This buf is here because Sum() will append the result to the passed
  48  	// in byte slice.  Pre-allocating here saves an allocation on the second
  49  	// hash as we can reuse it.  This allocation also does not escape to the
  50  	// heap, saving an allocation.
  51  	buf := make([]byte, 0, HashSize)
  52  	first := h.Sum(buf)
  53  	h.Reset()
  54  	h.Write(first)
  55  	res := h.Sum(buf)
  56  	return *(*Hash)(res)
  57  }
  58