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;
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::util::chacha20poly1305rfc::{ChaChaPolyReadAdapter, ChaChaPolyWriteAdapter};
23 use crate::util::logger::Logger;
24 use crate::util::ser::{BigSize, FixedLengthReader, LengthRead, LengthReadable, LengthReadableArgs, Readable, ReadableArgs, Writeable, Writer};
27 use crate::io::{self, Read};
28 use crate::prelude::*;
30 // Per the spec, an onion message packet's `hop_data` field length should be
31 // SMALL_PACKET_HOP_DATA_LEN if it fits, else BIG_PACKET_HOP_DATA_LEN if it fits.
32 pub(super) const SMALL_PACKET_HOP_DATA_LEN: usize = 1300;
33 pub(super) const BIG_PACKET_HOP_DATA_LEN: usize = 32768;
35 /// Packet of hop data for next peer
36 #[derive(Clone, Debug, PartialEq, Eq)]
38 /// Bolt 04 version number
40 /// A random sepc256k1 point, used to build the ECDH shared secret to decrypt hop_data
41 pub public_key: PublicKey,
42 /// Encrypted payload for the next hop
44 // Unlike the onion packets used for payments, onion message packets can have payloads greater
46 // TODO: if 1300 ends up being the most common size, optimize this to be:
47 // enum { ThirteenHundred([u8; 1300]), VarLen(Vec<u8>) }
48 pub hop_data: Vec<u8>,
49 /// HMAC to verify the integrity of hop_data
53 impl onion_utils::Packet for Packet {
55 fn new(public_key: PublicKey, hop_data: Vec<u8>, hmac: [u8; 32]) -> Packet {
65 impl Writeable for Packet {
66 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
67 self.version.write(w)?;
68 self.public_key.write(w)?;
69 w.write_all(&self.hop_data)?;
75 impl LengthReadable for Packet {
76 fn read<R: LengthRead>(r: &mut R) -> Result<Self, DecodeError> {
77 const READ_BUFFER_SIZE: usize = 4096;
79 let version = Readable::read(r)?;
80 let public_key = Readable::read(r)?;
82 let mut hop_data = Vec::new();
83 let hop_data_len = r.total_bytes().saturating_sub(66) as usize; // 1 (version) + 33 (pubkey) + 32 (HMAC) = 66
85 while read_idx < hop_data_len {
86 let mut read_buffer = [0; READ_BUFFER_SIZE];
87 let read_amt = cmp::min(hop_data_len - read_idx, READ_BUFFER_SIZE);
88 r.read_exact(&mut read_buffer[..read_amt])?;
89 hop_data.extend_from_slice(&read_buffer[..read_amt]);
93 let hmac = Readable::read(r)?;
103 /// Onion message payloads contain "control" TLVs and "data" TLVs. Control TLVs are used to route
104 /// the onion message from hop to hop and for path verification, whereas data TLVs contain the onion
105 /// message content itself, such as an invoice request.
106 pub(super) enum Payload<T: CustomOnionMessageContents> {
107 /// This payload is for an intermediate hop.
108 Forward(ForwardControlTlvs),
109 /// This payload is for the final hop.
111 control_tlvs: ReceiveControlTlvs,
112 reply_path: Option<BlindedPath>,
113 message: OnionMessageContents<T>,
118 /// The contents of an onion message. In the context of offers, this would be the invoice, invoice
119 /// request, or invoice error.
120 pub enum OnionMessageContents<T: CustomOnionMessageContents> {
121 /// A message related to BOLT 12 Offers.
122 Offers(OffersMessage),
123 /// A custom onion message specified by the user.
127 impl<T: CustomOnionMessageContents> OnionMessageContents<T> {
128 /// Returns the type that was used to decode the message payload.
130 /// This is not exported to bindings users as methods on non-cloneable enums are not currently exportable
131 pub fn tlv_type(&self) -> u64 {
133 &OnionMessageContents::Offers(ref msg) => msg.tlv_type(),
134 &OnionMessageContents::Custom(ref msg) => msg.tlv_type(),
139 /// This is not exported to bindings users as methods on non-cloneable enums are not currently exportable
140 impl<T: CustomOnionMessageContents> Writeable for OnionMessageContents<T> {
141 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
143 OnionMessageContents::Offers(msg) => Ok(msg.write(w)?),
144 OnionMessageContents::Custom(msg) => Ok(msg.write(w)?),
149 /// The contents of a custom onion message.
150 pub trait CustomOnionMessageContents: Writeable {
151 /// Returns the TLV type identifying the message contents. MUST be >= 64.
152 fn tlv_type(&self) -> u64;
155 /// Forward control TLVs in their blinded and unblinded form.
156 pub(super) enum ForwardControlTlvs {
157 /// If we're sending to a blinded path, the node that constructed the blinded path has provided
158 /// this hop's control TLVs, already encrypted into bytes.
160 /// If we're constructing an onion message hop through an intermediate unblinded node, we'll need
161 /// to construct the intermediate hop's control TLVs in their unblinded state to avoid encoding
162 /// them into an intermediate Vec. See [`crate::blinded_path::message::ForwardTlvs`] for more
164 Unblinded(ForwardTlvs),
167 /// Receive control TLVs in their blinded and unblinded form.
168 pub(super) enum ReceiveControlTlvs {
169 /// See [`ForwardControlTlvs::Blinded`].
171 /// See [`ForwardControlTlvs::Unblinded`] and [`crate::blinded_path::message::ReceiveTlvs`].
172 Unblinded(ReceiveTlvs),
175 // Uses the provided secret to simultaneously encode and encrypt the unblinded control TLVs.
176 impl<T: CustomOnionMessageContents> Writeable for (Payload<T>, [u8; 32]) {
177 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
179 Payload::Forward(ForwardControlTlvs::Blinded(encrypted_bytes)) => {
180 _encode_varint_length_prefixed_tlv!(w, {
181 (4, *encrypted_bytes, required_vec)
185 control_tlvs: ReceiveControlTlvs::Blinded(encrypted_bytes), reply_path, message,
187 _encode_varint_length_prefixed_tlv!(w, {
188 (2, reply_path, option),
189 (4, *encrypted_bytes, required_vec),
190 (message.tlv_type(), message, required)
193 Payload::Forward(ForwardControlTlvs::Unblinded(control_tlvs)) => {
194 let write_adapter = ChaChaPolyWriteAdapter::new(self.1, &control_tlvs);
195 _encode_varint_length_prefixed_tlv!(w, {
196 (4, write_adapter, required)
200 control_tlvs: ReceiveControlTlvs::Unblinded(control_tlvs), reply_path, message,
202 let write_adapter = ChaChaPolyWriteAdapter::new(self.1, &control_tlvs);
203 _encode_varint_length_prefixed_tlv!(w, {
204 (2, reply_path, option),
205 (4, write_adapter, required),
206 (message.tlv_type(), message, required)
214 // Uses the provided secret to simultaneously decode and decrypt the control TLVs and data TLV.
215 impl<H: CustomOnionMessageHandler + ?Sized, L: Logger + ?Sized>
216 ReadableArgs<(SharedSecret, &H, &L)> for Payload<<H as CustomOnionMessageHandler>::CustomMessage> {
217 fn read<R: Read>(r: &mut R, args: (SharedSecret, &H, &L)) -> Result<Self, DecodeError> {
218 let (encrypted_tlvs_ss, handler, logger) = args;
220 let v: BigSize = Readable::read(r)?;
221 let mut rd = FixedLengthReader::new(r, v.0);
222 let mut reply_path: Option<BlindedPath> = None;
223 let mut read_adapter: Option<ChaChaPolyReadAdapter<ControlTlvs>> = None;
224 let rho = onion_utils::gen_rho_from_shared_secret(&encrypted_tlvs_ss.secret_bytes());
225 let mut message_type: Option<u64> = None;
226 let mut message = None;
227 decode_tlv_stream_with_custom_tlv_decode!(&mut rd, {
228 (2, reply_path, option),
229 (4, read_adapter, (option: LengthReadableArgs, rho)),
230 }, |msg_type, msg_reader| {
231 if msg_type < 64 { return Ok(false) }
232 // Don't allow reading more than one data TLV from an onion message.
233 if message_type.is_some() { return Err(DecodeError::InvalidValue) }
235 message_type = Some(msg_type);
237 tlv_type if OffersMessage::is_known_type(tlv_type) => {
238 let msg = OffersMessage::read(msg_reader, (tlv_type, logger))?;
239 message = Some(OnionMessageContents::Offers(msg));
242 _ => match handler.read_custom_message(msg_type, msg_reader)? {
244 message = Some(OnionMessageContents::Custom(msg));
251 rd.eat_remaining().map_err(|_| DecodeError::ShortRead)?;
254 None => return Err(DecodeError::InvalidValue),
255 Some(ChaChaPolyReadAdapter { readable: ControlTlvs::Forward(tlvs)}) => {
256 if message_type.is_some() {
257 return Err(DecodeError::InvalidValue)
259 Ok(Payload::Forward(ForwardControlTlvs::Unblinded(tlvs)))
261 Some(ChaChaPolyReadAdapter { readable: ControlTlvs::Receive(tlvs)}) => {
262 Ok(Payload::Receive {
263 control_tlvs: ReceiveControlTlvs::Unblinded(tlvs),
265 message: message.ok_or(DecodeError::InvalidValue)?,
272 /// When reading a packet off the wire, we don't know a priori whether the packet is to be forwarded
273 /// or received. Thus we read a `ControlTlvs` rather than reading a [`ForwardTlvs`] or
274 /// [`ReceiveTlvs`] directly. Also useful on the encoding side to keep forward and receive TLVs in
275 /// the same iterator.
276 pub(crate) enum ControlTlvs {
277 /// This onion message is intended to be forwarded.
278 Forward(ForwardTlvs),
279 /// This onion message is intended to be received.
280 Receive(ReceiveTlvs),
283 impl Readable for ControlTlvs {
284 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
285 _init_and_read_tlv_stream!(r, {
286 (1, _padding, option),
287 (2, _short_channel_id, option),
288 (4, next_node_id, option),
289 (6, path_id, option),
290 (8, next_blinding_override, option),
292 let _padding: Option<Padding> = _padding;
293 let _short_channel_id: Option<u64> = _short_channel_id;
295 let valid_fwd_fmt = next_node_id.is_some() && path_id.is_none();
296 let valid_recv_fmt = next_node_id.is_none() && next_blinding_override.is_none();
298 let payload_fmt = if valid_fwd_fmt {
299 ControlTlvs::Forward(ForwardTlvs {
300 next_node_id: next_node_id.unwrap(),
301 next_blinding_override,
303 } else if valid_recv_fmt {
304 ControlTlvs::Receive(ReceiveTlvs {
308 return Err(DecodeError::InvalidValue)
315 impl Writeable for ControlTlvs {
316 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
318 Self::Forward(tlvs) => tlvs.write(w),
319 Self::Receive(tlvs) => tlvs.write(w),