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.

298 lines
8.3 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. "github.com/tendermint/tendermint/Godeps/_workspace/src/code.google.com/p/go.crypto/ripemd160"
  27. . "github.com/tendermint/tendermint/common"
  28. "github.com/tendermint/tendermint/wire"
  29. )
  30. func SimpleHashFromTwoHashes(left []byte, right []byte) []byte {
  31. var n int64
  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 := [][]byte{}
  57. for _, item := range items {
  58. hashes = append(hashes, SimpleHashFromBinary(item))
  59. }
  60. return SimpleHashFromHashes(hashes)
  61. }
  62. // General Convenience
  63. func SimpleHashFromBinary(item interface{}) []byte {
  64. hasher, n, err := ripemd160.New(), new(int64), 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 := [][]byte{}
  74. for _, item := range items {
  75. hash := item.Hash()
  76. hashes = append(hashes, 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(int64), 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. Index int `json:"index"`
  128. Total int `json:"total"`
  129. LeafHash []byte `json:"leaf_hash"`
  130. InnerHashes [][]byte `json:"inner_hashes"` // Hashes from leaf's sibling to a root's child.
  131. RootHash []byte `json:"root_hash"`
  132. }
  133. // proofs[0] is the proof for items[0].
  134. func SimpleProofsFromHashables(items []Hashable) (proofs []*SimpleProof) {
  135. trails, root := trailsFromHashables(items)
  136. proofs = make([]*SimpleProof, len(items))
  137. for i, trail := range trails {
  138. proofs[i] = &SimpleProof{
  139. Index: i,
  140. Total: len(items),
  141. LeafHash: trail.Hash,
  142. InnerHashes: trail.FlattenInnerHashes(),
  143. RootHash: root.Hash,
  144. }
  145. }
  146. return
  147. }
  148. // Verify that leafHash is a leaf hash of the simple-merkle-tree
  149. // which hashes to rootHash.
  150. func (sp *SimpleProof) Verify(leafHash []byte, rootHash []byte) bool {
  151. if !bytes.Equal(leafHash, sp.LeafHash) {
  152. return false
  153. }
  154. if !bytes.Equal(rootHash, sp.RootHash) {
  155. return false
  156. }
  157. computedHash := computeHashFromInnerHashes(sp.Index, sp.Total, sp.LeafHash, sp.InnerHashes)
  158. if computedHash == nil {
  159. return false
  160. }
  161. if !bytes.Equal(computedHash, rootHash) {
  162. return false
  163. }
  164. return true
  165. }
  166. func (sp *SimpleProof) String() string {
  167. return sp.StringIndented("")
  168. }
  169. func (sp *SimpleProof) StringIndented(indent string) string {
  170. return fmt.Sprintf(`SimpleProof{
  171. %s Index: %v
  172. %s Total: %v
  173. %s LeafHash: %X
  174. %s InnerHashes: %X
  175. %s RootHash: %X
  176. %s}`,
  177. indent, sp.Index,
  178. indent, sp.Total,
  179. indent, sp.LeafHash,
  180. indent, sp.InnerHashes,
  181. indent, sp.RootHash,
  182. indent)
  183. }
  184. // Use the leafHash and innerHashes to get the root merkle hash.
  185. // If the length of the innerHashes slice isn't exactly correct, the result is nil.
  186. func computeHashFromInnerHashes(index int, total int, leafHash []byte, innerHashes [][]byte) []byte {
  187. // Recursive impl.
  188. if index >= total {
  189. return nil
  190. }
  191. switch total {
  192. case 0:
  193. PanicSanity("Cannot call computeHashFromInnerHashes() with 0 total")
  194. return nil
  195. case 1:
  196. if len(innerHashes) != 0 {
  197. return nil
  198. }
  199. return leafHash
  200. default:
  201. if len(innerHashes) == 0 {
  202. return nil
  203. }
  204. numLeft := (total + 1) / 2
  205. if index < numLeft {
  206. leftHash := computeHashFromInnerHashes(index, numLeft, leafHash, innerHashes[:len(innerHashes)-1])
  207. if leftHash == nil {
  208. return nil
  209. }
  210. return SimpleHashFromTwoHashes(leftHash, innerHashes[len(innerHashes)-1])
  211. } else {
  212. rightHash := computeHashFromInnerHashes(index-numLeft, total-numLeft, leafHash, innerHashes[:len(innerHashes)-1])
  213. if rightHash == nil {
  214. return nil
  215. }
  216. return SimpleHashFromTwoHashes(innerHashes[len(innerHashes)-1], rightHash)
  217. }
  218. }
  219. }
  220. // Helper structure to construct merkle proof.
  221. // The node and the tree is thrown away afterwards.
  222. // Exactly one of node.Left and node.Right is nil, unless node is the root, in which case both are nil.
  223. // node.Parent.Hash = hash(node.Hash, node.Right.Hash) or
  224. // hash(node.Left.Hash, node.Hash), depending on whether node is a left/right child.
  225. type SimpleProofNode struct {
  226. Hash []byte
  227. Parent *SimpleProofNode
  228. Left *SimpleProofNode // Left sibling (only one of Left,Right is set)
  229. Right *SimpleProofNode // Right sibling (only one of Left,Right is set)
  230. }
  231. // Starting from a leaf SimpleProofNode, FlattenInnerHashes() will return
  232. // the inner hashes for the item corresponding to the leaf.
  233. func (spn *SimpleProofNode) FlattenInnerHashes() [][]byte {
  234. // Nonrecursive impl.
  235. innerHashes := [][]byte{}
  236. for spn != nil {
  237. if spn.Left != nil {
  238. innerHashes = append(innerHashes, spn.Left.Hash)
  239. } else if spn.Right != nil {
  240. innerHashes = append(innerHashes, spn.Right.Hash)
  241. } else {
  242. break
  243. }
  244. spn = spn.Parent
  245. }
  246. return innerHashes
  247. }
  248. // trails[0].Hash is the leaf hash for items[0].
  249. // trails[i].Parent.Parent....Parent == root for all i.
  250. func trailsFromHashables(items []Hashable) (trails []*SimpleProofNode, root *SimpleProofNode) {
  251. // Recursive impl.
  252. switch len(items) {
  253. case 0:
  254. return nil, nil
  255. case 1:
  256. trail := &SimpleProofNode{items[0].Hash(), nil, nil, nil}
  257. return []*SimpleProofNode{trail}, trail
  258. default:
  259. lefts, leftRoot := trailsFromHashables(items[:(len(items)+1)/2])
  260. rights, rightRoot := trailsFromHashables(items[(len(items)+1)/2:])
  261. rootHash := SimpleHashFromTwoHashes(leftRoot.Hash, rightRoot.Hash)
  262. root := &SimpleProofNode{rootHash, nil, nil, nil}
  263. leftRoot.Parent = root
  264. leftRoot.Right = rightRoot
  265. rightRoot.Parent = root
  266. rightRoot.Left = leftRoot
  267. return append(lefts, rights...), root
  268. }
  269. }