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