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