Skip to main content

iota_protocol_config/
lib.rs

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