github.com/arieschain/arieschain@v0.0.0-20191023063405-37c074544356/core/state/database.go (about)

     1  package state
     2  
     3  import (
     4  	"fmt"
     5  	"sync"
     6  
     7  	"github.com/quickchainproject/quickchain/common"
     8  	"github.com/quickchainproject/quickchain/qctdb"
     9  	"github.com/quickchainproject/quickchain/trie"
    10  	lru "github.com/hashicorp/golang-lru"
    11  )
    12  
    13  // Trie cache generation limit after which to evict trie nodes from memory.
    14  var MaxTrieCacheGen = uint16(120)
    15  
    16  const (
    17  	// Number of past tries to keep. This value is chosen such that
    18  	// reasonable chain reorg depths will hit an existing trie.
    19  	maxPastTries = 12
    20  
    21  	// Number of codehash->size associations to keep.
    22  	codeSizeCacheSize = 100000
    23  )
    24  
    25  // Database wraps access to tries and contract code.
    26  type Database interface {
    27  	// OpenTrie opens the main account trie.
    28  	OpenTrie(root common.Hash) (Trie, error)
    29  
    30  	// OpenStorageTrie opens the storage trie of an account.
    31  	OpenStorageTrie(addrHash, root common.Hash) (Trie, error)
    32  
    33  	// CopyTrie returns an independent copy of the given trie.
    34  	CopyTrie(Trie) Trie
    35  
    36  	// ContractCode retrieves a particular contract's code.
    37  	ContractCode(addrHash, codeHash common.Hash) ([]byte, error)
    38  
    39  	// ContractCodeSize retrieves a particular contracts code's size.
    40  	ContractCodeSize(addrHash, codeHash common.Hash) (int, error)
    41  
    42  	// TrieDB retrieves the low level trie database used for data storage.
    43  	TrieDB() *trie.Database
    44  }
    45  
    46  // Trie is a Ethereum Merkle Trie.
    47  type Trie interface {
    48  	TryGet(key []byte) ([]byte, error)
    49  	TryUpdate(key, value []byte) error
    50  	TryDelete(key []byte) error
    51  	Commit(onleaf trie.LeafCallback) (common.Hash, error)
    52  	Hash() common.Hash
    53  	NodeIterator(startKey []byte) trie.NodeIterator
    54  	GetKey([]byte) []byte // TODO(fjl): remove this when SecureTrie is removed
    55  	Prove(key []byte, fromLevel uint, proofDb qctdb.Putter) error
    56  }
    57  
    58  // NewDatabase creates a backing store for state. The returned database is safe for
    59  // concurrent use and retains cached trie nodes in memory. The pool is an optional
    60  // intermediate trie-node memory pool between the low level storage layer and the
    61  // high level trie abstraction.
    62  func NewDatabase(db qctdb.Database) Database {
    63  	csc, _ := lru.New(codeSizeCacheSize)
    64  	return &cachingDB{
    65  		db:            trie.NewDatabase(db),
    66  		codeSizeCache: csc,
    67  	}
    68  }
    69  
    70  type cachingDB struct {
    71  	db            *trie.Database
    72  	mu            sync.Mutex
    73  	pastTries     []*trie.SecureTrie
    74  	codeSizeCache *lru.Cache
    75  }
    76  
    77  // OpenTrie opens the main account trie.
    78  func (db *cachingDB) OpenTrie(root common.Hash) (Trie, error) {
    79  	db.mu.Lock()
    80  	defer db.mu.Unlock()
    81  
    82  	for i := len(db.pastTries) - 1; i >= 0; i-- {
    83  		if db.pastTries[i].Hash() == root {
    84  			return cachedTrie{db.pastTries[i].Copy(), db}, nil
    85  		}
    86  	}
    87  	tr, err := trie.NewSecure(root, db.db, MaxTrieCacheGen)
    88  	if err != nil {
    89  		return nil, err
    90  	}
    91  	return cachedTrie{tr, db}, nil
    92  }
    93  
    94  func (db *cachingDB) pushTrie(t *trie.SecureTrie) {
    95  	db.mu.Lock()
    96  	defer db.mu.Unlock()
    97  
    98  	if len(db.pastTries) >= maxPastTries {
    99  		copy(db.pastTries, db.pastTries[1:])
   100  		db.pastTries[len(db.pastTries)-1] = t
   101  	} else {
   102  		db.pastTries = append(db.pastTries, t)
   103  	}
   104  }
   105  
   106  // OpenStorageTrie opens the storage trie of an account.
   107  func (db *cachingDB) OpenStorageTrie(addrHash, root common.Hash) (Trie, error) {
   108  	return trie.NewSecure(root, db.db, 0)
   109  }
   110  
   111  // CopyTrie returns an independent copy of the given trie.
   112  func (db *cachingDB) CopyTrie(t Trie) Trie {
   113  	switch t := t.(type) {
   114  	case cachedTrie:
   115  		return cachedTrie{t.SecureTrie.Copy(), db}
   116  	case *trie.SecureTrie:
   117  		return t.Copy()
   118  	default:
   119  		panic(fmt.Errorf("unknown trie type %T", t))
   120  	}
   121  }
   122  
   123  // ContractCode retrieves a particular contract's code.
   124  func (db *cachingDB) ContractCode(addrHash, codeHash common.Hash) ([]byte, error) {
   125  	code, err := db.db.Node(codeHash)
   126  	if err == nil {
   127  		db.codeSizeCache.Add(codeHash, len(code))
   128  	}
   129  	return code, err
   130  }
   131  
   132  // ContractCodeSize retrieves a particular contracts code's size.
   133  func (db *cachingDB) ContractCodeSize(addrHash, codeHash common.Hash) (int, error) {
   134  	if cached, ok := db.codeSizeCache.Get(codeHash); ok {
   135  		return cached.(int), nil
   136  	}
   137  	code, err := db.ContractCode(addrHash, codeHash)
   138  	return len(code), err
   139  }
   140  
   141  // TrieDB retrieves any intermediate trie-node caching layer.
   142  func (db *cachingDB) TrieDB() *trie.Database {
   143  	return db.db
   144  }
   145  
   146  // cachedTrie inserts its trie into a cachingDB on commit.
   147  type cachedTrie struct {
   148  	*trie.SecureTrie
   149  	db *cachingDB
   150  }
   151  
   152  func (m cachedTrie) Commit(onleaf trie.LeafCallback) (common.Hash, error) {
   153  	root, err := m.SecureTrie.Commit(onleaf)
   154  	if err == nil {
   155  		m.db.pushTrie(m.SecureTrie)
   156  	}
   157  	return root, err
   158  }
   159  
   160  func (m cachedTrie) Prove(key []byte, fromLevel uint, proofDb qctdb.Putter) error {
   161  	return m.SecureTrie.Prove(key, fromLevel, proofDb)
   162  }