6 "chain/crypto/sha3pool"
10 leafPrefix = []byte{0x00}
11 interiorPrefix = []byte{0x01}
14 // MerkleRoot creates a merkle tree from a slice of transactions
15 // and returns the root hash of the tree.
16 func MerkleRoot(transactions []*Tx) (root Hash, err error) {
18 case len(transactions) == 0:
19 return EmptyStringHash, nil
21 case len(transactions) == 1:
22 h := sha3pool.Get256()
23 defer sha3pool.Put256(h)
26 transactions[0].ID.WriteTo(h)
31 k := prevPowerOfTwo(len(transactions))
32 left, err := MerkleRoot(transactions[:k])
37 right, err := MerkleRoot(transactions[k:])
42 h := sha3pool.Get256()
43 defer sha3pool.Put256(h)
44 h.Write(interiorPrefix)
52 // prevPowerOfTwo returns the largest power of two that is smaller than a given number.
53 // In other words, for some input n, the prevPowerOfTwo k is a power of two such that
54 // k < n <= 2k. This is a helper function used during the calculation of a merkle tree.
55 func prevPowerOfTwo(n int) int {
56 // If the number is a power of two, divide it by 2 and return.
61 // Otherwise, find the previous PoT.
62 exponent := uint(math.Log2(float64(n)))
63 return 1 << exponent // 2^exponent