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