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