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.

173 lines
4.2 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. "crypto/sha256"
  25. "github.com/tendermint/tendermint/binary"
  26. )
  27. func HashFromTwoHashes(left []byte, right []byte) []byte {
  28. var n int64
  29. var err error
  30. var hasher = sha256.New()
  31. binary.WriteByteSlice(left, hasher, &n, &err)
  32. binary.WriteByteSlice(right, hasher, &n, &err)
  33. if err != nil {
  34. panic(err)
  35. }
  36. return hasher.Sum(nil)
  37. }
  38. func HashFromHashes(hashes [][]byte) []byte {
  39. // Recursive impl.
  40. switch len(hashes) {
  41. case 0:
  42. return nil
  43. case 1:
  44. return hashes[0]
  45. default:
  46. left := HashFromHashes(hashes[:(len(hashes)+1)/2])
  47. right := HashFromHashes(hashes[(len(hashes)+1)/2:])
  48. return HashFromTwoHashes(left, right)
  49. }
  50. }
  51. // Convenience for HashFromHashes.
  52. func HashFromBinaries(items []interface{}) []byte {
  53. hashes := [][]byte{}
  54. for _, item := range items {
  55. hasher, n, err := sha256.New(), new(int64), new(error)
  56. binary.WriteBinary(item, hasher, n, err)
  57. if *err != nil {
  58. panic(err)
  59. }
  60. hashes = append(hashes, hasher.Sum(nil))
  61. }
  62. return HashFromHashes(hashes)
  63. }
  64. // Convenience for HashFromHashes.
  65. func HashFromHashables(items []Hashable) []byte {
  66. hashes := [][]byte{}
  67. for _, item := range items {
  68. hash := item.Hash()
  69. hashes = append(hashes, hash)
  70. }
  71. return HashFromHashes(hashes)
  72. }
  73. type HashTrail struct {
  74. Hash []byte
  75. Parent *HashTrail
  76. Left *HashTrail
  77. Right *HashTrail
  78. }
  79. func (ht *HashTrail) Flatten() [][]byte {
  80. // Nonrecursive impl.
  81. trail := [][]byte{}
  82. for ht != nil {
  83. if ht.Left != nil {
  84. trail = append(trail, ht.Left.Hash)
  85. } else if ht.Right != nil {
  86. trail = append(trail, ht.Right.Hash)
  87. } else {
  88. break
  89. }
  90. ht = ht.Parent
  91. }
  92. return trail
  93. }
  94. // returned trails[0].Hash is the leaf hash.
  95. // trails[0].Parent.Hash is the hash above that, etc.
  96. func HashTrailsFromHashables(items []Hashable) (trails []*HashTrail, root *HashTrail) {
  97. // Recursive impl.
  98. switch len(items) {
  99. case 0:
  100. return nil, nil
  101. case 1:
  102. trail := &HashTrail{items[0].Hash(), nil, nil, nil}
  103. return []*HashTrail{trail}, trail
  104. default:
  105. lefts, leftRoot := HashTrailsFromHashables(items[:(len(items)+1)/2])
  106. rights, rightRoot := HashTrailsFromHashables(items[(len(items)+1)/2:])
  107. rootHash := HashFromTwoHashes(leftRoot.Hash, rightRoot.Hash)
  108. root := &HashTrail{rootHash, nil, nil, nil}
  109. leftRoot.Parent = root
  110. leftRoot.Right = rightRoot
  111. rightRoot.Parent = root
  112. rightRoot.Left = leftRoot
  113. return append(lefts, rights...), root
  114. }
  115. }
  116. // Ensures that leafHash is part of rootHash.
  117. func VerifyHashTrail(index uint, total uint, leafHash []byte, trail [][]byte, rootHash []byte) bool {
  118. computedRoot := ComputeRootFromTrail(index, total, leafHash, trail)
  119. if computedRoot == nil {
  120. return false
  121. }
  122. return bytes.Equal(computedRoot, rootHash)
  123. }
  124. // Use the leafHash and trail to get the root merkle hash.
  125. // If the length of the trail slice isn't exactly correct, the result is nil.
  126. func ComputeRootFromTrail(index uint, total uint, leafHash []byte, trail [][]byte) []byte {
  127. // Recursive impl.
  128. if index >= total {
  129. return nil
  130. }
  131. switch total {
  132. case 0:
  133. panic("Cannot call ComputeRootFromTrail() with 0 total")
  134. case 1:
  135. if len(trail) != 0 {
  136. return nil
  137. }
  138. return leafHash
  139. default:
  140. if len(trail) == 0 {
  141. return nil
  142. }
  143. numLeft := (total + 1) / 2
  144. if index < numLeft {
  145. leftRoot := ComputeRootFromTrail(index, numLeft, leafHash, trail[:len(trail)-1])
  146. if leftRoot == nil {
  147. return nil
  148. }
  149. return HashFromTwoHashes(leftRoot, trail[len(trail)-1])
  150. } else {
  151. rightRoot := ComputeRootFromTrail(index-numLeft, total-numLeft, leafHash, trail[:len(trail)-1])
  152. if rightRoot == nil {
  153. return nil
  154. }
  155. return HashFromTwoHashes(trail[len(trail)-1], rightRoot)
  156. }
  157. }
  158. }