gitlab.com/flarenetwork/coreth@v0.1.1/core/state/database.go (about)

     1  // (c) 2019-2020, Ava Labs, Inc.
     2  //
     3  // This file is a derived work, based on the go-ethereum library whose original
     4  // notices appear below.
     5  //
     6  // It is distributed under a license compatible with the licensing terms of the
     7  // original code from which it is derived.
     8  //
     9  // Much love to the original authors for their work.
    10  // **********
    11  // Copyright 2017 The go-ethereum Authors
    12  // This file is part of the go-ethereum library.
    13  //
    14  // The go-ethereum library is free software: you can redistribute it and/or modify
    15  // it under the terms of the GNU Lesser General Public License as published by
    16  // the Free Software Foundation, either version 3 of the License, or
    17  // (at your option) any later version.
    18  //
    19  // The go-ethereum library is distributed in the hope that it will be useful,
    20  // but WITHOUT ANY WARRANTY; without even the implied warranty of
    21  // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
    22  // GNU Lesser General Public License for more details.
    23  //
    24  // You should have received a copy of the GNU Lesser General Public License
    25  // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
    26  
    27  package state
    28  
    29  import (
    30  	"errors"
    31  	"fmt"
    32  
    33  	"github.com/VictoriaMetrics/fastcache"
    34  	"github.com/ethereum/go-ethereum/common"
    35  	"github.com/ethereum/go-ethereum/ethdb"
    36  	"github.com/ethereum/go-ethereum/trie"
    37  	lru "github.com/hashicorp/golang-lru"
    38  	"gitlab.com/flarenetwork/coreth/core/rawdb"
    39  )
    40  
    41  const (
    42  	// Number of codehash->size associations to keep.
    43  	codeSizeCacheSize = 100000
    44  
    45  	// Cache size granted for caching clean code.
    46  	codeCacheSize = 64 * 1024 * 1024
    47  )
    48  
    49  // Database wraps access to tries and contract code.
    50  type Database interface {
    51  	// OpenTrie opens the main account trie.
    52  	OpenTrie(root common.Hash) (Trie, error)
    53  
    54  	// OpenStorageTrie opens the storage trie of an account.
    55  	OpenStorageTrie(addrHash, root common.Hash) (Trie, error)
    56  
    57  	// CopyTrie returns an independent copy of the given trie.
    58  	CopyTrie(Trie) Trie
    59  
    60  	// ContractCode retrieves a particular contract's code.
    61  	ContractCode(addrHash, codeHash common.Hash) ([]byte, error)
    62  
    63  	// ContractCodeSize retrieves a particular contracts code's size.
    64  	ContractCodeSize(addrHash, codeHash common.Hash) (int, error)
    65  
    66  	// TrieDB retrieves the low level trie database used for data storage.
    67  	TrieDB() *trie.Database
    68  }
    69  
    70  // Trie is a Ethereum Merkle Patricia trie.
    71  type Trie interface {
    72  	// GetKey returns the sha3 preimage of a hashed key that was previously used
    73  	// to store a value.
    74  	//
    75  	// TODO(fjl): remove this when SecureTrie is removed
    76  	GetKey([]byte) []byte
    77  
    78  	// TryGet returns the value for key stored in the trie. The value bytes must
    79  	// not be modified by the caller. If a node was not found in the database, a
    80  	// trie.MissingNodeError is returned.
    81  	TryGet(key []byte) ([]byte, error)
    82  
    83  	// TryUpdate associates key with value in the trie. If value has length zero, any
    84  	// existing value is deleted from the trie. The value bytes must not be modified
    85  	// by the caller while they are stored in the trie. If a node was not found in the
    86  	// database, a trie.MissingNodeError is returned.
    87  	TryUpdate(key, value []byte) error
    88  
    89  	// TryDelete removes any existing value for key from the trie. If a node was not
    90  	// found in the database, a trie.MissingNodeError is returned.
    91  	TryDelete(key []byte) error
    92  
    93  	// Hash returns the root hash of the trie. It does not write to the database and
    94  	// can be used even if the trie doesn't have one.
    95  	Hash() common.Hash
    96  
    97  	// Commit writes all nodes to the trie's memory database, tracking the internal
    98  	// and external (for account tries) references.
    99  	Commit(onleaf trie.LeafCallback) (common.Hash, error)
   100  
   101  	// NodeIterator returns an iterator that returns nodes of the trie. Iteration
   102  	// starts at the key after the given start key.
   103  	NodeIterator(startKey []byte) trie.NodeIterator
   104  
   105  	// Prove constructs a Merkle proof for key. The result contains all encoded nodes
   106  	// on the path to the value at key. The value itself is also included in the last
   107  	// node and can be retrieved by verifying the proof.
   108  	//
   109  	// If the trie does not contain a value for key, the returned proof contains all
   110  	// nodes of the longest existing prefix of the key (at least the root), ending
   111  	// with the node that proves the absence of the key.
   112  	Prove(key []byte, fromLevel uint, proofDb ethdb.KeyValueWriter) error
   113  }
   114  
   115  // NewDatabase creates a backing store for state. The returned database is safe for
   116  // concurrent use, but does not retain any recent trie nodes in memory. To keep some
   117  // historical state in memory, use the NewDatabaseWithConfig constructor.
   118  func NewDatabase(db ethdb.Database) Database {
   119  	return NewDatabaseWithConfig(db, nil)
   120  }
   121  
   122  // NewDatabaseWithConfig creates a backing store for state. The returned database
   123  // is safe for concurrent use and retains a lot of collapsed RLP trie nodes in a
   124  // large memory cache.
   125  func NewDatabaseWithConfig(db ethdb.Database, config *trie.Config) Database {
   126  	csc, _ := lru.New(codeSizeCacheSize)
   127  	return &cachingDB{
   128  		db:            trie.NewDatabaseWithConfig(db, config),
   129  		codeSizeCache: csc,
   130  		codeCache:     fastcache.New(codeCacheSize),
   131  	}
   132  }
   133  
   134  type cachingDB struct {
   135  	db            *trie.Database
   136  	codeSizeCache *lru.Cache
   137  	codeCache     *fastcache.Cache
   138  }
   139  
   140  // OpenTrie opens the main account trie at a specific root hash.
   141  func (db *cachingDB) OpenTrie(root common.Hash) (Trie, error) {
   142  	tr, err := trie.NewSecure(root, db.db)
   143  	if err != nil {
   144  		return nil, err
   145  	}
   146  	return tr, nil
   147  }
   148  
   149  // OpenStorageTrie opens the storage trie of an account.
   150  func (db *cachingDB) OpenStorageTrie(addrHash, root common.Hash) (Trie, error) {
   151  	tr, err := trie.NewSecure(root, db.db)
   152  	if err != nil {
   153  		return nil, err
   154  	}
   155  	return tr, nil
   156  }
   157  
   158  // CopyTrie returns an independent copy of the given trie.
   159  func (db *cachingDB) CopyTrie(t Trie) Trie {
   160  	switch t := t.(type) {
   161  	case *trie.SecureTrie:
   162  		return t.Copy()
   163  	default:
   164  		panic(fmt.Errorf("unknown trie type %T", t))
   165  	}
   166  }
   167  
   168  // ContractCode retrieves a particular contract's code.
   169  func (db *cachingDB) ContractCode(addrHash, codeHash common.Hash) ([]byte, error) {
   170  	if code := db.codeCache.Get(nil, codeHash.Bytes()); len(code) > 0 {
   171  		return code, nil
   172  	}
   173  	code := rawdb.ReadCode(db.db.DiskDB(), codeHash)
   174  	if len(code) > 0 {
   175  		db.codeCache.Set(codeHash.Bytes(), code)
   176  		db.codeSizeCache.Add(codeHash, len(code))
   177  		return code, nil
   178  	}
   179  	return nil, errors.New("not found")
   180  }
   181  
   182  // ContractCodeWithPrefix retrieves a particular contract's code. If the
   183  // code can't be found in the cache, then check the existence with **new**
   184  // db scheme.
   185  func (db *cachingDB) ContractCodeWithPrefix(addrHash, codeHash common.Hash) ([]byte, error) {
   186  	if code := db.codeCache.Get(nil, codeHash.Bytes()); len(code) > 0 {
   187  		return code, nil
   188  	}
   189  	code := rawdb.ReadCodeWithPrefix(db.db.DiskDB(), codeHash)
   190  	if len(code) > 0 {
   191  		db.codeCache.Set(codeHash.Bytes(), code)
   192  		db.codeSizeCache.Add(codeHash, len(code))
   193  		return code, nil
   194  	}
   195  	return nil, errors.New("not found")
   196  }
   197  
   198  // ContractCodeSize retrieves a particular contracts code's size.
   199  func (db *cachingDB) ContractCodeSize(addrHash, codeHash common.Hash) (int, error) {
   200  	if cached, ok := db.codeSizeCache.Get(codeHash); ok {
   201  		return cached.(int), nil
   202  	}
   203  	code, err := db.ContractCode(addrHash, codeHash)
   204  	return len(code), err
   205  }
   206  
   207  // TrieDB retrieves any intermediate trie-node caching layer.
   208  func (db *cachingDB) TrieDB() *trie.Database {
   209  	return db.db
   210  }