-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathevm_c_api.zig
More file actions
1854 lines (1631 loc) · 68.2 KB
/
evm_c_api.zig
File metadata and controls
1854 lines (1631 loc) · 68.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
//! C ABI wrapper for Guillotine EVM
//! Provides FFI-compatible exports for Bun and other language bindings
const std = @import("std");
const evm = @import("evm");
// Global log configuration - suppress debug logs
pub const std_options: std.Options = .{
.log_level = .warn,
};
const primitives = @import("primitives");
const bytecode_c = @import("bytecode/bytecode_c.zig");
const log = std.log.scoped(.c_api);
// Import pre-configured EVM types for FFI
const MainnetEvm = evm.MainnetEvm;
const MainnetEvmWithTracer = evm.MainnetEvmWithTracer;
const TestEvm = evm.TestEvm;
// Legacy aliases for backward compatibility
const DefaultEvm = MainnetEvm;
const TracerEvm = MainnetEvmWithTracer;
const Database = evm.Database;
const BlockInfo = evm.BlockInfo;
const TransactionContext = evm.TransactionContext;
const Hardfork = evm.Hardfork;
const Account = evm.Account;
// ============================================================================
// EVM C API
// ============================================================================
// Opaque handle for EVM instance
pub const EvmHandle = opaque {};
// Log entry for FFI
pub const LogEntry = extern struct {
address: [20]u8,
topics: [*]const [32]u8, // Array of 32-byte topics
topics_len: usize,
data: [*]const u8,
data_len: usize,
};
// Self-destruct record for FFI
pub const SelfDestructRecord = extern struct {
contract: [20]u8,
beneficiary: [20]u8,
};
// Storage access record for FFI
pub const StorageAccessRecord = extern struct {
address: [20]u8,
slot: [32]u8, // u256 as bytes
};
// Result structure for FFI
pub const EvmResult = extern struct {
success: bool,
gas_left: u64,
output: [*]const u8,
output_len: usize,
error_message: [*:0]const u8,
// Additional fields from CallResult
logs: [*]const LogEntry,
logs_len: usize,
selfdestructs: [*]const SelfDestructRecord,
selfdestructs_len: usize,
accessed_addresses: [*]const [20]u8, // Array of addresses
accessed_addresses_len: usize,
accessed_storage: [*]const StorageAccessRecord,
accessed_storage_len: usize,
created_address: [20]u8, // For CREATE/CREATE2, zero if not applicable
has_created_address: bool,
// JSON-RPC trace (if available)
trace_json: [*]const u8,
trace_json_len: usize,
};
// Call parameters for FFI
pub const CallParams = extern struct {
caller: [20]u8,
to: [20]u8,
value: [32]u8, // u256 as bytes
input: [*]const u8,
input_len: usize,
gas: u64,
call_type: u8, // 0=CALL, 1=CALLCODE, 2=DELEGATECALL, 3=STATICCALL, 4=CREATE, 5=CREATE2
salt: [32]u8, // For CREATE2
};
// Block info for FFI
pub const BlockInfoFFI = extern struct {
number: u64,
timestamp: u64,
gas_limit: u64,
coinbase: [20]u8,
base_fee: u64,
chain_id: u64,
difficulty: u64,
prev_randao: [32]u8,
};
// Thread-local allocator for FFI
threadlocal var ffi_allocator: ?std.mem.Allocator = null;
threadlocal var last_error: [256]u8 = undefined;
threadlocal var last_error_z: [257]u8 = undefined;
const empty_error: [1]u8 = .{0};
const empty_buffer: [0]u8 = .{};
// EVM configuration enum for runtime selection
pub const EvmConfiguration = enum(u8) {
mainnet = 0,
mainnet_with_tracer = 1,
test_mode = 2,
};
// Instance pooling for performance
const EvmInstance = struct {
evm: *MainnetEvm,
database: *Database,
block_info: BlockInfoFFI,
in_use: bool,
needs_reset: bool,
// Track addresses that have been set up for state dumping
setup_addresses: std.ArrayList(primitives.Address),
};
const TracingEvmInstance = struct {
evm: *MainnetEvmWithTracer,
database: *Database,
block_info: BlockInfoFFI,
in_use: bool,
needs_reset: bool,
};
const TestEvmInstance = struct {
evm: *TestEvm,
database: *Database,
block_info: BlockInfoFFI,
in_use: bool,
needs_reset: bool,
};
// Instance pools - maintain reusable EVM instances
var instance_pool: ?std.ArrayList(*EvmInstance) = null;
var tracing_instance_pool: ?std.ArrayList(*TracingEvmInstance) = null;
var test_instance_pool: ?std.ArrayList(*TestEvmInstance) = null;
var pool_mutex = std.Thread.Mutex{};
// Map handles to instances
var handle_map: ?std.AutoHashMap(*EvmHandle, *EvmInstance) = null;
var tracing_handle_map: ?std.AutoHashMap(*EvmHandle, *TracingEvmInstance) = null;
var test_handle_map: ?std.AutoHashMap(*EvmHandle, *TestEvmInstance) = null;
fn setError(comptime fmt: []const u8, args: anytype) void {
const slice = std.fmt.bufPrint(&last_error, fmt, args) catch "Unknown error";
@memcpy(last_error_z[0..slice.len], slice);
last_error_z[slice.len] = 0;
}
// Initialize FFI allocator and instance pools
export fn guillotine_init() void {
pool_mutex.lock();
defer pool_mutex.unlock();
if (ffi_allocator == null) {
// TODO: Use GPA not c allocator
ffi_allocator = std.heap.c_allocator;
}
const allocator = ffi_allocator.?;
if (instance_pool == null) {
instance_pool = std.ArrayList(*EvmInstance).initCapacity(allocator, 4) catch return;
tracing_instance_pool = std.ArrayList(*TracingEvmInstance).initCapacity(allocator, 4) catch return;
test_instance_pool = std.ArrayList(*TestEvmInstance).initCapacity(allocator, 4) catch return;
handle_map = std.AutoHashMap(*EvmHandle, *EvmInstance).init(allocator);
tracing_handle_map = std.AutoHashMap(*EvmHandle, *TracingEvmInstance).init(allocator);
test_handle_map = std.AutoHashMap(*EvmHandle, *TestEvmInstance).init(allocator);
}
}
// Cleanup FFI allocator and instance pools
export fn guillotine_cleanup() void {
pool_mutex.lock();
defer pool_mutex.unlock();
if (ffi_allocator) |allocator| {
// Clean up instance pools
if (instance_pool) |*pool| {
for (pool.items) |instance| {
instance.evm.deinit();
instance.database.deinit();
allocator.destroy(instance.database);
allocator.destroy(instance.evm);
allocator.destroy(instance);
}
pool.deinit(allocator);
instance_pool = null;
}
if (tracing_instance_pool) |*pool| {
for (pool.items) |instance| {
instance.evm.deinit();
instance.database.deinit();
allocator.destroy(instance.database);
allocator.destroy(instance.evm);
allocator.destroy(instance);
}
pool.deinit(allocator);
tracing_instance_pool = null;
}
if (handle_map) |*map| {
map.deinit();
handle_map = null;
}
if (tracing_handle_map) |*map| {
map.deinit();
tracing_handle_map = null;
}
if (test_instance_pool) |*pool| {
for (pool.items) |instance| {
instance.evm.deinit();
instance.database.deinit();
allocator.destroy(instance.database);
allocator.destroy(instance.evm);
allocator.destroy(instance);
}
pool.deinit(allocator);
test_instance_pool = null;
}
if (test_handle_map) |*map| {
map.deinit();
test_handle_map = null;
}
}
ffi_allocator = null;
}
// Create a new EVM instance with specific configuration
export fn guillotine_evm_create_with_config(block_info_ptr: *const BlockInfoFFI, config: EvmConfiguration) ?*EvmHandle {
return switch (config) {
.mainnet => guillotine_evm_create_mainnet(block_info_ptr),
.mainnet_with_tracer => guillotine_evm_create_tracing(block_info_ptr),
.test_mode => guillotine_evm_create_test(block_info_ptr),
};
}
// Create a new mainnet EVM instance (or reuse from pool) - default for backward compatibility
export fn guillotine_evm_create(block_info_ptr: *const BlockInfoFFI) ?*EvmHandle {
return guillotine_evm_create_mainnet(block_info_ptr);
}
// Create a new mainnet EVM instance (or reuse from pool)
export fn guillotine_evm_create_mainnet(block_info_ptr: *const BlockInfoFFI) ?*EvmHandle {
const allocator = ffi_allocator orelse {
setError("FFI not initialized. Call guillotine_init() first", .{});
return null;
};
pool_mutex.lock();
defer pool_mutex.unlock();
// Try to find a free instance in the pool
if (instance_pool) |*pool| {
for (pool.items) |instance| {
if (!instance.in_use) {
// Found a free instance - reset and reuse it
if (instance.needs_reset) {
// Reset the database by reinitializing it
instance.database.deinit();
instance.database.* = Database.init(allocator);
instance.needs_reset = false;
}
// Update block info
instance.block_info = block_info_ptr.*;
const block_info = BlockInfo{
.number = block_info_ptr.number,
.timestamp = block_info_ptr.timestamp,
.gas_limit = block_info_ptr.gas_limit,
.coinbase = primitives.Address{ .bytes = block_info_ptr.coinbase },
.base_fee = block_info_ptr.base_fee,
.difficulty = block_info_ptr.difficulty,
.prev_randao = block_info_ptr.prev_randao,
.chain_id = @intCast(block_info_ptr.chain_id),
.blob_base_fee = 0,
.blob_versioned_hashes = &.{},
};
instance.evm.block_info = block_info;
instance.in_use = true;
// Create handle and register it
const handle = @as(*EvmHandle, @ptrCast(instance.evm));
handle_map.?.put(handle, instance) catch {
instance.in_use = false;
setError("Failed to register handle", .{});
return null;
};
return handle;
}
}
}
// No free instance found, create a new one
const instance = allocator.create(EvmInstance) catch {
setError("Failed to allocate instance", .{});
return null;
};
// Create database
const db = allocator.create(Database) catch {
setError("Failed to allocate database", .{});
allocator.destroy(instance);
return null;
};
db.* = Database.init(allocator);
// Convert FFI block info to internal format
const block_info = BlockInfo{
.number = block_info_ptr.number,
.timestamp = block_info_ptr.timestamp,
.gas_limit = block_info_ptr.gas_limit,
.coinbase = primitives.Address{ .bytes = block_info_ptr.coinbase },
.base_fee = block_info_ptr.base_fee,
.difficulty = block_info_ptr.difficulty,
.prev_randao = block_info_ptr.prev_randao,
.chain_id = @intCast(block_info_ptr.chain_id),
.blob_base_fee = 0,
.blob_versioned_hashes = &.{},
};
// Create transaction context
const tx_context = TransactionContext{
.gas_limit = block_info_ptr.gas_limit,
.coinbase = primitives.Address{ .bytes = block_info_ptr.coinbase },
.chain_id = @intCast(block_info_ptr.chain_id),
.blob_versioned_hashes = &.{},
.blob_base_fee = 0,
};
// Create EVM instance (default, no tracing)
const evm_ptr = allocator.create(DefaultEvm) catch {
setError("Failed to allocate EVM", .{});
db.deinit();
allocator.destroy(db);
allocator.destroy(instance);
return null;
};
evm_ptr.* = DefaultEvm.init(
allocator,
db,
block_info,
tx_context,
0, // gas_price
primitives.Address.ZERO_ADDRESS, // origin
) catch {
setError("Failed to initialize EVM", .{});
db.deinit();
allocator.destroy(db);
allocator.destroy(evm_ptr);
allocator.destroy(instance);
return null;
};
// Initialize instance struct
instance.* = .{
.evm = evm_ptr,
.database = db,
.block_info = block_info_ptr.*,
.in_use = true,
.needs_reset = false,
.setup_addresses = std.ArrayList(primitives.Address).empty,
};
// Add to pool
instance_pool.?.append(allocator, instance) catch {
setError("Failed to add to pool", .{});
evm_ptr.deinit();
db.deinit();
allocator.destroy(db);
allocator.destroy(evm_ptr);
allocator.destroy(instance);
return null;
};
// Create handle and register it
const handle = @as(*EvmHandle, @ptrCast(evm_ptr));
handle_map.?.put(handle, instance) catch {
setError("Failed to register handle", .{});
return null;
};
return handle;
}
// Create a new EVM instance with JSON-RPC tracing enabled
export fn guillotine_evm_create_tracing(block_info_ptr: *const BlockInfoFFI) ?*EvmHandle {
const allocator = ffi_allocator orelse {
setError("FFI not initialized. Call guillotine_init() first", .{});
return null;
};
const db = allocator.create(Database) catch {
setError("Failed to allocate database", .{});
return null;
};
db.* = Database.init(allocator);
const block_info = BlockInfo{
.number = block_info_ptr.number,
.timestamp = block_info_ptr.timestamp,
.gas_limit = block_info_ptr.gas_limit,
.coinbase = primitives.Address{ .bytes = block_info_ptr.coinbase },
.base_fee = block_info_ptr.base_fee,
.difficulty = block_info_ptr.difficulty,
.prev_randao = block_info_ptr.prev_randao,
.chain_id = @intCast(block_info_ptr.chain_id),
.blob_base_fee = 0,
.blob_versioned_hashes = &.{},
};
const tx_context = TransactionContext{
.gas_limit = block_info_ptr.gas_limit,
.coinbase = primitives.Address{ .bytes = block_info_ptr.coinbase },
.chain_id = @intCast(block_info_ptr.chain_id),
.blob_versioned_hashes = &.{},
.blob_base_fee = 0,
};
const evm_ptr = allocator.create(TracerEvm) catch {
setError("Failed to allocate TracerEvm", .{});
db.deinit();
allocator.destroy(db);
return null;
};
evm_ptr.* = TracerEvm.init(
allocator,
db,
block_info,
tx_context,
0,
primitives.Address.ZERO_ADDRESS,
) catch {
setError("Failed to initialize TracerEvm", .{});
db.deinit();
allocator.destroy(db);
allocator.destroy(evm_ptr);
return null;
};
return @ptrCast(evm_ptr);
}
// Create a new test EVM instance with gas checks disabled
export fn guillotine_evm_create_test(block_info_ptr: *const BlockInfoFFI) ?*EvmHandle {
const allocator = ffi_allocator orelse {
setError("FFI not initialized. Call guillotine_init() first", .{});
return null;
};
pool_mutex.lock();
defer pool_mutex.unlock();
// Try to find a free instance in the pool
if (test_instance_pool) |*pool| {
for (pool.items) |instance| {
if (!instance.in_use) {
// Found a free instance - reset and reuse it
if (instance.needs_reset) {
// Reset the database by reinitializing it
instance.database.deinit();
instance.database.* = Database.init(allocator);
instance.needs_reset = false;
}
// Update block info
instance.block_info = block_info_ptr.*;
const block_info = BlockInfo{
.number = block_info_ptr.number,
.timestamp = block_info_ptr.timestamp,
.gas_limit = block_info_ptr.gas_limit,
.coinbase = primitives.Address{ .bytes = block_info_ptr.coinbase },
.base_fee = block_info_ptr.base_fee,
.difficulty = block_info_ptr.difficulty,
.prev_randao = block_info_ptr.prev_randao,
.chain_id = @intCast(block_info_ptr.chain_id),
.blob_base_fee = 0,
.blob_versioned_hashes = &.{},
};
instance.evm.block_info = block_info;
instance.in_use = true;
// Create handle and register it
const handle = @as(*EvmHandle, @ptrCast(instance.evm));
test_handle_map.?.put(handle, instance) catch {
instance.in_use = false;
setError("Failed to register handle", .{});
return null;
};
return handle;
}
}
}
// No free instances, create a new one
const db = allocator.create(Database) catch {
setError("Failed to allocate database", .{});
return null;
};
db.* = Database.init(allocator);
const block_info = BlockInfo{
.number = block_info_ptr.number,
.timestamp = block_info_ptr.timestamp,
.gas_limit = block_info_ptr.gas_limit,
.coinbase = primitives.Address{ .bytes = block_info_ptr.coinbase },
.base_fee = block_info_ptr.base_fee,
.difficulty = block_info_ptr.difficulty,
.prev_randao = block_info_ptr.prev_randao,
.chain_id = @intCast(block_info_ptr.chain_id),
.blob_base_fee = 0,
.blob_versioned_hashes = &.{},
};
const tx_context = TransactionContext{
.gas_limit = block_info_ptr.gas_limit,
.coinbase = primitives.Address{ .bytes = block_info_ptr.coinbase },
.chain_id = @intCast(block_info_ptr.chain_id),
.blob_versioned_hashes = &.{},
.blob_base_fee = 0,
};
const evm_ptr = allocator.create(TestEvm) catch {
setError("Failed to allocate TestEvm", .{});
db.deinit();
allocator.destroy(db);
return null;
};
evm_ptr.* = TestEvm.init(
allocator,
db,
block_info,
tx_context,
0,
primitives.Address.ZERO_ADDRESS,
) catch {
setError("Failed to initialize TestEvm", .{});
db.deinit();
allocator.destroy(db);
allocator.destroy(evm_ptr);
return null;
};
// Create instance for pool
const instance = allocator.create(TestEvmInstance) catch {
setError("Failed to allocate instance", .{});
evm_ptr.deinit();
db.deinit();
allocator.destroy(db);
allocator.destroy(evm_ptr);
return null;
};
instance.* = TestEvmInstance{
.evm = evm_ptr,
.database = db,
.block_info = block_info_ptr.*,
.in_use = true,
.needs_reset = false,
};
// Add to pool
test_instance_pool.?.append(allocator, instance) catch {
setError("Failed to add to pool", .{});
evm_ptr.deinit();
db.deinit();
allocator.destroy(db);
allocator.destroy(evm_ptr);
allocator.destroy(instance);
return null;
};
// Create handle and register it
const handle = @as(*EvmHandle, @ptrCast(evm_ptr));
test_handle_map.?.put(handle, instance) catch {
setError("Failed to register handle", .{});
return null;
};
return handle;
}
// Destroy an EVM instance (actually returns it to the pool)
export fn guillotine_evm_destroy(handle: *EvmHandle) void {
pool_mutex.lock();
defer pool_mutex.unlock();
// Try mainnet instances first
if (handle_map) |*map| {
if (map.fetchRemove(handle)) |entry| {
const instance = entry.value;
// Mark as not in use and needs reset
instance.in_use = false;
instance.needs_reset = true;
// Instance stays in the pool for reuse
return;
}
}
// Try test instances
if (test_handle_map) |*map| {
if (map.fetchRemove(handle)) |entry| {
const instance = entry.value;
// Mark as not in use and needs reset
instance.in_use = false;
instance.needs_reset = true;
// Instance stays in the pool for reuse
return;
}
}
}
// Destroy a tracing EVM instance
export fn guillotine_evm_destroy_tracing(handle: *EvmHandle) void {
const allocator = ffi_allocator orelse return;
const evm_ptr: *TracerEvm = @ptrCast(@alignCast(handle));
const db = evm_ptr.database;
evm_ptr.deinit();
db.deinit();
allocator.destroy(db);
allocator.destroy(evm_ptr);
}
// Set account balance
export fn guillotine_set_balance(handle: *EvmHandle, address: *const [20]u8, balance: *const [32]u8) bool {
const evm_ptr: *DefaultEvm = @ptrCast(@alignCast(handle));
// Convert balance bytes to u256
const balance_value = std.mem.readInt(u256, balance, .big);
// Get or create account
var account = evm_ptr.database.get_account(address.*) catch {
setError("Failed to get account", .{});
return false;
} orelse Account.zero();
account.balance = balance_value;
evm_ptr.database.set_account(address.*, account) catch {
setError("Failed to set account balance", .{});
return false;
};
// Track this address for state dump
const addr = primitives.Address{ .bytes = address.* };
evm_ptr.touched_addresses.put(addr, {}) catch {};
return true;
}
// Set account balance (tracing)
export fn guillotine_set_balance_tracing(handle: *EvmHandle, address: *const [20]u8, balance: *const [32]u8) bool {
const evm_ptr: *TracerEvm = @ptrCast(@alignCast(handle));
const balance_value = std.mem.readInt(u256, balance, .big);
var account = evm_ptr.database.get_account(address.*) catch {
setError("Failed to get account", .{});
return false;
} orelse Account.zero();
account.balance = balance_value;
evm_ptr.database.set_account(address.*, account) catch {
setError("Failed to set account balance", .{});
return false;
};
// Track this address for state dump
const addr = primitives.Address{ .bytes = address.* };
evm_ptr.touched_addresses.put(addr, {}) catch {};
return true;
}
// Set account nonce
export fn guillotine_set_nonce(handle: *EvmHandle, address: *const [20]u8, nonce: u64) bool {
const evm_ptr: *DefaultEvm = @ptrCast(@alignCast(handle));
// Get or create account
var account = evm_ptr.database.get_account(address.*) catch {
setError("Failed to get account", .{});
return false;
} orelse Account.zero();
account.nonce = nonce;
evm_ptr.database.set_account(address.*, account) catch {
setError("Failed to set account nonce", .{});
return false;
};
// Track this address for state dump
const addr = primitives.Address{ .bytes = address.* };
evm_ptr.touched_addresses.put(addr, {}) catch {};
return true;
}
// Set account nonce (tracing)
export fn guillotine_set_nonce_tracing(handle: *EvmHandle, address: *const [20]u8, nonce: u64) bool {
const evm_ptr: *TracerEvm = @ptrCast(@alignCast(handle));
var account = evm_ptr.database.get_account(address.*) catch {
setError("Failed to get account", .{});
return false;
} orelse Account.zero();
account.nonce = nonce;
evm_ptr.database.set_account(address.*, account) catch {
setError("Failed to set account nonce", .{});
return false;
};
// Track this address for state dump
const addr = primitives.Address{ .bytes = address.* };
evm_ptr.touched_addresses.put(addr, {}) catch {};
return true;
}
// Set contract code
export fn guillotine_set_code(handle: *EvmHandle, address: *const [20]u8, code: [*]const u8, code_len: usize) bool {
const evm_ptr: *DefaultEvm = @ptrCast(@alignCast(handle));
const code_slice = code[0..code_len];
// Store code in database
const code_hash = evm_ptr.database.set_code(code_slice) catch {
setError("Failed to store code", .{});
return false;
};
// Get or create account
var account = evm_ptr.database.get_account(address.*) catch {
setError("Failed to get account", .{});
return false;
} orelse Account.zero();
account.code_hash = code_hash;
evm_ptr.database.set_account(address.*, account) catch {
setError("Failed to update account code hash", .{});
return false;
};
// Track this address for state dump
const addr = primitives.Address{ .bytes = address.* };
evm_ptr.touched_addresses.put(addr, {}) catch {};
return true;
}
// Set contract code (tracing)
export fn guillotine_set_code_tracing(handle: *EvmHandle, address: *const [20]u8, code: [*]const u8, code_len: usize) bool {
const evm_ptr: *TracerEvm = @ptrCast(@alignCast(handle));
const code_slice = code[0..code_len];
const code_hash = evm_ptr.database.set_code(code_slice) catch {
setError("Failed to store code", .{});
return false;
};
var account = evm_ptr.database.get_account(address.*) catch {
setError("Failed to get account", .{});
return false;
} orelse Account.zero();
account.code_hash = code_hash;
evm_ptr.database.set_account(address.*, account) catch {
setError("Failed to update account code hash", .{});
return false;
};
// Track this address for state dump
const addr = primitives.Address{ .bytes = address.* };
evm_ptr.touched_addresses.put(addr, {}) catch {};
return true;
}
// Helper function to convert CallResult to EvmResult
fn convertCallResultToEvmResult(result: anytype, allocator: std.mem.Allocator) ?*EvmResult {
// Allocate result structure on heap
const evm_result = allocator.create(EvmResult) catch {
setError("Failed to allocate result", .{});
return null;
};
// Set basic fields
evm_result.success = result.success;
evm_result.gas_left = result.gas_left;
evm_result.error_message = if (result.error_info) |info| blk: {
_ = std.fmt.bufPrintZ(&last_error_z, "{s}", .{info}) catch "Unknown error";
break :blk @ptrCast(&last_error_z);
} else if (!result.success) @ptrCast(&last_error_z) else @as([*:0]const u8, @ptrCast(&empty_error));
// Copy output if present
if (result.output.len > 0) {
const output_copy = allocator.alloc(u8, result.output.len) catch {
setError("Failed to allocate output buffer", .{});
allocator.destroy(evm_result);
return null;
};
@memcpy(output_copy, result.output);
evm_result.output = output_copy.ptr;
evm_result.output_len = output_copy.len;
} else {
evm_result.output = @as([*]const u8, @ptrCast(&empty_error));
evm_result.output_len = 0;
}
// Copy logs if present
if (result.logs.len > 0) {
const logs_copy = allocator.alloc(LogEntry, result.logs.len) catch {
setError("Failed to allocate logs", .{});
if (evm_result.output_len > 0) allocator.free(evm_result.output[0..evm_result.output_len]);
allocator.destroy(evm_result);
return null;
};
for (result.logs, 0..) |log_item, i| {
logs_copy[i].address = log_item.address.bytes;
// Copy topics
if (log_item.topics.len > 0) {
const topics_copy = allocator.alloc([32]u8, log_item.topics.len) catch {
setError("Failed to allocate topics", .{});
// Clean up already allocated
for (logs_copy[0..i]) |prev_log| {
if (prev_log.topics_len > 0) allocator.free(prev_log.topics[0..prev_log.topics_len]);
if (prev_log.data_len > 0) allocator.free(prev_log.data[0..prev_log.data_len]);
}
allocator.free(logs_copy);
if (evm_result.output_len > 0) allocator.free(evm_result.output[0..evm_result.output_len]);
allocator.destroy(evm_result);
return null;
};
for (log_item.topics, 0..) |topic, j| {
std.mem.writeInt(u256, &topics_copy[j], topic, .big);
}
logs_copy[i].topics = topics_copy.ptr;
logs_copy[i].topics_len = topics_copy.len;
} else {
logs_copy[i].topics = @as([*]const [32]u8, @ptrCast(&empty_buffer));
logs_copy[i].topics_len = 0;
}
// Copy data
if (log_item.data.len > 0) {
const data_copy = allocator.alloc(u8, log_item.data.len) catch {
setError("Failed to allocate log data", .{});
// Clean up
if (logs_copy[i].topics_len > 0) allocator.free(logs_copy[i].topics[0..logs_copy[i].topics_len]);
for (logs_copy[0..i]) |prev_log| {
if (prev_log.topics_len > 0) allocator.free(prev_log.topics[0..prev_log.topics_len]);
if (prev_log.data_len > 0) allocator.free(prev_log.data[0..prev_log.data_len]);
}
allocator.free(logs_copy);
if (evm_result.output_len > 0) allocator.free(evm_result.output[0..evm_result.output_len]);
allocator.destroy(evm_result);
return null;
};
@memcpy(data_copy, log_item.data);
logs_copy[i].data = data_copy.ptr;
logs_copy[i].data_len = data_copy.len;
} else {
logs_copy[i].data = @as([*]const u8, @ptrCast(&empty_buffer));
logs_copy[i].data_len = 0;
}
}
evm_result.logs = logs_copy.ptr;
evm_result.logs_len = logs_copy.len;
} else {
evm_result.logs = @as([*]const LogEntry, @ptrCast(@alignCast(&empty_buffer)));
evm_result.logs_len = 0;
}
// Copy selfdestructs if present
if (result.selfdestructs.len > 0) {
const selfdestructs_copy = allocator.alloc(SelfDestructRecord, result.selfdestructs.len) catch {
setError("Failed to allocate selfdestructs", .{});
// Clean up logs
if (evm_result.logs_len > 0) {
for (evm_result.logs[0..evm_result.logs_len]) |log_item| {
if (log_item.topics_len > 0) allocator.free(log_item.topics[0..log_item.topics_len]);
if (log_item.data_len > 0) allocator.free(log_item.data[0..log_item.data_len]);
}
allocator.free(evm_result.logs[0..evm_result.logs_len]);
}
if (evm_result.output_len > 0) allocator.free(evm_result.output[0..evm_result.output_len]);
allocator.destroy(evm_result);
return null;
};
for (result.selfdestructs, 0..) |sd, i| {
selfdestructs_copy[i].contract = sd.contract.bytes;
selfdestructs_copy[i].beneficiary = sd.beneficiary.bytes;
}
evm_result.selfdestructs = selfdestructs_copy.ptr;
evm_result.selfdestructs_len = selfdestructs_copy.len;
} else {
evm_result.selfdestructs = @as([*]const SelfDestructRecord, @ptrCast(&empty_buffer));
evm_result.selfdestructs_len = 0;
}
// Copy accessed addresses if present
if (result.accessed_addresses.len > 0) {
const addresses_copy = allocator.alloc([20]u8, result.accessed_addresses.len) catch {
setError("Failed to allocate accessed addresses", .{});
// Clean up previous allocations
if (evm_result.selfdestructs_len > 0) allocator.free(evm_result.selfdestructs[0..evm_result.selfdestructs_len]);
if (evm_result.logs_len > 0) {
for (evm_result.logs[0..evm_result.logs_len]) |log_item| {
if (log_item.topics_len > 0) allocator.free(log_item.topics[0..log_item.topics_len]);
if (log_item.data_len > 0) allocator.free(log_item.data[0..log_item.data_len]);
}
allocator.free(evm_result.logs[0..evm_result.logs_len]);
}
if (evm_result.output_len > 0) allocator.free(evm_result.output[0..evm_result.output_len]);
allocator.destroy(evm_result);
return null;
};
for (result.accessed_addresses, 0..) |addr, i| {
addresses_copy[i] = addr.bytes;
}
evm_result.accessed_addresses = addresses_copy.ptr;
evm_result.accessed_addresses_len = addresses_copy.len;
} else {
evm_result.accessed_addresses = @as([*]const [20]u8, @ptrCast(&empty_buffer));
evm_result.accessed_addresses_len = 0;
}
// Copy accessed storage if present
if (result.accessed_storage.len > 0) {
const storage_copy = allocator.alloc(StorageAccessRecord, result.accessed_storage.len) catch {
setError("Failed to allocate accessed storage", .{});
// Clean up previous allocations
if (evm_result.accessed_addresses_len > 0) allocator.free(evm_result.accessed_addresses[0..evm_result.accessed_addresses_len]);
if (evm_result.selfdestructs_len > 0) allocator.free(evm_result.selfdestructs[0..evm_result.selfdestructs_len]);
if (evm_result.logs_len > 0) {
for (evm_result.logs[0..evm_result.logs_len]) |log_item| {
if (log_item.topics_len > 0) allocator.free(log_item.topics[0..log_item.topics_len]);
if (log_item.data_len > 0) allocator.free(log_item.data[0..log_item.data_len]);
}
allocator.free(evm_result.logs[0..evm_result.logs_len]);
}
if (evm_result.output_len > 0) allocator.free(evm_result.output[0..evm_result.output_len]);
allocator.destroy(evm_result);
return null;
};
for (result.accessed_storage, 0..) |access, i| {
storage_copy[i].address = access.address.bytes;
std.mem.writeInt(u256, &storage_copy[i].slot, access.slot, .big);
}
evm_result.accessed_storage = storage_copy.ptr;
evm_result.accessed_storage_len = storage_copy.len;
} else {
evm_result.accessed_storage = @as([*]const StorageAccessRecord, @ptrCast(&empty_buffer));
evm_result.accessed_storage_len = 0;
}
// Set created address if present
if (result.created_address) |addr| {
evm_result.created_address = addr.bytes;
evm_result.has_created_address = true;
} else {
evm_result.created_address = primitives.Address.ZERO_ADDRESS.bytes;
evm_result.has_created_address = false;
}
// If we have an execution trace, write to a temp file for large traces
evm_result.trace_json = @as([*]const u8, @ptrCast(&empty_error));
evm_result.trace_json_len = 0;
if (result.trace) |*trace| {
// Always use in-memory approach for now
// TODO: Re-implement file-based approach for large traces
if (false) {
// Disabled file-based approach
const w = undefined;
w.writeAll("{\"structLogs\":[") catch {};
for (trace.steps, 0..) |step, i| {
if (i > 0) w.writeAll(",") catch {};
w.writeAll("{") catch {};
w.print("\"pc\":{d},", .{step.pc}) catch {};
w.print("\"op\":\"{s}\",", .{step.opcode_name}) catch {};
w.print("\"gas\":{d},", .{step.gas}) catch {};