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::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};
28 use crate::io::{self, Read};
29 use crate::prelude::*;
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;
36 /// Packet of hop data for next peer
37 #[derive(Clone, Hash, PartialEq, Eq)]
39 /// Bolt 04 version number
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
45 // Unlike the onion packets used for payments, onion message packets can have payloads greater
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
54 impl onion_utils::Packet for Packet {
56 fn new(public_key: PublicKey, hop_data: Vec<u8>, hmac: [u8; 32]) -> Packet {
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[..]))
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)?;
82 impl LengthReadable for Packet {
83 fn read<R: LengthRead>(r: &mut R) -> Result<Self, DecodeError> {
84 const READ_BUFFER_SIZE: usize = 4096;
86 let version = Readable::read(r)?;
87 let public_key = Readable::read(r)?;
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
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]);
100 let hmac = Readable::read(r)?;
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.
118 control_tlvs: ReceiveControlTlvs,
119 reply_path: Option<BlindedPath>,
124 /// The contents of an [`OnionMessage`] as read from the wire.
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.
135 impl<T: OnionMessageContents> OnionMessageContents for ParsedOnionMessageContents<T> {
136 /// Returns the type that was used to decode the message payload.
138 /// This is not exported to bindings users as methods on non-cloneable enums are not currently exportable
139 fn tlv_type(&self) -> u64 {
141 &ParsedOnionMessageContents::Offers(ref msg) => msg.tlv_type(),
142 &ParsedOnionMessageContents::Custom(ref msg) => msg.tlv_type(),
145 fn msg_type(&self) -> &'static str {
147 ParsedOnionMessageContents::Offers(ref msg) => msg.msg_type(),
148 ParsedOnionMessageContents::Custom(ref msg) => msg.msg_type(),
153 impl<T: OnionMessageContents> Writeable for ParsedOnionMessageContents<T> {
154 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
156 ParsedOnionMessageContents::Offers(msg) => Ok(msg.write(w)?),
157 ParsedOnionMessageContents::Custom(msg) => Ok(msg.write(w)?),
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;
167 /// Returns the message type
168 fn msg_type(&self) -> &'static str;
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.
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
180 Unblinded(ForwardTlvs),
183 /// Receive control TLVs in their blinded and unblinded form.
184 pub(super) enum ReceiveControlTlvs {
185 /// See [`ForwardControlTlvs::Blinded`].
187 /// See [`ForwardControlTlvs::Unblinded`] and [`crate::blinded_path::message::ReceiveTlvs`].
188 Unblinded(ReceiveTlvs),
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> {
195 Payload::Forward(ForwardControlTlvs::Blinded(encrypted_bytes)) => {
196 _encode_varint_length_prefixed_tlv!(w, {
197 (4, *encrypted_bytes, required_vec)
201 control_tlvs: ReceiveControlTlvs::Blinded(encrypted_bytes), reply_path, message,
203 _encode_varint_length_prefixed_tlv!(w, {
204 (2, reply_path, option),
205 (4, *encrypted_bytes, required_vec),
206 (message.tlv_type(), message, required)
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)
216 control_tlvs: ReceiveControlTlvs::Unblinded(control_tlvs), reply_path, message,
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)
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;
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) }
251 message_type = Some(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));
258 _ => match handler.read_custom_message(msg_type, msg_reader)? {
260 message = Some(ParsedOnionMessageContents::Custom(msg));
267 rd.eat_remaining().map_err(|_| DecodeError::ShortRead)?;
270 None => return Err(DecodeError::InvalidValue),
271 Some(ChaChaPolyReadAdapter { readable: ControlTlvs::Forward(tlvs)}) => {
272 if message_type.is_some() {
273 return Err(DecodeError::InvalidValue)
275 Ok(Payload::Forward(ForwardControlTlvs::Unblinded(tlvs)))
277 Some(ChaChaPolyReadAdapter { readable: ControlTlvs::Receive(tlvs)}) => {
278 Ok(Payload::Receive {
279 control_tlvs: ReceiveControlTlvs::Unblinded(tlvs),
281 message: message.ok_or(DecodeError::InvalidValue)?,
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),
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),
308 let _padding: Option<Padding> = _padding;
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,
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();
320 let payload_fmt = if valid_fwd_fmt {
321 ControlTlvs::Forward(ForwardTlvs {
322 next_hop: next_hop.unwrap(),
323 next_blinding_override,
325 } else if valid_recv_fmt {
326 ControlTlvs::Receive(ReceiveTlvs {
330 return Err(DecodeError::InvalidValue)
337 impl Writeable for ControlTlvs {
338 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
340 Self::Forward(tlvs) => tlvs.write(w),
341 Self::Receive(tlvs) => tlvs.write(w),