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