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 //! Message handling for BOLT 12 Offers.
13 use crate::io::{self, Read};
14 use crate::ln::msgs::DecodeError;
15 use crate::offers::invoice_error::InvoiceError;
16 use crate::offers::invoice_request::InvoiceRequest;
17 use crate::offers::invoice::Bolt12Invoice;
18 use crate::offers::parse::Bolt12ParseError;
19 #[cfg(async_payments)]
20 use crate::offers::static_invoice::StaticInvoice;
21 use crate::onion_message::packet::OnionMessageContents;
22 use crate::util::logger::Logger;
23 use crate::util::ser::{Readable, ReadableArgs, Writeable, Writer};
24 use crate::onion_message::messenger::{ResponseInstruction, Responder};
25 #[cfg(not(c_bindings))]
26 use crate::onion_message::messenger::PendingOnionMessage;
28 use crate::prelude::*;
30 // TLV record types for the `onionmsg_tlv` TLV stream as defined in BOLT 4.
31 const INVOICE_REQUEST_TLV_TYPE: u64 = 64;
32 const INVOICE_TLV_TYPE: u64 = 66;
33 const INVOICE_ERROR_TLV_TYPE: u64 = 68;
34 #[cfg(async_payments)]
35 const STATIC_INVOICE_TLV_TYPE: u64 = 70;
37 /// A handler for an [`OnionMessage`] containing a BOLT 12 Offers message as its payload.
39 /// [`OnionMessage`]: crate::ln::msgs::OnionMessage
40 pub trait OffersMessageHandler {
41 /// Handles the given message by either responding with an [`Bolt12Invoice`], sending a payment,
42 /// or replying with an error.
44 /// The returned [`OffersMessage`], if any, is enqueued to be sent by [`OnionMessenger`].
46 /// [`OnionMessenger`]: crate::onion_message::messenger::OnionMessenger
47 fn handle_message(&self, message: OffersMessage, responder: Option<Responder>) -> ResponseInstruction<OffersMessage>;
49 /// Releases any [`OffersMessage`]s that need to be sent.
51 /// Typically, this is used for messages initiating a payment flow rather than in response to
52 /// another message. The latter should use the return value of [`Self::handle_message`].
53 #[cfg(not(c_bindings))]
54 fn release_pending_messages(&self) -> Vec<PendingOnionMessage<OffersMessage>> { vec![] }
56 /// Releases any [`OffersMessage`]s that need to be sent.
58 /// Typically, this is used for messages initiating a payment flow rather than in response to
59 /// another message. The latter should use the return value of [`Self::handle_message`].
61 fn release_pending_messages(&self) -> Vec<(OffersMessage, crate::onion_message::messenger::Destination, Option<crate::blinded_path::BlindedPath>)> { vec![] }
64 /// Possible BOLT 12 Offers messages sent and received via an [`OnionMessage`].
66 /// [`OnionMessage`]: crate::ln::msgs::OnionMessage
68 pub enum OffersMessage {
69 /// A request for a [`Bolt12Invoice`] for a particular [`Offer`].
71 /// [`Offer`]: crate::offers::offer::Offer
72 InvoiceRequest(InvoiceRequest),
74 /// A [`Bolt12Invoice`] sent in response to an [`InvoiceRequest`] or a [`Refund`].
76 /// [`Refund`]: crate::offers::refund::Refund
77 Invoice(Bolt12Invoice),
79 #[cfg(async_payments)]
80 /// A [`StaticInvoice`] sent in response to an [`InvoiceRequest`].
81 StaticInvoice(StaticInvoice),
83 /// An error from handling an [`OffersMessage`].
84 InvoiceError(InvoiceError),
88 /// Returns whether `tlv_type` corresponds to a TLV record for Offers.
89 pub fn is_known_type(tlv_type: u64) -> bool {
91 INVOICE_REQUEST_TLV_TYPE
93 | INVOICE_ERROR_TLV_TYPE => true,
94 #[cfg(async_payments)]
95 STATIC_INVOICE_TLV_TYPE => true,
100 fn parse(tlv_type: u64, bytes: Vec<u8>) -> Result<Self, Bolt12ParseError> {
102 INVOICE_REQUEST_TLV_TYPE => Ok(Self::InvoiceRequest(InvoiceRequest::try_from(bytes)?)),
103 INVOICE_TLV_TYPE => Ok(Self::Invoice(Bolt12Invoice::try_from(bytes)?)),
104 #[cfg(async_payments)]
105 STATIC_INVOICE_TLV_TYPE => Ok(Self::StaticInvoice(StaticInvoice::try_from(bytes)?)),
106 _ => Err(Bolt12ParseError::Decode(DecodeError::InvalidValue)),
111 impl fmt::Debug for OffersMessage {
112 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
114 OffersMessage::InvoiceRequest(message) => {
115 write!(f, "{:?}", message.as_tlv_stream())
117 OffersMessage::Invoice(message) => {
118 write!(f, "{:?}", message.as_tlv_stream())
120 #[cfg(async_payments)]
121 OffersMessage::StaticInvoice(message) => {
122 write!(f, "{:?}", message)
124 OffersMessage::InvoiceError(message) => {
125 write!(f, "{:?}", message)
131 impl OnionMessageContents for OffersMessage {
132 fn tlv_type(&self) -> u64 {
134 OffersMessage::InvoiceRequest(_) => INVOICE_REQUEST_TLV_TYPE,
135 OffersMessage::Invoice(_) => INVOICE_TLV_TYPE,
136 #[cfg(async_payments)]
137 OffersMessage::StaticInvoice(_) => STATIC_INVOICE_TLV_TYPE,
138 OffersMessage::InvoiceError(_) => INVOICE_ERROR_TLV_TYPE,
141 fn msg_type(&self) -> &'static str {
143 OffersMessage::InvoiceRequest(_) => "Invoice Request",
144 OffersMessage::Invoice(_) => "Invoice",
145 #[cfg(async_payments)]
146 OffersMessage::StaticInvoice(_) => "Static Invoice",
147 OffersMessage::InvoiceError(_) => "Invoice Error",
152 impl Writeable for OffersMessage {
153 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
155 OffersMessage::InvoiceRequest(message) => message.write(w),
156 OffersMessage::Invoice(message) => message.write(w),
157 #[cfg(async_payments)]
158 OffersMessage::StaticInvoice(message) => message.write(w),
159 OffersMessage::InvoiceError(message) => message.write(w),
164 impl<L: Logger + ?Sized> ReadableArgs<(u64, &L)> for OffersMessage {
165 fn read<R: Read>(r: &mut R, read_args: (u64, &L)) -> Result<Self, DecodeError> {
166 let (tlv_type, logger) = read_args;
167 if tlv_type == INVOICE_ERROR_TLV_TYPE {
168 return Ok(Self::InvoiceError(InvoiceError::read(r)?));
171 let mut bytes = Vec::new();
172 r.read_to_end(&mut bytes).unwrap();
174 match Self::parse(tlv_type, bytes) {
175 Ok(message) => Ok(message),
176 Err(Bolt12ParseError::Decode(e)) => Err(e),
177 Err(Bolt12ParseError::InvalidSemantics(e)) => {
178 log_trace!(logger, "Invalid semantics for TLV type {}: {:?}", tlv_type, e);
179 Err(DecodeError::InvalidValue)
181 Err(Bolt12ParseError::InvalidSignature(e)) => {
182 log_trace!(logger, "Invalid signature for TLV type {}: {:?}", tlv_type, e);
183 Err(DecodeError::InvalidValue)
185 Err(_) => Err(DecodeError::InvalidValue),