From 324b5144817afbcf3c612766a33c912369a699c6 Mon Sep 17 00:00:00 2001 From: driftluo Date: Fri, 30 Dec 2022 20:20:05 +0800 Subject: [PATCH 1/2] chore: upgrade deps --- Cargo.lock | 203 ++++++++++++++++++++----- ckb-bin/Cargo.toml | 2 +- ckb-bin/src/subcommand/init.rs | 3 +- ckb-bin/src/subcommand/list_hashes.rs | 4 +- util/app-config/Cargo.toml | 2 +- util/app-config/src/cli.rs | 133 +++++++++------- util/app-config/src/configs/miner.rs | 6 +- util/app-config/src/configs/network.rs | 2 +- util/app-config/src/configs/notify.rs | 2 +- util/app-config/src/configs/rpc.rs | 2 +- util/app-config/src/configs/tx_pool.rs | 2 +- util/app-config/src/lib.rs | 159 ++++++++++--------- util/app-config/src/sentry_config.rs | 2 +- util/app-config/src/tests/cli.rs | 34 ++--- 14 files changed, 362 insertions(+), 194 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 14b267f655..4bd6f3004f 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4,9 +4,9 @@ version = 3 [[package]] name = "addr2line" -version = "0.17.0" +version = "0.19.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b9ecd88a8c8378ca913a680cd98f0f13ac67383d35993f86c90a70e3f137816b" +checksum = "a76fd60b23679b7d19bd066031410fb7e458ccc5e958eb5c325888ce4baedc97" dependencies = [ "gimli", ] @@ -46,11 +46,12 @@ dependencies = [ [[package]] name = "ahash" -version = "0.8.0" +version = "0.8.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "57e6e951cfbb2db8de1828d49073a113a29fd7117b1596caa781a258c7e38d72" +checksum = "bf6ccdb167abbf410dcb915cabd428929d7f6a04980b54a11f26a39f1c7f7107" dependencies = [ "cfg-if 1.0.0", + "const-random", "getrandom 0.2.7", "once_cell", "version_check", @@ -112,7 +113,7 @@ version = "0.2.14" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d9b39be18770d11421cdb1b9947a45dd3f37e93092cbf377614828a319d5fee8" dependencies = [ - "hermit-abi", + "hermit-abi 0.1.19", "libc", "winapi 0.3.9", ] @@ -125,15 +126,15 @@ checksum = "d468802bab17cbc0cc575e9b053f41e72aa36bfa6b7f55e3529ffa43161b97fa" [[package]] name = "backtrace" -version = "0.3.66" +version = "0.3.67" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cab84319d616cfb654d03394f38ab7e6f0919e181b1b57e1fd15e7fb4077d9a7" +checksum = "233d376d6d185f2a3093e58f283f60f880315b6c60075b01f36b3b85154564ca" dependencies = [ "addr2line", "cc", "cfg-if 1.0.0", "libc", - "miniz_oxide", + "miniz_oxide 0.6.2", "object", "rustc-demangle", ] @@ -414,7 +415,7 @@ dependencies = [ "ckb-pow", "ckb-resource", "ckb-types", - "clap", + "clap 4.0.32", "faketime", "path-clean", "rand 0.7.3", @@ -497,7 +498,7 @@ dependencies = [ "ckb-types", "ckb-util", "ckb-verification-traits", - "clap", + "clap 4.0.32", "ctrlc", "fdlimit", "rayon", @@ -1549,13 +1550,23 @@ version = "3.2.21" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1ed5341b2301a26ab80be5cbdced622e80ed808483c52e45e3310a877d3b37d7" dependencies = [ - "atty", "bitflags", - "clap_lex", + "clap_lex 0.2.3", "indexmap", + "textwrap", +] + +[[package]] +name = "clap" +version = "4.0.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a7db700bc935f9e43e88d00b0850dae18a63773cfbec6d8e070fccf7fef89a39" +dependencies = [ + "bitflags", + "clap_lex 0.3.0", + "is-terminal", "strsim", "termcolor", - "textwrap", ] [[package]] @@ -1567,6 +1578,15 @@ dependencies = [ "os_str_bytes", ] +[[package]] +name = "clap_lex" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0d4198f73e42b4936b35b5bb248d81d2b595ecb170da0bac7655c54eedfa8da8" +dependencies = [ + "os_str_bytes", +] + [[package]] name = "console" version = "0.15.2" @@ -1581,6 +1601,28 @@ dependencies = [ "winapi 0.3.9", ] +[[package]] +name = "const-random" +version = "0.1.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "368a7a772ead6ce7e1de82bfb04c485f3db8ec744f72925af5735e29a22cc18e" +dependencies = [ + "const-random-macro", + "proc-macro-hack", +] + +[[package]] +name = "const-random-macro" +version = "0.1.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9d7d6ab3c3a2282db210df5f02c4dab6e0a7057af0fb7ebd4070f30fe05c0ddb" +dependencies = [ + "getrandom 0.2.7", + "once_cell", + "proc-macro-hack", + "tiny-keccak", +] + [[package]] name = "convert_case" version = "0.4.0" @@ -1631,7 +1673,7 @@ dependencies = [ "atty", "cast", "ciborium", - "clap", + "clap 3.2.21", "criterion-plot", "itertools", "lazy_static", @@ -1924,6 +1966,27 @@ dependencies = [ "termcolor", ] +[[package]] +name = "errno" +version = "0.2.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f639046355ee4f37944e44f60642c6f3a7efa3cf6b78c78a0d989a8ce6c396a1" +dependencies = [ + "errno-dragonfly", + "libc", + "winapi 0.3.9", +] + +[[package]] +name = "errno-dragonfly" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aa68f1b12764fab894d2755d2518754e71b4fd80ecfb822714a1206c2aab39bf" +dependencies = [ + "cc", + "libc", +] + [[package]] name = "fail" version = "0.4.0" @@ -2002,7 +2065,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f82b0f4c27ad9f8bfd1f3208d882da2b09c301bc1c828fd3a00d0216d2fbbff6" dependencies = [ "crc32fast", - "miniz_oxide", + "miniz_oxide 0.5.1", ] [[package]] @@ -2218,9 +2281,9 @@ dependencies = [ [[package]] name = "gimli" -version = "0.26.1" +version = "0.27.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "78cc372d058dcf6d5ecd98510e7fbc9e5aec4d21de70f65fea8fecebcd881bd4" +checksum = "dec7af912d60cdbd3677c1af9352ebae6fb8394d165568a2234df0fa00f87793" [[package]] name = "glob" @@ -2357,6 +2420,15 @@ dependencies = [ "libc", ] +[[package]] +name = "hermit-abi" +version = "0.2.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ee512640fe35acbfb4bb779db6f0d80704c2cacfa2e39b601ef3e3f47d1ae4c7" +dependencies = [ + "libc", +] + [[package]] name = "hex" version = "0.4.3" @@ -2554,6 +2626,16 @@ dependencies = [ "cfg-if 1.0.0", ] +[[package]] +name = "io-lifetimes" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "46112a93252b123d31a119a8d1a1ac19deac4fac6e0e8b0df58f0d4e5870e63c" +dependencies = [ + "libc", + "windows-sys 0.42.0", +] + [[package]] name = "iovec" version = "0.1.4" @@ -2590,6 +2672,18 @@ dependencies = [ "serde", ] +[[package]] +name = "is-terminal" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "28dfb6c8100ccc63462345b67d1bbc3679177c75ee4bf59bf29c8b1d110b8189" +dependencies = [ + "hermit-abi 0.2.6", + "io-lifetimes", + "rustix", + "windows-sys 0.42.0", +] + [[package]] name = "is_sorted" version = "0.1.1" @@ -2766,9 +2860,9 @@ checksum = "830d08ce1d1d941e6b30645f1a0eb5643013d835ce3779a5fc208261dbe10f55" [[package]] name = "libc" -version = "0.2.137" +version = "0.2.139" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fc7fcc620a3bff7cdd7a365be3376c97191aeaccc2a603e600951e452615bf89" +checksum = "201de327520df007757c1f0adce6e827fe8562fbc28bfd9c15571c66ca1f5f79" [[package]] name = "libloading" @@ -2795,6 +2889,12 @@ dependencies = [ "serde", ] +[[package]] +name = "linux-raw-sys" +version = "0.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f051f77a7c8e6957c0696eac88f26b0117e54f52d3fc682ab19397a8812846a4" + [[package]] name = "lock_api" version = "0.4.6" @@ -2888,6 +2988,15 @@ dependencies = [ "adler", ] +[[package]] +name = "miniz_oxide" +version = "0.6.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b275950c28b37e794e8c55d88aeb5e139d0ce23fdbbeda68f8d7174abdf9e8fa" +dependencies = [ + "adler", +] + [[package]] name = "mio" version = "0.6.23" @@ -3044,7 +3153,7 @@ version = "1.14.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f6058e64324c71e02bc2b150e4f3bc8286db6c83092132ffa3f6b1eab0f9def5" dependencies = [ - "hermit-abi", + "hermit-abi 0.1.19", "libc", ] @@ -3102,9 +3211,9 @@ dependencies = [ [[package]] name = "object" -version = "0.29.0" +version = "0.30.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "21158b2c33aa6d4561f1c0a6ea283ca92bc54802a93b263e910746d679a7eb53" +checksum = "239da7f290cfa979f43f85a8efeee9a8a76d0827c356d37f9d3d7254d6b537fb" dependencies = [ "memchr", ] @@ -3447,11 +3556,17 @@ dependencies = [ "toml", ] +[[package]] +name = "proc-macro-hack" +version = "0.5.20+deprecated" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dc375e1527247fe1a97d8b7156678dfe7c1af2fc075c9a4db3690ecd2a148068" + [[package]] name = "proc-macro2" -version = "1.0.47" +version = "1.0.49" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5ea3d908b0e36316caf9e9e2c4625cdde190a7e6f440d794667ed17a1855e725" +checksum = "57a8eca9f9c4ffde41714334dee777596264c7825420f521abc92b5b5deb63a5" dependencies = [ "unicode-ident", ] @@ -3521,9 +3636,9 @@ checksum = "a993555f31e5a609f617c12db6250dedcac1b0a85076912c436e6fc9b2c8e6a3" [[package]] name = "quote" -version = "1.0.21" +version = "1.0.23" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bbe448f377a7d6961e30f5955f9b8d106c3f5e449d493ee1b125c1d43c2b5179" +checksum = "8856d8364d252a14d474036ea1358d63c9e6965c8e5c1885c18f73d70bff9c7b" dependencies = [ "proc-macro2", ] @@ -3667,9 +3782,9 @@ dependencies = [ [[package]] name = "regex" -version = "1.6.0" +version = "1.7.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4c4eb3267174b8c6c2f654116623910a0fef09c4753f8dd83db29c48a0df988b" +checksum = "e076559ef8e241f2ae3479e36f97bd5741c0330689e217ad51ce2c76808b868a" dependencies = [ "aho-corasick", "memchr", @@ -3740,11 +3855,11 @@ dependencies = [ [[package]] name = "rhai" -version = "1.10.1" +version = "1.11.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6eec3a3db30f591ece18c66b3db4c9fa26f3bce20bc821c50550968361f84333" +checksum = "0f61559c2ea5fef5af856ae95443111dc14e7c9ce73d29c257a840249c0ed298" dependencies = [ - "ahash 0.8.0", + "ahash 0.8.2", "bitflags", "instant", "num-traits", @@ -3810,6 +3925,20 @@ dependencies = [ "semver", ] +[[package]] +name = "rustix" +version = "0.36.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4feacf7db682c6c329c4ede12649cd36ecab0f3be5b7d74e6a20304725db4549" +dependencies = [ + "bitflags", + "errno", + "io-lifetimes", + "libc", + "linux-raw-sys", + "windows-sys 0.42.0", +] + [[package]] name = "rusty-fork" version = "0.3.0" @@ -4033,9 +4162,9 @@ dependencies = [ [[package]] name = "serde_json" -version = "1.0.87" +version = "1.0.91" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6ce777b7b150d76b9cf60d28b55f5847135a003f7d7350c6be7a773508ce7d45" +checksum = "877c235533714907a8c2464236f5c4b2a17262ef1bd71f38f35ea592c8da6883" dependencies = [ "itoa", "ryu", @@ -4148,9 +4277,9 @@ dependencies = [ [[package]] name = "snap" -version = "1.0.5" +version = "1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "45456094d1983e2ee2a18fdfebce3189fa451699d0502cb8e3b49dba5ba41451" +checksum = "5e9f0ab6ef7eb7353d9119c170a436d1bf248eea575ac42d19d12f4e34130831" [[package]] name = "socket2" @@ -4236,9 +4365,9 @@ dependencies = [ [[package]] name = "tentacle" -version = "0.4.1" +version = "0.4.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "93b22d7b895652fdc6989d1078e6f1d2281074c44da4454a77010d8a65785c77" +checksum = "6ffbbdb4f54a9605ceda168884efcf5fb24ef655103362af211e6cfe61eff832" dependencies = [ "async-trait", "bytes 1.3.0", diff --git a/ckb-bin/Cargo.toml b/ckb-bin/Cargo.toml index 5801f4cf43..1187134e5f 100644 --- a/ckb-bin/Cargo.toml +++ b/ckb-bin/Cargo.toml @@ -9,7 +9,7 @@ homepage = "https://github.com/nervosnetwork/ckb" repository = "https://github.com/nervosnetwork/ckb" [dependencies] -clap = { version = "=3.2.21" } +clap = { version = "4" } serde = { version = "1.0", features = ["derive"] } serde_json = { version = "1.0" } serde_plain = "0.3.0" diff --git a/ckb-bin/src/subcommand/init.rs b/ckb-bin/src/subcommand/init.rs index 122fd012ac..384a419f3d 100644 --- a/ckb-bin/src/subcommand/init.rs +++ b/ckb-bin/src/subcommand/init.rs @@ -52,7 +52,6 @@ pub fn init(args: InitArgs) -> Result<(), ExitCode> { args.block_assembler_code_hash = Some(in_block_assembler_code_hash.trim().to_string()); args.block_assembler_args = in_args - .trim() .split_whitespace() .map(|s| s.to_string()) .collect::>(); @@ -180,7 +179,7 @@ pub fn init(args: InitArgs) -> Result<(), ExitCode> { let mut encoded_content = String::new(); io::stdin().read_to_string(&mut encoded_content)?; let spec_content = base64::decode_config( - &encoded_content.trim(), + encoded_content.trim(), base64::STANDARD.decode_allow_trailing_bits(true), ) .map_err(|err| { diff --git a/ckb-bin/src/subcommand/list_hashes.rs b/ckb-bin/src/subcommand/list_hashes.rs index ede4df804c..02f0509214 100644 --- a/ckb-bin/src/subcommand/list_hashes.rs +++ b/ckb-bin/src/subcommand/list_hashes.rs @@ -113,9 +113,9 @@ impl TryFrom for SpecHashes { pub fn list_hashes(root_dir: PathBuf, matches: &ArgMatches) -> Result<(), ExitCode> { let mut specs = Vec::new(); - let output_format = matches.value_of(cli::ARG_FORMAT).unwrap_or("toml"); + let output_format = matches.get_one::(cli::ARG_FORMAT).unwrap().as_str(); - if matches.is_present(cli::ARG_BUNDLED) { + if matches.contains_id(cli::ARG_BUNDLED) { if output_format == "toml" { println!("# Generated by: ckb list-hashes -b\n"); } diff --git a/util/app-config/Cargo.toml b/util/app-config/Cargo.toml index 23401f2233..2bf09350fd 100644 --- a/util/app-config/Cargo.toml +++ b/util/app-config/Cargo.toml @@ -9,7 +9,7 @@ homepage = "https://github.com/nervosnetwork/ckb" repository = "https://github.com/nervosnetwork/ckb" [dependencies] -clap = { version = "=3.2.21" } +clap = { version = "4", features = ["string"] } serde = { version = "1.0", features = ["derive"] } serde_plain = "0.3.0" serde_json = "1.0" diff --git a/util/app-config/src/cli.rs b/util/app-config/src/cli.rs index e810dae89c..e88188d184 100644 --- a/util/app-config/src/cli.rs +++ b/util/app-config/src/cli.rs @@ -118,7 +118,7 @@ pub const ARG_MIGRATE_CHECK: &str = "check"; const GROUP_BA: &str = "ba"; /// return root clap Command -pub fn basic_app<'help>() -> Command<'help> { +pub fn basic_app() -> Command { Command::new(BIN_NAME) .author("Nervos Core Dev ") .about("Nervos CKB - The Common Knowledge Base") @@ -129,7 +129,7 @@ pub fn basic_app<'help>() -> Command<'help> { .global(true) .short('C') .value_name("path") - .takes_value(true) + .action(clap::ArgAction::Set) .help( "Runs as if ckb was started in instead of the current working directory.", ), @@ -156,33 +156,36 @@ pub fn get_bin_name_and_matches(version: &Version) -> (String, ArgMatches) { .next() .unwrap_or_else(|| BIN_NAME.to_owned()); let matches = basic_app() - .version(version.short().as_str()) - .long_version(version.long().as_str()) + .version(version.short()) + .long_version(version.long()) .get_matches(); (bin_name, matches) } -fn run<'help>() -> Command<'help> { +fn run() -> Command { Command::new(CMD_RUN) .about("Runs ckb node") .arg( Arg::new(ARG_BA_ADVANCED) .long(ARG_BA_ADVANCED) + .action(clap::ArgAction::SetTrue) .help("Allows any block assembler code hash and args"), ) .arg( Arg::new(ARG_SKIP_CHAIN_SPEC_CHECK) .long(ARG_SKIP_CHAIN_SPEC_CHECK) + .action(clap::ArgAction::SetTrue) .help("Skips checking the chain spec with the hash stored in the database"), ).arg( Arg::new(ARG_OVERWRITE_CHAIN_SPEC) .long(ARG_OVERWRITE_CHAIN_SPEC) + .action(clap::ArgAction::SetTrue) .help("Overwrites the chain spec in the database with the present configured chain spec") ).arg( Arg::new(ARG_ASSUME_VALID_TARGET) .long(ARG_ASSUME_VALID_TARGET) - .takes_value(true) - .validator(is_h256) + .action(clap::ArgAction::Set) + .value_parser(is_h256) .help("This parameter specifies the hash of a block. \ When the height does not reach this block's height, the execution of the script will be disabled, \ that is, skip verifying the script content. \ @@ -195,16 +198,19 @@ fn run<'help>() -> Command<'help> { ).arg( Arg::new(ARG_INDEXER) .long(ARG_INDEXER) + .action(clap::ArgAction::SetTrue) .help("Start the built-in indexer service"), ) } -fn miner<'help>() -> Command<'help> { +fn miner() -> Command { Command::new(CMD_MINER).about("Runs ckb miner").arg( Arg::new(ARG_LIMIT) .short('l') .long(ARG_LIMIT) - .takes_value(true) + .action(clap::ArgAction::Set) + .value_parser(clap::value_parser!(u128)) + .default_value("0") .help( "Exit after how many nonces found; \ 0 means the miner will never exit. [default: 0]", @@ -212,7 +218,7 @@ fn miner<'help>() -> Command<'help> { ) } -fn reset_data<'help>() -> Command<'help> { +fn reset_data() -> Command { Command::new(CMD_RESET_DATA) .about( "Truncate the database directory\n\ @@ -223,41 +229,48 @@ fn reset_data<'help>() -> Command<'help> { Arg::new(ARG_FORCE) .short('f') .long(ARG_FORCE) + .action(clap::ArgAction::SetTrue) .help("Delete data without interactive prompt"), ) .arg( Arg::new(ARG_ALL) .long(ARG_ALL) + .action(clap::ArgAction::SetTrue) .help("Delete the whole data directory"), ) .arg( Arg::new(ARG_DATABASE) .long(ARG_DATABASE) + .action(clap::ArgAction::SetTrue) .help("Delete only `data/db`"), ) .arg( Arg::new(ARG_NETWORK) .long(ARG_NETWORK) + .action(clap::ArgAction::SetTrue) .help("Delete both peer store and secret key"), ) .arg( Arg::new(ARG_NETWORK_PEER_STORE) .long(ARG_NETWORK_PEER_STORE) + .action(clap::ArgAction::SetTrue) .help("Delete only `data/network/peer_store`"), ) .arg( Arg::new(ARG_NETWORK_SECRET_KEY) .long(ARG_NETWORK_SECRET_KEY) + .action(clap::ArgAction::SetTrue) .help("Delete only `data/network/secret_key`"), ) .arg( Arg::new(ARG_LOGS) .long(ARG_LOGS) + .action(clap::ArgAction::SetTrue) .help("Delete only `data/logs`"), ) } -pub(crate) fn stats<'help>() -> Command<'help> { +pub(crate) fn stats() -> Command { Command::new(CMD_STATS) .about( "Statics chain information\n\ @@ -267,123 +280,141 @@ pub(crate) fn stats<'help>() -> Command<'help> { .arg( Arg::new(ARG_FROM) .long(ARG_FROM) - .takes_value(true) + .value_parser(clap::value_parser!(u64)) + .action(clap::ArgAction::Set) .help("Specifies from block number."), ) .arg( Arg::new(ARG_TO) .long(ARG_TO) - .takes_value(true) + .value_parser(clap::value_parser!(u64)) + .action(clap::ArgAction::Set) .help("Specifies to block number."), ) } -fn replay<'help>() -> Command<'help> { +fn replay() -> Command { Command::new(CMD_REPLAY) .about("replay ckb process block") .override_help(" --tmp-target --profile 1 10,\n --tmp-target --sanity-check,\n ") - .arg(Arg::new(ARG_TMP_TARGET).long(ARG_TMP_TARGET).takes_value(true).required(true).help( + .arg(Arg::new(ARG_TMP_TARGET).long(ARG_TMP_TARGET).value_parser(clap::builder::PathBufValueParser::new()).action(clap::ArgAction::Set).required(true).help( "Specifies a target path, prof command make a temporary directory inside of target and the directory will be automatically deleted when finished", )) - .arg(Arg::new(ARG_PROFILE).long(ARG_PROFILE).help( + .arg(Arg::new(ARG_PROFILE).long(ARG_PROFILE).action(clap::ArgAction::SetTrue).help( "Enable profile", )) .arg( Arg::new(ARG_FROM) + .value_parser(clap::value_parser!(u64)) .help("Specifies profile from block number."), ) .arg( Arg::new(ARG_TO) + .value_parser(clap::value_parser!(u64)) .help("Specifies profile to block number."), ) .arg( - Arg::new(ARG_SANITY_CHECK).long(ARG_SANITY_CHECK).help("Enable sanity check") + Arg::new(ARG_SANITY_CHECK).long(ARG_SANITY_CHECK).action(clap::ArgAction::SetTrue).help("Enable sanity check") ) .arg( - Arg::new(ARG_FULL_VERIFICATION).long(ARG_FULL_VERIFICATION).help("Enable sanity check") + Arg::new(ARG_FULL_VERIFICATION).long(ARG_FULL_VERIFICATION).action(clap::ArgAction::SetTrue).help("Enable sanity check") ) .group( ArgGroup::new("mode") - .args(&[ARG_PROFILE, ARG_SANITY_CHECK]) + .args([ARG_PROFILE, ARG_SANITY_CHECK]) .required(true) ) } -fn export<'help>() -> Command<'help> { +fn export() -> Command { Command::new(CMD_EXPORT).about("Exports ckb data").arg( Arg::new(ARG_TARGET) .short('t') .long(ARG_TARGET) .value_name("path") + .value_parser(clap::builder::PathBufValueParser::new()) .required(true) .help("Specifies the export target path."), ) } -fn import<'help>() -> Command<'help> { +fn import() -> Command { Command::new(CMD_IMPORT).about("Imports ckb data").arg( Arg::new(ARG_SOURCE) .index(1) .value_name("path") + .value_parser(clap::builder::PathBufValueParser::new()) .required(true) .help("Specifies the exported data path."), ) } -fn migrate<'help>() -> Command<'help> { +fn migrate() -> Command { Command::new(CMD_MIGRATE) .about("Runs ckb migration") - .arg(Arg::new(ARG_MIGRATE_CHECK).long(ARG_MIGRATE_CHECK).help( - "Perform database version check without migrating, \ + .arg( + Arg::new(ARG_MIGRATE_CHECK) + .long(ARG_MIGRATE_CHECK) + .action(clap::ArgAction::SetTrue) + .help( + "Perform database version check without migrating, \ if migration is in need ExitCode(0) is returned,\ otherwise ExitCode(64) is returned", - )) + ), + ) .arg( Arg::new(ARG_FORCE) .long(ARG_FORCE) + .action(clap::ArgAction::SetTrue) .conflicts_with(ARG_MIGRATE_CHECK) .help("Do migration without interactive prompt"), ) } -fn db_repair<'help>() -> Command<'help> { +fn db_repair() -> Command { Command::new(CMD_DB_REPAIR).about("Try repair ckb database") } -fn list_hashes<'help>() -> Command<'help> { +fn list_hashes() -> Command { Command::new(CMD_LIST_HASHES) .about("Lists well known hashes") .arg( - Arg::new(ARG_BUNDLED).short('b').long(ARG_BUNDLED).help( - "Lists hashes of the bundled chain specs instead of the current effective one.", - ), + Arg::new(ARG_BUNDLED) + .short('b') + .long(ARG_BUNDLED) + .action(clap::ArgAction::SetTrue) + .help( + "Lists hashes of the bundled chain specs instead of the current effective one.", + ), ) .arg( Arg::new(ARG_FORMAT) .short('f') .long(ARG_FORMAT) - .possible_values(&["json", "toml"]) + .value_parser(["json", "toml"]) .default_value("toml") .help("Set the format of the printed hashes."), ) } -fn init<'help>() -> Command<'help> { +fn init() -> Command { Command::new(CMD_INIT) .about("Creates a CKB directory or re-initializes an existing one") .arg( Arg::new(ARG_INTERACTIVE) .short('i') .long(ARG_INTERACTIVE) + .action(clap::ArgAction::SetTrue) .help("Interactive mode"), ) .arg( Arg::new(ARG_LIST_CHAINS) .short('l') .long(ARG_LIST_CHAINS) + .action(clap::ArgAction::SetTrue) .help("Lists available options for --chain"), ) .arg( @@ -396,7 +427,7 @@ fn init<'help>() -> Command<'help> { .arg( Arg::new(ARG_IMPORT_SPEC) .long(ARG_IMPORT_SPEC) - .takes_value(true) + .action(clap::ArgAction::Set) .help( "Uses the specifies file as chain spec. Specially, \ The dash \"-\" denotes importing the spec from stdin encoded in base64", @@ -405,7 +436,7 @@ fn init<'help>() -> Command<'help> { .arg( Arg::new(ARG_LOG_TO) .long(ARG_LOG_TO) - .possible_values(&["file", "stdout", "both"]) + .value_parser(["file", "stdout", "both"]) .default_value("both") .help("Configures where the logs should print"), ) @@ -413,6 +444,7 @@ fn init<'help>() -> Command<'help> { Arg::new(ARG_FORCE) .short('f') .long(ARG_FORCE) + .action(clap::ArgAction::SetTrue) .help("Forces overwriting existing files"), ) .arg( @@ -431,8 +463,8 @@ fn init<'help>() -> Command<'help> { Arg::new(ARG_BA_CODE_HASH) .long(ARG_BA_CODE_HASH) .value_name("code_hash") - .validator(is_h256) - .takes_value(true) + .value_parser(is_h256) + .action(clap::ArgAction::Set) .help( "Sets code_hash in [block_assembler] \ [default: secp256k1 if --ba-arg is present]", @@ -442,30 +474,29 @@ fn init<'help>() -> Command<'help> { Arg::new(ARG_BA_ARG) .long(ARG_BA_ARG) .value_name("arg") - .validator(is_hex) - .multiple_occurrences(true) - .number_of_values(1) + .action(clap::ArgAction::Append) + .value_parser(is_hex) .help("Sets args in [block_assembler]"), ) .arg( Arg::new(ARG_BA_HASH_TYPE) .long(ARG_BA_HASH_TYPE) .value_name("hash_type") - .takes_value(true) - .possible_values(&["data", "type", "data1"]) + .action(clap::ArgAction::Set) + .value_parser(["data", "type", "data1"]) .default_value("type") .help("Sets hash type in [block_assembler]"), ) .group( ArgGroup::new(GROUP_BA) - .args(&[ARG_BA_CODE_HASH, ARG_BA_ARG]) + .args([ARG_BA_CODE_HASH, ARG_BA_ARG]) .multiple(true), ) .arg( Arg::new(ARG_BA_MESSAGE) .long(ARG_BA_MESSAGE) .value_name("message") - .validator(is_hex) + .value_parser(is_hex) .requires(GROUP_BA) .help("Sets message in [block_assembler]"), ) @@ -475,14 +506,14 @@ fn init<'help>() -> Command<'help> { Arg::new("spec") .short('s') .long("spec") - .takes_value(true) + .action(clap::ArgAction::Set) .hide(true), ) .arg( Arg::new(ARG_GENESIS_MESSAGE) .long(ARG_GENESIS_MESSAGE) .value_name(ARG_GENESIS_MESSAGE) - .takes_value(true) + .action(clap::ArgAction::Set) .help( "Specify a string as the genesis message. \ Only works for dev chains. \ @@ -491,7 +522,7 @@ fn init<'help>() -> Command<'help> { ) } -fn peer_id<'help>() -> Command<'help> { +fn peer_id() -> Command { Command::new(CMD_PEERID) .about("About peer id, base on Secp256k1") .subcommand_required(true) @@ -500,7 +531,7 @@ fn peer_id<'help>() -> Command<'help> { .about("Generate peer id from secret file") .arg( Arg::new(ARG_SECRET_PATH) - .takes_value(true) + .action(clap::ArgAction::Set) .long(ARG_SECRET_PATH) .required(true) .help("Generate peer id from secret file path"), @@ -513,13 +544,13 @@ fn peer_id<'help>() -> Command<'help> { Arg::new(ARG_SECRET_PATH) .long(ARG_SECRET_PATH) .required(true) - .takes_value(true) + .action(clap::ArgAction::Set) .help("Generate peer id to file path"), ), ) } -fn is_hex(hex: &str) -> Result<(), String> { +fn is_hex(hex: &str) -> Result { let tmp = hex.as_bytes(); if tmp.len() < 2 { Err("Must be a 0x-prefixed hexadecimal string".to_string()) @@ -535,13 +566,13 @@ fn is_hex(hex: &str) -> Result<(), String> { } } - Ok(()) + Ok(hex.to_string()) } else { Err("Must 0x-prefixed hexadecimal string".to_string()) } } -fn is_h256(hex: &str) -> Result<(), String> { +fn is_h256(hex: &str) -> Result { if hex.len() != 66 { Err("Must be 0x-prefixed hexadecimal string and string length is 66".to_owned()) } else { diff --git a/util/app-config/src/configs/miner.rs b/util/app-config/src/configs/miner.rs index bb7da8cf5e..61ec43922f 100644 --- a/util/app-config/src/configs/miner.rs +++ b/util/app-config/src/configs/miner.rs @@ -14,7 +14,7 @@ pub struct Config { } /// RPC client config options. -#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Eq)] #[serde(deny_unknown_fields)] pub struct ClientConfig { /// CKB node RPC endpoint. @@ -73,7 +73,7 @@ pub enum DummyConfig { } /// Eaglesong worker config options. -#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Eq)] #[serde(deny_unknown_fields)] pub struct EaglesongSimpleConfig { /// Number of worker threads. @@ -84,7 +84,7 @@ pub struct EaglesongSimpleConfig { } /// Specifies the hash function. -#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] +#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize, Eq)] pub enum ExtraHashFunction { /// Blake2b hash with CKB preferences. Blake2b, diff --git a/util/app-config/src/configs/network.rs b/util/app-config/src/configs/network.rs index f0afd33d74..abe5b08b7c 100644 --- a/util/app-config/src/configs/network.rs +++ b/util/app-config/src/configs/network.rs @@ -171,7 +171,7 @@ pub(crate) fn generate_random_key() -> [u8; 32] { loop { let mut key: [u8; 32] = [0; 32]; rand::thread_rng().fill(&mut key); - if secio::SecioKeyPair::secp256k1_raw_key(&key).is_ok() { + if secio::SecioKeyPair::secp256k1_raw_key(key).is_ok() { return key; } } diff --git a/util/app-config/src/configs/notify.rs b/util/app-config/src/configs/notify.rs index dddfc80628..ab6f3cf00a 100644 --- a/util/app-config/src/configs/notify.rs +++ b/util/app-config/src/configs/notify.rs @@ -1,6 +1,6 @@ use serde::{Deserialize, Serialize}; /// Notify config options. -#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Default)] +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Default, Eq)] #[serde(deny_unknown_fields)] pub struct Config { /// An executable script to be called whenever there's a new block in the canonical chain. diff --git a/util/app-config/src/configs/rpc.rs b/util/app-config/src/configs/rpc.rs index 84f081df7c..deaabbbbca 100644 --- a/util/app-config/src/configs/rpc.rs +++ b/util/app-config/src/configs/rpc.rs @@ -19,7 +19,7 @@ pub enum Module { } /// RPC config options. -#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Eq)] #[serde(deny_unknown_fields)] pub struct Config { /// RPC server listen addresses. diff --git a/util/app-config/src/configs/tx_pool.rs b/util/app-config/src/configs/tx_pool.rs index de4ae3e3dc..057576ddf3 100644 --- a/util/app-config/src/configs/tx_pool.rs +++ b/util/app-config/src/configs/tx_pool.rs @@ -41,7 +41,7 @@ pub struct TxPoolConfig { /// Block assembler config options. /// /// The block assembler section tells CKB how to claim the miner rewards. -#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Eq)] #[serde(deny_unknown_fields)] pub struct BlockAssemblerConfig { /// The miner lock script code hash. diff --git a/util/app-config/src/lib.rs b/util/app-config/src/lib.rs index 845b826c94..8b871e2dc1 100644 --- a/util/app-config/src/lib.rs +++ b/util/app-config/src/lib.rs @@ -27,7 +27,7 @@ pub use url::Url; use ckb_chain_spec::{consensus::Consensus, ChainSpec}; use ckb_jsonrpc_types::ScriptHashType; use ckb_types::{u256, H256, U256}; -use clap::{ArgMatches, ErrorKind}; +use clap::ArgMatches; use std::{path::PathBuf, str::FromStr}; // 500_000 total difficulty @@ -87,17 +87,17 @@ impl Setup { }; config.network.sync.assume_valid_target = matches - .value_of(cli::ARG_ASSUME_VALID_TARGET) + .get_one::(cli::ARG_ASSUME_VALID_TARGET) .and_then(|s| H256::from_str(&s[2..]).ok()); Ok(RunArgs { config, consensus, - block_assembler_advanced: matches.is_present(cli::ARG_BA_ADVANCED), - skip_chain_spec_check: matches.is_present(cli::ARG_SKIP_CHAIN_SPEC_CHECK), - overwrite_chain_spec: matches.is_present(cli::ARG_OVERWRITE_CHAIN_SPEC), + block_assembler_advanced: matches.get_flag(cli::ARG_BA_ADVANCED), + skip_chain_spec_check: matches.get_flag(cli::ARG_SKIP_CHAIN_SPEC_CHECK), + overwrite_chain_spec: matches.get_flag(cli::ARG_OVERWRITE_CHAIN_SPEC), chain_spec_hash, - indexer: matches.is_present(cli::ARG_INDEXER), + indexer: matches.get_flag(cli::ARG_INDEXER), }) } @@ -105,8 +105,8 @@ impl Setup { pub fn migrate(self, matches: &ArgMatches) -> Result { let consensus = self.consensus()?; let config = self.config.into_ckb()?; - let check = matches.is_present(cli::ARG_MIGRATE_CHECK); - let force = matches.is_present(cli::ARG_FORCE); + let check = matches.get_flag(cli::ARG_MIGRATE_CHECK); + let force = matches.get_flag(cli::ARG_FORCE); Ok(MigrateArgs { config, @@ -129,13 +129,9 @@ impl Setup { let memory_tracker = self.config.memory_tracker().to_owned(); let config = self.config.into_miner()?; let pow_engine = spec.pow_engine(); - let limit = match matches.value_of_t(cli::ARG_LIMIT) { - Ok(l) => l, - Err(ref e) if e.kind() == ErrorKind::ArgumentNotFound => 0, - Err(e) => { - return Err(e.into()); - } - }; + let limit = *matches + .get_one::(cli::ARG_LIMIT) + .expect("has default value"); Ok(MinerArgs { pow_engine, @@ -149,16 +145,22 @@ impl Setup { pub fn replay(self, matches: &ArgMatches) -> Result { let consensus = self.consensus()?; let config = self.config.into_ckb()?; - let tmp_target = matches.value_of_t(cli::ARG_TMP_TARGET)?; - let profile = if matches.is_present(cli::ARG_PROFILE) { - let from = option_value_t!(matches, cli::ARG_FROM, u64)?; - let to = option_value_t!(matches, cli::ARG_TO, u64)?; + let tmp_target = matches + .get_one::(cli::ARG_TMP_TARGET) + .ok_or_else(|| { + eprintln!("Args Error: {:?} no found", cli::ARG_TMP_TARGET); + ExitCode::Cli + })? + .clone(); + let profile = if matches.get_flag(cli::ARG_PROFILE) { + let from = matches.get_one::(cli::ARG_FROM).cloned(); + let to = matches.get_one::(cli::ARG_TO).cloned(); Some((from, to)) } else { None }; - let sanity_check = matches.is_present(cli::ARG_SANITY_CHECK); - let full_verification = matches.is_present(cli::ARG_FULL_VERIFICATION); + let sanity_check = matches.get_flag(cli::ARG_SANITY_CHECK); + let full_verification = matches.get_flag(cli::ARG_FULL_VERIFICATION); Ok(ReplayArgs { config, consensus, @@ -174,8 +176,8 @@ impl Setup { let consensus = self.consensus()?; let config = self.config.into_ckb()?; - let from = option_value_t!(matches, cli::ARG_FROM, u64)?; - let to = option_value_t!(matches, cli::ARG_TO, u64)?; + let from = matches.get_one::(cli::ARG_FROM).cloned(); + let to = matches.get_one::(cli::ARG_TO).cloned(); Ok(StatsArgs { config, @@ -189,7 +191,13 @@ impl Setup { pub fn import(self, matches: &ArgMatches) -> Result { let consensus = self.consensus()?; let config = self.config.into_ckb()?; - let source = matches.value_of_t(cli::ARG_SOURCE)?; + let source = matches + .get_one::(cli::ARG_SOURCE) + .ok_or_else(|| { + eprintln!("Args Error: {:?} no found", cli::ARG_SOURCE); + ExitCode::Cli + })? + .clone(); Ok(ImportArgs { config, @@ -202,7 +210,13 @@ impl Setup { pub fn export(self, matches: &ArgMatches) -> Result { let consensus = self.consensus()?; let config = self.config.into_ckb()?; - let target = matches.value_of_t(cli::ARG_TARGET)?; + let target = matches + .get_one::(cli::ARG_TARGET) + .ok_or_else(|| { + eprintln!("Args Error: {:?} no found", cli::ARG_TARGET); + ExitCode::Cli + })? + .clone(); Ok(ExportArgs { config, @@ -213,55 +227,65 @@ impl Setup { /// Executes `ckb init`. pub fn init(matches: &ArgMatches) -> Result { - if matches.is_present("list-specs") { + if matches.contains_id("list-specs") { eprintln!( "Deprecated: Option `--list-specs` is deprecated, use `--list-chains` instead" ); } - if matches.is_present("spec") { + if matches.contains_id("spec") { eprintln!("Deprecated: Option `--spec` is deprecated, use `--chain` instead"); } - if matches.is_present("export-specs") { + if matches.contains_id("export-specs") { eprintln!("Deprecated: Option `--export-specs` is deprecated"); } let root_dir = Self::root_dir_from_matches(matches)?; let list_chains = - matches.is_present(cli::ARG_LIST_CHAINS) || matches.is_present("list-specs"); - let interactive = matches.is_present(cli::ARG_INTERACTIVE); - let force = matches.is_present(cli::ARG_FORCE); - let chain = if matches.occurrences_of(cli::ARG_CHAIN) > 0 || !matches.is_present("spec") { - matches.value_of(cli::ARG_CHAIN).unwrap().to_string() + matches.get_flag(cli::ARG_LIST_CHAINS) || matches.contains_id("list-specs"); + let interactive = matches.get_flag(cli::ARG_INTERACTIVE); + let force = matches.get_flag(cli::ARG_FORCE); + let chain = if !matches.contains_id("spec") { + matches + .get_one::(cli::ARG_CHAIN) + .expect("has default value") + .to_string() } else { - matches.value_of("spec").unwrap().to_string() + matches.get_one::("spec").unwrap().to_string() }; - let rpc_port = matches.value_of(cli::ARG_RPC_PORT).unwrap().to_string(); - let p2p_port = matches.value_of(cli::ARG_P2P_PORT).unwrap().to_string(); - let (log_to_file, log_to_stdout) = match matches.value_of(cli::ARG_LOG_TO) { + let rpc_port = matches + .get_one::(cli::ARG_RPC_PORT) + .expect("has default value") + .to_string(); + let p2p_port = matches + .get_one::(cli::ARG_P2P_PORT) + .expect("has default value") + .to_string(); + let (log_to_file, log_to_stdout) = match matches + .get_one::(cli::ARG_LOG_TO) + .map(|s| s.as_str()) + { Some("file") => (true, false), Some("stdout") => (false, true), Some("both") => (true, true), _ => unreachable!(), }; - let block_assembler_code_hash = matches.value_of(cli::ARG_BA_CODE_HASH).map(str::to_string); + let block_assembler_code_hash = matches.get_one::(cli::ARG_BA_CODE_HASH).cloned(); let block_assembler_args: Vec<_> = matches - .values_of(cli::ARG_BA_ARG) + .get_many::(cli::ARG_BA_ARG) .unwrap_or_default() - .map(str::to_string) + .map(|a| a.to_owned()) .collect(); let block_assembler_hash_type = matches - .value_of(cli::ARG_BA_HASH_TYPE) + .get_one::(cli::ARG_BA_HASH_TYPE) .and_then(|hash_type| serde_plain::from_str::(hash_type).ok()) - .unwrap(); - let block_assembler_message = matches.value_of(cli::ARG_BA_MESSAGE).map(str::to_string); + .expect("has default value"); + let block_assembler_message = matches.get_one::(cli::ARG_BA_MESSAGE).cloned(); - let import_spec = matches.value_of(cli::ARG_IMPORT_SPEC).map(str::to_string); + let import_spec = matches.get_one::(cli::ARG_IMPORT_SPEC).cloned(); let customize_spec = { - let genesis_message = matches - .value_of(cli::ARG_GENESIS_MESSAGE) - .map(str::to_string); + let genesis_message = matches.get_one::(cli::ARG_GENESIS_MESSAGE).cloned(); args::CustomizeSpec { genesis_message } }; @@ -295,13 +319,13 @@ impl Setup { let network_secret_key_path = network_config.secret_key_path(); let logs_dir = Some(config.logger.log_dir); - let force = matches.is_present(cli::ARG_FORCE); - let all = matches.is_present(cli::ARG_ALL); - let database = matches.is_present(cli::ARG_DATABASE); - let network = matches.is_present(cli::ARG_NETWORK); - let network_peer_store = matches.is_present(cli::ARG_NETWORK_PEER_STORE); - let network_secret_key = matches.is_present(cli::ARG_NETWORK_SECRET_KEY); - let logs = matches.is_present(cli::ARG_LOGS); + let force = matches.get_flag(cli::ARG_FORCE); + let all = matches.get_flag(cli::ARG_ALL); + let database = matches.get_flag(cli::ARG_DATABASE); + let network = matches.get_flag(cli::ARG_NETWORK); + let network_peer_store = matches.get_flag(cli::ARG_NETWORK_PEER_STORE); + let network_secret_key = matches.get_flag(cli::ARG_NETWORK_SECRET_KEY); + let logs = matches.get_flag(cli::ARG_LOGS); Ok(ResetDataArgs { force, @@ -322,7 +346,7 @@ impl Setup { /// Resolves the root directory for ckb from the command line arguments. pub fn root_dir_from_matches(matches: &ArgMatches) -> Result { - let config_dir = match matches.value_of(cli::ARG_CONFIG_DIR) { + let config_dir = match matches.get_one::(cli::ARG_CONFIG_DIR) { Some(arg_config_dir) => PathBuf::from(arg_config_dir), None => ::std::env::current_dir()?, }; @@ -375,7 +399,9 @@ impl Setup { /// Gets the network peer id by reading the network secret key. pub fn peer_id(matches: &ArgMatches) -> Result { - let path = matches.value_of(cli::ARG_SECRET_PATH).unwrap(); + let path = matches + .get_one::(cli::ARG_SECRET_PATH) + .expect("required on command line"); match read_secret_key(path.into()) { Ok(Some(key)) => Ok(PeerIDArgs { peer_id: key.peer_id(), @@ -387,29 +413,14 @@ impl Setup { /// Generates the network secret key. pub fn gen(matches: &ArgMatches) -> Result<(), ExitCode> { - let path = matches.value_of(cli::ARG_SECRET_PATH).unwrap(); + let path = matches + .get_one::(cli::ARG_SECRET_PATH) + .expect("required on command line"); configs::write_secret_to_file(&configs::generate_random_key(), path.into()) .map_err(|_| ExitCode::IO) } } -// There are two types of errors, -// parse failures and those where the argument wasn't present -#[doc(hidden)] -#[macro_export] -macro_rules! option_value_t { - ($m:ident, $v:expr, $t:ty) => { - option_value_t!($m.value_of($v), $t) - }; - ($m:ident.value_of($v:expr), $t:ty) => { - match $m.value_of_t($v) { - Ok(from) => Ok(Some(from)), - Err(ref e) if e.kind() == ErrorKind::ArgumentNotFound => Ok(None), - Err(e) => Err(e), - } - }; -} - #[cfg(feature = "with_sentry")] fn is_daemon(subcommand_name: &str) -> bool { matches!(subcommand_name, cli::CMD_RUN | cli::CMD_MINER) diff --git a/util/app-config/src/sentry_config.rs b/util/app-config/src/sentry_config.rs index e8937b14a2..a8e2fa9c3e 100644 --- a/util/app-config/src/sentry_config.rs +++ b/util/app-config/src/sentry_config.rs @@ -8,7 +8,7 @@ use serde::{Deserialize, Serialize}; use std::borrow::Cow; use std::sync::Arc; -#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Default)] +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Default, Eq)] #[serde(deny_unknown_fields)] pub struct SentryConfig { pub dsn: String, diff --git a/util/app-config/src/tests/cli.rs b/util/app-config/src/tests/cli.rs index a92e33f86d..3b62a620b0 100644 --- a/util/app-config/src/tests/cli.rs +++ b/util/app-config/src/tests/cli.rs @@ -21,15 +21,13 @@ fn stats_args() { .try_get_matches_from(vec!["", CMD_STATS, "--to", "100"]); assert!(stats.is_ok()); - let stats = app - .clone() - .try_get_matches_from(vec!["", CMD_STATS, "--from", "10", "--to", "100"]); + let stats = app.try_get_matches_from(vec!["", CMD_STATS, "--from", "10", "--to", "100"]); assert!(stats.is_ok()); } #[test] fn ba_message_requires_ba_arg_or_ba_code_hash() { - let ok_ba_arg = basic_app().try_get_matches_from(&[ + let ok_ba_arg = basic_app().try_get_matches_from([ BIN_NAME, "init", "--ba-message", @@ -37,7 +35,7 @@ fn ba_message_requires_ba_arg_or_ba_code_hash() { "--ba-arg", "0x00", ]); - let ba_code_hash = basic_app().try_get_matches_from(&[ + let ba_code_hash = basic_app().try_get_matches_from([ BIN_NAME, "init", "--ba-message", @@ -45,7 +43,7 @@ fn ba_message_requires_ba_arg_or_ba_code_hash() { "--ba-code-hash", "0x00", ]); - let err = basic_app().try_get_matches_from(&[BIN_NAME, "init", "--ba-message", "0x00"]); + let err = basic_app().try_get_matches_from([BIN_NAME, "init", "--ba-message", "0x00"]); assert!( ok_ba_arg.is_ok(), @@ -59,7 +57,7 @@ fn ba_message_requires_ba_arg_or_ba_code_hash() { ); let err = err.err().unwrap(); - assert_eq!(clap::ErrorKind::MissingRequiredArgument, err.kind()); + assert_eq!(clap::error::ErrorKind::MissingRequiredArgument, err.kind()); assert!(err .to_string() .contains("The following required arguments were not provided")); @@ -69,7 +67,7 @@ fn ba_message_requires_ba_arg_or_ba_code_hash() { #[test] fn ba_arg_and_ba_code_hash() { - let matches = basic_app().try_get_matches_from(&[ + let matches = basic_app().try_get_matches_from([ BIN_NAME, "init", "--ba-code-hash", @@ -83,11 +81,11 @@ fn ba_arg_and_ba_code_hash() { #[test] fn ba_advanced() { let matches = basic_app() - .try_get_matches_from(&[BIN_NAME, "run", "--ba-advanced"]) + .try_get_matches_from([BIN_NAME, "run", "--ba-advanced"]) .unwrap(); let sub_matches = matches.subcommand().unwrap().1; - assert_eq!(1, sub_matches.occurrences_of(ARG_BA_ADVANCED)); + assert!(sub_matches.contains_id(ARG_BA_ADVANCED)); } #[test] @@ -96,7 +94,7 @@ fn ba_advanced() { /// ckb run --assume-valid-target /// not for `ckb init --ba-arg` && `ckb init --ba-message` fn h256_as_validator() { - let ok_matches = basic_app().try_get_matches_from(&[ + let ok_matches = basic_app().try_get_matches_from([ BIN_NAME, "init", "--ba-code-hash", @@ -106,7 +104,7 @@ fn h256_as_validator() { ]); assert!(ok_matches.is_ok()); - let err_matches = basic_app().try_get_matches_from(&[ + let err_matches = basic_app().try_get_matches_from([ BIN_NAME, "init", "--ba-code-hash", @@ -115,9 +113,9 @@ fn h256_as_validator() { "0x00", ]); let err = err_matches.err().unwrap(); - assert_eq!(clap::ErrorKind::ValueValidation, err.kind()); + assert_eq!(clap::error::ErrorKind::ValueValidation, err.kind()); - let err_matches = basic_app().try_get_matches_from(&[ + let err_matches = basic_app().try_get_matches_from([ BIN_NAME, "init", "--ba-code-hash", @@ -126,21 +124,21 @@ fn h256_as_validator() { "0x00", ]); let err = err_matches.err().unwrap(); - assert_eq!(clap::ErrorKind::ValueValidation, err.kind()); + assert_eq!(clap::error::ErrorKind::ValueValidation, err.kind()); - let ok_matches = basic_app().try_get_matches_from(&[ + let ok_matches = basic_app().try_get_matches_from([ BIN_NAME, "run", "--assume-valid-target", "0x94a4e93601f7295501891764880d37e9fcf886d02bf64b3d06f9137db8fa981e", ]); assert!(ok_matches.is_ok()); - let err_matches = basic_app().try_get_matches_from(&[ + let err_matches = basic_app().try_get_matches_from([ BIN_NAME, "run", "--assume-valid-target", "0x94a4e93601f729550", ]); let err = err_matches.err().unwrap(); - assert_eq!(clap::ErrorKind::ValueValidation, err.kind()); + assert_eq!(clap::error::ErrorKind::ValueValidation, err.kind()); } From e74887f43ba458169f8dbd12279551c360141cc0 Mon Sep 17 00:00:00 2001 From: driftluo Date: Fri, 30 Dec 2022 20:20:11 +0800 Subject: [PATCH 2/2] clippy warning --- build.rs | 4 +- db/src/db.rs | 4 +- db/src/db_with_ttl.rs | 2 +- db/src/read_only_db.rs | 4 +- db/src/snapshot.rs | 2 +- db/src/tests/db_with_ttl.rs | 4 +- miner/src/worker/eaglesong_simple.rs | 2 +- network/src/protocols/discovery/protocol.rs | 2 +- network/src/tests/peer_store_db.rs | 4 +- pow/src/eaglesong_blake2b.rs | 2 +- pow/src/tests.rs | 2 +- rpc/src/error.rs | 2 +- .../syscalls/tests/vm_latest/syscalls_1.rs | 4 +- script/src/type_id.rs | 2 +- script/src/verify.rs | 4 +- script/src/verify/tests/utils.rs | 4 +- spec/src/lib.rs | 2 +- sync/src/net_time_checker.rs | 2 +- test/src/main.rs | 2 +- test/src/node.rs | 12 ++--- test/src/specs/mod.rs | 6 +-- test/src/worker.rs | 2 +- tx-pool/src/component/tests/recent_reject.rs | 6 +-- util/build-info/src/lib.rs | 4 +- util/fixed-hash/core/src/error.rs | 4 +- util/indexer/src/indexer.rs | 14 +++--- util/indexer/src/service.rs | 2 +- util/indexer/src/store/rocksdb.rs | 44 +++++++++---------- util/indexer/src/store/secondary_db.rs | 2 +- util/jsonrpc-types/src/blockchain.rs | 2 +- util/logger-service/src/lib.rs | 4 +- util/types/src/conversion/primitive.rs | 2 +- util/types/src/conversion/storage.rs | 2 +- util/types/src/core/cell.rs | 2 +- util/types/src/core/extras.rs | 2 +- util/types/src/core/tests/transaction_meta.rs | 4 +- verification/src/cache.rs | 2 +- 37 files changed, 86 insertions(+), 84 deletions(-) diff --git a/build.rs b/build.rs index 533f09ae52..e2c16b1abe 100644 --- a/build.rs +++ b/build.rs @@ -30,7 +30,7 @@ fn rerun_if_changed(path_str: &str) -> bool { #[allow(clippy::manual_strip)] fn main() { let files_stdout = std::process::Command::new("git") - .args(&["ls-tree", "-r", "--name-only", "HEAD"]) + .args(["ls-tree", "-r", "--name-only", "HEAD"]) .output() .ok() .and_then(|r| String::from_utf8(r.stdout).ok()); @@ -48,7 +48,7 @@ fn main() { println!("cargo:rerun-if-changed=build.rs"); let git_head = std::process::Command::new("git") - .args(&["rev-parse", "--git-dir"]) + .args(["rev-parse", "--git-dir"]) .output() .ok() .and_then(|r| String::from_utf8(r.stdout).ok()) diff --git a/db/src/db.rs b/db/src/db.rs index 42575daecc..4da932d8f6 100644 --- a/db/src/db.rs +++ b/db/src/db.rs @@ -157,13 +157,13 @@ impl RocksDB { /// so as to avoid unnecessary memory copy. 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) + 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> { - self.inner.get_pinned(&key).map_err(internal_error) + self.inner.get_pinned(key).map_err(internal_error) } /// Insert a value into the database under the given key. diff --git a/db/src/db_with_ttl.rs b/db/src/db_with_ttl.rs index 558804bffd..49b3de5b17 100644 --- a/db/src/db_with_ttl.rs +++ b/db/src/db_with_ttl.rs @@ -61,7 +61,7 @@ impl DBWithTTL { .inner .cf_handle(col) .ok_or_else(|| internal_error(format!("column {} not found", col)))?; - self.inner.get_pinned_cf(cf, &key).map_err(internal_error) + self.inner.get_pinned_cf(cf, key).map_err(internal_error) } /// Insert a value into the database under the given key. diff --git a/db/src/read_only_db.rs b/db/src/read_only_db.rs index b31d405d45..10bb3f1f59 100644 --- a/db/src/read_only_db.rs +++ b/db/src/read_only_db.rs @@ -60,7 +60,7 @@ 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> { - self.inner.get_pinned(&key).map_err(internal_error) + self.inner.get_pinned(key).map_err(internal_error) } /// Return the value associated with a key using RocksDB's PinnableSlice from the given column @@ -70,6 +70,6 @@ impl ReadOnlyDB { .inner .cf_handle(col) .ok_or_else(|| internal_error(format!("column {} not found", col)))?; - self.inner.get_pinned_cf(cf, &key).map_err(internal_error) + self.inner.get_pinned_cf(cf, key).map_err(internal_error) } } diff --git a/db/src/snapshot.rs b/db/src/snapshot.rs index 57bf094707..18dffba891 100644 --- a/db/src/snapshot.rs +++ b/db/src/snapshot.rs @@ -37,7 +37,7 @@ impl RocksDBSnapshot { /// so as to avoid unnecessary memory copy. 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) + self.get_pinned_cf_full(Some(cf), key, None) .map_err(internal_error) } } diff --git a/db/src/tests/db_with_ttl.rs b/db/src/tests/db_with_ttl.rs index eaf7dd8147..5d4c25af6a 100644 --- a/db/src/tests/db_with_ttl.rs +++ b/db/src/tests/db_with_ttl.rs @@ -12,7 +12,7 @@ fn test_open_db_with_ttl() { let mut db = db.unwrap(); for i in 0..1000u64 { - db.put("1", &i.to_le_bytes(), &[2]).unwrap(); + db.put("1", i.to_le_bytes(), [2]).unwrap(); assert_eq!( db.get_pinned("1", &i.to_le_bytes()) .unwrap() @@ -33,6 +33,6 @@ fn test_open_db_with_ttl() { db.create_cf_with_ttl("1", 50).unwrap(); assert!(db.get_pinned("1", &[1]).unwrap().is_none()); - db.put("1", &[1], &[3]).unwrap(); + db.put("1", [1], [3]).unwrap(); assert_eq!(db.get_pinned("1", &[1]).unwrap().unwrap().as_ref(), &[3]); } diff --git a/miner/src/worker/eaglesong_simple.rs b/miner/src/worker/eaglesong_simple.rs index 3fca7cbc5d..6e097b8538 100644 --- a/miner/src/worker/eaglesong_simple.rs +++ b/miner/src/worker/eaglesong_simple.rs @@ -66,7 +66,7 @@ impl EaglesongSimple { let mut output_tmp = [0u8; 32]; eaglesong(&input, &mut output_tmp); match self.extra_hash_function { - Some(ExtraHashFunction::Blake2b) => blake2b_256(&output_tmp), + Some(ExtraHashFunction::Blake2b) => blake2b_256(output_tmp), None => output_tmp, } }; diff --git a/network/src/protocols/discovery/protocol.rs b/network/src/protocols/discovery/protocol.rs index 9380b5d5f7..fd25d04422 100644 --- a/network/src/protocols/discovery/protocol.rs +++ b/network/src/protocols/discovery/protocol.rs @@ -57,7 +57,7 @@ impl DiscoveryMessage { .build() } DiscoveryMessage::Nodes(Nodes { announce, items }) => { - let bool_ = if announce { 1u8 } else { 0 }; + let bool_ = u8::from(announce); let announce = packed::Bool::new_builder().set([bool_.into()]).build(); let mut item_vec = Vec::with_capacity(items.len()); for item in items { diff --git a/network/src/tests/peer_store_db.rs b/network/src/tests/peer_store_db.rs index e7f8fb5676..5d7e92b2b6 100644 --- a/network/src/tests/peer_store_db.rs +++ b/network/src/tests/peer_store_db.rs @@ -64,8 +64,8 @@ fn test_peer_store_persistent() { // dump and load let dir = tempfile::tempdir().unwrap(); - peer_store.dump_to_dir(&dir.path()).unwrap(); - let peer_store2 = PeerStore::load_from_dir_or_default(&dir.path()); + peer_store.dump_to_dir(dir.path()).unwrap(); + let peer_store2 = PeerStore::load_from_dir_or_default(dir.path()); // check addr manager let addr_manager2 = peer_store2.addr_manager(); diff --git a/pow/src/eaglesong_blake2b.rs b/pow/src/eaglesong_blake2b.rs index 7c2638f90f..497128a54d 100644 --- a/pow/src/eaglesong_blake2b.rs +++ b/pow/src/eaglesong_blake2b.rs @@ -15,7 +15,7 @@ impl PowEngine for EaglesongBlake2bPowEngine { let output = { let mut output_tmp = [0u8; 32]; eaglesong(&input, &mut output_tmp); - blake2b_256(&output_tmp) + blake2b_256(output_tmp) }; let (block_target, overflow) = compact_to_target(header.raw().compact_target().unpack()); diff --git a/pow/src/tests.rs b/pow/src/tests.rs index debabd9609..ad4f27ca26 100644 --- a/pow/src/tests.rs +++ b/pow/src/tests.rs @@ -4,7 +4,7 @@ use ckb_types::prelude::*; #[test] fn test_pow_message() { - let zero_hash = blake2b_256(&[]).pack(); + let zero_hash = blake2b_256([]).pack(); let nonce = u128::max_value(); let message = pow_message(&zero_hash, nonce); assert_eq!( diff --git a/rpc/src/error.rs b/rpc/src/error.rs index 19e1ecaa6d..a1bd8eca9e 100644 --- a/rpc/src/error.rs +++ b/rpc/src/error.rs @@ -28,7 +28,7 @@ use std::fmt::{Debug, Display}; /// /// Unless otherwise noted, all the errors return optional detailed information as `string` in the error /// object `data` field. -#[derive(Debug, PartialEq, Clone, Copy)] +#[derive(Debug, PartialEq, Clone, Copy, Eq)] pub enum RPCError { /// (-1): CKB internal errors are considered to never happen or only happen when the system /// resources are exhausted. diff --git a/script/src/syscalls/tests/vm_latest/syscalls_1.rs b/script/src/syscalls/tests/vm_latest/syscalls_1.rs index 33f5ac3a36..5fc852419f 100644 --- a/script/src/syscalls/tests/vm_latest/syscalls_1.rs +++ b/script/src/syscalls/tests/vm_latest/syscalls_1.rs @@ -655,7 +655,7 @@ fn _test_load_header( machine.set_register(A4, source); //source: 4 header machine.set_register(A7, LOAD_HEADER_SYSCALL_NUMBER); // syscall number - let data_hash = blake2b_256(&data).pack(); + let data_hash = blake2b_256(data).pack(); let header = HeaderBuilder::default() .transactions_root(data_hash) .build(); @@ -768,7 +768,7 @@ fn _test_load_header_by_field(data: &[u8], field: HeaderField) -> Result<(), Tes machine.set_register(A5, field as u64); machine.set_register(A7, LOAD_HEADER_BY_FIELD_SYSCALL_NUMBER); // syscall number - let data_hash: H256 = blake2b_256(&data).into(); + let data_hash: H256 = blake2b_256(data).into(); let epoch = EpochNumberWithFraction::new(1, 40, 1000); let header = HeaderBuilder::default() .transactions_root(data_hash.pack()) diff --git a/script/src/type_id.rs b/script/src/type_id.rs index a6313361ec..30d8d537dc 100644 --- a/script/src/type_id.rs +++ b/script/src/type_id.rs @@ -59,7 +59,7 @@ impl<'a> TypeIdSystemScript<'a> { let first_output_index: u64 = self .script_group .output_indices - .get(0) + .first() .map(|output_index| *output_index as u64) .ok_or_else(|| self.validation_failure(ERROR_ARGS))?; diff --git a/script/src/verify.rs b/script/src/verify.rs index dc65399b21..de4cea27fc 100644 --- a/script/src/verify.rs +++ b/script/src/verify.rs @@ -113,6 +113,8 @@ impl Binaries { } } +type DebugPrinter = Box; + /// This struct leverages CKB VM to verify transaction inputs. /// /// FlatBufferBuilder owned `Vec` that grows as needed, in the @@ -120,7 +122,7 @@ impl Binaries { pub struct TransactionScriptsVerifier<'a, DL> { data_loader: &'a DL, - debug_printer: Box, + debug_printer: DebugPrinter, outputs: Vec, rtx: &'a ResolvedTransaction, diff --git a/script/src/verify/tests/utils.rs b/script/src/verify/tests/utils.rs index 21bd16e6b2..2791991b84 100644 --- a/script/src/verify/tests/utils.rs +++ b/script/src/verify/tests/utils.rs @@ -228,10 +228,10 @@ pub(super) fn random_2_in_2_out_rtx() -> ResolvedTransaction { let mut generator = Generator::non_crypto_safe_prng(42); let privkey = generator.gen_privkey(); let pubkey_data = privkey.pubkey().expect("Get pubkey failed").serialize(); - let lock_arg = Bytes::from((&blake2b_256(&pubkey_data)[0..20]).to_owned()); + let lock_arg = Bytes::from((blake2b_256(&pubkey_data)[0..20]).to_owned()); let privkey2 = generator.gen_privkey(); let pubkey_data2 = privkey2.pubkey().expect("Get pubkey failed").serialize(); - let lock_arg2 = Bytes::from((&blake2b_256(&pubkey_data2)[0..20]).to_owned()); + let lock_arg2 = Bytes::from((blake2b_256(&pubkey_data2)[0..20]).to_owned()); let lock = Script::new_builder() .args(lock_arg.pack()) diff --git a/spec/src/lib.rs b/spec/src/lib.rs index 26c8002b70..5ce8b7d479 100644 --- a/spec/src/lib.rs +++ b/spec/src/lib.rs @@ -969,7 +969,7 @@ impl SystemCell { fn secp_lock_arg(privkey: &Privkey) -> Bytes { let pubkey_data = privkey.pubkey().expect("Get pubkey failed").serialize(); - Bytes::from((&blake2b_256(&pubkey_data)[0..20]).to_owned()) + Bytes::from((blake2b_256(&pubkey_data)[0..20]).to_owned()) } /// Shortcut for build genesis type_id script from specified output_index diff --git a/sync/src/net_time_checker.rs b/sync/src/net_time_checker.rs index ceec1a5557..42dec68945 100644 --- a/sync/src/net_time_checker.rs +++ b/sync/src/net_time_checker.rs @@ -60,7 +60,7 @@ impl NetTimeChecker { Some(offset) => offset, None => return Ok(()), }; - if network_offset.abs() as u64 > self.tolerant_offset { + if network_offset.unsigned_abs() > self.tolerant_offset { return Err(network_offset); } Ok(()) diff --git a/test/src/main.rs b/test/src/main.rs index 9319c462dc..9ddb1dbd8b 100644 --- a/test/src/main.rs +++ b/test/src/main.rs @@ -570,7 +570,7 @@ fn print_panicked_logs(node_log_paths: &[PathBuf]) { from_ln + print_lns, node_log.display(), ); - BufReader::new(File::open(&node_log).expect("failed to read node's log")) + BufReader::new(File::open(node_log).expect("failed to read node's log")) .lines() .skip(from_ln) .take(print_lns) diff --git a/test/src/node.rs b/test/src/node.rs index 040d166395..aab2b305b3 100644 --- a/test/src/node.rs +++ b/test/src/node.rs @@ -584,9 +584,9 @@ impl Node { pub fn start(&mut self) { let mut child_process = Command::new(binary()) .env("RUST_BACKTRACE", "full") - .args(&[ + .args([ "-C", - &self.working_dir().to_string_lossy().to_string(), + &self.working_dir().to_string_lossy(), "run", "--ba-advanced", ]) @@ -655,10 +655,10 @@ impl Node { pub fn export(&self, target: String) { Command::new(binary()) - .args(&[ + .args([ "export", "-C", - &self.working_dir().to_string_lossy().to_string(), + &self.working_dir().to_string_lossy(), &target, ]) .stdin(Stdio::null()) @@ -670,10 +670,10 @@ impl Node { pub fn import(&self, target: String) { Command::new(binary()) - .args(&[ + .args([ "import", "-C", - &self.working_dir().to_string_lossy().to_string(), + &self.working_dir().to_string_lossy(), &target, ]) .stdin(Stdio::null()) diff --git a/test/src/specs/mod.rs b/test/src/specs/mod.rs index 0f9a2da317..a81a5d061f 100644 --- a/test/src/specs/mod.rs +++ b/test/src/specs/mod.rs @@ -77,19 +77,19 @@ impl Default for Setup { #[macro_export] macro_rules! setup { ($($setup:tt)*) => { - fn setup(&self) -> $crate::Setup{ crate::setup_internal!($($setup)*) } + fn setup(&self) -> $crate::Setup{ $crate::setup_internal!($($setup)*) } }; } #[macro_export] macro_rules! setup_internal { ($field:ident: $value:expr,) => { - crate::setup_internal!($field: $value) + $crate::setup_internal!($field: $value) }; ($field:ident: $value:expr) => { $crate::Setup{ $field: $value, ..Default::default() } }; ($field:ident: $value:expr, $($rest:tt)*) => { - $crate::Setup{ $field: $value, ..crate::setup_internal!($($rest)*) } + $crate::Setup{ $field: $value, ..$crate::setup_internal!($($rest)*) } }; } diff --git a/test/src/worker.rs b/test/src/worker.rs index 9f49ad3187..4fec1ccd3f 100644 --- a/test/src/worker.rs +++ b/test/src/worker.rs @@ -10,7 +10,7 @@ use std::thread::{self, JoinHandle}; use std::time::Instant; /// Commands -#[derive(PartialEq)] +#[derive(PartialEq, Eq)] pub enum Command { Shutdown, } diff --git a/tx-pool/src/component/tests/recent_reject.rs b/tx-pool/src/component/tests/recent_reject.rs index c93812a4fa..35f1bbed86 100644 --- a/tx-pool/src/component/tests/recent_reject.rs +++ b/tx-pool/src/component/tests/recent_reject.rs @@ -13,14 +13,14 @@ fn test_basic() { let mut recent_reject = RecentReject::build(tmp_dir.path(), shard_num, limit, ttl).unwrap(); for i in 0..80u64 { - let key = Byte32::new(blake2b_256(&i.to_le_bytes())); + let key = Byte32::new(blake2b_256(i.to_le_bytes())); recent_reject .put(&key, Reject::Malformed(i.to_string())) .unwrap(); } for i in 0..80u64 { - let key = Byte32::new(blake2b_256(&i.to_le_bytes())); + let key = Byte32::new(blake2b_256(i.to_le_bytes())); let reject: ckb_jsonrpc_types::PoolTransactionReject = Reject::Malformed(i.to_string()).into(); assert_eq!( @@ -30,7 +30,7 @@ fn test_basic() { } for i in 0..80u64 { - let key = Byte32::new(blake2b_256(&i.to_le_bytes())); + let key = Byte32::new(blake2b_256(i.to_le_bytes())); recent_reject .put(&key, Reject::Malformed(i.to_string())) .unwrap(); diff --git a/util/build-info/src/lib.rs b/util/build-info/src/lib.rs index 995b75ee3d..665344a00e 100644 --- a/util/build-info/src/lib.rs +++ b/util/build-info/src/lib.rs @@ -105,7 +105,7 @@ impl std::fmt::Display for Version { /// [`commit_describe`]: struct.Version.html#structfield.commit_describe pub fn get_commit_describe() -> Option { std::process::Command::new("git") - .args(&[ + .args([ "describe", "--dirty", "--always", @@ -129,7 +129,7 @@ pub fn get_commit_describe() -> Option { pub fn get_commit_date() -> Option { std::process::Command::new("git") .env("TZ", "UTC") - .args(&["log", "-1", "--date=iso", "--pretty=format:%cd"]) + .args(["log", "-1", "--date=iso", "--pretty=format:%cd"]) .output() .ok() .filter(|output| output.status.success()) diff --git a/util/fixed-hash/core/src/error.rs b/util/fixed-hash/core/src/error.rs index 4c22a1a3f6..d678273df6 100644 --- a/util/fixed-hash/core/src/error.rs +++ b/util/fixed-hash/core/src/error.rs @@ -5,7 +5,7 @@ use thiserror::Error; /// The associated error of [`FromStr`] which can be returned from parsing a string. /// /// [`FromStr`]: https://doc.rust-lang.org/std/str/trait.FromStr.html#associatedtype.Err -#[derive(Error, Debug, PartialEq)] +#[derive(Error, Debug, PartialEq, Eq)] pub enum FromStrError { /// Invalid character. #[error("invalid character code `{chr}` at {idx}")] @@ -21,7 +21,7 @@ pub enum FromStrError { } /// The error which can be returned when convert a byte slice back into a Hash. -#[derive(Error, Debug, PartialEq)] +#[derive(Error, Debug, PartialEq, Eq)] pub enum FromSliceError { /// Invalid length. #[error("invalid length: {0}")] diff --git a/util/indexer/src/indexer.rs b/util/indexer/src/indexer.rs index 6119d69dd9..3e3e0ceb10 100644 --- a/util/indexer/src/indexer.rs +++ b/util/indexer/src/indexer.rs @@ -525,7 +525,7 @@ where pub(crate) fn rollback(&self) -> Result<(), Error> { let mut iter = self .store - .iter(&[KeyPrefix::Header as u8 + 1], IteratorDirection::Reverse)?; + .iter([KeyPrefix::Header as u8 + 1], IteratorDirection::Reverse)?; if let Some((block_number, block_hash, filtered, txs)) = iter.next().map(|(key, value)| { let filtered = key.len() == 42 && key[41] == 1; ( @@ -681,7 +681,7 @@ where pub(crate) fn tip(&self) -> Result, Error> { let mut iter = self .store - .iter(&[KeyPrefix::Header as u8 + 1], IteratorDirection::Reverse)?; + .iter([KeyPrefix::Header as u8 + 1], IteratorDirection::Reverse)?; Ok(iter.next().map(|(key, _)| { ( BlockNumber::from_be_bytes(key[1..9].try_into().expect("stored block key")), @@ -891,7 +891,7 @@ where /// Print statistics #[allow(dead_code)] pub(crate) fn report(&self) -> Result<(), Error> { - let iter = self.store.iter(&[], IteratorDirection::Forward)?; + let iter = self.store.iter([], IteratorDirection::Forward)?; let mut statistics: HashMap = HashMap::new(); for (key, value) in iter { let s = statistics.entry(*key.first().unwrap()).or_default(); @@ -1095,7 +1095,7 @@ mod tests { // tip should be None and store should be empty; assert!(indexer.tip().unwrap().is_none()); - let mut iter = indexer.store.iter(&[], IteratorDirection::Forward).unwrap(); + let mut iter = indexer.store.iter([], IteratorDirection::Forward).unwrap(); assert!(iter.next().is_none()); } @@ -1568,7 +1568,7 @@ mod tests { let key_prefix = [KeyPrefix::ConsumedOutPoint as u8]; let stored_consumed_out_points = indexer .store - .iter(&key_prefix, IteratorDirection::Forward) + .iter(key_prefix, IteratorDirection::Forward) .unwrap() .take_while(|(key, _value)| key.starts_with(&key_prefix)) .count(); @@ -1578,7 +1578,7 @@ mod tests { let key_prefix = [KeyPrefix::TxHash as u8]; let stored_tx_hashes = indexer .store - .iter(&key_prefix, IteratorDirection::Forward) + .iter(key_prefix, IteratorDirection::Forward) .unwrap() .take_while(|(key, _value)| key.starts_with(&key_prefix)) .count(); @@ -1738,7 +1738,7 @@ mod tests { // tip should be None and store should be empty; assert!(indexer.tip().unwrap().is_none()); - let mut iter = indexer.store.iter(&[], IteratorDirection::Forward).unwrap(); + let mut iter = indexer.store.iter([], IteratorDirection::Forward).unwrap(); assert!(iter.next().is_none()); } diff --git a/util/indexer/src/service.rs b/util/indexer/src/service.rs index 8e20791dcb..449663813e 100644 --- a/util/indexer/src/service.rs +++ b/util/indexer/src/service.rs @@ -276,7 +276,7 @@ impl IndexerHandle { pub fn get_indexer_tip(&self) -> Result, Error> { let mut iter = self .store - .iter(&[KeyPrefix::Header as u8 + 1], IteratorDirection::Reverse) + .iter([KeyPrefix::Header as u8 + 1], IteratorDirection::Reverse) .expect("iter Header should be OK"); Ok(iter.next().map(|(key, _)| IndexerTip { block_hash: packed::Byte32::from_slice(&key[9..41]) diff --git a/util/indexer/src/store/rocksdb.rs b/util/indexer/src/store/rocksdb.rs index 1ea9cfa302..e3fdfc5120 100644 --- a/util/indexer/src/store/rocksdb.rs +++ b/util/indexer/src/store/rocksdb.rs @@ -107,13 +107,13 @@ mod tests { tmp_dir.path().to_str().unwrap(), ); let mut batch = store.batch().unwrap(); - batch.put(&[0, 0], &[0, 0, 0]).unwrap(); - batch.put(&[1, 1], &[1, 1, 1]).unwrap(); + batch.put([0, 0], [0, 0, 0]).unwrap(); + batch.put([1, 1], [1, 1, 1]).unwrap(); batch.commit().unwrap(); - assert_eq!(Some(vec![0, 0, 0]), store.get(&[0, 0]).unwrap()); - assert_eq!(Some(vec![1, 1, 1]), store.get(&[1, 1]).unwrap()); - assert_eq!(None, store.get(&[2, 2]).unwrap()); + assert_eq!(Some(vec![0, 0, 0]), store.get([0, 0]).unwrap()); + assert_eq!(Some(vec![1, 1, 1]), store.get([1, 1]).unwrap()); + assert_eq!(None, store.get([2, 2]).unwrap()); } #[test] @@ -123,13 +123,13 @@ mod tests { &RocksdbStore::default_options(), tmp_dir.path().to_str().unwrap(), ); - assert!(!store.exists(&[0, 0]).unwrap()); + assert!(!store.exists([0, 0]).unwrap()); let mut batch = store.batch().unwrap(); - batch.put(&[0, 0], &[0, 0, 0]).unwrap(); + batch.put([0, 0], [0, 0, 0]).unwrap(); batch.commit().unwrap(); - assert!(store.exists(&[0, 0]).unwrap()); + assert!(store.exists([0, 0]).unwrap()); } #[test] @@ -140,14 +140,14 @@ mod tests { tmp_dir.path().to_str().unwrap(), ); let mut batch = store.batch().unwrap(); - batch.put(&[0, 0], &[0, 0, 0]).unwrap(); + batch.put([0, 0], [0, 0, 0]).unwrap(); batch.commit().unwrap(); - assert_eq!(Some(vec![0, 0, 0]), store.get(&[0, 0]).unwrap()); + assert_eq!(Some(vec![0, 0, 0]), store.get([0, 0]).unwrap()); let mut batch = store.batch().unwrap(); - batch.delete(&[0, 0]).unwrap(); + batch.delete([0, 0]).unwrap(); batch.commit().unwrap(); - assert_eq!(None, store.get(&[0, 0]).unwrap()); + assert_eq!(None, store.get([0, 0]).unwrap()); } #[test] @@ -158,16 +158,16 @@ mod tests { tmp_dir.path().to_str().unwrap(), ); let mut batch = store.batch().unwrap(); - batch.put(&[0, 0, 0], &[0, 0, 0]).unwrap(); - batch.put(&[0, 0, 1], &[0, 0, 1]).unwrap(); - batch.put(&[1, 0, 0], &[1, 0, 0]).unwrap(); - batch.put(&[1, 0, 1], &[1, 0, 1]).unwrap(); - batch.put(&[2, 0, 0, 1], &[2, 0, 0, 1]).unwrap(); - batch.put(&[2, 0, 1, 1], &[2, 0, 1, 1]).unwrap(); - batch.put(&[2, 0, 2, 1], &[2, 0, 2, 1]).unwrap(); + batch.put([0, 0, 0], [0, 0, 0]).unwrap(); + batch.put([0, 0, 1], [0, 0, 1]).unwrap(); + batch.put([1, 0, 0], [1, 0, 0]).unwrap(); + batch.put([1, 0, 1], [1, 0, 1]).unwrap(); + batch.put([2, 0, 0, 1], [2, 0, 0, 1]).unwrap(); + batch.put([2, 0, 1, 1], [2, 0, 1, 1]).unwrap(); + batch.put([2, 0, 2, 1], [2, 0, 2, 1]).unwrap(); batch.commit().unwrap(); - let mut iter = store.iter(&[0, 0, 1], IteratorDirection::Forward).unwrap(); + let mut iter = store.iter([0, 0, 1], IteratorDirection::Forward).unwrap(); assert_eq!( Some((vec![0, 0, 1], vec![0, 0, 1])), iter.next().map(|i| (i.0.to_vec(), i.1.to_vec())) @@ -177,7 +177,7 @@ mod tests { iter.next().map(|i| (i.0.to_vec(), i.1.to_vec())) ); - let mut iter = store.iter(&[0, 0, 1], IteratorDirection::Reverse).unwrap(); + let mut iter = store.iter([0, 0, 1], IteratorDirection::Reverse).unwrap(); assert_eq!( Some((vec![0, 0, 1], vec![0, 0, 1])), iter.next().map(|i| (i.0.to_vec(), i.1.to_vec())) @@ -188,7 +188,7 @@ mod tests { ); assert!(iter.next().is_none()); - let mut iter = store.iter(&[2, 0, 1], IteratorDirection::Reverse).unwrap(); + let mut iter = store.iter([2, 0, 1], IteratorDirection::Reverse).unwrap(); assert_eq!( Some((vec![2, 0, 0, 1], vec![2, 0, 0, 1])), iter.next().map(|i| (i.0.to_vec(), i.1.to_vec())) diff --git a/util/indexer/src/store/secondary_db.rs b/util/indexer/src/store/secondary_db.rs index 8180fe11a5..2554ce1687 100644 --- a/util/indexer/src/store/secondary_db.rs +++ b/util/indexer/src/store/secondary_db.rs @@ -73,7 +73,7 @@ impl SecondaryDB { .inner .cf_handle(col) .ok_or_else(|| Error::DB(format!("column {} not found", col)))?; - self.inner.get_pinned_cf(cf, &key).map_err(Into::into) + self.inner.get_pinned_cf(cf, key).map_err(Into::into) } /// Make the secondary instance catch up with the primary by tailing and diff --git a/util/jsonrpc-types/src/blockchain.rs b/util/jsonrpc-types/src/blockchain.rs index 0faf151f84..e6e3afcba2 100644 --- a/util/jsonrpc-types/src/blockchain.rs +++ b/util/jsonrpc-types/src/blockchain.rs @@ -1399,7 +1399,7 @@ impl HardForkFeature { } /// The fee_rate statistics information, includes mean and median, unit: shannons per kilo-weight -#[derive(Clone, Serialize, Deserialize, Debug, PartialEq)] +#[derive(Clone, Serialize, Deserialize, Debug, PartialEq, Eq)] pub struct FeeRateStatics { /// mean pub mean: Uint64, diff --git a/util/logger-service/src/lib.rs b/util/logger-service/src/lib.rs index e5117f1750..faed23e8b2 100644 --- a/util/logger-service/src/lib.rs +++ b/util/logger-service/src/lib.rs @@ -298,7 +298,7 @@ impl Logger { fs::OpenOptions::new() .append(true) .create(true) - .open(&file_path) + .open(file_path) .map_err(|err| { format!( "Cannot write to log file given: {:?} since {}", @@ -512,7 +512,7 @@ fn setup_panic_logger() { let msg = match info.payload().downcast_ref::<&'static str>() { Some(s) => *s, None => match info.payload().downcast_ref::() { - Some(s) => &*s, + Some(s) => s, None => "Box", }, }; diff --git a/util/types/src/conversion/primitive.rs b/util/types/src/conversion/primitive.rs index f592eb2471..69357eab47 100644 --- a/util/types/src/conversion/primitive.rs +++ b/util/types/src/conversion/primitive.rs @@ -2,7 +2,7 @@ use crate::{bytes::Bytes, packed, prelude::*}; impl Pack for bool { fn pack(&self) -> packed::Bool { - let b = if *self { 1u8 } else { 0 }; + let b = u8::from(*self); packed::Bool::new_unchecked(Bytes::from(vec![b])) } } diff --git a/util/types/src/conversion/storage.rs b/util/types/src/conversion/storage.rs index ddcd250e1f..fc7374d02b 100644 --- a/util/types/src/conversion/storage.rs +++ b/util/types/src/conversion/storage.rs @@ -81,7 +81,7 @@ impl Pack for core::BlockExt { .total_difficulty(self.total_difficulty.pack()) .total_uncles_count(self.total_uncles_count.pack()) .verified(self.verified.pack()) - .txs_fees((&self.txs_fees[..]).pack()) + .txs_fees((self.txs_fees[..]).pack()) .cycles(self.cycles.pack()) .txs_sizes(self.txs_sizes.pack()) .build() diff --git a/util/types/src/core/cell.rs b/util/types/src/core/cell.rs index dcec3ce268..c691b4668f 100644 --- a/util/types/src/core/cell.rs +++ b/util/types/src/core/cell.rs @@ -165,7 +165,7 @@ impl CellMeta { } /// TODO(doc): @quake -#[derive(PartialEq, Debug)] +#[derive(PartialEq, Debug, Eq)] pub enum CellStatus { /// Cell exists and has not been spent. Live(CellMeta), diff --git a/util/types/src/core/extras.rs b/util/types/src/core/extras.rs index 96cb4ad139..d42eb66ce6 100644 --- a/util/types/src/core/extras.rs +++ b/util/types/src/core/extras.rs @@ -11,7 +11,7 @@ use std::num::ParseIntError; use std::str::FromStr; /// TODO(doc): @quake -#[derive(Clone, PartialEq, Default, Debug)] +#[derive(Clone, PartialEq, Default, Debug, Eq)] pub struct BlockExt { /// TODO(doc): @quake pub received_at: u64, diff --git a/util/types/src/core/tests/transaction_meta.rs b/util/types/src/core/tests/transaction_meta.rs index 39ea97b23f..6a0d666dc4 100644 --- a/util/types/src/core/tests/transaction_meta.rs +++ b/util/types/src/core/tests/transaction_meta.rs @@ -14,9 +14,9 @@ fn set_unset_dead_out_of_bounds() { assert!(meta.is_dead(3) == Some(false)); // none-op meta.set_dead(4); - assert!(meta.is_dead(4) == None); + assert!(meta.is_dead(4).is_none()); meta.unset_dead(4); - assert!(meta.is_dead(4) == None); + assert!(meta.is_dead(4).is_none()); } #[test] diff --git a/verification/src/cache.rs b/verification/src/cache.rs index 60b228ae0f..b7ceab66ab 100644 --- a/verification/src/cache.rs +++ b/verification/src/cache.rs @@ -36,7 +36,7 @@ pub struct Suspended { } /// Completed entry -#[derive(Clone, Copy, Debug, PartialEq)] +#[derive(Clone, Copy, Debug, PartialEq, Eq)] pub struct Completed { /// Cached tx cycles pub cycles: Cycle,