github.com/prysmaticlabs/prysm@v1.4.4/shared/htrutils/hashers.go (about)

     1  // Package htrutils defines HashTreeRoot utility functions.
     2  package htrutils
     3  
     4  import "encoding/binary"
     5  
     6  // HashFn is the generic hash function signature.
     7  type HashFn func(input []byte) [32]byte
     8  
     9  // Hasher describes an interface through which we can
    10  // perform hash operations on byte arrays,indices,etc.
    11  type Hasher interface {
    12  	Hash(a []byte) [32]byte
    13  	Combi(a [32]byte, b [32]byte) [32]byte
    14  	MixIn(a [32]byte, i uint64) [32]byte
    15  }
    16  
    17  // HasherFunc defines a structure to hold a hash function and can be used for multiple rounds of
    18  // hashing.
    19  type HasherFunc struct {
    20  	b        [64]byte
    21  	hashFunc HashFn
    22  }
    23  
    24  // NewHasherFunc is the constructor for the object
    25  // that fulfills the Hasher interface.
    26  func NewHasherFunc(h HashFn) *HasherFunc {
    27  	return &HasherFunc{
    28  		b:        [64]byte{},
    29  		hashFunc: h,
    30  	}
    31  }
    32  
    33  // Hash utilizes the provided hash function for
    34  // the object.
    35  func (h *HasherFunc) Hash(a []byte) [32]byte {
    36  	return h.hashFunc(a)
    37  }
    38  
    39  // Combi appends the two inputs and hashes them.
    40  func (h *HasherFunc) Combi(a, b [32]byte) [32]byte {
    41  	copy(h.b[:32], a[:])
    42  	copy(h.b[32:], b[:])
    43  	return h.Hash(h.b[:])
    44  }
    45  
    46  // MixIn works like Combi, but using an integer as the second input.
    47  func (h *HasherFunc) MixIn(a [32]byte, i uint64) [32]byte {
    48  	copy(h.b[:32], a[:])
    49  	copy(h.b[32:], make([]byte, 32))
    50  	binary.LittleEndian.PutUint64(h.b[32:], i)
    51  	return h.Hash(h.b[:])
    52  }