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.

245 lines
6.8 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. "github.com/tendermint/tendermint/Godeps/_workspace/src/code.google.com/p/go.crypto/ripemd160"
  26. "github.com/tendermint/tendermint/binary"
  27. . "github.com/tendermint/tendermint/common"
  28. )
  29. func SimpleHashFromTwoHashes(left []byte, right []byte) []byte {
  30. var n int64
  31. var err error
  32. var hasher = ripemd160.New()
  33. binary.WriteByteSlice(left, hasher, &n, &err)
  34. binary.WriteByteSlice(right, hasher, &n, &err)
  35. if err != nil {
  36. PanicCrisis(err)
  37. }
  38. return hasher.Sum(nil)
  39. }
  40. func SimpleHashFromHashes(hashes [][]byte) []byte {
  41. // Recursive impl.
  42. switch len(hashes) {
  43. case 0:
  44. return nil
  45. case 1:
  46. return hashes[0]
  47. default:
  48. left := SimpleHashFromHashes(hashes[:(len(hashes)+1)/2])
  49. right := SimpleHashFromHashes(hashes[(len(hashes)+1)/2:])
  50. return SimpleHashFromTwoHashes(left, right)
  51. }
  52. }
  53. // Convenience for SimpleHashFromHashes.
  54. func SimpleHashFromBinaries(items []interface{}) []byte {
  55. hashes := [][]byte{}
  56. for _, item := range items {
  57. hashes = append(hashes, SimpleHashFromBinary(item))
  58. }
  59. return SimpleHashFromHashes(hashes)
  60. }
  61. // General Convenience
  62. func SimpleHashFromBinary(item interface{}) []byte {
  63. hasher, n, err := ripemd160.New(), new(int64), new(error)
  64. binary.WriteBinary(item, hasher, n, err)
  65. if *err != nil {
  66. PanicCrisis(err)
  67. }
  68. return hasher.Sum(nil)
  69. }
  70. // Convenience for SimpleHashFromHashes.
  71. func SimpleHashFromHashables(items []Hashable) []byte {
  72. hashes := [][]byte{}
  73. for _, item := range items {
  74. hash := item.Hash()
  75. hashes = append(hashes, hash)
  76. }
  77. return SimpleHashFromHashes(hashes)
  78. }
  79. //--------------------------------------------------------------------------------
  80. type SimpleProof struct {
  81. Index int `json:"index"`
  82. Total int `json:"total"`
  83. LeafHash []byte `json:"leaf_hash"`
  84. InnerHashes [][]byte `json:"inner_hashes"` // Hashes from leaf's sibling to a root's child.
  85. RootHash []byte `json:"root_hash"`
  86. }
  87. // proofs[0] is the proof for items[0].
  88. func SimpleProofsFromHashables(items []Hashable) (proofs []*SimpleProof) {
  89. trails, root := trailsFromHashables(items)
  90. proofs = make([]*SimpleProof, len(items))
  91. for i, trail := range trails {
  92. proofs[i] = &SimpleProof{
  93. Index: i,
  94. Total: len(items),
  95. LeafHash: trail.Hash,
  96. InnerHashes: trail.FlattenInnerHashes(),
  97. RootHash: root.Hash,
  98. }
  99. }
  100. return
  101. }
  102. // Verify that leafHash is a leaf hash of the simple-merkle-tree
  103. // which hashes to rootHash.
  104. func (sp *SimpleProof) Verify(leafHash []byte, rootHash []byte) bool {
  105. if !bytes.Equal(leafHash, sp.LeafHash) {
  106. return false
  107. }
  108. if !bytes.Equal(rootHash, sp.RootHash) {
  109. return false
  110. }
  111. computedHash := computeHashFromInnerHashes(sp.Index, sp.Total, sp.LeafHash, sp.InnerHashes)
  112. if computedHash == nil {
  113. return false
  114. }
  115. if !bytes.Equal(computedHash, rootHash) {
  116. return false
  117. }
  118. return true
  119. }
  120. func (sp *SimpleProof) String() string {
  121. return sp.StringIndented("")
  122. }
  123. func (sp *SimpleProof) StringIndented(indent string) string {
  124. return fmt.Sprintf(`SimpleProof{
  125. %s Index: %v
  126. %s Total: %v
  127. %s LeafHash: %X
  128. %s InnerHashes: %X
  129. %s RootHash: %X
  130. %s}`,
  131. indent, sp.Index,
  132. indent, sp.Total,
  133. indent, sp.LeafHash,
  134. indent, sp.InnerHashes,
  135. indent, sp.RootHash,
  136. indent)
  137. }
  138. // Use the leafHash and innerHashes to get the root merkle hash.
  139. // If the length of the innerHashes slice isn't exactly correct, the result is nil.
  140. func computeHashFromInnerHashes(index int, total int, leafHash []byte, innerHashes [][]byte) []byte {
  141. // Recursive impl.
  142. if index >= total {
  143. return nil
  144. }
  145. switch total {
  146. case 0:
  147. PanicSanity("Cannot call computeHashFromInnerHashes() with 0 total")
  148. return nil
  149. case 1:
  150. if len(innerHashes) != 0 {
  151. return nil
  152. }
  153. return leafHash
  154. default:
  155. if len(innerHashes) == 0 {
  156. return nil
  157. }
  158. numLeft := (total + 1) / 2
  159. if index < numLeft {
  160. leftHash := computeHashFromInnerHashes(index, numLeft, leafHash, innerHashes[:len(innerHashes)-1])
  161. if leftHash == nil {
  162. return nil
  163. }
  164. return SimpleHashFromTwoHashes(leftHash, innerHashes[len(innerHashes)-1])
  165. } else {
  166. rightHash := computeHashFromInnerHashes(index-numLeft, total-numLeft, leafHash, innerHashes[:len(innerHashes)-1])
  167. if rightHash == nil {
  168. return nil
  169. }
  170. return SimpleHashFromTwoHashes(innerHashes[len(innerHashes)-1], rightHash)
  171. }
  172. }
  173. }
  174. // Helper structure to construct merkle proof.
  175. // The node and the tree is thrown away afterwards.
  176. // Exactly one of node.Left and node.Right is nil, unless node is the root, in which case both are nil.
  177. // node.Parent.Hash = hash(node.Hash, node.Right.Hash) or
  178. // hash(node.Left.Hash, node.Hash), depending on whether node is a left/right child.
  179. type SimpleProofNode struct {
  180. Hash []byte
  181. Parent *SimpleProofNode
  182. Left *SimpleProofNode // Left sibling (only one of Left,Right is set)
  183. Right *SimpleProofNode // Right sibling (only one of Left,Right is set)
  184. }
  185. // Starting from a leaf SimpleProofNode, FlattenInnerHashes() will return
  186. // the inner hashes for the item corresponding to the leaf.
  187. func (spn *SimpleProofNode) FlattenInnerHashes() [][]byte {
  188. // Nonrecursive impl.
  189. innerHashes := [][]byte{}
  190. for spn != nil {
  191. if spn.Left != nil {
  192. innerHashes = append(innerHashes, spn.Left.Hash)
  193. } else if spn.Right != nil {
  194. innerHashes = append(innerHashes, spn.Right.Hash)
  195. } else {
  196. break
  197. }
  198. spn = spn.Parent
  199. }
  200. return innerHashes
  201. }
  202. // trails[0].Hash is the leaf hash for items[0].
  203. // trails[i].Parent.Parent....Parent == root for all i.
  204. func trailsFromHashables(items []Hashable) (trails []*SimpleProofNode, root *SimpleProofNode) {
  205. // Recursive impl.
  206. switch len(items) {
  207. case 0:
  208. return nil, nil
  209. case 1:
  210. trail := &SimpleProofNode{items[0].Hash(), nil, nil, nil}
  211. return []*SimpleProofNode{trail}, trail
  212. default:
  213. lefts, leftRoot := trailsFromHashables(items[:(len(items)+1)/2])
  214. rights, rightRoot := trailsFromHashables(items[(len(items)+1)/2:])
  215. rootHash := SimpleHashFromTwoHashes(leftRoot.Hash, rightRoot.Hash)
  216. root := &SimpleProofNode{rootHash, nil, nil, nil}
  217. leftRoot.Parent = root
  218. leftRoot.Right = rightRoot
  219. rightRoot.Parent = root
  220. rightRoot.Left = leftRoot
  221. return append(lefts, rights...), root
  222. }
  223. }