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 use crate::onion_message::packet::OnionMessageContents;
20 use crate::util::logger::Logger;
21 use crate::util::ser::{Readable, ReadableArgs, Writeable, Writer};
22 use crate::onion_message::messenger::{ResponseInstruction, Responder};
23 #[cfg(not(c_bindings))]
24 use crate::onion_message::messenger::PendingOnionMessage;
26 use crate::prelude::*;
28 // TLV record types for the `onionmsg_tlv` TLV stream as defined in BOLT 4.
29 const INVOICE_REQUEST_TLV_TYPE: u64 = 64;
30 const INVOICE_TLV_TYPE: u64 = 66;
31 const INVOICE_ERROR_TLV_TYPE: u64 = 68;
33 /// A handler for an [`OnionMessage`] containing a BOLT 12 Offers message as its payload.
35 /// [`OnionMessage`]: crate::ln::msgs::OnionMessage
36 pub trait OffersMessageHandler {
37 /// Handles the given message by either responding with an [`Bolt12Invoice`], sending a payment,
38 /// or replying with an error.
40 /// The returned [`OffersMessage`], if any, is enqueued to be sent by [`OnionMessenger`].
42 /// [`OnionMessenger`]: crate::onion_message::messenger::OnionMessenger
43 fn handle_message(&self, message: OffersMessage, responder: Option<Responder>) -> ResponseInstruction<OffersMessage>;
45 /// Releases any [`OffersMessage`]s that need to be sent.
47 /// Typically, this is used for messages initiating a payment flow rather than in response to
48 /// another message. The latter should use the return value of [`Self::handle_message`].
49 #[cfg(not(c_bindings))]
50 fn release_pending_messages(&self) -> Vec<PendingOnionMessage<OffersMessage>> { vec![] }
52 /// Releases any [`OffersMessage`]s that need to be sent.
54 /// Typically, this is used for messages initiating a payment flow rather than in response to
55 /// another message. The latter should use the return value of [`Self::handle_message`].
57 fn release_pending_messages(&self) -> Vec<(OffersMessage, crate::onion_message::messenger::Destination, Option<crate::blinded_path::BlindedPath>)> { vec![] }
60 /// Possible BOLT 12 Offers messages sent and received via an [`OnionMessage`].
62 /// [`OnionMessage`]: crate::ln::msgs::OnionMessage
64 pub enum OffersMessage {
65 /// A request for a [`Bolt12Invoice`] for a particular [`Offer`].
67 /// [`Offer`]: crate::offers::offer::Offer
68 InvoiceRequest(InvoiceRequest),
70 /// A [`Bolt12Invoice`] sent in response to an [`InvoiceRequest`] or a [`Refund`].
72 /// [`Refund`]: crate::offers::refund::Refund
73 Invoice(Bolt12Invoice),
75 /// An error from handling an [`OffersMessage`].
76 InvoiceError(InvoiceError),
80 /// Returns whether `tlv_type` corresponds to a TLV record for Offers.
81 pub fn is_known_type(tlv_type: u64) -> bool {
83 INVOICE_REQUEST_TLV_TYPE | INVOICE_TLV_TYPE | INVOICE_ERROR_TLV_TYPE => true,
88 fn parse(tlv_type: u64, bytes: Vec<u8>) -> Result<Self, Bolt12ParseError> {
90 INVOICE_REQUEST_TLV_TYPE => Ok(Self::InvoiceRequest(InvoiceRequest::try_from(bytes)?)),
91 INVOICE_TLV_TYPE => Ok(Self::Invoice(Bolt12Invoice::try_from(bytes)?)),
92 _ => Err(Bolt12ParseError::Decode(DecodeError::InvalidValue)),
97 impl fmt::Debug for OffersMessage {
98 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
100 OffersMessage::InvoiceRequest(message) => {
101 write!(f, "{:?}", message.as_tlv_stream())
103 OffersMessage::Invoice(message) => {
104 write!(f, "{:?}", message.as_tlv_stream())
106 OffersMessage::InvoiceError(message) => {
107 write!(f, "{:?}", message)
113 impl OnionMessageContents for OffersMessage {
114 fn tlv_type(&self) -> u64 {
116 OffersMessage::InvoiceRequest(_) => INVOICE_REQUEST_TLV_TYPE,
117 OffersMessage::Invoice(_) => INVOICE_TLV_TYPE,
118 OffersMessage::InvoiceError(_) => INVOICE_ERROR_TLV_TYPE,
121 fn msg_type(&self) -> &'static str {
123 OffersMessage::InvoiceRequest(_) => "Invoice Request",
124 OffersMessage::Invoice(_) => "Invoice",
125 OffersMessage::InvoiceError(_) => "Invoice Error",
130 impl Writeable for OffersMessage {
131 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
133 OffersMessage::InvoiceRequest(message) => message.write(w),
134 OffersMessage::Invoice(message) => message.write(w),
135 OffersMessage::InvoiceError(message) => message.write(w),
140 impl<L: Logger + ?Sized> ReadableArgs<(u64, &L)> for OffersMessage {
141 fn read<R: Read>(r: &mut R, read_args: (u64, &L)) -> Result<Self, DecodeError> {
142 let (tlv_type, logger) = read_args;
143 if tlv_type == INVOICE_ERROR_TLV_TYPE {
144 return Ok(Self::InvoiceError(InvoiceError::read(r)?));
147 let mut bytes = Vec::new();
148 r.read_to_end(&mut bytes).unwrap();
150 match Self::parse(tlv_type, bytes) {
151 Ok(message) => Ok(message),
152 Err(Bolt12ParseError::Decode(e)) => Err(e),
153 Err(Bolt12ParseError::InvalidSemantics(e)) => {
154 log_trace!(logger, "Invalid semantics for TLV type {}: {:?}", tlv_type, e);
155 Err(DecodeError::InvalidValue)
157 Err(Bolt12ParseError::InvalidSignature(e)) => {
158 log_trace!(logger, "Invalid signature for TLV type {}: {:?}", tlv_type, e);
159 Err(DecodeError::InvalidValue)
161 Err(_) => Err(DecodeError::InvalidValue),