sui_protocol_config/
lib.rs

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