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::str::FromStr;
25 use core::time::Duration;
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;
37 use crate::prelude::*;
39 #[cfg(feature = "std")]
40 use std::time::SystemTime;
42 /// A `Refund` is a request to send an `Invoice` without a preceding [`Offer`].
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
48 /// [`Offer`]: crate::offers::offer::Offer
49 #[derive(Clone, Debug)]
52 contents: RefundContents,
55 /// The contents of a [`Refund`], which may be shared with an `Invoice`.
56 #[derive(Clone, Debug)]
57 struct RefundContents {
60 metadata: Option<Vec<u8>>,
62 absolute_expiry: Option<Duration>,
63 issuer: Option<String>,
64 paths: Option<Vec<BlindedPath>>,
65 // invoice_request fields
66 chain: Option<ChainHash>,
68 features: InvoiceRequestFeatures,
70 payer_note: Option<String>,
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)
80 /// Duration since the Unix epoch when an invoice should no longer be sent.
82 /// If `None`, the refund does not expire.
83 pub fn absolute_expiry(&self) -> Option<Duration> {
84 self.contents.absolute_expiry
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,
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()))
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(&[])
111 /// An unpredictable series of bytes, typically containing information about the derivation of
114 /// [`payer_id`]: Self::payer_id
115 pub fn metadata(&self) -> &[u8] {
116 &self.contents.payer.0
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))
124 /// The amount to refund in msats (i.e., the minimum lightning-payable unit for [`chain`]).
126 /// [`chain`]: Self::chain
127 pub fn amount_msats(&self) -> u64 {
128 self.contents.amount_msats
131 /// Features pertaining to requesting an invoice.
132 pub fn features(&self) -> &InvoiceRequestFeatures {
133 &self.contents.features
136 /// A possibly transient pubkey used to sign the refund.
137 pub fn payer_id(&self) -> PublicKey {
138 self.contents.payer_id
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()))
147 impl AsRef<[u8]> for Refund {
148 fn as_ref(&self) -> &[u8] {
153 impl Writeable for Refund {
154 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
155 WithoutLength(&self.bytes).write(writer)
159 type RefundTlvStream = (PayerTlvStream, OfferTlvStream, InvoiceRequestTlvStream);
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)?;
167 Ok((payer, offer, invoice_request))
171 impl Bech32Encode for Refund {
172 const BECH32_HRP: &'static str = "lnr";
175 impl FromStr for Refund {
176 type Err = ParseError;
178 fn from_str(s: &str) -> Result<Self, <Self as FromStr>::Err> {
179 Refund::from_bech32_str(s)
183 impl TryFrom<Vec<u8>> for Refund {
184 type Error = ParseError;
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)?;
191 Ok(Refund { bytes, contents })
195 impl TryFrom<RefundTlvStream> for RefundContents {
196 type Error = SemanticError;
198 fn try_from(tlv_stream: RefundTlvStream) -> Result<Self, Self::Error> {
200 PayerTlvStream { metadata: payer_metadata },
202 chains, metadata, currency, amount: offer_amount, description,
203 features: offer_features, absolute_expiry, paths, issuer, quantity_max, node_id,
205 InvoiceRequestTlvStream { chain, amount, features, quantity, payer_id, payer_note },
208 let payer = match payer_metadata {
209 None => return Err(SemanticError::MissingPayerMetadata),
210 Some(metadata) => PayerContents(metadata),
213 if chains.is_some() {
214 return Err(SemanticError::UnexpectedChain);
217 if currency.is_some() || offer_amount.is_some() {
218 return Err(SemanticError::UnexpectedAmount);
221 let description = match description {
222 None => return Err(SemanticError::MissingDescription),
223 Some(description) => description,
226 if offer_features.is_some() {
227 return Err(SemanticError::UnexpectedFeatures);
230 let absolute_expiry = absolute_expiry.map(Duration::from_secs);
232 if quantity_max.is_some() {
233 return Err(SemanticError::UnexpectedQuantity);
236 if node_id.is_some() {
237 return Err(SemanticError::UnexpectedSigningPubkey);
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);
245 Some(amount_msats) => amount_msats,
248 let features = features.unwrap_or_else(InvoiceRequestFeatures::empty);
250 // TODO: Check why this isn't in the spec.
251 if quantity.is_some() {
252 return Err(SemanticError::UnexpectedQuantity);
255 let payer_id = match payer_id {
256 None => return Err(SemanticError::MissingPayerId),
257 Some(payer_id) => payer_id,
260 // TODO: Should metadata be included?
262 payer, metadata, description, absolute_expiry, issuer, paths, chain, amount_msats,
263 features, payer_id, payer_note,
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)