From e1235b2dadbe20ea50f4824db59d902ab7de1732 Mon Sep 17 00:00:00 2001 From: 0o-de-lally <1364012+0o-de-lally@users.noreply.github.com> Date: Sun, 19 Jan 2025 20:20:45 -0500 Subject: [PATCH] clippy wip --- .../sdk/v5_2_0_transaction_script_builder.rs | 21 +- .../src/version_five/hash_value_v5.rs | 242 +----------------- .../src/version_five/state_snapshot_v5.rs | 5 +- .../version_five/transaction_manifest_v5.rs | 5 +- .../src/libra_framework_sdk_builder.rs | 10 +- framework/src/framework_cli.rs | 2 +- tools/genesis/src/wizard.rs | 2 +- tools/storage/src/read_snapshot.rs | 8 +- tools/storage/src/read_tx_chunk.rs | 7 +- tools/wallet/src/core/mnemonic.rs | 2 +- tools/wallet/src/keys.rs | 1 - 11 files changed, 24 insertions(+), 281 deletions(-) diff --git a/compatibility/src/sdk/v5_2_0_transaction_script_builder.rs b/compatibility/src/sdk/v5_2_0_transaction_script_builder.rs index 7acc45ab6..a447938e3 100644 --- a/compatibility/src/sdk/v5_2_0_transaction_script_builder.rs +++ b/compatibility/src/sdk/v5_2_0_transaction_script_builder.rs @@ -4421,7 +4421,6 @@ pub fn encode_create_child_vasp_account_script_function( /// | `human_name` | `vector` | ASCII-encoded human name for the Designated Dealer. | /// | `add_all_currencies` | `bool` | Whether to publish preburn, balance, and tier info resources for all known (SCS) currencies or just `Currency` when the account is created. | /// - /// # Common Abort Conditions /// | Error Category | Error Reason | Description | /// | ---------------- | -------------- | ------------- | @@ -4695,9 +4694,7 @@ pub fn encode_create_validator_account_script_function( /// # Events /// Successful execution will emit: /// * A `DiemAccount::CreateAccountEvent` with the `created` field being `new_account_address`, -/// and the `rold_id` field being `Roles::VALIDATOR_OPERATOR_ROLE_ID`. This is emitted on the -/// `DiemAccount::AccountOperationsCapability` `creation_events` handle. -/// +/// and the `rold_id` field being `Roles::VALIDATOR_OPERATOR_ROLE_ID`. This is emitted on the `DiemAccount::AccountOperationsCapability` `creation_events` handle. /// # Parameters /// | Name | Type | Description | /// | ------ | ------ | ------------- | @@ -5058,11 +5055,9 @@ pub fn encode_peer_to_peer_with_metadata_script_function( /// /// # Events /// Successful execution of this script emits two events: -/// * `DiemAccount::SentPaymentEvent ` on `account`'s `DiemAccount::DiemAccount` `sent_events` -/// handle with the `payee` and `payer` fields being `account`'s address; and +/// * `DiemAccount::SentPaymentEvent ` on `account`'s `DiemAccount::DiemAccount` `sent_events` handle with the `payee` and `payer` fields being `account`'s address; and /// * A `Diem::PreburnEvent` with `Token`'s currency code on the -/// `Diem::CurrencyInfo HashValueBitIterator<'a> { } } -impl<'a> std::iter::Iterator for HashValueBitIterator<'a> { +impl std::iter::Iterator for HashValueBitIterator<'_> { type Item = bool; fn next(&mut self) -> Option { @@ -451,241 +446,10 @@ impl<'a> std::iter::Iterator for HashValueBitIterator<'a> { } } -impl<'a> std::iter::DoubleEndedIterator for HashValueBitIterator<'a> { +impl std::iter::DoubleEndedIterator for HashValueBitIterator<'_> { fn next_back(&mut self) -> Option { self.pos.next_back().map(|x| self.get_bit(x)) } } -impl<'a> std::iter::ExactSizeIterator for HashValueBitIterator<'a> {} - -// /// A type that can be cryptographically hashed to produce a `HashValue`. -// /// -// /// In most cases, this trait should not be implemented manually but rather derived using -// /// the macros `serde::Serialize`, `CryptoHasher`, and `BCSCryptoHash`. -// pub trait CryptoHash { -// /// The associated `Hasher` type which comes with a unique salt for this type. -// type Hasher: CryptoHasher; - -// /// Hashes the object and produces a `HashValue`. -// fn hash(&self) -> HashValue; -// } - -// /// A trait for representing the state of a cryptographic hasher. -// pub trait CryptoHasher: Default + std::io::Write { -// /// the seed used to initialize hashing `Self` before the serialization bytes of the actual value -// fn seed() -> &'static [u8; 32]; - -// /// Write bytes into the hasher. -// fn update(&mut self, bytes: &[u8]); - -// /// Finish constructing the [`HashValue`]. -// fn finish(self) -> HashValue; - -// /// Convenience method to compute the hash of a complete byte slice. -// fn hash_all(bytes: &[u8]) -> HashValue { -// let mut hasher = Self::default(); -// hasher.update(bytes); -// hasher.finish() -// } -// } - -// /// The default hasher underlying generated implementations of `CryptoHasher`. -// #[doc(hidden)] -// #[derive(Clone)] -// pub struct DefaultHasher { -// state: Sha3, -// } - -// impl DefaultHasher { -// #[doc(hidden)] -// /// This function does not return a HashValue in the sense of our usual -// /// hashes, but a construction of initial bytes that are fed into any hash -// /// provided we're passed a (bcs) serialization name as argument. -// pub fn prefixed_hash(buffer: &[u8]) -> [u8; HashValue::LENGTH] { -// // The salt is initial material we prefix to actual value bytes for -// // domain separation. Its length is variable. -// let salt: Vec = [DIEM_HASH_PREFIX, buffer].concat(); -// // The seed is a fixed-length hash of the salt, thereby preventing -// // suffix attacks on the domain separation bytes. -// HashValue::sha3_256_of(&salt[..]).hash -// } - -// #[doc(hidden)] -// pub fn new(typename: &[u8]) -> Self { -// let mut state = Sha3::v256(); -// if !typename.is_empty() { -// state.update(&Self::prefixed_hash(typename)); -// } -// DefaultHasher { state } -// } - -// #[doc(hidden)] -// pub fn update(&mut self, bytes: &[u8]) { -// self.state.update(bytes); -// } - -// #[doc(hidden)] -// pub fn finish(self) -> HashValue { -// let mut hasher = HashValue::default(); -// self.state.finalize(hasher.as_ref_mut()); -// hasher -// } -// } - -// impl fmt::Debug for DefaultHasher { -// fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { -// write!(f, "DefaultHasher: state = Sha3") -// } -// } - -// macro_rules! define_hasher { -// ( -// $(#[$attr:meta])* -// ($hasher_type: ident, $hasher_name: ident, $seed_name: ident, $salt: expr) -// ) => { - -// #[derive(Clone, Debug)] -// $(#[$attr])* -// pub struct $hasher_type(DefaultHasher); - -// impl $hasher_type { -// fn new() -> Self { -// $hasher_type(DefaultHasher::new($salt)) -// } -// } - -// static $hasher_name: Lazy<$hasher_type> = Lazy::new(|| { $hasher_type::new() }); -// static $seed_name: OnceCell<[u8; 32]> = OnceCell::new(); - -// impl Default for $hasher_type { -// fn default() -> Self { -// $hasher_name.clone() -// } -// } - -// impl CryptoHasher for $hasher_type { -// fn seed() -> &'static [u8;32] { -// $seed_name.get_or_init(|| { -// DefaultHasher::prefixed_hash($salt) -// }) -// } - -// fn update(&mut self, bytes: &[u8]) { -// self.0.update(bytes); -// } - -// fn finish(self) -> HashValue { -// self.0.finish() -// } -// } - -// impl std::io::Write for $hasher_type { -// fn write(&mut self, bytes: &[u8]) -> std::io::Result { -// self.0.update(bytes); -// Ok(bytes.len()) -// } -// fn flush(&mut self) -> std::io::Result<()> { -// Ok(()) -// } -// } -// }; -// } - -// define_hasher! { -// /// The hasher used to compute the hash of an internal node in the transaction accumulator. -// ( -// TransactionAccumulatorHasher, -// TRANSACTION_ACCUMULATOR_HASHER, -// TRANSACTION_ACCUMULATOR_SEED, -// b"TransactionAccumulator" -// ) -// } - -// define_hasher! { -// /// The hasher used to compute the hash of an internal node in the event accumulator. -// ( -// EventAccumulatorHasher, -// EVENT_ACCUMULATOR_HASHER, -// EVENT_ACCUMULATOR_SEED, -// b"EventAccumulator" -// ) -// } - -// define_hasher! { -// /// The hasher used to compute the hash of an internal node in the Sparse Merkle Tree. -// ( -// SparseMerkleInternalHasher, -// SPARSE_MERKLE_INTERNAL_HASHER, -// SPARSE_MERKLE_INTERNAL_SEED, -// b"SparseMerkleInternal" -// ) -// } - -// define_hasher! { -// /// The hasher used to compute the hash of an internal node in the transaction accumulator. -// ( -// VoteProposalHasher, -// VOTE_PROPOSAL_HASHER, -// VOTE_PROPOSAL_SEED, -// b"VoteProposalHasher" -// ) -// } - -// define_hasher! { -// /// The hasher used only for testing. It doesn't have a salt. -// (TestOnlyHasher, TEST_ONLY_HASHER, TEST_ONLY_SEED, b"") -// } - -// fn create_literal_hash(word: &str) -> HashValue { -// let mut s = word.as_bytes().to_vec(); -// assert!(s.len() <= HashValue::LENGTH); -// s.resize(HashValue::LENGTH, 0); -// HashValue::from_slice(&s).expect("Cannot fail") -// } - -// /// Placeholder hash of `Accumulator`. -// pub static ACCUMULATOR_PLACEHOLDER_HASH: Lazy = -// Lazy::new(|| create_literal_hash("ACCUMULATOR_PLACEHOLDER_HASH")); - -// /// Placeholder hash of `SparseMerkleTree`. -// pub static SPARSE_MERKLE_PLACEHOLDER_HASH: Lazy = -// Lazy::new(|| create_literal_hash("SPARSE_MERKLE_PLACEHOLDER_HASH")); - -// /// Block id reserved as the id of parent block of the genesis block. -// pub static PRE_GENESIS_BLOCK_ID: Lazy = -// Lazy::new(|| create_literal_hash("PRE_GENESIS_BLOCK_ID")); - -// /// Genesis block id is used as a parent of the very first block executed by the executor. -// pub static GENESIS_BLOCK_ID: Lazy = Lazy::new(|| { -// // This maintains the invariant that block.id() == block.hash(), for -// // the genesis block and allows us to (de/)serialize it consistently -// HashValue::new([ -// 0x5e, 0x10, 0xba, 0xd4, 0x5b, 0x35, 0xed, 0x92, 0x9c, 0xd6, 0xd2, 0xc7, 0x09, 0x8b, 0x13, -// 0x5d, 0x02, 0xdd, 0x25, 0x9a, 0xe8, 0x8a, 0x8d, 0x09, 0xf4, 0xeb, 0x5f, 0xba, 0xe9, 0xa6, -// 0xf6, 0xe4, -// ]) -// }); - -// /// Provides a test_only_hash() method that can be used in tests on types that implement -// /// `serde::Serialize`. -// /// -// /// # Example -// /// ``` -// /// use diem_crypto::hash::TestOnlyHash; -// /// -// /// b"hello world".test_only_hash(); -// /// ``` -// pub trait TestOnlyHash { -// /// Generates a hash used only for tests. -// fn test_only_hash(&self) -> HashValue; -// } - -// impl TestOnlyHash for T { -// fn test_only_hash(&self) -> HashValue { -// let bytes = bcs::to_bytes(self).expect("serialize failed during hash."); -// let mut hasher = TestOnlyHasher::default(); -// hasher.update(&bytes); -// hasher.finish() -// } -// } +impl std::iter::ExactSizeIterator for HashValueBitIterator<'_> {} diff --git a/compatibility/src/version_five/state_snapshot_v5.rs b/compatibility/src/version_five/state_snapshot_v5.rs index 8849bc12f..05250ef9c 100644 --- a/compatibility/src/version_five/state_snapshot_v5.rs +++ b/compatibility/src/version_five/state_snapshot_v5.rs @@ -45,9 +45,8 @@ pub struct AccountStateBlobRecord(HashValueV5, AccountStateBlob); ////// SNAPSHOT FILE IO ////// /// read snapshot manifest file into struct pub fn v5_read_from_snapshot_manifest(path: &Path) -> Result { - let config = std::fs::read_to_string(path).map_err(|e| { - format!("Error: cannot read file {:?}, error: {:?}", &path, &e); - e + let config = std::fs::read_to_string(path).inspect_err(|e| { + format!("Error: cannot read file {:?}, error: {:?}", &path, e); })?; let map: StateSnapshotBackupV5 = serde_json::from_str(&config)?; diff --git a/compatibility/src/version_five/transaction_manifest_v5.rs b/compatibility/src/version_five/transaction_manifest_v5.rs index 7a35ec535..d3d59a8fe 100644 --- a/compatibility/src/version_five/transaction_manifest_v5.rs +++ b/compatibility/src/version_five/transaction_manifest_v5.rs @@ -78,9 +78,8 @@ impl TransactionBackup { ////// TX FILES IO ////// /// read tx manifest file into struct pub fn v5_read_from_transaction_manifest(path: &Path) -> Result { - let config = std::fs::read_to_string(path).map_err(|e| { - format!("Error: cannot read file {:?}, error: {:?}", &path, &e); - e + let config = std::fs::read_to_string(path).inspect_err(|e| { + format!("Error: cannot read file {:?}, error: {:?}", &path, e); })?; let map: TransactionBackup = serde_json::from_str(&config)?; diff --git a/framework/cached-packages/src/libra_framework_sdk_builder.rs b/framework/cached-packages/src/libra_framework_sdk_builder.rs index 3c4909b23..908c6ad70 100644 --- a/framework/cached-packages/src/libra_framework_sdk_builder.rs +++ b/framework/cached-packages/src/libra_framework_sdk_builder.rs @@ -94,8 +94,7 @@ pub enum EntryFunctionCall { /// Generic authentication key rotation function that allows the user to rotate their authentication key from any scheme to any scheme. /// To authorize the rotation, we need two signatures: - /// - the first signature `cap_rotate_key` refers to the signature by the account owner's current key on a valid `RotationProofChallenge`, - /// demonstrating that the user intends to and has the capability to rotate the authentication key of this account; + /// - the first signature `cap_rotate_key` refers to the signature by the account owner's current key on a valid `RotationProofChallenge`,demonstrating that the user intends to and has the capability to rotate the authentication key of this account; /// - the second signature `cap_update_table` refers to the signature by the new key (that the account owner wants to rotate to) on a /// valid `RotationProofChallenge`, demonstrating that the user owns the new private key, and has the authority to update the /// `OriginatingAddress` map with the new address mapping ``. @@ -1043,14 +1042,11 @@ pub fn account_revoke_signer_capability( /// `OriginatingAddress` map with the new address mapping ``. /// To verify these two signatures, we need their corresponding public key and public key scheme: we use `from_scheme` and `from_public_key_bytes` /// to verify `cap_rotate_key`, and `to_scheme` and `to_public_key_bytes` to verify `cap_update_table`. -/// A scheme of 0 refers to an Ed25519 key and a scheme of 1 refers to Multi-Ed25519 keys. -/// `originating address` refers to an account's original/first address. -/// +/// A scheme of 0 refers to an Ed25519 key and a scheme of 1 refers to Multi-Ed25519 keys. `originating address` refers to an account's original/first address. /// Here is an example attack if we don't ask for the second signature `cap_update_table`: /// Alice has rotated her account `addr_a` to `new_addr_a`. As a result, the following entry is created, to help Alice when recovering her wallet: /// `OriginatingAddress[new_addr_a]` -> `addr_a` -/// Alice has had bad day: her laptop blew up and she needs to reset her account on a new one. -/// (Fortunately, she still has her secret key `new_sk_a` associated with her new address `new_addr_a`, so she can do this.) +/// Alice has had bad day: her laptop blew up and she needs to reset her account on a new one. (Fortunately, she still has her secret key `new_sk_a` associated with her new address `new_addr_a`, so she can do this.) /// /// But Bob likes to mess with Alice. /// Bob creates an account `addr_b` and maliciously rotates it to Alice's new address `new_addr_a`. Since we are no longer checking a PoK, diff --git a/framework/src/framework_cli.rs b/framework/src/framework_cli.rs index 892816f40..aff594896 100644 --- a/framework/src/framework_cli.rs +++ b/framework/src/framework_cli.rs @@ -124,7 +124,7 @@ impl GovernanceScript { } println!("A governance script dir does not exist here."); if dialoguer::Confirm::new() - .with_prompt(&format!( + .with_prompt(format!( "create a script template at {:?}", &self.script_dir.display() )) diff --git a/tools/genesis/src/wizard.rs b/tools/genesis/src/wizard.rs index cfe06fe3c..542f82e35 100644 --- a/tools/genesis/src/wizard.rs +++ b/tools/genesis/src/wizard.rs @@ -321,7 +321,7 @@ impl GenesisWizard { fn _download_snapshot(&mut self, _app_cfg: &AppCfg) -> anyhow::Result { if let Some(e) = self.epoch { if !Confirm::new() - .with_prompt(&format!("So are we migrating data from epoch {}?", e)) + .with_prompt(format!("So are we migrating data from epoch {}?", e)) .interact() .unwrap() { diff --git a/tools/storage/src/read_snapshot.rs b/tools/storage/src/read_snapshot.rs index 4b09dd2b3..9c1d1115a 100644 --- a/tools/storage/src/read_snapshot.rs +++ b/tools/storage/src/read_snapshot.rs @@ -1,5 +1,5 @@ //! read-archive -use anyhow::{anyhow, Error, Result}; +use anyhow::{anyhow, Context, Error, Result}; use diem_backup_cli::{ backup_types::{ epoch_ending::manifest::EpochEndingBackup, state_snapshot::manifest::StateSnapshotBackup, @@ -27,10 +27,8 @@ use tokio::{fs::OpenOptions, io::AsyncRead}; ////// SNAPSHOT FILE IO ////// /// read snapshot manifest file into object pub fn load_snapshot_manifest(path: &Path) -> Result { - let config = std::fs::read_to_string(path).map_err(|e| { - format!("Error: cannot read file {:?}, error: {:?}", &path, &e); - e - })?; + let config = + std::fs::read_to_string(path).context(format!("Error: cannot read file at {:?}", path))?; let map: StateSnapshotBackup = serde_json::from_str(&config)?; diff --git a/tools/storage/src/read_tx_chunk.rs b/tools/storage/src/read_tx_chunk.rs index cc321516a..f8786e448 100644 --- a/tools/storage/src/read_tx_chunk.rs +++ b/tools/storage/src/read_tx_chunk.rs @@ -1,6 +1,6 @@ use std::path::Path; -use anyhow::{anyhow, Result}; +use anyhow::{anyhow, Context, Result}; use diem_backup_cli::backup_types::transaction::manifest::TransactionBackup; use diem_backup_cli::backup_types::transaction::manifest::TransactionChunk; @@ -13,10 +13,7 @@ use libra_backwards_compatibility::version_five::state_snapshot_v5::open_for_rea /// read snapshot manifest file into object pub fn load_tx_chunk_manifest(path: &Path) -> anyhow::Result { - let s = std::fs::read_to_string(path).map_err(|e| { - format!("Error: cannot read file {:?}, error: {:?}", &path, &e); - e - })?; + let s = std::fs::read_to_string(path).context(format!("Error: cannot read file at {:?}", path))?; let map: TransactionBackup = serde_json::from_str(&s)?; diff --git a/tools/wallet/src/core/mnemonic.rs b/tools/wallet/src/core/mnemonic.rs index a0c0341c7..6aee3d5df 100644 --- a/tools/wallet/src/core/mnemonic.rs +++ b/tools/wallet/src/core/mnemonic.rs @@ -222,7 +222,7 @@ impl U11BitWriter { const MASKS: [u16; 8] = [0, 0b1, 0b11, 0b111, 0b1111, 0b11111, 0b11_1111, 0b111_1111]; // TODO: update this to hashmap or trie. -const WORDS: [&str; 2048] = [ +static WORDS: [&str; 2048] = [ "abandon", "ability", "able", "about", "above", "absent", "absorb", "abstract", "absurd", "abuse", "access", "accident", "account", "accuse", "achieve", "acid", "acoustic", "acquire", "across", "act", "action", "actor", "actress", "actual", "adapt", "add", "addict", "address", diff --git a/tools/wallet/src/keys.rs b/tools/wallet/src/keys.rs index 5b2c8d478..782c678d1 100644 --- a/tools/wallet/src/keys.rs +++ b/tools/wallet/src/keys.rs @@ -219,7 +219,6 @@ pub fn generate_key_objects_from_legacy( } /// Testing deterministic hkdf for bls - fn bls_generate_key(ikm: &[u8]) -> anyhow::Result { let priv_key = blst::min_pk::SecretKey::key_gen(ikm, &[]) .map_err(|e| anyhow!("blst key gen failed: {:?}", e))?;