/
statedb.go
754 lines (628 loc) · 22.1 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
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
package types
import (
"fmt"
"math/big"
"sort"
"sync"
ethstate "github.com/ethereum/go-ethereum/core/state"
"github.com/tendermint/tendermint/crypto"
"github.com/netcloth/netcloth-chain/modules/auth"
"github.com/netcloth/netcloth-chain/modules/auth/types"
sdk "github.com/netcloth/netcloth-chain/types"
)
var (
zeroBalance = sdk.ZeroInt().BigInt()
)
type revision struct {
id int
journalIndex int
}
type CommitStateDB struct {
// TODO: We need to store the context as part of the structure itself opposed
// to being passed as a parameter (as it should be) in order to implement the
// StateDB interface. Perhaps there is a better way.
ctx sdk.Context
ak auth.AccountKeeper
storageKey sdk.StoreKey
codeKey sdk.StoreKey
// maps that hold 'live' objects, which will get modified while processing a
// state transition
stateObjects map[string]*stateObject
stateObjectsDirty map[string]struct{}
// The refund counter, also used by state transitioning.
refund uint64
thash, bhash sdk.Hash
txIndex int
logs map[sdk.Hash][]*Log
logSize uint
// TODO: Determine if we actually need this as we do not need preimages in
// the SDK, but it seems to be used elsewhere in Geth.
preimages map[sdk.Hash][]byte
// DB error.
// State objects are used by the consensus core and VM which are
// unable to deal with database-level errors. Any error that occurs
// during a database read is memo-ized here and will eventually be returned
// by StateDB.Commit.
dbErr error
// Journal of state modifications. This is the backbone of
// Snapshot and RevertToSnapshot.
journal *journal
validRevisions []revision
nextRevisionID int
// mutex for state deep copying
lock sync.Mutex
}
// NewCommitStateDB returns a reference to a newly initialized CommitStateDB
// which implements Geth's state.StateDB interface.
//
// CONTRACT: Stores used for state must be cache-wrapped as the ordering of the
// key/value space matters in determining the merkle root.
//func NewCommitStateDB(ctx sdk.Context, ak auth.AccountKeeper, storageKey, codeKey sdk.StoreKey) *CommitStateDB {
func NewCommitStateDB(ak auth.AccountKeeper, storageKey, codeKey sdk.StoreKey) *CommitStateDB {
return &CommitStateDB{
ak: ak,
storageKey: storageKey,
codeKey: codeKey,
stateObjects: make(map[string]*stateObject),
stateObjectsDirty: make(map[string]struct{}),
logs: make(map[sdk.Hash][]*Log),
preimages: make(map[sdk.Hash][]byte),
journal: newJournal(),
}
}
func NewStateDB(db *CommitStateDB) *CommitStateDB {
return &CommitStateDB{
ak: db.ak,
storageKey: db.storageKey,
codeKey: db.codeKey,
stateObjects: make(map[string]*stateObject),
stateObjectsDirty: make(map[string]struct{}),
logs: make(map[sdk.Hash][]*Log),
preimages: make(map[sdk.Hash][]byte),
journal: newJournal(),
}
}
// WithContext returns a Database with an updated sdk context
func (csdb *CommitStateDB) WithContext(ctx sdk.Context) *CommitStateDB {
csdb.ctx = ctx
return csdb
}
func (csdb *CommitStateDB) WithTxHash(txHash []byte) *CommitStateDB {
csdb.thash = sdk.BytesToHash(txHash)
return csdb
}
// ----------------------------------------------------------------------------
// Setters
// ----------------------------------------------------------------------------
// SetBalance sets the balance of an account.
func (csdb *CommitStateDB) SetBalance(addr sdk.AccAddress, amount *big.Int) {
so := csdb.GetOrNewStateObject(addr)
if so != nil {
so.SetBalance(amount)
}
}
// AddBalance adds amount to the account associated with addr.
func (csdb *CommitStateDB) AddBalance(addr sdk.AccAddress, amount *big.Int) {
so := csdb.GetOrNewStateObject(addr)
if so != nil {
so.AddBalance(amount)
}
}
// SubBalance subtracts amount from the account associated with addr.
func (csdb *CommitStateDB) SubBalance(addr sdk.AccAddress, amount *big.Int) {
so := csdb.GetOrNewStateObject(addr)
if so != nil {
so.SubBalance(amount)
}
}
// SetNonce sets the nonce (sequence number) of an account.
func (csdb *CommitStateDB) SetNonce(addr sdk.AccAddress, nonce uint64) {
so := csdb.GetOrNewStateObject(addr)
if so != nil {
so.SetNonce(nonce)
}
}
// SetState sets the storage state with a key, value pair for an account.
func (csdb *CommitStateDB) SetState(addr sdk.AccAddress, key, value sdk.Hash) {
so := csdb.GetOrNewStateObject(addr)
if so != nil {
so.SetState(key, value)
}
}
// SetCode sets the code for a given account.
func (csdb *CommitStateDB) SetCode(addr sdk.AccAddress, code []byte) {
so := csdb.GetOrNewStateObject(addr)
if so != nil {
so.SetCode(sdk.BytesToHash(crypto.Sha256(code)), code)
}
}
// AddLog adds a new log to the state and sets the log metadata from the state.
func (csdb *CommitStateDB) AddLog(log *Log) {
csdb.journal.append(addLogChange{txhash: csdb.thash})
log.TxHash = csdb.thash
log.BlockHash = csdb.bhash
log.TxIndex = uint(csdb.txIndex)
log.Index = csdb.logSize
csdb.logs[csdb.thash] = append(csdb.logs[csdb.thash], log)
csdb.logSize++
}
// AddPreimage records a SHA3 preimage seen by the VM.
func (csdb *CommitStateDB) AddPreimage(hash sdk.Hash, preimage []byte) {
if _, ok := csdb.preimages[hash]; !ok {
csdb.journal.append(addPreimageChange{hash: hash})
pi := make([]byte, len(preimage))
copy(pi, preimage)
csdb.preimages[hash] = pi
}
}
// Preimages returns a list of SHA3 preimages that have been submitted.
func (csdb *CommitStateDB) Preimages() map[sdk.Hash][]byte {
return csdb.preimages
}
// AddRefund adds gas to the refund counter.
func (csdb *CommitStateDB) AddRefund(gas uint64) {
csdb.journal.append(refundChange{prev: csdb.refund})
csdb.refund += gas
}
// SubRefund removes gas from the refund counter. It will panic if the refund
// counter goes below zero.
func (csdb *CommitStateDB) SubRefund(gas uint64) {
csdb.journal.append(refundChange{prev: csdb.refund})
if gas > csdb.refund {
panic("refund counter below zero")
}
csdb.refund -= gas
}
// ----------------------------------------------------------------------------
// Getters
// ----------------------------------------------------------------------------
// GetBalance retrieves the balance from the given address or 0 if object not
// found.
func (csdb *CommitStateDB) GetBalance(addr sdk.AccAddress) *big.Int {
so := csdb.getStateObject(addr)
if so != nil {
return so.Balance()
}
return zeroBalance
}
// GetNonce returns the nonce (sequence number) for a given account.
func (csdb *CommitStateDB) GetNonce(addr sdk.AccAddress) uint64 {
so := csdb.getStateObject(addr)
if so != nil {
return so.Nonce()
}
return 0
}
// TxIndex returns the current transaction index set by Prepare.
func (csdb *CommitStateDB) TxIndex() int {
return csdb.txIndex
}
// BlockHash returns the current block hash set by Prepare.
func (csdb *CommitStateDB) BlockHash() sdk.Hash {
return csdb.bhash
}
// GetCode returns the code for a given account.
func (csdb *CommitStateDB) GetCode(addr sdk.AccAddress) []byte {
so := csdb.getStateObject(addr)
if so != nil {
return so.Code()
}
return nil
}
// GetCodeSize returns the code size for a given account.
func (csdb *CommitStateDB) GetCodeSize(addr sdk.AccAddress) int {
so := csdb.getStateObject(addr)
if so == nil {
return 0
}
if so.code != nil {
return len(so.code)
}
// TODO: we may need to cache these lookups directly
return len(so.Code())
}
// GetCodeHash returns the code hash for a given account.
func (csdb *CommitStateDB) GetCodeHash(addr sdk.AccAddress) sdk.Hash {
so := csdb.getStateObject(addr)
if so == nil {
return sdk.Hash{}
}
return sdk.BytesToHash(so.CodeHash())
}
// GetState retrieves a value from the given account's storage store.
func (csdb *CommitStateDB) GetState(addr sdk.AccAddress, hash sdk.Hash) sdk.Hash {
so := csdb.getStateObject(addr)
if so != nil {
return so.GetState(hash)
}
return sdk.Hash{}
}
// GetCommittedState retrieves a value from the given account's committed
// storage.
func (csdb *CommitStateDB) GetCommittedState(addr sdk.AccAddress, hash sdk.Hash) sdk.Hash {
so := csdb.getStateObject(addr)
if so != nil {
return so.GetCommittedState(hash)
}
return sdk.Hash{}
}
// GetLogs returns the current logs for a given hash in the state.
func (csdb *CommitStateDB) GetLogs(hash sdk.Hash) []*Log {
return csdb.logs[hash]
}
// Logs returns all the current logs in the state.
func (csdb *CommitStateDB) Logs() []*Log {
var logs []*Log
for _, lgs := range csdb.logs {
logs = append(logs, lgs...)
}
return logs
}
// GetRefund returns the current value of the refund counter.
func (csdb *CommitStateDB) GetRefund() uint64 {
return csdb.refund
}
// HasSuicided returns if the given account for the specified address has been
// killed.
func (csdb *CommitStateDB) HasSuicided(addr sdk.AccAddress) bool {
so := csdb.getStateObject(addr)
if so != nil {
return so.suicided
}
return false
}
// ----------------------------------------------------------------------------
// Persistence
// ----------------------------------------------------------------------------
// Commit writes the state to the appropriate KVStores. For each state object
// in the cache, it will either be removed, or have it's code set and/or it's
// state (storage) updated. In addition, the state object (account) itself will
// be written. Finally, the root hash (version) will be returned.
func (csdb *CommitStateDB) Commit(deleteEmptyObjects bool) (root sdk.Hash, err error) {
defer csdb.clearJournalAndRefund()
// remove dirty state object entries based on the journal
for addr := range csdb.journal.dirties {
csdb.stateObjectsDirty[addr] = struct{}{}
}
// set the state objects
for addr, so := range csdb.stateObjects {
_, isDirty := csdb.stateObjectsDirty[addr]
switch {
case so.suicided || (isDirty && deleteEmptyObjects && so.empty()):
// If the state object has been removed, don't bother syncing it and just
// remove it from the store.
csdb.deleteStateObject(so)
case isDirty:
// write any contract code associated with the state object
if so.code != nil && so.dirtyCode {
so.commitCode()
so.dirtyCode = false
}
// update the object in the KVStore
csdb.updateStateObject(so)
}
delete(csdb.stateObjectsDirty, addr)
}
// NOTE: Ethereum returns the trie merkle root here, but as commitment
// actually happens in the BaseApp at EndBlocker, we do not know the root at
// this time.
return
}
// Finalise finalizes the state objects (accounts) state by setting their state,
// removing the csdb destructed objects and clearing the journal as well as the
// refunds.
func (csdb *CommitStateDB) Finalise(deleteEmptyObjects bool) {
for addr := range csdb.journal.dirties {
so, exist := csdb.stateObjects[addr]
if !exist {
// ripeMD is 'touched' at block 1714175, in tx:
// 0x1237f737031e40bcde4a8b7e717b2d15e3ecadfe49bb1bbc71ee9deb09c6fcf2
//
// That tx goes out of gas, and although the notion of 'touched' does not
// exist there, the touch-event will still be recorded in the journal.
// Since ripeMD is a special snowflake, it will persist in the journal even
// though the journal is reverted. In this special circumstance, it may
// exist in journal.dirties but not in stateObjects. Thus, we can safely
// ignore it here.
continue
}
if so.suicided || (deleteEmptyObjects && so.empty()) {
csdb.deleteStateObject(so)
} else {
// Set all the dirty state storage items for the state object in the
// KVStore and finally set the account in the account mapper.
so.commitState()
csdb.updateStateObject(so)
}
csdb.stateObjectsDirty[addr] = struct{}{}
}
// invalidate journal because reverting across transactions is not allowed
csdb.clearJournalAndRefund()
}
// IntermediateRoot returns the current root hash of the state. It is called in
// between transactions to get the root hash that goes into transaction
// receipts.
//
// NOTE: The SDK has not concept or method of getting any intermediate merkle
// root as commitment of the merkle-ized tree doesn't happen until the
// BaseApps' EndBlocker.
func (csdb *CommitStateDB) IntermediateRoot(deleteEmptyObjects bool) sdk.Hash {
csdb.Finalise(deleteEmptyObjects)
return sdk.Hash{}
}
// updateStateObject writes the given state object to the store.
func (csdb *CommitStateDB) updateStateObject(so *stateObject) {
csdb.ak.SetAccount(csdb.ctx, so.account)
}
// deleteStateObject removes the given state object from the state store.
func (csdb *CommitStateDB) deleteStateObject(so *stateObject) {
so.deleted = true
csdb.ak.RemoveAccount(csdb.ctx, so.account)
}
// ----------------------------------------------------------------------------
// Snapshotting
// ----------------------------------------------------------------------------
// Snapshot returns an identifier for the current revision of the state.
func (csdb *CommitStateDB) Snapshot() int {
id := csdb.nextRevisionID
csdb.nextRevisionID++
csdb.validRevisions = append(
csdb.validRevisions,
revision{
id: id,
journalIndex: csdb.journal.length(),
},
)
return id
}
// RevertToSnapshot reverts all state changes made since the given revision.
func (csdb *CommitStateDB) RevertToSnapshot(revID int) {
// find the snapshot in the stack of valid snapshots
idx := sort.Search(len(csdb.validRevisions), func(i int) bool {
return csdb.validRevisions[i].id >= revID
})
if idx == len(csdb.validRevisions) || csdb.validRevisions[idx].id != revID {
panic(fmt.Errorf("revision ID %v cannot be reverted", revID))
}
snapshot := csdb.validRevisions[idx].journalIndex
// replay the journal to undo changes and remove invalidated snapshots
csdb.journal.revert(csdb, snapshot)
csdb.validRevisions = csdb.validRevisions[:idx]
}
// ----------------------------------------------------------------------------
// Auxiliary
// ----------------------------------------------------------------------------
// Database retrieves the low level database supporting the lower level trie
// ops. It is not used in Ethermint, so it returns nil.
func (csdb *CommitStateDB) Database() ethstate.Database {
return nil
}
// Empty returns whether the state object is either non-existent or empty
// according to the EIP161 specification (balance = nonce = code = 0).
func (csdb *CommitStateDB) Empty(addr sdk.AccAddress) bool {
so := csdb.getStateObject(addr)
return so == nil || so.empty()
}
// Exist reports whether the given account address exists in the state. Notably,
// this also returns true for suicided accounts.
func (csdb *CommitStateDB) Exist(addr sdk.AccAddress) bool {
return csdb.getStateObject(addr) != nil
}
// Error returns the first non-nil error the StateDB encountered.
func (csdb *CommitStateDB) Error() error {
return csdb.dbErr
}
// Suicide marks the given account as suicided and 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 (csdb *CommitStateDB) Suicide(addr sdk.AccAddress) bool {
so := csdb.getStateObject(addr)
if so == nil {
return false
}
csdb.journal.append(suicideChange{
account: &addr,
prev: so.suicided,
prevBalance: sdk.NewIntFromBigInt(so.Balance()),
})
so.markSuicided()
so.SetBalance(new(big.Int))
return true
}
// Reset clears out all ephemeral state objects from the state db, but keeps
// the underlying account mapper and store keys to avoid reloading data for the
// next operations.
func (csdb *CommitStateDB) Reset(_ sdk.Hash) error {
csdb.stateObjects = make(map[string]*stateObject)
csdb.stateObjectsDirty = make(map[string]struct{})
csdb.thash = sdk.Hash{}
csdb.bhash = sdk.Hash{}
csdb.txIndex = 0
csdb.logs = make(map[sdk.Hash][]*Log)
csdb.logSize = 0
csdb.preimages = make(map[sdk.Hash][]byte)
csdb.clearJournalAndRefund()
return nil
}
// UpdateAccounts updates the nonce and coin balances of accounts
func (csdb *CommitStateDB) UpdateAccounts() {
for addr, so := range csdb.stateObjects {
addr, err := sdk.AccAddressFromBech32(addr)
if err != nil {
continue
}
accI := csdb.ak.GetAccount(csdb.ctx, addr)
acc, ok := accI.(*types.BaseAccount)
if ok {
if (so.Balance() != acc.GetCoins().AmountOf(sdk.NativeTokenName).BigInt()) || (so.Nonce() != acc.GetSequence()) {
// If queried account's balance or nonce are invalid, update the account pointer
so.account = acc
}
}
}
}
// ClearStateObjects clears cache of state objects to handle account changes outside of the EVM
func (csdb *CommitStateDB) ClearStateObjects() {
csdb.stateObjects = make(map[string]*stateObject)
csdb.stateObjectsDirty = make(map[string]struct{})
}
func (csdb *CommitStateDB) clearJournalAndRefund() {
csdb.journal = newJournal()
csdb.validRevisions = csdb.validRevisions[:0]
csdb.refund = 0
}
// Prepare sets the current transaction hash and index and block hash which is
// used when the EVM emits new state logs.
func (csdb *CommitStateDB) Prepare(thash, bhash sdk.Hash, txi int) {
csdb.thash = thash
csdb.bhash = bhash
csdb.txIndex = txi
}
// 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 (csdb *CommitStateDB) CreateAccount(addr sdk.AccAddress) {
newobj, prevobj := csdb.createObject(addr)
if prevobj != nil {
newobj.setBalance(sdk.NewIntFromBigInt(prevobj.Balance()))
}
}
// Copy creates a deep, independent copy of the state.
//
// NOTE: Snapshots of the copied state cannot be applied to the copy.
func (csdb *CommitStateDB) Copy() *CommitStateDB {
csdb.lock.Lock()
defer csdb.lock.Unlock()
// copy all the basic fields, initialize the memory ones
state := &CommitStateDB{
ctx: csdb.ctx,
ak: csdb.ak,
storageKey: csdb.storageKey,
codeKey: csdb.codeKey,
stateObjects: make(map[string]*stateObject, len(csdb.journal.dirties)),
stateObjectsDirty: make(map[string]struct{}, len(csdb.journal.dirties)),
refund: csdb.refund,
logs: make(map[sdk.Hash][]*Log, len(csdb.logs)),
logSize: csdb.logSize,
preimages: make(map[sdk.Hash][]byte),
journal: newJournal(),
}
// copy the dirty states, logs, and preimages
for addr := range csdb.journal.dirties {
// There is a case where an object is in the journal but not in the
// stateObjects: OOG after touch on ripeMD prior to Byzantium. Thus, we
// need to check for nil.
//
// Ref: https://github.com/ethereum/go-ethereum/pull/16485#issuecomment-380438527
if object, exist := csdb.stateObjects[addr]; exist {
state.stateObjects[addr] = object.deepCopy(state)
state.stateObjectsDirty[addr] = struct{}{}
}
}
// Above, we don't copy the actual journal. This means that if the copy is
// copied, the loop above will be a no-op, since the copy's journal is empty.
// Thus, here we iterate over stateObjects, to enable copies of copies.
for addr := range csdb.stateObjectsDirty {
if _, exist := state.stateObjects[addr]; !exist {
state.stateObjects[addr] = csdb.stateObjects[addr].deepCopy(state)
state.stateObjectsDirty[addr] = struct{}{}
}
}
// copy logs
for hash, logs := range csdb.logs {
cpy := make([]*Log, len(logs))
for i, l := range logs {
cpy[i] = new(Log)
*cpy[i] = *l
}
state.logs[hash] = cpy
}
// copy pre-images
for hash, preimage := range csdb.preimages {
state.preimages[hash] = preimage
}
return state
}
// ForEachStorage iterates over each storage items, all invokes the provided
// callback on each key, value pair .
func (csdb *CommitStateDB) ForEachStorage(addr sdk.AccAddress, cb func(key, value sdk.Hash) bool) error {
so := csdb.getStateObject(addr)
if so == nil {
return nil
}
store := csdb.ctx.KVStore(csdb.storageKey)
iter := sdk.KVStorePrefixIterator(store, so.Address().Bytes())
for ; iter.Valid(); iter.Next() {
key := sdk.BytesToHash(iter.Key())
value := iter.Value()
if value, dirty := so.dirtyStorage[key]; dirty {
cb(key, value)
continue
}
cb(key, sdk.BytesToHash(value))
}
iter.Close()
return nil
}
// GetOrNewStateObject retrieves a state object or create a new state object if
// nil.
func (csdb *CommitStateDB) GetOrNewStateObject(addr sdk.AccAddress) StateObject {
so := csdb.getStateObject(addr)
if so == nil || so.deleted {
so, _ = csdb.createObject(addr)
}
return so
}
// 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 (csdb *CommitStateDB) createObject(addr sdk.AccAddress) (newObj, prevObj *stateObject) {
prevObj = csdb.getStateObject(addr)
acc := csdb.ak.NewAccountWithAddress(csdb.ctx, sdk.AccAddress(addr.Bytes()))
newObj = newObject(csdb, acc)
newObj.setNonce(0) // sets the object to dirty
if prevObj == nil {
csdb.journal.append(createObjectChange{account: &addr})
} else {
csdb.journal.append(resetObjectChange{prev: prevObj})
}
csdb.setStateObject(newObj)
return newObj, prevObj
}
// setError remembers the first non-nil error it is called with.
func (csdb *CommitStateDB) setError(err error) {
if csdb.dbErr == nil {
csdb.dbErr = err
}
}
// getStateObject attempts to retrieve a state object given by the address.
// Returns nil and sets an error if not found.
func (csdb *CommitStateDB) getStateObject(addr sdk.AccAddress) (stateObject *stateObject) {
// prefer 'live' (cached) objects
if so := csdb.stateObjects[addr.String()]; so != nil {
if so.deleted {
return nil
}
return so
}
// otherwise, attempt to fetch the account from the account mapper
acc := csdb.ak.GetAccount(csdb.ctx, addr.Bytes())
if acc == nil {
csdb.setError(fmt.Errorf("no account found for address: %X", addr.Bytes()))
return nil
}
// insert the state object into the live set
so := newObject(csdb, acc)
csdb.setStateObject(so)
return so
}
func (csdb *CommitStateDB) setStateObject(so *stateObject) {
csdb.stateObjects[so.Address().String()] = so
}