github.com/MikyChow/arbitrum-go-ethereum@v0.0.0-20230306102812-078da49636de/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/MikyChow/arbitrum-go-ethereum/common"
    25  	"github.com/MikyChow/arbitrum-go-ethereum/core/rawdb"
    26  	"github.com/MikyChow/arbitrum-go-ethereum/core/state"
    27  	"github.com/MikyChow/arbitrum-go-ethereum/core/types"
    28  	"github.com/MikyChow/arbitrum-go-ethereum/crypto"
    29  	"github.com/MikyChow/arbitrum-go-ethereum/ethdb"
    30  	"github.com/MikyChow/arbitrum-go-ethereum/rlp"
    31  	"github.com/MikyChow/arbitrum-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) TryGetAccount(key []byte) (*types.StateAccount, error) {
   116  	key = crypto.Keccak256(key)
   117  	var res types.StateAccount
   118  	err := t.do(key, func() (err error) {
   119  		value, err := t.trie.TryGet(key)
   120  		if err != nil {
   121  			return err
   122  		}
   123  		if value == nil {
   124  			return nil
   125  		}
   126  		return rlp.DecodeBytes(value, &res)
   127  	})
   128  	return &res, err
   129  }
   130  
   131  func (t *odrTrie) TryUpdateAccount(key []byte, acc *types.StateAccount) error {
   132  	key = crypto.Keccak256(key)
   133  	value, err := rlp.EncodeToBytes(acc)
   134  	if err != nil {
   135  		return fmt.Errorf("decoding error in account update: %w", err)
   136  	}
   137  	return t.do(key, func() error {
   138  		return t.trie.TryUpdate(key, value)
   139  	})
   140  }
   141  
   142  func (t *odrTrie) TryUpdate(key, value []byte) error {
   143  	key = crypto.Keccak256(key)
   144  	return t.do(key, func() error {
   145  		return t.trie.TryUpdate(key, value)
   146  	})
   147  }
   148  
   149  func (t *odrTrie) TryDelete(key []byte) error {
   150  	key = crypto.Keccak256(key)
   151  	return t.do(key, func() error {
   152  		return t.trie.TryDelete(key)
   153  	})
   154  }
   155  
   156  // TryDeleteAccount abstracts an account deletion from the trie.
   157  func (t *odrTrie) TryDeleteAccount(key []byte) error {
   158  	key = crypto.Keccak256(key)
   159  	return t.do(key, func() error {
   160  		return t.trie.TryDelete(key)
   161  	})
   162  }
   163  
   164  func (t *odrTrie) Commit(collectLeaf bool) (common.Hash, *trie.NodeSet, error) {
   165  	if t.trie == nil {
   166  		return t.id.Root, nil, nil
   167  	}
   168  	return t.trie.Commit(collectLeaf)
   169  }
   170  
   171  func (t *odrTrie) Hash() common.Hash {
   172  	if t.trie == nil {
   173  		return t.id.Root
   174  	}
   175  	return t.trie.Hash()
   176  }
   177  
   178  func (t *odrTrie) NodeIterator(startkey []byte) trie.NodeIterator {
   179  	return newNodeIterator(t, startkey)
   180  }
   181  
   182  func (t *odrTrie) GetKey(sha []byte) []byte {
   183  	return nil
   184  }
   185  
   186  func (t *odrTrie) Prove(key []byte, fromLevel uint, proofDb ethdb.KeyValueWriter) error {
   187  	return errors.New("not implemented, needs client/server interface split")
   188  }
   189  
   190  // do tries and retries to execute a function until it returns with no error or
   191  // an error type other than MissingNodeError
   192  func (t *odrTrie) do(key []byte, fn func() error) error {
   193  	for {
   194  		var err error
   195  		if t.trie == nil {
   196  			var owner common.Hash
   197  			if len(t.id.AccKey) > 0 {
   198  				owner = common.BytesToHash(t.id.AccKey)
   199  			}
   200  			t.trie, err = trie.New(owner, t.id.Root, trie.NewDatabase(t.db.backend.Database()))
   201  		}
   202  		if err == nil {
   203  			err = fn()
   204  		}
   205  		if _, ok := err.(*trie.MissingNodeError); !ok {
   206  			return err
   207  		}
   208  		r := &TrieRequest{Id: t.id, Key: key}
   209  		if err := t.db.backend.Retrieve(t.db.ctx, r); err != nil {
   210  			return err
   211  		}
   212  	}
   213  }
   214  
   215  type nodeIterator struct {
   216  	trie.NodeIterator
   217  	t   *odrTrie
   218  	err error
   219  }
   220  
   221  func newNodeIterator(t *odrTrie, startkey []byte) trie.NodeIterator {
   222  	it := &nodeIterator{t: t}
   223  	// Open the actual non-ODR trie if that hasn't happened yet.
   224  	if t.trie == nil {
   225  		it.do(func() error {
   226  			var owner common.Hash
   227  			if len(t.id.AccKey) > 0 {
   228  				owner = common.BytesToHash(t.id.AccKey)
   229  			}
   230  			t, err := trie.New(owner, t.id.Root, trie.NewDatabase(t.db.backend.Database()))
   231  			if err == nil {
   232  				it.t.trie = t
   233  			}
   234  			return err
   235  		})
   236  	}
   237  	it.do(func() error {
   238  		it.NodeIterator = it.t.trie.NodeIterator(startkey)
   239  		return it.NodeIterator.Error()
   240  	})
   241  	return it
   242  }
   243  
   244  func (it *nodeIterator) Next(descend bool) bool {
   245  	var ok bool
   246  	it.do(func() error {
   247  		ok = it.NodeIterator.Next(descend)
   248  		return it.NodeIterator.Error()
   249  	})
   250  	return ok
   251  }
   252  
   253  // do runs fn and attempts to fill in missing nodes by retrieving.
   254  func (it *nodeIterator) do(fn func() error) {
   255  	var lasthash common.Hash
   256  	for {
   257  		it.err = fn()
   258  		missing, ok := it.err.(*trie.MissingNodeError)
   259  		if !ok {
   260  			return
   261  		}
   262  		if missing.NodeHash == lasthash {
   263  			it.err = fmt.Errorf("retrieve loop for trie node %x", missing.NodeHash)
   264  			return
   265  		}
   266  		lasthash = missing.NodeHash
   267  		r := &TrieRequest{Id: it.t.id, Key: nibblesToKey(missing.Path)}
   268  		if it.err = it.t.db.backend.Retrieve(it.t.db.ctx, r); it.err != nil {
   269  			return
   270  		}
   271  	}
   272  }
   273  
   274  func (it *nodeIterator) Error() error {
   275  	if it.err != nil {
   276  		return it.err
   277  	}
   278  	return it.NodeIterator.Error()
   279  }
   280  
   281  func nibblesToKey(nib []byte) []byte {
   282  	if len(nib) > 0 && nib[len(nib)-1] == 0x10 {
   283  		nib = nib[:len(nib)-1] // drop terminator
   284  	}
   285  	if len(nib)&1 == 1 {
   286  		nib = append(nib, 0) // make even
   287  	}
   288  	key := make([]byte, len(nib)/2)
   289  	for bi, ni := 0, 0; ni < len(nib); bi, ni = bi+1, ni+2 {
   290  		key[bi] = nib[ni]<<4 | nib[ni+1]
   291  	}
   292  	return key
   293  }