Skip to main content

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 = 31;
23
24/// Protocol version that IIP8 took effect.
25pub const PROTOCOL_VERSION_IIP8: u64 = 20;
26// Record history of protocol version allocations here:
27//
28// Version 1:  Original version.
29// Version 2:  Don't redistribute slashed staking rewards, fix computation of
30//             SystemEpochInfoEventV1.
31// Version 3:  Set the `relocate_event_module` to be true so that the module
32//             that is associated as the "sending module" for an event is
33//             relocated by linkage.
34//             Add `Clock` based unlock to `Timelock` objects.
35// Version 4:  Introduce the `max_type_to_layout_nodes` config that sets the
36//             maximal nodes which are allowed when converting to a type layout.
37// Version 5:  Introduce fixed protocol-defined base fee, IotaSystemStateV2 and
38//             SystemEpochInfoEventV2.
39//             Disallow adding new modules in `deps-only` packages.
40//             Improve gas/wall time efficiency of some Move stdlib vector
41//             functions.
42//             Add new gas model version to update charging of functions.
43//             Enable proper conversion of certain type argument errors in the
44//             execution layer.
45// Version 6:  Bound size of values created in the adapter.
46// Version 7:  Improve handling of stake withdrawal from candidate validators.
47// Version 8:  Variants as type nodes.
48//             Enable smart ancestor selection for testnet.
49//             Enable probing for accepted rounds in round prober for testnet.
50//             Switch to distributed vote scoring in consensus in testnet.
51//             Enable zstd compression for consensus tonic network in testnet.
52//             Enable consensus garbage collection for testnet
53//             Enable the new consensus commit rule for testnet.
54//             Enable min_free_execution_slot for the shared object congestion
55//             tracker in devnet.
56// Version 9:  Disable smart ancestor selection for the testnet.
57//             Enable zstd compression for consensus tonic network in mainnet.
58//             Enable passkey auth in multisig for devnet.
59//             Remove the iota-bridge from the framework.
60// Version 10: Enable min_free_execution_slot for the shared object congestion
61//             tracker in all networks.
62//             Increase the committee size to 80 on all networks.
63//             Enable round prober in consensus for mainnet.
64//             Enable probing for accepted rounds in round prober for mainnet.
65//             Switch to distributed vote scoring in consensus for mainnet.
66//             Enable the new consensus commit rule for mainnet.
67//             Enable consensus garbage collection for mainnet with GC depth set
68//             to 60 rounds.
69//             Enable batching in synchronizer for testnet
70//             Enable the gas price feedback mechanism in devnet.
71//             Enable Identifier input validation.
72//             Removes unnecessary child object mutations
73//             Add additional signature checks
74//             Add additional linkage checks
75// Version 11: Framework fix regarding candidate validator commission rate.
76// Version 12: Enable the gas price feedback mechanism in all networks.
77//             Enable the normalization of PTB arguments.
78// Version 13: Introduce logic to allow the committee to be selected from a set
79//             of eligible active validators.
80//             Enable processing and tracking AuthorityCapabilitiesV1 from
81//             non-committee validators in the devnet.
82// Version 14: Switches the consensus protocol to Starfish in devnet.
83//             Enable median-based commit timestamp calculation in consensus,
84//             and enforce checkpoint timestamp monotonicity for testnet.
85//             Enable batched block sync for mainnet.
86//             Enable selecting committee only from active validators that
87//             support the next epoch's version and issued valid
88//             AuthorityCapabilities notification in testnet.
89// Version 15: Enable shared object transaction bursts of 10 times average load
90//             on devnet.
91// Version 16: Enable selecting committee only from active validators that
92//             support the next epoch's version and issued valid
93//             AuthorityCapabilities notification.
94//             Enable committing transactions only for traversed headers in
95//             Starfish.
96// Version 17: Increase the committee size to 100 on all networks.
97// Version 18: Enable passkey authentication support in testnet.
98// Version 19: Enable congestion limit overshoot in the gas price feedback
99//             mechanism on devnet.
100//             Enable a separate gas price feedback mechanism for transactions
101//             using randomness on devnet.
102//             Allow metadata bytes indexed with a dedicated key in compiled
103//             Move modules in devnet.
104//             Enable publishing package metadata v1 along with the package in
105//             devnet.
106//             Enable Move-based account authentication in devnet.
107//             Increase the base cost for transfer receive object in devnet.
108//             Switch consensus protocol to Starfish in testnet.
109//             Enable passkey authentication support in mainnet.
110//             Change epoch transaction will contain validator scores.
111//             Enable validator scoring on testnet and enable adjustment of
112//             validator rewards based on scores on Devnet.
113// Version 20: Supports the calculation of validator scores while still passing
114//             a default score value to the advance_epoch call. Enables this
115//             decoupling on Testnet; Devnet and Mainnet behavior remain the
116//             same.
117//             Introduce Dynamic Minimum Commission (IIP-8) on all networks.
118// Version 21: Enable overshoot of 100 in congestion control on testnet.
119//             Enable congestion limit overshoot in the gas price feedback
120//             mechanism on testnet.
121//             Enable a separate gas price feedback mechanism for transactions
122//             using randomness on testnet.
123//             Enable fast commit syncer for faster recovery in devnet.
124//             Add auth_context_tx native functions costs.
125//             Reduce max_auth_gas in Devnet.
126// Version 22: Enable overshoot of 100 in congestion control on all networks.
127//             Enable congestion limit overshoot in the gas price feedback
128//             mechanism on all networks.
129//             Enable a separate gas price feedback mechanism for transactions
130//             using randomness on all networks.
131//             Enable Move-based account authentication in testnet.
132//             Enable fast commit syncer for faster recovery on testnet.
133// Version 23: Enable Move native context (TxContext via native functions) in
134//             all networks. TxContext fields are read via native functions
135//             instead of being deserialized from a BCS-encoded struct.
136//             Enables sponsor, rgp, gas_price, and gas_budget to be exposed to
137//             Move.
138// Version 24: Switch consensus protocol to Starfish in all networks.
139//             Enable Move-based sponsor account authentication in devnet.
140//             Add AuthContext native functions cost for reading tx_data_bytes.
141//             Enable additional borrow checks.
142// Version 25: Deprecate zkLogin related parameters since zkLogin is no longer
143//             supported.
144// Version 26: Introduce a module to allow Move code to query protocol feature
145//             flags at runtime.
146// Version 27: Only sponsor Move authentication is performed pre-consensus in
147//             devnet.
148//             Enable consensus block restrictions on testnet and devnet:
149//             bound block-header size to O(committee_size) and enable
150//             garbage collection in the block manager.
151// Version 28: Move authenticator contracts can now inspect which authenticator
152//             function the sender and sponsor used during transaction execution
153//             via new AuthContext accessors.
154//             Enable Move-based account authentication in mainnet.
155//             Enable Move-based sponsor account authentication in testnet.
156// Version 29: Keep advancing the random beacon DKG state machine on every
157//             commit while it is still pending -- regardless of whether new DKG
158//             messages or confirmations arrived that commit -- so DKG resolves
159//             from persisted state (completing, or failing once the timeout
160//             round passes) even with no fresh inbound traffic, e.g. after a
161//             validator restart. Without this it can stay pending forever and
162//             block epoch close.
163//             Enable median-based commit timestamp calculation in consensus,
164//             and enforce checkpoint timestamp monotonicity for mainnet.
165//             Enable fast commit syncer for faster recovery on all networks.
166//             Enable consensus block restrictions on all networks:
167//             bound block-header size to O(committee_size) and enable
168//             garbage collection in the block manager.
169// Version 30: Extend the protocol_config framework module with a generic
170//             `get_attr<T>` native that lets Move code read any numeric or
171//             boolean protocol parameter by name, returning T directly and
172//             aborting on error.
173//             Expose `is_feature_enabled` and `get_attr<T>` natives to the
174//             iota_system package via a new iota_system::protocol_config
175//             module.
176// Version 31: Rebuild the framework binaries for the latest iota_system
177//             validator set changes.
178//             Enable validator metadata verification v2.
179//             Amortize the minimum checkpoint interval over a sliding window
180//             on non-Mainnet/Testnet chains.
181//             Start publishing package metadata using module metadata as a
182//             dynamic field.
183#[derive(Copy, Clone, Debug, Hash, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)]
184pub struct ProtocolVersion(u64);
185
186impl ProtocolVersion {
187    // The minimum and maximum protocol version supported by this binary.
188    // Counterintuitively, this constant may change over time as support for old
189    // protocol versions is removed from the source. This ensures that when a
190    // new network (such as a testnet) is created, its genesis committee will
191    // use a protocol version that is actually supported by the binary.
192    pub const MIN: Self = Self(MIN_PROTOCOL_VERSION);
193
194    pub const MAX: Self = Self(MAX_PROTOCOL_VERSION);
195
196    #[cfg(not(msim))]
197    const MAX_ALLOWED: Self = Self::MAX;
198
199    // We create one additional "fake" version in simulator builds so that we can
200    // test upgrades.
201    #[cfg(msim)]
202    pub const MAX_ALLOWED: Self = Self(MAX_PROTOCOL_VERSION + 1);
203
204    pub fn new(v: u64) -> Self {
205        Self(v)
206    }
207
208    pub const fn as_u64(&self) -> u64 {
209        self.0
210    }
211
212    // For serde deserialization - we don't define a Default impl because there
213    // isn't a single universally appropriate default value.
214    pub fn max() -> Self {
215        Self::MAX
216    }
217}
218
219impl From<u64> for ProtocolVersion {
220    fn from(v: u64) -> Self {
221        Self::new(v)
222    }
223}
224
225impl std::ops::Sub<u64> for ProtocolVersion {
226    type Output = Self;
227    fn sub(self, rhs: u64) -> Self::Output {
228        Self::new(self.0 - rhs)
229    }
230}
231
232impl std::ops::Add<u64> for ProtocolVersion {
233    type Output = Self;
234    fn add(self, rhs: u64) -> Self::Output {
235        Self::new(self.0 + rhs)
236    }
237}
238
239#[derive(
240    Clone, Serialize, Deserialize, Debug, PartialEq, Copy, PartialOrd, Ord, Eq, ValueEnum, Default,
241)]
242pub enum Chain {
243    Mainnet,
244    Testnet,
245    #[default]
246    Unknown,
247}
248
249impl Chain {
250    pub fn as_str(self) -> &'static str {
251        match self {
252            Chain::Mainnet => "mainnet",
253            Chain::Testnet => "testnet",
254            Chain::Unknown => "unknown",
255        }
256    }
257}
258
259pub struct Error(pub String);
260
261// TODO: There are quite a few non boolean values in the feature flags. We
262// should move them out.
263/// Records on/off feature flags that may vary at each protocol version.
264#[derive(
265    Default,
266    Clone,
267    Serialize,
268    Deserialize,
269    Debug,
270    ProtocolConfigFeatureFlagsGetters,
271    ProtocolConfigOverride,
272)]
273struct FeatureFlags {
274    // Add feature flags here, e.g.:
275    // new_protocol_feature: bool,
276
277    // Disables unnecessary invariant check in the Move VM when swapping the value out of a local
278    // This flag is used to provide the correct MoveVM configuration for clients.
279    #[serde(skip_serializing_if = "is_true")]
280    disable_invariant_violation_check_in_swap_loc: bool,
281
282    // If true, checks no extra bytes in a compiled module
283    // This flag is used to provide the correct MoveVM configuration for clients.
284    #[serde(skip_serializing_if = "is_true")]
285    no_extraneous_module_bytes: bool,
286
287    // How we order transactions coming out of consensus before sending to execution.
288    #[serde(skip_serializing_if = "ConsensusTransactionOrdering::is_none")]
289    consensus_transaction_ordering: ConsensusTransactionOrdering,
290
291    // If true, use the hardened OTW check
292    // This flag is used to provide the correct MoveVM configuration for clients.
293    #[serde(skip_serializing_if = "is_true")]
294    hardened_otw_check: bool,
295
296    // Enable the poseidon hash function
297    #[serde(skip_serializing_if = "is_false")]
298    enable_poseidon: bool,
299
300    // Enable native function for msm.
301    #[serde(skip_serializing_if = "is_false")]
302    enable_group_ops_native_function_msm: bool,
303
304    // Controls the behavior of per object congestion control in consensus handler.
305    #[serde(skip_serializing_if = "PerObjectCongestionControlMode::is_none")]
306    per_object_congestion_control_mode: PerObjectCongestionControlMode,
307
308    // The consensus protocol to be used for the epoch.
309    #[serde(
310        default = "ConsensusChoice::mysticeti_deprecated",
311        skip_serializing_if = "ConsensusChoice::is_mysticeti_deprecated"
312    )]
313    consensus_choice: ConsensusChoice,
314
315    // Consensus network to use.
316    #[serde(skip_serializing_if = "ConsensusNetwork::is_tonic")]
317    consensus_network: ConsensusNetwork,
318
319    // Set the upper bound allowed for max_epoch in zklogin signature.
320    #[deprecated]
321    #[serde(skip_serializing_if = "Option::is_none")]
322    zklogin_max_epoch_upper_bound_delta: Option<u64>,
323
324    // Enable VDF
325    #[serde(skip_serializing_if = "is_false")]
326    enable_vdf: bool,
327
328    // Enable passkey auth (SIP-9)
329    #[serde(skip_serializing_if = "is_false")]
330    passkey_auth: bool,
331
332    // Rethrow type layout errors during serialization instead of trying to convert them.
333    // This flag is used to provide the correct MoveVM configuration for clients.
334    #[serde(skip_serializing_if = "is_true")]
335    rethrow_serialization_type_layout_errors: bool,
336
337    // Makes the event's sending module version-aware.
338    #[serde(skip_serializing_if = "is_false")]
339    relocate_event_module: bool,
340
341    // Enable a protocol-defined base gas price for all transactions.
342    #[serde(skip_serializing_if = "is_false")]
343    protocol_defined_base_fee: bool,
344
345    // Enable uncompressed group elements in BLS123-81 G1
346    #[serde(skip_serializing_if = "is_false")]
347    uncompressed_g1_group_elements: bool,
348
349    // Disallow adding new modules in `deps-only` packages.
350    #[serde(skip_serializing_if = "is_false")]
351    disallow_new_modules_in_deps_only_packages: bool,
352
353    // Enable v2 native charging for natives.
354    #[serde(skip_serializing_if = "is_false")]
355    native_charging_v2: bool,
356
357    // Properly convert certain type argument errors in the execution layer.
358    #[serde(skip_serializing_if = "is_false")]
359    convert_type_argument_error: bool,
360
361    // Probe rounds received by peers from every authority.
362    #[serde(skip_serializing_if = "is_false")]
363    consensus_round_prober: bool,
364
365    // Use distributed vote leader scoring strategy in consensus.
366    #[serde(skip_serializing_if = "is_false")]
367    consensus_distributed_vote_scoring_strategy: bool,
368
369    // Enables the new logic for collecting the subdag in the consensus linearizer. The new logic
370    // does not stop the recursion at the highest committed round for each authority, but
371    // allows to commit uncommitted blocks up to gc round (excluded) for that authority.
372    #[serde(skip_serializing_if = "is_false")]
373    consensus_linearize_subdag_v2: bool,
374
375    // Variants count as nodes
376    #[serde(skip_serializing_if = "is_false")]
377    variant_nodes: bool,
378
379    // Use smart ancestor selection in consensus.
380    #[serde(skip_serializing_if = "is_false")]
381    consensus_smart_ancestor_selection: bool,
382
383    // Probe accepted rounds in round prober.
384    #[serde(skip_serializing_if = "is_false")]
385    consensus_round_prober_probe_accepted_rounds: bool,
386
387    // If true, enable zstd compression for consensus tonic network.
388    #[serde(skip_serializing_if = "is_false")]
389    consensus_zstd_compression: bool,
390
391    // Use the minimum free execution slot to schedule execution of a transaction in the shared
392    // object congestion tracker.
393    #[serde(skip_serializing_if = "is_false")]
394    congestion_control_min_free_execution_slot: bool,
395
396    // If true, multisig containing passkey sig is accepted.
397    #[serde(skip_serializing_if = "is_false")]
398    accept_passkey_in_multisig: bool,
399
400    // If true, enabled batched block sync in consensus.
401    #[serde(skip_serializing_if = "is_false")]
402    consensus_batched_block_sync: bool,
403
404    // To enable/disable the gas price feedback mechanism used for transactions
405    // cancelled due to shared object congestion
406    #[serde(skip_serializing_if = "is_false")]
407    congestion_control_gas_price_feedback_mechanism: bool,
408
409    // Validate identifier inputs separately
410    #[serde(skip_serializing_if = "is_false")]
411    validate_identifier_inputs: bool,
412
413    // If true, enables the optimizations for child object mutations, removing unnecessary
414    // mutations
415    #[serde(skip_serializing_if = "is_false")]
416    minimize_child_object_mutations: bool,
417
418    // If true enable additional linkage checks.
419    #[serde(skip_serializing_if = "is_false")]
420    dependency_linkage_error: bool,
421
422    // If true enable additional multisig checks.
423    #[serde(skip_serializing_if = "is_false")]
424    additional_multisig_checks: bool,
425
426    // If true, enables the normalization of PTB arguments but does not yet enable splatting
427    // `Result`s of length not equal to 1
428    #[serde(skip_serializing_if = "is_false")]
429    normalize_ptb_arguments: bool,
430
431    // If true, use ChangeEpochV3 for epoch change to pass an additional eligible_active_validators
432    // parameter to IotaSystem's advance_epoch call. This should only be enabled when on-chain
433    // IotaSystem objects are updated as well.
434    #[serde(skip_serializing_if = "is_false")]
435    select_committee_from_eligible_validators: bool,
436
437    // If true, non-committee active validators will sign and send AuthorityCapabilitiesV1 to the
438    // committee. Once the committee reaches consensus over the AuthorityCapabilitiesV1, it is
439    // recorded and possible to use in the committee selection if
440    // select_validators_supporting_next_epoch_version is enabled. This flag does not change the
441    // way that eligible_validators vector is created - still all active validators are used for
442    // selecting the committee.
443    #[serde(skip_serializing_if = "is_false")]
444    track_non_committee_eligible_validators: bool,
445
446    // The committee be selected from active_validators who support the next protocol version AND
447    // have issued a correct AuthorityCapabilities notification. This flag should only be enabled
448    // if both select_committee_from_eligible_validators and
449    // track_non_committee_eligible_validators are enabled. If this is disabled, then all
450    // active validators are used for selecting the committee (default behavior).
451    #[serde(skip_serializing_if = "is_false")]
452    select_committee_supporting_next_epoch_version: bool,
453
454    // If true, then it (1) will not enforce monotonicity checks for a block's ancestors, (2)
455    // calculates the commit's timestamp based on the weighted by stake median timestamp of the
456    // leader's ancestors, and (3) enforces checkpoint timestamps are non-decreasing.
457    #[serde(skip_serializing_if = "is_false")]
458    consensus_median_timestamp_with_checkpoint_enforcement: bool,
459
460    // If true, then transactions are committed only for traversed headers
461    #[serde(skip_serializing_if = "is_false")]
462    consensus_commit_transactions_only_for_traversed_headers: bool,
463
464    // To enable/disable congestion limit overshoot in the gas price feedback mechanism.
465    #[serde(skip_serializing_if = "is_false")]
466    congestion_limit_overshoot_in_gas_price_feedback_mechanism: bool,
467
468    // To enable/disable a separate gas price feedback mechanism for transactions using
469    // randomness.
470    #[serde(skip_serializing_if = "is_false")]
471    separate_gas_price_feedback_mechanism_for_randomness: bool,
472
473    // If true, it allows metadata bytes indexed with a dedicated key in a compiled module.
474    // This flag is used to provide the correct MoveVM configuration for clients.
475    #[serde(skip_serializing_if = "is_false")]
476    metadata_in_module_bytes: bool,
477
478    // If true, enables publishing package metadata v1 along with the package.
479    #[serde(skip_serializing_if = "is_false")]
480    publish_package_metadata: bool,
481
482    // If true, enables the authentication of account using Move code.
483    #[serde(skip_serializing_if = "is_false")]
484    enable_move_authentication: bool,
485
486    // If true, enables the authentication of a sponsor account using Move code.
487    #[serde(skip_serializing_if = "is_false")]
488    enable_move_authentication_for_sponsor: bool,
489
490    // If true, the change epoch transaction will contain validator scores.
491    #[serde(skip_serializing_if = "is_false")]
492    pass_validator_scores_to_advance_epoch: bool,
493
494    // If true, enables calculation of validator scores.
495    #[serde(skip_serializing_if = "is_false")]
496    calculate_validator_scores: bool,
497
498    // If true, validators will use the committee's score to adjust rewards.
499    #[serde(skip_serializing_if = "is_false")]
500    adjust_rewards_by_score: bool,
501
502    // If true, the change epoch transaction will contain the locally calculated validator scores.
503    // If false, a default score (MAX_SCORE) is passed
504    #[serde(skip_serializing_if = "is_false")]
505    pass_calculated_validator_scores_to_advance_epoch: bool,
506
507    // If true, enables the fast commit syncer in Starfish consensus for faster recovery
508    // from large commit gaps. Also controls whether TransactionRef is used in commits
509    // instead of BlockRef, and enables the associated gRPC endpoints for fetching
510    // commits and transactions.
511    #[serde(skip_serializing_if = "is_false")]
512    consensus_fast_commit_sync: bool,
513
514    // If true, enables consensus block restrictions: bounds the block header size for
515    // a given committee size.
516    #[serde(skip_serializing_if = "is_false")]
517    consensus_block_restrictions: bool,
518
519    // If true, enable `TxContext` Move API to go native.
520    #[serde(skip_serializing_if = "is_false")]
521    move_native_tx_context: bool,
522
523    // If true, perform additional borrow checks
524    #[serde(skip_serializing_if = "is_false")]
525    additional_borrow_checks: bool,
526
527    // If true, only sponsor Move authentication is performed pre-consensus.
528    #[serde(skip_serializing_if = "is_false")]
529    pre_consensus_sponsor_only_move_authentication: bool,
530
531    // If true, enables the optimistic commit rule (StarfishSpeed) in Starfish consensus.
532    #[serde(skip_serializing_if = "is_false")]
533    consensus_starfish_speed: bool,
534
535    // If true, keep advancing the random beacon DKG state machine on every
536    // consensus commit while DKG is still pending, even when no new messages or
537    // confirmations were processed that commit. This lets a validator resolve
538    // DKG from already-persisted state (completing, or failing once the timeout
539    // round passes) with no fresh inbound traffic -- e.g. after a restart --
540    // instead of staying pending forever.
541    #[serde(skip_serializing_if = "is_false")]
542    always_advance_dkg_to_resolution: bool,
543
544    // If true, enables the P-COOL (post-consensus owned-object locking) flow:
545    // transactions bypass pre-consensus certification and owned-object locking,
546    // and conflicts are resolved deterministically post-consensus (white-flag
547    // conflict resolution) using persistent locks.
548    #[serde(skip_serializing_if = "is_false")]
549    enable_pcool_flow: bool,
550
551    // If true perform consistent verification of metadata
552    #[serde(skip_serializing_if = "is_false")]
553    validator_metadata_verify_v2: bool,
554
555    // If true, post-consensus deny checks use a consensus-governed deny rule set
556    // (validators announce proposed rules; the active set is their stake-weighted
557    // aggregate) instead of each validator's local `TransactionDenyConfig`.
558    #[serde(skip_serializing_if = "is_false")]
559    deny_rule_governance: bool,
560
561    // If true, package metadata can be published with ModuleMetadata as a dynamic
562    // field.
563    #[serde(skip_serializing_if = "is_false")]
564    package_metadata_with_dynamic_module_metadata: bool,
565}
566
567fn is_true(b: &bool) -> bool {
568    *b
569}
570
571fn is_false(b: &bool) -> bool {
572    !b
573}
574
575/// Ordering mechanism for transactions in one consensus output.
576#[derive(Default, Copy, Clone, PartialEq, Eq, Serialize, Deserialize, Debug)]
577pub enum ConsensusTransactionOrdering {
578    /// No ordering. Transactions are processed in the order they appear in the
579    /// consensus output.
580    #[default]
581    None,
582    /// Order transactions by gas price, highest first.
583    ByGasPrice,
584}
585
586impl ConsensusTransactionOrdering {
587    pub fn is_none(&self) -> bool {
588        matches!(self, ConsensusTransactionOrdering::None)
589    }
590}
591
592// The config for per object congestion control in consensus handler.
593#[derive(Default, Copy, Clone, PartialEq, Eq, Serialize, Deserialize, Debug)]
594pub enum PerObjectCongestionControlMode {
595    #[default]
596    None, // No congestion control.
597    TotalGasBudget, // Use txn gas budget as execution cost.
598    TotalTxCount,   // Use total txn count as execution cost.
599}
600
601impl PerObjectCongestionControlMode {
602    pub fn is_none(&self) -> bool {
603        matches!(self, PerObjectCongestionControlMode::None)
604    }
605}
606
607// Configuration options for consensus algorithm.
608#[derive(Default, Copy, Clone, PartialEq, Eq, Serialize, Deserialize, Debug)]
609pub enum ConsensusChoice {
610    /// Kept only so protocol-config serialization of historical epochs stays
611    /// bit-for-bit identical; no runtime code branches on it.
612    #[deprecated(note = "Mysticeti was replaced by Starfish")]
613    MysticetiDeprecated,
614    #[default]
615    Starfish,
616}
617
618#[expect(deprecated)]
619impl ConsensusChoice {
620    /// serde deserialization default: an absent `consensus_choice` field in a
621    /// historical snapshot deserializes to `MysticetiDeprecated` so that
622    /// re-serialization stays byte-identical (the skip condition below also
623    /// triggers on that variant). Decoupled from the Rust `Default` impl,
624    /// which returns `Starfish` to reflect that Starfish is the current
625    /// consensus protocol.
626    fn mysticeti_deprecated() -> Self {
627        ConsensusChoice::MysticetiDeprecated
628    }
629
630    pub fn is_mysticeti_deprecated(&self) -> bool {
631        matches!(self, ConsensusChoice::MysticetiDeprecated)
632    }
633    pub fn is_starfish(&self) -> bool {
634        matches!(self, ConsensusChoice::Starfish)
635    }
636}
637
638// Configuration options for consensus network.
639#[derive(Default, Copy, Clone, PartialEq, Eq, Serialize, Deserialize, Debug)]
640pub enum ConsensusNetwork {
641    #[default]
642    Tonic,
643}
644
645impl ConsensusNetwork {
646    pub fn is_tonic(&self) -> bool {
647        matches!(self, ConsensusNetwork::Tonic)
648    }
649}
650
651/// Constants that change the behavior of the protocol.
652///
653/// The value of each constant here must be fixed for a given protocol version.
654/// To change the value of a constant, advance the protocol version, and add
655/// support for it in `get_for_version` under the new version number.
656/// (below).
657///
658/// To add a new field to this struct, use the following procedure:
659/// - Advance the protocol version.
660/// - Add the field as a private `Option<T>` to the struct.
661/// - Initialize the field to `None` in prior protocol versions.
662/// - Initialize the field to `Some(val)` for your new protocol version.
663/// - Add a public getter that simply unwraps the field.
664/// - Two public getters of the form `field(&self) -> field_type` and
665///   `field_as_option(&self) -> Option<field_type>` will be automatically
666///   generated for you.
667/// Example for a field: `new_constant: Option<u64>`
668/// ```rust,ignore
669///      pub fn new_constant(&self) -> u64 {
670///         self.new_constant.expect(Self::CONSTANT_ERR_MSG)
671///     }
672///      pub fn new_constant_as_option(&self) -> Option<u64> {
673///         self.new_constant.expect(Self::CONSTANT_ERR_MSG)
674///     }
675/// ```
676/// With `pub fn new_constant(&self) -> u64`, if the constant is accessed in a
677/// protocol version in which it is not defined, the validator will crash.
678/// (Crashing is necessary because this type of error would almost always result
679/// in forking if not prevented here). If you don't want the validator to crash,
680/// you can use the `pub fn new_constant_as_option(&self) -> Option<u64>`
681/// getter, which will return `None` if the field is not defined at that
682/// version.
683/// - If you want a customized getter, you can add a method in the impl.
684#[skip_serializing_none]
685#[derive(Clone, Serialize, Debug, ProtocolConfigAccessors, ProtocolConfigOverride)]
686pub struct ProtocolConfig {
687    pub version: ProtocolVersion,
688
689    feature_flags: FeatureFlags,
690
691    // ==== Transaction input limits ====
692
693    //
694    /// Maximum serialized size of a transaction (in bytes).
695    max_tx_size_bytes: Option<u64>,
696
697    /// Maximum number of input objects to a transaction. Enforced by the
698    /// transaction input checker
699    max_input_objects: Option<u64>,
700
701    /// Max size of objects a transaction can write to disk after completion.
702    /// Enforce by the IOTA adapter. This is the sum of the serialized size
703    /// of all objects written to disk. The max size of individual objects
704    /// on the other hand is `max_move_object_size`.
705    max_size_written_objects: Option<u64>,
706    /// Max size of objects a system transaction can write to disk after
707    /// completion. Enforce by the IOTA adapter. Similar to
708    /// `max_size_written_objects` but for system transactions.
709    max_size_written_objects_system_tx: Option<u64>,
710
711    /// Maximum size of serialized transaction effects.
712    max_serialized_tx_effects_size_bytes: Option<u64>,
713
714    /// Maximum size of serialized transaction effects for system transactions.
715    max_serialized_tx_effects_size_bytes_system_tx: Option<u64>,
716
717    /// Maximum number of gas payment objects for a transaction.
718    max_gas_payment_objects: Option<u32>,
719
720    /// Maximum number of modules in a Publish transaction.
721    max_modules_in_publish: Option<u32>,
722
723    /// Maximum number of transitive dependencies in a package when publishing.
724    max_package_dependencies: Option<u32>,
725
726    /// Maximum number of arguments in a move call or a
727    /// ProgrammableTransaction's TransferObjects command.
728    max_arguments: Option<u32>,
729
730    /// Maximum number of total type arguments, computed recursively.
731    max_type_arguments: Option<u32>,
732
733    /// Maximum depth of an individual type argument.
734    max_type_argument_depth: Option<u32>,
735
736    /// Maximum size of a Pure CallArg.
737    max_pure_argument_size: Option<u32>,
738
739    /// Maximum number of Commands in a ProgrammableTransaction.
740    max_programmable_tx_commands: Option<u32>,
741
742    // ==== Move VM, Move bytecode verifier, and execution limits ===
743
744    //
745    /// Maximum Move bytecode version the VM understands. All older versions are
746    /// accepted.
747    move_binary_format_version: Option<u32>,
748    min_move_binary_format_version: Option<u32>,
749
750    /// Configuration controlling binary tables size.
751    binary_module_handles: Option<u16>,
752    binary_struct_handles: Option<u16>,
753    binary_function_handles: Option<u16>,
754    binary_function_instantiations: Option<u16>,
755    binary_signatures: Option<u16>,
756    binary_constant_pool: Option<u16>,
757    binary_identifiers: Option<u16>,
758    binary_address_identifiers: Option<u16>,
759    binary_struct_defs: Option<u16>,
760    binary_struct_def_instantiations: Option<u16>,
761    binary_function_defs: Option<u16>,
762    binary_field_handles: Option<u16>,
763    binary_field_instantiations: Option<u16>,
764    binary_friend_decls: Option<u16>,
765    binary_enum_defs: Option<u16>,
766    binary_enum_def_instantiations: Option<u16>,
767    binary_variant_handles: Option<u16>,
768    binary_variant_instantiation_handles: Option<u16>,
769
770    /// Maximum size of the `contents` part of an object, in bytes. Enforced by
771    /// the IOTA adapter when effects are produced.
772    max_move_object_size: Option<u64>,
773
774    // TODO: Option<increase to 500 KB. currently, publishing a package > 500 KB exceeds the max
775    // computation gas cost
776    /// Maximum size of a Move package object, in bytes. Enforced by the IOTA
777    /// adapter at the end of a publish transaction.
778    max_move_package_size: Option<u64>,
779
780    /// Max number of publish or upgrade commands allowed in a programmable
781    /// transaction block.
782    max_publish_or_upgrade_per_ptb: Option<u64>,
783
784    /// Maximum gas budget in NANOS that a transaction can use.
785    max_tx_gas: Option<u64>,
786
787    /// Maximum gas budget in NANOS that a authentication transaction can use.
788    max_auth_gas: Option<u64>,
789
790    /// Maximum amount of the proposed gas price in NANOS (defined in the
791    /// transaction).
792    max_gas_price: Option<u64>,
793
794    /// The max computation bucket for gas. This is the max that can be charged
795    /// for computation.
796    max_gas_computation_bucket: Option<u64>,
797
798    // Define the value used to round up computation gas charges
799    gas_rounding_step: Option<u64>,
800
801    /// Maximum number of nested loops. Enforced by the Move bytecode verifier.
802    max_loop_depth: Option<u64>,
803
804    /// Maximum number of type arguments that can be bound to generic type
805    /// parameters. Enforced by the Move bytecode verifier.
806    max_generic_instantiation_length: Option<u64>,
807
808    /// Maximum number of parameters that a Move function can have. Enforced by
809    /// the Move bytecode verifier.
810    max_function_parameters: Option<u64>,
811
812    /// Maximum number of basic blocks that a Move function can have. Enforced
813    /// by the Move bytecode verifier.
814    max_basic_blocks: Option<u64>,
815
816    /// Maximum stack size value. Enforced by the Move bytecode verifier.
817    max_value_stack_size: Option<u64>,
818
819    /// Maximum number of "type nodes", a metric for how big a SignatureToken
820    /// will be when expanded into a fully qualified type. Enforced by the Move
821    /// bytecode verifier.
822    max_type_nodes: Option<u64>,
823
824    /// Maximum number of push instructions in one function. Enforced by the
825    /// Move bytecode verifier.
826    max_push_size: Option<u64>,
827
828    /// Maximum number of struct definitions in a module. Enforced by the Move
829    /// bytecode verifier.
830    max_struct_definitions: Option<u64>,
831
832    /// Maximum number of function definitions in a module. Enforced by the Move
833    /// bytecode verifier.
834    max_function_definitions: Option<u64>,
835
836    /// Maximum number of fields allowed in a struct definition. Enforced by the
837    /// Move bytecode verifier.
838    max_fields_in_struct: Option<u64>,
839
840    /// Maximum dependency depth. Enforced by the Move linker when loading
841    /// dependent modules.
842    max_dependency_depth: Option<u64>,
843
844    /// Maximum number of Move events that a single transaction can emit.
845    /// Enforced by the VM during execution.
846    max_num_event_emit: Option<u64>,
847
848    /// Maximum number of new IDs that a single transaction can create. Enforced
849    /// by the VM during execution.
850    max_num_new_move_object_ids: Option<u64>,
851
852    /// Maximum number of new IDs that a single system transaction can create.
853    /// Enforced by the VM during execution.
854    max_num_new_move_object_ids_system_tx: Option<u64>,
855
856    /// Maximum number of IDs that a single transaction can delete. Enforced by
857    /// the VM during execution.
858    max_num_deleted_move_object_ids: Option<u64>,
859
860    /// Maximum number of IDs that a single system transaction can delete.
861    /// Enforced by the VM during execution.
862    max_num_deleted_move_object_ids_system_tx: Option<u64>,
863
864    /// Maximum number of IDs that a single transaction can transfer. Enforced
865    /// by the VM during execution.
866    max_num_transferred_move_object_ids: Option<u64>,
867
868    /// Maximum number of IDs that a single system transaction can transfer.
869    /// Enforced by the VM during execution.
870    max_num_transferred_move_object_ids_system_tx: Option<u64>,
871
872    /// Maximum size of a Move user event. Enforced by the VM during execution.
873    max_event_emit_size: Option<u64>,
874
875    /// Maximum size of a Move user event. Enforced by the VM during execution.
876    max_event_emit_size_total: Option<u64>,
877
878    /// Maximum length of a vector in Move. Enforced by the VM during execution,
879    /// and for constants, by the verifier.
880    max_move_vector_len: Option<u64>,
881
882    /// Maximum length of an `Identifier` in Move. Enforced by the bytecode
883    /// verifier at signing.
884    max_move_identifier_len: Option<u64>,
885
886    /// Maximum depth of a Move value within the VM.
887    max_move_value_depth: Option<u64>,
888
889    /// Maximum number of variants in an enum. Enforced by the bytecode verifier
890    /// at signing.
891    max_move_enum_variants: Option<u64>,
892
893    /// Maximum number of back edges in Move function. Enforced by the bytecode
894    /// verifier at signing.
895    max_back_edges_per_function: Option<u64>,
896
897    /// Maximum number of back edges in Move module. Enforced by the bytecode
898    /// verifier at signing.
899    max_back_edges_per_module: Option<u64>,
900
901    /// Maximum number of meter `ticks` spent verifying a Move function.
902    /// Enforced by the bytecode verifier at signing.
903    max_verifier_meter_ticks_per_function: Option<u64>,
904
905    /// Maximum number of meter `ticks` spent verifying a Move function.
906    /// Enforced by the bytecode verifier at signing.
907    max_meter_ticks_per_module: Option<u64>,
908
909    /// Maximum number of meter `ticks` spent verifying a Move package. Enforced
910    /// by the bytecode verifier at signing.
911    max_meter_ticks_per_package: Option<u64>,
912
913    // === Object runtime internal operation limits ====
914    // These affect dynamic fields
915
916    //
917    /// Maximum number of cached objects in the object runtime ObjectStore.
918    /// Enforced by object runtime during execution
919    object_runtime_max_num_cached_objects: Option<u64>,
920
921    /// Maximum number of cached objects in the object runtime ObjectStore in
922    /// system transaction. Enforced by object runtime during execution
923    object_runtime_max_num_cached_objects_system_tx: Option<u64>,
924
925    /// Maximum number of stored objects accessed by object runtime ObjectStore.
926    /// Enforced by object runtime during execution
927    object_runtime_max_num_store_entries: Option<u64>,
928
929    /// Maximum number of stored objects accessed by object runtime ObjectStore
930    /// in system transaction. Enforced by object runtime during execution
931    object_runtime_max_num_store_entries_system_tx: Option<u64>,
932
933    // === Execution gas costs ====
934
935    //
936    /// Base cost for any IOTA transaction
937    base_tx_cost_fixed: Option<u64>,
938
939    /// Additional cost for a transaction that publishes a package
940    /// i.e., the base cost of such a transaction is base_tx_cost_fixed +
941    /// package_publish_cost_fixed
942    package_publish_cost_fixed: Option<u64>,
943
944    /// Cost per byte of a Move call transaction
945    /// i.e., the cost of such a transaction is base_cost +
946    /// (base_tx_cost_per_byte * size)
947    base_tx_cost_per_byte: Option<u64>,
948
949    /// Cost per byte for a transaction that publishes a package
950    package_publish_cost_per_byte: Option<u64>,
951
952    // Per-byte cost of reading an object during transaction execution
953    obj_access_cost_read_per_byte: Option<u64>,
954
955    // Per-byte cost of writing an object during transaction execution
956    obj_access_cost_mutate_per_byte: Option<u64>,
957
958    // Per-byte cost of deleting an object during transaction execution
959    obj_access_cost_delete_per_byte: Option<u64>,
960
961    /// Per-byte cost charged for each input object to a transaction.
962    /// Meant to approximate the cost of checking locks for each object
963    // TODO: Option<I'm not sure that this cost makes sense. Checking locks is "free"
964    // in the sense that an invalid tx that can never be committed/pay gas can
965    // force validators to check an arbitrary number of locks. If those checks are
966    // "free" for invalid transactions, why charge for them in valid transactions
967    // TODO: Option<if we keep this, I think we probably want it to be a fixed cost rather
968    // than a per-byte cost. checking an object lock should not require loading an
969    // entire object, just consulting an ID -> tx digest map
970    obj_access_cost_verify_per_byte: Option<u64>,
971
972    // Maximal nodes which are allowed when converting to a type layout.
973    max_type_to_layout_nodes: Option<u64>,
974
975    // Maximal size in bytes that a PTB value can be
976    max_ptb_value_size: Option<u64>,
977
978    // === Gas version. gas model ===
979
980    //
981    /// Gas model version, what code we are using to charge gas
982    gas_model_version: Option<u64>,
983
984    // === Storage gas costs ===
985
986    //
987    /// Per-byte cost of storing an object in the IOTA global object store. Some
988    /// of this cost may be refundable if the object is later freed
989    obj_data_cost_refundable: Option<u64>,
990
991    // Per-byte cost of storing an object in the IOTA transaction log (e.g., in
992    // CertifiedTransactionEffects) This depends on the size of various fields including the
993    // effects TODO: Option<I don't fully understand this^ and more details would be useful
994    obj_metadata_cost_non_refundable: Option<u64>,
995
996    // === Tokenomics ===
997
998    // TODO: Option<this should be changed to u64.
999    /// Sender of a txn that touches an object will get this percent of the
1000    /// storage rebate back. In basis point.
1001    storage_rebate_rate: Option<u64>,
1002
1003    /// The share of rewards that will be slashed and redistributed is 50%.
1004    /// In basis point.
1005    reward_slashing_rate: Option<u64>,
1006
1007    /// Unit storage gas price, Nanos per internal gas unit.
1008    storage_gas_price: Option<u64>,
1009
1010    // Base gas price for computation gas, nanos per computation unit.
1011    base_gas_price: Option<u64>,
1012
1013    /// The number of tokens minted as a validator subsidy per epoch.
1014    validator_target_reward: Option<u64>,
1015
1016    // === Core Protocol ===
1017
1018    //
1019    /// Max number of transactions per checkpoint.
1020    /// Note that this is a protocol constant and not a config as validators
1021    /// must have this set to the same value, otherwise they *will* fork.
1022    max_transactions_per_checkpoint: Option<u64>,
1023
1024    /// Max size of a checkpoint in bytes.
1025    /// Note that this is a protocol constant and not a config as validators
1026    /// must have this set to the same value, otherwise they *will* fork.
1027    max_checkpoint_size_bytes: Option<u64>,
1028
1029    /// A protocol upgrade always requires 2f+1 stake to agree. We support a
1030    /// buffer of additional stake (as a fraction of f, expressed in basis
1031    /// points) that is required before an upgrade can happen automatically.
1032    /// 10000bps would indicate that complete unanimity is required (all
1033    /// 3f+1 must vote), while 0bps would indicate that 2f+1 is sufficient.
1034    buffer_stake_for_protocol_upgrade_bps: Option<u64>,
1035
1036    // === Native Function Costs ===
1037
1038    // `address` module
1039    // Cost params for the Move native function `address::from_bytes(bytes: vector<u8>)`
1040    address_from_bytes_cost_base: Option<u64>,
1041    // Cost params for the Move native function `address::to_u256(address): u256`
1042    address_to_u256_cost_base: Option<u64>,
1043    // Cost params for the Move native function `address::from_u256(u256): address`
1044    address_from_u256_cost_base: Option<u64>,
1045
1046    // `config` module
1047    // Cost params for the Move native function `read_setting_impl<Name: copy + drop + store,
1048    // SettingValue: key + store, SettingDataValue: store, Value: copy + drop + store,
1049    // >(config: address, name: address, current_epoch: u64): Option<Value>`
1050    config_read_setting_impl_cost_base: Option<u64>,
1051    config_read_setting_impl_cost_per_byte: Option<u64>,
1052
1053    // `dynamic_field` module
1054    // Cost params for the Move native function `hash_type_and_key<K: copy + drop + store>(parent:
1055    // address, k: K): address`
1056    dynamic_field_hash_type_and_key_cost_base: Option<u64>,
1057    dynamic_field_hash_type_and_key_type_cost_per_byte: Option<u64>,
1058    dynamic_field_hash_type_and_key_value_cost_per_byte: Option<u64>,
1059    dynamic_field_hash_type_and_key_type_tag_cost_per_byte: Option<u64>,
1060    // Cost params for the Move native function `add_child_object<Child: key>(parent: address,
1061    // child: Child)`
1062    dynamic_field_add_child_object_cost_base: Option<u64>,
1063    dynamic_field_add_child_object_type_cost_per_byte: Option<u64>,
1064    dynamic_field_add_child_object_value_cost_per_byte: Option<u64>,
1065    dynamic_field_add_child_object_struct_tag_cost_per_byte: Option<u64>,
1066    // Cost params for the Move native function `borrow_child_object_mut<Child: key>(parent: &mut
1067    // UID, id: address): &mut Child`
1068    dynamic_field_borrow_child_object_cost_base: Option<u64>,
1069    dynamic_field_borrow_child_object_child_ref_cost_per_byte: Option<u64>,
1070    dynamic_field_borrow_child_object_type_cost_per_byte: Option<u64>,
1071    // Cost params for the Move native function `remove_child_object<Child: key>(parent: address,
1072    // id: address): Child`
1073    dynamic_field_remove_child_object_cost_base: Option<u64>,
1074    dynamic_field_remove_child_object_child_cost_per_byte: Option<u64>,
1075    dynamic_field_remove_child_object_type_cost_per_byte: Option<u64>,
1076    // Cost params for the Move native function `has_child_object(parent: address, id: address):
1077    // bool`
1078    dynamic_field_has_child_object_cost_base: Option<u64>,
1079    // Cost params for the Move native function `has_child_object_with_ty<Child: key>(parent:
1080    // address, id: address): bool`
1081    dynamic_field_has_child_object_with_ty_cost_base: Option<u64>,
1082    dynamic_field_has_child_object_with_ty_type_cost_per_byte: Option<u64>,
1083    dynamic_field_has_child_object_with_ty_type_tag_cost_per_byte: Option<u64>,
1084
1085    // `event` module
1086    // Cost params for the Move native function `event::emit<T: copy + drop>(event: T)`
1087    event_emit_cost_base: Option<u64>,
1088    event_emit_value_size_derivation_cost_per_byte: Option<u64>,
1089    event_emit_tag_size_derivation_cost_per_byte: Option<u64>,
1090    event_emit_output_cost_per_byte: Option<u64>,
1091
1092    //  `object` module
1093    // Cost params for the Move native function `borrow_uid<T: key>(obj: &T): &UID`
1094    object_borrow_uid_cost_base: Option<u64>,
1095    // Cost params for the Move native function `delete_impl(id: address)`
1096    object_delete_impl_cost_base: Option<u64>,
1097    // Cost params for the Move native function `record_new_uid(id: address)`
1098    object_record_new_uid_cost_base: Option<u64>,
1099
1100    // Transfer
1101    // Cost params for the Move native function `transfer_impl<T: key>(obj: T, recipient: address)`
1102    transfer_transfer_internal_cost_base: Option<u64>,
1103    // Cost params for the Move native function `freeze_object<T: key>(obj: T)`
1104    transfer_freeze_object_cost_base: Option<u64>,
1105    // Cost params for the Move native function `share_object<T: key>(obj: T)`
1106    transfer_share_object_cost_base: Option<u64>,
1107    // Cost params for the Move native function
1108    // `receive_object<T: key>(p: &mut UID, recv: Receiving<T>T)`
1109    transfer_receive_object_cost_base: Option<u64>,
1110
1111    // TxContext
1112    // Cost params for the Move native function `transfer_impl<T: key>(obj: T, recipient: address)`
1113    tx_context_derive_id_cost_base: Option<u64>,
1114    tx_context_fresh_id_cost_base: Option<u64>,
1115    tx_context_sender_cost_base: Option<u64>,
1116    tx_context_digest_cost_base: Option<u64>,
1117    tx_context_epoch_cost_base: Option<u64>,
1118    tx_context_epoch_timestamp_ms_cost_base: Option<u64>,
1119    tx_context_sponsor_cost_base: Option<u64>,
1120    tx_context_rgp_cost_base: Option<u64>,
1121    tx_context_gas_price_cost_base: Option<u64>,
1122    tx_context_gas_budget_cost_base: Option<u64>,
1123    tx_context_ids_created_cost_base: Option<u64>,
1124    tx_context_replace_cost_base: Option<u64>,
1125
1126    // Types
1127    // Cost params for the Move native function `is_one_time_witness<T: drop>(_: &T): bool`
1128    types_is_one_time_witness_cost_base: Option<u64>,
1129    types_is_one_time_witness_type_tag_cost_per_byte: Option<u64>,
1130    types_is_one_time_witness_type_cost_per_byte: Option<u64>,
1131
1132    // Validator
1133    // Cost params for the Move native function `validate_metadata_bcs(metadata: vector<u8>)`
1134    validator_validate_metadata_cost_base: Option<u64>,
1135    validator_validate_metadata_data_cost_per_byte: Option<u64>,
1136
1137    // Crypto natives
1138    crypto_invalid_arguments_cost: Option<u64>,
1139    // bls12381::bls12381_min_sig_verify
1140    bls12381_bls12381_min_sig_verify_cost_base: Option<u64>,
1141    bls12381_bls12381_min_sig_verify_msg_cost_per_byte: Option<u64>,
1142    bls12381_bls12381_min_sig_verify_msg_cost_per_block: Option<u64>,
1143
1144    // bls12381::bls12381_min_pk_verify
1145    bls12381_bls12381_min_pk_verify_cost_base: Option<u64>,
1146    bls12381_bls12381_min_pk_verify_msg_cost_per_byte: Option<u64>,
1147    bls12381_bls12381_min_pk_verify_msg_cost_per_block: Option<u64>,
1148
1149    // ecdsa_k1::ecrecover
1150    ecdsa_k1_ecrecover_keccak256_cost_base: Option<u64>,
1151    ecdsa_k1_ecrecover_keccak256_msg_cost_per_byte: Option<u64>,
1152    ecdsa_k1_ecrecover_keccak256_msg_cost_per_block: Option<u64>,
1153    ecdsa_k1_ecrecover_sha256_cost_base: Option<u64>,
1154    ecdsa_k1_ecrecover_sha256_msg_cost_per_byte: Option<u64>,
1155    ecdsa_k1_ecrecover_sha256_msg_cost_per_block: Option<u64>,
1156
1157    // ecdsa_k1::decompress_pubkey
1158    ecdsa_k1_decompress_pubkey_cost_base: Option<u64>,
1159
1160    // ecdsa_k1::secp256k1_verify
1161    ecdsa_k1_secp256k1_verify_keccak256_cost_base: Option<u64>,
1162    ecdsa_k1_secp256k1_verify_keccak256_msg_cost_per_byte: Option<u64>,
1163    ecdsa_k1_secp256k1_verify_keccak256_msg_cost_per_block: Option<u64>,
1164    ecdsa_k1_secp256k1_verify_sha256_cost_base: Option<u64>,
1165    ecdsa_k1_secp256k1_verify_sha256_msg_cost_per_byte: Option<u64>,
1166    ecdsa_k1_secp256k1_verify_sha256_msg_cost_per_block: Option<u64>,
1167
1168    // ecdsa_r1::ecrecover
1169    ecdsa_r1_ecrecover_keccak256_cost_base: Option<u64>,
1170    ecdsa_r1_ecrecover_keccak256_msg_cost_per_byte: Option<u64>,
1171    ecdsa_r1_ecrecover_keccak256_msg_cost_per_block: Option<u64>,
1172    ecdsa_r1_ecrecover_sha256_cost_base: Option<u64>,
1173    ecdsa_r1_ecrecover_sha256_msg_cost_per_byte: Option<u64>,
1174    ecdsa_r1_ecrecover_sha256_msg_cost_per_block: Option<u64>,
1175
1176    // ecdsa_r1::secp256k1_verify
1177    ecdsa_r1_secp256r1_verify_keccak256_cost_base: Option<u64>,
1178    ecdsa_r1_secp256r1_verify_keccak256_msg_cost_per_byte: Option<u64>,
1179    ecdsa_r1_secp256r1_verify_keccak256_msg_cost_per_block: Option<u64>,
1180    ecdsa_r1_secp256r1_verify_sha256_cost_base: Option<u64>,
1181    ecdsa_r1_secp256r1_verify_sha256_msg_cost_per_byte: Option<u64>,
1182    ecdsa_r1_secp256r1_verify_sha256_msg_cost_per_block: Option<u64>,
1183
1184    // ecvrf::verify
1185    ecvrf_ecvrf_verify_cost_base: Option<u64>,
1186    ecvrf_ecvrf_verify_alpha_string_cost_per_byte: Option<u64>,
1187    ecvrf_ecvrf_verify_alpha_string_cost_per_block: Option<u64>,
1188
1189    // ed25519
1190    ed25519_ed25519_verify_cost_base: Option<u64>,
1191    ed25519_ed25519_verify_msg_cost_per_byte: Option<u64>,
1192    ed25519_ed25519_verify_msg_cost_per_block: Option<u64>,
1193
1194    // groth16::prepare_verifying_key
1195    groth16_prepare_verifying_key_bls12381_cost_base: Option<u64>,
1196    groth16_prepare_verifying_key_bn254_cost_base: Option<u64>,
1197
1198    // groth16::verify_groth16_proof_internal
1199    groth16_verify_groth16_proof_internal_bls12381_cost_base: Option<u64>,
1200    groth16_verify_groth16_proof_internal_bls12381_cost_per_public_input: Option<u64>,
1201    groth16_verify_groth16_proof_internal_bn254_cost_base: Option<u64>,
1202    groth16_verify_groth16_proof_internal_bn254_cost_per_public_input: Option<u64>,
1203    groth16_verify_groth16_proof_internal_public_input_cost_per_byte: Option<u64>,
1204
1205    // hash::blake2b256
1206    hash_blake2b256_cost_base: Option<u64>,
1207    hash_blake2b256_data_cost_per_byte: Option<u64>,
1208    hash_blake2b256_data_cost_per_block: Option<u64>,
1209
1210    // hash::keccak256
1211    hash_keccak256_cost_base: Option<u64>,
1212    hash_keccak256_data_cost_per_byte: Option<u64>,
1213    hash_keccak256_data_cost_per_block: Option<u64>,
1214
1215    // poseidon::poseidon_bn254
1216    poseidon_bn254_cost_base: Option<u64>,
1217    poseidon_bn254_cost_per_block: Option<u64>,
1218
1219    // group_ops
1220    group_ops_bls12381_decode_scalar_cost: Option<u64>,
1221    group_ops_bls12381_decode_g1_cost: Option<u64>,
1222    group_ops_bls12381_decode_g2_cost: Option<u64>,
1223    group_ops_bls12381_decode_gt_cost: Option<u64>,
1224    group_ops_bls12381_scalar_add_cost: Option<u64>,
1225    group_ops_bls12381_g1_add_cost: Option<u64>,
1226    group_ops_bls12381_g2_add_cost: Option<u64>,
1227    group_ops_bls12381_gt_add_cost: Option<u64>,
1228    group_ops_bls12381_scalar_sub_cost: Option<u64>,
1229    group_ops_bls12381_g1_sub_cost: Option<u64>,
1230    group_ops_bls12381_g2_sub_cost: Option<u64>,
1231    group_ops_bls12381_gt_sub_cost: Option<u64>,
1232    group_ops_bls12381_scalar_mul_cost: Option<u64>,
1233    group_ops_bls12381_g1_mul_cost: Option<u64>,
1234    group_ops_bls12381_g2_mul_cost: Option<u64>,
1235    group_ops_bls12381_gt_mul_cost: Option<u64>,
1236    group_ops_bls12381_scalar_div_cost: Option<u64>,
1237    group_ops_bls12381_g1_div_cost: Option<u64>,
1238    group_ops_bls12381_g2_div_cost: Option<u64>,
1239    group_ops_bls12381_gt_div_cost: Option<u64>,
1240    group_ops_bls12381_g1_hash_to_base_cost: Option<u64>,
1241    group_ops_bls12381_g2_hash_to_base_cost: Option<u64>,
1242    group_ops_bls12381_g1_hash_to_cost_per_byte: Option<u64>,
1243    group_ops_bls12381_g2_hash_to_cost_per_byte: Option<u64>,
1244    group_ops_bls12381_g1_msm_base_cost: Option<u64>,
1245    group_ops_bls12381_g2_msm_base_cost: Option<u64>,
1246    group_ops_bls12381_g1_msm_base_cost_per_input: Option<u64>,
1247    group_ops_bls12381_g2_msm_base_cost_per_input: Option<u64>,
1248    group_ops_bls12381_msm_max_len: Option<u32>,
1249    group_ops_bls12381_pairing_cost: Option<u64>,
1250    group_ops_bls12381_g1_to_uncompressed_g1_cost: Option<u64>,
1251    group_ops_bls12381_uncompressed_g1_to_g1_cost: Option<u64>,
1252    group_ops_bls12381_uncompressed_g1_sum_base_cost: Option<u64>,
1253    group_ops_bls12381_uncompressed_g1_sum_cost_per_term: Option<u64>,
1254    group_ops_bls12381_uncompressed_g1_sum_max_terms: Option<u64>,
1255
1256    // hmac::hmac_sha3_256
1257    hmac_hmac_sha3_256_cost_base: Option<u64>,
1258    hmac_hmac_sha3_256_input_cost_per_byte: Option<u64>,
1259    hmac_hmac_sha3_256_input_cost_per_block: Option<u64>,
1260
1261    // zklogin::check_zklogin_id
1262    #[deprecated]
1263    check_zklogin_id_cost_base: Option<u64>,
1264    // zklogin::check_zklogin_issuer
1265    #[deprecated]
1266    check_zklogin_issuer_cost_base: Option<u64>,
1267
1268    vdf_verify_vdf_cost: Option<u64>,
1269    vdf_hash_to_input_cost: Option<u64>,
1270
1271    // Stdlib costs
1272    bcs_per_byte_serialized_cost: Option<u64>,
1273    bcs_legacy_min_output_size_cost: Option<u64>,
1274    bcs_failure_cost: Option<u64>,
1275
1276    hash_sha2_256_base_cost: Option<u64>,
1277    hash_sha2_256_per_byte_cost: Option<u64>,
1278    hash_sha2_256_legacy_min_input_len_cost: Option<u64>,
1279    hash_sha3_256_base_cost: Option<u64>,
1280    hash_sha3_256_per_byte_cost: Option<u64>,
1281    hash_sha3_256_legacy_min_input_len_cost: Option<u64>,
1282    type_name_get_base_cost: Option<u64>,
1283    type_name_get_per_byte_cost: Option<u64>,
1284
1285    string_check_utf8_base_cost: Option<u64>,
1286    string_check_utf8_per_byte_cost: Option<u64>,
1287    string_is_char_boundary_base_cost: Option<u64>,
1288    string_sub_string_base_cost: Option<u64>,
1289    string_sub_string_per_byte_cost: Option<u64>,
1290    string_index_of_base_cost: Option<u64>,
1291    string_index_of_per_byte_pattern_cost: Option<u64>,
1292    string_index_of_per_byte_searched_cost: Option<u64>,
1293
1294    vector_empty_base_cost: Option<u64>,
1295    vector_length_base_cost: Option<u64>,
1296    vector_push_back_base_cost: Option<u64>,
1297    vector_push_back_legacy_per_abstract_memory_unit_cost: Option<u64>,
1298    vector_borrow_base_cost: Option<u64>,
1299    vector_pop_back_base_cost: Option<u64>,
1300    vector_destroy_empty_base_cost: Option<u64>,
1301    vector_swap_base_cost: Option<u64>,
1302    debug_print_base_cost: Option<u64>,
1303    debug_print_stack_trace_base_cost: Option<u64>,
1304
1305    // === Execution Version ===
1306    execution_version: Option<u64>,
1307
1308    // Dictates the threshold (percentage of stake) that is used to calculate the "bad" nodes to be
1309    // swapped when creating the consensus schedule. The values should be of the range [0 - 33].
1310    // Anything above 33 (f) will not be allowed.
1311    consensus_bad_nodes_stake_threshold: Option<u64>,
1312
1313    #[deprecated]
1314    max_jwk_votes_per_validator_per_epoch: Option<u64>,
1315    // The maximum age of a JWK in epochs before it is removed from the AuthenticatorState object.
1316    // Applied at the end of an epoch as a delta from the new epoch value, so setting this to 1
1317    // will cause the new epoch to start with JWKs from the previous epoch still valid.
1318    #[deprecated]
1319    max_age_of_jwk_in_epochs: Option<u64>,
1320
1321    // === random beacon ===
1322    /// Maximum allowed precision loss when reducing voting weights for the
1323    /// random beacon protocol.
1324    random_beacon_reduction_allowed_delta: Option<u16>,
1325
1326    /// Minimum number of shares below which voting weights will not be reduced
1327    /// for the random beacon protocol.
1328    random_beacon_reduction_lower_bound: Option<u32>,
1329
1330    /// Consensus Round after which DKG should be aborted and randomness
1331    /// disabled for the epoch, if it hasn't already completed.
1332    random_beacon_dkg_timeout_round: Option<u32>,
1333
1334    /// Minimum interval between consecutive rounds of generated randomness.
1335    random_beacon_min_round_interval_ms: Option<u64>,
1336
1337    /// Version of the random beacon DKG protocol.
1338    /// 0 was deprecated (and currently not supported), 1 is the default
1339    /// version.
1340    random_beacon_dkg_version: Option<u64>,
1341
1342    /// The maximum serialized transaction size (in bytes) accepted by
1343    /// consensus. `consensus_max_transaction_size_bytes` should include
1344    /// space for additional metadata, on top of the `max_tx_size_bytes`
1345    /// value.
1346    consensus_max_transaction_size_bytes: Option<u64>,
1347    /// The maximum size of transactions included in a consensus block.
1348    consensus_max_transactions_in_block_bytes: Option<u64>,
1349    /// The maximum number of transactions included in a consensus block.
1350    consensus_max_num_transactions_in_block: Option<u64>,
1351
1352    /// The max number of consensus rounds a transaction can be deferred due to
1353    /// shared object congestion. Transactions will be cancelled after this
1354    /// many rounds.
1355    max_deferral_rounds_for_congestion_control: Option<u64>,
1356
1357    /// Minimum interval of commit timestamps between consecutive checkpoints.
1358    min_checkpoint_interval_ms: Option<u64>,
1359
1360    /// Number of recent checkpoints over which `min_checkpoint_interval_ms`
1361    /// may be amortized. When set, a checkpoint is built once the full
1362    /// interval elapsed since the previous checkpoint, or once the checkpoint
1363    /// this many back in the current epoch is at least that many intervals
1364    /// older. The windowed arm recycles the slack that discrete commit
1365    /// timestamps add to the strict arm, holding the sustained rate at the
1366    /// ceiling, while the strict arm keeps quiet gaps within one interval.
1367    /// The window does not cross epoch boundaries; before it fills — and
1368    /// always when unset — only the strict adjacent check applies.
1369    checkpoint_rate_window_size: Option<u64>,
1370
1371    /// Version number to use for version_specific_data in `CheckpointSummary`.
1372    checkpoint_summary_version_specific_data: Option<u64>,
1373
1374    /// The max number of transactions that can be included in a single Soft
1375    /// Bundle.
1376    max_soft_bundle_size: Option<u64>,
1377
1378    /// Deprecated because of bridge removal.
1379    /// Whether to try to form bridge committee
1380    // Note: this is not a feature flag because we want to distinguish between
1381    // `None` and `Some(false)`, as committee was already finalized on Testnet.
1382    bridge_should_try_to_finalize_committee: Option<bool>,
1383
1384    /// The max accumulated txn execution cost per object in a mysticeti commit.
1385    /// Transactions in a commit will be deferred once their touch shared
1386    /// objects hit this limit. Note that if
1387    /// `max_congestion_limit_overshoot_per_commit` is set, this may be overshot
1388    /// within a single commit, but the limit will be enforced in the long run.
1389    max_accumulated_txn_cost_per_object_in_mysticeti_commit: Option<u64>,
1390
1391    /// Maximum number of committee (validators taking part in consensus)
1392    /// validators at any moment. We do not allow the number of committee
1393    /// validators in any epoch to go above this.
1394    max_committee_members_count: Option<u64>,
1395
1396    /// Configures the garbage collection depth for consensus. When is unset or
1397    /// `0` then the garbage collection is disabled.
1398    consensus_gc_depth: Option<u32>,
1399
1400    /// Configures the maximum number of acknowledgments to be included in a
1401    /// block. It must be reasonably larger than the number of validators
1402    /// because not all validators create their blocks at the same pace.
1403    /// Default value set to 400. (5 x expected committee size (80)).
1404    /// Applicable only to `starfish` consensus.
1405    consensus_max_acknowledgments_per_block: Option<u32>,
1406
1407    /// The maximum amount that is allowed to overshoot the congestion limit
1408    /// specified by 'max_accumulated_txn_cost_per_object_in_mysticeti_commit'
1409    /// for any single commit. Any overshoot is tracked as a debt that must
1410    /// be accounted for in subsequent commits.
1411    max_congestion_limit_overshoot_per_commit: Option<u64>,
1412
1413    /// Scorer version. When set to `None`, MisbehaviorReports are not sent nor
1414    /// considered valid. When set to `Some(version)`, scores are included in
1415    /// the MisbehaviorReports messages, where `version` determines the scoring
1416    /// formulas and metrics to be used. Even if set to None, the Scorer
1417    /// component is created, having access to metrics and being able to expose
1418    /// validator scores. Also gates the wire format of the
1419    /// `MisbehaviorReport` consensus transaction — scorer and report bump
1420    /// together.
1421    scorer_version: Option<u16>,
1422
1423    // `auth_context` module
1424    // Cost params for the Move native function `native_digest(): vector<u8>`
1425    auth_context_digest_cost_base: Option<u64>,
1426    // Cost params for the Move native function `native_tx_data_bytes(): &vector<u8>`
1427    auth_context_tx_data_bytes_cost_base: Option<u64>,
1428    auth_context_tx_data_bytes_cost_per_byte: Option<u64>,
1429    // Cost params for the Move native function `native_tx_commands<C>(): vector<C>`
1430    auth_context_tx_commands_cost_base: Option<u64>,
1431    auth_context_tx_commands_cost_per_byte: Option<u64>,
1432    // Cost params for the Move native function `native_tx_inputs<I>(): vector<I>`
1433    auth_context_tx_inputs_cost_base: Option<u64>,
1434    auth_context_tx_inputs_cost_per_byte: Option<u64>,
1435    // Cost params for the Move native function `fun native_replace<I, C>(auth_digest: vector<u8>,
1436    // tx_inputs: vector<I>, tx_commands: vector<C>, tx_data_bytes: vector<u8>)`
1437    auth_context_replace_cost_base: Option<u64>,
1438    auth_context_replace_cost_per_byte: Option<u64>,
1439    // Cost params for the Move native functions
1440    // `fun native_sender_authenticator_function_info_v1<F>(): &Option<F>`
1441    // `fun native_sponsor_authenticator_function_info_v1<F>(): &Option<F>`
1442    auth_context_authenticator_function_info_v1_cost_base: Option<u64>,
1443
1444    /// Number of committed subdags between leader-schedule recomputations.
1445    /// When unset, defaults to 300.
1446    consensus_commits_per_schedule: Option<u32>,
1447}
1448
1449// feature flags
1450impl ProtocolConfig {
1451    // Add checks for feature flag support here, e.g.:
1452    // pub fn check_new_protocol_feature_supported(&self) -> Result<(), Error> {
1453    //     if self.feature_flags.new_protocol_feature_supported {
1454    //         Ok(())
1455    //     } else {
1456    //         Err(Error(format!(
1457    //             "new_protocol_feature is not supported at {:?}",
1458    //             self.version
1459    //         )))
1460    //     }
1461    // }
1462
1463    pub fn disable_invariant_violation_check_in_swap_loc(&self) -> bool {
1464        self.feature_flags
1465            .disable_invariant_violation_check_in_swap_loc
1466    }
1467
1468    pub fn no_extraneous_module_bytes(&self) -> bool {
1469        self.feature_flags.no_extraneous_module_bytes
1470    }
1471
1472    pub fn consensus_transaction_ordering(&self) -> ConsensusTransactionOrdering {
1473        self.feature_flags.consensus_transaction_ordering
1474    }
1475
1476    pub fn dkg_version(&self) -> u64 {
1477        // Version 0 was deprecated and removed, the default is 1 if not set.
1478        self.random_beacon_dkg_version.unwrap_or(1)
1479    }
1480
1481    pub fn hardened_otw_check(&self) -> bool {
1482        self.feature_flags.hardened_otw_check
1483    }
1484
1485    pub fn enable_poseidon(&self) -> bool {
1486        self.feature_flags.enable_poseidon
1487    }
1488
1489    pub fn enable_group_ops_native_function_msm(&self) -> bool {
1490        self.feature_flags.enable_group_ops_native_function_msm
1491    }
1492
1493    pub fn per_object_congestion_control_mode(&self) -> PerObjectCongestionControlMode {
1494        self.feature_flags.per_object_congestion_control_mode
1495    }
1496
1497    pub fn consensus_choice(&self) -> ConsensusChoice {
1498        self.feature_flags.consensus_choice
1499    }
1500
1501    pub fn consensus_network(&self) -> ConsensusNetwork {
1502        self.feature_flags.consensus_network
1503    }
1504
1505    pub fn enable_vdf(&self) -> bool {
1506        self.feature_flags.enable_vdf
1507    }
1508
1509    pub fn passkey_auth(&self) -> bool {
1510        self.feature_flags.passkey_auth
1511    }
1512
1513    pub fn max_transaction_size_bytes(&self) -> u64 {
1514        // Provide a default value if protocol config version is too low.
1515        self.consensus_max_transaction_size_bytes
1516            .unwrap_or(256 * 1024)
1517    }
1518
1519    pub fn max_transactions_in_block_bytes(&self) -> u64 {
1520        if cfg!(msim) {
1521            256 * 1024
1522        } else {
1523            self.consensus_max_transactions_in_block_bytes
1524                .unwrap_or(512 * 1024)
1525        }
1526    }
1527
1528    pub fn max_num_transactions_in_block(&self) -> u64 {
1529        if cfg!(msim) {
1530            8
1531        } else {
1532            self.consensus_max_num_transactions_in_block.unwrap_or(512)
1533        }
1534    }
1535
1536    pub fn rethrow_serialization_type_layout_errors(&self) -> bool {
1537        self.feature_flags.rethrow_serialization_type_layout_errors
1538    }
1539
1540    pub fn relocate_event_module(&self) -> bool {
1541        self.feature_flags.relocate_event_module
1542    }
1543
1544    pub fn protocol_defined_base_fee(&self) -> bool {
1545        self.feature_flags.protocol_defined_base_fee
1546    }
1547
1548    pub fn uncompressed_g1_group_elements(&self) -> bool {
1549        self.feature_flags.uncompressed_g1_group_elements
1550    }
1551
1552    pub fn disallow_new_modules_in_deps_only_packages(&self) -> bool {
1553        self.feature_flags
1554            .disallow_new_modules_in_deps_only_packages
1555    }
1556
1557    pub fn native_charging_v2(&self) -> bool {
1558        self.feature_flags.native_charging_v2
1559    }
1560
1561    pub fn consensus_round_prober(&self) -> bool {
1562        self.feature_flags.consensus_round_prober
1563    }
1564
1565    pub fn consensus_distributed_vote_scoring_strategy(&self) -> bool {
1566        self.feature_flags
1567            .consensus_distributed_vote_scoring_strategy
1568    }
1569
1570    pub fn gc_depth(&self) -> u32 {
1571        if cfg!(msim) {
1572            // exercise a very low gc_depth
1573            min(5, self.consensus_gc_depth.unwrap_or(0))
1574        } else {
1575            self.consensus_gc_depth.unwrap_or(0)
1576        }
1577    }
1578
1579    pub fn consensus_linearize_subdag_v2(&self) -> bool {
1580        let res = self.feature_flags.consensus_linearize_subdag_v2;
1581        assert!(
1582            !res || self.gc_depth() > 0,
1583            "The consensus linearize sub dag V2 requires GC to be enabled"
1584        );
1585        res
1586    }
1587
1588    pub fn consensus_max_acknowledgments_per_block_or_default(&self) -> u32 {
1589        self.consensus_max_acknowledgments_per_block.unwrap_or(400)
1590    }
1591
1592    pub fn max_acknowledgments_per_block(&self, committee_size: usize) -> usize {
1593        2 * committee_size
1594    }
1595
1596    pub fn max_commit_votes_per_block(&self, committee_size: usize) -> usize {
1597        committee_size
1598    }
1599
1600    pub fn variant_nodes(&self) -> bool {
1601        self.feature_flags.variant_nodes
1602    }
1603
1604    pub fn consensus_smart_ancestor_selection(&self) -> bool {
1605        self.feature_flags.consensus_smart_ancestor_selection
1606    }
1607
1608    pub fn consensus_round_prober_probe_accepted_rounds(&self) -> bool {
1609        self.feature_flags
1610            .consensus_round_prober_probe_accepted_rounds
1611    }
1612
1613    pub fn consensus_zstd_compression(&self) -> bool {
1614        self.feature_flags.consensus_zstd_compression
1615    }
1616
1617    pub fn congestion_control_min_free_execution_slot(&self) -> bool {
1618        self.feature_flags
1619            .congestion_control_min_free_execution_slot
1620    }
1621
1622    pub fn accept_passkey_in_multisig(&self) -> bool {
1623        self.feature_flags.accept_passkey_in_multisig
1624    }
1625
1626    pub fn consensus_batched_block_sync(&self) -> bool {
1627        self.feature_flags.consensus_batched_block_sync
1628    }
1629
1630    /// Check if the gas price feedback mechanism (which is used for
1631    /// transactions cancelled due to shared object congestion) is enabled
1632    pub fn congestion_control_gas_price_feedback_mechanism(&self) -> bool {
1633        self.feature_flags
1634            .congestion_control_gas_price_feedback_mechanism
1635    }
1636
1637    pub fn validate_identifier_inputs(&self) -> bool {
1638        self.feature_flags.validate_identifier_inputs
1639    }
1640
1641    pub fn minimize_child_object_mutations(&self) -> bool {
1642        self.feature_flags.minimize_child_object_mutations
1643    }
1644
1645    pub fn dependency_linkage_error(&self) -> bool {
1646        self.feature_flags.dependency_linkage_error
1647    }
1648
1649    pub fn additional_multisig_checks(&self) -> bool {
1650        self.feature_flags.additional_multisig_checks
1651    }
1652
1653    pub fn consensus_num_requested_prior_commits_at_startup(&self) -> u32 {
1654        // TODO: this will eventually be the max of some number of other
1655        // parameters.
1656        0
1657    }
1658
1659    pub fn normalize_ptb_arguments(&self) -> bool {
1660        self.feature_flags.normalize_ptb_arguments
1661    }
1662
1663    pub fn select_committee_from_eligible_validators(&self) -> bool {
1664        let res = self.feature_flags.select_committee_from_eligible_validators;
1665        assert!(
1666            !res || (self.protocol_defined_base_fee()
1667                && self.max_committee_members_count_as_option().is_some()),
1668            "select_committee_from_eligible_validators requires protocol_defined_base_fee and max_committee_members_count to be set"
1669        );
1670        res
1671    }
1672
1673    pub fn track_non_committee_eligible_validators(&self) -> bool {
1674        self.feature_flags.track_non_committee_eligible_validators
1675    }
1676
1677    pub fn select_committee_supporting_next_epoch_version(&self) -> bool {
1678        let res = self
1679            .feature_flags
1680            .select_committee_supporting_next_epoch_version;
1681        assert!(
1682            !res || (self.track_non_committee_eligible_validators()
1683                && self.select_committee_from_eligible_validators()),
1684            "select_committee_supporting_next_epoch_version requires select_committee_from_eligible_validators to be set"
1685        );
1686        res
1687    }
1688
1689    pub fn consensus_median_timestamp_with_checkpoint_enforcement(&self) -> bool {
1690        let res = self
1691            .feature_flags
1692            .consensus_median_timestamp_with_checkpoint_enforcement;
1693        assert!(
1694            !res || self.gc_depth() > 0,
1695            "The consensus median timestamp with checkpoint enforcement requires GC to be enabled"
1696        );
1697        res
1698    }
1699
1700    pub fn consensus_commit_transactions_only_for_traversed_headers(&self) -> bool {
1701        self.feature_flags
1702            .consensus_commit_transactions_only_for_traversed_headers
1703    }
1704
1705    /// Check whether congestion limit overshoot is enabled in the gas price
1706    /// feedback mechanism.
1707    pub fn congestion_limit_overshoot_in_gas_price_feedback_mechanism(&self) -> bool {
1708        self.feature_flags
1709            .congestion_limit_overshoot_in_gas_price_feedback_mechanism
1710    }
1711
1712    /// Check whether a separate gas price feedback mechanism is used for
1713    /// randomness transactions.
1714    pub fn separate_gas_price_feedback_mechanism_for_randomness(&self) -> bool {
1715        self.feature_flags
1716            .separate_gas_price_feedback_mechanism_for_randomness
1717    }
1718
1719    pub fn metadata_in_module_bytes(&self) -> bool {
1720        self.feature_flags.metadata_in_module_bytes
1721    }
1722
1723    pub fn publish_package_metadata(&self) -> bool {
1724        self.feature_flags.publish_package_metadata
1725    }
1726
1727    pub fn enable_move_authentication(&self) -> bool {
1728        self.feature_flags.enable_move_authentication
1729    }
1730
1731    pub fn additional_borrow_checks(&self) -> bool {
1732        self.feature_flags.additional_borrow_checks
1733    }
1734
1735    pub fn enable_move_authentication_for_sponsor(&self) -> bool {
1736        let enable_move_authentication_for_sponsor =
1737            self.feature_flags.enable_move_authentication_for_sponsor;
1738        assert!(
1739            !enable_move_authentication_for_sponsor || self.enable_move_authentication(),
1740            "enable_move_authentication_for_sponsor requires enable_move_authentication to be set"
1741        );
1742        enable_move_authentication_for_sponsor
1743    }
1744
1745    pub fn pass_validator_scores_to_advance_epoch(&self) -> bool {
1746        self.feature_flags.pass_validator_scores_to_advance_epoch
1747    }
1748
1749    pub fn calculate_validator_scores(&self) -> bool {
1750        let calculate_validator_scores = self.feature_flags.calculate_validator_scores;
1751        assert!(
1752            !calculate_validator_scores || self.scorer_version.is_some(),
1753            "calculate_validator_scores requires scorer_version to be set"
1754        );
1755        calculate_validator_scores
1756    }
1757
1758    pub fn adjust_rewards_by_score(&self) -> bool {
1759        let adjust = self.feature_flags.adjust_rewards_by_score;
1760        assert!(
1761            !adjust || (self.scorer_version.is_some() && self.calculate_validator_scores()),
1762            "adjust_rewards_by_score requires scorer_version to be set"
1763        );
1764        adjust
1765    }
1766
1767    pub fn pass_calculated_validator_scores_to_advance_epoch(&self) -> bool {
1768        let pass = self
1769            .feature_flags
1770            .pass_calculated_validator_scores_to_advance_epoch;
1771        assert!(
1772            !pass
1773                || (self.pass_validator_scores_to_advance_epoch()
1774                    && self.calculate_validator_scores()),
1775            "pass_calculated_validator_scores_to_advance_epoch requires pass_validator_scores_to_advance_epoch and calculate_validator_scores to be enabled"
1776        );
1777        pass
1778    }
1779    pub fn consensus_fast_commit_sync(&self) -> bool {
1780        let res = self.feature_flags.consensus_fast_commit_sync;
1781        assert!(
1782            !res || self.consensus_commit_transactions_only_for_traversed_headers(),
1783            "consensus_fast_commit_sync requires consensus_commit_transactions_only_for_traversed_headers to be enabled"
1784        );
1785        res
1786    }
1787
1788    pub fn consensus_block_restrictions(&self) -> bool {
1789        self.feature_flags.consensus_block_restrictions
1790    }
1791
1792    pub fn move_native_tx_context(&self) -> bool {
1793        self.feature_flags.move_native_tx_context
1794    }
1795
1796    pub fn pre_consensus_sponsor_only_move_authentication(&self) -> bool {
1797        let pre_consensus_sponsor_only_move_authentication = self
1798            .feature_flags
1799            .pre_consensus_sponsor_only_move_authentication;
1800        if pre_consensus_sponsor_only_move_authentication {
1801            assert!(
1802                self.enable_move_authentication(),
1803                "pre_consensus_sponsor_only_move_authentication requires enable_move_authentication to be set"
1804            );
1805            assert!(
1806                self.enable_move_authentication_for_sponsor(),
1807                "pre_consensus_sponsor_only_move_authentication requires enable_move_authentication_for_sponsor to be set"
1808            );
1809        }
1810        pre_consensus_sponsor_only_move_authentication
1811    }
1812
1813    pub fn consensus_starfish_speed(&self) -> bool {
1814        let res = self.feature_flags.consensus_starfish_speed;
1815        assert!(
1816            !res || self.consensus_fast_commit_sync(),
1817            "consensus_starfish_speed requires consensus_fast_commit_sync to be enabled"
1818        );
1819        res
1820    }
1821
1822    pub fn always_advance_dkg_to_resolution(&self) -> bool {
1823        self.feature_flags.always_advance_dkg_to_resolution
1824    }
1825
1826    pub fn enable_pcool_flow(&self) -> bool {
1827        self.feature_flags.enable_pcool_flow
1828    }
1829
1830    pub fn validator_metadata_verify_v2(&self) -> bool {
1831        self.feature_flags.validator_metadata_verify_v2
1832    }
1833
1834    pub fn commits_per_schedule(&self) -> u32 {
1835        if cfg!(msim) {
1836            // Exercise faster leader-schedule rotation in simtests.
1837            min(10, self.consensus_commits_per_schedule.unwrap_or(300))
1838        } else {
1839            self.consensus_commits_per_schedule.unwrap_or(300)
1840        }
1841    }
1842
1843    pub fn deny_rule_governance(&self) -> bool {
1844        self.feature_flags.deny_rule_governance
1845    }
1846
1847    pub fn package_metadata_with_dynamic_module_metadata(&self) -> bool {
1848        let res = self
1849            .feature_flags
1850            .package_metadata_with_dynamic_module_metadata;
1851        assert!(
1852            !res || self.publish_package_metadata(),
1853            "package_metadata_with_dynamic_module_metadata requires publish_package_metadata to be enabled"
1854        );
1855        res
1856    }
1857}
1858
1859#[cfg(not(msim))]
1860static POISON_VERSION_METHODS: AtomicBool = const { AtomicBool::new(false) };
1861
1862// Use a thread local in sim tests for test isolation.
1863#[cfg(msim)]
1864thread_local! {
1865    static POISON_VERSION_METHODS: AtomicBool = const { AtomicBool::new(false) };
1866}
1867
1868// Instantiations for each protocol version.
1869impl ProtocolConfig {
1870    /// Get the value ProtocolConfig that are in effect during the given
1871    /// protocol version.
1872    pub fn get_for_version(version: ProtocolVersion, chain: Chain) -> Self {
1873        // ProtocolVersion can be deserialized so we need to check it here as well.
1874        assert!(
1875            version >= ProtocolVersion::MIN,
1876            "Network protocol version is {:?}, but the minimum supported version by the binary is {:?}. Please upgrade the binary.",
1877            version,
1878            ProtocolVersion::MIN.0,
1879        );
1880        assert!(
1881            version <= ProtocolVersion::MAX_ALLOWED,
1882            "Network protocol version is {:?}, but the maximum supported version by the binary is {:?}. Please upgrade the binary.",
1883            version,
1884            ProtocolVersion::MAX_ALLOWED.0,
1885        );
1886
1887        let mut ret = Self::get_for_version_impl(version, chain);
1888        ret.version = version;
1889
1890        ret = CONFIG_OVERRIDE.with(|ovr| {
1891            if let Some(override_fn) = &*ovr.borrow() {
1892                warn!(
1893                    "overriding ProtocolConfig settings with custom settings (you should not see this log outside of tests)"
1894                );
1895                override_fn(version, ret)
1896            } else {
1897                ret
1898            }
1899        });
1900
1901        if std::env::var("IOTA_PROTOCOL_CONFIG_OVERRIDE_ENABLE").is_ok() {
1902            warn!(
1903                "overriding ProtocolConfig settings with custom settings; this may break non-local networks"
1904            );
1905
1906            // First, deserialize the top-level ProtocolConfig fields
1907            let overrides: ProtocolConfigOptional =
1908                serde_env::from_env_with_prefix("IOTA_PROTOCOL_CONFIG_OVERRIDE")
1909                    .expect("failed to parse ProtocolConfig override env variables");
1910            overrides.apply_to(&mut ret);
1911
1912            // Then, separately deserialize FeatureFlags fields
1913            let feature_flag_overrides: FeatureFlagsOptional =
1914                serde_env::from_env_with_prefix("IOTA_PROTOCOL_CONFIG_FEATURE_FLAGS_OVERRIDE")
1915                    .expect("failed to parse ProtocolConfig feature flags override env variables");
1916
1917            feature_flag_overrides.apply_to(&mut ret.feature_flags);
1918        }
1919
1920        ret
1921    }
1922
1923    /// Get the value ProtocolConfig that are in effect during the given
1924    /// protocol version. Or none if the version is not supported.
1925    pub fn get_for_version_if_supported(version: ProtocolVersion, chain: Chain) -> Option<Self> {
1926        if version.0 >= ProtocolVersion::MIN.0 && version.0 <= ProtocolVersion::MAX_ALLOWED.0 {
1927            let mut ret = Self::get_for_version_impl(version, chain);
1928            ret.version = version;
1929            Some(ret)
1930        } else {
1931            None
1932        }
1933    }
1934
1935    #[cfg(not(msim))]
1936    pub fn poison_get_for_min_version() {
1937        POISON_VERSION_METHODS.store(true, Ordering::Relaxed);
1938    }
1939
1940    #[cfg(not(msim))]
1941    fn load_poison_get_for_min_version() -> bool {
1942        POISON_VERSION_METHODS.load(Ordering::Relaxed)
1943    }
1944
1945    #[cfg(msim)]
1946    pub fn poison_get_for_min_version() {
1947        POISON_VERSION_METHODS.with(|p| p.store(true, Ordering::Relaxed));
1948    }
1949
1950    #[cfg(msim)]
1951    fn load_poison_get_for_min_version() -> bool {
1952        POISON_VERSION_METHODS.with(|p| p.load(Ordering::Relaxed))
1953    }
1954
1955    pub fn convert_type_argument_error(&self) -> bool {
1956        self.feature_flags.convert_type_argument_error
1957    }
1958
1959    /// Convenience to get the constants at the current minimum supported
1960    /// version. Mainly used by client code that may not yet be
1961    /// protocol-version aware.
1962    pub fn get_for_min_version() -> Self {
1963        if Self::load_poison_get_for_min_version() {
1964            panic!("get_for_min_version called on validator");
1965        }
1966        ProtocolConfig::get_for_version(ProtocolVersion::MIN, Chain::Unknown)
1967    }
1968
1969    /// CAREFUL! - You probably want to use `get_for_version` instead.
1970    ///
1971    /// Convenience to get the constants at the current maximum supported
1972    /// version. Mainly used by genesis. Note well that this function uses
1973    /// the max version supported locally by the node, which is not
1974    /// necessarily the current version of the network. ALSO, this function
1975    /// disregards chain specific config (by using Chain::Unknown), thereby
1976    /// potentially returning a protocol config that is incorrect for some
1977    /// feature flags. Definitely safe for testing and for protocol version
1978    /// 11 and prior.
1979    #[expect(non_snake_case)]
1980    pub fn get_for_max_version_UNSAFE() -> Self {
1981        if Self::load_poison_get_for_min_version() {
1982            panic!("get_for_max_version_UNSAFE called on validator");
1983        }
1984        ProtocolConfig::get_for_version(ProtocolVersion::MAX, Chain::Unknown)
1985    }
1986
1987    fn get_for_version_impl(version: ProtocolVersion, chain: Chain) -> Self {
1988        #[cfg(msim)]
1989        {
1990            // populate the fake simulator version # with a different base tx cost.
1991            if version > ProtocolVersion::MAX {
1992                let mut config = Self::get_for_version_impl(ProtocolVersion::MAX, Chain::Unknown);
1993                config.base_tx_cost_fixed = Some(config.base_tx_cost_fixed() + 1000);
1994                return config;
1995            }
1996        }
1997
1998        // IMPORTANT: Never modify the value of any constant for a pre-existing protocol
1999        // version. To change the values here you must create a new protocol
2000        // version with the new values!
2001        let mut cfg = Self {
2002            version,
2003
2004            feature_flags: Default::default(),
2005
2006            max_tx_size_bytes: Some(128 * 1024),
2007            // We need this number to be at least 100x less than
2008            // `max_serialized_tx_effects_size_bytes`otherwise effects can be huge
2009            max_input_objects: Some(2048),
2010            max_serialized_tx_effects_size_bytes: Some(512 * 1024),
2011            max_serialized_tx_effects_size_bytes_system_tx: Some(512 * 1024 * 16),
2012            max_gas_payment_objects: Some(256),
2013            max_modules_in_publish: Some(64),
2014            max_package_dependencies: Some(32),
2015            max_arguments: Some(512),
2016            max_type_arguments: Some(16),
2017            max_type_argument_depth: Some(16),
2018            max_pure_argument_size: Some(16 * 1024),
2019            max_programmable_tx_commands: Some(1024),
2020            move_binary_format_version: Some(7),
2021            min_move_binary_format_version: Some(6),
2022            binary_module_handles: Some(100),
2023            binary_struct_handles: Some(300),
2024            binary_function_handles: Some(1500),
2025            binary_function_instantiations: Some(750),
2026            binary_signatures: Some(1000),
2027            binary_constant_pool: Some(4000),
2028            binary_identifiers: Some(10000),
2029            binary_address_identifiers: Some(100),
2030            binary_struct_defs: Some(200),
2031            binary_struct_def_instantiations: Some(100),
2032            binary_function_defs: Some(1000),
2033            binary_field_handles: Some(500),
2034            binary_field_instantiations: Some(250),
2035            binary_friend_decls: Some(100),
2036            binary_enum_defs: None,
2037            binary_enum_def_instantiations: None,
2038            binary_variant_handles: None,
2039            binary_variant_instantiation_handles: None,
2040            max_move_object_size: Some(250 * 1024),
2041            max_move_package_size: Some(100 * 1024),
2042            max_publish_or_upgrade_per_ptb: Some(5),
2043            // max gas budget for an authentication is in NANOS
2044            max_auth_gas: None,
2045            // max gas budget is in NANOS and an absolute value 50IOTA
2046            max_tx_gas: Some(50_000_000_000),
2047            max_gas_price: Some(100_000),
2048            max_gas_computation_bucket: Some(5_000_000),
2049            max_loop_depth: Some(5),
2050            max_generic_instantiation_length: Some(32),
2051            max_function_parameters: Some(128),
2052            max_basic_blocks: Some(1024),
2053            max_value_stack_size: Some(1024),
2054            max_type_nodes: Some(256),
2055            max_push_size: Some(10000),
2056            max_struct_definitions: Some(200),
2057            max_function_definitions: Some(1000),
2058            max_fields_in_struct: Some(32),
2059            max_dependency_depth: Some(100),
2060            max_num_event_emit: Some(1024),
2061            max_num_new_move_object_ids: Some(2048),
2062            max_num_new_move_object_ids_system_tx: Some(2048 * 16),
2063            max_num_deleted_move_object_ids: Some(2048),
2064            max_num_deleted_move_object_ids_system_tx: Some(2048 * 16),
2065            max_num_transferred_move_object_ids: Some(2048),
2066            max_num_transferred_move_object_ids_system_tx: Some(2048 * 16),
2067            max_event_emit_size: Some(250 * 1024),
2068            max_move_vector_len: Some(256 * 1024),
2069            max_type_to_layout_nodes: None,
2070            max_ptb_value_size: None,
2071
2072            max_back_edges_per_function: Some(10_000),
2073            max_back_edges_per_module: Some(10_000),
2074
2075            max_verifier_meter_ticks_per_function: Some(16_000_000),
2076
2077            max_meter_ticks_per_module: Some(16_000_000),
2078            max_meter_ticks_per_package: Some(16_000_000),
2079
2080            object_runtime_max_num_cached_objects: Some(1000),
2081            object_runtime_max_num_cached_objects_system_tx: Some(1000 * 16),
2082            object_runtime_max_num_store_entries: Some(1000),
2083            object_runtime_max_num_store_entries_system_tx: Some(1000 * 16),
2084            // min gas budget is in NANOS and an absolute value 1000 NANOS or 0.000001IOTA
2085            base_tx_cost_fixed: Some(1_000),
2086            package_publish_cost_fixed: Some(1_000),
2087            base_tx_cost_per_byte: Some(0),
2088            package_publish_cost_per_byte: Some(80),
2089            obj_access_cost_read_per_byte: Some(15),
2090            obj_access_cost_mutate_per_byte: Some(40),
2091            obj_access_cost_delete_per_byte: Some(40),
2092            obj_access_cost_verify_per_byte: Some(200),
2093            obj_data_cost_refundable: Some(100),
2094            obj_metadata_cost_non_refundable: Some(50),
2095            gas_model_version: Some(1),
2096            storage_rebate_rate: Some(10000),
2097            // Change reward slashing rate to 100%.
2098            reward_slashing_rate: Some(10000),
2099            storage_gas_price: Some(76),
2100            base_gas_price: None,
2101            // The initial subsidy (target reward) for validators per epoch.
2102            // Refer to the IOTA tokenomics for the origin of this value.
2103            validator_target_reward: Some(767_000 * 1_000_000_000),
2104            max_transactions_per_checkpoint: Some(10_000),
2105            max_checkpoint_size_bytes: Some(30 * 1024 * 1024),
2106
2107            // For now, perform upgrades with a bare quorum of validators.
2108            buffer_stake_for_protocol_upgrade_bps: Some(5000),
2109
2110            // === Native Function Costs ===
2111            // `address` module
2112            // Cost params for the Move native function `address::from_bytes(bytes: vector<u8>)`
2113            address_from_bytes_cost_base: Some(52),
2114            // Cost params for the Move native function `address::to_u256(address): u256`
2115            address_to_u256_cost_base: Some(52),
2116            // Cost params for the Move native function `address::from_u256(u256): address`
2117            address_from_u256_cost_base: Some(52),
2118
2119            // `config` module
2120            // Cost params for the Move native function `read_setting_impl``
2121            config_read_setting_impl_cost_base: Some(100),
2122            config_read_setting_impl_cost_per_byte: Some(40),
2123
2124            // `dynamic_field` module
2125            // Cost params for the Move native function `hash_type_and_key<K: copy + drop +
2126            // store>(parent: address, k: K): address`
2127            dynamic_field_hash_type_and_key_cost_base: Some(100),
2128            dynamic_field_hash_type_and_key_type_cost_per_byte: Some(2),
2129            dynamic_field_hash_type_and_key_value_cost_per_byte: Some(2),
2130            dynamic_field_hash_type_and_key_type_tag_cost_per_byte: Some(2),
2131            // Cost params for the Move native function `add_child_object<Child: key>(parent:
2132            // address, child: Child)`
2133            dynamic_field_add_child_object_cost_base: Some(100),
2134            dynamic_field_add_child_object_type_cost_per_byte: Some(10),
2135            dynamic_field_add_child_object_value_cost_per_byte: Some(10),
2136            dynamic_field_add_child_object_struct_tag_cost_per_byte: Some(10),
2137            // Cost params for the Move native function `borrow_child_object_mut<Child: key>(parent:
2138            // &mut UID, id: address): &mut Child`
2139            dynamic_field_borrow_child_object_cost_base: Some(100),
2140            dynamic_field_borrow_child_object_child_ref_cost_per_byte: Some(10),
2141            dynamic_field_borrow_child_object_type_cost_per_byte: Some(10),
2142            // Cost params for the Move native function `remove_child_object<Child: key>(parent:
2143            // address, id: address): Child`
2144            dynamic_field_remove_child_object_cost_base: Some(100),
2145            dynamic_field_remove_child_object_child_cost_per_byte: Some(2),
2146            dynamic_field_remove_child_object_type_cost_per_byte: Some(2),
2147            // Cost params for the Move native function `has_child_object(parent: address, id:
2148            // address): bool`
2149            dynamic_field_has_child_object_cost_base: Some(100),
2150            // Cost params for the Move native function `has_child_object_with_ty<Child:
2151            // key>(parent: address, id: address): bool`
2152            dynamic_field_has_child_object_with_ty_cost_base: Some(100),
2153            dynamic_field_has_child_object_with_ty_type_cost_per_byte: Some(2),
2154            dynamic_field_has_child_object_with_ty_type_tag_cost_per_byte: Some(2),
2155
2156            // `event` module
2157            // Cost params for the Move native function `event::emit<T: copy + drop>(event: T)`
2158            event_emit_cost_base: Some(52),
2159            event_emit_value_size_derivation_cost_per_byte: Some(2),
2160            event_emit_tag_size_derivation_cost_per_byte: Some(5),
2161            event_emit_output_cost_per_byte: Some(10),
2162
2163            //  `object` module
2164            // Cost params for the Move native function `borrow_uid<T: key>(obj: &T): &UID`
2165            object_borrow_uid_cost_base: Some(52),
2166            // Cost params for the Move native function `delete_impl(id: address)`
2167            object_delete_impl_cost_base: Some(52),
2168            // Cost params for the Move native function `record_new_uid(id: address)`
2169            object_record_new_uid_cost_base: Some(52),
2170
2171            // `transfer` module
2172            // Cost params for the Move native function `transfer_impl<T: key>(obj: T, recipient:
2173            // address)`
2174            transfer_transfer_internal_cost_base: Some(52),
2175            // Cost params for the Move native function `freeze_object<T: key>(obj: T)`
2176            transfer_freeze_object_cost_base: Some(52),
2177            // Cost params for the Move native function `share_object<T: key>(obj: T)`
2178            transfer_share_object_cost_base: Some(52),
2179            transfer_receive_object_cost_base: Some(52),
2180
2181            // `tx_context` module
2182            // Cost params for the Move native function `transfer_impl<T: key>(obj: T, recipient:
2183            // address)`
2184            tx_context_derive_id_cost_base: Some(52),
2185            tx_context_fresh_id_cost_base: None,
2186            tx_context_sender_cost_base: None,
2187            tx_context_digest_cost_base: None,
2188            tx_context_epoch_cost_base: None,
2189            tx_context_epoch_timestamp_ms_cost_base: None,
2190            tx_context_sponsor_cost_base: None,
2191            tx_context_rgp_cost_base: None,
2192            tx_context_gas_price_cost_base: None,
2193            tx_context_gas_budget_cost_base: None,
2194            tx_context_ids_created_cost_base: None,
2195            tx_context_replace_cost_base: None,
2196
2197            // `types` module
2198            // Cost params for the Move native function `is_one_time_witness<T: drop>(_: &T): bool`
2199            types_is_one_time_witness_cost_base: Some(52),
2200            types_is_one_time_witness_type_tag_cost_per_byte: Some(2),
2201            types_is_one_time_witness_type_cost_per_byte: Some(2),
2202
2203            // `validator` module
2204            // Cost params for the Move native function `validate_metadata_bcs(metadata:
2205            // vector<u8>)`
2206            validator_validate_metadata_cost_base: Some(52),
2207            validator_validate_metadata_data_cost_per_byte: Some(2),
2208
2209            // Crypto
2210            crypto_invalid_arguments_cost: Some(100),
2211            // bls12381::bls12381_min_pk_verify
2212            bls12381_bls12381_min_sig_verify_cost_base: Some(52),
2213            bls12381_bls12381_min_sig_verify_msg_cost_per_byte: Some(2),
2214            bls12381_bls12381_min_sig_verify_msg_cost_per_block: Some(2),
2215
2216            // bls12381::bls12381_min_pk_verify
2217            bls12381_bls12381_min_pk_verify_cost_base: Some(52),
2218            bls12381_bls12381_min_pk_verify_msg_cost_per_byte: Some(2),
2219            bls12381_bls12381_min_pk_verify_msg_cost_per_block: Some(2),
2220
2221            // ecdsa_k1::ecrecover
2222            ecdsa_k1_ecrecover_keccak256_cost_base: Some(52),
2223            ecdsa_k1_ecrecover_keccak256_msg_cost_per_byte: Some(2),
2224            ecdsa_k1_ecrecover_keccak256_msg_cost_per_block: Some(2),
2225            ecdsa_k1_ecrecover_sha256_cost_base: Some(52),
2226            ecdsa_k1_ecrecover_sha256_msg_cost_per_byte: Some(2),
2227            ecdsa_k1_ecrecover_sha256_msg_cost_per_block: Some(2),
2228
2229            // ecdsa_k1::decompress_pubkey
2230            ecdsa_k1_decompress_pubkey_cost_base: Some(52),
2231
2232            // ecdsa_k1::secp256k1_verify
2233            ecdsa_k1_secp256k1_verify_keccak256_cost_base: Some(52),
2234            ecdsa_k1_secp256k1_verify_keccak256_msg_cost_per_byte: Some(2),
2235            ecdsa_k1_secp256k1_verify_keccak256_msg_cost_per_block: Some(2),
2236            ecdsa_k1_secp256k1_verify_sha256_cost_base: Some(52),
2237            ecdsa_k1_secp256k1_verify_sha256_msg_cost_per_byte: Some(2),
2238            ecdsa_k1_secp256k1_verify_sha256_msg_cost_per_block: Some(2),
2239
2240            // ecdsa_r1::ecrecover
2241            ecdsa_r1_ecrecover_keccak256_cost_base: Some(52),
2242            ecdsa_r1_ecrecover_keccak256_msg_cost_per_byte: Some(2),
2243            ecdsa_r1_ecrecover_keccak256_msg_cost_per_block: Some(2),
2244            ecdsa_r1_ecrecover_sha256_cost_base: Some(52),
2245            ecdsa_r1_ecrecover_sha256_msg_cost_per_byte: Some(2),
2246            ecdsa_r1_ecrecover_sha256_msg_cost_per_block: Some(2),
2247
2248            // ecdsa_r1::secp256k1_verify
2249            ecdsa_r1_secp256r1_verify_keccak256_cost_base: Some(52),
2250            ecdsa_r1_secp256r1_verify_keccak256_msg_cost_per_byte: Some(2),
2251            ecdsa_r1_secp256r1_verify_keccak256_msg_cost_per_block: Some(2),
2252            ecdsa_r1_secp256r1_verify_sha256_cost_base: Some(52),
2253            ecdsa_r1_secp256r1_verify_sha256_msg_cost_per_byte: Some(2),
2254            ecdsa_r1_secp256r1_verify_sha256_msg_cost_per_block: Some(2),
2255
2256            // ecvrf::verify
2257            ecvrf_ecvrf_verify_cost_base: Some(52),
2258            ecvrf_ecvrf_verify_alpha_string_cost_per_byte: Some(2),
2259            ecvrf_ecvrf_verify_alpha_string_cost_per_block: Some(2),
2260
2261            // ed25519
2262            ed25519_ed25519_verify_cost_base: Some(52),
2263            ed25519_ed25519_verify_msg_cost_per_byte: Some(2),
2264            ed25519_ed25519_verify_msg_cost_per_block: Some(2),
2265
2266            // groth16::prepare_verifying_key
2267            groth16_prepare_verifying_key_bls12381_cost_base: Some(52),
2268            groth16_prepare_verifying_key_bn254_cost_base: Some(52),
2269
2270            // groth16::verify_groth16_proof_internal
2271            groth16_verify_groth16_proof_internal_bls12381_cost_base: Some(52),
2272            groth16_verify_groth16_proof_internal_bls12381_cost_per_public_input: Some(2),
2273            groth16_verify_groth16_proof_internal_bn254_cost_base: Some(52),
2274            groth16_verify_groth16_proof_internal_bn254_cost_per_public_input: Some(2),
2275            groth16_verify_groth16_proof_internal_public_input_cost_per_byte: Some(2),
2276
2277            // hash::blake2b256
2278            hash_blake2b256_cost_base: Some(52),
2279            hash_blake2b256_data_cost_per_byte: Some(2),
2280            hash_blake2b256_data_cost_per_block: Some(2),
2281            // hash::keccak256
2282            hash_keccak256_cost_base: Some(52),
2283            hash_keccak256_data_cost_per_byte: Some(2),
2284            hash_keccak256_data_cost_per_block: Some(2),
2285
2286            poseidon_bn254_cost_base: None,
2287            poseidon_bn254_cost_per_block: None,
2288
2289            // hmac::hmac_sha3_256
2290            hmac_hmac_sha3_256_cost_base: Some(52),
2291            hmac_hmac_sha3_256_input_cost_per_byte: Some(2),
2292            hmac_hmac_sha3_256_input_cost_per_block: Some(2),
2293
2294            // group ops
2295            group_ops_bls12381_decode_scalar_cost: Some(52),
2296            group_ops_bls12381_decode_g1_cost: Some(52),
2297            group_ops_bls12381_decode_g2_cost: Some(52),
2298            group_ops_bls12381_decode_gt_cost: Some(52),
2299            group_ops_bls12381_scalar_add_cost: Some(52),
2300            group_ops_bls12381_g1_add_cost: Some(52),
2301            group_ops_bls12381_g2_add_cost: Some(52),
2302            group_ops_bls12381_gt_add_cost: Some(52),
2303            group_ops_bls12381_scalar_sub_cost: Some(52),
2304            group_ops_bls12381_g1_sub_cost: Some(52),
2305            group_ops_bls12381_g2_sub_cost: Some(52),
2306            group_ops_bls12381_gt_sub_cost: Some(52),
2307            group_ops_bls12381_scalar_mul_cost: Some(52),
2308            group_ops_bls12381_g1_mul_cost: Some(52),
2309            group_ops_bls12381_g2_mul_cost: Some(52),
2310            group_ops_bls12381_gt_mul_cost: Some(52),
2311            group_ops_bls12381_scalar_div_cost: Some(52),
2312            group_ops_bls12381_g1_div_cost: Some(52),
2313            group_ops_bls12381_g2_div_cost: Some(52),
2314            group_ops_bls12381_gt_div_cost: Some(52),
2315            group_ops_bls12381_g1_hash_to_base_cost: Some(52),
2316            group_ops_bls12381_g2_hash_to_base_cost: Some(52),
2317            group_ops_bls12381_g1_hash_to_cost_per_byte: Some(2),
2318            group_ops_bls12381_g2_hash_to_cost_per_byte: Some(2),
2319            group_ops_bls12381_g1_msm_base_cost: Some(52),
2320            group_ops_bls12381_g2_msm_base_cost: Some(52),
2321            group_ops_bls12381_g1_msm_base_cost_per_input: Some(52),
2322            group_ops_bls12381_g2_msm_base_cost_per_input: Some(52),
2323            group_ops_bls12381_msm_max_len: Some(32),
2324            group_ops_bls12381_pairing_cost: Some(52),
2325            group_ops_bls12381_g1_to_uncompressed_g1_cost: None,
2326            group_ops_bls12381_uncompressed_g1_to_g1_cost: None,
2327            group_ops_bls12381_uncompressed_g1_sum_base_cost: None,
2328            group_ops_bls12381_uncompressed_g1_sum_cost_per_term: None,
2329            group_ops_bls12381_uncompressed_g1_sum_max_terms: None,
2330
2331            // zklogin::check_zklogin_id
2332            #[allow(deprecated)]
2333            check_zklogin_id_cost_base: Some(200),
2334            #[allow(deprecated)]
2335            // zklogin::check_zklogin_issuer
2336            check_zklogin_issuer_cost_base: Some(200),
2337
2338            vdf_verify_vdf_cost: None,
2339            vdf_hash_to_input_cost: None,
2340
2341            bcs_per_byte_serialized_cost: Some(2),
2342            bcs_legacy_min_output_size_cost: Some(1),
2343            bcs_failure_cost: Some(52),
2344            hash_sha2_256_base_cost: Some(52),
2345            hash_sha2_256_per_byte_cost: Some(2),
2346            hash_sha2_256_legacy_min_input_len_cost: Some(1),
2347            hash_sha3_256_base_cost: Some(52),
2348            hash_sha3_256_per_byte_cost: Some(2),
2349            hash_sha3_256_legacy_min_input_len_cost: Some(1),
2350            type_name_get_base_cost: Some(52),
2351            type_name_get_per_byte_cost: Some(2),
2352            string_check_utf8_base_cost: Some(52),
2353            string_check_utf8_per_byte_cost: Some(2),
2354            string_is_char_boundary_base_cost: Some(52),
2355            string_sub_string_base_cost: Some(52),
2356            string_sub_string_per_byte_cost: Some(2),
2357            string_index_of_base_cost: Some(52),
2358            string_index_of_per_byte_pattern_cost: Some(2),
2359            string_index_of_per_byte_searched_cost: Some(2),
2360            vector_empty_base_cost: Some(52),
2361            vector_length_base_cost: Some(52),
2362            vector_push_back_base_cost: Some(52),
2363            vector_push_back_legacy_per_abstract_memory_unit_cost: Some(2),
2364            vector_borrow_base_cost: Some(52),
2365            vector_pop_back_base_cost: Some(52),
2366            vector_destroy_empty_base_cost: Some(52),
2367            vector_swap_base_cost: Some(52),
2368            debug_print_base_cost: Some(52),
2369            debug_print_stack_trace_base_cost: Some(52),
2370
2371            max_size_written_objects: Some(5 * 1000 * 1000),
2372            // max size of written objects during a system TXn to allow for larger writes
2373            // akin to `max_size_written_objects` but for system TXns
2374            max_size_written_objects_system_tx: Some(50 * 1000 * 1000),
2375
2376            // Limits the length of a Move identifier
2377            max_move_identifier_len: Some(128),
2378            max_move_value_depth: Some(128),
2379            max_move_enum_variants: None,
2380
2381            gas_rounding_step: Some(1_000),
2382
2383            execution_version: Some(1),
2384
2385            // We maintain the same total size limit for events, but increase the number of
2386            // events that can be emitted.
2387            max_event_emit_size_total: Some(
2388                256 /* former event count limit */ * 250 * 1024, // size limit per event
2389            ),
2390
2391            // Taking a baby step approach, we consider only 20% by stake as bad nodes so we
2392            // have a 80% by stake of nodes participating in the leader committee. That
2393            // allow us for more redundancy in case we have validators
2394            // under performing - since the responsibility is shared
2395            // amongst more nodes. We can increase that once we do have
2396            // higher confidence.
2397            consensus_bad_nodes_stake_threshold: Some(20),
2398
2399            // Max of 10 votes per hour.
2400            #[allow(deprecated)]
2401            max_jwk_votes_per_validator_per_epoch: Some(240),
2402
2403            #[allow(deprecated)]
2404            max_age_of_jwk_in_epochs: Some(1),
2405
2406            consensus_max_transaction_size_bytes: Some(256 * 1024), // 256KB
2407
2408            // Assume 1KB per transaction and 500 transactions per block.
2409            consensus_max_transactions_in_block_bytes: Some(512 * 1024),
2410
2411            random_beacon_reduction_allowed_delta: Some(800),
2412
2413            random_beacon_reduction_lower_bound: Some(1000),
2414            random_beacon_dkg_timeout_round: Some(3000),
2415            random_beacon_min_round_interval_ms: Some(500),
2416
2417            random_beacon_dkg_version: Some(1),
2418
2419            // Assume 20_000 TPS * 5% max stake per validator / (minimum) 4 blocks per round
2420            // = 250 transactions per block maximum Using a higher limit
2421            // that is 512, to account for bursty traffic and system transactions.
2422            consensus_max_num_transactions_in_block: Some(512),
2423
2424            max_deferral_rounds_for_congestion_control: Some(10),
2425
2426            min_checkpoint_interval_ms: Some(200),
2427
2428            checkpoint_rate_window_size: None,
2429
2430            checkpoint_summary_version_specific_data: Some(1),
2431
2432            max_soft_bundle_size: Some(5),
2433
2434            bridge_should_try_to_finalize_committee: None,
2435
2436            max_accumulated_txn_cost_per_object_in_mysticeti_commit: Some(10),
2437
2438            max_committee_members_count: None,
2439
2440            consensus_gc_depth: None,
2441
2442            consensus_max_acknowledgments_per_block: None,
2443
2444            max_congestion_limit_overshoot_per_commit: None,
2445
2446            scorer_version: None,
2447
2448            // `auth_context` module
2449            auth_context_digest_cost_base: None,
2450            auth_context_tx_data_bytes_cost_base: None,
2451            auth_context_tx_data_bytes_cost_per_byte: None,
2452            auth_context_tx_commands_cost_base: None,
2453            auth_context_tx_commands_cost_per_byte: None,
2454            auth_context_tx_inputs_cost_base: None,
2455            auth_context_tx_inputs_cost_per_byte: None,
2456            auth_context_replace_cost_base: None,
2457            auth_context_replace_cost_per_byte: None,
2458            auth_context_authenticator_function_info_v1_cost_base: None,
2459            consensus_commits_per_schedule: None,
2460            // When adding a new constant, set it to None in the earliest version, like this:
2461            // new_constant: None,
2462        };
2463
2464        cfg.feature_flags.consensus_transaction_ordering = ConsensusTransactionOrdering::ByGasPrice;
2465
2466        // MoveVM related flags
2467        {
2468            cfg.feature_flags
2469                .disable_invariant_violation_check_in_swap_loc = true;
2470            cfg.feature_flags.no_extraneous_module_bytes = true;
2471            cfg.feature_flags.hardened_otw_check = true;
2472            cfg.feature_flags.rethrow_serialization_type_layout_errors = true;
2473        }
2474
2475        // zkLogin related flags
2476        {
2477            #[allow(deprecated)]
2478            {
2479                cfg.feature_flags.zklogin_max_epoch_upper_bound_delta = Some(30);
2480            }
2481        }
2482
2483        // Historical default: Mysticeti. Kept explicitly to match the
2484        // serialized form of pre-v14/v19/v24 configs. No runtime behavior
2485        // depends on this — Starfish is the only consensus protocol.
2486        #[expect(deprecated)]
2487        {
2488            cfg.feature_flags.consensus_choice = ConsensusChoice::MysticetiDeprecated;
2489        }
2490        // Use tonic networking for consensus.
2491        cfg.feature_flags.consensus_network = ConsensusNetwork::Tonic;
2492
2493        cfg.feature_flags.per_object_congestion_control_mode =
2494            PerObjectCongestionControlMode::TotalTxCount;
2495
2496        // Do not allow bridge committee to finalize on mainnet.
2497        cfg.bridge_should_try_to_finalize_committee = Some(chain != Chain::Mainnet);
2498
2499        // Devnet
2500        if chain != Chain::Mainnet && chain != Chain::Testnet {
2501            cfg.feature_flags.enable_poseidon = true;
2502            cfg.poseidon_bn254_cost_base = Some(260);
2503            cfg.poseidon_bn254_cost_per_block = Some(10);
2504
2505            cfg.feature_flags.enable_group_ops_native_function_msm = true;
2506
2507            cfg.feature_flags.enable_vdf = true;
2508            // Set to 30x and 2x the cost of a signature verification for now. This
2509            // should be updated along with other native crypto functions.
2510            cfg.vdf_verify_vdf_cost = Some(1500);
2511            cfg.vdf_hash_to_input_cost = Some(100);
2512
2513            cfg.feature_flags.passkey_auth = true;
2514        }
2515
2516        for cur in 2..=version.0 {
2517            match cur {
2518                1 => unreachable!(),
2519                // version 2 is a new framework version but with no config changes
2520                2 => {}
2521                3 => {
2522                    cfg.feature_flags.relocate_event_module = true;
2523                }
2524                4 => {
2525                    cfg.max_type_to_layout_nodes = Some(512);
2526                }
2527                5 => {
2528                    cfg.feature_flags.protocol_defined_base_fee = true;
2529                    cfg.base_gas_price = Some(1000);
2530
2531                    cfg.feature_flags.disallow_new_modules_in_deps_only_packages = true;
2532                    cfg.feature_flags.convert_type_argument_error = true;
2533                    cfg.feature_flags.native_charging_v2 = true;
2534
2535                    if chain != Chain::Mainnet && chain != Chain::Testnet {
2536                        cfg.feature_flags.uncompressed_g1_group_elements = true;
2537                    }
2538
2539                    cfg.gas_model_version = Some(2);
2540
2541                    cfg.poseidon_bn254_cost_per_block = Some(388);
2542
2543                    cfg.bls12381_bls12381_min_sig_verify_cost_base = Some(44064);
2544                    cfg.bls12381_bls12381_min_pk_verify_cost_base = Some(49282);
2545                    cfg.ecdsa_k1_secp256k1_verify_keccak256_cost_base = Some(1470);
2546                    cfg.ecdsa_k1_secp256k1_verify_sha256_cost_base = Some(1470);
2547                    cfg.ecdsa_r1_secp256r1_verify_sha256_cost_base = Some(4225);
2548                    cfg.ecdsa_r1_secp256r1_verify_keccak256_cost_base = Some(4225);
2549                    cfg.ecvrf_ecvrf_verify_cost_base = Some(4848);
2550                    cfg.ed25519_ed25519_verify_cost_base = Some(1802);
2551
2552                    // Manually changed to be "under cost"
2553                    cfg.ecdsa_r1_ecrecover_keccak256_cost_base = Some(1173);
2554                    cfg.ecdsa_r1_ecrecover_sha256_cost_base = Some(1173);
2555                    cfg.ecdsa_k1_ecrecover_keccak256_cost_base = Some(500);
2556                    cfg.ecdsa_k1_ecrecover_sha256_cost_base = Some(500);
2557
2558                    cfg.groth16_prepare_verifying_key_bls12381_cost_base = Some(53838);
2559                    cfg.groth16_prepare_verifying_key_bn254_cost_base = Some(82010);
2560                    cfg.groth16_verify_groth16_proof_internal_bls12381_cost_base = Some(72090);
2561                    cfg.groth16_verify_groth16_proof_internal_bls12381_cost_per_public_input =
2562                        Some(8213);
2563                    cfg.groth16_verify_groth16_proof_internal_bn254_cost_base = Some(115502);
2564                    cfg.groth16_verify_groth16_proof_internal_bn254_cost_per_public_input =
2565                        Some(9484);
2566
2567                    cfg.hash_keccak256_cost_base = Some(10);
2568                    cfg.hash_blake2b256_cost_base = Some(10);
2569
2570                    // group ops
2571                    cfg.group_ops_bls12381_decode_scalar_cost = Some(7);
2572                    cfg.group_ops_bls12381_decode_g1_cost = Some(2848);
2573                    cfg.group_ops_bls12381_decode_g2_cost = Some(3770);
2574                    cfg.group_ops_bls12381_decode_gt_cost = Some(3068);
2575
2576                    cfg.group_ops_bls12381_scalar_add_cost = Some(10);
2577                    cfg.group_ops_bls12381_g1_add_cost = Some(1556);
2578                    cfg.group_ops_bls12381_g2_add_cost = Some(3048);
2579                    cfg.group_ops_bls12381_gt_add_cost = Some(188);
2580
2581                    cfg.group_ops_bls12381_scalar_sub_cost = Some(10);
2582                    cfg.group_ops_bls12381_g1_sub_cost = Some(1550);
2583                    cfg.group_ops_bls12381_g2_sub_cost = Some(3019);
2584                    cfg.group_ops_bls12381_gt_sub_cost = Some(497);
2585
2586                    cfg.group_ops_bls12381_scalar_mul_cost = Some(11);
2587                    cfg.group_ops_bls12381_g1_mul_cost = Some(4842);
2588                    cfg.group_ops_bls12381_g2_mul_cost = Some(9108);
2589                    cfg.group_ops_bls12381_gt_mul_cost = Some(27490);
2590
2591                    cfg.group_ops_bls12381_scalar_div_cost = Some(91);
2592                    cfg.group_ops_bls12381_g1_div_cost = Some(5091);
2593                    cfg.group_ops_bls12381_g2_div_cost = Some(9206);
2594                    cfg.group_ops_bls12381_gt_div_cost = Some(27804);
2595
2596                    cfg.group_ops_bls12381_g1_hash_to_base_cost = Some(2962);
2597                    cfg.group_ops_bls12381_g2_hash_to_base_cost = Some(8688);
2598
2599                    cfg.group_ops_bls12381_g1_msm_base_cost = Some(62648);
2600                    cfg.group_ops_bls12381_g2_msm_base_cost = Some(131192);
2601                    cfg.group_ops_bls12381_g1_msm_base_cost_per_input = Some(1333);
2602                    cfg.group_ops_bls12381_g2_msm_base_cost_per_input = Some(3216);
2603
2604                    cfg.group_ops_bls12381_uncompressed_g1_to_g1_cost = Some(677);
2605                    cfg.group_ops_bls12381_g1_to_uncompressed_g1_cost = Some(2099);
2606                    cfg.group_ops_bls12381_uncompressed_g1_sum_base_cost = Some(77);
2607                    cfg.group_ops_bls12381_uncompressed_g1_sum_cost_per_term = Some(26);
2608                    cfg.group_ops_bls12381_uncompressed_g1_sum_max_terms = Some(1200);
2609
2610                    cfg.group_ops_bls12381_pairing_cost = Some(26897);
2611
2612                    cfg.validator_validate_metadata_cost_base = Some(20000);
2613
2614                    cfg.max_committee_members_count = Some(50);
2615                }
2616                6 => {
2617                    cfg.max_ptb_value_size = Some(1024 * 1024);
2618                }
2619                7 => {
2620                    // version 7 is a new framework version but with no config
2621                    // changes
2622                }
2623                8 => {
2624                    cfg.feature_flags.variant_nodes = true;
2625
2626                    if chain != Chain::Mainnet {
2627                        // Enable round prober in consensus.
2628                        cfg.feature_flags.consensus_round_prober = true;
2629                        // Enable distributed vote scoring.
2630                        cfg.feature_flags
2631                            .consensus_distributed_vote_scoring_strategy = true;
2632                        cfg.feature_flags.consensus_linearize_subdag_v2 = true;
2633                        // Enable smart ancestor selection for testnet
2634                        cfg.feature_flags.consensus_smart_ancestor_selection = true;
2635                        // Enable probing for accepted rounds in round prober for testnet
2636                        cfg.feature_flags
2637                            .consensus_round_prober_probe_accepted_rounds = true;
2638                        // Enable zstd compression for consensus in testnet
2639                        cfg.feature_flags.consensus_zstd_compression = true;
2640                        // Assuming a round rate of max 15/sec, then using a gc depth of 60 allow
2641                        // blocks within a window of ~4 seconds
2642                        // to be included before be considered garbage collected.
2643                        cfg.consensus_gc_depth = Some(60);
2644                    }
2645
2646                    // Enable min_free_execution_slot for the shared object congestion tracker in
2647                    // devnet.
2648                    if chain != Chain::Testnet && chain != Chain::Mainnet {
2649                        cfg.feature_flags.congestion_control_min_free_execution_slot = true;
2650                    }
2651                }
2652                9 => {
2653                    if chain != Chain::Mainnet {
2654                        // Disable smart ancestor selection in the testnet and devnet.
2655                        cfg.feature_flags.consensus_smart_ancestor_selection = false;
2656                    }
2657
2658                    // Enable zstd compression for consensus
2659                    cfg.feature_flags.consensus_zstd_compression = true;
2660
2661                    // Enable passkey in multisig in devnet.
2662                    if chain != Chain::Testnet && chain != Chain::Mainnet {
2663                        cfg.feature_flags.accept_passkey_in_multisig = true;
2664                    }
2665
2666                    // this flag is now deprecated because of the bridge removal.
2667                    cfg.bridge_should_try_to_finalize_committee = None;
2668                }
2669                10 => {
2670                    // Enable min_free_execution_slot for the shared object congestion tracker in
2671                    // all networks.
2672                    cfg.feature_flags.congestion_control_min_free_execution_slot = true;
2673
2674                    // Increase the committee size to 80 on all networks.
2675                    cfg.max_committee_members_count = Some(80);
2676
2677                    // Enable round prober in consensus.
2678                    cfg.feature_flags.consensus_round_prober = true;
2679                    // Enable probing for accepted rounds in round.
2680                    cfg.feature_flags
2681                        .consensus_round_prober_probe_accepted_rounds = true;
2682                    // Enable distributed vote scoring.
2683                    cfg.feature_flags
2684                        .consensus_distributed_vote_scoring_strategy = true;
2685                    // Enable the new consensus commit rule.
2686                    cfg.feature_flags.consensus_linearize_subdag_v2 = true;
2687
2688                    // Enable consensus garbage collection
2689                    // Assuming a round rate of max 15/sec, then using a gc depth of 60 allow
2690                    // blocks within a window of ~4 seconds
2691                    // to be included before be considered garbage collected.
2692                    cfg.consensus_gc_depth = Some(60);
2693
2694                    // Enable minimized child object mutation counting.
2695                    cfg.feature_flags.minimize_child_object_mutations = true;
2696
2697                    if chain != Chain::Mainnet {
2698                        // Enable batched block sync in devnet and testnet.
2699                        cfg.feature_flags.consensus_batched_block_sync = true;
2700                    }
2701
2702                    if chain != Chain::Testnet && chain != Chain::Mainnet {
2703                        // Enable the gas price feedback mechanism (which is used for
2704                        // transactions cancelled due to shared object congestion) in devnet
2705                        cfg.feature_flags
2706                            .congestion_control_gas_price_feedback_mechanism = true;
2707                    }
2708
2709                    cfg.feature_flags.validate_identifier_inputs = true;
2710                    cfg.feature_flags.dependency_linkage_error = true;
2711                    cfg.feature_flags.additional_multisig_checks = true;
2712                }
2713                11 => {
2714                    // version 11 is a new framework version but with no config
2715                    // changes
2716                }
2717                12 => {
2718                    // Enable the gas price feedback mechanism for transactions
2719                    // cancelled due to congestion in all networks
2720                    cfg.feature_flags
2721                        .congestion_control_gas_price_feedback_mechanism = true;
2722
2723                    // Enable normalization of PTB arguments in all networks.
2724                    cfg.feature_flags.normalize_ptb_arguments = true;
2725                }
2726                13 => {
2727                    // Enable selecting committee based on eligible active validators on all
2728                    // networks.
2729                    cfg.feature_flags.select_committee_from_eligible_validators = true;
2730                    // Enable tracking non-committee eligible active
2731                    // validators on all networks.
2732                    cfg.feature_flags.track_non_committee_eligible_validators = true;
2733
2734                    if chain != Chain::Testnet && chain != Chain::Mainnet {
2735                        // Enable selecting committee only from active validators that next epoch
2736                        // version and issued valid AuthorityCapabilities notification in devnet.
2737                        cfg.feature_flags
2738                            .select_committee_supporting_next_epoch_version = true;
2739                    }
2740                }
2741                14 => {
2742                    // Enable batched block sync for mainnet.
2743                    cfg.feature_flags.consensus_batched_block_sync = true;
2744
2745                    if chain != Chain::Mainnet {
2746                        // Enable median-based commit timestamp calculation in consensus and
2747                        // enforce checkpoint timestamp monotonicity for testnet.
2748                        cfg.feature_flags
2749                            .consensus_median_timestamp_with_checkpoint_enforcement = true;
2750                        // Enable selecting committee only from active validators that support the
2751                        // next epoch's version and issued valid AuthorityCapabilities notification
2752                        // in testnet.
2753                        cfg.feature_flags
2754                            .select_committee_supporting_next_epoch_version = true;
2755                    }
2756                    if chain != Chain::Testnet && chain != Chain::Mainnet {
2757                        // Switch consensus protocol to Starfish in devnet
2758                        cfg.feature_flags.consensus_choice = ConsensusChoice::Starfish;
2759                    }
2760                }
2761                15 => {
2762                    if chain != Chain::Mainnet && chain != Chain::Testnet {
2763                        // Enable overshoot of 100 in congestion control. This allows bursts of
2764                        // shared object transactions up to 10 times the average allowable
2765                        // load set by `max_accumulated_txn_cost_per_object_in_mysticeti_commit`.
2766                        cfg.max_congestion_limit_overshoot_per_commit = Some(100);
2767                    }
2768                }
2769                16 => {
2770                    // Enable selecting committee only from active validators that support the
2771                    // next epoch's version and issued valid AuthorityCapabilities notification.
2772                    cfg.feature_flags
2773                        .select_committee_supporting_next_epoch_version = true;
2774                    // Enable committing transactions only for traversed headers in Starfish
2775                    cfg.feature_flags
2776                        .consensus_commit_transactions_only_for_traversed_headers = true;
2777                }
2778                17 => {
2779                    // Increase the committee size to 100 on all networks.
2780                    cfg.max_committee_members_count = Some(100);
2781                }
2782                18 => {
2783                    if chain != Chain::Mainnet {
2784                        // Enable passkey authentication support in testnet.
2785                        cfg.feature_flags.passkey_auth = true;
2786                    }
2787                }
2788                19 => {
2789                    if chain != Chain::Testnet && chain != Chain::Mainnet {
2790                        // Enable congestion limit overshoot in the gas price feedback
2791                        // mechanism on devnet.
2792                        cfg.feature_flags
2793                            .congestion_limit_overshoot_in_gas_price_feedback_mechanism = true;
2794                        // Enable a separate gas price feedback mechanism for transactions using
2795                        // randomness on devnet.
2796                        cfg.feature_flags
2797                            .separate_gas_price_feedback_mechanism_for_randomness = true;
2798                        // Enable storing metadata in module bytes and then
2799                        // publishing package metadata in devnet
2800                        cfg.feature_flags.metadata_in_module_bytes = true;
2801                        cfg.feature_flags.publish_package_metadata = true;
2802                        // Enable Move authentication in devnet
2803                        cfg.feature_flags.enable_move_authentication = true;
2804                        // Max auth gas budget is in NANOS and an absolute value 0.25 IOTA
2805                        cfg.max_auth_gas = Some(250_000_000);
2806                        // Increase the base cost for transfer receive object in devnet, since the
2807                        // implementation now does check if parent is not an account.
2808                        cfg.transfer_receive_object_cost_base = Some(100);
2809                        // Enable adjustment of validator rewards based on score in devnet.
2810                        cfg.feature_flags.adjust_rewards_by_score = true;
2811                    }
2812
2813                    if chain != Chain::Mainnet {
2814                        // Switch consensus protocol to Starfish in testnet.
2815                        cfg.feature_flags.consensus_choice = ConsensusChoice::Starfish;
2816
2817                        // Enable validator score calculation on testnet
2818                        cfg.feature_flags.calculate_validator_scores = true;
2819                        cfg.scorer_version = Some(1);
2820                    }
2821
2822                    // Change epoch transaction will contain validator scores
2823                    cfg.feature_flags.pass_validator_scores_to_advance_epoch = true;
2824
2825                    // Enable passkey authentication support in mainnet
2826                    cfg.feature_flags.passkey_auth = true;
2827                }
2828                20 => {
2829                    if chain != Chain::Testnet && chain != Chain::Mainnet {
2830                        // Passes the calculated validator scores to advance epoch only on Devnet
2831                        cfg.feature_flags
2832                            .pass_calculated_validator_scores_to_advance_epoch = true;
2833                    }
2834                }
2835                21 => {
2836                    if chain != Chain::Testnet && chain != Chain::Mainnet {
2837                        // Enable fast commit syncer for faster recovery in devnet.
2838                        cfg.feature_flags.consensus_fast_commit_sync = true;
2839                    }
2840                    if chain != Chain::Mainnet {
2841                        // Enable overshoot of 100 in congestion control on testnet.
2842                        // This allows bursts of shared-object transactions
2843                        // up to 10 times the average allowable load set by
2844                        // `max_accumulated_txn_cost_per_object_in_mysticeti_commit`.
2845                        cfg.max_congestion_limit_overshoot_per_commit = Some(100);
2846                        // Enable congestion limit overshoot in the gas price feedback
2847                        // mechanism on testnet.
2848                        cfg.feature_flags
2849                            .congestion_limit_overshoot_in_gas_price_feedback_mechanism = true;
2850                        // Enable a separate gas price feedback mechanism for transactions using
2851                        // randomness on testnet.
2852                        cfg.feature_flags
2853                            .separate_gas_price_feedback_mechanism_for_randomness = true;
2854                    }
2855
2856                    cfg.auth_context_digest_cost_base = Some(30);
2857                    cfg.auth_context_tx_commands_cost_base = Some(30);
2858                    cfg.auth_context_tx_commands_cost_per_byte = Some(2);
2859                    cfg.auth_context_tx_inputs_cost_base = Some(30);
2860                    cfg.auth_context_tx_inputs_cost_per_byte = Some(2);
2861                    cfg.auth_context_replace_cost_base = Some(30);
2862                    cfg.auth_context_replace_cost_per_byte = Some(2);
2863
2864                    if chain != Chain::Testnet && chain != Chain::Mainnet {
2865                        // Decrease max_auth_gas to 0.00025 IOTA
2866                        cfg.max_auth_gas = Some(250_000);
2867                    }
2868                }
2869                22 => {
2870                    // Enable overshoot of 100 in congestion control on all networks.
2871                    // This allows bursts of shared-object transactions
2872                    // up to 10 times the average allowable load set by
2873                    // `max_accumulated_txn_cost_per_object_in_mysticeti_commit`.
2874                    cfg.max_congestion_limit_overshoot_per_commit = Some(100);
2875                    // Enable congestion limit overshoot in the gas price feedback
2876                    // mechanism on all networks.
2877                    cfg.feature_flags
2878                        .congestion_limit_overshoot_in_gas_price_feedback_mechanism = true;
2879                    // Enable a separate gas price feedback mechanism for transactions using
2880                    // randomness on all networks.
2881                    cfg.feature_flags
2882                        .separate_gas_price_feedback_mechanism_for_randomness = true;
2883
2884                    if chain != Chain::Mainnet {
2885                        // Enable storing metadata in module bytes and then
2886                        // publishing package metadata in testnet
2887                        cfg.feature_flags.metadata_in_module_bytes = true;
2888                        cfg.feature_flags.publish_package_metadata = true;
2889                        // Enable Move authentication in testnet
2890                        cfg.feature_flags.enable_move_authentication = true;
2891                        // Max_auth_gas is 0.00025 IOTA
2892                        cfg.max_auth_gas = Some(250_000);
2893                        // Increase the base cost for transfer receive object in testnet, since the
2894                        // implementation now does check if parent is not an account.
2895                        cfg.transfer_receive_object_cost_base = Some(100);
2896                    }
2897
2898                    if chain != Chain::Mainnet {
2899                        // Enable fast commit syncer for faster recovery on testnet.
2900                        cfg.feature_flags.consensus_fast_commit_sync = true;
2901                    }
2902                }
2903                23 => {
2904                    // Enable Move native context (TxContext via native functions) in all networks.
2905                    cfg.feature_flags.move_native_tx_context = true;
2906                    cfg.tx_context_fresh_id_cost_base = Some(52);
2907                    cfg.tx_context_sender_cost_base = Some(30);
2908                    cfg.tx_context_digest_cost_base = Some(30);
2909                    cfg.tx_context_epoch_cost_base = Some(30);
2910                    cfg.tx_context_epoch_timestamp_ms_cost_base = Some(30);
2911                    cfg.tx_context_sponsor_cost_base = Some(30);
2912                    cfg.tx_context_rgp_cost_base = Some(30);
2913                    cfg.tx_context_gas_price_cost_base = Some(30);
2914                    cfg.tx_context_gas_budget_cost_base = Some(30);
2915                    cfg.tx_context_ids_created_cost_base = Some(30);
2916                    cfg.tx_context_replace_cost_base = Some(30);
2917                }
2918                24 => {
2919                    // Switch consensus protocol to Starfish in all networks.
2920                    cfg.feature_flags.consensus_choice = ConsensusChoice::Starfish;
2921
2922                    if chain != Chain::Testnet && chain != Chain::Mainnet {
2923                        // Enable Move-based sponsor account authentication in devnet.
2924                        cfg.feature_flags.enable_move_authentication_for_sponsor = true;
2925                    }
2926
2927                    // Add tx_data_bytes to AuthContext for intent-based signature
2928                    // verification in account abstraction.
2929                    cfg.auth_context_tx_data_bytes_cost_base = Some(30);
2930                    cfg.auth_context_tx_data_bytes_cost_per_byte = Some(2);
2931
2932                    // Enable additional borrow checks.
2933                    cfg.feature_flags.additional_borrow_checks = true;
2934                }
2935                #[allow(deprecated)]
2936                25 => {
2937                    // Deprecate zkLogin related parameters since zkLogin is deprecated and was
2938                    // never enabled on IOTA.
2939                    cfg.feature_flags.zklogin_max_epoch_upper_bound_delta = None;
2940                    cfg.check_zklogin_id_cost_base = None;
2941                    cfg.check_zklogin_issuer_cost_base = None;
2942                    cfg.max_jwk_votes_per_validator_per_epoch = None;
2943                    cfg.max_age_of_jwk_in_epochs = None;
2944                }
2945                26 => {
2946                    // Introduce a module to allow Move code to query protocol
2947                    // feature flags at runtime.
2948                }
2949                27 => {
2950                    if chain != Chain::Mainnet {
2951                        // Enable consensus block restrictions on testnet/devnet to bound
2952                        // header size by committee size.
2953                        cfg.feature_flags.consensus_block_restrictions = true;
2954                    }
2955
2956                    if chain != Chain::Testnet && chain != Chain::Mainnet {
2957                        // Only sponsor Move authentication is performed pre-consensus in devnet.
2958                        cfg.feature_flags
2959                            .pre_consensus_sponsor_only_move_authentication = true;
2960                    }
2961                }
2962                28 => {
2963                    // AuthenticatorFunctionInfoV1 max BCS size:
2964                    // package (32) + module_name (128) + function_name (128) = 288 bytes = 9 ×
2965                    // digest. auth_context_digest_cost_base = 30 for 32 bytes →
2966                    // 9 × 30 = 270.
2967                    cfg.auth_context_authenticator_function_info_v1_cost_base = Some(270);
2968
2969                    // Enable storing metadata in module bytes and then
2970                    // publishing package metadata in mainnet.
2971                    cfg.feature_flags.metadata_in_module_bytes = true;
2972                    cfg.feature_flags.publish_package_metadata = true;
2973                    // Enable Move authentication in mainnet.
2974                    cfg.feature_flags.enable_move_authentication = true;
2975                    // Increase the base cost for transfer receive object in mainnet, since the
2976                    // implementation now does check if parent is not an account.
2977                    cfg.transfer_receive_object_cost_base = Some(100);
2978
2979                    if chain != Chain::Unknown {
2980                        // max_auth_gas is 0.00002 IOTA in testnet and mainnet.
2981                        cfg.max_auth_gas = Some(20_000);
2982                    }
2983
2984                    if chain != Chain::Mainnet {
2985                        // Enable Move-based sponsor account authentication in testnet.
2986                        cfg.feature_flags.enable_move_authentication_for_sponsor = true;
2987                        // Only sponsor Move authentication is performed pre-consensus in testnet.
2988                        cfg.feature_flags
2989                            .pre_consensus_sponsor_only_move_authentication = true;
2990                    }
2991                }
2992                29 => {
2993                    // Keep advancing the random beacon DKG state machine on every commit
2994                    // while it is still pending so DKG resolves from persisted state
2995                    // (completing, or failing once the timeout round passes) even with no
2996                    // fresh inbound traffic -- e.g. after a validator restart -- instead of
2997                    // staying pending forever and blocking epoch close.
2998                    cfg.feature_flags.always_advance_dkg_to_resolution = true;
2999
3000                    // Enable median-based commit timestamp calculation in consensus and
3001                    // enforce checkpoint timestamp monotonicity for mainnet.
3002                    cfg.feature_flags
3003                        .consensus_median_timestamp_with_checkpoint_enforcement = true;
3004
3005                    // Enable fast commit syncer for faster recovery on all networks.
3006                    cfg.feature_flags.consensus_fast_commit_sync = true;
3007                    // Enable consensus block restrictions on all networks to bound
3008                    // header size by committee size and garbage-collect the block
3009                    // manager.
3010                    cfg.feature_flags.consensus_block_restrictions = true;
3011                }
3012                30 => {
3013                    // Extend the protocol_config framework module with
3014                    // `get_attr<T>`, a generic native that lets Move code
3015                    // read any numeric or boolean protocol parameter by name,
3016                    // returning T directly and aborting on error.
3017                    // Also expose `is_feature_enabled` and `get_attr<T>` to
3018                    // iota_system via a new iota_system::protocol_config
3019                    // module.
3020                }
3021                31 => {
3022                    cfg.feature_flags.validator_metadata_verify_v2 = true;
3023
3024                    // Amortize the minimum checkpoint interval over a sliding
3025                    // window so the checkpoint rate holds at the ceiling.
3026                    // Enabled on non-Mainnet/Testnet chains only for now.
3027                    if chain != Chain::Mainnet && chain != Chain::Testnet {
3028                        cfg.checkpoint_rate_window_size = Some(20);
3029                        // Publish package metadata with the module metadata stored as a
3030                        // dynamic field.
3031                        cfg.feature_flags
3032                            .package_metadata_with_dynamic_module_metadata = true;
3033                    }
3034                }
3035                // Use this template when making changes:
3036                //
3037                //     // modify an existing constant.
3038                //     move_binary_format_version: Some(7),
3039                //
3040                //     // Add a new constant (which is set to None in prior versions).
3041                //     new_constant: Some(new_value),
3042                //
3043                //     // Remove a constant (ensure that it is never accessed during this version).
3044                //     max_move_object_size: None,
3045                _ => panic!("unsupported version {version:?}"),
3046            }
3047        }
3048        cfg
3049    }
3050
3051    // Extract the bytecode verifier config from this protocol config.
3052    // If used during signing, `signing_limits` should be set.
3053    // The third limit configures`sanity_check_with_regex_reference_safety`,
3054    // which runs the new regex-based reference safety check to check that it is
3055    // strictly more permissive than the current implementation.
3056    pub fn verifier_config(&self, signing_limits: Option<(usize, usize, usize)>) -> VerifierConfig {
3057        let (
3058            max_back_edges_per_function,
3059            max_back_edges_per_module,
3060            sanity_check_with_regex_reference_safety,
3061        ) = if let Some((
3062            max_back_edges_per_function,
3063            max_back_edges_per_module,
3064            sanity_check_with_regex_reference_safety,
3065        )) = signing_limits
3066        {
3067            (
3068                Some(max_back_edges_per_function),
3069                Some(max_back_edges_per_module),
3070                Some(sanity_check_with_regex_reference_safety),
3071            )
3072        } else {
3073            (None, None, None)
3074        };
3075
3076        let additional_borrow_checks = if signing_limits.is_some() {
3077            // Always apply additional borrow checks during signing regardless of
3078            // protocol version, to prevent accepting potentially unsafe bytecode.
3079            true
3080        } else {
3081            self.additional_borrow_checks()
3082        };
3083
3084        VerifierConfig {
3085            max_loop_depth: Some(self.max_loop_depth() as usize),
3086            max_generic_instantiation_length: Some(self.max_generic_instantiation_length() as usize),
3087            max_function_parameters: Some(self.max_function_parameters() as usize),
3088            max_basic_blocks: Some(self.max_basic_blocks() as usize),
3089            max_value_stack_size: self.max_value_stack_size() as usize,
3090            max_type_nodes: Some(self.max_type_nodes() as usize),
3091            max_push_size: Some(self.max_push_size() as usize),
3092            max_dependency_depth: Some(self.max_dependency_depth() as usize),
3093            max_fields_in_struct: Some(self.max_fields_in_struct() as usize),
3094            max_function_definitions: Some(self.max_function_definitions() as usize),
3095            max_data_definitions: Some(self.max_struct_definitions() as usize),
3096            max_constant_vector_len: Some(self.max_move_vector_len()),
3097            max_back_edges_per_function,
3098            max_back_edges_per_module,
3099            max_basic_blocks_in_script: None,
3100            max_identifier_len: self.max_move_identifier_len_as_option(), /* Before protocol
3101                                                                           * version 9, there was
3102                                                                           * no limit */
3103            bytecode_version: self.move_binary_format_version(),
3104            max_variants_in_enum: self.max_move_enum_variants_as_option(),
3105            additional_borrow_checks,
3106            sanity_check_with_regex_reference_safety: sanity_check_with_regex_reference_safety
3107                .map(|limit| limit as u128),
3108        }
3109    }
3110
3111    /// Override one or more settings in the config, for testing.
3112    /// This must be called at the beginning of the test, before
3113    /// get_for_(min|max)_version is called, since those functions cache
3114    /// their return value.
3115    pub fn apply_overrides_for_testing(
3116        override_fn: impl Fn(ProtocolVersion, Self) -> Self + Send + Sync + 'static,
3117    ) -> OverrideGuard {
3118        CONFIG_OVERRIDE.with(|ovr| {
3119            let mut cur = ovr.borrow_mut();
3120            assert!(cur.is_none(), "config override already present");
3121            *cur = Some(Box::new(override_fn));
3122            OverrideGuard
3123        })
3124    }
3125}
3126
3127// Setters for tests.
3128// This is only needed for feature_flags. Please suffix each setter with
3129// `_for_testing`. Non-feature_flags should already have test setters defined
3130// through macros.
3131impl ProtocolConfig {
3132    pub fn set_per_object_congestion_control_mode_for_testing(
3133        &mut self,
3134        val: PerObjectCongestionControlMode,
3135    ) {
3136        self.feature_flags.per_object_congestion_control_mode = val;
3137    }
3138
3139    pub fn set_consensus_choice_for_testing(&mut self, val: ConsensusChoice) {
3140        self.feature_flags.consensus_choice = val;
3141    }
3142
3143    pub fn set_consensus_network_for_testing(&mut self, val: ConsensusNetwork) {
3144        self.feature_flags.consensus_network = val;
3145    }
3146
3147    pub fn set_passkey_auth_for_testing(&mut self, val: bool) {
3148        self.feature_flags.passkey_auth = val
3149    }
3150
3151    pub fn set_disallow_new_modules_in_deps_only_packages_for_testing(&mut self, val: bool) {
3152        self.feature_flags
3153            .disallow_new_modules_in_deps_only_packages = val;
3154    }
3155
3156    pub fn set_consensus_round_prober_for_testing(&mut self, val: bool) {
3157        self.feature_flags.consensus_round_prober = val;
3158    }
3159
3160    pub fn set_consensus_distributed_vote_scoring_strategy_for_testing(&mut self, val: bool) {
3161        self.feature_flags
3162            .consensus_distributed_vote_scoring_strategy = val;
3163    }
3164
3165    pub fn set_gc_depth_for_testing(&mut self, val: u32) {
3166        self.consensus_gc_depth = Some(val);
3167    }
3168
3169    pub fn set_consensus_linearize_subdag_v2_for_testing(&mut self, val: bool) {
3170        self.feature_flags.consensus_linearize_subdag_v2 = val;
3171    }
3172
3173    pub fn set_consensus_round_prober_probe_accepted_rounds(&mut self, val: bool) {
3174        self.feature_flags
3175            .consensus_round_prober_probe_accepted_rounds = val;
3176    }
3177
3178    pub fn set_accept_passkey_in_multisig_for_testing(&mut self, val: bool) {
3179        self.feature_flags.accept_passkey_in_multisig = val;
3180    }
3181
3182    pub fn set_consensus_smart_ancestor_selection_for_testing(&mut self, val: bool) {
3183        self.feature_flags.consensus_smart_ancestor_selection = val;
3184    }
3185
3186    pub fn set_consensus_batched_block_sync_for_testing(&mut self, val: bool) {
3187        self.feature_flags.consensus_batched_block_sync = val;
3188    }
3189
3190    pub fn set_congestion_control_min_free_execution_slot_for_testing(&mut self, val: bool) {
3191        self.feature_flags
3192            .congestion_control_min_free_execution_slot = val;
3193    }
3194
3195    pub fn set_congestion_control_gas_price_feedback_mechanism_for_testing(&mut self, val: bool) {
3196        self.feature_flags
3197            .congestion_control_gas_price_feedback_mechanism = val;
3198    }
3199
3200    pub fn set_select_committee_from_eligible_validators_for_testing(&mut self, val: bool) {
3201        self.feature_flags.select_committee_from_eligible_validators = val;
3202    }
3203
3204    pub fn set_track_non_committee_eligible_validators_for_testing(&mut self, val: bool) {
3205        self.feature_flags.track_non_committee_eligible_validators = val;
3206    }
3207
3208    pub fn set_select_committee_supporting_next_epoch_version(&mut self, val: bool) {
3209        self.feature_flags
3210            .select_committee_supporting_next_epoch_version = val;
3211    }
3212
3213    pub fn set_consensus_median_timestamp_with_checkpoint_enforcement_for_testing(
3214        &mut self,
3215        val: bool,
3216    ) {
3217        self.feature_flags
3218            .consensus_median_timestamp_with_checkpoint_enforcement = val;
3219    }
3220
3221    pub fn set_consensus_commit_transactions_only_for_traversed_headers_for_testing(
3222        &mut self,
3223        val: bool,
3224    ) {
3225        self.feature_flags
3226            .consensus_commit_transactions_only_for_traversed_headers = val;
3227    }
3228
3229    pub fn set_congestion_limit_overshoot_in_gas_price_feedback_mechanism_for_testing(
3230        &mut self,
3231        val: bool,
3232    ) {
3233        self.feature_flags
3234            .congestion_limit_overshoot_in_gas_price_feedback_mechanism = val;
3235    }
3236
3237    pub fn set_separate_gas_price_feedback_mechanism_for_randomness_for_testing(
3238        &mut self,
3239        val: bool,
3240    ) {
3241        self.feature_flags
3242            .separate_gas_price_feedback_mechanism_for_randomness = val;
3243    }
3244
3245    pub fn set_metadata_in_module_bytes_for_testing(&mut self, val: bool) {
3246        self.feature_flags.metadata_in_module_bytes = val;
3247    }
3248
3249    pub fn set_publish_package_metadata_for_testing(&mut self, val: bool) {
3250        self.feature_flags.publish_package_metadata = val;
3251    }
3252
3253    pub fn set_enable_move_authentication_for_testing(&mut self, val: bool) {
3254        self.feature_flags.enable_move_authentication = val;
3255    }
3256
3257    pub fn set_enable_move_authentication_for_sponsor_for_testing(&mut self, val: bool) {
3258        self.feature_flags.enable_move_authentication_for_sponsor = val;
3259    }
3260
3261    pub fn set_consensus_fast_commit_sync_for_testing(&mut self, val: bool) {
3262        self.feature_flags.consensus_fast_commit_sync = val;
3263    }
3264
3265    pub fn set_consensus_block_restrictions_for_testing(&mut self, val: bool) {
3266        self.feature_flags.consensus_block_restrictions = val;
3267    }
3268
3269    pub fn set_pre_consensus_sponsor_only_move_authentication_for_testing(&mut self, val: bool) {
3270        self.feature_flags
3271            .pre_consensus_sponsor_only_move_authentication = val;
3272    }
3273
3274    pub fn set_consensus_starfish_speed_for_testing(&mut self, val: bool) {
3275        self.feature_flags.consensus_starfish_speed = val;
3276    }
3277
3278    pub fn set_always_advance_dkg_to_resolution_for_testing(&mut self, val: bool) {
3279        self.feature_flags.always_advance_dkg_to_resolution = val;
3280    }
3281
3282    pub fn set_enable_pcool_flow_for_testing(&mut self, val: bool) {
3283        self.feature_flags.enable_pcool_flow = val;
3284    }
3285
3286    pub fn set_commits_per_schedule_for_testing(&mut self, val: u32) {
3287        self.consensus_commits_per_schedule = Some(val);
3288    }
3289
3290    pub fn set_deny_rule_governance_for_testing(&mut self, val: bool) {
3291        self.feature_flags.deny_rule_governance = val;
3292    }
3293
3294    pub fn set_package_metadata_with_dynamic_module_metadata_for_testing(&mut self, val: bool) {
3295        self.feature_flags
3296            .package_metadata_with_dynamic_module_metadata = val;
3297    }
3298}
3299
3300type OverrideFn = dyn Fn(ProtocolVersion, ProtocolConfig) -> ProtocolConfig + Send + Sync;
3301
3302thread_local! {
3303    static CONFIG_OVERRIDE: RefCell<Option<Box<OverrideFn>>> = const { RefCell::new(None) };
3304}
3305
3306#[must_use]
3307pub struct OverrideGuard;
3308
3309impl Drop for OverrideGuard {
3310    fn drop(&mut self) {
3311        info!("restoring override fn");
3312        CONFIG_OVERRIDE.with(|ovr| {
3313            *ovr.borrow_mut() = None;
3314        });
3315    }
3316}
3317
3318/// Defines which limit got crossed.
3319/// The value which crossed the limit and value of the limit crossed are
3320/// embedded
3321#[derive(PartialEq, Eq)]
3322pub enum LimitThresholdCrossed {
3323    None,
3324    Soft(u128, u128),
3325    Hard(u128, u128),
3326}
3327
3328/// Convenience function for comparing limit ranges
3329/// V::MAX must be at >= U::MAX and T::MAX
3330pub fn check_limit_in_range<T: Into<V>, U: Into<V>, V: PartialOrd + Into<u128>>(
3331    x: T,
3332    soft_limit: U,
3333    hard_limit: V,
3334) -> LimitThresholdCrossed {
3335    let x: V = x.into();
3336    let soft_limit: V = soft_limit.into();
3337
3338    debug_assert!(soft_limit <= hard_limit);
3339
3340    // It is important to preserve this comparison order because if soft_limit ==
3341    // hard_limit we want LimitThresholdCrossed::Hard
3342    if x >= hard_limit {
3343        LimitThresholdCrossed::Hard(x.into(), hard_limit.into())
3344    } else if x < soft_limit {
3345        LimitThresholdCrossed::None
3346    } else {
3347        LimitThresholdCrossed::Soft(x.into(), soft_limit.into())
3348    }
3349}
3350
3351#[macro_export]
3352macro_rules! check_limit {
3353    ($x:expr, $hard:expr) => {
3354        check_limit!($x, $hard, $hard)
3355    };
3356    ($x:expr, $soft:expr, $hard:expr) => {
3357        check_limit_in_range($x as u64, $soft, $hard)
3358    };
3359}
3360
3361/// Used to check which limits were crossed if the TX is metered (not system tx)
3362/// Args are: is_metered, value_to_check, metered_limit, unmetered_limit
3363/// metered_limit is always less than or equal to unmetered_hard_limit
3364#[macro_export]
3365macro_rules! check_limit_by_meter {
3366    ($is_metered:expr, $x:expr, $metered_limit:expr, $unmetered_hard_limit:expr, $metric:expr) => {{
3367        // If this is metered, we use the metered_limit limit as the upper bound
3368        let (h, metered_str) = if $is_metered {
3369            ($metered_limit, "metered")
3370        } else {
3371            // Unmetered gets more headroom
3372            ($unmetered_hard_limit, "unmetered")
3373        };
3374        use iota_protocol_config::check_limit_in_range;
3375        let result = check_limit_in_range($x as u64, $metered_limit, h);
3376        match result {
3377            LimitThresholdCrossed::None => {}
3378            LimitThresholdCrossed::Soft(_, _) => {
3379                $metric.with_label_values(&[metered_str, "soft"]).inc();
3380            }
3381            LimitThresholdCrossed::Hard(_, _) => {
3382                $metric.with_label_values(&[metered_str, "hard"]).inc();
3383            }
3384        };
3385        result
3386    }};
3387}
3388
3389#[cfg(all(test, not(msim)))]
3390mod test {
3391    use insta::assert_yaml_snapshot;
3392
3393    use super::*;
3394
3395    #[test]
3396    fn snapshot_tests() {
3397        println!("\n============================================================================");
3398        println!("!                                                                          !");
3399        println!("! IMPORTANT: never update snapshots from this test. only add new versions! !");
3400        println!("!                                                                          !");
3401        println!("============================================================================\n");
3402        for chain_id in &[Chain::Unknown, Chain::Mainnet, Chain::Testnet] {
3403            // make Chain::Unknown snapshots compatible with pre-chain-id snapshots so that
3404            // we don't break the release-time compatibility tests. Once Chain
3405            // Id configs have been released everywhere, we can remove this and
3406            // only test Mainnet and Testnet
3407            let chain_str = match chain_id {
3408                Chain::Unknown => "".to_string(),
3409                _ => format!("{chain_id:?}_"),
3410            };
3411            for i in MIN_PROTOCOL_VERSION..=MAX_PROTOCOL_VERSION {
3412                let cur = ProtocolVersion::new(i);
3413                assert_yaml_snapshot!(
3414                    format!("{}version_{}", chain_str, cur.as_u64()),
3415                    ProtocolConfig::get_for_version(cur, *chain_id)
3416                );
3417            }
3418        }
3419    }
3420
3421    #[test]
3422    fn test_getters() {
3423        let prot: ProtocolConfig =
3424            ProtocolConfig::get_for_version(ProtocolVersion::new(1), Chain::Unknown);
3425        assert_eq!(
3426            prot.max_arguments(),
3427            prot.max_arguments_as_option().unwrap()
3428        );
3429    }
3430
3431    #[test]
3432    fn test_setters() {
3433        let mut prot: ProtocolConfig =
3434            ProtocolConfig::get_for_version(ProtocolVersion::new(1), Chain::Unknown);
3435        prot.set_max_arguments_for_testing(123);
3436        assert_eq!(prot.max_arguments(), 123);
3437
3438        prot.set_max_arguments_from_str_for_testing("321".to_string());
3439        assert_eq!(prot.max_arguments(), 321);
3440
3441        prot.disable_max_arguments_for_testing();
3442        assert_eq!(prot.max_arguments_as_option(), None);
3443
3444        prot.set_attr_for_testing("max_arguments".to_string(), "456".to_string());
3445        assert_eq!(prot.max_arguments(), 456);
3446    }
3447
3448    #[test]
3449    #[should_panic(expected = "unsupported version")]
3450    fn max_version_test() {
3451        // When this does not panic, version higher than MAX_PROTOCOL_VERSION exists.
3452        // To fix, bump MAX_PROTOCOL_VERSION or disable this check for the version.
3453        let _ = ProtocolConfig::get_for_version_impl(
3454            ProtocolVersion::new(MAX_PROTOCOL_VERSION + 1),
3455            Chain::Unknown,
3456        );
3457    }
3458
3459    #[test]
3460    fn lookup_by_string_test() {
3461        let prot: ProtocolConfig =
3462            ProtocolConfig::get_for_version(ProtocolVersion::new(1), Chain::Mainnet);
3463        // Does not exist
3464        assert!(prot.lookup_attr("some random string".to_string()).is_none());
3465
3466        assert!(
3467            prot.lookup_attr("max_arguments".to_string())
3468                == Some(ProtocolConfigValue::u32(prot.max_arguments())),
3469        );
3470
3471        // We didnt have this in version 1 on Mainnet
3472        assert!(
3473            prot.lookup_attr("poseidon_bn254_cost_base".to_string())
3474                .is_none()
3475        );
3476        assert!(
3477            prot.attr_map()
3478                .get("poseidon_bn254_cost_base")
3479                .unwrap()
3480                .is_none()
3481        );
3482
3483        // But we did in version 1 on Devnet
3484        let prot: ProtocolConfig =
3485            ProtocolConfig::get_for_version(ProtocolVersion::new(1), Chain::Unknown);
3486
3487        assert!(
3488            prot.lookup_attr("poseidon_bn254_cost_base".to_string())
3489                == Some(ProtocolConfigValue::u64(prot.poseidon_bn254_cost_base()))
3490        );
3491        assert!(
3492            prot.attr_map().get("poseidon_bn254_cost_base").unwrap()
3493                == &Some(ProtocolConfigValue::u64(prot.poseidon_bn254_cost_base()))
3494        );
3495
3496        // Check feature flags
3497        let prot: ProtocolConfig =
3498            ProtocolConfig::get_for_version(ProtocolVersion::new(1), Chain::Mainnet);
3499        // Does not exist
3500        assert!(
3501            prot.feature_flags
3502                .lookup_attr("some random string".to_owned())
3503                .is_none()
3504        );
3505        assert!(
3506            !prot
3507                .feature_flags
3508                .attr_map()
3509                .contains_key("some random string")
3510        );
3511
3512        // Was false in v1 on Mainnet
3513        assert!(prot.feature_flags.lookup_attr("enable_poseidon".to_owned()) == Some(false));
3514        assert!(
3515            prot.feature_flags
3516                .attr_map()
3517                .get("enable_poseidon")
3518                .unwrap()
3519                == &false
3520        );
3521        let prot: ProtocolConfig =
3522            ProtocolConfig::get_for_version(ProtocolVersion::new(1), Chain::Unknown);
3523        // Was true from v1 and up on Devnet
3524        assert!(prot.feature_flags.lookup_attr("enable_poseidon".to_owned()) == Some(true));
3525        assert!(
3526            prot.feature_flags
3527                .attr_map()
3528                .get("enable_poseidon")
3529                .unwrap()
3530                == &true
3531        );
3532    }
3533
3534    #[test]
3535    fn limit_range_fn_test() {
3536        let low = 100u32;
3537        let high = 10000u64;
3538
3539        assert!(check_limit!(1u8, low, high) == LimitThresholdCrossed::None);
3540        assert!(matches!(
3541            check_limit!(255u16, low, high),
3542            LimitThresholdCrossed::Soft(255u128, 100)
3543        ));
3544        // This wont compile because lossy
3545        // assert!(check_limit!(100000000u128, low, high) ==
3546        // LimitThresholdCrossed::None); This wont compile because lossy
3547        // assert!(check_limit!(100000000usize, low, high) ==
3548        // LimitThresholdCrossed::None);
3549
3550        assert!(matches!(
3551            check_limit!(2550000u64, low, high),
3552            LimitThresholdCrossed::Hard(2550000, 10000)
3553        ));
3554
3555        assert!(matches!(
3556            check_limit!(2550000u64, high, high),
3557            LimitThresholdCrossed::Hard(2550000, 10000)
3558        ));
3559
3560        assert!(matches!(
3561            check_limit!(1u8, high),
3562            LimitThresholdCrossed::None
3563        ));
3564
3565        assert!(check_limit!(255u16, high) == LimitThresholdCrossed::None);
3566
3567        assert!(matches!(
3568            check_limit!(2550000u64, high),
3569            LimitThresholdCrossed::Hard(2550000, 10000)
3570        ));
3571    }
3572}