Support NextHop::ShortChannelId in BlindedPath
[rust-lightning] / lightning / src / blinded_path / message.rs
1 //! Data structures and methods for constructing [`BlindedPath`]s to send a message over.
2 //!
3 //! [`BlindedPath`]: crate::blinded_path::BlindedPath
4
5 use bitcoin::secp256k1::{self, PublicKey, Secp256k1, SecretKey};
6
7 #[allow(unused_imports)]
8 use crate::prelude::*;
9
10 use crate::blinded_path::{BlindedHop, BlindedPath, IntroductionNode, NextMessageHop, NodeIdLookUp};
11 use crate::blinded_path::utils;
12 use crate::io;
13 use crate::io::Cursor;
14 use crate::ln::onion_utils;
15 use crate::onion_message::packet::ControlTlvs;
16 use crate::sign::{NodeSigner, Recipient};
17 use crate::crypto::streams::ChaChaPolyReadAdapter;
18 use crate::util::ser::{FixedLengthReader, LengthReadableArgs, Writeable, Writer};
19
20 use core::mem;
21 use core::ops::Deref;
22
23 /// An intermediate node, and possibly a short channel id leading to the next node.
24 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
25 pub struct ForwardNode {
26         /// This node's pubkey.
27         pub node_id: PublicKey,
28         /// The channel between `node_id` and the next hop. If set, the constructed [`BlindedHop`]'s
29         /// `encrypted_payload` will use this instead of the next [`ForwardNode::node_id`] for a more
30         /// compact representation.
31         pub short_channel_id: Option<u64>,
32 }
33
34 /// TLVs to encode in an intermediate onion message packet's hop data. When provided in a blinded
35 /// route, they are encoded into [`BlindedHop::encrypted_payload`].
36 pub(crate) struct ForwardTlvs {
37         /// The next hop in the onion message's path.
38         pub(crate) next_hop: NextMessageHop,
39         /// Senders to a blinded path use this value to concatenate the route they find to the
40         /// introduction node with the blinded path.
41         pub(crate) next_blinding_override: Option<PublicKey>,
42 }
43
44 /// Similar to [`ForwardTlvs`], but these TLVs are for the final node.
45 pub(crate) struct ReceiveTlvs {
46         /// If `path_id` is `Some`, it is used to identify the blinded path that this onion message is
47         /// sending to. This is useful for receivers to check that said blinded path is being used in
48         /// the right context.
49         pub(crate) path_id: Option<[u8; 32]>,
50 }
51
52 impl Writeable for ForwardTlvs {
53         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
54                 let (next_node_id, short_channel_id) = match self.next_hop {
55                         NextMessageHop::NodeId(pubkey) => (Some(pubkey), None),
56                         NextMessageHop::ShortChannelId(scid) => (None, Some(scid)),
57                 };
58                 // TODO: write padding
59                 encode_tlv_stream!(writer, {
60                         (2, short_channel_id, option),
61                         (4, next_node_id, option),
62                         (8, self.next_blinding_override, option)
63                 });
64                 Ok(())
65         }
66 }
67
68 impl Writeable for ReceiveTlvs {
69         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
70                 // TODO: write padding
71                 encode_tlv_stream!(writer, {
72                         (6, self.path_id, option),
73                 });
74                 Ok(())
75         }
76 }
77
78 /// Construct blinded onion message hops for the given `intermediate_nodes` and `recipient_node_id`.
79 pub(super) fn blinded_hops<T: secp256k1::Signing + secp256k1::Verification>(
80         secp_ctx: &Secp256k1<T>, intermediate_nodes: &[ForwardNode], recipient_node_id: PublicKey,
81         session_priv: &SecretKey
82 ) -> Result<Vec<BlindedHop>, secp256k1::Error> {
83         let pks = intermediate_nodes.iter().map(|node| &node.node_id)
84                 .chain(core::iter::once(&recipient_node_id));
85         let tlvs = pks.clone()
86                 .skip(1) // The first node's TLVs contains the next node's pubkey
87                 .zip(intermediate_nodes.iter().map(|node| node.short_channel_id))
88                 .map(|(pubkey, scid)| match scid {
89                         Some(scid) => NextMessageHop::ShortChannelId(scid),
90                         None => NextMessageHop::NodeId(*pubkey),
91                 })
92                 .map(|next_hop| ControlTlvs::Forward(ForwardTlvs { next_hop, next_blinding_override: None }))
93                 .chain(core::iter::once(ControlTlvs::Receive(ReceiveTlvs { path_id: None })));
94
95         utils::construct_blinded_hops(secp_ctx, pks, tlvs, session_priv)
96 }
97
98 // Advance the blinded onion message path by one hop, so make the second hop into the new
99 // introduction node.
100 pub(crate) fn advance_path_by_one<NS: Deref, NL: Deref, T>(
101         path: &mut BlindedPath, node_signer: &NS, node_id_lookup: &NL, secp_ctx: &Secp256k1<T>
102 ) -> Result<(), ()>
103 where
104         NS::Target: NodeSigner,
105         NL::Target: NodeIdLookUp,
106         T: secp256k1::Signing + secp256k1::Verification,
107 {
108         let control_tlvs_ss = node_signer.ecdh(Recipient::Node, &path.blinding_point, None)?;
109         let rho = onion_utils::gen_rho_from_shared_secret(&control_tlvs_ss.secret_bytes());
110         let encrypted_control_tlvs = path.blinded_hops.remove(0).encrypted_payload;
111         let mut s = Cursor::new(&encrypted_control_tlvs);
112         let mut reader = FixedLengthReader::new(&mut s, encrypted_control_tlvs.len() as u64);
113         match ChaChaPolyReadAdapter::read(&mut reader, rho) {
114                 Ok(ChaChaPolyReadAdapter {
115                         readable: ControlTlvs::Forward(ForwardTlvs { next_hop, next_blinding_override })
116                 }) => {
117                         let next_node_id = match next_hop {
118                                 NextMessageHop::NodeId(pubkey) => pubkey,
119                                 NextMessageHop::ShortChannelId(scid) => match node_id_lookup.next_node_id(scid) {
120                                         Some(pubkey) => pubkey,
121                                         None => return Err(()),
122                                 },
123                         };
124                         let mut new_blinding_point = match next_blinding_override {
125                                 Some(blinding_point) => blinding_point,
126                                 None => {
127                                         onion_utils::next_hop_pubkey(secp_ctx, path.blinding_point,
128                                                 control_tlvs_ss.as_ref()).map_err(|_| ())?
129                                 }
130                         };
131                         mem::swap(&mut path.blinding_point, &mut new_blinding_point);
132                         path.introduction_node = IntroductionNode::NodeId(next_node_id);
133                         Ok(())
134                 },
135                 _ => Err(())
136         }
137 }