Use BABE to author blocks on Rialto (previously: Aura) (#1050)

* use BABE to author blocks on Rialto (previously: Aura)

* removed extra script

* use bp_rialto::Moment

* fix tests

* Babe should control session end

* test

* Revert "test"

This reverts commit 4bbbd76b1fe0aa65002fcfa600cfdc6d15c899e2.

* clippy

* fix test

* Revert "Revert "test""

This reverts commit e9220184d4a14ef4f5a792b239e835528d3baa31.

* Revert "Revert "Revert "test"""

This reverts commit 9f56a5528945f1d8f82c6346826be68207bf9c75.
This commit is contained in:
Svyatoslav Nikolsky
2021-07-19 15:18:29 +03:00
committed by Bastian Köcher
parent e18844d1f4
commit 08fd53adef
9 changed files with 192 additions and 221 deletions
+3 -2
View File
@@ -33,7 +33,7 @@ sc-basic-authorship = { git = "https://github.com/paritytech/substrate", branch
sc-cli = { git = "https://github.com/paritytech/substrate", branch = "master", features = ["wasmtime"] } sc-cli = { git = "https://github.com/paritytech/substrate", branch = "master", features = ["wasmtime"] }
sc-client-api = { git = "https://github.com/paritytech/substrate", branch = "master" } sc-client-api = { git = "https://github.com/paritytech/substrate", branch = "master" }
sc-consensus = { git = "https://github.com/paritytech/substrate", branch = "master" } sc-consensus = { git = "https://github.com/paritytech/substrate", branch = "master" }
sc-consensus-aura = { git = "https://github.com/paritytech/substrate", branch = "master" } sc-consensus-babe = { git = "https://github.com/paritytech/substrate", branch = "master" }
sc-executor = { git = "https://github.com/paritytech/substrate", branch = "master" } sc-executor = { git = "https://github.com/paritytech/substrate", branch = "master" }
sc-finality-grandpa = { git = "https://github.com/paritytech/substrate", branch = "master" } sc-finality-grandpa = { git = "https://github.com/paritytech/substrate", branch = "master" }
sc-finality-grandpa-rpc = { git = "https://github.com/paritytech/substrate", branch = "master" } sc-finality-grandpa-rpc = { git = "https://github.com/paritytech/substrate", branch = "master" }
@@ -42,8 +42,9 @@ sc-rpc = { git = "https://github.com/paritytech/substrate", branch = "master" }
sc-service = { git = "https://github.com/paritytech/substrate", branch = "master" } sc-service = { git = "https://github.com/paritytech/substrate", branch = "master" }
sc-telemetry = { git = "https://github.com/paritytech/substrate", branch = "master" } sc-telemetry = { git = "https://github.com/paritytech/substrate", branch = "master" }
sc-transaction-pool = { git = "https://github.com/paritytech/substrate", branch = "master" } sc-transaction-pool = { git = "https://github.com/paritytech/substrate", branch = "master" }
sp-authorship = { git = "https://github.com/paritytech/substrate", branch = "master" }
sp-consensus = { git = "https://github.com/paritytech/substrate", branch = "master" } sp-consensus = { git = "https://github.com/paritytech/substrate", branch = "master" }
sp-consensus-aura = { git = "https://github.com/paritytech/substrate", branch = "master" } sp-consensus-babe = { git = "https://github.com/paritytech/substrate", branch = "master" }
sp-core = { git = "https://github.com/paritytech/substrate", branch = "master" } sp-core = { git = "https://github.com/paritytech/substrate", branch = "master" }
sp-finality-grandpa = { git = "https://github.com/paritytech/substrate", branch = "master" } sp-finality-grandpa = { git = "https://github.com/paritytech/substrate", branch = "master" }
sp-inherents = { git = "https://github.com/paritytech/substrate", branch = "master" } sp-inherents = { git = "https://github.com/paritytech/substrate", branch = "master" }
+10 -9
View File
@@ -16,11 +16,11 @@
use bp_rialto::derive_account_from_millau_id; use bp_rialto::derive_account_from_millau_id;
use rialto_runtime::{ use rialto_runtime::{
AccountId, AuraConfig, BalancesConfig, BridgeKovanConfig, BridgeRialtoPoaConfig, GenesisConfig, GrandpaConfig, AccountId, BabeConfig, BalancesConfig, BridgeKovanConfig, BridgeRialtoPoaConfig, GenesisConfig, GrandpaConfig,
SessionConfig, SessionKeys, Signature, SudoConfig, SystemConfig, WASM_BINARY, SessionConfig, SessionKeys, Signature, SudoConfig, SystemConfig, WASM_BINARY,
}; };
use serde_json::json; use serde_json::json;
use sp_consensus_aura::sr25519::AuthorityId as AuraId; use sp_consensus_babe::AuthorityId as BabeId;
use sp_core::{sr25519, Pair, Public}; use sp_core::{sr25519, Pair, Public};
use sp_finality_grandpa::AuthorityId as GrandpaId; use sp_finality_grandpa::AuthorityId as GrandpaId;
use sp_runtime::traits::{IdentifyAccount, Verify}; use sp_runtime::traits::{IdentifyAccount, Verify};
@@ -56,11 +56,11 @@ where
AccountPublic::from(get_from_seed::<TPublic>(seed)).into_account() AccountPublic::from(get_from_seed::<TPublic>(seed)).into_account()
} }
/// Helper function to generate an authority key for Aura /// Helper function to generate an authority key for Babe
pub fn get_authority_keys_from_seed(s: &str) -> (AccountId, AuraId, GrandpaId) { pub fn get_authority_keys_from_seed(s: &str) -> (AccountId, BabeId, GrandpaId) {
( (
get_account_id_from_seed::<sr25519::Public>(s), get_account_id_from_seed::<sr25519::Public>(s),
get_from_seed::<AuraId>(s), get_from_seed::<BabeId>(s),
get_from_seed::<GrandpaId>(s), get_from_seed::<GrandpaId>(s),
) )
} }
@@ -174,12 +174,12 @@ impl Alternative {
} }
} }
fn session_keys(aura: AuraId, grandpa: GrandpaId) -> SessionKeys { fn session_keys(babe: BabeId, grandpa: GrandpaId) -> SessionKeys {
SessionKeys { aura, grandpa } SessionKeys { babe, grandpa }
} }
fn testnet_genesis( fn testnet_genesis(
initial_authorities: Vec<(AccountId, AuraId, GrandpaId)>, initial_authorities: Vec<(AccountId, BabeId, GrandpaId)>,
root_key: AccountId, root_key: AccountId,
endowed_accounts: Vec<AccountId>, endowed_accounts: Vec<AccountId>,
_enable_println: bool, _enable_println: bool,
@@ -192,8 +192,9 @@ fn testnet_genesis(
balances: BalancesConfig { balances: BalancesConfig {
balances: endowed_accounts.iter().cloned().map(|k| (k, 1 << 50)).collect(), balances: endowed_accounts.iter().cloned().map(|k| (k, 1 << 50)).collect(),
}, },
aura: AuraConfig { babe: BabeConfig {
authorities: Vec::new(), authorities: Vec::new(),
epoch_config: Some(rialto_runtime::BABE_GENESIS_EPOCH_CONFIG),
}, },
bridge_rialto_poa: load_rialto_poa_bridge_config(), bridge_rialto_poa: load_rialto_poa_bridge_config(),
bridge_kovan: load_kovan_bridge_config(), bridge_kovan: load_kovan_bridge_config(),
+3 -1
View File
@@ -162,7 +162,9 @@ pub fn run() -> sc_cli::Result<()> {
runner runner
.run_node_until_exit(|config| async move { .run_node_until_exit(|config| async move {
match config.role { match config.role {
Role::Light => service::new_light(config), Role::Light => Err(sc_service::Error::Other(
"Light client is not supported by this node".into(),
)),
_ => service::new_full(config), _ => service::new_full(config),
} }
}) })
+62 -171
View File
@@ -19,30 +19,28 @@
// ===================================================================================== // =====================================================================================
// ===================================================================================== // =====================================================================================
// ===================================================================================== // =====================================================================================
// UPDATE GUIDE: // There's no easy way to update this file. Currently it is a merge of two files:
// 1) replace everything with node-template/src/service.rs contents (found in main Substrate repo); // 1) node-template/src/service.rs from Substrate repo;
// 2) the only thing to keep from old code, is `rpc_extensions_builder` - we use our own custom RPCs; // 2) node/service/src/lib.rs from Polkadot repo.
// 3) fix compilation errors; //
// 4) test :) // The main things to notice when updating are:
// 1) we are using Babe for authoring blocks;
// 2) support for light client is dropped as we are not using it now.
// ===========================================s==========================================
// ===================================================================================== // =====================================================================================
// ===================================================================================== // =====================================================================================
// =====================================================================================
//! Service and ServiceFactory implementation. Specialized wrapper over substrate service.
use rialto_runtime::{self, opaque::Block, RuntimeApi}; use rialto_runtime::{self, opaque::Block, RuntimeApi};
use sc_client_api::{ExecutorProvider, RemoteBackend}; use sc_client_api::ExecutorProvider;
use sc_consensus_aura::{ImportQueueParams, SlotProportion, StartAuraParams}; use sc_consensus_babe::SlotProportion;
use sc_executor::native_executor_instance; use sc_executor::native_executor_instance;
pub use sc_executor::NativeExecutor;
use sc_keystore::LocalKeystore; use sc_keystore::LocalKeystore;
use sc_service::{error::Error as ServiceError, Configuration, TaskManager}; use sc_service::{error::Error as ServiceError, Configuration, TaskManager};
use sc_telemetry::{Telemetry, TelemetryWorker}; use sc_telemetry::{Telemetry, TelemetryWorker};
use sp_consensus::SlotData;
use sp_consensus_aura::sr25519::AuthorityPair as AuraPair;
use std::{sync::Arc, time::Duration}; use std::{sync::Arc, time::Duration};
pub use sc_executor::NativeExecutor;
// Our native executor instance. // Our native executor instance.
native_executor_instance!( native_executor_instance!(
pub Executor, pub Executor,
@@ -54,6 +52,7 @@ native_executor_instance!(
type FullClient = sc_service::TFullClient<Block, RuntimeApi, Executor>; type FullClient = sc_service::TFullClient<Block, RuntimeApi, Executor>;
type FullBackend = sc_service::TFullBackend<Block>; type FullBackend = sc_service::TFullBackend<Block>;
type FullSelectChain = sc_consensus::LongestChain<FullBackend, Block>; type FullSelectChain = sc_consensus::LongestChain<FullBackend, Block>;
type FullGrandpaBlockImport = sc_finality_grandpa::GrandpaBlockImport<FullBackend, Block, FullClient, FullSelectChain>;
#[allow(clippy::type_complexity)] #[allow(clippy::type_complexity)]
pub fn new_partial( pub fn new_partial(
@@ -66,8 +65,10 @@ pub fn new_partial(
sp_consensus::DefaultImportQueue<Block, FullClient>, sp_consensus::DefaultImportQueue<Block, FullClient>,
sc_transaction_pool::FullPool<Block, FullClient>, sc_transaction_pool::FullPool<Block, FullClient>,
( (
sc_finality_grandpa::GrandpaBlockImport<FullBackend, Block, FullClient, FullSelectChain>, FullGrandpaBlockImport,
sc_finality_grandpa::LinkHalf<Block, FullClient, FullSelectChain>, sc_finality_grandpa::LinkHalf<Block, FullClient, FullSelectChain>,
sc_consensus_babe::BabeBlockImport<Block, FullClient, FullGrandpaBlockImport>,
sc_consensus_babe::BabeLink<Block>,
Option<Telemetry>, Option<Telemetry>,
), ),
>, >,
@@ -115,29 +116,36 @@ pub fn new_partial(
select_chain.clone(), select_chain.clone(),
telemetry.as_ref().map(|x| x.handle()), telemetry.as_ref().map(|x| x.handle()),
)?; )?;
let justification_import = grandpa_block_import.clone();
let slot_duration = sc_consensus_aura::slot_duration(&*client)?.slot_duration(); let (babe_block_import, babe_link) = sc_consensus_babe::block_import(
sc_consensus_babe::Config::get_or_compute(&*client)?,
grandpa_block_import.clone(),
client.clone(),
)?;
let import_queue = sc_consensus_aura::import_queue::<AuraPair, _, _, _, _, _, _>(ImportQueueParams { let slot_duration = babe_link.config().slot_duration();
block_import: grandpa_block_import.clone(), let import_queue = sc_consensus_babe::import_queue(
justification_import: Some(Box::new(grandpa_block_import.clone())), babe_link.clone(),
client: client.clone(), babe_block_import.clone(),
create_inherent_data_providers: move |_, ()| async move { Some(Box::new(justification_import)),
client.clone(),
select_chain.clone(),
move |_, ()| async move {
let timestamp = sp_timestamp::InherentDataProvider::from_system_time(); let timestamp = sp_timestamp::InherentDataProvider::from_system_time();
let slot = sp_consensus_aura::inherents::InherentDataProvider::from_timestamp_and_duration( let slot = sp_consensus_babe::inherents::InherentDataProvider::from_timestamp_and_duration(
*timestamp, *timestamp,
slot_duration, slot_duration,
); );
Ok((timestamp, slot)) Ok((timestamp, slot))
}, },
spawner: &task_manager.spawn_essential_handle(), &task_manager.spawn_essential_handle(),
can_author_with: sp_consensus::CanAuthorWithNativeVersion::new(client.executor().clone()), config.prometheus_registry(),
registry: config.prometheus_registry(), sp_consensus::CanAuthorWithNativeVersion::new(client.executor().clone()),
check_for_equivocation: Default::default(), telemetry.as_ref().map(|x| x.handle()),
telemetry: telemetry.as_ref().map(|x| x.handle()), )?;
})?;
Ok(sc_service::PartialComponents { Ok(sc_service::PartialComponents {
client, client,
@@ -147,7 +155,13 @@ pub fn new_partial(
keystore_container, keystore_container,
select_chain, select_chain,
transaction_pool, transaction_pool,
other: (grandpa_block_import, grandpa_link, telemetry), other: (
grandpa_block_import,
grandpa_link,
babe_block_import,
babe_link,
telemetry,
),
}) })
} }
@@ -168,7 +182,7 @@ pub fn new_full(mut config: Configuration) -> Result<TaskManager, ServiceError>
mut keystore_container, mut keystore_container,
select_chain, select_chain,
transaction_pool, transaction_pool,
other: (block_import, grandpa_link, mut telemetry), other: (_grandpa_block_import, grandpa_link, babe_block_import, babe_link, mut telemetry),
} = new_partial(&config)?; } = new_partial(&config)?;
if let Some(url) = &config.keystore_remote { if let Some(url) = &config.keystore_remote {
@@ -268,7 +282,7 @@ pub fn new_full(mut config: Configuration) -> Result<TaskManager, ServiceError>
})?; })?;
if role.is_authority() { if role.is_authority() {
let proposer_factory = sc_basic_authorship::ProposerFactory::new( let proposer = sc_basic_authorship::ProposerFactory::new(
task_manager.spawn_handle(), task_manager.spawn_handle(),
client.clone(), client.clone(),
transaction_pool, transaction_pool,
@@ -278,39 +292,38 @@ pub fn new_full(mut config: Configuration) -> Result<TaskManager, ServiceError>
let can_author_with = sp_consensus::CanAuthorWithNativeVersion::new(client.executor().clone()); let can_author_with = sp_consensus::CanAuthorWithNativeVersion::new(client.executor().clone());
let slot_duration = sc_consensus_aura::slot_duration(&*client)?; let slot_duration = babe_link.config().slot_duration();
let raw_slot_duration = slot_duration.slot_duration(); let babe_config = sc_consensus_babe::BabeParams {
keystore: keystore_container.sync_keystore(),
let aura = sc_consensus_aura::start_aura::<AuraPair, _, _, _, _, _, _, _, _, _, _, _>(StartAuraParams {
slot_duration,
client, client,
select_chain, select_chain,
block_import, env: proposer,
proposer_factory, block_import: babe_block_import,
create_inherent_data_providers: move |_, ()| async move { sync_oracle: network.clone(),
justification_sync_link: network.clone(),
create_inherent_data_providers: move |_parent, ()| async move {
let timestamp = sp_timestamp::InherentDataProvider::from_system_time(); let timestamp = sp_timestamp::InherentDataProvider::from_system_time();
let slot = sp_consensus_aura::inherents::InherentDataProvider::from_timestamp_and_duration( let slot = sp_consensus_babe::inherents::InherentDataProvider::from_timestamp_and_duration(
*timestamp, *timestamp,
raw_slot_duration, slot_duration,
); );
Ok((timestamp, slot)) Ok((timestamp, slot))
}, },
force_authoring, force_authoring,
backoff_authoring_blocks, backoff_authoring_blocks,
keystore: keystore_container.sync_keystore(), babe_link,
can_author_with, can_author_with,
sync_oracle: network.clone(), block_proposal_slot_portion: SlotProportion::new(0.5),
justification_sync_link: network.clone(),
block_proposal_slot_portion: SlotProportion::new(2f32 / 3f32),
max_block_proposal_slot_portion: None, max_block_proposal_slot_portion: None,
telemetry: telemetry.as_ref().map(|x| x.handle()), telemetry: telemetry.as_ref().map(|x| x.handle()),
})?; };
// the AURA authoring task is considered essential, i.e. if it let babe = sc_consensus_babe::start_babe(babe_config)?;
// fails we take down the service with it. task_manager
task_manager.spawn_essential_handle().spawn_blocking("aura", aura); .spawn_essential_handle()
.spawn_blocking("babe-proposer", babe);
} }
// if the node isn't actively participating in consensus then it doesn't // if the node isn't actively participating in consensus then it doesn't
@@ -359,125 +372,3 @@ pub fn new_full(mut config: Configuration) -> Result<TaskManager, ServiceError>
network_starter.start_network(); network_starter.start_network();
Ok(task_manager) Ok(task_manager)
} }
/// Builds a new service for a light client.
pub fn new_light(mut config: Configuration) -> Result<TaskManager, ServiceError> {
let telemetry = config
.telemetry_endpoints
.clone()
.filter(|x| !x.is_empty())
.map(|endpoints| -> Result<_, sc_telemetry::Error> {
let worker = TelemetryWorker::new(16)?;
let telemetry = worker.handle().new_telemetry(endpoints);
Ok((worker, telemetry))
})
.transpose()?;
let (client, backend, keystore_container, mut task_manager, on_demand) =
sc_service::new_light_parts::<Block, RuntimeApi, Executor>(
&config,
telemetry.as_ref().map(|(_, telemetry)| telemetry.handle()),
)?;
let mut telemetry = telemetry.map(|(worker, telemetry)| {
task_manager.spawn_handle().spawn("telemetry", worker.run());
telemetry
});
config
.network
.extra_sets
.push(sc_finality_grandpa::grandpa_peers_set_config());
let select_chain = sc_consensus::LongestChain::new(backend.clone());
let transaction_pool = Arc::new(sc_transaction_pool::BasicPool::new_light(
config.transaction_pool.clone(),
config.prometheus_registry(),
task_manager.spawn_essential_handle(),
client.clone(),
on_demand.clone(),
));
let (grandpa_block_import, grandpa_link) = sc_finality_grandpa::block_import(
client.clone(),
&(client.clone() as Arc<_>),
select_chain,
telemetry.as_ref().map(|x| x.handle()),
)?;
let slot_duration = sc_consensus_aura::slot_duration(&*client)?.slot_duration();
let import_queue = sc_consensus_aura::import_queue::<AuraPair, _, _, _, _, _, _>(ImportQueueParams {
block_import: grandpa_block_import.clone(),
justification_import: Some(Box::new(grandpa_block_import)),
client: client.clone(),
create_inherent_data_providers: move |_, ()| async move {
let timestamp = sp_timestamp::InherentDataProvider::from_system_time();
let slot = sp_consensus_aura::inherents::InherentDataProvider::from_timestamp_and_duration(
*timestamp,
slot_duration,
);
Ok((timestamp, slot))
},
spawner: &task_manager.spawn_essential_handle(),
can_author_with: sp_consensus::NeverCanAuthor,
registry: config.prometheus_registry(),
check_for_equivocation: Default::default(),
telemetry: telemetry.as_ref().map(|x| x.handle()),
})?;
let (network, system_rpc_tx, network_starter) = sc_service::build_network(sc_service::BuildNetworkParams {
config: &config,
client: client.clone(),
transaction_pool: transaction_pool.clone(),
spawn_handle: task_manager.spawn_handle(),
import_queue,
on_demand: Some(on_demand.clone()),
block_announce_validator_builder: None,
})?;
if config.offchain_worker.enabled {
sc_service::build_offchain_workers(&config, task_manager.spawn_handle(), client.clone(), network.clone());
}
let enable_grandpa = !config.disable_grandpa;
if enable_grandpa {
let name = config.network.node_name.clone();
let config = sc_finality_grandpa::Config {
gossip_duration: std::time::Duration::from_millis(333),
justification_period: 512,
name: Some(name),
observer_enabled: false,
keystore: None,
local_role: config.role.clone(),
telemetry: telemetry.as_ref().map(|x| x.handle()),
};
task_manager.spawn_handle().spawn_blocking(
"grandpa-observer",
sc_finality_grandpa::run_grandpa_observer(config, grandpa_link, network.clone())?,
);
}
sc_service::spawn_tasks(sc_service::SpawnTasksParams {
remote_blockchain: Some(backend.remote_blockchain()),
transaction_pool,
task_manager: &mut task_manager,
on_demand: Some(on_demand),
rpc_extensions_builder: Box::new(|_, _| ()),
config,
client,
keystore: keystore_container.sync_keystore(),
backend,
network,
system_rpc_tx,
telemetry: telemetry.as_mut(),
})?;
network_starter.start_network();
Ok(task_manager)
}
+4 -4
View File
@@ -39,7 +39,7 @@ frame-executive = { git = "https://github.com/paritytech/substrate", branch = "m
frame-support = { git = "https://github.com/paritytech/substrate", branch = "master" , default-features = false } frame-support = { git = "https://github.com/paritytech/substrate", branch = "master" , default-features = false }
frame-system = { git = "https://github.com/paritytech/substrate", branch = "master" , default-features = false } frame-system = { git = "https://github.com/paritytech/substrate", branch = "master" , default-features = false }
frame-system-rpc-runtime-api = { git = "https://github.com/paritytech/substrate", branch = "master" , default-features = false } frame-system-rpc-runtime-api = { git = "https://github.com/paritytech/substrate", branch = "master" , default-features = false }
pallet-aura = { git = "https://github.com/paritytech/substrate", branch = "master" , default-features = false } pallet-babe = { git = "https://github.com/paritytech/substrate", branch = "master", default-features = false }
pallet-balances = { git = "https://github.com/paritytech/substrate", branch = "master" , default-features = false } pallet-balances = { git = "https://github.com/paritytech/substrate", branch = "master" , default-features = false }
pallet-grandpa = { git = "https://github.com/paritytech/substrate", branch = "master" , default-features = false } pallet-grandpa = { git = "https://github.com/paritytech/substrate", branch = "master" , default-features = false }
pallet-randomness-collective-flip = { git = "https://github.com/paritytech/substrate", branch = "master" , default-features = false } pallet-randomness-collective-flip = { git = "https://github.com/paritytech/substrate", branch = "master" , default-features = false }
@@ -50,7 +50,7 @@ pallet-transaction-payment = { git = "https://github.com/paritytech/substrate",
pallet-transaction-payment-rpc-runtime-api = { git = "https://github.com/paritytech/substrate", branch = "master" , default-features = false } pallet-transaction-payment-rpc-runtime-api = { git = "https://github.com/paritytech/substrate", branch = "master" , default-features = false }
sp-api = { git = "https://github.com/paritytech/substrate", branch = "master" , default-features = false } sp-api = { git = "https://github.com/paritytech/substrate", branch = "master" , default-features = false }
sp-block-builder = { git = "https://github.com/paritytech/substrate", branch = "master" , default-features = false } sp-block-builder = { git = "https://github.com/paritytech/substrate", branch = "master" , default-features = false }
sp-consensus-aura = { git = "https://github.com/paritytech/substrate", branch = "master" , default-features = false } sp-consensus-babe = { git = "https://github.com/paritytech/substrate", branch = "master", default-features = false }
sp-core = { git = "https://github.com/paritytech/substrate", branch = "master" , default-features = false } sp-core = { git = "https://github.com/paritytech/substrate", branch = "master" , default-features = false }
sp-finality-grandpa = { git = "https://github.com/paritytech/substrate", branch = "master" , default-features = false } sp-finality-grandpa = { git = "https://github.com/paritytech/substrate", branch = "master" , default-features = false }
sp-inherents = { git = "https://github.com/paritytech/substrate", branch = "master" , default-features = false } sp-inherents = { git = "https://github.com/paritytech/substrate", branch = "master" , default-features = false }
@@ -89,7 +89,7 @@ std = [
"frame-system-rpc-runtime-api/std", "frame-system-rpc-runtime-api/std",
"frame-system/std", "frame-system/std",
"log/std", "log/std",
"pallet-aura/std", "pallet-babe/std",
"pallet-balances/std", "pallet-balances/std",
"pallet-bridge-currency-exchange/std", "pallet-bridge-currency-exchange/std",
"pallet-bridge-dispatch/std", "pallet-bridge-dispatch/std",
@@ -106,7 +106,7 @@ std = [
"serde", "serde",
"sp-api/std", "sp-api/std",
"sp-block-builder/std", "sp-block-builder/std",
"sp-consensus-aura/std", "sp-consensus-babe/std",
"sp-core/std", "sp-core/std",
"sp-finality-grandpa/std", "sp-finality-grandpa/std",
"sp-inherents/std", "sp-inherents/std",
+96 -28
View File
@@ -45,7 +45,6 @@ use codec::Decode;
use pallet_grandpa::{fg_primitives, AuthorityId as GrandpaId, AuthorityList as GrandpaAuthorityList}; use pallet_grandpa::{fg_primitives, AuthorityId as GrandpaId, AuthorityList as GrandpaAuthorityList};
use pallet_transaction_payment::{FeeDetails, Multiplier, RuntimeDispatchInfo}; use pallet_transaction_payment::{FeeDetails, Multiplier, RuntimeDispatchInfo};
use sp_api::impl_runtime_apis; use sp_api::impl_runtime_apis;
use sp_consensus_aura::sr25519::AuthorityId as AuraId;
use sp_core::{crypto::KeyTypeId, OpaqueMetadata}; use sp_core::{crypto::KeyTypeId, OpaqueMetadata};
use sp_runtime::traits::{Block as BlockT, IdentityLookup, NumberFor, OpaqueKeys}; use sp_runtime::traits::{Block as BlockT, IdentityLookup, NumberFor, OpaqueKeys};
use sp_runtime::{ use sp_runtime::{
@@ -127,7 +126,7 @@ pub mod opaque {
impl_opaque_keys! { impl_opaque_keys! {
pub struct SessionKeys { pub struct SessionKeys {
pub aura: Aura, pub babe: Babe,
pub grandpa: Grandpa, pub grandpa: Grandpa,
} }
} }
@@ -214,8 +213,34 @@ impl frame_system::Config for Runtime {
impl pallet_randomness_collective_flip::Config for Runtime {} impl pallet_randomness_collective_flip::Config for Runtime {}
impl pallet_aura::Config for Runtime { /// The BABE epoch configuration at genesis.
type AuthorityId = AuraId; pub const BABE_GENESIS_EPOCH_CONFIG: sp_consensus_babe::BabeEpochConfiguration =
sp_consensus_babe::BabeEpochConfiguration {
c: bp_rialto::time_units::PRIMARY_PROBABILITY,
allowed_slots: sp_consensus_babe::AllowedSlots::PrimaryAndSecondaryVRFSlots,
};
parameter_types! {
pub const EpochDuration: u64 = bp_rialto::time_units::EPOCH_DURATION_IN_SLOTS as u64;
pub const ExpectedBlockTime: bp_rialto::Moment = bp_rialto::time_units::MILLISECS_PER_BLOCK;
}
impl pallet_babe::Config for Runtime {
type EpochDuration = EpochDuration;
type ExpectedBlockTime = ExpectedBlockTime;
// session module is the trigger
type EpochChangeTrigger = pallet_babe::ExternalTrigger;
// equivocation related configuration - we don't expect any equivocations in our testnets
type KeyOwnerProofSystem = ();
type KeyOwnerProof =
<Self::KeyOwnerProofSystem as KeyOwnerProofSystem<(KeyTypeId, pallet_babe::AuthorityId)>>::Proof;
type KeyOwnerIdentification =
<Self::KeyOwnerProofSystem as KeyOwnerProofSystem<(KeyTypeId, pallet_babe::AuthorityId)>>::IdentificationTuple;
type HandleEquivocation = ();
type WeightInfo = ();
} }
type RialtoPoA = pallet_bridge_eth_poa::Instance1; type RialtoPoA = pallet_bridge_eth_poa::Instance1;
@@ -347,8 +372,8 @@ parameter_types! {
impl pallet_timestamp::Config for Runtime { impl pallet_timestamp::Config for Runtime {
/// A timestamp: milliseconds since the unix epoch. /// A timestamp: milliseconds since the unix epoch.
type Moment = u64; type Moment = bp_rialto::Moment;
type OnTimestampSet = Aura; type OnTimestampSet = Babe;
type MinimumPeriod = MinimumPeriod; type MinimumPeriod = MinimumPeriod;
// TODO: update me (https://github.com/paritytech/parity-bridges-common/issues/78) // TODO: update me (https://github.com/paritytech/parity-bridges-common/issues/78)
type WeightInfo = (); type WeightInfo = ();
@@ -404,17 +429,12 @@ impl pallet_sudo::Config for Runtime {
type Call = Call; type Call = Call;
} }
parameter_types! {
pub const Period: BlockNumber = bp_rialto::SESSION_LENGTH;
pub const Offset: BlockNumber = 0;
}
impl pallet_session::Config for Runtime { impl pallet_session::Config for Runtime {
type Event = Event; type Event = Event;
type ValidatorId = <Self as frame_system::Config>::AccountId; type ValidatorId = <Self as frame_system::Config>::AccountId;
type ValidatorIdOf = (); type ValidatorIdOf = ();
type ShouldEndSession = pallet_session::PeriodicSessions<Period, Offset>; type ShouldEndSession = Babe;
type NextSessionRotation = pallet_session::PeriodicSessions<Period, Offset>; type NextSessionRotation = Babe;
type SessionManager = pallet_shift_session_manager::Pallet<Runtime>; type SessionManager = pallet_shift_session_manager::Pallet<Runtime>;
type SessionHandler = <SessionKeys as OpaqueKeys>::KeyTypeIdProviders; type SessionHandler = <SessionKeys as OpaqueKeys>::KeyTypeIdProviders;
type Keys = SessionKeys; type Keys = SessionKeys;
@@ -513,23 +533,32 @@ construct_runtime!(
NodeBlock = opaque::Block, NodeBlock = opaque::Block,
UncheckedExtrinsic = UncheckedExtrinsic UncheckedExtrinsic = UncheckedExtrinsic
{ {
System: frame_system::{Pallet, Call, Config, Storage, Event<T>},
Sudo: pallet_sudo::{Pallet, Call, Config<T>, Storage, Event<T>},
// Must be before session.
Babe: pallet_babe::{Pallet, Call, Storage, Config, ValidateUnsigned},
Timestamp: pallet_timestamp::{Pallet, Call, Storage, Inherent},
Balances: pallet_balances::{Pallet, Call, Storage, Config<T>, Event<T>},
TransactionPayment: pallet_transaction_payment::{Pallet, Storage},
// Consensus support.
Session: pallet_session::{Pallet, Call, Storage, Event, Config<T>},
Grandpa: pallet_grandpa::{Pallet, Call, Storage, Config, Event},
ShiftSessionManager: pallet_shift_session_manager::{Pallet},
RandomnessCollectiveFlip: pallet_randomness_collective_flip::{Pallet, Storage},
// Eth-PoA chains bridge modules.
BridgeRialtoPoa: pallet_bridge_eth_poa::<Instance1>::{Pallet, Call, Config, Storage, ValidateUnsigned}, BridgeRialtoPoa: pallet_bridge_eth_poa::<Instance1>::{Pallet, Call, Config, Storage, ValidateUnsigned},
BridgeKovan: pallet_bridge_eth_poa::<Instance2>::{Pallet, Call, Config, Storage, ValidateUnsigned}, BridgeKovan: pallet_bridge_eth_poa::<Instance2>::{Pallet, Call, Config, Storage, ValidateUnsigned},
BridgeRialtoCurrencyExchange: pallet_bridge_currency_exchange::<Instance1>::{Pallet, Call}, BridgeRialtoCurrencyExchange: pallet_bridge_currency_exchange::<Instance1>::{Pallet, Call},
BridgeKovanCurrencyExchange: pallet_bridge_currency_exchange::<Instance2>::{Pallet, Call}, BridgeKovanCurrencyExchange: pallet_bridge_currency_exchange::<Instance2>::{Pallet, Call},
// Millau bridge modules.
BridgeMillauGrandpa: pallet_bridge_grandpa::{Pallet, Call, Storage}, BridgeMillauGrandpa: pallet_bridge_grandpa::{Pallet, Call, Storage},
BridgeDispatch: pallet_bridge_dispatch::{Pallet, Event<T>}, BridgeDispatch: pallet_bridge_dispatch::{Pallet, Event<T>},
BridgeMillauMessages: pallet_bridge_messages::{Pallet, Call, Storage, Event<T>}, BridgeMillauMessages: pallet_bridge_messages::{Pallet, Call, Storage, Event<T>},
System: frame_system::{Pallet, Call, Config, Storage, Event<T>},
RandomnessCollectiveFlip: pallet_randomness_collective_flip::{Pallet, Storage},
Timestamp: pallet_timestamp::{Pallet, Call, Storage, Inherent},
Aura: pallet_aura::{Pallet, Config<T>},
Grandpa: pallet_grandpa::{Pallet, Call, Storage, Config, Event},
Balances: pallet_balances::{Pallet, Call, Storage, Config<T>, Event<T>},
TransactionPayment: pallet_transaction_payment::{Pallet, Storage},
Sudo: pallet_sudo::{Pallet, Call, Config<T>, Storage, Event<T>},
Session: pallet_session::{Pallet, Call, Storage, Event, Config<T>},
ShiftSessionManager: pallet_shift_session_manager::{Pallet},
} }
); );
@@ -690,13 +719,52 @@ impl_runtime_apis! {
} }
} }
impl sp_consensus_aura::AuraApi<Block, AuraId> for Runtime { impl sp_consensus_babe::BabeApi<Block> for Runtime {
fn slot_duration() -> sp_consensus_aura::SlotDuration { fn configuration() -> sp_consensus_babe::BabeGenesisConfiguration {
sp_consensus_aura::SlotDuration::from_millis(Aura::slot_duration()) // The choice of `c` parameter (where `1 - c` represents the
// probability of a slot being empty), is done in accordance to the
// slot duration and expected target block time, for safely
// resisting network delays of maximum two seconds.
// <https://research.web3.foundation/en/latest/polkadot/BABE/Babe/#6-practical-results>
sp_consensus_babe::BabeGenesisConfiguration {
slot_duration: Babe::slot_duration(),
epoch_length: EpochDuration::get(),
c: BABE_GENESIS_EPOCH_CONFIG.c,
genesis_authorities: Babe::authorities(),
randomness: Babe::randomness(),
allowed_slots: BABE_GENESIS_EPOCH_CONFIG.allowed_slots,
}
} }
fn authorities() -> Vec<AuraId> { fn current_epoch_start() -> sp_consensus_babe::Slot {
Aura::authorities() Babe::current_epoch_start()
}
fn current_epoch() -> sp_consensus_babe::Epoch {
Babe::current_epoch()
}
fn next_epoch() -> sp_consensus_babe::Epoch {
Babe::next_epoch()
}
fn generate_key_ownership_proof(
_slot: sp_consensus_babe::Slot,
_authority_id: sp_consensus_babe::AuthorityId,
) -> Option<sp_consensus_babe::OpaqueKeyOwnershipProof> {
None
}
fn submit_report_equivocation_unsigned_extrinsic(
equivocation_proof: sp_consensus_babe::EquivocationProof<<Block as BlockT>::Header>,
key_owner_proof: sp_consensus_babe::OpaqueKeyOwnershipProof,
) -> Option<()> {
let key_owner_proof = key_owner_proof.decode()?;
Babe::submit_unsigned_equivocation_report(
equivocation_proof,
key_owner_proof,
)
} }
} }
+9 -1
View File
@@ -105,7 +105,7 @@ pub use time_units::*;
/// Human readable time units defined in terms of number of blocks. /// Human readable time units defined in terms of number of blocks.
pub mod time_units { pub mod time_units {
use super::BlockNumber; use super::{BlockNumber, SESSION_LENGTH};
pub const MILLISECS_PER_BLOCK: u64 = 6000; pub const MILLISECS_PER_BLOCK: u64 = 6000;
pub const SLOT_DURATION: u64 = MILLISECS_PER_BLOCK; pub const SLOT_DURATION: u64 = MILLISECS_PER_BLOCK;
@@ -113,6 +113,11 @@ pub mod time_units {
pub const MINUTES: BlockNumber = 60_000 / (MILLISECS_PER_BLOCK as BlockNumber); pub const MINUTES: BlockNumber = 60_000 / (MILLISECS_PER_BLOCK as BlockNumber);
pub const HOURS: BlockNumber = MINUTES * 60; pub const HOURS: BlockNumber = MINUTES * 60;
pub const DAYS: BlockNumber = HOURS * 24; pub const DAYS: BlockNumber = HOURS * 24;
pub const EPOCH_DURATION_IN_SLOTS: BlockNumber = SESSION_LENGTH;
// 1 in 4 blocks (on average, not counting collisions) will be primary babe blocks.
pub const PRIMARY_PROBABILITY: (u64, u64) = (1, 4);
} }
/// Block number type used in Rialto. /// Block number type used in Rialto.
@@ -140,6 +145,9 @@ pub type AccountSigner = MultiSigner;
/// Balance of an account. /// Balance of an account.
pub type Balance = u128; pub type Balance = u128;
/// An instant or duration in time.
pub type Moment = u64;
/// Rialto chain. /// Rialto chain.
#[derive(RuntimeDebug)] #[derive(RuntimeDebug)]
pub struct Rialto; pub struct Rialto;
@@ -209,7 +209,7 @@ mod tests {
// then // then
assert_eq!( assert_eq!(
format!("{:?}", hex), format!("{:?}", hex),
"0x0c00d43593c715fdd31c61141abd04a99fd6822c8558854ccde39a5684e7a56da27de5c0" "0x0400d43593c715fdd31c61141abd04a99fd6822c8558854ccde39a5684e7a56da27de5c0"
); );
} }
@@ -222,7 +222,7 @@ mod tests {
let hex = encode_call.encode().unwrap(); let hex = encode_call.encode().unwrap();
// then // then
assert!(format!("{:?}", hex).starts_with("0x070154556e69782074696d653a")); assert!(format!("{:?}", hex).starts_with("0x000154556e69782074696d653a"));
} }
#[test] #[test]
@@ -240,7 +240,7 @@ mod tests {
let hex = encode_call.encode().unwrap(); let hex = encode_call.encode().unwrap();
// then // then
assert_eq!(format!("{:?}", hex), "0x0701081234"); assert_eq!(format!("{:?}", hex), "0x0001081234");
} }
#[test] #[test]
@@ -253,7 +253,7 @@ mod tests {
let hex = encode_call.encode().unwrap(); let hex = encode_call.encode().unwrap();
// then // then
assert_eq!(format!("{:?}", hex), "0x070130000000000000000000000000"); assert_eq!(format!("{:?}", hex), "0x000130000000000000000000000000");
} }
#[test] #[test]
@@ -344,7 +344,7 @@ mod tests {
signature, signature,
), ),
dispatch_fee_payment: bp_runtime::messages::DispatchFeePayment::AtSourceChain, dispatch_fee_payment: bp_runtime::messages::DispatchFeePayment::AtSourceChain,
call: hex!("0701081234").to_vec(), call: hex!("0001081234").to_vec(),
} }
); );
} }