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