You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

277 lines
7.6 KiB

  1. /*
  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.
  6. Use this for short deterministic trees, such as the validator list.
  7. For larger datasets, use IAVLTree.
  8. *
  9. / \
  10. / \
  11. / \
  12. / \
  13. * *
  14. / \ / \
  15. / \ / \
  16. / \ / \
  17. * * * h6
  18. / \ / \ / \
  19. h0 h1 h2 h3 h4 h5
  20. */
  21. package merkle
  22. import (
  23. "bytes"
  24. "fmt"
  25. "sort"
  26. "golang.org/x/crypto/ripemd160"
  27. . "github.com/tendermint/tmlibs/common"
  28. "github.com/tendermint/go-wire"
  29. )
  30. func SimpleHashFromTwoHashes(left []byte, right []byte) []byte {
  31. var n int
  32. var err error
  33. var hasher = ripemd160.New()
  34. wire.WriteByteSlice(left, hasher, &n, &err)
  35. wire.WriteByteSlice(right, hasher, &n, &err)
  36. if err != nil {
  37. PanicCrisis(err)
  38. }
  39. return hasher.Sum(nil)
  40. }
  41. func SimpleHashFromHashes(hashes [][]byte) []byte {
  42. // Recursive impl.
  43. switch len(hashes) {
  44. case 0:
  45. return nil
  46. case 1:
  47. return hashes[0]
  48. default:
  49. left := SimpleHashFromHashes(hashes[:(len(hashes)+1)/2])
  50. right := SimpleHashFromHashes(hashes[(len(hashes)+1)/2:])
  51. return SimpleHashFromTwoHashes(left, right)
  52. }
  53. }
  54. // Convenience for SimpleHashFromHashes.
  55. func SimpleHashFromBinaries(items []interface{}) []byte {
  56. hashes := make([][]byte, len(items))
  57. for i, item := range items {
  58. hashes[i] = SimpleHashFromBinary(item)
  59. }
  60. return SimpleHashFromHashes(hashes)
  61. }
  62. // General Convenience
  63. func SimpleHashFromBinary(item interface{}) []byte {
  64. hasher, n, err := ripemd160.New(), new(int), new(error)
  65. wire.WriteBinary(item, hasher, n, err)
  66. if *err != nil {
  67. PanicCrisis(err)
  68. }
  69. return hasher.Sum(nil)
  70. }
  71. // Convenience for SimpleHashFromHashes.
  72. func SimpleHashFromHashables(items []Hashable) []byte {
  73. hashes := make([][]byte, len(items))
  74. for i, item := range items {
  75. hash := item.Hash()
  76. hashes[i] = hash
  77. }
  78. return SimpleHashFromHashes(hashes)
  79. }
  80. // Convenience for SimpleHashFromHashes.
  81. func SimpleHashFromMap(m map[string]interface{}) []byte {
  82. kpPairsH := MakeSortedKVPairs(m)
  83. return SimpleHashFromHashables(kpPairsH)
  84. }
  85. //--------------------------------------------------------------------------------
  86. /* Convenience struct for key-value pairs.
  87. A list of KVPairs is hashed via `SimpleHashFromHashables`.
  88. NOTE: Each `Value` is encoded for hashing without extra type information,
  89. so the user is presumed to be aware of the Value types.
  90. */
  91. type KVPair struct {
  92. Key string
  93. Value interface{}
  94. }
  95. func (kv KVPair) Hash() []byte {
  96. hasher, n, err := ripemd160.New(), new(int), new(error)
  97. wire.WriteString(kv.Key, hasher, n, err)
  98. if kvH, ok := kv.Value.(Hashable); ok {
  99. wire.WriteByteSlice(kvH.Hash(), hasher, n, err)
  100. } else {
  101. wire.WriteBinary(kv.Value, hasher, n, err)
  102. }
  103. if *err != nil {
  104. PanicSanity(*err)
  105. }
  106. return hasher.Sum(nil)
  107. }
  108. type KVPairs []KVPair
  109. func (kvps KVPairs) Len() int { return len(kvps) }
  110. func (kvps KVPairs) Less(i, j int) bool { return kvps[i].Key < kvps[j].Key }
  111. func (kvps KVPairs) Swap(i, j int) { kvps[i], kvps[j] = kvps[j], kvps[i] }
  112. func (kvps KVPairs) Sort() { sort.Sort(kvps) }
  113. func MakeSortedKVPairs(m map[string]interface{}) []Hashable {
  114. kvPairs := []KVPair{}
  115. for k, v := range m {
  116. kvPairs = append(kvPairs, KVPair{k, v})
  117. }
  118. KVPairs(kvPairs).Sort()
  119. kvPairsH := []Hashable{}
  120. for _, kvp := range kvPairs {
  121. kvPairsH = append(kvPairsH, kvp)
  122. }
  123. return kvPairsH
  124. }
  125. //--------------------------------------------------------------------------------
  126. type SimpleProof struct {
  127. Aunts [][]byte `json:"aunts"` // Hashes from leaf's sibling to a root's child.
  128. }
  129. // proofs[0] is the proof for items[0].
  130. func SimpleProofsFromHashables(items []Hashable) (rootHash []byte, proofs []*SimpleProof) {
  131. trails, rootSPN := trailsFromHashables(items)
  132. rootHash = rootSPN.Hash
  133. proofs = make([]*SimpleProof, len(items))
  134. for i, trail := range trails {
  135. proofs[i] = &SimpleProof{
  136. Aunts: trail.FlattenAunts(),
  137. }
  138. }
  139. return
  140. }
  141. // Verify that leafHash is a leaf hash of the simple-merkle-tree
  142. // which hashes to rootHash.
  143. func (sp *SimpleProof) Verify(index int, total int, leafHash []byte, rootHash []byte) bool {
  144. computedHash := computeHashFromAunts(index, total, leafHash, sp.Aunts)
  145. if computedHash == nil {
  146. return false
  147. }
  148. if !bytes.Equal(computedHash, rootHash) {
  149. return false
  150. }
  151. return true
  152. }
  153. func (sp *SimpleProof) String() string {
  154. return sp.StringIndented("")
  155. }
  156. func (sp *SimpleProof) StringIndented(indent string) string {
  157. return fmt.Sprintf(`SimpleProof{
  158. %s Aunts: %X
  159. %s}`,
  160. indent, sp.Aunts,
  161. indent)
  162. }
  163. // Use the leafHash and innerHashes to get the root merkle hash.
  164. // If the length of the innerHashes slice isn't exactly correct, the result is nil.
  165. func computeHashFromAunts(index int, total int, leafHash []byte, innerHashes [][]byte) []byte {
  166. // Recursive impl.
  167. if index >= total {
  168. return nil
  169. }
  170. switch total {
  171. case 0:
  172. PanicSanity("Cannot call computeHashFromAunts() with 0 total")
  173. return nil
  174. case 1:
  175. if len(innerHashes) != 0 {
  176. return nil
  177. }
  178. return leafHash
  179. default:
  180. if len(innerHashes) == 0 {
  181. return nil
  182. }
  183. numLeft := (total + 1) / 2
  184. if index < numLeft {
  185. leftHash := computeHashFromAunts(index, numLeft, leafHash, innerHashes[:len(innerHashes)-1])
  186. if leftHash == nil {
  187. return nil
  188. }
  189. return SimpleHashFromTwoHashes(leftHash, innerHashes[len(innerHashes)-1])
  190. } else {
  191. rightHash := computeHashFromAunts(index-numLeft, total-numLeft, leafHash, innerHashes[:len(innerHashes)-1])
  192. if rightHash == nil {
  193. return nil
  194. }
  195. return SimpleHashFromTwoHashes(innerHashes[len(innerHashes)-1], rightHash)
  196. }
  197. }
  198. }
  199. // Helper structure to construct merkle proof.
  200. // The node and the tree is thrown away afterwards.
  201. // Exactly one of node.Left and node.Right is nil, unless node is the root, in which case both are nil.
  202. // node.Parent.Hash = hash(node.Hash, node.Right.Hash) or
  203. // hash(node.Left.Hash, node.Hash), depending on whether node is a left/right child.
  204. type SimpleProofNode struct {
  205. Hash []byte
  206. Parent *SimpleProofNode
  207. Left *SimpleProofNode // Left sibling (only one of Left,Right is set)
  208. Right *SimpleProofNode // Right sibling (only one of Left,Right is set)
  209. }
  210. // Starting from a leaf SimpleProofNode, FlattenAunts() will return
  211. // the inner hashes for the item corresponding to the leaf.
  212. func (spn *SimpleProofNode) FlattenAunts() [][]byte {
  213. // Nonrecursive impl.
  214. innerHashes := [][]byte{}
  215. for spn != nil {
  216. if spn.Left != nil {
  217. innerHashes = append(innerHashes, spn.Left.Hash)
  218. } else if spn.Right != nil {
  219. innerHashes = append(innerHashes, spn.Right.Hash)
  220. } else {
  221. break
  222. }
  223. spn = spn.Parent
  224. }
  225. return innerHashes
  226. }
  227. // trails[0].Hash is the leaf hash for items[0].
  228. // trails[i].Parent.Parent....Parent == root for all i.
  229. func trailsFromHashables(items []Hashable) (trails []*SimpleProofNode, root *SimpleProofNode) {
  230. // Recursive impl.
  231. switch len(items) {
  232. case 0:
  233. return nil, nil
  234. case 1:
  235. trail := &SimpleProofNode{items[0].Hash(), nil, nil, nil}
  236. return []*SimpleProofNode{trail}, trail
  237. default:
  238. lefts, leftRoot := trailsFromHashables(items[:(len(items)+1)/2])
  239. rights, rightRoot := trailsFromHashables(items[(len(items)+1)/2:])
  240. rootHash := SimpleHashFromTwoHashes(leftRoot.Hash, rightRoot.Hash)
  241. root := &SimpleProofNode{rootHash, nil, nil, nil}
  242. leftRoot.Parent = root
  243. leftRoot.Right = rightRoot
  244. rightRoot.Parent = root
  245. rightRoot.Left = leftRoot
  246. return append(lefts, rights...), root
  247. }
  248. }