iota_protocol_config/
lib.rs

1// Copyright (c) Mysten Labs, Inc.
2// Modifications Copyright (c) 2024 IOTA Stiftung
3// SPDX-License-Identifier: Apache-2.0
4
5use std::{
6    cell::RefCell,
7    cmp::min,
8    sync::atomic::{AtomicBool, Ordering},
9};
10
11use clap::*;
12use iota_protocol_config_macros::{
13    ProtocolConfigAccessors, ProtocolConfigFeatureFlagsGetters, ProtocolConfigOverride,
14};
15use move_vm_config::verifier::VerifierConfig;
16use serde::{Deserialize, Serialize};
17use serde_with::skip_serializing_none;
18use tracing::{info, warn};
19
20/// The minimum and maximum protocol versions supported by this build.
21const MIN_PROTOCOL_VERSION: u64 = 1;
22pub const MAX_PROTOCOL_VERSION: u64 = 16;
23
24// Record history of protocol version allocations here:
25//
26// Version 1:  Original version.
27// Version 2:  Don't redistribute slashed staking rewards, fix computation of
28//             SystemEpochInfoEventV1.
29// Version 3:  Set the `relocate_event_module` to be true so that the module
30//             that is associated as the "sending module" for an event is
31//             relocated by linkage.
32//             Add `Clock` based unlock to `Timelock` objects.
33// Version 4:  Introduce the `max_type_to_layout_nodes` config that sets the
34//             maximal nodes which are allowed when converting to a type layout.
35// Version 5:  Introduce fixed protocol-defined base fee, IotaSystemStateV2 and
36//             SystemEpochInfoEventV2.
37//             Disallow adding new modules in `deps-only` packages.
38//             Improve gas/wall time efficiency of some Move stdlib vector
39//             functions.
40//             Add new gas model version to update charging of functions.
41//             Enable proper conversion of certain type argument errors in the
42//             execution layer.
43// Version 6:  Bound size of values created in the adapter.
44// Version 7:  Improve handling of stake withdrawal from candidate validators.
45// Version 8:  Variants as type nodes.
46//             Enable smart ancestor selection for testnet.
47//             Enable probing for accepted rounds in round prober for testnet.
48//             Switch to distributed vote scoring in consensus in testnet.
49//             Enable zstd compression for consensus tonic network in testnet.
50//             Enable consensus garbage collection for testnet
51//             Enable the new consensus commit rule for testnet.
52//             Enable min_free_execution_slot for the shared object congestion
53//             tracker in devnet.
54// Version 9:  Disable smart ancestor selection for the testnet.
55//             Enable zstd compression for consensus tonic network in mainnet.
56//             Enable passkey auth in multisig for devnet.
57//             Remove the iota-bridge from the framework.
58// Version 10: Enable min_free_execution_slot for the shared object congestion
59//             tracker in all networks.
60//             Increase the committee size to 80 on all networks.
61//             Enable round prober in consensus for mainnet.
62//             Enable probing for accepted rounds in round prober for mainnet.
63//             Switch to distributed vote scoring in consensus for mainnet.
64//             Enable the new consensus commit rule for mainnet.
65//             Enable consensus garbage collection for mainnet with GC depth set
66//             to 60 rounds.
67//             Enable batching in synchronizer for testnet
68//             Enable the gas price feedback mechanism in devnet.
69//             Enable Identifier input validation.
70//             Removes unnecessary child object mutations
71//             Add additional signature checks
72//             Add additional linkage checks
73// Version 11: Framework fix regarding candidate validator commission rate.
74// Version 12: Enable the gas price feedback mechanism in all networks.
75//             Enable the normalization of PTB arguments.
76// Version 13: Introduce logic to allow the committee to be selected from a set
77//             of eligible active validators.
78//             Enable processing and tracking AuthorityCapabilitiesV1 from
79//             non-committee validators in the devnet.
80// Version 14: Switches the consensus protocol to Starfish in devnet.
81//             Enable median-based commit timestamp calculation in consensus,
82//             and enforce checkpoint timestamp monotonicity for testnet.
83//             Enable batched block sync for mainnet.
84//             Enable selecting committee only from active validators that
85//             support the next epoch's version and issued valid
86//             AuthorityCapabilities notification in testnet.
87// Version 15: Enable shared object transaction bursts of 10 times average load
88//             on devnet.
89// Version 16: Enable selecting committee only from active validators that
90//             support the next epoch's version and issued valid
91//             AuthorityCapabilities notification.
92#[derive(Copy, Clone, Debug, Hash, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)]
93pub struct ProtocolVersion(u64);
94
95impl ProtocolVersion {
96    // The minimum and maximum protocol version supported by this binary.
97    // Counterintuitively, this constant may change over time as support for old
98    // protocol versions is removed from the source. This ensures that when a
99    // new network (such as a testnet) is created, its genesis committee will
100    // use a protocol version that is actually supported by the binary.
101    pub const MIN: Self = Self(MIN_PROTOCOL_VERSION);
102
103    pub const MAX: Self = Self(MAX_PROTOCOL_VERSION);
104
105    #[cfg(not(msim))]
106    const MAX_ALLOWED: Self = Self::MAX;
107
108    // We create one additional "fake" version in simulator builds so that we can
109    // test upgrades.
110    #[cfg(msim)]
111    pub const MAX_ALLOWED: Self = Self(MAX_PROTOCOL_VERSION + 1);
112
113    pub fn new(v: u64) -> Self {
114        Self(v)
115    }
116
117    pub const fn as_u64(&self) -> u64 {
118        self.0
119    }
120
121    // For serde deserialization - we don't define a Default impl because there
122    // isn't a single universally appropriate default value.
123    pub fn max() -> Self {
124        Self::MAX
125    }
126}
127
128impl From<u64> for ProtocolVersion {
129    fn from(v: u64) -> Self {
130        Self::new(v)
131    }
132}
133
134impl std::ops::Sub<u64> for ProtocolVersion {
135    type Output = Self;
136    fn sub(self, rhs: u64) -> Self::Output {
137        Self::new(self.0 - rhs)
138    }
139}
140
141impl std::ops::Add<u64> for ProtocolVersion {
142    type Output = Self;
143    fn add(self, rhs: u64) -> Self::Output {
144        Self::new(self.0 + rhs)
145    }
146}
147
148#[derive(Clone, Serialize, Deserialize, Debug, PartialEq, Copy, PartialOrd, Ord, Eq, ValueEnum)]
149pub enum Chain {
150    Mainnet,
151    Testnet,
152    Unknown,
153}
154
155impl Default for Chain {
156    fn default() -> Self {
157        Self::Unknown
158    }
159}
160
161impl Chain {
162    pub fn as_str(self) -> &'static str {
163        match self {
164            Chain::Mainnet => "mainnet",
165            Chain::Testnet => "testnet",
166            Chain::Unknown => "unknown",
167        }
168    }
169}
170
171pub struct Error(pub String);
172
173// TODO: There are quite a few non boolean values in the feature flags. We
174// should move them out.
175/// Records on/off feature flags that may vary at each protocol version.
176#[derive(Default, Clone, Serialize, Deserialize, Debug, ProtocolConfigFeatureFlagsGetters)]
177struct FeatureFlags {
178    // Add feature flags here, e.g.:
179    // new_protocol_feature: bool,
180
181    // Disables unnecessary invariant check in the Move VM when swapping the value out of a local
182    // This flag is used to provide the correct MoveVM configuration for clients.
183    #[serde(skip_serializing_if = "is_true")]
184    disable_invariant_violation_check_in_swap_loc: bool,
185
186    // If true, checks no extra bytes in a compiled module
187    // This flag is used to provide the correct MoveVM configuration for clients.
188    #[serde(skip_serializing_if = "is_true")]
189    no_extraneous_module_bytes: bool,
190
191    // Enable zklogin auth
192    #[serde(skip_serializing_if = "is_false")]
193    zklogin_auth: bool,
194
195    // How we order transactions coming out of consensus before sending to execution.
196    #[serde(skip_serializing_if = "ConsensusTransactionOrdering::is_none")]
197    consensus_transaction_ordering: ConsensusTransactionOrdering,
198
199    #[serde(skip_serializing_if = "is_false")]
200    enable_jwk_consensus_updates: bool,
201
202    // If true, multisig containing zkLogin sig is accepted.
203    #[serde(skip_serializing_if = "is_false")]
204    accept_zklogin_in_multisig: bool,
205
206    // If true, use the hardened OTW check
207    // This flag is used to provide the correct MoveVM configuration for clients.
208    #[serde(skip_serializing_if = "is_true")]
209    hardened_otw_check: bool,
210
211    // Enable the poseidon hash function
212    #[serde(skip_serializing_if = "is_false")]
213    enable_poseidon: bool,
214
215    // Enable native function for msm.
216    #[serde(skip_serializing_if = "is_false")]
217    enable_group_ops_native_function_msm: bool,
218
219    // Controls the behavior of per object congestion control in consensus handler.
220    #[serde(skip_serializing_if = "PerObjectCongestionControlMode::is_none")]
221    per_object_congestion_control_mode: PerObjectCongestionControlMode,
222
223    // The consensus protocol to be used for the epoch.
224    #[serde(skip_serializing_if = "ConsensusChoice::is_mysticeti")]
225    consensus_choice: ConsensusChoice,
226
227    // Consensus network to use.
228    #[serde(skip_serializing_if = "ConsensusNetwork::is_tonic")]
229    consensus_network: ConsensusNetwork,
230
231    // Set the upper bound allowed for max_epoch in zklogin signature.
232    #[serde(skip_serializing_if = "Option::is_none")]
233    zklogin_max_epoch_upper_bound_delta: Option<u64>,
234
235    // Enable VDF
236    #[serde(skip_serializing_if = "is_false")]
237    enable_vdf: bool,
238
239    // Enable passkey auth (SIP-9)
240    #[serde(skip_serializing_if = "is_false")]
241    passkey_auth: bool,
242
243    // Rethrow type layout errors during serialization instead of trying to convert them.
244    // This flag is used to provide the correct MoveVM configuration for clients.
245    #[serde(skip_serializing_if = "is_true")]
246    rethrow_serialization_type_layout_errors: bool,
247
248    // Makes the event's sending module version-aware.
249    #[serde(skip_serializing_if = "is_false")]
250    relocate_event_module: bool,
251
252    // Enable a protocol-defined base gas price for all transactions.
253    #[serde(skip_serializing_if = "is_false")]
254    protocol_defined_base_fee: bool,
255
256    // Enable uncompressed group elements in BLS123-81 G1
257    #[serde(skip_serializing_if = "is_false")]
258    uncompressed_g1_group_elements: bool,
259
260    // Disallow adding new modules in `deps-only` packages.
261    #[serde(skip_serializing_if = "is_false")]
262    disallow_new_modules_in_deps_only_packages: bool,
263
264    // Enable v2 native charging for natives.
265    #[serde(skip_serializing_if = "is_false")]
266    native_charging_v2: bool,
267
268    // Properly convert certain type argument errors in the execution layer.
269    #[serde(skip_serializing_if = "is_false")]
270    convert_type_argument_error: bool,
271
272    // Probe rounds received by peers from every authority.
273    #[serde(skip_serializing_if = "is_false")]
274    consensus_round_prober: bool,
275
276    // Use distributed vote leader scoring strategy in consensus.
277    #[serde(skip_serializing_if = "is_false")]
278    consensus_distributed_vote_scoring_strategy: bool,
279
280    // Enables the new logic for collecting the subdag in the consensus linearizer. The new logic
281    // does not stop the recursion at the highest committed round for each authority, but
282    // allows to commit uncommitted blocks up to gc round (excluded) for that authority.
283    #[serde(skip_serializing_if = "is_false")]
284    consensus_linearize_subdag_v2: bool,
285
286    // Variants count as nodes
287    #[serde(skip_serializing_if = "is_false")]
288    variant_nodes: bool,
289
290    // Use smart ancestor selection in consensus.
291    #[serde(skip_serializing_if = "is_false")]
292    consensus_smart_ancestor_selection: bool,
293
294    // Probe accepted rounds in round prober.
295    #[serde(skip_serializing_if = "is_false")]
296    consensus_round_prober_probe_accepted_rounds: bool,
297
298    // If true, enable zstd compression for consensus tonic network.
299    #[serde(skip_serializing_if = "is_false")]
300    consensus_zstd_compression: bool,
301
302    // Use the minimum free execution slot to schedule execution of a transaction in the shared
303    // object congestion tracker.
304    #[serde(skip_serializing_if = "is_false")]
305    congestion_control_min_free_execution_slot: bool,
306
307    // If true, multisig containing passkey sig is accepted.
308    #[serde(skip_serializing_if = "is_false")]
309    accept_passkey_in_multisig: bool,
310
311    // If true, enabled batched block sync in consensus.
312    #[serde(skip_serializing_if = "is_false")]
313    consensus_batched_block_sync: bool,
314
315    // To enable/disable the gas price feedback mechanism used for transactions
316    // cancelled due to shared object congestion
317    #[serde(skip_serializing_if = "is_false")]
318    congestion_control_gas_price_feedback_mechanism: bool,
319
320    // Validate identifier inputs separately
321    #[serde(skip_serializing_if = "is_false")]
322    validate_identifier_inputs: bool,
323
324    // If true, enables the optimizations for child object mutations, removing unnecessary
325    // mutations
326    #[serde(skip_serializing_if = "is_false")]
327    minimize_child_object_mutations: bool,
328
329    // If true enable additional linkage checks.
330    #[serde(skip_serializing_if = "is_false")]
331    dependency_linkage_error: bool,
332
333    // If true enable additional multisig checks.
334    #[serde(skip_serializing_if = "is_false")]
335    additional_multisig_checks: bool,
336
337    // If true, enables the normalization of PTB arguments but does not yet enable splatting
338    // `Result`s of length not equal to 1
339    #[serde(skip_serializing_if = "is_false")]
340    normalize_ptb_arguments: bool,
341
342    // If true, use ChangeEpochV3 for epoch change to pass an additional eligible_active_validators
343    // parameter to IotaSystem's advance_epoch call. This should only be enabled when on-chain
344    // IotaSystem objects are updated as well.
345    #[serde(skip_serializing_if = "is_false")]
346    select_committee_from_eligible_validators: bool,
347
348    // If true, non-committee active validators will sign and send AuthorityCapabilitiesV1 to the
349    // committee. Once the committee reaches consensus over the AuthorityCapabilitiesV1, it is
350    // recorded and possible to use in the committee selection if
351    // select_validators_supporting_next_epoch_version is enabled. This flag does not change the
352    // way that eligible_validators vector is created - still all active validators are used for
353    // selecting the committee.
354    #[serde(skip_serializing_if = "is_false")]
355    track_non_committee_eligible_validators: bool,
356
357    // The committee be selected from active_validators who support the next protocol version AND
358    // have issued a correct AuthorityCapabilities notification. This flag should only be enabled
359    // if both select_committee_from_eligible_validators and
360    // track_non_committee_eligible_validators are enabled. If this is disabled, then all
361    // active validators are used for selecting the committee (default behavior).
362    #[serde(skip_serializing_if = "is_false")]
363    select_committee_supporting_next_epoch_version: bool,
364
365    // If true, then it (1) will not enforce monotonicity checks for a block's ancestors, (2)
366    // calculates the commit's timestamp based on the weighted by stake median timestamp of the
367    // leader's ancestors, and (3) enforces checkpoint timestamps are non-decreasing.
368    #[serde(skip_serializing_if = "is_false")]
369    consensus_median_timestamp_with_checkpoint_enforcement: bool,
370}
371
372fn is_true(b: &bool) -> bool {
373    *b
374}
375
376fn is_false(b: &bool) -> bool {
377    !b
378}
379
380/// Ordering mechanism for transactions in one consensus output.
381#[derive(Default, Copy, Clone, PartialEq, Eq, Serialize, Deserialize, Debug)]
382pub enum ConsensusTransactionOrdering {
383    /// No ordering. Transactions are processed in the order they appear in the
384    /// consensus output.
385    #[default]
386    None,
387    /// Order transactions by gas price, highest first.
388    ByGasPrice,
389}
390
391impl ConsensusTransactionOrdering {
392    pub fn is_none(&self) -> bool {
393        matches!(self, ConsensusTransactionOrdering::None)
394    }
395}
396
397// The config for per object congestion control in consensus handler.
398#[derive(Default, Copy, Clone, PartialEq, Eq, Serialize, Deserialize, Debug)]
399pub enum PerObjectCongestionControlMode {
400    #[default]
401    None, // No congestion control.
402    TotalGasBudget, // Use txn gas budget as execution cost.
403    TotalTxCount,   // Use total txn count as execution cost.
404}
405
406impl PerObjectCongestionControlMode {
407    pub fn is_none(&self) -> bool {
408        matches!(self, PerObjectCongestionControlMode::None)
409    }
410}
411
412// Configuration options for consensus algorithm.
413#[derive(Default, Copy, Clone, PartialEq, Eq, Serialize, Deserialize, Debug)]
414pub enum ConsensusChoice {
415    #[default]
416    Mysticeti,
417    Starfish,
418}
419
420impl ConsensusChoice {
421    pub fn is_mysticeti(&self) -> bool {
422        matches!(self, ConsensusChoice::Mysticeti)
423    }
424    pub fn is_starfish(&self) -> bool {
425        matches!(self, ConsensusChoice::Starfish)
426    }
427}
428
429// Configuration options for consensus network.
430#[derive(Default, Copy, Clone, PartialEq, Eq, Serialize, Deserialize, Debug)]
431pub enum ConsensusNetwork {
432    #[default]
433    Tonic,
434}
435
436impl ConsensusNetwork {
437    pub fn is_tonic(&self) -> bool {
438        matches!(self, ConsensusNetwork::Tonic)
439    }
440}
441
442/// Constants that change the behavior of the protocol.
443///
444/// The value of each constant here must be fixed for a given protocol version.
445/// To change the value of a constant, advance the protocol version, and add
446/// support for it in `get_for_version` under the new version number.
447/// (below).
448///
449/// To add a new field to this struct, use the following procedure:
450/// - Advance the protocol version.
451/// - Add the field as a private `Option<T>` to the struct.
452/// - Initialize the field to `None` in prior protocol versions.
453/// - Initialize the field to `Some(val)` for your new protocol version.
454/// - Add a public getter that simply unwraps the field.
455/// - Two public getters of the form `field(&self) -> field_type` and
456///   `field_as_option(&self) -> Option<field_type>` will be automatically
457///   generated for you.
458/// Example for a field: `new_constant: Option<u64>`
459/// ```rust,ignore
460///      pub fn new_constant(&self) -> u64 {
461///         self.new_constant.expect(Self::CONSTANT_ERR_MSG)
462///     }
463///      pub fn new_constant_as_option(&self) -> Option<u64> {
464///         self.new_constant.expect(Self::CONSTANT_ERR_MSG)
465///     }
466/// ```
467/// With `pub fn new_constant(&self) -> u64`, if the constant is accessed in a
468/// protocol version in which it is not defined, the validator will crash.
469/// (Crashing is necessary because this type of error would almost always result
470/// in forking if not prevented here). If you don't want the validator to crash,
471/// you can use the `pub fn new_constant_as_option(&self) -> Option<u64>`
472/// getter, which will return `None` if the field is not defined at that
473/// version.
474/// - If you want a customized getter, you can add a method in the impl.
475#[skip_serializing_none]
476#[derive(Clone, Serialize, Debug, ProtocolConfigAccessors, ProtocolConfigOverride)]
477pub struct ProtocolConfig {
478    pub version: ProtocolVersion,
479
480    feature_flags: FeatureFlags,
481
482    // ==== Transaction input limits ====
483
484    //
485    /// Maximum serialized size of a transaction (in bytes).
486    max_tx_size_bytes: Option<u64>,
487
488    /// Maximum number of input objects to a transaction. Enforced by the
489    /// transaction input checker
490    max_input_objects: Option<u64>,
491
492    /// Max size of objects a transaction can write to disk after completion.
493    /// Enforce by the IOTA adapter. This is the sum of the serialized size
494    /// of all objects written to disk. The max size of individual objects
495    /// on the other hand is `max_move_object_size`.
496    max_size_written_objects: Option<u64>,
497    /// Max size of objects a system transaction can write to disk after
498    /// completion. Enforce by the IOTA adapter. Similar to
499    /// `max_size_written_objects` but for system transactions.
500    max_size_written_objects_system_tx: Option<u64>,
501
502    /// Maximum size of serialized transaction effects.
503    max_serialized_tx_effects_size_bytes: Option<u64>,
504
505    /// Maximum size of serialized transaction effects for system transactions.
506    max_serialized_tx_effects_size_bytes_system_tx: Option<u64>,
507
508    /// Maximum number of gas payment objects for a transaction.
509    max_gas_payment_objects: Option<u32>,
510
511    /// Maximum number of modules in a Publish transaction.
512    max_modules_in_publish: Option<u32>,
513
514    /// Maximum number of transitive dependencies in a package when publishing.
515    max_package_dependencies: Option<u32>,
516
517    /// Maximum number of arguments in a move call or a
518    /// ProgrammableTransaction's TransferObjects command.
519    max_arguments: Option<u32>,
520
521    /// Maximum number of total type arguments, computed recursively.
522    max_type_arguments: Option<u32>,
523
524    /// Maximum depth of an individual type argument.
525    max_type_argument_depth: Option<u32>,
526
527    /// Maximum size of a Pure CallArg.
528    max_pure_argument_size: Option<u32>,
529
530    /// Maximum number of Commands in a ProgrammableTransaction.
531    max_programmable_tx_commands: Option<u32>,
532
533    // ==== Move VM, Move bytecode verifier, and execution limits ===
534
535    //
536    /// Maximum Move bytecode version the VM understands. All older versions are
537    /// accepted.
538    move_binary_format_version: Option<u32>,
539    min_move_binary_format_version: Option<u32>,
540
541    /// Configuration controlling binary tables size.
542    binary_module_handles: Option<u16>,
543    binary_struct_handles: Option<u16>,
544    binary_function_handles: Option<u16>,
545    binary_function_instantiations: Option<u16>,
546    binary_signatures: Option<u16>,
547    binary_constant_pool: Option<u16>,
548    binary_identifiers: Option<u16>,
549    binary_address_identifiers: Option<u16>,
550    binary_struct_defs: Option<u16>,
551    binary_struct_def_instantiations: Option<u16>,
552    binary_function_defs: Option<u16>,
553    binary_field_handles: Option<u16>,
554    binary_field_instantiations: Option<u16>,
555    binary_friend_decls: Option<u16>,
556    binary_enum_defs: Option<u16>,
557    binary_enum_def_instantiations: Option<u16>,
558    binary_variant_handles: Option<u16>,
559    binary_variant_instantiation_handles: Option<u16>,
560
561    /// Maximum size of the `contents` part of an object, in bytes. Enforced by
562    /// the IOTA adapter when effects are produced.
563    max_move_object_size: Option<u64>,
564
565    // TODO: Option<increase to 500 KB. currently, publishing a package > 500 KB exceeds the max
566    // computation gas cost
567    /// Maximum size of a Move package object, in bytes. Enforced by the IOTA
568    /// adapter at the end of a publish transaction.
569    max_move_package_size: Option<u64>,
570
571    /// Max number of publish or upgrade commands allowed in a programmable
572    /// transaction block.
573    max_publish_or_upgrade_per_ptb: Option<u64>,
574
575    /// Maximum gas budget in NANOS that a transaction can use.
576    max_tx_gas: Option<u64>,
577
578    /// Maximum amount of the proposed gas price in NANOS (defined in the
579    /// transaction).
580    max_gas_price: Option<u64>,
581
582    /// The max computation bucket for gas. This is the max that can be charged
583    /// for computation.
584    max_gas_computation_bucket: Option<u64>,
585
586    // Define the value used to round up computation gas charges
587    gas_rounding_step: Option<u64>,
588
589    /// Maximum number of nested loops. Enforced by the Move bytecode verifier.
590    max_loop_depth: Option<u64>,
591
592    /// Maximum number of type arguments that can be bound to generic type
593    /// parameters. Enforced by the Move bytecode verifier.
594    max_generic_instantiation_length: Option<u64>,
595
596    /// Maximum number of parameters that a Move function can have. Enforced by
597    /// the Move bytecode verifier.
598    max_function_parameters: Option<u64>,
599
600    /// Maximum number of basic blocks that a Move function can have. Enforced
601    /// by the Move bytecode verifier.
602    max_basic_blocks: Option<u64>,
603
604    /// Maximum stack size value. Enforced by the Move bytecode verifier.
605    max_value_stack_size: Option<u64>,
606
607    /// Maximum number of "type nodes", a metric for how big a SignatureToken
608    /// will be when expanded into a fully qualified type. Enforced by the Move
609    /// bytecode verifier.
610    max_type_nodes: Option<u64>,
611
612    /// Maximum number of push instructions in one function. Enforced by the
613    /// Move bytecode verifier.
614    max_push_size: Option<u64>,
615
616    /// Maximum number of struct definitions in a module. Enforced by the Move
617    /// bytecode verifier.
618    max_struct_definitions: Option<u64>,
619
620    /// Maximum number of function definitions in a module. Enforced by the Move
621    /// bytecode verifier.
622    max_function_definitions: Option<u64>,
623
624    /// Maximum number of fields allowed in a struct definition. Enforced by the
625    /// Move bytecode verifier.
626    max_fields_in_struct: Option<u64>,
627
628    /// Maximum dependency depth. Enforced by the Move linker when loading
629    /// dependent modules.
630    max_dependency_depth: Option<u64>,
631
632    /// Maximum number of Move events that a single transaction can emit.
633    /// Enforced by the VM during execution.
634    max_num_event_emit: Option<u64>,
635
636    /// Maximum number of new IDs that a single transaction can create. Enforced
637    /// by the VM during execution.
638    max_num_new_move_object_ids: Option<u64>,
639
640    /// Maximum number of new IDs that a single system transaction can create.
641    /// Enforced by the VM during execution.
642    max_num_new_move_object_ids_system_tx: Option<u64>,
643
644    /// Maximum number of IDs that a single transaction can delete. Enforced by
645    /// the VM during execution.
646    max_num_deleted_move_object_ids: Option<u64>,
647
648    /// Maximum number of IDs that a single system transaction can delete.
649    /// Enforced by the VM during execution.
650    max_num_deleted_move_object_ids_system_tx: Option<u64>,
651
652    /// Maximum number of IDs that a single transaction can transfer. Enforced
653    /// by the VM during execution.
654    max_num_transferred_move_object_ids: Option<u64>,
655
656    /// Maximum number of IDs that a single system transaction can transfer.
657    /// Enforced by the VM during execution.
658    max_num_transferred_move_object_ids_system_tx: Option<u64>,
659
660    /// Maximum size of a Move user event. Enforced by the VM during execution.
661    max_event_emit_size: Option<u64>,
662
663    /// Maximum size of a Move user event. Enforced by the VM during execution.
664    max_event_emit_size_total: Option<u64>,
665
666    /// Maximum length of a vector in Move. Enforced by the VM during execution,
667    /// and for constants, by the verifier.
668    max_move_vector_len: Option<u64>,
669
670    /// Maximum length of an `Identifier` in Move. Enforced by the bytecode
671    /// verifier at signing.
672    max_move_identifier_len: Option<u64>,
673
674    /// Maximum depth of a Move value within the VM.
675    max_move_value_depth: Option<u64>,
676
677    /// Maximum number of variants in an enum. Enforced by the bytecode verifier
678    /// at signing.
679    max_move_enum_variants: Option<u64>,
680
681    /// Maximum number of back edges in Move function. Enforced by the bytecode
682    /// verifier at signing.
683    max_back_edges_per_function: Option<u64>,
684
685    /// Maximum number of back edges in Move module. Enforced by the bytecode
686    /// verifier at signing.
687    max_back_edges_per_module: Option<u64>,
688
689    /// Maximum number of meter `ticks` spent verifying a Move function.
690    /// Enforced by the bytecode verifier at signing.
691    max_verifier_meter_ticks_per_function: Option<u64>,
692
693    /// Maximum number of meter `ticks` spent verifying a Move function.
694    /// Enforced by the bytecode verifier at signing.
695    max_meter_ticks_per_module: Option<u64>,
696
697    /// Maximum number of meter `ticks` spent verifying a Move package. Enforced
698    /// by the bytecode verifier at signing.
699    max_meter_ticks_per_package: Option<u64>,
700
701    // === Object runtime internal operation limits ====
702    // These affect dynamic fields
703
704    //
705    /// Maximum number of cached objects in the object runtime ObjectStore.
706    /// Enforced by object runtime during execution
707    object_runtime_max_num_cached_objects: Option<u64>,
708
709    /// Maximum number of cached objects in the object runtime ObjectStore in
710    /// system transaction. Enforced by object runtime during execution
711    object_runtime_max_num_cached_objects_system_tx: Option<u64>,
712
713    /// Maximum number of stored objects accessed by object runtime ObjectStore.
714    /// Enforced by object runtime during execution
715    object_runtime_max_num_store_entries: Option<u64>,
716
717    /// Maximum number of stored objects accessed by object runtime ObjectStore
718    /// in system transaction. Enforced by object runtime during execution
719    object_runtime_max_num_store_entries_system_tx: Option<u64>,
720
721    // === Execution gas costs ====
722
723    //
724    /// Base cost for any IOTA transaction
725    base_tx_cost_fixed: Option<u64>,
726
727    /// Additional cost for a transaction that publishes a package
728    /// i.e., the base cost of such a transaction is base_tx_cost_fixed +
729    /// package_publish_cost_fixed
730    package_publish_cost_fixed: Option<u64>,
731
732    /// Cost per byte of a Move call transaction
733    /// i.e., the cost of such a transaction is base_cost +
734    /// (base_tx_cost_per_byte * size)
735    base_tx_cost_per_byte: Option<u64>,
736
737    /// Cost per byte for a transaction that publishes a package
738    package_publish_cost_per_byte: Option<u64>,
739
740    // Per-byte cost of reading an object during transaction execution
741    obj_access_cost_read_per_byte: Option<u64>,
742
743    // Per-byte cost of writing an object during transaction execution
744    obj_access_cost_mutate_per_byte: Option<u64>,
745
746    // Per-byte cost of deleting an object during transaction execution
747    obj_access_cost_delete_per_byte: Option<u64>,
748
749    /// Per-byte cost charged for each input object to a transaction.
750    /// Meant to approximate the cost of checking locks for each object
751    // TODO: Option<I'm not sure that this cost makes sense. Checking locks is "free"
752    // in the sense that an invalid tx that can never be committed/pay gas can
753    // force validators to check an arbitrary number of locks. If those checks are
754    // "free" for invalid transactions, why charge for them in valid transactions
755    // TODO: Option<if we keep this, I think we probably want it to be a fixed cost rather
756    // than a per-byte cost. checking an object lock should not require loading an
757    // entire object, just consulting an ID -> tx digest map
758    obj_access_cost_verify_per_byte: Option<u64>,
759
760    // Maximal nodes which are allowed when converting to a type layout.
761    max_type_to_layout_nodes: Option<u64>,
762
763    // Maximal size in bytes that a PTB value can be
764    max_ptb_value_size: Option<u64>,
765
766    // === Gas version. gas model ===
767
768    //
769    /// Gas model version, what code we are using to charge gas
770    gas_model_version: Option<u64>,
771
772    // === Storage gas costs ===
773
774    //
775    /// Per-byte cost of storing an object in the IOTA global object store. Some
776    /// of this cost may be refundable if the object is later freed
777    obj_data_cost_refundable: Option<u64>,
778
779    // Per-byte cost of storing an object in the IOTA transaction log (e.g., in
780    // CertifiedTransactionEffects) This depends on the size of various fields including the
781    // effects TODO: Option<I don't fully understand this^ and more details would be useful
782    obj_metadata_cost_non_refundable: Option<u64>,
783
784    // === Tokenomics ===
785
786    // TODO: Option<this should be changed to u64.
787    /// Sender of a txn that touches an object will get this percent of the
788    /// storage rebate back. In basis point.
789    storage_rebate_rate: Option<u64>,
790
791    /// The share of rewards that will be slashed and redistributed is 50%.
792    /// In basis point.
793    reward_slashing_rate: Option<u64>,
794
795    /// Unit storage gas price, Nanos per internal gas unit.
796    storage_gas_price: Option<u64>,
797
798    // Base gas price for computation gas, nanos per computation unit.
799    base_gas_price: Option<u64>,
800
801    /// The number of tokens minted as a validator subsidy per epoch.
802    validator_target_reward: Option<u64>,
803
804    // === Core Protocol ===
805
806    //
807    /// Max number of transactions per checkpoint.
808    /// Note that this is a protocol constant and not a config as validators
809    /// must have this set to the same value, otherwise they *will* fork.
810    max_transactions_per_checkpoint: Option<u64>,
811
812    /// Max size of a checkpoint in bytes.
813    /// Note that this is a protocol constant and not a config as validators
814    /// must have this set to the same value, otherwise they *will* fork.
815    max_checkpoint_size_bytes: Option<u64>,
816
817    /// A protocol upgrade always requires 2f+1 stake to agree. We support a
818    /// buffer of additional stake (as a fraction of f, expressed in basis
819    /// points) that is required before an upgrade can happen automatically.
820    /// 10000bps would indicate that complete unanimity is required (all
821    /// 3f+1 must vote), while 0bps would indicate that 2f+1 is sufficient.
822    buffer_stake_for_protocol_upgrade_bps: Option<u64>,
823
824    // === Native Function Costs ===
825
826    // `address` module
827    // Cost params for the Move native function `address::from_bytes(bytes: vector<u8>)`
828    address_from_bytes_cost_base: Option<u64>,
829    // Cost params for the Move native function `address::to_u256(address): u256`
830    address_to_u256_cost_base: Option<u64>,
831    // Cost params for the Move native function `address::from_u256(u256): address`
832    address_from_u256_cost_base: Option<u64>,
833
834    // `config` module
835    // Cost params for the Move native function `read_setting_impl<Name: copy + drop + store,
836    // SettingValue: key + store, SettingDataValue: store, Value: copy + drop + store,
837    // >(config: address, name: address, current_epoch: u64): Option<Value>`
838    config_read_setting_impl_cost_base: Option<u64>,
839    config_read_setting_impl_cost_per_byte: Option<u64>,
840
841    // `dynamic_field` module
842    // Cost params for the Move native function `hash_type_and_key<K: copy + drop + store>(parent:
843    // address, k: K): address`
844    dynamic_field_hash_type_and_key_cost_base: Option<u64>,
845    dynamic_field_hash_type_and_key_type_cost_per_byte: Option<u64>,
846    dynamic_field_hash_type_and_key_value_cost_per_byte: Option<u64>,
847    dynamic_field_hash_type_and_key_type_tag_cost_per_byte: Option<u64>,
848    // Cost params for the Move native function `add_child_object<Child: key>(parent: address,
849    // child: Child)`
850    dynamic_field_add_child_object_cost_base: Option<u64>,
851    dynamic_field_add_child_object_type_cost_per_byte: Option<u64>,
852    dynamic_field_add_child_object_value_cost_per_byte: Option<u64>,
853    dynamic_field_add_child_object_struct_tag_cost_per_byte: Option<u64>,
854    // Cost params for the Move native function `borrow_child_object_mut<Child: key>(parent: &mut
855    // UID, id: address): &mut Child`
856    dynamic_field_borrow_child_object_cost_base: Option<u64>,
857    dynamic_field_borrow_child_object_child_ref_cost_per_byte: Option<u64>,
858    dynamic_field_borrow_child_object_type_cost_per_byte: Option<u64>,
859    // Cost params for the Move native function `remove_child_object<Child: key>(parent: address,
860    // id: address): Child`
861    dynamic_field_remove_child_object_cost_base: Option<u64>,
862    dynamic_field_remove_child_object_child_cost_per_byte: Option<u64>,
863    dynamic_field_remove_child_object_type_cost_per_byte: Option<u64>,
864    // Cost params for the Move native function `has_child_object(parent: address, id: address):
865    // bool`
866    dynamic_field_has_child_object_cost_base: Option<u64>,
867    // Cost params for the Move native function `has_child_object_with_ty<Child: key>(parent:
868    // address, id: address): bool`
869    dynamic_field_has_child_object_with_ty_cost_base: Option<u64>,
870    dynamic_field_has_child_object_with_ty_type_cost_per_byte: Option<u64>,
871    dynamic_field_has_child_object_with_ty_type_tag_cost_per_byte: Option<u64>,
872
873    // `event` module
874    // Cost params for the Move native function `event::emit<T: copy + drop>(event: T)`
875    event_emit_cost_base: Option<u64>,
876    event_emit_value_size_derivation_cost_per_byte: Option<u64>,
877    event_emit_tag_size_derivation_cost_per_byte: Option<u64>,
878    event_emit_output_cost_per_byte: Option<u64>,
879
880    //  `object` module
881    // Cost params for the Move native function `borrow_uid<T: key>(obj: &T): &UID`
882    object_borrow_uid_cost_base: Option<u64>,
883    // Cost params for the Move native function `delete_impl(id: address)`
884    object_delete_impl_cost_base: Option<u64>,
885    // Cost params for the Move native function `record_new_uid(id: address)`
886    object_record_new_uid_cost_base: Option<u64>,
887
888    // Transfer
889    // Cost params for the Move native function `transfer_impl<T: key>(obj: T, recipient: address)`
890    transfer_transfer_internal_cost_base: Option<u64>,
891    // Cost params for the Move native function `freeze_object<T: key>(obj: T)`
892    transfer_freeze_object_cost_base: Option<u64>,
893    // Cost params for the Move native function `share_object<T: key>(obj: T)`
894    transfer_share_object_cost_base: Option<u64>,
895    // Cost params for the Move native function
896    // `receive_object<T: key>(p: &mut UID, recv: Receiving<T>T)`
897    transfer_receive_object_cost_base: Option<u64>,
898
899    // TxContext
900    // Cost params for the Move native function `transfer_impl<T: key>(obj: T, recipient: address)`
901    tx_context_derive_id_cost_base: Option<u64>,
902
903    // Types
904    // Cost params for the Move native function `is_one_time_witness<T: drop>(_: &T): bool`
905    types_is_one_time_witness_cost_base: Option<u64>,
906    types_is_one_time_witness_type_tag_cost_per_byte: Option<u64>,
907    types_is_one_time_witness_type_cost_per_byte: Option<u64>,
908
909    // Validator
910    // Cost params for the Move native function `validate_metadata_bcs(metadata: vector<u8>)`
911    validator_validate_metadata_cost_base: Option<u64>,
912    validator_validate_metadata_data_cost_per_byte: Option<u64>,
913
914    // Crypto natives
915    crypto_invalid_arguments_cost: Option<u64>,
916    // bls12381::bls12381_min_sig_verify
917    bls12381_bls12381_min_sig_verify_cost_base: Option<u64>,
918    bls12381_bls12381_min_sig_verify_msg_cost_per_byte: Option<u64>,
919    bls12381_bls12381_min_sig_verify_msg_cost_per_block: Option<u64>,
920
921    // bls12381::bls12381_min_pk_verify
922    bls12381_bls12381_min_pk_verify_cost_base: Option<u64>,
923    bls12381_bls12381_min_pk_verify_msg_cost_per_byte: Option<u64>,
924    bls12381_bls12381_min_pk_verify_msg_cost_per_block: Option<u64>,
925
926    // ecdsa_k1::ecrecover
927    ecdsa_k1_ecrecover_keccak256_cost_base: Option<u64>,
928    ecdsa_k1_ecrecover_keccak256_msg_cost_per_byte: Option<u64>,
929    ecdsa_k1_ecrecover_keccak256_msg_cost_per_block: Option<u64>,
930    ecdsa_k1_ecrecover_sha256_cost_base: Option<u64>,
931    ecdsa_k1_ecrecover_sha256_msg_cost_per_byte: Option<u64>,
932    ecdsa_k1_ecrecover_sha256_msg_cost_per_block: Option<u64>,
933
934    // ecdsa_k1::decompress_pubkey
935    ecdsa_k1_decompress_pubkey_cost_base: Option<u64>,
936
937    // ecdsa_k1::secp256k1_verify
938    ecdsa_k1_secp256k1_verify_keccak256_cost_base: Option<u64>,
939    ecdsa_k1_secp256k1_verify_keccak256_msg_cost_per_byte: Option<u64>,
940    ecdsa_k1_secp256k1_verify_keccak256_msg_cost_per_block: Option<u64>,
941    ecdsa_k1_secp256k1_verify_sha256_cost_base: Option<u64>,
942    ecdsa_k1_secp256k1_verify_sha256_msg_cost_per_byte: Option<u64>,
943    ecdsa_k1_secp256k1_verify_sha256_msg_cost_per_block: Option<u64>,
944
945    // ecdsa_r1::ecrecover
946    ecdsa_r1_ecrecover_keccak256_cost_base: Option<u64>,
947    ecdsa_r1_ecrecover_keccak256_msg_cost_per_byte: Option<u64>,
948    ecdsa_r1_ecrecover_keccak256_msg_cost_per_block: Option<u64>,
949    ecdsa_r1_ecrecover_sha256_cost_base: Option<u64>,
950    ecdsa_r1_ecrecover_sha256_msg_cost_per_byte: Option<u64>,
951    ecdsa_r1_ecrecover_sha256_msg_cost_per_block: Option<u64>,
952
953    // ecdsa_r1::secp256k1_verify
954    ecdsa_r1_secp256r1_verify_keccak256_cost_base: Option<u64>,
955    ecdsa_r1_secp256r1_verify_keccak256_msg_cost_per_byte: Option<u64>,
956    ecdsa_r1_secp256r1_verify_keccak256_msg_cost_per_block: Option<u64>,
957    ecdsa_r1_secp256r1_verify_sha256_cost_base: Option<u64>,
958    ecdsa_r1_secp256r1_verify_sha256_msg_cost_per_byte: Option<u64>,
959    ecdsa_r1_secp256r1_verify_sha256_msg_cost_per_block: Option<u64>,
960
961    // ecvrf::verify
962    ecvrf_ecvrf_verify_cost_base: Option<u64>,
963    ecvrf_ecvrf_verify_alpha_string_cost_per_byte: Option<u64>,
964    ecvrf_ecvrf_verify_alpha_string_cost_per_block: Option<u64>,
965
966    // ed25519
967    ed25519_ed25519_verify_cost_base: Option<u64>,
968    ed25519_ed25519_verify_msg_cost_per_byte: Option<u64>,
969    ed25519_ed25519_verify_msg_cost_per_block: Option<u64>,
970
971    // groth16::prepare_verifying_key
972    groth16_prepare_verifying_key_bls12381_cost_base: Option<u64>,
973    groth16_prepare_verifying_key_bn254_cost_base: Option<u64>,
974
975    // groth16::verify_groth16_proof_internal
976    groth16_verify_groth16_proof_internal_bls12381_cost_base: Option<u64>,
977    groth16_verify_groth16_proof_internal_bls12381_cost_per_public_input: Option<u64>,
978    groth16_verify_groth16_proof_internal_bn254_cost_base: Option<u64>,
979    groth16_verify_groth16_proof_internal_bn254_cost_per_public_input: Option<u64>,
980    groth16_verify_groth16_proof_internal_public_input_cost_per_byte: Option<u64>,
981
982    // hash::blake2b256
983    hash_blake2b256_cost_base: Option<u64>,
984    hash_blake2b256_data_cost_per_byte: Option<u64>,
985    hash_blake2b256_data_cost_per_block: Option<u64>,
986
987    // hash::keccak256
988    hash_keccak256_cost_base: Option<u64>,
989    hash_keccak256_data_cost_per_byte: Option<u64>,
990    hash_keccak256_data_cost_per_block: Option<u64>,
991
992    // poseidon::poseidon_bn254
993    poseidon_bn254_cost_base: Option<u64>,
994    poseidon_bn254_cost_per_block: Option<u64>,
995
996    // group_ops
997    group_ops_bls12381_decode_scalar_cost: Option<u64>,
998    group_ops_bls12381_decode_g1_cost: Option<u64>,
999    group_ops_bls12381_decode_g2_cost: Option<u64>,
1000    group_ops_bls12381_decode_gt_cost: Option<u64>,
1001    group_ops_bls12381_scalar_add_cost: Option<u64>,
1002    group_ops_bls12381_g1_add_cost: Option<u64>,
1003    group_ops_bls12381_g2_add_cost: Option<u64>,
1004    group_ops_bls12381_gt_add_cost: Option<u64>,
1005    group_ops_bls12381_scalar_sub_cost: Option<u64>,
1006    group_ops_bls12381_g1_sub_cost: Option<u64>,
1007    group_ops_bls12381_g2_sub_cost: Option<u64>,
1008    group_ops_bls12381_gt_sub_cost: Option<u64>,
1009    group_ops_bls12381_scalar_mul_cost: Option<u64>,
1010    group_ops_bls12381_g1_mul_cost: Option<u64>,
1011    group_ops_bls12381_g2_mul_cost: Option<u64>,
1012    group_ops_bls12381_gt_mul_cost: Option<u64>,
1013    group_ops_bls12381_scalar_div_cost: Option<u64>,
1014    group_ops_bls12381_g1_div_cost: Option<u64>,
1015    group_ops_bls12381_g2_div_cost: Option<u64>,
1016    group_ops_bls12381_gt_div_cost: Option<u64>,
1017    group_ops_bls12381_g1_hash_to_base_cost: Option<u64>,
1018    group_ops_bls12381_g2_hash_to_base_cost: Option<u64>,
1019    group_ops_bls12381_g1_hash_to_cost_per_byte: Option<u64>,
1020    group_ops_bls12381_g2_hash_to_cost_per_byte: Option<u64>,
1021    group_ops_bls12381_g1_msm_base_cost: Option<u64>,
1022    group_ops_bls12381_g2_msm_base_cost: Option<u64>,
1023    group_ops_bls12381_g1_msm_base_cost_per_input: Option<u64>,
1024    group_ops_bls12381_g2_msm_base_cost_per_input: Option<u64>,
1025    group_ops_bls12381_msm_max_len: Option<u32>,
1026    group_ops_bls12381_pairing_cost: Option<u64>,
1027    group_ops_bls12381_g1_to_uncompressed_g1_cost: Option<u64>,
1028    group_ops_bls12381_uncompressed_g1_to_g1_cost: Option<u64>,
1029    group_ops_bls12381_uncompressed_g1_sum_base_cost: Option<u64>,
1030    group_ops_bls12381_uncompressed_g1_sum_cost_per_term: Option<u64>,
1031    group_ops_bls12381_uncompressed_g1_sum_max_terms: Option<u64>,
1032
1033    // hmac::hmac_sha3_256
1034    hmac_hmac_sha3_256_cost_base: Option<u64>,
1035    hmac_hmac_sha3_256_input_cost_per_byte: Option<u64>,
1036    hmac_hmac_sha3_256_input_cost_per_block: Option<u64>,
1037
1038    // zklogin::check_zklogin_id
1039    check_zklogin_id_cost_base: Option<u64>,
1040    // zklogin::check_zklogin_issuer
1041    check_zklogin_issuer_cost_base: Option<u64>,
1042
1043    vdf_verify_vdf_cost: Option<u64>,
1044    vdf_hash_to_input_cost: Option<u64>,
1045
1046    // Stdlib costs
1047    bcs_per_byte_serialized_cost: Option<u64>,
1048    bcs_legacy_min_output_size_cost: Option<u64>,
1049    bcs_failure_cost: Option<u64>,
1050
1051    hash_sha2_256_base_cost: Option<u64>,
1052    hash_sha2_256_per_byte_cost: Option<u64>,
1053    hash_sha2_256_legacy_min_input_len_cost: Option<u64>,
1054    hash_sha3_256_base_cost: Option<u64>,
1055    hash_sha3_256_per_byte_cost: Option<u64>,
1056    hash_sha3_256_legacy_min_input_len_cost: Option<u64>,
1057    type_name_get_base_cost: Option<u64>,
1058    type_name_get_per_byte_cost: Option<u64>,
1059
1060    string_check_utf8_base_cost: Option<u64>,
1061    string_check_utf8_per_byte_cost: Option<u64>,
1062    string_is_char_boundary_base_cost: Option<u64>,
1063    string_sub_string_base_cost: Option<u64>,
1064    string_sub_string_per_byte_cost: Option<u64>,
1065    string_index_of_base_cost: Option<u64>,
1066    string_index_of_per_byte_pattern_cost: Option<u64>,
1067    string_index_of_per_byte_searched_cost: Option<u64>,
1068
1069    vector_empty_base_cost: Option<u64>,
1070    vector_length_base_cost: Option<u64>,
1071    vector_push_back_base_cost: Option<u64>,
1072    vector_push_back_legacy_per_abstract_memory_unit_cost: Option<u64>,
1073    vector_borrow_base_cost: Option<u64>,
1074    vector_pop_back_base_cost: Option<u64>,
1075    vector_destroy_empty_base_cost: Option<u64>,
1076    vector_swap_base_cost: Option<u64>,
1077    debug_print_base_cost: Option<u64>,
1078    debug_print_stack_trace_base_cost: Option<u64>,
1079
1080    // === Execution Version ===
1081    execution_version: Option<u64>,
1082
1083    // Dictates the threshold (percentage of stake) that is used to calculate the "bad" nodes to be
1084    // swapped when creating the consensus schedule. The values should be of the range [0 - 33].
1085    // Anything above 33 (f) will not be allowed.
1086    consensus_bad_nodes_stake_threshold: Option<u64>,
1087
1088    max_jwk_votes_per_validator_per_epoch: Option<u64>,
1089    // The maximum age of a JWK in epochs before it is removed from the AuthenticatorState object.
1090    // Applied at the end of an epoch as a delta from the new epoch value, so setting this to 1
1091    // will cause the new epoch to start with JWKs from the previous epoch still valid.
1092    max_age_of_jwk_in_epochs: Option<u64>,
1093
1094    // === random beacon ===
1095    /// Maximum allowed precision loss when reducing voting weights for the
1096    /// random beacon protocol.
1097    random_beacon_reduction_allowed_delta: Option<u16>,
1098
1099    /// Minimum number of shares below which voting weights will not be reduced
1100    /// for the random beacon protocol.
1101    random_beacon_reduction_lower_bound: Option<u32>,
1102
1103    /// Consensus Round after which DKG should be aborted and randomness
1104    /// disabled for the epoch, if it hasn't already completed.
1105    random_beacon_dkg_timeout_round: Option<u32>,
1106
1107    /// Minimum interval between consecutive rounds of generated randomness.
1108    random_beacon_min_round_interval_ms: Option<u64>,
1109
1110    /// Version of the random beacon DKG protocol.
1111    /// 0 was deprecated (and currently not supported), 1 is the default
1112    /// version.
1113    random_beacon_dkg_version: Option<u64>,
1114
1115    /// The maximum serialized transaction size (in bytes) accepted by
1116    /// consensus. `consensus_max_transaction_size_bytes` should include
1117    /// space for additional metadata, on top of the `max_tx_size_bytes`
1118    /// value.
1119    consensus_max_transaction_size_bytes: Option<u64>,
1120    /// The maximum size of transactions included in a consensus block.
1121    consensus_max_transactions_in_block_bytes: Option<u64>,
1122    /// The maximum number of transactions included in a consensus block.
1123    consensus_max_num_transactions_in_block: Option<u64>,
1124
1125    /// The max number of consensus rounds a transaction can be deferred due to
1126    /// shared object congestion. Transactions will be cancelled after this
1127    /// many rounds.
1128    max_deferral_rounds_for_congestion_control: Option<u64>,
1129
1130    /// Minimum interval of commit timestamps between consecutive checkpoints.
1131    min_checkpoint_interval_ms: Option<u64>,
1132
1133    /// Version number to use for version_specific_data in `CheckpointSummary`.
1134    checkpoint_summary_version_specific_data: Option<u64>,
1135
1136    /// The max number of transactions that can be included in a single Soft
1137    /// Bundle.
1138    max_soft_bundle_size: Option<u64>,
1139
1140    /// Deprecated because of bridge removal.
1141    /// Whether to try to form bridge committee
1142    // Note: this is not a feature flag because we want to distinguish between
1143    // `None` and `Some(false)`, as committee was already finalized on Testnet.
1144    bridge_should_try_to_finalize_committee: Option<bool>,
1145
1146    /// The max accumulated txn execution cost per object in a mysticeti commit.
1147    /// Transactions in a commit will be deferred once their touch shared
1148    /// objects hit this limit. Note that if
1149    /// `max_congestion_limit_overshoot_per_commit` is set, this may be overshot
1150    /// within a single commit, but the limit will be enforced in the long run.
1151    max_accumulated_txn_cost_per_object_in_mysticeti_commit: Option<u64>,
1152
1153    /// Maximum number of committee (validators taking part in consensus)
1154    /// validators at any moment. We do not allow the number of committee
1155    /// validators in any epoch to go above this.
1156    max_committee_members_count: Option<u64>,
1157
1158    /// Configures the garbage collection depth for consensus. When is unset or
1159    /// `0` then the garbage collection is disabled.
1160    consensus_gc_depth: Option<u32>,
1161
1162    /// Configures the maximum number of acknowledgments to be included in a
1163    /// block. It must be reasonably larger than the number of validators
1164    /// because not all validators create their blocks at the same pace.
1165    /// Default value set to 400. (5 x expected committee size (80)).
1166    /// Applicable only to `starfish` consensus.
1167    consensus_max_acknowledgments_per_block: Option<u32>,
1168
1169    /// The maximum amount that is allowed to overshoot the congestion limit
1170    /// specified by 'max_accumulated_txn_cost_per_object_in_mysticeti_commit'
1171    /// for any single commit. Any overshoot is tracked as a debt that must
1172    /// be accounted for in subsequent commits.
1173    max_congestion_limit_overshoot_per_commit: Option<u64>,
1174}
1175
1176// feature flags
1177impl ProtocolConfig {
1178    // Add checks for feature flag support here, e.g.:
1179    // pub fn check_new_protocol_feature_supported(&self) -> Result<(), Error> {
1180    //     if self.feature_flags.new_protocol_feature_supported {
1181    //         Ok(())
1182    //     } else {
1183    //         Err(Error(format!(
1184    //             "new_protocol_feature is not supported at {:?}",
1185    //             self.version
1186    //         )))
1187    //     }
1188    // }
1189
1190    pub fn disable_invariant_violation_check_in_swap_loc(&self) -> bool {
1191        self.feature_flags
1192            .disable_invariant_violation_check_in_swap_loc
1193    }
1194
1195    pub fn no_extraneous_module_bytes(&self) -> bool {
1196        self.feature_flags.no_extraneous_module_bytes
1197    }
1198
1199    pub fn zklogin_auth(&self) -> bool {
1200        self.feature_flags.zklogin_auth
1201    }
1202
1203    pub fn consensus_transaction_ordering(&self) -> ConsensusTransactionOrdering {
1204        self.feature_flags.consensus_transaction_ordering
1205    }
1206
1207    pub fn enable_jwk_consensus_updates(&self) -> bool {
1208        self.feature_flags.enable_jwk_consensus_updates
1209    }
1210
1211    // this function only exists for readability in the genesis code.
1212    pub fn create_authenticator_state_in_genesis(&self) -> bool {
1213        self.enable_jwk_consensus_updates()
1214    }
1215
1216    pub fn dkg_version(&self) -> u64 {
1217        // Version 0 was deprecated and removed, the default is 1 if not set.
1218        self.random_beacon_dkg_version.unwrap_or(1)
1219    }
1220
1221    pub fn accept_zklogin_in_multisig(&self) -> bool {
1222        self.feature_flags.accept_zklogin_in_multisig
1223    }
1224
1225    pub fn zklogin_max_epoch_upper_bound_delta(&self) -> Option<u64> {
1226        self.feature_flags.zklogin_max_epoch_upper_bound_delta
1227    }
1228
1229    pub fn hardened_otw_check(&self) -> bool {
1230        self.feature_flags.hardened_otw_check
1231    }
1232
1233    pub fn enable_poseidon(&self) -> bool {
1234        self.feature_flags.enable_poseidon
1235    }
1236
1237    pub fn enable_group_ops_native_function_msm(&self) -> bool {
1238        self.feature_flags.enable_group_ops_native_function_msm
1239    }
1240
1241    pub fn per_object_congestion_control_mode(&self) -> PerObjectCongestionControlMode {
1242        self.feature_flags.per_object_congestion_control_mode
1243    }
1244
1245    pub fn consensus_choice(&self) -> ConsensusChoice {
1246        self.feature_flags.consensus_choice
1247    }
1248
1249    pub fn consensus_network(&self) -> ConsensusNetwork {
1250        self.feature_flags.consensus_network
1251    }
1252
1253    pub fn enable_vdf(&self) -> bool {
1254        self.feature_flags.enable_vdf
1255    }
1256
1257    pub fn passkey_auth(&self) -> bool {
1258        self.feature_flags.passkey_auth
1259    }
1260
1261    pub fn max_transaction_size_bytes(&self) -> u64 {
1262        // Provide a default value if protocol config version is too low.
1263        self.consensus_max_transaction_size_bytes
1264            .unwrap_or(256 * 1024)
1265    }
1266
1267    pub fn max_transactions_in_block_bytes(&self) -> u64 {
1268        if cfg!(msim) {
1269            256 * 1024
1270        } else {
1271            self.consensus_max_transactions_in_block_bytes
1272                .unwrap_or(512 * 1024)
1273        }
1274    }
1275
1276    pub fn max_num_transactions_in_block(&self) -> u64 {
1277        if cfg!(msim) {
1278            8
1279        } else {
1280            self.consensus_max_num_transactions_in_block.unwrap_or(512)
1281        }
1282    }
1283
1284    pub fn rethrow_serialization_type_layout_errors(&self) -> bool {
1285        self.feature_flags.rethrow_serialization_type_layout_errors
1286    }
1287
1288    pub fn relocate_event_module(&self) -> bool {
1289        self.feature_flags.relocate_event_module
1290    }
1291
1292    pub fn protocol_defined_base_fee(&self) -> bool {
1293        self.feature_flags.protocol_defined_base_fee
1294    }
1295
1296    pub fn uncompressed_g1_group_elements(&self) -> bool {
1297        self.feature_flags.uncompressed_g1_group_elements
1298    }
1299
1300    pub fn disallow_new_modules_in_deps_only_packages(&self) -> bool {
1301        self.feature_flags
1302            .disallow_new_modules_in_deps_only_packages
1303    }
1304
1305    pub fn native_charging_v2(&self) -> bool {
1306        self.feature_flags.native_charging_v2
1307    }
1308
1309    pub fn consensus_round_prober(&self) -> bool {
1310        self.feature_flags.consensus_round_prober
1311    }
1312
1313    pub fn consensus_distributed_vote_scoring_strategy(&self) -> bool {
1314        self.feature_flags
1315            .consensus_distributed_vote_scoring_strategy
1316    }
1317
1318    pub fn gc_depth(&self) -> u32 {
1319        if cfg!(msim) {
1320            // exercise a very low gc_depth
1321            min(5, self.consensus_gc_depth.unwrap_or(0))
1322        } else {
1323            self.consensus_gc_depth.unwrap_or(0)
1324        }
1325    }
1326
1327    pub fn consensus_linearize_subdag_v2(&self) -> bool {
1328        let res = self.feature_flags.consensus_linearize_subdag_v2;
1329        assert!(
1330            !res || self.gc_depth() > 0,
1331            "The consensus linearize sub dag V2 requires GC to be enabled"
1332        );
1333        res
1334    }
1335
1336    pub fn consensus_max_acknowledgments_per_block_or_default(&self) -> u32 {
1337        self.consensus_max_acknowledgments_per_block.unwrap_or(400)
1338    }
1339
1340    pub fn variant_nodes(&self) -> bool {
1341        self.feature_flags.variant_nodes
1342    }
1343
1344    pub fn consensus_smart_ancestor_selection(&self) -> bool {
1345        self.feature_flags.consensus_smart_ancestor_selection
1346    }
1347
1348    pub fn consensus_round_prober_probe_accepted_rounds(&self) -> bool {
1349        self.feature_flags
1350            .consensus_round_prober_probe_accepted_rounds
1351    }
1352
1353    pub fn consensus_zstd_compression(&self) -> bool {
1354        self.feature_flags.consensus_zstd_compression
1355    }
1356
1357    pub fn congestion_control_min_free_execution_slot(&self) -> bool {
1358        self.feature_flags
1359            .congestion_control_min_free_execution_slot
1360    }
1361
1362    pub fn accept_passkey_in_multisig(&self) -> bool {
1363        self.feature_flags.accept_passkey_in_multisig
1364    }
1365
1366    pub fn consensus_batched_block_sync(&self) -> bool {
1367        self.feature_flags.consensus_batched_block_sync
1368    }
1369
1370    /// Check if the gas price feedback mechanism (which is used for
1371    /// transactions cancelled due to shared object congestion) is enabled
1372    pub fn congestion_control_gas_price_feedback_mechanism(&self) -> bool {
1373        self.feature_flags
1374            .congestion_control_gas_price_feedback_mechanism
1375    }
1376
1377    pub fn validate_identifier_inputs(&self) -> bool {
1378        self.feature_flags.validate_identifier_inputs
1379    }
1380
1381    pub fn minimize_child_object_mutations(&self) -> bool {
1382        self.feature_flags.minimize_child_object_mutations
1383    }
1384
1385    pub fn dependency_linkage_error(&self) -> bool {
1386        self.feature_flags.dependency_linkage_error
1387    }
1388
1389    pub fn additional_multisig_checks(&self) -> bool {
1390        self.feature_flags.additional_multisig_checks
1391    }
1392
1393    pub fn consensus_num_requested_prior_commits_at_startup(&self) -> u32 {
1394        // TODO: this will eventually be the max of some number of other
1395        // parameters.
1396        0
1397    }
1398
1399    pub fn normalize_ptb_arguments(&self) -> bool {
1400        self.feature_flags.normalize_ptb_arguments
1401    }
1402
1403    pub fn select_committee_from_eligible_validators(&self) -> bool {
1404        let res = self.feature_flags.select_committee_from_eligible_validators;
1405        assert!(
1406            !res || (self.protocol_defined_base_fee()
1407                && self.max_committee_members_count_as_option().is_some()),
1408            "select_committee_from_eligible_validators requires protocol_defined_base_fee and max_committee_members_count to be set"
1409        );
1410        res
1411    }
1412
1413    pub fn track_non_committee_eligible_validators(&self) -> bool {
1414        self.feature_flags.track_non_committee_eligible_validators
1415    }
1416
1417    pub fn select_committee_supporting_next_epoch_version(&self) -> bool {
1418        let res = self
1419            .feature_flags
1420            .select_committee_supporting_next_epoch_version;
1421        assert!(
1422            !res || (self.track_non_committee_eligible_validators()
1423                && self.select_committee_from_eligible_validators()),
1424            "select_committee_supporting_next_epoch_version requires select_committee_from_eligible_validators to be set"
1425        );
1426        res
1427    }
1428
1429    pub fn consensus_median_timestamp_with_checkpoint_enforcement(&self) -> bool {
1430        let res = self
1431            .feature_flags
1432            .consensus_median_timestamp_with_checkpoint_enforcement;
1433        assert!(
1434            !res || self.gc_depth() > 0,
1435            "The consensus median timestamp with checkpoint enforcement requires GC to be enabled"
1436        );
1437        res
1438    }
1439}
1440
1441#[cfg(not(msim))]
1442static POISON_VERSION_METHODS: AtomicBool = const { AtomicBool::new(false) };
1443
1444// Use a thread local in sim tests for test isolation.
1445#[cfg(msim)]
1446thread_local! {
1447    static POISON_VERSION_METHODS: AtomicBool = const { AtomicBool::new(false) };
1448}
1449
1450// Instantiations for each protocol version.
1451impl ProtocolConfig {
1452    /// Get the value ProtocolConfig that are in effect during the given
1453    /// protocol version.
1454    pub fn get_for_version(version: ProtocolVersion, chain: Chain) -> Self {
1455        // ProtocolVersion can be deserialized so we need to check it here as well.
1456        assert!(
1457            version >= ProtocolVersion::MIN,
1458            "Network protocol version is {:?}, but the minimum supported version by the binary is {:?}. Please upgrade the binary.",
1459            version,
1460            ProtocolVersion::MIN.0,
1461        );
1462        assert!(
1463            version <= ProtocolVersion::MAX_ALLOWED,
1464            "Network protocol version is {:?}, but the maximum supported version by the binary is {:?}. Please upgrade the binary.",
1465            version,
1466            ProtocolVersion::MAX_ALLOWED.0,
1467        );
1468
1469        let mut ret = Self::get_for_version_impl(version, chain);
1470        ret.version = version;
1471
1472        ret = CONFIG_OVERRIDE.with(|ovr| {
1473            if let Some(override_fn) = &*ovr.borrow() {
1474                warn!(
1475                    "overriding ProtocolConfig settings with custom settings (you should not see this log outside of tests)"
1476                );
1477                override_fn(version, ret)
1478            } else {
1479                ret
1480            }
1481        });
1482
1483        if std::env::var("IOTA_PROTOCOL_CONFIG_OVERRIDE_ENABLE").is_ok() {
1484            warn!(
1485                "overriding ProtocolConfig settings with custom settings; this may break non-local networks"
1486            );
1487            let overrides: ProtocolConfigOptional =
1488                serde_env::from_env_with_prefix("IOTA_PROTOCOL_CONFIG_OVERRIDE")
1489                    .expect("failed to parse ProtocolConfig override env variables");
1490            overrides.apply_to(&mut ret);
1491        }
1492
1493        ret
1494    }
1495
1496    /// Get the value ProtocolConfig that are in effect during the given
1497    /// protocol version. Or none if the version is not supported.
1498    pub fn get_for_version_if_supported(version: ProtocolVersion, chain: Chain) -> Option<Self> {
1499        if version.0 >= ProtocolVersion::MIN.0 && version.0 <= ProtocolVersion::MAX_ALLOWED.0 {
1500            let mut ret = Self::get_for_version_impl(version, chain);
1501            ret.version = version;
1502            Some(ret)
1503        } else {
1504            None
1505        }
1506    }
1507
1508    #[cfg(not(msim))]
1509    pub fn poison_get_for_min_version() {
1510        POISON_VERSION_METHODS.store(true, Ordering::Relaxed);
1511    }
1512
1513    #[cfg(not(msim))]
1514    fn load_poison_get_for_min_version() -> bool {
1515        POISON_VERSION_METHODS.load(Ordering::Relaxed)
1516    }
1517
1518    #[cfg(msim)]
1519    pub fn poison_get_for_min_version() {
1520        POISON_VERSION_METHODS.with(|p| p.store(true, Ordering::Relaxed));
1521    }
1522
1523    #[cfg(msim)]
1524    fn load_poison_get_for_min_version() -> bool {
1525        POISON_VERSION_METHODS.with(|p| p.load(Ordering::Relaxed))
1526    }
1527
1528    pub fn convert_type_argument_error(&self) -> bool {
1529        self.feature_flags.convert_type_argument_error
1530    }
1531
1532    /// Convenience to get the constants at the current minimum supported
1533    /// version. Mainly used by client code that may not yet be
1534    /// protocol-version aware.
1535    pub fn get_for_min_version() -> Self {
1536        if Self::load_poison_get_for_min_version() {
1537            panic!("get_for_min_version called on validator");
1538        }
1539        ProtocolConfig::get_for_version(ProtocolVersion::MIN, Chain::Unknown)
1540    }
1541
1542    /// CAREFUL! - You probably want to use `get_for_version` instead.
1543    ///
1544    /// Convenience to get the constants at the current maximum supported
1545    /// version. Mainly used by genesis. Note well that this function uses
1546    /// the max version supported locally by the node, which is not
1547    /// necessarily the current version of the network. ALSO, this function
1548    /// disregards chain specific config (by using Chain::Unknown), thereby
1549    /// potentially returning a protocol config that is incorrect for some
1550    /// feature flags. Definitely safe for testing and for protocol version
1551    /// 11 and prior.
1552    #[expect(non_snake_case)]
1553    pub fn get_for_max_version_UNSAFE() -> Self {
1554        if Self::load_poison_get_for_min_version() {
1555            panic!("get_for_max_version_UNSAFE called on validator");
1556        }
1557        ProtocolConfig::get_for_version(ProtocolVersion::MAX, Chain::Unknown)
1558    }
1559
1560    fn get_for_version_impl(version: ProtocolVersion, chain: Chain) -> Self {
1561        #[cfg(msim)]
1562        {
1563            // populate the fake simulator version # with a different base tx cost.
1564            if version > ProtocolVersion::MAX {
1565                let mut config = Self::get_for_version_impl(ProtocolVersion::MAX, Chain::Unknown);
1566                config.base_tx_cost_fixed = Some(config.base_tx_cost_fixed() + 1000);
1567                return config;
1568            }
1569        }
1570
1571        // IMPORTANT: Never modify the value of any constant for a pre-existing protocol
1572        // version. To change the values here you must create a new protocol
1573        // version with the new values!
1574        let mut cfg = Self {
1575            version,
1576
1577            feature_flags: Default::default(),
1578
1579            max_tx_size_bytes: Some(128 * 1024),
1580            // We need this number to be at least 100x less than
1581            // `max_serialized_tx_effects_size_bytes`otherwise effects can be huge
1582            max_input_objects: Some(2048),
1583            max_serialized_tx_effects_size_bytes: Some(512 * 1024),
1584            max_serialized_tx_effects_size_bytes_system_tx: Some(512 * 1024 * 16),
1585            max_gas_payment_objects: Some(256),
1586            max_modules_in_publish: Some(64),
1587            max_package_dependencies: Some(32),
1588            max_arguments: Some(512),
1589            max_type_arguments: Some(16),
1590            max_type_argument_depth: Some(16),
1591            max_pure_argument_size: Some(16 * 1024),
1592            max_programmable_tx_commands: Some(1024),
1593            move_binary_format_version: Some(7),
1594            min_move_binary_format_version: Some(6),
1595            binary_module_handles: Some(100),
1596            binary_struct_handles: Some(300),
1597            binary_function_handles: Some(1500),
1598            binary_function_instantiations: Some(750),
1599            binary_signatures: Some(1000),
1600            binary_constant_pool: Some(4000),
1601            binary_identifiers: Some(10000),
1602            binary_address_identifiers: Some(100),
1603            binary_struct_defs: Some(200),
1604            binary_struct_def_instantiations: Some(100),
1605            binary_function_defs: Some(1000),
1606            binary_field_handles: Some(500),
1607            binary_field_instantiations: Some(250),
1608            binary_friend_decls: Some(100),
1609            binary_enum_defs: None,
1610            binary_enum_def_instantiations: None,
1611            binary_variant_handles: None,
1612            binary_variant_instantiation_handles: None,
1613            max_move_object_size: Some(250 * 1024),
1614            max_move_package_size: Some(100 * 1024),
1615            max_publish_or_upgrade_per_ptb: Some(5),
1616            // max gas budget is in NANOS and an absolute value 50IOTA
1617            max_tx_gas: Some(50_000_000_000),
1618            max_gas_price: Some(100_000),
1619            max_gas_computation_bucket: Some(5_000_000),
1620            max_loop_depth: Some(5),
1621            max_generic_instantiation_length: Some(32),
1622            max_function_parameters: Some(128),
1623            max_basic_blocks: Some(1024),
1624            max_value_stack_size: Some(1024),
1625            max_type_nodes: Some(256),
1626            max_push_size: Some(10000),
1627            max_struct_definitions: Some(200),
1628            max_function_definitions: Some(1000),
1629            max_fields_in_struct: Some(32),
1630            max_dependency_depth: Some(100),
1631            max_num_event_emit: Some(1024),
1632            max_num_new_move_object_ids: Some(2048),
1633            max_num_new_move_object_ids_system_tx: Some(2048 * 16),
1634            max_num_deleted_move_object_ids: Some(2048),
1635            max_num_deleted_move_object_ids_system_tx: Some(2048 * 16),
1636            max_num_transferred_move_object_ids: Some(2048),
1637            max_num_transferred_move_object_ids_system_tx: Some(2048 * 16),
1638            max_event_emit_size: Some(250 * 1024),
1639            max_move_vector_len: Some(256 * 1024),
1640            max_type_to_layout_nodes: None,
1641            max_ptb_value_size: None,
1642
1643            max_back_edges_per_function: Some(10_000),
1644            max_back_edges_per_module: Some(10_000),
1645
1646            max_verifier_meter_ticks_per_function: Some(16_000_000),
1647
1648            max_meter_ticks_per_module: Some(16_000_000),
1649            max_meter_ticks_per_package: Some(16_000_000),
1650
1651            object_runtime_max_num_cached_objects: Some(1000),
1652            object_runtime_max_num_cached_objects_system_tx: Some(1000 * 16),
1653            object_runtime_max_num_store_entries: Some(1000),
1654            object_runtime_max_num_store_entries_system_tx: Some(1000 * 16),
1655            // min gas budget is in NANOS and an absolute value 1000 NANOS or 0.000001IOTA
1656            base_tx_cost_fixed: Some(1_000),
1657            package_publish_cost_fixed: Some(1_000),
1658            base_tx_cost_per_byte: Some(0),
1659            package_publish_cost_per_byte: Some(80),
1660            obj_access_cost_read_per_byte: Some(15),
1661            obj_access_cost_mutate_per_byte: Some(40),
1662            obj_access_cost_delete_per_byte: Some(40),
1663            obj_access_cost_verify_per_byte: Some(200),
1664            obj_data_cost_refundable: Some(100),
1665            obj_metadata_cost_non_refundable: Some(50),
1666            gas_model_version: Some(1),
1667            storage_rebate_rate: Some(10000),
1668            // Change reward slashing rate to 100%.
1669            reward_slashing_rate: Some(10000),
1670            storage_gas_price: Some(76),
1671            base_gas_price: None,
1672            // The initial subsidy (target reward) for validators per epoch.
1673            // Refer to the IOTA tokenomics for the origin of this value.
1674            validator_target_reward: Some(767_000 * 1_000_000_000),
1675            max_transactions_per_checkpoint: Some(10_000),
1676            max_checkpoint_size_bytes: Some(30 * 1024 * 1024),
1677
1678            // For now, perform upgrades with a bare quorum of validators.
1679            buffer_stake_for_protocol_upgrade_bps: Some(5000),
1680
1681            // === Native Function Costs ===
1682            // `address` module
1683            // Cost params for the Move native function `address::from_bytes(bytes: vector<u8>)`
1684            address_from_bytes_cost_base: Some(52),
1685            // Cost params for the Move native function `address::to_u256(address): u256`
1686            address_to_u256_cost_base: Some(52),
1687            // Cost params for the Move native function `address::from_u256(u256): address`
1688            address_from_u256_cost_base: Some(52),
1689
1690            // `config` module
1691            // Cost params for the Move native function `read_setting_impl``
1692            config_read_setting_impl_cost_base: Some(100),
1693            config_read_setting_impl_cost_per_byte: Some(40),
1694
1695            // `dynamic_field` module
1696            // Cost params for the Move native function `hash_type_and_key<K: copy + drop +
1697            // store>(parent: address, k: K): address`
1698            dynamic_field_hash_type_and_key_cost_base: Some(100),
1699            dynamic_field_hash_type_and_key_type_cost_per_byte: Some(2),
1700            dynamic_field_hash_type_and_key_value_cost_per_byte: Some(2),
1701            dynamic_field_hash_type_and_key_type_tag_cost_per_byte: Some(2),
1702            // Cost params for the Move native function `add_child_object<Child: key>(parent:
1703            // address, child: Child)`
1704            dynamic_field_add_child_object_cost_base: Some(100),
1705            dynamic_field_add_child_object_type_cost_per_byte: Some(10),
1706            dynamic_field_add_child_object_value_cost_per_byte: Some(10),
1707            dynamic_field_add_child_object_struct_tag_cost_per_byte: Some(10),
1708            // Cost params for the Move native function `borrow_child_object_mut<Child: key>(parent:
1709            // &mut UID, id: address): &mut Child`
1710            dynamic_field_borrow_child_object_cost_base: Some(100),
1711            dynamic_field_borrow_child_object_child_ref_cost_per_byte: Some(10),
1712            dynamic_field_borrow_child_object_type_cost_per_byte: Some(10),
1713            // Cost params for the Move native function `remove_child_object<Child: key>(parent:
1714            // address, id: address): Child`
1715            dynamic_field_remove_child_object_cost_base: Some(100),
1716            dynamic_field_remove_child_object_child_cost_per_byte: Some(2),
1717            dynamic_field_remove_child_object_type_cost_per_byte: Some(2),
1718            // Cost params for the Move native function `has_child_object(parent: address, id:
1719            // address): bool`
1720            dynamic_field_has_child_object_cost_base: Some(100),
1721            // Cost params for the Move native function `has_child_object_with_ty<Child:
1722            // key>(parent: address, id: address): bool`
1723            dynamic_field_has_child_object_with_ty_cost_base: Some(100),
1724            dynamic_field_has_child_object_with_ty_type_cost_per_byte: Some(2),
1725            dynamic_field_has_child_object_with_ty_type_tag_cost_per_byte: Some(2),
1726
1727            // `event` module
1728            // Cost params for the Move native function `event::emit<T: copy + drop>(event: T)`
1729            event_emit_cost_base: Some(52),
1730            event_emit_value_size_derivation_cost_per_byte: Some(2),
1731            event_emit_tag_size_derivation_cost_per_byte: Some(5),
1732            event_emit_output_cost_per_byte: Some(10),
1733
1734            //  `object` module
1735            // Cost params for the Move native function `borrow_uid<T: key>(obj: &T): &UID`
1736            object_borrow_uid_cost_base: Some(52),
1737            // Cost params for the Move native function `delete_impl(id: address)`
1738            object_delete_impl_cost_base: Some(52),
1739            // Cost params for the Move native function `record_new_uid(id: address)`
1740            object_record_new_uid_cost_base: Some(52),
1741
1742            // `transfer` module
1743            // Cost params for the Move native function `transfer_impl<T: key>(obj: T, recipient:
1744            // address)`
1745            transfer_transfer_internal_cost_base: Some(52),
1746            // Cost params for the Move native function `freeze_object<T: key>(obj: T)`
1747            transfer_freeze_object_cost_base: Some(52),
1748            // Cost params for the Move native function `share_object<T: key>(obj: T)`
1749            transfer_share_object_cost_base: Some(52),
1750            transfer_receive_object_cost_base: Some(52),
1751
1752            // `tx_context` module
1753            // Cost params for the Move native function `transfer_impl<T: key>(obj: T, recipient:
1754            // address)`
1755            tx_context_derive_id_cost_base: Some(52),
1756
1757            // `types` module
1758            // Cost params for the Move native function `is_one_time_witness<T: drop>(_: &T): bool`
1759            types_is_one_time_witness_cost_base: Some(52),
1760            types_is_one_time_witness_type_tag_cost_per_byte: Some(2),
1761            types_is_one_time_witness_type_cost_per_byte: Some(2),
1762
1763            // `validator` module
1764            // Cost params for the Move native function `validate_metadata_bcs(metadata:
1765            // vector<u8>)`
1766            validator_validate_metadata_cost_base: Some(52),
1767            validator_validate_metadata_data_cost_per_byte: Some(2),
1768
1769            // Crypto
1770            crypto_invalid_arguments_cost: Some(100),
1771            // bls12381::bls12381_min_pk_verify
1772            bls12381_bls12381_min_sig_verify_cost_base: Some(52),
1773            bls12381_bls12381_min_sig_verify_msg_cost_per_byte: Some(2),
1774            bls12381_bls12381_min_sig_verify_msg_cost_per_block: Some(2),
1775
1776            // bls12381::bls12381_min_pk_verify
1777            bls12381_bls12381_min_pk_verify_cost_base: Some(52),
1778            bls12381_bls12381_min_pk_verify_msg_cost_per_byte: Some(2),
1779            bls12381_bls12381_min_pk_verify_msg_cost_per_block: Some(2),
1780
1781            // ecdsa_k1::ecrecover
1782            ecdsa_k1_ecrecover_keccak256_cost_base: Some(52),
1783            ecdsa_k1_ecrecover_keccak256_msg_cost_per_byte: Some(2),
1784            ecdsa_k1_ecrecover_keccak256_msg_cost_per_block: Some(2),
1785            ecdsa_k1_ecrecover_sha256_cost_base: Some(52),
1786            ecdsa_k1_ecrecover_sha256_msg_cost_per_byte: Some(2),
1787            ecdsa_k1_ecrecover_sha256_msg_cost_per_block: Some(2),
1788
1789            // ecdsa_k1::decompress_pubkey
1790            ecdsa_k1_decompress_pubkey_cost_base: Some(52),
1791
1792            // ecdsa_k1::secp256k1_verify
1793            ecdsa_k1_secp256k1_verify_keccak256_cost_base: Some(52),
1794            ecdsa_k1_secp256k1_verify_keccak256_msg_cost_per_byte: Some(2),
1795            ecdsa_k1_secp256k1_verify_keccak256_msg_cost_per_block: Some(2),
1796            ecdsa_k1_secp256k1_verify_sha256_cost_base: Some(52),
1797            ecdsa_k1_secp256k1_verify_sha256_msg_cost_per_byte: Some(2),
1798            ecdsa_k1_secp256k1_verify_sha256_msg_cost_per_block: Some(2),
1799
1800            // ecdsa_r1::ecrecover
1801            ecdsa_r1_ecrecover_keccak256_cost_base: Some(52),
1802            ecdsa_r1_ecrecover_keccak256_msg_cost_per_byte: Some(2),
1803            ecdsa_r1_ecrecover_keccak256_msg_cost_per_block: Some(2),
1804            ecdsa_r1_ecrecover_sha256_cost_base: Some(52),
1805            ecdsa_r1_ecrecover_sha256_msg_cost_per_byte: Some(2),
1806            ecdsa_r1_ecrecover_sha256_msg_cost_per_block: Some(2),
1807
1808            // ecdsa_r1::secp256k1_verify
1809            ecdsa_r1_secp256r1_verify_keccak256_cost_base: Some(52),
1810            ecdsa_r1_secp256r1_verify_keccak256_msg_cost_per_byte: Some(2),
1811            ecdsa_r1_secp256r1_verify_keccak256_msg_cost_per_block: Some(2),
1812            ecdsa_r1_secp256r1_verify_sha256_cost_base: Some(52),
1813            ecdsa_r1_secp256r1_verify_sha256_msg_cost_per_byte: Some(2),
1814            ecdsa_r1_secp256r1_verify_sha256_msg_cost_per_block: Some(2),
1815
1816            // ecvrf::verify
1817            ecvrf_ecvrf_verify_cost_base: Some(52),
1818            ecvrf_ecvrf_verify_alpha_string_cost_per_byte: Some(2),
1819            ecvrf_ecvrf_verify_alpha_string_cost_per_block: Some(2),
1820
1821            // ed25519
1822            ed25519_ed25519_verify_cost_base: Some(52),
1823            ed25519_ed25519_verify_msg_cost_per_byte: Some(2),
1824            ed25519_ed25519_verify_msg_cost_per_block: Some(2),
1825
1826            // groth16::prepare_verifying_key
1827            groth16_prepare_verifying_key_bls12381_cost_base: Some(52),
1828            groth16_prepare_verifying_key_bn254_cost_base: Some(52),
1829
1830            // groth16::verify_groth16_proof_internal
1831            groth16_verify_groth16_proof_internal_bls12381_cost_base: Some(52),
1832            groth16_verify_groth16_proof_internal_bls12381_cost_per_public_input: Some(2),
1833            groth16_verify_groth16_proof_internal_bn254_cost_base: Some(52),
1834            groth16_verify_groth16_proof_internal_bn254_cost_per_public_input: Some(2),
1835            groth16_verify_groth16_proof_internal_public_input_cost_per_byte: Some(2),
1836
1837            // hash::blake2b256
1838            hash_blake2b256_cost_base: Some(52),
1839            hash_blake2b256_data_cost_per_byte: Some(2),
1840            hash_blake2b256_data_cost_per_block: Some(2),
1841            // hash::keccak256
1842            hash_keccak256_cost_base: Some(52),
1843            hash_keccak256_data_cost_per_byte: Some(2),
1844            hash_keccak256_data_cost_per_block: Some(2),
1845
1846            poseidon_bn254_cost_base: None,
1847            poseidon_bn254_cost_per_block: None,
1848
1849            // hmac::hmac_sha3_256
1850            hmac_hmac_sha3_256_cost_base: Some(52),
1851            hmac_hmac_sha3_256_input_cost_per_byte: Some(2),
1852            hmac_hmac_sha3_256_input_cost_per_block: Some(2),
1853
1854            // group ops
1855            group_ops_bls12381_decode_scalar_cost: Some(52),
1856            group_ops_bls12381_decode_g1_cost: Some(52),
1857            group_ops_bls12381_decode_g2_cost: Some(52),
1858            group_ops_bls12381_decode_gt_cost: Some(52),
1859            group_ops_bls12381_scalar_add_cost: Some(52),
1860            group_ops_bls12381_g1_add_cost: Some(52),
1861            group_ops_bls12381_g2_add_cost: Some(52),
1862            group_ops_bls12381_gt_add_cost: Some(52),
1863            group_ops_bls12381_scalar_sub_cost: Some(52),
1864            group_ops_bls12381_g1_sub_cost: Some(52),
1865            group_ops_bls12381_g2_sub_cost: Some(52),
1866            group_ops_bls12381_gt_sub_cost: Some(52),
1867            group_ops_bls12381_scalar_mul_cost: Some(52),
1868            group_ops_bls12381_g1_mul_cost: Some(52),
1869            group_ops_bls12381_g2_mul_cost: Some(52),
1870            group_ops_bls12381_gt_mul_cost: Some(52),
1871            group_ops_bls12381_scalar_div_cost: Some(52),
1872            group_ops_bls12381_g1_div_cost: Some(52),
1873            group_ops_bls12381_g2_div_cost: Some(52),
1874            group_ops_bls12381_gt_div_cost: Some(52),
1875            group_ops_bls12381_g1_hash_to_base_cost: Some(52),
1876            group_ops_bls12381_g2_hash_to_base_cost: Some(52),
1877            group_ops_bls12381_g1_hash_to_cost_per_byte: Some(2),
1878            group_ops_bls12381_g2_hash_to_cost_per_byte: Some(2),
1879            group_ops_bls12381_g1_msm_base_cost: Some(52),
1880            group_ops_bls12381_g2_msm_base_cost: Some(52),
1881            group_ops_bls12381_g1_msm_base_cost_per_input: Some(52),
1882            group_ops_bls12381_g2_msm_base_cost_per_input: Some(52),
1883            group_ops_bls12381_msm_max_len: Some(32),
1884            group_ops_bls12381_pairing_cost: Some(52),
1885            group_ops_bls12381_g1_to_uncompressed_g1_cost: None,
1886            group_ops_bls12381_uncompressed_g1_to_g1_cost: None,
1887            group_ops_bls12381_uncompressed_g1_sum_base_cost: None,
1888            group_ops_bls12381_uncompressed_g1_sum_cost_per_term: None,
1889            group_ops_bls12381_uncompressed_g1_sum_max_terms: None,
1890
1891            // zklogin::check_zklogin_id
1892            check_zklogin_id_cost_base: Some(200),
1893            // zklogin::check_zklogin_issuer
1894            check_zklogin_issuer_cost_base: Some(200),
1895
1896            vdf_verify_vdf_cost: None,
1897            vdf_hash_to_input_cost: None,
1898
1899            bcs_per_byte_serialized_cost: Some(2),
1900            bcs_legacy_min_output_size_cost: Some(1),
1901            bcs_failure_cost: Some(52),
1902            hash_sha2_256_base_cost: Some(52),
1903            hash_sha2_256_per_byte_cost: Some(2),
1904            hash_sha2_256_legacy_min_input_len_cost: Some(1),
1905            hash_sha3_256_base_cost: Some(52),
1906            hash_sha3_256_per_byte_cost: Some(2),
1907            hash_sha3_256_legacy_min_input_len_cost: Some(1),
1908            type_name_get_base_cost: Some(52),
1909            type_name_get_per_byte_cost: Some(2),
1910            string_check_utf8_base_cost: Some(52),
1911            string_check_utf8_per_byte_cost: Some(2),
1912            string_is_char_boundary_base_cost: Some(52),
1913            string_sub_string_base_cost: Some(52),
1914            string_sub_string_per_byte_cost: Some(2),
1915            string_index_of_base_cost: Some(52),
1916            string_index_of_per_byte_pattern_cost: Some(2),
1917            string_index_of_per_byte_searched_cost: Some(2),
1918            vector_empty_base_cost: Some(52),
1919            vector_length_base_cost: Some(52),
1920            vector_push_back_base_cost: Some(52),
1921            vector_push_back_legacy_per_abstract_memory_unit_cost: Some(2),
1922            vector_borrow_base_cost: Some(52),
1923            vector_pop_back_base_cost: Some(52),
1924            vector_destroy_empty_base_cost: Some(52),
1925            vector_swap_base_cost: Some(52),
1926            debug_print_base_cost: Some(52),
1927            debug_print_stack_trace_base_cost: Some(52),
1928
1929            max_size_written_objects: Some(5 * 1000 * 1000),
1930            // max size of written objects during a system TXn to allow for larger writes
1931            // akin to `max_size_written_objects` but for system TXns
1932            max_size_written_objects_system_tx: Some(50 * 1000 * 1000),
1933
1934            // Limits the length of a Move identifier
1935            max_move_identifier_len: Some(128),
1936            max_move_value_depth: Some(128),
1937            max_move_enum_variants: None,
1938
1939            gas_rounding_step: Some(1_000),
1940
1941            execution_version: Some(1),
1942
1943            // We maintain the same total size limit for events, but increase the number of
1944            // events that can be emitted.
1945            max_event_emit_size_total: Some(
1946                256 /* former event count limit */ * 250 * 1024, // size limit per event
1947            ),
1948
1949            // Taking a baby step approach, we consider only 20% by stake as bad nodes so we
1950            // have a 80% by stake of nodes participating in the leader committee. That
1951            // allow us for more redundancy in case we have validators
1952            // under performing - since the responsibility is shared
1953            // amongst more nodes. We can increase that once we do have
1954            // higher confidence.
1955            consensus_bad_nodes_stake_threshold: Some(20),
1956
1957            // Max of 10 votes per hour.
1958            max_jwk_votes_per_validator_per_epoch: Some(240),
1959
1960            max_age_of_jwk_in_epochs: Some(1),
1961
1962            consensus_max_transaction_size_bytes: Some(256 * 1024), // 256KB
1963
1964            // Assume 1KB per transaction and 500 transactions per block.
1965            consensus_max_transactions_in_block_bytes: Some(512 * 1024),
1966
1967            random_beacon_reduction_allowed_delta: Some(800),
1968
1969            random_beacon_reduction_lower_bound: Some(1000),
1970            random_beacon_dkg_timeout_round: Some(3000),
1971            random_beacon_min_round_interval_ms: Some(500),
1972
1973            random_beacon_dkg_version: Some(1),
1974
1975            // Assume 20_000 TPS * 5% max stake per validator / (minimum) 4 blocks per round
1976            // = 250 transactions per block maximum Using a higher limit
1977            // that is 512, to account for bursty traffic and system transactions.
1978            consensus_max_num_transactions_in_block: Some(512),
1979
1980            max_deferral_rounds_for_congestion_control: Some(10),
1981
1982            min_checkpoint_interval_ms: Some(200),
1983
1984            checkpoint_summary_version_specific_data: Some(1),
1985
1986            max_soft_bundle_size: Some(5),
1987
1988            bridge_should_try_to_finalize_committee: None,
1989
1990            max_accumulated_txn_cost_per_object_in_mysticeti_commit: Some(10),
1991
1992            max_committee_members_count: None,
1993
1994            consensus_gc_depth: None,
1995
1996            consensus_max_acknowledgments_per_block: None,
1997
1998            max_congestion_limit_overshoot_per_commit: None,
1999            // When adding a new constant, set it to None in the earliest version, like this:
2000            // new_constant: None,
2001        };
2002
2003        cfg.feature_flags.consensus_transaction_ordering = ConsensusTransactionOrdering::ByGasPrice;
2004
2005        // MoveVM related flags
2006        {
2007            cfg.feature_flags
2008                .disable_invariant_violation_check_in_swap_loc = true;
2009            cfg.feature_flags.no_extraneous_module_bytes = true;
2010            cfg.feature_flags.hardened_otw_check = true;
2011            cfg.feature_flags.rethrow_serialization_type_layout_errors = true;
2012        }
2013
2014        // zkLogin related flags
2015        {
2016            cfg.feature_flags.zklogin_max_epoch_upper_bound_delta = Some(30);
2017        }
2018
2019        // Enable Mysticeti on mainnet.
2020        cfg.feature_flags.consensus_choice = ConsensusChoice::Mysticeti;
2021        // Use tonic networking for Mysticeti.
2022        cfg.feature_flags.consensus_network = ConsensusNetwork::Tonic;
2023
2024        cfg.feature_flags.per_object_congestion_control_mode =
2025            PerObjectCongestionControlMode::TotalTxCount;
2026
2027        // Do not allow bridge committee to finalize on mainnet.
2028        cfg.bridge_should_try_to_finalize_committee = Some(chain != Chain::Mainnet);
2029
2030        // Devnet
2031        if chain != Chain::Mainnet && chain != Chain::Testnet {
2032            cfg.feature_flags.enable_poseidon = true;
2033            cfg.poseidon_bn254_cost_base = Some(260);
2034            cfg.poseidon_bn254_cost_per_block = Some(10);
2035
2036            cfg.feature_flags.enable_group_ops_native_function_msm = true;
2037
2038            cfg.feature_flags.enable_vdf = true;
2039            // Set to 30x and 2x the cost of a signature verification for now. This
2040            // should be updated along with other native crypto functions.
2041            cfg.vdf_verify_vdf_cost = Some(1500);
2042            cfg.vdf_hash_to_input_cost = Some(100);
2043
2044            cfg.feature_flags.passkey_auth = true;
2045        }
2046
2047        for cur in 2..=version.0 {
2048            match cur {
2049                1 => unreachable!(),
2050                // version 2 is a new framework version but with no config changes
2051                2 => {}
2052                3 => {
2053                    cfg.feature_flags.relocate_event_module = true;
2054                }
2055                4 => {
2056                    cfg.max_type_to_layout_nodes = Some(512);
2057                }
2058                5 => {
2059                    cfg.feature_flags.protocol_defined_base_fee = true;
2060                    cfg.base_gas_price = Some(1000);
2061
2062                    cfg.feature_flags.disallow_new_modules_in_deps_only_packages = true;
2063                    cfg.feature_flags.convert_type_argument_error = true;
2064                    cfg.feature_flags.native_charging_v2 = true;
2065
2066                    if chain != Chain::Mainnet && chain != Chain::Testnet {
2067                        cfg.feature_flags.uncompressed_g1_group_elements = true;
2068                    }
2069
2070                    cfg.gas_model_version = Some(2);
2071
2072                    cfg.poseidon_bn254_cost_per_block = Some(388);
2073
2074                    cfg.bls12381_bls12381_min_sig_verify_cost_base = Some(44064);
2075                    cfg.bls12381_bls12381_min_pk_verify_cost_base = Some(49282);
2076                    cfg.ecdsa_k1_secp256k1_verify_keccak256_cost_base = Some(1470);
2077                    cfg.ecdsa_k1_secp256k1_verify_sha256_cost_base = Some(1470);
2078                    cfg.ecdsa_r1_secp256r1_verify_sha256_cost_base = Some(4225);
2079                    cfg.ecdsa_r1_secp256r1_verify_keccak256_cost_base = Some(4225);
2080                    cfg.ecvrf_ecvrf_verify_cost_base = Some(4848);
2081                    cfg.ed25519_ed25519_verify_cost_base = Some(1802);
2082
2083                    // Manually changed to be "under cost"
2084                    cfg.ecdsa_r1_ecrecover_keccak256_cost_base = Some(1173);
2085                    cfg.ecdsa_r1_ecrecover_sha256_cost_base = Some(1173);
2086                    cfg.ecdsa_k1_ecrecover_keccak256_cost_base = Some(500);
2087                    cfg.ecdsa_k1_ecrecover_sha256_cost_base = Some(500);
2088
2089                    cfg.groth16_prepare_verifying_key_bls12381_cost_base = Some(53838);
2090                    cfg.groth16_prepare_verifying_key_bn254_cost_base = Some(82010);
2091                    cfg.groth16_verify_groth16_proof_internal_bls12381_cost_base = Some(72090);
2092                    cfg.groth16_verify_groth16_proof_internal_bls12381_cost_per_public_input =
2093                        Some(8213);
2094                    cfg.groth16_verify_groth16_proof_internal_bn254_cost_base = Some(115502);
2095                    cfg.groth16_verify_groth16_proof_internal_bn254_cost_per_public_input =
2096                        Some(9484);
2097
2098                    cfg.hash_keccak256_cost_base = Some(10);
2099                    cfg.hash_blake2b256_cost_base = Some(10);
2100
2101                    // group ops
2102                    cfg.group_ops_bls12381_decode_scalar_cost = Some(7);
2103                    cfg.group_ops_bls12381_decode_g1_cost = Some(2848);
2104                    cfg.group_ops_bls12381_decode_g2_cost = Some(3770);
2105                    cfg.group_ops_bls12381_decode_gt_cost = Some(3068);
2106
2107                    cfg.group_ops_bls12381_scalar_add_cost = Some(10);
2108                    cfg.group_ops_bls12381_g1_add_cost = Some(1556);
2109                    cfg.group_ops_bls12381_g2_add_cost = Some(3048);
2110                    cfg.group_ops_bls12381_gt_add_cost = Some(188);
2111
2112                    cfg.group_ops_bls12381_scalar_sub_cost = Some(10);
2113                    cfg.group_ops_bls12381_g1_sub_cost = Some(1550);
2114                    cfg.group_ops_bls12381_g2_sub_cost = Some(3019);
2115                    cfg.group_ops_bls12381_gt_sub_cost = Some(497);
2116
2117                    cfg.group_ops_bls12381_scalar_mul_cost = Some(11);
2118                    cfg.group_ops_bls12381_g1_mul_cost = Some(4842);
2119                    cfg.group_ops_bls12381_g2_mul_cost = Some(9108);
2120                    cfg.group_ops_bls12381_gt_mul_cost = Some(27490);
2121
2122                    cfg.group_ops_bls12381_scalar_div_cost = Some(91);
2123                    cfg.group_ops_bls12381_g1_div_cost = Some(5091);
2124                    cfg.group_ops_bls12381_g2_div_cost = Some(9206);
2125                    cfg.group_ops_bls12381_gt_div_cost = Some(27804);
2126
2127                    cfg.group_ops_bls12381_g1_hash_to_base_cost = Some(2962);
2128                    cfg.group_ops_bls12381_g2_hash_to_base_cost = Some(8688);
2129
2130                    cfg.group_ops_bls12381_g1_msm_base_cost = Some(62648);
2131                    cfg.group_ops_bls12381_g2_msm_base_cost = Some(131192);
2132                    cfg.group_ops_bls12381_g1_msm_base_cost_per_input = Some(1333);
2133                    cfg.group_ops_bls12381_g2_msm_base_cost_per_input = Some(3216);
2134
2135                    cfg.group_ops_bls12381_uncompressed_g1_to_g1_cost = Some(677);
2136                    cfg.group_ops_bls12381_g1_to_uncompressed_g1_cost = Some(2099);
2137                    cfg.group_ops_bls12381_uncompressed_g1_sum_base_cost = Some(77);
2138                    cfg.group_ops_bls12381_uncompressed_g1_sum_cost_per_term = Some(26);
2139                    cfg.group_ops_bls12381_uncompressed_g1_sum_max_terms = Some(1200);
2140
2141                    cfg.group_ops_bls12381_pairing_cost = Some(26897);
2142
2143                    cfg.validator_validate_metadata_cost_base = Some(20000);
2144
2145                    cfg.max_committee_members_count = Some(50);
2146                }
2147                6 => {
2148                    cfg.max_ptb_value_size = Some(1024 * 1024);
2149                }
2150                7 => {
2151                    // version 7 is a new framework version but with no config
2152                    // changes
2153                }
2154                8 => {
2155                    cfg.feature_flags.variant_nodes = true;
2156
2157                    if chain != Chain::Mainnet {
2158                        // Enable round prober in consensus.
2159                        cfg.feature_flags.consensus_round_prober = true;
2160                        // Enable distributed vote scoring.
2161                        cfg.feature_flags
2162                            .consensus_distributed_vote_scoring_strategy = true;
2163                        cfg.feature_flags.consensus_linearize_subdag_v2 = true;
2164                        // Enable smart ancestor selection for testnet
2165                        cfg.feature_flags.consensus_smart_ancestor_selection = true;
2166                        // Enable probing for accepted rounds in round prober for testnet
2167                        cfg.feature_flags
2168                            .consensus_round_prober_probe_accepted_rounds = true;
2169                        // Enable zstd compression for consensus in testnet
2170                        cfg.feature_flags.consensus_zstd_compression = true;
2171                        // Assuming a round rate of max 15/sec, then using a gc depth of 60 allow
2172                        // blocks within a window of ~4 seconds
2173                        // to be included before be considered garbage collected.
2174                        cfg.consensus_gc_depth = Some(60);
2175                    }
2176
2177                    // Enable min_free_execution_slot for the shared object congestion tracker in
2178                    // devnet.
2179                    if chain != Chain::Testnet && chain != Chain::Mainnet {
2180                        cfg.feature_flags.congestion_control_min_free_execution_slot = true;
2181                    }
2182                }
2183                9 => {
2184                    if chain != Chain::Mainnet {
2185                        // Disable smart ancestor selection in the testnet and devnet.
2186                        cfg.feature_flags.consensus_smart_ancestor_selection = false;
2187                    }
2188
2189                    // Enable zstd compression for consensus
2190                    cfg.feature_flags.consensus_zstd_compression = true;
2191
2192                    // Enable passkey in multisig in devnet.
2193                    if chain != Chain::Testnet && chain != Chain::Mainnet {
2194                        cfg.feature_flags.accept_passkey_in_multisig = true;
2195                    }
2196
2197                    // this flag is now deprecated because of the bridge removal.
2198                    cfg.bridge_should_try_to_finalize_committee = None;
2199                }
2200                10 => {
2201                    // Enable min_free_execution_slot for the shared object congestion tracker in
2202                    // all networks.
2203                    cfg.feature_flags.congestion_control_min_free_execution_slot = true;
2204
2205                    // Increase the committee size to 80 on all networks.
2206                    cfg.max_committee_members_count = Some(80);
2207
2208                    // Enable round prober in consensus.
2209                    cfg.feature_flags.consensus_round_prober = true;
2210                    // Enable probing for accepted rounds in round.
2211                    cfg.feature_flags
2212                        .consensus_round_prober_probe_accepted_rounds = true;
2213                    // Enable distributed vote scoring.
2214                    cfg.feature_flags
2215                        .consensus_distributed_vote_scoring_strategy = true;
2216                    // Enable the new consensus commit rule.
2217                    cfg.feature_flags.consensus_linearize_subdag_v2 = true;
2218
2219                    // Enable consensus garbage collection
2220                    // Assuming a round rate of max 15/sec, then using a gc depth of 60 allow
2221                    // blocks within a window of ~4 seconds
2222                    // to be included before be considered garbage collected.
2223                    cfg.consensus_gc_depth = Some(60);
2224
2225                    // Enable minimized child object mutation counting.
2226                    cfg.feature_flags.minimize_child_object_mutations = true;
2227
2228                    if chain != Chain::Mainnet {
2229                        // Enable batched block sync in devnet and testnet.
2230                        cfg.feature_flags.consensus_batched_block_sync = true;
2231                    }
2232
2233                    if chain != Chain::Testnet && chain != Chain::Mainnet {
2234                        // Enable the gas price feedback mechanism (which is used for
2235                        // transactions cancelled due to shared object congestion) in devnet
2236                        cfg.feature_flags
2237                            .congestion_control_gas_price_feedback_mechanism = true;
2238                    }
2239
2240                    cfg.feature_flags.validate_identifier_inputs = true;
2241                    cfg.feature_flags.dependency_linkage_error = true;
2242                    cfg.feature_flags.additional_multisig_checks = true;
2243                }
2244                11 => {
2245                    // version 11 is a new framework version but with no config
2246                    // changes
2247                }
2248                12 => {
2249                    // Enable the gas price feedback mechanism for transactions
2250                    // cancelled due to congestion in all networks
2251                    cfg.feature_flags
2252                        .congestion_control_gas_price_feedback_mechanism = true;
2253
2254                    // Enable normalization of PTB arguments in all networks.
2255                    cfg.feature_flags.normalize_ptb_arguments = true;
2256                }
2257                13 => {
2258                    // Enable selecting committee based on eligible active validators on all
2259                    // networks.
2260                    cfg.feature_flags.select_committee_from_eligible_validators = true;
2261                    // Enable tracking non-committee eligible active
2262                    // validators on all networks.
2263                    cfg.feature_flags.track_non_committee_eligible_validators = true;
2264
2265                    if chain != Chain::Testnet && chain != Chain::Mainnet {
2266                        // Enable selecting committee only from active validators that next epoch
2267                        // version and issued valid AuthorityCapabilities notification in devnet.
2268                        cfg.feature_flags
2269                            .select_committee_supporting_next_epoch_version = true;
2270                    }
2271                }
2272                14 => {
2273                    // Enable batched block sync for mainnet.
2274                    cfg.feature_flags.consensus_batched_block_sync = true;
2275
2276                    if chain != Chain::Mainnet {
2277                        // Enable median-based commit timestamp calculation in consensus and
2278                        // enforce checkpoint timestamp monotonicity for testnet.
2279                        cfg.feature_flags
2280                            .consensus_median_timestamp_with_checkpoint_enforcement = true;
2281                        // Enable selecting committee only from active validators that support the
2282                        // next epoch's version and issued valid AuthorityCapabilities notification
2283                        // in testnet.
2284                        cfg.feature_flags
2285                            .select_committee_supporting_next_epoch_version = true;
2286                    }
2287                    if chain != Chain::Testnet && chain != Chain::Mainnet {
2288                        // Switch consensus protocol to Starfish in devnet
2289                        cfg.feature_flags.consensus_choice = ConsensusChoice::Starfish;
2290                    }
2291                }
2292                15 => {
2293                    if chain != Chain::Mainnet && chain != Chain::Testnet {
2294                        // Enable overshoot of 100 in congestion control. This allows bursts of
2295                        // shared object transactions up to 10 times the average allowable
2296                        // load set by `max_accumulated_txn_cost_per_object_in_mysticeti_commit`.
2297                        cfg.max_congestion_limit_overshoot_per_commit = Some(100);
2298                    }
2299                }
2300                16 => {
2301                    // Enable selecting committee only from active validators that support the
2302                    // next epoch's version and issued valid AuthorityCapabilities notification.
2303                    cfg.feature_flags
2304                        .select_committee_supporting_next_epoch_version = true;
2305                }
2306                // Use this template when making changes:
2307                //
2308                //     // modify an existing constant.
2309                //     move_binary_format_version: Some(7),
2310                //
2311                //     // Add a new constant (which is set to None in prior versions).
2312                //     new_constant: Some(new_value),
2313                //
2314                //     // Remove a constant (ensure that it is never accessed during this version).
2315                //     max_move_object_size: None,
2316                _ => panic!("unsupported version {version:?}"),
2317            }
2318        }
2319        cfg
2320    }
2321
2322    // Extract the bytecode verifier config from this protocol config. `for_signing`
2323    // indicates whether this config is used for verification during signing or
2324    // execution.
2325    pub fn verifier_config(&self, signing_limits: Option<(usize, usize)>) -> VerifierConfig {
2326        let (max_back_edges_per_function, max_back_edges_per_module) = if let Some((
2327            max_back_edges_per_function,
2328            max_back_edges_per_module,
2329        )) = signing_limits
2330        {
2331            (
2332                Some(max_back_edges_per_function),
2333                Some(max_back_edges_per_module),
2334            )
2335        } else {
2336            (None, None)
2337        };
2338
2339        VerifierConfig {
2340            max_loop_depth: Some(self.max_loop_depth() as usize),
2341            max_generic_instantiation_length: Some(self.max_generic_instantiation_length() as usize),
2342            max_function_parameters: Some(self.max_function_parameters() as usize),
2343            max_basic_blocks: Some(self.max_basic_blocks() as usize),
2344            max_value_stack_size: self.max_value_stack_size() as usize,
2345            max_type_nodes: Some(self.max_type_nodes() as usize),
2346            max_push_size: Some(self.max_push_size() as usize),
2347            max_dependency_depth: Some(self.max_dependency_depth() as usize),
2348            max_fields_in_struct: Some(self.max_fields_in_struct() as usize),
2349            max_function_definitions: Some(self.max_function_definitions() as usize),
2350            max_data_definitions: Some(self.max_struct_definitions() as usize),
2351            max_constant_vector_len: Some(self.max_move_vector_len()),
2352            max_back_edges_per_function,
2353            max_back_edges_per_module,
2354            max_basic_blocks_in_script: None,
2355            max_identifier_len: self.max_move_identifier_len_as_option(), /* Before protocol
2356                                                                           * version 9, there was
2357                                                                           * no limit */
2358            bytecode_version: self.move_binary_format_version(),
2359            max_variants_in_enum: self.max_move_enum_variants_as_option(),
2360        }
2361    }
2362
2363    /// Override one or more settings in the config, for testing.
2364    /// This must be called at the beginning of the test, before
2365    /// get_for_(min|max)_version is called, since those functions cache
2366    /// their return value.
2367    pub fn apply_overrides_for_testing(
2368        override_fn: impl Fn(ProtocolVersion, Self) -> Self + Send + Sync + 'static,
2369    ) -> OverrideGuard {
2370        CONFIG_OVERRIDE.with(|ovr| {
2371            let mut cur = ovr.borrow_mut();
2372            assert!(cur.is_none(), "config override already present");
2373            *cur = Some(Box::new(override_fn));
2374            OverrideGuard
2375        })
2376    }
2377}
2378
2379// Setters for tests.
2380// This is only needed for feature_flags. Please suffix each setter with
2381// `_for_testing`. Non-feature_flags should already have test setters defined
2382// through macros.
2383impl ProtocolConfig {
2384    pub fn set_zklogin_auth_for_testing(&mut self, val: bool) {
2385        self.feature_flags.zklogin_auth = val
2386    }
2387    pub fn set_enable_jwk_consensus_updates_for_testing(&mut self, val: bool) {
2388        self.feature_flags.enable_jwk_consensus_updates = val
2389    }
2390
2391    pub fn set_accept_zklogin_in_multisig_for_testing(&mut self, val: bool) {
2392        self.feature_flags.accept_zklogin_in_multisig = val
2393    }
2394
2395    pub fn set_per_object_congestion_control_mode_for_testing(
2396        &mut self,
2397        val: PerObjectCongestionControlMode,
2398    ) {
2399        self.feature_flags.per_object_congestion_control_mode = val;
2400    }
2401
2402    pub fn set_consensus_choice_for_testing(&mut self, val: ConsensusChoice) {
2403        self.feature_flags.consensus_choice = val;
2404    }
2405
2406    pub fn set_consensus_network_for_testing(&mut self, val: ConsensusNetwork) {
2407        self.feature_flags.consensus_network = val;
2408    }
2409
2410    pub fn set_zklogin_max_epoch_upper_bound_delta_for_testing(&mut self, val: Option<u64>) {
2411        self.feature_flags.zklogin_max_epoch_upper_bound_delta = val
2412    }
2413
2414    pub fn set_passkey_auth_for_testing(&mut self, val: bool) {
2415        self.feature_flags.passkey_auth = val
2416    }
2417
2418    pub fn set_disallow_new_modules_in_deps_only_packages_for_testing(&mut self, val: bool) {
2419        self.feature_flags
2420            .disallow_new_modules_in_deps_only_packages = val;
2421    }
2422
2423    pub fn set_consensus_round_prober_for_testing(&mut self, val: bool) {
2424        self.feature_flags.consensus_round_prober = val;
2425    }
2426
2427    pub fn set_consensus_distributed_vote_scoring_strategy_for_testing(&mut self, val: bool) {
2428        self.feature_flags
2429            .consensus_distributed_vote_scoring_strategy = val;
2430    }
2431
2432    pub fn set_gc_depth_for_testing(&mut self, val: u32) {
2433        self.consensus_gc_depth = Some(val);
2434    }
2435
2436    pub fn set_consensus_linearize_subdag_v2_for_testing(&mut self, val: bool) {
2437        self.feature_flags.consensus_linearize_subdag_v2 = val;
2438    }
2439
2440    pub fn set_consensus_round_prober_probe_accepted_rounds(&mut self, val: bool) {
2441        self.feature_flags
2442            .consensus_round_prober_probe_accepted_rounds = val;
2443    }
2444
2445    pub fn set_accept_passkey_in_multisig_for_testing(&mut self, val: bool) {
2446        self.feature_flags.accept_passkey_in_multisig = val;
2447    }
2448
2449    pub fn set_consensus_smart_ancestor_selection_for_testing(&mut self, val: bool) {
2450        self.feature_flags.consensus_smart_ancestor_selection = val;
2451    }
2452
2453    pub fn set_consensus_batched_block_sync_for_testing(&mut self, val: bool) {
2454        self.feature_flags.consensus_batched_block_sync = val;
2455    }
2456
2457    pub fn set_congestion_control_min_free_execution_slot_for_testing(&mut self, val: bool) {
2458        self.feature_flags
2459            .congestion_control_min_free_execution_slot = val;
2460    }
2461
2462    pub fn set_congestion_control_gas_price_feedback_mechanism_for_testing(&mut self, val: bool) {
2463        self.feature_flags
2464            .congestion_control_gas_price_feedback_mechanism = val;
2465    }
2466    pub fn set_select_committee_from_eligible_validators_for_testing(&mut self, val: bool) {
2467        self.feature_flags.select_committee_from_eligible_validators = val;
2468    }
2469
2470    pub fn set_track_non_committee_eligible_validators_for_testing(&mut self, val: bool) {
2471        self.feature_flags.track_non_committee_eligible_validators = val;
2472    }
2473
2474    pub fn set_select_committee_supporting_next_epoch_version(&mut self, val: bool) {
2475        self.feature_flags
2476            .select_committee_supporting_next_epoch_version = val;
2477    }
2478
2479    pub fn set_consensus_median_timestamp_with_checkpoint_enforcement_for_testing(
2480        &mut self,
2481        val: bool,
2482    ) {
2483        self.feature_flags
2484            .consensus_median_timestamp_with_checkpoint_enforcement = val;
2485    }
2486}
2487
2488type OverrideFn = dyn Fn(ProtocolVersion, ProtocolConfig) -> ProtocolConfig + Send + Sync;
2489
2490thread_local! {
2491    static CONFIG_OVERRIDE: RefCell<Option<Box<OverrideFn>>> = const { RefCell::new(None) };
2492}
2493
2494#[must_use]
2495pub struct OverrideGuard;
2496
2497impl Drop for OverrideGuard {
2498    fn drop(&mut self) {
2499        info!("restoring override fn");
2500        CONFIG_OVERRIDE.with(|ovr| {
2501            *ovr.borrow_mut() = None;
2502        });
2503    }
2504}
2505
2506/// Defines which limit got crossed.
2507/// The value which crossed the limit and value of the limit crossed are
2508/// embedded
2509#[derive(PartialEq, Eq)]
2510pub enum LimitThresholdCrossed {
2511    None,
2512    Soft(u128, u128),
2513    Hard(u128, u128),
2514}
2515
2516/// Convenience function for comparing limit ranges
2517/// V::MAX must be at >= U::MAX and T::MAX
2518pub fn check_limit_in_range<T: Into<V>, U: Into<V>, V: PartialOrd + Into<u128>>(
2519    x: T,
2520    soft_limit: U,
2521    hard_limit: V,
2522) -> LimitThresholdCrossed {
2523    let x: V = x.into();
2524    let soft_limit: V = soft_limit.into();
2525
2526    debug_assert!(soft_limit <= hard_limit);
2527
2528    // It is important to preserve this comparison order because if soft_limit ==
2529    // hard_limit we want LimitThresholdCrossed::Hard
2530    if x >= hard_limit {
2531        LimitThresholdCrossed::Hard(x.into(), hard_limit.into())
2532    } else if x < soft_limit {
2533        LimitThresholdCrossed::None
2534    } else {
2535        LimitThresholdCrossed::Soft(x.into(), soft_limit.into())
2536    }
2537}
2538
2539#[macro_export]
2540macro_rules! check_limit {
2541    ($x:expr, $hard:expr) => {
2542        check_limit!($x, $hard, $hard)
2543    };
2544    ($x:expr, $soft:expr, $hard:expr) => {
2545        check_limit_in_range($x as u64, $soft, $hard)
2546    };
2547}
2548
2549/// Used to check which limits were crossed if the TX is metered (not system tx)
2550/// Args are: is_metered, value_to_check, metered_limit, unmetered_limit
2551/// metered_limit is always less than or equal to unmetered_hard_limit
2552#[macro_export]
2553macro_rules! check_limit_by_meter {
2554    ($is_metered:expr, $x:expr, $metered_limit:expr, $unmetered_hard_limit:expr, $metric:expr) => {{
2555        // If this is metered, we use the metered_limit limit as the upper bound
2556        let (h, metered_str) = if $is_metered {
2557            ($metered_limit, "metered")
2558        } else {
2559            // Unmetered gets more headroom
2560            ($unmetered_hard_limit, "unmetered")
2561        };
2562        use iota_protocol_config::check_limit_in_range;
2563        let result = check_limit_in_range($x as u64, $metered_limit, h);
2564        match result {
2565            LimitThresholdCrossed::None => {}
2566            LimitThresholdCrossed::Soft(_, _) => {
2567                $metric.with_label_values(&[metered_str, "soft"]).inc();
2568            }
2569            LimitThresholdCrossed::Hard(_, _) => {
2570                $metric.with_label_values(&[metered_str, "hard"]).inc();
2571            }
2572        };
2573        result
2574    }};
2575}
2576
2577#[cfg(all(test, not(msim)))]
2578mod test {
2579    use insta::assert_yaml_snapshot;
2580
2581    use super::*;
2582
2583    #[test]
2584    fn snapshot_tests() {
2585        println!("\n============================================================================");
2586        println!("!                                                                          !");
2587        println!("! IMPORTANT: never update snapshots from this test. only add new versions! !");
2588        println!("!                                                                          !");
2589        println!("============================================================================\n");
2590        for chain_id in &[Chain::Unknown, Chain::Mainnet, Chain::Testnet] {
2591            // make Chain::Unknown snapshots compatible with pre-chain-id snapshots so that
2592            // we don't break the release-time compatibility tests. Once Chain
2593            // Id configs have been released everywhere, we can remove this and
2594            // only test Mainnet and Testnet
2595            let chain_str = match chain_id {
2596                Chain::Unknown => "".to_string(),
2597                _ => format!("{chain_id:?}_"),
2598            };
2599            for i in MIN_PROTOCOL_VERSION..=MAX_PROTOCOL_VERSION {
2600                let cur = ProtocolVersion::new(i);
2601                assert_yaml_snapshot!(
2602                    format!("{}version_{}", chain_str, cur.as_u64()),
2603                    ProtocolConfig::get_for_version(cur, *chain_id)
2604                );
2605            }
2606        }
2607    }
2608
2609    #[test]
2610    fn test_getters() {
2611        let prot: ProtocolConfig =
2612            ProtocolConfig::get_for_version(ProtocolVersion::new(1), Chain::Unknown);
2613        assert_eq!(
2614            prot.max_arguments(),
2615            prot.max_arguments_as_option().unwrap()
2616        );
2617    }
2618
2619    #[test]
2620    fn test_setters() {
2621        let mut prot: ProtocolConfig =
2622            ProtocolConfig::get_for_version(ProtocolVersion::new(1), Chain::Unknown);
2623        prot.set_max_arguments_for_testing(123);
2624        assert_eq!(prot.max_arguments(), 123);
2625
2626        prot.set_max_arguments_from_str_for_testing("321".to_string());
2627        assert_eq!(prot.max_arguments(), 321);
2628
2629        prot.disable_max_arguments_for_testing();
2630        assert_eq!(prot.max_arguments_as_option(), None);
2631
2632        prot.set_attr_for_testing("max_arguments".to_string(), "456".to_string());
2633        assert_eq!(prot.max_arguments(), 456);
2634    }
2635
2636    #[test]
2637    #[should_panic(expected = "unsupported version")]
2638    fn max_version_test() {
2639        // When this does not panic, version higher than MAX_PROTOCOL_VERSION exists.
2640        // To fix, bump MAX_PROTOCOL_VERSION or disable this check for the version.
2641        let _ = ProtocolConfig::get_for_version_impl(
2642            ProtocolVersion::new(MAX_PROTOCOL_VERSION + 1),
2643            Chain::Unknown,
2644        );
2645    }
2646
2647    #[test]
2648    fn lookup_by_string_test() {
2649        let prot: ProtocolConfig =
2650            ProtocolConfig::get_for_version(ProtocolVersion::new(1), Chain::Mainnet);
2651        // Does not exist
2652        assert!(prot.lookup_attr("some random string".to_string()).is_none());
2653
2654        assert!(
2655            prot.lookup_attr("max_arguments".to_string())
2656                == Some(ProtocolConfigValue::u32(prot.max_arguments())),
2657        );
2658
2659        // We didnt have this in version 1 on Mainnet
2660        assert!(
2661            prot.lookup_attr("poseidon_bn254_cost_base".to_string())
2662                .is_none()
2663        );
2664        assert!(
2665            prot.attr_map()
2666                .get("poseidon_bn254_cost_base")
2667                .unwrap()
2668                .is_none()
2669        );
2670
2671        // But we did in version 1 on Devnet
2672        let prot: ProtocolConfig =
2673            ProtocolConfig::get_for_version(ProtocolVersion::new(1), Chain::Unknown);
2674
2675        assert!(
2676            prot.lookup_attr("poseidon_bn254_cost_base".to_string())
2677                == Some(ProtocolConfigValue::u64(prot.poseidon_bn254_cost_base()))
2678        );
2679        assert!(
2680            prot.attr_map().get("poseidon_bn254_cost_base").unwrap()
2681                == &Some(ProtocolConfigValue::u64(prot.poseidon_bn254_cost_base()))
2682        );
2683
2684        // Check feature flags
2685        let prot: ProtocolConfig =
2686            ProtocolConfig::get_for_version(ProtocolVersion::new(1), Chain::Mainnet);
2687        // Does not exist
2688        assert!(
2689            prot.feature_flags
2690                .lookup_attr("some random string".to_owned())
2691                .is_none()
2692        );
2693        assert!(
2694            !prot
2695                .feature_flags
2696                .attr_map()
2697                .contains_key("some random string")
2698        );
2699
2700        // Was false in v1 on Mainnet
2701        assert!(prot.feature_flags.lookup_attr("enable_poseidon".to_owned()) == Some(false));
2702        assert!(
2703            prot.feature_flags
2704                .attr_map()
2705                .get("enable_poseidon")
2706                .unwrap()
2707                == &false
2708        );
2709        let prot: ProtocolConfig =
2710            ProtocolConfig::get_for_version(ProtocolVersion::new(1), Chain::Unknown);
2711        // Was true from v1 and up on Devnet
2712        assert!(prot.feature_flags.lookup_attr("enable_poseidon".to_owned()) == Some(true));
2713        assert!(
2714            prot.feature_flags
2715                .attr_map()
2716                .get("enable_poseidon")
2717                .unwrap()
2718                == &true
2719        );
2720    }
2721
2722    #[test]
2723    fn limit_range_fn_test() {
2724        let low = 100u32;
2725        let high = 10000u64;
2726
2727        assert!(check_limit!(1u8, low, high) == LimitThresholdCrossed::None);
2728        assert!(matches!(
2729            check_limit!(255u16, low, high),
2730            LimitThresholdCrossed::Soft(255u128, 100)
2731        ));
2732        // This wont compile because lossy
2733        // assert!(check_limit!(100000000u128, low, high) ==
2734        // LimitThresholdCrossed::None); This wont compile because lossy
2735        // assert!(check_limit!(100000000usize, low, high) ==
2736        // LimitThresholdCrossed::None);
2737
2738        assert!(matches!(
2739            check_limit!(2550000u64, low, high),
2740            LimitThresholdCrossed::Hard(2550000, 10000)
2741        ));
2742
2743        assert!(matches!(
2744            check_limit!(2550000u64, high, high),
2745            LimitThresholdCrossed::Hard(2550000, 10000)
2746        ));
2747
2748        assert!(matches!(
2749            check_limit!(1u8, high),
2750            LimitThresholdCrossed::None
2751        ));
2752
2753        assert!(check_limit!(255u16, high) == LimitThresholdCrossed::None);
2754
2755        assert!(matches!(
2756            check_limit!(2550000u64, high),
2757            LimitThresholdCrossed::Hard(2550000, 10000)
2758        ));
2759    }
2760}