Skip to content

Commit 827217a

Browse files
committed
Offer message interface and data format
Define an interface for BOLT 12 `offer` messages. The underlying format consists of the original bytes and the parsed contents. The bytes are later needed when constructing an `invoice_request` message. This is because it must mirror all the `offer` TLV records, including unknown ones, which aren't represented in the contents. The contents will be used in `invoice_request` messages to avoid duplication. Some fields while required in a typical user-pays-merchant flow may not be necessary in the merchant-pays-user flow (i.e., refund).
1 parent 7608df2 commit 827217a

File tree

6 files changed

+192
-4
lines changed

6 files changed

+192
-4
lines changed

lightning/src/lib.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -78,6 +78,7 @@ extern crate core;
7878
pub mod util;
7979
pub mod chain;
8080
pub mod ln;
81+
pub mod offers;
8182
pub mod routing;
8283
pub mod onion_message;
8384

lightning/src/offers/mod.rs

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
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+
//! Implementation of Lightning Offers
11+
//! ([BOLT 12](https://github.com/lightning/bolts/blob/master/12-offer-encoding.md)).
12+
//!
13+
//! Offers are a flexible protocol for Lightning payments.
14+
15+
pub mod offer;

lightning/src/offers/offer.rs

Lines changed: 169 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,169 @@
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 `offer` messages.
11+
12+
use bitcoin::blockdata::constants::ChainHash;
13+
use bitcoin::network::constants::Network;
14+
use bitcoin::secp256k1::PublicKey;
15+
use core::num::NonZeroU64;
16+
use core::time::Duration;
17+
use ln::features::OfferFeatures;
18+
use onion_message::BlindedPath;
19+
use util::string::PrintableString;
20+
21+
use prelude::*;
22+
23+
#[cfg(feature = "std")]
24+
use std::time::SystemTime;
25+
26+
/// An `Offer` is a potentially long-lived proposal for payment of a good or service.
27+
///
28+
/// An offer is precursor to an `InvoiceRequest`. A merchant publishes an offer from which a
29+
/// customer may request an `Invoice` for a specific quantity and using an amount enough to cover
30+
/// that quantity (i.e., at least `quantity * amount`). See [`Offer::amount`].
31+
///
32+
/// Offers may be denominated in currency other than bitcoin but are ultimately paid using the
33+
/// latter.
34+
///
35+
/// Through the use of [`BlindedPath`]s, offers provide recipient privacy.
36+
#[derive(Clone, Debug)]
37+
pub struct Offer {
38+
// The serialized offer. Needed when creating an `InvoiceRequest` if the offer contains unknown
39+
// fields.
40+
bytes: Vec<u8>,
41+
contents: OfferContents,
42+
}
43+
44+
/// The contents of an [`Offer`], which may be shared with an `InvoiceRequest` or an `Invoice`.
45+
#[derive(Clone, Debug)]
46+
pub(crate) struct OfferContents {
47+
chains: Option<Vec<ChainHash>>,
48+
metadata: Option<Vec<u8>>,
49+
amount: Option<Amount>,
50+
description: String,
51+
features: OfferFeatures,
52+
absolute_expiry: Option<Duration>,
53+
issuer: Option<String>,
54+
paths: Option<Vec<BlindedPath>>,
55+
quantity_max: Option<u64>,
56+
signing_pubkey: Option<PublicKey>,
57+
}
58+
59+
impl Offer {
60+
// TODO: Return a slice once ChainHash has constants.
61+
// - https://github.com/rust-bitcoin/rust-bitcoin/pull/1283
62+
// - https://github.com/rust-bitcoin/rust-bitcoin/pull/1286
63+
/// The chains that may be used when paying a requested invoice.
64+
pub fn chains(&self) -> Vec<ChainHash> {
65+
self.contents.chains
66+
.as_ref()
67+
.cloned()
68+
.unwrap_or_else(|| vec![ChainHash::using_genesis_block(Network::Bitcoin)])
69+
}
70+
71+
// TODO: Link to corresponding method in `InvoiceRequest`.
72+
/// Opaque bytes set by the originator. Useful for authentication and validating fields since it
73+
/// is reflected in `invoice_request` messages along with all the other fields from the `offer`.
74+
pub fn metadata(&self) -> Option<&Vec<u8>> {
75+
self.contents.metadata.as_ref()
76+
}
77+
78+
/// The minimum amount required for a successful payment of a single item.
79+
pub fn amount(&self) -> Option<&Amount> {
80+
self.contents.amount.as_ref()
81+
}
82+
83+
/// A complete description of the purpose of the payment. Intended to be displayed to the user
84+
/// but with the caveat that it has not been verified in any way.
85+
pub fn description(&self) -> PrintableString {
86+
PrintableString(&self.contents.description)
87+
}
88+
89+
/// Features pertaining to the offer.
90+
pub fn features(&self) -> &OfferFeatures {
91+
&self.contents.features
92+
}
93+
94+
/// Duration since the Unix epoch when an invoice should no longer be requested.
95+
///
96+
/// If `None`, the offer does not expire.
97+
pub fn absolute_expiry(&self) -> Option<Duration> {
98+
self.contents.absolute_expiry
99+
}
100+
101+
/// Whether the offer has expired.
102+
#[cfg(feature = "std")]
103+
pub fn is_expired(&self) -> bool {
104+
match self.absolute_expiry() {
105+
Some(seconds_from_epoch) => match SystemTime::UNIX_EPOCH.elapsed() {
106+
Ok(elapsed) => elapsed > seconds_from_epoch,
107+
Err(_) => false,
108+
},
109+
None => false,
110+
}
111+
}
112+
113+
/// The issuer of the offer, possibly beginning with `user@domain` or `domain`. Intended to be
114+
/// displayed to the user but with the caveat that it has not been verified in any way.
115+
pub fn issuer(&self) -> Option<PrintableString> {
116+
self.contents.issuer.as_ref().map(|issuer| PrintableString(issuer.as_str()))
117+
}
118+
119+
/// Paths to the recipient originating from publicly reachable nodes. Blinded paths provide
120+
/// recipient privacy by obfuscating its node id.
121+
pub fn paths(&self) -> &[BlindedPath] {
122+
self.contents.paths.as_ref().map(|paths| paths.as_slice()).unwrap_or(&[])
123+
}
124+
125+
/// The quantity of items supported.
126+
pub fn supported_quantity(&self) -> Quantity {
127+
match self.contents.quantity_max {
128+
None => Quantity::One,
129+
Some(0) => Quantity::Many,
130+
Some(n) => Quantity::Max(NonZeroU64::new(n).unwrap()),
131+
}
132+
}
133+
134+
/// The public key used by the recipient to sign invoices.
135+
pub fn signing_pubkey(&self) -> PublicKey {
136+
self.contents.signing_pubkey.unwrap()
137+
}
138+
}
139+
140+
/// The minimum amount required for an item in an [`Offer`], denominated in either bitcoin or
141+
/// another currency.
142+
#[derive(Clone, Debug)]
143+
pub enum Amount {
144+
/// An amount of bitcoin.
145+
Bitcoin {
146+
/// The amount in millisatoshi.
147+
amount_msats: u64,
148+
},
149+
/// An amount of currency specified using ISO 4712.
150+
Currency {
151+
/// The currency that the amount is denominated in.
152+
iso4217_code: CurrencyCode,
153+
/// The amount in the currency unit adjusted by the ISO 4712 exponent (e.g., USD cents).
154+
amount: u64,
155+
},
156+
}
157+
158+
/// An ISO 4712 three-letter currency code (e.g., USD).
159+
pub type CurrencyCode = [u8; 3];
160+
161+
/// Quantity of items supported by an [`Offer`].
162+
pub enum Quantity {
163+
/// A single item.
164+
One,
165+
/// One or more items.
166+
Many,
167+
/// Up to a specific number of items (inclusive).
168+
Max(NonZeroU64),
169+
}

