Expose `onion_message` items directly rather than via re-exports
[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::convert::TryFrom;
13 use core::fmt;
14 use crate::io::{self, Read};
15 use crate::ln::msgs::DecodeError;
16 use crate::offers::invoice_error::InvoiceError;
17 use crate::offers::invoice_request::InvoiceRequest;
18 use crate::offers::invoice::Bolt12Invoice;
19 use crate::offers::parse::Bolt12ParseError;
20 use crate::onion_message::packet::OnionMessageContents;
21 use crate::util::logger::Logger;
22 use crate::util::ser::{Readable, ReadableArgs, Writeable, Writer};
23 #[cfg(not(c_bindings))]
24 use crate::onion_message::messenger::PendingOnionMessage;
25
26 use crate::prelude::*;
27
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;
32
33 /// A handler for an [`OnionMessage`] containing a BOLT 12 Offers message as its payload.
34 ///
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.
39         ///
40         /// The returned [`OffersMessage`], if any, is enqueued to be sent by [`OnionMessenger`].
41         ///
42         /// [`OnionMessenger`]: crate::onion_message::messenger::OnionMessenger
43         fn handle_message(&self, message: OffersMessage) -> Option<OffersMessage>;
44
45         /// Releases any [`OffersMessage`]s that need to be sent.
46         ///
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![] }
51
52         /// Releases any [`OffersMessage`]s that need to be sent.
53         ///
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`].
56         #[cfg(c_bindings)]
57         fn release_pending_messages(&self) -> Vec<(OffersMessage, crate::onion_message::messenger::Destination, Option<crate::blinded_path::BlindedPath>)> { vec![] }
58 }
59
60 /// Possible BOLT 12 Offers messages sent and received via an [`OnionMessage`].
61 ///
62 /// [`OnionMessage`]: crate::ln::msgs::OnionMessage
63 #[derive(Clone)]
64 pub enum OffersMessage {
65         /// A request for a [`Bolt12Invoice`] for a particular [`Offer`].
66         ///
67         /// [`Offer`]: crate::offers::offer::Offer
68         InvoiceRequest(InvoiceRequest),
69
70         /// A [`Bolt12Invoice`] sent in response to an [`InvoiceRequest`] or a [`Refund`].
71         ///
72         /// [`Refund`]: crate::offers::refund::Refund
73         Invoice(Bolt12Invoice),
74
75         /// An error from handling an [`OffersMessage`].
76         InvoiceError(InvoiceError),
77 }
78
79 impl OffersMessage {
80         /// Returns whether `tlv_type` corresponds to a TLV record for Offers.
81         pub fn is_known_type(tlv_type: u64) -> bool {
82                 match tlv_type {
83                         INVOICE_REQUEST_TLV_TYPE | INVOICE_TLV_TYPE | INVOICE_ERROR_TLV_TYPE => true,
84                         _ => false,
85                 }
86         }
87
88         fn parse(tlv_type: u64, bytes: Vec<u8>) -> Result<Self, Bolt12ParseError> {
89                 match tlv_type {
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)),
93                 }
94         }
95 }
96
97 impl fmt::Debug for OffersMessage {
98         fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
99                 match self {
100                         OffersMessage::InvoiceRequest(message) => {
101                                 write!(f, "{:?}", message.as_tlv_stream())
102                         }
103                         OffersMessage::Invoice(message) => {
104                                 write!(f, "{:?}", message.as_tlv_stream())
105                         }
106                         OffersMessage::InvoiceError(message) => {
107                                 write!(f, "{:?}", message)
108                         }
109                 }
110         }
111 }
112
113 impl OnionMessageContents for OffersMessage {
114         fn tlv_type(&self) -> u64 {
115                 match self {
116                         OffersMessage::InvoiceRequest(_) => INVOICE_REQUEST_TLV_TYPE,
117                         OffersMessage::Invoice(_) => INVOICE_TLV_TYPE,
118                         OffersMessage::InvoiceError(_) => INVOICE_ERROR_TLV_TYPE,
119                 }
120         }
121 }
122
123 impl Writeable for OffersMessage {
124         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
125                 match self {
126                         OffersMessage::InvoiceRequest(message) => message.write(w),
127                         OffersMessage::Invoice(message) => message.write(w),
128                         OffersMessage::InvoiceError(message) => message.write(w),
129                 }
130         }
131 }
132
133 impl<L: Logger + ?Sized> ReadableArgs<(u64, &L)> for OffersMessage {
134         fn read<R: Read>(r: &mut R, read_args: (u64, &L)) -> Result<Self, DecodeError> {
135                 let (tlv_type, logger) = read_args;
136                 if tlv_type == INVOICE_ERROR_TLV_TYPE {
137                         return Ok(Self::InvoiceError(InvoiceError::read(r)?));
138                 }
139
140                 let mut bytes = Vec::new();
141                 r.read_to_end(&mut bytes).unwrap();
142
143                 match Self::parse(tlv_type, bytes) {
144                         Ok(message) => Ok(message),
145                         Err(Bolt12ParseError::Decode(e)) => Err(e),
146                         Err(Bolt12ParseError::InvalidSemantics(e)) => {
147                                 log_trace!(logger, "Invalid semantics for TLV type {}: {:?}", tlv_type, e);
148                                 Err(DecodeError::InvalidValue)
149                         },
150                         Err(Bolt12ParseError::InvalidSignature(e)) => {
151                                 log_trace!(logger, "Invalid signature for TLV type {}: {:?}", tlv_type, e);
152                                 Err(DecodeError::InvalidValue)
153                         },
154                         Err(_) => Err(DecodeError::InvalidValue),
155                 }
156         }
157 }