diff --git a/cli/src/commands/node/mod.rs b/cli/src/commands/node/mod.rs index 18468b822..b482050c4 100644 --- a/cli/src/commands/node/mod.rs +++ b/cli/src/commands/node/mod.rs @@ -35,7 +35,7 @@ use openmina_node_native::{http_server, tracing, NodeService, P2pTaskSpawner, Rp // old: // 3c41383994b87449625df91769dff7b507825c064287d30fada9286f3f1cb15e -const CHAIN_ID: &'static str = openmina_core::CHAIN_ID; +const CHAIN_ID: &str = openmina_core::CHAIN_ID; /// Openmina node #[derive(Debug, clap::Args)] diff --git a/cli/src/commands/replay/replay_state_with_input_actions.rs b/cli/src/commands/replay/replay_state_with_input_actions.rs index 75995eb7a..1079dc4a2 100644 --- a/cli/src/commands/replay/replay_state_with_input_actions.rs +++ b/cli/src/commands/replay/replay_state_with_input_actions.rs @@ -47,7 +47,7 @@ impl ReplayStateWithInputActions { // index/srs doesn't match deserialized one. state.snark.block_verify.verifier_index = node::snark::get_verifier_index(VerifierKind::Blockchain).into(); - state.snark.block_verify.verifier_srs = node::snark::get_srs().into(); + state.snark.block_verify.verifier_srs = node::snark::get_srs(); state }; @@ -203,7 +203,7 @@ fn dyn_effects(store: &mut Store, action: &ActionWithMeta) { } thread_local! { - static DYN_EFFECTS_LIB: RefCell> = RefCell::new(None); + static DYN_EFFECTS_LIB: RefCell> = const { RefCell::new(None) }; } struct DynEffectsLib { diff --git a/core/src/block/block_with_hash.rs b/core/src/block/block_with_hash.rs index 7b559e1d9..a66a12cf6 100644 --- a/core/src/block/block_with_hash.rs +++ b/core/src/block/block_with_hash.rs @@ -156,16 +156,14 @@ impl> BlockWithHash { } } } - match diff.1.as_ref() { - Some(v) => match &v.coinbase { - StagedLedgerDiffDiffPreDiffWithAtMostOneCoinbaseStableV2Coinbase::Zero => {} - StagedLedgerDiffDiffPreDiffWithAtMostOneCoinbaseStableV2Coinbase::One(v) => { - coinbases.push(v.as_ref()); - } - }, - _ => {} + if let Some(v) = diff.1.as_ref() { + if let StagedLedgerDiffDiffPreDiffWithAtMostOneCoinbaseStableV2Coinbase::One(coinbase) = + &v.coinbase + { + coinbases.push(coinbase.as_ref()); + } } - coinbases.into_iter().filter_map(|v| v) + coinbases.into_iter().flatten() } pub fn completed_works_iter<'a>( @@ -198,7 +196,7 @@ impl> BlockHeaderWithHash { } pub fn header(&self) -> &BlockHeader { - &self.header.as_ref() + self.header.as_ref() } pub fn consensus_state(&self) -> &ConsensusProofOfStakeDataConsensusStateValueStableV2 { diff --git a/core/src/consensus.rs b/core/src/consensus.rs index 1e0b31dda..6ec484c4e 100644 --- a/core/src/consensus.rs +++ b/core/src/consensus.rs @@ -53,7 +53,7 @@ pub fn is_short_range_fork(a: &MinaConsensusState, b: &MinaConsensusState) -> bo a_prev_lock_checkpoint == b_prev_lock_checkpoint } else { // Check for previous epoch case using both orientations - check(&a, &b) || check(&b, &a) + check(a, b) || check(b, a) } } @@ -85,6 +85,9 @@ pub fn relative_min_window_density(b1: &MinaConsensusState, b2: &MinaConsensusSt // Ring-shift let mut i = relative_sub_window_from_global_slot(global_slot(b1)); + // TODO(binier): is this correct? + // lint: this loops only once with `_` being `0..=shift_count` + #[allow(clippy::single_element_loop)] for _ in [0..=shift_count] { i = (i + 1) % SUB_WINDOWS_PER_WINDOW; projected_window[i as usize] = 0; @@ -121,7 +124,7 @@ pub fn short_range_fork_take( let tip_height = &tip_cs.blockchain_length; let candidate_height = &candidate_cs.blockchain_length; - match candidate_height.cmp(&tip_height) { + match candidate_height.cmp(tip_height) { Greater => return (true, ChainLength), Less => return (false, ChainLength), Equal => {} @@ -136,9 +139,9 @@ pub fn short_range_fork_take( } if candidate_hash > tip_hash { - return (true, StateHash); + (true, StateHash) } else { - return (false, StateHash); + (false, StateHash) } } @@ -161,7 +164,7 @@ pub fn long_range_fork_take( let tip_height = &tip_cs.blockchain_length; let candidate_height = &candidate_cs.blockchain_length; - match candidate_height.cmp(&tip_height) { + match candidate_height.cmp(tip_height) { Greater => return (true, ChainLength), Less => return (false, ChainLength), Equal => {} @@ -176,9 +179,9 @@ pub fn long_range_fork_take( } if candidate_hash > tip_hash { - return (true, StateHash); + (true, StateHash) } else { - return (false, StateHash); + (false, StateHash) } } diff --git a/core/src/constants.rs b/core/src/constants.rs index d05a63c34..1e8d61378 100644 --- a/core/src/constants.rs +++ b/core/src/constants.rs @@ -2,8 +2,7 @@ use binprot_derive::BinProtWrite; use mina_hasher::Fp; use mina_p2p_messages::{bigint, number, v2}; -pub const GENESIS_PRODUCER_SK: &'static str = - "EKFKgDtU3rcuFTVSEpmpXSkukjmX4cKefYREi6Sdsk7E7wsT7KRw"; +pub const GENESIS_PRODUCER_SK: &str = "EKFKgDtU3rcuFTVSEpmpXSkukjmX4cKefYREi6Sdsk7E7wsT7KRw"; pub const PROTOCOL_VERSION: v2::ProtocolVersionStableV2 = v2::ProtocolVersionStableV2 { transaction: number::Number(2), diff --git a/core/src/invariants.rs b/core/src/invariants.rs index 266a34337..3ab2861ee 100644 --- a/core/src/invariants.rs +++ b/core/src/invariants.rs @@ -8,13 +8,13 @@ pub trait InvariantService: redux::Service { pub struct InvariantsState(Vec>); impl InvariantsState { - pub fn get<'a, T: 'static + Send + Default>(&'a mut self, i: usize) -> &'a mut T { + pub fn get(&mut self, i: usize) -> &mut T { self.0.resize_with(i + 1, || Box::new(())); let v = self.0.get_mut(i).unwrap(); if v.is::() { v.downcast_mut().unwrap() } else { - *v = Box::new(T::default()); + *v = Box::::default(); v.downcast_mut().unwrap() } } diff --git a/core/src/lib.rs b/core/src/lib.rs index 1053fcb30..6a72835aa 100644 --- a/core/src/lib.rs +++ b/core/src/lib.rs @@ -1,3 +1,5 @@ +#![allow(clippy::too_many_arguments)] + pub mod invariants; pub mod log; pub mod requests; @@ -13,8 +15,7 @@ pub mod snark; pub mod consensus; /// Default chain id, as used by [berkeleynet](https://berkeley.minaexplorer.com/status). -pub const CHAIN_ID: &'static str = - "fd7d111973bf5a9e3e87384f560fdead2f272589ca00b6d9e357fca9839631da"; +pub const CHAIN_ID: &str = "fd7d111973bf5a9e3e87384f560fdead2f272589ca00b6d9e357fca9839631da"; pub fn preshared_key(chain_id: &str) -> [u8; 32] { use multihash::{Blake2b256, Hasher}; diff --git a/core/src/requests/mod.rs b/core/src/requests/mod.rs index de21675fb..df46fb40b 100644 --- a/core/src/requests/mod.rs +++ b/core/src/requests/mod.rs @@ -144,7 +144,7 @@ where use serde::de::{self, MapAccess, SeqAccess, Visitor}; struct RequestsVisitor(std::marker::PhantomData<(IdType, Request)>); - const FIELDS: &'static [&'static str] = &["list", "counter", "last_added_req_id"]; + const FIELDS: &[&str] = &["list", "counter", "last_added_req_id"]; impl<'de, IdType, Request> Visitor<'de> for RequestsVisitor where diff --git a/core/src/requests/request_id.rs b/core/src/requests/request_id.rs index 20127bab0..5c85e1bd7 100644 --- a/core/src/requests/request_id.rs +++ b/core/src/requests/request_id.rs @@ -138,11 +138,7 @@ impl fmt::Debug for RequestId { impl Clone for RequestId { fn clone(&self) -> Self { - Self { - locator: self.locator, - counter: self.counter, - _phantom_request_type: self._phantom_request_type.clone(), - } + *self } } diff --git a/core/src/snark/snark_cmp.rs b/core/src/snark/snark_cmp.rs index 9aaa84d75..4f9892eb1 100644 --- a/core/src/snark/snark_cmp.rs +++ b/core/src/snark/snark_cmp.rs @@ -71,7 +71,7 @@ where for<'a> &'a T: Into>, { fn eq(&self, other: &T) -> bool { - Into::>::into(&*self) == Into::>::into(other) + Into::>::into(self) == Into::>::into(other) } } diff --git a/core/src/snark/snark_job_id.rs b/core/src/snark/snark_job_id.rs index a24ac9d4f..45435104a 100644 --- a/core/src/snark/snark_job_id.rs +++ b/core/src/snark/snark_job_id.rs @@ -36,7 +36,7 @@ impl std::str::FromStr for LedgerHashTransition { type Err = (); fn from_str(s: &str) -> Result { - let (source, target) = s.split_once("-").ok_or(())?; + let (source, target) = s.split_once('-').ok_or(())?; Ok(Self { source: source.parse()?, target: target.parse()?, @@ -58,7 +58,7 @@ impl FromStr for LedgerHashTransitionPasses { type Err = (); fn from_str(s: &str) -> Result { - let (first_pass, second_pass) = s.split_once("_").ok_or(())?; + let (first_pass, second_pass) = s.split_once('_').ok_or(())?; Ok(Self { first_pass_ledger: first_pass.parse().or(Err(()))?, second_pass_ledger: second_pass.parse().or(Err(()))?, diff --git a/ledger/src/account/common.rs b/ledger/src/account/common.rs index 9e8c95d87..ee98b2fb8 100644 --- a/ledger/src/account/common.rs +++ b/ledger/src/account/common.rs @@ -278,7 +278,7 @@ impl AuthRequired { match self { Impossible | Proof => Signature, - x => x.clone(), + x => *x, } } } diff --git a/ledger/src/account/conv.rs b/ledger/src/account/conv.rs index 818e8d472..ecb3d35ba 100644 --- a/ledger/src/account/conv.rs +++ b/ledger/src/account/conv.rs @@ -123,7 +123,7 @@ where T: 'a, F: Fn(&T) -> U, { - value.each_ref().map(|value| fun(value)) + value.each_ref().map(fun) } impl From<&MinaBaseVerificationKeyWireStableV1> for VerificationKey { @@ -501,8 +501,8 @@ impl From<&MinaBaseAccountBinableArgStableV2> for Account { let s: String = (&acc.token_symbol).try_into().unwrap(); TokenSymbol::from(s) }, - balance: Balance::from_u64(acc.balance.0 .0 .0 .0 as u64), - nonce: Nonce::from_u32(acc.nonce.0 .0 as u32), + balance: Balance::from_u64(acc.balance.0 .0 .0 .0), + nonce: Nonce::from_u32(acc.nonce.0 .0), receipt_chain_hash: ReceiptChainHash((&acc.receipt_chain_hash.0).into()), delegate: acc.delegate.as_ref().map(|d| d.inner().into()), voting_for: VotingFor(acc.voting_for.0.to_field()), diff --git a/ledger/src/address/raw.rs b/ledger/src/address/raw.rs index 3fcd58c22..450073fc7 100644 --- a/ledger/src/address/raw.rs +++ b/ledger/src/address/raw.rs @@ -330,7 +330,7 @@ impl Address { .rev() .enumerate() .find_map(|(index, byte)| match byte.trailing_ones() as usize { - x if x == 8 => None, + 8 => None, x => Some((nused_bytes - index) * 8 - x - 1), })?; @@ -361,7 +361,7 @@ impl Address { .rev() .enumerate() .find_map(|(index, byte)| match byte.trailing_zeros() as usize { - x if x == 8 => None, + 8 => None, x => Some((nused_bytes - index) * 8 - x - 1), })?; diff --git a/ledger/src/database/database.rs b/ledger/src/database/database.rs index f2380b67e..7b1202c63 100644 --- a/ledger/src/database/database.rs +++ b/ledger/src/database/database.rs @@ -1003,7 +1003,7 @@ mod tests_ocaml { let index = rand::thread_rng().gen_range(0..NACCOUNTS); let index = AccountIndex(index as u64); - db.set_at_index(index.clone(), account.clone()).unwrap(); + db.set_at_index(index, account.clone()).unwrap(); let at_index = db.get_at_index(index).unwrap(); assert_eq!(account, at_index); } diff --git a/ledger/src/database/database_impl.rs b/ledger/src/database/database_impl.rs index 0207085d2..61d08b684 100644 --- a/ledger/src/database/database_impl.rs +++ b/ledger/src/database/database_impl.rs @@ -667,7 +667,7 @@ impl BaseLedger for DatabaseImpl { fn set(&mut self, addr: Address, account: Box) { let index = addr.to_index(); - self.hashes_matrix.invalidate_hashes(index.clone()); + self.hashes_matrix.invalidate_hashes(index); let index: usize = index.0 as usize; diff --git a/ledger/src/mask/mask_impl.rs b/ledger/src/mask/mask_impl.rs index 6e13b9ffd..675630747 100644 --- a/ledger/src/mask/mask_impl.rs +++ b/ledger/src/mask/mask_impl.rs @@ -392,7 +392,7 @@ impl MaskImpl { }; for (index, account) in accounts { - let addr = Address::from_index(index.clone(), depth); + let addr = Address::from_index(index, depth); parent.set_impl(addr, Box::new(account), Some(self_uuid.clone())); } @@ -439,7 +439,7 @@ impl MaskImpl { assert!(self.is_attached()); for child in self.childs().values() { - child.parent_set_notify(account_index.clone(), account) + child.parent_set_notify(account_index, account) } match self { @@ -455,12 +455,11 @@ impl MaskImpl { hashes.invalidate_hashes(account_index); - let own_account = match { - id_to_addr - .get(&account_id) - .and_then(|addr| owning_account.get(&addr.to_index())) - .cloned() - } { + let own_account = match id_to_addr + .get(&account_id) + .and_then(|addr| owning_account.get(&addr.to_index())) + .cloned() + { Some(own) => own, None => return, }; @@ -812,7 +811,7 @@ impl MaskImpl { for addr in addrs.iter().rev() { let account_index = addr.to_index(); - hashes.invalidate_hashes(account_index.clone()); + hashes.invalidate_hashes(account_index); let account = owning_account.remove(&account_index).unwrap(); token_to_account.remove(&account.token_id).unwrap(); @@ -845,7 +844,7 @@ impl MaskImpl { if Some(uuid) == child_to_ignore.as_ref() { continue; } - child.parent_set_notify(account_index.clone(), &account) + child.parent_set_notify(account_index, &account) } match self { @@ -867,7 +866,7 @@ impl MaskImpl { let account_id = account.id(); let token_id = account.token_id.clone(); - owning_account.insert(account_index.clone(), *account); + owning_account.insert(account_index, *account); id_to_addr.insert(account_id.clone(), addr.clone()); token_to_account.insert(token_id, account_id); @@ -937,7 +936,7 @@ impl MaskImpl { for index in 0..(2u64.pow(tree_depth as u32)) { let index = AccountIndex(index); match self - .get_account_hash(index.clone()) + .get_account_hash(index) .filter(|hash| hash != &empty_account_hash) { None => break, @@ -1200,7 +1199,7 @@ impl BaseLedger for MaskImpl { id_to_addr.insert(account_id.clone(), location.clone()); *last_location = Some(location.clone()); token_to_account.insert(token_id, account_id); - owning_account.insert(account_index.clone(), account); + owning_account.insert(account_index, account); self.invalidate_hashes(account_index); @@ -1434,7 +1433,7 @@ impl BaseLedger for MaskImpl { self.recurse_on_childs(&mut |child| { for index in &indexes { - child.invalidate_hashes(index.clone()); + child.invalidate_hashes(*index); } }); } diff --git a/ledger/src/ondisk/mod.rs b/ledger/src/ondisk/mod.rs index df349a376..c8367392e 100644 --- a/ledger/src/ondisk/mod.rs +++ b/ledger/src/ondisk/mod.rs @@ -55,9 +55,9 @@ //! ``` pub mod batch; -pub(self) mod compression; +mod compression; mod database; -pub(self) mod lock; +mod lock; pub use batch::Batch; pub use database::*; diff --git a/ledger/src/proofs/block.rs b/ledger/src/proofs/block.rs index 557076c62..a0e9d3a8d 100644 --- a/ledger/src/proofs/block.rs +++ b/ledger/src/proofs/block.rs @@ -657,7 +657,7 @@ mod vrf { let account = { let mut ledger: SparseLedger = (&prover_state.ledger).into(); - let staker_addr = message.delegator.clone(); + let staker_addr = message.delegator; let staker_addr = Address::from_index(staker_addr, CONSTRAINT_CONSTANTS.ledger_depth as usize); @@ -935,7 +935,7 @@ pub mod consensus { ) -> Self { Self { slot_number, - slots_per_epoch: constants.slots_per_epoch.clone(), + slots_per_epoch: constants.slots_per_epoch, } } @@ -1099,7 +1099,7 @@ pub mod consensus { let density = Length::from_u32(*density).to_checked::(); - let on_true = density.clone(); + let on_true = density; let on_false = { let cond = overlapping_window.and(&within_range.neg(), w); w.exists_no_check(match cond { @@ -1136,7 +1136,7 @@ pub mod consensus { let prev_min_window_density = Length::from_u32(prev_min_window_density).to_checked(); let cond = same_sub_window.or(&in_grace_period, w); - let on_true = prev_min_window_density.clone(); + let on_true = prev_min_window_density; let on_false = current_window_density.min(&prev_min_window_density, w); w.exists_no_check(match cond { @@ -1160,7 +1160,7 @@ pub mod consensus { w.exists_no_check(match is_next_sub_window { Boolean::True => on_true, - Boolean::False => density.clone(), + Boolean::False => *density, }) }) .collect::>(); @@ -1224,7 +1224,7 @@ pub mod consensus { let slot_diff = next_global_slot.diff_slots(&prev_global_slot, w); - let _ = { + { let global_slot_increased = prev_global_slot.less_than(&next_global_slot, w); let is_genesis = field::equal( CheckedSlot::zero().to_field(), @@ -1254,7 +1254,7 @@ pub mod consensus { }) }; - let next_slot_number = next_global_slot.slot_number.clone(); + let next_slot_number = next_global_slot.slot_number; let block_stake_winner = { let delegator_pk: CompressedPubKey = (&prover_state.delegator_pk).into(); diff --git a/ledger/src/proofs/caching.rs b/ledger/src/proofs/caching.rs index b19593122..e926620ba 100644 --- a/ledger/src/proofs/caching.rs +++ b/ledger/src/proofs/caching.rs @@ -333,7 +333,7 @@ impl From<&VerifierIndex> for VerifierIndexCached { w: (*w.get().unwrap()).into(), endo: endo.into(), lookup_index: lookup_index.clone(), - linearization: conv_linearization(&linearization), + linearization: conv_linearization(linearization), } } } @@ -389,7 +389,7 @@ impl From<&VerifierIndexCached> for VerifierIndex { w: OnceCell::with_value(w.to_field()), endo: endo.to_field(), lookup_index: lookup_index.clone(), - linearization: conv_linearization(&linearization), + linearization: conv_linearization(linearization), powers_of_alpha: { // `Alphas` contains private data, so we can't de/serialize it. // Initializing an `Alphas` is cheap anyway (for block verification). diff --git a/ledger/src/proofs/group_map.rs b/ledger/src/proofs/group_map.rs index b3251c1e7..56ab85c7f 100644 --- a/ledger/src/proofs/group_map.rs +++ b/ledger/src/proofs/group_map.rs @@ -30,7 +30,7 @@ pub mod bw19 { loop { match f(v) { Some(x) => return x, - None => v = v + one, + None => v += one, } } } @@ -105,8 +105,7 @@ use super::field::{Boolean, GroupAffine, ToBoolean}; use super::transaction::make_group; fn sqrt_exn(x: F, w: &mut Witness) -> F { - let y = w.exists(x.sqrt().unwrap()); - y + w.exists(x.sqrt().unwrap()) } fn is_square(x: F) -> bool { diff --git a/ledger/src/proofs/numbers/currency.rs b/ledger/src/proofs/numbers/currency.rs index ce9195de4..810190604 100644 --- a/ledger/src/proofs/numbers/currency.rs +++ b/ledger/src/proofs/numbers/currency.rs @@ -408,7 +408,7 @@ impl CheckedBalance { d: CheckedSigned>, w: &mut Witness, ) -> Self { - let d = CheckedSigned::::create(Self(d.magnitude.0), d.sgn, d.value.get().clone()); + let d = CheckedSigned::::create(Self(d.magnitude.0), d.sgn, d.value.get()); self.add_signed(d, w) } @@ -435,7 +435,7 @@ impl CheckedBalance { let amount = CheckedSigned::::create( Self(amount.magnitude.0), amount.sgn, - amount.value.get().clone(), + amount.value.get(), ); self.add_signed_flagged(amount, w) } diff --git a/ledger/src/proofs/opt_sponge.rs b/ledger/src/proofs/opt_sponge.rs index 43f447ebf..03824fb4e 100644 --- a/ledger/src/proofs/opt_sponge.rs +++ b/ledger/src/proofs/opt_sponge.rs @@ -106,7 +106,7 @@ impl OptSponge { SpongeState::Squeezed(n) => { let n = *n; if n == RATE { - self.state = block_cipher(self.state, &self.params, w); + self.state = block_cipher(self.state, self.params, w); self.sponge_state = SpongeState::Squeezed(1); self.state[0] } else { @@ -120,7 +120,7 @@ impl OptSponge { needs_final_permute_if_empty: self.needs_final_permute_if_empty, start_pos: CircuitVar::Constant(*next_index), params: self.params, - input: &xs, + input: xs, state: self.state, }, w, @@ -236,15 +236,15 @@ fn consume(params: ConsumeParams, w: &mut Witness) -> [F; // Note: It's Boolean.Array.any here, not sure if there is a difference let empty_input = CircuitVar::any(&fst_input, w).map(Boolean::neg); - let should_permute = match by_pairs.remainder() { - &[] => { + let should_permute = match *by_pairs.remainder() { + [] => { if needs_final_permute_if_empty { empty_input.or(&pos, w) } else { pos } } - &[(b, x)] => { + [(b, x)] => { let p = pos; pos = p.lxor(&b, w); @@ -287,7 +287,7 @@ fn full_round( for state_i in state.iter_mut() { *state_i = sbox::(*state_i); } - *state = apply_mds_matrix::(params, &state); + *state = apply_mds_matrix::(params, state); for (i, x) in params.round_constants[r].iter().enumerate() { state[i].add_assign(x); } diff --git a/ledger/src/proofs/public_input/plonk_checks.rs b/ledger/src/proofs/public_input/plonk_checks.rs index 687ece75c..1afdf2898 100644 --- a/ledger/src/proofs/public_input/plonk_checks.rs +++ b/ledger/src/proofs/public_input/plonk_checks.rs @@ -577,10 +577,7 @@ mod scalars { fn is_const(e: &Expr>) -> bool { use ConstantExpr::*; match e { - Expr::Constant(c) => match c { - EndoCoefficient | Literal(_) | Mds { .. } => true, - _ => false, - }, + Expr::Constant(c) => matches!(c, EndoCoefficient | Literal(_) | Mds { .. }), Expr::BinOp(_, x, y) => is_const(x) && is_const(y), Expr::Pow(x, _) => is_const(x), _ => false, @@ -605,15 +602,15 @@ mod scalars { let p = *p; let v = eval(x, ctx); - if is_const(&x) { + if is_const(x) { pow_const(v, p) } else { pow(v, p, ctx.w) } } BinOp(Op2::Mul, x, y) => { - let is_x_const = is_const(&x); - let is_y_const = is_const(&y); + let is_x_const = is_const(x); + let is_y_const = is_const(y); let y = eval(y, ctx); let x = eval(x, ctx); if is_x_const || is_y_const { @@ -623,7 +620,7 @@ mod scalars { } } Square(x) => { - let is_x_const = is_const(&x); + let is_x_const = is_const(x); let x = eval(x, ctx); if is_x_const { x * x @@ -711,7 +708,7 @@ mod scalars { Cache(id, e) => { let mut cached = Cached::default(); extract_caches(e, &mut cached); - cache.expr.insert(id.clone(), (Box::new(cached), e.clone())); + cache.expr.insert(*id, (Box::new(cached), e.clone())); } IfFeature(_feature, e1, e2) => { if false { @@ -728,7 +725,7 @@ mod scalars { for (id, (cache, expr)) in &cached_exprs.expr { let mut old_cache = std::mem::take(&mut ctx.cache); eval_cache::(cache, ctx); - old_cache.insert(*id, eval::(&expr, ctx)); + old_cache.insert(*id, eval::(expr, ctx)); ctx.cache = old_cache; } } @@ -823,7 +820,7 @@ mod scalars { let term = match gate { Some(gate) => index_terms.get(&Column::Index(gate)).unwrap(), - None => &constant_term, + None => constant_term, }; // We evaluate the cached expressions first diff --git a/ledger/src/proofs/step.rs b/ledger/src/proofs/step.rs index 30bd0c476..f8b2b5b04 100644 --- a/ledger/src/proofs/step.rs +++ b/ledger/src/proofs/step.rs @@ -536,7 +536,7 @@ pub mod step_verifier { (sg_evals1, sg_evals2) }; - let _sponge_state = { + { let challenge_digest = { let ntrim_front = 2 - max_proof_verified; @@ -633,7 +633,7 @@ pub mod step_verifier { }) }; - let srs_length_log2 = COMMON_MAX_DEGREE_STEP_LOG2 as u64; + let srs_length_log2 = COMMON_MAX_DEGREE_STEP_LOG2; let env = make_scalars_env_checked( MakeScalarsEnvParams { minimal: &plonk_mininal, @@ -822,12 +822,11 @@ pub mod step_verifier { let app_state = app_state .to_field_elements_owned() .into_iter() - .map(|v| MaybeOpt::NotOpt(v)); + .map(MaybeOpt::NotOpt); let both = challenge_polynomial_commitments .zip(old_bulletproof_challenges) - .map(|(c, o)| c.into_iter().chain(o.into_iter())) - .flatten(); + .flat_map(|(c, o)| c.into_iter().chain(o)); let sponge = Box::new(sponge); let res = app_state @@ -869,12 +868,12 @@ pub mod step_verifier { let chunks_needed = chunks_needed(s_div_2_bits); let actual_bits_used = chunks_needed * OPS_BITS_PER_CHUNK; - let g_value = g.value().clone(); + let g_value = g.value(); let shifted = F::Shifting::of_raw(s_div_2); let h = match actual_bits_used { - 255 => scale_fast_unpack::(g_value, shifted, w).0, - 130 => scale_fast_unpack::(g_value, shifted, w).0, - 10 => scale_fast_unpack::(g_value, shifted, w).0, + 255 => scale_fast_unpack::(*g_value, shifted, w).0, + 130 => scale_fast_unpack::(*g_value, shifted, w).0, + 10 => scale_fast_unpack::(*g_value, shifted, w).0, n => todo!("{:?} param_num_bits={:?}", n, num_bits), }; @@ -908,12 +907,12 @@ pub mod step_verifier { let chunks_needed = chunks_needed(s_div_2_bits); let actual_bits_used = chunks_needed * OPS_BITS_PER_CHUNK; - let g_value = g.value().clone(); + let g_value = g.value(); let shifted = F::Shifting::of_raw(s_div_2); let h = match actual_bits_used { - 255 => scale_fast_unpack::(g_value, shifted, w).0, - 130 => scale_fast_unpack::(g_value, shifted, w).0, - 10 => scale_fast_unpack::(g_value, shifted, w).0, + 255 => scale_fast_unpack::(*g_value, shifted, w).0, + 130 => scale_fast_unpack::(*g_value, shifted, w).0, + 10 => scale_fast_unpack::(*g_value, shifted, w).0, n => todo!("{:?} param_num_bits={:?}", n, num_bits), }; @@ -1150,7 +1149,7 @@ pub mod step_verifier { let pow2pow = |x: InnerCurve, n: usize| (0..n).fold(x, |acc, _| acc.clone() + acc); let (constant_part, non_constant_part): (Vec<_>, Vec<_>) = - ts.into_iter().partition_map(|(t, g)| { + ts.iter().partition_map(|(t, g)| { use itertools::Either::{Left, Right}; use CircuitVar::Constant; use Packed::{Field, PackedBits}; @@ -1350,7 +1349,7 @@ pub mod step_verifier { xi, &without_degree_bound .into_iter() - .map(|v| Point::Finite(v)) + .map(Point::Finite) .collect::>(), &[], w, @@ -1475,10 +1474,7 @@ pub mod step_verifier { multiscale_known(&ts, w).neg() } ForStepKind::SideLoaded(which) => { - let domains = [0, 1, 2] - .into_iter() - .map(|proofs_verified| wrap_domains(proofs_verified)) - .collect(); + let domains = [0, 1, 2].into_iter().map(wrap_domains).collect(); public_input_commitment_dynamic(which, srs, domains, public_input, w) } }; @@ -1524,7 +1520,7 @@ pub mod step_verifier { const WRAP_HACK_PADDED_LENGTH: usize = 2; const NUM_COMMITMENTS_WITHOUT_DEGREE_BOUND: usize = 45; - let cvar = |v| CircuitVar::Var(v); + let cvar = CircuitVar::Var; let without_degree_bound = { let sg_old = sg_old.iter().copied().map(cvar); @@ -1545,7 +1541,7 @@ pub mod step_verifier { .flat_map(|w| w.unshifted.iter().cloned().map(cvar)), ) .chain(wrap_verification_key.coefficients) - .chain(sigma_comm_init.iter().map(|v| v).cloned()); + .chain(sigma_comm_init.iter().cloned()); sg_old.chain(rest).collect::>() }; @@ -2192,7 +2188,7 @@ fn expand_proof(params: ExpandProofParams) -> ExpandedProof { let challenge_polynomial_commitment = match must_verify.value() { Boolean::False => wrap_compute_sg(&new_bulletproof_challenges), - Boolean::True => proof.proof.sg.clone(), + Boolean::True => proof.proof.sg, }; let witness = PerProofWitness { @@ -2401,10 +2397,10 @@ impl Check for PerProofWitness { } = wrap_proof; for poly in w_comm { - (&poly.unshifted).check(w); + (poly.unshifted).check(w); } - (&z_comm.unshifted).check(w); - (&t_comm.unshifted).check(w); + (z_comm.unshifted).check(w); + (t_comm.unshifted).check(w); lr.check(w); let shift = |f: Fq| ::Shifting::of_field(f); @@ -2675,7 +2671,7 @@ pub fn step( dlog_plonk_index: &dlog_plonk_index, challenge_polynomial_commitments: prevs .iter() - .map(|v| InnerCurve::of_affine(v.wrap_proof.proof.sg.clone())) + .map(|v| InnerCurve::of_affine(v.wrap_proof.proof.sg)) .collect(), old_bulletproof_challenges: bulletproof_challenges, }; @@ -2734,7 +2730,7 @@ pub fn step( let challenge_polynomial_commitments = expanded_proofs .iter() - .map(|v| InnerCurve::of_affine(v.sg.clone())) + .map(|v| InnerCurve::of_affine(v.sg)) .collect(); let (old_bulletproof_challenges, messages_for_next_wrap_proof): (Vec<_>, Vec<_>) = proofs diff --git a/ledger/src/proofs/transaction.rs b/ledger/src/proofs/transaction.rs index 5c0a1cada..aac821de4 100644 --- a/ledger/src/proofs/transaction.rs +++ b/ledger/src/proofs/transaction.rs @@ -476,7 +476,7 @@ pub mod plonk_curve_ops { } let bits_lsb = { - let mut bits_msb = bits_msb.clone(); + let mut bits_msb = bits_msb; bits_msb.reverse(); bits_msb }; @@ -559,50 +559,15 @@ impl PlonkVerificationKeyEvals { CircuitPlonkVerificationKeyEvals:: { sigma: sigma.each_ref().map(cvar), coefficients: coefficients.each_ref().map(cvar), - generic: cvar(&generic), - psm: cvar(&psm), - complete_add: cvar(&complete_add), - mul: cvar(&mul), - emul: cvar(&emul), - endomul_scalar: cvar(&endomul_scalar), + generic: cvar(generic), + psm: cvar(psm), + complete_add: cvar(complete_add), + mul: cvar(mul), + emul: cvar(emul), + endomul_scalar: cvar(endomul_scalar), } } - /// For debugging - fn to_string(&self) -> String { - let Self { - sigma, - coefficients, - generic, - psm, - complete_add, - mul, - emul, - endomul_scalar, - } = self; - - let mut string = String::with_capacity(1_000); - - use crate::util::FpExt; - - let mut inner_to_s = |c: &InnerCurve| { - let GroupAffine:: { x, y, .. } = c.to_affine(); - string.push_str(&format!("{}\n", x.to_decimal())); - string.push_str(&format!("{}\n", y.to_decimal())); - }; - - sigma.iter().for_each(|c| inner_to_s(c)); - coefficients.iter().for_each(|c| inner_to_s(c)); - inner_to_s(generic); - inner_to_s(psm); - inner_to_s(complete_add); - inner_to_s(mul); - inner_to_s(emul); - inner_to_s(endomul_scalar); - - string.trim().to_string() - } - /// For debugging fn from_string(s: &str) -> Self { let mut s = s.lines(); @@ -667,6 +632,43 @@ impl PlonkVerificationKeyEvals { } } +/// For debugging +impl std::fmt::Display for PlonkVerificationKeyEvals { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + let Self { + sigma, + coefficients, + generic, + psm, + complete_add, + mul, + emul, + endomul_scalar, + } = self; + + let mut string = String::with_capacity(1_000); + + use crate::util::FpExt; + + let mut inner_to_s = |c: &InnerCurve| { + let GroupAffine:: { x, y, .. } = c.to_affine(); + string.push_str(&format!("{}\n", x.to_decimal())); + string.push_str(&format!("{}\n", y.to_decimal())); + }; + + sigma.iter().for_each(&mut inner_to_s); + coefficients.iter().for_each(&mut inner_to_s); + inner_to_s(generic); + inner_to_s(psm); + inner_to_s(complete_add); + inner_to_s(mul); + inner_to_s(emul); + inner_to_s(endomul_scalar); + + write!(f, "{}", string.trim()) + } +} + impl crate::ToInputs for PlonkVerificationKeyEvals { fn to_inputs(&self, inputs: &mut crate::Inputs) { let Self { @@ -686,8 +688,8 @@ impl crate::ToInputs for PlonkVerificationKeyEvals { inputs.append(&y); }; - sigma.iter().for_each(|c| to_input(c)); - coefficients.iter().for_each(|c| to_input(c)); + sigma.iter().for_each(&mut to_input); + coefficients.iter().for_each(&mut to_input); to_input(generic); to_input(psm); to_input(complete_add); @@ -755,7 +757,7 @@ impl Check for mina_signer::Signature { impl> Check for MyCow<'_, T> { fn check(&self, w: &mut Witness) { - let this: &T = &*self; + let this: &T = self; this.check(w); } } @@ -1639,6 +1641,16 @@ pub mod poseidon { _constants: PhantomData, } + impl Default for Sponge + where + F: FieldWitness, + C: SpongeConstants, + { + fn default() -> Self { + Self::new() + } + } + impl Sponge where F: FieldWitness, @@ -2688,7 +2700,7 @@ pub mod transaction_snark { }; w.exists_no_check(match before_cliff { - Boolean::True => initial_minimum_balance.clone(), + Boolean::True => *initial_minimum_balance, Boolean::False => else_value, }) } @@ -2818,7 +2830,7 @@ pub mod transaction_snark { let current_global_slot = global_slot; let user_command_failure = - user_command_failure::compute_as_prover(current_global_slot.clone(), tx, &ledger, w); + user_command_failure::compute_as_prover(current_global_slot, tx, &ledger, w); let user_command_fails = Boolean::any(&user_command_failure.to_list(), w); let fee = payload.common.fee.to_checked(); @@ -2834,11 +2846,8 @@ pub mod transaction_snark { let pending_coinbase_init: pending_coinbase::Stack = pending_coinbase_init.into(); - let pending_coinbase_stack_with_state = pending_coinbase_init.checked_push_state( - state_body_hash, - current_global_slot.clone(), - w, - ); + let pending_coinbase_stack_with_state = + pending_coinbase_init.checked_push_state(state_body_hash, current_global_slot, w); let computed_pending_coinbase_stack_after = { let coinbase = Coinbase { @@ -2856,13 +2865,13 @@ pub mod transaction_snark { }; let _correct_coinbase_target_stack = - computed_pending_coinbase_stack_after.equal_var(&pending_coinbase_after, w); + computed_pending_coinbase_stack_after.equal_var(pending_coinbase_after, w); let _valid_init_state = { - let equal_source = pending_coinbase_init.equal_var(&pending_coinbase_stack_before, w); + let equal_source = pending_coinbase_init.equal_var(pending_coinbase_stack_before, w); let equal_source_with_state = - pending_coinbase_stack_with_state.equal_var(&pending_coinbase_stack_before, w); + pending_coinbase_stack_with_state.equal_var(pending_coinbase_stack_before, w); equal_source.or(&equal_source_with_state, w) }; @@ -3001,7 +3010,7 @@ pub mod transaction_snark { let account_creation_fee = { // We don't use `exists_no_check` here because both are constants let magnitude = if should_pay_to_create.as_bool() { - account_creation_amount.clone() + account_creation_amount } else { CheckedAmount::zero() }; @@ -3026,10 +3035,10 @@ pub mod transaction_snark { burned_tokens = amt; } - let txn_global_slot = current_global_slot.clone(); + let txn_global_slot = current_global_slot; let timing = { let txn_amount = w.exists_no_check(match amount.sgn { - Sgn::Neg => amount.magnitude.clone(), + Sgn::Neg => amount.magnitude, Sgn::Pos => CheckedAmount::zero(), }); @@ -3201,7 +3210,7 @@ pub mod transaction_snark { }; let account_creation_fee_neg = - CheckedSigned::of_unsigned(account_creation_fee.clone()).negate(); + CheckedSigned::of_unsigned(account_creation_fee).negate(); account_creation_fee_neg.set_value(); // We set it because it's a Constant new_account_fees.set_value(); // We set it because it's a Constant @@ -3479,7 +3488,7 @@ pub mod transaction_snark { let else_value = { let amount_fee = CheckedAmount::of_fee(&payload.common.fee.to_checked()); - let user_command_excess = CheckedSigned::of_unsigned(amount_fee.clone()); + let user_command_excess = CheckedSigned::of_unsigned(amount_fee); let (fee_transfer_excess, fee_transfer_excess_overflowed) = { let (magnitude, overflow) = @@ -3496,7 +3505,7 @@ pub mod transaction_snark { Boolean::True => fee_transfer_excess, Boolean::False => user_command_excess, }; - w.exists_no_check(value.magnitude.clone()); + w.exists_no_check(value.magnitude); value }; @@ -3511,8 +3520,8 @@ pub mod transaction_snark { Boolean::True => CheckedSigned::of_unsigned(payload.body.amount.to_checked()), Boolean::False => CheckedSigned::of_unsigned(CheckedAmount::zero()), }; - w.exists_no_check(expected_supply_increase.magnitude.clone()); - w.exists_no_check(expected_supply_increase.magnitude.clone()); + w.exists_no_check(expected_supply_increase.magnitude); + w.exists_no_check(expected_supply_increase.magnitude); let (amt0, _overflow0) = expected_supply_increase .add_flagged(&CheckedSigned::of_unsigned(burned_tokens).negate(), w); @@ -3835,8 +3844,8 @@ pub fn make_prover_index( let prev_challenges = C::PREVIOUS_CHALLENGES; let cs = ConstraintSystem::::create(gates) - .public(public as usize) - .prev_challenges(prev_challenges as usize) + .public(public) + .prev_challenges(prev_challenges) .build() .unwrap(); @@ -3921,7 +3930,7 @@ pub(super) fn create_proof( &group_map, computed_witness, &[], - &prover_index, + prover_index, prev_challenges, None, &mut rng, @@ -4389,8 +4398,8 @@ mod tests { statement: &statement, tx_witness: &tx_witness, message: &message, - tx_step_prover: &tx_step_prover, - tx_wrap_prover: &tx_wrap_prover, + tx_step_prover, + tx_wrap_prover, only_verify_constraints: false, expected_step_proof: None, ocaml_wrap_witness: None, @@ -4504,8 +4513,8 @@ mod tests { statement: (&*statement).into(), proofs: &proofs, message: &message, - step_prover: &merge_step_prover, - wrap_prover: &tx_wrap_prover, + step_prover: merge_step_prover, + wrap_prover: tx_wrap_prover, only_verify_constraints: false, expected_step_proof: None, // expected_step_proof: Some( @@ -4559,11 +4568,11 @@ mod tests { statement: &statement, tx_witness: &tx_witness, message: &message, - step_opt_signed_opt_signed_prover: &zkapp_step_opt_signed_opt_signed_prover, - step_opt_signed_prover: &zkapp_step_opt_signed_prover, - step_proof_prover: &zkapp_step_proof_prover, - merge_step_prover: &merge_step_prover, - tx_wrap_prover: &tx_wrap_prover, + step_opt_signed_opt_signed_prover: zkapp_step_opt_signed_opt_signed_prover, + step_opt_signed_prover: zkapp_step_opt_signed_prover, + step_proof_prover: zkapp_step_proof_prover, + merge_step_prover, + tx_wrap_prover, opt_signed_path: None, // opt_signed_path: Some("zkapp_opt_signed"), proved_path: None, @@ -4625,11 +4634,11 @@ mod tests { statement: &statement, tx_witness: &tx_witness, message: &message, - step_opt_signed_opt_signed_prover: &zkapp_step_opt_signed_opt_signed_prover, - step_opt_signed_prover: &zkapp_step_opt_signed_prover, - step_proof_prover: &zkapp_step_proof_prover, - merge_step_prover: &merge_step_prover, - tx_wrap_prover: &tx_wrap_prover, + step_opt_signed_opt_signed_prover: zkapp_step_opt_signed_opt_signed_prover, + step_opt_signed_prover: zkapp_step_opt_signed_prover, + step_proof_prover: zkapp_step_proof_prover, + merge_step_prover, + tx_wrap_prover, opt_signed_path: None, proved_path: None, // opt_signed_path: Some("zkapp_proof"), @@ -4678,9 +4687,9 @@ mod tests { let WrapProof { proof, .. } = generate_block_proof( BlockParams { input: &blockchain_input, - block_step_prover: &block_step_prover, - block_wrap_prover: &block_wrap_prover, - tx_wrap_prover: &tx_wrap_prover, + block_step_prover, + block_wrap_prover, + tx_wrap_prover, only_verify_constraints: false, expected_step_proof: None, ocaml_wrap_witness: None, @@ -4743,11 +4752,11 @@ mod tests { statement: &statement, tx_witness: &tx_witness, message: &message, - step_opt_signed_opt_signed_prover: &zkapp_step_opt_signed_opt_signed_prover, - step_opt_signed_prover: &zkapp_step_opt_signed_prover, - step_proof_prover: &zkapp_step_proof_prover, - merge_step_prover: &merge_step_prover, - tx_wrap_prover: &tx_wrap_prover, + step_opt_signed_opt_signed_prover: zkapp_step_opt_signed_opt_signed_prover, + step_opt_signed_prover: zkapp_step_opt_signed_prover, + step_proof_prover: zkapp_step_proof_prover, + merge_step_prover, + tx_wrap_prover, opt_signed_path, proved_path, }) @@ -4777,9 +4786,9 @@ mod tests { let WrapProof { proof, .. } = generate_block_proof( BlockParams { input: &blockchain_input, - block_step_prover: &block_step_prover, - block_wrap_prover: &block_wrap_prover, - tx_wrap_prover: &tx_wrap_prover, + block_step_prover, + block_wrap_prover, + tx_wrap_prover, only_verify_constraints: false, expected_step_proof: None, ocaml_wrap_witness: None, @@ -4814,8 +4823,8 @@ mod tests { statement: (&*statement).into(), proofs: &proofs, message: &message, - step_prover: &merge_step_prover, - wrap_prover: &tx_wrap_prover, + step_prover: merge_step_prover, + wrap_prover: tx_wrap_prover, only_verify_constraints: false, expected_step_proof: None, ocaml_wrap_witness: None, @@ -4879,8 +4888,8 @@ mod tests { statement: &statement, tx_witness: &tx_witness, message: &message, - tx_step_prover: &tx_step_prover, - tx_wrap_prover: &tx_wrap_prover, + tx_step_prover, + tx_wrap_prover, only_verify_constraints: false, expected_step_proof: None, ocaml_wrap_witness: None, diff --git a/ledger/src/proofs/util.rs b/ledger/src/proofs/util.rs index 667fcfd31..0d1764a76 100644 --- a/ledger/src/proofs/util.rs +++ b/ledger/src/proofs/util.rs @@ -63,7 +63,7 @@ where } /// https://github.com/MinaProtocol/mina/blob/bfd1009abdbee78979ff0343cc73a3480e862f58/src/lib/pickles/wrap_verifier.ml#L16 -pub fn challenge_polynomial<'a, F: FieldWitness>(chals: &'a [F]) -> impl Fn(F) -> F + 'a { +pub fn challenge_polynomial(chals: &[F]) -> impl Fn(F) -> F + '_ { |pt: F| { let k = chals.len(); let pow_two_pows = { @@ -86,9 +86,9 @@ pub fn challenge_polynomial<'a, F: FieldWitness>(chals: &'a [F]) -> impl Fn(F) - } /// https://github.com/MinaProtocol/mina/blob/bfd1009abdbee78979ff0343cc73a3480e862f58/src/lib/pickles/wrap_verifier.ml#L16 -pub fn challenge_polynomial_checked<'a, F: FieldWitness>( - chals: &'a [F], -) -> impl Fn(F, &mut Witness) -> F + 'a { +pub fn challenge_polynomial_checked( + chals: &[F], +) -> impl Fn(F, &mut Witness) -> F + '_ { |pt: F, w: &mut Witness| { let k = chals.len(); let pow_two_pows = { @@ -263,7 +263,7 @@ pub fn proof_evaluation_to_list_opt( ]; list.extend(optional_gates.into_iter().map(to_opt)); - list.extend(lookup_sorted.into_iter().map(to_opt)); + list.extend(lookup_sorted.iter().map(to_opt)); list.extend( [ @@ -481,13 +481,13 @@ pub fn to_absorption_sequence_opt( } = evals; let mut list = vec![ - Opt::Some(z.clone()), - Opt::Some(generic_selector.clone()), - Opt::Some(poseidon_selector.clone()), - Opt::Some(complete_add_selector.clone()), - Opt::Some(mul_selector.clone()), - Opt::Some(emul_selector.clone()), - Opt::Some(endomul_scalar_selector.clone()), + Opt::Some(*z), + Opt::Some(*generic_selector), + Opt::Some(*poseidon_selector), + Opt::Some(*complete_add_selector), + Opt::Some(*mul_selector), + Opt::Some(*emul_selector), + Opt::Some(*endomul_scalar_selector), ]; list.extend(w.iter().copied().map(Opt::Some)); @@ -511,14 +511,14 @@ pub fn to_absorption_sequence_opt( list.extend( [ - range_check0_selector.clone(), - range_check1_selector.clone(), - foreign_field_add_selector.clone(), - foreign_field_mul_selector.clone(), - xor_selector.clone(), - rot_selector.clone(), - lookup_aggregation.clone(), - lookup_table.clone(), + *range_check0_selector, + *range_check1_selector, + *foreign_field_add_selector, + *foreign_field_mul_selector, + *xor_selector, + *rot_selector, + *lookup_aggregation, + *lookup_table, ] .iter() .map(to_opt), diff --git a/ledger/src/proofs/verifier_index.rs b/ledger/src/proofs/verifier_index.rs index ff5ecae68..d915d6e4f 100644 --- a/ledger/src/proofs/verifier_index.rs +++ b/ledger/src/proofs/verifier_index.rs @@ -60,7 +60,7 @@ fn read_index(path: &Path, digest: &[u8]) -> anyhow::Result anyhow::Result, digest: &[u8]) -> any anyhow::bail!("cannot get parent for {path:?}"); }; std::fs::create_dir_all(parent).context("creating cache file parent directory")?; - let mut file = File::create(&path).context("creating cache file")?; + let mut file = File::create(path).context("creating cache file")?; file.write_all(digest).context("storing source digest")?; file.write_all(&hasher.finalize()) .context("storing verifier index digest")?; diff --git a/ledger/src/proofs/wrap.rs b/ledger/src/proofs/wrap.rs index edcc8911d..7ea5cbee8 100644 --- a/ledger/src/proofs/wrap.rs +++ b/ledger/src/proofs/wrap.rs @@ -205,7 +205,7 @@ pub fn create_oracle( type EFrSponge = DefaultFrSponge; let oracles_result = proof - .oracles::>(&verifier_index, &p_comm, public) + .oracles::>(verifier_index, &p_comm, public) .unwrap(); let OraclesResult { @@ -303,7 +303,7 @@ fn deferred_values(params: DeferredValuesParams) -> DeferredValuesAndHints { let step_vk = prover_index.verifier_index(); let log_size_of_group = step_vk.domain.log_size_of_group; - let oracle = create_oracle(&step_vk, &proof, public_input); + let oracle = create_oracle(&step_vk, proof, public_input); let x_hat = [oracle.p_eval.0, oracle.p_eval.1]; let alpha = oracle.alpha(); @@ -373,11 +373,7 @@ fn deferred_values(params: DeferredValuesParams) -> DeferredValuesAndHints { let challenge_poly = challenge_polynomial(&chals); let b = challenge_poly(zeta) + (r * challenge_poly(zetaw)); - let prechals = oracle - .opening_prechallenges - .iter() - .copied() - .collect::>(); + let prechals = oracle.opening_prechallenges.to_vec(); (prechals, b) }; @@ -762,7 +758,7 @@ pub fn wrap( prev_challenges: prev, only_verify_constraints: false, }, - &w, + w, )?; Ok(WrapProof { @@ -993,7 +989,7 @@ pub mod pseudo { .iter() .map(|d| domain_generator(*d)) .collect::>(); - mask(&which, &xs) + mask(which, &xs) } pub fn shifts( @@ -1365,7 +1361,7 @@ pub mod pcs_batch { } pub mod wrap_verifier { - use std::{convert::identity, ops::Neg, sync::Arc}; + use std::{ops::Neg, sync::Arc}; use itertools::Itertools; use kimchi::prover_index::ProverIndex; @@ -1555,7 +1551,7 @@ pub mod wrap_verifier { (sg_evals1, sg_evals2) }; - let _sponge_state = { + { let challenge_digest = { let mut sponge = Sponge::::new(); old_bulletproof_challenges.iter().for_each(|v| { @@ -1908,7 +1904,7 @@ pub mod wrap_verifier { pub fn finite(&self) -> CircuitVar { match self { Point::Finite(_) => CircuitVar::Constant(Boolean::True), - Point::MaybeFinite(b, _) => b.clone(), + Point::MaybeFinite(b, _) => *b, } } @@ -1921,8 +1917,8 @@ pub mod wrap_verifier { pub fn underlying(&self) -> CircuitVar> { match self { - Point::Finite(p) => p.clone(), - Point::MaybeFinite(_, p) => p.clone(), + Point::Finite(p) => *p, + Point::MaybeFinite(_, p) => *p, } } } @@ -2204,7 +2200,7 @@ pub mod wrap_verifier { sponge.absorb((CircuitVar::Constant(Boolean::True), index_digest)); for (b, v) in &sg_old { - absorb_curve(&b, *v, &mut sponge); + absorb_curve(b, v, &mut sponge); } let x_hat = { @@ -2271,7 +2267,7 @@ pub mod wrap_verifier { let init = constant_part .into_iter() - .filter_map(identity) + .flatten() .fold(correction, |acc, (x, y)| w.add_fast(acc, make_group(x, y))); terms @@ -2311,7 +2307,7 @@ pub mod wrap_verifier { for w in w_comm.iter().flat_map(|w| &w.unshifted) { absorb_curve( &CircuitVar::Constant(Boolean::True), - &InnerCurve::of_affine(w.clone()), + &InnerCurve::of_affine(*w), &mut sponge, ); } @@ -2323,7 +2319,7 @@ pub mod wrap_verifier { for z in z_comm.unshifted.iter() { absorb_curve( &CircuitVar::Constant(Boolean::True), - &InnerCurve::of_affine(z.clone()), + &InnerCurve::of_affine(*z), &mut sponge, ); } @@ -2334,7 +2330,7 @@ pub mod wrap_verifier { for t in t_comm.unshifted.iter() { absorb_curve( &CircuitVar::Constant(Boolean::True), - &InnerCurve::of_affine(t.clone()), + &InnerCurve::of_affine(*t), &mut sponge, ); } @@ -2440,7 +2436,7 @@ impl Check for poly_commitment::evaluation_proof::OpeningProof { sg, } = self; - let to_curve = |c: &Vesta| InnerCurve::::of_affine(c.clone()); + let to_curve = |c: &Vesta| InnerCurve::::of_affine(*c); let shift = |f: Fp| ::Shifting::of_field(f); lr.iter().for_each(|(a, b)| { @@ -2538,7 +2534,7 @@ impl Check for kimchi::proof::ProverCommitments { shifted: _, } = poly; for affine in unshifted { - InnerCurve::of_affine(affine.clone()).check(w); + InnerCurve::of_affine(*affine).check(w); } }; @@ -2791,7 +2787,7 @@ fn wrap_main(params: WrapMainParams, w: &mut Witness) { unfinalized_proofs .iter() .zip(&old_bp_chals) - .zip(&*evals) + .zip(evals) .zip(&wrap_domains) .map( |(((unfinalized, old_bulletproof_challenges), evals), wrap_domain)| { diff --git a/ledger/src/proofs/zkapp.rs b/ledger/src/proofs/zkapp.rs index b3735f5af..324b692d1 100644 --- a/ledger/src/proofs/zkapp.rs +++ b/ledger/src/proofs/zkapp.rs @@ -152,7 +152,7 @@ mod group { global: global_after.clone(), local: local_after.clone(), }, - connecting_ledger: connecting_ledger.clone(), + connecting_ledger: *connecting_ledger, } } @@ -201,7 +201,6 @@ mod group { match (zkapp_commands, stmtss) { ([] | [[]], [ _ ]) => { // eprintln!("GROUP 1"); - return; }, ([[ AccountUpdate { authorization: a1, .. } ]], [[ before, after ]]) => { // eprintln!("GROUP 2"); @@ -473,7 +472,7 @@ pub fn zkapp_command_witnesses_exn( &state_view, fee_excess, supply_increase, - &second_pass_ledger, + second_pass_ledger, zkapp_command, ) .unwrap(); @@ -1035,7 +1034,7 @@ fn zkapp_main( pending_coinbase_stack_init, pending_coinbase_stack_before: statement.source.pending_coinbase_stack.clone(), pending_coinbase_stack_after: statement.target.pending_coinbase_stack.clone(), - block_global_slot: block_global_slot.clone(), + block_global_slot, state_body, }, w, @@ -1054,7 +1053,7 @@ fn zkapp_main( fee_excess: CheckedSigned::zero(), supply_increase: CheckedSigned::zero(), protocol_state: protocol_state_body_view(state_body), - block_global_slot: block_global_slot.clone(), + block_global_slot, }; let l = zkapp_logic::LocalState:: { @@ -1253,7 +1252,7 @@ fn first_account_update<'a>(witness: &'a ZkappCommandSegmentWitness) -> Option<& fn account_update_proof(p: &AccountUpdate) -> Option<&v2::PicklesProofProofsVerifiedMaxStableV2> { match &p.authorization { - Control::Proof(proof) => Some(&*proof), + Control::Proof(proof) => Some(proof), Control::Signature(_) | Control::NoneGiven => None, } } diff --git a/ledger/src/scan_state/conv.rs b/ledger/src/scan_state/conv.rs index 194c48a72..2ef553b09 100644 --- a/ledger/src/scan_state/conv.rs +++ b/ledger/src/scan_state/conv.rs @@ -2497,7 +2497,7 @@ impl From<&MinaBasePendingCoinbaseStableV2> for PendingCoinbase { let stack_id: pending_coinbase::StackId = stack_id.into(); let stack_index = crate::AccountIndex::from(stack_index.as_u64() as usize); - let addr = Address::from_index(stack_index.clone(), depth); + let addr = Address::from_index(stack_index, depth); our_index.insert(stack_id, addr); // index_list.push_back(stack_id); diff --git a/ledger/src/scan_state/pending_coinbase.rs b/ledger/src/scan_state/pending_coinbase.rs index 59f125166..a7b2d8430 100644 --- a/ledger/src/scan_state/pending_coinbase.rs +++ b/ledger/src/scan_state/pending_coinbase.rs @@ -735,7 +735,7 @@ impl PendingCoinbase { ..stack.clone() }; let stack_with_state_hash = - stack_initialized.checked_push_state(state_body_hash, global_slot.clone(), w); + stack_initialized.checked_push_state(state_body_hash, *global_slot, w); w.exists_no_check(match no_update { Boolean::True => stack, Boolean::False => stack_with_state_hash, @@ -813,7 +813,7 @@ impl PendingCoinbase { state: StateStack::create(init_stack.state.curr), ..stack0.clone() } - .checked_push_state(state_body_hash, global_slot.clone(), w); + .checked_push_state(state_body_hash, *global_slot, w); w.exists_no_check(match update_state { Boolean::True => stack_with_state, Boolean::False => stack0, diff --git a/ledger/src/scan_state/scan_state.rs b/ledger/src/scan_state/scan_state.rs index 05d4dc90a..ce82943b9 100644 --- a/ledger/src/scan_state/scan_state.rs +++ b/ledger/src/scan_state/scan_state.rs @@ -2433,8 +2433,8 @@ impl TransactionsOrdered> { let complete_and_incomplete_transactions = |txs: Vec>| -> Option< TransactionsOrdered>, > { - let target_first_pass_ledger = txs.get(0)?.statement.source.first_pass_ledger; - let first_state_hash = txs.get(0)?.state_hash.0; + let target_first_pass_ledger = txs.first()?.statement.source.first_pass_ledger; + let first_state_hash = txs.first()?.state_hash.0; let first_pass_txns = Vec::with_capacity(txns_per_tree_len); let second_pass_txns = Vec::with_capacity(txns_per_tree_len); diff --git a/ledger/src/scan_state/snark_work.rs b/ledger/src/scan_state/snark_work.rs index 02ee46c89..a94622c79 100644 --- a/ledger/src/scan_state/snark_work.rs +++ b/ledger/src/scan_state/snark_work.rs @@ -89,8 +89,8 @@ mod tests { r.read_to_end(&mut buf).unwrap(); let mut read = buf.as_slice(); - let result = T::binprot_read(&mut read).unwrap(); - result + + T::binprot_read(&mut read).unwrap() } fn read_input(mut r: R) { @@ -221,7 +221,7 @@ mod tests { // dbg!(&good[0]); let n = 10.min(good.len()); - for index in 0..n { + for (index, _) in good.iter().enumerate().take(n) { let value = good[index].clone(); let value = ExternalSnarkWorkerRequest::PerformJob(value); diff --git a/ledger/src/scan_state/transaction_logic.rs b/ledger/src/scan_state/transaction_logic.rs index 41d76b9b2..1f0ba16f5 100644 --- a/ledger/src/scan_state/transaction_logic.rs +++ b/ledger/src/scan_state/transaction_logic.rs @@ -3196,7 +3196,7 @@ pub mod zkapp_command { this: TokenId, } - pub const ACCOUNT_UPDATE_CONS_HASH_PARAM: &'static str = "MinaAcctUpdateCons"; + pub const ACCOUNT_UPDATE_CONS_HASH_PARAM: &str = "MinaAcctUpdateCons"; impl CallForest { pub fn new() -> Self { @@ -4920,7 +4920,7 @@ pub mod local_state { inputs.append_field(self.caller.0); inputs.append_field(self.caller_caller.0); - let field = match self.calls.0.get(0) { + let field = match self.calls.0.first() { None => Fp::zero(), Some(call) => call.stack_hash, }; @@ -5083,7 +5083,7 @@ pub mod local_state { } pub fn add_check(&self, failure: TransactionFailure, b: bool) -> Self { - let failure_status_tbl = if let false = b { + let failure_status_tbl = if !b { let mut failure_status_tbl = self.failure_status_tbl.clone(); failure_status_tbl[0].insert(0, failure); failure_status_tbl @@ -7518,7 +7518,7 @@ pub fn account_min_balance_at_slot( let num_periods = (global_slot.as_u32() - cliff_time.as_u32()) / vesting_period.as_u32(); - let num_periods: u64 = num_periods.try_into().unwrap(); + let num_periods: u64 = num_periods.into(); let vesting_decrement = { let vesting_increment = vesting_increment.as_u64(); diff --git a/ledger/src/scan_state/zkapp_logic.rs b/ledger/src/scan_state/zkapp_logic.rs index 9735bae32..b779bb91d 100644 --- a/ledger/src/scan_state/zkapp_logic.rs +++ b/ledger/src/scan_state/zkapp_logic.rs @@ -758,7 +758,7 @@ where let auth = if older_than_current_version { original_auth.verification_key_perm_fallback_to_signature_with_older_version() } else { - original_auth.clone() + *original_auth }; let has_permission = controller_check(proof_verifies, signature_verifies, auth)?; diff --git a/ledger/src/sparse_ledger/sparse_ledger.rs b/ledger/src/sparse_ledger/sparse_ledger.rs index f9d25fc58..85b61a80d 100644 --- a/ledger/src/sparse_ledger/sparse_ledger.rs +++ b/ledger/src/sparse_ledger/sparse_ledger.rs @@ -426,7 +426,7 @@ impl From<&mina_p2p_messages::v2::MinaBaseSparseLedgerBaseStableV2> for SparseLe let account_id: AccountId = account_id.into(); let account_index = AccountIndex::from(account_index.as_u64() as usize); - let addr = Address::from_index(account_index.clone(), depth); + let addr = Address::from_index(account_index, depth); indexes.insert(account_id.clone(), addr); indexes_list.push_back(account_id); diff --git a/ledger/src/sparse_ledger/sparse_ledger_impl.rs b/ledger/src/sparse_ledger/sparse_ledger_impl.rs index 37d2b550c..3667005bd 100644 --- a/ledger/src/sparse_ledger/sparse_ledger_impl.rs +++ b/ledger/src/sparse_ledger/sparse_ledger_impl.rs @@ -113,7 +113,7 @@ impl SparseLedgerImpl { where F: Fn(Address, &Account), { - let addr = |index: &AccountIndex| Address::from_index(index.clone(), self.depth); + let addr = |index: &AccountIndex| Address::from_index(*index, self.depth); for (index, value) in &self.values { fun(addr(index), value); diff --git a/ledger/src/staged_ledger/staged_ledger.rs b/ledger/src/staged_ledger/staged_ledger.rs index efc8be9d0..cef41c08f 100644 --- a/ledger/src/staged_ledger/staged_ledger.rs +++ b/ledger/src/staged_ledger/staged_ledger.rs @@ -4918,7 +4918,7 @@ mod tests_ocaml { pre_diff.sort_by_key(|v| v.fee); pre_diff }) - .unwrap_or_else(Vec::new) + .unwrap_or_default() }; { diff --git a/ledger/src/util/mod.rs b/ledger/src/util/mod.rs index d56876ffa..0a92071a5 100644 --- a/ledger/src/util/mod.rs +++ b/ledger/src/util/mod.rs @@ -164,7 +164,7 @@ where T: ToFieldElements, { fn to_field_elements(&self, fields: &mut Vec) { - let this: &T = &*self; + let this: &T = self; this.to_field_elements(fields); } } diff --git a/ledger/src/zkapps/snark.rs b/ledger/src/zkapps/snark.rs index 247e626c1..5c7ba7adc 100644 --- a/ledger/src/zkapps/snark.rs +++ b/ledger/src/zkapps/snark.rs @@ -225,7 +225,7 @@ impl ZkappHandler for SnarkHandler { }; account_update.body.preconditions.account.checked_zcheck( new_account.as_boolean(), - &*account.data, + &account.data, check, w, ); @@ -631,7 +631,7 @@ impl GlobalStateInterface for GlobalStateForProof { self.supply_increase = supply_increase; } fn block_global_slot(&self) -> Self::GlobalSlotSinceGenesis { - self.block_global_slot.clone() + self.block_global_slot } } @@ -651,7 +651,7 @@ impl GlobalSlotSinceGenesisInterface for SnarkGlobalSlot { type Bool = SnarkBool; fn equal(&self, other: &Self, w: &mut Self::W) -> Self::Bool { - >::equal(&self, other, w).var() + >::equal(self, other, w).var() } } @@ -955,7 +955,7 @@ impl AccountInterface for SnarkAccount { } fn get(&self) -> &crate::Account { let Self { data, .. } = self; - &*data + data } fn get_mut(&mut self) -> &mut crate::Account { let Self { data, .. } = self; @@ -1009,13 +1009,8 @@ impl AccountInterface for SnarkAccount { invalid_timing = Some(b.neg()); }; let account = self.get(); - let (_min_balance, timing) = check_timing( - account, - None, - txn_global_slot.clone(), - timed_balance_check, - w, - ); + let (_min_balance, timing) = + check_timing(account, None, *txn_global_slot, timed_balance_check, w); (invalid_timing.unwrap().var(), timing) } fn make_zkapp(&mut self) { @@ -1336,7 +1331,7 @@ fn verification_key_perm_fallback_to_signature_with_older_version( } = encode_auth(auth); let on_true = SnarkBranch::make(w, |_| AuthRequired::Signature); - let on_false = SnarkBranch::make(w, |_| auth.clone()); + let on_false = SnarkBranch::make(w, |_| *auth); w.on_if( signature_sufficient.neg(), diff --git a/ledger/src/zkapps/zkapp_logic.rs b/ledger/src/zkapps/zkapp_logic.rs index 6cc640352..0542d7d50 100644 --- a/ledger/src/zkapps/zkapp_logic.rs +++ b/ledger/src/zkapps/zkapp_logic.rs @@ -263,7 +263,7 @@ fn update_action_state( last_action_slot: Z::GlobalSlotSinceGenesis, w: &mut Z::WitnessGenerator, ) -> ([Fp; 5], ::GlobalSlotSinceGenesis) { - let [s1, s2, s3, s4, s5] = action_state.clone(); + let [s1, s2, s3, s4, s5] = *action_state; let is_empty = Z::Actions::is_empty(actions, w); let s1_updated = Z::Actions::push_events(s1, actions, w); let s1_new = w.exists_no_check(match is_empty.as_boolean() { @@ -421,7 +421,7 @@ where new_frame: remaining, } = get_next_account_update::(to_pop, call_stack, w); - let _local_state = { + { let default_token_or_token_owner_was_caller = { let account_update_token_id = &account_update.body().token_id; // We decompose this way because of OCaml evaluation order @@ -435,7 +435,7 @@ where default_token_or_token_owner_was_caller, w, ); - }; + } let acct = local_state.ledger.get_account(&account_update, w); local_state.ledger.check_inclusion(&acct, w); @@ -489,7 +489,7 @@ where w, ); - let _a = { + { let self_delegate = { let account_update_token_id = &account_update.body().token_id; let is_default_token = @@ -536,7 +536,7 @@ where w, ); - let _local_state = { + { let valid_while = &account_update.body().preconditions.valid_while; let valid_while_satisfied = Z::Handler::check_valid_while_precondition(valid_while, global_state, w); @@ -589,7 +589,7 @@ where w, ); - let _local_state = { + { let precondition_has_constant_nonce = account_update.account_precondition_nonce_is_constant(w); let increments_nonce_and_constrains_its_old_value = Z::Bool::and( @@ -677,14 +677,14 @@ where let balance_change = &account_update_balance_change; let neg_creation_fee = { Z::SignedAmount::of_unsigned(account_creation_fee).negate() }; let (balance_change_for_creation, creation_overflow) = - Z::SignedAmount::add_flagged(&balance_change, &neg_creation_fee, w); + Z::SignedAmount::add_flagged(balance_change, &neg_creation_fee, w); let pay_creation_fee = Z::Bool::and(account_is_new, implicit_account_creation_fee, w); let creation_overflow = Z::Bool::and(pay_creation_fee, creation_overflow, w); let balance_change = Z::SignedAmount::on_if( pay_creation_fee, SignedAmountBranchParam { on_true: &balance_change_for_creation, - on_false: &balance_change, + on_false: balance_change, }, w, ); @@ -711,7 +711,7 @@ where Z::LocalState::add_check(local_state, TransactionFailure::Overflow, failed1.neg(), w); let account_creation_fee = Z::Amount::of_constant_fee(Fee::from_u64(CONSTRAINT_CONSTANTS.account_creation_fee)); - let _local_state = { + { let (excess_minus_creation_fee, excess_update_failed) = Z::SignedAmount::add_flagged( &local_state.excess, &Z::SignedAmount::of_unsigned(account_creation_fee.clone()).negate(), @@ -734,7 +734,7 @@ where .clone(); }; - let _local_state = { + { let (supply_increase_minus_creation_fee, supply_increase_update_failed) = Z::SignedAmount::add_flagged( &local_state.supply_increase, @@ -759,7 +759,7 @@ where }; let is_receiver = actual_balance_change.is_non_neg(); - let _local_state = { + { let controller = { let on_true = Z::Branch::make(w, |_| a.get().permissions.receive); let on_false = Z::Branch::make(w, |_| a.get().permissions.send); @@ -799,7 +799,7 @@ where }; Z::Account::make_zkapp(&mut a); // Check that the account can be accessed with the given authorization. - let _local_state = { + { let has_permission = { let access = &a.get().permissions.access; Z::Controller::check(proof_verifies, signature_verifies, access, &single_data, w) @@ -899,7 +899,7 @@ where w, ) }); - let on_false = Z::Branch::make(w, |_| original_auth.clone()); + let on_false = Z::Branch::make(w, |_| *original_auth); w.on_if( older_than_current_version, BranchParam { on_true, on_false }, @@ -1111,7 +1111,7 @@ where }; // Update receipt chain hash - let _ = { + { let new_hash = { let old_hash = a.get().receipt_chain_hash.clone(); let cond = Z::Bool::or(signature_verifies, proof_verifies, w); @@ -1299,7 +1299,7 @@ where w, ); - let _global_state = { + { let is_successful_last_party = Z::Bool::and(is_last_account_update, local_state.success, w); let global_state_supply_increase = global_state.supply_increase(); let supply_increase = Z::SignedAmount::on_if( @@ -1314,7 +1314,7 @@ where global_state.set_second_pass_ledger(is_successful_last_party, &local_state.ledger, w); }; - let _local_state = { + { let will_succeed = w.exists_no_check(match is_last_account_update.as_boolean() { Boolean::True => Z::Bool::true_(), Boolean::False => local_state.will_succeed, diff --git a/mina-p2p-messages/examples/mina-types-converter.rs b/mina-p2p-messages/examples/mina-types-converter.rs index 679992588..4cbc8660c 100644 --- a/mina-p2p-messages/examples/mina-types-converter.rs +++ b/mina-p2p-messages/examples/mina-types-converter.rs @@ -56,6 +56,8 @@ struct Cli { input: Option, } +// TODO: I'm not sure whether changing the acronyms breaks anything, check +#[allow(clippy::upper_case_acronyms)] #[derive(ValueEnum, Clone, Copy, Debug, PartialEq, Eq)] enum FileFormat { BinProt, diff --git a/mina-p2p-messages/src/array.rs b/mina-p2p-messages/src/array.rs index 350a2b778..c2f39f575 100644 --- a/mina-p2p-messages/src/array.rs +++ b/mina-p2p-messages/src/array.rs @@ -49,7 +49,7 @@ impl<'a, T, const N: u64> IntoIterator for &'a ArrayN { type IntoIter = <&'a Vec as IntoIterator>::IntoIter; fn into_iter(self) -> Self::IntoIter { - (&self.0).into_iter() + self.0.iter() } } diff --git a/mina-p2p-messages/src/b58.rs b/mina-p2p-messages/src/b58.rs index 3ce010278..33f40ce34 100644 --- a/mina-p2p-messages/src/b58.rs +++ b/mina-p2p-messages/src/b58.rs @@ -219,7 +219,7 @@ where { if deserializer.is_human_readable() { let b58: String = Deserialize::deserialize(deserializer)?; - Ok(b58.parse().map_err(|err| serde::de::Error::custom(err))?) + Ok(b58.parse().map_err(serde::de::Error::custom)?) } else { T::deserialize(deserializer).map(|v| Self(v, Default::default())) } diff --git a/mina-p2p-messages/src/bigint.rs b/mina-p2p-messages/src/bigint.rs index a4df113d3..a781f34dd 100644 --- a/mina-p2p-messages/src/bigint.rs +++ b/mina-p2p-messages/src/bigint.rs @@ -41,7 +41,7 @@ impl BigInt { F::read(&mut slice).expect("Conversion BigInt to Field failed") } - pub fn iter_bytes<'a>(&'a self) -> impl 'a + DoubleEndedIterator { + pub fn iter_bytes(&self) -> impl '_ + DoubleEndedIterator { self.0.iter().cloned() } } @@ -137,7 +137,7 @@ impl Serialize for BigInt { { if serializer.is_human_readable() { // TODO get rid of copying - let mut rev = self.0.as_ref().clone(); + let mut rev = *self.0.as_ref(); rev[..].reverse(); let mut hex = [0_u8; 32 * 2 + 2]; hex[..2].copy_from_slice(b"0x"); @@ -171,7 +171,7 @@ impl<'de> Deserialize<'de> for BigInt { Some(v) => hex::decode(v).map_err(|_| { serde::de::Error::custom(format!("failed to decode hex str: {v}")) }), - None => Err(serde::de::Error::custom(format!("mising 0x prefix"))), + None => Err(serde::de::Error::custom("mising 0x prefix".to_string())), } } @@ -183,14 +183,14 @@ impl<'de> Deserialize<'de> for BigInt { Some(v) => hex::decode(v).map_err(|_| { serde::de::Error::custom(format!("failed to decode hex str: {v}")) }), - None => Err(serde::de::Error::custom(format!("mising 0x prefix"))), + None => Err(serde::de::Error::custom("mising 0x prefix".to_string())), } } } let mut v = deserializer.deserialize_str(V)?; v.reverse(); v.try_into() - .map_err(|_| serde::de::Error::custom(format!("failed to convert vec to array"))) + .map_err(|_| serde::de::Error::custom("failed to convert vec to array".to_string())) } else { struct V; impl<'de> serde::de::Visitor<'de> for V { @@ -303,7 +303,7 @@ mod tests { for bigint in bigints { let json = serde_json::to_string(&bigint).unwrap(); - let mut v = bigint.0.as_ref().clone(); + let mut v = *bigint.0.as_ref(); v.reverse(); let json_exp = format!(r#""0x{}""#, hex::encode(v)); assert_eq!(json, json_exp); diff --git a/mina-p2p-messages/src/char.rs b/mina-p2p-messages/src/char.rs index 0987223e1..fe2976264 100644 --- a/mina-p2p-messages/src/char.rs +++ b/mina-p2p-messages/src/char.rs @@ -111,7 +111,7 @@ mod tests { #[test] fn json() { let ch = super::Char(16); - let json = serde_json::to_value(&ch).unwrap(); + let json = serde_json::to_value(ch).unwrap(); assert_eq!(json.as_str().unwrap(), "\u{0010}"); assert_eq!( serde_json::from_value::(json).unwrap(), diff --git a/mina-p2p-messages/src/core.rs b/mina-p2p-messages/src/core.rs index 4fd2c6cb2..a3ff971f7 100644 --- a/mina-p2p-messages/src/core.rs +++ b/mina-p2p-messages/src/core.rs @@ -56,7 +56,7 @@ impl TryFrom for Info { type Error = InfoFromSexpError; fn try_from(value: SexpString) -> Result { - let parsed = rsexp::from_slice(&value.0).map_err(|e| InfoFromSexpError(e))?; + let parsed = rsexp::from_slice(&value.0).map_err(InfoFromSexpError)?; Ok(Info(parsed)) } } @@ -108,7 +108,7 @@ mod test { fn bytes_to_info(mut bytes: &[u8]) -> Info { let info = Info::binprot_read(&mut bytes).unwrap(); - assert!(bytes.len() == 0); + assert!(bytes.is_empty()); info } diff --git a/mina-p2p-messages/src/hash_input.rs b/mina-p2p-messages/src/hash_input.rs index 301044224..1bcbfaf9d 100644 --- a/mina-p2p-messages/src/hash_input.rs +++ b/mina-p2p-messages/src/hash_input.rs @@ -77,7 +77,7 @@ where T: ToInput, { fn to_input(&self, inputs: &mut Inputs) { - self.deref().into_iter().for_each(|v| v.to_input(inputs)); + self.deref().iter().for_each(|v| v.to_input(inputs)); } } diff --git a/mina-p2p-messages/src/lib.rs b/mina-p2p-messages/src/lib.rs index 7f9f410f0..4641c65d3 100644 --- a/mina-p2p-messages/src/lib.rs +++ b/mina-p2p-messages/src/lib.rs @@ -1,3 +1,7 @@ +#![allow(clippy::large_enum_variant)] +#![allow(clippy::type_complexity)] +// TODO(akoptelov) +#![allow(clippy::suspicious_doc_comments)] pub mod array; ///! Mina wire types, represented in Rust. ///! diff --git a/mina-p2p-messages/src/list.rs b/mina-p2p-messages/src/list.rs index f37732e08..d7e77709e 100644 --- a/mina-p2p-messages/src/list.rs +++ b/mina-p2p-messages/src/list.rs @@ -67,7 +67,7 @@ impl<'a, T> IntoIterator for &'a List { type IntoIter = <&'a Backend as IntoIterator>::IntoIter; fn into_iter(self) -> Self::IntoIter { - (&self.0).into_iter() + self.0.iter() } } diff --git a/mina-p2p-messages/src/number.rs b/mina-p2p-messages/src/number.rs index 4b5302de0..a53ed72b6 100644 --- a/mina-p2p-messages/src/number.rs +++ b/mina-p2p-messages/src/number.rs @@ -122,7 +122,7 @@ where E: serde::de::Error, { v.parse().map_err(|_| { - serde::de::Error::custom(format!("failed to parse string as number")) + serde::de::Error::custom("failed to parse string as number".to_string()) }) } @@ -131,7 +131,7 @@ where E: serde::de::Error, { v.parse().map_err(|_| { - serde::de::Error::custom(format!("failed to parse string as number")) + serde::de::Error::custom("failed to parse string as number".to_string()) }) } @@ -140,7 +140,7 @@ where E: serde::de::Error, { v.parse().map_err(|_| { - serde::de::Error::custom(format!("failed to parse string as number")) + serde::de::Error::custom("failed to parse string as number".to_string()) }) } } diff --git a/mina-p2p-messages/src/rpc.rs b/mina-p2p-messages/src/rpc.rs index c0a6cc55a..d920958aa 100644 --- a/mina-p2p-messages/src/rpc.rs +++ b/mina-p2p-messages/src/rpc.rs @@ -286,6 +286,7 @@ pub struct JSONifyPayloadRegistry { impl JSONifyPayloadRegistry { #[deprecated = "Use `[v1]` or `[v2]` methods instead."] + #[allow(clippy::new_without_default)] pub fn new() -> Self { Self::v1() } diff --git a/mina-p2p-messages/src/string.rs b/mina-p2p-messages/src/string.rs index 57c1dd792..03eb8762b 100644 --- a/mina-p2p-messages/src/string.rs +++ b/mina-p2p-messages/src/string.rs @@ -99,7 +99,7 @@ impl<'de> Deserialize<'de> for ByteString { E: serde::de::Error, { hex::decode(v) - .map_err(|_| serde::de::Error::custom(format!("failed to decode hex str"))) + .map_err(|_| serde::de::Error::custom("failed to decode hex str".to_string())) } } deserializer.deserialize_str(V).map(Self) @@ -126,8 +126,8 @@ impl binprot::BinProtWrite for ByteString { if self.0.len() > MINA_STRING_MAX_LENGTH { return Err(MinaStringTooLong::as_io_err(self.0.len())); } - let _ = Nat0(self.0.len() as u64).binprot_write(w)?; - let _ = w.write_all(&self.0)?; + Nat0(self.0.len() as u64).binprot_write(w)?; + w.write_all(&self.0)?; Ok(()) } } @@ -258,8 +258,8 @@ impl binprot::BinProtWrite for CharString { if self.0.len() > MINA_STRING_MAX_LENGTH { return Err(MinaStringTooLong::as_io_err(self.0.len())); } - let _ = Nat0(self.0.len() as u64).binprot_write(w)?; - let _ = w.write_all(&self.0)?; + Nat0(self.0.len() as u64).binprot_write(w)?; + w.write_all(&self.0)?; Ok(()) } } diff --git a/mina-p2p-messages/src/utils.rs b/mina-p2p-messages/src/utils.rs index 4bcff2b79..f1bbe2df8 100644 --- a/mina-p2p-messages/src/utils.rs +++ b/mina-p2p-messages/src/utils.rs @@ -109,7 +109,7 @@ impl<'de> Deserialize<'de> for Greedy { D: serde::Deserializer<'de>, { let hex = String::deserialize(deserializer)?; - Ok(Self(hex::decode(&hex).unwrap())) + Ok(Self(hex::decode(hex).unwrap())) } } diff --git a/mina-p2p-messages/src/v1/hashing.rs b/mina-p2p-messages/src/v1/hashing.rs index 6ee0e6c2b..b9d5d2a4d 100644 --- a/mina-p2p-messages/src/v1/hashing.rs +++ b/mina-p2p-messages/src/v1/hashing.rs @@ -195,7 +195,7 @@ impl generated::MinaBaseStagedLedgerHashNonSnarkStableV1VersionedV1 { let ledger_hash_bytes: Vec = self.ledger_hash.inner().0 .0.iter_bytes().rev().collect(); hasher.update(&ledger_hash_bytes); hasher.update(self.aux_hash.inner().0.as_ref()); - hasher.update(&self.pending_coinbase_aux.inner().0.as_ref()); + hasher.update(self.pending_coinbase_aux.inner().0.as_ref()); hasher.finalize().to_vec() } } @@ -265,7 +265,7 @@ impl Hashable for generated::ConsensusVrfOutputTruncatedStableV1VersionedV1 { let data = self.0.as_ref(); let roi = ROInput::new(); if data.len() <= 31 { - roi.append_bytes(&data) + roi.append_bytes(data) } else { let roi = roi.append_bytes(&data[..31]); if data.len() > 31 { diff --git a/mina-p2p-messages/src/v1/manual.rs b/mina-p2p-messages/src/v1/manual.rs index 4a8ac8a2a..6534f6e96 100644 --- a/mina-p2p-messages/src/v1/manual.rs +++ b/mina-p2p-messages/src/v1/manual.rs @@ -56,7 +56,7 @@ where } let mut tree = Self::Leaf(data); while let Some(value) = values.pop() { - depth = depth - 1; + depth -= 1; tree = Self::Node { depth, value, diff --git a/mina-p2p-messages/src/v2/hashing.rs b/mina-p2p-messages/src/v2/hashing.rs index 9c2c8c1ca..05c320057 100644 --- a/mina-p2p-messages/src/v2/hashing.rs +++ b/mina-p2p-messages/src/v2/hashing.rs @@ -118,9 +118,9 @@ impl<'de> serde::Deserialize<'de> for TransactionHash { { if deserializer.is_human_readable() { let b58: String = Deserialize::deserialize(deserializer)?; - Ok(b58.parse().map_err(|err| serde::de::Error::custom(err))?) + Ok(b58.parse().map_err(serde::de::Error::custom)?) } else { - Vec::deserialize(deserializer).map(|v| Self(v)) + Vec::deserialize(deserializer).map(Self) } } } diff --git a/mina-p2p-messages/src/v2/manual.rs b/mina-p2p-messages/src/v2/manual.rs index 0e2344455..54d3790af 100644 --- a/mina-p2p-messages/src/v2/manual.rs +++ b/mina-p2p-messages/src/v2/manual.rs @@ -87,7 +87,7 @@ impl BinProtRead for TransactionSnarkScanStateStableV2ScanStateTreesA { } let mut tree = Self::Leaf(data); while let Some(value) = values.pop() { - depth = depth - 1; + depth -= 1; tree = Self::Node { depth: depth.into(), value, @@ -145,7 +145,7 @@ impl BinProtWrite for TransactionSnarkScanStateStableV2ScanStateTreesA { value, sub_tree, } => { - if &depth.0 != &curr_depth { + if depth.0 != curr_depth { return Err(std::io::Error::new( std::io::ErrorKind::InvalidInput, format!( @@ -531,10 +531,10 @@ mod tests { fn non_zero_curve_point() { let b58 = r#""B62qkUHaJUHERZuCHQhXCQ8xsGBqyYSgjQsKnKN5HhSJecakuJ4pYyk""#; - let v = serde_json::from_str::(&b58) + let v = serde_json::from_str::(b58) .unwrap() .into_inner(); - assert_eq!(v.is_odd, false); + assert!(!v.is_odd); assert_eq!( &hex::encode(&v.x), "3c2b5b48c22dc8b8c9d2c9d76a2ceaaf02beabb364301726c3f8e989653af513" @@ -590,7 +590,7 @@ impl<'de> Deserialize<'de> for PicklesProofProofsVerified2ReprStableV2StatementF A: serde::de::SeqAccess<'de>, { match seq.next_element::()? { - Some(v) if &v == SHIFTED_VALUE => {} + Some(v) if v == SHIFTED_VALUE => {} Some(v) => { return Err(serde::de::Error::custom(format!( "expecting `{SHIFTED_VALUE}`, got `{v}`" @@ -602,7 +602,7 @@ impl<'de> Deserialize<'de> for PicklesProofProofsVerified2ReprStableV2StatementF Some(v) => { Ok(PicklesProofProofsVerified2ReprStableV2StatementFp::ShiftedValue(v)) } - None => return Err(serde::de::Error::custom("expecting a value")), + None => Err(serde::de::Error::custom("expecting a value")), } } } @@ -796,6 +796,13 @@ impl<'de> Deserialize<'de> for SgnStableV1 { Ok(v) } + fn visit_str(self, v: &str) -> Result + where + E: serde::de::Error, + { + Ok(v.to_string()) + } + fn visit_seq(self, mut seq: A) -> Result where A: serde::de::SeqAccess<'de>, @@ -883,6 +890,7 @@ pub struct TokenFeeExcess { pub amount: SignedAmount, } +#[allow(clippy::derivable_impls)] impl Default for NonZeroCurvePointUncompressedStableV1 { fn default() -> Self { Self { diff --git a/mina-p2p-messages/src/versioned.rs b/mina-p2p-messages/src/versioned.rs index fa478af64..105998b9e 100644 --- a/mina-p2p-messages/src/versioned.rs +++ b/mina-p2p-messages/src/versioned.rs @@ -85,7 +85,7 @@ where } } - const FIELDS: &'static [&'static str] = &["version", "t"]; + const FIELDS: &[&str] = &["version", "t"]; deserializer .deserialize_struct( "MakeVersioned", @@ -172,7 +172,7 @@ mod tests { T: BinProtWrite, { let mut buf = Vec::new(); - let _ = t.binprot_write(&mut buf)?; + t.binprot_write(&mut buf)?; Ok(buf) } diff --git a/mina-p2p-messages/tests/binprot-read.rs b/mina-p2p-messages/tests/binprot-read.rs index ca30874e0..776a5e5d9 100644 --- a/mina-p2p-messages/tests/binprot-read.rs +++ b/mina-p2p-messages/tests/binprot-read.rs @@ -10,7 +10,7 @@ mod utils; fn external_transition_v1() { utils::for_all("v1/gossip/external-transition", |_, encoded| { utils::assert_binprot_read::( - &encoded, + encoded, ) }) .unwrap(); @@ -19,7 +19,7 @@ fn external_transition_v1() { #[test] fn snark_pool_diff() { utils::for_all("v1/gossip/snark-pool-diff", |_, encoded| { - utils::assert_binprot_read::(&encoded) + utils::assert_binprot_read::(encoded) }) .unwrap(); } @@ -28,7 +28,7 @@ fn snark_pool_diff() { fn tx_pool_diff() { utils::for_all("v1/gossip/tx-pool-diff", |_, encoded| { utils::assert_binprot_read::( - &encoded, + encoded, ) }) .unwrap(); @@ -39,7 +39,7 @@ fn tx_pool_diff() { fn gossip_v2() { utils::for_all("v2/gossip", |_, encoded| { use mina_p2p_messages::gossip::GossipNetMessageV2; - utils::assert_binprot_read::(&encoded) + utils::assert_binprot_read::(encoded) }) .unwrap(); } diff --git a/mina-p2p-messages/tests/decode_alloc.rs b/mina-p2p-messages/tests/decode_alloc.rs index 6d8631059..cd6dc346c 100644 --- a/mina-p2p-messages/tests/decode_alloc.rs +++ b/mina-p2p-messages/tests/decode_alloc.rs @@ -97,7 +97,7 @@ mod utils; fn collect_incoming_rpcs() { let mut queries = BTreeMap::new(); utils::for_all("v2/rpc/catchup-messages/out", |path, mut bytes| { - let modified = fs::metadata(&path).unwrap().modified().unwrap(); + let modified = fs::metadata(path).unwrap().modified().unwrap(); while !bytes.is_empty() { if let Some(b) = bytes.strip_prefix(b"\x07\x00\x00\x00\x00\x00\x00\x00\x02\xfd\x52\x50\x43\x00\x01") @@ -115,7 +115,7 @@ fn collect_incoming_rpcs() { let mut pairs = Vec::new(); utils::for_all("v2/rpc/catchup-messages/in", |path, mut bytes| { - let modified = fs::metadata(&path).unwrap().modified().unwrap(); + let modified = fs::metadata(path).unwrap().modified().unwrap(); while !bytes.is_empty() { if let Some(b) = bytes.strip_prefix(b"\x07\x00\x00\x00\x00\x00\x00\x00\x02\xfd\x52\x50\x43\x00\x01") diff --git a/mina-p2p-messages/tests/jsonify.rs b/mina-p2p-messages/tests/jsonify.rs index 1a0684a64..4013f0a30 100644 --- a/mina-p2p-messages/tests/jsonify.rs +++ b/mina-p2p-messages/tests/jsonify.rs @@ -15,7 +15,7 @@ fn jsonify_rpc_menu() { let mut p = data.as_slice(); let response = Message::<::Response>::binprot_read(&mut p).unwrap(); - let response_json = serde_json::to_value(&response).unwrap(); + let response_json = serde_json::to_value(response).unwrap(); let expected_json = serde_json::json!( { "Response": { diff --git a/mina-p2p-messages/tests/rpc-read.rs b/mina-p2p-messages/tests/rpc-read.rs index 69fdb3322..34c59d604 100644 --- a/mina-p2p-messages/tests/rpc-read.rs +++ b/mina-p2p-messages/tests/rpc-read.rs @@ -132,7 +132,7 @@ fn make_rpc_v2() { } let mut mapping: BTreeMap = BTreeMap::new(); utils::for_all("rpc-v2", |_, encoded| { - utils::stream_read_with::(&encoded, |header, slice| match header { + utils::stream_read_with::(encoded, |header, slice| match header { Ok(MessageHeader::Heartbeat) => {} Ok(MessageHeader::Query(q)) => { let t = mapping.entry(q.id).or_default(); @@ -198,7 +198,7 @@ fn debugger_to_wire() { println!("{tag}:{ver}"); File::create(path) .and_then(|mut f| { - f.write(&encoded[..1])?; + f.write_all(&encoded[..1])?; f.write_all(p)?; Ok(f) }) diff --git a/node/build.rs b/node/build.rs index 00c46ca5d..55336fa50 100644 --- a/node/build.rs +++ b/node/build.rs @@ -211,7 +211,7 @@ fn main() -> Result<(), Box> { let use_path = path .strip_prefix(crate_dir.file_name().unwrap()) .unwrap_or(path) - .into_iter() + .iter() .map(|v| v.to_str().unwrap().to_string()) .filter(|v| v != "src" && v != "node") .collect::>(); diff --git a/node/invariants/src/lib.rs b/node/invariants/src/lib.rs index 7726f3b4f..7112063a3 100644 --- a/node/invariants/src/lib.rs +++ b/node/invariants/src/lib.rs @@ -74,7 +74,7 @@ lazy_static::lazy_static! { /// List of invariants that need to be triggered if we see a given `ActionKind`. static ref INVARIANTS_BY_ACTION_KIND: Vec> = { let mut by_action_kind = Vec::new(); - by_action_kind.resize_with(ActionKind::COUNT as usize, || Vec::new()); + by_action_kind.resize_with(ActionKind::COUNT as usize, Vec::new); for invariant in Invariants::iter() { for action_kind in invariant.triggers() { let v = by_action_kind.get_mut(*action_kind as usize).unwrap(); @@ -98,7 +98,7 @@ impl Invariants { INVARIANTS_BY_ACTION_KIND .get(action_kind as usize) .unwrap() - .into_iter() + .iter() .map(|invariant| (*invariant, invariant.check(store, action))) } diff --git a/node/invariants/src/transition_frontier/only_syncs_to_better_blocks.rs b/node/invariants/src/transition_frontier/only_syncs_to_better_blocks.rs index 6be8a1712..91e3cffc7 100644 --- a/node/invariants/src/transition_frontier/only_syncs_to_better_blocks.rs +++ b/node/invariants/src/transition_frontier/only_syncs_to_better_blocks.rs @@ -57,24 +57,22 @@ impl Invariant for TransitionFrontierOnlySyncsToBetterBlocks { } // make sure new best tip target is better than current best tip. - match (target_best_tip, best_tip) { - (Some(target_best_tip), Some(best_tip)) => { - checked = true; - if !consensus_take( - best_tip.consensus_state(), - target_best_tip.consensus_state(), + if let (Some(target_best_tip), Some(best_tip)) = (target_best_tip, best_tip) { + checked = true; + if !consensus_take( + best_tip.consensus_state(), + target_best_tip.consensus_state(), + best_tip.hash(), + target_best_tip.hash(), + ) { + return InvariantResult::Violation(format!( + "best tip target not better than current best tip!\nprev({}): {}\nnew({}): {}", best_tip.hash(), + serde_json::to_string(best_tip.consensus_state()).unwrap(), target_best_tip.hash(), - ) { - return InvariantResult::Violation(format!("best tip target not better than current best tip!\nprev({}): {}\nnew({}): {}", - best_tip.hash(), - serde_json::to_string(best_tip.consensus_state()).unwrap(), - target_best_tip.hash(), - serde_json::to_string(target_best_tip.consensus_state()).unwrap(), - )); - } + serde_json::to_string(target_best_tip.consensus_state()).unwrap(), + )); } - _ => {} } // make sure new best tip target is better than the prev one. diff --git a/node/native/src/block_producer/mod.rs b/node/native/src/block_producer/mod.rs index 271a13890..5ba216da7 100644 --- a/node/native/src/block_producer/mod.rs +++ b/node/native/src/block_producer/mod.rs @@ -62,7 +62,7 @@ pub fn prove( let provers = get_provers(); let res = generate_block_proof(BlockParams { - input: &*input, + input, block_step_prover: &provers.block_step_prover, block_wrap_prover: &provers.block_wrap_prover, tx_wrap_prover: &provers.tx_wrap_prover, @@ -86,7 +86,7 @@ impl node::service::BlockProducerService for crate::NodeService { let tx = self.event_sender.clone(); std::thread::spawn(move || { - let res = prove(&*input, false).map_err(|err| format!("{err:?}")); + let res = prove(&input, false).map_err(|err| format!("{err:?}")); let _ = tx.send(BlockProducerEvent::BlockProve(block_hash, res).into()); }); } diff --git a/node/native/src/block_producer/vrf_evaluator.rs b/node/native/src/block_producer/vrf_evaluator.rs index 981658a6f..7179bfcfa 100644 --- a/node/native/src/block_producer/vrf_evaluator.rs +++ b/node/native/src/block_producer/vrf_evaluator.rs @@ -26,7 +26,7 @@ pub fn vrf_evaluator( vrf_evaluator_input.epoch_seed.clone(), pub_key.to_string(), vrf_evaluator_input.global_slot, - index.clone(), + *index, (*stake).into(), vrf_evaluator_input.total_currency.into(), ); diff --git a/node/native/src/ext_snark_worker.rs b/node/native/src/ext_snark_worker.rs index 7bb39c376..068e2d9b8 100644 --- a/node/native/src/ext_snark_worker.rs +++ b/node/native/src/ext_snark_worker.rs @@ -332,7 +332,7 @@ impl ExternalSnarkWorkerFacade { let event_sender_clone = event_sender.clone(); tokio::spawn(async move { if let Err(err) = stderr_reader(child_stderr).await { - send_event!(event_sender_clone, SnarkerError::from(err).into()); + send_event!(event_sender_clone, err.into()); } }); @@ -343,11 +343,8 @@ impl ExternalSnarkWorkerFacade { } else { send_event!(event_sender, ExternalSnarkWorkerEvent::Killed); } - return; - } - _ = child.wait() => { - return } + _ = child.wait() => {} }; } }); diff --git a/node/native/src/graphql.rs b/node/native/src/graphql.rs index 9aceb20e4..778cf53a3 100644 --- a/node/native/src/graphql.rs +++ b/node/native/src/graphql.rs @@ -9,6 +9,8 @@ struct Context(super::RpcSender); impl juniper::Context for Context {} +// TODO: I'm not sure whether changing the acronyms breaks anything, check +#[allow(clippy::upper_case_acronyms)] #[derive(Clone, Copy, Debug, GraphQLEnum)] enum SyncStatus { CONNECTING, diff --git a/node/native/src/http_server.rs b/node/native/src/http_server.rs index 64db839a2..8463b8875 100644 --- a/node/native/src/http_server.rs +++ b/node/native/src/http_server.rs @@ -165,7 +165,7 @@ pub async fn run(port: u16, rpc_sender: super::RpcSender) { .then(move |query: ActionQueryParams| { let rpc_sender_clone = rpc_sender_clone.clone(); async move { - let id_filter = query.id.as_ref().map(|s| s.as_str()); + let id_filter = query.id.as_deref(); let result: RpcActionStatsGetResponse = rpc_sender_clone .oneshot_request(RpcRequest::ActionStatsGet(match id_filter { None => ActionStatsQuery::SinceStart, @@ -358,8 +358,7 @@ pub async fn run(port: u16, rpc_sender: super::RpcSender) { }, |resp| match resp { RpcSnarkerJobSpecResponse::Ok(spec) - if accept.as_ref().map(String::as_str) - == Some("application/octet-stream") => + if accept.as_deref() == Some("application/octet-stream") => { JsonOrBinary::binary(spec) } diff --git a/node/native/src/lib.rs b/node/native/src/lib.rs index d7f4ad753..98868711d 100644 --- a/node/native/src/lib.rs +++ b/node/native/src/lib.rs @@ -1,3 +1,5 @@ +#![allow(clippy::large_enum_variant)] + pub mod block_producer; pub mod ext_snark_worker; pub mod graphql; diff --git a/node/native/src/rpc.rs b/node/native/src/rpc.rs index e0d711797..57b86817d 100644 --- a/node/native/src/rpc.rs +++ b/node/native/src/rpc.rs @@ -52,6 +52,12 @@ impl RpcService { } } +impl Default for RpcService { + fn default() -> Self { + Self::new() + } +} + impl NodeService { /// Channel for sending the rpc request to state machine. #[allow(dead_code)] @@ -113,10 +119,10 @@ macro_rules! state_field_filter { /// assert_eq!(filter, None); /// ``` fn strip_root_field<'a>(filter: &'a str, field: &str) -> Option<&'a str> { - let strip_root = |f: &'a str| f.strip_prefix("$"); + let strip_root = |f: &'a str| f.strip_prefix('$'); let field_char = |c: char| c.is_alphabetic() || c == '_'; let strip_dot_field = |f: &'a str| { - f.strip_prefix(".").and_then(|f| { + f.strip_prefix('.').and_then(|f| { f.strip_prefix(field) .and_then(|f| (!f.starts_with(field_char)).then_some(f)) }) @@ -129,27 +135,6 @@ fn strip_root_field<'a>(filter: &'a str, field: &str) -> Option<&'a str> { strip_root(filter).and_then(|f| strip_dot_field(f).or_else(|| strip_index_field(f))) } -#[cfg(test)] -mod tests { - use super::strip_root_field; - - #[test] - fn strip_root_field_test() { - for (filter, expected) in [ - ("$.field", Some("")), - ("$['field']", Some("")), - ("$.field.another", Some(".another")), - ("$['field'].another", Some(".another")), - ("$.another", None), - ("$.field_1", None), - ("$.fields", None), - ] { - let actual = strip_root_field(filter, "field"); - assert_eq!(actual, expected) - } - } -} - fn optimize_filtered_state( state: &State, filter: &str, @@ -286,3 +271,24 @@ impl node::core::invariants::InvariantService for NodeService { &mut self.invariants_state } } + +#[cfg(test)] +mod tests { + use super::strip_root_field; + + #[test] + fn strip_root_field_test() { + for (filter, expected) in [ + ("$.field", Some("")), + ("$['field']", Some("")), + ("$.field.another", Some(".another")), + ("$['field'].another", Some(".another")), + ("$.another", None), + ("$.field_1", None), + ("$.fields", None), + ] { + let actual = strip_root_field(filter, "field"); + assert_eq!(actual, expected) + } + } +} diff --git a/node/native/src/service.rs b/node/native/src/service.rs index 2f67e58e8..d82a0cd13 100644 --- a/node/native/src/service.rs +++ b/node/native/src/service.rs @@ -97,7 +97,7 @@ impl redux::TimeService for NodeService { self.replayer .as_ref() .map(|v| v.next_monotonic_time()) - .unwrap_or_else(|| redux::Instant::now()) + .unwrap_or_else(redux::Instant::now) } } @@ -199,7 +199,7 @@ impl P2pServiceWebrtcWithLibp2p for NodeService { self.libp2p() .cmd_sender() - .send(Cmd::FindNode(peer_id.into())) + .send(Cmd::FindNode(peer_id)) .unwrap_or_default(); } @@ -210,7 +210,7 @@ impl P2pServiceWebrtcWithLibp2p for NodeService { .into_iter() .filter_map(|opts| { Some(( - opts.peer_id().clone().into(), + (*opts.peer_id()).into(), match opts { P2pConnectionOutgoingInitOpts::LibP2P(opts) => opts.to_maddr(), _ => return None, @@ -289,7 +289,7 @@ impl SnarkWorkVerifyService for NodeService { [Some(conv(v1)), Some(conv(v2))] } }) - .filter_map(|v| v) + .flatten() .collect::>(); let verifier_srs = verifier_srs.lock().expect("Failed to lock SRS"); if !ledger::proofs::verification::verify_transaction( diff --git a/node/native/src/tracing.rs b/node/native/src/tracing.rs index baed0987e..70304ab1d 100644 --- a/node/native/src/tracing.rs +++ b/node/native/src/tracing.rs @@ -72,9 +72,7 @@ pub fn initialize(max_log_level: Level) { //.with_timer(ReduxTimer) ; if max_log_level != Level::TRACE { - let subscriber = builder - .fmt_fields(TracingFieldFormatter::default()) - .finish(); + let subscriber = builder.fmt_fields(TracingFieldFormatter).finish(); tracing::subscriber::set_global_default(subscriber) } else { let subscriber = builder.finish(); diff --git a/node/src/account/secret_key.rs b/node/src/account/secret_key.rs index 4d9826c20..dda9113f8 100644 --- a/node/src/account/secret_key.rs +++ b/node/src/account/secret_key.rs @@ -88,7 +88,7 @@ impl fmt::Display for AccountSecretKey { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { // TODO: implement to_bytes for Keypair, and remove this ugly workaround let hex = self.0.to_hex(); - let mut bytes = hex::decode(&hex).expect("to_hex should return hex string"); + let mut bytes = hex::decode(hex).expect("to_hex should return hex string"); bytes.reverse(); bytes.insert(0, 1); let s = bs58::encode(&bytes) @@ -113,7 +113,7 @@ impl<'de> serde::Deserialize<'de> for AccountSecretKey { D: serde::Deserializer<'de>, { let b58: String = Deserialize::deserialize(deserializer)?; - Ok(b58.parse().map_err(|err| serde::de::Error::custom(err))?) + b58.parse().map_err(serde::de::Error::custom) } } diff --git a/node/src/block_producer/block_producer_reducer.rs b/node/src/block_producer/block_producer_reducer.rs index 2a710a346..11e869bad 100644 --- a/node/src/block_producer/block_producer_reducer.rs +++ b/node/src/block_producer/block_producer_reducer.rs @@ -178,7 +178,7 @@ impl BlockProducerEnabled { let proposed_protocol_version_opt = self.config.proposed_protocol_version.clone(); let ledger_proof_statement = ledger_proof_statement_from_emitted_proof( - emitted_ledger_proof.as_ref().map(|proof| &**proof), + emitted_ledger_proof.as_deref(), &pred_blockchain_state.ledger_proof_statement, ); diff --git a/node/src/block_producer/mod.rs b/node/src/block_producer/mod.rs index bdef05737..9c9a979fd 100644 --- a/node/src/block_producer/mod.rs +++ b/node/src/block_producer/mod.rs @@ -65,7 +65,7 @@ impl BlockProducerWonSlot { let winner_pub_key = AccountPublicKey::from( CompressedPubKey::from_address(&won_slot.winner_account).unwrap(), ); - let delegator = (winner_pub_key.into(), won_slot.account_index.clone()); + let delegator = (winner_pub_key.into(), won_slot.account_index); let global_slot = v2::ConsensusGlobalSlotStableV1 { slot_number: v2::MinaNumbersGlobalSlotSinceHardForkMStableV1::SinceHardFork( won_slot.global_slot.into(), diff --git a/node/src/block_producer/vrf_evaluator/block_producer_vrf_evaluator_state.rs b/node/src/block_producer/vrf_evaluator/block_producer_vrf_evaluator_state.rs index b69b41bb1..19d7ef03c 100644 --- a/node/src/block_producer/vrf_evaluator/block_producer_vrf_evaluator_state.rs +++ b/node/src/block_producer/vrf_evaluator/block_producer_vrf_evaluator_state.rs @@ -384,7 +384,7 @@ impl EpochData { impl From for EpochData { fn from(value: ConsensusProofOfStakeDataEpochDataStakingValueVersionedValueStableV1) -> Self { Self { - seed: value.seed.into(), + seed: value.seed, ledger: value.ledger.hash, delegator_table: Default::default(), total_currency: value.ledger.total_currency.as_u64(), @@ -395,7 +395,7 @@ impl From impl From for EpochData { fn from(value: ConsensusProofOfStakeDataEpochDataNextValueVersionedValueStableV1) -> Self { Self { - seed: value.seed.into(), + seed: value.seed, ledger: value.ledger.hash, delegator_table: Default::default(), total_currency: value.ledger.total_currency.as_u64(), diff --git a/node/src/block_producer/vrf_evaluator/mod.rs b/node/src/block_producer/vrf_evaluator/mod.rs index 69e2293ed..e7125e09e 100644 --- a/node/src/block_producer/vrf_evaluator/mod.rs +++ b/node/src/block_producer/vrf_evaluator/mod.rs @@ -56,7 +56,7 @@ pub struct VrfEvaluationOutputWithHash { impl std::fmt::Display for VrfEvaluationOutputWithHash { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - write!(f, "{} ", self.staking_ledger_hash.to_string())?; + write!(f, "{} ", self.staking_ledger_hash)?; match &self.evaluation_result { VrfEvaluationOutput::SlotWon(won_slot) => { write!(f, "SlotWon {}", won_slot.global_slot) diff --git a/node/src/consensus/consensus_reducer.rs b/node/src/consensus/consensus_reducer.rs index 7f5a9a1f6..edf8e7eab 100644 --- a/node/src/consensus/consensus_reducer.rs +++ b/node/src/consensus/consensus_reducer.rs @@ -34,7 +34,7 @@ impl ConsensusState { if let Some(block) = self.blocks.get_mut(hash) { block.status = ConsensusBlockStatus::SnarkVerifyPending { time: meta.time(), - req_id: req_id.clone(), + req_id: *req_id, }; } } @@ -83,7 +83,7 @@ impl ConsensusState { let (take, why) = short_range_fork_take( tip_cs, candidate_cs, - &tip.hash, + tip.hash, candidate_hash, ); if take { @@ -158,9 +158,7 @@ impl ConsensusState { // keep at most latest 32 candidate blocks. let blocks_to_keep = (0..32) .scan(best_tip_hash, |block_hash, _| { - let Some(block_state) = blocks.remove(block_hash) else { - return None; - }; + let block_state = blocks.remove(block_hash)?; let block_hash = match block_state.status.compared_with() { None => block_hash.clone(), Some(compared_with) => { diff --git a/node/src/consensus/consensus_state.rs b/node/src/consensus/consensus_state.rs index 5557732db..ca0366458 100644 --- a/node/src/consensus/consensus_state.rs +++ b/node/src/consensus/consensus_state.rs @@ -140,7 +140,7 @@ impl ConsensusState { pub fn best_tip(&self) -> Option> { self.best_tip.as_ref().and_then(|hash| { - let block = &*self.blocks.get(hash)?; + let block = self.blocks.get(hash)?; Some(BlockRef { hash, header: &block.block.header, @@ -152,7 +152,7 @@ impl ConsensusState { pub fn previous_best_tip(&self) -> Option> { self.best_tip.as_ref().and_then(|hash| { - let block = &*self.blocks.get(hash)?; + let block = self.blocks.get(hash)?; let prev_hash = block.status.compared_with()?; let prev = self.blocks.get(prev_hash)?; Some(BlockRef { @@ -187,6 +187,12 @@ impl ConsensusState { } } +impl Default for ConsensusState { + fn default() -> Self { + Self::new() + } +} + #[derive(Serialize, Debug, Clone, Copy)] pub struct BlockRef<'a> { pub hash: &'a StateHash, diff --git a/node/src/external_snark_worker/external_snark_worker_effects.rs b/node/src/external_snark_worker/external_snark_worker_effects.rs index 8c1ffc424..5eac32afc 100644 --- a/node/src/external_snark_worker/external_snark_worker_effects.rs +++ b/node/src/external_snark_worker/external_snark_worker_effects.rs @@ -63,7 +63,6 @@ pub fn external_snark_worker_effects( }; if let Err(err) = store.service().submit(input) { store.dispatch(ExternalSnarkWorkerAction::WorkError { error: err.into() }); - return; } } ExternalSnarkWorkerAction::WorkResult { result } => { @@ -91,10 +90,9 @@ pub fn external_snark_worker_effects( ExternalSnarkWorkerAction::CancelWork => { if let Err(err) = store.service().cancel() { store.dispatch(ExternalSnarkWorkerAction::Error { - error: err.into(), + error: err, permanent: true, }); - return; } } ExternalSnarkWorkerAction::WorkCancelled => { diff --git a/node/src/external_snark_worker/external_snark_worker_impls.rs b/node/src/external_snark_worker/external_snark_worker_impls.rs index 101097bcc..2ce00bfb2 100644 --- a/node/src/external_snark_worker/external_snark_worker_impls.rs +++ b/node/src/external_snark_worker/external_snark_worker_impls.rs @@ -86,7 +86,7 @@ fn with_merged_statement( let ledger_stmt2 = Statement::<()>::from(&ledger_proof2.statement); let merged_stmt = ledger_stmt1 .merge(&ledger_stmt2) - .map_err(|err| SnarkWorkSpecError::MergeStatementError(err))?; + .map_err(SnarkWorkSpecError::MergeStatementError)?; Ok( SnarkWorkerWorkerRpcsVersionedGetWorkV2TResponseA0Single::Merge(Box::new(( (&merged_stmt).into(), diff --git a/node/src/external_snark_worker/external_snark_worker_state.rs b/node/src/external_snark_worker/external_snark_worker_state.rs index d4ad3404f..775b25d19 100644 --- a/node/src/external_snark_worker/external_snark_worker_state.rs +++ b/node/src/external_snark_worker/external_snark_worker_state.rs @@ -40,10 +40,7 @@ impl ExternalSnarkWorkers { } pub fn is_idle(&self) -> bool { - match self.0.state { - ExternalSnarkWorkerState::Idle => true, - _ => false, - } + matches!(self.0.state, ExternalSnarkWorkerState::Idle) } pub fn has_idle(&self) -> bool { diff --git a/node/src/ledger/ledger_service.rs b/node/src/ledger/ledger_service.rs index 29840cacc..2220c2d92 100644 --- a/node/src/ledger/ledger_service.rs +++ b/node/src/ledger/ledger_service.rs @@ -147,9 +147,9 @@ impl LedgerCtx { /// Returns a mutable reference to the [StagedLedger] with the specified `hash` if it exists or `None` otherwise. fn staged_ledger_mut(&mut self, hash: &LedgerHash) -> Option<&mut StagedLedger> { - match self.staged_ledgers.get_mut(&hash) { + match self.staged_ledgers.get_mut(hash) { Some(v) => Some(v), - None => self.sync.staged_ledger_mut(&hash), + None => self.sync.staged_ledger_mut(hash), } } @@ -197,7 +197,7 @@ impl LedgerCtx { .ok_or_else(|| { format!( "push_snarked_ledger: could not find old root snarked ledger: {}", - old_root_snarked_ledger_hash.to_string(), + old_root_snarked_ledger_hash, ) })?; let mut mt = root_snarked_ledger.make_child(); @@ -245,7 +245,7 @@ impl LedgerCtx { } else { Err(format!( "Failed to find protocol state for state hash: {}", - state_hash.to_string() + state_hash )) } }; @@ -255,7 +255,7 @@ impl LedgerCtx { .ok_or_else(|| { format!( "Failed to find staged ledger with hash: {}", - new_root_staged_ledger_hash.to_string() + new_root_staged_ledger_hash ) })? .scan_state(); @@ -276,8 +276,7 @@ impl LedgerCtx { if expected_hash != &obtained_hash { return Err(format!( "Expected to obtain snarked root ledger hash {} but got {}", - expected_hash.to_string(), - obtained_hash.to_string() + expected_hash, obtained_hash )); } @@ -298,9 +297,7 @@ impl LedgerCtx { let mut accounts = Vec::new(); mask.iter(|account| { - if filter(&account.public_key) - || account.delegate.as_ref().map_or(false, |key| filter(key)) - { + if filter(&account.public_key) || account.delegate.as_ref().map_or(false, &mut filter) { accounts.push(( account.id(), account.delegate.clone(), @@ -346,7 +343,7 @@ impl LedgerSyncState { } fn staged_ledger_mut(&mut self, hash: &LedgerHash) -> Option<&mut StagedLedger> { - self.staged_ledgers.get_mut(&hash) + self.staged_ledgers.get_mut(hash) } } @@ -483,8 +480,8 @@ impl TransitionFrontierService for T { ); let mut staged_ledger = self .ctx_mut() - .staged_ledger_mut(&pred_block.staged_ledger_hash()) - .ok_or_else(|| "parent staged ledger missing")? + .staged_ledger_mut(pred_block.staged_ledger_hash()) + .ok_or("parent staged ledger missing")? .clone(); let global_slot = block.global_slot_since_genesis(); @@ -522,7 +519,7 @@ impl TransitionFrontierService for T { if &ledger_hashes != expected_ledger_hashes { let staged_ledger = self .ctx_mut() - .staged_ledger_mut(&pred_block.staged_ledger_hash()) + .staged_ledger_mut(pred_block.staged_ledger_hash()) .unwrap(); // We already know the ledger exists, see the same call a few lines above match dump_application_to_file(staged_ledger, block.clone(), pred_block) { @@ -765,8 +762,8 @@ impl BlockProducerLedgerService for T { ) -> Result { let mut staged_ledger = self .ctx_mut() - .staged_ledger_mut(&pred_block.staged_ledger_hash()) - .ok_or_else(|| "parent staged ledger missing")? + .staged_ledger_mut(pred_block.staged_ledger_hash()) + .ok_or("parent staged ledger missing")? .clone(); // calculate merkle root hash, otherwise `MinaBasePendingCoinbaseStableV2::from` fails. diff --git a/node/src/lib.rs b/node/src/lib.rs index 2e0aed5c6..2ec57efc6 100644 --- a/node/src/lib.rs +++ b/node/src/lib.rs @@ -1,3 +1,7 @@ +#![allow(clippy::large_enum_variant)] +#![allow(clippy::too_many_arguments)] +#![allow(clippy::type_complexity)] + pub use openmina_core as core; #[macro_use] diff --git a/node/src/logger/logger_effects.rs b/node/src/logger/logger_effects.rs index 11ecd7625..d432cdd06 100644 --- a/node/src/logger/logger_effects.rs +++ b/node/src/logger/logger_effects.rs @@ -664,8 +664,8 @@ pub fn logger_effects(store: &Store, action: ActionWithMetaRef<'_ }, _ => {} }, - P2pNetworkAction::Pnet(action) => match action { - P2pNetworkPnetAction::SetupNonce(action) => { + P2pNetworkAction::Pnet(action) => { + if let P2pNetworkPnetAction::SetupNonce(action) = action { openmina_core::log::info!( meta.time(); node_id = node_id, @@ -674,8 +674,7 @@ pub fn logger_effects(store: &Store, action: ActionWithMetaRef<'_ incoming = action.incoming, ) } - _ => {} - }, + } P2pNetworkAction::Select(action) => match action { P2pNetworkSelectAction::Init(action) => match action.kind { SelectKind::Authentication => { @@ -984,53 +983,50 @@ pub fn logger_effects(store: &Store, action: ActionWithMetaRef<'_ } } } - Action::Snark(a) => match a { - SnarkAction::WorkVerify(a) => match a { - SnarkWorkVerifyAction::Init { - req_id, - batch, - sender, - } => { - openmina_core::log::info!( - meta.time(); - node_id = node_id, - kind = kind.to_string(), - summary = format!("id: {}, batch size: {}", req_id, batch.len()), - peer_id = sender, - rpc_id = req_id.to_string(), - trace_batch = serde_json::to_string(&batch.iter().map(|v| v.job_id()).collect::>()).ok() - ); - } - SnarkWorkVerifyAction::Error { req_id, .. } => { - let Some(req) = store.state().snark.work_verify.jobs.get(*req_id) else { - return; - }; - openmina_core::log::warn!( - meta.time(); - node_id = node_id, - kind = kind.to_string(), - summary = format!("id: {}, batch size: {}", req_id, req.batch().len()), - peer_id = req.sender(), - rpc_id = req_id.to_string(), - trace_batch = serde_json::to_string(&req.batch().iter().map(|v| v.job_id()).collect::>()).ok() - ); - } - SnarkWorkVerifyAction::Success { req_id } => { - let Some(req) = store.state().snark.work_verify.jobs.get(*req_id) else { - return; - }; - openmina_core::log::info!( - meta.time(); - node_id = node_id, - kind = kind.to_string(), - summary = format!("id: {}, batch size: {}", req_id, req.batch().len()), - peer_id = req.sender(), - rpc_id = req_id.to_string(), - trace_batch = serde_json::to_string(&req.batch().iter().map(|v| v.job_id()).collect::>()).ok() - ); - } - _ => {} - }, + Action::Snark(SnarkAction::WorkVerify(a)) => match a { + SnarkWorkVerifyAction::Init { + req_id, + batch, + sender, + } => { + openmina_core::log::info!( + meta.time(); + node_id = node_id, + kind = kind.to_string(), + summary = format!("id: {}, batch size: {}", req_id, batch.len()), + peer_id = sender, + rpc_id = req_id.to_string(), + trace_batch = serde_json::to_string(&batch.iter().map(|v| v.job_id()).collect::>()).ok() + ); + } + SnarkWorkVerifyAction::Error { req_id, .. } => { + let Some(req) = store.state().snark.work_verify.jobs.get(*req_id) else { + return; + }; + openmina_core::log::warn!( + meta.time(); + node_id = node_id, + kind = kind.to_string(), + summary = format!("id: {}, batch size: {}", req_id, req.batch().len()), + peer_id = req.sender(), + rpc_id = req_id.to_string(), + trace_batch = serde_json::to_string(&req.batch().iter().map(|v| v.job_id()).collect::>()).ok() + ); + } + SnarkWorkVerifyAction::Success { req_id } => { + let Some(req) = store.state().snark.work_verify.jobs.get(*req_id) else { + return; + }; + openmina_core::log::info!( + meta.time(); + node_id = node_id, + kind = kind.to_string(), + summary = format!("id: {}, batch size: {}", req_id, req.batch().len()), + peer_id = req.sender(), + rpc_id = req_id.to_string(), + trace_batch = serde_json::to_string(&req.batch().iter().map(|v| v.job_id()).collect::>()).ok() + ); + } _ => {} }, Action::TransitionFrontier(a) => match a { diff --git a/node/src/rpc/mod.rs b/node/src/rpc/mod.rs index edba1e70b..7dbd6fab8 100644 --- a/node/src/rpc/mod.rs +++ b/node/src/rpc/mod.rs @@ -416,8 +416,8 @@ pub mod discovery { impl From<(&P2pNetworkKadEntry, &P2pNetworkKadKey)> for RpcEntry { fn from((value, this_key): (&P2pNetworkKadEntry, &P2pNetworkKadKey)) -> Self { RpcEntry { - peer_id: value.peer_id.clone(), - libp2p: value.peer_id.clone().into(), + peer_id: value.peer_id, + libp2p: value.peer_id.into(), key: value.key.clone(), dist: this_key - &value.key, addrs: value.addrs.clone(), diff --git a/node/src/rpc/rpc_effects.rs b/node/src/rpc/rpc_effects.rs index 13a7203d8..f3e05524d 100644 --- a/node/src/rpc/rpc_effects.rs +++ b/node/src/rpc/rpc_effects.rs @@ -34,10 +34,9 @@ pub fn rpc_effects(store: &mut Store, action: RpcActionWithMeta) match action { RpcAction::GlobalStateGet { rpc_id, filter } => { - let _ = store.service.respond_state_get( - rpc_id, - (store.state.get(), filter.as_ref().map(String::as_str)), - ); + let _ = store + .service + .respond_state_get(rpc_id, (store.state.get(), filter.as_deref())); } RpcAction::ActionStatsGet { rpc_id, query } => match query { ActionStatsQuery::SinceStart => { @@ -178,7 +177,7 @@ pub fn rpc_effects(store: &mut Store, action: RpcActionWithMeta) } }; RpcPeerInfo { - peer_id: peer_id.clone(), + peer_id: *peer_id, connection_status, address: state.dial_opts.as_ref().map(|opts| opts.to_string()), best_tip: best_tip.map(|bt| bt.hash.clone()), @@ -214,7 +213,6 @@ pub fn rpc_effects(store: &mut Store, action: RpcActionWithMeta) store.dispatch(RpcAction::Finish { rpc_id }); } RpcAction::P2pConnectionIncomingInit { rpc_id, opts } => { - let rpc_id = rpc_id; match store.state().p2p.incoming_accept(opts.peer_id, &opts.offer) { Ok(_) => { store.dispatch(P2pConnectionIncomingAction::Init { @@ -303,13 +301,14 @@ pub fn rpc_effects(store: &mut Store, action: RpcActionWithMeta) }; let mut scan_state = service.scan_state_summary(block.staged_ledger_hash().clone()); - scan_state.iter_mut().flatten().for_each(|job| match job { - RpcScanStateSummaryScanStateJob::Todo { + scan_state.iter_mut().flatten().for_each(|job| { + if let RpcScanStateSummaryScanStateJob::Todo { job_id, bundle_job_id, job: kind, seq_no, - } => { + } = job + { let Some(data) = snark_pool.get(bundle_job_id) else { return; }; @@ -333,7 +332,6 @@ pub fn rpc_effects(store: &mut Store, action: RpcActionWithMeta) snark, }; } - _ => {} }); Some(RpcScanStateSummary { block: block_summary, @@ -420,7 +418,6 @@ pub fn rpc_effects(store: &mut Store, action: RpcActionWithMeta) store.dispatch(SnarkPoolAction::CommitmentCreate { job_id }); } RpcAction::SnarkerJobSpec { rpc_id, job_id } => { - let job_id = job_id; let Some(job) = store.state().snark_pool.get(&job_id) else { if store .service() @@ -458,7 +455,7 @@ pub fn rpc_effects(store: &mut Store, action: RpcActionWithMeta) .respond_snarker_job_spec(rpc_id, input) .is_err() { - return; + // TODO: log? } } RpcAction::SnarkerWorkersGet { rpc_id } => { @@ -468,7 +465,7 @@ pub fn rpc_effects(store: &mut Store, action: RpcActionWithMeta) .respond_snarker_workers(rpc_id, vec![the_only.into()]) .is_err() { - return; + // TODO: log? } } RpcAction::HealthCheck { rpc_id } => { @@ -538,7 +535,7 @@ pub fn rpc_effects(store: &mut Store, action: RpcActionWithMeta) .network .scheduler .discovery_state() - .and_then(|discovery_state| (&discovery_state.bootstrap_stats()).cloned()); + .and_then(|discovery_state| (discovery_state.bootstrap_stats()).cloned()); respond_or_log!( store .service() diff --git a/node/src/rpc/rpc_state.rs b/node/src/rpc/rpc_state.rs index d63e769c8..6f49ade0a 100644 --- a/node/src/rpc/rpc_state.rs +++ b/node/src/rpc/rpc_state.rs @@ -53,3 +53,9 @@ impl RpcState { } } } + +impl Default for RpcState { + fn default() -> Self { + Self::new() + } +} diff --git a/node/src/snark_pool/candidate/snark_pool_candidate_effects.rs b/node/src/snark_pool/candidate/snark_pool_candidate_effects.rs index ce963e300..6aace828b 100644 --- a/node/src/snark_pool/candidate/snark_pool_candidate_effects.rs +++ b/node/src/snark_pool/candidate/snark_pool_candidate_effects.rs @@ -59,7 +59,7 @@ pub fn snark_pool_candidate_effects( .range(..) .map(|(_, v)| (v.order, &v.id)) .collect::>(); - let job_ids_ordered_iter = job_id_orders.into_iter().map(|(_, id)| id); + let job_ids_ordered_iter = job_id_orders.into_values(); let batch = state .snark_pool .candidates diff --git a/node/src/snark_pool/candidate/snark_pool_candidate_state.rs b/node/src/snark_pool/candidate/snark_pool_candidate_state.rs index 5370fd8f3..756e4321c 100644 --- a/node/src/snark_pool/candidate/snark_pool_candidate_state.rs +++ b/node/src/snark_pool/candidate/snark_pool_candidate_state.rs @@ -136,7 +136,7 @@ impl SnarkPoolCandidatesState { *last_ord = Some(ord); Some(Some((peer_id, job_id.clone()))) }) - .filter_map(|v| v) + .flatten() .collect() } @@ -149,7 +149,7 @@ impl SnarkPoolCandidatesState { ) { if let Some(state) = self .by_peer - .get_mut(&peer_id) + .get_mut(peer_id) .and_then(|jobs| jobs.get_mut(job_id)) { if let SnarkPoolCandidateState::InfoReceived { info, .. } = state { @@ -324,6 +324,12 @@ impl SnarkPoolCandidatesState { } } +impl Default for SnarkPoolCandidatesState { + fn default() -> Self { + Self::new() + } +} + impl SnarkPoolCandidateState { pub fn fee(&self) -> u64 { match self { diff --git a/node/src/snark_pool/snark_pool_reducer.rs b/node/src/snark_pool/snark_pool_reducer.rs index 569c67d61..2f8cdb074 100644 --- a/node/src/snark_pool/snark_pool_reducer.rs +++ b/node/src/snark_pool/snark_pool_reducer.rs @@ -86,7 +86,7 @@ impl SnarkPoolState { self.last_check_timeouts = meta.time(); } SnarkPoolAction::JobCommitmentTimeout { job_id } => { - self.remove_commitment(&job_id); + self.remove_commitment(job_id); } } } diff --git a/node/src/snark_pool/snark_pool_state.rs b/node/src/snark_pool/snark_pool_state.rs index c9c7dd8e0..f8e6f6576 100644 --- a/node/src/snark_pool/snark_pool_state.rs +++ b/node/src/snark_pool/snark_pool_state.rs @@ -102,7 +102,7 @@ impl SnarkPoolState { pub fn remove_commitment(&mut self, id: &SnarkJobId) -> Option { let index = self.by_ledger_hash_index.get(id)?; - self.list.get_mut(&index)?.commitment.take() + self.list.get_mut(index)?.commitment.take() } pub fn retain(&mut self, mut get_new_job_order: F) @@ -127,10 +127,7 @@ impl SnarkPoolState { }); } - pub fn range<'a, R>( - &'a self, - range: R, - ) -> impl 'a + DoubleEndedIterator + pub fn range(&self, range: R) -> impl DoubleEndedIterator where R: RangeBounds, { @@ -176,11 +173,8 @@ impl SnarkPoolState { .map(|(id, _)| id) } - pub fn available_jobs_iter<'a>(&'a self) -> impl 'a + Iterator { - self.list - .iter() - .map(|(_, job)| job) - .filter(|job| job.is_available()) + pub fn available_jobs_iter(&self) -> impl Iterator { + self.list.values().filter(|job| job.is_available()) } pub fn available_jobs_with_highest_priority(&self, n: usize) -> Vec<&JobState> { @@ -196,7 +190,7 @@ impl SnarkPoolState { }) } - pub fn completed_snarks_iter<'a>(&'a self) -> impl 'a + Iterator { + pub fn completed_snarks_iter(&self) -> impl Iterator { self.list .iter() .filter_map(|(_, job)| job.snark.as_ref()) @@ -221,6 +215,12 @@ impl SnarkPoolState { } } +impl Default for SnarkPoolState { + fn default() -> Self { + Self::new() + } +} + impl fmt::Debug for SnarkPoolState { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_struct("JobCommitments") diff --git a/node/src/state.rs b/node/src/state.rs index d583a39bc..534c21f02 100644 --- a/node/src/state.rs +++ b/node/src/state.rs @@ -78,7 +78,7 @@ impl State { let best_tip = self.transition_frontier.best_tip()?; let best_tip_ms = u64::from(best_tip.timestamp()) / 1_000_000; let now_ms = u64::from(self.time()) / 1_000_000; - let ms = now_ms.saturating_sub(best_tip_ms) as u64; + let ms = now_ms.saturating_sub(best_tip_ms); let slots = ms / CONSTRAINT_CONSTANTS.block_window_duration_ms; Some(best_tip.global_slot() + (slots as u32)) diff --git a/node/src/stats/stats_actions.rs b/node/src/stats/stats_actions.rs index 293b52fea..3c4d3b82a 100644 --- a/node/src/stats/stats_actions.rs +++ b/node/src/stats/stats_actions.rs @@ -108,7 +108,7 @@ impl<'de> Deserialize<'de> for ActionStatsSnapshot { let list = (0..ActionKind::COUNT) .map(|i| { let kind = i.try_into().unwrap(); - m.remove(&kind).unwrap_or(ActionStatsForRanges::default()) + m.remove(&kind).unwrap_or_default() }) .collect(); Ok(Self(list)) diff --git a/node/src/stats/stats_sync.rs b/node/src/stats/stats_sync.rs index 9000a5d91..bc5d985cf 100644 --- a/node/src/stats/stats_sync.rs +++ b/node/src/stats/stats_sync.rs @@ -206,12 +206,12 @@ impl SyncStats { let ledgers = self .snapshots .back() - .map_or_else(|| Default::default(), |snapshot| snapshot.ledgers.clone()); + .map_or_else(Default::default, |snapshot| snapshot.ledgers.clone()); let mut resyncs = self .snapshots .back() - .map_or_else(|| Default::default(), |snapshot| snapshot.resyncs.clone()); + .map_or_else(Default::default, |snapshot| snapshot.resyncs.clone()); if let Some(prev_snapshot) = self.snapshots.back() { if prev_snapshot.synced.is_none() { @@ -301,7 +301,7 @@ impl SyncStats { }; snapshot.blocks = states - .into_iter() + .iter() .rev() // .take_while(|s| { // !s.is_apply_success() || s.block().map_or(false, |b| b.height() == root_height) diff --git a/node/src/transition_frontier/genesis/transition_frontier_genesis_config.rs b/node/src/transition_frontier/genesis/transition_frontier_genesis_config.rs index f41139f75..25b8961a8 100644 --- a/node/src/transition_frontier/genesis/transition_frontier_genesis_config.rs +++ b/node/src/transition_frontier/genesis/transition_frontier_genesis_config.rs @@ -83,8 +83,8 @@ impl GenesisConfig { (mask, load_result) } Self::BalancesDelegateTable { table, constants } => { - let table = table.into_iter().map(|(bp_balance, delegators)| { - let delegators = delegators.into_iter().copied(); + let table = table.iter().map(|(bp_balance, delegators)| { + let delegators = delegators.iter().copied(); (*bp_balance, delegators) }); let (mut mask, total_currency) = diff --git a/node/src/transition_frontier/sync/ledger/mod.rs b/node/src/transition_frontier/sync/ledger/mod.rs index 7c5eb4dcd..ff8edb65e 100644 --- a/node/src/transition_frontier/sync/ledger/mod.rs +++ b/node/src/transition_frontier/sync/ledger/mod.rs @@ -75,9 +75,9 @@ impl SyncLedgerTarget { /// In such case, we will reconstruct next_epoch_ledger anyways, /// once transition frontier's root will be first slot in the bew epoch. pub fn next_epoch(best_tip: &ArcBlockWithHash, root_block: &ArcBlockWithHash) -> Option { - if best_tip.next_epoch_ledger_hash() != root_block.next_epoch_ledger_hash() { - return None; - } else if best_tip.next_epoch_ledger_hash() == best_tip.genesis_ledger_hash() { + if best_tip.next_epoch_ledger_hash() != root_block.next_epoch_ledger_hash() + || best_tip.next_epoch_ledger_hash() == best_tip.genesis_ledger_hash() + { return None; } Some(Self { diff --git a/node/src/transition_frontier/sync/ledger/snarked/transition_frontier_sync_ledger_snarked_reducer.rs b/node/src/transition_frontier/sync/ledger/snarked/transition_frontier_sync_ledger_snarked_reducer.rs index 9445ef48e..dad992e19 100644 --- a/node/src/transition_frontier/sync/ledger/snarked/transition_frontier_sync_ledger_snarked_reducer.rs +++ b/node/src/transition_frontier/sync/ledger/snarked/transition_frontier_sync_ledger_snarked_reducer.rs @@ -124,7 +124,7 @@ impl TransitionFrontierSyncLedgerSnarkedState { return; }; let addr = address; - pending.remove(&addr); + pending.remove(addr); let (left, right) = hashes; let empty_hash = ledger_empty_hash_at_depth(addr.length() + 1); diff --git a/node/src/transition_frontier/sync/ledger/staged/transition_frontier_sync_ledger_staged_state.rs b/node/src/transition_frontier/sync/ledger/staged/transition_frontier_sync_ledger_staged_state.rs index dde97064c..17e282450 100644 --- a/node/src/transition_frontier/sync/ledger/staged/transition_frontier_sync_ledger_staged_state.rs +++ b/node/src/transition_frontier/sync/ledger/staged/transition_frontier_sync_ledger_staged_state.rs @@ -134,7 +134,7 @@ impl TransitionFrontierSyncLedgerStagedState { let attempts = self.fetch_attempts(); iter.filter(move |(peer_id, _)| { attempts.map_or(false, |attempts| { - !attempts.contains_key(&peer_id) + !attempts.contains_key(peer_id) && (attempts.is_empty() || attempts.iter().all(|(_, s)| s.is_error())) }) }) diff --git a/node/src/transition_frontier/sync/ledger/transition_frontier_sync_ledger_effects.rs b/node/src/transition_frontier/sync/ledger/transition_frontier_sync_ledger_effects.rs index 14f3506f7..ae8ab435b 100644 --- a/node/src/transition_frontier/sync/ledger/transition_frontier_sync_ledger_effects.rs +++ b/node/src/transition_frontier/sync/ledger/transition_frontier_sync_ledger_effects.rs @@ -13,6 +13,8 @@ pub fn transition_frontier_sync_ledger_init_effects( store.dispatch(TransitionFrontierSyncLedgerSnarkedAction::Pending); } +// TODO(binier): This looks unnecessary complicated +#[allow(clippy::if_same_then_else)] pub fn transition_frontier_sync_ledger_snarked_success_effects( _: &ActionMeta, store: &mut Store, diff --git a/node/src/transition_frontier/sync/ledger/transition_frontier_sync_ledger_reducer.rs b/node/src/transition_frontier/sync/ledger/transition_frontier_sync_ledger_reducer.rs index 06b47a66e..56c2bc037 100644 --- a/node/src/transition_frontier/sync/ledger/transition_frontier_sync_ledger_reducer.rs +++ b/node/src/transition_frontier/sync/ledger/transition_frontier_sync_ledger_reducer.rs @@ -60,7 +60,7 @@ impl TransitionFrontierSyncLedgerState { *self = Self::Staged(s); } Self::Staged(state) => state.reducer(meta.with_action(action)), - _ => return, + _ => (), } } } diff --git a/node/src/transition_frontier/sync/ledger/transition_frontier_sync_ledger_state.rs b/node/src/transition_frontier/sync/ledger/transition_frontier_sync_ledger_state.rs index d5754998b..65c24d278 100644 --- a/node/src/transition_frontier/sync/ledger/transition_frontier_sync_ledger_state.rs +++ b/node/src/transition_frontier/sync/ledger/transition_frontier_sync_ledger_state.rs @@ -41,11 +41,11 @@ impl TransitionFrontierSyncLedgerState { } pub fn is_snarked_ledger_synced(&self) -> bool { - match self { - Self::Init { .. } => false, - Self::Snarked(TransitionFrontierSyncLedgerSnarkedState::Pending { .. }) => false, - _ => true, - } + !matches!( + self, + Self::Init { .. } + | Self::Snarked(TransitionFrontierSyncLedgerSnarkedState::Pending { .. }) + ) } // TODO(binier): maybe avoid extra cloning. diff --git a/node/src/transition_frontier/sync/transition_frontier_sync_effects.rs b/node/src/transition_frontier/sync/transition_frontier_sync_effects.rs index e59be6598..e635146d7 100644 --- a/node/src/transition_frontier/sync/transition_frontier_sync_effects.rs +++ b/node/src/transition_frontier/sync/transition_frontier_sync_effects.rs @@ -59,6 +59,8 @@ impl TransitionFrontierSyncAction { TransitionFrontierSyncAction::LedgerStakingPending => { store.dispatch(TransitionFrontierSyncLedgerAction::Init); } + // TODO(binier): This looks unnecessary complicated + #[allow(clippy::if_same_then_else)] TransitionFrontierSyncAction::LedgerStakingSuccess => { if store.dispatch(TransitionFrontierSyncAction::LedgerNextEpochPending) { } else if store.dispatch(TransitionFrontierSyncAction::LedgerRootPending) { diff --git a/node/src/transition_frontier/sync/transition_frontier_sync_reducer.rs b/node/src/transition_frontier/sync/transition_frontier_sync_reducer.rs index f6a68447a..6f614450f 100644 --- a/node/src/transition_frontier/sync/transition_frontier_sync_reducer.rs +++ b/node/src/transition_frontier/sync/transition_frontier_sync_reducer.rs @@ -241,7 +241,7 @@ impl TransitionFrontierSyncState { ); } } - _ => return, + _ => (), }, TransitionFrontierSyncAction::LedgerStakingPending => { if let Self::Init { @@ -439,7 +439,7 @@ impl TransitionFrontierSyncState { let Some(attempts) = block_state.fetch_pending_attempts_mut() else { return; }; - attempts.insert(peer_id.clone(), PeerRpcState::Init { time: meta.time() }); + attempts.insert(*peer_id, PeerRpcState::Init { time: meta.time() }); } TransitionFrontierSyncAction::BlocksPeerQueryRetry { hash, peer_id } => { let Some(block_state) = self.block_state_mut(hash) else { @@ -448,7 +448,7 @@ impl TransitionFrontierSyncState { let Some(attempts) = block_state.fetch_pending_attempts_mut() else { return; }; - attempts.insert(peer_id.clone(), PeerRpcState::Init { time: meta.time() }); + attempts.insert(*peer_id, PeerRpcState::Init { time: meta.time() }); } TransitionFrontierSyncAction::BlocksPeerQueryPending { hash, @@ -588,7 +588,7 @@ fn next_required_ledger_to_sync( old_root: &ArcBlockWithHash, new_best_tip: &ArcBlockWithHash, new_root: &ArcBlockWithHash, - new_blocks_inbetween: &Vec, + new_blocks_inbetween: &[StateHash], ) -> TransitionFrontierSyncState { let next_epoch_target = SyncLedgerTarget::next_epoch(new_best_tip, new_root); @@ -637,7 +637,7 @@ fn next_required_ledger_to_sync( time, best_tip: new_best_tip.clone(), root_block: new_root.clone(), - blocks_inbetween: new_blocks_inbetween.clone(), + blocks_inbetween: new_blocks_inbetween.to_vec(), ledger, }; match kind { diff --git a/node/src/transition_frontier/sync/transition_frontier_sync_state.rs b/node/src/transition_frontier/sync/transition_frontier_sync_state.rs index aa8dac18f..374c35bf3 100644 --- a/node/src/transition_frontier/sync/transition_frontier_sync_state.rs +++ b/node/src/transition_frontier/sync/transition_frontier_sync_state.rs @@ -488,7 +488,7 @@ impl TransitionFrontierRootSnarkedLedgerUpdates { Some(Some((snarked_ledger_hash, update))) }) - .filter_map(|v| v), + .flatten(), ); } } diff --git a/node/src/watched_accounts/watched_accounts_actions.rs b/node/src/watched_accounts/watched_accounts_actions.rs index a3eafefb5..8eebf22f7 100644 --- a/node/src/watched_accounts/watched_accounts_actions.rs +++ b/node/src/watched_accounts/watched_accounts_actions.rs @@ -134,7 +134,7 @@ impl redux::EnablingCondition for WatchedAccountsAction { let Some(acc) = state.watched_accounts.get(pub_key) else { return false; }; - acc.block_find_by_hash(&block_hash) + acc.block_find_by_hash(block_hash) .filter(|b| { matches!(b, WatchedAccountBlockState::TransactionsInBlockBody { .. }) }) diff --git a/node/src/watched_accounts/watched_accounts_reducer.rs b/node/src/watched_accounts/watched_accounts_reducer.rs index e6dd5c7bd..847cf0cf5 100644 --- a/node/src/watched_accounts/watched_accounts_reducer.rs +++ b/node/src/watched_accounts/watched_accounts_reducer.rs @@ -84,7 +84,7 @@ impl WatchedAccountsState { .consensus_state .blockchain_length .0 - .0 as u32, + .0, hash: block.hash.clone(), pred_hash: block .block diff --git a/node/src/watched_accounts/watched_accounts_state.rs b/node/src/watched_accounts/watched_accounts_state.rs index d06adf3db..b52a3d850 100644 --- a/node/src/watched_accounts/watched_accounts_state.rs +++ b/node/src/watched_accounts/watched_accounts_state.rs @@ -177,9 +177,7 @@ impl WatchedAccountsState { self.list.insert(key, value); } - pub fn iter<'a>( - &'a self, - ) -> impl 'a + Iterator { + pub fn iter(&self) -> impl Iterator { self.list.iter() } @@ -187,3 +185,9 @@ impl WatchedAccountsState { self.iter().map(|v| v.0.clone()).collect() } } + +impl Default for WatchedAccountsState { + fn default() -> Self { + Self::new() + } +} diff --git a/node/testing/src/bin/runner.rs b/node/testing/src/bin/runner.rs index 7ffaabb33..07cfe9964 100644 --- a/node/testing/src/bin/runner.rs +++ b/node/testing/src/bin/runner.rs @@ -14,7 +14,7 @@ fn main() { .spawn() .expect("cannot run debugger"); thread::sleep(Duration::from_secs(2)); - let mut test = Command::new(env::args().skip(1).next().unwrap()) + let mut test = Command::new(env::args().nth(1).unwrap()) .args(env::args().skip(2)) .envs(env::vars()) .stderr(Stdio::inherit()) diff --git a/node/testing/src/cluster/mod.rs b/node/testing/src/cluster/mod.rs index df91ee336..a96583112 100644 --- a/node/testing/src/cluster/mod.rs +++ b/node/testing/src/cluster/mod.rs @@ -118,7 +118,7 @@ lazy_static::lazy_static! { lazy_static::lazy_static! { static ref DETERMINISTIC_ACCOUNT_SEC_KEYS: BTreeMap = (0..1000) - .map(|i| AccountSecretKey::deterministic(i)) + .map(AccountSecretKey::deterministic) .map(|sec_key| (sec_key.public_key(), sec_key)) .collect(); } @@ -361,7 +361,7 @@ impl Cluster { invariants_state: Default::default(), }; if let Some(producer_key) = block_producer_sec_key { - real_service.block_producer_start(producer_key.into()); + real_service.block_producer_start(producer_key); } let mut service = NodeTestingService::new(real_service, node_id, shutdown_rx); service.set_proof_kind(self.config.proof_kind()); @@ -592,10 +592,10 @@ impl Cluster { .ok_or_else(|| anyhow::anyhow!("node {node_id:?} not found"))?; let timeout = tokio::time::sleep(Duration::from_secs(60)); tokio::select! { - opt = node.wait_for_event(&event_pattern) => opt.ok_or_else(|| anyhow::anyhow!("wait_for_event: None")), + opt = node.wait_for_event(event_pattern) => opt.ok_or_else(|| anyhow::anyhow!("wait_for_event: None")), _ = timeout => { let pending_events = node.pending_events(false).map(|(_, event)| event.to_string()).collect::>(); - return Err(anyhow::anyhow!("waiting for event timed out! node {node_id:?}, event: \"{event_pattern}\"\n{pending_events:?}")); + Err(anyhow::anyhow!("waiting for event timed out! node {node_id:?}, event: \"{event_pattern}\"\n{pending_events:?}")) } } } @@ -800,11 +800,11 @@ impl Cluster { NonDeterministicEvent::P2pDiscoveryAddRoute(id, ids) => { let addrs = ids .into_iter() - .map(|id| node_addr_by_peer_id(&self, id)) + .map(|id| node_addr_by_peer_id(self, id)) .collect::, _>>()?; P2pEvent::Discovery(P2pDiscoveryEvent::AddRoute(id, addrs)).into() } - NonDeterministicEvent::RpcReadonly(id, req) => Event::Rpc(id, req).into(), + NonDeterministicEvent::RpcReadonly(id, req) => Event::Rpc(id, req), }; eprintln!("non_deterministic_event_dispatch({node_id:?}): {event}"); self.nodes diff --git a/node/testing/src/lib.rs b/node/testing/src/lib.rs index ed89903da..5f7baf0a8 100644 --- a/node/testing/src/lib.rs +++ b/node/testing/src/lib.rs @@ -1,3 +1,5 @@ +#![allow(clippy::large_enum_variant)] + mod exit_with_error; use std::sync::Arc; diff --git a/node/testing/src/main.rs b/node/testing/src/main.rs index 28326d3f1..908b1bca4 100644 --- a/node/testing/src/main.rs +++ b/node/testing/src/main.rs @@ -1,3 +1,5 @@ +#![allow(clippy::large_enum_variant)] + use clap::Parser; use openmina_node_testing::cluster::{Cluster, ClusterConfig}; diff --git a/node/testing/src/network_debugger.rs b/node/testing/src/network_debugger.rs index cfe10e98b..04f9547ca 100644 --- a/node/testing/src/network_debugger.rs +++ b/node/testing/src/network_debugger.rs @@ -102,7 +102,7 @@ impl Debugger { let host = self.host; let res = self .client - .get(&format!("http://{host}:{port}/connection/{id}")) + .get(format!("http://{host}:{port}/connection/{id}")) .send()? .text()?; serde_json::from_str(&res).map_err(From::from) @@ -113,7 +113,7 @@ impl Debugger { let host = self.host; let res = self .client - .get(&format!("http://{host}:{port}/connections?{params}")) + .get(format!("http://{host}:{port}/connections?{params}")) .send()? .text()?; serde_json::from_str(&res).map_err(From::from) @@ -123,7 +123,7 @@ impl Debugger { let port = self.port; let host = self.host; self.client - .get(&format!("http://{host}:{port}/message_bin/{id}")) + .get(format!("http://{host}:{port}/message_bin/{id}")) .send()? .bytes() .map(|x| x.to_vec()) @@ -135,7 +135,7 @@ impl Debugger { let host = self.host; let res = self .client - .get(&format!("http://{host}:{port}/messages?{params}")) + .get(format!("http://{host}:{port}/messages?{params}")) .send()? .text()?; serde_json::from_str(&res).map_err(From::from) diff --git a/node/testing/src/node/ocaml/config.rs b/node/testing/src/node/ocaml/config.rs index e3d731d22..4622e120f 100644 --- a/node/testing/src/node/ocaml/config.rs +++ b/node/testing/src/node/ocaml/config.rs @@ -123,7 +123,7 @@ impl OcamlNodeExecutable { "minaprotocol/mina-daemon:2.0.0berkeley-rc1-1551e2f-bullseye-berkeley"; pub const DEFAULT_MINA_EXECUTABLE: &'static str = "mina"; - fn docker_container_name<'a>(tmp_dir: &temp_dir::TempDir) -> String { + fn docker_container_name(tmp_dir: &temp_dir::TempDir) -> String { let path = tmp_dir.path().file_name().unwrap().to_str().unwrap(); format!("openmina_testing_ocaml_{}", &path[1..]) } diff --git a/node/testing/src/node/ocaml/mod.rs b/node/testing/src/node/ocaml/mod.rs index 3ee3bb9c6..54b3a5d26 100644 --- a/node/testing/src/node/ocaml/mod.rs +++ b/node/testing/src/node/ocaml/mod.rs @@ -138,12 +138,16 @@ impl OcamlNode { let prefix = format!("[localhost:{}] ", config.libp2p_port); let prefix2 = prefix.clone(); - std::thread::spawn(move || { - if let Err(_) = Self::read_stream(stdout, std::io::stdout(), &prefix) {} - }); - std::thread::spawn(move || { - if let Err(_) = Self::read_stream(stderr, std::io::stderr(), &prefix2) {} - }); + std::thread::spawn( + move || { + if Self::read_stream(stdout, std::io::stdout(), &prefix).is_err() {} + }, + ); + std::thread::spawn( + move || { + if Self::read_stream(stderr, std::io::stderr(), &prefix2).is_err() {} + }, + ); Ok(Self { child, @@ -251,6 +255,8 @@ impl OcamlNode { .map_err(Into::into) } + // TODO(binier) + #[allow(clippy::suspicious_open_options)] fn generate_libp2p_keypair(config: &OcamlNodeConfig, dir: &Path) -> anyhow::Result { use std::{fs::OpenOptions, io::Write, os::unix::fs::OpenOptionsExt}; @@ -382,9 +388,8 @@ impl OcamlNode { let probe = tokio::task::spawn(async move { loop { interval.tick().await; - match tokio::net::TcpStream::connect(("127.0.0.1", port)).await { - Ok(_) => return, - Err(_) => {} + if (tokio::net::TcpStream::connect(("127.0.0.1", port)).await).is_ok() { + return; } } }); diff --git a/node/testing/src/scenario/event_details.rs b/node/testing/src/scenario/event_details.rs index 0d7e35303..194b6db2a 100644 --- a/node/testing/src/scenario/event_details.rs +++ b/node/testing/src/scenario/event_details.rs @@ -9,28 +9,16 @@ use node::{ pub fn event_details(state: &State, event: &Event) -> Option { match event { - Event::P2p(e) => match e { - P2pEvent::Channel(e) => match e { - P2pChannelEvent::Received(peer_id, Ok(msg)) => match msg { - ChannelMsg::Rpc(msg) => match msg { - RpcChannelMsg::Response(req_id, _) => { - let rpc_state = &state.p2p.get_ready_peer(peer_id)?.channels.rpc; - if *req_id == rpc_state.pending_local_rpc_id()? { - return Some(format!( - "Request: {}", - rpc_state.pending_local_rpc()? - )); - } - None - } - _ => None, - }, - _ => None, - }, - _ => None, - }, - _ => None, - }, + Event::P2p(P2pEvent::Channel(P2pChannelEvent::Received( + peer_id, + Ok(ChannelMsg::Rpc(RpcChannelMsg::Response(req_id, _))), + ))) => { + let rpc_state = &state.p2p.get_ready_peer(peer_id)?.channels.rpc; + if *req_id == rpc_state.pending_local_rpc_id()? { + return Some(format!("Request: {}", rpc_state.pending_local_rpc()?)); + } + None + } _ => None, } } diff --git a/node/testing/src/scenario/id.rs b/node/testing/src/scenario/id.rs index e01028665..db1839e22 100644 --- a/node/testing/src/scenario/id.rs +++ b/node/testing/src/scenario/id.rs @@ -31,10 +31,10 @@ impl FromStr for ScenarioId { fn from_str(s: &str) -> Result { for c in s.chars() { - if ('A'..'Z').contains(&c) { + if c.is_ascii_uppercase() { return Err(ScenarioIdParseError::ContainsUpperCaseCharacters); } - if ('a'..'z').contains(&c) || ('0'..'9').contains(&c) || c == '-' || c == '_' { + if c.is_ascii_lowercase() || c.is_ascii_digit() || c == '-' || c == '_' { continue; } return Err(ScenarioIdParseError::AcceptedPatternMismatch); @@ -50,6 +50,6 @@ impl<'de> Deserialize<'de> for ScenarioId { { let s: &str = Deserialize::deserialize(deserializer)?; - Self::from_str(s).map_err(|err| serde::de::Error::custom(err)) + Self::from_str(s).map_err(serde::de::Error::custom) } } diff --git a/node/testing/src/scenarios/cluster_runner.rs b/node/testing/src/scenarios/cluster_runner.rs index d03858c7a..767759b29 100644 --- a/node/testing/src/scenarios/cluster_runner.rs +++ b/node/testing/src/scenarios/cluster_runner.rs @@ -162,7 +162,7 @@ impl<'a> ClusterRunner<'a> { match &step { ScenarioStep::Event { node_id, event } => { let node_id = *node_id; - let event_id = self.cluster.wait_for_pending_event(node_id, &event).await?; + let event_id = self.cluster.wait_for_pending_event(node_id, event).await?; let node = self.cluster.node(node_id).unwrap(); let event_ref = node.get_pending_event(event_id).unwrap(); if let Some(event) = NonDeterministicEvent::new(event_ref) { @@ -380,7 +380,7 @@ impl<'a> ClusterRunner<'a> { // get all block producers except an extra account added // by ocaml node. Looks like the block producer of the // genesis block. - const GENESIS_PRODUCER: &'static str = + const GENESIS_PRODUCER: &str = "B62qiy32p8kAKnny8ZFwoMhYpBppM1DWVCqAPBYNcXnsAHhnfAAuXgg"; LedgerService::ctx(node.service()) .producers_with_delegates(staking_ledger_hash, |pub_key| { diff --git a/node/testing/src/scenarios/driver.rs b/node/testing/src/scenarios/driver.rs index 538dff282..89e3cf8d4 100644 --- a/node/testing/src/scenarios/driver.rs +++ b/node/testing/src/scenarios/driver.rs @@ -52,7 +52,7 @@ pub fn match_addr_with_port_and_peer_id( }), } => &peer_id == pid && port == *p, P2pConnectionOutgoingInitOpts::LibP2P(libp2p_opts) => { - &libp2p_opts.peer_id == &peer_id && libp2p_opts.port == port + libp2p_opts.peer_id == peer_id && libp2p_opts.port == port } _ => false, } @@ -270,7 +270,6 @@ impl<'cluster> Driver<'cluster> { node_id, event: event.to_string(), }; - let node_id = node_id; self.runner.exec_step(step).await?; let state = self.runner.node(node_id).unwrap().state(); if f(node_id, &event, state) { @@ -298,7 +297,6 @@ impl<'cluster> Driver<'cluster> { node_id, event: event.to_string(), }; - let node_id = node_id; self.runner.exec_step(step).await?; let _state = self.runner.node(node_id).unwrap().state(); // println!("{node_id} state: {state:#?}, state = state.p2p"); @@ -552,22 +550,17 @@ pub async fn wait_for_connection_established<'cluster, F: PeerPredicate>( // } /// Creates `num` Rust nodes in the cluster -pub fn add_rust_nodes1<'cluster, N, T>( - driver: &mut Driver, - num: N, - config: RustNodeTestingConfig, -) -> T +pub fn add_rust_nodes1(driver: &mut Driver, num: N, config: RustNodeTestingConfig) -> T where N: Into, T: FromIterator<(ClusterNodeId, PeerId)>, { (0..num.into()) - .into_iter() .map(|_| driver.add_rust_node(config.clone())) .collect() } -pub fn add_rust_nodes<'cluster, N, NodeIds, PeerIds>( +pub fn add_rust_nodes( driver: &mut Driver, num: N, config: RustNodeTestingConfig, @@ -578,13 +571,12 @@ where PeerIds: Default + Extend, { (0..num.into()) - .into_iter() .map(|_| driver.add_rust_node(config.clone())) .unzip() } /// Creates `num` Rust nodes in the cluster -pub fn add_rust_nodes_with<'cluster, N, NodeIds, Items, Item, F>( +pub fn add_rust_nodes_with( driver: &mut Driver, num: N, config: RustNodeTestingConfig, @@ -597,7 +589,6 @@ where F: FnMut(&State) -> Item, { (0..num.into()) - .into_iter() .map(|_| driver.add_rust_node_with(config.clone(), &mut f)) .unzip() } @@ -651,7 +642,7 @@ pub async fn wait_for_connection_event<'cluster, F>( where F: ConnectionPredicate, { - Ok(driver + driver .run_until(duration, |node_id, event: &_, state: &_| { let Some((peer_id, result)) = as_connection_finalized_event(event) else { return false; @@ -679,7 +670,7 @@ where ); f.matches(node_id, addr, result) }) - .await?) + .await } #[cfg(not(feature = "p2p-libp2p"))] @@ -788,7 +779,6 @@ pub async fn trace_steps_state T>( node_id, event: event.to_string(), }; - let node_id = node_id; runner.exec_step(step).await?; let state = runner.node(node_id).unwrap().state(); let t = f(state); diff --git a/node/testing/src/scenarios/multi_node/basic_connectivity_initial_joining.rs b/node/testing/src/scenarios/multi_node/basic_connectivity_initial_joining.rs index 352f90bdb..19bbddfd4 100644 --- a/node/testing/src/scenarios/multi_node/basic_connectivity_initial_joining.rs +++ b/node/testing/src/scenarios/multi_node/basic_connectivity_initial_joining.rs @@ -190,7 +190,7 @@ impl MultiNodeBasicConnectivityInitialJoining { // TODO: fix debugger returns timeout let connections = debugger .connections() - .filter_map(|id| Some((id, connections.get(&id)?.clone()))) + .filter_map(|id| Some((id, *connections.get(&id)?))) .collect::>(); let incoming = connections.iter().filter(|(_, (_, _, _, i))| *i).count(); let outgoing = connections.len() - incoming; @@ -233,6 +233,6 @@ impl MultiNodeBasicConnectivityInitialJoining { println!("{node_id:?} - p2p state: {:#?}", &node.state().p2p); } - assert!(false); + unreachable!(); } } diff --git a/node/testing/src/scenarios/multi_node/basic_connectivity_peer_discovery.rs b/node/testing/src/scenarios/multi_node/basic_connectivity_peer_discovery.rs index 46a6f3002..e027b273f 100644 --- a/node/testing/src/scenarios/multi_node/basic_connectivity_peer_discovery.rs +++ b/node/testing/src/scenarios/multi_node/basic_connectivity_peer_discovery.rs @@ -91,13 +91,10 @@ impl MultiNodeBasicConnectivityPeerDiscovery { let steps = runner .pending_events(true) - .map(|(node_id, _, events)| { + .flat_map(|(node_id, _, events)| { events.map(move |(_, event)| { - match event { - Event::P2p(P2pEvent::Discovery(event)) => { - eprintln!("event: {event}"); - } - _ => {} + if let Event::P2p(P2pEvent::Discovery(event)) = event { + eprintln!("event: {event}"); } ScenarioStep::Event { node_id, @@ -105,7 +102,6 @@ impl MultiNodeBasicConnectivityPeerDiscovery { } }) }) - .flatten() .collect::>(); for step in steps { @@ -156,8 +152,7 @@ impl MultiNodeBasicConnectivityPeerDiscovery { .iter() .filter(|(id, n)| n.is_libp2p && id == &peer_id) .filter_map(|(_, n)| n.status.as_ready()) - .find(|n| n.is_incoming) - .is_some() + .any(|n| n.is_incoming) { eprintln!("the additional OCaml node connected to Openmina node"); eprintln!("success"); diff --git a/node/testing/src/scenarios/multi_node/connection_discovery.rs b/node/testing/src/scenarios/multi_node/connection_discovery.rs index b4d67bca3..f54e33f0f 100644 --- a/node/testing/src/scenarios/multi_node/connection_discovery.rs +++ b/node/testing/src/scenarios/multi_node/connection_discovery.rs @@ -23,7 +23,7 @@ use crate::{ pub struct RustNodeAsSeed; impl RustNodeAsSeed { - pub async fn run<'a>(self, mut runner: ClusterRunner<'a>) { + pub async fn run(self, mut runner: ClusterRunner<'_>) { let rust_node_id = runner.add_rust_node(RustNodeTestingConfig::berkeley_default()); let rust_node_dial_addr = runner.node(rust_node_id).unwrap().dial_addr(); @@ -54,7 +54,7 @@ impl RustNodeAsSeed { .expect("expected connected event"); let (ocaml_peer, _) = as_connection_finalized_event(&connected.1).unwrap(); peers.retain(|peer| peer != ocaml_peer); - let ocaml_peer = ocaml_peer.clone(); + let ocaml_peer = *ocaml_peer; // execute it let state = driver.exec_even_step(connected).await.unwrap().unwrap(); // check that now there is an outgoing connection to the ocaml peer @@ -62,7 +62,7 @@ impl RustNodeAsSeed { &state.p2p.peers.get(&ocaml_peer).unwrap().status, P2pPeerStatus::Ready(ready) if ready.is_incoming )); - duration = Duration::from_secs(1 * 60); + duration = Duration::from_secs(60); } let timeout = Instant::now() + Duration::from_secs(60); @@ -78,7 +78,7 @@ impl RustNodeAsSeed { println!("{}", serde_json::to_string_pretty(&node0_peers).unwrap()); node0_has_node1 = get_peers_iter(&node0_peers) .unwrap() - .any(|peer| peer.unwrap().2 == &ocaml_peer_id1.to_string()); + .any(|peer| peer.unwrap().2 == ocaml_peer_id1.to_string()); let node1_peers = driver .inner() @@ -89,7 +89,7 @@ impl RustNodeAsSeed { println!("{}", serde_json::to_string_pretty(&node1_peers).unwrap()); node1_has_node0 = get_peers_iter(&node1_peers) .unwrap() - .any(|peer| peer.unwrap().2 == &ocaml_peer_id0.to_string()); + .any(|peer| peer.unwrap().2 == ocaml_peer_id0.to_string()); tokio::time::sleep(Duration::from_secs(10)).await; } @@ -120,7 +120,7 @@ impl RustNodeAsSeed { pub struct OCamlToRust; impl OCamlToRust { - pub async fn run<'a>(self, mut runner: ClusterRunner<'a>) { + pub async fn run(self, mut runner: ClusterRunner<'_>) { let rust_node_id = runner.add_rust_node(RustNodeTestingConfig::berkeley_default()); let rust_node_dial_addr = runner.node(rust_node_id).unwrap().dial_addr(); @@ -154,10 +154,7 @@ impl OCamlToRust { // wait for identify message let identify = driver - .wait_for( - Duration::from_secs(5 * 60), - identify_event(ocaml_peer_id.clone().into()), - ) + .wait_for(Duration::from_secs(5 * 60), identify_event(ocaml_peer_id)) .await .unwrap() .expect("expected connected event"); @@ -169,7 +166,7 @@ impl OCamlToRust { .p2p .kademlia .routes - .get(&ocaml_peer_id.clone().into()) + .get(&ocaml_peer_id.clone()) .map_or(false, |l| !l.is_empty()), "kademlia should know ocaml node's addresses" ); @@ -181,7 +178,7 @@ impl OCamlToRust { pub struct RustToOCaml; impl RustToOCaml { - pub async fn run<'a>(self, mut runner: ClusterRunner<'a>) { + pub async fn run(self, mut runner: ClusterRunner<'_>) { let rust_node_id = runner.add_rust_node(RustNodeTestingConfig::berkeley_default()); let ocaml_seed_config = OcamlNodeTestingConfig { @@ -226,14 +223,14 @@ impl RustToOCaml { let state = driver.exec_even_step(connected).await.unwrap().unwrap(); // check that now there is an outgoing connection to the ocaml peer assert!(matches!( - &state.p2p.peers.get(&seed_peer_id.clone().into()).unwrap().status, + &state.p2p.peers.get(&seed_peer_id.clone()).unwrap().status, P2pPeerStatus::Ready(ready) if !ready.is_incoming )); // wait for kademlia to add the ocaml peer let kad_add_rounte = driver.wait_for(Duration::from_secs(1), |_, event, _| { matches!(event, Event::P2p(P2pEvent::Discovery(P2pDiscoveryEvent::AddRoute(peer, addresses))) - if peer == &seed_peer_id && addresses.iter().any(match_addr_with_port_and_peer_id(8302, seed_peer_id.clone().into())) + if peer == &seed_peer_id && addresses.iter().any(match_addr_with_port_and_peer_id(8302, seed_peer_id)) ) }).await.unwrap().expect("expected add route event"); let state = driver @@ -246,7 +243,7 @@ impl RustToOCaml { .p2p .kademlia .routes - .get(&seed_peer_id.clone().into()) + .get(&seed_peer_id.clone()) .map_or(false, |l| !l.is_empty()), "kademlia should know ocaml node's addresses" ); @@ -258,7 +255,7 @@ impl RustToOCaml { pub struct OCamlToRustViaSeed; impl OCamlToRustViaSeed { - pub async fn run<'a>(self, mut runner: ClusterRunner<'a>) { + pub async fn run(self, mut runner: ClusterRunner<'_>) { let rust_node_id = runner.add_rust_node(RustNodeTestingConfig::berkeley_default()); let ocaml_seed_config = OcamlNodeTestingConfig { @@ -304,7 +301,7 @@ impl OCamlToRustViaSeed { let state = driver.exec_even_step(connected).await.unwrap().unwrap(); assert!(matches!( - &state.p2p.peers.get(&seed_peer_id.clone().into()).unwrap().status, + &state.p2p.peers.get(&seed_peer_id.clone()).unwrap().status, P2pPeerStatus::Ready(ready) if !ready.is_incoming )); @@ -318,7 +315,7 @@ impl OCamlToRustViaSeed { .exec_step(ScenarioStep::ManualEvent { node_id: rust_node_id, event: Box::new(Event::P2p(node::p2p::P2pEvent::Connection( - P2pConnectionEvent::Closed(seed_peer_id.clone()), + P2pConnectionEvent::Closed(seed_peer_id), ))), }) .await @@ -331,7 +328,7 @@ impl OCamlToRustViaSeed { .state() .p2p .peers - .get(&seed_peer_id.clone().into()) + .get(&seed_peer_id.clone()) .unwrap() .status, P2pPeerStatus::Disconnected { .. } @@ -364,7 +361,7 @@ impl OCamlToRustViaSeed { pub struct RustToOCamlViaSeed; impl RustToOCamlViaSeed { - pub async fn run<'a>(self, mut runner: ClusterRunner<'a>) { + pub async fn run(self, mut runner: ClusterRunner<'_>) { let rust_node_id = runner.add_rust_node(RustNodeTestingConfig::berkeley_default()); let ocaml_seed_config = OcamlNodeTestingConfig { @@ -388,7 +385,7 @@ impl RustToOCamlViaSeed { let ocaml_peer_id = runner.ocaml_node(ocaml_node).unwrap().peer_id(); let wait_step = OcamlStep::WaitReady { - timeout: Duration::from_secs(1 * 60), + timeout: Duration::from_secs(60), }; runner .exec_step(ScenarioStep::Ocaml { @@ -426,7 +423,7 @@ impl RustToOCamlViaSeed { let state = driver.exec_even_step(connected).await.unwrap().unwrap(); assert!(matches!( - &state.p2p.peers.get(&seed_peer_id.clone().into()).unwrap().status, + &state.p2p.peers.get(&seed_peer_id.clone()).unwrap().status, P2pPeerStatus::Ready(ready) if !ready.is_incoming )); @@ -449,7 +446,7 @@ impl RustToOCamlViaSeed { steps.push(ScenarioStep::ManualEvent { node_id, event: Box::new(Event::P2p(P2pEvent::Connection( - P2pConnectionEvent::Closed(peer.clone()), + P2pConnectionEvent::Closed(*peer), ))), }); } else { diff --git a/node/testing/src/scenarios/multi_node/vrf_correct_ledgers.rs b/node/testing/src/scenarios/multi_node/vrf_correct_ledgers.rs index 23edab900..aeaf79b73 100644 --- a/node/testing/src/scenarios/multi_node/vrf_correct_ledgers.rs +++ b/node/testing/src/scenarios/multi_node/vrf_correct_ledgers.rs @@ -105,7 +105,7 @@ impl MultiNodeVrfGetCorrectLedgers { ), ]; - let expected_delegator_table: BTreeMap = + let _expected_delegator_table: BTreeMap = expected_delegator_table_data.into_iter().collect(); runner @@ -126,7 +126,7 @@ impl MultiNodeVrfGetCorrectLedgers { .await .expect("Timeout - waiting for VRF evaluator to update producer and delegates"); - let (state, _) = runner.node_pending_events(producer_node, false).unwrap(); + let (_state, _) = runner.node_pending_events(producer_node, false).unwrap(); // check if our producer and delegators are detected correctly from the epoch ledgers // let epoch_data = state diff --git a/node/testing/src/scenarios/multi_node/vrf_epoch_bounds_correct_ledgers.rs b/node/testing/src/scenarios/multi_node/vrf_epoch_bounds_correct_ledgers.rs index aaf0208aa..dab748385 100644 --- a/node/testing/src/scenarios/multi_node/vrf_epoch_bounds_correct_ledgers.rs +++ b/node/testing/src/scenarios/multi_node/vrf_epoch_bounds_correct_ledgers.rs @@ -22,7 +22,6 @@ const GLOBAL_TIMEOUT: Duration = Duration::from_secs(60 * 60); const STEP_DURATION: Duration = Duration::from_millis(500); const SECOND_EPOCH_LAST_SLOT: u32 = 14_279; -const THIRD_EPOCH_LAST_SLOT: u32 = 21_419; const KEEP_SYNCED: bool = true; diff --git a/node/testing/src/scenarios/p2p/basic_connection_handling.rs b/node/testing/src/scenarios/p2p/basic_connection_handling.rs index adb924405..c1c67a32d 100644 --- a/node/testing/src/scenarios/p2p/basic_connection_handling.rs +++ b/node/testing/src/scenarios/p2p/basic_connection_handling.rs @@ -23,7 +23,7 @@ fn has_active_peer(p2p_state: &P2pState, peer_id: &PeerId) -> bool { pub struct SimultaneousConnections; impl SimultaneousConnections { - pub async fn run<'cluster>(self, runner: ClusterRunner<'cluster>) { + pub async fn run(self, runner: ClusterRunner<'_>) { let mut driver = Driver::new(runner); let testing_config = RustNodeTestingConfig::berkeley_default().with_timeouts(P2pTimeouts { @@ -91,7 +91,7 @@ impl SimultaneousConnections { pub struct AllNodesConnectionsAreSymmetric; impl AllNodesConnectionsAreSymmetric { - pub async fn run<'cluster>(self, runner: ClusterRunner<'cluster>) { + pub async fn run(self, runner: ClusterRunner<'_>) { const MAX: u16 = 32; let mut driver = Driver::new(runner); @@ -105,7 +105,6 @@ impl AllNodesConnectionsAreSymmetric { let (seed_id, _) = driver.add_rust_node(testing_config.clone()); let peers: Vec<_> = (0..MAX) - .into_iter() .map(|_| { driver.add_rust_node(testing_config.clone().initial_peers(vec![seed_id.into()])) }) @@ -155,7 +154,7 @@ impl AllNodesConnectionsAreSymmetric { pub struct SeedConnectionsAreSymmetric; impl SeedConnectionsAreSymmetric { - pub async fn run<'cluster>(self, runner: ClusterRunner<'cluster>) { + pub async fn run(self, runner: ClusterRunner<'_>) { const MAX: u16 = 32; let mut driver = Driver::new(runner); @@ -164,7 +163,6 @@ impl SeedConnectionsAreSymmetric { driver.add_rust_node(RustNodeTestingConfig::berkeley_default()); let peers: Vec<_> = (0..MAX) - .into_iter() .map(|_| { driver.add_rust_node( RustNodeTestingConfig::berkeley_default().initial_peers(vec![node_ut.into()]), @@ -200,7 +198,7 @@ impl SeedConnectionsAreSymmetric { pub struct MaxNumberOfPeers; impl MaxNumberOfPeers { - pub async fn run<'cluster>(self, runner: ClusterRunner<'cluster>) { + pub async fn run(self, runner: ClusterRunner<'_>) { const TOTAL: u16 = 512; const MAX: u16 = 32; @@ -272,7 +270,7 @@ impl MaxNumberOfPeers { // assert!(count <= MAX.into(), "max number of peers exceeded: {count}"); // } - driver.run(Duration::from_secs(1 * 60)).await.unwrap(); + driver.run(Duration::from_secs(60)).await.unwrap(); // check that the number of ready peers does not exceed the maximal allowed number let state = driver.inner().node(node_ut).unwrap().state(); @@ -298,7 +296,7 @@ impl MaxNumberOfPeers { pub struct MaxNumberOfPeersIs1; impl MaxNumberOfPeersIs1 { - pub async fn run<'cluster>(self, runner: ClusterRunner<'cluster>) { + pub async fn run(self, runner: ClusterRunner<'_>) { const CONNECTED_TIME_SEC: u64 = 10; let mut driver = Driver::new(runner); @@ -344,8 +342,8 @@ impl MaxNumberOfPeersIs1 { pub struct ConnectionStability; impl ConnectionStability { - pub async fn run<'cluster>(self, runner: ClusterRunner<'cluster>) { - const CONNECTED_TIME_SEC: u64 = 1 * 60; + pub async fn run(self, runner: ClusterRunner<'_>) { + const CONNECTED_TIME_SEC: u64 = 60; let mut driver = Driver::new(runner); let (node1, _) = diff --git a/node/testing/src/scenarios/p2p/basic_incoming_connections.rs b/node/testing/src/scenarios/p2p/basic_incoming_connections.rs index 889dcdc28..fd22adffe 100644 --- a/node/testing/src/scenarios/p2p/basic_incoming_connections.rs +++ b/node/testing/src/scenarios/p2p/basic_incoming_connections.rs @@ -14,7 +14,7 @@ use crate::{ pub struct AcceptIncomingConnection; impl AcceptIncomingConnection { - pub async fn run<'cluster>(self, runner: ClusterRunner<'cluster>) { + pub async fn run(self, runner: ClusterRunner<'_>) { let mut driver = Driver::new(runner); let (node_ut, _) = driver.add_rust_node(RustNodeTestingConfig::berkeley_default()); @@ -56,7 +56,7 @@ impl AcceptIncomingConnection { pub struct AcceptMultipleIncomingConnections; impl AcceptMultipleIncomingConnections { - pub async fn run<'cluster>(self, runner: ClusterRunner<'cluster>) { + pub async fn run(self, runner: ClusterRunner<'_>) { const MAX: u8 = 16; let mut driver = Driver::new(runner); @@ -104,7 +104,7 @@ impl AcceptMultipleIncomingConnections { pub struct DoesNotAcceptConnectionFromSelf; impl DoesNotAcceptConnectionFromSelf { - pub async fn run<'cluster>(self, runner: ClusterRunner<'cluster>) { + pub async fn run(self, runner: ClusterRunner<'_>) { let mut driver = Driver::new(runner); let (node_ut, node_ut_peer_id) = driver.add_rust_node(RustNodeTestingConfig::berkeley_default()); diff --git a/node/testing/src/scenarios/p2p/basic_outgoing_connections.rs b/node/testing/src/scenarios/p2p/basic_outgoing_connections.rs index a186a7c24..b0b53844a 100644 --- a/node/testing/src/scenarios/p2p/basic_outgoing_connections.rs +++ b/node/testing/src/scenarios/p2p/basic_outgoing_connections.rs @@ -34,7 +34,7 @@ fn custom_listener(peer_id: PeerId, port: u16) -> ListenerNode { pub struct MakeOutgoingConnection; impl MakeOutgoingConnection { - pub async fn run<'cluster>(self, runner: ClusterRunner<'cluster>) { + pub async fn run(self, runner: ClusterRunner<'_>) { let mut driver = Driver::new(runner); let (node1, _) = driver.add_rust_node(RustNodeTestingConfig::berkeley_default()); @@ -76,7 +76,7 @@ impl MakeOutgoingConnection { pub struct MakeMultipleOutgoingConnections; impl MakeMultipleOutgoingConnections { - pub async fn run<'cluster>(self, runner: ClusterRunner<'cluster>) { + pub async fn run(self, runner: ClusterRunner<'_>) { const MAX: u8 = 32; let mut driver = Driver::new(runner); @@ -126,7 +126,7 @@ impl MakeMultipleOutgoingConnections { pub struct DontConnectToNodeWithSameId; impl DontConnectToNodeWithSameId { - pub async fn run<'cluster>(self, runner: ClusterRunner<'cluster>) { + pub async fn run(self, runner: ClusterRunner<'_>) { let mut driver = Driver::new(runner); let bytes: [u8; 32] = rand::random(); @@ -167,7 +167,7 @@ impl DontConnectToNodeWithSameId { pub struct DontConnectToSelfInitialPeer; impl DontConnectToSelfInitialPeer { - pub async fn run<'cluster>(self, runner: ClusterRunner<'cluster>) { + pub async fn run(self, runner: ClusterRunner<'_>) { let mut driver = Driver::new(runner); let bytes = [0xfe; 32]; @@ -175,7 +175,7 @@ impl DontConnectToSelfInitialPeer { let peer_id = SecretKey::from_bytes(bytes).public_key().peer_id(); let self_opts = P2pConnectionOutgoingInitOpts::LibP2P(P2pConnectionOutgoingInitLibp2pOpts { - peer_id: peer_id.clone(), + peer_id, host: node::p2p::webrtc::Host::Ipv4([127, 0, 0, 1].into()), port, }); @@ -205,7 +205,7 @@ impl DontConnectToSelfInitialPeer { pub struct DontConnectToInitialPeerWithSameId; impl DontConnectToInitialPeerWithSameId { - pub async fn run<'cluster>(self, runner: ClusterRunner<'cluster>) { + pub async fn run(self, runner: ClusterRunner<'_>) { let mut driver = Driver::new(runner); let bytes: [u8; 32] = rand::random(); @@ -241,7 +241,7 @@ impl DontConnectToInitialPeerWithSameId { pub struct ConnectToInitialPeers; impl ConnectToInitialPeers { - pub async fn run<'cluster>(self, runner: ClusterRunner<'cluster>) { + pub async fn run(self, runner: ClusterRunner<'_>) { const MAX: u8 = 32; let mut driver = Driver::new(runner); @@ -252,8 +252,7 @@ impl ConnectToInitialPeers { RustNodeTestingConfig::berkeley_default(), |state| { let config = &state.p2p.config; - let peer_id = config.identity_pub_key.peer_id(); - peer_id + config.identity_pub_key.peer_id() }, ); @@ -295,7 +294,7 @@ impl ConnectToInitialPeers { pub struct ConnectToInitialPeersBecomeReady; impl ConnectToInitialPeersBecomeReady { - pub async fn run<'cluster>(self, runner: ClusterRunner<'cluster>) { + pub async fn run(self, runner: ClusterRunner<'_>) { const MAX: u8 = 32; let mut driver = Driver::new(runner); @@ -350,14 +349,13 @@ impl ConnectToInitialPeersBecomeReady { pub struct ConnectToUnavailableInitialPeers; impl ConnectToUnavailableInitialPeers { - pub async fn run<'cluster>(self, runner: ClusterRunner<'cluster>) { + pub async fn run(self, runner: ClusterRunner<'_>) { const MAX: u16 = 2; const RETRIES: u8 = 3; let mut driver = Driver::new(runner); let (initial_peers, ports): (Vec<_>, Vec<_>) = (0..MAX) - .into_iter() .map(|i| { let port = 11200 + i; let peer_id = SecretKey::rand().public_key().peer_id(); diff --git a/node/testing/src/scenarios/p2p/kademlia.rs b/node/testing/src/scenarios/p2p/kademlia.rs index 3aac9ca87..fb31fd121 100644 --- a/node/testing/src/scenarios/p2p/kademlia.rs +++ b/node/testing/src/scenarios/p2p/kademlia.rs @@ -27,7 +27,7 @@ const LOCALHOST: Ipv4Addr = Ipv4Addr::new(127, 0, 0, 1); pub struct IncomingFindNode; impl IncomingFindNode { - pub async fn run<'cluster>(self, runner: ClusterRunner<'cluster>) { + pub async fn run(self, runner: ClusterRunner<'_>) { let mut driver = Driver::new(runner); let (node1, peer_id1) = driver.add_rust_node( RustNodeTestingConfig::berkeley_default().initial_peers( @@ -80,7 +80,7 @@ impl IncomingFindNode { fake_peer .behaviour_mut() .kademlia - .add_address(&peer_id1.clone().into(), addr); + .add_address(&peer_id1.into(), addr); loop { let next = fake_peer.next().await.unwrap(); println!("<<< {next:?}"); @@ -119,7 +119,7 @@ impl IncomingFindNode { pub struct KademliaBootstrap; impl KademliaBootstrap { - pub async fn run<'cluster>(self, runner: ClusterRunner<'cluster>) { + pub async fn run(self, runner: ClusterRunner<'_>) { const NUM: u8 = 10; let identity_key = Keypair::ed25519_from_bytes([0xba; 32]).expect("secret key bytes must be valid"); @@ -143,7 +143,7 @@ impl KademliaBootstrap { driver.add_rust_node(RustNodeTestingConfig::berkeley_default().initial_peers( FromIterator::from_iter([ListenerNode::Custom( P2pConnectionOutgoingInitOpts::LibP2P(P2pConnectionOutgoingInitLibp2pOpts { - peer_id: peer_id.clone().into(), + peer_id: peer_id.into(), host: Host::Ipv4(LOCALHOST), port: 13000, }), @@ -201,7 +201,7 @@ fn fake_kad_peer( port: Option, ) -> anyhow::Result> { let psk = PreSharedKey::new(openmina_core::preshared_key(openmina_core::CHAIN_ID)); - let identify = libp2p::identify::Behaviour::new(libp2p::identify::Config::new( + let _identify = libp2p::identify::Behaviour::new(libp2p::identify::Config::new( "ipfs/0.1.0".to_string(), identity_key.public(), )); @@ -210,7 +210,7 @@ fn fake_kad_peer( println!("======== peer_id: {peer_id}"); println!( "======== peer_id bytes: {}", - hex::encode(&peer_id.clone().to_bytes()) + hex::encode(peer_id.to_bytes()) ); let kad_config = { let mut c = libp2p::kad::Config::default(); diff --git a/node/testing/src/scenarios/solo_node/basic_connectivity_accept_incoming.rs b/node/testing/src/scenarios/solo_node/basic_connectivity_accept_incoming.rs index e053db7bf..393489e70 100644 --- a/node/testing/src/scenarios/solo_node/basic_connectivity_accept_incoming.rs +++ b/node/testing/src/scenarios/solo_node/basic_connectivity_accept_incoming.rs @@ -63,13 +63,10 @@ impl SoloNodeBasicConnectivityAcceptIncoming { let steps = runner .pending_events(true) - .map(|(node_id, _, events)| { + .flat_map(|(node_id, _, events)| { events.map(move |(_, event)| { - match event { - Event::P2p(P2pEvent::Discovery(event)) => { - eprintln!("event: {event}"); - } - _ => {} + if let Event::P2p(P2pEvent::Discovery(event)) = event { + eprintln!("event: {event}"); } ScenarioStep::Event { node_id, @@ -77,7 +74,6 @@ impl SoloNodeBasicConnectivityAcceptIncoming { } }) }) - .flatten() .collect::>(); for step in steps { diff --git a/node/testing/src/scenarios/solo_node/basic_connectivity_initial_joining.rs b/node/testing/src/scenarios/solo_node/basic_connectivity_initial_joining.rs index c76c725f9..a5bf5625e 100644 --- a/node/testing/src/scenarios/solo_node/basic_connectivity_initial_joining.rs +++ b/node/testing/src/scenarios/solo_node/basic_connectivity_initial_joining.rs @@ -68,13 +68,10 @@ impl SoloNodeBasicConnectivityInitialJoining { let steps = runner .pending_events(true) - .map(|(node_id, _, events)| { + .flat_map(|(node_id, _, events)| { events.map(move |(_, event)| { - match event { - Event::P2p(P2pEvent::Discovery(event)) => { - eprintln!("event: {event}"); - } - _ => {} + if let Event::P2p(P2pEvent::Discovery(event)) = event { + eprintln!("event: {event}"); } ScenarioStep::Event { node_id, @@ -82,7 +79,6 @@ impl SoloNodeBasicConnectivityInitialJoining { } }) }) - .flatten() .collect::>(); for step in steps { @@ -135,7 +131,7 @@ impl SoloNodeBasicConnectivityInitialJoining { // TODO: fix debugger returns timeout let connections = debugger .connections() - .filter_map(|id| Some((id, connections.get(&id)?.clone()))) + .filter_map(|id| Some((id, *connections.get(&id)?))) .collect::>(); let incoming = connections.iter().filter(|(_, (_, _, _, i))| *i).count(); let outgoing = connections.len() - incoming; diff --git a/node/testing/src/scenarios/solo_node/bootstrap.rs b/node/testing/src/scenarios/solo_node/bootstrap.rs index 223a6eec7..e22d31396 100644 --- a/node/testing/src/scenarios/solo_node/bootstrap.rs +++ b/node/testing/src/scenarios/solo_node/bootstrap.rs @@ -27,7 +27,7 @@ impl SoloNodeBootstrap { const TIMEOUT: Duration = Duration::from_secs(60 * 40); - const REPLAYER_1: &'static str = + const REPLAYER_1: &str = "/ip4/135.181.217.23/tcp/31968/p2p/12D3KooWPayQEdprqY2m3biReUUybA5LoULpJE7YWu6wetEKKELv"; let replayer = (&REPLAYER_1.parse::().unwrap()) .try_into() @@ -49,13 +49,12 @@ impl SoloNodeBootstrap { { let steps = runner .pending_events(true) - .map(|(node_id, _, events)| { + .flat_map(|(node_id, _, events)| { events.map(move |(_, event)| ScenarioStep::Event { node_id, event: event.to_string(), }) }) - .flatten() .collect::>(); for step in steps { diff --git a/node/testing/src/scenarios/solo_node/sync_root_snarked_ledger.rs b/node/testing/src/scenarios/solo_node/sync_root_snarked_ledger.rs index d3bdd3ae3..6fb035196 100644 --- a/node/testing/src/scenarios/solo_node/sync_root_snarked_ledger.rs +++ b/node/testing/src/scenarios/solo_node/sync_root_snarked_ledger.rs @@ -36,9 +36,9 @@ impl SoloNodeSyncRootSnarkedLedger { let node_id = runner.add_rust_node(RustNodeTestingConfig::berkeley_default()); eprintln!("launch Openmina node with default configuration, id: {node_id}"); - const REPLAYER_1: &'static str = + const REPLAYER_1: &str = "/ip4/65.109.110.75/tcp/18302/p2p/12D3KooWD8jSyPFXNdAcMBHyHjRBcK1AW9t3xvnpfCFSRKMweVKi"; - const REPLAYER_2: &'static str = + const REPLAYER_2: &str = "/ip4/65.109.110.75/tcp/18303/p2p/12D3KooWBxbfeaxGHxdxP3U5jRKpNK5wQmbjKywGJEqTCNpVPxqk"; // Initiate connection to 2 replayers. diff --git a/node/testing/src/scenarios/solo_node/sync_to_genesis.rs b/node/testing/src/scenarios/solo_node/sync_to_genesis.rs index 4d2e7074a..174c41022 100644 --- a/node/testing/src/scenarios/solo_node/sync_to_genesis.rs +++ b/node/testing/src/scenarios/solo_node/sync_to_genesis.rs @@ -22,7 +22,7 @@ impl SoloNodeSyncToGenesis { pub async fn run(self, mut runner: ClusterRunner<'_>) { // TODO(binier): make dynamic. // should match time in daemon_json - let initial_time = redux::Timestamp::new(1703494800000_000_000); + let initial_time = redux::Timestamp::new(1_703_494_800_000_000_000); let ocaml_node_config = OcamlNodeTestingConfig { initial_peers: Vec::new(), diff --git a/node/testing/src/service/mod.rs b/node/testing/src/service/mod.rs index c2271f9aa..c31b52da9 100644 --- a/node/testing/src/service/mod.rs +++ b/node/testing/src/service/mod.rs @@ -410,7 +410,7 @@ impl BlockProducerVrfEvaluatorService for NodeTestingService { use std::cell::RefCell; thread_local! { - static GENESIS_PROOF: RefCell)>> = RefCell::new(None); + static GENESIS_PROOF: RefCell)>> = const { RefCell::new(None) }; } impl BlockProducerService for NodeTestingService { @@ -429,7 +429,7 @@ impl BlockProducerService for NodeTestingService { let _ = self.real.event_sender.send(dummy_proof_event(block_hash)); } ProofKind::ConstraintsChecked => { - match openmina_node_native::block_producer::prove(&*input, true) { + match openmina_node_native::block_producer::prove(&input, true) { Err(ProofError::ConstraintsOk) => { let _ = self.real.event_sender.send(dummy_proof_event(block_hash)); } @@ -453,7 +453,7 @@ impl BlockProducerService for NodeTestingService { { Ok(proof.clone()) } else { - openmina_node_native::block_producer::prove(&*input, false) + openmina_node_native::block_producer::prove(&input, false) .map_err(|err| format!("{err:?}")) } }); diff --git a/node/testing/src/simulator/mod.rs b/node/testing/src/simulator/mod.rs index d2a2ea554..4cd6a8d46 100644 --- a/node/testing/src/simulator/mod.rs +++ b/node/testing/src/simulator/mod.rs @@ -160,7 +160,7 @@ impl Simulator { ); let config = RustNodeTestingConfig { snark_worker: Some(SnarkerConfig { - public_key: sec_key.public_key().into(), + public_key: sec_key.public_key(), fee: CurrencyFeeStableV1(UnsignedExtendedUInt64Int64ForVersionTagsStableV1( 10_000_000.into(), )), diff --git a/p2p/src/channels/best_tip/p2p_channels_best_tip_actions.rs b/p2p/src/channels/best_tip/p2p_channels_best_tip_actions.rs index a6fa853a5..0a0f8ee61 100644 --- a/p2p/src/channels/best_tip/p2p_channels_best_tip_actions.rs +++ b/p2p/src/channels/best_tip/p2p_channels_best_tip_actions.rs @@ -76,11 +76,11 @@ impl redux::EnablingCondition for P2pChannelsBestTipAction { P2pChannelsBestTipAction::RequestSend { peer_id } => state .get_ready_peer(peer_id) .map_or(false, |p| match &p.channels.best_tip { - P2pChannelsBestTipState::Ready { local, .. } => match local { - BestTipPropagationState::WaitingForRequest { .. } => true, - BestTipPropagationState::Responded { .. } => true, - _ => false, - }, + P2pChannelsBestTipState::Ready { local, .. } => matches!( + local, + BestTipPropagationState::WaitingForRequest { .. } + | BestTipPropagationState::Responded { .. } + ), _ => false, }), P2pChannelsBestTipAction::Received { peer_id, .. } => { @@ -89,21 +89,20 @@ impl redux::EnablingCondition for P2pChannelsBestTipAction { state .get_ready_peer(peer_id) .map_or(false, |p| match &p.channels.best_tip { - P2pChannelsBestTipState::Ready { local, .. } => match local { - BestTipPropagationState::Requested { .. } => true, - _ => false, - }, + P2pChannelsBestTipState::Ready { local, .. } => { + matches!(local, BestTipPropagationState::Requested { .. }) + } _ => false, }) } P2pChannelsBestTipAction::RequestReceived { peer_id } => state .get_ready_peer(peer_id) .map_or(false, |p| match &p.channels.best_tip { - P2pChannelsBestTipState::Ready { remote, .. } => match remote { - BestTipPropagationState::WaitingForRequest { .. } => true, - BestTipPropagationState::Responded { .. } => true, - _ => false, - }, + P2pChannelsBestTipState::Ready { remote, .. } => matches!( + remote, + BestTipPropagationState::WaitingForRequest { .. } + | BestTipPropagationState::Responded { .. } + ), _ => false, }), P2pChannelsBestTipAction::ResponseSend { peer_id, best_tip } => state diff --git a/p2p/src/channels/rpc/mod.rs b/p2p/src/channels/rpc/mod.rs index 3014903da..6dd0e47fc 100644 --- a/p2p/src/channels/rpc/mod.rs +++ b/p2p/src/channels/rpc/mod.rs @@ -121,11 +121,10 @@ fn addr_to_str( ) -> String { let addr = byte_string .as_ref() - .into_iter() + .iter() .copied() .flat_map(|byte| { (0..8) - .into_iter() .map(move |b| byte & (1 << (7 - b)) != 0) .map(|b| if b { '1' } else { '0' }) }) diff --git a/p2p/src/channels/rpc/p2p_channels_rpc_effects.rs b/p2p/src/channels/rpc/p2p_channels_rpc_effects.rs index 356d98963..aceb54903 100644 --- a/p2p/src/channels/rpc/p2p_channels_rpc_effects.rs +++ b/p2p/src/channels/rpc/p2p_channels_rpc_effects.rs @@ -31,14 +31,13 @@ impl P2pChannelsRpcAction { store .service() .channel_send(peer_id, MsgId::first(), msg.into()); - } else { - if let Some((query, data)) = super::internal_request_into_libp2p(request, id) { - store.dispatch(P2pNetworkRpcOutgoingQueryAction { - peer_id, - query, - data, - }); - } + } else if let Some((query, data)) = super::internal_request_into_libp2p(request, id) + { + store.dispatch(P2pNetworkRpcOutgoingQueryAction { + peer_id, + query, + data, + }); } } P2pChannelsRpcAction::ResponseReceived { diff --git a/p2p/src/channels/snark/p2p_channels_snark_actions.rs b/p2p/src/channels/snark/p2p_channels_snark_actions.rs index 641f49de6..a8d6b4975 100644 --- a/p2p/src/channels/snark/p2p_channels_snark_actions.rs +++ b/p2p/src/channels/snark/p2p_channels_snark_actions.rs @@ -88,34 +88,28 @@ impl redux::EnablingCondition for P2pChannelsSnarkAction { P2pChannelsSnarkAction::RequestSend { peer_id, .. } => state .get_ready_peer(peer_id) .map_or(false, |p| match &p.channels.snark { - P2pChannelsSnarkState::Ready { local, .. } => match local { - SnarkPropagationState::WaitingForRequest { .. } => true, - SnarkPropagationState::Responded { .. } => true, - _ => false, - }, + P2pChannelsSnarkState::Ready { local, .. } => matches!( + local, + SnarkPropagationState::WaitingForRequest { .. } + | SnarkPropagationState::Responded { .. } + ), _ => false, }), P2pChannelsSnarkAction::PromiseReceived { peer_id, promised_count, - } => state - .get_ready_peer(peer_id) - .map_or(false, |p| match &p.channels.snark { - P2pChannelsSnarkState::Ready { local, .. } => match local { - SnarkPropagationState::Requested { - requested_limit, .. - } => *promised_count > 0 && promised_count <= requested_limit, - _ => false, - }, - _ => false, - }), + } => state.get_ready_peer(peer_id).map_or(false, |p| { + matches!(&p.channels.snark, P2pChannelsSnarkState::Ready { + local: SnarkPropagationState::Requested { requested_limit, .. }, + .. + } if *promised_count > 0 && promised_count <= requested_limit) + }), P2pChannelsSnarkAction::Received { peer_id, .. } => state .get_ready_peer(peer_id) .map_or(false, |p| match &p.channels.snark { - P2pChannelsSnarkState::Ready { local, .. } => match local { - SnarkPropagationState::Responding { .. } => true, - _ => false, - }, + P2pChannelsSnarkState::Ready { local, .. } => { + matches!(local, SnarkPropagationState::Responding { .. }) + } _ => false, }), P2pChannelsSnarkAction::RequestReceived { peer_id, limit } => { @@ -123,11 +117,11 @@ impl redux::EnablingCondition for P2pChannelsSnarkAction { && state .get_ready_peer(peer_id) .map_or(false, |p| match &p.channels.snark { - P2pChannelsSnarkState::Ready { remote, .. } => match remote { - SnarkPropagationState::WaitingForRequest { .. } => true, - SnarkPropagationState::Responded { .. } => true, - _ => false, - }, + P2pChannelsSnarkState::Ready { remote, .. } => matches!( + remote, + SnarkPropagationState::WaitingForRequest { .. } + | SnarkPropagationState::Responded { .. } + ), _ => false, }) } diff --git a/p2p/src/channels/snark_job_commitment/p2p_channels_snark_job_commitment_actions.rs b/p2p/src/channels/snark_job_commitment/p2p_channels_snark_job_commitment_actions.rs index ad51f894c..6fbfcc62d 100644 --- a/p2p/src/channels/snark_job_commitment/p2p_channels_snark_job_commitment_actions.rs +++ b/p2p/src/channels/snark_job_commitment/p2p_channels_snark_job_commitment_actions.rs @@ -89,34 +89,22 @@ impl redux::EnablingCondition for P2pChannelsSnarkJobCommitmentAction P2pChannelsSnarkJobCommitmentAction::RequestSend { peer_id, .. } => state .get_ready_peer(peer_id) .map_or(false, |p| match &p.channels.snark_job_commitment { - P2pChannelsSnarkJobCommitmentState::Ready { local, .. } => match local { - SnarkJobCommitmentPropagationState::WaitingForRequest { .. } => true, - SnarkJobCommitmentPropagationState::Responded { .. } => true, - _ => false, - }, + P2pChannelsSnarkJobCommitmentState::Ready { local, .. } => matches!(local, SnarkJobCommitmentPropagationState::WaitingForRequest { .. } | SnarkJobCommitmentPropagationState::Responded { .. }), _ => false, }), P2pChannelsSnarkJobCommitmentAction::PromiseReceived { peer_id, promised_count, } => state.get_ready_peer(peer_id).map_or(false, |p| { - match &p.channels.snark_job_commitment { - P2pChannelsSnarkJobCommitmentState::Ready { local, .. } => match local { - SnarkJobCommitmentPropagationState::Requested { - requested_limit, .. - } => *promised_count > 0 && promised_count <= requested_limit, - _ => false, - }, - _ => false, - } + matches!(&p.channels.snark_job_commitment, P2pChannelsSnarkJobCommitmentState::Ready { + local: SnarkJobCommitmentPropagationState::Requested { requested_limit, .. }, + .. + } if *promised_count > 0 && promised_count <= requested_limit) }), P2pChannelsSnarkJobCommitmentAction::Received { peer_id, .. } => state .get_ready_peer(peer_id) .map_or(false, |p| match &p.channels.snark_job_commitment { - P2pChannelsSnarkJobCommitmentState::Ready { local, .. } => match local { - SnarkJobCommitmentPropagationState::Responding { .. } => true, - _ => false, - }, + P2pChannelsSnarkJobCommitmentState::Ready { local, .. } => matches!(local, SnarkJobCommitmentPropagationState::Responding { .. }), _ => false, }), P2pChannelsSnarkJobCommitmentAction::RequestReceived { peer_id, limit } => { @@ -124,13 +112,9 @@ impl redux::EnablingCondition for P2pChannelsSnarkJobCommitmentAction && state.get_ready_peer(peer_id).map_or(false, |p| { match &p.channels.snark_job_commitment { P2pChannelsSnarkJobCommitmentState::Ready { remote, .. } => { - match remote { - SnarkJobCommitmentPropagationState::WaitingForRequest { + matches!(remote, SnarkJobCommitmentPropagationState::WaitingForRequest { .. - } => true, - SnarkJobCommitmentPropagationState::Responded { .. } => true, - _ => false, - } + } | SnarkJobCommitmentPropagationState::Responded { .. }) } _ => false, } diff --git a/p2p/src/connection/incoming/p2p_connection_incoming_actions.rs b/p2p/src/connection/incoming/p2p_connection_incoming_actions.rs index 198380a36..4e170e622 100644 --- a/p2p/src/connection/incoming/p2p_connection_incoming_actions.rs +++ b/p2p/src/connection/incoming/p2p_connection_incoming_actions.rs @@ -84,78 +84,86 @@ impl redux::EnablingCondition for P2pConnectionIncomingAction { P2pConnectionIncomingAction::Init { opts, .. } => { state.incoming_accept(opts.peer_id, &opts.offer).is_ok() } - P2pConnectionIncomingAction::AnswerSdpCreatePending { peer_id } => state - .peers - .get(peer_id) - .map_or(false, |peer| match &peer.status { - P2pPeerStatus::Connecting(P2pConnectionState::Incoming( - P2pConnectionIncomingState::Init { .. }, - )) => true, - _ => false, - }), - P2pConnectionIncomingAction::AnswerSdpCreateError { peer_id, .. } => state - .peers - .get(peer_id) - .map_or(false, |peer| match &peer.status { - P2pPeerStatus::Connecting(P2pConnectionState::Incoming( - P2pConnectionIncomingState::AnswerSdpCreatePending { .. }, - )) => true, - _ => false, - }), - P2pConnectionIncomingAction::AnswerSdpCreateSuccess { peer_id, .. } => state - .peers - .get(peer_id) - .map_or(false, |peer| match &peer.status { - P2pPeerStatus::Connecting(P2pConnectionState::Incoming( - P2pConnectionIncomingState::AnswerSdpCreatePending { .. }, - )) => true, - _ => false, - }), - P2pConnectionIncomingAction::AnswerReady { peer_id, .. } => state - .peers - .get(peer_id) - .map_or(false, |peer| match &peer.status { - P2pPeerStatus::Connecting(P2pConnectionState::Incoming( - P2pConnectionIncomingState::AnswerSdpCreateSuccess { .. }, - )) => true, - _ => false, - }), - P2pConnectionIncomingAction::AnswerSendSuccess { peer_id } => state - .peers - .get(peer_id) - .map_or(false, |peer| match &peer.status { - P2pPeerStatus::Connecting(P2pConnectionState::Incoming( - P2pConnectionIncomingState::AnswerReady { .. }, - )) => true, - _ => false, - }), - P2pConnectionIncomingAction::FinalizePending { peer_id } => state - .peers - .get(peer_id) - .map_or(false, |peer| match &peer.status { - P2pPeerStatus::Connecting(P2pConnectionState::Incoming( - P2pConnectionIncomingState::AnswerSendSuccess { .. }, - )) => true, - _ => false, - }), - P2pConnectionIncomingAction::FinalizeError { peer_id, .. } => state - .peers - .get(peer_id) - .map_or(false, |peer| match &peer.status { - P2pPeerStatus::Connecting(P2pConnectionState::Incoming( - P2pConnectionIncomingState::FinalizePending { .. }, - )) => true, - _ => false, - }), - P2pConnectionIncomingAction::FinalizeSuccess { peer_id } => state - .peers - .get(peer_id) - .map_or(false, |peer| match &peer.status { - P2pPeerStatus::Connecting(P2pConnectionState::Incoming( - P2pConnectionIncomingState::FinalizePending { .. }, - )) => true, - _ => false, - }), + P2pConnectionIncomingAction::AnswerSdpCreatePending { peer_id } => { + state.peers.get(peer_id).map_or(false, |peer| { + matches!( + &peer.status, + P2pPeerStatus::Connecting(P2pConnectionState::Incoming( + P2pConnectionIncomingState::Init { .. }, + )) + ) + }) + } + P2pConnectionIncomingAction::AnswerSdpCreateError { peer_id, .. } => { + state.peers.get(peer_id).map_or(false, |peer| { + matches!( + &peer.status, + P2pPeerStatus::Connecting(P2pConnectionState::Incoming( + P2pConnectionIncomingState::AnswerSdpCreatePending { .. }, + )) + ) + }) + } + P2pConnectionIncomingAction::AnswerSdpCreateSuccess { peer_id, .. } => { + state.peers.get(peer_id).map_or(false, |peer| { + matches!( + &peer.status, + P2pPeerStatus::Connecting(P2pConnectionState::Incoming( + P2pConnectionIncomingState::AnswerSdpCreatePending { .. }, + )) + ) + }) + } + P2pConnectionIncomingAction::AnswerReady { peer_id, .. } => { + state.peers.get(peer_id).map_or(false, |peer| { + matches!( + &peer.status, + P2pPeerStatus::Connecting(P2pConnectionState::Incoming( + P2pConnectionIncomingState::AnswerSdpCreateSuccess { .. }, + )) + ) + }) + } + P2pConnectionIncomingAction::AnswerSendSuccess { peer_id } => { + state.peers.get(peer_id).map_or(false, |peer| { + matches!( + &peer.status, + P2pPeerStatus::Connecting(P2pConnectionState::Incoming( + P2pConnectionIncomingState::AnswerReady { .. }, + )) + ) + }) + } + P2pConnectionIncomingAction::FinalizePending { peer_id } => { + state.peers.get(peer_id).map_or(false, |peer| { + matches!( + &peer.status, + P2pPeerStatus::Connecting(P2pConnectionState::Incoming( + P2pConnectionIncomingState::AnswerSendSuccess { .. }, + )) + ) + }) + } + P2pConnectionIncomingAction::FinalizeError { peer_id, .. } => { + state.peers.get(peer_id).map_or(false, |peer| { + matches!( + &peer.status, + P2pPeerStatus::Connecting(P2pConnectionState::Incoming( + P2pConnectionIncomingState::FinalizePending { .. }, + )) + ) + }) + } + P2pConnectionIncomingAction::FinalizeSuccess { peer_id } => { + state.peers.get(peer_id).map_or(false, |peer| { + matches!( + &peer.status, + P2pPeerStatus::Connecting(P2pConnectionState::Incoming( + P2pConnectionIncomingState::FinalizePending { .. }, + )) + ) + }) + } P2pConnectionIncomingAction::Timeout { peer_id } => state .peers .get(peer_id) @@ -177,19 +185,18 @@ impl redux::EnablingCondition for P2pConnectionIncomingAction { _ => false, }), P2pConnectionIncomingAction::Success { peer_id } => { - state - .peers - .get(peer_id) - .map_or(false, |peer| match &peer.status { + state.peers.get(peer_id).map_or(false, |peer| { + matches!( + &peer.status, P2pPeerStatus::Connecting(P2pConnectionState::Incoming( P2pConnectionIncomingState::FinalizeSuccess { .. }, - )) => true, - _ => false, - }) + )) + ) + }) } P2pConnectionIncomingAction::Libp2pReceived { peer_id } => { - state.peers.get(&peer_id).map_or(true, |peer| { + state.peers.get(peer_id).map_or(true, |peer| { matches!(&peer.status, P2pPeerStatus::Disconnected { .. }) }) } diff --git a/p2p/src/connection/outgoing/mod.rs b/p2p/src/connection/outgoing/mod.rs index a9a5776f3..3b3599ada 100644 --- a/p2p/src/connection/outgoing/mod.rs +++ b/p2p/src/connection/outgoing/mod.rs @@ -56,7 +56,7 @@ mod libp2p_opts { impl super::P2pConnectionOutgoingInitLibp2pOpts { fn to_peer_id_multiaddr(&self) -> (PeerId, Multiaddr) { ( - self.peer_id.clone(), + self.peer_id, Multiaddr::from_iter([(&self.host).into(), multiaddr::Protocol::Tcp(self.port)]), ) } @@ -186,14 +186,14 @@ impl P2pConnectionOutgoingInitOpts { host: format!("http://{}", info.host).as_bytes().into(), libp2p_port: (info.port as u64).into(), peer_id: v2::NetworkPeerPeerIdStableV1( - PeerId::from(*peer_id).to_string().into_bytes().into(), + (*peer_id).to_string().into_bytes().into(), ), }), SignalingMethod::Https(info) => Some(v2::NetworkPeerPeerStableV1 { host: format!("https://{}", info.host).as_bytes().into(), libp2p_port: (info.port as u64).into(), peer_id: v2::NetworkPeerPeerIdStableV1( - PeerId::from(*peer_id).to_string().into_bytes().into(), + (*peer_id).to_string().into_bytes().into(), ), }), }, @@ -298,7 +298,7 @@ impl<'de> Deserialize<'de> for P2pConnectionOutgoingInitOpts { D: serde::Deserializer<'de>, { let s: String = Deserialize::deserialize(deserializer)?; - Ok(s.parse().map_err(|err| serde::de::Error::custom(err))?) + s.parse().map_err(serde::de::Error::custom) } } @@ -315,9 +315,7 @@ impl From<&P2pConnectionOutgoingInitLibp2pOpts> for multiaddr::Multiaddr { Host::Ipv6(v) => Protocol::Ip6(*v), }) .with(Protocol::Tcp(value.port)) - .with(Protocol::P2p( - libp2p_identity::PeerId::from(value.peer_id).into(), - )) + .with(Protocol::P2p(libp2p_identity::PeerId::from(value.peer_id))) } } diff --git a/p2p/src/connection/outgoing/p2p_connection_outgoing_actions.rs b/p2p/src/connection/outgoing/p2p_connection_outgoing_actions.rs index 94e207311..fddfda77e 100644 --- a/p2p/src/connection/outgoing/p2p_connection_outgoing_actions.rs +++ b/p2p/src/connection/outgoing/p2p_connection_outgoing_actions.rs @@ -155,78 +155,86 @@ impl redux::EnablingCondition for P2pConnectionOutgoingAction { || time.checked_sub(t) >= state.config.timeouts.reconnect_timeout }) } - P2pConnectionOutgoingAction::OfferSdpCreatePending { peer_id } => state - .peers - .get(peer_id) - .map_or(false, |peer| match &peer.status { - P2pPeerStatus::Connecting(P2pConnectionState::Outgoing( - P2pConnectionOutgoingState::Init { .. }, - )) => true, - _ => false, - }), - P2pConnectionOutgoingAction::OfferSdpCreateError { peer_id, .. } => state - .peers - .get(peer_id) - .map_or(false, |peer| match &peer.status { - P2pPeerStatus::Connecting(P2pConnectionState::Outgoing( - P2pConnectionOutgoingState::OfferSdpCreatePending { .. }, - )) => true, - _ => false, - }), - P2pConnectionOutgoingAction::OfferSdpCreateSuccess { peer_id, .. } => state - .peers - .get(peer_id) - .map_or(false, |peer| match &peer.status { - P2pPeerStatus::Connecting(P2pConnectionState::Outgoing( - P2pConnectionOutgoingState::OfferSdpCreatePending { .. }, - )) => true, - _ => false, - }), - P2pConnectionOutgoingAction::OfferReady { peer_id, .. } => state - .peers - .get(peer_id) - .map_or(false, |peer| match &peer.status { - P2pPeerStatus::Connecting(P2pConnectionState::Outgoing( - P2pConnectionOutgoingState::OfferSdpCreateSuccess { .. }, - )) => true, - _ => false, - }), - P2pConnectionOutgoingAction::OfferSendSuccess { peer_id } => state - .peers - .get(peer_id) - .map_or(false, |peer| match &peer.status { - P2pPeerStatus::Connecting(P2pConnectionState::Outgoing( - P2pConnectionOutgoingState::OfferReady { .. }, - )) => true, - _ => false, - }), - P2pConnectionOutgoingAction::AnswerRecvPending { peer_id } => state - .peers - .get(peer_id) - .map_or(false, |peer| match &peer.status { - P2pPeerStatus::Connecting(P2pConnectionState::Outgoing( - P2pConnectionOutgoingState::OfferSendSuccess { .. }, - )) => true, - _ => false, - }), - P2pConnectionOutgoingAction::AnswerRecvError { peer_id, .. } => state - .peers - .get(peer_id) - .map_or(false, |peer| match &peer.status { - P2pPeerStatus::Connecting(P2pConnectionState::Outgoing( - P2pConnectionOutgoingState::AnswerRecvPending { .. }, - )) => true, - _ => false, - }), - P2pConnectionOutgoingAction::AnswerRecvSuccess { peer_id, .. } => state - .peers - .get(peer_id) - .map_or(false, |peer| match &peer.status { - P2pPeerStatus::Connecting(P2pConnectionState::Outgoing( - P2pConnectionOutgoingState::AnswerRecvPending { .. }, - )) => true, - _ => false, - }), + P2pConnectionOutgoingAction::OfferSdpCreatePending { peer_id } => { + state.peers.get(peer_id).map_or(false, |peer| { + matches!( + &peer.status, + P2pPeerStatus::Connecting(P2pConnectionState::Outgoing( + P2pConnectionOutgoingState::Init { .. }, + )) + ) + }) + } + P2pConnectionOutgoingAction::OfferSdpCreateError { peer_id, .. } => { + state.peers.get(peer_id).map_or(false, |peer| { + matches!( + &peer.status, + P2pPeerStatus::Connecting(P2pConnectionState::Outgoing( + P2pConnectionOutgoingState::OfferSdpCreatePending { .. }, + )) + ) + }) + } + P2pConnectionOutgoingAction::OfferSdpCreateSuccess { peer_id, .. } => { + state.peers.get(peer_id).map_or(false, |peer| { + matches!( + &peer.status, + P2pPeerStatus::Connecting(P2pConnectionState::Outgoing( + P2pConnectionOutgoingState::OfferSdpCreatePending { .. }, + )) + ) + }) + } + P2pConnectionOutgoingAction::OfferReady { peer_id, .. } => { + state.peers.get(peer_id).map_or(false, |peer| { + matches!( + &peer.status, + P2pPeerStatus::Connecting(P2pConnectionState::Outgoing( + P2pConnectionOutgoingState::OfferSdpCreateSuccess { .. }, + )) + ) + }) + } + P2pConnectionOutgoingAction::OfferSendSuccess { peer_id } => { + state.peers.get(peer_id).map_or(false, |peer| { + matches!( + &peer.status, + P2pPeerStatus::Connecting(P2pConnectionState::Outgoing( + P2pConnectionOutgoingState::OfferReady { .. }, + )) + ) + }) + } + P2pConnectionOutgoingAction::AnswerRecvPending { peer_id } => { + state.peers.get(peer_id).map_or(false, |peer| { + matches!( + &peer.status, + P2pPeerStatus::Connecting(P2pConnectionState::Outgoing( + P2pConnectionOutgoingState::OfferSendSuccess { .. }, + )) + ) + }) + } + P2pConnectionOutgoingAction::AnswerRecvError { peer_id, .. } => { + state.peers.get(peer_id).map_or(false, |peer| { + matches!( + &peer.status, + P2pPeerStatus::Connecting(P2pConnectionState::Outgoing( + P2pConnectionOutgoingState::AnswerRecvPending { .. }, + )) + ) + }) + } + P2pConnectionOutgoingAction::AnswerRecvSuccess { peer_id, .. } => { + state.peers.get(peer_id).map_or(false, |peer| { + matches!( + &peer.status, + P2pPeerStatus::Connecting(P2pConnectionState::Outgoing( + P2pConnectionOutgoingState::AnswerRecvPending { .. }, + )) + ) + }) + } P2pConnectionOutgoingAction::FinalizePending { peer_id } => state .peers .get(peer_id) @@ -238,24 +246,26 @@ impl redux::EnablingCondition for P2pConnectionOutgoingAction { }, _ => false, }), - P2pConnectionOutgoingAction::FinalizeError { peer_id, .. } => state - .peers - .get(peer_id) - .map_or(false, |peer| match &peer.status { - P2pPeerStatus::Connecting(P2pConnectionState::Outgoing( - P2pConnectionOutgoingState::FinalizePending { .. }, - )) => true, - _ => false, - }), - P2pConnectionOutgoingAction::FinalizeSuccess { peer_id } => state - .peers - .get(peer_id) - .map_or(false, |peer| match &peer.status { - P2pPeerStatus::Connecting(P2pConnectionState::Outgoing( - P2pConnectionOutgoingState::FinalizePending { .. }, - )) => true, - _ => false, - }), + P2pConnectionOutgoingAction::FinalizeError { peer_id, .. } => { + state.peers.get(peer_id).map_or(false, |peer| { + matches!( + &peer.status, + P2pPeerStatus::Connecting(P2pConnectionState::Outgoing( + P2pConnectionOutgoingState::FinalizePending { .. }, + )) + ) + }) + } + P2pConnectionOutgoingAction::FinalizeSuccess { peer_id } => { + state.peers.get(peer_id).map_or(false, |peer| { + matches!( + &peer.status, + P2pPeerStatus::Connecting(P2pConnectionState::Outgoing( + P2pConnectionOutgoingState::FinalizePending { .. }, + )) + ) + }) + } P2pConnectionOutgoingAction::Timeout { peer_id } => state .peers .get(peer_id) @@ -281,15 +291,14 @@ impl redux::EnablingCondition for P2pConnectionOutgoingAction { _ => false, }), P2pConnectionOutgoingAction::Success { peer_id } => { - state - .peers - .get(peer_id) - .map_or(false, |peer| match &peer.status { + state.peers.get(peer_id).map_or(false, |peer| { + matches!( + &peer.status, P2pPeerStatus::Connecting(P2pConnectionState::Outgoing( P2pConnectionOutgoingState::FinalizeSuccess { .. }, - )) => true, - _ => false, - }) + )) + ) + }) } } } diff --git a/p2p/src/connection/outgoing/p2p_connection_outgoing_effects.rs b/p2p/src/connection/outgoing/p2p_connection_outgoing_effects.rs index fb2c52a12..3cb423cec 100644 --- a/p2p/src/connection/outgoing/p2p_connection_outgoing_effects.rs +++ b/p2p/src/connection/outgoing/p2p_connection_outgoing_effects.rs @@ -139,12 +139,13 @@ impl P2pConnectionOutgoingAction { }); } P2pConnectionOutgoingAction::Error { peer_id, error } => { - if let Some(_) = store + if store .state() .network .scheduler .discovery_state() .and_then(|discovery_state| discovery_state.request(&peer_id)) + .is_some() { store.dispatch(P2pNetworkKadRequestAction::Error { peer_id, diff --git a/p2p/src/discovery/p2p_discovery_reducer.rs b/p2p/src/discovery/p2p_discovery_reducer.rs index ec3ce5536..474fc8acf 100644 --- a/p2p/src/discovery/p2p_discovery_reducer.rs +++ b/p2p/src/discovery/p2p_discovery_reducer.rs @@ -26,18 +26,13 @@ impl P2pKademliaState { // TODO(vlad9486): handle failure, decrement the counter self.outgoing_requests -= 1; let len = self.known_peers.len(); - self.known_peers.extend( - peers - .iter() - .map(|peer_id| { - // TODO(vlad9486): use all - self.routes - .get(peer_id) - .and_then(|r| r.first()) - .map(|opts| (opts.peer_id().clone(), opts.clone())) - }) - .flatten(), - ); + self.known_peers.extend(peers.iter().filter_map(|peer_id| { + // TODO(vlad9486): use all + self.routes + .get(peer_id) + .and_then(|r| r.first()) + .map(|opts| (*opts.peer_id(), opts.clone())) + })); if self.known_peers.len() == len { // this response doesn't yield new peers self.saturated = Some(meta.time()); diff --git a/p2p/src/identity/peer_id.rs b/p2p/src/identity/peer_id.rs index e6816bca8..d074bd471 100644 --- a/p2p/src/identity/peer_id.rs +++ b/p2p/src/identity/peer_id.rs @@ -141,7 +141,7 @@ impl From for libp2p_identity::PeerId { fn from(value: PeerId) -> Self { let key = libp2p_identity::ed25519::PublicKey::try_from_bytes(&value.to_bytes()).unwrap(); #[allow(deprecated)] - let key = libp2p_identity::PublicKey::try_from(key).unwrap(); + let key = libp2p_identity::PublicKey::from(key); key.to_peer_id() } } diff --git a/p2p/src/lib.rs b/p2p/src/lib.rs index a03be9002..21d233ae3 100644 --- a/p2p/src/lib.rs +++ b/p2p/src/lib.rs @@ -1,3 +1,8 @@ +#![allow(clippy::large_enum_variant)] +#![allow(clippy::type_complexity)] +// TODO(akoptelov): We should resolve this lint +#![allow(clippy::suspicious_arithmetic_impl)] + ///#![feature(trivial_bounds)] pub mod channels; pub mod connection; diff --git a/p2p/src/listen/p2p_listen_reducer.rs b/p2p/src/listen/p2p_listen_reducer.rs index 2f65f44a6..9de51b010 100644 --- a/p2p/src/listen/p2p_listen_reducer.rs +++ b/p2p/src/listen/p2p_listen_reducer.rs @@ -15,8 +15,8 @@ impl P2pListenersState { } } super::P2pListenAction::Expired { listener_id, addr } => { - if let Some(P2pListenerState::Open { addrs, .. }) = self.0.get_mut(&listener_id) { - addrs.remove(&addr); + if let Some(P2pListenerState::Open { addrs, .. }) = self.0.get_mut(listener_id) { + addrs.remove(addr); } } super::P2pListenAction::Error { listener_id, error } => { diff --git a/p2p/src/network/kad/bootstrap/p2p_network_kad_bootstrap_reducer.rs b/p2p/src/network/kad/bootstrap/p2p_network_kad_bootstrap_reducer.rs index 2b48df5b1..b86113b3a 100644 --- a/p2p/src/network/kad/bootstrap/p2p_network_kad_bootstrap_reducer.rs +++ b/p2p/src/network/kad/bootstrap/p2p_network_kad_bootstrap_reducer.rs @@ -14,7 +14,7 @@ use crate::{ use super::{P2pNetworkKadBootstrapAction, P2pNetworkKadBootstrapState}; fn prepare_next_request( - addrs: &Vec, + addrs: &[Multiaddr], time: Timestamp, filter_addrs: bool, ) -> Option { @@ -32,9 +32,7 @@ fn prepare_next_request( } }); - let Some(addr) = addrs.next() else { - return None; - }; + let addr = addrs.next()?; let addrs_to_use = addrs.collect(); Some(P2pNetworkKadBoostrapRequestState { addr, @@ -88,7 +86,7 @@ impl P2pNetworkKadBootstrapState { peer_id, closest_peers, } => { - let Some(req) = self.requests.remove(&peer_id) else { + let Some(req) = self.requests.remove(peer_id) else { return Err(format!("cannot find reques for peer {peer_id}")); }; self.successful_requests += 1; @@ -121,7 +119,7 @@ impl P2pNetworkKadBootstrapState { Ok(()) } A::RequestError { peer_id, error } => { - let Some(req) = self.requests.remove(&peer_id) else { + let Some(req) = self.requests.remove(peer_id) else { return Err(format!("cannot find reques for peer {peer_id}")); }; let address = P2pConnectionOutgoingInitOpts::LibP2P((*peer_id, req.addr).into()); diff --git a/p2p/src/network/kad/p2p_network_kad_internals.rs b/p2p/src/network/kad/p2p_network_kad_internals.rs index c01865e0f..ac5dea970 100644 --- a/p2p/src/network/kad/p2p_network_kad_internals.rs +++ b/p2p/src/network/kad/p2p_network_kad_internals.rs @@ -46,7 +46,7 @@ mod u256_serde { { if deserializer.is_human_readable() { let s = String::deserialize(deserializer)?; - let bytes = hex::decode(&s) + let bytes = hex::decode(s) .map_err(decode_error)? .as_slice() .try_into() @@ -66,7 +66,7 @@ pub struct P2pNetworkKadKey(#[serde(with = "u256_serde")] U256); impl From<&PeerId> for P2pNetworkKadKey { fn from(value: &PeerId) -> Self { P2pNetworkKadKey(U256::from_be_byte_array(Sha256::digest( - libp2p_identity::PeerId::from(value.clone()).to_bytes(), + libp2p_identity::PeerId::from(*value).to_bytes(), ))) } } @@ -75,7 +75,7 @@ impl Debug for P2pNetworkKadKey { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { if f.alternate() { let bytes = self.0.to_be_bytes(); - f.write_str(&hex::encode(&bytes)) + f.write_str(&hex::encode(bytes)) } else { f.debug_tuple("P2pNetworkKadKey").field(&self.0).finish() } @@ -86,7 +86,7 @@ impl Add<&P2pNetworkKadDist> for &P2pNetworkKadKey { type Output = P2pNetworkKadKey; fn add(self, rhs: &P2pNetworkKadDist) -> Self::Output { - P2pNetworkKadKey(&self.0 ^ &rhs.0) + P2pNetworkKadKey(self.0 ^ rhs.0) } } @@ -102,7 +102,7 @@ impl Sub<&P2pNetworkKadKey> for &P2pNetworkKadKey { type Output = P2pNetworkKadDist; fn sub(self, rhs: &P2pNetworkKadKey) -> Self::Output { - P2pNetworkKadDist(&self.0 ^ &rhs.0) + P2pNetworkKadDist(self.0 ^ rhs.0) } } @@ -110,7 +110,7 @@ impl Sub for &P2pNetworkKadKey { type Output = P2pNetworkKadDist; fn sub(self, rhs: P2pNetworkKadKey) -> Self::Output { - P2pNetworkKadDist(&self.0 ^ rhs.0) + P2pNetworkKadDist(self.0 ^ rhs.0) } } @@ -118,7 +118,7 @@ impl Sub<&P2pNetworkKadKey> for P2pNetworkKadKey { type Output = P2pNetworkKadDist; fn sub(self, rhs: &P2pNetworkKadKey) -> Self::Output { - P2pNetworkKadDist(self.0 ^ &rhs.0) + P2pNetworkKadDist(self.0 ^ rhs.0) } } @@ -126,13 +126,13 @@ impl Shr for &P2pNetworkKadKey { type Output = P2pNetworkKadKey; fn shr(self, rhs: usize) -> Self::Output { - P2pNetworkKadKey(&self.0 >> rhs) + P2pNetworkKadKey(self.0 >> rhs) } } impl From for P2pNetworkKadKey { fn from(value: PeerId) -> Self { - let digest = Sha256::digest(&value.to_bytes()); + let digest = Sha256::digest(value.to_bytes()); P2pNetworkKadKey(::from_be_byte_array(digest)) } } @@ -145,7 +145,7 @@ impl Debug for P2pNetworkKadDist { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { if f.alternate() { let bytes = self.0.to_be_bytes(); - f.write_str(&hex::encode(&bytes)) + f.write_str(&hex::encode(bytes)) } else { f.debug_tuple("P2pNetworkKadDist").field(&self.0).finish() } @@ -254,28 +254,26 @@ impl P2pNetworkKadRoutingTable { } else { Err(P2pNetworkKadRoutingTableInsertError) } + } else if self.buckets[max_index].can_insert(&entry) { + Ok(self.buckets[max_index].insert(entry)) } else { - if self.buckets[max_index].can_insert(&entry) { - Ok(self.buckets[max_index].insert(entry)) + let split_dist = (max_index + 1).into(); + let Some((mut bucket1, mut bucket2)) = self + .buckets + .pop() + .map(|b| b.split(|e| (&self.this_key - &e.key) >= split_dist)) + else { + debug_assert!(false, "should be unreachable"); + return Err(P2pNetworkKadRoutingTableInsertError); + }; + + if max_index == index { + bucket1.insert(entry); } else { - let split_dist = (max_index + 1).into(); - let Some((mut bucket1, mut bucket2)) = self - .buckets - .pop() - .map(|b| b.split(|e| &(&self.this_key - &e.key) >= &split_dist)) - else { - debug_assert!(false, "should be unreachable"); - return Err(P2pNetworkKadRoutingTableInsertError); - }; - - if max_index == index { - bucket1.insert(entry); - } else { - bucket2.insert(entry); - }; - self.buckets.extend([bucket1, bucket2]); - Ok(true) - } + bucket2.insert(entry); + }; + self.buckets.extend([bucket1, bucket2]); + Ok(true) } } @@ -343,7 +341,7 @@ pub struct P2pNetworkKadEntry { impl P2pNetworkKadEntry { pub fn new(peer_id: PeerId, addrs: Vec) -> Self { - let key = peer_id.clone().into(); + let key = peer_id.into(); P2pNetworkKadEntry { key, peer_id, @@ -370,7 +368,7 @@ impl TryFrom> for P2pNetworkKadEntry { fn try_from(value: super::mod_Message::Peer) -> Result { let peer_id = super::peer_id_try_from_bytes(value.id)?; - let key = peer_id.clone().into(); + let key = peer_id.into(); let addrs = value .addrs .into_iter() @@ -432,7 +430,7 @@ impl<'a, const K: usize> Iterator for ClosestPeers<'a, K> { // TODO: items from other buckets might need sorting loop { if let Some(item) = self.bucket_iterator.next() { - if &item.key == self.key || &item.key == &self.table.this_key { + if &item.key == self.key || item.key == self.table.this_key { continue; } return Some(item); @@ -465,6 +463,10 @@ impl P2pNetworkKadBucket { self.0.len() } + pub fn is_empty(&self) -> bool { + self.0.is_empty() + } + pub fn iter(&self) -> std::slice::Iter<'_, P2pNetworkKadEntry> { self.0.iter() } @@ -473,15 +475,15 @@ impl P2pNetworkKadBucket { /// there is a free slot, or the entry with this peer_id already there and /// only needs to be updated. fn can_insert(&self, entry: &P2pNetworkKadEntry) -> bool { - self.len() < K || self.0.iter().any(|e| &e.key == &entry.key) + self.len() < K || self.0.iter().any(|e| e.key == entry.key) } /// Inserts an entry into the bucket. Returns true if a new entry is added, /// false if an existing one is updated. fn insert(&mut self, entry: P2pNetworkKadEntry) -> bool { - if let Some(pos) = self.0.iter().position(|e| &e.key == &entry.key) { + if let Some(pos) = self.0.iter().position(|e| e.key == entry.key) { let e = &mut self.0[pos]; - debug_assert!(&e.peer_id == &entry.peer_id); + debug_assert!(e.peer_id == entry.peer_id); for addr in entry.addrs { if !e.addrs.contains(&addr) { e.addrs.push(addr); @@ -557,14 +559,14 @@ mod tests { let peer_id = peer_id_rand(); P2pNetworkKadEntry { key, - peer_id: peer_id.into(), + peer_id, addrs: vec![], connection: super::ConnectionType::Connected, } } fn entry_with_peer_id(peer_id: PeerId) -> P2pNetworkKadEntry { - let key = peer_id.clone().into(); + let key = peer_id.into(); P2pNetworkKadEntry { key, peer_id, @@ -672,8 +674,8 @@ mod tests { .min_by_key(|e| entry.dist(e)) .unwrap(); - let max = entry.dist(&max_closest_dist); - let min = entry.dist(&min_non_closest_dist); + let max = entry.dist(max_closest_dist); + let min = entry.dist(min_non_closest_dist); println!( "farthest {:#?} is closer than the closest {:#?}", max_closest_dist.key, min_non_closest_dist.key @@ -707,8 +709,8 @@ mod tests { .min_by_key(|e| entry.dist(e)) .unwrap(); - let max = entry.dist(&max_closest_dist); - let min = entry.dist(&min_non_closest_dist); + let max = entry.dist(max_closest_dist); + let min = entry.dist(min_non_closest_dist); println!( "farthest {:#?} is closer than the closest {:#?}", max_closest_dist.key, min_non_closest_dist.key diff --git a/p2p/src/network/kad/p2p_network_kad_protocol.rs b/p2p/src/network/kad/p2p_network_kad_protocol.rs index 76e5316b5..1b97ff6d7 100644 --- a/p2p/src/network/kad/p2p_network_kad_protocol.rs +++ b/p2p/src/network/kad/p2p_network_kad_protocol.rs @@ -87,9 +87,7 @@ pub(super) fn peer_id_try_from_bytes( impl<'a> From<&PeerId> for Cow<'a, [u8]> { fn from(value: &PeerId) -> Self { - libp2p_identity::PeerId::from(value.clone()) - .to_bytes() - .into() + libp2p_identity::PeerId::from(*value).to_bytes().into() } } @@ -259,7 +257,7 @@ pub mod tests { .parse::() .unwrap(); assert_eq!( - from_bytes(&libp2p_identity::PeerId::from(peer_id.clone()).to_bytes()).unwrap(), + from_bytes(&libp2p_identity::PeerId::from(peer_id).to_bytes()).unwrap(), peer_id ); } diff --git a/p2p/src/network/kad/p2p_network_kad_reducer.rs b/p2p/src/network/kad/p2p_network_kad_reducer.rs index 88a76b0b8..d3a094954 100644 --- a/p2p/src/network/kad/p2p_network_kad_reducer.rs +++ b/p2p/src/network/kad/p2p_network_kad_reducer.rs @@ -23,7 +23,7 @@ impl super::P2pNetworkKadState { P2pNetworkKadAction::Request( action @ super::request::P2pNetworkKadRequestAction::New { addr, peer_id, key }, ) => self - .create_request(*addr, peer_id.clone(), key.clone()) + .create_request(*addr, *peer_id, *key) .map_err(|_request| format!("kademlia request to {addr} is already in progress")) .and_then(|request| request.reducer(meta.with_action(action))), P2pNetworkKadAction::Request(super::request::P2pNetworkKadRequestAction::Prune { @@ -75,15 +75,14 @@ impl super::P2pNetworkKadState { Ok(false) => P2pNetworkKadLatestRequestPeerKind::Existing, Err(_) => P2pNetworkKadLatestRequestPeerKind::Discarded, }; - latest_request_peers.push((entry.peer_id.clone(), kind)); + latest_request_peers.push((entry.peer_id, kind)); } self.latest_request_peers = latest_request_peers.into(); Ok(()) } (_, StartBootstrap { key }) => { - self.status = Bootstrapping(super::bootstrap::P2pNetworkKadBootstrapState::new( - key.clone(), - )); + self.status = + Bootstrapping(super::bootstrap::P2pNetworkKadBootstrapState::new(*key)); Ok(()) } (Bootstrapping(state), BootstrapFinished {}) => { diff --git a/p2p/src/network/kad/p2p_network_kad_state.rs b/p2p/src/network/kad/p2p_network_kad_state.rs index 07c1a4e88..0bfad4e66 100644 --- a/p2p/src/network/kad/p2p_network_kad_state.rs +++ b/p2p/src/network/kad/p2p_network_kad_state.rs @@ -114,12 +114,7 @@ impl P2pNetworkKadState { peer_id: &PeerId, stream_id: &StreamId, ) -> Result<&mut P2pNetworkKadStreamState, &P2pNetworkKadStreamState> { - match self - .streams - .entry(peer_id.clone()) - .or_default() - .entry(*stream_id) - { + match self.streams.entry(*peer_id).or_default().entry(*stream_id) { std::collections::btree_map::Entry::Vacant(e) => Ok(e.insert(Default::default())), std::collections::btree_map::Entry::Occupied(e) => Err(e.into_mut()), } diff --git a/p2p/src/network/kad/request/p2p_network_kad_request_effects.rs b/p2p/src/network/kad/request/p2p_network_kad_request_effects.rs index ef3fc1d05..9a3b050c0 100644 --- a/p2p/src/network/kad/request/p2p_network_kad_request_effects.rs +++ b/p2p/src/network/kad/request/p2p_network_kad_request_effects.rs @@ -126,8 +126,7 @@ impl P2pNetworkKadRequestAction { stream_id, addr, } => { - let data = - crate::P2pNetworkKademliaRpcRequest::find_node(request_state.key.clone()); + let data = crate::P2pNetworkKademliaRpcRequest::find_node(request_state.key); store.dispatch(P2pNetworkKademliaStreamAction::SendRequest { addr, peer_id, @@ -158,7 +157,7 @@ impl P2pNetworkKadRequestAction { }; for entry in data { let peer_id = entry.peer_id; - let to_opts = |addr| (peer_id.clone(), addr).into(); + let to_opts = |addr| (peer_id, addr).into(); let addresses = entry .addrs .iter() diff --git a/p2p/src/network/kad/request/p2p_network_kad_request_reducer.rs b/p2p/src/network/kad/request/p2p_network_kad_request_reducer.rs index edb01ecab..ff899deda 100644 --- a/p2p/src/network/kad/request/p2p_network_kad_request_reducer.rs +++ b/p2p/src/network/kad/request/p2p_network_kad_request_reducer.rs @@ -21,13 +21,11 @@ impl P2pNetworkKadRequestState { self.status = S::WaitingForKadStream(*stream_id) } A::StreamReady { .. } => { - let find_node = P2pNetworkKademliaRpcRequest::FindNode { - key: self.key.clone(), - }; + let find_node = P2pNetworkKademliaRpcRequest::FindNode { key: self.key }; let message = super::super::Message::from(&find_node); self.status = quick_protobuf::serialize_into_vec(&message).map_or_else( |e| S::Error(format!("error serializing message: {e}")), - |b| S::Request(b), + S::Request, ); } A::RequestSent { .. } => self.status = S::WaitingForReply, diff --git a/p2p/src/network/kad/stream/p2p_network_kad_stream_effects.rs b/p2p/src/network/kad/stream/p2p_network_kad_stream_effects.rs index 0d7213b0c..6520f07d5 100644 --- a/p2p/src/network/kad/stream/p2p_network_kad_stream_effects.rs +++ b/p2p/src/network/kad/stream/p2p_network_kad_stream_effects.rs @@ -56,7 +56,7 @@ impl P2pNetworkKademliaStreamAction { addr, peer_id, stream_id, - key: key.clone(), + key: *key, }); store.dispatch(A::WaitOutgoing { addr, diff --git a/p2p/src/network/kad/stream/p2p_network_kad_stream_reducer.rs b/p2p/src/network/kad/stream/p2p_network_kad_stream_reducer.rs index 0680c8330..a44c41c81 100644 --- a/p2p/src/network/kad/stream/p2p_network_kad_stream_reducer.rs +++ b/p2p/src/network/kad/stream/p2p_network_kad_stream_reducer.rs @@ -140,11 +140,9 @@ impl P2pNetworkKadStreamState { *self = S::Closed; Ok(()) } - _ => { - return Err(format!( - "kademlia state {self:?} is incorrect for action {action:?}" - )); - } + _ => Err(format!( + "kademlia state {self:?} is incorrect for action {action:?}" + )), } } diff --git a/p2p/src/network/mod.rs b/p2p/src/network/mod.rs index cd5e81eae..2abe9e6e6 100644 --- a/p2p/src/network/mod.rs +++ b/p2p/src/network/mod.rs @@ -49,7 +49,7 @@ mod data { where S: serde::Serializer, { - hex::encode(&self.0).serialize(serializer) + hex::encode(self.0).serialize(serializer) } } @@ -70,7 +70,7 @@ mod data { impl fmt::Display for DataSized { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - write!(f, "{}", hex::encode(&self.0)) + write!(f, "{}", hex::encode(self.0)) } } diff --git a/p2p/src/network/noise/p2p_network_noise_effects.rs b/p2p/src/network/noise/p2p_network_noise_effects.rs index 1d461b77a..1a4b5a3a8 100644 --- a/p2p/src/network/noise/p2p_network_noise_effects.rs +++ b/p2p/src/network/noise/p2p_network_noise_effects.rs @@ -21,9 +21,7 @@ impl P2pNetworkNoiseAction { let outgoing = state.outgoing_chunks.front().cloned(); let decrypted = state.decrypted_chunks.front().cloned(); let remote_peer_id = match &state.inner { - Some(P2pNetworkNoiseStateInner::Done { remote_peer_id, .. }) => { - Some(remote_peer_id.clone()) - } + Some(P2pNetworkNoiseStateInner::Done { remote_peer_id, .. }) => Some(*remote_peer_id), Some(P2pNetworkNoiseStateInner::Initiator(P2pNetworkNoiseStateInitiator { remote_pk: Some(pk), .. @@ -43,7 +41,7 @@ impl P2pNetworkNoiseAction { && *send_nonce == 0 && *recv_nonce == 0 { - Some((remote_peer_id.clone(), *incoming)) + Some((*remote_peer_id, *incoming)) } else { None } @@ -64,7 +62,7 @@ impl P2pNetworkNoiseAction { if let Self::HandshakeDone(a) = self { store.dispatch(P2pNetworkSelectInitAction { addr: a.addr, - kind: SelectKind::Multiplexing(a.peer_id.clone()), + kind: SelectKind::Multiplexing(a.peer_id), incoming: a.incoming, send_handshake: true, }); @@ -73,7 +71,7 @@ impl P2pNetworkNoiseAction { if let Self::DecryptedData(a) = self { let kind = match &a.peer_id.or(remote_peer_id) { - Some(peer_id) => SelectKind::Multiplexing(peer_id.clone()), + Some(peer_id) => SelectKind::Multiplexing(*peer_id), None => SelectKind::MultiplexingNoPeerId, }; if handshake_optimized && middle_initiator { @@ -119,7 +117,7 @@ impl P2pNetworkNoiseAction { Self::IncomingChunk(_) => { if handshake_optimized && middle_responder { let kind = match &remote_peer_id { - Some(peer_id) => SelectKind::Multiplexing(peer_id.clone()), + Some(peer_id) => SelectKind::Multiplexing(*peer_id), None => SelectKind::MultiplexingNoPeerId, }; @@ -158,7 +156,7 @@ impl P2pNetworkNoiseAction { .data .iter() .fold(vec![], |mut v, item| { - v.extend_from_slice(&*item); + v.extend_from_slice(item); v }) .into(), @@ -181,14 +179,12 @@ impl P2pNetworkNoiseAction { data: Data(vec![].into_boxed_slice()), }); } - } else { - if let Some((peer_id, incoming)) = handshake_done { - store.dispatch(P2pNetworkNoiseHandshakeDoneAction { - addr: self.addr(), - peer_id, - incoming, - }); - } + } else if let Some((peer_id, incoming)) = handshake_done { + store.dispatch(P2pNetworkNoiseHandshakeDoneAction { + addr: self.addr(), + peer_id, + incoming, + }); } } } diff --git a/p2p/src/network/noise/p2p_network_noise_reducer.rs b/p2p/src/network/noise/p2p_network_noise_reducer.rs index 48b7108f6..e63b53c18 100644 --- a/p2p/src/network/noise/p2p_network_noise_reducer.rs +++ b/p2p/src/network/noise/p2p_network_noise_reducer.rs @@ -137,8 +137,9 @@ impl P2pNetworkNoiseState { let data = &mut chunk[2..]; let (data, tag) = data.split_at_mut(data.len() - 16); let tag = GenericArray::from_slice(&*tag); - if let Err(_) = - aead.decrypt_in_place_detached(&nonce, &[], data, tag) + if aead + .decrypt_in_place_detached(&nonce, &[], data, tag) + .is_err() { *state = P2pNetworkNoiseStateInner::Error(dbg!( NoiseError::FirstMacMismatch diff --git a/p2p/src/network/noise/p2p_network_noise_state.rs b/p2p/src/network/noise/p2p_network_noise_state.rs index 80d82422b..2c81e0cf6 100644 --- a/p2p/src/network/noise/p2p_network_noise_state.rs +++ b/p2p/src/network/noise/p2p_network_noise_state.rs @@ -89,7 +89,7 @@ impl NoiseState { pub fn mix_hash(&mut self, data: &[u8]) { self.hash = DataSized( Sha256::default() - .chain(&self.hash.0) + .chain(self.hash.0) .chain(data) .finalize_fixed() .into(), @@ -110,7 +110,7 @@ impl NoiseState { nonce[4..].clone_from_slice(&NONCE.to_le_bytes()); let hash = Sha256::default() - .chain(&self.hash.0) + .chain(self.hash.0) .chain(&*data) .chain(tag) .finalize_fixed(); @@ -129,7 +129,7 @@ impl NoiseState { .encrypt_in_place_detached(&nonce, &self.hash.0, data) .unwrap(); let hash = Sha256::default() - .chain(&self.hash.0) + .chain(self.hash.0) .chain(&*data) .chain(tag) .finalize_fixed(); @@ -199,7 +199,7 @@ impl P2pNetworkNoiseStateInitiator { let mut chunk = vec![0; 2]; chunk.extend_from_slice(&i_spk_bytes); chunk.extend_from_slice(&tag); - chunk.extend_from_slice(&*payload); + chunk.extend_from_slice(&payload); chunk.extend_from_slice(&payload_tag); let l = (chunk.len() - 2) as u16; chunk[..2].clone_from_slice(&l.to_be_bytes()); @@ -229,7 +229,6 @@ impl P2pNetworkNoiseStateInitiator { let mut r_spk_bytes = <[u8; 32]>::try_from(&msg[32..64]).expect("cannot fail, checked above"); let tag = &msg[64..80]; - let r_spk; noise.mix_hash(r_epk.0.as_bytes()); noise.mix_secret(&*i_esk * &r_epk); @@ -237,7 +236,7 @@ impl P2pNetworkNoiseStateInitiator { .decrypt::<0>(&mut r_spk_bytes, tag) .map_err(|_| FirstMacMismatch)?; - r_spk = Pk::from_bytes(r_spk_bytes); + let r_spk = Pk::from_bytes(r_spk_bytes); noise.mix_secret(&*i_esk * &r_spk); let (msg, tag) = msg.split_at_mut(len - 16); @@ -289,7 +288,7 @@ impl P2pNetworkNoiseStateResponder { } let payload_tag = noise.encrypt::<0>(&mut payload); - buffer.extend_from_slice(&*payload); + buffer.extend_from_slice(&payload); buffer.extend_from_slice(&payload_tag); let l = (buffer.len() - 2) as u16; buffer[..2].clone_from_slice(&l.to_be_bytes()); @@ -358,14 +357,14 @@ impl P2pNetworkNoiseStateResponder { let (remote_payload, payload_tag) = msg.split_at_mut(len - 16); noise - .decrypt::<1>(&mut i_spk_bytes, &tag) + .decrypt::<1>(&mut i_spk_bytes, tag) .map_err(|()| FirstMacMismatch)?; let i_spk = Pk::from_bytes(i_spk_bytes); noise.mix_secret(&*r_esk * &i_spk); r_esk.zeroize(); noise - .decrypt::<0>(remote_payload, &payload_tag) + .decrypt::<0>(remote_payload, payload_tag) .map_err(|_| SecondMacMismatch)?; let (recv_key, send_key) = noise.finish(); @@ -414,7 +413,7 @@ mod wrapper { type Output = [u8; 32]; fn mul(self, rhs: &'b Pk) -> Self::Output { - (&self.0 * &rhs.0).0 + (self.0 * rhs.0).0 } } diff --git a/p2p/src/network/p2p_network_reducer.rs b/p2p/src/network/p2p_network_reducer.rs index f5fe43316..93d239ad9 100644 --- a/p2p/src/network/p2p_network_reducer.rs +++ b/p2p/src/network/p2p_network_reducer.rs @@ -68,50 +68,40 @@ impl P2pNetworkState { ) { let (action, meta) = action.split(); match action { - P2pNetworkAction::Scheduler(a) => self.scheduler.reducer(peers, meta.with_action(&a)), + P2pNetworkAction::Scheduler(a) => self.scheduler.reducer(peers, meta.with_action(a)), P2pNetworkAction::Pnet(a) => { - self.scheduler - .connections - .get_mut(&a.addr()) - .map(|cn| cn.pnet.reducer(meta.with_action(&a))); + if let Some(cn) = self.scheduler.connections.get_mut(&a.addr()) { + cn.pnet.reducer(meta.with_action(a)) + } } P2pNetworkAction::Select(a) => { - self.scheduler - .connections - .get_mut(&a.addr()) - .map(|cn| match a.id() { - SelectKind::Authentication => cn.select_auth.reducer(meta.with_action(&a)), + if let Some(cn) = self.scheduler.connections.get_mut(&a.addr()) { + match a.id() { + SelectKind::Authentication => cn.select_auth.reducer(meta.with_action(a)), SelectKind::Multiplexing(_) | SelectKind::MultiplexingNoPeerId => { - cn.select_mux.reducer(meta.with_action(&a)) + cn.select_mux.reducer(meta.with_action(a)) } SelectKind::Stream(_, stream_id) => { - cn.streams - .get_mut(&stream_id) - .map(|stream| stream.select.reducer(meta.with_action(&a))); + if let Some(stream) = cn.streams.get_mut(&stream_id) { + stream.select.reducer(meta.with_action(a)) + } } - }); + } + } } P2pNetworkAction::Noise(a) => { - self.scheduler - .connections - .get_mut(&a.addr()) - .map(|cn| match &mut cn.auth { - Some(P2pNetworkAuthState::Noise(state)) => { - state.reducer(meta.with_action(&a)) - } - _ => {} - }); + if let Some(cn) = self.scheduler.connections.get_mut(&a.addr()) { + if let Some(P2pNetworkAuthState::Noise(state)) = &mut cn.auth { + state.reducer(meta.with_action(a)) + } + } } P2pNetworkAction::Yamux(a) => { - self.scheduler - .connections - .get_mut(&a.addr()) - .map(|cn| match &mut cn.mux { - Some(P2pNetworkConnectionMuxState::Yamux(state)) => { - state.reducer(&mut cn.streams, meta.with_action(&a)) - } - _ => {} - }); + if let Some(cn) = self.scheduler.connections.get_mut(&a.addr()) { + if let Some(P2pNetworkConnectionMuxState::Yamux(state)) = &mut cn.mux { + state.reducer(&mut cn.streams, meta.with_action(a)) + } + } } P2pNetworkAction::Kad(a) => { let Some(state) = &mut self.scheduler.discovery_state else { @@ -120,7 +110,7 @@ impl P2pNetworkState { }; let time = meta.time(); // println!("======= kad reducer for {state:?}"); - if let Err(err) = state.reducer(meta.with_action(&a)) { + if let Err(err) = state.reducer(meta.with_action(a)) { error!(time; "{err}"); } // println!("======= kad reducer result {state:?}"); @@ -129,7 +119,7 @@ impl P2pNetworkState { if let Some(state) = self.find_rpc_state_mut(a) { if let Some(peer_state) = peers.get_mut(&a.peer_id()) { if let P2pPeerStatus::Ready(status) = &mut peer_state.status { - state.reducer(&mut status.channels.rpc, meta.with_action(&a)) + state.reducer(&mut status.channels.rpc, meta.with_action(a)) } } } diff --git a/p2p/src/network/rpc/p2p_network_rpc_effects.rs b/p2p/src/network/rpc/p2p_network_rpc_effects.rs index 8eccb3abe..e1cc5f0f7 100644 --- a/p2p/src/network/rpc/p2p_network_rpc_effects.rs +++ b/p2p/src/network/rpc/p2p_network_rpc_effects.rs @@ -93,12 +93,12 @@ impl P2pNetworkRpcAction { match (header.tag.to_string_lossy().as_str(), header.version) { (rpc::GetBestTipV2::NAME, rpc::GetBestTipV2::VERSION) => { - let Ok(()) = parse_q::(&bytes) else { + let Ok(()) = parse_q::(bytes) else { // TODO: close the stream panic!(); }; store.dispatch(P2pChannelsRpcAction::RequestReceived { - peer_id: a.peer_id.clone(), + peer_id: a.peer_id, id: header.id as u32, request: P2pRpcRequest::BestTipWithProof, }); @@ -108,7 +108,7 @@ impl P2pNetworkRpcAction { rpc::AnswerSyncLedgerQueryV2::VERSION, ) => { let Ok((hash, query)) = - parse_q::(&bytes) + parse_q::(bytes) else { // TODO: close the stream panic!(); @@ -118,7 +118,7 @@ impl P2pNetworkRpcAction { v2::LedgerHash::from(v2::MinaBaseLedgerHash0StableV1(hash)); store.dispatch(P2pChannelsRpcAction::RequestReceived { - peer_id: a.peer_id.clone(), + peer_id: a.peer_id, id: header.id as u32, request: P2pRpcRequest::LedgerQuery(hash, query), }); @@ -129,7 +129,7 @@ impl P2pNetworkRpcAction { ) => { let Ok(hash) = parse_q::< rpc::GetStagedLedgerAuxAndPendingCoinbasesAtHashV2, - >(&bytes) else { + >(bytes) else { // TODO: close the stream panic!(); }; @@ -140,7 +140,7 @@ impl P2pNetworkRpcAction { P2pRpcRequest::StagedLedgerAuxAndPendingCoinbasesAtBlock(hash); store.dispatch(P2pChannelsRpcAction::RequestReceived { - peer_id: a.peer_id.clone(), + peer_id: a.peer_id, id: header.id as u32, request, }); @@ -149,8 +149,7 @@ impl P2pNetworkRpcAction { rpc::GetTransitionChainV2::NAME, rpc::GetTransitionChainV2::VERSION, ) => { - let Ok(hashes) = parse_q::(&bytes) - else { + let Ok(hashes) = parse_q::(bytes) else { // TODO: close the stream panic!(); }; @@ -160,7 +159,7 @@ impl P2pNetworkRpcAction { v2::StateHash::from(v2::DataHashLibStateHashStableV1(hash)); store.dispatch(P2pChannelsRpcAction::RequestReceived { - peer_id: a.peer_id.clone(), + peer_id: a.peer_id, id: header.id as u32, request: P2pRpcRequest::Block(hash), }); @@ -170,14 +169,14 @@ impl P2pNetworkRpcAction { rpc::GetSomeInitialPeersV1ForV2::NAME, rpc::GetSomeInitialPeersV1ForV2::VERSION, ) => { - let Ok(()) = parse_q::(&bytes) + let Ok(()) = parse_q::(bytes) else { // TODO: close the stream panic!(); }; store.dispatch(P2pChannelsRpcAction::RequestReceived { - peer_id: a.peer_id.clone(), + peer_id: a.peer_id, id: header.id as u32, request: P2pRpcRequest::InitialPeers, }); @@ -199,7 +198,7 @@ impl P2pNetworkRpcAction { if let Ok(tag) = std::str::from_utf8(tag.as_ref()) { match (tag, *version) { (rpc::GetBestTipV2::NAME, rpc::GetBestTipV2::VERSION) => { - let Ok(response) = parse_r::(&bytes) + let Ok(response) = parse_r::(bytes) else { // TODO: close the stream panic!(); @@ -224,7 +223,7 @@ impl P2pNetworkRpcAction { rpc::AnswerSyncLedgerQueryV2::VERSION, ) => { let Ok(response) = - parse_r::(&bytes) + parse_r::(bytes) else { // TODO: close the stream panic!(); @@ -232,8 +231,7 @@ impl P2pNetworkRpcAction { let response = response .ok() - .map(|x| x.0.ok()) - .flatten() + .and_then(|x| x.0.ok()) .map(P2pRpcResponse::LedgerQuery); store.dispatch(P2pChannelsRpcAction::ResponseReceived { @@ -248,7 +246,7 @@ impl P2pNetworkRpcAction { ) => { type Method = rpc::GetStagedLedgerAuxAndPendingCoinbasesAtHashV2; - let Ok(response) = parse_r::(&bytes) else { + let Ok(response) = parse_r::(bytes) else { // TODO: close the stream panic!(); }; @@ -279,7 +277,7 @@ impl P2pNetworkRpcAction { rpc::GetTransitionChainV2::VERSION, ) => { type Method = rpc::GetTransitionChainV2; - let Ok(response) = parse_r::(&bytes) else { + let Ok(response) = parse_r::(bytes) else { // TODO: close the stream panic!(); }; @@ -312,7 +310,7 @@ impl P2pNetworkRpcAction { rpc::GetSomeInitialPeersV1ForV2::VERSION, ) => { type Method = rpc::GetSomeInitialPeersV1ForV2; - let Ok(response) = parse_r::(&bytes) else { + let Ok(response) = parse_r::(bytes) else { // TODO: close the stream panic!(); }; diff --git a/p2p/src/network/scheduler/p2p_network_scheduler_effects.rs b/p2p/src/network/scheduler/p2p_network_scheduler_effects.rs index aa48c59a7..30cb207cd 100644 --- a/p2p/src/network/scheduler/p2p_network_scheduler_effects.rs +++ b/p2p/src/network/scheduler/p2p_network_scheduler_effects.rs @@ -110,7 +110,7 @@ impl P2pNetworkSchedulerAction { }; store.dispatch(P2pNetworkSchedulerYamuxDidInitAction { addr: a.addr, - peer_id: peer_id.clone(), + peer_id, }); } Some(Protocol::Stream(kind)) => { @@ -172,7 +172,7 @@ impl P2pNetworkSchedulerAction { if let Some(P2pNetworkKadRequestState { status: P2pNetworkKadRequestStatus::WaitingForKadStream(id), .. - }) = discovery_state.request(&peer_id) + }) = discovery_state.request(peer_id) { if id == stream_id { store.dispatch(P2pNetworkKadRequestAction::Error { diff --git a/p2p/src/network/scheduler/p2p_network_scheduler_reducer.rs b/p2p/src/network/scheduler/p2p_network_scheduler_reducer.rs index 630860b9e..303f508ec 100644 --- a/p2p/src/network/scheduler/p2p_network_scheduler_reducer.rs +++ b/p2p/src/network/scheduler/p2p_network_scheduler_reducer.rs @@ -64,22 +64,19 @@ impl P2pNetworkSchedulerState { let Some(connection) = self.connections.get_mut(&a.addr) else { return; }; - match &a.kind { - SelectKind::Multiplexing(peer_id) => { - let enabled_channels = Some(ChannelId::Rpc).into_iter().collect(); - let state = P2pPeerState { - is_libp2p: true, - dial_opts: None, - status: P2pPeerStatus::Ready(P2pPeerStatusReady { - is_incoming: a.incoming, - connected_since: meta.time(), - channels: P2pChannelsState::new(&enabled_channels), - best_tip: None, - }), - }; - peers.insert(*peer_id, state); - } - _ => {} + if let SelectKind::Multiplexing(peer_id) = &a.kind { + let enabled_channels = Some(ChannelId::Rpc).into_iter().collect(); + let state = P2pPeerState { + is_libp2p: true, + dial_opts: None, + status: P2pPeerStatus::Ready(P2pPeerStatusReady { + is_incoming: a.incoming, + connected_since: meta.time(), + channels: P2pChannelsState::new(&enabled_channels), + best_tip: None, + }), + }; + peers.insert(*peer_id, state); } match &a.protocol { Some(token::Protocol::Auth(token::AuthKind::Noise)) => { diff --git a/p2p/src/network/yamux/p2p_network_yamux_reducer.rs b/p2p/src/network/yamux/p2p_network_yamux_reducer.rs index 411acfc2b..2017af3eb 100644 --- a/p2p/src/network/yamux/p2p_network_yamux_reducer.rs +++ b/p2p/src/network/yamux/p2p_network_yamux_reducer.rs @@ -35,13 +35,13 @@ impl P2pNetworkYamuxState { let _version = match buf[0] { 0 => 0, unknown => { - self.set_err(YamuxFrameParseError::UnknownVersion(unknown)); + self.set_err(YamuxFrameParseError::Version(unknown)); break; } }; let flags = u16::from_be_bytes(buf[2..4].try_into().expect("cannot fail")); let Some(flags) = YamuxFlags::from_bits(flags) else { - self.set_err(YamuxFrameParseError::UnknownFlags(flags)); + self.set_err(YamuxFrameParseError::Flags(flags)); break; }; let stream_id = @@ -93,9 +93,7 @@ impl P2pNetworkYamuxState { 1 => Err(YamuxSessionError::Protocol), 2 => Err(YamuxSessionError::Internal), unknown => { - self.set_err(YamuxFrameParseError::UnknownErrorCode( - unknown, - )); + self.set_err(YamuxFrameParseError::ErrorCode(unknown)); break; } }; @@ -109,7 +107,7 @@ impl P2pNetworkYamuxState { continue; } unknown => { - self.set_err(YamuxFrameParseError::UnknownType(unknown)); + self.set_err(YamuxFrameParseError::Type(unknown)); break; } } @@ -143,7 +141,7 @@ impl P2pNetworkYamuxState { YamuxFrameInner::WindowUpdate { difference } => { self.streams .entry(frame.stream_id) - .or_insert_with(|| YamuxStreamState::incoming()) + .or_insert_with(YamuxStreamState::incoming) .update_window(false, difference); } YamuxFrameInner::Ping { .. } => {} diff --git a/p2p/src/network/yamux/p2p_network_yamux_state.rs b/p2p/src/network/yamux/p2p_network_yamux_state.rs index 26022460d..7bd6ce183 100644 --- a/p2p/src/network/yamux/p2p_network_yamux_state.rs +++ b/p2p/src/network/yamux/p2p_network_yamux_state.rs @@ -4,7 +4,7 @@ use serde::{Deserialize, Serialize}; use super::super::*; -#[derive(Serialize, Deserialize, Debug, Clone)] +#[derive(Serialize, Deserialize, Debug, Clone, Default)] pub struct P2pNetworkYamuxState { pub buffer: Vec, pub incoming: VecDeque, @@ -67,18 +67,6 @@ impl YamuxStreamState { } } -impl Default for P2pNetworkYamuxState { - fn default() -> Self { - P2pNetworkYamuxState { - buffer: Vec::default(), - incoming: VecDeque::default(), - streams: BTreeMap::default(), - terminated: None, - init: false, - } - } -} - bitflags::bitflags! { #[derive(Serialize, Deserialize, Debug, Clone)] pub struct YamuxFlags: u16 { @@ -121,10 +109,10 @@ pub type StreamId = u32; #[derive(Serialize, Deserialize, Debug, Clone)] pub enum YamuxFrameParseError { - UnknownVersion(u8), - UnknownFlags(u16), - UnknownType(u8), - UnknownErrorCode(u32), + Version(u8), + Flags(u16), + Type(u8), + ErrorCode(u32), } #[derive(Serialize, Deserialize, Debug, Clone)] diff --git a/p2p/src/p2p_effects.rs b/p2p/src/p2p_effects.rs index 257456d02..34b728873 100644 --- a/p2p/src/p2p_effects.rs +++ b/p2p/src/p2p_effects.rs @@ -15,7 +15,7 @@ pub fn p2p_timeout_effects(store: &mut Store, meta: &ActionMeta) where Store: P2pStore, { - p2p_connection_timeouts(store, &meta); + p2p_connection_timeouts(store, meta); store.dispatch(P2pConnectionOutgoingAction::RandomInit); p2p_try_reconnect_disconnected_peers(store); @@ -24,7 +24,7 @@ where store.dispatch(P2pDiscoveryAction::KademliaInit); #[cfg(feature = "p2p-webrtc")] - p2p_discovery_request(store, &meta); + p2p_discovery_request(store, meta); #[cfg(not(feature = "p2p-libp2p"))] store.dispatch( diff --git a/p2p/src/p2p_reducer.rs b/p2p/src/p2p_reducer.rs index adb1337bf..261b1a1a7 100644 --- a/p2p/src/p2p_reducer.rs +++ b/p2p/src/p2p_reducer.rs @@ -93,7 +93,7 @@ impl P2pState { let dial_opts = addresses.first().cloned(); if dial_opts.is_some() { self.peers.insert( - peer_id.clone(), + *peer_id, P2pPeerState { is_libp2p: true, dial_opts, diff --git a/p2p/src/p2p_state.rs b/p2p/src/p2p_state.rs index a458d2093..530ef9d2d 100644 --- a/p2p/src/p2p_state.rs +++ b/p2p/src/p2p_state.rs @@ -107,7 +107,7 @@ impl P2pState { .iter() .map(|peer| { ( - peer.peer_id().clone(), + *peer.peer_id(), P2pPeerState { dial_opts: Some(peer.clone()), is_libp2p: peer.is_libp2p(), @@ -165,11 +165,7 @@ impl P2pState { self.kademlia .known_peers .values() - .filter(|v| { - self.ready_peers_iter() - .find(|(id, _)| (*id).eq(v.peer_id())) - .is_none() - }) + .filter(|v| !self.ready_peers_iter().any(|(id, _)| (*id).eq(v.peer_id()))) .cloned() .collect() } diff --git a/p2p/src/peer/p2p_peer_effects.rs b/p2p/src/peer/p2p_peer_effects.rs index 1caf0df7c..b4f5eba9b 100644 --- a/p2p/src/peer/p2p_peer_effects.rs +++ b/p2p/src/peer/p2p_peer_effects.rs @@ -14,7 +14,6 @@ impl P2pPeerAction { { match self { P2pPeerAction::Ready { peer_id, .. } => { - let peer_id = peer_id; // Dispatches can be done without a loop, but inside we do // exhaustive matching so that we don't miss any channels. for id in ChannelId::iter_all() { diff --git a/p2p/src/service_impl/libp2p/mod.rs b/p2p/src/service_impl/libp2p/mod.rs index beb4d243e..213c8d639 100644 --- a/p2p/src/service_impl/libp2p/mod.rs +++ b/p2p/src/service_impl/libp2p/mod.rs @@ -191,7 +191,7 @@ impl Libp2pService { let mut gossipsub: Gossipsub = Gossipsub::new(message_authenticity, gossipsub_config).unwrap(); topics_iter - .map(|v| IdentTopic::new(v)) + .map(IdentTopic::new) .for_each(|topic| assert!(gossipsub.subscribe(&topic).unwrap())); let identify = identify::Behaviour::new(identify::Config::new( @@ -335,12 +335,12 @@ impl Libp2pService { async fn handle_cmd>(swarm: &mut Swarm>, cmd: Cmd) { match cmd { Cmd::Dial(peer_id, addrs) => { - let opts = DialOpts::peer_id(peer_id.into()).addresses(addrs).build(); + let opts = DialOpts::peer_id(peer_id).addresses(addrs).build(); if let Err(e) = swarm.dial(opts) { let peer_id = crate::PeerId::from(peer_id); openmina_core::log::error!( openmina_core::log::system_time(); - node_id = crate::PeerId::from(swarm.local_peer_id().clone()).to_string(), + node_id = crate::PeerId::from(*swarm.local_peer_id()).to_string(), summary = format!("Cmd::Dial(...)"), peer_id = peer_id.to_string(), error = e.to_string() @@ -658,7 +658,7 @@ impl Libp2pService { let peer_id = peer_id.as_ref().map_or("", String::as_str); openmina_core::log::info!( openmina_core::log::system_time(); - node_id = crate::PeerId::from(swarm.local_peer_id().clone()).to_string(), + node_id = crate::PeerId::from(*swarm.local_peer_id()).to_string(), kind = "libp2p::Dialing", summary = format!("peer_id: {peer_id}"), peer_id = peer_id, @@ -669,7 +669,7 @@ impl Libp2pService { let peer_id: crate::PeerId = peer_id.into(); openmina_core::log::info!( openmina_core::log::system_time(); - node_id = crate::PeerId::from(swarm.local_peer_id().clone()).to_string(), + node_id = crate::PeerId::from(*swarm.local_peer_id()).to_string(), kind = "libp2p::ConnectionEstablished", summary = format!("peer_id: {}", peer_id), peer_id = peer_id.to_string(), @@ -853,7 +853,7 @@ impl Libp2pService { .add_address(&peer_id, maddr.clone()); let mut maddr = maddr.clone(); - maddr.push(libp2p::multiaddr::Protocol::P2p(peer_id.into())); + maddr.push(libp2p::multiaddr::Protocol::P2p(peer_id)); let _ = swarm .behaviour_mut() .event_source_sender @@ -1068,8 +1068,7 @@ impl Libp2pService { Ok(response) => { let response = response .ok() - .map(|x| x.0.ok()) - .flatten() + .and_then(|x| x.0.ok()) .map(P2pRpcResponse::LedgerQuery); send(response) } diff --git a/p2p/src/service_impl/mod.rs b/p2p/src/service_impl/mod.rs index a05c747ac..e1eb174f2 100644 --- a/p2p/src/service_impl/mod.rs +++ b/p2p/src/service_impl/mod.rs @@ -4,7 +4,7 @@ pub mod libp2p; pub mod mio; #[cfg(feature = "p2p-webrtc")] pub mod webrtc; -#[cfg(all(not(target_arch = "wasm32")))] +#[cfg(not(target_arch = "wasm32"))] pub mod webrtc_with_libp2p; use std::future::Future; diff --git a/p2p/src/service_impl/webrtc/mod.rs b/p2p/src/service_impl/webrtc/mod.rs index 2f900f860..697b8190f 100644 --- a/p2p/src/service_impl/webrtc/mod.rs +++ b/p2p/src/service_impl/webrtc/mod.rs @@ -80,16 +80,18 @@ pub struct PeerState { cmd_sender: mpsc::UnboundedSender, } +// TODO: I'm not sure whether changing the acronyms breaks anything, check +#[allow(clippy::upper_case_acronyms)] #[derive(thiserror::Error, derive_more::From, Debug)] pub(super) enum Error { #[cfg(not(target_arch = "wasm32"))] #[error("{0}")] - RTCError(::webrtc::Error), + RTC(::webrtc::Error), #[cfg(target_arch = "wasm32")] #[error("js error: {0:?}")] RTCJsError(String), #[error("signaling error: {0}")] - SignalingError(RTCSignalingError), + Signaling(RTCSignalingError), #[error("unexpected cmd received")] UnexpectedCmd, #[from(ignore)] @@ -267,7 +269,7 @@ async fn peer_start(args: PeerAddArgs) { }; answer_fut.await.and_then(|v| Ok(v.try_into()?)) } else { - pc.answer_create().await.map_err(|e| Error::from(e)) + pc.answer_create().await.map_err(Error::from) }; let Ok(answer) = answer else { return; @@ -455,7 +457,7 @@ async fn peer_loop( let done_tx_clone = done_tx.clone(); let internal_cmd_sender = internal_cmd_sender_clone.clone(); chan.on_error(move |err| { - if let Err(_) = done_tx_clone.try_send(Err(err.into())) { + if done_tx_clone.try_send(Err(err.into())).is_err() { let _ = internal_cmd_sender.send(PeerCmdInternal::ChannelClosed(id)); } @@ -465,7 +467,7 @@ async fn peer_loop( let done_tx_clone = done_tx.clone(); let internal_cmd_sender = internal_cmd_sender_clone.clone(); chan.on_close(move || { - if let Err(_) = done_tx_clone.try_send(Err(Error::ChannelClosed)) { + if done_tx_clone.try_send(Err(Error::ChannelClosed)).is_err() { let _ = internal_cmd_sender.send(PeerCmdInternal::ChannelClosed(id)); } @@ -585,7 +587,7 @@ async fn peer_loop( let event_sender = event_sender.clone(); chan.on_message(move |data| { - let mut data = &*data; + let mut data = data; while !data.is_empty() { let res = match process_msg(chan_id, &mut buf, &mut len, &mut data) { Ok(None) => continue, diff --git a/p2p/src/service_impl/webrtc/native.rs b/p2p/src/service_impl/webrtc/native.rs index 7dc02e743..1cbd06db8 100644 --- a/p2p/src/service_impl/webrtc/native.rs +++ b/p2p/src/service_impl/webrtc/native.rs @@ -33,11 +33,11 @@ pub struct RTCChannel(Arc, bool); #[derive(thiserror::Error, derive_more::From, Debug)] pub enum RTCSignalingError { #[error("serialization failed: {0}")] - SerializeError(serde_json::Error), + Serialize(serde_json::Error), #[error("http request failed: {0}")] - HyperError(hyper::Error), + Hyper(hyper::Error), #[error("http request failed: {0}")] - HttpError(hyper::http::Error), + Http(hyper::http::Error), } impl RTCConnection { @@ -56,7 +56,7 @@ impl RTCConnection { pub async fn channel_create(&self, config: RTCChannelConfig) -> Result { self.0 .create_data_channel( - &config.label, + config.label, Some(RTCDataChannelInit { ordered: Some(true), max_packet_life_time: None, @@ -202,8 +202,8 @@ impl From for RTCIceServer { }; RTCIceServer { urls: value.urls, - username: value.username.unwrap_or(String::new()), - credential: value.credential.unwrap_or(String::new()), + username: value.username.unwrap_or_default(), + credential: value.credential.unwrap_or_default(), credential_type, } } diff --git a/p2p/src/webrtc/host.rs b/p2p/src/webrtc/host.rs index 2f520773f..f28bb277f 100644 --- a/p2p/src/webrtc/host.rs +++ b/p2p/src/webrtc/host.rs @@ -45,7 +45,7 @@ mod binprot_impl { impl BinProtWrite for Host { fn binprot_write(&self, w: &mut W) -> std::io::Result<()> { - Ok(match self { + match self { Self::Domain(v) => { HostKind::Domain.binprot_write(w)?; v.binprot_write(w)? @@ -62,7 +62,8 @@ mod binprot_impl { b.binprot_write(w)?; } } - }) + }; + Ok(()) } } @@ -81,16 +82,16 @@ mod binprot_impl { } HostKind::Ipv4 => { let mut octets = [0; 4]; - for i in 0..octets.len() { - octets[i] = u8::binprot_read(r)?; + for octet in &mut octets { + *octet = u8::binprot_read(r)?; } Host::Ipv4(octets.into()) } HostKind::Ipv6 => { let mut segments = [0; 8]; - for i in 0..segments.len() { - segments[i] = u16::binprot_read(r)?; + for segment in &mut segments { + *segment = u16::binprot_read(r)?; } Host::Ipv6(segments.into()) diff --git a/p2p/src/webrtc/signaling_method/http.rs b/p2p/src/webrtc/signaling_method/http.rs index d52611c31..d343191a6 100644 --- a/p2p/src/webrtc/signaling_method/http.rs +++ b/p2p/src/webrtc/signaling_method/http.rs @@ -15,7 +15,7 @@ pub struct HttpSignalingInfo { impl fmt::Display for HttpSignalingInfo { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - write!(f, "/{}/{}", self.host.to_string(), self.port) + write!(f, "/{}/{}", self.host, self.port) } } @@ -64,6 +64,6 @@ impl<'de> serde::Deserialize<'de> for HttpSignalingInfo { D: serde::Deserializer<'de>, { let s: String = Deserialize::deserialize(deserializer)?; - Ok(s.parse().map_err(|err| serde::de::Error::custom(err))?) + s.parse().map_err(serde::de::Error::custom) } } diff --git a/p2p/src/webrtc/signaling_method/mod.rs b/p2p/src/webrtc/signaling_method/mod.rs index 397e0d8e7..45f967265 100644 --- a/p2p/src/webrtc/signaling_method/mod.rs +++ b/p2p/src/webrtc/signaling_method/mod.rs @@ -95,6 +95,6 @@ impl<'de> serde::Deserialize<'de> for SignalingMethod { D: serde::Deserializer<'de>, { let s: String = Deserialize::deserialize(deserializer)?; - Ok(s.parse().map_err(|err| serde::de::Error::custom(err))?) + s.parse().map_err(serde::de::Error::custom) } } diff --git a/tools/bootstrap-sandbox/src/main.rs b/tools/bootstrap-sandbox/src/main.rs index 3654f8c3d..14af027bb 100644 --- a/tools/bootstrap-sandbox/src/main.rs +++ b/tools/bootstrap-sandbox/src/main.rs @@ -83,8 +83,7 @@ async fn main() { "{}", bs58::encode(&bytes).with_check_version(0x80).into_string() ); - let sk = SecretKey::try_from_bytes(&mut bytes).unwrap(); - sk + SecretKey::try_from_bytes(&mut bytes).unwrap() }); let local_key: libp2p::identity::Keypair = mina_transport::ed25519::Keypair::from(sk).into(); diff --git a/tools/bootstrap-sandbox/src/record.rs b/tools/bootstrap-sandbox/src/record.rs index c908df426..49b46052a 100644 --- a/tools/bootstrap-sandbox/src/record.rs +++ b/tools/bootstrap-sandbox/src/record.rs @@ -22,7 +22,7 @@ use super::{bootstrap::Storage, client::Client, snarked_ledger::SnarkedLedger}; pub async fn run(swarm: Swarm, path_main: &Path, bootstrap: bool) { let mut client = Client::new(swarm); - fs::create_dir_all(&path_main).unwrap(); + fs::create_dir_all(path_main).unwrap(); let best_tip = client.rpc::(()).await.unwrap().unwrap(); diff --git a/tools/ledger-tool/src/main.rs b/tools/ledger-tool/src/main.rs index c20a363a0..b34bf60a6 100644 --- a/tools/ledger-tool/src/main.rs +++ b/tools/ledger-tool/src/main.rs @@ -75,13 +75,13 @@ fn parse_account(mut a: serde_json::Value) -> anyhow::Result { } = serde_json::from_value(timing.clone())?; if !initial_minimum_balance.contains('.') { - initial_minimum_balance.extend(".000000000".chars()); + initial_minimum_balance.push_str(".000000000"); } if !cliff_amount.contains('.') { - cliff_amount.extend(".000000000".chars()); + cliff_amount.push_str(".000000000"); } if !vesting_increment.contains('.') { - vesting_increment.extend(".000000000".chars()); + vesting_increment.push_str(".000000000"); } account.timing = Timing::Timed { @@ -105,7 +105,7 @@ fn main() -> anyhow::Result<()> { let Args { input, url, output } = Args::from_args(); let value = if let Some(input) = input { - let ledger_file = File::open(&input)?; + let ledger_file = File::open(input)?; serde_json::from_reader::<_, serde_json::Value>(ledger_file)? } else if let Some(url) = url { reqwest::blocking::get(url)?.json()? @@ -157,7 +157,7 @@ fn main() -> anyhow::Result<()> { let top_hash = v2::LedgerHash::from(v2::MinaBaseLedgerHash0StableV1(root.into())); println!("{top_hash}"); - let mut output = File::create(&output)?; + let mut output = File::create(output)?; Some(top_hash).binprot_write(&mut output)?; accounts.binprot_write(&mut output)?; diff --git a/tools/salsa-simple/src/lib.rs b/tools/salsa-simple/src/lib.rs index 96fdd665b..09cfa98ba 100644 --- a/tools/salsa-simple/src/lib.rs +++ b/tools/salsa-simple/src/lib.rs @@ -168,7 +168,7 @@ impl XSalsaCore { for mut block in blocks { let mut t = [0; 64]; self.gen_ks_block(&mut t); - block.xor_in2out(&GenericArray::from_slice(&t)); + block.xor_in2out(GenericArray::from_slice(&t)); } } } @@ -327,7 +327,7 @@ mod helpers { return serializer.serialize_str(&hex::encode(v)); } - serializer.serialize_bytes(&*v) + serializer.serialize_bytes(v) } pub fn de_bytes<'de, const N: usize, D>(deserializer: D) -> Result<[u8; N], D::Error> diff --git a/tools/transport/src/lib.rs b/tools/transport/src/lib.rs index 7d84088f8..437368a6c 100644 --- a/tools/transport/src/lib.rs +++ b/tools/transport/src/lib.rs @@ -161,7 +161,7 @@ where tcp::tokio::Transport::new(tcp::Config::default().nodelay(true)) .and_then(move |socket, _| pnet.handshake(socket)) .upgrade(upgrade::Version::V1) - .authenticate(noise::Config::new(&local_key).expect("libp2p-noise static keypair")) + .authenticate(noise::Config::new(local_key).expect("libp2p-noise static keypair")) .multiplex(yamux) .timeout(std::time::Duration::from_secs(20)) .boxed()