Skip to main content

soil_pow/
lib.rs

1// This file is part of Soil.
2
3// Copyright (C) Soil contributors.
4// Copyright (C) Parity Technologies (UK) Ltd.
5// SPDX-License-Identifier: GPL-3.0-or-later WITH Classpath-exception-2.0
6
7//! Proof of work consensus for Substrate.
8//!
9//! To use this engine, you can need to have a struct that implements
10//! [`PowAlgorithm`]. After that, pass an instance of the struct, along
11//! with other necessary client references to [`import_queue`] to setup
12//! the queue.
13//!
14//! This library also comes with an async mining worker, which can be
15//! started via the [`start_mining_worker`] function. It returns a worker
16//! handle together with a future. The future must be pulled. Through
17//! the worker handle, you can pull the metadata needed to start the
18//! mining process via [`MiningHandle::metadata`], and then do the actual
19//! mining on a standalone thread. Finally, when a seal is found, call
20//! [`MiningHandle::submit`] to build the block.
21//!
22//! The auxiliary storage for PoW engine only stores the total difficulty.
23//! For other storage requirements for particular PoW algorithm (such as
24//! the actual difficulty for each particular blocks), you can take a client
25//! reference in your [`PowAlgorithm`] implementation, and use a separate prefix
26//! for the auxiliary storage. It is also possible to just use the runtime
27//! as the storage, but it is not recommended as it won't work well with light
28//! clients.
29
30mod worker;
31
32pub use crate::worker::{MiningBuild, MiningHandle, MiningMetadata};
33
34use crate::worker::UntilImportedOrTimeout;
35use codec::{Decode, Encode};
36use futures::{Future, StreamExt};
37use log::*;
38use soil_prometheus::Registry;
39use soil_client::blockchain::HeaderBackend;
40use soil_client::client_api::{self, backend::AuxStore, BlockOf, BlockchainEvents};
41use soil_client::consensus::{
42	Environment, Error as ConsensusError, ProposeArgs, Proposer, SelectChain, SyncOracle,
43};
44use soil_client::import::{
45	BasicQueue, BlockCheckParams, BlockImport, BlockImportParams, BoxBlockImport,
46	BoxJustificationImport, ForkChoiceStrategy, ImportResult, Verifier,
47};
48use std::{cmp::Ordering, marker::PhantomData, sync::Arc, time::Duration};
49use subsoil::api::ProvideRuntimeApi;
50use subsoil::block_builder::BlockBuilder as BlockBuilderApi;
51use subsoil::consensus::pow::{Seal, TotalDifficulty, POW_ENGINE_ID};
52use subsoil::inherents::{CreateInherentDataProviders, InherentDataProvider};
53use subsoil::runtime::{
54	generic::{BlockId, Digest, DigestItem},
55	traits::{Block as BlockT, Header as HeaderT},
56};
57
58const LOG_TARGET: &str = "pow";
59
60#[derive(Debug, thiserror::Error)]
61pub enum Error<B: BlockT> {
62	#[error("Header uses the wrong engine {0:?}")]
63	WrongEngine([u8; 4]),
64	#[error("Header {0:?} is unsealed")]
65	HeaderUnsealed(B::Hash),
66	#[error("PoW validation error: invalid seal")]
67	InvalidSeal,
68	#[error("PoW validation error: preliminary verification failed")]
69	FailedPreliminaryVerify,
70	#[error("Rejecting block too far in future")]
71	TooFarInFuture,
72	#[error("Fetching best header failed using select chain: {0}")]
73	BestHeaderSelectChain(ConsensusError),
74	#[error("Fetching best header failed: {0}")]
75	BestHeader(soil_client::blockchain::Error),
76	#[error("Best header does not exist")]
77	NoBestHeader,
78	#[error("Block proposing error: {0}")]
79	BlockProposingError(String),
80	#[error("Fetch best hash failed via select chain: {0}")]
81	BestHashSelectChain(ConsensusError),
82	#[error("Error with block built on {0:?}: {1}")]
83	BlockBuiltError(B::Hash, ConsensusError),
84	#[error("Creating inherents failed: {0}")]
85	CreateInherents(subsoil::inherents::Error),
86	#[error("Checking inherents failed: {0}")]
87	CheckInherents(subsoil::inherents::Error),
88	#[error(
89		"Checking inherents unknown error for identifier: {}",
90		String::from_utf8_lossy(.0)
91	)]
92	CheckInherentsUnknownError(subsoil::inherents::InherentIdentifier),
93	#[error("Multiple pre-runtime digests")]
94	MultiplePreRuntimeDigests,
95	#[error(transparent)]
96	Client(soil_client::blockchain::Error),
97	#[error(transparent)]
98	Codec(codec::Error),
99	#[error("{0}")]
100	Environment(String),
101	#[error("{0}")]
102	Runtime(String),
103	#[error("{0}")]
104	Other(String),
105}
106
107impl<B: BlockT> From<Error<B>> for String {
108	fn from(error: Error<B>) -> String {
109		error.to_string()
110	}
111}
112
113impl<B: BlockT> From<Error<B>> for ConsensusError {
114	fn from(error: Error<B>) -> ConsensusError {
115		ConsensusError::ClientImport(error.to_string())
116	}
117}
118
119/// Auxiliary storage prefix for PoW engine.
120pub const POW_AUX_PREFIX: [u8; 4] = *b"PoW:";
121
122/// Get the auxiliary storage key used by engine to store total difficulty.
123fn aux_key<T: AsRef<[u8]>>(hash: &T) -> Vec<u8> {
124	POW_AUX_PREFIX.iter().chain(hash.as_ref()).copied().collect()
125}
126
127/// Intermediate value passed to block importer.
128#[derive(Encode, Decode, Clone, Debug, Default)]
129pub struct PowIntermediate<Difficulty> {
130	/// Difficulty of the block, if known.
131	pub difficulty: Option<Difficulty>,
132}
133
134/// Intermediate key for PoW engine.
135pub static INTERMEDIATE_KEY: &[u8] = b"pow1";
136
137/// Auxiliary storage data for PoW.
138#[derive(Encode, Decode, Clone, Debug, Default)]
139pub struct PowAux<Difficulty> {
140	/// Difficulty of the current block.
141	pub difficulty: Difficulty,
142	/// Total difficulty up to current block.
143	pub total_difficulty: Difficulty,
144}
145
146impl<Difficulty> PowAux<Difficulty>
147where
148	Difficulty: Decode + Default,
149{
150	/// Read the auxiliary from client.
151	pub fn read<C: AuxStore, B: BlockT>(client: &C, hash: &B::Hash) -> Result<Self, Error<B>> {
152		let key = aux_key(&hash);
153
154		match client.get_aux(&key).map_err(Error::Client)? {
155			Some(bytes) => Self::decode(&mut &bytes[..]).map_err(Error::Codec),
156			None => Ok(Self::default()),
157		}
158	}
159}
160
161/// Algorithm used for proof of work.
162pub trait PowAlgorithm<B: BlockT> {
163	/// Difficulty for the algorithm.
164	type Difficulty: TotalDifficulty + Default + Encode + Decode + Ord + Clone + Copy;
165
166	/// Get the next block's difficulty.
167	///
168	/// This function will be called twice during the import process, so the implementation
169	/// should be properly cached.
170	fn difficulty(&self, parent: B::Hash) -> Result<Self::Difficulty, Error<B>>;
171	/// Verify that the seal is valid against given pre hash when parent block is not yet imported.
172	///
173	/// None means that preliminary verify is not available for this algorithm.
174	fn preliminary_verify(
175		&self,
176		_pre_hash: &B::Hash,
177		_seal: &Seal,
178	) -> Result<Option<bool>, Error<B>> {
179		Ok(None)
180	}
181	/// Break a fork choice tie.
182	///
183	/// By default this chooses the earliest block seen. Using uniform tie
184	/// breaking algorithms will help to protect against selfish mining.
185	///
186	/// Returns if the new seal should be considered best block.
187	fn break_tie(&self, _own_seal: &Seal, _new_seal: &Seal) -> bool {
188		false
189	}
190	/// Verify that the difficulty is valid against given seal.
191	fn verify(
192		&self,
193		parent: &BlockId<B>,
194		pre_hash: &B::Hash,
195		pre_digest: Option<&[u8]>,
196		seal: &Seal,
197		difficulty: Self::Difficulty,
198	) -> Result<bool, Error<B>>;
199}
200
201/// A block importer for PoW.
202pub struct PowBlockImport<B: BlockT, I, C, S, Algorithm, CIDP> {
203	algorithm: Algorithm,
204	inner: I,
205	select_chain: S,
206	client: Arc<C>,
207	create_inherent_data_providers: Arc<CIDP>,
208	check_inherents_after: <<B as BlockT>::Header as HeaderT>::Number,
209}
210
211impl<B: BlockT, I: Clone, C, S: Clone, Algorithm: Clone, CIDP> Clone
212	for PowBlockImport<B, I, C, S, Algorithm, CIDP>
213{
214	fn clone(&self) -> Self {
215		Self {
216			algorithm: self.algorithm.clone(),
217			inner: self.inner.clone(),
218			select_chain: self.select_chain.clone(),
219			client: self.client.clone(),
220			create_inherent_data_providers: self.create_inherent_data_providers.clone(),
221			check_inherents_after: self.check_inherents_after,
222		}
223	}
224}
225
226impl<B, I, C, S, Algorithm, CIDP> PowBlockImport<B, I, C, S, Algorithm, CIDP>
227where
228	B: BlockT,
229	I: BlockImport<B> + Send + Sync,
230	I::Error: Into<ConsensusError>,
231	C: ProvideRuntimeApi<B> + Send + Sync + HeaderBackend<B> + AuxStore + BlockOf,
232	C::Api: BlockBuilderApi<B>,
233	Algorithm: PowAlgorithm<B>,
234	CIDP: CreateInherentDataProviders<B, ()>,
235{
236	/// Create a new block import suitable to be used in PoW
237	pub fn new(
238		inner: I,
239		client: Arc<C>,
240		algorithm: Algorithm,
241		check_inherents_after: <<B as BlockT>::Header as HeaderT>::Number,
242		select_chain: S,
243		create_inherent_data_providers: CIDP,
244	) -> Self {
245		Self {
246			inner,
247			client,
248			algorithm,
249			check_inherents_after,
250			select_chain,
251			create_inherent_data_providers: Arc::new(create_inherent_data_providers),
252		}
253	}
254
255	async fn check_inherents(
256		&self,
257		block: B,
258		at_hash: B::Hash,
259		inherent_data_providers: CIDP::InherentDataProviders,
260	) -> Result<(), Error<B>> {
261		use subsoil::block_builder::CheckInherentsError;
262
263		if *block.header().number() < self.check_inherents_after {
264			return Ok(());
265		}
266
267		subsoil::block_builder::check_inherents(
268			self.client.clone(),
269			at_hash,
270			block,
271			&inherent_data_providers,
272		)
273		.await
274		.map_err(|e| match e {
275			CheckInherentsError::CreateInherentData(e) => Error::CreateInherents(e),
276			CheckInherentsError::Client(e) => Error::Client(e.into()),
277			CheckInherentsError::CheckInherents(e) => Error::CheckInherents(e),
278			CheckInherentsError::CheckInherentsUnknownError(id) => {
279				Error::CheckInherentsUnknownError(id)
280			},
281		})?;
282
283		Ok(())
284	}
285}
286
287#[async_trait::async_trait]
288impl<B, I, C, S, Algorithm, CIDP> BlockImport<B> for PowBlockImport<B, I, C, S, Algorithm, CIDP>
289where
290	B: BlockT,
291	I: BlockImport<B> + Send + Sync,
292	I::Error: Into<ConsensusError>,
293	S: SelectChain<B>,
294	C: ProvideRuntimeApi<B> + Send + Sync + HeaderBackend<B> + AuxStore + BlockOf,
295	C::Api: BlockBuilderApi<B>,
296	Algorithm: PowAlgorithm<B> + Send + Sync,
297	Algorithm::Difficulty: 'static + Send,
298	CIDP: CreateInherentDataProviders<B, ()> + Send + Sync,
299{
300	type Error = ConsensusError;
301
302	async fn check_block(&self, block: BlockCheckParams<B>) -> Result<ImportResult, Self::Error> {
303		self.inner.check_block(block).await.map_err(Into::into)
304	}
305
306	async fn import_block(
307		&self,
308		mut block: BlockImportParams<B>,
309	) -> Result<ImportResult, Self::Error> {
310		let best_header = self
311			.select_chain
312			.best_chain()
313			.await
314			.map_err(|e| format!("Fetch best chain failed via select chain: {}", e))
315			.map_err(ConsensusError::ChainLookup)?;
316		let best_hash = best_header.hash();
317
318		let parent_hash = *block.header.parent_hash();
319		let best_aux = PowAux::read::<_, B>(self.client.as_ref(), &best_hash)?;
320		let mut aux = PowAux::read::<_, B>(self.client.as_ref(), &parent_hash)?;
321
322		if let Some(inner_body) = block.body.take() {
323			let check_block = B::new(block.header.clone(), inner_body);
324
325			if !block.state_action.skip_execution_checks() {
326				self.check_inherents(
327					check_block.clone(),
328					parent_hash,
329					self.create_inherent_data_providers
330						.create_inherent_data_providers(parent_hash, ())
331						.await?,
332				)
333				.await?;
334			}
335
336			block.body = Some(check_block.deconstruct().1);
337		}
338
339		let inner_seal = fetch_seal::<B>(block.post_digests.last(), block.header.hash())?;
340
341		let intermediate = block
342			.remove_intermediate::<PowIntermediate<Algorithm::Difficulty>>(INTERMEDIATE_KEY)?;
343
344		let difficulty = match intermediate.difficulty {
345			Some(difficulty) => difficulty,
346			None => self.algorithm.difficulty(parent_hash)?,
347		};
348
349		let pre_hash = block.header.hash();
350		let pre_digest = find_pre_digest::<B>(&block.header)?;
351		if !self.algorithm.verify(
352			&BlockId::hash(parent_hash),
353			&pre_hash,
354			pre_digest.as_ref().map(|v| &v[..]),
355			&inner_seal,
356			difficulty,
357		)? {
358			return Err(Error::<B>::InvalidSeal.into());
359		}
360
361		aux.difficulty = difficulty;
362		aux.total_difficulty.increment(difficulty);
363
364		let key = aux_key(&block.post_hash());
365		block.auxiliary.push((key, Some(aux.encode())));
366		if block.fork_choice.is_none() {
367			block.fork_choice = Some(ForkChoiceStrategy::Custom(
368				match aux.total_difficulty.cmp(&best_aux.total_difficulty) {
369					Ordering::Less => false,
370					Ordering::Greater => true,
371					Ordering::Equal => {
372						let best_inner_seal =
373							fetch_seal::<B>(best_header.digest().logs.last(), best_hash)?;
374
375						self.algorithm.break_tie(&best_inner_seal, &inner_seal)
376					},
377				},
378			));
379		}
380
381		self.inner.import_block(block).await.map_err(Into::into)
382	}
383}
384
385/// A verifier for PoW blocks.
386pub struct PowVerifier<B: BlockT, Algorithm> {
387	algorithm: Algorithm,
388	_marker: PhantomData<B>,
389}
390
391impl<B: BlockT, Algorithm> PowVerifier<B, Algorithm> {
392	pub fn new(algorithm: Algorithm) -> Self {
393		Self { algorithm, _marker: PhantomData }
394	}
395
396	fn check_header(&self, mut header: B::Header) -> Result<(B::Header, DigestItem), Error<B>>
397	where
398		Algorithm: PowAlgorithm<B>,
399	{
400		let hash = header.hash();
401
402		let (seal, inner_seal) = match header.digest_mut().pop() {
403			Some(DigestItem::Seal(id, seal)) => {
404				if id == POW_ENGINE_ID {
405					(DigestItem::Seal(id, seal.clone()), seal)
406				} else {
407					return Err(Error::WrongEngine(id));
408				}
409			},
410			_ => return Err(Error::HeaderUnsealed(hash)),
411		};
412
413		let pre_hash = header.hash();
414
415		if !self.algorithm.preliminary_verify(&pre_hash, &inner_seal)?.unwrap_or(true) {
416			return Err(Error::FailedPreliminaryVerify);
417		}
418
419		Ok((header, seal))
420	}
421}
422
423#[async_trait::async_trait]
424impl<B: BlockT, Algorithm> Verifier<B> for PowVerifier<B, Algorithm>
425where
426	Algorithm: PowAlgorithm<B> + Send + Sync,
427	Algorithm::Difficulty: 'static + Send,
428{
429	async fn verify(
430		&self,
431		mut block: BlockImportParams<B>,
432	) -> Result<BlockImportParams<B>, String> {
433		let hash = block.header.hash();
434		let (checked_header, seal) = self.check_header(block.header)?;
435
436		let intermediate = PowIntermediate::<Algorithm::Difficulty> { difficulty: None };
437		block.header = checked_header;
438		block.post_digests.push(seal);
439		block.insert_intermediate(INTERMEDIATE_KEY, intermediate);
440		block.post_hash = Some(hash);
441
442		Ok(block)
443	}
444}
445
446/// The PoW import queue type.
447pub type PowImportQueue<B> = BasicQueue<B>;
448
449/// Import queue for PoW engine.
450pub fn import_queue<B, Algorithm>(
451	block_import: BoxBlockImport<B>,
452	justification_import: Option<BoxJustificationImport<B>>,
453	algorithm: Algorithm,
454	spawner: &impl subsoil::core::traits::SpawnEssentialNamed,
455	registry: Option<&Registry>,
456) -> Result<PowImportQueue<B>, soil_client::consensus::Error>
457where
458	B: BlockT,
459	Algorithm: PowAlgorithm<B> + Clone + Send + Sync + 'static,
460	Algorithm::Difficulty: Send,
461{
462	let verifier = PowVerifier::new(algorithm);
463
464	Ok(BasicQueue::new(verifier, block_import, justification_import, spawner, registry))
465}
466
467/// Start the mining worker for PoW. This function provides the necessary helper functions that can
468/// be used to implement a miner. However, it does not do the CPU-intensive mining itself.
469///
470/// Two values are returned -- a worker, which contains functions that allows querying the current
471/// mining metadata and submitting mined blocks, and a future, which must be polled to fill in
472/// information in the worker.
473///
474/// `pre_runtime` is a parameter that allows a custom additional pre-runtime digest to be inserted
475/// for blocks being built. This can encode authorship information, or just be a graffiti.
476pub fn start_mining_worker<Block, C, S, Algorithm, E, SO, L, CIDP>(
477	block_import: BoxBlockImport<Block>,
478	client: Arc<C>,
479	select_chain: S,
480	algorithm: Algorithm,
481	mut env: E,
482	sync_oracle: SO,
483	justification_sync_link: L,
484	pre_runtime: Option<Vec<u8>>,
485	create_inherent_data_providers: CIDP,
486	timeout: Duration,
487	build_time: Duration,
488) -> (MiningHandle<Block, Algorithm, L>, impl Future<Output = ()>)
489where
490	Block: BlockT,
491	C: BlockchainEvents<Block> + 'static,
492	S: SelectChain<Block> + 'static,
493	Algorithm: PowAlgorithm<Block> + Clone,
494	Algorithm::Difficulty: Send + 'static,
495	E: Environment<Block> + Send + Sync + 'static,
496	E::Error: std::fmt::Debug,
497	E::Proposer: Proposer<Block>,
498	SO: SyncOracle + Clone + Send + Sync + 'static,
499	L: soil_client::import::JustificationSyncLink<Block>,
500	CIDP: CreateInherentDataProviders<Block, ()>,
501{
502	let mut timer = UntilImportedOrTimeout::new(client.import_notification_stream(), timeout);
503	let worker = MiningHandle::new(algorithm.clone(), block_import, justification_sync_link);
504	let worker_ret = worker.clone();
505
506	let task = async move {
507		loop {
508			if timer.next().await.is_none() {
509				break;
510			}
511
512			if sync_oracle.is_major_syncing() {
513				debug!(target: LOG_TARGET, "Skipping proposal due to sync.");
514				worker.on_major_syncing();
515				continue;
516			}
517
518			let best_header = match select_chain.best_chain().await {
519				Ok(x) => x,
520				Err(err) => {
521					warn!(
522						target: LOG_TARGET,
523						"Unable to pull new block for authoring. \
524						 Select best chain error: {}",
525						err
526					);
527					continue;
528				},
529			};
530			let best_hash = best_header.hash();
531
532			if worker.best_hash() == Some(best_hash) {
533				continue;
534			}
535
536			// The worker is locked for the duration of the whole proposing period. Within this
537			// period, the mining target is outdated and useless anyway.
538
539			let difficulty = match algorithm.difficulty(best_hash) {
540				Ok(x) => x,
541				Err(err) => {
542					warn!(
543						target: LOG_TARGET,
544						"Unable to propose new block for authoring. \
545						 Fetch difficulty failed: {}",
546						err,
547					);
548					continue;
549				},
550			};
551
552			let inherent_data_providers = match create_inherent_data_providers
553				.create_inherent_data_providers(best_hash, ())
554				.await
555			{
556				Ok(x) => x,
557				Err(err) => {
558					warn!(
559						target: LOG_TARGET,
560						"Unable to propose new block for authoring. \
561						 Creating inherent data providers failed: {}",
562						err,
563					);
564					continue;
565				},
566			};
567
568			let inherent_data = match inherent_data_providers.create_inherent_data().await {
569				Ok(r) => r,
570				Err(e) => {
571					warn!(
572						target: LOG_TARGET,
573						"Unable to propose new block for authoring. \
574						 Creating inherent data failed: {}",
575						e,
576					);
577					continue;
578				},
579			};
580
581			let mut inherent_digests = Digest::default();
582			if let Some(pre_runtime) = &pre_runtime {
583				inherent_digests.push(DigestItem::PreRuntime(POW_ENGINE_ID, pre_runtime.to_vec()));
584			}
585
586			let pre_runtime = pre_runtime.clone();
587
588			let proposer = match env.init(&best_header).await {
589				Ok(x) => x,
590				Err(err) => {
591					warn!(
592						target: LOG_TARGET,
593						"Unable to propose new block for authoring. \
594						 Creating proposer failed: {:?}",
595						err,
596					);
597					continue;
598				},
599			};
600
601			let propose_args = ProposeArgs {
602				inherent_data,
603				inherent_digests,
604				max_duration: build_time,
605				block_size_limit: None,
606				storage_proof_recorder: None,
607				extra_extensions: Default::default(),
608			};
609
610			let proposal = match proposer.propose(propose_args).await {
611				Ok(x) => x,
612				Err(err) => {
613					warn!(
614						target: LOG_TARGET,
615						"Unable to propose new block for authoring. \
616						 Creating proposal failed: {}",
617						err,
618					);
619					continue;
620				},
621			};
622
623			let build = MiningBuild::<Block, Algorithm> {
624				metadata: MiningMetadata {
625					best_hash,
626					pre_hash: proposal.block.header().hash(),
627					pre_runtime: pre_runtime.clone(),
628					difficulty,
629				},
630				proposal,
631			};
632
633			worker.on_build(build);
634		}
635	};
636
637	(worker_ret, task)
638}
639
640/// Find PoW pre-runtime.
641fn find_pre_digest<B: BlockT>(header: &B::Header) -> Result<Option<Vec<u8>>, Error<B>> {
642	let mut pre_digest: Option<_> = None;
643	for log in header.digest().logs() {
644		trace!(target: LOG_TARGET, "Checking log {:?}, looking for pre runtime digest", log);
645		match (log, pre_digest.is_some()) {
646			(DigestItem::PreRuntime(POW_ENGINE_ID, _), true) => {
647				return Err(Error::MultiplePreRuntimeDigests)
648			},
649			(DigestItem::PreRuntime(POW_ENGINE_ID, v), false) => {
650				pre_digest = Some(v.clone());
651			},
652			(_, _) => trace!(target: LOG_TARGET, "Ignoring digest not meant for us"),
653		}
654	}
655
656	Ok(pre_digest)
657}
658
659/// Fetch PoW seal.
660fn fetch_seal<B: BlockT>(digest: Option<&DigestItem>, hash: B::Hash) -> Result<Vec<u8>, Error<B>> {
661	match digest {
662		Some(DigestItem::Seal(id, seal)) => {
663			if id == &POW_ENGINE_ID {
664				Ok(seal.clone())
665			} else {
666				Err(Error::<B>::WrongEngine(*id))
667			}
668		},
669		_ => Err(Error::<B>::HeaderUnsealed(hash)),
670	}
671}