sui_protocol_config/
lib.rs

1// Copyright (c) Mysten Labs, Inc.
2// SPDX-License-Identifier: Apache-2.0
3
4use std::{
5    collections::{BTreeMap, BTreeSet},
6    sync::{
7        Arc, LazyLock,
8        atomic::{AtomicBool, Ordering},
9    },
10};
11
12#[cfg(msim)]
13use std::cell::RefCell;
14#[cfg(not(msim))]
15use std::sync::Mutex;
16
17use clap::*;
18use fastcrypto::encoding::{Base58, Encoding, Hex};
19use move_binary_format::{
20    binary_config::{BinaryConfig, TableConfig},
21    file_format_common::VERSION_1,
22};
23use move_core_types::account_address::AccountAddress;
24use move_vm_config::verifier::VerifierConfig;
25use mysten_common::in_integration_test;
26use serde::{Deserialize, Serialize};
27use serde_with::skip_serializing_none;
28use sui_protocol_config_macros::{
29    ProtocolConfigAccessors, ProtocolConfigFeatureFlagsGetters, ProtocolConfigOverride,
30};
31use tracing::{info, warn};
32
33/// The minimum and maximum protocol versions supported by this build.
34const MIN_PROTOCOL_VERSION: u64 = 1;
35const MAX_PROTOCOL_VERSION: u64 = 122;
36
37const TESTNET_USDC: &str =
38    "0xa1ec7fc00a6f40db9693ad1415d0c193ad3906494428cf252621037bd7117e29::usdc::USDC";
39
40// Record history of protocol version allocations here:
41//
42// Version 1: Original version.
43// Version 2: Framework changes, including advancing epoch_start_time in safemode.
44// Version 3: gas model v2, including all sui conservation fixes. Fix for loaded child object
45//            changes, enable package upgrades, add limits on `max_size_written_objects`,
46//            `max_size_written_objects_system_tx`
47// Version 4: New reward slashing rate. Framework changes to skip stake susbidy when the epoch
48//            length is short.
49// Version 5: Package upgrade compatibility error fix. New gas cost table. New scoring decision
50//            mechanism that includes up to f scoring authorities.
51// Version 6: Change to how bytes are charged in the gas meter, increase buffer stake to 0.5f
52// Version 7: Disallow adding new abilities to types during package upgrades,
53//            disable_invariant_violation_check_in_swap_loc,
54//            disable init functions becoming entry,
55//            hash module bytes individually before computing package digest.
56// Version 8: Disallow changing abilities and type constraints for type parameters in structs
57//            during upgrades.
58// Version 9: Limit the length of Move idenfitiers to 128.
59//            Disallow extraneous module bytes,
60//            advance_to_highest_supported_protocol_version,
61// Version 10:increase bytecode verifier `max_verifier_meter_ticks_per_function` and
62//            `max_meter_ticks_per_module` limits each from 6_000_000 to 16_000_000. sui-system
63//            framework changes.
64// Version 11: Introduce `std::type_name::get_with_original_ids` to the system frameworks. Bound max depth of values within the VM.
65// Version 12: Changes to deepbook in framework to add API for querying marketplace.
66//             Change NW Batch to use versioned metadata field.
67//             Changes to sui-system package to add PTB-friendly unstake function, and minor cleanup.
68// Version 13: System package change deprecating `0xdee9::clob` and `0xdee9::custodian`, replaced by
69//             `0xdee9::clob_v2` and `0xdee9::custodian_v2`.
70// Version 14: Introduce a config variable to allow charging of computation to be either
71//             bucket base or rounding up. The presence of `gas_rounding_step` (or `None`)
72//             decides whether rounding is applied or not.
73// Version 15: Add reordering of user transactions by gas price after consensus.
74//             Add `sui::table_vec::drop` to the framework via a system package upgrade.
75// Version 16: Enabled simplified_unwrap_then_delete feature flag, which allows the execution engine
76//             to no longer consult the object store when generating unwrapped_then_deleted in the
77//             effects; this also allows us to stop including wrapped tombstones in accumulator.
78//             Add self-matching prevention for deepbook.
79// Version 17: Enable upgraded multisig support.
80// Version 18: Introduce execution layer versioning, preserve all existing behaviour in v0.
81//             Gas minimum charges moved to be a multiplier over the reference gas price. In this
82//             protocol version the multiplier is the same as the lowest bucket of computation
83//             such that the minimum transaction cost is the same as the minimum computation
84//             bucket.
85//             Add a feature flag to indicate the changes semantics of `base_tx_cost_fixed`.
86// Version 19: Changes to sui-system package to enable liquid staking.
87//             Add limit for total size of events.
88//             Increase limit for number of events emitted to 1024.
89// Version 20: Enables the flag `narwhal_new_leader_election_schedule` for the new narwhal leader
90//             schedule algorithm for enhanced fault tolerance and sets the bad node stake threshold
91//             value. Both values are set for all the environments except mainnet.
92// Version 21: ZKLogin known providers.
93// Version 22: Child object format change.
94// Version 23: Enabling the flag `narwhal_new_leader_election_schedule` for the new narwhal leader
95//             schedule algorithm for enhanced fault tolerance and sets the bad node stake threshold
96//             value for mainnet.
97// Version 24: Re-enable simple gas conservation checks.
98//             Package publish/upgrade number in a single transaction limited.
99//             JWK / authenticator state flags.
100// Version 25: Add sui::table_vec::swap and sui::table_vec::swap_remove to system packages.
101// Version 26: New gas model version.
102//             Add support for receiving objects off of other objects in devnet only.
103// Version 28: Add sui::zklogin::verify_zklogin_id and related functions to sui framework.
104//             Enable transaction effects v2 in devnet.
105// Version 29: Add verify_legacy_zklogin_address flag to sui framework, this add ability to verify
106//             transactions from a legacy zklogin address.
107// Version 30: Enable Narwhal CertificateV2
108//             Add support for random beacon.
109//             Enable transaction effects v2 in testnet.
110//             Deprecate supported oauth providers from protocol config and rely on node config
111//             instead.
112//             In execution, has_public_transfer is recomputed when loading the object.
113//             Add support for shared obj deletion and receiving objects off of other objects in devnet only.
114// Version 31: Add support for shared object deletion in devnet only.
115//             Add support for getting object ID referenced by receiving object in sui framework.
116//             Create new execution layer version, and preserve previous behavior in v1.
117//             Update semantics of `sui::transfer::receive` and add `sui::transfer::public_receive`.
118// Version 32: Add delete functions for VerifiedID and VerifiedIssuer.
119//             Add sui::token module to sui framework.
120//             Enable transfer to object in testnet.
121//             Enable Narwhal CertificateV2 on mainnet
122//             Make critbit tree and order getters public in deepbook.
123// Version 33: Add support for `receiving_object_id` function in framework
124//             Hardened OTW check.
125//             Enable transfer-to-object in mainnet.
126//             Enable shared object deletion in testnet.
127//             Enable effects v2 in mainnet.
128// Version 34: Framework changes for random beacon.
129// Version 35: Add poseidon hash function.
130//             Enable coin deny list.
131// Version 36: Enable group operations native functions in devnet.
132//             Enable shared object deletion in mainnet.
133//             Set the consensus accepted transaction size and the included transactions size in the proposed block.
134// Version 37: Reject entry functions with mutable Random.
135// Version 38: Introduce limits for binary tables size.
136// Version 39: Allow skipped epochs for randomness updates.
137//             Extra version to fix `test_upgrade_compatibility` simtest.
138// Version 40:
139// Version 41: Enable group operations native functions in testnet and mainnet (without msm).
140// Version 42: Migrate sui framework and related code to Move 2024
141// Version 43: Introduce the upper bound delta config for a zklogin signature's max epoch.
142//             Introduce an explicit parameter for the tick limit per package (previously this was
143//             represented by the parameter for the tick limit per module).
144// Version 44: Enable consensus fork detection on mainnet.
145//             Switch between Narwhal and Mysticeti consensus in tests, devnet and testnet.
146// Version 45: Use tonic networking for Mysticeti consensus.
147//             Set min Move binary format version to 6.
148//             Enable transactions to be signed with zkLogin inside multisig signature.
149//             Add native bridge.
150//             Enable native bridge in devnet
151//             Enable Leader Scoring & Schedule Change for Mysticeti consensus on testnet.
152// Version 46: Enable native bridge in testnet
153//             Enable resharing at the same initial shared version.
154// Version 47: Deepbook changes (framework update)
155// Version 48: Use tonic networking for Mysticeti.
156//             Resolve Move abort locations to the package id instead of the runtime module ID.
157//             Enable random beacon in testnet.
158//             Use new VM when verifying framework packages.
159// Version 49: Enable Move enums on devnet.
160//             Enable VDF in devnet
161//             Enable consensus commit prologue V3 in devnet.
162//             Run Mysticeti consensus by default.
163// Version 50: Add update_node_url to native bridge,
164//             New Move stdlib integer modules
165//             Enable checkpoint batching in testnet.
166//             Prepose consensus commit prologue in checkpoints.
167//             Set number of leaders per round for Mysticeti commits.
168// Version 51: Switch to DKG V1.
169//             Enable deny list v2 on devnet.
170// Version 52: Emit `CommitteeMemberUrlUpdateEvent` when updating bridge node url.
171//             std::config native functions.
172//             Modified sui-system package to enable withdrawal of stake before it becomes active.
173//             Enable soft bundle in devnet and testnet.
174//             Core macro visibility in sui core framework.
175//             Enable checkpoint batching in mainnet.
176//             Enable Mysticeti on mainnet.
177//             Enable Leader Scoring & Schedule Change for Mysticeti consensus on mainnet.
178//             Turn on count based shared object congestion control in devnet.
179//             Enable consensus commit prologue V3 in testnet.
180//             Enable enums on testnet.
181//             Add support for passkey in devnet.
182//             Enable deny list v2 on testnet and mainnet.
183// Version 53: Add feature flag to decide whether to attempt to finalize bridge committee
184//             Enable consensus commit prologue V3 on testnet.
185//             Turn on shared object congestion control in testnet.
186//             Update stdlib natives costs
187// Version 54: Enable random beacon on mainnet.
188//             Enable soft bundle on mainnet.
189// Version 55: Enable enums on mainnet.
190//             Rethrow serialization type layout errors instead of converting them.
191// Version 56: Enable bridge on mainnet.
192//             Note: do not use version 56 for any new features.
193// Version 57: Reduce minimum number of random beacon shares.
194// Version 58: Optimize boolean binops
195//             Finalize bridge committee on mainnet.
196//             Switch to distributed vote scoring in consensus in devnet
197// Version 59: Enable round prober in consensus.
198// Version 60: Validation of public inputs for Groth16 verification.
199//             Enable configuration of maximum number of type nodes in a type layout.
200// Version 61: Switch to distributed vote scoring in consensus in testnet
201//             Further reduce minimum number of random beacon shares.
202//             Add feature flag for Mysticeti fastpath.
203// Version 62: Makes the event's sending module package upgrade-aware.
204// Version 63: Enable gas based congestion control in consensus commit.
205// Version 64: Revert congestion control change.
206// Version 65: Enable distributed vote scoring in mainnet.
207// Version 66: Revert distributed vote scoring in mainnet.
208//             Framework fix for fungible staking book-keeping.
209// Version 67: Re-enable distributed vote scoring in mainnet.
210// Version 68: Add G1Uncompressed group to group ops.
211//             Update to Move stdlib.
212//             Enable gas based congestion control with overage.
213//             Further reduce minimum number of random beacon shares.
214//             Disallow adding new modules in `deps-only` packages.
215// Version 69: Sets number of rounds allowed for fastpath voting in consensus.
216//             Enable smart ancestor selection in devnet.
217//             Enable G1Uncompressed group in testnet.
218// Version 70: Enable smart ancestor selection in testnet.
219//             Enable probing for accepted rounds in round prober in testnet
220//             Add new gas model version to update charging of native functions.
221//             Add std::uq64_64 module to Move stdlib.
222//             Improve gas/wall time efficiency of some Move stdlib vector functions
223// Version 71: [SIP-45] Enable consensus amplification.
224// Version 72: Fix issue where `convert_type_argument_error` wasn't being used in all cases.
225//             Max gas budget moved to 50_000 SUI
226//             Max gas price moved to 50 SUI
227//             Variants as type nodes.
228// Version 73: Enable new marker table version.
229//             Enable consensus garbage collection and new commit rule for devnet.
230//             Enable zstd compression for consensus tonic network in testnet.
231//             Enable smart ancestor selection in mainnet.
232//             Enable probing for accepted rounds in round prober in mainnet
233// Version 74: Enable load_nitro_attestation move function in sui framework in devnet.
234//             Enable all gas costs for load_nitro_attestation.
235//             Enable zstd compression for consensus tonic network in mainnet.
236//             Enable the new commit rule for devnet.
237// Version 75: Enable passkey auth in testnet.
238// Version 76: Deprecate Deepbook V2 order placement and deposit.
239//             Removes unnecessary child object mutations
240//             Enable passkey auth in multisig for testnet.
241// Version 77: Enable uncompressed point group ops on mainnet.
242//             Enable consensus garbage collection for testnet
243//             Enable the new consensus commit rule for testnet.
244// Version 78: Make `TxContext` Move API native
245//             Enable execution time estimate mode for congestion control on testnet.
246// Version 79: Enable median based commit timestamp in consensus on testnet.
247//             Increase threshold for bad nodes that won't be considered leaders in consensus in testnet
248//             Enable load_nitro_attestation move function in sui framework in testnet.
249//             Enable consensus garbage collection for mainnet
250//             Enable the new consensus commit rule for mainnet.
251// Version 80: Bound size of values created in the adapter.
252// Version 81: Enable median based commit timestamp in consensus on mainnet.
253//             Enforce checkpoint timestamps are non-decreasing for testnet and mainnet.
254//             Increase threshold for bad nodes that won't be considered leaders in consensus in mainnet
255// Version 82: Relax bounding of size of values created in the adapter.
256// Version 83: Resolve `TypeInput` IDs to defining ID when converting to `TypeTag`s in the adapter.
257//             Enable execution time estimate mode for congestion control on mainnet.
258//             Enable nitro attestation upgraded parsing and mainnet.
259// Version 84: Limit number of stored execution time observations between epochs.
260// Version 85: Enable party transfer in devnet.
261// Version 86: Use type tags in the object runtime and adapter instead of `Type`s.
262//             Make variant count limit explicit in protocol config.
263//             Enable party transfer in testnet.
264// Version 87: Enable better type resolution errors in the adapter.
265// Version 88: Update `sui-system` package to use `calculate_rewards` function.
266//             Define the cost for the native Move function `rgp`.
267//             Ignore execution time observations after validator stops accepting certs.
268// Version 89: Add additional signature checks
269//             Add additional linkage checks
270// Version 90: Standard library improvements.
271//             Enable `debug_fatal` on Move invariant violations.
272//             Enable passkey and passkey inside multisig for mainnet.
273// Version 91: Minor changes in Sui Framework. Include CheckpointDigest in consensus dedup key for checkpoint signatures (V2).
274// Version 92: Disable checking shared object transfer restrictions per command = false
275// Version 93: Enable CheckpointDigest in consensus dedup key for checkpoint signatures.
276// Version 94: Decrease stored observations limit by 10% to stay within system object size limit.
277//             Enable party transfer on mainnet.
278// Version 95: Change type name id base cost to 52, increase max transactions per checkpoint to 20000.
279// Version 96: Enable authority capabilities v2.
280//             Fix bug where MFP transaction shared inputs' debts were not loaded
281//             Create Coin Registry object
282//             Enable checkpoint artifacts digest in devnet.
283// Version 97: Enable additional borrow checks
284// Version 98: Add authenticated event streams support via emit_authenticated function.
285//             Add better error messages to the loader.
286// Version 99: Enable new commit handler.
287// Version 100: Framework update
288// Version 101: Framework update
289//              Set max updates per settlement txn to 100.
290// Version 103: Framework update: internal Coin methods
291// Version 104: Framework update: CoinRegistry follow up for Coin methods
292//              Enable all non-zero PCRs parsing for nitro attestation native function in Devnet and Testnet.
293// Version 105: Framework update: address aliases
294//              Enable multi-epoch transaction expiration.
295//              Enable always include required PCRs (0-4 & 8) parsing even if they are zeros for
296//              nitro attestation native function in Devnet and Testnet.
297// Version 106: Framework update: accumulator storage fund calculations
298//              Enable address balances on devnet
299// Version 108: Enable new digit based gas rounding.
300//              Support TxContext in all parameter positions.
301//              Disable entry point signature check.
302//              Enable address aliases on testnet.
303//              Enable poseidon_bn254 on mainnet.
304// Version 109: Update where we set bounds for some binary tables to be a bit more idiomatic.
305// Version 110: Enable parsing on all nonzero custom pcrs in nitro attestation parsing native
306//              function on mainnet.
307//              split_checkpoints_in_consensus_handler in devnet
308//              Enable additional validation on zkLogin public identifier.
309// Version 111: Validator metadata
310// Version 112: Enable Ristretto255 in devnet.
311// Version 113: Validate gas price >= RGP at signing for address balance gas payments.
312// Version 114: Gate seeded test overrides for checkpoint tx limit behind feature flag.
313// Version 115: Gasless transaction drop safety.
314//              Enable address aliases on mainnet.
315//              Relax ValidDuring requirement for transactions with owned inputs.
316// Version 116: Enable Display Registry.
317//              Disable defer_unpaid_amplification (debugging).
318// Version 117: Update Sui System metadata handling.
319// Version 118: Adds `transfer_migration_cap` to display registry
320// Version 119: Enable the new VM.
321// Version 120: Disallow unused jump tables
322// Version 121: Re-enable defer_unpaid_amplification (devnet + testnet).
323// Version 122: Framework update: vector::empty is deprecated.
324//              Enable bulletproofs verification on devnet.
325
326#[derive(Copy, Clone, Debug, Hash, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)]
327pub struct ProtocolVersion(u64);
328
329impl ProtocolVersion {
330    // The minimum and maximum protocol version supported by this binary. Counterintuitively, this constant may
331    // change over time as support for old protocol versions is removed from the source. This
332    // ensures that when a new network (such as a testnet) is created, its genesis committee will
333    // use a protocol version that is actually supported by the binary.
334    pub const MIN: Self = Self(MIN_PROTOCOL_VERSION);
335
336    pub const MAX: Self = Self(MAX_PROTOCOL_VERSION);
337
338    #[cfg(not(msim))]
339    pub const MAX_ALLOWED: Self = Self::MAX;
340
341    // We create one additional "fake" version in simulator builds so that we can test upgrades.
342    #[cfg(msim)]
343    pub const MAX_ALLOWED: Self = Self(MAX_PROTOCOL_VERSION + 1);
344
345    pub fn new(v: u64) -> Self {
346        Self(v)
347    }
348
349    pub const fn as_u64(&self) -> u64 {
350        self.0
351    }
352
353    // For serde deserialization - we don't define a Default impl because there isn't a single
354    // universally appropriate default value.
355    pub fn max() -> Self {
356        Self::MAX
357    }
358
359    pub fn prev(self) -> Self {
360        Self(self.0.checked_sub(1).unwrap())
361    }
362}
363
364impl From<u64> for ProtocolVersion {
365    fn from(v: u64) -> Self {
366        Self::new(v)
367    }
368}
369
370impl std::ops::Sub<u64> for ProtocolVersion {
371    type Output = Self;
372    fn sub(self, rhs: u64) -> Self::Output {
373        Self::new(self.0 - rhs)
374    }
375}
376
377impl std::ops::Add<u64> for ProtocolVersion {
378    type Output = Self;
379    fn add(self, rhs: u64) -> Self::Output {
380        Self::new(self.0 + rhs)
381    }
382}
383
384#[derive(
385    Clone, Serialize, Deserialize, Debug, Default, PartialEq, Copy, PartialOrd, Ord, Eq, ValueEnum,
386)]
387pub enum Chain {
388    Mainnet,
389    Testnet,
390    #[default]
391    Unknown,
392}
393
394impl Chain {
395    pub fn as_str(self) -> &'static str {
396        match self {
397            Chain::Mainnet => "mainnet",
398            Chain::Testnet => "testnet",
399            Chain::Unknown => "unknown",
400        }
401    }
402}
403
404pub struct Error(pub String);
405
406// TODO: There are quite a few non boolean values in the feature flags. We should move them out.
407/// Records on/off feature flags that may vary at each protocol version.
408#[derive(Default, Clone, Serialize, Deserialize, Debug, ProtocolConfigFeatureFlagsGetters)]
409struct FeatureFlags {
410    // Add feature flags here, e.g.:
411    // new_protocol_feature: bool,
412    #[serde(skip_serializing_if = "is_false")]
413    package_upgrades: bool,
414    // If true, validators will commit to the root state digest
415    // in end of epoch checkpoint proposals
416    #[serde(skip_serializing_if = "is_false")]
417    commit_root_state_digest: bool,
418    // Pass epoch start time to advance_epoch safe mode function.
419    #[serde(skip_serializing_if = "is_false")]
420    advance_epoch_start_time_in_safe_mode: bool,
421    // If true, apply the fix to correctly capturing loaded child object versions in execution's
422    // object runtime.
423    #[serde(skip_serializing_if = "is_false")]
424    loaded_child_objects_fixed: bool,
425    // If true, treat missing types in the upgraded modules when creating an upgraded package as a
426    // compatibility error.
427    #[serde(skip_serializing_if = "is_false")]
428    missing_type_is_compatibility_error: bool,
429    // If true, then the scoring decision mechanism will not get disabled when we do have more than
430    // f low scoring authorities, but it will simply flag as low scoring only up to f authorities.
431    #[serde(skip_serializing_if = "is_false")]
432    scoring_decision_with_validity_cutoff: bool,
433
434    // DEPRECATED: this was an ephemeral feature flag only used by consensus handler, which has now
435    // been deployed everywhere.
436    #[serde(skip_serializing_if = "is_false")]
437    consensus_order_end_of_epoch_last: bool,
438
439    // Disallow adding abilities to types during package upgrades.
440    #[serde(skip_serializing_if = "is_false")]
441    disallow_adding_abilities_on_upgrade: bool,
442    // Disables unnecessary invariant check in the Move VM when swapping the value out of a local
443    #[serde(skip_serializing_if = "is_false")]
444    disable_invariant_violation_check_in_swap_loc: bool,
445    // advance to highest supported protocol version at epoch change, instead of the next consecutive
446    // protocol version.
447    #[serde(skip_serializing_if = "is_false")]
448    advance_to_highest_supported_protocol_version: bool,
449    // If true, disallow entry modifiers on entry functions
450    #[serde(skip_serializing_if = "is_false")]
451    ban_entry_init: bool,
452    // If true, hash module bytes individually when calculating package digests for upgrades
453    #[serde(skip_serializing_if = "is_false")]
454    package_digest_hash_module: bool,
455    // If true, disallow changing struct type parameters during package upgrades
456    #[serde(skip_serializing_if = "is_false")]
457    disallow_change_struct_type_params_on_upgrade: bool,
458    // If true, checks no extra bytes in a compiled module
459    #[serde(skip_serializing_if = "is_false")]
460    no_extraneous_module_bytes: bool,
461    // If true, then use the versioned metadata format in narwhal entities.
462    #[serde(skip_serializing_if = "is_false")]
463    narwhal_versioned_metadata: bool,
464
465    // Enable zklogin auth
466    #[serde(skip_serializing_if = "is_false")]
467    zklogin_auth: bool,
468    // How we order transactions coming out of consensus before sending to execution.
469    #[serde(skip_serializing_if = "ConsensusTransactionOrdering::is_none")]
470    consensus_transaction_ordering: ConsensusTransactionOrdering,
471
472    // Previously, the unwrapped_then_deleted field in TransactionEffects makes a distinction between
473    // whether an object has existed in the store previously (i.e. whether there is a tombstone).
474    // Such dependency makes effects generation inefficient, and requires us to include wrapped
475    // tombstone in state root hash.
476    // To prepare for effects V2, with this flag set to true, we simplify the definition of
477    // unwrapped_then_deleted to always include unwrapped then deleted objects,
478    // regardless of their previous state in the store.
479    #[serde(skip_serializing_if = "is_false")]
480    simplified_unwrap_then_delete: bool,
481    // Enable upgraded multisig support
482    #[serde(skip_serializing_if = "is_false")]
483    upgraded_multisig_supported: bool,
484    // If true minimum txn charge is a multiplier of the gas price
485    #[serde(skip_serializing_if = "is_false")]
486    txn_base_cost_as_multiplier: bool,
487
488    // If true, the ability to delete shared objects is in effect
489    #[serde(skip_serializing_if = "is_false")]
490    shared_object_deletion: bool,
491
492    // If true, then the new algorithm for the leader election schedule will be used
493    #[serde(skip_serializing_if = "is_false")]
494    narwhal_new_leader_election_schedule: bool,
495
496    // A list of supported OIDC providers that can be used for zklogin.
497    #[serde(skip_serializing_if = "is_empty")]
498    zklogin_supported_providers: BTreeSet<String>,
499
500    // If true, use the new child object format
501    #[serde(skip_serializing_if = "is_false")]
502    loaded_child_object_format: bool,
503
504    #[serde(skip_serializing_if = "is_false")]
505    enable_jwk_consensus_updates: bool,
506
507    #[serde(skip_serializing_if = "is_false")]
508    end_of_epoch_transaction_supported: bool,
509
510    // Perform simple conservation checks keeping into account out of gas scenarios
511    // while charging for storage.
512    #[serde(skip_serializing_if = "is_false")]
513    simple_conservation_checks: bool,
514
515    // If true, use the new child object format type logging
516    #[serde(skip_serializing_if = "is_false")]
517    loaded_child_object_format_type: bool,
518
519    // Enable receiving sent objects
520    #[serde(skip_serializing_if = "is_false")]
521    receive_objects: bool,
522
523    // If true, include CheckpointDigest in consensus dedup key for checkpoint signatures (V2).
524    #[serde(skip_serializing_if = "is_false")]
525    consensus_checkpoint_signature_key_includes_digest: bool,
526
527    // Enable random beacon protocol
528    #[serde(skip_serializing_if = "is_false")]
529    random_beacon: bool,
530
531    // Enable bridge protocol
532    #[serde(skip_serializing_if = "is_false")]
533    bridge: bool,
534
535    #[serde(skip_serializing_if = "is_false")]
536    enable_effects_v2: bool,
537
538    // If true, then use CertificateV2 in narwhal.
539    #[serde(skip_serializing_if = "is_false")]
540    narwhal_certificate_v2: bool,
541
542    // If true, allow verify with legacy zklogin address
543    #[serde(skip_serializing_if = "is_false")]
544    verify_legacy_zklogin_address: bool,
545
546    // Enable throughput aware consensus submission
547    #[serde(skip_serializing_if = "is_false")]
548    throughput_aware_consensus_submission: bool,
549
550    // If true, recompute has_public_transfer from the type instead of what is stored in the object
551    #[serde(skip_serializing_if = "is_false")]
552    recompute_has_public_transfer_in_execution: bool,
553
554    // If true, multisig containing zkLogin sig is accepted.
555    #[serde(skip_serializing_if = "is_false")]
556    accept_zklogin_in_multisig: bool,
557
558    // If true, multisig containing passkey sig is accepted.
559    #[serde(skip_serializing_if = "is_false")]
560    accept_passkey_in_multisig: bool,
561
562    // If true, additional zkLogin public identifier structure is validated.
563    #[serde(skip_serializing_if = "is_false")]
564    validate_zklogin_public_identifier: bool,
565
566    // If true, consensus prologue transaction also includes the consensus output digest.
567    // It can be used to detect consensus output folk.
568    #[serde(skip_serializing_if = "is_false")]
569    include_consensus_digest_in_prologue: bool,
570
571    // If true, use the hardened OTW check
572    #[serde(skip_serializing_if = "is_false")]
573    hardened_otw_check: bool,
574
575    // If true allow calling receiving_object_id function
576    #[serde(skip_serializing_if = "is_false")]
577    allow_receiving_object_id: bool,
578
579    // Enable the poseidon hash function
580    #[serde(skip_serializing_if = "is_false")]
581    enable_poseidon: bool,
582
583    // If true, enable the coin deny list.
584    #[serde(skip_serializing_if = "is_false")]
585    enable_coin_deny_list: bool,
586
587    // Enable native functions for group operations.
588    #[serde(skip_serializing_if = "is_false")]
589    enable_group_ops_native_functions: bool,
590
591    // Enable native function for msm.
592    #[serde(skip_serializing_if = "is_false")]
593    enable_group_ops_native_function_msm: bool,
594
595    // Enable group operations for Ristretto255
596    #[serde(skip_serializing_if = "is_false")]
597    enable_ristretto255_group_ops: bool,
598
599    // Enable native functions for group operations.
600    #[serde(skip_serializing_if = "is_false")]
601    enable_verify_bulletproofs_ristretto255: bool,
602
603    // Enable nitro attestation.
604    #[serde(skip_serializing_if = "is_false")]
605    enable_nitro_attestation: bool,
606
607    // Enable upgraded parsing of nitro attestation that interprets pcrs as a map.
608    #[serde(skip_serializing_if = "is_false")]
609    enable_nitro_attestation_upgraded_parsing: bool,
610
611    // Enable upgraded parsing of nitro attestation containing all nonzero PCRs.
612    #[serde(skip_serializing_if = "is_false")]
613    enable_nitro_attestation_all_nonzero_pcrs_parsing: bool,
614
615    // Enable upgraded parsing of nitro attestation to always include required PCRs, even when all zeros.
616    #[serde(skip_serializing_if = "is_false")]
617    enable_nitro_attestation_always_include_required_pcrs_parsing: bool,
618
619    // Reject functions with mutable Random.
620    #[serde(skip_serializing_if = "is_false")]
621    reject_mutable_random_on_entry_functions: bool,
622
623    // Controls the behavior of per object congestion control in consensus handler.
624    #[serde(skip_serializing_if = "PerObjectCongestionControlMode::is_none")]
625    per_object_congestion_control_mode: PerObjectCongestionControlMode,
626
627    // The consensus protocol to be used for the epoch.
628    #[serde(skip_serializing_if = "ConsensusChoice::is_narwhal")]
629    consensus_choice: ConsensusChoice,
630
631    // Consensus network to use.
632    #[serde(skip_serializing_if = "ConsensusNetwork::is_anemo")]
633    consensus_network: ConsensusNetwork,
634
635    // If true, use the correct (<=) comparison for max_gas_payment_objects instead of (<)
636    #[serde(skip_serializing_if = "is_false")]
637    correct_gas_payment_limit_check: bool,
638
639    // Set the upper bound allowed for max_epoch in zklogin signature.
640    #[serde(skip_serializing_if = "Option::is_none")]
641    zklogin_max_epoch_upper_bound_delta: Option<u64>,
642
643    // Controls leader scoring & schedule change in Mysticeti consensus.
644    #[serde(skip_serializing_if = "is_false")]
645    mysticeti_leader_scoring_and_schedule: bool,
646
647    // Enable resharing of shared objects using the same initial shared version
648    #[serde(skip_serializing_if = "is_false")]
649    reshare_at_same_initial_version: bool,
650
651    // Resolve Move abort locations to the package id instead of the runtime module ID.
652    #[serde(skip_serializing_if = "is_false")]
653    resolve_abort_locations_to_package_id: bool,
654
655    // Enables the use of the Mysticeti committed sub dag digest to the `ConsensusCommitInfo` in checkpoints.
656    // When disabled the default digest is used instead. It's important to have this guarded behind
657    // a flag as it will lead to checkpoint forks.
658    #[serde(skip_serializing_if = "is_false")]
659    mysticeti_use_committed_subdag_digest: bool,
660
661    // Enable VDF
662    #[serde(skip_serializing_if = "is_false")]
663    enable_vdf: bool,
664
665    // Controls whether consensus handler should record consensus determined shared object version
666    // assignments in consensus commit prologue transaction.
667    // The purpose of doing this is to enable replaying transaction without transaction effects.
668    // V2 also records initial shared versions for consensus objects.
669    #[serde(skip_serializing_if = "is_false")]
670    record_consensus_determined_version_assignments_in_prologue: bool,
671    #[serde(skip_serializing_if = "is_false")]
672    record_consensus_determined_version_assignments_in_prologue_v2: bool,
673
674    // Run verification of framework upgrades using a new/fresh VM.
675    #[serde(skip_serializing_if = "is_false")]
676    fresh_vm_on_framework_upgrade: bool,
677
678    // When set to true, the consensus commit prologue transaction will be placed first
679    // in a consensus commit in checkpoints.
680    // If a checkpoint contains multiple consensus commit, say [cm1][cm2]. The each commit's
681    // consensus commit prologue will be the first transaction in each segment:
682    //     [ccp1, rest cm1][ccp2, rest cm2]
683    // The reason to prepose the prologue transaction is to provide information for transaction
684    // cancellation.
685    #[serde(skip_serializing_if = "is_false")]
686    prepend_prologue_tx_in_consensus_commit_in_checkpoints: bool,
687
688    // Set number of leaders per round for Mysticeti commits.
689    #[serde(skip_serializing_if = "Option::is_none")]
690    mysticeti_num_leaders_per_round: Option<usize>,
691
692    // Enable Soft Bundle (SIP-19).
693    #[serde(skip_serializing_if = "is_false")]
694    soft_bundle: bool,
695
696    // If true, enable the coin deny list V2.
697    #[serde(skip_serializing_if = "is_false")]
698    enable_coin_deny_list_v2: bool,
699
700    // Enable passkey auth (SIP-9)
701    #[serde(skip_serializing_if = "is_false")]
702    passkey_auth: bool,
703
704    // Use AuthorityCapabilitiesV2
705    #[serde(skip_serializing_if = "is_false")]
706    authority_capabilities_v2: bool,
707
708    // Rethrow type layout errors during serialization instead of trying to convert them.
709    #[serde(skip_serializing_if = "is_false")]
710    rethrow_serialization_type_layout_errors: bool,
711
712    // Use distributed vote leader scoring strategy in consensus.
713    #[serde(skip_serializing_if = "is_false")]
714    consensus_distributed_vote_scoring_strategy: bool,
715
716    // Probe rounds received by peers from every authority.
717    #[serde(skip_serializing_if = "is_false")]
718    consensus_round_prober: bool,
719
720    // Validate identifier inputs separately
721    #[serde(skip_serializing_if = "is_false")]
722    validate_identifier_inputs: bool,
723
724    // Disallow self identifier
725    #[serde(skip_serializing_if = "is_false")]
726    disallow_self_identifier: bool,
727
728    // Enables Mysticeti fastpath.
729    #[serde(skip_serializing_if = "is_false")]
730    mysticeti_fastpath: bool,
731
732    // If true, disable pre-consensus locking for owned objects.
733    // All transactions go through consensus, and owned object conflict detection
734    // happens post-consensus via lock acquisition.
735    #[serde(skip_serializing_if = "is_false")]
736    disable_preconsensus_locking: bool,
737
738    // Makes the event's sending module version-aware.
739    #[serde(skip_serializing_if = "is_false")]
740    relocate_event_module: bool,
741
742    // Enable uncompressed group elements in BLS123-81 G1
743    #[serde(skip_serializing_if = "is_false")]
744    uncompressed_g1_group_elements: bool,
745
746    #[serde(skip_serializing_if = "is_false")]
747    disallow_new_modules_in_deps_only_packages: bool,
748
749    // Use smart ancestor selection in consensus.
750    #[serde(skip_serializing_if = "is_false")]
751    consensus_smart_ancestor_selection: bool,
752
753    // Probe accepted rounds in round prober.
754    #[serde(skip_serializing_if = "is_false")]
755    consensus_round_prober_probe_accepted_rounds: bool,
756
757    // Enable v2 native charging for natives.
758    #[serde(skip_serializing_if = "is_false")]
759    native_charging_v2: bool,
760
761    // Enables the new logic for collecting the subdag in the consensus linearizer. The new logic does not stop the recursion at the highest
762    // committed round for each authority, but allows to commit uncommitted blocks up to gc round (excluded) for that authority.
763    #[serde(skip_serializing_if = "is_false")]
764    consensus_linearize_subdag_v2: bool,
765
766    // Properly convert certain type argument errors in the execution layer.
767    #[serde(skip_serializing_if = "is_false")]
768    convert_type_argument_error: bool,
769
770    // Variants count as nodes
771    #[serde(skip_serializing_if = "is_false")]
772    variant_nodes: bool,
773
774    // If true, enable zstd compression for consensus tonic network.
775    #[serde(skip_serializing_if = "is_false")]
776    consensus_zstd_compression: bool,
777
778    // If true, enables the optimizations for child object mutations, removing unnecessary mutations
779    #[serde(skip_serializing_if = "is_false")]
780    minimize_child_object_mutations: bool,
781
782    // If true, record the additional state digest in the consensus commit prologue.
783    #[serde(skip_serializing_if = "is_false")]
784    record_additional_state_digest_in_prologue: bool,
785
786    // If true, enable `TxContext` Move API to go native.
787    #[serde(skip_serializing_if = "is_false")]
788    move_native_context: bool,
789
790    // If true, then it (1) will not enforce monotonicity checks for a block's ancestors and (2) calculates the commit's timestamp based on the
791    // weighted by stake median timestamp of the leader's ancestors.
792    #[serde(skip_serializing_if = "is_false")]
793    consensus_median_based_commit_timestamp: bool,
794
795    // If true, enables the normalization of PTB arguments but does not yet enable splatting
796    // `Result`s of length not equal to 1
797    #[serde(skip_serializing_if = "is_false")]
798    normalize_ptb_arguments: bool,
799
800    // If true, enabled batched block sync in consensus.
801    #[serde(skip_serializing_if = "is_false")]
802    consensus_batched_block_sync: bool,
803
804    // If true, enforces checkpoint timestamps are non-decreasing.
805    #[serde(skip_serializing_if = "is_false")]
806    enforce_checkpoint_timestamp_monotonicity: bool,
807
808    // If true, enables better errors and bounds for max ptb values
809    #[serde(skip_serializing_if = "is_false")]
810    max_ptb_value_size_v2: bool,
811
812    // If true, resolves all type input ids to be defining ID based in the adapter
813    #[serde(skip_serializing_if = "is_false")]
814    resolve_type_input_ids_to_defining_id: bool,
815
816    // Enable native function for party transfer
817    #[serde(skip_serializing_if = "is_false")]
818    enable_party_transfer: bool,
819
820    // Allow objects created or mutated in system transactions to exceed the max object size limit.
821    #[serde(skip_serializing_if = "is_false")]
822    allow_unbounded_system_objects: bool,
823
824    // Signifies the cut-over of using type tags instead of `Type`s in the object runtime.
825    #[serde(skip_serializing_if = "is_false")]
826    type_tags_in_object_runtime: bool,
827
828    // Enable accumulators
829    #[serde(skip_serializing_if = "is_false")]
830    enable_accumulators: bool,
831
832    // Enable coin reservation
833    #[serde(skip_serializing_if = "is_false")]
834    enable_coin_reservation_obj_refs: bool,
835
836    // If true, create the root accumulator object in the change epoch transaction.
837    // This must be enabled and shipped before `enable_accumulators` is set to true.
838    #[serde(skip_serializing_if = "is_false")]
839    create_root_accumulator_object: bool,
840
841    // Enable authenticated event streams
842    #[serde(skip_serializing_if = "is_false")]
843    enable_authenticated_event_streams: bool,
844
845    // Enable address balance gas payments
846    #[serde(skip_serializing_if = "is_false")]
847    enable_address_balance_gas_payments: bool,
848
849    // Validate gas price >= RGP at signing for address balance gas payments
850    #[serde(skip_serializing_if = "is_false")]
851    address_balance_gas_check_rgp_at_signing: bool,
852
853    #[serde(skip_serializing_if = "is_false")]
854    address_balance_gas_reject_gas_coin_arg: bool,
855
856    // Enable multi-epoch transaction expiration (max 1 epoch difference)
857    #[serde(skip_serializing_if = "is_false")]
858    enable_multi_epoch_transaction_expiration: bool,
859
860    // Relax ValidDuring expiration requirement for transactions with owned inputs
861    #[serde(skip_serializing_if = "is_false")]
862    relax_valid_during_for_owned_inputs: bool,
863
864    // Enable statically type checked ptb execution
865    #[serde(skip_serializing_if = "is_false")]
866    enable_ptb_execution_v2: bool,
867
868    // Provide better type resolution errors in the adapter.
869    #[serde(skip_serializing_if = "is_false")]
870    better_adapter_type_resolution_errors: bool,
871
872    // If true, record the time estimate processed in the consensus commit prologue.
873    #[serde(skip_serializing_if = "is_false")]
874    record_time_estimate_processed: bool,
875
876    // If true enable additional linkage checks.
877    #[serde(skip_serializing_if = "is_false")]
878    dependency_linkage_error: bool,
879
880    // If true enable additional multisig checks.
881    #[serde(skip_serializing_if = "is_false")]
882    additional_multisig_checks: bool,
883
884    // If true, ignore execution time observations after certs are closed.
885    #[serde(skip_serializing_if = "is_false")]
886    ignore_execution_time_observations_after_certs_closed: bool,
887
888    // If true use `debug_fatal` to report invariant violations.
889    // `debug_fatal` panics in debug builds and breaks tests/behavior based on older
890    // protocol versions (see make_vec_non_existent_type_v71.move)
891    #[serde(skip_serializing_if = "is_false")]
892    debug_fatal_on_move_invariant_violation: bool,
893
894    // DO NOT ENABLE THIS FOR PRODUCTION NETWORKS. used for testing only.
895    // Allow private accumulator entrypoints
896    #[serde(skip_serializing_if = "is_false")]
897    allow_private_accumulator_entrypoints: bool,
898
899    // If true, include indirect state in the additional consensus digest.
900    #[serde(skip_serializing_if = "is_false")]
901    additional_consensus_digest_indirect_state: bool,
902
903    // Check for `init` for new modules to a package on upgrade.
904    #[serde(skip_serializing_if = "is_false")]
905    check_for_init_during_upgrade: bool,
906
907    // Check shared object transfer restrictions per command.
908    #[serde(skip_serializing_if = "is_false")]
909    per_command_shared_object_transfer_rules: bool,
910
911    // Enable including checkpoint artifacts digest in the summary.
912    #[serde(skip_serializing_if = "is_false")]
913    include_checkpoint_artifacts_digest_in_summary: bool,
914
915    // If true, use MFP txns in load initial object debts.
916    #[serde(skip_serializing_if = "is_false")]
917    use_mfp_txns_in_load_initial_object_debts: bool,
918
919    // If true, cancel randomness-using txns when DKG has failed *before* doing other congestion checks.
920    #[serde(skip_serializing_if = "is_false")]
921    cancel_for_failed_dkg_early: bool,
922
923    // Enable coin registry protocol
924    #[serde(skip_serializing_if = "is_false")]
925    enable_coin_registry: bool,
926
927    // Use abstract size in the object runtime instead the legacy value size.
928    #[serde(skip_serializing_if = "is_false")]
929    abstract_size_in_object_runtime: bool,
930
931    // If true charge for loads into the cache (i.e., fetches from storage) in the object runtime.
932    #[serde(skip_serializing_if = "is_false")]
933    object_runtime_charge_cache_load_gas: bool,
934
935    // If true, perform additional borrow checks
936    #[serde(skip_serializing_if = "is_false")]
937    additional_borrow_checks: bool,
938
939    // If true, use the new commit handler.
940    #[serde(skip_serializing_if = "is_false")]
941    use_new_commit_handler: bool,
942
943    // If true return a better error message when we encounter a loader error.
944    #[serde(skip_serializing_if = "is_false")]
945    better_loader_errors: bool,
946
947    // If true generate layouts for dynamic fields
948    #[serde(skip_serializing_if = "is_false")]
949    generate_df_type_layouts: bool,
950
951    // If true, allow Move functions called in PTBs to return references
952    #[serde(skip_serializing_if = "is_false")]
953    allow_references_in_ptbs: bool,
954
955    // Enable display registry protocol
956    #[serde(skip_serializing_if = "is_false")]
957    enable_display_registry: bool,
958
959    // If true, enable private generics verifier v2
960    #[serde(skip_serializing_if = "is_false")]
961    private_generics_verifier_v2: bool,
962
963    // If true, deprecate global storage ops during Move module deserialization
964    #[serde(skip_serializing_if = "is_false")]
965    deprecate_global_storage_ops_during_deserialization: bool,
966
967    // If true, enable non-exclusive writes for user transactions.
968    // DO NOT ENABLE outside of the transaction test runner.
969    #[serde(skip_serializing_if = "is_false")]
970    enable_non_exclusive_writes: bool,
971
972    // If true, deprecate global storage ops everywhere.
973    #[serde(skip_serializing_if = "is_false")]
974    deprecate_global_storage_ops: bool,
975
976    // If true, normalize depth formula to not be empty for zero depth.
977    #[serde(skip_serializing_if = "is_false")]
978    normalize_depth_formula: bool,
979
980    // If true, skip GC'ed accept votes in CommitFinalizer.
981    #[serde(skip_serializing_if = "is_false")]
982    consensus_skip_gced_accept_votes: bool,
983
984    // If true, include cancelled randomness txns in the consensus commit prologue.
985    #[serde(skip_serializing_if = "is_false")]
986    include_cancelled_randomness_txns_in_prologue: bool,
987
988    // Enables address aliases.
989    #[serde(skip_serializing_if = "is_false")]
990    address_aliases: bool,
991
992    // Corrects signature-to-signer mapping in CheckpointContentsV2.
993    // TODO: remove old code and deprecate once in mainnet.
994    #[serde(skip_serializing_if = "is_false")]
995    fix_checkpoint_signature_mapping: bool,
996
997    // If true, enable object funds withdraw.
998    #[serde(skip_serializing_if = "is_false")]
999    enable_object_funds_withdraw: bool,
1000
1001    // If true, skip GC'ed blocks in direct finalization.
1002    #[serde(skip_serializing_if = "is_false")]
1003    consensus_skip_gced_blocks_in_direct_finalization: bool,
1004
1005    // If true, uses a new rounding mechanism for gas calculations, replacing the step-based one
1006    #[serde(skip_serializing_if = "is_false")]
1007    gas_rounding_halve_digits: bool,
1008
1009    // If true, enable tx contexts in all argument positions
1010    #[serde(skip_serializing_if = "is_false")]
1011    flexible_tx_context_positions: bool,
1012
1013    // If true, disable entry point signature check.
1014    #[serde(skip_serializing_if = "is_false")]
1015    disable_entry_point_signature_check: bool,
1016
1017    // If true, convert withdrawal compatibility PTB arguments to coins at the start of the PTB.
1018    #[serde(skip_serializing_if = "is_false")]
1019    convert_withdrawal_compatibility_ptb_arguments: bool,
1020
1021    // If true, additional restrictions for hot or not entry functions are enforced.
1022    #[serde(skip_serializing_if = "is_false")]
1023    restrict_hot_or_not_entry_functions: bool,
1024
1025    // If true, split checkpoints in consensus handler.
1026    #[serde(skip_serializing_if = "is_false")]
1027    split_checkpoints_in_consensus_handler: bool,
1028
1029    // If true, always accept committed system transactions.
1030    #[serde(skip_serializing_if = "is_false")]
1031    consensus_always_accept_system_transactions: bool,
1032
1033    // If true perform consistent verification of metadata
1034    #[serde(skip_serializing_if = "is_false")]
1035    validator_metadata_verify_v2: bool,
1036
1037    // If true, defer transactions with unpaid consensus amplification
1038    // (where duplicate count exceeds gas_price / RGP + 1)
1039    #[serde(skip_serializing_if = "is_false")]
1040    defer_unpaid_amplification: bool,
1041
1042    #[serde(skip_serializing_if = "is_false")]
1043    randomize_checkpoint_tx_limit_in_tests: bool,
1044
1045    // If true, mark the gas coin as uninitialized in drop safety when there is no gas coin.
1046    #[serde(skip_serializing_if = "is_false")]
1047    gasless_transaction_drop_safety: bool,
1048
1049    // When split-checkpoints enabled, merge randomness and non-randomness schedulables together.
1050    #[serde(skip_serializing_if = "is_false")]
1051    merge_randomness_into_checkpoint: bool,
1052
1053    // If true, use coin party owner information.
1054    #[serde(skip_serializing_if = "is_false")]
1055    use_coin_party_owner: bool,
1056
1057    #[serde(skip_serializing_if = "is_false")]
1058    enable_gasless: bool,
1059
1060    #[serde(skip_serializing_if = "is_false")]
1061    gasless_verify_remaining_balance: bool,
1062
1063    #[serde(skip_serializing_if = "is_false")]
1064    disallow_jump_orphans: bool,
1065
1066    // If true, return early on type mismatch in receive_object.
1067    #[serde(skip_serializing_if = "is_false")]
1068    early_return_receive_object_mismatched_type: bool,
1069}
1070
1071fn is_false(b: &bool) -> bool {
1072    !b
1073}
1074
1075fn is_empty(b: &BTreeSet<String>) -> bool {
1076    b.is_empty()
1077}
1078
1079fn is_zero(val: &u64) -> bool {
1080    *val == 0
1081}
1082
1083/// Ordering mechanism for transactions in one Narwhal consensus output.
1084#[derive(Default, Copy, Clone, PartialEq, Eq, Serialize, Deserialize, Debug)]
1085pub enum ConsensusTransactionOrdering {
1086    /// No ordering. Transactions are processed in the order they appear in the consensus output.
1087    #[default]
1088    None,
1089    /// Order transactions by gas price, highest first.
1090    ByGasPrice,
1091}
1092
1093impl ConsensusTransactionOrdering {
1094    pub fn is_none(&self) -> bool {
1095        matches!(self, ConsensusTransactionOrdering::None)
1096    }
1097}
1098
1099#[derive(Default, Copy, Clone, PartialEq, Eq, Serialize, Deserialize, Debug)]
1100pub struct ExecutionTimeEstimateParams {
1101    // Targeted per-object utilization as an integer percentage (1-100).
1102    pub target_utilization: u64,
1103    // Schedule up to this much extra work (in microseconds) per object,
1104    // but don't allow more than a single transaction to exceed this
1105    // burst limit.
1106    pub allowed_txn_cost_overage_burst_limit_us: u64,
1107
1108    // For separate budget for randomness-using tx, the above limits are
1109    // used with this integer-percentage scaling factor (1-100).
1110    pub randomness_scalar: u64,
1111
1112    // Absolute maximum allowed transaction duration estimate (in microseconds).
1113    pub max_estimate_us: u64,
1114
1115    // Number of the final checkpoints in an epoch whose observations should be
1116    // stored for use in the next epoch.
1117    pub stored_observations_num_included_checkpoints: u64,
1118
1119    // Absolute limit on the number of saved observations at end of epoch.
1120    pub stored_observations_limit: u64,
1121
1122    // Requires observations from at least this amount of stake in order to use
1123    // observation-based execution time estimates instead of the default.
1124    #[serde(skip_serializing_if = "is_zero")]
1125    pub stake_weighted_median_threshold: u64,
1126
1127    // For backwards compatibility with old behavior we use a zero default duration when adding
1128    // new execution time observation keys and a zero generation when loading stored observations.
1129    // This can be removed once set to "true" on mainnet.
1130    #[serde(skip_serializing_if = "is_false")]
1131    pub default_none_duration_for_new_keys: bool,
1132
1133    // Number of observations per chunk. When None, chunking is disabled.
1134    #[serde(skip_serializing_if = "Option::is_none")]
1135    pub observations_chunk_size: Option<u64>,
1136}
1137
1138// The config for per object congestion control in consensus handler.
1139#[derive(Default, Copy, Clone, PartialEq, Eq, Serialize, Deserialize, Debug)]
1140pub enum PerObjectCongestionControlMode {
1141    #[default]
1142    None, // Deprecated.
1143    TotalGasBudget,                                     // Deprecated.
1144    TotalTxCount,                                       // Deprecated.
1145    TotalGasBudgetWithCap,                              // Deprecated.
1146    ExecutionTimeEstimate(ExecutionTimeEstimateParams), // Use execution time estimate as execution cost.
1147}
1148
1149impl PerObjectCongestionControlMode {
1150    pub fn is_none(&self) -> bool {
1151        matches!(self, PerObjectCongestionControlMode::None)
1152    }
1153}
1154
1155// Configuration options for consensus algorithm.
1156#[derive(Default, Copy, Clone, PartialEq, Eq, Serialize, Deserialize, Debug)]
1157pub enum ConsensusChoice {
1158    #[default]
1159    Narwhal,
1160    SwapEachEpoch,
1161    Mysticeti,
1162}
1163
1164impl ConsensusChoice {
1165    pub fn is_narwhal(&self) -> bool {
1166        matches!(self, ConsensusChoice::Narwhal)
1167    }
1168}
1169
1170// Configuration options for consensus network.
1171#[derive(Default, Copy, Clone, PartialEq, Eq, Serialize, Deserialize, Debug)]
1172pub enum ConsensusNetwork {
1173    #[default]
1174    Anemo,
1175    Tonic,
1176}
1177
1178impl ConsensusNetwork {
1179    pub fn is_anemo(&self) -> bool {
1180        matches!(self, ConsensusNetwork::Anemo)
1181    }
1182}
1183
1184/// Constants that change the behavior of the protocol.
1185///
1186/// The value of each constant here must be fixed for a given protocol version. To change the value
1187/// of a constant, advance the protocol version, and add support for it in `get_for_version` under
1188/// the new version number.
1189/// (below).
1190///
1191/// To add a new field to this struct, use the following procedure:
1192/// - Advance the protocol version.
1193/// - Add the field as a private `Option<T>` to the struct.
1194/// - Initialize the field to `None` in prior protocol versions.
1195/// - Initialize the field to `Some(val)` for your new protocol version.
1196/// - Add a public getter that simply unwraps the field.
1197/// - Two public getters of the form `field(&self) -> field_type`
1198///     and `field_as_option(&self) -> Option<field_type>` will be automatically generated for you.
1199/// Example for a field: `new_constant: Option<u64>`
1200/// ```rust,ignore
1201///      pub fn new_constant(&self) -> u64 {
1202///         self.new_constant.expect(Self::CONSTANT_ERR_MSG)
1203///     }
1204///      pub fn new_constant_as_option(&self) -> Option<u64> {
1205///         self.new_constant.expect(Self::CONSTANT_ERR_MSG)
1206///     }
1207/// ```
1208/// With `pub fn new_constant(&self) -> u64`, if the constant is accessed in a protocol version
1209/// in which it is not defined, the validator will crash. (Crashing is necessary because
1210/// this type of error would almost always result in forking if not prevented here).
1211/// If you don't want the validator to crash, you can use the
1212/// `pub fn new_constant_as_option(&self) -> Option<u64>` getter, which will
1213/// return `None` if the field is not defined at that version.
1214/// - If you want a customized getter, you can add a method in the impl.
1215#[skip_serializing_none]
1216#[derive(Clone, Serialize, Debug, ProtocolConfigAccessors, ProtocolConfigOverride)]
1217pub struct ProtocolConfig {
1218    pub version: ProtocolVersion,
1219
1220    feature_flags: FeatureFlags,
1221
1222    // ==== Transaction input limits ====
1223    /// Maximum serialized size of a transaction (in bytes).
1224    max_tx_size_bytes: Option<u64>,
1225
1226    /// Maximum number of input objects to a transaction. Enforced by the transaction input checker
1227    max_input_objects: Option<u64>,
1228
1229    /// Max size of objects a transaction can write to disk after completion. Enforce by the Sui adapter.
1230    /// This is the sum of the serialized size of all objects written to disk.
1231    /// The max size of individual objects on the other hand is `max_move_object_size`.
1232    max_size_written_objects: Option<u64>,
1233    /// Max size of objects a system transaction can write to disk after completion. Enforce by the Sui adapter.
1234    /// Similar to `max_size_written_objects` but for system transactions.
1235    max_size_written_objects_system_tx: Option<u64>,
1236
1237    /// Maximum size of serialized transaction effects.
1238    max_serialized_tx_effects_size_bytes: Option<u64>,
1239
1240    /// Maximum size of serialized transaction effects for system transactions.
1241    max_serialized_tx_effects_size_bytes_system_tx: Option<u64>,
1242
1243    /// Maximum number of gas payment objects for a transaction.
1244    max_gas_payment_objects: Option<u32>,
1245
1246    /// Maximum number of modules in a Publish transaction.
1247    max_modules_in_publish: Option<u32>,
1248
1249    /// Maximum number of transitive dependencies in a package when publishing.
1250    max_package_dependencies: Option<u32>,
1251
1252    /// Maximum number of arguments in a move call or a ProgrammableTransaction's
1253    /// TransferObjects command.
1254    max_arguments: Option<u32>,
1255
1256    /// Maximum number of total type arguments, computed recursively.
1257    max_type_arguments: Option<u32>,
1258
1259    /// Maximum depth of an individual type argument.
1260    max_type_argument_depth: Option<u32>,
1261
1262    /// Maximum size of a Pure CallArg.
1263    max_pure_argument_size: Option<u32>,
1264
1265    /// Maximum number of Commands in a ProgrammableTransaction.
1266    max_programmable_tx_commands: Option<u32>,
1267
1268    // ==== Move VM, Move bytecode verifier, and execution limits ===
1269    /// Maximum Move bytecode version the VM understands. All older versions are accepted.
1270    move_binary_format_version: Option<u32>,
1271    min_move_binary_format_version: Option<u32>,
1272
1273    /// Configuration controlling binary tables size.
1274    binary_module_handles: Option<u16>,
1275    binary_struct_handles: Option<u16>,
1276    binary_function_handles: Option<u16>,
1277    binary_function_instantiations: Option<u16>,
1278    binary_signatures: Option<u16>,
1279    binary_constant_pool: Option<u16>,
1280    binary_identifiers: Option<u16>,
1281    binary_address_identifiers: Option<u16>,
1282    binary_struct_defs: Option<u16>,
1283    binary_struct_def_instantiations: Option<u16>,
1284    binary_function_defs: Option<u16>,
1285    binary_field_handles: Option<u16>,
1286    binary_field_instantiations: Option<u16>,
1287    binary_friend_decls: Option<u16>,
1288    binary_enum_defs: Option<u16>,
1289    binary_enum_def_instantiations: Option<u16>,
1290    binary_variant_handles: Option<u16>,
1291    binary_variant_instantiation_handles: Option<u16>,
1292
1293    /// Maximum size of the `contents` part of an object, in bytes. Enforced by the Sui adapter when effects are produced.
1294    max_move_object_size: Option<u64>,
1295
1296    // TODO: Option<increase to 500 KB. currently, publishing a package > 500 KB exceeds the max computation gas cost
1297    /// Maximum size of a Move package object, in bytes. Enforced by the Sui adapter at the end of a publish transaction.
1298    max_move_package_size: Option<u64>,
1299
1300    /// Max number of publish or upgrade commands allowed in a programmable transaction block.
1301    max_publish_or_upgrade_per_ptb: Option<u64>,
1302
1303    /// Maximum gas budget in MIST that a transaction can use.
1304    max_tx_gas: Option<u64>,
1305
1306    /// Maximum amount of the proposed gas price in MIST (defined in the transaction).
1307    max_gas_price: Option<u64>,
1308
1309    /// For aborted txns, we cap the gas price at a factor of RGP. This lowers risk of setting higher priority gas price
1310    /// if there's a chance the txn will abort.
1311    max_gas_price_rgp_factor_for_aborted_transactions: Option<u64>,
1312
1313    /// The max computation bucket for gas. This is the max that can be charged for computation.
1314    max_gas_computation_bucket: Option<u64>,
1315
1316    // Define the value used to round up computation gas charges
1317    gas_rounding_step: Option<u64>,
1318
1319    /// Maximum number of nested loops. Enforced by the Move bytecode verifier.
1320    max_loop_depth: Option<u64>,
1321
1322    /// Maximum number of type arguments that can be bound to generic type parameters. Enforced by the Move bytecode verifier.
1323    max_generic_instantiation_length: Option<u64>,
1324
1325    /// Maximum number of parameters that a Move function can have. Enforced by the Move bytecode verifier.
1326    max_function_parameters: Option<u64>,
1327
1328    /// Maximum number of basic blocks that a Move function can have. Enforced by the Move bytecode verifier.
1329    max_basic_blocks: Option<u64>,
1330
1331    /// Maximum stack size value. Enforced by the Move bytecode verifier.
1332    max_value_stack_size: Option<u64>,
1333
1334    /// Maximum number of "type nodes", a metric for how big a SignatureToken will be when expanded into a fully qualified type. Enforced by the Move bytecode verifier.
1335    max_type_nodes: Option<u64>,
1336
1337    /// Maximum number of push instructions in one function. Enforced by the Move bytecode verifier.
1338    max_push_size: Option<u64>,
1339
1340    /// Maximum number of struct definitions in a module. Enforced by the Move bytecode verifier.
1341    max_struct_definitions: Option<u64>,
1342
1343    /// Maximum number of function definitions in a module. Enforced by the Move bytecode verifier.
1344    max_function_definitions: Option<u64>,
1345
1346    /// Maximum number of fields allowed in a struct definition. Enforced by the Move bytecode verifier.
1347    max_fields_in_struct: Option<u64>,
1348
1349    /// Maximum dependency depth. Enforced by the Move linker when loading dependent modules.
1350    max_dependency_depth: Option<u64>,
1351
1352    /// Maximum number of Move events that a single transaction can emit. Enforced by the VM during execution.
1353    max_num_event_emit: Option<u64>,
1354
1355    /// Maximum number of new IDs that a single transaction can create. Enforced by the VM during execution.
1356    max_num_new_move_object_ids: Option<u64>,
1357
1358    /// Maximum number of new IDs that a single system transaction can create. Enforced by the VM during execution.
1359    max_num_new_move_object_ids_system_tx: Option<u64>,
1360
1361    /// Maximum number of IDs that a single transaction can delete. Enforced by the VM during execution.
1362    max_num_deleted_move_object_ids: Option<u64>,
1363
1364    /// Maximum number of IDs that a single system transaction can delete. Enforced by the VM during execution.
1365    max_num_deleted_move_object_ids_system_tx: Option<u64>,
1366
1367    /// Maximum number of IDs that a single transaction can transfer. Enforced by the VM during execution.
1368    max_num_transferred_move_object_ids: Option<u64>,
1369
1370    /// Maximum number of IDs that a single system transaction can transfer. Enforced by the VM during execution.
1371    max_num_transferred_move_object_ids_system_tx: Option<u64>,
1372
1373    /// Maximum size of a Move user event. Enforced by the VM during execution.
1374    max_event_emit_size: Option<u64>,
1375
1376    /// Maximum size of a Move user event. Enforced by the VM during execution.
1377    max_event_emit_size_total: Option<u64>,
1378
1379    /// Maximum length of a vector in Move. Enforced by the VM during execution, and for constants, by the verifier.
1380    max_move_vector_len: Option<u64>,
1381
1382    /// Maximum length of an `Identifier` in Move. Enforced by the bytecode verifier at signing.
1383    max_move_identifier_len: Option<u64>,
1384
1385    /// Maximum depth of a Move value within the VM.
1386    max_move_value_depth: Option<u64>,
1387
1388    /// Maximum number of variants in an enum. Enforced by the bytecode verifier at signing.
1389    max_move_enum_variants: Option<u64>,
1390
1391    /// Maximum number of back edges in Move function. Enforced by the bytecode verifier at signing.
1392    max_back_edges_per_function: Option<u64>,
1393
1394    /// Maximum number of back edges in Move module. Enforced by the bytecode verifier at signing.
1395    max_back_edges_per_module: Option<u64>,
1396
1397    /// Maximum number of meter `ticks` spent verifying a Move function. Enforced by the bytecode verifier at signing.
1398    max_verifier_meter_ticks_per_function: Option<u64>,
1399
1400    /// Maximum number of meter `ticks` spent verifying a Move module. Enforced by the bytecode verifier at signing.
1401    max_meter_ticks_per_module: Option<u64>,
1402
1403    /// Maximum number of meter `ticks` spent verifying a Move package. Enforced by the bytecode verifier at signing.
1404    max_meter_ticks_per_package: Option<u64>,
1405
1406    // === Object runtime internal operation limits ====
1407    // These affect dynamic fields
1408    /// Maximum number of cached objects in the object runtime ObjectStore. Enforced by object runtime during execution
1409    object_runtime_max_num_cached_objects: Option<u64>,
1410
1411    /// Maximum number of cached objects in the object runtime ObjectStore in system transaction. Enforced by object runtime during execution
1412    object_runtime_max_num_cached_objects_system_tx: Option<u64>,
1413
1414    /// Maximum number of stored objects accessed by object runtime ObjectStore. Enforced by object runtime during execution
1415    object_runtime_max_num_store_entries: Option<u64>,
1416
1417    /// Maximum number of stored objects accessed by object runtime ObjectStore in system transaction. Enforced by object runtime during execution
1418    object_runtime_max_num_store_entries_system_tx: Option<u64>,
1419
1420    // === Execution gas costs ====
1421    /// Base cost for any Sui transaction
1422    base_tx_cost_fixed: Option<u64>,
1423
1424    /// Additional cost for a transaction that publishes a package
1425    /// i.e., the base cost of such a transaction is base_tx_cost_fixed + package_publish_cost_fixed
1426    package_publish_cost_fixed: Option<u64>,
1427
1428    /// Cost per byte of a Move call transaction
1429    /// i.e., the cost of such a transaction is base_cost + (base_tx_cost_per_byte * size)
1430    base_tx_cost_per_byte: Option<u64>,
1431
1432    /// Cost per byte for a transaction that publishes a package
1433    package_publish_cost_per_byte: Option<u64>,
1434
1435    // Per-byte cost of reading an object during transaction execution
1436    obj_access_cost_read_per_byte: Option<u64>,
1437
1438    // Per-byte cost of writing an object during transaction execution
1439    obj_access_cost_mutate_per_byte: Option<u64>,
1440
1441    // Per-byte cost of deleting an object during transaction execution
1442    obj_access_cost_delete_per_byte: Option<u64>,
1443
1444    /// Per-byte cost charged for each input object to a transaction.
1445    /// Meant to approximate the cost of checking locks for each object
1446    // TODO: Option<I'm not sure that this cost makes sense. Checking locks is "free"
1447    // in the sense that an invalid tx that can never be committed/pay gas can
1448    // force validators to check an arbitrary number of locks. If those checks are
1449    // "free" for invalid transactions, why charge for them in valid transactions
1450    // TODO: Option<if we keep this, I think we probably want it to be a fixed cost rather
1451    // than a per-byte cost. checking an object lock should not require loading an
1452    // entire object, just consulting an ID -> tx digest map
1453    obj_access_cost_verify_per_byte: Option<u64>,
1454
1455    // Maximal nodes which are allowed when converting to a type layout.
1456    max_type_to_layout_nodes: Option<u64>,
1457
1458    // Maximal size in bytes that a PTB value can be
1459    max_ptb_value_size: Option<u64>,
1460
1461    // === Gas version. gas model ===
1462    /// Gas model version, what code we are using to charge gas
1463    gas_model_version: Option<u64>,
1464
1465    // === Storage gas costs ===
1466    /// Per-byte cost of storing an object in the Sui global object store. Some of this cost may be refundable if the object is later freed
1467    obj_data_cost_refundable: Option<u64>,
1468
1469    // Per-byte cost of storing an object in the Sui transaction log (e.g., in CertifiedTransactionEffects)
1470    // This depends on the size of various fields including the effects
1471    // TODO: Option<I don't fully understand this^ and more details would be useful
1472    obj_metadata_cost_non_refundable: Option<u64>,
1473
1474    // === Tokenomics ===
1475
1476    // TODO: Option<this should be changed to u64.
1477    /// Sender of a txn that touches an object will get this percent of the storage rebate back.
1478    /// In basis point.
1479    storage_rebate_rate: Option<u64>,
1480
1481    /// 5% of the storage fund's share of rewards are reinvested into the storage fund.
1482    /// In basis point.
1483    storage_fund_reinvest_rate: Option<u64>,
1484
1485    /// The share of rewards that will be slashed and redistributed is 50%.
1486    /// In basis point.
1487    reward_slashing_rate: Option<u64>,
1488
1489    /// Unit gas price, Mist per internal gas unit.
1490    storage_gas_price: Option<u64>,
1491
1492    /// Per-object storage cost for accumulator objects, used during end-of-epoch accounting.
1493    accumulator_object_storage_cost: Option<u64>,
1494
1495    // === Core Protocol ===
1496    /// Max number of transactions per checkpoint.
1497    /// Note that this is a protocol constant and not a config as validators must have this set to
1498    /// the same value, otherwise they *will* fork.
1499    max_transactions_per_checkpoint: Option<u64>,
1500
1501    /// Max size of a checkpoint in bytes.
1502    /// Note that this is a protocol constant and not a config as validators must have this set to
1503    /// the same value, otherwise they *will* fork.
1504    max_checkpoint_size_bytes: Option<u64>,
1505
1506    /// A protocol upgrade always requires 2f+1 stake to agree. We support a buffer of additional
1507    /// stake (as a fraction of f, expressed in basis points) that is required before an upgrade
1508    /// can happen automatically. 10000bps would indicate that complete unanimity is required (all
1509    /// 3f+1 must vote), while 0bps would indicate that 2f+1 is sufficient.
1510    buffer_stake_for_protocol_upgrade_bps: Option<u64>,
1511
1512    // === Native Function Costs ===
1513
1514    // `address` module
1515    // Cost params for the Move native function `address::from_bytes(bytes: vector<u8>)`
1516    address_from_bytes_cost_base: Option<u64>,
1517    // Cost params for the Move native function `address::to_u256(address): u256`
1518    address_to_u256_cost_base: Option<u64>,
1519    // Cost params for the Move native function `address::from_u256(u256): address`
1520    address_from_u256_cost_base: Option<u64>,
1521
1522    // `config` module
1523    // Cost params for the Move native function `read_setting_impl<Name: copy + drop + store,
1524    // SettingValue: key + store, SettingDataValue: store, Value: copy + drop + store,
1525    // >(config: address, name: address, current_epoch: u64): Option<Value>`
1526    config_read_setting_impl_cost_base: Option<u64>,
1527    config_read_setting_impl_cost_per_byte: Option<u64>,
1528
1529    // `dynamic_field` module
1530    // Cost params for the Move native function `hash_type_and_key<K: copy + drop + store>(parent: address, k: K): address`
1531    dynamic_field_hash_type_and_key_cost_base: Option<u64>,
1532    dynamic_field_hash_type_and_key_type_cost_per_byte: Option<u64>,
1533    dynamic_field_hash_type_and_key_value_cost_per_byte: Option<u64>,
1534    dynamic_field_hash_type_and_key_type_tag_cost_per_byte: Option<u64>,
1535    // Cost params for the Move native function `add_child_object<Child: key>(parent: address, child: Child)`
1536    dynamic_field_add_child_object_cost_base: Option<u64>,
1537    dynamic_field_add_child_object_type_cost_per_byte: Option<u64>,
1538    dynamic_field_add_child_object_value_cost_per_byte: Option<u64>,
1539    dynamic_field_add_child_object_struct_tag_cost_per_byte: Option<u64>,
1540    // Cost params for the Move native function `borrow_child_object_mut<Child: key>(parent: &mut UID, id: address): &mut Child`
1541    dynamic_field_borrow_child_object_cost_base: Option<u64>,
1542    dynamic_field_borrow_child_object_child_ref_cost_per_byte: Option<u64>,
1543    dynamic_field_borrow_child_object_type_cost_per_byte: Option<u64>,
1544    // Cost params for the Move native function `remove_child_object<Child: key>(parent: address, id: address): Child`
1545    dynamic_field_remove_child_object_cost_base: Option<u64>,
1546    dynamic_field_remove_child_object_child_cost_per_byte: Option<u64>,
1547    dynamic_field_remove_child_object_type_cost_per_byte: Option<u64>,
1548    // Cost params for the Move native function `has_child_object(parent: address, id: address): bool`
1549    dynamic_field_has_child_object_cost_base: Option<u64>,
1550    // Cost params for the Move native function `has_child_object_with_ty<Child: key>(parent: address, id: address): bool`
1551    dynamic_field_has_child_object_with_ty_cost_base: Option<u64>,
1552    dynamic_field_has_child_object_with_ty_type_cost_per_byte: Option<u64>,
1553    dynamic_field_has_child_object_with_ty_type_tag_cost_per_byte: Option<u64>,
1554
1555    // `event` module
1556    // Cost params for the Move native function `event::emit<T: copy + drop>(event: T)`
1557    event_emit_cost_base: Option<u64>,
1558    event_emit_value_size_derivation_cost_per_byte: Option<u64>,
1559    event_emit_tag_size_derivation_cost_per_byte: Option<u64>,
1560    event_emit_output_cost_per_byte: Option<u64>,
1561    event_emit_auth_stream_cost: Option<u64>,
1562
1563    //  `object` module
1564    // Cost params for the Move native function `borrow_uid<T: key>(obj: &T): &UID`
1565    object_borrow_uid_cost_base: Option<u64>,
1566    // Cost params for the Move native function `delete_impl(id: address)`
1567    object_delete_impl_cost_base: Option<u64>,
1568    // Cost params for the Move native function `record_new_uid(id: address)`
1569    object_record_new_uid_cost_base: Option<u64>,
1570
1571    // Transfer
1572    // Cost params for the Move native function `transfer_impl<T: key>(obj: T, recipient: address)`
1573    transfer_transfer_internal_cost_base: Option<u64>,
1574    // Cost params for the Move native function `party_transfer_impl<T: key>(obj: T, party_members: vector<address>)`
1575    transfer_party_transfer_internal_cost_base: Option<u64>,
1576    // Cost params for the Move native function `freeze_object<T: key>(obj: T)`
1577    transfer_freeze_object_cost_base: Option<u64>,
1578    // Cost params for the Move native function `share_object<T: key>(obj: T)`
1579    transfer_share_object_cost_base: Option<u64>,
1580    // Cost params for the Move native function
1581    // `receive_object<T: key>(p: &mut UID, recv: Receiving<T>T)`
1582    transfer_receive_object_cost_base: Option<u64>,
1583    transfer_receive_object_cost_per_byte: Option<u64>,
1584    transfer_receive_object_type_cost_per_byte: Option<u64>,
1585
1586    // TxContext
1587    // Cost params for the Move native function `transfer_impl<T: key>(obj: T, recipient: address)`
1588    tx_context_derive_id_cost_base: Option<u64>,
1589    tx_context_fresh_id_cost_base: Option<u64>,
1590    tx_context_sender_cost_base: Option<u64>,
1591    tx_context_epoch_cost_base: Option<u64>,
1592    tx_context_epoch_timestamp_ms_cost_base: Option<u64>,
1593    tx_context_sponsor_cost_base: Option<u64>,
1594    tx_context_rgp_cost_base: Option<u64>,
1595    tx_context_gas_price_cost_base: Option<u64>,
1596    tx_context_gas_budget_cost_base: Option<u64>,
1597    tx_context_ids_created_cost_base: Option<u64>,
1598    tx_context_replace_cost_base: Option<u64>,
1599
1600    // Types
1601    // Cost params for the Move native function `is_one_time_witness<T: drop>(_: &T): bool`
1602    types_is_one_time_witness_cost_base: Option<u64>,
1603    types_is_one_time_witness_type_tag_cost_per_byte: Option<u64>,
1604    types_is_one_time_witness_type_cost_per_byte: Option<u64>,
1605
1606    // Validator
1607    // Cost params for the Move native function `validate_metadata_bcs(metadata: vector<u8>)`
1608    validator_validate_metadata_cost_base: Option<u64>,
1609    validator_validate_metadata_data_cost_per_byte: Option<u64>,
1610
1611    // Crypto natives
1612    crypto_invalid_arguments_cost: Option<u64>,
1613    // bls12381::bls12381_min_sig_verify
1614    bls12381_bls12381_min_sig_verify_cost_base: Option<u64>,
1615    bls12381_bls12381_min_sig_verify_msg_cost_per_byte: Option<u64>,
1616    bls12381_bls12381_min_sig_verify_msg_cost_per_block: Option<u64>,
1617
1618    // bls12381::bls12381_min_pk_verify
1619    bls12381_bls12381_min_pk_verify_cost_base: Option<u64>,
1620    bls12381_bls12381_min_pk_verify_msg_cost_per_byte: Option<u64>,
1621    bls12381_bls12381_min_pk_verify_msg_cost_per_block: Option<u64>,
1622
1623    // ecdsa_k1::ecrecover
1624    ecdsa_k1_ecrecover_keccak256_cost_base: Option<u64>,
1625    ecdsa_k1_ecrecover_keccak256_msg_cost_per_byte: Option<u64>,
1626    ecdsa_k1_ecrecover_keccak256_msg_cost_per_block: Option<u64>,
1627    ecdsa_k1_ecrecover_sha256_cost_base: Option<u64>,
1628    ecdsa_k1_ecrecover_sha256_msg_cost_per_byte: Option<u64>,
1629    ecdsa_k1_ecrecover_sha256_msg_cost_per_block: Option<u64>,
1630
1631    // ecdsa_k1::decompress_pubkey
1632    ecdsa_k1_decompress_pubkey_cost_base: Option<u64>,
1633
1634    // ecdsa_k1::secp256k1_verify
1635    ecdsa_k1_secp256k1_verify_keccak256_cost_base: Option<u64>,
1636    ecdsa_k1_secp256k1_verify_keccak256_msg_cost_per_byte: Option<u64>,
1637    ecdsa_k1_secp256k1_verify_keccak256_msg_cost_per_block: Option<u64>,
1638    ecdsa_k1_secp256k1_verify_sha256_cost_base: Option<u64>,
1639    ecdsa_k1_secp256k1_verify_sha256_msg_cost_per_byte: Option<u64>,
1640    ecdsa_k1_secp256k1_verify_sha256_msg_cost_per_block: Option<u64>,
1641
1642    // ecdsa_r1::ecrecover
1643    ecdsa_r1_ecrecover_keccak256_cost_base: Option<u64>,
1644    ecdsa_r1_ecrecover_keccak256_msg_cost_per_byte: Option<u64>,
1645    ecdsa_r1_ecrecover_keccak256_msg_cost_per_block: Option<u64>,
1646    ecdsa_r1_ecrecover_sha256_cost_base: Option<u64>,
1647    ecdsa_r1_ecrecover_sha256_msg_cost_per_byte: Option<u64>,
1648    ecdsa_r1_ecrecover_sha256_msg_cost_per_block: Option<u64>,
1649
1650    // ecdsa_r1::secp256k1_verify
1651    ecdsa_r1_secp256r1_verify_keccak256_cost_base: Option<u64>,
1652    ecdsa_r1_secp256r1_verify_keccak256_msg_cost_per_byte: Option<u64>,
1653    ecdsa_r1_secp256r1_verify_keccak256_msg_cost_per_block: Option<u64>,
1654    ecdsa_r1_secp256r1_verify_sha256_cost_base: Option<u64>,
1655    ecdsa_r1_secp256r1_verify_sha256_msg_cost_per_byte: Option<u64>,
1656    ecdsa_r1_secp256r1_verify_sha256_msg_cost_per_block: Option<u64>,
1657
1658    // ecvrf::verify
1659    ecvrf_ecvrf_verify_cost_base: Option<u64>,
1660    ecvrf_ecvrf_verify_alpha_string_cost_per_byte: Option<u64>,
1661    ecvrf_ecvrf_verify_alpha_string_cost_per_block: Option<u64>,
1662
1663    // ed25519
1664    ed25519_ed25519_verify_cost_base: Option<u64>,
1665    ed25519_ed25519_verify_msg_cost_per_byte: Option<u64>,
1666    ed25519_ed25519_verify_msg_cost_per_block: Option<u64>,
1667
1668    // groth16::prepare_verifying_key
1669    groth16_prepare_verifying_key_bls12381_cost_base: Option<u64>,
1670    groth16_prepare_verifying_key_bn254_cost_base: Option<u64>,
1671
1672    // groth16::verify_groth16_proof_internal
1673    groth16_verify_groth16_proof_internal_bls12381_cost_base: Option<u64>,
1674    groth16_verify_groth16_proof_internal_bls12381_cost_per_public_input: Option<u64>,
1675    groth16_verify_groth16_proof_internal_bn254_cost_base: Option<u64>,
1676    groth16_verify_groth16_proof_internal_bn254_cost_per_public_input: Option<u64>,
1677    groth16_verify_groth16_proof_internal_public_input_cost_per_byte: Option<u64>,
1678
1679    // hash::blake2b256
1680    hash_blake2b256_cost_base: Option<u64>,
1681    hash_blake2b256_data_cost_per_byte: Option<u64>,
1682    hash_blake2b256_data_cost_per_block: Option<u64>,
1683
1684    // hash::keccak256
1685    hash_keccak256_cost_base: Option<u64>,
1686    hash_keccak256_data_cost_per_byte: Option<u64>,
1687    hash_keccak256_data_cost_per_block: Option<u64>,
1688
1689    // poseidon::poseidon_bn254
1690    poseidon_bn254_cost_base: Option<u64>,
1691    poseidon_bn254_cost_per_block: Option<u64>,
1692
1693    // group_ops
1694    group_ops_bls12381_decode_scalar_cost: Option<u64>,
1695    group_ops_bls12381_decode_g1_cost: Option<u64>,
1696    group_ops_bls12381_decode_g2_cost: Option<u64>,
1697    group_ops_bls12381_decode_gt_cost: Option<u64>,
1698    group_ops_bls12381_scalar_add_cost: Option<u64>,
1699    group_ops_bls12381_g1_add_cost: Option<u64>,
1700    group_ops_bls12381_g2_add_cost: Option<u64>,
1701    group_ops_bls12381_gt_add_cost: Option<u64>,
1702    group_ops_bls12381_scalar_sub_cost: Option<u64>,
1703    group_ops_bls12381_g1_sub_cost: Option<u64>,
1704    group_ops_bls12381_g2_sub_cost: Option<u64>,
1705    group_ops_bls12381_gt_sub_cost: Option<u64>,
1706    group_ops_bls12381_scalar_mul_cost: Option<u64>,
1707    group_ops_bls12381_g1_mul_cost: Option<u64>,
1708    group_ops_bls12381_g2_mul_cost: Option<u64>,
1709    group_ops_bls12381_gt_mul_cost: Option<u64>,
1710    group_ops_bls12381_scalar_div_cost: Option<u64>,
1711    group_ops_bls12381_g1_div_cost: Option<u64>,
1712    group_ops_bls12381_g2_div_cost: Option<u64>,
1713    group_ops_bls12381_gt_div_cost: Option<u64>,
1714    group_ops_bls12381_g1_hash_to_base_cost: Option<u64>,
1715    group_ops_bls12381_g2_hash_to_base_cost: Option<u64>,
1716    group_ops_bls12381_g1_hash_to_cost_per_byte: Option<u64>,
1717    group_ops_bls12381_g2_hash_to_cost_per_byte: Option<u64>,
1718    group_ops_bls12381_g1_msm_base_cost: Option<u64>,
1719    group_ops_bls12381_g2_msm_base_cost: Option<u64>,
1720    group_ops_bls12381_g1_msm_base_cost_per_input: Option<u64>,
1721    group_ops_bls12381_g2_msm_base_cost_per_input: Option<u64>,
1722    group_ops_bls12381_msm_max_len: Option<u32>,
1723    group_ops_bls12381_pairing_cost: Option<u64>,
1724    group_ops_bls12381_g1_to_uncompressed_g1_cost: Option<u64>,
1725    group_ops_bls12381_uncompressed_g1_to_g1_cost: Option<u64>,
1726    group_ops_bls12381_uncompressed_g1_sum_base_cost: Option<u64>,
1727    group_ops_bls12381_uncompressed_g1_sum_cost_per_term: Option<u64>,
1728    group_ops_bls12381_uncompressed_g1_sum_max_terms: Option<u64>,
1729
1730    group_ops_ristretto_decode_scalar_cost: Option<u64>,
1731    group_ops_ristretto_decode_point_cost: Option<u64>,
1732    group_ops_ristretto_scalar_add_cost: Option<u64>,
1733    group_ops_ristretto_point_add_cost: Option<u64>,
1734    group_ops_ristretto_scalar_sub_cost: Option<u64>,
1735    group_ops_ristretto_point_sub_cost: Option<u64>,
1736    group_ops_ristretto_scalar_mul_cost: Option<u64>,
1737    group_ops_ristretto_point_mul_cost: Option<u64>,
1738    group_ops_ristretto_scalar_div_cost: Option<u64>,
1739    group_ops_ristretto_point_div_cost: Option<u64>,
1740
1741    verify_bulletproofs_ristretto255_base_cost: Option<u64>,
1742    verify_bulletproofs_ristretto255_cost_per_bit_and_commitment: Option<u64>,
1743
1744    // hmac::hmac_sha3_256
1745    hmac_hmac_sha3_256_cost_base: Option<u64>,
1746    hmac_hmac_sha3_256_input_cost_per_byte: Option<u64>,
1747    hmac_hmac_sha3_256_input_cost_per_block: Option<u64>,
1748
1749    // zklogin::check_zklogin_id
1750    check_zklogin_id_cost_base: Option<u64>,
1751    // zklogin::check_zklogin_issuer
1752    check_zklogin_issuer_cost_base: Option<u64>,
1753
1754    vdf_verify_vdf_cost: Option<u64>,
1755    vdf_hash_to_input_cost: Option<u64>,
1756
1757    // nitro_attestation::load_nitro_attestation
1758    nitro_attestation_parse_base_cost: Option<u64>,
1759    nitro_attestation_parse_cost_per_byte: Option<u64>,
1760    nitro_attestation_verify_base_cost: Option<u64>,
1761    nitro_attestation_verify_cost_per_cert: Option<u64>,
1762
1763    // Stdlib costs
1764    bcs_per_byte_serialized_cost: Option<u64>,
1765    bcs_legacy_min_output_size_cost: Option<u64>,
1766    bcs_failure_cost: Option<u64>,
1767
1768    hash_sha2_256_base_cost: Option<u64>,
1769    hash_sha2_256_per_byte_cost: Option<u64>,
1770    hash_sha2_256_legacy_min_input_len_cost: Option<u64>,
1771    hash_sha3_256_base_cost: Option<u64>,
1772    hash_sha3_256_per_byte_cost: Option<u64>,
1773    hash_sha3_256_legacy_min_input_len_cost: Option<u64>,
1774    type_name_get_base_cost: Option<u64>,
1775    type_name_get_per_byte_cost: Option<u64>,
1776    type_name_id_base_cost: Option<u64>,
1777
1778    string_check_utf8_base_cost: Option<u64>,
1779    string_check_utf8_per_byte_cost: Option<u64>,
1780    string_is_char_boundary_base_cost: Option<u64>,
1781    string_sub_string_base_cost: Option<u64>,
1782    string_sub_string_per_byte_cost: Option<u64>,
1783    string_index_of_base_cost: Option<u64>,
1784    string_index_of_per_byte_pattern_cost: Option<u64>,
1785    string_index_of_per_byte_searched_cost: Option<u64>,
1786
1787    vector_empty_base_cost: Option<u64>,
1788    vector_length_base_cost: Option<u64>,
1789    vector_push_back_base_cost: Option<u64>,
1790    vector_push_back_legacy_per_abstract_memory_unit_cost: Option<u64>,
1791    vector_borrow_base_cost: Option<u64>,
1792    vector_pop_back_base_cost: Option<u64>,
1793    vector_destroy_empty_base_cost: Option<u64>,
1794    vector_swap_base_cost: Option<u64>,
1795    debug_print_base_cost: Option<u64>,
1796    debug_print_stack_trace_base_cost: Option<u64>,
1797
1798    // ==== Ephemeral (consensus only) params deleted ====
1799    //
1800    // Const params for consensus scoring decision
1801    // The scaling factor property for the MED outlier detection
1802    // scoring_decision_mad_divisor: Option<f64>,
1803    // The cutoff value for the MED outlier detection
1804    // scoring_decision_cutoff_value: Option<f64>,
1805    /// === Execution Version ===
1806    execution_version: Option<u64>,
1807
1808    // Dictates the threshold (percentage of stake) that is used to calculate the "bad" nodes to be
1809    // swapped when creating the consensus schedule. The values should be of the range [0 - 33]. Anything
1810    // above 33 (f) will not be allowed.
1811    consensus_bad_nodes_stake_threshold: Option<u64>,
1812
1813    max_jwk_votes_per_validator_per_epoch: Option<u64>,
1814    // The maximum age of a JWK in epochs before it is removed from the AuthenticatorState object.
1815    // Applied at the end of an epoch as a delta from the new epoch value, so setting this to 1
1816    // will cause the new epoch to start with JWKs from the previous epoch still valid.
1817    max_age_of_jwk_in_epochs: Option<u64>,
1818
1819    // === random beacon ===
1820    /// Maximum allowed precision loss when reducing voting weights for the random beacon
1821    /// protocol.
1822    random_beacon_reduction_allowed_delta: Option<u16>,
1823
1824    /// Minimum number of shares below which voting weights will not be reduced for the
1825    /// random beacon protocol.
1826    random_beacon_reduction_lower_bound: Option<u32>,
1827
1828    /// Consensus Round after which DKG should be aborted and randomness disabled for
1829    /// the epoch, if it hasn't already completed.
1830    random_beacon_dkg_timeout_round: Option<u32>,
1831
1832    /// Minimum interval between consecutive rounds of generated randomness.
1833    random_beacon_min_round_interval_ms: Option<u64>,
1834
1835    /// Version of the random beacon DKG protocol.
1836    /// 0 was deprecated (and currently not supported), 1 is the default version.
1837    random_beacon_dkg_version: Option<u64>,
1838
1839    /// The maximum serialised transaction size (in bytes) accepted by consensus. That should be bigger than the
1840    /// `max_tx_size_bytes` with some additional headroom.
1841    consensus_max_transaction_size_bytes: Option<u64>,
1842    /// The maximum size of transactions included in a consensus block.
1843    consensus_max_transactions_in_block_bytes: Option<u64>,
1844    /// The maximum number of transactions included in a consensus block.
1845    consensus_max_num_transactions_in_block: Option<u64>,
1846
1847    /// The maximum number of rounds where transaction voting is allowed.
1848    consensus_voting_rounds: Option<u32>,
1849
1850    /// DEPRECATED. Do not use.
1851    max_accumulated_txn_cost_per_object_in_narwhal_commit: Option<u64>,
1852
1853    /// The max number of consensus rounds a transaction can be deferred due to shared object congestion.
1854    /// Transactions will be cancelled after this many rounds.
1855    max_deferral_rounds_for_congestion_control: Option<u64>,
1856
1857    /// DEPRECATED. Do not use.
1858    max_txn_cost_overage_per_object_in_commit: Option<u64>,
1859
1860    /// DEPRECATED. Do not use.
1861    allowed_txn_cost_overage_burst_per_object_in_commit: Option<u64>,
1862
1863    /// Minimum interval of commit timestamps between consecutive checkpoints.
1864    min_checkpoint_interval_ms: Option<u64>,
1865
1866    /// Version number to use for version_specific_data in `CheckpointSummary`.
1867    checkpoint_summary_version_specific_data: Option<u64>,
1868
1869    /// The max number of transactions that can be included in a single Soft Bundle.
1870    max_soft_bundle_size: Option<u64>,
1871
1872    /// Whether to try to form bridge committee
1873    // Note: this is not a feature flag because we want to distinguish between
1874    // `None` and `Some(false)`, as committee was already finalized on Testnet.
1875    bridge_should_try_to_finalize_committee: Option<bool>,
1876
1877    /// The max accumulated txn execution cost per object in a mysticeti. Transactions
1878    /// in a commit will be deferred once their touch shared objects hit this limit,
1879    /// unless the selected congestion control mode allows overage.
1880    /// This config plays the same role as `max_accumulated_txn_cost_per_object_in_narwhal_commit`
1881    /// but for mysticeti commits due to that mysticeti has higher commit rate.
1882    max_accumulated_txn_cost_per_object_in_mysticeti_commit: Option<u64>,
1883
1884    /// As above, but separate per-commit budget for transactions that use randomness.
1885    /// If not configured, uses the setting for `max_accumulated_txn_cost_per_object_in_mysticeti_commit`.
1886    max_accumulated_randomness_txn_cost_per_object_in_mysticeti_commit: Option<u64>,
1887
1888    /// Configures the garbage collection depth for consensus. When is unset or `0` then the garbage collection
1889    /// is disabled.
1890    consensus_gc_depth: Option<u32>,
1891
1892    /// DEPRECATED. Do not use.
1893    gas_budget_based_txn_cost_cap_factor: Option<u64>,
1894
1895    /// DEPRECATED. Do not use.
1896    gas_budget_based_txn_cost_absolute_cap_commit_count: Option<u64>,
1897
1898    /// SIP-45: K in the formula `amplification_factor = max(0, gas_price / reference_gas_price - K)`.
1899    /// This is the threshold for activating consensus amplification.
1900    sip_45_consensus_amplification_threshold: Option<u64>,
1901
1902    /// DEPRECATED: this was an ephemeral feature flag only used in per-epoch tables, which has now
1903    /// been deployed everywhere.
1904    use_object_per_epoch_marker_table_v2: Option<bool>,
1905
1906    /// The number of commits to consider when computing a deterministic commit rate.
1907    consensus_commit_rate_estimation_window_size: Option<u32>,
1908
1909    /// A list of effective AliasedAddress.
1910    /// For each pair, `aliased` is allowed to act as `original` for any of the transaction digests
1911    /// listed in `tx_digests`
1912    #[serde(skip_serializing_if = "Vec::is_empty")]
1913    aliased_addresses: Vec<AliasedAddress>,
1914
1915    /// The base charge for each command in a programmable transaction. This is a fixed cost to
1916    /// account for the overhead of processing each command.
1917    translation_per_command_base_charge: Option<u64>,
1918
1919    /// The base charge for each input in a programmable transaction regardless of if it is used or
1920    /// not, or a pure/object/funds withdrawal input.
1921    translation_per_input_base_charge: Option<u64>,
1922
1923    /// The base charge for each byte of pure input in a programmable transaction.
1924    translation_pure_input_per_byte_charge: Option<u64>,
1925
1926    /// The multiplier for the number of type nodes when charging for type loading.
1927    /// This is multiplied by the number of type nodes to get the total cost.
1928    /// This should be a small number to avoid excessive gas costs for loading types.
1929    translation_per_type_node_charge: Option<u64>,
1930
1931    /// The multiplier for the number of type references when charging for type checking and reference
1932    /// checking.
1933    translation_per_reference_node_charge: Option<u64>,
1934
1935    /// The multiplier for each linkage entry when charging for linkage tables that we have
1936    /// created.
1937    translation_per_linkage_entry_charge: Option<u64>,
1938
1939    /// The maximum number of updates per settlement transaction.
1940    max_updates_per_settlement_txn: Option<u32>,
1941
1942    /// Maximum computation units allowed for a gasless transaction.
1943    gasless_max_computation_units: Option<u64>,
1944
1945    /// Allowed token types for gasless transactions, with minimum transfer sizes per token.
1946    #[skip_accessor]
1947    gasless_allowed_token_types: Option<Vec<(String, u64)>>,
1948
1949    /// Maximum number of unused Pure inputs allowed in a gasless transaction.
1950    /// Object and FundsWithdrawal inputs must always be used.
1951    /// When None, there is no limit (effectively unlimited).
1952    gasless_max_unused_inputs: Option<u64>,
1953
1954    /// Maximum size in bytes of each Pure input in a gasless transaction.
1955    /// When None, there is no limit (effectively unlimited).
1956    gasless_max_pure_input_bytes: Option<u64>,
1957
1958    /// Max tps for gasless transactions. Unlimited when unset, zero when set to zero.
1959    gasless_max_tps: Option<u64>,
1960
1961    #[serde(skip_serializing_if = "Option::is_none")]
1962    #[skip_accessor]
1963    include_special_package_amendments: Option<Arc<Amendments>>,
1964}
1965
1966/// An aliased address.
1967#[derive(Clone, Serialize, Deserialize, Debug)]
1968pub struct AliasedAddress {
1969    /// The original address.
1970    pub original: [u8; 32],
1971    /// An aliased address which is allowed to act as the original address.
1972    pub aliased: [u8; 32],
1973    /// A list of transaction digests for which the aliasing is allowed to be in effect.
1974    pub allowed_tx_digests: Vec<[u8; 32]>,
1975}
1976
1977// feature flags
1978impl ProtocolConfig {
1979    // Add checks for feature flag support here, e.g.:
1980    // pub fn check_new_protocol_feature_supported(&self) -> Result<(), Error> {
1981    //     if self.feature_flags.new_protocol_feature_supported {
1982    //         Ok(())
1983    //     } else {
1984    //         Err(Error(format!(
1985    //             "new_protocol_feature is not supported at {:?}",
1986    //             self.version
1987    //         )))
1988    //     }
1989    // }
1990
1991    pub fn check_package_upgrades_supported(&self) -> Result<(), Error> {
1992        if self.feature_flags.package_upgrades {
1993            Ok(())
1994        } else {
1995            Err(Error(format!(
1996                "package upgrades are not supported at {:?}",
1997                self.version
1998            )))
1999        }
2000    }
2001
2002    pub fn allow_receiving_object_id(&self) -> bool {
2003        self.feature_flags.allow_receiving_object_id
2004    }
2005
2006    pub fn receiving_objects_supported(&self) -> bool {
2007        self.feature_flags.receive_objects
2008    }
2009
2010    pub fn package_upgrades_supported(&self) -> bool {
2011        self.feature_flags.package_upgrades
2012    }
2013
2014    pub fn check_commit_root_state_digest_supported(&self) -> bool {
2015        self.feature_flags.commit_root_state_digest
2016    }
2017
2018    pub fn get_advance_epoch_start_time_in_safe_mode(&self) -> bool {
2019        self.feature_flags.advance_epoch_start_time_in_safe_mode
2020    }
2021
2022    pub fn loaded_child_objects_fixed(&self) -> bool {
2023        self.feature_flags.loaded_child_objects_fixed
2024    }
2025
2026    pub fn missing_type_is_compatibility_error(&self) -> bool {
2027        self.feature_flags.missing_type_is_compatibility_error
2028    }
2029
2030    pub fn scoring_decision_with_validity_cutoff(&self) -> bool {
2031        self.feature_flags.scoring_decision_with_validity_cutoff
2032    }
2033
2034    pub fn narwhal_versioned_metadata(&self) -> bool {
2035        self.feature_flags.narwhal_versioned_metadata
2036    }
2037
2038    pub fn consensus_order_end_of_epoch_last(&self) -> bool {
2039        self.feature_flags.consensus_order_end_of_epoch_last
2040    }
2041
2042    pub fn disallow_adding_abilities_on_upgrade(&self) -> bool {
2043        self.feature_flags.disallow_adding_abilities_on_upgrade
2044    }
2045
2046    pub fn disable_invariant_violation_check_in_swap_loc(&self) -> bool {
2047        self.feature_flags
2048            .disable_invariant_violation_check_in_swap_loc
2049    }
2050
2051    pub fn advance_to_highest_supported_protocol_version(&self) -> bool {
2052        self.feature_flags
2053            .advance_to_highest_supported_protocol_version
2054    }
2055
2056    pub fn ban_entry_init(&self) -> bool {
2057        self.feature_flags.ban_entry_init
2058    }
2059
2060    pub fn package_digest_hash_module(&self) -> bool {
2061        self.feature_flags.package_digest_hash_module
2062    }
2063
2064    pub fn disallow_change_struct_type_params_on_upgrade(&self) -> bool {
2065        self.feature_flags
2066            .disallow_change_struct_type_params_on_upgrade
2067    }
2068
2069    pub fn no_extraneous_module_bytes(&self) -> bool {
2070        self.feature_flags.no_extraneous_module_bytes
2071    }
2072
2073    pub fn zklogin_auth(&self) -> bool {
2074        self.feature_flags.zklogin_auth
2075    }
2076
2077    pub fn zklogin_supported_providers(&self) -> &BTreeSet<String> {
2078        &self.feature_flags.zklogin_supported_providers
2079    }
2080
2081    pub fn consensus_transaction_ordering(&self) -> ConsensusTransactionOrdering {
2082        self.feature_flags.consensus_transaction_ordering
2083    }
2084
2085    pub fn simplified_unwrap_then_delete(&self) -> bool {
2086        self.feature_flags.simplified_unwrap_then_delete
2087    }
2088
2089    pub fn supports_upgraded_multisig(&self) -> bool {
2090        self.feature_flags.upgraded_multisig_supported
2091    }
2092
2093    pub fn txn_base_cost_as_multiplier(&self) -> bool {
2094        self.feature_flags.txn_base_cost_as_multiplier
2095    }
2096
2097    pub fn shared_object_deletion(&self) -> bool {
2098        self.feature_flags.shared_object_deletion
2099    }
2100
2101    pub fn narwhal_new_leader_election_schedule(&self) -> bool {
2102        self.feature_flags.narwhal_new_leader_election_schedule
2103    }
2104
2105    pub fn loaded_child_object_format(&self) -> bool {
2106        self.feature_flags.loaded_child_object_format
2107    }
2108
2109    pub fn enable_jwk_consensus_updates(&self) -> bool {
2110        let ret = self.feature_flags.enable_jwk_consensus_updates;
2111        if ret {
2112            // jwk updates required end-of-epoch transactions
2113            assert!(self.feature_flags.end_of_epoch_transaction_supported);
2114        }
2115        ret
2116    }
2117
2118    pub fn simple_conservation_checks(&self) -> bool {
2119        self.feature_flags.simple_conservation_checks
2120    }
2121
2122    pub fn loaded_child_object_format_type(&self) -> bool {
2123        self.feature_flags.loaded_child_object_format_type
2124    }
2125
2126    pub fn end_of_epoch_transaction_supported(&self) -> bool {
2127        let ret = self.feature_flags.end_of_epoch_transaction_supported;
2128        if !ret {
2129            // jwk updates required end-of-epoch transactions
2130            assert!(!self.feature_flags.enable_jwk_consensus_updates);
2131        }
2132        ret
2133    }
2134
2135    pub fn recompute_has_public_transfer_in_execution(&self) -> bool {
2136        self.feature_flags
2137            .recompute_has_public_transfer_in_execution
2138    }
2139
2140    // this function only exists for readability in the genesis code.
2141    pub fn create_authenticator_state_in_genesis(&self) -> bool {
2142        self.enable_jwk_consensus_updates()
2143    }
2144
2145    pub fn random_beacon(&self) -> bool {
2146        self.feature_flags.random_beacon
2147    }
2148
2149    pub fn dkg_version(&self) -> u64 {
2150        // Version 0 was deprecated and removed, the default is 1 if not set.
2151        self.random_beacon_dkg_version.unwrap_or(1)
2152    }
2153
2154    pub fn enable_bridge(&self) -> bool {
2155        let ret = self.feature_flags.bridge;
2156        if ret {
2157            // bridge required end-of-epoch transactions
2158            assert!(self.feature_flags.end_of_epoch_transaction_supported);
2159        }
2160        ret
2161    }
2162
2163    pub fn should_try_to_finalize_bridge_committee(&self) -> bool {
2164        if !self.enable_bridge() {
2165            return false;
2166        }
2167        // In the older protocol version, always try to finalize the committee.
2168        self.bridge_should_try_to_finalize_committee.unwrap_or(true)
2169    }
2170
2171    pub fn enable_effects_v2(&self) -> bool {
2172        self.feature_flags.enable_effects_v2
2173    }
2174
2175    pub fn narwhal_certificate_v2(&self) -> bool {
2176        self.feature_flags.narwhal_certificate_v2
2177    }
2178
2179    pub fn verify_legacy_zklogin_address(&self) -> bool {
2180        self.feature_flags.verify_legacy_zklogin_address
2181    }
2182
2183    pub fn accept_zklogin_in_multisig(&self) -> bool {
2184        self.feature_flags.accept_zklogin_in_multisig
2185    }
2186
2187    pub fn accept_passkey_in_multisig(&self) -> bool {
2188        self.feature_flags.accept_passkey_in_multisig
2189    }
2190
2191    pub fn validate_zklogin_public_identifier(&self) -> bool {
2192        self.feature_flags.validate_zklogin_public_identifier
2193    }
2194
2195    pub fn zklogin_max_epoch_upper_bound_delta(&self) -> Option<u64> {
2196        self.feature_flags.zklogin_max_epoch_upper_bound_delta
2197    }
2198
2199    pub fn throughput_aware_consensus_submission(&self) -> bool {
2200        self.feature_flags.throughput_aware_consensus_submission
2201    }
2202
2203    pub fn include_consensus_digest_in_prologue(&self) -> bool {
2204        self.feature_flags.include_consensus_digest_in_prologue
2205    }
2206
2207    pub fn record_consensus_determined_version_assignments_in_prologue(&self) -> bool {
2208        self.feature_flags
2209            .record_consensus_determined_version_assignments_in_prologue
2210    }
2211
2212    pub fn record_additional_state_digest_in_prologue(&self) -> bool {
2213        self.feature_flags
2214            .record_additional_state_digest_in_prologue
2215    }
2216
2217    pub fn record_consensus_determined_version_assignments_in_prologue_v2(&self) -> bool {
2218        self.feature_flags
2219            .record_consensus_determined_version_assignments_in_prologue_v2
2220    }
2221
2222    pub fn prepend_prologue_tx_in_consensus_commit_in_checkpoints(&self) -> bool {
2223        self.feature_flags
2224            .prepend_prologue_tx_in_consensus_commit_in_checkpoints
2225    }
2226
2227    pub fn hardened_otw_check(&self) -> bool {
2228        self.feature_flags.hardened_otw_check
2229    }
2230
2231    pub fn enable_poseidon(&self) -> bool {
2232        self.feature_flags.enable_poseidon
2233    }
2234
2235    pub fn enable_coin_deny_list_v1(&self) -> bool {
2236        self.feature_flags.enable_coin_deny_list
2237    }
2238
2239    pub fn enable_accumulators(&self) -> bool {
2240        self.feature_flags.enable_accumulators
2241    }
2242
2243    pub fn enable_coin_reservation_obj_refs(&self) -> bool {
2244        self.new_vm_enabled() && self.feature_flags.enable_coin_reservation_obj_refs
2245    }
2246
2247    pub fn create_root_accumulator_object(&self) -> bool {
2248        self.feature_flags.create_root_accumulator_object
2249    }
2250
2251    pub fn enable_address_balance_gas_payments(&self) -> bool {
2252        self.feature_flags.enable_address_balance_gas_payments
2253    }
2254
2255    pub fn address_balance_gas_check_rgp_at_signing(&self) -> bool {
2256        self.feature_flags.address_balance_gas_check_rgp_at_signing
2257    }
2258
2259    pub fn address_balance_gas_reject_gas_coin_arg(&self) -> bool {
2260        self.feature_flags.address_balance_gas_reject_gas_coin_arg
2261    }
2262
2263    pub fn enable_multi_epoch_transaction_expiration(&self) -> bool {
2264        self.feature_flags.enable_multi_epoch_transaction_expiration
2265    }
2266
2267    pub fn relax_valid_during_for_owned_inputs(&self) -> bool {
2268        self.feature_flags.relax_valid_during_for_owned_inputs
2269    }
2270
2271    pub fn enable_authenticated_event_streams(&self) -> bool {
2272        self.feature_flags.enable_authenticated_event_streams && self.enable_accumulators()
2273    }
2274
2275    pub fn enable_non_exclusive_writes(&self) -> bool {
2276        self.feature_flags.enable_non_exclusive_writes
2277    }
2278
2279    pub fn enable_coin_registry(&self) -> bool {
2280        self.feature_flags.enable_coin_registry
2281    }
2282
2283    pub fn enable_display_registry(&self) -> bool {
2284        self.feature_flags.enable_display_registry
2285    }
2286
2287    pub fn enable_coin_deny_list_v2(&self) -> bool {
2288        self.feature_flags.enable_coin_deny_list_v2
2289    }
2290
2291    pub fn enable_group_ops_native_functions(&self) -> bool {
2292        self.feature_flags.enable_group_ops_native_functions
2293    }
2294
2295    pub fn enable_group_ops_native_function_msm(&self) -> bool {
2296        self.feature_flags.enable_group_ops_native_function_msm
2297    }
2298
2299    pub fn enable_ristretto255_group_ops(&self) -> bool {
2300        self.feature_flags.enable_ristretto255_group_ops
2301    }
2302
2303    pub fn enable_verify_bulletproofs_ristretto255(&self) -> bool {
2304        self.feature_flags.enable_verify_bulletproofs_ristretto255
2305    }
2306
2307    pub fn reject_mutable_random_on_entry_functions(&self) -> bool {
2308        self.feature_flags.reject_mutable_random_on_entry_functions
2309    }
2310
2311    pub fn per_object_congestion_control_mode(&self) -> PerObjectCongestionControlMode {
2312        self.feature_flags.per_object_congestion_control_mode
2313    }
2314
2315    pub fn consensus_choice(&self) -> ConsensusChoice {
2316        self.feature_flags.consensus_choice
2317    }
2318
2319    pub fn consensus_network(&self) -> ConsensusNetwork {
2320        self.feature_flags.consensus_network
2321    }
2322
2323    pub fn correct_gas_payment_limit_check(&self) -> bool {
2324        self.feature_flags.correct_gas_payment_limit_check
2325    }
2326
2327    pub fn reshare_at_same_initial_version(&self) -> bool {
2328        self.feature_flags.reshare_at_same_initial_version
2329    }
2330
2331    pub fn resolve_abort_locations_to_package_id(&self) -> bool {
2332        self.feature_flags.resolve_abort_locations_to_package_id
2333    }
2334
2335    pub fn mysticeti_use_committed_subdag_digest(&self) -> bool {
2336        self.feature_flags.mysticeti_use_committed_subdag_digest
2337    }
2338
2339    pub fn enable_vdf(&self) -> bool {
2340        self.feature_flags.enable_vdf
2341    }
2342
2343    pub fn fresh_vm_on_framework_upgrade(&self) -> bool {
2344        self.feature_flags.fresh_vm_on_framework_upgrade
2345    }
2346
2347    pub fn mysticeti_num_leaders_per_round(&self) -> Option<usize> {
2348        self.feature_flags.mysticeti_num_leaders_per_round
2349    }
2350
2351    pub fn soft_bundle(&self) -> bool {
2352        self.feature_flags.soft_bundle
2353    }
2354
2355    pub fn passkey_auth(&self) -> bool {
2356        self.feature_flags.passkey_auth
2357    }
2358
2359    pub fn authority_capabilities_v2(&self) -> bool {
2360        self.feature_flags.authority_capabilities_v2
2361    }
2362
2363    pub fn max_transaction_size_bytes(&self) -> u64 {
2364        // Provide a default value if protocol config version is too low.
2365        self.consensus_max_transaction_size_bytes
2366            .unwrap_or(256 * 1024)
2367    }
2368
2369    pub fn max_transactions_in_block_bytes(&self) -> u64 {
2370        if cfg!(msim) {
2371            256 * 1024
2372        } else {
2373            self.consensus_max_transactions_in_block_bytes
2374                .unwrap_or(512 * 1024)
2375        }
2376    }
2377
2378    pub fn max_num_transactions_in_block(&self) -> u64 {
2379        if cfg!(msim) {
2380            8
2381        } else {
2382            self.consensus_max_num_transactions_in_block.unwrap_or(512)
2383        }
2384    }
2385
2386    pub fn rethrow_serialization_type_layout_errors(&self) -> bool {
2387        self.feature_flags.rethrow_serialization_type_layout_errors
2388    }
2389
2390    pub fn consensus_distributed_vote_scoring_strategy(&self) -> bool {
2391        self.feature_flags
2392            .consensus_distributed_vote_scoring_strategy
2393    }
2394
2395    pub fn consensus_round_prober(&self) -> bool {
2396        self.feature_flags.consensus_round_prober
2397    }
2398
2399    pub fn validate_identifier_inputs(&self) -> bool {
2400        self.feature_flags.validate_identifier_inputs
2401    }
2402
2403    pub fn gc_depth(&self) -> u32 {
2404        self.consensus_gc_depth.unwrap_or(0)
2405    }
2406
2407    pub fn mysticeti_fastpath(&self) -> bool {
2408        self.feature_flags.mysticeti_fastpath
2409    }
2410
2411    pub fn relocate_event_module(&self) -> bool {
2412        self.feature_flags.relocate_event_module
2413    }
2414
2415    pub fn uncompressed_g1_group_elements(&self) -> bool {
2416        self.feature_flags.uncompressed_g1_group_elements
2417    }
2418
2419    pub fn disallow_new_modules_in_deps_only_packages(&self) -> bool {
2420        self.feature_flags
2421            .disallow_new_modules_in_deps_only_packages
2422    }
2423
2424    pub fn consensus_smart_ancestor_selection(&self) -> bool {
2425        self.feature_flags.consensus_smart_ancestor_selection
2426    }
2427
2428    pub fn disable_preconsensus_locking(&self) -> bool {
2429        self.feature_flags.disable_preconsensus_locking
2430    }
2431
2432    pub fn consensus_round_prober_probe_accepted_rounds(&self) -> bool {
2433        self.feature_flags
2434            .consensus_round_prober_probe_accepted_rounds
2435    }
2436
2437    pub fn native_charging_v2(&self) -> bool {
2438        self.feature_flags.native_charging_v2
2439    }
2440
2441    pub fn consensus_linearize_subdag_v2(&self) -> bool {
2442        let res = self.feature_flags.consensus_linearize_subdag_v2;
2443        assert!(
2444            !res || self.gc_depth() > 0,
2445            "The consensus linearize sub dag V2 requires GC to be enabled"
2446        );
2447        res
2448    }
2449
2450    pub fn consensus_median_based_commit_timestamp(&self) -> bool {
2451        let res = self.feature_flags.consensus_median_based_commit_timestamp;
2452        assert!(
2453            !res || self.gc_depth() > 0,
2454            "The consensus median based commit timestamp requires GC to be enabled"
2455        );
2456        res
2457    }
2458
2459    pub fn consensus_batched_block_sync(&self) -> bool {
2460        self.feature_flags.consensus_batched_block_sync
2461    }
2462
2463    pub fn convert_type_argument_error(&self) -> bool {
2464        self.feature_flags.convert_type_argument_error
2465    }
2466
2467    pub fn variant_nodes(&self) -> bool {
2468        self.feature_flags.variant_nodes
2469    }
2470
2471    pub fn consensus_zstd_compression(&self) -> bool {
2472        self.feature_flags.consensus_zstd_compression
2473    }
2474
2475    pub fn enable_nitro_attestation(&self) -> bool {
2476        self.feature_flags.enable_nitro_attestation
2477    }
2478
2479    pub fn enable_nitro_attestation_upgraded_parsing(&self) -> bool {
2480        self.feature_flags.enable_nitro_attestation_upgraded_parsing
2481    }
2482
2483    pub fn enable_nitro_attestation_all_nonzero_pcrs_parsing(&self) -> bool {
2484        self.feature_flags
2485            .enable_nitro_attestation_all_nonzero_pcrs_parsing
2486    }
2487
2488    pub fn enable_nitro_attestation_always_include_required_pcrs_parsing(&self) -> bool {
2489        self.feature_flags
2490            .enable_nitro_attestation_always_include_required_pcrs_parsing
2491    }
2492
2493    pub fn get_consensus_commit_rate_estimation_window_size(&self) -> u32 {
2494        self.consensus_commit_rate_estimation_window_size
2495            .unwrap_or(0)
2496    }
2497
2498    pub fn consensus_num_requested_prior_commits_at_startup(&self) -> u32 {
2499        // Currently there is only one parameter driving this value. If there are multiple
2500        // things computed from prior consensus commits, this function must return the max
2501        // of all of them.
2502        let window_size = self.get_consensus_commit_rate_estimation_window_size();
2503        // Ensure we are not using past commits without recording a state digest in the prologue.
2504        assert!(window_size == 0 || self.record_additional_state_digest_in_prologue());
2505        window_size
2506    }
2507
2508    pub fn minimize_child_object_mutations(&self) -> bool {
2509        self.feature_flags.minimize_child_object_mutations
2510    }
2511
2512    pub fn move_native_context(&self) -> bool {
2513        self.feature_flags.move_native_context
2514    }
2515
2516    pub fn normalize_ptb_arguments(&self) -> bool {
2517        self.feature_flags.normalize_ptb_arguments
2518    }
2519
2520    pub fn enforce_checkpoint_timestamp_monotonicity(&self) -> bool {
2521        self.feature_flags.enforce_checkpoint_timestamp_monotonicity
2522    }
2523
2524    pub fn max_ptb_value_size_v2(&self) -> bool {
2525        self.feature_flags.max_ptb_value_size_v2
2526    }
2527
2528    pub fn resolve_type_input_ids_to_defining_id(&self) -> bool {
2529        self.feature_flags.resolve_type_input_ids_to_defining_id
2530    }
2531
2532    pub fn enable_party_transfer(&self) -> bool {
2533        self.feature_flags.enable_party_transfer
2534    }
2535
2536    pub fn allow_unbounded_system_objects(&self) -> bool {
2537        self.feature_flags.allow_unbounded_system_objects
2538    }
2539
2540    pub fn type_tags_in_object_runtime(&self) -> bool {
2541        self.feature_flags.type_tags_in_object_runtime
2542    }
2543
2544    pub fn enable_ptb_execution_v2(&self) -> bool {
2545        self.feature_flags.enable_ptb_execution_v2
2546    }
2547
2548    pub fn better_adapter_type_resolution_errors(&self) -> bool {
2549        self.feature_flags.better_adapter_type_resolution_errors
2550    }
2551
2552    pub fn record_time_estimate_processed(&self) -> bool {
2553        self.feature_flags.record_time_estimate_processed
2554    }
2555
2556    pub fn ignore_execution_time_observations_after_certs_closed(&self) -> bool {
2557        self.feature_flags
2558            .ignore_execution_time_observations_after_certs_closed
2559    }
2560
2561    pub fn dependency_linkage_error(&self) -> bool {
2562        self.feature_flags.dependency_linkage_error
2563    }
2564
2565    pub fn additional_multisig_checks(&self) -> bool {
2566        self.feature_flags.additional_multisig_checks
2567    }
2568
2569    pub fn debug_fatal_on_move_invariant_violation(&self) -> bool {
2570        self.feature_flags.debug_fatal_on_move_invariant_violation
2571    }
2572
2573    pub fn allow_private_accumulator_entrypoints(&self) -> bool {
2574        self.feature_flags.allow_private_accumulator_entrypoints
2575    }
2576
2577    pub fn additional_consensus_digest_indirect_state(&self) -> bool {
2578        self.feature_flags
2579            .additional_consensus_digest_indirect_state
2580    }
2581
2582    pub fn check_for_init_during_upgrade(&self) -> bool {
2583        self.feature_flags.check_for_init_during_upgrade
2584    }
2585
2586    pub fn per_command_shared_object_transfer_rules(&self) -> bool {
2587        self.feature_flags.per_command_shared_object_transfer_rules
2588    }
2589
2590    pub fn consensus_checkpoint_signature_key_includes_digest(&self) -> bool {
2591        self.feature_flags
2592            .consensus_checkpoint_signature_key_includes_digest
2593    }
2594
2595    pub fn include_checkpoint_artifacts_digest_in_summary(&self) -> bool {
2596        self.feature_flags
2597            .include_checkpoint_artifacts_digest_in_summary
2598    }
2599
2600    pub fn use_mfp_txns_in_load_initial_object_debts(&self) -> bool {
2601        self.feature_flags.use_mfp_txns_in_load_initial_object_debts
2602    }
2603
2604    pub fn cancel_for_failed_dkg_early(&self) -> bool {
2605        self.feature_flags.cancel_for_failed_dkg_early
2606    }
2607
2608    pub fn abstract_size_in_object_runtime(&self) -> bool {
2609        self.feature_flags.abstract_size_in_object_runtime
2610    }
2611
2612    pub fn object_runtime_charge_cache_load_gas(&self) -> bool {
2613        self.feature_flags.object_runtime_charge_cache_load_gas
2614    }
2615
2616    pub fn additional_borrow_checks(&self) -> bool {
2617        self.feature_flags.additional_borrow_checks
2618    }
2619
2620    pub fn use_new_commit_handler(&self) -> bool {
2621        self.feature_flags.use_new_commit_handler
2622    }
2623
2624    pub fn better_loader_errors(&self) -> bool {
2625        self.feature_flags.better_loader_errors
2626    }
2627
2628    pub fn generate_df_type_layouts(&self) -> bool {
2629        self.feature_flags.generate_df_type_layouts
2630    }
2631
2632    pub fn allow_references_in_ptbs(&self) -> bool {
2633        self.feature_flags.allow_references_in_ptbs
2634    }
2635
2636    pub fn private_generics_verifier_v2(&self) -> bool {
2637        self.feature_flags.private_generics_verifier_v2
2638    }
2639
2640    pub fn deprecate_global_storage_ops_during_deserialization(&self) -> bool {
2641        self.feature_flags
2642            .deprecate_global_storage_ops_during_deserialization
2643    }
2644
2645    pub fn enable_observation_chunking(&self) -> bool {
2646        matches!(self.feature_flags.per_object_congestion_control_mode,
2647            PerObjectCongestionControlMode::ExecutionTimeEstimate(ref params)
2648                if params.observations_chunk_size.is_some()
2649        )
2650    }
2651
2652    pub fn deprecate_global_storage_ops(&self) -> bool {
2653        self.feature_flags.deprecate_global_storage_ops
2654    }
2655
2656    pub fn normalize_depth_formula(&self) -> bool {
2657        self.feature_flags.normalize_depth_formula
2658    }
2659
2660    pub fn consensus_skip_gced_accept_votes(&self) -> bool {
2661        self.feature_flags.consensus_skip_gced_accept_votes
2662    }
2663
2664    pub fn include_cancelled_randomness_txns_in_prologue(&self) -> bool {
2665        self.feature_flags
2666            .include_cancelled_randomness_txns_in_prologue
2667    }
2668
2669    pub fn address_aliases(&self) -> bool {
2670        let address_aliases = self.feature_flags.address_aliases;
2671        assert!(
2672            !address_aliases || self.mysticeti_fastpath(),
2673            "Address aliases requires Mysticeti fastpath to be enabled"
2674        );
2675        if address_aliases {
2676            assert!(
2677                self.feature_flags.disable_preconsensus_locking,
2678                "Address aliases requires CertifiedTransaction to be disabled"
2679            );
2680        }
2681        address_aliases
2682    }
2683
2684    pub fn fix_checkpoint_signature_mapping(&self) -> bool {
2685        self.feature_flags.fix_checkpoint_signature_mapping
2686    }
2687
2688    pub fn enable_object_funds_withdraw(&self) -> bool {
2689        self.feature_flags.enable_object_funds_withdraw
2690    }
2691
2692    pub fn gas_rounding_halve_digits(&self) -> bool {
2693        self.feature_flags.gas_rounding_halve_digits
2694    }
2695
2696    pub fn flexible_tx_context_positions(&self) -> bool {
2697        self.feature_flags.flexible_tx_context_positions
2698    }
2699
2700    pub fn disable_entry_point_signature_check(&self) -> bool {
2701        self.feature_flags.disable_entry_point_signature_check
2702    }
2703
2704    pub fn consensus_skip_gced_blocks_in_direct_finalization(&self) -> bool {
2705        self.feature_flags
2706            .consensus_skip_gced_blocks_in_direct_finalization
2707    }
2708
2709    pub fn convert_withdrawal_compatibility_ptb_arguments(&self) -> bool {
2710        self.feature_flags
2711            .convert_withdrawal_compatibility_ptb_arguments
2712    }
2713
2714    pub fn restrict_hot_or_not_entry_functions(&self) -> bool {
2715        self.feature_flags.restrict_hot_or_not_entry_functions
2716    }
2717
2718    pub fn split_checkpoints_in_consensus_handler(&self) -> bool {
2719        self.feature_flags.split_checkpoints_in_consensus_handler
2720    }
2721
2722    pub fn consensus_always_accept_system_transactions(&self) -> bool {
2723        self.feature_flags
2724            .consensus_always_accept_system_transactions
2725    }
2726
2727    pub fn validator_metadata_verify_v2(&self) -> bool {
2728        self.feature_flags.validator_metadata_verify_v2
2729    }
2730
2731    pub fn defer_unpaid_amplification(&self) -> bool {
2732        self.feature_flags.defer_unpaid_amplification
2733    }
2734
2735    pub fn gasless_transaction_drop_safety(&self) -> bool {
2736        self.feature_flags.gasless_transaction_drop_safety
2737    }
2738
2739    pub fn new_vm_enabled(&self) -> bool {
2740        self.execution_version.is_some_and(|v| v >= 4)
2741    }
2742
2743    pub fn merge_randomness_into_checkpoint(&self) -> bool {
2744        self.feature_flags.merge_randomness_into_checkpoint
2745    }
2746
2747    pub fn use_coin_party_owner(&self) -> bool {
2748        self.feature_flags.use_coin_party_owner
2749    }
2750
2751    pub fn enable_gasless(&self) -> bool {
2752        self.feature_flags.enable_gasless
2753    }
2754
2755    pub fn gasless_verify_remaining_balance(&self) -> bool {
2756        self.feature_flags.gasless_verify_remaining_balance
2757    }
2758
2759    pub fn gasless_allowed_token_types(&self) -> &[(String, u64)] {
2760        debug_assert!(self.gasless_allowed_token_types.is_some());
2761        self.gasless_allowed_token_types.as_deref().unwrap_or(&[])
2762    }
2763
2764    pub fn get_gasless_max_unused_inputs(&self) -> u64 {
2765        self.gasless_max_unused_inputs.unwrap_or(u64::MAX)
2766    }
2767
2768    pub fn get_gasless_max_pure_input_bytes(&self) -> u64 {
2769        self.gasless_max_pure_input_bytes.unwrap_or(u64::MAX)
2770    }
2771
2772    pub fn disallow_jump_orphans(&self) -> bool {
2773        self.feature_flags.disallow_jump_orphans
2774    }
2775
2776    pub fn early_return_receive_object_mismatched_type(&self) -> bool {
2777        self.feature_flags
2778            .early_return_receive_object_mismatched_type
2779    }
2780
2781    pub fn include_special_package_amendments_as_option(&self) -> &Option<Arc<Amendments>> {
2782        &self.include_special_package_amendments
2783    }
2784}
2785
2786#[cfg(not(msim))]
2787static POISON_VERSION_METHODS: AtomicBool = AtomicBool::new(false);
2788
2789// Use a thread local in sim tests for test isolation.
2790#[cfg(msim)]
2791thread_local! {
2792    static POISON_VERSION_METHODS: AtomicBool = AtomicBool::new(false);
2793}
2794
2795// Instantiations for each protocol version.
2796impl ProtocolConfig {
2797    /// Get the value ProtocolConfig that are in effect during the given protocol version.
2798    pub fn get_for_version(version: ProtocolVersion, chain: Chain) -> Self {
2799        // ProtocolVersion can be deserialized so we need to check it here as well.
2800        assert!(
2801            version >= ProtocolVersion::MIN,
2802            "Network protocol version is {:?}, but the minimum supported version by the binary is {:?}. Please upgrade the binary.",
2803            version,
2804            ProtocolVersion::MIN.0,
2805        );
2806        assert!(
2807            version <= ProtocolVersion::MAX_ALLOWED,
2808            "Network protocol version is {:?}, but the maximum supported version by the binary is {:?}. Please upgrade the binary.",
2809            version,
2810            ProtocolVersion::MAX_ALLOWED.0,
2811        );
2812
2813        let mut ret = Self::get_for_version_impl(version, chain);
2814        ret.version = version;
2815
2816        ret = Self::apply_config_override(version, ret);
2817
2818        if std::env::var("SUI_PROTOCOL_CONFIG_OVERRIDE_ENABLE").is_ok() {
2819            warn!(
2820                "overriding ProtocolConfig settings with custom settings; this may break non-local networks"
2821            );
2822            let overrides: ProtocolConfigOptional =
2823                serde_env::from_env_with_prefix("SUI_PROTOCOL_CONFIG_OVERRIDE")
2824                    .expect("failed to parse ProtocolConfig override env variables");
2825            overrides.apply_to(&mut ret);
2826        }
2827
2828        ret
2829    }
2830
2831    /// Get the value ProtocolConfig that are in effect during the given protocol version.
2832    /// Or none if the version is not supported.
2833    pub fn get_for_version_if_supported(version: ProtocolVersion, chain: Chain) -> Option<Self> {
2834        if version.0 >= ProtocolVersion::MIN.0 && version.0 <= ProtocolVersion::MAX_ALLOWED.0 {
2835            let mut ret = Self::get_for_version_impl(version, chain);
2836            ret.version = version;
2837            ret = Self::apply_config_override(version, ret);
2838            Some(ret)
2839        } else {
2840            None
2841        }
2842    }
2843
2844    #[cfg(not(msim))]
2845    pub fn poison_get_for_min_version() {
2846        POISON_VERSION_METHODS.store(true, Ordering::Relaxed);
2847    }
2848
2849    #[cfg(not(msim))]
2850    fn load_poison_get_for_min_version() -> bool {
2851        POISON_VERSION_METHODS.load(Ordering::Relaxed)
2852    }
2853
2854    #[cfg(msim)]
2855    pub fn poison_get_for_min_version() {
2856        POISON_VERSION_METHODS.with(|p| p.store(true, Ordering::Relaxed));
2857    }
2858
2859    #[cfg(msim)]
2860    fn load_poison_get_for_min_version() -> bool {
2861        POISON_VERSION_METHODS.with(|p| p.load(Ordering::Relaxed))
2862    }
2863
2864    /// Convenience to get the constants at the current minimum supported version.
2865    /// Mainly used by client code that may not yet be protocol-version aware.
2866    pub fn get_for_min_version() -> Self {
2867        if Self::load_poison_get_for_min_version() {
2868            panic!("get_for_min_version called on validator");
2869        }
2870        ProtocolConfig::get_for_version(ProtocolVersion::MIN, Chain::Unknown)
2871    }
2872
2873    /// CAREFUL! - You probably want to use `get_for_version` instead.
2874    ///
2875    /// Convenience to get the constants at the current maximum supported version.
2876    /// Mainly used by genesis. Note well that this function uses the max version
2877    /// supported locally by the node, which is not necessarily the current version
2878    /// of the network. ALSO, this function disregards chain specific config (by
2879    /// using Chain::Unknown), thereby potentially returning a protocol config that
2880    /// is incorrect for some feature flags. Definitely safe for testing and for
2881    /// protocol version 11 and prior.
2882    #[allow(non_snake_case)]
2883    pub fn get_for_max_version_UNSAFE() -> Self {
2884        if Self::load_poison_get_for_min_version() {
2885            panic!("get_for_max_version_UNSAFE called on validator");
2886        }
2887        ProtocolConfig::get_for_version(ProtocolVersion::MAX, Chain::Unknown)
2888    }
2889
2890    fn get_for_version_impl(version: ProtocolVersion, chain: Chain) -> Self {
2891        #[cfg(msim)]
2892        {
2893            // populate the fake simulator version # with a different base tx cost.
2894            if version == ProtocolVersion::MAX_ALLOWED {
2895                let mut config = Self::get_for_version_impl(version - 1, Chain::Unknown);
2896                config.base_tx_cost_fixed = Some(config.base_tx_cost_fixed() + 1000);
2897                return config;
2898            }
2899        }
2900
2901        // IMPORTANT: Never modify the value of any constant for a pre-existing protocol version.
2902        // To change the values here you must create a new protocol version with the new values!
2903        let mut cfg = Self {
2904            // will be overwritten before being returned
2905            version,
2906
2907            // All flags are disabled in V1
2908            feature_flags: Default::default(),
2909
2910            max_tx_size_bytes: Some(128 * 1024),
2911            // We need this number to be at least 100x less than `max_serialized_tx_effects_size_bytes`otherwise effects can be huge
2912            max_input_objects: Some(2048),
2913            max_serialized_tx_effects_size_bytes: Some(512 * 1024),
2914            max_serialized_tx_effects_size_bytes_system_tx: Some(512 * 1024 * 16),
2915            max_gas_payment_objects: Some(256),
2916            max_modules_in_publish: Some(128),
2917            max_package_dependencies: None,
2918            max_arguments: Some(512),
2919            max_type_arguments: Some(16),
2920            max_type_argument_depth: Some(16),
2921            max_pure_argument_size: Some(16 * 1024),
2922            max_programmable_tx_commands: Some(1024),
2923            move_binary_format_version: Some(6),
2924            min_move_binary_format_version: None,
2925            binary_module_handles: None,
2926            binary_struct_handles: None,
2927            binary_function_handles: None,
2928            binary_function_instantiations: None,
2929            binary_signatures: None,
2930            binary_constant_pool: None,
2931            binary_identifiers: None,
2932            binary_address_identifiers: None,
2933            binary_struct_defs: None,
2934            binary_struct_def_instantiations: None,
2935            binary_function_defs: None,
2936            binary_field_handles: None,
2937            binary_field_instantiations: None,
2938            binary_friend_decls: None,
2939            binary_enum_defs: None,
2940            binary_enum_def_instantiations: None,
2941            binary_variant_handles: None,
2942            binary_variant_instantiation_handles: None,
2943            max_move_object_size: Some(250 * 1024),
2944            max_move_package_size: Some(100 * 1024),
2945            max_publish_or_upgrade_per_ptb: None,
2946            max_tx_gas: Some(10_000_000_000),
2947            max_gas_price: Some(100_000),
2948            max_gas_price_rgp_factor_for_aborted_transactions: None,
2949            max_gas_computation_bucket: Some(5_000_000),
2950            max_loop_depth: Some(5),
2951            max_generic_instantiation_length: Some(32),
2952            max_function_parameters: Some(128),
2953            max_basic_blocks: Some(1024),
2954            max_value_stack_size: Some(1024),
2955            max_type_nodes: Some(256),
2956            max_push_size: Some(10000),
2957            max_struct_definitions: Some(200),
2958            max_function_definitions: Some(1000),
2959            max_fields_in_struct: Some(32),
2960            max_dependency_depth: Some(100),
2961            max_num_event_emit: Some(256),
2962            max_num_new_move_object_ids: Some(2048),
2963            max_num_new_move_object_ids_system_tx: Some(2048 * 16),
2964            max_num_deleted_move_object_ids: Some(2048),
2965            max_num_deleted_move_object_ids_system_tx: Some(2048 * 16),
2966            max_num_transferred_move_object_ids: Some(2048),
2967            max_num_transferred_move_object_ids_system_tx: Some(2048 * 16),
2968            max_event_emit_size: Some(250 * 1024),
2969            max_move_vector_len: Some(256 * 1024),
2970            max_type_to_layout_nodes: None,
2971            max_ptb_value_size: None,
2972
2973            max_back_edges_per_function: Some(10_000),
2974            max_back_edges_per_module: Some(10_000),
2975            max_verifier_meter_ticks_per_function: Some(6_000_000),
2976            max_meter_ticks_per_module: Some(6_000_000),
2977            max_meter_ticks_per_package: None,
2978
2979            object_runtime_max_num_cached_objects: Some(1000),
2980            object_runtime_max_num_cached_objects_system_tx: Some(1000 * 16),
2981            object_runtime_max_num_store_entries: Some(1000),
2982            object_runtime_max_num_store_entries_system_tx: Some(1000 * 16),
2983            base_tx_cost_fixed: Some(110_000),
2984            package_publish_cost_fixed: Some(1_000),
2985            base_tx_cost_per_byte: Some(0),
2986            package_publish_cost_per_byte: Some(80),
2987            obj_access_cost_read_per_byte: Some(15),
2988            obj_access_cost_mutate_per_byte: Some(40),
2989            obj_access_cost_delete_per_byte: Some(40),
2990            obj_access_cost_verify_per_byte: Some(200),
2991            obj_data_cost_refundable: Some(100),
2992            obj_metadata_cost_non_refundable: Some(50),
2993            gas_model_version: Some(1),
2994            storage_rebate_rate: Some(9900),
2995            storage_fund_reinvest_rate: Some(500),
2996            reward_slashing_rate: Some(5000),
2997            storage_gas_price: Some(1),
2998            accumulator_object_storage_cost: None,
2999            max_transactions_per_checkpoint: Some(10_000),
3000            max_checkpoint_size_bytes: Some(30 * 1024 * 1024),
3001
3002            // For now, perform upgrades with a bare quorum of validators.
3003            // MUSTFIX: This number should be increased to at least 2000 (20%) for mainnet.
3004            buffer_stake_for_protocol_upgrade_bps: Some(0),
3005
3006            // === Native Function Costs ===
3007            // `address` module
3008            // Cost params for the Move native function `address::from_bytes(bytes: vector<u8>)`
3009            address_from_bytes_cost_base: Some(52),
3010            // Cost params for the Move native function `address::to_u256(address): u256`
3011            address_to_u256_cost_base: Some(52),
3012            // Cost params for the Move native function `address::from_u256(u256): address`
3013            address_from_u256_cost_base: Some(52),
3014
3015            // `config` module
3016            // Cost params for the Move native function `read_setting_impl``
3017            config_read_setting_impl_cost_base: None,
3018            config_read_setting_impl_cost_per_byte: None,
3019
3020            // `dynamic_field` module
3021            // Cost params for the Move native function `hash_type_and_key<K: copy + drop + store>(parent: address, k: K): address`
3022            dynamic_field_hash_type_and_key_cost_base: Some(100),
3023            dynamic_field_hash_type_and_key_type_cost_per_byte: Some(2),
3024            dynamic_field_hash_type_and_key_value_cost_per_byte: Some(2),
3025            dynamic_field_hash_type_and_key_type_tag_cost_per_byte: Some(2),
3026            // Cost params for the Move native function `add_child_object<Child: key>(parent: address, child: Child)`
3027            dynamic_field_add_child_object_cost_base: Some(100),
3028            dynamic_field_add_child_object_type_cost_per_byte: Some(10),
3029            dynamic_field_add_child_object_value_cost_per_byte: Some(10),
3030            dynamic_field_add_child_object_struct_tag_cost_per_byte: Some(10),
3031            // Cost params for the Move native function `borrow_child_object_mut<Child: key>(parent: &mut UID, id: address): &mut Child`
3032            dynamic_field_borrow_child_object_cost_base: Some(100),
3033            dynamic_field_borrow_child_object_child_ref_cost_per_byte: Some(10),
3034            dynamic_field_borrow_child_object_type_cost_per_byte: Some(10),
3035            // Cost params for the Move native function `remove_child_object<Child: key>(parent: address, id: address): Child`
3036            dynamic_field_remove_child_object_cost_base: Some(100),
3037            dynamic_field_remove_child_object_child_cost_per_byte: Some(2),
3038            dynamic_field_remove_child_object_type_cost_per_byte: Some(2),
3039            // Cost params for the Move native function `has_child_object(parent: address, id: address): bool`
3040            dynamic_field_has_child_object_cost_base: Some(100),
3041            // Cost params for the Move native function `has_child_object_with_ty<Child: key>(parent: address, id: address): bool`
3042            dynamic_field_has_child_object_with_ty_cost_base: Some(100),
3043            dynamic_field_has_child_object_with_ty_type_cost_per_byte: Some(2),
3044            dynamic_field_has_child_object_with_ty_type_tag_cost_per_byte: Some(2),
3045
3046            // `event` module
3047            // Cost params for the Move native function `event::emit<T: copy + drop>(event: T)`
3048            event_emit_cost_base: Some(52),
3049            event_emit_value_size_derivation_cost_per_byte: Some(2),
3050            event_emit_tag_size_derivation_cost_per_byte: Some(5),
3051            event_emit_output_cost_per_byte: Some(10),
3052            event_emit_auth_stream_cost: None,
3053
3054            //  `object` module
3055            // Cost params for the Move native function `borrow_uid<T: key>(obj: &T): &UID`
3056            object_borrow_uid_cost_base: Some(52),
3057            // Cost params for the Move native function `delete_impl(id: address)`
3058            object_delete_impl_cost_base: Some(52),
3059            // Cost params for the Move native function `record_new_uid(id: address)`
3060            object_record_new_uid_cost_base: Some(52),
3061
3062            // `transfer` module
3063            // Cost params for the Move native function `transfer_impl<T: key>(obj: T, recipient: address)`
3064            transfer_transfer_internal_cost_base: Some(52),
3065            // Cost params for the Move native function `party_transfer_impl<T: key>(obj: T, party_members: vector<address>)`
3066            transfer_party_transfer_internal_cost_base: None,
3067            // Cost params for the Move native function `freeze_object<T: key>(obj: T)`
3068            transfer_freeze_object_cost_base: Some(52),
3069            // Cost params for the Move native function `share_object<T: key>(obj: T)`
3070            transfer_share_object_cost_base: Some(52),
3071            transfer_receive_object_cost_base: None,
3072            transfer_receive_object_type_cost_per_byte: None,
3073            transfer_receive_object_cost_per_byte: None,
3074
3075            // `tx_context` module
3076            // Cost params for the Move native function `transfer_impl<T: key>(obj: T, recipient: address)`
3077            tx_context_derive_id_cost_base: Some(52),
3078            tx_context_fresh_id_cost_base: None,
3079            tx_context_sender_cost_base: None,
3080            tx_context_epoch_cost_base: None,
3081            tx_context_epoch_timestamp_ms_cost_base: None,
3082            tx_context_sponsor_cost_base: None,
3083            tx_context_rgp_cost_base: None,
3084            tx_context_gas_price_cost_base: None,
3085            tx_context_gas_budget_cost_base: None,
3086            tx_context_ids_created_cost_base: None,
3087            tx_context_replace_cost_base: None,
3088
3089            // `types` module
3090            // Cost params for the Move native function `is_one_time_witness<T: drop>(_: &T): bool`
3091            types_is_one_time_witness_cost_base: Some(52),
3092            types_is_one_time_witness_type_tag_cost_per_byte: Some(2),
3093            types_is_one_time_witness_type_cost_per_byte: Some(2),
3094
3095            // `validator` module
3096            // Cost params for the Move native function `validate_metadata_bcs(metadata: vector<u8>)`
3097            validator_validate_metadata_cost_base: Some(52),
3098            validator_validate_metadata_data_cost_per_byte: Some(2),
3099
3100            // Crypto
3101            crypto_invalid_arguments_cost: Some(100),
3102            // bls12381::bls12381_min_pk_verify
3103            bls12381_bls12381_min_sig_verify_cost_base: Some(52),
3104            bls12381_bls12381_min_sig_verify_msg_cost_per_byte: Some(2),
3105            bls12381_bls12381_min_sig_verify_msg_cost_per_block: Some(2),
3106
3107            // bls12381::bls12381_min_pk_verify
3108            bls12381_bls12381_min_pk_verify_cost_base: Some(52),
3109            bls12381_bls12381_min_pk_verify_msg_cost_per_byte: Some(2),
3110            bls12381_bls12381_min_pk_verify_msg_cost_per_block: Some(2),
3111
3112            // ecdsa_k1::ecrecover
3113            ecdsa_k1_ecrecover_keccak256_cost_base: Some(52),
3114            ecdsa_k1_ecrecover_keccak256_msg_cost_per_byte: Some(2),
3115            ecdsa_k1_ecrecover_keccak256_msg_cost_per_block: Some(2),
3116            ecdsa_k1_ecrecover_sha256_cost_base: Some(52),
3117            ecdsa_k1_ecrecover_sha256_msg_cost_per_byte: Some(2),
3118            ecdsa_k1_ecrecover_sha256_msg_cost_per_block: Some(2),
3119
3120            // ecdsa_k1::decompress_pubkey
3121            ecdsa_k1_decompress_pubkey_cost_base: Some(52),
3122
3123            // ecdsa_k1::secp256k1_verify
3124            ecdsa_k1_secp256k1_verify_keccak256_cost_base: Some(52),
3125            ecdsa_k1_secp256k1_verify_keccak256_msg_cost_per_byte: Some(2),
3126            ecdsa_k1_secp256k1_verify_keccak256_msg_cost_per_block: Some(2),
3127            ecdsa_k1_secp256k1_verify_sha256_cost_base: Some(52),
3128            ecdsa_k1_secp256k1_verify_sha256_msg_cost_per_byte: Some(2),
3129            ecdsa_k1_secp256k1_verify_sha256_msg_cost_per_block: Some(2),
3130
3131            // ecdsa_r1::ecrecover
3132            ecdsa_r1_ecrecover_keccak256_cost_base: Some(52),
3133            ecdsa_r1_ecrecover_keccak256_msg_cost_per_byte: Some(2),
3134            ecdsa_r1_ecrecover_keccak256_msg_cost_per_block: Some(2),
3135            ecdsa_r1_ecrecover_sha256_cost_base: Some(52),
3136            ecdsa_r1_ecrecover_sha256_msg_cost_per_byte: Some(2),
3137            ecdsa_r1_ecrecover_sha256_msg_cost_per_block: Some(2),
3138
3139            // ecdsa_r1::secp256k1_verify
3140            ecdsa_r1_secp256r1_verify_keccak256_cost_base: Some(52),
3141            ecdsa_r1_secp256r1_verify_keccak256_msg_cost_per_byte: Some(2),
3142            ecdsa_r1_secp256r1_verify_keccak256_msg_cost_per_block: Some(2),
3143            ecdsa_r1_secp256r1_verify_sha256_cost_base: Some(52),
3144            ecdsa_r1_secp256r1_verify_sha256_msg_cost_per_byte: Some(2),
3145            ecdsa_r1_secp256r1_verify_sha256_msg_cost_per_block: Some(2),
3146
3147            // ecvrf::verify
3148            ecvrf_ecvrf_verify_cost_base: Some(52),
3149            ecvrf_ecvrf_verify_alpha_string_cost_per_byte: Some(2),
3150            ecvrf_ecvrf_verify_alpha_string_cost_per_block: Some(2),
3151
3152            // ed25519
3153            ed25519_ed25519_verify_cost_base: Some(52),
3154            ed25519_ed25519_verify_msg_cost_per_byte: Some(2),
3155            ed25519_ed25519_verify_msg_cost_per_block: Some(2),
3156
3157            // groth16::prepare_verifying_key
3158            groth16_prepare_verifying_key_bls12381_cost_base: Some(52),
3159            groth16_prepare_verifying_key_bn254_cost_base: Some(52),
3160
3161            // groth16::verify_groth16_proof_internal
3162            groth16_verify_groth16_proof_internal_bls12381_cost_base: Some(52),
3163            groth16_verify_groth16_proof_internal_bls12381_cost_per_public_input: Some(2),
3164            groth16_verify_groth16_proof_internal_bn254_cost_base: Some(52),
3165            groth16_verify_groth16_proof_internal_bn254_cost_per_public_input: Some(2),
3166            groth16_verify_groth16_proof_internal_public_input_cost_per_byte: Some(2),
3167
3168            // hash::blake2b256
3169            hash_blake2b256_cost_base: Some(52),
3170            hash_blake2b256_data_cost_per_byte: Some(2),
3171            hash_blake2b256_data_cost_per_block: Some(2),
3172
3173            // hash::keccak256
3174            hash_keccak256_cost_base: Some(52),
3175            hash_keccak256_data_cost_per_byte: Some(2),
3176            hash_keccak256_data_cost_per_block: Some(2),
3177
3178            poseidon_bn254_cost_base: None,
3179            poseidon_bn254_cost_per_block: None,
3180
3181            // hmac::hmac_sha3_256
3182            hmac_hmac_sha3_256_cost_base: Some(52),
3183            hmac_hmac_sha3_256_input_cost_per_byte: Some(2),
3184            hmac_hmac_sha3_256_input_cost_per_block: Some(2),
3185
3186            // group ops
3187            group_ops_bls12381_decode_scalar_cost: None,
3188            group_ops_bls12381_decode_g1_cost: None,
3189            group_ops_bls12381_decode_g2_cost: None,
3190            group_ops_bls12381_decode_gt_cost: None,
3191            group_ops_bls12381_scalar_add_cost: None,
3192            group_ops_bls12381_g1_add_cost: None,
3193            group_ops_bls12381_g2_add_cost: None,
3194            group_ops_bls12381_gt_add_cost: None,
3195            group_ops_bls12381_scalar_sub_cost: None,
3196            group_ops_bls12381_g1_sub_cost: None,
3197            group_ops_bls12381_g2_sub_cost: None,
3198            group_ops_bls12381_gt_sub_cost: None,
3199            group_ops_bls12381_scalar_mul_cost: None,
3200            group_ops_bls12381_g1_mul_cost: None,
3201            group_ops_bls12381_g2_mul_cost: None,
3202            group_ops_bls12381_gt_mul_cost: None,
3203            group_ops_bls12381_scalar_div_cost: None,
3204            group_ops_bls12381_g1_div_cost: None,
3205            group_ops_bls12381_g2_div_cost: None,
3206            group_ops_bls12381_gt_div_cost: None,
3207            group_ops_bls12381_g1_hash_to_base_cost: None,
3208            group_ops_bls12381_g2_hash_to_base_cost: None,
3209            group_ops_bls12381_g1_hash_to_cost_per_byte: None,
3210            group_ops_bls12381_g2_hash_to_cost_per_byte: None,
3211            group_ops_bls12381_g1_msm_base_cost: None,
3212            group_ops_bls12381_g2_msm_base_cost: None,
3213            group_ops_bls12381_g1_msm_base_cost_per_input: None,
3214            group_ops_bls12381_g2_msm_base_cost_per_input: None,
3215            group_ops_bls12381_msm_max_len: None,
3216            group_ops_bls12381_pairing_cost: None,
3217            group_ops_bls12381_g1_to_uncompressed_g1_cost: None,
3218            group_ops_bls12381_uncompressed_g1_to_g1_cost: None,
3219            group_ops_bls12381_uncompressed_g1_sum_base_cost: None,
3220            group_ops_bls12381_uncompressed_g1_sum_cost_per_term: None,
3221            group_ops_bls12381_uncompressed_g1_sum_max_terms: None,
3222
3223            group_ops_ristretto_decode_scalar_cost: None,
3224            group_ops_ristretto_decode_point_cost: None,
3225            group_ops_ristretto_scalar_add_cost: None,
3226            group_ops_ristretto_point_add_cost: None,
3227            group_ops_ristretto_scalar_sub_cost: None,
3228            group_ops_ristretto_point_sub_cost: None,
3229            group_ops_ristretto_scalar_mul_cost: None,
3230            group_ops_ristretto_point_mul_cost: None,
3231            group_ops_ristretto_scalar_div_cost: None,
3232            group_ops_ristretto_point_div_cost: None,
3233
3234            verify_bulletproofs_ristretto255_base_cost: None,
3235            verify_bulletproofs_ristretto255_cost_per_bit_and_commitment: None,
3236
3237            // zklogin::check_zklogin_id
3238            check_zklogin_id_cost_base: None,
3239            // zklogin::check_zklogin_issuer
3240            check_zklogin_issuer_cost_base: None,
3241
3242            vdf_verify_vdf_cost: None,
3243            vdf_hash_to_input_cost: None,
3244
3245            // nitro_attestation::verify_nitro_attestation
3246            nitro_attestation_parse_base_cost: None,
3247            nitro_attestation_parse_cost_per_byte: None,
3248            nitro_attestation_verify_base_cost: None,
3249            nitro_attestation_verify_cost_per_cert: None,
3250
3251            bcs_per_byte_serialized_cost: None,
3252            bcs_legacy_min_output_size_cost: None,
3253            bcs_failure_cost: None,
3254            hash_sha2_256_base_cost: None,
3255            hash_sha2_256_per_byte_cost: None,
3256            hash_sha2_256_legacy_min_input_len_cost: None,
3257            hash_sha3_256_base_cost: None,
3258            hash_sha3_256_per_byte_cost: None,
3259            hash_sha3_256_legacy_min_input_len_cost: None,
3260            type_name_get_base_cost: None,
3261            type_name_get_per_byte_cost: None,
3262            type_name_id_base_cost: None,
3263            string_check_utf8_base_cost: None,
3264            string_check_utf8_per_byte_cost: None,
3265            string_is_char_boundary_base_cost: None,
3266            string_sub_string_base_cost: None,
3267            string_sub_string_per_byte_cost: None,
3268            string_index_of_base_cost: None,
3269            string_index_of_per_byte_pattern_cost: None,
3270            string_index_of_per_byte_searched_cost: None,
3271            vector_empty_base_cost: None,
3272            vector_length_base_cost: None,
3273            vector_push_back_base_cost: None,
3274            vector_push_back_legacy_per_abstract_memory_unit_cost: None,
3275            vector_borrow_base_cost: None,
3276            vector_pop_back_base_cost: None,
3277            vector_destroy_empty_base_cost: None,
3278            vector_swap_base_cost: None,
3279            debug_print_base_cost: None,
3280            debug_print_stack_trace_base_cost: None,
3281
3282            max_size_written_objects: None,
3283            max_size_written_objects_system_tx: None,
3284
3285            // ==== Ephemeral (consensus only) params deleted ====
3286            // Const params for consensus scoring decision
3287            // scoring_decision_mad_divisor: None,
3288            // scoring_decision_cutoff_value: None,
3289
3290            // Limits the length of a Move identifier
3291            max_move_identifier_len: None,
3292            max_move_value_depth: None,
3293            max_move_enum_variants: None,
3294
3295            gas_rounding_step: None,
3296
3297            execution_version: None,
3298
3299            max_event_emit_size_total: None,
3300
3301            consensus_bad_nodes_stake_threshold: None,
3302
3303            max_jwk_votes_per_validator_per_epoch: None,
3304
3305            max_age_of_jwk_in_epochs: None,
3306
3307            random_beacon_reduction_allowed_delta: None,
3308
3309            random_beacon_reduction_lower_bound: None,
3310
3311            random_beacon_dkg_timeout_round: None,
3312
3313            random_beacon_min_round_interval_ms: None,
3314
3315            random_beacon_dkg_version: None,
3316
3317            consensus_max_transaction_size_bytes: None,
3318
3319            consensus_max_transactions_in_block_bytes: None,
3320
3321            consensus_max_num_transactions_in_block: None,
3322
3323            consensus_voting_rounds: None,
3324
3325            max_accumulated_txn_cost_per_object_in_narwhal_commit: None,
3326
3327            max_deferral_rounds_for_congestion_control: None,
3328
3329            max_txn_cost_overage_per_object_in_commit: None,
3330
3331            allowed_txn_cost_overage_burst_per_object_in_commit: None,
3332
3333            min_checkpoint_interval_ms: None,
3334
3335            checkpoint_summary_version_specific_data: None,
3336
3337            max_soft_bundle_size: None,
3338
3339            bridge_should_try_to_finalize_committee: None,
3340
3341            max_accumulated_txn_cost_per_object_in_mysticeti_commit: None,
3342
3343            max_accumulated_randomness_txn_cost_per_object_in_mysticeti_commit: None,
3344
3345            consensus_gc_depth: None,
3346
3347            gas_budget_based_txn_cost_cap_factor: None,
3348
3349            gas_budget_based_txn_cost_absolute_cap_commit_count: None,
3350
3351            sip_45_consensus_amplification_threshold: None,
3352
3353            use_object_per_epoch_marker_table_v2: None,
3354
3355            consensus_commit_rate_estimation_window_size: None,
3356
3357            aliased_addresses: vec![],
3358
3359            translation_per_command_base_charge: None,
3360            translation_per_input_base_charge: None,
3361            translation_pure_input_per_byte_charge: None,
3362            translation_per_type_node_charge: None,
3363            translation_per_reference_node_charge: None,
3364            translation_per_linkage_entry_charge: None,
3365
3366            max_updates_per_settlement_txn: None,
3367
3368            gasless_max_computation_units: None,
3369            gasless_allowed_token_types: None,
3370            gasless_max_unused_inputs: None,
3371            gasless_max_pure_input_bytes: None,
3372            gasless_max_tps: None,
3373            include_special_package_amendments: None,
3374            // When adding a new constant, set it to None in the earliest version, like this:
3375            // new_constant: None,
3376        };
3377        for cur in 2..=version.0 {
3378            match cur {
3379                1 => unreachable!(),
3380                2 => {
3381                    cfg.feature_flags.advance_epoch_start_time_in_safe_mode = true;
3382                }
3383                3 => {
3384                    // changes for gas model
3385                    cfg.gas_model_version = Some(2);
3386                    // max gas budget is in MIST and an absolute value 50SUI
3387                    cfg.max_tx_gas = Some(50_000_000_000);
3388                    // min gas budget is in MIST and an absolute value 2000MIST or 0.000002SUI
3389                    cfg.base_tx_cost_fixed = Some(2_000);
3390                    // storage gas price multiplier
3391                    cfg.storage_gas_price = Some(76);
3392                    cfg.feature_flags.loaded_child_objects_fixed = true;
3393                    // max size of written objects during a TXn
3394                    // this is a sum of all objects written during a TXn
3395                    cfg.max_size_written_objects = Some(5 * 1000 * 1000);
3396                    // max size of written objects during a system TXn to allow for larger writes
3397                    // akin to `max_size_written_objects` but for system TXns
3398                    cfg.max_size_written_objects_system_tx = Some(50 * 1000 * 1000);
3399                    cfg.feature_flags.package_upgrades = true;
3400                }
3401                // This is the first protocol version currently possible.
3402                // Mainnet starts with version 4. Previous versions are pre mainnet and have
3403                // all been wiped out.
3404                // Every other chain is after version 4.
3405                4 => {
3406                    // Change reward slashing rate to 100%.
3407                    cfg.reward_slashing_rate = Some(10000);
3408                    // protect old and new lookup for object version
3409                    cfg.gas_model_version = Some(3);
3410                }
3411                5 => {
3412                    cfg.feature_flags.missing_type_is_compatibility_error = true;
3413                    cfg.gas_model_version = Some(4);
3414                    cfg.feature_flags.scoring_decision_with_validity_cutoff = true;
3415                    // ==== Ephemeral (consensus only) params deleted ====
3416                    // cfg.scoring_decision_mad_divisor = Some(2.3);
3417                    // cfg.scoring_decision_cutoff_value = Some(2.5);
3418                }
3419                6 => {
3420                    cfg.gas_model_version = Some(5);
3421                    cfg.buffer_stake_for_protocol_upgrade_bps = Some(5000);
3422                    cfg.feature_flags.consensus_order_end_of_epoch_last = true;
3423                }
3424                7 => {
3425                    cfg.feature_flags.disallow_adding_abilities_on_upgrade = true;
3426                    cfg.feature_flags
3427                        .disable_invariant_violation_check_in_swap_loc = true;
3428                    cfg.feature_flags.ban_entry_init = true;
3429                    cfg.feature_flags.package_digest_hash_module = true;
3430                }
3431                8 => {
3432                    cfg.feature_flags
3433                        .disallow_change_struct_type_params_on_upgrade = true;
3434                }
3435                9 => {
3436                    // Limits the length of a Move identifier
3437                    cfg.max_move_identifier_len = Some(128);
3438                    cfg.feature_flags.no_extraneous_module_bytes = true;
3439                    cfg.feature_flags
3440                        .advance_to_highest_supported_protocol_version = true;
3441                }
3442                10 => {
3443                    cfg.max_verifier_meter_ticks_per_function = Some(16_000_000);
3444                    cfg.max_meter_ticks_per_module = Some(16_000_000);
3445                }
3446                11 => {
3447                    cfg.max_move_value_depth = Some(128);
3448                }
3449                12 => {
3450                    cfg.feature_flags.narwhal_versioned_metadata = true;
3451                    if chain != Chain::Mainnet {
3452                        cfg.feature_flags.commit_root_state_digest = true;
3453                    }
3454
3455                    if chain != Chain::Mainnet && chain != Chain::Testnet {
3456                        cfg.feature_flags.zklogin_auth = true;
3457                    }
3458                }
3459                13 => {}
3460                14 => {
3461                    cfg.gas_rounding_step = Some(1_000);
3462                    cfg.gas_model_version = Some(6);
3463                }
3464                15 => {
3465                    cfg.feature_flags.consensus_transaction_ordering =
3466                        ConsensusTransactionOrdering::ByGasPrice;
3467                }
3468                16 => {
3469                    cfg.feature_flags.simplified_unwrap_then_delete = true;
3470                }
3471                17 => {
3472                    cfg.feature_flags.upgraded_multisig_supported = true;
3473                }
3474                18 => {
3475                    cfg.execution_version = Some(1);
3476                    // Following flags are implied by this execution version.  Once support for earlier
3477                    // protocol versions is dropped, these flags can be removed:
3478                    // cfg.feature_flags.package_upgrades = true;
3479                    // cfg.feature_flags.disallow_adding_abilities_on_upgrade = true;
3480                    // cfg.feature_flags.disallow_change_struct_type_params_on_upgrade = true;
3481                    // cfg.feature_flags.loaded_child_objects_fixed = true;
3482                    // cfg.feature_flags.ban_entry_init = true;
3483                    // cfg.feature_flags.pack_digest_hash_modules = true;
3484                    cfg.feature_flags.txn_base_cost_as_multiplier = true;
3485                    // this is a multiplier of the gas price
3486                    cfg.base_tx_cost_fixed = Some(1_000);
3487                }
3488                19 => {
3489                    cfg.max_num_event_emit = Some(1024);
3490                    // We maintain the same total size limit for events, but increase the number of
3491                    // events that can be emitted.
3492                    cfg.max_event_emit_size_total = Some(
3493                        256 /* former event count limit */ * 250 * 1024, /* size limit per event */
3494                    );
3495                }
3496                20 => {
3497                    cfg.feature_flags.commit_root_state_digest = true;
3498
3499                    if chain != Chain::Mainnet {
3500                        cfg.feature_flags.narwhal_new_leader_election_schedule = true;
3501                        cfg.consensus_bad_nodes_stake_threshold = Some(20);
3502                    }
3503                }
3504
3505                21 => {
3506                    if chain != Chain::Mainnet {
3507                        cfg.feature_flags.zklogin_supported_providers = BTreeSet::from([
3508                            "Google".to_string(),
3509                            "Facebook".to_string(),
3510                            "Twitch".to_string(),
3511                        ]);
3512                    }
3513                }
3514                22 => {
3515                    cfg.feature_flags.loaded_child_object_format = true;
3516                }
3517                23 => {
3518                    cfg.feature_flags.loaded_child_object_format_type = true;
3519                    cfg.feature_flags.narwhal_new_leader_election_schedule = true;
3520                    // Taking a baby step approach, we consider only 20% by stake as bad nodes so we
3521                    // have a 80% by stake of nodes participating in the leader committee. That allow
3522                    // us for more redundancy in case we have validators under performing - since the
3523                    // responsibility is shared amongst more nodes. We can increase that once we do have
3524                    // higher confidence.
3525                    cfg.consensus_bad_nodes_stake_threshold = Some(20);
3526                }
3527                24 => {
3528                    cfg.feature_flags.simple_conservation_checks = true;
3529                    cfg.max_publish_or_upgrade_per_ptb = Some(5);
3530
3531                    cfg.feature_flags.end_of_epoch_transaction_supported = true;
3532
3533                    if chain != Chain::Mainnet {
3534                        cfg.feature_flags.enable_jwk_consensus_updates = true;
3535                        // Max of 10 votes per hour
3536                        cfg.max_jwk_votes_per_validator_per_epoch = Some(240);
3537                        cfg.max_age_of_jwk_in_epochs = Some(1);
3538                    }
3539                }
3540                25 => {
3541                    // Enable zkLogin for all providers in all networks.
3542                    cfg.feature_flags.zklogin_supported_providers = BTreeSet::from([
3543                        "Google".to_string(),
3544                        "Facebook".to_string(),
3545                        "Twitch".to_string(),
3546                    ]);
3547                    cfg.feature_flags.zklogin_auth = true;
3548
3549                    // Enable jwk consensus updates
3550                    cfg.feature_flags.enable_jwk_consensus_updates = true;
3551                    cfg.max_jwk_votes_per_validator_per_epoch = Some(240);
3552                    cfg.max_age_of_jwk_in_epochs = Some(1);
3553                }
3554                26 => {
3555                    cfg.gas_model_version = Some(7);
3556                    // Only enable receiving objects in devnet
3557                    if chain != Chain::Mainnet && chain != Chain::Testnet {
3558                        cfg.transfer_receive_object_cost_base = Some(52);
3559                        cfg.feature_flags.receive_objects = true;
3560                    }
3561                }
3562                27 => {
3563                    cfg.gas_model_version = Some(8);
3564                }
3565                28 => {
3566                    // zklogin::check_zklogin_id
3567                    cfg.check_zklogin_id_cost_base = Some(200);
3568                    // zklogin::check_zklogin_issuer
3569                    cfg.check_zklogin_issuer_cost_base = Some(200);
3570
3571                    // Only enable effects v2 on devnet.
3572                    if chain != Chain::Mainnet && chain != Chain::Testnet {
3573                        cfg.feature_flags.enable_effects_v2 = true;
3574                    }
3575                }
3576                29 => {
3577                    cfg.feature_flags.verify_legacy_zklogin_address = true;
3578                }
3579                30 => {
3580                    // Only enable nw certificate v2 on testnet.
3581                    if chain != Chain::Mainnet {
3582                        cfg.feature_flags.narwhal_certificate_v2 = true;
3583                    }
3584
3585                    cfg.random_beacon_reduction_allowed_delta = Some(800);
3586                    // Only enable effects v2 on devnet and testnet.
3587                    if chain != Chain::Mainnet {
3588                        cfg.feature_flags.enable_effects_v2 = true;
3589                    }
3590
3591                    // zklogin_supported_providers config is deprecated, zklogin
3592                    // signature verifier will use the fetched jwk map to determine
3593                    // whether the provider is supported based on node config.
3594                    cfg.feature_flags.zklogin_supported_providers = BTreeSet::default();
3595
3596                    cfg.feature_flags.recompute_has_public_transfer_in_execution = true;
3597                }
3598                31 => {
3599                    cfg.execution_version = Some(2);
3600                    // Only enable shared object deletion on devnet
3601                    if chain != Chain::Mainnet && chain != Chain::Testnet {
3602                        cfg.feature_flags.shared_object_deletion = true;
3603                    }
3604                }
3605                32 => {
3606                    // enable zklogin in multisig in devnet and testnet
3607                    if chain != Chain::Mainnet {
3608                        cfg.feature_flags.accept_zklogin_in_multisig = true;
3609                    }
3610                    // enable receiving objects in devnet and testnet
3611                    if chain != Chain::Mainnet {
3612                        cfg.transfer_receive_object_cost_base = Some(52);
3613                        cfg.feature_flags.receive_objects = true;
3614                    }
3615                    // Only enable random beacon on devnet
3616                    if chain != Chain::Mainnet && chain != Chain::Testnet {
3617                        cfg.feature_flags.random_beacon = true;
3618                        cfg.random_beacon_reduction_lower_bound = Some(1600);
3619                        cfg.random_beacon_dkg_timeout_round = Some(3000);
3620                        cfg.random_beacon_min_round_interval_ms = Some(150);
3621                    }
3622                    // Only enable consensus digest in consensus commit prologue in devnet.
3623                    if chain != Chain::Testnet && chain != Chain::Mainnet {
3624                        cfg.feature_flags.include_consensus_digest_in_prologue = true;
3625                    }
3626
3627                    // enable nw cert v2 on mainnet
3628                    cfg.feature_flags.narwhal_certificate_v2 = true;
3629                }
3630                33 => {
3631                    cfg.feature_flags.hardened_otw_check = true;
3632                    cfg.feature_flags.allow_receiving_object_id = true;
3633
3634                    // Enable transfer-to-object in mainnet
3635                    cfg.transfer_receive_object_cost_base = Some(52);
3636                    cfg.feature_flags.receive_objects = true;
3637
3638                    // Enable shared object deletion in testnet and devnet
3639                    if chain != Chain::Mainnet {
3640                        cfg.feature_flags.shared_object_deletion = true;
3641                    }
3642
3643                    cfg.feature_flags.enable_effects_v2 = true;
3644                }
3645                34 => {}
3646                35 => {
3647                    // Add costs for poseidon::poseidon_bn254
3648                    if chain != Chain::Mainnet && chain != Chain::Testnet {
3649                        cfg.feature_flags.enable_poseidon = true;
3650                        cfg.poseidon_bn254_cost_base = Some(260);
3651                        cfg.poseidon_bn254_cost_per_block = Some(10);
3652                    }
3653
3654                    cfg.feature_flags.enable_coin_deny_list = true;
3655                }
3656                36 => {
3657                    // Only enable group ops on devnet
3658                    if chain != Chain::Mainnet && chain != Chain::Testnet {
3659                        cfg.feature_flags.enable_group_ops_native_functions = true;
3660                        cfg.feature_flags.enable_group_ops_native_function_msm = true;
3661                        // Next values are arbitrary in a similar way as the other crypto native functions.
3662                        cfg.group_ops_bls12381_decode_scalar_cost = Some(52);
3663                        cfg.group_ops_bls12381_decode_g1_cost = Some(52);
3664                        cfg.group_ops_bls12381_decode_g2_cost = Some(52);
3665                        cfg.group_ops_bls12381_decode_gt_cost = Some(52);
3666                        cfg.group_ops_bls12381_scalar_add_cost = Some(52);
3667                        cfg.group_ops_bls12381_g1_add_cost = Some(52);
3668                        cfg.group_ops_bls12381_g2_add_cost = Some(52);
3669                        cfg.group_ops_bls12381_gt_add_cost = Some(52);
3670                        cfg.group_ops_bls12381_scalar_sub_cost = Some(52);
3671                        cfg.group_ops_bls12381_g1_sub_cost = Some(52);
3672                        cfg.group_ops_bls12381_g2_sub_cost = Some(52);
3673                        cfg.group_ops_bls12381_gt_sub_cost = Some(52);
3674                        cfg.group_ops_bls12381_scalar_mul_cost = Some(52);
3675                        cfg.group_ops_bls12381_g1_mul_cost = Some(52);
3676                        cfg.group_ops_bls12381_g2_mul_cost = Some(52);
3677                        cfg.group_ops_bls12381_gt_mul_cost = Some(52);
3678                        cfg.group_ops_bls12381_scalar_div_cost = Some(52);
3679                        cfg.group_ops_bls12381_g1_div_cost = Some(52);
3680                        cfg.group_ops_bls12381_g2_div_cost = Some(52);
3681                        cfg.group_ops_bls12381_gt_div_cost = Some(52);
3682                        cfg.group_ops_bls12381_g1_hash_to_base_cost = Some(52);
3683                        cfg.group_ops_bls12381_g2_hash_to_base_cost = Some(52);
3684                        cfg.group_ops_bls12381_g1_hash_to_cost_per_byte = Some(2);
3685                        cfg.group_ops_bls12381_g2_hash_to_cost_per_byte = Some(2);
3686                        cfg.group_ops_bls12381_g1_msm_base_cost = Some(52);
3687                        cfg.group_ops_bls12381_g2_msm_base_cost = Some(52);
3688                        cfg.group_ops_bls12381_g1_msm_base_cost_per_input = Some(52);
3689                        cfg.group_ops_bls12381_g2_msm_base_cost_per_input = Some(52);
3690                        cfg.group_ops_bls12381_msm_max_len = Some(32);
3691                        cfg.group_ops_bls12381_pairing_cost = Some(52);
3692                    }
3693                    // Enable shared object deletion on all networks.
3694                    cfg.feature_flags.shared_object_deletion = true;
3695
3696                    cfg.consensus_max_transaction_size_bytes = Some(256 * 1024); // 256KB
3697                    cfg.consensus_max_transactions_in_block_bytes = Some(6 * 1_024 * 1024);
3698                    // 6 MB
3699                }
3700                37 => {
3701                    cfg.feature_flags.reject_mutable_random_on_entry_functions = true;
3702
3703                    // Enable consensus digest in consensus commit prologue in testnet and devnet.
3704                    if chain != Chain::Mainnet {
3705                        cfg.feature_flags.include_consensus_digest_in_prologue = true;
3706                    }
3707                }
3708                38 => {
3709                    cfg.binary_module_handles = Some(100);
3710                    cfg.binary_struct_handles = Some(300);
3711                    cfg.binary_function_handles = Some(1500);
3712                    cfg.binary_function_instantiations = Some(750);
3713                    cfg.binary_signatures = Some(1000);
3714                    // constants and identifiers are proportional to the binary size,
3715                    // and they vastly depend on the code, so we are leaving them
3716                    // reasonably high
3717                    cfg.binary_constant_pool = Some(4000);
3718                    cfg.binary_identifiers = Some(10000);
3719                    cfg.binary_address_identifiers = Some(100);
3720                    cfg.binary_struct_defs = Some(200);
3721                    cfg.binary_struct_def_instantiations = Some(100);
3722                    cfg.binary_function_defs = Some(1000);
3723                    cfg.binary_field_handles = Some(500);
3724                    cfg.binary_field_instantiations = Some(250);
3725                    cfg.binary_friend_decls = Some(100);
3726                    // reduce dependencies maximum
3727                    cfg.max_package_dependencies = Some(32);
3728                    cfg.max_modules_in_publish = Some(64);
3729                    // bump execution version
3730                    cfg.execution_version = Some(3);
3731                }
3732                39 => {
3733                    // It is important that we keep this protocol version blank due to an issue with random.move.
3734                }
3735                40 => {}
3736                41 => {
3737                    // Enable group ops and all networks (but not msm)
3738                    cfg.feature_flags.enable_group_ops_native_functions = true;
3739                    // Next values are arbitrary in a similar way as the other crypto native functions.
3740                    cfg.group_ops_bls12381_decode_scalar_cost = Some(52);
3741                    cfg.group_ops_bls12381_decode_g1_cost = Some(52);
3742                    cfg.group_ops_bls12381_decode_g2_cost = Some(52);
3743                    cfg.group_ops_bls12381_decode_gt_cost = Some(52);
3744                    cfg.group_ops_bls12381_scalar_add_cost = Some(52);
3745                    cfg.group_ops_bls12381_g1_add_cost = Some(52);
3746                    cfg.group_ops_bls12381_g2_add_cost = Some(52);
3747                    cfg.group_ops_bls12381_gt_add_cost = Some(52);
3748                    cfg.group_ops_bls12381_scalar_sub_cost = Some(52);
3749                    cfg.group_ops_bls12381_g1_sub_cost = Some(52);
3750                    cfg.group_ops_bls12381_g2_sub_cost = Some(52);
3751                    cfg.group_ops_bls12381_gt_sub_cost = Some(52);
3752                    cfg.group_ops_bls12381_scalar_mul_cost = Some(52);
3753                    cfg.group_ops_bls12381_g1_mul_cost = Some(52);
3754                    cfg.group_ops_bls12381_g2_mul_cost = Some(52);
3755                    cfg.group_ops_bls12381_gt_mul_cost = Some(52);
3756                    cfg.group_ops_bls12381_scalar_div_cost = Some(52);
3757                    cfg.group_ops_bls12381_g1_div_cost = Some(52);
3758                    cfg.group_ops_bls12381_g2_div_cost = Some(52);
3759                    cfg.group_ops_bls12381_gt_div_cost = Some(52);
3760                    cfg.group_ops_bls12381_g1_hash_to_base_cost = Some(52);
3761                    cfg.group_ops_bls12381_g2_hash_to_base_cost = Some(52);
3762                    cfg.group_ops_bls12381_g1_hash_to_cost_per_byte = Some(2);
3763                    cfg.group_ops_bls12381_g2_hash_to_cost_per_byte = Some(2);
3764                    cfg.group_ops_bls12381_g1_msm_base_cost = Some(52);
3765                    cfg.group_ops_bls12381_g2_msm_base_cost = Some(52);
3766                    cfg.group_ops_bls12381_g1_msm_base_cost_per_input = Some(52);
3767                    cfg.group_ops_bls12381_g2_msm_base_cost_per_input = Some(52);
3768                    cfg.group_ops_bls12381_msm_max_len = Some(32);
3769                    cfg.group_ops_bls12381_pairing_cost = Some(52);
3770                }
3771                42 => {}
3772                43 => {
3773                    cfg.feature_flags.zklogin_max_epoch_upper_bound_delta = Some(30);
3774                    cfg.max_meter_ticks_per_package = Some(16_000_000);
3775                }
3776                44 => {
3777                    // Enable consensus digest in consensus commit prologue on all networks..
3778                    cfg.feature_flags.include_consensus_digest_in_prologue = true;
3779                    // Switch between Narwhal and Mysticeti per epoch in tests, devnet and testnet.
3780                    if chain != Chain::Mainnet {
3781                        cfg.feature_flags.consensus_choice = ConsensusChoice::SwapEachEpoch;
3782                    }
3783                }
3784                45 => {
3785                    // Use tonic networking for consensus, in tests and devnet.
3786                    if chain != Chain::Testnet && chain != Chain::Mainnet {
3787                        cfg.feature_flags.consensus_network = ConsensusNetwork::Tonic;
3788                    }
3789
3790                    if chain != Chain::Mainnet {
3791                        // Enable leader scoring & schedule change on testnet for mysticeti.
3792                        cfg.feature_flags.mysticeti_leader_scoring_and_schedule = true;
3793                    }
3794                    cfg.min_move_binary_format_version = Some(6);
3795                    cfg.feature_flags.accept_zklogin_in_multisig = true;
3796
3797                    // Also bumps framework snapshot to fix binop issue.
3798
3799                    // enable bridge in devnet
3800                    if chain != Chain::Mainnet && chain != Chain::Testnet {
3801                        cfg.feature_flags.bridge = true;
3802                    }
3803                }
3804                46 => {
3805                    // enable bridge in devnet and testnet
3806                    if chain != Chain::Mainnet {
3807                        cfg.feature_flags.bridge = true;
3808                    }
3809
3810                    // Enable resharing at same initial version
3811                    cfg.feature_flags.reshare_at_same_initial_version = true;
3812                }
3813                47 => {}
3814                48 => {
3815                    // Use tonic networking for Mysticeti.
3816                    cfg.feature_flags.consensus_network = ConsensusNetwork::Tonic;
3817
3818                    // Enable resolving abort code IDs to package ID instead of runtime module ID
3819                    cfg.feature_flags.resolve_abort_locations_to_package_id = true;
3820
3821                    // Enable random beacon on testnet.
3822                    if chain != Chain::Mainnet {
3823                        cfg.feature_flags.random_beacon = true;
3824                        cfg.random_beacon_reduction_lower_bound = Some(1600);
3825                        cfg.random_beacon_dkg_timeout_round = Some(3000);
3826                        cfg.random_beacon_min_round_interval_ms = Some(200);
3827                    }
3828
3829                    // Enable the committed sub dag digest inclusion on the commit output
3830                    cfg.feature_flags.mysticeti_use_committed_subdag_digest = true;
3831                }
3832                49 => {
3833                    if chain != Chain::Testnet && chain != Chain::Mainnet {
3834                        cfg.move_binary_format_version = Some(7);
3835                    }
3836
3837                    // enable vdf in devnet
3838                    if chain != Chain::Mainnet && chain != Chain::Testnet {
3839                        cfg.feature_flags.enable_vdf = true;
3840                        // Set to 30x and 2x the cost of a signature verification for now. This
3841                        // should be updated along with other native crypto functions.
3842                        cfg.vdf_verify_vdf_cost = Some(1500);
3843                        cfg.vdf_hash_to_input_cost = Some(100);
3844                    }
3845
3846                    // Only enable consensus commit prologue V3 in devnet.
3847                    if chain != Chain::Testnet && chain != Chain::Mainnet {
3848                        cfg.feature_flags
3849                            .record_consensus_determined_version_assignments_in_prologue = true;
3850                    }
3851
3852                    // Run Mysticeti consensus in testnet.
3853                    if chain != Chain::Mainnet {
3854                        cfg.feature_flags.consensus_choice = ConsensusChoice::Mysticeti;
3855                    }
3856
3857                    // Run Move verification on framework upgrades in its own VM
3858                    cfg.feature_flags.fresh_vm_on_framework_upgrade = true;
3859                }
3860                50 => {
3861                    // Enable checkpoint batching in testnet.
3862                    if chain != Chain::Mainnet {
3863                        cfg.checkpoint_summary_version_specific_data = Some(1);
3864                        cfg.min_checkpoint_interval_ms = Some(200);
3865                    }
3866
3867                    // Only enable prepose consensus commit prologue in checkpoints in devnet.
3868                    if chain != Chain::Testnet && chain != Chain::Mainnet {
3869                        cfg.feature_flags
3870                            .prepend_prologue_tx_in_consensus_commit_in_checkpoints = true;
3871                    }
3872
3873                    cfg.feature_flags.mysticeti_num_leaders_per_round = Some(1);
3874
3875                    // Set max transaction deferral to 10 consensus rounds.
3876                    cfg.max_deferral_rounds_for_congestion_control = Some(10);
3877                }
3878                51 => {
3879                    cfg.random_beacon_dkg_version = Some(1);
3880
3881                    if chain != Chain::Testnet && chain != Chain::Mainnet {
3882                        cfg.feature_flags.enable_coin_deny_list_v2 = true;
3883                    }
3884                }
3885                52 => {
3886                    if chain != Chain::Mainnet {
3887                        cfg.feature_flags.soft_bundle = true;
3888                        cfg.max_soft_bundle_size = Some(5);
3889                    }
3890
3891                    cfg.config_read_setting_impl_cost_base = Some(100);
3892                    cfg.config_read_setting_impl_cost_per_byte = Some(40);
3893
3894                    // Turn on shared object congestion control in devnet.
3895                    if chain != Chain::Testnet && chain != Chain::Mainnet {
3896                        cfg.max_accumulated_txn_cost_per_object_in_narwhal_commit = Some(100);
3897                        cfg.feature_flags.per_object_congestion_control_mode =
3898                            PerObjectCongestionControlMode::TotalTxCount;
3899                    }
3900
3901                    // Enable Mysticeti on mainnet.
3902                    cfg.feature_flags.consensus_choice = ConsensusChoice::Mysticeti;
3903
3904                    // Enable leader scoring & schedule change on mainnet for mysticeti.
3905                    cfg.feature_flags.mysticeti_leader_scoring_and_schedule = true;
3906
3907                    // Enable checkpoint batching on mainnet.
3908                    cfg.checkpoint_summary_version_specific_data = Some(1);
3909                    cfg.min_checkpoint_interval_ms = Some(200);
3910
3911                    // Enable consensus commit prologue V3 in testnet.
3912                    if chain != Chain::Mainnet {
3913                        cfg.feature_flags
3914                            .record_consensus_determined_version_assignments_in_prologue = true;
3915                        cfg.feature_flags
3916                            .prepend_prologue_tx_in_consensus_commit_in_checkpoints = true;
3917                    }
3918                    // Turn on enums in testnet and devnet
3919                    if chain != Chain::Mainnet {
3920                        cfg.move_binary_format_version = Some(7);
3921                    }
3922
3923                    if chain != Chain::Testnet && chain != Chain::Mainnet {
3924                        cfg.feature_flags.passkey_auth = true;
3925                    }
3926                    cfg.feature_flags.enable_coin_deny_list_v2 = true;
3927                }
3928                53 => {
3929                    // Do not allow bridge committee to finalize on mainnet.
3930                    cfg.bridge_should_try_to_finalize_committee = Some(chain != Chain::Mainnet);
3931
3932                    // Enable consensus commit prologue V3 on mainnet.
3933                    cfg.feature_flags
3934                        .record_consensus_determined_version_assignments_in_prologue = true;
3935                    cfg.feature_flags
3936                        .prepend_prologue_tx_in_consensus_commit_in_checkpoints = true;
3937
3938                    if chain == Chain::Unknown {
3939                        cfg.feature_flags.authority_capabilities_v2 = true;
3940                    }
3941
3942                    // Turns on shared object congestion control on testnet.
3943                    if chain != Chain::Mainnet {
3944                        cfg.max_accumulated_txn_cost_per_object_in_narwhal_commit = Some(100);
3945                        cfg.max_accumulated_txn_cost_per_object_in_mysticeti_commit = Some(10);
3946                        cfg.feature_flags.per_object_congestion_control_mode =
3947                            PerObjectCongestionControlMode::TotalTxCount;
3948                    }
3949
3950                    // Adjust stdlib gas costs
3951                    cfg.bcs_per_byte_serialized_cost = Some(2);
3952                    cfg.bcs_legacy_min_output_size_cost = Some(1);
3953                    cfg.bcs_failure_cost = Some(52);
3954                    cfg.debug_print_base_cost = Some(52);
3955                    cfg.debug_print_stack_trace_base_cost = Some(52);
3956                    cfg.hash_sha2_256_base_cost = Some(52);
3957                    cfg.hash_sha2_256_per_byte_cost = Some(2);
3958                    cfg.hash_sha2_256_legacy_min_input_len_cost = Some(1);
3959                    cfg.hash_sha3_256_base_cost = Some(52);
3960                    cfg.hash_sha3_256_per_byte_cost = Some(2);
3961                    cfg.hash_sha3_256_legacy_min_input_len_cost = Some(1);
3962                    cfg.type_name_get_base_cost = Some(52);
3963                    cfg.type_name_get_per_byte_cost = Some(2);
3964                    cfg.string_check_utf8_base_cost = Some(52);
3965                    cfg.string_check_utf8_per_byte_cost = Some(2);
3966                    cfg.string_is_char_boundary_base_cost = Some(52);
3967                    cfg.string_sub_string_base_cost = Some(52);
3968                    cfg.string_sub_string_per_byte_cost = Some(2);
3969                    cfg.string_index_of_base_cost = Some(52);
3970                    cfg.string_index_of_per_byte_pattern_cost = Some(2);
3971                    cfg.string_index_of_per_byte_searched_cost = Some(2);
3972                    cfg.vector_empty_base_cost = Some(52);
3973                    cfg.vector_length_base_cost = Some(52);
3974                    cfg.vector_push_back_base_cost = Some(52);
3975                    cfg.vector_push_back_legacy_per_abstract_memory_unit_cost = Some(2);
3976                    cfg.vector_borrow_base_cost = Some(52);
3977                    cfg.vector_pop_back_base_cost = Some(52);
3978                    cfg.vector_destroy_empty_base_cost = Some(52);
3979                    cfg.vector_swap_base_cost = Some(52);
3980                }
3981                54 => {
3982                    // Enable random beacon on mainnet.
3983                    cfg.feature_flags.random_beacon = true;
3984                    cfg.random_beacon_reduction_lower_bound = Some(1000);
3985                    cfg.random_beacon_dkg_timeout_round = Some(3000);
3986                    cfg.random_beacon_min_round_interval_ms = Some(500);
3987
3988                    // Turns on shared object congestion control on mainnet.
3989                    cfg.max_accumulated_txn_cost_per_object_in_narwhal_commit = Some(100);
3990                    cfg.max_accumulated_txn_cost_per_object_in_mysticeti_commit = Some(10);
3991                    cfg.feature_flags.per_object_congestion_control_mode =
3992                        PerObjectCongestionControlMode::TotalTxCount;
3993
3994                    // Enable soft bundle on mainnet.
3995                    cfg.feature_flags.soft_bundle = true;
3996                    cfg.max_soft_bundle_size = Some(5);
3997                }
3998                55 => {
3999                    // Turn on enums mainnet
4000                    cfg.move_binary_format_version = Some(7);
4001
4002                    // Assume 1KB per transaction and 500 transactions per block.
4003                    cfg.consensus_max_transactions_in_block_bytes = Some(512 * 1024);
4004                    // Assume 20_000 TPS * 5% max stake per validator / (minimum) 4 blocks per round = 250 transactions per block maximum
4005                    // Using a higher limit that is 512, to account for bursty traffic and system transactions.
4006                    cfg.consensus_max_num_transactions_in_block = Some(512);
4007
4008                    cfg.feature_flags.rethrow_serialization_type_layout_errors = true;
4009                }
4010                56 => {
4011                    if chain == Chain::Mainnet {
4012                        cfg.feature_flags.bridge = true;
4013                    }
4014                }
4015                57 => {
4016                    // Reduce minimum number of random beacon shares.
4017                    cfg.random_beacon_reduction_lower_bound = Some(800);
4018                }
4019                58 => {
4020                    if chain == Chain::Mainnet {
4021                        cfg.bridge_should_try_to_finalize_committee = Some(true);
4022                    }
4023
4024                    if chain != Chain::Mainnet && chain != Chain::Testnet {
4025                        // Enable distributed vote scoring for devnet
4026                        cfg.feature_flags
4027                            .consensus_distributed_vote_scoring_strategy = true;
4028                    }
4029                }
4030                59 => {
4031                    // Enable round prober in consensus.
4032                    cfg.feature_flags.consensus_round_prober = true;
4033                }
4034                60 => {
4035                    cfg.max_type_to_layout_nodes = Some(512);
4036                    cfg.feature_flags.validate_identifier_inputs = true;
4037                }
4038                61 => {
4039                    if chain != Chain::Mainnet {
4040                        // Enable distributed vote scoring for testnet
4041                        cfg.feature_flags
4042                            .consensus_distributed_vote_scoring_strategy = true;
4043                    }
4044                    // Further reduce minimum number of random beacon shares.
4045                    cfg.random_beacon_reduction_lower_bound = Some(700);
4046
4047                    if chain != Chain::Mainnet && chain != Chain::Testnet {
4048                        // Enable Mysticeti fastpath for devnet
4049                        cfg.feature_flags.mysticeti_fastpath = true;
4050                    }
4051                }
4052                62 => {
4053                    cfg.feature_flags.relocate_event_module = true;
4054                }
4055                63 => {
4056                    cfg.feature_flags.per_object_congestion_control_mode =
4057                        PerObjectCongestionControlMode::TotalGasBudgetWithCap;
4058                    cfg.gas_budget_based_txn_cost_cap_factor = Some(400_000);
4059                    cfg.max_accumulated_txn_cost_per_object_in_mysticeti_commit = Some(18_500_000);
4060                    cfg.max_accumulated_txn_cost_per_object_in_narwhal_commit = Some(240_000_000);
4061                }
4062                64 => {
4063                    cfg.feature_flags.per_object_congestion_control_mode =
4064                        PerObjectCongestionControlMode::TotalTxCount;
4065                    cfg.max_accumulated_txn_cost_per_object_in_narwhal_commit = Some(40);
4066                    cfg.max_accumulated_txn_cost_per_object_in_mysticeti_commit = Some(3);
4067                }
4068                65 => {
4069                    // Enable distributed vote scoring for mainnet
4070                    cfg.feature_flags
4071                        .consensus_distributed_vote_scoring_strategy = true;
4072                }
4073                66 => {
4074                    if chain == Chain::Mainnet {
4075                        // Revert the distributed vote scoring for mainnet (for one protocol upgrade)
4076                        cfg.feature_flags
4077                            .consensus_distributed_vote_scoring_strategy = false;
4078                    }
4079                }
4080                67 => {
4081                    // Enable it once again.
4082                    cfg.feature_flags
4083                        .consensus_distributed_vote_scoring_strategy = true;
4084                }
4085                68 => {
4086                    cfg.group_ops_bls12381_g1_to_uncompressed_g1_cost = Some(26);
4087                    cfg.group_ops_bls12381_uncompressed_g1_to_g1_cost = Some(52);
4088                    cfg.group_ops_bls12381_uncompressed_g1_sum_base_cost = Some(26);
4089                    cfg.group_ops_bls12381_uncompressed_g1_sum_cost_per_term = Some(13);
4090                    cfg.group_ops_bls12381_uncompressed_g1_sum_max_terms = Some(2000);
4091
4092                    if chain != Chain::Mainnet && chain != Chain::Testnet {
4093                        cfg.feature_flags.uncompressed_g1_group_elements = true;
4094                    }
4095
4096                    cfg.feature_flags.per_object_congestion_control_mode =
4097                        PerObjectCongestionControlMode::TotalGasBudgetWithCap;
4098                    cfg.gas_budget_based_txn_cost_cap_factor = Some(400_000);
4099                    cfg.max_accumulated_txn_cost_per_object_in_mysticeti_commit = Some(18_500_000);
4100                    cfg.max_accumulated_randomness_txn_cost_per_object_in_mysticeti_commit =
4101                        Some(3_700_000); // 20% of above
4102                    cfg.max_txn_cost_overage_per_object_in_commit = Some(u64::MAX);
4103                    cfg.gas_budget_based_txn_cost_absolute_cap_commit_count = Some(50);
4104
4105                    // Further reduce minimum number of random beacon shares.
4106                    cfg.random_beacon_reduction_lower_bound = Some(500);
4107
4108                    cfg.feature_flags.disallow_new_modules_in_deps_only_packages = true;
4109                }
4110                69 => {
4111                    // Sets number of rounds allowed for fastpath voting in consensus.
4112                    cfg.consensus_voting_rounds = Some(40);
4113
4114                    if chain != Chain::Mainnet && chain != Chain::Testnet {
4115                        // Enable smart ancestor selection for devnet
4116                        cfg.feature_flags.consensus_smart_ancestor_selection = true;
4117                    }
4118
4119                    if chain != Chain::Mainnet {
4120                        cfg.feature_flags.uncompressed_g1_group_elements = true;
4121                    }
4122                }
4123                70 => {
4124                    if chain != Chain::Mainnet {
4125                        // Enable smart ancestor selection for testnet
4126                        cfg.feature_flags.consensus_smart_ancestor_selection = true;
4127                        // Enable probing for accepted rounds in round prober for testnet
4128                        cfg.feature_flags
4129                            .consensus_round_prober_probe_accepted_rounds = true;
4130                    }
4131
4132                    cfg.poseidon_bn254_cost_per_block = Some(388);
4133
4134                    cfg.gas_model_version = Some(9);
4135                    cfg.feature_flags.native_charging_v2 = true;
4136                    cfg.bls12381_bls12381_min_sig_verify_cost_base = Some(44064);
4137                    cfg.bls12381_bls12381_min_pk_verify_cost_base = Some(49282);
4138                    cfg.ecdsa_k1_secp256k1_verify_keccak256_cost_base = Some(1470);
4139                    cfg.ecdsa_k1_secp256k1_verify_sha256_cost_base = Some(1470);
4140                    cfg.ecdsa_r1_secp256r1_verify_sha256_cost_base = Some(4225);
4141                    cfg.ecdsa_r1_secp256r1_verify_keccak256_cost_base = Some(4225);
4142                    cfg.ecvrf_ecvrf_verify_cost_base = Some(4848);
4143                    cfg.ed25519_ed25519_verify_cost_base = Some(1802);
4144
4145                    // Manually changed to be "under cost"
4146                    cfg.ecdsa_r1_ecrecover_keccak256_cost_base = Some(1173);
4147                    cfg.ecdsa_r1_ecrecover_sha256_cost_base = Some(1173);
4148                    cfg.ecdsa_k1_ecrecover_keccak256_cost_base = Some(500);
4149                    cfg.ecdsa_k1_ecrecover_sha256_cost_base = Some(500);
4150
4151                    cfg.groth16_prepare_verifying_key_bls12381_cost_base = Some(53838);
4152                    cfg.groth16_prepare_verifying_key_bn254_cost_base = Some(82010);
4153                    cfg.groth16_verify_groth16_proof_internal_bls12381_cost_base = Some(72090);
4154                    cfg.groth16_verify_groth16_proof_internal_bls12381_cost_per_public_input =
4155                        Some(8213);
4156                    cfg.groth16_verify_groth16_proof_internal_bn254_cost_base = Some(115502);
4157                    cfg.groth16_verify_groth16_proof_internal_bn254_cost_per_public_input =
4158                        Some(9484);
4159
4160                    cfg.hash_keccak256_cost_base = Some(10);
4161                    cfg.hash_blake2b256_cost_base = Some(10);
4162
4163                    // group ops
4164                    cfg.group_ops_bls12381_decode_scalar_cost = Some(7);
4165                    cfg.group_ops_bls12381_decode_g1_cost = Some(2848);
4166                    cfg.group_ops_bls12381_decode_g2_cost = Some(3770);
4167                    cfg.group_ops_bls12381_decode_gt_cost = Some(3068);
4168
4169                    cfg.group_ops_bls12381_scalar_add_cost = Some(10);
4170                    cfg.group_ops_bls12381_g1_add_cost = Some(1556);
4171                    cfg.group_ops_bls12381_g2_add_cost = Some(3048);
4172                    cfg.group_ops_bls12381_gt_add_cost = Some(188);
4173
4174                    cfg.group_ops_bls12381_scalar_sub_cost = Some(10);
4175                    cfg.group_ops_bls12381_g1_sub_cost = Some(1550);
4176                    cfg.group_ops_bls12381_g2_sub_cost = Some(3019);
4177                    cfg.group_ops_bls12381_gt_sub_cost = Some(497);
4178
4179                    cfg.group_ops_bls12381_scalar_mul_cost = Some(11);
4180                    cfg.group_ops_bls12381_g1_mul_cost = Some(4842);
4181                    cfg.group_ops_bls12381_g2_mul_cost = Some(9108);
4182                    cfg.group_ops_bls12381_gt_mul_cost = Some(27490);
4183
4184                    cfg.group_ops_bls12381_scalar_div_cost = Some(91);
4185                    cfg.group_ops_bls12381_g1_div_cost = Some(5091);
4186                    cfg.group_ops_bls12381_g2_div_cost = Some(9206);
4187                    cfg.group_ops_bls12381_gt_div_cost = Some(27804);
4188
4189                    cfg.group_ops_bls12381_g1_hash_to_base_cost = Some(2962);
4190                    cfg.group_ops_bls12381_g2_hash_to_base_cost = Some(8688);
4191
4192                    cfg.group_ops_bls12381_g1_msm_base_cost = Some(62648);
4193                    cfg.group_ops_bls12381_g2_msm_base_cost = Some(131192);
4194                    cfg.group_ops_bls12381_g1_msm_base_cost_per_input = Some(1333);
4195                    cfg.group_ops_bls12381_g2_msm_base_cost_per_input = Some(3216);
4196
4197                    cfg.group_ops_bls12381_uncompressed_g1_to_g1_cost = Some(677);
4198                    cfg.group_ops_bls12381_g1_to_uncompressed_g1_cost = Some(2099);
4199                    cfg.group_ops_bls12381_uncompressed_g1_sum_base_cost = Some(77);
4200                    cfg.group_ops_bls12381_uncompressed_g1_sum_cost_per_term = Some(26);
4201
4202                    cfg.group_ops_bls12381_pairing_cost = Some(26897);
4203                    cfg.group_ops_bls12381_uncompressed_g1_sum_max_terms = Some(1200);
4204
4205                    cfg.validator_validate_metadata_cost_base = Some(20000);
4206                }
4207                71 => {
4208                    cfg.sip_45_consensus_amplification_threshold = Some(5);
4209
4210                    // Enable bursts for congestion control. (10x the per-commit budget)
4211                    cfg.allowed_txn_cost_overage_burst_per_object_in_commit = Some(185_000_000);
4212                }
4213                72 => {
4214                    cfg.feature_flags.convert_type_argument_error = true;
4215
4216                    // Invariant: max_gas_price * base_tx_cost_fixed <= max_tx_gas
4217                    // max gas budget is in MIST and an absolute value 50_000 SUI
4218                    cfg.max_tx_gas = Some(50_000_000_000_000);
4219                    // max gas price is in MIST and an absolute value 50 SUI
4220                    cfg.max_gas_price = Some(50_000_000_000);
4221
4222                    cfg.feature_flags.variant_nodes = true;
4223                }
4224                73 => {
4225                    // Enable new marker table version.
4226                    cfg.use_object_per_epoch_marker_table_v2 = Some(true);
4227
4228                    if chain != Chain::Mainnet && chain != Chain::Testnet {
4229                        // Assuming a round rate of max 15/sec, then using a gc depth of 60 allow blocks within a window of ~4 seconds
4230                        // to be included before be considered garbage collected.
4231                        cfg.consensus_gc_depth = Some(60);
4232                    }
4233
4234                    if chain != Chain::Mainnet {
4235                        // Enable zstd compression for consensus in testnet
4236                        cfg.feature_flags.consensus_zstd_compression = true;
4237                    }
4238
4239                    // Enable smart ancestor selection for mainnet
4240                    cfg.feature_flags.consensus_smart_ancestor_selection = true;
4241                    // Enable probing for accepted rounds in round prober for mainnet
4242                    cfg.feature_flags
4243                        .consensus_round_prober_probe_accepted_rounds = true;
4244
4245                    // Increase congestion control budget.
4246                    cfg.feature_flags.per_object_congestion_control_mode =
4247                        PerObjectCongestionControlMode::TotalGasBudgetWithCap;
4248                    cfg.gas_budget_based_txn_cost_cap_factor = Some(400_000);
4249                    cfg.max_accumulated_txn_cost_per_object_in_mysticeti_commit = Some(37_000_000);
4250                    cfg.max_accumulated_randomness_txn_cost_per_object_in_mysticeti_commit =
4251                        Some(7_400_000); // 20% of above
4252                    cfg.max_txn_cost_overage_per_object_in_commit = Some(u64::MAX);
4253                    cfg.gas_budget_based_txn_cost_absolute_cap_commit_count = Some(50);
4254                    cfg.allowed_txn_cost_overage_burst_per_object_in_commit = Some(370_000_000);
4255                }
4256                74 => {
4257                    // Enable nitro attestation verify native move function for devnet
4258                    if chain != Chain::Mainnet && chain != Chain::Testnet {
4259                        cfg.feature_flags.enable_nitro_attestation = true;
4260                    }
4261                    cfg.nitro_attestation_parse_base_cost = Some(53 * 50);
4262                    cfg.nitro_attestation_parse_cost_per_byte = Some(50);
4263                    cfg.nitro_attestation_verify_base_cost = Some(49632 * 50);
4264                    cfg.nitro_attestation_verify_cost_per_cert = Some(52369 * 50);
4265
4266                    // Enable zstd compression for consensus in mainnet
4267                    cfg.feature_flags.consensus_zstd_compression = true;
4268
4269                    if chain != Chain::Mainnet && chain != Chain::Testnet {
4270                        cfg.feature_flags.consensus_linearize_subdag_v2 = true;
4271                    }
4272                }
4273                75 => {
4274                    if chain != Chain::Mainnet {
4275                        cfg.feature_flags.passkey_auth = true;
4276                    }
4277                }
4278                76 => {
4279                    if chain != Chain::Mainnet && chain != Chain::Testnet {
4280                        cfg.feature_flags.record_additional_state_digest_in_prologue = true;
4281                        cfg.consensus_commit_rate_estimation_window_size = Some(10);
4282                    }
4283                    cfg.feature_flags.minimize_child_object_mutations = true;
4284
4285                    if chain != Chain::Mainnet {
4286                        cfg.feature_flags.accept_passkey_in_multisig = true;
4287                    }
4288                }
4289                77 => {
4290                    cfg.feature_flags.uncompressed_g1_group_elements = true;
4291
4292                    if chain != Chain::Mainnet {
4293                        cfg.consensus_gc_depth = Some(60);
4294                        cfg.feature_flags.consensus_linearize_subdag_v2 = true;
4295                    }
4296                }
4297                78 => {
4298                    cfg.feature_flags.move_native_context = true;
4299                    cfg.tx_context_fresh_id_cost_base = Some(52);
4300                    cfg.tx_context_sender_cost_base = Some(30);
4301                    cfg.tx_context_epoch_cost_base = Some(30);
4302                    cfg.tx_context_epoch_timestamp_ms_cost_base = Some(30);
4303                    cfg.tx_context_sponsor_cost_base = Some(30);
4304                    cfg.tx_context_gas_price_cost_base = Some(30);
4305                    cfg.tx_context_gas_budget_cost_base = Some(30);
4306                    cfg.tx_context_ids_created_cost_base = Some(30);
4307                    cfg.tx_context_replace_cost_base = Some(30);
4308                    cfg.gas_model_version = Some(10);
4309
4310                    if chain != Chain::Mainnet {
4311                        cfg.feature_flags.record_additional_state_digest_in_prologue = true;
4312                        cfg.consensus_commit_rate_estimation_window_size = Some(10);
4313
4314                        // Enable execution time estimate mode for congestion control on testnet.
4315                        cfg.feature_flags.per_object_congestion_control_mode =
4316                            PerObjectCongestionControlMode::ExecutionTimeEstimate(
4317                                ExecutionTimeEstimateParams {
4318                                    target_utilization: 30,
4319                                    allowed_txn_cost_overage_burst_limit_us: 100_000, // 100 ms
4320                                    randomness_scalar: 20,
4321                                    max_estimate_us: 1_500_000, // 1.5s
4322                                    stored_observations_num_included_checkpoints: 10,
4323                                    stored_observations_limit: u64::MAX,
4324                                    stake_weighted_median_threshold: 0,
4325                                    default_none_duration_for_new_keys: false,
4326                                    observations_chunk_size: None,
4327                                },
4328                            );
4329                    }
4330                }
4331                79 => {
4332                    if chain != Chain::Mainnet {
4333                        cfg.feature_flags.consensus_median_based_commit_timestamp = true;
4334
4335                        // Increase threshold for bad nodes that won't be considered
4336                        // leaders in consensus in testnet
4337                        cfg.consensus_bad_nodes_stake_threshold = Some(30);
4338
4339                        cfg.feature_flags.consensus_batched_block_sync = true;
4340
4341                        // Enable verify nitro attestation in testnet.
4342                        cfg.feature_flags.enable_nitro_attestation = true
4343                    }
4344                    cfg.feature_flags.normalize_ptb_arguments = true;
4345
4346                    cfg.consensus_gc_depth = Some(60);
4347                    cfg.feature_flags.consensus_linearize_subdag_v2 = true;
4348                }
4349                80 => {
4350                    cfg.max_ptb_value_size = Some(1024 * 1024);
4351                }
4352                81 => {
4353                    cfg.feature_flags.consensus_median_based_commit_timestamp = true;
4354                    cfg.feature_flags.enforce_checkpoint_timestamp_monotonicity = true;
4355                    cfg.consensus_bad_nodes_stake_threshold = Some(30)
4356                }
4357                82 => {
4358                    cfg.feature_flags.max_ptb_value_size_v2 = true;
4359                }
4360                83 => {
4361                    if chain == Chain::Mainnet {
4362                        // The address that will sign the recovery transaction.
4363                        let aliased: [u8; 32] = Hex::decode(
4364                            "0x0b2da327ba6a4cacbe75dddd50e6e8bbf81d6496e92d66af9154c61c77f7332f",
4365                        )
4366                        .unwrap()
4367                        .try_into()
4368                        .unwrap();
4369
4370                        // Allow aliasing for the two addresses that contain stolen funds.
4371                        cfg.aliased_addresses.push(AliasedAddress {
4372                            original: Hex::decode("0xcd8962dad278d8b50fa0f9eb0186bfa4cbdecc6d59377214c88d0286a0ac9562").unwrap().try_into().unwrap(),
4373                            aliased,
4374                            allowed_tx_digests: vec![
4375                                Base58::decode("B2eGLFoMHgj93Ni8dAJBfqGzo8EWSTLBesZzhEpTPA4").unwrap().try_into().unwrap(),
4376                            ],
4377                        });
4378
4379                        cfg.aliased_addresses.push(AliasedAddress {
4380                            original: Hex::decode("0xe28b50cef1d633ea43d3296a3f6b67ff0312a5f1a99f0af753c85b8b5de8ff06").unwrap().try_into().unwrap(),
4381                            aliased,
4382                            allowed_tx_digests: vec![
4383                                Base58::decode("J4QqSAgp7VrQtQpMy5wDX4QGsCSEZu3U5KuDAkbESAge").unwrap().try_into().unwrap(),
4384                            ],
4385                        });
4386                    }
4387
4388                    // These features had to be deferred to v84 for mainnet in order to ship the recovery protocol
4389                    // upgrade as a patch to 1.48
4390                    if chain != Chain::Mainnet {
4391                        cfg.feature_flags.resolve_type_input_ids_to_defining_id = true;
4392                        cfg.transfer_party_transfer_internal_cost_base = Some(52);
4393
4394                        // Enable execution time estimate mode for congestion control on mainnet.
4395                        cfg.feature_flags.record_additional_state_digest_in_prologue = true;
4396                        cfg.consensus_commit_rate_estimation_window_size = Some(10);
4397                        cfg.feature_flags.per_object_congestion_control_mode =
4398                            PerObjectCongestionControlMode::ExecutionTimeEstimate(
4399                                ExecutionTimeEstimateParams {
4400                                    target_utilization: 30,
4401                                    allowed_txn_cost_overage_burst_limit_us: 100_000, // 100 ms
4402                                    randomness_scalar: 20,
4403                                    max_estimate_us: 1_500_000, // 1.5s
4404                                    stored_observations_num_included_checkpoints: 10,
4405                                    stored_observations_limit: u64::MAX,
4406                                    stake_weighted_median_threshold: 0,
4407                                    default_none_duration_for_new_keys: false,
4408                                    observations_chunk_size: None,
4409                                },
4410                            );
4411
4412                        // Enable the new depth-first block sync logic.
4413                        cfg.feature_flags.consensus_batched_block_sync = true;
4414
4415                        // Enable nitro attestation upgraded parsing logic and enable the
4416                        // native function on mainnet.
4417                        cfg.feature_flags.enable_nitro_attestation_upgraded_parsing = true;
4418                        cfg.feature_flags.enable_nitro_attestation = true;
4419                    }
4420                }
4421                84 => {
4422                    if chain == Chain::Mainnet {
4423                        cfg.feature_flags.resolve_type_input_ids_to_defining_id = true;
4424                        cfg.transfer_party_transfer_internal_cost_base = Some(52);
4425
4426                        // Enable execution time estimate mode for congestion control on mainnet.
4427                        cfg.feature_flags.record_additional_state_digest_in_prologue = true;
4428                        cfg.consensus_commit_rate_estimation_window_size = Some(10);
4429                        cfg.feature_flags.per_object_congestion_control_mode =
4430                            PerObjectCongestionControlMode::ExecutionTimeEstimate(
4431                                ExecutionTimeEstimateParams {
4432                                    target_utilization: 30,
4433                                    allowed_txn_cost_overage_burst_limit_us: 100_000, // 100 ms
4434                                    randomness_scalar: 20,
4435                                    max_estimate_us: 1_500_000, // 1.5s
4436                                    stored_observations_num_included_checkpoints: 10,
4437                                    stored_observations_limit: u64::MAX,
4438                                    stake_weighted_median_threshold: 0,
4439                                    default_none_duration_for_new_keys: false,
4440                                    observations_chunk_size: None,
4441                                },
4442                            );
4443
4444                        // Enable the new depth-first block sync logic.
4445                        cfg.feature_flags.consensus_batched_block_sync = true;
4446
4447                        // Enable nitro attestation upgraded parsing logic and enable the
4448                        // native function on mainnet.
4449                        cfg.feature_flags.enable_nitro_attestation_upgraded_parsing = true;
4450                        cfg.feature_flags.enable_nitro_attestation = true;
4451                    }
4452
4453                    // Limit the number of stored execution time observations at end of epoch.
4454                    cfg.feature_flags.per_object_congestion_control_mode =
4455                        PerObjectCongestionControlMode::ExecutionTimeEstimate(
4456                            ExecutionTimeEstimateParams {
4457                                target_utilization: 30,
4458                                allowed_txn_cost_overage_burst_limit_us: 100_000, // 100 ms
4459                                randomness_scalar: 20,
4460                                max_estimate_us: 1_500_000, // 1.5s
4461                                stored_observations_num_included_checkpoints: 10,
4462                                stored_observations_limit: 20,
4463                                stake_weighted_median_threshold: 0,
4464                                default_none_duration_for_new_keys: false,
4465                                observations_chunk_size: None,
4466                            },
4467                        );
4468                    cfg.feature_flags.allow_unbounded_system_objects = true;
4469                }
4470                85 => {
4471                    if chain != Chain::Mainnet && chain != Chain::Testnet {
4472                        cfg.feature_flags.enable_party_transfer = true;
4473                    }
4474
4475                    cfg.feature_flags
4476                        .record_consensus_determined_version_assignments_in_prologue_v2 = true;
4477                    cfg.feature_flags.disallow_self_identifier = true;
4478                    cfg.feature_flags.per_object_congestion_control_mode =
4479                        PerObjectCongestionControlMode::ExecutionTimeEstimate(
4480                            ExecutionTimeEstimateParams {
4481                                target_utilization: 50,
4482                                allowed_txn_cost_overage_burst_limit_us: 500_000, // 500 ms
4483                                randomness_scalar: 20,
4484                                max_estimate_us: 1_500_000, // 1.5s
4485                                stored_observations_num_included_checkpoints: 10,
4486                                stored_observations_limit: 20,
4487                                stake_weighted_median_threshold: 0,
4488                                default_none_duration_for_new_keys: false,
4489                                observations_chunk_size: None,
4490                            },
4491                        );
4492                }
4493                86 => {
4494                    cfg.feature_flags.type_tags_in_object_runtime = true;
4495                    cfg.max_move_enum_variants = Some(move_core_types::VARIANT_COUNT_MAX);
4496
4497                    // Set a stake_weighted_median_threshold for congestion control.
4498                    cfg.feature_flags.per_object_congestion_control_mode =
4499                        PerObjectCongestionControlMode::ExecutionTimeEstimate(
4500                            ExecutionTimeEstimateParams {
4501                                target_utilization: 50,
4502                                allowed_txn_cost_overage_burst_limit_us: 500_000, // 500 ms
4503                                randomness_scalar: 20,
4504                                max_estimate_us: 1_500_000, // 1.5s
4505                                stored_observations_num_included_checkpoints: 10,
4506                                stored_observations_limit: 20,
4507                                stake_weighted_median_threshold: 3334,
4508                                default_none_duration_for_new_keys: false,
4509                                observations_chunk_size: None,
4510                            },
4511                        );
4512                    // Enable party transfer for testnet.
4513                    if chain != Chain::Mainnet {
4514                        cfg.feature_flags.enable_party_transfer = true;
4515                    }
4516                }
4517                87 => {
4518                    if chain == Chain::Mainnet {
4519                        cfg.feature_flags.record_time_estimate_processed = true;
4520                    }
4521                    cfg.feature_flags.better_adapter_type_resolution_errors = true;
4522                }
4523                88 => {
4524                    cfg.feature_flags.record_time_estimate_processed = true;
4525                    cfg.tx_context_rgp_cost_base = Some(30);
4526                    cfg.feature_flags
4527                        .ignore_execution_time_observations_after_certs_closed = true;
4528
4529                    // Disable backwards compatible behavior in execution time estimator for
4530                    // new protocol version.
4531                    cfg.feature_flags.per_object_congestion_control_mode =
4532                        PerObjectCongestionControlMode::ExecutionTimeEstimate(
4533                            ExecutionTimeEstimateParams {
4534                                target_utilization: 50,
4535                                allowed_txn_cost_overage_burst_limit_us: 500_000, // 500 ms
4536                                randomness_scalar: 20,
4537                                max_estimate_us: 1_500_000, // 1.5s
4538                                stored_observations_num_included_checkpoints: 10,
4539                                stored_observations_limit: 20,
4540                                stake_weighted_median_threshold: 3334,
4541                                default_none_duration_for_new_keys: true,
4542                                observations_chunk_size: None,
4543                            },
4544                        );
4545                }
4546                89 => {
4547                    cfg.feature_flags.dependency_linkage_error = true;
4548                    cfg.feature_flags.additional_multisig_checks = true;
4549                }
4550                90 => {
4551                    // 100x RGP
4552                    cfg.max_gas_price_rgp_factor_for_aborted_transactions = Some(100);
4553                    cfg.feature_flags.debug_fatal_on_move_invariant_violation = true;
4554                    cfg.feature_flags.additional_consensus_digest_indirect_state = true;
4555                    cfg.feature_flags.accept_passkey_in_multisig = true;
4556                    cfg.feature_flags.passkey_auth = true;
4557                    cfg.feature_flags.check_for_init_during_upgrade = true;
4558
4559                    // Enable Mysticeti fastpath handlers on testnet.
4560                    if chain != Chain::Mainnet {
4561                        cfg.feature_flags.mysticeti_fastpath = true;
4562                    }
4563                }
4564                91 => {
4565                    cfg.feature_flags.per_command_shared_object_transfer_rules = true;
4566                }
4567                92 => {
4568                    cfg.feature_flags.per_command_shared_object_transfer_rules = false;
4569                }
4570                93 => {
4571                    cfg.feature_flags
4572                        .consensus_checkpoint_signature_key_includes_digest = true;
4573                }
4574                94 => {
4575                    // Decrease stored observations limit 20->18 to stay within system object size limit.
4576                    cfg.feature_flags.per_object_congestion_control_mode =
4577                        PerObjectCongestionControlMode::ExecutionTimeEstimate(
4578                            ExecutionTimeEstimateParams {
4579                                target_utilization: 50,
4580                                allowed_txn_cost_overage_burst_limit_us: 500_000, // 500 ms
4581                                randomness_scalar: 20,
4582                                max_estimate_us: 1_500_000, // 1.5s
4583                                stored_observations_num_included_checkpoints: 10,
4584                                stored_observations_limit: 18,
4585                                stake_weighted_median_threshold: 3334,
4586                                default_none_duration_for_new_keys: true,
4587                                observations_chunk_size: None,
4588                            },
4589                        );
4590
4591                    // Enable party transfer on mainnet.
4592                    cfg.feature_flags.enable_party_transfer = true;
4593                }
4594                95 => {
4595                    cfg.type_name_id_base_cost = Some(52);
4596
4597                    // Reduce the frequency of checkpoint splitting under high TPS.
4598                    cfg.max_transactions_per_checkpoint = Some(20_000);
4599                }
4600                96 => {
4601                    // Enable artifacts digest in devnet.
4602                    if chain != Chain::Mainnet && chain != Chain::Testnet {
4603                        cfg.feature_flags
4604                            .include_checkpoint_artifacts_digest_in_summary = true;
4605                    }
4606                    cfg.feature_flags.correct_gas_payment_limit_check = true;
4607                    cfg.feature_flags.authority_capabilities_v2 = true;
4608                    cfg.feature_flags.use_mfp_txns_in_load_initial_object_debts = true;
4609                    cfg.feature_flags.cancel_for_failed_dkg_early = true;
4610                    cfg.feature_flags.enable_coin_registry = true;
4611
4612                    // Enable Mysticeti fastpath handlers on mainnet.
4613                    cfg.feature_flags.mysticeti_fastpath = true;
4614                }
4615                97 => {
4616                    cfg.feature_flags.additional_borrow_checks = true;
4617                }
4618                98 => {
4619                    cfg.event_emit_auth_stream_cost = Some(52);
4620                    cfg.feature_flags.better_loader_errors = true;
4621                    cfg.feature_flags.generate_df_type_layouts = true;
4622                }
4623                99 => {
4624                    cfg.feature_flags.use_new_commit_handler = true;
4625                }
4626                100 => {
4627                    cfg.feature_flags.private_generics_verifier_v2 = true;
4628                }
4629                101 => {
4630                    cfg.feature_flags.create_root_accumulator_object = true;
4631                    cfg.max_updates_per_settlement_txn = Some(100);
4632                    if chain != Chain::Mainnet {
4633                        cfg.feature_flags.enable_poseidon = true;
4634                    }
4635                }
4636                102 => {
4637                    // Enable execution time observation chunking and increase limit to 180.
4638                    // max_move_object_size is 250 KB, we've experientially determined that fits ~ 18 estimates
4639                    // so if we have 10 chunks, that's 2.5MB, < 8MB max_serialized_tx_effects_size_bytes_system_tx
4640                    cfg.feature_flags.per_object_congestion_control_mode =
4641                        PerObjectCongestionControlMode::ExecutionTimeEstimate(
4642                            ExecutionTimeEstimateParams {
4643                                target_utilization: 50,
4644                                allowed_txn_cost_overage_burst_limit_us: 500_000, // 500 ms
4645                                randomness_scalar: 20,
4646                                max_estimate_us: 1_500_000, // 1.5s
4647                                stored_observations_num_included_checkpoints: 10,
4648                                stored_observations_limit: 180,
4649                                stake_weighted_median_threshold: 3334,
4650                                default_none_duration_for_new_keys: true,
4651                                observations_chunk_size: Some(18),
4652                            },
4653                        );
4654                    cfg.feature_flags.deprecate_global_storage_ops = true;
4655                }
4656                103 => {}
4657                104 => {
4658                    cfg.translation_per_command_base_charge = Some(1);
4659                    cfg.translation_per_input_base_charge = Some(1);
4660                    cfg.translation_pure_input_per_byte_charge = Some(1);
4661                    cfg.translation_per_type_node_charge = Some(1);
4662                    cfg.translation_per_reference_node_charge = Some(1);
4663                    cfg.translation_per_linkage_entry_charge = Some(10);
4664                    cfg.gas_model_version = Some(11);
4665                    cfg.feature_flags.abstract_size_in_object_runtime = true;
4666                    cfg.feature_flags.object_runtime_charge_cache_load_gas = true;
4667                    cfg.dynamic_field_hash_type_and_key_cost_base = Some(52);
4668                    cfg.dynamic_field_add_child_object_cost_base = Some(52);
4669                    cfg.dynamic_field_add_child_object_value_cost_per_byte = Some(1);
4670                    cfg.dynamic_field_borrow_child_object_cost_base = Some(52);
4671                    cfg.dynamic_field_borrow_child_object_child_ref_cost_per_byte = Some(1);
4672                    cfg.dynamic_field_remove_child_object_cost_base = Some(52);
4673                    cfg.dynamic_field_remove_child_object_child_cost_per_byte = Some(1);
4674                    cfg.dynamic_field_has_child_object_cost_base = Some(52);
4675                    cfg.dynamic_field_has_child_object_with_ty_cost_base = Some(52);
4676                    cfg.feature_flags.enable_ptb_execution_v2 = true;
4677
4678                    cfg.poseidon_bn254_cost_base = Some(260);
4679
4680                    cfg.feature_flags.consensus_skip_gced_accept_votes = true;
4681
4682                    if chain != Chain::Mainnet {
4683                        cfg.feature_flags
4684                            .enable_nitro_attestation_all_nonzero_pcrs_parsing = true;
4685                    }
4686
4687                    cfg.feature_flags
4688                        .include_cancelled_randomness_txns_in_prologue = true;
4689                }
4690                105 => {
4691                    cfg.feature_flags.enable_multi_epoch_transaction_expiration = true;
4692                    cfg.feature_flags.disable_preconsensus_locking = true;
4693
4694                    if chain != Chain::Mainnet {
4695                        cfg.feature_flags
4696                            .enable_nitro_attestation_always_include_required_pcrs_parsing = true;
4697                    }
4698                }
4699                106 => {
4700                    // est. 100 bytes per object * 76 (storage_gas_price)
4701                    cfg.accumulator_object_storage_cost = Some(7600);
4702
4703                    if chain != Chain::Mainnet && chain != Chain::Testnet {
4704                        cfg.feature_flags.enable_accumulators = true;
4705                        cfg.feature_flags.enable_address_balance_gas_payments = true;
4706                        cfg.feature_flags.enable_authenticated_event_streams = true;
4707                        cfg.feature_flags.enable_object_funds_withdraw = true;
4708                    }
4709                }
4710                107 => {
4711                    cfg.feature_flags
4712                        .consensus_skip_gced_blocks_in_direct_finalization = true;
4713
4714                    // Trigger edge cases more often in integration tests.
4715                    if in_integration_test() {
4716                        cfg.consensus_gc_depth = Some(6);
4717                        cfg.consensus_max_num_transactions_in_block = Some(8);
4718                    }
4719                }
4720                108 => {
4721                    cfg.feature_flags.gas_rounding_halve_digits = true;
4722                    cfg.feature_flags.flexible_tx_context_positions = true;
4723                    cfg.feature_flags.disable_entry_point_signature_check = true;
4724
4725                    if chain != Chain::Mainnet {
4726                        cfg.feature_flags.address_aliases = true;
4727
4728                        cfg.feature_flags.enable_accumulators = true;
4729                        cfg.feature_flags.enable_address_balance_gas_payments = true;
4730                    }
4731
4732                    cfg.feature_flags.enable_poseidon = true;
4733                }
4734                109 => {
4735                    cfg.binary_variant_handles = Some(1024);
4736                    cfg.binary_variant_instantiation_handles = Some(1024);
4737                    cfg.feature_flags.restrict_hot_or_not_entry_functions = true;
4738                }
4739                110 => {
4740                    cfg.feature_flags
4741                        .enable_nitro_attestation_all_nonzero_pcrs_parsing = true;
4742                    cfg.feature_flags
4743                        .enable_nitro_attestation_always_include_required_pcrs_parsing = true;
4744                    if chain != Chain::Mainnet && chain != Chain::Testnet {
4745                        cfg.feature_flags.split_checkpoints_in_consensus_handler = true;
4746                    }
4747                    cfg.feature_flags.validate_zklogin_public_identifier = true;
4748                    cfg.feature_flags.fix_checkpoint_signature_mapping = true;
4749                    cfg.feature_flags
4750                        .consensus_always_accept_system_transactions = true;
4751                    if chain != Chain::Mainnet {
4752                        cfg.feature_flags.enable_object_funds_withdraw = true;
4753                    }
4754                }
4755                111 => {
4756                    cfg.feature_flags.validator_metadata_verify_v2 = true;
4757                }
4758                112 => {
4759                    cfg.group_ops_ristretto_decode_scalar_cost = Some(7);
4760                    cfg.group_ops_ristretto_decode_point_cost = Some(200);
4761                    cfg.group_ops_ristretto_scalar_add_cost = Some(10);
4762                    cfg.group_ops_ristretto_point_add_cost = Some(500);
4763                    cfg.group_ops_ristretto_scalar_sub_cost = Some(10);
4764                    cfg.group_ops_ristretto_point_sub_cost = Some(500);
4765                    cfg.group_ops_ristretto_scalar_mul_cost = Some(11);
4766                    cfg.group_ops_ristretto_point_mul_cost = Some(1200);
4767                    cfg.group_ops_ristretto_scalar_div_cost = Some(151);
4768                    cfg.group_ops_ristretto_point_div_cost = Some(2500);
4769
4770                    if chain != Chain::Mainnet && chain != Chain::Testnet {
4771                        cfg.feature_flags.enable_ristretto255_group_ops = true;
4772                    }
4773                }
4774                113 => {
4775                    cfg.feature_flags.address_balance_gas_check_rgp_at_signing = true;
4776                    if chain != Chain::Mainnet && chain != Chain::Testnet {
4777                        cfg.feature_flags.defer_unpaid_amplification = true;
4778                    }
4779                }
4780                114 => {
4781                    cfg.feature_flags.randomize_checkpoint_tx_limit_in_tests = true;
4782                    cfg.feature_flags.address_balance_gas_reject_gas_coin_arg = true;
4783                    if chain != Chain::Mainnet {
4784                        cfg.feature_flags.split_checkpoints_in_consensus_handler = true;
4785                        cfg.feature_flags.enable_authenticated_event_streams = true;
4786                        cfg.feature_flags
4787                            .include_checkpoint_artifacts_digest_in_summary = true;
4788                    }
4789                }
4790                115 => {
4791                    cfg.feature_flags.normalize_depth_formula = true;
4792                }
4793                116 => {
4794                    cfg.feature_flags.gasless_transaction_drop_safety = true;
4795                    cfg.feature_flags.address_aliases = true;
4796                    cfg.feature_flags.relax_valid_during_for_owned_inputs = true;
4797                    // Disabled while debugging
4798                    cfg.feature_flags.defer_unpaid_amplification = false;
4799                    cfg.feature_flags.enable_display_registry = true;
4800                }
4801                117 => {}
4802                118 => {
4803                    cfg.feature_flags.use_coin_party_owner = true;
4804                }
4805                119 => {
4806                    // Enable new VM.
4807                    cfg.execution_version = Some(4);
4808                    cfg.feature_flags.address_balance_gas_reject_gas_coin_arg = false;
4809                    cfg.feature_flags.merge_randomness_into_checkpoint = true;
4810                    if chain != Chain::Mainnet {
4811                        cfg.feature_flags.enable_gasless = true;
4812                        cfg.gasless_max_computation_units = Some(50_000);
4813                        cfg.gasless_allowed_token_types = Some(vec![]);
4814                        cfg.feature_flags.enable_coin_reservation_obj_refs = true;
4815                        cfg.feature_flags
4816                            .convert_withdrawal_compatibility_ptb_arguments = true;
4817                    }
4818                    cfg.gasless_max_unused_inputs = Some(1);
4819                    cfg.gasless_max_pure_input_bytes = Some(32);
4820                    if chain == Chain::Testnet {
4821                        cfg.gasless_allowed_token_types = Some(vec![(TESTNET_USDC.to_string(), 0)]);
4822                    }
4823                    cfg.transfer_receive_object_cost_per_byte = Some(1);
4824                    cfg.transfer_receive_object_type_cost_per_byte = Some(2);
4825                }
4826                120 => {
4827                    cfg.feature_flags.disallow_jump_orphans = true;
4828                }
4829                121 => {
4830                    // Re-enable unpaid amplification deferral protection (testnet + devnet)
4831                    if chain != Chain::Mainnet {
4832                        cfg.feature_flags.defer_unpaid_amplification = true;
4833                        cfg.gasless_max_tps = Some(50);
4834                    }
4835                    cfg.feature_flags
4836                        .early_return_receive_object_mismatched_type = true;
4837                }
4838                122 => {
4839                    // Enable bulletproofs range proofs on devnet
4840                    cfg.verify_bulletproofs_ristretto255_base_cost = Some(30000);
4841                    cfg.verify_bulletproofs_ristretto255_cost_per_bit_and_commitment = Some(6500);
4842                    if chain != Chain::Mainnet && chain != Chain::Testnet {
4843                        cfg.feature_flags.enable_verify_bulletproofs_ristretto255 = true;
4844                    }
4845                    cfg.feature_flags.gasless_verify_remaining_balance = true;
4846                    cfg.include_special_package_amendments = match chain {
4847                        Chain::Mainnet => Some(MAINNET_LINKAGE_AMENDMENTS.clone()),
4848                        Chain::Testnet => Some(TESTNET_LINKAGE_AMENDMENTS.clone()),
4849                        Chain::Unknown => None,
4850                    };
4851                }
4852                // Use this template when making changes:
4853                //
4854                //     // modify an existing constant.
4855                //     move_binary_format_version: Some(7),
4856                //
4857                //     // Add a new constant (which is set to None in prior versions).
4858                //     new_constant: Some(new_value),
4859                //
4860                //     // Remove a constant (ensure that it is never accessed during this version).
4861                //     max_move_object_size: None,
4862                _ => panic!("unsupported version {:?}", version),
4863            }
4864        }
4865
4866        cfg
4867    }
4868
4869    pub fn apply_seeded_test_overrides(&mut self, seed: &[u8; 32]) {
4870        if !self.feature_flags.randomize_checkpoint_tx_limit_in_tests
4871            || !self.feature_flags.split_checkpoints_in_consensus_handler
4872        {
4873            return;
4874        }
4875
4876        if !mysten_common::in_test_configuration() {
4877            return;
4878        }
4879
4880        use rand::{Rng, SeedableRng, rngs::StdRng};
4881        let mut rng = StdRng::from_seed(*seed);
4882        let max_txns = rng.gen_range(10..=100u64);
4883        info!("seeded test override: max_transactions_per_checkpoint = {max_txns}");
4884        self.max_transactions_per_checkpoint = Some(max_txns);
4885    }
4886
4887    // Extract the bytecode verifier config from this protocol config.
4888    // If used during signing, `signing_limits` should be set.
4889    // The third limit configures`sanity_check_with_regex_reference_safety`,
4890    // which runs the new regex-based reference safety check to check that it is strictly more
4891    // permissive than the current implementation.
4892    pub fn verifier_config(&self, signing_limits: Option<(usize, usize, usize)>) -> VerifierConfig {
4893        let (
4894            max_back_edges_per_function,
4895            max_back_edges_per_module,
4896            sanity_check_with_regex_reference_safety,
4897        ) = if let Some((
4898            max_back_edges_per_function,
4899            max_back_edges_per_module,
4900            sanity_check_with_regex_reference_safety,
4901        )) = signing_limits
4902        {
4903            (
4904                Some(max_back_edges_per_function),
4905                Some(max_back_edges_per_module),
4906                Some(sanity_check_with_regex_reference_safety),
4907            )
4908        } else {
4909            (None, None, None)
4910        };
4911
4912        let additional_borrow_checks = if signing_limits.is_some() {
4913            // always turn on additional borrow checks during signing
4914            true
4915        } else {
4916            self.additional_borrow_checks()
4917        };
4918        let deprecate_global_storage_ops = if signing_limits.is_some() {
4919            // always turn on additional vector borrow checks during signing
4920            true
4921        } else {
4922            self.deprecate_global_storage_ops()
4923        };
4924
4925        VerifierConfig {
4926            max_loop_depth: Some(self.max_loop_depth() as usize),
4927            max_generic_instantiation_length: Some(self.max_generic_instantiation_length() as usize),
4928            max_function_parameters: Some(self.max_function_parameters() as usize),
4929            max_basic_blocks: Some(self.max_basic_blocks() as usize),
4930            max_value_stack_size: self.max_value_stack_size() as usize,
4931            max_type_nodes: Some(self.max_type_nodes() as usize),
4932            max_push_size: Some(self.max_push_size() as usize),
4933            max_dependency_depth: Some(self.max_dependency_depth() as usize),
4934            max_fields_in_struct: Some(self.max_fields_in_struct() as usize),
4935            max_function_definitions: Some(self.max_function_definitions() as usize),
4936            max_data_definitions: Some(self.max_struct_definitions() as usize),
4937            max_constant_vector_len: Some(self.max_move_vector_len()),
4938            max_back_edges_per_function,
4939            max_back_edges_per_module,
4940            max_basic_blocks_in_script: None,
4941            max_identifier_len: self.max_move_identifier_len_as_option(), // Before protocol version 9, there was no limit
4942            disallow_self_identifier: self.feature_flags.disallow_self_identifier,
4943            allow_receiving_object_id: self.allow_receiving_object_id(),
4944            reject_mutable_random_on_entry_functions: self
4945                .reject_mutable_random_on_entry_functions(),
4946            bytecode_version: self.move_binary_format_version(),
4947            max_variants_in_enum: self.max_move_enum_variants_as_option(),
4948            additional_borrow_checks,
4949            better_loader_errors: self.better_loader_errors(),
4950            private_generics_verifier_v2: self.private_generics_verifier_v2(),
4951            sanity_check_with_regex_reference_safety: sanity_check_with_regex_reference_safety
4952                .map(|limit| limit as u128),
4953            deprecate_global_storage_ops,
4954            disable_entry_point_signature_check: self.disable_entry_point_signature_check(),
4955            switch_to_regex_reference_safety: false,
4956            disallow_jump_orphans: self.disallow_jump_orphans(),
4957        }
4958    }
4959
4960    pub fn binary_config(
4961        &self,
4962        override_deprecate_global_storage_ops_during_deserialization: Option<bool>,
4963    ) -> BinaryConfig {
4964        let deprecate_global_storage_ops =
4965            override_deprecate_global_storage_ops_during_deserialization
4966                .unwrap_or_else(|| self.deprecate_global_storage_ops());
4967        BinaryConfig::new(
4968            self.move_binary_format_version(),
4969            self.min_move_binary_format_version_as_option()
4970                .unwrap_or(VERSION_1),
4971            self.no_extraneous_module_bytes(),
4972            deprecate_global_storage_ops,
4973            TableConfig {
4974                module_handles: self.binary_module_handles_as_option().unwrap_or(u16::MAX),
4975                datatype_handles: self.binary_struct_handles_as_option().unwrap_or(u16::MAX),
4976                function_handles: self.binary_function_handles_as_option().unwrap_or(u16::MAX),
4977                function_instantiations: self
4978                    .binary_function_instantiations_as_option()
4979                    .unwrap_or(u16::MAX),
4980                signatures: self.binary_signatures_as_option().unwrap_or(u16::MAX),
4981                constant_pool: self.binary_constant_pool_as_option().unwrap_or(u16::MAX),
4982                identifiers: self.binary_identifiers_as_option().unwrap_or(u16::MAX),
4983                address_identifiers: self
4984                    .binary_address_identifiers_as_option()
4985                    .unwrap_or(u16::MAX),
4986                struct_defs: self.binary_struct_defs_as_option().unwrap_or(u16::MAX),
4987                struct_def_instantiations: self
4988                    .binary_struct_def_instantiations_as_option()
4989                    .unwrap_or(u16::MAX),
4990                function_defs: self.binary_function_defs_as_option().unwrap_or(u16::MAX),
4991                field_handles: self.binary_field_handles_as_option().unwrap_or(u16::MAX),
4992                field_instantiations: self
4993                    .binary_field_instantiations_as_option()
4994                    .unwrap_or(u16::MAX),
4995                friend_decls: self.binary_friend_decls_as_option().unwrap_or(u16::MAX),
4996                enum_defs: self.binary_enum_defs_as_option().unwrap_or(u16::MAX),
4997                enum_def_instantiations: self
4998                    .binary_enum_def_instantiations_as_option()
4999                    .unwrap_or(u16::MAX),
5000                variant_handles: self.binary_variant_handles_as_option().unwrap_or(u16::MAX),
5001                variant_instantiation_handles: self
5002                    .binary_variant_instantiation_handles_as_option()
5003                    .unwrap_or(u16::MAX),
5004            },
5005        )
5006    }
5007
5008    /// Override one or more settings in the config, for testing.
5009    /// This must be called at the beginning of the test, before get_for_(min|max)_version is
5010    /// called, since those functions cache their return value.
5011    #[cfg(not(msim))]
5012    pub fn apply_overrides_for_testing(
5013        override_fn: impl Fn(ProtocolVersion, Self) -> Self + Send + Sync + 'static,
5014    ) -> OverrideGuard {
5015        let mut cur = CONFIG_OVERRIDE.lock().unwrap();
5016        assert!(cur.is_none(), "config override already present");
5017        *cur = Some(Box::new(override_fn));
5018        OverrideGuard
5019    }
5020
5021    /// Override one or more settings in the config, for testing.
5022    /// This must be called at the beginning of the test, before get_for_(min|max)_version is
5023    /// called, since those functions cache their return value.
5024    #[cfg(msim)]
5025    pub fn apply_overrides_for_testing(
5026        override_fn: impl Fn(ProtocolVersion, Self) -> Self + Send + 'static,
5027    ) -> OverrideGuard {
5028        CONFIG_OVERRIDE.with(|ovr| {
5029            let mut cur = ovr.borrow_mut();
5030            assert!(cur.is_none(), "config override already present");
5031            *cur = Some(Box::new(override_fn));
5032            OverrideGuard
5033        })
5034    }
5035
5036    #[cfg(not(msim))]
5037    fn apply_config_override(version: ProtocolVersion, mut ret: Self) -> Self {
5038        if let Some(override_fn) = CONFIG_OVERRIDE.lock().unwrap().as_ref() {
5039            warn!(
5040                "overriding ProtocolConfig settings with custom settings (you should not see this log outside of tests)"
5041            );
5042            ret = override_fn(version, ret);
5043        }
5044        ret
5045    }
5046
5047    #[cfg(msim)]
5048    fn apply_config_override(version: ProtocolVersion, ret: Self) -> Self {
5049        CONFIG_OVERRIDE.with(|ovr| {
5050            if let Some(override_fn) = &*ovr.borrow() {
5051                warn!(
5052                    "overriding ProtocolConfig settings with custom settings (you should not see this log outside of tests)"
5053                );
5054                override_fn(version, ret)
5055            } else {
5056                ret
5057            }
5058        })
5059    }
5060}
5061
5062// Setters for tests.
5063// This is only needed for feature_flags. Please suffix each setter with `_for_testing`.
5064// Non-feature_flags should already have test setters defined through macros.
5065impl ProtocolConfig {
5066    pub fn set_advance_to_highest_supported_protocol_version_for_testing(&mut self, val: bool) {
5067        self.feature_flags
5068            .advance_to_highest_supported_protocol_version = val
5069    }
5070    pub fn set_commit_root_state_digest_supported_for_testing(&mut self, val: bool) {
5071        self.feature_flags.commit_root_state_digest = val
5072    }
5073    pub fn set_zklogin_auth_for_testing(&mut self, val: bool) {
5074        self.feature_flags.zklogin_auth = val
5075    }
5076    pub fn set_enable_jwk_consensus_updates_for_testing(&mut self, val: bool) {
5077        self.feature_flags.enable_jwk_consensus_updates = val
5078    }
5079    pub fn set_random_beacon_for_testing(&mut self, val: bool) {
5080        self.feature_flags.random_beacon = val
5081    }
5082
5083    pub fn set_upgraded_multisig_for_testing(&mut self, val: bool) {
5084        self.feature_flags.upgraded_multisig_supported = val
5085    }
5086    pub fn set_accept_zklogin_in_multisig_for_testing(&mut self, val: bool) {
5087        self.feature_flags.accept_zklogin_in_multisig = val
5088    }
5089
5090    pub fn set_shared_object_deletion_for_testing(&mut self, val: bool) {
5091        self.feature_flags.shared_object_deletion = val;
5092    }
5093
5094    pub fn set_narwhal_new_leader_election_schedule_for_testing(&mut self, val: bool) {
5095        self.feature_flags.narwhal_new_leader_election_schedule = val;
5096    }
5097
5098    pub fn set_receive_object_for_testing(&mut self, val: bool) {
5099        self.feature_flags.receive_objects = val
5100    }
5101    pub fn set_narwhal_certificate_v2_for_testing(&mut self, val: bool) {
5102        self.feature_flags.narwhal_certificate_v2 = val
5103    }
5104    pub fn set_verify_legacy_zklogin_address_for_testing(&mut self, val: bool) {
5105        self.feature_flags.verify_legacy_zklogin_address = val
5106    }
5107
5108    pub fn set_per_object_congestion_control_mode_for_testing(
5109        &mut self,
5110        val: PerObjectCongestionControlMode,
5111    ) {
5112        self.feature_flags.per_object_congestion_control_mode = val;
5113    }
5114
5115    pub fn set_consensus_choice_for_testing(&mut self, val: ConsensusChoice) {
5116        self.feature_flags.consensus_choice = val;
5117    }
5118
5119    pub fn set_consensus_network_for_testing(&mut self, val: ConsensusNetwork) {
5120        self.feature_flags.consensus_network = val;
5121    }
5122
5123    pub fn set_zklogin_max_epoch_upper_bound_delta_for_testing(&mut self, val: Option<u64>) {
5124        self.feature_flags.zklogin_max_epoch_upper_bound_delta = val
5125    }
5126
5127    pub fn set_disable_bridge_for_testing(&mut self) {
5128        self.feature_flags.bridge = false
5129    }
5130
5131    pub fn set_mysticeti_num_leaders_per_round_for_testing(&mut self, val: Option<usize>) {
5132        self.feature_flags.mysticeti_num_leaders_per_round = val;
5133    }
5134
5135    pub fn set_enable_soft_bundle_for_testing(&mut self, val: bool) {
5136        self.feature_flags.soft_bundle = val;
5137    }
5138
5139    pub fn set_passkey_auth_for_testing(&mut self, val: bool) {
5140        self.feature_flags.passkey_auth = val
5141    }
5142
5143    pub fn set_enable_party_transfer_for_testing(&mut self, val: bool) {
5144        self.feature_flags.enable_party_transfer = val
5145    }
5146
5147    pub fn set_consensus_distributed_vote_scoring_strategy_for_testing(&mut self, val: bool) {
5148        self.feature_flags
5149            .consensus_distributed_vote_scoring_strategy = val;
5150    }
5151
5152    pub fn set_consensus_round_prober_for_testing(&mut self, val: bool) {
5153        self.feature_flags.consensus_round_prober = val;
5154    }
5155
5156    pub fn set_disallow_new_modules_in_deps_only_packages_for_testing(&mut self, val: bool) {
5157        self.feature_flags
5158            .disallow_new_modules_in_deps_only_packages = val;
5159    }
5160
5161    pub fn set_correct_gas_payment_limit_check_for_testing(&mut self, val: bool) {
5162        self.feature_flags.correct_gas_payment_limit_check = val;
5163    }
5164
5165    pub fn set_address_aliases_for_testing(&mut self, val: bool) {
5166        self.feature_flags.address_aliases = val;
5167    }
5168
5169    pub fn set_consensus_round_prober_probe_accepted_rounds(&mut self, val: bool) {
5170        self.feature_flags
5171            .consensus_round_prober_probe_accepted_rounds = val;
5172    }
5173
5174    pub fn set_mysticeti_fastpath_for_testing(&mut self, val: bool) {
5175        self.feature_flags.mysticeti_fastpath = val;
5176    }
5177
5178    pub fn set_accept_passkey_in_multisig_for_testing(&mut self, val: bool) {
5179        self.feature_flags.accept_passkey_in_multisig = val;
5180    }
5181
5182    pub fn set_consensus_batched_block_sync_for_testing(&mut self, val: bool) {
5183        self.feature_flags.consensus_batched_block_sync = val;
5184    }
5185
5186    pub fn set_record_time_estimate_processed_for_testing(&mut self, val: bool) {
5187        self.feature_flags.record_time_estimate_processed = val;
5188    }
5189
5190    pub fn set_prepend_prologue_tx_in_consensus_commit_in_checkpoints_for_testing(
5191        &mut self,
5192        val: bool,
5193    ) {
5194        self.feature_flags
5195            .prepend_prologue_tx_in_consensus_commit_in_checkpoints = val;
5196    }
5197
5198    pub fn enable_accumulators_for_testing(&mut self) {
5199        self.feature_flags.enable_accumulators = true;
5200    }
5201
5202    pub fn disable_accumulators_for_testing(&mut self) {
5203        self.feature_flags.enable_accumulators = false;
5204        self.feature_flags.enable_address_balance_gas_payments = false;
5205    }
5206
5207    pub fn enable_coin_reservation_for_testing(&mut self) {
5208        self.feature_flags.enable_coin_reservation_obj_refs = true;
5209        self.feature_flags
5210            .convert_withdrawal_compatibility_ptb_arguments = true;
5211        // Ensure execution_version >= 4 so new_vm_enabled() returns true,
5212        // which is required for enable_coin_reservation_obj_refs() to return true.
5213        self.execution_version = Some(self.execution_version.map_or(4, |v| v.max(4)));
5214    }
5215
5216    pub fn disable_coin_reservation_for_testing(&mut self) {
5217        self.feature_flags.enable_coin_reservation_obj_refs = false;
5218        self.feature_flags
5219            .convert_withdrawal_compatibility_ptb_arguments = false;
5220    }
5221
5222    pub fn create_root_accumulator_object_for_testing(&mut self) {
5223        self.feature_flags.create_root_accumulator_object = true;
5224    }
5225
5226    pub fn disable_create_root_accumulator_object_for_testing(&mut self) {
5227        self.feature_flags.create_root_accumulator_object = false;
5228    }
5229
5230    pub fn enable_address_balance_gas_payments_for_testing(&mut self) {
5231        self.feature_flags.enable_accumulators = true;
5232        self.feature_flags.allow_private_accumulator_entrypoints = true;
5233        self.feature_flags.enable_address_balance_gas_payments = true;
5234        self.feature_flags.address_balance_gas_check_rgp_at_signing = true;
5235        self.feature_flags.address_balance_gas_reject_gas_coin_arg = false;
5236        self.execution_version = Some(self.execution_version.map_or(4, |v| v.max(4)))
5237    }
5238
5239    pub fn disable_address_balance_gas_payments_for_testing(&mut self) {
5240        self.feature_flags.enable_address_balance_gas_payments = false;
5241    }
5242
5243    pub fn enable_gasless_for_testing(&mut self) {
5244        self.enable_address_balance_gas_payments_for_testing();
5245        self.feature_flags.enable_gasless = true;
5246        self.feature_flags.gasless_verify_remaining_balance = true;
5247        self.gasless_max_computation_units = Some(50_000);
5248        self.gasless_allowed_token_types = Some(vec![]);
5249        self.gasless_max_tps = Some(1000);
5250    }
5251
5252    pub fn disable_gasless_for_testing(&mut self) {
5253        self.feature_flags.enable_gasless = false;
5254        self.gasless_max_computation_units = None;
5255        self.gasless_allowed_token_types = None;
5256    }
5257
5258    pub fn set_gasless_allowed_token_types_for_testing(&mut self, types: Vec<(String, u64)>) {
5259        self.gasless_allowed_token_types = Some(types);
5260    }
5261
5262    pub fn enable_multi_epoch_transaction_expiration_for_testing(&mut self) {
5263        self.feature_flags.enable_multi_epoch_transaction_expiration = true;
5264    }
5265
5266    pub fn enable_authenticated_event_streams_for_testing(&mut self) {
5267        self.enable_accumulators_for_testing();
5268        self.feature_flags.enable_authenticated_event_streams = true;
5269        self.feature_flags
5270            .include_checkpoint_artifacts_digest_in_summary = true;
5271        self.feature_flags.split_checkpoints_in_consensus_handler = true;
5272    }
5273
5274    pub fn disable_authenticated_event_streams_for_testing(&mut self) {
5275        self.feature_flags.enable_authenticated_event_streams = false;
5276    }
5277
5278    pub fn disable_randomize_checkpoint_tx_limit_for_testing(&mut self) {
5279        self.feature_flags.randomize_checkpoint_tx_limit_in_tests = false;
5280    }
5281
5282    pub fn enable_non_exclusive_writes_for_testing(&mut self) {
5283        self.feature_flags.enable_non_exclusive_writes = true;
5284    }
5285
5286    pub fn set_relax_valid_during_for_owned_inputs_for_testing(&mut self, val: bool) {
5287        self.feature_flags.relax_valid_during_for_owned_inputs = val;
5288    }
5289
5290    pub fn set_ignore_execution_time_observations_after_certs_closed_for_testing(
5291        &mut self,
5292        val: bool,
5293    ) {
5294        self.feature_flags
5295            .ignore_execution_time_observations_after_certs_closed = val;
5296    }
5297
5298    pub fn set_consensus_checkpoint_signature_key_includes_digest_for_testing(
5299        &mut self,
5300        val: bool,
5301    ) {
5302        self.feature_flags
5303            .consensus_checkpoint_signature_key_includes_digest = val;
5304    }
5305
5306    pub fn set_cancel_for_failed_dkg_early_for_testing(&mut self, val: bool) {
5307        self.feature_flags.cancel_for_failed_dkg_early = val;
5308    }
5309
5310    pub fn set_use_mfp_txns_in_load_initial_object_debts_for_testing(&mut self, val: bool) {
5311        self.feature_flags.use_mfp_txns_in_load_initial_object_debts = val;
5312    }
5313
5314    pub fn set_authority_capabilities_v2_for_testing(&mut self, val: bool) {
5315        self.feature_flags.authority_capabilities_v2 = val;
5316    }
5317
5318    pub fn allow_references_in_ptbs_for_testing(&mut self) {
5319        self.feature_flags.allow_references_in_ptbs = true;
5320    }
5321
5322    pub fn set_consensus_skip_gced_accept_votes_for_testing(&mut self, val: bool) {
5323        self.feature_flags.consensus_skip_gced_accept_votes = val;
5324    }
5325
5326    pub fn set_enable_object_funds_withdraw_for_testing(&mut self, val: bool) {
5327        self.feature_flags.enable_object_funds_withdraw = val;
5328    }
5329
5330    pub fn set_split_checkpoints_in_consensus_handler_for_testing(&mut self, val: bool) {
5331        self.feature_flags.split_checkpoints_in_consensus_handler = val;
5332    }
5333
5334    pub fn set_merge_randomness_into_checkpoint_for_testing(&mut self, val: bool) {
5335        self.feature_flags.merge_randomness_into_checkpoint = val;
5336    }
5337}
5338
5339#[cfg(not(msim))]
5340type OverrideFn = dyn Fn(ProtocolVersion, ProtocolConfig) -> ProtocolConfig + Send + Sync;
5341
5342#[cfg(not(msim))]
5343static CONFIG_OVERRIDE: Mutex<Option<Box<OverrideFn>>> = Mutex::new(None);
5344
5345#[cfg(msim)]
5346type OverrideFn = dyn Fn(ProtocolVersion, ProtocolConfig) -> ProtocolConfig + Send;
5347
5348#[cfg(msim)]
5349thread_local! {
5350    static CONFIG_OVERRIDE: RefCell<Option<Box<OverrideFn>>> = RefCell::new(None);
5351}
5352
5353#[must_use]
5354pub struct OverrideGuard;
5355
5356#[cfg(not(msim))]
5357impl Drop for OverrideGuard {
5358    fn drop(&mut self) {
5359        info!("restoring override fn");
5360        *CONFIG_OVERRIDE.lock().unwrap() = None;
5361    }
5362}
5363
5364#[cfg(msim)]
5365impl Drop for OverrideGuard {
5366    fn drop(&mut self) {
5367        info!("restoring override fn");
5368        CONFIG_OVERRIDE.with(|ovr| {
5369            *ovr.borrow_mut() = None;
5370        });
5371    }
5372}
5373
5374/// Defines which limit got crossed.
5375/// The value which crossed the limit and value of the limit crossed are embedded
5376#[derive(PartialEq, Eq)]
5377pub enum LimitThresholdCrossed {
5378    None,
5379    Soft(u128, u128),
5380    Hard(u128, u128),
5381}
5382
5383/// Convenience function for comparing limit ranges
5384/// V::MAX must be at >= U::MAX and T::MAX
5385pub fn check_limit_in_range<T: Into<V>, U: Into<V>, V: PartialOrd + Into<u128>>(
5386    x: T,
5387    soft_limit: U,
5388    hard_limit: V,
5389) -> LimitThresholdCrossed {
5390    let x: V = x.into();
5391    let soft_limit: V = soft_limit.into();
5392
5393    debug_assert!(soft_limit <= hard_limit);
5394
5395    // It is important to preserve this comparison order because if soft_limit == hard_limit
5396    // we want LimitThresholdCrossed::Hard
5397    if x >= hard_limit {
5398        LimitThresholdCrossed::Hard(x.into(), hard_limit.into())
5399    } else if x < soft_limit {
5400        LimitThresholdCrossed::None
5401    } else {
5402        LimitThresholdCrossed::Soft(x.into(), soft_limit.into())
5403    }
5404}
5405
5406#[macro_export]
5407macro_rules! check_limit {
5408    ($x:expr, $hard:expr) => {
5409        check_limit!($x, $hard, $hard)
5410    };
5411    ($x:expr, $soft:expr, $hard:expr) => {
5412        check_limit_in_range($x as u64, $soft, $hard)
5413    };
5414}
5415
5416/// Used to check which limits were crossed if the TX is metered (not system tx)
5417/// Args are: is_metered, value_to_check, metered_limit, unmetered_limit
5418/// metered_limit is always less than or equal to unmetered_hard_limit
5419#[macro_export]
5420macro_rules! check_limit_by_meter {
5421    ($is_metered:expr, $x:expr, $metered_limit:expr, $unmetered_hard_limit:expr, $metric:expr) => {{
5422        // If this is metered, we use the metered_limit limit as the upper bound
5423        let (h, metered_str) = if $is_metered {
5424            ($metered_limit, "metered")
5425        } else {
5426            // Unmetered gets more headroom
5427            ($unmetered_hard_limit, "unmetered")
5428        };
5429        use sui_protocol_config::check_limit_in_range;
5430        let result = check_limit_in_range($x as u64, $metered_limit, h);
5431        match result {
5432            LimitThresholdCrossed::None => {}
5433            LimitThresholdCrossed::Soft(_, _) => {
5434                $metric.with_label_values(&[metered_str, "soft"]).inc();
5435            }
5436            LimitThresholdCrossed::Hard(_, _) => {
5437                $metric.with_label_values(&[metered_str, "hard"]).inc();
5438            }
5439        };
5440        result
5441    }};
5442}
5443
5444// Amendments tables
5445
5446pub type Amendments = BTreeMap<AccountAddress, BTreeMap<AccountAddress, AccountAddress>>;
5447
5448static MAINNET_LINKAGE_AMENDMENTS: LazyLock<Arc<Amendments>> =
5449    LazyLock::new(|| parse_amendments(include_str!("mainnet_amendments.json")));
5450
5451static TESTNET_LINKAGE_AMENDMENTS: LazyLock<Arc<Amendments>> =
5452    LazyLock::new(|| parse_amendments(include_str!("testnet_amendments.json")));
5453
5454fn parse_amendments(json: &str) -> Arc<Amendments> {
5455    #[derive(serde::Deserialize)]
5456    struct AmendmentEntry {
5457        root: String,
5458        deps: Vec<DepEntry>,
5459    }
5460
5461    #[derive(serde::Deserialize)]
5462    struct DepEntry {
5463        original_id: String,
5464        version_id: String,
5465    }
5466
5467    let entries: Vec<AmendmentEntry> =
5468        serde_json::from_str(json).expect("Failed to parse amendments JSON");
5469    let mut amendments = BTreeMap::new();
5470    for entry in entries {
5471        let root_id = AccountAddress::from_hex_literal(&entry.root).unwrap();
5472        let mut dep_ids = BTreeMap::new();
5473        for dep in entry.deps {
5474            let orig_id = AccountAddress::from_hex_literal(&dep.original_id).unwrap();
5475            let upgraded_id = AccountAddress::from_hex_literal(&dep.version_id).unwrap();
5476            assert!(
5477                dep_ids.insert(orig_id, upgraded_id).is_none(),
5478                "Duplicate original ID in amendments table"
5479            );
5480        }
5481        assert!(
5482            amendments.insert(root_id, dep_ids).is_none(),
5483            "Duplicate root ID in amendments table"
5484        );
5485    }
5486    Arc::new(amendments)
5487}
5488
5489#[cfg(all(test, not(msim)))]
5490mod test {
5491    use insta::assert_yaml_snapshot;
5492
5493    use super::*;
5494
5495    #[test]
5496    fn snapshot_tests() {
5497        println!("\n============================================================================");
5498        println!("!                                                                          !");
5499        println!("! IMPORTANT: never update snapshots from this test. only add new versions! !");
5500        println!("!                                                                          !");
5501        println!("============================================================================\n");
5502        for chain_id in &[Chain::Unknown, Chain::Mainnet, Chain::Testnet] {
5503            // make Chain::Unknown snapshots compatible with pre-chain-id snapshots so that we
5504            // don't break the release-time compatibility tests. Once Chain Id configs have been
5505            // released everywhere, we can remove this and only test Mainnet and Testnet
5506            let chain_str = match chain_id {
5507                Chain::Unknown => "".to_string(),
5508                _ => format!("{:?}_", chain_id),
5509            };
5510            for i in MIN_PROTOCOL_VERSION..=MAX_PROTOCOL_VERSION {
5511                let cur = ProtocolVersion::new(i);
5512                assert_yaml_snapshot!(
5513                    format!("{}version_{}", chain_str, cur.as_u64()),
5514                    ProtocolConfig::get_for_version(cur, *chain_id)
5515                );
5516            }
5517        }
5518    }
5519
5520    #[test]
5521    fn test_getters() {
5522        let prot: ProtocolConfig =
5523            ProtocolConfig::get_for_version(ProtocolVersion::new(1), Chain::Unknown);
5524        assert_eq!(
5525            prot.max_arguments(),
5526            prot.max_arguments_as_option().unwrap()
5527        );
5528    }
5529
5530    #[test]
5531    fn test_setters() {
5532        let mut prot: ProtocolConfig =
5533            ProtocolConfig::get_for_version(ProtocolVersion::new(1), Chain::Unknown);
5534        prot.set_max_arguments_for_testing(123);
5535        assert_eq!(prot.max_arguments(), 123);
5536
5537        prot.set_max_arguments_from_str_for_testing("321".to_string());
5538        assert_eq!(prot.max_arguments(), 321);
5539
5540        prot.disable_max_arguments_for_testing();
5541        assert_eq!(prot.max_arguments_as_option(), None);
5542
5543        prot.set_attr_for_testing("max_arguments".to_string(), "456".to_string());
5544        assert_eq!(prot.max_arguments(), 456);
5545    }
5546
5547    #[test]
5548    fn test_get_for_version_if_supported_applies_test_overrides() {
5549        let before =
5550            ProtocolConfig::get_for_version_if_supported(ProtocolVersion::new(1), Chain::Unknown)
5551                .unwrap();
5552
5553        assert!(!before.enable_coin_reservation_obj_refs());
5554
5555        let _guard = ProtocolConfig::apply_overrides_for_testing(|_, mut cfg| {
5556            cfg.enable_coin_reservation_for_testing();
5557            cfg
5558        });
5559
5560        let after =
5561            ProtocolConfig::get_for_version_if_supported(ProtocolVersion::new(1), Chain::Unknown)
5562                .unwrap();
5563
5564        assert!(after.enable_coin_reservation_obj_refs());
5565    }
5566
5567    #[test]
5568    #[should_panic(expected = "unsupported version")]
5569    fn max_version_test() {
5570        // When this does not panic, version higher than MAX_PROTOCOL_VERSION exists.
5571        // To fix, bump MAX_PROTOCOL_VERSION or disable this check for the version.
5572        let _ = ProtocolConfig::get_for_version_impl(
5573            ProtocolVersion::new(MAX_PROTOCOL_VERSION + 1),
5574            Chain::Unknown,
5575        );
5576    }
5577
5578    #[test]
5579    fn lookup_by_string_test() {
5580        let prot: ProtocolConfig =
5581            ProtocolConfig::get_for_version(ProtocolVersion::new(1), Chain::Unknown);
5582        // Does not exist
5583        assert!(prot.lookup_attr("some random string".to_string()).is_none());
5584
5585        assert!(
5586            prot.lookup_attr("max_arguments".to_string())
5587                == Some(ProtocolConfigValue::u32(prot.max_arguments())),
5588        );
5589
5590        // We didnt have this in version 1
5591        assert!(
5592            prot.lookup_attr("max_move_identifier_len".to_string())
5593                .is_none()
5594        );
5595
5596        // But we did in version 9
5597        let prot: ProtocolConfig =
5598            ProtocolConfig::get_for_version(ProtocolVersion::new(9), Chain::Unknown);
5599        assert!(
5600            prot.lookup_attr("max_move_identifier_len".to_string())
5601                == Some(ProtocolConfigValue::u64(prot.max_move_identifier_len()))
5602        );
5603
5604        let prot: ProtocolConfig =
5605            ProtocolConfig::get_for_version(ProtocolVersion::new(1), Chain::Unknown);
5606        // We didnt have this in version 1
5607        assert!(
5608            prot.attr_map()
5609                .get("max_move_identifier_len")
5610                .unwrap()
5611                .is_none()
5612        );
5613        // We had this in version 1
5614        assert!(
5615            prot.attr_map().get("max_arguments").unwrap()
5616                == &Some(ProtocolConfigValue::u32(prot.max_arguments()))
5617        );
5618
5619        // Check feature flags
5620        let prot: ProtocolConfig =
5621            ProtocolConfig::get_for_version(ProtocolVersion::new(1), Chain::Unknown);
5622        // Does not exist
5623        assert!(
5624            prot.feature_flags
5625                .lookup_attr("some random string".to_owned())
5626                .is_none()
5627        );
5628        assert!(
5629            !prot
5630                .feature_flags
5631                .attr_map()
5632                .contains_key("some random string")
5633        );
5634
5635        // Was false in v1
5636        assert!(
5637            prot.feature_flags
5638                .lookup_attr("package_upgrades".to_owned())
5639                == Some(false)
5640        );
5641        assert!(
5642            prot.feature_flags
5643                .attr_map()
5644                .get("package_upgrades")
5645                .unwrap()
5646                == &false
5647        );
5648        let prot: ProtocolConfig =
5649            ProtocolConfig::get_for_version(ProtocolVersion::new(4), Chain::Unknown);
5650        // Was true from v3 and up
5651        assert!(
5652            prot.feature_flags
5653                .lookup_attr("package_upgrades".to_owned())
5654                == Some(true)
5655        );
5656        assert!(
5657            prot.feature_flags
5658                .attr_map()
5659                .get("package_upgrades")
5660                .unwrap()
5661                == &true
5662        );
5663    }
5664
5665    #[test]
5666    fn limit_range_fn_test() {
5667        let low = 100u32;
5668        let high = 10000u64;
5669
5670        assert!(check_limit!(1u8, low, high) == LimitThresholdCrossed::None);
5671        assert!(matches!(
5672            check_limit!(255u16, low, high),
5673            LimitThresholdCrossed::Soft(255u128, 100)
5674        ));
5675        // This wont compile because lossy
5676        //assert!(check_limit!(100000000u128, low, high) == LimitThresholdCrossed::None);
5677        // This wont compile because lossy
5678        //assert!(check_limit!(100000000usize, low, high) == LimitThresholdCrossed::None);
5679
5680        assert!(matches!(
5681            check_limit!(2550000u64, low, high),
5682            LimitThresholdCrossed::Hard(2550000, 10000)
5683        ));
5684
5685        assert!(matches!(
5686            check_limit!(2550000u64, high, high),
5687            LimitThresholdCrossed::Hard(2550000, 10000)
5688        ));
5689
5690        assert!(matches!(
5691            check_limit!(1u8, high),
5692            LimitThresholdCrossed::None
5693        ));
5694
5695        assert!(check_limit!(255u16, high) == LimitThresholdCrossed::None);
5696
5697        assert!(matches!(
5698            check_limit!(2550000u64, high),
5699            LimitThresholdCrossed::Hard(2550000, 10000)
5700        ));
5701    }
5702
5703    #[test]
5704    fn linkage_amendments_load() {
5705        let mainnet = LazyLock::force(&MAINNET_LINKAGE_AMENDMENTS);
5706        let testnet = LazyLock::force(&TESTNET_LINKAGE_AMENDMENTS);
5707        assert!(!mainnet.is_empty(), "mainnet amendments must not be empty");
5708        assert!(!testnet.is_empty(), "testnet amendments must not be empty");
5709    }
5710}