sc-block-builder: Remove BlockBuilderProvider (#2099)

The `BlockBuilderProvider` was a trait that was defined in
`sc-block-builder`. The trait was implemented for `Client`. This
basically meant that you needed to import `sc-block-builder` any way to
have access to the block builder. So, this trait was not providing any
real value. This pull request is removing the said trait. Instead of the
trait it introduces a builder for creating a `BlockBuilder`. The builder
currently has the quite fabulous name `BlockBuilderBuilder` (I'm open to
any better name 😅). The rest of the pull request is about
replacing the old trait with the new builder.

# Downstream code changes

If you used `new_block` or `new_block_at` before you now need to switch
it over to the new `BlockBuilderBuilder` pattern:

```rust
// `new` requires a type that implements `CallApiAt`. 
let mut block_builder = BlockBuilderBuilder::new(client)
                // Then you need to specify the hash of the parent block the block will be build on top of
		.on_parent_block(at)
                // The block builder also needs the block number of the parent block. 
                // Here it is fetched from the given `client` using the `HeaderBackend`
                // However, there also exists `with_parent_block_number` for directly passing the number
		.fetch_parent_block_number(client)
		.unwrap()
                // Enable proof recording if required. This call is optional.
		.enable_proof_recording()
                // Pass the digests. This call is optional.
                .with_inherent_digests(digests)
		.build()
		.expect("Creates new block builder");
```

---------

Co-authored-by: Sebastian Kunert <skunert49@gmail.com>
Co-authored-by: command-bot <>
This commit is contained in:
Bastian Köcher
2023-11-03 19:06:31 +01:00
committed by GitHub
parent cd2d5d2579
commit ca5f10567a
49 changed files with 1808 additions and 737 deletions
Generated
-2
View File
@@ -14769,7 +14769,6 @@ name = "sc-block-builder"
version = "0.10.0-dev"
dependencies = [
"parity-scale-codec",
"sc-client-api",
"sp-api",
"sp-block-builder",
"sp-blockchain",
@@ -15834,7 +15833,6 @@ dependencies = [
"parking_lot 0.12.1",
"pin-project",
"rand 0.8.5",
"sc-block-builder",
"sc-chain-spec",
"sc-client-api",
"sc-client-db",
+16 -12
View File
@@ -14,13 +14,13 @@
// You should have received a copy of the GNU General Public License
// along with Cumulus. If not, see <http://www.gnu.org/licenses/>.
use crate::{Backend, Client};
use crate::Client;
use cumulus_primitives_core::{ParachainBlockData, PersistedValidationData};
use cumulus_primitives_parachain_inherent::{ParachainInherentData, INHERENT_IDENTIFIER};
use cumulus_test_relay_sproof_builder::RelayStateSproofBuilder;
use cumulus_test_runtime::{Block, GetLastTimestamp, Hash, Header};
use polkadot_primitives::{BlockNumber as PBlockNumber, Hash as PHash};
use sc_block_builder::{BlockBuilder, BlockBuilderProvider};
use sc_block_builder::{BlockBuilder, BlockBuilderBuilder};
use sp_api::ProvideRuntimeApi;
use sp_runtime::traits::{Block as BlockT, Header as HeaderT};
@@ -37,7 +37,7 @@ pub trait InitBlockBuilder {
&self,
validation_data: Option<PersistedValidationData<PHash, PBlockNumber>>,
relay_sproof_builder: RelayStateSproofBuilder,
) -> sc_block_builder::BlockBuilder<Block, Client, Backend>;
) -> sc_block_builder::BlockBuilder<Block, Client>;
/// Init a specific block builder at a specific block that works for the test runtime.
///
@@ -48,7 +48,7 @@ pub trait InitBlockBuilder {
at: Hash,
validation_data: Option<PersistedValidationData<PHash, PBlockNumber>>,
relay_sproof_builder: RelayStateSproofBuilder,
) -> sc_block_builder::BlockBuilder<Block, Client, Backend>;
) -> sc_block_builder::BlockBuilder<Block, Client>;
/// Init a specific block builder that works for the test runtime.
///
@@ -61,7 +61,7 @@ pub trait InitBlockBuilder {
validation_data: Option<PersistedValidationData<PHash, PBlockNumber>>,
relay_sproof_builder: RelayStateSproofBuilder,
timestamp: u64,
) -> sc_block_builder::BlockBuilder<Block, Client, Backend>;
) -> sc_block_builder::BlockBuilder<Block, Client>;
}
fn init_block_builder(
@@ -70,9 +70,13 @@ fn init_block_builder(
validation_data: Option<PersistedValidationData<PHash, PBlockNumber>>,
relay_sproof_builder: RelayStateSproofBuilder,
timestamp: u64,
) -> BlockBuilder<'_, Block, Client, Backend> {
let mut block_builder = client
.new_block_at(at, Default::default(), true)
) -> BlockBuilder<'_, Block, Client> {
let mut block_builder = BlockBuilderBuilder::new(client)
.on_parent_block(at)
.fetch_parent_block_number(client)
.unwrap()
.enable_proof_recording()
.build()
.expect("Creates new block builder for test runtime");
let mut inherent_data = sp_inherents::InherentData::new();
@@ -118,7 +122,7 @@ impl InitBlockBuilder for Client {
&self,
validation_data: Option<PersistedValidationData<PHash, PBlockNumber>>,
relay_sproof_builder: RelayStateSproofBuilder,
) -> BlockBuilder<Block, Client, Backend> {
) -> BlockBuilder<Block, Client> {
let chain_info = self.chain_info();
self.init_block_builder_at(chain_info.best_hash, validation_data, relay_sproof_builder)
}
@@ -128,7 +132,7 @@ impl InitBlockBuilder for Client {
at: Hash,
validation_data: Option<PersistedValidationData<PHash, PBlockNumber>>,
relay_sproof_builder: RelayStateSproofBuilder,
) -> BlockBuilder<Block, Client, Backend> {
) -> BlockBuilder<Block, Client> {
let last_timestamp = self.runtime_api().get_last_timestamp(at).expect("Get last timestamp");
let timestamp = last_timestamp + cumulus_test_runtime::MinimumPeriod::get();
@@ -142,7 +146,7 @@ impl InitBlockBuilder for Client {
validation_data: Option<PersistedValidationData<PHash, PBlockNumber>>,
relay_sproof_builder: RelayStateSproofBuilder,
timestamp: u64,
) -> sc_block_builder::BlockBuilder<Block, Client, Backend> {
) -> sc_block_builder::BlockBuilder<Block, Client> {
init_block_builder(self, at, validation_data, relay_sproof_builder, timestamp)
}
}
@@ -155,7 +159,7 @@ pub trait BuildParachainBlockData {
fn build_parachain_block(self, parent_state_root: Hash) -> ParachainBlockData<Block>;
}
impl<'a> BuildParachainBlockData for sc_block_builder::BlockBuilder<'a, Block, Client, Backend> {
impl<'a> BuildParachainBlockData for sc_block_builder::BlockBuilder<'a, Block, Client> {
fn build_parachain_block(self, parent_state_root: Hash) -> ParachainBlockData<Block> {
let built_block = self.build().expect("Builds the block");
+7 -3
View File
@@ -17,12 +17,12 @@
use criterion::{criterion_group, criterion_main, BatchSize, Criterion, Throughput};
use sc_block_builder::BlockBuilderBuilder;
use sc_client_api::UsageProvider;
use core::time::Duration;
use cumulus_primitives_core::ParaId;
use sc_block_builder::{BlockBuilderProvider, RecordProof};
use sp_api::{Core, ProvideRuntimeApi};
use sp_keyring::Sr25519Keyring::Alice;
@@ -52,8 +52,12 @@ fn benchmark_block_import(c: &mut Criterion) {
utils::create_benchmarking_transfer_extrinsics(&client, &src_accounts, &dst_accounts);
let parent_hash = client.usage_info().chain.best_hash;
let mut block_builder =
client.new_block_at(parent_hash, Default::default(), RecordProof::No).unwrap();
let mut block_builder = BlockBuilderBuilder::new(&*client)
.on_parent_block(parent_hash)
.fetch_parent_block_number(&*client)
.unwrap()
.build()
.unwrap();
for extrinsic in extrinsics {
block_builder.push(extrinsic).unwrap();
}
@@ -17,7 +17,6 @@
use criterion::{criterion_group, criterion_main, BatchSize, Criterion};
use sc_client_api::UsageProvider;
use sp_api::{Core, ProvideRuntimeApi};
use sp_arithmetic::{
traits::{One, Zero},
@@ -27,7 +26,7 @@ use sp_arithmetic::{
use core::time::Duration;
use cumulus_primitives_core::ParaId;
use sc_block_builder::{BlockBuilderProvider, RecordProof};
use sc_block_builder::BlockBuilderBuilder;
use sp_keyring::Sr25519Keyring::Alice;
use cumulus_test_service::bench_utils as utils;
@@ -61,10 +60,14 @@ fn benchmark_block_import(c: &mut Criterion) {
runtime.block_on(utils::import_block(&client, &block, false));
// Build the block we will use for benchmarking
let parent_hash = client.usage_info().chain.best_hash;
let parent_hash = client.chain_info().best_hash;
let parent_header = client.header(parent_hash).expect("Just fetched this hash.").unwrap();
let mut block_builder =
client.new_block_at(parent_hash, Default::default(), RecordProof::No).unwrap();
let mut block_builder = BlockBuilderBuilder::new(&*client)
.on_parent_block(parent_hash)
.fetch_parent_block_number(&*client)
.unwrap()
.build()
.unwrap();
block_builder
.push(utils::extrinsic_set_validation_data(parent_header.clone()).clone())
.unwrap();
@@ -21,7 +21,7 @@ use sc_client_api::UsageProvider;
use core::time::Duration;
use cumulus_primitives_core::ParaId;
use sc_block_builder::{BlockBuilderProvider, RecordProof};
use sc_block_builder::BlockBuilderBuilder;
use sp_keyring::Sr25519Keyring::Alice;
@@ -50,7 +50,11 @@ fn benchmark_block_production(c: &mut Criterion) {
let parent_header = client.header(parent_hash).expect("Just fetched this hash.").unwrap();
let set_validation_data_extrinsic = utils::extrinsic_set_validation_data(parent_header);
let mut block_builder = client.new_block(Default::default()).unwrap();
let mut block_builder = BlockBuilderBuilder::new(&*client)
.on_parent_block(client.chain_info().best_hash)
.with_parent_block_number(client.chain_info().best_number)
.build()
.unwrap();
block_builder.push(utils::extrinsic_set_time(&client)).unwrap();
block_builder.push(set_validation_data_extrinsic).unwrap();
let built_block = block_builder.build().unwrap();
@@ -66,7 +70,7 @@ fn benchmark_block_production(c: &mut Criterion) {
group.measurement_time(Duration::from_secs(120));
group.throughput(Throughput::Elements(max_transfer_count as u64));
let best_hash = client.chain_info().best_hash;
let chain = client.chain_info();
group.bench_function(
format!("(proof = true, transfers = {}) block production", max_transfer_count),
@@ -74,9 +78,13 @@ fn benchmark_block_production(c: &mut Criterion) {
b.iter_batched(
|| extrinsics.clone(),
|extrinsics| {
let mut block_builder = client
.new_block_at(best_hash, Default::default(), RecordProof::Yes)
let mut block_builder = BlockBuilderBuilder::new(&*client)
.on_parent_block(chain.best_hash)
.with_parent_block_number(chain.best_number)
.enable_proof_recording()
.build()
.unwrap();
for extrinsic in extrinsics {
block_builder.push(extrinsic).unwrap();
}
@@ -93,9 +101,12 @@ fn benchmark_block_production(c: &mut Criterion) {
b.iter_batched(
|| extrinsics.clone(),
|extrinsics| {
let mut block_builder = client
.new_block_at(best_hash, Default::default(), RecordProof::No)
let mut block_builder = BlockBuilderBuilder::new(&*client)
.on_parent_block(chain.best_hash)
.with_parent_block_number(chain.best_number)
.build()
.unwrap();
for extrinsic in extrinsics {
block_builder.push(extrinsic).unwrap();
}
@@ -17,7 +17,6 @@
use criterion::{criterion_group, criterion_main, BatchSize, Criterion};
use sc_client_api::UsageProvider;
use sp_arithmetic::{
traits::{One, Zero},
FixedPointNumber,
@@ -26,7 +25,7 @@ use sp_arithmetic::{
use core::time::Duration;
use cumulus_primitives_core::ParaId;
use sc_block_builder::{BlockBuilderProvider, RecordProof};
use sc_block_builder::BlockBuilderBuilder;
use sp_keyring::Sr25519Keyring::Alice;
@@ -60,11 +59,11 @@ fn benchmark_block_production_compute(c: &mut Criterion) {
runtime.block_on(utils::import_block(&client, &block, false));
initialize_glutton_pallet = false;
let parent_hash = client.usage_info().chain.best_hash;
let parent_header = client.header(parent_hash).expect("Just fetched this hash.").unwrap();
let best_hash = client.chain_info().best_hash;
let best_number = client.chain_info().best_number;
let parent_header = client.header(best_hash).expect("Just fetched this hash.").unwrap();
let set_validation_data_extrinsic = utils::extrinsic_set_validation_data(parent_header);
let set_time_extrinsic = utils::extrinsic_set_time(&client);
let best_hash = client.chain_info().best_hash;
group.bench_function(
format!(
@@ -76,8 +75,11 @@ fn benchmark_block_production_compute(c: &mut Criterion) {
b.iter_batched(
|| (set_validation_data_extrinsic.clone(), set_time_extrinsic.clone()),
|(validation_data, time)| {
let mut block_builder = client
.new_block_at(best_hash, Default::default(), RecordProof::Yes)
let mut block_builder = BlockBuilderBuilder::new(&*client)
.on_parent_block(best_hash)
.with_parent_block_number(best_number)
.enable_proof_recording()
.build()
.unwrap();
block_builder.push(validation_data).unwrap();
block_builder.push(time).unwrap();
@@ -98,8 +100,10 @@ fn benchmark_block_production_compute(c: &mut Criterion) {
b.iter_batched(
|| (set_validation_data_extrinsic.clone(), set_time_extrinsic.clone()),
|(validation_data, time)| {
let mut block_builder = client
.new_block_at(best_hash, Default::default(), RecordProof::No)
let mut block_builder = BlockBuilderBuilder::new(&*client)
.on_parent_block(best_hash)
.with_parent_block_number(best_number)
.build()
.unwrap();
block_builder.push(validation_data).unwrap();
block_builder.push(time).unwrap();
@@ -27,7 +27,7 @@ use cumulus_test_relay_sproof_builder::RelayStateSproofBuilder;
use cumulus_test_runtime::{BalancesCall, Block, Header, UncheckedExtrinsic};
use cumulus_test_service::bench_utils as utils;
use polkadot_primitives::HeadData;
use sc_block_builder::BlockBuilderProvider;
use sc_block_builder::BlockBuilderBuilder;
use sc_client_api::UsageProvider;
use sc_executor_common::wasm_runtime::WasmModule;
@@ -46,7 +46,11 @@ fn create_extrinsics(
dst_accounts: &[sr25519::Pair],
) -> (usize, Vec<UncheckedExtrinsic>) {
// Add as many tranfer extrinsics as possible into a single block.
let mut block_builder = client.new_block(Default::default()).unwrap();
let mut block_builder = BlockBuilderBuilder::new(client)
.on_parent_block(client.chain_info().best_hash)
.with_parent_block_number(client.chain_info().best_number)
.build()
.unwrap();
let mut max_transfer_count = 0;
let mut extrinsics = Vec::new();
+13 -3
View File
@@ -16,6 +16,7 @@
// limitations under the License.
use codec::Encode;
use sc_block_builder::BlockBuilderBuilder;
use crate::{construct_extrinsic, Client as TestClient};
use cumulus_primitives_core::{relay_chain::AccountId, PersistedValidationData};
@@ -26,7 +27,6 @@ use cumulus_test_runtime::{
};
use frame_system_rpc_runtime_api::AccountNonceApi;
use polkadot_primitives::HeadData;
use sc_block_builder::BlockBuilderProvider;
use sc_client_api::UsageProvider;
use sc_consensus::{
block_import::{BlockImportParams, ForkChoiceStrategy},
@@ -126,8 +126,13 @@ pub fn create_benchmarking_transfer_extrinsics(
src_accounts: &[sr25519::Pair],
dst_accounts: &[sr25519::Pair],
) -> (usize, Vec<OpaqueExtrinsic>) {
let chain = client.usage_info().chain;
// Add as many transfer extrinsics as possible into a single block.
let mut block_builder = client.new_block(Default::default()).unwrap();
let mut block_builder = BlockBuilderBuilder::new(client)
.on_parent_block(chain.best_hash)
.with_parent_block_number(chain.best_number)
.build()
.expect("Creates block builder");
let mut max_transfer_count = 0;
let mut extrinsics = Vec::new();
// Every block needs one timestamp extrinsic.
@@ -248,8 +253,13 @@ pub fn set_glutton_parameters(
Some(last_nonce),
);
extrinsics.push(set_storage);
let chain = client.usage_info().chain;
let mut block_builder = client.new_block(Default::default()).unwrap();
let mut block_builder = BlockBuilderBuilder::new(client)
.on_parent_block(chain.best_hash)
.with_parent_block_number(chain.best_number)
.build()
.unwrap();
block_builder.push(extrinsic_set_time(client)).unwrap();
block_builder.push(extrinsic_set_validation_data(parent_header)).unwrap();
for extrinsic in extrinsics {
+13 -11
View File
@@ -14,12 +14,12 @@
// You should have received a copy of the GNU General Public License
// along with Polkadot. If not, see <http://www.gnu.org/licenses/>.
use crate::{Client, FullBackend};
use crate::Client;
use parity_scale_codec::{Decode, Encode};
use polkadot_primitives::{Block, InherentData as ParachainsInherentData};
use polkadot_test_runtime::UncheckedExtrinsic;
use polkadot_test_service::GetLastTimestamp;
use sc_block_builder::{BlockBuilder, BlockBuilderProvider};
use sc_block_builder::{BlockBuilder, BlockBuilderBuilder};
use sp_api::ProvideRuntimeApi;
use sp_consensus_babe::{
digests::{PreDigest, SecondaryPlainPreDigest},
@@ -34,9 +34,7 @@ pub trait InitPolkadotBlockBuilder {
///
/// This will automatically create and push the inherents for you to make the block valid for
/// the test runtime.
fn init_polkadot_block_builder(
&self,
) -> sc_block_builder::BlockBuilder<Block, Client, FullBackend>;
fn init_polkadot_block_builder(&self) -> sc_block_builder::BlockBuilder<Block, Client>;
/// Init a Polkadot specific block builder at a specific block that works for the test runtime.
///
@@ -45,11 +43,11 @@ pub trait InitPolkadotBlockBuilder {
fn init_polkadot_block_builder_at(
&self,
hash: <Block as BlockT>::Hash,
) -> sc_block_builder::BlockBuilder<Block, Client, FullBackend>;
) -> sc_block_builder::BlockBuilder<Block, Client>;
}
impl InitPolkadotBlockBuilder for Client {
fn init_polkadot_block_builder(&self) -> BlockBuilder<Block, Client, FullBackend> {
fn init_polkadot_block_builder(&self) -> BlockBuilder<Block, Client> {
let chain_info = self.chain_info();
self.init_polkadot_block_builder_at(chain_info.best_hash)
}
@@ -57,7 +55,7 @@ impl InitPolkadotBlockBuilder for Client {
fn init_polkadot_block_builder_at(
&self,
hash: <Block as BlockT>::Hash,
) -> BlockBuilder<Block, Client, FullBackend> {
) -> BlockBuilder<Block, Client> {
let last_timestamp =
self.runtime_api().get_last_timestamp(hash).expect("Get last timestamp");
@@ -90,8 +88,12 @@ impl InitPolkadotBlockBuilder for Client {
)],
};
let mut block_builder = self
.new_block_at(hash, digest, false)
let mut block_builder = BlockBuilderBuilder::new(self)
.on_parent_block(hash)
.fetch_parent_block_number(&self)
.expect("Fetches parent block number")
.with_inherent_digests(digest)
.build()
.expect("Creates new block builder for test runtime");
let mut inherent_data = sp_inherents::InherentData::new();
@@ -144,7 +146,7 @@ pub trait BlockBuilderExt {
) -> Result<(), sp_blockchain::Error>;
}
impl BlockBuilderExt for BlockBuilder<'_, Block, Client, FullBackend> {
impl BlockBuilderExt for BlockBuilder<'_, Block, Client> {
fn push_polkadot_extrinsic(
&mut self,
ext: UncheckedExtrinsic,
@@ -20,7 +20,7 @@ use criterion::{criterion_group, criterion_main, BatchSize, Criterion, Throughpu
use kitchensink_runtime::{constants::currency::*, BalancesCall};
use node_cli::service::{create_extrinsic, FullClient};
use sc_block_builder::{BlockBuilderProvider, BuiltBlock, RecordProof};
use sc_block_builder::{BlockBuilderBuilder, BuiltBlock};
use sc_consensus::{
block_import::{BlockImportParams, ForkChoiceStrategy},
BlockImport, StateAction,
@@ -127,7 +127,11 @@ fn prepare_benchmark(client: &FullClient) -> (usize, Vec<OpaqueExtrinsic>) {
let mut max_transfer_count = 0;
let mut extrinsics = Vec::new();
let mut block_builder = client.new_block(Default::default()).unwrap();
let mut block_builder = BlockBuilderBuilder::new(client)
.on_parent_block(client.chain_info().best_hash)
.with_parent_block_number(client.chain_info().best_number)
.build()
.unwrap();
// Every block needs one timestamp extrinsic.
let extrinsic_set_time = extrinsic_set_time(1 + MINIMUM_PERIOD_FOR_BLOCKS);
@@ -174,7 +178,11 @@ fn block_production(c: &mut Criterion) {
// Buliding the very first block is around ~30x slower than any subsequent one,
// so let's make sure it's built and imported before we benchmark anything.
let mut block_builder = client.new_block(Default::default()).unwrap();
let mut block_builder = BlockBuilderBuilder::new(client)
.on_parent_block(client.chain_info().best_hash)
.with_parent_block_number(client.chain_info().best_number)
.build()
.unwrap();
block_builder.push(extrinsic_set_time(1)).unwrap();
import_block(client, block_builder.build().unwrap());
@@ -186,14 +194,19 @@ fn block_production(c: &mut Criterion) {
group.sample_size(10);
group.throughput(Throughput::Elements(max_transfer_count as u64));
let best_hash = client.chain_info().best_hash;
let chain = client.chain_info();
let best_hash = chain.best_hash;
let best_number = chain.best_number;
group.bench_function(format!("{} transfers (no proof)", max_transfer_count), |b| {
b.iter_batched(
|| extrinsics.clone(),
|extrinsics| {
let mut block_builder =
client.new_block_at(best_hash, Default::default(), RecordProof::No).unwrap();
let mut block_builder = BlockBuilderBuilder::new(client)
.on_parent_block(best_hash)
.with_parent_block_number(best_number)
.build()
.unwrap();
for extrinsic in extrinsics {
block_builder.push(extrinsic).unwrap();
}
@@ -207,8 +220,11 @@ fn block_production(c: &mut Criterion) {
b.iter_batched(
|| extrinsics.clone(),
|extrinsics| {
let mut block_builder =
client.new_block_at(best_hash, Default::default(), RecordProof::Yes).unwrap();
let mut block_builder = BlockBuilderBuilder::new(client)
.on_parent_block(best_hash)
.with_parent_block_number(best_number)
.build()
.unwrap();
for extrinsic in extrinsics {
block_builder.push(extrinsic).unwrap();
}
+8 -3
View File
@@ -39,8 +39,8 @@ use kitchensink_runtime::{
RuntimeCall, Signature, SystemCall, UncheckedExtrinsic,
};
use node_primitives::Block;
use sc_block_builder::BlockBuilderProvider;
use sc_client_api::execution_extensions::ExecutionExtensions;
use sc_block_builder::BlockBuilderBuilder;
use sc_client_api::{execution_extensions::ExecutionExtensions, UsageProvider};
use sc_client_db::PruningMode;
use sc_consensus::{BlockImport, BlockImportParams, ForkChoiceStrategy, ImportResult, ImportedAux};
use sc_executor::{NativeElseWasmExecutor, WasmExecutionMethod, WasmtimeInstantiationStrategy};
@@ -455,8 +455,13 @@ impl BenchDb {
/// Generate new block using this database.
pub fn generate_block(&mut self, content: BlockContent) -> Block {
let client = self.client();
let chain = client.usage_info().chain;
let mut block = client.new_block(Default::default()).expect("Block creation failed");
let mut block = BlockBuilderBuilder::new(&client)
.on_parent_block(chain.best_hash)
.with_parent_block_number(chain.best_number)
.build()
.expect("Failed to create block builder.");
for extrinsic in self.generate_inherents(&client) {
block.push(extrinsic).expect("Push inherent failed");
+1 -1
View File
@@ -19,7 +19,6 @@ futures-timer = "3.0.1"
log = "0.4.17"
prometheus-endpoint = { package = "substrate-prometheus-endpoint", path = "../../utils/prometheus" }
sc-block-builder = { path = "../block-builder" }
sc-client-api = { path = "../api" }
sc-proposer-metrics = { path = "../proposer-metrics" }
sc-telemetry = { path = "../telemetry" }
sc-transaction-pool-api = { path = "../transaction-pool/api" }
@@ -32,5 +31,6 @@ sp-runtime = { path = "../../primitives/runtime" }
[dev-dependencies]
parking_lot = "0.12.1"
sc-client-api = { path = "../api" }
sc-transaction-pool = { path = "../transaction-pool" }
substrate-test-runtime-client = { path = "../../test-utils/runtime/client" }
@@ -28,11 +28,10 @@ use futures::{
select,
};
use log::{debug, error, info, trace, warn};
use sc_block_builder::{BlockBuilderApi, BlockBuilderProvider};
use sc_client_api::backend;
use sc_block_builder::{BlockBuilderApi, BlockBuilderBuilder};
use sc_telemetry::{telemetry, TelemetryHandle, CONSENSUS_INFO};
use sc_transaction_pool_api::{InPoolTransaction, TransactionPool};
use sp_api::{ApiExt, ProvideRuntimeApi};
use sp_api::{ApiExt, CallApiAt, ProvideRuntimeApi};
use sp_blockchain::{ApplyExtrinsicFailed::Validity, Error::ApplyExtrinsicFailed, HeaderBackend};
use sp_consensus::{DisableProofRecording, EnableProofRecording, ProofRecording, Proposal};
use sp_core::traits::SpawnNamed;
@@ -60,7 +59,7 @@ const DEFAULT_SOFT_DEADLINE_PERCENT: Percent = Percent::from_percent(50);
const LOG_TARGET: &'static str = "basic-authorship";
/// [`Proposer`] factory.
pub struct ProposerFactory<A, B, C, PR> {
pub struct ProposerFactory<A, C, PR> {
spawn_handle: Box<dyn SpawnNamed>,
/// The client instance.
client: Arc<C>,
@@ -84,11 +83,11 @@ pub struct ProposerFactory<A, B, C, PR> {
telemetry: Option<TelemetryHandle>,
/// When estimating the block size, should the proof be included?
include_proof_in_block_size_estimation: bool,
/// phantom member to pin the `Backend`/`ProofRecording` type.
_phantom: PhantomData<(B, PR)>,
/// phantom member to pin the `ProofRecording` type.
_phantom: PhantomData<PR>,
}
impl<A, B, C> ProposerFactory<A, B, C, DisableProofRecording> {
impl<A, C> ProposerFactory<A, C, DisableProofRecording> {
/// Create a new proposer factory.
///
/// Proof recording will be disabled when using proposers built by this instance to build
@@ -114,7 +113,7 @@ impl<A, B, C> ProposerFactory<A, B, C, DisableProofRecording> {
}
}
impl<A, B, C> ProposerFactory<A, B, C, EnableProofRecording> {
impl<A, C> ProposerFactory<A, C, EnableProofRecording> {
/// Create a new proposer factory with proof recording enabled.
///
/// Each proposer created by this instance will record a proof while building a block.
@@ -147,7 +146,7 @@ impl<A, B, C> ProposerFactory<A, B, C, EnableProofRecording> {
}
}
impl<A, B, C, PR> ProposerFactory<A, B, C, PR> {
impl<A, C, PR> ProposerFactory<A, C, PR> {
/// Set the default block size limit in bytes.
///
/// The default value for the block size limit is:
@@ -176,29 +175,23 @@ impl<A, B, C, PR> ProposerFactory<A, B, C, PR> {
}
}
impl<B, Block, C, A, PR> ProposerFactory<A, B, C, PR>
impl<Block, C, A, PR> ProposerFactory<A, C, PR>
where
A: TransactionPool<Block = Block> + 'static,
B: backend::Backend<Block> + Send + Sync + 'static,
Block: BlockT,
C: BlockBuilderProvider<B, Block, C>
+ HeaderBackend<Block>
+ ProvideRuntimeApi<Block>
+ Send
+ Sync
+ 'static,
C: HeaderBackend<Block> + ProvideRuntimeApi<Block> + Send + Sync + 'static,
C::Api: ApiExt<Block> + BlockBuilderApi<Block>,
{
fn init_with_now(
&mut self,
parent_header: &<Block as BlockT>::Header,
now: Box<dyn Fn() -> time::Instant + Send + Sync>,
) -> Proposer<B, Block, C, A, PR> {
) -> Proposer<Block, C, A, PR> {
let parent_hash = parent_header.hash();
info!("🙌 Starting consensus session on top of parent {:?}", parent_hash);
let proposer = Proposer::<_, _, _, _, PR> {
let proposer = Proposer::<_, _, _, PR> {
spawn_handle: self.spawn_handle.clone(),
client: self.client.clone(),
parent_hash,
@@ -217,22 +210,16 @@ where
}
}
impl<A, B, Block, C, PR> sp_consensus::Environment<Block> for ProposerFactory<A, B, C, PR>
impl<A, Block, C, PR> sp_consensus::Environment<Block> for ProposerFactory<A, C, PR>
where
A: TransactionPool<Block = Block> + 'static,
B: backend::Backend<Block> + Send + Sync + 'static,
Block: BlockT,
C: BlockBuilderProvider<B, Block, C>
+ HeaderBackend<Block>
+ ProvideRuntimeApi<Block>
+ Send
+ Sync
+ 'static,
C: HeaderBackend<Block> + ProvideRuntimeApi<Block> + CallApiAt<Block> + Send + Sync + 'static,
C::Api: ApiExt<Block> + BlockBuilderApi<Block>,
PR: ProofRecording,
{
type CreateProposer = future::Ready<Result<Self::Proposer, Self::Error>>;
type Proposer = Proposer<B, Block, C, A, PR>;
type Proposer = Proposer<Block, C, A, PR>;
type Error = sp_blockchain::Error;
fn init(&mut self, parent_header: &<Block as BlockT>::Header) -> Self::CreateProposer {
@@ -241,7 +228,7 @@ where
}
/// The proposer logic.
pub struct Proposer<B, Block: BlockT, C, A: TransactionPool, PR> {
pub struct Proposer<Block: BlockT, C, A: TransactionPool, PR> {
spawn_handle: Box<dyn SpawnNamed>,
client: Arc<C>,
parent_hash: Block::Hash,
@@ -253,20 +240,14 @@ pub struct Proposer<B, Block: BlockT, C, A: TransactionPool, PR> {
include_proof_in_block_size_estimation: bool,
soft_deadline_percent: Percent,
telemetry: Option<TelemetryHandle>,
_phantom: PhantomData<(B, PR)>,
_phantom: PhantomData<PR>,
}
impl<A, B, Block, C, PR> sp_consensus::Proposer<Block> for Proposer<B, Block, C, A, PR>
impl<A, Block, C, PR> sp_consensus::Proposer<Block> for Proposer<Block, C, A, PR>
where
A: TransactionPool<Block = Block> + 'static,
B: backend::Backend<Block> + Send + Sync + 'static,
Block: BlockT,
C: BlockBuilderProvider<B, Block, C>
+ HeaderBackend<Block>
+ ProvideRuntimeApi<Block>
+ Send
+ Sync
+ 'static,
C: HeaderBackend<Block> + ProvideRuntimeApi<Block> + CallApiAt<Block> + Send + Sync + 'static,
C::Api: ApiExt<Block> + BlockBuilderApi<Block>,
PR: ProofRecording,
{
@@ -313,17 +294,11 @@ where
/// It allows us to increase block utilization.
const MAX_SKIPPED_TRANSACTIONS: usize = 8;
impl<A, B, Block, C, PR> Proposer<B, Block, C, A, PR>
impl<A, Block, C, PR> Proposer<Block, C, A, PR>
where
A: TransactionPool<Block = Block>,
B: backend::Backend<Block> + Send + Sync + 'static,
Block: BlockT,
C: BlockBuilderProvider<B, Block, C>
+ HeaderBackend<Block>
+ ProvideRuntimeApi<Block>
+ Send
+ Sync
+ 'static,
C: HeaderBackend<Block> + ProvideRuntimeApi<Block> + CallApiAt<Block> + Send + Sync + 'static,
C::Api: ApiExt<Block> + BlockBuilderApi<Block>,
PR: ProofRecording,
{
@@ -335,8 +310,12 @@ where
block_size_limit: Option<usize>,
) -> Result<Proposal<Block, PR::Proof>, sp_blockchain::Error> {
let block_timer = time::Instant::now();
let mut block_builder =
self.client.new_block_at(self.parent_hash, inherent_digests, PR::ENABLED)?;
let mut block_builder = BlockBuilderBuilder::new(&*self.client)
.on_parent_block(self.parent_hash)
.with_parent_block_number(self.parent_number)
.with_proof_recording(PR::ENABLED)
.with_inherent_digests(inherent_digests)
.build()?;
self.apply_inherents(&mut block_builder, inherent_data)?;
@@ -358,7 +337,7 @@ where
/// Apply all inherents to the block.
fn apply_inherents(
&self,
block_builder: &mut sc_block_builder::BlockBuilder<'_, Block, C, B>,
block_builder: &mut sc_block_builder::BlockBuilder<'_, Block, C>,
inherent_data: InherentData,
) -> Result<(), sp_blockchain::Error> {
let create_inherents_start = time::Instant::now();
@@ -402,7 +381,7 @@ where
/// Apply as many extrinsics as possible to the block.
async fn apply_extrinsics(
&self,
block_builder: &mut sc_block_builder::BlockBuilder<'_, Block, C, B>,
block_builder: &mut sc_block_builder::BlockBuilder<'_, Block, C>,
deadline: time::Instant,
block_size_limit: Option<usize>,
) -> Result<EndProposingReason, sp_blockchain::Error> {
@@ -976,8 +955,12 @@ mod tests {
// Exact block_limit, which includes:
// 99 (header_size) + 718 (proof@initialize_block) + 246 (one Transfer extrinsic)
let block_limit = {
let builder =
client.new_block_at(genesis_header.hash(), Default::default(), true).unwrap();
let builder = BlockBuilderBuilder::new(&*client)
.on_parent_block(genesis_header.hash())
.with_parent_block_number(0)
.enable_proof_recording()
.build()
.unwrap();
builder.estimate_block_size(true) + extrinsics[0].encoded_size()
};
let block = block_on(proposer.propose(
@@ -16,7 +16,6 @@ targets = ["x86_64-unknown-linux-gnu"]
codec = { package = "parity-scale-codec", version = "3.6.1", features = [
"derive",
] }
sc-client-api = { path = "../api" }
sp-api = { path = "../../primitives/api" }
sp-block-builder = { path = "../../primitives/block-builder" }
sp-blockchain = { path = "../../primitives/blockchain" }
+164 -115
View File
@@ -29,56 +29,147 @@
use codec::Encode;
use sp_api::{
ApiExt, ApiRef, Core, ProvideRuntimeApi, StorageChanges, StorageProof, TransactionOutcome,
ApiExt, ApiRef, CallApiAt, Core, ProvideRuntimeApi, StorageChanges, StorageProof,
TransactionOutcome,
};
use sp_blockchain::{ApplyExtrinsicFailed, Error};
use sp_blockchain::{ApplyExtrinsicFailed, Error, HeaderBackend};
use sp_core::traits::CallContext;
use sp_runtime::{
legacy,
traits::{Block as BlockT, Hash, HashingFor, Header as HeaderT, NumberFor, One},
Digest,
};
use std::marker::PhantomData;
use sc_client_api::backend;
pub use sp_block_builder::BlockBuilder as BlockBuilderApi;
/// Used as parameter to [`BlockBuilderProvider`] to express if proof recording should be enabled.
/// A builder for creating an instance of [`BlockBuilder`].
pub struct BlockBuilderBuilder<'a, B, C> {
call_api_at: &'a C,
_phantom: PhantomData<B>,
}
impl<'a, B, C> BlockBuilderBuilder<'a, B, C>
where
B: BlockT,
{
/// Create a new instance of the builder.
///
/// `call_api_at`: Something that implements [`CallApiAt`].
pub fn new(call_api_at: &'a C) -> Self {
Self { call_api_at, _phantom: PhantomData }
}
/// Specify the parent block to build on top of.
pub fn on_parent_block(self, parent_block: B::Hash) -> BlockBuilderBuilderStage1<'a, B, C> {
BlockBuilderBuilderStage1 { call_api_at: self.call_api_at, parent_block }
}
}
/// The second stage of the [`BlockBuilderBuilder`].
///
/// When `RecordProof::Yes` is given, all accessed trie nodes should be saved. These recorded
/// trie nodes can be used by a third party to proof this proposal without having access to the
/// full storage.
#[derive(Copy, Clone, PartialEq)]
pub enum RecordProof {
/// `Yes`, record a proof.
Yes,
/// `No`, don't record any proof.
No,
/// This type can not be instantiated directly. To get an instance of it
/// [`BlockBuilderBuilder::new`] needs to be used.
pub struct BlockBuilderBuilderStage1<'a, B: BlockT, C> {
call_api_at: &'a C,
parent_block: B::Hash,
}
impl RecordProof {
/// Returns if `Self` == `Yes`.
pub fn yes(&self) -> bool {
matches!(self, Self::Yes)
impl<'a, B, C> BlockBuilderBuilderStage1<'a, B, C>
where
B: BlockT,
{
/// Fetch the parent block number from the given `header_backend`.
///
/// The parent block number is used to initialize the block number of the new block.
///
/// Returns an error if the parent block specified in
/// [`on_parent_block`](BlockBuilderBuilder::on_parent_block) does not exist.
pub fn fetch_parent_block_number<H: HeaderBackend<B>>(
self,
header_backend: &H,
) -> Result<BlockBuilderBuilderStage2<'a, B, C>, Error> {
let parent_number = header_backend.number(self.parent_block)?.ok_or_else(|| {
Error::Backend(format!(
"Could not fetch block number for block: {:?}",
self.parent_block
))
})?;
Ok(BlockBuilderBuilderStage2 {
call_api_at: self.call_api_at,
enable_proof_recording: false,
inherent_digests: Default::default(),
parent_block: self.parent_block,
parent_number,
})
}
}
/// Will return [`RecordProof::No`] as default value.
impl Default for RecordProof {
fn default() -> Self {
Self::No
}
}
impl From<bool> for RecordProof {
fn from(val: bool) -> Self {
if val {
Self::Yes
} else {
Self::No
/// Provide the block number for the parent block directly.
///
/// The parent block is specified in [`on_parent_block`](BlockBuilderBuilder::on_parent_block).
/// The parent block number is used to initialize the block number of the new block.
pub fn with_parent_block_number(
self,
parent_number: NumberFor<B>,
) -> BlockBuilderBuilderStage2<'a, B, C> {
BlockBuilderBuilderStage2 {
call_api_at: self.call_api_at,
enable_proof_recording: false,
inherent_digests: Default::default(),
parent_block: self.parent_block,
parent_number,
}
}
}
/// The second stage of the [`BlockBuilderBuilder`].
///
/// This type can not be instantiated directly. To get an instance of it
/// [`BlockBuilderBuilder::new`] needs to be used.
pub struct BlockBuilderBuilderStage2<'a, B: BlockT, C> {
call_api_at: &'a C,
enable_proof_recording: bool,
inherent_digests: Digest,
parent_block: B::Hash,
parent_number: NumberFor<B>,
}
impl<'a, B: BlockT, C> BlockBuilderBuilderStage2<'a, B, C> {
/// Enable proof recording for the block builder.
pub fn enable_proof_recording(mut self) -> Self {
self.enable_proof_recording = true;
self
}
/// Enable/disable proof recording for the block builder.
pub fn with_proof_recording(mut self, enable: bool) -> Self {
self.enable_proof_recording = enable;
self
}
/// Build the block with the given inherent digests.
pub fn with_inherent_digests(mut self, inherent_digests: Digest) -> Self {
self.inherent_digests = inherent_digests;
self
}
/// Create the instance of the [`BlockBuilder`].
pub fn build(self) -> Result<BlockBuilder<'a, B, C>, Error>
where
C: CallApiAt<B> + ProvideRuntimeApi<B>,
C::Api: BlockBuilderApi<B>,
{
BlockBuilder::new(
self.call_api_at,
self.parent_block,
self.parent_number,
self.enable_proof_recording,
self.inherent_digests,
)
}
}
/// A block that was build by [`BlockBuilder`] plus some additional data.
///
/// This additional data includes the `storage_changes`, these changes can be applied to the
@@ -101,63 +192,34 @@ impl<Block: BlockT> BuiltBlock<Block> {
}
}
/// Block builder provider
pub trait BlockBuilderProvider<B, Block, RA>
where
Block: BlockT,
B: backend::Backend<Block>,
Self: Sized,
RA: ProvideRuntimeApi<Block>,
{
/// Create a new block, built on top of `parent`.
///
/// When proof recording is enabled, all accessed trie nodes are saved.
/// These recorded trie nodes can be used by a third party to proof the
/// output of this block builder without having access to the full storage.
fn new_block_at<R: Into<RecordProof>>(
&self,
parent: Block::Hash,
inherent_digests: Digest,
record_proof: R,
) -> sp_blockchain::Result<BlockBuilder<Block, RA, B>>;
/// Create a new block, built on the head of the chain.
fn new_block(
&self,
inherent_digests: Digest,
) -> sp_blockchain::Result<BlockBuilder<Block, RA, B>>;
}
/// Utility for building new (valid) blocks from a stream of extrinsics.
pub struct BlockBuilder<'a, Block: BlockT, A: ProvideRuntimeApi<Block>, B> {
pub struct BlockBuilder<'a, Block: BlockT, C: ProvideRuntimeApi<Block> + 'a> {
extrinsics: Vec<Block::Extrinsic>,
api: ApiRef<'a, A::Api>,
api: ApiRef<'a, C::Api>,
call_api_at: &'a C,
version: u32,
parent_hash: Block::Hash,
backend: &'a B,
/// The estimated size of the block header.
estimated_header_size: usize,
}
impl<'a, Block, A, B> BlockBuilder<'a, Block, A, B>
impl<'a, Block, C> BlockBuilder<'a, Block, C>
where
Block: BlockT,
A: ProvideRuntimeApi<Block> + 'a,
A::Api: BlockBuilderApi<Block> + ApiExt<Block>,
B: backend::Backend<Block>,
C: CallApiAt<Block> + ProvideRuntimeApi<Block> + 'a,
C::Api: BlockBuilderApi<Block>,
{
/// Create a new instance of builder based on the given `parent_hash` and `parent_number`.
///
/// While proof recording is enabled, all accessed trie nodes are saved.
/// These recorded trie nodes can be used by a third party to prove the
/// output of this block builder without having access to the full storage.
pub fn new(
api: &'a A,
fn new(
call_api_at: &'a C,
parent_hash: Block::Hash,
parent_number: NumberFor<Block>,
record_proof: RecordProof,
record_proof: bool,
inherent_digests: Digest,
backend: &'a B,
) -> Result<Self, Error> {
let header = <<Block as BlockT>::Header as HeaderT>::new(
parent_number + One::one(),
@@ -169,9 +231,9 @@ where
let estimated_header_size = header.encoded_size();
let mut api = api.runtime_api();
let mut api = call_api_at.runtime_api();
if record_proof.yes() {
if record_proof {
api.record_proof();
}
@@ -188,8 +250,8 @@ where
extrinsics: Vec::new(),
api,
version,
backend,
estimated_header_size,
call_api_at,
})
}
@@ -241,7 +303,7 @@ where
let proof = self.api.extract_proof();
let state = self.backend.state_at(self.parent_hash)?;
let state = self.call_api_at.state_at(self.parent_hash)?;
let storage_changes = self
.api
@@ -300,22 +362,18 @@ mod tests {
#[test]
fn block_building_storage_proof_does_not_include_runtime_by_default() {
let builder = substrate_test_runtime_client::TestClientBuilder::new();
let backend = builder.backend();
let client = builder.build();
let genesis_hash = client.info().best_hash;
let block = BlockBuilder::new(
&client,
genesis_hash,
client.info().best_number,
RecordProof::Yes,
Default::default(),
&*backend,
)
.unwrap()
.build()
.unwrap();
let block = BlockBuilderBuilder::new(&client)
.on_parent_block(genesis_hash)
.with_parent_block_number(0)
.enable_proof_recording()
.build()
.unwrap()
.build()
.unwrap();
let proof = block.proof.expect("Proof is build on request");
let genesis_state_root = client.header(genesis_hash).unwrap().unwrap().state_root;
@@ -333,18 +391,15 @@ mod tests {
#[test]
fn failing_extrinsic_rolls_back_changes_in_storage_proof() {
let builder = substrate_test_runtime_client::TestClientBuilder::new();
let backend = builder.backend();
let client = builder.build();
let genesis_hash = client.info().best_hash;
let mut block_builder = BlockBuilder::new(
&client,
client.info().best_hash,
client.info().best_number,
RecordProof::Yes,
Default::default(),
&*backend,
)
.unwrap();
let mut block_builder = BlockBuilderBuilder::new(&client)
.on_parent_block(genesis_hash)
.with_parent_block_number(0)
.enable_proof_recording()
.build()
.unwrap();
block_builder.push(ExtrinsicBuilder::new_read_and_panic(8).build()).unwrap_err();
@@ -352,15 +407,12 @@ mod tests {
let proof_with_panic = block.proof.expect("Proof is build on request").encoded_size();
let mut block_builder = BlockBuilder::new(
&client,
client.info().best_hash,
client.info().best_number,
RecordProof::Yes,
Default::default(),
&*backend,
)
.unwrap();
let mut block_builder = BlockBuilderBuilder::new(&client)
.on_parent_block(genesis_hash)
.with_parent_block_number(0)
.enable_proof_recording()
.build()
.unwrap();
block_builder.push(ExtrinsicBuilder::new_read(8).build()).unwrap();
@@ -368,17 +420,14 @@ mod tests {
let proof_without_panic = block.proof.expect("Proof is build on request").encoded_size();
let block = BlockBuilder::new(
&client,
client.info().best_hash,
client.info().best_number,
RecordProof::Yes,
Default::default(),
&*backend,
)
.unwrap()
.build()
.unwrap();
let block = BlockBuilderBuilder::new(&client)
.on_parent_block(genesis_hash)
.with_parent_block_number(0)
.enable_proof_recording()
.build()
.unwrap()
.build()
.unwrap();
let proof_empty_block = block.proof.expect("Proof is build on request").encoded_size();
+9 -2
View File
@@ -548,7 +548,7 @@ where
mod tests {
use super::*;
use parking_lot::Mutex;
use sc_block_builder::BlockBuilderProvider;
use sc_block_builder::BlockBuilderBuilder;
use sc_client_api::BlockchainEvents;
use sc_consensus::BoxJustificationImport;
use sc_consensus_slots::{BackoffAuthoringOnFinalizedHeadLagging, SimpleSlotWorker};
@@ -604,7 +604,14 @@ mod tests {
_: Duration,
_: Option<usize>,
) -> Self::Proposal {
let r = self.1.new_block(digests).unwrap().build().map_err(|e| e.into());
let r = BlockBuilderBuilder::new(&*self.1)
.on_parent_block(self.1.chain_info().best_hash)
.fetch_parent_block_number(&*self.1)
.unwrap()
.with_inherent_digests(digests)
.build()
.unwrap()
.build();
future::ready(r.map(|b| Proposal {
block: b.block,
+9 -4
View File
@@ -20,7 +20,7 @@
use super::*;
use authorship::claim_slot;
use sc_block_builder::{BlockBuilder, BlockBuilderProvider};
use sc_block_builder::{BlockBuilder, BlockBuilderBuilder};
use sc_client_api::{BlockchainEvents, Finalizer};
use sc_consensus::{BoxBlockImport, BoxJustificationImport};
use sc_consensus_epochs::{EpochIdentifier, EpochIdentifierPosition};
@@ -98,8 +98,13 @@ impl DummyProposer {
&mut self,
pre_digests: Digest,
) -> future::Ready<Result<Proposal<TestBlock, ()>, Error>> {
let block_builder =
self.factory.client.new_block_at(self.parent_hash, pre_digests, false).unwrap();
let block_builder = BlockBuilderBuilder::new(&*self.factory.client)
.on_parent_block(self.parent_hash)
.fetch_parent_block_number(&*self.factory.client)
.unwrap()
.with_inherent_digests(pre_digests)
.build()
.unwrap();
let mut block = match block_builder.build().map_err(|e| e.into()) {
Ok(b) => b.block,
@@ -297,7 +302,7 @@ impl TestNetFactory for BabeTestNet {
async fn rejects_empty_block() {
sp_tracing::try_init_simple();
let mut net = BabeTestNet::new(3);
let block_builder = |builder: BlockBuilder<_, _, _>| builder.build().unwrap().block;
let block_builder = |builder: BlockBuilder<_, _>| builder.build().unwrap().block;
net.mut_peers(|peer| {
peer[0].generate_blocks(1, BlockOrigin::NetworkInitialSync, block_builder);
})
+20 -6
View File
@@ -35,6 +35,7 @@ use crate::{
};
use futures::{future, stream::FuturesUnordered, Future, FutureExt, StreamExt};
use parking_lot::Mutex;
use sc_block_builder::BlockBuilderBuilder;
use sc_client_api::{Backend as BackendT, BlockchainEvents, FinalityNotifications, HeaderBackend};
use sc_consensus::{
BlockImport, BlockImportParams, BoxJustificationImport, ForkChoiceStrategy, ImportResult,
@@ -741,7 +742,6 @@ async fn correct_beefy_payload() {
#[tokio::test]
async fn beefy_importing_justifications() {
use futures::{future::poll_fn, task::Poll};
use sc_block_builder::BlockBuilderProvider;
use sc_client_api::BlockBackend;
sp_tracing::try_init_simple();
@@ -774,8 +774,10 @@ async fn beefy_importing_justifications() {
.and_then(|j| j.get(BEEFY_ENGINE_ID).cloned())
};
let builder = full_client
.new_block_at(full_client.chain_info().genesis_hash, Default::default(), false)
let builder = BlockBuilderBuilder::new(&*full_client)
.on_parent_block(full_client.genesis_hash())
.with_parent_block_number(0)
.build()
.unwrap();
let block = builder.build().unwrap().block;
let hashof1 = block.header.hash();
@@ -792,7 +794,11 @@ async fn beefy_importing_justifications() {
// Import block 2 with "valid" justification (beefy pallet genesis block not yet reached).
let block_num = 2;
let builder = full_client.new_block_at(hashof1, Default::default(), false).unwrap();
let builder = BlockBuilderBuilder::new(&*full_client)
.on_parent_block(hashof1)
.with_parent_block_number(1)
.build()
.unwrap();
let block = builder.build().unwrap().block;
let hashof2 = block.header.hash();
@@ -824,7 +830,11 @@ async fn beefy_importing_justifications() {
// Import block 3 with valid justification.
let block_num = 3;
let builder = full_client.new_block_at(hashof2, Default::default(), false).unwrap();
let builder = BlockBuilderBuilder::new(&*full_client)
.on_parent_block(hashof2)
.with_parent_block_number(2)
.build()
.unwrap();
let block = builder.build().unwrap().block;
let hashof3 = block.header.hash();
let proof = crate::justification::tests::new_finality_proof(block_num, &good_set, keys);
@@ -858,7 +868,11 @@ async fn beefy_importing_justifications() {
// Import block 4 with invalid justification (incorrect validator set).
let block_num = 4;
let builder = full_client.new_block_at(hashof3, Default::default(), false).unwrap();
let builder = BlockBuilderBuilder::new(&*full_client)
.on_parent_block(hashof3)
.with_parent_block_number(3)
.build()
.unwrap();
let block = builder.build().unwrap().block;
let hashof4 = block.header.hash();
let keys = &[BeefyKeyring::Alice];
@@ -142,7 +142,7 @@ mod tests {
RpcModule,
};
use parity_scale_codec::{Decode, Encode};
use sc_block_builder::{BlockBuilder, RecordProof};
use sc_block_builder::BlockBuilderBuilder;
use sc_consensus_grandpa::{
report, AuthorityId, FinalityProof, GrandpaJustification, GrandpaJustificationSender,
};
@@ -335,21 +335,16 @@ mod tests {
let peers = &[Ed25519Keyring::Alice];
let builder = TestClientBuilder::new();
let backend = builder.backend();
let client = builder.build();
let client = Arc::new(client);
let built_block = BlockBuilder::new(
&*client,
client.info().best_hash,
client.info().best_number,
RecordProof::No,
Default::default(),
&*backend,
)
.unwrap()
.build()
.unwrap();
let built_block = BlockBuilderBuilder::new(&*client)
.on_parent_block(client.info().best_hash)
.with_parent_block_number(client.info().best_number)
.build()
.unwrap()
.build()
.unwrap();
let block = built_block.block;
let block_hash = block.hash();
@@ -261,7 +261,7 @@ mod tests {
use super::*;
use crate::{authorities::AuthoritySetChanges, BlockNumberOps, ClientError, SetId};
use futures::executor::block_on;
use sc_block_builder::BlockBuilderProvider;
use sc_block_builder::BlockBuilderBuilder;
use sc_client_api::{apply_aux, LockImportRun};
use sp_consensus::BlockOrigin;
use sp_consensus_grandpa::GRANDPA_ENGINE_ID as ID;
@@ -323,7 +323,14 @@ mod tests {
let mut blocks = Vec::new();
for _ in 0..number_of_blocks {
let block = client.new_block(Default::default()).unwrap().build().unwrap().block;
let block = BlockBuilderBuilder::new(&*client)
.on_parent_block(client.chain_info().best_hash)
.with_parent_block_number(client.chain_info().best_number)
.build()
.unwrap()
.build()
.unwrap()
.block;
block_on(client.import(BlockOrigin::Own, block.clone())).unwrap();
blocks.push(block);
}
@@ -54,7 +54,7 @@ use tokio::runtime::Handle;
use authorities::AuthoritySet;
use communication::grandpa_protocol_name;
use sc_block_builder::{BlockBuilder, BlockBuilderProvider};
use sc_block_builder::{BlockBuilder, BlockBuilderBuilder};
use sc_consensus::LongestChain;
use sp_application_crypto::key_types::GRANDPA;
@@ -897,8 +897,11 @@ async fn allows_reimporting_change_blocks() {
let (mut block_import, ..) = net.make_block_import(client.clone());
let full_client = client.as_client();
let mut builder = full_client
.new_block_at(full_client.chain_info().genesis_hash, Default::default(), false)
let mut builder = BlockBuilderBuilder::new(&*full_client)
.on_parent_block(full_client.chain_info().best_hash)
.fetch_parent_block_number(&*full_client)
.unwrap()
.build()
.unwrap();
add_scheduled_change(
@@ -942,8 +945,11 @@ async fn test_bad_justification() {
let (mut block_import, ..) = net.make_block_import(client.clone());
let full_client = client.as_client();
let mut builder = full_client
.new_block_at(full_client.chain_info().genesis_hash, Default::default(), false)
let mut builder = BlockBuilderBuilder::new(&*full_client)
.on_parent_block(full_client.chain_info().best_hash)
.fetch_parent_block_number(&*full_client)
.unwrap()
.build()
.unwrap();
add_scheduled_change(
@@ -1913,7 +1919,12 @@ async fn imports_justification_for_regular_blocks_on_import() {
// create a new block (without importing it)
let generate_block = |parent| {
let builder = full_client.new_block_at(parent, Default::default(), false).unwrap();
let builder = BlockBuilderBuilder::new(&*full_client)
.on_parent_block(parent)
.fetch_parent_block_number(&*full_client)
.unwrap()
.build()
.unwrap();
builder.build().unwrap().block
};
@@ -2042,8 +2053,7 @@ async fn revert_prunes_authority_changes() {
let peers = &[Ed25519Keyring::Alice, Ed25519Keyring::Bob, Ed25519Keyring::Charlie];
type TestBlockBuilder<'a> =
BlockBuilder<'a, Block, PeersFullClient, substrate_test_runtime_client::Backend>;
type TestBlockBuilder<'a> = BlockBuilder<'a, Block, PeersFullClient>;
let edit_block = |mut builder: TestBlockBuilder| {
add_scheduled_change(
&mut builder,
@@ -330,7 +330,7 @@ where
#[cfg(test)]
mod tests {
use super::*;
use sc_block_builder::BlockBuilderProvider;
use sc_block_builder::BlockBuilderBuilder;
use sp_consensus::BlockOrigin;
use sp_runtime::traits::Header as _;
@@ -371,7 +371,14 @@ mod tests {
let mut hashes = Vec::with_capacity(200);
for _ in 0..200 {
let block = client.new_block(Default::default()).unwrap().build().unwrap().block;
let block = BlockBuilderBuilder::new(&*client)
.on_parent_block(client.chain_info().best_hash)
.with_parent_block_number(client.chain_info().best_number)
.build()
.unwrap()
.build()
.unwrap()
.block;
hashes.push(block.hash());
futures::executor::block_on(client.import(BlockOrigin::Own, block)).unwrap();
@@ -414,7 +421,14 @@ mod tests {
let n = 5;
let mut hashes = Vec::with_capacity(n);
for _ in 0..n {
let block = client.new_block(Default::default()).unwrap().build().unwrap().block;
let block = BlockBuilderBuilder::new(&*client)
.on_parent_block(client.chain_info().best_hash)
.with_parent_block_number(client.chain_info().best_number)
.build()
.unwrap()
.build()
.unwrap()
.block;
hashes.push(block.hash());
futures::executor::block_on(client.import(BlockOrigin::Own, block)).unwrap();
@@ -322,7 +322,7 @@ mod tests {
use crate::{AuthoritySetChanges, GrandpaJustification};
use parity_scale_codec::Encode;
use rand::prelude::*;
use sc_block_builder::BlockBuilderProvider;
use sc_block_builder::BlockBuilderBuilder;
use sp_blockchain::HeaderBackend;
use sp_consensus::BlockOrigin;
use sp_consensus_grandpa::GRANDPA_ENGINE_ID;
@@ -348,7 +348,11 @@ mod tests {
let mut authority_set_changes = Vec::new();
for n in 1..=100 {
let mut builder = client.new_block(Default::default()).unwrap();
let mut builder = BlockBuilderBuilder::new(&*client)
.on_parent_block(client.chain_info().best_hash)
.with_parent_block_number(client.chain_info().best_number)
.build()
.unwrap();
let mut new_authorities = None;
// we will trigger an authority set change every 10 blocks
@@ -18,7 +18,7 @@
use crate::MmrGadget;
use parking_lot::Mutex;
use sc_block_builder::BlockBuilderProvider;
use sc_block_builder::BlockBuilderBuilder;
use sc_client_api::{
Backend as BackendT, BlockchainEvents, FinalityNotifications, ImportNotifications,
StorageEventStream, StorageKey,
@@ -125,7 +125,12 @@ impl MockClient {
let mut client = self.client.lock();
let hash = client.expect_block_hash_from_id(&at).unwrap();
let mut block_builder = client.new_block_at(hash, Default::default(), false).unwrap();
let mut block_builder = BlockBuilderBuilder::new(&*client)
.on_parent_block(hash)
.fetch_parent_block_number(&*client)
.unwrap()
.build()
.unwrap();
// Make sure the block has a different hash than its siblings
block_builder
.push_storage_change(b"name".to_vec(), Some(name.to_vec()))
+6 -2
View File
@@ -290,7 +290,7 @@ pub enum BitswapError {
mod tests {
use super::*;
use futures::channel::oneshot;
use sc_block_builder::BlockBuilderProvider;
use sc_block_builder::BlockBuilderBuilder;
use schema::bitswap::{
message::{wantlist::Entry, Wantlist},
Message as BitswapMessage,
@@ -468,7 +468,11 @@ mod tests {
#[tokio::test]
async fn transaction_found() {
let mut client = TestClientBuilder::with_tx_storage(u32::MAX).build();
let mut block_builder = client.new_block(Default::default()).unwrap();
let mut block_builder = BlockBuilderBuilder::new(&client)
.on_parent_block(client.chain_info().genesis_hash)
.with_parent_block_number(0)
.build()
.unwrap();
// encoded extrinsic: [161, .. , 2, 6, 16, 19, 55, 19, 56]
let ext = ExtrinsicBuilder::new_indexed_call(vec![0x13, 0x37, 0x13, 0x38]).build();
@@ -21,7 +21,7 @@
use super::*;
use crate::service::network::NetworkServiceProvider;
use futures::executor::block_on;
use sc_block_builder::BlockBuilderProvider;
use sc_block_builder::BlockBuilderBuilder;
use sc_network_common::sync::message::{BlockAnnounce, BlockData, BlockState, FromBlock};
use sp_blockchain::HeaderBackend;
use substrate_test_runtime_client::{
@@ -52,7 +52,14 @@ fn processes_empty_response_on_justification_request_for_unknown_block() {
.unwrap();
let (a1_hash, a1_number) = {
let a1 = client.new_block(Default::default()).unwrap().build().unwrap().block;
let a1 = BlockBuilderBuilder::new(&*client)
.on_parent_block(client.chain_info().best_hash)
.with_parent_block_number(client.chain_info().best_number)
.build()
.unwrap()
.build()
.unwrap()
.block;
(a1.hash(), *a1.header.number())
};
@@ -115,7 +122,14 @@ fn restart_doesnt_affect_peers_downloading_finality_data() {
let mut new_blocks = |n| {
for _ in 0..n {
let block = client.new_block(Default::default()).unwrap().build().unwrap().block;
let block = BlockBuilderBuilder::new(&*client)
.on_parent_block(client.chain_info().best_hash)
.with_parent_block_number(client.chain_info().best_number)
.build()
.unwrap()
.build()
.unwrap()
.block;
block_on(client.import(BlockOrigin::Own, block.clone())).unwrap();
}
@@ -233,7 +247,12 @@ fn get_block_request(
fn build_block(client: &mut Arc<TestClient>, at: Option<Hash>, fork: bool) -> Block {
let at = at.unwrap_or_else(|| client.info().best_hash);
let mut block_builder = client.new_block_at(at, Default::default(), false).unwrap();
let mut block_builder = BlockBuilderBuilder::new(&**client)
.on_parent_block(at)
.fetch_parent_block_number(&**client)
.unwrap()
.build()
.unwrap();
if fork {
block_builder.push_storage_change(vec![1, 2, 3], Some(vec![4, 5, 6])).unwrap();
@@ -774,7 +793,14 @@ fn sync_restart_removes_block_but_not_justification_requests() {
let mut new_blocks = |n| {
for _ in 0..n {
let block = client.new_block(Default::default()).unwrap().build().unwrap().block;
let block = BlockBuilderBuilder::new(&*client)
.on_parent_block(client.chain_info().best_hash)
.with_parent_block_number(client.chain_info().best_number)
.build()
.unwrap()
.build()
.unwrap()
.block;
block_on(client.import(BlockOrigin::Own, block.clone())).unwrap();
}
@@ -20,7 +20,6 @@
use super::*;
use futures::executor::block_on;
use sc_block_builder::BlockBuilderProvider;
use sc_consensus::{
import_single_block, BasicQueue, BlockImportError, BlockImportStatus, ImportedAux,
IncomingBlock,
@@ -34,7 +33,14 @@ use substrate_test_runtime_client::{
fn prepare_good_block() -> (TestClient, Hash, u64, PeerId, IncomingBlock<Block>) {
let mut client = substrate_test_runtime_client::new();
let block = client.new_block(Default::default()).unwrap().build().unwrap().block;
let block = BlockBuilderBuilder::new(&client)
.on_parent_block(client.chain_info().best_hash)
.with_parent_block_number(client.chain_info().best_number)
.build()
.unwrap()
.build()
.unwrap()
.block;
block_on(client.import(BlockOrigin::File, block)).unwrap();
let (hash, number) = (client.block_hash(1).unwrap().unwrap(), 1);
+10 -11
View File
@@ -38,7 +38,7 @@ use futures::{channel::oneshot, future::BoxFuture, pin_mut, prelude::*};
use libp2p::{build_multiaddr, PeerId};
use log::trace;
use parking_lot::Mutex;
use sc_block_builder::{BlockBuilder, BlockBuilderProvider};
use sc_block_builder::{BlockBuilder, BlockBuilderBuilder};
use sc_client_api::{
backend::{AuxStore, Backend, Finalizer},
BlockBackend, BlockImportNotification, BlockchainEvents, FinalityNotification,
@@ -305,9 +305,7 @@ where
edit_block: F,
) -> Vec<H256>
where
F: FnMut(
BlockBuilder<Block, PeersFullClient, substrate_test_runtime_client::Backend>,
) -> Block,
F: FnMut(BlockBuilder<Block, PeersFullClient>) -> Block,
{
let best_hash = self.client.info().best_hash;
self.generate_blocks_at(
@@ -331,9 +329,7 @@ where
fork_choice: ForkChoiceStrategy,
) -> Vec<H256>
where
F: FnMut(
BlockBuilder<Block, PeersFullClient, substrate_test_runtime_client::Backend>,
) -> Block,
F: FnMut(BlockBuilder<Block, PeersFullClient>) -> Block,
{
let best_hash = self.client.info().best_hash;
self.generate_blocks_at(
@@ -362,15 +358,18 @@ where
fork_choice: ForkChoiceStrategy,
) -> Vec<H256>
where
F: FnMut(
BlockBuilder<Block, PeersFullClient, substrate_test_runtime_client::Backend>,
) -> Block,
F: FnMut(BlockBuilder<Block, PeersFullClient>) -> Block,
{
let mut hashes = Vec::with_capacity(count);
let full_client = self.client.as_client();
let mut at = full_client.block_hash_from_id(&at).unwrap().unwrap();
for _ in 0..count {
let builder = full_client.new_block_at(at, Default::default(), false).unwrap();
let builder = BlockBuilderBuilder::new(&*full_client)
.on_parent_block(at)
.fetch_parent_block_number(&*full_client)
.unwrap()
.build()
.unwrap();
let block = edit_block(builder);
let hash = block.header.hash();
trace!(
+13 -4
View File
@@ -328,12 +328,13 @@ mod tests {
use super::*;
use futures::executor::block_on;
use libp2p::{Multiaddr, PeerId};
use sc_block_builder::BlockBuilderProvider as _;
use sc_block_builder::BlockBuilderBuilder;
use sc_client_api::Backend as _;
use sc_network::{config::MultiaddrWithPeerId, types::ProtocolName, ReputationChange};
use sc_transaction_pool::BasicPool;
use sc_transaction_pool_api::{InPoolTransaction, TransactionPool};
use sp_consensus::BlockOrigin;
use sp_runtime::traits::Block as BlockT;
use std::{collections::HashSet, sync::Arc};
use substrate_test_runtime_client::{
runtime::{
@@ -470,16 +471,24 @@ mod tests {
let key = &b"hello"[..];
let value = &b"world"[..];
let mut block_builder = client.new_block(Default::default()).unwrap();
let mut block_builder = BlockBuilderBuilder::new(&*client)
.on_parent_block(client.chain_info().genesis_hash)
.with_parent_block_number(0)
.build()
.unwrap();
let ext = ExtrinsicBuilder::new_offchain_index_set(key.to_vec(), value.to_vec()).build();
block_builder.push(ext).unwrap();
let block = block_builder.build().unwrap().block;
block_on(client.import(BlockOrigin::Own, block)).unwrap();
block_on(client.import(BlockOrigin::Own, block.clone())).unwrap();
assert_eq!(value, &offchain_db.get(sp_offchain::STORAGE_PREFIX, &key).unwrap());
let mut block_builder = client.new_block(Default::default()).unwrap();
let mut block_builder = BlockBuilderBuilder::new(&*client)
.on_parent_block(block.hash())
.with_parent_block_number(1)
.build()
.unwrap();
let ext = ExtrinsicBuilder::new_offchain_index_clear(key.to_vec()).nonce(1).build();
block_builder.push(ext).unwrap();
@@ -27,10 +27,13 @@ use jsonrpsee::{
types::{error::CallError, EmptyServerParams as EmptyParams},
RpcModule,
};
use sc_block_builder::BlockBuilderProvider;
use sc_block_builder::BlockBuilderBuilder;
use sp_blockchain::HeaderBackend;
use sp_consensus::BlockOrigin;
use sp_runtime::SaturatedConversion;
use sp_runtime::{
traits::{Block as BlockT, Header as HeaderT},
SaturatedConversion,
};
use std::sync::Arc;
use substrate_test_runtime::Transfer;
use substrate_test_runtime_client::{
@@ -72,7 +75,12 @@ async fn archive_body() {
assert!(res.is_none());
// Import a new block with an extrinsic.
let mut builder = client.new_block(Default::default()).unwrap();
let mut builder = BlockBuilderBuilder::new(&*client)
.on_parent_block(client.chain_info().genesis_hash)
.with_parent_block_number(0)
.build()
.unwrap();
builder
.push_transfer(runtime::Transfer {
from: AccountKeyring::Alice.into(),
@@ -101,7 +109,12 @@ async fn archive_header() {
assert!(res.is_none());
// Import a new block with an extrinsic.
let mut builder = client.new_block(Default::default()).unwrap();
let mut builder = BlockBuilderBuilder::new(&*client)
.on_parent_block(client.chain_info().genesis_hash)
.with_parent_block_number(0)
.build()
.unwrap();
builder
.push_transfer(runtime::Transfer {
from: AccountKeyring::Alice.into(),
@@ -147,24 +160,57 @@ async fn archive_hash_by_height() {
// ^^^ h = N
// ^^^ h = N + 1
// ^^^ h = N + 2
let finalized = client.new_block(Default::default()).unwrap().build().unwrap().block;
let finalized = BlockBuilderBuilder::new(&*client)
.on_parent_block(client.chain_info().genesis_hash)
.with_parent_block_number(0)
.build()
.unwrap()
.build()
.unwrap()
.block;
let finalized_hash = finalized.header.hash();
client.import(BlockOrigin::Own, finalized.clone()).await.unwrap();
client.finalize_block(finalized_hash, None).unwrap();
let block_1 = client.new_block(Default::default()).unwrap().build().unwrap().block;
let block_1 = BlockBuilderBuilder::new(&*client)
.on_parent_block(finalized.hash())
.with_parent_block_number(*finalized.header().number())
.build()
.unwrap()
.build()
.unwrap()
.block;
let block_1_hash = block_1.header.hash();
client.import(BlockOrigin::Own, block_1.clone()).await.unwrap();
let block_2 = client.new_block(Default::default()).unwrap().build().unwrap().block;
let block_2 = BlockBuilderBuilder::new(&*client)
.on_parent_block(block_1.hash())
.with_parent_block_number(*block_1.header().number())
.build()
.unwrap()
.build()
.unwrap()
.block;
let block_2_hash = block_2.header.hash();
client.import(BlockOrigin::Own, block_2.clone()).await.unwrap();
let block_3 = client.new_block(Default::default()).unwrap().build().unwrap().block;
let block_3 = BlockBuilderBuilder::new(&*client)
.on_parent_block(block_2.hash())
.with_parent_block_number(*block_2.header().number())
.build()
.unwrap()
.build()
.unwrap()
.block;
let block_3_hash = block_3.header.hash();
client.import(BlockOrigin::Own, block_3.clone()).await.unwrap();
// Import block 4 fork.
let mut block_builder = client.new_block_at(block_1_hash, Default::default(), false).unwrap();
let mut block_builder = BlockBuilderBuilder::new(&*client)
.on_parent_block(block_1_hash)
.with_parent_block_number(*block_1.header().number())
.build()
.unwrap();
// This push is required as otherwise block 3 has the same hash as block 1 and won't get
// imported
block_builder
@@ -238,7 +284,14 @@ async fn archive_call() {
.unwrap();
assert_matches!(result, MethodResult::Err(_));
let block_1 = client.new_block(Default::default()).unwrap().build().unwrap().block;
let block_1 = BlockBuilderBuilder::new(&*client)
.on_parent_block(client.chain_info().genesis_hash)
.with_parent_block_number(0)
.build()
.unwrap()
.build()
.unwrap()
.block;
let block_1_hash = block_1.header.hash();
client.import(BlockOrigin::Own, block_1.clone()).await.unwrap();
@@ -806,7 +806,7 @@ impl<Block: BlockT, BE: Backend<Block>> SubscriptionsInner<Block, BE> {
#[cfg(test)]
mod tests {
use super::*;
use sc_block_builder::BlockBuilderProvider;
use sc_block_builder::BlockBuilderBuilder;
use sc_service::client::new_in_mem;
use sp_consensus::BlockOrigin;
use sp_core::{testing::TaskExecutor, H256};
@@ -1004,8 +1004,15 @@ mod tests {
fn subscription_check_block() {
let (backend, mut client) = init_backend();
let block = client.new_block(Default::default()).unwrap().build().unwrap().block;
let hash = block.header.hash();
let block = BlockBuilderBuilder::new(&*client)
.on_parent_block(client.chain_info().genesis_hash)
.with_parent_block_number(0)
.build()
.unwrap()
.build()
.unwrap()
.block;
let hash = block.hash();
futures::executor::block_on(client.import(BlockOrigin::Own, block.clone())).unwrap();
let mut subs =
@@ -1034,7 +1041,14 @@ mod tests {
#[test]
fn subscription_ref_count() {
let (backend, mut client) = init_backend();
let block = client.new_block(Default::default()).unwrap().build().unwrap().block;
let block = BlockBuilderBuilder::new(&*client)
.on_parent_block(client.chain_info().genesis_hash)
.with_parent_block_number(0)
.build()
.unwrap()
.build()
.unwrap()
.block;
let hash = block.header.hash();
futures::executor::block_on(client.import(BlockOrigin::Own, block.clone())).unwrap();
@@ -1077,13 +1091,34 @@ mod tests {
#[test]
fn subscription_remove_subscription() {
let (backend, mut client) = init_backend();
let block = client.new_block(Default::default()).unwrap().build().unwrap().block;
let block = BlockBuilderBuilder::new(&*client)
.on_parent_block(client.chain_info().genesis_hash)
.with_parent_block_number(0)
.build()
.unwrap()
.build()
.unwrap()
.block;
let hash_1 = block.header.hash();
futures::executor::block_on(client.import(BlockOrigin::Own, block.clone())).unwrap();
let block = client.new_block(Default::default()).unwrap().build().unwrap().block;
let block = BlockBuilderBuilder::new(&*client)
.on_parent_block(hash_1)
.with_parent_block_number(1)
.build()
.unwrap()
.build()
.unwrap()
.block;
let hash_2 = block.header.hash();
futures::executor::block_on(client.import(BlockOrigin::Own, block.clone())).unwrap();
let block = client.new_block(Default::default()).unwrap().build().unwrap().block;
let block = BlockBuilderBuilder::new(&*client)
.on_parent_block(hash_2)
.with_parent_block_number(2)
.build()
.unwrap()
.build()
.unwrap()
.block;
let hash_3 = block.header.hash();
futures::executor::block_on(client.import(BlockOrigin::Own, block.clone())).unwrap();
@@ -1122,13 +1157,34 @@ mod tests {
#[test]
fn subscription_check_limits() {
let (backend, mut client) = init_backend();
let block = client.new_block(Default::default()).unwrap().build().unwrap().block;
let block = BlockBuilderBuilder::new(&*client)
.on_parent_block(client.chain_info().genesis_hash)
.with_parent_block_number(0)
.build()
.unwrap()
.build()
.unwrap()
.block;
let hash_1 = block.header.hash();
futures::executor::block_on(client.import(BlockOrigin::Own, block.clone())).unwrap();
let block = client.new_block(Default::default()).unwrap().build().unwrap().block;
let block = BlockBuilderBuilder::new(&*client)
.on_parent_block(hash_1)
.with_parent_block_number(1)
.build()
.unwrap()
.build()
.unwrap()
.block;
let hash_2 = block.header.hash();
futures::executor::block_on(client.import(BlockOrigin::Own, block.clone())).unwrap();
let block = client.new_block(Default::default()).unwrap().build().unwrap().block;
let block = BlockBuilderBuilder::new(&*client)
.on_parent_block(hash_2)
.with_parent_block_number(2)
.build()
.unwrap()
.build()
.unwrap()
.block;
let hash_3 = block.header.hash();
futures::executor::block_on(client.import(BlockOrigin::Own, block.clone())).unwrap();
@@ -1173,13 +1229,34 @@ mod tests {
#[test]
fn subscription_check_limits_with_duration() {
let (backend, mut client) = init_backend();
let block = client.new_block(Default::default()).unwrap().build().unwrap().block;
let hash_1 = block.header.hash();
let block = BlockBuilderBuilder::new(&*client)
.on_parent_block(client.chain_info().genesis_hash)
.with_parent_block_number(0)
.build()
.unwrap()
.build()
.unwrap()
.block;
let hash_1 = block.hash();
futures::executor::block_on(client.import(BlockOrigin::Own, block.clone())).unwrap();
let block = client.new_block(Default::default()).unwrap().build().unwrap().block;
let block = BlockBuilderBuilder::new(&*client)
.on_parent_block(hash_1)
.with_parent_block_number(1)
.build()
.unwrap()
.build()
.unwrap()
.block;
let hash_2 = block.header.hash();
futures::executor::block_on(client.import(BlockOrigin::Own, block.clone())).unwrap();
let block = client.new_block(Default::default()).unwrap().build().unwrap().block;
let block = BlockBuilderBuilder::new(&*client)
.on_parent_block(hash_2)
.with_parent_block_number(2)
.build()
.unwrap()
.build()
.unwrap()
.block;
let hash_3 = block.header.hash();
futures::executor::block_on(client.import(BlockOrigin::Own, block.clone())).unwrap();
@@ -31,7 +31,7 @@ use jsonrpsee::{
types::{error::CallError, EmptyServerParams as EmptyParams},
RpcModule,
};
use sc_block_builder::BlockBuilderProvider;
use sc_block_builder::BlockBuilderBuilder;
use sc_client_api::ChildInfo;
use sc_service::client::new_in_mem;
use sp_api::BlockT;
@@ -125,7 +125,14 @@ async fn setup_api() -> (
let sub_id = sub.subscription_id();
let sub_id = serde_json::to_string(&sub_id).unwrap();
let block = client.new_block(Default::default()).unwrap().build().unwrap().block;
let block = BlockBuilderBuilder::new(&*client)
.on_parent_block(client.chain_info().genesis_hash)
.with_parent_block_number(0)
.build()
.unwrap()
.build()
.unwrap()
.block;
client.import(BlockOrigin::Own, block.clone()).await.unwrap();
// Ensure the imported block is propagated and pinned for this subscription.
@@ -177,7 +184,14 @@ async fn follow_subscription_produces_blocks() {
});
assert_eq!(event, expected);
let block = client.new_block(Default::default()).unwrap().build().unwrap().block;
let block = BlockBuilderBuilder::new(&*client)
.on_parent_block(client.chain_info().genesis_hash)
.with_parent_block_number(0)
.build()
.unwrap()
.build()
.unwrap()
.block;
let best_hash = block.header.hash();
client.import(BlockOrigin::Own, block.clone()).await.unwrap();
@@ -255,8 +269,15 @@ async fn follow_with_runtime() {
// Import a new block without runtime changes.
// The runtime field must be None in this case.
let block = client.new_block(Default::default()).unwrap().build().unwrap().block;
let best_hash = block.header.hash();
let block = BlockBuilderBuilder::new(&*client)
.on_parent_block(client.chain_info().genesis_hash)
.with_parent_block_number(0)
.build()
.unwrap()
.build()
.unwrap()
.block;
let best_hash = block.hash();
client.import(BlockOrigin::Own, block.clone()).await.unwrap();
let event: FollowEvent<String> = get_next_event(&mut sub).await;
@@ -302,7 +323,11 @@ async fn follow_with_runtime() {
)
.unwrap();
let mut builder = client.new_block(Default::default()).unwrap();
let mut builder = BlockBuilderBuilder::new(&*client)
.on_parent_block(best_hash)
.with_parent_block_number(1)
.build()
.unwrap();
builder.push_storage_change(CODE.to_vec(), Some(wasm)).unwrap();
let block = builder.build().unwrap().block;
let best_hash = block.header.hash();
@@ -411,7 +436,11 @@ async fn get_body() {
);
// Import a block with extrinsics.
let mut builder = client.new_block(Default::default()).unwrap();
let mut builder = BlockBuilderBuilder::new(&*client)
.on_parent_block(block.hash())
.with_parent_block_number(1)
.build()
.unwrap();
builder
.push_transfer(runtime::Transfer {
from: AccountKeyring::Alice.into(),
@@ -554,7 +583,14 @@ async fn call_runtime_without_flag() {
let sub_id = sub.subscription_id();
let sub_id = serde_json::to_string(&sub_id).unwrap();
let block = client.new_block(Default::default()).unwrap().build().unwrap().block;
let block = BlockBuilderBuilder::new(&*client)
.on_parent_block(client.chain_info().genesis_hash)
.with_parent_block_number(0)
.build()
.unwrap()
.build()
.unwrap()
.block;
let block_hash = format!("{:?}", block.header.hash());
client.import(BlockOrigin::Own, block.clone()).await.unwrap();
@@ -648,7 +684,11 @@ async fn get_storage_hash() {
);
// Import a new block with storage changes.
let mut builder = client.new_block(Default::default()).unwrap();
let mut builder = BlockBuilderBuilder::new(&*client)
.on_parent_block(block.hash())
.with_parent_block_number(1)
.build()
.unwrap();
builder.push_storage_change(KEY.to_vec(), Some(VALUE.to_vec())).unwrap();
let block = builder.build().unwrap().block;
let block_hash = format!("{:?}", block.header.hash());
@@ -730,11 +770,15 @@ async fn get_storage_hash() {
#[tokio::test]
async fn get_storage_multi_query_iter() {
let (mut client, api, mut block_sub, sub_id, _) = setup_api().await;
let (mut client, api, mut block_sub, sub_id, block) = setup_api().await;
let key = hex_string(&KEY);
// Import a new block with storage changes.
let mut builder = client.new_block(Default::default()).unwrap();
let mut builder = BlockBuilderBuilder::new(&*client)
.on_parent_block(block.hash())
.with_parent_block_number(1)
.build()
.unwrap();
builder.push_storage_change(KEY.to_vec(), Some(VALUE.to_vec())).unwrap();
let block = builder.build().unwrap().block;
let block_hash = format!("{:?}", block.header.hash());
@@ -851,7 +895,7 @@ async fn get_storage_multi_query_iter() {
#[tokio::test]
async fn get_storage_value() {
let (mut client, api, mut block_sub, sub_id, block) = setup_api().await;
let block_hash = format!("{:?}", block.header.hash());
let block_hash = format!("{:?}", block.hash());
let invalid_hash = hex_string(&INVALID_HASH);
let key = hex_string(&KEY);
@@ -908,10 +952,14 @@ async fn get_storage_value() {
);
// Import a new block with storage changes.
let mut builder = client.new_block(Default::default()).unwrap();
let mut builder = BlockBuilderBuilder::new(&*client)
.on_parent_block(block.hash())
.with_parent_block_number(1)
.build()
.unwrap();
builder.push_storage_change(KEY.to_vec(), Some(VALUE.to_vec())).unwrap();
let block = builder.build().unwrap().block;
let block_hash = format!("{:?}", block.header.hash());
let block_hash = format!("{:?}", block.hash());
client.import(BlockOrigin::Own, block.clone()).await.unwrap();
// Ensure the imported block is propagated and pinned for this subscription.
@@ -1199,7 +1247,14 @@ async fn separate_operation_ids_for_subscriptions() {
let sub_id_second = sub_second.subscription_id();
let sub_id_second = serde_json::to_string(&sub_id_second).unwrap();
let block = client.new_block(Default::default()).unwrap().build().unwrap().block;
let block = BlockBuilderBuilder::new(&*client)
.on_parent_block(client.chain_info().genesis_hash)
.with_parent_block_number(0)
.build()
.unwrap()
.build()
.unwrap()
.block;
client.import(BlockOrigin::Own, block.clone()).await.unwrap();
let block_hash = format!("{:?}", block.header.hash());
@@ -1274,18 +1329,35 @@ async fn follow_generates_initial_blocks() {
let finalized_hash = client.info().finalized_hash;
// Block tree:
// finalized -> block 1 -> block 2 -> block 4
// -> block 1 -> block 3
let block_1 = client.new_block(Default::default()).unwrap().build().unwrap().block;
// finalized -> block 1 -> block 2 -> block 3
// -> block 1 -> block 2_f
let block_1 = BlockBuilderBuilder::new(&*client)
.on_parent_block(client.chain_info().genesis_hash)
.with_parent_block_number(0)
.build()
.unwrap()
.build()
.unwrap()
.block;
let block_1_hash = block_1.header.hash();
client.import(BlockOrigin::Own, block_1.clone()).await.unwrap();
let block_2 = client.new_block(Default::default()).unwrap().build().unwrap().block;
let block_2 = BlockBuilderBuilder::new(&*client)
.on_parent_block(block_1_hash)
.with_parent_block_number(1)
.build()
.unwrap()
.build()
.unwrap()
.block;
let block_2_hash = block_2.header.hash();
client.import(BlockOrigin::Own, block_2.clone()).await.unwrap();
let mut block_builder =
client.new_block_at(block_1.header.hash(), Default::default(), false).unwrap();
let mut block_builder = BlockBuilderBuilder::new(&*client)
.on_parent_block(block_1_hash)
.with_parent_block_number(1)
.build()
.unwrap();
// This push is required as otherwise block 3 has the same hash as block 2 and won't get
// imported
block_builder
@@ -1296,9 +1368,9 @@ async fn follow_generates_initial_blocks() {
nonce: 0,
})
.unwrap();
let block_3 = block_builder.build().unwrap().block;
let block_3_hash = block_3.header.hash();
client.import(BlockOrigin::Own, block_3.clone()).await.unwrap();
let block_2_f = block_builder.build().unwrap().block;
let block_2_f_hash = block_2_f.header.hash();
client.import(BlockOrigin::Own, block_2_f.clone()).await.unwrap();
let mut sub = api.subscribe("chainHead_unstable_follow", [false]).await.unwrap();
@@ -1333,7 +1405,7 @@ async fn follow_generates_initial_blocks() {
// Check block 3.
let event: FollowEvent<String> = get_next_event(&mut sub).await;
let expected = FollowEvent::NewBlock(NewBlock {
block_hash: format!("{:?}", block_3_hash),
block_hash: format!("{:?}", block_2_f_hash),
parent_block_hash: format!("{:?}", block_1_hash),
new_runtime: None,
with_runtime: false,
@@ -1346,14 +1418,21 @@ async fn follow_generates_initial_blocks() {
});
assert_eq!(event, expected);
// Import block 4.
let block_4 = client.new_block(Default::default()).unwrap().build().unwrap().block;
let block_4_hash = block_4.header.hash();
client.import(BlockOrigin::Own, block_4.clone()).await.unwrap();
// Import block 3.
let block_3 = BlockBuilderBuilder::new(&*client)
.on_parent_block(block_2_hash)
.with_parent_block_number(2)
.build()
.unwrap()
.build()
.unwrap()
.block;
let block_3_hash = block_3.hash();
client.import(BlockOrigin::Own, block_3.clone()).await.unwrap();
let event: FollowEvent<String> = get_next_event(&mut sub).await;
let expected = FollowEvent::NewBlock(NewBlock {
block_hash: format!("{:?}", block_4_hash),
block_hash: format!("{:?}", block_3_hash),
parent_block_hash: format!("{:?}", block_2_hash),
new_runtime: None,
with_runtime: false,
@@ -1362,23 +1441,23 @@ async fn follow_generates_initial_blocks() {
let event: FollowEvent<String> = get_next_event(&mut sub).await;
let expected = FollowEvent::BestBlockChanged(BestBlockChanged {
best_block_hash: format!("{:?}", block_4_hash),
best_block_hash: format!("{:?}", block_3_hash),
});
assert_eq!(event, expected);
// Check the finalized event:
// - blocks 1, 2, 4 from canonical chain are finalized
// - block 3 from the fork is pruned
client.finalize_block(block_4_hash, None).unwrap();
client.finalize_block(block_3_hash, None).unwrap();
let event: FollowEvent<String> = get_next_event(&mut sub).await;
let expected = FollowEvent::Finalized(Finalized {
finalized_block_hashes: vec![
format!("{:?}", block_1_hash),
format!("{:?}", block_2_hash),
format!("{:?}", block_4_hash),
format!("{:?}", block_3_hash),
],
pruned_block_hashes: vec![format!("{:?}", block_3_hash)],
pruned_block_hashes: vec![format!("{:?}", block_2_f_hash)],
});
assert_eq!(event, expected);
}
@@ -1405,7 +1484,15 @@ async fn follow_exceeding_pinned_blocks() {
let mut sub = api.subscribe("chainHead_unstable_follow", [false]).await.unwrap();
let block = client.new_block(Default::default()).unwrap().build().unwrap().block;
let block = BlockBuilderBuilder::new(&*client)
.on_parent_block(client.chain_info().genesis_hash)
.with_parent_block_number(0)
.build()
.unwrap()
.build()
.unwrap()
.block;
client.import(BlockOrigin::Own, block.clone()).await.unwrap();
// Ensure the imported block is propagated and pinned for this subscription.
@@ -1426,13 +1513,27 @@ async fn follow_exceeding_pinned_blocks() {
// finalized_block -> block -> block2
// The first 2 blocks are pinned into the subscription, but the block2 will exceed the limit (2
// blocks).
let block2 = client.new_block(Default::default()).unwrap().build().unwrap().block;
let block2 = BlockBuilderBuilder::new(&*client)
.on_parent_block(block.hash())
.with_parent_block_number(1)
.build()
.unwrap()
.build()
.unwrap()
.block;
client.import(BlockOrigin::Own, block2.clone()).await.unwrap();
assert_matches!(get_next_event::<FollowEvent<String>>(&mut sub).await, FollowEvent::Stop);
// Subscription will not produce any more event for further blocks.
let block3 = client.new_block(Default::default()).unwrap().build().unwrap().block;
let block3 = BlockBuilderBuilder::new(&*client)
.on_parent_block(block2.hash())
.with_parent_block_number(2)
.build()
.unwrap()
.build()
.unwrap()
.block;
client.import(BlockOrigin::Own, block3.clone()).await.unwrap();
assert!(sub.next::<FollowEvent<String>>().await.is_none());
@@ -1462,7 +1563,14 @@ async fn follow_with_unpin() {
let sub_id = sub.subscription_id();
let sub_id = serde_json::to_string(&sub_id).unwrap();
let block = client.new_block(Default::default()).unwrap().build().unwrap().block;
let block = BlockBuilderBuilder::new(&*client)
.on_parent_block(client.chain_info().genesis_hash)
.with_parent_block_number(0)
.build()
.unwrap()
.build()
.unwrap()
.block;
let block_hash = format!("{:?}", block.header.hash());
client.import(BlockOrigin::Own, block.clone()).await.unwrap();
@@ -1503,7 +1611,14 @@ async fn follow_with_unpin() {
// Block tree:
// finalized_block -> block -> block2
// ^ has been unpinned
let block2 = client.new_block(Default::default()).unwrap().build().unwrap().block;
let block2 = BlockBuilderBuilder::new(&*client)
.on_parent_block(block.hash())
.with_parent_block_number(1)
.build()
.unwrap()
.build()
.unwrap()
.block;
client.import(BlockOrigin::Own, block2.clone()).await.unwrap();
assert_matches!(
@@ -1516,7 +1631,14 @@ async fn follow_with_unpin() {
FollowEvent::BestBlockChanged(_)
);
let block3 = client.new_block(Default::default()).unwrap().build().unwrap().block;
let block3 = BlockBuilderBuilder::new(&*client)
.on_parent_block(block2.hash())
.with_parent_block_number(2)
.build()
.unwrap()
.build()
.unwrap()
.block;
client.import(BlockOrigin::Own, block3.clone()).await.unwrap();
assert_matches!(get_next_event::<FollowEvent<String>>(&mut sub).await, FollowEvent::Stop);
@@ -1560,27 +1682,52 @@ async fn follow_prune_best_block() {
// finalized -> block 1 -> block 2
// ^^^ best block reported
//
// -> block 1 -> block 3 -> block 4
// -> block 1 -> block 2_f -> block 4
// ^^^ finalized
//
// The block 4 is needed on the longest chain because we want the
// best block 2 to be reported as pruned. Pruning is happening at
// height (N - 1), where N is the finalized block number.
let block_1 = client.new_block(Default::default()).unwrap().build().unwrap().block;
let block_1_hash = block_1.header.hash();
let block_1 = BlockBuilderBuilder::new(&*client)
.on_parent_block(client.chain_info().genesis_hash)
.with_parent_block_number(0)
.build()
.unwrap()
.build()
.unwrap()
.block;
let block_1_hash = block_1.hash();
client.import(BlockOrigin::Own, block_1.clone()).await.unwrap();
let block_3 = client.new_block(Default::default()).unwrap().build().unwrap().block;
let block_3_hash = block_3.header.hash();
client.import(BlockOrigin::Own, block_3.clone()).await.unwrap();
let block_2_f = BlockBuilderBuilder::new(&*client)
.on_parent_block(block_1_hash)
.with_parent_block_number(1)
.build()
.unwrap()
.build()
.unwrap()
.block;
let block_2_f_hash = block_2_f.hash();
client.import(BlockOrigin::Own, block_2_f.clone()).await.unwrap();
let block_4 = client.new_block(Default::default()).unwrap().build().unwrap().block;
let block_4_hash = block_4.header.hash();
let block_4 = BlockBuilderBuilder::new(&*client)
.on_parent_block(block_2_f_hash)
.with_parent_block_number(2)
.build()
.unwrap()
.build()
.unwrap()
.block;
let block_4_hash = block_4.hash();
client.import(BlockOrigin::Own, block_4.clone()).await.unwrap();
// Import block 2 as best on the fork.
let mut block_builder = client.new_block_at(block_1_hash, Default::default(), false).unwrap();
let mut block_builder = BlockBuilderBuilder::new(&*client)
.on_parent_block(block_1_hash)
.with_parent_block_number(1)
.build()
.unwrap();
// This push is required as otherwise block 3 has the same hash as block 2 and won't get
// imported
block_builder
@@ -1613,7 +1760,7 @@ async fn follow_prune_best_block() {
// Check block 3.
let event: FollowEvent<String> = get_next_event(&mut sub).await;
let expected = FollowEvent::NewBlock(NewBlock {
block_hash: format!("{:?}", block_3_hash),
block_hash: format!("{:?}", block_2_f_hash),
parent_block_hash: format!("{:?}", block_1_hash),
new_runtime: None,
with_runtime: false,
@@ -1621,7 +1768,7 @@ async fn follow_prune_best_block() {
assert_eq!(event, expected);
let event: FollowEvent<String> = get_next_event(&mut sub).await;
let expected = FollowEvent::BestBlockChanged(BestBlockChanged {
best_block_hash: format!("{:?}", block_3_hash),
best_block_hash: format!("{:?}", block_2_f_hash),
});
assert_eq!(event, expected);
@@ -1629,7 +1776,7 @@ async fn follow_prune_best_block() {
let event: FollowEvent<String> = get_next_event(&mut sub).await;
let expected = FollowEvent::NewBlock(NewBlock {
block_hash: format!("{:?}", block_4_hash),
parent_block_hash: format!("{:?}", block_3_hash),
parent_block_hash: format!("{:?}", block_2_f_hash),
new_runtime: None,
with_runtime: false,
});
@@ -1670,7 +1817,7 @@ async fn follow_prune_best_block() {
let expected = FollowEvent::Finalized(Finalized {
finalized_block_hashes: vec![
format!("{:?}", block_1_hash),
format!("{:?}", block_3_hash),
format!("{:?}", block_2_f_hash),
format!("{:?}", block_4_hash),
],
pruned_block_hashes: vec![format!("{:?}", block_2_hash)],
@@ -1708,22 +1855,46 @@ async fn follow_forks_pruned_block() {
//
// finalized -> block 1 -> block 2 -> block 3
// ^^^ finalized
// -> block 1 -> block 4 -> block 5
// -> block 1 -> block 2_f -> block 3_f
//
let block_1 = client.new_block(Default::default()).unwrap().build().unwrap().block;
let block_1 = BlockBuilderBuilder::new(&*client)
.on_parent_block(client.chain_info().genesis_hash)
.with_parent_block_number(0)
.build()
.unwrap()
.build()
.unwrap()
.block;
client.import(BlockOrigin::Own, block_1.clone()).await.unwrap();
let block_2 = client.new_block(Default::default()).unwrap().build().unwrap().block;
let block_2 = BlockBuilderBuilder::new(&*client)
.on_parent_block(block_1.hash())
.with_parent_block_number(1)
.build()
.unwrap()
.build()
.unwrap()
.block;
client.import(BlockOrigin::Own, block_2.clone()).await.unwrap();
let block_3 = client.new_block(Default::default()).unwrap().build().unwrap().block;
let block_3 = BlockBuilderBuilder::new(&*client)
.on_parent_block(block_2.hash())
.with_parent_block_number(2)
.build()
.unwrap()
.build()
.unwrap()
.block;
let block_3_hash = block_3.header.hash();
client.import(BlockOrigin::Own, block_3.clone()).await.unwrap();
// Block 4 with parent Block 1 is not the best imported.
let mut block_builder =
client.new_block_at(block_1.header.hash(), Default::default(), false).unwrap();
let mut block_builder = BlockBuilderBuilder::new(&*client)
.on_parent_block(block_1.hash())
.with_parent_block_number(1)
.build()
.unwrap();
// This push is required as otherwise block 4 has the same hash as block 2 and won't get
// imported
block_builder
@@ -1734,11 +1905,14 @@ async fn follow_forks_pruned_block() {
nonce: 0,
})
.unwrap();
let block_4 = block_builder.build().unwrap().block;
client.import(BlockOrigin::Own, block_4.clone()).await.unwrap();
let block_2_f = block_builder.build().unwrap().block;
client.import(BlockOrigin::Own, block_2_f.clone()).await.unwrap();
let mut block_builder =
client.new_block_at(block_4.header.hash(), Default::default(), false).unwrap();
let mut block_builder = BlockBuilderBuilder::new(&*client)
.on_parent_block(block_2_f.hash())
.with_parent_block_number(2)
.build()
.unwrap();
block_builder
.push_transfer(Transfer {
from: AccountKeyring::Bob.into(),
@@ -1747,10 +1921,10 @@ async fn follow_forks_pruned_block() {
nonce: 0,
})
.unwrap();
let block_5 = block_builder.build().unwrap().block;
client.import(BlockOrigin::Own, block_5.clone()).await.unwrap();
let block_3_f = block_builder.build().unwrap().block;
client.import(BlockOrigin::Own, block_3_f.clone()).await.unwrap();
// Block 4 and 5 are not pruned, pruning happens at height (N - 1).
// Block 2_f and 3_f are not pruned, pruning happens at height (N - 1).
client.finalize_block(block_3_hash, None).unwrap();
let mut sub = api.subscribe("chainHead_unstable_follow", [false]).await.unwrap();
@@ -1766,22 +1940,29 @@ async fn follow_forks_pruned_block() {
// Block tree:
//
// finalized -> block 1 -> block 2 -> block 3 -> block 6
// finalized -> block 1 -> block 2 -> block 3 -> block 4
// ^^^ finalized
// -> block 1 -> block 4 -> block 5
// -> block 1 -> block 2_f -> block 3_f
//
// Mark block 6 as finalized to force block 4 and 5 to get pruned.
// Mark block 4 as finalized to force block 2_f and 3_f to get pruned.
let block_6 = client.new_block(Default::default()).unwrap().build().unwrap().block;
let block_6_hash = block_6.header.hash();
client.import(BlockOrigin::Own, block_6.clone()).await.unwrap();
let block_4 = BlockBuilderBuilder::new(&*client)
.on_parent_block(block_3.hash())
.with_parent_block_number(3)
.build()
.unwrap()
.build()
.unwrap()
.block;
let block_4_hash = block_4.hash();
client.import(BlockOrigin::Own, block_4.clone()).await.unwrap();
client.finalize_block(block_6_hash, None).unwrap();
client.finalize_block(block_4_hash, None).unwrap();
// Check block 6.
let event: FollowEvent<String> = get_next_event(&mut sub).await;
let expected = FollowEvent::NewBlock(NewBlock {
block_hash: format!("{:?}", block_6_hash),
block_hash: format!("{:?}", block_4_hash),
parent_block_hash: format!("{:?}", block_3_hash),
new_runtime: None,
with_runtime: false,
@@ -1789,14 +1970,14 @@ async fn follow_forks_pruned_block() {
assert_eq!(event, expected);
let event: FollowEvent<String> = get_next_event(&mut sub).await;
let expected = FollowEvent::BestBlockChanged(BestBlockChanged {
best_block_hash: format!("{:?}", block_6_hash),
best_block_hash: format!("{:?}", block_4_hash),
});
assert_eq!(event, expected);
// Block 4 and 5 must not be reported as pruned.
let event: FollowEvent<String> = get_next_event(&mut sub).await;
let expected = FollowEvent::Finalized(Finalized {
finalized_block_hashes: vec![format!("{:?}", block_6_hash)],
finalized_block_hashes: vec![format!("{:?}", block_4_hash)],
pruned_block_hashes: vec![],
});
assert_eq!(event, expected);
@@ -1826,26 +2007,51 @@ async fn follow_report_multiple_pruned_block() {
//
// finalized -> block 1 -> block 2 -> block 3
// ^^^ finalized after subscription
// -> block 1 -> block 4 -> block 5
// -> block 1 -> block 2_f -> block 3_f
let finalized_hash = client.info().finalized_hash;
let block_1 = client.new_block(Default::default()).unwrap().build().unwrap().block;
let block_1_hash = block_1.header.hash();
let block_1 = BlockBuilderBuilder::new(&*client)
.on_parent_block(client.chain_info().genesis_hash)
.with_parent_block_number(0)
.build()
.unwrap()
.build()
.unwrap()
.block;
let block_1_hash = block_1.hash();
client.import(BlockOrigin::Own, block_1.clone()).await.unwrap();
let block_2 = client.new_block(Default::default()).unwrap().build().unwrap().block;
let block_2_hash = block_2.header.hash();
let block_2 = BlockBuilderBuilder::new(&*client)
.on_parent_block(block_1.hash())
.with_parent_block_number(1)
.build()
.unwrap()
.build()
.unwrap()
.block;
let block_2_hash = block_2.hash();
client.import(BlockOrigin::Own, block_2.clone()).await.unwrap();
let block_3 = client.new_block(Default::default()).unwrap().build().unwrap().block;
let block_3_hash = block_3.header.hash();
let block_3 = BlockBuilderBuilder::new(&*client)
.on_parent_block(block_2.hash())
.with_parent_block_number(2)
.build()
.unwrap()
.build()
.unwrap()
.block;
let block_3_hash = block_3.hash();
client.import(BlockOrigin::Own, block_3.clone()).await.unwrap();
// Block 4 with parent Block 1 is not the best imported.
let mut block_builder =
client.new_block_at(block_1.header.hash(), Default::default(), false).unwrap();
// This push is required as otherwise block 4 has the same hash as block 2 and won't get
// Block 2_f with parent Block 1 is not the best imported.
let mut block_builder = BlockBuilderBuilder::new(&*client)
.on_parent_block(block_1.hash())
.with_parent_block_number(1)
.build()
.unwrap();
// This push is required as otherwise block 2_f has the same hash as block 2 and won't get
// imported
block_builder
.push_transfer(Transfer {
@@ -1855,12 +2061,16 @@ async fn follow_report_multiple_pruned_block() {
nonce: 0,
})
.unwrap();
let block_4 = block_builder.build().unwrap().block;
let block_4_hash = block_4.header.hash();
client.import(BlockOrigin::Own, block_4.clone()).await.unwrap();
let block_2_f = block_builder.build().unwrap().block;
let block_2_f_hash = block_2_f.hash();
client.import(BlockOrigin::Own, block_2_f.clone()).await.unwrap();
let mut block_builder = BlockBuilderBuilder::new(&*client)
.on_parent_block(block_2_f.hash())
.with_parent_block_number(2)
.build()
.unwrap();
let mut block_builder =
client.new_block_at(block_4.header.hash(), Default::default(), false).unwrap();
block_builder
.push_transfer(Transfer {
from: AccountKeyring::Bob.into(),
@@ -1869,9 +2079,9 @@ async fn follow_report_multiple_pruned_block() {
nonce: 0,
})
.unwrap();
let block_5 = block_builder.build().unwrap().block;
let block_5_hash = block_5.header.hash();
client.import(BlockOrigin::Own, block_5.clone()).await.unwrap();
let block_3_f = block_builder.build().unwrap().block;
let block_3_f_hash = block_3_f.hash();
client.import(BlockOrigin::Own, block_3_f.clone()).await.unwrap();
let mut sub = api.subscribe("chainHead_unstable_follow", [false]).await.unwrap();
// Initialized must always be reported first.
@@ -1913,7 +2123,7 @@ async fn follow_report_multiple_pruned_block() {
// The fork must also be reported.
let event: FollowEvent<String> = get_next_event(&mut sub).await;
let expected = FollowEvent::NewBlock(NewBlock {
block_hash: format!("{:?}", block_4_hash),
block_hash: format!("{:?}", block_2_f_hash),
parent_block_hash: format!("{:?}", block_1_hash),
new_runtime: None,
with_runtime: false,
@@ -1922,8 +2132,8 @@ async fn follow_report_multiple_pruned_block() {
let event: FollowEvent<String> = get_next_event(&mut sub).await;
let expected = FollowEvent::NewBlock(NewBlock {
block_hash: format!("{:?}", block_5_hash),
parent_block_hash: format!("{:?}", block_4_hash),
block_hash: format!("{:?}", block_3_f_hash),
parent_block_hash: format!("{:?}", block_2_f_hash),
new_runtime: None,
with_runtime: false,
});
@@ -1953,22 +2163,30 @@ async fn follow_report_multiple_pruned_block() {
// Block tree:
//
// finalized -> block 1 -> block 2 -> block 3 -> block 6
// finalized -> block 1 -> block 2 -> block 3 -> block 4
// ^^^ finalized
// -> block 1 -> block 4 -> block 5
// -> block 1 -> block 2_f -> block 3_f
//
// Mark block 6 as finalized to force block 4 and 5 to get pruned.
// Mark block 4 as finalized to force block 2_f and 3_f to get pruned.
let block_6 = client.new_block(Default::default()).unwrap().build().unwrap().block;
let block_6_hash = block_6.header.hash();
client.import(BlockOrigin::Own, block_6.clone()).await.unwrap();
let block_4 = BlockBuilderBuilder::new(&*client)
.on_parent_block(block_3.hash())
.with_parent_block_number(3)
.build()
.unwrap()
.build()
.unwrap()
.block;
client.finalize_block(block_6_hash, None).unwrap();
let block_4_hash = block_4.hash();
client.import(BlockOrigin::Own, block_4.clone()).await.unwrap();
client.finalize_block(block_4_hash, None).unwrap();
// Check block 6.
let event: FollowEvent<String> = get_next_event(&mut sub).await;
let expected = FollowEvent::NewBlock(NewBlock {
block_hash: format!("{:?}", block_6_hash),
block_hash: format!("{:?}", block_4_hash),
parent_block_hash: format!("{:?}", block_3_hash),
new_runtime: None,
with_runtime: false,
@@ -1976,15 +2194,15 @@ async fn follow_report_multiple_pruned_block() {
assert_eq!(event, expected);
let event: FollowEvent<String> = get_next_event(&mut sub).await;
let expected = FollowEvent::BestBlockChanged(BestBlockChanged {
best_block_hash: format!("{:?}", block_6_hash),
best_block_hash: format!("{:?}", block_4_hash),
});
assert_eq!(event, expected);
// Block 4 and 5 be reported as pruned, not just the stale head (block 5).
let event: FollowEvent<String> = get_next_event(&mut sub).await;
let expected = FollowEvent::Finalized(Finalized {
finalized_block_hashes: vec![format!("{:?}", block_6_hash)],
pruned_block_hashes: vec![format!("{:?}", block_4_hash), format!("{:?}", block_5_hash)],
finalized_block_hashes: vec![format!("{:?}", block_4_hash)],
pruned_block_hashes: vec![format!("{:?}", block_2_f_hash), format!("{:?}", block_3_f_hash)],
});
assert_eq!(event, expected);
}
@@ -2052,7 +2270,14 @@ async fn pin_block_references() {
let sub_id = sub.subscription_id();
let sub_id = serde_json::to_string(&sub_id).unwrap();
let block = client.new_block(Default::default()).unwrap().build().unwrap().block;
let block = BlockBuilderBuilder::new(&*client)
.on_parent_block(client.chain_info().genesis_hash)
.with_parent_block_number(0)
.build()
.unwrap()
.build()
.unwrap()
.block;
let hash = block.header.hash();
let block_hash = format!("{:?}", hash);
client.import(BlockOrigin::Own, block.clone()).await.unwrap();
@@ -2089,8 +2314,15 @@ async fn pin_block_references() {
// Add another 2 blocks and make sure we drop the subscription with the blocks pinned.
let mut hashes = Vec::new();
for _ in 0..2 {
let block = client.new_block(Default::default()).unwrap().build().unwrap().block;
let hash = block.header.hash();
let block = BlockBuilderBuilder::new(&*client)
.on_parent_block(client.chain_info().best_hash)
.with_parent_block_number(client.chain_info().best_number)
.build()
.unwrap()
.build()
.unwrap()
.block;
let hash = block.hash();
client.import(BlockOrigin::Own, block.clone()).await.unwrap();
// Ensure the imported block is propagated for this subscription.
@@ -2115,7 +2347,14 @@ async fn pin_block_references() {
drop(sub);
// The `chainHead` detects the subscription was terminated when it tries
// to send another block.
let block = client.new_block(Default::default()).unwrap().build().unwrap().block;
let block = BlockBuilderBuilder::new(&*client)
.on_parent_block(client.chain_info().best_hash)
.with_parent_block_number(client.chain_info().best_number)
.build()
.unwrap()
.build()
.unwrap()
.block;
client.import(BlockOrigin::Own, block.clone()).await.unwrap();
for hash in &hashes {
@@ -2146,7 +2385,14 @@ async fn follow_finalized_before_new_block() {
.into_rpc();
// Make sure the block is imported for it to be pinned.
let block_1 = client.new_block(Default::default()).unwrap().build().unwrap().block;
let block_1 = BlockBuilderBuilder::new(&*client)
.on_parent_block(client.chain_info().genesis_hash)
.with_parent_block_number(0)
.build()
.unwrap()
.build()
.unwrap()
.block;
let block_1_hash = block_1.header.hash();
client.import(BlockOrigin::Own, block_1.clone()).await.unwrap();
@@ -2191,8 +2437,15 @@ async fn follow_finalized_before_new_block() {
});
assert_eq!(event, expected);
let block_2 = client.new_block(Default::default()).unwrap().build().unwrap().block;
let block_2_hash = block_2.header.hash();
let block_2 = BlockBuilderBuilder::new(&*client)
.on_parent_block(block_1.hash())
.with_parent_block_number(1)
.build()
.unwrap()
.build()
.unwrap()
.block;
let block_2_hash = block_2.hash();
client.import(BlockOrigin::Own, block_2.clone()).await.unwrap();
// Triggering the `BlockImportNotification` notification for block 1 should have no effect
@@ -2250,7 +2503,14 @@ async fn ensure_operation_limits_works() {
let sub_id = sub.subscription_id();
let sub_id = serde_json::to_string(&sub_id).unwrap();
let block = client.new_block(Default::default()).unwrap().build().unwrap().block;
let block = BlockBuilderBuilder::new(&*client)
.on_parent_block(client.chain_info().genesis_hash)
.with_parent_block_number(0)
.build()
.unwrap()
.build()
.unwrap()
.block;
client.import(BlockOrigin::Own, block.clone()).await.unwrap();
// Ensure the imported block is propagated and pinned for this subscription.
@@ -2349,7 +2609,11 @@ async fn check_continue_operation() {
let sub_id = serde_json::to_string(&sub_id).unwrap();
// Import a new block with storage changes.
let mut builder = client.new_block(Default::default()).unwrap();
let mut builder = BlockBuilderBuilder::new(&*client)
.on_parent_block(client.chain_info().genesis_hash)
.with_parent_block_number(0)
.build()
.unwrap();
builder.push_storage_change(b":m".to_vec(), Some(b"a".to_vec())).unwrap();
builder.push_storage_change(b":mo".to_vec(), Some(b"ab".to_vec())).unwrap();
builder.push_storage_change(b":moc".to_vec(), Some(b"abc".to_vec())).unwrap();
@@ -2528,7 +2792,11 @@ async fn stop_storage_operation() {
let sub_id = serde_json::to_string(&sub_id).unwrap();
// Import a new block with storage changes.
let mut builder = client.new_block(Default::default()).unwrap();
let mut builder = BlockBuilderBuilder::new(&*client)
.on_parent_block(client.chain_info().genesis_hash)
.with_parent_block_number(0)
.build()
.unwrap();
builder.push_storage_change(b":m".to_vec(), Some(b"a".to_vec())).unwrap();
builder.push_storage_change(b":mo".to_vec(), Some(b"ab".to_vec())).unwrap();
let block = builder.build().unwrap().block;
@@ -2612,7 +2880,7 @@ async fn stop_storage_operation() {
#[tokio::test]
async fn storage_closest_merkle_value() {
let (mut client, api, mut sub, sub_id, _) = setup_api().await;
let (mut client, api, mut sub, sub_id, block) = setup_api().await;
/// The core of this test.
///
@@ -2738,7 +3006,11 @@ async fn storage_closest_merkle_value() {
}
// Import a new block with storage changes.
let mut builder = client.new_block(Default::default()).unwrap();
let mut builder = BlockBuilderBuilder::new(&*client)
.on_parent_block(block.hash())
.with_parent_block_number(1)
.build()
.unwrap();
builder.push_storage_change(b":AAAA".to_vec(), Some(vec![1; 64])).unwrap();
builder.push_storage_change(b":AAAB".to_vec(), Some(vec![2; 64])).unwrap();
let block = builder.build().unwrap().block;
@@ -2758,7 +3030,11 @@ async fn storage_closest_merkle_value() {
let merkle_values_lhs = expect_merkle_request(&api, &mut sub, sub_id.clone(), block_hash).await;
// Import a new block with and change AAAB value.
let mut builder = client.new_block(Default::default()).unwrap();
let mut builder = BlockBuilderBuilder::new(&*client)
.on_parent_block(block.hash())
.with_parent_block_number(2)
.build()
.unwrap();
builder.push_storage_change(b":AAAA".to_vec(), Some(vec![1; 64])).unwrap();
builder.push_storage_change(b":AAAB".to_vec(), Some(vec![3; 64])).unwrap();
let block = builder.build().unwrap().block;
+33 -5
View File
@@ -20,7 +20,7 @@ use super::*;
use crate::testing::{test_executor, timeout_secs};
use assert_matches::assert_matches;
use jsonrpsee::types::EmptyServerParams as EmptyParams;
use sc_block_builder::BlockBuilderProvider;
use sc_block_builder::BlockBuilderBuilder;
use sp_consensus::BlockOrigin;
use sp_rpc::list::ListOrValue;
use substrate_test_runtime_client::{
@@ -75,7 +75,14 @@ async fn should_return_a_block() {
let mut client = Arc::new(substrate_test_runtime_client::new());
let api = new_full(client.clone(), test_executor()).into_rpc();
let block = client.new_block(Default::default()).unwrap().build().unwrap().block;
let block = BlockBuilderBuilder::new(&*client)
.on_parent_block(client.chain_info().best_hash)
.with_parent_block_number(client.chain_info().best_number)
.build()
.unwrap()
.build()
.unwrap()
.block;
let block_hash = block.hash();
client.import(BlockOrigin::Own, block).await.unwrap();
@@ -152,7 +159,14 @@ async fn should_return_block_hash() {
api.call("chain_getBlockHash", [ListOrValue::from(1_u64)]).await.unwrap();
assert_matches!(res, None);
let block = client.new_block(Default::default()).unwrap().build().unwrap().block;
let block = BlockBuilderBuilder::new(&*client)
.on_parent_block(client.chain_info().best_hash)
.with_parent_block_number(client.chain_info().best_number)
.build()
.unwrap()
.build()
.unwrap()
.block;
client.import(BlockOrigin::Own, block.clone()).await.unwrap();
let res: ListOrValue<Option<H256>> =
@@ -197,7 +211,14 @@ async fn should_return_finalized_hash() {
assert_eq!(res, client.genesis_hash());
// import new block
let block = client.new_block(Default::default()).unwrap().build().unwrap().block;
let block = BlockBuilderBuilder::new(&*client)
.on_parent_block(client.chain_info().best_hash)
.with_parent_block_number(client.chain_info().best_number)
.build()
.unwrap()
.build()
.unwrap()
.block;
let block_hash = block.hash();
client.import(BlockOrigin::Own, block).await.unwrap();
@@ -232,7 +253,14 @@ async fn test_head_subscription(method: &str) {
let mut sub = {
let api = new_full(client.clone(), test_executor()).into_rpc();
let sub = api.subscribe(method, EmptyParams::new()).await.unwrap();
let block = client.new_block(Default::default()).unwrap().build().unwrap().block;
let block = BlockBuilderBuilder::new(&*client)
.on_parent_block(client.chain_info().best_hash)
.with_parent_block_number(client.chain_info().best_number)
.build()
.unwrap()
.build()
.unwrap()
.block;
let block_hash = block.hash();
client.import(BlockOrigin::Own, block).await.unwrap();
client.finalize_block(block_hash, None).unwrap();
+17 -3
View File
@@ -17,7 +17,7 @@
// along with this program. If not, see <https://www.gnu.org/licenses/>.
use super::*;
use sc_block_builder::BlockBuilderProvider;
use sc_block_builder::BlockBuilderBuilder;
use sp_blockchain::HeaderBackend;
use sp_consensus::BlockOrigin;
use substrate_test_runtime_client::{prelude::*, runtime::Block};
@@ -27,7 +27,14 @@ async fn block_stats_work() {
let mut client = Arc::new(substrate_test_runtime_client::new());
let api = <Dev<Block, _>>::new(client.clone(), DenyUnsafe::No).into_rpc();
let block = client.new_block(Default::default()).unwrap().build().unwrap().block;
let block = BlockBuilderBuilder::new(&*client)
.on_parent_block(client.chain_info().genesis_hash)
.with_parent_block_number(0)
.build()
.unwrap()
.build()
.unwrap()
.block;
let (expected_witness_len, expected_witness_compact_len, expected_block_len) = {
let genesis_hash = client.chain_info().genesis_hash;
@@ -72,7 +79,14 @@ async fn deny_unsafe_works() {
let mut client = Arc::new(substrate_test_runtime_client::new());
let api = <Dev<Block, _>>::new(client.clone(), DenyUnsafe::Yes).into_rpc();
let block = client.new_block(Default::default()).unwrap().build().unwrap().block;
let block = BlockBuilderBuilder::new(&*client)
.on_parent_block(client.chain_info().genesis_hash)
.with_parent_block_number(0)
.build()
.unwrap()
.build()
.unwrap()
.block;
client.import(BlockOrigin::Own, block).await.unwrap();
let best_hash = client.info().best_hash;
+16 -4
View File
@@ -25,7 +25,7 @@ use jsonrpsee::{
core::Error as RpcError,
types::{error::CallError as RpcCallError, EmptyServerParams as EmptyParams, ErrorObject},
};
use sc_block_builder::BlockBuilderProvider;
use sc_block_builder::BlockBuilderBuilder;
use sc_rpc_api::DenyUnsafe;
use sp_consensus::BlockOrigin;
use sp_core::{hash::H256, storage::ChildInfo};
@@ -218,7 +218,11 @@ async fn should_notify_about_storage_changes() {
let sub = api_rpc.subscribe("state_subscribeStorage", EmptyParams::new()).await.unwrap();
// Cause a change:
let mut builder = client.new_block(Default::default()).unwrap();
let mut builder = BlockBuilderBuilder::new(&*client)
.on_parent_block(client.chain_info().best_hash)
.with_parent_block_number(client.chain_info().best_number)
.build()
.unwrap();
builder
.push_transfer(Transfer {
from: AccountKeyring::Alice.into(),
@@ -263,7 +267,11 @@ async fn should_send_initial_storage_changes_and_notifications() {
.await
.unwrap();
let mut builder = client.new_block(Default::default()).unwrap();
let mut builder = BlockBuilderBuilder::new(&*client)
.on_parent_block(client.chain_info().best_hash)
.with_parent_block_number(client.chain_info().best_number)
.build()
.unwrap();
builder
.push_transfer(Transfer {
from: AccountKeyring::Alice.into(),
@@ -291,7 +299,11 @@ async fn should_query_storage() {
let (api, _child) = new_full(client.clone(), test_executor(), DenyUnsafe::No);
let mut add_block = |index| {
let mut builder = client.new_block(Default::default()).unwrap();
let mut builder = BlockBuilderBuilder::new(&*client)
.on_parent_block(client.chain_info().best_hash)
.with_parent_block_number(client.chain_info().best_number)
.build()
.unwrap();
// fake change: None -> None -> None
builder
.push(ExtrinsicBuilder::new_storage_change(vec![1], None).build())
-1
View File
@@ -69,7 +69,6 @@ sp-transaction-storage-proof = { path = "../../primitives/transaction-storage-pr
sc-rpc-server = { path = "../rpc-servers" }
sc-rpc = { path = "../rpc" }
sc-rpc-spec-v2 = { path = "../rpc-spec-v2" }
sc-block-builder = { path = "../block-builder" }
sc-informant = { path = "../informant" }
sc-telemetry = { path = "../telemetry" }
prometheus-endpoint = { package = "substrate-prometheus-endpoint", path = "../../utils/prometheus" }
+1 -42
View File
@@ -24,7 +24,6 @@ use log::{error, info, trace, warn};
use parking_lot::{Mutex, RwLock};
use prometheus_endpoint::Registry;
use rand::Rng;
use sc_block_builder::{BlockBuilderApi, BlockBuilderProvider, RecordProof};
use sc_chain_spec::{resolve_state_version_from_wasm, BuildGenesisBlock};
use sc_client_api::{
backend::{
@@ -70,7 +69,7 @@ use sp_runtime::{
Block as BlockT, BlockIdTo, HashingFor, Header as HeaderT, NumberFor, One,
SaturatedConversion, Zero,
},
Digest, Justification, Justifications, StateVersion,
Justification, Justifications, StateVersion,
};
use sp_state_machine::{
prove_child_read, prove_range_read_with_child_with_size, prove_read,
@@ -1402,46 +1401,6 @@ where
}
}
impl<B, E, Block, RA> BlockBuilderProvider<B, Block, Self> for Client<B, E, Block, RA>
where
B: backend::Backend<Block> + Send + Sync + 'static,
E: CallExecutor<Block> + Send + Sync + 'static,
Block: BlockT,
Self: ChainHeaderBackend<Block> + ProvideRuntimeApi<Block>,
<Self as ProvideRuntimeApi<Block>>::Api: ApiExt<Block> + BlockBuilderApi<Block>,
{
fn new_block_at<R: Into<RecordProof>>(
&self,
parent: Block::Hash,
inherent_digests: Digest,
record_proof: R,
) -> sp_blockchain::Result<sc_block_builder::BlockBuilder<Block, Self, B>> {
sc_block_builder::BlockBuilder::new(
self,
parent,
self.expect_block_number_from_id(&BlockId::Hash(parent))?,
record_proof.into(),
inherent_digests,
&self.backend,
)
}
fn new_block(
&self,
inherent_digests: Digest,
) -> sp_blockchain::Result<sc_block_builder::BlockBuilder<Block, Self, B>> {
let info = self.chain_info();
sc_block_builder::BlockBuilder::new(
self,
info.best_hash,
info.best_number,
RecordProof::No,
inherent_digests,
&self.backend,
)
}
}
impl<B, E, Block, RA> ExecutorProvider<Block> for Client<B, E, Block, RA>
where
B: backend::Backend<Block>,
File diff suppressed because it is too large Load Diff
@@ -24,7 +24,7 @@ use futures::{
prelude::*,
task::Poll,
};
use sc_block_builder::BlockBuilderProvider;
use sc_block_builder::BlockBuilderBuilder;
use sc_client_api::client::BlockchainEvents;
use sc_transaction_pool::*;
use sc_transaction_pool_api::{
@@ -1011,7 +1011,11 @@ fn import_notification_to_pool_maintain_works() {
let mut import_stream = block_on_stream(client.import_notification_stream());
// Build the block with the transaction included
let mut block_builder = client.new_block(Default::default()).unwrap();
let mut block_builder = BlockBuilderBuilder::new(&*client)
.on_parent_block(best_hash)
.with_parent_block_number(0)
.build()
.unwrap();
block_builder.push(xt).unwrap();
let block = block_builder.build().unwrap().block;
block_on(client.import(BlockOrigin::Own, block)).unwrap();
+28
View File
@@ -665,6 +665,34 @@ pub trait CallApiAt<Block: BlockT> {
) -> Result<(), ApiError>;
}
#[cfg(feature = "std")]
impl<Block: BlockT, T: CallApiAt<Block>> CallApiAt<Block> for std::sync::Arc<T> {
type StateBackend = T::StateBackend;
fn call_api_at(&self, params: CallApiAtParams<Block>) -> Result<Vec<u8>, ApiError> {
(**self).call_api_at(params)
}
fn runtime_version_at(
&self,
at_hash: <Block as BlockT>::Hash,
) -> Result<RuntimeVersion, ApiError> {
(**self).runtime_version_at(at_hash)
}
fn state_at(&self, at: <Block as BlockT>::Hash) -> Result<Self::StateBackend, ApiError> {
(**self).state_at(at)
}
fn initialize_extensions(
&self,
at: <Block as BlockT>::Hash,
extensions: &mut Extensions,
) -> Result<(), ApiError> {
(**self).initialize_extensions(at, extensions)
}
}
/// Auxiliary wrapper that holds an api instance and binds it to the given lifetime.
#[cfg(feature = "std")]
pub struct ApiRef<'a, T>(T, std::marker::PhantomData<&'a ()>);
@@ -17,6 +17,7 @@
use std::panic::UnwindSafe;
use sc_block_builder::BlockBuilderBuilder;
use sp_api::{ApiExt, Core, ProvideRuntimeApi};
use sp_runtime::{
traits::{HashingFor, Header as HeaderT},
@@ -31,7 +32,6 @@ use substrate_test_runtime_client::{
};
use codec::Encode;
use sc_block_builder::BlockBuilderProvider;
use sp_consensus::SelectChain;
use substrate_test_runtime_client::sc_executor::WasmExecutor;
@@ -105,9 +105,12 @@ fn record_proof_works() {
.into_unchecked_extrinsic();
// Build the block and record proof
let mut builder = client
.new_block_at(client.chain_info().best_hash, Default::default(), true)
.expect("Creates block builder");
let mut builder = BlockBuilderBuilder::new(&client)
.on_parent_block(client.chain_info().best_hash)
.with_parent_block_number(client.chain_info().best_number)
.enable_proof_recording()
.build()
.unwrap();
builder.push(transaction.clone()).unwrap();
let (block, _, proof) = builder.build().expect("Bake block").into_inner();
@@ -17,10 +17,8 @@
//! Block Builder extensions for tests.
use sc_client_api::backend;
use sp_api::{ApiExt, ProvideRuntimeApi};
use sc_block_builder::BlockBuilderApi;
use sp_api::{ApiExt, ProvideRuntimeApi};
use substrate_test_runtime::*;
/// Extension trait for test block builder.
@@ -45,12 +43,12 @@ pub trait BlockBuilderExt {
) -> Result<(), sp_blockchain::Error>;
}
impl<'a, A, B> BlockBuilderExt
for sc_block_builder::BlockBuilder<'a, substrate_test_runtime::Block, A, B>
impl<'a, A> BlockBuilderExt for sc_block_builder::BlockBuilder<'a, substrate_test_runtime::Block, A>
where
A: ProvideRuntimeApi<substrate_test_runtime::Block> + 'a,
A: ProvideRuntimeApi<substrate_test_runtime::Block>
+ sp_api::CallApiAt<substrate_test_runtime::Block>
+ 'a,
A::Api: BlockBuilderApi<substrate_test_runtime::Block> + ApiExt<substrate_test_runtime::Block>,
B: backend::Backend<substrate_test_runtime::Block>,
{
fn push_transfer(
&mut self,
@@ -26,14 +26,14 @@ use crate::{
AccountKeyring, BlockBuilderExt, ClientBlockImportExt, TestClientBuilder, TestClientBuilderExt,
};
use futures::executor::block_on;
use sc_block_builder::BlockBuilderProvider;
use sc_block_builder::BlockBuilderBuilder;
use sc_client_api::{
backend,
blockchain::{Backend as BlockChainBackendT, HeaderBackend},
};
use sp_consensus::BlockOrigin;
use sp_runtime::traits::Block as BlockT;
use substrate_test_runtime::{self, Transfer};
use substrate_test_runtime::Transfer;
/// helper to test the `leaves` implementation for various backends
pub fn test_leaves_for_backend<B: 'static>(backend: Arc<B>)
@@ -54,13 +54,24 @@ where
assert_eq!(blockchain.leaves().unwrap(), vec![genesis_hash]);
// G -> A1
let a1 = client.new_block(Default::default()).unwrap().build().unwrap().block;
let a1 = BlockBuilderBuilder::new(&client)
.on_parent_block(genesis_hash)
.fetch_parent_block_number(&client)
.unwrap()
.build()
.unwrap()
.build()
.unwrap()
.block;
block_on(client.import(BlockOrigin::Own, a1.clone())).unwrap();
assert_eq!(blockchain.leaves().unwrap(), vec![a1.hash()]);
// A1 -> A2
let a2 = client
.new_block_at(a1.hash(), Default::default(), false)
let a2 = BlockBuilderBuilder::new(&client)
.on_parent_block(a1.hash())
.fetch_parent_block_number(&client)
.unwrap()
.build()
.unwrap()
.build()
.unwrap()
@@ -70,8 +81,11 @@ where
assert_eq!(blockchain.leaves().unwrap(), vec![a2.hash()]);
// A2 -> A3
let a3 = client
.new_block_at(a2.hash(), Default::default(), false)
let a3 = BlockBuilderBuilder::new(&client)
.on_parent_block(a2.hash())
.fetch_parent_block_number(&client)
.unwrap()
.build()
.unwrap()
.build()
.unwrap()
@@ -81,8 +95,11 @@ where
assert_eq!(blockchain.leaves().unwrap(), vec![a3.hash()]);
// A3 -> A4
let a4 = client
.new_block_at(a3.hash(), Default::default(), false)
let a4 = BlockBuilderBuilder::new(&client)
.on_parent_block(a3.hash())
.fetch_parent_block_number(&client)
.unwrap()
.build()
.unwrap()
.build()
.unwrap()
@@ -91,8 +108,11 @@ where
assert_eq!(blockchain.leaves().unwrap(), vec![a4.hash()]);
// A4 -> A5
let a5 = client
.new_block_at(a4.hash(), Default::default(), false)
let a5 = BlockBuilderBuilder::new(&client)
.on_parent_block(a4.hash())
.fetch_parent_block_number(&client)
.unwrap()
.build()
.unwrap()
.build()
.unwrap()
@@ -102,7 +122,12 @@ where
assert_eq!(blockchain.leaves().unwrap(), vec![a5.hash()]);
// A1 -> B2
let mut builder = client.new_block_at(a1.hash(), Default::default(), false).unwrap();
let mut builder = BlockBuilderBuilder::new(&client)
.on_parent_block(a1.hash())
.fetch_parent_block_number(&client)
.unwrap()
.build()
.unwrap();
// this push is required as otherwise B2 has the same hash as A2 and won't get imported
builder
@@ -118,8 +143,11 @@ where
assert_eq!(blockchain.leaves().unwrap(), vec![a5.hash(), b2.hash()]);
// B2 -> B3
let b3 = client
.new_block_at(b2.hash(), Default::default(), false)
let b3 = BlockBuilderBuilder::new(&client)
.on_parent_block(b2.hash())
.fetch_parent_block_number(&client)
.unwrap()
.build()
.unwrap()
.build()
.unwrap()
@@ -129,8 +157,11 @@ where
assert_eq!(blockchain.leaves().unwrap(), vec![a5.hash(), b3.hash()]);
// B3 -> B4
let b4 = client
.new_block_at(b3.hash(), Default::default(), false)
let b4 = BlockBuilderBuilder::new(&client)
.on_parent_block(b3.hash())
.fetch_parent_block_number(&client)
.unwrap()
.build()
.unwrap()
.build()
.unwrap()
@@ -139,7 +170,12 @@ where
assert_eq!(blockchain.leaves().unwrap(), vec![a5.hash(), b4.hash()]);
// // B2 -> C3
let mut builder = client.new_block_at(b2.hash(), Default::default(), false).unwrap();
let mut builder = BlockBuilderBuilder::new(&client)
.on_parent_block(b2.hash())
.fetch_parent_block_number(&client)
.unwrap()
.build()
.unwrap();
// this push is required as otherwise C3 has the same hash as B3 and won't get imported
builder
.push_transfer(Transfer {
@@ -154,7 +190,12 @@ where
assert_eq!(blockchain.leaves().unwrap(), vec![a5.hash(), b4.hash(), c3.hash()]);
// A1 -> D2
let mut builder = client.new_block_at(a1.hash(), Default::default(), false).unwrap();
let mut builder = BlockBuilderBuilder::new(&client)
.on_parent_block(a1.hash())
.fetch_parent_block_number(&client)
.unwrap()
.build()
.unwrap();
// this push is required as otherwise D2 has the same hash as B2 and won't get imported
builder
.push_transfer(Transfer {
@@ -182,14 +223,26 @@ where
let mut client = TestClientBuilder::with_backend(backend.clone()).build();
let blockchain = backend.blockchain();
let genesis_hash = client.chain_info().genesis_hash;
// G -> A1
let a1 = client.new_block(Default::default()).unwrap().build().unwrap().block;
let a1 = BlockBuilderBuilder::new(&client)
.on_parent_block(genesis_hash)
.fetch_parent_block_number(&client)
.unwrap()
.build()
.unwrap()
.build()
.unwrap()
.block;
block_on(client.import(BlockOrigin::Own, a1.clone())).unwrap();
// A1 -> A2
let a2 = client
.new_block_at(a1.hash(), Default::default(), false)
let a2 = BlockBuilderBuilder::new(&client)
.on_parent_block(a1.hash())
.fetch_parent_block_number(&client)
.unwrap()
.build()
.unwrap()
.build()
.unwrap()
@@ -197,8 +250,11 @@ where
block_on(client.import(BlockOrigin::Own, a2.clone())).unwrap();
// A2 -> A3
let a3 = client
.new_block_at(a2.hash(), Default::default(), false)
let a3 = BlockBuilderBuilder::new(&client)
.on_parent_block(a2.hash())
.fetch_parent_block_number(&client)
.unwrap()
.build()
.unwrap()
.build()
.unwrap()
@@ -206,8 +262,11 @@ where
block_on(client.import(BlockOrigin::Own, a3.clone())).unwrap();
// A3 -> A4
let a4 = client
.new_block_at(a3.hash(), Default::default(), false)
let a4 = BlockBuilderBuilder::new(&client)
.on_parent_block(a3.hash())
.fetch_parent_block_number(&client)
.unwrap()
.build()
.unwrap()
.build()
.unwrap()
@@ -215,8 +274,11 @@ where
block_on(client.import(BlockOrigin::Own, a4.clone())).unwrap();
// A4 -> A5
let a5 = client
.new_block_at(a4.hash(), Default::default(), false)
let a5 = BlockBuilderBuilder::new(&client)
.on_parent_block(a4.hash())
.fetch_parent_block_number(&client)
.unwrap()
.build()
.unwrap()
.build()
.unwrap()
@@ -224,7 +286,12 @@ where
block_on(client.import(BlockOrigin::Own, a5.clone())).unwrap();
// A1 -> B2
let mut builder = client.new_block_at(a1.hash(), Default::default(), false).unwrap();
let mut builder = BlockBuilderBuilder::new(&client)
.on_parent_block(a1.hash())
.fetch_parent_block_number(&client)
.unwrap()
.build()
.unwrap();
// this push is required as otherwise B2 has the same hash as A2 and won't get imported
builder
.push_transfer(Transfer {
@@ -238,8 +305,11 @@ where
block_on(client.import(BlockOrigin::Own, b2.clone())).unwrap();
// B2 -> B3
let b3 = client
.new_block_at(b2.hash(), Default::default(), false)
let b3 = BlockBuilderBuilder::new(&client)
.on_parent_block(b2.hash())
.fetch_parent_block_number(&client)
.unwrap()
.build()
.unwrap()
.build()
.unwrap()
@@ -247,8 +317,11 @@ where
block_on(client.import(BlockOrigin::Own, b3.clone())).unwrap();
// B3 -> B4
let b4 = client
.new_block_at(b3.hash(), Default::default(), false)
let b4 = BlockBuilderBuilder::new(&client)
.on_parent_block(b3.hash())
.fetch_parent_block_number(&client)
.unwrap()
.build()
.unwrap()
.build()
.unwrap()
@@ -256,7 +329,12 @@ where
block_on(client.import(BlockOrigin::Own, b4)).unwrap();
// // B2 -> C3
let mut builder = client.new_block_at(b2.hash(), Default::default(), false).unwrap();
let mut builder = BlockBuilderBuilder::new(&client)
.on_parent_block(b2.hash())
.fetch_parent_block_number(&client)
.unwrap()
.build()
.unwrap();
// this push is required as otherwise C3 has the same hash as B3 and won't get imported
builder
.push_transfer(Transfer {
@@ -270,7 +348,12 @@ where
block_on(client.import(BlockOrigin::Own, c3.clone())).unwrap();
// A1 -> D2
let mut builder = client.new_block_at(a1.hash(), Default::default(), false).unwrap();
let mut builder = BlockBuilderBuilder::new(&client)
.on_parent_block(a1.hash())
.fetch_parent_block_number(&client)
.unwrap()
.build()
.unwrap();
// this push is required as otherwise D2 has the same hash as B2 and won't get imported
builder
.push_transfer(Transfer {
@@ -309,14 +392,26 @@ where
// A1 -> D2
let mut client = TestClientBuilder::with_backend(backend.clone()).build();
let blockchain = backend.blockchain();
let genesis_hash = client.chain_info().genesis_hash;
// G -> A1
let a1 = client.new_block(Default::default()).unwrap().build().unwrap().block;
let a1 = BlockBuilderBuilder::new(&client)
.on_parent_block(genesis_hash)
.fetch_parent_block_number(&client)
.unwrap()
.build()
.unwrap()
.build()
.unwrap()
.block;
block_on(client.import(BlockOrigin::Own, a1.clone())).unwrap();
// A1 -> A2
let a2 = client
.new_block_at(a1.hash(), Default::default(), false)
let a2 = BlockBuilderBuilder::new(&client)
.on_parent_block(a1.hash())
.fetch_parent_block_number(&client)
.unwrap()
.build()
.unwrap()
.build()
.unwrap()
@@ -324,8 +419,11 @@ where
block_on(client.import(BlockOrigin::Own, a2.clone())).unwrap();
// A2 -> A3
let a3 = client
.new_block_at(a2.hash(), Default::default(), false)
let a3 = BlockBuilderBuilder::new(&client)
.on_parent_block(a2.hash())
.fetch_parent_block_number(&client)
.unwrap()
.build()
.unwrap()
.build()
.unwrap()
@@ -333,8 +431,11 @@ where
block_on(client.import(BlockOrigin::Own, a3.clone())).unwrap();
// A3 -> A4
let a4 = client
.new_block_at(a3.hash(), Default::default(), false)
let a4 = BlockBuilderBuilder::new(&client)
.on_parent_block(a3.hash())
.fetch_parent_block_number(&client)
.unwrap()
.build()
.unwrap()
.build()
.unwrap()
@@ -342,8 +443,11 @@ where
block_on(client.import(BlockOrigin::Own, a4.clone())).unwrap();
// A4 -> A5
let a5 = client
.new_block_at(a4.hash(), Default::default(), false)
let a5 = BlockBuilderBuilder::new(&client)
.on_parent_block(a4.hash())
.fetch_parent_block_number(&client)
.unwrap()
.build()
.unwrap()
.build()
.unwrap()
@@ -351,7 +455,12 @@ where
block_on(client.import(BlockOrigin::Own, a5.clone())).unwrap();
// A1 -> B2
let mut builder = client.new_block_at(a1.hash(), Default::default(), false).unwrap();
let mut builder = BlockBuilderBuilder::new(&client)
.on_parent_block(a1.hash())
.fetch_parent_block_number(&client)
.unwrap()
.build()
.unwrap();
// this push is required as otherwise B2 has the same hash as A2 and won't get imported
builder
.push_transfer(Transfer {
@@ -365,8 +474,11 @@ where
block_on(client.import(BlockOrigin::Own, b2.clone())).unwrap();
// B2 -> B3
let b3 = client
.new_block_at(b2.hash(), Default::default(), false)
let b3 = BlockBuilderBuilder::new(&client)
.on_parent_block(b2.hash())
.fetch_parent_block_number(&client)
.unwrap()
.build()
.unwrap()
.build()
.unwrap()
@@ -374,8 +486,11 @@ where
block_on(client.import(BlockOrigin::Own, b3.clone())).unwrap();
// B3 -> B4
let b4 = client
.new_block_at(b3.hash(), Default::default(), false)
let b4 = BlockBuilderBuilder::new(&client)
.on_parent_block(b3.hash())
.fetch_parent_block_number(&client)
.unwrap()
.build()
.unwrap()
.build()
.unwrap()
@@ -383,7 +498,12 @@ where
block_on(client.import(BlockOrigin::Own, b4)).unwrap();
// // B2 -> C3
let mut builder = client.new_block_at(b2.hash(), Default::default(), false).unwrap();
let mut builder = BlockBuilderBuilder::new(&client)
.on_parent_block(b2.hash())
.fetch_parent_block_number(&client)
.unwrap()
.build()
.unwrap();
// this push is required as otherwise C3 has the same hash as B3 and won't get imported
builder
.push_transfer(Transfer {
@@ -397,7 +517,12 @@ where
block_on(client.import(BlockOrigin::Own, c3)).unwrap();
// A1 -> D2
let mut builder = client.new_block_at(a1.hash(), Default::default(), false).unwrap();
let mut builder = BlockBuilderBuilder::new(&client)
.on_parent_block(a1.hash())
.fetch_parent_block_number(&client)
.unwrap()
.build()
.unwrap();
// this push is required as otherwise D2 has the same hash as B2 and won't get imported
builder
.push_transfer(Transfer {
+6 -2
View File
@@ -1020,7 +1020,7 @@ mod tests {
use super::*;
use codec::Encode;
use frame_support::dispatch::DispatchInfo;
use sc_block_builder::BlockBuilderProvider;
use sc_block_builder::BlockBuilderBuilder;
use sp_api::{ApiExt, ProvideRuntimeApi};
use sp_consensus::BlockOrigin;
use sp_core::{storage::well_known_keys::HEAP_PAGES, traits::CallContext};
@@ -1052,7 +1052,11 @@ mod tests {
// Create a block that sets the `:heap_pages` to 32 pages of memory which corresponds to
// ~2048k of heap memory.
let (new_at_hash, block) = {
let mut builder = client.new_block(Default::default()).unwrap();
let mut builder = BlockBuilderBuilder::new(&client)
.on_parent_block(best_hash)
.with_parent_block_number(0)
.build()
.unwrap();
builder.push_storage_change(HEAP_PAGES.to_vec(), Some(32u64.encode())).unwrap();
let block = builder.build().unwrap().block;
let hash = block.header.hash();
@@ -20,7 +20,7 @@
use codec::DecodeAll;
use frame_support::weights::constants::WEIGHT_REF_TIME_PER_NANOS;
use frame_system::ConsumedWeight;
use sc_block_builder::{BlockBuilderApi, BlockBuilderProvider};
use sc_block_builder::BlockBuilderApi;
use sc_cli::{Error, Result};
use sc_client_api::{
Backend as ClientBackend, BlockBackend, HeaderBackend, StorageProvider, UsageProvider,
@@ -71,8 +71,7 @@ impl<Block, BA, C> Benchmark<Block, BA, C>
where
Block: BlockT<Extrinsic = OpaqueExtrinsic>,
BA: ClientBackend<Block>,
C: BlockBuilderProvider<BA, Block, C>
+ ProvideRuntimeApi<Block>
C: ProvideRuntimeApi<Block>
+ StorageProvider<Block, BA>
+ UsageProvider<Block>
+ BlockBackend<Block>
@@ -18,7 +18,7 @@
//! Contains the [`BlockCmd`] as entry point for the CLI to execute
//! the *block* benchmark.
use sc_block_builder::{BlockBuilderApi, BlockBuilderProvider};
use sc_block_builder::BlockBuilderApi;
use sc_cli::{CliConfiguration, ImportParams, Result, SharedParams};
use sc_client_api::{Backend as ClientBackend, BlockBackend, StorageProvider, UsageProvider};
use sp_api::{ApiExt, ProvideRuntimeApi};
@@ -84,8 +84,7 @@ impl BlockCmd {
where
Block: BlockT<Extrinsic = OpaqueExtrinsic>,
BA: ClientBackend<Block>,
C: BlockBuilderProvider<BA, Block, C>
+ BlockBackend<Block>
C: BlockBackend<Block>
+ ProvideRuntimeApi<Block>
+ StorageProvider<Block, BA>
+ UsageProvider<Block>
@@ -17,10 +17,10 @@
//! Contains the core benchmarking logic.
use sc_block_builder::{BlockBuilderApi, BlockBuilderProvider};
use sc_block_builder::{BlockBuilderApi, BlockBuilderBuilder};
use sc_cli::{Error, Result};
use sc_client_api::Backend as ClientBackend;
use sp_api::{ApiExt, Core, ProvideRuntimeApi};
use sc_client_api::UsageProvider;
use sp_api::{ApiExt, CallApiAt, Core, ProvideRuntimeApi};
use sp_blockchain::{
ApplyExtrinsicFailed::Validity,
Error::{ApplyExtrinsicFailed, RuntimeApiError},
@@ -61,20 +61,20 @@ pub struct BenchmarkParams {
pub(crate) type BenchRecord = Vec<u64>;
/// Holds all objects needed to run the *overhead* benchmarks.
pub(crate) struct Benchmark<Block, BA, C> {
pub(crate) struct Benchmark<Block, C> {
client: Arc<C>,
params: BenchmarkParams,
inherent_data: sp_inherents::InherentData,
digest_items: Vec<DigestItem>,
_p: PhantomData<(Block, BA)>,
_p: PhantomData<Block>,
}
impl<Block, BA, C> Benchmark<Block, BA, C>
impl<Block, C> Benchmark<Block, C>
where
Block: BlockT<Extrinsic = OpaqueExtrinsic>,
BA: ClientBackend<Block>,
C: BlockBuilderProvider<BA, Block, C>
+ ProvideRuntimeApi<Block>
C: ProvideRuntimeApi<Block>
+ CallApiAt<Block>
+ UsageProvider<Block>
+ sp_blockchain::HeaderBackend<Block>,
C::Api: ApiExt<Block> + BlockBuilderApi<Block>,
{
@@ -129,7 +129,13 @@ where
&self,
ext_builder: Option<&dyn ExtrinsicBuilder>,
) -> Result<(Block, Option<u64>)> {
let mut builder = self.client.new_block(Digest { logs: self.digest_items.clone() })?;
let chain = self.client.usage_info().chain;
let mut builder = BlockBuilderBuilder::new(&*self.client)
.on_parent_block(chain.best_hash)
.with_parent_block_number(chain.best_number)
.with_inherent_digests(Digest { logs: self.digest_items.clone() })
.build()?;
// Create and insert the inherents.
let inherents = builder.create_inherents(self.inherent_data.clone())?;
for inherent in inherents {
@@ -15,10 +15,10 @@
// See the License for the specific language governing permissions and
// limitations under the License.
use sc_block_builder::{BlockBuilderApi, BlockBuilderProvider};
use sc_block_builder::BlockBuilderApi;
use sc_cli::{CliConfiguration, ImportParams, Result, SharedParams};
use sc_client_api::Backend as ClientBackend;
use sp_api::{ApiExt, ProvideRuntimeApi};
use sc_client_api::UsageProvider;
use sp_api::{ApiExt, CallApiAt, ProvideRuntimeApi};
use sp_runtime::{traits::Block as BlockT, DigestItem, OpaqueExtrinsic};
use clap::{Args, Parser};
@@ -84,7 +84,7 @@ impl ExtrinsicCmd {
/// Benchmark the execution time of a specific type of extrinsic.
///
/// The output will be printed to console.
pub fn run<Block, BA, C>(
pub fn run<Block, C>(
&self,
client: Arc<C>,
inherent_data: sp_inherents::InherentData,
@@ -93,9 +93,9 @@ impl ExtrinsicCmd {
) -> Result<()>
where
Block: BlockT<Extrinsic = OpaqueExtrinsic>,
BA: ClientBackend<Block>,
C: BlockBuilderProvider<BA, Block, C>
+ ProvideRuntimeApi<Block>
C: ProvideRuntimeApi<Block>
+ CallApiAt<Block>
+ UsageProvider<Block>
+ sp_blockchain::HeaderBackend<Block>,
C::Api: ApiExt<Block> + BlockBuilderApi<Block>,
{
@@ -18,11 +18,11 @@
//! Contains the [`OverheadCmd`] as entry point for the CLI to execute
//! the *overhead* benchmarks.
use sc_block_builder::{BlockBuilderApi, BlockBuilderProvider};
use sc_block_builder::BlockBuilderApi;
use sc_cli::{CliConfiguration, ImportParams, Result, SharedParams};
use sc_client_api::Backend as ClientBackend;
use sc_client_api::UsageProvider;
use sc_service::Configuration;
use sp_api::{ApiExt, ProvideRuntimeApi};
use sp_api::{ApiExt, CallApiAt, ProvideRuntimeApi};
use sp_runtime::{traits::Block as BlockT, DigestItem, OpaqueExtrinsic};
use clap::{Args, Parser};
@@ -97,7 +97,7 @@ impl OverheadCmd {
///
/// Writes the results to console and into two instances of the
/// `weights.hbs` template, one for each benchmark.
pub fn run<Block, BA, C>(
pub fn run<Block, C>(
&self,
cfg: Configuration,
client: Arc<C>,
@@ -107,9 +107,9 @@ impl OverheadCmd {
) -> Result<()>
where
Block: BlockT<Extrinsic = OpaqueExtrinsic>,
BA: ClientBackend<Block>,
C: BlockBuilderProvider<BA, Block, C>
+ ProvideRuntimeApi<Block>
C: ProvideRuntimeApi<Block>
+ CallApiAt<Block>
+ UsageProvider<Block>
+ sp_blockchain::HeaderBackend<Block>,
C::Api: ApiExt<Block> + BlockBuilderApi<Block>,
{