github.com/MMMY001/go-ethereum@v1.9.7/trie/proof.go (about)

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