1 // This file is Copyright its original authors, visible in version control
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
10 //! Data structures and encoding for refunds.
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.
15 //! This is an [`InvoiceRequest`] produced *not* in response to an [`Offer`].
17 //! [`InvoiceRequest`]: crate::offers::invoice_request::InvoiceRequest
18 //! [`Offer`]: crate::offers::offer::Offer
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;
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;
36 use crate::prelude::*;
38 #[cfg(feature = "std")]
39 use std::time::SystemTime;
41 /// A `Refund` is a request to send an `Invoice` without a preceding [`Offer`].
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
47 /// [`Offer`]: crate::offers::offer::Offer
48 #[derive(Clone, Debug)]
51 contents: RefundContents,
54 /// The contents of a [`Refund`], which may be shared with an `Invoice`.
55 #[derive(Clone, Debug)]
56 struct RefundContents {
59 metadata: Option<Vec<u8>>,
61 absolute_expiry: Option<Duration>,
62 issuer: Option<String>,
63 paths: Option<Vec<BlindedPath>>,
64 // invoice_request fields
65 chain: Option<ChainHash>,
67 features: InvoiceRequestFeatures,
69 payer_note: Option<String>,
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)
79 /// Duration since the Unix epoch when an invoice should no longer be sent.
81 /// If `None`, the refund does not expire.
82 pub fn absolute_expiry(&self) -> Option<Duration> {
83 self.contents.absolute_expiry
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,
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()))
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(&[])
110 /// An unpredictable series of bytes, typically containing information about the derivation of
113 /// [`payer_id`]: Self::payer_id
114 pub fn metadata(&self) -> &[u8] {
115 &self.contents.payer.0
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))
123 /// The amount to refund in msats (i.e., the minimum lightning-payable unit for [`chain`]).
125 /// [`chain`]: Self::chain
126 pub fn amount_msats(&self) -> u64 {
127 self.contents.amount_msats
130 /// Features pertaining to requesting an invoice.
131 pub fn features(&self) -> &InvoiceRequestFeatures {
132 &self.contents.features
135 /// A possibly transient pubkey used to sign the refund.
136 pub fn payer_id(&self) -> PublicKey {
137 self.contents.payer_id
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()))
146 type RefundTlvStream = (PayerTlvStream, OfferTlvStream, InvoiceRequestTlvStream);
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)?;
154 Ok((payer, offer, invoice_request))
158 impl TryFrom<Vec<u8>> for Refund {
159 type Error = ParseError;
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)?;
166 Ok(Refund { bytes, contents })
170 impl TryFrom<RefundTlvStream> for RefundContents {
171 type Error = SemanticError;
173 fn try_from(tlv_stream: RefundTlvStream) -> Result<Self, Self::Error> {
175 PayerTlvStream { metadata: payer_metadata },
177 chains, metadata, currency, amount: offer_amount, description,
178 features: offer_features, absolute_expiry, paths, issuer, quantity_max, node_id,
180 InvoiceRequestTlvStream { chain, amount, features, quantity, payer_id, payer_note },
183 let payer = match payer_metadata {
184 None => return Err(SemanticError::MissingPayerMetadata),
185 Some(metadata) => PayerContents(metadata),
188 if chains.is_some() {
189 return Err(SemanticError::UnexpectedChain);
192 if currency.is_some() || offer_amount.is_some() {
193 return Err(SemanticError::UnexpectedAmount);
196 let description = match description {
197 None => return Err(SemanticError::MissingDescription),
198 Some(description) => description,
201 if offer_features.is_some() {
202 return Err(SemanticError::UnexpectedFeatures);
205 let absolute_expiry = absolute_expiry.map(Duration::from_secs);
207 if quantity_max.is_some() {
208 return Err(SemanticError::UnexpectedQuantity);
211 if node_id.is_some() {
212 return Err(SemanticError::UnexpectedSigningPubkey);
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);
220 Some(amount_msats) => amount_msats,
223 let features = features.unwrap_or_else(InvoiceRequestFeatures::empty);
225 // TODO: Check why this isn't in the spec.
226 if quantity.is_some() {
227 return Err(SemanticError::UnexpectedQuantity);
230 let payer_id = match payer_id {
231 None => return Err(SemanticError::MissingPayerId),
232 Some(payer_id) => payer_id,
235 // TODO: Should metadata be included?
237 payer, metadata, description, absolute_expiry, issuer, paths, chain, amount_msats,
238 features, payer_id, payer_note,