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