proof.go 4.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144
  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/log"
  23. "github.com/ethereum/go-ethereum/rlp"
  24. )
  25. // Prove constructs a merkle proof for key. The result contains all
  26. // encoded nodes on the path to the value at key. The value itself is
  27. // also included in the last node and can be retrieved by verifying
  28. // the proof.
  29. //
  30. // If the trie does not contain a value for key, the returned proof
  31. // contains all nodes of the longest existing prefix of the key
  32. // (at least the root node), ending with the node that proves the
  33. // absence of the key.
  34. func (t *Trie) Prove(key []byte, fromLevel uint, proofDb DatabaseWriter) error {
  35. // Collect all nodes on the path to key.
  36. key = keybytesToHex(key)
  37. nodes := []node{}
  38. tn := t.root
  39. for len(key) > 0 && tn != nil {
  40. switch n := tn.(type) {
  41. case *shortNode:
  42. if len(key) < len(n.Key) || !bytes.Equal(n.Key, key[:len(n.Key)]) {
  43. // The trie doesn't contain the key.
  44. tn = nil
  45. } else {
  46. tn = n.Val
  47. key = key[len(n.Key):]
  48. }
  49. nodes = append(nodes, n)
  50. case *fullNode:
  51. tn = n.Children[key[0]]
  52. key = key[1:]
  53. nodes = append(nodes, n)
  54. case hashNode:
  55. var err error
  56. tn, err = t.resolveHash(n, nil)
  57. if err != nil {
  58. log.Error(fmt.Sprintf("Unhandled trie error: %v", err))
  59. return err
  60. }
  61. default:
  62. panic(fmt.Sprintf("%T: invalid node: %v", tn, tn))
  63. }
  64. }
  65. hasher := newHasher(0, 0)
  66. for i, n := range nodes {
  67. // Don't bother checking for errors here since hasher panics
  68. // if encoding doesn't work and we're not writing to any database.
  69. n, _, _ = hasher.hashChildren(n, nil)
  70. hn, _ := hasher.store(n, nil, false)
  71. if hash, ok := hn.(hashNode); ok || i == 0 {
  72. // If the node's database encoding is a hash (or is the
  73. // root node), it becomes a proof element.
  74. if fromLevel > 0 {
  75. fromLevel--
  76. } else {
  77. enc, _ := rlp.EncodeToBytes(n)
  78. if !ok {
  79. hash = crypto.Keccak256(enc)
  80. }
  81. proofDb.Put(hash, enc)
  82. }
  83. }
  84. }
  85. return nil
  86. }
  87. // VerifyProof checks merkle proofs. The given proof must contain the
  88. // value for key in a trie with the given root hash. VerifyProof
  89. // returns an error if the proof contains invalid trie nodes or the
  90. // wrong value.
  91. func VerifyProof(rootHash common.Hash, key []byte, proofDb DatabaseReader) (value []byte, err error, nodes int) {
  92. key = keybytesToHex(key)
  93. wantHash := rootHash[:]
  94. for i := 0; ; i++ {
  95. buf, _ := proofDb.Get(wantHash)
  96. if buf == nil {
  97. return nil, fmt.Errorf("proof node %d (hash %064x) missing", i, wantHash[:]), i
  98. }
  99. n, err := decodeNode(wantHash, buf, 0)
  100. if err != nil {
  101. return nil, fmt.Errorf("bad proof node %d: %v", i, err), i
  102. }
  103. keyrest, cld := get(n, key)
  104. switch cld := cld.(type) {
  105. case nil:
  106. // The trie doesn't contain the key.
  107. return nil, nil, i
  108. case hashNode:
  109. key = keyrest
  110. wantHash = cld
  111. case valueNode:
  112. return cld, nil, i + 1
  113. }
  114. }
  115. }
  116. func get(tn node, key []byte) ([]byte, node) {
  117. for {
  118. switch n := tn.(type) {
  119. case *shortNode:
  120. if len(key) < len(n.Key) || !bytes.Equal(n.Key, key[:len(n.Key)]) {
  121. return nil, nil
  122. }
  123. tn = n.Val
  124. key = key[len(n.Key):]
  125. case *fullNode:
  126. tn = n.Children[key[0]]
  127. key = key[1:]
  128. case hashNode:
  129. return key, n
  130. case nil:
  131. return key, nil
  132. case valueNode:
  133. return nil, n
  134. default:
  135. panic(fmt.Sprintf("%T: invalid node: %v", tn, tn))
  136. }
  137. }
  138. }