Skip to main content

iota_protocol_config/
lib.rs

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