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