forked from 10d9e/zevm
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathjournal.zig
More file actions
1447 lines (1273 loc) · 65 KB
/
journal.zig
File metadata and controls
1447 lines (1273 loc) · 65 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
const std = @import("std");
const primitives = @import("primitives");
const state = @import("state");
const bytecode = @import("bytecode");
const database = @import("database");
const alloc_mod = @import("zevm_allocator");
/// Journal entry factory functions
pub const JournalEntryFactory = struct {
pub fn accountTouched(address: primitives.Address) JournalEntry {
return JournalEntry{ .AccountTouched = address };
}
pub fn accountCreated(address: primitives.Address, is_created_globally: bool) JournalEntry {
return JournalEntry{ .AccountCreated = .{ .address = address, .is_created_globally = is_created_globally } };
}
pub fn accountDestroyed(address: primitives.Address, target: primitives.Address, destroyed_status: SelfdestructionRevertStatus, balance: primitives.U256) JournalEntry {
return JournalEntry{ .AccountDestroyed = .{ .address = address, .target = target, .destroyed_status = destroyed_status, .balance = balance } };
}
pub fn balanceChanged(address: primitives.Address, old_balance: primitives.U256) JournalEntry {
return JournalEntry{ .BalanceChanged = .{ .address = address, .old_balance = old_balance } };
}
pub fn balanceTransfer(from: primitives.Address, to: primitives.Address, balance: primitives.U256) JournalEntry {
return JournalEntry{ .BalanceTransfer = .{ .from = from, .to = to, .balance = balance } };
}
pub fn nonceChanged(address: primitives.Address) JournalEntry {
return JournalEntry{ .NonceChanged = address };
}
pub fn codeChanged(address: primitives.Address) JournalEntry {
return JournalEntry{ .CodeChanged = address };
}
pub fn storageChanged(address: primitives.Address, key: primitives.StorageKey, old_value: primitives.StorageValue, old_was_written: bool) JournalEntry {
return JournalEntry{ .StorageChanged = .{ .address = address, .key = key, .old_value = old_value, .old_was_written = old_was_written } };
}
pub fn storageWarmed(address: primitives.Address, key: primitives.StorageKey) JournalEntry {
return JournalEntry{ .StorageWarmed = .{ .address = address, .key = key } };
}
pub fn accountWarmed(address: primitives.Address) JournalEntry {
return JournalEntry{ .AccountWarmed = address };
}
pub fn transientStorageChanged(address: primitives.Address, key: primitives.StorageKey, old_value: primitives.StorageValue) JournalEntry {
return JournalEntry{ .TransientStorageChanged = .{ .address = address, .key = key, .old_value = old_value } };
}
};
/// Selfdestruction revert status
pub const SelfdestructionRevertStatus = enum {
GloballySelfdestroyed,
LocallySelfdestroyed,
RepeatedSelfdestruction,
};
/// Journal entry
pub const JournalEntry = union(enum) {
AccountTouched: primitives.Address,
AccountCreated: struct { address: primitives.Address, is_created_globally: bool },
AccountDestroyed: struct { address: primitives.Address, target: primitives.Address, destroyed_status: SelfdestructionRevertStatus, balance: primitives.U256 },
BalanceChanged: struct { address: primitives.Address, old_balance: primitives.U256 },
BalanceTransfer: struct { from: primitives.Address, to: primitives.Address, balance: primitives.U256 },
NonceChanged: primitives.Address,
CodeChanged: primitives.Address,
StorageChanged: struct { address: primitives.Address, key: primitives.StorageKey, old_value: primitives.StorageValue, old_was_written: bool },
StorageWarmed: struct { address: primitives.Address, key: primitives.StorageKey },
AccountWarmed: primitives.Address,
TransientStorageChanged: struct { address: primitives.Address, key: primitives.StorageKey, old_value: primitives.StorageValue },
pub fn revert(self: JournalEntry, evm_state: *state.EvmState, transient_storage: ?*state.TransientStorage, is_spurious_dragon_enabled: bool) void {
switch (self) {
.AccountTouched => |address| {
if (evm_state.getPtr(address)) |account| {
account.unmarkTouch();
}
},
.AccountCreated => |data| {
if (evm_state.getPtr(data.address)) |account| {
account.unmarkCreatedLocally();
if (data.is_created_globally) {
account.unmarkCreated();
}
if (is_spurious_dragon_enabled) {
account.info.nonce = 0;
}
}
},
.AccountDestroyed => |data| {
if (evm_state.getPtr(data.address)) |account| {
switch (data.destroyed_status) {
.GloballySelfdestroyed => {
account.unmarkSelfdestructedLocally();
account.unmarkSelfdestruct();
},
.LocallySelfdestroyed => {
account.unmarkSelfdestructedLocally();
},
.RepeatedSelfdestruction => {
// Do nothing
},
}
account.info.balance = data.balance;
}
// Restore the target account's balance: the selfdestruct transferred
// data.balance wei from source to target; undo that transfer on revert.
if (!std.mem.eql(u8, &data.address, &data.target)) {
if (evm_state.getPtr(data.target)) |target_account| {
target_account.info.balance -= data.balance;
}
}
},
.BalanceChanged => |data| {
if (evm_state.getPtr(data.address)) |account| {
account.info.balance = data.old_balance;
}
},
.BalanceTransfer => |data| {
if (evm_state.getPtr(data.from)) |from_account| {
from_account.info.balance += data.balance;
}
if (evm_state.getPtr(data.to)) |to_account| {
to_account.info.balance -= data.balance;
}
},
.NonceChanged => |address| {
if (evm_state.getPtr(address)) |account| {
account.info.nonce -= 1;
}
},
.CodeChanged => |address| {
if (evm_state.getPtr(address)) |account| {
account.info.code = null;
account.info.code_hash = primitives.KECCAK_EMPTY;
}
},
.StorageChanged => |data| {
if (evm_state.getPtr(data.address)) |account| {
if (account.storage.getPtr(data.key)) |slot| {
slot.present_value = data.old_value;
slot.was_written = data.old_was_written;
}
}
},
.StorageWarmed => |data| {
if (evm_state.getPtr(data.address)) |account| {
if (account.storage.getPtr(data.key)) |slot| {
slot.markCold();
}
}
},
.AccountWarmed => |address| {
if (evm_state.getPtr(address)) |account| {
account.markCold();
}
},
.TransientStorageChanged => |data| {
if (transient_storage) |ts| {
if (data.old_value == 0) {
_ = ts.remove(.{ data.address, data.key });
} else {
ts.put(.{ data.address, data.key }, data.old_value) catch {};
}
}
},
}
}
};
/// Warm addresses
pub const WarmAddresses = struct {
coinbase: ?primitives.Address,
precompiles: std.ArrayList(primitives.Address),
access_list: std.AutoHashMap(primitives.Address, std.ArrayList(primitives.StorageKey)),
pub fn new() WarmAddresses {
return .{
.coinbase = null,
.precompiles = std.ArrayList(primitives.Address){},
.access_list = std.AutoHashMap(primitives.Address, std.ArrayList(primitives.StorageKey)).init(alloc_mod.get()),
};
}
pub fn deinit(self: *WarmAddresses) void {
self.precompiles.deinit(alloc_mod.get());
var iterator = self.access_list.iterator();
while (iterator.next()) |entry| {
entry.value_ptr.deinit(alloc_mod.get());
}
self.access_list.deinit();
}
pub fn setCoinbase(self: *WarmAddresses, address: primitives.Address) void {
self.coinbase = address;
}
pub fn setPrecompileAddresses(self: *WarmAddresses, addresses: []const primitives.Address) !void {
self.precompiles.clearRetainingCapacity();
try self.precompiles.appendSlice(alloc_mod.get(), addresses);
}
pub fn setAccessList(self: *WarmAddresses, access_list: std.AutoHashMap(primitives.Address, std.ArrayList(primitives.StorageKey))) !void {
// Clear existing access list
var iterator = self.access_list.iterator();
while (iterator.next()) |entry| {
entry.value_ptr.deinit(alloc_mod.get());
}
self.access_list.clearRetainingCapacity();
// Copy new access list
var new_iterator = access_list.iterator();
while (new_iterator.next()) |entry| {
var storage_keys = std.ArrayList(primitives.StorageKey){};
try storage_keys.appendSlice(alloc_mod.get(), entry.value_ptr.items);
try self.access_list.put(entry.key_ptr.*, storage_keys);
}
}
pub fn clearCoinbaseAndAccessList(self: *WarmAddresses) void {
self.coinbase = null;
var iterator = self.access_list.iterator();
while (iterator.next()) |entry| {
entry.value_ptr.deinit(alloc_mod.get());
}
self.access_list.clearRetainingCapacity();
}
pub fn isCold(self: WarmAddresses, address: primitives.Address) bool {
// Check if address is coinbase
if (self.coinbase) |coinbase| {
if (std.mem.eql(u8, &address, &coinbase)) {
return false;
}
}
// Check if address is precompile
for (self.precompiles.items) |precompile| {
if (std.mem.eql(u8, &address, &precompile)) {
return false;
}
}
// Check if address is in access list
if (self.access_list.contains(address)) {
return false;
}
return true;
}
pub fn isStorageWarm(self: WarmAddresses, address: primitives.Address, key: primitives.StorageKey) bool {
if (self.access_list.get(address)) |storage_keys| {
for (storage_keys.items) |storage_key| {
if (key == storage_key) {
return true;
}
}
}
return false;
}
pub fn getPrecompiles(self: *const WarmAddresses) []const primitives.Address {
return self.precompiles.items;
}
};
/// Journal checkpoint
pub const JournalCheckpoint = struct {
log_i: usize,
journal_i: usize,
/// Index into JournalInner.pending_burns at checkpoint time (for EIP-7708 revert).
burn_i: usize,
};
/// EIP-7708 deferred burn entry.
///
/// Tracks an account in `accounts_to_delete` that may receive ETH after its SELFDESTRUCT opcode
/// executes and before the transaction finalizes (e.g. a payer contract calling into the already-
/// destructed address, or the coinbase receiving its priority fee). These accounts are added to
/// `pending_burns` at SELFDESTRUCT time; `emitBurnLogs()` re-reads their balance after the
/// coinbase payment and emits a Burn log for any non-zero remainder.
///
/// `amount` is unused — it is kept for potential future use (e.g. assertions) but the finalization
/// path always reads the live balance from `evm_state`.
pub const PendingBurn = struct {
address: primitives.Address,
amount: primitives.U256,
};
/// State load result
pub fn StateLoad(comptime T: type) type {
return struct {
data: T,
is_cold: bool,
pub fn new(data: T, is_cold: bool) @This() {
return .{ .data = data, .is_cold = is_cold };
}
pub fn map(self: @This(), comptime U: type, f: fn (T) U) StateLoad(U) {
return StateLoad(U).new(f(self.data), self.is_cold);
}
};
}
/// SStore result
pub const SStoreResult = struct {
original_value: primitives.StorageValue,
present_value: primitives.StorageValue,
new_value: primitives.StorageValue,
};
/// SelfDestruct result
pub const SelfDestructResult = struct {
had_value: bool,
target_exists: bool,
previously_destroyed: bool,
};
/// Transfer error
pub const TransferError = error{
OutOfFunds,
OverflowPayment,
CreateCollision,
};
/// Journal load error
pub const JournalLoadError = error{
ColdLoadSkipped,
DatabaseError,
};
/// Account load result
pub const AccountLoad = struct {
is_delegate_account_cold: ?bool,
is_empty: bool,
};
/// Account info load result
pub const AccountInfoLoad = struct {
info: *state.AccountInfo,
is_cold: bool,
is_empty: bool,
pub fn new(info: *state.AccountInfo, is_cold: bool, is_empty: bool) AccountInfoLoad {
return .{ .info = info, .is_cold = is_cold, .is_empty = is_empty };
}
};
/// Journaled account
pub const JournaledAccount = struct {
address: primitives.Address,
account: *state.Account,
journal: *std.ArrayList(JournalEntry),
pub fn new(address: primitives.Address, account: *state.Account, journal: *std.ArrayList(JournalEntry)) JournaledAccount {
return .{ .address = address, .account = account, .journal = journal };
}
pub fn intoAccountRef(self: JournaledAccount) *state.Account {
return self.account;
}
};
/// Inner journal evm_state that contains journal and evm_state changes.
///
/// Spec Id is a essential information for the Journal.
pub const JournalInner = struct {
/// The current evm_state
evm_state: state.EvmState,
/// Transient storage that is discarded after every transaction.
///
/// See EIP-1153.
transient_storage: state.TransientStorage,
/// Emitted logs
logs: std.ArrayList(primitives.Log),
/// The journal of evm_state changes, one for each transaction
journal: std.ArrayList(JournalEntry),
/// Global transaction id that represent number of transactions executed (Including reverted ones).
/// It can be different from number of `journal_history` as some transaction could be
/// reverted or had a error on execution.
///
/// This ID is used in `Self::evm_state` to determine if account/storage is touched/warm/cold.
transaction_id: usize,
/// The spec ID for the EVM. Spec is required for some journal entries and needs to be set for
/// JournalInner to be functional.
///
/// If spec is set it assumed that precompile addresses are set as well for this particular spec.
///
/// This spec is used for two things:
///
/// - EIP-161: Prior to this EIP, Ethereum had separate definitions for empty and non-existing accounts.
/// - EIP-6780: `SELFDESTRUCT` only in same transaction
spec: primitives.SpecId,
/// Warm addresses containing both coinbase and current precompiles.
warm_addresses: WarmAddresses,
/// EIP-7708: pending burn entries for same-tx-created accounts that selfdestructed to self.
/// Emitted as Burn logs at postExecution, sorted by address. Checkpointed via burn_i.
pending_burns: std.ArrayList(PendingBurn),
pub fn new() JournalInner {
return .{
.evm_state = state.EvmState.init(alloc_mod.get()),
.transient_storage = state.TransientStorage.init(alloc_mod.get()),
.logs = std.ArrayList(primitives.Log){},
.journal = std.ArrayList(JournalEntry){},
.transaction_id = 0,
.spec = primitives.SpecId.prague,
.warm_addresses = WarmAddresses.new(),
.pending_burns = std.ArrayList(PendingBurn){},
};
}
pub fn deinit(self: *JournalInner) void {
self.evm_state.deinit();
self.transient_storage.deinit();
for (self.logs.items) |log| log.deinit(alloc_mod.get());
self.logs.deinit(alloc_mod.get());
self.journal.deinit(alloc_mod.get());
self.warm_addresses.deinit();
self.pending_burns.deinit(alloc_mod.get());
}
/// Returns the logs
pub fn takeLogs(self: *JournalInner) std.ArrayList(primitives.Log) {
const logs = self.logs;
self.logs = std.ArrayList(primitives.Log){};
return logs;
}
/// Prepare for next transaction, by committing the current journal to history, incrementing the transaction id
/// and returning the logs.
///
/// This function is used to prepare for next transaction. It will save the current journal
/// and clear the journal for the next transaction.
///
/// `commit_tx` is used even for discarding transactions so transaction_id will be incremented.
pub fn commitTx(self: *JournalInner) void {
// Per EIP-2200/EIP-3529: after committing a transaction, the "original value"
// of each storage slot becomes the committed (present) value. Without this,
// subsequent transactions in the same block would incorrectly treat slots as
// "dirty" (original ≠ current) rather than "clean" (original == current),
// causing SSTORE to charge 100 gas (dirty-warm) instead of 2900 (clean-nonzero).
var state_it = self.evm_state.iterator();
while (state_it.next()) |entry| {
var slot_it = entry.value_ptr.storage.valueIterator();
while (slot_it.next()) |slot| {
if (slot.original_value != slot.present_value) {
slot.original_value = slot.present_value;
}
}
}
self.transient_storage.clearRetainingCapacity();
self.journal.clearRetainingCapacity();
self.warm_addresses.clearCoinbaseAndAccessList();
self.transaction_id += 1;
// Free heap-allocated data/topics (in case takeLogs() was not called — e.g. failed tx)
for (self.logs.items) |log| log.deinit(alloc_mod.get());
self.logs.clearRetainingCapacity();
self.pending_burns.clearRetainingCapacity();
}
/// Discard the current transaction, by reverting the journal entries and incrementing the transaction id.
pub fn discardTx(self: *JournalInner) void {
const is_spurious_dragon_enabled = primitives.isEnabledIn(self.spec, .spurious_dragon);
// iterate over all journals entries and revert our global evm_state
var i = self.journal.items.len;
while (i > 0) {
i -= 1;
const entry = self.journal.swapRemove(i);
entry.revert(&self.evm_state, &self.transient_storage, is_spurious_dragon_enabled);
}
self.transient_storage.clearRetainingCapacity();
// Free heap-allocated data/topics before clearing the log list
for (self.logs.items) |log| log.deinit(alloc_mod.get());
self.logs.clearRetainingCapacity();
self.pending_burns.clearRetainingCapacity();
self.transaction_id += 1;
self.warm_addresses.clearCoinbaseAndAccessList();
}
/// Take the [`EvmState`] and clears the journal by resetting it to initial state.
///
/// Note: Precompile addresses and spec are preserved and initial evm_state of
/// warm_preloaded_addresses will contain precompiles addresses.
pub fn finalize(self: *JournalInner) state.EvmState {
self.warm_addresses.clearCoinbaseAndAccessList();
const evm_state = self.evm_state;
self.evm_state = state.EvmState.init(alloc_mod.get());
for (self.logs.items) |log| log.deinit(alloc_mod.get());
self.logs.clearRetainingCapacity();
self.pending_burns.clearRetainingCapacity();
self.transient_storage.clearRetainingCapacity();
self.journal.clearRetainingCapacity();
self.transaction_id = 0;
return evm_state;
}
/// Return reference to state.
pub fn getState(self: *JournalInner) *state.EvmState {
return &self.evm_state;
}
/// Sets SpecId.
pub fn setSpecId(self: *JournalInner, spec: primitives.SpecId) void {
self.spec = spec;
}
/// Mark account as touched as only touched accounts will be added to state.
/// This is especially important for evm_state clear where touched empty accounts needs to
/// be removed from state.
pub fn touch(self: *JournalInner, address: primitives.Address) void {
if (self.evm_state.getPtr(address)) |account| {
JournalInner.touchAccount(&self.journal, address, account);
}
}
/// Mark account as touched.
fn touchAccount(journal: *std.ArrayList(JournalEntry), address: primitives.Address, account: *state.Account) void {
if (!account.isTouched()) {
journal.append(alloc_mod.get(), JournalEntryFactory.accountTouched(address)) catch {};
account.markTouch();
}
}
/// Returns the _loaded_ [Account] for the given address.
///
/// This assumes that the account has already been loaded.
///
/// # Panics
///
/// Panics if the account has not been loaded and is missing from the evm_state set.
pub fn getAccount(self: JournalInner, address: primitives.Address) *const state.Account {
return self.evm_state.get(address) orelse unreachable;
}
/// Set code and its hash to the account.
///
/// Note: Assume account is warm and that hash is calculated from code.
pub fn setCodeWithHash(self: *JournalInner, address: primitives.Address, code: bytecode.Bytecode, hash: primitives.Hash) void {
const account = self.evm_state.getPtr(address).?;
JournalInner.touchAccount(&self.journal, address, account);
self.journal.append(alloc_mod.get(), JournalEntryFactory.codeChanged(address)) catch {};
account.info.code_hash = hash;
account.info.code = code;
}
/// Use it only if you know that acc is warm.
///
/// Assume account is warm.
///
/// In case of EIP-7702 code with zero address, the bytecode will be erased.
pub fn setCode(self: *JournalInner, address: primitives.Address, code: bytecode.Bytecode) void {
if (code == .eip7702) {
if (std.mem.eql(u8, &code.eip7702.address, &[_]u8{0} ** 20)) {
self.setCodeWithHash(address, bytecode.Bytecode.new(), primitives.KECCAK_EMPTY);
return;
}
}
const hash = code.hashSlow();
self.setCodeWithHash(address, code, hash);
}
/// Add journal entry for caller accounting.
pub fn callerAccountingJournalEntry(self: *JournalInner, address: primitives.Address, old_balance: primitives.U256, bump_nonce: bool) void {
// account balance changed.
self.journal.append(alloc_mod.get(), JournalEntryFactory.balanceChanged(address, old_balance)) catch {};
// account is touched.
self.journal.append(alloc_mod.get(), JournalEntryFactory.accountTouched(address)) catch {};
if (bump_nonce) {
// nonce changed.
self.journal.append(alloc_mod.get(), JournalEntryFactory.nonceChanged(address)) catch {};
}
}
/// Increments the balance of the account.
///
/// Mark account as touched.
pub fn balanceIncr(self: *JournalInner, db: anytype, address: primitives.Address, balance: primitives.U256) !void {
const account = try self.loadAccountMut(db, address);
account.data.account.incrBalance(balance);
}
/// Increments the nonce of the account.
pub fn nonceBumpJournalEntry(self: *JournalInner, address: primitives.Address) void {
self.journal.append(alloc_mod.get(), JournalEntryFactory.nonceChanged(address)) catch {};
}
/// Transfers balance from two accounts. Returns error if sender balance is not enough.
///
/// # Panics
///
/// Panics if from or to are not loaded.
pub fn transferLoaded(self: *JournalInner, from: primitives.Address, to: primitives.Address, balance: primitives.U256) ?TransferError {
if (std.mem.eql(u8, &from, &to)) {
const from_balance = self.evm_state.getPtr(to).?.info.balance;
// Check if from balance is enough to transfer the balance.
if (balance > from_balance) {
return TransferError.OutOfFunds;
}
return null;
}
if (balance == 0) {
JournalInner.touchAccount(&self.journal, to, self.evm_state.getPtr(to).?);
return null;
}
// sub balance from
const from_account = self.evm_state.getPtr(from).?;
JournalInner.touchAccount(&self.journal, from, from_account);
const from_balance = &from_account.info.balance;
const from_balance_decr = std.math.sub(u256, from_balance.*, balance) catch return TransferError.OutOfFunds;
from_balance.* = from_balance_decr;
// add balance to
const to_account = self.evm_state.getPtr(to).?;
JournalInner.touchAccount(&self.journal, to, to_account);
const to_balance = &to_account.info.balance;
const to_balance_incr = std.math.add(u256, to_balance.*, balance) catch return TransferError.OverflowPayment;
to_balance.* = to_balance_incr;
// add journal entry
self.journal.append(alloc_mod.get(), JournalEntryFactory.balanceTransfer(from, to, balance)) catch {};
return null;
}
/// Transfers balance from two accounts. Returns error if sender balance is not enough.
pub fn transfer(self: *JournalInner, db: anytype, from: primitives.Address, to: primitives.Address, balance: primitives.U256) !?TransferError {
_ = try self.loadAccount(db, from);
_ = try self.loadAccount(db, to);
return self.transferLoaded(from, to, balance);
}
/// Creates account or returns false if collision is detected.
///
/// There are few steps done:
/// 1. Make created account warm loaded (AccessList) and this should
/// be done before subroutine checkpoint is created.
/// 2. Check if there is collision of newly created account with existing one.
/// 3. Mark created account as created.
/// 4. Add fund to created account
/// 5. Increment nonce of created account if SpuriousDragon is active
/// 6. Decrease balance of caller account.
///
/// # Panics
///
/// Panics if the caller is not loaded inside the EVM state.
/// This should have been done inside `create_inner`.
pub fn createAccountCheckpoint(self: *JournalInner, caller: primitives.Address, target_address: primitives.Address, balance: primitives.U256, spec_id: primitives.SpecId) !JournalCheckpoint {
// Enter subroutine
const checkpoint = self.getCheckpoint();
// Newly created account is present, as we just loaded it.
const target_acc = self.evm_state.getPtr(target_address).?;
const last_journal = &self.journal;
// EIP-7610: CREATE fails if the target address already has non-empty code or non-zero nonce.
// Pre-existing balance does NOT cause a collision — it is inherited by the new contract.
if (!std.mem.eql(u8, &target_acc.info.code_hash, &primitives.KECCAK_EMPTY) or
target_acc.info.nonce != 0)
{
self.checkpointRevert(checkpoint);
return TransferError.CreateCollision;
}
// set account status to create.
const is_created_globally = target_acc.markCreatedLocally();
// this entry will revert set nonce.
last_journal.append(alloc_mod.get(), JournalEntryFactory.accountCreated(target_address, is_created_globally)) catch {};
target_acc.info.code = null;
// EIP-161: State trie clearing (invariant-preserving alternative)
if (primitives.isEnabledIn(spec_id, .spurious_dragon)) {
// nonce is going to be reset to zero in AccountCreated journal entry.
target_acc.info.nonce = 1;
}
// touch account. This is important as for pre SpuriousDragon account could be
// saved even empty.
JournalInner.touchAccount(last_journal, target_address, target_acc);
// Add balance to created account, as we already have target here.
const new_balance = std.math.add(u256, target_acc.info.balance, balance) catch {
self.checkpointRevert(checkpoint);
return TransferError.OverflowPayment;
};
target_acc.info.balance = new_balance;
// Decrement caller balance — if it underflows the value exceeds the caller's balance.
const new_caller_balance = std.math.sub(u256, self.evm_state.getPtr(caller).?.info.balance, balance) catch {
self.checkpointRevert(checkpoint);
return TransferError.OutOfFunds;
};
self.evm_state.getPtr(caller).?.info.balance = new_caller_balance;
// add journal entry of transferred balance
last_journal.append(alloc_mod.get(), JournalEntryFactory.balanceTransfer(caller, target_address, balance)) catch {};
return checkpoint;
}
/// Makes a checkpoint that in case of Revert can bring back evm_state to this point.
pub fn getCheckpoint(self: *JournalInner) JournalCheckpoint {
return JournalCheckpoint{
.log_i = self.logs.items.len,
.journal_i = self.journal.items.len,
.burn_i = self.pending_burns.items.len,
};
}
/// Commits the checkpoint (no-op: state accumulates until commitTx).
pub fn checkpointCommit(self: *JournalInner) void {
_ = self;
}
/// Reverts all changes to evm_state until given checkpoint.
pub fn checkpointRevert(self: *JournalInner, checkpoint: JournalCheckpoint) void {
const is_spurious_dragon_enabled = primitives.isEnabledIn(self.spec, .spurious_dragon);
// Free heap-allocated data/topics of logs being discarded by this revert.
for (self.logs.items[checkpoint.log_i..]) |log| log.deinit(alloc_mod.get());
self.logs.shrinkRetainingCapacity(checkpoint.log_i);
// Revert EIP-7708 pending burns added since this checkpoint.
self.pending_burns.shrinkRetainingCapacity(checkpoint.burn_i);
// iterate over last N journals sets and revert our global evm_state
if (checkpoint.journal_i < self.journal.items.len) {
var i = self.journal.items.len;
while (i > checkpoint.journal_i) {
i -= 1;
const entry = self.journal.swapRemove(i);
entry.revert(&self.evm_state, &self.transient_storage, is_spurious_dragon_enabled);
}
}
}
/// Performs selfdestruct action.
/// Transfers balance from address to target. Check if target exist/is_cold
///
/// Note: Balance will be lost if address and target are the same BUT when
/// current spec enables Cancun, this happens only when the account associated to address
/// is created in the same tx
///
// ─── EIP-7708 helpers ─────────────────────────────────────────────────────────
/// EIP-7708: Build and append a Transfer(from, to, amount) log to the journal log list.
/// Address is encoded into the upper 12 zero-padded bytes of a 32-byte topic.
/// OOM silently skips the log (same policy as addLog).
fn addEip7708TransferLog(self: *JournalInner, from: primitives.Address, to: primitives.Address, amount: primitives.U256) void {
const alloc = alloc_mod.get();
const topics = alloc.alloc(primitives.Hash, 3) catch return;
topics[0] = primitives.EIP7708_TRANSFER_TOPIC;
topics[1] = std.mem.zeroes([32]u8);
@memcpy(topics[1][12..], &from);
topics[2] = std.mem.zeroes([32]u8);
@memcpy(topics[2][12..], &to);
const data = alloc.alloc(u8, 32) catch {
alloc.free(topics);
return;
};
const amount_bytes: [32]u8 = @bitCast(@byteSwap(amount));
@memcpy(data, &amount_bytes);
self.addLog(.{
.address = primitives.EIP7708_LOG_ADDRESS,
.topics = topics,
.data = data,
});
}
/// EIP-7708: Build and append a Burn(address, amount) log to the journal log list.
fn addEip7708BurnLog(self: *JournalInner, addr: primitives.Address, amount: primitives.U256) void {
const alloc = alloc_mod.get();
const topics = alloc.alloc(primitives.Hash, 2) catch return;
topics[0] = primitives.EIP7708_BURN_TOPIC;
topics[1] = std.mem.zeroes([32]u8);
@memcpy(topics[1][12..], &addr);
const data = alloc.alloc(u8, 32) catch {
alloc.free(topics);
return;
};
const amount_bytes: [32]u8 = @bitCast(@byteSwap(amount));
@memcpy(data, &amount_bytes);
self.addLog(.{
.address = primitives.EIP7708_LOG_ADDRESS,
.topics = topics,
.data = data,
});
}
/// EIP-7708: Register an account for a deferred finalization burn check.
///
/// Called at SELFDESTRUCT time for every account entering `accounts_to_delete` (i.e. same-tx-
/// created accounts under Cancun+, or any account pre-Cancun). `amount` is stored but not
/// used by `emitBurnLogs()`; pass 0. The entry is checkpointed so it can be reverted if the
/// enclosing call frame reverts.
fn addPendingBurn(self: *JournalInner, addr: primitives.Address, amount: primitives.U256) void {
self.pending_burns.append(alloc_mod.get(), .{ .address = addr, .amount = amount }) catch {};
}
/// EIP-7708 finalization: emit deferred Burn logs for accounts that received ETH after their
/// SELFDESTRUCT opcode executed.
///
/// # When this is called
/// `postExecution` in `mainnet_builder.zig` calls this after the coinbase priority-fee payment
/// and before `takeLogs()` collects the tx log list. This matches the EELS ordering in
/// `process_transaction` (amsterdam/fork.py): miner fee is transferred first, then for each
/// address in `accounts_to_delete` the current balance is checked and a Burn log is emitted
/// if non-zero.
///
/// # Why two Burn logs can appear for the same address
/// The SELFDESTRUCT opcode itself emits a Burn log for the balance held *at that moment*
/// (see the `addEip7708BurnLog` call in `selfdestruct()`). The account's `evm_state` balance
/// is then zeroed. Any ETH that arrives afterwards — a payer's CALL sending value, or the
/// coinbase receiving its priority fee — accumulates back in `evm_state`. This second pass
/// emits a *separate* Burn log only for that post-SELFDESTRUCT ETH, producing two distinct
/// log entries exactly as the EELS reference implementation does.
///
/// # Sorting
/// Logs are emitted in ascending address order (lexicographic bytes), matching EELS.
pub fn emitBurnLogs(self: *JournalInner) void {
if (self.pending_burns.items.len == 0) return;
std.mem.sort(PendingBurn, self.pending_burns.items, {}, struct {
fn lessThan(_: void, a: PendingBurn, b: PendingBurn) bool {
return std.mem.order(u8, &a.address, &b.address) == .lt;
}
}.lessThan);
for (self.pending_burns.items) |burn| {
// The account's `evm_state` balance was zeroed when SELFDESTRUCT executed.
// Any non-zero balance here is ETH that arrived *after* the opcode (e.g. a
// subsequent CALL with value from a payer, or the coinbase priority fee).
const finalization_balance = if (self.evm_state.get(burn.address)) |acct|
acct.info.balance
else
0;
if (finalization_balance > 0) self.addEip7708BurnLog(burn.address, finalization_balance);
}
self.pending_burns.clearRetainingCapacity();
}
// ─── Selfdestruct ──────────────────────────────────────────────────────────────
/// # References:
/// * <https://github.com/ethereum/go-ethereum/blob/141cd425310b503c5678e674a8c3872cf46b7086/core/vm/instructions.go#L832-L833>
/// * <https://github.com/ethereum/go-ethereum/blob/141cd425310b503c5678e674a8c3872cf46b7086/core/evm_state/evm_statedb.go#L449>
/// * <https://eips.ethereum.org/EIPS/eip-6780>
pub fn selfdestruct(self: *JournalInner, db: anytype, address: primitives.Address, target: primitives.Address) !StateLoad(SelfDestructResult) {
const spec = self.spec;
const account_load = try self.loadAccount(db, target);
const is_cold = account_load.is_cold;
const is_empty = account_load.data.stateClearAwareIsEmpty(spec);
if (!std.mem.eql(u8, &address, &target)) {
// Both accounts are loaded before this point, `address` as we execute its contract.
// and `target` at the beginning of the function.
const acc_balance = self.evm_state.get(address).?.info.balance;
const target_account = self.evm_state.getPtr(target).?;
JournalInner.touchAccount(&self.journal, target, target_account);
target_account.info.balance = std.math.add(u256, target_account.info.balance, acc_balance) catch unreachable;
}
const acc = self.evm_state.getPtr(address).?;
const balance = acc.info.balance;
const destroyed_status = if (!acc.isSelfdestructed())
SelfdestructionRevertStatus.GloballySelfdestroyed
else if (!acc.isSelfdestructedLocally())
SelfdestructionRevertStatus.LocallySelfdestroyed
else
SelfdestructionRevertStatus.RepeatedSelfdestruction;
const is_cancun_enabled = primitives.isEnabledIn(spec, .cancun);
// EIP-6780 (Cancun hard-fork): selfdestruct only if contract is created in the same tx
const journal_entry: ?JournalEntry = entry_blk: {
if (acc.isCreatedLocally() or !is_cancun_enabled) {
_ = acc.markSelfdestructedLocally();
acc.info.balance = @as(primitives.U256, 0);
break :entry_blk JournalEntryFactory.accountDestroyed(address, target, destroyed_status, balance);
} else if (!std.mem.eql(u8, &address, &target)) {
acc.info.balance = @as(primitives.U256, 0);
break :entry_blk JournalEntryFactory.balanceTransfer(address, target, balance);
} else {
// State is not changed:
// * if we are after Cancun upgrade and
// * Selfdestruct account that is created in the same transaction and
// * Specify the target is same as selfdestructed account. The balance stays unchanged.
break :entry_blk null;
}
};
if (journal_entry) |entry| {
self.journal.append(alloc_mod.get(), entry) catch {};
}
// ── EIP-7708 (Amsterdam+): ETH transfer / burn log emission ─────────────────
//
// EIP-7708 requires a LOG2 event for every wei movement that would otherwise be
// invisible on-chain. There are two distinct moments where logs must be emitted:
//
// 1. **Opcode time** — when SELFDESTRUCT executes:
// • SELFDESTRUCT to a *different* beneficiary: the ETH is moved now, so a
// Transfer log is emitted immediately (LOG3 with from/to/amount).
// • SELFDESTRUCT to *self* (same-tx-created or pre-Cancun): the ETH is
// destroyed now, so a Burn log is emitted immediately (LOG2 with addr/amount).
// The account's `evm_state` balance is then zeroed by `entry_blk` above.
//
// 2. **Finalization time** — after the coinbase priority-fee payment:
// Any account in `accounts_to_delete` (same-tx-created SELFDESTRUCTs) may
// receive ETH *after* the opcode executes but *before* the tx commits — for
// example a payer contract calling into the already-destructed address, or
// the coinbase receiving its miner tip. A second Burn log is emitted for
// this post-opcode ETH via `emitBurnLogs()` in `postExecution`.
//
// Only accounts in `accounts_to_delete` (isCreatedLocally || pre-Cancun) are
// eligible for the finalization burn; pre-existing Cancun+ self-destructed accounts
// are a no-op (no state change, no log).
//
// Reference: ethereum/execution-specs — amsterdam/vm/instructions/system.py
// (selfdestruct) and amsterdam/fork.py (process_transaction finalization).
if (primitives.isEnabledIn(self.spec, .amsterdam)) {
if (!std.mem.eql(u8, &address, &target)) {
// Case 1a: SELFDESTRUCT to a different beneficiary.
// Emit Transfer log immediately for the ETH moved by `entry_blk` above.
if (balance > 0) self.addEip7708TransferLog(address, target, balance);
// If this account is also in `accounts_to_delete`, register it for the
// finalization burn check: a payer may still send ETH to this address
// within the same transaction after the opcode returns.
if (acc.isCreatedLocally() or !is_cancun_enabled) {
self.addPendingBurn(address, 0);
}
} else if (acc.isCreatedLocally() or !is_cancun_enabled) {
// Case 1b: SELFDESTRUCT to self (same-tx-created or pre-Cancun).
// Emit Burn log immediately for the ETH destroyed right now, then register
// for the finalization burn check so that any ETH arriving *after* this
// opcode (payer call, coinbase priority fee) also gets a Burn log.
// The two logs are intentionally separate, matching the EELS reference.
if (balance > 0) self.addEip7708BurnLog(address, balance);
self.addPendingBurn(address, 0);
}
// Case 2: SELFDESTRUCT to self on a pre-existing account (Cancun+).
// EIP-6780 makes this a no-op — state is unchanged, no log is emitted.
}
return StateLoad(SelfDestructResult).new(SelfDestructResult{
.had_value = balance != 0,
.target_exists = !is_empty,
.previously_destroyed = destroyed_status == SelfdestructionRevertStatus.RepeatedSelfdestruction,
}, is_cold);
}
/// Loads account into memory. return if it is cold or warm accessed
pub fn loadAccount(self: *JournalInner, db: anytype, address: primitives.Address) !StateLoad(*const state.Account) {
return self.loadAccountOptional(db, address, false, false);
}
/// Loads account and its code. If account is already loaded it will load its code.
///
/// It will mark account as warm loaded. If not existing Database will be queried for data.
///
/// In case of EIP-7702 delegated account will not be loaded,
/// [`Self::load_account_delegated`] should be used instead.
pub fn loadCode(self: *JournalInner, db: anytype, address: primitives.Address) !StateLoad(*const state.Account) {
return self.loadAccountOptional(db, address, true, false);
}
/// Loads account into memory. If account is already loaded it will be marked as warm.
/// Check whether an address is cold WITHOUT loading it from the database.
/// Used by opcode handlers to pre-check gas costs before committing to a DB load.
pub fn isAddressCold(self: *const JournalInner, address: primitives.Address) bool {
if (self.evm_state.get(address)) |acct| {
if (acct.isColdTransactionId(self.transaction_id)) {
// EIP-3651: coinbase is pre-warmed each tx. If the coinbase was loaded in
// a previous tx (old transaction_id), still treat it as warm for gas purposes.
// Only check the coinbase slot — not precompiles or access-list entries, to
// avoid unintended cross-tx warm promotion for those.
if (self.warm_addresses.coinbase) |cb| {
if (std.mem.eql(u8, &address, &cb)) return false;
}
return true;
}
return false;
}
return self.warm_addresses.isCold(address);
}