Skip to main content

iota_protocol_config/
lib.rs

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