This repository was archived by the owner on Jul 22, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 53
/
Copy pathnative_syscall_handler.rs
1566 lines (1407 loc) · 52.6 KB
/
native_syscall_handler.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 crate::{
core::errors::state_errors::StateError,
definitions::{
block_context::BlockContext,
constants::{
CONSTRUCTOR_ENTRY_POINT_SELECTOR, EVENT_MAX_DATA_LENGTH, EVENT_MAX_KEYS_LENGTH,
MAX_N_EMITTED_EVENTS,
},
},
execution::{
execution_entry_point::{ExecutionEntryPoint, ExecutionResult},
CallInfo, CallResult, CallType, OrderedEvent, OrderedL2ToL1Message,
TransactionExecutionContext,
},
hash_utils::calculate_contract_address,
services::api::{
contract_class_errors::ContractClassError, contract_classes::compiled_class::CompiledClass,
},
state::{
contract_storage_state::ContractStorageState,
state_api::{State, StateReader},
ExecutionResourcesManager,
},
syscalls::{
business_logic_syscall_handler::{KECCAK_ROUND_COST, SYSCALL_BASE, SYSCALL_GAS_COST},
syscall_handler_errors::SyscallHandlerError,
},
transaction::{error::TransactionError, Address, ClassHash},
utils::felt_to_hash,
ContractClassCache, EntryPointType, VersionSpecificAccountTxFields,
};
use cairo_native::{
cache::ProgramCache,
starknet::{
BlockInfo, ExecutionInfo, ExecutionInfoV2, ResourceBounds, Secp256k1Point, Secp256r1Point,
StarknetSyscallHandler, SyscallResult, TxInfo, TxV2Info, U256,
},
};
use cairo_vm::Felt252;
use k256::elliptic_curve::sec1::{FromEncodedPoint, ToEncodedPoint};
use sec1::point::Coordinates;
use sha3::digest::generic_array::GenericArray;
use starknet::core::utils::cairo_short_string_to_felt;
use std::{cell::RefCell, iter::once, rc::Rc};
#[derive(Debug)]
pub struct NativeSyscallHandler<'a, 'cache, S, C>
where
S: StateReader,
C: ContractClassCache,
{
pub(crate) starknet_storage_state: ContractStorageState<'a, S, C>,
pub(crate) contract_address: Address,
pub(crate) caller_address: Address,
pub(crate) entry_point_selector: Felt252,
pub(crate) events: Vec<OrderedEvent>,
pub(crate) l2_to_l1_messages: Vec<OrderedL2ToL1Message>,
pub(crate) resources_manager: ExecutionResourcesManager,
pub(crate) tx_execution_context: TransactionExecutionContext,
pub(crate) block_context: BlockContext,
pub(crate) internal_calls: Vec<CallInfo>,
pub(crate) program_cache: Rc<RefCell<ProgramCache<'cache, ClassHash>>>,
}
impl<'a, 'cache, S: StateReader, C: ContractClassCache> NativeSyscallHandler<'a, 'cache, S, C> {
/// Generic code that needs to be run on all syscalls.
fn handle_syscall_request(&mut self, gas: &mut u128, syscall_name: &str) -> SyscallResult<()> {
let required_gas = SYSCALL_GAS_COST
.get(syscall_name)
.map(|&x| x.saturating_sub(SYSCALL_BASE))
.unwrap_or(0);
if *gas < required_gas {
let out_of_gas_felt = Felt252::from_bytes_be_slice("Out of gas".as_bytes());
tracing::debug!("out of gas!: {:?} < {:?}", *gas, required_gas);
return Err(vec![out_of_gas_felt]);
}
*gas = gas.saturating_sub(required_gas);
self.resources_manager
.increment_syscall_counter(syscall_name, 1);
Ok(())
}
}
impl<'a, 'cache, S: StateReader, C: ContractClassCache> StarknetSyscallHandler
for &mut NativeSyscallHandler<'a, 'cache, S, C>
{
fn get_block_hash(
&mut self,
block_number: u64,
gas: &mut u128,
) -> Result<Felt252, Vec<Felt252>> {
tracing::debug!("Called `get_block_hash({block_number})` from Cairo Native");
self.handle_syscall_request(gas, "get_block_hash")?;
let current_block_number = self.block_context.block_info.block_number;
if current_block_number < 10 || block_number > current_block_number - 10 {
let out_of_range_felt =
Felt252::from_bytes_be_slice("Block number out of range".as_bytes());
return Err(vec![out_of_range_felt]);
}
let key: Felt252 = block_number.into();
let block_hash_address = Address(1.into());
match self
.starknet_storage_state
.state
.get_storage_at(&(block_hash_address, key.to_bytes_be()))
{
Ok(value) => Ok(value),
Err(e) => Err(vec![Felt252::from_bytes_be_slice(e.to_string().as_bytes())]),
}
}
fn get_execution_info(
&mut self,
gas: &mut u128,
) -> SyscallResult<cairo_native::starknet::ExecutionInfo> {
tracing::debug!("Called `get_execution_info()` from Cairo Native");
self.handle_syscall_request(gas, "get_execution_info")?;
Ok(ExecutionInfo {
block_info: BlockInfo {
block_number: self.block_context.block_info.block_number,
block_timestamp: self.block_context.block_info.block_timestamp,
sequencer_address: self.block_context.block_info.sequencer_address.0,
},
tx_info: TxInfo {
version: self.tx_execution_context.version,
account_contract_address: self.tx_execution_context.account_contract_address.0,
max_fee: self
.tx_execution_context
.account_tx_fields
.max_fee_for_execution_info(),
signature: self.tx_execution_context.signature.clone(),
transaction_hash: self.tx_execution_context.transaction_hash,
chain_id: self.block_context.starknet_os_config.chain_id,
nonce: self.tx_execution_context.nonce,
},
caller_address: self.caller_address.0,
contract_address: self.contract_address.0,
entry_point_selector: self.entry_point_selector,
})
}
fn deploy(
&mut self,
class_hash: Felt252,
contract_address_salt: Felt252,
calldata: &[Felt252],
deploy_from_zero: bool,
gas: &mut u128,
) -> SyscallResult<(Felt252, Vec<Felt252>)> {
tracing::debug!("Called `deploy({class_hash}, {calldata:?})` from Cairo Native");
self.handle_syscall_request(gas, "deploy")?;
let deployer_address = if deploy_from_zero {
Address::default()
} else {
self.contract_address.clone()
};
let contract_address = Address(
calculate_contract_address(
&contract_address_salt,
&class_hash,
calldata,
deployer_address,
)
.map_err(|_| {
vec![Felt252::from_bytes_be_slice(
b"FAILED_TO_CALCULATE_CONTRACT_ADDRESS",
)]
})?,
);
// Initialize the contract.
let class_hash_bytes: ClassHash = felt_to_hash(&class_hash);
self.starknet_storage_state
.state
.deploy_contract(contract_address.clone(), class_hash_bytes)
.map_err(|_| {
vec![Felt252::from_bytes_be_slice(
b"CONTRACT_ADDRESS_UNAVAILABLE",
)]
})?;
let result = self
.execute_constructor_entry_point(
&contract_address,
class_hash_bytes,
calldata.to_vec(),
*gas,
)
.map_err(|_| {
vec![Felt252::from_bytes_be_slice(
b"CONSTRUCTOR_ENTRYPOINT_FAILURE",
)]
})?;
*gas = gas.saturating_sub(result.gas_consumed);
Ok((
contract_address.0,
result
.retdata
.iter()
.map(|mb| mb.get_int_ref().cloned().unwrap_or_default())
.collect(),
))
}
fn replace_class(&mut self, class_hash: Felt252, gas: &mut u128) -> SyscallResult<()> {
tracing::debug!("Called `replace_class({class_hash})` from Cairo Native");
self.handle_syscall_request(gas, "replace_class")?;
match self
.starknet_storage_state
.state
.set_class_hash_at(self.contract_address.clone(), ClassHash::from(class_hash))
{
Ok(_) => Ok(()),
Err(e) => {
let replace_class_felt = Felt252::from_bytes_be_slice(e.to_string().as_bytes());
Err(vec![replace_class_felt])
}
}
}
fn library_call(
&mut self,
class_hash: Felt252,
function_selector: Felt252,
calldata: &[Felt252],
gas: &mut u128,
) -> SyscallResult<Vec<Felt252>> {
tracing::debug!(
"Called `library_call({class_hash}, {function_selector}, {calldata:?})` from Cairo Native"
);
self.handle_syscall_request(gas, "library_call")?;
let execution_entry_point = ExecutionEntryPoint::new(
self.contract_address.clone(),
calldata.to_vec(),
function_selector,
self.caller_address.clone(),
EntryPointType::External,
Some(CallType::Delegate),
Some(ClassHash::from(class_hash)),
*gas,
);
let ExecutionResult {
call_info,
revert_error,
..
} = execution_entry_point.execute(
self.starknet_storage_state.state,
&self.block_context,
&mut self.resources_manager,
&mut self.tx_execution_context,
false,
self.block_context.invoke_tx_max_n_steps,
Some(self.program_cache.clone()),
)?;
let call_info = call_info.ok_or(SyscallHandlerError::ExecutionError(
revert_error.unwrap_or_else(|| "Execution error".to_string()),
))?;
let remaining_gas = gas.saturating_sub(call_info.gas_consumed);
*gas = remaining_gas;
let failure_flag = call_info.failure_flag;
let retdata = call_info.retdata.clone();
self.starknet_storage_state
.read_values
.extend(call_info.storage_read_values.clone());
self.starknet_storage_state
.accessed_keys
.extend(call_info.accessed_storage_keys.clone());
self.internal_calls.push(call_info);
if failure_flag {
Err(retdata)
} else {
Ok(retdata)
}
}
fn call_contract(
&mut self,
address: Felt252,
entrypoint_selector: Felt252,
calldata: &[Felt252],
gas: &mut u128,
) -> SyscallResult<Vec<Felt252>> {
tracing::debug!(
"Called `call_contract({address}, {entrypoint_selector}, {calldata:?})` from Cairo Native"
);
self.handle_syscall_request(gas, "call_contract")?;
let address = Address(address);
let exec_entry_point = ExecutionEntryPoint::new(
address,
calldata.to_vec(),
entrypoint_selector,
self.contract_address.clone(),
EntryPointType::External,
Some(CallType::Call),
None,
*gas,
);
let ExecutionResult { call_info, .. } = exec_entry_point
.execute(
self.starknet_storage_state.state,
// TODO: This fields dont make much sense in the Cairo Native context,
// they are only dummy values for the `execute` method.
&self.block_context,
&mut self.resources_manager,
&mut self.tx_execution_context,
false,
self.block_context.invoke_tx_max_n_steps,
Some(self.program_cache.clone()),
)
.unwrap();
let call_info = call_info.unwrap();
*gas = gas.saturating_sub(call_info.gas_consumed);
// update syscall handler information
self.starknet_storage_state
.read_values
.extend(call_info.storage_read_values.clone());
self.starknet_storage_state
.accessed_keys
.extend(call_info.accessed_storage_keys.clone());
let retdata = call_info.retdata.clone();
self.internal_calls.push(call_info);
Ok(retdata)
}
fn storage_read(
&mut self,
address_domain: u32,
address: Felt252,
gas: &mut u128,
) -> SyscallResult<Felt252> {
tracing::debug!("Called `storage_read({address_domain}, {address})` from Cairo Native");
self.handle_syscall_request(gas, "storage_read")?;
let value = match self.starknet_storage_state.read(Address(address)) {
Ok(value) => Ok(value),
Err(_e @ StateError::Io(_)) => todo!(),
Err(_) => Ok(Felt252::ZERO),
};
tracing::debug!(
"Called `storage_read({address_domain}, {address}) = {value:?}` from Cairo Native"
);
value
}
fn storage_write(
&mut self,
address_domain: u32,
address: Felt252,
value: Felt252,
gas: &mut u128,
) -> SyscallResult<()> {
tracing::debug!(
"Called `storage_write({address_domain}, {address}, {value})` from Cairo Native"
);
self.handle_syscall_request(gas, "storage_write")?;
self.starknet_storage_state.write(Address(address), value);
Ok(())
}
fn emit_event(
&mut self,
keys: &[Felt252],
data: &[Felt252],
gas: &mut u128,
) -> SyscallResult<()> {
let order = self.tx_execution_context.n_emitted_events;
tracing::debug!("Called `emit_event(KEYS: {keys:?}, DATA: {data:?})` from Cairo Native");
// Check event limits
if order >= MAX_N_EMITTED_EVENTS {
return Err(vec![Felt252::from_bytes_be_slice(
"Max number of emitted events reached".as_bytes(),
)]);
}
if keys.len() > EVENT_MAX_KEYS_LENGTH {
return Err(vec![Felt252::from_bytes_be_slice(
"Event max keys length exceeded".as_bytes(),
)]);
}
if data.len() > EVENT_MAX_DATA_LENGTH {
return Err(vec![Felt252::from_bytes_be_slice(
"Event data keys length exceeded".as_bytes(),
)]);
}
self.handle_syscall_request(gas, "emit_event")?;
self.events
.push(OrderedEvent::new(order, keys.to_vec(), data.to_vec()));
self.tx_execution_context.n_emitted_events += 1;
Ok(())
}
fn send_message_to_l1(
&mut self,
to_address: Felt252,
payload: &[Felt252],
gas: &mut u128,
) -> SyscallResult<()> {
tracing::debug!("Called `send_message_to_l1({to_address}, {payload:?})` from Cairo Native");
self.handle_syscall_request(gas, "send_message_to_l1")?;
let addr = Address(to_address);
self.l2_to_l1_messages.push(OrderedL2ToL1Message::new(
self.tx_execution_context.n_sent_messages,
addr,
payload.to_vec(),
));
// Update messages count.
self.tx_execution_context.n_sent_messages += 1;
Ok(())
}
fn keccak(
&mut self,
input: &[u64],
gas: &mut u128,
) -> SyscallResult<cairo_native::starknet::U256> {
tracing::debug!("Called `keccak({input:?})` from Cairo Native");
self.handle_syscall_request(gas, "keccak")?;
let length = input.len();
if length % 17 != 0 {
let error_msg = b"Invalid keccak input size";
let felt_error = Felt252::from_bytes_be_slice(error_msg);
return Err(vec![felt_error]);
}
let n_chunks = length / 17;
let mut state = [0u64; 25];
for i in 0..n_chunks {
if *gas < KECCAK_ROUND_COST {
let error_msg = b"Syscall out of gas";
let felt_error = Felt252::from_bytes_be_slice(error_msg);
return Err(vec![felt_error]);
}
*gas -= KECCAK_ROUND_COST;
let chunk = &input[i * 17..(i + 1) * 17]; //(request.input_start + i * 17)?;
for (i, val) in chunk.iter().enumerate() {
state[i] ^= val;
}
keccak::f1600(&mut state)
}
// state[0] and state[1] conform the hash_high (u128)
// state[2] and state[3] conform the hash_low (u128)
SyscallResult::Ok(U256 {
lo: state[2] as u128 | ((state[3] as u128) << 64),
hi: state[0] as u128 | ((state[1] as u128) << 64),
})
}
fn get_execution_info_v2(
&mut self,
gas: &mut u128,
) -> Result<ExecutionInfoV2, Vec<cairo_vm::Felt252>> {
tracing::debug!("Called `get_execution_info_v2()` from Cairo Native");
self.handle_syscall_request(gas, "get_execution_info")?;
lazy_static::lazy_static! {
static ref L1_GAS: Felt252 = Felt252::from_hex(
"0x00000000000000000000000000000000000000000000000000004c315f474153"
)
.unwrap();
static ref L2_GAS: Felt252 = Felt252::from_hex(
"0x00000000000000000000000000000000000000000000000000004c325f474153"
)
.unwrap();
}
let mut resource_bounds = vec![];
let mut tip = 0;
let mut paymaster_data = vec![];
let mut nonce_data_availability_mode: u32 = 0;
let mut fee_data_availability_mode: u32 = 0;
let mut account_deployment_data = vec![];
if let VersionSpecificAccountTxFields::Current(fields) =
&self.tx_execution_context.account_tx_fields
{
resource_bounds.push(ResourceBounds {
resource: *L1_GAS,
max_amount: fields.l1_resource_bounds.max_amount,
max_price_per_unit: fields.l1_resource_bounds.max_price_per_unit,
});
if let Some(bounds) = &fields.l2_resource_bounds {
resource_bounds.push(ResourceBounds {
resource: *L2_GAS,
max_amount: bounds.max_amount,
max_price_per_unit: bounds.max_price_per_unit,
});
}
tip = fields.tip as u128;
paymaster_data = fields.paymaster_data.clone();
account_deployment_data = fields.account_deployment_data.clone();
nonce_data_availability_mode = fields.nonce_data_availability_mode.into();
fee_data_availability_mode = fields.fee_data_availability_mode.into();
}
Ok(ExecutionInfoV2 {
block_info: BlockInfo {
block_number: self.block_context.block_info.block_number,
block_timestamp: self.block_context.block_info.block_timestamp,
sequencer_address: self.block_context.block_info.sequencer_address.0,
},
tx_info: TxV2Info {
version: self.tx_execution_context.version,
account_contract_address: self.tx_execution_context.account_contract_address.0,
max_fee: self
.tx_execution_context
.account_tx_fields
.max_fee_for_execution_info(),
signature: self.tx_execution_context.signature.clone(),
transaction_hash: self.tx_execution_context.transaction_hash,
chain_id: self.block_context.starknet_os_config.chain_id,
nonce: self.tx_execution_context.nonce,
resource_bounds,
tip,
paymaster_data,
nonce_data_availability_mode,
fee_data_availability_mode,
account_deployment_data,
},
caller_address: self.caller_address.0,
contract_address: self.contract_address.0,
entry_point_selector: self.entry_point_selector,
})
}
fn secp256k1_new(
&mut self,
x: U256,
y: U256,
_gas: &mut u128,
) -> SyscallResult<Option<Secp256k1Point>> {
// The following unwraps should be unreachable because the iterator we provide has the
// expected number of bytes.
let point = k256::ProjectivePoint::from_encoded_point(
&k256::EncodedPoint::from_affine_coordinates(
&GenericArray::from_exact_iter(
x.hi.to_be_bytes().into_iter().chain(x.lo.to_be_bytes()),
)
.unwrap(),
&GenericArray::from_exact_iter(
y.hi.to_be_bytes().into_iter().chain(y.lo.to_be_bytes()),
)
.unwrap(),
false,
),
);
if bool::from(point.is_some()) {
Ok(Some(Secp256k1Point { x, y }))
} else {
Ok(None)
}
}
fn secp256k1_add(
&mut self,
p0: Secp256k1Point,
p1: Secp256k1Point,
_gas: &mut u128,
) -> SyscallResult<Secp256k1Point> {
// The inner unwraps should be unreachable because the iterator we provide has the expected
// number of bytes. The outer unwraps depend on the felt values, which should be valid since
// they'll be provided by secp256 syscalls.
let p0 = k256::ProjectivePoint::from_encoded_point(
&k256::EncodedPoint::from_affine_coordinates(
&GenericArray::from_exact_iter(
p0.x.hi
.to_be_bytes()
.into_iter()
.chain(p0.x.lo.to_be_bytes()),
)
.unwrap(),
&GenericArray::from_exact_iter(
p0.y.hi
.to_be_bytes()
.into_iter()
.chain(p0.y.lo.to_be_bytes()),
)
.unwrap(),
false,
),
)
.unwrap();
let p1 = k256::ProjectivePoint::from_encoded_point(
&k256::EncodedPoint::from_affine_coordinates(
&GenericArray::from_exact_iter(
p1.x.hi
.to_be_bytes()
.into_iter()
.chain(p1.x.lo.to_be_bytes()),
)
.unwrap(),
&GenericArray::from_exact_iter(
p1.y.hi
.to_be_bytes()
.into_iter()
.chain(p1.y.lo.to_be_bytes()),
)
.unwrap(),
false,
),
)
.unwrap();
let p = p0 + p1;
let p = p.to_encoded_point(false);
let (x, y) = match p.coordinates() {
Coordinates::Uncompressed { x, y } => (x, y),
_ => {
// This should be unreachable because we explicitly asked for the uncompressed
// encoding.
unreachable!()
}
};
// The following two unwraps should be safe because the array always has 32 bytes. The other
// four are definitely safe because the slicing guarantees its length to be the right one.
let x: [u8; 32] = x.as_slice().try_into().unwrap();
let y: [u8; 32] = y.as_slice().try_into().unwrap();
Ok(Secp256k1Point {
x: U256 {
hi: u128::from_be_bytes(x[0..16].try_into().unwrap()),
lo: u128::from_be_bytes(x[16..32].try_into().unwrap()),
},
y: U256 {
hi: u128::from_be_bytes(y[0..16].try_into().unwrap()),
lo: u128::from_be_bytes(y[16..32].try_into().unwrap()),
},
})
}
fn secp256k1_mul(
&mut self,
p: Secp256k1Point,
m: U256,
_gas: &mut u128,
) -> SyscallResult<Secp256k1Point> {
// The inner unwrap should be unreachable because the iterator we provide has the expected
// number of bytes. The outer unwrap depends on the felt values, which should be valid since
// they'll be provided by secp256 syscalls.
let p = k256::ProjectivePoint::from_encoded_point(
&k256::EncodedPoint::from_affine_coordinates(
&GenericArray::from_exact_iter(
p.x.hi.to_be_bytes().into_iter().chain(p.x.lo.to_be_bytes()),
)
.unwrap(),
&GenericArray::from_exact_iter(
p.y.hi.to_be_bytes().into_iter().chain(p.y.lo.to_be_bytes()),
)
.unwrap(),
false,
),
)
.unwrap();
let m: k256::Scalar = k256::elliptic_curve::ScalarPrimitive::from_slice(&{
let mut buf = [0u8; 32];
buf[0..16].copy_from_slice(&m.hi.to_be_bytes());
buf[16..32].copy_from_slice(&m.lo.to_be_bytes());
buf
})
.map_err(|_| {
vec![Felt252::from_bytes_be(
b"\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0invalid scalar",
)]
})?
.into();
let p = p * m;
let p = p.to_encoded_point(false);
let (x, y) = match p.coordinates() {
Coordinates::Uncompressed { x, y } => (x, y),
_ => {
// This should be unreachable because we explicitly asked for the uncompressed
// encoding.
unreachable!()
}
};
// The following two unwraps should be safe because the array always has 32 bytes. The other
// four are definitely safe because the slicing guarantees its length to be the right one.
let x: [u8; 32] = x.as_slice().try_into().unwrap();
let y: [u8; 32] = y.as_slice().try_into().unwrap();
Ok(Secp256k1Point {
x: U256 {
hi: u128::from_be_bytes(x[0..16].try_into().unwrap()),
lo: u128::from_be_bytes(x[16..32].try_into().unwrap()),
},
y: U256 {
hi: u128::from_be_bytes(y[0..16].try_into().unwrap()),
lo: u128::from_be_bytes(y[16..32].try_into().unwrap()),
},
})
}
fn secp256k1_get_point_from_x(
&mut self,
x: U256,
y_parity: bool,
_gas: &mut u128,
) -> SyscallResult<Option<Secp256k1Point>> {
// The inner unwrap should be unreachable because the iterator we provide has the expected
// number of bytes. The outer unwrap depends on the encoding format, which should be valid
// since it's hardcoded..
let point = k256::ProjectivePoint::from_encoded_point(
&k256::EncodedPoint::from_bytes(
k256::CompressedPoint::from_exact_iter(
once(0x02 | y_parity as u8)
.chain(x.hi.to_be_bytes())
.chain(x.lo.to_be_bytes()),
)
.unwrap(),
)
.unwrap(),
);
if bool::from(point.is_some()) {
// This unwrap has already been checked in the `if` expression's condition.
let p = point.unwrap();
let p = p.to_encoded_point(false);
let y = match p.coordinates() {
Coordinates::Uncompressed { y, .. } => y,
_ => {
// This should be unreachable because we explicitly asked for the uncompressed
// encoding.
unreachable!()
}
};
// The following unwrap should be safe because the array always has 32 bytes. The other
// two are definitely safe because the slicing guarantees its length to be the right
// one.
let y: [u8; 32] = y.as_slice().try_into().unwrap();
Ok(Some(Secp256k1Point {
x,
y: U256 {
hi: u128::from_be_bytes(y[0..16].try_into().unwrap()),
lo: u128::from_be_bytes(y[16..32].try_into().unwrap()),
},
}))
} else {
Ok(None)
}
}
fn secp256k1_get_xy(
&mut self,
p: Secp256k1Point,
_gas: &mut u128,
) -> SyscallResult<(U256, U256)> {
Ok((p.x, p.y))
}
fn secp256r1_new(
&mut self,
x: U256,
y: U256,
_gas: &mut u128,
) -> SyscallResult<Option<Secp256r1Point>> {
// The following unwraps should be unreachable because the iterator we provide has the
// expected number of bytes.
let point = p256::ProjectivePoint::from_encoded_point(
&k256::EncodedPoint::from_affine_coordinates(
&GenericArray::from_exact_iter(
x.hi.to_be_bytes().into_iter().chain(x.lo.to_be_bytes()),
)
.unwrap(),
&GenericArray::from_exact_iter(
y.hi.to_be_bytes().into_iter().chain(y.lo.to_be_bytes()),
)
.unwrap(),
false,
),
);
if bool::from(point.is_some()) {
Ok(Some(Secp256r1Point { x, y }))
} else {
Ok(None)
}
}
fn secp256r1_add(
&mut self,
p0: Secp256r1Point,
p1: Secp256r1Point,
_gas: &mut u128,
) -> SyscallResult<Secp256r1Point> {
// The inner unwraps should be unreachable because the iterator we provide has the expected
// number of bytes. The outer unwraps depend on the felt values, which should be valid since
// they'll be provided by secp256 syscalls.
let p0 = p256::ProjectivePoint::from_encoded_point(
&p256::EncodedPoint::from_affine_coordinates(
&GenericArray::from_exact_iter(
p0.x.hi
.to_be_bytes()
.into_iter()
.chain(p0.x.lo.to_be_bytes()),
)
.unwrap(),
&GenericArray::from_exact_iter(
p0.y.hi
.to_be_bytes()
.into_iter()
.chain(p0.y.lo.to_be_bytes()),
)
.unwrap(),
false,
),
)
.unwrap();
let p1 = p256::ProjectivePoint::from_encoded_point(
&p256::EncodedPoint::from_affine_coordinates(
&GenericArray::from_exact_iter(
p1.x.hi
.to_be_bytes()
.into_iter()
.chain(p1.x.lo.to_be_bytes()),
)
.unwrap(),
&GenericArray::from_exact_iter(
p1.y.hi
.to_be_bytes()
.into_iter()
.chain(p1.y.lo.to_be_bytes()),
)
.unwrap(),
false,
),
)
.unwrap();
let p = p0 + p1;
let p = p.to_encoded_point(false);
let (x, y) = match p.coordinates() {
Coordinates::Uncompressed { x, y } => (x, y),
_ => {
// This should be unreachable because we explicitly asked for the uncompressed
// encoding.
unreachable!()
}
};
// The following two unwraps should be safe because the array always has 32 bytes. The other
// four are definitely safe because the slicing guarantees its length to be the right one.
let x: [u8; 32] = x.as_slice().try_into().unwrap();
let y: [u8; 32] = y.as_slice().try_into().unwrap();
Ok(Secp256r1Point {
x: U256 {
hi: u128::from_be_bytes(x[0..16].try_into().unwrap()),
lo: u128::from_be_bytes(x[16..32].try_into().unwrap()),
},
y: U256 {
hi: u128::from_be_bytes(y[0..16].try_into().unwrap()),
lo: u128::from_be_bytes(y[16..32].try_into().unwrap()),
},
})
}
fn secp256r1_mul(
&mut self,
p: Secp256r1Point,
m: U256,
_gas: &mut u128,
) -> SyscallResult<Secp256r1Point> {
// The inner unwrap should be unreachable because the iterator we provide has the expected
// number of bytes. The outer unwrap depends on the felt values, which should be valid since
// they'll be provided by secp256 syscalls.
let p = p256::ProjectivePoint::from_encoded_point(
&p256::EncodedPoint::from_affine_coordinates(
&GenericArray::from_exact_iter(
p.x.hi.to_be_bytes().into_iter().chain(p.x.lo.to_be_bytes()),
)
.unwrap(),
&GenericArray::from_exact_iter(
p.y.hi.to_be_bytes().into_iter().chain(p.y.lo.to_be_bytes()),
)
.unwrap(),
false,
),
)
.unwrap();
let m: p256::Scalar = p256::elliptic_curve::ScalarPrimitive::from_slice(&{
let mut buf = [0u8; 32];
buf[0..16].copy_from_slice(&m.hi.to_be_bytes());
buf[16..32].copy_from_slice(&m.lo.to_be_bytes());
buf
})
.map_err(|_| {
vec![Felt252::from_bytes_be(
b"\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0invalid scalar",
)]
})?
.into();
let p = p * m;
let p = p.to_encoded_point(false);
let (x, y) = match p.coordinates() {
Coordinates::Uncompressed { x, y } => (x, y),
_ => {
// This should be unreachable because we explicitly asked for the uncompressed
// encoding.
unreachable!()
}
};
// The following two unwraps should be safe because the array always has 32 bytes. The other
// four are definitely safe because the slicing guarantees its length to be the right one.
let x: [u8; 32] = x.as_slice().try_into().unwrap();
let y: [u8; 32] = y.as_slice().try_into().unwrap();
Ok(Secp256r1Point {
x: U256 {
hi: u128::from_be_bytes(x[0..16].try_into().unwrap()),
lo: u128::from_be_bytes(x[16..32].try_into().unwrap()),
},
y: U256 {
hi: u128::from_be_bytes(y[0..16].try_into().unwrap()),
lo: u128::from_be_bytes(y[16..32].try_into().unwrap()),
},
})
}
fn secp256r1_get_point_from_x(
&mut self,
x: U256,
y_parity: bool,
_gas: &mut u128,
) -> SyscallResult<Option<Secp256r1Point>> {
let point = p256::ProjectivePoint::from_encoded_point(
&p256::EncodedPoint::from_bytes(
p256::CompressedPoint::from_exact_iter(
once(0x02 | y_parity as u8)
.chain(x.hi.to_be_bytes())
.chain(x.lo.to_be_bytes()),
)
.unwrap(),
)
.unwrap(),
);
if bool::from(point.is_some()) {
let p = point.unwrap();
let p = p.to_encoded_point(false);
let y = match p.coordinates() {
Coordinates::Uncompressed { y, .. } => y,
_ => unreachable!(),
};
let y: [u8; 32] = y.as_slice().try_into().unwrap();
Ok(Some(Secp256r1Point {
x,
y: U256 {
hi: u128::from_be_bytes(y[0..16].try_into().unwrap()),
lo: u128::from_be_bytes(y[16..32].try_into().unwrap()),