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.

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