diff --git a/.github/workflows/ci_aarch64_build_ubuntu.yaml b/.github/workflows/ci_aarch64_build_ubuntu.yaml index 04cf92e5cf..7cc4958a8f 100644 --- a/.github/workflows/ci_aarch64_build_ubuntu.yaml +++ b/.github/workflows/ci_aarch64_build_ubuntu.yaml @@ -38,7 +38,7 @@ jobs: ci-aarch64-cargo- - uses: dtolnay/rust-toolchain@master with: - toolchain: 1.85.0 + toolchain: 1.92.0 components: rustfmt - run: sudo apt-get update && sudo apt-get install -y libssl-dev pkg-config libclang-dev build-essential - name: Build for aarch64 diff --git a/.github/workflows/ci_benchmarks_ubuntu.yaml b/.github/workflows/ci_benchmarks_ubuntu.yaml index 804c7e3e07..204102f812 100644 --- a/.github/workflows/ci_benchmarks_ubuntu.yaml +++ b/.github/workflows/ci_benchmarks_ubuntu.yaml @@ -28,7 +28,7 @@ jobs: sudo docker image prune --all --force - uses: dtolnay/rust-toolchain@master with: - toolchain: 1.85.0 + toolchain: 1.92.0 components: rustfmt, clippy - run: sudo apt-get update && sudo apt-get install -y libssl-dev pkg-config libclang-dev build-essential - uses: actions/checkout@v4 diff --git a/.github/workflows/ci_integration_tests_ubuntu.yaml b/.github/workflows/ci_integration_tests_ubuntu.yaml index c8d308f22a..fb23664b65 100644 --- a/.github/workflows/ci_integration_tests_ubuntu.yaml +++ b/.github/workflows/ci_integration_tests_ubuntu.yaml @@ -31,7 +31,7 @@ jobs: sudo docker image prune --all --force - uses: dtolnay/rust-toolchain@master with: - toolchain: 1.85.0 + toolchain: 1.92.0 components: rustfmt, clippy - run: sudo apt-get update && sudo apt-get install -y libssl-dev pkg-config libclang-dev build-essential tor - uses: actions/setup-go@v6 @@ -84,7 +84,7 @@ jobs: sudo docker image prune --all --force - uses: dtolnay/rust-toolchain@master with: - toolchain: 1.85.0 + toolchain: 1.92.0 components: rustfmt, clippy - run: sudo apt-get update && sudo apt-get install -y libssl-dev pkg-config libclang-dev build-essential procps wget - uses: actions/checkout@v4 diff --git a/.github/workflows/ci_linters_ubuntu.yaml b/.github/workflows/ci_linters_ubuntu.yaml index 3feb549dcb..fce29f6a3b 100644 --- a/.github/workflows/ci_linters_ubuntu.yaml +++ b/.github/workflows/ci_linters_ubuntu.yaml @@ -30,7 +30,7 @@ jobs: - uses: actions/checkout@v4 - uses: dtolnay/rust-toolchain@master with: - toolchain: 1.85.0 + toolchain: 1.92.0 components: rustfmt, clippy - uses: actions/setup-go@v6 with: diff --git a/.github/workflows/ci_quick_checks_ubuntu.yaml b/.github/workflows/ci_quick_checks_ubuntu.yaml index 2aacf5c80f..aa6f6c29f2 100644 --- a/.github/workflows/ci_quick_checks_ubuntu.yaml +++ b/.github/workflows/ci_quick_checks_ubuntu.yaml @@ -29,7 +29,7 @@ jobs: sudo docker image prune --all --force - uses: dtolnay/rust-toolchain@master with: - toolchain: 1.85.0 + toolchain: 1.92.0 components: rustfmt, clippy - uses: actions/setup-go@v6 with: diff --git a/.github/workflows/ci_unit_tests_ubuntu.yaml b/.github/workflows/ci_unit_tests_ubuntu.yaml index 882f3c4b18..4186bad294 100644 --- a/.github/workflows/ci_unit_tests_ubuntu.yaml +++ b/.github/workflows/ci_unit_tests_ubuntu.yaml @@ -29,7 +29,7 @@ jobs: sudo docker image prune --all --force - uses: dtolnay/rust-toolchain@master with: - toolchain: 1.85.0 + toolchain: 1.92.0 - run: sudo apt-get update && sudo apt-get install -y libssl-dev pkg-config libclang-dev build-essential - name: Install nextest uses: taiki-e/install-action@nextest diff --git a/.github/workflows/coverage_report.yaml b/.github/workflows/coverage_report.yaml index fc68cc0a4b..79ebac1f76 100644 --- a/.github/workflows/coverage_report.yaml +++ b/.github/workflows/coverage_report.yaml @@ -16,7 +16,7 @@ jobs: - uses: actions/checkout@v4 - uses: dtolnay/rust-toolchain@master with: - toolchain: 1.85.0 + toolchain: 1.92.0 components: rustfmt,llvm-tools-preview - run: sudo apt-get update && sudo apt-get install libssl-dev pkg-config libclang-dev -y && sudo apt-get install -y gcc-multilib build-essential - name: unit coverage diff --git a/.github/workflows/package.yaml b/.github/workflows/package.yaml index 29b648391a..37eb9fc74b 100644 --- a/.github/workflows/package.yaml +++ b/.github/workflows/package.yaml @@ -93,7 +93,7 @@ jobs: name: ckb_${{env.GIT_TAG_NAME }}_${{env.REL_PKG }}.asc path: ckb_${{env.GIT_TAG_NAME }}_${{env.REL_PKG }}.asc env: - BUILDER_IMAGE: nervos/ckb-docker-builder:bionic-rust-1.85.0 + BUILDER_IMAGE: nervos/ckb-docker-builder:bionic-rust-1.92.0 REL_PKG: ${{ matrix.rel_pkg }} CKB_CLI_VERSION: ${{ needs.get-ckb-cli-version.outputs.version }} @@ -181,7 +181,7 @@ jobs: name: ckb_${{env.GIT_TAG_NAME }}_${{env.REL_PKG }}.asc path: ckb_${{env.GIT_TAG_NAME }}_${{env.REL_PKG }}.asc env: - BUILDER_IMAGE: nervos/ckb-docker-builder:centos-7-rust-1.85.0 + BUILDER_IMAGE: nervos/ckb-docker-builder:centos-7-rust-1.92.0 REL_PKG: ${{ matrix.rel_pkg }} CKB_CLI_VERSION: ${{ needs.get-ckb-cli-version.outputs.version }} diff --git a/Cargo.toml b/Cargo.toml index 144531089c..4377beb71e 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -8,7 +8,7 @@ build = "build.rs" description = "CKB is the layer 1 of Nervos Network, a public/permissionless blockchain" homepage = "https://github.com/nervosnetwork/ckb" repository = "https://github.com/nervosnetwork/ckb" -rust-version = "1.85.0" +rust-version = "1.92.0" default-run = "ckb" [[bin]] diff --git a/chain/src/chain_controller.rs b/chain/src/chain_controller.rs index a44c54efa1..5bfdaa5d73 100644 --- a/chain/src/chain_controller.rs +++ b/chain/src/chain_controller.rs @@ -1,6 +1,6 @@ //! CKB chain controller. #![allow(missing_docs)] -#![allow(elided_named_lifetimes)] +#![allow(mismatched_lifetime_syntaxes)] use crate::utils::orphan_block_pool::OrphanBlockPool; use crate::{LonelyBlock, ProcessBlockRequest, RemoteBlock, TruncateRequest, VerifyResult}; diff --git a/chain/src/init_load_unverified.rs b/chain/src/init_load_unverified.rs index 6a6f8abd04..7516562f72 100644 --- a/chain/src/init_load_unverified.rs +++ b/chain/src/init_load_unverified.rs @@ -50,8 +50,8 @@ impl InitLoadUnverified { .map(|(key_number_hash, _v)| { let reader = packed::NumberHashReader::from_slice_should_be_ok(key_number_hash.as_ref()); - let unverified_block_hash = reader.block_hash().to_entity(); - unverified_block_hash + + reader.block_hash().to_entity() }) .filter(|hash| self.shared.store().get_block_ext(hash).is_none()) .collect::>(); diff --git a/chain/src/tests/basic.rs b/chain/src/tests/basic.rs index ddf277c82a..176d8d60a7 100644 --- a/chain/src/tests/basic.rs +++ b/chain/src/tests/basic.rs @@ -536,7 +536,7 @@ fn test_chain_fork_by_first_received() { chain3.gen_empty_block_with_diff(20u64, &mock_store); } - for chain in vec![chain1.clone(), chain2.clone(), chain3.clone()] { + for chain in [chain1.clone(), chain2.clone(), chain3.clone()] { for block in chain.blocks() { chain_controller .blocking_process_block_with_switch(Arc::new(block.clone()), Switch::DISABLE_ALL) diff --git a/chain/src/tests/block_assembler.rs b/chain/src/tests/block_assembler.rs index acb6ea93a7..de682c6ba8 100644 --- a/chain/src/tests/block_assembler.rs +++ b/chain/src/tests/block_assembler.rs @@ -320,7 +320,7 @@ fn test_candidate_uncles_retain() { let block1_0 = gen_block(&block0_0.header(), 12, &epoch); let block2_0 = gen_block(&block1_0.header(), 13, &epoch); - for block in vec![block1_0, block2_0.clone()] { + for block in [block1_0, block2_0.clone()] { chain_controller .blocking_process_block_with_switch(Arc::new(block), Switch::DISABLE_ALL) .unwrap(); diff --git a/chain/src/tests/delay_verify.rs b/chain/src/tests/delay_verify.rs index a2275e7344..79de5e1f73 100644 --- a/chain/src/tests/delay_verify.rs +++ b/chain/src/tests/delay_verify.rs @@ -276,7 +276,7 @@ fn test_full_dead_transaction() { let dao = dao_data( shared.consensus(), &parent, - &[cellbase_tx.clone()], + std::slice::from_ref(&cellbase_tx), &mock_store, false, ); diff --git a/chain/src/tests/load_code_with_snapshot.rs b/chain/src/tests/load_code_with_snapshot.rs index 722017dd47..29bba64aba 100644 --- a/chain/src/tests/load_code_with_snapshot.rs +++ b/chain/src/tests/load_code_with_snapshot.rs @@ -180,10 +180,10 @@ fn test_load_code_with_snapshot() { let mut counter = 0; loop { let tx_status = tx_pool.get_tx_status(tx.hash()); - if let Ok(Ok((status, _))) = tx_status { - if status == TxStatus::Pending { - break; - } + if let Ok(Ok((status, _))) = tx_status + && status == TxStatus::Pending + { + break; } // wait tx_pool if got `None` counter += 1; @@ -273,10 +273,10 @@ fn _test_load_code_with_snapshot_after_hardfork(script_type: ScriptHashType) { let mut counter = 0; loop { let tx_status = tx_pool.get_tx_status(tx.hash()); - if let Ok(Ok((status, _))) = tx_status { - if status == TxStatus::Pending { - break; - } + if let Ok(Ok((status, _))) = tx_status + && status == TxStatus::Pending + { + break; } // wait tx_pool if got `None` counter += 1; diff --git a/chain/src/verify.rs b/chain/src/verify.rs index b52178170c..ab5953a97c 100644 --- a/chain/src/verify.rs +++ b/chain/src/verify.rs @@ -245,22 +245,22 @@ impl ConsumeUnverifiedBlockProcessor { )), )?; - if let Some(ext) = self.shared.store().get_block_ext(&block.hash()) { - if let Some(verified) = ext.verified { - debug!( - "block {}-{} has been verified, previously verified result: {}", - block.number(), - block.hash(), - verified - ); - return if verified { - Ok(false) - } else { - Err(InternalErrorKind::Other - .other("block previously verified failed") - .into()) - }; - } + if let Some(ext) = self.shared.store().get_block_ext(&block.hash()) + && let Some(verified) = ext.verified + { + debug!( + "block {}-{} has been verified, previously verified result: {}", + block.number(), + block.hash(), + verified + ); + return if verified { + Ok(false) + } else { + Err(InternalErrorKind::Other + .other("block previously verified failed") + .into()) + }; } let cannon_total_difficulty = diff --git a/ckb-bin/src/setup.rs b/ckb-bin/src/setup.rs index 6ae2f60a86..3da8e1e0be 100644 --- a/ckb-bin/src/setup.rs +++ b/ckb-bin/src/setup.rs @@ -97,21 +97,19 @@ H256::from_str(&target[2..]).expect("default assume_valid_target for testnet mus }; } - if let Some(ref assume_valid_targets) = config.network.sync.assume_valid_targets { - if let Some(first_target) = assume_valid_targets.first() { - if assume_valid_targets.len() == 1 { - if first_target - == &H256::from_slice(&[0; 32]).expect("must parse Zero h256 successful") - { - info!("Disable assume valid targets since assume_valid_targets is zero"); - config.network.sync.assume_valid_targets = None; - } else { - info!( - "assume_valid_targets set to {:?}", - config.network.sync.assume_valid_targets - ); - } - } + if let Some(ref assume_valid_targets) = config.network.sync.assume_valid_targets + && let Some(first_target) = assume_valid_targets.first() + && assume_valid_targets.len() == 1 + { + if first_target == &H256::from_slice(&[0; 32]).expect("must parse Zero h256 successful") + { + info!("Disable assume valid targets since assume_valid_targets is zero"); + config.network.sync.assume_valid_targets = None; + } else { + info!( + "assume_valid_targets set to {:?}", + config.network.sync.assume_valid_targets + ); } } @@ -418,13 +416,13 @@ H256::from_str(&target[2..]).expect("default assume_valid_target for testnet mus #[cfg(feature = "with_sentry")] fn chain_spec(&self) -> Result { let result = self.config.chain_spec(); - if let Ok(spec) = &result { - if self.is_sentry_enabled { - sentry::configure_scope(|scope| { - scope.set_tag("spec.name", &spec.name); - scope.set_tag("spec.pow", &spec.pow); - }); - } + if let Ok(spec) = &result + && self.is_sentry_enabled + { + sentry::configure_scope(|scope| { + scope.set_tag("spec.name", &spec.name); + scope.set_tag("spec.pow", &spec.pow); + }); } result @@ -440,12 +438,12 @@ H256::from_str(&target[2..]).expect("default assume_valid_target for testnet mus pub fn consensus(&self) -> Result { let result = consensus_from_spec(&self.chain_spec()?); - if let Ok(consensus) = &result { - if self.is_sentry_enabled { - sentry::configure_scope(|scope| { - scope.set_tag("genesis", consensus.genesis_hash()); - }); - } + if let Ok(consensus) = &result + && self.is_sentry_enabled + { + sentry::configure_scope(|scope| { + scope.set_tag("genesis", consensus.genesis_hash()); + }); } result diff --git a/ckb-bin/src/subcommand/reset_data.rs b/ckb-bin/src/subcommand/reset_data.rs index 5e21488d96..c19c4d1859 100644 --- a/ckb-bin/src/subcommand/reset_data.rs +++ b/ckb-bin/src/subcommand/reset_data.rs @@ -36,10 +36,10 @@ pub fn reset_data(args: ResetDataArgs) -> Result<(), ExitCode> { target_files.push(args.network_secret_key_path); } - if args.logs { - if let Some(dir) = args.logs_dir { - target_dirs.push(dir); - } + if args.logs + && let Some(dir) = args.logs_dir + { + target_dirs.push(dir); } if !args.force && (!target_dirs.is_empty() || !target_files.is_empty()) { diff --git a/db-migration/src/lib.rs b/db-migration/src/lib.rs index edb2237702..28bbccfc03 100644 --- a/db-migration/src/lib.rs +++ b/db-migration/src/lib.rs @@ -138,13 +138,13 @@ impl Migrations { }; debug!("Current database version [{}]", db_version); - let migrations = self + let mut migrations = self .migrations .values() .filter(|m| include_background || !m.run_in_background()); let latest_version = migrations - .last() + .next_back() .unwrap_or_else(|| panic!("should have at least one version")) .version(); debug!("Latest database version [{}]", latest_version); @@ -201,19 +201,19 @@ impl Migrations { } fn is_non_empty_rdb(&self, db: &ReadOnlyDB) -> bool { - if let Ok(v) = db.get_pinned(COLUMN_META, META_TIP_HEADER_KEY) { - if v.is_some() { - return true; - } + if let Ok(v) = db.get_pinned(COLUMN_META, META_TIP_HEADER_KEY) + && v.is_some() + { + return true; } false } fn is_non_empty_db(&self, db: &RocksDB) -> bool { - if let Ok(v) = db.get_pinned(COLUMN_META, META_TIP_HEADER_KEY) { - if v.is_some() { - return true; - } + if let Ok(v) = db.get_pinned(COLUMN_META, META_TIP_HEADER_KEY) + && v.is_some() + { + return true; } false } @@ -288,14 +288,12 @@ impl Migrations { /// Initial db version pub fn init_db_version(&self, db: &RocksDB) -> Result<(), Error> { let db_version = self.get_migration_version(db)?; - if db_version.is_none() { - if let Some(m) = self.migrations.values().last() { - info!("Init database version {}", m.version()); - db.put_default(MIGRATION_VERSION_KEY, m.version()) - .map_err(|err| { - internal_error(format!("failed to migrate the database: {err}")) - })?; - } + if db_version.is_none() + && let Some(m) = self.migrations.values().last() + { + info!("Init database version {}", m.version()); + db.put_default(MIGRATION_VERSION_KEY, m.version()) + .map_err(|err| internal_error(format!("failed to migrate the database: {err}")))?; } Ok(()) } @@ -334,17 +332,17 @@ impl Migrations { } fn check_migration_downgrade(&self, cur_version: &str) -> Result<(), Error> { - if let Some(m) = self.migrations.values().last() { - if m.version() < cur_version { - error!( - "Database downgrade detected. \ + if let Some(m) = self.migrations.values().last() + && m.version() < cur_version + { + error!( + "Database downgrade detected. \ The database schema version is newer than `ckb` schema version,\ please upgrade `ckb` to the latest version" - ); - return Err(internal_error( - "Database downgrade is not supported".to_string(), - )); - } + ); + return Err(internal_error( + "Database downgrade is not supported".to_string(), + )); } Ok(()) } diff --git a/db/src/db.rs b/db/src/db.rs index 40ec4ce330..1e74bc59f6 100644 --- a/db/src/db.rs +++ b/db/src/db.rs @@ -168,14 +168,14 @@ impl RocksDB { /// Return the value associated with a key using RocksDB's PinnableSlice from the given column /// so as to avoid unnecessary memory copy. - pub fn get_pinned(&self, col: Col, key: &[u8]) -> Result> { + pub fn get_pinned(&self, col: Col, key: &[u8]) -> Result>> { let cf = cf_handle(&self.inner, col)?; self.inner.get_pinned_cf(cf, key).map_err(internal_error) } /// Return the value associated with a key using RocksDB's PinnableSlice from the default column /// so as to avoid unnecessary memory copy. - pub fn get_pinned_default(&self, key: &[u8]) -> Result> { + pub fn get_pinned_default(&self, key: &[u8]) -> Result>> { self.inner.get_pinned(key).map_err(internal_error) } diff --git a/db/src/db_with_ttl.rs b/db/src/db_with_ttl.rs index 7e3e1df2f6..d63f330142 100644 --- a/db/src/db_with_ttl.rs +++ b/db/src/db_with_ttl.rs @@ -56,7 +56,7 @@ impl DBWithTTL { /// Return the value associated with a key using RocksDB's PinnableSlice from the given column /// so as to avoid unnecessary memory copy. - pub fn get_pinned(&self, col: &str, key: &[u8]) -> Result> { + pub fn get_pinned(&self, col: &str, key: &[u8]) -> Result>> { let cf = self .inner .cf_handle(col) diff --git a/db/src/iter.rs b/db/src/iter.rs index e165357272..bd27531eaa 100644 --- a/db/src/iter.rs +++ b/db/src/iter.rs @@ -12,18 +12,18 @@ use rocksdb::{ReadOptions, ops::IterateCF}; pub trait DBIterator { /// Opens an iterator using the provided IteratorMode. /// This is used when you want to iterate over a specific ColumnFamily - fn iter(&self, col: Col, mode: IteratorMode) -> Result { + fn iter(&self, col: Col, mode: IteratorMode) -> Result> { let opts = ReadOptions::default(); self.iter_opt(col, mode, &opts) } /// Opens an iterator using the provided IteratorMode and ReadOptions. /// This is used when you want to iterate over a specific ColumnFamily with a modified ReadOptions - fn iter_opt(&self, col: Col, mode: IteratorMode, readopts: &ReadOptions) -> Result; + fn iter_opt(&self, col: Col, mode: IteratorMode, readopts: &ReadOptions) -> Result>; } impl DBIterator for RocksDB { - fn iter_opt(&self, col: Col, mode: IteratorMode, readopts: &ReadOptions) -> Result { + fn iter_opt(&self, col: Col, mode: IteratorMode, readopts: &ReadOptions) -> Result> { let cf = cf_handle(&self.inner, col)?; self.inner .iterator_cf_opt(cf, mode, readopts) @@ -32,7 +32,7 @@ impl DBIterator for RocksDB { } impl DBIterator for RocksDBTransaction { - fn iter_opt(&self, col: Col, mode: IteratorMode, readopts: &ReadOptions) -> Result { + fn iter_opt(&self, col: Col, mode: IteratorMode, readopts: &ReadOptions) -> Result> { let cf = cf_handle(&self.db, col)?; self.inner .iterator_cf_opt(cf, mode, readopts) @@ -41,7 +41,7 @@ impl DBIterator for RocksDBTransaction { } impl<'a> DBIterator for RocksDBTransactionSnapshot<'a> { - fn iter_opt(&self, col: Col, mode: IteratorMode, readopts: &ReadOptions) -> Result { + fn iter_opt(&self, col: Col, mode: IteratorMode, readopts: &ReadOptions) -> Result> { let cf = cf_handle(&self.db, col)?; self.inner .iterator_cf_opt(cf, mode, readopts) @@ -50,7 +50,7 @@ impl<'a> DBIterator for RocksDBTransactionSnapshot<'a> { } impl DBIterator for RocksDBSnapshot { - fn iter_opt(&self, col: Col, mode: IteratorMode, readopts: &ReadOptions) -> Result { + fn iter_opt(&self, col: Col, mode: IteratorMode, readopts: &ReadOptions) -> Result> { let cf = cf_handle(&self.db, col)?; self.iterator_cf_opt(cf, mode, readopts) .map_err(internal_error) diff --git a/db/src/read_only_db.rs b/db/src/read_only_db.rs index 498a8f5a7c..98b13c3af1 100644 --- a/db/src/read_only_db.rs +++ b/db/src/read_only_db.rs @@ -50,13 +50,13 @@ impl ReadOnlyDB { /// Return the value associated with a key using RocksDB's PinnableSlice from the default column /// so as to avoid unnecessary memory copy. - pub fn get_pinned_default(&self, key: &[u8]) -> Result> { + pub fn get_pinned_default(&self, key: &[u8]) -> Result>> { self.inner.get_pinned(key).map_err(internal_error) } /// Return the value associated with a key using RocksDB's PinnableSlice from the given column /// so as to avoid unnecessary memory copy. - pub fn get_pinned(&self, col: Col, key: &[u8]) -> Result> { + pub fn get_pinned(&self, col: Col, key: &[u8]) -> Result>> { let cf = self .inner .cf_handle(col) diff --git a/db/src/snapshot.rs b/db/src/snapshot.rs index 4e5ef7e550..739e36d548 100644 --- a/db/src/snapshot.rs +++ b/db/src/snapshot.rs @@ -35,7 +35,7 @@ impl RocksDBSnapshot { /// Return the value associated with a key using RocksDB's PinnableSlice from the given column /// so as to avoid unnecessary memory copy. - pub fn get_pinned(&self, col: Col, key: &[u8]) -> Result> { + pub fn get_pinned(&self, col: Col, key: &[u8]) -> Result>> { let cf = cf_handle(&self.db, col)?; self.get_pinned_cf_full(Some(cf), key, None) .map_err(internal_error) diff --git a/db/src/transaction.rs b/db/src/transaction.rs index dadfe540eb..85b45c7228 100644 --- a/db/src/transaction.rs +++ b/db/src/transaction.rs @@ -17,7 +17,7 @@ pub struct RocksDBTransaction { impl RocksDBTransaction { /// Return the bytes associated with the given key and given column. - pub fn get_pinned(&self, col: Col, key: &[u8]) -> Result> { + pub fn get_pinned(&self, col: Col, key: &[u8]) -> Result>> { let cf = cf_handle(&self.db, col)?; self.inner.get_pinned_cf(cf, key).map_err(internal_error) } @@ -86,7 +86,7 @@ pub struct RocksDBTransactionSnapshot<'a> { impl<'a> RocksDBTransactionSnapshot<'a> { /// Return the bytes associated with the given key and given column. - pub fn get_pinned(&self, col: Col, key: &[u8]) -> Result> { + pub fn get_pinned(&self, col: Col, key: &[u8]) -> Result>> { let cf = cf_handle(&self.db, col)?; self.inner.get_pinned_cf(cf, key).map_err(internal_error) } diff --git a/devtools/doc/rpc-gen/src/gen.rs b/devtools/doc/rpc-gen/src/gen.rs index 669ed3b384..9e156c3d24 100644 --- a/devtools/doc/rpc-gen/src/gen.rs +++ b/devtools/doc/rpc-gen/src/gen.rs @@ -435,12 +435,10 @@ fn gen_type(ty: &Value) -> String { format!("`{}`", ty.as_str().unwrap()) } } else if let Some(arr) = ty.as_array() { - let ty = arr - .iter() + arr.iter() .map(|t| format!("`{}`", gen_type(t))) .collect::>() - .join(" `|` "); - ty + .join(" `|` ") } else if ty.as_str() == Some("object") { // json schemars bug! // type is `HashMap` here @@ -465,7 +463,7 @@ fn gen_type(ty: &Value) -> String { res.retain(|value| value != "`string`"); format!("\nIt's an enum value from one of:\n{}\n", res.join("\n")) } else if let Some(link) = map.get("$ref") { - let link = link.as_str().unwrap().split('/').last().unwrap(); + let link = link.as_str().unwrap().split('/').next_back().unwrap(); format!("[`{}`](#type-{})", fix_type_name(link), link.to_lowercase()) } else { "".to_owned() diff --git a/devtools/doc/rpc-gen/src/syn.rs b/devtools/doc/rpc-gen/src/syn.rs index 7669e751dd..3ac34324d3 100644 --- a/devtools/doc/rpc-gen/src/syn.rs +++ b/devtools/doc/rpc-gen/src/syn.rs @@ -36,8 +36,8 @@ fn get_deprected_attr(attr: &syn::Attribute) -> Option> { } fn get_doc_from_attr(attr: &syn::Attribute) -> String { - if attr.path().is_ident("doc") { - if let Meta::NameValue(MetaNameValue { + if attr.path().is_ident("doc") + && let Meta::NameValue(MetaNameValue { value: Expr::Lit(syn::ExprLit { lit: syn::Lit::Str(lit), @@ -45,10 +45,9 @@ fn get_doc_from_attr(attr: &syn::Attribute) -> String { }), .. }) = &attr.meta - { - let lit = lit.value(); - return lit; - } + { + let lit = lit.value(); + return lit; } "".to_string() } @@ -96,19 +95,19 @@ impl Visit<'_> for CommentFinder { fn visit_item_trait(&mut self, trait_item: &'_ syn::ItemTrait) { for i in trait_item.items.iter() { - if let syn::TraitItem::Fn(item_fn) = i { - if !item_fn.attrs.is_empty() { - let current_rpc = trait_item - .ident - .to_string() - .trim_end_matches("Rpc") - .to_owned(); - self.current_fn = Some(format!("{}.{}", current_rpc, item_fn.sig.ident)); - for attr in &item_fn.attrs { - self.visit_attribute(attr); - } - self.current_fn = None; + if let syn::TraitItem::Fn(item_fn) = i + && !item_fn.attrs.is_empty() + { + let current_rpc = trait_item + .ident + .to_string() + .trim_end_matches("Rpc") + .to_owned(); + self.current_fn = Some(format!("{}.{}", current_rpc, item_fn.sig.ident)); + for attr in &item_fn.attrs { + self.visit_attribute(attr); } + self.current_fn = None; } } } @@ -143,10 +142,10 @@ impl Visit<'_> for CommentFinder { impl CommentFinder { fn visit_source_file(&mut self, file_path: &std::path::Path) { let code = std::fs::read_to_string(file_path).unwrap(); - if let Ok(tokens) = code.parse() { - if let Ok(file) = parse2(tokens) { - self.visit_file(&file); - } + if let Ok(tokens) = code.parse() + && let Ok(file) = parse2(tokens) + { + self.visit_file(&file); } } diff --git a/docker/hub/Dockerfile b/docker/hub/Dockerfile index 62952bdc95..a15432ba4a 100644 --- a/docker/hub/Dockerfile +++ b/docker/hub/Dockerfile @@ -1,4 +1,4 @@ -FROM nervos/ckb-docker-builder:bionic-rust-1.85.0 as ckb-docker-builder +FROM nervos/ckb-docker-builder:bionic-rust-1.92.0 as ckb-docker-builder WORKDIR /ckb COPY ./ . diff --git a/docker/hub/Dockerfile-aarch64 b/docker/hub/Dockerfile-aarch64 index 243d8559b3..468c333e7a 100644 --- a/docker/hub/Dockerfile-aarch64 +++ b/docker/hub/Dockerfile-aarch64 @@ -1,4 +1,4 @@ -FROM nervos/ckb-docker-builder:aarch64-rust-1.85.0 as ckb-docker-builder +FROM nervos/ckb-docker-builder:aarch64-rust-1.92.0 as ckb-docker-builder WORKDIR /ckb COPY ./ . diff --git a/freezer/src/freezer.rs b/freezer/src/freezer.rs index 5fd57052cb..6d8787bed3 100644 --- a/freezer/src/freezer.rs +++ b/freezer/src/freezer.rs @@ -105,14 +105,14 @@ impl Freezer { } if let Some(block) = get_block_by_number(number) { - if let Some(ref header) = guard.tip { - if header.hash() != block.header().parent_hash() { - return Err(internal_error(format!( - "appending unexpected block expected parent_hash {} have {}", - header.hash(), - block.header().parent_hash() - ))); - } + if let Some(ref header) = guard.tip + && header.hash() != block.header().parent_hash() + { + return Err(internal_error(format!( + "appending unexpected block expected parent_hash {} have {}", + header.hash(), + block.header().parent_hash() + ))); } let raw_block = block.data(); guard diff --git a/freezer/src/freezer_files.rs b/freezer/src/freezer_files.rs index 02f4c954ba..5d7d957d92 100644 --- a/freezer/src/freezer_files.rs +++ b/freezer/src/freezer_files.rs @@ -2,7 +2,7 @@ use fail::fail_point; use lru::LruCache; use snap::raw::{Decoder as SnappyDecoder, Encoder as SnappyEncoder}; use std::fs::{self, File}; -use std::io::{Error as IoError, ErrorKind as IoErrorKind}; +use std::io::Error as IoError; use std::io::{Read, Write}; use std::io::{Seek, SeekFrom}; use std::path::{Path, PathBuf}; @@ -84,12 +84,12 @@ impl IndexEntry { let file_id = u32::from_le_bytes( raw_file_id .try_into() - .map_err(|e| IoError::new(IoErrorKind::Other, format!("decode file_id {e}")))?, + .map_err(|e| IoError::other(format!("decode file_id {e}")))?, ); let offset = u64::from_le_bytes( raw_offset .try_into() - .map_err(|e| IoError::new(IoErrorKind::Other, format!("decode offset {e}")))?, + .map_err(|e| IoError::other(format!("decode offset {e}")))?, ); Ok(IndexEntry { offset, file_id }) } @@ -114,10 +114,9 @@ impl FreezerFiles { let expected = self.number.load(Ordering::SeqCst); fail_point!("append-unexpected-number"); if expected != number { - return Err(IoError::new( - IoErrorKind::Other, - format!("appending unexpected block expected {expected} have {number}"), - )); + return Err(IoError::other(format!( + "appending unexpected block expected {expected} have {number}" + ))); } // https://github.com/rust-lang/rust/issues/49171 @@ -127,7 +126,7 @@ impl FreezerFiles { if self.enable_compression { compressed_data = SnappyEncoder::new() .compress_vec(data) - .map_err(|e| IoError::new(IoErrorKind::Other, format!("compress error {e}")))?; + .map_err(|e| IoError::other(format!("compress error {e}")))?; data = &compressed_data; }; @@ -192,12 +191,9 @@ impl FreezerFiles { if self.enable_compression { data = SnappyDecoder::new().decompress_vec(&data).map_err(|e| { - IoError::new( - IoErrorKind::Other, - format!( - "decompress file-id-{file_id} offset-{start_offset} size-{size}: error {e}" - ), - ) + IoError::other(format!( + "decompress file-id-{file_id} offset-{start_offset} size-{size}: error {e}" + )) })?; } diff --git a/miner/src/worker/dummy.rs b/miner/src/worker/dummy.rs index 728097cb11..ff7a087769 100644 --- a/miner/src/worker/dummy.rs +++ b/miner/src/worker/dummy.rs @@ -111,11 +111,10 @@ impl Dummy { work: new_work, .. }) = self.worker_rx.try_recv() + && new_pow_hash != pow_hash { - if new_pow_hash != pow_hash { - pow_hash = new_pow_hash; - work = new_work; - } + pow_hash = new_pow_hash; + work = new_work; } } } @@ -125,10 +124,10 @@ impl Worker for Dummy { fn run u128>(&mut self, mut rng: G, _progress_bar: ProgressBar) { loop { self.poll_worker_message(); - if self.start { - if let Some((pow_hash, work)) = self.pow_work.clone() { - self.solve(pow_hash, work, rng()); - } + if self.start + && let Some((pow_hash, work)) = self.pow_work.clone() + { + self.solve(pow_hash, work, rng()); } } } diff --git a/network/src/lib.rs b/network/src/lib.rs index 363d42374b..8b5b29f52c 100644 --- a/network/src/lib.rs +++ b/network/src/lib.rs @@ -71,15 +71,15 @@ pub async fn observe_listen_port_occupancy( None => multiaddr_to_socketaddr(raw_addr), }; - if let Some(addr) = ip_addr { - if let Err(e) = TcpListener::bind(addr) { - ckb_logger::error!( - "addr {} can't use on your machines by error: {}, please check", - raw_addr, - e - ); - return Err(e); - } + if let Some(addr) = ip_addr + && let Err(e) = TcpListener::bind(addr) + { + ckb_logger::error!( + "addr {} can't use on your machines by error: {}, please check", + raw_addr, + e + ); + return Err(e); } } } diff --git a/network/src/network.rs b/network/src/network.rs index c36766ec9f..5fde2fffee 100644 --- a/network/src/network.rs +++ b/network/src/network.rs @@ -225,10 +225,10 @@ impl NetworkState { }) { trace!("Report {:?} because {:?}", addr, behaviour); let report_result = self.peer_store.lock().report(&addr, behaviour); - if report_result.is_banned() { - if let Err(err) = disconnect_with_message(p2p_control, session_id, "banned") { - debug!("Disconnect failed {:?}, error: {:?}", session_id, err); - } + if report_result.is_banned() + && let Err(err) = disconnect_with_message(p2p_control, session_id, "banned") + { + debug!("Disconnect failed {:?}, error: {:?}", session_id, err); } } else { debug!( @@ -287,15 +287,15 @@ impl NetworkState { // NOTE: be careful, here easy cause a deadlock, // because peer_store's lock scope across peer_registry's lock scope let mut peer_store = self.peer_store.lock(); - let accept_peer_result = { + + { self.peer_registry.write().accept_peer( session_context.address.clone(), session_context.id, session_context.ty, &mut peer_store, ) - }; - accept_peer_result + } } /// For restrict lock in inner scope @@ -1455,14 +1455,14 @@ impl NetworkController { fn disconnect_peers_in_ip_range(&self, address: IpNetwork, reason: &str) { self.network_state.with_peer_registry(|reg| { reg.peers().iter().for_each(|(peer_index, peer)| { - if let Some(addr) = multiaddr_to_socketaddr(&peer.connected_addr) { - if address.contains(addr.ip()) { - let _ = disconnect_with_message( - &self.p2p_control, - *peer_index, - &format!("Ban peer {}, reason: {}", addr.ip(), reason), - ); - } + if let Some(addr) = multiaddr_to_socketaddr(&peer.connected_addr) + && address.contains(addr.ip()) + { + let _ = disconnect_with_message( + &self.p2p_control, + *peer_index, + &format!("Ban peer {}, reason: {}", addr.ip(), reason), + ); } }) }); diff --git a/network/src/peer_registry.rs b/network/src/peer_registry.rs index 07e1c74e78..1726f612be 100644 --- a/network/src/peer_registry.rs +++ b/network/src/peer_registry.rs @@ -219,11 +219,11 @@ impl PeerRegistry { /// Identify change feeler flags pub fn change_feeler_flags(&mut self, addr: &Multiaddr, flags: Flags) -> bool { - if let Some(peer_id) = extract_peer_id(addr) { - if let Some(i) = self.feeler_peers.get_mut(&peer_id) { - *i = flags; - return true; - } + if let Some(peer_id) = extract_peer_id(addr) + && let Some(i) = self.feeler_peers.get_mut(&peer_id) + { + *i = flags; + return true; } false } diff --git a/network/src/peer_store/ban_list.rs b/network/src/peer_store/ban_list.rs index fd6571131e..3cbc5a80e4 100644 --- a/network/src/peer_store/ban_list.rs +++ b/network/src/peer_store/ban_list.rs @@ -35,7 +35,7 @@ impl BanList { self.inner.insert(banned_addr.address, banned_addr); let (insert_count, _) = self.insert_count.overflowing_add(1); self.insert_count = insert_count; - if self.insert_count % CLEAR_INTERVAL_COUNTER == 0 { + if self.insert_count.is_multiple_of(CLEAR_INTERVAL_COUNTER) { self.clear_expires(); } } @@ -47,10 +47,10 @@ impl BanList { fn is_ip_banned_until(&self, ip: IpAddr, now_ms: u64) -> bool { let ip_network = ip_to_network(ip); - if let Some(banned_addr) = self.inner.get(&ip_network) { - if banned_addr.ban_until.gt(&now_ms) { - return true; - } + if let Some(banned_addr) = self.inner.get(&ip_network) + && banned_addr.ban_until.gt(&now_ms) + { + return true; } self.inner.iter().any(|(ip_network, banned_addr)| { diff --git a/network/src/protocols/discovery/mod.rs b/network/src/protocols/discovery/mod.rs index 9df075fce0..b4363f3fa4 100644 --- a/network/src/protocols/discovery/mod.rs +++ b/network/src/protocols/discovery/mod.rs @@ -168,13 +168,13 @@ impl ServiceProtocol for DiscoveryProtocol { } } DiscoveryMessage::Nodes(nodes) => { - if let Some(misbehavior) = verify_nodes_message(&nodes) { - if check(misbehavior) { - if context.disconnect(session.id).await.is_err() { - debug!("Disconnect {:?} msg failed to send", session.id) - } - return; + if let Some(misbehavior) = verify_nodes_message(&nodes) + && check(misbehavior) + { + if context.disconnect(session.id).await.is_err() { + debug!("Disconnect {:?} msg failed to send", session.id) } + return; } if let Some(state) = self.sessions.get_mut(&session.id) { @@ -231,10 +231,9 @@ impl ServiceProtocol for DiscoveryProtocol { if let Some(addr) = state .check_timer(now, ANNOUNCE_INTERVAL) .filter(|addr| self.addr_mgr.is_valid_addr(addr)) + && let Some(flags) = self.addr_mgr.node_flags(*id) { - if let Some(flags) = self.addr_mgr.node_flags(*id) { - announce_list.push((addr.clone(), flags)); - } + announce_list.push((addr.clone(), flags)); } } diff --git a/network/src/protocols/hole_punching/mod.rs b/network/src/protocols/hole_punching/mod.rs index 1fb2a2277c..1a680bf7b2 100644 --- a/network/src/protocols/hole_punching/mod.rs +++ b/network/src/protocols/hole_punching/mod.rs @@ -266,11 +266,10 @@ impl HolePunching { for multi_addr in &network_state.config.listen_addresses { if let crate::network::TransportType::Tcp = crate::network::find_type(multi_addr) + && let Some(addr) = p2p::utils::multiaddr_to_socketaddr(multi_addr) { - if let Some(addr) = p2p::utils::multiaddr_to_socketaddr(multi_addr) { - bind_addr = Some(addr); - break; - } + bind_addr = Some(addr); + break; } } } diff --git a/network/src/protocols/ping.rs b/network/src/protocols/ping.rs index f1b88e613f..fa4a1458d6 100644 --- a/network/src/protocols/ping.rs +++ b/network/src/protocols/ping.rs @@ -224,13 +224,13 @@ impl ServiceProtocol for PingHandler { } PingPayload::Pong(nonce) => { // check pong - if let Some(status) = self.connected_session_ids.get_mut(&session.id) { - if (true, nonce) == (status.processing, status.nonce()) { - status.processing = false; - let last_ping_sent_at = status.last_ping_sent_at; - self.pong_received(session.id, last_ping_sent_at); - return; - } + if let Some(status) = self.connected_session_ids.get_mut(&session.id) + && (true, nonce) == (status.processing, status.nonce()) + { + status.processing = false; + let last_ping_sent_at = status.last_ping_sent_at; + self.pong_received(session.id, last_ping_sent_at); + return; } // if nonce is incorrect or can't find ping info if let Err(err) = async_disconnect_with_message( diff --git a/network/src/tests/peer_registry.rs b/network/src/tests/peer_registry.rs index d9112c7f09..814961c9fe 100644 --- a/network/src/tests/peer_registry.rs +++ b/network/src/tests/peer_registry.rs @@ -1,4 +1,4 @@ -#![allow(clippy::unchecked_duration_subtraction)] +#![allow(clippy::unchecked_time_subtraction)] use super::random_addr; use crate::{ diff --git a/resource/src/lib.rs b/resource/src/lib.rs index 3c95e3fa05..68d3e2ed5f 100644 --- a/resource/src/lib.rs +++ b/resource/src/lib.rs @@ -33,7 +33,7 @@ use serde::{Deserialize, Serialize}; use std::borrow::Cow; use std::fmt; use std::fs; -use std::io::{self, BufReader, Cursor, Read}; +use std::io::{BufReader, Cursor, Read}; use std::path::{Path, PathBuf}; use ckb_system_scripts::BUNDLED_CELL; @@ -185,10 +185,10 @@ impl Resource { /// /// If the path is relative, expand the path relative to the directory `base`. pub fn absolutize>(&mut self, base: P) { - if let Resource::FileSystem { file: path } = self { - if path.is_relative() { - *path = base.as_ref().join(&path) - } + if let Resource::FileSystem { file: path } = self + && path.is_relative() + { + *path = base.as_ref().join(&path) } } @@ -267,7 +267,7 @@ impl<'a> SourceFiles<'a> { } fn from_utf8(data: Cow<[u8]>) -> Result { - String::from_utf8(data.to_vec()).map_err(|err| Error::new(io::ErrorKind::Other, err)) + String::from_utf8(data.to_vec()).map_err(Error::other) } fn join_bundled_key(mut root_dir: PathBuf, key: &str) -> PathBuf { diff --git a/rpc/src/module/chain.rs b/rpc/src/module/chain.rs index 60e5ee6c3e..b229eda7de 100644 --- a/rpc/src/module/chain.rs +++ b/rpc/src/module/chain.rs @@ -2316,12 +2316,12 @@ impl ChainRpcImpl { } let retrieved_block_hash = retrieved_block_hash.expect("checked len"); - if let Some(specified_block_hash) = block_hash { - if !retrieved_block_hash.eq(&specified_block_hash.into()) { - return Err(RPCError::invalid_params( - "Not all transactions found in specified block", - )); - } + if let Some(specified_block_hash) = block_hash + && !retrieved_block_hash.eq(&specified_block_hash.into()) + { + return Err(RPCError::invalid_params( + "Not all transactions found in specified block", + )); } snapshot @@ -2350,12 +2350,11 @@ impl<'a> CellProvider for CyclesEstimator<'a> { snapshot .get_cell(out_point) .map(|mut cell_meta| { - if eager_load { - if let Some((data, data_hash)) = snapshot.get_cell_data(out_point) { + if eager_load + && let Some((data, data_hash)) = snapshot.get_cell_data(out_point) { cell_meta.mem_cell_data = Some(data); cell_meta.mem_cell_data_hash = Some(data_hash); } - } CellStatus::live_cell(cell_meta) }) // treat as live cell, regardless of live or dead .unwrap_or(CellStatus::Unknown) diff --git a/rpc/src/server.rs b/rpc/src/server.rs index 34bbc6bedb..d20f044af3 100644 --- a/rpc/src/server.rs +++ b/rpc/src/server.rs @@ -269,13 +269,13 @@ async fn handle_jsonrpc( } } Request::Batch(calls) => { - if let Some(batch_size) = JSONRPC_BATCH_LIMIT.get() { - if calls.len() > *batch_size { - return make_error_response(jsonrpc_core::Error::invalid_params(format!( - "batch size is too large, expect it less than: {}", - batch_size - ))); - } + if let Some(batch_size) = JSONRPC_BATCH_LIMIT.get() + && calls.len() > *batch_size + { + return make_error_response(jsonrpc_core::Error::invalid_params(format!( + "batch size is too large, expect it less than: {}", + batch_size + ))); } let stream = stream::iter(calls) diff --git a/rpc/src/tests/examples.rs b/rpc/src/tests/examples.rs index d841398e7b..0060f4424b 100644 --- a/rpc/src/tests/examples.rs +++ b/rpc/src/tests/examples.rs @@ -59,42 +59,30 @@ fn collect_code_block( ) -> io::Result<()> { if code_block.contains("\"method\":") { if let Some(request) = request { - return Err(io::Error::new( - io::ErrorKind::Other, - format!("Unexpected request. The request {request} has no matched response yet."), - )); + return Err(io::Error::other(format!( + "Unexpected request. The request {request} has no matched response yet." + ))); } - let new_request: RpcTestRequest = serde_json::from_str(&code_block).map_err(|e| { - io::Error::new( - io::ErrorKind::Other, - format!("Invalid JSONRPC Request: {e}\n{code_block}"), - ) - })?; + let new_request: RpcTestRequest = serde_json::from_str(&code_block) + .map_err(|e| io::Error::other(format!("Invalid JSONRPC Request: {e}\n{code_block}")))?; *request = Some(new_request); } else { let response: RpcTestResponse = serde_json::from_str(&code_block).map_err(|e| { - io::Error::new( - io::ErrorKind::Other, - format!("Invalid JSONRPC Response: {e}\n{code_block}"), - ) + io::Error::other(format!("Invalid JSONRPC Response: {e}\n{code_block}")) })?; if let Some(request) = request.take() { if request.id != response.id { - return Err(io::Error::new( - io::ErrorKind::Other, - "Unmatched response id", - )); + return Err(io::Error::other("Unmatched response id")); } let request_display = format!("{request}"); if !collected.insert(RpcTestExample { request, response }) { - return Err(io::Error::new( - io::ErrorKind::Other, - format!("Duplicate example {request_display}"), - )); + return Err(io::Error::other(format!( + "Duplicate example {request_display}" + ))); } } else { - return Err(io::Error::new(io::ErrorKind::Other, "Unexpected response")); + return Err(io::Error::other("Unexpected response")); } } @@ -143,20 +131,18 @@ fn collect_rpc_examples_in_file( if let Some(comment) = find_comment(&line) { if comment == "```json" { if !collecting.is_empty() { - return Err(io::Error::new( - io::ErrorKind::Other, - format!("{}:{}: Unexpected code block start", path.display(), lineno), - )); + return Err(io::Error::other(format!( + "{}:{}: Unexpected code block start", + path.display(), + lineno + ))); } collecting.push("".to_string()); } else if comment == "```" { let code_block = collecting.join("\n"); if code_block.contains("\"jsonrpc\":") { collect_code_block(collected, &mut request, code_block).map_err(|e| { - io::Error::new( - io::ErrorKind::Other, - format!("{}:{}: {}", path.display(), lineno, e), - ) + io::Error::other(format!("{}:{}: {}", path.display(), lineno, e)) })?; } collecting.clear(); @@ -165,10 +151,11 @@ fn collect_rpc_examples_in_file( } } else { if !collecting.is_empty() { - return Err(io::Error::new( - io::ErrorKind::Other, - format!("{}:{}: Unexpected end of comment", path.display(), lineno), - )); + return Err(io::Error::other(format!( + "{}:{}: Unexpected end of comment", + path.display(), + lineno + ))); } if let Some(rpc_method) = find_rpc_method(&line) { @@ -188,13 +175,10 @@ fn collect_rpc_examples_in_file( if collecting.is_empty() { Ok(()) } else { - Err(io::Error::new( - io::ErrorKind::Other, - format!( - "{}: Unexpected EOF while the code block is still open", - path.display() - ), - )) + Err(io::Error::other(format!( + "{}: Unexpected EOF while the code block is still open", + path.display() + ))) } } diff --git a/rpc/src/util/fee_rate.rs b/rpc/src/util/fee_rate.rs index f06a89b3a6..ab76b5f319 100644 --- a/rpc/src/util/fee_rate.rs +++ b/rpc/src/util/fee_rate.rs @@ -19,7 +19,7 @@ fn mean(numbers: &[u64]) -> u64 { fn median(numbers: &mut [u64]) -> u64 { numbers.sort_unstable(); let mid = numbers.len() / 2; - if numbers.len() % 2 == 0 { + if numbers.len().is_multiple_of(2) { mean(&[numbers[mid - 1], numbers[mid]]) } else { numbers[mid] diff --git a/rust-toolchain.toml b/rust-toolchain.toml index c1bc0a6944..f19782d3c5 100644 --- a/rust-toolchain.toml +++ b/rust-toolchain.toml @@ -1,2 +1,2 @@ [toolchain] -channel = "1.85.0" +channel = "1.92.0" diff --git a/script/src/scheduler.rs b/script/src/scheduler.rs index b903680751..f68a2a4692 100644 --- a/script/src/scheduler.rs +++ b/script/src/scheduler.rs @@ -358,7 +358,8 @@ where self.process_message_box()?; assert!(self.message_box.lock().expect("lock").is_empty()); // If the VM terminates, update VMs in join state, also closes its fds - let result = match result { + + match result { Ok(code) => { self.terminated_vms.insert(vm_id_to_run, code); // When root VM terminates, the execution stops immediately, we will purge @@ -406,8 +407,7 @@ where } Err(Error::Yield) => Ok(()), Err(e) => Err(e), - }; - result + } } // This internal function is actually a wrapper over +iterate_inner+, diff --git a/script/src/syscalls/generator.rs b/script/src/syscalls/generator.rs index 79bc49c05d..d08276c9bc 100644 --- a/script/src/syscalls/generator.rs +++ b/script/src/syscalls/generator.rs @@ -15,12 +15,12 @@ pub fn generate_ckb_syscalls( sg_data: &SgData
, vm_context: &VmContext
, debug_printer: &DebugPrinter, -) -> Vec)>> +) -> Vec>> where DL: CellDataProvider + HeaderProvider + ExtensionProvider + Send + Sync + Clone + 'static, M: SupportMachine, { - let mut syscalls: Vec)>> = vec![ + let mut syscalls: Vec>> = vec![ Box::new(LoadScriptHash::new(sg_data)), Box::new(LoadTx::new(sg_data)), Box::new(LoadCell::new(sg_data)), diff --git a/script/src/types.rs b/script/src/types.rs index dd1fd97809..8ac4672679 100644 --- a/script/src/types.rs +++ b/script/src/types.rs @@ -58,7 +58,7 @@ pub type Machine = ckb_vm::TraceMachine< pub type DebugPrinter = Arc; /// Syscall generator function type pub type SyscallGenerator = - fn(&VmId, &SgData
, &VmContext
, &V) -> Vec)>>; + fn(&VmId, &SgData
, &VmContext
, &V) -> Vec>>; /// The version of CKB Script Verifier. #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)] @@ -295,7 +295,7 @@ impl Fd { /// Tests if current fd is used for reading from a pipe pub fn is_read(&self) -> bool { - self.0 % 2 == 0 + self.0.is_multiple_of(2) } /// Tests if current fd is used for writing to a pipe diff --git a/script/src/verify/tests/utils.rs b/script/src/verify/tests/utils.rs index 93bbef9860..fc705b800f 100644 --- a/script/src/verify/tests/utils.rs +++ b/script/src/verify/tests/utils.rs @@ -134,7 +134,7 @@ pub(crate) fn generate_syscalls_with_skip_pause( sg_data: &SgData
, vm_context: &VmContext
, debug_context: &DebugContext, -) -> Vec)>> +) -> Vec>> where DL: CellDataProvider + HeaderProvider + ExtensionProvider + Send + Sync + Clone + 'static, M: SupportMachine, diff --git a/script/testdata/spawn_dag.rs b/script/testdata/spawn_dag.rs index f3a20a27c5..959b6fa286 100644 --- a/script/testdata/spawn_dag.rs +++ b/script/testdata/spawn_dag.rs @@ -1384,7 +1384,9 @@ impl<'r> molecule::prelude::Reader<'r> for PipeReader<'r> { return ve!(Self, HeaderIsBroken, molecule::NUMBER_SIZE * 2, slice_len); } let offset_first = molecule::unpack_number(&slice[molecule::NUMBER_SIZE..]) as usize; - if offset_first % molecule::NUMBER_SIZE != 0 || offset_first < molecule::NUMBER_SIZE * 2 { + if !offset_first.is_multiple_of(molecule::NUMBER_SIZE) + || offset_first < molecule::NUMBER_SIZE * 2 + { return ve!(Self, OffsetsNotMatch); } if slice_len < offset_first { @@ -1666,7 +1668,9 @@ impl<'r> molecule::prelude::Reader<'r> for PipesReader<'r> { ); } let offset_first = molecule::unpack_number(&slice[molecule::NUMBER_SIZE..]) as usize; - if offset_first % molecule::NUMBER_SIZE != 0 || offset_first < molecule::NUMBER_SIZE * 2 { + if !offset_first.is_multiple_of(molecule::NUMBER_SIZE) + || offset_first < molecule::NUMBER_SIZE * 2 + { return ve!(Self, OffsetsNotMatch); } if slice_len < offset_first { @@ -2048,7 +2052,9 @@ impl<'r> molecule::prelude::Reader<'r> for WriteReader<'r> { return ve!(Self, HeaderIsBroken, molecule::NUMBER_SIZE * 2, slice_len); } let offset_first = molecule::unpack_number(&slice[molecule::NUMBER_SIZE..]) as usize; - if offset_first % molecule::NUMBER_SIZE != 0 || offset_first < molecule::NUMBER_SIZE * 2 { + if !offset_first.is_multiple_of(molecule::NUMBER_SIZE) + || offset_first < molecule::NUMBER_SIZE * 2 + { return ve!(Self, OffsetsNotMatch); } if slice_len < offset_first { @@ -2350,7 +2356,9 @@ impl<'r> molecule::prelude::Reader<'r> for WritesReader<'r> { ); } let offset_first = molecule::unpack_number(&slice[molecule::NUMBER_SIZE..]) as usize; - if offset_first % molecule::NUMBER_SIZE != 0 || offset_first < molecule::NUMBER_SIZE * 2 { + if !offset_first.is_multiple_of(molecule::NUMBER_SIZE) + || offset_first < molecule::NUMBER_SIZE * 2 + { return ve!(Self, OffsetsNotMatch); } if slice_len < offset_first { @@ -2701,7 +2709,9 @@ impl<'r> molecule::prelude::Reader<'r> for SpawnReader<'r> { return ve!(Self, HeaderIsBroken, molecule::NUMBER_SIZE * 2, slice_len); } let offset_first = molecule::unpack_number(&slice[molecule::NUMBER_SIZE..]) as usize; - if offset_first % molecule::NUMBER_SIZE != 0 || offset_first < molecule::NUMBER_SIZE * 2 { + if !offset_first.is_multiple_of(molecule::NUMBER_SIZE) + || offset_first < molecule::NUMBER_SIZE * 2 + { return ve!(Self, OffsetsNotMatch); } if slice_len < offset_first { @@ -2983,7 +2993,9 @@ impl<'r> molecule::prelude::Reader<'r> for SpawnsReader<'r> { ); } let offset_first = molecule::unpack_number(&slice[molecule::NUMBER_SIZE..]) as usize; - if offset_first % molecule::NUMBER_SIZE != 0 || offset_first < molecule::NUMBER_SIZE * 2 { + if !offset_first.is_multiple_of(molecule::NUMBER_SIZE) + || offset_first < molecule::NUMBER_SIZE * 2 + { return ve!(Self, OffsetsNotMatch); } if slice_len < offset_first { @@ -3333,7 +3345,9 @@ impl<'r> molecule::prelude::Reader<'r> for DataReader<'r> { return ve!(Self, HeaderIsBroken, molecule::NUMBER_SIZE * 2, slice_len); } let offset_first = molecule::unpack_number(&slice[molecule::NUMBER_SIZE..]) as usize; - if offset_first % molecule::NUMBER_SIZE != 0 || offset_first < molecule::NUMBER_SIZE * 2 { + if !offset_first.is_multiple_of(molecule::NUMBER_SIZE) + || offset_first < molecule::NUMBER_SIZE * 2 + { return ve!(Self, OffsetsNotMatch); } if slice_len < offset_first { diff --git a/shared/src/shared.rs b/shared/src/shared.rs index be44252067..7e0d1e89b7 100644 --- a/shared/src/shared.rs +++ b/shared/src/shared.rs @@ -467,7 +467,7 @@ impl Shared { ); } - pub fn assume_valid_targets(&self) -> MutexGuard>> { + pub fn assume_valid_targets(&self) -> MutexGuard<'_, Option>> { self.assume_valid_targets.lock() } diff --git a/shared/src/shared_builder.rs b/shared/src/shared_builder.rs index 63309cce3b..778e1ec69a 100644 --- a/shared/src/shared_builder.rs +++ b/shared/src/shared_builder.rs @@ -530,8 +530,8 @@ fn build_store( store_config: StoreConfig, ancient_path: Option, ) -> Result { - let store = if store_config.freezer_enable && ancient_path.is_some() { - let freezer = Freezer::open(ancient_path.expect("exist checked"))?; + let store = if let (true, Some(ancient_path)) = (store_config.freezer_enable, ancient_path) { + let freezer = Freezer::open(ancient_path)?; ChainDB::new_with_freezer(db, freezer, store_config) } else { ChainDB::new(db, store_config) @@ -577,20 +577,19 @@ fn register_tx_pool_callback( move |tx_pool: &mut TxPool, entry: &TxEntry, reject: Reject| { let tx_hash = entry.transaction().hash(); // record recent reject - if reject.should_recorded() { - if let Some(ref mut recent_reject) = tx_pool.recent_reject { - if let Err(e) = recent_reject.put(&tx_hash, reject.clone()) { - error!("record recent_reject failed {} {} {}", tx_hash, reject, e); - } - } + if reject.should_recorded() + && let Some(ref mut recent_reject) = tx_pool.recent_reject + && let Err(e) = recent_reject.put(&tx_hash, reject.clone()) + { + error!("record recent_reject failed {} {} {}", tx_hash, reject, e); } - if reject.is_allowed_relay() { - if let Err(e) = tx_relay_sender.send(TxVerificationResult::Reject { + if reject.is_allowed_relay() + && let Err(e) = tx_relay_sender.send(TxVerificationResult::Reject { tx_hash: tx_hash.clone(), - }) { - error!("tx-pool tx_relay_sender internal error {}", e); - } + }) + { + error!("tx-pool tx_relay_sender internal error {}", e); } // notify diff --git a/shared/src/types/header_map/kernel_lru.rs b/shared/src/types/header_map/kernel_lru.rs index 41607b6d87..84cd083942 100644 --- a/shared/src/types/header_map/kernel_lru.rs +++ b/shared/src/types/header_map/kernel_lru.rs @@ -186,7 +186,7 @@ where let mut stats = self.stats(); let progress = stats.trace_progress(); let frequency = stats.frequency(); - if progress % frequency == 0 { + if progress.is_multiple_of(frequency) { info!( "Header Map Statistics\ \n>\t| storage | length | limit | contain | select | insert | delete |\ @@ -214,7 +214,7 @@ where } #[cfg(feature = "stats")] - fn stats(&self) -> MutexGuard { + fn stats(&self) -> MutexGuard<'_, HeaderMapKernelStats> { self.stats.lock() } } diff --git a/shared/src/types/header_map/memory.rs b/shared/src/types/header_map/memory.rs index 24338217a5..62a107d1e1 100644 --- a/shared/src/types/header_map/memory.rs +++ b/shared/src/types/header_map/memory.rs @@ -96,10 +96,10 @@ impl MemoryMap { let mut guard = self.0.write(); let (key, value) = header.into(); let ret = guard.insert(key, value); - if ret.is_none() { - if let Some(metrics) = ckb_metrics::handle() { - metrics.ckb_header_map_memory_count.inc(); - } + if ret.is_none() + && let Some(metrics) = ckb_metrics::handle() + { + metrics.ckb_header_map_memory_count.inc(); } ret.map(|_| ()) } diff --git a/spec/src/consensus.rs b/spec/src/consensus.rs index 3534a7422c..11de267f94 100644 --- a/spec/src/consensus.rs +++ b/spec/src/consensus.rs @@ -989,7 +989,7 @@ impl Consensus { } fn primary_epoch_reward_of_next_epoch(&self, epoch: &EpochExt) -> Capacity { - if (epoch.number() + 1) % self.primary_epoch_reward_halving_interval() != 0 { + if !(epoch.number() + 1).is_multiple_of(self.primary_epoch_reward_halving_interval()) { epoch.primary_reward() } else { self.primary_epoch_reward(epoch.number() + 1) diff --git a/spec/src/lib.rs b/spec/src/lib.rs index d78ec698de..6e1c949fb4 100644 --- a/spec/src/lib.rs +++ b/spec/src/lib.rs @@ -1022,7 +1022,7 @@ pub(crate) fn build_type_id_script(input: &packed::CellInput, output_index: u64) pub fn calculate_block_reward(epoch_reward: Capacity, epoch_length: BlockNumber) -> Capacity { let epoch_reward = epoch_reward.as_u64(); Capacity::shannons({ - if epoch_reward % epoch_length != 0 { + if !epoch_reward.is_multiple_of(epoch_length) { epoch_reward / epoch_length + 1 } else { epoch_reward / epoch_length diff --git a/spec/src/versionbits/mod.rs b/spec/src/versionbits/mod.rs index 12960928c4..43058b1913 100644 --- a/spec/src/versionbits/mod.rs +++ b/spec/src/versionbits/mod.rs @@ -438,18 +438,17 @@ impl<'a> VersionbitsConditionChecker for Versionbits<'a> { } fn condition(&self, header: &HeaderView, indexer: &I) -> bool { - if let Some(cellbase) = indexer.cellbase(&header.hash()) { - if let Some(witness) = cellbase.witnesses().get(0) { - if let Ok(reader) = CellbaseWitnessReader::from_slice(&witness.raw_data()) { - let message = reader.message().to_entity(); - if message.len() >= 4 { - if let Ok(raw) = message.raw_data()[..4].try_into() { - let version = u32::from_le_bytes(raw); - return ((version & VERSIONBITS_TOP_MASK) == VERSIONBITS_TOP_BITS) - && (version & self.mask()) != 0; - } - } - } + if let Some(cellbase) = indexer.cellbase(&header.hash()) + && let Some(witness) = cellbase.witnesses().get(0) + && let Ok(reader) = CellbaseWitnessReader::from_slice(&witness.raw_data()) + { + let message = reader.message().to_entity(); + if message.len() >= 4 + && let Ok(raw) = message.raw_data()[..4].try_into() + { + let version = u32::from_le_bytes(raw); + return ((version & VERSIONBITS_TOP_MASK) == VERSIONBITS_TOP_BITS) + && (version & self.mask()) != 0; } } false diff --git a/store/src/db.rs b/store/src/db.rs index b7148a6cb3..0591077600 100644 --- a/store/src/db.rs +++ b/store/src/db.rs @@ -38,13 +38,13 @@ impl ChainStore for ChainDB { self.freezer.as_ref() } - fn get(&self, col: Col, key: &[u8]) -> Option { + fn get(&self, col: Col, key: &[u8]) -> Option> { self.db .get_pinned(col, key) .expect("db operation should be ok") } - fn get_iter(&self, col: Col, mode: IteratorMode) -> DBIter { + fn get_iter(&self, col: Col, mode: IteratorMode) -> DBIter<'_> { self.db.iter(col, mode).expect("db operation should be ok") } } @@ -112,7 +112,7 @@ impl ChainDB { } /// Return the chain spec hash - pub fn get_migration_version(&self) -> Option { + pub fn get_migration_version(&self) -> Option> { self.db .get_pinned_default(MIGRATION_VERSION_KEY) .expect("db operation should be ok") diff --git a/store/src/snapshot.rs b/store/src/snapshot.rs index a660e0caff..c2200b197c 100644 --- a/store/src/snapshot.rs +++ b/store/src/snapshot.rs @@ -24,13 +24,13 @@ impl ChainStore for StoreSnapshot { self.freezer.as_ref() } - fn get(&self, col: Col, key: &[u8]) -> Option { + fn get(&self, col: Col, key: &[u8]) -> Option> { self.inner .get_pinned(col, key) .expect("db operation should be ok") } - fn get_iter(&self, col: Col, mode: IteratorMode) -> DBIter { + fn get_iter(&self, col: Col, mode: IteratorMode) -> DBIter<'_> { self.inner .iter(col, mode) .expect("db operation should be ok") diff --git a/store/src/store.rs b/store/src/store.rs index d5135f2cc7..cad1645e82 100644 --- a/store/src/store.rs +++ b/store/src/store.rs @@ -30,25 +30,26 @@ pub trait ChainStore: Send + Sync + Sized { /// Return freezer reference fn freezer(&self) -> Option<&Freezer>; /// Return the bytes associated with a key value and the given column family. - fn get(&self, col: Col, key: &[u8]) -> Option; + fn get(&self, col: Col, key: &[u8]) -> Option>; /// Return an iterator over the database key-value pairs in the given column family. - fn get_iter(&self, col: Col, mode: IteratorMode) -> DBIter; + fn get_iter(&self, col: Col, mode: IteratorMode) -> DBIter<'_>; /// Return the borrowed data loader wrapper - fn borrow_as_data_loader(&self) -> BorrowedDataLoaderWrapper { + fn borrow_as_data_loader(&self) -> BorrowedDataLoaderWrapper<'_, Self> { BorrowedDataLoaderWrapper::new(self) } /// Get block by block header hash fn get_block(&self, h: &packed::Byte32) -> Option { let header = self.get_block_header(h)?; - if let Some(freezer) = self.freezer() { - if header.number() > 0 && header.number() < freezer.number() { - let raw_block = freezer.retrieve(header.number()).expect("block frozen")?; - let raw_block = packed::BlockReader::from_compatible_slice(&raw_block) - .expect("checked data") - .to_entity(); - return Some(raw_block.into_view()); - } + if let Some(freezer) = self.freezer() + && header.number() > 0 + && header.number() < freezer.number() + { + let raw_block = freezer.retrieve(header.number()).expect("block frozen")?; + let raw_block = packed::BlockReader::from_compatible_slice(&raw_block) + .expect("checked data") + .to_entity(); + return Some(raw_block.into_view()); } let body = self.get_block_body(h); let uncles = self @@ -69,10 +70,10 @@ pub trait ChainStore: Send + Sync + Sized { /// Get header by block header hash fn get_block_header(&self, hash: &packed::Byte32) -> Option { - if let Some(cache) = self.cache() { - if let Some(header) = cache.headers.lock().get(hash) { - return Some(header.clone()); - } + if let Some(cache) = self.cache() + && let Some(header) = cache.headers.lock().get(hash) + { + return Some(header.clone()); }; let ret = self.get(COLUMN_BLOCK_HEADER, hash.as_slice()).map(|slice| { let reader = packed::HeaderViewReader::from_slice_should_be_ok(slice.as_ref()); @@ -146,10 +147,10 @@ pub trait ChainStore: Send + Sync + Sized { /// Get all transaction-hashes in block body by block header hash fn get_block_txs_hashes(&self, hash: &packed::Byte32) -> Vec { - if let Some(cache) = self.cache() { - if let Some(hashes) = cache.block_tx_hashes.lock().get(hash) { - return hashes.clone(); - } + if let Some(cache) = self.cache() + && let Some(hashes) = cache.block_tx_hashes.lock().get(hash) + { + return hashes.clone(); }; let prefix = hash.as_slice(); @@ -177,10 +178,10 @@ pub trait ChainStore: Send + Sync + Sized { &self, hash: &packed::Byte32, ) -> Option { - if let Some(cache) = self.cache() { - if let Some(data) = cache.block_proposals.lock().get(hash) { - return Some(data.clone()); - } + if let Some(cache) = self.cache() + && let Some(data) = cache.block_proposals.lock().get(hash) + { + return Some(data.clone()); }; let ret = self @@ -201,10 +202,10 @@ pub trait ChainStore: Send + Sync + Sized { /// Get block uncles by block header hash fn get_block_uncles(&self, hash: &packed::Byte32) -> Option { - if let Some(cache) = self.cache() { - if let Some(data) = cache.block_uncles.lock().get(hash) { - return Some(data.clone()); - } + if let Some(cache) = self.cache() + && let Some(data) = cache.block_uncles.lock().get(hash) + { + return Some(data.clone()); }; let ret = self.get(COLUMN_BLOCK_UNCLE, hash.as_slice()).map(|slice| { @@ -223,10 +224,10 @@ pub trait ChainStore: Send + Sync + Sized { /// Get block extension by block header hash fn get_block_extension(&self, hash: &packed::Byte32) -> Option { - if let Some(cache) = self.cache() { - if let Some(data) = cache.block_extensions.lock().get(hash) { - return data.clone(); - } + if let Some(cache) = self.cache() + && let Some(data) = cache.block_extensions.lock().get(hash) + { + return data.clone(); }; let ret = self @@ -316,16 +317,17 @@ pub trait ChainStore: Send + Sync + Sized { hash: &packed::Byte32, ) -> Option<(TransactionView, TransactionInfo)> { let tx_info = self.get_transaction_info(hash)?; - if let Some(freezer) = self.freezer() { - if tx_info.block_number > 0 && tx_info.block_number < freezer.number() { - let raw_block = freezer - .retrieve(tx_info.block_number) - .expect("block frozen")?; - let raw_block_reader = - packed::BlockReader::from_compatible_slice(&raw_block).expect("checked data"); - let tx_reader = raw_block_reader.transactions().get(tx_info.index)?; - return Some((tx_reader.to_entity().into_view(), tx_info)); - } + if let Some(freezer) = self.freezer() + && tx_info.block_number > 0 + && tx_info.block_number < freezer.number() + { + let raw_block = freezer + .retrieve(tx_info.block_number) + .expect("block frozen")?; + let raw_block_reader = + packed::BlockReader::from_compatible_slice(&raw_block).expect("checked data"); + let tx_reader = raw_block_reader.transactions().get(tx_info.index)?; + return Some((tx_reader.to_entity().into_view(), tx_info)); } self.get(COLUMN_BLOCK_BODY, tx_info.key().as_slice()) .map(|slice| { @@ -352,10 +354,10 @@ pub trait ChainStore: Send + Sync + Sized { /// Returns cell data and its hash for the given outpoint. fn get_cell_data(&self, out_point: &OutPoint) -> Option<(Bytes, packed::Byte32)> { let key = out_point.to_cell_key(); - if let Some(cache) = self.cache() { - if let Some(cached) = cache.cell_data.lock().get(&key) { - return Some(cached.clone()); - } + if let Some(cache) = self.cache() + && let Some(cached) = cache.cell_data.lock().get(&key) + { + return Some(cached.clone()); }; let ret = self.get(COLUMN_CELL_DATA, &key).map(|slice| { @@ -381,10 +383,10 @@ pub trait ChainStore: Send + Sync + Sized { /// Returns the hash of cell data for the given outpoint. fn get_cell_data_hash(&self, out_point: &OutPoint) -> Option { let key = out_point.to_cell_key(); - if let Some(cache) = self.cache() { - if let Some(cached) = cache.cell_data_hash.lock().get(&key) { - return Some(cached.clone()); - } + if let Some(cache) = self.cache() + && let Some(cached) = cache.cell_data_hash.lock().get(&key) + { + return Some(cached.clone()); }; let ret = self.get(COLUMN_CELL_DATA_HASH, &key).map(|raw| { @@ -450,10 +452,10 @@ pub trait ChainStore: Send + Sync + Sized { /// Returns true if a block with the given hash exists in the store. fn block_exists(&self, hash: &packed::Byte32) -> bool { - if let Some(cache) = self.cache() { - if cache.headers.lock().get(hash).is_some() { - return true; - } + if let Some(cache) = self.cache() + && cache.headers.lock().get(hash).is_some() + { + return true; }; self.get(COLUMN_BLOCK_HEADER, hash.as_slice()).is_some() } diff --git a/store/src/transaction.rs b/store/src/transaction.rs index f1cfbff440..cb0f5b7805 100644 --- a/store/src/transaction.rs +++ b/store/src/transaction.rs @@ -49,7 +49,7 @@ impl ChainStore for StoreTransaction { .expect("db operation should be ok") } - fn get_iter(&self, col: Col, mode: IteratorMode) -> DBIter { + fn get_iter(&self, col: Col, mode: IteratorMode) -> DBIter<'_> { self.inner .iter(col, mode) .expect("db operation should be ok") @@ -78,11 +78,9 @@ impl CellProvider for StoreTransaction { fn cell(&self, out_point: &OutPoint, eager_load: bool) -> CellStatus { match self.get_cell(out_point) { Some(mut cell_meta) => { - if eager_load { - if let Some((data, data_hash)) = self.get_cell_data(out_point) { - cell_meta.mem_cell_data = Some(data); - cell_meta.mem_cell_data_hash = Some(data_hash); - } + if eager_load && let Some((data, data_hash)) = self.get_cell_data(out_point) { + cell_meta.mem_cell_data = Some(data); + cell_meta.mem_cell_data_hash = Some(data_hash); } CellStatus::live_cell(cell_meta) } @@ -116,13 +114,13 @@ impl<'a> ChainStore for StoreTransactionSnapshot<'a> { self.freezer.as_ref() } - fn get(&self, col: Col, key: &[u8]) -> Option { + fn get(&self, col: Col, key: &[u8]) -> Option> { self.inner .get_pinned(col, key) .expect("db operation should be ok") } - fn get_iter(&self, col: Col, mode: IteratorMode) -> DBIter { + fn get_iter(&self, col: Col, mode: IteratorMode) -> DBIter<'_> { self.inner .iter(col, mode) .expect("db operation should be ok") diff --git a/sync/src/relayer/tests/compact_block_process.rs b/sync/src/relayer/tests/compact_block_process.rs index 4866a6d675..a9ab319931 100644 --- a/sync/src/relayer/tests/compact_block_process.rs +++ b/sync/src/relayer/tests/compact_block_process.rs @@ -176,12 +176,12 @@ fn test_accept_not_a_better_block() { }; let second_to_last_header: HeaderView = { let tip_header: HeaderView = relayer.shared().store().get_tip_header().unwrap(); - let second_to_last_header = relayer + + relayer .shared() .store() .get_block_header(&tip_header.data().raw().parent_hash()) - .unwrap(); - second_to_last_header + .unwrap() }; let rt = tokio::runtime::Builder::new_current_thread() diff --git a/sync/src/synchronizer/block_process.rs b/sync/src/synchronizer/block_process.rs index 2aad02bfd2..7c642aca9c 100644 --- a/sync/src/synchronizer/block_process.rs +++ b/sync/src/synchronizer/block_process.rs @@ -90,19 +90,17 @@ impl<'a> BlockProcess<'a> { ); let shared = self.synchronizer.shared(); - if shared.new_block_received(&block) { - if let Err(err) = self + if shared.new_block_received(&block) + && let Err(err) = self .synchronizer .blocking_process_new_block(block.clone(), self.peer) - { - if !ckb_error::is_internal_db_error(&err) { - return crate::StatusCode::BlockIsInvalid.with_context(format!( - "{}, error: {}", - block.hash(), - err, - )); - } - } + && !ckb_error::is_internal_db_error(&err) + { + return crate::StatusCode::BlockIsInvalid.with_context(format!( + "{}, error: {}", + block.hash(), + err, + )); } crate::Status::ok() } diff --git a/sync/src/synchronizer/get_headers_process.rs b/sync/src/synchronizer/get_headers_process.rs index 38249fa719..809c2b7700 100644 --- a/sync/src/synchronizer/get_headers_process.rs +++ b/sync/src/synchronizer/get_headers_process.rs @@ -57,10 +57,10 @@ impl<'a> GetHeadersProcess<'a> { ); self.send_in_ibd(); let shared = self.synchronizer.shared(); - if let Some(flag) = shared.state().peers().get_flag(self.peer) { - if flag.is_outbound || flag.is_whitelist || flag.is_protect { - shared.insert_peer_unknown_header_list(self.peer, block_locator_hashes); - } + if let Some(flag) = shared.state().peers().get_flag(self.peer) + && (flag.is_outbound || flag.is_whitelist || flag.is_protect) + { + shared.insert_peer_unknown_header_list(self.peer, block_locator_hashes); }; return Status::ignored(); } diff --git a/sync/src/synchronizer/headers_process.rs b/sync/src/synchronizer/headers_process.rs index c6c3de8ce7..b88824ee55 100644 --- a/sync/src/synchronizer/headers_process.rs +++ b/sync/src/synchronizer/headers_process.rs @@ -39,15 +39,15 @@ impl<'a> HeadersProcess<'a> { fn is_continuous(&self, headers: &[core::HeaderView]) -> bool { for window in headers.windows(2) { - if let [parent, header] = &window { - if header.data().raw().parent_hash() != parent.hash() { - debug!( - "header.parent_hash {} parent.hash {}", - header.parent_hash(), - parent.hash() - ); - return false; - } + if let [parent, header] = &window + && header.data().raw().parent_hash() != parent.hash() + { + debug!( + "header.parent_hash {} parent.hash {}", + header.parent_hash(), + parent.hash() + ); + return false; } } true diff --git a/sync/src/synchronizer/mod.rs b/sync/src/synchronizer/mod.rs index 0969a560f0..f570167dcd 100644 --- a/sync/src/synchronizer/mod.rs +++ b/sync/src/synchronizer/mod.rs @@ -124,7 +124,7 @@ impl BlockFetchCMD { CanStart::MinWorkNotReach => { let best_known = self.sync_shared.state().shared_best_header_ref(); let number = best_known.number(); - if number != self.number && (number - self.number) % 10000 == 0 { + if number != self.number && (number - self.number).is_multiple_of(10000) { self.number = number; info!( "The current best known header number: {}, total difficulty: {:#x}. \ @@ -147,7 +147,7 @@ impl BlockFetchCMD { .map(Pack::pack) .expect("assume valid target must exist"); - if number != self.number && (number - self.number) % 10000 == 0 { + if number != self.number && (number - self.number).is_multiple_of(10000) { self.number = number; let remaining_headers_sync_log = self.reaming_headers_sync_log(); diff --git a/sync/src/types/mod.rs b/sync/src/types/mod.rs index b7dccdc9a7..60c0de21ad 100644 --- a/sync/src/types/mod.rs +++ b/sync/src/types/mod.rs @@ -720,18 +720,18 @@ impl InflightBlocks { // If the time exceeds low time limit, delete the task and halve the number of // executable tasks for the corresponding node if now > timeout_limit + *time { - if let Some(state) = states.remove(key) { - if let Some(d) = download_schedulers.get_mut(&state.peer) { - if should_punish && adjustment { - d.punish(1); - } - d.hashes.remove(key); - debug!( - "prune: remove download_schedulers: remove {}-{} from {}", - key.number, key.hash, state.peer - ); - }; - } + if let Some(state) = states.remove(key) + && let Some(d) = download_schedulers.get_mut(&state.peer) + { + if should_punish && adjustment { + d.punish(1); + } + d.hashes.remove(key); + debug!( + "prune: remove download_schedulers: remove {}-{} from {}", + key.number, key.hash, state.peer + ); + }; if key.number > *restart_number { *restart_number = key.number; @@ -955,10 +955,10 @@ impl Peers { if !state.unknown_header_list.is_empty() { return None; } - if let Some(ref header) = state.best_known_header { - if header.number() < tip { - return Some(*peer_index); - } + if let Some(ref header) = state.best_known_header + && header.number() < tip + { + return Some(*peer_index); } None }) @@ -1368,11 +1368,11 @@ impl SyncState { self.pending_compact_blocks.lock().await } - pub fn read_inflight_blocks(&self) -> RwLockReadGuard { + pub fn read_inflight_blocks(&self) -> RwLockReadGuard<'_, InflightBlocks> { self.inflight_blocks.read() } - pub fn write_inflight_blocks(&self) -> RwLockWriteGuard { + pub fn write_inflight_blocks(&self) -> RwLockWriteGuard<'_, InflightBlocks> { self.inflight_blocks.write() } @@ -1384,7 +1384,7 @@ impl SyncState { self.shared_best_header.read().to_owned() } - pub fn shared_best_header_ref(&self) -> RwLockReadGuard { + pub fn shared_best_header_ref(&self) -> RwLockReadGuard<'_, HeaderIndexView> { self.shared_best_header.read() } @@ -1528,13 +1528,13 @@ impl SyncState { self.tx_filter.lock().contains(hash) } - pub fn tx_filter(&self) -> MutexGuard> { + pub fn tx_filter(&self) -> MutexGuard<'_, TtlFilter> { self.tx_filter.lock() } pub fn unknown_tx_hashes( &self, - ) -> MutexGuard> { + ) -> MutexGuard<'_, KeyedPriorityQueue> { self.unknown_tx_hashes.lock() } diff --git a/test/src/node.rs b/test/src/node.rs index 416bedc71a..7f5e18d14f 100644 --- a/test/src/node.rs +++ b/test/src/node.rs @@ -219,16 +219,14 @@ impl Node { } pub fn get_onion_public_addr(&self) -> Option { - let onion_public_addr = self - .rpc_client() + self.rpc_client() .local_node_info() .addresses .iter() .filter(|addr| addr.address.contains("/onion3/")) .collect::>() .first() - .map(|addr| addr.address.clone()); - onion_public_addr + .map(|addr| addr.address.clone()) } pub fn p2p_address(&self) -> String { @@ -916,16 +914,16 @@ impl Node { #[allow(unused_mut)] pub fn stop_gracefully(&mut self) { let guard = self.take_guard(); - if let Some(mut guard) = guard { - if !guard.killed { - // on nix: send SIGINT to the child - // on windows: don't kill gracefully..... fix later - #[cfg(not(target_os = "windows"))] - { - Self::kill_gracefully(guard.child.id()); - let _ = guard.child.wait(); - guard.killed = true; - } + if let Some(mut guard) = guard + && !guard.killed + { + // on nix: send SIGINT to the child + // on windows: don't kill gracefully..... fix later + #[cfg(not(target_os = "windows"))] + { + Self::kill_gracefully(guard.child.id()); + let _ = guard.child.wait(); + guard.killed = true; } } } @@ -1032,12 +1030,11 @@ pub fn make_bootnodes_for_all>(nodes: &mut [N]) { let other_node_addrs: Vec> = node_multiaddrs .keys() .map(|id| { - let addrs = node_multiaddrs + node_multiaddrs .iter() .filter(|(other_id, _)| other_id.as_str() != id.as_str()) .map(|(_, addr)| addr.to_owned()) - .collect::>(); - addrs + .collect::>() }) .collect(); for (i, node) in nodes.iter_mut().enumerate() { diff --git a/test/src/specs/sync/get_blocks.rs b/test/src/specs/sync/get_blocks.rs index 9004f41fd6..9213b5d073 100644 --- a/test/src/specs/sync/get_blocks.rs +++ b/test/src/specs/sync/get_blocks.rs @@ -74,17 +74,16 @@ fn wait_get_blocks_point( let instant = Instant::now(); let mut last_hash = None; while instant.elapsed() < Duration::from_secs(secs) { - if let Ok((_, _, data)) = net.receive_timeout(node, Duration::from_secs(1)) { - if let Ok(message) = packed::SyncMessage::from_slice(&data) { - if let packed::SyncMessageUnion::GetBlocks(inner) = message.to_enum() { - count += inner.block_hashes().len(); - if let Some(hash) = inner.block_hashes().into_iter().last() { - last_hash = Some(hash); - } - if count >= expected_count { - break; - } - } + if let Ok((_, _, data)) = net.receive_timeout(node, Duration::from_secs(1)) + && let Ok(message) = packed::SyncMessage::from_slice(&data) + && let packed::SyncMessageUnion::GetBlocks(inner) = message.to_enum() + { + count += inner.block_hashes().len(); + if let Some(hash) = inner.block_hashes().into_iter().last() { + last_hash = Some(hash); + } + if count >= expected_count { + break; } } } diff --git a/test/src/specs/sync/invalid_block.rs b/test/src/specs/sync/invalid_block.rs index 816b9f1d22..8751b94709 100644 --- a/test/src/specs/sync/invalid_block.rs +++ b/test/src/specs/sync/invalid_block.rs @@ -155,10 +155,10 @@ impl Spec for ForkContainsInvalidBlock { build_get_blocks(&bad_hashes), ); let ret = wait_until(10, || { - if let Ok((_, _, data)) = net.receive_timeout(&good_node, Duration::from_secs(10)) { - if let Ok(message) = SyncMessage::from_slice(&data) { - return message.to_enum().item_name() == packed::SendBlock::NAME; - } + if let Ok((_, _, data)) = net.receive_timeout(&good_node, Duration::from_secs(10)) + && let Ok(message) = SyncMessage::from_slice(&data) + { + return message.to_enum().item_name() == packed::SendBlock::NAME; } false }); diff --git a/test/src/specs/tx_pool/dead_cell_deps.rs b/test/src/specs/tx_pool/dead_cell_deps.rs index 77ae8fb619..57c97ea3b2 100644 --- a/test/src/specs/tx_pool/dead_cell_deps.rs +++ b/test/src/specs/tx_pool/dead_cell_deps.rs @@ -214,7 +214,7 @@ impl Spec for CellBeingCellDepAndSpentInSameBlockTestGetBlockTemplate { tx.as_advanced_builder().cell_dep(cell_dep_to_tx_a).build() }; - let b_weightier_than_c = rand::random::() % 2 == 0; + let b_weightier_than_c = rand::random::().is_multiple_of(2); if b_weightier_than_c { // make B's fee >> C's fee, which means B's tx-weight > C's tx-weight let minimum_outputs_capacity = tx_b diff --git a/test/src/utils.rs b/test/src/utils.rs index 9084dbe37c..4434922564 100644 --- a/test/src/utils.rs +++ b/test/src/utils.rs @@ -66,7 +66,7 @@ pub fn build_block_transactions(block: &BlockView) -> Bytes { } pub fn build_header(header: &HeaderView) -> Bytes { - build_headers(&[header.clone()]) + build_headers(std::slice::from_ref(header)) } pub fn build_headers(headers: &[HeaderView]) -> Bytes { diff --git a/tx-pool/src/block_assembler/process.rs b/tx-pool/src/block_assembler/process.rs index 103484b65f..be451fa07d 100644 --- a/tx-pool/src/block_assembler/process.rs +++ b/tx-pool/src/block_assembler/process.rs @@ -9,10 +9,10 @@ pub(crate) async fn process(service: TxPoolService, message: &BlockAssemblerMess } } BlockAssemblerMessage::Proposed => { - if let Some(ref block_assembler) = service.block_assembler { - if let Err(e) = block_assembler.update_transactions(&service.tx_pool).await { - ckb_logger::error!("block_assembler update_transactions error {}", e); - } + if let Some(ref block_assembler) = service.block_assembler + && let Err(e) = block_assembler.update_transactions(&service.tx_pool).await + { + ckb_logger::error!("block_assembler update_transactions error {}", e); } } BlockAssemblerMessage::Uncle => { @@ -21,10 +21,10 @@ pub(crate) async fn process(service: TxPoolService, message: &BlockAssemblerMess } } BlockAssemblerMessage::Reset(snapshot) => { - if let Some(ref block_assembler) = service.block_assembler { - if let Err(e) = block_assembler.update_blank(Arc::clone(snapshot)).await { - ckb_logger::error!("block_assembler update_blank error {}", e); - } + if let Some(ref block_assembler) = service.block_assembler + && let Err(e) = block_assembler.update_blank(Arc::clone(snapshot)).await + { + ckb_logger::error!("block_assembler update_blank error {}", e); } } } diff --git a/tx-pool/src/component/commit_txs_scanner.rs b/tx-pool/src/component/commit_txs_scanner.rs index 7795a711c4..720ffc9c93 100644 --- a/tx-pool/src/component/commit_txs_scanner.rs +++ b/tx-pool/src/component/commit_txs_scanner.rs @@ -86,11 +86,11 @@ impl<'a> CommitTxsScanner<'a> { loop { let mut using_modified = false; - if let Some(entry) = iter.peek() { - if self.skip_proposed_entry(&entry.proposal_short_id()) { - iter.next(); - continue; - } + if let Some(entry) = iter.peek() + && self.skip_proposed_entry(&entry.proposal_short_id()) + { + iter.next(); + continue; } // First try to find a new transaction in `proposed_pool` to evaluate. diff --git a/tx-pool/src/component/pool_map.rs b/tx-pool/src/component/pool_map.rs index 0e84727245..449feb7f22 100644 --- a/tx-pool/src/component/pool_map.rs +++ b/tx-pool/src/component/pool_map.rs @@ -196,7 +196,7 @@ impl PoolMap { /// Returns `Reject` when any error happened, otherwise return `Ok((succ, evicts))` /// - succ : means whether the entry is inserted actually into pool, /// - evicts: is the evicted transactions before inserting this `TxEntry`, - /// Currently, evicts when inserting is only due to referring cell dep will be consumed by this new transaction. + /// Currently, evicts when inserting is only due to referring cell dep will be consumed by this new transaction. pub(crate) fn add_entry( &mut self, mut entry: TxEntry, @@ -307,7 +307,7 @@ impl PoolMap { let entries = self.remove_entry_and_descendants(&id); if !entries.is_empty() { let reject = Reject::Resolve(OutPointError::Dead(i.clone())); - let rejects = std::iter::repeat(reject).take(entries.len()); + let rejects = std::iter::repeat_n(reject, entries.len()); conflicts.extend(entries.into_iter().zip(rejects)); } } @@ -318,7 +318,7 @@ impl PoolMap { let entries = self.remove_entry_and_descendants(&id); if !entries.is_empty() { let reject = Reject::Resolve(OutPointError::Dead(i.clone())); - let rejects = std::iter::repeat(reject).take(entries.len()); + let rejects = std::iter::repeat_n(reject, entries.len()); conflicts.extend(entries.into_iter().zip(rejects)); } } diff --git a/tx-pool/src/pool.rs b/tx-pool/src/pool.rs index 5a7ff07551..dff3cec755 100644 --- a/tx-pool/src/pool.rs +++ b/tx-pool/src/pool.rs @@ -315,10 +315,10 @@ impl TxPool { "the fee_rate for this transaction is: {}", entry.fee_rate() )); - if let Some(short_id) = current_entry_id { - if entry.proposal_short_id() == *short_id { - ret = Some(reject.clone()); - } + if let Some(short_id) = current_entry_id + && entry.proposal_short_id() == *short_id + { + ret = Some(reject.clone()); } callbacks.call_reject(self, &entry, reject); } diff --git a/tx-pool/src/process.rs b/tx-pool/src/process.rs index 3e571bf6d2..56c69aaf8d 100644 --- a/tx-pool/src/process.rs +++ b/tx-pool/src/process.rs @@ -333,11 +333,11 @@ impl TxPoolService { remote: Option<(Cycle, PeerIndex)>, ) -> Result<(), Reject> { if let Err(reject) = non_contextual_verify(&self.consensus, tx) { - if reject.is_malformed_tx() { - if let Some(remote) = remote { - self.ban_malformed(remote.1, format!("reject {reject}")) - .await; - } + if reject.is_malformed_tx() + && let Some(remote) = remote + { + self.ban_malformed(remote.1, format!("reject {reject}")) + .await; } return Err(reject); } @@ -407,13 +407,13 @@ impl TxPoolService { pub(crate) async fn put_recent_reject(&self, tx_hash: &Byte32, reject: &Reject) { let mut tx_pool = self.tx_pool.write().await; - if let Some(ref mut recent_reject) = tx_pool.recent_reject { - if let Err(e) = recent_reject.put(tx_hash, reject.clone()) { - error!( - "Failed to record recent_reject {} {} {}", - tx_hash, reject, e - ); - } + if let Some(ref mut recent_reject) = tx_pool.recent_reject + && let Err(e) = recent_reject.put(tx_hash, reject.clone()) + { + error!( + "Failed to record recent_reject {} {} {}", + tx_hash, reject, e + ); } } @@ -445,15 +445,15 @@ impl TxPoolService { let tx_hash = tx.hash(); // log tx verification result for monitor node - if log_enabled_target!("ckb_tx_monitor", Trace) { - if let Ok(c) = ret { - trace_target!( - "ckb_tx_monitor", - r#"{{"tx_hash":"{:#x}","cycles":{}}}"#, - tx_hash, - c.cycles - ); - } + if log_enabled_target!("ckb_tx_monitor", Trace) + && let Ok(c) = ret + { + trace_target!( + "ckb_tx_monitor", + r#"{{"tx_hash":"{:#x}","cycles":{}}}"#, + tx_hash, + c.cycles + ); } if matches!( @@ -696,17 +696,17 @@ impl TxPoolService { let verified = try_or_return_with_snapshot!(verified_ret, snapshot); - if let Some(declared) = declared_cycles { - if declared != verified.cycles { - info!( - "process_tx declared cycles not match verified cycles, declared: {:?} verified: {:?}, tx: {:?}", - declared, verified.cycles, tx - ); - return Some(( - Err(Reject::DeclaredWrongCycles(declared, verified.cycles)), - snapshot, - )); - } + if let Some(declared) = declared_cycles + && declared != verified.cycles + { + info!( + "process_tx declared cycles not match verified cycles, declared: {:?} verified: {:?}, tx: {:?}", + declared, verified.cycles, tx + ); + return Some(( + Err(Reject::DeclaredWrongCycles(declared, verified.cycles)), + snapshot, + )); } let entry = TxEntry::new(rtx, verified.cycles, fee, tx_size); @@ -845,28 +845,28 @@ impl TxPoolService { for tx in txs { let tx_size = tx.data().serialized_size_in_block(); let tx_hash = tx.hash(); - if let Ok((rtx, status)) = resolve_tx(tx_pool, tx_pool.snapshot(), tx, false) { - if let Ok(fee) = check_tx_fee(tx_pool, tx_pool.snapshot(), &rtx, tx_size) { - let verify_cache = fetched_cache.get(&tx_hash).cloned(); - let snapshot = tx_pool.cloned_snapshot(); - let tip_header = snapshot.tip_header(); - let tx_env = Arc::new(status.with_env(tip_header)); - if let Ok(verified) = verify_rtx( - snapshot, - Arc::clone(&rtx), - tx_env, - &verify_cache, - max_cycles, - None, - ) - .await - { - let entry = TxEntry::new(rtx, verified.cycles, fee, tx_size); - if let Err(e) = _submit_entry(tx_pool, status, entry, &self.callbacks) { - error!("readd_detached_tx submit_entry {} error {}", tx_hash, e); - } else { - debug!("readd_detached_tx submit_entry {}", tx_hash); - } + if let Ok((rtx, status)) = resolve_tx(tx_pool, tx_pool.snapshot(), tx, false) + && let Ok(fee) = check_tx_fee(tx_pool, tx_pool.snapshot(), &rtx, tx_size) + { + let verify_cache = fetched_cache.get(&tx_hash).cloned(); + let snapshot = tx_pool.cloned_snapshot(); + let tip_header = snapshot.tip_header(); + let tx_env = Arc::new(status.with_env(tip_header)); + if let Ok(verified) = verify_rtx( + snapshot, + Arc::clone(&rtx), + tx_env, + &verify_cache, + max_cycles, + None, + ) + .await + { + let entry = TxEntry::new(rtx, verified.cycles, fee, tx_size); + if let Err(e) = _submit_entry(tx_pool, status, entry, &self.callbacks) { + error!("readd_detached_tx submit_entry {} error {}", tx_hash, e); + } else { + debug!("readd_detached_tx submit_entry {}", tx_hash); } } } diff --git a/tx-pool/src/service.rs b/tx-pool/src/service.rs index 98182caeee..3c534ade9b 100644 --- a/tx-pool/src/service.rs +++ b/tx-pool/src/service.rs @@ -668,11 +668,10 @@ impl TxPoolServiceBuilder { let service_clone = process_service.clone(); block_assembler::process(service_clone, message).await; } - if !queue.is_empty() { - if let Some(ref block_assembler) = process_service.block_assembler { + if !queue.is_empty() + && let Some(ref block_assembler) = process_service.block_assembler { block_assembler.notify().await; } - } queue.clear(); } _ = signal_receiver.cancelled() => { @@ -1102,11 +1101,9 @@ impl TxPoolService { match provider.cell(&out_point, false) { CellStatus::Live(mut cell_meta) => { - if eager_load { - if let Some((data, data_hash)) = snapshot.get_cell_data(&out_point) { - cell_meta.mem_cell_data = Some(data); - cell_meta.mem_cell_data_hash = Some(data_hash); - } + if eager_load && let Some((data, data_hash)) = snapshot.get_cell_data(&out_point) { + cell_meta.mem_cell_data = Some(data); + cell_meta.mem_cell_data_hash = Some(data_hash); } CellStatus::live_cell(cell_meta) } diff --git a/util/app-config/src/configs/db.rs b/util/app-config/src/configs/db.rs index 1cbd154231..5560f98a27 100644 --- a/util/app-config/src/configs/db.rs +++ b/util/app-config/src/configs/db.rs @@ -41,11 +41,11 @@ impl Config { self.path = root_dir.to_path_buf().join(&self.path) } // If options file is a relative path, set the base path to `ckb.toml` - if let Some(file) = self.options_file.iter_mut().next() { - if file.is_relative() { - let file_new = root_dir.to_path_buf().join(&file); - *file = file_new; - } + if let Some(file) = self.options_file.iter_mut().next() + && file.is_relative() + { + let file_new = root_dir.to_path_buf().join(&file); + *file = file_new; } } } diff --git a/util/app-config/src/configs/notify.rs b/util/app-config/src/configs/notify.rs index ab6f3cf00a..f46ed285ba 100644 --- a/util/app-config/src/configs/notify.rs +++ b/util/app-config/src/configs/notify.rs @@ -31,13 +31,13 @@ where { let op = Option::::deserialize(d)?; - if let Some(ref value) = op { - if value < &100 { - return Err(serde::de::Error::invalid_value( - serde::de::Unexpected::Unsigned(*value), - &"a value at least 100", - )); - } + if let Some(ref value) = op + && value < &100 + { + return Err(serde::de::Error::invalid_value( + serde::de::Unexpected::Unsigned(*value), + &"a value at least 100", + )); } Ok(op) } diff --git a/util/dao/src/lib.rs b/util/dao/src/lib.rs index bbf22a38d0..cf81e22ce7 100644 --- a/util/dao/src/lib.rs +++ b/util/dao/src/lib.rs @@ -324,14 +324,13 @@ pub fn modified_occupied_capacity( cell_meta: &CellMeta, consensus: &Consensus, ) -> CapacityResult { - if let Some(tx_info) = &cell_meta.transaction_info { - if tx_info.is_genesis() - && tx_info.is_cellbase() - && cell_meta.cell_output.lock().args().raw_data() == consensus.satoshi_pubkey_hash.0[..] - { - return Into::::into(cell_meta.cell_output.capacity()) - .safe_mul_ratio(consensus.satoshi_cell_occupied_ratio); - } + if let Some(tx_info) = &cell_meta.transaction_info + && tx_info.is_genesis() + && tx_info.is_cellbase() + && cell_meta.cell_output.lock().args().raw_data() == consensus.satoshi_pubkey_hash.0[..] + { + return Into::::into(cell_meta.cell_output.capacity()) + .safe_mul_ratio(consensus.satoshi_cell_occupied_ratio); } cell_meta.occupied_capacity() } diff --git a/util/gen-types/src/core.rs b/util/gen-types/src/core.rs index 695270def6..2ce54527b3 100644 --- a/util/gen-types/src/core.rs +++ b/util/gen-types/src/core.rs @@ -37,7 +37,7 @@ impl ScriptHashType { /// when the low 1 bit is 0, it indicates the data #[inline] pub fn verify_value(v: u8) -> bool { - v % 2 == 0 || v == 1 + v.is_multiple_of(2) || v == 1 } } diff --git a/util/gen-types/src/extension/serialized_size.rs b/util/gen-types/src/extension/serialized_size.rs index 027cb9e6a6..c0d07a9642 100644 --- a/util/gen-types/src/extension/serialized_size.rs +++ b/util/gen-types/src/extension/serialized_size.rs @@ -78,8 +78,8 @@ impl packed::UncleBlock { /// The block has 1 more uncle: /// - the block will has 1 more offset (+NUM_SIZE) in UncleBlockVec /// - UncleBlockVec has 1 more UncleBlock. - /// UncleBlock comes with 1 `total` field, and 2 field offsets, (+NUM_SIZE * 3) - /// UncleBlock contains Header (+208) and empty proposals (only one total_size, + NUM_SIZE because it is a fixVec) + /// UncleBlock comes with 1 `total` field, and 2 field offsets, (+NUM_SIZE * 3) + /// UncleBlock contains Header (+208) and empty proposals (only one total_size, + NUM_SIZE because it is a fixVec) /// /// The total is +NUM_SIZE*5 + Header.size() = 228 /// see tests block_size_should_not_include_uncles_proposals. diff --git a/util/gen-types/src/extension/shortcut.rs b/util/gen-types/src/extension/shortcut.rs index 8e944d4f50..e00ccc444e 100644 --- a/util/gen-types/src/extension/shortcut.rs +++ b/util/gen-types/src/extension/shortcut.rs @@ -252,7 +252,7 @@ impl<'r> packed::BlockReader<'r> { /// # Panics /// /// Panics if the first extra field exists but not a valid [`BytesReader`](struct.BytesReader.html). - pub fn extension(&self) -> Option { + pub fn extension(&self) -> Option> { self.extra_field(0) .map(|data| packed::BytesReader::from_slice(data).unwrap()) } @@ -260,7 +260,7 @@ impl<'r> packed::BlockReader<'r> { impl<'r> packed::BlockV1Reader<'r> { /// Converts to a compatible [`BlockReader`](struct.BlockReader.html) with an extra field. - pub fn as_v0(&self) -> packed::BlockReader { + pub fn as_v0(&self) -> packed::BlockReader<'_> { packed::BlockReader::new_unchecked(self.as_slice()) } } @@ -274,7 +274,7 @@ impl packed::CompactBlockV1 { impl<'r> packed::CompactBlockV1Reader<'r> { /// Converts to a compatible [`CompactBlockReader`](struct.CompactBlockReader.html) with an extra field. - pub fn as_v0(&self) -> packed::CompactBlockReader { + pub fn as_v0(&self) -> packed::CompactBlockReader<'_> { packed::CompactBlockReader::new_unchecked(self.as_slice()) } } diff --git a/util/indexer-sync/src/lib.rs b/util/indexer-sync/src/lib.rs index 94dc1d1935..6043588acc 100644 --- a/util/indexer-sync/src/lib.rs +++ b/util/indexer-sync/src/lib.rs @@ -108,12 +108,11 @@ impl IndexerSyncService { let indexer_tip = indexer_service .tip() .expect("indexer_service tip should be OK"); - if let Some((indexer_tip, _)) = indexer_tip { - if let Some(init_tip) = self.secondary_db.get_block_header(&init_tip_hash.into()) { - if indexer_tip >= init_tip.number() { - return; - } - } + if let Some((indexer_tip, _)) = indexer_tip + && let Some(init_tip) = self.secondary_db.get_block_header(&init_tip_hash.into()) + && indexer_tip >= init_tip.number() + { + return; } loop { if has_received_stop_signal() { diff --git a/util/indexer-sync/src/store.rs b/util/indexer-sync/src/store.rs index 90e1495656..d57bbcbb53 100644 --- a/util/indexer-sync/src/store.rs +++ b/util/indexer-sync/src/store.rs @@ -68,7 +68,7 @@ impl SecondaryDB { /// Return the value associated with a key using RocksDB's PinnableSlice from the given column /// so as to avoid unnecessary memory copy. - pub fn get_pinned(&self, col: Col, key: &[u8]) -> Result, Error> { + pub fn get_pinned(&self, col: Col, key: &[u8]) -> Result>, Error> { let cf = self .inner .cf_handle(col) @@ -91,7 +91,7 @@ impl SecondaryDB { } /// This is used when you want to iterate over a specific ColumnFamily - fn iter(&self, col: Col, mode: IteratorMode) -> Result { + fn iter(&self, col: Col, mode: IteratorMode) -> Result, Error> { let opts = ReadOptions::default(); let cf = self .inner @@ -112,12 +112,12 @@ impl ChainStore for SecondaryDB { None } - fn get(&self, col: Col, key: &[u8]) -> Option { + fn get(&self, col: Col, key: &[u8]) -> Option> { self.get_pinned(col, key) .expect("db operation should be ok") } - fn get_iter(&self, col: Col, mode: IteratorMode) -> DBIterator { + fn get_iter(&self, col: Col, mode: IteratorMode) -> DBIterator<'_> { self.iter(col, mode).expect("db operation should be ok") } } diff --git a/util/indexer/src/indexer.rs b/util/indexer/src/indexer.rs index 006fc4e2a4..9307dad329 100644 --- a/util/indexer/src/indexer.rs +++ b/util/indexer/src/indexer.rs @@ -514,7 +514,7 @@ where pool.transactions_committed(&transactions); } - if block_number % self.prune_interval == 0 { + if block_number.is_multiple_of(self.prune_interval) { self.prune()?; } diff --git a/util/indexer/src/service.rs b/util/indexer/src/service.rs index baff28230f..a4b8f5e215 100644 --- a/util/indexer/src/service.rs +++ b/util/indexer/src/service.rs @@ -335,10 +335,10 @@ impl IndexerHandle { } } - if let Some([r0, r1]) = filter_options.output_data_len_range { - if output_data.len() < r0 || output_data.len() >= r1 { - return None; - } + if let Some([r0, r1]) = filter_options.output_data_len_range + && (output_data.len() < r0 || output_data.len() >= r1) + { + return None; } if let Some([r0, r1]) = filter_options.output_capacity_range { @@ -348,10 +348,10 @@ impl IndexerHandle { } } - if let Some([r0, r1]) = filter_options.block_range { - if block_number < r0 || block_number >= r1 { - return None; - } + if let Some([r0, r1]) = filter_options.block_range + && (block_number < r0 || block_number >= r1) + { + return None; } last_key = key.to_vec(); @@ -544,10 +544,10 @@ impl IndexerHandle { } } - if let Some([r0, r1]) = filter_block_range { - if block_number < r0 || block_number >= r1 { - continue; - } + if let Some([r0, r1]) = filter_block_range + && (block_number < r0 || block_number >= r1) + { + continue; } let last_tx_hash_is_same = tx_with_cells @@ -656,10 +656,10 @@ impl IndexerHandle { } } - if let Some([r0, r1]) = filter_block_range { - if block_number < r0 || block_number >= r1 { - return None; - } + if let Some([r0, r1]) = filter_block_range + && (block_number < r0 || block_number >= r1) + { + return None; } last_key = key.to_vec(); @@ -812,10 +812,10 @@ impl IndexerHandle { } } - if let Some([r0, r1]) = filter_options.output_data_len_range { - if output_data.len() < r0 || output_data.len() >= r1 { - return None; - } + if let Some([r0, r1]) = filter_options.output_data_len_range + && (output_data.len() < r0 || output_data.len() >= r1) + { + return None; } if let Some([r0, r1]) = filter_options.output_capacity_range { @@ -825,10 +825,10 @@ impl IndexerHandle { } } - if let Some([r0, r1]) = filter_options.block_range { - if block_number < r0 || block_number >= r1 { - return None; - } + if let Some([r0, r1]) = filter_options.block_range + && (block_number < r0 || block_number >= r1) + { + return None; } Some(Into::::into(output.capacity()).as_u64()) diff --git a/util/jsonrpc-types/src/fee_estimator.rs b/util/jsonrpc-types/src/fee_estimator.rs index 0c1821d061..2a9305fadb 100644 --- a/util/jsonrpc-types/src/fee_estimator.rs +++ b/util/jsonrpc-types/src/fee_estimator.rs @@ -6,8 +6,10 @@ use schemars::JsonSchema; /// The fee estimate mode. #[derive(Clone, Copy, Debug, Serialize, Deserialize, JsonSchema)] #[serde(rename_all = "snake_case")] +#[derive(Default)] pub enum EstimateMode { /// No priority, expect the transaction to be committed in 1 hour. + #[default] NoPriority, /// Low priority, expect the transaction to be committed in 30 minutes. LowPriority, @@ -17,12 +19,6 @@ pub enum EstimateMode { HighPriority, } -impl Default for EstimateMode { - fn default() -> Self { - Self::NoPriority - } -} - impl From for core::EstimateMode { fn from(json: EstimateMode) -> Self { match json { diff --git a/util/jsonrpc-types/src/indexer.rs b/util/jsonrpc-types/src/indexer.rs index 0f6099e5a1..16ff1c9130 100644 --- a/util/jsonrpc-types/src/indexer.rs +++ b/util/jsonrpc-types/src/indexer.rs @@ -79,8 +79,10 @@ impl Default for IndexerSearchKey { /// IndexerSearchMode represent search mode, default is prefix search #[derive(Deserialize, PartialEq, Eq, JsonSchema, Clone, Copy)] #[serde(rename_all = "snake_case")] +#[derive(Default)] pub enum IndexerSearchMode { /// Mode `prefix` search with prefix + #[default] Prefix, /// Mode `exact` search with exact match Exact, @@ -88,12 +90,6 @@ pub enum IndexerSearchMode { Partial, } -impl Default for IndexerSearchMode { - fn default() -> Self { - Self::Prefix - } -} - /// A array represent (half-open) range bounded inclusively below and exclusively above [start, end). /// /// ## Examples diff --git a/util/launcher/src/lib.rs b/util/launcher/src/lib.rs index 3760aa27cc..987729e300 100644 --- a/util/launcher/src/lib.rs +++ b/util/launcher/src/lib.rs @@ -146,34 +146,34 @@ impl Launcher { let store = shared.store(); let stored_spec_hash = store.get_chain_spec_hash(); - if stored_spec_hash.is_none() { + if let Some(stored_hash) = stored_spec_hash { + if stored_hash == self.args.chain_spec_hash { + // stored == configured + // do nothing + } else if self.args.overwrite_chain_spec { + // stored != configured with --overwrite-spec + self.write_chain_spec_hash(store)?; + info!( + "Overwrite chain spec hash from {} to {}", + stored_hash, self.args.overwrite_chain_spec, + ); + } else if self.args.skip_chain_spec_check { + // stored != configured with --skip-spec-check + // do nothing + } else { + // stored != configured + eprintln!( + "chain_spec_hash mismatch: Config({}), storage({}). \ + If the two chains are compatible, pass command line argument --skip-spec-check; \ + otherwise, pass --overwrite-spec to enforce overriding the stored chain spec with the configured one.", + self.args.chain_spec_hash, stored_hash + ); + return Err(ExitCode::Config); + } + } else { // fresh yet self.write_chain_spec_hash(store)?; info!("Touch chain spec hash: {}", self.args.chain_spec_hash); - } else if stored_spec_hash.as_ref() == Some(&self.args.chain_spec_hash) { - // stored == configured - // do nothing - } else if self.args.overwrite_chain_spec { - // stored != configured with --overwrite-spec - self.write_chain_spec_hash(store)?; - info!( - "Overwrite chain spec hash from {} to {}", - stored_spec_hash.expect("checked"), - self.args.overwrite_chain_spec, - ); - } else if self.args.skip_chain_spec_check { - // stored != configured with --skip-spec-check - // do nothing - } else { - // stored != configured - eprintln!( - "chain_spec_hash mismatch: Config({}), storage({}). \ - If the two chains are compatible, pass command line argument --skip-spec-check; \ - otherwise, pass --overwrite-spec to enforce overriding the stored chain spec with the configured one.", - self.args.chain_spec_hash, - stored_spec_hash.expect("checked") - ); - return Err(ExitCode::Config); } Ok(()) } @@ -318,13 +318,12 @@ impl Launcher { let mut iter = addr.iter(); if let (Some(Protocol::Ip4(ip)), Some(Protocol::Tcp(port))) = (iter.next(), iter.next()) + && (ip == Ipv4Addr::new(0, 0, 0, 0) + || ip == Ipv4Addr::new(127, 0, 0, 1)) { - if ip == Ipv4Addr::new(0, 0, 0, 0) - || ip == Ipv4Addr::new(127, 0, 0, 1) - { - return Some(port); - } + return Some(port); } + None }) } { diff --git a/util/light-client-protocol-server/src/components/get_last_state_proof.rs b/util/light-client-protocol-server/src/components/get_last_state_proof.rs index 219877b850..24e9c4b4b9 100644 --- a/util/light-client-protocol-server/src/components/get_last_state_proof.rs +++ b/util/light-client-protocol-server/src/components/get_last_state_proof.rs @@ -260,26 +260,26 @@ impl<'a> GetLastStateProofProcess<'a> { return StatusCode::InvalidRequest.with_context(errmsg); } // The first difficulty should be greater than the total difficulty before the start block. - if let Some(start_difficulty) = difficulties.first() { - if start_block_number > 0 { - let previous_block_number = start_block_number - 1; - if let Some(total_difficulty) = - sampler.get_block_total_difficulty(previous_block_number) - { - if total_difficulty >= *start_difficulty { - let errmsg = format!( - "the start difficulty is {start_difficulty:#x} too less than \ - the previous block #{previous_block_number} of the start block" - ); - return StatusCode::InvalidRequest.with_context(errmsg); - } - } else { + if let Some(start_difficulty) = difficulties.first() + && start_block_number > 0 + { + let previous_block_number = start_block_number - 1; + if let Some(total_difficulty) = + sampler.get_block_total_difficulty(previous_block_number) + { + if total_difficulty >= *start_difficulty { let errmsg = format!( - "the total difficulty for block#{previous_block_number} is not found" + "the start difficulty is {start_difficulty:#x} too less than \ + the previous block #{previous_block_number} of the start block" ); - return StatusCode::InternalError.with_context(errmsg); - }; - } + return StatusCode::InvalidRequest.with_context(errmsg); + } + } else { + let errmsg = format!( + "the total difficulty for block#{previous_block_number} is not found" + ); + return StatusCode::InternalError.with_context(errmsg); + }; } } diff --git a/util/logger-service/src/lib.rs b/util/logger-service/src/lib.rs index 84c4e71a79..09b1439e03 100644 --- a/util/logger-service/src/lib.rs +++ b/util/logger-service/src/lib.rs @@ -215,12 +215,12 @@ impl Logger { }; println!("{output}"); } - if main_logger.to_file { - if let Some(mut file) = main_logger.file.as_ref() { - let _ = file.write_all(removed_color.as_bytes()); - let _ = file.write_all(b"\n"); - }; - } + if main_logger.to_file + && let Some(mut file) = main_logger.file.as_ref() + { + let _ = file.write_all(removed_color.as_bytes()); + let _ = file.write_all(b"\n"); + }; } for name in extras { if let Some(mut file) = extra_files.get(&name) { diff --git a/util/migrate/src/migrations/table_to_struct.rs b/util/migrate/src/migrations/table_to_struct.rs index 54eee95de5..9fbf9bcc90 100644 --- a/util/migrate/src/migrations/table_to_struct.rs +++ b/util/migrate/src/migrations/table_to_struct.rs @@ -167,10 +167,10 @@ impl Migration for ChangeMoleculeTableToStruct { pb.inc(1); let mut wb = db.new_write_batch(); - if let Some(current_epoch) = db.get_pinned(COLUMN_META, META_CURRENT_EPOCH_KEY)? { - if current_epoch.len() != 108 { - wb.put(COLUMN_META, META_CURRENT_EPOCH_KEY, ¤t_epoch[36..])?; - } + if let Some(current_epoch) = db.get_pinned(COLUMN_META, META_CURRENT_EPOCH_KEY)? + && current_epoch.len() != 108 + { + wb.put(COLUMN_META, META_CURRENT_EPOCH_KEY, ¤t_epoch[36..])?; } db.write(&wb)?; diff --git a/util/onion/src/tor_controller.rs b/util/onion/src/tor_controller.rs index 7aab445689..3b2d027bd7 100644 --- a/util/onion/src/tor_controller.rs +++ b/util/onion/src/tor_controller.rs @@ -73,10 +73,10 @@ impl TorController { })?; debug!("tor server's uptime is {} seconds", uptime); let secs: u64 = uptime.parse().map_err(|err| { - ConnError::IOError(std::io::Error::new( - std::io::ErrorKind::Other, - format!("failed to parse uptime {} to u64 {}", uptime, err), - )) + ConnError::IOError(std::io::Error::other(format!( + "failed to parse uptime {} to u64 {}", + uptime, err + ))) })?; Ok(Duration::from_secs(secs)) } diff --git a/util/rich-indexer/src/indexer/mod.rs b/util/rich-indexer/src/indexer/mod.rs index fa5e8349c9..70719e70a7 100644 --- a/util/rich-indexer/src/indexer/mod.rs +++ b/util/rich-indexer/src/indexer/mod.rs @@ -206,14 +206,12 @@ impl AsyncRichIndexer { if self.custom_filters.is_cell_filter_enabled() { if let Some((output_id, output, output_data)) = query_output_cell(&out_point, tx).await? - { - if self + && self .custom_filters .is_cell_filter_match(&output, &output_data.into()) - { - build_input_rows(output_id, &input, input_index, &mut input_rows); - is_tx_matched = true; - } + { + build_input_rows(output_id, &input, input_index, &mut input_rows); + is_tx_matched = true; } } else if let Some(output_id) = query_output_id(&out_point, tx).await? { build_input_rows(output_id, &input, input_index, &mut input_rows); diff --git a/util/rich-indexer/src/indexer/remove.rs b/util/rich-indexer/src/indexer/remove.rs index 740634d179..60c4d7bbe0 100644 --- a/util/rich-indexer/src/indexer/remove.rs +++ b/util/rich-indexer/src/indexer/remove.rs @@ -30,10 +30,10 @@ pub(crate) async fn rollback_block(tx: &mut Transaction<'_, Any>) -> Result<(), if !script_exists_in_output(lock_script_id, tx).await? { script_id_list_to_remove.push(lock_script_id); } - if let Some(type_script_id) = type_script_id { - if !script_exists_in_output(type_script_id, tx).await? { - script_id_list_to_remove.push(type_script_id); - } + if let Some(type_script_id) = type_script_id + && !script_exists_in_output(type_script_id, tx).await? + { + script_id_list_to_remove.push(type_script_id); } } remove_batch_by_blobs("script", "id", &script_id_list_to_remove, tx).await?; diff --git a/util/rich-indexer/src/indexer_handle/async_indexer_handle/get_cells_capacity.rs b/util/rich-indexer/src/indexer_handle/async_indexer_handle/get_cells_capacity.rs index 3120836d03..20b42ccd64 100644 --- a/util/rich-indexer/src/indexer_handle/async_indexer_handle/get_cells_capacity.rs +++ b/util/rich-indexer/src/indexer_handle/async_indexer_handle/get_cells_capacity.rs @@ -35,36 +35,36 @@ impl AsyncRichIndexerHandle { } } let mut joined_ckb_transaction = false; - if let Some(ref filter) = search_key.filter { - if filter.block_range.is_some() { - query_builder - .join("ckb_transaction") - .on("output.tx_id = ckb_transaction.id") - .join("block") - .on("ckb_transaction.block_id = block.id"); - joined_ckb_transaction = true; - } + if let Some(ref filter) = search_key.filter + && filter.block_range.is_some() + { + query_builder + .join("ckb_transaction") + .on("output.tx_id = ckb_transaction.id") + .join("block") + .on("ckb_transaction.block_id = block.id"); + joined_ckb_transaction = true; } if self.pool.is_some() && !joined_ckb_transaction { query_builder .join("ckb_transaction") .on("output.tx_id = ckb_transaction.id"); } - if let Some(ref filter) = search_key.filter { - if filter.script.is_some() || filter.script_len_range.is_some() { - match search_key.script_type { - IndexerScriptType::Lock => { - query_builder - .left() - .join(name!("script";"type_script")) - .on("output.type_script_id = type_script.id"); - } - IndexerScriptType::Type => { - query_builder - .left() - .join(name!("script";"lock_script")) - .on("output.lock_script_id = lock_script.id"); - } + if let Some(ref filter) = search_key.filter + && (filter.script.is_some() || filter.script_len_range.is_some()) + { + match search_key.script_type { + IndexerScriptType::Lock => { + query_builder + .left() + .join(name!("script";"type_script")) + .on("output.type_script_id = type_script.id"); + } + IndexerScriptType::Type => { + query_builder + .left() + .join(name!("script";"lock_script")) + .on("output.lock_script_id = lock_script.id"); } } } diff --git a/util/rich-indexer/src/indexer_handle/async_indexer_handle/get_transactions.rs b/util/rich-indexer/src/indexer_handle/async_indexer_handle/get_transactions.rs index 97a6bdd8ca..7ed2cf6b53 100644 --- a/util/rich-indexer/src/indexer_handle/async_indexer_handle/get_transactions.rs +++ b/util/rich-indexer/src/indexer_handle/async_indexer_handle/get_transactions.rs @@ -160,11 +160,11 @@ pub async fn get_tx_with_cell( .join("block") .on("ckb_transaction.block_id = block.id"); - if let Some(filter) = &search_key.filter { - if let Some(block_range) = &filter.block_range { - query_builder.and_where_ge("block.block_number", block_range.start()); - query_builder.and_where_lt("block.block_number", block_range.end()); - } + if let Some(filter) = &search_key.filter + && let Some(block_range) = &filter.block_range + { + query_builder.and_where_ge("block.block_number", block_range.start()); + query_builder.and_where_lt("block.block_number", block_range.end()); } if let Some((last, _)) = last_cursor { match order { @@ -286,11 +286,11 @@ pub async fn get_tx_with_cells( .join("block") .on("ckb_transaction.block_id = block.id"); - if let Some(filter) = &search_key.filter { - if let Some(block_range) = &filter.block_range { - query_builder.and_where_ge("block.block_number", block_range.start()); - query_builder.and_where_lt("block.block_number", block_range.end()); - } + if let Some(filter) = &search_key.filter + && let Some(block_range) = &filter.block_range + { + query_builder.and_where_ge("block.block_number", block_range.start()); + query_builder.and_where_lt("block.block_number", block_range.end()); } let sql = query_builder .subquery() @@ -453,21 +453,21 @@ fn build_tx_with_cell_union_sub_query( query_output_builder.on("output.type_script_id = query_script.id"); } } - if let Some(ref filter) = search_key.filter { - if filter.script.is_some() || filter.script_len_range.is_some() { - match search_key.script_type { - IndexerScriptType::Lock => { - query_output_builder - .left() - .join(name!("script";"type_script")) - .on("output.type_script_id = type_script.id"); - } - IndexerScriptType::Type => { - query_output_builder - .left() - .join(name!("script";"lock_script")) - .on("output.lock_script_id = lock_script.id"); - } + if let Some(ref filter) = search_key.filter + && (filter.script.is_some() || filter.script_len_range.is_some()) + { + match search_key.script_type { + IndexerScriptType::Lock => { + query_output_builder + .left() + .join(name!("script";"type_script")) + .on("output.type_script_id = type_script.id"); + } + IndexerScriptType::Type => { + query_output_builder + .left() + .join(name!("script";"lock_script")) + .on("output.lock_script_id = lock_script.id"); } } } @@ -499,21 +499,21 @@ fn build_tx_with_cell_union_sub_query( query_input_builder.on("output.type_script_id = query_script.id"); } } - if let Some(ref filter) = search_key.filter { - if filter.script.is_some() || filter.script_len_range.is_some() { - match search_key.script_type { - IndexerScriptType::Lock => { - query_input_builder - .left() - .join(name!("script";"type_script")) - .on("output.type_script_id = type_script.id"); - } - IndexerScriptType::Type => { - query_input_builder - .left() - .join(name!("script";"lock_script")) - .on("output.lock_script_id = lock_script.id"); - } + if let Some(ref filter) = search_key.filter + && (filter.script.is_some() || filter.script_len_range.is_some()) + { + match search_key.script_type { + IndexerScriptType::Lock => { + query_input_builder + .left() + .join(name!("script";"type_script")) + .on("output.type_script_id = type_script.id"); + } + IndexerScriptType::Type => { + query_input_builder + .left() + .join(name!("script";"lock_script")) + .on("output.lock_script_id = lock_script.id"); } } } diff --git a/util/rich-indexer/src/store.rs b/util/rich-indexer/src/store.rs index 237912afe9..cb37b248b6 100644 --- a/util/rich-indexer/src/store.rs +++ b/util/rich-indexer/src/store.rs @@ -113,11 +113,11 @@ impl SQLXPool { Ok(count.try_into().expect("i64 to u64")) } - pub fn new_query(sql: &str) -> Query { + pub fn new_query(sql: &str) -> Query<'_, Any, AnyArguments<'_>> { sqlx::query(sql) } - pub fn new_query_as(sql: &str) -> QueryAs + pub fn new_query_as(sql: &str) -> QueryAs<'_, Any, T, AnyArguments<'_>> where T: for<'r> sqlx::FromRow<'r, AnyRow>, { diff --git a/util/snapshot/src/lib.rs b/util/snapshot/src/lib.rs index 6d214cda1c..d3769586e0 100644 --- a/util/snapshot/src/lib.rs +++ b/util/snapshot/src/lib.rs @@ -189,7 +189,7 @@ impl ChainStore for Snapshot { self.store.cache() } - fn get(&self, col: Col, key: &[u8]) -> Option { + fn get(&self, col: Col, key: &[u8]) -> Option> { self.store.get(col, key) } @@ -197,7 +197,7 @@ impl ChainStore for Snapshot { self.store.freezer() } - fn get_iter(&self, col: Col, mode: IteratorMode) -> DBIter { + fn get_iter(&self, col: Col, mode: IteratorMode) -> DBIter<'_> { self.store.get_iter(col, mode) } @@ -232,11 +232,9 @@ impl CellProvider for Snapshot { fn cell(&self, out_point: &OutPoint, eager_load: bool) -> CellStatus { match self.get_cell(out_point) { Some(mut cell_meta) => { - if eager_load { - if let Some((data, data_hash)) = self.get_cell_data(out_point) { - cell_meta.mem_cell_data = Some(data); - cell_meta.mem_cell_data_hash = Some(data_hash); - } + if eager_load && let Some((data, data_hash)) = self.get_cell_data(out_point) { + cell_meta.mem_cell_data = Some(data); + cell_meta.mem_cell_data_hash = Some(data_hash); } CellStatus::live_cell(cell_meta) } diff --git a/util/src/linked_hash_set.rs b/util/src/linked_hash_set.rs index f34dfaefa6..7f18c6a81e 100644 --- a/util/src/linked_hash_set.rs +++ b/util/src/linked_hash_set.rs @@ -167,7 +167,7 @@ where /// Gets an iterator visiting all elements in insertion order. /// /// The iterator element type is `&'a T`. - pub fn iter(&self) -> Iter { + pub fn iter(&self) -> Iter<'_, T> { Iter { iter: self.map.keys(), } diff --git a/util/systemtime/src/test_faketime.rs b/util/systemtime/src/test_faketime.rs index bba3a57421..36b8d59328 100644 --- a/util/systemtime/src/test_faketime.rs +++ b/util/systemtime/src/test_faketime.rs @@ -5,7 +5,9 @@ mod tests_faketime { #[test] fn test_basic() { - assert!(cfg!(feature = "enable_faketime")); + const { + assert!(cfg!(feature = "enable_faketime")); + } let faketime_guard = faketime(); diff --git a/util/test-chain-utils/src/mock_chain.rs b/util/test-chain-utils/src/mock_chain.rs index ec19ba825c..34b2c165c8 100644 --- a/util/test-chain-utils/src/mock_chain.rs +++ b/util/test-chain-utils/src/mock_chain.rs @@ -39,7 +39,13 @@ impl<'a> MockChain<'a> { pub fn gen_block_with_proposal_txs(&mut self, txs: Vec, store: &MockStore) { let parent = self.tip_header(); let cellbase = create_cellbase(store, self.consensus, &parent); - let dao = dao_data(self.consensus, &parent, &[cellbase.clone()], store, false); + let dao = dao_data( + self.consensus, + &parent, + std::slice::from_ref(&cellbase), + store, + false, + ); let epoch = self .consensus @@ -68,7 +74,13 @@ impl<'a> MockChain<'a> { ) { let parent = self.tip_header(); let cellbase = create_cellbase(store, self.consensus, &parent); - let dao = dao_data(self.consensus, &parent, &[cellbase.clone()], store, false); + let dao = dao_data( + self.consensus, + &parent, + std::slice::from_ref(&cellbase), + store, + false, + ); let epoch = self .consensus @@ -92,7 +104,13 @@ impl<'a> MockChain<'a> { pub fn gen_empty_block_with_diff(&mut self, difficulty: u64, store: &MockStore) { let parent = self.tip_header(); let cellbase = create_cellbase(store, self.consensus, &parent); - let dao = dao_data(self.consensus, &parent, &[cellbase.clone()], store, false); + let dao = dao_data( + self.consensus, + &parent, + std::slice::from_ref(&cellbase), + store, + false, + ); let epoch = self .consensus @@ -116,7 +134,13 @@ impl<'a> MockChain<'a> { let difficulty = self.difficulty(); let parent = self.tip_header(); let cellbase = create_cellbase(store, self.consensus, &parent); - let dao = dao_data(self.consensus, &parent, &[cellbase.clone()], store, false); + let dao = dao_data( + self.consensus, + &parent, + std::slice::from_ref(&cellbase), + store, + false, + ); let epoch = self .consensus @@ -139,7 +163,13 @@ impl<'a> MockChain<'a> { pub fn gen_empty_block_with_nonce(&mut self, nonce: u128, store: &MockStore) { let parent = self.tip_header(); let cellbase = create_cellbase(store, self.consensus, &parent); - let dao = dao_data(self.consensus, &parent, &[cellbase.clone()], store, false); + let dao = dao_data( + self.consensus, + &parent, + std::slice::from_ref(&cellbase), + store, + false, + ); let epoch = self .consensus @@ -163,7 +193,13 @@ impl<'a> MockChain<'a> { pub fn gen_empty_block(&mut self, store: &MockStore) { let parent = self.tip_header(); let cellbase = create_cellbase(store, self.consensus, &parent); - let dao = dao_data(self.consensus, &parent, &[cellbase.clone()], store, false); + let dao = dao_data( + self.consensus, + &parent, + std::slice::from_ref(&cellbase), + store, + false, + ); let epoch = self .consensus diff --git a/util/types/src/core/cell.rs b/util/types/src/core/cell.rs index 7a00e44bdd..23c8b33e8d 100644 --- a/util/types/src/core/cell.rs +++ b/util/types/src/core/cell.rs @@ -489,17 +489,17 @@ impl<'a> BlockCellProvider<'a> { for (idx, tx) in block.transactions().iter().enumerate() { for dep in tx.cell_deps_iter() { - if let Some(output_idx) = output_indices.get(&dep.out_point().tx_hash()) { - if *output_idx >= idx { - return Err(OutPointError::OutOfOrder(dep.out_point()).into()); - } + if let Some(output_idx) = output_indices.get(&dep.out_point().tx_hash()) + && *output_idx >= idx + { + return Err(OutPointError::OutOfOrder(dep.out_point()).into()); } } for out_point in tx.input_pts_iter() { - if let Some(output_idx) = output_indices.get(&out_point.tx_hash()) { - if *output_idx >= idx { - return Err(OutPointError::OutOfOrder(out_point).into()); - } + if let Some(output_idx) = output_indices.get(&out_point.tx_hash()) + && *output_idx >= idx + { + return Err(OutPointError::OutOfOrder(out_point).into()); } } } diff --git a/util/types/src/core/fee_estimator.rs b/util/types/src/core/fee_estimator.rs index e93ada5bf7..aee992b816 100644 --- a/util/types/src/core/fee_estimator.rs +++ b/util/types/src/core/fee_estimator.rs @@ -1,7 +1,8 @@ /// The fee estimate mode. -#[derive(Clone, Copy, Debug)] +#[derive(Clone, Copy, Debug, Default)] pub enum EstimateMode { /// No priority, expect the transaction to be committed in 1 hour. + #[default] NoPriority, /// Low priority, expect the transaction to be committed in 30 minutes. LowPriority, @@ -10,9 +11,3 @@ pub enum EstimateMode { /// High priority, expect the transaction to be committed as soon as possible. HighPriority, } - -impl Default for EstimateMode { - fn default() -> Self { - Self::NoPriority - } -} diff --git a/util/types/src/core/tx_pool.rs b/util/types/src/core/tx_pool.rs index 4e409527bd..acdc305dbc 100644 --- a/util/types/src/core/tx_pool.rs +++ b/util/types/src/core/tx_pool.rs @@ -104,9 +104,9 @@ impl Reject { /// Returns true if tx can be resubmitted, allowing relay /// * Declared wrong cycles should allow relay with the correct cycles /// * Reject but is not malformed and the fee rate reached the threshold, - /// it may be due to double spending - /// or temporary limitations of the pool resources, - /// and expired clearing + /// it may be due to double spending + /// or temporary limitations of the pool resources, + /// and expired clearing pub fn is_allowed_relay(&self) -> bool { matches!(self, Reject::DeclaredWrongCycles(..)) || (!matches!(self, Reject::LowFeeRate(..)) && !self.is_malformed_tx()) diff --git a/util/types/src/utilities/block_filter.rs b/util/types/src/utilities/block_filter.rs index cbde2caedf..41043b3125 100644 --- a/util/types/src/utilities/block_filter.rs +++ b/util/types/src/utilities/block_filter.rs @@ -60,6 +60,6 @@ pub fn calc_filter_hash( ) } -fn build_gcs_filter(out: &mut dyn Write) -> GCSFilterWriter { +fn build_gcs_filter(out: &mut dyn Write) -> GCSFilterWriter<'_, SipHasher24Builder> { GCSFilterWriter::new(out, SipHasher24Builder::new(0, 0), M, P) } diff --git a/util/types/src/utilities/difficulty.rs b/util/types/src/utilities/difficulty.rs index 313d64dfb4..2b79278456 100644 --- a/util/types/src/utilities/difficulty.rs +++ b/util/types/src/utilities/difficulty.rs @@ -47,7 +47,7 @@ fn get_low64(target: &U256) -> u64 { /// Converts PoW target into compact format of difficulty. pub fn target_to_compact(target: U256) -> u32 { let bits = 256 - target.leading_zeros(); - let exponent = u64::from((bits + 7) / 8); + let exponent = u64::from(bits.div_ceil(8)); let mut compact = if exponent <= 3 { get_low64(&target) << (8 * (3 - exponent)) } else { diff --git a/verification/src/transaction_verifier.rs b/verification/src/transaction_verifier.rs index 2e3114d12a..25cfb35b9c 100644 --- a/verification/src/transaction_verifier.rs +++ b/verification/src/transaction_verifier.rs @@ -865,14 +865,13 @@ impl DaoScriptSizeVerifier
{ // Only cells committed after the pre-defined block number in consensus is // applied to this rule - if let Some(info) = &input_meta.transaction_info { - if info.block_number + if let Some(info) = &input_meta.transaction_info + && info.block_number < self .consensus .starting_block_limiting_dao_withdrawing_lock() - { - continue; - } + { + continue; } // Now we have a pair of DAO deposit and withdrawing cells, it is expected