diff --git a/rust-toolchain.toml b/rust-toolchain.toml index eac0c37227a1..9a3d7a1a5906 100644 --- a/rust-toolchain.toml +++ b/rust-toolchain.toml @@ -1,3 +1,3 @@ [toolchain] -channel = "1.88.0" +channel = "1.89.0" components = ["clippy", "llvm-tools-preview", "rustfmt"] diff --git a/src/blocks/tipset.rs b/src/blocks/tipset.rs index a361f5996ef8..47b1aed481cf 100644 --- a/src/blocks/tipset.rs +++ b/src/blocks/tipset.rs @@ -427,12 +427,12 @@ impl Tipset { (*calibnet::GENESIS_CID, &headers.calibnet), (*mainnet::GENESIS_CID, &headers.mainnet), ] { - if let Some(known_block_cid) = known_blocks.get(&tipset.epoch()) { - if known_block_cid == &tipset.min_ticket_block().cid().to_string() { - return store - .get_cbor(&genesis_cid)? - .context("Genesis block missing from database"); - } + if let Some(known_block_cid) = known_blocks.get(&tipset.epoch()) + && known_block_cid == &tipset.min_ticket_block().cid().to_string() + { + return store + .get_cbor(&genesis_cid)? + .context("Genesis block missing from database"); } } diff --git a/src/chain/store/index.rs b/src/chain/store/index.rs index cc33e174f717..fbe3f919a582 100644 --- a/src/chain/store/index.rs +++ b/src/chain/store/index.rs @@ -47,13 +47,13 @@ impl ChainIndex { /// Loads a tipset from memory given the tipset keys and cache. Semantically /// identical to [`Tipset::load`] but the result is cached. pub fn load_tipset(&self, tsk: &TipsetKey) -> Result>, Error> { - if !is_env_truthy("FOREST_TIPSET_CACHE_DISABLED") { - if let Some(ts) = self.ts_cache.lock().get(tsk) { - metrics::LRU_CACHE_HIT - .get_or_create(&metrics::values::TIPSET) - .inc(); - return Ok(Some(ts.clone())); - } + if !is_env_truthy("FOREST_TIPSET_CACHE_DISABLED") + && let Some(ts) = self.ts_cache.lock().get(tsk) + { + metrics::LRU_CACHE_HIT + .get_or_create(&metrics::values::TIPSET) + .inc(); + return Ok(Some(ts.clone())); } let ts_opt = Tipset::load(&self.db, tsk)?.map(Arc::new); diff --git a/src/chain/store/tipset_tracker.rs b/src/chain/store/tipset_tracker.rs index 4c11ae9ecd3c..0f0a87d0df3f 100644 --- a/src/chain/store/tipset_tracker.rs +++ b/src/chain/store/tipset_tracker.rs @@ -54,16 +54,16 @@ impl TipsetTracker { /// height. fn check_multiple_blocks_from_same_miner(&self, cids: &[Cid], header: &CachingBlockHeader) { for cid in cids.iter() { - if let Ok(Some(block)) = CachingBlockHeader::load(&self.db, *cid) { - if header.miner_address == block.miner_address { - warn!( - "Have multiple blocks from miner {} at height {} in our tipset cache {}-{}", - header.miner_address, - header.epoch, - header.cid(), - cid - ); - } + if let Ok(Some(block)) = CachingBlockHeader::load(&self.db, *cid) + && header.miner_address == block.miner_address + { + warn!( + "Have multiple blocks from miner {} at height {} in our tipset cache {}-{}", + header.miner_address, + header.epoch, + header.cid(), + cid + ); } } } diff --git a/src/chain_sync/network_context.rs b/src/chain_sync/network_context.rs index 3dfabe1411c7..8def73d7e9eb 100644 --- a/src/chain_sync/network_context.rs +++ b/src/chain_sync/network_context.rs @@ -103,10 +103,10 @@ where F: Fn(&T) -> bool, { while let Some(result) = self.tasks.join_next().await { - if let Ok(Ok(value)) = result { - if validate(&value) { - return Some(value); - } + if let Ok(Ok(value)) = result + && validate(&value) + { + return Some(value); } } // So far every task have failed @@ -309,14 +309,14 @@ where .get_ok_validated(validate) .await .ok_or_else(make_failure_message)?; - if let Ok(mean) = success_time_cost_millis_stats.lock().mean() { - if CHAIN_EXCHANGE_TIMEOUT_MILLIS.adapt_on_success(mean as _) { - tracing::debug!( - "Decreased chain exchange timeout to {}ms. Current average: {}ms", - CHAIN_EXCHANGE_TIMEOUT_MILLIS.get(), - mean, - ); - } + if let Ok(mean) = success_time_cost_millis_stats.lock().mean() + && CHAIN_EXCHANGE_TIMEOUT_MILLIS.adapt_on_success(mean as _) + { + tracing::debug!( + "Decreased chain exchange timeout to {}ms. Current average: {}ms", + CHAIN_EXCHANGE_TIMEOUT_MILLIS.get(), + mean, + ); } trace!("Succeed: handle_chain_exchange_request"); v diff --git a/src/chain_sync/validation.rs b/src/chain_sync/validation.rs index 545876f6ce57..b05100956101 100644 --- a/src/chain_sync/validation.rs +++ b/src/chain_sync/validation.rs @@ -74,10 +74,10 @@ impl TipsetValidator<'_> { // previously been seen in the bad blocks cache for block in self.0.blocks() { self.validate_msg_root(&chainstore.db, block)?; - if let Some(bad_block_cache) = bad_block_cache { - if bad_block_cache.peek(block.cid()).is_some() { - return Err(TipsetValidationError::InvalidBlock(*block.cid())); - } + if let Some(bad_block_cache) = bad_block_cache + && bad_block_cache.peek(block.cid()).is_some() + { + return Err(TipsetValidationError::InvalidBlock(*block.cid())); } } diff --git a/src/cid_collections/hash_map.rs b/src/cid_collections/hash_map.rs index 3ae7060f6abf..8de5b3f6a778 100644 --- a/src/cid_collections/hash_map.rs +++ b/src/cid_collections/hash_map.rs @@ -109,7 +109,7 @@ impl CidHashMap { /// /// See also [`HashMap::entry`]. #[allow(dead_code)] - pub fn entry(&mut self, key: Cid) -> Entry { + pub fn entry(&mut self, key: Cid) -> Entry<'_, V> { match MaybeCompactedCid::from(key) { MaybeCompactedCid::Compact(c) => match self.compact.entry(c) { StdEntry::Occupied(o) => Entry::Occupied(OccupiedEntry { diff --git a/src/cid_collections/mod.rs b/src/cid_collections/mod.rs index 0ddfc2f42734..b10715a4f36b 100644 --- a/src/cid_collections/mod.rs +++ b/src/cid_collections/mod.rs @@ -75,13 +75,13 @@ mod imp { type Error = &'static str; fn try_from(value: Cid) -> Result { - if value.version() == cid::Version::V1 && value.codec() == fvm_ipld_encoding::DAG_CBOR { - if let Ok(small_hash) = value.hash().resize() { - let (code, digest, size) = small_hash.into_inner(); - if code == u64::from(MultihashCode::Blake2b256) && size as usize == Self::WIDTH - { - return Ok(Self { digest }); - } + if value.version() == cid::Version::V1 + && value.codec() == fvm_ipld_encoding::DAG_CBOR + && let Ok(small_hash) = value.hash().resize() + { + let (code, digest, size) = small_hash.into_inner(); + if code == u64::from(MultihashCode::Blake2b256) && size as usize == Self::WIDTH { + return Ok(Self { digest }); } } Err("cannot be compacted") diff --git a/src/cli/main.rs b/src/cli/main.rs index 8b2d5c818cad..c0b17e0e79e1 100644 --- a/src/cli/main.rs +++ b/src/cli/main.rs @@ -27,10 +27,10 @@ where .block_on(async { logger::setup_logger(&crate::cli_shared::cli::CliOpts::default()); - if let Ok(name) = StateNetworkName::call(&client, ()).await { - if !matches!(NetworkChain::from_str(&name), Ok(NetworkChain::Mainnet)) { - CurrentNetwork::set_global(Network::Testnet); - } + if let Ok(name) = StateNetworkName::call(&client, ()).await + && !matches!(NetworkChain::from_str(&name), Ok(NetworkChain::Mainnet)) + { + CurrentNetwork::set_global(Network::Testnet); } // Run command diff --git a/src/cli/subcommands/net_cmd.rs b/src/cli/subcommands/net_cmd.rs index 44bfc736ed05..e46897b3815c 100644 --- a/src/cli/subcommands/net_cmd.rs +++ b/src/cli/subcommands/net_cmd.rs @@ -160,12 +160,12 @@ impl NetCommands { Self::Reachability => { let nat_status = NetAutoNatStatus::call(&client, ()).await?; println!("AutoNAT status: {}", nat_status.reachability_as_str()); - if let Some(public_addrs) = nat_status.public_addrs { - if !public_addrs.is_empty() { - // Format is compatible with Go code: - // `fmt.Println("Public address:", []string{"foo", "bar"})` - println!("Public address: [{}]", public_addrs.join(" ")); - } + if let Some(public_addrs) = nat_status.public_addrs + && !public_addrs.is_empty() + { + // Format is compatible with Go code: + // `fmt.Println("Public address:", []string{"foo", "bar"})` + println!("Public address: [{}]", public_addrs.join(" ")); } Ok(()) } diff --git a/src/cli/subcommands/state_cmd.rs b/src/cli/subcommands/state_cmd.rs index c6ed5432dd45..f223e379d4e1 100644 --- a/src/cli/subcommands/state_cmd.rs +++ b/src/cli/subcommands/state_cmd.rs @@ -6,25 +6,12 @@ use crate::rpc::state::ForestStateCompute; use crate::rpc::{self, prelude::*}; use crate::shim::address::{CurrentNetwork, Error, Network, StrictAddress}; use crate::shim::clock::ChainEpoch; -use crate::shim::econ::TokenAmount; use cid::Cid; use clap::Subcommand; -use fvm_ipld_encoding::tuple::*; use std::path::PathBuf; use std::str::FromStr; use std::time::Duration; -#[derive(Serialize_tuple, Deserialize_tuple, Clone, Debug)] -struct VestingSchedule { - entries: Vec, -} - -#[derive(Serialize_tuple, Deserialize_tuple, Clone, Debug)] -struct VestingScheduleEntry { - epoch: ChainEpoch, - amount: TokenAmount, -} - #[derive(Debug, Subcommand)] pub enum StateCommands { Fetch { diff --git a/src/cli_shared/snapshot.rs b/src/cli_shared/snapshot.rs index b7fb3085ef57..f3a06bb40a0a 100644 --- a/src/cli_shared/snapshot.rs +++ b/src/cli_shared/snapshot.rs @@ -267,7 +267,7 @@ mod parse { } } - fn full(input: &str) -> nom::IResult<&str, ParsedFilename> { + fn full(input: &str) -> nom::IResult<&str, ParsedFilename<'_>> { let (rest, (vendor, _snapshot_, chain, _, date, _height_, height, car_zst)) = ( take_until("_snapshot_"), tag("_snapshot_"), @@ -291,7 +291,7 @@ mod parse { )) } - fn short(input: &str) -> nom::IResult<&str, ParsedFilename> { + fn short(input: &str) -> nom::IResult<&str, ParsedFilename<'_>> { let (rest, (height, _, date, _, time, _)) = ( number, tag("_"), diff --git a/src/daemon/context.rs b/src/daemon/context.rs index 40d6b6f886d7..b3458d6bea8a 100644 --- a/src/daemon/context.rs +++ b/src/daemon/context.rs @@ -337,15 +337,15 @@ fn handle_admin_token( tracing::warn!("Failed to save the default admin token file: {e}"); } if let Some(path) = opts.save_token.as_ref() { - if let Some(dir) = path.parent() { - if !dir.is_dir() { - std::fs::create_dir_all(dir).with_context(|| { - format!( - "Failed to create `--save-token` directory {}", - dir.display() - ) - })?; - } + if let Some(dir) = path.parent() + && !dir.is_dir() + { + std::fs::create_dir_all(dir).with_context(|| { + format!( + "Failed to create `--save-token` directory {}", + dir.display() + ) + })?; } std::fs::write(path, &token) .with_context(|| format!("Failed to save admin token to {}", path.display()))?; diff --git a/src/daemon/mod.rs b/src/daemon/mod.rs index 49d4a2b1b472..26b3bbe9e9d4 100644 --- a/src/daemon/mod.rs +++ b/src/daemon/mod.rs @@ -133,28 +133,28 @@ async fn maybe_import_snapshot( let snapshot_tracker = ctx.snapshot_progress_tracker.clone(); // Import chain if needed - if !opts.skip_load.unwrap_or_default() { - if let Some(path) = &config.client.snapshot_path { - let (car_db_path, ts) = import_chain_as_forest_car( - path, - &ctx.db_meta_data.get_forest_car_db_dir(), - config.client.import_mode, - &snapshot_tracker, - ) - .await?; - ctx.db - .read_only_files(std::iter::once(car_db_path.clone()))?; - let ts_epoch = ts.epoch(); - // Explicitly set heaviest tipset here in case HEAD_KEY has already been set - // in the current setting store - ctx.state_manager - .chain_store() - .set_heaviest_tipset(ts.into())?; - debug!( - "Loaded car DB at {} and set current head to epoch {ts_epoch}", - car_db_path.display(), - ); - } + if !opts.skip_load.unwrap_or_default() + && let Some(path) = &config.client.snapshot_path + { + let (car_db_path, ts) = import_chain_as_forest_car( + path, + &ctx.db_meta_data.get_forest_car_db_dir(), + config.client.import_mode, + &snapshot_tracker, + ) + .await?; + ctx.db + .read_only_files(std::iter::once(car_db_path.clone()))?; + let ts_epoch = ts.epoch(); + // Explicitly set heaviest tipset here in case HEAD_KEY has already been set + // in the current setting store + ctx.state_manager + .chain_store() + .set_heaviest_tipset(ts.into())?; + debug!( + "Loaded car DB at {} and set current head to epoch {ts_epoch}", + car_db_path.display(), + ); } // If the snapshot progress state is not completed, diff --git a/src/db/blockstore_with_read_cache.rs b/src/db/blockstore_with_read_cache.rs index ef64a8757482..afbfc636a338 100644 --- a/src/db/blockstore_with_read_cache.rs +++ b/src/db/blockstore_with_read_cache.rs @@ -14,8 +14,6 @@ pub trait BlockstoreReadCache { fn get(&self, k: &Cid) -> Option>; fn put(&self, k: Cid, block: Vec); - - fn len(&self) -> usize; } pub type LruBlockstoreReadCache = SizeTrackingLruCache>; @@ -28,25 +26,6 @@ impl BlockstoreReadCache for SizeTrackingLruCache> fn put(&self, k: Cid, block: Vec) { self.push(k.into(), block); } - - fn len(&self) -> usize { - self.len() - } -} - -#[derive(Debug, Default)] -pub struct VoidBlockstoreReadCache; - -impl BlockstoreReadCache for VoidBlockstoreReadCache { - fn get(&self, _: &Cid) -> Option> { - None - } - - fn put(&self, _: Cid, _: Vec) {} - - fn len(&self) -> usize { - 0 - } } impl BlockstoreReadCache for Arc { @@ -57,10 +36,6 @@ impl BlockstoreReadCache for Arc { fn put(&self, k: Cid, block: Vec) { self.as_ref().put(k, block) } - - fn len(&self) -> usize { - self.as_ref().len() - } } pub trait BlockstoreReadCacheStats { diff --git a/src/db/car/any.rs b/src/db/car/any.rs index fc271c6fe1d4..29371c35c598 100644 --- a/src/db/car/any.rs +++ b/src/db/car/any.rs @@ -36,10 +36,10 @@ impl AnyCar { } // Maybe use a tempfile for this in the future. - if let Ok(decompressed) = zstd::stream::decode_all(positioned_io::Cursor::new(&reader)) { - if let Ok(mem_car) = super::PlainCar::new(decompressed) { - return Ok(AnyCar::Memory(mem_car)); - } + if let Ok(decompressed) = zstd::stream::decode_all(positioned_io::Cursor::new(&reader)) + && let Ok(mem_car) = super::PlainCar::new(decompressed) + { + return Ok(AnyCar::Memory(mem_car)); } if let Ok(plain_car) = super::PlainCar::new(reader) { diff --git a/src/db/car/plain.rs b/src/db/car/plain.rs index 9e2defcfab7c..5b8fb78414e1 100644 --- a/src/db/car/plain.rs +++ b/src/db/car/plain.rs @@ -375,10 +375,10 @@ fn read_block_data_location_and_skip( mut reader: (impl Read + Seek), limit_position: Option, ) -> io::Result> { - if let Some(limit_position) = limit_position { - if reader.stream_position()? >= limit_position { - return Ok(None); - } + if let Some(limit_position) = limit_position + && reader.stream_position()? >= limit_position + { + return Ok(None); } let Some(body_length) = read_varint_body_length_or_eof(&mut reader)? else { return Ok(None); diff --git a/src/db/gc/snapshot.rs b/src/db/gc/snapshot.rs index 0d7cb99368c5..d00889b5df39 100644 --- a/src/db/gc/snapshot.rs +++ b/src/db/gc/snapshot.rs @@ -172,18 +172,16 @@ where if !self.running.load(Ordering::Relaxed) && let Some(db) = &*self.db.read() && let Some(car_db_head_epoch) = *self.car_db_head_epoch.read() + && let Ok(head_key) = HeaviestTipsetKeyProvider::heaviest_tipset_key(db) + && let Ok(head) = Tipset::load_required(db, &head_key) { - if let Ok(head_key) = HeaviestTipsetKeyProvider::heaviest_tipset_key(db) { - if let Ok(head) = Tipset::load_required(db, &head_key) { - let head_epoch = head.epoch(); - if head_epoch - car_db_head_epoch >= snap_gc_interval_epochs - && self.trigger_tx.try_send(()).is_ok() - { - tracing::info!(%car_db_head_epoch, %head_epoch, %snap_gc_interval_epochs, "Snap GC scheduled"); - } else { - tracing::trace!(%car_db_head_epoch, %head_epoch, %snap_gc_interval_epochs, "Snap GC not scheduled"); - } - } + let head_epoch = head.epoch(); + if head_epoch - car_db_head_epoch >= snap_gc_interval_epochs + && self.trigger_tx.try_send(()).is_ok() + { + tracing::info!(%car_db_head_epoch, %head_epoch, %snap_gc_interval_epochs, "Snap GC scheduled"); + } else { + tracing::trace!(%car_db_head_epoch, %head_epoch, %snap_gc_interval_epochs, "Snap GC not scheduled"); } } tokio::time::sleep(snap_gc_check_interval).await; @@ -269,93 +267,92 @@ where async fn cleanup_before_reboot_inner(&self) -> anyhow::Result<()> { tracing::info!("cleaning up db before rebooting"); - if let Some(blessed_lite_snapshot) = { self.blessed_lite_snapshot.read().clone() } { - if blessed_lite_snapshot.is_file() { - let mut opts = ParityDb::to_options(self.db_root_dir.clone(), &self.db_config); - for col in [ - DbColumn::GraphDagCborBlake2b256 as u8, - DbColumn::GraphFull as u8, - ] { - let start = Instant::now(); - tracing::info!("pruning parity-db column {col}..."); - loop { - match parity_db::Db::reset_column(&mut opts, col, None) { - Ok(_) => break, - Err(_) => { - tokio::time::sleep(Duration::from_secs(1)).await; - } + if let Some(blessed_lite_snapshot) = { self.blessed_lite_snapshot.read().clone() } + && blessed_lite_snapshot.is_file() + { + let mut opts = ParityDb::to_options(self.db_root_dir.clone(), &self.db_config); + for col in [ + DbColumn::GraphDagCborBlake2b256 as u8, + DbColumn::GraphFull as u8, + ] { + let start = Instant::now(); + tracing::info!("pruning parity-db column {col}..."); + loop { + match parity_db::Db::reset_column(&mut opts, col, None) { + Ok(_) => break, + Err(_) => { + tokio::time::sleep(Duration::from_secs(1)).await; } } - tracing::info!( - "pruned parity-db column {col}, took {}", - humantime::format_duration(start.elapsed()) - ); } + tracing::info!( + "pruned parity-db column {col}, took {}", + humantime::format_duration(start.elapsed()) + ); + } - for car_to_remove in walkdir::WalkDir::new(&self.car_db_dir) - .max_depth(1) - .into_iter() - .filter_map(|entry| { - if let Ok(entry) = entry { - // Also cleanup `.tmp*` files snapshot export is interrupted ungracefully - if entry.path().is_file() - && entry.path() != blessed_lite_snapshot.as_path() - { - return Some(entry.into_path()); - } - } - None - }) - { - match std::fs::remove_file(&car_to_remove) { - Ok(_) => { - tracing::info!("deleted car db at {}", car_to_remove.display()); - } - Err(e) => { - tracing::warn!( - "failed to delete car db at {}: {e}", - car_to_remove.display() - ); + for car_to_remove in walkdir::WalkDir::new(&self.car_db_dir) + .max_depth(1) + .into_iter() + .filter_map(|entry| { + if let Ok(entry) = entry { + // Also cleanup `.tmp*` files snapshot export is interrupted ungracefully + if entry.path().is_file() && entry.path() != blessed_lite_snapshot.as_path() + { + return Some(entry.into_path()); } } + None + }) + { + match std::fs::remove_file(&car_to_remove) { + Ok(_) => { + tracing::info!("deleted car db at {}", car_to_remove.display()); + } + Err(e) => { + tracing::warn!( + "failed to delete car db at {}: {e}", + car_to_remove.display() + ); + } } + } - // Backfill new db records during snapshot export - if let Ok(db) = open_db(self.db_root_dir.clone(), &self.db_config) { - if let Some(mem_db) = self.memory_db.write().take() { - let count = mem_db.len(); - let approximate_heap_size = { - let mut size = 0; - for (_k, v) in mem_db.iter() { - size += std::mem::size_of::(); - size += v.len(); - } - size - }; - let start = Instant::now(); - if let Err(e) = db.put_many_keyed(mem_db) { - tracing::warn!("{e}"); + // Backfill new db records during snapshot export + if let Ok(db) = open_db(self.db_root_dir.clone(), &self.db_config) { + if let Some(mem_db) = self.memory_db.write().take() { + let count = mem_db.len(); + let approximate_heap_size = { + let mut size = 0; + for (_k, v) in mem_db.iter() { + size += std::mem::size_of::(); + size += v.len(); } - tracing::info!( - "backfilled {count} new db records since snapshot epoch, approximate heap size: {}, took {}", - human_bytes::human_bytes(approximate_heap_size as f64), - humantime::format_duration(start.elapsed()) - ); + size + }; + let start = Instant::now(); + if let Err(e) = db.put_many_keyed(mem_db) { + tracing::warn!("{e}"); } - match ( - self.memory_db_head_key.write().take(), - self.exported_head_key.write().take(), - ) { - (Some(head_key), _) if Tipset::load_required(&db, &head_key).is_ok() => { - let _ = db.set_heaviest_tipset_key(&head_key); - tracing::info!("set memory db head key"); - } - (_, Some(head_key)) => { - let _ = db.set_heaviest_tipset_key(&head_key); - tracing::info!("set exported head key"); - } - _ => {} + tracing::info!( + "backfilled {count} new db records since snapshot epoch, approximate heap size: {}, took {}", + human_bytes::human_bytes(approximate_heap_size as f64), + humantime::format_duration(start.elapsed()) + ); + } + match ( + self.memory_db_head_key.write().take(), + self.exported_head_key.write().take(), + ) { + (Some(head_key), _) if Tipset::load_required(&db, &head_key).is_ok() => { + let _ = db.set_heaviest_tipset_key(&head_key); + tracing::info!("set memory db head key"); + } + (_, Some(head_key)) => { + let _ = db.set_heaviest_tipset_key(&head_key); + tracing::info!("set exported head key"); } + _ => {} } } } diff --git a/src/db/mod.rs b/src/db/mod.rs index afdc693dae8e..9712dfab063b 100644 --- a/src/db/mod.rs +++ b/src/db/mod.rs @@ -49,6 +49,7 @@ pub trait SettingsStore { fn exists(&self, key: &str) -> anyhow::Result; /// Returns all setting keys. + #[allow(dead_code)] fn setting_keys(&self) -> anyhow::Result>; } @@ -113,6 +114,7 @@ pub trait EthMappingsStore { fn write_bin(&self, key: &EthHash, value: &[u8]) -> anyhow::Result<()>; /// Returns `Ok(true)` if key exists in store. + #[allow(dead_code)] fn exists(&self, key: &EthHash) -> anyhow::Result; /// Returns all message CIDs with their timestamp. @@ -194,6 +196,7 @@ pub trait IndicesStore { fn write_bin(&self, key: &Cid, value: &[u8]) -> anyhow::Result<()>; + #[allow(dead_code)] fn exists(&self, key: &Cid) -> anyhow::Result; } diff --git a/src/key_management/wallet.rs b/src/key_management/wallet.rs index 14e18f12609e..34e37970df56 100644 --- a/src/key_management/wallet.rs +++ b/src/key_management/wallet.rs @@ -179,10 +179,10 @@ pub fn list_addrs(keystore: &KeyStore) -> Result, Error> { all.sort(); let mut out = Vec::new(); for i in all { - if let Some(addr_str) = i.strip_prefix("wallet-") { - if let Ok(addr) = Address::from_str(addr_str) { - out.push(addr); - } + if let Some(addr_str) = i.strip_prefix("wallet-") + && let Ok(addr) = Address::from_str(addr_str) + { + out.push(addr); } } Ok(out) @@ -202,12 +202,12 @@ pub fn remove_key(addr: &Address, keystore: &mut KeyStore) -> Result<(), Error> let deleted_keyinfo = keystore .remove(&key_string) .map_err(|_| Error::KeyNotExists)?; - if let Ok(default_keyinfo) = keystore.get("default") { - if default_keyinfo == deleted_keyinfo { - keystore - .remove("default") - .map_err(|_| Error::KeyNotExists)?; - } + if let Ok(default_keyinfo) = keystore.get("default") + && default_keyinfo == deleted_keyinfo + { + keystore + .remove("default") + .map_err(|_| Error::KeyNotExists)?; } println!("wallet {addr} deleted"); Ok(()) diff --git a/src/libp2p/chain_exchange/behaviour.rs b/src/libp2p/chain_exchange/behaviour.rs index b17c04cc98fe..a57631fc4140 100644 --- a/src/libp2p/chain_exchange/behaviour.rs +++ b/src/libp2p/chain_exchange/behaviour.rs @@ -73,14 +73,14 @@ impl ChainExchangeBehaviour { pub fn on_outbound_error(&mut self, request_id: &OutboundRequestId, error: OutboundFailure) { self.track_metrics(); - if let Some(tx) = self.response_channels.remove(request_id) { - if let Err(err) = tx.send(Err(error.into())) { - // Demoting log level here because the same request might be sent to multiple - // remote peers simultaneously, it's expected that outbound failures that happen - // after receiving the first successful response could be sent to a closed - // channel. - debug!("{err}"); - } + if let Some(tx) = self.response_channels.remove(request_id) + && let Err(err) = tx.send(Err(error.into())) + { + // Demoting log level here because the same request might be sent to multiple + // remote peers simultaneously, it's expected that outbound failures that happen + // after receiving the first successful response could be sent to a closed + // channel. + debug!("{err}"); } } diff --git a/src/libp2p/hello/behaviour.rs b/src/libp2p/hello/behaviour.rs index d4552e4320a2..dc491997994a 100644 --- a/src/libp2p/hello/behaviour.rs +++ b/src/libp2p/hello/behaviour.rs @@ -156,11 +156,11 @@ impl NetworkBehaviour for HelloBehaviour { } fn on_swarm_event(&mut self, event: FromSwarm) { - if let FromSwarm::ConnectionEstablished(e) = &event { - if e.other_established == 0 { - self.pending_inbound_hello_peers - .insert(e.peer_id, Instant::now()); - } + if let FromSwarm::ConnectionEstablished(e) = &event + && e.other_established == 0 + { + self.pending_inbound_hello_peers + .insert(e.peer_id, Instant::now()); } self.inner.on_swarm_event(event) diff --git a/src/libp2p/peer_manager.rs b/src/libp2p/peer_manager.rs index a855472da834..4d7c7c738d2a 100644 --- a/src/libp2p/peer_manager.rs +++ b/src/libp2p/peer_manager.rs @@ -255,10 +255,10 @@ impl PeerManager { let now = Instant::now(); for (peer, expiration) in self.peer_ban_list.read().await.iter() { - if let Some(expiration) = expiration { - if &now > expiration { - unban_list.push(*peer); - } + if let Some(expiration) = expiration + && &now > expiration + { + unban_list.push(*peer); } } if !unban_list.is_empty() { diff --git a/src/libp2p/service.rs b/src/libp2p/service.rs index e81b9d62e6cd..0749b65ebbdd 100644 --- a/src/libp2p/service.rs +++ b/src/libp2p/service.rs @@ -239,11 +239,10 @@ where address, listener_id, } = swarm.select_next_some().await + && id == listener_id { - if id == listener_id { - info!("p2p peer is now listening on: {address}"); - break; - } + info!("p2p peer is now listening on: {address}"); + break; } }, Err(err) => error!("Fail to listen on {addr}: {err}"), diff --git a/src/libp2p_bitswap/request_manager.rs b/src/libp2p_bitswap/request_manager.rs index ed81416e329e..0a5225d87441 100644 --- a/src/libp2p_bitswap/request_manager.rs +++ b/src/libp2p_bitswap/request_manager.rs @@ -149,10 +149,10 @@ impl BitswapRequestManager { metrics::message_counter_get_block_failure().inc(); } - if let Some(responder) = responder { - if let Err(e) = responder.send_async(success).await { - debug!("{e}"); - } + if let Some(responder) = responder + && let Err(e) = responder.send_async(success).await + { + debug!("{e}"); } metrics::GET_BLOCK_TIME.observe((Instant::now() - start).as_secs_f64()); @@ -221,11 +221,9 @@ impl BitswapRequestManager { } } - if !success { - if let Ok(data) = block_saved_rx.recv_deadline(deadline) { - success = true; - block_data = data; - } + if !success && let Ok(data) = block_saved_rx.recv_deadline(deadline) { + success = true; + block_data = data; } if let Some(data) = block_data { diff --git a/src/lotus_json/ipld.rs b/src/lotus_json/ipld.rs index bf28a57754ab..91a6c68c6ab9 100644 --- a/src/lotus_json/ipld.rs +++ b/src/lotus_json/ipld.rs @@ -226,37 +226,37 @@ impl<'de> de::Visitor<'de> for JSONVisitor { map.insert(key, value); } - if map.len() == 1 { - if let Some(v) = map.get("/") { - match v { - Ipld::String(s) => { - // { "/": ".." } Json block is a Cid - return Ok(Ipld::Link(s.parse().map_err(de::Error::custom)?)); + if map.len() == 1 + && let Some(v) = map.get("/") + { + match v { + Ipld::String(s) => { + // { "/": ".." } Json block is a Cid + return Ok(Ipld::Link(s.parse().map_err(de::Error::custom)?)); + } + Ipld::Map(obj) => { + if let Some(Ipld::String(s)) = obj.get(BYTES_JSON_KEY) { + // { "/": { "bytes": "" } } Json block are bytes encoded + let (_, bz) = + multibase::decode(s).map_err(|e| de::Error::custom(e.to_string()))?; + return Ok(Ipld::Bytes(bz)); + } + if let Some(Ipld::String(s)) = obj.get(INT_JSON_KEY) { + // { "/": { "int": "i128" } } + let s = s + .parse::() + .map_err(|e| de::Error::custom(e.to_string()))?; + return Ok(Ipld::Integer(s)); } - Ipld::Map(obj) => { - if let Some(Ipld::String(s)) = obj.get(BYTES_JSON_KEY) { - // { "/": { "bytes": "" } } Json block are bytes encoded - let (_, bz) = multibase::decode(s) - .map_err(|e| de::Error::custom(e.to_string()))?; - return Ok(Ipld::Bytes(bz)); - } - if let Some(Ipld::String(s)) = obj.get(INT_JSON_KEY) { - // { "/": { "int": "i128" } } - let s = s - .parse::() - .map_err(|e| de::Error::custom(e.to_string()))?; - return Ok(Ipld::Integer(s)); - } - if let Some(Ipld::String(s)) = obj.get(FLOAT_JSON_KEY) { - // { "/": { "float": "f64" } } - let s = s - .parse::() - .map_err(|e| de::Error::custom(e.to_string()))?; - return Ok(Ipld::Float(s)); - } + if let Some(Ipld::String(s)) = obj.get(FLOAT_JSON_KEY) { + // { "/": { "float": "f64" } } + let s = s + .parse::() + .map_err(|e| de::Error::custom(e.to_string()))?; + return Ok(Ipld::Float(s)); } - _ => (), } + _ => (), } } diff --git a/src/message_pool/msg_chain.rs b/src/message_pool/msg_chain.rs index 2bf5332f68cd..0cbd76d4b2f6 100644 --- a/src/message_pool/msg_chain.rs +++ b/src/message_pool/msg_chain.rs @@ -313,16 +313,16 @@ impl MsgChainNode { pub fn set_eff_perf(&mut self, prev: Option<(f64, u64)>) { let mut eff_perf = self.gas_perf * self.bp; - if let Some(prev) = prev { - if eff_perf > 0.0 { - let prev_eff_perf = prev.0; - let prev_gas_limit = prev.1; - let eff_perf_with_parent = (eff_perf * self.gas_limit as f64 - + prev_eff_perf * prev_gas_limit as f64) - / (self.gas_limit + prev_gas_limit) as f64; - self.parent_offset = eff_perf - eff_perf_with_parent; - eff_perf = eff_perf_with_parent; - } + if let Some(prev) = prev + && eff_perf > 0.0 + { + let prev_eff_perf = prev.0; + let prev_gas_limit = prev.1; + let eff_perf_with_parent = (eff_perf * self.gas_limit as f64 + + prev_eff_perf * prev_gas_limit as f64) + / (self.gas_limit + prev_gas_limit) as f64; + self.parent_offset = eff_perf - eff_perf_with_parent; + eff_perf = eff_perf_with_parent; } self.eff_perf = eff_perf; } diff --git a/src/rpc/methods/chain.rs b/src/rpc/methods/chain.rs index 1d7a7ae53cc8..f848880b861f 100644 --- a/src/rpc/methods/chain.rs +++ b/src/rpc/methods/chain.rs @@ -100,15 +100,15 @@ pub(crate) fn logs( HeadChange::Apply(ts) => { match eth_logs_with_filter(&ctx, &ts, filter.clone(), None).await { Ok(logs) => { - if !logs.is_empty() { - if let Err(e) = sender.send(logs) { - tracing::error!( - "Failed to send logs for tipset {}: {}", - ts.key(), - e - ); - break; - } + if !logs.is_empty() + && let Err(e) = sender.send(logs) + { + tracing::error!( + "Failed to send logs for tipset {}: {}", + ts.key(), + e + ); + break; } } Err(e) => { @@ -492,14 +492,13 @@ impl RpcMethod<2> for ChainStatObj { stats.links += 1; stats.size += data.len(); } - if matches!(link_cid.codec(), fvm_ipld_encoding::DAG_CBOR) { - if let Ok(ipld) = + if matches!(link_cid.codec(), fvm_ipld_encoding::DAG_CBOR) + && let Ok(ipld) = crate::utils::encoding::from_slice_with_fallback::(&data) - { - for ipld in DfsIter::new(ipld) { - if let Ipld::Link(cid) = ipld { - queue.push_back(cid); - } + { + for ipld in DfsIter::new(ipld) { + if let Ipld::Link(cid) = ipld { + queue.push_back(cid); } } } diff --git a/src/rpc/methods/eth.rs b/src/rpc/methods/eth.rs index 83ee71bfbd19..a6f24f1863dc 100644 --- a/src/rpc/methods/eth.rs +++ b/src/rpc/methods/eth.rs @@ -1143,19 +1143,18 @@ fn eth_tx_from_native_message( // We try to decode the input as an EVM method invocation and/or a contract creation. If // that fails, we encode the "native" parameters as Solidity ABI. let input = 'decode: { - if msg.method_num() == EVMMethod::InvokeContract as MethodNum - || msg.method_num() == EAMMethod::CreateExternal as MethodNum + if (msg.method_num() == EVMMethod::InvokeContract as MethodNum + || msg.method_num() == EAMMethod::CreateExternal as MethodNum) + && let Ok(buffer) = decode_payload(msg.params(), codec) { - if let Ok(buffer) = decode_payload(msg.params(), codec) { - // If this is a valid "create external", unset the "to" address. - if msg.method_num() == EAMMethod::CreateExternal as MethodNum { - to = None; - } - break 'decode buffer; + // If this is a valid "create external", unset the "to" address. + if msg.method_num() == EAMMethod::CreateExternal as MethodNum { + to = None; } - // Yeah, we're going to ignore errors here because the user can send whatever they - // want and may send garbage. + break 'decode buffer; } + // Yeah, we're going to ignore errors here because the user can send whatever they + // want and may send garbage. encode_filecoin_params_as_abi(msg.method_num(), codec, msg.params())? }; @@ -1507,15 +1506,14 @@ async fn get_block_receipts( block_param, ResolveNullTipset::TakeOlder, )?; - if let Some(limit) = limit { - if limit > LOOKBACK_NO_LIMIT - && ts.epoch() < ctx.chain_store().heaviest_tipset().epoch() - limit - { - bail!( - "tipset {} is older than the allowed lookback limit", - ts.key().format_lotus() - ); - } + if let Some(limit) = limit + && limit > LOOKBACK_NO_LIMIT + && ts.epoch() < ctx.chain_store().heaviest_tipset().epoch() - limit + { + bail!( + "tipset {} is older than the allowed lookback limit", + ts.key().format_lotus() + ); } let ts_ref = Arc::new(ts); let ts_key = ts_ref.key(); @@ -2240,10 +2238,10 @@ impl RpcMethod<2> for EthGetTransactionCount { (sender, block_param): Self::Params, ) -> Result { let addr = sender.to_filecoin_address()?; - if let BlockNumberOrHash::PredefinedBlock(ref predefined) = block_param { - if *predefined == Predefined::Pending { - return Ok(EthUint64(ctx.mpool.get_sequence(&addr)?)); - } + if let BlockNumberOrHash::PredefinedBlock(ref predefined) = block_param + && *predefined == Predefined::Pending + { + return Ok(EthUint64(ctx.mpool.get_sequence(&addr)?)); } let ts = tipset_by_block_number_or_hash( ctx.chain_store(), @@ -2507,19 +2505,19 @@ impl RpcMethod<1> for EthGetTransactionHashByCid { ) -> Result { let smsgs_result: Result, crate::chain::Error> = crate::chain::messages_from_cids(ctx.store(), &[cid]); - if let Ok(smsgs) = smsgs_result { - if let Some(smsg) = smsgs.first() { - let hash = if smsg.is_delegated() { - let chain_id = ctx.chain_config().eth_chain_id; - let (_, tx) = eth_tx_from_signed_eth_message(smsg, chain_id)?; - tx.eth_hash()?.into() - } else if smsg.is_secp256k1() { - smsg.cid().into() - } else { - smsg.message().cid().into() - }; - return Ok(Some(hash)); - } + if let Ok(smsgs) = smsgs_result + && let Some(smsg) = smsgs.first() + { + let hash = if smsg.is_delegated() { + let chain_id = ctx.chain_config().eth_chain_id; + let (_, tx) = eth_tx_from_signed_eth_message(smsg, chain_id)?; + tx.eth_hash()?.into() + } else if smsg.is_secp256k1() { + smsg.cid().into() + } else { + smsg.message().cid().into() + }; + return Ok(Some(hash)); } let msg_result = crate::chain::get_chain_message(ctx.store(), &cid); @@ -3497,10 +3495,10 @@ async fn trace_filter( .match_filter_criteria(&filter.from_address, &filter.to_address)? { trace_counter += 1; - if let Some(after) = filter.after.clone() { - if trace_counter <= after.0 { - continue; - } + if let Some(after) = filter.after.clone() + && trace_counter <= after.0 + { + continue; } results.insert(block_trace); diff --git a/src/rpc/methods/eth/filter/mod.rs b/src/rpc/methods/eth/filter/mod.rs index 3594c4cf0b74..f4c79e474a4f 100644 --- a/src/rpc/methods/eth/filter/mod.rs +++ b/src/rpc/methods/eth/filter/mod.rs @@ -160,14 +160,14 @@ impl EthEventHandler { .install(pf) .context("Installation error")?; - if let Some(filter_store) = &self.filter_store { - if let Err(err) = filter_store.add(filter.clone()) { - ensure!( - event_filter_manager.remove(filter.id()).is_some(), - "Filter not found" - ); - bail!("Adding filter failed: {}", err); - } + if let Some(filter_store) = &self.filter_store + && let Err(err) = filter_store.add(filter.clone()) + { + ensure!( + event_filter_manager.remove(filter.id()).is_some(), + "Filter not found" + ); + bail!("Adding filter failed: {}", err); } Ok(filter.id().clone()) } else { @@ -181,11 +181,11 @@ impl EthEventHandler { ) -> Result { if let Some(manager) = filter_manager { let filter = manager.install().context("Installation error")?; - if let Some(filter_store) = &self.filter_store { - if let Err(err) = filter_store.add(filter.clone()) { - ensure!(manager.remove(filter.id()).is_some(), "Filter not found"); - bail!("Adding filter failed: {}", err); - } + if let Some(filter_store) = &self.filter_store + && let Err(err) = filter_store.add(filter.clone()) + { + ensure!(manager.remove(filter.id()).is_some(), "Filter not found"); + bail!("Adding filter failed: {}", err); } Ok(filter.id().clone()) } else { diff --git a/src/rpc/methods/eth/trace.rs b/src/rpc/methods/eth/trace.rs index 642dc8d2a108..fcb948ad9ae5 100644 --- a/src/rpc/methods/eth/trace.rs +++ b/src/rpc/methods/eth/trace.rs @@ -45,10 +45,10 @@ pub fn base_environment( } fn trace_to_address(trace: &ActorTrace) -> EthAddress { - if let Some(addr) = trace.state.delegated_address { - if let Ok(eth_addr) = EthAddress::from_filecoin_address(&addr.into()) { - return eth_addr; - } + if let Some(addr) = trace.state.delegated_address + && let Ok(eth_addr) = EthAddress::from_filecoin_address(&addr.into()) + { + return eth_addr; } EthAddress::from_actor_id(trace.id) } @@ -550,11 +550,11 @@ fn trace_evm_private( // DELEGATECALL any non-EVM actor, but there's no need to encode that fact // here in case we decide to loosen this up in the future. env.last_byte_code = None; - if trace.msg_rct.exit_code.is_success() { - if let Option::Some(actor_trace) = &trace.invoked_actor { - let to = trace_to_address(actor_trace); - env.last_byte_code = Some(to); - } + if trace.msg_rct.exit_code.is_success() + && let Option::Some(actor_trace) = &trace.invoked_actor + { + let to = trace_to_address(actor_trace); + env.last_byte_code = Some(to); } Ok((None, None)) } diff --git a/src/rpc/methods/eth/types.rs b/src/rpc/methods/eth/types.rs index 29087f9a67cb..98c442715b2f 100644 --- a/src/rpc/methods/eth/types.rs +++ b/src/rpc/methods/eth/types.rs @@ -734,17 +734,19 @@ impl EthTrace { }; // Match FromAddress - if let Some(from_addresses) = from_decoded_addresses { - if !from_addresses.is_empty() && !from_addresses.contains(&trace_from) { - return Ok(false); - } + if let Some(from_addresses) = from_decoded_addresses + && !from_addresses.is_empty() + && !from_addresses.contains(&trace_from) + { + return Ok(false); } // Match ToAddress - if let Some(to_addresses) = to_decoded_addresses { - if !to_addresses.is_empty() && !trace_to.is_some_and(|to| to_addresses.contains(&to)) { - return Ok(false); - } + if let Some(to_addresses) = to_decoded_addresses + && !to_addresses.is_empty() + && !trace_to.is_some_and(|to| to_addresses.contains(&to)) + { + return Ok(false); } Ok(true) diff --git a/src/rpc/methods/eth/utils.rs b/src/rpc/methods/eth/utils.rs index 09db9e0f511f..1b33d5a53177 100644 --- a/src/rpc/methods/eth/utils.rs +++ b/src/rpc/methods/eth/utils.rs @@ -23,10 +23,10 @@ pub fn lookup_eth_address( state: &StateTree, ) -> Result> { // Attempt to convert directly, if it's an f4 address. - if let Ok(eth_addr) = EthAddress::from_filecoin_address(addr) { - if !eth_addr.is_masked_id() { - return Ok(Some(eth_addr)); - } + if let Ok(eth_addr) = EthAddress::from_filecoin_address(addr) + && !eth_addr.is_masked_id() + { + return Ok(Some(eth_addr)); } // Otherwise, resolve the ID addr. @@ -39,11 +39,11 @@ pub fn lookup_eth_address( let result = state.get_actor(addr); if let Ok(Some(actor_state)) = result { if let Some(addr) = actor_state.delegated_address { - if let Ok(eth_addr) = EthAddress::from_filecoin_address(&addr.into()) { - if !eth_addr.is_masked_id() { - // Conversable into an eth address, use it. - return Ok(Some(eth_addr)); - } + if let Ok(eth_addr) = EthAddress::from_filecoin_address(&addr.into()) + && !eth_addr.is_masked_id() + { + // Conversable into an eth address, use it. + return Ok(Some(eth_addr)); } } else { // No delegated address -> use a masked ID address diff --git a/src/rpc/methods/state.rs b/src/rpc/methods/state.rs index a15e9d0dae4f..2c3502e9b356 100644 --- a/src/rpc/methods/state.rs +++ b/src/rpc/methods/state.rs @@ -1357,10 +1357,10 @@ impl RpcMethod<2> for StateFetchRoot { } while let Some(cid) = to_be_fetched.pop() { - if task_set.len() == MAX_CONCURRENT_REQUESTS { - if let Some(ret) = task_set.join_next().await { - handle_worker(&mut fetched, &mut failures, ret?) - } + if task_set.len() == MAX_CONCURRENT_REQUESTS + && let Some(ret) = task_set.join_next().await + { + handle_worker(&mut fetched, &mut failures, ret?) } task_set.spawn_blocking({ let network_send = network_send.clone(); @@ -2449,10 +2449,10 @@ impl RpcMethod<3> for StateListMessages { if ctx.state_manager.lookup_id(&to, ts.as_ref())?.is_none() { return Ok(vec![]); } - } else if let Some(from) = from_to.from { - if ctx.state_manager.lookup_id(&from, ts.as_ref())?.is_none() { - return Ok(vec![]); - } + } else if let Some(from) = from_to.from + && ctx.state_manager.lookup_id(&from, ts.as_ref())?.is_none() + { + return Ok(vec![]); } let mut out = Vec::new(); diff --git a/src/rpc/registry/actors_reg.rs b/src/rpc/registry/actors_reg.rs index 53f13a0ba11a..83225e76b472 100644 --- a/src/rpc/registry/actors_reg.rs +++ b/src/rpc/registry/actors_reg.rs @@ -244,8 +244,8 @@ mod test { // Some actors might fail due to state format issues, but the function // should at least recognize the actor type and attempt to load it - if result.is_err() { - let error_msg = result.unwrap_err().to_string(); + if let Err(e) = result { + let error_msg = e.to_string(); // Should not be "unknown actor" or "no serializer" errors assert!( !error_msg.contains("Unknown actor code CID") diff --git a/src/rpc/registry/methods_reg.rs b/src/rpc/registry/methods_reg.rs index eccfe1d75818..cb9a05bf3e8c 100644 --- a/src/rpc/registry/methods_reg.rs +++ b/src/rpc/registry/methods_reg.rs @@ -269,8 +269,8 @@ mod test { // returning the "no deserializer registered" error let result = deserialize_params(&actor_cid, constructor_method, &[]); - if result.is_err() { - let error_msg = result.unwrap_err().to_string(); + if let Err(e) = result { + let error_msg = e.to_string(); assert!( !error_msg.contains("No deserializer registered"), "Actor type {actor_type:?} should have methods registered but got error: {error_msg}" diff --git a/src/rpc/types/mod.rs b/src/rpc/types/mod.rs index 1e1ae85aedd8..e198abd27fa6 100644 --- a/src/rpc/types/mod.rs +++ b/src/rpc/types/mod.rs @@ -459,16 +459,16 @@ pub struct MessageFilter { impl MessageFilter { pub fn matches(&self, msg: &Message) -> bool { - if let Some(from) = &self.from { - if from != &msg.from { - return false; - } + if let Some(from) = &self.from + && from != &msg.from + { + return false; } - if let Some(to) = &self.to { - if to != &msg.to { - return false; - } + if let Some(to) = &self.to + && to != &msg.to + { + return false; } true diff --git a/src/shim/executor.rs b/src/shim/executor.rs index 5547e436b693..a1a98b5c5719 100644 --- a/src/shim/executor.rs +++ b/src/shim/executor.rs @@ -180,10 +180,10 @@ impl Receipt { i: u64, ) -> anyhow::Result> { // Try Receipt_v4 first. (Receipt_v4 and Receipt_v3 are identical, use v4 here) - if let Ok(amt) = Amtv0::load(receipts, db) { - if let Ok(receipts) = amt.get(i) { - return Ok(receipts.cloned().map(Receipt::V4)); - } + if let Ok(amt) = Amtv0::load(receipts, db) + && let Ok(receipts) = amt.get(i) + { + return Ok(receipts.cloned().map(Receipt::V4)); } // Fallback to Receipt_v2. diff --git a/src/shim/machine/manifest.rs b/src/shim/machine/manifest.rs index 98ddad652068..d93eec69056c 100644 --- a/src/shim/machine/manifest.rs +++ b/src/shim/machine/manifest.rs @@ -194,6 +194,7 @@ macro_rules! exhaustive { ($vis:vis const $ident:ident: &[$ty:ty] = &[$($variant:path),* $(,)?];) => { $vis const $ident: &[$ty] = &[$($variant,)*]; const _: () = { + #[allow(dead_code)] fn check_exhaustive(it: $ty) { match it { $( diff --git a/src/shim/state_tree.rs b/src/shim/state_tree.rs index 707583f75ec4..e11a66e38390 100644 --- a/src/shim/state_tree.rs +++ b/src/shim/state_tree.rs @@ -361,10 +361,10 @@ where // A workaround to implement `if state.Version() >= types.StateTreeVersion5` // When state tree version is not available in rust APIs - if !matches!(self, Self::FvmV2(_) | Self::V0(_)) { - if let Some(address) = actor.delegated_address { - return Ok(address.into()); - } + if !matches!(self, Self::FvmV2(_) | Self::V0(_)) + && let Some(address) = actor.delegated_address + { + return Ok(address.into()); } let account_state = account::State::load(store, actor.code, actor.state)?; diff --git a/src/state_manager/mod.rs b/src/state_manager/mod.rs index e138d9fdae56..a4503a85444f 100644 --- a/src/state_manager/mod.rs +++ b/src/state_manager/mod.rs @@ -448,11 +448,11 @@ where .insert_events(key, events_data); } - if let Ok(receipts) = Receipt::get_receipts(self.blockstore(), state_output.receipt_root) { - if !receipts.is_empty() { - self.receipt_event_cache_handler - .insert_receipt(key, receipts); - } + if let Ok(receipts) = Receipt::get_receipts(self.blockstore(), state_output.receipt_root) + && !receipts.is_empty() + { + self.receipt_event_cache_handler + .insert_receipt(key, receipts); } } @@ -748,12 +748,12 @@ where } }; let result = self.compute_tipset_state_blocking(ts, Some(callback), VMTrace::Traced); - if let Err(error_message) = result { - if error_message.to_string() != REPLAY_HALT { - return Err(Error::Other(format!( - "unexpected error during execution : {error_message:}" - ))); - } + if let Err(error_message) = result + && error_message.to_string() != REPLAY_HALT + { + return Err(Error::Other(format!( + "unexpected error during execution : {error_message:}" + ))); } api_invoc_result.ok_or_else(|| Error::Other("failed to replay".into())) } @@ -1599,12 +1599,10 @@ where // First try to resolve the actor in the parent state, so we don't have to compute anything. if let Ok(state) = StateTree::new_from_root(self.chain_store().db.clone(), ts.parent_state()) - { - if let Ok(address) = state + && let Ok(address) = state .resolve_to_deterministic_addr(self.chain_store().blockstore(), address) - { - return Ok(address); - } + { + return Ok(address); } // If that fails, compute the tip-set and try again. diff --git a/src/statediff/resolve.rs b/src/statediff/resolve.rs index ced878b40f32..904678aecd1d 100644 --- a/src/statediff/resolve.rs +++ b/src/statediff/resolve.rs @@ -46,11 +46,11 @@ where } } Ipld::Link(cid) => { - if cid.codec() == DAG_CBOR { - if let Some(mut x) = bs.get_cbor(cid)? { - resolve_ipld(bs, &mut x, depth)?; - *ipld = x; - } + if cid.codec() == DAG_CBOR + && let Some(mut x) = bs.get_cbor(cid)? + { + resolve_ipld(bs, &mut x, depth)?; + *ipld = x; } } _ => (), diff --git a/src/tool/subcommands/api_cmd/test_snapshot.rs b/src/tool/subcommands/api_cmd/test_snapshot.rs index d6dca321f617..83a59ed437e8 100644 --- a/src/tool/subcommands/api_cmd/test_snapshot.rs +++ b/src/tool/subcommands/api_cmd/test_snapshot.rs @@ -52,18 +52,18 @@ pub struct RpcTestSnapshot { fn backfill_eth_mappings(db: &MemoryDB, index: Option) -> anyhow::Result<()> { if let Some(index) = index { - if let Some(mut guard) = db.eth_mappings_db.try_write() { - if let Some(eth_mappings) = index.eth_mappings { - for (k, v) in eth_mappings.iter() { - guard.insert(EthHash::from_str(k)?, v.0.clone()); - } + if let Some(mut guard) = db.eth_mappings_db.try_write() + && let Some(eth_mappings) = index.eth_mappings + { + for (k, v) in eth_mappings.iter() { + guard.insert(EthHash::from_str(k)?, v.0.clone()); } } - if let Some(mut guard) = db.indices_db.try_write() { - if let Some(indices) = index.indices { - for (k, v) in indices.iter() { - guard.insert(Cid::from_str(k)?, v.0.clone()); - } + if let Some(mut guard) = db.indices_db.try_write() + && let Some(indices) = index.indices + { + for (k, v) in indices.iter() { + guard.insert(Cid::from_str(k)?, v.0.clone()); } } } diff --git a/src/utils/io/writer_checksum.rs b/src/utils/io/writer_checksum.rs index 1b6cc806c442..d13952877d29 100644 --- a/src/utils/io/writer_checksum.rs +++ b/src/utils/io/writer_checksum.rs @@ -32,13 +32,12 @@ impl AsyncWrite for AsyncWriterWithChecksum { let mut this = self.project(); let w = this.inner.poll_write(cx, buf); - if let Some(hasher) = &mut this.hasher { - if let Poll::Ready(Ok(size)) = w { - if size > 0 { - #[allow(clippy::indexing_slicing)] - hasher.update(&buf[..size]); - } - } + if let Some(hasher) = &mut this.hasher + && let Poll::Ready(Ok(size)) = w + && size > 0 + { + #[allow(clippy::indexing_slicing)] + hasher.update(&buf[..size]); } w } diff --git a/src/utils/misc/adaptive_value_provider.rs b/src/utils/misc/adaptive_value_provider.rs index 350fb4eb3f79..2d0ef57118cc 100644 --- a/src/utils/misc/adaptive_value_provider.rs +++ b/src/utils/misc/adaptive_value_provider.rs @@ -34,10 +34,10 @@ impl ExponentialAdaptiveValueProvider { return false; } let new_value = current.shl(1).min(self.max); - if let Some(record) = record { - if record < new_value { - return false; - } + if let Some(record) = record + && record < new_value + { + return false; } *self.value.write() = new_value; true @@ -49,10 +49,10 @@ impl ExponentialAdaptiveValueProvider { return false; } let new_value = current.shr(1).max(self.min); - if let Some(record) = record { - if record > new_value { - return false; - } + if let Some(record) = record + && record > new_value + { + return false; } *self.value.write() = new_value; true diff --git a/src/utils/net/download_file.rs b/src/utils/net/download_file.rs index 08b8c70b79d5..d290f7261a3f 100644 --- a/src/utils/net/download_file.rs +++ b/src/utils/net/download_file.rs @@ -34,10 +34,10 @@ pub async fn download_file_with_cache( ) -> anyhow::Result { let cache_file_path = cache_dir.join(url.path().strip_prefix('/').unwrap_or_else(|| url.path())); - if let Some(cache_file_dir) = cache_file_path.parent() { - if !cache_file_dir.is_dir() { - std::fs::create_dir_all(cache_file_dir)?; - } + if let Some(cache_file_dir) = cache_file_path.parent() + && !cache_file_dir.is_dir() + { + std::fs::create_dir_all(cache_file_dir)?; } let cache_hit = match get_file_md5_hash(&cache_file_path) { diff --git a/tests/lints/mod.rs b/tests/lints/mod.rs index 0a41f37261a7..e68924c89760 100644 --- a/tests/lints/mod.rs +++ b/tests/lints/mod.rs @@ -84,14 +84,13 @@ impl<'ast> Visit<'ast> for NoTestsWithReturn { if i.attrs .iter() .any(|attr| attr == &parse_quote!(#[test]) || attr == &parse_quote!(#[tokio::test])) + && let ReturnType::Type(..) = i.sig.output { - if let ReturnType::Type(..) = i.sig.output { - self.violations.push( - Violation::new(&i.sig.output) - .with_message("not allowed to have a return type") - .with_color(Color::Red), - ) - } + self.violations.push( + Violation::new(&i.sig.output) + .with_message("not allowed to have a return type") + .with_color(Color::Red), + ) } visit::visit_item_fn(self, i) } @@ -131,23 +130,22 @@ pub struct SpecializedAssertions { impl<'ast> Visit<'ast> for SpecializedAssertions { fn visit_macro(&mut self, i: &'ast Macro) { - if i.path.is_ident("assert") { - if let Ok(exprs) = i.parse_body_with(Punctuated::::parse_terminated) { - if let Some(Expr::Binary(binary)) = exprs.first() { - match binary.op { - BinOp::Eq(_) => self.violations.push( - Violation::new(i) - .with_message("should be `assert_eq(..)`") - .with_color(Color::Red), - ), - BinOp::Ne(_) => self.violations.push( - Violation::new(i) - .with_message("should be `assert_ne(..)`") - .with_color(Color::Red), - ), - _ => {} - } - } + if i.path.is_ident("assert") + && let Ok(exprs) = i.parse_body_with(Punctuated::::parse_terminated) + && let Some(Expr::Binary(binary)) = exprs.first() + { + match binary.op { + BinOp::Eq(_) => self.violations.push( + Violation::new(i) + .with_message("should be `assert_eq(..)`") + .with_color(Color::Red), + ), + BinOp::Ne(_) => self.violations.push( + Violation::new(i) + .with_message("should be `assert_ne(..)`") + .with_color(Color::Red), + ), + _ => {} } } visit::visit_macro(self, i)