forked from solana-labs/solana
-
Notifications
You must be signed in to change notification settings - Fork 238
/
mod.rs
4978 lines (4496 loc) · 172 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
pub use self::{
cpi::{SyscallInvokeSignedC, SyscallInvokeSignedRust},
logging::{
SyscallLog, SyscallLogBpfComputeUnits, SyscallLogData, SyscallLogPubkey, SyscallLogU64,
},
mem_ops::{SyscallMemcmp, SyscallMemcpy, SyscallMemmove, SyscallMemset},
sysvar::{
SyscallGetClockSysvar, SyscallGetEpochRewardsSysvar, SyscallGetEpochScheduleSysvar,
SyscallGetFeesSysvar, SyscallGetLastRestartSlotSysvar, SyscallGetRentSysvar,
SyscallGetSysvar,
},
};
#[allow(deprecated)]
use {
solana_bn254::prelude::{
alt_bn128_addition, alt_bn128_multiplication, alt_bn128_pairing, AltBn128Error,
ALT_BN128_ADDITION_OUTPUT_LEN, ALT_BN128_MULTIPLICATION_OUTPUT_LEN,
ALT_BN128_PAIRING_ELEMENT_LEN, ALT_BN128_PAIRING_OUTPUT_LEN,
},
solana_compute_budget::compute_budget::ComputeBudget,
solana_feature_set::{
self as feature_set, abort_on_invalid_curve, blake3_syscall_enabled,
bpf_account_data_direct_mapping, curve25519_syscall_enabled,
disable_deploy_of_alloc_free_syscall, disable_fees_sysvar, disable_sbpf_v1_execution,
enable_alt_bn128_compression_syscall, enable_alt_bn128_syscall, enable_big_mod_exp_syscall,
enable_get_epoch_stake_syscall, enable_partitioned_epoch_reward, enable_poseidon_syscall,
get_sysvar_syscall_enabled, last_restart_slot_sysvar,
partitioned_epoch_rewards_superfeature, reenable_sbpf_v1_execution,
remaining_compute_units_syscall_enabled, FeatureSet,
},
solana_log_collector::{ic_logger_msg, ic_msg},
solana_poseidon as poseidon,
solana_program_memory::is_nonoverlapping,
solana_program_runtime::{invoke_context::InvokeContext, stable_log},
solana_rbpf::{
declare_builtin_function,
memory_region::{AccessType, MemoryMapping},
program::{BuiltinFunction, BuiltinProgram, FunctionRegistry},
vm::Config,
},
solana_sdk::{
account_info::AccountInfo,
big_mod_exp::{big_mod_exp, BigModExpParams},
blake3, bpf_loader, bpf_loader_deprecated, bpf_loader_upgradeable,
entrypoint::{BPF_ALIGN_OF_U128, MAX_PERMITTED_DATA_INCREASE, SUCCESS},
hash::{Hash, Hasher},
instruction::{AccountMeta, InstructionError, ProcessedSiblingInstruction},
keccak, native_loader,
precompiles::is_precompile,
program::MAX_RETURN_DATA,
pubkey::{Pubkey, PubkeyError, MAX_SEEDS, MAX_SEED_LEN, PUBKEY_BYTES},
secp256k1_recover::{
Secp256k1RecoverError, SECP256K1_PUBLIC_KEY_LENGTH, SECP256K1_SIGNATURE_LENGTH,
},
sysvar::{Sysvar, SysvarId},
transaction_context::{IndexOfAccount, InstructionAccount},
},
solana_timings::ExecuteTimings,
solana_type_overrides::sync::Arc,
std::{
alloc::Layout,
mem::{align_of, size_of},
slice::from_raw_parts_mut,
str::{from_utf8, Utf8Error},
},
thiserror::Error as ThisError,
};
mod cpi;
mod logging;
mod mem_ops;
mod sysvar;
/// Maximum signers
pub const MAX_SIGNERS: usize = 16;
/// Error definitions
#[derive(Debug, ThisError, PartialEq, Eq)]
pub enum SyscallError {
#[error("{0}: {1:?}")]
InvalidString(Utf8Error, Vec<u8>),
#[error("SBF program panicked")]
Abort,
#[error("SBF program Panicked in {0} at {1}:{2}")]
Panic(String, u64, u64),
#[error("Cannot borrow invoke context")]
InvokeContextBorrowFailed,
#[error("Malformed signer seed: {0}: {1:?}")]
MalformedSignerSeed(Utf8Error, Vec<u8>),
#[error("Could not create program address with signer seeds: {0}")]
BadSeeds(PubkeyError),
#[error("Program {0} not supported by inner instructions")]
ProgramNotSupported(Pubkey),
#[error("Unaligned pointer")]
UnalignedPointer,
#[error("Too many signers")]
TooManySigners,
#[error("Instruction passed to inner instruction is too large ({0} > {1})")]
InstructionTooLarge(usize, usize),
#[error("Too many accounts passed to inner instruction")]
TooManyAccounts,
#[error("Overlapping copy")]
CopyOverlapping,
#[error("Return data too large ({0} > {1})")]
ReturnDataTooLarge(u64, u64),
#[error("Hashing too many sequences")]
TooManySlices,
#[error("InvalidLength")]
InvalidLength,
#[error("Invoked an instruction with data that is too large ({data_len} > {max_data_len})")]
MaxInstructionDataLenExceeded { data_len: u64, max_data_len: u64 },
#[error("Invoked an instruction with too many accounts ({num_accounts} > {max_accounts})")]
MaxInstructionAccountsExceeded {
num_accounts: u64,
max_accounts: u64,
},
#[error("Invoked an instruction with too many account info's ({num_account_infos} > {max_account_infos})")]
MaxInstructionAccountInfosExceeded {
num_account_infos: u64,
max_account_infos: u64,
},
#[error("InvalidAttribute")]
InvalidAttribute,
#[error("Invalid pointer")]
InvalidPointer,
#[error("Arithmetic overflow")]
ArithmeticOverflow,
}
type Error = Box<dyn std::error::Error>;
pub trait HasherImpl {
const NAME: &'static str;
type Output: AsRef<[u8]>;
fn create_hasher() -> Self;
fn hash(&mut self, val: &[u8]);
fn result(self) -> Self::Output;
fn get_base_cost(compute_budget: &ComputeBudget) -> u64;
fn get_byte_cost(compute_budget: &ComputeBudget) -> u64;
fn get_max_slices(compute_budget: &ComputeBudget) -> u64;
}
pub struct Sha256Hasher(Hasher);
pub struct Blake3Hasher(blake3::Hasher);
pub struct Keccak256Hasher(keccak::Hasher);
impl HasherImpl for Sha256Hasher {
const NAME: &'static str = "Sha256";
type Output = Hash;
fn create_hasher() -> Self {
Sha256Hasher(Hasher::default())
}
fn hash(&mut self, val: &[u8]) {
self.0.hash(val);
}
fn result(self) -> Self::Output {
self.0.result()
}
fn get_base_cost(compute_budget: &ComputeBudget) -> u64 {
compute_budget.sha256_base_cost
}
fn get_byte_cost(compute_budget: &ComputeBudget) -> u64 {
compute_budget.sha256_byte_cost
}
fn get_max_slices(compute_budget: &ComputeBudget) -> u64 {
compute_budget.sha256_max_slices
}
}
impl HasherImpl for Blake3Hasher {
const NAME: &'static str = "Blake3";
type Output = blake3::Hash;
fn create_hasher() -> Self {
Blake3Hasher(blake3::Hasher::default())
}
fn hash(&mut self, val: &[u8]) {
self.0.hash(val);
}
fn result(self) -> Self::Output {
self.0.result()
}
fn get_base_cost(compute_budget: &ComputeBudget) -> u64 {
compute_budget.sha256_base_cost
}
fn get_byte_cost(compute_budget: &ComputeBudget) -> u64 {
compute_budget.sha256_byte_cost
}
fn get_max_slices(compute_budget: &ComputeBudget) -> u64 {
compute_budget.sha256_max_slices
}
}
impl HasherImpl for Keccak256Hasher {
const NAME: &'static str = "Keccak256";
type Output = keccak::Hash;
fn create_hasher() -> Self {
Keccak256Hasher(keccak::Hasher::default())
}
fn hash(&mut self, val: &[u8]) {
self.0.hash(val);
}
fn result(self) -> Self::Output {
self.0.result()
}
fn get_base_cost(compute_budget: &ComputeBudget) -> u64 {
compute_budget.sha256_base_cost
}
fn get_byte_cost(compute_budget: &ComputeBudget) -> u64 {
compute_budget.sha256_byte_cost
}
fn get_max_slices(compute_budget: &ComputeBudget) -> u64 {
compute_budget.sha256_max_slices
}
}
fn consume_compute_meter(invoke_context: &InvokeContext, amount: u64) -> Result<(), Error> {
invoke_context.consume_checked(amount)?;
Ok(())
}
macro_rules! register_feature_gated_function {
($result:expr, $is_feature_active:expr, $name:expr, $call:expr $(,)?) => {
if $is_feature_active {
$result.register_function_hashed($name, $call)
} else {
Ok(0)
}
};
}
pub fn morph_into_deployment_environment_v1(
from: Arc<BuiltinProgram<InvokeContext>>,
) -> Result<BuiltinProgram<InvokeContext>, Error> {
let mut config = *from.get_config();
config.reject_broken_elfs = true;
let mut result = FunctionRegistry::<BuiltinFunction<InvokeContext>>::default();
for (key, (name, value)) in from.get_function_registry().iter() {
// Deployment of programs with sol_alloc_free is disabled. So do not register the syscall.
if name != *b"sol_alloc_free_" {
result.register_function(key, name, value)?;
}
}
Ok(BuiltinProgram::new_loader(config, result))
}
pub fn create_program_runtime_environment_v1<'a>(
feature_set: &FeatureSet,
compute_budget: &ComputeBudget,
reject_deployment_of_broken_elfs: bool,
debugging_features: bool,
) -> Result<BuiltinProgram<InvokeContext<'a>>, Error> {
let enable_alt_bn128_syscall = feature_set.is_active(&enable_alt_bn128_syscall::id());
let enable_alt_bn128_compression_syscall =
feature_set.is_active(&enable_alt_bn128_compression_syscall::id());
let enable_big_mod_exp_syscall = feature_set.is_active(&enable_big_mod_exp_syscall::id());
let blake3_syscall_enabled = feature_set.is_active(&blake3_syscall_enabled::id());
let curve25519_syscall_enabled = feature_set.is_active(&curve25519_syscall_enabled::id());
let disable_fees_sysvar = feature_set.is_active(&disable_fees_sysvar::id());
let epoch_rewards_syscall_enabled = feature_set
.is_active(&enable_partitioned_epoch_reward::id())
|| feature_set.is_active(&partitioned_epoch_rewards_superfeature::id());
let disable_deploy_of_alloc_free_syscall = reject_deployment_of_broken_elfs
&& feature_set.is_active(&disable_deploy_of_alloc_free_syscall::id());
let last_restart_slot_syscall_enabled = feature_set.is_active(&last_restart_slot_sysvar::id());
let enable_poseidon_syscall = feature_set.is_active(&enable_poseidon_syscall::id());
let remaining_compute_units_syscall_enabled =
feature_set.is_active(&remaining_compute_units_syscall_enabled::id());
let get_sysvar_syscall_enabled = feature_set.is_active(&get_sysvar_syscall_enabled::id());
let enable_get_epoch_stake_syscall =
feature_set.is_active(&enable_get_epoch_stake_syscall::id());
let config = Config {
max_call_depth: compute_budget.max_call_depth,
stack_frame_size: compute_budget.stack_frame_size,
enable_address_translation: true,
enable_stack_frame_gaps: !feature_set.is_active(&bpf_account_data_direct_mapping::id()),
instruction_meter_checkpoint_distance: 10000,
enable_instruction_meter: true,
enable_instruction_tracing: debugging_features,
enable_symbol_and_section_labels: debugging_features,
reject_broken_elfs: reject_deployment_of_broken_elfs,
noop_instruction_rate: 256,
sanitize_user_provided_values: true,
external_internal_function_hash_collision: true,
reject_callx_r10: true,
enable_sbpf_v1: !feature_set.is_active(&disable_sbpf_v1_execution::id())
|| feature_set.is_active(&reenable_sbpf_v1_execution::id()),
enable_sbpf_v2: false,
optimize_rodata: false,
aligned_memory_mapping: !feature_set.is_active(&bpf_account_data_direct_mapping::id()),
// Warning, do not use `Config::default()` so that configuration here is explicit.
};
let mut result = FunctionRegistry::<BuiltinFunction<InvokeContext>>::default();
// Abort
result.register_function_hashed(*b"abort", SyscallAbort::vm)?;
// Panic
result.register_function_hashed(*b"sol_panic_", SyscallPanic::vm)?;
// Logging
result.register_function_hashed(*b"sol_log_", SyscallLog::vm)?;
result.register_function_hashed(*b"sol_log_64_", SyscallLogU64::vm)?;
result.register_function_hashed(*b"sol_log_compute_units_", SyscallLogBpfComputeUnits::vm)?;
result.register_function_hashed(*b"sol_log_pubkey", SyscallLogPubkey::vm)?;
// Program defined addresses (PDA)
result.register_function_hashed(
*b"sol_create_program_address",
SyscallCreateProgramAddress::vm,
)?;
result.register_function_hashed(
*b"sol_try_find_program_address",
SyscallTryFindProgramAddress::vm,
)?;
// Sha256
result.register_function_hashed(*b"sol_sha256", SyscallHash::vm::<Sha256Hasher>)?;
// Keccak256
result.register_function_hashed(*b"sol_keccak256", SyscallHash::vm::<Keccak256Hasher>)?;
// Secp256k1 Recover
result.register_function_hashed(*b"sol_secp256k1_recover", SyscallSecp256k1Recover::vm)?;
// Blake3
register_feature_gated_function!(
result,
blake3_syscall_enabled,
*b"sol_blake3",
SyscallHash::vm::<Blake3Hasher>,
)?;
// Elliptic Curve Operations
register_feature_gated_function!(
result,
curve25519_syscall_enabled,
*b"sol_curve_validate_point",
SyscallCurvePointValidation::vm,
)?;
register_feature_gated_function!(
result,
curve25519_syscall_enabled,
*b"sol_curve_group_op",
SyscallCurveGroupOps::vm,
)?;
register_feature_gated_function!(
result,
curve25519_syscall_enabled,
*b"sol_curve_multiscalar_mul",
SyscallCurveMultiscalarMultiplication::vm,
)?;
// Sysvars
result.register_function_hashed(*b"sol_get_clock_sysvar", SyscallGetClockSysvar::vm)?;
result.register_function_hashed(
*b"sol_get_epoch_schedule_sysvar",
SyscallGetEpochScheduleSysvar::vm,
)?;
register_feature_gated_function!(
result,
!disable_fees_sysvar,
*b"sol_get_fees_sysvar",
SyscallGetFeesSysvar::vm,
)?;
result.register_function_hashed(*b"sol_get_rent_sysvar", SyscallGetRentSysvar::vm)?;
register_feature_gated_function!(
result,
last_restart_slot_syscall_enabled,
*b"sol_get_last_restart_slot",
SyscallGetLastRestartSlotSysvar::vm,
)?;
register_feature_gated_function!(
result,
epoch_rewards_syscall_enabled,
*b"sol_get_epoch_rewards_sysvar",
SyscallGetEpochRewardsSysvar::vm,
)?;
// Memory ops
result.register_function_hashed(*b"sol_memcpy_", SyscallMemcpy::vm)?;
result.register_function_hashed(*b"sol_memmove_", SyscallMemmove::vm)?;
result.register_function_hashed(*b"sol_memcmp_", SyscallMemcmp::vm)?;
result.register_function_hashed(*b"sol_memset_", SyscallMemset::vm)?;
// Processed sibling instructions
result.register_function_hashed(
*b"sol_get_processed_sibling_instruction",
SyscallGetProcessedSiblingInstruction::vm,
)?;
// Stack height
result.register_function_hashed(*b"sol_get_stack_height", SyscallGetStackHeight::vm)?;
// Return data
result.register_function_hashed(*b"sol_set_return_data", SyscallSetReturnData::vm)?;
result.register_function_hashed(*b"sol_get_return_data", SyscallGetReturnData::vm)?;
// Cross-program invocation
result.register_function_hashed(*b"sol_invoke_signed_c", SyscallInvokeSignedC::vm)?;
result.register_function_hashed(*b"sol_invoke_signed_rust", SyscallInvokeSignedRust::vm)?;
// Memory allocator
register_feature_gated_function!(
result,
!disable_deploy_of_alloc_free_syscall,
*b"sol_alloc_free_",
SyscallAllocFree::vm,
)?;
// Alt_bn128
register_feature_gated_function!(
result,
enable_alt_bn128_syscall,
*b"sol_alt_bn128_group_op",
SyscallAltBn128::vm,
)?;
// Big_mod_exp
register_feature_gated_function!(
result,
enable_big_mod_exp_syscall,
*b"sol_big_mod_exp",
SyscallBigModExp::vm,
)?;
// Poseidon
register_feature_gated_function!(
result,
enable_poseidon_syscall,
*b"sol_poseidon",
SyscallPoseidon::vm,
)?;
// Accessing remaining compute units
register_feature_gated_function!(
result,
remaining_compute_units_syscall_enabled,
*b"sol_remaining_compute_units",
SyscallRemainingComputeUnits::vm
)?;
// Alt_bn128_compression
register_feature_gated_function!(
result,
enable_alt_bn128_compression_syscall,
*b"sol_alt_bn128_compression",
SyscallAltBn128Compression::vm,
)?;
// Sysvar getter
register_feature_gated_function!(
result,
get_sysvar_syscall_enabled,
*b"sol_get_sysvar",
SyscallGetSysvar::vm,
)?;
// Get Epoch Stake
register_feature_gated_function!(
result,
enable_get_epoch_stake_syscall,
*b"sol_get_epoch_stake",
SyscallGetEpochStake::vm,
)?;
// Log data
result.register_function_hashed(*b"sol_log_data", SyscallLogData::vm)?;
Ok(BuiltinProgram::new_loader(config, result))
}
pub fn create_program_runtime_environment_v2<'a>(
compute_budget: &ComputeBudget,
debugging_features: bool,
) -> BuiltinProgram<InvokeContext<'a>> {
let config = Config {
max_call_depth: compute_budget.max_call_depth,
stack_frame_size: compute_budget.stack_frame_size,
enable_address_translation: true, // To be deactivated once we have BTF inference and verification
enable_stack_frame_gaps: false,
instruction_meter_checkpoint_distance: 10000,
enable_instruction_meter: true,
enable_instruction_tracing: debugging_features,
enable_symbol_and_section_labels: debugging_features,
reject_broken_elfs: true,
noop_instruction_rate: 256,
sanitize_user_provided_values: true,
external_internal_function_hash_collision: true,
reject_callx_r10: true,
enable_sbpf_v1: false,
enable_sbpf_v2: true,
optimize_rodata: true,
aligned_memory_mapping: true,
// Warning, do not use `Config::default()` so that configuration here is explicit.
};
BuiltinProgram::new_loader(config, FunctionRegistry::default())
}
fn address_is_aligned<T>(address: u64) -> bool {
(address as *mut T as usize)
.checked_rem(align_of::<T>())
.map(|rem| rem == 0)
.expect("T to be non-zero aligned")
}
fn translate(
memory_mapping: &MemoryMapping,
access_type: AccessType,
vm_addr: u64,
len: u64,
) -> Result<u64, Error> {
memory_mapping
.map(access_type, vm_addr, len)
.map_err(|err| err.into())
.into()
}
fn translate_type_inner<'a, T>(
memory_mapping: &MemoryMapping,
access_type: AccessType,
vm_addr: u64,
check_aligned: bool,
) -> Result<&'a mut T, Error> {
let host_addr = translate(memory_mapping, access_type, vm_addr, size_of::<T>() as u64)?;
if !check_aligned {
Ok(unsafe { std::mem::transmute::<u64, &mut T>(host_addr) })
} else if !address_is_aligned::<T>(host_addr) {
Err(SyscallError::UnalignedPointer.into())
} else {
Ok(unsafe { &mut *(host_addr as *mut T) })
}
}
fn translate_type_mut<'a, T>(
memory_mapping: &MemoryMapping,
vm_addr: u64,
check_aligned: bool,
) -> Result<&'a mut T, Error> {
translate_type_inner::<T>(memory_mapping, AccessType::Store, vm_addr, check_aligned)
}
fn translate_type<'a, T>(
memory_mapping: &MemoryMapping,
vm_addr: u64,
check_aligned: bool,
) -> Result<&'a T, Error> {
translate_type_inner::<T>(memory_mapping, AccessType::Load, vm_addr, check_aligned)
.map(|value| &*value)
}
fn translate_slice_inner<'a, T>(
memory_mapping: &MemoryMapping,
access_type: AccessType,
vm_addr: u64,
len: u64,
check_aligned: bool,
) -> Result<&'a mut [T], Error> {
if len == 0 {
return Ok(&mut []);
}
let total_size = len.saturating_mul(size_of::<T>() as u64);
if isize::try_from(total_size).is_err() {
return Err(SyscallError::InvalidLength.into());
}
let host_addr = translate(memory_mapping, access_type, vm_addr, total_size)?;
if check_aligned && !address_is_aligned::<T>(host_addr) {
return Err(SyscallError::UnalignedPointer.into());
}
Ok(unsafe { from_raw_parts_mut(host_addr as *mut T, len as usize) })
}
fn translate_slice_mut<'a, T>(
memory_mapping: &MemoryMapping,
vm_addr: u64,
len: u64,
check_aligned: bool,
) -> Result<&'a mut [T], Error> {
translate_slice_inner::<T>(
memory_mapping,
AccessType::Store,
vm_addr,
len,
check_aligned,
)
}
fn translate_slice<'a, T>(
memory_mapping: &MemoryMapping,
vm_addr: u64,
len: u64,
check_aligned: bool,
) -> Result<&'a [T], Error> {
translate_slice_inner::<T>(
memory_mapping,
AccessType::Load,
vm_addr,
len,
check_aligned,
)
.map(|value| &*value)
}
/// Take a virtual pointer to a string (points to SBF VM memory space), translate it
/// pass it to a user-defined work function
fn translate_string_and_do(
memory_mapping: &MemoryMapping,
addr: u64,
len: u64,
check_aligned: bool,
work: &mut dyn FnMut(&str) -> Result<u64, Error>,
) -> Result<u64, Error> {
let buf = translate_slice::<u8>(memory_mapping, addr, len, check_aligned)?;
match from_utf8(buf) {
Ok(message) => work(message),
Err(err) => Err(SyscallError::InvalidString(err, buf.to_vec()).into()),
}
}
declare_builtin_function!(
/// Abort syscall functions, called when the SBF program calls `abort()`
/// LLVM will insert calls to `abort()` if it detects an untenable situation,
/// `abort()` is not intended to be called explicitly by the program.
/// Causes the SBF program to be halted immediately
SyscallAbort,
fn rust(
_invoke_context: &mut InvokeContext,
_arg1: u64,
_arg2: u64,
_arg3: u64,
_arg4: u64,
_arg5: u64,
_memory_mapping: &mut MemoryMapping,
) -> Result<u64, Error> {
Err(SyscallError::Abort.into())
}
);
declare_builtin_function!(
/// Panic syscall function, called when the SBF program calls 'sol_panic_()`
/// Causes the SBF program to be halted immediately
SyscallPanic,
fn rust(
invoke_context: &mut InvokeContext,
file: u64,
len: u64,
line: u64,
column: u64,
_arg5: u64,
memory_mapping: &mut MemoryMapping,
) -> Result<u64, Error> {
consume_compute_meter(invoke_context, len)?;
translate_string_and_do(
memory_mapping,
file,
len,
invoke_context.get_check_aligned(),
&mut |string: &str| Err(SyscallError::Panic(string.to_string(), line, column).into()),
)
}
);
declare_builtin_function!(
/// Dynamic memory allocation syscall called when the SBF program calls
/// `sol_alloc_free_()`. The allocator is expected to allocate/free
/// from/to a given chunk of memory and enforce size restrictions. The
/// memory chunk is given to the allocator during allocator creation and
/// information about that memory (start address and size) is passed
/// to the VM to use for enforcement.
SyscallAllocFree,
fn rust(
invoke_context: &mut InvokeContext,
size: u64,
free_addr: u64,
_arg3: u64,
_arg4: u64,
_arg5: u64,
_memory_mapping: &mut MemoryMapping,
) -> Result<u64, Error> {
let align = if invoke_context.get_check_aligned() {
BPF_ALIGN_OF_U128
} else {
align_of::<u8>()
};
let Ok(layout) = Layout::from_size_align(size as usize, align) else {
return Ok(0);
};
let allocator = &mut invoke_context.get_syscall_context_mut()?.allocator;
if free_addr == 0 {
match allocator.alloc(layout) {
Ok(addr) => Ok(addr),
Err(_) => Ok(0),
}
} else {
// Unimplemented
Ok(0)
}
}
);
fn translate_and_check_program_address_inputs<'a>(
seeds_addr: u64,
seeds_len: u64,
program_id_addr: u64,
memory_mapping: &mut MemoryMapping,
check_aligned: bool,
) -> Result<(Vec<&'a [u8]>, &'a Pubkey), Error> {
let untranslated_seeds =
translate_slice::<&[u8]>(memory_mapping, seeds_addr, seeds_len, check_aligned)?;
if untranslated_seeds.len() > MAX_SEEDS {
return Err(SyscallError::BadSeeds(PubkeyError::MaxSeedLengthExceeded).into());
}
let seeds = untranslated_seeds
.iter()
.map(|untranslated_seed| {
if untranslated_seed.len() > MAX_SEED_LEN {
return Err(SyscallError::BadSeeds(PubkeyError::MaxSeedLengthExceeded).into());
}
translate_slice::<u8>(
memory_mapping,
untranslated_seed.as_ptr() as *const _ as u64,
untranslated_seed.len() as u64,
check_aligned,
)
})
.collect::<Result<Vec<_>, Error>>()?;
let program_id = translate_type::<Pubkey>(memory_mapping, program_id_addr, check_aligned)?;
Ok((seeds, program_id))
}
declare_builtin_function!(
/// Create a program address
SyscallCreateProgramAddress,
fn rust(
invoke_context: &mut InvokeContext,
seeds_addr: u64,
seeds_len: u64,
program_id_addr: u64,
address_addr: u64,
_arg5: u64,
memory_mapping: &mut MemoryMapping,
) -> Result<u64, Error> {
let cost = invoke_context
.get_compute_budget()
.create_program_address_units;
consume_compute_meter(invoke_context, cost)?;
let (seeds, program_id) = translate_and_check_program_address_inputs(
seeds_addr,
seeds_len,
program_id_addr,
memory_mapping,
invoke_context.get_check_aligned(),
)?;
let Ok(new_address) = Pubkey::create_program_address(&seeds, program_id) else {
return Ok(1);
};
let address = translate_slice_mut::<u8>(
memory_mapping,
address_addr,
32,
invoke_context.get_check_aligned(),
)?;
address.copy_from_slice(new_address.as_ref());
Ok(0)
}
);
declare_builtin_function!(
/// Create a program address
SyscallTryFindProgramAddress,
fn rust(
invoke_context: &mut InvokeContext,
seeds_addr: u64,
seeds_len: u64,
program_id_addr: u64,
address_addr: u64,
bump_seed_addr: u64,
memory_mapping: &mut MemoryMapping,
) -> Result<u64, Error> {
let cost = invoke_context
.get_compute_budget()
.create_program_address_units;
consume_compute_meter(invoke_context, cost)?;
let (seeds, program_id) = translate_and_check_program_address_inputs(
seeds_addr,
seeds_len,
program_id_addr,
memory_mapping,
invoke_context.get_check_aligned(),
)?;
let mut bump_seed = [u8::MAX];
for _ in 0..u8::MAX {
{
let mut seeds_with_bump = seeds.to_vec();
seeds_with_bump.push(&bump_seed);
if let Ok(new_address) =
Pubkey::create_program_address(&seeds_with_bump, program_id)
{
let bump_seed_ref = translate_type_mut::<u8>(
memory_mapping,
bump_seed_addr,
invoke_context.get_check_aligned(),
)?;
let address = translate_slice_mut::<u8>(
memory_mapping,
address_addr,
std::mem::size_of::<Pubkey>() as u64,
invoke_context.get_check_aligned(),
)?;
if !is_nonoverlapping(
bump_seed_ref as *const _ as usize,
std::mem::size_of_val(bump_seed_ref),
address.as_ptr() as usize,
std::mem::size_of::<Pubkey>(),
) {
return Err(SyscallError::CopyOverlapping.into());
}
*bump_seed_ref = bump_seed[0];
address.copy_from_slice(new_address.as_ref());
return Ok(0);
}
}
bump_seed[0] = bump_seed[0].saturating_sub(1);
consume_compute_meter(invoke_context, cost)?;
}
Ok(1)
}
);
declare_builtin_function!(
/// secp256k1_recover
SyscallSecp256k1Recover,
fn rust(
invoke_context: &mut InvokeContext,
hash_addr: u64,
recovery_id_val: u64,
signature_addr: u64,
result_addr: u64,
_arg5: u64,
memory_mapping: &mut MemoryMapping,
) -> Result<u64, Error> {
let cost = invoke_context.get_compute_budget().secp256k1_recover_cost;
consume_compute_meter(invoke_context, cost)?;
let hash = translate_slice::<u8>(
memory_mapping,
hash_addr,
keccak::HASH_BYTES as u64,
invoke_context.get_check_aligned(),
)?;
let signature = translate_slice::<u8>(
memory_mapping,
signature_addr,
SECP256K1_SIGNATURE_LENGTH as u64,
invoke_context.get_check_aligned(),
)?;
let secp256k1_recover_result = translate_slice_mut::<u8>(
memory_mapping,
result_addr,
SECP256K1_PUBLIC_KEY_LENGTH as u64,
invoke_context.get_check_aligned(),
)?;
let Ok(message) = libsecp256k1::Message::parse_slice(hash) else {
return Ok(Secp256k1RecoverError::InvalidHash.into());
};
let Ok(adjusted_recover_id_val) = recovery_id_val.try_into() else {
return Ok(Secp256k1RecoverError::InvalidRecoveryId.into());
};
let Ok(recovery_id) = libsecp256k1::RecoveryId::parse(adjusted_recover_id_val) else {
return Ok(Secp256k1RecoverError::InvalidRecoveryId.into());
};
let Ok(signature) = libsecp256k1::Signature::parse_standard_slice(signature) else {
return Ok(Secp256k1RecoverError::InvalidSignature.into());
};
let public_key = match libsecp256k1::recover(&message, &signature, &recovery_id) {
Ok(key) => key.serialize(),
Err(_) => {
return Ok(Secp256k1RecoverError::InvalidSignature.into());
}
};
secp256k1_recover_result.copy_from_slice(&public_key[1..65]);
Ok(SUCCESS)
}
);
declare_builtin_function!(
// Elliptic Curve Point Validation
//
// Currently, only curve25519 Edwards and Ristretto representations are supported
SyscallCurvePointValidation,
fn rust(
invoke_context: &mut InvokeContext,
curve_id: u64,
point_addr: u64,
_arg3: u64,
_arg4: u64,
_arg5: u64,
memory_mapping: &mut MemoryMapping,
) -> Result<u64, Error> {
use solana_curve25519::{curve_syscall_traits::*, edwards, ristretto};
match curve_id {
CURVE25519_EDWARDS => {
let cost = invoke_context
.get_compute_budget()
.curve25519_edwards_validate_point_cost;
consume_compute_meter(invoke_context, cost)?;
let point = translate_type::<edwards::PodEdwardsPoint>(
memory_mapping,
point_addr,
invoke_context.get_check_aligned(),
)?;
if edwards::validate_edwards(point) {
Ok(0)
} else {
Ok(1)
}
}
CURVE25519_RISTRETTO => {
let cost = invoke_context
.get_compute_budget()
.curve25519_ristretto_validate_point_cost;
consume_compute_meter(invoke_context, cost)?;
let point = translate_type::<ristretto::PodRistrettoPoint>(
memory_mapping,
point_addr,
invoke_context.get_check_aligned(),
)?;
if ristretto::validate_ristretto(point) {
Ok(0)
} else {
Ok(1)
}
}
_ => {
if invoke_context
.get_feature_set()
.is_active(&abort_on_invalid_curve::id())
{
Err(SyscallError::InvalidAttribute.into())
} else {
Ok(1)
}
}
}
}
);
declare_builtin_function!(
// Elliptic Curve Group Operations
//
// Currently, only curve25519 Edwards and Ristretto representations are supported
SyscallCurveGroupOps,
fn rust(
invoke_context: &mut InvokeContext,
curve_id: u64,
group_op: u64,
left_input_addr: u64,
right_input_addr: u64,
result_point_addr: u64,
memory_mapping: &mut MemoryMapping,
) -> Result<u64, Error> {
use solana_curve25519::{curve_syscall_traits::*, edwards, ristretto, scalar};
match curve_id {
CURVE25519_EDWARDS => match group_op {
ADD => {
let cost = invoke_context
.get_compute_budget()
.curve25519_edwards_add_cost;
consume_compute_meter(invoke_context, cost)?;