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.

263 lines
5.6 KiB

10 years ago
11 years ago
11 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
11 years ago
10 years ago
11 years ago
10 years ago
10 years ago
10 years ago
11 years ago
10 years ago
10 years ago
10 years ago
11 years ago
10 years ago
10 years ago
11 years ago
11 years ago
10 years ago
11 years ago
11 years ago
10 years ago
11 years ago
11 years ago
11 years ago
  1. package merkle
  2. import (
  3. "bytes"
  4. "crypto/sha256"
  5. "fmt"
  6. . "github.com/tendermint/tendermint/binary"
  7. )
  8. func HashFromTwoHashes(left []byte, right []byte) []byte {
  9. var n int64
  10. var err error
  11. var hasher = sha256.New()
  12. WriteByteSlice(hasher, left, &n, &err)
  13. WriteByteSlice(hasher, right, &n, &err)
  14. if err != nil {
  15. panic(err)
  16. }
  17. return hasher.Sum(nil)
  18. }
  19. /*
  20. Computes a deterministic minimal height merkle tree hash.
  21. If the number of items is not a power of two, some leaves
  22. will be at different levels.
  23. *
  24. / \
  25. / \
  26. / \
  27. / \
  28. * *
  29. / \ / \
  30. / \ / \
  31. / \ / \
  32. * h2 * *
  33. / \ / \ / \
  34. h0 h1 h3 h4 h5 h6
  35. */
  36. func HashFromHashes(hashes [][]byte) []byte {
  37. switch len(hashes) {
  38. case 0:
  39. return nil
  40. case 1:
  41. return hashes[0]
  42. default:
  43. left := HashFromHashes(hashes[:len(hashes)/2])
  44. right := HashFromHashes(hashes[len(hashes)/2:])
  45. return HashFromTwoHashes(left, right)
  46. }
  47. }
  48. // Convenience for HashFromHashes.
  49. func HashFromBinaries(items []Binary) []byte {
  50. hashes := [][]byte{}
  51. for _, item := range items {
  52. hasher := sha256.New()
  53. _, err := item.WriteTo(hasher)
  54. if err != nil {
  55. panic(err)
  56. }
  57. hash := hasher.Sum(nil)
  58. hashes = append(hashes, hash)
  59. }
  60. return HashFromHashes(hashes)
  61. }
  62. // Convenience for HashFromHashes.
  63. func HashFromHashables(items []Hashable) []byte {
  64. hashes := [][]byte{}
  65. for _, item := range items {
  66. hash := item.Hash()
  67. hashes = append(hashes, hash)
  68. }
  69. return HashFromHashes(hashes)
  70. }
  71. /*
  72. Calculates an array of hashes, useful for deriving hash trails.
  73. 7
  74. / \
  75. / \
  76. / \
  77. / \
  78. 3 11
  79. / \ / \
  80. / \ / \
  81. / \ / \
  82. 1 5 9 13
  83. / \ / \ / \ / \
  84. 0 2 4 6 8 10 12 14
  85. h0 h1 h2 h3 h4 h5 h6 h7
  86. (diagram and idea borrowed from libswift)
  87. The hashes provided get assigned to even indices.
  88. The derived merkle hashes get assigned to odd indices.
  89. If "hashes" is not of length power of 2, it is padded
  90. with blank (zeroed) hashes.
  91. */
  92. func HashTreeFromHashes(hashes [][]byte) [][]byte {
  93. // Make length of "hashes" a power of 2
  94. hashesLen := uint32(len(hashes))
  95. fullLen := uint32(1)
  96. for {
  97. if fullLen >= hashesLen {
  98. break
  99. } else {
  100. fullLen <<= 1
  101. }
  102. }
  103. blank := make([]byte, len(hashes[0]))
  104. for i := hashesLen; i < fullLen; i++ {
  105. hashes = append(hashes, blank)
  106. }
  107. // The result is twice the length minus one.
  108. res := make([][]byte, len(hashes)*2-1)
  109. for i, hash := range hashes {
  110. res[i*2] = hash
  111. }
  112. // Fill all the hashes recursively.
  113. fillTreeRoot(res, 0, len(res)-1)
  114. return res
  115. }
  116. // Fill in the blanks.
  117. func fillTreeRoot(res [][]byte, start, end int) []byte {
  118. if start == end {
  119. return res[start]
  120. } else {
  121. mid := (start + end) / 2
  122. left := fillTreeRoot(res, start, mid-1)
  123. right := fillTreeRoot(res, mid+1, end)
  124. root := HashFromTwoHashes(left, right)
  125. res[mid] = root
  126. return root
  127. }
  128. }
  129. // Convenience for HashTreeFromHashes.
  130. func HashTreeFromHashables(items []Hashable) [][]byte {
  131. hashes := [][]byte{}
  132. for _, item := range items {
  133. hash := item.Hash()
  134. hashes = append(hashes, hash)
  135. }
  136. return HashTreeFromHashes(hashes)
  137. }
  138. /*
  139. Given the original index of an item,
  140. (e.g. for h5 in the diagram above, the index is 5, not 10)
  141. returns a trail of hashes, which along with the index can be
  142. used to calculate the merkle root.
  143. See VerifyHashTrailForIndex()
  144. */
  145. func HashTrailForIndex(hashTree [][]byte, index int) [][]byte {
  146. trail := [][]byte{}
  147. index *= 2
  148. // We start from the leaf layer and work our way up.
  149. // Notice the indices in the diagram:
  150. // 0 2 4 ... offset 0, stride 2
  151. // 1 5 9 ... offset 1, stride 4
  152. // 3 11 19 ... offset 3, stride 8
  153. // 7 23 39 ... offset 7, stride 16 etc.
  154. offset := 0
  155. stride := 2
  156. for {
  157. // Calculate sibling of index.
  158. var next int
  159. if ((index-offset)/stride)%2 == 0 {
  160. next = index + stride
  161. } else {
  162. next = index - stride
  163. }
  164. if next >= len(hashTree) {
  165. break
  166. }
  167. // Insert sibling hash to trail.
  168. trail = append(trail, hashTree[next])
  169. index = (index + next) / 2
  170. offset += stride / 2
  171. stride *= 2
  172. }
  173. return trail
  174. }
  175. // Ensures that leafHash is part of rootHash.
  176. func VerifyHashTrailForIndex(index int, leafHash []byte, trail [][]byte, rootHash []byte) bool {
  177. index *= 2
  178. offset := 0
  179. stride := 2
  180. tempHash := make([]byte, len(leafHash))
  181. copy(tempHash, leafHash)
  182. for i := 0; i < len(trail); i++ {
  183. var next int
  184. if ((index-offset)/stride)%2 == 0 {
  185. next = index + stride
  186. tempHash = HashFromTwoHashes(tempHash, trail[i])
  187. } else {
  188. next = index - stride
  189. tempHash = HashFromTwoHashes(trail[i], tempHash)
  190. }
  191. index = (index + next) / 2
  192. offset += stride / 2
  193. stride *= 2
  194. }
  195. return bytes.Equal(rootHash, tempHash)
  196. }
  197. //-----------------------------------------------------------------------------
  198. func PrintIAVLNode(node *IAVLNode) {
  199. fmt.Println("==== NODE")
  200. if node != nil {
  201. printIAVLNode(node, 0)
  202. }
  203. fmt.Println("==== END")
  204. }
  205. func printIAVLNode(node *IAVLNode, indent int) {
  206. indentPrefix := ""
  207. for i := 0; i < indent; i++ {
  208. indentPrefix += " "
  209. }
  210. if node.rightNode != nil {
  211. printIAVLNode(node.rightNode, indent+1)
  212. } else if node.rightHash != nil {
  213. fmt.Printf("%s %X\n", indentPrefix, node.rightHash)
  214. }
  215. fmt.Printf("%s%v:%v\n", indentPrefix, node.key, node.height)
  216. if node.leftNode != nil {
  217. printIAVLNode(node.leftNode, indent+1)
  218. } else if node.leftHash != nil {
  219. fmt.Printf("%s %X\n", indentPrefix, node.leftHash)
  220. }
  221. }
  222. func maxUint8(a, b uint8) uint8 {
  223. if a > b {
  224. return a
  225. }
  226. return b
  227. }