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