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.

228 lines
6.8 KiB

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