1use bitcoin::constants::ChainHash;
2pub use lightning::offers::invoice::Bolt12Invoice;
3pub use lightning_invoice::Bolt11Invoice;
4pub use lightning::offers::offer::{Amount as OfferAmount, Offer};
5
6use std::fmt;
7use std::borrow::Borrow;
8use std::str::FromStr;
9
10use bitcoin::{Amount, Network};
11use bitcoin::bech32::{encode_to_fmt, EncodeError, Hrp, NoChecksum, primitives::decode::CheckedHrpstring};
12use bitcoin::hashes::{sha256, Hash};
13use bitcoin::secp256k1::Message;
14use lightning::offers::parse::Bolt12ParseError;
15use lightning::util::ser::Writeable;
16
17use bitcoin_ext::{AmountExt, P2TR_DUST};
18
19use crate::SECP;
20
21const BECH32_BOLT12_INVOICE_HRP: &str = "lni";
22
23pub const HTLC_MIN_FEE: Amount = P2TR_DUST;
25
26pub const PREIMAGE_SIZE: usize = 32;
27pub const PAYMENT_HASH_SIZE: usize = 32;
28
29#[derive(Clone, Copy, PartialEq, Eq, Hash)]
31pub struct Preimage([u8; PREIMAGE_SIZE]);
32impl_byte_newtype!(Preimage, PREIMAGE_SIZE);
33
34impl Preimage {
35 pub fn random() -> Preimage {
37 Preimage(rand::random())
38 }
39
40 pub fn compute_payment_hash(&self) -> PaymentHash {
42 sha256::Hash::hash(self.as_ref()).into()
43 }
44}
45
46#[derive(Clone, Copy, PartialEq, Eq, Hash, Ord, PartialOrd)]
48pub struct PaymentHash([u8; PAYMENT_HASH_SIZE]);
49impl_byte_newtype!(PaymentHash, PAYMENT_HASH_SIZE);
50
51impl From<sha256::Hash> for PaymentHash {
52 fn from(hash: sha256::Hash) -> Self {
53 PaymentHash(hash.to_byte_array())
54 }
55}
56
57impl From<Preimage> for PaymentHash {
58 fn from(preimage: Preimage) -> Self {
59 preimage.compute_payment_hash()
60 }
61}
62
63impl From<lightning::types::payment::PaymentHash> for PaymentHash {
64 fn from(hash: lightning::types::payment::PaymentHash) -> Self {
65 PaymentHash(hash.0)
66 }
67}
68
69impl<'a> From<&'a Bolt11Invoice> for PaymentHash {
70 fn from(i: &'a Bolt11Invoice) -> Self {
71 (*i.payment_hash()).into()
72 }
73}
74
75impl From<Bolt11Invoice> for PaymentHash {
76 fn from(i: Bolt11Invoice) -> Self {
77 (&i).into()
78 }
79}
80
81impl PaymentHash {
82 pub fn to_sha256_hash(&self) -> sha256::Hash {
84 sha256::Hash::from_byte_array(self.0)
85 }
86}
87
88pub trait AsPaymentHash {
90 fn as_payment_hash(&self) -> PaymentHash;
93}
94
95impl AsPaymentHash for PaymentHash {
96 fn as_payment_hash(&self) -> PaymentHash { *self }
97}
98
99impl AsPaymentHash for Preimage {
100 fn as_payment_hash(&self) -> PaymentHash { self.compute_payment_hash() }
101}
102
103impl AsPaymentHash for Bolt11Invoice {
104 fn as_payment_hash(&self) -> PaymentHash { PaymentHash::from(*self.payment_hash()) }
105}
106
107impl AsPaymentHash for Bolt12Invoice {
108 fn as_payment_hash(&self) -> PaymentHash { self.payment_hash().into() }
109}
110
111impl AsPaymentHash for Invoice {
112 fn as_payment_hash(&self) -> PaymentHash {
113 match self {
114 Invoice::Bolt11(i) => AsPaymentHash::as_payment_hash(i),
115 Invoice::Bolt12(i) => AsPaymentHash::as_payment_hash(i),
116 }
117 }
118}
119
120impl<'a, T: AsPaymentHash> AsPaymentHash for &'a T {
121 fn as_payment_hash(&self) -> PaymentHash {
122 AsPaymentHash::as_payment_hash(*self)
123 }
124}
125
126#[derive(Debug, Clone)]
127pub enum PaymentStatus {
128 Pending,
129 Success(Preimage),
130 Failed,
131}
132
133impl fmt::Display for PaymentStatus {
134 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
135 fmt::Debug::fmt(self, f)
136 }
137}
138
139#[derive(Debug, Clone, PartialEq, Eq, Hash)]
141pub enum Invoice {
142 Bolt11(Bolt11Invoice),
143 Bolt12(Bolt12Invoice),
144}
145
146#[derive(Debug, thiserror::Error)]
147#[error("cannot parse invoice")]
148pub struct InvoiceParseError;
149
150impl FromStr for Invoice {
151 type Err = InvoiceParseError;
152
153 fn from_str(s: &str) -> Result<Self, Self::Err> {
154 if let Ok(bolt11) = Bolt11Invoice::from_str(s) {
155 Ok(Invoice::Bolt11(bolt11))
156 } else if let Ok(bolt12) = Bolt12Invoice::from_str(s) {
157 Ok(Invoice::Bolt12(bolt12))
158 } else {
159 Err(InvoiceParseError)
160 }
161 }
162}
163
164impl From<Bolt11Invoice> for Invoice {
165 fn from(invoice: Bolt11Invoice) -> Self {
166 Invoice::Bolt11(invoice)
167 }
168}
169
170impl From<Bolt12Invoice> for Invoice {
171 fn from(invoice: Bolt12Invoice) -> Self {
172 Invoice::Bolt12(invoice)
173 }
174}
175
176impl<'a> TryFrom<&'a str> for Invoice {
177 type Error = <Invoice as FromStr>::Err;
178 fn try_from(invoice: &'a str) -> Result<Self, Self::Error> {
179 FromStr::from_str(invoice)
180 }
181}
182
183impl TryFrom<String> for Invoice {
184 type Error = <Invoice as FromStr>::Err;
185 fn try_from(invoice: String) -> Result<Self, Self::Error> {
186 FromStr::from_str(&invoice)
187 }
188}
189
190impl serde::Serialize for Invoice {
191 fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
192 s.collect_str(self)
193 }
194}
195
196impl<'de> serde::Deserialize<'de> for Invoice {
197 fn deserialize<D: serde::Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
198 struct Visitor;
199 impl<'de> serde::de::Visitor<'de> for Visitor {
200 type Value = Invoice;
201 fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
202 write!(f, "a lightning invoice")
203 }
204 fn visit_str<E: serde::de::Error>(self, v: &str) -> Result<Self::Value, E> {
205 Invoice::from_str(v).map_err(serde::de::Error::custom)
206 }
207 }
208 d.deserialize_str(Visitor)
209 }
210}
211
212
213#[derive(Debug, thiserror::Error)]
214#[error("invoice amount mismatch: invoice={invoice}, user={user}")]
215pub enum CheckAmountError {
216 #[error("invalid user amount: invoice={invoice}, user={user}")]
217 InvalidUserAmount { invoice: Amount, user: Amount },
218 #[error("offer currency is not supported: {amount:?}")]
219 UnsupportedCurrency { amount: OfferAmount },
220 #[error("user amount required")]
221 UserAmountRequired,
222}
223
224#[derive(Debug, thiserror::Error)]
225#[error("invalid invoice signature: {0}")]
226pub struct CheckSignatureError(pub String);
227
228impl Invoice {
229 pub fn into_bolt11(self) -> Option<Bolt11Invoice> {
230 match self {
231 Invoice::Bolt11(invoice) => Some(invoice),
232 Invoice::Bolt12(_) => None
233 }
234 }
235
236 pub fn payment_hash(&self) -> PaymentHash {
237 match self {
238 Invoice::Bolt11(invoice) => PaymentHash::from(*invoice.payment_hash().as_byte_array()),
239 Invoice::Bolt12(invoice) => PaymentHash::from(invoice.payment_hash()),
240 }
241 }
242
243 pub fn network(&self) -> Network {
244 match self {
245 Invoice::Bolt11(invoice) => invoice.network(),
246 Invoice::Bolt12(invoice) => match invoice.chain() {
247 ChainHash::BITCOIN => Network::Bitcoin,
248 ChainHash::TESTNET3 => Network::Testnet,
249 ChainHash::TESTNET4 => Network::Testnet4,
250 ChainHash::SIGNET => Network::Signet,
251 ChainHash::REGTEST => Network::Regtest,
252 _ => panic!("unsupported network"),
253 },
254 }
255 }
256
257 pub fn get_payment_amount(
261 &self,
262 user_amount: Option<Amount>,
263 ) -> Result<Amount, CheckAmountError> {
264 match self {
265 Invoice::Bolt11(invoice) => invoice.get_payment_amount(user_amount),
266 Invoice::Bolt12(invoice) => invoice.get_payment_amount(user_amount),
267 }
268 }
269
270 pub fn amount_msat(&self) -> Option<u64> {
271 match self {
272 Invoice::Bolt11(invoice) => invoice.amount_milli_satoshis(),
273 Invoice::Bolt12(invoice) => Some(invoice.amount_msats()),
274 }
275 }
276
277 pub fn check_signature(&self) -> Result<(), CheckSignatureError> {
278 match self {
279 Invoice::Bolt11(invoice) => invoice
280 .check_signature()
281 .map_err(|e| CheckSignatureError(e.to_string())),
282 Invoice::Bolt12(invoice) => invoice.check_signature(),
283 }
284 }
285}
286
287impl fmt::Display for Invoice {
288 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
289 match self {
290 Invoice::Bolt11(invoice) => write!(f, "{}", invoice.to_string()),
291 Invoice::Bolt12(invoice) => encode_to_fmt::<NoChecksum, _>(
292 f,
293 Hrp::parse("lni").unwrap(),
294 &invoice.bytes(),
295 )
296 .map_err(|e| match e {
297 EncodeError::Fmt(e) => e,
298 _ => fmt::Error {},
299 }),
300 }
301 }
302}
303
304fn get_invoice_payment_amount(invoice_amount: Option<Amount>, user_amount: Option<Amount>) -> Result<Amount, CheckAmountError> {
308 match (invoice_amount, user_amount) {
309 (Some(invoice_amount), Some(user_amount)) => {
310 if user_amount >= invoice_amount && user_amount <= invoice_amount * 2 {
313 return Ok(user_amount);
314 }
315
316 return Err(CheckAmountError::InvalidUserAmount {
317 invoice: invoice_amount,
318 user: user_amount,
319 });
320 }
321 (Some(invoice_amount), None) => {
322 return Ok(invoice_amount);
323 }
324 (None, Some(user_amount)) => {
325 return Ok(user_amount);
326 }
327 (None, None) => {
328 return Err(CheckAmountError::UserAmountRequired);
329 }
330 }
331}
332
333pub trait Bolt11InvoiceExt: Borrow<Bolt11Invoice> {
335 fn get_payment_amount(&self, user_amount: Option<Amount>) -> Result<Amount, CheckAmountError> {
339 let invoice_amount = self.borrow().amount_milli_satoshis()
340 .map(Amount::from_msat_ceil);
341
342 get_invoice_payment_amount(invoice_amount, user_amount)
343 }
344}
345
346impl Bolt11InvoiceExt for Bolt11Invoice {}
347
348pub trait Bolt12InvoiceExt: Borrow<Bolt12Invoice> {
350 fn payment_hash(&self) -> PaymentHash { PaymentHash::from(self.borrow().payment_hash()) }
351
352 fn get_payment_amount(&self, user_amount: Option<Amount>) -> Result<Amount, CheckAmountError> {
356 let invoice_amount = Amount::from_msat_ceil(self.borrow().amount_msats());
357 get_invoice_payment_amount(Some(invoice_amount), user_amount)
358 }
359
360 fn bytes(&self) -> Vec<u8> {
361 let mut bytes = Vec::new();
362 self.borrow().write(&mut bytes).expect("Writing into a Vec is infallible");
363 bytes
364 }
365
366 fn from_bytes(bytes: &[u8]) -> Result<Bolt12Invoice, Bolt12ParseError> {
367 Bolt12Invoice::try_from(bytes.to_vec())
368 }
369
370 fn from_str(s: &str) -> Result<Bolt12Invoice, Bolt12ParseError> {
371 let dec = CheckedHrpstring::new::<NoChecksum>(&s)?;
372 if dec.hrp().to_lowercase() != BECH32_BOLT12_INVOICE_HRP {
373 return Err(Bolt12ParseError::InvalidBech32Hrp);
374 }
375
376 let data = dec.byte_iter().collect::<Vec<_>>();
377 Bolt12Invoice::try_from(data)
378 }
379
380 fn check_signature(&self) -> Result<(), CheckSignatureError> {
385 let message = Message::from_digest(self.borrow().signable_hash());
386 let signature = self.borrow().signature();
387
388 let pubkey = self.borrow().signing_pubkey();
389 SECP.verify_schnorr(&signature, &message, &pubkey.into())
390 .map_err(|_| CheckSignatureError("invalid signature".to_string()))
391 }
392
393 fn validate_issuance(&self, offer: &Offer) -> Result<(), CheckSignatureError> {
397 if let Some(issuer_signing_pubkey) = offer.issuer_signing_pubkey() {
398 if issuer_signing_pubkey != self.borrow().signing_pubkey() {
399 return Err(CheckSignatureError("public keys mismatch".to_string()));
400 }
401
402 self.check_signature()
403 } else {
404 for offer_path in offer.paths() {
405 let final_hop_pk = offer_path.blinded_hops().last()
406 .map(|hop| hop.blinded_node_id);
407
408 match final_hop_pk {
409 Some(final_hop_pk) if final_hop_pk == self.borrow().signing_pubkey() => {
410 return self.check_signature();
411 }
412 _ => {}
413 }
414 }
415
416 Err(CheckSignatureError("public keys mismatch".to_string()))
417 }
418 }
419}
420
421impl Bolt12InvoiceExt for Bolt12Invoice {}
422
423#[cfg(test)]
424mod test {
425 use super::*;
426
427 use hex_conservative::FromHex;
428 use bitcoin::secp256k1::{Keypair, Secp256k1, SecretKey};
429 use lightning::blinded_path::BlindedHop;
430 use lightning::blinded_path::payment::{BlindedPayInfo, BlindedPaymentPath};
431 use lightning::ln::channelmanager::PaymentId;
432 use lightning::ln::inbound_payment::ExpandedKey;
433 use lightning::offers::nonce::Nonce;
434 use lightning::offers::invoice_request::InvoiceRequest;
435 use lightning::offers::offer::OfferBuilder;
436 use lightning::sign::EntropySource;
437 use lightning::types::features::BlindedHopFeatures;
438
439 struct FixedEntropy;
440
441 impl EntropySource for FixedEntropy {
442 fn get_secure_random_bytes(&self) -> [u8; 32] { [42; 32] }
443 }
444
445 fn pubkey(byte: u8) -> bitcoin::secp256k1::PublicKey {
446 let secp = Secp256k1::new();
447 bitcoin::secp256k1::PublicKey::from_secret_key(
448 &secp,
449 &SecretKey::from_slice(&[byte; 32]).unwrap(),
450 )
451 }
452
453 fn payment_paths() -> Vec<BlindedPaymentPath> {
454 vec![BlindedPaymentPath::from_blinded_path_and_payinfo(
455 pubkey(40),
456 pubkey(41),
457 vec![
458 BlindedHop { blinded_node_id: pubkey(43), encrypted_payload: vec![0; 43] },
459 BlindedHop { blinded_node_id: pubkey(44), encrypted_payload: vec![0; 44] },
460 ],
461 BlindedPayInfo {
462 fee_base_msat: 1,
463 fee_proportional_millionths: 1_000,
464 cltv_expiry_delta: 42,
465 htlc_minimum_msat: 100,
466 htlc_maximum_msat: 1_000_000_000_000,
467 features: BlindedHopFeatures::empty(),
468 },
469 )]
470 }
471
472 #[test]
473 fn offer_with_signing_pubkey_validate_invoice() {
474 let secp = Secp256k1::new();
475 let expanded_key = ExpandedKey::new([42; 32]);
476 let entropy = FixedEntropy;
477 let nonce = Nonce::from_entropy_source(&entropy);
478
479 let recipient_keys = Keypair::from_secret_key(
481 &secp,
482 &SecretKey::from_slice(&[43; 32]).unwrap(),
483 );
484
485 let offer = OfferBuilder::new(recipient_keys.public_key())
487 .amount_msats(1_000_000)
488 .build()
489 .unwrap();
490
491 assert_eq!(offer.amount(), Some(OfferAmount::Bitcoin { amount_msats: 1_000_000 }));
492 assert_eq!(offer.issuer_signing_pubkey(), Some(recipient_keys.public_key()));
493
494 let payment_id = PaymentId([1; 32]);
496 let invoice_request = offer
497 .request_invoice(&expanded_key, nonce, &secp, payment_id)
498 .unwrap()
499 .build_and_sign()
500 .unwrap();
501
502 assert_eq!(invoice_request.issuer_signing_pubkey(), Some(recipient_keys.public_key()));
503
504 let payment_hash = lightning::types::payment::PaymentHash([99; 32]);
506 let unsigned_invoice = invoice_request
507 .respond_with(payment_paths(), payment_hash)
508 .unwrap()
509 .build()
510 .unwrap();
511
512 let invoice = unsigned_invoice
513 .sign(|msg: &lightning::offers::invoice::UnsignedBolt12Invoice| {
514 Ok(secp.sign_schnorr_no_aux_rand(msg.as_ref().as_digest(), &recipient_keys))
515 })
516 .unwrap();
517
518 assert_eq!(invoice.payment_hash(), payment_hash);
520 assert_eq!(invoice.amount_msats(), 1_000_000);
521 assert_eq!(
522 invoice.issuer_signing_pubkey(),
523 Some(recipient_keys.public_key()),
524 );
525
526 let amount = invoice.get_payment_amount(None).unwrap();
527 assert_eq!(amount, Amount::from_sat(1_000));
528
529 invoice.check_signature().unwrap();
530 invoice.validate_issuance(&offer).unwrap();
531 }
532
533 #[test]
534 fn offer_no_signing_pubkey_validate_invoice() {
535 let offer_str = "lno1pqpzwyq2qe3k7enxv4j3pjgrrwzv24nmzfjypx2a8m264ws9vht3uxp5vpypnluuzl67n4waq78syn2tdngnvypje2da9t4emyq25n29m84dszkfggehf3z35uj56pmxqgp5vfme44926w23gc282xn3pp0j7y8pc7je8e8qxrhmtwrjrnj4kzcqyqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqjnrlnqdqf52q7jwgcnxgnuseav37nvs0zn06dyfs79hk7uk8lrxuqzqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq";
537 let invoice_request_hex = "00208f483020855be2127df9a1b25963afbb633c183d06d3223cf31942a059fb861b080227100a06636f6666656510c9031b84c5567b126440995d3ed5aaba0565d71e1834604819ff9c17f5e9d5dd078f024d4b6cd1361032ca9bd2aeb9d900aa4d45d9ead80ac9423374c451a7254d07660203462779ad4aad39514614751a71085f2f10e1c7a593e4e030efb5b8721ce55b0b0020000000000000000000000000000000000000000000000000000000000000000002531fe6068134503d2723133227c867ac8fa6c83c537e9a44c3c5bdbdcb1fe3370020000000000000000000000000000000000000000000000000000000000000000052022710582103d084805e2f4c2bcf5188e40e7baec8b8680a1554da028b3d4c25e8969869fbe5f0401404f55082e4499ad85ac9cef739909f61243800ba31e2718bd5e40f08b05be22181ec91a4ccdf8c2cbb1feae62a62cda13ea069ca0134add34b215e6019bc33";
539 let invoice_hex = "00208f483020855be2127df9a1b25963afbb633c183d06d3223cf31942a059fb861b080227100a06636f6666656510c9031b84c5567b126440995d3ed5aaba0565d71e1834604819ff9c17f5e9d5dd078f024d4b6cd1361032ca9bd2aeb9d900aa4d45d9ead80ac9423374c451a7254d07660203462779ad4aad39514614751a71085f2f10e1c7a593e4e030efb5b8721ce55b0b0020000000000000000000000000000000000000000000000000000000000000000002531fe6068134503d2723133227c867ac8fa6c83c537e9a44c3c5bdbdcb1fe3370020000000000000000000000000000000000000000000000000000000000000000052022710582103d084805e2f4c2bcf5188e40e7baec8b8680a1554da028b3d4c25e8969869fbe5a0c9031b84c5567b126440995d3ed5aaba0565d71e1834604819ff9c17f5e9d5dd078f024d4b6cd1361032ca9bd2aeb9d900aa4d45d9ead80ac9423374c451a7254d07660203462779ad4aad39514614751a71085f2f10e1c7a593e4e030efb5b8721ce55b0b0020000000000000000000000000000000000000000000000000000000000000000002531fe6068134503d2723133227c867ac8fa6c83c537e9a44c3c5bdbdcb1fe33700200000000000000000000000000000000000000000000000000000000000000000a21c00000001000003e8002a0000000000000064000000e8d4a510000000a40469d570dfa820aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa022710b02102531fe6068134503d2723133227c867ac8fa6c83c537e9a44c3c5bdbdcb1fe337f0408f1efd3aafd2b200bb740b16b2311487312da67520b9d2977335074e27db8c8cdba9ea1c45f89f1c345ace60c48c1cd8cc149c184851cbc58d8221be4794db7b";
541 let other_offer_invoice_hex = "00202aa648ba07b96455928d4908f851c9e7f4bc1c4b44896ffa952bd116db27873e080213880a0374656110c90362c0a046dacce86ddd0343c6d3c7c79c2208ba0d9c9cf24a6d046d21d21f90f703f006a18d5653c4edf5391ff23a61f03ff83d237e880ee61187fa9f379a028e0a0203f991f944d1e1954a7fc8b9bf62e0d78f015f4c07762d505e20e6c45260a3661b0020000000000000000000000000000000000000000000000000000000000000000002989c0b76cb563971fdc9bef31ec06c3560f3249d6ee9e5d83c57625596e05f6f0020000000000000000000000000000000000000000000000000000000000000000052021388582103d9f3787be32e810bc0a72ebb252160b76da09c9adba45ee62aa94f048c8f12e1a0c90362c0a046dacce86ddd0343c6d3c7c79c2208ba0d9c9cf24a6d046d21d21f90f703f006a18d5653c4edf5391ff23a61f03ff83d237e880ee61187fa9f379a028e0a0203f991f944d1e1954a7fc8b9bf62e0d78f015f4c07762d505e20e6c45260a3661b0020000000000000000000000000000000000000000000000000000000000000000002989c0b76cb563971fdc9bef31ec06c3560f3249d6ee9e5d83c57625596e05f6f00200000000000000000000000000000000000000000000000000000000000000000a21c00000001000003e8002a0000000000000064000000e8d4a510000000a40469d5f147a820bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbaa021388b02102989c0b76cb563971fdc9bef31ec06c3560f3249d6ee9e5d83c57625596e05f6ff0407e645ece0602cddf966b5fcb99cf0829ca3952f5a2401d2c063be0e7895944d61409774afdea389c7486e5eadc74666347307f251444f9ea34f6eb2538848e65";
543 let extra_path_invoice_hex = "00208f483020855be2127df9a1b25963afbb633c183d06d3223cf31942a059fb861b080227100a06636f6666656510c9031b84c5567b126440995d3ed5aaba0565d71e1834604819ff9c17f5e9d5dd078f024d4b6cd1361032ca9bd2aeb9d900aa4d45d9ead80ac9423374c451a7254d07660203462779ad4aad39514614751a71085f2f10e1c7a593e4e030efb5b8721ce55b0b0020000000000000000000000000000000000000000000000000000000000000000002531fe6068134503d2723133227c867ac8fa6c83c537e9a44c3c5bdbdcb1fe3370020000000000000000000000000000000000000000000000000000000000000000052022710582103d084805e2f4c2bcf5188e40e7baec8b8680a1554da028b3d4c25e8969869fbe5a0fd0192031b84c5567b126440995d3ed5aaba0565d71e1834604819ff9c17f5e9d5dd078f024d4b6cd1361032ca9bd2aeb9d900aa4d45d9ead80ac9423374c451a7254d07660203462779ad4aad39514614751a71085f2f10e1c7a593e4e030efb5b8721ce55b0b0020000000000000000000000000000000000000000000000000000000000000000002531fe6068134503d2723133227c867ac8fa6c83c537e9a44c3c5bdbdcb1fe3370020000000000000000000000000000000000000000000000000000000000000000003ff8adab52623bcb2717fc71d7edc6f55e98396e6c234dff01f307a12b2af1c9903d793631af7aa0e709439dd47fc001acd0b0727670b6670ea528ac83cb0127f4a0202a8397a935f0dfceba6ba9618f6451ef4d80637abf4e6af2669fbc9de6a8fd2ac002000000000000000000000000000000000000000000000000000000000000000000257eb3638f51f4dc5c8d5a7324b47df99e816cfcc5b5eb1245bc8c98029f9e67400200000000000000000000000000000000000000000000000000000000000000000a23800000001000003e8002a0000000000000064000000e8d4a51000000000000001000003e8002a0000000000000064000000e8d4a510000000a40469d5f704a820aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa022710b02102531fe6068134503d2723133227c867ac8fa6c83c537e9a44c3c5bdbdcb1fe337f04050faf92c0ac2aebd997ca25cee63f5b3186ef8a7e4dc977289f77130acb37894cc5fd48fb9875335f445b30359892f04954fe2b6623507aca7d403ebcc4ec938";
545
546 let offer = offer_str.parse::<Offer>().unwrap();
548 assert_eq!(offer.issuer_signing_pubkey(), None);
549 assert_eq!(offer.paths().len(), 1, "offer should have blinded paths");
550
551 let secp = Secp256k1::new();
553 let recipient_secret = SecretKey::from_slice(&[0x03; 32]).unwrap();
554 let recipient_keys = Keypair::from_secret_key(&secp, &recipient_secret);
555 assert_eq!(
556 recipient_keys.public_key().to_string(),
557 "02531fe6068134503d2723133227c867ac8fa6c83c537e9a44c3c5bdbdcb1fe337",
558 );
559
560 let invoice_request_bytes = Vec::from_hex(invoice_request_hex).unwrap();
562 let invoice_request = InvoiceRequest::try_from(invoice_request_bytes).unwrap();
563 assert_eq!(invoice_request.issuer_signing_pubkey(), None);
564 assert_eq!(invoice_request.paths().len(), 1, "offer should have blinded paths");
565
566 let invoice_bytes = Vec::from_hex(invoice_hex).unwrap();
568 let invoice = Bolt12Invoice::try_from(invoice_bytes).unwrap();
569
570 assert_eq!(invoice.amount_msats(), 10_000);
571 assert_eq!(invoice.payment_hash(), lightning::types::payment::PaymentHash([0xaa; 32]));
572
573 invoice.validate_issuance(&offer).unwrap();
575 invoice.check_signature().unwrap();
576
577 let invoice_bytes = Vec::from_hex(other_offer_invoice_hex).unwrap();
579 let invoice = Bolt12Invoice::try_from(invoice_bytes).unwrap();
580
581 let err = invoice.validate_issuance(&offer).unwrap_err();
582 assert!(err.to_string().contains("public keys mismatch"), "{:?}", err);
583
584 let invoice_bytes = Vec::from_hex(extra_path_invoice_hex).unwrap();
586 let invoice = Bolt12Invoice::try_from(invoice_bytes).unwrap();
587
588 invoice.validate_issuance(&offer).unwrap();
590 invoice.check_signature().unwrap();
591 }
592}