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.

200 lines
6.0 KiB

  1. package merkle
  2. import (
  3. "bytes"
  4. "errors"
  5. "fmt"
  6. cmn "github.com/tendermint/tendermint/libs/common"
  7. )
  8. // SimpleProof represents a simple Merkle proof.
  9. // NOTE: The convention for proofs is to include leaf hashes but to
  10. // exclude the root hash.
  11. // This convention is implemented across IAVL range proofs as well.
  12. // Keep this consistent unless there's a very good reason to change
  13. // everything. This also affects the generalized proof system as
  14. // well.
  15. type SimpleProof struct {
  16. Total int `json:"total"` // Total number of items.
  17. Index int `json:"index"` // Index of item to prove.
  18. LeafHash []byte `json:"leaf_hash"` // Hash of item value.
  19. Aunts [][]byte `json:"aunts"` // Hashes from leaf's sibling to a root's child.
  20. }
  21. // SimpleProofsFromByteSlices computes inclusion proof for given items.
  22. // proofs[0] is the proof for items[0].
  23. func SimpleProofsFromByteSlices(items [][]byte) (rootHash []byte, proofs []*SimpleProof) {
  24. trails, rootSPN := trailsFromByteSlices(items)
  25. rootHash = rootSPN.Hash
  26. proofs = make([]*SimpleProof, len(items))
  27. for i, trail := range trails {
  28. proofs[i] = &SimpleProof{
  29. Total: len(items),
  30. Index: i,
  31. LeafHash: trail.Hash,
  32. Aunts: trail.FlattenAunts(),
  33. }
  34. }
  35. return
  36. }
  37. // SimpleProofsFromMap generates proofs from a map. The keys/values of the map will be used as the keys/values
  38. // in the underlying key-value pairs.
  39. // The keys are sorted before the proofs are computed.
  40. func SimpleProofsFromMap(m map[string][]byte) (rootHash []byte, proofs map[string]*SimpleProof, keys []string) {
  41. sm := newSimpleMap()
  42. for k, v := range m {
  43. sm.Set(k, v)
  44. }
  45. sm.Sort()
  46. kvs := sm.kvs
  47. kvsBytes := make([][]byte, len(kvs))
  48. for i, kvp := range kvs {
  49. kvsBytes[i] = KVPair(kvp).Bytes()
  50. }
  51. rootHash, proofList := SimpleProofsFromByteSlices(kvsBytes)
  52. proofs = make(map[string]*SimpleProof)
  53. keys = make([]string, len(proofList))
  54. for i, kvp := range kvs {
  55. proofs[string(kvp.Key)] = proofList[i]
  56. keys[i] = string(kvp.Key)
  57. }
  58. return
  59. }
  60. // Verify that the SimpleProof proves the root hash.
  61. // Check sp.Index/sp.Total manually if needed
  62. func (sp *SimpleProof) Verify(rootHash []byte, leaf []byte) error {
  63. leafHash := leafHash(leaf)
  64. if sp.Total < 0 {
  65. return errors.New("Proof total must be positive")
  66. }
  67. if sp.Index < 0 {
  68. return errors.New("Proof index cannot be negative")
  69. }
  70. if !bytes.Equal(sp.LeafHash, leafHash) {
  71. return cmn.NewError("invalid leaf hash: wanted %X got %X", leafHash, sp.LeafHash)
  72. }
  73. computedHash := sp.ComputeRootHash()
  74. if !bytes.Equal(computedHash, rootHash) {
  75. return cmn.NewError("invalid root hash: wanted %X got %X", rootHash, computedHash)
  76. }
  77. return nil
  78. }
  79. // Compute the root hash given a leaf hash. Does not verify the result.
  80. func (sp *SimpleProof) ComputeRootHash() []byte {
  81. return computeHashFromAunts(
  82. sp.Index,
  83. sp.Total,
  84. sp.LeafHash,
  85. sp.Aunts,
  86. )
  87. }
  88. // String implements the stringer interface for SimpleProof.
  89. // It is a wrapper around StringIndented.
  90. func (sp *SimpleProof) String() string {
  91. return sp.StringIndented("")
  92. }
  93. // StringIndented generates a canonical string representation of a SimpleProof.
  94. func (sp *SimpleProof) StringIndented(indent string) string {
  95. return fmt.Sprintf(`SimpleProof{
  96. %s Aunts: %X
  97. %s}`,
  98. indent, sp.Aunts,
  99. indent)
  100. }
  101. // Use the leafHash and innerHashes to get the root merkle hash.
  102. // If the length of the innerHashes slice isn't exactly correct, the result is nil.
  103. // Recursive impl.
  104. func computeHashFromAunts(index int, total int, leafHash []byte, innerHashes [][]byte) []byte {
  105. if index >= total || index < 0 || total <= 0 {
  106. return nil
  107. }
  108. switch total {
  109. case 0:
  110. panic("Cannot call computeHashFromAunts() with 0 total")
  111. case 1:
  112. if len(innerHashes) != 0 {
  113. return nil
  114. }
  115. return leafHash
  116. default:
  117. if len(innerHashes) == 0 {
  118. return nil
  119. }
  120. numLeft := getSplitPoint(total)
  121. if index < numLeft {
  122. leftHash := computeHashFromAunts(index, numLeft, leafHash, innerHashes[:len(innerHashes)-1])
  123. if leftHash == nil {
  124. return nil
  125. }
  126. return innerHash(leftHash, innerHashes[len(innerHashes)-1])
  127. }
  128. rightHash := computeHashFromAunts(index-numLeft, total-numLeft, leafHash, innerHashes[:len(innerHashes)-1])
  129. if rightHash == nil {
  130. return nil
  131. }
  132. return innerHash(innerHashes[len(innerHashes)-1], rightHash)
  133. }
  134. }
  135. // SimpleProofNode is a helper structure to construct merkle proof.
  136. // The node and the tree is thrown away afterwards.
  137. // Exactly one of node.Left and node.Right is nil, unless node is the root, in which case both are nil.
  138. // node.Parent.Hash = hash(node.Hash, node.Right.Hash) or
  139. // hash(node.Left.Hash, node.Hash), depending on whether node is a left/right child.
  140. type SimpleProofNode struct {
  141. Hash []byte
  142. Parent *SimpleProofNode
  143. Left *SimpleProofNode // Left sibling (only one of Left,Right is set)
  144. Right *SimpleProofNode // Right sibling (only one of Left,Right is set)
  145. }
  146. // FlattenAunts will return the inner hashes for the item corresponding to the leaf,
  147. // starting from a leaf SimpleProofNode.
  148. func (spn *SimpleProofNode) FlattenAunts() [][]byte {
  149. // Nonrecursive impl.
  150. innerHashes := [][]byte{}
  151. for spn != nil {
  152. switch {
  153. case spn.Left != nil:
  154. innerHashes = append(innerHashes, spn.Left.Hash)
  155. case spn.Right != nil:
  156. innerHashes = append(innerHashes, spn.Right.Hash)
  157. default:
  158. break
  159. }
  160. spn = spn.Parent
  161. }
  162. return innerHashes
  163. }
  164. // trails[0].Hash is the leaf hash for items[0].
  165. // trails[i].Parent.Parent....Parent == root for all i.
  166. func trailsFromByteSlices(items [][]byte) (trails []*SimpleProofNode, root *SimpleProofNode) {
  167. // Recursive impl.
  168. switch len(items) {
  169. case 0:
  170. return nil, nil
  171. case 1:
  172. trail := &SimpleProofNode{leafHash(items[0]), nil, nil, nil}
  173. return []*SimpleProofNode{trail}, trail
  174. default:
  175. k := getSplitPoint(len(items))
  176. lefts, leftRoot := trailsFromByteSlices(items[:k])
  177. rights, rightRoot := trailsFromByteSlices(items[k:])
  178. rootHash := innerHash(leftRoot.Hash, rightRoot.Hash)
  179. root := &SimpleProofNode{rootHash, nil, nil, nil}
  180. leftRoot.Parent = root
  181. leftRoot.Right = rightRoot
  182. rightRoot.Parent = root
  183. rightRoot.Left = leftRoot
  184. return append(lefts, rights...), root
  185. }
  186. }