github.com/jimmyx0x/go-ethereum@v1.10.28/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  	"github.com/ethereum/go-ethereum/common"
    21  	"github.com/ethereum/go-ethereum/core/types"
    22  	"github.com/ethereum/go-ethereum/log"
    23  	"github.com/ethereum/go-ethereum/rlp"
    24  )
    25  
    26  // SecureTrie is the old name of StateTrie.
    27  // Deprecated: use StateTrie.
    28  type SecureTrie = StateTrie
    29  
    30  // NewSecure creates a new StateTrie.
    31  // Deprecated: use NewStateTrie.
    32  func NewSecure(stateRoot common.Hash, owner common.Hash, root common.Hash, db *Database) (*SecureTrie, error) {
    33  	id := &ID{
    34  		StateRoot: stateRoot,
    35  		Owner:     owner,
    36  		Root:      root,
    37  	}
    38  	return NewStateTrie(id, db)
    39  }
    40  
    41  // StateTrie wraps a trie with key hashing. In a stateTrie trie, all
    42  // access operations hash the key using keccak256. This prevents
    43  // calling code from creating long chains of nodes that
    44  // increase the access time.
    45  //
    46  // Contrary to a regular trie, a StateTrie can only be created with
    47  // New and must have an attached database. The database also stores
    48  // the preimage of each key if preimage recording is enabled.
    49  //
    50  // StateTrie is not safe for concurrent use.
    51  type StateTrie struct {
    52  	trie             Trie
    53  	preimages        *preimageStore
    54  	hashKeyBuf       [common.HashLength]byte
    55  	secKeyCache      map[string][]byte
    56  	secKeyCacheOwner *StateTrie // Pointer to self, replace the key cache on mismatch
    57  }
    58  
    59  // NewStateTrie creates a trie with an existing root node from a backing database.
    60  //
    61  // If root is the zero hash or the sha3 hash of an empty string, the
    62  // trie is initially empty. Otherwise, New will panic if db is nil
    63  // and returns MissingNodeError if the root node cannot be found.
    64  func NewStateTrie(id *ID, db *Database) (*StateTrie, error) {
    65  	if db == nil {
    66  		panic("trie.NewStateTrie called without a database")
    67  	}
    68  	trie, err := New(id, db)
    69  	if err != nil {
    70  		return nil, err
    71  	}
    72  	return &StateTrie{trie: *trie, preimages: db.preimages}, nil
    73  }
    74  
    75  // Get returns the value for key stored in the trie.
    76  // The value bytes must not be modified by the caller.
    77  func (t *StateTrie) Get(key []byte) []byte {
    78  	res, err := t.TryGet(key)
    79  	if err != nil {
    80  		log.Error("Unhandled trie error in StateTrie.Get", "err", err)
    81  	}
    82  	return res
    83  }
    84  
    85  // TryGet returns the value for key stored in the trie.
    86  // The value bytes must not be modified by the caller.
    87  // If the specified node is not in the trie, nil will be returned.
    88  // If a trie node is not found in the database, a MissingNodeError is returned.
    89  func (t *StateTrie) TryGet(key []byte) ([]byte, error) {
    90  	return t.trie.TryGet(t.hashKey(key))
    91  }
    92  
    93  // TryGetAccount attempts to retrieve an account with provided account address.
    94  // If the specified account is not in the trie, nil will be returned.
    95  // If a trie node is not found in the database, a MissingNodeError is returned.
    96  func (t *StateTrie) TryGetAccount(address common.Address) (*types.StateAccount, error) {
    97  	res, err := t.trie.TryGet(t.hashKey(address.Bytes()))
    98  	if res == nil || err != nil {
    99  		return nil, err
   100  	}
   101  	ret := new(types.StateAccount)
   102  	err = rlp.DecodeBytes(res, ret)
   103  	return ret, err
   104  }
   105  
   106  // TryGetAccountByHash does the same thing as TryGetAccount, however
   107  // it expects an account hash that is the hash of address. This constitutes an
   108  // abstraction leak, since the client code needs to know the key format.
   109  func (t *StateTrie) TryGetAccountByHash(addrHash common.Hash) (*types.StateAccount, error) {
   110  	res, err := t.trie.TryGet(addrHash.Bytes())
   111  	if res == nil || err != nil {
   112  		return nil, err
   113  	}
   114  	ret := new(types.StateAccount)
   115  	err = rlp.DecodeBytes(res, ret)
   116  	return ret, err
   117  }
   118  
   119  // TryGetNode attempts to retrieve a trie node by compact-encoded path. It is not
   120  // possible to use keybyte-encoding as the path might contain odd nibbles.
   121  // If the specified trie node is not in the trie, nil will be returned.
   122  // If a trie node is not found in the database, a MissingNodeError is returned.
   123  func (t *StateTrie) TryGetNode(path []byte) ([]byte, int, error) {
   124  	return t.trie.TryGetNode(path)
   125  }
   126  
   127  // Update associates key with value in the trie. Subsequent calls to
   128  // Get will return value. If value has length zero, any existing value
   129  // is deleted from the trie and calls to Get will return nil.
   130  //
   131  // The value bytes must not be modified by the caller while they are
   132  // stored in the trie.
   133  func (t *StateTrie) Update(key, value []byte) {
   134  	if err := t.TryUpdate(key, value); err != nil {
   135  		log.Error("Unhandled trie error in StateTrie.Update", "err", err)
   136  	}
   137  }
   138  
   139  // TryUpdate associates key with value in the trie. Subsequent calls to
   140  // Get will return value. If value has length zero, any existing value
   141  // is deleted from the trie and calls to Get will return nil.
   142  //
   143  // The value bytes must not be modified by the caller while they are
   144  // stored in the trie.
   145  //
   146  // If a node is not found in the database, a MissingNodeError is returned.
   147  func (t *StateTrie) TryUpdate(key, value []byte) error {
   148  	hk := t.hashKey(key)
   149  	err := t.trie.TryUpdate(hk, value)
   150  	if err != nil {
   151  		return err
   152  	}
   153  	t.getSecKeyCache()[string(hk)] = common.CopyBytes(key)
   154  	return nil
   155  }
   156  
   157  // TryUpdateAccount account will abstract the write of an account to the
   158  // secure trie.
   159  func (t *StateTrie) TryUpdateAccount(address common.Address, acc *types.StateAccount) error {
   160  	hk := t.hashKey(address.Bytes())
   161  	data, err := rlp.EncodeToBytes(acc)
   162  	if err != nil {
   163  		return err
   164  	}
   165  	if err := t.trie.TryUpdate(hk, data); err != nil {
   166  		return err
   167  	}
   168  	t.getSecKeyCache()[string(hk)] = address.Bytes()
   169  	return nil
   170  }
   171  
   172  // Delete removes any existing value for key from the trie.
   173  func (t *StateTrie) Delete(key []byte) {
   174  	if err := t.TryDelete(key); err != nil {
   175  		log.Error("Unhandled trie error in StateTrie.Delete", "err", err)
   176  	}
   177  }
   178  
   179  // TryDelete removes any existing value for key from the trie.
   180  // If the specified trie node is not in the trie, nothing will be changed.
   181  // If a node is not found in the database, a MissingNodeError is returned.
   182  func (t *StateTrie) TryDelete(key []byte) error {
   183  	hk := t.hashKey(key)
   184  	delete(t.getSecKeyCache(), string(hk))
   185  	return t.trie.TryDelete(hk)
   186  }
   187  
   188  // TryDeleteAccount abstracts an account deletion from the trie.
   189  func (t *StateTrie) TryDeleteAccount(address common.Address) error {
   190  	hk := t.hashKey(address.Bytes())
   191  	delete(t.getSecKeyCache(), string(hk))
   192  	return t.trie.TryDelete(hk)
   193  }
   194  
   195  // GetKey returns the sha3 preimage of a hashed key that was
   196  // previously used to store a value.
   197  func (t *StateTrie) GetKey(shaKey []byte) []byte {
   198  	if key, ok := t.getSecKeyCache()[string(shaKey)]; ok {
   199  		return key
   200  	}
   201  	if t.preimages == nil {
   202  		return nil
   203  	}
   204  	return t.preimages.preimage(common.BytesToHash(shaKey))
   205  }
   206  
   207  // Commit collects all dirty nodes in the trie and replaces them with the
   208  // corresponding node hash. All collected nodes (including dirty leaves if
   209  // collectLeaf is true) will be encapsulated into a nodeset for return.
   210  // The returned nodeset can be nil if the trie is clean (nothing to commit).
   211  // All cached preimages will be also flushed if preimages recording is enabled.
   212  // Once the trie is committed, it's not usable anymore. A new trie must
   213  // be created with new root and updated trie database for following usage
   214  func (t *StateTrie) Commit(collectLeaf bool) (common.Hash, *NodeSet, error) {
   215  	// Write all the pre-images to the actual disk database
   216  	if len(t.getSecKeyCache()) > 0 {
   217  		if t.preimages != nil {
   218  			preimages := make(map[common.Hash][]byte)
   219  			for hk, key := range t.secKeyCache {
   220  				preimages[common.BytesToHash([]byte(hk))] = key
   221  			}
   222  			t.preimages.insertPreimage(preimages)
   223  		}
   224  		t.secKeyCache = make(map[string][]byte)
   225  	}
   226  	// Commit the trie and return its modified nodeset.
   227  	return t.trie.Commit(collectLeaf)
   228  }
   229  
   230  // Hash returns the root hash of StateTrie. It does not write to the
   231  // database and can be used even if the trie doesn't have one.
   232  func (t *StateTrie) Hash() common.Hash {
   233  	return t.trie.Hash()
   234  }
   235  
   236  // Copy returns a copy of StateTrie.
   237  func (t *StateTrie) Copy() *StateTrie {
   238  	return &StateTrie{
   239  		trie:        *t.trie.Copy(),
   240  		preimages:   t.preimages,
   241  		secKeyCache: t.secKeyCache,
   242  	}
   243  }
   244  
   245  // NodeIterator returns an iterator that returns nodes of the underlying trie. Iteration
   246  // starts at the key after the given start key.
   247  func (t *StateTrie) NodeIterator(start []byte) NodeIterator {
   248  	return t.trie.NodeIterator(start)
   249  }
   250  
   251  // hashKey returns the hash of key as an ephemeral buffer.
   252  // The caller must not hold onto the return value because it will become
   253  // invalid on the next call to hashKey or secKey.
   254  func (t *StateTrie) hashKey(key []byte) []byte {
   255  	h := newHasher(false)
   256  	h.sha.Reset()
   257  	h.sha.Write(key)
   258  	h.sha.Read(t.hashKeyBuf[:])
   259  	returnHasherToPool(h)
   260  	return t.hashKeyBuf[:]
   261  }
   262  
   263  // getSecKeyCache returns the current secure key cache, creating a new one if
   264  // ownership changed (i.e. the current secure trie is a copy of another owning
   265  // the actual cache).
   266  func (t *StateTrie) getSecKeyCache() map[string][]byte {
   267  	if t != t.secKeyCacheOwner {
   268  		t.secKeyCacheOwner = t
   269  		t.secKeyCache = make(map[string][]byte)
   270  	}
   271  	return t.secKeyCache
   272  }