github.com/carter-ya/go-ethereum@v0.0.0-20230628080049-d2309be3983b/core/state/database.go (about)

     1  // Copyright 2017 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 state
    18  
    19  import (
    20  	"errors"
    21  	"fmt"
    22  
    23  	"github.com/VictoriaMetrics/fastcache"
    24  	"github.com/ethereum/go-ethereum/common"
    25  	"github.com/ethereum/go-ethereum/core/rawdb"
    26  	"github.com/ethereum/go-ethereum/core/types"
    27  	"github.com/ethereum/go-ethereum/ethdb"
    28  	"github.com/ethereum/go-ethereum/trie"
    29  	lru "github.com/hashicorp/golang-lru"
    30  )
    31  
    32  const (
    33  	// Number of codehash->size associations to keep.
    34  	codeSizeCacheSize = 100000
    35  
    36  	// Cache size granted for caching clean code.
    37  	codeCacheSize = 64 * 1024 * 1024
    38  )
    39  
    40  // Database wraps access to tries and contract code.
    41  type Database interface {
    42  	// OpenTrie opens the main account trie.
    43  	OpenTrie(root common.Hash) (Trie, error)
    44  
    45  	// OpenStorageTrie opens the storage trie of an account.
    46  	OpenStorageTrie(stateRoot common.Hash, addrHash, root common.Hash) (Trie, error)
    47  
    48  	// CopyTrie returns an independent copy of the given trie.
    49  	CopyTrie(Trie) Trie
    50  
    51  	// ContractCode retrieves a particular contract's code.
    52  	ContractCode(addrHash, codeHash common.Hash) ([]byte, error)
    53  
    54  	// ContractCodeSize retrieves a particular contracts code's size.
    55  	ContractCodeSize(addrHash, codeHash common.Hash) (int, error)
    56  
    57  	// DiskDB returns the underlying key-value disk database.
    58  	DiskDB() ethdb.KeyValueStore
    59  
    60  	// TrieDB retrieves the low level trie database used for data storage.
    61  	TrieDB() *trie.Database
    62  }
    63  
    64  // Trie is a Ethereum Merkle Patricia trie.
    65  type Trie interface {
    66  	// GetKey returns the sha3 preimage of a hashed key that was previously used
    67  	// to store a value.
    68  	//
    69  	// TODO(fjl): remove this when StateTrie is removed
    70  	GetKey([]byte) []byte
    71  
    72  	// TryGet returns the value for key stored in the trie. The value bytes must
    73  	// not be modified by the caller. If a node was not found in the database, a
    74  	// trie.MissingNodeError is returned.
    75  	TryGet(key []byte) ([]byte, error)
    76  
    77  	// TryGetAccount abstract an account read from the trie.
    78  	TryGetAccount(key []byte) (*types.StateAccount, error)
    79  
    80  	// TryUpdate associates key with value in the trie. If value has length zero, any
    81  	// existing value is deleted from the trie. The value bytes must not be modified
    82  	// by the caller while they are stored in the trie. If a node was not found in the
    83  	// database, a trie.MissingNodeError is returned.
    84  	TryUpdate(key, value []byte) error
    85  
    86  	// TryUpdateAccount abstract an account write to the trie.
    87  	TryUpdateAccount(key []byte, account *types.StateAccount) 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  	// TryDeleteAccount abstracts an account deletion from the trie.
    94  	TryDeleteAccount(key []byte) error
    95  
    96  	// Hash returns the root hash of the trie. It does not write to the database and
    97  	// can be used even if the trie doesn't have one.
    98  	Hash() common.Hash
    99  
   100  	// Commit collects all dirty nodes in the trie and replace them with the
   101  	// corresponding node hash. All collected nodes(including dirty leaves if
   102  	// collectLeaf is true) will be encapsulated into a nodeset for return.
   103  	// The returned nodeset can be nil if the trie is clean(nothing to commit).
   104  	// Once the trie is committed, it's not usable anymore. A new trie must
   105  	// be created with new root and updated trie database for following usage
   106  	Commit(collectLeaf bool) (common.Hash, *trie.NodeSet, error)
   107  
   108  	// NodeIterator returns an iterator that returns nodes of the trie. Iteration
   109  	// starts at the key after the given start key.
   110  	NodeIterator(startKey []byte) trie.NodeIterator
   111  
   112  	// Prove constructs a Merkle proof for key. The result contains all encoded nodes
   113  	// on the path to the value at key. The value itself is also included in the last
   114  	// node and can be retrieved by verifying the proof.
   115  	//
   116  	// If the trie does not contain a value for key, the returned proof contains all
   117  	// nodes of the longest existing prefix of the key (at least the root), ending
   118  	// with the node that proves the absence of the key.
   119  	Prove(key []byte, fromLevel uint, proofDb ethdb.KeyValueWriter) error
   120  }
   121  
   122  // NewDatabase creates a backing store for state. The returned database is safe for
   123  // concurrent use, but does not retain any recent trie nodes in memory. To keep some
   124  // historical state in memory, use the NewDatabaseWithConfig constructor.
   125  func NewDatabase(db ethdb.Database) Database {
   126  	return NewDatabaseWithConfig(db, nil)
   127  }
   128  
   129  // NewDatabaseWithConfig creates a backing store for state. The returned database
   130  // is safe for concurrent use and retains a lot of collapsed RLP trie nodes in a
   131  // large memory cache.
   132  func NewDatabaseWithConfig(db ethdb.Database, config *trie.Config) Database {
   133  	csc, _ := lru.New(codeSizeCacheSize)
   134  	return &cachingDB{
   135  		db:            trie.NewDatabaseWithConfig(db, config),
   136  		disk:          db,
   137  		codeSizeCache: csc,
   138  		codeCache:     fastcache.New(codeCacheSize),
   139  	}
   140  }
   141  
   142  type cachingDB struct {
   143  	db            *trie.Database
   144  	disk          ethdb.KeyValueStore
   145  	codeSizeCache *lru.Cache
   146  	codeCache     *fastcache.Cache
   147  }
   148  
   149  // OpenTrie opens the main account trie at a specific root hash.
   150  func (db *cachingDB) OpenTrie(root common.Hash) (Trie, error) {
   151  	tr, err := trie.NewStateTrie(trie.StateTrieID(root), db.db)
   152  	if err != nil {
   153  		return nil, err
   154  	}
   155  	return tr, nil
   156  }
   157  
   158  // OpenStorageTrie opens the storage trie of an account.
   159  func (db *cachingDB) OpenStorageTrie(stateRoot common.Hash, addrHash, root common.Hash) (Trie, error) {
   160  	tr, err := trie.NewStateTrie(trie.StorageTrieID(stateRoot, addrHash, root), db.db)
   161  	if err != nil {
   162  		return nil, err
   163  	}
   164  	return tr, nil
   165  }
   166  
   167  // CopyTrie returns an independent copy of the given trie.
   168  func (db *cachingDB) CopyTrie(t Trie) Trie {
   169  	switch t := t.(type) {
   170  	case *trie.StateTrie:
   171  		return t.Copy()
   172  	default:
   173  		panic(fmt.Errorf("unknown trie type %T", t))
   174  	}
   175  }
   176  
   177  // ContractCode retrieves a particular contract's code.
   178  func (db *cachingDB) ContractCode(addrHash, codeHash common.Hash) ([]byte, error) {
   179  	if code := db.codeCache.Get(nil, codeHash.Bytes()); len(code) > 0 {
   180  		return code, nil
   181  	}
   182  	code := rawdb.ReadCode(db.disk, codeHash)
   183  	if len(code) > 0 {
   184  		db.codeCache.Set(codeHash.Bytes(), code)
   185  		db.codeSizeCache.Add(codeHash, len(code))
   186  		return code, nil
   187  	}
   188  	return nil, errors.New("not found")
   189  }
   190  
   191  // ContractCodeWithPrefix retrieves a particular contract's code. If the
   192  // code can't be found in the cache, then check the existence with **new**
   193  // db scheme.
   194  func (db *cachingDB) ContractCodeWithPrefix(addrHash, codeHash common.Hash) ([]byte, error) {
   195  	if code := db.codeCache.Get(nil, codeHash.Bytes()); len(code) > 0 {
   196  		return code, nil
   197  	}
   198  	code := rawdb.ReadCodeWithPrefix(db.disk, codeHash)
   199  	if len(code) > 0 {
   200  		db.codeCache.Set(codeHash.Bytes(), code)
   201  		db.codeSizeCache.Add(codeHash, len(code))
   202  		return code, nil
   203  	}
   204  	return nil, errors.New("not found")
   205  }
   206  
   207  // ContractCodeSize retrieves a particular contracts code's size.
   208  func (db *cachingDB) ContractCodeSize(addrHash, codeHash common.Hash) (int, error) {
   209  	if cached, ok := db.codeSizeCache.Get(codeHash); ok {
   210  		return cached.(int), nil
   211  	}
   212  	code, err := db.ContractCode(addrHash, codeHash)
   213  	return len(code), err
   214  }
   215  
   216  // DiskDB returns the underlying key-value disk database.
   217  func (db *cachingDB) DiskDB() ethdb.KeyValueStore {
   218  	return db.disk
   219  }
   220  
   221  // TrieDB retrieves any intermediate trie-node caching layer.
   222  func (db *cachingDB) TrieDB() *trie.Database {
   223  	return db.db
   224  }