github.com/xfond/eth-implementation@v1.8.9-0.20180514135602-f6bc65fc6811/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  	"sync"
    22  
    23  	"github.com/ethereum/go-ethereum/common"
    24  	"github.com/ethereum/go-ethereum/ethdb"
    25  	"github.com/ethereum/go-ethereum/trie"
    26  	lru "github.com/hashicorp/golang-lru"
    27  )
    28  
    29  // Trie cache generation limit after which to evict trie nodes from memory.
    30  var MaxTrieCacheGen = uint16(120)
    31  
    32  const (
    33  	// Number of past tries to keep. This value is chosen such that
    34  	// reasonable chain reorg depths will hit an existing trie.
    35  	maxPastTries = 12
    36  
    37  	// Number of codehash->size associations to keep.
    38  	codeSizeCacheSize = 100000
    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 Trie.
    63  type Trie interface {
    64  	TryGet(key []byte) ([]byte, error)
    65  	TryUpdate(key, value []byte) error
    66  	TryDelete(key []byte) error
    67  	Commit(onleaf trie.LeafCallback) (common.Hash, error)
    68  	Hash() common.Hash
    69  	NodeIterator(startKey []byte) trie.NodeIterator
    70  	GetKey([]byte) []byte // TODO(fjl): remove this when SecureTrie is removed
    71  	Prove(key []byte, fromLevel uint, proofDb ethdb.Putter) error
    72  }
    73  
    74  // NewDatabase creates a backing store for state. The returned database is safe for
    75  // concurrent use and retains cached trie nodes in memory. The pool is an optional
    76  // intermediate trie-node memory pool between the low level storage layer and the
    77  // high level trie abstraction.
    78  func NewDatabase(db ethdb.Database) Database {
    79  	csc, _ := lru.New(codeSizeCacheSize)
    80  	return &cachingDB{
    81  		db:            trie.NewDatabase(db),
    82  		codeSizeCache: csc,
    83  	}
    84  }
    85  
    86  type cachingDB struct {
    87  	db            *trie.Database
    88  	mu            sync.Mutex
    89  	pastTries     []*trie.SecureTrie
    90  	codeSizeCache *lru.Cache
    91  }
    92  
    93  // OpenTrie opens the main account trie.
    94  func (db *cachingDB) OpenTrie(root common.Hash) (Trie, error) {
    95  	db.mu.Lock()
    96  	defer db.mu.Unlock()
    97  
    98  	for i := len(db.pastTries) - 1; i >= 0; i-- {
    99  		if db.pastTries[i].Hash() == root {
   100  			return cachedTrie{db.pastTries[i].Copy(), db}, nil
   101  		}
   102  	}
   103  	tr, err := trie.NewSecure(root, db.db, MaxTrieCacheGen)
   104  	if err != nil {
   105  		return nil, err
   106  	}
   107  	return cachedTrie{tr, db}, nil
   108  }
   109  
   110  func (db *cachingDB) pushTrie(t *trie.SecureTrie) {
   111  	db.mu.Lock()
   112  	defer db.mu.Unlock()
   113  
   114  	if len(db.pastTries) >= maxPastTries {
   115  		copy(db.pastTries, db.pastTries[1:])
   116  		db.pastTries[len(db.pastTries)-1] = t
   117  	} else {
   118  		db.pastTries = append(db.pastTries, t)
   119  	}
   120  }
   121  
   122  // OpenStorageTrie opens the storage trie of an account.
   123  func (db *cachingDB) OpenStorageTrie(addrHash, root common.Hash) (Trie, error) {
   124  	return trie.NewSecure(root, db.db, 0)
   125  }
   126  
   127  // CopyTrie returns an independent copy of the given trie.
   128  func (db *cachingDB) CopyTrie(t Trie) Trie {
   129  	switch t := t.(type) {
   130  	case cachedTrie:
   131  		return cachedTrie{t.SecureTrie.Copy(), db}
   132  	case *trie.SecureTrie:
   133  		return t.Copy()
   134  	default:
   135  		panic(fmt.Errorf("unknown trie type %T", t))
   136  	}
   137  }
   138  
   139  // ContractCode retrieves a particular contract's code.
   140  func (db *cachingDB) ContractCode(addrHash, codeHash common.Hash) ([]byte, error) {
   141  	code, err := db.db.Node(codeHash)
   142  	if err == nil {
   143  		db.codeSizeCache.Add(codeHash, len(code))
   144  	}
   145  	return code, err
   146  }
   147  
   148  // ContractCodeSize retrieves a particular contracts code's size.
   149  func (db *cachingDB) ContractCodeSize(addrHash, codeHash common.Hash) (int, error) {
   150  	if cached, ok := db.codeSizeCache.Get(codeHash); ok {
   151  		return cached.(int), nil
   152  	}
   153  	code, err := db.ContractCode(addrHash, codeHash)
   154  	return len(code), err
   155  }
   156  
   157  // TrieDB retrieves any intermediate trie-node caching layer.
   158  func (db *cachingDB) TrieDB() *trie.Database {
   159  	return db.db
   160  }
   161  
   162  // cachedTrie inserts its trie into a cachingDB on commit.
   163  type cachedTrie struct {
   164  	*trie.SecureTrie
   165  	db *cachingDB
   166  }
   167  
   168  func (m cachedTrie) Commit(onleaf trie.LeafCallback) (common.Hash, error) {
   169  	root, err := m.SecureTrie.Commit(onleaf)
   170  	if err == nil {
   171  		m.db.pushTrie(m.SecureTrie)
   172  	}
   173  	return root, err
   174  }
   175  
   176  func (m cachedTrie) Prove(key []byte, fromLevel uint, proofDb ethdb.Putter) error {
   177  	return m.SecureTrie.Prove(key, fromLevel, proofDb)
   178  }