sui_protocol_config/
lib.rs

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