Refund parsing from bech32 strings
[rust-lightning] / lightning / src / offers / refund.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 //! Data structures and encoding for refunds.
11 //!
12 //! A [`Refund`] is an "offer for money" and is typically constructed by a merchant and presented
13 //! directly to the customer. The recipient responds with an `Invoice` to be paid.
14 //!
15 //! This is an [`InvoiceRequest`] produced *not* in response to an [`Offer`].
16 //!
17 //! [`InvoiceRequest`]: crate::offers::invoice_request::InvoiceRequest
18 //! [`Offer`]: crate::offers::offer::Offer
19
20 use bitcoin::blockdata::constants::ChainHash;
21 use bitcoin::network::constants::Network;
22 use bitcoin::secp256k1::PublicKey;
23 use core::convert::TryFrom;
24 use core::str::FromStr;
25 use core::time::Duration;
26 use crate::io;
27 use crate::ln::features::InvoiceRequestFeatures;
28 use crate::ln::msgs::{DecodeError, MAX_VALUE_MSAT};
29 use crate::offers::invoice_request::InvoiceRequestTlvStream;
30 use crate::offers::offer::OfferTlvStream;
31 use crate::offers::parse::{Bech32Encode, ParseError, ParsedMessage, SemanticError};
32 use crate::offers::payer::{PayerContents, PayerTlvStream};
33 use crate::onion_message::BlindedPath;
34 use crate::util::ser::{SeekReadable, WithoutLength, Writeable, Writer};
35 use crate::util::string::PrintableString;
36
37 use crate::prelude::*;
38
39 #[cfg(feature = "std")]
40 use std::time::SystemTime;
41
42 /// A `Refund` is a request to send an `Invoice` without a preceding [`Offer`].
43 ///
44 /// Typically, after an invoice is paid, the recipient may publish a refund allowing the sender to
45 /// recoup their funds. A refund may be used more generally as an "offer for money", such as with a
46 /// bitcoin ATM.
47 ///
48 /// [`Offer`]: crate::offers::offer::Offer
49 #[derive(Clone, Debug)]
50 pub struct Refund {
51         bytes: Vec<u8>,
52         contents: RefundContents,
53 }
54
55 /// The contents of a [`Refund`], which may be shared with an `Invoice`.
56 #[derive(Clone, Debug)]
57 struct RefundContents {
58         payer: PayerContents,
59         // offer fields
60         metadata: Option<Vec<u8>>,
61         description: String,
62         absolute_expiry: Option<Duration>,
63         issuer: Option<String>,
64         paths: Option<Vec<BlindedPath>>,
65         // invoice_request fields
66         chain: Option<ChainHash>,
67         amount_msats: u64,
68         features: InvoiceRequestFeatures,
69         payer_id: PublicKey,
70         payer_note: Option<String>,
71 }
72
73 impl Refund {
74         /// A complete description of the purpose of the refund. Intended to be displayed to the user
75         /// but with the caveat that it has not been verified in any way.
76         pub fn description(&self) -> PrintableString {
77                 PrintableString(&self.contents.description)
78         }
79
80         /// Duration since the Unix epoch when an invoice should no longer be sent.
81         ///
82         /// If `None`, the refund does not expire.
83         pub fn absolute_expiry(&self) -> Option<Duration> {
84                 self.contents.absolute_expiry
85         }
86
87         /// Whether the refund has expired.
88         #[cfg(feature = "std")]
89         pub fn is_expired(&self) -> bool {
90                 match self.absolute_expiry() {
91                         Some(seconds_from_epoch) => match SystemTime::UNIX_EPOCH.elapsed() {
92                                 Ok(elapsed) => elapsed > seconds_from_epoch,
93                                 Err(_) => false,
94                         },
95                         None => false,
96                 }
97         }
98
99         /// The issuer of the refund, possibly beginning with `user@domain` or `domain`. Intended to be
100         /// displayed to the user but with the caveat that it has not been verified in any way.
101         pub fn issuer(&self) -> Option<PrintableString> {
102                 self.contents.issuer.as_ref().map(|issuer| PrintableString(issuer.as_str()))
103         }
104
105         /// Paths to the sender originating from publicly reachable nodes. Blinded paths provide sender
106         /// privacy by obfuscating its node id.
107         pub fn paths(&self) -> &[BlindedPath] {
108                 self.contents.paths.as_ref().map(|paths| paths.as_slice()).unwrap_or(&[])
109         }
110
111         /// An unpredictable series of bytes, typically containing information about the derivation of
112         /// [`payer_id`].
113         ///
114         /// [`payer_id`]: Self::payer_id
115         pub fn metadata(&self) -> &[u8] {
116                 &self.contents.payer.0
117         }
118
119         /// A chain that the refund is valid for.
120         pub fn chain(&self) -> ChainHash {
121                 self.contents.chain.unwrap_or_else(|| ChainHash::using_genesis_block(Network::Bitcoin))
122         }
123
124         /// The amount to refund in msats (i.e., the minimum lightning-payable unit for [`chain`]).
125         ///
126         /// [`chain`]: Self::chain
127         pub fn amount_msats(&self) -> u64 {
128                 self.contents.amount_msats
129         }
130
131         /// Features pertaining to requesting an invoice.
132         pub fn features(&self) -> &InvoiceRequestFeatures {
133                 &self.contents.features
134         }
135
136         /// A possibly transient pubkey used to sign the refund.
137         pub fn payer_id(&self) -> PublicKey {
138                 self.contents.payer_id
139         }
140
141         /// Payer provided note to include in the invoice.
142         pub fn payer_note(&self) -> Option<PrintableString> {
143                 self.contents.payer_note.as_ref().map(|payer_note| PrintableString(payer_note.as_str()))
144         }
145 }
146
147 impl AsRef<[u8]> for Refund {
148         fn as_ref(&self) -> &[u8] {
149                 &self.bytes
150         }
151 }
152
153 impl Writeable for Refund {
154         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
155                 WithoutLength(&self.bytes).write(writer)
156         }
157 }
158
159 type RefundTlvStream = (PayerTlvStream, OfferTlvStream, InvoiceRequestTlvStream);
160
161 impl SeekReadable for RefundTlvStream {
162         fn read<R: io::Read + io::Seek>(r: &mut R) -> Result<Self, DecodeError> {
163                 let payer = SeekReadable::read(r)?;
164                 let offer = SeekReadable::read(r)?;
165                 let invoice_request = SeekReadable::read(r)?;
166
167                 Ok((payer, offer, invoice_request))
168         }
169 }
170
171 impl Bech32Encode for Refund {
172         const BECH32_HRP: &'static str = "lnr";
173 }
174
175 impl FromStr for Refund {
176         type Err = ParseError;
177
178         fn from_str(s: &str) -> Result<Self, <Self as FromStr>::Err> {
179                 Refund::from_bech32_str(s)
180         }
181 }
182
183 impl TryFrom<Vec<u8>> for Refund {
184         type Error = ParseError;
185
186         fn try_from(bytes: Vec<u8>) -> Result<Self, Self::Error> {
187                 let refund = ParsedMessage::<RefundTlvStream>::try_from(bytes)?;
188                 let ParsedMessage { bytes, tlv_stream } = refund;
189                 let contents = RefundContents::try_from(tlv_stream)?;
190
191                 Ok(Refund { bytes, contents })
192         }
193 }
194
195 impl TryFrom<RefundTlvStream> for RefundContents {
196         type Error = SemanticError;
197
198         fn try_from(tlv_stream: RefundTlvStream) -> Result<Self, Self::Error> {
199                 let (
200                         PayerTlvStream { metadata: payer_metadata },
201                         OfferTlvStream {
202                                 chains, metadata, currency, amount: offer_amount, description,
203                                 features: offer_features, absolute_expiry, paths, issuer, quantity_max, node_id,
204                         },
205                         InvoiceRequestTlvStream { chain, amount, features, quantity, payer_id, payer_note },
206                 ) = tlv_stream;
207
208                 let payer = match payer_metadata {
209                         None => return Err(SemanticError::MissingPayerMetadata),
210                         Some(metadata) => PayerContents(metadata),
211                 };
212
213                 if chains.is_some() {
214                         return Err(SemanticError::UnexpectedChain);
215                 }
216
217                 if currency.is_some() || offer_amount.is_some() {
218                         return Err(SemanticError::UnexpectedAmount);
219                 }
220
221                 let description = match description {
222                         None => return Err(SemanticError::MissingDescription),
223                         Some(description) => description,
224                 };
225
226                 if offer_features.is_some() {
227                         return Err(SemanticError::UnexpectedFeatures);
228                 }
229
230                 let absolute_expiry = absolute_expiry.map(Duration::from_secs);
231
232                 if quantity_max.is_some() {
233                         return Err(SemanticError::UnexpectedQuantity);
234                 }
235
236                 if node_id.is_some() {
237                         return Err(SemanticError::UnexpectedSigningPubkey);
238                 }
239
240                 let amount_msats = match amount {
241                         None => return Err(SemanticError::MissingAmount),
242                         Some(amount_msats) if amount_msats > MAX_VALUE_MSAT => {
243                                 return Err(SemanticError::InvalidAmount);
244                         },
245                         Some(amount_msats) => amount_msats,
246                 };
247
248                 let features = features.unwrap_or_else(InvoiceRequestFeatures::empty);
249
250                 // TODO: Check why this isn't in the spec.
251                 if quantity.is_some() {
252                         return Err(SemanticError::UnexpectedQuantity);
253                 }
254
255                 let payer_id = match payer_id {
256                         None => return Err(SemanticError::MissingPayerId),
257                         Some(payer_id) => payer_id,
258                 };
259
260                 // TODO: Should metadata be included?
261                 Ok(RefundContents {
262                         payer, metadata, description, absolute_expiry, issuer, paths, chain, amount_msats,
263                         features, payer_id, payer_note,
264                 })
265         }
266 }
267
268 impl core::fmt::Display for Refund {
269         fn fmt(&self, f: &mut core::fmt::Formatter) -> Result<(), core::fmt::Error> {
270                 self.fmt_bech32_str(f)
271         }
272 }