From f0ec37ec16e175bb5d4418462149ed7584f2dfc8 Mon Sep 17 00:00:00 2001 From: Elias Rohrer Date: Mon, 10 Jun 2024 13:40:38 +0200 Subject: [PATCH 1/5] Prepare `chanmon_consistency.rs` for `rustfmt` --- fuzz/src/chanmon_consistency.rs | 180 +++++++++++++++++--------------- 1 file changed, 98 insertions(+), 82 deletions(-) diff --git a/fuzz/src/chanmon_consistency.rs b/fuzz/src/chanmon_consistency.rs index a4b68ae1978..a311ee9f7f2 100644 --- a/fuzz/src/chanmon_consistency.rs +++ b/fuzz/src/chanmon_consistency.rs @@ -238,6 +238,7 @@ struct KeyProvider { impl EntropySource for KeyProvider { fn get_secure_random_bytes(&self) -> [u8; 32] { let id = self.rand_bytes_id.fetch_add(1, atomic::Ordering::Relaxed); + #[rustfmt::skip] let mut res = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 11, self.node_secret[31]]; res[30-4..30].copy_from_slice(&id.to_le_bytes()); res @@ -265,7 +266,9 @@ impl NodeSigner for KeyProvider { } fn get_inbound_payment_key_material(&self) -> KeyMaterial { - KeyMaterial([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, self.node_secret[31]]) + #[rustfmt::skip] + let random_bytes = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, self.node_secret[31]]; + KeyMaterial(random_bytes) } fn sign_invoice(&self, _hrp_bytes: &[u8], _invoice_data: &[u5], _recipient: Recipient) -> Result { @@ -304,6 +307,7 @@ impl SignerProvider for KeyProvider { fn derive_channel_signer(&self, channel_value_satoshis: u64, channel_keys_id: [u8; 32]) -> Self::EcdsaSigner { let secp_ctx = Secp256k1::signing_only(); let id = channel_keys_id[0]; + #[rustfmt::skip] let keys = InMemorySigner::new( &secp_ctx, SecretKey::from_slice(&[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, self.node_secret[31]]).unwrap(), @@ -336,6 +340,7 @@ impl SignerProvider for KeyProvider { fn get_destination_script(&self, _channel_keys_id: [u8; 32]) -> Result { let secp_ctx = Secp256k1::signing_only(); + #[rustfmt::skip] let channel_monitor_claim_key = SecretKey::from_slice(&[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, self.node_secret[31]]).unwrap(); let our_channel_monitor_claim_key_hash = WPubkeyHash::hash(&PublicKey::from_secret_key(&secp_ctx, &channel_monitor_claim_key).serialize()); Ok(Builder::new().push_opcode(opcodes::all::OP_PUSHBYTES_0).push_slice(our_channel_monitor_claim_key_hash).into_script()) @@ -343,6 +348,7 @@ impl SignerProvider for KeyProvider { fn get_shutdown_scriptpubkey(&self) -> Result { let secp_ctx = Secp256k1::signing_only(); + #[rustfmt::skip] let secret_key = SecretKey::from_slice(&[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, self.node_secret[31]]).unwrap(); let pubkey_hash = WPubkeyHash::hash(&PublicKey::from_secret_key(&secp_ctx, &secret_key).serialize()); Ok(ShutdownScript::new_p2wpkh(&pubkey_hash)) @@ -588,12 +594,14 @@ pub fn do_test(data: &[u8], underlying_out: Out, anchors: bool) { let mut channel_txn = Vec::new(); macro_rules! make_channel { ($source: expr, $dest: expr, $dest_keys_manager: expr, $chan_id: expr) => { { - $source.peer_connected(&$dest.get_our_node_id(), &Init { + let init_dest = Init { features: $dest.init_features(), networks: None, remote_network_address: None - }, true).unwrap(); - $dest.peer_connected(&$source.get_our_node_id(), &Init { + }; + $source.peer_connected(&$dest.get_our_node_id(), &init_dest, true).unwrap(); + let init_src = Init { features: $source.init_features(), networks: None, remote_network_address: None - }, false).unwrap(); + }; + $dest.peer_connected(&$source.get_our_node_id(), &init_src, false).unwrap(); $source.create_channel($dest.get_our_node_id(), 100_000, 42, 0, None, None).unwrap(); let open_channel = { @@ -745,8 +753,8 @@ pub fn do_test(data: &[u8], underlying_out: Out, anchors: bool) { let chan_a = nodes[0].list_usable_channels()[0].short_channel_id.unwrap(); let chan_b = nodes[2].list_usable_channels()[0].short_channel_id.unwrap(); - let mut payment_id: u8 = 0; - let mut payment_idx: u64 = 0; + let mut p_id: u8 = 0; + let mut p_idx: u64 = 0; let mut chan_a_disconnected = false; let mut chan_b_disconnected = false; @@ -1157,23 +1165,27 @@ pub fn do_test(data: &[u8], underlying_out: Out, anchors: bool) { }, 0x0e => { if chan_a_disconnected { - nodes[0].peer_connected(&nodes[1].get_our_node_id(), &Init { + let init_1 = Init { features: nodes[1].init_features(), networks: None, remote_network_address: None - }, true).unwrap(); - nodes[1].peer_connected(&nodes[0].get_our_node_id(), &Init { + }; + nodes[0].peer_connected(&nodes[1].get_our_node_id(), &init_1, true).unwrap(); + let init_0 = Init { features: nodes[0].init_features(), networks: None, remote_network_address: None - }, false).unwrap(); + }; + nodes[1].peer_connected(&nodes[0].get_our_node_id(), &init_0, false).unwrap(); chan_a_disconnected = false; } }, 0x0f => { if chan_b_disconnected { - nodes[1].peer_connected(&nodes[2].get_our_node_id(), &Init { + let init_2 = Init { features: nodes[2].init_features(), networks: None, remote_network_address: None - }, true).unwrap(); - nodes[2].peer_connected(&nodes[1].get_our_node_id(), &Init { + }; + nodes[1].peer_connected(&nodes[2].get_our_node_id(), &init_2, true).unwrap(); + let init_1 = Init { features: nodes[1].init_features(), networks: None, remote_network_address: None - }, false).unwrap(); + }; + nodes[2].peer_connected(&nodes[1].get_our_node_id(), &init_1, false).unwrap(); chan_b_disconnected = false; } }, @@ -1253,61 +1265,61 @@ pub fn do_test(data: &[u8], underlying_out: Out, anchors: bool) { }, // 1/10th the channel size: - 0x30 => { send_payment(&nodes[0], &nodes[1], chan_a, 10_000_000, &mut payment_id, &mut payment_idx); }, - 0x31 => { send_payment(&nodes[1], &nodes[0], chan_a, 10_000_000, &mut payment_id, &mut payment_idx); }, - 0x32 => { send_payment(&nodes[1], &nodes[2], chan_b, 10_000_000, &mut payment_id, &mut payment_idx); }, - 0x33 => { send_payment(&nodes[2], &nodes[1], chan_b, 10_000_000, &mut payment_id, &mut payment_idx); }, - 0x34 => { send_hop_payment(&nodes[0], &nodes[1], chan_a, &nodes[2], chan_b, 10_000_000, &mut payment_id, &mut payment_idx); }, - 0x35 => { send_hop_payment(&nodes[2], &nodes[1], chan_b, &nodes[0], chan_a, 10_000_000, &mut payment_id, &mut payment_idx); }, - - 0x38 => { send_payment(&nodes[0], &nodes[1], chan_a, 1_000_000, &mut payment_id, &mut payment_idx); }, - 0x39 => { send_payment(&nodes[1], &nodes[0], chan_a, 1_000_000, &mut payment_id, &mut payment_idx); }, - 0x3a => { send_payment(&nodes[1], &nodes[2], chan_b, 1_000_000, &mut payment_id, &mut payment_idx); }, - 0x3b => { send_payment(&nodes[2], &nodes[1], chan_b, 1_000_000, &mut payment_id, &mut payment_idx); }, - 0x3c => { send_hop_payment(&nodes[0], &nodes[1], chan_a, &nodes[2], chan_b, 1_000_000, &mut payment_id, &mut payment_idx); }, - 0x3d => { send_hop_payment(&nodes[2], &nodes[1], chan_b, &nodes[0], chan_a, 1_000_000, &mut payment_id, &mut payment_idx); }, - - 0x40 => { send_payment(&nodes[0], &nodes[1], chan_a, 100_000, &mut payment_id, &mut payment_idx); }, - 0x41 => { send_payment(&nodes[1], &nodes[0], chan_a, 100_000, &mut payment_id, &mut payment_idx); }, - 0x42 => { send_payment(&nodes[1], &nodes[2], chan_b, 100_000, &mut payment_id, &mut payment_idx); }, - 0x43 => { send_payment(&nodes[2], &nodes[1], chan_b, 100_000, &mut payment_id, &mut payment_idx); }, - 0x44 => { send_hop_payment(&nodes[0], &nodes[1], chan_a, &nodes[2], chan_b, 100_000, &mut payment_id, &mut payment_idx); }, - 0x45 => { send_hop_payment(&nodes[2], &nodes[1], chan_b, &nodes[0], chan_a, 100_000, &mut payment_id, &mut payment_idx); }, - - 0x48 => { send_payment(&nodes[0], &nodes[1], chan_a, 10_000, &mut payment_id, &mut payment_idx); }, - 0x49 => { send_payment(&nodes[1], &nodes[0], chan_a, 10_000, &mut payment_id, &mut payment_idx); }, - 0x4a => { send_payment(&nodes[1], &nodes[2], chan_b, 10_000, &mut payment_id, &mut payment_idx); }, - 0x4b => { send_payment(&nodes[2], &nodes[1], chan_b, 10_000, &mut payment_id, &mut payment_idx); }, - 0x4c => { send_hop_payment(&nodes[0], &nodes[1], chan_a, &nodes[2], chan_b, 10_000, &mut payment_id, &mut payment_idx); }, - 0x4d => { send_hop_payment(&nodes[2], &nodes[1], chan_b, &nodes[0], chan_a, 10_000, &mut payment_id, &mut payment_idx); }, - - 0x50 => { send_payment(&nodes[0], &nodes[1], chan_a, 1_000, &mut payment_id, &mut payment_idx); }, - 0x51 => { send_payment(&nodes[1], &nodes[0], chan_a, 1_000, &mut payment_id, &mut payment_idx); }, - 0x52 => { send_payment(&nodes[1], &nodes[2], chan_b, 1_000, &mut payment_id, &mut payment_idx); }, - 0x53 => { send_payment(&nodes[2], &nodes[1], chan_b, 1_000, &mut payment_id, &mut payment_idx); }, - 0x54 => { send_hop_payment(&nodes[0], &nodes[1], chan_a, &nodes[2], chan_b, 1_000, &mut payment_id, &mut payment_idx); }, - 0x55 => { send_hop_payment(&nodes[2], &nodes[1], chan_b, &nodes[0], chan_a, 1_000, &mut payment_id, &mut payment_idx); }, - - 0x58 => { send_payment(&nodes[0], &nodes[1], chan_a, 100, &mut payment_id, &mut payment_idx); }, - 0x59 => { send_payment(&nodes[1], &nodes[0], chan_a, 100, &mut payment_id, &mut payment_idx); }, - 0x5a => { send_payment(&nodes[1], &nodes[2], chan_b, 100, &mut payment_id, &mut payment_idx); }, - 0x5b => { send_payment(&nodes[2], &nodes[1], chan_b, 100, &mut payment_id, &mut payment_idx); }, - 0x5c => { send_hop_payment(&nodes[0], &nodes[1], chan_a, &nodes[2], chan_b, 100, &mut payment_id, &mut payment_idx); }, - 0x5d => { send_hop_payment(&nodes[2], &nodes[1], chan_b, &nodes[0], chan_a, 100, &mut payment_id, &mut payment_idx); }, - - 0x60 => { send_payment(&nodes[0], &nodes[1], chan_a, 10, &mut payment_id, &mut payment_idx); }, - 0x61 => { send_payment(&nodes[1], &nodes[0], chan_a, 10, &mut payment_id, &mut payment_idx); }, - 0x62 => { send_payment(&nodes[1], &nodes[2], chan_b, 10, &mut payment_id, &mut payment_idx); }, - 0x63 => { send_payment(&nodes[2], &nodes[1], chan_b, 10, &mut payment_id, &mut payment_idx); }, - 0x64 => { send_hop_payment(&nodes[0], &nodes[1], chan_a, &nodes[2], chan_b, 10, &mut payment_id, &mut payment_idx); }, - 0x65 => { send_hop_payment(&nodes[2], &nodes[1], chan_b, &nodes[0], chan_a, 10, &mut payment_id, &mut payment_idx); }, - - 0x68 => { send_payment(&nodes[0], &nodes[1], chan_a, 1, &mut payment_id, &mut payment_idx); }, - 0x69 => { send_payment(&nodes[1], &nodes[0], chan_a, 1, &mut payment_id, &mut payment_idx); }, - 0x6a => { send_payment(&nodes[1], &nodes[2], chan_b, 1, &mut payment_id, &mut payment_idx); }, - 0x6b => { send_payment(&nodes[2], &nodes[1], chan_b, 1, &mut payment_id, &mut payment_idx); }, - 0x6c => { send_hop_payment(&nodes[0], &nodes[1], chan_a, &nodes[2], chan_b, 1, &mut payment_id, &mut payment_idx); }, - 0x6d => { send_hop_payment(&nodes[2], &nodes[1], chan_b, &nodes[0], chan_a, 1, &mut payment_id, &mut payment_idx); }, + 0x30 => { send_payment(&nodes[0], &nodes[1], chan_a, 10_000_000, &mut p_id, &mut p_idx); }, + 0x31 => { send_payment(&nodes[1], &nodes[0], chan_a, 10_000_000, &mut p_id, &mut p_idx); }, + 0x32 => { send_payment(&nodes[1], &nodes[2], chan_b, 10_000_000, &mut p_id, &mut p_idx); }, + 0x33 => { send_payment(&nodes[2], &nodes[1], chan_b, 10_000_000, &mut p_id, &mut p_idx); }, + 0x34 => { send_hop_payment(&nodes[0], &nodes[1], chan_a, &nodes[2], chan_b, 10_000_000, &mut p_id, &mut p_idx); }, + 0x35 => { send_hop_payment(&nodes[2], &nodes[1], chan_b, &nodes[0], chan_a, 10_000_000, &mut p_id, &mut p_idx); }, + + 0x38 => { send_payment(&nodes[0], &nodes[1], chan_a, 1_000_000, &mut p_id, &mut p_idx); }, + 0x39 => { send_payment(&nodes[1], &nodes[0], chan_a, 1_000_000, &mut p_id, &mut p_idx); }, + 0x3a => { send_payment(&nodes[1], &nodes[2], chan_b, 1_000_000, &mut p_id, &mut p_idx); }, + 0x3b => { send_payment(&nodes[2], &nodes[1], chan_b, 1_000_000, &mut p_id, &mut p_idx); }, + 0x3c => { send_hop_payment(&nodes[0], &nodes[1], chan_a, &nodes[2], chan_b, 1_000_000, &mut p_id, &mut p_idx); }, + 0x3d => { send_hop_payment(&nodes[2], &nodes[1], chan_b, &nodes[0], chan_a, 1_000_000, &mut p_id, &mut p_idx); }, + + 0x40 => { send_payment(&nodes[0], &nodes[1], chan_a, 100_000, &mut p_id, &mut p_idx); }, + 0x41 => { send_payment(&nodes[1], &nodes[0], chan_a, 100_000, &mut p_id, &mut p_idx); }, + 0x42 => { send_payment(&nodes[1], &nodes[2], chan_b, 100_000, &mut p_id, &mut p_idx); }, + 0x43 => { send_payment(&nodes[2], &nodes[1], chan_b, 100_000, &mut p_id, &mut p_idx); }, + 0x44 => { send_hop_payment(&nodes[0], &nodes[1], chan_a, &nodes[2], chan_b, 100_000, &mut p_id, &mut p_idx); }, + 0x45 => { send_hop_payment(&nodes[2], &nodes[1], chan_b, &nodes[0], chan_a, 100_000, &mut p_id, &mut p_idx); }, + + 0x48 => { send_payment(&nodes[0], &nodes[1], chan_a, 10_000, &mut p_id, &mut p_idx); }, + 0x49 => { send_payment(&nodes[1], &nodes[0], chan_a, 10_000, &mut p_id, &mut p_idx); }, + 0x4a => { send_payment(&nodes[1], &nodes[2], chan_b, 10_000, &mut p_id, &mut p_idx); }, + 0x4b => { send_payment(&nodes[2], &nodes[1], chan_b, 10_000, &mut p_id, &mut p_idx); }, + 0x4c => { send_hop_payment(&nodes[0], &nodes[1], chan_a, &nodes[2], chan_b, 10_000, &mut p_id, &mut p_idx); }, + 0x4d => { send_hop_payment(&nodes[2], &nodes[1], chan_b, &nodes[0], chan_a, 10_000, &mut p_id, &mut p_idx); }, + + 0x50 => { send_payment(&nodes[0], &nodes[1], chan_a, 1_000, &mut p_id, &mut p_idx); }, + 0x51 => { send_payment(&nodes[1], &nodes[0], chan_a, 1_000, &mut p_id, &mut p_idx); }, + 0x52 => { send_payment(&nodes[1], &nodes[2], chan_b, 1_000, &mut p_id, &mut p_idx); }, + 0x53 => { send_payment(&nodes[2], &nodes[1], chan_b, 1_000, &mut p_id, &mut p_idx); }, + 0x54 => { send_hop_payment(&nodes[0], &nodes[1], chan_a, &nodes[2], chan_b, 1_000, &mut p_id, &mut p_idx); }, + 0x55 => { send_hop_payment(&nodes[2], &nodes[1], chan_b, &nodes[0], chan_a, 1_000, &mut p_id, &mut p_idx); }, + + 0x58 => { send_payment(&nodes[0], &nodes[1], chan_a, 100, &mut p_id, &mut p_idx); }, + 0x59 => { send_payment(&nodes[1], &nodes[0], chan_a, 100, &mut p_id, &mut p_idx); }, + 0x5a => { send_payment(&nodes[1], &nodes[2], chan_b, 100, &mut p_id, &mut p_idx); }, + 0x5b => { send_payment(&nodes[2], &nodes[1], chan_b, 100, &mut p_id, &mut p_idx); }, + 0x5c => { send_hop_payment(&nodes[0], &nodes[1], chan_a, &nodes[2], chan_b, 100, &mut p_id, &mut p_idx); }, + 0x5d => { send_hop_payment(&nodes[2], &nodes[1], chan_b, &nodes[0], chan_a, 100, &mut p_id, &mut p_idx); }, + + 0x60 => { send_payment(&nodes[0], &nodes[1], chan_a, 10, &mut p_id, &mut p_idx); }, + 0x61 => { send_payment(&nodes[1], &nodes[0], chan_a, 10, &mut p_id, &mut p_idx); }, + 0x62 => { send_payment(&nodes[1], &nodes[2], chan_b, 10, &mut p_id, &mut p_idx); }, + 0x63 => { send_payment(&nodes[2], &nodes[1], chan_b, 10, &mut p_id, &mut p_idx); }, + 0x64 => { send_hop_payment(&nodes[0], &nodes[1], chan_a, &nodes[2], chan_b, 10, &mut p_id, &mut p_idx); }, + 0x65 => { send_hop_payment(&nodes[2], &nodes[1], chan_b, &nodes[0], chan_a, 10, &mut p_id, &mut p_idx); }, + + 0x68 => { send_payment(&nodes[0], &nodes[1], chan_a, 1, &mut p_id, &mut p_idx); }, + 0x69 => { send_payment(&nodes[1], &nodes[0], chan_a, 1, &mut p_id, &mut p_idx); }, + 0x6a => { send_payment(&nodes[1], &nodes[2], chan_b, 1, &mut p_id, &mut p_idx); }, + 0x6b => { send_payment(&nodes[2], &nodes[1], chan_b, 1, &mut p_id, &mut p_idx); }, + 0x6c => { send_hop_payment(&nodes[0], &nodes[1], chan_a, &nodes[2], chan_b, 1, &mut p_id, &mut p_idx); }, + 0x6d => { send_hop_payment(&nodes[2], &nodes[1], chan_b, &nodes[0], chan_a, 1, &mut p_id, &mut p_idx); }, 0x80 => { let mut max_feerate = last_htlc_clear_fee_a; @@ -1377,21 +1389,25 @@ pub fn do_test(data: &[u8], underlying_out: Out, anchors: bool) { // Next, make sure peers are all connected to each other if chan_a_disconnected { - nodes[0].peer_connected(&nodes[1].get_our_node_id(), &Init { + let init_1 = Init { features: nodes[1].init_features(), networks: None, remote_network_address: None - }, true).unwrap(); - nodes[1].peer_connected(&nodes[0].get_our_node_id(), &Init { + }; + nodes[0].peer_connected(&nodes[1].get_our_node_id(), &init_1, true).unwrap(); + let init_0 = Init { features: nodes[0].init_features(), networks: None, remote_network_address: None - }, false).unwrap(); + }; + nodes[1].peer_connected(&nodes[0].get_our_node_id(), &init_0, false).unwrap(); chan_a_disconnected = false; } if chan_b_disconnected { - nodes[1].peer_connected(&nodes[2].get_our_node_id(), &Init { + let init_2 = Init { features: nodes[2].init_features(), networks: None, remote_network_address: None - }, true).unwrap(); - nodes[2].peer_connected(&nodes[1].get_our_node_id(), &Init { + }; + nodes[1].peer_connected(&nodes[2].get_our_node_id(), &init_2, true).unwrap(); + let init_1 = Init { features: nodes[1].init_features(), networks: None, remote_network_address: None - }, false).unwrap(); + }; + nodes[2].peer_connected(&nodes[1].get_our_node_id(), &init_1, false).unwrap(); chan_b_disconnected = false; } @@ -1411,11 +1427,11 @@ pub fn do_test(data: &[u8], underlying_out: Out, anchors: bool) { // Finally, make sure that at least one end of each channel can make a substantial payment assert!( - send_payment(&nodes[0], &nodes[1], chan_a, 10_000_000, &mut payment_id, &mut payment_idx) || - send_payment(&nodes[1], &nodes[0], chan_a, 10_000_000, &mut payment_id, &mut payment_idx)); + send_payment(&nodes[0], &nodes[1], chan_a, 10_000_000, &mut p_id, &mut p_idx) || + send_payment(&nodes[1], &nodes[0], chan_a, 10_000_000, &mut p_id, &mut p_idx)); assert!( - send_payment(&nodes[1], &nodes[2], chan_b, 10_000_000, &mut payment_id, &mut payment_idx) || - send_payment(&nodes[2], &nodes[1], chan_b, 10_000_000, &mut payment_id, &mut payment_idx)); + send_payment(&nodes[1], &nodes[2], chan_b, 10_000_000, &mut p_id, &mut p_idx) || + send_payment(&nodes[2], &nodes[1], chan_b, 10_000_000, &mut p_id, &mut p_idx)); last_htlc_clear_fee_a = fee_est_a.ret_val.load(atomic::Ordering::Acquire); last_htlc_clear_fee_b = fee_est_b.ret_val.load(atomic::Ordering::Acquire); From 7b3e9a82f8322e75a90f13b9e87ae3f279f51ca7 Mon Sep 17 00:00:00 2001 From: Elias Rohrer Date: Wed, 12 Jun 2024 19:51:10 +0200 Subject: [PATCH 2/5] Introduce `noret` wrappers --- fuzz/src/chanmon_consistency.rs | 181 ++++++++++++++++++-------------- 1 file changed, 102 insertions(+), 79 deletions(-) diff --git a/fuzz/src/chanmon_consistency.rs b/fuzz/src/chanmon_consistency.rs index a311ee9f7f2..582f2d736cd 100644 --- a/fuzz/src/chanmon_consistency.rs +++ b/fuzz/src/chanmon_consistency.rs @@ -422,6 +422,11 @@ fn get_payment_secret_hash(dest: &ChanMan, payment_id: &mut u8) -> Option<(Payme None } +#[inline] +fn send_noret(source: &ChanMan, dest: &ChanMan, dest_chan_id: u64, amt: u64, payment_id: &mut u8, payment_idx: &mut u64) { + send_payment(source, dest, dest_chan_id, amt, payment_id, payment_idx); +} + #[inline] fn send_payment(source: &ChanMan, dest: &ChanMan, dest_chan_id: u64, amt: u64, payment_id: &mut u8, payment_idx: &mut u64) -> bool { let (payment_secret, payment_hash) = @@ -456,6 +461,12 @@ fn send_payment(source: &ChanMan, dest: &ChanMan, dest_chan_id: u64, amt: u64, p true } } + +#[inline] +fn send_hop_noret(source: &ChanMan, middle: &ChanMan, middle_chan_id: u64, dest: &ChanMan, dest_chan_id: u64, amt: u64, payment_id: &mut u8, payment_idx: &mut u64) { + send_hop_payment(source, middle, middle_chan_id, dest, dest_chan_id, amt, payment_id, payment_idx); +} + #[inline] fn send_hop_payment(source: &ChanMan, middle: &ChanMan, middle_chan_id: u64, dest: &ChanMan, dest_chan_id: u64, amt: u64, payment_id: &mut u8, payment_idx: &mut u64) -> bool { let (payment_secret, payment_hash) = @@ -980,6 +991,12 @@ pub fn do_test(data: &[u8], underlying_out: Out, anchors: bool) { } } } + macro_rules! process_msg_noret { + ($node: expr, $corrupt_forward: expr, $limit_events: expr) => { { + process_msg_events!($node, $corrupt_forward, $limit_events); + } } + } + macro_rules! drain_msg_events_on_disconnect { ($counterparty_id: expr) => { { if $counterparty_id == 0 { @@ -1091,6 +1108,12 @@ pub fn do_test(data: &[u8], underlying_out: Out, anchors: bool) { } } } + macro_rules! process_ev_noret { + ($node: expr, $fail: expr) => { { + process_events!($node, $fail); + } } + } + let complete_first = |v: &mut Vec<_>| if !v.is_empty() { Some(v.remove(0)) } else { None }; let complete_second = |v: &mut Vec<_>| if v.len() > 1 { Some(v.remove(1)) } else { None }; let complete_monitor_update = | @@ -1190,35 +1213,35 @@ pub fn do_test(data: &[u8], underlying_out: Out, anchors: bool) { } }, - 0x10 => { process_msg_events!(0, true, ProcessMessages::AllMessages); }, - 0x11 => { process_msg_events!(0, false, ProcessMessages::AllMessages); }, - 0x12 => { process_msg_events!(0, true, ProcessMessages::OneMessage); }, - 0x13 => { process_msg_events!(0, false, ProcessMessages::OneMessage); }, - 0x14 => { process_msg_events!(0, true, ProcessMessages::OnePendingMessage); }, - 0x15 => { process_msg_events!(0, false, ProcessMessages::OnePendingMessage); }, + 0x10 => process_msg_noret!(0, true, ProcessMessages::AllMessages), + 0x11 => process_msg_noret!(0, false, ProcessMessages::AllMessages), + 0x12 => process_msg_noret!(0, true, ProcessMessages::OneMessage), + 0x13 => process_msg_noret!(0, false, ProcessMessages::OneMessage), + 0x14 => process_msg_noret!(0, true, ProcessMessages::OnePendingMessage), + 0x15 => process_msg_noret!(0, false, ProcessMessages::OnePendingMessage), - 0x16 => { process_events!(0, true); }, - 0x17 => { process_events!(0, false); }, + 0x16 => process_ev_noret!(0, true), + 0x17 => process_ev_noret!(0, false), - 0x18 => { process_msg_events!(1, true, ProcessMessages::AllMessages); }, - 0x19 => { process_msg_events!(1, false, ProcessMessages::AllMessages); }, - 0x1a => { process_msg_events!(1, true, ProcessMessages::OneMessage); }, - 0x1b => { process_msg_events!(1, false, ProcessMessages::OneMessage); }, - 0x1c => { process_msg_events!(1, true, ProcessMessages::OnePendingMessage); }, - 0x1d => { process_msg_events!(1, false, ProcessMessages::OnePendingMessage); }, + 0x18 => process_msg_noret!(1, true, ProcessMessages::AllMessages), + 0x19 => process_msg_noret!(1, false, ProcessMessages::AllMessages), + 0x1a => process_msg_noret!(1, true, ProcessMessages::OneMessage), + 0x1b => process_msg_noret!(1, false, ProcessMessages::OneMessage), + 0x1c => process_msg_noret!(1, true, ProcessMessages::OnePendingMessage), + 0x1d => process_msg_noret!(1, false, ProcessMessages::OnePendingMessage), - 0x1e => { process_events!(1, true); }, - 0x1f => { process_events!(1, false); }, + 0x1e => process_ev_noret!(1, true), + 0x1f => process_ev_noret!(1, false), - 0x20 => { process_msg_events!(2, true, ProcessMessages::AllMessages); }, - 0x21 => { process_msg_events!(2, false, ProcessMessages::AllMessages); }, - 0x22 => { process_msg_events!(2, true, ProcessMessages::OneMessage); }, - 0x23 => { process_msg_events!(2, false, ProcessMessages::OneMessage); }, - 0x24 => { process_msg_events!(2, true, ProcessMessages::OnePendingMessage); }, - 0x25 => { process_msg_events!(2, false, ProcessMessages::OnePendingMessage); }, + 0x20 => process_msg_noret!(2, true, ProcessMessages::AllMessages), + 0x21 => process_msg_noret!(2, false, ProcessMessages::AllMessages), + 0x22 => process_msg_noret!(2, true, ProcessMessages::OneMessage), + 0x23 => process_msg_noret!(2, false, ProcessMessages::OneMessage), + 0x24 => process_msg_noret!(2, true, ProcessMessages::OnePendingMessage), + 0x25 => process_msg_noret!(2, false, ProcessMessages::OnePendingMessage), - 0x26 => { process_events!(2, true); }, - 0x27 => { process_events!(2, false); }, + 0x26 => process_ev_noret!(2, true), + 0x27 => process_ev_noret!(2, false), 0x2c => { if !chan_a_disconnected { @@ -1265,61 +1288,61 @@ pub fn do_test(data: &[u8], underlying_out: Out, anchors: bool) { }, // 1/10th the channel size: - 0x30 => { send_payment(&nodes[0], &nodes[1], chan_a, 10_000_000, &mut p_id, &mut p_idx); }, - 0x31 => { send_payment(&nodes[1], &nodes[0], chan_a, 10_000_000, &mut p_id, &mut p_idx); }, - 0x32 => { send_payment(&nodes[1], &nodes[2], chan_b, 10_000_000, &mut p_id, &mut p_idx); }, - 0x33 => { send_payment(&nodes[2], &nodes[1], chan_b, 10_000_000, &mut p_id, &mut p_idx); }, - 0x34 => { send_hop_payment(&nodes[0], &nodes[1], chan_a, &nodes[2], chan_b, 10_000_000, &mut p_id, &mut p_idx); }, - 0x35 => { send_hop_payment(&nodes[2], &nodes[1], chan_b, &nodes[0], chan_a, 10_000_000, &mut p_id, &mut p_idx); }, - - 0x38 => { send_payment(&nodes[0], &nodes[1], chan_a, 1_000_000, &mut p_id, &mut p_idx); }, - 0x39 => { send_payment(&nodes[1], &nodes[0], chan_a, 1_000_000, &mut p_id, &mut p_idx); }, - 0x3a => { send_payment(&nodes[1], &nodes[2], chan_b, 1_000_000, &mut p_id, &mut p_idx); }, - 0x3b => { send_payment(&nodes[2], &nodes[1], chan_b, 1_000_000, &mut p_id, &mut p_idx); }, - 0x3c => { send_hop_payment(&nodes[0], &nodes[1], chan_a, &nodes[2], chan_b, 1_000_000, &mut p_id, &mut p_idx); }, - 0x3d => { send_hop_payment(&nodes[2], &nodes[1], chan_b, &nodes[0], chan_a, 1_000_000, &mut p_id, &mut p_idx); }, - - 0x40 => { send_payment(&nodes[0], &nodes[1], chan_a, 100_000, &mut p_id, &mut p_idx); }, - 0x41 => { send_payment(&nodes[1], &nodes[0], chan_a, 100_000, &mut p_id, &mut p_idx); }, - 0x42 => { send_payment(&nodes[1], &nodes[2], chan_b, 100_000, &mut p_id, &mut p_idx); }, - 0x43 => { send_payment(&nodes[2], &nodes[1], chan_b, 100_000, &mut p_id, &mut p_idx); }, - 0x44 => { send_hop_payment(&nodes[0], &nodes[1], chan_a, &nodes[2], chan_b, 100_000, &mut p_id, &mut p_idx); }, - 0x45 => { send_hop_payment(&nodes[2], &nodes[1], chan_b, &nodes[0], chan_a, 100_000, &mut p_id, &mut p_idx); }, - - 0x48 => { send_payment(&nodes[0], &nodes[1], chan_a, 10_000, &mut p_id, &mut p_idx); }, - 0x49 => { send_payment(&nodes[1], &nodes[0], chan_a, 10_000, &mut p_id, &mut p_idx); }, - 0x4a => { send_payment(&nodes[1], &nodes[2], chan_b, 10_000, &mut p_id, &mut p_idx); }, - 0x4b => { send_payment(&nodes[2], &nodes[1], chan_b, 10_000, &mut p_id, &mut p_idx); }, - 0x4c => { send_hop_payment(&nodes[0], &nodes[1], chan_a, &nodes[2], chan_b, 10_000, &mut p_id, &mut p_idx); }, - 0x4d => { send_hop_payment(&nodes[2], &nodes[1], chan_b, &nodes[0], chan_a, 10_000, &mut p_id, &mut p_idx); }, - - 0x50 => { send_payment(&nodes[0], &nodes[1], chan_a, 1_000, &mut p_id, &mut p_idx); }, - 0x51 => { send_payment(&nodes[1], &nodes[0], chan_a, 1_000, &mut p_id, &mut p_idx); }, - 0x52 => { send_payment(&nodes[1], &nodes[2], chan_b, 1_000, &mut p_id, &mut p_idx); }, - 0x53 => { send_payment(&nodes[2], &nodes[1], chan_b, 1_000, &mut p_id, &mut p_idx); }, - 0x54 => { send_hop_payment(&nodes[0], &nodes[1], chan_a, &nodes[2], chan_b, 1_000, &mut p_id, &mut p_idx); }, - 0x55 => { send_hop_payment(&nodes[2], &nodes[1], chan_b, &nodes[0], chan_a, 1_000, &mut p_id, &mut p_idx); }, - - 0x58 => { send_payment(&nodes[0], &nodes[1], chan_a, 100, &mut p_id, &mut p_idx); }, - 0x59 => { send_payment(&nodes[1], &nodes[0], chan_a, 100, &mut p_id, &mut p_idx); }, - 0x5a => { send_payment(&nodes[1], &nodes[2], chan_b, 100, &mut p_id, &mut p_idx); }, - 0x5b => { send_payment(&nodes[2], &nodes[1], chan_b, 100, &mut p_id, &mut p_idx); }, - 0x5c => { send_hop_payment(&nodes[0], &nodes[1], chan_a, &nodes[2], chan_b, 100, &mut p_id, &mut p_idx); }, - 0x5d => { send_hop_payment(&nodes[2], &nodes[1], chan_b, &nodes[0], chan_a, 100, &mut p_id, &mut p_idx); }, - - 0x60 => { send_payment(&nodes[0], &nodes[1], chan_a, 10, &mut p_id, &mut p_idx); }, - 0x61 => { send_payment(&nodes[1], &nodes[0], chan_a, 10, &mut p_id, &mut p_idx); }, - 0x62 => { send_payment(&nodes[1], &nodes[2], chan_b, 10, &mut p_id, &mut p_idx); }, - 0x63 => { send_payment(&nodes[2], &nodes[1], chan_b, 10, &mut p_id, &mut p_idx); }, - 0x64 => { send_hop_payment(&nodes[0], &nodes[1], chan_a, &nodes[2], chan_b, 10, &mut p_id, &mut p_idx); }, - 0x65 => { send_hop_payment(&nodes[2], &nodes[1], chan_b, &nodes[0], chan_a, 10, &mut p_id, &mut p_idx); }, - - 0x68 => { send_payment(&nodes[0], &nodes[1], chan_a, 1, &mut p_id, &mut p_idx); }, - 0x69 => { send_payment(&nodes[1], &nodes[0], chan_a, 1, &mut p_id, &mut p_idx); }, - 0x6a => { send_payment(&nodes[1], &nodes[2], chan_b, 1, &mut p_id, &mut p_idx); }, - 0x6b => { send_payment(&nodes[2], &nodes[1], chan_b, 1, &mut p_id, &mut p_idx); }, - 0x6c => { send_hop_payment(&nodes[0], &nodes[1], chan_a, &nodes[2], chan_b, 1, &mut p_id, &mut p_idx); }, - 0x6d => { send_hop_payment(&nodes[2], &nodes[1], chan_b, &nodes[0], chan_a, 1, &mut p_id, &mut p_idx); }, + 0x30 => send_noret(&nodes[0], &nodes[1], chan_a, 10_000_000, &mut p_id, &mut p_idx), + 0x31 => send_noret(&nodes[1], &nodes[0], chan_a, 10_000_000, &mut p_id, &mut p_idx), + 0x32 => send_noret(&nodes[1], &nodes[2], chan_b, 10_000_000, &mut p_id, &mut p_idx), + 0x33 => send_noret(&nodes[2], &nodes[1], chan_b, 10_000_000, &mut p_id, &mut p_idx), + 0x34 => send_hop_noret(&nodes[0], &nodes[1], chan_a, &nodes[2], chan_b, 10_000_000, &mut p_id, &mut p_idx), + 0x35 => send_hop_noret(&nodes[2], &nodes[1], chan_b, &nodes[0], chan_a, 10_000_000, &mut p_id, &mut p_idx), + + 0x38 => send_noret(&nodes[0], &nodes[1], chan_a, 1_000_000, &mut p_id, &mut p_idx), + 0x39 => send_noret(&nodes[1], &nodes[0], chan_a, 1_000_000, &mut p_id, &mut p_idx), + 0x3a => send_noret(&nodes[1], &nodes[2], chan_b, 1_000_000, &mut p_id, &mut p_idx), + 0x3b => send_noret(&nodes[2], &nodes[1], chan_b, 1_000_000, &mut p_id, &mut p_idx), + 0x3c => send_hop_noret(&nodes[0], &nodes[1], chan_a, &nodes[2], chan_b, 1_000_000, &mut p_id, &mut p_idx), + 0x3d => send_hop_noret(&nodes[2], &nodes[1], chan_b, &nodes[0], chan_a, 1_000_000, &mut p_id, &mut p_idx), + + 0x40 => send_noret(&nodes[0], &nodes[1], chan_a, 100_000, &mut p_id, &mut p_idx), + 0x41 => send_noret(&nodes[1], &nodes[0], chan_a, 100_000, &mut p_id, &mut p_idx), + 0x42 => send_noret(&nodes[1], &nodes[2], chan_b, 100_000, &mut p_id, &mut p_idx), + 0x43 => send_noret(&nodes[2], &nodes[1], chan_b, 100_000, &mut p_id, &mut p_idx), + 0x44 => send_hop_noret(&nodes[0], &nodes[1], chan_a, &nodes[2], chan_b, 100_000, &mut p_id, &mut p_idx), + 0x45 => send_hop_noret(&nodes[2], &nodes[1], chan_b, &nodes[0], chan_a, 100_000, &mut p_id, &mut p_idx), + + 0x48 => send_noret(&nodes[0], &nodes[1], chan_a, 10_000, &mut p_id, &mut p_idx), + 0x49 => send_noret(&nodes[1], &nodes[0], chan_a, 10_000, &mut p_id, &mut p_idx), + 0x4a => send_noret(&nodes[1], &nodes[2], chan_b, 10_000, &mut p_id, &mut p_idx), + 0x4b => send_noret(&nodes[2], &nodes[1], chan_b, 10_000, &mut p_id, &mut p_idx), + 0x4c => send_hop_noret(&nodes[0], &nodes[1], chan_a, &nodes[2], chan_b, 10_000, &mut p_id, &mut p_idx), + 0x4d => send_hop_noret(&nodes[2], &nodes[1], chan_b, &nodes[0], chan_a, 10_000, &mut p_id, &mut p_idx), + + 0x50 => send_noret(&nodes[0], &nodes[1], chan_a, 1_000, &mut p_id, &mut p_idx), + 0x51 => send_noret(&nodes[1], &nodes[0], chan_a, 1_000, &mut p_id, &mut p_idx), + 0x52 => send_noret(&nodes[1], &nodes[2], chan_b, 1_000, &mut p_id, &mut p_idx), + 0x53 => send_noret(&nodes[2], &nodes[1], chan_b, 1_000, &mut p_id, &mut p_idx), + 0x54 => send_hop_noret(&nodes[0], &nodes[1], chan_a, &nodes[2], chan_b, 1_000, &mut p_id, &mut p_idx), + 0x55 => send_hop_noret(&nodes[2], &nodes[1], chan_b, &nodes[0], chan_a, 1_000, &mut p_id, &mut p_idx), + + 0x58 => send_noret(&nodes[0], &nodes[1], chan_a, 100, &mut p_id, &mut p_idx), + 0x59 => send_noret(&nodes[1], &nodes[0], chan_a, 100, &mut p_id, &mut p_idx), + 0x5a => send_noret(&nodes[1], &nodes[2], chan_b, 100, &mut p_id, &mut p_idx), + 0x5b => send_noret(&nodes[2], &nodes[1], chan_b, 100, &mut p_id, &mut p_idx), + 0x5c => send_hop_noret(&nodes[0], &nodes[1], chan_a, &nodes[2], chan_b, 100, &mut p_id, &mut p_idx), + 0x5d => send_hop_noret(&nodes[2], &nodes[1], chan_b, &nodes[0], chan_a, 100, &mut p_id, &mut p_idx), + + 0x60 => send_noret(&nodes[0], &nodes[1], chan_a, 10, &mut p_id, &mut p_idx), + 0x61 => send_noret(&nodes[1], &nodes[0], chan_a, 10, &mut p_id, &mut p_idx), + 0x62 => send_noret(&nodes[1], &nodes[2], chan_b, 10, &mut p_id, &mut p_idx), + 0x63 => send_noret(&nodes[2], &nodes[1], chan_b, 10, &mut p_id, &mut p_idx), + 0x64 => send_hop_noret(&nodes[0], &nodes[1], chan_a, &nodes[2], chan_b, 10, &mut p_id, &mut p_idx), + 0x65 => send_hop_noret(&nodes[2], &nodes[1], chan_b, &nodes[0], chan_a, 10, &mut p_id, &mut p_idx), + + 0x68 => send_noret(&nodes[0], &nodes[1], chan_a, 1, &mut p_id, &mut p_idx), + 0x69 => send_noret(&nodes[1], &nodes[0], chan_a, 1, &mut p_id, &mut p_idx), + 0x6a => send_noret(&nodes[1], &nodes[2], chan_b, 1, &mut p_id, &mut p_idx), + 0x6b => send_noret(&nodes[2], &nodes[1], chan_b, 1, &mut p_id, &mut p_idx), + 0x6c => send_hop_noret(&nodes[0], &nodes[1], chan_a, &nodes[2], chan_b, 1, &mut p_id, &mut p_idx), + 0x6d => send_hop_noret(&nodes[2], &nodes[1], chan_b, &nodes[0], chan_a, 1, &mut p_id, &mut p_idx), 0x80 => { let mut max_feerate = last_htlc_clear_fee_a; From 0583f643b990a6b671a8529bcb784c9c214ddf34 Mon Sep 17 00:00:00 2001 From: Elias Rohrer Date: Mon, 10 Jun 2024 10:37:50 +0200 Subject: [PATCH 3/5] `rustfmt`: `fuzz/src/chanmon_consistency.rs` --- fuzz/src/chanmon_consistency.rs | 953 ++++++++++++++++++++++---------- rustfmt_excluded_files | 1 - 2 files changed, 662 insertions(+), 292 deletions(-) diff --git a/fuzz/src/chanmon_consistency.rs b/fuzz/src/chanmon_consistency.rs index 582f2d736cd..c4d179e745c 100644 --- a/fuzz/src/chanmon_consistency.rs +++ b/fuzz/src/chanmon_consistency.rs @@ -20,61 +20,70 @@ use bitcoin::amount::Amount; use bitcoin::blockdata::constants::genesis_block; -use bitcoin::blockdata::transaction::{Transaction, TxOut}; -use bitcoin::blockdata::script::{Builder, ScriptBuf}; -use bitcoin::blockdata::opcodes; use bitcoin::blockdata::locktime::absolute::LockTime; +use bitcoin::blockdata::opcodes; +use bitcoin::blockdata::script::{Builder, ScriptBuf}; +use bitcoin::blockdata::transaction::{Transaction, TxOut}; use bitcoin::network::Network; use bitcoin::transaction::Version; -use bitcoin::WPubkeyHash; -use bitcoin::hashes::Hash as TraitImport; +use bitcoin::hash_types::BlockHash; use bitcoin::hashes::sha256::Hash as Sha256; use bitcoin::hashes::sha256d::Hash as Sha256dHash; -use bitcoin::hash_types::BlockHash; +use bitcoin::hashes::Hash as TraitImport; +use bitcoin::WPubkeyHash; -use lightning::blinded_path::BlindedPath; use lightning::blinded_path::payment::ReceiveTlvs; +use lightning::blinded_path::BlindedPath; use lightning::chain; -use lightning::chain::{BestBlock, ChannelMonitorUpdateStatus, chainmonitor, channelmonitor, Confirm, Watch}; +use lightning::chain::chaininterface::{BroadcasterInterface, ConfirmationTarget, FeeEstimator}; use lightning::chain::channelmonitor::{ChannelMonitor, MonitorEvent}; use lightning::chain::transaction::OutPoint; -use lightning::chain::chaininterface::{BroadcasterInterface, ConfirmationTarget, FeeEstimator}; -use lightning::sign::{KeyMaterial, InMemorySigner, Recipient, EntropySource, NodeSigner, SignerProvider}; +use lightning::chain::{ + chainmonitor, channelmonitor, BestBlock, ChannelMonitorUpdateStatus, Confirm, Watch, +}; use lightning::events; use lightning::events::MessageSendEventsProvider; -use lightning::ln::{ChannelId, PaymentHash, PaymentPreimage, PaymentSecret}; -use lightning::ln::channel_state::ChannelDetails; -use lightning::ln::channelmanager::{ChainParameters,ChannelManager, PaymentSendFailure, ChannelManagerReadArgs, PaymentId, RecipientOnionFields}; use lightning::ln::channel::FEE_SPIKE_BUFFER_FEE_INCREASE_MULTIPLE; -use lightning::ln::msgs::{self, CommitmentUpdate, ChannelMessageHandler, DecodeError, UpdateAddHTLC, Init}; -use lightning::ln::script::ShutdownScript; +use lightning::ln::channel_state::ChannelDetails; +use lightning::ln::channelmanager::{ + ChainParameters, ChannelManager, ChannelManagerReadArgs, PaymentId, PaymentSendFailure, + RecipientOnionFields, +}; use lightning::ln::functional_test_utils::*; +use lightning::ln::msgs::{ + self, ChannelMessageHandler, CommitmentUpdate, DecodeError, Init, UpdateAddHTLC, +}; +use lightning::ln::script::ShutdownScript; +use lightning::ln::{ChannelId, PaymentHash, PaymentPreimage, PaymentSecret}; use lightning::offers::invoice::{BlindedPayInfo, UnsignedBolt12Invoice}; use lightning::offers::invoice_request::UnsignedInvoiceRequest; use lightning::onion_message::messenger::{Destination, MessageRouter, OnionMessagePath}; -use lightning::util::test_channel_signer::{TestChannelSigner, EnforcementState}; +use lightning::routing::router::{InFlightHtlcs, Path, Route, RouteHop, RouteParameters, Router}; +use lightning::sign::{ + EntropySource, InMemorySigner, KeyMaterial, NodeSigner, Recipient, SignerProvider, +}; +use lightning::util::config::UserConfig; use lightning::util::errors::APIError; use lightning::util::hash_tables::*; use lightning::util::logger::Logger; -use lightning::util::config::UserConfig; use lightning::util::ser::{Readable, ReadableArgs, Writeable, Writer}; -use lightning::routing::router::{InFlightHtlcs, Path, Route, RouteHop, RouteParameters, Router}; +use lightning::util::test_channel_signer::{EnforcementState, TestChannelSigner}; use crate::utils::test_logger::{self, Output}; use crate::utils::test_persister::TestPersister; -use bitcoin::secp256k1::{Message, PublicKey, SecretKey, Scalar, Secp256k1, self}; use bitcoin::secp256k1::ecdh::SharedSecret; use bitcoin::secp256k1::ecdsa::{RecoverableSignature, Signature}; use bitcoin::secp256k1::schnorr; +use bitcoin::secp256k1::{self, Message, PublicKey, Scalar, Secp256k1, SecretKey}; -use std::mem; +use bech32::u5; use std::cmp::{self, Ordering}; -use std::sync::{Arc,Mutex}; -use std::sync::atomic; use std::io::Cursor; -use bech32::u5; +use std::mem; +use std::sync::atomic; +use std::sync::{Arc, Mutex}; const MAX_FEE: u32 = 10_000; struct FuzzEstimator { @@ -88,8 +97,14 @@ impl FeeEstimator for FuzzEstimator { // Background feerate which is <= the minimum Normal feerate. match conf_target { ConfirmationTarget::OnChainSweep => MAX_FEE, - ConfirmationTarget::ChannelCloseMinimum|ConfirmationTarget::AnchorChannelFee|ConfirmationTarget::MinAllowedAnchorChannelRemoteFee|ConfirmationTarget::MinAllowedNonAnchorChannelRemoteFee|ConfirmationTarget::OutputSpendingFee => 253, - ConfirmationTarget::NonAnchorChannelFee => cmp::min(self.ret_val.load(atomic::Ordering::Acquire), MAX_FEE), + ConfirmationTarget::ChannelCloseMinimum + | ConfirmationTarget::AnchorChannelFee + | ConfirmationTarget::MinAllowedAnchorChannelRemoteFee + | ConfirmationTarget::MinAllowedNonAnchorChannelRemoteFee + | ConfirmationTarget::OutputSpendingFee => 253, + ConfirmationTarget::NonAnchorChannelFee => { + cmp::min(self.ret_val.load(atomic::Ordering::Acquire), MAX_FEE) + }, } } } @@ -98,12 +113,12 @@ struct FuzzRouter {} impl Router for FuzzRouter { fn find_route( - &self, _payer: &PublicKey, _params: &RouteParameters, _first_hops: Option<&[&ChannelDetails]>, - _inflight_htlcs: InFlightHtlcs + &self, _payer: &PublicKey, _params: &RouteParameters, + _first_hops: Option<&[&ChannelDetails]>, _inflight_htlcs: InFlightHtlcs, ) -> Result { Err(msgs::LightningError { err: String::from("Not implemented"), - action: msgs::ErrorAction::IgnoreError + action: msgs::ErrorAction::IgnoreError, }) } @@ -117,7 +132,7 @@ impl Router for FuzzRouter { impl MessageRouter for FuzzRouter { fn find_path( - &self, _sender: PublicKey, _peers: Vec, _destination: Destination + &self, _sender: PublicKey, _peers: Vec, _destination: Destination, ) -> Result { unreachable!() } @@ -131,7 +146,7 @@ impl MessageRouter for FuzzRouter { pub struct TestBroadcaster {} impl BroadcasterInterface for TestBroadcaster { - fn broadcast_transactions(&self, _txs: &[&Transaction]) { } + fn broadcast_transactions(&self, _txs: &[&Transaction]) {} } pub struct VecWriter(pub Vec); @@ -163,13 +178,31 @@ struct TestChainMonitor { pub logger: Arc, pub keys: Arc, pub persister: Arc, - pub chain_monitor: Arc, Arc, Arc, Arc, Arc>>, + pub chain_monitor: Arc< + chainmonitor::ChainMonitor< + TestChannelSigner, + Arc, + Arc, + Arc, + Arc, + Arc, + >, + >, pub latest_monitors: Mutex>, } impl TestChainMonitor { - pub fn new(broadcaster: Arc, logger: Arc, feeest: Arc, persister: Arc, keys: Arc) -> Self { + pub fn new( + broadcaster: Arc, logger: Arc, feeest: Arc, + persister: Arc, keys: Arc, + ) -> Self { Self { - chain_monitor: Arc::new(chainmonitor::ChainMonitor::new(None, broadcaster, logger.clone(), feeest, Arc::clone(&persister))), + chain_monitor: Arc::new(chainmonitor::ChainMonitor::new( + None, + broadcaster, + logger.clone(), + feeest, + Arc::clone(&persister), + )), logger, keys, persister, @@ -178,20 +211,22 @@ impl TestChainMonitor { } } impl chain::Watch for TestChainMonitor { - fn watch_channel(&self, funding_txo: OutPoint, monitor: channelmonitor::ChannelMonitor) -> Result { + fn watch_channel( + &self, funding_txo: OutPoint, monitor: channelmonitor::ChannelMonitor, + ) -> Result { let mut ser = VecWriter(Vec::new()); monitor.write(&mut ser).unwrap(); let monitor_id = monitor.get_latest_update_id(); let res = self.chain_monitor.watch_channel(funding_txo, monitor); let state = match res { - Ok(chain::ChannelMonitorUpdateStatus::Completed) => { - LatestMonitorState { - persisted_monitor_id: monitor_id, persisted_monitor: ser.0, - pending_monitors: Vec::new(), - } + Ok(chain::ChannelMonitorUpdateStatus::Completed) => LatestMonitorState { + persisted_monitor_id: monitor_id, + persisted_monitor: ser.0, + pending_monitors: Vec::new(), + }, + Ok(chain::ChannelMonitorUpdateStatus::InProgress) => { + panic!("The test currently doesn't test initial-persistence via the async pipeline") }, - Ok(chain::ChannelMonitorUpdateStatus::InProgress) => - panic!("The test currently doesn't test initial-persistence via the async pipeline"), Ok(chain::ChannelMonitorUpdateStatus::UnrecoverableError) => panic!(), Err(()) => panic!(), }; @@ -201,13 +236,32 @@ impl chain::Watch for TestChainMonitor { res } - fn update_channel(&self, funding_txo: OutPoint, update: &channelmonitor::ChannelMonitorUpdate) -> chain::ChannelMonitorUpdateStatus { + fn update_channel( + &self, funding_txo: OutPoint, update: &channelmonitor::ChannelMonitorUpdate, + ) -> chain::ChannelMonitorUpdateStatus { let mut map_lock = self.latest_monitors.lock().unwrap(); let map_entry = map_lock.get_mut(&funding_txo).expect("Didn't have monitor on update call"); - let latest_monitor_data = map_entry.pending_monitors.last().as_ref().map(|(_, data)| data).unwrap_or(&map_entry.persisted_monitor); - let deserialized_monitor = <(BlockHash, channelmonitor::ChannelMonitor)>:: - read(&mut Cursor::new(&latest_monitor_data), (&*self.keys, &*self.keys)).unwrap().1; - deserialized_monitor.update_monitor(update, &&TestBroadcaster{}, &&FuzzEstimator { ret_val: atomic::AtomicU32::new(253) }, &self.logger).unwrap(); + let latest_monitor_data = map_entry + .pending_monitors + .last() + .as_ref() + .map(|(_, data)| data) + .unwrap_or(&map_entry.persisted_monitor); + let deserialized_monitor = + <(BlockHash, channelmonitor::ChannelMonitor)>::read( + &mut Cursor::new(&latest_monitor_data), + (&*self.keys, &*self.keys), + ) + .unwrap() + .1; + deserialized_monitor + .update_monitor( + update, + &&TestBroadcaster {}, + &&FuzzEstimator { ret_val: atomic::AtomicU32::new(253) }, + &self.logger, + ) + .unwrap(); let mut ser = VecWriter(Vec::new()); deserialized_monitor.write(&mut ser).unwrap(); let res = self.chain_monitor.update_channel(funding_txo, update); @@ -224,7 +278,9 @@ impl chain::Watch for TestChainMonitor { res } - fn release_pending_monitor_events(&self) -> Vec<(OutPoint, ChannelId, Vec, Option)> { + fn release_pending_monitor_events( + &self, + ) -> Vec<(OutPoint, ChannelId, Vec, Option)> { return self.chain_monitor.release_pending_monitor_events(); } } @@ -232,7 +288,7 @@ impl chain::Watch for TestChainMonitor { struct KeyProvider { node_secret: SecretKey, rand_bytes_id: atomic::AtomicU32, - enforcement_states: Mutex>>>, + enforcement_states: Mutex>>>, } impl EntropySource for KeyProvider { @@ -240,7 +296,7 @@ impl EntropySource for KeyProvider { let id = self.rand_bytes_id.fetch_add(1, atomic::Ordering::Relaxed); #[rustfmt::skip] let mut res = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 11, self.node_secret[31]]; - res[30-4..30].copy_from_slice(&id.to_le_bytes()); + res[30 - 4..30].copy_from_slice(&id.to_le_bytes()); res } } @@ -249,15 +305,17 @@ impl NodeSigner for KeyProvider { fn get_node_id(&self, recipient: Recipient) -> Result { let node_secret = match recipient { Recipient::Node => Ok(&self.node_secret), - Recipient::PhantomNode => Err(()) + Recipient::PhantomNode => Err(()), }?; Ok(PublicKey::from_secret_key(&Secp256k1::signing_only(), node_secret)) } - fn ecdh(&self, recipient: Recipient, other_key: &PublicKey, tweak: Option<&Scalar>) -> Result { + fn ecdh( + &self, recipient: Recipient, other_key: &PublicKey, tweak: Option<&Scalar>, + ) -> Result { let mut node_secret = match recipient { Recipient::Node => Ok(self.node_secret.clone()), - Recipient::PhantomNode => Err(()) + Recipient::PhantomNode => Err(()), }?; if let Some(tweak) = tweak { node_secret = node_secret.mul_tweak(tweak).map_err(|_| ())?; @@ -271,12 +329,14 @@ impl NodeSigner for KeyProvider { KeyMaterial(random_bytes) } - fn sign_invoice(&self, _hrp_bytes: &[u8], _invoice_data: &[u5], _recipient: Recipient) -> Result { + fn sign_invoice( + &self, _hrp_bytes: &[u8], _invoice_data: &[u5], _recipient: Recipient, + ) -> Result { unreachable!() } fn sign_bolt12_invoice_request( - &self, _invoice_request: &UnsignedInvoiceRequest + &self, _invoice_request: &UnsignedInvoiceRequest, ) -> Result { unreachable!() } @@ -287,7 +347,9 @@ impl NodeSigner for KeyProvider { unreachable!() } - fn sign_gossip_message(&self, msg: lightning::ln::msgs::UnsignedGossipMessage) -> Result { + fn sign_gossip_message( + &self, msg: lightning::ln::msgs::UnsignedGossipMessage, + ) -> Result { let msg_hash = Message::from_digest(Sha256dHash::hash(&msg.encode()[..]).to_byte_array()); let secp_ctx = Secp256k1::signing_only(); Ok(secp_ctx.sign_ecdsa(&msg_hash, &self.node_secret)) @@ -299,12 +361,16 @@ impl SignerProvider for KeyProvider { #[cfg(taproot)] type TaprootSigner = TestChannelSigner; - fn generate_channel_keys_id(&self, _inbound: bool, _channel_value_satoshis: u64, _user_channel_id: u128) -> [u8; 32] { + fn generate_channel_keys_id( + &self, _inbound: bool, _channel_value_satoshis: u64, _user_channel_id: u128, + ) -> [u8; 32] { let id = self.rand_bytes_id.fetch_add(1, atomic::Ordering::Relaxed) as u8; [id; 32] } - fn derive_channel_signer(&self, channel_value_satoshis: u64, channel_keys_id: [u8; 32]) -> Self::EcdsaSigner { + fn derive_channel_signer( + &self, channel_value_satoshis: u64, channel_keys_id: [u8; 32], + ) -> Self::EcdsaSigner { let secp_ctx = Secp256k1::signing_only(); let id = channel_keys_id[0]; #[rustfmt::skip] @@ -342,24 +408,33 @@ impl SignerProvider for KeyProvider { let secp_ctx = Secp256k1::signing_only(); #[rustfmt::skip] let channel_monitor_claim_key = SecretKey::from_slice(&[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, self.node_secret[31]]).unwrap(); - let our_channel_monitor_claim_key_hash = WPubkeyHash::hash(&PublicKey::from_secret_key(&secp_ctx, &channel_monitor_claim_key).serialize()); - Ok(Builder::new().push_opcode(opcodes::all::OP_PUSHBYTES_0).push_slice(our_channel_monitor_claim_key_hash).into_script()) + let our_channel_monitor_claim_key_hash = WPubkeyHash::hash( + &PublicKey::from_secret_key(&secp_ctx, &channel_monitor_claim_key).serialize(), + ); + Ok(Builder::new() + .push_opcode(opcodes::all::OP_PUSHBYTES_0) + .push_slice(our_channel_monitor_claim_key_hash) + .into_script()) } fn get_shutdown_scriptpubkey(&self) -> Result { let secp_ctx = Secp256k1::signing_only(); #[rustfmt::skip] let secret_key = SecretKey::from_slice(&[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, self.node_secret[31]]).unwrap(); - let pubkey_hash = WPubkeyHash::hash(&PublicKey::from_secret_key(&secp_ctx, &secret_key).serialize()); + let pubkey_hash = + WPubkeyHash::hash(&PublicKey::from_secret_key(&secp_ctx, &secret_key).serialize()); Ok(ShutdownScript::new_p2wpkh(&pubkey_hash)) } } impl KeyProvider { - fn make_enforcement_state_cell(&self, commitment_seed: [u8; 32]) -> Arc> { + fn make_enforcement_state_cell( + &self, commitment_seed: [u8; 32], + ) -> Arc> { let mut revoked_commitments = self.enforcement_states.lock().unwrap(); if !revoked_commitments.contains_key(&commitment_seed) { - revoked_commitments.insert(commitment_seed, Arc::new(Mutex::new(EnforcementState::new()))); + revoked_commitments + .insert(commitment_seed, Arc::new(Mutex::new(EnforcementState::new()))); } let cell = revoked_commitments.get(&commitment_seed).unwrap(); Arc::clone(cell) @@ -387,34 +462,61 @@ fn check_api_err(api_err: APIError, sendable_bounds_violated: bool) { APIError::MonitorUpdateInProgress => { // We can (obviously) temp-fail a monitor update }, - APIError::IncompatibleShutdownScript { .. } => panic!("Cannot send an incompatible shutdown script"), + APIError::IncompatibleShutdownScript { .. } => { + panic!("Cannot send an incompatible shutdown script") + }, } } #[inline] fn check_payment_err(send_err: PaymentSendFailure, sendable_bounds_violated: bool) { match send_err { - PaymentSendFailure::ParameterError(api_err) => check_api_err(api_err, sendable_bounds_violated), + PaymentSendFailure::ParameterError(api_err) => { + check_api_err(api_err, sendable_bounds_violated) + }, PaymentSendFailure::PathParameterError(per_path_results) => { - for res in per_path_results { if let Err(api_err) = res { check_api_err(api_err, sendable_bounds_violated); } } + for res in per_path_results { + if let Err(api_err) = res { + check_api_err(api_err, sendable_bounds_violated); + } + } }, PaymentSendFailure::AllFailedResendSafe(per_path_results) => { - for api_err in per_path_results { check_api_err(api_err, sendable_bounds_violated); } + for api_err in per_path_results { + check_api_err(api_err, sendable_bounds_violated); + } }, PaymentSendFailure::PartialFailure { results, .. } => { - for res in results { if let Err(api_err) = res { check_api_err(api_err, sendable_bounds_violated); } } + for res in results { + if let Err(api_err) = res { + check_api_err(api_err, sendable_bounds_violated); + } + } }, PaymentSendFailure::DuplicatePayment => panic!(), } } -type ChanMan<'a> = ChannelManager, Arc, Arc, Arc, Arc, Arc, &'a FuzzRouter, Arc>; +type ChanMan<'a> = ChannelManager< + Arc, + Arc, + Arc, + Arc, + Arc, + Arc, + &'a FuzzRouter, + Arc, +>; #[inline] -fn get_payment_secret_hash(dest: &ChanMan, payment_id: &mut u8) -> Option<(PaymentSecret, PaymentHash)> { +fn get_payment_secret_hash( + dest: &ChanMan, payment_id: &mut u8, +) -> Option<(PaymentSecret, PaymentHash)> { let mut payment_hash; for _ in 0..256 { payment_hash = PaymentHash(Sha256::hash(&[*payment_id; 1]).to_byte_array()); - if let Ok(payment_secret) = dest.create_inbound_payment_for_hash(payment_hash, None, 3600, None) { + if let Ok(payment_secret) = + dest.create_inbound_payment_for_hash(payment_hash, None, 3600, None) + { return Some((payment_secret, payment_hash)); } *payment_id = payment_id.wrapping_add(1); @@ -423,34 +525,53 @@ fn get_payment_secret_hash(dest: &ChanMan, payment_id: &mut u8) -> Option<(Payme } #[inline] -fn send_noret(source: &ChanMan, dest: &ChanMan, dest_chan_id: u64, amt: u64, payment_id: &mut u8, payment_idx: &mut u64) { +fn send_noret( + source: &ChanMan, dest: &ChanMan, dest_chan_id: u64, amt: u64, payment_id: &mut u8, + payment_idx: &mut u64, +) { send_payment(source, dest, dest_chan_id, amt, payment_id, payment_idx); } #[inline] -fn send_payment(source: &ChanMan, dest: &ChanMan, dest_chan_id: u64, amt: u64, payment_id: &mut u8, payment_idx: &mut u64) -> bool { +fn send_payment( + source: &ChanMan, dest: &ChanMan, dest_chan_id: u64, amt: u64, payment_id: &mut u8, + payment_idx: &mut u64, +) -> bool { let (payment_secret, payment_hash) = - if let Some((secret, hash)) = get_payment_secret_hash(dest, payment_id) { (secret, hash) } else { return true; }; + if let Some((secret, hash)) = get_payment_secret_hash(dest, payment_id) { + (secret, hash) + } else { + return true; + }; let mut payment_id = [0; 32]; payment_id[0..8].copy_from_slice(&payment_idx.to_ne_bytes()); *payment_idx += 1; - let (min_value_sendable, max_value_sendable) = source.list_usable_channels() - .iter().find(|chan| chan.short_channel_id == Some(dest_chan_id)) - .map(|chan| - (chan.next_outbound_htlc_minimum_msat, chan.next_outbound_htlc_limit_msat)) + let (min_value_sendable, max_value_sendable) = source + .list_usable_channels() + .iter() + .find(|chan| chan.short_channel_id == Some(dest_chan_id)) + .map(|chan| (chan.next_outbound_htlc_minimum_msat, chan.next_outbound_htlc_limit_msat)) .unwrap_or((0, 0)); - if let Err(err) = source.send_payment_with_route(&Route { - paths: vec![Path { hops: vec![RouteHop { - pubkey: dest.get_our_node_id(), - node_features: dest.node_features(), - short_channel_id: dest_chan_id, - channel_features: dest.channel_features(), - fee_msat: amt, - cltv_expiry_delta: 200, - maybe_announced_channel: true, - }], blinded_tail: None }], - route_params: None, - }, payment_hash, RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_id)) { + if let Err(err) = source.send_payment_with_route( + &Route { + paths: vec![Path { + hops: vec![RouteHop { + pubkey: dest.get_our_node_id(), + node_features: dest.node_features(), + short_channel_id: dest_chan_id, + channel_features: dest.channel_features(), + fee_msat: amt, + cltv_expiry_delta: 200, + maybe_announced_channel: true, + }], + blinded_tail: None, + }], + route_params: None, + }, + payment_hash, + RecipientOnionFields::secret_only(payment_secret), + PaymentId(payment_id), + ) { check_payment_err(err, amt > max_value_sendable || amt < min_value_sendable); false } else { @@ -463,43 +584,74 @@ fn send_payment(source: &ChanMan, dest: &ChanMan, dest_chan_id: u64, amt: u64, p } #[inline] -fn send_hop_noret(source: &ChanMan, middle: &ChanMan, middle_chan_id: u64, dest: &ChanMan, dest_chan_id: u64, amt: u64, payment_id: &mut u8, payment_idx: &mut u64) { - send_hop_payment(source, middle, middle_chan_id, dest, dest_chan_id, amt, payment_id, payment_idx); +fn send_hop_noret( + source: &ChanMan, middle: &ChanMan, middle_chan_id: u64, dest: &ChanMan, dest_chan_id: u64, + amt: u64, payment_id: &mut u8, payment_idx: &mut u64, +) { + send_hop_payment( + source, + middle, + middle_chan_id, + dest, + dest_chan_id, + amt, + payment_id, + payment_idx, + ); } #[inline] -fn send_hop_payment(source: &ChanMan, middle: &ChanMan, middle_chan_id: u64, dest: &ChanMan, dest_chan_id: u64, amt: u64, payment_id: &mut u8, payment_idx: &mut u64) -> bool { +fn send_hop_payment( + source: &ChanMan, middle: &ChanMan, middle_chan_id: u64, dest: &ChanMan, dest_chan_id: u64, + amt: u64, payment_id: &mut u8, payment_idx: &mut u64, +) -> bool { let (payment_secret, payment_hash) = - if let Some((secret, hash)) = get_payment_secret_hash(dest, payment_id) { (secret, hash) } else { return true; }; + if let Some((secret, hash)) = get_payment_secret_hash(dest, payment_id) { + (secret, hash) + } else { + return true; + }; let mut payment_id = [0; 32]; payment_id[0..8].copy_from_slice(&payment_idx.to_ne_bytes()); *payment_idx += 1; - let (min_value_sendable, max_value_sendable) = source.list_usable_channels() - .iter().find(|chan| chan.short_channel_id == Some(middle_chan_id)) - .map(|chan| - (chan.next_outbound_htlc_minimum_msat, chan.next_outbound_htlc_limit_msat)) + let (min_value_sendable, max_value_sendable) = source + .list_usable_channels() + .iter() + .find(|chan| chan.short_channel_id == Some(middle_chan_id)) + .map(|chan| (chan.next_outbound_htlc_minimum_msat, chan.next_outbound_htlc_limit_msat)) .unwrap_or((0, 0)); let first_hop_fee = 50_000; - if let Err(err) = source.send_payment_with_route(&Route { - paths: vec![Path { hops: vec![RouteHop { - pubkey: middle.get_our_node_id(), - node_features: middle.node_features(), - short_channel_id: middle_chan_id, - channel_features: middle.channel_features(), - fee_msat: first_hop_fee, - cltv_expiry_delta: 100, - maybe_announced_channel: true, - }, RouteHop { - pubkey: dest.get_our_node_id(), - node_features: dest.node_features(), - short_channel_id: dest_chan_id, - channel_features: dest.channel_features(), - fee_msat: amt, - cltv_expiry_delta: 200, - maybe_announced_channel: true, - }], blinded_tail: None }], - route_params: None, - }, payment_hash, RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_id)) { + if let Err(err) = source.send_payment_with_route( + &Route { + paths: vec![Path { + hops: vec![ + RouteHop { + pubkey: middle.get_our_node_id(), + node_features: middle.node_features(), + short_channel_id: middle_chan_id, + channel_features: middle.channel_features(), + fee_msat: first_hop_fee, + cltv_expiry_delta: 100, + maybe_announced_channel: true, + }, + RouteHop { + pubkey: dest.get_our_node_id(), + node_features: dest.node_features(), + short_channel_id: dest_chan_id, + channel_features: dest.channel_features(), + fee_msat: amt, + cltv_expiry_delta: 200, + maybe_announced_channel: true, + }, + ], + blinded_tail: None, + }], + route_params: None, + }, + payment_hash, + RecipientOnionFields::secret_only(payment_secret), + PaymentId(payment_id), + ) { let sent_amt = amt + first_hop_fee; check_payment_err(err, sent_amt < min_value_sendable || sent_amt > max_value_sendable); false @@ -515,18 +667,32 @@ fn send_hop_payment(source: &ChanMan, middle: &ChanMan, middle_chan_id: u64, des #[inline] pub fn do_test(data: &[u8], underlying_out: Out, anchors: bool) { let out = SearchingOutput::new(underlying_out); - let broadcast = Arc::new(TestBroadcaster{}); + let broadcast = Arc::new(TestBroadcaster {}); let router = FuzzRouter {}; macro_rules! make_node { - ($node_id: expr, $fee_estimator: expr) => { { - let logger: Arc = Arc::new(test_logger::TestLogger::new($node_id.to_string(), out.clone())); - let node_secret = SecretKey::from_slice(&[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, $node_id]).unwrap(); - let keys_manager = Arc::new(KeyProvider { node_secret, rand_bytes_id: atomic::AtomicU32::new(0), enforcement_states: Mutex::new(new_hash_map()) }); - let monitor = Arc::new(TestChainMonitor::new(broadcast.clone(), logger.clone(), $fee_estimator.clone(), + ($node_id: expr, $fee_estimator: expr) => {{ + let logger: Arc = + Arc::new(test_logger::TestLogger::new($node_id.to_string(), out.clone())); + let node_secret = SecretKey::from_slice(&[ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 1, $node_id, + ]) + .unwrap(); + let keys_manager = Arc::new(KeyProvider { + node_secret, + rand_bytes_id: atomic::AtomicU32::new(0), + enforcement_states: Mutex::new(new_hash_map()), + }); + let monitor = Arc::new(TestChainMonitor::new( + broadcast.clone(), + logger.clone(), + $fee_estimator.clone(), Arc::new(TestPersister { - update_ret: Mutex::new(ChannelMonitorUpdateStatus::Completed) - }), Arc::clone(&keys_manager))); + update_ret: Mutex::new(ChannelMonitorUpdateStatus::Completed), + }), + Arc::clone(&keys_manager), + )); let mut config = UserConfig::default(); config.channel_config.forwarding_fee_proportional_millionths = 0; @@ -537,23 +703,41 @@ pub fn do_test(data: &[u8], underlying_out: Out, anchors: bool) { } let network = Network::Bitcoin; let best_block_timestamp = genesis_block(network).header.time; - let params = ChainParameters { - network, - best_block: BestBlock::from_network(network), - }; - (ChannelManager::new($fee_estimator.clone(), monitor.clone(), broadcast.clone(), &router, Arc::clone(&logger), keys_manager.clone(), keys_manager.clone(), keys_manager.clone(), config, params, best_block_timestamp), - monitor, keys_manager) - } } + let params = ChainParameters { network, best_block: BestBlock::from_network(network) }; + ( + ChannelManager::new( + $fee_estimator.clone(), + monitor.clone(), + broadcast.clone(), + &router, + Arc::clone(&logger), + keys_manager.clone(), + keys_manager.clone(), + keys_manager.clone(), + config, + params, + best_block_timestamp, + ), + monitor, + keys_manager, + ) + }}; } macro_rules! reload_node { - ($ser: expr, $node_id: expr, $old_monitors: expr, $keys_manager: expr, $fee_estimator: expr) => { { - let keys_manager = Arc::clone(& $keys_manager); - let logger: Arc = Arc::new(test_logger::TestLogger::new($node_id.to_string(), out.clone())); - let chain_monitor = Arc::new(TestChainMonitor::new(broadcast.clone(), logger.clone(), $fee_estimator.clone(), + ($ser: expr, $node_id: expr, $old_monitors: expr, $keys_manager: expr, $fee_estimator: expr) => {{ + let keys_manager = Arc::clone(&$keys_manager); + let logger: Arc = + Arc::new(test_logger::TestLogger::new($node_id.to_string(), out.clone())); + let chain_monitor = Arc::new(TestChainMonitor::new( + broadcast.clone(), + logger.clone(), + $fee_estimator.clone(), Arc::new(TestPersister { - update_ret: Mutex::new(ChannelMonitorUpdateStatus::Completed) - }), Arc::clone(& $keys_manager))); + update_ret: Mutex::new(ChannelMonitorUpdateStatus::Completed), + }), + Arc::clone(&$keys_manager), + )); let mut config = UserConfig::default(); config.channel_config.forwarding_fee_proportional_millionths = 0; @@ -566,9 +750,15 @@ pub fn do_test(data: &[u8], underlying_out: Out, anchors: bool) { let mut monitors = new_hash_map(); let mut old_monitors = $old_monitors.latest_monitors.lock().unwrap(); for (outpoint, mut prev_state) in old_monitors.drain() { - monitors.insert(outpoint, <(BlockHash, ChannelMonitor)>::read( - &mut Cursor::new(&prev_state.persisted_monitor), (&*$keys_manager, &*$keys_manager) - ).expect("Failed to read monitor").1); + monitors.insert( + outpoint, + <(BlockHash, ChannelMonitor)>::read( + &mut Cursor::new(&prev_state.persisted_monitor), + (&*$keys_manager, &*$keys_manager), + ) + .expect("Failed to read monitor") + .1, + ); // Wipe any `ChannelMonitor`s which we never told LDK we finished persisting, // considering them discarded. LDK should replay these for us as they're stored in // the `ChannelManager`. @@ -593,24 +783,35 @@ pub fn do_test(data: &[u8], underlying_out: Out, anchors: bool) { channel_monitors: monitor_refs, }; - let res = (<(BlockHash, ChanMan)>::read(&mut Cursor::new(&$ser.0), read_args).expect("Failed to read manager").1, chain_monitor.clone()); + let res = ( + <(BlockHash, ChanMan)>::read(&mut Cursor::new(&$ser.0), read_args) + .expect("Failed to read manager") + .1, + chain_monitor.clone(), + ); for (funding_txo, mon) in monitors.drain() { - assert_eq!(chain_monitor.chain_monitor.watch_channel(funding_txo, mon), - Ok(ChannelMonitorUpdateStatus::Completed)); + assert_eq!( + chain_monitor.chain_monitor.watch_channel(funding_txo, mon), + Ok(ChannelMonitorUpdateStatus::Completed) + ); } res - } } + }}; } let mut channel_txn = Vec::new(); macro_rules! make_channel { - ($source: expr, $dest: expr, $dest_keys_manager: expr, $chan_id: expr) => { { + ($source: expr, $dest: expr, $dest_keys_manager: expr, $chan_id: expr) => {{ let init_dest = Init { - features: $dest.init_features(), networks: None, remote_network_address: None + features: $dest.init_features(), + networks: None, + remote_network_address: None, }; $source.peer_connected(&$dest.get_our_node_id(), &init_dest, true).unwrap(); let init_src = Init { - features: $source.init_features(), networks: None, remote_network_address: None + features: $source.init_features(), + networks: None, + remote_network_address: None, }; $dest.peer_connected(&$source.get_our_node_id(), &init_src, false).unwrap(); @@ -620,7 +821,9 @@ pub fn do_test(data: &[u8], underlying_out: Out, anchors: bool) { assert_eq!(events.len(), 1); if let events::MessageSendEvent::SendOpenChannel { ref msg, .. } = events[0] { msg.clone() - } else { panic!("Wrong event type"); } + } else { + panic!("Wrong event type"); + } }; $dest.handle_open_channel(&$source.get_our_node_id(), &open_channel); @@ -629,23 +832,33 @@ pub fn do_test(data: &[u8], underlying_out: Out, anchors: bool) { let events = $dest.get_and_clear_pending_events(); assert_eq!(events.len(), 1); if let events::Event::OpenChannelRequest { - ref temporary_channel_id, ref counterparty_node_id, .. - } = events[0] { + ref temporary_channel_id, + ref counterparty_node_id, + .. + } = events[0] + { let mut random_bytes = [0u8; 16]; - random_bytes.copy_from_slice(&$dest_keys_manager.get_secure_random_bytes()[..16]); + random_bytes + .copy_from_slice(&$dest_keys_manager.get_secure_random_bytes()[..16]); let user_channel_id = u128::from_be_bytes(random_bytes); - $dest.accept_inbound_channel( - temporary_channel_id, - counterparty_node_id, - user_channel_id, - ).unwrap(); - } else { panic!("Wrong event type"); } + $dest + .accept_inbound_channel( + temporary_channel_id, + counterparty_node_id, + user_channel_id, + ) + .unwrap(); + } else { + panic!("Wrong event type"); + } } let events = $dest.get_and_clear_pending_msg_events(); assert_eq!(events.len(), 1); if let events::MessageSendEvent::SendAcceptChannel { ref msg, .. } = events[0] { msg.clone() - } else { panic!("Wrong event type"); } + } else { + panic!("Wrong event type"); + } }; $source.handle_accept_channel(&$dest.get_our_node_id(), &accept_channel); @@ -653,14 +866,34 @@ pub fn do_test(data: &[u8], underlying_out: Out, anchors: bool) { { let events = $source.get_and_clear_pending_events(); assert_eq!(events.len(), 1); - if let events::Event::FundingGenerationReady { ref temporary_channel_id, ref channel_value_satoshis, ref output_script, .. } = events[0] { - let tx = Transaction { version: Version($chan_id), lock_time: LockTime::ZERO, input: Vec::new(), output: vec![TxOut { - value: Amount::from_sat(*channel_value_satoshis), script_pubkey: output_script.clone(), - }]}; + if let events::Event::FundingGenerationReady { + ref temporary_channel_id, + ref channel_value_satoshis, + ref output_script, + .. + } = events[0] + { + let tx = Transaction { + version: Version($chan_id), + lock_time: LockTime::ZERO, + input: Vec::new(), + output: vec![TxOut { + value: Amount::from_sat(*channel_value_satoshis), + script_pubkey: output_script.clone(), + }], + }; funding_output = OutPoint { txid: tx.txid(), index: 0 }; - $source.funding_transaction_generated(&temporary_channel_id, &$dest.get_our_node_id(), tx.clone()).unwrap(); + $source + .funding_transaction_generated( + &temporary_channel_id, + &$dest.get_our_node_id(), + tx.clone(), + ) + .unwrap(); channel_txn.push(tx); - } else { panic!("Wrong event type"); } + } else { + panic!("Wrong event type"); + } } let funding_created = { @@ -668,7 +901,9 @@ pub fn do_test(data: &[u8], underlying_out: Out, anchors: bool) { assert_eq!(events.len(), 1); if let events::MessageSendEvent::SendFundingCreated { ref msg, .. } = events[0] { msg.clone() - } else { panic!("Wrong event type"); } + } else { + panic!("Wrong event type"); + } }; $dest.handle_funding_created(&$source.get_our_node_id(), &funding_created); @@ -677,53 +912,64 @@ pub fn do_test(data: &[u8], underlying_out: Out, anchors: bool) { assert_eq!(events.len(), 1); if let events::MessageSendEvent::SendFundingSigned { ref msg, .. } = events[0] { msg.clone() - } else { panic!("Wrong event type"); } + } else { + panic!("Wrong event type"); + } }; let events = $dest.get_and_clear_pending_events(); assert_eq!(events.len(), 1); - if let events::Event::ChannelPending{ ref counterparty_node_id, .. } = events[0] { + if let events::Event::ChannelPending { ref counterparty_node_id, .. } = events[0] { assert_eq!(counterparty_node_id, &$source.get_our_node_id()); - } else { panic!("Wrong event type"); } + } else { + panic!("Wrong event type"); + } $source.handle_funding_signed(&$dest.get_our_node_id(), &funding_signed); let events = $source.get_and_clear_pending_events(); assert_eq!(events.len(), 1); - if let events::Event::ChannelPending{ ref counterparty_node_id, .. } = events[0] { + if let events::Event::ChannelPending { ref counterparty_node_id, .. } = events[0] { assert_eq!(counterparty_node_id, &$dest.get_our_node_id()); - } else { panic!("Wrong event type"); } + } else { + panic!("Wrong event type"); + } funding_output - } } + }}; } macro_rules! confirm_txn { - ($node: expr) => { { + ($node: expr) => {{ let chain_hash = genesis_block(Network::Bitcoin).block_hash(); let mut header = create_dummy_header(chain_hash, 42); - let txdata: Vec<_> = channel_txn.iter().enumerate().map(|(i, tx)| (i + 1, tx)).collect(); + let txdata: Vec<_> = + channel_txn.iter().enumerate().map(|(i, tx)| (i + 1, tx)).collect(); $node.transactions_confirmed(&header, &txdata, 1); for _ in 2..100 { header = create_dummy_header(header.block_hash(), 42); } $node.best_block_updated(&header, 99); - } } + }}; } macro_rules! lock_fundings { - ($nodes: expr) => { { + ($nodes: expr) => {{ let mut node_events = Vec::new(); for node in $nodes.iter() { node_events.push(node.get_and_clear_pending_msg_events()); } for (idx, node_event) in node_events.iter().enumerate() { for event in node_event { - if let events::MessageSendEvent::SendChannelReady { ref node_id, ref msg } = event { + if let events::MessageSendEvent::SendChannelReady { ref node_id, ref msg } = + event + { for node in $nodes.iter() { if node.get_our_node_id() == *node_id { node.handle_channel_ready(&$nodes[idx].get_our_node_id(), msg); } } - } else { panic!("Wrong event type"); } + } else { + panic!("Wrong event type"); + } } } @@ -731,18 +977,20 @@ pub fn do_test(data: &[u8], underlying_out: Out, anchors: bool) { let events = node.get_and_clear_pending_msg_events(); for event in events { if let events::MessageSendEvent::SendAnnouncementSignatures { .. } = event { - } else { panic!("Wrong event type"); } + } else { + panic!("Wrong event type"); + } } } - } } + }}; } let fee_est_a = Arc::new(FuzzEstimator { ret_val: atomic::AtomicU32::new(253) }); - let mut last_htlc_clear_fee_a = 253; + let mut last_htlc_clear_fee_a = 253; let fee_est_b = Arc::new(FuzzEstimator { ret_val: atomic::AtomicU32::new(253) }); - let mut last_htlc_clear_fee_b = 253; + let mut last_htlc_clear_fee_b = 253; let fee_est_c = Arc::new(FuzzEstimator { ret_val: atomic::AtomicU32::new(253) }); - let mut last_htlc_clear_fee_c = 253; + let mut last_htlc_clear_fee_c = 253; // 3 nodes is enough to hit all the possible cases, notably unknown-source-unknown-dest // forwarding. @@ -782,26 +1030,24 @@ pub fn do_test(data: &[u8], underlying_out: Out, anchors: bool) { nodes[2].write(&mut node_c_ser).unwrap(); macro_rules! test_return { - () => { { + () => {{ assert_eq!(nodes[0].list_channels().len(), 1); assert_eq!(nodes[1].list_channels().len(), 2); assert_eq!(nodes[2].list_channels().len(), 1); return; - } } + }}; } let mut read_pos = 0; macro_rules! get_slice { - ($len: expr) => { - { - let slice_len = $len as usize; - if data.len() < read_pos + slice_len { - test_return!(); - } - read_pos += slice_len; - &data[read_pos - slice_len..read_pos] + ($len: expr) => {{ + let slice_len = $len as usize; + if data.len() < read_pos + slice_len { + test_return!(); } - } + read_pos += slice_len; + &data[read_pos - slice_len..read_pos] + }}; } loop { @@ -992,13 +1238,13 @@ pub fn do_test(data: &[u8], underlying_out: Out, anchors: bool) { } macro_rules! process_msg_noret { - ($node: expr, $corrupt_forward: expr, $limit_events: expr) => { { + ($node: expr, $corrupt_forward: expr, $limit_events: expr) => {{ process_msg_events!($node, $corrupt_forward, $limit_events); - } } + }}; } macro_rules! drain_msg_events_on_disconnect { - ($counterparty_id: expr) => { { + ($counterparty_id: expr) => {{ if $counterparty_id == 0 { for event in nodes[0].get_and_clear_pending_msg_events() { match event { @@ -1010,14 +1256,19 @@ pub fn do_test(data: &[u8], underlying_out: Out, anchors: bool) { events::MessageSendEvent::SendChannelUpdate { ref msg, .. } => { assert_eq!(msg.contents.flags & 2, 0); // The disable bit must never be set! }, - _ => if out.may_fail.load(atomic::Ordering::Acquire) { - return; - } else { - panic!("Unhandled message event") + _ => { + if out.may_fail.load(atomic::Ordering::Acquire) { + return; + } else { + panic!("Unhandled message event") + } }, } } - push_excess_b_events!(nodes[1].get_and_clear_pending_msg_events().drain(..), Some(0)); + push_excess_b_events!( + nodes[1].get_and_clear_pending_msg_events().drain(..), + Some(0) + ); ab_events.clear(); ba_events.clear(); } else { @@ -1031,22 +1282,27 @@ pub fn do_test(data: &[u8], underlying_out: Out, anchors: bool) { events::MessageSendEvent::SendChannelUpdate { ref msg, .. } => { assert_eq!(msg.contents.flags & 2, 0); // The disable bit must never be set! }, - _ => if out.may_fail.load(atomic::Ordering::Acquire) { - return; - } else { - panic!("Unhandled message event") + _ => { + if out.may_fail.load(atomic::Ordering::Acquire) { + return; + } else { + panic!("Unhandled message event") + } }, } } - push_excess_b_events!(nodes[1].get_and_clear_pending_msg_events().drain(..), Some(2)); + push_excess_b_events!( + nodes[1].get_and_clear_pending_msg_events().drain(..), + Some(2) + ); bc_events.clear(); cb_events.clear(); } - } } + }}; } macro_rules! process_events { - ($node: expr, $fail: expr) => { { + ($node: expr, $fail: expr) => {{ // In case we get 256 payments we may have a hash collision, resulting in the // second claim/fail call not finding the duplicate-hash HTLC, so we have to // deduplicate the calls here. @@ -1061,12 +1317,18 @@ pub fn do_test(data: &[u8], underlying_out: Out, anchors: bool) { if let events::Event::PaymentClaimable { .. } = a { if let events::Event::PendingHTLCsForwardable { .. } = b { Ordering::Less - } else { Ordering::Equal } + } else { + Ordering::Equal + } } else if let events::Event::PendingHTLCsForwardable { .. } = a { if let events::Event::PaymentClaimable { .. } = b { Ordering::Greater - } else { Ordering::Equal } - } else { Ordering::Equal } + } else { + Ordering::Equal + } + } else { + Ordering::Equal + } }); let had_events = !events.is_empty(); for event in events.drain(..) { @@ -1085,7 +1347,8 @@ pub fn do_test(data: &[u8], underlying_out: Out, anchors: bool) { events::Event::PaymentPathSuccessful { .. } => {}, events::Event::PaymentPathFailed { .. } => {}, events::Event::PaymentFailed { .. } => {}, - events::Event::ProbeSuccessful { .. } | events::Event::ProbeFailed { .. } => { + events::Event::ProbeSuccessful { .. } + | events::Event::ProbeFailed { .. } => { // Even though we don't explicitly send probes, because probes are // detected based on hashing the payment hash+preimage, its rather // trivial for the fuzzer to build payments that accidentally end up @@ -1097,43 +1360,45 @@ pub fn do_test(data: &[u8], underlying_out: Out, anchors: bool) { nodes[$node].process_pending_htlc_forwards(); }, events::Event::HTLCHandlingFailed { .. } => {}, - _ => if out.may_fail.load(atomic::Ordering::Acquire) { - return; - } else { - panic!("Unhandled event") + _ => { + if out.may_fail.load(atomic::Ordering::Acquire) { + return; + } else { + panic!("Unhandled event") + } }, } } had_events - } } + }}; } macro_rules! process_ev_noret { - ($node: expr, $fail: expr) => { { + ($node: expr, $fail: expr) => {{ process_events!($node, $fail); - } } + }}; } let complete_first = |v: &mut Vec<_>| if !v.is_empty() { Some(v.remove(0)) } else { None }; let complete_second = |v: &mut Vec<_>| if v.len() > 1 { Some(v.remove(1)) } else { None }; - let complete_monitor_update = | - monitor: &Arc, chan_funding, - compl_selector: &dyn Fn(&mut Vec<(u64, Vec)>) -> Option<(u64, Vec)>, - | { - if let Some(state) = monitor.latest_monitors.lock().unwrap().get_mut(chan_funding) { - assert!( - state.pending_monitors.windows(2).all(|pair| pair[0].0 < pair[1].0), - "updates should be sorted by id" - ); - if let Some((id, data)) = compl_selector(&mut state.pending_monitors) { - monitor.chain_monitor.channel_monitor_updated(*chan_funding, id).unwrap(); - if id > state.persisted_monitor_id { - state.persisted_monitor_id = id; - state.persisted_monitor = data; + let complete_monitor_update = + |monitor: &Arc, + chan_funding, + compl_selector: &dyn Fn(&mut Vec<(u64, Vec)>) -> Option<(u64, Vec)>| { + if let Some(state) = monitor.latest_monitors.lock().unwrap().get_mut(chan_funding) { + assert!( + state.pending_monitors.windows(2).all(|pair| pair[0].0 < pair[1].0), + "updates should be sorted by id" + ); + if let Some((id, data)) = compl_selector(&mut state.pending_monitors) { + monitor.chain_monitor.channel_monitor_updated(*chan_funding, id).unwrap(); + if id > state.persisted_monitor_id { + state.persisted_monitor_id = id; + state.persisted_monitor = data; + } } } - } - }; + }; let complete_all_monitor_updates = |monitor: &Arc, chan_funding| { if let Some(state) = monitor.latest_monitors.lock().unwrap().get_mut(chan_funding) { @@ -1157,13 +1422,30 @@ pub fn do_test(data: &[u8], underlying_out: Out, anchors: bool) { // In general, we keep related message groups close together in binary form, allowing // bit-twiddling mutations to have similar effects. This is probably overkill, but no // harm in doing so. - - 0x00 => *monitor_a.persister.update_ret.lock().unwrap() = ChannelMonitorUpdateStatus::InProgress, - 0x01 => *monitor_b.persister.update_ret.lock().unwrap() = ChannelMonitorUpdateStatus::InProgress, - 0x02 => *monitor_c.persister.update_ret.lock().unwrap() = ChannelMonitorUpdateStatus::InProgress, - 0x04 => *monitor_a.persister.update_ret.lock().unwrap() = ChannelMonitorUpdateStatus::Completed, - 0x05 => *monitor_b.persister.update_ret.lock().unwrap() = ChannelMonitorUpdateStatus::Completed, - 0x06 => *monitor_c.persister.update_ret.lock().unwrap() = ChannelMonitorUpdateStatus::Completed, + 0x00 => { + *monitor_a.persister.update_ret.lock().unwrap() = + ChannelMonitorUpdateStatus::InProgress + }, + 0x01 => { + *monitor_b.persister.update_ret.lock().unwrap() = + ChannelMonitorUpdateStatus::InProgress + }, + 0x02 => { + *monitor_c.persister.update_ret.lock().unwrap() = + ChannelMonitorUpdateStatus::InProgress + }, + 0x04 => { + *monitor_a.persister.update_ret.lock().unwrap() = + ChannelMonitorUpdateStatus::Completed + }, + 0x05 => { + *monitor_b.persister.update_ret.lock().unwrap() = + ChannelMonitorUpdateStatus::Completed + }, + 0x06 => { + *monitor_c.persister.update_ret.lock().unwrap() = + ChannelMonitorUpdateStatus::Completed + }, 0x08 => complete_all_monitor_updates(&monitor_a, &chan_1_funding), 0x09 => complete_all_monitor_updates(&monitor_b, &chan_1_funding), @@ -1189,11 +1471,15 @@ pub fn do_test(data: &[u8], underlying_out: Out, anchors: bool) { 0x0e => { if chan_a_disconnected { let init_1 = Init { - features: nodes[1].init_features(), networks: None, remote_network_address: None + features: nodes[1].init_features(), + networks: None, + remote_network_address: None, }; nodes[0].peer_connected(&nodes[1].get_our_node_id(), &init_1, true).unwrap(); let init_0 = Init { - features: nodes[0].init_features(), networks: None, remote_network_address: None + features: nodes[0].init_features(), + networks: None, + remote_network_address: None, }; nodes[1].peer_connected(&nodes[0].get_our_node_id(), &init_0, false).unwrap(); chan_a_disconnected = false; @@ -1202,11 +1488,15 @@ pub fn do_test(data: &[u8], underlying_out: Out, anchors: bool) { 0x0f => { if chan_b_disconnected { let init_2 = Init { - features: nodes[2].init_features(), networks: None, remote_network_address: None + features: nodes[2].init_features(), + networks: None, + remote_network_address: None, }; nodes[1].peer_connected(&nodes[2].get_our_node_id(), &init_2, true).unwrap(); let init_1 = Init { - features: nodes[1].init_features(), networks: None, remote_network_address: None + features: nodes[1].init_features(), + networks: None, + remote_network_address: None, }; nodes[2].peer_connected(&nodes[1].get_our_node_id(), &init_1, false).unwrap(); chan_b_disconnected = false; @@ -1247,11 +1537,15 @@ pub fn do_test(data: &[u8], underlying_out: Out, anchors: bool) { if !chan_a_disconnected { nodes[1].peer_disconnected(&nodes[0].get_our_node_id()); chan_a_disconnected = true; - push_excess_b_events!(nodes[1].get_and_clear_pending_msg_events().drain(..), Some(0)); + push_excess_b_events!( + nodes[1].get_and_clear_pending_msg_events().drain(..), + Some(0) + ); ab_events.clear(); ba_events.clear(); } - let (new_node_a, new_monitor_a) = reload_node!(node_a_ser, 0, monitor_a, keys_manager_a, fee_est_a); + let (new_node_a, new_monitor_a) = + reload_node!(node_a_ser, 0, monitor_a, keys_manager_a, fee_est_a); nodes[0] = new_node_a; monitor_a = new_monitor_a; }, @@ -1270,7 +1564,8 @@ pub fn do_test(data: &[u8], underlying_out: Out, anchors: bool) { bc_events.clear(); cb_events.clear(); } - let (new_node_b, new_monitor_b) = reload_node!(node_b_ser, 1, monitor_b, keys_manager_b, fee_est_b); + let (new_node_b, new_monitor_b) = + reload_node!(node_b_ser, 1, monitor_b, keys_manager_b, fee_est_b); nodes[1] = new_node_b; monitor_b = new_monitor_b; }, @@ -1278,11 +1573,15 @@ pub fn do_test(data: &[u8], underlying_out: Out, anchors: bool) { if !chan_b_disconnected { nodes[1].peer_disconnected(&nodes[2].get_our_node_id()); chan_b_disconnected = true; - push_excess_b_events!(nodes[1].get_and_clear_pending_msg_events().drain(..), Some(2)); + push_excess_b_events!( + nodes[1].get_and_clear_pending_msg_events().drain(..), + Some(2) + ); bc_events.clear(); cb_events.clear(); } - let (new_node_c, new_monitor_c) = reload_node!(node_c_ser, 2, monitor_c, keys_manager_c, fee_est_c); + let (new_node_c, new_monitor_c) = + reload_node!(node_c_ser, 2, monitor_c, keys_manager_c, fee_est_c); nodes[2] = new_node_c; monitor_c = new_monitor_c; }, @@ -1292,57 +1591,89 @@ pub fn do_test(data: &[u8], underlying_out: Out, anchors: bool) { 0x31 => send_noret(&nodes[1], &nodes[0], chan_a, 10_000_000, &mut p_id, &mut p_idx), 0x32 => send_noret(&nodes[1], &nodes[2], chan_b, 10_000_000, &mut p_id, &mut p_idx), 0x33 => send_noret(&nodes[2], &nodes[1], chan_b, 10_000_000, &mut p_id, &mut p_idx), - 0x34 => send_hop_noret(&nodes[0], &nodes[1], chan_a, &nodes[2], chan_b, 10_000_000, &mut p_id, &mut p_idx), - 0x35 => send_hop_noret(&nodes[2], &nodes[1], chan_b, &nodes[0], chan_a, 10_000_000, &mut p_id, &mut p_idx), + 0x34 => send_hop_noret( + &nodes[0], &nodes[1], chan_a, &nodes[2], chan_b, 10_000_000, &mut p_id, &mut p_idx, + ), + 0x35 => send_hop_noret( + &nodes[2], &nodes[1], chan_b, &nodes[0], chan_a, 10_000_000, &mut p_id, &mut p_idx, + ), 0x38 => send_noret(&nodes[0], &nodes[1], chan_a, 1_000_000, &mut p_id, &mut p_idx), 0x39 => send_noret(&nodes[1], &nodes[0], chan_a, 1_000_000, &mut p_id, &mut p_idx), 0x3a => send_noret(&nodes[1], &nodes[2], chan_b, 1_000_000, &mut p_id, &mut p_idx), 0x3b => send_noret(&nodes[2], &nodes[1], chan_b, 1_000_000, &mut p_id, &mut p_idx), - 0x3c => send_hop_noret(&nodes[0], &nodes[1], chan_a, &nodes[2], chan_b, 1_000_000, &mut p_id, &mut p_idx), - 0x3d => send_hop_noret(&nodes[2], &nodes[1], chan_b, &nodes[0], chan_a, 1_000_000, &mut p_id, &mut p_idx), + 0x3c => send_hop_noret( + &nodes[0], &nodes[1], chan_a, &nodes[2], chan_b, 1_000_000, &mut p_id, &mut p_idx, + ), + 0x3d => send_hop_noret( + &nodes[2], &nodes[1], chan_b, &nodes[0], chan_a, 1_000_000, &mut p_id, &mut p_idx, + ), 0x40 => send_noret(&nodes[0], &nodes[1], chan_a, 100_000, &mut p_id, &mut p_idx), 0x41 => send_noret(&nodes[1], &nodes[0], chan_a, 100_000, &mut p_id, &mut p_idx), 0x42 => send_noret(&nodes[1], &nodes[2], chan_b, 100_000, &mut p_id, &mut p_idx), 0x43 => send_noret(&nodes[2], &nodes[1], chan_b, 100_000, &mut p_id, &mut p_idx), - 0x44 => send_hop_noret(&nodes[0], &nodes[1], chan_a, &nodes[2], chan_b, 100_000, &mut p_id, &mut p_idx), - 0x45 => send_hop_noret(&nodes[2], &nodes[1], chan_b, &nodes[0], chan_a, 100_000, &mut p_id, &mut p_idx), + 0x44 => send_hop_noret( + &nodes[0], &nodes[1], chan_a, &nodes[2], chan_b, 100_000, &mut p_id, &mut p_idx, + ), + 0x45 => send_hop_noret( + &nodes[2], &nodes[1], chan_b, &nodes[0], chan_a, 100_000, &mut p_id, &mut p_idx, + ), 0x48 => send_noret(&nodes[0], &nodes[1], chan_a, 10_000, &mut p_id, &mut p_idx), 0x49 => send_noret(&nodes[1], &nodes[0], chan_a, 10_000, &mut p_id, &mut p_idx), 0x4a => send_noret(&nodes[1], &nodes[2], chan_b, 10_000, &mut p_id, &mut p_idx), 0x4b => send_noret(&nodes[2], &nodes[1], chan_b, 10_000, &mut p_id, &mut p_idx), - 0x4c => send_hop_noret(&nodes[0], &nodes[1], chan_a, &nodes[2], chan_b, 10_000, &mut p_id, &mut p_idx), - 0x4d => send_hop_noret(&nodes[2], &nodes[1], chan_b, &nodes[0], chan_a, 10_000, &mut p_id, &mut p_idx), + 0x4c => send_hop_noret( + &nodes[0], &nodes[1], chan_a, &nodes[2], chan_b, 10_000, &mut p_id, &mut p_idx, + ), + 0x4d => send_hop_noret( + &nodes[2], &nodes[1], chan_b, &nodes[0], chan_a, 10_000, &mut p_id, &mut p_idx, + ), 0x50 => send_noret(&nodes[0], &nodes[1], chan_a, 1_000, &mut p_id, &mut p_idx), 0x51 => send_noret(&nodes[1], &nodes[0], chan_a, 1_000, &mut p_id, &mut p_idx), 0x52 => send_noret(&nodes[1], &nodes[2], chan_b, 1_000, &mut p_id, &mut p_idx), 0x53 => send_noret(&nodes[2], &nodes[1], chan_b, 1_000, &mut p_id, &mut p_idx), - 0x54 => send_hop_noret(&nodes[0], &nodes[1], chan_a, &nodes[2], chan_b, 1_000, &mut p_id, &mut p_idx), - 0x55 => send_hop_noret(&nodes[2], &nodes[1], chan_b, &nodes[0], chan_a, 1_000, &mut p_id, &mut p_idx), + 0x54 => send_hop_noret( + &nodes[0], &nodes[1], chan_a, &nodes[2], chan_b, 1_000, &mut p_id, &mut p_idx, + ), + 0x55 => send_hop_noret( + &nodes[2], &nodes[1], chan_b, &nodes[0], chan_a, 1_000, &mut p_id, &mut p_idx, + ), 0x58 => send_noret(&nodes[0], &nodes[1], chan_a, 100, &mut p_id, &mut p_idx), 0x59 => send_noret(&nodes[1], &nodes[0], chan_a, 100, &mut p_id, &mut p_idx), 0x5a => send_noret(&nodes[1], &nodes[2], chan_b, 100, &mut p_id, &mut p_idx), 0x5b => send_noret(&nodes[2], &nodes[1], chan_b, 100, &mut p_id, &mut p_idx), - 0x5c => send_hop_noret(&nodes[0], &nodes[1], chan_a, &nodes[2], chan_b, 100, &mut p_id, &mut p_idx), - 0x5d => send_hop_noret(&nodes[2], &nodes[1], chan_b, &nodes[0], chan_a, 100, &mut p_id, &mut p_idx), + 0x5c => send_hop_noret( + &nodes[0], &nodes[1], chan_a, &nodes[2], chan_b, 100, &mut p_id, &mut p_idx, + ), + 0x5d => send_hop_noret( + &nodes[2], &nodes[1], chan_b, &nodes[0], chan_a, 100, &mut p_id, &mut p_idx, + ), 0x60 => send_noret(&nodes[0], &nodes[1], chan_a, 10, &mut p_id, &mut p_idx), 0x61 => send_noret(&nodes[1], &nodes[0], chan_a, 10, &mut p_id, &mut p_idx), 0x62 => send_noret(&nodes[1], &nodes[2], chan_b, 10, &mut p_id, &mut p_idx), 0x63 => send_noret(&nodes[2], &nodes[1], chan_b, 10, &mut p_id, &mut p_idx), - 0x64 => send_hop_noret(&nodes[0], &nodes[1], chan_a, &nodes[2], chan_b, 10, &mut p_id, &mut p_idx), - 0x65 => send_hop_noret(&nodes[2], &nodes[1], chan_b, &nodes[0], chan_a, 10, &mut p_id, &mut p_idx), + 0x64 => send_hop_noret( + &nodes[0], &nodes[1], chan_a, &nodes[2], chan_b, 10, &mut p_id, &mut p_idx, + ), + 0x65 => send_hop_noret( + &nodes[2], &nodes[1], chan_b, &nodes[0], chan_a, 10, &mut p_id, &mut p_idx, + ), 0x68 => send_noret(&nodes[0], &nodes[1], chan_a, 1, &mut p_id, &mut p_idx), 0x69 => send_noret(&nodes[1], &nodes[0], chan_a, 1, &mut p_id, &mut p_idx), 0x6a => send_noret(&nodes[1], &nodes[2], chan_b, 1, &mut p_id, &mut p_idx), 0x6b => send_noret(&nodes[2], &nodes[1], chan_b, 1, &mut p_id, &mut p_idx), - 0x6c => send_hop_noret(&nodes[0], &nodes[1], chan_a, &nodes[2], chan_b, 1, &mut p_id, &mut p_idx), - 0x6d => send_hop_noret(&nodes[2], &nodes[1], chan_b, &nodes[0], chan_a, 1, &mut p_id, &mut p_idx), + 0x6c => send_hop_noret( + &nodes[0], &nodes[1], chan_a, &nodes[2], chan_b, 1, &mut p_id, &mut p_idx, + ), + 0x6d => send_hop_noret( + &nodes[2], &nodes[1], chan_b, &nodes[0], chan_a, 1, &mut p_id, &mut p_idx, + ), 0x80 => { let mut max_feerate = last_htlc_clear_fee_a; @@ -1354,7 +1685,10 @@ pub fn do_test(data: &[u8], underlying_out: Out, anchors: bool) { } nodes[0].maybe_update_chan_fees(); }, - 0x81 => { fee_est_a.ret_val.store(253, atomic::Ordering::Release); nodes[0].maybe_update_chan_fees(); }, + 0x81 => { + fee_est_a.ret_val.store(253, atomic::Ordering::Release); + nodes[0].maybe_update_chan_fees(); + }, 0x84 => { let mut max_feerate = last_htlc_clear_fee_b; @@ -1366,7 +1700,10 @@ pub fn do_test(data: &[u8], underlying_out: Out, anchors: bool) { } nodes[1].maybe_update_chan_fees(); }, - 0x85 => { fee_est_b.ret_val.store(253, atomic::Ordering::Release); nodes[1].maybe_update_chan_fees(); }, + 0x85 => { + fee_est_b.ret_val.store(253, atomic::Ordering::Release); + nodes[1].maybe_update_chan_fees(); + }, 0x88 => { let mut max_feerate = last_htlc_clear_fee_c; @@ -1378,7 +1715,10 @@ pub fn do_test(data: &[u8], underlying_out: Out, anchors: bool) { } nodes[2].maybe_update_chan_fees(); }, - 0x89 => { fee_est_c.ret_val.store(253, atomic::Ordering::Release); nodes[2].maybe_update_chan_fees(); }, + 0x89 => { + fee_est_c.ret_val.store(253, atomic::Ordering::Release); + nodes[2].maybe_update_chan_fees(); + }, 0xf0 => complete_monitor_update(&monitor_a, &chan_1_funding, &complete_first), 0xf1 => complete_monitor_update(&monitor_a, &chan_1_funding, &complete_second), @@ -1401,9 +1741,12 @@ pub fn do_test(data: &[u8], underlying_out: Out, anchors: bool) { // after we resolve all pending events. // First make sure there are no pending monitor updates and further update // operations complete. - *monitor_a.persister.update_ret.lock().unwrap() = ChannelMonitorUpdateStatus::Completed; - *monitor_b.persister.update_ret.lock().unwrap() = ChannelMonitorUpdateStatus::Completed; - *monitor_c.persister.update_ret.lock().unwrap() = ChannelMonitorUpdateStatus::Completed; + *monitor_a.persister.update_ret.lock().unwrap() = + ChannelMonitorUpdateStatus::Completed; + *monitor_b.persister.update_ret.lock().unwrap() = + ChannelMonitorUpdateStatus::Completed; + *monitor_c.persister.update_ret.lock().unwrap() = + ChannelMonitorUpdateStatus::Completed; complete_all_monitor_updates(&monitor_a, &chan_1_funding); complete_all_monitor_updates(&monitor_b, &chan_1_funding); @@ -1413,48 +1756,76 @@ pub fn do_test(data: &[u8], underlying_out: Out, anchors: bool) { // Next, make sure peers are all connected to each other if chan_a_disconnected { let init_1 = Init { - features: nodes[1].init_features(), networks: None, remote_network_address: None + features: nodes[1].init_features(), + networks: None, + remote_network_address: None, }; nodes[0].peer_connected(&nodes[1].get_our_node_id(), &init_1, true).unwrap(); let init_0 = Init { - features: nodes[0].init_features(), networks: None, remote_network_address: None + features: nodes[0].init_features(), + networks: None, + remote_network_address: None, }; nodes[1].peer_connected(&nodes[0].get_our_node_id(), &init_0, false).unwrap(); chan_a_disconnected = false; } if chan_b_disconnected { let init_2 = Init { - features: nodes[2].init_features(), networks: None, remote_network_address: None + features: nodes[2].init_features(), + networks: None, + remote_network_address: None, }; nodes[1].peer_connected(&nodes[2].get_our_node_id(), &init_2, true).unwrap(); let init_1 = Init { - features: nodes[1].init_features(), networks: None, remote_network_address: None + features: nodes[1].init_features(), + networks: None, + remote_network_address: None, }; nodes[2].peer_connected(&nodes[1].get_our_node_id(), &init_1, false).unwrap(); chan_b_disconnected = false; } for i in 0..std::usize::MAX { - if i == 100 { panic!("It may take may iterations to settle the state, but it should not take forever"); } + if i == 100 { + panic!("It may take may iterations to settle the state, but it should not take forever"); + } // Then, make sure any current forwards make their way to their destination - if process_msg_events!(0, false, ProcessMessages::AllMessages) { continue; } - if process_msg_events!(1, false, ProcessMessages::AllMessages) { continue; } - if process_msg_events!(2, false, ProcessMessages::AllMessages) { continue; } + if process_msg_events!(0, false, ProcessMessages::AllMessages) { + continue; + } + if process_msg_events!(1, false, ProcessMessages::AllMessages) { + continue; + } + if process_msg_events!(2, false, ProcessMessages::AllMessages) { + continue; + } // ...making sure any pending PendingHTLCsForwardable events are handled and // payments claimed. - if process_events!(0, false) { continue; } - if process_events!(1, false) { continue; } - if process_events!(2, false) { continue; } + if process_events!(0, false) { + continue; + } + if process_events!(1, false) { + continue; + } + if process_events!(2, false) { + continue; + } break; } // Finally, make sure that at least one end of each channel can make a substantial payment assert!( - send_payment(&nodes[0], &nodes[1], chan_a, 10_000_000, &mut p_id, &mut p_idx) || - send_payment(&nodes[1], &nodes[0], chan_a, 10_000_000, &mut p_id, &mut p_idx)); + send_payment(&nodes[0], &nodes[1], chan_a, 10_000_000, &mut p_id, &mut p_idx) + || send_payment( + &nodes[1], &nodes[0], chan_a, 10_000_000, &mut p_id, &mut p_idx + ) + ); assert!( - send_payment(&nodes[1], &nodes[2], chan_b, 10_000_000, &mut p_id, &mut p_idx) || - send_payment(&nodes[2], &nodes[1], chan_b, 10_000_000, &mut p_id, &mut p_idx)); + send_payment(&nodes[1], &nodes[2], chan_b, 10_000_000, &mut p_id, &mut p_idx) + || send_payment( + &nodes[2], &nodes[1], chan_b, 10_000_000, &mut p_id, &mut p_idx + ) + ); last_htlc_clear_fee_a = fee_est_a.ret_val.load(atomic::Ordering::Acquire); last_htlc_clear_fee_b = fee_est_b.ret_val.load(atomic::Ordering::Acquire); @@ -1507,6 +1878,6 @@ pub fn chanmon_consistency_test(data: &[u8], out: Out) { #[no_mangle] pub extern "C" fn chanmon_consistency_run(data: *const u8, datalen: usize) { - do_test(unsafe { std::slice::from_raw_parts(data, datalen) }, test_logger::DevNull{}, false); - do_test(unsafe { std::slice::from_raw_parts(data, datalen) }, test_logger::DevNull{}, true); + do_test(unsafe { std::slice::from_raw_parts(data, datalen) }, test_logger::DevNull {}, false); + do_test(unsafe { std::slice::from_raw_parts(data, datalen) }, test_logger::DevNull {}, true); } diff --git a/rustfmt_excluded_files b/rustfmt_excluded_files index d4317eb0e89..aa0f1784123 100644 --- a/rustfmt_excluded_files +++ b/rustfmt_excluded_files @@ -1,5 +1,4 @@ ./bench/benches/bench.rs -./fuzz/src/chanmon_consistency.rs ./fuzz/src/full_stack.rs ./fuzz/src/lib.rs ./lightning-background-processor/src/lib.rs From 945cb7724790c08caa6766e872a159252b49a354 Mon Sep 17 00:00:00 2001 From: Elias Rohrer Date: Mon, 10 Jun 2024 10:47:50 +0200 Subject: [PATCH 4/5] Prepare `fuzz/src/full_stack.rs` for `rustfmt` --- fuzz/src/full_stack.rs | 118 ++++++++++++++++++++++++++++------------- 1 file changed, 80 insertions(+), 38 deletions(-) diff --git a/fuzz/src/full_stack.rs b/fuzz/src/full_stack.rs index 4591888e3f0..5394dd313b0 100644 --- a/fuzz/src/full_stack.rs +++ b/fuzz/src/full_stack.rs @@ -75,6 +75,7 @@ use std::sync::atomic::{AtomicU64,AtomicUsize,AtomicBool,Ordering}; use bech32::u5; #[inline] +#[rustfmt::skip] pub fn slice_to_be16(v: &[u8]) -> u16 { ((v[0] as u16) << 8*1) | ((v[1] as u16) << 8*0) @@ -89,6 +90,7 @@ pub fn be16_to_array(u: u16) -> [u8; 2] { } #[inline] +#[rustfmt::skip] pub fn slice_to_be24(v: &[u8]) -> u32 { ((v[0] as u32) << 8*2) | ((v[1] as u32) << 8*1) | @@ -313,8 +315,11 @@ struct KeyProvider { impl EntropySource for KeyProvider { fn get_secure_random_bytes(&self) -> [u8; 32] { let ctr = self.counter.fetch_add(1, Ordering::Relaxed); - [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - (ctr >> 8*7) as u8, (ctr >> 8*6) as u8, (ctr >> 8*5) as u8, (ctr >> 8*4) as u8, (ctr >> 8*3) as u8, (ctr >> 8*2) as u8, (ctr >> 8*1) as u8, 14, (ctr >> 8*0) as u8] + #[rustfmt::skip] + let random_bytes = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + (ctr >> 8*7) as u8, (ctr >> 8*6) as u8, (ctr >> 8*5) as u8, (ctr >> 8*4) as u8, + (ctr >> 8*3) as u8, (ctr >> 8*2) as u8, (ctr >> 8*1) as u8, 14, (ctr >> 8*0) as u8]; + random_bytes } } @@ -514,12 +519,15 @@ pub fn do_test(mut data: &[u8], logger: &Arc) { let gossip_sync = Arc::new(P2PGossipSync::new(Arc::clone(&network_graph), None, Arc::clone(&logger))); let peers = RefCell::new([false; 256]); - let mut loss_detector = MoneyLossDetector::new(&peers, channelmanager.clone(), monitor.clone(), PeerManager::new(MessageHandler { + let message_handler = MessageHandler { chan_handler: channelmanager.clone(), route_handler: gossip_sync.clone(), onion_message_handler: IgnoringMessageHandler {}, custom_message_handler: IgnoringMessageHandler {}, - }, 0, &[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 15, 0], Arc::clone(&logger), keys_manager.clone())); + }; + let random_data = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 15, 0]; + let peer_manager = PeerManager::new(message_handler, 0, &random_data, Arc::clone(&logger), keys_manager.clone()); + let mut loss_detector = MoneyLossDetector::new(&peers, channelmanager.clone(), monitor.clone(), peer_manager); let mut should_forward = false; let mut payments_received: Vec = Vec::new(); @@ -539,7 +547,8 @@ pub fn do_test(mut data: &[u8], logger: &Arc) { } } if new_id == 0 { return; } - loss_detector.handler.new_outbound_connection(get_pubkey!(), Peer{id: (new_id - 1) as u8, peers_connected: &peers}, None).unwrap(); + let peer = Peer{id: (new_id - 1) as u8, peers_connected: &peers}; + loss_detector.handler.new_outbound_connection(get_pubkey!(), peer, None).unwrap(); peers.borrow_mut()[new_id - 1] = true; }, 1 => { @@ -551,19 +560,22 @@ pub fn do_test(mut data: &[u8], logger: &Arc) { } } if new_id == 0 { return; } - loss_detector.handler.new_inbound_connection(Peer{id: (new_id - 1) as u8, peers_connected: &peers}, None).unwrap(); + let peer = Peer{id: (new_id - 1) as u8, peers_connected: &peers}; + loss_detector.handler.new_inbound_connection(peer, None).unwrap(); peers.borrow_mut()[new_id - 1] = true; }, 2 => { let peer_id = get_slice!(1)[0]; if !peers.borrow()[peer_id as usize] { return; } - loss_detector.handler.socket_disconnected(&Peer{id: peer_id, peers_connected: &peers}); + let peer = Peer{id: peer_id, peers_connected: &peers}; + loss_detector.handler.socket_disconnected(&peer); peers.borrow_mut()[peer_id as usize] = false; }, 3 => { let peer_id = get_slice!(1)[0]; if !peers.borrow()[peer_id as usize] { return; } - match loss_detector.handler.read_event(&mut Peer{id: peer_id, peers_connected: &peers}, get_slice!(get_slice!(1)[0])) { + let mut peer = Peer{id: peer_id, peers_connected: &peers}; + match loss_detector.handler.read_event(&mut peer, get_slice!(get_slice!(1)[0])) { Ok(res) => assert!(!res), Err(_) => { peers.borrow_mut()[peer_id as usize] = false; } } @@ -921,32 +933,45 @@ mod tests { ext_from_hex("0c005e", &mut test); // the funding transaction ext_from_hex("020000000100000000000000000000000000000000000000000000000000000000000000000000000000ffffffff0150c3000000000000220020ae0000000000000000000000000000000000000000000000000000000000000000000000", &mut test); - ext_from_hex("00fd00fd", &mut test); // Two feerate requests during block connection + // Two feerate requests during block connection + ext_from_hex("00fd00fd", &mut test); // connect a block with no transactions, one per line ext_from_hex("0c0000", &mut test); - ext_from_hex("00fd00fd", &mut test); // Two feerate requests during block connection + // Two feerate requests during block connection + ext_from_hex("00fd00fd", &mut test); ext_from_hex("0c0000", &mut test); - ext_from_hex("00fd00fd", &mut test); // Two feerate requests during block connection + // Two feerate requests during block connection + ext_from_hex("00fd00fd", &mut test); ext_from_hex("0c0000", &mut test); - ext_from_hex("00fd00fd", &mut test); // Two feerate requests during block connection + // Two feerate requests during block connection + ext_from_hex("00fd00fd", &mut test); ext_from_hex("0c0000", &mut test); - ext_from_hex("00fd00fd", &mut test); // Two feerate requests during block connection + // Two feerate requests during block connection + ext_from_hex("00fd00fd", &mut test); ext_from_hex("0c0000", &mut test); - ext_from_hex("00fd00fd", &mut test); // Two feerate requests during block connection + // Two feerate requests during block connection + ext_from_hex("00fd00fd", &mut test); ext_from_hex("0c0000", &mut test); - ext_from_hex("00fd00fd", &mut test); // Two feerate requests during block connection + // Two feerate requests during block connection + ext_from_hex("00fd00fd", &mut test); ext_from_hex("0c0000", &mut test); - ext_from_hex("00fd00fd", &mut test); // Two feerate requests during block connection + // Two feerate requests during block connection + ext_from_hex("00fd00fd", &mut test); ext_from_hex("0c0000", &mut test); - ext_from_hex("00fd00fd", &mut test); // Two feerate requests during block connection + // Two feerate requests during block connection + ext_from_hex("00fd00fd", &mut test); ext_from_hex("0c0000", &mut test); - ext_from_hex("00fd00fd", &mut test); // Two feerate requests during block connection + // Two feerate requests during block connection + ext_from_hex("00fd00fd", &mut test); ext_from_hex("0c0000", &mut test); - ext_from_hex("00fd00fd", &mut test); // Two feerate requests during block connection + // Two feerate requests during block connection + ext_from_hex("00fd00fd", &mut test); ext_from_hex("0c0000", &mut test); - ext_from_hex("00fd00fd", &mut test); // Two feerate requests during block connection + // Two feerate requests during block connection + ext_from_hex("00fd00fd", &mut test); ext_from_hex("0c0000", &mut test); - ext_from_hex("00fd00fd", &mut test); // Two feerate requests during block connection + // Two feerate requests during block connection + ext_from_hex("00fd00fd", &mut test); // by now client should have sent a channel_ready (CHECK 3: SendChannelReady to 03000000 for chan 3d000000) // inbound read from peer id 0 of len 18 @@ -1316,28 +1341,35 @@ mod tests { ext_from_hex("0c007d", &mut test); // the commitment transaction for channel 3f00000000000000000000000000000000000000000000000000000000000000 ext_from_hex("02000000013a000000000000000000000000000000000000000000000000000000000000000000000000000000800258020000000000002200204b0000000000000000000000000000000000000000000000000000000000000014c0000000000000160014280000000000000000000000000000000000000005000020", &mut test); - ext_from_hex("00fd00fd", &mut test); // Two feerate requests during block connection + // Two feerate requests during block connection + ext_from_hex("00fd00fd", &mut test); // // connect a block with one transaction of len 94 ext_from_hex("0c005e", &mut test); // the HTLC timeout transaction ext_from_hex("0200000001730000000000000000000000000000000000000000000000000000000000000000000000000000000001a701000000000000220020b20000000000000000000000000000000000000000000000000000000000000000000000", &mut test); - ext_from_hex("00fd00fd", &mut test); // Two feerate requests during block connection + // Two feerate requests during block connection + ext_from_hex("00fd00fd", &mut test); // connect a block with no transactions ext_from_hex("0c0000", &mut test); - ext_from_hex("00fd00fd", &mut test); // Two feerate requests during block connection + // Two feerate requests during block connection + ext_from_hex("00fd00fd", &mut test); // connect a block with no transactions ext_from_hex("0c0000", &mut test); - ext_from_hex("00fd00fd", &mut test); // Two feerate requests during block connection + // Two feerate requests during block connection + ext_from_hex("00fd00fd", &mut test); // connect a block with no transactions ext_from_hex("0c0000", &mut test); - ext_from_hex("00fd00fd", &mut test); // Two feerate requests during block connection + // Two feerate requests during block connection + ext_from_hex("00fd00fd", &mut test); // connect a block with no transactions ext_from_hex("0c0000", &mut test); - ext_from_hex("00fd00fd", &mut test); // Two feerate requests during block connection + // Two feerate requests during block connection + ext_from_hex("00fd00fd", &mut test); // connect a block with no transactions ext_from_hex("0c0000", &mut test); - ext_from_hex("00fd00fd", &mut test); // Two feerate requests during block connection + // Two feerate requests during block connection + ext_from_hex("00fd00fd", &mut test); // process the now-pending HTLC forward ext_from_hex("07", &mut test); @@ -1347,16 +1379,26 @@ mod tests { super::do_test(&test, &(Arc::clone(&logger) as Arc)); let log_entries = logger.lines.lock().unwrap(); - assert_eq!(log_entries.get(&("lightning::ln::peer_handler".to_string(), "Handling SendAcceptChannel event in peer_handler for node 030000000000000000000000000000000000000000000000000000000000000002 for channel ff4f00f805273c1b203bb5ebf8436bfde57b3be8c2f5e95d9491dbb181909679".to_string())), Some(&1)); // 1 - assert_eq!(log_entries.get(&("lightning::ln::peer_handler".to_string(), "Handling SendFundingSigned event in peer_handler for node 030000000000000000000000000000000000000000000000000000000000000002 for channel 3d00000000000000000000000000000000000000000000000000000000000000".to_string())), Some(&1)); // 2 - assert_eq!(log_entries.get(&("lightning::ln::peer_handler".to_string(), "Handling SendChannelReady event in peer_handler for node 030000000000000000000000000000000000000000000000000000000000000002 for channel 3d00000000000000000000000000000000000000000000000000000000000000".to_string())), Some(&1)); // 3 - assert_eq!(log_entries.get(&("lightning::ln::peer_handler".to_string(), "Handling SendChannelReady event in peer_handler for node 030200000000000000000000000000000000000000000000000000000000000000 for channel 3a00000000000000000000000000000000000000000000000000000000000000".to_string())), Some(&1)); // 4 - assert_eq!(log_entries.get(&("lightning::ln::peer_handler".to_string(), "Handling SendRevokeAndACK event in peer_handler for node 030000000000000000000000000000000000000000000000000000000000000002 for channel 3d00000000000000000000000000000000000000000000000000000000000000".to_string())), Some(&4)); // 5 - assert_eq!(log_entries.get(&("lightning::ln::peer_handler".to_string(), "Handling UpdateHTLCs event in peer_handler for node 030000000000000000000000000000000000000000000000000000000000000002 with 0 adds, 0 fulfills, 0 fails for channel 3d00000000000000000000000000000000000000000000000000000000000000".to_string())), Some(&3)); // 6 - assert_eq!(log_entries.get(&("lightning::ln::peer_handler".to_string(), "Handling UpdateHTLCs event in peer_handler for node 030200000000000000000000000000000000000000000000000000000000000000 with 1 adds, 0 fulfills, 0 fails for channel 3a00000000000000000000000000000000000000000000000000000000000000".to_string())), Some(&3)); // 7 - assert_eq!(log_entries.get(&("lightning::ln::peer_handler".to_string(), "Handling UpdateHTLCs event in peer_handler for node 030000000000000000000000000000000000000000000000000000000000000002 with 0 adds, 1 fulfills, 0 fails for channel 3d00000000000000000000000000000000000000000000000000000000000000".to_string())), Some(&1)); // 8 - assert_eq!(log_entries.get(&("lightning::ln::peer_handler".to_string(), "Handling UpdateHTLCs event in peer_handler for node 030000000000000000000000000000000000000000000000000000000000000002 with 0 adds, 0 fulfills, 1 fails for channel 3d00000000000000000000000000000000000000000000000000000000000000".to_string())), Some(&2)); // 9 - assert_eq!(log_entries.get(&("lightning::chain::channelmonitor".to_string(), "Input spending counterparty commitment tx (0000000000000000000000000000000000000000000000000000000000000073:0) in 0000000000000000000000000000000000000000000000000000000000000067 resolves outbound HTLC with payment hash ff00000000000000000000000000000000000000000000000000000000000000 with timeout".to_string())), Some(&1)); // 10 + // 1 + assert_eq!(log_entries.get(&("lightning::ln::peer_handler".to_string(), "Handling SendAcceptChannel event in peer_handler for node 030000000000000000000000000000000000000000000000000000000000000002 for channel ff4f00f805273c1b203bb5ebf8436bfde57b3be8c2f5e95d9491dbb181909679".to_string())), Some(&1)); + // 2 + assert_eq!(log_entries.get(&("lightning::ln::peer_handler".to_string(), "Handling SendFundingSigned event in peer_handler for node 030000000000000000000000000000000000000000000000000000000000000002 for channel 3d00000000000000000000000000000000000000000000000000000000000000".to_string())), Some(&1)); + // 3 + assert_eq!(log_entries.get(&("lightning::ln::peer_handler".to_string(), "Handling SendChannelReady event in peer_handler for node 030000000000000000000000000000000000000000000000000000000000000002 for channel 3d00000000000000000000000000000000000000000000000000000000000000".to_string())), Some(&1)); + // 4 + assert_eq!(log_entries.get(&("lightning::ln::peer_handler".to_string(), "Handling SendChannelReady event in peer_handler for node 030200000000000000000000000000000000000000000000000000000000000000 for channel 3a00000000000000000000000000000000000000000000000000000000000000".to_string())), Some(&1)); + // 5 + assert_eq!(log_entries.get(&("lightning::ln::peer_handler".to_string(), "Handling SendRevokeAndACK event in peer_handler for node 030000000000000000000000000000000000000000000000000000000000000002 for channel 3d00000000000000000000000000000000000000000000000000000000000000".to_string())), Some(&4)); + // 6 + assert_eq!(log_entries.get(&("lightning::ln::peer_handler".to_string(), "Handling UpdateHTLCs event in peer_handler for node 030000000000000000000000000000000000000000000000000000000000000002 with 0 adds, 0 fulfills, 0 fails for channel 3d00000000000000000000000000000000000000000000000000000000000000".to_string())), Some(&3)); + // 7 + assert_eq!(log_entries.get(&("lightning::ln::peer_handler".to_string(), "Handling UpdateHTLCs event in peer_handler for node 030200000000000000000000000000000000000000000000000000000000000000 with 1 adds, 0 fulfills, 0 fails for channel 3a00000000000000000000000000000000000000000000000000000000000000".to_string())), Some(&3)); + // 8 + assert_eq!(log_entries.get(&("lightning::ln::peer_handler".to_string(), "Handling UpdateHTLCs event in peer_handler for node 030000000000000000000000000000000000000000000000000000000000000002 with 0 adds, 1 fulfills, 0 fails for channel 3d00000000000000000000000000000000000000000000000000000000000000".to_string())), Some(&1)); + // 9 + assert_eq!(log_entries.get(&("lightning::ln::peer_handler".to_string(), "Handling UpdateHTLCs event in peer_handler for node 030000000000000000000000000000000000000000000000000000000000000002 with 0 adds, 0 fulfills, 1 fails for channel 3d00000000000000000000000000000000000000000000000000000000000000".to_string())), Some(&2)); + // 10 + assert_eq!(log_entries.get(&("lightning::chain::channelmonitor".to_string(), "Input spending counterparty commitment tx (0000000000000000000000000000000000000000000000000000000000000073:0) in 0000000000000000000000000000000000000000000000000000000000000067 resolves outbound HTLC with payment hash ff00000000000000000000000000000000000000000000000000000000000000 with timeout".to_string())), Some(&1)); } #[test] From 4e9ce52c72809ec3e394e4535604ae30d7f9b671 Mon Sep 17 00:00:00 2001 From: Elias Rohrer Date: Mon, 10 Jun 2024 10:48:19 +0200 Subject: [PATCH 5/5] `rustfmt`: `fuzz/src/full_stack.rs` --- fuzz/src/full_stack.rs | 616 ++++++++++++++++++++++++++++++----------- rustfmt_excluded_files | 2 - 2 files changed, 447 insertions(+), 171 deletions(-) diff --git a/fuzz/src/full_stack.rs b/fuzz/src/full_stack.rs index 5394dd313b0..110987d972f 100644 --- a/fuzz/src/full_stack.rs +++ b/fuzz/src/full_stack.rs @@ -15,64 +15,72 @@ use bitcoin::amount::Amount; use bitcoin::blockdata::constants::genesis_block; -use bitcoin::blockdata::transaction::{Transaction, TxOut}; -use bitcoin::blockdata::script::{Builder, ScriptBuf}; -use bitcoin::blockdata::opcodes; use bitcoin::blockdata::locktime::absolute::LockTime; +use bitcoin::blockdata::opcodes; +use bitcoin::blockdata::script::{Builder, ScriptBuf}; +use bitcoin::blockdata::transaction::{Transaction, TxOut}; use bitcoin::consensus::encode::deserialize; use bitcoin::network::Network; use bitcoin::transaction::Version; -use bitcoin::WPubkeyHash; +use bitcoin::hash_types::{BlockHash, Txid}; use bitcoin::hashes::hex::FromHex; -use bitcoin::hashes::Hash as _; use bitcoin::hashes::sha256::Hash as Sha256; use bitcoin::hashes::sha256d::Hash as Sha256dHash; -use bitcoin::hash_types::{Txid, BlockHash}; +use bitcoin::hashes::Hash as _; +use bitcoin::WPubkeyHash; -use lightning::blinded_path::BlindedPath; use lightning::blinded_path::payment::ReceiveTlvs; +use lightning::blinded_path::BlindedPath; use lightning::chain; -use lightning::chain::{BestBlock, ChannelMonitorUpdateStatus, Confirm, Listen}; use lightning::chain::chaininterface::{BroadcasterInterface, ConfirmationTarget, FeeEstimator}; use lightning::chain::chainmonitor; use lightning::chain::transaction::OutPoint; -use lightning::sign::{InMemorySigner, Recipient, KeyMaterial, EntropySource, NodeSigner, SignerProvider}; +use lightning::chain::{BestBlock, ChannelMonitorUpdateStatus, Confirm, Listen}; use lightning::events::Event; -use lightning::ln::{ChannelId, PaymentHash, PaymentPreimage, PaymentSecret}; use lightning::ln::channel_state::ChannelDetails; -use lightning::ln::channelmanager::{ChainParameters, ChannelManager, PaymentId, RecipientOnionFields, Retry, InterceptId}; -use lightning::ln::peer_handler::{MessageHandler,PeerManager,SocketDescriptor,IgnoringMessageHandler}; +use lightning::ln::channelmanager::{ + ChainParameters, ChannelManager, InterceptId, PaymentId, RecipientOnionFields, Retry, +}; +use lightning::ln::functional_test_utils::*; use lightning::ln::msgs::{self, DecodeError}; +use lightning::ln::peer_handler::{ + IgnoringMessageHandler, MessageHandler, PeerManager, SocketDescriptor, +}; use lightning::ln::script::ShutdownScript; -use lightning::ln::functional_test_utils::*; +use lightning::ln::{ChannelId, PaymentHash, PaymentPreimage, PaymentSecret}; use lightning::offers::invoice::{BlindedPayInfo, UnsignedBolt12Invoice}; use lightning::offers::invoice_request::UnsignedInvoiceRequest; use lightning::onion_message::messenger::{Destination, MessageRouter, OnionMessagePath}; -use lightning::routing::gossip::{P2PGossipSync, NetworkGraph}; +use lightning::routing::gossip::{NetworkGraph, P2PGossipSync}; +use lightning::routing::router::{ + InFlightHtlcs, PaymentParameters, Route, RouteParameters, Router, +}; use lightning::routing::utxo::UtxoLookup; -use lightning::routing::router::{InFlightHtlcs, PaymentParameters, Route, RouteParameters, Router}; +use lightning::sign::{ + EntropySource, InMemorySigner, KeyMaterial, NodeSigner, Recipient, SignerProvider, +}; use lightning::util::config::{ChannelConfig, UserConfig}; -use lightning::util::hash_tables::*; use lightning::util::errors::APIError; -use lightning::util::test_channel_signer::{TestChannelSigner, EnforcementState}; +use lightning::util::hash_tables::*; use lightning::util::logger::Logger; use lightning::util::ser::{Readable, ReadableArgs, Writeable}; +use lightning::util::test_channel_signer::{EnforcementState, TestChannelSigner}; use crate::utils::test_logger; use crate::utils::test_persister::TestPersister; -use bitcoin::secp256k1::{Message, PublicKey, SecretKey, Scalar, Secp256k1, self}; use bitcoin::secp256k1::ecdh::SharedSecret; use bitcoin::secp256k1::ecdsa::{RecoverableSignature, Signature}; use bitcoin::secp256k1::schnorr; +use bitcoin::secp256k1::{self, Message, PublicKey, Scalar, Secp256k1, SecretKey}; +use bech32::u5; use std::cell::RefCell; -use std::convert::TryInto; use std::cmp; +use std::convert::TryInto; +use std::sync::atomic::{AtomicBool, AtomicU64, AtomicUsize, Ordering}; use std::sync::{Arc, Mutex}; -use std::sync::atomic::{AtomicU64,AtomicUsize,AtomicBool,Ordering}; -use bech32::u5; #[inline] #[rustfmt::skip] @@ -84,8 +92,8 @@ pub fn slice_to_be16(v: &[u8]) -> u16 { #[inline] pub fn be16_to_array(u: u16) -> [u8; 2] { let mut v = [0; 2]; - v[0] = ((u >> 8*1) & 0xff) as u8; - v[1] = ((u >> 8*0) & 0xff) as u8; + v[0] = ((u >> 8 * 1) & 0xff) as u8; + v[1] = ((u >> 8 * 0) & 0xff) as u8; v } @@ -133,7 +141,7 @@ impl FeeEstimator for FuzzEstimator { //TODO: We should actually be testing at least much more than 64k... match self.input.get_slice(2) { Some(slice) => cmp::max(slice_to_be16(slice) as u32, 253), - None => 253 + None => 253, } } } @@ -142,12 +150,12 @@ struct FuzzRouter {} impl Router for FuzzRouter { fn find_route( - &self, _payer: &PublicKey, _params: &RouteParameters, _first_hops: Option<&[&ChannelDetails]>, - _inflight_htlcs: InFlightHtlcs + &self, _payer: &PublicKey, _params: &RouteParameters, + _first_hops: Option<&[&ChannelDetails]>, _inflight_htlcs: InFlightHtlcs, ) -> Result { Err(msgs::LightningError { err: String::from("Not implemented"), - action: msgs::ErrorAction::IgnoreError + action: msgs::ErrorAction::IgnoreError, }) } @@ -161,7 +169,7 @@ impl Router for FuzzRouter { impl MessageRouter for FuzzRouter { fn find_path( - &self, _sender: PublicKey, _peers: Vec, _destination: Destination + &self, _sender: PublicKey, _peers: Vec, _destination: Destination, ) -> Result { unreachable!() } @@ -204,19 +212,52 @@ impl<'a> PartialEq for Peer<'a> { } impl<'a> Eq for Peer<'a> {} impl<'a> std::hash::Hash for Peer<'a> { - fn hash(&self, h: &mut H) { + fn hash(&self, h: &mut H) { self.id.hash(h) } } type ChannelMan<'a> = ChannelManager< - Arc, Arc, Arc, Arc, Arc>>, - Arc, Arc, Arc, Arc, Arc, &'a FuzzRouter, Arc>; -type PeerMan<'a> = PeerManager, Arc>, Arc>>, Arc, Arc>>, IgnoringMessageHandler, Arc, IgnoringMessageHandler, Arc>; + Arc< + chainmonitor::ChainMonitor< + TestChannelSigner, + Arc, + Arc, + Arc, + Arc, + Arc, + >, + >, + Arc, + Arc, + Arc, + Arc, + Arc, + &'a FuzzRouter, + Arc, +>; +type PeerMan<'a> = PeerManager< + Peer<'a>, + Arc>, + Arc>>, Arc, Arc>>, + IgnoringMessageHandler, + Arc, + IgnoringMessageHandler, + Arc, +>; struct MoneyLossDetector<'a> { manager: Arc>, - monitor: Arc, Arc, Arc, Arc, Arc>>, + monitor: Arc< + chainmonitor::ChainMonitor< + TestChannelSigner, + Arc, + Arc, + Arc, + Arc, + Arc, + >, + >, handler: PeerMan<'a>, peers: &'a RefCell<[bool; 256]>, @@ -229,10 +270,20 @@ struct MoneyLossDetector<'a> { error_message: String, } impl<'a> MoneyLossDetector<'a> { - pub fn new(peers: &'a RefCell<[bool; 256]>, - manager: Arc>, - monitor: Arc, Arc, Arc, Arc, Arc>>, - handler: PeerMan<'a>) -> Self { + pub fn new( + peers: &'a RefCell<[bool; 256]>, manager: Arc>, + monitor: Arc< + chainmonitor::ChainMonitor< + TestChannelSigner, + Arc, + Arc, + Arc, + Arc, + Arc, + >, + >, + handler: PeerMan<'a>, + ) -> Self { MoneyLossDetector { manager, monitor, @@ -277,14 +328,15 @@ impl<'a> MoneyLossDetector<'a> { fn disconnect_block(&mut self) { if self.height > 0 && (self.max_height < 6 || self.height >= self.max_height - 6) { - let header = create_dummy_header(self.header_hashes[self.height - 1].0, self.header_hashes[self.height].1); + let header = create_dummy_header( + self.header_hashes[self.height - 1].0, + self.header_hashes[self.height].1, + ); self.manager.block_disconnected(&header, self.height as u32); self.monitor.block_disconnected(&header, self.height as u32); self.height -= 1; let removal_height = self.height; - self.txids_confirmed.retain(|_, height| { - removal_height != *height - }); + self.txids_confirmed.retain(|_, height| removal_height != *height); } } } @@ -295,12 +347,14 @@ impl<'a> Drop for MoneyLossDetector<'a> { // Disconnect all peers for (idx, peer) in self.peers.borrow().iter().enumerate() { if *peer { - self.handler.socket_disconnected(&Peer{id: idx as u8, peers_connected: &self.peers}); + self.handler + .socket_disconnected(&Peer { id: idx as u8, peers_connected: &self.peers }); } } // Force all channels onto the chain (and time out claim txn) - self.manager.force_close_all_channels_broadcasting_latest_txn(self.error_message.to_string()); + self.manager + .force_close_all_channels_broadcasting_latest_txn(self.error_message.to_string()); } } } @@ -309,7 +363,7 @@ struct KeyProvider { node_secret: SecretKey, inbound_payment_key: KeyMaterial, counter: AtomicU64, - signer_state: RefCell>)>> + signer_state: RefCell>)>>, } impl EntropySource for KeyProvider { @@ -327,15 +381,17 @@ impl NodeSigner for KeyProvider { fn get_node_id(&self, recipient: Recipient) -> Result { let node_secret = match recipient { Recipient::Node => Ok(&self.node_secret), - Recipient::PhantomNode => Err(()) + Recipient::PhantomNode => Err(()), }?; Ok(PublicKey::from_secret_key(&Secp256k1::signing_only(), node_secret)) } - fn ecdh(&self, recipient: Recipient, other_key: &PublicKey, tweak: Option<&Scalar>) -> Result { + fn ecdh( + &self, recipient: Recipient, other_key: &PublicKey, tweak: Option<&Scalar>, + ) -> Result { let mut node_secret = match recipient { Recipient::Node => Ok(self.node_secret.clone()), - Recipient::PhantomNode => Err(()) + Recipient::PhantomNode => Err(()), }?; if let Some(tweak) = tweak { node_secret = node_secret.mul_tweak(tweak).map_err(|_| ())?; @@ -347,12 +403,14 @@ impl NodeSigner for KeyProvider { self.inbound_payment_key.clone() } - fn sign_invoice(&self, _hrp_bytes: &[u8], _invoice_data: &[u5], _recipient: Recipient) -> Result { + fn sign_invoice( + &self, _hrp_bytes: &[u8], _invoice_data: &[u5], _recipient: Recipient, + ) -> Result { unreachable!() } fn sign_bolt12_invoice_request( - &self, _invoice_request: &UnsignedInvoiceRequest + &self, _invoice_request: &UnsignedInvoiceRequest, ) -> Result { unreachable!() } @@ -363,7 +421,9 @@ impl NodeSigner for KeyProvider { unreachable!() } - fn sign_gossip_message(&self, msg: lightning::ln::msgs::UnsignedGossipMessage) -> Result { + fn sign_gossip_message( + &self, msg: lightning::ln::msgs::UnsignedGossipMessage, + ) -> Result { let msg_hash = Message::from_digest(Sha256dHash::hash(&msg.encode()[..]).to_byte_array()); let secp_ctx = Secp256k1::signing_only(); Ok(secp_ctx.sign_ecdsa(&msg_hash, &self.node_secret)) @@ -375,74 +435,144 @@ impl SignerProvider for KeyProvider { #[cfg(taproot)] type TaprootSigner = TestChannelSigner; - fn generate_channel_keys_id(&self, inbound: bool, _channel_value_satoshis: u64, _user_channel_id: u128) -> [u8; 32] { + fn generate_channel_keys_id( + &self, inbound: bool, _channel_value_satoshis: u64, _user_channel_id: u128, + ) -> [u8; 32] { let ctr = self.counter.fetch_add(1, Ordering::Relaxed) as u8; - self.signer_state.borrow_mut().insert(ctr, (inbound, Arc::new(Mutex::new(EnforcementState::new())))); + self.signer_state + .borrow_mut() + .insert(ctr, (inbound, Arc::new(Mutex::new(EnforcementState::new())))); [ctr; 32] } - fn derive_channel_signer(&self, channel_value_satoshis: u64, channel_keys_id: [u8; 32]) -> Self::EcdsaSigner { + fn derive_channel_signer( + &self, channel_value_satoshis: u64, channel_keys_id: [u8; 32], + ) -> Self::EcdsaSigner { let secp_ctx = Secp256k1::signing_only(); let ctr = channel_keys_id[0]; let (inbound, state) = self.signer_state.borrow().get(&ctr).unwrap().clone(); - TestChannelSigner::new_with_revoked(if inbound { - InMemorySigner::new( - &secp_ctx, - SecretKey::from_slice(&[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, ctr]).unwrap(), - SecretKey::from_slice(&[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, ctr]).unwrap(), - SecretKey::from_slice(&[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, ctr]).unwrap(), - SecretKey::from_slice(&[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, ctr]).unwrap(), - SecretKey::from_slice(&[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, ctr]).unwrap(), - [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, ctr], - channel_value_satoshis, - channel_keys_id, - channel_keys_id, - ) - } else { - InMemorySigner::new( - &secp_ctx, - SecretKey::from_slice(&[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, ctr]).unwrap(), - SecretKey::from_slice(&[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8, ctr]).unwrap(), - SecretKey::from_slice(&[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9, ctr]).unwrap(), - SecretKey::from_slice(&[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 10, ctr]).unwrap(), - SecretKey::from_slice(&[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 11, ctr]).unwrap(), - [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 12, ctr], - channel_value_satoshis, - channel_keys_id, - channel_keys_id, - ) - }, state, false) + TestChannelSigner::new_with_revoked( + if inbound { + InMemorySigner::new( + &secp_ctx, + SecretKey::from_slice(&[ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 1, ctr, + ]) + .unwrap(), + SecretKey::from_slice(&[ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 2, ctr, + ]) + .unwrap(), + SecretKey::from_slice(&[ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 3, ctr, + ]) + .unwrap(), + SecretKey::from_slice(&[ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 4, ctr, + ]) + .unwrap(), + SecretKey::from_slice(&[ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 5, ctr, + ]) + .unwrap(), + [ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 6, ctr, + ], + channel_value_satoshis, + channel_keys_id, + channel_keys_id, + ) + } else { + InMemorySigner::new( + &secp_ctx, + SecretKey::from_slice(&[ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 7, ctr, + ]) + .unwrap(), + SecretKey::from_slice(&[ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 8, ctr, + ]) + .unwrap(), + SecretKey::from_slice(&[ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 9, ctr, + ]) + .unwrap(), + SecretKey::from_slice(&[ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 10, ctr, + ]) + .unwrap(), + SecretKey::from_slice(&[ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 11, ctr, + ]) + .unwrap(), + [ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 12, ctr, + ], + channel_value_satoshis, + channel_keys_id, + channel_keys_id, + ) + }, + state, + false, + ) } fn read_chan_signer(&self, mut data: &[u8]) -> Result { let inner: InMemorySigner = ReadableArgs::read(&mut data, self)?; let state = Arc::new(Mutex::new(EnforcementState::new())); - Ok(TestChannelSigner::new_with_revoked( - inner, - state, - false - )) + Ok(TestChannelSigner::new_with_revoked(inner, state, false)) } fn get_destination_script(&self, _channel_keys_id: [u8; 32]) -> Result { let secp_ctx = Secp256k1::signing_only(); - let channel_monitor_claim_key = SecretKey::from_slice(&>::from_hex("0fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff").unwrap()[..]).unwrap(); - let our_channel_monitor_claim_key_hash = WPubkeyHash::hash(&PublicKey::from_secret_key(&secp_ctx, &channel_monitor_claim_key).serialize()); - Ok(Builder::new().push_opcode(opcodes::all::OP_PUSHBYTES_0).push_slice(our_channel_monitor_claim_key_hash).into_script()) + let channel_monitor_claim_key = SecretKey::from_slice( + &>::from_hex( + "0fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff", + ) + .unwrap()[..], + ) + .unwrap(); + let our_channel_monitor_claim_key_hash = WPubkeyHash::hash( + &PublicKey::from_secret_key(&secp_ctx, &channel_monitor_claim_key).serialize(), + ); + Ok(Builder::new() + .push_opcode(opcodes::all::OP_PUSHBYTES_0) + .push_slice(our_channel_monitor_claim_key_hash) + .into_script()) } fn get_shutdown_scriptpubkey(&self) -> Result { let secp_ctx = Secp256k1::signing_only(); - let secret_key = SecretKey::from_slice(&[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1]).unwrap(); - let pubkey_hash = WPubkeyHash::hash(&PublicKey::from_secret_key(&secp_ctx, &secret_key).serialize()); + let secret_key = SecretKey::from_slice(&[ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 1, + ]) + .unwrap(); + let pubkey_hash = + WPubkeyHash::hash(&PublicKey::from_secret_key(&secp_ctx, &secret_key).serialize()); Ok(ShutdownScript::new_p2wpkh(&pubkey_hash)) } } #[inline] pub fn do_test(mut data: &[u8], logger: &Arc) { - if data.len() < 32 { return; } + if data.len() < 32 { + return; + } let our_network_key = match SecretKey::from_slice(&data[..32]) { Ok(key) => key, @@ -450,16 +580,18 @@ pub fn do_test(mut data: &[u8], logger: &Arc) { }; data = &data[32..]; - let config: UserConfig = if let Ok(config) = Readable::read(&mut data) { config } else { return; }; + let config: UserConfig = if let Ok(config) = Readable::read(&mut data) { + config + } else { + return; + }; let input = Arc::new(InputData { data: data.to_vec(), read_pos: AtomicUsize::new(0), halt_fee_est_reads: AtomicBool::new(false), }); - let fee_est = Arc::new(FuzzEstimator { - input: input.clone(), - }); + let fee_est = Arc::new(FuzzEstimator { input: input.clone() }); let router = FuzzRouter {}; macro_rules! get_slice { @@ -468,18 +600,18 @@ pub fn do_test(mut data: &[u8], logger: &Arc) { Some(slice) => slice, None => return, } - } + }; } macro_rules! get_bytes { - ($len: expr) => { { + ($len: expr) => {{ let mut res = [0; $len]; match input.get_slice($len as usize) { Some(slice) => res.copy_from_slice(slice), None => return, } res - } } + }}; } macro_rules! get_pubkey { @@ -488,35 +620,52 @@ pub fn do_test(mut data: &[u8], logger: &Arc) { Ok(key) => key, Err(_) => return, } - } + }; } + let inbound_payment_key = [ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 42, + ]; - let inbound_payment_key = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 42]; - - let broadcast = Arc::new(TestBroadcaster{ txn_broadcasted: Mutex::new(Vec::new()) }); - let monitor = Arc::new(chainmonitor::ChainMonitor::new(None, broadcast.clone(), Arc::clone(&logger), fee_est.clone(), - Arc::new(TestPersister { update_ret: Mutex::new(ChannelMonitorUpdateStatus::Completed) }))); + let broadcast = Arc::new(TestBroadcaster { txn_broadcasted: Mutex::new(Vec::new()) }); + let monitor = Arc::new(chainmonitor::ChainMonitor::new( + None, + broadcast.clone(), + Arc::clone(&logger), + fee_est.clone(), + Arc::new(TestPersister { update_ret: Mutex::new(ChannelMonitorUpdateStatus::Completed) }), + )); let keys_manager = Arc::new(KeyProvider { node_secret: our_network_key.clone(), inbound_payment_key: KeyMaterial(inbound_payment_key.try_into().unwrap()), counter: AtomicU64::new(0), - signer_state: RefCell::new(new_hash_map()) + signer_state: RefCell::new(new_hash_map()), }); let network = Network::Bitcoin; let best_block_timestamp = genesis_block(network).header.time; - let params = ChainParameters { - network, - best_block: BestBlock::from_network(network), - }; - let channelmanager = Arc::new(ChannelManager::new(fee_est.clone(), monitor.clone(), broadcast.clone(), &router, Arc::clone(&logger), keys_manager.clone(), keys_manager.clone(), keys_manager.clone(), config, params, best_block_timestamp)); + let params = ChainParameters { network, best_block: BestBlock::from_network(network) }; + let channelmanager = Arc::new(ChannelManager::new( + fee_est.clone(), + monitor.clone(), + broadcast.clone(), + &router, + Arc::clone(&logger), + keys_manager.clone(), + keys_manager.clone(), + keys_manager.clone(), + config, + params, + best_block_timestamp, + )); // Adding new calls to `EntropySource::get_secure_random_bytes` during startup can change all the // keys subsequently generated in this test. Rather than regenerating all the messages manually, // it's easier to just increment the counter here so the keys don't change. keys_manager.counter.fetch_sub(3, Ordering::AcqRel); let network_graph = Arc::new(NetworkGraph::new(network, Arc::clone(&logger))); - let gossip_sync = Arc::new(P2PGossipSync::new(Arc::clone(&network_graph), None, Arc::clone(&logger))); + let gossip_sync = + Arc::new(P2PGossipSync::new(Arc::clone(&network_graph), None, Arc::clone(&logger))); let peers = RefCell::new([false; 256]); let message_handler = MessageHandler { @@ -525,9 +674,19 @@ pub fn do_test(mut data: &[u8], logger: &Arc) { onion_message_handler: IgnoringMessageHandler {}, custom_message_handler: IgnoringMessageHandler {}, }; - let random_data = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 15, 0]; - let peer_manager = PeerManager::new(message_handler, 0, &random_data, Arc::clone(&logger), keys_manager.clone()); - let mut loss_detector = MoneyLossDetector::new(&peers, channelmanager.clone(), monitor.clone(), peer_manager); + let random_data = [ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 15, 0, + ]; + let peer_manager = PeerManager::new( + message_handler, + 0, + &random_data, + Arc::clone(&logger), + keys_manager.clone(), + ); + let mut loss_detector = + MoneyLossDetector::new(&peers, channelmanager.clone(), monitor.clone(), peer_manager); let mut should_forward = false; let mut payments_received: Vec = Vec::new(); @@ -541,64 +700,81 @@ pub fn do_test(mut data: &[u8], logger: &Arc) { 0 => { let mut new_id = 0; for i in 1..256 { - if !peers.borrow()[i-1] { + if !peers.borrow()[i - 1] { new_id = i; break; } } - if new_id == 0 { return; } - let peer = Peer{id: (new_id - 1) as u8, peers_connected: &peers}; + if new_id == 0 { + return; + } + let peer = Peer { id: (new_id - 1) as u8, peers_connected: &peers }; loss_detector.handler.new_outbound_connection(get_pubkey!(), peer, None).unwrap(); peers.borrow_mut()[new_id - 1] = true; }, 1 => { let mut new_id = 0; for i in 1..256 { - if !peers.borrow()[i-1] { + if !peers.borrow()[i - 1] { new_id = i; break; } } - if new_id == 0 { return; } - let peer = Peer{id: (new_id - 1) as u8, peers_connected: &peers}; + if new_id == 0 { + return; + } + let peer = Peer { id: (new_id - 1) as u8, peers_connected: &peers }; loss_detector.handler.new_inbound_connection(peer, None).unwrap(); peers.borrow_mut()[new_id - 1] = true; }, 2 => { let peer_id = get_slice!(1)[0]; - if !peers.borrow()[peer_id as usize] { return; } - let peer = Peer{id: peer_id, peers_connected: &peers}; + if !peers.borrow()[peer_id as usize] { + return; + } + let peer = Peer { id: peer_id, peers_connected: &peers }; loss_detector.handler.socket_disconnected(&peer); peers.borrow_mut()[peer_id as usize] = false; }, 3 => { let peer_id = get_slice!(1)[0]; - if !peers.borrow()[peer_id as usize] { return; } - let mut peer = Peer{id: peer_id, peers_connected: &peers}; + if !peers.borrow()[peer_id as usize] { + return; + } + let mut peer = Peer { id: peer_id, peers_connected: &peers }; match loss_detector.handler.read_event(&mut peer, get_slice!(get_slice!(1)[0])) { Ok(res) => assert!(!res), - Err(_) => { peers.borrow_mut()[peer_id as usize] = false; } + Err(_) => { + peers.borrow_mut()[peer_id as usize] = false; + }, } }, 4 => { let final_value_msat = slice_to_be24(get_slice!(3)) as u64; let payment_params = PaymentParameters::from_node_id(get_pubkey!(), 42); let params = RouteParameters::from_payment_params_and_value( - payment_params, final_value_msat); + payment_params, + final_value_msat, + ); let mut payment_hash = PaymentHash([0; 32]); payment_hash.0[0..2].copy_from_slice(&be16_to_array(payments_sent)); payment_hash.0 = Sha256::hash(&payment_hash.0[..]).to_byte_array(); payments_sent += 1; let _ = channelmanager.send_payment( - payment_hash, RecipientOnionFields::spontaneous_empty(), - PaymentId(payment_hash.0), params, Retry::Attempts(2) + payment_hash, + RecipientOnionFields::spontaneous_empty(), + PaymentId(payment_hash.0), + params, + Retry::Attempts(2), ); }, 15 => { let final_value_msat = slice_to_be24(get_slice!(3)) as u64; let payment_params = PaymentParameters::from_node_id(get_pubkey!(), 42); let params = RouteParameters::from_payment_params_and_value( - payment_params, final_value_msat); + payment_params, + final_value_msat, + ); let mut payment_hash = PaymentHash([0; 32]); payment_hash.0[0..2].copy_from_slice(&be16_to_array(payments_sent)); payment_hash.0 = Sha256::hash(&payment_hash.0[..]).to_byte_array(); @@ -607,15 +783,20 @@ pub fn do_test(mut data: &[u8], logger: &Arc) { payment_secret.0[0..2].copy_from_slice(&be16_to_array(payments_sent)); payments_sent += 1; let _ = channelmanager.send_payment( - payment_hash, RecipientOnionFields::secret_only(payment_secret), - PaymentId(payment_hash.0), params, Retry::Attempts(2) + payment_hash, + RecipientOnionFields::secret_only(payment_secret), + PaymentId(payment_hash.0), + params, + Retry::Attempts(2), ); }, 17 => { let final_value_msat = slice_to_be24(get_slice!(3)) as u64; let payment_params = PaymentParameters::from_node_id(get_pubkey!(), 42); let params = RouteParameters::from_payment_params_and_value( - payment_params, final_value_msat); + payment_params, + final_value_msat, + ); let _ = channelmanager.send_preflight_probes(params, None); }, 18 => { @@ -626,18 +807,35 @@ pub fn do_test(mut data: &[u8], logger: &Arc) { }, 5 => { let peer_id = get_slice!(1)[0]; - if !peers.borrow()[peer_id as usize] { return; } + if !peers.borrow()[peer_id as usize] { + return; + } let their_key = get_pubkey!(); let chan_value = slice_to_be24(get_slice!(3)) as u64; let push_msat_value = slice_to_be24(get_slice!(3)) as u64; - if channelmanager.create_channel(their_key, chan_value, push_msat_value, 0, None, None).is_err() { return; } + if channelmanager + .create_channel(their_key, chan_value, push_msat_value, 0, None, None) + .is_err() + { + return; + } }, 6 => { let mut channels = channelmanager.list_channels(); let channel_id = get_slice!(1)[0] as usize; - if channel_id >= channels.len() { return; } - channels.sort_by(|a, b| { a.channel_id.cmp(&b.channel_id) }); - if channelmanager.close_channel(&channels[channel_id].channel_id, &channels[channel_id].counterparty.node_id).is_err() { return; } + if channel_id >= channels.len() { + return; + } + channels.sort_by(|a, b| a.channel_id.cmp(&b.channel_id)); + if channelmanager + .close_channel( + &channels[channel_id].channel_id, + &channels[channel_id].counterparty.node_id, + ) + .is_err() + { + return; + } }, 7 => { if should_forward { @@ -662,7 +860,8 @@ pub fn do_test(mut data: &[u8], logger: &Arc) { }, 16 => { let payment_preimage = PaymentPreimage(keys_manager.get_secure_random_bytes()); - let payment_hash = PaymentHash(Sha256::hash(&payment_preimage.0[..]).to_byte_array()); + let payment_hash = + PaymentHash(Sha256::hash(&payment_preimage.0[..]).to_byte_array()); // Note that this may fail - our hashes may collide and we'll end up trying to // double-register the same payment_hash. let _ = channelmanager.create_inbound_payment_for_hash(payment_hash, None, 1, None); @@ -673,11 +872,17 @@ pub fn do_test(mut data: &[u8], logger: &Arc) { } }, 10 => { - let mut tx = Transaction { version: Version(0), lock_time: LockTime::ZERO, input: Vec::new(), output: Vec::new() }; + let mut tx = Transaction { + version: Version(0), + lock_time: LockTime::ZERO, + input: Vec::new(), + output: Vec::new(), + }; let mut channels = Vec::new(); for funding_generation in pending_funding_generation.drain(..) { let txout = TxOut { - value: Amount::from_sat(funding_generation.2), script_pubkey: funding_generation.3, + value: Amount::from_sat(funding_generation.2), + script_pubkey: funding_generation.3, }; if !tx.output.contains(&txout) { tx.output.push(txout); @@ -705,10 +910,15 @@ pub fn do_test(mut data: &[u8], logger: &Arc) { } if tx.version.0 <= 0xff && !channels.is_empty() { let chans = channels.iter().map(|(a, b)| (a, b)).collect::>(); - if let Err(e) = channelmanager.batch_funding_transaction_generated(&chans, tx.clone()) { + if let Err(e) = + channelmanager.batch_funding_transaction_generated(&chans, tx.clone()) + { // It's possible the channel has been closed in the mean time, but any other // failure may be a bug. - if let APIError::ChannelUnavailable { .. } = e { } else { panic!(); } + if let APIError::ChannelUnavailable { .. } = e { + } else { + panic!(); + } } let funding_txid = tx.txid(); for idx in 0..tx.output.len() { @@ -740,9 +950,13 @@ pub fn do_test(mut data: &[u8], logger: &Arc) { if let Ok(tx) = txres { let mut output_val = Amount::ZERO; for out in tx.output.iter() { - if out.value > Amount::MAX_MONEY { return; } + if out.value > Amount::MAX_MONEY { + return; + } output_val += out.value; - if output_val > Amount::MAX_MONEY { return; } + if output_val > Amount::MAX_MONEY { + return; + } } loss_detector.connect_block(&[tx]); } else { @@ -757,9 +971,17 @@ pub fn do_test(mut data: &[u8], logger: &Arc) { let mut channels = channelmanager.list_channels(); let channel_id = get_slice!(1)[0] as usize; let error_message = "Channel force-closed"; - if channel_id >= channels.len() { return; } - channels.sort_by(|a, b| { a.channel_id.cmp(&b.channel_id) }); - channelmanager.force_close_broadcasting_latest_txn(&channels[channel_id].channel_id, &channels[channel_id].counterparty.node_id, error_message.to_string()).unwrap(); + if channel_id >= channels.len() { + return; + } + channels.sort_by(|a, b| a.channel_id.cmp(&b.channel_id)); + channelmanager + .force_close_broadcasting_latest_txn( + &channels[channel_id].channel_id, + &channels[channel_id].counterparty.node_id, + error_message.to_string(), + ) + .unwrap(); }, // 15, 16, 17, 18 is above 19 => { @@ -771,14 +993,13 @@ pub fn do_test(mut data: &[u8], logger: &Arc) { }, 20 => loss_detector.handler.disconnect_all_peers(), 21 => loss_detector.handler.timer_tick_occurred(), - 22 => - loss_detector.handler.broadcast_node_announcement([42; 3], [43; 32], Vec::new()), + 22 => loss_detector.handler.broadcast_node_announcement([42; 3], [43; 32], Vec::new()), 32 => channelmanager.timer_tick_occurred(), 33 => { for id in intercepted_htlcs.drain(..) { channelmanager.fail_intercepted_htlc(id).unwrap(); } - } + }, 34 => { let amt = u64::from_be_bytes(get_bytes!(8)); let chans = channelmanager.list_channels(); @@ -787,33 +1008,56 @@ pub fn do_test(mut data: &[u8], logger: &Arc) { channelmanager.fail_intercepted_htlc(id).unwrap(); } else { let chan = &chans[amt as usize % chans.len()]; - channelmanager.forward_intercepted_htlc(id, &chan.channel_id, chan.counterparty.node_id, amt).unwrap(); + channelmanager + .forward_intercepted_htlc( + id, + &chan.channel_id, + chan.counterparty.node_id, + amt, + ) + .unwrap(); } } - } + }, 35 => { - let config: ChannelConfig = - if let Ok(c) = Readable::read(&mut &*input) { c } else { return; }; + let config: ChannelConfig = if let Ok(c) = Readable::read(&mut &*input) { + c + } else { + return; + }; let chans = channelmanager.list_channels(); if let Some(chan) = chans.get(0) { let _ = channelmanager.update_channel_config( - &chan.counterparty.node_id, &[chan.channel_id], &config + &chan.counterparty.node_id, + &[chan.channel_id], + &config, ); } - } + }, _ => return, } loss_detector.handler.process_events(); for event in loss_detector.manager.get_and_clear_pending_events() { match event { - Event::FundingGenerationReady { temporary_channel_id, counterparty_node_id, channel_value_satoshis, output_script, .. } => { - pending_funding_generation.push((temporary_channel_id, counterparty_node_id, channel_value_satoshis, output_script)); + Event::FundingGenerationReady { + temporary_channel_id, + counterparty_node_id, + channel_value_satoshis, + output_script, + .. + } => { + pending_funding_generation.push(( + temporary_channel_id, + counterparty_node_id, + channel_value_satoshis, + output_script, + )); }, Event::PaymentClaimable { payment_hash, .. } => { //TODO: enhance by fetching random amounts from fuzz input? payments_received.push(payment_hash); }, - Event::PendingHTLCsForwardable {..} => { + Event::PendingHTLCsForwardable { .. } => { should_forward = true; }, Event::HTLCIntercepted { intercept_id, .. } => { @@ -834,7 +1078,8 @@ pub fn full_stack_test(data: &[u8], out: Out) { #[no_mangle] pub extern "C" fn full_stack_run(data: *const u8, datalen: usize) { - let logger: Arc = Arc::new(test_logger::TestLogger::new("".to_owned(), test_logger::DevNull {})); + let logger: Arc = + Arc::new(test_logger::TestLogger::new("".to_owned(), test_logger::DevNull {})); do_test(unsafe { std::slice::from_raw_parts(data, datalen) }, &logger); } @@ -851,8 +1096,20 @@ mod tests { } impl Logger for TrackingLogger { fn log(&self, record: Record) { - *self.lines.lock().unwrap().entry((record.module_path.to_string(), format!("{}", record.args))).or_insert(0) += 1; - println!("{:<5} [{} : {}, {}] {}", record.level.to_string(), record.module_path, record.file, record.line, record.args); + *self + .lines + .lock() + .unwrap() + .entry((record.module_path.to_string(), format!("{}", record.args))) + .or_insert(0) += 1; + println!( + "{:<5} [{} : {}, {}] {}", + record.level.to_string(), + record.module_path, + record.file, + record.line, + record.args + ); } } @@ -887,7 +1144,10 @@ mod tests { // new outbound connection with id 0 ext_from_hex("00", &mut test); // peer's pubkey - ext_from_hex("030000000000000000000000000000000000000000000000000000000000000002", &mut test); + ext_from_hex( + "030000000000000000000000000000000000000000000000000000000000000002", + &mut test, + ); // inbound read from peer id 0 of len 50 ext_from_hex("030032", &mut test); // noise act two (0||pubkey||mac) @@ -900,7 +1160,10 @@ mod tests { // inbound read from peer id 0 of len 32 ext_from_hex("030020", &mut test); // init message (type 16) with static_remotekey required, no channel_type/anchors/taproot, and other bits optional and mac - ext_from_hex("0010 00021aaa 0008aaa20aaa2a0a9aaa 03000000000000000000000000000000", &mut test); + ext_from_hex( + "0010 00021aaa 0008aaa20aaa2a0a9aaa 03000000000000000000000000000000", + &mut test, + ); // inbound read from peer id 0 of len 18 ext_from_hex("030012", &mut test); @@ -1001,7 +1264,10 @@ mod tests { // inbound read from peer id 1 of len 32 ext_from_hex("030120", &mut test); // init message (type 16) with static_remotekey required, no channel_type/anchors/taproot, and other bits optional and mac - ext_from_hex("0010 00021aaa 0008aaa20aaa2a0a9aaa 01000000000000000000000000000000", &mut test); + ext_from_hex( + "0010 00021aaa 0008aaa20aaa2a0a9aaa 01000000000000000000000000000000", + &mut test, + ); // create outbound channel to peer 1 for 50k sat ext_from_hex("05 01 030200000000000000000000000000000000000000000000000000000000000000 00c350 0003e8", &mut test); @@ -1019,7 +1285,10 @@ mod tests { // inbound read from peer id 1 of len 35 ext_from_hex("030123", &mut test); // rest of accept_channel and mac - ext_from_hex("0000000000000000000000000000000000 0000 01000000000000000000000000000000", &mut test); + ext_from_hex( + "0000000000000000000000000000000000 0000 01000000000000000000000000000000", + &mut test, + ); // create the funding transaction (client should send funding_created now) ext_from_hex("0a", &mut test); @@ -1430,7 +1699,10 @@ mod tests { // new outbound connection with id 0 ext_from_hex("00", &mut test); // peer's pubkey - ext_from_hex("030000000000000000000000000000000000000000000000000000000000000002", &mut test); + ext_from_hex( + "030000000000000000000000000000000000000000000000000000000000000002", + &mut test, + ); // inbound read from peer id 0 of len 50 ext_from_hex("030032", &mut test); // noise act two (0||pubkey||mac) @@ -1443,7 +1715,10 @@ mod tests { // inbound read from peer id 0 of len 32 ext_from_hex("030020", &mut test); // init message (type 16) with static_remotekey required, no channel_type/anchors/taproot, and other bits optional and mac - ext_from_hex("0010 00021aaa 0008aaa20aaa2a0a9aaa 03000000000000000000000000000000", &mut test); + ext_from_hex( + "0010 00021aaa 0008aaa20aaa2a0a9aaa 03000000000000000000000000000000", + &mut test, + ); // new inbound connection with id 1 ext_from_hex("01", &mut test); @@ -1463,7 +1738,10 @@ mod tests { // inbound read from peer id 1 of len 32 ext_from_hex("030120", &mut test); // init message (type 16) with static_remotekey required, no channel_type/anchors/taproot, and other bits optional and mac - ext_from_hex("0010 00021aaa 0008aaa20aaa2a0a9aaa 01000000000000000000000000000000", &mut test); + ext_from_hex( + "0010 00021aaa 0008aaa20aaa2a0a9aaa 01000000000000000000000000000000", + &mut test, + ); // inbound read from peer id 0 of len 18 ext_from_hex("030012", &mut test); diff --git a/rustfmt_excluded_files b/rustfmt_excluded_files index aa0f1784123..cb3d02ec5a3 100644 --- a/rustfmt_excluded_files +++ b/rustfmt_excluded_files @@ -1,6 +1,4 @@ ./bench/benches/bench.rs -./fuzz/src/full_stack.rs -./fuzz/src/lib.rs ./lightning-background-processor/src/lib.rs ./lightning-block-sync/src/convert.rs ./lightning-block-sync/src/gossip.rs