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