]> git.bitcoin.ninja Git - rust-lightning/blob - lightning/src/onion_message/offers.rs
Include OfferId in VerifiedInvoiceRequest
[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::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;
24
25 use crate::prelude::*;
26
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;
31
32 /// A handler for an [`OnionMessage`] containing a BOLT 12 Offers message as its payload.
33 ///
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.
38         ///
39         /// The returned [`OffersMessage`], if any, is enqueued to be sent by [`OnionMessenger`].
40         ///
41         /// [`OnionMessenger`]: crate::onion_message::messenger::OnionMessenger
42         fn handle_message(&self, message: OffersMessage) -> Option<OffersMessage>;
43
44         /// Releases any [`OffersMessage`]s that need to be sent.
45         ///
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![] }
50
51         /// Releases any [`OffersMessage`]s that need to be sent.
52         ///
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`].
55         #[cfg(c_bindings)]
56         fn release_pending_messages(&self) -> Vec<(OffersMessage, crate::onion_message::messenger::Destination, Option<crate::blinded_path::BlindedPath>)> { vec![] }
57 }
58
59 /// Possible BOLT 12 Offers messages sent and received via an [`OnionMessage`].
60 ///
61 /// [`OnionMessage`]: crate::ln::msgs::OnionMessage
62 #[derive(Clone)]
63 pub enum OffersMessage {
64         /// A request for a [`Bolt12Invoice`] for a particular [`Offer`].
65         ///
66         /// [`Offer`]: crate::offers::offer::Offer
67         InvoiceRequest(InvoiceRequest),
68
69         /// A [`Bolt12Invoice`] sent in response to an [`InvoiceRequest`] or a [`Refund`].
70         ///
71         /// [`Refund`]: crate::offers::refund::Refund
72         Invoice(Bolt12Invoice),
73
74         /// An error from handling an [`OffersMessage`].
75         InvoiceError(InvoiceError),
76 }
77
78 impl OffersMessage {
79         /// Returns whether `tlv_type` corresponds to a TLV record for Offers.
80         pub fn is_known_type(tlv_type: u64) -> bool {
81                 match tlv_type {
82                         INVOICE_REQUEST_TLV_TYPE | INVOICE_TLV_TYPE | INVOICE_ERROR_TLV_TYPE => true,
83                         _ => false,
84                 }
85         }
86
87         fn parse(tlv_type: u64, bytes: Vec<u8>) -> Result<Self, Bolt12ParseError> {
88                 match tlv_type {
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)),
92                 }
93         }
94 }
95
96 impl fmt::Debug for OffersMessage {
97         fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
98                 match self {
99                         OffersMessage::InvoiceRequest(message) => {
100                                 write!(f, "{:?}", message.as_tlv_stream())
101                         }
102                         OffersMessage::Invoice(message) => {
103                                 write!(f, "{:?}", message.as_tlv_stream())
104                         }
105                         OffersMessage::InvoiceError(message) => {
106                                 write!(f, "{:?}", message)
107                         }
108                 }
109         }
110 }
111
112 impl OnionMessageContents for OffersMessage {
113         fn tlv_type(&self) -> u64 {
114                 match self {
115                         OffersMessage::InvoiceRequest(_) => INVOICE_REQUEST_TLV_TYPE,
116                         OffersMessage::Invoice(_) => INVOICE_TLV_TYPE,
117                         OffersMessage::InvoiceError(_) => INVOICE_ERROR_TLV_TYPE,
118                 }
119         }
120 }
121
122 impl Writeable for OffersMessage {
123         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
124                 match self {
125                         OffersMessage::InvoiceRequest(message) => message.write(w),
126                         OffersMessage::Invoice(message) => message.write(w),
127                         OffersMessage::InvoiceError(message) => message.write(w),
128                 }
129         }
130 }
131
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)?));
137                 }
138
139                 let mut bytes = Vec::new();
140                 r.read_to_end(&mut bytes).unwrap();
141
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)
148                         },
149                         Err(Bolt12ParseError::InvalidSignature(e)) => {
150                                 log_trace!(logger, "Invalid signature for TLV type {}: {:?}", tlv_type, e);
151                                 Err(DecodeError::InvalidValue)
152                         },
153                         Err(_) => Err(DecodeError::InvalidValue),
154                 }
155         }
156 }