Skip to main content

iota_protocol_config/
lib.rs

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