]> git.bitcoin.ninja Git - rust-lightning/commitdiff
Refund encoding and parsing
authorJeffrey Czyz <jkczyz@gmail.com>
Wed, 21 Sep 2022 14:32:23 +0000 (09:32 -0500)
committerJeffrey Czyz <jkczyz@gmail.com>
Wed, 14 Dec 2022 22:20:40 +0000 (16:20 -0600)
Define an interface for BOLT 12 refunds (i.e., an `invoice_request`
message without an `offer_node_id`). A refund is more generally an
"offer for money". While it is encoded using the same TLV streams as an
`invoice_request` message, it has different semantics.

lightning/src/offers/invoice_request.rs
lightning/src/offers/mod.rs
lightning/src/offers/parse.rs
lightning/src/offers/refund.rs [new file with mode: 0644]

index 69dc616eb0f3b90ff6ac73009876d0356d494c11..e3fe112112eb151e5964fec8bad81c5dd0c9f8fa 100644 (file)
@@ -9,13 +9,14 @@
 
 //! Data structures and encoding for `invoice_request` messages.
 //!
-//! An [`InvoiceRequest`] can be either built from a parsed [`Offer`] as an "offer to be paid" or
-//! built directly as an "offer for money" (e.g., refund, ATM withdrawal). In the former case, it is
+//! An [`InvoiceRequest`] can be built from a parsed [`Offer`] as an "offer to be paid". It is
 //! typically constructed by a customer and sent to the merchant who had published the corresponding
-//! offer. In the latter case, an offer doesn't exist as a precursor to the request. Rather the
-//! merchant would typically construct the invoice request and present it to the customer.
+//! offer. The recipient of the request responds with an `Invoice`.
 //!
-//! The recipient of the request responds with an `Invoice`.
+//! For an "offer for money" (e.g., refund, ATM withdrawal), where an offer doesn't exist as a
+//! precursor, see [`Refund`].
+//!
+//! [`Refund`]: crate::offers::refund::Refund
 //!
 //! ```ignore
 //! extern crate bitcoin;
@@ -34,7 +35,6 @@
 //! let pubkey = PublicKey::from(keys);
 //! let mut buffer = Vec::new();
 //!
-//! // "offer to be paid" flow
 //! "lno1qcp4256ypq"
 //!     .parse::<Offer>()?
 //!     .request_invoice(vec![42; 64], pubkey)?
@@ -287,7 +287,7 @@ impl InvoiceRequest {
                self.contents.amount_msats
        }
 
-       /// Features for paying the invoice.
+       /// Features pertaining to requesting an invoice.
        pub fn features(&self) -> &InvoiceRequestFeatures {
                &self.contents.features
        }
index be0eb2da522c3f260bec2db2b370ed6a3bf2711c..11df5ca1f8a108457fe1df9864ec8c0a916fdbe8 100644 (file)
@@ -17,3 +17,4 @@ mod merkle;
 pub mod offer;
 pub mod parse;
 mod payer;
