1
// This file is part of Substrate.
2

            
3
// Copyright (C) Parity Technologies (UK) Ltd.
4
// SPDX-License-Identifier: GPL-3.0-or-later WITH Classpath-exception-2.0
5

            
6
// This program is free software: you can redistribute it and/or modify
7
// it under the terms of the GNU General Public License as published by
8
// the Free Software Foundation, either version 3 of the License, or
9
// (at your option) any later version.
10

            
11
// This program is distributed in the hope that it will be useful,
12
// but WITHOUT ANY WARRANTY; without even the implied warranty of
13
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14
// GNU General Public License for more details.
15

            
16
// You should have received a copy of the GNU General Public License
17
// along with this program. If not, see <https://www.gnu.org/licenses/>.
18

            
19
//! Service configuration.
20

            
21
pub use jsonrpsee::server::BatchRequestConfig as RpcBatchRequestConfig;
22
use prometheus_endpoint::Registry;
23
use sc_chain_spec::ChainSpec;
24
pub use sc_client_db::{BlocksPruning, Database, DatabaseSource, PruningMode};
25
pub use sc_executor::{WasmExecutionMethod, WasmtimeInstantiationStrategy};
26
pub use sc_informant::OutputFormat;
27
pub use sc_network::{
28
	config::{
29
		MultiaddrWithPeerId, NetworkConfiguration, NodeKeyConfig, NonDefaultSetConfig, ProtocolId,
30
		Role, SetConfig, SyncMode, TransportConfig,
31
	},
32
	request_responses::{
33
		IncomingRequest, OutgoingResponse, ProtocolConfig as RequestResponseConfig,
34
	},
35
	Multiaddr,
36
};
37
pub use sc_rpc_server::IpNetwork;
38
pub use sc_telemetry::TelemetryEndpoints;
39
pub use sc_transaction_pool::Options as TransactionPoolOptions;
40
use sp_core::crypto::SecretString;
41
use std::{
42
	io, iter,
43
	net::SocketAddr,
44
	num::NonZeroU32,
45
	path::{Path, PathBuf},
46
};
47
use tempfile::TempDir;
48

            
49
/// Service configuration.
50
#[derive(Debug)]
51
pub struct Configuration {
52
	/// Implementation name
53
	pub impl_name: String,
54
	/// Implementation version (see sc-cli to see an example of format)
55
	pub impl_version: String,
56
	/// Node role.
57
	pub role: Role,
58
	/// Handle to the tokio runtime. Will be used to spawn futures by the task manager.
59
	pub tokio_handle: tokio::runtime::Handle,
60
	/// Extrinsic pool configuration.
61
	pub transaction_pool: TransactionPoolOptions,
62
	/// Network configuration.
63
	pub network: NetworkConfiguration,
64
	/// Configuration for the keystore.
65
	pub keystore: KeystoreConfig,
66
	/// Configuration for the database.
67
	pub database: DatabaseSource,
68
	/// Maximum size of internal trie cache in bytes.
69
	///
70
	/// If `None` is given the cache is disabled.
71
	pub trie_cache_maximum_size: Option<usize>,
72
	/// State pruning settings.
73
	pub state_pruning: Option<PruningMode>,
74
	/// Number of blocks to keep in the db.
75
	///
76
	/// NOTE: only finalized blocks are subject for removal!
77
	pub blocks_pruning: BlocksPruning,
78
	/// Chain configuration.
79
	pub chain_spec: Box<dyn ChainSpec>,
80
	/// Wasm execution method.
81
	pub wasm_method: WasmExecutionMethod,
82
	/// Directory where local WASM precompiled artifacts live. These wasm modules
83
	/// take precedence over runtimes when the spec and wasm config matches. Set to `None` to
84
	/// disable (default).
85
	pub wasmtime_precompiled: Option<PathBuf>,
86
	/// Directory where local WASM runtimes live. These runtimes take precedence
87
	/// over on-chain runtimes when the spec version matches. Set to `None` to
88
	/// disable overrides (default).
89
	pub wasm_runtime_overrides: Option<PathBuf>,
90
	/// JSON-RPC server binding address.
91
	pub rpc_addr: Option<SocketAddr>,
92
	/// Maximum number of connections for JSON-RPC server.
93
	pub rpc_max_connections: u32,
94
	/// CORS settings for HTTP & WS servers. `None` if all origins are allowed.
95
	pub rpc_cors: Option<Vec<String>>,
96
	/// RPC methods to expose (by default only a safe subset or all of them).
97
	pub rpc_methods: RpcMethods,
98
	/// Maximum payload of a rpc request
99
	pub rpc_max_request_size: u32,
100
	/// Maximum payload of a rpc response.
101
	pub rpc_max_response_size: u32,
102
	/// Custom JSON-RPC subscription ID provider.
103
	///
104
	/// Default: [`crate::RandomStringSubscriptionId`].
105
	pub rpc_id_provider: Option<Box<dyn crate::RpcSubscriptionIdProvider>>,
106
	/// Maximum allowed subscriptions per rpc connection
107
	pub rpc_max_subs_per_conn: u32,
108
	/// JSON-RPC server default port.
109
	pub rpc_port: u16,
110
	/// The number of messages the JSON-RPC server is allowed to keep in memory.
111
	pub rpc_message_buffer_capacity: u32,
112
	/// JSON-RPC server batch config.
113
	pub rpc_batch_config: RpcBatchRequestConfig,
114
	/// RPC rate limit per minute.
115
	pub rpc_rate_limit: Option<NonZeroU32>,
116
	/// RPC rate limit whitelisted ip addresses.
117
	pub rpc_rate_limit_whitelisted_ips: Vec<IpNetwork>,
118
	/// RPC rate limit trust proxy headers.
119
	pub rpc_rate_limit_trust_proxy_headers: bool,
120
	/// Prometheus endpoint configuration. `None` if disabled.
121
	pub prometheus_config: Option<PrometheusConfig>,
122
	/// Telemetry service URL. `None` if disabled.
123
	pub telemetry_endpoints: Option<TelemetryEndpoints>,
124
	/// The default number of 64KB pages to allocate for Wasm execution
125
	pub default_heap_pages: Option<u64>,
126
	/// Should offchain workers be executed.
127
	pub offchain_worker: OffchainWorkerConfig,
128
	/// Enable authoring even when offline.
129
	pub force_authoring: bool,
130
	/// Disable GRANDPA when running in validator mode
131
	pub disable_grandpa: bool,
132
	/// Development key seed.
133
	///
134
	/// When running in development mode, the seed will be used to generate authority keys by the
135
	/// keystore.
136
	///
137
	/// Should only be set when `node` is running development mode.
138
	pub dev_key_seed: Option<String>,
139
	/// Tracing targets
140
	pub tracing_targets: Option<String>,
141
	/// Tracing receiver
142
	pub tracing_receiver: sc_tracing::TracingReceiver,
143
	/// The size of the instances cache.
144
	///
145
	/// The default value is 8.
146
	pub max_runtime_instances: usize,
147
	/// Announce block automatically after they have been imported
148
	pub announce_block: bool,
149
	/// Data path root for the configured chain.
150
	pub data_path: PathBuf,
151
	/// Base path of the configuration. This is shared between chains.
152
	pub base_path: BasePath,
153
	/// Configuration of the output format that the informant uses.
154
	pub informant_output_format: OutputFormat,
155
	/// Maximum number of different runtime versions that can be cached.
156
	pub runtime_cache_size: u8,
157
}
158

            
159
/// Type for tasks spawned by the executor.
160
#[derive(PartialEq)]
161
pub enum TaskType {
162
	/// Regular non-blocking futures. Polling the task is expected to be a lightweight operation.
163
	Async,
164
	/// The task might perform a lot of expensive CPU operations and/or call `thread::sleep`.
165
	Blocking,
166
}
167

            
168
/// Configuration of the client keystore.
169
#[derive(Debug, Clone)]
170
pub enum KeystoreConfig {
171
	/// Keystore at a path on-disk. Recommended for native nodes.
172
	Path {
173
		/// The path of the keystore.
174
		path: PathBuf,
175
		/// Node keystore's password.
176
		password: Option<SecretString>,
177
	},
178
	/// In-memory keystore. Recommended for in-browser nodes.
179
	InMemory,
180
}
181

            
182
impl KeystoreConfig {
183
	/// Returns the path for the keystore.
184
	pub fn path(&self) -> Option<&Path> {
185
		match self {
186
			Self::Path { path, .. } => Some(path),
187
			Self::InMemory => None,
188
		}
189
	}
190
}
191
/// Configuration of the database of the client.
192
#[derive(Debug, Clone, Default)]
193
pub struct OffchainWorkerConfig {
194
	/// If this is allowed.
195
	pub enabled: bool,
196
	/// allow writes from the runtime to the offchain worker database.
197
	pub indexing_enabled: bool,
198
}
199

            
200
/// Configuration of the Prometheus endpoint.
201
#[derive(Debug, Clone)]
202
pub struct PrometheusConfig {
203
	/// Port to use.
204
	pub port: SocketAddr,
205
	/// A metrics registry to use. Useful for setting the metric prefix.
206
	pub registry: Registry,
207
}
208

            
209
impl PrometheusConfig {
210
	/// Create a new config using the default registry.
211
	pub fn new_with_default_registry(port: SocketAddr, chain_id: String) -> Self {
212
		let param = iter::once((String::from("chain"), chain_id)).collect();
213
		Self {
214
			port,
215
			registry: Registry::new_custom(None, Some(param))
216
				.expect("this can only fail if the prefix is empty"),
217
		}
218
	}
219
}
220

            
221
impl Configuration {
222
	/// Returns a string displaying the node role.
223
	pub fn display_role(&self) -> String {
224
		self.role.to_string()
225
	}
226

            
227
	/// Returns the prometheus metrics registry, if available.
228
	pub fn prometheus_registry(&self) -> Option<&Registry> {
229
		self.prometheus_config.as_ref().map(|config| &config.registry)
230
	}
231

            
232
	/// Returns the network protocol id from the chain spec, or the default.
233
	pub fn protocol_id(&self) -> ProtocolId {
234
		let protocol_id_full = match self.chain_spec.protocol_id() {
235
			Some(pid) => pid,
236
			None => {
237
				log::warn!(
238
					"Using default protocol ID {:?} because none is configured in the \
239
					chain specs",
240
					crate::DEFAULT_PROTOCOL_ID
241
				);
242
				crate::DEFAULT_PROTOCOL_ID
243
			},
244
		};
245
		ProtocolId::from(protocol_id_full)
246
	}
247

            
248
	/// Returns true if the genesis state writing will be skipped while initializing the genesis
249
	/// block.
250
	pub fn no_genesis(&self) -> bool {
251
		matches!(self.network.sync_mode, SyncMode::LightState { .. } | SyncMode::Warp { .. })
252
	}
253

            
254
	/// Returns the database config for creating the backend.
255
	pub fn db_config(&self) -> sc_client_db::DatabaseSettings {
256
		sc_client_db::DatabaseSettings {
257
			trie_cache_maximum_size: self.trie_cache_maximum_size,
258
			state_pruning: self.state_pruning.clone(),
259
			source: self.database.clone(),
260
			blocks_pruning: self.blocks_pruning,
261
		}
262
	}
263
}
264

            
265
/// Available RPC methods.
266
#[derive(Debug, Copy, Clone)]
267
pub enum RpcMethods {
268
	/// Expose every RPC method only when RPC is listening on `localhost`,
269
	/// otherwise serve only safe RPC methods.
270
	Auto,
271
	/// Allow only a safe subset of RPC methods.
272
	Safe,
273
	/// Expose every RPC method (even potentially unsafe ones).
274
	Unsafe,
275
}
276

            
277
impl Default for RpcMethods {
278
	fn default() -> RpcMethods {
279
		RpcMethods::Auto
280
	}
281
}
282

            
283
#[static_init::dynamic(drop, lazy)]
284
static mut BASE_PATH_TEMP: Option<TempDir> = None;
285

            
286
/// The base path that is used for everything that needs to be written on disk to run a node.
287
#[derive(Clone, Debug)]
288
pub struct BasePath {
289
	path: PathBuf,
290
}
291

            
292
impl BasePath {
293
	/// Create a `BasePath` instance using a temporary directory prefixed with "substrate" and use
294
	/// it as base path.
295
	///
296
	/// Note: The temporary directory will be created automatically and deleted when the program
297
	/// exits. Every call to this function will return the same path for the lifetime of the
298
	/// program.
299
	pub fn new_temp_dir() -> io::Result<BasePath> {
300
		let mut temp = BASE_PATH_TEMP.write();
301

            
302
		match &*temp {
303
			Some(p) => Ok(Self::new(p.path())),
304
			None => {
305
				let temp_dir = tempfile::Builder::new().prefix("substrate").tempdir()?;
306
				let path = PathBuf::from(temp_dir.path());
307

            
308
				*temp = Some(temp_dir);
309
				Ok(Self::new(path))
310
			},
311
		}
312
	}
313

            
314
	/// Create a `BasePath` instance based on an existing path on disk.
315
	///
316
	/// Note: this function will not ensure that the directory exist nor create the directory. It
317
	/// will also not delete the directory when the instance is dropped.
318
	pub fn new<P: Into<PathBuf>>(path: P) -> BasePath {
319
		Self { path: path.into() }
320
	}
321

            
322
	/// Create a base path from values describing the project.
323
	pub fn from_project(qualifier: &str, organization: &str, application: &str) -> BasePath {
324
		BasePath::new(
325
			directories::ProjectDirs::from(qualifier, organization, application)
326
				.expect("app directories exist on all supported platforms; qed")
327
				.data_local_dir(),
328
		)
329
	}
330

            
331
	/// Retrieve the base path.
332
	pub fn path(&self) -> &Path {
333
		&self.path
334
	}
335

            
336
	/// Returns the configuration directory inside this base path.
337
	///
338
	/// The path looks like `$base_path/chains/$chain_id`
339
	pub fn config_dir(&self, chain_id: &str) -> PathBuf {
340
		self.path().join("chains").join(chain_id)
341
	}
342
}
343

            
344
impl From<PathBuf> for BasePath {
345
	fn from(path: PathBuf) -> Self {
346
		BasePath::new(path)
347
	}
348
}