Skip to content

Commit 77a0bbe

Browse files
authored
Add BIP21 Unified QR Code Support (#302)
* Add `UnifiedQrPayment` module for BIP21 URIs Firstly, I thought I staged and made commits for `unified_qr.rs` so sorry if this is out of order! But in `unified_qr.rs` I - I introduced the `UnifiedQrPayment` struct to handle creating and paying BIP21 URIs - `receive` generates a URI with an on-chain address and BOLT11 invoice and returns the URI as a string - `send` will parse a given URI string and attempt to send the BOLT12 offer, BOLT11 invoice, then if those fail the fallback on-chain address will be paid to. - Then I included tests for URI generation and URI parsing - Also has logging and error handling for payment operations * Add `unified_qr_payment` payment handler to `Node` - implement unified_qr_payment method to create the Unified QR payment handler - Includes conditional UniFFI features and updates docs with BIP21 and BOLT11 links * Add support for `unified_qr` in payment mod - Included unified_qr in payment module - Added `PaymentResult` and `UnifiedQrPayment` from unified_qr for public use * Add bip21 crate to handle BIP21 URIs * Add `UnifiedQrPayment` and `PaymentResult` to `ldk_node.udl` - Introduced `UnifiedQrPayment` method to `Node` interface - Add `UnifiedQrPayment` interface with `receieve and `send` methods - Add `PaymentResult` interface (enum) with `Onchain`, `Bolt11` and `Bolt12` fields These changes add support for our UniFFI bindings and enable the use of `unified_qr_payment` payment handler in Swift, and Kotlin. * Update `Error` enum with URI related errors - Add `UriParameterFailed` and `InvalidUri` fields to the `Error` enum - Added related error messages in the Display impl for the new fields * Add `PaymentResult` import for UniFFI bindings - Added `PaymentResult` so the .udl could access the enum - Added comment to explain the need to import any re-exported items to enure they're accessible in UniFFI. (becasue rustc says to add them in `lib.rs` * Add Unified QR `send`/`receive` integration tests - Added `unified_qr_send_receive` test to verify the `UnifedQrPayment` functionality - Added logic to handle paying a `BOLT12` offer, `BOLT11` invoice, and if those fail `On-chain` tx from a URI. - Validated each payments successful event - Ensured the off-chain and on-chain balacnes reflected the payment attempts * Update PR with optimizations and nit fixups The changes include: - Fixed a handful of nits for better readability in docs and simple grammar errors and made various name changes that affected the committed files. - Added a helper function in unified_qr.rs called capitalize_qr_params to format the lightning param in the receive method - Removed the optional message in the receive method and made it a required &str - Adjusted UDL formatting to use tabs instead of spaces These changes were made to improve code quality and maintainability based on the review feedback * Refactor URI parsing and add Bolt12 offer in receive Changes include: - Modified serialize_params to serialize both invoices and offers - Refactored deserialize_temp by removing the code that was parsing based on the lightning invoice/offer prefix. I instead used for loop to iterate over each lightning parameter, attempting to parse the string as an offer first, and then as an invoice. May need to log an error if neither succeeds - Added support for Bolt12 offers in the receive method - Updated capitalize_params function to handle multiple lightning parameters - Added a generate_bip21_uri test to show what the uri looks like in integration_tests_rust - Adjusted integration tests. Still needs work Still trying to figure out a bug related to Bolt12 offers being "paid" when it should fall back to an on-chain tx * Update BOLT12 offer to use `lno` key In this commit: - In serialize_params, BOLT12 offers were changed to be serialized with the `lno` key rather than the `lightning` key - During deserializing, I had to make the same update. Used a match to check whether it was a `lightning` or `lno` key and then parsed accordingly. - Next, a small name change: capitalize_qr_params to format_uri. Previously I changed the value after "&lightning" to all caps, but the "&lno=" value wasn't being changed. So, added a helper method inside format_uri to capitalize the values given the key! - Updated corresponding tests with `lno` update Small nits: - Updated QrPaymentResult with more thorough docs - Added a parsing test with an offer * Refactor for clarity and improve error handling This commit fixes a handful of minor comments/nits that include: - Updates to set the `bip21` crates default-features to false, to minimize dependencies. - Enable the `std` feature since we use/benefit from it. - In `receive` return `InvoiceCreationFailed` or `OfferCreationFailed` when creating an invoice or offer. Rather than silently logging the error. - Also in `receive` we first check if an amount is specified, and if not, return an error and abort. - Pass in `Config` to `UnifiedQrPayment` struct to use the users config network. - In `send` instead of checking each network for the `NetworkChecked` URI, we pass in the `Config::Network`. - Simplifed param parsing in `deserialize_temp` by directly finding the key and parsing the corresponding value. - General documentation fixes. - In parsing tests, moved longer invoice/offer strings into. variables that start with expected_ for clarity. * Fix docs for clarity Cleaned up the docs so they are easier to understand for the user. Also changed the message param in receive to description.
1 parent 8dd3790 commit 77a0bbe

File tree

8 files changed

+645
-5
lines changed

8 files changed

+645
-5
lines changed

Cargo.toml

+1
Original file line numberDiff line numberDiff line change
@@ -61,6 +61,7 @@ reqwest = { version = "0.11", default-features = false, features = ["json", "rus
6161
rusqlite = { version = "0.28.0", features = ["bundled"] }
6262
bitcoin = "0.30.2"
6363
bip39 = "2.0.0"
64+
bip21 = { version = "0.3.1", features = ["std"], default-features = false }
6465

6566
rand = "0.8.5"
6667
chrono = { version = "0.4", default-features = false, features = ["clock"] }

bindings/ldk_node.udl

+17
Original file line numberDiff line numberDiff line change
@@ -63,6 +63,7 @@ interface Node {
6363
Bolt12Payment bolt12_payment();
6464
SpontaneousPayment spontaneous_payment();
6565
OnchainPayment onchain_payment();
66+
UnifiedQrPayment unified_qr_payment();
6667
[Throws=NodeError]
6768
void connect(PublicKey node_id, SocketAddress address, boolean persist);
6869
[Throws=NodeError]
@@ -148,6 +149,13 @@ interface OnchainPayment {
148149
Txid send_all_to_address([ByRef]Address address);
149150
};
150151

152+
interface UnifiedQrPayment {
153+
[Throws=NodeError]
154+
string receive(u64 amount_sats, [ByRef]string message, u32 expiry_sec);
155+
[Throws=NodeError]
156+
QrPaymentResult send([ByRef]string uri_str);
157+
};
158+
151159
[Error]
152160
enum NodeError {
153161
"AlreadyRunning",
@@ -175,6 +183,7 @@ enum NodeError {
175183
"GossipUpdateFailed",
176184
"GossipUpdateTimeout",
177185
"LiquidityRequestFailed",
186+
"UriParameterParsingFailed",
178187
"InvalidAddress",
179188
"InvalidSocketAddress",
180189
"InvalidPublicKey",
@@ -191,6 +200,7 @@ enum NodeError {
191200
"InvalidRefund",
192201
"InvalidChannelId",
193202
"InvalidNetwork",
203+
"InvalidUri",
194204
"DuplicatePayment",
195205
"UnsupportedCurrency",
196206
"InsufficientFunds",
@@ -276,6 +286,13 @@ interface PaymentKind {
276286
Spontaneous(PaymentHash hash, PaymentPreimage? preimage);
277287
};
278288

289+
[Enum]
290+
interface QrPaymentResult {
291+
Onchain(Txid txid);
292+
Bolt11(PaymentId payment_id);
293+
Bolt12(PaymentId payment_id);
294+
};
295+
279296
enum PaymentDirection {
280297
"Inbound",
281298
"Outbound",

src/error.rs

+6
Original file line numberDiff line numberDiff line change
@@ -53,6 +53,8 @@ pub enum Error {
5353
GossipUpdateTimeout,
5454
/// A liquidity request operation failed.
5555
LiquidityRequestFailed,
56+
/// Parsing a URI parameter has failed.
57+
UriParameterParsingFailed,
5658
/// The given address is invalid.
5759
InvalidAddress,
5860
/// The given network address is invalid.
@@ -85,6 +87,8 @@ pub enum Error {
8587
InvalidChannelId,
8688
/// The given network is invalid.
8789
InvalidNetwork,
90+
/// The given URI is invalid.
91+
InvalidUri,
8892
/// A payment with the given hash has already been initiated.
8993
DuplicatePayment,
9094
/// The provided offer was denonminated in an unsupported currency.
@@ -131,6 +135,7 @@ impl fmt::Display for Error {
131135
Self::GossipUpdateFailed => write!(f, "Failed to update gossip data."),
132136
Self::GossipUpdateTimeout => write!(f, "Updating gossip data timed out."),
133137
Self::LiquidityRequestFailed => write!(f, "Failed to request inbound liquidity."),
138+
Self::UriParameterParsingFailed => write!(f, "Failed to parse a URI parameter."),
134139
Self::InvalidAddress => write!(f, "The given address is invalid."),
135140
Self::InvalidSocketAddress => write!(f, "The given network address is invalid."),
136141
Self::InvalidPublicKey => write!(f, "The given public key is invalid."),
@@ -147,6 +152,7 @@ impl fmt::Display for Error {
147152
Self::InvalidRefund => write!(f, "The given refund is invalid."),
148153
Self::InvalidChannelId => write!(f, "The given channel ID is invalid."),
149154
Self::InvalidNetwork => write!(f, "The given network is invalid."),
155+
Self::InvalidUri => write!(f, "The given URI is invalid."),
150156
Self::DuplicatePayment => {
151157
write!(f, "A payment with the given hash has already been initiated.")
152158
},

src/lib.rs

+38-1
Original file line numberDiff line numberDiff line change
@@ -133,7 +133,10 @@ use gossip::GossipSource;
133133
use graph::NetworkGraph;
134134
use liquidity::LiquiditySource;
135135
use payment::store::PaymentStore;
136-
use payment::{Bolt11Payment, Bolt12Payment, OnchainPayment, PaymentDetails, SpontaneousPayment};
136+
use payment::{
137+
Bolt11Payment, Bolt12Payment, OnchainPayment, PaymentDetails, SpontaneousPayment,
138+
UnifiedQrPayment,
139+
};
137140
use peer_store::{PeerInfo, PeerStore};
138141
use types::{
139142
Broadcaster, BumpTransactionEventHandler, ChainMonitor, ChannelManager, DynStore, FeeEstimator,
@@ -1072,6 +1075,40 @@ impl Node {
10721075
))
10731076
}
10741077

1078+
/// Returns a payment handler allowing to create [BIP 21] URIs with an on-chain, [BOLT 11],
1079+
/// and [BOLT 12] payment options.
1080+
///
1081+
/// [BOLT 11]: https://github.com/lightning/bolts/blob/master/11-payment-encoding.md
1082+
/// [BOLT 12]: https://github.com/lightning/bolts/blob/master/12-offer-encoding.md
1083+
/// [BIP 21]: https://github.com/bitcoin/bips/blob/master/bip-0021.mediawiki
1084+
#[cfg(not(feature = "uniffi"))]
1085+
pub fn unified_qr_payment(&self) -> UnifiedQrPayment {
1086+
UnifiedQrPayment::new(
1087+
self.onchain_payment().into(),
1088+
self.bolt11_payment().into(),
1089+
self.bolt12_payment().into(),
1090+
Arc::clone(&self.config),
1091+
Arc::clone(&self.logger),
1092+
)
1093+
}
1094+
1095+
/// Returns a payment handler allowing to create [BIP 21] URIs with an on-chain, [BOLT 11],
1096+
/// and [BOLT 12] payment options.
1097+
///
1098+
/// [BOLT 11]: https://github.com/lightning/bolts/blob/master/11-payment-encoding.md
1099+
/// [BOLT 12]: https://github.com/lightning/bolts/blob/master/12-offer-encoding.md
1100+
/// [BIP 21]: https://github.com/bitcoin/bips/blob/master/bip-0021.mediawiki
1101+
#[cfg(feature = "uniffi")]
1102+
pub fn unified_qr_payment(&self) -> Arc<UnifiedQrPayment> {
1103+
Arc::new(UnifiedQrPayment::new(
1104+
self.onchain_payment(),
1105+
self.bolt11_payment(),
1106+
self.bolt12_payment(),
1107+
Arc::clone(&self.config),
1108+
Arc::clone(&self.logger),
1109+
))
1110+
}
1111+
10751112
/// Retrieve a list of known channels.
10761113
pub fn list_channels(&self) -> Vec<ChannelDetails> {
10771114
self.channel_manager.list_channels().into_iter().map(|c| c.into()).collect()

src/payment/mod.rs

+2
Original file line numberDiff line numberDiff line change
@@ -5,9 +5,11 @@ mod bolt12;
55
mod onchain;
66
mod spontaneous;
77
pub(crate) mod store;
8+
mod unified_qr;
89

910
pub use bolt11::Bolt11Payment;
1011
pub use bolt12::Bolt12Payment;
1112
pub use onchain::OnchainPayment;
1213
pub use spontaneous::SpontaneousPayment;
1314
pub use store::{LSPFeeLimits, PaymentDetails, PaymentDirection, PaymentKind, PaymentStatus};
15+
pub use unified_qr::{QrPaymentResult, UnifiedQrPayment};

0 commit comments

Comments
 (0)