From 900a31c6c486d02eb7d16ca8a3059e3bdef0b25d Mon Sep 17 00:00:00 2001 From: yukang Date: Mon, 27 Jan 2025 11:41:08 +0800 Subject: [PATCH 1/4] make bless to auto fix clippy --- migrate/Cargo.lock | 4 +- src/cch/actor.rs | 2 +- src/ckb/contracts.rs | 2 +- src/ckb/funding/funding_tx.rs | 10 +- src/ckb/tests/test_utils.rs | 11 +- src/fiber/channel.rs | 109 +++++------- src/fiber/config.rs | 5 +- src/fiber/gossip.rs | 47 +++-- src/fiber/graph.rs | 26 ++- src/fiber/history.rs | 22 +-- src/fiber/key.rs | 6 +- src/fiber/network.rs | 17 +- src/fiber/tests/channel.rs | 274 +++++++++++++++--------------- src/fiber/tests/gossip.rs | 75 ++++---- src/fiber/tests/graph.rs | 4 +- src/fiber/tests/history.rs | 71 ++++---- src/fiber/tests/network.rs | 8 +- src/fiber/tests/payment.rs | 54 +++--- src/fiber/tests/test_utils.rs | 36 ++-- src/fiber/tests/tlc_op.rs | 12 +- src/fiber/tests/types.rs | 16 +- src/fiber/types.rs | 28 +-- src/invoice/tests/invoice_impl.rs | 6 +- src/rpc/channel.rs | 1 - src/rpc/dev.rs | 4 +- src/rpc/invoice.rs | 6 +- src/rpc/payment.rs | 8 +- src/store/migration.rs | 6 + src/store/store.rs | 15 +- src/store/tests/store.rs | 10 +- 30 files changed, 438 insertions(+), 457 deletions(-) diff --git a/migrate/Cargo.lock b/migrate/Cargo.lock index 947707804..879e5354e 100644 --- a/migrate/Cargo.lock +++ b/migrate/Cargo.lock @@ -1710,7 +1710,7 @@ dependencies = [ [[package]] name = "fnn" -version = "0.3.0" +version = "0.3.1" dependencies = [ "anyhow", "arcode", @@ -1772,7 +1772,7 @@ dependencies = [ "fnn 0.2.0", "fnn 0.2.1 (git+https://github.com/nervosnetwork/fiber.git?tag=v0.2.1)", "fnn 0.2.1 (git+https://github.com/nervosnetwork/fiber.git?tag=v0.3.0-rc1)", - "fnn 0.3.0", + "fnn 0.3.1", "hex", "indicatif", "serde", diff --git a/src/cch/actor.rs b/src/cch/actor.rs index d42ba4740..59b38fe41 100644 --- a/src/cch/actor.rs +++ b/src/cch/actor.rs @@ -594,7 +594,7 @@ impl CchActor { + self.config.ckb_final_tlc_expiry_delta, hash_algorithm: HashAlgorithm::Sha256, onion_packet: None, - shared_secret: NO_SHARED_SECRET.clone(), + shared_secret: NO_SHARED_SECRET, previous_tlc: None, }, rpc_reply, diff --git a/src/ckb/contracts.rs b/src/ckb/contracts.rs index 965a69c24..38cf48a05 100644 --- a/src/ckb/contracts.rs +++ b/src/ckb/contracts.rs @@ -209,7 +209,7 @@ impl ContractsContext { pub(crate) fn get_udt_info(&self, udt_script: &Script) -> Option<&UdtArgInfo> { for udt in &self.get_udt_whitelist().0 { - if let Some(_type) = udt_script.hash_type().try_into().ok() { + if let Ok(_type) = udt_script.hash_type().try_into() { if udt.script.code_hash.pack() == udt_script.code_hash() && udt.script.hash_type == _type { diff --git a/src/ckb/funding/funding_tx.rs b/src/ckb/funding/funding_tx.rs index 6e51437ad..586b5296b 100644 --- a/src/ckb/funding/funding_tx.rs +++ b/src/ckb/funding/funding_tx.rs @@ -155,13 +155,13 @@ impl FundingTxBuilder { match self.request.udt_type_script { Some(ref udt_type_script) => { - let mut udt_amount = self.request.local_amount as u128; + let mut udt_amount = self.request.local_amount; let mut ckb_amount = self.request.local_reserved_ckb_amount; // To make tx building easier, do not include the amount not funded yet in the // funding cell. if remote_funded { - udt_amount += self.request.remote_amount as u128; + udt_amount += self.request.remote_amount; ckb_amount = ckb_amount .checked_add(self.request.remote_reserved_ckb_amount) .ok_or(FundingError::InvalidChannel)?; @@ -190,7 +190,7 @@ impl FundingTxBuilder { .ok_or(FundingError::InvalidChannel)?; } let ckb_output = packed::CellOutput::new_builder() - .capacity(Capacity::shannons(ckb_amount as u64).pack()) + .capacity(Capacity::shannons(ckb_amount).pack()) .lock(self.context.funding_cell_lock_script.clone()) .build(); Ok((ckb_output, packed::Bytes::default())) @@ -206,7 +206,7 @@ impl FundingTxBuilder { outputs_data: &mut Vec, cell_deps: &mut HashSet, ) -> Result<(), TxBuilderError> { - let udt_amount = self.request.local_amount as u128; + let udt_amount = self.request.local_amount; // return early if we don't need to build UDT cell if self.request.udt_type_script.is_none() || udt_amount == 0 { return Ok(()); @@ -306,7 +306,7 @@ impl FundingTxBuilder { let ckb_client = CkbRpcClient::new(&self.context.rpc_url); let cell_dep_resolver = ckb_client .get_block_by_number(0.into()) - .map_err(|err| FundingError::CkbRpcError(err))? + .map_err(FundingError::CkbRpcError)? .and_then(|genesis_block| { DefaultCellDepResolver::from_genesis(&BlockView::from(genesis_block)).ok() }) diff --git a/src/ckb/tests/test_utils.rs b/src/ckb/tests/test_utils.rs index f47a8166c..214dba802 100644 --- a/src/ckb/tests/test_utils.rs +++ b/src/ckb/tests/test_utils.rs @@ -53,6 +53,12 @@ pub struct MockContext { pub contracts_context: ContractsContext, } +impl Default for MockContext { + fn default() -> Self { + Self::new() + } +} + impl MockContext { pub fn new() -> Self { let binaries = [ @@ -108,8 +114,7 @@ impl MockContext { script_cell_deps .get(&Contract::CkbAuth) .unwrap() - .clone() - .get(0) + .clone().first() .unwrap() .clone(), ] @@ -167,7 +172,7 @@ impl Actor for TraceTxReplier { myself: ActorRef, (notifier, timeout, reply_port): Self::Arguments, ) -> Result { - let _ = myself.send_after(timeout, || TraceTxResult::Timeout()); + let _ = myself.send_after(timeout, TraceTxResult::Timeout); let hash = self.tx_hash.clone(); notifier.subscribe(myself, move |notification| { if notification.0 == hash { diff --git a/src/fiber/channel.rs b/src/fiber/channel.rs index 641f2cda1..3c6b61521 100644 --- a/src/fiber/channel.rs +++ b/src/fiber/channel.rs @@ -904,7 +904,7 @@ where .await .map_err(ProcessingChannelError::without_shared_secret)? { - let shared_secret = peeled_onion_packet.shared_secret.clone(); + let shared_secret = peeled_onion_packet.shared_secret; self.apply_add_tlc_operation_with_peeled_onion_packet( myself, state, @@ -942,15 +942,13 @@ where ) -> Result, ProcessingChannelError> { state.check_tlc_expiry(add_tlc.expiry)?; - assert!(state.get_received_tlc(add_tlc.tlc_id.into()).is_some()); + assert!(state.get_received_tlc(add_tlc.tlc_id).is_some()); - Ok( - OptionFuture::from(add_tlc.onion_packet.clone().map(|onion_packet| { - self.peel_onion_packet(onion_packet, add_tlc.payment_hash.clone()) + OptionFuture::from(add_tlc.onion_packet.clone().map(|onion_packet| { + self.peel_onion_packet(onion_packet, add_tlc.payment_hash) })) .await - .transpose()?, - ) + .transpose() } async fn apply_add_tlc_operation_with_peeled_onion_packet( @@ -1545,7 +1543,7 @@ where channel_id: *channel_id, command: ChannelCommand::RemoveTlc( RemoveTlcCommand { - id: u64::from(*tlc_id), + id: (*tlc_id), reason: reason.clone(), }, port, @@ -1638,7 +1636,7 @@ where } _ => { let error = ProcessingChannelError::TlcForwardingError(tlc_err) - .with_shared_secret(peeled_onion.shared_secret.clone()); + .with_shared_secret(peeled_onion.shared_secret); self.process_add_tlc_error( myself, state, @@ -1774,7 +1772,7 @@ where ChannelCommand::AddTlc(command, reply) => { let res = self.handle_add_tlc_command(state, command.clone()); let error_info = if let Err(ref err) = res { - Some((err.clone(), self.get_tlc_error(state, &err).await)) + Some((err.clone(), self.get_tlc_error(state, err).await)) } else { None }; @@ -1950,7 +1948,7 @@ where fn get_invoice_status(&self, invoice: &CkbInvoice) -> CkbInvoiceStatus { match self .store - .get_invoice_status(&invoice.payment_hash()) + .get_invoice_status(invoice.payment_hash()) .expect("no invoice status found") { CkbInvoiceStatus::Open if invoice.is_expired() => CkbInvoiceStatus::Expired, @@ -1967,7 +1965,7 @@ where NetworkActorCommand::PeelPaymentOnionPacket(onion_packet, payment_hash, tx) )) .expect(ASSUME_NETWORK_ACTOR_ALIVE) - .map_err(|err| ProcessingChannelError::PeelingOnionPacketError(err)) + .map_err(ProcessingChannelError::PeelingOnionPacketError) } } @@ -2808,14 +2806,11 @@ impl TlcState { // if we already finished the RemoveTlc operation for the tlc, // we should also remove the ForwardTlc to avoid any later retry. - match retryable_tlc_op { - RetryableTlcOperation::RemoveTlc(tlc_id, _) => { - self.retryable_tlc_operations.retain(|op| match op { - RetryableTlcOperation::ForwardTlc(_, id, ..) => id != tlc_id, - _ => true, - }); - } - _ => {} + if let RetryableTlcOperation::RemoveTlc(tlc_id, _) = retryable_tlc_op { + self.retryable_tlc_operations.retain(|op| match op { + RetryableTlcOperation::ForwardTlc(_, id, ..) => id != tlc_id, + _ => true, + }); } } @@ -2872,29 +2867,23 @@ impl TlcState { pub fn update_for_commitment_signed(&mut self) -> bool { for tlc in self.offered_tlcs.tlcs.iter_mut() { - match tlc.outbound_status() { - OutboundTlcStatus::RemoteRemoved => { - let status = if self.waiting_ack { - OutboundTlcStatus::RemoveWaitPrevAck - } else { - OutboundTlcStatus::RemoveWaitAck - }; - tlc.status = TlcStatus::Outbound(status); - } - _ => {} + if tlc.outbound_status() == OutboundTlcStatus::RemoteRemoved { + let status = if self.waiting_ack { + OutboundTlcStatus::RemoveWaitPrevAck + } else { + OutboundTlcStatus::RemoveWaitAck + }; + tlc.status = TlcStatus::Outbound(status); } } for tlc in self.received_tlcs.tlcs.iter_mut() { - match tlc.inbound_status() { - InboundTlcStatus::RemoteAnnounced => { - let status = if self.waiting_ack { - InboundTlcStatus::AnnounceWaitPrevAck - } else { - InboundTlcStatus::AnnounceWaitAck - }; - tlc.status = TlcStatus::Inbound(status) - } - _ => {} + if tlc.inbound_status() == InboundTlcStatus::RemoteAnnounced { + let status = if self.waiting_ack { + InboundTlcStatus::AnnounceWaitPrevAck + } else { + InboundTlcStatus::AnnounceWaitAck + }; + tlc.status = TlcStatus::Inbound(status) } } self.need_another_commitment_signed() @@ -3311,7 +3300,7 @@ impl ProcessingChannelError { } pub fn without_shared_secret(self) -> ProcessingChannelErrorWithSharedSecret { - self.with_shared_secret(NO_SHARED_SECRET.clone()) + self.with_shared_secret(NO_SHARED_SECRET) } } @@ -3568,15 +3557,15 @@ impl ChannelActorState { } else { (self.remote_pubkey, self.local_pubkey) }; - let channel_announcement = ChannelAnnouncement::new_unsigned( + + ChannelAnnouncement::new_unsigned( &node1_id, &node2_id, channel_outpoint, &self.get_funding_lock_script_xonly_key(), capacity, self.funding_udt_type_script.clone(), - ); - channel_announcement + ) } }; @@ -3779,14 +3768,10 @@ impl ChannelActorState { return None; } - match self + if let Some(x) = self .public_channel_info .as_ref() - .and_then(|state| state.channel_update.clone()) - { - Some(x) => return Some(x), - _ => {} - }; + .and_then(|state| state.channel_update.clone()) { return Some(x) }; Some(self.generate_channel_update(network).await) } @@ -3875,7 +3860,7 @@ impl ChannelActorState { funding_fee_rate, id: channel_id, tlc_state: Default::default(), - local_shutdown_script: local_shutdown_script, + local_shutdown_script, local_channel_public_keys: local_base_pubkeys, signer, remote_channel_public_keys: Some(remote_pubkeys), @@ -4301,12 +4286,12 @@ impl ChannelActorState { // Get the total liquid capacity of the channel, which will exclude the reserved ckb amount. // This is the capacity used for gossiping channel information. pub(crate) fn get_liquid_capacity(&self) -> u128 { - let capacity = if self.funding_udt_type_script.is_some() { + + if self.funding_udt_type_script.is_some() { self.get_total_udt_amount() } else { - self.to_local_amount as u128 + self.to_remote_amount as u128 - }; - capacity + self.to_local_amount + self.to_remote_amount + } } // Send RevokeAndAck message to the counterparty, and update the @@ -4694,7 +4679,7 @@ impl ChannelActorState { .iter() .find_map(|(number, point)| { if *number == commitment_number { - Some(point.clone()) + Some(*point) } else { None } @@ -4778,16 +4763,14 @@ impl ChannelActorState { fn get_active_received_tlcs(&self, for_remote: bool) -> Vec { self.tlc_state .commitment_signed_tlcs(for_remote) - .filter(|tlc| tlc.is_received()) - .map(|tlc| tlc.clone()) + .filter(|tlc| tlc.is_received()).cloned() .collect() } fn get_active_offered_tlcs(&self, for_remote: bool) -> Vec { self.tlc_state .commitment_signed_tlcs(for_remote) - .filter(|tlc| tlc.is_offered()) - .map(|tlc| tlc.clone()) + .filter(|tlc| tlc.is_offered()).cloned() .collect() } @@ -5151,7 +5134,7 @@ impl ChannelActorState { // will be set when apply AddTlc operations after the signature is checked onion_packet: message.onion_packet, // No need to save shared secret for inbound TLC. - shared_secret: NO_SHARED_SECRET.clone(), + shared_secret: NO_SHARED_SECRET, created_at: self.get_current_commitment_numbers(), removed_reason: None, previous_tlc: None, @@ -6336,7 +6319,7 @@ impl ChannelActorState { let common_ctx = self.get_deterministic_common_context(); Musig2VerifyContext { common_ctx, - pubkey: self.get_remote_funding_pubkey().clone(), + pubkey: *self.get_remote_funding_pubkey(), pubnonce: self.get_last_committed_remote_nonce(), } } @@ -6348,7 +6331,7 @@ impl ChannelActorState { Musig2VerifyContext { common_ctx, - pubkey: self.get_remote_funding_pubkey().clone(), + pubkey: *self.get_remote_funding_pubkey(), pubnonce: self.get_last_committed_remote_nonce(), } } diff --git a/src/fiber/config.rs b/src/fiber/config.rs index 10d74ada5..f93118b8f 100644 --- a/src/fiber/config.rs +++ b/src/fiber/config.rs @@ -11,7 +11,7 @@ use std::{fs, path::PathBuf, str::FromStr}; use tentacle::secio::{PublicKey, SecioKeyPair}; pub const CKB_SHANNONS: u64 = 100_000_000; // 1 CKB = 10 ^ 8 shannons -pub const DEFAULT_MIN_SHUTDOWN_FEE: u64 = 1 * CKB_SHANNONS; // 1 CKB prepared for shutdown transaction fee +pub const DEFAULT_MIN_SHUTDOWN_FEE: u64 = CKB_SHANNONS; // 1 CKB prepared for shutdown transaction fee /// By default, listen to any tcp port allocated by the kernel. pub const DEFAULT_LISTENING_ADDR: &str = "/ip4/0.0.0.0/tcp/0"; @@ -382,8 +382,7 @@ impl FiberConfig { #[cfg(not(test))] pub fn read_or_generate_secret_key(&self) -> Result { FIBER_SECRET_KEY - .get_or_try_init(|| self.inner_read_or_generate_secret_key()) - .map(|key| key.clone()) + .get_or_try_init(|| self.inner_read_or_generate_secret_key()).cloned() } pub fn store_path(&self) -> PathBuf { diff --git a/src/fiber/gossip.rs b/src/fiber/gossip.rs index 0fa92d688..171cab884 100644 --- a/src/fiber/gossip.rs +++ b/src/fiber/gossip.rs @@ -81,7 +81,7 @@ pub trait GossipMessageStore { ) -> Vec { self.get_broadcast_messages_iter(after_cursor) .into_iter() - .take(count.unwrap_or(DEFAULT_NUM_OF_BROADCAST_MESSAGE as u16) as usize) + .take(count.unwrap_or(DEFAULT_NUM_OF_BROADCAST_MESSAGE) as usize) .collect() } @@ -116,10 +116,10 @@ pub trait GossipMessageStore { }), BroadcastMessageQueryFlags::ChannelUpdateOfNode1 => self .get_latest_channel_update(&query.channel_outpoint, true) - .map(|channel_update| BroadcastMessageWithTimestamp::ChannelUpdate(channel_update)), + .map(BroadcastMessageWithTimestamp::ChannelUpdate), BroadcastMessageQueryFlags::ChannelUpdateOfNode2 => self .get_latest_channel_update(&query.channel_outpoint, false) - .map(|channel_update| BroadcastMessageWithTimestamp::ChannelUpdate(channel_update)), + .map(BroadcastMessageWithTimestamp::ChannelUpdate), BroadcastMessageQueryFlags::NodeAnnouncementNode1 | BroadcastMessageQueryFlags::NodeAnnouncementNode2 => self @@ -131,7 +131,7 @@ pub trait GossipMessageStore { &channel_announcement.node2_id }; self.get_latest_node_announcement(node) - .map(|m| BroadcastMessageWithTimestamp::NodeAnnouncement(m)) + .map(BroadcastMessageWithTimestamp::NodeAnnouncement) }), } } @@ -162,11 +162,11 @@ pub trait GossipMessageStore { self.get_broadcast_message_with_cursor(&Cursor::new( timestamp, BroadcastMessageID::ChannelAnnouncement(outpoint.clone()), - )).and_then(|message| match message { + )).map(|message| match message { BroadcastMessageWithTimestamp::ChannelAnnouncement( _, channel_announcement, - ) => Some((timestamp, channel_announcement)), + ) => (timestamp, channel_announcement), _ => panic!( "get_latest_channel_announcement returned non-ChannelAnnouncement message from db: channel outpoint {:?}, message {:?}", outpoint, message ), @@ -184,8 +184,8 @@ pub trait GossipMessageStore { self.get_broadcast_message_with_cursor(&Cursor::new( timestamp, BroadcastMessageID::ChannelUpdate(outpoint.clone()), - )).and_then(|message| match message { - BroadcastMessageWithTimestamp::ChannelUpdate(channel_update) => Some(channel_update), + )).map(|message| match message { + BroadcastMessageWithTimestamp::ChannelUpdate(channel_update) => channel_update, _ => panic!("get_latest_channel_update returned non-ChannelUpdate message from db: channel outpoint {:?}, is_node1 {:?}, message {:?}", outpoint, is_node1, message), }) }) @@ -195,10 +195,10 @@ pub trait GossipMessageStore { self.get_latest_node_announcement_timestamp(pk).and_then(|timestamp| { self.get_broadcast_message_with_cursor(&Cursor::new( timestamp, - BroadcastMessageID::NodeAnnouncement(pk.clone()), - )).and_then(|message| + BroadcastMessageID::NodeAnnouncement(*pk), + )).map(|message| match message { - BroadcastMessageWithTimestamp::NodeAnnouncement(node_announcement) => Some(node_announcement), + BroadcastMessageWithTimestamp::NodeAnnouncement(node_announcement) => node_announcement, _ => panic!("get_lastest_node_announcement returned non-NodeAnnouncement message from db: pk {:?}, message {:?}", pk, message), } ) @@ -782,11 +782,8 @@ impl Drop for PeerState { .actor .stop(Some("peer state dropped".to_string())); } - match &self.sync_status { - PeerSyncStatus::ActiveGet(actor) => { - actor.stop(Some("peer state dropped".to_string())); - } - _ => {} + if let PeerSyncStatus::ActiveGet(actor) = &self.sync_status { + actor.stop(Some("peer state dropped".to_string())); } } } @@ -1100,7 +1097,7 @@ impl ExtendedGossipMessageStoreState { } } - if self.messages_to_be_saved.contains(&message) { + if self.messages_to_be_saved.contains(message) { return Ok(()); } @@ -1600,7 +1597,7 @@ where let queries = get_dependent_message_queries(&message, self.get_store()); self.pending_queries.extend(queries); - let _ = self + self .store .actor .send_message(ExtendedGossipMessageStoreMessage::SaveMessages(vec![ @@ -1719,7 +1716,7 @@ async fn get_message_cursor( )), BroadcastMessage::NodeAnnouncement(node_announcement) => Ok(Cursor::new( node_announcement.timestamp, - BroadcastMessageID::NodeAnnouncement(node_announcement.node_id.clone()), + BroadcastMessageID::NodeAnnouncement(node_announcement.node_id), )), } } @@ -1835,7 +1832,7 @@ async fn get_channel_timestamp( store: &S, chain: &ActorRef, ) -> Result { - if let Some((timestamp, _)) = store.get_latest_channel_announcement(&outpoint) { + if let Some((timestamp, _)) = store.get_latest_channel_announcement(outpoint) { return Ok(timestamp); } @@ -2312,10 +2309,10 @@ where ¤t_peers, &new_peers ); for peers in new_peers.difference(¤t_peers) { - state.start_passive_syncer(&peers).await; + state.start_passive_syncer(peers).await; } for peers in current_peers.difference(&new_peers) { - state.stop_passive_syncer(&peers).await; + state.stop_passive_syncer(peers).await; } } @@ -2466,7 +2463,7 @@ where let id = get_broadcast_messages.id; let messages = state.get_store().get_broadcast_messages( &get_broadcast_messages.after_cursor, - Some(get_broadcast_messages.count as u16), + Some(get_broadcast_messages.count), ); let result = GossipMessage::GetBroadcastMessagesResult(GetBroadcastMessagesResult { @@ -2518,7 +2515,7 @@ where QueryBroadcastMessagesResult { id, messages: results.into_iter().map(|m| m.into()).collect(), - missing_queries: missing_queries, + missing_queries, }, ); if let Err(error) = state.send_message_to_peer(&peer_id, result).await { @@ -2597,7 +2594,7 @@ impl ServiceProtocol for GossipProtocolHandle { match context.session.remote_pubkey.as_ref() { Some(remote_pubkey) => { - let remote_peer_id = PeerId::from_public_key(&remote_pubkey); + let remote_peer_id = PeerId::from_public_key(remote_pubkey); let _ = self .actor .send_message(GossipActorMessage::PeerDisconnected( diff --git a/src/fiber/graph.rs b/src/fiber/graph.rs index b9a8dc2b5..42da0d352 100644 --- a/src/fiber/graph.rs +++ b/src/fiber/graph.rs @@ -538,11 +538,11 @@ where // associated with the node as failed. Here we tell the history about // the mapping between nodes and channels. self.history.add_node_channel_map( - channel_info.node1.clone(), + channel_info.node1, channel_info.out_point().clone(), ); self.history.add_node_channel_map( - channel_info.node2.clone(), + channel_info.node2, channel_info.out_point().clone(), ); self.channels @@ -791,10 +791,8 @@ where if let Some(info) = channel.update_of_node2.as_mut() { info.enabled = false; } - } else { - if let Some(info) = channel.update_of_node1.as_mut() { - info.enabled = false; - } + } else if let Some(info) = channel.update_of_node1.as_mut() { + info.enabled = false; } } } @@ -887,16 +885,16 @@ where hops_data.push(PaymentHopData { amount: r.amount_received, next_hop: Some(r.target), - hash_algorithm: hash_algorithm, + hash_algorithm, expiry: now + r.incoming_tlc_expiry, funding_tx_hash: r.channel_outpoint.tx_hash().into(), payment_preimage: None, }); } hops_data.push(PaymentHopData { - amount: amount, + amount, next_hop: None, - hash_algorithm: hash_algorithm, + hash_algorithm, expiry: now + final_tlc_expiry_delta, funding_tx_hash: Default::default(), payment_preimage: preimage, @@ -975,8 +973,8 @@ where )?; assert_ne!(target, t); target = t; - expiry = expiry + e; - amount = amount + f; + expiry += e; + amount += f; last_edge = Some(edge); } assert_ne!(source, target); @@ -1093,7 +1091,7 @@ where * self.history.eval_probability( from, to, - &channel_info.out_point(), + channel_info.out_point(), amount_to_send, channel_info.capacity(), ); @@ -1200,7 +1198,7 @@ where } if let Some(state) = self .store - .get_channel_state_by_outpoint(&channel_info.out_point()) + .get_channel_state_by_outpoint(channel_info.out_point()) { let balance = state.to_remote_amount; return balance >= amount; @@ -1314,7 +1312,7 @@ impl SessionRoute { .chain( payment_hops .iter() - .map(|hop| hop.next_hop.clone().unwrap_or(target)), + .map(|hop| hop.next_hop.unwrap_or(target)), ) .zip(payment_hops) .map(|(pubkey, hop)| SessionRouteNode { diff --git a/src/fiber/history.rs b/src/fiber/history.rs index bc11c9aa4..3f3ec3313 100644 --- a/src/fiber/history.rs +++ b/src/fiber/history.rs @@ -491,21 +491,21 @@ where return 1.0; } let ret = self.get_channel_probability(capacity, success_amount, fail_amount, amount); - assert!(ret >= 0.0 && ret <= 1.0); + assert!((0.0..=1.0).contains(&ret)); ret } // The factor approaches 0 for success_time a long time in the past, // is 1 when the success_time is now. fn time_factor(&self, time: u64) -> f64 { - let time_ago = (now_timestamp_as_millis_u64() - time).max(0); + let time_ago = now_timestamp_as_millis_u64() - time; // if time_ago is less than 1 second, we treat it as 0, this makes the factor 1 // this is to avoid the factor is too small when the time is very close to now, // this will make the probability calculation more stable let time_ago = if time_ago < 1000 { 0 } else { time_ago }; let exponent = -(time_ago as f64) / (DEFAULT_BIMODAL_DECAY_TIME as f64); - let factor = exponent.exp(); - factor + + exponent.exp() } pub(crate) fn cannot_send(&self, fail_amount: u128, time: u64, capacity: u128) -> u128 { @@ -517,14 +517,14 @@ where let factor = self.time_factor(time); - let cannot_send = capacity - (factor * (capacity - fail_amount) as f64) as u128; - cannot_send + + capacity - (factor * (capacity - fail_amount) as f64) as u128 } pub(crate) fn can_send(&self, amount: u128, time: u64) -> u128 { let factor = self.time_factor(time); - let can_send = (amount as f64 * factor) as u128; - can_send + + (amount as f64 * factor) as u128 } // Get the probability of a payment success through a direct channel, @@ -538,7 +538,7 @@ where let mut prob = 1.0; if let Some(result) = self.get_result(channel, direction) { if result.fail_time != 0 { - let time_ago = (now_timestamp_as_millis_u64() - result.fail_time).max(0); + let time_ago = now_timestamp_as_millis_u64() - result.fail_time; let exponent = -(time_ago as f64) / (DEFAULT_BIMODAL_DECAY_TIME as f64); prob -= exponent.exp(); } @@ -600,7 +600,7 @@ where // f128 is only on nightly, so we use f64 here, we may lose some precision // but it's acceptable since all the values are cast to f64 let mut prob = - self.integral_probability(capacity as f64, amount as f64, fail_amount as f64); + self.integral_probability(capacity as f64, amount, fail_amount); if prob.is_nan() { error!( "probability is NaN: capacity: {} amount: {} fail_amount: {}", @@ -609,7 +609,7 @@ where return 0.0; } let re_norm = - self.integral_probability(capacity as f64, success_amount as f64, fail_amount as f64); + self.integral_probability(capacity as f64, success_amount, fail_amount); if re_norm == 0.0 { return 0.0; } diff --git a/src/fiber/key.rs b/src/fiber/key.rs index 371bb6b6d..77e88f15d 100644 --- a/src/fiber/key.rs +++ b/src/fiber/key.rs @@ -97,9 +97,9 @@ impl TryFrom<&[u8]> for KeyPair { } } -impl Into for KeyPair { - fn into(self) -> Privkey { - Privkey::from(self.0) +impl From for Privkey { + fn from(val: KeyPair) -> Self { + Privkey::from(val.0) } } diff --git a/src/fiber/network.rs b/src/fiber/network.rs index 8877d0cca..8c09021de 100644 --- a/src/fiber/network.rs +++ b/src/fiber/network.rs @@ -412,8 +412,7 @@ impl SendPaymentData { .and_then(|i| i.final_tlc_minimum_expiry_delta().copied()) }) .unwrap_or(DEFAULT_TLC_EXPIRY_DELTA); - if final_tlc_expiry_delta < MIN_TLC_EXPIRY_DELTA - || final_tlc_expiry_delta > MAX_PAYMENT_TLC_EXPIRY_LIMIT + if !(MIN_TLC_EXPIRY_DELTA..=MAX_PAYMENT_TLC_EXPIRY_LIMIT).contains(&final_tlc_expiry_delta) { return Err(format!( "invalid final_tlc_expiry_delta, expect between {} and {}", @@ -1385,8 +1384,8 @@ where } NetworkActorCommand::NodeInfo(_, rpc) => { let response = NodeInfoResponse { - node_name: state.node_name.clone(), - node_id: state.get_public_key().clone(), + node_name: state.node_name, + node_id: state.get_public_key(), addresses: state.announced_addrs.clone(), chain_hash: get_chain_hash(), open_channel_auto_accept_min_ckb_funding_amount: state @@ -1448,7 +1447,7 @@ where expiry: info.expiry, hash_algorithm: info.hash_algorithm, onion_packet: peeled_onion_packet.next.clone(), - shared_secret: shared_secret.clone(), + shared_secret, previous_tlc, }, rpc_reply, @@ -1670,7 +1669,7 @@ where .network_graph .write() .await - .record_payment_fail(&payment_session, error_detail.clone()); + .record_payment_fail(payment_session, error_detail.clone()); let err = format!( "Failed to send onion packet with error {}", error_detail.error_code_as_str() @@ -1958,7 +1957,7 @@ impl PersistentNetworkActorState { } fn get_peer_pubkey(&self, peer_id: &PeerId) -> Option { - self.peer_pubkey_map.get(peer_id).map(|x| *x) + self.peer_pubkey_map.get(peer_id).copied() } // Save a single peer pubkey to the peer store. Returns true if the new pubkey is different from the old one, @@ -3056,8 +3055,8 @@ where let fiber_handle = FiberProtocolHandle::from(&handle); let (gossip_handle, store_update_subscriber) = GossipProtocolHandle::new( Some(format!("gossip actor {:?}", my_peer_id)), - Duration::from_millis(config.gossip_network_maintenance_interval_ms()).into(), - Duration::from_millis(config.gossip_store_maintenance_interval_ms()).into(), + Duration::from_millis(config.gossip_network_maintenance_interval_ms()), + Duration::from_millis(config.gossip_store_maintenance_interval_ms()), config.announce_private_addr(), config.gossip_network_num_targeted_active_syncing_peers, config.gossip_network_num_targeted_outbound_passive_syncing_peers, diff --git a/src/fiber/tests/channel.rs b/src/fiber/tests/channel.rs index f22ca4ef7..ec4f70b15 100644 --- a/src/fiber/tests/channel.rs +++ b/src/fiber/tests/channel.rs @@ -729,7 +729,7 @@ async fn test_network_send_payment_normal_keysend_workflow() { // Wait for the channel announcement to be broadcasted tokio::time::sleep(tokio::time::Duration::from_millis(1000)).await; - let node_b_pubkey = node_b.pubkey.clone(); + let node_b_pubkey = node_b.pubkey; let message = |rpc_reply| -> NetworkActorMessage { NetworkActorMessage::Command(NetworkActorCommand::SendPayment( SendPaymentCommand { @@ -835,8 +835,8 @@ async fn test_network_send_payment_send_each_other() { let node_a_old_balance = node_a.get_local_balance_from_channel(new_channel_id); let node_b_old_balance = node_b.get_local_balance_from_channel(new_channel_id); - let node_a_pubkey = node_a.pubkey.clone(); - let node_b_pubkey = node_b.pubkey.clone(); + let node_a_pubkey = node_a.pubkey; + let node_b_pubkey = node_b.pubkey; let message = |rpc_reply| -> NetworkActorMessage { NetworkActorMessage::Command(NetworkActorCommand::SendPayment( SendPaymentCommand { @@ -950,8 +950,8 @@ async fn test_network_send_payment_more_send_each_other() { let node_a_old_balance = node_a.get_local_balance_from_channel(new_channel_id); let node_b_old_balance = node_b.get_local_balance_from_channel(new_channel_id); - let node_a_pubkey = node_a.pubkey.clone(); - let node_b_pubkey = node_b.pubkey.clone(); + let node_a_pubkey = node_a.pubkey; + let node_b_pubkey = node_b.pubkey; let message = |rpc_reply| -> NetworkActorMessage { NetworkActorMessage::Command(NetworkActorCommand::SendPayment( SendPaymentCommand { @@ -1094,7 +1094,7 @@ async fn test_network_send_payment_send_with_ack() { // Wait for the channel announcement to be broadcasted tokio::time::sleep(tokio::time::Duration::from_millis(1000)).await; - let node_b_pubkey = node_b.pubkey.clone(); + let node_b_pubkey = node_b.pubkey; let message = |rpc_reply| -> NetworkActorMessage { NetworkActorMessage::Command(NetworkActorCommand::SendPayment( SendPaymentCommand { @@ -1172,14 +1172,14 @@ async fn test_network_send_previous_tlc_error() { tokio::time::sleep(tokio::time::Duration::from_millis(2000)).await; let secp = Secp256k1::new(); - let keys: Vec = std::iter::repeat_with(|| gen_rand_fiber_private_key().into()) + let keys: Vec = std::iter::repeat_with(gen_rand_fiber_private_key) .take(1) .collect(); let hops_infos = vec![ PaymentHopData { amount: 2, expiry: 3, - next_hop: Some(keys[0].pubkey().into()), + next_hop: Some(keys[0].pubkey()), funding_tx_hash: Hash256::default(), hash_algorithm: HashAlgorithm::Sha256, payment_preimage: None, @@ -1217,7 +1217,7 @@ async fn test_network_send_previous_tlc_error() { hash_algorithm: HashAlgorithm::Sha256, // invalid onion packet onion_packet: packet.next.clone(), - shared_secret: packet.shared_secret.clone(), + shared_secret: packet.shared_secret, previous_tlc: None, }, rpc_reply, @@ -1293,7 +1293,7 @@ async fn test_network_send_payment_keysend_with_payment_hash() { // Wait for the channel announcement to be broadcasted tokio::time::sleep(tokio::time::Duration::from_millis(1000)).await; - let node_b_pubkey = node_b.pubkey.clone(); + let node_b_pubkey = node_b.pubkey; let payment_hash = gen_rand_sha256_hash(); // This payment request is without an invoice, the receiver will return an error `IncorrectOrUnknownPaymentDetails` @@ -1343,7 +1343,7 @@ async fn test_network_send_payment_final_incorrect_hash() { let node_a_local_balance = node_a.get_local_balance_from_channel(channel_id); let node_b_local_balance = node_b.get_local_balance_from_channel(channel_id); - let node_b_pubkey = node_b.pubkey.clone(); + let node_b_pubkey = node_b.pubkey; let payment_hash = gen_rand_sha256_hash(); // This payment request is without an invoice, the receiver will return an error `IncorrectOrUnknownPaymentDetails` @@ -1412,7 +1412,7 @@ async fn test_network_send_payment_target_not_found() { // Wait for the channel announcement to be broadcasted tokio::time::sleep(tokio::time::Duration::from_millis(1000)).await; - let node_b_pubkey = gen_rand_fiber_public_key().into(); + let node_b_pubkey = gen_rand_fiber_public_key(); let message = |rpc_reply| -> NetworkActorMessage { NetworkActorMessage::Command(NetworkActorCommand::SendPayment( SendPaymentCommand { @@ -1453,7 +1453,7 @@ async fn test_network_send_payment_amount_is_too_large() { // Wait for the channel announcement to be broadcasted tokio::time::sleep(tokio::time::Duration::from_millis(1000)).await; - let node_b_pubkey = node_b.pubkey.clone(); + let node_b_pubkey = node_b.pubkey; let message = |rpc_reply| -> NetworkActorMessage { NetworkActorMessage::Command(NetworkActorCommand::SendPayment( SendPaymentCommand { @@ -1498,7 +1498,7 @@ async fn test_network_send_payment_with_dry_run() { // Wait for the channel announcement to be broadcasted tokio::time::sleep(tokio::time::Duration::from_millis(1000)).await; - let node_b_pubkey = node_b.pubkey.clone(); + let node_b_pubkey = node_b.pubkey; let message = |rpc_reply| -> NetworkActorMessage { NetworkActorMessage::Command(NetworkActorCommand::SendPayment( SendPaymentCommand { @@ -1571,7 +1571,7 @@ async fn test_send_payment_with_3_nodes() { // sleep for 2 seconds to make sure the channel is established tokio::time::sleep(tokio::time::Duration::from_millis(1000)).await; let sent_amount = 1000000 + 5; - let node_c_pubkey = node_c.pubkey.clone(); + let node_c_pubkey = node_c.pubkey; let message = |rpc_reply| -> NetworkActorMessage { NetworkActorMessage::Command(NetworkActorCommand::SendPayment( SendPaymentCommand { @@ -1648,7 +1648,7 @@ async fn test_send_payment_with_rev_3_nodes() { let node_a_local = node_a.get_local_balance_from_channel(channel_2); let sent_amount = 1000000 + 5; - let node_a_pubkey = node_a.pubkey.clone(); + let node_a_pubkey = node_a.pubkey; let message = |rpc_reply| -> NetworkActorMessage { NetworkActorMessage::Command(NetworkActorCommand::SendPayment( SendPaymentCommand { @@ -1711,7 +1711,7 @@ async fn test_send_payment_with_max_nodes() { let (nodes, channels) = create_n_nodes_with_established_channel(&amounts, nodes_num, true).await; let source_node = &nodes[0]; - let target_pubkey = nodes[last].pubkey.clone(); + let target_pubkey = nodes[last].pubkey; let sender_local = nodes[0].get_local_balance_from_channel(channels[0]); let receiver_local = nodes[last].get_local_balance_from_channel(channels[last - 1]); @@ -1800,7 +1800,7 @@ async fn test_send_payment_with_3_nodes_overflow() { // sleep for 2 seconds to make sure the channel is established tokio::time::sleep(tokio::time::Duration::from_millis(1000)).await; let sent_amount = 0xfffffffffffffffffffffffffffffff; - let node_c_pubkey = node_c.pubkey.clone(); + let node_c_pubkey = node_c.pubkey; let message = |rpc_reply| -> NetworkActorMessage { NetworkActorMessage::Command(NetworkActorCommand::SendPayment( SendPaymentCommand { @@ -1849,7 +1849,7 @@ async fn test_send_payment_fail_with_3_nodes_invalid_hash() { // sleep for 2 seconds to make sure the channel is established tokio::time::sleep(tokio::time::Duration::from_millis(1000)).await; - let node_c_pubkey = node_c.pubkey.clone(); + let node_c_pubkey = node_c.pubkey; let message = |rpc_reply| -> NetworkActorMessage { NetworkActorMessage::Command(NetworkActorCommand::SendPayment( SendPaymentCommand { @@ -1921,7 +1921,7 @@ async fn test_send_payment_fail_with_3_nodes_final_tlc_expiry_delta() { // sleep for 2 seconds to make sure the channel is established tokio::time::sleep(tokio::time::Duration::from_millis(1000)).await; - let node_c_pubkey = node_c.pubkey.clone(); + let node_c_pubkey = node_c.pubkey; let message = |rpc_reply| -> NetworkActorMessage { NetworkActorMessage::Command(NetworkActorCommand::SendPayment( SendPaymentCommand { @@ -1948,7 +1948,7 @@ async fn test_send_payment_fail_with_3_nodes_final_tlc_expiry_delta() { let res = res.unwrap(); assert_eq!(res.status, PaymentSessionStatus::Created); - let node_c_pubkey = node_c.pubkey.clone(); + let node_c_pubkey = node_c.pubkey; let message = |rpc_reply| -> NetworkActorMessage { NetworkActorMessage::Command(NetworkActorCommand::SendPayment( SendPaymentCommand { @@ -1974,7 +1974,7 @@ async fn test_send_payment_fail_with_3_nodes_final_tlc_expiry_delta() { assert!(res.is_err()); assert!(res.unwrap_err().contains("invalid final_tlc_expiry_delta")); - let node_c_pubkey = node_c.pubkey.clone(); + let node_c_pubkey = node_c.pubkey; let message = |rpc_reply| -> NetworkActorMessage { NetworkActorMessage::Command(NetworkActorCommand::SendPayment( SendPaymentCommand { @@ -2017,7 +2017,7 @@ async fn test_send_payment_fail_with_3_nodes_dry_run_fee() { // sleep for 2 seconds to make sure the channel is established tokio::time::sleep(tokio::time::Duration::from_millis(2000)).await; - let node_c_pubkey = node_c.pubkey.clone(); + let node_c_pubkey = node_c.pubkey; let message = |rpc_reply| -> NetworkActorMessage { NetworkActorMessage::Command(NetworkActorCommand::SendPayment( SendPaymentCommand { @@ -2071,7 +2071,7 @@ async fn test_send_payment_fail_with_3_nodes_dry_run_fee() { // expect smaller fee since amount is smaller assert_eq!(res.fee, 1000000); - let node_c_pubkey = node_c.pubkey.clone(); + let node_c_pubkey = node_c.pubkey; let message = |rpc_reply| -> NetworkActorMessage { NetworkActorMessage::Command(NetworkActorCommand::SendPayment( SendPaymentCommand { @@ -2098,7 +2098,7 @@ async fn test_send_payment_fail_with_3_nodes_dry_run_fee() { let res = res.unwrap(); assert_eq!(res.fee, 1000000); - let node_c_pubkey = node_c.pubkey.clone(); + let node_c_pubkey = node_c.pubkey; let message = |rpc_reply| -> NetworkActorMessage { NetworkActorMessage::Command(NetworkActorCommand::SendPayment( SendPaymentCommand { @@ -2139,7 +2139,7 @@ async fn test_network_send_payment_dry_run_can_still_query() { tokio::time::sleep(tokio::time::Duration::from_millis(2000)).await; let payment_hash = gen_rand_sha256_hash(); - let node_b_pubkey = node_b.pubkey.clone(); + let node_b_pubkey = node_b.pubkey; let message = |rpc_reply| -> NetworkActorMessage { NetworkActorMessage::Command(NetworkActorCommand::SendPayment( SendPaymentCommand { @@ -2206,7 +2206,7 @@ async fn test_network_send_payment_dry_run_will_not_create_payment_session() { tokio::time::sleep(tokio::time::Duration::from_millis(2000)).await; let payment_hash = gen_rand_sha256_hash(); - let node_b_pubkey = node_b.pubkey.clone(); + let node_b_pubkey = node_b.pubkey; let message = |rpc_reply| -> NetworkActorMessage { NetworkActorMessage::Command(NetworkActorCommand::SendPayment( SendPaymentCommand { @@ -2370,7 +2370,7 @@ async fn do_test_channel_commitment_tx_after_add_tlc(algorithm: HashAlgorithm) { .await; let preimage = [1; 32]; - let digest = algorithm.hash(&preimage); + let digest = algorithm.hash(preimage); let tlc_amount = 1000000000; let add_tlc_result = call!(node_a.network_actor, |rpc_reply| { @@ -2384,7 +2384,7 @@ async fn do_test_channel_commitment_tx_after_add_tlc(algorithm: HashAlgorithm) { payment_hash: digest.into(), expiry: now_timestamp_as_millis_u64() + DEFAULT_EXPIRY_DELTA, onion_packet: None, - shared_secret: NO_SHARED_SECRET.clone(), + shared_secret: NO_SHARED_SECRET, previous_tlc: None, }, rpc_reply, @@ -2490,7 +2490,7 @@ async fn do_test_remove_tlc_with_wrong_hash_algorithm( .await; let preimage = [1; 32]; - let digest = correct_algorithm.hash(&preimage); + let digest = correct_algorithm.hash(preimage); let tlc_amount = 1000000000; let add_tlc_result = call!(node_a.network_actor, |rpc_reply| { @@ -2504,7 +2504,7 @@ async fn do_test_remove_tlc_with_wrong_hash_algorithm( payment_hash: digest.into(), expiry: now_timestamp_as_millis_u64() + DEFAULT_EXPIRY_DELTA, onion_packet: None, - shared_secret: NO_SHARED_SECRET.clone(), + shared_secret: NO_SHARED_SECRET, previous_tlc: None, }, rpc_reply, @@ -2544,7 +2544,7 @@ async fn do_test_remove_tlc_with_wrong_hash_algorithm( let preimage = [2; 32]; // create a new payment hash - let digest = correct_algorithm.hash(&preimage); + let digest = correct_algorithm.hash(preimage); let add_tlc_result = call!(node_a.network_actor, |rpc_reply| { NetworkActorMessage::Command(NetworkActorCommand::ControlFiberChannel( ChannelCommandWithId { @@ -2556,7 +2556,7 @@ async fn do_test_remove_tlc_with_wrong_hash_algorithm( payment_hash: digest.into(), expiry: now_timestamp_as_millis_u64() + DEFAULT_EXPIRY_DELTA, onion_packet: None, - shared_secret: NO_SHARED_SECRET.clone(), + shared_secret: NO_SHARED_SECRET, previous_tlc: None, }, rpc_reply, @@ -2629,7 +2629,7 @@ async fn do_test_channel_remote_commitment_error() { // create a new payment hash let hash_algorithm = HashAlgorithm::Sha256; - let digest = hash_algorithm.hash(&preimage); + let digest = hash_algorithm.hash(preimage); if let Ok(add_tlc_result) = call!(node_a.network_actor, |rpc_reply| { NetworkActorMessage::Command(NetworkActorCommand::ControlFiberChannel( ChannelCommandWithId { @@ -2641,7 +2641,7 @@ async fn do_test_channel_remote_commitment_error() { payment_hash: digest.into(), expiry: now_timestamp_as_millis_u64() + DEFAULT_EXPIRY_DELTA, onion_packet: None, - shared_secret: NO_SHARED_SECRET.clone(), + shared_secret: NO_SHARED_SECRET, previous_tlc: None, }, rpc_reply, @@ -2657,7 +2657,7 @@ async fn do_test_channel_remote_commitment_error() { tokio::time::sleep(tokio::time::Duration::from_millis(10)).await; if all_sent.len() >= tlc_number_in_flight_limit { while all_sent.len() > tlc_number_in_flight_limit - 2 { - if let Some((preimage, tlc_id)) = all_sent.iter().next().cloned() { + if let Some((preimage, tlc_id)) = all_sent.first().cloned() { let remove_tlc_result = call!(node_b.network_actor, |rpc_reply| { NetworkActorMessage::Command(NetworkActorCommand::ControlFiberChannel( ChannelCommandWithId { @@ -2711,12 +2711,12 @@ async fn test_network_add_two_tlcs_remove_one() { let preimage_a = [1; 32]; let algorithm = HashAlgorithm::Sha256; - let digest = algorithm.hash(&preimage_a); + let digest = algorithm.hash(preimage_a); let add_tlc_result_a = call!(node_a.network_actor, |rpc_reply| { NetworkActorMessage::Command(NetworkActorCommand::ControlFiberChannel( ChannelCommandWithId { - channel_id: channel_id, + channel_id, command: ChannelCommand::AddTlc( AddTlcCommand { amount: 1000, @@ -2724,7 +2724,7 @@ async fn test_network_add_two_tlcs_remove_one() { payment_hash: digest.into(), expiry: now_timestamp_as_millis_u64() + DEFAULT_EXPIRY_DELTA, onion_packet: None, - shared_secret: NO_SHARED_SECRET.clone(), + shared_secret: NO_SHARED_SECRET, previous_tlc: None, }, rpc_reply, @@ -2739,11 +2739,11 @@ async fn test_network_add_two_tlcs_remove_one() { // if we don't wait for a while, the next add_tlc will fail with temporary failure let preimage_b = [2; 32]; let algorithm = HashAlgorithm::Sha256; - let digest = algorithm.hash(&preimage_b); + let digest = algorithm.hash(preimage_b); let add_tlc_result = call!(node_a.network_actor, |rpc_reply| { NetworkActorMessage::Command(NetworkActorCommand::ControlFiberChannel( ChannelCommandWithId { - channel_id: channel_id, + channel_id, command: ChannelCommand::AddTlc( AddTlcCommand { amount: 2000, @@ -2751,7 +2751,7 @@ async fn test_network_add_two_tlcs_remove_one() { payment_hash: digest.into(), expiry: now_timestamp_as_millis_u64() + DEFAULT_EXPIRY_DELTA, onion_packet: None, - shared_secret: NO_SHARED_SECRET.clone(), + shared_secret: NO_SHARED_SECRET, previous_tlc: None, }, rpc_reply, @@ -2767,7 +2767,7 @@ async fn test_network_add_two_tlcs_remove_one() { let add_tlc_result_b = call!(node_a.network_actor, |rpc_reply| { NetworkActorMessage::Command(NetworkActorCommand::ControlFiberChannel( ChannelCommandWithId { - channel_id: channel_id, + channel_id, command: ChannelCommand::AddTlc( AddTlcCommand { amount: 2000, @@ -2775,7 +2775,7 @@ async fn test_network_add_two_tlcs_remove_one() { payment_hash: digest.into(), expiry: now_timestamp_as_millis_u64() + DEFAULT_EXPIRY_DELTA, onion_packet: None, - shared_secret: NO_SHARED_SECRET.clone(), + shared_secret: NO_SHARED_SECRET, previous_tlc: None, }, rpc_reply, @@ -2790,10 +2790,10 @@ async fn test_network_add_two_tlcs_remove_one() { tokio::time::sleep(tokio::time::Duration::from_millis(500)).await; // remove tlc from node_b - let res = call!(node_b.network_actor, |rpc_reply| { + call!(node_b.network_actor, |rpc_reply| { NetworkActorMessage::Command(NetworkActorCommand::ControlFiberChannel( ChannelCommandWithId { - channel_id: channel_id, + channel_id, command: ChannelCommand::RemoveTlc( RemoveTlcCommand { id: add_tlc_result_a.tlc_id, @@ -2808,7 +2808,7 @@ async fn test_network_add_two_tlcs_remove_one() { }) .expect("node_b alive") .expect("successfully removed tlc"); - eprintln!("remove tlc result: {:?}", res); + eprintln!("remove tlc result: {:?}", ()); tokio::time::sleep(tokio::time::Duration::from_millis(500)).await; let new_a_balance = node_a.get_local_balance_from_channel(channel_id); @@ -2822,10 +2822,10 @@ async fn test_network_add_two_tlcs_remove_one() { tokio::time::sleep(tokio::time::Duration::from_millis(500)).await; // remove the later tlc from node_b - let res = call!(node_b.network_actor, |rpc_reply| { + call!(node_b.network_actor, |rpc_reply| { NetworkActorMessage::Command(NetworkActorCommand::ControlFiberChannel( ChannelCommandWithId { - channel_id: channel_id, + channel_id, command: ChannelCommand::RemoveTlc( RemoveTlcCommand { id: add_tlc_result_b.unwrap().tlc_id, @@ -2840,7 +2840,7 @@ async fn test_network_add_two_tlcs_remove_one() { }) .expect("node_b alive") .expect("successfully removed tlc"); - eprintln!("remove tlc result: {:?}", res); + eprintln!("remove tlc result: {:?}", ()); tokio::time::sleep(tokio::time::Duration::from_millis(400)).await; let new_a_balance = node_a.get_local_balance_from_channel(channel_id); @@ -2863,7 +2863,7 @@ async fn test_remove_tlc_with_expiry_error() { .await; let preimage = [1; 32]; - let digest = HashAlgorithm::CkbHash.hash(&preimage); + let digest = HashAlgorithm::CkbHash.hash(preimage); let tlc_amount = 1000000000; // add tlc command with expiry soon @@ -2873,7 +2873,7 @@ async fn test_remove_tlc_with_expiry_error() { payment_hash: digest.into(), expiry: now_timestamp_as_millis_u64() + 10, onion_packet: None, - shared_secret: NO_SHARED_SECRET.clone(), + shared_secret: NO_SHARED_SECRET, previous_tlc: None, }; @@ -2896,7 +2896,7 @@ async fn test_remove_tlc_with_expiry_error() { payment_hash: digest.into(), expiry: now_timestamp_as_millis_u64() + MAX_PAYMENT_TLC_EXPIRY_LIMIT + 20 * 1000, onion_packet: None, - shared_secret: NO_SHARED_SECRET.clone(), + shared_secret: NO_SHARED_SECRET, previous_tlc: None, }; @@ -2923,7 +2923,7 @@ async fn do_test_add_tlc_duplicated() { .await; let preimage = [1; 32]; - let digest = HashAlgorithm::CkbHash.hash(&preimage); + let digest = HashAlgorithm::CkbHash.hash(preimage); let tlc_amount = 1000000000; for i in 1..=2 { @@ -2935,7 +2935,7 @@ async fn do_test_add_tlc_duplicated() { payment_hash: digest.into(), expiry: now_timestamp_as_millis_u64() + 10, onion_packet: None, - shared_secret: NO_SHARED_SECRET.clone(), + shared_secret: NO_SHARED_SECRET, previous_tlc: None, }; let add_tlc_result = call!(node_a.network_actor, |rpc_reply| { @@ -2971,10 +2971,10 @@ async fn do_test_add_tlc_waiting_ack() { let add_tlc_command = AddTlcCommand { amount: tlc_amount, hash_algorithm: HashAlgorithm::CkbHash, - payment_hash: gen_rand_sha256_hash().into(), + payment_hash: gen_rand_sha256_hash(), expiry: now_timestamp_as_millis_u64() + 100000000, onion_packet: None, - shared_secret: NO_SHARED_SECRET.clone(), + shared_secret: NO_SHARED_SECRET, previous_tlc: None, }; let add_tlc_result = call!(node_a.network_actor, |rpc_reply| { @@ -3002,11 +3002,11 @@ async fn do_test_add_tlc_waiting_ack() { let add_tlc_command = AddTlcCommand { amount: tlc_amount, hash_algorithm: HashAlgorithm::CkbHash, - payment_hash: gen_rand_sha256_hash().into(), + payment_hash: gen_rand_sha256_hash(), expiry: now_timestamp_as_millis_u64() + 100000000, onion_packet: None, previous_tlc: None, - shared_secret: NO_SHARED_SECRET.clone(), + shared_secret: NO_SHARED_SECRET, }; let add_tlc_result = call!(node_b.network_actor, |rpc_reply| { NetworkActorMessage::Command(NetworkActorCommand::ControlFiberChannel( @@ -3063,10 +3063,10 @@ async fn do_test_add_tlc_with_number_limit() { let add_tlc_command = AddTlcCommand { amount: tlc_amount, hash_algorithm: HashAlgorithm::CkbHash, - payment_hash: gen_rand_sha256_hash().into(), + payment_hash: gen_rand_sha256_hash(), expiry: now_timestamp_as_millis_u64() + 100000000, onion_packet: None, - shared_secret: NO_SHARED_SECRET.clone(), + shared_secret: NO_SHARED_SECRET, previous_tlc: None, }; let add_tlc_result = call!(node_a.network_actor, |rpc_reply| { @@ -3094,10 +3094,10 @@ async fn do_test_add_tlc_with_number_limit() { let add_tlc_command = AddTlcCommand { amount: tlc_amount, hash_algorithm: HashAlgorithm::CkbHash, - payment_hash: gen_rand_sha256_hash().into(), + payment_hash: gen_rand_sha256_hash(), expiry: now_timestamp_as_millis_u64() + 100000000, onion_packet: None, - shared_secret: NO_SHARED_SECRET.clone(), + shared_secret: NO_SHARED_SECRET, previous_tlc: None, }; let add_tlc_result = call!(node_b.network_actor, |rpc_reply| { @@ -3148,10 +3148,10 @@ async fn do_test_add_tlc_number_limit_reverse() { let add_tlc_command = AddTlcCommand { amount: tlc_amount, hash_algorithm: HashAlgorithm::CkbHash, - payment_hash: gen_rand_sha256_hash().into(), + payment_hash: gen_rand_sha256_hash(), expiry: now_timestamp_as_millis_u64() + 100000000, onion_packet: None, - shared_secret: NO_SHARED_SECRET.clone(), + shared_secret: NO_SHARED_SECRET, previous_tlc: None, }; let add_tlc_result = call!(node_b.network_actor, |rpc_reply| { @@ -3179,10 +3179,10 @@ async fn do_test_add_tlc_number_limit_reverse() { let add_tlc_command = AddTlcCommand { amount: tlc_amount, hash_algorithm: HashAlgorithm::CkbHash, - payment_hash: gen_rand_sha256_hash().into(), + payment_hash: gen_rand_sha256_hash(), expiry: now_timestamp_as_millis_u64() + 100000000, onion_packet: None, - shared_secret: NO_SHARED_SECRET.clone(), + shared_secret: NO_SHARED_SECRET, previous_tlc: None, }; let add_tlc_result = call!(node_a.network_actor, |rpc_reply| { @@ -3234,10 +3234,10 @@ async fn do_test_add_tlc_value_limit() { let add_tlc_command = AddTlcCommand { amount: tlc_amount, hash_algorithm: HashAlgorithm::CkbHash, - payment_hash: gen_rand_sha256_hash().into(), + payment_hash: gen_rand_sha256_hash(), expiry: now_timestamp_as_millis_u64() + 100000000, onion_packet: None, - shared_secret: NO_SHARED_SECRET.clone(), + shared_secret: NO_SHARED_SECRET, previous_tlc: None, }; let add_tlc_result = call!(node_a.network_actor, |rpc_reply| { @@ -3266,10 +3266,10 @@ async fn do_test_add_tlc_value_limit() { let add_tlc_command = AddTlcCommand { amount: tlc_amount, hash_algorithm: HashAlgorithm::CkbHash, - payment_hash: gen_rand_sha256_hash().into(), + payment_hash: gen_rand_sha256_hash(), expiry: now_timestamp_as_millis_u64() + 100000000, onion_packet: None, - shared_secret: NO_SHARED_SECRET.clone(), + shared_secret: NO_SHARED_SECRET, previous_tlc: None, }; let add_tlc_result = call!(node_b.network_actor, |rpc_reply| { @@ -3319,11 +3319,11 @@ async fn do_test_add_tlc_min_tlc_value_limit() { let add_tlc_command = AddTlcCommand { amount: tlc_amount, hash_algorithm: HashAlgorithm::CkbHash, - payment_hash: gen_rand_sha256_hash().into(), + payment_hash: gen_rand_sha256_hash(), expiry: now_timestamp_as_millis_u64() + 100000000, onion_packet: None, previous_tlc: None, - shared_secret: NO_SHARED_SECRET.clone(), + shared_secret: NO_SHARED_SECRET, }; let add_tlc_result = call!(node_a.network_actor, |rpc_reply| { NetworkActorMessage::Command(NetworkActorCommand::ControlFiberChannel( @@ -3343,11 +3343,11 @@ async fn do_test_add_tlc_min_tlc_value_limit() { let add_tlc_command = AddTlcCommand { amount: tlc_amount, hash_algorithm: HashAlgorithm::CkbHash, - payment_hash: gen_rand_sha256_hash().into(), + payment_hash: gen_rand_sha256_hash(), expiry: now_timestamp_as_millis_u64() + 100000000, onion_packet: None, previous_tlc: None, - shared_secret: NO_SHARED_SECRET.clone(), + shared_secret: NO_SHARED_SECRET, }; let add_tlc_result = call!(node_b.network_actor, |rpc_reply| { NetworkActorMessage::Command(NetworkActorCommand::ControlFiberChannel( @@ -3367,11 +3367,11 @@ async fn do_test_add_tlc_min_tlc_value_limit() { let add_tlc_command = AddTlcCommand { amount: tlc_amount, hash_algorithm: HashAlgorithm::CkbHash, - payment_hash: gen_rand_sha256_hash().into(), + payment_hash: gen_rand_sha256_hash(), expiry: now_timestamp_as_millis_u64() + 100000000, onion_packet: None, previous_tlc: None, - shared_secret: NO_SHARED_SECRET.clone(), + shared_secret: NO_SHARED_SECRET, }; let add_tlc_result = call!(node_b.network_actor, |rpc_reply| { NetworkActorMessage::Command(NetworkActorCommand::ControlFiberChannel( @@ -3565,8 +3565,8 @@ async fn test_forward_payment_tlc_minimum_value() { let [node_a, node_b, node_c] = nodes.try_into().expect("3 nodes"); let [channel_a_b, channel_b_c] = channels.try_into().expect("2 channels"); - let node_c_pubkey = node_c.pubkey.clone(); - let node_b_pubkey = node_b.pubkey.clone(); + let node_c_pubkey = node_c.pubkey; + let node_b_pubkey = node_b.pubkey; let tlc_amount = 99; // update B's ChannelUpdate in channel_b_c with tlc_minimum_value set to our tlc_amount @@ -3648,11 +3648,11 @@ async fn test_forward_payment_tlc_minimum_value() { let add_tlc_command = AddTlcCommand { amount: tlc_amount, hash_algorithm: HashAlgorithm::CkbHash, - payment_hash: gen_rand_sha256_hash().into(), + payment_hash: gen_rand_sha256_hash(), expiry: now_timestamp_as_millis_u64() + 100000000, onion_packet: None, previous_tlc: None, - shared_secret: NO_SHARED_SECRET.clone(), + shared_secret: NO_SHARED_SECRET, }; let add_tlc_result = call!(node_a.network_actor, |rpc_reply| { NetworkActorMessage::Command(NetworkActorCommand::ControlFiberChannel( @@ -3778,8 +3778,8 @@ async fn test_send_payment_with_outdated_fee_rate() { .await; let [node_a, node_b, node_c] = nodes.try_into().expect("3 nodes"); - let node_b_pubkey = node_b.pubkey.clone(); - let node_c_pubkey = node_c.pubkey.clone(); + let node_b_pubkey = node_b.pubkey; + let node_c_pubkey = node_c.pubkey; let hash_set: HashSet<_> = [node_b_pubkey, node_c_pubkey].into_iter().collect(); tokio::time::sleep(tokio::time::Duration::from_millis(1000)).await; @@ -3861,7 +3861,7 @@ async fn do_test_channel_with_simple_update_operation(algorithm: HashAlgorithm) .await; let preimage = [1; 32]; - let digest = algorithm.hash(&preimage); + let digest = algorithm.hash(preimage); let tlc_amount = 1000000000; let add_tlc_result = call!(node_a.network_actor, |rpc_reply| { @@ -3875,7 +3875,7 @@ async fn do_test_channel_with_simple_update_operation(algorithm: HashAlgorithm) payment_hash: digest.into(), expiry: now_timestamp_as_millis_u64() + DEFAULT_EXPIRY_DELTA, onion_packet: None, - shared_secret: NO_SHARED_SECRET.clone(), + shared_secret: NO_SHARED_SECRET, previous_tlc: None, }, rpc_reply, @@ -4153,7 +4153,7 @@ async fn test_revoke_old_commitment_transaction() { .cell_deps(get_cell_deps(vec![Contract::CommitmentLock], &None)) .input( CellInput::new_builder() - .previous_output(commitment_tx.output_pts().get(0).unwrap().clone()) + .previous_output(commitment_tx.output_pts().first().unwrap().clone()) .build(), ) .output(revocation_data.output) @@ -4586,7 +4586,7 @@ async fn test_send_payment_with_node_restart_then_resend_add_tlc() { tokio::time::sleep(tokio::time::Duration::from_secs(2)).await; - let node_b_pubkey = node_b.pubkey.clone(); + let node_b_pubkey = node_b.pubkey; let tlc_amount = 99; let message = |rpc_reply| { NetworkActorMessage::Command(NetworkActorCommand::SendPayment( @@ -4662,7 +4662,7 @@ async fn test_node_reestablish_resend_remove_tlc() { let preimage = [2; 32]; // create a new payment hash - let payment_hash = HashAlgorithm::CkbHash.hash(&preimage); + let payment_hash = HashAlgorithm::CkbHash.hash(preimage); let add_tlc_result = call!(node_a.network_actor, |rpc_reply| { NetworkActorMessage::Command(NetworkActorCommand::ControlFiberChannel( @@ -4672,10 +4672,10 @@ async fn test_node_reestablish_resend_remove_tlc() { AddTlcCommand { amount: 1000, hash_algorithm: HashAlgorithm::CkbHash, - payment_hash: payment_hash.clone().into(), + payment_hash: payment_hash.into(), expiry: now_timestamp_as_millis_u64() + DEFAULT_EXPIRY_DELTA, onion_packet: None, - shared_secret: NO_SHARED_SECRET.clone(), + shared_secret: NO_SHARED_SECRET, previous_tlc: None, }, rpc_reply, @@ -4760,7 +4760,7 @@ async fn test_open_channel_with_large_size_shutdown_script_should_fail() { OpenChannelCommand { peer_id: node_b.peer_id.clone(), public: false, - shutdown_script: Some(Script::new_builder().args(vec![0u8; 40].pack()).build()), + shutdown_script: Some(Script::new_builder().args([0u8; 40].pack()).build()), funding_amount: (81 + 1) * 100000000 - 1, funding_udt_type_script: None, commitment_fee_rate: None, @@ -4809,7 +4809,7 @@ async fn test_accept_channel_with_large_size_shutdown_script_should_fail() { OpenChannelCommand { peer_id: node_b.peer_id.clone(), public: false, - shutdown_script: Some(Script::new_builder().args(vec![0u8; 40].pack()).build()), + shutdown_script: Some(Script::new_builder().args([0u8; 40].pack()).build()), funding_amount: (81 + 1 + 90) * 100000000, funding_udt_type_script: None, commitment_fee_rate: None, @@ -4872,7 +4872,7 @@ async fn test_shutdown_channel_with_large_size_shutdown_script_should_fail() { channel_id: new_channel_id, command: ChannelCommand::Shutdown( ShutdownCommand { - close_script: Script::new_builder().args(vec![0u8; 21].pack()).build(), + close_script: Script::new_builder().args([0u8; 21].pack()).build(), fee_rate: FeeRate::from_u64(DEFAULT_COMMITMENT_FEE_RATE), force: false, }, @@ -4906,7 +4906,7 @@ async fn test_shutdown_channel_with_different_size_shutdown_script() { channel_id: new_channel_id, command: ChannelCommand::Shutdown( ShutdownCommand { - close_script: Script::new_builder().args(vec![0u8; 19].pack()).build(), + close_script: Script::new_builder().args([0u8; 19].pack()).build(), fee_rate: FeeRate::from_u64(DEFAULT_COMMITMENT_FEE_RATE), force: false, }, @@ -5022,10 +5022,10 @@ async fn test_shutdown_channel_network_graph_with_sync_up() { let message = |rpc_reply| { NetworkActorMessage::Command(NetworkActorCommand::ControlFiberChannel( ChannelCommandWithId { - channel_id: channel_id, + channel_id, command: ChannelCommand::Shutdown( ShutdownCommand { - close_script: Script::new_builder().args(vec![0u8; 19].pack()).build(), + close_script: Script::new_builder().args([0u8; 19].pack()).build(), fee_rate: FeeRate::from_u64(DEFAULT_COMMITMENT_FEE_RATE), force: false, }, @@ -5064,7 +5064,7 @@ async fn test_send_payment_with_channel_balance_error() { create_n_nodes_with_established_channel(&amounts, nodes_num, true).await; let [node_0, _node_1, mut node_2, node_3] = nodes.try_into().expect("4 nodes"); let source_node = &node_0; - let target_pubkey = node_3.pubkey.clone(); + let target_pubkey = node_3.pubkey; // sleep for a while tokio::time::sleep(tokio::time::Duration::from_secs(1)).await; @@ -5072,7 +5072,7 @@ async fn test_send_payment_with_channel_balance_error() { let message = |rpc_reply| -> NetworkActorMessage { NetworkActorMessage::Command(NetworkActorCommand::SendPayment( SendPaymentCommand { - target_pubkey: Some(target_pubkey.clone()), + target_pubkey: Some(target_pubkey), amount: Some(3000), payment_hash: None, final_tlc_expiry_delta: None, @@ -5102,7 +5102,7 @@ async fn test_send_payment_with_channel_balance_error() { let message = |rpc_reply| -> NetworkActorMessage { NetworkActorMessage::Command(NetworkActorCommand::SendPayment( SendPaymentCommand { - target_pubkey: Some(target_pubkey.clone()), + target_pubkey: Some(target_pubkey), amount: Some(3000), payment_hash: None, final_tlc_expiry_delta: None, @@ -5211,12 +5211,12 @@ async fn test_send_payment_with_multiple_edges_in_middle_hops() { .await; let [node_0, _node_1, _node_2, node_3] = nodes.try_into().expect("4 nodes"); let source_node = &node_0; - let target_pubkey = node_3.pubkey.clone(); + let target_pubkey = node_3.pubkey; let message = |rpc_reply| -> NetworkActorMessage { NetworkActorMessage::Command(NetworkActorCommand::SendPayment( SendPaymentCommand { - target_pubkey: Some(target_pubkey.clone()), + target_pubkey: Some(target_pubkey), amount: Some(999), payment_hash: None, final_tlc_expiry_delta: None, @@ -5267,12 +5267,12 @@ async fn test_send_payment_with_all_failed_middle_hops() { .await; let [node_0, _node_1, _node_2, node_3] = nodes.try_into().expect("4 nodes"); let source_node = &node_0; - let target_pubkey = node_3.pubkey.clone(); + let target_pubkey = node_3.pubkey; let message = |rpc_reply| -> NetworkActorMessage { NetworkActorMessage::Command(NetworkActorCommand::SendPayment( SendPaymentCommand { - target_pubkey: Some(target_pubkey.clone()), + target_pubkey: Some(target_pubkey), amount: Some(999), payment_hash: None, final_tlc_expiry_delta: None, @@ -5324,12 +5324,12 @@ async fn test_send_payment_with_multiple_edges_can_succeed_in_retry() { .await; let [node_0, _node_1, _node_2, node_3] = nodes.try_into().expect("4 nodes"); let source_node = &node_0; - let target_pubkey = node_3.pubkey.clone(); + let target_pubkey = node_3.pubkey; let message = |rpc_reply| -> NetworkActorMessage { NetworkActorMessage::Command(NetworkActorCommand::SendPayment( SendPaymentCommand { - target_pubkey: Some(target_pubkey.clone()), + target_pubkey: Some(target_pubkey), amount: Some(999), payment_hash: None, final_tlc_expiry_delta: None, @@ -5380,12 +5380,12 @@ async fn test_send_payment_with_final_hop_multiple_edges_in_middle_hops() { .await; let [node_0, _node_1, _node_2, node_3] = nodes.try_into().expect("4 nodes"); let source_node = &node_0; - let target_pubkey = node_3.pubkey.clone(); + let target_pubkey = node_3.pubkey; let message = |rpc_reply| -> NetworkActorMessage { NetworkActorMessage::Command(NetworkActorCommand::SendPayment( SendPaymentCommand { - target_pubkey: Some(target_pubkey.clone()), + target_pubkey: Some(target_pubkey), amount: Some(999), payment_hash: None, final_tlc_expiry_delta: None, @@ -5436,12 +5436,12 @@ async fn test_send_payment_with_final_all_failed_middle_hops() { .await; let [node_0, _node_1, _node_2, node_3] = nodes.try_into().expect("4 nodes"); let source_node = &node_0; - let target_pubkey = node_3.pubkey.clone(); + let target_pubkey = node_3.pubkey; let message = |rpc_reply| -> NetworkActorMessage { NetworkActorMessage::Command(NetworkActorCommand::SendPayment( SendPaymentCommand { - target_pubkey: Some(target_pubkey.clone()), + target_pubkey: Some(target_pubkey), amount: Some(999), payment_hash: None, final_tlc_expiry_delta: None, @@ -5492,12 +5492,12 @@ async fn test_send_payment_with_final_multiple_edges_can_succeed_in_retry() { .await; let [node_0, _node_1, _node_2, node_3] = nodes.try_into().expect("4 nodes"); let source_node = &node_0; - let target_pubkey = node_3.pubkey.clone(); + let target_pubkey = node_3.pubkey; let message = |rpc_reply| -> NetworkActorMessage { NetworkActorMessage::Command(NetworkActorCommand::SendPayment( SendPaymentCommand { - target_pubkey: Some(target_pubkey.clone()), + target_pubkey: Some(target_pubkey), amount: Some(999), payment_hash: None, final_tlc_expiry_delta: None, @@ -5546,12 +5546,12 @@ async fn test_send_payment_with_first_hop_failed_with_fee() { .await; let [node_0, _node_1, _node_2, node_3] = nodes.try_into().expect("4 nodes"); let source_node = &node_0; - let target_pubkey = node_3.pubkey.clone(); + let target_pubkey = node_3.pubkey; let message = |rpc_reply| -> NetworkActorMessage { NetworkActorMessage::Command(NetworkActorCommand::SendPayment( SendPaymentCommand { - target_pubkey: Some(target_pubkey.clone()), + target_pubkey: Some(target_pubkey), amount: Some(999), payment_hash: None, final_tlc_expiry_delta: None, @@ -5596,12 +5596,12 @@ async fn test_send_payment_succeed_with_multiple_edges_in_first_hop() { .await; let [node_0, _node_1, _node_2, node_3] = nodes.try_into().expect("4 nodes"); let source_node = &node_0; - let target_pubkey = node_3.pubkey.clone(); + let target_pubkey = node_3.pubkey; let message = |rpc_reply| -> NetworkActorMessage { NetworkActorMessage::Command(NetworkActorCommand::SendPayment( SendPaymentCommand { - target_pubkey: Some(target_pubkey.clone()), + target_pubkey: Some(target_pubkey), amount: Some(999), payment_hash: None, final_tlc_expiry_delta: None, @@ -5651,12 +5651,12 @@ async fn test_send_payment_with_first_hop_all_failed() { .await; let [node_0, _node_1, _node_2, node_3] = nodes.try_into().expect("4 nodes"); let source_node = &node_0; - let target_pubkey = node_3.pubkey.clone(); + let target_pubkey = node_3.pubkey; let message = |rpc_reply| -> NetworkActorMessage { NetworkActorMessage::Command(NetworkActorCommand::SendPayment( SendPaymentCommand { - target_pubkey: Some(target_pubkey.clone()), + target_pubkey: Some(target_pubkey), amount: Some(999), payment_hash: None, final_tlc_expiry_delta: None, @@ -5703,7 +5703,7 @@ async fn test_send_payment_will_succeed_with_direct_channel_info_first_hop() { .await; let [mut node_0, _node_1, _node_2, node_3] = nodes.try_into().expect("4 nodes"); let source_node = &mut node_0; - let target_pubkey = node_3.pubkey.clone(); + let target_pubkey = node_3.pubkey; // manually update the channel's to_local_amount source_node @@ -5714,7 +5714,7 @@ async fn test_send_payment_will_succeed_with_direct_channel_info_first_hop() { let message = |rpc_reply| -> NetworkActorMessage { NetworkActorMessage::Command(NetworkActorCommand::SendPayment( SendPaymentCommand { - target_pubkey: Some(target_pubkey.clone()), + target_pubkey: Some(target_pubkey), amount: Some(999), payment_hash: None, final_tlc_expiry_delta: None, @@ -5767,7 +5767,7 @@ async fn test_send_payment_will_succeed_with_retry_in_middle_hops() { let [mut node_0, _node_1, mut node_2, node_3] = nodes.try_into().expect("4 nodes"); let source_node = &mut node_0; let node_0_amount = source_node.get_local_balance_from_channel(channels[0]); - let target_pubkey = node_3.pubkey.clone(); + let target_pubkey = node_3.pubkey; // manually update the channel's to_local_amount node_2.update_channel_local_balance(channels[2], 100).await; @@ -5777,7 +5777,7 @@ async fn test_send_payment_will_succeed_with_retry_in_middle_hops() { let message = |rpc_reply| -> NetworkActorMessage { NetworkActorMessage::Command(NetworkActorCommand::SendPayment( SendPaymentCommand { - target_pubkey: Some(target_pubkey.clone()), + target_pubkey: Some(target_pubkey), amount: Some(amount), payment_hash: None, final_tlc_expiry_delta: None, @@ -5836,7 +5836,7 @@ async fn test_send_payment_will_fail_with_last_hop_info_in_add_tlc_peer() { .await; let [mut node_0, _node_1, _node_2, mut node_3] = nodes.try_into().expect("4 nodes"); let source_node = &mut node_0; - let target_pubkey = node_3.pubkey.clone(); + let target_pubkey = node_3.pubkey; // manually update the channel's to_remote_amount node_3 @@ -5846,7 +5846,7 @@ async fn test_send_payment_will_fail_with_last_hop_info_in_add_tlc_peer() { let res = source_node .send_payment(SendPaymentCommand { - target_pubkey: Some(target_pubkey.clone()), + target_pubkey: Some(target_pubkey), amount: Some(999), payment_hash: None, final_tlc_expiry_delta: None, @@ -5902,7 +5902,7 @@ async fn test_send_payment_will_fail_with_invoice_not_generated_by_target() { .await; let [mut node_0, _node_1, _node_2, node_3] = nodes.try_into().expect("4 nodes"); let source_node = &mut node_0; - let target_pubkey = node_3.pubkey.clone(); + let target_pubkey = node_3.pubkey; let invoice = InvoiceBuilder::new(Currency::Fibd) .amount(Some(100)) @@ -5915,7 +5915,7 @@ async fn test_send_payment_will_fail_with_invoice_not_generated_by_target() { let res = source_node .send_payment(SendPaymentCommand { - target_pubkey: Some(target_pubkey.clone()), + target_pubkey: Some(target_pubkey), amount: Some(100), payment_hash: None, final_tlc_expiry_delta: None, @@ -5960,13 +5960,13 @@ async fn test_send_payment_will_succeed_with_valid_invoice() { .await; let [mut node_0, _node_1, _node_2, mut node_3] = nodes.try_into().expect("4 nodes"); let source_node = &mut node_0; - let target_pubkey = node_3.pubkey.clone(); + let target_pubkey = node_3.pubkey; let old_amount = node_3.get_local_balance_from_channel(channels[2]); let preimage = gen_rand_sha256_hash(); let ckb_invoice = InvoiceBuilder::new(Currency::Fibd) .amount(Some(100)) - .payment_preimage(preimage.clone()) + .payment_preimage(preimage) .payee_pub_key(target_pubkey.into()) .expiry_time(Duration::from_secs(100)) .build() @@ -5976,7 +5976,7 @@ async fn test_send_payment_will_succeed_with_valid_invoice() { let res = source_node .send_payment(SendPaymentCommand { - target_pubkey: Some(target_pubkey.clone()), + target_pubkey: Some(target_pubkey), amount: Some(100), payment_hash: None, final_tlc_expiry_delta: None, @@ -6028,13 +6028,13 @@ async fn test_send_payment_will_fail_with_no_invoice_preimage() { .await; let [mut node_0, _node_1, _node_2, mut node_3] = nodes.try_into().expect("4 nodes"); let source_node = &mut node_0; - let target_pubkey = node_3.pubkey.clone(); + let target_pubkey = node_3.pubkey; let old_amount = node_3.get_local_balance_from_channel(channels[2]); let preimage = gen_rand_sha256_hash(); let ckb_invoice = InvoiceBuilder::new(Currency::Fibd) .amount(Some(100)) - .payment_preimage(preimage.clone()) + .payment_preimage(preimage) .payee_pub_key(target_pubkey.into()) .expiry_time(Duration::from_secs(100)) .build() @@ -6045,7 +6045,7 @@ async fn test_send_payment_will_fail_with_no_invoice_preimage() { let res = source_node .send_payment(SendPaymentCommand { - target_pubkey: Some(target_pubkey.clone()), + target_pubkey: Some(target_pubkey), amount: Some(100), payment_hash: None, final_tlc_expiry_delta: None, @@ -6100,13 +6100,13 @@ async fn test_send_payment_will_fail_with_cancelled_invoice() { .await; let [mut node_0, _node_1, _node_2, mut node_3] = nodes.try_into().expect("4 nodes"); let source_node = &mut node_0; - let target_pubkey = node_3.pubkey.clone(); + let target_pubkey = node_3.pubkey; let old_amount = node_3.get_local_balance_from_channel(channels[2]); let preimage = gen_rand_sha256_hash(); let ckb_invoice = InvoiceBuilder::new(Currency::Fibd) .amount(Some(100)) - .payment_preimage(preimage.clone()) + .payment_preimage(preimage) .payee_pub_key(target_pubkey.into()) .expiry_time(Duration::from_secs(100)) .build() @@ -6119,7 +6119,7 @@ async fn test_send_payment_will_fail_with_cancelled_invoice() { let res = source_node .send_payment(SendPaymentCommand { - target_pubkey: Some(target_pubkey.clone()), + target_pubkey: Some(target_pubkey), amount: Some(100), payment_hash: None, final_tlc_expiry_delta: None, @@ -6170,13 +6170,13 @@ async fn test_send_payment_will_succeed_with_large_tlc_expiry_limit() { .await; let [mut node_0, _node_1, _node_2, node_3] = nodes.try_into().expect("4 nodes"); let source_node = &mut node_0; - let target_pubkey = node_3.pubkey.clone(); + let target_pubkey = node_3.pubkey; let expected_minimal_tlc_expiry_limit = (24 * 60 * 60 * 1000) * 3; let res = source_node .send_payment(SendPaymentCommand { - target_pubkey: Some(target_pubkey.clone()), + target_pubkey: Some(target_pubkey), amount: Some(999), payment_hash: None, final_tlc_expiry_delta: None, @@ -6197,7 +6197,7 @@ async fn test_send_payment_will_succeed_with_large_tlc_expiry_limit() { let res = source_node .send_payment(SendPaymentCommand { - target_pubkey: Some(target_pubkey.clone()), + target_pubkey: Some(target_pubkey), amount: Some(999), payment_hash: None, final_tlc_expiry_delta: None, diff --git a/src/fiber/tests/gossip.rs b/src/fiber/tests/gossip.rs index 55d3fc9e1..989acf2e7 100644 --- a/src/fiber/tests/gossip.rs +++ b/src/fiber/tests/gossip.rs @@ -68,8 +68,8 @@ impl GossipTestingContext { let root_actor = get_test_root_actor().await; let (gossip_handle, store_update_subscriber) = GossipProtocolHandle::new( None, - Duration::from_millis(50).into(), - Duration::from_millis(50).into(), + Duration::from_millis(50), + Duration::from_millis(50), true, None, None, @@ -219,7 +219,7 @@ async fn test_save_gossip_message() { let context = GossipTestingContext::new().await; let (_, announcement) = gen_rand_node_announcement(); context.save_message(BroadcastMessage::NodeAnnouncement(announcement.clone())); - tokio::time::sleep(Duration::from_millis(200).into()).await; + tokio::time::sleep(Duration::from_millis(200)).await; let new_announcement = context .get_store() .get_latest_node_announcement(&announcement.node_id) @@ -234,7 +234,7 @@ async fn test_saving_unconfirmed_channel_announcement() { context.save_message(BroadcastMessage::ChannelAnnouncement( channel_context.channel_announcement.clone(), )); - tokio::time::sleep(Duration::from_millis(200).into()).await; + tokio::time::sleep(Duration::from_millis(200)).await; let new_announcement = context .get_store() .get_latest_channel_announcement(channel_context.channel_outpoint()); @@ -250,7 +250,7 @@ async fn test_saving_confirmed_channel_announcement() { )); let status = context.submit_tx(channel_context.funding_tx.clone()).await; assert_eq!(status, Status::Committed); - tokio::time::sleep(Duration::from_millis(200).into()).await; + tokio::time::sleep(Duration::from_millis(200)).await; let new_announcement = context .get_store() .get_latest_channel_announcement(channel_context.channel_outpoint()); @@ -273,7 +273,7 @@ async fn test_saving_invalid_channel_announcement() { Bytes::new_builder() .set( b"wrong lock args" - .into_iter() + .iter() .map(|b| Byte::new(*b)) .collect(), ) @@ -287,7 +287,7 @@ async fn test_saving_invalid_channel_announcement() { .build(); let status = context.submit_tx(invalid_tx).await; assert_eq!(status, Status::Committed); - tokio::time::sleep(Duration::from_millis(200).into()).await; + tokio::time::sleep(Duration::from_millis(200)).await; let new_announcement = context .get_store() .get_latest_channel_announcement(channel_context.channel_outpoint()); @@ -303,7 +303,7 @@ async fn test_saving_channel_update_after_saving_channel_announcement() { )); let status = context.submit_tx(channel_context.funding_tx.clone()).await; assert_eq!(status, Status::Committed); - tokio::time::sleep(Duration::from_millis(200).into()).await; + tokio::time::sleep(Duration::from_millis(200)).await; let new_announcement = context .get_store() .get_latest_channel_announcement(channel_context.channel_outpoint()); @@ -324,7 +324,7 @@ async fn test_saving_channel_update_after_saving_channel_announcement() { ] { context.save_message(BroadcastMessage::ChannelUpdate(channel_update.clone())); } - tokio::time::sleep(Duration::from_millis(200).into()).await; + tokio::time::sleep(Duration::from_millis(200)).await; for b in [true, false] { let channel_update = context .get_store() @@ -354,7 +354,7 @@ async fn test_saving_channel_update_before_saving_channel_announcement() { ] { context.save_message(BroadcastMessage::ChannelUpdate(channel_update.clone())); } - tokio::time::sleep(Duration::from_millis(200).into()).await; + tokio::time::sleep(Duration::from_millis(200)).await; for b in [true, false] { let channel_update = context .get_store() @@ -367,7 +367,7 @@ async fn test_saving_channel_update_before_saving_channel_announcement() { )); let status = context.submit_tx(channel_context.funding_tx.clone()).await; assert_eq!(status, Status::Committed); - tokio::time::sleep(Duration::from_millis(200).into()).await; + tokio::time::sleep(Duration::from_millis(200)).await; let new_announcement = context .get_store() .get_latest_channel_announcement(channel_context.channel_outpoint()); @@ -389,7 +389,7 @@ async fn test_saving_invalid_channel_update() { )); let status = context.submit_tx(channel_context.funding_tx.clone()).await; assert_eq!(status, Status::Committed); - tokio::time::sleep(Duration::from_millis(200).into()).await; + tokio::time::sleep(Duration::from_millis(200)).await; let new_announcement = context .get_store() .get_latest_channel_announcement(channel_context.channel_outpoint()); @@ -411,7 +411,7 @@ async fn test_saving_invalid_channel_update() { channel_update.signature = Some(create_invalid_ecdsa_signature()); context.save_message(BroadcastMessage::ChannelUpdate(channel_update.clone())); } - tokio::time::sleep(Duration::from_millis(200).into()).await; + tokio::time::sleep(Duration::from_millis(200)).await; for b in [true, false] { let channel_update = context .get_store() @@ -430,7 +430,7 @@ async fn test_saving_channel_update_independency() { )); let status = context.submit_tx(channel_context.funding_tx.clone()).await; assert_eq!(status, Status::Committed); - tokio::time::sleep(Duration::from_millis(200).into()).await; + tokio::time::sleep(Duration::from_millis(200)).await; let new_announcement = context .get_store() .get_latest_channel_announcement(channel_context.channel_outpoint()); @@ -457,7 +457,7 @@ async fn test_saving_channel_update_independency() { } context.save_message(BroadcastMessage::ChannelUpdate(channel_update.clone())); } - tokio::time::sleep(Duration::from_millis(200).into()).await; + tokio::time::sleep(Duration::from_millis(200)).await; for is_channel_update_of_node1 in [true, false] { let channel_update = context.get_store().get_latest_channel_update( channel_context.channel_outpoint(), @@ -469,12 +469,10 @@ async fn test_saving_channel_update_independency() { } else { assert_ne!(channel_update, None); } + } else if node2_has_invalid_signature { + assert_eq!(channel_update, None); } else { - if node2_has_invalid_signature { - assert_eq!(channel_update, None); - } else { - assert_ne!(channel_update, None); - } + assert_ne!(channel_update, None); } } } @@ -505,7 +503,7 @@ async fn test_saving_channel_update_with_invalid_channel_announcement() { Bytes::new_builder() .set( b"wrong lock args" - .into_iter() + .iter() .map(|b| Byte::new(*b)) .collect(), ) @@ -519,7 +517,7 @@ async fn test_saving_channel_update_with_invalid_channel_announcement() { .build(); let status = context.submit_tx(invalid_tx).await; assert_eq!(status, Status::Committed); - tokio::time::sleep(Duration::from_millis(200).into()).await; + tokio::time::sleep(Duration::from_millis(200)).await; let new_announcement = context .get_store() .get_latest_channel_announcement(channel_context.channel_outpoint()); @@ -540,7 +538,7 @@ async fn test_saving_channel_update_with_invalid_channel_announcement() { ] { context.save_message(BroadcastMessage::ChannelUpdate(channel_update.clone())); } - tokio::time::sleep(Duration::from_millis(200).into()).await; + tokio::time::sleep(Duration::from_millis(200)).await; for b in [true, false] { let channel_update = context .get_store() @@ -554,10 +552,10 @@ async fn test_save_outdated_gossip_message() { let context = GossipTestingContext::new().await; let (sk, old_announcement) = gen_rand_node_announcement(); // Make sure new announcement has a different timestamp - tokio::time::sleep(Duration::from_millis(2).into()).await; + tokio::time::sleep(Duration::from_millis(2)).await; let new_announcement = gen_node_announcement_from_privkey(&sk); context.save_message(BroadcastMessage::NodeAnnouncement(new_announcement.clone())); - tokio::time::sleep(Duration::from_millis(200).into()).await; + tokio::time::sleep(Duration::from_millis(200)).await; let announcement_in_store = context .get_store() .get_latest_node_announcement(&new_announcement.node_id) @@ -565,7 +563,7 @@ async fn test_save_outdated_gossip_message() { assert_eq!(announcement_in_store, new_announcement); context.save_message(BroadcastMessage::NodeAnnouncement(old_announcement.clone())); - tokio::time::sleep(Duration::from_millis(200).into()).await; + tokio::time::sleep(Duration::from_millis(200)).await; let announcement_in_store = context .get_store() .get_latest_node_announcement(&new_announcement.node_id) @@ -579,7 +577,7 @@ async fn test_gossip_store_updates_basic_subscription() { let messages = context.subscribe(Default::default()).await; let (_, announcement) = gen_rand_node_announcement(); context.save_message(BroadcastMessage::NodeAnnouncement(announcement.clone())); - tokio::time::sleep(Duration::from_millis(200).into()).await; + tokio::time::sleep(Duration::from_millis(200)).await; let messages = messages.read().await; assert!(messages.len() == 1); assert_eq!( @@ -596,7 +594,7 @@ async fn test_gossip_store_updates_repeated_saving() { for _ in 0..10 { context.save_message(BroadcastMessage::NodeAnnouncement(announcement.clone())); } - tokio::time::sleep(Duration::from_millis(200).into()).await; + tokio::time::sleep(Duration::from_millis(200)).await; let messages = messages.read().await; assert!(messages.len() == 1); assert_eq!( @@ -610,19 +608,18 @@ async fn test_gossip_store_updates_saving_multiple_messages() { let context = GossipTestingContext::new().await; let messages = context.subscribe(Default::default()).await; let announcements = (0..10) - .into_iter() .map(|_| gen_rand_node_announcement().1) .collect::>(); for annoncement in &announcements { context.save_message(BroadcastMessage::NodeAnnouncement(annoncement.clone())); } - tokio::time::sleep(Duration::from_millis(200).into()).await; + tokio::time::sleep(Duration::from_millis(200)).await; let messages = messages.read().await; assert_eq!( messages.iter().cloned().collect::>(), announcements .into_iter() - .map(|a| BroadcastMessageWithTimestamp::NodeAnnouncement(a)) + .map(BroadcastMessageWithTimestamp::NodeAnnouncement) .collect::>() ); } @@ -633,13 +630,13 @@ async fn test_gossip_store_updates_saving_outdated_message() { let messages = context.subscribe(Default::default()).await; let (sk, old_announcement) = gen_rand_node_announcement(); // Make sure new announcement has a different timestamp - tokio::time::sleep(Duration::from_millis(2).into()).await; + tokio::time::sleep(Duration::from_millis(2)).await; let new_announcement = gen_node_announcement_from_privkey(&sk); for announcement in [&old_announcement, &new_announcement] { context.save_message(BroadcastMessage::NodeAnnouncement(announcement.clone())); } - tokio::time::sleep(Duration::from_millis(200).into()).await; + tokio::time::sleep(Duration::from_millis(200)).await; let messages = messages.read().await; // The subscriber may or may not receive the old announcement, but it should always receive the // new announcement. @@ -663,7 +660,7 @@ async fn check_two_node_announcements_with_one_invalid( for announcement in announcements { context.save_message(BroadcastMessage::NodeAnnouncement(announcement.clone())); } - tokio::time::sleep(Duration::from_millis(200).into()).await; + tokio::time::sleep(Duration::from_millis(200)).await; let messages = messages.read().await; assert_eq!(messages.len(), 1); assert_eq!( @@ -679,7 +676,7 @@ async fn test_gossip_store_updates_saving_invalid_message_1() { let (sk, mut old_announcement) = gen_rand_node_announcement(); old_announcement.signature = Some(create_invalid_ecdsa_signature()); // Make sure new announcement has a different timestamp - tokio::time::sleep(Duration::from_millis(2).into()).await; + tokio::time::sleep(Duration::from_millis(2)).await; let new_announcement = gen_node_announcement_from_privkey(&sk); check_two_node_announcements_with_one_invalid(new_announcement, old_announcement).await; @@ -690,7 +687,7 @@ async fn test_gossip_store_updates_saving_invalid_message_1() { async fn test_gossip_store_updates_saving_invalid_message_2() { let (sk, old_announcement) = gen_rand_node_announcement(); // Make sure new announcement has a different timestamp - tokio::time::sleep(Duration::from_millis(2).into()).await; + tokio::time::sleep(Duration::from_millis(2)).await; let mut new_announcement = gen_node_announcement_from_privkey(&sk); new_announcement.signature = Some(create_invalid_ecdsa_signature()); @@ -737,14 +734,14 @@ async fn test_our_own_channel_gossip_message_propagated() { for node in [&node_a, &node_b] { node.with_network_graph(|graph| { - let channels = graph.channels().into_iter().collect::>(); + let channels = graph.channels().collect::>(); assert_eq!(channels.len(), 1); let channel = channels[0].clone(); assert!(channel.update_of_node1.is_some()); assert!(channel.update_of_node2.is_some()); - let nodes = graph.nodes().into_iter().collect::>(); + let nodes = graph.nodes().collect::>(); assert_eq!(nodes.len(), 2); }) .await; @@ -758,7 +755,7 @@ async fn test_never_miss_any_message() { let context = GossipTestingContext::new().await; let messages = context.subscribe(Default::default()).await; context.save_message(BroadcastMessage::NodeAnnouncement(announcement.clone())); - tokio::time::sleep(Duration::from_secs(1).into()).await; + tokio::time::sleep(Duration::from_secs(1)).await; let messages = messages.read().await; assert_eq!(messages.len(), 1); assert_eq!( diff --git a/src/fiber/tests/graph.rs b/src/fiber/tests/graph.rs index c0260c9aa..30be8497a 100644 --- a/src/fiber/tests/graph.rs +++ b/src/fiber/tests/graph.rs @@ -91,7 +91,7 @@ impl MockNetworkGraph { .iter() .find(|(a, b, _)| (*a == node_a && *b == node_b) || (*a == node_b && *b == node_a)); if let Some((_, _, outpoint)) = outpoint { - self.graph.mark_channel_failed(&outpoint); + self.graph.mark_channel_failed(outpoint); } } @@ -814,7 +814,7 @@ fn test_graph_build_route_three_nodes_amount() { // TODO: pass randomized input to this function. fn do_test_graph_build_route_expiry(n_nodes: usize) { let mut network = MockNetworkGraph::new(n_nodes); - let ns = (0..n_nodes).into_iter().collect::>(); + let ns = (0..n_nodes).collect::>(); for window in ns.windows(2) { let source = window[0]; let target = window[1]; diff --git a/src/fiber/tests/history.rs b/src/fiber/tests/history.rs index 5996464fc..ad7ddfe04 100644 --- a/src/fiber/tests/history.rs +++ b/src/fiber/tests/history.rs @@ -123,7 +123,7 @@ fn test_history_internal_result() { .get(&(channel_outpoint.clone(), direction)) .unwrap(); assert_eq!(res.amount, 0); - assert_eq!(res.success, false); + assert!(!res.success); assert_ne!(res.time, 0); let res = internal_result @@ -131,7 +131,7 @@ fn test_history_internal_result() { .get(&(channel_outpoint.clone(), rev_direction)) .unwrap(); assert_eq!(res.amount, 0); - assert_eq!(res.success, false); + assert!(!res.success); assert_ne!(res.time, 0); internal_result.add_fail_pair_balanced(from, target, channel_outpoint.clone(), 100); @@ -141,7 +141,7 @@ fn test_history_internal_result() { .get(&(channel_outpoint, direction)) .unwrap(); assert_eq!(res.amount, 100); - assert_eq!(res.success, false); + assert!(!res.success); } #[test] @@ -175,14 +175,14 @@ fn test_history_internal_result_fail_pair() { .get(&(channel_outpoint.clone(), direction)) .unwrap(); assert_eq!(res.amount, 0); - assert_eq!(res.success, false); + assert!(!res.success); let res = internal_result .pairs .get(&(channel_outpoint, rev_direction)) .unwrap(); assert_eq!(res.amount, 0); - assert_eq!(res.success, false); + assert!(!res.success); } #[test] @@ -221,13 +221,13 @@ fn test_history_internal_result_success_range_pair() { .get(&(channel_outpoint1, direction1)) .unwrap(); assert_eq!(res.amount, 10); - assert_eq!(res.success, true); + assert!(res.success); let res = internal_result .pairs .get(&(channel_outpoint2, direction2)) .unwrap(); assert_eq!(res.amount, 5); - assert_eq!(res.success, true); + assert!(res.success); } #[test] @@ -267,28 +267,28 @@ fn test_history_internal_result_fail_range_pair() { .get(&(channel_outpoint1.clone(), direction1)) .unwrap(); assert_eq!(res.amount, 0); - assert_eq!(res.success, false); + assert!(!res.success); let res = internal_result .pairs .get(&(channel_outpoint1.clone(), rev_direction1)) .unwrap(); assert_eq!(res.amount, 0); - assert_eq!(res.success, false); + assert!(!res.success); let res = internal_result .pairs .get(&(channel_outpoint2.clone(), direction2)) .unwrap(); assert_eq!(res.amount, 0); - assert_eq!(res.success, false); + assert!(!res.success); let res = internal_result .pairs .get(&(channel_outpoint2.clone(), rev_direction2)) .unwrap(); assert_eq!(res.amount, 0); - assert_eq!(res.success, false); + assert!(!res.success); let mut history = - PaymentHistory::new(gen_rand_fiber_public_key().into(), None, generate_store()); + PaymentHistory::new(gen_rand_fiber_public_key(), None, generate_store()); history.apply_internal_result(internal_result); assert!(matches!( @@ -336,7 +336,7 @@ fn test_history_internal_result_fail_range_pair() { fn test_history_apply_internal_result_fail_node() { let mut internal_result = InternalResult::default(); let mut history = - PaymentHistory::new(gen_rand_fiber_public_key().into(), None, generate_store()); + PaymentHistory::new(gen_rand_fiber_public_key(), None, generate_store()); let node1 = gen_rand_fiber_public_key(); let node2 = gen_rand_fiber_public_key(); let node3 = gen_rand_fiber_public_key(); @@ -433,7 +433,7 @@ fn test_history_apply_internal_result_fail_node() { fn test_history_fail_node_with_multiple_channels() { let mut internal_result = InternalResult::default(); let mut history = - PaymentHistory::new(gen_rand_fiber_public_key().into(), None, generate_store()); + PaymentHistory::new(gen_rand_fiber_public_key(), None, generate_store()); let node1 = gen_rand_fiber_public_key(); let node2 = gen_rand_fiber_public_key(); let node3 = gen_rand_fiber_public_key(); @@ -526,15 +526,9 @@ fn test_history_fail_node_with_multiple_channels() { }) )); - assert!(matches!( - history.get_result(&channel_outpoint1, rev_direction1), - None, - )); + assert!(history.get_result(&channel_outpoint1, rev_direction1).is_none()); - assert!(matches!( - history.get_result(&channel_outpoint2, rev_direction2), - None, - )); + assert!(history.get_result(&channel_outpoint2, rev_direction2).is_none()); assert!(matches!( history.get_result(&channel_outpoint3, direction1), @@ -576,7 +570,7 @@ fn test_history_fail_node_with_multiple_channels() { #[test] fn test_history_interal_success_fail() { let mut history = - PaymentHistory::new(gen_rand_fiber_public_key().into(), None, generate_store()); + PaymentHistory::new(gen_rand_fiber_public_key(), None, generate_store()); let from = gen_rand_fiber_public_key(); let target = gen_rand_fiber_public_key(); let channel_outpoint = OutPoint::default(); @@ -640,7 +634,7 @@ fn test_history_interal_success_fail() { #[test] fn test_history_interal_fuzz_assertion_crash() { let mut history = - PaymentHistory::new(gen_rand_fiber_public_key().into(), None, generate_store()); + PaymentHistory::new(gen_rand_fiber_public_key(), None, generate_store()); let from = gen_rand_fiber_public_key(); let target = gen_rand_fiber_public_key(); let channel_outpoint = OutPoint::default(); @@ -674,7 +668,7 @@ fn test_history_interal_fuzz_assertion_crash() { #[test] fn test_history_interal_fail_zero_after_succ() { let mut history = - PaymentHistory::new(gen_rand_fiber_public_key().into(), None, generate_store()); + PaymentHistory::new(gen_rand_fiber_public_key(), None, generate_store()); let from = gen_rand_fiber_public_key(); let target = gen_rand_fiber_public_key(); let channel_outpoint = OutPoint::default(); @@ -704,7 +698,7 @@ fn test_history_interal_fail_zero_after_succ() { #[test] fn test_history_interal_keep_valid_range() { let mut history = - PaymentHistory::new(gen_rand_fiber_public_key().into(), None, generate_store()); + PaymentHistory::new(gen_rand_fiber_public_key(), None, generate_store()); let from = gen_rand_fiber_public_key(); let target = gen_rand_fiber_public_key(); let channel_outpoint = OutPoint::default(); @@ -737,7 +731,7 @@ fn test_history_interal_keep_valid_range() { #[test] fn test_history_probability() { let mut history = - PaymentHistory::new(gen_rand_fiber_public_key().into(), None, generate_store()); + PaymentHistory::new(gen_rand_fiber_public_key(), None, generate_store()); let from = gen_rand_fiber_public_key(); let target = gen_rand_fiber_public_key(); let channel_outpoint = OutPoint::default(); @@ -827,7 +821,7 @@ fn test_history_probability() { #[test] fn test_history_direct_probability() { let mut history = - PaymentHistory::new(gen_rand_fiber_public_key().into(), None, generate_store()); + PaymentHistory::new(gen_rand_fiber_public_key(), None, generate_store()); let from = gen_rand_fiber_public_key(); let target = gen_rand_fiber_public_key(); let channel_outpoint = OutPoint::default(); @@ -888,7 +882,7 @@ fn test_history_direct_probability() { #[test] fn test_history_small_fail_amount_probability() { let mut history = - PaymentHistory::new(gen_rand_fiber_public_key().into(), None, generate_store()); + PaymentHistory::new(gen_rand_fiber_public_key(), None, generate_store()); let from = gen_rand_fiber_public_key(); let target = gen_rand_fiber_public_key(); let channel_outpoint = OutPoint::default(); @@ -913,7 +907,7 @@ fn test_history_small_fail_amount_probability() { #[test] fn test_history_channel_probability_range() { let mut history = - PaymentHistory::new(gen_rand_fiber_public_key().into(), None, generate_store()); + PaymentHistory::new(gen_rand_fiber_public_key(), None, generate_store()); let from = gen_rand_fiber_public_key(); let target = gen_rand_fiber_public_key(); let channel_outpoint = OutPoint::default(); @@ -954,7 +948,7 @@ fn test_history_channel_probability_range() { #[test] fn test_history_eval_probability_range() { let mut history = - PaymentHistory::new(gen_rand_fiber_public_key().into(), None, generate_store()); + PaymentHistory::new(gen_rand_fiber_public_key(), None, generate_store()); let from = gen_rand_fiber_public_key(); let target = gen_rand_fiber_public_key(); let channel_outpoint = OutPoint::default(); @@ -973,7 +967,7 @@ fn test_history_eval_probability_range() { history.add_result(channel_outpoint.clone(), direction, result); let prob1 = history.eval_probability(from, target, &channel_outpoint, 50000000, 100000000); - assert!(0.0 <= prob1 && prob1 < 0.001); + assert!((0.0..0.001).contains(&prob1)); let prob2 = history.eval_probability(from, target, &channel_outpoint, 50000000 - 10, 100000000); assert!(0.0 < prob2 && prob2 < 0.001); assert!(prob2 > prob1); @@ -1006,7 +1000,7 @@ fn test_history_eval_probability_range() { prev_prob = 0.0; let now = now_timestamp_as_millis_u64(); - for time in (60 * 1000..DEFAULT_BIMODAL_DECAY_TIME * 2).step_by(1 * 60 * 60 * 1000) { + for time in (60 * 1000..DEFAULT_BIMODAL_DECAY_TIME * 2).step_by(60 * 60 * 1000) { history.reset(); let result = TimedResult { success_time: now, @@ -1027,7 +1021,7 @@ fn test_history_eval_probability_range() { fn test_history_load_store() { let temp_path = TempDir::new("test-history-store"); let store = Store::new(temp_path).expect("created store failed"); - let mut history = PaymentHistory::new(gen_rand_fiber_public_key().into(), None, store.clone()); + let mut history = PaymentHistory::new(gen_rand_fiber_public_key(), None, store.clone()); let from = gen_rand_fiber_public_key(); let target = gen_rand_fiber_public_key(); let channel_outpoint = OutPoint::default(); @@ -1041,10 +1035,9 @@ fn test_history_load_store() { }; history.add_result(channel_outpoint.clone(), direction, result); - let result = history + let result = *history .get_result(&channel_outpoint, direction) - .unwrap() - .clone(); + .unwrap(); history.reset(); assert_eq!(history.get_result(&channel_outpoint, direction), None); history.load_from_store(); @@ -1071,7 +1064,7 @@ fn test_history_load_store() { fn test_history_can_send_with_time() { use crate::fiber::history::DEFAULT_BIMODAL_DECAY_TIME; - let history = PaymentHistory::new(gen_rand_fiber_public_key().into(), None, generate_store()); + let history = PaymentHistory::new(gen_rand_fiber_public_key(), None, generate_store()); let now = now_timestamp_as_millis_u64(); let res = history.can_send(100, now); assert_eq!(res, 100); @@ -1093,7 +1086,7 @@ fn test_history_can_send_with_time() { fn test_history_can_not_send_with_time() { use crate::fiber::history::DEFAULT_BIMODAL_DECAY_TIME; - let history = PaymentHistory::new(gen_rand_fiber_public_key().into(), None, generate_store()); + let history = PaymentHistory::new(gen_rand_fiber_public_key(), None, generate_store()); let now = now_timestamp_as_millis_u64(); let res = history.cannot_send(90, now, 100); assert_eq!(res, 90); diff --git a/src/fiber/tests/network.rs b/src/fiber/tests/network.rs index c3936a9a2..3c065c462 100644 --- a/src/fiber/tests/network.rs +++ b/src/fiber/tests/network.rs @@ -91,7 +91,7 @@ fn create_fake_channel_announcement_mesage( fn create_node_announcement_mesage_with_priv_key(priv_key: &Privkey) -> NodeAnnouncement { let node_name = "fake node"; let addresses = - vec!["/ip4/1.1.1.1/tcp/8346/p2p/QmaFDJb9CkMrXy7nhTWBY5y9mvuykre3EzzRsCJUAVXprZ"] + ["/ip4/1.1.1.1/tcp/8346/p2p/QmaFDJb9CkMrXy7nhTWBY5y9mvuykre3EzzRsCJUAVXprZ"] .iter() .map(|x| MultiAddr::from_str(x).expect("valid multiaddr")) .collect(); @@ -220,7 +220,7 @@ async fn test_sync_channel_announcement_on_startup() { .lock(ScriptBuilder::default().args(pubkey_hash.pack()).build()) .build(), ) - .output_data(vec![0u8; 8].pack()) + .output_data([0u8; 8].pack()) .build(); let outpoint = tx.output_pts()[0].clone(); let (node_announcement_1, node_announcement_2, channel_announcement) = @@ -684,7 +684,7 @@ fn test_announcement_message_serialize() { .lock(ScriptBuilder::default().args(pubkey_hash.pack()).build()) .build(), ) - .output_data(vec![0u8; 8].pack()) + .output_data([0u8; 8].pack()) .build(); let outpoint = tx.output_pts()[0].clone(); let (_, _, mut channel_announcement) = @@ -698,7 +698,7 @@ fn test_announcement_message_serialize() { let shutdown_info = ShutdownInfo { close_script: ScriptBuilder::default().build(), - fee_rate: 100 as u64, + fee_rate: 100_u64, signature: Some(PartialSignature::max()), }; let serialized = bincode::serialize(&shutdown_info).unwrap(); diff --git a/src/fiber/tests/payment.rs b/src/fiber/tests/payment.rs index 0e0a69292..06c04c01d 100644 --- a/src/fiber/tests/payment.rs +++ b/src/fiber/tests/payment.rs @@ -69,11 +69,11 @@ async fn test_send_payment_prefer_newer_channels() { .await; let [mut node_0, node_1] = nodes.try_into().expect("2 nodes"); let source_node = &mut node_0; - let target_pubkey = node_1.pubkey.clone(); + let target_pubkey = node_1.pubkey; let res = source_node .send_payment(SendPaymentCommand { - target_pubkey: Some(target_pubkey.clone()), + target_pubkey: Some(target_pubkey), amount: Some(10000000000), payment_hash: None, final_tlc_expiry_delta: None, @@ -128,11 +128,11 @@ async fn test_send_payment_prefer_channels_with_larger_balance() { .await; let [mut node_0, node_1] = nodes.try_into().expect("2 nodes"); let source_node = &mut node_0; - let target_pubkey = node_1.pubkey.clone(); + let target_pubkey = node_1.pubkey; let res = source_node .send_payment(SendPaymentCommand { - target_pubkey: Some(target_pubkey.clone()), + target_pubkey: Some(target_pubkey), amount: Some(5000000000), payment_hash: None, final_tlc_expiry_delta: None, @@ -279,11 +279,11 @@ async fn test_send_payment_over_private_channel() { tokio::time::sleep(tokio::time::Duration::from_secs(2)).await; let source_node = &mut node1; - let target_pubkey = node3.pubkey.clone(); + let target_pubkey = node3.pubkey; let res = source_node .send_payment(SendPaymentCommand { - target_pubkey: Some(target_pubkey.clone()), + target_pubkey: Some(target_pubkey), amount: Some(amount_to_send), payment_hash: None, final_tlc_expiry_delta: None, @@ -581,7 +581,7 @@ async fn test_send_payment_with_route_to_self_with_hop_hints() { // then the only valid route will be node0 -> node2 -> node1 -> node0 let res = node_0 .send_payment(SendPaymentCommand { - target_pubkey: Some(node_0.pubkey.clone()), + target_pubkey: Some(node_0.pubkey), amount: Some(60000000), payment_hash: None, final_tlc_expiry_delta: None, @@ -594,7 +594,7 @@ async fn test_send_payment_with_route_to_self_with_hop_hints() { udt_type_script: None, allow_self_payment: true, hop_hints: Some(vec![HopHint { - pubkey: node_0.pubkey.clone(), + pubkey: node_0.pubkey, channel_funding_tx: channel_0_funding_tx, inbound: true, }]), @@ -693,7 +693,7 @@ async fn test_send_payment_with_route_to_self_with_outbound_hop_hints() { // then the only valid route will be node0 -> node1 -> node2 -> node0 let res = node_0 .send_payment(SendPaymentCommand { - target_pubkey: Some(node_0.pubkey.clone()), + target_pubkey: Some(node_0.pubkey), amount: Some(60000000), payment_hash: None, final_tlc_expiry_delta: None, @@ -706,7 +706,7 @@ async fn test_send_payment_with_route_to_self_with_outbound_hop_hints() { udt_type_script: None, allow_self_payment: true, hop_hints: Some(vec![HopHint { - pubkey: node_0.pubkey.clone(), + pubkey: node_0.pubkey, channel_funding_tx: channel_0_funding_tx, inbound: false, }]), @@ -783,7 +783,7 @@ async fn test_send_payment_select_channel_with_hop_hints() { eprintln!("channel_3_funding_tx: {:?}", channel_3_funding_tx); let res = node_0 .send_payment(SendPaymentCommand { - target_pubkey: Some(node_3.pubkey.clone()), + target_pubkey: Some(node_3.pubkey), amount: Some(60000000), payment_hash: None, final_tlc_expiry_delta: None, @@ -797,7 +797,7 @@ async fn test_send_payment_select_channel_with_hop_hints() { allow_self_payment: true, // at node_1, we must use channel_3 to reach node_2 hop_hints: Some(vec![HopHint { - pubkey: node_2.pubkey.clone(), + pubkey: node_2.pubkey, channel_funding_tx: channel_3_funding_tx, inbound: true, }]), @@ -830,7 +830,7 @@ async fn test_send_payment_select_channel_with_hop_hints() { eprintln!("channel_2_funding_tx: {:?}", channel_2_funding_tx); let res = node_0 .send_payment(SendPaymentCommand { - target_pubkey: Some(node_3.pubkey.clone()), + target_pubkey: Some(node_3.pubkey), amount: Some(60000000), payment_hash: None, final_tlc_expiry_delta: None, @@ -844,7 +844,7 @@ async fn test_send_payment_select_channel_with_hop_hints() { allow_self_payment: true, // at node_1, we must use channel_2 to reach node_2 hop_hints: Some(vec![HopHint { - pubkey: node_1.pubkey.clone(), + pubkey: node_1.pubkey, channel_funding_tx: channel_2_funding_tx, inbound: false, }]), @@ -874,7 +874,7 @@ async fn test_send_payment_select_channel_with_hop_hints() { // if we specify a wrong funding_tx, the payment will fail let res = node_0 .send_payment(SendPaymentCommand { - target_pubkey: Some(node_3.pubkey.clone()), + target_pubkey: Some(node_3.pubkey), amount: Some(60000000), payment_hash: None, final_tlc_expiry_delta: None, @@ -888,7 +888,7 @@ async fn test_send_payment_select_channel_with_hop_hints() { allow_self_payment: true, // at node_1, we must use channel_3 to reach node_2 hop_hints: Some(vec![HopHint { - pubkey: node_2.pubkey.clone(), + pubkey: node_2.pubkey, channel_funding_tx: wrong_channel_hash, inbound: true, }]), @@ -929,7 +929,7 @@ async fn test_send_payment_two_nodes_with_hop_hints_and_multiple_channels() { eprintln!("channel_1_funding_tx: {:?}", channel_1_funding_tx); let res = node_0 .send_payment(SendPaymentCommand { - target_pubkey: Some(node_0.pubkey.clone()), + target_pubkey: Some(node_0.pubkey), amount: Some(60000000), payment_hash: None, final_tlc_expiry_delta: None, @@ -944,13 +944,13 @@ async fn test_send_payment_two_nodes_with_hop_hints_and_multiple_channels() { hop_hints: Some(vec![ // node1 - channel_1 -> node2 HopHint { - pubkey: node_0.pubkey.clone(), + pubkey: node_0.pubkey, channel_funding_tx: channel_1_funding_tx, inbound: false, }, // node2 - channel_3 -> node1 HopHint { - pubkey: node_0.pubkey.clone(), + pubkey: node_0.pubkey, channel_funding_tx: channel_3_funding_tx, inbound: true, }, @@ -1008,8 +1008,8 @@ async fn test_network_send_payment_randomly_send_each_other() { let node_a_old_balance = node_a.get_local_balance_from_channel(new_channel_id); let node_b_old_balance = node_b.get_local_balance_from_channel(new_channel_id); - let node_a_pubkey = node_a.pubkey.clone(); - let node_b_pubkey = node_b.pubkey.clone(); + let node_a_pubkey = node_a.pubkey; + let node_b_pubkey = node_b.pubkey; let mut node_a_sent = 0; let mut node_b_sent = 0; @@ -1022,9 +1022,9 @@ async fn test_network_send_payment_randomly_send_each_other() { let amount = rand::random::() % 10000; eprintln!("generated ampunt: {}", amount); let (source, target) = if rand_num == 0 { - (&node_a.network_actor, node_b_pubkey.clone()) + (&node_a.network_actor, node_b_pubkey) } else { - (&node_b.network_actor, node_a_pubkey.clone()) + (&node_b.network_actor, node_a_pubkey) }; let message = |rpc_reply| -> NetworkActorMessage { NetworkActorMessage::Command(NetworkActorCommand::SendPayment( @@ -1203,14 +1203,14 @@ async fn test_network_three_nodes_send_each_other() { node_b_old_balance_channel_2, node_b_old_balance_channel_3 ); - let node_a_pubkey = node_a.pubkey.clone(); - let node_c_pubkey = node_c.pubkey.clone(); + let node_a_pubkey = node_a.pubkey; + let node_c_pubkey = node_c.pubkey; let amount_a_to_c = 60000; let message = |rpc_reply| -> NetworkActorMessage { NetworkActorMessage::Command(NetworkActorCommand::SendPayment( SendPaymentCommand { - target_pubkey: Some(node_c_pubkey.clone()), + target_pubkey: Some(node_c_pubkey), amount: Some(amount_a_to_c), payment_hash: None, final_tlc_expiry_delta: None, @@ -1240,7 +1240,7 @@ async fn test_network_three_nodes_send_each_other() { let message = |rpc_reply| -> NetworkActorMessage { NetworkActorMessage::Command(NetworkActorCommand::SendPayment( SendPaymentCommand { - target_pubkey: Some(node_a_pubkey.clone()), + target_pubkey: Some(node_a_pubkey), amount: Some(amount_c_to_a), payment_hash: None, final_tlc_expiry_delta: None, diff --git a/src/fiber/tests/test_utils.rs b/src/fiber/tests/test_utils.rs index 56b7379da..8596dcbe3 100644 --- a/src/fiber/tests/test_utils.rs +++ b/src/fiber/tests/test_utils.rs @@ -60,7 +60,7 @@ use crate::{ static RETAIN_VAR: &str = "TEST_TEMP_RETAIN"; pub(crate) const MIN_RESERVED_CKB: u128 = 4200000000; -pub(crate) const HUGE_CKB_AMOUNT: u128 = MIN_RESERVED_CKB + 1000000000000 as u128; +pub(crate) const HUGE_CKB_AMOUNT: u128 = MIN_RESERVED_CKB + 1000000000000_u128; #[derive(Debug)] pub struct TempDir(ManuallyDrop); @@ -157,7 +157,7 @@ pub fn get_fiber_config>(base_dir: P, node_name: Option<&str>) -> // Mock function to create a dummy EcdsaSignature pub fn mock_ecdsa_signature() -> EcdsaSignature { let secp = Secp256k1::new(); - let mut rng = OsRng::default(); + let mut rng = OsRng; let (secret_key, _public_key) = secp.generate_keypair(&mut rng); let message = Message::from_digest_slice(&[0u8; 32]).expect("32 bytes"); let signature = secp.sign_ecdsa(&message, &secret_key); @@ -209,6 +209,12 @@ pub struct NetworkNodeConfigBuilder { fiber_config_updater: Option>, } +impl Default for NetworkNodeConfigBuilder { + fn default() -> Self { + Self::new() + } +} + impl NetworkNodeConfigBuilder { pub fn new() -> Self { Self { @@ -568,7 +574,7 @@ impl NetworkNode { dry_run: bool, ) -> std::result::Result { self.send_payment(SendPaymentCommand { - target_pubkey: Some(recipient.pubkey.clone()), + target_pubkey: Some(recipient.pubkey), amount: Some(amount), payment_hash: None, final_tlc_expiry_delta: None, @@ -591,7 +597,7 @@ impl NetworkNode { amount: u128, dry_run: bool, ) -> std::result::Result { - let pubkey = self.pubkey.clone(); + let pubkey = self.pubkey; self.send_payment(SendPaymentCommand { target_pubkey: Some(pubkey), amount: Some(amount), @@ -697,10 +703,10 @@ impl NetworkNode { let message = |rpc_reply| NetworkActorMessage::Command(NetworkActorCommand::NodeInfo((), rpc_reply)); eprintln!("query node_info ..."); - let res = call!(self.network_actor, message) + + call!(self.network_actor, message) .expect("node_a alive") - .unwrap(); - res + .unwrap() } pub async fn update_channel_actor_state( @@ -708,7 +714,7 @@ impl NetworkNode { state: ChannelActorState, reload_params: Option, ) { - let channel_id = state.id.clone(); + let channel_id = state.id; self.store.insert_channel_actor_state(state); self.network_actor .send_message(NetworkActorMessage::Command( @@ -804,7 +810,7 @@ impl NetworkNode { let network_graph = Arc::new(TokioRwLock::new(NetworkGraph::new( store.clone(), - public_key.clone(), + public_key, true, ))); @@ -856,10 +862,10 @@ impl NetworkNode { network_actor, network_graph, chain_actor, - private_key: secret_key.into(), + private_key: secret_key, peer_id, event_emitter: event_receiver, - pubkey: public_key.into(), + pubkey: public_key, } } @@ -1081,7 +1087,7 @@ impl NetworkNode { F: FnOnce(&NetworkGraph) -> T, { let graph = self.get_network_graph().read().await; - f(&*graph) + f(&graph) } pub async fn with_network_graph_mut(&self, f: F) -> T @@ -1093,7 +1099,7 @@ impl NetworkNode { } pub async fn get_network_graph_nodes(&self) -> Vec { - self.with_network_graph(|graph| graph.nodes().into_iter().cloned().collect()) + self.with_network_graph(|graph| graph.nodes().cloned().collect()) .await } @@ -1103,7 +1109,7 @@ impl NetworkNode { } pub async fn get_network_graph_channels(&self) -> Vec { - self.with_network_graph(|graph| graph.channels().into_iter().cloned().collect()) + self.with_network_graph(|graph| graph.channels().cloned().collect()) .await } @@ -1112,7 +1118,7 @@ impl NetworkNode { tracing::debug!("Getting channel info for {:?}", channel_id); tracing::debug!( "Channels: {:?}", - graph.channels().into_iter().collect::>() + graph.channels().collect::>() ); graph.get_channel(channel_id).cloned() }) diff --git a/src/fiber/tests/tlc_op.rs b/src/fiber/tests/tlc_op.rs index 4bfa9b7ca..c6a9b1b29 100644 --- a/src/fiber/tests/tlc_op.rs +++ b/src/fiber/tests/tlc_op.rs @@ -372,7 +372,7 @@ async fn test_tlc_actor() { expiry: now_timestamp_as_millis_u64() + 1000, hash_algorithm: HashAlgorithm::Sha256, onion_packet: None, - shared_secret: NO_SHARED_SECRET.clone(), + shared_secret: NO_SHARED_SECRET, previous_tlc: None, }, )) @@ -388,7 +388,7 @@ async fn test_tlc_actor() { expiry: now_timestamp_as_millis_u64() + 1000, hash_algorithm: HashAlgorithm::Sha256, onion_packet: None, - shared_secret: NO_SHARED_SECRET.clone(), + shared_secret: NO_SHARED_SECRET, previous_tlc: None, }, )) @@ -404,7 +404,7 @@ async fn test_tlc_actor() { expiry: now_timestamp_as_millis_u64() + 1000, hash_algorithm: HashAlgorithm::Sha256, onion_packet: None, - shared_secret: NO_SHARED_SECRET.clone(), + shared_secret: NO_SHARED_SECRET, previous_tlc: None, }, )) @@ -420,7 +420,7 @@ async fn test_tlc_actor() { expiry: now_timestamp_as_millis_u64() + 1000, hash_algorithm: HashAlgorithm::Sha256, onion_packet: None, - shared_secret: NO_SHARED_SECRET.clone(), + shared_secret: NO_SHARED_SECRET, previous_tlc: None, }, )) @@ -462,7 +462,7 @@ fn test_tlc_state_v2() { expiry: now_timestamp_as_millis_u64() + 1000, hash_algorithm: HashAlgorithm::Sha256, onion_packet: None, - shared_secret: NO_SHARED_SECRET.clone(), + shared_secret: NO_SHARED_SECRET, tlc_id: TLCId::Offered(0), created_at: CommitmentNumbers::default(), removed_reason: None, @@ -476,7 +476,7 @@ fn test_tlc_state_v2() { expiry: now_timestamp_as_millis_u64() + 2000, hash_algorithm: HashAlgorithm::Sha256, onion_packet: None, - shared_secret: NO_SHARED_SECRET.clone(), + shared_secret: NO_SHARED_SECRET, tlc_id: TLCId::Offered(1), created_at: CommitmentNumbers::default(), removed_reason: None, diff --git a/src/fiber/tests/types.rs b/src/fiber/tests/types.rs index a57fce232..53d4e0ec7 100644 --- a/src/fiber/tests/types.rs +++ b/src/fiber/tests/types.rs @@ -67,8 +67,8 @@ fn test_cursor_timestamp() { let node_id = gen_rand_fiber_public_key(); // 255 is larger than 256 in little endian. assert!( - Cursor::new(255, BroadcastMessageID::NodeAnnouncement(node_id.clone())) - < Cursor::new(256, BroadcastMessageID::NodeAnnouncement(node_id.clone())) + Cursor::new(255, BroadcastMessageID::NodeAnnouncement(node_id)) + < Cursor::new(256, BroadcastMessageID::NodeAnnouncement(node_id)) ); } @@ -80,7 +80,7 @@ fn test_cursor_types() { Cursor::new( 0, BroadcastMessageID::ChannelAnnouncement(channel_outpoint.clone()) - ) < Cursor::new(0, BroadcastMessageID::NodeAnnouncement(node_id.clone())) + ) < Cursor::new(0, BroadcastMessageID::NodeAnnouncement(node_id)) ); assert!( Cursor::new( @@ -95,7 +95,7 @@ fn test_cursor_types() { Cursor::new( 0, BroadcastMessageID::ChannelUpdate(channel_outpoint.clone()) - ) < Cursor::new(0, BroadcastMessageID::NodeAnnouncement(node_id.clone())) + ) < Cursor::new(0, BroadcastMessageID::NodeAnnouncement(node_id)) ); } @@ -118,14 +118,14 @@ fn test_add_tlc_serialization() { #[test] fn test_peeled_onion_packet() { let secp = Secp256k1::new(); - let keys: Vec = std::iter::repeat_with(|| gen_rand_fiber_private_key()) + let keys: Vec = std::iter::repeat_with(gen_rand_fiber_private_key) .take(3) .collect(); let hops_infos = vec![ PaymentHopData { amount: 2, expiry: 3, - next_hop: Some(keys[1].pubkey().into()), + next_hop: Some(keys[1].pubkey()), funding_tx_hash: Hash256::default(), hash_algorithm: HashAlgorithm::Sha256, payment_preimage: None, @@ -133,7 +133,7 @@ fn test_peeled_onion_packet() { PaymentHopData { amount: 5, expiry: 6, - next_hop: Some(keys[2].pubkey().into()), + next_hop: Some(keys[2].pubkey()), funding_tx_hash: Hash256::default(), hash_algorithm: HashAlgorithm::Sha256, payment_preimage: None, @@ -212,7 +212,7 @@ fn test_tlc_err_packet_encryption() { let session_key = SecretKey::from_slice(&[0x41; 32]).expect("32 bytes, within curve order"); let hops_ss: Vec<[u8; 32]> = - OnionSharedSecretIter::new(hops_path.iter().map(|k| &k.0), session_key.clone(), &secp) + OnionSharedSecretIter::new(hops_path.iter().map(|k| &k.0), session_key, &secp) .collect(); let tlc_fail_detail = TlcErr::new(TlcErrorCode::InvalidOnionVersion); diff --git a/src/fiber/types.rs b/src/fiber/types.rs index 010b8932e..4db631236 100644 --- a/src/fiber/types.rs +++ b/src/fiber/types.rs @@ -1108,7 +1108,7 @@ impl TryFrom for AddTlc { fn try_from(add_tlc: molecule_fiber::AddTlc) -> Result { let onion_packet_bytes: Vec = add_tlc.onion_packet().unpack(); let onion_packet = - (onion_packet_bytes.len() > 0).then(|| PaymentOnionPacket::new(onion_packet_bytes)); + (!onion_packet_bytes.is_empty()).then(|| PaymentOnionPacket::new(onion_packet_bytes)); Ok(AddTlc { onion_packet, channel_id: add_tlc.channel_id().into(), @@ -1219,14 +1219,14 @@ impl Display for TlcErr { impl TlcErr { pub fn new(error_code: TlcErrorCode) -> Self { TlcErr { - error_code: error_code, + error_code, extra_data: None, } } pub fn new_node_fail(error_code: TlcErrorCode, node_id: Pubkey) -> Self { TlcErr { - error_code: error_code.into(), + error_code, extra_data: Some(TlcErrData::NodeFailed { node_id }), } } @@ -1238,7 +1238,7 @@ impl TlcErr { channel_update: Option, ) -> Self { TlcErr { - error_code: error_code.into(), + error_code, extra_data: Some(TlcErrData::ChannelFailed { node_id, channel_outpoint, @@ -1269,7 +1269,7 @@ impl TlcErr { } pub fn error_code_as_str(&self) -> String { - let error_code: TlcErrorCode = self.error_code.into(); + let error_code: TlcErrorCode = self.error_code; error_code.as_ref().to_string() } @@ -1304,7 +1304,7 @@ impl TryFrom for molecule_fiber::TlcErrData { channel_update, node_id, } => Ok(molecule_fiber::ChannelFailed::new_builder() - .channel_outpoint(channel_outpoint.into()) + .channel_outpoint(channel_outpoint) .channel_update( ChannelUpdateOpt::new_builder() .set(channel_update.map(|x| x.into())) @@ -1328,7 +1328,7 @@ impl TryFrom for TlcErrData { match tlc_err_data.to_enum() { molecule_fiber::TlcErrDataUnion::ChannelFailed(channel_failed) => { Ok(TlcErrData::ChannelFailed { - channel_outpoint: channel_failed.channel_outpoint().into(), + channel_outpoint: channel_failed.channel_outpoint(), channel_update: channel_failed .channel_update() .to_opt() @@ -1400,7 +1400,7 @@ impl TlcErrPacket { let onion_packet = if shared_secret != &NO_SHARED_SECRET { OnionErrorPacket::create(shared_secret, payload) } else { - OnionErrorPacket::concat(NO_ERROR_PACKET_HMAC.clone(), payload) + OnionErrorPacket::concat(NO_ERROR_PACKET_HMAC, payload) } .into_bytes(); TlcErrPacket { onion_packet } @@ -1433,7 +1433,7 @@ impl TlcErrPacket { } let hops_public_keys: Vec = - hops_public_keys.iter().map(|k| k.0.clone()).collect(); + hops_public_keys.iter().map(|k| k.0).collect(); let session_key = SecretKey::from_slice(session_key).inspect_err(|err| error!(target: "fnn::fiber::types::TlcErrPacket", "decode session_key error={} key={}", err, hex::encode(session_key)) ).ok()?; @@ -3355,7 +3355,7 @@ impl TryFrom for QueryBroadcastMe missing_queries: query_broadcast_messages_result .missing_queries() .into_iter() - .map(|x| u16::from(x)) + .map(u16::from) .collect(), }) } @@ -3562,7 +3562,7 @@ macro_rules! impl_traits { impl_traits!(FiberMessage); pub(crate) fn deterministically_hash(v: &T) -> [u8; 32] { - ckb_hash::blake2b_256(v.as_slice()).into() + ckb_hash::blake2b_256(v.as_slice()) } #[serde_as] @@ -3590,7 +3590,7 @@ impl HopData for PaymentHopData { const PACKET_DATA_LEN: usize = 6500; fn next_hop(&self) -> Option { - self.next_hop.clone() + self.next_hop } fn assoc_data(&self) -> Option> { @@ -3783,7 +3783,7 @@ impl PeeledOnionPacket { current, next, // Use all zeros for the sender - shared_secret: NO_SHARED_SECRET.clone(), + shared_secret: NO_SHARED_SECRET, }) } @@ -3825,7 +3825,7 @@ impl PeeledOnionPacket { .ok_or_else(|| Error::OnionPacket(OnionPacketError::InvalidHopData))?; // Ensure backward compatibility - let mut shared_secret = NO_SHARED_SECRET.clone(); + let mut shared_secret = NO_SHARED_SECRET; if data.len() >= read_bytes + 32 && data.len() != read_bytes + T::PACKET_DATA_LEN { shared_secret.copy_from_slice(&data[read_bytes..read_bytes + 32]); read_bytes += 32; diff --git a/src/invoice/tests/invoice_impl.rs b/src/invoice/tests/invoice_impl.rs index 5885ac5fc..e6ec99c4a 100644 --- a/src/invoice/tests/invoice_impl.rs +++ b/src/invoice/tests/invoice_impl.rs @@ -199,7 +199,7 @@ fn test_invoice_builder() { assert_eq!(invoice.amount, Some(1280)); assert_eq!(invoice.payment_hash(), &gen_payment_hash); assert_eq!(invoice.data.attrs.len(), 7); - assert_eq!(invoice.check_signature().is_ok(), true); + assert!(invoice.check_signature().is_ok()); } #[test] @@ -454,7 +454,7 @@ fn test_invoice_check_expired() { .build_with_sign(|hash| Secp256k1::new().sign_ecdsa_recoverable(hash, &private_key)) .unwrap(); - assert_eq!(invoice.is_expired(), false); + assert!(!invoice.is_expired()); std::thread::sleep(Duration::from_secs(2)); - assert_eq!(invoice.is_expired(), true); + assert!(invoice.is_expired()); } diff --git a/src/rpc/channel.rs b/src/rpc/channel.rs index 1a1024f5f..e1c20a7d6 100644 --- a/src/rpc/channel.rs +++ b/src/rpc/channel.rs @@ -348,7 +348,6 @@ where shutdown_script: params.shutdown_script.clone().map(|s| s.into()), commitment_delay_epoch: params .commitment_delay_epoch - .clone() .map(|e| EpochNumberWithFractionCore::from_full_value(e.value())), funding_udt_type_script: params .funding_udt_type_script diff --git a/src/rpc/dev.rs b/src/rpc/dev.rs index 3584e0505..172cc6c28 100644 --- a/src/rpc/dev.rs +++ b/src/rpc/dev.rs @@ -175,7 +175,7 @@ impl DevRpcServer for DevRpcServerImpl { expiry: params.expiry, hash_algorithm: params.hash_algorithm.unwrap_or_default(), onion_packet: None, - shared_secret: NO_SHARED_SECRET.clone(), + shared_secret: NO_SHARED_SECRET, previous_tlc: None, }, rpc_reply, @@ -191,7 +191,7 @@ impl DevRpcServer for DevRpcServerImpl { async fn remove_tlc(&self, params: RemoveTlcParams) -> Result<(), ErrorObjectOwned> { let err_code = match ¶ms.reason { RemoveTlcReason::RemoveTlcFail { error_code } => { - let Ok(err) = TlcErrorCode::from_str(&error_code) else { + let Ok(err) = TlcErrorCode::from_str(error_code) else { return log_and_error!(params, format!("invalid error code: {}", error_code)); }; Some(err) diff --git a/src/rpc/invoice.rs b/src/rpc/invoice.rs index ed6f72423..aa3f84dfb 100644 --- a/src/rpc/invoice.rs +++ b/src/rpc/invoice.rs @@ -141,7 +141,7 @@ impl InvoiceRpcServerImpl { }); Self { store, - keypair: config.as_ref().map(|(kp, _)| kp.clone()), + keypair: config.as_ref().map(|(kp, _)| *kp), currency: config.as_ref().map(|(_, currency)| *currency), } } @@ -199,9 +199,9 @@ where }; let invoice = if let Some((public_key, secret_key)) = &self.keypair { - invoice_builder = invoice_builder.payee_pub_key(public_key.clone()); + invoice_builder = invoice_builder.payee_pub_key(*public_key); invoice_builder - .build_with_sign(|hash| Secp256k1::new().sign_ecdsa_recoverable(hash, &secret_key)) + .build_with_sign(|hash| Secp256k1::new().sign_ecdsa_recoverable(hash, secret_key)) } else { invoice_builder.build() }; diff --git a/src/rpc/payment.rs b/src/rpc/payment.rs index 2bc504c25..4fcc957d6 100644 --- a/src/rpc/payment.rs +++ b/src/rpc/payment.rs @@ -198,13 +198,13 @@ where }; handle_actor_call!(self.actor, message, params).map(|response| GetPaymentCommandResult { payment_hash: response.payment_hash, - status: response.status.into(), + status: response.status, created_at: response.created_at, last_updated_at: response.last_updated_at, failed_error: response.failed_error, fee: response.fee, #[cfg(debug_assertions)] - router: response.router.into(), + router: response.router, }) } @@ -220,13 +220,13 @@ where }; handle_actor_call!(self.actor, message, params).map(|response| GetPaymentCommandResult { payment_hash: response.payment_hash, - status: response.status.into(), + status: response.status, last_updated_at: response.last_updated_at, created_at: response.created_at, failed_error: response.failed_error, fee: response.fee, #[cfg(debug_assertions)] - router: response.router.into(), + router: response.router, }) } } diff --git a/src/store/migration.rs b/src/store/migration.rs index 55692cf5b..0812d1b28 100644 --- a/src/store/migration.rs +++ b/src/store/migration.rs @@ -178,6 +178,12 @@ pub struct DefaultMigration { version: String, } +impl Default for DefaultMigration { + fn default() -> Self { + Self::new() + } +} + impl DefaultMigration { pub fn new() -> Self { Self { diff --git a/src/store/store.rs b/src/store/store.rs index 5b1e552e2..d0962d1d0 100644 --- a/src/store/store.rs +++ b/src/store/store.rs @@ -470,8 +470,7 @@ impl NetworkGraphStateStore for Store { let iter = self.prefix_iterator(&prefix); iter.map(|(key, value)| { let channel_outpoint: OutPoint = OutPoint::from_slice(&key[1..=36]) - .expect("deserialize OutPoint should be OK") - .into(); + .expect("deserialize OutPoint should be OK"); let direction = deserialize_from(&key[37..], "Direction"); let result = deserialize_from(value.as_ref(), "TimedResult"); (channel_outpoint, direction, result) @@ -531,7 +530,7 @@ impl GossipMessageStore for Store { fn get_latest_channel_announcement_timestamp(&self, outpoint: &OutPoint) -> Option { self.get( - &[ + [ [BROADCAST_MESSAGE_TIMESTAMP_PREFIX].as_slice(), BroadcastMessageID::ChannelAnnouncement(outpoint.clone()) .to_bytes() @@ -555,7 +554,7 @@ impl GossipMessageStore for Store { is_node1: bool, ) -> Option { self.get( - &[ + [ [BROADCAST_MESSAGE_TIMESTAMP_PREFIX].as_slice(), BroadcastMessageID::ChannelUpdate(outpoint.clone()) .to_bytes() @@ -579,9 +578,9 @@ impl GossipMessageStore for Store { pk: &crate::fiber::types::Pubkey, ) -> Option { self.get( - &[ + [ [BROADCAST_MESSAGE_TIMESTAMP_PREFIX].as_slice(), - BroadcastMessageID::NodeAnnouncement(pk.clone()) + BroadcastMessageID::NodeAnnouncement(*pk) .to_bytes() .as_slice(), ] @@ -676,7 +675,7 @@ impl GossipMessageStore for Store { node_announcement ); let mut batch = self.batch(); - let message_id = BroadcastMessageID::NodeAnnouncement(node_announcement.node_id.clone()); + let message_id = BroadcastMessageID::NodeAnnouncement(node_announcement.node_id); if let Some(old_timestamp) = self.get_latest_node_announcement_timestamp(&node_announcement.node_id) @@ -698,7 +697,7 @@ impl GossipMessageStore for Store { ); } batch.put_kv(KeyValue::BroadcastMessageTimestamp( - BroadcastMessageID::NodeAnnouncement(node_announcement.node_id.clone()), + BroadcastMessageID::NodeAnnouncement(node_announcement.node_id), node_announcement.timestamp, )); diff --git a/src/store/tests/store.rs b/src/store/tests/store.rs index 2e57daf9b..3d9007cc3 100644 --- a/src/store/tests/store.rs +++ b/src/store/tests/store.rs @@ -391,12 +391,12 @@ fn test_channel_actor_state_store() { let get_state = store.get_channel_actor_state(&state.id); assert!(get_state.is_some()); - assert_eq!(get_state.unwrap().is_tlc_forwarding_enabled(), false); + assert!(!get_state.unwrap().is_tlc_forwarding_enabled()); let remote_peer_id = state.get_remote_peer_id(); assert_eq!( store.get_channel_ids_by_peer(&remote_peer_id), - vec![state.id.clone()] + vec![state.id] ); let channel_point = state.must_get_funding_transaction_outpoint(); assert!(store @@ -538,7 +538,7 @@ fn test_store_payment_history() { }; let channel_outpoint = OutPoint::default(); let direction = Direction::Forward; - store.insert_payment_history_result(channel_outpoint.clone(), direction, result.clone()); + store.insert_payment_history_result(channel_outpoint.clone(), direction, result); assert_eq!( store.get_payment_history_results(), vec![(channel_outpoint.clone(), direction, result)] @@ -558,7 +558,7 @@ fn test_store_payment_history() { success_amount: 5, }; let direction_2 = Direction::Backward; - store.insert_payment_history_result(channel_outpoint.clone(), direction_2, result_2.clone()); + store.insert_payment_history_result(channel_outpoint.clone(), direction_2, result_2); let mut r1 = store.get_payment_history_results(); sort_results(&mut r1); let mut r2: Vec<(OutPoint, Direction, TimedResult)> = vec![ @@ -580,7 +580,7 @@ fn test_store_payment_history() { success_amount: 6, }; - store.insert_payment_history_result(outpoint_3.clone(), direction_3, result_3.clone()); + store.insert_payment_history_result(outpoint_3.clone(), direction_3, result_3); let mut r1 = store.get_payment_history_results(); sort_results(&mut r1); From 55c5ab87af81c7fe812f2c15ef46ca49705d02f2 Mon Sep 17 00:00:00 2001 From: yukang Date: Mon, 27 Jan 2025 12:43:08 +0800 Subject: [PATCH 2/4] fix clippy manually --- Makefile | 2 +- src/ckb/contracts.rs | 2 +- src/ckb/tests/test_utils.rs | 5 +- src/fiber/channel.rs | 95 +++++++++++++++++------------------ src/fiber/config.rs | 9 ++-- src/fiber/gossip.rs | 34 +++++-------- src/fiber/graph.rs | 13 ++--- src/fiber/history.rs | 13 ++--- src/fiber/key.rs | 1 + src/fiber/network.rs | 2 +- src/fiber/tests/channel.rs | 6 +-- src/fiber/tests/gossip.rs | 16 ++---- src/fiber/tests/graph.rs | 10 ++-- src/fiber/tests/network.rs | 11 ++-- src/fiber/tests/test_utils.rs | 17 ++++--- src/fiber/tests/tlc_op.rs | 15 +++--- src/fiber/tests/types.rs | 4 +- src/fiber/types.rs | 21 ++++---- src/invoice/invoice_impl.rs | 27 +++++----- src/rpc/mod.rs | 2 + src/store/store.rs | 6 +-- src/store/tests/store.rs | 6 +-- src/tests/mod.rs | 2 +- 23 files changed, 146 insertions(+), 173 deletions(-) diff --git a/Makefile b/Makefile index 2613c462c..3846c691a 100644 --- a/Makefile +++ b/Makefile @@ -11,7 +11,7 @@ test: .PHONY: clippy clippy: - cargo clippy --all --all-targets --all-features + cargo clippy --all --all-targets --all-features -- -D warnings -A clippy::module-inception .PHONY: bless bless: diff --git a/src/ckb/contracts.rs b/src/ckb/contracts.rs index 38cf48a05..b9f7880f5 100644 --- a/src/ckb/contracts.rs +++ b/src/ckb/contracts.rs @@ -249,7 +249,7 @@ fn get_contracts_context() -> &'static ContractsContext { } #[cfg(test)] -fn get_contracts_context<'a>() -> ContractsContext { +fn get_contracts_context() -> ContractsContext { super::tests::test_utils::MOCK_CONTEXT .read() .expect("read mock context") diff --git a/src/ckb/tests/test_utils.rs b/src/ckb/tests/test_utils.rs index 214dba802..34a448357 100644 --- a/src/ckb/tests/test_utils.rs +++ b/src/ckb/tests/test_utils.rs @@ -114,7 +114,8 @@ impl MockContext { script_cell_deps .get(&Contract::CkbAuth) .unwrap() - .clone().first() + .clone() + .first() .unwrap() .clone(), ] @@ -172,7 +173,7 @@ impl Actor for TraceTxReplier { myself: ActorRef, (notifier, timeout, reply_port): Self::Arguments, ) -> Result { - let _ = myself.send_after(timeout, TraceTxResult::Timeout); + myself.send_after(timeout, TraceTxResult::Timeout); let hash = self.tx_hash.clone(); notifier.subscribe(myself, move |notification| { if notification.0 == hash { diff --git a/src/fiber/channel.rs b/src/fiber/channel.rs index 3c6b61521..e2a532727 100644 --- a/src/fiber/channel.rs +++ b/src/fiber/channel.rs @@ -73,7 +73,6 @@ use std::{ fmt::{self, Debug}, sync::Arc, time::{SystemTime, UNIX_EPOCH}, - u128, }; use super::types::{ChannelUpdateChannelFlags, ChannelUpdateMessageFlags, UpdateTlcInfo}; @@ -651,7 +650,7 @@ where // we expect `ChannelReady` will be both OK for tlc forwarding, // so here are the unreachable point in normal workflow, // set `TemporaryNodeFailure` for general temporary failure of the processing node here - assert!(false, "unreachable point in normal workflow"); + debug_assert!(false, "unreachable point in normal workflow"); TlcErrorCode::TemporaryNodeFailure } } @@ -944,11 +943,14 @@ where assert!(state.get_received_tlc(add_tlc.tlc_id).is_some()); - OptionFuture::from(add_tlc.onion_packet.clone().map(|onion_packet| { - self.peel_onion_packet(onion_packet, add_tlc.payment_hash) - })) - .await - .transpose() + OptionFuture::from( + add_tlc + .onion_packet + .clone() + .map(|onion_packet| self.peel_onion_packet(onion_packet, add_tlc.payment_hash)), + ) + .await + .transpose() } async fn apply_add_tlc_operation_with_peeled_onion_packet( @@ -1009,37 +1011,34 @@ where } else { return Err(ProcessingChannelError::FinalIncorrectPaymentHash); } - } else { - if state.is_public() && state.is_tlc_forwarding_enabled() { - if add_tlc.expiry - < peeled_onion_packet.current.expiry + state.local_tlc_info.tlc_expiry_delta - { - return Err(ProcessingChannelError::IncorrectTlcExpiry); - } + } else if state.is_public() && state.is_tlc_forwarding_enabled() { + if add_tlc.expiry + < peeled_onion_packet.current.expiry + state.local_tlc_info.tlc_expiry_delta + { + return Err(ProcessingChannelError::IncorrectTlcExpiry); + } - assert!(received_amount >= forward_amount); + assert!(received_amount >= forward_amount); - // Next forwarding channel will get the forward_fee and check if it's enough. - let forward_fee = received_amount.saturating_sub(forward_amount); + // Next forwarding channel will get the forward_fee and check if it's enough. + let forward_fee = received_amount.saturating_sub(forward_amount); - // if this is not the last hop, forward TLC to next hop - self.register_retryable_forward_tlc( - myself, - state, - add_tlc.tlc_id, - add_tlc.payment_hash, - peeled_onion_packet.clone(), - forward_fee, - ) - .await; - } else { - // if we don't have public channel info, we can not forward the TLC - // this may happended some malicious sender build a invalid onion router - return Err(ProcessingChannelError::InvalidState( - "Received AddTlc message, but the channel is not public or disabled" - .to_string(), - )); - } + // if this is not the last hop, forward TLC to next hop + self.register_retryable_forward_tlc( + myself, + state, + add_tlc.tlc_id, + add_tlc.payment_hash, + peeled_onion_packet.clone(), + forward_fee, + ) + .await; + } else { + // if we don't have public channel info, we can not forward the TLC + // this may happended some malicious sender build a invalid onion router + return Err(ProcessingChannelError::InvalidState( + "Received AddTlc message, but the channel is not public or disabled".to_string(), + )); } Ok(()) } @@ -2667,15 +2666,9 @@ impl PendingTlcs { .iter() .filter(|tlc| { if tlc.is_offered() { - match tlc.outbound_status() { - OutboundTlcStatus::Committed => true, - _ => false, - } + matches!(tlc.outbound_status(), OutboundTlcStatus::Committed) } else { - match tlc.inbound_status() { - InboundTlcStatus::Committed => true, - _ => false, - } + matches!(tlc.inbound_status(), InboundTlcStatus::Committed) } }) .cloned() @@ -3557,7 +3550,7 @@ impl ChannelActorState { } else { (self.remote_pubkey, self.local_pubkey) }; - + ChannelAnnouncement::new_unsigned( &node1_id, &node2_id, @@ -3771,7 +3764,10 @@ impl ChannelActorState { if let Some(x) = self .public_channel_info .as_ref() - .and_then(|state| state.channel_update.clone()) { return Some(x) }; + .and_then(|state| state.channel_update.clone()) + { + return Some(x); + }; Some(self.generate_channel_update(network).await) } @@ -3802,7 +3798,7 @@ impl ChannelActorState { )) } - pub fn new_inbound_channel<'a>( + pub fn new_inbound_channel( temp_channel_id: Hash256, public_channel_info: Option, local_value: u128, @@ -4286,7 +4282,6 @@ impl ChannelActorState { // Get the total liquid capacity of the channel, which will exclude the reserved ckb amount. // This is the capacity used for gossiping channel information. pub(crate) fn get_liquid_capacity(&self) -> u128 { - if self.funding_udt_type_script.is_some() { self.get_total_udt_amount() } else { @@ -4763,14 +4758,16 @@ impl ChannelActorState { fn get_active_received_tlcs(&self, for_remote: bool) -> Vec { self.tlc_state .commitment_signed_tlcs(for_remote) - .filter(|tlc| tlc.is_received()).cloned() + .filter(|tlc| tlc.is_received()) + .cloned() .collect() } fn get_active_offered_tlcs(&self, for_remote: bool) -> Vec { self.tlc_state .commitment_signed_tlcs(for_remote) - .filter(|tlc| tlc.is_offered()).cloned() + .filter(|tlc| tlc.is_offered()) + .cloned() .collect() } diff --git a/src/fiber/config.rs b/src/fiber/config.rs index f93118b8f..f85cc058c 100644 --- a/src/fiber/config.rs +++ b/src/fiber/config.rs @@ -300,7 +300,7 @@ impl AnnouncedNodeName { Ok(Self(bytes)) } - pub fn from_str(value: &str) -> std::result::Result { + pub fn from_string(value: &str) -> std::result::Result { let str_bytes = value.as_bytes(); Self::from_slice(str_bytes) } @@ -328,7 +328,7 @@ impl std::fmt::Debug for AnnouncedNodeName { impl<'s> From<&'s str> for AnnouncedNodeName { fn from(value: &'s str) -> Self { - Self::from_str(value).expect("Valid announced node name") + Self::from_string(value).expect("Valid announced node name") } } @@ -347,7 +347,7 @@ impl<'de> serde::Deserialize<'de> for AnnouncedNodeName { D: Deserializer<'de>, { let s = String::deserialize(deserializer)?; - Self::from_str(&s).map_err(serde::de::Error::custom) + Self::from_string(&s).map_err(serde::de::Error::custom) } } @@ -382,7 +382,8 @@ impl FiberConfig { #[cfg(not(test))] pub fn read_or_generate_secret_key(&self) -> Result { FIBER_SECRET_KEY - .get_or_try_init(|| self.inner_read_or_generate_secret_key()).cloned() + .get_or_try_init(|| self.inner_read_or_generate_secret_key()) + .cloned() } pub fn store_path(&self) -> PathBuf { diff --git a/src/fiber/gossip.rs b/src/fiber/gossip.rs index 171cab884..aa9ad20c6 100644 --- a/src/fiber/gossip.rs +++ b/src/fiber/gossip.rs @@ -725,24 +725,15 @@ enum PeerSyncStatus { impl PeerSyncStatus { fn is_passive_syncing(&self) -> bool { - match self { - PeerSyncStatus::PassiveFilter(_) => true, - _ => false, - } + matches!(self, PeerSyncStatus::PassiveFilter(_)) } fn is_active_syncing(&self) -> bool { - match self { - PeerSyncStatus::ActiveGet(_) => true, - _ => false, - } + matches!(self, PeerSyncStatus::ActiveGet(_)) } fn is_finished_active_syncing(&self) -> bool { - match self { - PeerSyncStatus::FinishedActiveSyncing(_, _) => true, - _ => false, - } + matches!(self, PeerSyncStatus::FinishedActiveSyncing(_, _)) } fn can_start_active_syncing(&self) -> bool { @@ -1041,7 +1032,7 @@ impl ExtendedGossipMessageStoreState { for (id, subscription) in self.output_ports.iter() { let messages_to_send = messages .iter() - .filter(|m| &m.cursor() > &subscription.filter) + .filter(|m| m.cursor() > subscription.filter) .cloned() .collect::>(); trace!( @@ -1242,10 +1233,9 @@ impl Actor for ExtendedGossipMess match cursor { Some(cursor) => { - state - .output_ports - .get_mut(&id) - .map(|output| output.filter = cursor); + if let Some(outpout) = state.output_ports.get_mut(&id) { + outpout.filter = cursor; + } } _ => { state.output_ports.remove(&id); @@ -1597,8 +1587,7 @@ where let queries = get_dependent_message_queries(&message, self.get_store()); self.pending_queries.extend(queries); - self - .store + self.store .actor .send_message(ExtendedGossipMessageStoreMessage::SaveMessages(vec![ message, @@ -2085,6 +2074,7 @@ fn verify_node_announcement( } } +#[allow(clippy::too_many_arguments)] impl GossipProtocolHandle { pub(crate) async fn new( name: Option, @@ -2188,7 +2178,7 @@ where myself.get_cell(), ) .await; - if let Err(_) = tx.send(store.clone()) { + if tx.send(store.clone()).is_err() { panic!("failed to send store to the caller"); } let control = timeout(Duration::from_secs(1), rx) @@ -2197,7 +2187,7 @@ where .expect("receive control"); debug!("Gossip actor received service control"); - let _ = myself.send_interval(network_maintenance_interval, || { + myself.send_interval(network_maintenance_interval, || { GossipActorMessage::TickNetworkMaintenance }); let state = Self::State { @@ -2556,7 +2546,7 @@ impl ServiceProtocol for GossipProtocolHandle { .sender .take() .expect("service control sender set and init called once"); - if let Err(_) = sender.send(context.control().clone()) { + if sender.send(context.control().clone()).is_err() { panic!("Failed to send service control"); } } diff --git a/src/fiber/graph.rs b/src/fiber/graph.rs index 42da0d352..adb6805a2 100644 --- a/src/fiber/graph.rs +++ b/src/fiber/graph.rs @@ -537,14 +537,10 @@ where // So that when a node is marked as failed, the history can mark all the channels // associated with the node as failed. Here we tell the history about // the mapping between nodes and channels. - self.history.add_node_channel_map( - channel_info.node1, - channel_info.out_point().clone(), - ); - self.history.add_node_channel_map( - channel_info.node2, - channel_info.out_point().clone(), - ); + self.history + .add_node_channel_map(channel_info.node1, channel_info.out_point().clone()); + self.history + .add_node_channel_map(channel_info.node2, channel_info.out_point().clone()); self.channels .insert(channel_info.channel_outpoint.clone(), channel_info); return Some(cursor); @@ -914,6 +910,7 @@ where } // the algorithm works from target-to-source to find the shortest path + #[allow(clippy::too_many_arguments)] pub fn find_path( &self, source: Pubkey, diff --git a/src/fiber/history.rs b/src/fiber/history.rs index 3f3ec3313..8b5593731 100644 --- a/src/fiber/history.rs +++ b/src/fiber/history.rs @@ -504,7 +504,7 @@ where // this will make the probability calculation more stable let time_ago = if time_ago < 1000 { 0 } else { time_ago }; let exponent = -(time_ago as f64) / (DEFAULT_BIMODAL_DECAY_TIME as f64); - + exponent.exp() } @@ -517,13 +517,12 @@ where let factor = self.time_factor(time); - capacity - (factor * (capacity - fail_amount) as f64) as u128 } pub(crate) fn can_send(&self, amount: u128, time: u64) -> u128 { let factor = self.time_factor(time); - + (amount as f64 * factor) as u128 } @@ -599,8 +598,7 @@ where // f128 is only on nightly, so we use f64 here, we may lose some precision // but it's acceptable since all the values are cast to f64 - let mut prob = - self.integral_probability(capacity as f64, amount, fail_amount); + let mut prob = self.integral_probability(capacity as f64, amount, fail_amount); if prob.is_nan() { error!( "probability is NaN: capacity: {} amount: {} fail_amount: {}", @@ -608,13 +606,12 @@ where ); return 0.0; } - let re_norm = - self.integral_probability(capacity as f64, success_amount, fail_amount); + let re_norm = self.integral_probability(capacity as f64, success_amount, fail_amount); if re_norm == 0.0 { return 0.0; } prob /= re_norm; - prob = prob.max(0.0).min(1.0); + prob = prob.clamp(0.0, 1.0); return prob; } diff --git a/src/fiber/key.rs b/src/fiber/key.rs index 77e88f15d..9eba897a0 100644 --- a/src/fiber/key.rs +++ b/src/fiber/key.rs @@ -40,6 +40,7 @@ impl KeyPair { pub fn write_to_file(&self, path: &Path) -> Result<(), Error> { fs::OpenOptions::new() .create(true) + .truncate(true) .write(true) .open(path) .and_then(|mut file| { diff --git a/src/fiber/network.rs b/src/fiber/network.rs index 8c09021de..032767f61 100644 --- a/src/fiber/network.rs +++ b/src/fiber/network.rs @@ -21,7 +21,6 @@ use std::str::FromStr; use std::sync::atomic::{AtomicU64, Ordering}; use std::sync::Arc; use std::time::SystemTime; -use std::{u128, u64}; use tentacle::multiaddr::{MultiAddr, Protocol}; use tentacle::service::SessionType; use tentacle::utils::{extract_peer_id, is_reachable, multiaddr_to_socketaddr}; @@ -3432,6 +3431,7 @@ fn try_send_actor_message(actor: &ActorRef, message: Networ let _ = actor.send_message(message); } +#[allow(clippy::too_many_arguments)] pub async fn start_network< S: NetworkActorStateStore + ChannelActorStateStore diff --git a/src/fiber/tests/channel.rs b/src/fiber/tests/channel.rs index ec4f70b15..25281a187 100644 --- a/src/fiber/tests/channel.rs +++ b/src/fiber/tests/channel.rs @@ -3471,7 +3471,7 @@ async fn test_forward_payment_channel_disabled() { let [node_a, node_b, node_c] = nodes.try_into().expect("3 nodes"); let [_channel_a_b, channel_b_c] = channels.try_into().expect("2 channels"); - let node_c_pubkey = node_c.pubkey.clone(); + let node_c_pubkey = node_c.pubkey; tokio::time::sleep(tokio::time::Duration::from_millis(1000)).await; @@ -5148,7 +5148,7 @@ async fn test_send_payment_with_disable_channel() { create_n_nodes_with_established_channel(&amounts, nodes_num, true).await; let [node_0, _node_1, mut node_2, node_3] = nodes.try_into().expect("4 nodes"); let source_node = &node_0; - let target_pubkey = node_3.pubkey.clone(); + let target_pubkey = node_3.pubkey; // sleep for a while tokio::time::sleep(tokio::time::Duration::from_secs(1)).await; @@ -5160,7 +5160,7 @@ async fn test_send_payment_with_disable_channel() { let message = |rpc_reply| -> NetworkActorMessage { NetworkActorMessage::Command(NetworkActorCommand::SendPayment( SendPaymentCommand { - target_pubkey: Some(target_pubkey.clone()), + target_pubkey: Some(target_pubkey), amount: Some(3000), payment_hash: None, final_tlc_expiry_delta: None, diff --git a/src/fiber/tests/gossip.rs b/src/fiber/tests/gossip.rs index 989acf2e7..a80296c1b 100644 --- a/src/fiber/tests/gossip.rs +++ b/src/fiber/tests/gossip.rs @@ -142,7 +142,7 @@ async fn run_dummy_tentacle_service(gossip_handle: GossipProtocolHandle) { .await .expect("listen tentacle"); - let _ = spawn(async move { + spawn(async move { service.run().await; }); } @@ -271,12 +271,7 @@ async fn test_saving_invalid_channel_announcement() { .as_builder() .args( Bytes::new_builder() - .set( - b"wrong lock args" - .iter() - .map(|b| Byte::new(*b)) - .collect(), - ) + .set(b"wrong lock args".iter().map(|b| Byte::new(*b)).collect()) .build(), ) .build(); @@ -501,12 +496,7 @@ async fn test_saving_channel_update_with_invalid_channel_announcement() { .as_builder() .args( Bytes::new_builder() - .set( - b"wrong lock args" - .iter() - .map(|b| Byte::new(*b)) - .collect(), - ) + .set(b"wrong lock args".iter().map(|b| Byte::new(*b)).collect()) .build(), ) .build(); diff --git a/src/fiber/tests/graph.rs b/src/fiber/tests/graph.rs index 30be8497a..711a19c81 100644 --- a/src/fiber/tests/graph.rs +++ b/src/fiber/tests/graph.rs @@ -1,3 +1,4 @@ +#![allow(clippy::needless_range_loop)] use crate::fiber::config::MAX_PAYMENT_TLC_EXPIRY_LIMIT; use crate::fiber::gossip::GossipMessageStore; use crate::fiber::graph::{PathFindError, SessionRoute}; @@ -56,12 +57,12 @@ impl MockNetworkGraph { now_timestamp_as_millis_u64(), 0, )); - for i in 1..keypairs.len() { - let (sk, _pk) = keypairs[i]; + for (i, keypair) in keypairs.iter().enumerate().skip(1) { + let (sk, _pk) = keypair; store.save_node_announcement(NodeAnnouncement::new( format!("node{i}").as_str().into(), vec![], - &sk.into(), + &(*sk).into(), now_timestamp_as_millis_u64(), 0, )); @@ -101,6 +102,7 @@ impl MockNetworkGraph { // is the minimum tlc value that node_b will accept when forwarding tlc for node_a. // The udt_type_script is the udt type script of the channel. The other_fee_rate // is the fee rate that node_a will charge when forwarding tlc for node_b. + #[allow(clippy::too_many_arguments)] pub fn add_edge_with_config( &mut self, node_a: usize, @@ -260,7 +262,7 @@ impl MockNetworkGraph { pub fn build_route_with_possible_expects( &self, payment_data: &SendPaymentData, - expects: &Vec>, + expects: &[Vec], ) { let route = self.graph.build_route(payment_data.clone()); assert!(route.is_ok()); diff --git a/src/fiber/tests/network.rs b/src/fiber/tests/network.rs index 3c065c462..adb83cd24 100644 --- a/src/fiber/tests/network.rs +++ b/src/fiber/tests/network.rs @@ -90,11 +90,10 @@ fn create_fake_channel_announcement_mesage( fn create_node_announcement_mesage_with_priv_key(priv_key: &Privkey) -> NodeAnnouncement { let node_name = "fake node"; - let addresses = - ["/ip4/1.1.1.1/tcp/8346/p2p/QmaFDJb9CkMrXy7nhTWBY5y9mvuykre3EzzRsCJUAVXprZ"] - .iter() - .map(|x| MultiAddr::from_str(x).expect("valid multiaddr")) - .collect(); + let addresses = ["/ip4/1.1.1.1/tcp/8346/p2p/QmaFDJb9CkMrXy7nhTWBY5y9mvuykre3EzzRsCJUAVXprZ"] + .iter() + .map(|x| MultiAddr::from_str(x).expect("valid multiaddr")) + .collect(); NodeAnnouncement::new( node_name.into(), addresses, @@ -621,7 +620,7 @@ async fn test_persisting_announced_nodes() { let peers = node .with_network_graph(|graph| graph.sample_n_peers_to_connect(1)) .await; - assert!(peers.get(&peer_id).is_some()); + assert!(peers.contains_key(&peer_id)); } #[tokio::test] diff --git a/src/fiber/tests/test_utils.rs b/src/fiber/tests/test_utils.rs index 8596dcbe3..dfd3c4cb6 100644 --- a/src/fiber/tests/test_utils.rs +++ b/src/fiber/tests/test_utils.rs @@ -206,6 +206,7 @@ pub struct NetworkNodeConfigBuilder { node_name: Option, // We may generate a FiberConfig based on the base_dir and node_name, // but allow user to override it. + #[allow(clippy::type_complexity)] fiber_config_updater: Option>, } @@ -267,6 +268,7 @@ impl NetworkNodeConfigBuilder { } } +#[allow(clippy::too_many_arguments)] pub(crate) async fn establish_channel_between_nodes( node_a: &mut NetworkNode, node_b: &mut NetworkNode, @@ -443,6 +445,7 @@ pub(crate) async fn create_n_nodes_with_established_channel( .await } +#[allow(clippy::type_complexity)] pub(crate) async fn create_n_nodes_with_index_and_amounts_with_established_channel( amounts: &[((usize, usize), (u128, u128))], n: usize, @@ -486,9 +489,9 @@ pub(crate) async fn create_n_nodes_with_index_and_amounts_with_established_chann }; channels.push(channel_id); // all the other nodes submit_tx - for k in 0..n { - let res = nodes[k].submit_tx(funding_tx.clone()).await; - nodes[k].add_channel_tx(channel_id, funding_tx.clone()); + for node in nodes.iter_mut() { + let res = node.submit_tx(funding_tx.clone()).await; + node.add_channel_tx(channel_id, funding_tx.clone()); assert_eq!(res, Status::Committed); } } @@ -703,7 +706,7 @@ impl NetworkNode { let message = |rpc_reply| NetworkActorMessage::Command(NetworkActorCommand::NodeInfo((), rpc_reply)); eprintln!("query node_info ..."); - + call!(self.network_actor, message) .expect("node_a alive") .unwrap() @@ -942,6 +945,7 @@ impl NetworkNode { } nodes.push(new); } + #[allow(clippy::useless_conversion)] match nodes.try_into() { Ok(nodes) => nodes, Err(_) => unreachable!(), @@ -1116,10 +1120,7 @@ impl NetworkNode { pub async fn get_network_graph_channel(&self, channel_id: &OutPoint) -> Option { self.with_network_graph(|graph| { tracing::debug!("Getting channel info for {:?}", channel_id); - tracing::debug!( - "Channels: {:?}", - graph.channels().collect::>() - ); + tracing::debug!("Channels: {:?}", graph.channels().collect::>()); graph.get_channel(channel_id).cloned() }) .await diff --git a/src/fiber/tests/tlc_op.rs b/src/fiber/tests/tlc_op.rs index c6a9b1b29..ba4c378c6 100644 --- a/src/fiber/tests/tlc_op.rs +++ b/src/fiber/tests/tlc_op.rs @@ -338,15 +338,12 @@ impl Actor for TlcActor { _myself: ActorRef, args: Self::Arguments, ) -> Result { - eprintln!("TlcActor pre_start"); - match args { - peer_id => { - eprintln!("peer_id: {:?}", peer_id); - Ok(TlcActorState { - tlc_state: Default::default(), - peer_id, - }) - } + let peer_id = args; + { + Ok(TlcActorState { + tlc_state: Default::default(), + peer_id, + }) } } } diff --git a/src/fiber/tests/types.rs b/src/fiber/tests/types.rs index 53d4e0ec7..2da29532d 100644 --- a/src/fiber/tests/types.rs +++ b/src/fiber/tests/types.rs @@ -254,7 +254,7 @@ fn test_tlc_error_code() { fn test_create_and_verify_node_announcement() { let privkey = gen_rand_fiber_private_key(); let node_announcement = NodeAnnouncement::new( - AnnouncedNodeName::from_str("node1").expect("valid name"), + AnnouncedNodeName::from_string("node1").expect("valid name"), vec![], &privkey, now_timestamp_as_millis_u64(), @@ -271,7 +271,7 @@ fn test_create_and_verify_node_announcement() { fn test_serde_node_announcement() { let privkey = gen_rand_fiber_private_key(); let node_announcement = NodeAnnouncement::new( - AnnouncedNodeName::from_str("node1").expect("valid name"), + AnnouncedNodeName::from_string("node1").expect("valid name"), vec![], &privkey, now_timestamp_as_millis_u64(), diff --git a/src/fiber/types.rs b/src/fiber/types.rs index 4db631236..33440aeda 100644 --- a/src/fiber/types.rs +++ b/src/fiber/types.rs @@ -1432,8 +1432,7 @@ impl TlcErrPacket { } } - let hops_public_keys: Vec = - hops_public_keys.iter().map(|k| k.0).collect(); + let hops_public_keys: Vec = hops_public_keys.iter().map(|k| k.0).collect(); let session_key = SecretKey::from_slice(session_key).inspect_err(|err| error!(target: "fnn::fiber::types::TlcErrPacket", "decode session_key error={} key={}", err, hex::encode(session_key)) ).ok()?; @@ -1543,16 +1542,16 @@ impl TlcErrorCode { } pub fn payment_failed(&self) -> bool { - match self { + matches!( + self, TlcErrorCode::IncorrectOrUnknownPaymentDetails - | TlcErrorCode::FinalIncorrectExpiryDelta - | TlcErrorCode::FinalIncorrectTlcAmount - | TlcErrorCode::InvoiceExpired - | TlcErrorCode::InvoiceCancelled - | TlcErrorCode::ExpiryTooFar - | TlcErrorCode::ExpiryTooSoon => true, - _ => false, - } + | TlcErrorCode::FinalIncorrectExpiryDelta + | TlcErrorCode::FinalIncorrectTlcAmount + | TlcErrorCode::InvoiceExpired + | TlcErrorCode::InvoiceCancelled + | TlcErrorCode::ExpiryTooFar + | TlcErrorCode::ExpiryTooSoon + ) } } diff --git a/src/invoice/invoice_impl.rs b/src/invoice/invoice_impl.rs index eb2d7b7f3..b82b53edc 100644 --- a/src/invoice/invoice_impl.rs +++ b/src/invoice/invoice_impl.rs @@ -80,12 +80,12 @@ impl TryFrom for Currency { } } -impl ToString for Currency { - fn to_string(&self) -> String { +impl Display for Currency { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { - Currency::Fibb => "fibb".to_string(), - Currency::Fibt => "fibt".to_string(), - Currency::Fibd => "fibd".to_string(), + Currency::Fibb => write!(f, "fibb"), + Currency::Fibt => write!(f, "fibt"), + Currency::Fibd => write!(f, "fibd"), } } } @@ -169,7 +169,7 @@ impl CkbInvoice { fn hrp_part(&self) -> String { format!( "{}{}", - self.currency.to_string(), + self.currency, self.amount .map_or_else(|| "".to_string(), |x| x.to_string()), ) @@ -406,13 +406,8 @@ impl InvoiceSignature { } } -impl ToString for CkbInvoice { - /// hrp: fib{currency}{amount}{prefix} - /// data: compressed(InvoiceData) + signature - /// signature: 64 bytes + 1 byte recovery id = Vec - /// if signature is present: bech32m(hrp, 1 + data + signature) - /// else if signature is not present: bech32m(hrp, 0 + data) - fn to_string(&self) -> String { +impl Display for CkbInvoice { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let hrp = self.hrp_part(); let mut data = self.data_part(); data.insert( @@ -422,7 +417,11 @@ impl ToString for CkbInvoice { if let Some(signature) = &self.signature { data.extend_from_slice(&signature.to_base32()); } - encode(&hrp, data, Variant::Bech32m).expect("encode invoice using Bech32m") + write!( + f, + "{}", + encode(&hrp, data, Variant::Bech32m).expect("encode invoice using Bech32m") + ) } } diff --git a/src/rpc/mod.rs b/src/rpc/mod.rs index b62c81285..22cda46b9 100644 --- a/src/rpc/mod.rs +++ b/src/rpc/mod.rs @@ -79,6 +79,8 @@ async fn build_server(addr: &str) -> Server { } } +#[allow(clippy::type_complexity)] +#[allow(clippy::too_many_arguments)] pub async fn start_rpc< S: ChannelActorStateStore + InvoiceStore diff --git a/src/store/store.rs b/src/store/store.rs index d0962d1d0..0150b008a 100644 --- a/src/store/store.rs +++ b/src/store/store.rs @@ -469,8 +469,8 @@ impl NetworkGraphStateStore for Store { let prefix = vec![PAYMENT_HISTORY_TIMED_RESULT_PREFIX]; let iter = self.prefix_iterator(&prefix); iter.map(|(key, value)| { - let channel_outpoint: OutPoint = OutPoint::from_slice(&key[1..=36]) - .expect("deserialize OutPoint should be OK"); + let channel_outpoint: OutPoint = + OutPoint::from_slice(&key[1..=36]).expect("deserialize OutPoint should be OK"); let direction = deserialize_from(&key[37..], "Direction"); let result = deserialize_from(value.as_ref(), "TimedResult"); (channel_outpoint, direction, result) @@ -491,7 +491,7 @@ impl GossipMessageStore for Store { self.db .iterator(mode) // We should skip the value with the same cursor (after_cursor is exclusive). - .skip_while(move |(key, _)| key.as_ref() == &start) + .skip_while(move |(key, _)| key.as_ref() == start) .take_while(move |(key, _)| key.starts_with(&prefix)) .map(|(key, value)| { debug_assert_eq!(key.len(), 1 + CURSOR_SIZE); diff --git a/src/store/tests/store.rs b/src/store/tests/store.rs index 3d9007cc3..58e804182 100644 --- a/src/store/tests/store.rs +++ b/src/store/tests/store.rs @@ -44,7 +44,7 @@ fn mock_node() -> (Privkey, NodeAnnouncement) { ( sk.clone(), NodeAnnouncement::new( - AnnouncedNodeName::from_str("node1").expect("invalid name"), + AnnouncedNodeName::from_string("node1").expect("invalid name"), vec![], &sk, now_timestamp_as_millis_u64(), @@ -544,7 +544,7 @@ fn test_store_payment_history() { vec![(channel_outpoint.clone(), direction, result)] ); - fn sort_results(results: &mut Vec<(OutPoint, Direction, TimedResult)>) { + fn sort_results(results: &mut [(OutPoint, Direction, TimedResult)]) { results.sort_by(|a, b| match a.0.cmp(&b.0) { Ordering::Equal => a.1.cmp(&b.1), other => other, @@ -597,7 +597,7 @@ fn test_store_payment_history() { fn test_serde_node_announcement_as_broadcast_message() { let privkey = gen_rand_fiber_private_key(); let node_announcement = NodeAnnouncement::new( - AnnouncedNodeName::from_str("node1").expect("valid name"), + AnnouncedNodeName::from_string("node1").expect("valid name"), vec![], &privkey, now_timestamp_as_millis_u64(), diff --git a/src/tests/mod.rs b/src/tests/mod.rs index d286fb372..c2ec66929 100644 --- a/src/tests/mod.rs +++ b/src/tests/mod.rs @@ -59,7 +59,7 @@ pub fn gen_rand_node_announcement() -> (Privkey, NodeAnnouncement) { pub fn gen_node_announcement_from_privkey(sk: &Privkey) -> NodeAnnouncement { NodeAnnouncement::new( - AnnouncedNodeName::from_str("node1").expect("valid name"), + AnnouncedNodeName::from_string("node1").expect("valid name"), vec![], sk, now_timestamp_as_millis_u64(), From f7d18207082e8a0babb6624f191b131c084f8a41 Mon Sep 17 00:00:00 2001 From: yukang Date: Mon, 27 Jan 2025 12:56:32 +0800 Subject: [PATCH 3/4] resolve conflicts --- migrate/Cargo.lock | 6 ------ src/fiber/tests/history.rs | 1 + 2 files changed, 1 insertion(+), 6 deletions(-) diff --git a/migrate/Cargo.lock b/migrate/Cargo.lock index 48c6474f0..da3912165 100644 --- a/migrate/Cargo.lock +++ b/migrate/Cargo.lock @@ -1711,8 +1711,6 @@ dependencies = [ [[package]] name = "fnn" version = "0.3.1" -<<<<<<< HEAD -======= dependencies = [ "anyhow", "arcode", @@ -1821,7 +1819,6 @@ dependencies = [ name = "fnn" version = "0.3.1" source = "git+https://github.com/chenyukang/fiber.git?branch=yukang-fix-480-keep-fail-tlc#07d054da4a2e9769eb12da35558183dcfb48bb8c" ->>>>>>> develop dependencies = [ "anyhow", "arcode", @@ -1884,11 +1881,8 @@ dependencies = [ "fnn 0.2.1 (git+https://github.com/nervosnetwork/fiber.git?tag=v0.2.1)", "fnn 0.2.1 (git+https://github.com/nervosnetwork/fiber.git?tag=v0.3.0-rc1)", "fnn 0.3.1", -<<<<<<< HEAD -======= "fnn 0.3.1 (git+https://github.com/nervosnetwork/fiber.git?tag=v0.3.1)", "fnn 0.3.1 (git+https://github.com/chenyukang/fiber.git?branch=yukang-fix-480-keep-fail-tlc)", ->>>>>>> develop "hex", "indicatif", "serde", diff --git a/src/fiber/tests/history.rs b/src/fiber/tests/history.rs index ad7ddfe04..295d1b75b 100644 --- a/src/fiber/tests/history.rs +++ b/src/fiber/tests/history.rs @@ -399,6 +399,7 @@ fn test_history_apply_internal_result_fail_node() { .. }) )); + assert!(matches!( history.get_result(&channel_outpoint1, rev_direction1), Some(&TimedResult { From 81fc71098455ea79140142cef5bc6ebab5d93f7b Mon Sep 17 00:00:00 2001 From: yukang Date: Mon, 27 Jan 2025 12:59:44 +0800 Subject: [PATCH 4/4] fix fmt --- src/fiber/channel.rs | 14 +++++------ src/fiber/tests/history.rs | 48 +++++++++++++++----------------------- src/fiber/tests/payment.rs | 3 ++- src/fiber/tests/types.rs | 3 +-- 4 files changed, 29 insertions(+), 39 deletions(-) diff --git a/src/fiber/channel.rs b/src/fiber/channel.rs index 91089716c..f976cb75e 100644 --- a/src/fiber/channel.rs +++ b/src/fiber/channel.rs @@ -2615,12 +2615,12 @@ impl TlcInfo { pub fn is_fail_remove_confirmed(&self) -> bool { matches!(self.removed_reason, Some(RemoveTlcReason::RemoveTlcFail(_))) - && match self.status { - TlcStatus::Outbound(OutboundTlcStatus::RemoveAckConfirmed) => true, - TlcStatus::Outbound(OutboundTlcStatus::RemoveWaitAck) => true, - TlcStatus::Inbound(InboundTlcStatus::RemoveAckConfirmed) => true, - _ => false, - } + && matches!( + self.status, + TlcStatus::Outbound(OutboundTlcStatus::RemoveAckConfirmed) + | TlcStatus::Outbound(OutboundTlcStatus::RemoveWaitAck) + | TlcStatus::Inbound(InboundTlcStatus::RemoveAckConfirmed) + ) } fn get_hash(&self) -> ShortHash { @@ -4717,7 +4717,7 @@ impl ChannelActorState { .iter() .chain(failed_received_tlcs.iter()) { - debug_assert!(self.tlc_state.applied_remove_tlcs.contains(&tlc_id)); + debug_assert!(self.tlc_state.applied_remove_tlcs.contains(tlc_id)); self.tlc_state.apply_remove_tlc(*tlc_id); } } diff --git a/src/fiber/tests/history.rs b/src/fiber/tests/history.rs index 295d1b75b..c0970b186 100644 --- a/src/fiber/tests/history.rs +++ b/src/fiber/tests/history.rs @@ -287,8 +287,7 @@ fn test_history_internal_result_fail_range_pair() { assert_eq!(res.amount, 0); assert!(!res.success); - let mut history = - PaymentHistory::new(gen_rand_fiber_public_key(), None, generate_store()); + let mut history = PaymentHistory::new(gen_rand_fiber_public_key(), None, generate_store()); history.apply_internal_result(internal_result); assert!(matches!( @@ -335,8 +334,7 @@ fn test_history_internal_result_fail_range_pair() { #[test] fn test_history_apply_internal_result_fail_node() { let mut internal_result = InternalResult::default(); - let mut history = - PaymentHistory::new(gen_rand_fiber_public_key(), None, generate_store()); + let mut history = PaymentHistory::new(gen_rand_fiber_public_key(), None, generate_store()); let node1 = gen_rand_fiber_public_key(); let node2 = gen_rand_fiber_public_key(); let node3 = gen_rand_fiber_public_key(); @@ -433,8 +431,7 @@ fn test_history_apply_internal_result_fail_node() { #[test] fn test_history_fail_node_with_multiple_channels() { let mut internal_result = InternalResult::default(); - let mut history = - PaymentHistory::new(gen_rand_fiber_public_key(), None, generate_store()); + let mut history = PaymentHistory::new(gen_rand_fiber_public_key(), None, generate_store()); let node1 = gen_rand_fiber_public_key(); let node2 = gen_rand_fiber_public_key(); let node3 = gen_rand_fiber_public_key(); @@ -527,9 +524,13 @@ fn test_history_fail_node_with_multiple_channels() { }) )); - assert!(history.get_result(&channel_outpoint1, rev_direction1).is_none()); + assert!(history + .get_result(&channel_outpoint1, rev_direction1) + .is_none()); - assert!(history.get_result(&channel_outpoint2, rev_direction2).is_none()); + assert!(history + .get_result(&channel_outpoint2, rev_direction2) + .is_none()); assert!(matches!( history.get_result(&channel_outpoint3, direction1), @@ -570,8 +571,7 @@ fn test_history_fail_node_with_multiple_channels() { #[test] fn test_history_interal_success_fail() { - let mut history = - PaymentHistory::new(gen_rand_fiber_public_key(), None, generate_store()); + let mut history = PaymentHistory::new(gen_rand_fiber_public_key(), None, generate_store()); let from = gen_rand_fiber_public_key(); let target = gen_rand_fiber_public_key(); let channel_outpoint = OutPoint::default(); @@ -634,8 +634,7 @@ fn test_history_interal_success_fail() { #[test] fn test_history_interal_fuzz_assertion_crash() { - let mut history = - PaymentHistory::new(gen_rand_fiber_public_key(), None, generate_store()); + let mut history = PaymentHistory::new(gen_rand_fiber_public_key(), None, generate_store()); let from = gen_rand_fiber_public_key(); let target = gen_rand_fiber_public_key(); let channel_outpoint = OutPoint::default(); @@ -668,8 +667,7 @@ fn test_history_interal_fuzz_assertion_crash() { #[test] fn test_history_interal_fail_zero_after_succ() { - let mut history = - PaymentHistory::new(gen_rand_fiber_public_key(), None, generate_store()); + let mut history = PaymentHistory::new(gen_rand_fiber_public_key(), None, generate_store()); let from = gen_rand_fiber_public_key(); let target = gen_rand_fiber_public_key(); let channel_outpoint = OutPoint::default(); @@ -698,8 +696,7 @@ fn test_history_interal_fail_zero_after_succ() { #[test] fn test_history_interal_keep_valid_range() { - let mut history = - PaymentHistory::new(gen_rand_fiber_public_key(), None, generate_store()); + let mut history = PaymentHistory::new(gen_rand_fiber_public_key(), None, generate_store()); let from = gen_rand_fiber_public_key(); let target = gen_rand_fiber_public_key(); let channel_outpoint = OutPoint::default(); @@ -731,8 +728,7 @@ fn test_history_interal_keep_valid_range() { #[test] fn test_history_probability() { - let mut history = - PaymentHistory::new(gen_rand_fiber_public_key(), None, generate_store()); + let mut history = PaymentHistory::new(gen_rand_fiber_public_key(), None, generate_store()); let from = gen_rand_fiber_public_key(); let target = gen_rand_fiber_public_key(); let channel_outpoint = OutPoint::default(); @@ -821,8 +817,7 @@ fn test_history_probability() { #[test] fn test_history_direct_probability() { - let mut history = - PaymentHistory::new(gen_rand_fiber_public_key(), None, generate_store()); + let mut history = PaymentHistory::new(gen_rand_fiber_public_key(), None, generate_store()); let from = gen_rand_fiber_public_key(); let target = gen_rand_fiber_public_key(); let channel_outpoint = OutPoint::default(); @@ -882,8 +877,7 @@ fn test_history_direct_probability() { #[test] fn test_history_small_fail_amount_probability() { - let mut history = - PaymentHistory::new(gen_rand_fiber_public_key(), None, generate_store()); + let mut history = PaymentHistory::new(gen_rand_fiber_public_key(), None, generate_store()); let from = gen_rand_fiber_public_key(); let target = gen_rand_fiber_public_key(); let channel_outpoint = OutPoint::default(); @@ -907,8 +901,7 @@ fn test_history_small_fail_amount_probability() { #[test] fn test_history_channel_probability_range() { - let mut history = - PaymentHistory::new(gen_rand_fiber_public_key(), None, generate_store()); + let mut history = PaymentHistory::new(gen_rand_fiber_public_key(), None, generate_store()); let from = gen_rand_fiber_public_key(); let target = gen_rand_fiber_public_key(); let channel_outpoint = OutPoint::default(); @@ -948,8 +941,7 @@ fn test_history_channel_probability_range() { #[test] fn test_history_eval_probability_range() { - let mut history = - PaymentHistory::new(gen_rand_fiber_public_key(), None, generate_store()); + let mut history = PaymentHistory::new(gen_rand_fiber_public_key(), None, generate_store()); let from = gen_rand_fiber_public_key(); let target = gen_rand_fiber_public_key(); let channel_outpoint = OutPoint::default(); @@ -1036,9 +1028,7 @@ fn test_history_load_store() { }; history.add_result(channel_outpoint.clone(), direction, result); - let result = *history - .get_result(&channel_outpoint, direction) - .unwrap(); + let result = *history.get_result(&channel_outpoint, direction).unwrap(); history.reset(); assert_eq!(history.get_result(&channel_outpoint, direction), None); history.load_from_store(); diff --git a/src/fiber/tests/payment.rs b/src/fiber/tests/payment.rs index 428bf923e..0de94a678 100644 --- a/src/fiber/tests/payment.rs +++ b/src/fiber/tests/payment.rs @@ -1,3 +1,4 @@ +#![allow(clippy::needless_range_loop)] use super::test_utils::init_tracing; use crate::fiber::channel::UpdateCommand; use crate::fiber::graph::PaymentSessionStatus; @@ -2169,7 +2170,7 @@ async fn test_send_payment_complex_network_payself_amount_exceeded() { // the channel amount is not enough, so payments maybe be failed let ckb_unit = 100_000_000; let res = run_complex_network_with_params(MIN_RESERVED_CKB + 1000 * ckb_unit, || { - (400 as u128 + (rand::random::() % 100) as u128) * ckb_unit + (400_u128 + (rand::random::() % 100) as u128) * ckb_unit }) .await; diff --git a/src/fiber/tests/types.rs b/src/fiber/tests/types.rs index 2da29532d..0228737c5 100644 --- a/src/fiber/tests/types.rs +++ b/src/fiber/tests/types.rs @@ -212,8 +212,7 @@ fn test_tlc_err_packet_encryption() { let session_key = SecretKey::from_slice(&[0x41; 32]).expect("32 bytes, within curve order"); let hops_ss: Vec<[u8; 32]> = - OnionSharedSecretIter::new(hops_path.iter().map(|k| &k.0), session_key, &secp) - .collect(); + OnionSharedSecretIter::new(hops_path.iter().map(|k| &k.0), session_key, &secp).collect(); let tlc_fail_detail = TlcErr::new(TlcErrorCode::InvalidOnionVersion); {