proof.go 4.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154
  1. // Copyright 2015 The go-ethereum Authors
  2. // This file is part of the go-ethereum library.
  3. //
  4. // The go-ethereum library is free software: you can redistribute it and/or modify
  5. // it under the terms of the GNU Lesser General Public License as published by
  6. // the Free Software Foundation, either version 3 of the License, or
  7. // (at your option) any later version.
  8. //
  9. // The go-ethereum library is distributed in the hope that it will be useful,
  10. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. // GNU Lesser General Public License for more details.
  13. //
  14. // You should have received a copy of the GNU Lesser General Public License
  15. // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
  16. package trie
  17. import (
  18. "bytes"
  19. "fmt"
  20. "github.com/ethereum/go-ethereum/common"
  21. "github.com/ethereum/go-ethereum/ethdb"
  22. "github.com/ethereum/go-ethereum/log"
  23. "github.com/ethereum/go-ethereum/rlp"
  24. )
  25. // Prove constructs a merkle proof for key. The result contains all encoded nodes
  26. // on the path to the value at key. The value itself is also included in the last
  27. // node and can be retrieved by verifying the proof.
  28. //
  29. // If the trie does not contain a value for key, the returned proof contains all
  30. // nodes of the longest existing prefix of the key (at least the root node), ending
  31. // with the node that proves the absence of the key.
  32. func (t *Trie) Prove(key []byte, fromLevel uint, proofDb ethdb.KeyValueWriter) error {
  33. // Collect all nodes on the path to key.
  34. key = keybytesToHex(key)
  35. var nodes []node
  36. tn := t.root
  37. for len(key) > 0 && tn != nil {
  38. switch n := tn.(type) {
  39. case *shortNode:
  40. if len(key) < len(n.Key) || !bytes.Equal(n.Key, key[:len(n.Key)]) {
  41. // The trie doesn't contain the key.
  42. tn = nil
  43. } else {
  44. tn = n.Val
  45. key = key[len(n.Key):]
  46. }
  47. nodes = append(nodes, n)
  48. case *fullNode:
  49. tn = n.Children[key[0]]
  50. key = key[1:]
  51. nodes = append(nodes, n)
  52. case hashNode:
  53. var err error
  54. tn, err = t.resolveHash(n, nil)
  55. if err != nil {
  56. log.Error(fmt.Sprintf("Unhandled trie error: %v", err))
  57. return err
  58. }
  59. default:
  60. panic(fmt.Sprintf("%T: invalid node: %v", tn, tn))
  61. }
  62. }
  63. hasher := newHasher(nil)
  64. defer returnHasherToPool(hasher)
  65. for i, n := range nodes {
  66. // Don't bother checking for errors here since hasher panics
  67. // if encoding doesn't work and we're not writing to any database.
  68. n, _, _ = hasher.hashChildren(n, nil)
  69. hn, _ := hasher.store(n, nil, false)
  70. if hash, ok := hn.(hashNode); ok || i == 0 {
  71. // If the node's database encoding is a hash (or is the
  72. // root node), it becomes a proof element.
  73. if fromLevel > 0 {
  74. fromLevel--
  75. } else {
  76. enc, _ := rlp.EncodeToBytes(n)
  77. if !ok {
  78. hash = hasher.makeHashNode(enc)
  79. }
  80. proofDb.Put(hash, enc)
  81. }
  82. }
  83. }
  84. return nil
  85. }
  86. // Prove constructs a merkle proof for key. The result contains all encoded nodes
  87. // on the path to the value at key. The value itself is also included in the last
  88. // node and can be retrieved by verifying the proof.
  89. //
  90. // If the trie does not contain a value for key, the returned proof contains all
  91. // nodes of the longest existing prefix of the key (at least the root node), ending
  92. // with the node that proves the absence of the key.
  93. func (t *SecureTrie) Prove(key []byte, fromLevel uint, proofDb ethdb.KeyValueWriter) error {
  94. return t.trie.Prove(key, fromLevel, proofDb)
  95. }
  96. // VerifyProof checks merkle proofs. The given proof must contain the value for
  97. // key in a trie with the given root hash. VerifyProof returns an error if the
  98. // proof contains invalid trie nodes or the wrong value.
  99. func VerifyProof(rootHash common.Hash, key []byte, proofDb ethdb.KeyValueReader) (value []byte, nodes int, err error) {
  100. key = keybytesToHex(key)
  101. wantHash := rootHash
  102. for i := 0; ; i++ {
  103. buf, _ := proofDb.Get(wantHash[:])
  104. if buf == nil {
  105. return nil, i, fmt.Errorf("proof node %d (hash %064x) missing", i, wantHash)
  106. }
  107. n, err := decodeNode(wantHash[:], buf)
  108. if err != nil {
  109. return nil, i, fmt.Errorf("bad proof node %d: %v", i, err)
  110. }
  111. keyrest, cld := get(n, key)
  112. switch cld := cld.(type) {
  113. case nil:
  114. // The trie doesn't contain the key.
  115. return nil, i, nil
  116. case hashNode:
  117. key = keyrest
  118. copy(wantHash[:], cld)
  119. case valueNode:
  120. return cld, i + 1, nil
  121. }
  122. }
  123. }
  124. func get(tn node, key []byte) ([]byte, node) {
  125. for {
  126. switch n := tn.(type) {
  127. case *shortNode:
  128. if len(key) < len(n.Key) || !bytes.Equal(n.Key, key[:len(n.Key)]) {
  129. return nil, nil
  130. }
  131. tn = n.Val
  132. key = key[len(n.Key):]
  133. case *fullNode:
  134. tn = n.Children[key[0]]
  135. key = key[1:]
  136. case hashNode:
  137. return key, n
  138. case nil:
  139. return key, nil
  140. case valueNode:
  141. return nil, n
  142. default:
  143. panic(fmt.Sprintf("%T: invalid node: %v", tn, tn))
  144. }
  145. }
  146. }