near_parameters/config.rs
1//! Settings of the parameters of the runtime.
2use super::parameter_table::InvalidConfigError;
3use crate::config_store::INITIAL_TESTNET_CONFIG;
4use crate::cost::RuntimeFeesConfig;
5use crate::parameter_table::ParameterTable;
6use near_account_id::AccountId;
7use near_primitives_core::types::{Balance, Gas, ProtocolVersion};
8use near_primitives_core::version::PROTOCOL_VERSION;
9use std::sync::Arc;
10
11// Lowered promise yield timeout length used in integration tests.
12// The resharding tests for yield timeouts take too long to run otherwise.
13pub const TEST_CONFIG_YIELD_TIMEOUT_LENGTH: u64 = 10;
14
15/// The structure that holds the parameters of the runtime, mostly economics.
16#[derive(Debug, Clone, PartialEq)]
17pub struct RuntimeConfig {
18    /// Action gas costs, storage fees, and economic constants around them.
19    ///
20    /// This contains parameters that are required by the WASM runtime and the
21    /// transaction runtime.
22    pub fees: Arc<RuntimeFeesConfig>,
23    /// Config of wasm operations, also includes wasm gas costs.
24    ///
25    /// This contains all the configuration parameters that are only required by
26    /// the WASM runtime.
27    pub wasm_config: Arc<crate::vm::Config>,
28    /// Config that defines rules for account creation.
29    pub account_creation_config: AccountCreationConfig,
30    /// The configuration for congestion control.
31    pub congestion_control_config: CongestionControlConfig,
32    /// Configuration specific to ChunkStateWitness.
33    pub witness_config: WitnessConfig,
34    /// Configuration specific to BandwidthScheduler.
35    pub bandwidth_scheduler_config: BandwidthSchedulerConfig,
36
37    /// Whether receipts should be stored as [StateStoredReceipt].
38    pub use_state_stored_receipt: bool,
39}
40
41impl RuntimeConfig {
42    pub(crate) fn new(params: &ParameterTable) -> Result<Self, InvalidConfigError> {
43        RuntimeConfig::try_from(params)
44    }
45
46    pub fn initial_testnet_config() -> RuntimeConfig {
47        INITIAL_TESTNET_CONFIG
48            .parse()
49            .and_then(|params| RuntimeConfig::new(¶ms))
50            .expect("Failed parsing initial testnet config")
51    }
52
53    pub fn test() -> Self {
54        Self::test_protocol_version(PROTOCOL_VERSION)
55    }
56
57    pub fn test_protocol_version(protocol_version: ProtocolVersion) -> Self {
58        let config_store = super::config_store::RuntimeConfigStore::new(None);
59        let runtime_config = config_store.get_config(protocol_version);
60
61        let mut wasm_config = crate::vm::Config::clone(&runtime_config.wasm_config);
62        // Lower the yield timeout length so that we can observe timeouts in integration tests.
63        wasm_config.limit_config.yield_timeout_length_in_blocks = TEST_CONFIG_YIELD_TIMEOUT_LENGTH;
64
65        RuntimeConfig {
66            fees: Arc::new(RuntimeFeesConfig::test()),
67            wasm_config: Arc::new(wasm_config),
68            account_creation_config: AccountCreationConfig::default(),
69            congestion_control_config: runtime_config.congestion_control_config,
70            witness_config: runtime_config.witness_config,
71            bandwidth_scheduler_config: runtime_config.bandwidth_scheduler_config,
72            use_state_stored_receipt: runtime_config.use_state_stored_receipt,
73        }
74    }
75
76    pub fn free() -> Self {
77        let config_store = super::config_store::RuntimeConfigStore::new(None);
78        let runtime_config = config_store.get_config(PROTOCOL_VERSION);
79
80        let mut wasm_config = crate::vm::Config::clone(&runtime_config.wasm_config);
81        wasm_config.make_free();
82
83        Self {
84            fees: Arc::new(RuntimeFeesConfig::free()),
85            wasm_config: Arc::new(wasm_config),
86            account_creation_config: AccountCreationConfig::default(),
87            congestion_control_config: runtime_config.congestion_control_config,
88            witness_config: runtime_config.witness_config,
89            bandwidth_scheduler_config: runtime_config.bandwidth_scheduler_config,
90            use_state_stored_receipt: runtime_config.use_state_stored_receipt,
91        }
92    }
93
94    pub fn storage_amount_per_byte(&self) -> Balance {
95        self.fees.storage_usage_config.storage_amount_per_byte
96    }
97}
98
99/// The structure describes configuration for creation of new accounts.
100#[derive(Debug, Clone, PartialEq, Eq)]
101pub struct AccountCreationConfig {
102    /// The minimum length of the top-level account ID that is allowed to be created by any account.
103    pub min_allowed_top_level_account_length: u8,
104    /// The account ID of the account registrar. This account ID allowed to create top-level
105    /// accounts of any valid length.
106    pub registrar_account_id: AccountId,
107}
108
109impl Default for AccountCreationConfig {
110    fn default() -> Self {
111        Self {
112            min_allowed_top_level_account_length: 0,
113            registrar_account_id: "registrar".parse().unwrap(),
114        }
115    }
116}
117
118/// The configuration for congestion control.
119#[derive(Debug, Copy, Clone, PartialEq)]
120pub struct CongestionControlConfig {
121    /// How much gas in delayed receipts of a shard is 100% incoming congestion.
122    ///
123    /// Based on incoming congestion levels, a shard reduces the gas it spends on
124    /// accepting new transactions instead of working on incoming receipts. Plus,
125    /// incoming congestion contributes to overall congestion, which reduces how
126    /// much other shards are allowed to forward to this shard.
127    pub max_congestion_incoming_gas: Gas,
128
129    /// How much gas in outgoing buffered receipts of a shard is 100% congested.
130    ///
131    /// Outgoing congestion contributes to overall congestion, which reduces how
132    /// much other shards are allowed to forward to this shard.
133    pub max_congestion_outgoing_gas: Gas,
134
135    /// How much memory space of all delayed and buffered receipts in a shard is
136    /// considered 100% congested.
137    ///
138    /// Memory congestion contributes to overall congestion, which reduces how much
139    /// other shards are allowed to forward to this shard.
140    ///
141    /// This threshold limits memory requirements of validators to a degree but it
142    /// is not a hard guarantee.
143    pub max_congestion_memory_consumption: u64,
144
145    /// How many missed chunks in a row in a shard is considered 100% congested.
146    pub max_congestion_missed_chunks: u64,
147
148    /// The maximum amount of gas attached to receipts a shard can forward to
149    /// another shard per chunk.
150    ///
151    /// The actual gas forwarding allowance is a linear interpolation between
152    /// [MIN_OUTGOING_GAS](CongestionControlConfig::min_outgoing_gas) and
153    /// [MAX_OUTGOING_GAS](CongestionControlConfig::max_outgoing_gas), or 0 if the receiver is
154    /// fully congested.
155    pub max_outgoing_gas: Gas,
156
157    /// The minimum gas each shard can send to a shard that is not fully congested.
158    ///
159    /// The actual gas forwarding allowance is a linear interpolation between
160    /// [MIN_OUTGOING_GAS](CongestionControlConfig::min_outgoing_gas) and
161    /// [MAX_OUTGOING_GAS](CongestionControlConfig::max_outgoing_gas), or 0 if the receiver is
162    /// fully congested.
163    pub min_outgoing_gas: Gas,
164
165    /// How much gas the chosen allowed shard can send to a 100% congested shard.
166    ///
167    /// This amount is the absolute minimum of new workload a congested shard has to
168    /// accept every round. It ensures deadlocks are provably impossible. But in
169    /// ideal conditions, the gradual reduction of new workload entering the system
170    /// combined with gradually limited forwarding to congested shards should
171    /// prevent shards from becoming 100% congested in the first place.
172    pub allowed_shard_outgoing_gas: Gas,
173
174    /// The maximum amount of gas in a chunk spent on converting new transactions to
175    /// receipts.
176    ///
177    /// The actual gas forwarding allowance is a linear interpolation between
178    /// [MIN_OUTGOING_GAS](CongestionControlConfig::min_outgoing_gas) and
179    /// [MAX_OUTGOING_GAS](CongestionControlConfig::max_outgoing_gas),
180    /// based on the incoming congestion of the local shard.
181    /// Additionally, transactions can be rejected if the receiving
182    /// remote shard is congested more than
183    /// [REJECT_TX_CONGESTION_THRESHOLD](CongestionControlConfig::reject_tx_congestion_threshold)
184    /// based on their general congestion level.
185    pub max_tx_gas: Gas,
186
187    /// The minimum amount of gas in a chunk spent on converting new transactions
188    /// to receipts, as long as the receiving shard is not congested.
189    ///
190    /// The actual gas forwarding allowance is a linear interpolation between
191    /// [MIN_OUTGOING_GAS](CongestionControlConfig::min_outgoing_gas) and
192    /// [MAX_OUTGOING_GAS](CongestionControlConfig::max_outgoing_gas),
193    /// based on the incoming congestion of the local shard.
194    /// Additionally, transactions can be rejected if the receiving
195    /// remote shard is congested more than
196    /// [REJECT_TX_CONGESTION_THRESHOLD](CongestionControlConfig::reject_tx_congestion_threshold)
197    /// based on their general congestion level.
198    pub min_tx_gas: Gas,
199
200    /// How much congestion a shard can tolerate before it stops all shards from
201    /// accepting new transactions with the receiver set to the congested shard.
202    pub reject_tx_congestion_threshold: f64,
203
204    /// The standard size limit for outgoing receipts aimed at a single shard.
205    /// This limit is pretty small to keep the size of source_receipt_proofs under control.
206    /// It limits the total sum of outgoing receipts, not individual receipts.
207    pub outgoing_receipts_usual_size_limit: u64,
208
209    /// Large size limit for outgoing receipts to a shard, used when it's safe
210    /// to send a lot of receipts without making the state witness too large.
211    /// It limits the total sum of outgoing receipts, not individual receipts.
212    pub outgoing_receipts_big_size_limit: u64,
213}
214
215// The Eq cannot be automatically derived for this class because it contains a
216// f64 field. The f64 type does not implement the Eq trait because it's possible
217// that NaN != NaN. In the CongestionControlConfig the field should never be NaN
218// so it is okay for us to add the Eq trait to it manually.
219impl Eq for CongestionControlConfig {}
220
221impl CongestionControlConfig {
222    /// Creates a config where congestion control is disabled. This config can
223    /// be used for tests. It can be useful e.g. in tests with missing chunks
224    /// where we still want to process all transactions.
225    pub fn test_disabled() -> Self {
226        let max_value = u64::MAX;
227        Self {
228            max_congestion_incoming_gas: max_value,
229            max_congestion_outgoing_gas: max_value,
230            max_congestion_memory_consumption: max_value,
231            max_congestion_missed_chunks: max_value,
232            max_outgoing_gas: max_value,
233            min_outgoing_gas: max_value,
234            allowed_shard_outgoing_gas: max_value,
235            max_tx_gas: max_value,
236            min_tx_gas: max_value,
237            reject_tx_congestion_threshold: 2.0,
238            outgoing_receipts_usual_size_limit: max_value,
239            outgoing_receipts_big_size_limit: max_value,
240        }
241    }
242}
243
244/// Configuration specific to ChunkStateWitness.
245#[derive(Debug, Copy, Clone, PartialEq)]
246pub struct WitnessConfig {
247    /// Size limit for storage proof generated while executing receipts in a chunk.
248    /// After this limit is reached we defer execution of any new receipts.
249    pub main_storage_proof_size_soft_limit: usize,
250    /// Maximum size of transactions contained inside ChunkStateWitness.
251    /// A witness contains transactions from both the previous chunk and the current one.
252    /// This parameter limits the sum of sizes of transactions from both of those chunks.
253    pub combined_transactions_size_limit: usize,
254    /// Soft size limit of storage proof used to validate new transactions in ChunkStateWitness.
255    pub new_transactions_validation_state_size_soft_limit: usize,
256}
257
258impl WitnessConfig {
259    /// Creates a config that effectively disables ChunkStateWitness related limits by setting them
260    /// to max values. This can be useful for tests and benchmarks.
261    pub fn test_disabled() -> Self {
262        let max_value = usize::MAX;
263        Self {
264            main_storage_proof_size_soft_limit: max_value,
265            combined_transactions_size_limit: max_value,
266            new_transactions_validation_state_size_soft_limit: max_value,
267        }
268    }
269}
270
271/// Configuration specific to BandwidthScheduler
272#[derive(Debug, Copy, Clone, PartialEq)]
273pub struct BandwidthSchedulerConfig {
274    /// The maximum amount of data that a shard can send or receive at a single height.
275    pub max_shard_bandwidth: u64,
276    /// The maximum amount of bandwidth that can be granted on a single link.
277    /// Should be at least as big as `max_receipt_size`.
278    pub max_single_grant: u64,
279    /// Maximum bandwidth allowance that a link can accumulate.
280    pub max_allowance: u64,
281    /// Max value of `base_bandwidth` that is granted on all links by default.
282    pub max_base_bandwidth: u64,
283}