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