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