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