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