Skip to main content

iota_protocol_config/
lib.rs

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