Client::info() no longer returns a Result (#2776)

This commit is contained in:
Pierre Krieger
2019-06-04 16:09:46 +02:00
committed by Bastian Köcher
parent 53e8ad8728
commit 5df89a8a6f
33 changed files with 235 additions and 274 deletions
+61 -64
View File
@@ -53,79 +53,76 @@ where C: Components {
let display_notifications = network.status().for_each(move |sync_status| {
if let Ok(info) = client.info() {
let best_number = info.chain.best_number.saturated_into::<u64>();
let best_hash = info.chain.best_hash;
let num_peers = sync_status.num_peers;
let speed = move || speed(best_number, last_number, last_update);
last_update = time::Instant::now();
let (status, target) = match (sync_status.sync.state, sync_status.sync.best_seen_block) {
(SyncState::Idle, _) => ("Idle".into(), "".into()),
(SyncState::Downloading, None) => (format!("Syncing{}", speed()), "".into()),
(SyncState::Downloading, Some(n)) => (format!("Syncing{}", speed()), format!(", target=#{}", n)),
};
last_number = Some(best_number);
let txpool_status = txpool.status();
let finalized_number: u64 = info.chain.finalized_number.saturated_into::<u64>();
let bandwidth_download = network.average_download_per_sec();
let bandwidth_upload = network.average_upload_per_sec();
info!(
target: "substrate",
"{}{} ({} peers), best: #{} ({}), finalized #{} ({}), ⬇ {} ⬆ {}",
Colour::White.bold().paint(&status),
target,
Colour::White.bold().paint(format!("{}", sync_status.num_peers)),
Colour::White.paint(format!("{}", best_number)),
best_hash,
Colour::White.paint(format!("{}", finalized_number)),
info.chain.finalized_hash,
TransferRateFormat(bandwidth_download),
TransferRateFormat(bandwidth_upload),
);
let info = client.info();
let best_number = info.chain.best_number.saturated_into::<u64>();
let best_hash = info.chain.best_hash;
let num_peers = sync_status.num_peers;
let speed = move || speed(best_number, last_number, last_update);
last_update = time::Instant::now();
let (status, target) = match (sync_status.sync.state, sync_status.sync.best_seen_block) {
(SyncState::Idle, _) => ("Idle".into(), "".into()),
(SyncState::Downloading, None) => (format!("Syncing{}", speed()), "".into()),
(SyncState::Downloading, Some(n)) => (format!("Syncing{}", speed()), format!(", target=#{}", n)),
};
last_number = Some(best_number);
let txpool_status = txpool.status();
let finalized_number: u64 = info.chain.finalized_number.saturated_into::<u64>();
let bandwidth_download = network.average_download_per_sec();
let bandwidth_upload = network.average_upload_per_sec();
info!(
target: "substrate",
"{}{} ({} peers), best: #{} ({}), finalized #{} ({}), ⬇ {} ⬆ {}",
Colour::White.bold().paint(&status),
target,
Colour::White.bold().paint(format!("{}", sync_status.num_peers)),
Colour::White.paint(format!("{}", best_number)),
best_hash,
Colour::White.paint(format!("{}", finalized_number)),
info.chain.finalized_hash,
TransferRateFormat(bandwidth_download),
TransferRateFormat(bandwidth_upload),
);
#[allow(deprecated)]
let backend = (*client).backend();
let used_state_cache_size = match backend.used_state_cache_size(){
Some(size) => size,
None => 0,
};
#[allow(deprecated)]
let backend = (*client).backend();
let used_state_cache_size = match backend.used_state_cache_size(){
Some(size) => size,
None => 0,
};
// get cpu usage and memory usage of this process
let (cpu_usage, memory) = if sys.refresh_process(self_pid) {
let proc = sys.get_process(self_pid).expect("Above refresh_process succeeds, this should be Some(), qed");
(proc.cpu_usage(), proc.memory())
} else { (0.0, 0) };
// get cpu usage and memory usage of this process
let (cpu_usage, memory) = if sys.refresh_process(self_pid) {
let proc = sys.get_process(self_pid).expect("Above refresh_process succeeds, this should be Some(), qed");
(proc.cpu_usage(), proc.memory())
} else { (0.0, 0) };
let network_state = network.network_state();
let network_state = network.network_state();
telemetry!(
SUBSTRATE_INFO;
"system.interval";
"network_state" => network_state,
"status" => format!("{}{}", status, target),
"peers" => num_peers,
"height" => best_number,
"best" => ?best_hash,
"txcount" => txpool_status.ready,
"cpu" => cpu_usage,
"memory" => memory,
"finalized_height" => finalized_number,
"finalized_hash" => ?info.chain.finalized_hash,
"bandwidth_download" => bandwidth_download,
"bandwidth_upload" => bandwidth_upload,
"used_state_cache_size" => used_state_cache_size,
);
} else {
warn!("Error getting best block information");
}
telemetry!(
SUBSTRATE_INFO;
"system.interval";
"network_state" => network_state,
"status" => format!("{}{}", status, target),
"peers" => num_peers,
"height" => best_number,
"best" => ?best_hash,
"txcount" => txpool_status.ready,
"cpu" => cpu_usage,
"memory" => memory,
"finalized_height" => finalized_number,
"finalized_hash" => ?info.chain.finalized_hash,
"bandwidth_download" => bandwidth_download,
"bandwidth_upload" => bandwidth_upload,
"used_state_cache_size" => used_state_cache_size,
);
Ok(())
});
let client = service.client();
let mut last = match client.info() {
Ok(info) => Some((info.chain.best_number, info.chain.best_hash)),
Err(e) => { warn!("Error getting best block information: {:?}", e); None }
let mut last = {
let info = client.info();
Some((info.chain.best_number, info.chain.best_hash))
};
let display_block_import = client.import_notification_stream().for_each(move |n| {
+7 -7
View File
@@ -271,15 +271,15 @@ impl<Block: BlockT> client::blockchain::HeaderBackend<Block> for BlockchainDb<Bl
utils::read_header(&*self.db, columns::KEY_LOOKUP, columns::HEADER, id)
}
fn info(&self) -> Result<client::blockchain::Info<Block>, client::error::Error> {
fn info(&self) -> client::blockchain::Info<Block> {
let meta = self.meta.read();
Ok(client::blockchain::Info {
client::blockchain::Info {
best_hash: meta.best_hash,
best_number: meta.best_number,
genesis_hash: meta.genesis_hash,
finalized_hash: meta.finalized_hash,
finalized_number: meta.finalized_number,
})
}
}
fn status(&self, id: BlockId<Block>) -> Result<client::blockchain::BlockStatus, client::error::Error> {
@@ -742,7 +742,7 @@ impl<Block: BlockT<Hash=H256>> Backend<Block> {
}
// insert all other headers + bodies + justifications
let info = self.blockchain.info().unwrap();
let info = self.blockchain.info();
for (number, hash, header) in headers {
let id = BlockId::Hash(hash);
let justification = self.blockchain.justification(id).unwrap();
@@ -1258,8 +1258,8 @@ impl<Block> client::backend::Backend<Block, Blake2Hasher> for Backend<Block> whe
}
fn revert(&self, n: NumberFor<Block>) -> Result<NumberFor<Block>, client::error::Error> {
let mut best = self.blockchain.info()?.best_number;
let finalized = self.blockchain.info()?.finalized_number;
let mut best = self.blockchain.info().best_number;
let finalized = self.blockchain.info().finalized_number;
let revertible = best - finalized;
let n = if revertible < n { revertible } else { n };
@@ -1463,7 +1463,7 @@ mod tests {
};
let backend = Backend::<Block>::from_kvdb(backing, PruningMode::keep_blocks(1), 0, 16777216).unwrap();
assert_eq!(backend.blockchain().info().unwrap().best_number, 9);
assert_eq!(backend.blockchain().info().best_number, 9);
for i in 0..10 {
assert!(backend.blockchain().hash(i).unwrap().is_some())
}
+7 -7
View File
@@ -155,15 +155,15 @@ impl<Block> BlockchainHeaderBackend<Block> for LightStorage<Block>
utils::read_header(&*self.db, columns::KEY_LOOKUP, columns::HEADER, id)
}
fn info(&self) -> ClientResult<BlockchainInfo<Block>> {
fn info(&self) -> BlockchainInfo<Block> {
let meta = self.meta.read();
Ok(BlockchainInfo {
BlockchainInfo {
best_hash: meta.best_hash,
best_number: meta.best_number,
genesis_hash: meta.genesis_hash,
finalized_hash: meta.finalized_hash,
finalized_number: meta.finalized_number,
})
}
}
fn status(&self, id: BlockId<Block>) -> ClientResult<BlockStatus> {
@@ -655,12 +655,12 @@ pub(crate) mod tests {
fn returns_info() {
let db = LightStorage::new_test();
let genesis_hash = insert_block(&db, HashMap::new(), || default_header(&Default::default(), 0));
let info = db.info().unwrap();
let info = db.info();
assert_eq!(info.best_hash, genesis_hash);
assert_eq!(info.best_number, 0);
assert_eq!(info.genesis_hash, genesis_hash);
let best_hash = insert_block(&db, HashMap::new(), || default_header(&genesis_hash, 1));
let info = db.info().unwrap();
let info = db.info();
assert_eq!(info.best_hash, best_hash);
assert_eq!(info.best_number, 1);
assert_eq!(info.genesis_hash, genesis_hash);
@@ -1034,12 +1034,12 @@ pub(crate) mod tests {
fn database_is_reopened() {
let db = LightStorage::new_test();
let hash0 = insert_final_block(&db, HashMap::new(), || default_header(&Default::default(), 0));
assert_eq!(db.info().unwrap().best_hash, hash0);
assert_eq!(db.info().best_hash, hash0);
assert_eq!(db.header(BlockId::Hash(hash0)).unwrap().unwrap().hash(), hash0);
let db = db.db;
let db = LightStorage::from_kvdb(db).unwrap();
assert_eq!(db.info().unwrap().best_hash, hash0);
assert_eq!(db.info().best_hash, hash0);
assert_eq!(db.header(BlockId::Hash::<Block>(hash0)).unwrap().unwrap().hash(), hash0);
}
@@ -44,9 +44,7 @@ where
/// Create a new instance of builder from the given client, building on the
/// latest block.
pub fn new(api: &'a A, inherent_digests: DigestFor<Block>) -> error::Result<Self> {
api.info().and_then(|i|
Self::at_block(&BlockId::Hash(i.best_hash), api, false, inherent_digests)
)
Self::at_block(&BlockId::Hash(api.info().best_hash), api, false, inherent_digests)
}
/// Create a new instance of builder from the given client using a
+1 -1
View File
@@ -30,7 +30,7 @@ pub trait HeaderBackend<Block: BlockT>: Send + Sync {
/// Get block header. Returns `None` if block is not found.
fn header(&self, id: BlockId<Block>) -> Result<Option<Block::Header>>;
/// Get blockchain info.
fn info(&self) -> Result<Info<Block>>;
fn info(&self) -> Info<Block>;
/// Get block status.
fn status(&self, id: BlockId<Block>) -> Result<BlockStatus>;
/// Get block number by hash. Returns `None` if the header is not in the chain.
+29 -32
View File
@@ -497,7 +497,7 @@ impl<B, E, Block, RA> Client<B, E, Block, RA> where
if first > last_num {
return Err(error::Error::ChangesTrieAccessFailed("Invalid changes trie range".into()));
}
let finalized_number = self.backend.blockchain().info()?.finalized_number;
let finalized_number = self.backend.blockchain().info().finalized_number;
let oldest = storage.oldest_changes_trie_block(&config, finalized_number);
let first = ::std::cmp::max(first, oldest);
Ok(Some((first, last)))
@@ -523,7 +523,7 @@ impl<B, E, Block, RA> Client<B, E, Block, RA> where
hash: convert_hash(&last_hash),
number: last_number,
},
self.backend.blockchain().info()?.best_number,
self.backend.blockchain().info().best_number,
&key.0)
.and_then(|r| r.map(|r| r.map(|(block, tx)| (block, tx))).collect::<Result<_, _>>())
.map_err(|err| error::Error::ChangesTrieAccessFailed(err))
@@ -608,7 +608,7 @@ impl<B, E, Block, RA> Client<B, E, Block, RA> where
};
let max_number = ::std::cmp::min(
self.backend.blockchain().info()?.best_number,
self.backend.blockchain().info().best_number,
self.backend.blockchain().expect_block_number_from_id(&BlockId::Hash(max))?,
);
@@ -879,7 +879,7 @@ impl<B, E, Block, RA> Client<B, E, Block, RA> where
}
let (last_best, last_best_number) = {
let info = self.backend.blockchain().info()?;
let info = self.backend.blockchain().info();
(info.best_hash, info.best_number)
};
@@ -1152,7 +1152,7 @@ impl<B, E, Block, RA> Client<B, E, Block, RA> where
justification: Option<Justification>,
notify: bool,
) -> error::Result<()> {
let last_best = self.backend.blockchain().info()?.best_hash;
let last_best = self.backend.blockchain().info().best_hash;
let to_finalize_hash = self.backend.blockchain().expect_block_hash_from_id(&id)?;
self.apply_finality_with_block_hash(operation, to_finalize_hash, justification, last_best, notify)
}
@@ -1165,7 +1165,7 @@ impl<B, E, Block, RA> Client<B, E, Block, RA> where
/// while performing major synchronization work.
pub fn finalize_block(&self, id: BlockId<Block>, justification: Option<Justification>, notify: bool) -> error::Result<()> {
self.lock_import_and_run(|operation| {
let last_best = self.backend.blockchain().info()?.best_hash;
let last_best = self.backend.blockchain().info().best_hash;
let to_finalize_hash = self.backend.blockchain().expect_block_hash_from_id(&id)?;
self.apply_finality_with_block_hash(operation, to_finalize_hash, justification, last_best, notify)
})
@@ -1178,13 +1178,13 @@ impl<B, E, Block, RA> Client<B, E, Block, RA> where
}
/// Get blockchain info.
pub fn info(&self) -> error::Result<ClientInfo<Block>> {
let info = self.backend.blockchain().info().map_err(|e| error::Error::from_blockchain(Box::new(e)))?;
Ok(ClientInfo {
pub fn info(&self) -> ClientInfo<Block> {
let info = self.backend.blockchain().info();
ClientInfo {
chain: info,
best_queued_hash: None,
best_queued_number: None,
})
}
}
/// Get block status.
@@ -1246,7 +1246,7 @@ impl<B, E, Block, RA> Client<B, E, Block, RA> where
}
};
let genesis_hash = self.backend.blockchain().info()?.genesis_hash;
let genesis_hash = self.backend.blockchain().info().genesis_hash;
if genesis_hash == target_hash { return Ok(Vec::new()); }
let mut current_hash = target_hash;
@@ -1269,7 +1269,7 @@ impl<B, E, Block, RA> Client<B, E, Block, RA> where
}
fn changes_trie_config(&self) -> Result<Option<ChangesTrieConfiguration>, Error> {
Ok(self.backend.state_at(BlockId::Number(self.backend.blockchain().info()?.best_number))?
Ok(self.backend.state_at(BlockId::Number(self.backend.blockchain().info().best_number))?
.storage(well_known_keys::CHANGES_TRIE_CONFIG)
.map_err(|e| error::Error::from_state(Box::new(e)))?
.and_then(|c| Decode::decode(&mut &*c)))
@@ -1298,7 +1298,7 @@ impl<B, E, Block, RA> ChainHeaderBackend<Block> for Client<B, E, Block, RA> wher
self.backend.blockchain().header(id)
}
fn info(&self) -> error::Result<blockchain::Info<Block>> {
fn info(&self) -> blockchain::Info<Block> {
self.backend.blockchain().info()
}
@@ -1448,7 +1448,7 @@ impl<B, E, Block, RA> CurrentHeight for Client<B, E, Block, RA> where
{
type BlockNumber = <Block::Header as HeaderT>::Number;
fn current_height(&self) -> Self::BlockNumber {
self.backend.blockchain().info().map(|i| i.best_number).unwrap_or_else(|_| Zero::zero())
self.backend.blockchain().info().best_number
}
}
@@ -1524,10 +1524,7 @@ where
}
fn best_block_header(&self) -> error::Result<<Block as BlockT>::Header> {
let info : ChainInfo<Block> = match self.backend.blockchain().info() {
Ok(i) => i,
Err(e) => return Err(error::Error::from_blockchain(Box::new(e)))
};
let info : ChainInfo<Block> = self.backend.blockchain().info();
Ok(self.backend.blockchain().header(BlockId::Hash(info.best_hash))?
.expect("Best block header must always exist"))
}
@@ -1569,7 +1566,7 @@ where
// we depend on the canonical chain staying the same during this code block.
let _import_lock = self.import_lock.lock();
let info = self.backend.blockchain().info()?;
let info = self.backend.blockchain().info();
let canon_hash = self.backend.blockchain().hash(*target_header.number())?
.ok_or_else(|| error::Error::from(format!("failed to get hash for block number {}", target_header.number())))?;
@@ -1816,14 +1813,14 @@ pub(crate) mod tests {
assert_eq!(
client.runtime_api().balance_of(
&BlockId::Number(client.info().unwrap().chain.best_number),
&BlockId::Number(client.info().chain.best_number),
AccountKeyring::Alice.into()
).unwrap(),
1000
);
assert_eq!(
client.runtime_api().balance_of(
&BlockId::Number(client.info().unwrap().chain.best_number),
&BlockId::Number(client.info().chain.best_number),
AccountKeyring::Ferdie.into()
).unwrap(),
0
@@ -1838,7 +1835,7 @@ pub(crate) mod tests {
client.import(BlockOrigin::Own, builder.bake().unwrap()).unwrap();
assert_eq!(client.info().unwrap().chain.best_number, 1);
assert_eq!(client.info().chain.best_number, 1);
}
#[test]
@@ -1856,18 +1853,18 @@ pub(crate) mod tests {
client.import(BlockOrigin::Own, builder.bake().unwrap()).unwrap();
assert_eq!(client.info().unwrap().chain.best_number, 1);
assert_eq!(client.info().chain.best_number, 1);
assert!(client.state_at(&BlockId::Number(1)).unwrap().pairs() != client.state_at(&BlockId::Number(0)).unwrap().pairs());
assert_eq!(
client.runtime_api().balance_of(
&BlockId::Number(client.info().unwrap().chain.best_number),
&BlockId::Number(client.info().chain.best_number),
AccountKeyring::Alice.into()
).unwrap(),
958
);
assert_eq!(
client.runtime_api().balance_of(
&BlockId::Number(client.info().unwrap().chain.best_number),
&BlockId::Number(client.info().chain.best_number),
AccountKeyring::Ferdie.into()
).unwrap(),
42
@@ -1896,7 +1893,7 @@ pub(crate) mod tests {
client.import(BlockOrigin::Own, builder.bake().unwrap()).unwrap();
assert_eq!(client.info().unwrap().chain.best_number, 1);
assert_eq!(client.info().chain.best_number, 1);
assert!(client.state_at(&BlockId::Number(1)).unwrap().pairs() != client.state_at(&BlockId::Number(0)).unwrap().pairs());
assert_eq!(client.body(&BlockId::Number(1)).unwrap().unwrap().len(), 1)
}
@@ -1908,7 +1905,7 @@ pub(crate) mod tests {
let client = test_client::new();
let genesis_hash = client.info().unwrap().chain.genesis_hash;
let genesis_hash = client.info().chain.genesis_hash;
#[allow(deprecated)]
let longest_chain_select = test_client::client::LongestChain::new(
client.backend().clone(),
@@ -2029,7 +2026,7 @@ pub(crate) mod tests {
let d2 = builder.bake().unwrap();
client.import(BlockOrigin::Own, d2.clone()).unwrap();
let genesis_hash = client.info().unwrap().chain.genesis_hash;
let genesis_hash = client.info().chain.genesis_hash;
let uncles1 = client.uncles(a4.hash(), 10).unwrap();
assert_eq!(vec![b2.hash(), d2.hash()], uncles1);
@@ -2065,7 +2062,7 @@ pub(crate) mod tests {
let a2 = client.new_block(Default::default()).unwrap().bake().unwrap();
client.import(BlockOrigin::Own, a2.clone()).unwrap();
let genesis_hash = client.info().unwrap().chain.genesis_hash;
let genesis_hash = client.info().chain.genesis_hash;
#[allow(deprecated)]
let longest_chain_select = test_client::client::LongestChain::new(
Arc::new(client.backend().as_in_memory()),
@@ -2152,9 +2149,9 @@ pub(crate) mod tests {
let d2 = builder.bake().unwrap();
client.import(BlockOrigin::Own, d2.clone()).unwrap();
assert_eq!(client.info().unwrap().chain.best_hash, a5.hash());
assert_eq!(client.info().chain.best_hash, a5.hash());
let genesis_hash = client.info().unwrap().chain.genesis_hash;
let genesis_hash = client.info().chain.genesis_hash;
#[allow(deprecated)]
let longest_chain_select = test_client::client::LongestChain::new(
Arc::new(client.backend().as_in_memory()),
@@ -2385,7 +2382,7 @@ pub(crate) mod tests {
let a2 = client.new_block(Default::default()).unwrap().bake().unwrap();
client.import(BlockOrigin::Own, a2.clone()).unwrap();
let genesis_hash = client.info().unwrap().chain.genesis_hash;
let genesis_hash = client.info().chain.genesis_hash;
#[allow(deprecated)]
let longest_chain_select = test_client::client::LongestChain::new(
Arc::new(client.backend().as_in_memory()),
+3 -3
View File
@@ -297,15 +297,15 @@ impl<Block: BlockT> HeaderBackend<Block> for Blockchain<Block> {
}))
}
fn info(&self) -> error::Result<blockchain::Info<Block>> {
fn info(&self) -> blockchain::Info<Block> {
let storage = self.storage.read();
Ok(blockchain::Info {
blockchain::Info {
best_hash: storage.best_hash,
best_number: storage.best_number,
genesis_hash: storage.genesis_hash,
finalized_hash: storage.finalized_hash,
finalized_number: storage.finalized_number,
})
}
}
fn status(&self, id: BlockId<Block>) -> error::Result<BlockStatus> {
@@ -134,7 +134,7 @@ impl<S, F, Block> BlockchainHeaderBackend<Block> for Blockchain<S, F> where Bloc
}
}
fn info(&self) -> ClientResult<BlockchainInfo<Block>> {
fn info(&self) -> BlockchainInfo<Block> {
self.storage.info()
}
@@ -223,8 +223,8 @@ pub mod tests {
Err(ClientError::Backend("Test error".into()))
}
fn info(&self) -> ClientResult<Info<Block>> {
Err(ClientError::Backend("Test error".into()))
fn info(&self) -> Info<Block> {
panic!("Test error")
}
fn status(&self, _id: BlockId<Block>) -> ClientResult<BlockStatus> {
+4 -4
View File
@@ -668,8 +668,8 @@ pub mod tests {
test_client::LocalExecutor::new(None)
);
let local_checker = &local_checker as &FetchChecker<Block>;
let max = remote_client.info().unwrap().chain.best_number;
let max_hash = remote_client.info().unwrap().chain.best_hash;
let max = remote_client.info().chain.best_number;
let max_hash = remote_client.info().chain.best_hash;
for (index, (begin, end, key, expected_result)) in test_cases.into_iter().enumerate() {
let begin_hash = remote_client.block_hash(begin).unwrap().unwrap();
@@ -764,8 +764,8 @@ pub mod tests {
test_client::LocalExecutor::new(None)
);
let local_checker = &local_checker as &FetchChecker<Block>;
let max = remote_client.info().unwrap().chain.best_number;
let max_hash = remote_client.info().unwrap().chain.best_hash;
let max = remote_client.info().chain.best_number;
let max_hash = remote_client.info().chain.best_hash;
let (begin, end, key, _) = test_cases[0].clone();
let begin_hash = remote_client.block_hash(begin).unwrap().unwrap();
+1 -1
View File
@@ -943,7 +943,7 @@ mod tests {
fn authorities_call_works() {
let client = test_client::new();
assert_eq!(client.info().unwrap().chain.best_number, 0);
assert_eq!(client.info().chain.best_number, 0);
assert_eq!(authorities(&client, &BlockId::Number(0)).unwrap(), vec![
Keyring::Alice.into(),
Keyring::Bob.into(),
+1 -1
View File
@@ -1058,7 +1058,7 @@ mod tests {
drop(env_logger::try_init());
let client = test_client::new();
assert_eq!(client.info().unwrap().chain.best_number, 0);
assert_eq!(client.info().chain.best_number, 0);
assert_eq!(authorities(&client, &BlockId::Number(0)).unwrap(), vec![
Keyring::Alice.into(),
Keyring::Bob.into(),
@@ -662,7 +662,7 @@ where
#[allow(deprecated)]
let blockchain = self.inner.backend().blockchain();
let status = blockchain.info()?;
let status = blockchain.info();
if number <= status.finalized_number && blockchain.hash(number)? == Some(hash) {
// This can happen after a forced change (triggered by the finality tracker when finality is stalled), since
// the voter will be restarted at the median last finalized block, which can be lower than the local best
@@ -812,7 +812,7 @@ pub(crate) fn finalize_block<B, Block: BlockT<Hash=H256>, E, RA>(
// finalization to remote nodes
if !justification_required {
if let Some(justification_period) = justification_period {
let last_finalized_number = client.info()?.chain.finalized_number;
let last_finalized_number = client.info().chain.finalized_number;
justification_required =
(!last_finalized_number.is_zero() || number - last_finalized_number == justification_period) &&
(last_finalized_number / justification_period != number / justification_period);
@@ -268,7 +268,7 @@ pub(crate) fn prove_finality<Block: BlockT<Hash=H256>, B: BlockchainBackend<Bloc
let begin_number = blockchain.expect_block_number_from_id(&begin_id)?;
// early-return if we sure that there are no blocks finalized AFTER begin block
let info = blockchain.info()?;
let info = blockchain.info();
if info.finalized_number <= begin_number {
trace!(
target: "finality",
@@ -77,10 +77,7 @@ impl<B, E, Block: BlockT<Hash=H256>, RA, PRA, SC> JustificationImport<Block>
type Error = ConsensusError;
fn on_start(&self, link: &::consensus_common::import_queue::Link<Block>) {
let chain_info = match self.inner.info() {
Ok(info) => info.chain,
_ => return,
};
let chain_info = self.inner.info().chain;
// request justifications for all pending changes for which change blocks have already been imported
let authorities = self.authority_set.inner().read();
@@ -320,7 +317,6 @@ where
#[allow(deprecated)]
let best_finalized_number = self.inner.backend().blockchain().info()
.map_err(|e| ConsensusError::ClientImport(e.to_string()))?
.finalized_number;
let canon_number = best_finalized_number.min(median_last_finalized_number);
+11 -16
View File
@@ -316,7 +316,7 @@ where
{
use runtime_primitives::traits::Zero;
let chain_info = client.info()?;
let chain_info = client.info();
let genesis_hash = chain_info.chain.genesis_hash;
let persistent_data = aux_schema::load_persistent(
@@ -431,15 +431,13 @@ fn register_finality_tracker_inherent_data_provider<B, E, Block: BlockT<Hash=H25
inherent_data_providers
.register_provider(srml_finality_tracker::InherentDataProvider::new(move || {
#[allow(deprecated)]
match client.backend().blockchain().info() {
Err(e) => Err(std::borrow::Cow::Owned(e.to_string())),
Ok(info) => {
telemetry!(CONSENSUS_INFO; "afg.finalized";
"finalized_number" => ?info.finalized_number,
"finalized_hash" => ?info.finalized_hash,
);
Ok(info.finalized_number)
},
{
let info = client.backend().blockchain().info();
telemetry!(CONSENSUS_INFO; "afg.finalized";
"finalized_number" => ?info.finalized_number,
"finalized_hash" => ?info.finalized_hash,
);
Ok(info.finalized_number)
}
}))
.map_err(|err| consensus_common::Error::InherentData(err.into()))
@@ -579,10 +577,7 @@ pub fn run_grandpa_voter<B, E, Block: BlockT<Hash=H256>, N, RA, SC, X>(
let mut maybe_voter = match &*env.voter_set_state.read() {
VoterSetState::Live { completed_rounds, .. } => {
let chain_info = match client.info() {
Ok(i) => i,
Err(e) => return future::Either::B(future::err(Error::Client(e))),
};
let chain_info = client.info();
let last_finalized = (
chain_info.chain.finalized_hash,
@@ -691,7 +686,7 @@ pub fn run_grandpa_voter<B, E, Block: BlockT<Hash=H256>, N, RA, SC, X>(
}
};
future::Either::A(poll_voter.select2(voter_commands_rx).then(move |res| match res {
poll_voter.select2(voter_commands_rx).then(move |res| match res {
Ok(future::Either::A(((), _))) => {
// voters don't conclude naturally; this could reasonably be an error.
Ok(FutureLoop::Break(()))
@@ -716,7 +711,7 @@ pub fn run_grandpa_voter<B, E, Block: BlockT<Hash=H256>, N, RA, SC, X>(
// some command issued internally.
handle_voter_command(command, voter_commands_rx)
},
}))
})
});
let voter_work = voter_work
@@ -63,7 +63,7 @@ pub fn light_block_import<B, E, Block: BlockT<Hash=H256>, RA, PRA>(
PRA: ProvideRuntimeApi,
PRA::Api: GrandpaApi<Block>,
{
let info = client.info()?;
let info = client.info();
#[allow(deprecated)]
let import_data = load_aux_import_data(info.chain.finalized_hash, &**client.backend(), api)?;
Ok(GrandpaLightBlockImport {
@@ -145,10 +145,7 @@ impl<B, E, Block: BlockT<Hash=H256>, RA> FinalityProofImport<Block>
type Error = ConsensusError;
fn on_start(&self, link: &::consensus_common::import_queue::Link<Block>) {
let chain_info = match self.client.info() {
Ok(info) => info.chain,
_ => return,
};
let chain_info = self.client.info().chain;
let data = self.data.read();
for (pending_number, pending_hash) in data.consensus_changes.pending_changes() {
@@ -620,7 +617,7 @@ pub mod tests {
origin: BlockOrigin::Own,
header: Header {
number: 1,
parent_hash: client.info().unwrap().chain.best_hash,
parent_hash: client.info().chain.best_hash,
state_root: Default::default(),
digest: Default::default(),
extrinsics_root: Default::default(),
@@ -31,7 +31,7 @@ use substrate_primitives::{ed25519::Public as AuthorityId, H256, Blake2Hasher};
use crate::{
AuthoritySignature, global_communication, CommandOrError, Config, environment,
Error, LinkHalf, Network, aux_schema::PersistentData, VoterCommand, VoterSetState,
LinkHalf, Network, aux_schema::PersistentData, VoterCommand, VoterSetState,
};
use crate::authorities::SharedAuthoritySet;
use crate::communication::NetworkBridge;
@@ -191,12 +191,7 @@ pub fn run_grandpa_observer<B, E, Block: BlockT<Hash=H256>, N, RA, SC>(
&network,
);
let chain_info = match client.info() {
Ok(i) => i,
Err(e) => return future::Either::B(future::err(Error::Client(e))),
};
let last_finalized_number = chain_info.chain.finalized_number;
let last_finalized_number = client.info().chain.finalized_number;
// create observer for the current set
let observer = grandpa_observer(
@@ -250,7 +245,7 @@ pub fn run_grandpa_observer<B, E, Block: BlockT<Hash=H256>, N, RA, SC>(
};
// run observer and listen to commands (switch authorities or pause)
future::Either::A(observer.select2(voter_commands_rx).then(move |res| match res {
observer.select2(voter_commands_rx).then(move |res| match res {
Ok(future::Either::A((_, _))) => {
// observer commit stream doesn't conclude naturally; this could reasonably be an error.
Ok(FutureLoop::Break(()))
@@ -275,7 +270,7 @@ pub fn run_grandpa_observer<B, E, Block: BlockT<Hash=H256>, N, RA, SC>(
// some command issued internally
handle_voter_command(command, voter_commands_rx)
},
}))
})
});
let observer_work = observer_work
+13 -13
View File
@@ -561,7 +561,7 @@ fn finalize_3_voters_no_observers() {
net.sync();
for i in 0..3 {
assert_eq!(net.peer(i).client().info().unwrap().chain.best_number, 20,
assert_eq!(net.peer(i).client().info().chain.best_number, 20,
"Peer #{} failed to sync", i);
}
@@ -673,7 +673,7 @@ fn transition_3_voters_twice_1_full_observer() {
for (i, peer) in net.lock().peers().iter().enumerate() {
let full_client = peer.client().as_full().expect("only full clients are used in test");
assert_eq!(full_client.info().unwrap().chain.best_number, 1,
assert_eq!(full_client.info().chain.best_number, 1,
"Peer #{} failed to sync", i);
let set: AuthoritySet<Hash, BlockNumber> = crate::aux_schema::load_authorities(
@@ -895,7 +895,7 @@ fn sync_justifications_on_change_blocks() {
net.sync();
for i in 0..4 {
assert_eq!(net.peer(i).client().info().unwrap().chain.best_number, 25,
assert_eq!(net.peer(i).client().info().chain.best_number, 25,
"Peer #{} failed to sync", i);
}
@@ -966,7 +966,7 @@ fn finalizes_multiple_pending_changes_in_order() {
// all peers imported both change blocks
for i in 0..6 {
assert_eq!(net.peer(i).client().info().unwrap().chain.best_number, 30,
assert_eq!(net.peer(i).client().info().chain.best_number, 30,
"Peer #{} failed to sync", i);
}
@@ -986,7 +986,7 @@ fn doesnt_vote_on_the_tip_of_the_chain() {
net.sync();
for i in 0..3 {
assert_eq!(net.peer(i).client().info().unwrap().chain.best_number, 100,
assert_eq!(net.peer(i).client().info().chain.best_number, 100,
"Peer #{} failed to sync", i);
}
@@ -1016,7 +1016,7 @@ fn force_change_to_new_set() {
{
// add a forced transition at block 12.
let parent_hash = net.lock().peer(0).client().info().unwrap().chain.best_hash;
let parent_hash = net.lock().peer(0).client().info().chain.best_hash;
forced_transitions.lock().insert(parent_hash, (0, ScheduledChange {
next_authorities: voters.clone(),
delay: 10,
@@ -1033,7 +1033,7 @@ fn force_change_to_new_set() {
net.lock().sync();
for (i, peer) in net.lock().peers().iter().enumerate() {
assert_eq!(peer.client().info().unwrap().chain.best_number, 26,
assert_eq!(peer.client().info().chain.best_number, 26,
"Peer #{} failed to sync", i);
let full_client = peer.client().as_full().expect("only full clients are used in test");
@@ -1172,7 +1172,7 @@ fn voter_persists_its_votes() {
net.peer(0).push_blocks(20, false);
net.sync();
assert_eq!(net.peer(0).client().info().unwrap().chain.best_number, 20,
assert_eq!(net.peer(0).client().info().chain.best_number, 20,
"Peer #{} failed to sync", 0);
let mut runtime = current_thread::Runtime::new().unwrap();
@@ -1289,7 +1289,7 @@ fn voter_persists_its_votes() {
net.lock().peer(0).push_blocks(20, false);
net.lock().sync();
assert_eq!(net.lock().peer(0).client().info().unwrap().chain.best_number, 40,
assert_eq!(net.lock().peer(0).client().info().chain.best_number, 40,
"Peer #{} failed to sync", 0);
#[allow(deprecated)]
@@ -1366,7 +1366,7 @@ fn finalize_3_voters_1_light_observer() {
net.sync();
for i in 0..4 {
assert_eq!(net.peer(i).client().info().unwrap().chain.best_number, 20,
assert_eq!(net.peer(i).client().info().chain.best_number, 20,
"Peer #{} failed to sync", i);
}
@@ -1412,7 +1412,7 @@ fn finality_proof_is_fetched_by_light_client_when_consensus_data_changes() {
net.lock().sync_without_disconnects();
// check that the block#1 is finalized on light client
while net.lock().peer(1).client().info().unwrap().chain.finalized_number != 1 {
while net.lock().peer(1).client().info().chain.finalized_number != 1 {
net.lock().tick_peer(1);
net.lock().sync_without_disconnects();
}
@@ -1455,7 +1455,7 @@ fn empty_finality_proof_is_returned_to_light_client_when_authority_set_is_differ
// add a forced transition at block 5.
if FORCE_CHANGE {
let parent_hash = net.lock().peer(0).client().info().unwrap().chain.best_hash;
let parent_hash = net.lock().peer(0).client().info().chain.best_hash;
forced_transitions.lock().insert(parent_hash, (0, ScheduledChange {
next_authorities: voters.clone(),
delay: 3,
@@ -1482,7 +1482,7 @@ fn empty_finality_proof_is_returned_to_light_client_when_authority_set_is_differ
// check block, finalized on light client
assert_eq!(
runner_net.lock().peer(3).client().info().unwrap().chain.finalized_number,
runner_net.lock().peer(3).client().info().chain.finalized_number,
if FORCE_CHANGE { 0 } else { 10 },
);
}
+2 -2
View File
@@ -28,7 +28,7 @@ use primitives::{H256, Blake2Hasher, storage::StorageKey};
/// Local client abstraction for the network.
pub trait Client<Block: BlockT>: Send + Sync {
/// Get blockchain info.
fn info(&self) -> Result<ClientInfo<Block>, Error>;
fn info(&self) -> ClientInfo<Block>;
/// Get block status.
fn block_status(&self, id: &BlockId<Block>) -> Result<BlockStatus, Error>;
@@ -81,7 +81,7 @@ impl<B, E, Block, RA> Client<Block> for SubstrateClient<B, E, Block, RA> where
Block: BlockT<Hash=H256>,
RA: Send + Sync
{
fn info(&self) -> Result<ClientInfo<Block>, Error> {
fn info(&self) -> ClientInfo<Block> {
(self as &SubstrateClient<B, E, Block, RA>).info()
}
+14 -15
View File
@@ -399,7 +399,7 @@ impl<B: BlockT, S: NetworkSpecialization<B>, H: ExHashT> Protocol<B, S, H> {
checker: Arc<dyn FetchChecker<B>>,
specialization: S,
) -> error::Result<Protocol<B, S, H>> {
let info = chain.info()?;
let info = chain.info();
let sync = ChainSync::new(config.roles, &info);
Ok(Protocol {
tick_timeout: tokio_timer::Interval::new_interval(TICK_TIMEOUT),
@@ -861,8 +861,7 @@ impl<B: BlockT, S: NetworkSpecialization<B>, H: ExHashT> Protocol<B, S, H> {
.context_data
.chain
.info()
.ok()
.and_then(|info| info.best_queued_number)
.best_queued_number
.unwrap_or_else(|| Zero::zero());
let blocks_difference = self_best_block
.checked_sub(&status.best_number)
@@ -1008,18 +1007,18 @@ impl<B: BlockT, S: NetworkSpecialization<B>, H: ExHashT> Protocol<B, S, H> {
/// Send Status message
fn send_status(&mut self, network_out: &mut dyn NetworkOut<B>, who: PeerId) {
if let Ok(info) = self.context_data.chain.info() {
let status = message::generic::Status {
version: CURRENT_VERSION,
min_supported_version: MIN_VERSION,
genesis_hash: info.chain.genesis_hash,
roles: self.config.roles.into(),
best_number: info.chain.best_number,
best_hash: info.chain.best_hash,
chain_status: self.specialization.status(),
};
self.send_message(network_out, who, GenericMessage::Status(status))
}
let info = self.context_data.chain.info();
let status = message::generic::Status {
version: CURRENT_VERSION,
min_supported_version: MIN_VERSION,
genesis_hash: info.chain.genesis_hash,
roles: self.config.roles.into(),
best_number: info.chain.best_number,
best_hash: info.chain.best_hash,
chain_status: self.specialization.status(),
};
self.send_message(network_out, who, GenericMessage::Status(status))
}
fn on_block_announce(
+4 -12
View File
@@ -829,18 +829,10 @@ impl<B: BlockT> ChainSync<B> {
self.queue_blocks.clear();
self.best_importing_number = Zero::zero();
self.blocks.clear();
match protocol.client().info() {
Ok(info) => {
self.best_queued_hash = info.best_queued_hash.unwrap_or(info.chain.best_hash);
self.best_queued_number = info.best_queued_number.unwrap_or(info.chain.best_number);
debug!(target:"sync", "Restarted with {} ({})", self.best_queued_number, self.best_queued_hash);
},
Err(e) => {
debug!(target:"sync", "Error reading blockchain: {:?}", e);
self.best_queued_hash = self.genesis_hash;
self.best_queued_number = Zero::zero();
}
}
let info = protocol.client().info();
self.best_queued_hash = info.best_queued_hash.unwrap_or(info.chain.best_hash);
self.best_queued_number = info.best_queued_number.unwrap_or(info.chain.best_number);
debug!(target:"sync", "Restarted with {} ({})", self.best_queued_number, self.best_queued_hash);
let ids: Vec<PeerId> = self.peers.drain().map(|(id, _)| id).collect();
for id in ids {
self.new_peer(protocol, id);
+6 -6
View File
@@ -163,7 +163,7 @@ impl PeersClient {
}
}
pub fn info(&self) -> ClientResult<ClientInfo<Block>> {
pub fn info(&self) -> ClientInfo<Block> {
match *self {
PeersClient::Full(ref client) => client.info(),
PeersClient::Light(ref client) => client.info(),
@@ -465,7 +465,7 @@ impl<D, S: NetworkSpecialization<Block>> Peer<D, S> {
/// Called after blockchain has been populated to updated current state.
fn start(&self) {
// Update the sync state to the latest chain state.
let info = self.client.info().expect("In-mem client does not fail");
let info = self.client.info();
let header = self
.client
.header(&BlockId::Hash(info.chain.best_hash))
@@ -538,7 +538,7 @@ impl<D, S: NetworkSpecialization<Block>> Peer<D, S> {
/// Send block import notifications.
fn send_import_notifications(&self) {
let info = self.client.info().expect("In-mem client does not fail");
let info = self.client.info();
let mut best_hash = self.best_hash.lock();
match *best_hash {
@@ -554,7 +554,7 @@ impl<D, S: NetworkSpecialization<Block>> Peer<D, S> {
/// Send block finalization notifications.
fn send_finality_notifications(&self) {
let info = self.client.info().expect("In-mem client does not fail");
let info = self.client.info();
let mut finalized_hash = self.finalized_hash.lock();
match *finalized_hash {
@@ -625,7 +625,7 @@ impl<D, S: NetworkSpecialization<Block>> Peer<D, S> {
pub fn generate_blocks<F>(&self, count: usize, origin: BlockOrigin, edit_block: F) -> H256
where F: FnMut(BlockBuilder<Block, PeersFullClient>) -> Block
{
let best_hash = self.client.info().unwrap().chain.best_hash;
let best_hash = self.client.info().chain.best_hash;
self.generate_blocks_at(BlockId::Hash(best_hash), count, origin, edit_block)
}
@@ -674,7 +674,7 @@ impl<D, S: NetworkSpecialization<Block>> Peer<D, S> {
/// Push blocks to the peer (simplified: with or without a TX)
pub fn push_blocks(&self, count: usize, with_tx: bool) -> H256 {
let best_hash = self.client.info().unwrap().chain.best_hash;
let best_hash = self.client.info().chain.best_hash;
self.push_blocks_at(BlockId::Hash(best_hash), count, with_tx)
}
+12 -12
View File
@@ -320,8 +320,8 @@ fn own_blocks_are_announced() {
net.peer(0).on_block_imported(header.hash(), &header);
net.sync();
assert_eq!(net.peer(0).client.as_in_memory_backend().blockchain().info().unwrap().best_number, 1);
assert_eq!(net.peer(1).client.as_in_memory_backend().blockchain().info().unwrap().best_number, 1);
assert_eq!(net.peer(0).client.as_in_memory_backend().blockchain().info().best_number, 1);
assert_eq!(net.peer(1).client.as_in_memory_backend().blockchain().info().best_number, 1);
let peer0_chain = net.peer(0).client.as_in_memory_backend().blockchain().clone();
assert!(net.peer(1).client.as_in_memory_backend().blockchain().canon_equals_to(&peer0_chain));
assert!(net.peer(2).client.as_in_memory_backend().blockchain().canon_equals_to(&peer0_chain));
@@ -356,9 +356,9 @@ fn blocks_are_not_announced_by_light_nodes() {
// peer 0 has the best chain
// peer 1 has the best chain
// peer 2 has genesis-chain only
assert_eq!(net.peer(0).client.info().unwrap().chain.best_number, 1);
assert_eq!(net.peer(1).client.info().unwrap().chain.best_number, 1);
assert_eq!(net.peer(2).client.info().unwrap().chain.best_number, 0);
assert_eq!(net.peer(0).client.info().chain.best_number, 1);
assert_eq!(net.peer(1).client.info().chain.best_number, 1);
assert_eq!(net.peer(2).client.info().chain.best_number, 0);
}
#[test]
@@ -371,13 +371,13 @@ fn can_sync_small_non_best_forks() {
// small fork + reorg on peer 1.
net.peer(0).push_blocks_at(BlockId::Number(30), 2, true);
let small_hash = net.peer(0).client().info().unwrap().chain.best_hash;
let small_hash = net.peer(0).client().info().chain.best_hash;
net.peer(0).push_blocks_at(BlockId::Number(30), 10, false);
assert_eq!(net.peer(0).client().info().unwrap().chain.best_number, 40);
assert_eq!(net.peer(0).client().info().chain.best_number, 40);
// peer 1 only ever had the long fork.
net.peer(1).push_blocks(10, false);
assert_eq!(net.peer(1).client().info().unwrap().chain.best_number, 40);
assert_eq!(net.peer(1).client().info().chain.best_number, 40);
assert!(net.peer(0).client().header(&BlockId::Hash(small_hash)).unwrap().is_some());
assert!(net.peer(1).client().header(&BlockId::Hash(small_hash)).unwrap().is_none());
@@ -386,7 +386,7 @@ fn can_sync_small_non_best_forks() {
// synchronization: 0 synced to longer chain and 1 didn't sync to small chain.
assert_eq!(net.peer(0).client().info().unwrap().chain.best_number, 40);
assert_eq!(net.peer(0).client().info().chain.best_number, 40);
assert!(net.peer(0).client().header(&BlockId::Hash(small_hash)).unwrap().is_some());
assert!(!net.peer(1).client().header(&BlockId::Hash(small_hash)).unwrap().is_some());
@@ -416,8 +416,8 @@ fn can_not_sync_from_light_peer() {
net.sync();
// ensure #0 && #1 have the same best block
let full0_info = net.peer(0).client.info().unwrap().chain;
let light_info = net.peer(1).client.info().unwrap().chain;
let full0_info = net.peer(0).client.info().chain;
let light_info = net.peer(1).client.info().chain;
assert_eq!(full0_info.best_number, 1);
assert_eq!(light_info.best_number, 1);
assert_eq!(light_info.best_hash, full0_info.best_hash);
@@ -430,7 +430,7 @@ fn can_not_sync_from_light_peer() {
net.sync_with(true, Some(vec![0].into_iter().collect()));
// ensure that the #2 has failed to sync block #1
assert_eq!(net.peer(2).client.info().unwrap().chain.best_number, 0);
assert_eq!(net.peer(2).client.info().chain.best_number, 0);
// and that the #1 is still connected to #2
// (because #2 has not tried to fetch block data from the #1 light node)
assert_eq!(net.peer(1).protocol_status().num_peers, 2);
+2 -2
View File
@@ -110,7 +110,7 @@ impl<B, E, P, RA> AuthorApi<ExHash<P>, BlockHash<P>> for Author<B, E, P, RA> whe
fn submit_extrinsic(&self, ext: Bytes) -> Result<ExHash<P>> {
let xt = Decode::decode(&mut &ext[..]).ok_or(error::Error::BadFormat)?;
let best_block_hash = self.client.info()?.chain.best_hash;
let best_block_hash = self.client.info().chain.best_hash;
self.pool
.submit_one(&generic::BlockId::hash(best_block_hash), xt)
.map_err(|e| e.into_pool_error()
@@ -144,7 +144,7 @@ impl<B, E, P, RA> AuthorApi<ExHash<P>, BlockHash<P>> for Author<B, E, P, RA> whe
fn watch_extrinsic(&self, _metadata: Self::Metadata, subscriber: Subscriber<Status<ExHash<P>, BlockHash<P>>>, xt: Bytes) {
let submit = || -> Result<_> {
let best_block_hash = self.client.info()?.chain.best_hash;
let best_block_hash = self.client.info().chain.best_hash;
let dxt = <<P as PoolChainApi>::Block as traits::Block>::Extrinsic::decode(&mut &xt[..])
.ok_or(error::Error::BadFormat)?;
self.pool
+4 -4
View File
@@ -124,7 +124,7 @@ impl<B, E, Block, RA> Chain<B, E, Block, RA> where
{
fn unwrap_or_best(&self, hash: Option<Block::Hash>) -> Result<Block::Hash> {
Ok(match hash.into() {
None => self.client.info()?.chain.best_hash,
None => self.client.info().chain.best_hash,
Some(hash) => hash,
})
}
@@ -188,13 +188,13 @@ impl<B, E, Block, RA> ChainApi<NumberFor<Block>, Block::Hash, Block::Header, Sig
fn block_hash(&self, number: Option<number::NumberOrHex<NumberFor<Block>>>) -> Result<Option<Block::Hash>> {
Ok(match number {
None => Some(self.client.info()?.chain.best_hash),
None => Some(self.client.info().chain.best_hash),
Some(num_or_hex) => self.client.header(&BlockId::number(num_or_hex.to_number()?))?.map(|h| h.hash()),
})
}
fn finalized_head(&self) -> Result<Block::Hash> {
Ok(self.client.info()?.chain.finalized_hash)
Ok(self.client.info().chain.finalized_hash)
}
fn subscribe_new_head(&self, _metadata: Self::Metadata, subscriber: Subscriber<Block::Header>) {
@@ -214,7 +214,7 @@ impl<B, E, Block, RA> ChainApi<NumberFor<Block>, Block::Hash, Block::Header, Sig
fn subscribe_finalized_heads(&self, _meta: Self::Metadata, subscriber: Subscriber<Block::Header>) {
self.subscribe_headers(
subscriber,
|| Ok(Some(self.client.info()?.chain.finalized_hash)),
|| Ok(Some(self.client.info().chain.finalized_hash)),
|| self.client.finality_notification_stream()
.map(|notification| notification.header),
)
+5 -5
View File
@@ -322,7 +322,7 @@ impl<B, E, Block, RA> State<B, E, Block, RA> where
E: CallExecutor<Block, Blake2Hasher>,
{
fn unwrap_or_best(&self, hash: Option<Block::Hash>) -> Result<Block::Hash> {
crate::helpers::unwrap_or_else(|| Ok(self.client.info()?.chain.best_hash), hash)
crate::helpers::unwrap_or_else(|| Ok(self.client.info().chain.best_hash), hash)
}
}
@@ -449,7 +449,7 @@ impl<B, E, Block, RA> StateApi<Block::Hash> for State<B, E, Block, RA> where
// initial values
let initial = stream::iter_result(keys
.map(|keys| {
let block = self.client.info().map(|info| info.chain.best_hash).unwrap_or_default();
let block = self.client.info().chain.best_hash;
let changes = keys
.into_iter()
.map(|key| self.storage(key.clone(), Some(block.clone()).into())
@@ -506,9 +506,9 @@ impl<B, E, Block, RA> StateApi<Block::Hash> for State<B, E, Block, RA> where
let stream = stream
.map_err(|e| warn!("Error creating storage notification stream: {:?}", e))
.filter_map(move |_| {
let version = client.info().and_then(|info| {
client.runtime_version_at(&BlockId::hash(info.chain.best_hash))
})
let info = client.info();
let version = client
.runtime_version_at(&BlockId::hash(info.chain.best_hash))
.map_err(error::Error::from)
.map_err(Into::into);
if previous_version != version {
+3 -3
View File
@@ -52,7 +52,7 @@ pub fn export_blocks<F, E, W>(
let last = match to {
Some(v) if v.is_zero() => One::one(),
Some(v) => v,
None => client.info()?.chain.best_number,
None => client.info().chain.best_number,
};
if last < block {
@@ -186,7 +186,7 @@ pub fn import_blocks<F, E, R>(
blocks_imported += 1;
}
info!("Imported {} blocks. Best: #{}", block_count, client.info()?.chain.best_number);
info!("Imported {} blocks. Best: #{}", block_count, client.info().chain.best_number);
Ok(())
}
@@ -200,7 +200,7 @@ pub fn revert_chain<F>(
{
let client = new_client::<F>(&config)?;
let reverted = client.revert(blocks)?;
let info = client.info()?.chain;
let info = client.info().chain;
if reverted.is_zero() {
info!("There aren't any non-finalized blocks to revert.");
+2 -7
View File
@@ -156,7 +156,7 @@ impl<Components: components::Components> Service<Components> {
select_chain.clone(),
)?);
let finality_proof_provider = Components::build_finality_proof_provider(client.clone())?;
let chain_info = client.info()?.chain;
let chain_info = client.info().chain;
let version = config.full_version();
info!("Highest known block at #{}", chain_info.best_number);
@@ -479,12 +479,7 @@ pub struct TransactionPoolAdapter<C: Components> {
impl<C: Components> TransactionPoolAdapter<C> {
fn best_block_id(&self) -> Option<BlockId<ComponentBlock<C>>> {
self.client.info()
.map(|info| BlockId::hash(info.chain.best_hash))
.map_err(|e| {
debug!("Error getting best block: {:?}", e);
})
.ok()
Some(BlockId::hash(self.client.info().chain.best_hash))
}
}
+4 -4
View File
@@ -250,11 +250,11 @@ where
service.network().add_reserved_peer(first_address.to_string()).expect("Error adding reserved peer");
}
network.run_until_all_full(|_index, service|
service.client().info().unwrap().chain.best_number == NUM_BLOCKS.into()
service.client().info().chain.best_number == NUM_BLOCKS.into()
);
info!("Checking extrinsic propagation");
let first_service = network.full_nodes[0].1.clone();
let best_block = BlockId::number(first_service.client().info().unwrap().chain.best_number);
let best_block = BlockId::number(first_service.client().info().chain.best_number);
first_service.transaction_pool().submit_one(&best_block, extrinsic_factory(&first_service)).unwrap();
network.run_until_all_full(|_index, service|
service.transaction_pool().ready().count() == 1
@@ -278,7 +278,7 @@ pub fn consensus<F>(spec: FactoryChainSpec<F>, authorities: Vec<String>)
service.network().add_reserved_peer(first_address.to_string()).expect("Error adding reserved peer");
}
network.run_until_all_full(|_index, service| {
service.client().info().unwrap().chain.finalized_number >= (NUM_BLOCKS / 2).into()
service.client().info().chain.finalized_number >= (NUM_BLOCKS / 2).into()
});
info!("Adding more peers");
network.insert_nodes(&temp, NUM_NODES / 2, 0, vec![]);
@@ -286,6 +286,6 @@ pub fn consensus<F>(spec: FactoryChainSpec<F>, authorities: Vec<String>)
service.network().add_reserved_peer(first_address.to_string()).expect("Error adding reserved peer");
}
network.run_until_all_full(|_index, service|
service.client().info().unwrap().chain.finalized_number >= NUM_BLOCKS.into()
service.client().info().chain.finalized_number >= NUM_BLOCKS.into()
);
}
@@ -23,14 +23,14 @@ fn sr_api_benchmark(c: &mut Criterion) {
c.bench_function("add one with same runtime api", |b| {
let client = test_client::new();
let runtime_api = client.runtime_api();
let block_id = BlockId::Number(client.info().unwrap().chain.best_number);
let block_id = BlockId::Number(client.info().chain.best_number);
b.iter(|| runtime_api.benchmark_add_one(&block_id, &1))
});
c.bench_function("add one with recreating runtime api", |b| {
let client = test_client::new();
let block_id = BlockId::Number(client.info().unwrap().chain.best_number);
let block_id = BlockId::Number(client.info().chain.best_number);
b.iter(|| client.runtime_api().benchmark_add_one(&block_id, &1))
});
@@ -38,7 +38,7 @@ fn sr_api_benchmark(c: &mut Criterion) {
c.bench_function("vector add one with same runtime api", |b| {
let client = test_client::new();
let runtime_api = client.runtime_api();
let block_id = BlockId::Number(client.info().unwrap().chain.best_number);
let block_id = BlockId::Number(client.info().chain.best_number);
let data = vec![0; 1000];
b.iter_with_large_drop(|| runtime_api.benchmark_vector_add_one(&block_id, &data))
@@ -46,7 +46,7 @@ fn sr_api_benchmark(c: &mut Criterion) {
c.bench_function("vector add one with recreating runtime api", |b| {
let client = test_client::new();
let block_id = BlockId::Number(client.info().unwrap().chain.best_number);
let block_id = BlockId::Number(client.info().chain.best_number);
let data = vec![0; 1000];
b.iter_with_large_drop(|| client.runtime_api().benchmark_vector_add_one(&block_id, &data))
@@ -54,13 +54,13 @@ fn sr_api_benchmark(c: &mut Criterion) {
c.bench_function("calling function by function pointer in wasm", |b| {
let client = test_client::new_with_execution_strategy(ExecutionStrategy::AlwaysWasm);
let block_id = BlockId::Number(client.info().unwrap().chain.best_number);
let block_id = BlockId::Number(client.info().chain.best_number);
b.iter(|| client.runtime_api().benchmark_indirect_call(&block_id).unwrap())
});
c.bench_function("calling function in wasm", |b| {
let client = test_client::new_with_execution_strategy(ExecutionStrategy::AlwaysWasm);
let block_id = BlockId::Number(client.info().unwrap().chain.best_number);
let block_id = BlockId::Number(client.info().chain.best_number);
b.iter(|| client.runtime_api().benchmark_direct_call(&block_id).unwrap())
});
}
@@ -34,7 +34,7 @@ use codec::Encode;
fn calling_function_with_strat(strat: ExecutionStrategy) {
let client = test_client::new_with_execution_strategy(strat);
let runtime_api = client.runtime_api();
let block_id = BlockId::Number(client.info().unwrap().chain.best_number);
let block_id = BlockId::Number(client.info().chain.best_number);
assert_eq!(runtime_api.benchmark_add_one(&block_id, &1).unwrap(), 2);
}
@@ -54,7 +54,7 @@ fn calling_wasm_runtime_function() {
fn calling_native_runtime_function_with_non_decodable_parameter() {
let client = test_client::new_with_execution_strategy(ExecutionStrategy::NativeWhenPossible);
let runtime_api = client.runtime_api();
let block_id = BlockId::Number(client.info().unwrap().chain.best_number);
let block_id = BlockId::Number(client.info().chain.best_number);
runtime_api.fail_convert_parameter(&block_id, DecodeFails::new()).unwrap();
}
@@ -63,7 +63,7 @@ fn calling_native_runtime_function_with_non_decodable_parameter() {
fn calling_native_runtime_function_with_non_decodable_return_value() {
let client = test_client::new_with_execution_strategy(ExecutionStrategy::NativeWhenPossible);
let runtime_api = client.runtime_api();
let block_id = BlockId::Number(client.info().unwrap().chain.best_number);
let block_id = BlockId::Number(client.info().chain.best_number);
runtime_api.fail_convert_return_value(&block_id).unwrap();
}
@@ -71,7 +71,7 @@ fn calling_native_runtime_function_with_non_decodable_return_value() {
fn calling_native_runtime_signature_changed_function() {
let client = test_client::new_with_execution_strategy(ExecutionStrategy::NativeWhenPossible);
let runtime_api = client.runtime_api();
let block_id = BlockId::Number(client.info().unwrap().chain.best_number);
let block_id = BlockId::Number(client.info().chain.best_number);
assert_eq!(runtime_api.function_signature_changed(&block_id).unwrap(), 1);
}
@@ -80,7 +80,7 @@ fn calling_native_runtime_signature_changed_function() {
fn calling_wasm_runtime_signature_changed_old_function() {
let client = test_client::new_with_execution_strategy(ExecutionStrategy::AlwaysWasm);
let runtime_api = client.runtime_api();
let block_id = BlockId::Number(client.info().unwrap().chain.best_number);
let block_id = BlockId::Number(client.info().chain.best_number);
#[allow(deprecated)]
let res = runtime_api.function_signature_changed_before_version_2(&block_id).unwrap();
@@ -91,7 +91,7 @@ fn calling_wasm_runtime_signature_changed_old_function() {
fn calling_with_both_strategy_and_fail_on_wasm_should_return_error() {
let client = test_client::new_with_execution_strategy(ExecutionStrategy::Both);
let runtime_api = client.runtime_api();
let block_id = BlockId::Number(client.info().unwrap().chain.best_number);
let block_id = BlockId::Number(client.info().chain.best_number);
assert!(runtime_api.fail_on_wasm(&block_id).is_err());
}
@@ -99,7 +99,7 @@ fn calling_with_both_strategy_and_fail_on_wasm_should_return_error() {
fn calling_with_both_strategy_and_fail_on_native_should_work() {
let client = test_client::new_with_execution_strategy(ExecutionStrategy::Both);
let runtime_api = client.runtime_api();
let block_id = BlockId::Number(client.info().unwrap().chain.best_number);
let block_id = BlockId::Number(client.info().chain.best_number);
assert_eq!(runtime_api.fail_on_native(&block_id).unwrap(), 1);
}
@@ -108,7 +108,7 @@ fn calling_with_both_strategy_and_fail_on_native_should_work() {
fn calling_with_native_else_wasm_and_faild_on_wasm_should_work() {
let client = test_client::new_with_execution_strategy(ExecutionStrategy::NativeElseWasm);
let runtime_api = client.runtime_api();
let block_id = BlockId::Number(client.info().unwrap().chain.best_number);
let block_id = BlockId::Number(client.info().chain.best_number);
assert_eq!(runtime_api.fail_on_wasm(&block_id).unwrap(), 1);
}
@@ -116,7 +116,7 @@ fn calling_with_native_else_wasm_and_faild_on_wasm_should_work() {
fn calling_with_native_else_wasm_and_fail_on_native_should_work() {
let client = test_client::new_with_execution_strategy(ExecutionStrategy::NativeElseWasm);
let runtime_api = client.runtime_api();
let block_id = BlockId::Number(client.info().unwrap().chain.best_number);
let block_id = BlockId::Number(client.info().chain.best_number);
assert_eq!(runtime_api.fail_on_native(&block_id).unwrap(), 1);
}
@@ -124,7 +124,7 @@ fn calling_with_native_else_wasm_and_fail_on_native_should_work() {
fn use_trie_function() {
let client = test_client::new_with_execution_strategy(ExecutionStrategy::AlwaysWasm);
let runtime_api = client.runtime_api();
let block_id = BlockId::Number(client.info().unwrap().chain.best_number);
let block_id = BlockId::Number(client.info().chain.best_number);
assert_eq!(runtime_api.use_trie(&block_id).unwrap(), 2);
}
@@ -132,7 +132,7 @@ fn use_trie_function() {
fn initialize_block_works() {
let client = test_client::new_with_execution_strategy(ExecutionStrategy::Both);
let runtime_api = client.runtime_api();
let block_id = BlockId::Number(client.info().unwrap().chain.best_number);
let block_id = BlockId::Number(client.info().chain.best_number);
assert_eq!(runtime_api.get_block_number(&block_id).unwrap(), 1);
}
@@ -140,7 +140,7 @@ fn initialize_block_works() {
fn initialize_block_is_called_only_once() {
let client = test_client::new_with_execution_strategy(ExecutionStrategy::Both);
let runtime_api = client.runtime_api();
let block_id = BlockId::Number(client.info().unwrap().chain.best_number);
let block_id = BlockId::Number(client.info().chain.best_number);
assert_eq!(runtime_api.take_block_number(&block_id).unwrap(), Some(1));
assert_eq!(runtime_api.take_block_number(&block_id).unwrap(), None);
}
@@ -149,7 +149,7 @@ fn initialize_block_is_called_only_once() {
fn initialize_block_is_skipped() {
let client = test_client::new_with_execution_strategy(ExecutionStrategy::Both);
let runtime_api = client.runtime_api();
let block_id = BlockId::Number(client.info().unwrap().chain.best_number);
let block_id = BlockId::Number(client.info().chain.best_number);
assert!(runtime_api.without_initialize_block(&block_id).unwrap());
}
@@ -157,7 +157,7 @@ fn initialize_block_is_skipped() {
fn record_proof_works() {
let client = test_client::new_with_execution_strategy(ExecutionStrategy::Both);
let block_id = BlockId::Number(client.info().unwrap().chain.best_number);
let block_id = BlockId::Number(client.info().chain.best_number);
#[allow(deprecated)]
let storage_root = LongestChain::new(client.backend().clone(), client.import_lock())
.best_chain().unwrap().state_root().clone();
@@ -43,7 +43,7 @@ pub fn test_leaves_for_backend<B: 'static>(backend: Arc<B>) where
let client = new_with_backend(backend.clone(), false);
let blockchain = backend.blockchain();
let genesis_hash = client.info().unwrap().chain.genesis_hash;
let genesis_hash = client.info().chain.genesis_hash;
assert_eq!(
blockchain.leaves().unwrap(),
@@ -223,7 +223,7 @@ pub fn test_children_for_backend<B: 'static>(backend: Arc<B>) where
let d2 = builder.bake().unwrap();
client.import(BlockOrigin::Own, d2.clone()).unwrap();
let genesis_hash = client.info().unwrap().chain.genesis_hash;
let genesis_hash = client.info().chain.genesis_hash;
let children1 = blockchain.children(a4.hash()).unwrap();
assert_eq!(vec![a5.hash()], children1);
@@ -313,7 +313,7 @@ pub fn test_blockchain_query_by_number_gets_canonical<B: 'static>(backend: Arc<B
let d2 = builder.bake().unwrap();
client.import(BlockOrigin::Own, d2.clone()).unwrap();
let genesis_hash = client.info().unwrap().chain.genesis_hash;
let genesis_hash = client.info().chain.genesis_hash;
assert_eq!(blockchain.header(BlockId::Number(0)).unwrap().unwrap().hash(), genesis_hash);
assert_eq!(blockchain.hash(0).unwrap().unwrap(), genesis_hash);
+1 -1
View File
@@ -231,7 +231,7 @@ mod tests {
let keys: Vec<&ed25519::Pair> = vec![&*alice, &*bob];
let dummy_runtime = ::tokio::runtime::Runtime::new().unwrap();
let block_factory = |service: &<Factory as service::ServiceFactory>::FullService| {
let block_id = BlockId::number(service.client().info().unwrap().chain.best_number);
let block_id = BlockId::number(service.client().info().chain.best_number);
let parent_header = service.client().header(&block_id).unwrap().unwrap();
let consensus_net = ConsensusNetwork::new(service.network(), service.client().clone());
let proposer_factory = consensus::ProposerFactory {