github.com/aquanetwork/aquachain@v1.7.8/trie/proof.go (about)

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