Rename OnionMessageContents
[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::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::util::chacha20poly1305rfc::{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, 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: CustomOnionMessageContents> {
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: ParsedOnionMessageContents<T>,
114         }
115 }
116
117 /// The contents of an onion message as read from the wire.
118 #[derive(Debug)]
119 pub enum ParsedOnionMessageContents<T: CustomOnionMessageContents> {
120         /// A message related to BOLT 12 Offers.
121         Offers(OffersMessage),
122         /// A custom onion message specified by the user.
123         Custom(T),
124 }
125
126 impl<T: CustomOnionMessageContents> ParsedOnionMessageContents<T> {
127         /// Returns the type that was used to decode the message payload.
128         ///
129         /// This is not exported to bindings users as methods on non-cloneable enums are not currently exportable
130         pub fn tlv_type(&self) -> u64 {
131                 match self {
132                         &ParsedOnionMessageContents::Offers(ref msg) => msg.tlv_type(),
133                         &ParsedOnionMessageContents::Custom(ref msg) => msg.tlv_type(),
134                 }
135         }
136 }
137
138 /// This is not exported to bindings users as methods on non-cloneable enums are not currently exportable
139 impl<T: CustomOnionMessageContents> Writeable for ParsedOnionMessageContents<T> {
140         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
141                 match self {
142                         ParsedOnionMessageContents::Offers(msg) => Ok(msg.write(w)?),
143                         ParsedOnionMessageContents::Custom(msg) => Ok(msg.write(w)?),
144                 }
145         }
146 }
147
148 /// The contents of a custom onion message.
149 pub trait CustomOnionMessageContents: Writeable {
150         /// Returns the TLV type identifying the message contents. MUST be >= 64.
151         fn tlv_type(&self) -> u64;
152 }
153
154 /// Forward control TLVs in their blinded and unblinded form.
155 pub(super) enum ForwardControlTlvs {
156         /// If we're sending to a blinded path, the node that constructed the blinded path has provided
157         /// this hop's control TLVs, already encrypted into bytes.
158         Blinded(Vec<u8>),
159         /// If we're constructing an onion message hop through an intermediate unblinded node, we'll need
160         /// to construct the intermediate hop's control TLVs in their unblinded state to avoid encoding
161         /// them into an intermediate Vec. See [`crate::blinded_path::message::ForwardTlvs`] for more
162         /// info.
163         Unblinded(ForwardTlvs),
164 }
165
166 /// Receive control TLVs in their blinded and unblinded form.
167 pub(super) enum ReceiveControlTlvs {
168         /// See [`ForwardControlTlvs::Blinded`].
169         Blinded(Vec<u8>),
170         /// See [`ForwardControlTlvs::Unblinded`] and [`crate::blinded_path::message::ReceiveTlvs`].
171         Unblinded(ReceiveTlvs),
172 }
173
174 // Uses the provided secret to simultaneously encode and encrypt the unblinded control TLVs.
175 impl<T: CustomOnionMessageContents> Writeable for (Payload<T>, [u8; 32]) {
176         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
177                 match &self.0 {
178                         Payload::Forward(ForwardControlTlvs::Blinded(encrypted_bytes)) => {
179                                 _encode_varint_length_prefixed_tlv!(w, {
180                                         (4, *encrypted_bytes, required_vec)
181                                 })
182                         },
183                         Payload::Receive {
184                                 control_tlvs: ReceiveControlTlvs::Blinded(encrypted_bytes), reply_path, message,
185                         } => {
186                                 _encode_varint_length_prefixed_tlv!(w, {
187                                         (2, reply_path, option),
188                                         (4, *encrypted_bytes, required_vec),
189                                         (message.tlv_type(), message, required)
190                                 })
191                         },
192                         Payload::Forward(ForwardControlTlvs::Unblinded(control_tlvs)) => {
193                                 let write_adapter = ChaChaPolyWriteAdapter::new(self.1, &control_tlvs);
194                                 _encode_varint_length_prefixed_tlv!(w, {
195                                         (4, write_adapter, required)
196                                 })
197                         },
198                         Payload::Receive {
199                                 control_tlvs: ReceiveControlTlvs::Unblinded(control_tlvs), reply_path, message,
200                         } => {
201                                 let write_adapter = ChaChaPolyWriteAdapter::new(self.1, &control_tlvs);
202                                 _encode_varint_length_prefixed_tlv!(w, {
203                                         (2, reply_path, option),
204                                         (4, write_adapter, required),
205                                         (message.tlv_type(), message, required)
206                                 })
207                         },
208                 }
209                 Ok(())
210         }
211 }
212
213 // Uses the provided secret to simultaneously decode and decrypt the control TLVs and data TLV.
214 impl<H: CustomOnionMessageHandler + ?Sized, L: Logger + ?Sized>
215 ReadableArgs<(SharedSecret, &H, &L)> for Payload<<H as CustomOnionMessageHandler>::CustomMessage> {
216         fn read<R: Read>(r: &mut R, args: (SharedSecret, &H, &L)) -> Result<Self, DecodeError> {
217                 let (encrypted_tlvs_ss, handler, logger) = args;
218
219                 let v: BigSize = Readable::read(r)?;
220                 let mut rd = FixedLengthReader::new(r, v.0);
221                 let mut reply_path: Option<BlindedPath> = None;
222                 let mut read_adapter: Option<ChaChaPolyReadAdapter<ControlTlvs>> = None;
223                 let rho = onion_utils::gen_rho_from_shared_secret(&encrypted_tlvs_ss.secret_bytes());
224                 let mut message_type: Option<u64> = None;
225                 let mut message = None;
226                 decode_tlv_stream_with_custom_tlv_decode!(&mut rd, {
227                         (2, reply_path, option),
228                         (4, read_adapter, (option: LengthReadableArgs, rho)),
229                 }, |msg_type, msg_reader| {
230                         if msg_type < 64 { return Ok(false) }
231                         // Don't allow reading more than one data TLV from an onion message.
232                         if message_type.is_some() { return Err(DecodeError::InvalidValue) }
233
234                         message_type = Some(msg_type);
235                         match msg_type {
236                                 tlv_type if OffersMessage::is_known_type(tlv_type) => {
237                                         let msg = OffersMessage::read(msg_reader, (tlv_type, logger))?;
238                                         message = Some(ParsedOnionMessageContents::Offers(msg));
239                                         Ok(true)
240                                 },
241                                 _ => match handler.read_custom_message(msg_type, msg_reader)? {
242                                         Some(msg) => {
243                                                 message = Some(ParsedOnionMessageContents::Custom(msg));
244                                                 Ok(true)
245                                         },
246                                         None => Ok(false),
247                                 },
248                         }
249                 });
250                 rd.eat_remaining().map_err(|_| DecodeError::ShortRead)?;
251
252                 match read_adapter {
253                         None => return Err(DecodeError::InvalidValue),
254                         Some(ChaChaPolyReadAdapter { readable: ControlTlvs::Forward(tlvs)}) => {
255                                 if message_type.is_some() {
256                                         return Err(DecodeError::InvalidValue)
257                                 }
258                                 Ok(Payload::Forward(ForwardControlTlvs::Unblinded(tlvs)))
259                         },
260                         Some(ChaChaPolyReadAdapter { readable: ControlTlvs::Receive(tlvs)}) => {
261                                 Ok(Payload::Receive {
262                                         control_tlvs: ReceiveControlTlvs::Unblinded(tlvs),
263                                         reply_path,
264                                         message: message.ok_or(DecodeError::InvalidValue)?,
265                                 })
266                         },
267                 }
268         }
269 }
270
271 /// When reading a packet off the wire, we don't know a priori whether the packet is to be forwarded
272 /// or received. Thus we read a `ControlTlvs` rather than reading a [`ForwardTlvs`] or
273 /// [`ReceiveTlvs`] directly. Also useful on the encoding side to keep forward and receive TLVs in
274 /// the same iterator.
275 pub(crate) enum ControlTlvs {
276         /// This onion message is intended to be forwarded.
277         Forward(ForwardTlvs),
278         /// This onion message is intended to be received.
279         Receive(ReceiveTlvs),
280 }
281
282 impl Readable for ControlTlvs {
283         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
284                 _init_and_read_tlv_stream!(r, {
285                         (1, _padding, option),
286                         (2, _short_channel_id, option),
287                         (4, next_node_id, option),
288                         (6, path_id, option),
289                         (8, next_blinding_override, option),
290                 });
291                 let _padding: Option<Padding> = _padding;
292                 let _short_channel_id: Option<u64> = _short_channel_id;
293
294                 let valid_fwd_fmt  = next_node_id.is_some() && path_id.is_none();
295                 let valid_recv_fmt = next_node_id.is_none() && next_blinding_override.is_none();
296
297                 let payload_fmt = if valid_fwd_fmt {
298                         ControlTlvs::Forward(ForwardTlvs {
299                                 next_node_id: next_node_id.unwrap(),
300                                 next_blinding_override,
301                         })
302                 } else if valid_recv_fmt {
303                         ControlTlvs::Receive(ReceiveTlvs {
304                                 path_id,
305                         })
306                 } else {
307                         return Err(DecodeError::InvalidValue)
308                 };
309
310                 Ok(payload_fmt)
311         }
312 }
313
314 impl Writeable for ControlTlvs {
315         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
316                 match self {
317                         Self::Forward(tlvs) => tlvs.write(w),
318                         Self::Receive(tlvs) => tlvs.write(w),
319                 }
320         }
321 }