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: ParsedOnionMessageContents<T>,
117 /// The contents of an onion message as read from the wire.
119 pub enum ParsedOnionMessageContents<T: CustomOnionMessageContents> {
120 /// A message related to BOLT 12 Offers.
121 Offers(OffersMessage),
122 /// A custom onion message specified by the user.
126 impl<T: CustomOnionMessageContents> ParsedOnionMessageContents<T> {
127 /// Returns the type that was used to decode the message payload.
129 /// This is not exported to bindings users as methods on non-cloneable enums are not currently exportable
130 pub fn tlv_type(&self) -> u64 {
132 &ParsedOnionMessageContents::Offers(ref msg) => msg.tlv_type(),
133 &ParsedOnionMessageContents::Custom(ref msg) => msg.tlv_type(),
138 /// This is not exported to bindings users as methods on non-cloneable enums are not currently exportable
139 impl<T: CustomOnionMessageContents> Writeable for ParsedOnionMessageContents<T> {
140 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
142 ParsedOnionMessageContents::Offers(msg) => Ok(msg.write(w)?),
143 ParsedOnionMessageContents::Custom(msg) => Ok(msg.write(w)?),
148 /// The contents of a custom onion message.
149 pub trait CustomOnionMessageContents: Writeable {
150 /// Returns the TLV type identifying the message contents. MUST be >= 64.
151 fn tlv_type(&self) -> u64;
154 /// Forward control TLVs in their blinded and unblinded form.
155 pub(super) enum ForwardControlTlvs {
156 /// If we're sending to a blinded path, the node that constructed the blinded path has provided
157 /// this hop's control TLVs, already encrypted into bytes.
159 /// If we're constructing an onion message hop through an intermediate unblinded node, we'll need
160 /// to construct the intermediate hop's control TLVs in their unblinded state to avoid encoding
161 /// them into an intermediate Vec. See [`crate::blinded_path::message::ForwardTlvs`] for more
163 Unblinded(ForwardTlvs),
166 /// Receive control TLVs in their blinded and unblinded form.
167 pub(super) enum ReceiveControlTlvs {
168 /// See [`ForwardControlTlvs::Blinded`].
170 /// See [`ForwardControlTlvs::Unblinded`] and [`crate::blinded_path::message::ReceiveTlvs`].
171 Unblinded(ReceiveTlvs),
174 // Uses the provided secret to simultaneously encode and encrypt the unblinded control TLVs.
175 impl<T: CustomOnionMessageContents> Writeable for (Payload<T>, [u8; 32]) {
176 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
178 Payload::Forward(ForwardControlTlvs::Blinded(encrypted_bytes)) => {
179 _encode_varint_length_prefixed_tlv!(w, {
180 (4, *encrypted_bytes, required_vec)
184 control_tlvs: ReceiveControlTlvs::Blinded(encrypted_bytes), reply_path, message,
186 _encode_varint_length_prefixed_tlv!(w, {
187 (2, reply_path, option),
188 (4, *encrypted_bytes, required_vec),
189 (message.tlv_type(), message, required)
192 Payload::Forward(ForwardControlTlvs::Unblinded(control_tlvs)) => {
193 let write_adapter = ChaChaPolyWriteAdapter::new(self.1, &control_tlvs);
194 _encode_varint_length_prefixed_tlv!(w, {
195 (4, write_adapter, required)
199 control_tlvs: ReceiveControlTlvs::Unblinded(control_tlvs), reply_path, message,
201 let write_adapter = ChaChaPolyWriteAdapter::new(self.1, &control_tlvs);
202 _encode_varint_length_prefixed_tlv!(w, {
203 (2, reply_path, option),
204 (4, write_adapter, required),
205 (message.tlv_type(), message, required)
213 // Uses the provided secret to simultaneously decode and decrypt the control TLVs and data TLV.
214 impl<H: CustomOnionMessageHandler + ?Sized, L: Logger + ?Sized>
215 ReadableArgs<(SharedSecret, &H, &L)> for Payload<<H as CustomOnionMessageHandler>::CustomMessage> {
216 fn read<R: Read>(r: &mut R, args: (SharedSecret, &H, &L)) -> Result<Self, DecodeError> {
217 let (encrypted_tlvs_ss, handler, logger) = args;
219 let v: BigSize = Readable::read(r)?;
220 let mut rd = FixedLengthReader::new(r, v.0);
221 let mut reply_path: Option<BlindedPath> = None;
222 let mut read_adapter: Option<ChaChaPolyReadAdapter<ControlTlvs>> = None;
223 let rho = onion_utils::gen_rho_from_shared_secret(&encrypted_tlvs_ss.secret_bytes());
224 let mut message_type: Option<u64> = None;
225 let mut message = None;
226 decode_tlv_stream_with_custom_tlv_decode!(&mut rd, {
227 (2, reply_path, option),
228 (4, read_adapter, (option: LengthReadableArgs, rho)),
229 }, |msg_type, msg_reader| {
230 if msg_type < 64 { return Ok(false) }
231 // Don't allow reading more than one data TLV from an onion message.
232 if message_type.is_some() { return Err(DecodeError::InvalidValue) }
234 message_type = Some(msg_type);
236 tlv_type if OffersMessage::is_known_type(tlv_type) => {
237 let msg = OffersMessage::read(msg_reader, (tlv_type, logger))?;
238 message = Some(ParsedOnionMessageContents::Offers(msg));
241 _ => match handler.read_custom_message(msg_type, msg_reader)? {
243 message = Some(ParsedOnionMessageContents::Custom(msg));
250 rd.eat_remaining().map_err(|_| DecodeError::ShortRead)?;
253 None => return Err(DecodeError::InvalidValue),
254 Some(ChaChaPolyReadAdapter { readable: ControlTlvs::Forward(tlvs)}) => {
255 if message_type.is_some() {
256 return Err(DecodeError::InvalidValue)
258 Ok(Payload::Forward(ForwardControlTlvs::Unblinded(tlvs)))
260 Some(ChaChaPolyReadAdapter { readable: ControlTlvs::Receive(tlvs)}) => {
261 Ok(Payload::Receive {
262 control_tlvs: ReceiveControlTlvs::Unblinded(tlvs),
264 message: message.ok_or(DecodeError::InvalidValue)?,
271 /// When reading a packet off the wire, we don't know a priori whether the packet is to be forwarded
272 /// or received. Thus we read a `ControlTlvs` rather than reading a [`ForwardTlvs`] or
273 /// [`ReceiveTlvs`] directly. Also useful on the encoding side to keep forward and receive TLVs in
274 /// the same iterator.
275 pub(crate) enum ControlTlvs {
276 /// This onion message is intended to be forwarded.
277 Forward(ForwardTlvs),
278 /// This onion message is intended to be received.
279 Receive(ReceiveTlvs),
282 impl Readable for ControlTlvs {
283 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
284 _init_and_read_tlv_stream!(r, {
285 (1, _padding, option),
286 (2, _short_channel_id, option),
287 (4, next_node_id, option),
288 (6, path_id, option),
289 (8, next_blinding_override, option),
291 let _padding: Option<Padding> = _padding;
292 let _short_channel_id: Option<u64> = _short_channel_id;
294 let valid_fwd_fmt = next_node_id.is_some() && path_id.is_none();
295 let valid_recv_fmt = next_node_id.is_none() && next_blinding_override.is_none();
297 let payload_fmt = if valid_fwd_fmt {
298 ControlTlvs::Forward(ForwardTlvs {
299 next_node_id: next_node_id.unwrap(),
300 next_blinding_override,
302 } else if valid_recv_fmt {
303 ControlTlvs::Receive(ReceiveTlvs {
307 return Err(DecodeError::InvalidValue)
314 impl Writeable for ControlTlvs {
315 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
317 Self::Forward(tlvs) => tlvs.write(w),
318 Self::Receive(tlvs) => tlvs.write(w),