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 #[cfg(not(c_bindings))]
23 use crate::onion_message::messenger::PendingOnionMessage;
25 use crate::prelude::*;
27 // TLV record types for the `onionmsg_tlv` TLV stream as defined in BOLT 4.
28 const INVOICE_REQUEST_TLV_TYPE: u64 = 64;
29 const INVOICE_TLV_TYPE: u64 = 66;
30 const INVOICE_ERROR_TLV_TYPE: u64 = 68;
32 /// A handler for an [`OnionMessage`] containing a BOLT 12 Offers message as its payload.
34 /// [`OnionMessage`]: crate::ln::msgs::OnionMessage
35 pub trait OffersMessageHandler {
36 /// Handles the given message by either responding with an [`Bolt12Invoice`], sending a payment,
37 /// or replying with an error.
39 /// The returned [`OffersMessage`], if any, is enqueued to be sent by [`OnionMessenger`].
41 /// [`OnionMessenger`]: crate::onion_message::messenger::OnionMessenger
42 fn handle_message(&self, message: OffersMessage) -> Option<OffersMessage>;
44 /// Releases any [`OffersMessage`]s that need to be sent.
46 /// Typically, this is used for messages initiating a payment flow rather than in response to
47 /// another message. The latter should use the return value of [`Self::handle_message`].
48 #[cfg(not(c_bindings))]
49 fn release_pending_messages(&self) -> Vec<PendingOnionMessage<OffersMessage>> { vec![] }
51 /// Releases any [`OffersMessage`]s that need to be sent.
53 /// Typically, this is used for messages initiating a payment flow rather than in response to
54 /// another message. The latter should use the return value of [`Self::handle_message`].
56 fn release_pending_messages(&self) -> Vec<(OffersMessage, crate::onion_message::messenger::Destination, Option<crate::blinded_path::BlindedPath>)> { vec![] }
59 /// Possible BOLT 12 Offers messages sent and received via an [`OnionMessage`].
61 /// [`OnionMessage`]: crate::ln::msgs::OnionMessage
63 pub enum OffersMessage {
64 /// A request for a [`Bolt12Invoice`] for a particular [`Offer`].
66 /// [`Offer`]: crate::offers::offer::Offer
67 InvoiceRequest(InvoiceRequest),
69 /// A [`Bolt12Invoice`] sent in response to an [`InvoiceRequest`] or a [`Refund`].
71 /// [`Refund`]: crate::offers::refund::Refund
72 Invoice(Bolt12Invoice),
74 /// An error from handling an [`OffersMessage`].
75 InvoiceError(InvoiceError),
79 /// Returns whether `tlv_type` corresponds to a TLV record for Offers.
80 pub fn is_known_type(tlv_type: u64) -> bool {
82 INVOICE_REQUEST_TLV_TYPE | INVOICE_TLV_TYPE | INVOICE_ERROR_TLV_TYPE => true,
87 fn parse(tlv_type: u64, bytes: Vec<u8>) -> Result<Self, Bolt12ParseError> {
89 INVOICE_REQUEST_TLV_TYPE => Ok(Self::InvoiceRequest(InvoiceRequest::try_from(bytes)?)),
90 INVOICE_TLV_TYPE => Ok(Self::Invoice(Bolt12Invoice::try_from(bytes)?)),
91 _ => Err(Bolt12ParseError::Decode(DecodeError::InvalidValue)),
96 impl fmt::Debug for OffersMessage {
97 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
99 OffersMessage::InvoiceRequest(message) => {
100 write!(f, "{:?}", message.as_tlv_stream())
102 OffersMessage::Invoice(message) => {
103 write!(f, "{:?}", message.as_tlv_stream())
105 OffersMessage::InvoiceError(message) => {
106 write!(f, "{:?}", message)
112 impl OnionMessageContents for OffersMessage {
113 fn tlv_type(&self) -> u64 {
115 OffersMessage::InvoiceRequest(_) => INVOICE_REQUEST_TLV_TYPE,
116 OffersMessage::Invoice(_) => INVOICE_TLV_TYPE,
117 OffersMessage::InvoiceError(_) => INVOICE_ERROR_TLV_TYPE,
122 impl Writeable for OffersMessage {
123 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
125 OffersMessage::InvoiceRequest(message) => message.write(w),
126 OffersMessage::Invoice(message) => message.write(w),
127 OffersMessage::InvoiceError(message) => message.write(w),
132 impl<L: Logger + ?Sized> ReadableArgs<(u64, &L)> for OffersMessage {
133 fn read<R: Read>(r: &mut R, read_args: (u64, &L)) -> Result<Self, DecodeError> {
134 let (tlv_type, logger) = read_args;
135 if tlv_type == INVOICE_ERROR_TLV_TYPE {
136 return Ok(Self::InvoiceError(InvoiceError::read(r)?));
139 let mut bytes = Vec::new();
140 r.read_to_end(&mut bytes).unwrap();
142 match Self::parse(tlv_type, bytes) {
143 Ok(message) => Ok(message),
144 Err(Bolt12ParseError::Decode(e)) => Err(e),
145 Err(Bolt12ParseError::InvalidSemantics(e)) => {
146 log_trace!(logger, "Invalid semantics for TLV type {}: {:?}", tlv_type, e);
147 Err(DecodeError::InvalidValue)
149 Err(Bolt12ParseError::InvalidSignature(e)) => {
150 log_trace!(logger, "Invalid signature for TLV type {}: {:?}", tlv_type, e);
151 Err(DecodeError::InvalidValue)
153 Err(_) => Err(DecodeError::InvalidValue),