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/crypto"
  22. "github.com/ethereum/go-ethereum/ethdb"
  23. "github.com/ethereum/go-ethereum/log"
  24. "github.com/ethereum/go-ethereum/rlp"
  25. )
  26. // Prove constructs a merkle proof for key. The result contains all encoded nodes
  27. // on the path to the value at key. The value itself is also included in the last
  28. // node and can be retrieved by verifying the proof.
  29. //
  30. // If the trie does not contain a value for key, the returned proof contains all
  31. // nodes of the longest existing prefix of the key (at least the root node), ending
  32. // with the node that proves the absence of the key.
  33. func (t *Trie) Prove(key []byte, fromLevel uint, proofDb ethdb.Putter) error {
  34. // Collect all nodes on the path to key.
  35. key = keybytesToHex(key)
  36. nodes := []node{}
  37. tn := t.root
  38. for len(key) > 0 && tn != nil {
  39. switch n := tn.(type) {
  40. case *shortNode:
  41. if len(key) < len(n.Key) || !bytes.Equal(n.Key, key[:len(n.Key)]) {
  42. // The trie doesn't contain the key.
  43. tn = nil
  44. } else {
  45. tn = n.Val
  46. key = key[len(n.Key):]
  47. }
  48. nodes = append(nodes, n)
  49. case *fullNode:
  50. tn = n.Children[key[0]]
  51. key = key[1:]
  52. nodes = append(nodes, n)
  53. case hashNode:
  54. var err error
  55. tn, err = t.resolveHash(n, nil)
  56. if err != nil {
  57. log.Error(fmt.Sprintf("Unhandled trie error: %v", err))
  58. return err
  59. }
  60. default:
  61. panic(fmt.Sprintf("%T: invalid node: %v", tn, tn))
  62. }
  63. }
  64. hasher := newHasher(0, 0, nil)
  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 = crypto.Keccak256(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.Putter) 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 DatabaseReader) (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, 0)
  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. }