github.com/theQRL/go-zond@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/theQRL/go-zond/common"
    25  	"github.com/theQRL/go-zond/core/rawdb"
    26  	"github.com/theQRL/go-zond/core/state"
    27  	"github.com/theQRL/go-zond/core/types"
    28  	"github.com/theQRL/go-zond/crypto"
    29  	"github.com/theQRL/go-zond/zonddb"
    30  	"github.com/theQRL/go-zond/rlp"
    31  	"github.com/theQRL/go-zond/trie"
    32  	"github.com/theQRL/go-zond/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(stateRoot common.Hash, address common.Address, root common.Hash) (state.Trie, error) {
    59  	return &odrTrie{db: db, id: StorageTrieID(db.id, address, 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(addr common.Address, 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.AccountAddress = addr[:]
    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(addr common.Address, codeHash common.Hash) (int, error) {
    91  	code, err := db.ContractCode(addr, 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() zonddb.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 enc []byte
   112  	err := t.do(key, func() (err error) {
   113  		enc, err = t.trie.Get(key)
   114  		return err
   115  	})
   116  	if err != nil || len(enc) == 0 {
   117  		return nil, err
   118  	}
   119  	_, content, _, err := rlp.Split(enc)
   120  	return content, err
   121  }
   122  
   123  func (t *odrTrie) GetAccount(address common.Address) (*types.StateAccount, error) {
   124  	var (
   125  		enc []byte
   126  		key = crypto.Keccak256(address.Bytes())
   127  	)
   128  	err := t.do(key, func() (err error) {
   129  		enc, err = t.trie.Get(key)
   130  		return err
   131  	})
   132  	if err != nil || len(enc) == 0 {
   133  		return nil, err
   134  	}
   135  	acct := new(types.StateAccount)
   136  	if err := rlp.DecodeBytes(enc, acct); err != nil {
   137  		return nil, err
   138  	}
   139  	return acct, nil
   140  }
   141  
   142  func (t *odrTrie) UpdateAccount(address common.Address, acc *types.StateAccount) error {
   143  	key := crypto.Keccak256(address.Bytes())
   144  	value, err := rlp.EncodeToBytes(acc)
   145  	if err != nil {
   146  		return fmt.Errorf("decoding error in account update: %w", err)
   147  	}
   148  	return t.do(key, func() error {
   149  		return t.trie.Update(key, value)
   150  	})
   151  }
   152  
   153  func (t *odrTrie) UpdateContractCode(_ common.Address, _ common.Hash, _ []byte) error {
   154  	return nil
   155  }
   156  
   157  func (t *odrTrie) UpdateStorage(_ common.Address, key, value []byte) error {
   158  	key = crypto.Keccak256(key)
   159  	v, _ := rlp.EncodeToBytes(value)
   160  	return t.do(key, func() error {
   161  		return t.trie.Update(key, v)
   162  	})
   163  }
   164  
   165  func (t *odrTrie) DeleteStorage(_ common.Address, key []byte) error {
   166  	key = crypto.Keccak256(key)
   167  	return t.do(key, func() error {
   168  		return t.trie.Delete(key)
   169  	})
   170  }
   171  
   172  // DeleteAccount abstracts an account deletion from the trie.
   173  func (t *odrTrie) DeleteAccount(address common.Address) error {
   174  	key := crypto.Keccak256(address.Bytes())
   175  	return t.do(key, func() error {
   176  		return t.trie.Delete(key)
   177  	})
   178  }
   179  
   180  func (t *odrTrie) Commit(collectLeaf bool) (common.Hash, *trienode.NodeSet, error) {
   181  	if t.trie == nil {
   182  		return t.id.Root, nil, nil
   183  	}
   184  	return t.trie.Commit(collectLeaf)
   185  }
   186  
   187  func (t *odrTrie) Hash() common.Hash {
   188  	if t.trie == nil {
   189  		return t.id.Root
   190  	}
   191  	return t.trie.Hash()
   192  }
   193  
   194  func (t *odrTrie) NodeIterator(startkey []byte) (trie.NodeIterator, error) {
   195  	return newNodeIterator(t, startkey), nil
   196  }
   197  
   198  func (t *odrTrie) GetKey(sha []byte) []byte {
   199  	return nil
   200  }
   201  
   202  func (t *odrTrie) Prove(key []byte, proofDb zonddb.KeyValueWriter) error {
   203  	return errors.New("not implemented, needs client/server interface split")
   204  }
   205  
   206  // do tries and retries to execute a function until it returns with no error or
   207  // an error type other than MissingNodeError
   208  func (t *odrTrie) do(key []byte, fn func() error) error {
   209  	for {
   210  		var err error
   211  		if t.trie == nil {
   212  			var id *trie.ID
   213  			if len(t.id.AccountAddress) > 0 {
   214  				id = trie.StorageTrieID(t.id.StateRoot, crypto.Keccak256Hash(t.id.AccountAddress), t.id.Root)
   215  			} else {
   216  				id = trie.StateTrieID(t.id.StateRoot)
   217  			}
   218  			triedb := trie.NewDatabase(t.db.backend.Database(), trie.HashDefaults)
   219  			t.trie, err = trie.New(id, triedb)
   220  		}
   221  		if err == nil {
   222  			err = fn()
   223  		}
   224  		if _, ok := err.(*trie.MissingNodeError); !ok {
   225  			return err
   226  		}
   227  		r := &TrieRequest{Id: t.id, Key: key}
   228  		if err := t.db.backend.Retrieve(t.db.ctx, r); err != nil {
   229  			return err
   230  		}
   231  	}
   232  }
   233  
   234  type nodeIterator struct {
   235  	trie.NodeIterator
   236  	t   *odrTrie
   237  	err error
   238  }
   239  
   240  func newNodeIterator(t *odrTrie, startkey []byte) trie.NodeIterator {
   241  	it := &nodeIterator{t: t}
   242  	// Open the actual non-ODR trie if that hasn't happened yet.
   243  	if t.trie == nil {
   244  		it.do(func() error {
   245  			var id *trie.ID
   246  			if len(t.id.AccountAddress) > 0 {
   247  				id = trie.StorageTrieID(t.id.StateRoot, crypto.Keccak256Hash(t.id.AccountAddress), t.id.Root)
   248  			} else {
   249  				id = trie.StateTrieID(t.id.StateRoot)
   250  			}
   251  			triedb := trie.NewDatabase(t.db.backend.Database(), trie.HashDefaults)
   252  			t, err := trie.New(id, triedb)
   253  			if err == nil {
   254  				it.t.trie = t
   255  			}
   256  			return err
   257  		})
   258  	}
   259  	it.do(func() error {
   260  		var err error
   261  		it.NodeIterator, err = it.t.trie.NodeIterator(startkey)
   262  		if err != nil {
   263  			return err
   264  		}
   265  		return it.NodeIterator.Error()
   266  	})
   267  	return it
   268  }
   269  
   270  func (it *nodeIterator) Next(descend bool) bool {
   271  	var ok bool
   272  	it.do(func() error {
   273  		ok = it.NodeIterator.Next(descend)
   274  		return it.NodeIterator.Error()
   275  	})
   276  	return ok
   277  }
   278  
   279  // do runs fn and attempts to fill in missing nodes by retrieving.
   280  func (it *nodeIterator) do(fn func() error) {
   281  	var lasthash common.Hash
   282  	for {
   283  		it.err = fn()
   284  		missing, ok := it.err.(*trie.MissingNodeError)
   285  		if !ok {
   286  			return
   287  		}
   288  		if missing.NodeHash == lasthash {
   289  			it.err = fmt.Errorf("retrieve loop for trie node %x", missing.NodeHash)
   290  			return
   291  		}
   292  		lasthash = missing.NodeHash
   293  		r := &TrieRequest{Id: it.t.id, Key: nibblesToKey(missing.Path)}
   294  		if it.err = it.t.db.backend.Retrieve(it.t.db.ctx, r); it.err != nil {
   295  			return
   296  		}
   297  	}
   298  }
   299  
   300  func (it *nodeIterator) Error() error {
   301  	if it.err != nil {
   302  		return it.err
   303  	}
   304  	return it.NodeIterator.Error()
   305  }
   306  
   307  func nibblesToKey(nib []byte) []byte {
   308  	if len(nib) > 0 && nib[len(nib)-1] == 0x10 {
   309  		nib = nib[:len(nib)-1] // drop terminator
   310  	}
   311  	if len(nib)&1 == 1 {
   312  		nib = append(nib, 0) // make even
   313  	}
   314  	key := make([]byte, len(nib)/2)
   315  	for bi, ni := 0, 0; ni < len(nib); bi, ni = bi+1, ni+2 {
   316  		key[bi] = nib[ni]<<4 | nib[ni+1]
   317  	}
   318  	return key
   319  }