github.com/jimmyx0x/go-ethereum@v1.10.28/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(state, 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  			cpy.trie = t.trie.Copy()
    67  		}
    68  		return cpy
    69  	default:
    70  		panic(fmt.Errorf("unknown trie type %T", t))
    71  	}
    72  }
    73  
    74  func (db *odrDatabase) ContractCode(addrHash, codeHash common.Hash) ([]byte, error) {
    75  	if codeHash == sha3Nil {
    76  		return nil, nil
    77  	}
    78  	code := rawdb.ReadCode(db.backend.Database(), codeHash)
    79  	if len(code) != 0 {
    80  		return code, nil
    81  	}
    82  	id := *db.id
    83  	id.AccKey = addrHash[:]
    84  	req := &CodeRequest{Id: &id, Hash: codeHash}
    85  	err := db.backend.Retrieve(db.ctx, req)
    86  	return req.Data, err
    87  }
    88  
    89  func (db *odrDatabase) ContractCodeSize(addrHash, codeHash common.Hash) (int, error) {
    90  	code, err := db.ContractCode(addrHash, codeHash)
    91  	return len(code), err
    92  }
    93  
    94  func (db *odrDatabase) TrieDB() *trie.Database {
    95  	return nil
    96  }
    97  
    98  func (db *odrDatabase) DiskDB() ethdb.KeyValueStore {
    99  	panic("not implemented")
   100  }
   101  
   102  type odrTrie struct {
   103  	db   *odrDatabase
   104  	id   *TrieID
   105  	trie *trie.Trie
   106  }
   107  
   108  func (t *odrTrie) TryGet(key []byte) ([]byte, error) {
   109  	key = crypto.Keccak256(key)
   110  	var res []byte
   111  	err := t.do(key, func() (err error) {
   112  		res, err = t.trie.TryGet(key)
   113  		return err
   114  	})
   115  	return res, err
   116  }
   117  
   118  func (t *odrTrie) TryGetAccount(address common.Address) (*types.StateAccount, error) {
   119  	var res types.StateAccount
   120  	key := crypto.Keccak256(address.Bytes())
   121  	err := t.do(key, func() (err error) {
   122  		value, err := t.trie.TryGet(key)
   123  		if err != nil {
   124  			return err
   125  		}
   126  		if value == nil {
   127  			return nil
   128  		}
   129  		return rlp.DecodeBytes(value, &res)
   130  	})
   131  	return &res, err
   132  }
   133  
   134  func (t *odrTrie) TryUpdateAccount(address common.Address, acc *types.StateAccount) error {
   135  	key := crypto.Keccak256(address.Bytes())
   136  	value, err := rlp.EncodeToBytes(acc)
   137  	if err != nil {
   138  		return fmt.Errorf("decoding error in account update: %w", err)
   139  	}
   140  	return t.do(key, func() error {
   141  		return t.trie.TryUpdate(key, value)
   142  	})
   143  }
   144  
   145  func (t *odrTrie) TryUpdate(key, value []byte) error {
   146  	key = crypto.Keccak256(key)
   147  	return t.do(key, func() error {
   148  		return t.trie.TryUpdate(key, value)
   149  	})
   150  }
   151  
   152  func (t *odrTrie) TryDelete(key []byte) error {
   153  	key = crypto.Keccak256(key)
   154  	return t.do(key, func() error {
   155  		return t.trie.TryDelete(key)
   156  	})
   157  }
   158  
   159  // TryDeleteAccount abstracts an account deletion from the trie.
   160  func (t *odrTrie) TryDeleteAccount(address common.Address) error {
   161  	key := crypto.Keccak256(address.Bytes())
   162  	return t.do(key, func() error {
   163  		return t.trie.TryDelete(key)
   164  	})
   165  }
   166  
   167  func (t *odrTrie) Commit(collectLeaf bool) (common.Hash, *trie.NodeSet, error) {
   168  	if t.trie == nil {
   169  		return t.id.Root, nil, nil
   170  	}
   171  	return t.trie.Commit(collectLeaf)
   172  }
   173  
   174  func (t *odrTrie) Hash() common.Hash {
   175  	if t.trie == nil {
   176  		return t.id.Root
   177  	}
   178  	return t.trie.Hash()
   179  }
   180  
   181  func (t *odrTrie) NodeIterator(startkey []byte) trie.NodeIterator {
   182  	return newNodeIterator(t, startkey)
   183  }
   184  
   185  func (t *odrTrie) GetKey(sha []byte) []byte {
   186  	return nil
   187  }
   188  
   189  func (t *odrTrie) Prove(key []byte, fromLevel uint, proofDb ethdb.KeyValueWriter) error {
   190  	return errors.New("not implemented, needs client/server interface split")
   191  }
   192  
   193  // do tries and retries to execute a function until it returns with no error or
   194  // an error type other than MissingNodeError
   195  func (t *odrTrie) do(key []byte, fn func() error) error {
   196  	for {
   197  		var err error
   198  		if t.trie == nil {
   199  			var id *trie.ID
   200  			if len(t.id.AccKey) > 0 {
   201  				id = trie.StorageTrieID(t.id.StateRoot, common.BytesToHash(t.id.AccKey), t.id.Root)
   202  			} else {
   203  				id = trie.StateTrieID(t.id.StateRoot)
   204  			}
   205  			t.trie, err = trie.New(id, trie.NewDatabase(t.db.backend.Database()))
   206  		}
   207  		if err == nil {
   208  			err = fn()
   209  		}
   210  		if _, ok := err.(*trie.MissingNodeError); !ok {
   211  			return err
   212  		}
   213  		r := &TrieRequest{Id: t.id, Key: key}
   214  		if err := t.db.backend.Retrieve(t.db.ctx, r); err != nil {
   215  			return err
   216  		}
   217  	}
   218  }
   219  
   220  type nodeIterator struct {
   221  	trie.NodeIterator
   222  	t   *odrTrie
   223  	err error
   224  }
   225  
   226  func newNodeIterator(t *odrTrie, startkey []byte) trie.NodeIterator {
   227  	it := &nodeIterator{t: t}
   228  	// Open the actual non-ODR trie if that hasn't happened yet.
   229  	if t.trie == nil {
   230  		it.do(func() error {
   231  			var id *trie.ID
   232  			if len(t.id.AccKey) > 0 {
   233  				id = trie.StorageTrieID(t.id.StateRoot, common.BytesToHash(t.id.AccKey), t.id.Root)
   234  			} else {
   235  				id = trie.StateTrieID(t.id.StateRoot)
   236  			}
   237  			t, err := trie.New(id, trie.NewDatabase(t.db.backend.Database()))
   238  			if err == nil {
   239  				it.t.trie = t
   240  			}
   241  			return err
   242  		})
   243  	}
   244  	it.do(func() error {
   245  		it.NodeIterator = it.t.trie.NodeIterator(startkey)
   246  		return it.NodeIterator.Error()
   247  	})
   248  	return it
   249  }
   250  
   251  func (it *nodeIterator) Next(descend bool) bool {
   252  	var ok bool
   253  	it.do(func() error {
   254  		ok = it.NodeIterator.Next(descend)
   255  		return it.NodeIterator.Error()
   256  	})
   257  	return ok
   258  }
   259  
   260  // do runs fn and attempts to fill in missing nodes by retrieving.
   261  func (it *nodeIterator) do(fn func() error) {
   262  	var lasthash common.Hash
   263  	for {
   264  		it.err = fn()
   265  		missing, ok := it.err.(*trie.MissingNodeError)
   266  		if !ok {
   267  			return
   268  		}
   269  		if missing.NodeHash == lasthash {
   270  			it.err = fmt.Errorf("retrieve loop for trie node %x", missing.NodeHash)
   271  			return
   272  		}
   273  		lasthash = missing.NodeHash
   274  		r := &TrieRequest{Id: it.t.id, Key: nibblesToKey(missing.Path)}
   275  		if it.err = it.t.db.backend.Retrieve(it.t.db.ctx, r); it.err != nil {
   276  			return
   277  		}
   278  	}
   279  }
   280  
   281  func (it *nodeIterator) Error() error {
   282  	if it.err != nil {
   283  		return it.err
   284  	}
   285  	return it.NodeIterator.Error()
   286  }
   287  
   288  func nibblesToKey(nib []byte) []byte {
   289  	if len(nib) > 0 && nib[len(nib)-1] == 0x10 {
   290  		nib = nib[:len(nib)-1] // drop terminator
   291  	}
   292  	if len(nib)&1 == 1 {
   293  		nib = append(nib, 0) // make even
   294  	}
   295  	key := make([]byte, len(nib)/2)
   296  	for bi, ni := 0, 0; ni < len(nib); bi, ni = bi+1, ni+2 {
   297  		key[bi] = nib[ni]<<4 | nib[ni+1]
   298  	}
   299  	return key
   300  }