7 "github.com/bytom/crypto/sha3pool"
11 leafPrefix = []byte{0x00}
12 interiorPrefix = []byte{0x01}
15 type merkleNode interface {
16 WriteTo(io.Writer) (int64, error)
19 func merkleRoot(nodes []merkleNode) (root Hash, err error) {
22 return EmptyStringHash, nil
25 h := sha3pool.Get256()
26 defer sha3pool.Put256(h)
34 k := prevPowerOfTwo(len(nodes))
35 left, err := merkleRoot(nodes[:k])
40 right, err := merkleRoot(nodes[k:])
45 h := sha3pool.Get256()
46 defer sha3pool.Put256(h)
47 h.Write(interiorPrefix)
55 // TxStatusMerkleRoot creates a merkle tree from a slice of TxVerifyResult
56 func TxStatusMerkleRoot(tvrs []*TxVerifyResult) (root Hash, err error) {
57 nodes := []merkleNode{}
58 for _, tvr := range tvrs {
59 nodes = append(nodes, tvr)
61 return merkleRoot(nodes)
64 // TxMerkleRoot creates a merkle tree from a slice of transactions
65 // and returns the root hash of the tree.
66 func TxMerkleRoot(transactions []*Tx) (root Hash, err error) {
67 nodes := []merkleNode{}
68 for _, tx := range transactions {
69 nodes = append(nodes, tx.ID)
71 return merkleRoot(nodes)
74 // prevPowerOfTwo returns the largest power of two that is smaller than a given number.
75 // In other words, for some input n, the prevPowerOfTwo k is a power of two such that
76 // k < n <= 2k. This is a helper function used during the calculation of a merkle tree.
77 func prevPowerOfTwo(n int) int {
78 // If the number is a power of two, divide it by 2 and return.
83 // Otherwise, find the previous PoT.
84 exponent := uint(math.Log2(float64(n)))
85 return 1 << exponent // 2^exponent