+pub mod refund;
index 0b3dda7928593871f8007c5ff50d2d081366dac8..b462e686910a2ed9d26f44c74c75cec3f00b5187 100644 (file)
@@ -127,20 +127,28 @@ pub enum SemanticError {
        AlreadyExpired,
        /// The provided chain hash does not correspond to a supported chain.
        UnsupportedChain,
+       /// A chain was provided but was not expected.
+       UnexpectedChain,
        /// An amount was expected but was missing.
        MissingAmount,
        /// The amount exceeded the total bitcoin supply.
        InvalidAmount,
        /// An amount was provided but was not sufficient in value.
        InsufficientAmount,
+       /// An amount was provided but was not expected.
+       UnexpectedAmount,
        /// A currency was provided that is not supported.
        UnsupportedCurrency,
        /// A feature was required but is unknown.
        UnknownRequiredFeatures,
+       /// Features were provided but were not expected.
+       UnexpectedFeatures,
        /// A required description was not provided.
        MissingDescription,
        /// A signing pubkey was not provided.
        MissingSigningPubkey,
+       /// A signing pubkey was provided but was not expected.
+       UnexpectedSigningPubkey,
        /// A quantity was expected but was missing.
        MissingQuantity,
        /// An unsupported quantity was provided.
diff --git a/lightning/src/offers/refund.rs b/lightning/src/offers/refund.rs
new file mode 100644 (file)
index 0000000..0a6c7e2
--- /dev/null
@@ -0,0 +1,241 @@
+// This file is Copyright its original authors, visible in version control
+// history.
+//
+// This file is licensed under the Apache License, Version 2.0 <LICENSE-APACHE
+// or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option.
+// You may not use this file except in accordance with one or both of these
+// licenses.
+
+//! Data structures and encoding for refunds.
+//!
+//! A [`Refund`] is an "offer for money" and is typically constructed by a merchant and presented
+//! directly to the customer. The recipient responds with an `Invoice` to be paid.
+//!
+//! This is an [`InvoiceRequest`] produced *not* in response to an [`Offer`].
+//!
+//! [`InvoiceRequest`]: crate::offers::invoice_request::InvoiceRequest
+//! [`Offer`]: crate::offers::offer::Offer
+
+use bitcoin::blockdata::constants::ChainHash;
+use bitcoin::network::constants::Network;
+use bitcoin::secp256k1::PublicKey;
+use core::convert::TryFrom;
+use core::time::Duration;
+use crate::io;
+use crate::ln::features::InvoiceRequestFeatures;
+use crate::ln::msgs::{DecodeError, MAX_VALUE_MSAT};
+use crate::offers::invoice_request::InvoiceRequestTlvStream;
+use crate::offers::offer::OfferTlvStream;
+use crate::offers::parse::{ParseError, ParsedMessage, SemanticError};
+use crate::offers::payer::{PayerContents, PayerTlvStream};
+use crate::onion_message::BlindedPath;
+use crate::util::ser::SeekReadable;
+use crate::util::string::PrintableString;
+
+use crate::prelude::*;
+
+#[cfg(feature = "std")]
+use std::time::SystemTime;
+
+/// A `Refund` is a request to send an `Invoice` without a preceding [`Offer`].
+///
+/// Typically, after an invoice is paid, the recipient may publish a refund allowing the sender to
+/// recoup their funds. A refund may be used more generally as an "offer for money", such as with a
+/// bitcoin ATM.
+///
+/// [`Offer`]: crate::offers::offer::Offer
+#[derive(Clone, Debug)]
+pub struct Refund {
+       bytes: Vec<u8>,
+       contents: RefundContents,
+}
+
+/// The contents of a [`Refund`], which may be shared with an `Invoice`.
+#[derive(Clone, Debug)]
+struct RefundContents {
+       payer: PayerContents,
+       // offer fields
+       metadata: Option<Vec<u8>>,
+       description: String,
+       absolute_expiry: Option<Duration>,
+       issuer: Option<String>,
+       paths: Option<Vec<BlindedPath>>,
+       // invoice_request fields
+       chain: Option<ChainHash>,
+       amount_msats: u64,
+       features: InvoiceRequestFeatures,
+       payer_id: PublicKey,
+       payer_note: Option<String>,
+}
+
+impl Refund {
+       /// A complete description of the purpose of the refund. Intended to be displayed to the user
+       /// but with the caveat that it has not been verified in any way.
+       pub fn description(&self) -> PrintableString {
+               PrintableString(&self.contents.description)
+       }
+
+       /// Duration since the Unix epoch when an invoice should no longer be sent.
+       ///
+       /// If `None`, the refund does not expire.
+       pub fn absolute_expiry(&self) -> Option<Duration> {
+               self.contents.absolute_expiry
+       }
+
+       /// Whether the refund has expired.
+       #[cfg(feature = "std")]
+       pub fn is_expired(&self) -> bool {
+               match self.absolute_expiry() {
+                       Some(seconds_from_epoch) => match SystemTime::UNIX_EPOCH.elapsed() {
+                               Ok(elapsed) => elapsed > seconds_from_epoch,
+                               Err(_) => false,
+                       },
+                       None => false,
+               }
+       }
+
+       /// The issuer of the refund, possibly beginning with `user@domain` or `domain`. Intended to be
+       /// displayed to the user but with the caveat that it has not been verified in any way.
+       pub fn issuer(&self) -> Option<PrintableString> {
+               self.contents.issuer.as_ref().map(|issuer| PrintableString(issuer.as_str()))
+       }
+
+       /// Paths to the sender originating from publicly reachable nodes. Blinded paths provide sender
+       /// privacy by obfuscating its node id.
+       pub fn paths(&self) -> &[BlindedPath] {
+               self.contents.paths.as_ref().map(|paths| paths.as_slice()).unwrap_or(&[])
+       }
+
+       /// An unpredictable series of bytes, typically containing information about the derivation of
+       /// [`payer_id`].
+       ///
+       /// [`payer_id`]: Self::payer_id
+       pub fn metadata(&self) -> &[u8] {
+               &self.contents.payer.0
+       }
+
+       /// A chain that the refund is valid for.
+       pub fn chain(&self) -> ChainHash {
+               self.contents.chain.unwrap_or_else(|| ChainHash::using_genesis_block(Network::Bitcoin))
+       }
+
+       /// The amount to refund in msats (i.e., the minimum lightning-payable unit for [`chain`]).
+       ///
+       /// [`chain`]: Self::chain
+       pub fn amount_msats(&self) -> u64 {
+               self.contents.amount_msats
+       }
+
+       /// Features pertaining to requesting an invoice.
+       pub fn features(&self) -> &InvoiceRequestFeatures {
+               &self.contents.features
+       }
+
+       /// A possibly transient pubkey used to sign the refund.
+       pub fn payer_id(&self) -> PublicKey {
+               self.contents.payer_id
+       }
+
+       /// Payer provided note to include in the invoice.
+       pub fn payer_note(&self) -> Option<PrintableString> {
+               self.contents.payer_note.as_ref().map(|payer_note| PrintableString(payer_note.as_str()))
+       }
+}
+
+type RefundTlvStream = (PayerTlvStream, OfferTlvStream, InvoiceRequestTlvStream);
+
+impl SeekReadable for RefundTlvStream {
+       fn read<R: io::Read + io::Seek>(r: &mut R) -> Result<Self, DecodeError> {
+               let payer = SeekReadable::read(r)?;
+               let offer = SeekReadable::read(r)?;
+               let invoice_request = SeekReadable::read(r)?;
+
+               Ok((payer, offer, invoice_request))
+       }
+}
+
+impl TryFrom<Vec<u8>> for Refund {
+       type Error = ParseError;
+
+       fn try_from(bytes: Vec<u8>) -> Result<Self, Self::Error> {
+               let refund = ParsedMessage::<RefundTlvStream>::try_from(bytes)?;
+               let ParsedMessage { bytes, tlv_stream } = refund;
+               let contents = RefundContents::try_from(tlv_stream)?;
+
+               Ok(Refund { bytes, contents })
+       }
+}
+
+impl TryFrom<RefundTlvStream> for RefundContents {
+       type Error = SemanticError;
+
+       fn try_from(tlv_stream: RefundTlvStream) -> Result<Self, Self::Error> {
+               let (
+                       PayerTlvStream { metadata: payer_metadata },
+                       OfferTlvStream {
+                               chains, metadata, currency, amount: offer_amount, description,
+                               features: offer_features, absolute_expiry, paths, issuer, quantity_max, node_id,
+                       },
+                       InvoiceRequestTlvStream { chain, amount, features, quantity, payer_id, payer_note },
+               ) = tlv_stream;
+
+               let payer = match payer_metadata {
+                       None => return Err(SemanticError::MissingPayerMetadata),
+                       Some(metadata) => PayerContents(metadata),
+               };
+
+               if chains.is_some() {
+                       return Err(SemanticError::UnexpectedChain);
+               }
+
+               if currency.is_some() || offer_amount.is_some() {
+                       return Err(SemanticError::UnexpectedAmount);
+               }
+
+               let description = match description {
+                       None => return Err(SemanticError::MissingDescription),
+                       Some(description) => description,
+               };
+
+               if offer_features.is_some() {
+                       return Err(SemanticError::UnexpectedFeatures);
+               }
+
+               let absolute_expiry = absolute_expiry.map(Duration::from_secs);
+
+               if quantity_max.is_some() {
+                       return Err(SemanticError::UnexpectedQuantity);
+               }
+
+               if node_id.is_some() {
+                       return Err(SemanticError::UnexpectedSigningPubkey);
+               }
+
+               let amount_msats = match amount {
+                       None => return Err(SemanticError::MissingAmount),
+                       Some(amount_msats) if amount_msats > MAX_VALUE_MSAT => {
+                               return Err(SemanticError::InvalidAmount);
+                       },
+                       Some(amount_msats) => amount_msats,
+               };
+
+               let features = features.unwrap_or_else(InvoiceRequestFeatures::empty);
+
+               // TODO: Check why this isn't in the spec.
+               if quantity.is_some() {
+                       return Err(SemanticError::UnexpectedQuantity);
+               }
+
+               let payer_id = match payer_id {
+                       None => return Err(SemanticError::MissingPayerId),
+                       Some(payer_id) => payer_id,
+               };
+
+               // TODO: Should metadata be included?
+               Ok(RefundContents {
+                       payer, metadata, description, absolute_expiry, issuer, paths, chain, amount_msats,
+                       features, payer_id, payer_note,
+               })
+       }
+}