2 Computes a deterministic minimal height merkle tree hash.
3 If the number of items is not a power of two, some leaves
4 will be at different levels. Tries to keep both sides of
5 the tree the same size, but the left may be one greater.
7 Use this for short deterministic trees, such as the validator list.
8 For larger datasets, use IAVLTree.
32 "golang.org/x/crypto/ripemd160"
34 "github.com/tendermint/go-wire"
35 . "github.com/tendermint/tmlibs/common"
38 func SimpleHashFromTwoHashes(left []byte, right []byte) []byte {
41 var hasher = ripemd160.New()
42 wire.WriteByteSlice(left, hasher, &n, &err)
43 wire.WriteByteSlice(right, hasher, &n, &err)
47 return hasher.Sum(nil)
50 func SimpleHashFromHashes(hashes [][]byte) []byte {
58 left := SimpleHashFromHashes(hashes[:(len(hashes)+1)/2])
59 right := SimpleHashFromHashes(hashes[(len(hashes)+1)/2:])
60 return SimpleHashFromTwoHashes(left, right)
64 // Convenience for SimpleHashFromHashes.
65 func SimpleHashFromBinaries(items []interface{}) []byte {
66 hashes := make([][]byte, len(items))
67 for i, item := range items {
68 hashes[i] = SimpleHashFromBinary(item)
70 return SimpleHashFromHashes(hashes)
73 // General Convenience
74 func SimpleHashFromBinary(item interface{}) []byte {
75 hasher, n, err := ripemd160.New(), new(int), new(error)
76 wire.WriteBinary(item, hasher, n, err)
80 return hasher.Sum(nil)
83 // Convenience for SimpleHashFromHashes.
84 func SimpleHashFromHashables(items []Hashable) []byte {
85 hashes := make([][]byte, len(items))
86 for i, item := range items {
90 return SimpleHashFromHashes(hashes)
93 // Convenience for SimpleHashFromHashes.
94 func SimpleHashFromMap(m map[string]interface{}) []byte {
95 kpPairsH := MakeSortedKVPairs(m)
96 return SimpleHashFromHashables(kpPairsH)
99 //--------------------------------------------------------------------------------
101 /* Convenience struct for key-value pairs.
102 A list of KVPairs is hashed via `SimpleHashFromHashables`.
103 NOTE: Each `Value` is encoded for hashing without extra type information,
104 so the user is presumed to be aware of the Value types.
111 func (kv KVPair) Hash() []byte {
112 hasher, n, err := ripemd160.New(), new(int), new(error)
113 wire.WriteString(kv.Key, hasher, n, err)
114 if kvH, ok := kv.Value.(Hashable); ok {
115 wire.WriteByteSlice(kvH.Hash(), hasher, n, err)
117 wire.WriteBinary(kv.Value, hasher, n, err)
122 return hasher.Sum(nil)
125 type KVPairs []KVPair
127 func (kvps KVPairs) Len() int { return len(kvps) }
128 func (kvps KVPairs) Less(i, j int) bool { return kvps[i].Key < kvps[j].Key }
129 func (kvps KVPairs) Swap(i, j int) { kvps[i], kvps[j] = kvps[j], kvps[i] }
130 func (kvps KVPairs) Sort() { sort.Sort(kvps) }
132 func MakeSortedKVPairs(m map[string]interface{}) []Hashable {
133 kvPairs := []KVPair{}
134 for k, v := range m {
135 kvPairs = append(kvPairs, KVPair{k, v})
137 KVPairs(kvPairs).Sort()
138 kvPairsH := []Hashable{}
139 for _, kvp := range kvPairs {
140 kvPairsH = append(kvPairsH, kvp)
145 //--------------------------------------------------------------------------------
147 type SimpleProof struct {
148 Aunts [][]byte `json:"aunts"` // Hashes from leaf's sibling to a root's child.
151 // proofs[0] is the proof for items[0].
152 func SimpleProofsFromHashables(items []Hashable) (rootHash []byte, proofs []*SimpleProof) {
153 trails, rootSPN := trailsFromHashables(items)
154 rootHash = rootSPN.Hash
155 proofs = make([]*SimpleProof, len(items))
156 for i, trail := range trails {
157 proofs[i] = &SimpleProof{
158 Aunts: trail.FlattenAunts(),
164 // Verify that leafHash is a leaf hash of the simple-merkle-tree
165 // which hashes to rootHash.
166 func (sp *SimpleProof) Verify(index int, total int, leafHash []byte, rootHash []byte) bool {
167 computedHash := computeHashFromAunts(index, total, leafHash, sp.Aunts)
168 if computedHash == nil {
171 if !bytes.Equal(computedHash, rootHash) {
177 func (sp *SimpleProof) String() string {
178 return sp.StringIndented("")
181 func (sp *SimpleProof) StringIndented(indent string) string {
182 return fmt.Sprintf(`SimpleProof{
189 // Use the leafHash and innerHashes to get the root merkle hash.
190 // If the length of the innerHashes slice isn't exactly correct, the result is nil.
191 func computeHashFromAunts(index int, total int, leafHash []byte, innerHashes [][]byte) []byte {
198 PanicSanity("Cannot call computeHashFromAunts() with 0 total")
201 if len(innerHashes) != 0 {
206 if len(innerHashes) == 0 {
209 numLeft := (total + 1) / 2
211 leftHash := computeHashFromAunts(index, numLeft, leafHash, innerHashes[:len(innerHashes)-1])
215 return SimpleHashFromTwoHashes(leftHash, innerHashes[len(innerHashes)-1])
217 rightHash := computeHashFromAunts(index-numLeft, total-numLeft, leafHash, innerHashes[:len(innerHashes)-1])
218 if rightHash == nil {
221 return SimpleHashFromTwoHashes(innerHashes[len(innerHashes)-1], rightHash)
226 // Helper structure to construct merkle proof.
227 // The node and the tree is thrown away afterwards.
228 // Exactly one of node.Left and node.Right is nil, unless node is the root, in which case both are nil.
229 // node.Parent.Hash = hash(node.Hash, node.Right.Hash) or
230 // hash(node.Left.Hash, node.Hash), depending on whether node is a left/right child.
231 type SimpleProofNode struct {
233 Parent *SimpleProofNode
234 Left *SimpleProofNode // Left sibling (only one of Left,Right is set)
235 Right *SimpleProofNode // Right sibling (only one of Left,Right is set)
238 // Starting from a leaf SimpleProofNode, FlattenAunts() will return
239 // the inner hashes for the item corresponding to the leaf.
240 func (spn *SimpleProofNode) FlattenAunts() [][]byte {
241 // Nonrecursive impl.
242 innerHashes := [][]byte{}
245 innerHashes = append(innerHashes, spn.Left.Hash)
246 } else if spn.Right != nil {
247 innerHashes = append(innerHashes, spn.Right.Hash)
256 // trails[0].Hash is the leaf hash for items[0].
257 // trails[i].Parent.Parent....Parent == root for all i.
258 func trailsFromHashables(items []Hashable) (trails []*SimpleProofNode, root *SimpleProofNode) {
264 trail := &SimpleProofNode{items[0].Hash(), nil, nil, nil}
265 return []*SimpleProofNode{trail}, trail
267 lefts, leftRoot := trailsFromHashables(items[:(len(items)+1)/2])
268 rights, rightRoot := trailsFromHashables(items[(len(items)+1)/2:])
269 rootHash := SimpleHashFromTwoHashes(leftRoot.Hash, rightRoot.Hash)
270 root := &SimpleProofNode{rootHash, nil, nil, nil}
271 leftRoot.Parent = root
272 leftRoot.Right = rightRoot
273 rightRoot.Parent = root
274 rightRoot.Left = leftRoot
275 return append(lefts, rights...), root