difftreelog
Merge pull request #1012 from UniqueNetwork/feature/lookahead-leftovers
in: master
Fix lookahead collator build
11 files changed
Cargo.lockdiffbeforeafterboth--- a/Cargo.lock
+++ b/Cargo.lock
@@ -6450,6 +6450,7 @@
"cumulus-pallet-parachain-system",
"cumulus-pallet-xcm",
"cumulus-pallet-xcmp-queue",
+ "cumulus-primitives-aura",
"cumulus-primitives-core",
"cumulus-primitives-timestamp",
"cumulus-primitives-utility",
@@ -8109,12 +8110,14 @@
"pallet-evm-coder-substrate",
"pallet-nonfungible",
"pallet-refungible",
+ "pallet-structure",
"parity-scale-codec",
"scale-info",
"sp-core",
"sp-io",
"sp-runtime",
"sp-std",
+ "up-common",
"up-data-structs",
]
@@ -14732,6 +14735,7 @@
"cumulus-client-consensus-proposer",
"cumulus-client-network",
"cumulus-client-service",
+ "cumulus-primitives-aura",
"cumulus-primitives-core",
"cumulus-primitives-parachain-inherent",
"cumulus-relay-chain-inprocess-interface",
Cargo.tomldiffbeforeafterboth--- a/Cargo.toml
+++ b/Cargo.toml
@@ -100,6 +100,7 @@
cumulus-pallet-parachain-system = { default-features = false, git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.1.0" }
cumulus-pallet-xcm = { default-features = false, git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.1.0" }
cumulus-pallet-xcmp-queue = { default-features = false, git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.1.0" }
+cumulus-primitives-aura = { default-features = false, git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.1.0" }
cumulus-primitives-core = { default-features = false, git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.1.0" }
cumulus-primitives-parachain-inherent = { default-features = false, git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.1.0" }
cumulus-primitives-timestamp = { default-features = false, git = "https://github.com/paritytech/polkadot-sdk", branch = "release-polkadot-v1.1.0" }
node/cli/Cargo.tomldiffbeforeafterboth--- a/node/cli/Cargo.toml
+++ b/node/cli/Cargo.toml
@@ -36,6 +36,7 @@
cumulus-client-consensus-proposer = { workspace = true }
cumulus-client-network = { workspace = true }
cumulus-client-service = { workspace = true }
+cumulus-primitives-aura = { workspace = true }
cumulus-primitives-core = { workspace = true }
cumulus-primitives-parachain-inherent = { features = ["std"], workspace = true }
cumulus-relay-chain-inprocess-interface = { workspace = true }
@@ -113,7 +114,9 @@
'quartz-runtime?/gov-test-timings',
'unique-runtime?/gov-test-timings',
]
-lookahead = []
+lookahead = [
+ 'opal-runtime/lookahead'
+]
pov-estimate = [
'opal-runtime/pov-estimate',
'quartz-runtime?/pov-estimate',
node/cli/src/command.rsdiffbeforeafterboth1// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.2// This file is part of Unique Network.34// Unique Network is free software: you can redistribute it and/or modify5// it under the terms of the GNU General Public License as published by6// the Free Software Foundation, either version 3 of the License, or7// (at your option) any later version.89// Unique Network is distributed in the hope that it will be useful,10// but WITHOUT ANY WARRANTY; without even the implied warranty of11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the12// GNU General Public License for more details.1314// You should have received a copy of the GNU General Public License15// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.1617// Original license18// This file is part of Substrate.1920// Copyright (C) 2017-2021 Parity Technologies (UK) Ltd.21// SPDX-License-Identifier: Apache-2.02223// Licensed under the Apache License, Version 2.0 (the "License");24// you may not use this file except in compliance with the License.25// You may obtain a copy of the License at26//27// http://www.apache.org/licenses/LICENSE-2.028//29// Unless required by applicable law or agreed to in writing, software30// distributed under the License is distributed on an "AS IS" BASIS,31// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.32// See the License for the specific language governing permissions and33// limitations under the License.3435use cumulus_primitives_core::ParaId;36use log::info;37use sc_cli::{38 ChainSpec, CliConfiguration, DefaultConfigurationValues, ImportParams, KeystoreParams,39 NetworkParams, Result, SharedParams, SubstrateCli,40};41use sc_service::config::{BasePath, PrometheusConfig};42use sp_runtime::traits::AccountIdConversion;43use up_common::types::opaque::RuntimeId;4445#[cfg(feature = "quartz-runtime")]46use crate::service::QuartzRuntimeExecutor;47#[cfg(feature = "unique-runtime")]48use crate::service::UniqueRuntimeExecutor;49use crate::{50 chain_spec::{self, RuntimeIdentification, ServiceId, ServiceIdentification},51 cli::{Cli, RelayChainCli, Subcommand},52 service::{new_partial, start_dev_node, start_node, OpalRuntimeExecutor},53};5455macro_rules! no_runtime_err {56 ($runtime_id:expr) => {57 format!(58 "No runtime valid runtime was found for chain {:#?}",59 $runtime_id60 )61 };62}6364fn load_spec(id: &str) -> std::result::Result<Box<dyn sc_service::ChainSpec>, String> {65 Ok(match id {66 "dev" => Box::new(chain_spec::development_config()),67 "" | "local" => Box::new(chain_spec::local_testnet_config()),68 path => {69 let path = std::path::PathBuf::from(path);70 #[allow(clippy::redundant_clone)]71 let chain_spec = Box::new(chain_spec::OpalChainSpec::from_json_file(path.clone())?)72 as Box<dyn sc_service::ChainSpec>;7374 match chain_spec.runtime_id() {75 #[cfg(feature = "unique-runtime")]76 RuntimeId::Unique => Box::new(chain_spec::UniqueChainSpec::from_json_file(path)?),7778 #[cfg(feature = "quartz-runtime")]79 RuntimeId::Quartz => Box::new(chain_spec::QuartzChainSpec::from_json_file(path)?),8081 RuntimeId::Opal => chain_spec,82 runtime_id => return Err(no_runtime_err!(runtime_id)),83 }84 }85 })86}8788impl SubstrateCli for Cli {89 // TODO use args90 fn impl_name() -> String {91 format!("{} Node", Self::node_name())92 }9394 fn impl_version() -> String {95 env!("SUBSTRATE_CLI_IMPL_VERSION").into()96 }97 // TODO use args98 fn description() -> String {99 format!(100 "{} Node\n\nThe command-line arguments provided first will be \101 passed to the parachain node, while the arguments provided after -- will be passed \102 to the relaychain node.\n\n\103 {} [parachain-args] -- [relaychain-args]",104 Self::node_name(),105 Self::executable_name()106 )107 }108109 fn author() -> String {110 env!("CARGO_PKG_AUTHORS").into()111 }112113 //TODO use args114 fn support_url() -> String {115 "support@unique.network".into()116 }117118 fn copyright_start_year() -> i32 {119 2019120 }121122 fn load_spec(&self, id: &str) -> std::result::Result<Box<dyn sc_service::ChainSpec>, String> {123 load_spec(id)124 }125}126127impl SubstrateCli for RelayChainCli {128 // TODO use args129 fn impl_name() -> String {130 format!("{} Node", Cli::node_name())131 }132133 fn impl_version() -> String {134 env!("SUBSTRATE_CLI_IMPL_VERSION").into()135 }136 // TODO use args137 fn description() -> String {138 format!(139 "{} Node\n\nThe command-line arguments provided first will be \140 passed to the parachain node, while the arguments provided after -- will be passed \141 to the relaychain node.\n\n\142 parachain-collator [parachain-args] -- [relaychain-args]",143 Cli::node_name()144 )145 }146147 fn author() -> String {148 env!("CARGO_PKG_AUTHORS").into()149 }150 // TODO use args151 fn support_url() -> String {152 "support@unique.network".into()153 }154155 fn copyright_start_year() -> i32 {156 2019157 }158159 fn load_spec(&self, id: &str) -> std::result::Result<Box<dyn sc_service::ChainSpec>, String> {160 polkadot_cli::Cli::from_iter([RelayChainCli::executable_name()].iter()).load_spec(id)161 }162}163164macro_rules! async_run_with_runtime {165 (166 $runtime:path, $runtime_api:path, $executor:path,167 $runner:ident, $components:ident, $cli:ident, $cmd:ident, $config:ident,168 $( $code:tt )*169 ) => {170 $runner.async_run(|$config| {171 let $components = new_partial::<172 $runtime, $runtime_api, $executor, _173 >(174 &$config,175 crate::service::parachain_build_import_queue::<$runtime, _, _>,176 )?;177 let task_manager = $components.task_manager;178179 { $( $code )* }.map(|v| (v, task_manager))180 })181 };182}183184macro_rules! construct_async_run {185 (|$components:ident, $cli:ident, $cmd:ident, $config:ident| $( $code:tt )* ) => {{186 let runner = $cli.create_runner($cmd)?;187188 match runner.config().chain_spec.runtime_id() {189 #[cfg(feature = "unique-runtime")]190 RuntimeId::Unique => async_run_with_runtime!(191 unique_runtime::Runtime, unique_runtime::RuntimeApi, UniqueRuntimeExecutor,192 runner, $components, $cli, $cmd, $config, $( $code )*193 ),194195 #[cfg(feature = "quartz-runtime")]196 RuntimeId::Quartz => async_run_with_runtime!(197 quartz_runtime::Runtime, quartz_runtime::RuntimeApi, QuartzRuntimeExecutor,198 runner, $components, $cli, $cmd, $config, $( $code )*199 ),200201 RuntimeId::Opal => async_run_with_runtime!(202 opal_runtime::Runtime, opal_runtime::RuntimeApi, OpalRuntimeExecutor,203 runner, $components, $cli, $cmd, $config, $( $code )*204 ),205206 runtime_id => Err(no_runtime_err!(runtime_id).into())207 }208 }}209}210211macro_rules! sync_run_with_runtime {212 (213 $runtime:path, $runtime_api:path, $executor:path,214 $runner:ident, $components:ident, $cli:ident, $cmd:ident, $config:ident,215 $( $code:tt )*216 ) => {217 $runner.sync_run(|$config| {218 let $components = new_partial::<219 $runtime, $runtime_api, $executor, _220 >(221 &$config,222 crate::service::parachain_build_import_queue::<$runtime, _, _>,223 )?;224225 $( $code )*226 })227 };228}229230macro_rules! construct_sync_run {231 (|$components:ident, $cli:ident, $cmd:ident, $config:ident| $( $code:tt )* ) => {{232 let runner = $cli.create_runner($cmd)?;233234 match runner.config().chain_spec.runtime_id() {235 #[cfg(feature = "unique-runtime")]236 RuntimeId::Unique => sync_run_with_runtime!(237 unique_runtime::Runtime, unique_runtime::RuntimeApi, UniqueRuntimeExecutor,238 runner, $components, $cli, $cmd, $config, $( $code )*239 ),240241 #[cfg(feature = "quartz-runtime")]242 RuntimeId::Quartz => sync_run_with_runtime!(243 quartz_runtime::Runtime, quartz_runtime::RuntimeApi, QuartzRuntimeExecutor,244 runner, $components, $cli, $cmd, $config, $( $code )*245 ),246247 RuntimeId::Opal => sync_run_with_runtime!(248 opal_runtime::Runtime, opal_runtime::RuntimeApi, OpalRuntimeExecutor,249 runner, $components, $cli, $cmd, $config, $( $code )*250 ),251252 runtime_id => Err(no_runtime_err!(runtime_id).into())253 }254 }}255}256257macro_rules! start_node_using_chain_runtime {258 ($start_node_fn:ident($config:expr $(, $($args:expr),+)?) $($code:tt)*) => {259 match $config.chain_spec.runtime_id() {260 #[cfg(feature = "unique-runtime")]261 RuntimeId::Unique => $start_node_fn::<262 unique_runtime::Runtime,263 unique_runtime::RuntimeApi,264 UniqueRuntimeExecutor,265 >($config $(, $($args),+)?) $($code)*,266267 #[cfg(feature = "quartz-runtime")]268 RuntimeId::Quartz => $start_node_fn::<269 quartz_runtime::Runtime,270 quartz_runtime::RuntimeApi,271 QuartzRuntimeExecutor,272 >($config $(, $($args),+)?) $($code)*,273274 RuntimeId::Opal => $start_node_fn::<275 opal_runtime::Runtime,276 opal_runtime::RuntimeApi,277 OpalRuntimeExecutor,278 >($config $(, $($args),+)?) $($code)*,279280 runtime_id => Err(no_runtime_err!(runtime_id).into()),281 }282 };283}284285/// Parse command line arguments into service configuration.286pub fn run() -> Result<()> {287 let cli = Cli::from_args();288289 match &cli.subcommand {290 Some(Subcommand::Key(cmd)) => cmd.run(&cli),291 Some(Subcommand::BuildSpec(cmd)) => {292 let runner = cli.create_runner(cmd)?;293 runner.sync_run(|config| cmd.run(config.chain_spec, config.network))294 }295 Some(Subcommand::CheckBlock(cmd)) => {296 construct_async_run!(|components, cli, cmd, config| {297 Ok(cmd.run(components.client, components.import_queue))298 })299 }300 Some(Subcommand::ExportBlocks(cmd)) => {301 construct_async_run!(|components, cli, cmd, config| {302 Ok(cmd.run(components.client, config.database))303 })304 }305 Some(Subcommand::ExportState(cmd)) => {306 construct_async_run!(|components, cli, cmd, config| {307 Ok(cmd.run(components.client, config.chain_spec))308 })309 }310 Some(Subcommand::ImportBlocks(cmd)) => {311 construct_async_run!(|components, cli, cmd, config| {312 Ok(cmd.run(components.client, components.import_queue))313 })314 }315 Some(Subcommand::PurgeChain(cmd)) => {316 let runner = cli.create_runner(cmd)?;317318 runner.sync_run(|config| {319 let polkadot_cli = RelayChainCli::new(320 &config,321 [RelayChainCli::executable_name()]322 .iter()323 .chain(cli.relaychain_args.iter()),324 );325326 let polkadot_config = SubstrateCli::create_configuration(327 &polkadot_cli,328 &polkadot_cli,329 config.tokio_handle.clone(),330 )331 .map_err(|err| format!("Relay chain argument error: {err}"))?;332333 cmd.run(config, polkadot_config)334 })335 }336 Some(Subcommand::Revert(cmd)) => construct_async_run!(|components, cli, cmd, config| {337 Ok(cmd.run(components.client, components.backend, None))338 }),339 Some(Subcommand::ExportGenesisState(cmd)) => {340 construct_sync_run!(|components, cli, cmd, _config| {341 let spec = cli.load_spec(&cmd.shared_params.chain.clone().unwrap_or_default())?;342 cmd.run(&*spec, &*components.client)343 })344 }345 Some(Subcommand::ExportGenesisWasm(cmd)) => {346 construct_sync_run!(|_components, cli, cmd, _config| {347 let spec = cli.load_spec(&cmd.shared_params.chain.clone().unwrap_or_default())?;348 cmd.run(&*spec)349 })350 }351 #[cfg(feature = "runtime-benchmarks")]352 Some(Subcommand::Benchmark(cmd)) => {353 use frame_benchmarking_cli::{BenchmarkCmd, SUBSTRATE_REFERENCE_HARDWARE};354 use polkadot_cli::Block;355 use sp_io::SubstrateHostFunctions;356357 let runner = cli.create_runner(cmd)?;358 // Switch on the concrete benchmark sub-command-359 match cmd {360 BenchmarkCmd::Pallet(cmd) => {361 runner.sync_run(|config| cmd.run::<Block, SubstrateHostFunctions>(config))362 }363 BenchmarkCmd::Block(cmd) => runner.sync_run(|config| {364 let partials = new_partial::<365 opal_runtime::Runtime,366 opal_runtime::RuntimeApi,367 OpalRuntimeExecutor,368 _,369 >(370 &config,371 crate::service::parachain_build_import_queue::<opal_runtime::Runtime, _, _>,372 )?;373 cmd.run(partials.client)374 }),375 BenchmarkCmd::Storage(cmd) => runner.sync_run(|config| {376 let partials = new_partial::<377 opal_runtime::Runtime,378 opal_runtime::RuntimeApi,379 OpalRuntimeExecutor,380 _,381 >(382 &config,383 crate::service::parachain_build_import_queue::<opal_runtime::Runtime, _, _>,384 )?;385 let db = partials.backend.expose_db();386 let storage = partials.backend.expose_storage();387388 cmd.run(config, partials.client.clone(), db, storage)389 }),390 BenchmarkCmd::Machine(cmd) => {391 runner.sync_run(|config| cmd.run(&config, SUBSTRATE_REFERENCE_HARDWARE.clone()))392 }393 BenchmarkCmd::Overhead(_) | BenchmarkCmd::Extrinsic(_) => {394 Err("Unsupported benchmarking command".into())395 }396 }397 }398 #[cfg(feature = "try-runtime")]399 // embedded try-runtime cli will be removed soon.400 #[allow(deprecated)]401 Some(Subcommand::TryRuntime(cmd)) => {402 use std::{future::Future, pin::Pin};403404 use polkadot_cli::Block;405 use sc_executor::{sp_wasm_interface::ExtendedHostFunctions, NativeExecutionDispatch};406 use try_runtime_cli::block_building_info::timestamp_with_aura_info;407408 let runner = cli.create_runner(cmd)?;409410 // grab the task manager.411 let registry = &runner412 .config()413 .prometheus_config414 .as_ref()415 .map(|cfg| &cfg.registry);416 let task_manager =417 sc_service::TaskManager::new(runner.config().tokio_handle.clone(), *registry)418 .map_err(|e| format!("Error: {e:?}"))?;419 let info_provider = Some(timestamp_with_aura_info(12000));420421 runner.async_run(|config| -> Result<(Pin<Box<dyn Future<Output = _>>>, _)> {422 Ok((423 match config.chain_spec.runtime_id() {424 #[cfg(feature = "unique-runtime")]425 RuntimeId::Unique => Box::pin(cmd.run::<Block, ExtendedHostFunctions<426 sp_io::SubstrateHostFunctions,427 <UniqueRuntimeExecutor as NativeExecutionDispatch>::ExtendHostFunctions,428 >, _>(info_provider)),429430 #[cfg(feature = "quartz-runtime")]431 RuntimeId::Quartz => Box::pin(cmd.run::<Block, ExtendedHostFunctions<432 sp_io::SubstrateHostFunctions,433 <QuartzRuntimeExecutor as NativeExecutionDispatch>::ExtendHostFunctions,434 >, _>(info_provider)),435436 RuntimeId::Opal => Box::pin(cmd.run::<Block, ExtendedHostFunctions<437 sp_io::SubstrateHostFunctions,438 <OpalRuntimeExecutor as NativeExecutionDispatch>::ExtendHostFunctions,439 >, _>(info_provider)),440 runtime_id => return Err(no_runtime_err!(runtime_id).into()),441 },442 task_manager,443 ))444 })445 }446 #[cfg(not(feature = "try-runtime"))]447 Some(Subcommand::TryRuntime) => {448 Err("Try-runtime must be enabled by `--features try-runtime`.".into())449 }450 None => {451 let runner = cli.create_runner(&cli.run.normalize())?;452 let collator_options = cli.run.collator_options();453454 runner.run_node_until_exit(|config| async move {455 let hwbench = if !cli.no_hardware_benchmarks {456 config.database.path().map(|database_path| {457 let _ = std::fs::create_dir_all(database_path);458 sc_sysinfo::gather_hwbench(Some(database_path))459 })460 } else {461 None462 };463464 let extensions = chain_spec::Extensions::try_get(&*config.chain_spec);465466 let service_id = config.chain_spec.service_id();467 let relay_chain_id = extensions.map(|e| e.relay_chain.clone());468 let is_dev_service = matches![service_id, ServiceId::Dev]469 || relay_chain_id == Some("dev-service".into());470471 if is_dev_service {472 info!("Running Dev service");473474 let mut config = config;475476 config.state_pruning = Some(sc_service::PruningMode::ArchiveAll);477478 return start_node_using_chain_runtime! {479 start_dev_node(config, cli.idle_autoseal_interval, cli.autoseal_finalization_delay, cli.disable_autoseal_on_tx).map_err(Into::into)480 };481 };482483 let para_id = extensions484 .map(|e| e.para_id)485 .ok_or("Could not find parachain ID in chain-spec.")?;486487 let polkadot_cli = RelayChainCli::new(488 &config,489 [RelayChainCli::executable_name()]490 .iter()491 .chain(cli.relaychain_args.iter()),492 );493494 let para_id = ParaId::from(para_id);495496 let parachain_account =497 AccountIdConversion::<polkadot_primitives::AccountId>::into_account_truncating(498 ¶_id,499 );500501 let polkadot_config = SubstrateCli::create_configuration(502 &polkadot_cli,503 &polkadot_cli,504 config.tokio_handle.clone(),505 )506 .map_err(|err| format!("Relay chain argument error: {err}"))?;507508 info!("Parachain id: {:?}", para_id);509 info!("Parachain Account: {}", parachain_account);510 info!(511 "Is collating: {}",512 if config.role.is_authority() {513 "yes"514 } else {515 "no"516 }517 );518519 start_node_using_chain_runtime! {520 start_node(config, polkadot_config, collator_options, para_id, hwbench)521 .await522 .map(|r| r.0)523 .map_err(Into::into)524 }525 })526 }527 }528}529530impl DefaultConfigurationValues for RelayChainCli {531 fn p2p_listen_port() -> u16 {532 30334533 }534535 fn rpc_listen_port() -> u16 {536 9945537 }538539 fn prometheus_listen_port() -> u16 {540 9616541 }542}543544impl CliConfiguration<Self> for RelayChainCli {545 fn shared_params(&self) -> &SharedParams {546 self.base.base.shared_params()547 }548549 fn import_params(&self) -> Option<&ImportParams> {550 self.base.base.import_params()551 }552553 fn network_params(&self) -> Option<&NetworkParams> {554 self.base.base.network_params()555 }556557 fn keystore_params(&self) -> Option<&KeystoreParams> {558 self.base.base.keystore_params()559 }560561 fn base_path(&self) -> Result<Option<BasePath>> {562 Ok(self563 .shared_params()564 .base_path()?565 .or_else(|| Some(self.base_path.clone().into())))566 }567568 fn prometheus_config(569 &self,570 default_listen_port: u16,571 chain_spec: &Box<dyn ChainSpec>,572 ) -> Result<Option<PrometheusConfig>> {573 self.base574 .base575 .prometheus_config(default_listen_port, chain_spec)576 }577578 fn init<F>(579 &self,580 _support_url: &String,581 _impl_version: &String,582 _logger_hook: F,583 _config: &sc_service::Configuration,584 ) -> Result<()> {585 unreachable!("PolkadotCli is never initialized; qed");586 }587588 fn chain_id(&self, is_dev: bool) -> Result<String> {589 let chain_id = self.base.base.chain_id(is_dev)?;590591 Ok(if chain_id.is_empty() {592 self.chain_id.clone().unwrap_or_default()593 } else {594 chain_id595 })596 }597598 fn role(&self, is_dev: bool) -> Result<sc_service::Role> {599 self.base.base.role(is_dev)600 }601602 fn transaction_pool(&self, is_dev: bool) -> Result<sc_service::config::TransactionPoolOptions> {603 self.base.base.transaction_pool(is_dev)604 }605606 fn rpc_methods(&self) -> Result<sc_service::config::RpcMethods> {607 self.base.base.rpc_methods()608 }609610 fn rpc_max_connections(&self) -> Result<u32> {611 self.base.base.rpc_max_connections()612 }613614 fn rpc_cors(&self, is_dev: bool) -> Result<Option<Vec<String>>> {615 self.base.base.rpc_cors(is_dev)616 }617618 fn default_heap_pages(&self) -> Result<Option<u64>> {619 self.base.base.default_heap_pages()620 }621622 fn force_authoring(&self) -> Result<bool> {623 self.base.base.force_authoring()624 }625626 fn disable_grandpa(&self) -> Result<bool> {627 self.base.base.disable_grandpa()628 }629630 fn max_runtime_instances(&self) -> Result<Option<usize>> {631 self.base.base.max_runtime_instances()632 }633634 fn announce_block(&self) -> Result<bool> {635 self.base.base.announce_block()636 }637638 fn telemetry_endpoints(639 &self,640 chain_spec: &Box<dyn ChainSpec>,641 ) -> Result<Option<sc_telemetry::TelemetryEndpoints>> {642 self.base.base.telemetry_endpoints(chain_spec)643 }644}node/cli/src/service.rsdiffbeforeafterboth--- a/node/cli/src/service.rs
+++ b/node/cli/src/service.rs
@@ -221,6 +221,14 @@
{
}
);
+#[cfg(not(feature = "lookahead"))]
+ez_bounds!(
+ pub trait LookaheadApiDep {}
+);
+#[cfg(feature = "lookahead")]
+ez_bounds!(
+ pub trait LookaheadApiDep: cumulus_primitives_aura::AuraUnincludedSegmentApi<Block> {}
+);
/// Starts a `ServiceBuilder` for a full service.
///
@@ -358,6 +366,7 @@
+ Sync
+ 'static,
RuntimeApi::RuntimeApi: RuntimeApiDep<Runtime> + 'static,
+ RuntimeApi::RuntimeApi: LookaheadApiDep,
Runtime: RuntimeInstance,
ExecutorDispatch: NativeExecutionDispatch + 'static,
{
@@ -687,6 +696,8 @@
announce_block: Arc<dyn Fn(Hash, Option<Vec<u8>>) + Send + Sync>,
}
+// Clones ignored for optional lookahead collator
+#[allow(clippy::redundant_clone)]
pub fn start_consensus<ExecutorDispatch, RuntimeApi, Runtime>(
client: Arc<FullClient<RuntimeApi, ExecutorDispatch>>,
transaction_pool: Arc<
@@ -701,6 +712,7 @@
+ Sync
+ 'static,
RuntimeApi::RuntimeApi: RuntimeApiDep<Runtime> + 'static,
+ RuntimeApi::RuntimeApi: LookaheadApiDep,
Runtime: RuntimeInstance,
{
let StartConsensusParameters {
@@ -735,12 +747,12 @@
client.clone(),
);
- let block_import = ParachainBlockImport::new(client.clone(), backend);
+ let block_import = ParachainBlockImport::new(client.clone(), backend.clone());
let params = BuildAuraConsensusParams {
create_inherent_data_providers: move |_, ()| async move { Ok(()) },
block_import,
- para_client: client,
+ para_client: client.clone(),
#[cfg(feature = "lookahead")]
para_backend: backend,
para_id,
@@ -751,10 +763,19 @@
proposer,
collator_service,
// With async-baking, we allowed to be both slower (longer authoring) and faster (multiple para blocks per relay block)
+ #[cfg(not(feature = "lookahead"))]
authoring_duration: Duration::from_millis(500),
+ #[cfg(feature = "lookahead")]
+ authoring_duration: Duration::from_millis(1500),
overseer_handle,
#[cfg(feature = "lookahead")]
- code_hash_provider: || {},
+ code_hash_provider: move |block_hash| {
+ client
+ .code_at(block_hash)
+ .ok()
+ .map(cumulus_primitives_core::relay_chain::ValidationCode)
+ .map(|c| c.hash())
+ },
collator_key,
relay_chain_slot_duration,
};
@@ -762,7 +783,10 @@
task_manager.spawn_essential_handle().spawn(
"aura",
None,
+ #[cfg(not(feature = "lookahead"))]
run_aura::<_, AuraAuthorityPair, _, _, _, _, _, _, _>(params),
+ #[cfg(feature = "lookahead")]
+ run_aura::<_, AuraAuthorityPair, _, _, _, _, _, _, _, _, _>(params),
);
Ok(())
}
pallets/inflation/src/lib.rsdiffbeforeafterboth--- a/pallets/inflation/src/lib.rs
+++ b/pallets/inflation/src/lib.rs
@@ -70,8 +70,10 @@
+ Mutate<Self::AccountId>;
type TreasuryAccountId: Get<Self::AccountId>;
- // The block number provider
- type BlockNumberProvider: BlockNumberProvider<BlockNumber = BlockNumberFor<Self>>;
+ // The block number provider, which should be callable from `on_initialize` hook.
+ type OnInitializeBlockNumberProvider: BlockNumberProvider<
+ BlockNumber = BlockNumberFor<Self>,
+ >;
/// Number of blocks that pass between treasury balance updates due to inflation
#[pallet::constant]
@@ -118,7 +120,7 @@
};
let block_interval: u32 = T::InflationBlockInterval::get().try_into().unwrap_or(0);
- let current_relay_block = T::BlockNumberProvider::current_block_number();
+ let current_relay_block = T::OnInitializeBlockNumberProvider::current_block_number();
let next_inflation: BlockNumberFor<T> = <NextInflationBlock<T>>::get();
add_weight(1, 0, Weight::from_parts(5_000_000, 0));
primitives/common/src/constants.rsdiffbeforeafterboth--- a/primitives/common/src/constants.rs
+++ b/primitives/common/src/constants.rs
@@ -23,7 +23,10 @@
use crate::types::{Balance, BlockNumber};
+#[cfg(not(feature = "lookahead"))]
pub const MILLISECS_PER_BLOCK: u64 = 12000;
+#[cfg(feature = "lookahead")]
+pub const MILLISECS_PER_BLOCK: u64 = 3000;
pub const MILLISECS_PER_RELAY_BLOCK: u64 = 6000;
pub const SLOT_DURATION: u64 = MILLISECS_PER_BLOCK;
runtime/common/config/pallets/mod.rsdiffbeforeafterboth--- a/runtime/common/config/pallets/mod.rs
+++ b/runtime/common/config/pallets/mod.rs
@@ -21,7 +21,7 @@
traits::{ConstU32, ConstU64, Currency},
};
use sp_arithmetic::Perbill;
-use sp_runtime::traits::AccountIdConversion;
+use sp_runtime::traits::{AccountIdConversion, BlockNumberProvider};
use up_common::{
constants::*,
types::{AccountId, Balance, BlockNumber},
@@ -105,12 +105,34 @@
pub const InflationBlockInterval: BlockNumber = 100; // every time per how many blocks inflation is applied
}
+/// Pallet-inflation needs block number in on_initialize, where there is no `validation_data` exists yet
+pub struct OnInitializeBlockNumberProvider;
+impl BlockNumberProvider for OnInitializeBlockNumberProvider {
+ type BlockNumber = BlockNumber;
+
+ fn current_block_number() -> Self::BlockNumber {
+ use hex_literal::hex;
+ use parity_scale_codec::Decode;
+ use sp_io::storage;
+ // TODO: Replace with the following code after https://github.com/paritytech/polkadot-sdk/commit/3ea497b5a0fdda252f9c5a3c257cfaf8685f02fd lands
+ // <cumulus_pallet_parachain_system::Pallet<Runtime>>::last_relay_block_number()
+
+ // ParachainSystem.LastRelayChainBlockNumber
+ let Some(encoded) = storage::get(&hex!("45323df7cc47150b3930e2666b0aa313a2bca190d36bd834cc73a38fc213ecbd")) else {
+ // First parachain block
+ return Default::default()
+ };
+ BlockNumber::decode(&mut encoded.as_ref())
+ .expect("typeof(RelayBlockNumber) == typeof(BlockNumber) == u32; qed")
+ }
+}
+
/// Used for the pallet inflation
impl pallet_inflation::Config for Runtime {
type Currency = Balances;
type TreasuryAccountId = TreasuryAccountId;
type InflationBlockInterval = InflationBlockInterval;
- type BlockNumberProvider = RelayChainBlockNumberProvider<Runtime>;
+ type OnInitializeBlockNumberProvider = OnInitializeBlockNumberProvider;
}
impl pallet_unique::Config for Runtime {
runtime/common/config/parachain.rsdiffbeforeafterboth--- a/runtime/common/config/parachain.rs
+++ b/runtime/common/config/parachain.rs
@@ -38,9 +38,29 @@
type ReservedDmpWeight = ReservedDmpWeight;
type ReservedXcmpWeight = ReservedXcmpWeight;
type XcmpMessageHandler = XcmpQueue;
+ #[cfg(not(feature = "lookahead"))]
type CheckAssociatedRelayNumber = cumulus_pallet_parachain_system::RelayNumberStrictlyIncreases;
+ #[cfg(feature = "lookahead")]
+ type CheckAssociatedRelayNumber =
+ cumulus_pallet_parachain_system::RelayNumberMonotonicallyIncreases;
}
impl parachain_info::Config for Runtime {}
impl cumulus_pallet_aura_ext::Config for Runtime {}
+
+/// Maximum number of blocks simultaneously accepted by the Runtime, not yet included
+/// into the relay chain.
+#[cfg(feature = "lookahead")]
+const UNINCLUDED_SEGMENT_CAPACITY: u32 = 3;
+/// How many parachain blocks are processed by the relay chain per parent. Limits the
+/// number of blocks authored per slot.
+#[cfg(feature = "lookahead")]
+const BLOCK_PROCESSING_VELOCITY: u32 = 2;
+#[cfg(feature = "lookahead")]
+pub type ConsensusHook = cumulus_pallet_aura_ext::FixedVelocityConsensusHook<
+ Runtime,
+ { MILLISECS_PER_RELAY_BLOCK as u32 },
+ BLOCK_PROCESSING_VELOCITY,
+ UNINCLUDED_SEGMENT_CAPACITY,
+>;
runtime/common/runtime_apis.rsdiffbeforeafterboth--- a/runtime/common/runtime_apis.rs
+++ b/runtime/common/runtime_apis.rs
@@ -679,6 +679,16 @@
}
}
+ #[cfg(feature = "lookahead")]
+ impl cumulus_primitives_aura::AuraUnincludedSegmentApi<Block> for Runtime {
+ fn can_build_upon(
+ included_hash: <Block as BlockT>::Hash,
+ slot: cumulus_primitives_aura::Slot,
+ ) -> bool {
+ $crate::config::parachain::ConsensusHook::can_build_upon(included_hash, slot)
+ }
+ }
+
/// Should never be used, yet still required because of https://github.com/paritytech/polkadot-sdk/issues/27
/// Not allowed to panic, because rpc may be called using native runtime, thus causing thread panic.
impl fp_rpc::ConvertTransactionRuntimeApi<Block> for Runtime {
runtime/opal/Cargo.tomldiffbeforeafterboth--- a/runtime/opal/Cargo.toml
+++ b/runtime/opal/Cargo.toml
@@ -69,6 +69,7 @@
'cumulus-pallet-parachain-system/std',
'cumulus-pallet-xcm/std',
'cumulus-pallet-xcmp-queue/std',
+ 'cumulus-primitives-aura/std',
'cumulus-primitives-core/std',
'cumulus-primitives-utility/std',
'frame-executive/std',
@@ -230,6 +231,7 @@
preimage = []
refungible = []
session-test-timings = []
+lookahead = []
################################################################################
# local dependencies
@@ -240,6 +242,7 @@
cumulus-pallet-parachain-system = { workspace = true }
cumulus-pallet-xcm = { workspace = true }
cumulus-pallet-xcmp-queue = { workspace = true }
+cumulus-primitives-aura = { workspace = true }
cumulus-primitives-core = { workspace = true }
cumulus-primitives-timestamp = { workspace = true }
cumulus-primitives-utility = { workspace = true }