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