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