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