Skip to content

Commit 134b83b

Browse files
Static invoice encoding and parsing
Define an interface for BOLT 12 static invoice messages. The underlying format consists of the original bytes and the parsed contents. The bytes are later needed for serialization. This is because it must mirror all the offer TLV records, including unknown ones, which aren't represented in the contents. Invoices may be created from an offer.
1 parent 172d05f commit 134b83b

File tree

3 files changed

+355
-0
lines changed

3 files changed

+355
-0
lines changed

lightning/src/offers/mod.rs

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,5 +24,7 @@ pub mod parse;
2424
mod payer;
2525
pub mod refund;
2626
pub(crate) mod signer;
27+
#[allow(unused)]
28+
pub(crate) mod static_invoice;
2729
#[cfg(test)]
2830
pub(crate) mod test_utils;

lightning/src/offers/parse.rs

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -189,6 +189,8 @@ pub enum Bolt12SemanticError {
189189
MissingCreationTime,
190190
/// An invoice payment hash was expected but was missing.
191191
MissingPaymentHash,
192+
/// An invoice payment hash was provided but was not expected.
193+
UnexpectedPaymentHash,
192194
/// A signature was expected but was missing.
193195
MissingSignature,
194196
}
Lines changed: 351 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,351 @@
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 static BOLT 12 invoices.
11+
12+
use crate::blinded_path::BlindedPath;
13+
use crate::io;
14+
use crate::ln::features::{Bolt12InvoiceFeatures, OfferFeatures};
15+
use crate::ln::msgs::DecodeError;
16+
use crate::offers::invoice::{
17+
check_invoice_signing_pubkey, construct_payment_paths, filter_fallbacks, BlindedPathIter,
18+
BlindedPayInfo, BlindedPayInfoIter, FallbackAddress, InvoiceTlvStream, InvoiceTlvStreamRef,
19+
SIGNATURE_TAG,
20+
};
21+
use crate::offers::invoice_macros::invoice_accessors_common;
22+
use crate::offers::merkle::{self, SignatureTlvStream, TaggedHash};
23+
use crate::offers::offer::{Amount, OfferContents, OfferTlvStream, Quantity};
24+
use crate::offers::parse::{Bolt12ParseError, Bolt12SemanticError, ParsedMessage};
25+
use crate::util::ser::{
26+
HighZeroBytesDroppedBigSize, Iterable, SeekReadable, WithoutLength, Writeable, Writer,
27+
};
28+
use crate::util::string::PrintableString;
29+
use bitcoin::address::Address;
30+
use bitcoin::blockdata::constants::ChainHash;
31+
use bitcoin::secp256k1::schnorr::Signature;
32+
use bitcoin::secp256k1::PublicKey;
33+
use core::time::Duration;
34+
35+
#[cfg(feature = "std")]
36+
use crate::offers::invoice::is_expired;
37+
38+
#[allow(unused_imports)]
39+
use crate::prelude::*;
40+
41+
/// Static invoices default to expiring after 24 hours.
42+
const DEFAULT_RELATIVE_EXPIRY: Duration = Duration::from_secs(3600 * 24);
43+
44+
/// A `StaticInvoice` is a reusable payment request corresponding to an [`Offer`].
45+
///
46+
/// A static invoice may be sent in response to an [`InvoiceRequest`] and includes all the
47+
/// information needed to pay the recipient. However, unlike [`Bolt12Invoice`]s, static invoices do
48+
/// not provide proof-of-payment. Therefore, [`Bolt12Invoice`]s should be preferred when the
49+
/// recipient is online to provide one.
50+
///
51+
/// [`Offer`]: crate::offers::offer::Offer
52+
/// [`InvoiceRequest`]: crate::offers::invoice_request::InvoiceRequest
53+
/// [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice
54+
#[derive(Clone, Debug)]
55+
pub struct StaticInvoice {
56+
bytes: Vec<u8>,
57+
contents: InvoiceContents,
58+
signature: Signature,
59+
}
60+
61+
/// The contents of a [`StaticInvoice`] for responding to an [`Offer`].
62+
///
63+
/// [`Offer`]: crate::offers::offer::Offer
64+
#[derive(Clone, Debug)]
65+
struct InvoiceContents {
66+
offer: OfferContents,
67+
payment_paths: Vec<(BlindedPayInfo, BlindedPath)>,
68+
created_at: Duration,
69+
relative_expiry: Option<Duration>,
70+
fallbacks: Option<Vec<FallbackAddress>>,
71+
features: Bolt12InvoiceFeatures,
72+
signing_pubkey: PublicKey,
73+
message_paths: Vec<BlindedPath>,
74+
}
75+
76+
macro_rules! invoice_accessors { ($self: ident, $contents: expr) => {
77+
/// The chain that must be used when paying the invoice. [`StaticInvoice`]s currently can only be
78+
/// created from offers that support a single chain.
79+
pub fn chain(&$self) -> ChainHash {
80+
$contents.chain()
81+
}
82+
83+
/// Opaque bytes set by the originating [`Offer::metadata`].
84+
///
85+
/// [`Offer::metadata`]: crate::offers::offer::Offer::metadata
86+
pub fn metadata(&$self) -> Option<&Vec<u8>> {
87+
$contents.metadata()
88+
}
89+
90+
/// The minimum amount required for a successful payment of a single item.
91+
///
92+
/// From [`Offer::amount`].
93+
///
94+
/// [`Offer::amount`]: crate::offers::offer::Offer::amount
95+
pub fn amount(&$self) -> Option<Amount> {
96+
$contents.amount()
97+
}
98+
99+
/// Features pertaining to the originating [`Offer`], from [`Offer::offer_features`].
100+
///
101+
/// [`Offer`]: crate::offers::offer::Offer
102+
/// [`Offer::offer_features`]: crate::offers::offer::Offer::offer_features
103+
pub fn offer_features(&$self) -> &OfferFeatures {
104+
$contents.offer_features()
105+
}
106+
107+
/// A complete description of the purpose of the originating offer, from [`Offer::description`].
108+
///
109+
/// [`Offer::description`]: crate::offers::offer::Offer::description
110+
pub fn description(&$self) -> Option<PrintableString> {
111+
$contents.description()
112+
}
113+
114+
/// Duration since the Unix epoch when an invoice should no longer be requested, from
115+
/// [`Offer::absolute_expiry`].
116+
///
117+
/// [`Offer::absolute_expiry`]: crate::offers::offer::Offer::absolute_expiry
118+
pub fn absolute_expiry(&$self) -> Option<Duration> {
119+
$contents.absolute_expiry()
120+
}
121+
122+
/// The issuer of the offer, from [`Offer::issuer`].
123+
///
124+
/// [`Offer::issuer`]: crate::offers::offer::Offer::issuer
125+
pub fn issuer(&$self) -> Option<PrintableString> {
126+
$contents.issuer()
127+
}
128+
129+
/// Paths to the node that may supply the invoice on the recipient's behalf, originating from
130+
/// publicly reachable nodes. Taken from [`Offer::paths`].
131+
///
132+
/// [`Offer::paths`]: crate::offers::offer::Offer::paths
133+
pub fn offer_message_paths(&$self) -> &[BlindedPath] {
134+
$contents.offer_message_paths()
135+
}
136+
137+
/// Paths to the recipient for indicating that a held HTLC is available to claim when they next
138+
/// come online.
139+
pub fn message_paths(&$self) -> &[BlindedPath] {
140+
$contents.message_paths()
141+
}
142+
143+
/// The quantity of items supported, from [`Offer::supported_quantity`].
144+
///
145+
/// [`Offer::supported_quantity`]: crate::offers::offer::Offer::supported_quantity
146+
pub fn supported_quantity(&$self) -> Quantity {
147+
$contents.supported_quantity()
148+
}
149+
} }
150+
151+
impl StaticInvoice {
152+
invoice_accessors_common!(self, self.contents, StaticInvoice);
153+
invoice_accessors!(self, self.contents);
154+
155+
/// Signature of the invoice verified using [`StaticInvoice::signing_pubkey`].
156+
pub fn signature(&self) -> Signature {
157+
self.signature
158+
}
159+
}
160+
161+
impl InvoiceContents {
162+
fn chain(&self) -> ChainHash {
163+
debug_assert_eq!(self.offer.chains().len(), 1);
164+
self.offer.chains().first().cloned().unwrap_or_else(|| self.offer.implied_chain())
165+
}
166+
167+
fn metadata(&self) -> Option<&Vec<u8>> {
168+
self.offer.metadata()
169+
}
170+
171+
fn amount(&self) -> Option<Amount> {
172+
self.offer.amount()
173+
}
174+
175+
fn offer_features(&self) -> &OfferFeatures {
176+
self.offer.features()
177+
}
178+
179+
fn description(&self) -> Option<PrintableString> {
180+
self.offer.description()
181+
}
182+
183+
fn absolute_expiry(&self) -> Option<Duration> {
184+
self.offer.absolute_expiry()
185+
}
186+
187+
fn issuer(&self) -> Option<PrintableString> {
188+
self.offer.issuer()
189+
}
190+
191+
fn offer_message_paths(&self) -> &[BlindedPath] {
192+
self.offer.paths()
193+
}
194+
195+
fn message_paths(&self) -> &[BlindedPath] {
196+
&self.message_paths[..]
197+
}
198+
199+
fn supported_quantity(&self) -> Quantity {
200+
self.offer.supported_quantity()
201+
}
202+
203+
fn payment_paths(&self) -> &[(BlindedPayInfo, BlindedPath)] {
204+
&self.payment_paths[..]
205+
}
206+
207+
fn created_at(&self) -> Duration {
208+
self.created_at
209+
}
210+
211+
fn relative_expiry(&self) -> Duration {
212+
self.relative_expiry.unwrap_or(DEFAULT_RELATIVE_EXPIRY)
213+
}
214+
215+
#[cfg(feature = "std")]
216+
fn is_expired(&self) -> bool {
217+
is_expired(self.created_at(), self.relative_expiry())
218+
}
219+
220+
fn fallbacks(&self) -> Vec<Address> {
221+
let chain =
222+
self.offer.chains().first().cloned().unwrap_or_else(|| self.offer.implied_chain());
223+
self.fallbacks
224+
.as_ref()
225+
.map(|fallbacks| filter_fallbacks(chain, fallbacks))
226+
.unwrap_or_else(Vec::new)
227+
}
228+
229+
fn features(&self) -> &Bolt12InvoiceFeatures {
230+
&self.features
231+
}
232+
233+
fn signing_pubkey(&self) -> PublicKey {
234+
self.signing_pubkey
235+
}
236+
}
237+
238+
impl Writeable for StaticInvoice {
239+
fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
240+
WithoutLength(&self.bytes).write(writer)
241+
}
242+
}
243+
244+
impl TryFrom<Vec<u8>> for StaticInvoice {
245+
type Error = Bolt12ParseError;
246+
247+
fn try_from(bytes: Vec<u8>) -> Result<Self, Self::Error> {
248+
let parsed_invoice = ParsedMessage::<FullInvoiceTlvStream>::try_from(bytes)?;
249+
StaticInvoice::try_from(parsed_invoice)
250+
}
251+
}
252+
253+
type FullInvoiceTlvStream = (OfferTlvStream, InvoiceTlvStream, SignatureTlvStream);
254+
255+
impl SeekReadable for FullInvoiceTlvStream {
256+
fn read<R: io::Read + io::Seek>(r: &mut R) -> Result<Self, DecodeError> {
257+
let offer = SeekReadable::read(r)?;
258+
let invoice = SeekReadable::read(r)?;
259+
let signature = SeekReadable::read(r)?;
260+
261+
Ok((offer, invoice, signature))
262+
}
263+
}
264+
265+
type PartialInvoiceTlvStream = (OfferTlvStream, InvoiceTlvStream);
266+
267+
impl TryFrom<ParsedMessage<FullInvoiceTlvStream>> for StaticInvoice {
268+
type Error = Bolt12ParseError;
269+
270+
fn try_from(invoice: ParsedMessage<FullInvoiceTlvStream>) -> Result<Self, Self::Error> {
271+
let ParsedMessage { bytes, tlv_stream } = invoice;
272+
let (offer_tlv_stream, invoice_tlv_stream, SignatureTlvStream { signature }) = tlv_stream;
273+
let contents = InvoiceContents::try_from((offer_tlv_stream, invoice_tlv_stream))?;
274+
275+
let signature = match signature {
276+
None => {
277+
return Err(Bolt12ParseError::InvalidSemantics(
278+
Bolt12SemanticError::MissingSignature,
279+
))
280+
},
281+
Some(signature) => signature,
282+
};
283+
let tagged_hash = TaggedHash::from_valid_tlv_stream_bytes(SIGNATURE_TAG, &bytes);
284+
let pubkey = contents.signing_pubkey;
285+
merkle::verify_signature(&signature, &tagged_hash, pubkey)?;
286+
287+
Ok(StaticInvoice { bytes, contents, signature })
288+
}
289+
}
290+
291+
impl TryFrom<PartialInvoiceTlvStream> for InvoiceContents {
292+
type Error = Bolt12SemanticError;
293+
294+
fn try_from(tlv_stream: PartialInvoiceTlvStream) -> Result<Self, Self::Error> {
295+
let (
296+
offer_tlv_stream,
297+
InvoiceTlvStream {
298+
paths,
299+
blindedpay,
300+
created_at,
301+
relative_expiry,
302+
fallbacks,
303+
features,
304+
node_id,
305+
message_paths,
306+
payment_hash,
307+
amount,
308+
},
309+
) = tlv_stream;
310+
311+
if payment_hash.is_some() {
312+
return Err(Bolt12SemanticError::UnexpectedPaymentHash);
313+
}
314+
if amount.is_some() {
315+
return Err(Bolt12SemanticError::UnexpectedAmount);
316+
}
317+
318+
let payment_paths = construct_payment_paths(blindedpay, paths)?;
319+
let message_paths = message_paths.ok_or(Bolt12SemanticError::MissingPaths)?;
320+
321+
let created_at = match created_at {
322+
None => return Err(Bolt12SemanticError::MissingCreationTime),
323+
Some(timestamp) => Duration::from_secs(timestamp),
324+
};
325+
326+
let relative_expiry = relative_expiry.map(Into::<u64>::into).map(Duration::from_secs);
327+
328+
let features = features.unwrap_or_else(Bolt12InvoiceFeatures::empty);
329+
330+
let signing_pubkey = node_id.ok_or(Bolt12SemanticError::MissingSigningPubkey)?;
331+
check_invoice_signing_pubkey(&signing_pubkey, &offer_tlv_stream)?;
332+
333+
if offer_tlv_stream.paths.is_none() {
334+
return Err(Bolt12SemanticError::MissingPaths);
335+
}
336+
if offer_tlv_stream.chains.as_ref().map_or(0, |chains| chains.len()) > 1 {
337+
return Err(Bolt12SemanticError::UnexpectedChain);
338+
}
339+
340+
Ok(InvoiceContents {
341+
offer: OfferContents::try_from(offer_tlv_stream)?,
342+
payment_paths,
343+
message_paths,
344+
created_at,
345+
relative_expiry,
346+
fallbacks,
347+
features,
348+
signing_pubkey,
349+
})
350+
}
351+
}

0 commit comments

Comments
 (0)