github.com/beyonderyue/gochain@v2.2.26+incompatible/trie/secure_trie.go (about)

     1  // Copyright 2015 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 trie
    18  
    19  import (
    20  	"fmt"
    21  
    22  	"github.com/gochain-io/gochain/common"
    23  	"github.com/gochain-io/gochain/log"
    24  )
    25  
    26  // SecureTrie wraps a trie with key hashing. In a secure trie, all
    27  // access operations hash the key using keccak256. This prevents
    28  // calling code from creating long chains of nodes that
    29  // increase the access time.
    30  //
    31  // Contrary to a regular trie, a SecureTrie can only be created with
    32  // New and must have an attached database. The database also stores
    33  // the preimage of each key.
    34  //
    35  // SecureTrie is not safe for concurrent use.
    36  type SecureTrie struct {
    37  	trie             Trie
    38  	hashKeyCache     map[string][common.HashLength]byte
    39  	hashKeyBuf       [common.HashLength]byte
    40  	secKeyCache      map[string][]byte
    41  	secKeyCacheOwner *SecureTrie // Pointer to self, replace the key cache on mismatch
    42  }
    43  
    44  // NewSecure creates a trie with an existing root node from a backing database
    45  // and optional intermediate in-memory node pool.
    46  //
    47  // If root is the zero hash or the sha3 hash of an empty string, the
    48  // trie is initially empty. Otherwise, New will panic if db is nil
    49  // and returns MissingNodeError if the root node cannot be found.
    50  //
    51  // Accessing the trie loads nodes from the database or node pool on demand.
    52  // Loaded nodes are kept around until their 'cache generation' expires.
    53  // A new cache generation is created by each call to Commit.
    54  // cachelimit sets the number of past cache generations to keep.
    55  func NewSecure(root common.Hash, db *Database, cachelimit uint16) (*SecureTrie, error) {
    56  	if db == nil {
    57  		panic("trie.NewSecure called without a database")
    58  	}
    59  	trie, err := New(root, db)
    60  	if err != nil {
    61  		return nil, err
    62  	}
    63  	trie.SetCacheLimit(cachelimit)
    64  	return &SecureTrie{
    65  		trie:         *trie,
    66  		hashKeyCache: make(map[string][common.HashLength]byte, 1024),
    67  	}, nil
    68  }
    69  
    70  // Get returns the value for key stored in the trie.
    71  // The value bytes must not be modified by the caller.
    72  func (t *SecureTrie) Get(key []byte) []byte {
    73  	res, err := t.TryGet(key)
    74  	if err != nil {
    75  		log.Error(fmt.Sprintf("Unhandled trie error: %v", err))
    76  	}
    77  	return res
    78  }
    79  
    80  // TryGet returns the value for key stored in the trie.
    81  // The value bytes must not be modified by the caller.
    82  // If a node was not found in the database, a MissingNodeError is returned.
    83  func (t *SecureTrie) TryGet(key []byte) ([]byte, error) {
    84  	return t.trie.TryGet(t.hashKey(key))
    85  }
    86  
    87  // Update associates key with value in the trie. Subsequent calls to
    88  // Get will return value. If value has length zero, any existing value
    89  // is deleted from the trie and calls to Get will return nil.
    90  //
    91  // The value bytes must not be modified by the caller while they are
    92  // stored in the trie.
    93  func (t *SecureTrie) Update(key, value []byte) {
    94  	if err := t.TryUpdate(key, value); err != nil {
    95  		log.Error(fmt.Sprintf("Unhandled trie error: %v", err))
    96  	}
    97  }
    98  
    99  // TryUpdate associates key with value in the trie. Subsequent calls to
   100  // Get will return value. If value has length zero, any existing value
   101  // is deleted from the trie and calls to Get will return nil.
   102  //
   103  // The value bytes must not be modified by the caller while they are
   104  // stored in the trie.
   105  //
   106  // If a node was not found in the database, a MissingNodeError is returned.
   107  func (t *SecureTrie) TryUpdate(key, value []byte) error {
   108  	hk := t.hashKey(key)
   109  	err := t.trie.TryUpdate(hk, value)
   110  	if err != nil {
   111  		return err
   112  	}
   113  	t.getSecKeyCache()[string(hk)] = common.CopyBytes(key)
   114  	return nil
   115  }
   116  
   117  // Delete removes any existing value for key from the trie.
   118  func (t *SecureTrie) Delete(key []byte) {
   119  	if err := t.TryDelete(key); err != nil {
   120  		log.Error(fmt.Sprintf("Unhandled trie error: %v", err))
   121  	}
   122  }
   123  
   124  // TryDelete removes any existing value for key from the trie.
   125  // If a node was not found in the database, a MissingNodeError is returned.
   126  func (t *SecureTrie) TryDelete(key []byte) error {
   127  	hk := t.hashKey(key)
   128  	delete(t.getSecKeyCache(), string(hk))
   129  	return t.trie.TryDelete(hk)
   130  }
   131  
   132  // GetKey returns the sha3 preimage of a hashed key that was
   133  // previously used to store a value.
   134  func (t *SecureTrie) GetKey(shaKey []byte) []byte {
   135  	if key, ok := t.getSecKeyCache()[string(shaKey)]; ok {
   136  		return key
   137  	}
   138  	key, _ := t.trie.db.preimage(common.BytesToHash(shaKey))
   139  	return key
   140  }
   141  
   142  // Commit writes all nodes and the secure hash pre-images to the trie's database.
   143  // Nodes are stored with their sha3 hash as the key.
   144  //
   145  // Committing flushes nodes from memory. Subsequent Get calls will load nodes
   146  // from the database.
   147  func (t *SecureTrie) Commit(onleaf LeafCallback) (root common.Hash, err error) {
   148  	// Write all the pre-images to the actual disk database
   149  	if len(t.getSecKeyCache()) > 0 {
   150  		t.trie.db.lock.Lock()
   151  		for hk, key := range t.secKeyCache {
   152  			t.trie.db.insertPreimage(common.BytesToHash([]byte(hk)), key)
   153  		}
   154  		t.trie.db.lock.Unlock()
   155  
   156  		t.secKeyCache = make(map[string][]byte)
   157  	}
   158  	// Commit the trie to its intermediate node database
   159  	return t.trie.Commit(onleaf)
   160  }
   161  
   162  // Hash returns the root hash of SecureTrie. It does not write to the
   163  // database and can be used even if the trie doesn't have one.
   164  func (t *SecureTrie) Hash() common.Hash {
   165  	return t.trie.Hash()
   166  }
   167  
   168  // Root returns the root hash of SecureTrie.
   169  // Deprecated: use Hash instead.
   170  func (t *SecureTrie) Root() []byte {
   171  	return t.trie.Root()
   172  }
   173  
   174  // Copy returns a copy of SecureTrie.
   175  func (t *SecureTrie) Copy() *SecureTrie {
   176  	other := *t
   177  	other.hashKeyCache = make(map[string][common.HashLength]byte, len(t.hashKeyCache))
   178  	for k, v := range t.hashKeyCache {
   179  		other.hashKeyCache[k] = v
   180  	}
   181  	return &other
   182  }
   183  
   184  // NodeIterator returns an iterator that returns nodes of the underlying trie. Iteration
   185  // starts at the key after the given start key.
   186  func (t *SecureTrie) NodeIterator(start []byte) NodeIterator {
   187  	return t.trie.NodeIterator(start)
   188  }
   189  
   190  // hashKey returns the hash of key as an ephemeral buffer.
   191  // The caller must not hold onto the return value because it will become
   192  // invalid on the next call to hashKey or secKey.
   193  func (t *SecureTrie) hashKey(key []byte) []byte {
   194  	// Use cache version, if available.
   195  	if buf, ok := t.hashKeyCache[string(key)]; ok {
   196  		return buf[:]
   197  	}
   198  
   199  	h := newHasher(0, 0, nil)
   200  	h.sha.Reset()
   201  	h.sha.Write(key)
   202  	buf := h.sha.Sum(t.hashKeyBuf[:0])
   203  	returnHasherToPool(h)
   204  
   205  	// Copy result to the cache.
   206  	t.hashKeyCache[string(key)] = t.hashKeyBuf
   207  
   208  	return buf
   209  }
   210  
   211  // getSecKeyCache returns the current secure key cache, creating a new one if
   212  // ownership changed (i.e. the current secure trie is a copy of another owning
   213  // the actual cache).
   214  func (t *SecureTrie) getSecKeyCache() map[string][]byte {
   215  	if t != t.secKeyCacheOwner {
   216  		t.secKeyCacheOwner = t
   217  		t.secKeyCache = make(map[string][]byte)
   218  	}
   219  	return t.secKeyCache
   220  }