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