mirror of
https://github.com/pezkuwichain/pezkuwi-subxt.git
synced 2026-06-12 17:01:09 +00:00
Punish offline validators, aura-style (#1216)
* make offline-reporting infrastructure more generic * add a listener-trait for watching when the timestamp has been set * prevent inclusion of empty offline reports * add test for exclusion * generate aura-offline reports * ability to slash many times for being offline "multiple" times * Logic for punishing validators for missing aura steps * stub tests * pave way for verification of timestamp vs slot * alter aura import queue to wait for timestamp * check timestamp matches seal * do inherent check properly * service compiles * all tests compile * test srml-aura logic * aura tests pass * everything builds * some more final tweaks to block authorship for aura * switch to manual delays before step * restore substrate-consensus-aura to always std and address grumbles * update some state roots in executor tests * node-executor tests pass * get most tests passing * address grumbles
This commit is contained in:
committed by
GitHub
parent
dcc38fe45a
commit
6299b42a4d
@@ -642,6 +642,30 @@ fn apply_state_commit(transaction: &mut DBTransaction, commit: state_db::CommitS
|
||||
}
|
||||
}
|
||||
|
||||
impl<Block> client::backend::AuxStore for Backend<Block> where Block: BlockT<Hash=H256> {
|
||||
fn insert_aux<
|
||||
'a,
|
||||
'b: 'a,
|
||||
'c: 'a,
|
||||
I: IntoIterator<Item=&'a(&'c [u8], &'c [u8])>,
|
||||
D: IntoIterator<Item=&'a &'b [u8]>,
|
||||
>(&self, insert: I, delete: D) -> client::error::Result<()> {
|
||||
let mut transaction = DBTransaction::new();
|
||||
for (k, v) in insert {
|
||||
transaction.put(columns::AUX, k, v);
|
||||
}
|
||||
for k in delete {
|
||||
transaction.delete(columns::AUX, k);
|
||||
}
|
||||
self.storage.db.write(transaction).map_err(db_err)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn get_aux(&self, key: &[u8]) -> Result<Option<Vec<u8>>, client::error::Error> {
|
||||
Ok(self.storage.db.get(columns::AUX, key).map(|r| r.map(|v| v.to_vec())).map_err(db_err)?)
|
||||
}
|
||||
}
|
||||
|
||||
impl<Block> client::backend::Backend<Block, Blake2Hasher> for Backend<Block> where Block: BlockT<Hash=H256> {
|
||||
type BlockImportOperation = BlockImportOperation<Block, Blake2Hasher>;
|
||||
type Blockchain = BlockchainDb<Block>;
|
||||
@@ -883,24 +907,6 @@ impl<Block> client::backend::Backend<Block, Blake2Hasher> for Backend<Block> whe
|
||||
_ => Err(client::error::ErrorKind::UnknownBlock(format!("{:?}", block)).into()),
|
||||
}
|
||||
}
|
||||
|
||||
fn insert_aux<'a, 'b: 'a, 'c: 'a, I: IntoIterator<Item=&'a (&'c [u8], &'c [u8])>, D: IntoIterator<Item=&'a &'b [u8]>>
|
||||
(&self, insert: I, delete: D) -> Result<(), client::error::Error>
|
||||
{
|
||||
let mut transaction = DBTransaction::new();
|
||||
for (k, v) in insert {
|
||||
transaction.put(columns::AUX, k, v);
|
||||
}
|
||||
for k in delete {
|
||||
transaction.delete(columns::AUX, k);
|
||||
}
|
||||
self.storage.db.write(transaction).map_err(db_err)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn get_aux(&self, key: &[u8]) -> Result<Option<Vec<u8>>, client::error::Error> {
|
||||
Ok(self.storage.db.get(columns::AUX, key).map(|r| r.map(|v| v.to_vec())).map_err(db_err)?)
|
||||
}
|
||||
}
|
||||
|
||||
impl<Block> client::backend::LocalBackend<Block, Blake2Hasher> for Backend<Block>
|
||||
|
||||
@@ -79,6 +79,20 @@ pub trait BlockImportOperation<Block, H> where
|
||||
where I: IntoIterator<Item=(Vec<u8>, Option<Vec<u8>>)>;
|
||||
}
|
||||
|
||||
/// Provides access to an auxiliary database.
|
||||
pub trait AuxStore {
|
||||
/// Insert auxiliary data into key-value store. Deletions occur after insertions.
|
||||
fn insert_aux<
|
||||
'a,
|
||||
'b: 'a,
|
||||
'c: 'a,
|
||||
I: IntoIterator<Item=&'a(&'c [u8], &'c [u8])>,
|
||||
D: IntoIterator<Item=&'a &'b [u8]>,
|
||||
>(&self, insert: I, delete: D) -> error::Result<()>;
|
||||
/// Query auxiliary data from key-value store.
|
||||
fn get_aux(&self, key: &[u8]) -> error::Result<Option<Vec<u8>>>;
|
||||
}
|
||||
|
||||
/// Client backend. Manages the data layer.
|
||||
///
|
||||
/// Note on state pruning: while an object from `state_at` is alive, the state
|
||||
@@ -87,7 +101,7 @@ pub trait BlockImportOperation<Block, H> where
|
||||
///
|
||||
/// The same applies for live `BlockImportOperation`s: while an import operation building on a parent `P`
|
||||
/// is alive, the state for `P` should not be pruned.
|
||||
pub trait Backend<Block, H>: Send + Sync where
|
||||
pub trait Backend<Block, H>: AuxStore + Send + Sync where
|
||||
Block: BlockT,
|
||||
H: Hasher<Out=Block::Hash>,
|
||||
{
|
||||
@@ -117,10 +131,22 @@ pub trait Backend<Block, H>: Send + Sync where
|
||||
/// Attempts to revert the chain by `n` blocks. Returns the number of blocks that were
|
||||
/// successfully reverted.
|
||||
fn revert(&self, n: NumberFor<Block>) -> error::Result<NumberFor<Block>>;
|
||||
|
||||
/// Insert auxiliary data into key-value store.
|
||||
fn insert_aux<'a, 'b: 'a, 'c: 'a, I: IntoIterator<Item=&'a(&'c [u8], &'c [u8])>, D: IntoIterator<Item=&'a &'b [u8]>>(&self, insert: I, delete: D) -> error::Result<()>;
|
||||
fn insert_aux<
|
||||
'a,
|
||||
'b: 'a,
|
||||
'c: 'a,
|
||||
I: IntoIterator<Item=&'a(&'c [u8], &'c [u8])>,
|
||||
D: IntoIterator<Item=&'a &'b [u8]>,
|
||||
>(&self, insert: I, delete: D) -> error::Result<()>
|
||||
{
|
||||
AuxStore::insert_aux(self, insert, delete)
|
||||
}
|
||||
/// Query auxiliary data from key-value store.
|
||||
fn get_aux(&self, key: &[u8]) -> error::Result<Option<Vec<u8>>>;
|
||||
fn get_aux(&self, key: &[u8]) -> error::Result<Option<Vec<u8>>> {
|
||||
AuxStore::get_aux(self, key)
|
||||
}
|
||||
}
|
||||
|
||||
/// Mark for all Backend implementations, that are making use of state data, stored locally.
|
||||
|
||||
@@ -1170,6 +1170,27 @@ impl<B, E, Block, RA> BlockBody<Block> for Client<B, E, Block, RA>
|
||||
}
|
||||
}
|
||||
|
||||
impl<B, E, Block, RA> backend::AuxStore for Client<B, E, Block, RA>
|
||||
where
|
||||
B: backend::Backend<Block, Blake2Hasher>,
|
||||
E: CallExecutor<Block, Blake2Hasher>,
|
||||
Block: BlockT<Hash=H256>,
|
||||
{
|
||||
/// Insert auxiliary data into key-value store.
|
||||
fn insert_aux<
|
||||
'a,
|
||||
'b: 'a,
|
||||
'c: 'a,
|
||||
I: IntoIterator<Item=&'a(&'c [u8], &'c [u8])>,
|
||||
D: IntoIterator<Item=&'a &'b [u8]>,
|
||||
>(&self, insert: I, delete: D) -> error::Result<()> {
|
||||
::backend::AuxStore::insert_aux(&*self.backend, insert, delete)
|
||||
}
|
||||
/// Query auxiliary data from key-value store.
|
||||
fn get_aux(&self, key: &[u8]) -> error::Result<Option<Vec<u8>>> {
|
||||
::backend::AuxStore::get_aux(&*self.backend, key)
|
||||
}
|
||||
}
|
||||
#[cfg(test)]
|
||||
pub(crate) mod tests {
|
||||
use std::collections::HashMap;
|
||||
|
||||
@@ -498,6 +498,34 @@ where
|
||||
}
|
||||
}
|
||||
|
||||
impl<Block, H> backend::AuxStore for Backend<Block, H>
|
||||
where
|
||||
Block: BlockT,
|
||||
H: Hasher<Out=Block::Hash>,
|
||||
H::Out: HeapSizeOf + Ord,
|
||||
{
|
||||
fn insert_aux<
|
||||
'a,
|
||||
'b: 'a,
|
||||
'c: 'a,
|
||||
I: IntoIterator<Item=&'a(&'c [u8], &'c [u8])>,
|
||||
D: IntoIterator<Item=&'a &'b [u8]>,
|
||||
>(&self, insert: I, delete: D) -> error::Result<()> {
|
||||
let mut storage = self.blockchain.storage.write();
|
||||
for (k, v) in insert {
|
||||
storage.aux.insert(k.to_vec(), v.to_vec());
|
||||
}
|
||||
for k in delete {
|
||||
storage.aux.remove(*k);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn get_aux(&self, key: &[u8]) -> error::Result<Option<Vec<u8>>> {
|
||||
Ok(self.blockchain.storage.read().aux.get(key).cloned())
|
||||
}
|
||||
}
|
||||
|
||||
impl<Block, H> backend::Backend<Block, H> for Backend<Block, H>
|
||||
where
|
||||
Block: BlockT,
|
||||
@@ -578,21 +606,6 @@ where
|
||||
fn revert(&self, _n: NumberFor<Block>) -> error::Result<NumberFor<Block>> {
|
||||
Ok(As::sa(0))
|
||||
}
|
||||
|
||||
fn insert_aux<'a, 'b: 'a, 'c: 'a, I: IntoIterator<Item=&'a (&'c [u8], &'c [u8])>, D: IntoIterator<Item=&'a &'b [u8]>>(&self, insert: I, delete: D) -> error::Result<()> {
|
||||
let mut storage = self.blockchain.storage.write();
|
||||
for (k, v) in insert {
|
||||
storage.aux.insert(k.to_vec(), v.to_vec());
|
||||
}
|
||||
for k in delete {
|
||||
storage.aux.remove(*k);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn get_aux(&self, key: &[u8]) -> error::Result<Option<Vec<u8>>> {
|
||||
Ok(self.blockchain.storage.read().aux.get(key).cloned())
|
||||
}
|
||||
}
|
||||
|
||||
impl<Block, H> backend::LocalBackend<Block, H> for Backend<Block, H>
|
||||
|
||||
@@ -70,6 +70,22 @@ impl<S, F> Backend<S, F> {
|
||||
}
|
||||
}
|
||||
|
||||
impl<S, F> ::backend::AuxStore for Backend<S, F> {
|
||||
fn insert_aux<
|
||||
'a,
|
||||
'b: 'a,
|
||||
'c: 'a,
|
||||
I: IntoIterator<Item=&'a(&'c [u8], &'c [u8])>,
|
||||
D: IntoIterator<Item=&'a &'b [u8]>,
|
||||
>(&self, _insert: I, _delete: D) -> ClientResult<()> {
|
||||
Err(ClientErrorKind::NotAvailableOnLightClient.into())
|
||||
}
|
||||
|
||||
fn get_aux(&self, _key: &[u8]) -> ClientResult<Option<Vec<u8>>> {
|
||||
Err(ClientErrorKind::NotAvailableOnLightClient.into())
|
||||
}
|
||||
}
|
||||
|
||||
impl<S, F, Block, H> ClientBackend<Block, H> for Backend<S, F> where
|
||||
Block: BlockT,
|
||||
S: BlockchainStorage<Block>,
|
||||
@@ -131,14 +147,6 @@ impl<S, F, Block, H> ClientBackend<Block, H> for Backend<S, F> where
|
||||
fn revert(&self, _n: NumberFor<Block>) -> ClientResult<NumberFor<Block>> {
|
||||
Err(ClientErrorKind::NotAvailableOnLightClient.into())
|
||||
}
|
||||
|
||||
fn insert_aux<'a, 'b: 'a, 'c: 'a, I: IntoIterator<Item=&'a (&'c [u8], &'c [u8])>, D: IntoIterator<Item=&'a &'b [u8]>>(&self, _insert: I, _delete: D) -> ClientResult<()> {
|
||||
Err(ClientErrorKind::NotAvailableOnLightClient.into())
|
||||
}
|
||||
|
||||
fn get_aux(&self, _key: &[u8]) -> ClientResult<Option<Vec<u8>>> {
|
||||
Err(ClientErrorKind::NotAvailableOnLightClient.into())
|
||||
}
|
||||
}
|
||||
|
||||
impl<S, F, Block, H> RemoteBackend<Block, H> for Backend<S, F>
|
||||
|
||||
@@ -2,41 +2,33 @@
|
||||
name = "substrate-consensus-aura"
|
||||
version = "0.1.0"
|
||||
authors = ["Parity Technologies <admin@parity.io>"]
|
||||
description = "Rhododendron Round-Based consensus-algorithm for substrate"
|
||||
description = "Aura consensus algorithm for substrate"
|
||||
|
||||
[dependencies]
|
||||
futures = "0.1.17"
|
||||
parity-codec = { version = "2.1" }
|
||||
substrate-consensus-common = { path = "../common" }
|
||||
parity-codec = "2.1"
|
||||
substrate-client = { path = "../../client" }
|
||||
substrate-primitives = { path = "../../primitives" }
|
||||
substrate-network = { path = "../../network" }
|
||||
srml-support = { path = "../../../srml/support" }
|
||||
sr-primitives = { path = "../../sr-primitives" }
|
||||
sr-version = { path = "../../sr-version" }
|
||||
sr-io = { path = "../../sr-io" }
|
||||
substrate-consensus-aura-primitives = { path = "primitives" }
|
||||
|
||||
srml-consensus = { path = "../../../srml/consensus" }
|
||||
futures = "0.1.17"
|
||||
tokio = "0.1.7"
|
||||
parking_lot = "0.4"
|
||||
error-chain = "0.12"
|
||||
log = "0.3"
|
||||
substrate-consensus-common = { path = "../common" }
|
||||
substrate-network = { path = "../../network" }
|
||||
|
||||
[dev-dependencies]
|
||||
substrate-keyring = { path = "../../keyring" }
|
||||
substrate-executor = { path = "../../executor" }
|
||||
substrate-service = { path = "../../service" }
|
||||
substrate-test-client = { path = "../../test-client" }
|
||||
env_logger = { version = "0.4" }
|
||||
env_logger = "0.4"
|
||||
|
||||
[target.'cfg(test)'.dependencies]
|
||||
substrate-network = { path = "../../network", features = ["test-helpers"] }
|
||||
|
||||
[features]
|
||||
default = ["std"]
|
||||
std = [
|
||||
"substrate-primitives/std",
|
||||
"srml-support/std",
|
||||
"sr-primitives/std",
|
||||
"sr-version/std",
|
||||
]
|
||||
|
||||
substrate-network = { path = "../../network", features = ["test-helpers"], optional = true }
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
[package]
|
||||
name = "substrate-consensus-aura-primitives"
|
||||
version = "0.1.0"
|
||||
authors = ["Parity Technologies <admin@parity.io>"]
|
||||
description = "Primitives for Aura consensus"
|
||||
|
||||
[dependencies]
|
||||
parity-codec = { version = "2.1", default-features = false }
|
||||
substrate-client = { path = "../../../client", default-features = false }
|
||||
substrate-primitives = { path = "../../../primitives", default-features = false }
|
||||
srml-support = { path = "../../../../srml/support", default-features = false }
|
||||
sr-primitives = { path = "../../../sr-primitives", default-features = false }
|
||||
sr-version = { path = "../../../sr-version", default-features = false }
|
||||
sr-io = { path = "../../../sr-io", default-features = false }
|
||||
|
||||
[features]
|
||||
default = ["std"]
|
||||
std = [
|
||||
"parity-codec/std",
|
||||
"substrate-client/std",
|
||||
"substrate-primitives/std",
|
||||
"srml-support/std",
|
||||
"sr-primitives/std",
|
||||
"sr-version/std",
|
||||
"sr-io/std",
|
||||
]
|
||||
@@ -0,0 +1,50 @@
|
||||
// Copyright 2017-2018 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 Aura.
|
||||
|
||||
#![cfg_attr(not(feature = "std"), no_std)]
|
||||
|
||||
extern crate parity_codec as codec;
|
||||
extern crate substrate_client as client;
|
||||
extern crate substrate_primitives as primitives;
|
||||
extern crate srml_support as runtime_support;
|
||||
extern crate sr_io as runtime_io;
|
||||
extern crate sr_primitives as runtime_primitives;
|
||||
|
||||
/// The ApiIds for Aura authorship API.
|
||||
pub mod id {
|
||||
use client::runtime_api::ApiId;
|
||||
|
||||
/// ApiId for the AuraApi trait.
|
||||
pub const AURA_API: ApiId = *b"aura_api";
|
||||
}
|
||||
|
||||
/// Runtime-APIs
|
||||
pub mod api {
|
||||
use client::decl_runtime_apis;
|
||||
decl_runtime_apis! {
|
||||
/// API necessary for block authorship with aura.
|
||||
pub trait AuraApi {
|
||||
/// Return the slot duration in seconds for Aura.
|
||||
/// Currently, only the value provided by this type at genesis
|
||||
/// will be used.
|
||||
///
|
||||
/// Dynamic slot duration may be supported in the future.
|
||||
fn slot_duration() -> u64;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -27,15 +27,22 @@
|
||||
//! far in the future they are.
|
||||
|
||||
extern crate parity_codec as codec;
|
||||
extern crate substrate_consensus_common as consensus_common;
|
||||
extern crate substrate_client as client;
|
||||
extern crate substrate_primitives as primitives;
|
||||
extern crate substrate_network as network;
|
||||
extern crate srml_support as runtime_support;
|
||||
extern crate sr_primitives as runtime_primitives;
|
||||
extern crate sr_version as runtime_version;
|
||||
extern crate sr_io as runtime_io;
|
||||
extern crate sr_primitives as runtime_primitives;
|
||||
extern crate substrate_consensus_aura_primitives as aura_primitives;
|
||||
|
||||
extern crate substrate_consensus_common as consensus_common;
|
||||
extern crate tokio;
|
||||
extern crate sr_version as runtime_version;
|
||||
extern crate substrate_network as network;
|
||||
extern crate futures;
|
||||
extern crate parking_lot;
|
||||
|
||||
#[macro_use]
|
||||
extern crate log;
|
||||
|
||||
#[cfg(test)]
|
||||
extern crate substrate_keyring as keyring;
|
||||
@@ -46,12 +53,7 @@ extern crate substrate_test_client as test_client;
|
||||
#[cfg(test)]
|
||||
extern crate env_logger;
|
||||
|
||||
extern crate parking_lot;
|
||||
|
||||
#[macro_use]
|
||||
extern crate log;
|
||||
|
||||
extern crate futures;
|
||||
pub use aura_primitives::*;
|
||||
|
||||
use std::sync::Arc;
|
||||
use std::time::{Duration, Instant};
|
||||
@@ -59,14 +61,16 @@ use std::time::{Duration, Instant};
|
||||
use codec::Encode;
|
||||
use consensus_common::{Authorities, BlockImport, Environment, Proposer};
|
||||
use client::ChainHead;
|
||||
use client::block_builder::api::BlockBuilder as BlockBuilderApi;
|
||||
use consensus_common::{ImportBlock, BlockOrigin};
|
||||
use runtime_primitives::{generic, generic::BlockId, Justification};
|
||||
use runtime_primitives::traits::{Block, Header, Digest, DigestItemFor};
|
||||
use runtime_primitives::{generic, generic::BlockId, Justification, BasicInherentData};
|
||||
use runtime_primitives::traits::{Block, Header, Digest, DigestItemFor, ProvideRuntimeApi};
|
||||
use network::import_queue::{Verifier, BasicQueue};
|
||||
use primitives::{AuthorityId, ed25519};
|
||||
|
||||
use futures::{Stream, Future, IntoFuture, future::{self, Either}};
|
||||
use tokio::timer::Interval;
|
||||
use tokio::timer::{Delay, Timeout};
|
||||
use api::AuraApi;
|
||||
|
||||
pub use consensus_common::SyncOracle;
|
||||
|
||||
@@ -82,15 +86,6 @@ pub trait Network: Clone {
|
||||
fn send_message(&self, slot: u64, message: Vec<u8>);
|
||||
}
|
||||
|
||||
/// Configuration for Aura consensus.
|
||||
#[derive(Clone)]
|
||||
pub struct Config {
|
||||
/// The local authority keypair. Can be none if this is just an observer.
|
||||
pub local_key: Option<Arc<ed25519::Pair>>,
|
||||
/// The slot duration in seconds.
|
||||
pub slot_duration: u64
|
||||
}
|
||||
|
||||
/// Get slot author for given block along with authorities.
|
||||
fn slot_author(slot_num: u64, authorities: &[AuthorityId]) -> Option<AuthorityId> {
|
||||
if authorities.is_empty() { return None }
|
||||
@@ -115,6 +110,13 @@ fn duration_now() -> Option<Duration> {
|
||||
}).ok()
|
||||
}
|
||||
|
||||
fn timestamp_and_slot_now(slot_duration: u64) -> Option<(u64, u64)> {
|
||||
duration_now().map(|s| {
|
||||
let s = s.as_secs();
|
||||
(s, s / slot_duration)
|
||||
})
|
||||
}
|
||||
|
||||
/// Get the slot for now.
|
||||
fn slot_now(slot_duration: u64) -> Option<u64> {
|
||||
duration_now().map(|s| s.as_secs() / slot_duration)
|
||||
@@ -145,15 +147,56 @@ impl<Hash, AuthorityId> CompatibleDigestItem for generic::DigestItem<Hash, Autho
|
||||
}
|
||||
}
|
||||
|
||||
/// Start the aura worker. This should be run in a tokio runtime.
|
||||
pub fn start_aura<B, C, E, I, SO, Error>(
|
||||
config: Config,
|
||||
/// Start the aura worker in a separate thread.
|
||||
pub fn start_aura_thread<B, C, E, I, SO, Error>(
|
||||
slot_duration: SlotDuration,
|
||||
local_key: Arc<ed25519::Pair>,
|
||||
client: Arc<C>,
|
||||
block_import: Arc<I>,
|
||||
env: Arc<E>,
|
||||
sync_oracle: SO,
|
||||
)
|
||||
-> impl Future<Item=(),Error=()> where
|
||||
) where
|
||||
B: Block + 'static,
|
||||
C: Authorities<B> + ChainHead<B> + Send + Sync + 'static,
|
||||
E: Environment<B, Error=Error> + Send + Sync + 'static,
|
||||
E::Proposer: Proposer<B, Error=Error> + 'static,
|
||||
I: BlockImport<B> + Send + Sync + 'static,
|
||||
Error: From<C::Error> + From<I::Error> + 'static,
|
||||
SO: SyncOracle + Send + Clone + 'static,
|
||||
DigestItemFor<B>: CompatibleDigestItem + 'static,
|
||||
Error: ::std::error::Error + Send + From<::consensus_common::Error> + 'static,
|
||||
{
|
||||
use tokio::runtime::current_thread::Runtime;
|
||||
|
||||
::std::thread::spawn(move || {
|
||||
let mut runtime = match Runtime::new() {
|
||||
Ok(r) => r,
|
||||
Err(e) => {
|
||||
warn!("Unable to start authorship: {:?}", e);
|
||||
return;
|
||||
}
|
||||
};
|
||||
|
||||
runtime.block_on(start_aura(
|
||||
slot_duration,
|
||||
local_key,
|
||||
client,
|
||||
block_import,
|
||||
env,
|
||||
sync_oracle,
|
||||
)).expect("aura authorship never returns error; qed");
|
||||
});
|
||||
}
|
||||
|
||||
/// Start the aura worker. The returned future should be run in a tokio runtime.
|
||||
pub fn start_aura<B, C, E, I, SO, Error>(
|
||||
slot_duration: SlotDuration,
|
||||
local_key: Arc<ed25519::Pair>,
|
||||
client: Arc<C>,
|
||||
block_import: Arc<I>,
|
||||
env: Arc<E>,
|
||||
sync_oracle: SO,
|
||||
) -> impl Future<Item=(),Error=()> where
|
||||
B: Block,
|
||||
C: Authorities<B> + ChainHead<B>,
|
||||
E: Environment<B, Error=Error>,
|
||||
@@ -165,99 +208,138 @@ pub fn start_aura<B, C, E, I, SO, Error>(
|
||||
Error: ::std::error::Error + Send + 'static + From<::consensus_common::Error>,
|
||||
{
|
||||
let make_authorship = move || {
|
||||
let config = config.clone();
|
||||
use futures::future;
|
||||
|
||||
let client = client.clone();
|
||||
let pair = local_key.clone();
|
||||
let block_import = block_import.clone();
|
||||
let env = env.clone();
|
||||
let sync_oracle = sync_oracle.clone();
|
||||
let SlotDuration(slot_duration) = slot_duration;
|
||||
|
||||
let local_keys = config.local_key.map(|pair| (pair.public(), pair));
|
||||
let slot_duration = config.slot_duration;
|
||||
let mut last_authored_slot = 0;
|
||||
let next_slot_start = duration_now().map(|now| {
|
||||
fn time_until_next(now: Duration, slot_duration: u64) -> Duration {
|
||||
let remaining_full_secs = slot_duration - (now.as_secs() % slot_duration) - 1;
|
||||
let remaining_nanos = 1_000_000_000 - now.subsec_nanos();
|
||||
Instant::now() + Duration::new(remaining_full_secs, remaining_nanos)
|
||||
}).unwrap_or_else(|| Instant::now());
|
||||
Duration::new(remaining_full_secs, remaining_nanos)
|
||||
};
|
||||
|
||||
Interval::new(next_slot_start, Duration::from_secs(slot_duration))
|
||||
.filter(move |_| !sync_oracle.is_major_syncing()) // only propose when we are not syncing.
|
||||
.filter_map(move |_| local_keys.clone()) // skip if not authoring.
|
||||
.map_err(|e| debug!(target: "aura", "Faulty timer: {:?}", e))
|
||||
.for_each(move |(public_key, key)| {
|
||||
use futures::future;
|
||||
// rather than use an interval, we schedule our waits ourselves
|
||||
future::loop_fn((), move |()| {
|
||||
let next_slot_start = duration_now()
|
||||
.map(|now| Instant::now() + time_until_next(now, slot_duration))
|
||||
.unwrap_or_else(|| Instant::now());
|
||||
|
||||
let slot_num = match slot_now(slot_duration) {
|
||||
Some(n) => n,
|
||||
None => return Either::B(future::err(())),
|
||||
};
|
||||
let client = client.clone();
|
||||
let pair = pair.clone();
|
||||
let block_import = block_import.clone();
|
||||
let env = env.clone();
|
||||
let sync_oracle = sync_oracle.clone();
|
||||
let public_key = pair.public();
|
||||
|
||||
if last_authored_slot >= slot_num { return Either::B(future::ok(())) }
|
||||
last_authored_slot = slot_num;
|
||||
|
||||
let chain_head = match client.best_block_header() {
|
||||
Ok(x) => x,
|
||||
Err(e) => {
|
||||
warn!(target:"aura", "Unable to author block in slot {}. no best block header: {:?}", slot_num, e);
|
||||
return Either::B(future::ok(()))
|
||||
}
|
||||
};
|
||||
|
||||
let authorities = match client.authorities(&BlockId::Hash(chain_head.hash())){
|
||||
Ok(authorities) => authorities,
|
||||
Err(e) => {
|
||||
warn!("Unable to fetch authorities at block {:?}: {:?}", chain_head.hash(), e);
|
||||
Delay::new(next_slot_start)
|
||||
.map_err(|e| debug!(target: "aura", "Faulty timer: {:?}", e))
|
||||
.and_then(move |_| {
|
||||
// only propose when we are not syncing.
|
||||
if sync_oracle.is_major_syncing() {
|
||||
debug!(target: "aura", "Skipping proposal slot due to sync.");
|
||||
return Either::B(future::ok(()));
|
||||
}
|
||||
};
|
||||
|
||||
let proposal_work = match slot_author(slot_num, &authorities) {
|
||||
None => return Either::B(future::ok(())),
|
||||
Some(author) => if author.0 == public_key.0 {
|
||||
// we are the slot author. make a block and sign it.
|
||||
let proposer = match env.init(&chain_head, &authorities, key.clone()) {
|
||||
Ok(p) => p,
|
||||
Err(e) => {
|
||||
warn!("Unable to author block in slot {:?}: {:?}", slot_num, e);
|
||||
return Either::B(future::ok(()))
|
||||
}
|
||||
};
|
||||
let pair = pair.clone();
|
||||
let (timestamp, slot_num) = match timestamp_and_slot_now(slot_duration) {
|
||||
Some(n) => n,
|
||||
None => return Either::B(future::err(())),
|
||||
};
|
||||
|
||||
proposer.propose().into_future()
|
||||
} else {
|
||||
return Either::B(future::ok(()));
|
||||
}
|
||||
};
|
||||
|
||||
let block_import = block_import.clone();
|
||||
Either::A(proposal_work
|
||||
.map(move |b| {
|
||||
let (header, body) = b.deconstruct();
|
||||
let pre_hash = header.hash();
|
||||
let parent_hash = header.parent_hash().clone();
|
||||
|
||||
// sign the pre-sealed hash of the block and then
|
||||
// add it to a digest item.
|
||||
let to_sign = (slot_num, pre_hash).encode();
|
||||
let signature = key.sign(&to_sign[..]);
|
||||
let item = <DigestItemFor<B> as CompatibleDigestItem>::aura_seal(slot_num, signature);
|
||||
let import_block = ImportBlock {
|
||||
origin: BlockOrigin::Own,
|
||||
header,
|
||||
justification: None,
|
||||
post_digests: vec![item],
|
||||
body: Some(body),
|
||||
finalized: false,
|
||||
auxiliary: Vec::new(),
|
||||
};
|
||||
|
||||
if let Err(e) = block_import.import_block(import_block, None) {
|
||||
warn!(target: "aura", "Error with block built on {:?}: {:?}", parent_hash, e);
|
||||
let chain_head = match client.best_block_header() {
|
||||
Ok(x) => x,
|
||||
Err(e) => {
|
||||
warn!(target:"aura", "Unable to author block in slot {}. \
|
||||
no best block header: {:?}", slot_num, e);
|
||||
return Either::B(future::ok(()))
|
||||
}
|
||||
})
|
||||
.map_err(|e| warn!("Failed to construct block: {:?}", e))
|
||||
)
|
||||
})
|
||||
};
|
||||
|
||||
let authorities = match client.authorities(&BlockId::Hash(chain_head.hash())) {
|
||||
Ok(authorities) => authorities,
|
||||
Err(e) => {
|
||||
warn!("Unable to fetch authorities at\
|
||||
block {:?}: {:?}", chain_head.hash(), e);
|
||||
return Either::B(future::ok(()));
|
||||
}
|
||||
};
|
||||
|
||||
let proposal_work = match slot_author(slot_num, &authorities) {
|
||||
None => return Either::B(future::ok(())),
|
||||
Some(author) => if author.0 == public_key.0 {
|
||||
debug!(target: "aura", "Starting authorship at slot {}; timestamp = {}",
|
||||
slot_num, timestamp);
|
||||
|
||||
// we are the slot author. make a block and sign it.
|
||||
let proposer = match env.init(&chain_head, &authorities, pair.clone()) {
|
||||
Ok(p) => p,
|
||||
Err(e) => {
|
||||
warn!("Unable to author block in slot {:?}: {:?}", slot_num, e);
|
||||
return Either::B(future::ok(()))
|
||||
}
|
||||
};
|
||||
|
||||
// deadline our production to approx. the end of the
|
||||
// slot
|
||||
Timeout::new(
|
||||
proposer.propose().into_future(),
|
||||
time_until_next(Duration::from_secs(timestamp), slot_duration),
|
||||
)
|
||||
} else {
|
||||
return Either::B(future::ok(()));
|
||||
}
|
||||
};
|
||||
|
||||
let block_import = block_import.clone();
|
||||
Either::A(proposal_work
|
||||
.map(move |b| {
|
||||
// minor hack since we don't have access to the timestamp
|
||||
// that is actually set by the proposer.
|
||||
let slot_after_building = slot_now(slot_duration);
|
||||
if slot_after_building != Some(slot_num) {
|
||||
info!("Discarding proposal for slot {}; block production took too long",
|
||||
slot_num);
|
||||
return
|
||||
}
|
||||
|
||||
let (header, body) = b.deconstruct();
|
||||
let pre_hash = header.hash();
|
||||
let parent_hash = header.parent_hash().clone();
|
||||
|
||||
// sign the pre-sealed hash of the block and then
|
||||
// add it to a digest item.
|
||||
let to_sign = (slot_num, pre_hash).encode();
|
||||
let signature = pair.sign(&to_sign[..]);
|
||||
let item = <DigestItemFor<B> as CompatibleDigestItem>::aura_seal(
|
||||
slot_num,
|
||||
signature,
|
||||
);
|
||||
|
||||
let import_block = ImportBlock {
|
||||
origin: BlockOrigin::Own,
|
||||
header,
|
||||
justification: None,
|
||||
post_digests: vec![item],
|
||||
body: Some(body),
|
||||
finalized: false,
|
||||
auxiliary: Vec::new(),
|
||||
};
|
||||
|
||||
if let Err(e) = block_import.import_block(import_block, None) {
|
||||
warn!(target: "aura", "Error with block built on {:?}: {:?}",
|
||||
parent_hash, e);
|
||||
}
|
||||
})
|
||||
.map_err(|e| warn!("Failed to construct block: {:?}", e))
|
||||
)
|
||||
})
|
||||
.map(|_| future::Loop::Continue(()))
|
||||
})
|
||||
};
|
||||
|
||||
future::loop_fn((), move |()| {
|
||||
@@ -337,7 +419,19 @@ pub trait ExtraVerification<B: Block>: Send + Sync {
|
||||
type Verified: IntoFuture<Item=(),Error=String>;
|
||||
|
||||
/// Do additional verification for this block.
|
||||
fn verify(&self, header: &B::Header, body: Option<&[B::Extrinsic]>) -> Self::Verified;
|
||||
fn verify(
|
||||
&self,
|
||||
header: &B::Header,
|
||||
body: Option<&[B::Extrinsic]>,
|
||||
) -> Self::Verified;
|
||||
}
|
||||
|
||||
/// A verifier for Aura blocks.
|
||||
pub struct AuraVerifier<C, E, MakeInherent> {
|
||||
slot_duration: SlotDuration,
|
||||
client: Arc<C>,
|
||||
make_inherent: MakeInherent,
|
||||
extra: E,
|
||||
}
|
||||
|
||||
/// No-op extra verification.
|
||||
@@ -351,33 +445,35 @@ impl<B: Block> ExtraVerification<B> for NothingExtra {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
/// A verifier for Aura blocks.
|
||||
pub struct AuraVerifier<C, E> {
|
||||
config: Config,
|
||||
client: Arc<C>,
|
||||
extra: E,
|
||||
}
|
||||
|
||||
impl<B: Block, C, E> Verifier<B> for AuraVerifier<C, E> where
|
||||
C: Authorities<B> + BlockImport<B> + Send + Sync,
|
||||
impl<B: Block, C, E, MakeInherent, Inherent> Verifier<B> for AuraVerifier<C, E, MakeInherent> where
|
||||
C: Authorities<B> + BlockImport<B> + ProvideRuntimeApi + Send + Sync,
|
||||
C::Api: BlockBuilderApi<B, Inherent>,
|
||||
DigestItemFor<B>: CompatibleDigestItem,
|
||||
E: ExtraVerification<B>,
|
||||
MakeInherent: Fn(u64, u64) -> Inherent + Send + Sync,
|
||||
{
|
||||
fn verify(
|
||||
&self,
|
||||
origin: BlockOrigin,
|
||||
header: B::Header,
|
||||
justification: Option<Justification>,
|
||||
body: Option<Vec<B::Extrinsic>>
|
||||
mut body: Option<Vec<B::Extrinsic>>,
|
||||
) -> Result<(ImportBlock<B>, Option<Vec<AuthorityId>>), String> {
|
||||
let slot_now = slot_now(self.config.slot_duration)
|
||||
use runtime_primitives::CheckInherentError;
|
||||
const MAX_TIMESTAMP_DRIFT_SECS: u64 = 60;
|
||||
|
||||
let (timestamp_now, slot_now) = timestamp_and_slot_now(self.slot_duration.0)
|
||||
.ok_or("System time is before UnixTime?".to_owned())?;
|
||||
let hash = header.hash();
|
||||
let parent_hash = *header.parent_hash();
|
||||
let authorities = self.client.authorities(&BlockId::Hash(parent_hash))
|
||||
.map_err(|e| format!("Could not fetch authorities at {:?}: {:?}", parent_hash, e))?;
|
||||
|
||||
let extra_verification = self.extra.verify(&header, body.as_ref().map(|x| &x[..]));
|
||||
let extra_verification = self.extra.verify(
|
||||
&header,
|
||||
body.as_ref().map(|x| &x[..]),
|
||||
);
|
||||
|
||||
// we add one to allow for some small drift.
|
||||
// FIXME: in the future, alter this queue to allow deferring of headers
|
||||
@@ -387,7 +483,40 @@ impl<B: Block, C, E> Verifier<B> for AuraVerifier<C, E> where
|
||||
CheckedHeader::Checked(pre_header, slot_num, sig) => {
|
||||
let item = <DigestItemFor<B>>::aura_seal(slot_num, sig);
|
||||
|
||||
debug!(target: "aura", "Checked {:?}; importing.", pre_header);
|
||||
// if the body is passed through, we need to use the runtime
|
||||
// to check that the internally-set timestamp in the inherents
|
||||
// actually matches the slot set in the seal.
|
||||
if let Some(inner_body) = body.take() {
|
||||
let inherent = (self.make_inherent)(timestamp_now, slot_num);
|
||||
let block = Block::new(pre_header.clone(), inner_body);
|
||||
|
||||
let inherent_res = self.client.runtime_api().check_inherents(
|
||||
&BlockId::Hash(parent_hash),
|
||||
&block,
|
||||
&inherent,
|
||||
).map_err(|e| format!("{:?}", e))?;
|
||||
|
||||
match inherent_res {
|
||||
Ok(()) => {}
|
||||
Err(CheckInherentError::ValidAtTimestamp(timestamp)) => {
|
||||
// halt import until timestamp is valid.
|
||||
// reject when too far ahead.
|
||||
if timestamp > timestamp_now + MAX_TIMESTAMP_DRIFT_SECS {
|
||||
return Err("Rejecting block too far in future".into());
|
||||
}
|
||||
|
||||
let diff = timestamp.saturating_sub(timestamp_now);
|
||||
info!(target: "aura", "halting for block {} seconds in the future", diff);
|
||||
::std::thread::sleep(Duration::from_secs(diff));
|
||||
},
|
||||
Err(CheckInherentError::Other(s)) => return Err(s.into_owned()),
|
||||
}
|
||||
|
||||
let (_, inner_body) = block.deconstruct();
|
||||
body = Some(inner_body);
|
||||
}
|
||||
|
||||
trace!(target: "aura", "Checked {:?}; importing.", pre_header);
|
||||
|
||||
extra_verification.into_future().wait()?;
|
||||
|
||||
@@ -412,17 +541,72 @@ impl<B: Block, C, E> Verifier<B> for AuraVerifier<C, E> where
|
||||
}
|
||||
}
|
||||
|
||||
/// A utility for making the basic-inherent data.
|
||||
pub fn make_basic_inherent(timestamp: u64, slot_now: u64) -> BasicInherentData {
|
||||
BasicInherentData::new(timestamp, slot_now)
|
||||
}
|
||||
|
||||
/// A type for a function which produces inherent.
|
||||
pub type InherentProducingFn<I> = fn(u64, u64) -> I;
|
||||
|
||||
/// The Aura import queue type.
|
||||
pub type AuraImportQueue<B, C, E> = BasicQueue<B, AuraVerifier<C, E>>;
|
||||
pub type AuraImportQueue<B, C, E, MakeInherent> = BasicQueue<B, AuraVerifier<C, E, MakeInherent>>;
|
||||
|
||||
/// A slot duration. Create with `get_or_compute`.
|
||||
// The internal member should stay private here.
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub struct SlotDuration(u64);
|
||||
|
||||
impl SlotDuration {
|
||||
/// Either fetch the slot duration from disk or compute it from the genesis
|
||||
/// state.
|
||||
pub fn get_or_compute<B: Block, C>(client: &C) -> ::client::error::Result<Self> where
|
||||
C: ::client::backend::AuxStore,
|
||||
C: ProvideRuntimeApi,
|
||||
C::Api: AuraApi<B>,
|
||||
{
|
||||
use codec::Decode;
|
||||
const SLOT_KEY: &[u8] = b"aura_slot_duration";
|
||||
|
||||
match client.get_aux(SLOT_KEY)? {
|
||||
Some(v) => u64::decode(&mut &v[..])
|
||||
.map(SlotDuration)
|
||||
.ok_or_else(|| ::client::error::ErrorKind::Backend(
|
||||
format!("Aura slot duration kept in invalid format"),
|
||||
).into()),
|
||||
None => {
|
||||
use runtime_primitives::traits::Zero;
|
||||
let genesis_slot_duration = client.runtime_api()
|
||||
.slot_duration(&BlockId::number(Zero::zero()))?;
|
||||
|
||||
info!("Loaded block-time = {:?} seconds from genesis on first-launch",
|
||||
genesis_slot_duration);
|
||||
|
||||
genesis_slot_duration.using_encoded(|s| {
|
||||
client.insert_aux(&[(SLOT_KEY, &s[..])], &[])
|
||||
})?;
|
||||
|
||||
Ok(SlotDuration(genesis_slot_duration))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Start an import queue for the Aura consensus algorithm.
|
||||
pub fn import_queue<B, C, E>(config: Config, client: Arc<C>, extra: E) -> AuraImportQueue<B, C, E> where
|
||||
pub fn import_queue<B, C, E, MakeInherent, Inherent>(
|
||||
slot_duration: SlotDuration,
|
||||
client: Arc<C>,
|
||||
extra: E,
|
||||
make_inherent: MakeInherent,
|
||||
) -> AuraImportQueue<B, C, E, MakeInherent> where
|
||||
B: Block,
|
||||
C: Authorities<B> + BlockImport<B,Error=client::error::Error> + Send + Sync,
|
||||
C: Authorities<B> + BlockImport<B,Error=::client::error::Error> + ProvideRuntimeApi + Send + Sync,
|
||||
C::Api: BlockBuilderApi<B, Inherent>,
|
||||
DigestItemFor<B>: CompatibleDigestItem,
|
||||
E: ExtraVerification<B>,
|
||||
MakeInherent: Fn(u64, u64) -> Inherent + Send + Sync,
|
||||
{
|
||||
let verifier = Arc::new(AuraVerifier { config, client: client.clone(), extra, });
|
||||
let verifier = Arc::new(AuraVerifier { slot_duration, client: client.clone(), extra, make_inherent });
|
||||
BasicQueue::new(verifier, client)
|
||||
}
|
||||
|
||||
@@ -440,9 +624,9 @@ mod tests {
|
||||
use client::BlockchainEvents;
|
||||
use test_client;
|
||||
|
||||
type Error = client::error::Error;
|
||||
type Error = ::client::error::Error;
|
||||
|
||||
type TestClient = client::Client<test_client::Backend, test_client::Executor, TestBlock, test_client::runtime::RuntimeApi>;
|
||||
type TestClient = ::client::Client<test_client::Backend, test_client::Executor, TestBlock, test_client::runtime::RuntimeApi>;
|
||||
|
||||
struct DummyFactory(Arc<TestClient>);
|
||||
struct DummyProposer(u64, Arc<TestClient>);
|
||||
@@ -471,12 +655,16 @@ mod tests {
|
||||
const TEST_ROUTING_INTERVAL: Duration = Duration::from_millis(50);
|
||||
|
||||
pub struct AuraTestNet {
|
||||
peers: Vec<Arc<Peer<AuraVerifier<PeersClient, NothingExtra>, ()>>>,
|
||||
peers: Vec<Arc<Peer<AuraVerifier<
|
||||
PeersClient,
|
||||
NothingExtra,
|
||||
InherentProducingFn<()>,
|
||||
>, ()>>>,
|
||||
started: bool
|
||||
}
|
||||
|
||||
impl TestNetFactory for AuraTestNet {
|
||||
type Verifier = AuraVerifier<PeersClient, NothingExtra>;
|
||||
type Verifier = AuraVerifier<PeersClient, NothingExtra, InherentProducingFn<()>>;
|
||||
type PeerData = ();
|
||||
|
||||
/// Create new test network with peers and given config.
|
||||
@@ -490,8 +678,17 @@ mod tests {
|
||||
fn make_verifier(&self, client: Arc<PeersClient>, _cfg: &ProtocolConfig)
|
||||
-> Arc<Self::Verifier>
|
||||
{
|
||||
let config = Config { local_key: None, slot_duration: SLOT_DURATION };
|
||||
Arc::new(AuraVerifier { client, config, extra: NothingExtra })
|
||||
fn make_inherent(_: u64, _: u64) { () }
|
||||
let slot_duration = SlotDuration::get_or_compute(&*client)
|
||||
.expect("slot duration available");
|
||||
|
||||
assert_eq!(slot_duration.0, SLOT_DURATION);
|
||||
Arc::new(AuraVerifier {
|
||||
client,
|
||||
slot_duration,
|
||||
extra: NothingExtra,
|
||||
make_inherent: make_inherent as _,
|
||||
})
|
||||
}
|
||||
|
||||
fn peer(&self, i: usize) -> &Peer<Self::Verifier, ()> {
|
||||
@@ -542,11 +739,13 @@ mod tests {
|
||||
})
|
||||
.for_each(move |_| Ok(()))
|
||||
);
|
||||
|
||||
let slot_duration = SlotDuration::get_or_compute(&*client)
|
||||
.expect("slot duration available");
|
||||
|
||||
let aura = start_aura(
|
||||
Config {
|
||||
local_key: Some(Arc::new(key.clone().into())),
|
||||
slot_duration: SLOT_DURATION
|
||||
},
|
||||
slot_duration,
|
||||
Arc::new(key.clone().into()),
|
||||
client.clone(),
|
||||
client,
|
||||
environ.clone(),
|
||||
|
||||
@@ -505,9 +505,8 @@ impl<B, E, Block: BlockT<Hash=H256>, N, RA> voter::Environment<Block::Hash, Numb
|
||||
);
|
||||
|
||||
let encoded_state = (round, state).encode();
|
||||
if let Err(e) = self.inner.backend()
|
||||
.insert_aux(&[(LAST_COMPLETED_KEY, &encoded_state[..])], &[])
|
||||
{
|
||||
let res = Backend::insert_aux(&**self.inner.backend(), &[(LAST_COMPLETED_KEY, &encoded_state[..])], &[]);
|
||||
if let Err(e) = res {
|
||||
warn!(target: "afg", "Shutting down voter due to error bookkeeping last completed round in DB: {:?}", e);
|
||||
Err(Error::Client(e).into())
|
||||
} else {
|
||||
@@ -737,7 +736,8 @@ fn finalize_block<B, Block: BlockT<Hash=H256>, E, RA>(
|
||||
let last_completed: LastCompleted<_, _> = (0, round_state);
|
||||
let encoded = last_completed.encode();
|
||||
|
||||
client.backend().insert_aux(
|
||||
Backend::insert_aux(
|
||||
&**client.backend(),
|
||||
&[
|
||||
(AUTHORITY_SET_KEY, &encoded_set[..]),
|
||||
(LAST_COMPLETED_KEY, &encoded[..]),
|
||||
@@ -745,7 +745,7 @@ fn finalize_block<B, Block: BlockT<Hash=H256>, E, RA>(
|
||||
&[]
|
||||
)
|
||||
} else {
|
||||
client.backend().insert_aux(&[(AUTHORITY_SET_KEY, &encoded_set[..])], &[])
|
||||
Backend::insert_aux(&**client.backend(), &[(AUTHORITY_SET_KEY, &encoded_set[..])], &[])
|
||||
};
|
||||
|
||||
if let Err(e) = write_result {
|
||||
@@ -954,7 +954,7 @@ impl<B, E, Block: BlockT<Hash=H256>, RA, PRA> BlockImport<Block>
|
||||
)?;
|
||||
|
||||
let encoded = authorities.encode();
|
||||
self.inner.backend().insert_aux(&[(AUTHORITY_SET_KEY, &encoded[..])], &[])?;
|
||||
Backend::insert_aux(&**self.inner.backend(), &[(AUTHORITY_SET_KEY, &encoded[..])], &[])?;
|
||||
};
|
||||
|
||||
let enacts_change = self.authority_set.inner().read().enacts_change(number, |canon_number| {
|
||||
@@ -1066,6 +1066,19 @@ where
|
||||
}
|
||||
}
|
||||
|
||||
impl<B, E, Block: BlockT<Hash=H256>, RA, PRA> ProvideRuntimeApi for GrandpaBlockImport<B, E, Block, RA, PRA>
|
||||
where
|
||||
B: Backend<Block, Blake2Hasher> + 'static,
|
||||
E: CallExecutor<Block, Blake2Hasher> + 'static + Clone + Send + Sync,
|
||||
PRA: ProvideRuntimeApi,
|
||||
{
|
||||
type Api = PRA::Api;
|
||||
|
||||
fn runtime_api<'a>(&'a self) -> ::runtime_primitives::traits::ApiRef<'a, Self::Api> {
|
||||
self.api.runtime_api()
|
||||
}
|
||||
}
|
||||
|
||||
/// Half of a link between a block-import worker and a the background voter.
|
||||
// This should remain non-clone.
|
||||
pub struct LinkHalf<B, E, Block: BlockT<Hash=H256>, RA> {
|
||||
@@ -1131,7 +1144,7 @@ pub fn block_import<B, E, Block: BlockT<Hash=H256>, RA, PRA>(
|
||||
PRA::Api: GrandpaApi<Block>
|
||||
{
|
||||
use runtime_primitives::traits::Zero;
|
||||
let authority_set = match client.backend().get_aux(AUTHORITY_SET_KEY)? {
|
||||
let authority_set = match Backend::get_aux(&**client.backend(), AUTHORITY_SET_KEY)? {
|
||||
None => {
|
||||
info!(target: "afg", "Loading GRANDPA authorities \
|
||||
from genesis on what appears to be first startup.");
|
||||
@@ -1144,7 +1157,7 @@ pub fn block_import<B, E, Block: BlockT<Hash=H256>, RA, PRA>(
|
||||
|
||||
let authority_set = SharedAuthoritySet::genesis(genesis_authorities);
|
||||
let encoded = authority_set.inner().read().encode();
|
||||
client.backend().insert_aux(&[(AUTHORITY_SET_KEY, &encoded[..])], &[])?;
|
||||
Backend::insert_aux(&**client.backend(), &[(AUTHORITY_SET_KEY, &encoded[..])], &[])?;
|
||||
|
||||
authority_set
|
||||
}
|
||||
@@ -1261,7 +1274,7 @@ pub fn run_grandpa<B, E, Block: BlockT<Hash=H256>, N, RA>(
|
||||
let chain_info = client.info()?;
|
||||
let genesis_hash = chain_info.chain.genesis_hash;
|
||||
|
||||
let (last_round_number, last_state) = match client.backend().get_aux(LAST_COMPLETED_KEY)? {
|
||||
let (last_round_number, last_state) = match Backend::get_aux(&**client.backend(), LAST_COMPLETED_KEY)? {
|
||||
None => (0, RoundState::genesis((genesis_hash, <NumberFor<Block>>::zero()))),
|
||||
Some(raw) => LastCompleted::decode(&mut &raw[..])
|
||||
.ok_or_else(|| ::client::error::ErrorKind::Backend(
|
||||
|
||||
@@ -19,23 +19,19 @@
|
||||
// FIXME: move this into substrate-consensus-common - https://github.com/paritytech/substrate/issues/1021
|
||||
|
||||
use std::sync::Arc;
|
||||
use std::time::{self, Duration, Instant};
|
||||
use std::time;
|
||||
use std;
|
||||
|
||||
use client::{self, error, Client as SubstrateClient, CallExecutor};
|
||||
use client::{block_builder::api::BlockBuilder as BlockBuilderApi, runtime_api::Core};
|
||||
use codec::{Decode, Encode};
|
||||
use consensus_common::{self, evaluation, offline_tracker::OfflineTracker};
|
||||
use consensus_common::{self, evaluation};
|
||||
use primitives::{H256, AuthorityId, ed25519, Blake2Hasher};
|
||||
use runtime_primitives::traits::{Block as BlockT, Hash as HashT, Header as HeaderT, ProvideRuntimeApi};
|
||||
use runtime_primitives::generic::BlockId;
|
||||
use runtime_primitives::BasicInherentData;
|
||||
use transaction_pool::txpool::{self, Pool as TransactionPool};
|
||||
|
||||
use parking_lot::RwLock;
|
||||
|
||||
/// Shared offline validator tracker.
|
||||
pub type SharedOfflineTracker = Arc<RwLock<OfflineTracker>>;
|
||||
type Timestamp = u64;
|
||||
|
||||
// block size limit.
|
||||
@@ -113,10 +109,6 @@ pub struct ProposerFactory<C, A> where A: txpool::ChainApi {
|
||||
pub client: Arc<C>,
|
||||
/// The transaction pool.
|
||||
pub transaction_pool: Arc<TransactionPool<A>>,
|
||||
/// Offline-tracker.
|
||||
pub offline: SharedOfflineTracker,
|
||||
/// Force delay in evaluation this long.
|
||||
pub force_delay: Timestamp,
|
||||
}
|
||||
|
||||
impl<C, A> consensus_common::Environment<<C as AuthoringApi>::Block> for ProposerFactory<C, A> where
|
||||
@@ -138,22 +130,14 @@ impl<C, A> consensus_common::Environment<<C as AuthoringApi>::Block> for Propose
|
||||
|
||||
let id = BlockId::hash(parent_hash);
|
||||
|
||||
let authorities: Vec<AuthorityId> = self.client.runtime_api().authorities(&id)?;
|
||||
self.offline.write().note_new_block(&authorities[..]);
|
||||
|
||||
info!("Starting consensus session on top of parent {:?}", parent_hash);
|
||||
|
||||
let now = Instant::now();
|
||||
let proposer = Proposer {
|
||||
client: self.client.clone(),
|
||||
start: now,
|
||||
parent_hash,
|
||||
parent_id: id,
|
||||
parent_number: *parent_header.number(),
|
||||
transaction_pool: self.transaction_pool.clone(),
|
||||
offline: self.offline.clone(),
|
||||
authorities,
|
||||
minimum_timestamp: current_timestamp() + self.force_delay,
|
||||
};
|
||||
|
||||
Ok(proposer)
|
||||
@@ -163,14 +147,10 @@ impl<C, A> consensus_common::Environment<<C as AuthoringApi>::Block> for Propose
|
||||
/// The proposer logic.
|
||||
pub struct Proposer<Block: BlockT, C, A: txpool::ChainApi> {
|
||||
client: Arc<C>,
|
||||
start: Instant,
|
||||
parent_hash: <Block as BlockT>::Hash,
|
||||
parent_id: BlockId<Block>,
|
||||
parent_number: <<Block as BlockT>::Header as HeaderT>::Number,
|
||||
transaction_pool: Arc<TransactionPool<A>>,
|
||||
offline: SharedOfflineTracker,
|
||||
authorities: Vec<AuthorityId>,
|
||||
minimum_timestamp: u64,
|
||||
}
|
||||
|
||||
impl<Block, C, A> consensus_common::Proposer<<C as AuthoringApi>::Block> for Proposer<Block, C, A> where
|
||||
@@ -186,24 +166,8 @@ impl<Block, C, A> consensus_common::Proposer<<C as AuthoringApi>::Block> for Pro
|
||||
fn propose(&self) -> Result<<C as AuthoringApi>::Block, error::Error> {
|
||||
use runtime_primitives::traits::BlakeTwo256;
|
||||
|
||||
const MAX_VOTE_OFFLINE_SECONDS: Duration = Duration::from_secs(60);
|
||||
|
||||
let timestamp = ::std::cmp::max(self.minimum_timestamp, current_timestamp());
|
||||
|
||||
let elapsed_since_start = self.start.elapsed();
|
||||
let offline_indices = if elapsed_since_start > MAX_VOTE_OFFLINE_SECONDS {
|
||||
Vec::new()
|
||||
} else {
|
||||
self.offline.read().reports(&self.authorities[..])
|
||||
};
|
||||
|
||||
if !offline_indices.is_empty() {
|
||||
info!("Submitting offline authorities {:?} for slash-vote",
|
||||
offline_indices.iter().map(|&i| self.authorities[i as usize]).collect::<Vec<_>>(),
|
||||
)
|
||||
}
|
||||
|
||||
let inherent_data = BasicInherentData::new(timestamp, offline_indices);
|
||||
let timestamp = current_timestamp();
|
||||
let inherent_data = BasicInherentData::new(timestamp, 0);
|
||||
|
||||
let block = self.client.build_block(
|
||||
&self.parent_id,
|
||||
|
||||
@@ -480,16 +480,19 @@ macro_rules! impl_outer_log {
|
||||
pub struct BasicInherentData {
|
||||
/// Current timestamp.
|
||||
pub timestamp: u64,
|
||||
/// Indices of offline validators.
|
||||
pub consensus: Vec<u32>,
|
||||
/// Blank report.
|
||||
pub consensus: (),
|
||||
/// Aura expected slot. Can take any value during block construction.
|
||||
pub aura_expected_slot: u64,
|
||||
}
|
||||
|
||||
impl BasicInherentData {
|
||||
/// Create a new `BasicInherentData` instance.
|
||||
pub fn new(timestamp: u64, consensus: Vec<u32>) -> Self {
|
||||
pub fn new(timestamp: u64, expected_slot: u64) -> Self {
|
||||
Self {
|
||||
timestamp,
|
||||
consensus,
|
||||
consensus: (),
|
||||
aura_expected_slot: expected_slot,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -506,6 +509,22 @@ pub enum CheckInherentError {
|
||||
Other(RuntimeString),
|
||||
}
|
||||
|
||||
impl CheckInherentError {
|
||||
/// Combine two results, taking the "worse" of the two.
|
||||
pub fn combine_results<F: FnOnce() -> Result<(), Self>>(this: Result<(), Self>, other: F) -> Result<(), Self> {
|
||||
match this {
|
||||
Ok(()) => other(),
|
||||
Err(CheckInherentError::Other(s)) => Err(CheckInherentError::Other(s)),
|
||||
Err(CheckInherentError::ValidAtTimestamp(x)) => match other() {
|
||||
Ok(()) => Err(CheckInherentError::ValidAtTimestamp(x)),
|
||||
Err(CheckInherentError::ValidAtTimestamp(y))
|
||||
=> Err(CheckInherentError::ValidAtTimestamp(rstd::cmp::max(x, y))),
|
||||
Err(CheckInherentError::Other(s)) => Err(CheckInherentError::Other(s)),
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use substrate_primitives::hash::H256;
|
||||
|
||||
@@ -13,6 +13,7 @@ parity-codec-derive = { version = "2.1", default-features = false }
|
||||
substrate-keyring = { path = "../keyring", optional = true }
|
||||
substrate-client = { path = "../client", optional = true }
|
||||
substrate-primitives = { path = "../primitives", default-features = false }
|
||||
substrate-consensus-aura-primitives = { path = "../consensus/aura/primitives", default-features = false }
|
||||
sr-std = { path = "../sr-std", default-features = false }
|
||||
sr-io = { path = "../sr-io", default-features = false }
|
||||
sr-primitives = { path = "../sr-primitives", default-features = false }
|
||||
@@ -35,4 +36,5 @@ std = [
|
||||
"substrate-primitives/std",
|
||||
"sr-primitives/std",
|
||||
"sr-version/std",
|
||||
"substrate-consensus-aura-primitives/std",
|
||||
]
|
||||
|
||||
@@ -24,6 +24,7 @@ extern crate serde;
|
||||
extern crate sr_std as rstd;
|
||||
extern crate parity_codec as codec;
|
||||
extern crate sr_primitives as runtime_primitives;
|
||||
extern crate substrate_consensus_aura_primitives as consensus_aura;
|
||||
|
||||
#[macro_use]
|
||||
extern crate substrate_client as client;
|
||||
@@ -64,6 +65,7 @@ use primitives::AuthorityId;
|
||||
use primitives::OpaqueMetadata;
|
||||
#[cfg(any(feature = "std", test))]
|
||||
use runtime_version::NativeVersion;
|
||||
use consensus_aura::api as aura_api;
|
||||
|
||||
/// Test runtime version.
|
||||
pub const VERSION: RuntimeVersion = RuntimeVersion {
|
||||
@@ -234,7 +236,7 @@ impl_runtime_apis! {
|
||||
}
|
||||
|
||||
fn check_inherents(_block: Block, _data: ()) -> Result<(), CheckInherentError> {
|
||||
unimplemented!()
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn random_seed() -> <Block as BlockT>::Hash {
|
||||
@@ -247,4 +249,8 @@ impl_runtime_apis! {
|
||||
system::balance_of(id)
|
||||
}
|
||||
}
|
||||
|
||||
impl aura_api::AuraApi<Block> for Runtime {
|
||||
fn slot_duration() -> u64 { 1 }
|
||||
}
|
||||
}
|
||||
|
||||
+14
@@ -1087,6 +1087,19 @@ dependencies = [
|
||||
"substrate-trie 0.4.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "substrate-consensus-aura-primitives"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"parity-codec 2.1.5 (registry+https://github.com/rust-lang/crates.io-index)",
|
||||
"sr-io 0.1.0",
|
||||
"sr-primitives 0.1.0",
|
||||
"sr-version 0.1.0",
|
||||
"srml-support 0.1.0",
|
||||
"substrate-client 0.1.0",
|
||||
"substrate-primitives 0.1.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "substrate-consensus-common"
|
||||
version = "0.1.0"
|
||||
@@ -1208,6 +1221,7 @@ dependencies = [
|
||||
"sr-version 0.1.0",
|
||||
"srml-support 0.1.0",
|
||||
"substrate-client 0.1.0",
|
||||
"substrate-consensus-aura-primitives 0.1.0",
|
||||
"substrate-primitives 0.1.0",
|
||||
]
|
||||
|
||||
|
||||
@@ -9,6 +9,7 @@ hex-literal = { version = "0.1.0", optional = true }
|
||||
parity-codec = { version = "2.1", default-features = false }
|
||||
parity-codec-derive = { version = "2.1", default-features = false }
|
||||
substrate-primitives = { path = "../../primitives", default-features = false }
|
||||
substrate-consensus-aura-primitives = { path = "../../consensus/aura/primitives", default-features = false }
|
||||
substrate-client = { path = "../../client", default-features = false }
|
||||
sr-std = { path = "../../sr-std", default-features = false }
|
||||
sr-io = { path = "../../sr-io", default-features = false }
|
||||
@@ -28,7 +29,8 @@ std = [
|
||||
"sr-version/std",
|
||||
"substrate-primitives/std",
|
||||
"substrate-client/std",
|
||||
"sr-primitives/std"
|
||||
"sr-primitives/std",
|
||||
"substrate-consensus-aura-primitives/std",
|
||||
]
|
||||
|
||||
[lib]
|
||||
|
||||
Reference in New Issue
Block a user