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