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