// 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,
};
use sr_primitives::Justification;
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::{Difficulty, Seal, POW_ENGINE_ID};
use primitives::H256;
use inherents::{InherentDataProviders, InherentData};
use consensus_common::{
BlockImportParams, BlockOrigin, ForkChoiceStrategy,
well_known_cache_keys::Id as CacheKeyId, Environment, Proposer,
};
use consensus_common::import_queue::{BoxBlockImport, BasicQueue, Verifier};
use codec::{Encode, Decode};
use log::*;
/// 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 {
/// Total difficulty.
pub total_difficulty: Difficulty,
}
impl PowAux {
/// 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(|e| format!("{:?}", e))? {
Some(bytes) => PowAux::decode(&mut &bytes[..]).map_err(|e| format!("{:?}", e)),
None => Ok(PowAux::default()),
}
}
}
/// Algorithm used for proof of work.
pub trait PowAlgorithm {
/// 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: Difficulty,
) -> Result;
/// Mine a seal that satisfy the given difficulty.
fn mine(
&self,
parent: &BlockId,
pre_hash: &H256,
seed: &H256,
difficulty: Difficulty,
round: u32,
) -> Result