-
Notifications
You must be signed in to change notification settings - Fork 562
/
Copy pathmod.rs
1923 lines (1813 loc) · 77 KB
/
mod.rs
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
use std::any::Any;
use std::borrow::Cow;
use std::collections::{HashMap, VecDeque};
use std::ops::{Deref, Shl};
use ark_ff::fields::{Fp256, MontBackend, MontConfig};
use ark_ff::{BigInteger, Field, PrimeField};
use ark_std::UniformRand;
use cairo_felt::{felt_str as felt252_str, Felt252};
use cairo_lang_casm::hints::{CoreHint, DeprecatedHint, Hint, StarknetHint};
use cairo_lang_casm::instructions::Instruction;
use cairo_lang_casm::operand::{
BinOpOperand, CellRef, DerefOrImmediate, Operation, Register, ResOperand,
};
use cairo_lang_sierra::ids::FunctionId;
use cairo_lang_utils::extract_matches;
use cairo_vm::hint_processor::hint_processor_definition::{HintProcessor, HintReference};
use cairo_vm::serde::deserialize_program::{
ApTracking, BuiltinName, FlowTrackingData, HintParams, ReferenceManager,
};
use cairo_vm::types::exec_scope::ExecutionScopes;
use cairo_vm::types::program::Program;
use cairo_vm::types::relocatable::{MaybeRelocatable, Relocatable};
use cairo_vm::vm::errors::cairo_run_errors::CairoRunError;
use cairo_vm::vm::errors::hint_errors::HintError;
use cairo_vm::vm::errors::memory_errors::MemoryError;
use cairo_vm::vm::errors::vm_errors::VirtualMachineError;
use cairo_vm::vm::runners::cairo_runner::CairoRunner;
use cairo_vm::vm::vm_core::VirtualMachine;
use dict_manager::DictManagerExecScope;
use num_bigint::BigUint;
use num_integer::Integer;
use num_traits::{FromPrimitive, ToPrimitive, Zero};
use {ark_secp256k1 as secp256k1, ark_secp256r1 as secp256r1};
use self::dict_manager::DictSquashExecScope;
use crate::short_string::as_cairo_short_string;
use crate::{build_hints_dict, Arg, RunResultValue, SierraCasmRunner};
#[cfg(test)]
mod test;
mod dict_manager;
// TODO(orizi): This def is duplicated.
/// Returns the Beta value of the Starkware elliptic curve.
fn get_beta() -> Felt252 {
felt252_str!("3141592653589793238462643383279502884197169399375105820974944592307816406665")
}
#[derive(MontConfig)]
#[modulus = "3618502788666131213697322783095070105623107215331596699973092056135872020481"]
#[generator = "3"]
struct FqConfig;
type Fq = Fp256<MontBackend<FqConfig, 4>>;
/// Convert a Hint to the cairo-vm class HintParams by canonically serializing it to a string.
pub fn hint_to_hint_params(hint: &Hint) -> HintParams {
HintParams {
code: hint.to_string(),
accessible_scopes: vec![],
flow_tracking_data: FlowTrackingData {
ap_tracking: ApTracking::new(),
reference_ids: HashMap::new(),
},
}
}
/// Helper object to allocate and track Secp256k1 elliptic curve points.
#[derive(Default)]
struct Secp256k1ExecutionScope {
/// All elliptic curve points provided by the secp256k1 syscalls.
/// The id of a point is the index in the vector.
ec_points: Vec<secp256k1::Affine>,
}
/// Helper object to allocate and track Secp256r1 elliptic curve points.
#[derive(Default)]
struct Secp256r1ExecutionScope {
/// All elliptic curve points provided by the secp256r1 syscalls.
/// The id of a point is the index in the vector.
ec_points: Vec<secp256r1::Affine>,
}
/// HintProcessor for Cairo compiler hints.
pub struct CairoHintProcessor<'a> {
/// The Cairo runner.
#[allow(dead_code)]
pub runner: Option<&'a SierraCasmRunner>,
// A mapping from a string that represents a hint to the hint object.
pub string_to_hint: HashMap<String, Hint>,
// The starknet state.
pub starknet_state: StarknetState,
}
fn cell_ref_to_relocatable(cell_ref: &CellRef, vm: &VirtualMachine) -> Relocatable {
let base = match cell_ref.register {
Register::AP => vm.get_ap(),
Register::FP => vm.get_fp(),
};
(base + (cell_ref.offset as i32)).unwrap()
}
/// Inserts a value into the vm memory cell represented by the cellref.
macro_rules! insert_value_to_cellref {
($vm:ident, $cell_ref:ident, $value:expr) => {
$vm.insert_value(cell_ref_to_relocatable($cell_ref, $vm), $value)
};
}
// Log type signature
type Log = (Vec<Felt252>, Vec<Felt252>);
/// Execution scope for starknet related data.
/// All values will be 0 and by default if not setup by the test.
#[derive(Clone, Default)]
pub struct StarknetState {
/// The values of addresses in the simulated storage per contract.
storage: HashMap<Felt252, HashMap<Felt252, Felt252>>,
/// A mapping from contract address to class hash.
#[allow(dead_code)]
deployed_contracts: HashMap<Felt252, Felt252>,
/// A mapping from contract address to logs.
logs: HashMap<Felt252, VecDeque<Log>>,
/// The simulated execution info.
exec_info: ExecutionInfo,
next_id: Felt252,
}
impl StarknetState {
pub fn get_next_id(&mut self) -> Felt252 {
self.next_id += Felt252::from(1);
self.next_id.clone()
}
}
/// Copy of the cairo `ExecutionInfo` struct.
#[derive(Clone, Default)]
struct ExecutionInfo {
block_info: BlockInfo,
tx_info: TxInfo,
caller_address: Felt252,
contract_address: Felt252,
}
/// Copy of the cairo `BlockInfo` struct.
#[derive(Clone, Default)]
struct BlockInfo {
block_number: Felt252,
block_timestamp: Felt252,
sequencer_address: Felt252,
}
/// Copy of the cairo `TxInfo` struct.
#[derive(Clone, Default)]
struct TxInfo {
version: Felt252,
account_contract_address: Felt252,
max_fee: Felt252,
signature: Vec<Felt252>,
transaction_hash: Felt252,
chain_id: Felt252,
nonce: Felt252,
}
/// Execution scope for constant memory allocation.
struct MemoryExecScope {
/// The first free address in the segment.
next_address: Relocatable,
}
/// Fetches the value of a cell from the vm.
fn get_cell_val(vm: &VirtualMachine, cell: &CellRef) -> Result<Felt252, VirtualMachineError> {
Ok(vm.get_integer(cell_ref_to_relocatable(cell, vm))?.as_ref().clone())
}
/// Fetch the `MaybeRelocatable` value from an address.
fn get_maybe_from_addr(
vm: &VirtualMachine,
addr: Relocatable,
) -> Result<MaybeRelocatable, VirtualMachineError> {
vm.get_maybe(&addr)
.ok_or_else(|| VirtualMachineError::InvalidMemoryValueTemporaryAddress(Box::new(addr)))
}
/// Fetches the maybe relocatable value of a cell from the vm.
fn get_cell_maybe(
vm: &VirtualMachine,
cell: &CellRef,
) -> Result<MaybeRelocatable, VirtualMachineError> {
get_maybe_from_addr(vm, cell_ref_to_relocatable(cell, vm))
}
/// Fetches the value of a cell plus an offset from the vm, useful for pointers.
fn get_ptr(
vm: &VirtualMachine,
cell: &CellRef,
offset: &Felt252,
) -> Result<Relocatable, VirtualMachineError> {
Ok((vm.get_relocatable(cell_ref_to_relocatable(cell, vm))? + offset)?)
}
/// Fetches the value of a pointer described by the value at `cell` plus an offset from the vm.
fn get_double_deref_val(
vm: &VirtualMachine,
cell: &CellRef,
offset: &Felt252,
) -> Result<Felt252, VirtualMachineError> {
Ok(vm.get_integer(get_ptr(vm, cell, offset)?)?.as_ref().clone())
}
/// Fetches the maybe relocatable value of a pointer described by the value at `cell` plus an offset
/// from the vm.
fn get_double_deref_maybe(
vm: &VirtualMachine,
cell: &CellRef,
offset: &Felt252,
) -> Result<MaybeRelocatable, VirtualMachineError> {
get_maybe_from_addr(vm, get_ptr(vm, cell, offset)?)
}
/// Fetches the value of `res_operand` from the vm.
fn get_val(vm: &VirtualMachine, res_operand: &ResOperand) -> Result<Felt252, VirtualMachineError> {
match res_operand {
ResOperand::Deref(cell) => get_cell_val(vm, cell),
ResOperand::DoubleDeref(cell, offset) => get_double_deref_val(vm, cell, &(*offset).into()),
ResOperand::Immediate(x) => Ok(Felt252::from(x.value.clone())),
ResOperand::BinOp(op) => {
let a = get_cell_val(vm, &op.a)?;
let b = match &op.b {
DerefOrImmediate::Deref(cell) => get_cell_val(vm, cell)?,
DerefOrImmediate::Immediate(x) => Felt252::from(x.value.clone()),
};
match op.op {
Operation::Add => Ok(a + b),
Operation::Mul => Ok(a * b),
}
}
}
}
/// Resulting options from a syscall.
enum SyscallResult {
/// The syscall was successful.
Success(Vec<MaybeRelocatable>),
/// The syscall failed, with the revert reason.
Failure(Vec<Felt252>),
}
macro_rules! fail_syscall {
($reason:expr) => {
return Ok(SyscallResult::Failure(vec![Felt252::from_bytes_be($reason)]))
};
($existing:ident, $reason:expr) => {
$existing.push(Felt252::from_bytes_be($reason));
return Ok(SyscallResult::Failure($existing))
};
}
/// Deducts gas from the given gas counter, or fails the syscall if there is not enough gas.
macro_rules! deduct_gas {
($gas:ident, $amount:expr) => {
if *$gas < $amount {
fail_syscall!(b"Syscall out of gas");
}
*$gas -= $amount;
};
}
/// Fetches the maybe relocatable value of `res_operand` from the vm.
fn get_maybe(
vm: &VirtualMachine,
res_operand: &ResOperand,
) -> Result<MaybeRelocatable, VirtualMachineError> {
match res_operand {
ResOperand::Deref(cell) => get_cell_maybe(vm, cell),
ResOperand::DoubleDeref(cell, offset) => {
get_double_deref_maybe(vm, cell, &(*offset).into())
}
ResOperand::Immediate(x) => Ok(Felt252::from(x.value.clone()).into()),
ResOperand::BinOp(op) => {
let a = get_cell_maybe(vm, &op.a)?;
let b = match &op.b {
DerefOrImmediate::Deref(cell) => get_cell_val(vm, cell)?,
DerefOrImmediate::Immediate(x) => Felt252::from(x.value.clone()),
};
Ok(match op.op {
Operation::Add => a.add_int(&b)?,
Operation::Mul => match a {
MaybeRelocatable::RelocatableValue(_) => {
panic!("mul not implemented for relocatable values")
}
MaybeRelocatable::Int(a) => (a * b).into(),
},
})
}
}
}
impl HintProcessor for CairoHintProcessor<'_> {
/// Trait function to execute a given hint in the hint processor.
fn execute_hint(
&mut self,
vm: &mut VirtualMachine,
exec_scopes: &mut ExecutionScopes,
hint_data: &Box<dyn Any>,
_constants: &HashMap<String, Felt252>,
) -> Result<(), HintError> {
let hint = hint_data.downcast_ref::<Hint>().unwrap();
let hint = match hint {
Hint::Core(core_hint_base) => {
return execute_core_hint_base(vm, exec_scopes, core_hint_base);
}
Hint::Starknet(hint) => hint,
};
match hint {
StarknetHint::SystemCall { system } => {
self.execute_syscall(system, vm, exec_scopes)?;
}
StarknetHint::SetSequencerAddress { value } => {
self.starknet_state.exec_info.block_info.sequencer_address = get_val(vm, value)?;
}
StarknetHint::SetBlockTimestamp { value } => {
self.starknet_state.exec_info.block_info.block_timestamp = get_val(vm, value)?;
}
StarknetHint::SetCallerAddress { value } => {
self.starknet_state.exec_info.caller_address = get_val(vm, value)?;
}
StarknetHint::SetContractAddress { value } => {
self.starknet_state.exec_info.contract_address = get_val(vm, value)?;
}
StarknetHint::SetVersion { value } => {
self.starknet_state.exec_info.tx_info.version = get_val(vm, value)?;
}
StarknetHint::SetAccountContractAddress { value } => {
self.starknet_state.exec_info.tx_info.account_contract_address =
get_val(vm, value)?;
}
StarknetHint::SetMaxFee { value } => {
self.starknet_state.exec_info.tx_info.max_fee = get_val(vm, value)?;
}
StarknetHint::SetTransactionHash { value } => {
self.starknet_state.exec_info.tx_info.transaction_hash = get_val(vm, value)?;
}
StarknetHint::SetChainId { value } => {
self.starknet_state.exec_info.tx_info.chain_id = get_val(vm, value)?;
}
StarknetHint::SetNonce { value } => {
self.starknet_state.exec_info.tx_info.nonce = get_val(vm, value)?;
}
StarknetHint::SetSignature { start, end } => {
let (cell, offset) = extract_buffer(start);
let start = get_ptr(vm, cell, &offset)?;
let (cell, offset) = extract_buffer(end);
let end = get_ptr(vm, cell, &offset)?;
self.starknet_state.exec_info.tx_info.signature = vm_get_range(vm, start, end)?;
}
StarknetHint::PopLog {
value,
opt_variant,
keys_start,
keys_end,
data_start,
data_end,
} => {
let contract_address = get_val(vm, value)?;
let mut res_segment = MemBuffer::new_segment(vm);
let logs = self.starknet_state.logs.entry(contract_address).or_default();
if let Some((keys, data)) = logs.pop_front() {
let keys_start_ptr = res_segment.ptr;
res_segment.write_data(keys.iter())?;
let keys_end_ptr = res_segment.ptr;
let data_start_ptr = res_segment.ptr;
res_segment.write_data(data.iter())?;
let data_end_ptr = res_segment.ptr;
// Option::Some variant
insert_value_to_cellref!(vm, opt_variant, 0)?;
insert_value_to_cellref!(vm, keys_start, keys_start_ptr)?;
insert_value_to_cellref!(vm, keys_end, keys_end_ptr)?;
insert_value_to_cellref!(vm, data_start, data_start_ptr)?;
insert_value_to_cellref!(vm, data_end, data_end_ptr)?;
} else {
// Option::None variant
insert_value_to_cellref!(vm, opt_variant, 1)?;
}
}
StarknetHint::Cheatcode { selector, input_start, input_end, .. } => {
let selector = &selector.value.to_bytes_be().1;
let selector = std::str::from_utf8(selector).map_err(|_| {
HintError::CustomHint(Box::from("failed to parse selector".to_string()))
})?;
match selector {
"set_block_number" => {
let as_relocatable = |vm, value| {
let (base, offset) = extract_buffer(value);
get_ptr(vm, base, &offset)
};
let mut curr = as_relocatable(vm, input_start)?;
let end = as_relocatable(vm, input_end)?;
let mut input: Vec<Felt252> = vec![];
while curr != end {
let value = vm.get_integer(curr)?;
input.push(value.into_owned());
curr += 1;
}
match &input[..] {
[input] => {
self.starknet_state.exec_info.block_info.block_number =
input.clone();
}
_ => {
return Err(HintError::CustomHint(Box::from(
"set_block_number cheatcode invalid args: pass span of an \
array with exactly one element",
)));
}
}
}
_ => Err(HintError::CustomHint(Box::from(format!(
"Unknown cheatcode selector: {selector}"
))))?,
}
}
};
Ok(())
}
/// Trait function to store hint in the hint processor by string.
fn compile_hint(
&self,
hint_code: &str,
_ap_tracking_data: &ApTracking,
_reference_ids: &HashMap<String, usize>,
_references: &HashMap<usize, HintReference>,
) -> Result<Box<dyn Any>, VirtualMachineError> {
Ok(Box::new(self.string_to_hint[hint_code].clone()))
}
}
/// Wrapper trait for a VM owner.
trait VMWrapper {
fn vm(&mut self) -> &mut VirtualMachine;
}
impl VMWrapper for VirtualMachine {
fn vm(&mut self) -> &mut VirtualMachine {
self
}
}
/// Creates a new segment in the VM memory and writes data to it, returing the start and end
/// pointers of the segment.
fn segment_with_data<T: Into<MaybeRelocatable>, Data: Iterator<Item = T>>(
vm: &mut dyn VMWrapper,
data: Data,
) -> Result<(Relocatable, Relocatable), MemoryError> {
let mut segment = MemBuffer::new_segment(vm);
let start = segment.ptr;
segment.write_data(data)?;
Ok((start, segment.ptr))
}
/// A helper struct to continuously write and read from a buffer in the VM memory.
struct MemBuffer<'a> {
/// The VM to write to.
/// This is a trait so that we would borrow the actual VM only once.
vm: &'a mut dyn VMWrapper,
/// The current location of the buffer.
pub ptr: Relocatable,
}
impl<'a> MemBuffer<'a> {
/// Creates a new buffer.
fn new(vm: &'a mut dyn VMWrapper, ptr: Relocatable) -> Self {
Self { vm, ptr }
}
/// Creates a new segment and returns a buffer wrapping it.
fn new_segment(vm: &'a mut dyn VMWrapper) -> Self {
let ptr = vm.vm().add_memory_segment();
Self::new(vm, ptr)
}
/// Returns the current position of the buffer and advances it by one.
fn next(&mut self) -> Relocatable {
let ptr = self.ptr;
self.ptr += 1;
ptr
}
/// Returns the felt252 value in the current position of the buffer and advances it by one.
/// Fails if the value is not a felt252.
/// Borrows the buffer since a reference is returned.
fn next_felt252(&mut self) -> Result<Cow<'_, Felt252>, MemoryError> {
let ptr = self.next();
self.vm.vm().get_integer(ptr)
}
/// Returns the usize value in the current position of the buffer and advances it by one.
/// Fails with `MemoryError` if the value is not a felt252.
/// Panics if the value is not a usize.
fn next_usize(&mut self) -> Result<usize, MemoryError> {
Ok(self.next_felt252()?.to_usize().unwrap())
}
/// Returns the u128 value in the current position of the buffer and advances it by one.
/// Fails with `MemoryError` if the value is not a felt252.
/// Panics if the value is not a u128.
fn next_u128(&mut self) -> Result<u128, MemoryError> {
Ok(self.next_felt252()?.to_u128().unwrap())
}
/// Returns the u64 value in the current position of the buffer and advances it by one.
/// Fails with `MemoryError` if the value is not a felt252.
/// Panics if the value is not a u64.
fn next_u64(&mut self) -> Result<u64, MemoryError> {
Ok(self.next_felt252()?.to_u64().unwrap())
}
/// Returns the u256 value encoded starting from the current position of the buffer and advances
/// it by two.
/// Fails with `MemoryError` if any of the next two values are not felt252s.
/// Panics if any of the next two values are not u128.
fn next_u256(&mut self) -> Result<BigUint, MemoryError> {
Ok(self.next_u128()? + BigUint::from(self.next_u128()?).shl(128))
}
/// Returns the address value in the current position of the buffer and advances it by one.
/// Fails if the value is not an address.
fn next_addr(&mut self) -> Result<Relocatable, MemoryError> {
let ptr = self.next();
self.vm.vm().get_relocatable(ptr)
}
/// Returns the array of integer values pointed to by the two next addresses in the buffer and
/// advances it by two. Will fail if the two values are not addresses or if the addresses do
/// not point to an array of integers.
fn next_arr(&mut self) -> Result<Vec<Felt252>, HintError> {
let start = self.next_addr()?;
let end = self.next_addr()?;
vm_get_range(self.vm.vm(), start, end)
}
/// Writes a value to the current position of the buffer and advances it by one.
fn write<T: Into<MaybeRelocatable>>(&mut self, value: T) -> Result<(), MemoryError> {
let ptr = self.next();
self.vm.vm().insert_value(ptr, value)
}
/// Writes an iterator of values starting from the current position of the buffer and advances
/// it to after the end of the written value.
fn write_data<T: Into<MaybeRelocatable>, Data: Iterator<Item = T>>(
&mut self,
data: Data,
) -> Result<(), MemoryError> {
for value in data {
self.write(value)?;
}
Ok(())
}
/// Writes an array into a new segment and writes the start and end pointers to the current
/// position of the buffer. Advances the buffer by two.
fn write_arr<T: Into<MaybeRelocatable>, Data: Iterator<Item = T>>(
&mut self,
data: Data,
) -> Result<(), MemoryError> {
let (start, end) = segment_with_data(self, data)?;
self.write(start)?;
self.write(end)
}
}
impl<'a> VMWrapper for MemBuffer<'a> {
fn vm(&mut self) -> &mut VirtualMachine {
self.vm.vm()
}
}
impl<'a> CairoHintProcessor<'a> {
/// Executes a syscall.
fn execute_syscall(
&mut self,
system: &ResOperand,
vm: &mut VirtualMachine,
exec_scopes: &mut ExecutionScopes,
) -> Result<(), HintError> {
let (cell, offset) = extract_buffer(system);
let system_ptr = get_ptr(vm, cell, &offset)?;
let mut system_buffer = MemBuffer::new(vm, system_ptr);
let selector = system_buffer.next_felt252()?.to_bytes_be();
let mut gas_counter = system_buffer.next_usize()?;
let mut execute_handle_helper =
|handler: &mut dyn FnMut(
// The syscall buffer.
&mut MemBuffer<'_>,
// The gas counter.
&mut usize,
) -> Result<SyscallResult, HintError>| {
match handler(&mut system_buffer, &mut gas_counter)? {
SyscallResult::Success(values) => {
system_buffer.write(gas_counter)?;
system_buffer.write(Felt252::from(0))?;
system_buffer.write_data(values.into_iter())?;
}
SyscallResult::Failure(revert_reason) => {
system_buffer.write(gas_counter)?;
system_buffer.write(Felt252::from(1))?;
system_buffer.write_arr(revert_reason.into_iter())?;
}
}
Ok(())
};
match std::str::from_utf8(&selector).unwrap() {
"StorageWrite" => execute_handle_helper(&mut |system_buffer, gas_counter| {
self.storage_write(
gas_counter,
system_buffer.next_felt252()?.into_owned(),
system_buffer.next_felt252()?.into_owned(),
system_buffer.next_felt252()?.into_owned(),
)
}),
"StorageRead" => execute_handle_helper(&mut |system_buffer, gas_counter| {
self.storage_read(
gas_counter,
system_buffer.next_felt252()?.into_owned(),
system_buffer.next_felt252()?.into_owned(),
)
}),
"GetBlockHash" => execute_handle_helper(&mut |system_buffer, gas_counter| {
self.get_block_hash(gas_counter, system_buffer.next_u64()?)
}),
"GetExecutionInfo" => execute_handle_helper(&mut |system_buffer, gas_counter| {
self.get_execution_info(gas_counter, system_buffer)
}),
"EmitEvent" => execute_handle_helper(&mut |system_buffer, gas_counter| {
self.emit_event(gas_counter, system_buffer.next_arr()?, system_buffer.next_arr()?)
}),
"SendMessageToL1" => execute_handle_helper(&mut |system_buffer, gas_counter| {
let _to_address = system_buffer.next_felt252()?;
let _payload = system_buffer.next_arr()?;
deduct_gas!(gas_counter, 50);
Ok(SyscallResult::Success(vec![]))
}),
"Keccak" => execute_handle_helper(&mut |system_buffer, gas_counter| {
keccak(gas_counter, system_buffer.next_arr()?)
}),
"Secp256k1New" => execute_handle_helper(&mut |system_buffer, gas_counter| {
secp256k1_new(
gas_counter,
system_buffer.next_u256()?,
system_buffer.next_u256()?,
exec_scopes,
)
}),
"Secp256k1Add" => execute_handle_helper(&mut |system_buffer, gas_counter| {
secp256k1_add(
gas_counter,
exec_scopes,
system_buffer.next_usize()?,
system_buffer.next_usize()?,
)
}),
"Secp256k1Mul" => execute_handle_helper(&mut |system_buffer, gas_counter| {
secp256k1_mul(
gas_counter,
system_buffer.next_usize()?,
system_buffer.next_u256()?,
exec_scopes,
)
}),
"Secp256k1GetPointFromX" => execute_handle_helper(&mut |system_buffer, gas_counter| {
secp256k1_get_point_from_x(
gas_counter,
system_buffer.next_u256()?,
system_buffer.next_felt252()?.is_zero(),
exec_scopes,
)
}),
"Secp256k1GetXy" => execute_handle_helper(&mut |system_buffer, gas_counter| {
secp256k1_get_xy(gas_counter, system_buffer.next_usize()?, exec_scopes)
}),
"Secp256r1New" => execute_handle_helper(&mut |system_buffer, gas_counter| {
secp256r1_new(
gas_counter,
system_buffer.next_u256()?,
system_buffer.next_u256()?,
exec_scopes,
)
}),
"Secp256r1Add" => execute_handle_helper(&mut |system_buffer, gas_counter| {
secp256r1_add(
gas_counter,
exec_scopes,
system_buffer.next_usize()?,
system_buffer.next_usize()?,
)
}),
"Secp256r1Mul" => execute_handle_helper(&mut |system_buffer, gas_counter| {
secp256r1_mul(
gas_counter,
system_buffer.next_usize()?,
system_buffer.next_u256()?,
exec_scopes,
)
}),
"Secp256r1GetPointFromX" => execute_handle_helper(&mut |system_buffer, gas_counter| {
secp256r1_get_point_from_x(
gas_counter,
system_buffer.next_u256()?,
system_buffer.next_felt252()?.is_zero(),
exec_scopes,
)
}),
"Secp256r1GetXy" => execute_handle_helper(&mut |system_buffer, gas_counter| {
secp256r1_get_xy(gas_counter, system_buffer.next_usize()?, exec_scopes)
}),
"Deploy" => execute_handle_helper(&mut |system_buffer, gas_counter| {
self.deploy(
gas_counter,
system_buffer.next_felt252()?.into_owned(),
system_buffer.next_felt252()?.into_owned(),
system_buffer.next_arr()?,
system_buffer.next_felt252()?.into_owned(),
system_buffer,
)
}),
"CallContract" => execute_handle_helper(&mut |system_buffer, gas_counter| {
self.call_contract(
gas_counter,
system_buffer.next_felt252()?.into_owned(),
system_buffer.next_felt252()?.into_owned(),
system_buffer.next_arr()?,
system_buffer,
)
}),
"LibraryCall" => execute_handle_helper(&mut |system_buffer, gas_counter| {
self.library_call(
gas_counter,
system_buffer.next_felt252()?.into_owned(),
system_buffer.next_felt252()?.into_owned(),
system_buffer.next_arr()?,
system_buffer,
)
}),
"ReplaceClass" => execute_handle_helper(&mut |system_buffer, gas_counter| {
self.replace_class(
gas_counter,
system_buffer.next_felt252()?.into_owned(),
system_buffer,
)
}),
_ => panic!("Unknown selector for system call!"),
}
}
/// Executes the `storage_write_syscall` syscall.
fn storage_write(
&mut self,
gas_counter: &mut usize,
addr_domain: Felt252,
addr: Felt252,
value: Felt252,
) -> Result<SyscallResult, HintError> {
deduct_gas!(gas_counter, 1000);
if !addr_domain.is_zero() {
// Only address_domain 0 is currently supported.
fail_syscall!(b"Unsupported address domain");
}
let contract = self.starknet_state.exec_info.contract_address.clone();
self.starknet_state.storage.entry(contract).or_default().insert(addr, value);
Ok(SyscallResult::Success(vec![]))
}
/// Executes the `storage_read_syscall` syscall.
fn storage_read(
&mut self,
gas_counter: &mut usize,
addr_domain: Felt252,
addr: Felt252,
) -> Result<SyscallResult, HintError> {
deduct_gas!(gas_counter, 100);
if !addr_domain.is_zero() {
// Only address_domain 0 is currently supported.
fail_syscall!(b"Unsupported address domain");
}
let value = self
.starknet_state
.storage
.get(&self.starknet_state.exec_info.contract_address)
.and_then(|contract_storage| contract_storage.get(&addr))
.cloned()
.unwrap_or_else(|| Felt252::from(0));
Ok(SyscallResult::Success(vec![value.into()]))
}
/// Executes the `get_block_hash_syscall` syscall.
fn get_block_hash(
&mut self,
gas_counter: &mut usize,
_block_number: u64,
) -> Result<SyscallResult, HintError> {
deduct_gas!(gas_counter, 100);
// TODO(Arni, 28/5/2023): Replace the temporary return value with the required value.
// One design suggestion - to preform a storage read. Have an arbitrary, hardcoded
// (For example, addr=1) contain the mapping from block number to block hash.
fail_syscall!(b"GET_BLOCK_HASH_UNIMPLEMENTED");
}
/// Executes the `get_execution_info_syscall` syscall.
fn get_execution_info(
&mut self,
gas_counter: &mut usize,
vm: &mut dyn VMWrapper,
) -> Result<SyscallResult, HintError> {
deduct_gas!(gas_counter, 50);
let exec_info = &self.starknet_state.exec_info;
let block_info = &exec_info.block_info;
let tx_info = &exec_info.tx_info;
let mut res_segment = MemBuffer::new_segment(vm);
let signature_start = res_segment.ptr;
res_segment.write_data(tx_info.signature.iter().cloned())?;
let signature_end = res_segment.ptr;
let tx_info_ptr = res_segment.ptr;
res_segment.write(tx_info.version.clone())?;
res_segment.write(tx_info.account_contract_address.clone())?;
res_segment.write(tx_info.max_fee.clone())?;
res_segment.write(signature_start)?;
res_segment.write(signature_end)?;
res_segment.write(tx_info.transaction_hash.clone())?;
res_segment.write(tx_info.chain_id.clone())?;
res_segment.write(tx_info.nonce.clone())?;
let block_info_ptr = res_segment.ptr;
res_segment.write(block_info.block_number.clone())?;
res_segment.write(block_info.block_timestamp.clone())?;
res_segment.write(block_info.sequencer_address.clone())?;
let exec_info_ptr = res_segment.ptr;
res_segment.write(block_info_ptr)?;
res_segment.write(tx_info_ptr)?;
res_segment.write(exec_info.caller_address.clone())?;
res_segment.write(exec_info.contract_address.clone())?;
Ok(SyscallResult::Success(vec![exec_info_ptr.into()]))
}
/// Executes the `emit_event_syscall` syscall.
fn emit_event(
&mut self,
gas_counter: &mut usize,
keys: Vec<Felt252>,
data: Vec<Felt252>,
) -> Result<SyscallResult, HintError> {
deduct_gas!(gas_counter, 50);
let contract = self.starknet_state.exec_info.contract_address.clone();
self.starknet_state.logs.entry(contract).or_default().push_front((keys, data));
Ok(SyscallResult::Success(vec![]))
}
/// Executes the `deploy_syscall` syscall.
fn deploy(
&mut self,
gas_counter: &mut usize,
class_hash: Felt252,
_contract_address_salt: Felt252,
calldata: Vec<Felt252>,
_deploy_from_zero: Felt252,
vm: &mut dyn VMWrapper,
) -> Result<SyscallResult, HintError> {
deduct_gas!(gas_counter, 50);
// Assign an arbitrary address to the contract.
let deployed_contract_address = self.starknet_state.get_next_id();
// Prepare runner for running the constructor.
let runner = self.runner.expect("Runner is needed for starknet.");
let Some(contract_info) = runner.starknet_contracts_info.get(&class_hash) else {
fail_syscall!(b"CLASS_HASH_NOT_FOUND");
};
// Call constructor if it exists.
let (res_data_start, res_data_end) = if let Some(constructor) = &contract_info.constructor {
// Replace the contract address in the context.
let old_contract_address = std::mem::replace(
&mut self.starknet_state.exec_info.contract_address,
deployed_contract_address.clone(),
);
// Run the constructor.
let res = self.call_entry_point(gas_counter, runner, constructor, calldata, vm);
// Restore the contract address in the context.
self.starknet_state.exec_info.contract_address = old_contract_address;
match res {
Ok(value) => value,
Err(mut revert_reason) => {
fail_syscall!(revert_reason, b"CONSTRUCTOR_FAILED");
}
}
} else {
(Relocatable::from((0, 0)), Relocatable::from((0, 0)))
};
// Set the class hash of the deployed contract.
self.starknet_state
.deployed_contracts
.insert(deployed_contract_address.clone(), class_hash);
Ok(SyscallResult::Success(vec![
deployed_contract_address.into(),
res_data_start.into(),
res_data_end.into(),
]))
}
/// Executes the `call_contract_syscall` syscall.
fn call_contract(
&mut self,
gas_counter: &mut usize,
contract_address: Felt252,
selector: Felt252,
calldata: Vec<Felt252>,
vm: &mut dyn VMWrapper,
) -> Result<SyscallResult, HintError> {
deduct_gas!(gas_counter, 50);
// Get the class hash of the contract.
let Some(class_hash) = self.starknet_state.deployed_contracts.get(&contract_address) else {
fail_syscall!(b"CONTRACT_NOT_DEPLOYED");
};
// Prepare runner for running the ctor.
let runner = self.runner.expect("Runner is needed for starknet.");
let contract_info = runner
.starknet_contracts_info
.get(class_hash)
.expect("Deployed contract not found in registry.");
// Call the function.
let Some(entry_point) = contract_info.externals.get(&selector) else {
fail_syscall!(b"ENTRYPOINT_NOT_FOUND");
};
// Replace the contract address in the context.
let old_contract_address = std::mem::replace(
&mut self.starknet_state.exec_info.contract_address,
contract_address.clone(),
);
let old_caller_address = std::mem::replace(
&mut self.starknet_state.exec_info.caller_address,
old_contract_address.clone(),
);
let res = self.call_entry_point(gas_counter, runner, entry_point, calldata, vm);
// Restore the contract address in the context.
self.starknet_state.exec_info.caller_address = old_caller_address;
self.starknet_state.exec_info.contract_address = old_contract_address;
match res {
Ok((res_data_start, res_data_end)) => {
Ok(SyscallResult::Success(vec![res_data_start.into(), res_data_end.into()]))
}
Err(mut revert_reason) => {
fail_syscall!(revert_reason, b"ENTRYPOINT_FAILED");
}
}
}
/// Executes the `library_call_syscall` syscall.
fn library_call(
&mut self,
gas_counter: &mut usize,
class_hash: Felt252,
selector: Felt252,
calldata: Vec<Felt252>,
vm: &mut dyn VMWrapper,
) -> Result<SyscallResult, HintError> {
deduct_gas!(gas_counter, 50);
// Prepare runner for running the call.
let runner = self.runner.expect("Runner is needed for starknet.");
let contract_info = runner
.starknet_contracts_info
.get(&class_hash)
.expect("Deployed contract not found in registry.");
// Call the function.
let Some(entry_point) = contract_info.externals.get(&selector) else {
fail_syscall!(b"ENTRYPOINT_NOT_FOUND");
};
match self.call_entry_point(gas_counter, runner, entry_point, calldata, vm) {
Ok((res_data_start, res_data_end)) => {
Ok(SyscallResult::Success(vec![res_data_start.into(), res_data_end.into()]))
}
Err(mut revert_reason) => {
fail_syscall!(revert_reason, b"ENTRYPOINT_FAILED");
}
}
}
/// Executes the `replace_class_syscall` syscall.
fn replace_class(
&mut self,