github.com/cheng762/platon-go@v1.8.17-0.20190529111256-7deff2d7be26/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/PlatONnetwork/PlatON-Go/common"
    24  	"github.com/PlatONnetwork/PlatON-Go/ethdb"
    25  	"github.com/PlatONnetwork/PlatON-Go/trie"
    26  	"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  	ContractAbi(addrHash, abiHash common.Hash) ([]byte, error)
    62  }
    63  
    64  // Trie is a Ethereum Merkle Trie.
    65  type Trie interface {
    66  	TryGet(key []byte) ([]byte, error)
    67  	TryUpdate(key, value []byte) error
    68  	TryUpdateValue(key, value []byte) error
    69  	TryDelete(key []byte) error
    70  	Commit(onleaf trie.LeafCallback) (common.Hash, error)
    71  	Hash() common.Hash
    72  	NodeIterator(startKey []byte) trie.NodeIterator
    73  	GetKey([]byte) []byte // TODO(fjl): remove this when SecureTrie is removed
    74  	Prove(key []byte, fromLevel uint, proofDb ethdb.Putter) error
    75  }
    76  
    77  // NewDatabase creates a backing store for state. The returned database is safe for
    78  // concurrent use and retains cached trie nodes in memory. The pool is an optional
    79  // intermediate trie-node memory pool between the low level storage layer and the
    80  // high level trie abstraction.
    81  func NewDatabase(db ethdb.Database) Database {
    82  	//LRU
    83  	csc, _ := lru.New(codeSizeCacheSize)
    84  	return &cachingDB{
    85  		db:            trie.NewDatabase(db),
    86  		codeSizeCache: csc,
    87  	}
    88  }
    89  
    90  type cachingDB struct {
    91  	db            *trie.Database
    92  	mu            sync.Mutex
    93  	pastTries     []*trie.SecureTrie
    94  	codeSizeCache *lru.Cache
    95  }
    96  
    97  //OpenTrie opens the main account trie.
    98  func (db *cachingDB) OpenTrie(root common.Hash) (Trie, error) {
    99  	db.mu.Lock()
   100  	defer db.mu.Unlock()
   101  
   102  	for i := len(db.pastTries) - 1; i >= 0; i-- {
   103  		if db.pastTries[i].Hash() == root {
   104  			return cachedTrie{db.pastTries[i].Copy(), db}, nil
   105  		}
   106  	}
   107  
   108  	tr, err := trie.NewSecure(root, db.db, MaxTrieCacheGen)
   109  	if err != nil {
   110  		return nil, err
   111  	}
   112  	return cachedTrie{tr, db}, nil
   113  }
   114  
   115  func (db *cachingDB) pushTrie(t *trie.SecureTrie) {
   116  	db.mu.Lock()
   117  	defer db.mu.Unlock()
   118  
   119  	if len(db.pastTries) >= maxPastTries {
   120  		copy(db.pastTries, db.pastTries[1:])
   121  		db.pastTries[len(db.pastTries)-1] = t
   122  	} else {
   123  		db.pastTries = append(db.pastTries, t)
   124  	}
   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, 0)
   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 cachedTrie:
   136  		return cachedTrie{t.SecureTrie.Copy(), db}
   137  	case *trie.SecureTrie:
   138  		return t.Copy()
   139  	default:
   140  		panic(fmt.Errorf("unknown trie type %T", t))
   141  	}
   142  }
   143  
   144  // ContractCode retrieves a particular contract's code.
   145  func (db *cachingDB) ContractCode(addrHash, codeHash common.Hash) ([]byte, error) {
   146  	code, err := db.db.Node(codeHash)
   147  	if err == nil {
   148  		db.codeSizeCache.Add(codeHash, len(code))
   149  	}
   150  	return code, err
   151  }
   152  
   153  // ContractAbi retrieves a particular contract's abi.
   154  func (db *cachingDB) ContractAbi(addrHash, abiHash common.Hash) ([]byte, error) {
   155  	abi, err := db.db.Node(abiHash)
   156  	return abi, err
   157  }
   158  
   159  // ContractCodeSize retrieves a particular contracts code's size.
   160  func (db *cachingDB) ContractCodeSize(addrHash, codeHash common.Hash) (int, error) {
   161  	if cached, ok := db.codeSizeCache.Get(codeHash); ok {
   162  		return cached.(int), nil
   163  	}
   164  	code, err := db.ContractCode(addrHash, codeHash)
   165  	return len(code), err
   166  }
   167  
   168  // TrieDB retrieves any intermediate trie-node caching layer.
   169  func (db *cachingDB) TrieDB() *trie.Database {
   170  	return db.db
   171  }
   172  
   173  // cachedTrie inserts its trie into a cachingDB on commit.
   174  type cachedTrie struct {
   175  	*trie.SecureTrie
   176  	db *cachingDB
   177  }
   178  
   179  func (m cachedTrie) Commit(onleaf trie.LeafCallback) (common.Hash, error) {
   180  	root, err := m.SecureTrie.Commit(onleaf)
   181  	if err == nil {
   182  		m.db.pushTrie(m.SecureTrie)
   183  	}
   184  	return root, err
   185  }
   186  
   187  func (m cachedTrie) Prove(key []byte, fromLevel uint, proofDb ethdb.Putter) error {
   188  	return m.SecureTrie.Prove(key, fromLevel, proofDb)
   189  }