github.com/dogestan/eth@v1.9.7/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  	"fmt"
    21  
    22  	"github.com/ethereum/go-ethereum/common"
    23  	"github.com/ethereum/go-ethereum/ethdb"
    24  	"github.com/ethereum/go-ethereum/trie"
    25  	lru "github.com/hashicorp/golang-lru"
    26  )
    27  
    28  const (
    29  	// Number of codehash->size associations to keep.
    30  	codeSizeCacheSize = 100000
    31  )
    32  
    33  // Database wraps access to tries and contract code.
    34  type Database interface {
    35  	// OpenTrie opens the main account trie.
    36  	OpenTrie(root common.Hash) (Trie, error)
    37  
    38  	// OpenStorageTrie opens the storage trie of an account.
    39  	OpenStorageTrie(addrHash, root common.Hash) (Trie, error)
    40  
    41  	// CopyTrie returns an independent copy of the given trie.
    42  	CopyTrie(Trie) Trie
    43  
    44  	// ContractCode retrieves a particular contract's code.
    45  	ContractCode(addrHash, codeHash common.Hash) ([]byte, error)
    46  
    47  	// ContractCodeSize retrieves a particular contracts code's size.
    48  	ContractCodeSize(addrHash, codeHash common.Hash) (int, error)
    49  
    50  	// TrieDB retrieves the low level trie database used for data storage.
    51  	TrieDB() *trie.Database
    52  }
    53  
    54  // Trie is a Ethereum Merkle Patricia trie.
    55  type Trie interface {
    56  	// GetKey returns the sha3 preimage of a hashed key that was previously used
    57  	// to store a value.
    58  	//
    59  	// TODO(fjl): remove this when SecureTrie is removed
    60  	GetKey([]byte) []byte
    61  
    62  	// TryGet returns the value for key stored in the trie. The value bytes must
    63  	// not be modified by the caller. If a node was not found in the database, a
    64  	// trie.MissingNodeError is returned.
    65  	TryGet(key []byte) ([]byte, error)
    66  
    67  	// TryUpdate associates key with value in the trie. If value has length zero, any
    68  	// existing value is deleted from the trie. The value bytes must not be modified
    69  	// by the caller while they are stored in the trie. If a node was not found in the
    70  	// database, a trie.MissingNodeError is returned.
    71  	TryUpdate(key, value []byte) error
    72  
    73  	// TryDelete removes any existing value for key from the trie. If a node was not
    74  	// found in the database, a trie.MissingNodeError is returned.
    75  	TryDelete(key []byte) error
    76  
    77  	// Hash returns the root hash of the trie. It does not write to the database and
    78  	// can be used even if the trie doesn't have one.
    79  	Hash() common.Hash
    80  
    81  	// Commit writes all nodes to the trie's memory database, tracking the internal
    82  	// and external (for account tries) references.
    83  	Commit(onleaf trie.LeafCallback) (common.Hash, error)
    84  
    85  	// NodeIterator returns an iterator that returns nodes of the trie. Iteration
    86  	// starts at the key after the given start key.
    87  	NodeIterator(startKey []byte) trie.NodeIterator
    88  
    89  	// Prove constructs a Merkle proof for key. The result contains all encoded nodes
    90  	// on the path to the value at key. The value itself is also included in the last
    91  	// node and can be retrieved by verifying the proof.
    92  	//
    93  	// If the trie does not contain a value for key, the returned proof contains all
    94  	// nodes of the longest existing prefix of the key (at least the root), ending
    95  	// with the node that proves the absence of the key.
    96  	Prove(key []byte, fromLevel uint, proofDb ethdb.KeyValueWriter) error
    97  }
    98  
    99  // NewDatabase creates a backing store for state. The returned database is safe for
   100  // concurrent use, but does not retain any recent trie nodes in memory. To keep some
   101  // historical state in memory, use the NewDatabaseWithCache constructor.
   102  func NewDatabase(db ethdb.Database) Database {
   103  	return NewDatabaseWithCache(db, 0)
   104  }
   105  
   106  // NewDatabaseWithCache creates a backing store for state. The returned database
   107  // is safe for concurrent use and retains a lot of collapsed RLP trie nodes in a
   108  // large memory cache.
   109  func NewDatabaseWithCache(db ethdb.Database, cache int) Database {
   110  	csc, _ := lru.New(codeSizeCacheSize)
   111  	return &cachingDB{
   112  		db:            trie.NewDatabaseWithCache(db, cache),
   113  		codeSizeCache: csc,
   114  	}
   115  }
   116  
   117  type cachingDB struct {
   118  	db            *trie.Database
   119  	codeSizeCache *lru.Cache
   120  }
   121  
   122  // OpenTrie opens the main account trie at a specific root hash.
   123  func (db *cachingDB) OpenTrie(root common.Hash) (Trie, error) {
   124  	return trie.NewSecure(root, db.db)
   125  }
   126  
   127  // OpenStorageTrie opens the storage trie of an account.
   128  func (db *cachingDB) OpenStorageTrie(addrHash, root common.Hash) (Trie, error) {
   129  	return trie.NewSecure(root, db.db)
   130  }
   131  
   132  // CopyTrie returns an independent copy of the given trie.
   133  func (db *cachingDB) CopyTrie(t Trie) Trie {
   134  	switch t := t.(type) {
   135  	case *trie.SecureTrie:
   136  		return t.Copy()
   137  	default:
   138  		panic(fmt.Errorf("unknown trie type %T", t))
   139  	}
   140  }
   141  
   142  // ContractCode retrieves a particular contract's code.
   143  func (db *cachingDB) ContractCode(addrHash, codeHash common.Hash) ([]byte, error) {
   144  	code, err := db.db.Node(codeHash)
   145  	if err == nil {
   146  		db.codeSizeCache.Add(codeHash, len(code))
   147  	}
   148  	return code, err
   149  }
   150  
   151  // ContractCodeSize retrieves a particular contracts code's size.
   152  func (db *cachingDB) ContractCodeSize(addrHash, codeHash common.Hash) (int, error) {
   153  	if cached, ok := db.codeSizeCache.Get(codeHash); ok {
   154  		return cached.(int), nil
   155  	}
   156  	code, err := db.ContractCode(addrHash, codeHash)
   157  	return len(code), err
   158  }
   159  
   160  // TrieDB retrieves any intermediate trie-node caching layer.
   161  func (db *cachingDB) TrieDB() *trie.Database {
   162  	return db.db
   163  }