Skip to main content

iota_protocol_config/
lib.rs

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