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