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