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 use super::async_payments::AsyncPaymentsMessage;
21 use super::messenger::CustomOnionMessageHandler;
22 use super::offers::OffersMessage;
23 use crate::crypto::streams::{ChaChaPolyReadAdapter, ChaChaPolyWriteAdapter};
24 use crate::util::logger::Logger;
25 use crate::util::ser::{BigSize, FixedLengthReader, LengthRead, LengthReadable, LengthReadableArgs, Readable, ReadableArgs, Writeable, Writer};
29 use crate::io::{self, Read};
30 use crate::prelude::*;
32 // Per the spec, an onion message packet's `hop_data` field length should be
33 // SMALL_PACKET_HOP_DATA_LEN if it fits, else BIG_PACKET_HOP_DATA_LEN if it fits.
34 pub(super) const SMALL_PACKET_HOP_DATA_LEN: usize = 1300;
35 pub(super) const BIG_PACKET_HOP_DATA_LEN: usize = 32768;
37 /// Packet of hop data for next peer
38 #[derive(Clone, Hash, PartialEq, Eq)]
40 /// Bolt 04 version number
42 /// A random sepc256k1 point, used to build the ECDH shared secret to decrypt hop_data
43 pub public_key: PublicKey,
44 /// Encrypted payload for the next hop
46 // Unlike the onion packets used for payments, onion message packets can have payloads greater
48 // TODO: if 1300 ends up being the most common size, optimize this to be:
49 // enum { ThirteenHundred([u8; 1300]), VarLen(Vec<u8>) }
50 pub hop_data: Vec<u8>,
51 /// HMAC to verify the integrity of hop_data
55 impl onion_utils::Packet for Packet {
57 fn new(public_key: PublicKey, hop_data: Vec<u8>, hmac: [u8; 32]) -> Packet {
67 impl fmt::Debug for Packet {
68 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
69 f.write_fmt(format_args!("Onion message packet version {} with hmac {:?}", self.version, &self.hmac[..]))
73 impl Writeable for Packet {
74 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
75 self.version.write(w)?;
76 self.public_key.write(w)?;
77 w.write_all(&self.hop_data)?;
83 impl LengthReadable for Packet {
84 fn read<R: LengthRead>(r: &mut R) -> Result<Self, DecodeError> {
85 const READ_BUFFER_SIZE: usize = 4096;
87 let version = Readable::read(r)?;
88 let public_key = Readable::read(r)?;
90 let mut hop_data = Vec::new();
91 let hop_data_len = r.total_bytes().saturating_sub(66) as usize; // 1 (version) + 33 (pubkey) + 32 (HMAC) = 66
93 while read_idx < hop_data_len {
94 let mut read_buffer = [0; READ_BUFFER_SIZE];
95 let read_amt = cmp::min(hop_data_len - read_idx, READ_BUFFER_SIZE);
96 r.read_exact(&mut read_buffer[..read_amt])?;
97 hop_data.extend_from_slice(&read_buffer[..read_amt]);
101 let hmac = Readable::read(r)?;
111 /// Onion message payloads contain "control" TLVs and "data" TLVs. Control TLVs are used to route
112 /// the onion message from hop to hop and for path verification, whereas data TLVs contain the onion
113 /// message content itself, such as an invoice request.
114 pub(super) enum Payload<T: OnionMessageContents> {
115 /// This payload is for an intermediate hop.
116 Forward(ForwardControlTlvs),
117 /// This payload is for the final hop.
119 control_tlvs: ReceiveControlTlvs,
120 reply_path: Option<BlindedPath>,
125 /// The contents of an [`OnionMessage`] as read from the wire.
127 /// [`OnionMessage`]: crate::ln::msgs::OnionMessage
128 #[derive(Clone, Debug)]
129 pub enum ParsedOnionMessageContents<T: OnionMessageContents> {
130 /// A message related to BOLT 12 Offers.
131 Offers(OffersMessage),
132 /// A message related to async payments.
133 AsyncPayments(AsyncPaymentsMessage),
134 /// A custom onion message specified by the user.
138 impl<T: OnionMessageContents> OnionMessageContents for ParsedOnionMessageContents<T> {
139 /// Returns the type that was used to decode the message payload.
141 /// This is not exported to bindings users as methods on non-cloneable enums are not currently exportable
142 fn tlv_type(&self) -> u64 {
144 &ParsedOnionMessageContents::Offers(ref msg) => msg.tlv_type(),
145 &ParsedOnionMessageContents::AsyncPayments(ref msg) => msg.tlv_type(),
146 &ParsedOnionMessageContents::Custom(ref msg) => msg.tlv_type(),
149 fn msg_type(&self) -> &'static str {
151 ParsedOnionMessageContents::Offers(ref msg) => msg.msg_type(),
152 ParsedOnionMessageContents::AsyncPayments(ref msg) => msg.msg_type(),
153 ParsedOnionMessageContents::Custom(ref msg) => msg.msg_type(),
158 impl<T: OnionMessageContents> Writeable for ParsedOnionMessageContents<T> {
159 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
161 ParsedOnionMessageContents::Offers(msg) => Ok(msg.write(w)?),
162 ParsedOnionMessageContents::AsyncPayments(msg) => Ok(msg.write(w)?),
163 ParsedOnionMessageContents::Custom(msg) => Ok(msg.write(w)?),
168 /// The contents of an onion message.
169 pub trait OnionMessageContents: Writeable + core::fmt::Debug {
170 /// Returns the TLV type identifying the message contents. MUST be >= 64.
171 fn tlv_type(&self) -> u64;
173 /// Returns the message type
174 fn msg_type(&self) -> &'static str;
177 /// Forward control TLVs in their blinded and unblinded form.
178 pub(super) enum ForwardControlTlvs {
179 /// If we're sending to a blinded path, the node that constructed the blinded path has provided
180 /// this hop's control TLVs, already encrypted into bytes.
182 /// If we're constructing an onion message hop through an intermediate unblinded node, we'll need
183 /// to construct the intermediate hop's control TLVs in their unblinded state to avoid encoding
184 /// them into an intermediate Vec. See [`crate::blinded_path::message::ForwardTlvs`] for more
186 Unblinded(ForwardTlvs),
189 /// Receive control TLVs in their blinded and unblinded form.
190 pub(super) enum ReceiveControlTlvs {
191 /// See [`ForwardControlTlvs::Blinded`].
193 /// See [`ForwardControlTlvs::Unblinded`] and [`crate::blinded_path::message::ReceiveTlvs`].
194 Unblinded(ReceiveTlvs),
197 // Uses the provided secret to simultaneously encode and encrypt the unblinded control TLVs.
198 impl<T: OnionMessageContents> Writeable for (Payload<T>, [u8; 32]) {
199 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
201 Payload::Forward(ForwardControlTlvs::Blinded(encrypted_bytes)) => {
202 _encode_varint_length_prefixed_tlv!(w, {
203 (4, *encrypted_bytes, required_vec)
207 control_tlvs: ReceiveControlTlvs::Blinded(encrypted_bytes), reply_path, message,
209 _encode_varint_length_prefixed_tlv!(w, {
210 (2, reply_path, option),
211 (4, *encrypted_bytes, required_vec),
212 (message.tlv_type(), message, required)
215 Payload::Forward(ForwardControlTlvs::Unblinded(control_tlvs)) => {
216 let write_adapter = ChaChaPolyWriteAdapter::new(self.1, &control_tlvs);
217 _encode_varint_length_prefixed_tlv!(w, {
218 (4, write_adapter, required)
222 control_tlvs: ReceiveControlTlvs::Unblinded(control_tlvs), reply_path, message,
224 let write_adapter = ChaChaPolyWriteAdapter::new(self.1, &control_tlvs);
225 _encode_varint_length_prefixed_tlv!(w, {
226 (2, reply_path, option),
227 (4, write_adapter, required),
228 (message.tlv_type(), message, required)
236 // Uses the provided secret to simultaneously decode and decrypt the control TLVs and data TLV.
237 impl<H: CustomOnionMessageHandler + ?Sized, L: Logger + ?Sized> ReadableArgs<(SharedSecret, &H, &L)>
238 for Payload<ParsedOnionMessageContents<<H as CustomOnionMessageHandler>::CustomMessage>> {
239 fn read<R: Read>(r: &mut R, args: (SharedSecret, &H, &L)) -> Result<Self, DecodeError> {
240 let (encrypted_tlvs_ss, handler, logger) = args;
242 let v: BigSize = Readable::read(r)?;
243 let mut rd = FixedLengthReader::new(r, v.0);
244 let mut reply_path: Option<BlindedPath> = None;
245 let mut read_adapter: Option<ChaChaPolyReadAdapter<ControlTlvs>> = None;
246 let rho = onion_utils::gen_rho_from_shared_secret(&encrypted_tlvs_ss.secret_bytes());
247 let mut message_type: Option<u64> = None;
248 let mut message = None;
249 decode_tlv_stream_with_custom_tlv_decode!(&mut rd, {
250 (2, reply_path, option),
251 (4, read_adapter, (option: LengthReadableArgs, rho)),
252 }, |msg_type, msg_reader| {
253 if msg_type < 64 { return Ok(false) }
254 // Don't allow reading more than one data TLV from an onion message.
255 if message_type.is_some() { return Err(DecodeError::InvalidValue) }
257 message_type = Some(msg_type);
259 tlv_type if OffersMessage::is_known_type(tlv_type) => {
260 let msg = OffersMessage::read(msg_reader, (tlv_type, logger))?;
261 message = Some(ParsedOnionMessageContents::Offers(msg));
264 tlv_type if AsyncPaymentsMessage::is_known_type(tlv_type) => {
265 let msg = AsyncPaymentsMessage::read(msg_reader, tlv_type)?;
266 message = Some(ParsedOnionMessageContents::AsyncPayments(msg));
269 _ => match handler.read_custom_message(msg_type, msg_reader)? {
271 message = Some(ParsedOnionMessageContents::Custom(msg));
278 rd.eat_remaining().map_err(|_| DecodeError::ShortRead)?;
281 None => return Err(DecodeError::InvalidValue),
282 Some(ChaChaPolyReadAdapter { readable: ControlTlvs::Forward(tlvs)}) => {
283 if message_type.is_some() {
284 return Err(DecodeError::InvalidValue)
286 Ok(Payload::Forward(ForwardControlTlvs::Unblinded(tlvs)))
288 Some(ChaChaPolyReadAdapter { readable: ControlTlvs::Receive(tlvs)}) => {
289 Ok(Payload::Receive {
290 control_tlvs: ReceiveControlTlvs::Unblinded(tlvs),
292 message: message.ok_or(DecodeError::InvalidValue)?,
299 /// When reading a packet off the wire, we don't know a priori whether the packet is to be forwarded
300 /// or received. Thus we read a `ControlTlvs` rather than reading a [`ForwardTlvs`] or
301 /// [`ReceiveTlvs`] directly. Also useful on the encoding side to keep forward and receive TLVs in
302 /// the same iterator.
303 pub(crate) enum ControlTlvs {
304 /// This onion message is intended to be forwarded.
305 Forward(ForwardTlvs),
306 /// This onion message is intended to be received.
307 Receive(ReceiveTlvs),
310 impl Readable for ControlTlvs {
311 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
312 _init_and_read_tlv_stream!(r, {
313 (1, _padding, option),
314 (2, short_channel_id, option),
315 (4, next_node_id, option),
316 (6, path_id, option),
317 (8, next_blinding_override, option),
319 let _padding: Option<Padding> = _padding;
321 let next_hop = match (short_channel_id, next_node_id) {
322 (Some(_), Some(_)) => return Err(DecodeError::InvalidValue),
323 (Some(scid), None) => Some(NextMessageHop::ShortChannelId(scid)),
324 (None, Some(pubkey)) => Some(NextMessageHop::NodeId(pubkey)),
325 (None, None) => None,
328 let valid_fwd_fmt = next_hop.is_some() && path_id.is_none();
329 let valid_recv_fmt = next_hop.is_none() && next_blinding_override.is_none();
331 let payload_fmt = if valid_fwd_fmt {
332 ControlTlvs::Forward(ForwardTlvs {
333 next_hop: next_hop.unwrap(),
334 next_blinding_override,
336 } else if valid_recv_fmt {
337 ControlTlvs::Receive(ReceiveTlvs {
341 return Err(DecodeError::InvalidValue)
348 impl Writeable for ControlTlvs {
349 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
351 Self::Forward(tlvs) => tlvs.write(w),
352 Self::Receive(tlvs) => tlvs.write(w),