BlockId removal: refactor: HeaderBackend::header (#12874)

* BlockId removal: refactor: HeaderBackend::header

It changes the arguments of:
- `HeaderBackend::header`,
- `Client::header`,
- `PeersClient::header`
- `ChainApi::block_header`

methods from: `BlockId<Block>` to: `Block::Hash`

This PR is part of BlockId::Number refactoring analysis (paritytech/substrate#11292)

* non-trivial usages of haeder(block_id) refactored

This may required introduction of dedicated function:
header_for_block_num

* fmt

* fix

* doc fixed

* ".git/.scripts/fmt.sh"

* BlockId removal: refactor: HeaderBackend::expect_header

It changes the arguments of `HeaderBackend::expect_header` method from: `BlockId<Block>` to: `Block::Hash`

* ".git/.scripts/fmt.sh"

* readme updated

* ".git/.scripts/fmt.sh"

* fix

Co-authored-by: parity-processbot <>
This commit is contained in:
Michal Kucharczyk
2022-12-20 10:43:31 +01:00
committed by GitHub
parent 74da30c8a2
commit 548955a73f
55 changed files with 307 additions and 360 deletions
+2 -2
View File
@@ -957,7 +957,7 @@ mod tests {
compatibility_mode: Default::default(),
};
let head = client.header(&BlockId::Number(0)).unwrap().unwrap();
let head = client.expect_header(client.info().genesis_hash).unwrap();
let res = worker
.on_slot(SlotInfo {
@@ -972,6 +972,6 @@ mod tests {
.unwrap();
// The returned block should be imported and we should be able to get its header by now.
assert!(client.header(&BlockId::Hash(res.block.hash())).unwrap().is_some());
assert!(client.header(res.block.hash()).unwrap().is_some());
}
}
+2 -2
View File
@@ -1425,7 +1425,7 @@ where
let parent_hash = *block.header.parent_hash();
let parent_header = self
.client
.header(BlockId::Hash(parent_hash))
.header(parent_hash)
.map_err(|e| ConsensusError::ChainLookup(e.to_string()))?
.ok_or_else(|| {
ConsensusError::ChainLookup(
@@ -1664,7 +1664,7 @@ where
let finalized_slot = {
let finalized_header = client
.header(BlockId::Hash(info.finalized_hash))
.header(info.finalized_hash)
.map_err(|e| ConsensusError::ClientImport(e.to_string()))?
.expect(
"best finalized hash was given by client; finalized headers must exist in db; qed",
+32 -62
View File
@@ -668,17 +668,17 @@ async fn propose_and_import_blocks<Transaction: Send + 'static>(
client: &PeersFullClient,
proposer_factory: &mut DummyFactory,
block_import: &mut BoxBlockImport<TestBlock, Transaction>,
parent_id: BlockId<TestBlock>,
parent_hash: Hash,
n: usize,
) -> Vec<Hash> {
let mut hashes = Vec::with_capacity(n);
let mut parent_header = client.header(&parent_id).unwrap().unwrap();
let mut parent_header = client.header(parent_hash).unwrap().unwrap();
for _ in 0..n {
let block_hash =
propose_and_import_block(&parent_header, None, proposer_factory, block_import).await;
hashes.push(block_hash);
parent_header = client.header(&BlockId::Hash(block_hash)).unwrap().unwrap();
parent_header = client.header(block_hash).unwrap().unwrap();
}
hashes
@@ -701,7 +701,7 @@ async fn importing_block_one_sets_genesis_epoch() {
let mut block_import = data.block_import.lock().take().expect("import set up during init");
let genesis_header = client.header(&BlockId::Number(0)).unwrap().unwrap();
let genesis_header = client.header(client.chain_info().genesis_hash).unwrap().unwrap();
let block_hash = propose_and_import_block(
&genesis_header,
@@ -759,34 +759,19 @@ async fn revert_prunes_epoch_changes_and_removes_weights() {
&client,
&mut proposer_factory,
&mut block_import,
BlockId::Number(0),
client.chain_info().genesis_hash,
21,
)
.await;
let fork1 = propose_and_import_blocks(
&client,
&mut proposer_factory,
&mut block_import,
BlockId::Hash(canon[0]),
10,
)
.await;
let fork2 = propose_and_import_blocks(
&client,
&mut proposer_factory,
&mut block_import,
BlockId::Hash(canon[7]),
10,
)
.await;
let fork3 = propose_and_import_blocks(
&client,
&mut proposer_factory,
&mut block_import,
BlockId::Hash(canon[11]),
8,
)
.await;
let fork1 =
propose_and_import_blocks(&client, &mut proposer_factory, &mut block_import, canon[0], 10)
.await;
let fork2 =
propose_and_import_blocks(&client, &mut proposer_factory, &mut block_import, canon[7], 10)
.await;
let fork3 =
propose_and_import_blocks(&client, &mut proposer_factory, &mut block_import, canon[11], 8)
.await;
// We should be tracking a total of 9 epochs in the fork tree
assert_eq!(epoch_changes.shared_data().tree().iter().count(), 8);
@@ -850,7 +835,7 @@ async fn revert_not_allowed_for_finalized() {
&client,
&mut proposer_factory,
&mut block_import,
BlockId::Number(0),
client.chain_info().genesis_hash,
3,
)
.await;
@@ -903,36 +888,21 @@ async fn importing_epoch_change_block_prunes_tree() {
&client,
&mut proposer_factory,
&mut block_import,
BlockId::Number(0),
client.chain_info().genesis_hash,
30,
)
.await;
// Create the forks
let fork_1 = propose_and_import_blocks(
&client,
&mut proposer_factory,
&mut block_import,
BlockId::Hash(canon[0]),
10,
)
.await;
let fork_2 = propose_and_import_blocks(
&client,
&mut proposer_factory,
&mut block_import,
BlockId::Hash(canon[12]),
15,
)
.await;
let fork_3 = propose_and_import_blocks(
&client,
&mut proposer_factory,
&mut block_import,
BlockId::Hash(canon[18]),
10,
)
.await;
let fork_1 =
propose_and_import_blocks(&client, &mut proposer_factory, &mut block_import, canon[0], 10)
.await;
let fork_2 =
propose_and_import_blocks(&client, &mut proposer_factory, &mut block_import, canon[12], 15)
.await;
let fork_3 =
propose_and_import_blocks(&client, &mut proposer_factory, &mut block_import, canon[18], 10)
.await;
// We should be tracking a total of 9 epochs in the fork tree
assert_eq!(epoch_changes.shared_data().tree().iter().count(), 9);
@@ -947,7 +917,7 @@ async fn importing_epoch_change_block_prunes_tree() {
&client,
&mut proposer_factory,
&mut block_import,
BlockId::Hash(client.chain_info().best_hash),
client.chain_info().best_hash,
7,
)
.await;
@@ -967,7 +937,7 @@ async fn importing_epoch_change_block_prunes_tree() {
&client,
&mut proposer_factory,
&mut block_import,
BlockId::Hash(client.chain_info().best_hash),
client.chain_info().best_hash,
8,
)
.await;
@@ -1001,7 +971,7 @@ async fn verify_slots_are_strictly_increasing() {
mutator: Arc::new(|_, _| ()),
};
let genesis_header = client.header(&BlockId::Number(0)).unwrap().unwrap();
let genesis_header = client.header(client.chain_info().genesis_hash).unwrap().unwrap();
// we should have no issue importing this block
let b1 = propose_and_import_block(
@@ -1012,7 +982,7 @@ async fn verify_slots_are_strictly_increasing() {
)
.await;
let b1 = client.header(&BlockId::Hash(b1)).unwrap().unwrap();
let b1 = client.header(b1).unwrap().unwrap();
// we should fail to import this block since the slot number didn't increase.
// we will panic due to the `PanickingBlockImport` defined above.
@@ -1091,7 +1061,7 @@ async fn obsolete_blocks_aux_data_cleanup() {
&client,
&mut proposer_factory,
&mut block_import,
BlockId::Number(0),
client.chain_info().genesis_hash,
4,
)
.await;
@@ -1099,7 +1069,7 @@ async fn obsolete_blocks_aux_data_cleanup() {
&client,
&mut proposer_factory,
&mut block_import,
BlockId::Number(0),
client.chain_info().genesis_hash,
2,
)
.await;
@@ -1107,7 +1077,7 @@ async fn obsolete_blocks_aux_data_cleanup() {
&client,
&mut proposer_factory,
&mut block_import,
BlockId::Number(3),
fork1_hashes[2],
2,
)
.await;
@@ -21,10 +21,7 @@
use sc_client_api::backend;
use sp_blockchain::{Backend, HeaderBackend};
use sp_consensus::{Error as ConsensusError, SelectChain};
use sp_runtime::{
generic::BlockId,
traits::{Block as BlockT, NumberFor},
};
use sp_runtime::traits::{Block as BlockT, NumberFor};
use std::{marker::PhantomData, sync::Arc};
/// Implement Longest Chain Select implementation
@@ -63,7 +60,7 @@ where
Ok(self
.backend
.blockchain()
.header(BlockId::Hash(best_hash))?
.header(best_hash)?
.expect("given block hash was fetched from block in db; qed"))
}
@@ -44,7 +44,7 @@ use sp_consensus_babe::{
use sp_consensus_slots::Slot;
use sp_inherents::InherentData;
use sp_runtime::{
generic::{BlockId, Digest},
generic::Digest,
traits::{Block as BlockT, Header},
DigestItem,
};
@@ -108,7 +108,7 @@ where
let parent_hash = import_params.header.parent_hash();
let parent = self
.client
.header(BlockId::Hash(*parent_hash))
.header(*parent_hash)
.ok()
.flatten()
.ok_or_else(|| format!("header for block {} not found", parent_hash))?;
@@ -30,10 +30,7 @@ use sp_consensus_aura::{
use sp_consensus_babe::BabeApi;
use sp_consensus_slots::{Slot, SlotDuration};
use sp_inherents::{InherentData, InherentDataProvider, InherentIdentifier};
use sp_runtime::{
generic::BlockId,
traits::{Block as BlockT, Zero},
};
use sp_runtime::traits::{Block as BlockT, Zero};
use sp_timestamp::{InherentType, INHERENT_IDENTIFIER};
use std::{
sync::{atomic, Arc},
@@ -109,7 +106,7 @@ impl SlotTimestampProvider {
// otherwise we'd be producing blocks for older slots.
let time = if info.best_number != Zero::zero() {
let header = client
.header(BlockId::Hash(info.best_hash))?
.header(info.best_hash)?
.ok_or_else(|| "best header not found in the db!".to_string())?;
let slot = func(header)?;
// add the slot duration so there's no collision of slots
@@ -360,7 +360,7 @@ mod tests {
let (client, select_chain) = builder.build_with_longest_chain();
let client = Arc::new(client);
let spawner = sp_core::testing::TaskExecutor::new();
let genesis_hash = client.header(&BlockId::Number(0)).unwrap().unwrap().hash();
let genesis_hash = client.info().genesis_hash;
let pool = Arc::new(BasicPool::with_revalidation_type(
Options::default(),
true.into(),
@@ -424,7 +424,8 @@ mod tests {
}
);
// assert that there's a new block in the db.
assert!(client.header(&BlockId::Number(1)).unwrap().is_some())
assert!(client.header(created_block.hash).unwrap().is_some());
assert_eq!(client.header(created_block.hash).unwrap().unwrap().number, 1)
}
#[tokio::test]
@@ -433,7 +434,7 @@ mod tests {
let (client, select_chain) = builder.build_with_longest_chain();
let client = Arc::new(client);
let spawner = sp_core::testing::TaskExecutor::new();
let genesis_hash = client.header(&BlockId::Number(0)).unwrap().unwrap().hash();
let genesis_hash = client.info().genesis_hash;
let pool = Arc::new(BasicPool::with_revalidation_type(
Options::default(),
true.into(),
@@ -494,7 +495,7 @@ mod tests {
}
);
// assert that there's a new block in the db.
let header = client.header(&BlockId::Number(1)).unwrap().unwrap();
let header = client.header(created_block.hash).unwrap().unwrap();
let (tx, rx) = futures::channel::oneshot::channel();
sink.send(EngineCommand::FinalizeBlock {
sender: Some(tx),
@@ -518,7 +519,7 @@ mod tests {
&sp_core::testing::TaskExecutor::new(),
));
let spawner = sp_core::testing::TaskExecutor::new();
let genesis_hash = client.header(&BlockId::Number(0)).unwrap().unwrap().hash();
let genesis_hash = client.info().genesis_hash;
let pool = Arc::new(BasicPool::with_revalidation_type(
Options::default(),
true.into(),
@@ -582,7 +583,8 @@ mod tests {
assert!(pool.submit_one(&BlockId::Number(1), SOURCE, uxt(Alice, 1)).await.is_ok());
let header = client.header(&BlockId::Number(1)).expect("db error").expect("imported above");
let header = client.header(created_block.hash).expect("db error").expect("imported above");
assert_eq!(header.number, 1);
pool.maintain(sc_transaction_pool_api::ChainEvent::NewBestBlock {
hash: header.hash(),
tree_route: None,
@@ -614,7 +616,7 @@ mod tests {
.is_ok());
let imported = rx2.await.unwrap().unwrap();
// assert that fork block is in the db
assert!(client.header(&BlockId::Hash(imported.hash)).unwrap().is_some())
assert!(client.header(imported.hash).unwrap().is_some())
}
#[tokio::test]
@@ -623,7 +625,7 @@ mod tests {
let (client, select_chain) = builder.build_with_longest_chain();
let client = Arc::new(client);
let spawner = sp_core::testing::TaskExecutor::new();
let genesis_hash = client.header(&BlockId::Number(0)).unwrap().unwrap().hash();
let genesis_hash = client.header(client.info().genesis_hash).unwrap().unwrap().hash();
let pool = Arc::new(BasicPool::with_revalidation_type(
Options::default(),
true.into(),
@@ -665,7 +667,7 @@ mod tests {
let created_block = rx.await.unwrap().unwrap();
// assert that the background task returned the actual header hash
let header = client.header(&BlockId::Number(1)).unwrap().unwrap();
assert_eq!(header.hash(), created_block.hash);
let header = client.header(created_block.hash).unwrap().unwrap();
assert_eq!(header.number, 1);
}
}
@@ -26,10 +26,7 @@ use sp_api::{ProvideRuntimeApi, TransactionFor};
use sp_blockchain::HeaderBackend;
use sp_consensus::{self, BlockOrigin, Environment, Proposer, SelectChain};
use sp_inherents::{CreateInherentDataProviders, InherentDataProvider};
use sp_runtime::{
generic::BlockId,
traits::{Block as BlockT, Header as HeaderT},
};
use sp_runtime::traits::{Block as BlockT, Header as HeaderT};
use std::{collections::HashMap, sync::Arc, time::Duration};
/// max duration for creating a proposal in secs
@@ -102,9 +99,8 @@ pub async fn seal_block<B, BI, SC, C, E, TP, CIDP, P>(
// use the parent_hash supplied via `EngineCommand`
// or fetch the best_block.
let parent = match parent_hash {
Some(hash) => client
.header(BlockId::Hash(hash))?
.ok_or_else(|| Error::BlockNotFound(format!("{}", hash)))?,
Some(hash) =>
client.header(hash)?.ok_or_else(|| Error::BlockNotFound(format!("{}", hash)))?,
None => select_chain.best_chain().await?,
};