Merge pull request #2828 from TheBlueMatt/2024-01-crypto-module
authorvalentinewallace <valentinewallace@users.noreply.github.com>
Wed, 17 Jan 2024 17:53:02 +0000 (12:53 -0500)
committerGitHub <noreply@github.com>
Wed, 17 Jan 2024 17:53:02 +0000 (12:53 -0500)
Move cryptographic algorithms and utilities to a new `crypto` mod

12 files changed:
CONTRIBUTING.md
lightning-invoice/src/ser.rs
lightning-net-tokio/src/lib.rs
lightning/src/blinded_path/payment.rs
lightning/src/ln/blinded_payment_tests.rs
lightning/src/ln/channelmanager.rs
lightning/src/ln/msgs.rs
lightning/src/ln/onion_payment.rs
lightning/src/ln/onion_utils.rs
lightning/src/ln/peer_handler.rs
lightning/src/routing/router.rs
lightning/src/util/wakers.rs

index 78c515007d03a75ba2b0261d25ebc74f46531244..b57217165e6b79c239351ebeef85647bafdab18a 100644 (file)
@@ -148,7 +148,7 @@ Security
 --------
 
 Security is the primary focus of `rust-lightning`; disclosure of security
-vulnerabilites helps prevent user loss of funds. If you believe a vulnerability
+vulnerabilities helps prevent user loss of funds. If you believe a vulnerability
 may affect other Lightning implementations, please inform them.
 
 You can find further information on submitting (possible) vulnerabilities in the
index fe42f72b6532f593083049832a07f31272cd43a5..dc63783bfa388fc35f7394d8cc243471683df99e 100644 (file)
@@ -52,7 +52,7 @@ impl<'a, W: WriteBase32> BytesToBase32<'a, W> {
                }
 
                // Combine all bits from buffer with enough bits from this rounds byte so that they fill
-               // a u5. Save reamining bits from byte to buffer.
+               // a u5. Save remaining bits from byte to buffer.
                let from_buffer = self.buffer >> 3;
                let from_byte = byte >> (3 + self.buffer_bits); // buffer_bits <= 4
 
index 1aa2cc25a13cc0772ee2e958da66aca602ce0eb4..be41a2401244f0bff743e44b9e7ec26482d95227 100644 (file)
@@ -502,6 +502,9 @@ impl peer_handler::SocketDescriptor for SocketDescriptor {
                                                        written_len += res;
                                                        if written_len == data.len() { return written_len; }
                                                },
+                                               Err(ref e) if e.kind() == std::io::ErrorKind::WouldBlock => {
+                                                       continue;
+                                               }
                                                Err(_) => return written_len,
                                        }
                                },
index f4df1e379d931b3ac65cbcdae65441c629554c6c..5d332a76faf57fed3b2fe844b91d5c5d04ed8a81 100644 (file)
@@ -97,12 +97,24 @@ pub struct PaymentConstraints {
        pub htlc_minimum_msat: u64,
 }
 
