iota_protocol_config/lib.rs
1// Copyright (c) Mysten Labs, Inc.
2// Modifications Copyright (c) 2024 IOTA Stiftung
3// SPDX-License-Identifier: Apache-2.0
4
5use std::{
6 cell::RefCell,
7 cmp::min,
8 sync::atomic::{AtomicBool, Ordering},
9};
10
11use clap::*;
12use iota_protocol_config_macros::{
13 ProtocolConfigAccessors, ProtocolConfigFeatureFlagsGetters, ProtocolConfigOverride,
14};
15use move_vm_config::verifier::{MeterConfig, VerifierConfig};
16use serde::{Deserialize, Serialize};
17use serde_with::skip_serializing_none;
18use tracing::{info, warn};
19
20/// The minimum and maximum protocol versions supported by this build.
21const MIN_PROTOCOL_VERSION: u64 = 1;
22pub const MAX_PROTOCOL_VERSION: u64 = 41;
23
24/// Protocol version that IIP8 took effect.
25pub const PROTOCOL_VERSION_IIP8: u64 = 20;
26// Record history of protocol version allocations here:
27//
28// Version 1: Original version.
29// Version 2: Don't redistribute slashed staking rewards, fix computation of
30// SystemEpochInfoEventV1.
31// Version 3: Set the `relocate_event_module` to be true so that the module
32// that is associated as the "sending module" for an event is
33// relocated by linkage.
34// Add `Clock` based unlock to `Timelock` objects.
35// Version 4: Introduce the `max_type_to_layout_nodes` config that sets the
36// maximal nodes which are allowed when converting to a type layout.
37// Version 5: Introduce fixed protocol-defined base fee, IotaSystemStateV2 and
38// SystemEpochInfoEventV2.
39// Disallow adding new modules in `deps-only` packages.
40// Improve gas/wall time efficiency of some Move stdlib vector
41// functions.
42// Add new gas model version to update charging of functions.
43// Enable proper conversion of certain type argument errors in the
44// execution layer.
45// Version 6: Bound size of values created in the adapter.
46// Version 7: Improve handling of stake withdrawal from candidate validators.
47// Version 8: Variants as type nodes.
48// Enable smart ancestor selection for testnet.
49// Enable probing for accepted rounds in round prober for testnet.
50// Switch to distributed vote scoring in consensus in testnet.
51// Enable zstd compression for consensus tonic network in testnet.
52// Enable consensus garbage collection for testnet
53// Enable the new consensus commit rule for testnet.
54// Enable min_free_execution_slot for the shared object congestion
55// tracker in devnet.
56// Version 9: Disable smart ancestor selection for the testnet.
57// Enable zstd compression for consensus tonic network in mainnet.
58// Enable passkey auth in multisig for devnet.
59// Remove the iota-bridge from the framework.
60// Version 10: Enable min_free_execution_slot for the shared object congestion
61// tracker in all networks.
62// Increase the committee size to 80 on all networks.
63// Enable round prober in consensus for mainnet.
64// Enable probing for accepted rounds in round prober for mainnet.
65// Switch to distributed vote scoring in consensus for mainnet.
66// Enable the new consensus commit rule for mainnet.
67// Enable consensus garbage collection for mainnet with GC depth set
68// to 60 rounds.
69// Enable batching in synchronizer for testnet
70// Enable the gas price feedback mechanism in devnet.
71// Enable Identifier input validation.
72// Removes unnecessary child object mutations
73// Add additional signature checks
74// Add additional linkage checks
75// Version 11: Framework fix regarding candidate validator commission rate.
76// Version 12: Enable the gas price feedback mechanism in all networks.
77// Enable the normalization of PTB arguments.
78// Version 13: Introduce logic to allow the committee to be selected from a set
79// of eligible active validators.
80// Enable processing and tracking AuthorityCapabilitiesV1 from
81// non-committee validators in the devnet.
82// Version 14: Switches the consensus protocol to Starfish in devnet.
83// Enable median-based commit timestamp calculation in consensus,
84// and enforce checkpoint timestamp monotonicity for testnet.
85// Enable batched block sync for mainnet.
86// Enable selecting committee only from active validators that
87// support the next epoch's version and issued valid
88// AuthorityCapabilities notification in testnet.
89// Version 15: Enable shared object transaction bursts of 10 times average load
90// on devnet.
91// Version 16: Enable selecting committee only from active validators that
92// support the next epoch's version and issued valid
93// AuthorityCapabilities notification.
94// Enable committing transactions only for traversed headers in
95// Starfish.
96// Version 17: Increase the committee size to 100 on all networks.
97// Version 18: Enable passkey authentication support in testnet.
98// Version 19: Enable congestion limit overshoot in the gas price feedback
99// mechanism on devnet.
100// Enable a separate gas price feedback mechanism for transactions
101// using randomness on devnet.
102// Allow metadata bytes indexed with a dedicated key in compiled
103// Move modules in devnet.
104// Enable publishing package metadata v1 along with the package in
105// devnet.
106// Enable Move-based account authentication in devnet.
107// Increase the base cost for transfer receive object in devnet.
108// Switch consensus protocol to Starfish in testnet.
109// Enable passkey authentication support in mainnet.
110// Change epoch transaction will contain validator scores.
111// Enable validator scoring on testnet and enable adjustment of
112// validator rewards based on scores on Devnet.
113// Version 20: Supports the calculation of validator scores while still passing
114// a default score value to the advance_epoch call. Enables this
115// decoupling on Testnet; Devnet and Mainnet behavior remain the
116// same.
117// Introduce Dynamic Minimum Commission (IIP-8) on all networks.
118// Version 21: Enable overshoot of 100 in congestion control on testnet.
119// Enable congestion limit overshoot in the gas price feedback
120// mechanism on testnet.
121// Enable a separate gas price feedback mechanism for transactions
122// using randomness on testnet.
123// Enable fast commit syncer for faster recovery in devnet.
124// Add auth_context_tx native functions costs.
125// Reduce max_auth_gas in Devnet.
126// Version 22: Enable overshoot of 100 in congestion control on all networks.
127// Enable congestion limit overshoot in the gas price feedback
128// mechanism on all networks.
129// Enable a separate gas price feedback mechanism for transactions
130// using randomness on all networks.
131// Enable Move-based account authentication in testnet.
132// Enable fast commit syncer for faster recovery on testnet.
133// Version 23: Enable Move native context (TxContext via native functions) in
134// all networks. TxContext fields are read via native functions
135// instead of being deserialized from a BCS-encoded struct.
136// Enables sponsor, rgp, gas_price, and gas_budget to be exposed to
137// Move.
138// Version 24: Switch consensus protocol to Starfish in all networks.
139// Enable Move-based sponsor account authentication in devnet.
140// Add AuthContext native functions cost for reading tx_data_bytes.
141// Enable additional borrow checks.
142// Version 25: Deprecate zkLogin related parameters since zkLogin is no longer
143// supported.
144// Version 26: Introduce a module to allow Move code to query protocol feature
145// flags at runtime.
146// Version 27: Only sponsor Move authentication is performed pre-consensus in
147// devnet.
148// Enable consensus block restrictions on testnet and devnet:
149// bound block-header size to O(committee_size) and enable
150// garbage collection in the block manager.
151// Version 28: Move authenticator contracts can now inspect which authenticator
152// function the sender and sponsor used during transaction execution
153// via new AuthContext accessors.
154// Enable Move-based account authentication in mainnet.
155// Enable Move-based sponsor account authentication in testnet.
156// Version 29: Keep advancing the random beacon DKG state machine on every
157// commit while it is still pending -- regardless of whether new DKG
158// messages or confirmations arrived that commit -- so DKG resolves
159// from persisted state (completing, or failing once the timeout
160// round passes) even with no fresh inbound traffic, e.g. after a
161// validator restart. Without this it can stay pending forever and
162// block epoch close.
163// Enable median-based commit timestamp calculation in consensus,
164// and enforce checkpoint timestamp monotonicity for mainnet.
165// Enable fast commit syncer for faster recovery on all networks.
166// Enable consensus block restrictions on all networks:
167// bound block-header size to O(committee_size) and enable
168// garbage collection in the block manager.
169// Version 30: Extend the protocol_config framework module with a generic
170// `get_attr<T>` native that lets Move code read any numeric or
171// boolean protocol parameter by name, returning T directly and
172// aborting on error.
173// Expose `is_feature_enabled` and `get_attr<T>` natives to the
174// iota_system package via a new iota_system::protocol_config
175// module.
176// Version 31: Rebuild the framework binaries for the latest iota_system
177// validator set changes.
178// Enable validator metadata verification v2.
179// Amortize the minimum checkpoint interval over a sliding window
180// on non-Mainnet/Testnet chains.
181// Start publishing package metadata using module metadata as a
182// dynamic field.
183// Report a failure of the Move authentication with a distinct
184// `MoveAuthentication` execution error.
185// Enable the optimistic commit rule (StarfishSpeed) in Starfish
186// consensus on devnet.
187// Version 32: Move validator count limits (min/max validator count) and
188// stake thresholds (joining stake, low/very low stake
189// thresholds, grace period) into the protocol config.
190// Enable the optimistic commit rule (StarfishSpeed) in Starfish
191// consensus on testnet.
192// Amortize the minimum checkpoint interval over a sliding window
193// on testnet.
194// Start publishing package metadata using module metadata as a
195// dynamic field on testnet.
196// Enable the redesigned leader schedule (sliding-window reputation
197// scoring and absolute-score bad-node selection) in Starfish
198// consensus on devnet.
199// Enable Move-based sponsor account authentication on mainnet.
200// Only sponsor Move authentication is performed pre-consensus on
201// mainnet.
202// Enable the P-COOL flow on devnet.
203// Version 33: Amortize the minimum checkpoint interval over a sliding window
204// on mainnet.
205// Enable the sliding-window reputation scoring and absolute-score
206// bad-node selection on testnet
207// Version 34: Bump the scorer version to 2 on devnet: misbehavior reports
208// carry a dedicated counter for invalid bundle parts, previously
209// folded into the unprovable block-fault counter.
210// Add the `iota::transaction_deny_rules` framework module and its
211// reserved object ID 0xDE9 (dormant until deny-rule governance
212// activates).
213// Stop locking immutable objects in post-consensus conflict
214// resolution.
215// Disable Move-based sponsor account authentication on mainnet.
216// Version 35: Scale the PTB value size limit by the value's type.
217// Allow objects created or mutated by system transactions to exceed
218// the max object size limit.
219// Enable the optimistic commit rule (StarfishSpeed) in Starfish
220// consensus on mainnet.
221// Meter the packages a transaction publishes with the protocol
222// config's verifier limits in post-consensus validation, and set
223// those limits to the node config's defaults on all chains
224// (inert where the P-COOL flow is off).
225// Start publishing package metadata using module metadata as a
226// dynamic field on mainnet.
227// Enable the redesigned leader schedule (sliding-window reputation
228// scoring and absolute-score bad-node selection) in Starfish
229// consensus on mainnet.
230// Version 36: Reject a transaction whose sender or sponsor is authenticated by
231// a `MoveAuthenticator` with an immutable account object.
232// Version 37: Reject a transaction that names an object version in the range
233// assigned to canceled transactions, or one below it, from the
234// transaction bytes, before any object is loaded.
235// Reject `<SELF>` as an identifier in published modules.
236// Make the enum variant count limit explicit in the protocol
237// config.
238// Check the package that holds a `MoveAuthenticator`'s
239// authenticate function, and that package's dependencies, against
240// the package deny list.
241// Require the version field of a published module header to be the
242// encoding the serializer produces for that version, rejecting a
243// non-zero flavor byte below binary format version 7.
244// Reject the randomness state object as a `MoveAuthenticator`
245// input.
246// Traverse the module graph when checking a published module for
247// cyclic dependencies, instead of stopping at its immediate
248// dependencies.
249// Version 38: Bound system Move packages by `max_move_system_package_size`
250// rather than the limit that applies to user packages.
251// Abort `iota::account::create_immutable_account_v1`, so no new
252// immutable account object can be created.
253// Validate PTB indices at signing time.
254// Version 39: Allow random beacon DKG to complete after its timeout on devnet
255// and testnet.
256// The consensus handler's processed-transaction cache holds only
257// messages recorded as processed, so a cache hit gives the same
258// answer as the processed-message table on every validator. A
259// user transaction from an authority that has sent EndOfPublish
260// no longer makes a later transaction with the same key in the
261// same commit be skipped as a duplicate.
262// Raise the minimum validator joining stake to 6M IOTA, the low
263// stake threshold to 5.5M IOTA and the very low stake threshold to
264// 5M IOTA on all chains.
265// Reject a multisig whose committee mixes Ed25519 with other key
266// schemes unless every committee member has signed.
267// Enable Groth16 verifying key input length checks before deserialization.
268// Reject the deprecated global storage instructions and non-empty
269// `acquires` lists when execution deserializes a module, and
270// verify modules without the acquires pass and with vector element
271// borrows checked by the call rule.
272// Version 40: Post-consensus validation takes the instantiation-loop graph
273// edge limit, and whether the instantiation-loop check is
274// metered, from the protocol config.
275// Make the packages named by a `MoveAuthenticator`'s type
276// arguments inputs of that authenticator.
277// Limit the struct, enum and vector values in Move-call
278// arguments, per call and per transaction.
279// Reject `<SELF>` as an identifier in transactions, at signing,
280// after consensus and in block verification. Block verification
281// also rejects a block that carries a system transaction kind in
282// a user transaction or certificate.
283// Update the gas model version to 3.
284// Enable validator attestation on devnet, with the checkpoint
285// summary data version that certifies the verdicts.
286// Version 41: Commit a block's transactions once its header is traversed even
287// if its acknowledgment quorum was reached first, outside Mainnet.
288// `ecdsa_r1::secp256r1_ecrecover` rejects a signature whose
289// restored x-coordinate is not below the field modulus.
290#[derive(Copy, Clone, Debug, Hash, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)]
291pub struct ProtocolVersion(u64);
292
293impl ProtocolVersion {
294 // The minimum and maximum protocol version supported by this binary.
295 // Counterintuitively, this constant may change over time as support for old
296 // protocol versions is removed from the source. This ensures that when a
297 // new network (such as a testnet) is created, its genesis committee will
298 // use a protocol version that is actually supported by the binary.
299 pub const MIN: Self = Self(MIN_PROTOCOL_VERSION);
300
301 pub const MAX: Self = Self(MAX_PROTOCOL_VERSION);
302
303 #[cfg(not(msim))]
304 const MAX_ALLOWED: Self = Self::MAX;
305
306 // We create one additional "fake" version in simulator builds so that we can
307 // test upgrades.
308 #[cfg(msim)]
309 pub const MAX_ALLOWED: Self = Self(MAX_PROTOCOL_VERSION + 1);
310
311 pub fn new(v: u64) -> Self {
312 Self(v)
313 }
314
315 pub const fn as_u64(&self) -> u64 {
316 self.0
317 }
318
319 // For serde deserialization - we don't define a Default impl because there
320 // isn't a single universally appropriate default value.
321 pub fn max() -> Self {
322 Self::MAX
323 }
324}
325
326impl From<u64> for ProtocolVersion {
327 fn from(v: u64) -> Self {
328 Self::new(v)
329 }
330}
331
332impl std::ops::Sub<u64> for ProtocolVersion {
333 type Output = Self;
334 fn sub(self, rhs: u64) -> Self::Output {
335 Self::new(self.0 - rhs)
336 }
337}
338
339impl std::ops::Add<u64> for ProtocolVersion {
340 type Output = Self;
341 fn add(self, rhs: u64) -> Self::Output {
342 Self::new(self.0 + rhs)
343 }
344}
345
346#[derive(
347 Clone, Serialize, Deserialize, Debug, PartialEq, Copy, PartialOrd, Ord, Eq, ValueEnum, Default,
348)]
349pub enum Chain {
350 Mainnet,
351 Testnet,
352 #[default]
353 Unknown,
354}
355
356impl Chain {
357 pub fn as_str(self) -> &'static str {
358 match self {
359 Chain::Mainnet => "mainnet",
360 Chain::Testnet => "testnet",
361 Chain::Unknown => "unknown",
362 }
363 }
364}
365
366pub struct Error(pub String);
367
368// TODO: There are quite a few non boolean values in the feature flags. We
369// should move them out.
370/// Records on/off feature flags that may vary at each protocol version.
371#[derive(
372 Default,
373 Clone,
374 Serialize,
375 Deserialize,
376 Debug,
377 ProtocolConfigFeatureFlagsGetters,
378 ProtocolConfigOverride,
379)]
380struct FeatureFlags {
381 // Add feature flags here, e.g.:
382 // new_protocol_feature: bool,
383
384 // Disables unnecessary invariant check in the Move VM when swapping the value out of a local
385 // This flag is used to provide the correct MoveVM configuration for clients.
386 #[serde(skip_serializing_if = "is_true")]
387 disable_invariant_violation_check_in_swap_loc: bool,
388
389 // If true, checks no extra bytes in a compiled module
390 // This flag is used to provide the correct MoveVM configuration for clients.
391 #[serde(skip_serializing_if = "is_true")]
392 no_extraneous_module_bytes: bool,
393
394 // How we order transactions coming out of consensus before sending to execution.
395 #[serde(skip_serializing_if = "ConsensusTransactionOrdering::is_none")]
396 consensus_transaction_ordering: ConsensusTransactionOrdering,
397
398 // If true, use the hardened OTW check
399 // This flag is used to provide the correct MoveVM configuration for clients.
400 #[serde(skip_serializing_if = "is_true")]
401 hardened_otw_check: bool,
402
403 // Enable the poseidon hash function
404 #[serde(skip_serializing_if = "is_false")]
405 enable_poseidon: bool,
406
407 // Enable native function for msm.
408 #[serde(skip_serializing_if = "is_false")]
409 enable_group_ops_native_function_msm: bool,
410
411 // Controls the behavior of per object congestion control in consensus handler.
412 #[serde(skip_serializing_if = "PerObjectCongestionControlMode::is_none")]
413 per_object_congestion_control_mode: PerObjectCongestionControlMode,
414
415 // The consensus protocol to be used for the epoch.
416 #[serde(
417 default = "ConsensusChoice::mysticeti_deprecated",
418 skip_serializing_if = "ConsensusChoice::is_mysticeti_deprecated"
419 )]
420 consensus_choice: ConsensusChoice,
421
422 // Consensus network to use.
423 #[serde(skip_serializing_if = "ConsensusNetwork::is_tonic")]
424 consensus_network: ConsensusNetwork,
425
426 // Set the upper bound allowed for max_epoch in zklogin signature.
427 #[deprecated]
428 #[serde(skip_serializing_if = "Option::is_none")]
429 zklogin_max_epoch_upper_bound_delta: Option<u64>,
430
431 // Enable VDF
432 #[serde(skip_serializing_if = "is_false")]
433 enable_vdf: bool,
434
435 // Enable passkey auth (SIP-9)
436 #[serde(skip_serializing_if = "is_false")]
437 passkey_auth: bool,
438
439 // Rethrow type layout errors during serialization instead of trying to convert them.
440 // This flag is used to provide the correct MoveVM configuration for clients.
441 #[serde(skip_serializing_if = "is_true")]
442 rethrow_serialization_type_layout_errors: bool,
443
444 // Makes the event's sending module version-aware.
445 #[serde(skip_serializing_if = "is_false")]
446 relocate_event_module: bool,
447
448 // Enable a protocol-defined base gas price for all transactions.
449 #[serde(skip_serializing_if = "is_false")]
450 protocol_defined_base_fee: bool,
451
452 // Enable uncompressed group elements in BLS123-81 G1
453 #[serde(skip_serializing_if = "is_false")]
454 uncompressed_g1_group_elements: bool,
455
456 // Disallow adding new modules in `deps-only` packages.
457 #[serde(skip_serializing_if = "is_false")]
458 disallow_new_modules_in_deps_only_packages: bool,
459
460 // Enable v2 native charging for natives.
461 #[serde(skip_serializing_if = "is_false")]
462 native_charging_v2: bool,
463
464 // Properly convert certain type argument errors in the execution layer.
465 #[serde(skip_serializing_if = "is_false")]
466 convert_type_argument_error: bool,
467
468 // Probe rounds received by peers from every authority.
469 #[serde(skip_serializing_if = "is_false")]
470 consensus_round_prober: bool,
471
472 // Use distributed vote leader scoring strategy in consensus.
473 #[serde(skip_serializing_if = "is_false")]
474 consensus_distributed_vote_scoring_strategy: bool,
475
476 // Enables the new logic for collecting the subdag in the consensus linearizer. The new logic
477 // does not stop the recursion at the highest committed round for each authority, but
478 // allows to commit uncommitted blocks up to gc round (excluded) for that authority.
479 #[serde(skip_serializing_if = "is_false")]
480 consensus_linearize_subdag_v2: bool,
481
482 // Variants count as nodes
483 #[serde(skip_serializing_if = "is_false")]
484 variant_nodes: bool,
485
486 // Use smart ancestor selection in consensus.
487 #[serde(skip_serializing_if = "is_false")]
488 consensus_smart_ancestor_selection: bool,
489
490 // Probe accepted rounds in round prober.
491 #[serde(skip_serializing_if = "is_false")]
492 consensus_round_prober_probe_accepted_rounds: bool,
493
494 // If true, enable zstd compression for consensus tonic network.
495 #[serde(skip_serializing_if = "is_false")]
496 consensus_zstd_compression: bool,
497
498 // Use the minimum free execution slot to schedule execution of a transaction in the shared
499 // object congestion tracker.
500 #[serde(skip_serializing_if = "is_false")]
501 congestion_control_min_free_execution_slot: bool,
502
503 // If true, multisig containing passkey sig is accepted.
504 #[serde(skip_serializing_if = "is_false")]
505 accept_passkey_in_multisig: bool,
506
507 // If true, enabled batched block sync in consensus.
508 #[serde(skip_serializing_if = "is_false")]
509 consensus_batched_block_sync: bool,
510
511 // To enable/disable the gas price feedback mechanism used for transactions
512 // cancelled due to shared object congestion
513 #[serde(skip_serializing_if = "is_false")]
514 congestion_control_gas_price_feedback_mechanism: bool,
515
516 // Validate identifier inputs separately
517 #[serde(skip_serializing_if = "is_false")]
518 validate_identifier_inputs: bool,
519
520 // If true, enables the optimizations for child object mutations, removing unnecessary
521 // mutations
522 #[serde(skip_serializing_if = "is_false")]
523 minimize_child_object_mutations: bool,
524
525 // If true enable additional linkage checks.
526 #[serde(skip_serializing_if = "is_false")]
527 dependency_linkage_error: bool,
528
529 // If true enable additional multisig checks.
530 #[serde(skip_serializing_if = "is_false")]
531 additional_multisig_checks: bool,
532
533 // If true, enables the normalization of PTB arguments but does not yet enable splatting
534 // `Result`s of length not equal to 1
535 #[serde(skip_serializing_if = "is_false")]
536 normalize_ptb_arguments: bool,
537
538 // If true, use ChangeEpochV3 for epoch change to pass an additional eligible_active_validators
539 // parameter to IotaSystem's advance_epoch call. This should only be enabled when on-chain
540 // IotaSystem objects are updated as well.
541 #[serde(skip_serializing_if = "is_false")]
542 select_committee_from_eligible_validators: bool,
543
544 // If true, non-committee active validators will sign and send AuthorityCapabilitiesV1 to the
545 // committee. Once the committee reaches consensus over the AuthorityCapabilitiesV1, it is
546 // recorded and possible to use in the committee selection if
547 // select_validators_supporting_next_epoch_version is enabled. This flag does not change the
548 // way that eligible_validators vector is created - still all active validators are used for
549 // selecting the committee.
550 #[serde(skip_serializing_if = "is_false")]
551 track_non_committee_eligible_validators: bool,
552
553 // The committee be selected from active_validators who support the next protocol version AND
554 // have issued a correct AuthorityCapabilities notification. This flag should only be enabled
555 // if both select_committee_from_eligible_validators and
556 // track_non_committee_eligible_validators are enabled. If this is disabled, then all
557 // active validators are used for selecting the committee (default behavior).
558 #[serde(skip_serializing_if = "is_false")]
559 select_committee_supporting_next_epoch_version: bool,
560
561 // If true, then it (1) will not enforce monotonicity checks for a block's ancestors, (2)
562 // calculates the commit's timestamp based on the weighted by stake median timestamp of the
563 // leader's ancestors, and (3) enforces checkpoint timestamps are non-decreasing.
564 #[serde(skip_serializing_if = "is_false")]
565 consensus_median_timestamp_with_checkpoint_enforcement: bool,
566
567 // If true, then transactions are committed only for traversed headers
568 #[serde(skip_serializing_if = "is_false")]
569 consensus_commit_transactions_only_for_traversed_headers: bool,
570
571 // To enable/disable congestion limit overshoot in the gas price feedback mechanism.
572 #[serde(skip_serializing_if = "is_false")]
573 congestion_limit_overshoot_in_gas_price_feedback_mechanism: bool,
574
575 // To enable/disable a separate gas price feedback mechanism for transactions using
576 // randomness.
577 #[serde(skip_serializing_if = "is_false")]
578 separate_gas_price_feedback_mechanism_for_randomness: bool,
579
580 // If true, it allows metadata bytes indexed with a dedicated key in a compiled module.
581 // This flag is used to provide the correct MoveVM configuration for clients.
582 #[serde(skip_serializing_if = "is_false")]
583 metadata_in_module_bytes: bool,
584
585 // If true, enables publishing package metadata v1 along with the package.
586 #[serde(skip_serializing_if = "is_false")]
587 publish_package_metadata: bool,
588
589 // If true, enables the authentication of account using Move code.
590 #[serde(skip_serializing_if = "is_false")]
591 enable_move_authentication: bool,
592
593 // If true, enables the authentication of a sponsor account using Move code.
594 #[serde(skip_serializing_if = "is_false")]
595 enable_move_authentication_for_sponsor: bool,
596
597 // If true, the change epoch transaction will contain validator scores.
598 #[serde(skip_serializing_if = "is_false")]
599 pass_validator_scores_to_advance_epoch: bool,
600
601 // If true, enables calculation of validator scores.
602 #[serde(skip_serializing_if = "is_false")]
603 calculate_validator_scores: bool,
604
605 // If true, validators will use the committee's score to adjust rewards.
606 #[serde(skip_serializing_if = "is_false")]
607 adjust_rewards_by_score: bool,
608
609 // If true, the change epoch transaction will contain the locally calculated validator scores.
610 // If false, a default score (MAX_SCORE) is passed
611 #[serde(skip_serializing_if = "is_false")]
612 pass_calculated_validator_scores_to_advance_epoch: bool,
613
614 // If true, enables the fast commit syncer in Starfish consensus for faster recovery
615 // from large commit gaps. Also controls whether TransactionRef is used in commits
616 // instead of BlockRef, and enables the associated gRPC endpoints for fetching
617 // commits and transactions.
618 #[serde(skip_serializing_if = "is_false")]
619 consensus_fast_commit_sync: bool,
620
621 // If true, enables consensus block restrictions: bounds the block header size for
622 // a given committee size.
623 #[serde(skip_serializing_if = "is_false")]
624 consensus_block_restrictions: bool,
625
626 // If true, enable `TxContext` Move API to go native.
627 #[serde(skip_serializing_if = "is_false")]
628 move_native_tx_context: bool,
629
630 // If true, perform additional borrow checks
631 #[serde(skip_serializing_if = "is_false")]
632 additional_borrow_checks: bool,
633
634 // If true, only sponsor Move authentication is performed pre-consensus.
635 #[serde(skip_serializing_if = "is_false")]
636 pre_consensus_sponsor_only_move_authentication: bool,
637
638 // If true, enables the optimistic commit rule (StarfishSpeed) in Starfish consensus.
639 #[serde(skip_serializing_if = "is_false")]
640 consensus_starfish_speed: bool,
641
642 // If true, keep advancing the random beacon DKG state machine on every
643 // consensus commit while DKG is still pending, even when no new messages or
644 // confirmations were processed that commit. This lets a validator resolve
645 // DKG from already-persisted state (completing, or failing once the timeout
646 // round passes) with no fresh inbound traffic -- e.g. after a restart --
647 // instead of staying pending forever.
648 #[serde(skip_serializing_if = "is_false")]
649 always_advance_dkg_to_resolution: bool,
650
651 // If true, enables the P-COOL (post-consensus owned-object locking) flow:
652 // transactions bypass pre-consensus certification and owned-object locking,
653 // and conflicts are resolved deterministically post-consensus (white-flag
654 // conflict resolution) using persistent locks. Post-consensus deny checks
655 // use a consensus-governed deny rule set instead of each validator's local
656 // `TransactionDenyConfig`: validators announce proposed rules, and the
657 // active set is their stake-weighted aggregate. The active set is mirrored
658 // into the on-chain `TransactionDenyRules` object, which is created at the
659 // end of the first epoch with the flow and updated by system transactions
660 // when the active set changes.
661 //
662 // Post-consensus validation is deterministic: it reads object state as of
663 // `pcool_deterministic_validation_horizon_distance` commits below the
664 // commit it validates, and checks the sender against the coin deny list
665 // for the coin types of its inputs there, with changes made this epoch
666 // counting; execution no longer checks inputs against it. A committee
667 // validator does not execute state-synced checkpoints while its epoch is
668 // running: it waits for its own checkpoint builder and takes only
669 // randomness signatures from state sync. Once the certified last
670 // checkpoint of the epoch is known, it executes the rest of the epoch from
671 // state sync and stops processing consensus commits.
672 //
673 // From protocol version 39 requires `max_meter_ticks_regex_reference_safety`,
674 // `consensus_dedup_only_recorded_messages`, a positive
675 // `pcool_deterministic_validation_horizon_distance` and
676 // `deny_rule_update_max_entries_per_tx`, and excludes
677 // `pre_consensus_sponsor_only_move_authentication`.
678 #[serde(skip_serializing_if = "is_false")]
679 enable_pcool_flow: bool,
680
681 // No longer read: post-consensus validation never locks immutable inputs.
682 // Kept because shipped protocol versions set it.
683 #[serde(skip_serializing_if = "is_false")]
684 pcool_skip_immutable_object_locks: bool,
685
686 // No longer read: post-consensus validation always meters published
687 // packages with the verifier limits from this config. Kept because
688 // shipped protocol versions set it.
689 #[serde(skip_serializing_if = "is_false")]
690 pcool_verifier_limits_from_protocol_config: bool,
691
692 // If true perform consistent verification of metadata
693 #[serde(skip_serializing_if = "is_false")]
694 validator_metadata_verify_v2: bool,
695
696 // If true, the package holding a `MoveAuthenticator`'s authenticate function,
697 // together with that package's dependencies, is checked against the package
698 // deny list.
699 #[serde(skip_serializing_if = "is_false")]
700 deny_authenticator_packages: bool,
701
702 // If true, package metadata can be published with ModuleMetadata as a dynamic
703 // field.
704 #[serde(skip_serializing_if = "is_false")]
705 package_metadata_with_dynamic_module_metadata: bool,
706
707 // If true, a failure of the Move authentication is reported with a distinct
708 // `MoveAuthentication` execution error.
709 #[serde(skip_serializing_if = "is_false")]
710 report_move_authentication_error: bool,
711
712 // If true, the Starfish leader schedule scores reputation over a sliding
713 // window and rebuilds the swap table every `consensus_commits_per_schedule`
714 // commits with a uniform base election; when false, V2 snapshot scoring +
715 // stake-weighted base election is used.
716 #[serde(skip_serializing_if = "is_false")]
717 consensus_enable_sliding_window_leader_schedule: bool,
718
719 // If true, Starfish selects "bad" leader-schedule nodes by absolute
720 // normalized reputation score: exclude validators below a low threshold,
721 // capped at a maximum number of validators, and keep a minimum-size good
722 // (swap-in) pool; when false, the fixed stake cut by rank is used.
723 #[serde(skip_serializing_if = "is_false")]
724 consensus_enable_absolute_score_leader_schedule: bool,
725
726 // If true, enables better errors and bounds for max ptb values
727 #[serde(skip_serializing_if = "is_false")]
728 max_ptb_value_size_v2: bool,
729
730 // Allow objects created or mutated in system transactions to exceed the max object size limit.
731 #[serde(skip_serializing_if = "is_false")]
732 allow_unbounded_system_objects: bool,
733
734 // If true, transaction validation rejects a `MoveAuthenticator` whose
735 // account object is immutable.
736 #[serde(skip_serializing_if = "is_false")]
737 reject_immutable_account_objects: bool,
738
739 // If true, `iota::account::create_immutable_account_v1` aborts, so no new
740 // immutable account object can be created.
741 #[serde(skip_serializing_if = "is_false")]
742 reject_immutable_account_creation: bool,
743
744 // If true, `validity_check` rejects a transaction that names an object
745 // version at or above `Version::MAX_VALID_EXCL`, the range assigned to the
746 // objects of canceled transactions, or right below it, from the transaction
747 // bytes alone. Version assignment increments the largest input version and
748 // halts the node when the result is not a valid version.
749 #[serde(skip_serializing_if = "is_false")]
750 validate_input_object_versions: bool,
751
752 // Disallow self identifier
753 #[serde(skip_serializing_if = "is_false")]
754 disallow_self_identifier: bool,
755
756 // Reject a transaction whose type arguments, Move call module or function
757 // name, or Move authenticator type arguments carry an identifier that
758 // move-core rejects (`<SELF>`), at signing, after consensus and in block
759 // verification.
760 #[serde(skip_serializing_if = "is_false")]
761 disallow_self_identifier_in_transactions: bool,
762
763 // If true, the version field of a published module header must be the encoding
764 // the serializer produces for the version it decodes to. Below binary format
765 // version 7 the flavor byte is not part of the header, and without this check
766 // a non-zero flavor byte is masked off instead of rejected.
767 #[serde(skip_serializing_if = "is_false")]
768 check_canonical_module_version_header: bool,
769
770 // If true, `validity_check` rejects a `MoveAuthenticator` that names the
771 // randomness state object among its inputs. An authenticate function cannot
772 // derive randomness from it, but naming it schedules the transaction as
773 // randomness-using and defers it to a randomness round for nothing.
774 #[serde(skip_serializing_if = "is_false")]
775 disallow_randomness_in_move_authenticator: bool,
776
777 // If true, the cyclic dependency check traverses the module graph. Without it
778 // the traversal descends only into modules it has already visited, so it stops
779 // at the immediate dependencies and never reports a cycle.
780 #[serde(skip_serializing_if = "is_false")]
781 check_cyclic_dependencies: bool,
782
783 // Validate PTB input and result indices before signing.
784 #[serde(skip_serializing_if = "is_false")]
785 validate_ptb_argument_indices: bool,
786
787 // If true, keep DKG pending after its timeout so that it can complete later
788 // in the epoch.
789 #[serde(skip_serializing_if = "is_false")]
790 allow_dkg_completion_after_timeout: bool,
791
792 // If true, a consensus message is skipped as a duplicate of an earlier message with the same
793 // key that was recorded as processed or passed verification in the same commit:
794 // - The consensus handler adds a message to its processed-transaction cache only after the
795 // epoch store recorded it as processed. Otherwise the cache also holds messages that were
796 // dropped without being recorded, and since it differs between validators and after a
797 // restart, skipping on a cache hit lets validators disagree about a later message with the
798 // same key.
799 // - A user transaction from an authority that has sent EndOfPublish fails verification, so it
800 // does not make a later transaction with the same key in its commit be skipped.
801 #[serde(skip_serializing_if = "is_false")]
802 consensus_dedup_only_recorded_messages: bool,
803
804 // If true, a multisig whose committee mixes Ed25519 with other key schemes
805 // is only accepted when every committee member has signed. Ed25519 members
806 // carry no flag byte in the multisig address preimage, so two different
807 // mixed committees can derive the same address.
808 #[serde(skip_serializing_if = "is_false")]
809 reject_partially_signed_mixed_ed25519_multisig: bool,
810
811 // If true, groth16::prepare_verifying_key checks that the verifying key has
812 // no more than MAX_PUBLIC_INPUTS public inputs.
813 #[serde(skip_serializing_if = "is_false")]
814 limit_groth16_pvk_inputs: bool,
815
816 // If true, groth16::verify_groth16_proof checks that the prepared verifying
817 // key has the length implied by the number of public inputs, and aborts
818 // with EInvalidVerifyingKey if it does not.
819 #[serde(skip_serializing_if = "is_false")]
820 check_groth16_pvk_length: bool,
821
822 // If true, deprecate global storage ops everywhere. A module that uses the
823 // deprecated global storage instructions, or has a non-empty `acquires`
824 // list, fails to deserialize. The verifier skips the acquires pass, checks
825 // vector element borrows with the same rule as calls, and fails if a
826 // deprecated instruction reaches it. This applies to every module the VM
827 // verifies, including published packages it loads. Signing always runs
828 // with it on; post-consensus validation follows this flag.
829 #[serde(skip_serializing_if = "is_false")]
830 deprecate_global_storage_ops: bool,
831
832 // If true, post-consensus validation meters the instantiation-loop check
833 // of the bytecode verifier. Signing always meters it.
834 #[serde(skip_serializing_if = "is_false")]
835 meter_instantiation_loops: bool,
836
837 // If true, the packages named by a `MoveAuthenticator`'s type arguments are
838 // inputs of that authenticator, as those of a `MoveCall` are. Without it no
839 // node waits for them, so a node that has not executed such a package's
840 // publish yet fails an authentication that the others pass.
841 #[serde(skip_serializing_if = "is_false")]
842 move_authenticator_type_arg_packages_as_inputs: bool,
843
844 // If true, the block-proposing validator attests each received user transaction
845 // before sending it to consensus. The attestor certifies that Move authentication
846 // passed and the attestation carries a computation cost estimate for
847 // shared-object scheduling.
848 #[serde(skip_serializing_if = "is_false")]
849 enable_validator_attestation: bool,
850
851 // If true, a block whose transactions reach their acknowledgment quorum
852 // before its header is traversed is committed once its header is traversed.
853 #[serde(skip_serializing_if = "is_false")]
854 consensus_commit_transactions_once_traversed: bool,
855
856 // If true, `ecdsa_r1::secp256r1_ecrecover` rejects a signature whose
857 // restored x-coordinate `r + n` is not below the field modulus, instead
858 // of wrapping it at 2^256.
859 #[serde(skip_serializing_if = "is_false")]
860 secp256r1_ecrecover_checks_x_below_p: bool,
861}
862
863fn is_true(b: &bool) -> bool {
864 *b
865}
866
867fn is_false(b: &bool) -> bool {
868 !b
869}
870
871/// Ordering mechanism for transactions in one consensus output.
872#[derive(Default, Copy, Clone, PartialEq, Eq, Serialize, Deserialize, Debug)]
873pub enum ConsensusTransactionOrdering {
874 /// No ordering. Transactions are processed in the order they appear in the
875 /// consensus output.
876 #[default]
877 None,
878 /// Order transactions by gas price, highest first.
879 ByGasPrice,
880}
881
882impl ConsensusTransactionOrdering {
883 pub fn is_none(&self) -> bool {
884 matches!(self, ConsensusTransactionOrdering::None)
885 }
886}
887
888// The config for per object congestion control in consensus handler.
889#[derive(Default, Copy, Clone, PartialEq, Eq, Serialize, Deserialize, Debug)]
890pub enum PerObjectCongestionControlMode {
891 #[default]
892 None, // No congestion control.
893 TotalGasBudget, // Use txn gas budget as execution cost.
894 TotalTxCount, // Use total txn count as execution cost.
895 TotalComputationUnits, // Use attested computation units as execution cost.
896}
897
898impl PerObjectCongestionControlMode {
899 pub fn is_none(&self) -> bool {
900 matches!(self, PerObjectCongestionControlMode::None)
901 }
902}
903
904// Configuration options for consensus algorithm.
905#[derive(Default, Copy, Clone, PartialEq, Eq, Serialize, Deserialize, Debug)]
906pub enum ConsensusChoice {
907 /// Kept only so protocol-config serialization of historical epochs stays
908 /// bit-for-bit identical; no runtime code branches on it.
909 #[deprecated(note = "Mysticeti was replaced by Starfish")]
910 MysticetiDeprecated,
911 #[default]
912 Starfish,
913}
914
915#[expect(deprecated)]
916impl ConsensusChoice {
917 /// serde deserialization default: an absent `consensus_choice` field in a
918 /// historical snapshot deserializes to `MysticetiDeprecated` so that
919 /// re-serialization stays byte-identical (the skip condition below also
920 /// triggers on that variant). Decoupled from the Rust `Default` impl,
921 /// which returns `Starfish` to reflect that Starfish is the current
922 /// consensus protocol.
923 fn mysticeti_deprecated() -> Self {
924 ConsensusChoice::MysticetiDeprecated
925 }
926
927 pub fn is_mysticeti_deprecated(&self) -> bool {
928 matches!(self, ConsensusChoice::MysticetiDeprecated)
929 }
930 pub fn is_starfish(&self) -> bool {
931 matches!(self, ConsensusChoice::Starfish)
932 }
933}
934
935// Configuration options for consensus network.
936#[derive(Default, Copy, Clone, PartialEq, Eq, Serialize, Deserialize, Debug)]
937pub enum ConsensusNetwork {
938 #[default]
939 Tonic,
940}
941
942impl ConsensusNetwork {
943 pub fn is_tonic(&self) -> bool {
944 matches!(self, ConsensusNetwork::Tonic)
945 }
946}
947
948/// Constants that change the behavior of the protocol.
949///
950/// The value of each constant here must be fixed for a given protocol version.
951/// To change the value of a constant, advance the protocol version, and add
952/// support for it in `get_for_version` under the new version number.
953/// (below).
954///
955/// To add a new field to this struct, use the following procedure:
956/// - Advance the protocol version.
957/// - Add the field as a private `Option<T>` to the struct.
958/// - Initialize the field to `None` in prior protocol versions.
959/// - Initialize the field to `Some(val)` for your new protocol version.
960/// - Add a public getter that simply unwraps the field.
961/// - Two public getters of the form `field(&self) -> field_type` and `field_as_option(&self) ->
962/// Option<field_type>` will be automatically generated for you.
963/// Example for a field: `new_constant: Option<u64>`
964/// ```rust,ignore
965/// pub fn new_constant(&self) -> u64 {
966/// self.new_constant.expect(Self::CONSTANT_ERR_MSG)
967/// }
968/// pub fn new_constant_as_option(&self) -> Option<u64> {
969/// self.new_constant.expect(Self::CONSTANT_ERR_MSG)
970/// }
971/// ```
972/// With `pub fn new_constant(&self) -> u64`, if the constant is accessed in a
973/// protocol version in which it is not defined, the validator will crash.
974/// (Crashing is necessary because this type of error would almost always result
975/// in forking if not prevented here). If you don't want the validator to crash,
976/// you can use the `pub fn new_constant_as_option(&self) -> Option<u64>`
977/// getter, which will return `None` if the field is not defined at that
978/// version.
979/// - If you want a customized getter, you can add a method in the impl.
980#[skip_serializing_none]
981#[derive(Clone, Serialize, Debug, ProtocolConfigAccessors, ProtocolConfigOverride)]
982pub struct ProtocolConfig {
983 pub version: ProtocolVersion,
984
985 feature_flags: FeatureFlags,
986
987 // ==== Transaction input limits ====
988
989 //
990 /// Maximum serialized size of a transaction (in bytes).
991 max_tx_size_bytes: Option<u64>,
992
993 /// Maximum number of input objects to a transaction. Enforced by the
994 /// transaction input checker. Pure inputs do not count towards it; all
995 /// inputs together cannot exceed
996 /// `iota_types::transaction::MAX_PROGRAMMABLE_TX_INPUTS`.
997 max_input_objects: Option<u64>,
998
999 /// Max size of objects a transaction can write to disk after completion.
1000 /// Enforce by the IOTA adapter. This is the sum of the serialized size
1001 /// of all objects written to disk. The max size of individual objects
1002 /// on the other hand is `max_move_object_size`.
1003 max_size_written_objects: Option<u64>,
1004 /// Max size of objects a system transaction can write to disk after
1005 /// completion. Enforce by the IOTA adapter. Similar to
1006 /// `max_size_written_objects` but for system transactions.
1007 max_size_written_objects_system_tx: Option<u64>,
1008
1009 /// Maximum size of serialized transaction effects.
1010 max_serialized_tx_effects_size_bytes: Option<u64>,
1011
1012 /// Maximum size of serialized transaction effects for system transactions.
1013 max_serialized_tx_effects_size_bytes_system_tx: Option<u64>,
1014
1015 /// Maximum number of gas payment objects for a transaction.
1016 max_gas_payment_objects: Option<u32>,
1017
1018 /// Maximum number of modules in a Publish transaction.
1019 max_modules_in_publish: Option<u32>,
1020
1021 /// Maximum number of transitive dependencies in a package when publishing.
1022 max_package_dependencies: Option<u32>,
1023
1024 /// Maximum number of arguments in a move call or a
1025 /// ProgrammableTransaction's TransferObjects command.
1026 max_arguments: Option<u32>,
1027
1028 /// Maximum number of total type arguments, computed recursively.
1029 max_type_arguments: Option<u32>,
1030
1031 /// Maximum depth of an individual type argument.
1032 max_type_argument_depth: Option<u32>,
1033
1034 /// Maximum size of a Pure CallArg.
1035 max_pure_argument_size: Option<u32>,
1036
1037 /// Maximum number of Commands in a ProgrammableTransaction.
1038 max_programmable_tx_commands: Option<u32>,
1039
1040 // ==== Move VM, Move bytecode verifier, and execution limits ===
1041
1042 //
1043 /// Maximum Move bytecode version the VM understands. All older versions are
1044 /// accepted.
1045 move_binary_format_version: Option<u32>,
1046 min_move_binary_format_version: Option<u32>,
1047
1048 /// Configuration controlling binary tables size.
1049 binary_module_handles: Option<u16>,
1050 binary_struct_handles: Option<u16>,
1051 binary_function_handles: Option<u16>,
1052 binary_function_instantiations: Option<u16>,
1053 binary_signatures: Option<u16>,
1054 binary_constant_pool: Option<u16>,
1055 binary_identifiers: Option<u16>,
1056 binary_address_identifiers: Option<u16>,
1057 binary_struct_defs: Option<u16>,
1058 binary_struct_def_instantiations: Option<u16>,
1059 binary_function_defs: Option<u16>,
1060 binary_field_handles: Option<u16>,
1061 binary_field_instantiations: Option<u16>,
1062 binary_friend_decls: Option<u16>,
1063 binary_enum_defs: Option<u16>,
1064 binary_enum_def_instantiations: Option<u16>,
1065 binary_variant_handles: Option<u16>,
1066 binary_variant_instantiation_handles: Option<u16>,
1067
1068 /// Maximum size of the `contents` part of an object, in bytes. Enforced by
1069 /// the IOTA adapter when effects are produced.
1070 max_move_object_size: Option<u64>,
1071
1072 // TODO: Option<increase to 500 KB. currently, publishing a package > 500 KB exceeds the max
1073 // computation gas cost
1074 /// Maximum size of a Move package object, in bytes. Enforced by the IOTA
1075 /// adapter at the end of a publish transaction.
1076 max_move_package_size: Option<u64>,
1077
1078 /// Max number of publish or upgrade commands allowed in a programmable
1079 /// transaction block.
1080 max_publish_or_upgrade_per_ptb: Option<u64>,
1081
1082 /// Maximum gas budget in NANOS that a transaction can use.
1083 max_tx_gas: Option<u64>,
1084
1085 /// Maximum gas budget in NANOS that a authentication transaction can use.
1086 max_auth_gas: Option<u64>,
1087
1088 /// Maximum amount of the proposed gas price in NANOS (defined in the
1089 /// transaction).
1090 max_gas_price: Option<u64>,
1091
1092 /// The max computation bucket for gas. This is the max that can be charged
1093 /// for computation.
1094 max_gas_computation_bucket: Option<u64>,
1095
1096 // Define the value used to round up computation gas charges
1097 gas_rounding_step: Option<u64>,
1098
1099 /// Maximum number of nested loops. Enforced by the Move bytecode verifier.
1100 max_loop_depth: Option<u64>,
1101
1102 /// Maximum number of type arguments that can be bound to generic type
1103 /// parameters. Enforced by the Move bytecode verifier.
1104 max_generic_instantiation_length: Option<u64>,
1105
1106 /// Maximum number of parameters that a Move function can have. Enforced by
1107 /// the Move bytecode verifier.
1108 max_function_parameters: Option<u64>,
1109
1110 /// Maximum number of basic blocks that a Move function can have. Enforced
1111 /// by the Move bytecode verifier.
1112 max_basic_blocks: Option<u64>,
1113
1114 /// Maximum stack size value. Enforced by the Move bytecode verifier.
1115 max_value_stack_size: Option<u64>,
1116
1117 /// Maximum number of "type nodes", a metric for how big a SignatureToken
1118 /// will be when expanded into a fully qualified type. Enforced by the Move
1119 /// bytecode verifier.
1120 max_type_nodes: Option<u64>,
1121
1122 /// Maximum number of push instructions in one function. Enforced by the
1123 /// Move bytecode verifier.
1124 max_push_size: Option<u64>,
1125
1126 /// Maximum number of struct definitions in a module. Enforced by the Move
1127 /// bytecode verifier.
1128 max_struct_definitions: Option<u64>,
1129
1130 /// Maximum number of function definitions in a module. Enforced by the Move
1131 /// bytecode verifier.
1132 max_function_definitions: Option<u64>,
1133
1134 /// Maximum number of fields allowed in a struct definition. Enforced by the
1135 /// Move bytecode verifier.
1136 max_fields_in_struct: Option<u64>,
1137
1138 /// Maximum dependency depth. Enforced by the Move linker when loading
1139 /// dependent modules.
1140 max_dependency_depth: Option<u64>,
1141
1142 /// Maximum number of Move events that a single transaction can emit.
1143 /// Enforced by the VM during execution.
1144 max_num_event_emit: Option<u64>,
1145
1146 /// Maximum number of new IDs that a single transaction can create. Enforced
1147 /// by the VM during execution.
1148 max_num_new_move_object_ids: Option<u64>,
1149
1150 /// Maximum number of new IDs that a single system transaction can create.
1151 /// Enforced by the VM during execution.
1152 max_num_new_move_object_ids_system_tx: Option<u64>,
1153
1154 /// Maximum number of IDs that a single transaction can delete. Enforced by
1155 /// the VM during execution.
1156 max_num_deleted_move_object_ids: Option<u64>,
1157
1158 /// Maximum number of IDs that a single system transaction can delete.
1159 /// Enforced by the VM during execution.
1160 max_num_deleted_move_object_ids_system_tx: Option<u64>,
1161
1162 /// Maximum number of IDs that a single transaction can transfer. Enforced
1163 /// by the VM during execution.
1164 max_num_transferred_move_object_ids: Option<u64>,
1165
1166 /// Maximum number of IDs that a single system transaction can transfer.
1167 /// Enforced by the VM during execution.
1168 max_num_transferred_move_object_ids_system_tx: Option<u64>,
1169
1170 /// Maximum size of a Move user event. Enforced by the VM during execution.
1171 max_event_emit_size: Option<u64>,
1172
1173 /// Maximum size of a Move user event. Enforced by the VM during execution.
1174 max_event_emit_size_total: Option<u64>,
1175
1176 /// Maximum length of a vector in Move. Enforced by the VM during execution,
1177 /// and for constants, by the verifier.
1178 max_move_vector_len: Option<u64>,
1179
1180 /// Maximum length of an `Identifier` in Move. Enforced by the bytecode
1181 /// verifier at signing.
1182 max_move_identifier_len: Option<u64>,
1183
1184 /// Maximum depth of a Move value within the VM.
1185 max_move_value_depth: Option<u64>,
1186
1187 /// Maximum number of struct, enum and vector values in the arguments of
1188 /// one Move call.
1189 max_move_call_argument_nodes: Option<u64>,
1190
1191 /// Maximum number of struct, enum and vector values in the arguments of
1192 /// all Move calls of one programmable transaction.
1193 max_move_call_argument_nodes_total: Option<u64>,
1194
1195 /// Maximum number of variants in an enum. Enforced by the bytecode verifier
1196 /// at signing.
1197 max_move_enum_variants: Option<u64>,
1198
1199 // === Metered bytecode verifier limits ===
1200 // Enforced on the packages a transaction publishes when post-consensus
1201 // validation checks them.
1202 // Signing, admission and simulation are validator-local decisions and use
1203 // each validator's own `VerifierSigningConfig` instead.
1204
1205 //
1206 /// Maximum number of back edges in a Move function.
1207 max_back_edges_per_function: Option<u64>,
1208
1209 /// Maximum number of back edges in a Move module.
1210 max_back_edges_per_module: Option<u64>,
1211
1212 /// Maximum number of meter `ticks` spent verifying a Move function.
1213 max_verifier_meter_ticks_per_function: Option<u64>,
1214
1215 /// Maximum number of meter `ticks` spent verifying a Move module.
1216 max_meter_ticks_per_module: Option<u64>,
1217
1218 /// Maximum number of meter `ticks` spent verifying a Move package.
1219 max_meter_ticks_per_package: Option<u64>,
1220
1221 /// Maximum number of meter `ticks` the regex-based reference safety check
1222 /// may spend per function, module and package. The check rejects a module
1223 /// it cannot finish within the limit.
1224 max_meter_ticks_regex_reference_safety: Option<u64>,
1225
1226 /// Maximum number of edges in the instantiation-loop graph of a Move
1227 /// module, checked only by post-consensus validation. Signing uses a limit
1228 /// set in the binary instead, and execution does not check it.
1229 max_instantiation_loop_graph_edges: Option<u64>,
1230
1231 // === Object runtime internal operation limits ====
1232 // These affect dynamic fields
1233
1234 //
1235 /// Maximum number of cached objects in the object runtime ObjectStore.
1236 /// Enforced by object runtime during execution
1237 object_runtime_max_num_cached_objects: Option<u64>,
1238
1239 /// Maximum number of cached objects in the object runtime ObjectStore in
1240 /// system transaction. Enforced by object runtime during execution
1241 object_runtime_max_num_cached_objects_system_tx: Option<u64>,
1242
1243 /// Maximum number of stored objects accessed by object runtime ObjectStore.
1244 /// Enforced by object runtime during execution
1245 object_runtime_max_num_store_entries: Option<u64>,
1246
1247 /// Maximum number of stored objects accessed by object runtime ObjectStore
1248 /// in system transaction. Enforced by object runtime during execution
1249 object_runtime_max_num_store_entries_system_tx: Option<u64>,
1250
1251 // === Execution gas costs ====
1252
1253 //
1254 /// Base cost for any IOTA transaction
1255 base_tx_cost_fixed: Option<u64>,
1256
1257 /// Additional cost for a transaction that publishes a package
1258 /// i.e., the base cost of such a transaction is base_tx_cost_fixed +
1259 /// package_publish_cost_fixed
1260 package_publish_cost_fixed: Option<u64>,
1261
1262 /// Cost per byte of a Move call transaction
1263 /// i.e., the cost of such a transaction is base_cost +
1264 /// (base_tx_cost_per_byte * size)
1265 base_tx_cost_per_byte: Option<u64>,
1266
1267 /// Cost per byte for a transaction that publishes a package
1268 package_publish_cost_per_byte: Option<u64>,
1269
1270 // Per-byte cost of reading an object during transaction execution
1271 obj_access_cost_read_per_byte: Option<u64>,
1272
1273 // Per-byte cost of writing an object during transaction execution
1274 obj_access_cost_mutate_per_byte: Option<u64>,
1275
1276 // Per-byte cost of deleting an object during transaction execution
1277 obj_access_cost_delete_per_byte: Option<u64>,
1278
1279 /// Per-byte cost charged for each input object to a transaction.
1280 /// Meant to approximate the cost of checking locks for each object
1281 // TODO: Option<I'm not sure that this cost makes sense. Checking locks is "free"
1282 // in the sense that an invalid tx that can never be committed/pay gas can
1283 // force validators to check an arbitrary number of locks. If those checks are
1284 // "free" for invalid transactions, why charge for them in valid transactions
1285 // TODO: Option<if we keep this, I think we probably want it to be a fixed cost rather
1286 // than a per-byte cost. checking an object lock should not require loading an
1287 // entire object, just consulting an ID -> tx digest map
1288 obj_access_cost_verify_per_byte: Option<u64>,
1289
1290 // Maximal nodes which are allowed when converting to a type layout.
1291 max_type_to_layout_nodes: Option<u64>,
1292
1293 // Maximal size in bytes that a PTB value can be
1294 max_ptb_value_size: Option<u64>,
1295
1296 // === Gas version. gas model ===
1297
1298 //
1299 /// Gas model version, what code we are using to charge gas
1300 gas_model_version: Option<u64>,
1301
1302 // === Storage gas costs ===
1303
1304 //
1305 /// Per-byte cost of storing an object in the IOTA global object store. Some
1306 /// of this cost may be refundable if the object is later freed
1307 obj_data_cost_refundable: Option<u64>,
1308
1309 // Per-byte cost of storing an object in the IOTA transaction log (e.g., in
1310 // CertifiedTransactionEffects) This depends on the size of various fields including the
1311 // effects TODO: Option<I don't fully understand this^ and more details would be useful
1312 obj_metadata_cost_non_refundable: Option<u64>,
1313
1314 // === Tokenomics ===
1315
1316 // TODO: Option<this should be changed to u64.
1317 /// Sender of a txn that touches an object will get this percent of the
1318 /// storage rebate back. In basis point.
1319 storage_rebate_rate: Option<u64>,
1320
1321 /// The share of rewards that will be slashed and redistributed is 50%.
1322 /// In basis point.
1323 reward_slashing_rate: Option<u64>,
1324
1325 /// Unit storage gas price, Nanos per internal gas unit.
1326 storage_gas_price: Option<u64>,
1327
1328 // Base gas price for computation gas, nanos per computation unit.
1329 base_gas_price: Option<u64>,
1330
1331 /// The number of tokens minted as a validator subsidy per epoch.
1332 validator_target_reward: Option<u64>,
1333
1334 // === Core Protocol ===
1335
1336 //
1337 /// Max number of transactions per checkpoint.
1338 /// Note that this is a protocol constant and not a config as validators
1339 /// must have this set to the same value, otherwise they *will* fork.
1340 max_transactions_per_checkpoint: Option<u64>,
1341
1342 /// Max size of a checkpoint in bytes.
1343 /// Note that this is a protocol constant and not a config as validators
1344 /// must have this set to the same value, otherwise they *will* fork.
1345 max_checkpoint_size_bytes: Option<u64>,
1346
1347 /// A protocol upgrade always requires 2f+1 stake to agree. We support a
1348 /// buffer of additional stake (as a fraction of f, expressed in basis
1349 /// points) that is required before an upgrade can happen automatically.
1350 /// 10000bps would indicate that complete unanimity is required (all
1351 /// 3f+1 must vote), while 0bps would indicate that 2f+1 is sufficient.
1352 buffer_stake_for_protocol_upgrade_bps: Option<u64>,
1353
1354 // === Native Function Costs ===
1355
1356 // `address` module
1357 // Cost params for the Move native function `address::from_bytes(bytes: vector<u8>)`
1358 address_from_bytes_cost_base: Option<u64>,
1359 // Cost params for the Move native function `address::to_u256(address): u256`
1360 address_to_u256_cost_base: Option<u64>,
1361 // Cost params for the Move native function `address::from_u256(u256): address`
1362 address_from_u256_cost_base: Option<u64>,
1363
1364 // `config` module
1365 // Cost params for the Move native function `read_setting_impl<Name: copy + drop + store,
1366 // SettingValue: key + store, SettingDataValue: store, Value: copy + drop + store,
1367 // >(config: address, name: address, current_epoch: u64): Option<Value>`
1368 config_read_setting_impl_cost_base: Option<u64>,
1369 config_read_setting_impl_cost_per_byte: Option<u64>,
1370
1371 // `dynamic_field` module
1372 // Cost params for the Move native function `hash_type_and_key<K: copy + drop + store>(parent:
1373 // address, k: K): address`
1374 dynamic_field_hash_type_and_key_cost_base: Option<u64>,
1375 dynamic_field_hash_type_and_key_type_cost_per_byte: Option<u64>,
1376 dynamic_field_hash_type_and_key_value_cost_per_byte: Option<u64>,
1377 dynamic_field_hash_type_and_key_type_tag_cost_per_byte: Option<u64>,
1378 // Cost params for the Move native function `add_child_object<Child: key>(parent: address,
1379 // child: Child)`
1380 dynamic_field_add_child_object_cost_base: Option<u64>,
1381 dynamic_field_add_child_object_type_cost_per_byte: Option<u64>,
1382 dynamic_field_add_child_object_value_cost_per_byte: Option<u64>,
1383 dynamic_field_add_child_object_struct_tag_cost_per_byte: Option<u64>,
1384 // Cost params for the Move native function `borrow_child_object_mut<Child: key>(parent: &mut
1385 // UID, id: address): &mut Child`
1386 dynamic_field_borrow_child_object_cost_base: Option<u64>,
1387 dynamic_field_borrow_child_object_child_ref_cost_per_byte: Option<u64>,
1388 dynamic_field_borrow_child_object_type_cost_per_byte: Option<u64>,
1389 // Cost params for the Move native function `remove_child_object<Child: key>(parent: address,
1390 // id: address): Child`
1391 dynamic_field_remove_child_object_cost_base: Option<u64>,
1392 dynamic_field_remove_child_object_child_cost_per_byte: Option<u64>,
1393 dynamic_field_remove_child_object_type_cost_per_byte: Option<u64>,
1394 // Cost params for the Move native function `has_child_object(parent: address, id: address):
1395 // bool`
1396 dynamic_field_has_child_object_cost_base: Option<u64>,
1397 // Cost params for the Move native function `has_child_object_with_ty<Child: key>(parent:
1398 // address, id: address): bool`
1399 dynamic_field_has_child_object_with_ty_cost_base: Option<u64>,
1400 dynamic_field_has_child_object_with_ty_type_cost_per_byte: Option<u64>,
1401 dynamic_field_has_child_object_with_ty_type_tag_cost_per_byte: Option<u64>,
1402
1403 // `event` module
1404 // Cost params for the Move native function `event::emit<T: copy + drop>(event: T)`
1405 event_emit_cost_base: Option<u64>,
1406 event_emit_value_size_derivation_cost_per_byte: Option<u64>,
1407 event_emit_tag_size_derivation_cost_per_byte: Option<u64>,
1408 event_emit_output_cost_per_byte: Option<u64>,
1409
1410 // `object` module
1411 // Cost params for the Move native function `borrow_uid<T: key>(obj: &T): &UID`
1412 object_borrow_uid_cost_base: Option<u64>,
1413 // Cost params for the Move native function `delete_impl(id: address)`
1414 object_delete_impl_cost_base: Option<u64>,
1415 // Cost params for the Move native function `record_new_uid(id: address)`
1416 object_record_new_uid_cost_base: Option<u64>,
1417
1418 // Transfer
1419 // Cost params for the Move native function `transfer_impl<T: key>(obj: T, recipient: address)`
1420 transfer_transfer_internal_cost_base: Option<u64>,
1421 // Cost params for the Move native function `freeze_object<T: key>(obj: T)`
1422 transfer_freeze_object_cost_base: Option<u64>,
1423 // Cost params for the Move native function `share_object<T: key>(obj: T)`
1424 transfer_share_object_cost_base: Option<u64>,
1425 // Cost params for the Move native function
1426 // `receive_object<T: key>(p: &mut UID, recv: Receiving<T>T)`
1427 transfer_receive_object_cost_base: Option<u64>,
1428
1429 // TxContext
1430 // Cost params for the Move native function `transfer_impl<T: key>(obj: T, recipient: address)`
1431 tx_context_derive_id_cost_base: Option<u64>,
1432 tx_context_fresh_id_cost_base: Option<u64>,
1433 tx_context_sender_cost_base: Option<u64>,
1434 tx_context_digest_cost_base: Option<u64>,
1435 tx_context_epoch_cost_base: Option<u64>,
1436 tx_context_epoch_timestamp_ms_cost_base: Option<u64>,
1437 tx_context_sponsor_cost_base: Option<u64>,
1438 tx_context_rgp_cost_base: Option<u64>,
1439 tx_context_gas_price_cost_base: Option<u64>,
1440 tx_context_gas_budget_cost_base: Option<u64>,
1441 tx_context_ids_created_cost_base: Option<u64>,
1442 tx_context_replace_cost_base: Option<u64>,
1443
1444 // Types
1445 // Cost params for the Move native function `is_one_time_witness<T: drop>(_: &T): bool`
1446 types_is_one_time_witness_cost_base: Option<u64>,
1447 types_is_one_time_witness_type_tag_cost_per_byte: Option<u64>,
1448 types_is_one_time_witness_type_cost_per_byte: Option<u64>,
1449
1450 // Validator
1451 // Cost params for the Move native function `validate_metadata_bcs(metadata: vector<u8>)`
1452 validator_validate_metadata_cost_base: Option<u64>,
1453 validator_validate_metadata_data_cost_per_byte: Option<u64>,
1454
1455 // Crypto natives
1456 crypto_invalid_arguments_cost: Option<u64>,
1457 // bls12381::bls12381_min_sig_verify
1458 bls12381_bls12381_min_sig_verify_cost_base: Option<u64>,
1459 bls12381_bls12381_min_sig_verify_msg_cost_per_byte: Option<u64>,
1460 bls12381_bls12381_min_sig_verify_msg_cost_per_block: Option<u64>,
1461
1462 // bls12381::bls12381_min_pk_verify
1463 bls12381_bls12381_min_pk_verify_cost_base: Option<u64>,
1464 bls12381_bls12381_min_pk_verify_msg_cost_per_byte: Option<u64>,
1465 bls12381_bls12381_min_pk_verify_msg_cost_per_block: Option<u64>,
1466
1467 // ecdsa_k1::ecrecover
1468 ecdsa_k1_ecrecover_keccak256_cost_base: Option<u64>,
1469 ecdsa_k1_ecrecover_keccak256_msg_cost_per_byte: Option<u64>,
1470 ecdsa_k1_ecrecover_keccak256_msg_cost_per_block: Option<u64>,
1471 ecdsa_k1_ecrecover_sha256_cost_base: Option<u64>,
1472 ecdsa_k1_ecrecover_sha256_msg_cost_per_byte: Option<u64>,
1473 ecdsa_k1_ecrecover_sha256_msg_cost_per_block: Option<u64>,
1474
1475 // ecdsa_k1::decompress_pubkey
1476 ecdsa_k1_decompress_pubkey_cost_base: Option<u64>,
1477
1478 // ecdsa_k1::secp256k1_verify
1479 ecdsa_k1_secp256k1_verify_keccak256_cost_base: Option<u64>,
1480 ecdsa_k1_secp256k1_verify_keccak256_msg_cost_per_byte: Option<u64>,
1481 ecdsa_k1_secp256k1_verify_keccak256_msg_cost_per_block: Option<u64>,
1482 ecdsa_k1_secp256k1_verify_sha256_cost_base: Option<u64>,
1483 ecdsa_k1_secp256k1_verify_sha256_msg_cost_per_byte: Option<u64>,
1484 ecdsa_k1_secp256k1_verify_sha256_msg_cost_per_block: Option<u64>,
1485
1486 // ecdsa_r1::ecrecover
1487 ecdsa_r1_ecrecover_keccak256_cost_base: Option<u64>,
1488 ecdsa_r1_ecrecover_keccak256_msg_cost_per_byte: Option<u64>,
1489 ecdsa_r1_ecrecover_keccak256_msg_cost_per_block: Option<u64>,
1490 ecdsa_r1_ecrecover_sha256_cost_base: Option<u64>,
1491 ecdsa_r1_ecrecover_sha256_msg_cost_per_byte: Option<u64>,
1492 ecdsa_r1_ecrecover_sha256_msg_cost_per_block: Option<u64>,
1493
1494 // ecdsa_r1::secp256k1_verify
1495 ecdsa_r1_secp256r1_verify_keccak256_cost_base: Option<u64>,
1496 ecdsa_r1_secp256r1_verify_keccak256_msg_cost_per_byte: Option<u64>,
1497 ecdsa_r1_secp256r1_verify_keccak256_msg_cost_per_block: Option<u64>,
1498 ecdsa_r1_secp256r1_verify_sha256_cost_base: Option<u64>,
1499 ecdsa_r1_secp256r1_verify_sha256_msg_cost_per_byte: Option<u64>,
1500 ecdsa_r1_secp256r1_verify_sha256_msg_cost_per_block: Option<u64>,
1501
1502 // ecvrf::verify
1503 ecvrf_ecvrf_verify_cost_base: Option<u64>,
1504 ecvrf_ecvrf_verify_alpha_string_cost_per_byte: Option<u64>,
1505 ecvrf_ecvrf_verify_alpha_string_cost_per_block: Option<u64>,
1506
1507 // ed25519
1508 ed25519_ed25519_verify_cost_base: Option<u64>,
1509 ed25519_ed25519_verify_msg_cost_per_byte: Option<u64>,
1510 ed25519_ed25519_verify_msg_cost_per_block: Option<u64>,
1511
1512 // groth16::prepare_verifying_key
1513 groth16_prepare_verifying_key_bls12381_cost_base: Option<u64>,
1514 groth16_prepare_verifying_key_bn254_cost_base: Option<u64>,
1515
1516 // groth16::verify_groth16_proof_internal
1517 groth16_verify_groth16_proof_internal_bls12381_cost_base: Option<u64>,
1518 groth16_verify_groth16_proof_internal_bls12381_cost_per_public_input: Option<u64>,
1519 groth16_verify_groth16_proof_internal_bn254_cost_base: Option<u64>,
1520 groth16_verify_groth16_proof_internal_bn254_cost_per_public_input: Option<u64>,
1521 groth16_verify_groth16_proof_internal_public_input_cost_per_byte: Option<u64>,
1522
1523 // hash::blake2b256
1524 hash_blake2b256_cost_base: Option<u64>,
1525 hash_blake2b256_data_cost_per_byte: Option<u64>,
1526 hash_blake2b256_data_cost_per_block: Option<u64>,
1527
1528 // hash::keccak256
1529 hash_keccak256_cost_base: Option<u64>,
1530 hash_keccak256_data_cost_per_byte: Option<u64>,
1531 hash_keccak256_data_cost_per_block: Option<u64>,
1532
1533 // poseidon::poseidon_bn254
1534 poseidon_bn254_cost_base: Option<u64>,
1535 poseidon_bn254_cost_per_block: Option<u64>,
1536
1537 // group_ops
1538 group_ops_bls12381_decode_scalar_cost: Option<u64>,
1539 group_ops_bls12381_decode_g1_cost: Option<u64>,
1540 group_ops_bls12381_decode_g2_cost: Option<u64>,
1541 group_ops_bls12381_decode_gt_cost: Option<u64>,
1542 group_ops_bls12381_scalar_add_cost: Option<u64>,
1543 group_ops_bls12381_g1_add_cost: Option<u64>,
1544 group_ops_bls12381_g2_add_cost: Option<u64>,
1545 group_ops_bls12381_gt_add_cost: Option<u64>,
1546 group_ops_bls12381_scalar_sub_cost: Option<u64>,
1547 group_ops_bls12381_g1_sub_cost: Option<u64>,
1548 group_ops_bls12381_g2_sub_cost: Option<u64>,
1549 group_ops_bls12381_gt_sub_cost: Option<u64>,
1550 group_ops_bls12381_scalar_mul_cost: Option<u64>,
1551 group_ops_bls12381_g1_mul_cost: Option<u64>,
1552 group_ops_bls12381_g2_mul_cost: Option<u64>,
1553 group_ops_bls12381_gt_mul_cost: Option<u64>,
1554 group_ops_bls12381_scalar_div_cost: Option<u64>,
1555 group_ops_bls12381_g1_div_cost: Option<u64>,
1556 group_ops_bls12381_g2_div_cost: Option<u64>,
1557 group_ops_bls12381_gt_div_cost: Option<u64>,
1558 group_ops_bls12381_g1_hash_to_base_cost: Option<u64>,
1559 group_ops_bls12381_g2_hash_to_base_cost: Option<u64>,
1560 group_ops_bls12381_g1_hash_to_cost_per_byte: Option<u64>,
1561 group_ops_bls12381_g2_hash_to_cost_per_byte: Option<u64>,
1562 group_ops_bls12381_g1_msm_base_cost: Option<u64>,
1563 group_ops_bls12381_g2_msm_base_cost: Option<u64>,
1564 group_ops_bls12381_g1_msm_base_cost_per_input: Option<u64>,
1565 group_ops_bls12381_g2_msm_base_cost_per_input: Option<u64>,
1566 group_ops_bls12381_msm_max_len: Option<u32>,
1567 group_ops_bls12381_pairing_cost: Option<u64>,
1568 group_ops_bls12381_g1_to_uncompressed_g1_cost: Option<u64>,
1569 group_ops_bls12381_uncompressed_g1_to_g1_cost: Option<u64>,
1570 group_ops_bls12381_uncompressed_g1_sum_base_cost: Option<u64>,
1571 group_ops_bls12381_uncompressed_g1_sum_cost_per_term: Option<u64>,
1572 group_ops_bls12381_uncompressed_g1_sum_max_terms: Option<u64>,
1573
1574 // hmac::hmac_sha3_256
1575 hmac_hmac_sha3_256_cost_base: Option<u64>,
1576 hmac_hmac_sha3_256_input_cost_per_byte: Option<u64>,
1577 hmac_hmac_sha3_256_input_cost_per_block: Option<u64>,
1578
1579 // zklogin::check_zklogin_id
1580 #[deprecated]
1581 check_zklogin_id_cost_base: Option<u64>,
1582 // zklogin::check_zklogin_issuer
1583 #[deprecated]
1584 check_zklogin_issuer_cost_base: Option<u64>,
1585
1586 vdf_verify_vdf_cost: Option<u64>,
1587 vdf_hash_to_input_cost: Option<u64>,
1588
1589 // Stdlib costs
1590 bcs_per_byte_serialized_cost: Option<u64>,
1591 bcs_legacy_min_output_size_cost: Option<u64>,
1592 bcs_failure_cost: Option<u64>,
1593
1594 hash_sha2_256_base_cost: Option<u64>,
1595 hash_sha2_256_per_byte_cost: Option<u64>,
1596 hash_sha2_256_legacy_min_input_len_cost: Option<u64>,
1597 hash_sha3_256_base_cost: Option<u64>,
1598 hash_sha3_256_per_byte_cost: Option<u64>,
1599 hash_sha3_256_legacy_min_input_len_cost: Option<u64>,
1600 type_name_get_base_cost: Option<u64>,
1601 type_name_get_per_byte_cost: Option<u64>,
1602
1603 string_check_utf8_base_cost: Option<u64>,
1604 string_check_utf8_per_byte_cost: Option<u64>,
1605 string_is_char_boundary_base_cost: Option<u64>,
1606 string_sub_string_base_cost: Option<u64>,
1607 string_sub_string_per_byte_cost: Option<u64>,
1608 string_index_of_base_cost: Option<u64>,
1609 string_index_of_per_byte_pattern_cost: Option<u64>,
1610 string_index_of_per_byte_searched_cost: Option<u64>,
1611
1612 vector_empty_base_cost: Option<u64>,
1613 vector_length_base_cost: Option<u64>,
1614 vector_push_back_base_cost: Option<u64>,
1615 vector_push_back_legacy_per_abstract_memory_unit_cost: Option<u64>,
1616 vector_borrow_base_cost: Option<u64>,
1617 vector_pop_back_base_cost: Option<u64>,
1618 vector_destroy_empty_base_cost: Option<u64>,
1619 vector_swap_base_cost: Option<u64>,
1620 debug_print_base_cost: Option<u64>,
1621 debug_print_stack_trace_base_cost: Option<u64>,
1622
1623 // === Execution Version ===
1624 execution_version: Option<u64>,
1625
1626 // Dictates the threshold (percentage of stake) that is used to calculate the "bad" nodes to be
1627 // swapped when creating the consensus schedule. The values should be of the range [0 - 33].
1628 // Anything above 33 (f) will not be allowed.
1629 consensus_bad_nodes_stake_threshold: Option<u64>,
1630
1631 #[deprecated]
1632 max_jwk_votes_per_validator_per_epoch: Option<u64>,
1633 // The maximum age of a JWK in epochs before it is removed from the AuthenticatorState object.
1634 // Applied at the end of an epoch as a delta from the new epoch value, so setting this to 1
1635 // will cause the new epoch to start with JWKs from the previous epoch still valid.
1636 #[deprecated]
1637 max_age_of_jwk_in_epochs: Option<u64>,
1638
1639 // === random beacon ===
1640 /// Maximum allowed precision loss when reducing voting weights for the
1641 /// random beacon protocol.
1642 random_beacon_reduction_allowed_delta: Option<u16>,
1643
1644 /// Minimum number of shares below which voting weights will not be reduced
1645 /// for the random beacon protocol.
1646 random_beacon_reduction_lower_bound: Option<u32>,
1647
1648 /// Consensus Round after which DKG should be aborted and randomness
1649 /// disabled for the epoch, if it hasn't already completed.
1650 random_beacon_dkg_timeout_round: Option<u32>,
1651
1652 /// Minimum interval between consecutive rounds of generated randomness.
1653 random_beacon_min_round_interval_ms: Option<u64>,
1654
1655 /// Version of the random beacon DKG protocol.
1656 /// 0 was deprecated (and currently not supported), 1 is the default
1657 /// version.
1658 random_beacon_dkg_version: Option<u64>,
1659
1660 /// The maximum serialized transaction size (in bytes) accepted by
1661 /// consensus. `consensus_max_transaction_size_bytes` should include
1662 /// space for additional metadata, on top of the `max_tx_size_bytes`
1663 /// value.
1664 consensus_max_transaction_size_bytes: Option<u64>,
1665 /// The maximum size of transactions included in a consensus block.
1666 consensus_max_transactions_in_block_bytes: Option<u64>,
1667 /// The maximum number of transactions included in a consensus block.
1668 consensus_max_num_transactions_in_block: Option<u64>,
1669
1670 /// The max number of consensus rounds a transaction can be deferred due to
1671 /// shared object congestion. Transactions will be cancelled after this
1672 /// many rounds.
1673 max_deferral_rounds_for_congestion_control: Option<u64>,
1674
1675 /// Minimum interval of commit timestamps between consecutive checkpoints.
1676 min_checkpoint_interval_ms: Option<u64>,
1677
1678 /// Number of recent checkpoints over which `min_checkpoint_interval_ms`
1679 /// may be amortized. When set, a checkpoint is built once the full
1680 /// interval elapsed since the previous checkpoint, or once the checkpoint
1681 /// this many back in the current epoch is at least that many intervals
1682 /// older. The windowed arm recycles the slack that discrete commit
1683 /// timestamps add to the strict arm, holding the sustained rate at the
1684 /// ceiling, while the strict arm keeps quiet gaps within one interval.
1685 /// The window does not cross epoch boundaries; before it fills — and
1686 /// always when unset — only the strict adjacent check applies.
1687 checkpoint_rate_window_size: Option<u64>,
1688
1689 /// Version number to use for version_specific_data in `CheckpointSummary`.
1690 /// 2 adds the attestation entries and totals and is required by
1691 /// `enable_validator_attestation`.
1692 checkpoint_summary_version_specific_data: Option<u64>,
1693
1694 /// Tolerance, in percent of the executed computation units, within which
1695 /// an attestor's claimed units count as accurate. Both sides are rounded
1696 /// up to `gas_rounding_step` and capped at the budget on out-of-gas, and
1697 /// the check only applies when the transaction body ran. Unset disables
1698 /// it.
1699 attestor_accuracy_tolerance_percentage: Option<u64>,
1700
1701 /// Sum of the squared wasted authentication units of an attestor's refuted
1702 /// attestations at which the cut takes its whole epoch reward, through its
1703 /// entry in the change-epoch scores: one fault of √value units takes it
1704 /// all, one of half that size a quarter; 0 takes the whole reward on the
1705 /// first refuted attestation. The cut reaches the reward only under
1706 /// `adjust_rewards_by_score`. An attestor whose sum reaches it has its
1707 /// attested transactions dropped at post-consensus validation for the rest
1708 /// of the epoch. Unset disables the penalty and the cutoff.
1709 attestation_max_refuted_units_squared: Option<u64>,
1710
1711 /// The max number of transactions that can be included in a single Soft
1712 /// Bundle.
1713 max_soft_bundle_size: Option<u64>,
1714
1715 /// Deprecated because of bridge removal.
1716 /// Whether to try to form bridge committee
1717 // Note: this is not a feature flag because we want to distinguish between
1718 // `None` and `Some(false)`, as committee was already finalized on Testnet.
1719 bridge_should_try_to_finalize_committee: Option<bool>,
1720
1721 /// The max accumulated txn execution cost per object in a mysticeti commit.
1722 /// Transactions in a commit will be deferred once their touch shared
1723 /// objects hit this limit. Note that if
1724 /// `max_congestion_limit_overshoot_per_commit` is set, this may be overshot
1725 /// within a single commit, but the limit will be enforced in the long run.
1726 max_accumulated_txn_cost_per_object_in_mysticeti_commit: Option<u64>,
1727
1728 /// Maximum number of committee (validators taking part in consensus)
1729 /// validators at any moment. We do not allow the number of committee
1730 /// validators in any epoch to go above this.
1731 max_committee_members_count: Option<u64>,
1732
1733 /// Maximum number of added plus removed entries one injected
1734 /// `TransactionDenyRulesUpdate` transaction may carry; a larger diff is
1735 /// split into multiple transactions in the same commit. Required by
1736 /// `enable_pcool_flow` from protocol version 39.
1737 deny_rule_update_max_entries_per_tx: Option<u64>,
1738
1739 /// Configures the garbage collection depth for consensus. When is unset or
1740 /// `0` then the garbage collection is disabled.
1741 consensus_gc_depth: Option<u32>,
1742
1743 /// Configures the maximum number of acknowledgments to be included in a
1744 /// block. It must be reasonably larger than the number of validators
1745 /// because not all validators create their blocks at the same pace.
1746 /// Default value set to 400. (5 x expected committee size (80)).
1747 /// Applicable only to `starfish` consensus.
1748 consensus_max_acknowledgments_per_block: Option<u32>,
1749
1750 /// The maximum amount that is allowed to overshoot the congestion limit
1751 /// specified by 'max_accumulated_txn_cost_per_object_in_mysticeti_commit'
1752 /// for any single commit. Any overshoot is tracked as a debt that must
1753 /// be accounted for in subsequent commits.
1754 max_congestion_limit_overshoot_per_commit: Option<u64>,
1755
1756 /// Maximum number of transactions from a single consensus commit that may
1757 /// be scheduled to execute concurrently (the execution-worker pool size).
1758 /// `Some` activates execution-worker congestion control, under which
1759 /// owned-object-only transactions are also scheduled, deferred and shed
1760 /// by the congestion tracker; `None` disables it. Must be positive when
1761 /// set. Requires `enable_pcool_flow`.
1762 max_concurrent_execution_workers: Option<u16>,
1763
1764 /// How many consensus commits back post-consensus validation reads object
1765 /// state. Validating a transaction in commit C reads object state as of
1766 /// commit C - K, where K is this distance; that commit is the horizon of
1767 /// C, and it must be fully executed before C is validated. Set on Devnet
1768 /// from protocol version 39. Required by `enable_pcool_flow` from that
1769 /// version.
1770 pcool_deterministic_validation_horizon_distance: Option<u64>,
1771
1772 /// Scorer version. When set to `None`, MisbehaviorReports are not sent nor
1773 /// considered valid. When set to `Some(version)`, scores are included in
1774 /// the MisbehaviorReports messages, where `version` determines the scoring
1775 /// formulas and metrics to be used. Even if set to None, the Scorer
1776 /// component is created, having access to metrics and being able to expose
1777 /// validator scores. Also gates the wire format of the
1778 /// `MisbehaviorReport` consensus transaction — scorer and report bump
1779 /// together.
1780 scorer_version: Option<u16>,
1781
1782 // `auth_context` module
1783 // Cost params for the Move native function `native_digest(): vector<u8>`
1784 auth_context_digest_cost_base: Option<u64>,
1785 // Cost params for the Move native function `native_tx_data_bytes(): &vector<u8>`
1786 auth_context_tx_data_bytes_cost_base: Option<u64>,
1787 auth_context_tx_data_bytes_cost_per_byte: Option<u64>,
1788 // Cost params for the Move native function `native_tx_commands<C>(): vector<C>`
1789 auth_context_tx_commands_cost_base: Option<u64>,
1790 auth_context_tx_commands_cost_per_byte: Option<u64>,
1791 // Cost params for the Move native function `native_tx_inputs<I>(): vector<I>`
1792 auth_context_tx_inputs_cost_base: Option<u64>,
1793 auth_context_tx_inputs_cost_per_byte: Option<u64>,
1794 // Cost params for the Move native function `fun native_replace<I, C>(auth_digest: vector<u8>,
1795 // tx_inputs: vector<I>, tx_commands: vector<C>, tx_data_bytes: vector<u8>)`
1796 auth_context_replace_cost_base: Option<u64>,
1797 auth_context_replace_cost_per_byte: Option<u64>,
1798 // Cost params for the Move native functions
1799 // `fun native_sender_authenticator_function_info_v1<F>(): &Option<F>`
1800 // `fun native_sponsor_authenticator_function_info_v1<F>(): &Option<F>`
1801 auth_context_authenticator_function_info_v1_cost_base: Option<u64>,
1802
1803 /// Number of committed subdags between leader-schedule recomputations.
1804 /// When unset, defaults to 300.
1805 consensus_commits_per_schedule: Option<u32>,
1806
1807 /// Minimum number of active validators at any moment.
1808 /// Supersedes `SystemParametersV1::min_validator_count`.
1809 min_validator_count: Option<u64>,
1810
1811 /// Maximum number of active validators at any moment. The number of
1812 /// validators in any epoch is not allowed to go above this.
1813 /// Supersedes `SystemParametersV1::max_validator_count`.
1814 max_validator_count: Option<u64>,
1815
1816 /// Minimum stake, in nanos, a validator candidate needs to join the
1817 /// active set. Supersedes
1818 /// `SystemParametersV1::min_validator_joining_stake`.
1819 min_validator_joining_stake: Option<u64>,
1820
1821 /// Active validators with stake, in nanos, below this threshold are
1822 /// considered at risk and are removed after
1823 /// `validator_low_stake_grace_period` consecutive epochs below it.
1824 /// Supersedes `SystemParametersV1::validator_low_stake_threshold`.
1825 validator_low_stake_threshold: Option<u64>,
1826
1827 /// Active validators with stake, in nanos, below this threshold are
1828 /// removed at the next epoch boundary without a grace period.
1829 /// Supersedes `SystemParametersV1::validator_very_low_stake_threshold`.
1830 validator_very_low_stake_threshold: Option<u64>,
1831
1832 /// Number of consecutive epochs a validator may stay below
1833 /// `validator_low_stake_threshold` before being removed.
1834 /// Supersedes `SystemParametersV1::validator_low_stake_grace_period`.
1835 validator_low_stake_grace_period: Option<u64>,
1836
1837 /// Number of committed subdags the sliding-window leader scorer aggregates
1838 /// over (the scoring depth). When unset, defaults to 600. Consulted only
1839 /// when `consensus_enable_sliding_window_leader_schedule` is set.
1840 consensus_leader_schedule_window_size: Option<u32>,
1841
1842 /// Maximum size of a system Move package object, in bytes. System packages
1843 /// are published by the network rather than by users, so they are held to a
1844 /// larger bound than `max_move_package_size`. When unset, system packages
1845 /// are bound by `max_move_package_size` like any other package.
1846 max_move_system_package_size: Option<u64>,
1847}
1848
1849// feature flags
1850impl ProtocolConfig {
1851 // Add checks for feature flag support here, e.g.:
1852 // pub fn check_new_protocol_feature_supported(&self) -> Result<(), Error> {
1853 // if self.feature_flags.new_protocol_feature_supported {
1854 // Ok(())
1855 // } else {
1856 // Err(Error(format!(
1857 // "new_protocol_feature is not supported at {:?}",
1858 // self.version
1859 // )))
1860 // }
1861 // }
1862
1863 pub fn disable_invariant_violation_check_in_swap_loc(&self) -> bool {
1864 self.feature_flags
1865 .disable_invariant_violation_check_in_swap_loc
1866 }
1867
1868 pub fn no_extraneous_module_bytes(&self) -> bool {
1869 self.feature_flags.no_extraneous_module_bytes
1870 }
1871
1872 pub fn consensus_transaction_ordering(&self) -> ConsensusTransactionOrdering {
1873 self.feature_flags.consensus_transaction_ordering
1874 }
1875
1876 pub fn dkg_version(&self) -> u64 {
1877 // Version 0 was deprecated and removed, the default is 1 if not set.
1878 self.random_beacon_dkg_version.unwrap_or(1)
1879 }
1880
1881 pub fn hardened_otw_check(&self) -> bool {
1882 self.feature_flags.hardened_otw_check
1883 }
1884
1885 pub fn enable_poseidon(&self) -> bool {
1886 self.feature_flags.enable_poseidon
1887 }
1888
1889 pub fn enable_group_ops_native_function_msm(&self) -> bool {
1890 self.feature_flags.enable_group_ops_native_function_msm
1891 }
1892
1893 pub fn per_object_congestion_control_mode(&self) -> PerObjectCongestionControlMode {
1894 self.feature_flags.per_object_congestion_control_mode
1895 }
1896
1897 pub fn consensus_choice(&self) -> ConsensusChoice {
1898 self.feature_flags.consensus_choice
1899 }
1900
1901 pub fn consensus_network(&self) -> ConsensusNetwork {
1902 self.feature_flags.consensus_network
1903 }
1904
1905 pub fn enable_vdf(&self) -> bool {
1906 self.feature_flags.enable_vdf
1907 }
1908
1909 pub fn passkey_auth(&self) -> bool {
1910 self.feature_flags.passkey_auth
1911 }
1912
1913 pub fn max_transaction_size_bytes(&self) -> u64 {
1914 // Provide a default value if protocol config version is too low.
1915 self.consensus_max_transaction_size_bytes
1916 .unwrap_or(256 * 1024)
1917 }
1918
1919 pub fn max_transactions_in_block_bytes(&self) -> u64 {
1920 if cfg!(msim) {
1921 256 * 1024
1922 } else {
1923 self.consensus_max_transactions_in_block_bytes
1924 .unwrap_or(512 * 1024)
1925 }
1926 }
1927
1928 pub fn max_num_transactions_in_block(&self) -> u64 {
1929 if cfg!(msim) {
1930 8
1931 } else {
1932 self.consensus_max_num_transactions_in_block.unwrap_or(512)
1933 }
1934 }
1935
1936 pub fn rethrow_serialization_type_layout_errors(&self) -> bool {
1937 self.feature_flags.rethrow_serialization_type_layout_errors
1938 }
1939
1940 pub fn relocate_event_module(&self) -> bool {
1941 self.feature_flags.relocate_event_module
1942 }
1943
1944 pub fn protocol_defined_base_fee(&self) -> bool {
1945 self.feature_flags.protocol_defined_base_fee
1946 }
1947
1948 pub fn uncompressed_g1_group_elements(&self) -> bool {
1949 self.feature_flags.uncompressed_g1_group_elements
1950 }
1951
1952 pub fn disallow_new_modules_in_deps_only_packages(&self) -> bool {
1953 self.feature_flags
1954 .disallow_new_modules_in_deps_only_packages
1955 }
1956
1957 pub fn native_charging_v2(&self) -> bool {
1958 self.feature_flags.native_charging_v2
1959 }
1960
1961 pub fn consensus_round_prober(&self) -> bool {
1962 self.feature_flags.consensus_round_prober
1963 }
1964
1965 pub fn consensus_distributed_vote_scoring_strategy(&self) -> bool {
1966 self.feature_flags
1967 .consensus_distributed_vote_scoring_strategy
1968 }
1969
1970 pub fn gc_depth(&self) -> u32 {
1971 if cfg!(msim) {
1972 // exercise a very low gc_depth
1973 min(5, self.consensus_gc_depth.unwrap_or(0))
1974 } else {
1975 self.consensus_gc_depth.unwrap_or(0)
1976 }
1977 }
1978
1979 pub fn consensus_linearize_subdag_v2(&self) -> bool {
1980 let res = self.feature_flags.consensus_linearize_subdag_v2;
1981 assert!(
1982 !res || self.gc_depth() > 0,
1983 "The consensus linearize sub dag V2 requires GC to be enabled"
1984 );
1985 res
1986 }
1987
1988 pub fn consensus_max_acknowledgments_per_block_or_default(&self) -> u32 {
1989 self.consensus_max_acknowledgments_per_block.unwrap_or(400)
1990 }
1991
1992 pub fn max_acknowledgments_per_block(&self, committee_size: usize) -> usize {
1993 2 * committee_size
1994 }
1995
1996 pub fn max_commit_votes_per_block(&self, committee_size: usize) -> usize {
1997 committee_size
1998 }
1999
2000 pub fn variant_nodes(&self) -> bool {
2001 self.feature_flags.variant_nodes
2002 }
2003
2004 pub fn consensus_smart_ancestor_selection(&self) -> bool {
2005 self.feature_flags.consensus_smart_ancestor_selection
2006 }
2007
2008 pub fn consensus_round_prober_probe_accepted_rounds(&self) -> bool {
2009 self.feature_flags
2010 .consensus_round_prober_probe_accepted_rounds
2011 }
2012
2013 pub fn consensus_zstd_compression(&self) -> bool {
2014 self.feature_flags.consensus_zstd_compression
2015 }
2016
2017 pub fn congestion_control_min_free_execution_slot(&self) -> bool {
2018 self.feature_flags
2019 .congestion_control_min_free_execution_slot
2020 }
2021
2022 pub fn accept_passkey_in_multisig(&self) -> bool {
2023 self.feature_flags.accept_passkey_in_multisig
2024 }
2025
2026 pub fn consensus_batched_block_sync(&self) -> bool {
2027 self.feature_flags.consensus_batched_block_sync
2028 }
2029
2030 /// Check if the gas price feedback mechanism (which is used for
2031 /// transactions cancelled due to shared object congestion) is enabled
2032 pub fn congestion_control_gas_price_feedback_mechanism(&self) -> bool {
2033 self.feature_flags
2034 .congestion_control_gas_price_feedback_mechanism
2035 }
2036
2037 pub fn validate_identifier_inputs(&self) -> bool {
2038 self.feature_flags.validate_identifier_inputs
2039 }
2040
2041 pub fn minimize_child_object_mutations(&self) -> bool {
2042 self.feature_flags.minimize_child_object_mutations
2043 }
2044
2045 pub fn dependency_linkage_error(&self) -> bool {
2046 self.feature_flags.dependency_linkage_error
2047 }
2048
2049 pub fn additional_multisig_checks(&self) -> bool {
2050 self.feature_flags.additional_multisig_checks
2051 }
2052
2053 pub fn consensus_num_requested_prior_commits_at_startup(&self) -> u32 {
2054 // TODO: this will eventually be the max of some number of other
2055 // parameters.
2056 0
2057 }
2058
2059 pub fn normalize_ptb_arguments(&self) -> bool {
2060 self.feature_flags.normalize_ptb_arguments
2061 }
2062
2063 pub fn select_committee_from_eligible_validators(&self) -> bool {
2064 let res = self.feature_flags.select_committee_from_eligible_validators;
2065 assert!(
2066 !res || (self.protocol_defined_base_fee()
2067 && self.max_committee_members_count_as_option().is_some()),
2068 "select_committee_from_eligible_validators requires protocol_defined_base_fee and max_committee_members_count to be set"
2069 );
2070 res
2071 }
2072
2073 pub fn track_non_committee_eligible_validators(&self) -> bool {
2074 self.feature_flags.track_non_committee_eligible_validators
2075 }
2076
2077 pub fn select_committee_supporting_next_epoch_version(&self) -> bool {
2078 let res = self
2079 .feature_flags
2080 .select_committee_supporting_next_epoch_version;
2081 assert!(
2082 !res || (self.track_non_committee_eligible_validators()
2083 && self.select_committee_from_eligible_validators()),
2084 "select_committee_supporting_next_epoch_version requires select_committee_from_eligible_validators to be set"
2085 );
2086 res
2087 }
2088
2089 pub fn consensus_median_timestamp_with_checkpoint_enforcement(&self) -> bool {
2090 let res = self
2091 .feature_flags
2092 .consensus_median_timestamp_with_checkpoint_enforcement;
2093 assert!(
2094 !res || self.gc_depth() > 0,
2095 "The consensus median timestamp with checkpoint enforcement requires GC to be enabled"
2096 );
2097 res
2098 }
2099
2100 pub fn consensus_commit_transactions_only_for_traversed_headers(&self) -> bool {
2101 self.feature_flags
2102 .consensus_commit_transactions_only_for_traversed_headers
2103 }
2104
2105 /// Whether a block whose transactions reached their acknowledgment quorum
2106 /// before its header was traversed is committed once its header is
2107 /// traversed.
2108 ///
2109 /// # Panics
2110 ///
2111 /// If the flag is set without
2112 /// `consensus_commit_transactions_only_for_traversed_headers`.
2113 pub fn consensus_commit_transactions_once_traversed(&self) -> bool {
2114 let res = self
2115 .feature_flags
2116 .consensus_commit_transactions_once_traversed;
2117 assert!(
2118 !res || self.consensus_commit_transactions_only_for_traversed_headers(),
2119 "consensus_commit_transactions_once_traversed requires consensus_commit_transactions_only_for_traversed_headers to be enabled"
2120 );
2121 res
2122 }
2123
2124 /// Check whether congestion limit overshoot is enabled in the gas price
2125 /// feedback mechanism.
2126 pub fn congestion_limit_overshoot_in_gas_price_feedback_mechanism(&self) -> bool {
2127 self.feature_flags
2128 .congestion_limit_overshoot_in_gas_price_feedback_mechanism
2129 }
2130
2131 /// Check whether a separate gas price feedback mechanism is used for
2132 /// randomness transactions.
2133 pub fn separate_gas_price_feedback_mechanism_for_randomness(&self) -> bool {
2134 self.feature_flags
2135 .separate_gas_price_feedback_mechanism_for_randomness
2136 }
2137
2138 pub fn metadata_in_module_bytes(&self) -> bool {
2139 self.feature_flags.metadata_in_module_bytes
2140 }
2141
2142 pub fn publish_package_metadata(&self) -> bool {
2143 self.feature_flags.publish_package_metadata
2144 }
2145
2146 pub fn enable_move_authentication(&self) -> bool {
2147 self.feature_flags.enable_move_authentication
2148 }
2149
2150 pub fn additional_borrow_checks(&self) -> bool {
2151 self.feature_flags.additional_borrow_checks
2152 }
2153
2154 pub fn enable_move_authentication_for_sponsor(&self) -> bool {
2155 let enable_move_authentication_for_sponsor =
2156 self.feature_flags.enable_move_authentication_for_sponsor;
2157 assert!(
2158 !enable_move_authentication_for_sponsor || self.enable_move_authentication(),
2159 "enable_move_authentication_for_sponsor requires enable_move_authentication to be set"
2160 );
2161 enable_move_authentication_for_sponsor
2162 }
2163
2164 pub fn pass_validator_scores_to_advance_epoch(&self) -> bool {
2165 self.feature_flags.pass_validator_scores_to_advance_epoch
2166 }
2167
2168 pub fn calculate_validator_scores(&self) -> bool {
2169 let calculate_validator_scores = self.feature_flags.calculate_validator_scores;
2170 assert!(
2171 !calculate_validator_scores || self.scorer_version.is_some(),
2172 "calculate_validator_scores requires scorer_version to be set"
2173 );
2174 calculate_validator_scores
2175 }
2176
2177 pub fn adjust_rewards_by_score(&self) -> bool {
2178 let adjust = self.feature_flags.adjust_rewards_by_score;
2179 assert!(
2180 !adjust || (self.scorer_version.is_some() && self.calculate_validator_scores()),
2181 "adjust_rewards_by_score requires scorer_version to be set"
2182 );
2183 adjust
2184 }
2185
2186 pub fn pass_calculated_validator_scores_to_advance_epoch(&self) -> bool {
2187 let pass = self
2188 .feature_flags
2189 .pass_calculated_validator_scores_to_advance_epoch;
2190 assert!(
2191 !pass
2192 || (self.pass_validator_scores_to_advance_epoch()
2193 && self.calculate_validator_scores()),
2194 "pass_calculated_validator_scores_to_advance_epoch requires pass_validator_scores_to_advance_epoch and calculate_validator_scores to be enabled"
2195 );
2196 pass
2197 }
2198 pub fn consensus_fast_commit_sync(&self) -> bool {
2199 let res = self.feature_flags.consensus_fast_commit_sync;
2200 assert!(
2201 !res || self.consensus_commit_transactions_only_for_traversed_headers(),
2202 "consensus_fast_commit_sync requires consensus_commit_transactions_only_for_traversed_headers to be enabled"
2203 );
2204 res
2205 }
2206
2207 pub fn consensus_block_restrictions(&self) -> bool {
2208 self.feature_flags.consensus_block_restrictions
2209 }
2210
2211 pub fn move_native_tx_context(&self) -> bool {
2212 self.feature_flags.move_native_tx_context
2213 }
2214
2215 pub fn pre_consensus_sponsor_only_move_authentication(&self) -> bool {
2216 let pre_consensus_sponsor_only_move_authentication = self
2217 .feature_flags
2218 .pre_consensus_sponsor_only_move_authentication;
2219 if pre_consensus_sponsor_only_move_authentication {
2220 assert!(
2221 self.enable_move_authentication(),
2222 "pre_consensus_sponsor_only_move_authentication requires enable_move_authentication to be set"
2223 );
2224 assert!(
2225 self.enable_move_authentication_for_sponsor(),
2226 "pre_consensus_sponsor_only_move_authentication requires enable_move_authentication_for_sponsor to be set"
2227 );
2228 }
2229 pre_consensus_sponsor_only_move_authentication
2230 }
2231
2232 pub fn consensus_starfish_speed(&self) -> bool {
2233 let res = self.feature_flags.consensus_starfish_speed;
2234 assert!(
2235 !res || self.consensus_fast_commit_sync(),
2236 "consensus_starfish_speed requires consensus_fast_commit_sync to be enabled"
2237 );
2238 res
2239 }
2240
2241 pub fn always_advance_dkg_to_resolution(&self) -> bool {
2242 self.feature_flags.always_advance_dkg_to_resolution
2243 }
2244
2245 pub fn enable_pcool_flow(&self) -> bool {
2246 self.feature_flags.enable_pcool_flow
2247 }
2248
2249 pub fn validator_metadata_verify_v2(&self) -> bool {
2250 self.feature_flags.validator_metadata_verify_v2
2251 }
2252
2253 pub fn commits_per_schedule(&self) -> u32 {
2254 let commits_per_schedule = if cfg!(msim) {
2255 // Exercise faster leader-schedule rotation in simtests.
2256 min(10, self.consensus_commits_per_schedule.unwrap_or(300))
2257 } else {
2258 self.consensus_commits_per_schedule.unwrap_or(300)
2259 };
2260 assert!(
2261 commits_per_schedule > 0,
2262 "consensus_commits_per_schedule must be greater than 0"
2263 );
2264 commits_per_schedule
2265 }
2266
2267 pub fn leader_schedule_window_size(&self) -> u32 {
2268 if cfg!(msim) {
2269 // Keep the scoring window commensurate with the msim-scaled
2270 // commit sync parameters.
2271 min(
2272 20,
2273 self.consensus_leader_schedule_window_size.unwrap_or(600),
2274 )
2275 } else {
2276 self.consensus_leader_schedule_window_size.unwrap_or(600)
2277 }
2278 }
2279
2280 pub fn consensus_enable_sliding_window_leader_schedule(&self) -> bool {
2281 let res = self
2282 .feature_flags
2283 .consensus_enable_sliding_window_leader_schedule;
2284 assert!(
2285 !res || self.leader_schedule_window_size() >= self.commits_per_schedule(),
2286 "consensus_enable_sliding_window_leader_schedule requires window_size >= commits_per_schedule"
2287 );
2288 res
2289 }
2290
2291 pub fn consensus_enable_absolute_score_leader_schedule(&self) -> bool {
2292 self.feature_flags
2293 .consensus_enable_absolute_score_leader_schedule
2294 }
2295
2296 pub fn max_ptb_value_size_v2(&self) -> bool {
2297 self.feature_flags.max_ptb_value_size_v2
2298 }
2299
2300 pub fn deny_authenticator_packages(&self) -> bool {
2301 self.feature_flags.deny_authenticator_packages
2302 }
2303
2304 pub fn package_metadata_with_dynamic_module_metadata(&self) -> bool {
2305 let res = self
2306 .feature_flags
2307 .package_metadata_with_dynamic_module_metadata;
2308 assert!(
2309 !res || self.publish_package_metadata(),
2310 "package_metadata_with_dynamic_module_metadata requires publish_package_metadata to be enabled"
2311 );
2312 res
2313 }
2314
2315 pub fn report_move_authentication_error(&self) -> bool {
2316 let report_move_authentication_error = self.feature_flags.report_move_authentication_error;
2317 assert!(
2318 !report_move_authentication_error || self.enable_move_authentication(),
2319 "report_move_authentication_error requires enable_move_authentication to be set"
2320 );
2321 report_move_authentication_error
2322 }
2323
2324 /// Named to avoid colliding with the derive-generated
2325 /// `max_concurrent_execution_workers[_as_option]()`, which bypass the
2326 /// checks below — always read the parameter through this getter.
2327 pub fn concurrent_execution_workers(&self) -> Option<u16> {
2328 let res = self.max_concurrent_execution_workers;
2329 assert!(
2330 res.is_none() || self.enable_pcool_flow(),
2331 "max_concurrent_execution_workers requires enable_pcool_flow to be enabled"
2332 );
2333 assert!(
2334 res.is_none()
2335 || self
2336 .max_accumulated_txn_cost_per_object_in_mysticeti_commit
2337 .is_some(),
2338 "max_concurrent_execution_workers requires per-object congestion control \
2339 (max_accumulated_txn_cost_per_object_in_mysticeti_commit) to be enabled"
2340 );
2341 assert!(
2342 res.is_none() || self.congestion_control_gas_price_feedback_mechanism(),
2343 "max_concurrent_execution_workers requires the gas price feedback mechanism \
2344 (congestion_control_gas_price_feedback_mechanism), which carries the suggested \
2345 gas price of an execution-worker congestion cancellation"
2346 );
2347 assert!(
2348 res.is_none() || !self.separate_gas_price_feedback_mechanism_for_randomness(),
2349 "max_concurrent_execution_workers implies a single congestion tracker and suggested \
2350 gas price calculator for all transactions, which is incompatible with \
2351 separate_gas_price_feedback_mechanism_for_randomness"
2352 );
2353 assert!(
2354 res != Some(0),
2355 "max_concurrent_execution_workers must be positive when set"
2356 );
2357 res
2358 }
2359
2360 pub fn allow_unbounded_system_objects(&self) -> bool {
2361 self.feature_flags.allow_unbounded_system_objects
2362 }
2363
2364 pub fn reject_immutable_account_objects(&self) -> bool {
2365 let reject_immutable_account_objects = self.feature_flags.reject_immutable_account_objects;
2366 assert!(
2367 !reject_immutable_account_objects || self.enable_move_authentication(),
2368 "reject_immutable_account_objects requires enable_move_authentication to be set"
2369 );
2370 reject_immutable_account_objects
2371 }
2372
2373 pub fn reject_immutable_account_creation(&self) -> bool {
2374 let reject_immutable_account_creation =
2375 self.feature_flags.reject_immutable_account_creation;
2376 assert!(
2377 !reject_immutable_account_creation || self.reject_immutable_account_objects(),
2378 "reject_immutable_account_creation requires reject_immutable_account_objects to be set"
2379 );
2380 reject_immutable_account_creation
2381 }
2382
2383 pub fn validate_input_object_versions(&self) -> bool {
2384 self.feature_flags.validate_input_object_versions
2385 }
2386
2387 pub fn check_canonical_module_version_header(&self) -> bool {
2388 self.feature_flags.check_canonical_module_version_header
2389 }
2390
2391 pub fn disallow_randomness_in_move_authenticator(&self) -> bool {
2392 self.feature_flags.disallow_randomness_in_move_authenticator
2393 }
2394
2395 pub fn check_cyclic_dependencies(&self) -> bool {
2396 self.feature_flags.check_cyclic_dependencies
2397 }
2398
2399 pub fn validate_ptb_argument_indices(&self) -> bool {
2400 self.feature_flags.validate_ptb_argument_indices
2401 }
2402
2403 pub fn allow_dkg_completion_after_timeout(&self) -> bool {
2404 self.feature_flags.allow_dkg_completion_after_timeout
2405 }
2406
2407 pub fn disallow_self_identifier_in_transactions(&self) -> bool {
2408 self.feature_flags.disallow_self_identifier_in_transactions
2409 }
2410
2411 pub fn consensus_dedup_only_recorded_messages(&self) -> bool {
2412 self.feature_flags.consensus_dedup_only_recorded_messages
2413 }
2414
2415 pub fn reject_partially_signed_mixed_ed25519_multisig(&self) -> bool {
2416 self.feature_flags
2417 .reject_partially_signed_mixed_ed25519_multisig
2418 }
2419
2420 pub fn limit_groth16_pvk_inputs(&self) -> bool {
2421 self.feature_flags.limit_groth16_pvk_inputs
2422 }
2423
2424 pub fn check_groth16_pvk_length(&self) -> bool {
2425 self.feature_flags.check_groth16_pvk_length
2426 }
2427
2428 pub fn deprecate_global_storage_ops(&self) -> bool {
2429 self.feature_flags.deprecate_global_storage_ops
2430 }
2431
2432 pub fn meter_instantiation_loops(&self) -> bool {
2433 self.feature_flags.meter_instantiation_loops
2434 }
2435
2436 pub fn move_authenticator_type_arg_packages_as_inputs(&self) -> bool {
2437 self.feature_flags
2438 .move_authenticator_type_arg_packages_as_inputs
2439 }
2440
2441 /// Its prerequisites are checked once, in [`Self::get_for_version`].
2442 pub fn enable_validator_attestation(&self) -> bool {
2443 self.feature_flags.enable_validator_attestation
2444 }
2445
2446 pub fn secp256r1_ecrecover_checks_x_below_p(&self) -> bool {
2447 self.feature_flags.secp256r1_ecrecover_checks_x_below_p
2448 }
2449}
2450
2451#[cfg(not(msim))]
2452static POISON_VERSION_METHODS: AtomicBool = const { AtomicBool::new(false) };
2453
2454// Use a thread local in sim tests for test isolation.
2455#[cfg(msim)]
2456thread_local! {
2457 static POISON_VERSION_METHODS: AtomicBool = const { AtomicBool::new(false) };
2458}
2459
2460// Instantiations for each protocol version.
2461impl ProtocolConfig {
2462 /// Get the value ProtocolConfig that are in effect during the given
2463 /// protocol version.
2464 pub fn get_for_version(version: ProtocolVersion, chain: Chain) -> Self {
2465 // ProtocolVersion can be deserialized so we need to check it here as well.
2466 assert!(
2467 version >= ProtocolVersion::MIN,
2468 "Network protocol version is {:?}, but the minimum supported version by the binary is {:?}. Please upgrade the binary.",
2469 version,
2470 ProtocolVersion::MIN.0,
2471 );
2472 assert!(
2473 version <= ProtocolVersion::MAX_ALLOWED,
2474 "Network protocol version is {:?}, but the maximum supported version by the binary is {:?}. Please upgrade the binary.",
2475 version,
2476 ProtocolVersion::MAX_ALLOWED.0,
2477 );
2478
2479 let mut ret = Self::get_for_version_impl(version, chain);
2480 ret.version = version;
2481
2482 ret = CONFIG_OVERRIDE.with(|ovr| {
2483 if let Some(override_fn) = &*ovr.borrow() {
2484 warn!(
2485 "overriding ProtocolConfig settings with custom settings (you should not see this log outside of tests)"
2486 );
2487 override_fn(version, ret)
2488 } else {
2489 ret
2490 }
2491 });
2492
2493 if std::env::var("IOTA_PROTOCOL_CONFIG_OVERRIDE_ENABLE").is_ok() {
2494 warn!(
2495 "overriding ProtocolConfig settings with custom settings; this may break non-local networks"
2496 );
2497
2498 // First, deserialize the top-level ProtocolConfig fields
2499 let overrides: ProtocolConfigOptional =
2500 serde_env::from_env_with_prefix("IOTA_PROTOCOL_CONFIG_OVERRIDE")
2501 .expect("failed to parse ProtocolConfig override env variables");
2502 overrides.apply_to(&mut ret);
2503
2504 // Then, separately deserialize FeatureFlags fields
2505 let feature_flag_overrides: FeatureFlagsOptional =
2506 serde_env::from_env_with_prefix("IOTA_PROTOCOL_CONFIG_FEATURE_FLAGS_OVERRIDE")
2507 .expect("failed to parse ProtocolConfig feature flags override env variables");
2508
2509 feature_flag_overrides.apply_to(&mut ret.feature_flags);
2510 }
2511
2512 // Devnet runs the P-COOL flow from version 32, before the settings it
2513 // requires exist; only versions from 39 on are checked for them. A test
2514 // override can return the config of another version, so the check
2515 // reads the version of the config returned.
2516 let pcool_requirements_apply =
2517 ret.feature_flags.enable_pcool_flow && ret.version >= ProtocolVersion::new(39);
2518 // Post-consensus validation meters published packages with the
2519 // verifier limits from this config, and reads the regex check budget
2520 // through the panicking accessor.
2521 assert!(
2522 !pcool_requirements_apply || ret.max_meter_ticks_regex_reference_safety.is_some(),
2523 "enable_pcool_flow requires max_meter_ticks_regex_reference_safety"
2524 );
2525 // For the same reason, the consensus handler must not skip a message
2526 // as a duplicate of one that was dropped without being recorded, as
2527 // its cache of such messages differs between validators.
2528 assert!(
2529 !pcool_requirements_apply || ret.feature_flags.consensus_dedup_only_recorded_messages,
2530 "enable_pcool_flow requires consensus_dedup_only_recorded_messages"
2531 );
2532 // With a distance of 0, the consensus handler processing commit C
2533 // would wait for C itself to be fully executed, which cannot happen
2534 // before the handler finishes processing C.
2535 assert!(
2536 !pcool_requirements_apply
2537 || ret
2538 .pcool_deterministic_validation_horizon_distance
2539 .is_some_and(|distance| distance > 0),
2540 "enable_pcool_flow requires a positive pcool_deterministic_validation_horizon_distance"
2541 );
2542 // Without the sender's authenticator run before consensus, a sponsor
2543 // alone could get a transaction sequenced that locks a Move account's
2544 // owned objects.
2545 assert!(
2546 !pcool_requirements_apply
2547 || !ret
2548 .feature_flags
2549 .pre_consensus_sponsor_only_move_authentication,
2550 "enable_pcool_flow excludes pre_consensus_sponsor_only_move_authentication"
2551 );
2552 // The injection cannot chunk updates without its limit.
2553 assert!(
2554 !pcool_requirements_apply || ret.deny_rule_update_max_entries_per_tx.is_some(),
2555 "enable_pcool_flow requires deny_rule_update_max_entries_per_tx"
2556 );
2557 // A deny-rule update chunk must always execute, or the object falls
2558 // permanently behind the mirrored state on every validator at once.
2559 // The binding limits are `max_event_emit_size` (the update event
2560 // carries every entry, ~32 bytes each) and the object-runtime store
2561 // entries touched when removals re-link `LinkedTable` nodes — neither
2562 // expressible as an entry count here, so the constant keeps a wide
2563 // margin below them (tightest is roughly 5000 entries).
2564 const DENY_RULE_UPDATE_MAX_ENTRIES_PER_TX_CEILING: u64 = 2048;
2565 assert!(
2566 ret.deny_rule_update_max_entries_per_tx
2567 .is_none_or(|max_entries| {
2568 max_entries > 0
2569 && max_entries <= DENY_RULE_UPDATE_MAX_ENTRIES_PER_TX_CEILING
2570 && [
2571 ret.max_num_new_move_object_ids_system_tx,
2572 ret.max_num_deleted_move_object_ids_system_tx,
2573 ret.object_runtime_max_num_cached_objects_system_tx,
2574 ret.object_runtime_max_num_store_entries_system_tx,
2575 ]
2576 .iter()
2577 .all(|limit| limit.is_none_or(|limit| max_entries <= limit))
2578 }),
2579 "deny_rule_update_max_entries_per_tx must be positive, at most {DENY_RULE_UPDATE_MAX_ENTRIES_PER_TX_CEILING}, and within the system transaction object limits"
2580 );
2581
2582 if ret.enable_validator_attestation() {
2583 assert!(
2584 ret.enable_pcool_flow(),
2585 "enable_validator_attestation requires enable_pcool_flow to be set"
2586 );
2587 assert!(
2588 ret.report_move_authentication_error(),
2589 "enable_validator_attestation requires report_move_authentication_error to be set"
2590 );
2591 // The attestation verdicts are certified in the summary's version 2.
2592 assert!(
2593 ret.checkpoint_summary_version_specific_data == Some(2),
2594 "enable_validator_attestation requires checkpoint_summary_version_specific_data = 2"
2595 );
2596 }
2597 if ret.attestation_max_refuted_units_squared.is_some() {
2598 assert!(
2599 ret.enable_validator_attestation(),
2600 "attestation_max_refuted_units_squared requires enable_validator_attestation"
2601 );
2602 assert!(
2603 ret.pass_validator_scores_to_advance_epoch(),
2604 "attestation_max_refuted_units_squared requires \
2605 pass_validator_scores_to_advance_epoch"
2606 );
2607 }
2608
2609 ret
2610 }
2611
2612 /// Get the value ProtocolConfig that are in effect during the given
2613 /// protocol version. Or none if the version is not supported.
2614 pub fn get_for_version_if_supported(version: ProtocolVersion, chain: Chain) -> Option<Self> {
2615 if version.0 >= ProtocolVersion::MIN.0 && version.0 <= ProtocolVersion::MAX_ALLOWED.0 {
2616 let mut ret = Self::get_for_version_impl(version, chain);
2617 ret.version = version;
2618 Some(ret)
2619 } else {
2620 None
2621 }
2622 }
2623
2624 #[cfg(not(msim))]
2625 pub fn poison_get_for_min_version() {
2626 POISON_VERSION_METHODS.store(true, Ordering::Relaxed);
2627 }
2628
2629 #[cfg(not(msim))]
2630 fn load_poison_get_for_min_version() -> bool {
2631 POISON_VERSION_METHODS.load(Ordering::Relaxed)
2632 }
2633
2634 #[cfg(msim)]
2635 pub fn poison_get_for_min_version() {
2636 POISON_VERSION_METHODS.with(|p| p.store(true, Ordering::Relaxed));
2637 }
2638
2639 #[cfg(msim)]
2640 fn load_poison_get_for_min_version() -> bool {
2641 POISON_VERSION_METHODS.with(|p| p.load(Ordering::Relaxed))
2642 }
2643
2644 pub fn convert_type_argument_error(&self) -> bool {
2645 self.feature_flags.convert_type_argument_error
2646 }
2647
2648 /// Convenience to get the constants at the current minimum supported
2649 /// version. Mainly used by client code that may not yet be
2650 /// protocol-version aware.
2651 pub fn get_for_min_version() -> Self {
2652 if Self::load_poison_get_for_min_version() {
2653 panic!("get_for_min_version called on validator");
2654 }
2655 ProtocolConfig::get_for_version(ProtocolVersion::MIN, Chain::Unknown)
2656 }
2657
2658 /// CAREFUL! - You probably want to use `get_for_version` instead.
2659 ///
2660 /// Convenience to get the constants at the current maximum supported
2661 /// version. Mainly used by genesis. Note well that this function uses
2662 /// the max version supported locally by the node, which is not
2663 /// necessarily the current version of the network. ALSO, this function
2664 /// disregards chain specific config (by using Chain::Unknown), thereby
2665 /// potentially returning a protocol config that is incorrect for some
2666 /// feature flags. Definitely safe for testing and for protocol version
2667 /// 11 and prior.
2668 #[expect(non_snake_case)]
2669 pub fn get_for_max_version_UNSAFE() -> Self {
2670 if Self::load_poison_get_for_min_version() {
2671 panic!("get_for_max_version_UNSAFE called on validator");
2672 }
2673 ProtocolConfig::get_for_version(ProtocolVersion::MAX, Chain::Unknown)
2674 }
2675
2676 fn get_for_version_impl(version: ProtocolVersion, chain: Chain) -> Self {
2677 #[cfg(msim)]
2678 {
2679 // populate the fake simulator version # with a different base tx cost.
2680 if version > ProtocolVersion::MAX {
2681 let mut config = Self::get_for_version_impl(ProtocolVersion::MAX, Chain::Unknown);
2682 config.base_tx_cost_fixed = Some(config.base_tx_cost_fixed() + 1000);
2683 return config;
2684 }
2685 }
2686
2687 // IMPORTANT: Never modify the value of any constant for a pre-existing protocol
2688 // version. To change the values here you must create a new protocol
2689 // version with the new values!
2690 let mut cfg = Self {
2691 version,
2692
2693 feature_flags: Default::default(),
2694
2695 max_tx_size_bytes: Some(128 * 1024),
2696 // We need this number to be at least 100x less than
2697 // `max_serialized_tx_effects_size_bytes`otherwise effects can be huge
2698 max_input_objects: Some(2048),
2699 max_serialized_tx_effects_size_bytes: Some(512 * 1024),
2700 max_serialized_tx_effects_size_bytes_system_tx: Some(512 * 1024 * 16),
2701 max_gas_payment_objects: Some(256),
2702 max_modules_in_publish: Some(64),
2703 max_package_dependencies: Some(32),
2704 max_arguments: Some(512),
2705 max_type_arguments: Some(16),
2706 max_type_argument_depth: Some(16),
2707 max_pure_argument_size: Some(16 * 1024),
2708 max_programmable_tx_commands: Some(1024),
2709 move_binary_format_version: Some(7),
2710 min_move_binary_format_version: Some(6),
2711 binary_module_handles: Some(100),
2712 binary_struct_handles: Some(300),
2713 binary_function_handles: Some(1500),
2714 binary_function_instantiations: Some(750),
2715 binary_signatures: Some(1000),
2716 binary_constant_pool: Some(4000),
2717 binary_identifiers: Some(10000),
2718 binary_address_identifiers: Some(100),
2719 binary_struct_defs: Some(200),
2720 binary_struct_def_instantiations: Some(100),
2721 binary_function_defs: Some(1000),
2722 binary_field_handles: Some(500),
2723 binary_field_instantiations: Some(250),
2724 binary_friend_decls: Some(100),
2725 binary_enum_defs: None,
2726 binary_enum_def_instantiations: None,
2727 binary_variant_handles: None,
2728 binary_variant_instantiation_handles: None,
2729 max_move_object_size: Some(250 * 1024),
2730 max_move_package_size: Some(100 * 1024),
2731 max_publish_or_upgrade_per_ptb: Some(5),
2732 // max gas budget for an authentication is in NANOS
2733 max_auth_gas: None,
2734 // max gas budget is in NANOS and an absolute value 50IOTA
2735 max_tx_gas: Some(50_000_000_000),
2736 max_gas_price: Some(100_000),
2737 max_gas_computation_bucket: Some(5_000_000),
2738 max_loop_depth: Some(5),
2739 max_generic_instantiation_length: Some(32),
2740 max_function_parameters: Some(128),
2741 max_basic_blocks: Some(1024),
2742 max_value_stack_size: Some(1024),
2743 max_type_nodes: Some(256),
2744 max_push_size: Some(10000),
2745 max_struct_definitions: Some(200),
2746 max_function_definitions: Some(1000),
2747 max_fields_in_struct: Some(32),
2748 max_dependency_depth: Some(100),
2749 max_num_event_emit: Some(1024),
2750 max_num_new_move_object_ids: Some(2048),
2751 max_num_new_move_object_ids_system_tx: Some(2048 * 16),
2752 max_num_deleted_move_object_ids: Some(2048),
2753 max_num_deleted_move_object_ids_system_tx: Some(2048 * 16),
2754 max_num_transferred_move_object_ids: Some(2048),
2755 max_num_transferred_move_object_ids_system_tx: Some(2048 * 16),
2756 max_event_emit_size: Some(250 * 1024),
2757 max_move_vector_len: Some(256 * 1024),
2758 max_type_to_layout_nodes: None,
2759 max_ptb_value_size: None,
2760
2761 max_back_edges_per_function: Some(10_000),
2762 max_back_edges_per_module: Some(10_000),
2763
2764 max_verifier_meter_ticks_per_function: Some(16_000_000),
2765
2766 max_meter_ticks_per_module: Some(16_000_000),
2767 max_meter_ticks_per_package: Some(16_000_000),
2768 max_meter_ticks_regex_reference_safety: None,
2769 max_instantiation_loop_graph_edges: None,
2770
2771 object_runtime_max_num_cached_objects: Some(1000),
2772 object_runtime_max_num_cached_objects_system_tx: Some(1000 * 16),
2773 object_runtime_max_num_store_entries: Some(1000),
2774 object_runtime_max_num_store_entries_system_tx: Some(1000 * 16),
2775 // min gas budget is in NANOS and an absolute value 1000 NANOS or 0.000001IOTA
2776 base_tx_cost_fixed: Some(1_000),
2777 package_publish_cost_fixed: Some(1_000),
2778 base_tx_cost_per_byte: Some(0),
2779 package_publish_cost_per_byte: Some(80),
2780 obj_access_cost_read_per_byte: Some(15),
2781 obj_access_cost_mutate_per_byte: Some(40),
2782 obj_access_cost_delete_per_byte: Some(40),
2783 obj_access_cost_verify_per_byte: Some(200),
2784 obj_data_cost_refundable: Some(100),
2785 obj_metadata_cost_non_refundable: Some(50),
2786 gas_model_version: Some(1),
2787 storage_rebate_rate: Some(10000),
2788 // Change reward slashing rate to 100%.
2789 reward_slashing_rate: Some(10000),
2790 storage_gas_price: Some(76),
2791 base_gas_price: None,
2792 // The initial subsidy (target reward) for validators per epoch.
2793 // Refer to the IOTA tokenomics for the origin of this value.
2794 validator_target_reward: Some(767_000 * 1_000_000_000),
2795 max_transactions_per_checkpoint: Some(10_000),
2796 max_checkpoint_size_bytes: Some(30 * 1024 * 1024),
2797
2798 // For now, perform upgrades with a bare quorum of validators.
2799 buffer_stake_for_protocol_upgrade_bps: Some(5000),
2800
2801 // === Native Function Costs ===
2802 // `address` module
2803 // Cost params for the Move native function `address::from_bytes(bytes: vector<u8>)`
2804 address_from_bytes_cost_base: Some(52),
2805 // Cost params for the Move native function `address::to_u256(address): u256`
2806 address_to_u256_cost_base: Some(52),
2807 // Cost params for the Move native function `address::from_u256(u256): address`
2808 address_from_u256_cost_base: Some(52),
2809
2810 // `config` module
2811 // Cost params for the Move native function `read_setting_impl``
2812 config_read_setting_impl_cost_base: Some(100),
2813 config_read_setting_impl_cost_per_byte: Some(40),
2814
2815 // `dynamic_field` module
2816 // Cost params for the Move native function `hash_type_and_key<K: copy + drop +
2817 // store>(parent: address, k: K): address`
2818 dynamic_field_hash_type_and_key_cost_base: Some(100),
2819 dynamic_field_hash_type_and_key_type_cost_per_byte: Some(2),
2820 dynamic_field_hash_type_and_key_value_cost_per_byte: Some(2),
2821 dynamic_field_hash_type_and_key_type_tag_cost_per_byte: Some(2),
2822 // Cost params for the Move native function `add_child_object<Child: key>(parent:
2823 // address, child: Child)`
2824 dynamic_field_add_child_object_cost_base: Some(100),
2825 dynamic_field_add_child_object_type_cost_per_byte: Some(10),
2826 dynamic_field_add_child_object_value_cost_per_byte: Some(10),
2827 dynamic_field_add_child_object_struct_tag_cost_per_byte: Some(10),
2828 // Cost params for the Move native function `borrow_child_object_mut<Child: key>(parent:
2829 // &mut UID, id: address): &mut Child`
2830 dynamic_field_borrow_child_object_cost_base: Some(100),
2831 dynamic_field_borrow_child_object_child_ref_cost_per_byte: Some(10),
2832 dynamic_field_borrow_child_object_type_cost_per_byte: Some(10),
2833 // Cost params for the Move native function `remove_child_object<Child: key>(parent:
2834 // address, id: address): Child`
2835 dynamic_field_remove_child_object_cost_base: Some(100),
2836 dynamic_field_remove_child_object_child_cost_per_byte: Some(2),
2837 dynamic_field_remove_child_object_type_cost_per_byte: Some(2),
2838 // Cost params for the Move native function `has_child_object(parent: address, id:
2839 // address): bool`
2840 dynamic_field_has_child_object_cost_base: Some(100),
2841 // Cost params for the Move native function `has_child_object_with_ty<Child:
2842 // key>(parent: address, id: address): bool`
2843 dynamic_field_has_child_object_with_ty_cost_base: Some(100),
2844 dynamic_field_has_child_object_with_ty_type_cost_per_byte: Some(2),
2845 dynamic_field_has_child_object_with_ty_type_tag_cost_per_byte: Some(2),
2846
2847 // `event` module
2848 // Cost params for the Move native function `event::emit<T: copy + drop>(event: T)`
2849 event_emit_cost_base: Some(52),
2850 event_emit_value_size_derivation_cost_per_byte: Some(2),
2851 event_emit_tag_size_derivation_cost_per_byte: Some(5),
2852 event_emit_output_cost_per_byte: Some(10),
2853
2854 // `object` module
2855 // Cost params for the Move native function `borrow_uid<T: key>(obj: &T): &UID`
2856 object_borrow_uid_cost_base: Some(52),
2857 // Cost params for the Move native function `delete_impl(id: address)`
2858 object_delete_impl_cost_base: Some(52),
2859 // Cost params for the Move native function `record_new_uid(id: address)`
2860 object_record_new_uid_cost_base: Some(52),
2861
2862 // `transfer` module
2863 // Cost params for the Move native function `transfer_impl<T: key>(obj: T, recipient:
2864 // address)`
2865 transfer_transfer_internal_cost_base: Some(52),
2866 // Cost params for the Move native function `freeze_object<T: key>(obj: T)`
2867 transfer_freeze_object_cost_base: Some(52),
2868 // Cost params for the Move native function `share_object<T: key>(obj: T)`
2869 transfer_share_object_cost_base: Some(52),
2870 transfer_receive_object_cost_base: Some(52),
2871
2872 // `tx_context` module
2873 // Cost params for the Move native function `transfer_impl<T: key>(obj: T, recipient:
2874 // address)`
2875 tx_context_derive_id_cost_base: Some(52),
2876 tx_context_fresh_id_cost_base: None,
2877 tx_context_sender_cost_base: None,
2878 tx_context_digest_cost_base: None,
2879 tx_context_epoch_cost_base: None,
2880 tx_context_epoch_timestamp_ms_cost_base: None,
2881 tx_context_sponsor_cost_base: None,
2882 tx_context_rgp_cost_base: None,
2883 tx_context_gas_price_cost_base: None,
2884 tx_context_gas_budget_cost_base: None,
2885 tx_context_ids_created_cost_base: None,
2886 tx_context_replace_cost_base: None,
2887
2888 // `types` module
2889 // Cost params for the Move native function `is_one_time_witness<T: drop>(_: &T): bool`
2890 types_is_one_time_witness_cost_base: Some(52),
2891 types_is_one_time_witness_type_tag_cost_per_byte: Some(2),
2892 types_is_one_time_witness_type_cost_per_byte: Some(2),
2893
2894 // `validator` module
2895 // Cost params for the Move native function `validate_metadata_bcs(metadata:
2896 // vector<u8>)`
2897 validator_validate_metadata_cost_base: Some(52),
2898 validator_validate_metadata_data_cost_per_byte: Some(2),
2899
2900 // Crypto
2901 crypto_invalid_arguments_cost: Some(100),
2902 // bls12381::bls12381_min_pk_verify
2903 bls12381_bls12381_min_sig_verify_cost_base: Some(52),
2904 bls12381_bls12381_min_sig_verify_msg_cost_per_byte: Some(2),
2905 bls12381_bls12381_min_sig_verify_msg_cost_per_block: Some(2),
2906
2907 // bls12381::bls12381_min_pk_verify
2908 bls12381_bls12381_min_pk_verify_cost_base: Some(52),
2909 bls12381_bls12381_min_pk_verify_msg_cost_per_byte: Some(2),
2910 bls12381_bls12381_min_pk_verify_msg_cost_per_block: Some(2),
2911
2912 // ecdsa_k1::ecrecover
2913 ecdsa_k1_ecrecover_keccak256_cost_base: Some(52),
2914 ecdsa_k1_ecrecover_keccak256_msg_cost_per_byte: Some(2),
2915 ecdsa_k1_ecrecover_keccak256_msg_cost_per_block: Some(2),
2916 ecdsa_k1_ecrecover_sha256_cost_base: Some(52),
2917 ecdsa_k1_ecrecover_sha256_msg_cost_per_byte: Some(2),
2918 ecdsa_k1_ecrecover_sha256_msg_cost_per_block: Some(2),
2919
2920 // ecdsa_k1::decompress_pubkey
2921 ecdsa_k1_decompress_pubkey_cost_base: Some(52),
2922
2923 // ecdsa_k1::secp256k1_verify
2924 ecdsa_k1_secp256k1_verify_keccak256_cost_base: Some(52),
2925 ecdsa_k1_secp256k1_verify_keccak256_msg_cost_per_byte: Some(2),
2926 ecdsa_k1_secp256k1_verify_keccak256_msg_cost_per_block: Some(2),
2927 ecdsa_k1_secp256k1_verify_sha256_cost_base: Some(52),
2928 ecdsa_k1_secp256k1_verify_sha256_msg_cost_per_byte: Some(2),
2929 ecdsa_k1_secp256k1_verify_sha256_msg_cost_per_block: Some(2),
2930
2931 // ecdsa_r1::ecrecover
2932 ecdsa_r1_ecrecover_keccak256_cost_base: Some(52),
2933 ecdsa_r1_ecrecover_keccak256_msg_cost_per_byte: Some(2),
2934 ecdsa_r1_ecrecover_keccak256_msg_cost_per_block: Some(2),
2935 ecdsa_r1_ecrecover_sha256_cost_base: Some(52),
2936 ecdsa_r1_ecrecover_sha256_msg_cost_per_byte: Some(2),
2937 ecdsa_r1_ecrecover_sha256_msg_cost_per_block: Some(2),
2938
2939 // ecdsa_r1::secp256k1_verify
2940 ecdsa_r1_secp256r1_verify_keccak256_cost_base: Some(52),
2941 ecdsa_r1_secp256r1_verify_keccak256_msg_cost_per_byte: Some(2),
2942 ecdsa_r1_secp256r1_verify_keccak256_msg_cost_per_block: Some(2),
2943 ecdsa_r1_secp256r1_verify_sha256_cost_base: Some(52),
2944 ecdsa_r1_secp256r1_verify_sha256_msg_cost_per_byte: Some(2),
2945 ecdsa_r1_secp256r1_verify_sha256_msg_cost_per_block: Some(2),
2946
2947 // ecvrf::verify
2948 ecvrf_ecvrf_verify_cost_base: Some(52),
2949 ecvrf_ecvrf_verify_alpha_string_cost_per_byte: Some(2),
2950 ecvrf_ecvrf_verify_alpha_string_cost_per_block: Some(2),
2951
2952 // ed25519
2953 ed25519_ed25519_verify_cost_base: Some(52),
2954 ed25519_ed25519_verify_msg_cost_per_byte: Some(2),
2955 ed25519_ed25519_verify_msg_cost_per_block: Some(2),
2956
2957 // groth16::prepare_verifying_key
2958 groth16_prepare_verifying_key_bls12381_cost_base: Some(52),
2959 groth16_prepare_verifying_key_bn254_cost_base: Some(52),
2960
2961 // groth16::verify_groth16_proof_internal
2962 groth16_verify_groth16_proof_internal_bls12381_cost_base: Some(52),
2963 groth16_verify_groth16_proof_internal_bls12381_cost_per_public_input: Some(2),
2964 groth16_verify_groth16_proof_internal_bn254_cost_base: Some(52),
2965 groth16_verify_groth16_proof_internal_bn254_cost_per_public_input: Some(2),
2966 groth16_verify_groth16_proof_internal_public_input_cost_per_byte: Some(2),
2967
2968 // hash::blake2b256
2969 hash_blake2b256_cost_base: Some(52),
2970 hash_blake2b256_data_cost_per_byte: Some(2),
2971 hash_blake2b256_data_cost_per_block: Some(2),
2972 // hash::keccak256
2973 hash_keccak256_cost_base: Some(52),
2974 hash_keccak256_data_cost_per_byte: Some(2),
2975 hash_keccak256_data_cost_per_block: Some(2),
2976
2977 poseidon_bn254_cost_base: None,
2978 poseidon_bn254_cost_per_block: None,
2979
2980 // hmac::hmac_sha3_256
2981 hmac_hmac_sha3_256_cost_base: Some(52),
2982 hmac_hmac_sha3_256_input_cost_per_byte: Some(2),
2983 hmac_hmac_sha3_256_input_cost_per_block: Some(2),
2984
2985 // group ops
2986 group_ops_bls12381_decode_scalar_cost: Some(52),
2987 group_ops_bls12381_decode_g1_cost: Some(52),
2988 group_ops_bls12381_decode_g2_cost: Some(52),
2989 group_ops_bls12381_decode_gt_cost: Some(52),
2990 group_ops_bls12381_scalar_add_cost: Some(52),
2991 group_ops_bls12381_g1_add_cost: Some(52),
2992 group_ops_bls12381_g2_add_cost: Some(52),
2993 group_ops_bls12381_gt_add_cost: Some(52),
2994 group_ops_bls12381_scalar_sub_cost: Some(52),
2995 group_ops_bls12381_g1_sub_cost: Some(52),
2996 group_ops_bls12381_g2_sub_cost: Some(52),
2997 group_ops_bls12381_gt_sub_cost: Some(52),
2998 group_ops_bls12381_scalar_mul_cost: Some(52),
2999 group_ops_bls12381_g1_mul_cost: Some(52),
3000 group_ops_bls12381_g2_mul_cost: Some(52),
3001 group_ops_bls12381_gt_mul_cost: Some(52),
3002 group_ops_bls12381_scalar_div_cost: Some(52),
3003 group_ops_bls12381_g1_div_cost: Some(52),
3004 group_ops_bls12381_g2_div_cost: Some(52),
3005 group_ops_bls12381_gt_div_cost: Some(52),
3006 group_ops_bls12381_g1_hash_to_base_cost: Some(52),
3007 group_ops_bls12381_g2_hash_to_base_cost: Some(52),
3008 group_ops_bls12381_g1_hash_to_cost_per_byte: Some(2),
3009 group_ops_bls12381_g2_hash_to_cost_per_byte: Some(2),
3010 group_ops_bls12381_g1_msm_base_cost: Some(52),
3011 group_ops_bls12381_g2_msm_base_cost: Some(52),
3012 group_ops_bls12381_g1_msm_base_cost_per_input: Some(52),
3013 group_ops_bls12381_g2_msm_base_cost_per_input: Some(52),
3014 group_ops_bls12381_msm_max_len: Some(32),
3015 group_ops_bls12381_pairing_cost: Some(52),
3016 group_ops_bls12381_g1_to_uncompressed_g1_cost: None,
3017 group_ops_bls12381_uncompressed_g1_to_g1_cost: None,
3018 group_ops_bls12381_uncompressed_g1_sum_base_cost: None,
3019 group_ops_bls12381_uncompressed_g1_sum_cost_per_term: None,
3020 group_ops_bls12381_uncompressed_g1_sum_max_terms: None,
3021
3022 // zklogin::check_zklogin_id
3023 #[allow(deprecated)]
3024 check_zklogin_id_cost_base: Some(200),
3025 #[allow(deprecated)]
3026 // zklogin::check_zklogin_issuer
3027 check_zklogin_issuer_cost_base: Some(200),
3028
3029 vdf_verify_vdf_cost: None,
3030 vdf_hash_to_input_cost: None,
3031
3032 bcs_per_byte_serialized_cost: Some(2),
3033 bcs_legacy_min_output_size_cost: Some(1),
3034 bcs_failure_cost: Some(52),
3035 hash_sha2_256_base_cost: Some(52),
3036 hash_sha2_256_per_byte_cost: Some(2),
3037 hash_sha2_256_legacy_min_input_len_cost: Some(1),
3038 hash_sha3_256_base_cost: Some(52),
3039 hash_sha3_256_per_byte_cost: Some(2),
3040 hash_sha3_256_legacy_min_input_len_cost: Some(1),
3041 type_name_get_base_cost: Some(52),
3042 type_name_get_per_byte_cost: Some(2),
3043 string_check_utf8_base_cost: Some(52),
3044 string_check_utf8_per_byte_cost: Some(2),
3045 string_is_char_boundary_base_cost: Some(52),
3046 string_sub_string_base_cost: Some(52),
3047 string_sub_string_per_byte_cost: Some(2),
3048 string_index_of_base_cost: Some(52),
3049 string_index_of_per_byte_pattern_cost: Some(2),
3050 string_index_of_per_byte_searched_cost: Some(2),
3051 vector_empty_base_cost: Some(52),
3052 vector_length_base_cost: Some(52),
3053 vector_push_back_base_cost: Some(52),
3054 vector_push_back_legacy_per_abstract_memory_unit_cost: Some(2),
3055 vector_borrow_base_cost: Some(52),
3056 vector_pop_back_base_cost: Some(52),
3057 vector_destroy_empty_base_cost: Some(52),
3058 vector_swap_base_cost: Some(52),
3059 debug_print_base_cost: Some(52),
3060 debug_print_stack_trace_base_cost: Some(52),
3061
3062 max_size_written_objects: Some(5 * 1000 * 1000),
3063 // max size of written objects during a system TXn to allow for larger writes
3064 // akin to `max_size_written_objects` but for system TXns
3065 max_size_written_objects_system_tx: Some(50 * 1000 * 1000),
3066
3067 // Limits the length of a Move identifier
3068 max_move_identifier_len: Some(128),
3069 max_move_value_depth: Some(128),
3070 max_move_call_argument_nodes: None,
3071 max_move_call_argument_nodes_total: None,
3072 max_move_enum_variants: None,
3073
3074 gas_rounding_step: Some(1_000),
3075
3076 execution_version: Some(1),
3077
3078 // We maintain the same total size limit for events, but increase the number of
3079 // events that can be emitted.
3080 max_event_emit_size_total: Some(
3081 256 /* former event count limit */ * 250 * 1024, // size limit per event
3082 ),
3083
3084 // Taking a baby step approach, we consider only 20% by stake as bad nodes so we
3085 // have a 80% by stake of nodes participating in the leader committee. That
3086 // allow us for more redundancy in case we have validators
3087 // under performing - since the responsibility is shared
3088 // amongst more nodes. We can increase that once we do have
3089 // higher confidence.
3090 consensus_bad_nodes_stake_threshold: Some(20),
3091
3092 // Max of 10 votes per hour.
3093 #[allow(deprecated)]
3094 max_jwk_votes_per_validator_per_epoch: Some(240),
3095
3096 #[allow(deprecated)]
3097 max_age_of_jwk_in_epochs: Some(1),
3098
3099 consensus_max_transaction_size_bytes: Some(256 * 1024), // 256KB
3100
3101 // Assume 1KB per transaction and 500 transactions per block.
3102 consensus_max_transactions_in_block_bytes: Some(512 * 1024),
3103
3104 random_beacon_reduction_allowed_delta: Some(800),
3105
3106 random_beacon_reduction_lower_bound: Some(1000),
3107 random_beacon_dkg_timeout_round: Some(3000),
3108 random_beacon_min_round_interval_ms: Some(500),
3109
3110 random_beacon_dkg_version: Some(1),
3111
3112 // Assume 20_000 TPS * 5% max stake per validator / (minimum) 4 blocks per round
3113 // = 250 transactions per block maximum Using a higher limit
3114 // that is 512, to account for bursty traffic and system transactions.
3115 consensus_max_num_transactions_in_block: Some(512),
3116
3117 max_deferral_rounds_for_congestion_control: Some(10),
3118
3119 min_checkpoint_interval_ms: Some(200),
3120
3121 checkpoint_rate_window_size: None,
3122
3123 checkpoint_summary_version_specific_data: Some(1),
3124 attestor_accuracy_tolerance_percentage: None,
3125 attestation_max_refuted_units_squared: None,
3126
3127 max_soft_bundle_size: Some(5),
3128
3129 bridge_should_try_to_finalize_committee: None,
3130
3131 max_accumulated_txn_cost_per_object_in_mysticeti_commit: Some(10),
3132
3133 max_committee_members_count: None,
3134 deny_rule_update_max_entries_per_tx: None,
3135
3136 consensus_gc_depth: None,
3137
3138 consensus_max_acknowledgments_per_block: None,
3139
3140 max_congestion_limit_overshoot_per_commit: None,
3141
3142 max_concurrent_execution_workers: None,
3143
3144 pcool_deterministic_validation_horizon_distance: None,
3145
3146 scorer_version: None,
3147
3148 // `auth_context` module
3149 auth_context_digest_cost_base: None,
3150 auth_context_tx_data_bytes_cost_base: None,
3151 auth_context_tx_data_bytes_cost_per_byte: None,
3152 auth_context_tx_commands_cost_base: None,
3153 auth_context_tx_commands_cost_per_byte: None,
3154 auth_context_tx_inputs_cost_base: None,
3155 auth_context_tx_inputs_cost_per_byte: None,
3156 auth_context_replace_cost_base: None,
3157 auth_context_replace_cost_per_byte: None,
3158 auth_context_authenticator_function_info_v1_cost_base: None,
3159 consensus_commits_per_schedule: None,
3160 min_validator_count: None,
3161 max_validator_count: None,
3162 min_validator_joining_stake: None,
3163 validator_low_stake_threshold: None,
3164 validator_very_low_stake_threshold: None,
3165 validator_low_stake_grace_period: None,
3166 consensus_leader_schedule_window_size: None,
3167
3168 max_move_system_package_size: None,
3169 // When adding a new constant, set it to None in the earliest version, like this:
3170 // new_constant: None,
3171 };
3172
3173 cfg.feature_flags.consensus_transaction_ordering = ConsensusTransactionOrdering::ByGasPrice;
3174
3175 // MoveVM related flags
3176 {
3177 cfg.feature_flags
3178 .disable_invariant_violation_check_in_swap_loc = true;
3179 cfg.feature_flags.no_extraneous_module_bytes = true;
3180 cfg.feature_flags.hardened_otw_check = true;
3181 cfg.feature_flags.rethrow_serialization_type_layout_errors = true;
3182 }
3183
3184 // zkLogin related flags
3185 {
3186 #[allow(deprecated)]
3187 {
3188 cfg.feature_flags.zklogin_max_epoch_upper_bound_delta = Some(30);
3189 }
3190 }
3191
3192 // Historical default: Mysticeti. Kept explicitly to match the
3193 // serialized form of pre-v14/v19/v24 configs. No runtime behavior
3194 // depends on this — Starfish is the only consensus protocol.
3195 #[expect(deprecated)]
3196 {
3197 cfg.feature_flags.consensus_choice = ConsensusChoice::MysticetiDeprecated;
3198 }
3199 // Use tonic networking for consensus.
3200 cfg.feature_flags.consensus_network = ConsensusNetwork::Tonic;
3201
3202 cfg.feature_flags.per_object_congestion_control_mode =
3203 PerObjectCongestionControlMode::TotalTxCount;
3204
3205 // Do not allow bridge committee to finalize on mainnet.
3206 cfg.bridge_should_try_to_finalize_committee = Some(chain != Chain::Mainnet);
3207
3208 // Devnet
3209 if chain != Chain::Mainnet && chain != Chain::Testnet {
3210 cfg.feature_flags.enable_poseidon = true;
3211 cfg.poseidon_bn254_cost_base = Some(260);
3212 cfg.poseidon_bn254_cost_per_block = Some(10);
3213
3214 cfg.feature_flags.enable_group_ops_native_function_msm = true;
3215
3216 cfg.feature_flags.enable_vdf = true;
3217 // Set to 30x and 2x the cost of a signature verification for now. This
3218 // should be updated along with other native crypto functions.
3219 cfg.vdf_verify_vdf_cost = Some(1500);
3220 cfg.vdf_hash_to_input_cost = Some(100);
3221
3222 cfg.feature_flags.passkey_auth = true;
3223 }
3224
3225 for cur in 2..=version.0 {
3226 match cur {
3227 1 => unreachable!(),
3228 // version 2 is a new framework version but with no config changes
3229 2 => {}
3230 3 => {
3231 cfg.feature_flags.relocate_event_module = true;
3232 }
3233 4 => {
3234 cfg.max_type_to_layout_nodes = Some(512);
3235 }
3236 5 => {
3237 cfg.feature_flags.protocol_defined_base_fee = true;
3238 cfg.base_gas_price = Some(1000);
3239
3240 cfg.feature_flags.disallow_new_modules_in_deps_only_packages = true;
3241 cfg.feature_flags.convert_type_argument_error = true;
3242 cfg.feature_flags.native_charging_v2 = true;
3243
3244 if chain != Chain::Mainnet && chain != Chain::Testnet {
3245 cfg.feature_flags.uncompressed_g1_group_elements = true;
3246 }
3247
3248 cfg.gas_model_version = Some(2);
3249
3250 cfg.poseidon_bn254_cost_per_block = Some(388);
3251
3252 cfg.bls12381_bls12381_min_sig_verify_cost_base = Some(44064);
3253 cfg.bls12381_bls12381_min_pk_verify_cost_base = Some(49282);
3254 cfg.ecdsa_k1_secp256k1_verify_keccak256_cost_base = Some(1470);
3255 cfg.ecdsa_k1_secp256k1_verify_sha256_cost_base = Some(1470);
3256 cfg.ecdsa_r1_secp256r1_verify_sha256_cost_base = Some(4225);
3257 cfg.ecdsa_r1_secp256r1_verify_keccak256_cost_base = Some(4225);
3258 cfg.ecvrf_ecvrf_verify_cost_base = Some(4848);
3259 cfg.ed25519_ed25519_verify_cost_base = Some(1802);
3260
3261 // Manually changed to be "under cost"
3262 cfg.ecdsa_r1_ecrecover_keccak256_cost_base = Some(1173);
3263 cfg.ecdsa_r1_ecrecover_sha256_cost_base = Some(1173);
3264 cfg.ecdsa_k1_ecrecover_keccak256_cost_base = Some(500);
3265 cfg.ecdsa_k1_ecrecover_sha256_cost_base = Some(500);
3266
3267 cfg.groth16_prepare_verifying_key_bls12381_cost_base = Some(53838);
3268 cfg.groth16_prepare_verifying_key_bn254_cost_base = Some(82010);
3269 cfg.groth16_verify_groth16_proof_internal_bls12381_cost_base = Some(72090);
3270 cfg.groth16_verify_groth16_proof_internal_bls12381_cost_per_public_input =
3271 Some(8213);
3272 cfg.groth16_verify_groth16_proof_internal_bn254_cost_base = Some(115502);
3273 cfg.groth16_verify_groth16_proof_internal_bn254_cost_per_public_input =
3274 Some(9484);
3275
3276 cfg.hash_keccak256_cost_base = Some(10);
3277 cfg.hash_blake2b256_cost_base = Some(10);
3278
3279 // group ops
3280 cfg.group_ops_bls12381_decode_scalar_cost = Some(7);
3281 cfg.group_ops_bls12381_decode_g1_cost = Some(2848);
3282 cfg.group_ops_bls12381_decode_g2_cost = Some(3770);
3283 cfg.group_ops_bls12381_decode_gt_cost = Some(3068);
3284
3285 cfg.group_ops_bls12381_scalar_add_cost = Some(10);
3286 cfg.group_ops_bls12381_g1_add_cost = Some(1556);
3287 cfg.group_ops_bls12381_g2_add_cost = Some(3048);
3288 cfg.group_ops_bls12381_gt_add_cost = Some(188);
3289
3290 cfg.group_ops_bls12381_scalar_sub_cost = Some(10);
3291 cfg.group_ops_bls12381_g1_sub_cost = Some(1550);
3292 cfg.group_ops_bls12381_g2_sub_cost = Some(3019);
3293 cfg.group_ops_bls12381_gt_sub_cost = Some(497);
3294
3295 cfg.group_ops_bls12381_scalar_mul_cost = Some(11);
3296 cfg.group_ops_bls12381_g1_mul_cost = Some(4842);
3297 cfg.group_ops_bls12381_g2_mul_cost = Some(9108);
3298 cfg.group_ops_bls12381_gt_mul_cost = Some(27490);
3299
3300 cfg.group_ops_bls12381_scalar_div_cost = Some(91);
3301 cfg.group_ops_bls12381_g1_div_cost = Some(5091);
3302 cfg.group_ops_bls12381_g2_div_cost = Some(9206);
3303 cfg.group_ops_bls12381_gt_div_cost = Some(27804);
3304
3305 cfg.group_ops_bls12381_g1_hash_to_base_cost = Some(2962);
3306 cfg.group_ops_bls12381_g2_hash_to_base_cost = Some(8688);
3307
3308 cfg.group_ops_bls12381_g1_msm_base_cost = Some(62648);
3309 cfg.group_ops_bls12381_g2_msm_base_cost = Some(131192);
3310 cfg.group_ops_bls12381_g1_msm_base_cost_per_input = Some(1333);
3311 cfg.group_ops_bls12381_g2_msm_base_cost_per_input = Some(3216);
3312
3313 cfg.group_ops_bls12381_uncompressed_g1_to_g1_cost = Some(677);
3314 cfg.group_ops_bls12381_g1_to_uncompressed_g1_cost = Some(2099);
3315 cfg.group_ops_bls12381_uncompressed_g1_sum_base_cost = Some(77);
3316 cfg.group_ops_bls12381_uncompressed_g1_sum_cost_per_term = Some(26);
3317 cfg.group_ops_bls12381_uncompressed_g1_sum_max_terms = Some(1200);
3318
3319 cfg.group_ops_bls12381_pairing_cost = Some(26897);
3320
3321 cfg.validator_validate_metadata_cost_base = Some(20000);
3322
3323 cfg.max_committee_members_count = Some(50);
3324 }
3325 6 => {
3326 cfg.max_ptb_value_size = Some(1024 * 1024);
3327 }
3328 7 => {
3329 // version 7 is a new framework version but with no config
3330 // changes
3331 }
3332 8 => {
3333 cfg.feature_flags.variant_nodes = true;
3334
3335 if chain != Chain::Mainnet {
3336 // Enable round prober in consensus.
3337 cfg.feature_flags.consensus_round_prober = true;
3338 // Enable distributed vote scoring.
3339 cfg.feature_flags
3340 .consensus_distributed_vote_scoring_strategy = true;
3341 cfg.feature_flags.consensus_linearize_subdag_v2 = true;
3342 // Enable smart ancestor selection for testnet
3343 cfg.feature_flags.consensus_smart_ancestor_selection = true;
3344 // Enable probing for accepted rounds in round prober for testnet
3345 cfg.feature_flags
3346 .consensus_round_prober_probe_accepted_rounds = true;
3347 // Enable zstd compression for consensus in testnet
3348 cfg.feature_flags.consensus_zstd_compression = true;
3349 // Assuming a round rate of max 15/sec, then using a gc depth of 60 allow
3350 // blocks within a window of ~4 seconds
3351 // to be included before be considered garbage collected.
3352 cfg.consensus_gc_depth = Some(60);
3353 }
3354
3355 // Enable min_free_execution_slot for the shared object congestion tracker in
3356 // devnet.
3357 if chain != Chain::Testnet && chain != Chain::Mainnet {
3358 cfg.feature_flags.congestion_control_min_free_execution_slot = true;
3359 }
3360 }
3361 9 => {
3362 if chain != Chain::Mainnet {
3363 // Disable smart ancestor selection in the testnet and devnet.
3364 cfg.feature_flags.consensus_smart_ancestor_selection = false;
3365 }
3366
3367 // Enable zstd compression for consensus
3368 cfg.feature_flags.consensus_zstd_compression = true;
3369
3370 // Enable passkey in multisig in devnet.
3371 if chain != Chain::Testnet && chain != Chain::Mainnet {
3372 cfg.feature_flags.accept_passkey_in_multisig = true;
3373 }
3374
3375 // this flag is now deprecated because of the bridge removal.
3376 cfg.bridge_should_try_to_finalize_committee = None;
3377 }
3378 10 => {
3379 // Enable min_free_execution_slot for the shared object congestion tracker in
3380 // all networks.
3381 cfg.feature_flags.congestion_control_min_free_execution_slot = true;
3382
3383 // Increase the committee size to 80 on all networks.
3384 cfg.max_committee_members_count = Some(80);
3385
3386 // Enable round prober in consensus.
3387 cfg.feature_flags.consensus_round_prober = true;
3388 // Enable probing for accepted rounds in round.
3389 cfg.feature_flags
3390 .consensus_round_prober_probe_accepted_rounds = true;
3391 // Enable distributed vote scoring.
3392 cfg.feature_flags
3393 .consensus_distributed_vote_scoring_strategy = true;
3394 // Enable the new consensus commit rule.
3395 cfg.feature_flags.consensus_linearize_subdag_v2 = true;
3396
3397 // Enable consensus garbage collection
3398 // Assuming a round rate of max 15/sec, then using a gc depth of 60 allow
3399 // blocks within a window of ~4 seconds
3400 // to be included before be considered garbage collected.
3401 cfg.consensus_gc_depth = Some(60);
3402
3403 // Enable minimized child object mutation counting.
3404 cfg.feature_flags.minimize_child_object_mutations = true;
3405
3406 if chain != Chain::Mainnet {
3407 // Enable batched block sync in devnet and testnet.
3408 cfg.feature_flags.consensus_batched_block_sync = true;
3409 }
3410
3411 if chain != Chain::Testnet && chain != Chain::Mainnet {
3412 // Enable the gas price feedback mechanism (which is used for
3413 // transactions cancelled due to shared object congestion) in devnet
3414 cfg.feature_flags
3415 .congestion_control_gas_price_feedback_mechanism = true;
3416 }
3417
3418 cfg.feature_flags.validate_identifier_inputs = true;
3419 cfg.feature_flags.dependency_linkage_error = true;
3420 cfg.feature_flags.additional_multisig_checks = true;
3421 }
3422 11 => {
3423 // version 11 is a new framework version but with no config
3424 // changes
3425 }
3426 12 => {
3427 // Enable the gas price feedback mechanism for transactions
3428 // cancelled due to congestion in all networks
3429 cfg.feature_flags
3430 .congestion_control_gas_price_feedback_mechanism = true;
3431
3432 // Enable normalization of PTB arguments in all networks.
3433 cfg.feature_flags.normalize_ptb_arguments = true;
3434 }
3435 13 => {
3436 // Enable selecting committee based on eligible active validators on all
3437 // networks.
3438 cfg.feature_flags.select_committee_from_eligible_validators = true;
3439 // Enable tracking non-committee eligible active
3440 // validators on all networks.
3441 cfg.feature_flags.track_non_committee_eligible_validators = true;
3442
3443 if chain != Chain::Testnet && chain != Chain::Mainnet {
3444 // Enable selecting committee only from active validators that next epoch
3445 // version and issued valid AuthorityCapabilities notification in devnet.
3446 cfg.feature_flags
3447 .select_committee_supporting_next_epoch_version = true;
3448 }
3449 }
3450 14 => {
3451 // Enable batched block sync for mainnet.
3452 cfg.feature_flags.consensus_batched_block_sync = true;
3453
3454 if chain != Chain::Mainnet {
3455 // Enable median-based commit timestamp calculation in consensus and
3456 // enforce checkpoint timestamp monotonicity for testnet.
3457 cfg.feature_flags
3458 .consensus_median_timestamp_with_checkpoint_enforcement = true;
3459 // Enable selecting committee only from active validators that support the
3460 // next epoch's version and issued valid AuthorityCapabilities notification
3461 // in testnet.
3462 cfg.feature_flags
3463 .select_committee_supporting_next_epoch_version = true;
3464 }
3465 if chain != Chain::Testnet && chain != Chain::Mainnet {
3466 // Switch consensus protocol to Starfish in devnet
3467 cfg.feature_flags.consensus_choice = ConsensusChoice::Starfish;
3468 }
3469 }
3470 15 => {
3471 if chain != Chain::Mainnet && chain != Chain::Testnet {
3472 // Enable overshoot of 100 in congestion control. This allows bursts of
3473 // shared object transactions up to 10 times the average allowable
3474 // load set by `max_accumulated_txn_cost_per_object_in_mysticeti_commit`.
3475 cfg.max_congestion_limit_overshoot_per_commit = Some(100);
3476 }
3477 }
3478 16 => {
3479 // Enable selecting committee only from active validators that support the
3480 // next epoch's version and issued valid AuthorityCapabilities notification.
3481 cfg.feature_flags
3482 .select_committee_supporting_next_epoch_version = true;
3483 // Enable committing transactions only for traversed headers in Starfish
3484 cfg.feature_flags
3485 .consensus_commit_transactions_only_for_traversed_headers = true;
3486 }
3487 17 => {
3488 // Increase the committee size to 100 on all networks.
3489 cfg.max_committee_members_count = Some(100);
3490 }
3491 18 => {
3492 if chain != Chain::Mainnet {
3493 // Enable passkey authentication support in testnet.
3494 cfg.feature_flags.passkey_auth = true;
3495 }
3496 }
3497 19 => {
3498 if chain != Chain::Testnet && chain != Chain::Mainnet {
3499 // Enable congestion limit overshoot in the gas price feedback
3500 // mechanism on devnet.
3501 cfg.feature_flags
3502 .congestion_limit_overshoot_in_gas_price_feedback_mechanism = true;
3503 // Enable a separate gas price feedback mechanism for transactions using
3504 // randomness on devnet.
3505 cfg.feature_flags
3506 .separate_gas_price_feedback_mechanism_for_randomness = true;
3507 // Enable storing metadata in module bytes and then
3508 // publishing package metadata in devnet
3509 cfg.feature_flags.metadata_in_module_bytes = true;
3510 cfg.feature_flags.publish_package_metadata = true;
3511 // Enable Move authentication in devnet
3512 cfg.feature_flags.enable_move_authentication = true;
3513 // Max auth gas budget is in NANOS and an absolute value 0.25 IOTA
3514 cfg.max_auth_gas = Some(250_000_000);
3515 // Increase the base cost for transfer receive object in devnet, since the
3516 // implementation now does check if parent is not an account.
3517 cfg.transfer_receive_object_cost_base = Some(100);
3518 // Enable adjustment of validator rewards based on score in devnet.
3519 cfg.feature_flags.adjust_rewards_by_score = true;
3520 }
3521
3522 if chain != Chain::Mainnet {
3523 // Switch consensus protocol to Starfish in testnet.
3524 cfg.feature_flags.consensus_choice = ConsensusChoice::Starfish;
3525
3526 // Enable validator score calculation on testnet
3527 cfg.feature_flags.calculate_validator_scores = true;
3528 cfg.scorer_version = Some(1);
3529 }
3530
3531 // Change epoch transaction will contain validator scores
3532 cfg.feature_flags.pass_validator_scores_to_advance_epoch = true;
3533
3534 // Enable passkey authentication support in mainnet
3535 cfg.feature_flags.passkey_auth = true;
3536 }
3537 20 => {
3538 if chain != Chain::Testnet && chain != Chain::Mainnet {
3539 // Passes the calculated validator scores to advance epoch only on Devnet
3540 cfg.feature_flags
3541 .pass_calculated_validator_scores_to_advance_epoch = true;
3542 }
3543 }
3544 21 => {
3545 if chain != Chain::Testnet && chain != Chain::Mainnet {
3546 // Enable fast commit syncer for faster recovery in devnet.
3547 cfg.feature_flags.consensus_fast_commit_sync = true;
3548 }
3549 if chain != Chain::Mainnet {
3550 // Enable overshoot of 100 in congestion control on testnet.
3551 // This allows bursts of shared-object transactions
3552 // up to 10 times the average allowable load set by
3553 // `max_accumulated_txn_cost_per_object_in_mysticeti_commit`.
3554 cfg.max_congestion_limit_overshoot_per_commit = Some(100);
3555 // Enable congestion limit overshoot in the gas price feedback
3556 // mechanism on testnet.
3557 cfg.feature_flags
3558 .congestion_limit_overshoot_in_gas_price_feedback_mechanism = true;
3559 // Enable a separate gas price feedback mechanism for transactions using
3560 // randomness on testnet.
3561 cfg.feature_flags
3562 .separate_gas_price_feedback_mechanism_for_randomness = true;
3563 }
3564
3565 cfg.auth_context_digest_cost_base = Some(30);
3566 cfg.auth_context_tx_commands_cost_base = Some(30);
3567 cfg.auth_context_tx_commands_cost_per_byte = Some(2);
3568 cfg.auth_context_tx_inputs_cost_base = Some(30);
3569 cfg.auth_context_tx_inputs_cost_per_byte = Some(2);
3570 cfg.auth_context_replace_cost_base = Some(30);
3571 cfg.auth_context_replace_cost_per_byte = Some(2);
3572
3573 if chain != Chain::Testnet && chain != Chain::Mainnet {
3574 // Decrease max_auth_gas to 0.00025 IOTA
3575 cfg.max_auth_gas = Some(250_000);
3576 }
3577 }
3578 22 => {
3579 // Enable overshoot of 100 in congestion control on all networks.
3580 // This allows bursts of shared-object transactions
3581 // up to 10 times the average allowable load set by
3582 // `max_accumulated_txn_cost_per_object_in_mysticeti_commit`.
3583 cfg.max_congestion_limit_overshoot_per_commit = Some(100);
3584 // Enable congestion limit overshoot in the gas price feedback
3585 // mechanism on all networks.
3586 cfg.feature_flags
3587 .congestion_limit_overshoot_in_gas_price_feedback_mechanism = true;
3588 // Enable a separate gas price feedback mechanism for transactions using
3589 // randomness on all networks.
3590 cfg.feature_flags
3591 .separate_gas_price_feedback_mechanism_for_randomness = true;
3592
3593 if chain != Chain::Mainnet {
3594 // Enable storing metadata in module bytes and then
3595 // publishing package metadata in testnet
3596 cfg.feature_flags.metadata_in_module_bytes = true;
3597 cfg.feature_flags.publish_package_metadata = true;
3598 // Enable Move authentication in testnet
3599 cfg.feature_flags.enable_move_authentication = true;
3600 // Max_auth_gas is 0.00025 IOTA
3601 cfg.max_auth_gas = Some(250_000);
3602 // Increase the base cost for transfer receive object in testnet, since the
3603 // implementation now does check if parent is not an account.
3604 cfg.transfer_receive_object_cost_base = Some(100);
3605 }
3606
3607 if chain != Chain::Mainnet {
3608 // Enable fast commit syncer for faster recovery on testnet.
3609 cfg.feature_flags.consensus_fast_commit_sync = true;
3610 }
3611 }
3612 23 => {
3613 // Enable Move native context (TxContext via native functions) in all networks.
3614 cfg.feature_flags.move_native_tx_context = true;
3615 cfg.tx_context_fresh_id_cost_base = Some(52);
3616 cfg.tx_context_sender_cost_base = Some(30);
3617 cfg.tx_context_digest_cost_base = Some(30);
3618 cfg.tx_context_epoch_cost_base = Some(30);
3619 cfg.tx_context_epoch_timestamp_ms_cost_base = Some(30);
3620 cfg.tx_context_sponsor_cost_base = Some(30);
3621 cfg.tx_context_rgp_cost_base = Some(30);
3622 cfg.tx_context_gas_price_cost_base = Some(30);
3623 cfg.tx_context_gas_budget_cost_base = Some(30);
3624 cfg.tx_context_ids_created_cost_base = Some(30);
3625 cfg.tx_context_replace_cost_base = Some(30);
3626 }
3627 24 => {
3628 // Switch consensus protocol to Starfish in all networks.
3629 cfg.feature_flags.consensus_choice = ConsensusChoice::Starfish;
3630
3631 if chain != Chain::Testnet && chain != Chain::Mainnet {
3632 // Enable Move-based sponsor account authentication in devnet.
3633 cfg.feature_flags.enable_move_authentication_for_sponsor = true;
3634 }
3635
3636 // Add tx_data_bytes to AuthContext for intent-based signature
3637 // verification in account abstraction.
3638 cfg.auth_context_tx_data_bytes_cost_base = Some(30);
3639 cfg.auth_context_tx_data_bytes_cost_per_byte = Some(2);
3640
3641 // Enable additional borrow checks.
3642 cfg.feature_flags.additional_borrow_checks = true;
3643 }
3644 #[allow(deprecated)]
3645 25 => {
3646 // Deprecate zkLogin related parameters since zkLogin is deprecated and was
3647 // never enabled on IOTA.
3648 cfg.feature_flags.zklogin_max_epoch_upper_bound_delta = None;
3649 cfg.check_zklogin_id_cost_base = None;
3650 cfg.check_zklogin_issuer_cost_base = None;
3651 cfg.max_jwk_votes_per_validator_per_epoch = None;
3652 cfg.max_age_of_jwk_in_epochs = None;
3653 }
3654 26 => {
3655 // Introduce a module to allow Move code to query protocol
3656 // feature flags at runtime.
3657 }
3658 27 => {
3659 if chain != Chain::Mainnet {
3660 // Enable consensus block restrictions on testnet/devnet to bound
3661 // header size by committee size.
3662 cfg.feature_flags.consensus_block_restrictions = true;
3663 }
3664
3665 if chain != Chain::Testnet && chain != Chain::Mainnet {
3666 // Only sponsor Move authentication is performed pre-consensus in devnet.
3667 cfg.feature_flags
3668 .pre_consensus_sponsor_only_move_authentication = true;
3669 }
3670 }
3671 28 => {
3672 // AuthenticatorFunctionInfoV1 max BCS size:
3673 // package (32) + module_name (128) + function_name (128) = 288 bytes = 9 ×
3674 // digest. auth_context_digest_cost_base = 30 for 32 bytes →
3675 // 9 × 30 = 270.
3676 cfg.auth_context_authenticator_function_info_v1_cost_base = Some(270);
3677
3678 // Enable storing metadata in module bytes and then
3679 // publishing package metadata in mainnet.
3680 cfg.feature_flags.metadata_in_module_bytes = true;
3681 cfg.feature_flags.publish_package_metadata = true;
3682 // Enable Move authentication in mainnet.
3683 cfg.feature_flags.enable_move_authentication = true;
3684 // Increase the base cost for transfer receive object in mainnet, since the
3685 // implementation now does check if parent is not an account.
3686 cfg.transfer_receive_object_cost_base = Some(100);
3687
3688 if chain != Chain::Unknown {
3689 // max_auth_gas is 0.00002 IOTA in testnet and mainnet.
3690 cfg.max_auth_gas = Some(20_000);
3691 }
3692
3693 if chain != Chain::Mainnet {
3694 // Enable Move-based sponsor account authentication in testnet.
3695 cfg.feature_flags.enable_move_authentication_for_sponsor = true;
3696 // Only sponsor Move authentication is performed pre-consensus in testnet.
3697 cfg.feature_flags
3698 .pre_consensus_sponsor_only_move_authentication = true;
3699 }
3700 }
3701 29 => {
3702 // Keep advancing the random beacon DKG state machine on every commit
3703 // while it is still pending so DKG resolves from persisted state
3704 // (completing, or failing once the timeout round passes) even with no
3705 // fresh inbound traffic -- e.g. after a validator restart -- instead of
3706 // staying pending forever and blocking epoch close.
3707 cfg.feature_flags.always_advance_dkg_to_resolution = true;
3708
3709 // Enable median-based commit timestamp calculation in consensus and
3710 // enforce checkpoint timestamp monotonicity for mainnet.
3711 cfg.feature_flags
3712 .consensus_median_timestamp_with_checkpoint_enforcement = true;
3713
3714 // Enable fast commit syncer for faster recovery on all networks.
3715 cfg.feature_flags.consensus_fast_commit_sync = true;
3716 // Enable consensus block restrictions on all networks to bound
3717 // header size by committee size and garbage-collect the block
3718 // manager.
3719 cfg.feature_flags.consensus_block_restrictions = true;
3720 }
3721 30 => {
3722 // Extend the protocol_config framework module with
3723 // `get_attr<T>`, a generic native that lets Move code
3724 // read any numeric or boolean protocol parameter by name,
3725 // returning T directly and aborting on error.
3726 // Also expose `is_feature_enabled` and `get_attr<T>` to
3727 // iota_system via a new iota_system::protocol_config
3728 // module.
3729 }
3730 31 => {
3731 cfg.feature_flags.validator_metadata_verify_v2 = true;
3732
3733 if chain != Chain::Mainnet && chain != Chain::Testnet {
3734 // Amortize the minimum checkpoint interval over a sliding
3735 // window so the checkpoint rate holds at the ceiling.
3736 cfg.checkpoint_rate_window_size = Some(20);
3737 // Publish package metadata with the module metadata stored as a
3738 // dynamic field.
3739 cfg.feature_flags
3740 .package_metadata_with_dynamic_module_metadata = true;
3741 // Enable the optimistic commit rule (StarfishSpeed) in
3742 // Starfish consensus.
3743 cfg.feature_flags.consensus_starfish_speed = true;
3744 }
3745
3746 cfg.feature_flags.report_move_authentication_error = true;
3747 }
3748 32 => {
3749 // Identical to the genesis SystemParametersV1 values on
3750 // all existing networks; enforcement moves from on-chain
3751 // state to the protocol config.
3752 cfg.min_validator_count = Some(4);
3753 cfg.max_validator_count = Some(150);
3754 cfg.min_validator_joining_stake = Some(2_000_000_000_000_000);
3755 cfg.validator_low_stake_threshold = Some(1_500_000_000_000_000);
3756 cfg.validator_very_low_stake_threshold = Some(1_000_000_000_000_000);
3757 cfg.validator_low_stake_grace_period = Some(7);
3758
3759 // Enable Move-based sponsor account authentication in mainnet.
3760 cfg.feature_flags.enable_move_authentication_for_sponsor = true;
3761 // Only sponsor Move authentication is performed pre-consensus in mainnet.
3762 cfg.feature_flags
3763 .pre_consensus_sponsor_only_move_authentication = true;
3764
3765 if chain != Chain::Mainnet {
3766 // Enable the optimistic commit rule (StarfishSpeed) in
3767 // Starfish consensus.
3768 cfg.feature_flags.consensus_starfish_speed = true;
3769 // Amortize the minimum checkpoint interval over a sliding
3770 // window so the checkpoint rate holds at the ceiling.
3771 cfg.checkpoint_rate_window_size = Some(20);
3772 // Publish package metadata with the module metadata stored as a
3773 // dynamic field.
3774 cfg.feature_flags
3775 .package_metadata_with_dynamic_module_metadata = true;
3776 }
3777
3778 if chain != Chain::Mainnet && chain != Chain::Testnet {
3779 // Enable the redesigned leader schedule: sliding-window
3780 // reputation scoring and absolute-score bad-node
3781 // selection.
3782 cfg.feature_flags
3783 .consensus_enable_sliding_window_leader_schedule = true;
3784 cfg.feature_flags
3785 .consensus_enable_absolute_score_leader_schedule = true;
3786 // Enable the P-COOL flow: transactions skip
3787 // pre-consensus certification and owned-object locking,
3788 // and conflicts are resolved after consensus.
3789 cfg.feature_flags.enable_pcool_flow = true;
3790 }
3791 }
3792 33 => {
3793 // Amortize the minimum checkpoint interval over a sliding
3794 // window so the checkpoint rate holds at the ceiling.
3795 cfg.checkpoint_rate_window_size = Some(20);
3796 // Enable the redesigned leader schedule: sliding-window
3797 // reputation scoring and absolute-score bad-node
3798 // selection.
3799 if chain != Chain::Mainnet {
3800 cfg.feature_flags
3801 .consensus_enable_sliding_window_leader_schedule = true;
3802 cfg.feature_flags
3803 .consensus_enable_absolute_score_leader_schedule = true;
3804 }
3805 }
3806 34 => {
3807 if chain != Chain::Testnet && chain != Chain::Mainnet {
3808 // Misbehavior reports carry a dedicated counter for
3809 // invalid bundle parts, previously folded into the
3810 // unprovable block-fault counter.
3811 cfg.scorer_version = Some(2);
3812 }
3813 // Stop locking immutable objects in post-consensus conflict
3814 // resolution. Set on all chains; inert where the P-COOL flow
3815 // is off.
3816 cfg.feature_flags.pcool_skip_immutable_object_locks = true;
3817
3818 if chain == Chain::Mainnet {
3819 // Disable Move-based sponsor account authentication.
3820 cfg.feature_flags.enable_move_authentication_for_sponsor = false;
3821 // The pre-consensus sponsor-only flag requires
3822 // `enable_move_authentication_for_sponsor`, so clear it too.
3823 cfg.feature_flags
3824 .pre_consensus_sponsor_only_move_authentication = false;
3825 }
3826 }
3827 35 => {
3828 // Scale the PTB value size limit by the value's type.
3829 cfg.feature_flags.max_ptb_value_size_v2 = true;
3830 // Let system objects grow past the per-object size bound.
3831 cfg.feature_flags.allow_unbounded_system_objects = true;
3832
3833 // Enable the optimistic commit rule (StarfishSpeed) in
3834 // Starfish consensus.
3835 cfg.feature_flags.consensus_starfish_speed = true;
3836
3837 // Post-consensus validation meters published packages with
3838 // the limits below instead of each validator's own
3839 // `VerifierSigningConfig`. The values are that config's
3840 // defaults, so a validator that leaves it alone reaches
3841 // the same result at admission and post-consensus. Set on
3842 // all chains; inert where the P-COOL flow is off.
3843 cfg.max_verifier_meter_ticks_per_function = Some(2_200_000);
3844 cfg.max_meter_ticks_per_module = Some(2_200_000);
3845 cfg.max_meter_ticks_per_package = Some(2_200_000);
3846 cfg.max_meter_ticks_regex_reference_safety = Some(2_200_000);
3847 cfg.feature_flags.pcool_verifier_limits_from_protocol_config = true;
3848 // Publish package metadata with the module metadata stored as a
3849 // dynamic field.
3850 cfg.feature_flags
3851 .package_metadata_with_dynamic_module_metadata = true;
3852 // Enable the redesigned leader schedule: sliding-window
3853 // reputation scoring and absolute-score bad-node
3854 // selection.
3855 cfg.feature_flags
3856 .consensus_enable_sliding_window_leader_schedule = true;
3857 cfg.feature_flags
3858 .consensus_enable_absolute_score_leader_schedule = true;
3859
3860 // Enable Move-based sponsor account authentication on all
3861 // networks.
3862 cfg.feature_flags.enable_move_authentication_for_sponsor = true;
3863 // Run every `MoveAuthenticator` pre-consensus again, not
3864 // just the sponsor's, on all networks.
3865 cfg.feature_flags
3866 .pre_consensus_sponsor_only_move_authentication = false;
3867 }
3868 36 => {
3869 // No immutable account object can authenticate a sender or
3870 // a sponsor.
3871 cfg.feature_flags.reject_immutable_account_objects = true;
3872 }
3873 37 => {
3874 // Refuse object versions in, or right below, the range
3875 // assigned to canceled transactions before any object is
3876 // loaded, by consulting the transaction bytes only.
3877 cfg.feature_flags.validate_input_object_versions = true;
3878 cfg.feature_flags.disallow_self_identifier = true;
3879 cfg.max_move_enum_variants = Some(move_core_types::VARIANT_COUNT_MAX);
3880 // Apply the package deny list to the package that holds a
3881 // `MoveAuthenticator`'s authenticate function.
3882 cfg.feature_flags.deny_authenticator_packages = true;
3883 // Require a published module header to carry the canonical
3884 // encoding of its binary format version.
3885 cfg.feature_flags.check_canonical_module_version_header = true;
3886 // An authenticate function cannot read randomness, so the
3887 // randomness state object is refused as an authenticator
3888 // input instead of scheduling the transaction as
3889 // randomness-using for nothing.
3890 cfg.feature_flags.disallow_randomness_in_move_authenticator = true;
3891 // Traverse the module graph when checking for cyclic
3892 // dependencies.
3893 cfg.feature_flags.check_cyclic_dependencies = true;
3894 }
3895 38 => {
3896 // A system package is published by the network, not by a
3897 // user, so the user-package bound was never meant to apply
3898 // to it: an existing system package is already exempt when
3899 // it is upgraded at an epoch change, and only a first
3900 // publish (genesis, or a newly added system package) is
3901 // checked against it.
3902 cfg.max_move_system_package_size = Some(200 * 1024);
3903 // An immutable account object cannot authenticate anything
3904 // since version 36, so stop creating new ones.
3905 cfg.feature_flags.reject_immutable_account_creation = true;
3906
3907 cfg.feature_flags.validate_ptb_argument_indices = true;
3908 }
3909 39 => {
3910 // Keep random beacon DKG running after its timeout round, so
3911 // randomness is enabled again mid-epoch if DKG completes late.
3912 if chain != Chain::Mainnet {
3913 cfg.feature_flags.allow_dkg_completion_after_timeout = true;
3914 }
3915 cfg.feature_flags.consensus_dedup_only_recorded_messages = true;
3916
3917 // Raise the minimum validator joining stake to 6M IOTA, the low
3918 // stake threshold to 5.5M IOTA and the very low stake threshold to
3919 // 5M IOTA on all chains.
3920 cfg.min_validator_joining_stake = Some(6_000_000_000_000_000);
3921 cfg.validator_low_stake_threshold = Some(5_500_000_000_000_000);
3922 cfg.validator_very_low_stake_threshold = Some(5_000_000_000_000_000);
3923
3924 // Reject a multisig whose committee mixes Ed25519 with other key
3925 // schemes unless every committee member has signed.
3926 cfg.feature_flags
3927 .reject_partially_signed_mixed_ed25519_multisig = true;
3928
3929 if chain != Chain::Mainnet && chain != Chain::Testnet {
3930 // Post-consensus validation reads object state as of
3931 // 4 commits below the one it validates.
3932 cfg.pcool_deterministic_validation_horizon_distance = Some(4);
3933 // Mirror the governed deny rules into the on-chain
3934 // object in chunks of at most 1000 entries.
3935 cfg.deny_rule_update_max_entries_per_tx = Some(1000);
3936 }
3937
3938 // Reject Groth16 verifying keys whose size does not match the
3939 // number of public inputs before deserializing them.
3940 cfg.feature_flags.limit_groth16_pvk_inputs = true;
3941 cfg.feature_flags.check_groth16_pvk_length = true;
3942
3943 // At execution too, not only at signing: reject the
3944 // deprecated global storage instructions and non-empty
3945 // `acquires` lists when deserializing a module, and verify
3946 // modules without the acquires pass and with vector element
3947 // borrows checked by the call rule.
3948 cfg.feature_flags.deprecate_global_storage_ops = true;
3949 }
3950 40 => {
3951 // Post-consensus validation meters the instantiation-loop
3952 // check and caps its graph with these values, which signing
3953 // also uses.
3954 cfg.feature_flags.meter_instantiation_loops = true;
3955 cfg.max_instantiation_loop_graph_edges = Some(100_000);
3956
3957 // Make the packages named by a `MoveAuthenticator`'s type
3958 // arguments inputs of that authenticator.
3959 cfg.feature_flags
3960 .move_authenticator_type_arg_packages_as_inputs = true;
3961
3962 // Limit the struct, enum and vector values in Move-call
3963 // arguments.
3964 cfg.max_move_call_argument_nodes = Some(2_097_152);
3965 cfg.max_move_call_argument_nodes_total = Some(16_777_216);
3966
3967 // Reject `<SELF>` as an identifier in transactions, at
3968 // signing, after consensus and in block verification.
3969 cfg.feature_flags.disallow_self_identifier_in_transactions = true;
3970
3971 // Update the gas model version.
3972 cfg.gas_model_version = Some(3);
3973
3974 if chain != Chain::Mainnet && chain != Chain::Testnet {
3975 // Validators attest the user transactions they propose,
3976 // and the checkpoint summary certifies the verdicts.
3977 cfg.feature_flags.enable_validator_attestation = true;
3978 cfg.checkpoint_summary_version_specific_data = Some(2);
3979 }
3980 }
3981 41 => {
3982 // Commit a block's transactions once its header is
3983 // traversed, also when their acknowledgment quorum came
3984 // first.
3985 if chain != Chain::Mainnet {
3986 cfg.feature_flags
3987 .consensus_commit_transactions_once_traversed = true;
3988 }
3989
3990 // `ecdsa_r1::secp256r1_ecrecover` rejects a signature
3991 // whose restored x-coordinate is not below the field
3992 // modulus.
3993 cfg.feature_flags.secp256r1_ecrecover_checks_x_below_p = true;
3994 }
3995 // Use this template when making changes:
3996 //
3997 // // modify an existing constant.
3998 // move_binary_format_version: Some(7),
3999 //
4000 // // Add a new constant (which is set to None in prior versions).
4001 // new_constant: Some(new_value),
4002 //
4003 // // Remove a constant (ensure that it is never accessed during this version).
4004 // max_move_object_size: None,
4005 _ => panic!("unsupported version {version:?}"),
4006 }
4007 }
4008 cfg
4009 }
4010
4011 // Extract the bytecode verifier config from this protocol config.
4012 // If used during signing, `signing_limits` should be set.
4013 // The third limit configures`sanity_check_with_regex_reference_safety`,
4014 // which runs the new regex-based reference safety check to check that it is
4015 // strictly more permissive than the current implementation.
4016 pub fn verifier_config(&self, signing_limits: Option<(usize, usize, usize)>) -> VerifierConfig {
4017 let (
4018 max_back_edges_per_function,
4019 max_back_edges_per_module,
4020 sanity_check_with_regex_reference_safety,
4021 ) = if let Some((
4022 max_back_edges_per_function,
4023 max_back_edges_per_module,
4024 sanity_check_with_regex_reference_safety,
4025 )) = signing_limits
4026 {
4027 (
4028 Some(max_back_edges_per_function),
4029 Some(max_back_edges_per_module),
4030 Some(sanity_check_with_regex_reference_safety),
4031 )
4032 } else {
4033 (None, None, None)
4034 };
4035
4036 let additional_borrow_checks = if signing_limits.is_some() {
4037 // Always apply additional borrow checks during signing regardless of
4038 // protocol version, to prevent accepting potentially unsafe bytecode.
4039 true
4040 } else {
4041 self.additional_borrow_checks()
4042 };
4043 let deprecate_global_storage_ops = if signing_limits.is_some() {
4044 // Always on during signing, regardless of protocol version: reject
4045 // the deprecated global storage instructions, skip the acquires
4046 // pass and check vector element borrows with the call rule.
4047 true
4048 } else {
4049 self.deprecate_global_storage_ops()
4050 };
4051
4052 // Far above the largest instantiation-loop graph in the system packages
4053 // and examples.
4054 const MAX_INSTANTIATION_LOOP_GRAPH_EDGES_AT_SIGNING: usize = 100_000;
4055
4056 // Applied with the signing limits only: execution verifies without a
4057 // meter. Both fail with PROGRAM_TOO_COMPLEX, which signing rejects.
4058 // Post-consensus validation takes them from the protocol config, see
4059 // `post_consensus_verifier_config`.
4060 let (meter_instantiation_loops, max_instantiation_loop_graph_edges) =
4061 if signing_limits.is_some() {
4062 (true, Some(MAX_INSTANTIATION_LOOP_GRAPH_EDGES_AT_SIGNING))
4063 } else {
4064 (false, None)
4065 };
4066
4067 VerifierConfig {
4068 max_loop_depth: Some(self.max_loop_depth() as usize),
4069 max_generic_instantiation_length: Some(self.max_generic_instantiation_length() as usize),
4070 max_function_parameters: Some(self.max_function_parameters() as usize),
4071 max_basic_blocks: Some(self.max_basic_blocks() as usize),
4072 max_value_stack_size: self.max_value_stack_size() as usize,
4073 max_type_nodes: Some(self.max_type_nodes() as usize),
4074 max_push_size: Some(self.max_push_size() as usize),
4075 max_dependency_depth: Some(self.max_dependency_depth() as usize),
4076 max_fields_in_struct: Some(self.max_fields_in_struct() as usize),
4077 max_function_definitions: Some(self.max_function_definitions() as usize),
4078 max_data_definitions: Some(self.max_struct_definitions() as usize),
4079 max_constant_vector_len: Some(self.max_move_vector_len()),
4080 max_back_edges_per_function,
4081 max_back_edges_per_module,
4082 max_basic_blocks_in_script: None,
4083 max_identifier_len: self.max_move_identifier_len_as_option(), /* Before protocol
4084 * version 9, there was
4085 * no limit */
4086 disallow_self_identifier: self.feature_flags.disallow_self_identifier,
4087 bytecode_version: self.move_binary_format_version(),
4088 max_variants_in_enum: self.max_move_enum_variants_as_option(),
4089 additional_borrow_checks,
4090 sanity_check_with_regex_reference_safety: sanity_check_with_regex_reference_safety
4091 .map(|limit| limit as u128),
4092 check_cyclic_dependencies: self.feature_flags.check_cyclic_dependencies,
4093 meter_instantiation_loops,
4094 max_instantiation_loop_graph_edges,
4095 deprecate_global_storage_ops,
4096 }
4097 }
4098
4099 /// The bytecode verifier config for post-consensus validation: the
4100 /// protocol's sign-time limits, with `deprecate_global_storage_ops`, the
4101 /// instantiation-loop graph edge limit and the metering of that check
4102 /// taken from the protocol config rather than set as at signing.
4103 ///
4104 /// # Panics
4105 ///
4106 /// Panics before protocol version 35, which has no
4107 /// `max_meter_ticks_regex_reference_safety`.
4108 pub fn post_consensus_verifier_config(&self) -> VerifierConfig {
4109 // Before protocol version 40, the check is metered and capped at
4110 // 100,000 edges, the values signing used then.
4111 let (meter_instantiation_loops, max_instantiation_loop_graph_edges) =
4112 if self.version < ProtocolVersion::new(40) {
4113 (true, Some(100_000))
4114 } else {
4115 (
4116 self.meter_instantiation_loops(),
4117 self.max_instantiation_loop_graph_edges_as_option()
4118 .map(|edges| edges as usize),
4119 )
4120 };
4121 VerifierConfig {
4122 deprecate_global_storage_ops: self.deprecate_global_storage_ops(),
4123 meter_instantiation_loops,
4124 max_instantiation_loop_graph_edges,
4125 ..self.verifier_config(Some(self.verifier_signing_limits()))
4126 }
4127 }
4128
4129 /// The sign-time verifier limits as protocol parameters, in the shape
4130 /// `verifier_config` takes: back edges per function, back edges per module,
4131 /// and the meter limit of the regex-based reference safety check.
4132 /// `VerifierSigningConfig::limits_for_signing` is the validator-local
4133 /// counterpart. Defined from protocol version 35, which sets
4134 /// `max_meter_ticks_regex_reference_safety`.
4135 pub fn verifier_signing_limits(&self) -> (usize, usize, usize) {
4136 (
4137 self.max_back_edges_per_function() as usize,
4138 self.max_back_edges_per_module() as usize,
4139 self.max_meter_ticks_regex_reference_safety() as usize,
4140 )
4141 }
4142
4143 /// The meter limits for verifying the packages a transaction publishes, as
4144 /// protocol parameters. `VerifierSigningConfig::meter_config_for_signing`
4145 /// is the validator-local counterpart.
4146 pub fn meter_config(&self) -> MeterConfig {
4147 MeterConfig {
4148 max_per_fun_meter_units: Some(self.max_verifier_meter_ticks_per_function() as u128),
4149 max_per_mod_meter_units: Some(self.max_meter_ticks_per_module() as u128),
4150 max_per_pkg_meter_units: Some(self.max_meter_ticks_per_package() as u128),
4151 }
4152 }
4153
4154 /// Override one or more settings in the config, for testing.
4155 /// This must be called at the beginning of the test, before
4156 /// get_for_(min|max)_version is called, since those functions cache
4157 /// their return value.
4158 pub fn apply_overrides_for_testing(
4159 override_fn: impl Fn(ProtocolVersion, Self) -> Self + Send + Sync + 'static,
4160 ) -> OverrideGuard {
4161 CONFIG_OVERRIDE.with(|ovr| {
4162 let mut cur = ovr.borrow_mut();
4163 assert!(cur.is_none(), "config override already present");
4164 *cur = Some(Box::new(override_fn));
4165 OverrideGuard
4166 })
4167 }
4168}
4169
4170// Setters for tests.
4171// This is only needed for feature_flags. Please suffix each setter with
4172// `_for_testing`. Non-feature_flags should already have test setters defined
4173// through macros.
4174impl ProtocolConfig {
4175 pub fn set_per_object_congestion_control_mode_for_testing(
4176 &mut self,
4177 val: PerObjectCongestionControlMode,
4178 ) {
4179 self.feature_flags.per_object_congestion_control_mode = val;
4180 }
4181
4182 pub fn set_consensus_choice_for_testing(&mut self, val: ConsensusChoice) {
4183 self.feature_flags.consensus_choice = val;
4184 }
4185
4186 pub fn set_consensus_network_for_testing(&mut self, val: ConsensusNetwork) {
4187 self.feature_flags.consensus_network = val;
4188 }
4189
4190 pub fn set_passkey_auth_for_testing(&mut self, val: bool) {
4191 self.feature_flags.passkey_auth = val
4192 }
4193
4194 pub fn set_disallow_new_modules_in_deps_only_packages_for_testing(&mut self, val: bool) {
4195 self.feature_flags
4196 .disallow_new_modules_in_deps_only_packages = val;
4197 }
4198
4199 pub fn set_check_canonical_module_version_header_for_testing(&mut self, val: bool) {
4200 self.feature_flags.check_canonical_module_version_header = val;
4201 }
4202
4203 pub fn set_deprecate_global_storage_ops_for_testing(&mut self, val: bool) {
4204 self.feature_flags.deprecate_global_storage_ops = val;
4205 }
4206
4207 pub fn set_meter_instantiation_loops_for_testing(&mut self, val: bool) {
4208 self.feature_flags.meter_instantiation_loops = val;
4209 }
4210
4211 pub fn set_consensus_round_prober_for_testing(&mut self, val: bool) {
4212 self.feature_flags.consensus_round_prober = val;
4213 }
4214
4215 pub fn set_consensus_distributed_vote_scoring_strategy_for_testing(&mut self, val: bool) {
4216 self.feature_flags
4217 .consensus_distributed_vote_scoring_strategy = val;
4218 }
4219
4220 pub fn set_gc_depth_for_testing(&mut self, val: u32) {
4221 self.consensus_gc_depth = Some(val);
4222 }
4223
4224 pub fn set_consensus_linearize_subdag_v2_for_testing(&mut self, val: bool) {
4225 self.feature_flags.consensus_linearize_subdag_v2 = val;
4226 }
4227
4228 pub fn set_consensus_round_prober_probe_accepted_rounds(&mut self, val: bool) {
4229 self.feature_flags
4230 .consensus_round_prober_probe_accepted_rounds = val;
4231 }
4232
4233 pub fn set_accept_passkey_in_multisig_for_testing(&mut self, val: bool) {
4234 self.feature_flags.accept_passkey_in_multisig = val;
4235 }
4236
4237 pub fn set_consensus_smart_ancestor_selection_for_testing(&mut self, val: bool) {
4238 self.feature_flags.consensus_smart_ancestor_selection = val;
4239 }
4240
4241 pub fn set_consensus_batched_block_sync_for_testing(&mut self, val: bool) {
4242 self.feature_flags.consensus_batched_block_sync = val;
4243 }
4244
4245 pub fn set_congestion_control_min_free_execution_slot_for_testing(&mut self, val: bool) {
4246 self.feature_flags
4247 .congestion_control_min_free_execution_slot = val;
4248 }
4249
4250 pub fn set_congestion_control_gas_price_feedback_mechanism_for_testing(&mut self, val: bool) {
4251 self.feature_flags
4252 .congestion_control_gas_price_feedback_mechanism = val;
4253 }
4254
4255 pub fn set_select_committee_from_eligible_validators_for_testing(&mut self, val: bool) {
4256 self.feature_flags.select_committee_from_eligible_validators = val;
4257 }
4258
4259 pub fn set_track_non_committee_eligible_validators_for_testing(&mut self, val: bool) {
4260 self.feature_flags.track_non_committee_eligible_validators = val;
4261 }
4262
4263 pub fn set_select_committee_supporting_next_epoch_version(&mut self, val: bool) {
4264 self.feature_flags
4265 .select_committee_supporting_next_epoch_version = val;
4266 }
4267
4268 pub fn set_consensus_median_timestamp_with_checkpoint_enforcement_for_testing(
4269 &mut self,
4270 val: bool,
4271 ) {
4272 self.feature_flags
4273 .consensus_median_timestamp_with_checkpoint_enforcement = val;
4274 }
4275
4276 pub fn set_consensus_commit_transactions_only_for_traversed_headers_for_testing(
4277 &mut self,
4278 val: bool,
4279 ) {
4280 self.feature_flags
4281 .consensus_commit_transactions_only_for_traversed_headers = val;
4282 }
4283
4284 pub fn set_consensus_commit_transactions_once_traversed_for_testing(&mut self, val: bool) {
4285 self.feature_flags
4286 .consensus_commit_transactions_once_traversed = val;
4287 }
4288
4289 pub fn set_congestion_limit_overshoot_in_gas_price_feedback_mechanism_for_testing(
4290 &mut self,
4291 val: bool,
4292 ) {
4293 self.feature_flags
4294 .congestion_limit_overshoot_in_gas_price_feedback_mechanism = val;
4295 }
4296
4297 pub fn set_separate_gas_price_feedback_mechanism_for_randomness_for_testing(
4298 &mut self,
4299 val: bool,
4300 ) {
4301 self.feature_flags
4302 .separate_gas_price_feedback_mechanism_for_randomness = val;
4303 }
4304
4305 pub fn set_metadata_in_module_bytes_for_testing(&mut self, val: bool) {
4306 self.feature_flags.metadata_in_module_bytes = val;
4307 }
4308
4309 pub fn set_publish_package_metadata_for_testing(&mut self, val: bool) {
4310 self.feature_flags.publish_package_metadata = val;
4311 }
4312
4313 /// Turning Move authentication off also turns off reporting Move
4314 /// authentication errors and validator attestation, which require it.
4315 pub fn set_enable_move_authentication_for_testing(&mut self, val: bool) {
4316 self.feature_flags.enable_move_authentication = val;
4317 if !val {
4318 self.set_report_move_authentication_error_for_testing(false);
4319 self.set_enable_validator_attestation_for_testing(false);
4320 }
4321 }
4322
4323 pub fn set_enable_move_authentication_for_sponsor_for_testing(&mut self, val: bool) {
4324 self.feature_flags.enable_move_authentication_for_sponsor = val;
4325 }
4326
4327 pub fn set_consensus_fast_commit_sync_for_testing(&mut self, val: bool) {
4328 self.feature_flags.consensus_fast_commit_sync = val;
4329 }
4330
4331 pub fn set_consensus_block_restrictions_for_testing(&mut self, val: bool) {
4332 self.feature_flags.consensus_block_restrictions = val;
4333 }
4334
4335 pub fn set_pre_consensus_sponsor_only_move_authentication_for_testing(&mut self, val: bool) {
4336 self.feature_flags
4337 .pre_consensus_sponsor_only_move_authentication = val;
4338 }
4339
4340 pub fn set_consensus_starfish_speed_for_testing(&mut self, val: bool) {
4341 self.feature_flags.consensus_starfish_speed = val;
4342 }
4343
4344 pub fn set_always_advance_dkg_to_resolution_for_testing(&mut self, val: bool) {
4345 self.feature_flags.always_advance_dkg_to_resolution = val;
4346 }
4347
4348 /// Turning the flow on also turns on the flags it requires, turns off
4349 /// `pre_consensus_sponsor_only_move_authentication`, which it excludes, and
4350 /// fills in the settings it requires when unset, whatever the version.
4351 /// Turning the flow off also turns validator attestation off, since
4352 /// attestation cannot run without the flow.
4353 pub fn set_enable_pcool_flow_for_testing(&mut self, val: bool) {
4354 self.feature_flags.enable_pcool_flow = val;
4355 if val {
4356 self.feature_flags
4357 .pre_consensus_sponsor_only_move_authentication = false;
4358 // Post-consensus validation reads this budget; versions before 35
4359 // leave it unset.
4360 self.max_meter_ticks_regex_reference_safety
4361 .get_or_insert(2_200_000);
4362 self.feature_flags.consensus_dedup_only_recorded_messages = true;
4363 self.pcool_deterministic_validation_horizon_distance
4364 .get_or_insert(4);
4365 self.deny_rule_update_max_entries_per_tx.get_or_insert(1000);
4366 } else {
4367 self.set_enable_validator_attestation_for_testing(false);
4368 }
4369 }
4370
4371 pub fn set_reject_immutable_account_objects_for_testing(&mut self, val: bool) {
4372 self.feature_flags.reject_immutable_account_objects = val;
4373 }
4374
4375 pub fn set_reject_immutable_account_creation_for_testing(&mut self, val: bool) {
4376 self.feature_flags.reject_immutable_account_creation = val;
4377 }
4378
4379 pub fn set_validate_input_object_versions_for_testing(&mut self, val: bool) {
4380 self.feature_flags.validate_input_object_versions = val;
4381 }
4382
4383 pub fn set_disallow_randomness_in_move_authenticator_for_testing(&mut self, val: bool) {
4384 self.feature_flags.disallow_randomness_in_move_authenticator = val;
4385 }
4386
4387 pub fn set_move_authenticator_type_arg_packages_as_inputs_for_testing(&mut self, val: bool) {
4388 self.feature_flags
4389 .move_authenticator_type_arg_packages_as_inputs = val;
4390 }
4391
4392 pub fn set_disallow_self_identifier_in_transactions_for_testing(&mut self, val: bool) {
4393 self.feature_flags.disallow_self_identifier_in_transactions = val;
4394 }
4395
4396 pub fn set_commits_per_schedule_for_testing(&mut self, val: u32) {
4397 self.consensus_commits_per_schedule = Some(val);
4398 }
4399
4400 pub fn set_deny_authenticator_packages_for_testing(&mut self, val: bool) {
4401 self.feature_flags.deny_authenticator_packages = val;
4402 }
4403
4404 /// Keeps the config consistent with the getters that assert on this flag:
4405 /// enabling fills in `scorer_version` when unset, disabling also switches
4406 /// off `adjust_rewards_by_score` and
4407 /// `pass_calculated_validator_scores_to_advance_epoch`.
4408 pub fn set_calculate_validator_scores_for_testing(&mut self, val: bool) {
4409 self.feature_flags.calculate_validator_scores = val;
4410 if val {
4411 self.scorer_version.get_or_insert(1);
4412 } else {
4413 self.feature_flags.adjust_rewards_by_score = false;
4414 self.feature_flags
4415 .pass_calculated_validator_scores_to_advance_epoch = false;
4416 }
4417 }
4418
4419 pub fn set_pass_calculated_validator_scores_to_advance_epoch_for_testing(&mut self, val: bool) {
4420 self.feature_flags
4421 .pass_calculated_validator_scores_to_advance_epoch = val;
4422 }
4423
4424 pub fn set_package_metadata_with_dynamic_module_metadata_for_testing(&mut self, val: bool) {
4425 self.feature_flags
4426 .package_metadata_with_dynamic_module_metadata = val;
4427 }
4428
4429 pub fn set_report_move_authentication_error_for_testing(&mut self, val: bool) {
4430 self.feature_flags.report_move_authentication_error = val;
4431 }
4432
4433 pub fn set_leader_schedule_window_size_for_testing(&mut self, val: u32) {
4434 self.consensus_leader_schedule_window_size = Some(val);
4435 }
4436
4437 pub fn set_consensus_enable_sliding_window_leader_schedule_for_testing(&mut self, val: bool) {
4438 self.feature_flags
4439 .consensus_enable_sliding_window_leader_schedule = val;
4440 }
4441
4442 pub fn set_consensus_enable_absolute_score_leader_schedule_for_testing(&mut self, val: bool) {
4443 self.feature_flags
4444 .consensus_enable_absolute_score_leader_schedule = val;
4445 }
4446
4447 pub fn set_allow_dkg_completion_after_timeout_for_testing(&mut self, val: bool) {
4448 self.feature_flags.allow_dkg_completion_after_timeout = val;
4449 }
4450
4451 /// Turning the flag off also turns off `enable_pcool_flow`, which requires
4452 /// it.
4453 pub fn set_consensus_dedup_only_recorded_messages_for_testing(&mut self, val: bool) {
4454 self.feature_flags.consensus_dedup_only_recorded_messages = val;
4455 if !val {
4456 self.set_enable_pcool_flow_for_testing(false);
4457 }
4458 }
4459
4460 pub fn set_enable_validator_attestation_for_testing(&mut self, val: bool) {
4461 self.feature_flags.enable_validator_attestation = val;
4462 }
4463}
4464
4465type OverrideFn = dyn Fn(ProtocolVersion, ProtocolConfig) -> ProtocolConfig + Send + Sync;
4466
4467thread_local! {
4468 static CONFIG_OVERRIDE: RefCell<Option<Box<OverrideFn>>> = const { RefCell::new(None) };
4469}
4470
4471#[must_use]
4472pub struct OverrideGuard;
4473
4474impl Drop for OverrideGuard {
4475 fn drop(&mut self) {
4476 info!("restoring override fn");
4477 CONFIG_OVERRIDE.with(|ovr| {
4478 *ovr.borrow_mut() = None;
4479 });
4480 }
4481}
4482
4483/// Defines which limit got crossed.
4484/// The value which crossed the limit and value of the limit crossed are
4485/// embedded
4486#[derive(PartialEq, Eq)]
4487pub enum LimitThresholdCrossed {
4488 None,
4489 Soft(u128, u128),
4490 Hard(u128, u128),
4491}
4492
4493/// Convenience function for comparing limit ranges
4494/// V::MAX must be at >= U::MAX and T::MAX
4495pub fn check_limit_in_range<T: Into<V>, U: Into<V>, V: PartialOrd + Into<u128>>(
4496 x: T,
4497 soft_limit: U,
4498 hard_limit: V,
4499) -> LimitThresholdCrossed {
4500 let x: V = x.into();
4501 let soft_limit: V = soft_limit.into();
4502
4503 debug_assert!(soft_limit <= hard_limit);
4504
4505 // It is important to preserve this comparison order because if soft_limit ==
4506 // hard_limit we want LimitThresholdCrossed::Hard
4507 if x >= hard_limit {
4508 LimitThresholdCrossed::Hard(x.into(), hard_limit.into())
4509 } else if x < soft_limit {
4510 LimitThresholdCrossed::None
4511 } else {
4512 LimitThresholdCrossed::Soft(x.into(), soft_limit.into())
4513 }
4514}
4515
4516#[macro_export]
4517macro_rules! check_limit {
4518 ($x:expr, $hard:expr) => {
4519 check_limit!($x, $hard, $hard)
4520 };
4521 ($x:expr, $soft:expr, $hard:expr) => {
4522 check_limit_in_range($x as u64, $soft, $hard)
4523 };
4524}
4525
4526/// Used to check which limits were crossed if the TX is metered (not system tx)
4527/// Args are: is_metered, value_to_check, metered_limit, unmetered_limit
4528/// metered_limit is always less than or equal to unmetered_hard_limit
4529#[macro_export]
4530macro_rules! check_limit_by_meter {
4531 ($is_metered:expr, $x:expr, $metered_limit:expr, $unmetered_hard_limit:expr, $metric:expr) => {{
4532 // If this is metered, we use the metered_limit limit as the upper bound
4533 let (h, metered_str) = if $is_metered {
4534 ($metered_limit, "metered")
4535 } else {
4536 // Unmetered gets more headroom
4537 ($unmetered_hard_limit, "unmetered")
4538 };
4539 use iota_protocol_config::check_limit_in_range;
4540 let result = check_limit_in_range($x as u64, $metered_limit, h);
4541 match result {
4542 LimitThresholdCrossed::None => {}
4543 LimitThresholdCrossed::Soft(_, _) => {
4544 $metric.with_label_values(&[metered_str, "soft"]).inc();
4545 }
4546 LimitThresholdCrossed::Hard(_, _) => {
4547 $metric.with_label_values(&[metered_str, "hard"]).inc();
4548 }
4549 };
4550 result
4551 }};
4552}
4553
4554#[cfg(all(test, not(msim)))]
4555mod test {
4556 use insta::assert_yaml_snapshot;
4557
4558 use super::*;
4559
4560 #[test]
4561 fn snapshot_tests() {
4562 println!("\n============================================================================");
4563 println!("! !");
4564 println!("! IMPORTANT: never update snapshots from this test. only add new versions! !");
4565 println!("! !");
4566 println!("============================================================================\n");
4567 for chain_id in &[Chain::Unknown, Chain::Mainnet, Chain::Testnet] {
4568 // make Chain::Unknown snapshots compatible with pre-chain-id snapshots so that
4569 // we don't break the release-time compatibility tests. Once Chain
4570 // Id configs have been released everywhere, we can remove this and
4571 // only test Mainnet and Testnet
4572 let chain_str = match chain_id {
4573 Chain::Unknown => "".to_string(),
4574 _ => format!("{chain_id:?}_"),
4575 };
4576 for i in MIN_PROTOCOL_VERSION..=MAX_PROTOCOL_VERSION {
4577 let cur = ProtocolVersion::new(i);
4578 assert_yaml_snapshot!(
4579 format!("{}version_{}", chain_str, cur.as_u64()),
4580 ProtocolConfig::get_for_version(cur, *chain_id)
4581 );
4582 }
4583 }
4584 }
4585
4586 #[test]
4587 fn commit_transactions_once_traversed_activation() {
4588 for chain in [Chain::Unknown, Chain::Mainnet, Chain::Testnet] {
4589 for version in MIN_PROTOCOL_VERSION..=MAX_PROTOCOL_VERSION {
4590 let config = ProtocolConfig::get_for_version(ProtocolVersion::new(version), chain);
4591 assert_eq!(
4592 config.consensus_commit_transactions_once_traversed(),
4593 version >= 41 && chain != Chain::Mainnet,
4594 "unexpected activation for {chain:?} at version {version}"
4595 );
4596 }
4597 }
4598 }
4599
4600 #[test]
4601 fn test_getters() {
4602 let prot: ProtocolConfig =
4603 ProtocolConfig::get_for_version(ProtocolVersion::new(1), Chain::Unknown);
4604 assert_eq!(
4605 prot.max_arguments(),
4606 prot.max_arguments_as_option().unwrap()
4607 );
4608 }
4609
4610 #[test]
4611 fn only_signing_bounds_the_instantiation_loop_checker() {
4612 let prot = ProtocolConfig::get_for_max_version_UNSAFE();
4613
4614 let signing = prot.verifier_config(Some((0, 0, 0)));
4615 assert!(signing.max_instantiation_loop_graph_edges.is_some());
4616 assert!(signing.meter_instantiation_loops);
4617
4618 let execution = prot.verifier_config(None);
4619 assert_eq!(execution.max_instantiation_loop_graph_edges, None);
4620 assert!(!execution.meter_instantiation_loops);
4621 }
4622
4623 #[test]
4624 fn post_consensus_verifier_config_follows_deprecate_global_storage_ops() {
4625 let mut prot = ProtocolConfig::get_for_max_version_UNSAFE();
4626 prot.set_deprecate_global_storage_ops_for_testing(false);
4627
4628 assert!(
4629 prot.verifier_config(Some((0, 0, 0)))
4630 .deprecate_global_storage_ops
4631 );
4632 let post_consensus = prot.post_consensus_verifier_config();
4633 assert!(!post_consensus.deprecate_global_storage_ops);
4634 assert_eq!(
4635 post_consensus.max_back_edges_per_function,
4636 Some(prot.max_back_edges_per_function() as usize)
4637 );
4638
4639 prot.set_deprecate_global_storage_ops_for_testing(true);
4640 assert!(
4641 prot.post_consensus_verifier_config()
4642 .deprecate_global_storage_ops
4643 );
4644 }
4645
4646 #[test]
4647 fn post_consensus_verifier_config_bounds_the_instantiation_loop_checker() {
4648 let before = ProtocolConfig::get_for_version(ProtocolVersion::new(39), Chain::Unknown);
4649 let config = before.post_consensus_verifier_config();
4650 assert!(config.meter_instantiation_loops);
4651 assert_eq!(config.max_instantiation_loop_graph_edges, Some(100_000));
4652
4653 let mut prot = ProtocolConfig::get_for_version(ProtocolVersion::new(40), Chain::Unknown);
4654 prot.set_max_instantiation_loop_graph_edges_for_testing(7);
4655 prot.set_meter_instantiation_loops_for_testing(false);
4656 let config = prot.post_consensus_verifier_config();
4657 assert!(!config.meter_instantiation_loops);
4658 assert_eq!(config.max_instantiation_loop_graph_edges, Some(7));
4659
4660 // The node's signing config keeps its own values.
4661 let signing = prot.verifier_config(Some((0, 0, 0)));
4662 assert!(signing.meter_instantiation_loops);
4663 assert_eq!(signing.max_instantiation_loop_graph_edges, Some(100_000));
4664 }
4665
4666 #[test]
4667 fn signing_and_post_consensus_instantiation_loop_limits_match() {
4668 let prot = ProtocolConfig::get_for_max_version_UNSAFE();
4669 let signing = prot.verifier_config(Some(prot.verifier_signing_limits()));
4670 let post_consensus = prot.post_consensus_verifier_config();
4671
4672 assert_eq!(
4673 signing.meter_instantiation_loops,
4674 post_consensus.meter_instantiation_loops
4675 );
4676 assert_eq!(
4677 signing.max_instantiation_loop_graph_edges,
4678 post_consensus.max_instantiation_loop_graph_edges
4679 );
4680 }
4681
4682 #[test]
4683 fn test_setters() {
4684 let mut prot: ProtocolConfig =
4685 ProtocolConfig::get_for_version(ProtocolVersion::new(1), Chain::Unknown);
4686 prot.set_max_arguments_for_testing(123);
4687 assert_eq!(prot.max_arguments(), 123);
4688
4689 prot.set_max_arguments_from_str_for_testing("321".to_string());
4690 assert_eq!(prot.max_arguments(), 321);
4691
4692 prot.disable_max_arguments_for_testing();
4693 assert_eq!(prot.max_arguments_as_option(), None);
4694
4695 prot.set_attr_for_testing("max_arguments".to_string(), "456".to_string());
4696 assert_eq!(prot.max_arguments(), 456);
4697 }
4698
4699 #[test]
4700 fn reject_immutable_account_creation_implies_rejecting_the_objects() {
4701 for chain in [Chain::Unknown, Chain::Mainnet, Chain::Testnet] {
4702 for version in MIN_PROTOCOL_VERSION..=MAX_PROTOCOL_VERSION {
4703 // The getter asserts the dependency on
4704 // `reject_immutable_account_objects`.
4705 ProtocolConfig::get_for_version(ProtocolVersion::new(version), chain)
4706 .reject_immutable_account_creation();
4707 }
4708 }
4709 }
4710
4711 #[test]
4712 #[should_panic(expected = "unsupported version")]
4713 fn max_version_test() {
4714 // When this does not panic, version higher than MAX_PROTOCOL_VERSION exists.
4715 // To fix, bump MAX_PROTOCOL_VERSION or disable this check for the version.
4716 let _ = ProtocolConfig::get_for_version_impl(
4717 ProtocolVersion::new(MAX_PROTOCOL_VERSION + 1),
4718 Chain::Unknown,
4719 );
4720 }
4721
4722 #[test]
4723 fn lookup_by_string_test() {
4724 let prot: ProtocolConfig =
4725 ProtocolConfig::get_for_version(ProtocolVersion::new(1), Chain::Mainnet);
4726 // Does not exist
4727 assert!(prot.lookup_attr("some random string".to_string()).is_none());
4728
4729 assert!(
4730 prot.lookup_attr("max_arguments".to_string())
4731 == Some(ProtocolConfigValue::u32(prot.max_arguments())),
4732 );
4733
4734 // We didnt have this in version 1 on Mainnet
4735 assert!(
4736 prot.lookup_attr("poseidon_bn254_cost_base".to_string())
4737 .is_none()
4738 );
4739 assert!(
4740 prot.attr_map()
4741 .get("poseidon_bn254_cost_base")
4742 .unwrap()
4743 .is_none()
4744 );
4745
4746 // But we did in version 1 on Devnet
4747 let prot: ProtocolConfig =
4748 ProtocolConfig::get_for_version(ProtocolVersion::new(1), Chain::Unknown);
4749
4750 assert!(
4751 prot.lookup_attr("poseidon_bn254_cost_base".to_string())
4752 == Some(ProtocolConfigValue::u64(prot.poseidon_bn254_cost_base()))
4753 );
4754 assert!(
4755 prot.attr_map().get("poseidon_bn254_cost_base").unwrap()
4756 == &Some(ProtocolConfigValue::u64(prot.poseidon_bn254_cost_base()))
4757 );
4758
4759 // Check feature flags
4760 let prot: ProtocolConfig =
4761 ProtocolConfig::get_for_version(ProtocolVersion::new(1), Chain::Mainnet);
4762 // Does not exist
4763 assert!(
4764 prot.feature_flags
4765 .lookup_attr("some random string".to_owned())
4766 .is_none()
4767 );
4768 assert!(
4769 !prot
4770 .feature_flags
4771 .attr_map()
4772 .contains_key("some random string")
4773 );
4774
4775 // Was false in v1 on Mainnet
4776 assert!(prot.feature_flags.lookup_attr("enable_poseidon".to_owned()) == Some(false));
4777 assert!(
4778 prot.feature_flags
4779 .attr_map()
4780 .get("enable_poseidon")
4781 .unwrap()
4782 == &false
4783 );
4784 let prot: ProtocolConfig =
4785 ProtocolConfig::get_for_version(ProtocolVersion::new(1), Chain::Unknown);
4786 // Was true from v1 and up on Devnet
4787 assert!(prot.feature_flags.lookup_attr("enable_poseidon".to_owned()) == Some(true));
4788 assert!(
4789 prot.feature_flags
4790 .attr_map()
4791 .get("enable_poseidon")
4792 .unwrap()
4793 == &true
4794 );
4795 }
4796
4797 /// A chunk limit above the executability ceiling would fail execution on
4798 /// every validator at once, so the configuration is rejected at startup
4799 /// rather than at the flip.
4800 #[test]
4801 #[should_panic(expected = "deny_rule_update_max_entries_per_tx must be positive")]
4802 fn deny_rule_chunk_limit_above_the_ceiling_is_rejected() {
4803 let _guard = ProtocolConfig::apply_overrides_for_testing(|_, mut config| {
4804 config.set_enable_pcool_flow_for_testing(true);
4805 config.set_deny_rule_update_max_entries_per_tx_for_testing(2048 + 1);
4806 config
4807 });
4808 let _ = ProtocolConfig::get_for_version(ProtocolVersion::max(), Chain::Unknown);
4809 }
4810
4811 /// A zero chunk limit would make every delta unsplittable; the pure
4812 /// chunking function clamps it, but the configuration is still invalid.
4813 #[test]
4814 #[should_panic(expected = "deny_rule_update_max_entries_per_tx must be positive")]
4815 fn deny_rule_chunk_limit_of_zero_is_rejected() {
4816 let _guard = ProtocolConfig::apply_overrides_for_testing(|_, mut config| {
4817 config.set_enable_pcool_flow_for_testing(true);
4818 config.set_deny_rule_update_max_entries_per_tx_for_testing(0);
4819 config
4820 });
4821 let _ = ProtocolConfig::get_for_version(ProtocolVersion::max(), Chain::Unknown);
4822 }
4823
4824 /// The value the flip is expected to ship stays inside the limits.
4825 #[test]
4826 fn deny_rule_chunk_limit_within_system_tx_object_id_limit_is_accepted() {
4827 let _guard = ProtocolConfig::apply_overrides_for_testing(|_, mut config| {
4828 config.set_enable_pcool_flow_for_testing(true);
4829 config.set_deny_rule_update_max_entries_per_tx_for_testing(1000);
4830 config
4831 });
4832 let config = ProtocolConfig::get_for_version(ProtocolVersion::max(), Chain::Unknown);
4833 assert_eq!(config.deny_rule_update_max_entries_per_tx(), 1000);
4834 }
4835
4836 /// From version 39 the P-COOL flow requires the deny rule settings, which
4837 /// mirror the governed deny rules into the on-chain object.
4838 #[test]
4839 #[should_panic(expected = "enable_pcool_flow requires deny_rule_update_max_entries_per_tx")]
4840 fn pcool_flow_without_the_deny_rule_settings_is_rejected() {
4841 let _guard = ProtocolConfig::apply_overrides_for_testing(|_, mut config| {
4842 config.set_enable_pcool_flow_for_testing(true);
4843 config.disable_deny_rule_update_max_entries_per_tx_for_testing();
4844 config
4845 });
4846 let _ = ProtocolConfig::get_for_version(ProtocolVersion::new(39), Chain::Unknown);
4847 }
4848
4849 /// Devnet runs the P-COOL flow from version 32, before the settings it
4850 /// requires exist. Those versions are not checked for them.
4851 #[test]
4852 fn devnet_versions_before_39_run_the_pcool_flow_without_its_settings() {
4853 for version in 32..39 {
4854 let config =
4855 ProtocolConfig::get_for_version(ProtocolVersion::new(version), Chain::Unknown);
4856 assert!(config.enable_pcool_flow(), "version {version}");
4857 assert_eq!(
4858 config.deny_rule_update_max_entries_per_tx_as_option(),
4859 None,
4860 "version {version}"
4861 );
4862 }
4863 }
4864
4865 /// Devnet sets the horizon distance from version 39 on; Mainnet, Testnet
4866 /// and earlier versions leave it unset. An override still wins.
4867 #[test]
4868 fn horizon_distance_is_set_on_devnet_from_version_39() {
4869 let config = ProtocolConfig::get_for_version(ProtocolVersion::new(39), Chain::Unknown);
4870 assert_eq!(config.pcool_deterministic_validation_horizon_distance(), 4);
4871 for (version, chain) in [
4872 (38, Chain::Unknown),
4873 (39, Chain::Mainnet),
4874 (39, Chain::Testnet),
4875 ] {
4876 let config = ProtocolConfig::get_for_version(ProtocolVersion::new(version), chain);
4877 assert_eq!(
4878 config.pcool_deterministic_validation_horizon_distance_as_option(),
4879 None,
4880 "version {version} on {chain:?}"
4881 );
4882 }
4883
4884 let _guard = ProtocolConfig::apply_overrides_for_testing(|_, mut config| {
4885 config.set_pcool_deterministic_validation_horizon_distance_for_testing(5);
4886 config
4887 });
4888 let config = ProtocolConfig::get_for_version(ProtocolVersion::max(), Chain::Unknown);
4889 assert_eq!(config.pcool_deterministic_validation_horizon_distance(), 5);
4890 }
4891
4892 /// The P-COOL flow has no horizon distance to fall back on.
4893 #[test]
4894 #[should_panic(expected = "pcool_deterministic_validation_horizon_distance")]
4895 fn pcool_flow_without_a_horizon_distance_is_rejected() {
4896 let _guard = ProtocolConfig::apply_overrides_for_testing(|_, mut config| {
4897 config.set_enable_pcool_flow_for_testing(true);
4898 config.disable_pcool_deterministic_validation_horizon_distance_for_testing();
4899 config
4900 });
4901 let _ = ProtocolConfig::get_for_version(ProtocolVersion::max(), Chain::Unknown);
4902 }
4903
4904 /// With a horizon distance of 0, the consensus handler processing commit C
4905 /// would wait for C itself to be fully executed, which cannot happen before
4906 /// the handler finishes processing C, so the network would halt. The
4907 /// configuration is rejected at startup.
4908 #[test]
4909 #[should_panic(expected = "pcool_deterministic_validation_horizon_distance")]
4910 fn horizon_distance_of_zero_with_the_pcool_flow_is_rejected() {
4911 let _guard = ProtocolConfig::apply_overrides_for_testing(|_, mut config| {
4912 config.set_enable_pcool_flow_for_testing(true);
4913 config.set_pcool_deterministic_validation_horizon_distance_for_testing(0);
4914 config
4915 });
4916 let _ = ProtocolConfig::get_for_version(ProtocolVersion::max(), Chain::Unknown);
4917 }
4918
4919 /// Every version from 39 and chain that turns the P-COOL flow on sets a
4920 /// positive horizon distance and the verifier limits post-consensus
4921 /// validation meters published packages with.
4922 #[test]
4923 fn every_version_with_the_pcool_flow_sets_its_requirements() {
4924 for chain in [Chain::Unknown, Chain::Mainnet, Chain::Testnet] {
4925 for version in 39..=MAX_PROTOCOL_VERSION {
4926 let config = ProtocolConfig::get_for_version(ProtocolVersion::new(version), chain);
4927 if config.enable_pcool_flow() {
4928 assert!(
4929 config
4930 .pcool_deterministic_validation_horizon_distance_as_option()
4931 .is_some_and(|distance| distance > 0),
4932 "version {version} on {chain:?} runs the P-COOL flow without a positive \
4933 horizon distance"
4934 );
4935 assert!(
4936 config
4937 .max_meter_ticks_regex_reference_safety_as_option()
4938 .is_some(),
4939 "version {version} on {chain:?} runs the P-COOL flow without the \
4940 regex reference safety budget"
4941 );
4942 }
4943 }
4944 }
4945 }
4946
4947 /// Turning the P-COOL flow on for a test also turns on what it requires,
4948 /// as a version that turns it on must, whatever the version the test
4949 /// starts from.
4950 #[test]
4951 fn enabling_the_pcool_flow_for_testing_enables_its_requirements() {
4952 let mut config = ProtocolConfig::get_for_version(
4953 ProtocolVersion::new(MIN_PROTOCOL_VERSION),
4954 Chain::Unknown,
4955 );
4956 assert!(
4957 config
4958 .max_meter_ticks_regex_reference_safety_as_option()
4959 .is_none()
4960 );
4961 config.set_enable_pcool_flow_for_testing(true);
4962 assert!(config.enable_pcool_flow());
4963 assert_eq!(config.max_meter_ticks_regex_reference_safety(), 2_200_000);
4964 assert!(config.consensus_dedup_only_recorded_messages());
4965 assert_eq!(config.pcool_deterministic_validation_horizon_distance(), 4);
4966 assert_eq!(config.deny_rule_update_max_entries_per_tx(), 1000);
4967 }
4968
4969 /// An override that returns an older version's config for every version
4970 /// asked for, as `TestAuthorityBuilder` installs, is checked against the
4971 /// version of that config, which runs the P-COOL flow on Devnet before the
4972 /// settings it requires exist.
4973 #[test]
4974 fn an_override_returning_an_older_config_is_checked_against_its_version() {
4975 let older = ProtocolConfig::get_for_version(ProtocolVersion::new(37), Chain::Unknown);
4976 assert!(older.enable_pcool_flow());
4977 assert!(!older.consensus_dedup_only_recorded_messages());
4978 let _guard = ProtocolConfig::apply_overrides_for_testing(move |_, _| older.clone());
4979 let config = ProtocolConfig::get_for_version(ProtocolVersion::max(), Chain::Unknown);
4980 assert_eq!(config.version, ProtocolVersion::new(37));
4981 }
4982
4983 /// Without `consensus_dedup_only_recorded_messages` the consensus handler
4984 /// could skip a message as a duplicate of one only some validators saw
4985 /// dropped, so the combination is rejected at startup.
4986 #[test]
4987 #[should_panic(expected = "enable_pcool_flow requires consensus_dedup_only_recorded_messages")]
4988 fn pcool_flow_without_dedup_of_recorded_messages_is_rejected() {
4989 let _guard = ProtocolConfig::apply_overrides_for_testing(|_, mut config| {
4990 config.feature_flags.consensus_dedup_only_recorded_messages = false;
4991 config
4992 });
4993 let _ = ProtocolConfig::get_for_version(ProtocolVersion::max(), Chain::Unknown);
4994 }
4995
4996 /// With sponsor-only pre-consensus authentication, a sponsor alone could get
4997 /// a transaction sequenced that locks a Move account's owned objects, so
4998 /// the P-COOL flow excludes it.
4999 #[test]
5000 #[should_panic(
5001 expected = "enable_pcool_flow excludes pre_consensus_sponsor_only_move_authentication"
5002 )]
5003 fn pcool_flow_with_sponsor_only_pre_consensus_authentication_is_rejected() {
5004 let _guard = ProtocolConfig::apply_overrides_for_testing(|_, mut config| {
5005 config
5006 .feature_flags
5007 .pre_consensus_sponsor_only_move_authentication = true;
5008 config
5009 });
5010 let _ = ProtocolConfig::get_for_version(ProtocolVersion::max(), Chain::Unknown);
5011 }
5012
5013 /// Turning the P-COOL flow on for testing turns sponsor-only pre-consensus
5014 /// authentication off, which Testnet's version 34 has on.
5015 #[test]
5016 fn turning_the_pcool_flow_on_turns_sponsor_only_authentication_off() {
5017 let mut config = ProtocolConfig::get_for_version(ProtocolVersion::new(34), Chain::Testnet);
5018 assert!(config.pre_consensus_sponsor_only_move_authentication());
5019 config.set_enable_pcool_flow_for_testing(true);
5020 assert!(!config.pre_consensus_sponsor_only_move_authentication());
5021 }
5022
5023 /// A test that turns a requirement off keeps a valid config instead of
5024 /// tripping the startup check.
5025 #[test]
5026 fn disabling_a_requirement_for_testing_disables_the_pcool_flow() {
5027 let _guard = ProtocolConfig::apply_overrides_for_testing(|_, mut config| {
5028 config.set_consensus_dedup_only_recorded_messages_for_testing(false);
5029 config
5030 });
5031 let config = ProtocolConfig::get_for_version(ProtocolVersion::max(), Chain::Unknown);
5032 assert!(!config.enable_pcool_flow());
5033 }
5034
5035 #[test]
5036 fn limit_range_fn_test() {
5037 let low = 100u32;
5038 let high = 10000u64;
5039
5040 assert!(check_limit!(1u8, low, high) == LimitThresholdCrossed::None);
5041 assert!(matches!(
5042 check_limit!(255u16, low, high),
5043 LimitThresholdCrossed::Soft(255u128, 100)
5044 ));
5045 // This wont compile because lossy
5046 // assert!(check_limit!(100000000u128, low, high) ==
5047 // LimitThresholdCrossed::None); This wont compile because lossy
5048 // assert!(check_limit!(100000000usize, low, high) ==
5049 // LimitThresholdCrossed::None);
5050
5051 assert!(matches!(
5052 check_limit!(2550000u64, low, high),
5053 LimitThresholdCrossed::Hard(2550000, 10000)
5054 ));
5055
5056 assert!(matches!(
5057 check_limit!(2550000u64, high, high),
5058 LimitThresholdCrossed::Hard(2550000, 10000)
5059 ));
5060
5061 assert!(matches!(
5062 check_limit!(1u8, high),
5063 LimitThresholdCrossed::None
5064 ));
5065
5066 assert!(check_limit!(255u16, high) == LimitThresholdCrossed::None);
5067
5068 assert!(matches!(
5069 check_limit!(2550000u64, high),
5070 LimitThresholdCrossed::Hard(2550000, 10000)
5071 ));
5072 }
5073}