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