github.com/sberex/go-sberex@v1.8.2-0.20181113200658-ed96ac38f7d7/trie/proof.go (about)

     1  // This file is part of the go-sberex library. The go-sberex library is 
     2  // free software: you can redistribute it and/or modify it under the terms 
     3  // of the GNU Lesser General Public License as published by the Free 
     4  // Software Foundation, either version 3 of the License, or (at your option)
     5  // any later version.
     6  //
     7  // The go-sberex library is distributed in the hope that it will be useful, 
     8  // but WITHOUT ANY WARRANTY; without even the implied warranty of
     9  // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser 
    10  // General Public License <http://www.gnu.org/licenses/> for more details.
    11  
    12  package trie
    13  
    14  import (
    15  	"bytes"
    16  	"fmt"
    17  
    18  	"github.com/Sberex/go-sberex/common"
    19  	"github.com/Sberex/go-sberex/crypto"
    20  	"github.com/Sberex/go-sberex/ethdb"
    21  	"github.com/Sberex/go-sberex/log"
    22  	"github.com/Sberex/go-sberex/rlp"
    23  )
    24  
    25  // Prove constructs a merkle proof for key. The result contains all encoded nodes
    26  // on the path to the value at key. The value itself is also included in the last
    27  // node and can be retrieved by verifying the proof.
    28  //
    29  // If the trie does not contain a value for key, the returned proof contains all
    30  // nodes of the longest existing prefix of the key (at least the root node), ending
    31  // with the node that proves the absence of the key.
    32  func (t *Trie) Prove(key []byte, fromLevel uint, proofDb ethdb.Putter) error {
    33  	// Collect all nodes on the path to key.
    34  	key = keybytesToHex(key)
    35  	nodes := []node{}
    36  	tn := t.root
    37  	for len(key) > 0 && tn != nil {
    38  		switch n := tn.(type) {
    39  		case *shortNode:
    40  			if len(key) < len(n.Key) || !bytes.Equal(n.Key, key[:len(n.Key)]) {
    41  				// The trie doesn't contain the key.
    42  				tn = nil
    43  			} else {
    44  				tn = n.Val
    45  				key = key[len(n.Key):]
    46  			}
    47  			nodes = append(nodes, n)
    48  		case *fullNode:
    49  			tn = n.Children[key[0]]
    50  			key = key[1:]
    51  			nodes = append(nodes, n)
    52  		case hashNode:
    53  			var err error
    54  			tn, err = t.resolveHash(n, nil)
    55  			if err != nil {
    56  				log.Error(fmt.Sprintf("Unhandled trie error: %v", err))
    57  				return err
    58  			}
    59  		default:
    60  			panic(fmt.Sprintf("%T: invalid node: %v", tn, tn))
    61  		}
    62  	}
    63  	hasher := newHasher(0, 0, nil)
    64  	for i, n := range nodes {
    65  		// Don't bother checking for errors here since hasher panics
    66  		// if encoding doesn't work and we're not writing to any database.
    67  		n, _, _ = hasher.hashChildren(n, nil)
    68  		hn, _ := hasher.store(n, nil, false)
    69  		if hash, ok := hn.(hashNode); ok || i == 0 {
    70  			// If the node's database encoding is a hash (or is the
    71  			// root node), it becomes a proof element.
    72  			if fromLevel > 0 {
    73  				fromLevel--
    74  			} else {
    75  				enc, _ := rlp.EncodeToBytes(n)
    76  				if !ok {
    77  					hash = crypto.Keccak256(enc)
    78  				}
    79  				proofDb.Put(hash, enc)
    80  			}
    81  		}
    82  	}
    83  	return nil
    84  }
    85  
    86  // Prove constructs a merkle proof for key. The result contains all encoded nodes
    87  // on the path to the value at key. The value itself is also included in the last
    88  // node and can be retrieved by verifying the proof.
    89  //
    90  // If the trie does not contain a value for key, the returned proof contains all
    91  // nodes of the longest existing prefix of the key (at least the root node), ending
    92  // with the node that proves the absence of the key.
    93  func (t *SecureTrie) Prove(key []byte, fromLevel uint, proofDb ethdb.Putter) error {
    94  	return t.trie.Prove(key, fromLevel, proofDb)
    95  }
    96  
    97  // VerifyProof checks merkle proofs. The given proof must contain the value for
    98  // key in a trie with the given root hash. VerifyProof returns an error if the
    99  // proof contains invalid trie nodes or the wrong value.
   100  func VerifyProof(rootHash common.Hash, key []byte, proofDb DatabaseReader) (value []byte, err error, nodes int) {
   101  	key = keybytesToHex(key)
   102  	wantHash := rootHash
   103  	for i := 0; ; i++ {
   104  		buf, _ := proofDb.Get(wantHash[:])
   105  		if buf == nil {
   106  			return nil, fmt.Errorf("proof node %d (hash %064x) missing", i, wantHash), i
   107  		}
   108  		n, err := decodeNode(wantHash[:], buf, 0)
   109  		if err != nil {
   110  			return nil, fmt.Errorf("bad proof node %d: %v", i, err), i
   111  		}
   112  		keyrest, cld := get(n, key)
   113  		switch cld := cld.(type) {
   114  		case nil:
   115  			// The trie doesn't contain the key.
   116  			return nil, nil, i
   117  		case hashNode:
   118  			key = keyrest
   119  			copy(wantHash[:], cld)
   120  		case valueNode:
   121  			return cld, nil, i + 1
   122  		}
   123  	}
   124  }
   125  
   126  func get(tn node, key []byte) ([]byte, node) {
   127  	for {
   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.Children[key[0]]
   137  			key = key[1:]
   138  		case hashNode:
   139  			return key, n
   140  		case nil:
   141  			return key, nil
   142  		case valueNode:
   143  			return nil, n
   144  		default:
   145  			panic(fmt.Sprintf("%T: invalid node: %v", tn, tn))
   146  		}
   147  	}
   148  }