Skip to content

Commit 0075f98

Browse files
committed
Refund encoding and parsing
1 parent bee43ef commit 0075f98

File tree

4 files changed

+253
-6
lines changed

4 files changed

+253
-6
lines changed

lightning/src/offers/invoice_request.rs

+6-6
Original file line numberDiff line numberDiff line change
@@ -9,13 +9,14 @@
99

1010
//! Data structures and encoding for `invoice_request` messages.
1111
//!
12-
//! An [`InvoiceRequest`] can be either built from a parsed [`Offer`] as an "offer to be paid" or
13-
//! built directly as an "offer for money" (e.g., refund, ATM withdrawal). In the former case, it is
12+
//! An [`InvoiceRequest`] can be built from a parsed [`Offer`] as an "offer to be paid". It is
1413
//! typically constructed by a customer and sent to the merchant who had published the corresponding
15-
//! offer. In the latter case, an offer doesn't exist as a precursor to the request. Rather the
16-
//! merchant would typically construct the invoice request and present it to the customer.
14+
//! offer. The recipient of the request responds with an `Invoice`.
1715
//!
18-
//! The recipient of the request responds with an `Invoice`.
16+
//! For an "offer for money" (e.g., refund, ATM withdrawal), where an offer doesn't exist as a
17+
//! precursor, see [`Refund`].
18+
//!
19+
//! [`Refund`]: crate::offers::refund::Refund
1920
//!
2021
//! ```ignore
2122
//! extern crate bitcoin;
@@ -34,7 +35,6 @@
3435
//! let pubkey = PublicKey::from(keys);
3536
//! let mut buffer = Vec::new();
3637
//!
37-
//! // "offer to be paid" flow
3838
//! "lno1qcp4256ypq"
3939
//! .parse::<Offer>()?
4040
//! .request_invoice(vec![42; 64], pubkey)?

lightning/src/offers/mod.rs

+1
Original file line numberDiff line numberDiff line change
@@ -17,3 +17,4 @@ mod merkle;
1717
pub mod offer;
1818
pub mod parse;
1919
mod payer;
20+
pub mod refund;

lightning/src/offers/parse.rs

+8
Original file line numberDiff line numberDiff line change
@@ -127,20 +127,28 @@ pub enum SemanticError {
127127
AlreadyExpired,
128128
/// The provided chain hash does not correspond to a supported chain.
129129
UnsupportedChain,
130+
/// A chain was provided but was not expected.
131+
UnexpectedChain,
130132
/// An amount was expected but was missing.
131133
MissingAmount,
132134
/// The amount exceeded the total bitcoin supply.
133135
InvalidAmount,
134136
/// An amount was provided but was not sufficient in value.
135137
InsufficientAmount,
138+
/// An amount was provided but was not expected.
139+
UnexpectedAmount,
136140
/// A currency was provided that is not supported.
137141
UnsupportedCurrency,
138142
/// A feature was required but is unknown.
139143
UnknownRequiredFeatures,
144+
/// Features were provided but were not expected.
145+
UnexpectedFeatures,
140146
/// A required description was not provided.
141147
MissingDescription,
142148
/// A signing pubkey was not provided.
143149
MissingSigningPubkey,
150+
/// A signing pubkey was provided but was not expected.
151+
UnexpectedSigningPubkey,
144152
/// A quantity was expected but was missing.
145153
MissingQuantity,
146154
/// An unsupported quantity was provided.

lightning/src/offers/refund.rs

+238
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,238 @@
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 as 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;
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 for paying the invoice.
131+
pub fn features(&self) -> &InvoiceRequestFeatures {
132+
&self.contents.features
133+
}
134+
135+
/// A 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) => amount_msats,
218+
};
219+
220+
let features = features.unwrap_or_else(InvoiceRequestFeatures::empty);
221+
222+
// TODO: Check why this isn't in the spec.
223+
if quantity.is_some() {
224+
return Err(SemanticError::UnexpectedQuantity);
225+
}
226+
227+
let payer_id = match payer_id {
228+
None => return Err(SemanticError::MissingPayerId),
229+
Some(payer_id) => payer_id,
230+
};
231+
232+
// TODO: Should metadata be included?
233+
Ok(RefundContents {
234+
payer, metadata, description, absolute_expiry, issuer, paths, chain, amount_msats,
235+
features, payer_id, payer_note,
236+
})
237+
}
238+
}

0 commit comments

Comments
 (0)