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