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.

199 lines
6.0 KiB

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