-
Notifications
You must be signed in to change notification settings - Fork 20
/
Copy pathstatedb.go
557 lines (488 loc) · 16.5 KB
/
statedb.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
package statedb
import (
"errors"
"fmt"
"math/big"
"sort"
"github.com/ethereum/go-ethereum/common"
ethtypes "github.com/ethereum/go-ethereum/core/types"
"github.com/ethereum/go-ethereum/core/vm"
"github.com/ethereum/go-ethereum/crypto"
"github.com/cosmos/evm/x/vm/types"
errorsmod "cosmossdk.io/errors"
storetypes "cosmossdk.io/store/types"
sdk "github.com/cosmos/cosmos-sdk/types"
)
// revision is the identifier of a version of state.
// it consists of an auto-increment id and a journal index.
// it's safer to use than using journal index alone.
type revision struct {
id int
journalIndex int
}
var _ vm.StateDB = &StateDB{}
// StateDB structs within the ethereum protocol are used to store anything
// within the merkle trie. StateDBs take care of caching and storing
// nested states. It's the general query interface to retrieve:
// * Contracts
// * Accounts
type StateDB struct {
keeper Keeper
ctx sdk.Context
// cacheCtx is used on precompile calls. It allows to commit the current journal
// entries to get the updated state in for the precompile call.
cacheCtx sdk.Context
// writeCache function contains all the changes related to precompile calls.
writeCache func()
// Journal of state modifications. This is the backbone of
// Snapshot and RevertToSnapshot.
journal *journal
validRevisions []revision
nextRevisionID int
stateObjects map[common.Address]*stateObject
txConfig TxConfig
// The refund counter, also used by state transitioning.
refund uint64
// Per-transaction logs
logs []*ethtypes.Log
// Per-transaction access list
accessList *accessList
// The count of calls to precompiles
precompileCallsCounter uint8
}
// New creates a new state from a given trie.
func New(ctx sdk.Context, keeper Keeper, txConfig TxConfig) *StateDB {
return &StateDB{
keeper: keeper,
ctx: ctx,
stateObjects: make(map[common.Address]*stateObject),
journal: newJournal(),
accessList: newAccessList(),
txConfig: txConfig,
}
}
// Keeper returns the underlying `Keeper`
func (s *StateDB) Keeper() Keeper {
return s.keeper
}
// GetContext returns the transaction Context.
func (s *StateDB) GetContext() sdk.Context {
return s.ctx
}
// GetCacheContext returns the stateDB CacheContext.
func (s *StateDB) GetCacheContext() (sdk.Context, error) {
if s.writeCache == nil {
err := s.cache()
if err != nil {
return s.ctx, err
}
}
return s.cacheCtx, nil
}
// MultiStoreSnapshot returns a copy of the stateDB CacheMultiStore.
func (s *StateDB) MultiStoreSnapshot() storetypes.CacheMultiStore {
if s.writeCache == nil {
err := s.cache()
if err != nil {
return s.ctx.MultiStore().CacheMultiStore()
}
}
// the cacheCtx multi store is already a CacheMultiStore
// so we need to pass a copy of the current state of it
cms := s.cacheCtx.MultiStore().(storetypes.CacheMultiStore)
snapshot := cms.CacheMultiStore()
return snapshot
}
// cache creates the stateDB cache context
func (s *StateDB) cache() error {
if s.ctx.MultiStore() == nil {
return errors.New("ctx has no multi store")
}
s.cacheCtx, s.writeCache = s.ctx.CacheContext()
return nil
}
// AddLog adds a log, called by evm.
func (s *StateDB) AddLog(log *ethtypes.Log) {
s.journal.append(addLogChange{})
log.TxHash = s.txConfig.TxHash
log.BlockHash = s.txConfig.BlockHash
log.TxIndex = s.txConfig.TxIndex
log.Index = s.txConfig.LogIndex + uint(len(s.logs))
s.logs = append(s.logs, log)
}
// Logs returns the logs of current transaction.
func (s *StateDB) Logs() []*ethtypes.Log {
return s.logs
}
// AddRefund adds gas to the refund counter
func (s *StateDB) AddRefund(gas uint64) {
s.journal.append(refundChange{prev: s.refund})
s.refund += gas
}
// SubRefund removes gas from the refund counter.
// This method will panic if the refund counter goes below zero
func (s *StateDB) SubRefund(gas uint64) {
s.journal.append(refundChange{prev: s.refund})
if gas > s.refund {
panic(fmt.Sprintf("Refund counter below zero (gas: %d > refund: %d)", gas, s.refund))
}
s.refund -= gas
}
// Exist reports whether the given account address exists in the state.
// Notably this also returns true for suicided accounts.
func (s *StateDB) Exist(addr common.Address) bool {
return s.getStateObject(addr) != nil
}
// Empty returns whether the state object is either non-existent
// or empty according to the EIP161 specification (balance = nonce = code = 0)
func (s *StateDB) Empty(addr common.Address) bool {
so := s.getStateObject(addr)
return so == nil || so.empty()
}
// GetBalance retrieves the balance from the given address or 0 if object not found
func (s *StateDB) GetBalance(addr common.Address) *big.Int {
stateObject := s.getStateObject(addr)
if stateObject != nil {
return stateObject.Balance()
}
return common.Big0
}
// GetNonce returns the nonce of account, 0 if not exists.
func (s *StateDB) GetNonce(addr common.Address) uint64 {
stateObject := s.getStateObject(addr)
if stateObject != nil {
return stateObject.Nonce()
}
return 0
}
// GetCode returns the code of account, nil if not exists.
func (s *StateDB) GetCode(addr common.Address) []byte {
stateObject := s.getStateObject(addr)
if stateObject != nil {
return stateObject.Code()
}
return nil
}
// GetCodeSize returns the code size of account.
func (s *StateDB) GetCodeSize(addr common.Address) int {
stateObject := s.getStateObject(addr)
if stateObject != nil {
return stateObject.CodeSize()
}
return 0
}
// GetCodeHash returns the code hash of account.
func (s *StateDB) GetCodeHash(addr common.Address) common.Hash {
stateObject := s.getStateObject(addr)
if stateObject == nil {
return common.Hash{}
}
return common.BytesToHash(stateObject.CodeHash())
}
// GetState retrieves a value from the given account's storage trie.
func (s *StateDB) GetState(addr common.Address, hash common.Hash) common.Hash {
stateObject := s.getStateObject(addr)
if stateObject != nil {
return stateObject.GetState(hash)
}
return common.Hash{}
}
// GetCommittedState retrieves a value from the given account's committed storage trie.
func (s *StateDB) GetCommittedState(addr common.Address, hash common.Hash) common.Hash {
stateObject := s.getStateObject(addr)
if stateObject != nil {
return stateObject.GetCommittedState(hash)
}
return common.Hash{}
}
// GetRefund returns the current value of the refund counter.
func (s *StateDB) GetRefund() uint64 {
return s.refund
}
// HasSuicided returns if the contract is suicided in current transaction.
func (s *StateDB) HasSuicided(addr common.Address) bool {
stateObject := s.getStateObject(addr)
if stateObject != nil {
return stateObject.suicided
}
return false
}
// AddPreimage records a SHA3 preimage seen by the VM.
// AddPreimage performs a no-op since the EnablePreimageRecording flag is disabled
// on the vm.Config during state transitions. No store trie preimages are written
// to the database.
func (s *StateDB) AddPreimage(_ common.Hash, _ []byte) {}
// getStateObject retrieves a state object given by the address, returning nil if
// the object is not found.
func (s *StateDB) getStateObject(addr common.Address) *stateObject {
// Prefer live objects if any is available
if obj := s.stateObjects[addr]; obj != nil {
return obj
}
// If no live objects are available, load it from keeper
account := s.keeper.GetAccount(s.ctx, addr)
if account == nil {
return nil
}
// Insert into the live set
obj := newObject(s, addr, *account)
s.setStateObject(obj)
return obj
}
// getOrNewStateObject retrieves a state object or create a new state object if nil.
func (s *StateDB) getOrNewStateObject(addr common.Address) *stateObject {
stateObject := s.getStateObject(addr)
if stateObject == nil {
stateObject, _ = s.createObject(addr)
}
return stateObject
}
// createObject creates a new state object. If there is an existing account with
// the given address, it is overwritten and returned as the second return value.
func (s *StateDB) createObject(addr common.Address) (newobj, prev *stateObject) {
prev = s.getStateObject(addr)
newobj = newObject(s, addr, Account{})
if prev == nil {
s.journal.append(createObjectChange{account: &addr})
} else {
s.journal.append(resetObjectChange{prev: prev})
}
s.setStateObject(newobj)
if prev != nil {
return newobj, prev
}
return newobj, nil
}
// CreateAccount explicitly creates a state object. If a state object with the address
// already exists the balance is carried over to the new account.
//
// CreateAccount is called during the EVM CREATE operation. The situation might arise that
// a contract does the following:
//
// 1. sends funds to sha(account ++ (nonce + 1))
// 2. tx_create(sha(account ++ nonce)) (note that this gets the address of 1)
//
// Carrying over the balance ensures that Ether doesn't disappear.
func (s *StateDB) CreateAccount(addr common.Address) {
newObj, prev := s.createObject(addr)
if prev != nil {
newObj.setBalance(prev.account.Balance)
}
}
// ForEachStorage iterate the contract storage, the iteration order is not defined.
func (s *StateDB) ForEachStorage(addr common.Address, cb func(key, value common.Hash) bool) error {
so := s.getStateObject(addr)
if so == nil {
return nil
}
s.keeper.ForEachStorage(s.ctx, addr, func(key, value common.Hash) bool {
if value, dirty := so.dirtyStorage[key]; dirty {
return cb(key, value)
}
if len(value) > 0 {
return cb(key, value)
}
return true
})
return nil
}
func (s *StateDB) setStateObject(object *stateObject) {
s.stateObjects[object.Address()] = object
}
/*
* SETTERS
*/
// AddPrecompileFn adds a precompileCall journal entry
// with a snapshot of the multi-store and events previous
// to the precompile call.
func (s *StateDB) AddPrecompileFn(addr common.Address, cms storetypes.CacheMultiStore, events sdk.Events) error {
stateObject := s.getOrNewStateObject(addr)
if stateObject == nil {
return fmt.Errorf("could not add precompile call to address %s. State object not found", addr)
}
stateObject.AddPrecompileFn(cms, events)
s.precompileCallsCounter++
if s.precompileCallsCounter > types.MaxPrecompileCalls {
return fmt.Errorf("max calls to precompiles (%d) reached", types.MaxPrecompileCalls)
}
return nil
}
// AddBalance adds amount to the account associated with addr.
func (s *StateDB) AddBalance(addr common.Address, amount *big.Int) {
stateObject := s.getOrNewStateObject(addr)
if stateObject != nil {
stateObject.AddBalance(amount)
}
}
// SubBalance subtracts amount from the account associated with addr.
func (s *StateDB) SubBalance(addr common.Address, amount *big.Int) {
stateObject := s.getOrNewStateObject(addr)
if stateObject != nil {
stateObject.SubBalance(amount)
}
}
// SetNonce sets the nonce of account.
func (s *StateDB) SetNonce(addr common.Address, nonce uint64) {
stateObject := s.getOrNewStateObject(addr)
if stateObject != nil {
stateObject.SetNonce(nonce)
}
}
// SetCode sets the code of account.
func (s *StateDB) SetCode(addr common.Address, code []byte) {
stateObject := s.getOrNewStateObject(addr)
if stateObject != nil {
stateObject.SetCode(crypto.Keccak256Hash(code), code)
}
}
// SetState sets the contract state.
func (s *StateDB) SetState(addr common.Address, key, value common.Hash) {
stateObject := s.getOrNewStateObject(addr)
if stateObject != nil {
stateObject.SetState(key, value)
}
}
// Suicide marks the given account as suicided.
// This clears the account balance.
//
// The account's state object is still available until the state is committed,
// getStateObject will return a non-nil account after Suicide.
func (s *StateDB) Suicide(addr common.Address) bool {
stateObject := s.getStateObject(addr)
if stateObject == nil {
return false
}
s.journal.append(suicideChange{
account: &addr,
prev: stateObject.suicided,
prevbalance: new(big.Int).Set(stateObject.Balance()),
})
stateObject.markSuicided()
stateObject.account.Balance = new(big.Int)
return true
}
// PrepareAccessList handles the preparatory steps for executing a state transition with
// regards to both EIP-2929 and EIP-2930:
//
// - Add sender to access list (2929)
// - Add destination to access list (2929)
// - Add precompiles to access list (2929)
// - Add the contents of the optional tx access list (2930)
//
// This method should only be called if Yolov3/Berlin/2929+2930 is applicable at the current number.
func (s *StateDB) PrepareAccessList(sender common.Address, dst *common.Address, precompiles []common.Address, list ethtypes.AccessList) {
s.AddAddressToAccessList(sender)
if dst != nil {
s.AddAddressToAccessList(*dst)
// If it's a create-tx, the destination will be added inside evm.create
}
for _, addr := range precompiles {
s.AddAddressToAccessList(addr)
}
for _, el := range list {
s.AddAddressToAccessList(el.Address)
for _, key := range el.StorageKeys {
s.AddSlotToAccessList(el.Address, key)
}
}
}
// AddAddressToAccessList adds the given address to the access list
func (s *StateDB) AddAddressToAccessList(addr common.Address) {
if s.accessList.AddAddress(addr) {
s.journal.append(accessListAddAccountChange{&addr})
}
}
// AddSlotToAccessList adds the given (address, slot)-tuple to the access list
func (s *StateDB) AddSlotToAccessList(addr common.Address, slot common.Hash) {
addrMod, slotMod := s.accessList.AddSlot(addr, slot)
if addrMod {
// In practice, this should not happen, since there is no way to enter the
// scope of 'address' without having the 'address' become already added
// to the access list (via call-variant, create, etc).
// Better safe than sorry, though
s.journal.append(accessListAddAccountChange{&addr})
}
if slotMod {
s.journal.append(accessListAddSlotChange{
address: &addr,
slot: &slot,
})
}
}
// AddressInAccessList returns true if the given address is in the access list.
func (s *StateDB) AddressInAccessList(addr common.Address) bool {
return s.accessList.ContainsAddress(addr)
}
// SlotInAccessList returns true if the given (address, slot)-tuple is in the access list.
func (s *StateDB) SlotInAccessList(addr common.Address, slot common.Hash) (addressPresent bool, slotPresent bool) {
return s.accessList.Contains(addr, slot)
}
// Snapshot returns an identifier for the current revision of the state.
func (s *StateDB) Snapshot() int {
id := s.nextRevisionID
s.nextRevisionID++
s.validRevisions = append(s.validRevisions, revision{id, s.journal.length()})
return id
}
// RevertToSnapshot reverts all state changes made since the given revision.
func (s *StateDB) RevertToSnapshot(revid int) {
// Find the snapshot in the stack of valid snapshots.
idx := sort.Search(len(s.validRevisions), func(i int) bool {
return s.validRevisions[i].id >= revid
})
if idx == len(s.validRevisions) || s.validRevisions[idx].id != revid {
panic(fmt.Errorf("revision id %v cannot be reverted", revid))
}
snapshot := s.validRevisions[idx].journalIndex
// Replay the journal to undo changes and remove invalidated snapshots
s.journal.Revert(s, snapshot)
s.validRevisions = s.validRevisions[:idx]
}
// Commit writes the dirty states to keeper
// the StateDB object should be discarded after committed.
func (s *StateDB) Commit() error {
// writeCache func will exist only when there's a call to a precompile.
// It applies all the store updates preformed by precompile calls.
if s.writeCache != nil {
s.writeCache()
}
return s.commitWithCtx(s.ctx)
}
// CommitWithCacheCtx writes the dirty states to keeper using the cacheCtx.
// This function is used before any precompile call to make sure the cacheCtx
// is updated with the latest changes within the tx (StateDB's journal entries).
func (s *StateDB) CommitWithCacheCtx() error {
return s.commitWithCtx(s.cacheCtx)
}
// commitWithCtx writes the dirty states to keeper
// using the provided context
func (s *StateDB) commitWithCtx(ctx sdk.Context) error {
for _, addr := range s.journal.sortedDirties() {
obj := s.stateObjects[addr]
if obj.suicided {
if err := s.keeper.DeleteAccount(ctx, obj.Address()); err != nil {
return errorsmod.Wrapf(err, "failed to delete account %s", obj.Address())
}
} else {
if obj.code != nil && obj.dirtyCode {
if len(obj.code) == 0 {
s.keeper.DeleteCode(ctx, obj.CodeHash())
} else {
s.keeper.SetCode(ctx, obj.CodeHash(), obj.code)
}
}
if err := s.keeper.SetAccount(ctx, obj.Address(), obj.account); err != nil {
return errorsmod.Wrap(err, "failed to set account")
}
for _, key := range obj.dirtyStorage.SortedKeys() {
valueBytes := obj.dirtyStorage[key].Bytes()
if len(valueBytes) == 0 {
s.keeper.DeleteState(ctx, obj.Address(), key)
} else {
s.keeper.SetState(ctx, obj.Address(), key, valueBytes)
}
}
}
}
return nil
}