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