lightning/src/onion_message/blinded_route.rs

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@ use prelude::*;
2222

2323
/// Onion messages can be sent and received to blinded routes, which serve to hide the identity of
2424
/// the recipient.
25+
#[derive(Clone, Debug)]
2526
pub struct BlindedRoute {
2627
/// To send to a blinded route, the sender first finds a route to the unblinded
2728
/// `introduction_node_id`, which can unblind its [`encrypted_payload`] to find out the onion
@@ -35,14 +36,15 @@ pub struct BlindedRoute {
3536
/// [`encrypted_payload`]: BlindedHop::encrypted_payload
3637
pub(super) blinding_point: PublicKey,
3738
/// The hops composing the blinded route.
38-
pub(super) blinded_hops: Vec<BlindedHop>,
39+
pub(crate) blinded_hops: Vec<BlindedHop>,
3940
}
4041

4142
/// Used to construct the blinded hops portion of a blinded route. These hops cannot be identified
4243
/// by outside observers and thus can be used to hide the identity of the recipient.
44+
#[derive(Clone, Debug)]
4345
pub struct BlindedHop {
4446
/// The blinded node id of this hop in a blinded route.
45-
pub(super) blinded_node_id: PublicKey,
47+
pub(crate) blinded_node_id: PublicKey,
4648
/// The encrypted payload intended for this hop in a blinded route.
4749
// The node sending to this blinded route will later encode this payload into the onion packet for
4850
// this hop.

lightning/src/onion_message/mod.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,6 @@ mod utils;
2828
mod functional_tests;
2929

3030
// Re-export structs so they can be imported with just the `onion_message::` module prefix.
31-
pub use self::blinded_route::{BlindedRoute, BlindedHop};
31+
pub use self::blinded_route::{BlindedRoute, BlindedRoute as BlindedPath, BlindedHop};
3232
pub use self::messenger::{CustomOnionMessageContents, CustomOnionMessageHandler, Destination, OnionMessageContents, OnionMessenger, SendError, SimpleArcOnionMessenger, SimpleRefOnionMessenger};
3333
pub(crate) use self::packet::Packet;

lightning/src/util/ser.rs

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -408,7 +408,8 @@ impl Readable for BigSize {
408408
/// In TLV we occasionally send fields which only consist of, or potentially end with, a
409409
/// variable-length integer which is simply truncated by skipping high zero bytes. This type
410410
/// encapsulates such integers implementing Readable/Writeable for them.
411-
#[cfg_attr(test, derive(PartialEq, Eq, Debug))]
411+
#[cfg_attr(test, derive(PartialEq, Eq))]
412+
#[derive(Clone, Debug)]
412413
pub(crate) struct HighZeroBytesDroppedBigSize<T>(pub T);
413414

414415
macro_rules! impl_writeable_primitive {

0 commit comments

Comments
 (0)