github.com/core-coin/go-core/v2@v2.1.9/light/trie.go (about)

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