github.com/codysnider/go-ethereum@v1.10.18-0.20220420071915-14f4ae99222a/light/trie.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 light
    18  
    19  import (
    20  	"context"
    21  	"errors"
    22  	"fmt"
    23  
    24  	"github.com/ethereum/go-ethereum/common"
    25  	"github.com/ethereum/go-ethereum/core/rawdb"
    26  	"github.com/ethereum/go-ethereum/core/state"
    27  	"github.com/ethereum/go-ethereum/core/types"
    28  	"github.com/ethereum/go-ethereum/crypto"
    29  	"github.com/ethereum/go-ethereum/ethdb"
    30  	"github.com/ethereum/go-ethereum/rlp"
    31  	"github.com/ethereum/go-ethereum/trie"
    32  )
    33  
    34  var (
    35  	sha3Nil = crypto.Keccak256Hash(nil)
    36  )
    37  
    38  func NewState(ctx context.Context, head *types.Header, odr OdrBackend) *state.StateDB {
    39  	state, _ := state.New(head.Root, NewStateDatabase(ctx, head, odr), nil)
    40  	return state
    41  }
    42  
    43  func NewStateDatabase(ctx context.Context, head *types.Header, odr OdrBackend) state.Database {
    44  	return &odrDatabase{ctx, StateTrieID(head), odr}
    45  }
    46  
    47  type odrDatabase struct {
    48  	ctx     context.Context
    49  	id      *TrieID
    50  	backend OdrBackend
    51  }
    52  
    53  func (db *odrDatabase) OpenTrie(root common.Hash) (state.Trie, error) {
    54  	return &odrTrie{db: db, id: db.id}, nil
    55  }
    56  
    57  func (db *odrDatabase) OpenStorageTrie(addrHash, root common.Hash) (state.Trie, error) {
    58  	return &odrTrie{db: db, id: StorageTrieID(db.id, addrHash, root)}, nil
    59  }
    60  
    61  func (db *odrDatabase) CopyTrie(t state.Trie) state.Trie {
    62  	switch t := t.(type) {
    63  	case *odrTrie:
    64  		cpy := &odrTrie{db: t.db, id: t.id}
    65  		if t.trie != nil {
    66  			cpytrie := *t.trie
    67  			cpy.trie = &cpytrie
    68  		}
    69  		return cpy
    70  	default:
    71  		panic(fmt.Errorf("unknown trie type %T", t))
    72  	}
    73  }
    74  
    75  func (db *odrDatabase) ContractCode(addrHash, codeHash common.Hash) ([]byte, error) {
    76  	if codeHash == sha3Nil {
    77  		return nil, nil
    78  	}
    79  	code := rawdb.ReadCode(db.backend.Database(), codeHash)
    80  	if len(code) != 0 {
    81  		return code, nil
    82  	}
    83  	id := *db.id
    84  	id.AccKey = addrHash[:]
    85  	req := &CodeRequest{Id: &id, Hash: codeHash}
    86  	err := db.backend.Retrieve(db.ctx, req)
    87  	return req.Data, err
    88  }
    89  
    90  func (db *odrDatabase) ContractCodeSize(addrHash, codeHash common.Hash) (int, error) {
    91  	code, err := db.ContractCode(addrHash, codeHash)
    92  	return len(code), err
    93  }
    94  
    95  func (db *odrDatabase) TrieDB() *trie.Database {
    96  	return nil
    97  }
    98  
    99  type odrTrie struct {
   100  	db   *odrDatabase
   101  	id   *TrieID
   102  	trie *trie.Trie
   103  }
   104  
   105  func (t *odrTrie) TryGet(key []byte) ([]byte, error) {
   106  	key = crypto.Keccak256(key)
   107  	var res []byte
   108  	err := t.do(key, func() (err error) {
   109  		res, err = t.trie.TryGet(key)
   110  		return err
   111  	})
   112  	return res, err
   113  }
   114  
   115  func (t *odrTrie) TryUpdateAccount(key []byte, acc *types.StateAccount) error {
   116  	key = crypto.Keccak256(key)
   117  	value, err := rlp.EncodeToBytes(acc)
   118  	if err != nil {
   119  		return fmt.Errorf("decoding error in account update: %w", err)
   120  	}
   121  	return t.do(key, func() error {
   122  		return t.trie.TryUpdate(key, value)
   123  	})
   124  }
   125  
   126  func (t *odrTrie) TryUpdate(key, value []byte) error {
   127  	key = crypto.Keccak256(key)
   128  	return t.do(key, func() error {
   129  		return t.trie.TryUpdate(key, value)
   130  	})
   131  }
   132  
   133  func (t *odrTrie) TryDelete(key []byte) error {
   134  	key = crypto.Keccak256(key)
   135  	return t.do(key, func() error {
   136  		return t.trie.TryDelete(key)
   137  	})
   138  }
   139  
   140  func (t *odrTrie) Commit(onleaf trie.LeafCallback) (common.Hash, int, error) {
   141  	if t.trie == nil {
   142  		return t.id.Root, 0, nil
   143  	}
   144  	return t.trie.Commit(onleaf)
   145  }
   146  
   147  func (t *odrTrie) Hash() common.Hash {
   148  	if t.trie == nil {
   149  		return t.id.Root
   150  	}
   151  	return t.trie.Hash()
   152  }
   153  
   154  func (t *odrTrie) NodeIterator(startkey []byte) trie.NodeIterator {
   155  	return newNodeIterator(t, startkey)
   156  }
   157  
   158  func (t *odrTrie) GetKey(sha []byte) []byte {
   159  	return nil
   160  }
   161  
   162  func (t *odrTrie) Prove(key []byte, fromLevel uint, proofDb ethdb.KeyValueWriter) error {
   163  	return errors.New("not implemented, needs client/server interface split")
   164  }
   165  
   166  // do tries and retries to execute a function until it returns with no error or
   167  // an error type other than MissingNodeError
   168  func (t *odrTrie) do(key []byte, fn func() error) error {
   169  	for {
   170  		var err error
   171  		if t.trie == nil {
   172  			t.trie, err = trie.New(t.id.Root, trie.NewDatabase(t.db.backend.Database()))
   173  		}
   174  		if err == nil {
   175  			err = fn()
   176  		}
   177  		if _, ok := err.(*trie.MissingNodeError); !ok {
   178  			return err
   179  		}
   180  		r := &TrieRequest{Id: t.id, Key: key}
   181  		if err := t.db.backend.Retrieve(t.db.ctx, r); err != nil {
   182  			return err
   183  		}
   184  	}
   185  }
   186  
   187  type nodeIterator struct {
   188  	trie.NodeIterator
   189  	t   *odrTrie
   190  	err error
   191  }
   192  
   193  func newNodeIterator(t *odrTrie, startkey []byte) trie.NodeIterator {
   194  	it := &nodeIterator{t: t}
   195  	// Open the actual non-ODR trie if that hasn't happened yet.
   196  	if t.trie == nil {
   197  		it.do(func() error {
   198  			t, err := trie.New(t.id.Root, trie.NewDatabase(t.db.backend.Database()))
   199  			if err == nil {
   200  				it.t.trie = t
   201  			}
   202  			return err
   203  		})
   204  	}
   205  	it.do(func() error {
   206  		it.NodeIterator = it.t.trie.NodeIterator(startkey)
   207  		return it.NodeIterator.Error()
   208  	})
   209  	return it
   210  }
   211  
   212  func (it *nodeIterator) Next(descend bool) bool {
   213  	var ok bool
   214  	it.do(func() error {
   215  		ok = it.NodeIterator.Next(descend)
   216  		return it.NodeIterator.Error()
   217  	})
   218  	return ok
   219  }
   220  
   221  // do runs fn and attempts to fill in missing nodes by retrieving.
   222  func (it *nodeIterator) do(fn func() error) {
   223  	var lasthash common.Hash
   224  	for {
   225  		it.err = fn()
   226  		missing, ok := it.err.(*trie.MissingNodeError)
   227  		if !ok {
   228  			return
   229  		}
   230  		if missing.NodeHash == lasthash {
   231  			it.err = fmt.Errorf("retrieve loop for trie node %x", missing.NodeHash)
   232  			return
   233  		}
   234  		lasthash = missing.NodeHash
   235  		r := &TrieRequest{Id: it.t.id, Key: nibblesToKey(missing.Path)}
   236  		if it.err = it.t.db.backend.Retrieve(it.t.db.ctx, r); it.err != nil {
   237  			return
   238  		}
   239  	}
   240  }
   241  
   242  func (it *nodeIterator) Error() error {
   243  	if it.err != nil {
   244  		return it.err
   245  	}
   246  	return it.NodeIterator.Error()
   247  }
   248  
   249  func nibblesToKey(nib []byte) []byte {
   250  	if len(nib) > 0 && nib[len(nib)-1] == 0x10 {
   251  		nib = nib[:len(nib)-1] // drop terminator
   252  	}
   253  	if len(nib)&1 == 1 {
   254  		nib = append(nib, 0) // make even
   255  	}
   256  	key := make([]byte, len(nib)/2)
   257  	for bi, ni := 0, 0; ni < len(nib); bi, ni = bi+1, ni+2 {
   258  		key[bi] = nib[ni]<<4 | nib[ni+1]
   259  	}
   260  	return key
   261  }