github.com/ethereum/go-ethereum@v1.14.4-0.20240516095835-473ee8fc07a3/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/ethereum/go-ethereum/common"
    24  	"github.com/ethereum/go-ethereum/common/lru"
    25  	"github.com/ethereum/go-ethereum/core/rawdb"
    26  	"github.com/ethereum/go-ethereum/core/types"
    27  	"github.com/ethereum/go-ethereum/crypto"
    28  	"github.com/ethereum/go-ethereum/ethdb"
    29  	"github.com/ethereum/go-ethereum/trie"
    30  	"github.com/ethereum/go-ethereum/trie/trienode"
    31  	"github.com/ethereum/go-ethereum/trie/utils"
    32  	"github.com/ethereum/go-ethereum/triedb"
    33  )
    34  
    35  const (
    36  	// Number of codehash->size associations to keep.
    37  	codeSizeCacheSize = 100000
    38  
    39  	// Cache size granted for caching clean code.
    40  	codeCacheSize = 64 * 1024 * 1024
    41  
    42  	// Number of address->curve point associations to keep.
    43  	pointCacheSize = 4096
    44  )
    45  
    46  // Database wraps access to tries and contract code.
    47  type Database interface {
    48  	// OpenTrie opens the main account trie.
    49  	OpenTrie(root common.Hash) (Trie, error)
    50  
    51  	// OpenStorageTrie opens the storage trie of an account.
    52  	OpenStorageTrie(stateRoot common.Hash, address common.Address, root common.Hash, trie Trie) (Trie, error)
    53  
    54  	// CopyTrie returns an independent copy of the given trie.
    55  	CopyTrie(Trie) Trie
    56  
    57  	// ContractCode retrieves a particular contract's code.
    58  	ContractCode(addr common.Address, codeHash common.Hash) ([]byte, error)
    59  
    60  	// ContractCodeSize retrieves a particular contracts code's size.
    61  	ContractCodeSize(addr common.Address, codeHash common.Hash) (int, error)
    62  
    63  	// DiskDB returns the underlying key-value disk database.
    64  	DiskDB() ethdb.KeyValueStore
    65  
    66  	// PointCache returns the cache holding points used in verkle tree key computation
    67  	PointCache() *utils.PointCache
    68  
    69  	// TrieDB returns the underlying trie database for managing trie nodes.
    70  	TrieDB() *triedb.Database
    71  }
    72  
    73  // Trie is a Ethereum Merkle Patricia trie.
    74  type Trie interface {
    75  	// GetKey returns the sha3 preimage of a hashed key that was previously used
    76  	// to store a value.
    77  	//
    78  	// TODO(fjl): remove this when StateTrie is removed
    79  	GetKey([]byte) []byte
    80  
    81  	// GetAccount abstracts an account read from the trie. It retrieves the
    82  	// account blob from the trie with provided account address and decodes it
    83  	// with associated decoding algorithm. If the specified account is not in
    84  	// the trie, nil will be returned. If the trie is corrupted(e.g. some nodes
    85  	// are missing or the account blob is incorrect for decoding), an error will
    86  	// be returned.
    87  	GetAccount(address common.Address) (*types.StateAccount, error)
    88  
    89  	// GetStorage returns the value for key stored in the trie. The value bytes
    90  	// must not be modified by the caller. If a node was not found in the database,
    91  	// a trie.MissingNodeError is returned.
    92  	GetStorage(addr common.Address, key []byte) ([]byte, error)
    93  
    94  	// UpdateAccount abstracts an account write to the trie. It encodes the
    95  	// provided account object with associated algorithm and then updates it
    96  	// in the trie with provided address.
    97  	UpdateAccount(address common.Address, account *types.StateAccount) error
    98  
    99  	// UpdateStorage associates key with value in the trie. If value has length zero,
   100  	// any existing value is deleted from the trie. The value bytes must not be modified
   101  	// by the caller while they are stored in the trie. If a node was not found in the
   102  	// database, a trie.MissingNodeError is returned.
   103  	UpdateStorage(addr common.Address, key, value []byte) error
   104  
   105  	// DeleteAccount abstracts an account deletion from the trie.
   106  	DeleteAccount(address common.Address) error
   107  
   108  	// DeleteStorage removes any existing value for key from the trie. If a node
   109  	// was not found in the database, a trie.MissingNodeError is returned.
   110  	DeleteStorage(addr common.Address, key []byte) error
   111  
   112  	// UpdateContractCode abstracts code write to the trie. It is expected
   113  	// to be moved to the stateWriter interface when the latter is ready.
   114  	UpdateContractCode(address common.Address, codeHash common.Hash, code []byte) error
   115  
   116  	// Hash returns the root hash of the trie. It does not write to the database and
   117  	// can be used even if the trie doesn't have one.
   118  	Hash() common.Hash
   119  
   120  	// Commit collects all dirty nodes in the trie and replace them with the
   121  	// corresponding node hash. All collected nodes(including dirty leaves if
   122  	// collectLeaf is true) will be encapsulated into a nodeset for return.
   123  	// The returned nodeset can be nil if the trie is clean(nothing to commit).
   124  	// Once the trie is committed, it's not usable anymore. A new trie must
   125  	// be created with new root and updated trie database for following usage
   126  	Commit(collectLeaf bool) (common.Hash, *trienode.NodeSet, error)
   127  
   128  	// NodeIterator returns an iterator that returns nodes of the trie. Iteration
   129  	// starts at the key after the given start key. And error will be returned
   130  	// if fails to create node iterator.
   131  	NodeIterator(startKey []byte) (trie.NodeIterator, error)
   132  
   133  	// Prove constructs a Merkle proof for key. The result contains all encoded nodes
   134  	// on the path to the value at key. The value itself is also included in the last
   135  	// node and can be retrieved by verifying the proof.
   136  	//
   137  	// If the trie does not contain a value for key, the returned proof contains all
   138  	// nodes of the longest existing prefix of the key (at least the root), ending
   139  	// with the node that proves the absence of the key.
   140  	Prove(key []byte, proofDb ethdb.KeyValueWriter) error
   141  
   142  	// IsVerkle returns true if the trie is verkle-tree based
   143  	IsVerkle() bool
   144  }
   145  
   146  // NewDatabase creates a backing store for state. The returned database is safe for
   147  // concurrent use, but does not retain any recent trie nodes in memory. To keep some
   148  // historical state in memory, use the NewDatabaseWithConfig constructor.
   149  func NewDatabase(db ethdb.Database) Database {
   150  	return NewDatabaseWithConfig(db, nil)
   151  }
   152  
   153  // NewDatabaseWithConfig creates a backing store for state. The returned database
   154  // is safe for concurrent use and retains a lot of collapsed RLP trie nodes in a
   155  // large memory cache.
   156  func NewDatabaseWithConfig(db ethdb.Database, config *triedb.Config) Database {
   157  	return &cachingDB{
   158  		disk:          db,
   159  		codeSizeCache: lru.NewCache[common.Hash, int](codeSizeCacheSize),
   160  		codeCache:     lru.NewSizeConstrainedCache[common.Hash, []byte](codeCacheSize),
   161  		triedb:        triedb.NewDatabase(db, config),
   162  		pointCache:    utils.NewPointCache(pointCacheSize),
   163  	}
   164  }
   165  
   166  // NewDatabaseWithNodeDB creates a state database with an already initialized node database.
   167  func NewDatabaseWithNodeDB(db ethdb.Database, triedb *triedb.Database) Database {
   168  	return &cachingDB{
   169  		disk:          db,
   170  		codeSizeCache: lru.NewCache[common.Hash, int](codeSizeCacheSize),
   171  		codeCache:     lru.NewSizeConstrainedCache[common.Hash, []byte](codeCacheSize),
   172  		triedb:        triedb,
   173  		pointCache:    utils.NewPointCache(pointCacheSize),
   174  	}
   175  }
   176  
   177  type cachingDB struct {
   178  	disk          ethdb.KeyValueStore
   179  	codeSizeCache *lru.Cache[common.Hash, int]
   180  	codeCache     *lru.SizeConstrainedCache[common.Hash, []byte]
   181  	triedb        *triedb.Database
   182  	pointCache    *utils.PointCache
   183  }
   184  
   185  // OpenTrie opens the main account trie at a specific root hash.
   186  func (db *cachingDB) OpenTrie(root common.Hash) (Trie, error) {
   187  	if db.triedb.IsVerkle() {
   188  		return trie.NewVerkleTrie(root, db.triedb, db.pointCache)
   189  	}
   190  	tr, err := trie.NewStateTrie(trie.StateTrieID(root), db.triedb)
   191  	if err != nil {
   192  		return nil, err
   193  	}
   194  	return tr, nil
   195  }
   196  
   197  // OpenStorageTrie opens the storage trie of an account.
   198  func (db *cachingDB) OpenStorageTrie(stateRoot common.Hash, address common.Address, root common.Hash, self Trie) (Trie, error) {
   199  	// In the verkle case, there is only one tree. But the two-tree structure
   200  	// is hardcoded in the codebase. So we need to return the same trie in this
   201  	// case.
   202  	if db.triedb.IsVerkle() {
   203  		return self, nil
   204  	}
   205  	tr, err := trie.NewStateTrie(trie.StorageTrieID(stateRoot, crypto.Keccak256Hash(address.Bytes()), root), db.triedb)
   206  	if err != nil {
   207  		return nil, err
   208  	}
   209  	return tr, nil
   210  }
   211  
   212  // CopyTrie returns an independent copy of the given trie.
   213  func (db *cachingDB) CopyTrie(t Trie) Trie {
   214  	switch t := t.(type) {
   215  	case *trie.StateTrie:
   216  		return t.Copy()
   217  	case *trie.VerkleTrie:
   218  		return t.Copy()
   219  	default:
   220  		panic(fmt.Errorf("unknown trie type %T", t))
   221  	}
   222  }
   223  
   224  // ContractCode retrieves a particular contract's code.
   225  func (db *cachingDB) ContractCode(address common.Address, codeHash common.Hash) ([]byte, error) {
   226  	code, _ := db.codeCache.Get(codeHash)
   227  	if len(code) > 0 {
   228  		return code, nil
   229  	}
   230  	code = rawdb.ReadCode(db.disk, codeHash)
   231  	if len(code) > 0 {
   232  		db.codeCache.Add(codeHash, code)
   233  		db.codeSizeCache.Add(codeHash, len(code))
   234  		return code, nil
   235  	}
   236  	return nil, errors.New("not found")
   237  }
   238  
   239  // ContractCodeWithPrefix retrieves a particular contract's code. If the
   240  // code can't be found in the cache, then check the existence with **new**
   241  // db scheme.
   242  func (db *cachingDB) ContractCodeWithPrefix(address common.Address, codeHash common.Hash) ([]byte, error) {
   243  	code, _ := db.codeCache.Get(codeHash)
   244  	if len(code) > 0 {
   245  		return code, nil
   246  	}
   247  	code = rawdb.ReadCodeWithPrefix(db.disk, codeHash)
   248  	if len(code) > 0 {
   249  		db.codeCache.Add(codeHash, code)
   250  		db.codeSizeCache.Add(codeHash, len(code))
   251  		return code, nil
   252  	}
   253  	return nil, errors.New("not found")
   254  }
   255  
   256  // ContractCodeSize retrieves a particular contracts code's size.
   257  func (db *cachingDB) ContractCodeSize(addr common.Address, codeHash common.Hash) (int, error) {
   258  	if cached, ok := db.codeSizeCache.Get(codeHash); ok {
   259  		return cached, nil
   260  	}
   261  	code, err := db.ContractCode(addr, codeHash)
   262  	return len(code), err
   263  }
   264  
   265  // DiskDB returns the underlying key-value disk database.
   266  func (db *cachingDB) DiskDB() ethdb.KeyValueStore {
   267  	return db.disk
   268  }
   269  
   270  // TrieDB retrieves any intermediate trie-node caching layer.
   271  func (db *cachingDB) TrieDB() *triedb.Database {
   272  	return db.triedb
   273  }
   274  
   275  // PointCache returns the cache of evaluated curve points.
   276  func (db *cachingDB) PointCache() *utils.PointCache {
   277  	return db.pointCache
   278  }