Files
pezkuwi-subxt/substrate/core/finality-grandpa/primitives/src/lib.rs
T
Gavin Wood 1a524b8207 Refactor key management (#3296)
* Add Call type to extensible transactions.

Cleanup some naming

* Merge Resource and BlockExhausted into just Exhausted

* Fix

* Another fix

* Call

* Some fixes

* Fix srml tests.

* Fix all tests.

* Refactor crypto so each application of it has its own type.

* Introduce new AuthorityProvider API into Aura

This will eventually allow for dynamic determination of authority
keys and avoid having to set them directly on CLI.

* Introduce authority determinator for Babe.

Experiment with modular consensus API.

* Work in progress to introduce KeyTypeId and avoid polluting API
with validator IDs

* Finish up drafting imonline

* Rework offchain workers API.

* Rework API implementation.

* Make it compile for wasm, simplify app_crypto.

* Fix compilation of im-online.

* Fix compilation of im-online.

* Fix more compilation errors.

* Make it compile.

* Fixing tests.

* Rewrite `keystore`

* Fix session tests

* Bring back `TryFrom`'s'

* Fix `srml-grandpa`

* Fix `srml-aura`

* Fix consensus babe

* More fixes

* Make service generate keys from dev_seed

* Build fixes

* Remove offchain tests

* More fixes and cleanups

* Fixes finality grandpa

* Fix `consensus-aura`

* Fix cli

* Fix `node-cli`

* Fix chain_spec builder

* Fix doc tests

* Add authority getter for grandpa.

* Test fix

* Fixes

* Make keystore accessible from the runtime

* Move app crypto to its own crate

* Update `Cargo.lock`

* Make the crypto stuff usable from the runtime

* Adds some runtime crypto tests

* Use last finalized block for grandpa authority

* Fix warning

* Adds `SessionKeys` runtime api

* Remove `FinalityPair` and `ConsensusPair`

* Minor governance tweaks to get it inline with docs.

* Make the governance be up to date with the docs.

* Build fixes.

* Generate the inital session keys

* Failing keystore is a hard error

* Make babe work again

* Fix grandpa

* Fix tests

* Disable `keystore` in consensus critical stuff

* Build fix.

* ImOnline supports multiple authorities at once.

* Update core/application-crypto/src/ed25519.rs

* Merge branch 'master' into gav-in-progress

* Remove unneeded code for now.

* Some `session` testing

* Support querying the public keys

* Cleanup offchain

* Remove warnings

* More cleanup

* Apply suggestions from code review

Co-Authored-By: Benjamin Kampmann <ben.kampmann@googlemail.com>

* More cleanups

* JSONRPC API for setting keys.

Also, rename traits::KeyStore* -> traits::BareCryptoStore*

* Bad merge

* Fix integration tests

* Fix test build

* Test fix

* Fixes

* Warnings

* Another warning

* Bump version.
2019-08-07 20:47:48 +02:00

208 lines
7.4 KiB
Rust

// Copyright 2018-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 <http://www.gnu.org/licenses/>.
//! Primitives for GRANDPA integration, suitable for WASM compilation.
#![cfg_attr(not(feature = "std"), no_std)]
#[cfg(not(feature = "std"))]
extern crate alloc;
#[cfg(feature = "std")]
use serde::Serialize;
use codec::{Encode, Decode, Codec};
use sr_primitives::{ConsensusEngineId, traits::{DigestFor, NumberFor}};
use client::decl_runtime_apis;
use rstd::vec::Vec;
mod app {
use app_crypto::{app_crypto, key_types::GRANDPA, ed25519};
app_crypto!(ed25519, GRANDPA);
}
/// The grandpa crypto scheme defined via the keypair type.
#[cfg(feature = "std")]
pub type AuthorityPair = app::Pair;
/// Identity of a Grandpa authority.
pub type AuthorityId = app::Public;
/// Signature for a Grandpa authority.
pub type AuthoritySignature = app::Signature;
/// The `ConsensusEngineId` of GRANDPA.
pub const GRANDPA_ENGINE_ID: ConsensusEngineId = *b"FRNK";
/// The weight of an authority.
pub type AuthorityWeight = u64;
/// The index of an authority.
pub type AuthorityIndex = u64;
/// A scheduled change of authority set.
#[cfg_attr(feature = "std", derive(Debug, Serialize))]
#[derive(Clone, Eq, PartialEq, Encode, Decode)]
pub struct ScheduledChange<N> {
/// The new authorities after the change, along with their respective weights.
pub next_authorities: Vec<(AuthorityId, AuthorityWeight)>,
/// The number of blocks to delay.
pub delay: N,
}
/// An consensus log item for GRANDPA.
#[cfg_attr(feature = "std", derive(Serialize, Debug))]
#[derive(Decode, Encode, PartialEq, Eq, Clone)]
pub enum ConsensusLog<N: Codec> {
/// Schedule an authority set change.
///
/// Precedence towards earlier or later digest items can be given
/// based on the rules of the chain.
///
/// No change should be scheduled if one is already and the delay has not
/// passed completely.
///
/// This should be a pure function: i.e. as long as the runtime can interpret
/// the digest type it should return the same result regardless of the current
/// state.
#[codec(index = "1")]
ScheduledChange(ScheduledChange<N>),
/// Force an authority set change.
///
/// Forced changes are applied after a delay of _imported_ blocks,
/// while pending changes are applied after a delay of _finalized_ blocks.
///
/// Precedence towards earlier or later digest items can be given
/// based on the rules of the chain.
///
/// No change should be scheduled if one is already and the delay has not
/// passed completely.
///
/// This should be a pure function: i.e. as long as the runtime can interpret
/// the digest type it should return the same result regardless of the current
/// state.
#[codec(index = "2")]
ForcedChange(N, ScheduledChange<N>),
/// Note that the authority with given index is disabled until the next change.
#[codec(index = "3")]
OnDisabled(AuthorityIndex),
/// A signal to pause the current authority set after the given delay.
/// After finalizing the block at _delay_ the authorities should stop voting.
#[codec(index = "4")]
Pause(N),
/// A signal to resume the current authority set after the given delay.
/// After authoring the block at _delay_ the authorities should resume voting.
#[codec(index = "5")]
Resume(N),
}
impl<N: Codec> ConsensusLog<N> {
/// Try to cast the log entry as a contained signal.
pub fn try_into_change(self) -> Option<ScheduledChange<N>> {
match self {
ConsensusLog::ScheduledChange(change) => Some(change),
_ => None,
}
}
/// Try to cast the log entry as a contained forced signal.
pub fn try_into_forced_change(self) -> Option<(N, ScheduledChange<N>)> {
match self {
ConsensusLog::ForcedChange(median, change) => Some((median, change)),
_ => None,
}
}
/// Try to cast the log entry as a contained pause signal.
pub fn try_into_pause(self) -> Option<N> {
match self {
ConsensusLog::Pause(delay) => Some(delay),
_ => None,
}
}
/// Try to cast the log entry as a contained resume signal.
pub fn try_into_resume(self) -> Option<N> {
match self {
ConsensusLog::Resume(delay) => Some(delay),
_ => None,
}
}
}
/// WASM function call to check for pending changes.
pub const PENDING_CHANGE_CALL: &str = "grandpa_pending_change";
/// WASM function call to get current GRANDPA authorities.
pub const AUTHORITIES_CALL: &str = "grandpa_authorities";
decl_runtime_apis! {
/// APIs for integrating the GRANDPA finality gadget into runtimes.
/// This should be implemented on the runtime side.
///
/// This is primarily used for negotiating authority-set changes for the
/// gadget. GRANDPA uses a signaling model of changing authority sets:
/// changes should be signaled with a delay of N blocks, and then automatically
/// applied in the runtime after those N blocks have passed.
///
/// The consensus protocol will coordinate the handoff externally.
#[api_version(2)]
pub trait GrandpaApi {
/// Check a digest for pending changes.
/// Return `None` if there are no pending changes.
///
/// Precedence towards earlier or later digest items can be given
/// based on the rules of the chain.
///
/// No change should be scheduled if one is already and the delay has not
/// passed completely.
///
/// This should be a pure function: i.e. as long as the runtime can interpret
/// the digest type it should return the same result regardless of the current
/// state.
fn grandpa_pending_change(digest: &DigestFor<Block>)
-> Option<ScheduledChange<NumberFor<Block>>>;
/// Check a digest for forced changes.
/// Return `None` if there are no forced changes. Otherwise, return a
/// tuple containing the pending change and the median last finalized
/// block number at the time the change was signaled.
///
/// Added in version 2.
///
/// Forced changes are applied after a delay of _imported_ blocks,
/// while pending changes are applied after a delay of _finalized_ blocks.
///
/// Precedence towards earlier or later digest items can be given
/// based on the rules of the chain.
///
/// No change should be scheduled if one is already and the delay has not
/// passed completely.
///
/// This should be a pure function: i.e. as long as the runtime can interpret
/// the digest type it should return the same result regardless of the current
/// state.
fn grandpa_forced_change(digest: &DigestFor<Block>)
-> Option<(NumberFor<Block>, ScheduledChange<NumberFor<Block>>)>;
/// Get the current GRANDPA authorities and weights. This should not change except
/// for when changes are scheduled and the corresponding delay has passed.
///
/// When called at block B, it will return the set of authorities that should be
/// used to finalize descendants of this block (B+1, B+2, ...). The block B itself
/// is finalized by the authorities from block B-1.
fn grandpa_authorities() -> Vec<(AuthorityId, AuthorityWeight)>;
}
}