// This file is part of Substrate.
// Copyright (C) 2017-2020 Parity Technologies (UK) Ltd.
// SPDX-License-Identifier: GPL-3.0-or-later WITH Classpath-exception-2.0
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see .
//! Proof of work consensus for Substrate.
//!
//! To use this engine, you can need to have a struct that implements
//! `PowAlgorithm`. After that, pass an instance of the struct, along
//! with other necessary client references to `import_queue` to setup
//! the queue. Use the `start_mine` function for basic CPU mining.
//!
//! The auxiliary storage for PoW engine only stores the total difficulty.
//! For other storage requirements for particular PoW algorithm (such as
//! the actual difficulty for each particular blocks), you can take a client
//! reference in your `PowAlgorithm` implementation, and use a separate prefix
//! for the auxiliary storage. It is also possible to just use the runtime
//! as the storage, but it is not recommended as it won't work well with light
//! clients.
use std::sync::Arc;
use std::any::Any;
use std::borrow::Cow;
use std::thread;
use std::collections::HashMap;
use std::marker::PhantomData;
use sc_client_api::{BlockOf, backend::AuxStore};
use sp_blockchain::{HeaderBackend, ProvideCache, well_known_cache_keys::Id as CacheKeyId};
use sp_block_builder::BlockBuilder as BlockBuilderApi;
use sp_runtime::{Justification, RuntimeString};
use sp_runtime::generic::{BlockId, Digest, DigestItem};
use sp_runtime::traits::{Block as BlockT, Header as HeaderT};
use sp_api::ProvideRuntimeApi;
use sp_consensus_pow::{Seal, TotalDifficulty, POW_ENGINE_ID};
use sp_inherents::{InherentDataProviders, InherentData};
use sp_consensus::{
BlockImportParams, BlockOrigin, ForkChoiceStrategy, SyncOracle, Environment, Proposer,
SelectChain, Error as ConsensusError, CanAuthorWith, RecordProof, BlockImport,
BlockCheckParams, ImportResult,
};
use sp_consensus::import_queue::{
BoxBlockImport, BasicQueue, Verifier, BoxJustificationImport, BoxFinalityProofImport,
};
use codec::{Encode, Decode};
use prometheus_endpoint::Registry;
use sc_client_api;
use log::*;
use sp_timestamp::{InherentError as TIError, TimestampInherentData};
#[derive(derive_more::Display, Debug)]
pub enum Error {
#[display(fmt = "Header uses the wrong engine {:?}", _0)]
WrongEngine([u8; 4]),
#[display(fmt = "Header {:?} is unsealed", _0)]
HeaderUnsealed(B::Hash),
#[display(fmt = "PoW validation error: invalid seal")]
InvalidSeal,
#[display(fmt = "PoW validation error: preliminary verification failed")]
FailedPreliminaryVerify,
#[display(fmt = "Rejecting block too far in future")]
TooFarInFuture,
#[display(fmt = "Fetching best header failed using select chain: {:?}", _0)]
BestHeaderSelectChain(ConsensusError),
#[display(fmt = "Fetching best header failed: {:?}", _0)]
BestHeader(sp_blockchain::Error),
#[display(fmt = "Best header does not exist")]
NoBestHeader,
#[display(fmt = "Block proposing error: {:?}", _0)]
BlockProposingError(String),
#[display(fmt = "Fetch best hash failed via select chain: {:?}", _0)]
BestHashSelectChain(ConsensusError),
#[display(fmt = "Error with block built on {:?}: {:?}", _0, _1)]
BlockBuiltError(B::Hash, ConsensusError),
#[display(fmt = "Creating inherents failed: {}", _0)]
CreateInherents(sp_inherents::Error),
#[display(fmt = "Checking inherents failed: {}", _0)]
CheckInherents(String),
Client(sp_blockchain::Error),
Codec(codec::Error),
Environment(String),
Runtime(RuntimeString)
}
impl std::convert::From> for String {
fn from(error: Error) -> String {
error.to_string()
}
}
impl std::convert::From> for ConsensusError {
fn from(error: Error) -> ConsensusError {
ConsensusError::ClientImport(error.to_string())
}
}
/// Auxiliary storage prefix for PoW engine.
pub const POW_AUX_PREFIX: [u8; 4] = *b"PoW:";
/// Get the auxiliary storage key used by engine to store total difficulty.
fn aux_key>(hash: &T) -> Vec {
POW_AUX_PREFIX.iter().chain(hash.as_ref()).copied().collect()
}
/// Intermediate value passed to block importer.
#[derive(Encode, Decode, Clone, Debug, Default)]
pub struct PowIntermediate {
/// Difficulty of the block, if known.
pub difficulty: Option,
}
/// Intermediate key for PoW engine.
pub static INTERMEDIATE_KEY: &[u8] = b"pow1";
/// Auxiliary storage data for PoW.
#[derive(Encode, Decode, Clone, Debug, Default)]
pub struct PowAux {
/// Difficulty of the current block.
pub difficulty: Difficulty,
/// Total difficulty up to current block.
pub total_difficulty: Difficulty,
}
impl PowAux where
Difficulty: Decode + Default,
{
/// Read the auxiliary from client.
pub fn read(client: &C, hash: &B::Hash) -> Result> {
let key = aux_key(&hash);
match client.get_aux(&key).map_err(Error::Client)? {
Some(bytes) => Self::decode(&mut &bytes[..]).map_err(Error::Codec),
None => Ok(Self::default()),
}
}
}
/// Algorithm used for proof of work.
pub trait PowAlgorithm {
/// Difficulty for the algorithm.
type Difficulty: TotalDifficulty + Default + Encode + Decode + Ord + Clone + Copy;
/// Get the next block's difficulty.
///
/// This function will be called twice during the import process, so the implementation
/// should be properly cached.
fn difficulty(&self, parent: B::Hash) -> Result>;
/// Verify that the seal is valid against given pre hash when parent block is not yet imported.
///
/// None means that preliminary verify is not available for this algorithm.
fn preliminary_verify(
&self,
_pre_hash: &B::Hash,
_seal: &Seal,
) -> Result