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