/
statedb.go
1312 lines (1097 loc) · 38.8 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
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package types
import (
"fmt"
"math/big"
"sort"
"sync"
"github.com/cosmos/cosmos-sdk/x/auth"
"github.com/cosmos/cosmos-sdk/store/prefix"
"github.com/cosmos/cosmos-sdk/store/types"
sdk "github.com/cosmos/cosmos-sdk/types"
ethcmn "github.com/ethereum/go-ethereum/common"
ethstate "github.com/ethereum/go-ethereum/core/state"
ethtypes "github.com/ethereum/go-ethereum/core/types"
ethvm "github.com/ethereum/go-ethereum/core/vm"
ethcrypto "github.com/ethereum/go-ethereum/crypto"
ethermint "github.com/okex/exchain/app/types"
"github.com/okex/exchain/x/analyzer"
"github.com/okex/exchain/x/params"
)
var (
_ ethvm.StateDB = (*CommitStateDB)(nil)
zeroBalance = sdk.ZeroInt().BigInt()
)
type revision struct {
id int
journalIndex int
}
type CommitStateDBParams struct {
StoreKey sdk.StoreKey
ParamSpace Subspace
AccountKeeper AccountKeeper
SupplyKeeper SupplyKeeper
Watcher Watcher
BankKeeper BankKeeper
Ada DbAdapter
}
type Watcher interface {
SaveAccount(account auth.Account, isDirectly bool)
SaveState(addr ethcmn.Address, key, value []byte)
Enabled() bool
SaveContractBlockedListItem(addr sdk.AccAddress)
SaveContractDeploymentWhitelistItem(addr sdk.AccAddress)
DeleteContractBlockedList(addr sdk.AccAddress)
DeleteContractDeploymentWhitelist(addr sdk.AccAddress)
}
type CacheCode struct {
CodeHash []byte
Code []byte
}
// CommitStateDB implements the Geth state.StateDB interface. Instead of using
// a trie and database for querying and persistence, the Keeper uses KVStores
// and an account mapper is used to facilitate state transitions.
//
// TODO: This implementation is subject to change in regards to its statefull
// manner. In otherwords, how this relates to the keeper in this module.
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
storeKey sdk.StoreKey
paramSpace Subspace
accountKeeper AccountKeeper
supplyKeeper SupplyKeeper
Watcher Watcher
bankKeeper BankKeeper
// array that hold 'live' objects, which will get modified while processing a
// state transition
stateObjects []stateEntry
addressToObjectIndex map[ethcmn.Address]int // map from address to the index of the state objects slice
stateObjectsDirty map[ethcmn.Address]struct{}
// The refund counter, also used by state transitioning.
refund uint64
thash, bhash ethcmn.Hash
txIndex int
logSize uint
logs []*ethtypes.Log
// 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 []preimageEntry
hashToPreimageIndex map[ethcmn.Hash]int // map from hash to the index of the preimages slice
// 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
// Per-transaction access list
accessList *accessList
// mutex for state deep copying
lock sync.Mutex
params *Params
codeCache map[ethcmn.Address]CacheCode
dbAdapter DbAdapter
}
type StoreProxy interface {
Set(key, value []byte)
Get(key []byte) []byte
Delete(key []byte)
Has(key []byte) bool
}
type DbAdapter interface {
NewStore(parent types.KVStore, prefix []byte) StoreProxy
}
type DefaultPrefixDb struct {
}
func (d DefaultPrefixDb) NewStore(parent types.KVStore, Prefix []byte) StoreProxy {
return prefix.NewStore(parent, Prefix)
}
// 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, storeKey sdk.StoreKey, paramSpace params.Subspace, ak AccountKeeper, sk SupplyKeeper, bk BankKeeper, watcher Watcher,
) *CommitStateDB {
return &CommitStateDB{
ctx: ctx,
storeKey: storeKey,
paramSpace: paramSpace,
accountKeeper: ak,
supplyKeeper: sk,
bankKeeper: bk,
Watcher: watcher,
stateObjects: []stateEntry{},
addressToObjectIndex: make(map[ethcmn.Address]int),
stateObjectsDirty: make(map[ethcmn.Address]struct{}),
preimages: []preimageEntry{},
hashToPreimageIndex: make(map[ethcmn.Hash]int),
journal: newJournal(),
validRevisions: []revision{},
accessList: newAccessList(),
logs: []*ethtypes.Log{},
codeCache: make(map[ethcmn.Address]CacheCode, 0),
dbAdapter: DefaultPrefixDb{},
}
}
func CreateEmptyCommitStateDB(csdbParams CommitStateDBParams, ctx sdk.Context) *CommitStateDB {
return &CommitStateDB{
ctx: ctx,
storeKey: csdbParams.StoreKey,
paramSpace: csdbParams.ParamSpace,
accountKeeper: csdbParams.AccountKeeper,
supplyKeeper: csdbParams.SupplyKeeper,
bankKeeper: csdbParams.BankKeeper,
Watcher: csdbParams.Watcher,
stateObjects: []stateEntry{},
addressToObjectIndex: make(map[ethcmn.Address]int),
stateObjectsDirty: make(map[ethcmn.Address]struct{}),
preimages: []preimageEntry{},
hashToPreimageIndex: make(map[ethcmn.Hash]int),
journal: newJournal(),
validRevisions: []revision{},
accessList: newAccessList(),
logSize: 0,
logs: []*ethtypes.Log{},
codeCache: make(map[ethcmn.Address]CacheCode, 0),
dbAdapter: csdbParams.Ada,
}
}
func (csdb *CommitStateDB) SetInternalDb(dba DbAdapter) {
csdb.dbAdapter = dba
}
// 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) GetCacheCode(addr ethcmn.Address) *CacheCode {
if !csdb.ctx.IsCheckTx() {
funcName := analyzer.RunFuncName()
analyzer.StartTxLog(funcName)
defer analyzer.StopTxLog(funcName)
}
code, ok := csdb.codeCache[addr]
if ok {
return &code
}
return nil
}
func (csdb *CommitStateDB) IteratorCode(cb func(addr ethcmn.Address, c CacheCode) bool) {
for addr, v := range csdb.codeCache {
cb(addr, v)
}
}
// ----------------------------------------------------------------------------
// Setters
// ----------------------------------------------------------------------------
// SetHeightHash sets the block header hash associated with a given height.
func (csdb *CommitStateDB) SetHeightHash(height uint64, hash ethcmn.Hash) {
if !csdb.ctx.IsCheckTx() {
funcName := analyzer.RunFuncName()
analyzer.StartTxLog(funcName)
defer analyzer.StopTxLog(funcName)
}
store := csdb.dbAdapter.NewStore(csdb.ctx.KVStore(csdb.storeKey), KeyPrefixHeightHash)
key := HeightHashKey(height)
store.Set(key, hash.Bytes())
}
// SetParams sets the evm parameters to the param space.
func (csdb *CommitStateDB) SetParams(params Params) {
csdb.params = ¶ms
csdb.paramSpace.SetParamSet(csdb.ctx, ¶ms)
}
// SetBalance sets the balance of an account.
func (csdb *CommitStateDB) SetBalance(addr ethcmn.Address, 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 ethcmn.Address, amount *big.Int) {
if !csdb.ctx.IsCheckTx() {
funcName := analyzer.RunFuncName()
analyzer.StartTxLog(funcName)
defer analyzer.StopTxLog(funcName)
}
so := csdb.GetOrNewStateObject(addr)
if so != nil {
so.AddBalance(amount)
}
}
// SubBalance subtracts amount from the account associated with addr.
func (csdb *CommitStateDB) SubBalance(addr ethcmn.Address, amount *big.Int) {
if !csdb.ctx.IsCheckTx() {
funcName := analyzer.RunFuncName()
analyzer.StartTxLog(funcName)
defer analyzer.StopTxLog(funcName)
}
so := csdb.GetOrNewStateObject(addr)
if so != nil {
so.SubBalance(amount)
}
}
// SetNonce sets the nonce (sequence number) of an account.
func (csdb *CommitStateDB) SetNonce(addr ethcmn.Address, nonce uint64) {
if !csdb.ctx.IsCheckTx() {
funcName := analyzer.RunFuncName()
analyzer.StartTxLog(funcName)
defer analyzer.StopTxLog(funcName)
}
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 ethcmn.Address, key, value ethcmn.Hash) {
if !csdb.ctx.IsCheckTx() {
funcName := analyzer.RunFuncName()
analyzer.StartTxLog(funcName)
defer analyzer.StopTxLog(funcName)
}
so := csdb.GetOrNewStateObject(addr)
if so != nil {
so.SetState(nil, key, value)
}
}
// SetCode sets the code for a given account.
func (csdb *CommitStateDB) SetCode(addr ethcmn.Address, code []byte) {
if !csdb.ctx.IsCheckTx() {
funcName := analyzer.RunFuncName()
analyzer.StartTxLog(funcName)
defer analyzer.StopTxLog(funcName)
}
so := csdb.GetOrNewStateObject(addr)
hash := ethcrypto.Keccak256Hash(code)
if so != nil {
so.SetCode(hash, code)
csdb.codeCache[addr] = CacheCode{
CodeHash: hash.Bytes(),
Code: code,
}
}
}
// ----------------------------------------------------------------------------
// Transaction logs
// Required for upgrade logic or ease of querying.
// NOTE: we use BinaryLengthPrefixed since the tx logs are also included on Result data,
// which can't use BinaryBare.
// ----------------------------------------------------------------------------
// SetLogs sets the logs for a transaction in the KVStore.
func (csdb *CommitStateDB) SetLogs(hash ethcmn.Hash, logs []*ethtypes.Log) error {
csdb.logs = logs
return nil
}
// DeleteLogs removes the logs from the KVStore. It is used during journal.Revert.
func (csdb *CommitStateDB) DeleteLogs(hash ethcmn.Hash) {
csdb.logs = []*ethtypes.Log{}
}
// AddLog adds a new log to the state and sets the log metadata from the state.
func (csdb *CommitStateDB) AddLog(log *ethtypes.Log) {
if !csdb.ctx.IsCheckTx() {
funcName := analyzer.RunFuncName()
analyzer.StartTxLog(funcName)
defer analyzer.StopTxLog(funcName)
}
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.logSize = csdb.logSize + 1
csdb.logs = append(csdb.logs, log)
}
// AddPreimage records a SHA3 preimage seen by the VM.
func (csdb *CommitStateDB) AddPreimage(hash ethcmn.Hash, preimage []byte) {
if !csdb.ctx.IsCheckTx() {
funcName := analyzer.RunFuncName()
analyzer.StartTxLog(funcName)
defer analyzer.StopTxLog(funcName)
}
if _, ok := csdb.hashToPreimageIndex[hash]; !ok {
csdb.journal.append(addPreimageChange{hash: hash})
pi := make([]byte, len(preimage))
copy(pi, preimage)
csdb.preimages = append(csdb.preimages, preimageEntry{hash: hash, preimage: pi})
csdb.hashToPreimageIndex[hash] = len(csdb.preimages) - 1
}
}
// AddRefund adds gas to the refund counter.
func (csdb *CommitStateDB) AddRefund(gas uint64) {
if !csdb.ctx.IsCheckTx() {
funcName := analyzer.RunFuncName()
analyzer.StartTxLog(funcName)
defer analyzer.StopTxLog(funcName)
}
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) {
if !csdb.ctx.IsCheckTx() {
funcName := analyzer.RunFuncName()
analyzer.StartTxLog(funcName)
defer analyzer.StopTxLog(funcName)
}
csdb.journal.append(refundChange{prev: csdb.refund})
if gas > csdb.refund {
panic("refund counter below zero")
}
csdb.refund -= gas
}
// AddAddressToAccessList adds the given address to the access list
func (csdb *CommitStateDB) AddAddressToAccessList(addr ethcmn.Address) {
if !csdb.ctx.IsCheckTx() {
funcName := analyzer.RunFuncName()
analyzer.StartTxLog(funcName)
defer analyzer.StopTxLog(funcName)
}
if csdb.accessList.AddAddress(addr) {
csdb.journal.append(accessListAddAccountChange{&addr})
}
}
// AddSlotToAccessList adds the given (address, slot)-tuple to the access list
func (csdb *CommitStateDB) AddSlotToAccessList(addr ethcmn.Address, slot ethcmn.Hash) {
if !csdb.ctx.IsCheckTx() {
funcName := analyzer.RunFuncName()
analyzer.StartTxLog(funcName)
defer analyzer.StopTxLog(funcName)
}
addrMod, slotMod := csdb.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
csdb.journal.append(accessListAddAccountChange{&addr})
}
if slotMod {
csdb.journal.append(accessListAddSlotChange{
address: &addr,
slot: &slot,
})
}
}
func (csdb *CommitStateDB) PrepareAccessList(sender ethcmn.Address, dest *ethcmn.Address, precompiles []ethcmn.Address, txAccesses ethtypes.AccessList) {
if !csdb.ctx.IsCheckTx() {
funcName := analyzer.RunFuncName()
analyzer.StartTxLog(funcName)
defer analyzer.StopTxLog(funcName)
}
csdb.AddAddressToAccessList(sender)
if csdb != nil {
csdb.AddAddressToAccessList(*dest)
// If it's a create-tx, the destination will be added inside evm.create
}
for _, addr := range precompiles {
csdb.AddAddressToAccessList(addr)
}
for _, el := range txAccesses {
csdb.AddAddressToAccessList(el.Address)
for _, key := range el.StorageKeys {
csdb.AddSlotToAccessList(el.Address, key)
}
}
}
// AddressInAccessList returns true if the given address is in the access list.
func (csdb *CommitStateDB) AddressInAccessList(addr ethcmn.Address) bool {
if !csdb.ctx.IsCheckTx() {
funcName := analyzer.RunFuncName()
analyzer.StartTxLog(funcName)
defer analyzer.StopTxLog(funcName)
}
return csdb.accessList.ContainsAddress(addr)
}
// SlotInAccessList returns true if the given (address, slot)-tuple is in the access list.
func (csdb *CommitStateDB) SlotInAccessList(addr ethcmn.Address, slot ethcmn.Hash) (bool, bool) {
if !csdb.ctx.IsCheckTx() {
funcName := analyzer.RunFuncName()
analyzer.StartTxLog(funcName)
defer analyzer.StopTxLog(funcName)
}
return csdb.accessList.Contains(addr, slot)
}
// ----------------------------------------------------------------------------
// Getters
// ----------------------------------------------------------------------------
// GetHeightHash returns the block header hash associated with a given block height and chain epoch number.
func (csdb *CommitStateDB) GetHeightHash(height uint64) ethcmn.Hash {
store := csdb.dbAdapter.NewStore(csdb.ctx.KVStore(csdb.storeKey), KeyPrefixHeightHash)
key := HeightHashKey(height)
bz := store.Get(key)
if len(bz) == 0 {
return ethcmn.Hash{}
}
return ethcmn.BytesToHash(bz)
}
// GetParams returns the total set of evm parameters.
func (csdb *CommitStateDB) GetParams() Params {
if csdb.params == nil {
var params Params
csdb.paramSpace.GetParamSet(csdb.ctx, ¶ms)
csdb.params = ¶ms
}
return *csdb.params
}
// GetBalance retrieves the balance from the given address or 0 if object not
// found.
func (csdb *CommitStateDB) GetBalance(addr ethcmn.Address) *big.Int {
if !csdb.ctx.IsCheckTx() {
funcName := analyzer.RunFuncName()
analyzer.StartTxLog(funcName)
defer analyzer.StopTxLog(funcName)
}
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 ethcmn.Address) uint64 {
if !csdb.ctx.IsCheckTx() {
funcName := analyzer.RunFuncName()
analyzer.StartTxLog(funcName)
defer analyzer.StopTxLog(funcName)
}
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() ethcmn.Hash {
return csdb.bhash
}
func (csdb *CommitStateDB) SetBlockHash(hash ethcmn.Hash) {
csdb.bhash = hash
}
// GetCode returns the code for a given account.
func (csdb *CommitStateDB) GetCode(addr ethcmn.Address) []byte {
if !csdb.ctx.IsCheckTx() {
funcName := analyzer.RunFuncName()
analyzer.StartTxLog(funcName)
defer analyzer.StopTxLog(funcName)
}
// check for the contract calling from blocked list if contract blocked list is enabled
if csdb.GetParams().EnableContractBlockedList && csdb.IsContractInBlockedList(addr.Bytes()) {
panic(addr)
}
so := csdb.getStateObject(addr)
if so != nil {
return so.Code(nil)
}
return nil
}
// GetCode returns the code for a given code hash.
func (csdb *CommitStateDB) GetCodeByHash(hash ethcmn.Hash) []byte {
ctx := csdb.ctx
store := csdb.dbAdapter.NewStore(ctx.KVStore(csdb.storeKey), KeyPrefixCode)
code := store.Get(hash.Bytes())
return code
}
// GetCodeSize returns the code size for a given account.
func (csdb *CommitStateDB) GetCodeSize(addr ethcmn.Address) int {
if !csdb.ctx.IsCheckTx() {
funcName := analyzer.RunFuncName()
analyzer.StartTxLog(funcName)
defer analyzer.StopTxLog(funcName)
}
so := csdb.getStateObject(addr)
if so == nil {
return 0
}
if so.code != nil {
return len(so.code)
}
return len(so.Code(nil))
}
// GetCodeHash returns the code hash for a given account.
func (csdb *CommitStateDB) GetCodeHash(addr ethcmn.Address) ethcmn.Hash {
if !csdb.ctx.IsCheckTx() {
funcName := analyzer.RunFuncName()
analyzer.StartTxLog(funcName)
defer analyzer.StopTxLog(funcName)
}
so := csdb.getStateObject(addr)
if so == nil {
return ethcmn.Hash{}
}
return ethcmn.BytesToHash(so.CodeHash())
}
// GetState retrieves a value from the given account's storage store.
func (csdb *CommitStateDB) GetState(addr ethcmn.Address, hash ethcmn.Hash) ethcmn.Hash {
if !csdb.ctx.IsCheckTx() {
funcName := analyzer.RunFuncName()
analyzer.StartTxLog(funcName)
defer analyzer.StopTxLog(funcName)
}
so := csdb.getStateObject(addr)
if so != nil {
return so.GetState(nil, hash)
}
return ethcmn.Hash{}
}
// GetStateByKey retrieves a value from the given account's storage store.
func (csdb *CommitStateDB) GetStateByKey(addr ethcmn.Address, hash ethcmn.Hash) ethcmn.Hash {
ctx := csdb.ctx
store := csdb.dbAdapter.NewStore(ctx.KVStore(csdb.storeKey), AddressStoragePrefix(addr))
data := store.Get(hash.Bytes())
return ethcmn.BytesToHash(data)
}
// GetCommittedState retrieves a value from the given account's committed
// storage.
func (csdb *CommitStateDB) GetCommittedState(addr ethcmn.Address, hash ethcmn.Hash) ethcmn.Hash {
if !csdb.ctx.IsCheckTx() {
funcName := analyzer.RunFuncName()
analyzer.StartTxLog(funcName)
defer analyzer.StopTxLog(funcName)
}
so := csdb.getStateObject(addr)
if so != nil {
return so.GetCommittedState(nil, hash)
}
return ethcmn.Hash{}
}
// GetLogs returns the current logs for a given transaction hash from the KVStore.
func (csdb *CommitStateDB) GetLogs(hash ethcmn.Hash) ([]*ethtypes.Log, error) {
return csdb.logs, nil
}
// GetRefund returns the current value of the refund counter.
func (csdb *CommitStateDB) GetRefund() uint64 {
if !csdb.ctx.IsCheckTx() {
funcName := analyzer.RunFuncName()
analyzer.StartTxLog(funcName)
defer analyzer.StopTxLog(funcName)
}
return csdb.refund
}
// Preimages returns a list of SHA3 preimages that have been submitted.
func (csdb *CommitStateDB) Preimages() map[ethcmn.Hash][]byte {
preimages := map[ethcmn.Hash][]byte{}
for _, pe := range csdb.preimages {
preimages[pe.hash] = pe.preimage
}
return preimages
}
// HasSuicided returns if the given account for the specified address has been
// killed.
func (csdb *CommitStateDB) HasSuicided(addr ethcmn.Address) bool {
if !csdb.ctx.IsCheckTx() {
funcName := analyzer.RunFuncName()
analyzer.StartTxLog(funcName)
defer analyzer.StopTxLog(funcName)
}
so := csdb.getStateObject(addr)
if so != nil {
return so.suicided
}
return false
}
// StorageTrie returns nil as the state in Ethermint does not use a direct
// storage trie.
func (csdb *CommitStateDB) StorageTrie(addr ethcmn.Address) ethstate.Trie {
return nil
}
// ----------------------------------------------------------------------------
// 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) (ethcmn.Hash, error) {
defer csdb.clearJournalAndRefund()
// remove dirty state object entries based on the journal
for _, dirty := range csdb.journal.dirties {
csdb.stateObjectsDirty[dirty.address] = struct{}{}
}
// set the state objects
for _, stateEntry := range csdb.stateObjects {
_, isDirty := csdb.stateObjectsDirty[stateEntry.address]
switch {
case stateEntry.stateObject.suicided || (isDirty && deleteEmptyObjects && stateEntry.stateObject.empty()):
// If the state object has been removed, don't bother syncing it and just
// remove it from the store.
csdb.deleteStateObject(stateEntry.stateObject)
case isDirty:
// write any contract code associated with the state object
if stateEntry.stateObject.code != nil && stateEntry.stateObject.dirtyCode {
stateEntry.stateObject.commitCode()
stateEntry.stateObject.dirtyCode = false
}
// update the object in the KVStore
if err := csdb.updateStateObject(stateEntry.stateObject); err != nil {
return ethcmn.Hash{}, err
}
}
delete(csdb.stateObjectsDirty, stateEntry.address)
}
// 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 ethcmn.Hash{}, nil
}
// 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) error {
for _, dirty := range csdb.journal.dirties {
idx, exist := csdb.addressToObjectIndex[dirty.address]
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
}
stateEntry := csdb.stateObjects[idx]
if stateEntry.stateObject.suicided || (deleteEmptyObjects && stateEntry.stateObject.empty()) {
csdb.deleteStateObject(stateEntry.stateObject)
} else {
// Set all the dirty state storage items for the state object in the
// KVStore and finally set the account in the account mapper.
stateEntry.stateObject.commitState()
if err := csdb.updateStateObject(stateEntry.stateObject); err != nil {
return err
}
}
csdb.stateObjectsDirty[dirty.address] = struct{}{}
}
// invalidate journal because reverting across transactions is not allowed
csdb.clearJournalAndRefund()
csdb.DeleteLogs(csdb.thash)
return nil
}
// 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) (ethcmn.Hash, error) {
if err := csdb.Finalise(deleteEmptyObjects); err != nil {
return ethcmn.Hash{}, err
}
return ethcmn.Hash{}, nil
}
// updateStateObject writes the given state object to the store.
func (csdb *CommitStateDB) updateStateObject(so *stateObject) error {
// NOTE: we don't use sdk.NewCoin here to avoid panic on test importer's genesis
newBalance := sdk.Coin{Denom: sdk.DefaultBondDenom, Amount: sdk.NewDecFromBigIntWithPrec(so.Balance(), sdk.Precision)} // int2dec
if !newBalance.IsValid() {
return fmt.Errorf("invalid balance %s", newBalance)
}
//checking and reject tx if address in blacklist
if csdb.bankKeeper.BlacklistedAddr(so.account.GetAddress()) {
return fmt.Errorf("address <%s> in blacklist is not allowed", so.account.GetAddress().String())
}
coins := so.account.GetCoins()
balance := coins.AmountOf(newBalance.Denom)
if balance.IsZero() || !balance.Equal(newBalance.Amount) {
coins = coins.Add(newBalance)
}
if err := so.account.SetCoins(coins); err != nil {
return err
}
csdb.accountKeeper.SetAccount(csdb.ctx, so.account)
if !csdb.ctx.IsCheckTx() {
if csdb.Watcher.Enabled() {
csdb.Watcher.SaveAccount(so.account, false)
}
}
// return csdb.bankKeeper.SetBalance(csdb.ctx, so.account.Address, newBalance)
return nil
}
// deleteStateObject removes the given state object from the state store.
func (csdb *CommitStateDB) deleteStateObject(so *stateObject) {
so.deleted = true
csdb.accountKeeper.RemoveAccount(csdb.ctx, so.account)
}
// ----------------------------------------------------------------------------
// Snapshotting
// ----------------------------------------------------------------------------
// Snapshot returns an identifier for the current revision of the state.
func (csdb *CommitStateDB) Snapshot() int {
if !csdb.ctx.IsCheckTx() {
funcName := analyzer.RunFuncName()
analyzer.StartTxLog(funcName)
defer analyzer.StopTxLog(funcName)
}
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) {
if !csdb.ctx.IsCheckTx() {
funcName := analyzer.RunFuncName()
analyzer.StartTxLog(funcName)
defer analyzer.StopTxLog(funcName)
}
// 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 ethcmn.Address) bool {
if !csdb.ctx.IsCheckTx() {
funcName := analyzer.RunFuncName()
analyzer.StartTxLog(funcName)
defer analyzer.StopTxLog(funcName)
}
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 ethcmn.Address) bool {
if !csdb.ctx.IsCheckTx() {
funcName := analyzer.RunFuncName()
analyzer.StartTxLog(funcName)
defer analyzer.StopTxLog(funcName)
}
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 ethcmn.Address) bool {
if !csdb.ctx.IsCheckTx() {
funcName := analyzer.RunFuncName()
analyzer.StartTxLog(funcName)
defer analyzer.StopTxLog(funcName)
}
so := csdb.getStateObject(addr)
if so == nil {
return false
}
csdb.journal.append(suicideChange{
account: &addr,
prev: so.suicided,
prevBalance: sdk.NewDecFromBigIntWithPrec(so.Balance(), sdk.Precision), // int2dec
})
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(_ ethcmn.Hash) error {
csdb.stateObjects = []stateEntry{}
csdb.addressToObjectIndex = make(map[ethcmn.Address]int)
csdb.stateObjectsDirty = make(map[ethcmn.Address]struct{})