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