proof.go 4.3 KB

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