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