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