github.com/DxChainNetwork/dxc@v0.8.1-0.20220824085222-1162e304b6e7/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/DxChainNetwork/dxc/common"
    24  	"github.com/DxChainNetwork/dxc/core/rawdb"
    25  	"github.com/DxChainNetwork/dxc/ethdb"
    26  	"github.com/DxChainNetwork/dxc/trie"
    27  	"github.com/VictoriaMetrics/fastcache"
    28  	lru "github.com/hashicorp/golang-lru"
    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(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  	// TrieDB retrieves the low level trie database used for data storage.
    57  	TrieDB() *trie.Database
    58  }
    59  
    60  // Trie is a Ethereum Merkle Patricia trie.
    61  type Trie interface {
    62  	// GetKey returns the sha3 preimage of a hashed key that was previously used
    63  	// to store a value.
    64  	//
    65  	// TODO(fjl): remove this when SecureTrie is removed
    66  	GetKey([]byte) []byte
    67  
    68  	// TryGet returns the value for key stored in the trie. The value bytes must
    69  	// not be modified by the caller. If a node was not found in the database, a
    70  	// trie.MissingNodeError is returned.
    71  	TryGet(key []byte) ([]byte, error)
    72  
    73  	// TryUpdate associates key with value in the trie. If value has length zero, any
    74  	// existing value is deleted from the trie. The value bytes must not be modified
    75  	// by the caller while they are stored in the trie. If a node was not found in the
    76  	// database, a trie.MissingNodeError is returned.
    77  	TryUpdate(key, value []byte) error
    78  
    79  	// TryDelete removes any existing value for key from the trie. If a node was not
    80  	// found in the database, a trie.MissingNodeError is returned.
    81  	TryDelete(key []byte) error
    82  
    83  	// Hash returns the root hash of the trie. It does not write to the database and
    84  	// can be used even if the trie doesn't have one.
    85  	Hash() common.Hash
    86  
    87  	// Commit writes all nodes to the trie's memory database, tracking the internal
    88  	// and external (for account tries) references.
    89  	Commit(onleaf trie.LeafCallback) (common.Hash, error)
    90  
    91  	// NodeIterator returns an iterator that returns nodes of the trie. Iteration
    92  	// starts at the key after the given start key.
    93  	NodeIterator(startKey []byte) trie.NodeIterator
    94  
    95  	// Prove constructs a Merkle proof for key. The result contains all encoded nodes
    96  	// on the path to the value at key. The value itself is also included in the last
    97  	// node and can be retrieved by verifying the proof.
    98  	//
    99  	// If the trie does not contain a value for key, the returned proof contains all
   100  	// nodes of the longest existing prefix of the key (at least the root), ending
   101  	// with the node that proves the absence of the key.
   102  	Prove(key []byte, fromLevel uint, proofDb ethdb.KeyValueWriter) error
   103  }
   104  
   105  // NewDatabase creates a backing store for state. The returned database is safe for
   106  // concurrent use, but does not retain any recent trie nodes in memory. To keep some
   107  // historical state in memory, use the NewDatabaseWithConfig constructor.
   108  func NewDatabase(db ethdb.Database) Database {
   109  	return NewDatabaseWithConfig(db, nil)
   110  }
   111  
   112  // NewDatabaseWithConfig creates a backing store for state. The returned database
   113  // is safe for concurrent use and retains a lot of collapsed RLP trie nodes in a
   114  // large memory cache.
   115  func NewDatabaseWithConfig(db ethdb.Database, config *trie.Config) Database {
   116  	csc, _ := lru.New(codeSizeCacheSize)
   117  	return &cachingDB{
   118  		db:            trie.NewDatabaseWithConfig(db, config),
   119  		codeSizeCache: csc,
   120  		codeCache:     fastcache.New(codeCacheSize),
   121  	}
   122  }
   123  
   124  type cachingDB struct {
   125  	db            *trie.Database
   126  	codeSizeCache *lru.Cache
   127  	codeCache     *fastcache.Cache
   128  }
   129  
   130  // OpenTrie opens the main account trie at a specific root hash.
   131  func (db *cachingDB) OpenTrie(root common.Hash) (Trie, error) {
   132  	tr, err := trie.NewSecure(root, db.db)
   133  	if err != nil {
   134  		return nil, err
   135  	}
   136  	return tr, nil
   137  }
   138  
   139  // OpenStorageTrie opens the storage trie of an account.
   140  func (db *cachingDB) OpenStorageTrie(addrHash, root common.Hash) (Trie, error) {
   141  	tr, err := trie.NewSecure(root, db.db)
   142  	if err != nil {
   143  		return nil, err
   144  	}
   145  	return tr, nil
   146  }
   147  
   148  // CopyTrie returns an independent copy of the given trie.
   149  func (db *cachingDB) CopyTrie(t Trie) Trie {
   150  	switch t := t.(type) {
   151  	case *trie.SecureTrie:
   152  		return t.Copy()
   153  	default:
   154  		panic(fmt.Errorf("unknown trie type %T", t))
   155  	}
   156  }
   157  
   158  // ContractCode retrieves a particular contract's code.
   159  func (db *cachingDB) ContractCode(addrHash, codeHash common.Hash) ([]byte, error) {
   160  	if code := db.codeCache.Get(nil, codeHash.Bytes()); len(code) > 0 {
   161  		return code, nil
   162  	}
   163  	code := rawdb.ReadCode(db.db.DiskDB(), codeHash)
   164  	if len(code) > 0 {
   165  		db.codeCache.Set(codeHash.Bytes(), code)
   166  		db.codeSizeCache.Add(codeHash, len(code))
   167  		return code, nil
   168  	}
   169  	return nil, errors.New("not found")
   170  }
   171  
   172  // ContractCodeWithPrefix retrieves a particular contract's code. If the
   173  // code can't be found in the cache, then check the existence with **new**
   174  // db scheme.
   175  func (db *cachingDB) ContractCodeWithPrefix(addrHash, codeHash common.Hash) ([]byte, error) {
   176  	if code := db.codeCache.Get(nil, codeHash.Bytes()); len(code) > 0 {
   177  		return code, nil
   178  	}
   179  	code := rawdb.ReadCodeWithPrefix(db.db.DiskDB(), codeHash)
   180  	if len(code) > 0 {
   181  		db.codeCache.Set(codeHash.Bytes(), code)
   182  		db.codeSizeCache.Add(codeHash, len(code))
   183  		return code, nil
   184  	}
   185  	return nil, errors.New("not found")
   186  }
   187  
   188  // ContractCodeSize retrieves a particular contracts code's size.
   189  func (db *cachingDB) ContractCodeSize(addrHash, codeHash common.Hash) (int, error) {
   190  	if cached, ok := db.codeSizeCache.Get(codeHash); ok {
   191  		return cached.(int), nil
   192  	}
   193  	code, err := db.ContractCode(addrHash, codeHash)
   194  	return len(code), err
   195  }
   196  
   197  // TrieDB retrieves any intermediate trie-node caching layer.
   198  func (db *cachingDB) TrieDB() *trie.Database {
   199  	return db.db
   200  }