Skip to main content

lightning/onion_message/
offers.rs

1// This file is Copyright its original authors, visible in version control
2// history.
3//
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
8// licenses.
9
10//! Message handling for BOLT 12 Offers.
11
12use crate::blinded_path::message::OffersContext;
13use crate::io::{self, Read};
14use crate::ln::msgs::DecodeError;
15use crate::offers::invoice::Bolt12Invoice;
16use crate::offers::invoice_error::InvoiceError;
17use crate::offers::invoice_request::InvoiceRequest;
18use crate::offers::parse::Bolt12ParseError;
19use crate::offers::static_invoice::StaticInvoice;
20use crate::onion_message::messenger::{MessageSendInstructions, Responder, ResponseInstruction};
21use crate::onion_message::packet::OnionMessageContents;
22use crate::util::logger::Logger;
23use crate::util::ser::{Readable, ReadableArgs, Writeable, Writer};
24use core::fmt;
25use core::ops::Deref;
26
27use crate::prelude::*;
28
29// TLV record types for the `onionmsg_tlv` TLV stream as defined in BOLT 4.
30const INVOICE_REQUEST_TLV_TYPE: u64 = 64;
31const INVOICE_TLV_TYPE: u64 = 66;
32const INVOICE_ERROR_TLV_TYPE: u64 = 68;
33// Spec'd in https://github.com/lightning/bolts/pull/1149.
34const STATIC_INVOICE_TLV_TYPE: u64 = 70;
35
36/// A handler for an [`OnionMessage`] containing a BOLT 12 Offers message as its payload.
37///
38/// [`OnionMessage`]: crate::ln::msgs::OnionMessage
39pub trait OffersMessageHandler {
40	/// Handles the given message by either responding with an [`Bolt12Invoice`], sending a payment,
41	/// or replying with an error.
42	///
43	/// If the provided [`OffersContext`] is `Some`, then the message was sent to a blinded path that we
44	/// created and was authenticated as such by the [`OnionMessenger`]. There is one exception to
45	/// this: [`OffersContext::InvoiceRequest`].
46	///
47	/// In order to support offers created prior to LDK 0.2, [`OffersContext::InvoiceRequest`]s are
48	/// not authenticated by the [`OnionMessenger`]. It is the responsibility of message handling code
49	/// to authenticate the provided [`OffersContext`] in this case.
50	///
51	/// The returned [`OffersMessage`], if any, is enqueued to be sent by [`OnionMessenger`].
52	///
53	/// [`OnionMessenger`]: crate::onion_message::messenger::OnionMessenger
54	fn handle_message(
55		&self, message: OffersMessage, context: Option<OffersContext>, responder: Option<Responder>,
56	) -> Option<(OffersMessage, ResponseInstruction)>;
57
58	/// Releases any [`OffersMessage`]s that need to be sent.
59	///
60	/// Typically, this is used for messages initiating a payment flow rather than in response to
61	/// another message. The latter should use the return value of [`Self::handle_message`].
62	fn release_pending_messages(&self) -> Vec<(OffersMessage, MessageSendInstructions)> {
63		vec![]
64	}
65}
66
67impl<T: OffersMessageHandler + ?Sized, O: Deref<Target = T>> OffersMessageHandler for O {
68	fn handle_message(
69		&self, message: OffersMessage, context: Option<OffersContext>, responder: Option<Responder>,
70	) -> Option<(OffersMessage, ResponseInstruction)> {
71		self.deref().handle_message(message, context, responder)
72	}
73	fn release_pending_messages(&self) -> Vec<(OffersMessage, MessageSendInstructions)> {
74		self.deref().release_pending_messages()
75	}
76}
77
78/// Possible BOLT 12 Offers messages sent and received via an [`OnionMessage`].
79///
80/// [`OnionMessage`]: crate::ln::msgs::OnionMessage
81#[derive(Clone)]
82pub enum OffersMessage {
83	/// A request for a [`Bolt12Invoice`] for a particular [`Offer`].
84	///
85	/// [`Offer`]: crate::offers::offer::Offer
86	InvoiceRequest(InvoiceRequest),
87
88	/// A [`Bolt12Invoice`] sent in response to an [`InvoiceRequest`] or a [`Refund`].
89	///
90	/// [`Refund`]: crate::offers::refund::Refund
91	Invoice(Bolt12Invoice),
92
93	/// A [`StaticInvoice`] sent in response to an [`InvoiceRequest`].
94	StaticInvoice(StaticInvoice),
95
96	/// An error from handling an [`OffersMessage`].
97	InvoiceError(InvoiceError),
98}
99
100impl OffersMessage {
101	/// Returns whether `tlv_type` corresponds to a TLV record for Offers.
102	pub fn is_known_type(tlv_type: u64) -> bool {
103		match tlv_type {
104			INVOICE_REQUEST_TLV_TYPE
105			| INVOICE_TLV_TYPE
106			| INVOICE_ERROR_TLV_TYPE
107			| STATIC_INVOICE_TLV_TYPE => true,
108			_ => false,
109		}
110	}
111
112	fn parse(tlv_type: u64, bytes: Vec<u8>) -> Result<Self, Bolt12ParseError> {
113		match tlv_type {
114			INVOICE_REQUEST_TLV_TYPE => Ok(Self::InvoiceRequest(InvoiceRequest::try_from(bytes)?)),
115			INVOICE_TLV_TYPE => Ok(Self::Invoice(Bolt12Invoice::try_from(bytes)?)),
116			STATIC_INVOICE_TLV_TYPE => Ok(Self::StaticInvoice(StaticInvoice::try_from(bytes)?)),
117			_ => Err(Bolt12ParseError::Decode(DecodeError::InvalidValue)),
118		}
119	}
120
121	fn get_msg_type(&self) -> &'static str {
122		match &self {
123			OffersMessage::InvoiceRequest(_) => "Invoice Request",
124			OffersMessage::Invoice(_) => "Invoice",
125			OffersMessage::StaticInvoice(_) => "Static Invoice",
126			OffersMessage::InvoiceError(_) => "Invoice Error",
127		}
128	}
129}
130
131impl fmt::Debug for OffersMessage {
132	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
133		match self {
134			OffersMessage::InvoiceRequest(message) => {
135				write!(f, "{:?}", message.as_tlv_stream())
136			},
137			OffersMessage::Invoice(message) => {
138				write!(f, "{:?}", message.as_tlv_stream())
139			},
140			OffersMessage::StaticInvoice(message) => {
141				write!(f, "{:?}", message)
142			},
143			OffersMessage::InvoiceError(message) => {
144				write!(f, "{:?}", message)
145			},
146		}
147	}
148}
149
150impl OnionMessageContents for OffersMessage {
151	fn tlv_type(&self) -> u64 {
152		match self {
153			OffersMessage::InvoiceRequest(_) => INVOICE_REQUEST_TLV_TYPE,
154			OffersMessage::Invoice(_) => INVOICE_TLV_TYPE,
155			OffersMessage::StaticInvoice(_) => STATIC_INVOICE_TLV_TYPE,
156			OffersMessage::InvoiceError(_) => INVOICE_ERROR_TLV_TYPE,
157		}
158	}
159	#[cfg(c_bindings)]
160	fn msg_type(&self) -> String {
161		self.get_msg_type().to_string()
162	}
163	#[cfg(not(c_bindings))]
164	fn msg_type(&self) -> &'static str {
165		self.get_msg_type()
166	}
167}
168
169impl Writeable for OffersMessage {
170	fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
171		match self {
172			OffersMessage::InvoiceRequest(message) => message.write(w),
173			OffersMessage::Invoice(message) => message.write(w),
174			OffersMessage::StaticInvoice(message) => message.write(w),
175			OffersMessage::InvoiceError(message) => message.write(w),
176		}
177	}
178}
179
180impl<L: Logger + ?Sized> ReadableArgs<(u64, &L)> for OffersMessage {
181	fn read<R: Read>(r: &mut R, read_args: (u64, &L)) -> Result<Self, DecodeError> {
182		let (tlv_type, logger) = read_args;
183		if tlv_type == INVOICE_ERROR_TLV_TYPE {
184			return Ok(Self::InvoiceError(InvoiceError::read(r)?));
185		}
186
187		let mut bytes = Vec::new();
188		r.read_to_limit(&mut bytes, u64::MAX).unwrap();
189
190		match Self::parse(tlv_type, bytes) {
191			Ok(message) => Ok(message),
192			Err(Bolt12ParseError::Decode(e)) => Err(e),
193			Err(Bolt12ParseError::InvalidSemantics(e)) => {
194				log_trace!(logger, "Invalid semantics for TLV type {}: {:?}", tlv_type, e);
195				Err(DecodeError::InvalidValue)
196			},
197			Err(Bolt12ParseError::InvalidSignature(e)) => {
198				log_trace!(logger, "Invalid signature for TLV type {}: {:?}", tlv_type, e);
199				Err(DecodeError::InvalidValue)
200			},
201			Err(_) => Err(DecodeError::InvalidValue),
202		}
203	}
204}