From: Jeffrey Czyz Date: Wed, 21 Sep 2022 14:32:23 +0000 (-0500) Subject: Refund encoding and parsing X-Git-Tag: v0.0.114-beta~72^2~9 X-Git-Url: http://git.bitcoin.ninja/index.cgi?a=commitdiff_plain;h=92a53dd7aaf91d9541d596dd2b8fbc6f3fa77f71;p=rust-lightning Refund encoding and parsing 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. --- diff --git a/lightning/src/offers/invoice_request.rs b/lightning/src/offers/invoice_request.rs index 69dc616e..e3fe1121 100644 --- a/lightning/src/offers/invoice_request.rs +++ b/lightning/src/offers/invoice_request.rs @@ -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::()? //! .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 } diff --git a/lightning/src/offers/mod.rs b/lightning/src/offers/mod.rs index be0eb2da..11df5ca1 100644 --- a/lightning/src/offers/mod.rs +++ b/lightning/src/offers/mod.rs @@ -17,3 +17,4 @@ mod merkle; pub mod offer; pub mod parse; mod payer; +pub mod refund; diff --git a/lightning/src/offers/parse.rs b/lightning/src/offers/parse.rs index 0b3dda79..b462e686 100644 --- a/lightning/src/offers/parse.rs +++ b/lightning/src/offers/parse.rs @@ -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 index 00000000..0a6c7e23 --- /dev/null +++ b/lightning/src/offers/refund.rs @@ -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 or the MIT license +// , 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, + 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>, + description: String, + absolute_expiry: Option, + issuer: Option, + paths: Option>, + // invoice_request fields + chain: Option, + amount_msats: u64, + features: InvoiceRequestFeatures, + payer_id: PublicKey, + payer_note: Option, +} + +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 { + 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 { + 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 { + 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: &mut R) -> Result { + let payer = SeekReadable::read(r)?; + let offer = SeekReadable::read(r)?; + let invoice_request = SeekReadable::read(r)?; + + Ok((payer, offer, invoice_request)) + } +} + +impl TryFrom> for Refund { + type Error = ParseError; + + fn try_from(bytes: Vec) -> Result { + let refund = ParsedMessage::::try_from(bytes)?; + let ParsedMessage { bytes, tlv_stream } = refund; + let contents = RefundContents::try_from(tlv_stream)?; + + Ok(Refund { bytes, contents }) + } +} + +impl TryFrom for RefundContents { + type Error = SemanticError; + + fn try_from(tlv_stream: RefundTlvStream) -> Result { + 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, + }) + } +}