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