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