1 // This file is Copyright its original authors, visible in version control
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
10 //! Structs and enums useful for constructing and reading an onion message packet.
12 use bitcoin::secp256k1::PublicKey;
13 use bitcoin::secp256k1::ecdh::SharedSecret;
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 #[cfg(async_payments)]
21 use super::async_payments::AsyncPaymentsMessage;
22 use super::messenger::CustomOnionMessageHandler;
23 use super::offers::OffersMessage;
24 use crate::crypto::streams::{ChaChaPolyReadAdapter, ChaChaPolyWriteAdapter};
25 use crate::util::logger::Logger;
26 use crate::util::ser::{BigSize, FixedLengthReader, LengthRead, LengthReadable, LengthReadableArgs, Readable, ReadableArgs, Writeable, Writer};
30 use crate::io::{self, Read};
31 use crate::prelude::*;
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.
35 pub(super) const SMALL_PACKET_HOP_DATA_LEN: usize = 1300;
36 pub(super) const BIG_PACKET_HOP_DATA_LEN: usize = 32768;
38 /// Packet of hop data for next peer
39 #[derive(Clone, Hash, PartialEq, Eq)]
41 /// Bolt 04 version number
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
47 // Unlike the onion packets used for payments, onion message packets can have payloads greater
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
56 impl onion_utils::Packet for Packet {
58 fn new(public_key: PublicKey, hop_data: Vec<u8>, hmac: [u8; 32]) -> Packet {
68 impl 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[..]))
74 impl 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)?;
84 impl LengthReadable for Packet {
85 fn read<R: LengthRead>(r: &mut R) -> Result<Self, DecodeError> {
86 const READ_BUFFER_SIZE: usize = 4096;
88 let version = Readable::read(r)?;
89 let public_key = Readable::read(r)?;
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
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]);
102 let hmac = Readable::read(r)?;
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.
115 pub(super) enum Payload<T: OnionMessageContents> {
116 /// This payload is for an intermediate hop.
117 Forward(ForwardControlTlvs),
118 /// This payload is for the final hop.
120 control_tlvs: ReceiveControlTlvs,
121 reply_path: Option<BlindedPath>,
126 /// The contents of an [`OnionMessage`] as read from the wire.
128 /// [`OnionMessage`]: crate::ln::msgs::OnionMessage
129 #[derive(Clone, Debug)]
130 pub 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 custom onion message specified by the user.
140 impl<T: OnionMessageContents> OnionMessageContents for ParsedOnionMessageContents<T> {
141 /// Returns the type that was used to decode the message payload.
143 /// This is not exported to bindings users as methods on non-cloneable enums are not currently exportable
144 fn tlv_type(&self) -> u64 {
146 &ParsedOnionMessageContents::Offers(ref msg) => msg.tlv_type(),
147 #[cfg(async_payments)]
148 &ParsedOnionMessageContents::AsyncPayments(ref msg) => msg.tlv_type(),
149 &ParsedOnionMessageContents::Custom(ref msg) => msg.tlv_type(),
152 fn msg_type(&self) -> &'static str {
154 ParsedOnionMessageContents::Offers(ref msg) => msg.msg_type(),
155 #[cfg(async_payments)]
156 ParsedOnionMessageContents::AsyncPayments(ref msg) => msg.msg_type(),
157 ParsedOnionMessageContents::Custom(ref msg) => msg.msg_type(),
162 impl<T: OnionMessageContents> Writeable for ParsedOnionMessageContents<T> {
163 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
165 ParsedOnionMessageContents::Offers(msg) => Ok(msg.write(w)?),
166 #[cfg(async_payments)]
167 ParsedOnionMessageContents::AsyncPayments(msg) => Ok(msg.write(w)?),
168 ParsedOnionMessageContents::Custom(msg) => Ok(msg.write(w)?),
173 /// The contents of an onion message.
174 pub trait OnionMessageContents: Writeable + core::fmt::Debug {
175 /// Returns the TLV type identifying the message contents. MUST be >= 64.
176 fn tlv_type(&self) -> u64;
178 /// Returns the message type
179 fn msg_type(&self) -> &'static str;
182 /// Forward control TLVs in their blinded and unblinded form.
183 pub(super) enum ForwardControlTlvs {
184 /// If we're sending to a blinded path, the node that constructed the blinded path has provided
185 /// this hop's control TLVs, already encrypted into bytes.
187 /// If we're constructing an onion message hop through an intermediate unblinded node, we'll need
188 /// to construct the intermediate hop's control TLVs in their unblinded state to avoid encoding
189 /// them into an intermediate Vec. See [`crate::blinded_path::message::ForwardTlvs`] for more
191 Unblinded(ForwardTlvs),
194 /// Receive control TLVs in their blinded and unblinded form.
195 pub(super) enum ReceiveControlTlvs {
196 /// See [`ForwardControlTlvs::Blinded`].
198 /// See [`ForwardControlTlvs::Unblinded`] and [`crate::blinded_path::message::ReceiveTlvs`].
199 Unblinded(ReceiveTlvs),
202 // Uses the provided secret to simultaneously encode and encrypt the unblinded control TLVs.
203 impl<T: OnionMessageContents> Writeable for (Payload<T>, [u8; 32]) {
204 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
206 Payload::Forward(ForwardControlTlvs::Blinded(encrypted_bytes)) => {
207 _encode_varint_length_prefixed_tlv!(w, {
208 (4, *encrypted_bytes, required_vec)
212 control_tlvs: ReceiveControlTlvs::Blinded(encrypted_bytes), reply_path, message,
214 _encode_varint_length_prefixed_tlv!(w, {
215 (2, reply_path, option),
216 (4, *encrypted_bytes, required_vec),
217 (message.tlv_type(), message, required)
220 Payload::Forward(ForwardControlTlvs::Unblinded(control_tlvs)) => {
221 let write_adapter = ChaChaPolyWriteAdapter::new(self.1, &control_tlvs);
222 _encode_varint_length_prefixed_tlv!(w, {
223 (4, write_adapter, required)
227 control_tlvs: ReceiveControlTlvs::Unblinded(control_tlvs), reply_path, message,
229 let write_adapter = ChaChaPolyWriteAdapter::new(self.1, &control_tlvs);
230 _encode_varint_length_prefixed_tlv!(w, {
231 (2, reply_path, option),
232 (4, write_adapter, required),
233 (message.tlv_type(), message, required)
241 // Uses the provided secret to simultaneously decode and decrypt the control TLVs and data TLV.
242 impl<H: CustomOnionMessageHandler + ?Sized, L: Logger + ?Sized> ReadableArgs<(SharedSecret, &H, &L)>
243 for Payload<ParsedOnionMessageContents<<H as CustomOnionMessageHandler>::CustomMessage>> {
244 fn read<R: Read>(r: &mut R, args: (SharedSecret, &H, &L)) -> Result<Self, DecodeError> {
245 let (encrypted_tlvs_ss, handler, logger) = args;
247 let v: BigSize = Readable::read(r)?;
248 let mut rd = FixedLengthReader::new(r, v.0);
249 let mut reply_path: Option<BlindedPath> = None;
250 let mut read_adapter: Option<ChaChaPolyReadAdapter<ControlTlvs>> = None;
251 let rho = onion_utils::gen_rho_from_shared_secret(&encrypted_tlvs_ss.secret_bytes());
252 let mut message_type: Option<u64> = None;
253 let mut message = None;
254 decode_tlv_stream_with_custom_tlv_decode!(&mut rd, {
255 (2, reply_path, option),
256 (4, read_adapter, (option: LengthReadableArgs, rho)),
257 }, |msg_type, msg_reader| {
258 if msg_type < 64 { return Ok(false) }
259 // Don't allow reading more than one data TLV from an onion message.
260 if message_type.is_some() { return Err(DecodeError::InvalidValue) }
262 message_type = Some(msg_type);
264 tlv_type if OffersMessage::is_known_type(tlv_type) => {
265 let msg = OffersMessage::read(msg_reader, (tlv_type, logger))?;
266 message = Some(ParsedOnionMessageContents::Offers(msg));
269 #[cfg(async_payments)]
270 tlv_type if AsyncPaymentsMessage::is_known_type(tlv_type) => {
271 let msg = AsyncPaymentsMessage::read(msg_reader, tlv_type)?;
272 message = Some(ParsedOnionMessageContents::AsyncPayments(msg));
275 _ => match handler.read_custom_message(msg_type, msg_reader)? {
277 message = Some(ParsedOnionMessageContents::Custom(msg));
284 rd.eat_remaining().map_err(|_| DecodeError::ShortRead)?;
287 None => return Err(DecodeError::InvalidValue),
288 Some(ChaChaPolyReadAdapter { readable: ControlTlvs::Forward(tlvs)}) => {
289 if message_type.is_some() {
290 return Err(DecodeError::InvalidValue)
292 Ok(Payload::Forward(ForwardControlTlvs::Unblinded(tlvs)))
294 Some(ChaChaPolyReadAdapter { readable: ControlTlvs::Receive(tlvs)}) => {
295 Ok(Payload::Receive {
296 control_tlvs: ReceiveControlTlvs::Unblinded(tlvs),
298 message: message.ok_or(DecodeError::InvalidValue)?,
305 /// When reading a packet off the wire, we don't know a priori whether the packet is to be forwarded
306 /// or received. Thus we read a `ControlTlvs` rather than reading a [`ForwardTlvs`] or
307 /// [`ReceiveTlvs`] directly. Also useful on the encoding side to keep forward and receive TLVs in
308 /// the same iterator.
309 pub(crate) enum ControlTlvs {
310 /// This onion message is intended to be forwarded.
311 Forward(ForwardTlvs),
312 /// This onion message is intended to be received.
313 Receive(ReceiveTlvs),
316 impl Readable for ControlTlvs {
317 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
318 _init_and_read_tlv_stream!(r, {
319 (1, _padding, option),
320 (2, short_channel_id, option),
321 (4, next_node_id, option),
322 (6, path_id, option),
323 (8, next_blinding_override, option),
325 let _padding: Option<Padding> = _padding;
327 let next_hop = match (short_channel_id, next_node_id) {
328 (Some(_), Some(_)) => return Err(DecodeError::InvalidValue),
329 (Some(scid), None) => Some(NextMessageHop::ShortChannelId(scid)),
330 (None, Some(pubkey)) => Some(NextMessageHop::NodeId(pubkey)),
331 (None, None) => None,
334 let valid_fwd_fmt = next_hop.is_some() && path_id.is_none();
335 let valid_recv_fmt = next_hop.is_none() && next_blinding_override.is_none();
337 let payload_fmt = if valid_fwd_fmt {
338 ControlTlvs::Forward(ForwardTlvs {
339 next_hop: next_hop.unwrap(),
340 next_blinding_override,
342 } else if valid_recv_fmt {
343 ControlTlvs::Receive(ReceiveTlvs {
347 return Err(DecodeError::InvalidValue)
354 impl Writeable for ControlTlvs {
355 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
357 Self::Forward(tlvs) => tlvs.write(w),
358 Self::Receive(tlvs) => tlvs.write(w),