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