Merge pull request #2412 from valentinewallace/2023-07-construct-blinded-paths
[rust-lightning] / lightning / src / onion_message / packet.rs
1 // This file is Copyright its original authors, visible in version control
2 // history.
3 //
4 // This file is licensed under the Apache License, Version 2.0 <LICENSE-APACHE
5 // or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option.
7 // You may not use this file except in accordance with one or both of these
8 // licenses.
9
10 //! Structs and enums useful for constructing and reading an onion message packet.
11
12 use bitcoin::secp256k1::PublicKey;
13 use bitcoin::secp256k1::ecdh::SharedSecret;
14
15 use crate::blinded_path::BlindedPath;
16 use crate::blinded_path::message::{ForwardTlvs, ReceiveTlvs};
17 use crate::blinded_path::utils::Padding;
18 use crate::ln::msgs::DecodeError;
19 use crate::ln::onion_utils;
20 use super::messenger::CustomOnionMessageHandler;
21 use super::offers::OffersMessage;
22 use crate::util::chacha20poly1305rfc::{ChaChaPolyReadAdapter, ChaChaPolyWriteAdapter};
23 use crate::util::logger::Logger;
24 use crate::util::ser::{BigSize, FixedLengthReader, LengthRead, LengthReadable, LengthReadableArgs, Readable, ReadableArgs, Writeable, Writer};
25
26 use core::cmp;
27 use crate::io::{self, Read};
28 use crate::prelude::*;
29
30 // Per the spec, an onion message packet's `hop_data` field length should be
31 // SMALL_PACKET_HOP_DATA_LEN if it fits, else BIG_PACKET_HOP_DATA_LEN if it fits.
32 pub(super) const SMALL_PACKET_HOP_DATA_LEN: usize = 1300;
33 pub(super) const BIG_PACKET_HOP_DATA_LEN: usize = 32768;
34
35 #[derive(Clone, Debug, PartialEq, Eq)]
36 pub(crate) struct Packet {
37         pub(super) version: u8,
38         pub(super) public_key: PublicKey,
39         // Unlike the onion packets used for payments, onion message packets can have payloads greater
40         // than 1300 bytes.
41         // TODO: if 1300 ends up being the most common size, optimize this to be:
42         // enum { ThirteenHundred([u8; 1300]), VarLen(Vec<u8>) }
43         pub(super) hop_data: Vec<u8>,
44         pub(super) hmac: [u8; 32],
45 }
46
47 impl onion_utils::Packet for Packet {
48         type Data = Vec<u8>;
49         fn new(public_key: PublicKey, hop_data: Vec<u8>, hmac: [u8; 32]) -> Packet {
50                 Self {
51                         version: 0,
52                         public_key,
53                         hop_data,
54                         hmac,
55                 }
56         }
57 }
58
59 impl Writeable for Packet {
60         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
61                 self.version.write(w)?;
62                 self.public_key.write(w)?;
63                 w.write_all(&self.hop_data)?;
64                 self.hmac.write(w)?;
65                 Ok(())
66         }
67 }
68
69 impl LengthReadable for Packet {
70         fn read<R: LengthRead>(r: &mut R) -> Result<Self, DecodeError> {
71                 const READ_BUFFER_SIZE: usize = 4096;
72
73                 let version = Readable::read(r)?;
74                 let public_key = Readable::read(r)?;
75
76                 let mut hop_data = Vec::new();
77                 let hop_data_len = r.total_bytes().saturating_sub(66) as usize; // 1 (version) + 33 (pubkey) + 32 (HMAC) = 66
78                 let mut read_idx = 0;
79                 while read_idx < hop_data_len {
80                         let mut read_buffer = [0; READ_BUFFER_SIZE];
81                         let read_amt = cmp::min(hop_data_len - read_idx, READ_BUFFER_SIZE);
82                         r.read_exact(&mut read_buffer[..read_amt])?;
83                         hop_data.extend_from_slice(&read_buffer[..read_amt]);
84                         read_idx += read_amt;
85                 }
86
87                 let hmac = Readable::read(r)?;
88                 Ok(Packet {
89                         version,
90                         public_key,
91                         hop_data,
92                         hmac,
93                 })
94         }
95 }
96
97 /// Onion message payloads contain "control" TLVs and "data" TLVs. Control TLVs are used to route
98 /// the onion message from hop to hop and for path verification, whereas data TLVs contain the onion
99 /// message content itself, such as an invoice request.
100 pub(super) enum Payload<T: CustomOnionMessageContents> {
101         /// This payload is for an intermediate hop.
102         Forward(ForwardControlTlvs),
103         /// This payload is for the final hop.
104         Receive {
105                 control_tlvs: ReceiveControlTlvs,
106                 reply_path: Option<BlindedPath>,
107                 message: OnionMessageContents<T>,
108         }
109 }
110
111 #[derive(Debug)]
112 /// The contents of an onion message. In the context of offers, this would be the invoice, invoice
113 /// request, or invoice error.
114 pub enum OnionMessageContents<T: CustomOnionMessageContents> {
115         /// A message related to BOLT 12 Offers.
116         Offers(OffersMessage),
117         /// A custom onion message specified by the user.
118         Custom(T),
119 }
120
121 impl<T: CustomOnionMessageContents> OnionMessageContents<T> {
122         /// Returns the type that was used to decode the message payload.
123         ///
124         /// This is not exported to bindings users as methods on non-cloneable enums are not currently exportable
125         pub fn tlv_type(&self) -> u64 {
126                 match self {
127                         &OnionMessageContents::Offers(ref msg) => msg.tlv_type(),
128                         &OnionMessageContents::Custom(ref msg) => msg.tlv_type(),
129                 }
130         }
131 }
132
133 /// This is not exported to bindings users as methods on non-cloneable enums are not currently exportable
134 impl<T: CustomOnionMessageContents> Writeable for OnionMessageContents<T> {
135         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
136                 match self {
137                         OnionMessageContents::Offers(msg) => Ok(msg.write(w)?),
138                         OnionMessageContents::Custom(msg) => Ok(msg.write(w)?),
139                 }
140         }
141 }
142
143 /// The contents of a custom onion message.
144 pub trait CustomOnionMessageContents: Writeable {
145         /// Returns the TLV type identifying the message contents. MUST be >= 64.
146         fn tlv_type(&self) -> u64;
147 }
148
149 /// Forward control TLVs in their blinded and unblinded form.
150 pub(super) enum ForwardControlTlvs {
151         /// If we're sending to a blinded path, the node that constructed the blinded path has provided
152         /// this hop's control TLVs, already encrypted into bytes.
153         Blinded(Vec<u8>),
154         /// If we're constructing an onion message hop through an intermediate unblinded node, we'll need
155         /// to construct the intermediate hop's control TLVs in their unblinded state to avoid encoding
156         /// them into an intermediate Vec. See [`crate::blinded_path::message::ForwardTlvs`] for more
157         /// info.
158         Unblinded(ForwardTlvs),
159 }
160
161 /// Receive control TLVs in their blinded and unblinded form.
162 pub(super) enum ReceiveControlTlvs {
163         /// See [`ForwardControlTlvs::Blinded`].
164         Blinded(Vec<u8>),
165         /// See [`ForwardControlTlvs::Unblinded`] and [`crate::blinded_path::message::ReceiveTlvs`].
166         Unblinded(ReceiveTlvs),
167 }
168
169 // Uses the provided secret to simultaneously encode and encrypt the unblinded control TLVs.
170 impl<T: CustomOnionMessageContents> Writeable for (Payload<T>, [u8; 32]) {
171         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
172                 match &self.0 {
173                         Payload::Forward(ForwardControlTlvs::Blinded(encrypted_bytes)) => {
174                                 _encode_varint_length_prefixed_tlv!(w, {
175                                         (4, *encrypted_bytes, required_vec)
176                                 })
177                         },
178                         Payload::Receive {
179                                 control_tlvs: ReceiveControlTlvs::Blinded(encrypted_bytes), reply_path, message,
180                         } => {
181                                 _encode_varint_length_prefixed_tlv!(w, {
182                                         (2, reply_path, option),
183                                         (4, *encrypted_bytes, required_vec),
184                                         (message.tlv_type(), message, required)
185                                 })
186                         },
187                         Payload::Forward(ForwardControlTlvs::Unblinded(control_tlvs)) => {
188                                 let write_adapter = ChaChaPolyWriteAdapter::new(self.1, &control_tlvs);
189                                 _encode_varint_length_prefixed_tlv!(w, {
190                                         (4, write_adapter, required)
191                                 })
192                         },
193                         Payload::Receive {
194                                 control_tlvs: ReceiveControlTlvs::Unblinded(control_tlvs), reply_path, message,
195                         } => {
196                                 let write_adapter = ChaChaPolyWriteAdapter::new(self.1, &control_tlvs);
197                                 _encode_varint_length_prefixed_tlv!(w, {
198                                         (2, reply_path, option),
199                                         (4, write_adapter, required),
200                                         (message.tlv_type(), message, required)
201                                 })
202                         },
203                 }
204                 Ok(())
205         }
206 }
207
208 // Uses the provided secret to simultaneously decode and decrypt the control TLVs and data TLV.
209 impl<H: CustomOnionMessageHandler + ?Sized, L: Logger + ?Sized>
210 ReadableArgs<(SharedSecret, &H, &L)> for Payload<<H as CustomOnionMessageHandler>::CustomMessage> {
211         fn read<R: Read>(r: &mut R, args: (SharedSecret, &H, &L)) -> Result<Self, DecodeError> {
212                 let (encrypted_tlvs_ss, handler, logger) = args;
213
214                 let v: BigSize = Readable::read(r)?;
215                 let mut rd = FixedLengthReader::new(r, v.0);
216                 let mut reply_path: Option<BlindedPath> = None;
217                 let mut read_adapter: Option<ChaChaPolyReadAdapter<ControlTlvs>> = None;
218                 let rho = onion_utils::gen_rho_from_shared_secret(&encrypted_tlvs_ss.secret_bytes());
219                 let mut message_type: Option<u64> = None;
220                 let mut message = None;
221                 decode_tlv_stream_with_custom_tlv_decode!(&mut rd, {
222                         (2, reply_path, option),
223                         (4, read_adapter, (option: LengthReadableArgs, rho)),
224                 }, |msg_type, msg_reader| {
225                         if msg_type < 64 { return Ok(false) }
226                         // Don't allow reading more than one data TLV from an onion message.
227                         if message_type.is_some() { return Err(DecodeError::InvalidValue) }
228
229                         message_type = Some(msg_type);
230                         match msg_type {
231                                 tlv_type if OffersMessage::is_known_type(tlv_type) => {
232                                         let msg = OffersMessage::read(msg_reader, (tlv_type, logger))?;
233                                         message = Some(OnionMessageContents::Offers(msg));
234                                         Ok(true)
235                                 },
236                                 _ => match handler.read_custom_message(msg_type, msg_reader)? {
237                                         Some(msg) => {
238                                                 message = Some(OnionMessageContents::Custom(msg));
239                                                 Ok(true)
240                                         },
241                                         None => Ok(false),
242                                 },
243                         }
244                 });
245                 rd.eat_remaining().map_err(|_| DecodeError::ShortRead)?;
246
247                 match read_adapter {
248                         None => return Err(DecodeError::InvalidValue),
249                         Some(ChaChaPolyReadAdapter { readable: ControlTlvs::Forward(tlvs)}) => {
250                                 if message_type.is_some() {
251                                         return Err(DecodeError::InvalidValue)
252                                 }
253                                 Ok(Payload::Forward(ForwardControlTlvs::Unblinded(tlvs)))
254                         },
255                         Some(ChaChaPolyReadAdapter { readable: ControlTlvs::Receive(tlvs)}) => {
256                                 Ok(Payload::Receive {
257                                         control_tlvs: ReceiveControlTlvs::Unblinded(tlvs),
258                                         reply_path,
259                                         message: message.ok_or(DecodeError::InvalidValue)?,
260                                 })
261                         },
262                 }
263         }
264 }
265
266 /// When reading a packet off the wire, we don't know a priori whether the packet is to be forwarded
267 /// or received. Thus we read a `ControlTlvs` rather than reading a [`ForwardTlvs`] or
268 /// [`ReceiveTlvs`] directly. Also useful on the encoding side to keep forward and receive TLVs in
269 /// the same iterator.
270 pub(crate) enum ControlTlvs {
271         /// This onion message is intended to be forwarded.
272         Forward(ForwardTlvs),
273         /// This onion message is intended to be received.
274         Receive(ReceiveTlvs),
275 }
276
277 impl Readable for ControlTlvs {
278         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
279                 _init_and_read_tlv_stream!(r, {
280                         (1, _padding, option),
281                         (2, _short_channel_id, option),
282                         (4, next_node_id, option),
283                         (6, path_id, option),
284                         (8, next_blinding_override, option),
285                 });
286                 let _padding: Option<Padding> = _padding;
287                 let _short_channel_id: Option<u64> = _short_channel_id;
288
289                 let valid_fwd_fmt  = next_node_id.is_some() && path_id.is_none();
290                 let valid_recv_fmt = next_node_id.is_none() && next_blinding_override.is_none();
291
292                 let payload_fmt = if valid_fwd_fmt {
293                         ControlTlvs::Forward(ForwardTlvs {
294                                 next_node_id: next_node_id.unwrap(),
295                                 next_blinding_override,
296                         })
297                 } else if valid_recv_fmt {
298                         ControlTlvs::Receive(ReceiveTlvs {
299                                 path_id,
300                         })
301                 } else {
302                         return Err(DecodeError::InvalidValue)
303                 };
304
305                 Ok(payload_fmt)
306         }
307 }
308
309 impl Writeable for ControlTlvs {
310         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
311                 match self {
312                         Self::Forward(tlvs) => tlvs.write(w),
313                         Self::Receive(tlvs) => tlvs.write(w),
314                 }
315         }
316 }