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