github.com/klaytn/klaytn@v1.10.2/storage/statedb/secure_trie.go (about)

     1  // Modifications Copyright 2018 The klaytn Authors
     2  // Copyright 2015 The go-ethereum Authors
     3  // This file is part of the go-ethereum library.
     4  //
     5  // The go-ethereum library is free software: you can redistribute it and/or modify
     6  // it under the terms of the GNU Lesser General Public License as published by
     7  // the Free Software Foundation, either version 3 of the License, or
     8  // (at your option) any later version.
     9  //
    10  // The go-ethereum library is distributed in the hope that it will be useful,
    11  // but WITHOUT ANY WARRANTY; without even the implied warranty of
    12  // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
    13  // GNU Lesser General Public License for more details.
    14  //
    15  // You should have received a copy of the GNU Lesser General Public License
    16  // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
    17  //
    18  // This file is derived from trie/secure_trie.go (2018/06/04).
    19  // Modified and improved for the klaytn development.
    20  
    21  package statedb
    22  
    23  import (
    24  	"github.com/klaytn/klaytn/common"
    25  )
    26  
    27  // SecureTrie wraps a trie with key hashing. In a secure trie, all
    28  // access operations hash the key using keccak256. This prevents
    29  // calling code from creating long chains of nodes that
    30  // increase the access time.
    31  //
    32  // Contrary to a regular trie, a SecureTrie can only be created with
    33  // NewTrie and must have an attached database. The database also stores
    34  // the preimage of each key.
    35  //
    36  // SecureTrie is not safe for concurrent use.
    37  type SecureTrie struct {
    38  	trie             Trie
    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  // NewSecureTrie 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, NewTrie 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 NewSecureTrie(root common.Hash, db *Database) (*SecureTrie, error) {
    56  	if db == nil {
    57  		panic("statedb.NewSecureTrie called without a database")
    58  	}
    59  	trie, err := NewTrie(root, db)
    60  	if err != nil {
    61  		return nil, err
    62  	}
    63  	return &SecureTrie{trie: *trie}, nil
    64  }
    65  
    66  func NewSecureTrieForPrefetching(root common.Hash, db *Database) (*SecureTrie, error) {
    67  	if db == nil {
    68  		panic("statedb.NewSecureTrieForPrefetching called without a database")
    69  	}
    70  	trie, err := NewTrieForPrefetching(root, db)
    71  	if err != nil {
    72  		return nil, err
    73  	}
    74  	return &SecureTrie{trie: *trie}, nil
    75  }
    76  
    77  // Get returns the value for key stored in the trie.
    78  // The value bytes must not be modified by the caller.
    79  func (t *SecureTrie) Get(key []byte) []byte {
    80  	res, err := t.TryGet(key)
    81  	if err != nil {
    82  		logger.Error("Unhandled trie error in SecureTrie.Get", "err", err)
    83  	}
    84  	return res
    85  }
    86  
    87  // TryGet returns the value for key stored in the trie.
    88  // The value bytes must not be modified by the caller.
    89  // If a node was not found in the database, a MissingNodeError is returned.
    90  func (t *SecureTrie) TryGet(key []byte) ([]byte, error) {
    91  	return t.trie.TryGet(t.hashKey(key))
    92  }
    93  
    94  // TryGetNode attempts to retrieve a trie node by compact-encoded path. It is not
    95  // possible to use keybyte-encoding as the path might contain odd nibbles.
    96  func (t *SecureTrie) TryGetNode(path []byte) ([]byte, int, error) {
    97  	return t.trie.TryGetNode(path)
    98  }
    99  
   100  // Update associates key with value in the trie. Subsequent calls to
   101  // Get will return value. If value has length zero, any existing value
   102  // is deleted from the trie and calls to Get will return nil.
   103  //
   104  // The value bytes must not be modified by the caller while they are
   105  // stored in the trie.
   106  func (t *SecureTrie) Update(key, value []byte) {
   107  	if err := t.TryUpdate(key, value); err != nil {
   108  		logger.Error("Unhandled trie error in SecureTrie.Update", "err", err)
   109  	}
   110  }
   111  
   112  // TryUpdate associates key with value in the trie. Subsequent calls to
   113  // Get will return value. If value has length zero, any existing value
   114  // is deleted from the trie and calls to Get will return nil.
   115  //
   116  // The value bytes must not be modified by the caller while they are
   117  // stored in the trie.
   118  //
   119  // If a node was not found in the database, a MissingNodeError is returned.
   120  func (t *SecureTrie) TryUpdate(key, value []byte) error {
   121  	hk := t.hashKey(key)
   122  	err := t.trie.TryUpdate(hk, value)
   123  	if err != nil {
   124  		return err
   125  	}
   126  	t.getSecKeyCache()[string(hk)] = common.CopyBytes(key)
   127  	return nil
   128  }
   129  
   130  // TryUpdateWithKeys does basically same thing that TryUpdate does.
   131  // Only difference is that it uses pre-encoded hashKey and hexKey.
   132  func (t *SecureTrie) TryUpdateWithKeys(key, hashKey, hexKey, value []byte) error {
   133  	err := t.trie.TryUpdateWithHexKey(hexKey, value)
   134  	if err != nil {
   135  		return err
   136  	}
   137  	t.getSecKeyCache()[string(hashKey)] = common.CopyBytes(key)
   138  	return nil
   139  }
   140  
   141  // Delete removes any existing value for key from the trie.
   142  func (t *SecureTrie) Delete(key []byte) {
   143  	if err := t.TryDelete(key); err != nil {
   144  		logger.Error("Unhandled trie error in SecureTrie.Delete", "err", err)
   145  	}
   146  }
   147  
   148  // TryDelete removes any existing value for key from the trie.
   149  // If a node was not found in the database, a MissingNodeError is returned.
   150  func (t *SecureTrie) TryDelete(key []byte) error {
   151  	hk := t.hashKey(key)
   152  	delete(t.getSecKeyCache(), string(hk))
   153  	return t.trie.TryDelete(hk)
   154  }
   155  
   156  // GetKey returns the sha3 preimage of a hashed key that was
   157  // previously used to store a value.
   158  func (t *SecureTrie) GetKey(shaKey []byte) []byte {
   159  	if key, ok := t.getSecKeyCache()[string(shaKey)]; ok {
   160  		return key
   161  	}
   162  	key, _ := t.trie.db.preimage(common.BytesToHash(shaKey))
   163  	return key
   164  }
   165  
   166  // Commit writes all nodes and the secure hash pre-images to the trie's database.
   167  // Nodes are stored with their sha3 hash as the key.
   168  //
   169  // Committing flushes nodes from memory. Subsequent Get calls will load nodes
   170  // from the database.
   171  func (t *SecureTrie) Commit(onleaf LeafCallback) (root common.Hash, err error) {
   172  	// Write all the pre-images to the actual disk database
   173  	if len(t.getSecKeyCache()) > 0 {
   174  		t.trie.db.lock.Lock()
   175  		for hk, key := range t.secKeyCache {
   176  			t.trie.db.insertPreimage(common.BytesToHash([]byte(hk)), key)
   177  		}
   178  		t.trie.db.lock.Unlock()
   179  
   180  		t.secKeyCache = make(map[string][]byte)
   181  	}
   182  	// Commit the trie to its intermediate node database
   183  	return t.trie.Commit(onleaf)
   184  }
   185  
   186  func (t *SecureTrie) Hash() common.Hash {
   187  	return t.trie.Hash()
   188  }
   189  
   190  func (t *SecureTrie) Copy() *SecureTrie {
   191  	cpy := *t
   192  	return &cpy
   193  }
   194  
   195  // NodeIterator returns an iterator that returns nodes of the underlying trie. Iteration
   196  // starts at the key after the given start key.
   197  func (t *SecureTrie) NodeIterator(start []byte) NodeIterator {
   198  	return t.trie.NodeIterator(start)
   199  }
   200  
   201  // hashKey returns the hash of key as an ephemeral buffer.
   202  // The caller must not hold onto the return value because it will become
   203  // invalid on the next call to hashKey or secKey.
   204  func (t *SecureTrie) hashKey(key []byte) []byte {
   205  	h := newHasher(nil)
   206  	h.sha.Reset()
   207  	h.sha.Write(key)
   208  	buf := h.sha.Sum(t.hashKeyBuf[:0])
   209  	returnHasherToPool(h)
   210  	return buf
   211  }
   212  
   213  // getSecKeyCache returns the current secure key cache, creating a new one if
   214  // ownership changed (i.e. the current secure trie is a copy of another owning
   215  // the actual cache).
   216  func (t *SecureTrie) getSecKeyCache() map[string][]byte {
   217  	if t != t.secKeyCacheOwner {
   218  		t.secKeyCacheOwner = t
   219  		t.secKeyCache = make(map[string][]byte)
   220  	}
   221  	return t.secKeyCache
   222  }