diff --git a/substrate/core/cli/src/informant.rs b/substrate/core/cli/src/informant.rs index 6149d6c95b..607ab9ae85 100644 --- a/substrate/core/cli/src/informant.rs +++ b/substrate/core/cli/src/informant.rs @@ -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::(); - 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::(); - 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::(); + 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::(); + 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| { diff --git a/substrate/core/client/db/src/lib.rs b/substrate/core/client/db/src/lib.rs index dd38f10bcd..a253cc6783 100644 --- a/substrate/core/client/db/src/lib.rs +++ b/substrate/core/client/db/src/lib.rs @@ -271,15 +271,15 @@ impl client::blockchain::HeaderBackend for BlockchainDb Result, client::error::Error> { + fn info(&self) -> client::blockchain::Info { 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) -> Result { @@ -742,7 +742,7 @@ impl> Backend { } // 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 client::backend::Backend for Backend whe } fn revert(&self, n: NumberFor) -> Result, 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::::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()) } diff --git a/substrate/core/client/db/src/light.rs b/substrate/core/client/db/src/light.rs index 16b0fc616a..e0f2153a13 100644 --- a/substrate/core/client/db/src/light.rs +++ b/substrate/core/client/db/src/light.rs @@ -155,15 +155,15 @@ impl BlockchainHeaderBackend for LightStorage utils::read_header(&*self.db, columns::KEY_LOOKUP, columns::HEADER, id) } - fn info(&self) -> ClientResult> { + fn info(&self) -> BlockchainInfo { 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) -> ClientResult { @@ -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::(hash0)).unwrap().unwrap().hash(), hash0); } diff --git a/substrate/core/client/src/block_builder/block_builder.rs b/substrate/core/client/src/block_builder/block_builder.rs index eb7d81f978..4564c29aae 100644 --- a/substrate/core/client/src/block_builder/block_builder.rs +++ b/substrate/core/client/src/block_builder/block_builder.rs @@ -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) -> error::Result { - 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 diff --git a/substrate/core/client/src/blockchain.rs b/substrate/core/client/src/blockchain.rs index d168ecda19..05210fc9ad 100644 --- a/substrate/core/client/src/blockchain.rs +++ b/substrate/core/client/src/blockchain.rs @@ -30,7 +30,7 @@ pub trait HeaderBackend: Send + Sync { /// Get block header. Returns `None` if block is not found. fn header(&self, id: BlockId) -> Result>; /// Get blockchain info. - fn info(&self) -> Result>; + fn info(&self) -> Info; /// Get block status. fn status(&self, id: BlockId) -> Result; /// Get block number by hash. Returns `None` if the header is not in the chain. diff --git a/substrate/core/client/src/client.rs b/substrate/core/client/src/client.rs index 1f19b96d3c..0d8f8aa548 100644 --- a/substrate/core/client/src/client.rs +++ b/substrate/core/client/src/client.rs @@ -497,7 +497,7 @@ impl Client 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 Client 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::>()) .map_err(|err| error::Error::ChangesTrieAccessFailed(err)) @@ -608,7 +608,7 @@ impl Client 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 Client 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 Client where justification: Option, 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 Client where /// while performing major synchronization work. pub fn finalize_block(&self, id: BlockId, justification: Option, 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 Client where } /// Get blockchain info. - pub fn info(&self) -> error::Result> { - let info = self.backend.blockchain().info().map_err(|e| error::Error::from_blockchain(Box::new(e)))?; - Ok(ClientInfo { + pub fn info(&self) -> ClientInfo { + 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 Client 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 Client where } fn changes_trie_config(&self) -> Result, 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 ChainHeaderBackend for Client wher self.backend.blockchain().header(id) } - fn info(&self) -> error::Result> { + fn info(&self) -> blockchain::Info { self.backend.blockchain().info() } @@ -1448,7 +1448,7 @@ impl CurrentHeight for Client where { type BlockNumber = ::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<::Header> { - let info : ChainInfo = match self.backend.blockchain().info() { - Ok(i) => i, - Err(e) => return Err(error::Error::from_blockchain(Box::new(e))) - }; + let info : ChainInfo = 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()), diff --git a/substrate/core/client/src/in_mem.rs b/substrate/core/client/src/in_mem.rs index 1172939b34..6c11d0ed57 100644 --- a/substrate/core/client/src/in_mem.rs +++ b/substrate/core/client/src/in_mem.rs @@ -297,15 +297,15 @@ impl HeaderBackend for Blockchain { })) } - fn info(&self) -> error::Result> { + fn info(&self) -> blockchain::Info { 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) -> error::Result { diff --git a/substrate/core/client/src/light/blockchain.rs b/substrate/core/client/src/light/blockchain.rs index b231f7e8aa..62c13db5a4 100644 --- a/substrate/core/client/src/light/blockchain.rs +++ b/substrate/core/client/src/light/blockchain.rs @@ -134,7 +134,7 @@ impl BlockchainHeaderBackend for Blockchain where Bloc } } - fn info(&self) -> ClientResult> { + fn info(&self) -> BlockchainInfo { self.storage.info() } @@ -223,8 +223,8 @@ pub mod tests { Err(ClientError::Backend("Test error".into())) } - fn info(&self) -> ClientResult> { - Err(ClientError::Backend("Test error".into())) + fn info(&self) -> Info { + panic!("Test error") } fn status(&self, _id: BlockId) -> ClientResult { diff --git a/substrate/core/client/src/light/fetcher.rs b/substrate/core/client/src/light/fetcher.rs index 0a8a05b850..f25a2acd30 100644 --- a/substrate/core/client/src/light/fetcher.rs +++ b/substrate/core/client/src/light/fetcher.rs @@ -668,8 +668,8 @@ pub mod tests { test_client::LocalExecutor::new(None) ); let local_checker = &local_checker as &FetchChecker; - 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; - 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(); diff --git a/substrate/core/consensus/aura/src/lib.rs b/substrate/core/consensus/aura/src/lib.rs index 36c51c8cff..263381d5f1 100644 --- a/substrate/core/consensus/aura/src/lib.rs +++ b/substrate/core/consensus/aura/src/lib.rs @@ -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(), diff --git a/substrate/core/consensus/babe/src/lib.rs b/substrate/core/consensus/babe/src/lib.rs index 81b4be4137..969c7b8593 100644 --- a/substrate/core/consensus/babe/src/lib.rs +++ b/substrate/core/consensus/babe/src/lib.rs @@ -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(), diff --git a/substrate/core/finality-grandpa/src/environment.rs b/substrate/core/finality-grandpa/src/environment.rs index ed50629f47..4aab32be8a 100644 --- a/substrate/core/finality-grandpa/src/environment.rs +++ b/substrate/core/finality-grandpa/src/environment.rs @@ -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, 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); diff --git a/substrate/core/finality-grandpa/src/finality_proof.rs b/substrate/core/finality-grandpa/src/finality_proof.rs index 4ad1844358..e8af599279 100644 --- a/substrate/core/finality-grandpa/src/finality_proof.rs +++ b/substrate/core/finality-grandpa/src/finality_proof.rs @@ -268,7 +268,7 @@ pub(crate) fn prove_finality, B: BlockchainBackend, RA, PRA, SC> JustificationImport type Error = ConsensusError; fn on_start(&self, link: &::consensus_common::import_queue::Link) { - 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); diff --git a/substrate/core/finality-grandpa/src/lib.rs b/substrate/core/finality-grandpa/src/lib.rs index aee6c16d13..2a1da15499 100644 --- a/substrate/core/finality-grandpa/src/lib.rs +++ b/substrate/core/finality-grandpa/src/lib.rs @@ -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 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, 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, 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, N, RA, SC, X>( // some command issued internally. handle_voter_command(command, voter_commands_rx) }, - })) + }) }); let voter_work = voter_work diff --git a/substrate/core/finality-grandpa/src/light_import.rs b/substrate/core/finality-grandpa/src/light_import.rs index 9e257e9ccc..73bc3411fe 100644 --- a/substrate/core/finality-grandpa/src/light_import.rs +++ b/substrate/core/finality-grandpa/src/light_import.rs @@ -63,7 +63,7 @@ pub fn light_block_import, RA, PRA>( PRA: ProvideRuntimeApi, PRA::Api: GrandpaApi, { - 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, RA> FinalityProofImport type Error = ConsensusError; fn on_start(&self, link: &::consensus_common::import_queue::Link) { - 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(), diff --git a/substrate/core/finality-grandpa/src/observer.rs b/substrate/core/finality-grandpa/src/observer.rs index 3fc9665a8d..f172e58ee9 100644 --- a/substrate/core/finality-grandpa/src/observer.rs +++ b/substrate/core/finality-grandpa/src/observer.rs @@ -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, 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, 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, N, RA, SC>( // some command issued internally handle_voter_command(command, voter_commands_rx) }, - })) + }) }); let observer_work = observer_work diff --git a/substrate/core/finality-grandpa/src/tests.rs b/substrate/core/finality-grandpa/src/tests.rs index 5b4fa9155a..ef04396b5f 100644 --- a/substrate/core/finality-grandpa/src/tests.rs +++ b/substrate/core/finality-grandpa/src/tests.rs @@ -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 = 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 }, ); } diff --git a/substrate/core/network/src/chain.rs b/substrate/core/network/src/chain.rs index f7ce4f9d5c..76096a44aa 100644 --- a/substrate/core/network/src/chain.rs +++ b/substrate/core/network/src/chain.rs @@ -28,7 +28,7 @@ use primitives::{H256, Blake2Hasher, storage::StorageKey}; /// Local client abstraction for the network. pub trait Client: Send + Sync { /// Get blockchain info. - fn info(&self) -> Result, Error>; + fn info(&self) -> ClientInfo; /// Get block status. fn block_status(&self, id: &BlockId) -> Result; @@ -81,7 +81,7 @@ impl Client for SubstrateClient where Block: BlockT, RA: Send + Sync { - fn info(&self) -> Result, Error> { + fn info(&self) -> ClientInfo { (self as &SubstrateClient).info() } diff --git a/substrate/core/network/src/protocol.rs b/substrate/core/network/src/protocol.rs index e1fa38576a..b660e097a1 100644 --- a/substrate/core/network/src/protocol.rs +++ b/substrate/core/network/src/protocol.rs @@ -399,7 +399,7 @@ impl, H: ExHashT> Protocol { checker: Arc>, specialization: S, ) -> error::Result> { - 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, H: ExHashT> Protocol { .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, H: ExHashT> Protocol { /// Send Status message fn send_status(&mut self, network_out: &mut dyn NetworkOut, 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( diff --git a/substrate/core/network/src/sync.rs b/substrate/core/network/src/sync.rs index e451372847..27a412ca0e 100644 --- a/substrate/core/network/src/sync.rs +++ b/substrate/core/network/src/sync.rs @@ -829,18 +829,10 @@ impl ChainSync { 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 = self.peers.drain().map(|(id, _)| id).collect(); for id in ids { self.new_peer(protocol, id); diff --git a/substrate/core/network/src/test/mod.rs b/substrate/core/network/src/test/mod.rs index 6103a6ecd9..b47cef11ac 100644 --- a/substrate/core/network/src/test/mod.rs +++ b/substrate/core/network/src/test/mod.rs @@ -163,7 +163,7 @@ impl PeersClient { } } - pub fn info(&self) -> ClientResult> { + pub fn info(&self) -> ClientInfo { match *self { PeersClient::Full(ref client) => client.info(), PeersClient::Light(ref client) => client.info(), @@ -465,7 +465,7 @@ impl> Peer { /// 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> Peer { /// 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> Peer { /// 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> Peer { pub fn generate_blocks(&self, count: usize, origin: BlockOrigin, edit_block: F) -> H256 where F: FnMut(BlockBuilder) -> 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> Peer { /// 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) } diff --git a/substrate/core/network/src/test/sync.rs b/substrate/core/network/src/test/sync.rs index 50b00ac62a..1e9e2948f3 100644 --- a/substrate/core/network/src/test/sync.rs +++ b/substrate/core/network/src/test/sync.rs @@ -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); diff --git a/substrate/core/rpc/src/author/mod.rs b/substrate/core/rpc/src/author/mod.rs index 59641e8466..4e3bc96ca9 100644 --- a/substrate/core/rpc/src/author/mod.rs +++ b/substrate/core/rpc/src/author/mod.rs @@ -110,7 +110,7 @@ impl AuthorApi, BlockHash

> for Author whe fn submit_extrinsic(&self, ext: Bytes) -> Result> { 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 AuthorApi, BlockHash

> for Author whe fn watch_extrinsic(&self, _metadata: Self::Metadata, subscriber: Subscriber, BlockHash

>>, 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 = <

::Block as traits::Block>::Extrinsic::decode(&mut &xt[..]) .ok_or(error::Error::BadFormat)?; self.pool diff --git a/substrate/core/rpc/src/chain/mod.rs b/substrate/core/rpc/src/chain/mod.rs index 9dd7ad84b8..90c833e3fd 100644 --- a/substrate/core/rpc/src/chain/mod.rs +++ b/substrate/core/rpc/src/chain/mod.rs @@ -124,7 +124,7 @@ impl Chain where { fn unwrap_or_best(&self, hash: Option) -> Result { 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 ChainApi, Block::Hash, Block::Header, Sig fn block_hash(&self, number: Option>>) -> Result> { 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 { - Ok(self.client.info()?.chain.finalized_hash) + Ok(self.client.info().chain.finalized_hash) } fn subscribe_new_head(&self, _metadata: Self::Metadata, subscriber: Subscriber) { @@ -214,7 +214,7 @@ impl ChainApi, Block::Hash, Block::Header, Sig fn subscribe_finalized_heads(&self, _meta: Self::Metadata, subscriber: Subscriber) { 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), ) diff --git a/substrate/core/rpc/src/state/mod.rs b/substrate/core/rpc/src/state/mod.rs index 98d62d678d..ebb45d6b5f 100644 --- a/substrate/core/rpc/src/state/mod.rs +++ b/substrate/core/rpc/src/state/mod.rs @@ -322,7 +322,7 @@ impl State where E: CallExecutor, { fn unwrap_or_best(&self, hash: Option) -> Result { - 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 StateApi for State 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 StateApi for State 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 { diff --git a/substrate/core/service/src/chain_ops.rs b/substrate/core/service/src/chain_ops.rs index 4df3b06cdf..3be3b9b17a 100644 --- a/substrate/core/service/src/chain_ops.rs +++ b/substrate/core/service/src/chain_ops.rs @@ -52,7 +52,7 @@ pub fn export_blocks( 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( 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( { let client = new_client::(&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."); diff --git a/substrate/core/service/src/lib.rs b/substrate/core/service/src/lib.rs index cb65ece34e..0e16d2e7be 100644 --- a/substrate/core/service/src/lib.rs +++ b/substrate/core/service/src/lib.rs @@ -156,7 +156,7 @@ impl Service { 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 { impl TransactionPoolAdapter { fn best_block_id(&self) -> Option>> { - 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)) } } diff --git a/substrate/core/service/test/src/lib.rs b/substrate/core/service/test/src/lib.rs index 88425e1956..9b73cfa14c 100644 --- a/substrate/core/service/test/src/lib.rs +++ b/substrate/core/service/test/src/lib.rs @@ -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(spec: FactoryChainSpec, authorities: Vec) 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(spec: FactoryChainSpec, authorities: Vec) 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() ); } diff --git a/substrate/core/sr-api-macros/benches/bench.rs b/substrate/core/sr-api-macros/benches/bench.rs index f467721789..55399fb4d8 100644 --- a/substrate/core/sr-api-macros/benches/bench.rs +++ b/substrate/core/sr-api-macros/benches/bench.rs @@ -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()) }); } diff --git a/substrate/core/sr-api-macros/tests/runtime_calls.rs b/substrate/core/sr-api-macros/tests/runtime_calls.rs index ff462d9e2a..f4d87ca8ca 100644 --- a/substrate/core/sr-api-macros/tests/runtime_calls.rs +++ b/substrate/core/sr-api-macros/tests/runtime_calls.rs @@ -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(); diff --git a/substrate/core/test-client/src/trait_tests.rs b/substrate/core/test-client/src/trait_tests.rs index c1df6ffdf8..a7ef1a01f6 100644 --- a/substrate/core/test-client/src/trait_tests.rs +++ b/substrate/core/test-client/src/trait_tests.rs @@ -43,7 +43,7 @@ pub fn test_leaves_for_backend(backend: Arc) 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(backend: Arc) 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(backend: Arc = vec![&*alice, &*bob]; let dummy_runtime = ::tokio::runtime::Runtime::new().unwrap(); let block_factory = |service: &::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 {