Skip to main content

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