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