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