sui_protocol_config/
lib.rs

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