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