-impl From<CounterpartyForwardingInfo> for PaymentRelay {
-       fn from(info: CounterpartyForwardingInfo) -> Self {
+impl TryFrom<CounterpartyForwardingInfo> for PaymentRelay {
+       type Error = ();
+
+       fn try_from(info: CounterpartyForwardingInfo) -> Result<Self, ()> {
                let CounterpartyForwardingInfo {
                        fee_base_msat, fee_proportional_millionths, cltv_expiry_delta
                } = info;
-               Self { cltv_expiry_delta, fee_proportional_millionths, fee_base_msat }
+
+               // Avoid exposing esoteric CLTV expiry deltas
+               let cltv_expiry_delta = match cltv_expiry_delta {
+                       0..=40 => 40,
+                       41..=80 => 80,
+                       81..=144 => 144,
+                       145..=216 => 216,
+                       _ => return Err(()),
+               };
+
+               Ok(Self { cltv_expiry_delta, fee_proportional_millionths, fee_base_msat })
        }
 }
 
index 9b580d1fa7599df71a70cf3d8819d4402545d5c8..a3126b3b53744ee2a8fc596e116ddfd354375ea4 100644 (file)
@@ -490,6 +490,29 @@ fn two_hop_blinded_path_success() {
        claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
 }
 
+#[test]
+fn three_hop_blinded_path_success() {
+       let chanmon_cfgs = create_chanmon_cfgs(5);
+       let node_cfgs = create_node_cfgs(5, &chanmon_cfgs);
+       let node_chanmgrs = create_node_chanmgrs(5, &node_cfgs, &[None, None, None, None, None]);
+       let mut nodes = create_network(5, &node_cfgs, &node_chanmgrs);
+       create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0);
+       create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 1_000_000, 0);
+       let chan_upd_2_3 = create_announced_chan_between_nodes_with_value(&nodes, 2, 3, 1_000_000, 0).0.contents;
+       let chan_upd_3_4 = create_announced_chan_between_nodes_with_value(&nodes, 3, 4, 1_000_000, 0).0.contents;
+
+       let amt_msat = 5000;
+       let (payment_preimage, payment_hash, payment_secret) = get_payment_preimage_hash(&nodes[4], Some(amt_msat), None);
+       let route_params = get_blinded_route_parameters(amt_msat, payment_secret,
+               nodes.iter().skip(2).map(|n| n.node.get_our_node_id()).collect(),
+               &[&chan_upd_2_3, &chan_upd_3_4], &chanmon_cfgs[4].keys_manager);
+
+       nodes[0].node.send_payment(payment_hash, RecipientOnionFields::spontaneous_empty(), PaymentId(payment_hash.0), route_params, Retry::Attempts(0)).unwrap();
+       check_added_monitors(&nodes[0], 1);
+       pass_along_route(&nodes[0], &[&[&nodes[1], &nodes[2], &nodes[3], &nodes[4]]], amt_msat, payment_hash, payment_secret);
+       claim_payment(&nodes[0], &[&nodes[1], &nodes[2], &nodes[3], &nodes[4]], payment_preimage);
+}
+
 #[derive(PartialEq)]
 enum ReceiveCheckFail {
        // The recipient fails the payment upon `PaymentClaimable`.
@@ -537,11 +560,11 @@ fn do_multi_hop_receiver_fail(check: ReceiveCheckFail) {
        };
 
        let amt_msat = 5000;
-       let final_cltv_delta = if check == ReceiveCheckFail::ProcessPendingHTLCsCheck {
+       let excess_final_cltv_delta_opt = if check == ReceiveCheckFail::ProcessPendingHTLCsCheck {
                // Set the final CLTV expiry too low to trigger the failure in process_pending_htlc_forwards.
                Some(TEST_FINAL_CLTV as u16 - 2)
        } else { None };
-       let (_, payment_hash, payment_secret) = get_payment_preimage_hash(&nodes[2], Some(amt_msat), final_cltv_delta);
+       let (_, payment_hash, payment_secret) = get_payment_preimage_hash(&nodes[2], Some(amt_msat), excess_final_cltv_delta_opt);
        let mut route_params = get_blinded_route_parameters(amt_msat, payment_secret,
                nodes.iter().skip(1).map(|n| n.node.get_our_node_id()).collect(), &[&chan_upd_1_2],
                &chanmon_cfgs[2].keys_manager);
@@ -549,7 +572,8 @@ fn do_multi_hop_receiver_fail(check: ReceiveCheckFail) {
        let route = if check == ReceiveCheckFail::ProcessPendingHTLCsCheck {
                let mut route = get_route(&nodes[0], &route_params).unwrap();
                // Set the final CLTV expiry too low to trigger the failure in process_pending_htlc_forwards.
-               route.paths[0].blinded_tail.as_mut().map(|bt| bt.excess_final_cltv_expiry_delta = TEST_FINAL_CLTV - 2);
+               route.paths[0].hops.last_mut().map(|h| h.cltv_expiry_delta += excess_final_cltv_delta_opt.unwrap() as u32);
+               route.paths[0].blinded_tail.as_mut().map(|bt| bt.excess_final_cltv_expiry_delta = excess_final_cltv_delta_opt.unwrap() as u32);
                route
        } else if check == ReceiveCheckFail::PaymentConstraints {
                // Create a blinded path where the receiver's encrypted payload has an htlc_minimum_msat that is
@@ -657,6 +681,7 @@ fn do_multi_hop_receiver_fail(check: ReceiveCheckFail) {
                        commitment_signed_dance!(nodes[2], nodes[1], (), false, true, false, false);
                },
                ReceiveCheckFail::ProcessPendingHTLCsCheck => {
+                       assert_eq!(payment_event_1_2.msgs[0].cltv_expiry, nodes[0].best_block_info().1 + 1 + excess_final_cltv_delta_opt.unwrap() as u32);
                        nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_1_2.msgs[0]);
                        check_added_monitors!(nodes[2], 0);
                        do_commitment_signed_dance(&nodes[2], &nodes[1], &payment_event_1_2.commitment_msg, true, true);
index e405c3a672abe6fc2359da3cac35fdc71259ca4f..87197dd45493ff6ba689179cbe721cd905d834ea 100644 (file)
@@ -202,15 +202,16 @@ pub struct BlindedForward {
        /// onion payload if we're the introduction node. Useful for calculating the next hop's
        /// [`msgs::UpdateAddHTLC::blinding_point`].
        pub inbound_blinding_point: PublicKey,
-       // Another field will be added here when we support forwarding as a non-intro node.
+       /// If needed, this determines how this HTLC should be failed backwards, based on whether we are
+       /// the introduction node.
+       pub failure: BlindedFailure,
 }
 
 impl PendingHTLCRouting {
        // Used to override the onion failure code and data if the HTLC is blinded.
        fn blinded_failure(&self) -> Option<BlindedFailure> {
-               // TODO: needs update when we support forwarding blinded HTLCs as non-intro node
                match self {
-                       Self::Forward { blinded: Some(_), .. } => Some(BlindedFailure::FromIntroductionNode),
+                       Self::Forward { blinded: Some(BlindedForward { failure, .. }), .. } => Some(*failure),
                        Self::Receive { requires_blinded_error: true, .. } => Some(BlindedFailure::FromBlindedNode),
                        _ => None,
                }
@@ -305,10 +306,15 @@ pub(super) enum HTLCForwardInfo {
        },
 }
 
-// Used for failing blinded HTLCs backwards correctly.
+/// Whether this blinded HTLC is being failed backwards by the introduction node or a blinded node,
+/// which determines the failure message that should be used.
 #[derive(Clone, Copy, Debug, Hash, PartialEq, Eq)]
-enum BlindedFailure {
+pub enum BlindedFailure {
+       /// This HTLC is being failed backwards by the introduction node, and thus should be failed with
+       /// [`msgs::UpdateFailHTLC`] and error code `0x8000|0x4000|24`.
        FromIntroductionNode,
+       /// This HTLC is being failed backwards by a blinded node within the path, and thus should be
+       /// failed with [`msgs::UpdateFailMalformedHTLC`] and error code `0x8000|0x4000|24`.
        FromBlindedNode,
 }
 
@@ -3025,8 +3031,9 @@ where
 
                let is_intro_node_forward = match next_hop {
                        onion_utils::Hop::Forward {
-                               // TODO: update this when we support blinded forwarding as non-intro node
-                               next_hop_data: msgs::InboundOnionPayload::BlindedForward { .. }, ..
+                               next_hop_data: msgs::InboundOnionPayload::BlindedForward {
+                                       intro_node_blinding_point: Some(_), ..
+                               }, ..
                        } => true,
                        _ => false,
                };
@@ -4371,7 +4378,7 @@ where
                                                                                incoming_packet_shared_secret: incoming_shared_secret,
                                                                                // Phantom payments are only PendingHTLCRouting::Receive.
                                                                                phantom_shared_secret: None,
-                                                                               blinded_failure: blinded.map(|_| BlindedFailure::FromIntroductionNode),
+                                                                               blinded_failure: blinded.map(|b| b.failure),
                                                                        });
                                                                        let next_blinding_point = blinded.and_then(|b| {
                                                                                let encrypted_tlvs_ss = self.node_signer.ecdh(
@@ -9351,6 +9358,7 @@ pub fn provided_init_features(config: &UserConfig) -> InitFeatures {
        features.set_channel_type_optional();
        features.set_scid_privacy_optional();
        features.set_zero_conf_optional();
+       features.set_route_blinding_optional();
        if config.channel_handshake_config.negotiate_anchors_zero_fee_htlc_tx {
                features.set_anchors_zero_fee_htlc_tx_optional();
        }
@@ -9496,6 +9504,7 @@ impl_writeable_tlv_based!(PhantomRouteHints, {
 
 impl_writeable_tlv_based!(BlindedForward, {
        (0, inbound_blinding_point, required),
+       (1, failure, (default_value, BlindedFailure::FromIntroductionNode)),
 });
 
 impl_writeable_tlv_based_enum!(PendingHTLCRouting,
index efd04d143d93a98d211608d59040671a52c758b1..d39f1a6084274762331b456d28494b725999d69e 100644 (file)
@@ -1714,7 +1714,7 @@ mod fuzzy_internal_msgs {
                        payment_relay: PaymentRelay,
                        payment_constraints: PaymentConstraints,
                        features: BlindedHopFeatures,
-                       intro_node_blinding_point: PublicKey,
+                       intro_node_blinding_point: Option<PublicKey>,
                },
                BlindedReceive {
                        sender_intended_htlc_amt_msat: u64,
@@ -2394,7 +2394,7 @@ impl<NS: Deref> ReadableArgs<(Option<PublicKey>, &NS)> for InboundOnionPayload w
                                                payment_relay,
                                                payment_constraints,
                                                features,
-                                               intro_node_blinding_point: intro_node_blinding_point.ok_or(DecodeError::InvalidValue)?,
+                                               intro_node_blinding_point,
                                        })
                                },
                                ChaChaPolyReadAdapter { readable: BlindedPaymentTlvs::Receive(ReceiveTlvs {
index c552bf13b8efd0fa80cd396d23e2f96da5c85eba..00843d5e4e93d0ec11feb609e9d5009c98e85203 100644 (file)
@@ -12,7 +12,7 @@ use crate::blinded_path;
 use crate::blinded_path::payment::{PaymentConstraints, PaymentRelay};
 use crate::chain::channelmonitor::{HTLC_FAIL_BACK_BUFFER, LATENCY_GRACE_PERIOD_BLOCKS};
 use crate::ln::PaymentHash;
-use crate::ln::channelmanager::{BlindedForward, CLTV_FAR_FAR_AWAY, HTLCFailureMsg, MIN_CLTV_EXPIRY_DELTA, PendingHTLCInfo, PendingHTLCRouting};
+use crate::ln::channelmanager::{BlindedFailure, BlindedForward, CLTV_FAR_FAR_AWAY, HTLCFailureMsg, MIN_CLTV_EXPIRY_DELTA, PendingHTLCInfo, PendingHTLCRouting};
 use crate::ln::features::BlindedHopFeatures;
 use crate::ln::msgs;
 use crate::ln::onion_utils;
@@ -73,7 +73,7 @@ pub(super) fn create_fwd_pending_htlc_info(
        };
 
        let (
-               short_channel_id, amt_to_forward, outgoing_cltv_value, inbound_blinding_point
+               short_channel_id, amt_to_forward, outgoing_cltv_value, intro_node_blinding_point
        ) = match hop_data {
                msgs::InboundOnionPayload::Forward { short_channel_id, amt_to_forward, outgoing_cltv_value } =>
                        (short_channel_id, amt_to_forward, outgoing_cltv_value, None),
@@ -91,7 +91,7 @@ pub(super) fn create_fwd_pending_htlc_info(
                                        err_data: vec![0; 32],
                                }
                        })?;
-                       (short_channel_id, amt_to_forward, outgoing_cltv_value, Some(intro_node_blinding_point))
+                       (short_channel_id, amt_to_forward, outgoing_cltv_value, intro_node_blinding_point)
                },
                msgs::InboundOnionPayload::Receive { .. } | msgs::InboundOnionPayload::BlindedReceive { .. } =>
                        return Err(InboundHTLCErr {
@@ -105,7 +105,13 @@ pub(super) fn create_fwd_pending_htlc_info(
                routing: PendingHTLCRouting::Forward {
                        onion_packet: outgoing_packet,
                        short_channel_id,
-                       blinded: inbound_blinding_point.map(|bp| BlindedForward { inbound_blinding_point: bp }),
+                       blinded: intro_node_blinding_point.or(msg.blinding_point)
+                               .map(|bp| BlindedForward {
+                                       inbound_blinding_point: bp,
+                                       failure: intro_node_blinding_point
+                                               .map(|_| BlindedFailure::FromIntroductionNode)
+                                               .unwrap_or(BlindedFailure::FromBlindedNode),
+                               }),
                },
                payment_hash: msg.payment_hash,
                incoming_shared_secret: shared_secret,
index d9455fc1de2472f935e5cf1daf1b979c7820394f..1ea6fd83aa237f08e9f911dc052c42b06a042b01 100644 (file)
@@ -189,11 +189,10 @@ pub(super) fn build_onion_payloads(path: &Path, total_msat: u64, mut recipient_o
                                for (i, blinded_hop) in hops.iter().enumerate() {
                                        if i == hops.len() - 1 {
                                                cur_value_msat += final_value_msat;
-                                               cur_cltv += excess_final_cltv_expiry_delta;
                                                res.push(msgs::OutboundOnionPayload::BlindedReceive {
                                                        sender_intended_htlc_amt_msat: *final_value_msat,
                                                        total_msat,
-                                                       cltv_expiry_height: cltv,
+                                                       cltv_expiry_height: cur_cltv + excess_final_cltv_expiry_delta,
                                                        encrypted_tlvs: blinded_hop.encrypted_payload.clone(),
                                                        intro_node_blinding_point: blinding_point.take(),
                                                });
index 6ffffec4dd0bd94febc085ed998051c7090da5eb..6d46558b188b60c2433f51f002121bad268df60c 100644 (file)
@@ -305,6 +305,7 @@ impl ChannelMessageHandler for ErroringMessageHandler {
                features.set_channel_type_optional();
                features.set_scid_privacy_optional();
                features.set_zero_conf_optional();
+               features.set_route_blinding_optional();
                features
        }
 
@@ -1609,7 +1610,7 @@ impl<Descriptor: SocketDescriptor, CM: Deref, RM: Deref, OM: Deref, L: Deref, CM
                }
 
                if let wire::Message::GossipTimestampFilter(_msg) = message {
-                       // When supporting gossip messages, start inital gossip sync only after we receive
+                       // When supporting gossip messages, start initial gossip sync only after we receive
                        // a GossipTimestampFilter
                        if peer_lock.their_features.as_ref().unwrap().supports_gossip_queries() &&
                                !peer_lock.sent_gossip_timestamp_filter {
@@ -2216,7 +2217,7 @@ impl<Descriptor: SocketDescriptor, CM: Deref, RM: Deref, OM: Deref, L: Deref, CM
                                                                                        log_pubkey!(node_id));
                                                                        }
                                                                        // We do not have the peers write lock, so we just store that we're
-                                                                       // about to disconenct the peer and do it after we finish
+                                                                       // about to disconnect the peer and do it after we finish
                                                                        // processing most messages.
                                                                        let msg = msg.map(|msg| wire::Message::<<<CMH as core::ops::Deref>::Target as wire::CustomMessageReader>::CustomMessage>::Error(msg));
                                                                        peers_to_disconnect.insert(node_id, msg);
@@ -2225,7 +2226,7 @@ impl<Descriptor: SocketDescriptor, CM: Deref, RM: Deref, OM: Deref, L: Deref, CM
                                                                        log_trace!(logger, "Handling DisconnectPeer HandleError event in peer_handler for node {} with message {}",
                                                                                log_pubkey!(node_id), msg.data);
                                                                        // We do not have the peers write lock, so we just store that we're
-                                                                       // about to disconenct the peer and do it after we finish
+                                                                       // about to disconnect the peer and do it after we finish
                                                                        // processing most messages.
                                                                        peers_to_disconnect.insert(node_id, Some(wire::Message::Warning(msg)));
                                                                },
index 0b19369a4aa74bf95ed1cc4e3f038c6b381f486d..9a5c2dfbf215d5a21a3cab0fe2d2689a8453c496 100644 (file)
@@ -114,19 +114,14 @@ impl<G: Deref<Target = NetworkGraph<L>> + Clone, L: Deref, S: Deref, SP: Sized,
                                        None => return None,
                                };
                                let payment_relay: PaymentRelay = match details.counterparty.forwarding_info {
-                                       Some(forwarding_info) => forwarding_info.into(),
+                                       Some(forwarding_info) => match forwarding_info.try_into() {
+                                               Ok(payment_relay) => payment_relay,
+                                               Err(()) => return None,
+                                       },
                                        None => return None,
                                };
 
-                               // Avoid exposing esoteric CLTV expiry deltas
-                               let cltv_expiry_delta = match payment_relay.cltv_expiry_delta {
-                                       0..=40 => 40u32,
-                                       41..=80 => 80u32,
-                                       81..=144 => 144u32,
-                                       145..=216 => 216u32,
-                                       _ => return None,
-                               };
-
+                               let cltv_expiry_delta = payment_relay.cltv_expiry_delta as u32;
                                let payment_constraints = PaymentConstraints {
                                        max_cltv_expiry: tlvs.payment_constraints.max_cltv_expiry + cltv_expiry_delta,
                                        htlc_minimum_msat: details.inbound_htlc_minimum_msat.unwrap_or(0),
@@ -2706,7 +2701,7 @@ where L::Target: Logger {
                                                }
                                        }
 
-                                       // Means we succesfully traversed from the payer to the payee, now
+                                       // Means we successfully traversed from the payer to the payee, now
                                        // save this path for the payment route. Also, update the liquidity
                                        // remaining on the used hops, so that we take them into account
                                        // while looking for more paths.
@@ -7803,7 +7798,7 @@ mod tests {
        fn do_min_htlc_overpay_violates_max_htlc(blinded_payee: bool) {
                // Test that if overpaying to meet a later hop's min_htlc and causes us to violate an earlier
                // hop's max_htlc, we don't consider that candidate hop valid. Previously we would add this hop
-               // to `targets` and build an invalid path with it, and subsquently hit a debug panic asserting
+               // to `targets` and build an invalid path with it, and subsequently hit a debug panic asserting
                // that the used liquidity for a hop was less than its available liquidity limit.
                let secp_ctx = Secp256k1::new();
                let logger = Arc::new(ln_test_utils::TestLogger::new());
@@ -8452,7 +8447,7 @@ pub(crate) mod bench_utils {
                                                        }
                                                        break;
                                                }
-                                               // If we couldn't find a path with a higer amount, reduce and try again.
+                                               // If we couldn't find a path with a higher amount, reduce and try again.
                                                score_amt /= 100;
                                        }
 
index 37c036da9594747ea81b142e151ff960c2892dad..14e6bbe64a24524367661da70772f603538c3b55 100644 (file)
@@ -491,7 +491,7 @@ mod tests {
        }
 
        // Rather annoyingly, there's no safe way in Rust std to construct a Waker despite it being
-       // totally possible to construct from a trait implementation (though somewhat less effecient
+       // totally possible to construct from a trait implementation (though somewhat less efficient
        // compared to a raw VTable). Instead, we have to write out a lot of boilerplate to build a
        // waker, which we do here with a trivial Arc<AtomicBool> data element to track woke-ness.
        const WAKER_V_TABLE: RawWakerVTable = RawWakerVTable::new(waker_clone, wake, wake_by_ref, drop);