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