github.com/aigarnetwork/aigar@v0.0.0-20191115204914-d59a6eb70f8e/trie/secure_trie.go (about)

     1  //  Copyright 2018 The go-ethereum Authors
     2  //  Copyright 2019 The go-aigar Authors
     3  //  This file is part of the go-aigar library.
     4  //
     5  //  The go-aigar 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-aigar 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-aigar library. If not, see <http://www.gnu.org/licenses/>.
    17  
    18  package trie
    19  
    20  import (
    21  	"fmt"
    22  
    23  	"github.com/AigarNetwork/aigar/common"
    24  	"github.com/AigarNetwork/aigar/log"
    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  // New 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  // 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) (*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  	return &SecureTrie{trie: *trie}, nil
    64  }
    65  
    66  // Get returns the value for key stored in the trie.
    67  // The value bytes must not be modified by the caller.
    68  func (t *SecureTrie) Get(key []byte) []byte {
    69  	res, err := t.TryGet(key)
    70  	if err != nil {
    71  		log.Error(fmt.Sprintf("Unhandled trie error: %v", err))
    72  	}
    73  	return res
    74  }
    75  
    76  // TryGet returns the value for key stored in the trie.
    77  // The value bytes must not be modified by the caller.
    78  // If a node was not found in the database, a MissingNodeError is returned.
    79  func (t *SecureTrie) TryGet(key []byte) ([]byte, error) {
    80  	return t.trie.TryGet(t.hashKey(key))
    81  }
    82  
    83  // Update associates key with value in the trie. Subsequent calls to
    84  // Get will return value. If value has length zero, any existing value
    85  // is deleted from the trie and calls to Get will return nil.
    86  //
    87  // The value bytes must not be modified by the caller while they are
    88  // stored in the trie.
    89  func (t *SecureTrie) Update(key, value []byte) {
    90  	if err := t.TryUpdate(key, value); err != nil {
    91  		log.Error(fmt.Sprintf("Unhandled trie error: %v", err))
    92  	}
    93  }
    94  
    95  // TryUpdate associates key with value in the trie. Subsequent calls to
    96  // Get will return value. If value has length zero, any existing value
    97  // is deleted from the trie and calls to Get will return nil.
    98  //
    99  // The value bytes must not be modified by the caller while they are
   100  // stored in the trie.
   101  //
   102  // If a node was not found in the database, a MissingNodeError is returned.
   103  func (t *SecureTrie) TryUpdate(key, value []byte) error {
   104  	hk := t.hashKey(key)
   105  	err := t.trie.TryUpdate(hk, value)
   106  	if err != nil {
   107  		return err
   108  	}
   109  	t.getSecKeyCache()[string(hk)] = common.CopyBytes(key)
   110  	return nil
   111  }
   112  
   113  // Delete removes any existing value for key from the trie.
   114  func (t *SecureTrie) Delete(key []byte) {
   115  	if err := t.TryDelete(key); err != nil {
   116  		log.Error(fmt.Sprintf("Unhandled trie error: %v", err))
   117  	}
   118  }
   119  
   120  // TryDelete removes any existing value for key from the trie.
   121  // If a node was not found in the database, a MissingNodeError is returned.
   122  func (t *SecureTrie) TryDelete(key []byte) error {
   123  	hk := t.hashKey(key)
   124  	delete(t.getSecKeyCache(), string(hk))
   125  	return t.trie.TryDelete(hk)
   126  }
   127  
   128  // GetKey returns the sha3 preimage of a hashed key that was
   129  // previously used to store a value.
   130  func (t *SecureTrie) GetKey(shaKey []byte) []byte {
   131  	if key, ok := t.getSecKeyCache()[string(shaKey)]; ok {
   132  		return key
   133  	}
   134  	key, _ := t.trie.db.preimage(common.BytesToHash(shaKey))
   135  	return key
   136  }
   137  
   138  // Commit writes all nodes and the secure hash pre-images to the trie's database.
   139  // Nodes are stored with their sha3 hash as the key.
   140  //
   141  // Committing flushes nodes from memory. Subsequent Get calls will load nodes
   142  // from the database.
   143  func (t *SecureTrie) Commit(onleaf LeafCallback) (root common.Hash, err error) {
   144  	// Write all the pre-images to the actual disk database
   145  	if len(t.getSecKeyCache()) > 0 {
   146  		t.trie.db.lock.Lock()
   147  		for hk, key := range t.secKeyCache {
   148  			t.trie.db.insertPreimage(common.BytesToHash([]byte(hk)), key)
   149  		}
   150  		t.trie.db.lock.Unlock()
   151  
   152  		t.secKeyCache = make(map[string][]byte)
   153  	}
   154  	// Commit the trie to its intermediate node database
   155  	return t.trie.Commit(onleaf)
   156  }
   157  
   158  // Hash returns the root hash of SecureTrie. It does not write to the
   159  // database and can be used even if the trie doesn't have one.
   160  func (t *SecureTrie) Hash() common.Hash {
   161  	return t.trie.Hash()
   162  }
   163  
   164  // Copy returns a copy of SecureTrie.
   165  func (t *SecureTrie) Copy() *SecureTrie {
   166  	cpy := *t
   167  	return &cpy
   168  }
   169  
   170  // NodeIterator returns an iterator that returns nodes of the underlying trie. Iteration
   171  // starts at the key after the given start key.
   172  func (t *SecureTrie) NodeIterator(start []byte) NodeIterator {
   173  	return t.trie.NodeIterator(start)
   174  }
   175  
   176  // hashKey returns the hash of key as an ephemeral buffer.
   177  // The caller must not hold onto the return value because it will become
   178  // invalid on the next call to hashKey or secKey.
   179  func (t *SecureTrie) hashKey(key []byte) []byte {
   180  	h := newHasher(nil)
   181  	h.sha.Reset()
   182  	h.sha.Write(key)
   183  	buf := h.sha.Sum(t.hashKeyBuf[:0])
   184  	returnHasherToPool(h)
   185  	return buf
   186  }
   187  
   188  // getSecKeyCache returns the current secure key cache, creating a new one if
   189  // ownership changed (i.e. the current secure trie is a copy of another owning
   190  // the actual cache).
   191  func (t *SecureTrie) getSecKeyCache() map[string][]byte {
   192  	if t != t.secKeyCacheOwner {
   193  		t.secKeyCacheOwner = t
   194  		t.secKeyCache = make(map[string][]byte)
   195  	}
   196  	return t.secKeyCache
   197  }