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