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