-
Notifications
You must be signed in to change notification settings - Fork 66
Expand file tree
/
Copy pathblockifier_versioned_constants.rs
More file actions
1449 lines (1296 loc) · 57 KB
/
blockifier_versioned_constants.rs
File metadata and controls
1449 lines (1296 loc) · 57 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
use std::collections::{BTreeMap, HashMap, HashSet};
use std::io;
use std::path::Path;
use std::sync::Arc;
use apollo_config::dumping::{ser_param, SerializeConfig};
use apollo_config::{ParamPath, ParamPrivacyInput, SerializedParam};
use cairo_vm::types::builtin_name::BuiltinName;
use cairo_vm::vm::runners::cairo_runner::ExecutionResources;
use num_rational::Ratio;
use num_traits::Inv;
use semver::Version;
use serde::de::Error as DeserializationError;
use serde::{Deserialize, Deserializer, Serialize};
use starknet_api::block::{GasPrice, StarknetVersion};
use starknet_api::contract_class::SierraVersion;
use starknet_api::core::{ClassHash, ContractAddress, EntryPointSelector};
use starknet_api::define_versioned_constants;
use starknet_api::executable_transaction::TransactionType;
use starknet_api::execution_resources::{GasAmount, GasVector};
use starknet_api::hash::StarkHash;
use starknet_api::transaction::fields::{hex_to_tip, GasVectorComputationMode, Tip};
use starknet_api::versioned_constants_logic::VersionedConstantsTrait;
use strum::IntoEnumIterator;
use thiserror::Error;
use crate::execution::call_info::{CairoPrimitiveName, OpcodeName};
use crate::execution::common_hints::ExecutionMode;
use crate::execution::execution_utils::poseidon_hash_many_cost;
use crate::execution::syscalls::vm_syscall_utils::{SyscallSelector, SyscallUsageMap};
use crate::fee::resources::StarknetResources;
use crate::transaction::objects::ExecutionResourcesTraits;
use crate::utils::get_gas_cost_from_vm_resources;
#[cfg(test)]
#[path = "versioned_constants_test.rs"]
pub mod test;
define_versioned_constants!(
VersionedConstants,
RawVersionedConstants,
VersionedConstantsError,
StarknetVersion::V0_13_0,
"resources/versioned_constants_diff_regression",
(V0_13_0, "../resources/blockifier_versioned_constants_0_13_0.json"),
(V0_13_1, "../resources/blockifier_versioned_constants_0_13_1.json"),
(V0_13_1_1, "../resources/blockifier_versioned_constants_0_13_1_1.json"),
(V0_13_2, "../resources/blockifier_versioned_constants_0_13_2.json"),
(V0_13_2_1, "../resources/blockifier_versioned_constants_0_13_2_1.json"),
(V0_13_3, "../resources/blockifier_versioned_constants_0_13_3.json"),
(V0_13_4, "../resources/blockifier_versioned_constants_0_13_4.json"),
(V0_13_5, "../resources/blockifier_versioned_constants_0_13_5.json"),
(V0_13_6, "../resources/blockifier_versioned_constants_0_13_6.json"),
(V0_14_0, "../resources/blockifier_versioned_constants_0_14_0.json"),
(V0_14_1, "../resources/blockifier_versioned_constants_0_14_1.json"),
(V0_14_2, "../resources/blockifier_versioned_constants_0_14_2.json"),
);
pub type SyscallGasCostsMap = HashMap<SyscallSelector, RawSyscallGasCost>;
/// Representation of the JSON data of versioned constants. Used as an intermediate struct for
/// serde.
#[derive(Deserialize, Debug, Clone)]
#[serde(deny_unknown_fields)]
pub struct RawVersionedConstants {
// Limits.
pub tx_event_limits: EventLimits,
pub gateway: VersionedConstantsGatewayLimits,
pub invoke_tx_max_n_steps: u32,
pub validate_max_n_steps: u32,
pub max_recursion_depth: usize,
// Costs.
pub deprecated_l2_resource_gas_costs: ArchivalDataGasCosts,
pub archival_data_gas_costs: ArchivalDataGasCosts,
pub allocation_cost: AllocationCost,
pub vm_resource_fee_cost: VmResourceCosts,
// Feature flags.
pub disable_cairo0_redeclaration: bool,
pub enable_stateful_compression: bool,
pub comprehensive_state_diff: bool,
pub block_direct_execute_call: bool,
pub ignore_inner_event_resources: bool,
pub disable_deploy_in_validation_mode: bool,
pub enable_reverts: bool,
pub enable_casm_hash_migration: bool,
pub block_casm_hash_v1_declares: bool,
pub min_sierra_version_for_sierra_gas: SierraVersion,
pub enable_tip: bool,
pub segment_arena_cells: bool,
// OS.
pub os_constants: RawOsConstants,
pub os_resources: RawOsResources,
}
#[cfg_attr(any(test, feature = "testing"), derive(Serialize))]
#[derive(Deserialize, Debug, Clone)]
#[serde(deny_unknown_fields)]
pub struct RawOsConstants {
// Allowed virtual OS program hashes for client-side proving.
pub allowed_virtual_os_program_hashes: Vec<StarkHash>,
// Selectors.
pub constructor_entry_point_selector: EntryPointSelector,
pub default_entry_point_selector: EntryPointSelector,
pub execute_entry_point_selector: EntryPointSelector,
pub transfer_entry_point_selector: EntryPointSelector,
pub validate_declare_entry_point_selector: EntryPointSelector,
pub validate_deploy_entry_point_selector: EntryPointSelector,
pub validate_entry_point_selector: EntryPointSelector,
// Entry point type identifiers (in the OS).
pub entry_point_type_constructor: u8,
pub entry_point_type_external: u8,
pub entry_point_type_l1_handler: u8,
// Validation.
pub validate_rounding_consts: ValidateRoundingConsts,
pub validated: String,
// Execution limits.
pub execute_max_sierra_gas: GasAmount,
pub validate_max_sierra_gas: GasAmount,
// Error strings.
pub error_block_number_out_of_range: String,
pub error_invalid_input_len: String,
pub error_invalid_argument: String,
pub error_out_of_gas: String,
pub error_entry_point_failed: String,
pub error_entry_point_not_found: String,
// Resource bounds names.
pub l1_gas: String,
pub l2_gas: String,
pub l1_data_gas: String,
// Resource bounds indices.
pub l1_gas_index: usize,
pub l1_data_gas_index: usize,
pub l2_gas_index: usize,
// Costs.
pub memory_hole_gas_cost: GasAmount,
pub builtin_gas_costs: BuiltinGasCosts,
pub step_gas_cost: u64,
pub syscall_base_gas_cost: RawStepGasCost,
// Deprecated field for computation of syscall gas costs in old blocks.
// New VCs set this to null.
pub syscall_gas_costs: Option<SyscallGasCostsMap>,
// Initial costs.
pub entry_point_initial_budget: RawStepGasCost,
pub default_initial_gas_cost: RawStepGasCost,
// L1 handler.
pub l1_handler_version: u8,
pub l1_handler_max_amount_bounds: GasVector,
// Miscellaneous.
pub nop_entry_point_offset: i8,
pub os_contract_addresses: OsContractAddresses,
pub sierra_array_len_bound: u64,
pub stored_block_hash_buffer: u8,
// Deprecated contract logic support.
pub v1_bound_accounts_cairo0: Vec<ClassHash>,
pub v1_bound_accounts_cairo1: Vec<ClassHash>,
#[serde(deserialize_with = "hex_to_tip")]
pub v1_bound_accounts_max_tip: Tip,
pub data_gas_accounts: Vec<ClassHash>,
}
#[cfg_attr(any(test, feature = "testing"), derive(Serialize))]
#[derive(Deserialize, Debug, Clone)]
#[serde(deny_unknown_fields)]
pub struct RawStepGasCost {
pub step_gas_cost: GasAmount,
}
pub type ResourceCost = Ratio<u64>;
// TODO(Dori): Delete this ratio-converter function once event keys / data length are no longer 128
// bits (no other usage is expected).
pub fn resource_cost_to_u128_ratio(cost: ResourceCost) -> Ratio<u128> {
Ratio::new((*cost.numer()).into(), (*cost.denom()).into())
}
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, PartialOrd)]
pub struct CompilerVersion(pub Version);
impl Default for CompilerVersion {
fn default() -> Self {
Self(Version::new(0, 0, 0))
}
}
#[derive(Clone, Debug, Default, Deserialize, PartialEq)]
pub struct VmResourceCosts {
pub n_steps: ResourceCost,
#[serde(deserialize_with = "builtin_map_from_string_map")]
pub builtins: HashMap<BuiltinName, ResourceCost>,
}
#[derive(Clone, Debug, Default, Deserialize, PartialEq)]
pub struct AllocationCost {
pub blob_cost: GasVector,
pub gas_cost: GasVector,
}
impl AllocationCost {
pub const ZERO: AllocationCost =
AllocationCost { blob_cost: GasVector::ZERO, gas_cost: GasVector::ZERO };
pub fn get_cost(&self, use_kzg_da: bool) -> &GasVector {
if use_kzg_da { &self.blob_cost } else { &self.gas_cost }
}
}
// TODO(Dori): This (along with the Serialize impl) is implemented in pub(crate) scope in the VM
// (named serde_generic_map_impl); use it if and when it's public.
fn builtin_map_from_string_map<'de, D: Deserializer<'de>>(
d: D,
) -> Result<HashMap<BuiltinName, ResourceCost>, D::Error> {
HashMap::<String, ResourceCost>::deserialize(d)?
.into_iter()
.map(|(k, v)| BuiltinName::from_str_with_suffix(&k).map(|k| (k, v)))
.collect::<Option<HashMap<_, _>>>()
.ok_or(D::Error::custom("Invalid builtin name"))
}
/// Contains constants for the Blockifier that may vary between versions.
/// Additional constants in the JSON file, not used by Blockifier but included for transparency, are
/// automatically ignored during deserialization.
/// Instances of this struct for specific Starknet versions can be selected by using the above enum.
#[cfg_attr(any(test, feature = "testing"), derive(PartialEq))]
#[derive(Clone, Debug, Default)]
pub struct VersionedConstants {
// Limits.
pub tx_event_limits: EventLimits,
pub invoke_tx_max_n_steps: u32,
pub deprecated_l2_resource_gas_costs: ArchivalDataGasCosts,
pub archival_data_gas_costs: ArchivalDataGasCosts,
pub max_recursion_depth: usize,
pub validate_max_n_steps: u32,
pub min_sierra_version_for_sierra_gas: SierraVersion,
// BACKWARD COMPATIBILITY: If true, the segment_arena builtin instance counter will be
// multiplied by 3. This offsets a bug in the old vm where the counter counted the number of
// cells used by instances of the builtin, instead of the number of instances.
pub segment_arena_cells: bool,
// Transactions settings.
pub disable_cairo0_redeclaration: bool,
pub enable_stateful_compression: bool,
pub enable_casm_hash_migration: bool,
pub block_casm_hash_v1_declares: bool,
pub comprehensive_state_diff: bool,
pub block_direct_execute_call: bool,
pub ignore_inner_event_resources: bool,
pub disable_deploy_in_validation_mode: bool,
// Compiler settings.
pub enable_reverts: bool,
// Cairo OS constants.
// Note: if loaded from a json file, there are some assumptions made on its structure.
// See the struct's docstring for more details.
pub os_constants: Arc<OsConstants>,
// Fee related.
pub(crate) vm_resource_fee_cost: Arc<VmResourceCosts>,
pub enable_tip: bool,
// Cost of allocating a storage cell.
pub allocation_cost: AllocationCost,
// Resources.
pub os_resources: Arc<OsResources>,
// Just to make sure the value exists, but don't use the actual values.
#[allow(dead_code)]
gateway: VersionedConstantsGatewayLimits,
}
impl From<RawVersionedConstants> for VersionedConstants {
fn from(raw_vc: RawVersionedConstants) -> Self {
let os_constants = OsConstants::from_raw(&raw_vc.os_constants, &raw_vc.os_resources);
let os_resources = OsResources::from_raw(&raw_vc.os_resources);
Self {
tx_event_limits: raw_vc.tx_event_limits,
invoke_tx_max_n_steps: raw_vc.invoke_tx_max_n_steps,
deprecated_l2_resource_gas_costs: raw_vc.deprecated_l2_resource_gas_costs,
archival_data_gas_costs: raw_vc.archival_data_gas_costs,
max_recursion_depth: raw_vc.max_recursion_depth,
validate_max_n_steps: raw_vc.validate_max_n_steps,
min_sierra_version_for_sierra_gas: raw_vc.min_sierra_version_for_sierra_gas,
segment_arena_cells: raw_vc.segment_arena_cells,
disable_cairo0_redeclaration: raw_vc.disable_cairo0_redeclaration,
enable_stateful_compression: raw_vc.enable_stateful_compression,
comprehensive_state_diff: raw_vc.comprehensive_state_diff,
block_direct_execute_call: raw_vc.block_direct_execute_call,
ignore_inner_event_resources: raw_vc.ignore_inner_event_resources,
disable_deploy_in_validation_mode: raw_vc.disable_deploy_in_validation_mode,
enable_reverts: raw_vc.enable_reverts,
enable_casm_hash_migration: raw_vc.enable_casm_hash_migration,
block_casm_hash_v1_declares: raw_vc.block_casm_hash_v1_declares,
os_constants: Arc::new(os_constants),
vm_resource_fee_cost: Arc::new(raw_vc.vm_resource_fee_cost),
enable_tip: raw_vc.enable_tip,
allocation_cost: raw_vc.allocation_cost,
os_resources: Arc::new(os_resources),
gateway: raw_vc.gateway,
}
}
}
impl VersionedConstants {
pub fn from_path(path: &Path) -> VersionedConstantsResult<Self> {
let raw_vc: RawVersionedConstants = serde_json::from_reader(std::fs::File::open(path)?)?;
Ok(raw_vc.into())
}
/// Converts from L1 gas price to L2 gas price with **upward rounding**, based on the
/// conversion of a Cairo step from Sierra gas to L1 gas.
pub fn convert_l1_to_l2_gas_price_round_up(&self, l1_gas_price: GasPrice) -> GasPrice {
(*(resource_cost_to_u128_ratio(self.sierra_gas_in_l1_gas_amount()) * l1_gas_price.0)
.ceil()
.numer())
.into()
}
/// Converts L1 gas amount to Sierra (L2) gas amount with **upward rounding**.
pub fn l1_gas_to_sierra_gas_amount_round_up(&self, l1_gas_amount: GasAmount) -> GasAmount {
// The amount ratio is the inverse of the price ratio.
(*(self.sierra_gas_in_l1_gas_amount().inv() * l1_gas_amount.0).ceil().numer()).into()
}
/// Converts Sierra (L2) gas amount to L1 gas amount with **upward rounding**.
pub fn sierra_gas_to_l1_gas_amount_round_up(&self, l2_gas_amount: GasAmount) -> GasAmount {
(*(self.sierra_gas_in_l1_gas_amount() * l2_gas_amount.0).ceil().numer()).into()
}
/// Returns the equivalent L1 gas amount of one unit of Sierra gas.
/// The conversion is based on the pricing of a single Cairo step.
fn sierra_gas_in_l1_gas_amount(&self) -> ResourceCost {
Ratio::new(1, self.os_constants.gas_costs.base.step_gas_cost)
* self.vm_resource_fee_cost().n_steps
}
/// Default initial gas amount when L2 gas is not provided.
pub fn initial_gas_no_user_l2_bound(&self) -> GasAmount {
(self
.os_constants
.execute_max_sierra_gas
.checked_add(self.os_constants.validate_max_sierra_gas))
.expect("The default initial gas cost should be less than the maximum gas amount.")
}
/// Returns the maximum gas amount according to the given mode.
pub fn sierra_gas_limit(&self, mode: &ExecutionMode) -> GasAmount {
match mode {
ExecutionMode::Validate => self.os_constants.validate_max_sierra_gas,
ExecutionMode::Execute => self.os_constants.execute_max_sierra_gas,
}
}
/// Returns the default initial gas for VM mode transactions.
pub fn infinite_gas_for_vm_mode(&self) -> u64 {
self.os_constants.gas_costs.base.default_initial_gas_cost
}
pub fn vm_resource_fee_cost(&self) -> &VmResourceCosts {
&self.vm_resource_fee_cost
}
pub fn os_resources_for_tx_type(
&self,
tx_type: &TransactionType,
calldata_length: usize,
) -> ExecutionResources {
self.os_resources.resources_for_tx_type(tx_type, calldata_length)
}
pub fn os_kzg_da_resources(&self, data_segment_length: usize) -> ExecutionResources {
self.os_resources.os_kzg_da_resources(data_segment_length)
}
pub fn get_additional_os_tx_resources(
&self,
tx_type: TransactionType,
starknet_resources: &StarknetResources,
use_kzg_da: bool,
) -> ExecutionResources {
self.os_resources.get_additional_os_tx_resources(
tx_type,
starknet_resources.archival_data.calldata_length,
starknet_resources.state.get_onchain_data_segment_length(),
use_kzg_da,
)
}
pub fn get_additional_os_syscall_resources(
&self,
syscalls_usage: &SyscallUsageMap,
) -> ExecutionResources {
self.os_resources.get_additional_os_syscall_resources(syscalls_usage)
}
pub fn get_validate_block_number_rounding(&self) -> u64 {
self.os_constants.validate_rounding_consts.validate_block_number_rounding
}
pub fn get_validate_timestamp_rounding(&self) -> u64 {
self.os_constants.validate_rounding_consts.validate_timestamp_rounding
}
#[cfg(any(feature = "testing", test))]
pub fn create_for_account_testing() -> Self {
let step_cost = ResourceCost::from_integer(1);
let vm_resource_fee_cost = Arc::new(VmResourceCosts {
n_steps: step_cost,
builtins: HashMap::from([
(BuiltinName::pedersen, ResourceCost::from_integer(1)),
(BuiltinName::range_check, ResourceCost::from_integer(1)),
(BuiltinName::ecdsa, ResourceCost::from_integer(1)),
(BuiltinName::bitwise, ResourceCost::from_integer(1)),
(BuiltinName::poseidon, ResourceCost::from_integer(1)),
(BuiltinName::output, ResourceCost::from_integer(1)),
(BuiltinName::ec_op, ResourceCost::from_integer(1)),
(BuiltinName::range_check96, ResourceCost::from_integer(1)),
(BuiltinName::add_mod, ResourceCost::from_integer(1)),
(BuiltinName::mul_mod, ResourceCost::from_integer(1)),
]),
});
// Maintain the ratio between L1 gas price and L2 gas price.
let latest = Self::create_for_testing();
let latest_step_cost = latest.vm_resource_fee_cost.n_steps;
let mut archival_data_gas_costs = latest.archival_data_gas_costs;
archival_data_gas_costs.gas_per_code_byte *= latest_step_cost / step_cost;
archival_data_gas_costs.gas_per_data_felt *= latest_step_cost / step_cost;
Self { vm_resource_fee_cost, archival_data_gas_costs, ..latest }
}
// TODO(Arni): Consider replacing each call to this function with `latest_with_overrides`, and
// squashing the functions together.
/// Returns the latest versioned constants, applying the given overrides.
pub fn get_versioned_constants(
versioned_constants_overrides: Option<VersionedConstantsOverrides>,
) -> Self {
let latest_constants = Self::latest_constants().clone();
match versioned_constants_overrides {
None => latest_constants,
Some(VersionedConstantsOverrides {
validate_max_n_steps,
max_recursion_depth,
invoke_tx_max_n_steps,
max_n_events,
}) => {
let tx_event_limits = EventLimits {
max_n_emitted_events: max_n_events,
..latest_constants.tx_event_limits
};
Self {
validate_max_n_steps,
max_recursion_depth,
invoke_tx_max_n_steps,
tx_event_limits,
..latest_constants
}
}
}
}
pub fn get_archival_data_gas_costs(
&self,
mode: &GasVectorComputationMode,
) -> &ArchivalDataGasCosts {
match mode {
GasVectorComputationMode::All => &self.archival_data_gas_costs,
GasVectorComputationMode::NoL2Gas => &self.deprecated_l2_resource_gas_costs,
}
}
}
#[derive(Clone, Debug, Default, Deserialize, Eq, PartialEq)]
pub struct ArchivalDataGasCosts {
// TODO(barak, 18/03/2024): Once we start charging per byte change to milligas_per_data_byte,
// divide the value by 32 in the JSON file.
pub gas_per_data_felt: ResourceCost,
pub event_key_factor: ResourceCost,
// TODO(avi, 15/04/2024): This constant was changed to 32 milligas in the JSON file, but the
// actual number we wanted is 1/32 gas per byte. Change the value to 1/32 in the next version
// where rational numbers are supported.
pub gas_per_code_byte: ResourceCost,
// TODO(AvivG): Update value for 0.14.2 once the value is finalized.
// Note: This field is only present in archival_data_gas_costs (for V3+ transactions with
// proof facts). It's not present in deprecated_l2_resource_gas_costs (for V0-V2 transactions).
#[serde(default)]
pub gas_per_proof: ResourceCost,
}
pub struct CairoNativeStackConfig {
pub gas_to_stack_ratio: Ratio<u64>,
pub max_stack_size: u64,
pub min_stack_red_zone: u64,
pub buffer_size: u64,
}
impl CairoNativeStackConfig {
/// Rounds up the given size to the nearest multiple of MB.
pub fn round_up_to_mb(size: u64) -> u64 {
const MB: u64 = 1024 * 1024;
size.div_ceil(MB) * MB
}
/// Returns the stack size sufficient for running Cairo Native.
/// Rounds up to the nearest multiple of MB.
pub fn get_stack_size_red_zone(&self, remaining_gas: u64) -> u64 {
let stack_size_based_on_gas =
(self.gas_to_stack_ratio * Ratio::new(remaining_gas, 1)).to_integer();
// Ensure the computed stack size is within the allowed range.
CairoNativeStackConfig::round_up_to_mb(
stack_size_based_on_gas.clamp(self.min_stack_red_zone, self.max_stack_size),
)
}
pub fn get_target_stack_size(&self, red_zone: u64) -> u64 {
// Stack size should be a multiple of page size, since `stacker::grow` works with this unit.
CairoNativeStackConfig::round_up_to_mb(red_zone + self.buffer_size)
}
}
#[derive(Deserialize, Debug, Clone, Default, PartialEq)]
#[serde(deny_unknown_fields)]
pub struct VersionedConstantsGatewayLimits {
pub max_calldata_length: usize,
pub max_contract_bytecode_size: usize,
pub max_proof_size: usize,
}
#[derive(Clone, Copy, Debug, Default, Deserialize, Eq, PartialEq)]
pub struct EventLimits {
pub max_data_length: usize,
pub max_keys_length: usize,
pub max_n_emitted_events: usize,
}
#[derive(Error, Debug)]
pub enum RawOsResourcesError {
#[error("os_resources.execute_syscalls are missing a selector: {0:?}")]
MissingSelector(SyscallSelector),
#[error("os_resources.execute_tx_inner is missing transaction_type: {0:?}")]
MissingTxType(TransactionType),
#[error("unknown os resource {0}")]
UnknownResource(String),
}
#[cfg_attr(any(test, feature = "testing"), derive(PartialEq))]
#[derive(Clone, Debug, Default)]
pub struct OsResources {
// Mapping from every syscall to its execution resources in the OS (e.g., amount of Cairo
// steps).
// TODO(Arni, 14/6/2023): Update `GetBlockHash` values.
// TODO(ilya): Consider moving the resources of a keccak round to a seperate dict.
execute_syscalls: HashMap<SyscallSelector, ResourcesParams>,
// Mapping from every transaction to its extra execution resources in the OS,
// i.e., resources that don't count during the execution itself.
// For each transaction the OS uses a constant amount of VM resources, and an
// additional variable amount that depends on the calldata length.
execute_txs_inner: HashMap<TransactionType, ResourcesParams>,
// Resources needed for the OS to compute the KZG commitment info, as a factor of the data
// segment length. Does not include poseidon_hash_many cost.
pub compute_os_kzg_commitment_info: ExecutionResources,
}
fn validate_all_tx_types<V>(
tx_type_map: &HashMap<TransactionType, V>,
) -> Result<(), RawOsResourcesError> {
for tx_type in TransactionType::iter() {
if !tx_type_map.contains_key(&tx_type) {
return Err(RawOsResourcesError::MissingTxType(tx_type));
}
}
Ok(())
}
fn validate_all_selectors<V>(
selector_map: &HashMap<SyscallSelector, V>,
) -> Result<(), RawOsResourcesError> {
for syscall_handler in SyscallSelector::iter() {
if !selector_map.contains_key(&syscall_handler) {
return Err(RawOsResourcesError::MissingSelector(syscall_handler));
}
}
Ok(())
}
fn validate_builtins_known<'a, B: Iterator<Item = &'a BuiltinName>>(
builtin_names: B,
) -> Result<(), RawOsResourcesError> {
let known_builtin_names: HashSet<&str> = [
BuiltinName::output,
BuiltinName::pedersen,
BuiltinName::range_check,
BuiltinName::ecdsa,
BuiltinName::bitwise,
BuiltinName::ec_op,
BuiltinName::keccak,
BuiltinName::poseidon,
BuiltinName::segment_arena,
]
.iter()
.map(|builtin| builtin.to_str_with_suffix())
.collect();
for builtin_name in builtin_names {
if !(known_builtin_names.contains(builtin_name.to_str_with_suffix())) {
return Err(RawOsResourcesError::UnknownResource(builtin_name.to_string()));
}
}
Ok(())
}
impl OsResources {
fn from_raw(raw_os_resources: &RawOsResources) -> Self {
Self {
execute_syscalls: raw_os_resources
.execute_syscalls
.iter()
.map(|(k, v)| (*k, ResourcesParams::from(v)))
.collect(),
execute_txs_inner: raw_os_resources
.execute_txs_inner
.iter()
.map(|(k, v)| (*k, ResourcesParams::from(v)))
.collect(),
compute_os_kzg_commitment_info: raw_os_resources.compute_os_kzg_commitment_info.clone(),
}
}
/// Calculates the additional resources needed for the OS to run the given transaction;
/// i.e., the resources of the Starknet OS function `execute_transactions_inner`.
/// Also adds the resources needed for the fee transfer execution, performed in the end·
/// of every transaction.
fn get_additional_os_tx_resources(
&self,
tx_type: TransactionType,
calldata_length: usize,
data_segment_length: usize,
use_kzg_da: bool,
) -> ExecutionResources {
let mut os_additional_vm_resources = self.resources_for_tx_type(&tx_type, calldata_length);
if use_kzg_da {
os_additional_vm_resources += &self.os_kzg_da_resources(data_segment_length);
}
os_additional_vm_resources
}
/// Calculates the additional resources needed for the OS to run the given syscalls;
/// i.e., the resources of the Starknet OS function `execute_syscalls`.
fn get_additional_os_syscall_resources(
&self,
syscalls_usage: &SyscallUsageMap,
) -> ExecutionResources {
let mut os_additional_resources = ExecutionResources::default();
for (syscall_selector, syscall_usage) in syscalls_usage {
if syscall_selector == &SyscallSelector::Keccak {
let keccak_base_resources =
self.execute_syscalls.get(syscall_selector).unwrap_or_else(|| {
panic!("OS resources of syscall '{syscall_selector:?}' are unknown.")
});
os_additional_resources += &keccak_base_resources.constant;
}
let syscall_selector = if syscall_selector == &SyscallSelector::Keccak {
&SyscallSelector::KeccakRound
} else {
syscall_selector
};
let syscall_resources =
self.execute_syscalls.get(syscall_selector).unwrap_or_else(|| {
panic!("OS resources of syscall '{syscall_selector:?}' are unknown.")
});
let calldata_factor = CallDataFactor::from(&syscall_resources.calldata_factor);
os_additional_resources += &(&(&syscall_resources.constant * syscall_usage.call_count)
+ &calldata_factor.calculate_resources(syscall_usage.linear_factor));
}
os_additional_resources
}
fn resources_params_for_tx_type(&self, tx_type: &TransactionType) -> &ResourcesParams {
self.execute_txs_inner
.get(tx_type)
.unwrap_or_else(|| panic!("should contain transaction type '{tx_type:?}'."))
}
fn resources_for_tx_type(
&self,
tx_type: &TransactionType,
calldata_length: usize,
) -> ExecutionResources {
let resources_vector = self.resources_params_for_tx_type(tx_type);
&resources_vector.constant
+ &CallDataFactor::from(&resources_vector.calldata_factor)
.calculate_resources(calldata_length)
}
fn os_kzg_da_resources(&self, data_segment_length: usize) -> ExecutionResources {
// BACKWARD COMPATIBILITY: we set compute_os_kzg_commitment_info to empty in older versions
// where this was not yet computed.
let empty_resources = ExecutionResources::default();
if self.compute_os_kzg_commitment_info == empty_resources {
return empty_resources;
}
&(&self.compute_os_kzg_commitment_info * data_segment_length)
+ &poseidon_hash_many_cost(data_segment_length)
}
}
#[derive(Deserialize, Debug, Clone)]
#[serde(deny_unknown_fields)]
// Serde trick for adding validations via a customr deserializer, without forgoing the derive.
// See: https://github.com/serde-rs/serde/issues/1220.
#[serde(remote = "Self")]
pub struct RawOsResources {
pub execute_syscalls: HashMap<SyscallSelector, VariableResourceParams>,
pub execute_txs_inner: HashMap<TransactionType, VariableResourceParams>,
pub compute_os_kzg_commitment_info: ExecutionResources,
}
impl RawOsResources {
pub fn validate(&self) -> Result<(), RawOsResourcesError> {
validate_all_tx_types(&self.execute_txs_inner)?;
validate_all_selectors(&self.execute_syscalls)?;
// Extract all `ExecutionResources` objects from the resource params.
fn resources_params_exec_resources(
resources_params: &VariableResourceParams,
) -> Vec<&ExecutionResources> {
match resources_params {
VariableResourceParams::Constant(constant) => vec![constant],
VariableResourceParams::WithFactor(ResourcesParams {
constant,
calldata_factor:
VariableCallDataFactor::Scaled(CallDataFactor { resources, .. }),
})
| VariableResourceParams::WithFactor(ResourcesParams {
constant,
calldata_factor: VariableCallDataFactor::Unscaled(resources),
}) => {
vec![constant, resources]
}
}
}
let execution_resources = self
.execute_txs_inner
.values()
.flat_map(resources_params_exec_resources)
.chain(self.execute_syscalls.values().flat_map(resources_params_exec_resources))
.chain(std::iter::once(&self.compute_os_kzg_commitment_info));
let builtin_names =
execution_resources.flat_map(|resources| resources.builtin_instance_counter.keys());
validate_builtins_known(builtin_names)?;
Ok(())
}
}
impl<'de> Deserialize<'de> for RawOsResources {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
let raw_os_resources = Self::deserialize(deserializer)?;
raw_os_resources
.validate()
.map_err(|error| DeserializationError::custom(format!("ValidationError: {error}")))?;
Ok(raw_os_resources)
}
}
#[cfg_attr(any(test, feature = "testing"), derive(Serialize))]
#[derive(Deserialize, Debug, Clone, PartialEq)]
#[serde(untagged, deny_unknown_fields)]
pub enum RawSyscallGasCost {
Flat(u64),
Structured(RawStructuredDeprecatedSyscallGasCost),
}
#[cfg_attr(any(test, feature = "testing"), derive(Serialize))]
#[derive(Deserialize, Debug, Clone, PartialEq)]
#[serde(deny_unknown_fields)]
pub struct RawStructuredDeprecatedSyscallGasCost {
#[serde(default)]
pub step_gas_cost: u64,
#[serde(default)]
pub range_check: u64,
#[serde(default)]
pub bitwise: u64,
#[serde(default)]
pub syscall_base_gas_cost: u64,
#[serde(default)]
pub memory_hole_gas_cost: u64,
}
#[derive(PartialEq, Debug, Clone, Copy, Serialize, Default)]
pub struct SyscallGasCost {
base: u64,
linear_factor: u64,
}
impl SyscallGasCost {
pub fn new_from_base_cost(base: u64) -> Self {
Self { base, linear_factor: 0 }
}
pub fn get_syscall_cost(&self, linear_length: u64) -> u64 {
self.base + self.linear_factor * linear_length
}
pub fn base_syscall_cost(&self) -> u64 {
assert!(self.linear_factor == 0, "The syscall has a linear factor cost to be considered.");
self.base
}
pub fn linear_syscall_cost(&self) -> u64 {
self.linear_factor
}
}
#[cfg_attr(any(test, feature = "testing"), derive(Clone))]
#[derive(Debug, Default, PartialEq)]
pub struct SyscallGasCosts {
pub call_contract: SyscallGasCost,
pub deploy: SyscallGasCost,
pub get_block_hash: SyscallGasCost,
pub get_execution_info: SyscallGasCost,
pub library_call: SyscallGasCost,
pub replace_class: SyscallGasCost,
pub storage_read: SyscallGasCost,
pub storage_write: SyscallGasCost,
pub get_class_hash_at: SyscallGasCost,
pub emit_event: SyscallGasCost,
pub send_message_to_l1: SyscallGasCost,
pub secp256k1_add: SyscallGasCost,
pub secp256k1_get_point_from_x: SyscallGasCost,
pub secp256k1_get_xy: SyscallGasCost,
pub secp256k1_mul: SyscallGasCost,
pub secp256k1_new: SyscallGasCost,
pub secp256r1_add: SyscallGasCost,
pub secp256r1_get_point_from_x: SyscallGasCost,
pub secp256r1_get_xy: SyscallGasCost,
pub secp256r1_mul: SyscallGasCost,
pub secp256r1_new: SyscallGasCost,
pub keccak: SyscallGasCost,
pub keccak_round: SyscallGasCost,
pub meta_tx_v0: SyscallGasCost,
pub sha256_process_block: SyscallGasCost,
}
impl SyscallGasCosts {
pub fn get_syscall_gas_cost(
&self,
selector: &SyscallSelector,
) -> Result<SyscallGasCost, GasCostsError> {
let gas_cost = match *selector {
SyscallSelector::CallContract => self.call_contract,
SyscallSelector::Deploy => self.deploy,
SyscallSelector::EmitEvent => self.emit_event,
SyscallSelector::GetBlockHash => self.get_block_hash,
SyscallSelector::GetExecutionInfo => self.get_execution_info,
SyscallSelector::GetClassHashAt => self.get_class_hash_at,
SyscallSelector::KeccakRound => self.keccak_round,
SyscallSelector::Keccak => self.keccak,
SyscallSelector::Sha256ProcessBlock => self.sha256_process_block,
SyscallSelector::LibraryCall => self.library_call,
SyscallSelector::MetaTxV0 => self.meta_tx_v0,
SyscallSelector::ReplaceClass => self.replace_class,
SyscallSelector::Secp256k1Add => self.secp256k1_add,
SyscallSelector::Secp256k1GetPointFromX => self.secp256k1_get_point_from_x,
SyscallSelector::Secp256k1GetXy => self.secp256k1_get_xy,
SyscallSelector::Secp256k1Mul => self.secp256k1_mul,
SyscallSelector::Secp256k1New => self.secp256k1_new,
SyscallSelector::Secp256r1Add => self.secp256r1_add,
SyscallSelector::Secp256r1GetPointFromX => self.secp256r1_get_point_from_x,
SyscallSelector::Secp256r1GetXy => self.secp256r1_get_xy,
SyscallSelector::Secp256r1Mul => self.secp256r1_mul,
SyscallSelector::Secp256r1New => self.secp256r1_new,
SyscallSelector::SendMessageToL1 => self.send_message_to_l1,
SyscallSelector::StorageRead => self.storage_read,
SyscallSelector::StorageWrite => self.storage_write,
SyscallSelector::DelegateCall
| SyscallSelector::DelegateL1Handler
| SyscallSelector::GetBlockNumber
| SyscallSelector::GetBlockTimestamp
| SyscallSelector::GetCallerAddress
| SyscallSelector::GetContractAddress
| SyscallSelector::GetTxInfo
| SyscallSelector::GetSequencerAddress
| SyscallSelector::GetTxSignature
| SyscallSelector::LibraryCallL1Handler => {
return Err(GasCostsError::DeprecatedSyscall { selector: *selector });
}
};
Ok(gas_cost)
}
}
#[cfg_attr(any(test, feature = "testing"), derive(Clone, Copy))]
#[derive(Debug, Default, PartialEq)]
pub struct BaseGasCosts {
pub step_gas_cost: u64,
pub memory_hole_gas_cost: u64,
// An estimation of the initial gas for a transaction to run with. This solution is
// temporary and this value will be deduced from the transaction's fields.
pub default_initial_gas_cost: u64,
// Compiler gas costs.
pub entry_point_initial_budget: u64,
pub syscall_base_gas_cost: u64,
}
#[derive(Clone, Copy, Debug, Default, Deserialize, PartialEq, Serialize)]
// TODO(AvivG): Consider renaming to CairoPrimitiveGasCosts to match with its usage in the bouncer.
pub struct BuiltinGasCosts {
// Range check has a hard-coded cost higher than its proof percentage to avoid the overhead of
// retrieving its price from the table.
pub range_check: u64,
pub range_check96: u64,
// Priced builtins.
pub keccak: u64,
pub pedersen: u64,
pub bitwise: u64,
pub ecop: u64,
pub poseidon: u64,
pub add_mod: u64,
pub mul_mod: u64,
pub ecdsa: u64,
// Blake opcode gas cost.
pub blake: u64,
}
impl BuiltinGasCosts {
// TODO(AvivG): Make this function private and use get_cairo_primitive_gas_cost instead.
pub fn get_builtin_gas_cost(&self, builtin: &BuiltinName) -> Result<u64, GasCostsError> {
let gas_cost = match *builtin {
BuiltinName::range_check => self.range_check,
BuiltinName::pedersen => self.pedersen,
BuiltinName::bitwise => self.bitwise,
BuiltinName::ec_op => self.ecop,
BuiltinName::keccak => self.keccak,
BuiltinName::poseidon => self.poseidon,
BuiltinName::range_check96 => self.range_check96,
BuiltinName::add_mod => self.add_mod,
BuiltinName::mul_mod => self.mul_mod,
BuiltinName::ecdsa => self.ecdsa,
BuiltinName::segment_arena => return Err(GasCostsError::VirtualBuiltin),
BuiltinName::output => {
return Err(GasCostsError::UnsupportedBuiltinInCairo1 { builtin: *builtin });
}
};
Ok(gas_cost)
}
pub fn get_opcode_gas_cost(&self, opcode: &OpcodeName) -> u64 {
match opcode {
OpcodeName::Blake => self.blake,
}
}
/// Returns the gas cost for any Cairo primitive (builtin or opcode).
pub fn get_cairo_primitive_gas_cost(
&self,
primitive: &CairoPrimitiveName,
) -> Result<u64, GasCostsError> {
match primitive {
CairoPrimitiveName::Builtin(builtin) => self.get_builtin_gas_cost(builtin),
CairoPrimitiveName::Opcode(opcode) => Ok(self.get_opcode_gas_cost(opcode)),
}
}
}
/// Gas cost constants. For more documentation see in core/os/constants.cairo.
#[cfg_attr(any(test, feature = "testing"), derive(Clone))]
#[derive(Debug, Default, PartialEq)]
pub struct GasCosts {
pub base: BaseGasCosts,
pub builtins: BuiltinGasCosts,
pub syscalls: SyscallGasCosts,
}
impl GasCosts {
fn from_raw(os_constants: &RawOsConstants, os_resources: &RawOsResources) -> Self {