-
Notifications
You must be signed in to change notification settings - Fork 1.5k
Expand file tree
/
Copy pathversionedio.go
More file actions
1631 lines (1418 loc) · 48.2 KB
/
versionedio.go
File metadata and controls
1631 lines (1418 loc) · 48.2 KB
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 state
import (
"bytes"
"encoding/hex"
"errors"
"fmt"
"reflect"
"slices"
"sort"
"strconv"
"github.com/heimdalr/dag"
"github.com/holiman/uint256"
"github.com/erigontech/erigon/common/dbg"
"github.com/erigontech/erigon/common/log/v3"
"github.com/erigontech/erigon/execution/protocol/params"
"github.com/erigontech/erigon/execution/tracing"
"github.com/erigontech/erigon/execution/types"
"github.com/erigontech/erigon/execution/types/accounts"
)
type ReadSource int
func (s ReadSource) String() string {
switch s {
case MapRead:
return "version-map"
case StorageRead:
return "storage"
case WriteSetRead:
return "tx-writes"
case ReadSetRead:
return "tx-reads"
default:
return "unknown"
}
}
func (s ReadSource) VersionedString(version Version) string {
switch s {
case MapRead:
return fmt.Sprintf("version-map:%d.%d", version.TxIndex, version.Incarnation)
case StorageRead:
return "storage"
case WriteSetRead:
return "tx-writes"
case ReadSetRead:
return "tx-reads"
default:
return "unknown"
}
}
const (
UnknownSource ReadSource = iota
MapRead
StorageRead
WriteSetRead
ReadSetRead
)
type ReadSet map[accounts.Address]map[AccountKey]VersionedRead
func (a ReadSet) Merge(b ReadSet) ReadSet {
if a == nil && b == nil {
return nil
}
out := make(ReadSet)
if a != nil {
a.Scan(func(vr *VersionedRead) bool {
out.Set(*vr)
return true
})
}
if b != nil {
b.Scan(func(vr *VersionedRead) bool {
out.Set(*vr)
return true
})
}
return out
}
func (rs ReadSet) Set(v VersionedRead) {
reads, ok := rs[v.Address]
if !ok {
rs[v.Address] = map[AccountKey]VersionedRead{
{v.Path, v.Key}: v,
}
} else {
reads[AccountKey{v.Path, v.Key}] = v
}
}
func (s ReadSet) Scan(yield func(input *VersionedRead) bool) {
for _, reads := range s {
for _, v := range reads {
if !yield(&v) {
return
}
}
}
}
func (s ReadSet) Len() int {
var l int
for _, p := range s {
l += len(p)
}
return l
}
func (s ReadSet) Delete(addr accounts.Address, key AccountKey) {
if reads, ok := s[addr]; ok {
delete(reads, key)
if len(reads) == 0 {
delete(s, addr)
}
}
}
type WriteSet map[accounts.Address]map[AccountKey]VersionedWrite
func (s WriteSet) Set(v VersionedWrite) {
writes, ok := s[v.Address]
if !ok {
s[v.Address] = map[AccountKey]VersionedWrite{
{v.Path, v.Key}: v,
}
} else {
writes[AccountKey{v.Path, v.Key}] = v
}
}
// UpdateVal updates the Val field of an existing entry. Returns true if the entry was found.
func (s WriteSet) UpdateVal(addr accounts.Address, key AccountKey, val any) bool {
if writes, ok := s[addr]; ok {
if v, ok := writes[key]; ok {
v.Val = val
writes[key] = v
return true
}
}
return false
}
func (s WriteSet) Delete(addr accounts.Address, key AccountKey) {
if writes, ok := s[addr]; ok {
delete(writes, key)
if len(writes) == 0 {
delete(s, addr)
}
}
}
func (s WriteSet) Len() int {
var l int
for _, p := range s {
l += len(p)
}
return l
}
func (s WriteSet) Scan(yield func(input *VersionedWrite) bool) {
for _, writes := range s {
for _, v := range writes {
if !yield(&v) {
return
}
}
}
}
type VersionedRead struct {
Address accounts.Address
Path AccountPath
Key accounts.StorageKey
Source ReadSource
Version Version
Val any
internal bool // when true, read is used for conflict detection only; excluded from BAL
}
func (vr VersionedRead) String() string {
return fmt.Sprintf("(%s) %x %s: %s", vr.Source.VersionedString(vr.Version), vr.Address, AccountKey{Path: vr.Path, Key: vr.Key}, valueString(vr.Path, vr.Val))
}
type VersionedWrite struct {
Address accounts.Address
Path AccountPath
Key accounts.StorageKey
Version Version
Val any
Reason tracing.BalanceChangeReason
}
func (vr VersionedWrite) String() string {
return fmt.Sprintf("%x %s: %s (%d.%d)", vr.Address, AccountKey{Path: vr.Path, Key: vr.Key}, valueString(vr.Path, vr.Val), vr.Version.TxIndex, vr.Version.Incarnation)
}
func valueString(path AccountPath, value any) string {
if value == nil {
return "<nil>"
}
switch path {
case AddressPath:
return fmt.Sprintf("%+v", value)
case BalancePath:
num := value.(uint256.Int)
return (&num).String()
case StoragePath:
num := value.(uint256.Int)
return fmt.Sprintf("%x", &num)
case NoncePath, IncarnationPath:
return strconv.FormatUint(value.(uint64), 10)
case CodePath:
l := min(len(value.([]byte)), 40)
return hex.EncodeToString(value.([]byte)[0:l])
}
return fmt.Sprint(value)
}
var ErrDependency = errors.New("found dependency")
type versionedStateReader struct {
txIndex int
reads ReadSet
versionMap *VersionMap
stateReader StateReader
}
func NewVersionedStateReader(txIndex int, reads ReadSet, versionMap *VersionMap, stateReader StateReader) *versionedStateReader {
return &versionedStateReader{txIndex, reads, versionMap, stateReader}
}
func (vr *versionedStateReader) SetTrace(trace bool, tracePrefix string) {
vr.stateReader.SetTrace(trace, tracePrefix)
}
func (vr *versionedStateReader) Trace() bool {
return vr.stateReader.Trace()
}
func (vr *versionedStateReader) TracePrefix() string {
return vr.stateReader.TracePrefix()
}
func (vr *versionedStateReader) ReadAccountData(address accounts.Address) (*accounts.Account, error) {
if r, ok := vr.reads[address][AccountKey{Path: AddressPath}]; ok && r.Val != nil {
if account, ok := r.Val.(*accounts.Account); ok && account != nil {
updated := vr.applyVersionedUpdates(address, *account)
return &updated, nil
}
}
// Check version map for AddressPath — handles accounts created by
// prior transactions in the same block that aren't in the read set.
if vr.versionMap != nil {
// A prior tx may have self-destructed this account. If so, the
// account must be treated as non-existent even if the version map
// still holds the pre-destruct AddressPath entry.
if res := vr.versionMap.Read(address, SelfDestructPath, accounts.NilKey, vr.txIndex); res.Status() == MVReadResultDone {
if destructed, ok := res.Value().(bool); ok && destructed {
return nil, nil
}
}
if acc, ok := versionedUpdate[*accounts.Account](vr.versionMap, address, AddressPath, accounts.NilKey, vr.txIndex); ok && acc != nil {
updated := vr.applyVersionedUpdates(address, *acc)
return &updated, nil
}
}
if vr.stateReader != nil {
account, err := vr.stateReader.ReadAccountData(address)
if err != nil {
return nil, err
}
if account != nil {
updated := vr.applyVersionedUpdates(address, *account)
return &updated, nil
}
}
return nil, nil
}
func versionedUpdate[T any](versionMap *VersionMap, addr accounts.Address, path AccountPath, key accounts.StorageKey, txIndex int) (T, bool) {
if res := versionMap.Read(addr, path, key, txIndex); res.Status() == MVReadResultDone {
return res.Value().(T), true
}
var v T
return v, false
}
// applyVersionedUpdates applies updated from the version map to the account before returning it, this is necessary
// for the account obkect becuase the state reader/.writer api's treat the subfileds as a group and this
// may lead to updated from pervious transactions being missed where we only update a subset of the fiels as these won't
// be recored as reads and hence the varification process will miss them. We don't want to creat a fail but
// we do want to capture the updates
func (vr versionedStateReader) applyVersionedUpdates(address accounts.Address, account accounts.Account) accounts.Account {
if update, ok := versionedUpdate[uint256.Int](vr.versionMap, address, BalancePath, accounts.NilKey, vr.txIndex); ok {
account.Balance = update
}
if update, ok := versionedUpdate[uint64](vr.versionMap, address, NoncePath, accounts.NilKey, vr.txIndex); ok {
account.Nonce = update
}
if update, ok := versionedUpdate[uint64](vr.versionMap, address, IncarnationPath, accounts.NilKey, vr.txIndex); ok {
account.Incarnation = update
}
if update, ok := versionedUpdate[accounts.CodeHash](vr.versionMap, address, CodeHashPath, accounts.NilKey, vr.txIndex); ok {
account.CodeHash = update
}
return account
}
func (vr versionedStateReader) ReadAccountDataForDebug(address accounts.Address) (*accounts.Account, error) {
if r, ok := vr.reads[address][AccountKey{Path: AddressPath}]; ok && r.Val != nil {
if account, ok := r.Val.(*accounts.Account); ok {
updated := vr.applyVersionedUpdates(address, *account)
return &updated, nil
}
}
if vr.stateReader != nil {
account, err := vr.stateReader.ReadAccountDataForDebug(address)
if err != nil {
return nil, err
}
updated := vr.applyVersionedUpdates(address, *account)
return &updated, nil
}
return nil, nil
}
func (vr versionedStateReader) ReadAccountStorage(address accounts.Address, key accounts.StorageKey) (uint256.Int, bool, error) {
if r, ok := vr.reads[address][AccountKey{Path: StoragePath, Key: key}]; ok && r.Val != nil {
val := r.Val.(uint256.Int)
return val, true, nil
}
// Check version map for storage written by prior transactions.
if vr.versionMap != nil {
if res := vr.versionMap.Read(address, SelfDestructPath, accounts.NilKey, vr.txIndex); res.Status() == MVReadResultDone {
if destructed, ok := res.Value().(bool); ok && destructed {
return uint256.Int{}, false, nil
}
}
if val, ok := versionedUpdate[uint256.Int](vr.versionMap, address, StoragePath, key, vr.txIndex); ok {
return val, true, nil
}
}
if vr.stateReader != nil {
return vr.stateReader.ReadAccountStorage(address, key)
}
return uint256.Int{}, false, nil
}
func (vr versionedStateReader) HasStorage(address accounts.Address) (bool, error) {
if r, ok := vr.reads[address]; ok {
for k := range r {
if k.Path == StoragePath {
return true, nil
}
}
}
if vr.stateReader != nil {
return vr.stateReader.HasStorage(address)
}
return false, nil
}
func (vr versionedStateReader) ReadAccountCode(address accounts.Address) ([]byte, error) {
if r, ok := vr.reads[address][AccountKey{Path: CodePath}]; ok && r.Val != nil {
if code, ok := r.Val.([]byte); ok {
return code, nil
}
}
// Check version map for CodePath entries written by prior transactions
// (e.g. EIP-7702 delegation set by an earlier tx in the same block).
if vr.versionMap != nil {
if res := vr.versionMap.Read(address, SelfDestructPath, accounts.NilKey, vr.txIndex); res.Status() == MVReadResultDone {
if destructed, ok := res.Value().(bool); ok && destructed {
return nil, nil
}
}
if code, ok := versionedUpdate[[]byte](vr.versionMap, address, CodePath, accounts.NilKey, vr.txIndex); ok {
return code, nil
}
}
if vr.stateReader != nil {
return vr.stateReader.ReadAccountCode(address)
}
return nil, nil
}
func (vr versionedStateReader) ReadAccountCodeSize(address accounts.Address) (int, error) {
if r, ok := vr.reads[address][AccountKey{Path: CodePath}]; ok && r.Val != nil {
if code, ok := r.Val.([]byte); ok {
return len(code), nil
}
}
if vr.versionMap != nil {
if res := vr.versionMap.Read(address, SelfDestructPath, accounts.NilKey, vr.txIndex); res.Status() == MVReadResultDone {
if destructed, ok := res.Value().(bool); ok && destructed {
return 0, nil
}
}
if code, ok := versionedUpdate[[]byte](vr.versionMap, address, CodePath, accounts.NilKey, vr.txIndex); ok {
return len(code), nil
}
}
if vr.stateReader != nil {
return vr.stateReader.ReadAccountCodeSize(address)
}
return 0, nil
}
func (vr versionedStateReader) ReadAccountIncarnation(address accounts.Address) (uint64, error) {
if r, ok := vr.reads[address][AccountKey{Path: AddressPath}]; ok && r.Val != nil {
return r.Val.(*accounts.Account).Incarnation, nil
}
if vr.stateReader != nil {
return vr.stateReader.ReadAccountIncarnation(address)
}
return 0, nil
}
type VersionedWrites []*VersionedWrite
// sortVersionedWrites sorts a VersionedWrites slice by (Address, Path, Key)
// to ensure deterministic processing order. VersionedWrites originate from
// WriteSet map iteration which has non-deterministic order in Go.
// The sort relies on the AccountPath enum ordering defined in versionmap.go.
func sortVersionedWrites(writes VersionedWrites) {
sort.Slice(writes, func(i, j int) bool {
if c := writes[i].Address.Cmp(writes[j].Address); c != 0 {
return c < 0
}
if writes[i].Path != writes[j].Path {
return writes[i].Path < writes[j].Path
}
return writes[i].Key.Cmp(writes[j].Key) < 0
})
}
func (prev VersionedWrites) Merge(next VersionedWrites) VersionedWrites {
if len(prev) == 0 {
return next
}
if len(next) == 0 {
return prev
}
merged := WriteSet{}
for _, v := range prev {
merged.Set(*v)
}
for _, v := range next {
merged.Set(*v)
}
out := make(VersionedWrites, 0, merged.Len())
merged.Scan(func(v *VersionedWrite) bool {
out = append(out, v)
return true
})
return out
}
// hasNewWrite: returns true if the current set has a new write compared to the input
func (writes VersionedWrites) HasNewWrite(cmpSet []*VersionedWrite) bool {
if len(writes) == 0 {
return false
} else if len(cmpSet) == 0 || len(writes) > len(cmpSet) {
return true
}
cmpMap := map[accounts.Address]map[AccountKey]struct{}{}
for _, vw := range cmpSet {
keys, ok := cmpMap[vw.Address]
if !ok {
keys = map[AccountKey]struct{}{}
cmpMap[vw.Address] = keys
}
keys[AccountKey{vw.Path, vw.Key}] = struct{}{}
}
for _, v := range writes {
if _, ok := cmpMap[v.Address][AccountKey{v.Path, v.Key}]; !ok {
return true
}
}
return false
}
// StripBalanceWrite removes the BalancePath write for addr from the write set
// and computes the TX's net balance delta by comparing the stale write with
// the stale read from readSet. This is used in finalize to prevent stale
// speculative coinbase/burnt-contract balance writes from being applied via
// ApplyVersionedWrites. The delta is returned so it can be applied separately
// on top of the correct base balance from the VersionedStateReader.
//
// Returns:
// - stripped: the write set with the balance write removed
// - delta: the absolute difference between stale write and stale read
// - increase: true if the TX increased the balance, false if decreased
// - found: true if both a stale read and write were found and a non-zero delta computed
func (writes VersionedWrites) StripBalanceWrite(addr accounts.Address, readSet ReadSet) (stripped VersionedWrites, delta uint256.Int, increase bool, found bool) {
stripped = writes
if addr.IsNil() {
return
}
reads, ok := readSet[addr]
if !ok {
// TX didn't read this address — no delta to compute.
// Still strip the write to prevent stale cache pollution.
for i, w := range stripped {
if w.Address == addr && w.Path == BalancePath {
stripped = append(stripped[:i], stripped[i+1:]...)
return
}
}
return
}
balKey := AccountKey{Path: BalancePath, Key: accounts.NilKey}
balRead, ok := reads[balKey]
if !ok {
return
}
staleRead, ok := balRead.Val.(uint256.Int)
if !ok {
return
}
for i, w := range stripped {
if w.Address == addr && w.Path == BalancePath {
staleWrite, ok := w.Val.(uint256.Int)
if !ok {
break
}
// Remove the stale absolute write
stripped = append(stripped[:i], stripped[i+1:]...)
// Compute the TX's net effect on this balance
if staleWrite.Gt(&staleRead) {
delta.Sub(&staleWrite, &staleRead)
increase = true
found = true
} else if staleRead.Gt(&staleWrite) {
delta.Sub(&staleRead, &staleWrite)
increase = false
found = true
}
return
}
}
return
}
// SetBalance replaces the BalancePath write for addr in the write set with
// the given value. If no existing BalancePath write is found, a new entry is
// appended. This is used in the direct finalize path to adjust fee-calc
// balances in pre-computed collector writes without IBS reconstruction.
func (writes VersionedWrites) SetBalance(addr accounts.Address, val uint256.Int, reason tracing.BalanceChangeReason) VersionedWrites {
for _, w := range writes {
if w.Address == addr && w.Path == BalancePath {
w.Val = val
w.Reason = reason
return writes
}
}
return append(writes, &VersionedWrite{Address: addr, Path: BalancePath, Val: val, Reason: reason})
}
// SetAccountBalanceOrDelete replaces the BalancePath write for addr. If the
// address has no existing writes in the set, all four account fields (balance,
// nonce, incarnation, codeHash) are emitted so that applyVersionedWrites can
// reconstruct a complete account. Without the full set, it would create an
// account with nonce=0, incarnation=0, empty codeHash — wiping the real values.
//
// When emptyRemoval is true (EIP-161 SpuriousDragon), if the final account
// would be empty (balance=0, nonce=0, empty code), the existing writes for
// this address are stripped and a SelfDestructPath entry is emitted instead.
func (writes VersionedWrites) SetAccountBalanceOrDelete(addr accounts.Address, acc *accounts.Account, val uint256.Int, reason tracing.BalanceChangeReason, emptyRemoval bool) VersionedWrites {
if acc == nil {
a := accounts.NewAccount()
acc = &a
}
// EIP-161: if the final account is empty, delete it.
if emptyRemoval && val.IsZero() && acc.Nonce == 0 && acc.IsEmptyCodeHash() {
// Strip any existing writes for this address and emit a delete.
filtered := make(VersionedWrites, 0, len(writes)+1)
for _, w := range writes {
if w.Address != addr {
filtered = append(filtered, w)
}
}
return append(filtered, &VersionedWrite{Address: addr, Path: SelfDestructPath, Val: true})
}
for _, w := range writes {
if w.Address == addr && w.Path == BalancePath {
w.Val = val
w.Reason = reason
return writes
}
}
// Account not in writes — emit complete account fields.
return append(writes,
&VersionedWrite{Address: addr, Path: BalancePath, Val: val, Reason: reason},
&VersionedWrite{Address: addr, Path: NoncePath, Val: acc.Nonce},
&VersionedWrite{Address: addr, Path: IncarnationPath, Val: acc.Incarnation},
&VersionedWrite{Address: addr, Path: CodeHashPath, Val: acc.CodeHash},
)
}
func versionedRead[T any](s *IntraBlockState, addr accounts.Address, path AccountPath, key accounts.StorageKey, commited bool, defaultV T, copyV func(T) T, readStorage func(sdb *stateObject) (T, error)) (T, ReadSource, Version, error) {
if s.versionMap == nil {
so, err := s.getStateObject(addr, true)
if err != nil || readStorage == nil {
return defaultV, StorageRead, UnknownVersion, err
}
val, err := readStorage(so)
return val, StorageRead, UnknownVersion, err
}
var destrcutedVersion Version
if so, ok := s.stateObjects[addr]; ok && so.deleted {
return defaultV, StorageRead, UnknownVersion, nil
} else if res := s.versionMap.Read(addr, SelfDestructPath, accounts.NilKey, s.txIndex); res.Status() == MVReadResultDone && res.value.(bool) {
if path != CodePath {
// A prior tx self-destructed this account — all state reads must
// return the zero value of the type, not the caller-supplied default.
// refreshVersionedAccount passes the account's pre-destruction field
// values as defaultV, so using defaultV here would return stale data.
var zero T
sdVersion := Version{TxIndex: res.DepIdx(), Incarnation: res.Incarnation()}
if commited {
return zero, MapRead, sdVersion, nil
}
if vw, ok := s.versionedWrite(addr, SelfDestructPath, key); !ok || vw.Val.(bool) {
// Record the SelfDestructPath dependency so that
// ValidateVersion can verify the destruct is still
// valid. Without this entry the readSet would be
// empty for the affected address, and validation
// would have nothing to cross-check — allowing
// skipCheck to commit stale results.
if s.versionedReads == nil {
s.versionedReads = ReadSet{}
}
s.versionedReads.Set(VersionedRead{
Address: addr,
Path: SelfDestructPath,
Key: accounts.NilKey,
Source: MapRead,
Version: sdVersion,
Val: true,
})
return zero, MapRead, sdVersion, nil
}
destrcutedVersion = Version{
TxIndex: res.DepIdx(),
}
}
}
res := s.versionMap.Read(addr, path, key, s.txIndex)
var v T
var vr = VersionedRead{
Address: addr,
Path: path,
Key: key,
Version: Version{
TxIndex: res.DepIdx(),
Incarnation: res.Incarnation(),
},
}
if !commited {
if vw, ok := s.versionedWrite(addr, path, key); ok {
if res.Status() == MVReadResultDone {
if pr, ok := s.versionedReads[addr][AccountKey{Path: path, Key: key}]; ok {
if vr.Version.TxIndex > destrcutedVersion.TxIndex && vr.Version != pr.Version {
if vr.Version.TxIndex > s.dep {
s.dep = vr.Version.TxIndex
}
if dbg.TraceTransactionIO && (s.trace || dbg.TraceAccount(addr.Handle())) {
fmt.Printf("%d (%d.%d) WR DEP (%d.%d)!=(%d.%d) %x %s: %s\n", s.blockNum, s.txIndex, s.version, pr.Version.TxIndex, pr.Version.Incarnation, vr.Version.TxIndex, vr.Version.Incarnation, addr, AccountKey{path, key}, valueString(path, pr.Val))
}
if s.versionedReads == nil {
s.versionedReads = ReadSet{}
}
s.versionedReads.Set(vr)
panic(ErrDependency)
}
}
}
if dbg.TraceTransactionIO && (s.trace || dbg.TraceAccount(addr.Handle())) {
fmt.Printf("%d (%d.%d) RD (%s) %x %s: %s\n", s.blockNum, s.txIndex, s.version, WriteSetRead, addr, AccountKey{path, key}, valueString(path, vw.Val))
}
val := vw.Val.(T)
return val, WriteSetRead, Version{TxIndex: s.txIndex, Incarnation: s.version}, nil
}
}
switch res.Status() {
case MVReadResultDone:
vr.Source = MapRead
if pr, ok := s.versionedReads[addr][AccountKey{Path: path, Key: key}]; ok {
if pr.Version == vr.Version {
if dbg.TraceTransactionIO && (s.trace || dbg.TraceAccount(addr.Handle())) {
fmt.Printf("%d (%d.%d) RD (%s:%s) %x %s: %s\n", s.blockNum, s.txIndex, s.version, MapRead, res.DepString(), addr, AccountKey{path, key}, valueString(path, pr.Val))
}
return pr.Val.(T), vr.Source, vr.Version, nil
}
if vr.Version.TxIndex > s.dep {
s.dep = vr.Version.TxIndex
}
if dbg.TraceTransactionIO && (s.trace || dbg.TraceAccount(addr.Handle())) {
fmt.Printf("%d (%d.%d) RD DEP (%d.%d)!=(%d.%d) %x %s\n", s.blockNum, s.txIndex, s.version, pr.Version.TxIndex, pr.Version.Incarnation, vr.Version.TxIndex, vr.Version.Incarnation, addr, AccountKey{path, key})
}
if s.versionedReads == nil {
s.versionedReads = ReadSet{}
}
s.versionedReads.Set(vr)
panic(ErrDependency)
}
var ok bool
if v, ok = res.Value().(T); !ok {
return defaultV, UnknownSource, vr.Version, fmt.Errorf("unexpected type: got: %T, expected %v", res.Value(), reflect.TypeFor[T]())
}
if path == CodePath {
sdres := s.versionMap.Read(addr, SelfDestructPath, accounts.NilKey, s.txIndex)
if sdres.Status() == MVReadResultDone && sdres.Value().(bool) && sdres.DepIdx() >= res.DepIdx() {
return defaultV, MapRead, Version{TxIndex: res.DepIdx(), Incarnation: res.Incarnation()}, nil
}
}
if dbg.TraceTransactionIO && (s.trace || dbg.TraceAccount(addr.Handle())) {
fmt.Printf("%d (%d.%d) RD (%s:%s) %x %s: %s\n", s.blockNum, s.txIndex, s.version, MapRead, res.DepString(), addr, AccountKey{path, key}, valueString(path, v))
}
if copyV == nil {
return v, MapRead, vr.Version, nil
}
vr.Val = copyV(v)
case MVReadResultDependency:
if dbg.TraceTransactionIO && (s.trace || dbg.TraceAccount(addr.Handle())) {
fmt.Printf("%d (%d.%d) MP DEP (%d.%d) %x %s\n", s.blockNum, s.txIndex, s.version, res.DepIdx(), res.Incarnation(), addr, AccountKey{path, key})
}
if res.DepIdx() > s.dep {
s.dep = res.DepIdx()
}
vr.Source = MapRead
if s.versionedReads == nil {
s.versionedReads = ReadSet{}
}
s.versionedReads.Set(vr)
panic(ErrDependency)
case MVReadResultNone:
if versionedReads := s.versionedReads; !commited && versionedReads != nil {
if pr, ok := versionedReads[addr][AccountKey{Path: path, Key: key}]; ok {
if pr.Version == vr.Version {
if dbg.TraceTransactionIO && (s.trace || dbg.TraceAccount(addr.Handle())) {
fmt.Printf("%d (%d.%d) RD (%s) %x %s: %s\n", s.blockNum, s.txIndex, s.version, ReadSetRead, addr, AccountKey{path, key}, valueString(path, pr.Val))
}
return pr.Val.(T), ReadSetRead, pr.Version, nil
}
if pr.Source == MapRead {
if path == BalancePath || path == NoncePath || path == IncarnationPath || path == CodeHashPath {
if _, source, version, _ := versionedRead(s, addr, AddressPath, accounts.NilKey, false, nil,
func(v *accounts.Account) *accounts.Account { return v }, nil); source == pr.Source && version == pr.Version {
return pr.Val.(T), ReadSetRead, pr.Version, nil
}
}
// a previous dependency has been removed from the map
if dbg.TraceTransactionIO && (s.trace || dbg.TraceAccount(addr.Handle())) {
fmt.Printf("%d (%d.%d) RM DEP (%d.%d)!=(%d.%d) %x %s\n", s.blockNum, s.txIndex, s.version, pr.Version.TxIndex, pr.Version.Incarnation, vr.Version.TxIndex, vr.Version.Incarnation, addr, AccountKey{path, key})
}
if pr.Version.TxIndex > s.dep {
s.dep = pr.Version.TxIndex
}
panic(ErrDependency)
}
}
}
if readStorage == nil {
// Record reads so that ValidateVersion can detect when a prior
// transaction modifies any account property. Without tracking
// these reads, validation misses conflicts where a prior tx
// changes an account's balance/nonce/etc. — causing later txs
// to execute against stale data.
//
// Do NOT cache CodePath: getStateObject calls versionedRead for
// CodePath with readStorage=nil to check if a prior tx wrote
// code (EIP-7702). Caching defaultV (nil) would poison the
// ReadSet, causing subsequent getCode calls (which pass a real
// readStorage callback) to return empty code instead of loading
// it from the DB — breaking deposit contract execution, etc.
if !commited && path != CodePath {
vr.Source = StorageRead
vr.Val = defaultV
if s.versionedReads == nil {
s.versionedReads = ReadSet{}
}
s.versionedReads.Set(vr)
}
return defaultV, UnknownSource, UnknownVersion, nil
}
var so *stateObject
var err error
// For StoragePath, detect contract creation/destruction by a prior tx.
// IncarnationPath is written ONLY by CreateAccount (contract creation) and
// Selfdestruct — both operations that clear all storage. When no prior tx
// wrote this specific storage slot (MVReadResultNone), but a prior tx DID
// write IncarnationPath, the account was created or destroyed in this block
// and all unwritten storage slots must be zero.
//
// Without this check, the read falls through to StorageDomain which may
// contain stale data from before a prior block's SELFDESTRUCT (because
// Writer.DeleteAccount clears AccountsDomain but NOT StorageDomain).
if path == StoragePath {
incRes := s.versionMap.Read(addr, IncarnationPath, accounts.NilKey, s.txIndex)
if incRes.Status() == MVReadResultDone {
var zero T
vr.Source = StorageRead
vr.Val = zero
if dbg.TraceTransactionIO && (s.trace || dbg.TraceAccount(addr.Handle())) {
fmt.Printf("%d (%d.%d) RD (%s) %x %s: zero (IncarnationPath written by tx %d)\n",
s.blockNum, s.txIndex, s.version, StorageRead, addr, AccountKey{path, key}, incRes.DepIdx())
}
if s.versionedReads == nil {
s.versionedReads = ReadSet{}
}
s.versionedReads.Set(vr)
// Record dependency on IncarnationPath so that ValidateVersion
// detects if the creation/destruction is reverted by a re-execution.
incVersion := Version{TxIndex: incRes.DepIdx(), Incarnation: incRes.Incarnation()}
s.versionedReads.Set(VersionedRead{
Address: addr,
Path: IncarnationPath,
Key: accounts.NilKey,
Source: MapRead,
Version: incVersion,
Val: incRes.Value(),
})
return zero, StorageRead, UnknownVersion, nil
}
}
if path == BalancePath || path == NoncePath || path == IncarnationPath || path == CodeHashPath {
readAccount, source, version, err := versionedRead(s, addr, AddressPath, accounts.NilKey, false, nil,
func(v *accounts.Account) *accounts.Account { return v }, nil)
if err != nil {
return defaultV, source, UnknownVersion, err
}
if readAccount != nil {
vr.Source = source
vr.Version = version
so = newObject(s, addr, readAccount, readAccount)
}
}
if so == nil {
vr.Source = StorageRead
so, err = s.getStateObject(addr, true)
if err != nil {
return defaultV, StorageRead, UnknownVersion, err
}
}
if v, err = readStorage(so); err != nil {
return defaultV, StorageRead, UnknownVersion, err
}
if dbg.TraceTransactionIO && (s.trace || dbg.TraceAccount(addr.Handle())) {
fmt.Printf("%d (%d.%d) RD (%s:%d.%d) %x %s: %s\n", s.blockNum, s.txIndex, s.version, vr.Source, vr.Version.TxIndex, vr.Version.Incarnation, addr, AccountKey{path, key}, valueString(path, v))
}
vr.Val = copyV(v)
default:
return defaultV, UnknownSource, UnknownVersion, nil
}
if s.versionedReads == nil {
s.versionedReads = ReadSet{}
}
s.versionedReads.Set(vr)
return v, vr.Source, vr.Version, nil
}
// note that TxIndex starts at -1 (the begin system tx)
type VersionedIO struct {
inputs []versionedReadSet
outputs []VersionedWrites // write sets that should be checked during validation
accessed []AccessSet
}
func NewVersionedIO(numTx int) *VersionedIO {
return &VersionedIO{
inputs: make([]versionedReadSet, numTx+1),
outputs: make([]VersionedWrites, numTx+1),
accessed: make([]AccessSet, numTx+1),
}
}
func (io *VersionedIO) Len() int {
if io == nil {
return 0
}
return max(len(io.inputs), max(len(io.outputs), len(io.accessed)))
}
func (io *VersionedIO) Inputs() []versionedReadSet {
return io.inputs
}
func (io *VersionedIO) Outputs() []VersionedWrites {
return io.outputs
}
func (io *VersionedIO) ReadSet(txnIdx int) ReadSet {
if len(io.inputs) <= txnIdx+1 {
return nil
}
return io.inputs[txnIdx+1].readSet
}
func (io *VersionedIO) ReadSetIncarnation(txnIdx int) int {
if len(io.inputs) <= txnIdx+1 {
return -1
}
if io.inputs[txnIdx+1].readSet != nil {
return io.inputs[txnIdx+1].incarnation
}
return 0
}
func (io *VersionedIO) WriteSet(txnIdx int) VersionedWrites {
if len(io.outputs) <= txnIdx+1 {