github.com/phillinzzz/newBsc@v1.1.6/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/phillinzzz/newBsc/common"
    25  	"github.com/phillinzzz/newBsc/core/rawdb"
    26  	"github.com/phillinzzz/newBsc/core/state"
    27  	"github.com/phillinzzz/newBsc/core/types"
    28  	"github.com/phillinzzz/newBsc/crypto"
    29  	"github.com/phillinzzz/newBsc/ethdb"
    30  	"github.com/phillinzzz/newBsc/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  func (db *odrDatabase) CacheAccount(_ common.Hash, _ state.Trie) {}
    99  
   100  func (db *odrDatabase) CacheStorage(_ common.Hash, _ common.Hash, _ state.Trie) {}
   101  
   102  func (db *odrDatabase) Purge() {}
   103  
   104  type odrTrie struct {
   105  	db   *odrDatabase
   106  	id   *TrieID
   107  	trie *trie.Trie
   108  }
   109  
   110  func (t *odrTrie) TryGet(key []byte) ([]byte, error) {
   111  	key = crypto.Keccak256(key)
   112  	var res []byte
   113  	err := t.do(key, func() (err error) {
   114  		res, err = t.trie.TryGet(key)
   115  		return err
   116  	})
   117  	return res, err
   118  }
   119  
   120  func (t *odrTrie) TryUpdate(key, value []byte) error {
   121  	key = crypto.Keccak256(key)
   122  	return t.do(key, func() error {
   123  		return t.trie.TryUpdate(key, value)
   124  	})
   125  }
   126  
   127  func (t *odrTrie) TryDelete(key []byte) error {
   128  	key = crypto.Keccak256(key)
   129  	return t.do(key, func() error {
   130  		return t.trie.TryDelete(key)
   131  	})
   132  }
   133  
   134  func (t *odrTrie) Commit(onleaf trie.LeafCallback) (common.Hash, error) {
   135  	if t.trie == nil {
   136  		return t.id.Root, nil
   137  	}
   138  	return t.trie.Commit(onleaf)
   139  }
   140  
   141  func (t *odrTrie) Hash() common.Hash {
   142  	if t.trie == nil {
   143  		return t.id.Root
   144  	}
   145  	return t.trie.Hash()
   146  }
   147  
   148  func (t *odrTrie) NodeIterator(startkey []byte) trie.NodeIterator {
   149  	return newNodeIterator(t, startkey)
   150  }
   151  
   152  func (t *odrTrie) GetKey(sha []byte) []byte {
   153  	return nil
   154  }
   155  
   156  func (t *odrTrie) Prove(key []byte, fromLevel uint, proofDb ethdb.KeyValueWriter) error {
   157  	return errors.New("not implemented, needs client/server interface split")
   158  }
   159  
   160  // do tries and retries to execute a function until it returns with no error or
   161  // an error type other than MissingNodeError
   162  func (t *odrTrie) do(key []byte, fn func() error) error {
   163  	for {
   164  		var err error
   165  		if t.trie == nil {
   166  			t.trie, err = trie.New(t.id.Root, trie.NewDatabase(t.db.backend.Database()))
   167  		}
   168  		if err == nil {
   169  			err = fn()
   170  		}
   171  		if _, ok := err.(*trie.MissingNodeError); !ok {
   172  			return err
   173  		}
   174  		r := &TrieRequest{Id: t.id, Key: key}
   175  		if err := t.db.backend.Retrieve(t.db.ctx, r); err != nil {
   176  			return err
   177  		}
   178  	}
   179  }
   180  
   181  type nodeIterator struct {
   182  	trie.NodeIterator
   183  	t   *odrTrie
   184  	err error
   185  }
   186  
   187  func newNodeIterator(t *odrTrie, startkey []byte) trie.NodeIterator {
   188  	it := &nodeIterator{t: t}
   189  	// Open the actual non-ODR trie if that hasn't happened yet.
   190  	if t.trie == nil {
   191  		it.do(func() error {
   192  			t, err := trie.New(t.id.Root, trie.NewDatabase(t.db.backend.Database()))
   193  			if err == nil {
   194  				it.t.trie = t
   195  			}
   196  			return err
   197  		})
   198  	}
   199  	it.do(func() error {
   200  		it.NodeIterator = it.t.trie.NodeIterator(startkey)
   201  		return it.NodeIterator.Error()
   202  	})
   203  	return it
   204  }
   205  
   206  func (it *nodeIterator) Next(descend bool) bool {
   207  	var ok bool
   208  	it.do(func() error {
   209  		ok = it.NodeIterator.Next(descend)
   210  		return it.NodeIterator.Error()
   211  	})
   212  	return ok
   213  }
   214  
   215  // do runs fn and attempts to fill in missing nodes by retrieving.
   216  func (it *nodeIterator) do(fn func() error) {
   217  	var lasthash common.Hash
   218  	for {
   219  		it.err = fn()
   220  		missing, ok := it.err.(*trie.MissingNodeError)
   221  		if !ok {
   222  			return
   223  		}
   224  		if missing.NodeHash == lasthash {
   225  			it.err = fmt.Errorf("retrieve loop for trie node %x", missing.NodeHash)
   226  			return
   227  		}
   228  		lasthash = missing.NodeHash
   229  		r := &TrieRequest{Id: it.t.id, Key: nibblesToKey(missing.Path)}
   230  		if it.err = it.t.db.backend.Retrieve(it.t.db.ctx, r); it.err != nil {
   231  			return
   232  		}
   233  	}
   234  }
   235  
   236  func (it *nodeIterator) Error() error {
   237  	if it.err != nil {
   238  		return it.err
   239  	}
   240  	return it.NodeIterator.Error()
   241  }
   242  
   243  func nibblesToKey(nib []byte) []byte {
   244  	if len(nib) > 0 && nib[len(nib)-1] == 0x10 {
   245  		nib = nib[:len(nib)-1] // drop terminator
   246  	}
   247  	if len(nib)&1 == 1 {
   248  		nib = append(nib, 0) // make even
   249  	}
   250  	key := make([]byte, len(nib)/2)
   251  	for bi, ni := 0, 0; ni < len(nib); bi, ni = bi+1, ni+2 {
   252  		key[bi] = nib[ni]<<4 | nib[ni+1]
   253  	}
   254  	return key
   255  }