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