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