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