github.com/tirogen/go-ethereum@v1.10.12-0.20221226051715-250cfede41b6/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/tirogen/go-ethereum/common"
    24  	"github.com/tirogen/go-ethereum/common/lru"
    25  	"github.com/tirogen/go-ethereum/core/rawdb"
    26  	"github.com/tirogen/go-ethereum/core/types"
    27  	"github.com/tirogen/go-ethereum/ethdb"
    28  	"github.com/tirogen/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 abstract an account read from the trie.
    77  	TryGetAccount(key []byte) (*types.StateAccount, error)
    78  
    79  	// TryUpdate associates key with value in the trie. If value has length zero, any
    80  	// existing value is deleted from the trie. The value bytes must not be modified
    81  	// by the caller while they are stored in the trie. If a node was not found in the
    82  	// database, a trie.MissingNodeError is returned.
    83  	TryUpdate(key, value []byte) error
    84  
    85  	// TryUpdateAccount abstract an account write to the trie.
    86  	TryUpdateAccount(key []byte, account *types.StateAccount) error
    87  
    88  	// TryDelete removes any existing value for key from the trie. If a node was not
    89  	// found in the database, a trie.MissingNodeError is returned.
    90  	TryDelete(key []byte) error
    91  
    92  	// TryDeleteAccount abstracts an account deletion from the trie.
    93  	TryDeleteAccount(key []byte) error
    94  
    95  	// Hash returns the root hash of the trie. It does not write to the database and
    96  	// can be used even if the trie doesn't have one.
    97  	Hash() common.Hash
    98  
    99  	// Commit collects all dirty nodes in the trie and replace them with the
   100  	// corresponding node hash. All collected nodes(including dirty leaves if
   101  	// collectLeaf is true) will be encapsulated into a nodeset for return.
   102  	// The returned nodeset can be nil if the trie is clean(nothing to commit).
   103  	// Once the trie is committed, it's not usable anymore. A new trie must
   104  	// be created with new root and updated trie database for following usage
   105  	Commit(collectLeaf bool) (common.Hash, *trie.NodeSet, error)
   106  
   107  	// NodeIterator returns an iterator that returns nodes of the trie. Iteration
   108  	// starts at the key after the given start key.
   109  	NodeIterator(startKey []byte) trie.NodeIterator
   110  
   111  	// Prove constructs a Merkle proof for key. The result contains all encoded nodes
   112  	// on the path to the value at key. The value itself is also included in the last
   113  	// node and can be retrieved by verifying the proof.
   114  	//
   115  	// If the trie does not contain a value for key, the returned proof contains all
   116  	// nodes of the longest existing prefix of the key (at least the root), ending
   117  	// with the node that proves the absence of the key.
   118  	Prove(key []byte, fromLevel uint, proofDb ethdb.KeyValueWriter) error
   119  }
   120  
   121  // NewDatabase creates a backing store for state. The returned database is safe for
   122  // concurrent use, but does not retain any recent trie nodes in memory. To keep some
   123  // historical state in memory, use the NewDatabaseWithConfig constructor.
   124  func NewDatabase(db ethdb.Database) Database {
   125  	return NewDatabaseWithConfig(db, nil)
   126  }
   127  
   128  // NewDatabaseWithConfig creates a backing store for state. The returned database
   129  // is safe for concurrent use and retains a lot of collapsed RLP trie nodes in a
   130  // large memory cache.
   131  func NewDatabaseWithConfig(db ethdb.Database, config *trie.Config) Database {
   132  	return &cachingDB{
   133  		disk:          db,
   134  		codeSizeCache: lru.NewCache[common.Hash, int](codeSizeCacheSize),
   135  		codeCache:     lru.NewSizeConstrainedCache[common.Hash, []byte](codeCacheSize),
   136  		triedb:        trie.NewDatabaseWithConfig(db, config),
   137  	}
   138  }
   139  
   140  // NewDatabaseWithNodeDB creates a state database with an already initialized node database.
   141  func NewDatabaseWithNodeDB(db ethdb.Database, triedb *trie.Database) Database {
   142  	return &cachingDB{
   143  		disk:          db,
   144  		codeSizeCache: lru.NewCache[common.Hash, int](codeSizeCacheSize),
   145  		codeCache:     lru.NewSizeConstrainedCache[common.Hash, []byte](codeCacheSize),
   146  		triedb:        triedb,
   147  	}
   148  }
   149  
   150  type cachingDB struct {
   151  	disk          ethdb.KeyValueStore
   152  	codeSizeCache *lru.Cache[common.Hash, int]
   153  	codeCache     *lru.SizeConstrainedCache[common.Hash, []byte]
   154  	triedb        *trie.Database
   155  }
   156  
   157  // OpenTrie opens the main account trie at a specific root hash.
   158  func (db *cachingDB) OpenTrie(root common.Hash) (Trie, error) {
   159  	tr, err := trie.NewStateTrie(trie.StateTrieID(root), db.triedb)
   160  	if err != nil {
   161  		return nil, err
   162  	}
   163  	return tr, nil
   164  }
   165  
   166  // OpenStorageTrie opens the storage trie of an account.
   167  func (db *cachingDB) OpenStorageTrie(stateRoot common.Hash, addrHash, root common.Hash) (Trie, error) {
   168  	tr, err := trie.NewStateTrie(trie.StorageTrieID(stateRoot, addrHash, root), db.triedb)
   169  	if err != nil {
   170  		return nil, err
   171  	}
   172  	return tr, nil
   173  }
   174  
   175  // CopyTrie returns an independent copy of the given trie.
   176  func (db *cachingDB) CopyTrie(t Trie) Trie {
   177  	switch t := t.(type) {
   178  	case *trie.StateTrie:
   179  		return t.Copy()
   180  	default:
   181  		panic(fmt.Errorf("unknown trie type %T", t))
   182  	}
   183  }
   184  
   185  // ContractCode retrieves a particular contract's code.
   186  func (db *cachingDB) ContractCode(addrHash, codeHash common.Hash) ([]byte, error) {
   187  	code, _ := db.codeCache.Get(codeHash)
   188  	if len(code) > 0 {
   189  		return code, nil
   190  	}
   191  	code = rawdb.ReadCode(db.disk, codeHash)
   192  	if len(code) > 0 {
   193  		db.codeCache.Add(codeHash, code)
   194  		db.codeSizeCache.Add(codeHash, len(code))
   195  		return code, nil
   196  	}
   197  	return nil, errors.New("not found")
   198  }
   199  
   200  // ContractCodeWithPrefix retrieves a particular contract's code. If the
   201  // code can't be found in the cache, then check the existence with **new**
   202  // db scheme.
   203  func (db *cachingDB) ContractCodeWithPrefix(addrHash, codeHash common.Hash) ([]byte, error) {
   204  	code, _ := db.codeCache.Get(codeHash)
   205  	if len(code) > 0 {
   206  		return code, nil
   207  	}
   208  	code = rawdb.ReadCodeWithPrefix(db.disk, codeHash)
   209  	if len(code) > 0 {
   210  		db.codeCache.Add(codeHash, code)
   211  		db.codeSizeCache.Add(codeHash, len(code))
   212  		return code, nil
   213  	}
   214  	return nil, errors.New("not found")
   215  }
   216  
   217  // ContractCodeSize retrieves a particular contracts code's size.
   218  func (db *cachingDB) ContractCodeSize(addrHash, codeHash common.Hash) (int, error) {
   219  	if cached, ok := db.codeSizeCache.Get(codeHash); ok {
   220  		return cached, nil
   221  	}
   222  	code, err := db.ContractCode(addrHash, codeHash)
   223  	return len(code), err
   224  }
   225  
   226  // DiskDB returns the underlying key-value disk database.
   227  func (db *cachingDB) DiskDB() ethdb.KeyValueStore {
   228  	return db.disk
   229  }
   230  
   231  // TrieDB retrieves any intermediate trie-node caching layer.
   232  func (db *cachingDB) TrieDB() *trie.Database {
   233  	return db.triedb
   234  }