proof.go 4.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151
  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.Children[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. hasher := newHasher()
  70. proof := make([]rlp.RawValue, 0, len(nodes))
  71. for i, n := range nodes {
  72. // Don't bother checking for errors here since hasher panics
  73. // if encoding doesn't work and we're not writing to any database.
  74. n, _, _ = hasher.hashChildren(n, nil)
  75. hn, _ := hasher.store(n, nil, false)
  76. if _, ok := hn.(hashNode); ok || i == 0 {
  77. // If the node's database encoding is a hash (or is the
  78. // root node), it becomes a proof element.
  79. enc, _ := rlp.EncodeToBytes(n)
  80. proof = append(proof, enc)
  81. }
  82. }
  83. return proof
  84. }
  85. // VerifyProof checks merkle proofs. The given proof must contain the
  86. // value for key in a trie with the given root hash. VerifyProof
  87. // returns an error if the proof contains invalid trie nodes or the
  88. // wrong value.
  89. func VerifyProof(rootHash common.Hash, key []byte, proof []rlp.RawValue) (value []byte, err error) {
  90. key = compactHexDecode(key)
  91. sha := sha3.NewKeccak256()
  92. wantHash := rootHash.Bytes()
  93. for i, buf := range proof {
  94. sha.Reset()
  95. sha.Write(buf)
  96. if !bytes.Equal(sha.Sum(nil), wantHash) {
  97. return nil, fmt.Errorf("bad proof node %d: hash mismatch", i)
  98. }
  99. n, err := decodeNode(wantHash, buf)
  100. if err != nil {
  101. return nil, fmt.Errorf("bad proof node %d: %v", i, err)
  102. }
  103. keyrest, cld := get(n, key)
  104. switch cld := cld.(type) {
  105. case nil:
  106. if i != len(proof)-1 {
  107. return nil, fmt.Errorf("key mismatch at proof node %d", i)
  108. } else {
  109. // The trie doesn't contain the key.
  110. return nil, nil
  111. }
  112. case hashNode:
  113. key = keyrest
  114. wantHash = cld
  115. case valueNode:
  116. if i != len(proof)-1 {
  117. return nil, errors.New("additional nodes at end of proof")
  118. }
  119. return cld, nil
  120. }
  121. }
  122. return nil, errors.New("unexpected end of proof")
  123. }
  124. func get(tn node, key []byte) ([]byte, node) {
  125. for len(key) > 0 {
  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. default:
  141. panic(fmt.Sprintf("%T: invalid node: %v", tn, tn))
  142. }
  143. }
  144. return nil, tn.(valueNode)
  145. }