// Copyright 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 .
//! Authorship tracking for SRML runtimes.
//!
//! This tracks the current author of the block and recent uncles.
#![cfg_attr(not(feature = "std"), no_std)]
use rstd::prelude::*;
use rstd::collections::btree_set::BTreeSet;
use srml_support::{decl_module, decl_storage, for_each_tuple, StorageValue};
use srml_support::traits::{FindAuthor, VerifySeal, Get};
use srml_support::dispatch::Result as DispatchResult;
use parity_codec::{Encode, Decode};
use system::ensure_none;
use primitives::traits::{SimpleArithmetic, Header as HeaderT, One, Zero};
pub trait Trait: system::Trait {
/// Find the author of a block.
type FindAuthor: FindAuthor;
/// The number of blocks back we should accept uncles.
/// This means that we will deal with uncle-parents that are
/// `UncleGenerations + 1` before `now`.
type UncleGenerations: Get;
/// A filter for uncles within a block. This is for implementing
/// further constraints on what uncles can be included, other than their ancestry.
///
/// For PoW, as long as the seals are checked, there is no need to use anything
/// but the `VerifySeal` implementation as the filter. This is because the cost of making many equivocating
/// uncles is high.
///
/// For PoS, there is no such limitation, so a further constraint must be imposed
/// beyond a seal check in order to prevent an arbitrary number of
/// equivocating uncles from being included.
///
/// The `OnePerAuthorPerHeight` filter is good for many slot-based PoS
/// engines.
type FilterUncle: FilterUncle;
/// An event handler for authored blocks.
type EventHandler: EventHandler;
}
/// An event handler for the authorship module. There is a dummy implementation
/// for `()`, which does nothing.
pub trait EventHandler {
/// Note that the given account ID is the author of the current block.
fn note_author(author: Author);
/// Note that the given account ID authored the given uncle, and how many
/// blocks older than the current block it is (age >= 0, so siblings are allowed)
fn note_uncle(author: Author, age: BlockNumber);
}
macro_rules! impl_event_handler {
() => (
impl EventHandler for () {
fn note_author(_author: A) { }
fn note_uncle(_author: A, _age: B) { }
}
);
( $($t:ident)* ) => {
impl),*>
EventHandler for ($($t,)*)
{
fn note_author(author: Author) {
$($t::note_author(author.clone());)*
}
fn note_uncle(author: Author, age: BlockNumber) {
$($t::note_uncle(author.clone(), age.clone());)*
}
}
}
}
for_each_tuple!(impl_event_handler);
/// Additional filtering on uncles that pass preliminary ancestry checks.
///
/// This should do work such as checking seals
pub trait FilterUncle {
/// An accumulator of data about uncles included.
///
/// In practice, this is used to validate uncles against others in the same block.
type Accumulator: Default;
/// Do additional filtering on a seal-checked uncle block, with the accumulated
/// filter.
fn filter_uncle(header: &Header, acc: Self::Accumulator)
-> Result<(Option, Self::Accumulator), &'static str>;
}
impl FilterUncle for () {
type Accumulator = ();
fn filter_uncle(_: &H, acc: Self::Accumulator)
-> Result<(Option, Self::Accumulator), &'static str>
{
Ok((None, acc))
}
}
/// A filter on uncles which verifies seals and does no additional checks.
/// This is well-suited to consensus modes such as PoW where the cost of
/// equivocating is high.
pub struct SealVerify(rstd::marker::PhantomData);
impl> FilterUncle
for SealVerify
{
type Accumulator = ();
fn filter_uncle(header: &Header, _acc: ())
-> Result<(Option, ()), &'static str>
{
T::verify_seal(header).map(|author| (author, ()))
}
}
/// A filter on uncles which verifies seals and ensures that there is only
/// one uncle included per author per height.
///
/// This does O(n log n) work in the number of uncles included.
pub struct OnePerAuthorPerHeight(rstd::marker::PhantomData<(T, N)>);
impl FilterUncle
for OnePerAuthorPerHeight
where
Header: HeaderT + PartialEq,
Header::Number: Ord,
Author: Clone + PartialEq + Ord,
T: VerifySeal,
{
type Accumulator = BTreeSet<(Header::Number, Author)>;
fn filter_uncle(header: &Header, mut acc: Self::Accumulator)
-> Result<(Option, Self::Accumulator), &'static str>
{
let author = T::verify_seal(header)?;
let number = header.number();
if let Some(ref author) = author {
if !acc.insert((number.clone(), author.clone())) {
return Err("more than one uncle per number per author included");
}
}
Ok((author, acc))
}
}
#[derive(Encode, Decode)]
#[cfg_attr(any(feature = "std", test), derive(PartialEq, Debug))]
enum UncleEntryItem {
InclusionHeight(BlockNumber),
Uncle(Hash, Option),
}
decl_storage! {
trait Store for Module as Authorship {
/// Uncles
Uncles: Vec>;
/// Author of current block.
Author: Option;
/// Whether uncles were already set in this block.
DidSetUncles: bool;
}
}
fn prune_old_uncles(
minimum_height: BlockNumber,
uncles: &mut Vec>
) where BlockNumber: SimpleArithmetic {
let prune_entries = uncles.iter().take_while(|item| match item {
UncleEntryItem::Uncle(_, _) => true,
UncleEntryItem::InclusionHeight(height) => height < &minimum_height,
});
let prune_index = prune_entries.count();
let _ = uncles.drain(..prune_index);
}
decl_module! {
pub struct Module for enum Call where origin: T::Origin {
fn on_initialize(now: T::BlockNumber) {
let uncle_generations = T::UncleGenerations::get();
let mut uncles = ::Uncles::get();
// prune uncles that are older than the allowed number of generations.
if uncle_generations <= now {
let minimum_height = now - uncle_generations;
prune_old_uncles(minimum_height, &mut uncles)
}
::DidSetUncles::put(false);
T::EventHandler::note_author(Self::author());
}
fn on_finalize() {
// ensure we never go to trie with these values.
::Author::kill();
::DidSetUncles::kill();
}
/// Provide a set of uncles.
fn set_uncles(origin, new_uncles: Vec) -> DispatchResult {
ensure_none(origin)?;
if ::DidSetUncles::get() {
return Err("Uncles already set in block.");
}
::DidSetUncles::put(true);
Self::verify_and_import_uncles(new_uncles)
}
}
}
impl Module {
/// Fetch the author of the block.
///
/// This is safe to invoke in `on_initialize` implementations, as well
/// as afterwards.
pub fn author() -> T::AccountId {
// Check the memoized storage value.
if let Some(author) = ::Author::get() {
return author;
}
let digest = >::digest();
let pre_runtime_digests = digest.logs.iter().filter_map(|d| d.as_pre_runtime());
if let Some(author) = T::FindAuthor::find_author(pre_runtime_digests) {
::Author::put(&author);
author
} else {
Default::default()
}
}
fn verify_and_import_uncles(new_uncles: Vec) -> DispatchResult {
let now = >::block_number();
let (minimum_height, maximum_height) = {
let uncle_generations = T::UncleGenerations::get();
let min = if now >= uncle_generations {
now - uncle_generations
} else {
Zero::zero()
};
(min, now)
};
let mut uncles = ::Uncles::get();
uncles.push(UncleEntryItem::InclusionHeight(now));
let mut acc: >::Accumulator = Default::default();
for uncle in new_uncles {
let hash = uncle.hash();
if uncle.number() < &One::one() {
return Err("uncle is genesis");
}
if uncle.number() > &maximum_height {
return Err("uncles too high in chain");
}
{
let parent_number = uncle.number().clone() - One::one();
let parent_hash = >::block_hash(&parent_number);
if &parent_hash != uncle.parent_hash() {
return Err("uncle parent not in chain");
}
}
if uncle.number() < &minimum_height {
return Err("uncle not recent enough to be included");
}
let duplicate = uncles.iter().find(|entry| match entry {
UncleEntryItem::InclusionHeight(_) => false,
UncleEntryItem::Uncle(h, _) => h == &hash,
}).is_some();
let in_chain = >::block_hash(uncle.number()) == hash;
if duplicate || in_chain { return Err("uncle already included") }
// check uncle validity.
let (author, temp_acc) = T::FilterUncle::filter_uncle(&uncle, acc)?;
acc = temp_acc;
T::EventHandler::note_uncle(
author.clone().unwrap_or_default(),
now - uncle.number().clone(),
);
uncles.push(UncleEntryItem::Uncle(hash, author));
}
::Uncles::put(&uncles);
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::*;
use runtime_io::with_externalities;
use substrate_primitives::{H256, Blake2Hasher};
use primitives::traits::{BlakeTwo256, IdentityLookup};
use primitives::testing::Header;
use primitives::generic::DigestItem;
use srml_support::{parameter_types, impl_outer_origin, ConsensusEngineId};
impl_outer_origin!{
pub enum Origin for Test {}
}
#[derive(Clone, Eq, PartialEq)]
pub struct Test;
parameter_types! {
pub const BlockHashCount: u64 = 250;
}
impl system::Trait for Test {
type Origin = Origin;
type Index = u64;
type BlockNumber = u64;
type Hash = H256;
type Hashing = BlakeTwo256;
type AccountId = u64;
type Lookup = IdentityLookup;
type Header = Header;
type Event = ();
type BlockHashCount = BlockHashCount;
}
impl Trait for Test {
type FindAuthor = AuthorGiven;
type UncleGenerations = UncleGenerations;
type FilterUncle = SealVerify;
type EventHandler = ();
}
type System = system::Module;
type Authorship = Module;
const TEST_ID: ConsensusEngineId = [1, 2, 3, 4];
pub struct AuthorGiven;
impl FindAuthor for AuthorGiven {
fn find_author<'a, I>(digests: I) -> Option
where I: 'a + IntoIterator-
{
for (id, data) in digests {
if id == TEST_ID {
return u64::decode(&mut &data[..]);
}
}
None
}
}
parameter_types! {
pub const UncleGenerations: u64 = 5;
}
pub struct VerifyBlock;
impl VerifySeal for VerifyBlock {
fn verify_seal(header: &Header) -> Result