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