397f4b8a72b7a827b8bb0543f78a076cd9eb2210
[rust-lightning] / lightning / src / 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
12 use core::fmt;
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;
27
28 use crate::prelude::*;
29
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;
36
37 /// A handler for an [`OnionMessage`] containing a BOLT 12 Offers message as its payload.
38 ///
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.
43         ///
44         /// The returned [`OffersMessage`], if any, is enqueued to be sent by [`OnionMessenger`].
45         ///
46         /// [`OnionMessenger`]: crate::onion_message::messenger::OnionMessenger
47         fn handle_message(&self, message: OffersMessage, responder: Option<Responder>) -> ResponseInstruction<OffersMessage>;
48
49         /// Releases any [`OffersMessage`]s that need to be sent.
50         ///
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![] }
55
56         /// Releases any [`OffersMessage`]s that need to be sent.
57         ///
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`].
60         #[cfg(c_bindings)]
61         fn release_pending_messages(&self) -> Vec<(OffersMessage, crate::onion_message::messenger::Destination, Option<crate::blinded_path::BlindedPath>)> { vec![] }
62 }
63
64 /// Possible BOLT 12 Offers messages sent and received via an [`OnionMessage`].
65 ///
66 /// [`OnionMessage`]: crate::ln::msgs::OnionMessage
67 #[derive(Clone)]
68 pub enum OffersMessage {
69         /// A request for a [`Bolt12Invoice`] for a particular [`Offer`].
70         ///
71         /// [`Offer`]: crate::offers::offer::Offer
72         InvoiceRequest(InvoiceRequest),
73
74         /// A [`Bolt12Invoice`] sent in response to an [`InvoiceRequest`] or a [`Refund`].
75         ///
76         /// [`Refund`]: crate::offers::refund::Refund
77         Invoice(Bolt12Invoice),
78
79         #[cfg(async_payments)]
80         /// A [`StaticInvoice`] sent in response to an [`InvoiceRequest`].
81         StaticInvoice(StaticInvoice),
82
83         /// An error from handling an [`OffersMessage`].
84         InvoiceError(InvoiceError),
85 }
86
87 impl OffersMessage {
88         /// Returns whether `tlv_type` corresponds to a TLV record for Offers.
89         pub fn is_known_type(tlv_type: u64) -> bool {
90                 match tlv_type {
91                         INVOICE_REQUEST_TLV_TYPE
92                         | INVOICE_TLV_TYPE
93                         | INVOICE_ERROR_TLV_TYPE => true,
94                         #[cfg(async_payments)]
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                         #[cfg(async_payments)]
105                         STATIC_INVOICE_TLV_TYPE => Ok(Self::StaticInvoice(StaticInvoice::try_from(bytes)?)),
106                         _ => Err(Bolt12ParseError::Decode(DecodeError::InvalidValue)),
107                 }
108         }
109 }
110
111 impl fmt::Debug for OffersMessage {
112         fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
113                 match self {
114                         OffersMessage::InvoiceRequest(message) => {
115                                 write!(f, "{:?}", message.as_tlv_stream())
116                         }
117                         OffersMessage::Invoice(message) => {
118                                 write!(f, "{:?}", message.as_tlv_stream())
119                         }
120                         #[cfg(async_payments)]
121                         OffersMessage::StaticInvoice(message) => {
122                                 write!(f, "{:?}", message)
123                         }
124                         OffersMessage::InvoiceError(message) => {
125                                 write!(f, "{:?}", message)
126                         }
127                 }
128         }
129 }
130
131 impl OnionMessageContents for OffersMessage {
132         fn tlv_type(&self) -> u64 {
133                 match self {
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,
139                 }
140         }
141         fn msg_type(&self) -> &'static str {
142                 match &self {
143                         OffersMessage::InvoiceRequest(_) => "Invoice Request",
144                         OffersMessage::Invoice(_) => "Invoice",
145                         #[cfg(async_payments)]
146                         OffersMessage::StaticInvoice(_) => "Static Invoice",
147                         OffersMessage::InvoiceError(_) => "Invoice Error",
148                 }
149         }
150 }
151
152 impl Writeable for OffersMessage {
153         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
154                 match self {
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),
160                 }
161         }
162 }
163
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)?));
169                 }
170
171                 let mut bytes = Vec::new();
172                 r.read_to_end(&mut bytes).unwrap();
173
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)
180                         },
181                         Err(Bolt12ParseError::InvalidSignature(e)) => {
182                                 log_trace!(logger, "Invalid signature for TLV type {}: {:?}", tlv_type, e);
183                                 Err(DecodeError::InvalidValue)
184                         },
185                         Err(_) => Err(DecodeError::InvalidValue),
186                 }
187         }
188 }