-
Notifications
You must be signed in to change notification settings - Fork 4
/
merkle.go
89 lines (78 loc) · 2.1 KB
/
merkle.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
/*
Package merkle implements the Merkle tree hash computation.
*/
package merkle
import (
"crypto"
"encoding"
"math/bits"
)
// Domain separation prefixes
const (
LeafHashPrefix = 0
NodeHashPrefix = 1
)
// Hasher implements the hashing algorithm described in the IOTA protocol RFC-12.
type Hasher struct {
hash crypto.Hash
}
// NewHasher creates a new Hasher using the provided hash function.
func NewHasher(h crypto.Hash) *Hasher {
return &Hasher{hash: h}
}
// Size returns the length, in bytes, of a digest resulting from the given hash function.
func (t *Hasher) Size() int {
return t.hash.Size()
}
// EmptyRoot returns a special case for an empty tree.
// This is equivalent to Hash(nil).
func (t *Hasher) EmptyRoot() []byte {
return t.hash.New().Sum(nil)
}
// Hash computes the Merkle tree hash of the provided data encodings.
func (t *Hasher) Hash(data []encoding.BinaryMarshaler) ([]byte, error) {
if len(data) == 0 {
return t.EmptyRoot(), nil
}
if len(data) == 1 {
return t.hashLeaf(data[0])
}
k := largestPowerOfTwo(len(data))
l, err := t.Hash(data[:k])
if err != nil {
return nil, err
}
r, err := t.Hash(data[k:])
if err != nil {
return nil, err
}
return t.hashNode(l, r), nil
}
// hashLeaf returns the Merkle tree leaf hash of data.
func (t *Hasher) hashLeaf(data encoding.BinaryMarshaler) ([]byte, error) {
b, err := data.MarshalBinary()
if err != nil {
return nil, err
}
h := t.hash.New()
h.Write([]byte{LeafHashPrefix})
h.Write(b)
return h.Sum(nil), nil
}
// hashNode returns the inner Merkle tree node hash of the two child nodes l and r.
func (t *Hasher) hashNode(l, r []byte) []byte {
h := t.hash.New()
h.Write([]byte{NodeHashPrefix})
h.Write(l)
h.Write(r)
return h.Sum(nil)
}
// largestPowerOfTwo returns the largest power of two strictly less than n, i.e. 2^⌊log₂(x-1)⌋ for x > 1.
func largestPowerOfTwo(x int) uint {
if x <= 1 {
panic("invalid value")
}
// bitsLen(n) := ⌊log₂(n) + 1⌋ ⇒ ⌊log₂(n-1)⌋ = bitsLen(n-1) - 1 for n > 1
log := bits.Len(uint(x-1)) - 1
return 1 << (log & (bits.UintSize - 1)) // hint to the compiler that 0 ≤ log < 2^64
}