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.

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