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