// Copyright 2017-2019 Parity Technologies (UK) Ltd.
// This file is part of Substrate.
// Substrate 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.
// Substrate 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 Substrate. 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::thread;
use std::collections::HashMap;
use client::{
BlockOf, blockchain::{HeaderBackend, ProvideCache},
block_builder::api::BlockBuilder as BlockBuilderApi, backend::AuxStore,
well_known_cache_keys::Id as CacheKeyId,
};
use sr_primitives::{Justification, RuntimeString};
use sr_primitives::generic::{BlockId, Digest, DigestItem};
use sr_primitives::traits::{Block as BlockT, Header as HeaderT, ProvideRuntimeApi};
use srml_timestamp::{TimestampInherentData, InherentError as TIError};
use pow_primitives::{Seal, TotalDifficulty, POW_ENGINE_ID};
use primitives::H256;
use inherents::{InherentDataProviders, InherentData};
use consensus_common::{
BlockImportParams, BlockOrigin, ForkChoiceStrategy, SyncOracle, Environment, Proposer,
SelectChain, Error as ConsensusError
};
use consensus_common::import_queue::{BoxBlockImport, BasicQueue, Verifier};
use codec::{Encode, Decode};
use log::*;
#[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 = "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(client::error::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(RuntimeString),
#[display(fmt = "Checking inherents failed: {}", _0)]
CheckInherents(String),
Client(client::error::Error),
Codec(codec::Error),
Environment(String),
Runtime(RuntimeString)
}
impl std::convert::From> for String {
fn from(error: Error) -> String {
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: &H256) -> Vec {
POW_AUX_PREFIX.iter().chain(&hash[..])
.cloned().collect::>()
}
/// 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: &H256) -> 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.
fn difficulty(&self, parent: &BlockId) -> Result>;
/// Verify proof of work against the given difficulty.
fn verify(
&self,
parent: &BlockId,
pre_hash: &H256,
seal: &Seal,
difficulty: Self::Difficulty,
) -> Result>;
/// Mine a seal that satisfies the given difficulty.
fn mine(
&self,
parent: &BlockId,
pre_hash: &H256,
difficulty: Self::Difficulty,
round: u32,
) -> Result