proof.go 4.4 KB

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