Skip to main content

iota_protocol_config/
lib.rs

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