github.com/intfoundation/intchain@v0.0.0-20220727031208-4316ad31ca73/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/intfoundation/intchain/common"
    24  	"github.com/intfoundation/intchain/intdb"
    25  	"github.com/intfoundation/intchain/log"
    26  	"github.com/intfoundation/intchain/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 intdb.Writer) 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 intdb.Writer) 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  //
   107  // Note, the method assumes that all key-values in proofDb satisfy key = hash(value).
   108  func VerifyProof(rootHash common.Hash, key []byte, proofDb intdb.Reader) (value []byte, nodes int, err error) {
   109  	key = keybytesToHex(key)
   110  	wantHash := rootHash
   111  	for i := 0; ; i++ {
   112  		buf, _ := proofDb.Get(wantHash[:])
   113  		if buf == nil {
   114  			return nil, i, fmt.Errorf("proof node %d (hash %064x) missing", i, wantHash)
   115  		}
   116  		n, err := decodeNode(wantHash[:], buf)
   117  		if err != nil {
   118  			return nil, i, fmt.Errorf("bad proof node %d: %v", i, err)
   119  		}
   120  		keyrest, cld := get(n, key)
   121  		switch cld := cld.(type) {
   122  		case nil:
   123  			// The trie doesn't contain the key.
   124  			return nil, i, nil
   125  		case hashNode:
   126  			key = keyrest
   127  			copy(wantHash[:], cld)
   128  		case valueNode:
   129  			return cld, i + 1, nil
   130  		}
   131  	}
   132  }
   133  
   134  func get(tn node, key []byte) ([]byte, node) {
   135  	for {
   136  		switch n := tn.(type) {
   137  		case *shortNode:
   138  			if len(key) < len(n.Key) || !bytes.Equal(n.Key, key[:len(n.Key)]) {
   139  				return nil, nil
   140  			}
   141  			tn = n.Val
   142  			key = key[len(n.Key):]
   143  		case *fullNode:
   144  			tn = n.Children[key[0]]
   145  			key = key[1:]
   146  		case hashNode:
   147  			return key, n
   148  		case nil:
   149  			return key, nil
   150  		case valueNode:
   151  			return nil, n
   152  		default:
   153  			panic(fmt.Sprintf("%T: invalid node: %v", tn, tn))
   154  		}
   155  	}
   156  }