405ab87be3f11fb25c99a13960d854e6253f2cbe
[rust-lightning] / lightning / src / ln / offers_tests.rs
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 //! Functional tests for the BOLT 12 Offers payment flow.
11 //!
12 //! [`ChannelManager`] provides utilities to create [`Offer`]s and [`Refund`]s along with utilities
13 //! to initiate and request payment for them, respectively. It also manages the payment flow via
14 //! implementing [`OffersMessageHandler`]. This module tests that functionality, including the
15 //! resulting [`Event`] generation.
16 //!
17 //! Two-node success tests use an announced channel:
18 //!
19 //! Alice --- Bob
20 //!
21 //! While two-node failure tests use an unannounced channel:
22 //!
23 //! Alice ... Bob
24 //!
25 //! Six-node tests use unannounced channels for the sender and recipient and announced channels for
26 //! the rest of the network.
27 //!
28 //!               nodes[4]
29 //!              /        \
30 //!             /          \
31 //!            /            \
32 //! Alice ... Bob -------- Charlie ... David
33 //!            \            /
34 //!             \          /
35 //!              \        /
36 //!               nodes[5]
37 //!
38 //! Unnamed nodes are needed to ensure unannounced nodes can create two-hop blinded paths.
39 //!
40 //! Nodes without channels are disconnected and connected as needed to ensure that deterministic
41 //! blinded paths are used.
42
43 use bitcoin::network::Network;
44 use bitcoin::secp256k1::PublicKey;
45 use core::time::Duration;
46 use crate::blinded_path::{BlindedPath, IntroductionNode};
47 use crate::blinded_path::payment::{Bolt12OfferContext, Bolt12RefundContext, PaymentContext};
48 use crate::events::{Event, MessageSendEventsProvider, PaymentPurpose};
49 use crate::ln::channelmanager::{Bolt12PaymentError, MAX_SHORT_LIVED_RELATIVE_EXPIRY, PaymentId, RecentPaymentDetails, Retry, self};
50 use crate::ln::functional_test_utils::*;
51 use crate::ln::msgs::{ChannelMessageHandler, Init, NodeAnnouncement, OnionMessage, OnionMessageHandler, RoutingMessageHandler, SocketAddress, UnsignedGossipMessage, UnsignedNodeAnnouncement};
52 use crate::ln::outbound_payment::IDEMPOTENCY_TIMEOUT_TICKS;
53 use crate::offers::invoice::Bolt12Invoice;
54 use crate::offers::invoice_error::InvoiceError;
55 use crate::offers::invoice_request::{InvoiceRequest, InvoiceRequestFields};
56 use crate::offers::parse::Bolt12SemanticError;
57 use crate::onion_message::messenger::PeeledOnion;
58 use crate::onion_message::offers::OffersMessage;
59 use crate::onion_message::packet::ParsedOnionMessageContents;
60 use crate::routing::gossip::{NodeAlias, NodeId};
61 use crate::sign::{NodeSigner, Recipient};
62
63 use crate::prelude::*;
64
65 macro_rules! expect_recent_payment {
66         ($node: expr, $payment_state: path, $payment_id: expr) => {
67                 match $node.node.list_recent_payments().first() {
68                         Some(&$payment_state { payment_id: actual_payment_id, .. }) => {
69                                 assert_eq!($payment_id, actual_payment_id);
70                         },
71                         Some(_) => panic!("Unexpected recent payment state"),
72                         None => panic!("No recent payments"),
73                 }
74         }
75 }
76
77 fn connect_peers<'a, 'b, 'c>(node_a: &Node<'a, 'b, 'c>, node_b: &Node<'a, 'b, 'c>) {
78         let node_id_a = node_a.node.get_our_node_id();
79         let node_id_b = node_b.node.get_our_node_id();
80
81         let init_a = Init {
82                 features: node_a.init_features(&node_id_b),
83                 networks: None,
84                 remote_network_address: None,
85         };
86         let init_b = Init {
87                 features: node_b.init_features(&node_id_a),
88                 networks: None,
89                 remote_network_address: None,
90         };
91
92         node_a.node.peer_connected(&node_id_b, &init_b, true).unwrap();
93         node_b.node.peer_connected(&node_id_a, &init_a, false).unwrap();
94         node_a.onion_messenger.peer_connected(&node_id_b, &init_b, true).unwrap();
95         node_b.onion_messenger.peer_connected(&node_id_a, &init_a, false).unwrap();
96 }
97
98 fn disconnect_peers<'a, 'b, 'c>(node_a: &Node<'a, 'b, 'c>, peers: &[&Node<'a, 'b, 'c>]) {
99         for node_b in peers {
100                 node_a.node.peer_disconnected(&node_b.node.get_our_node_id());
101                 node_b.node.peer_disconnected(&node_a.node.get_our_node_id());
102                 node_a.onion_messenger.peer_disconnected(&node_b.node.get_our_node_id());
103                 node_b.onion_messenger.peer_disconnected(&node_a.node.get_our_node_id());
104         }
105 }
106
107 fn announce_node_address<'a, 'b, 'c>(
108         node: &Node<'a, 'b, 'c>, peers: &[&Node<'a, 'b, 'c>], address: SocketAddress,
109 ) {
110         let features = node.onion_messenger.provided_node_features()
111                 | node.gossip_sync.provided_node_features();
112         let rgb = [0u8; 3];
113         let announcement = UnsignedNodeAnnouncement {
114                 features,
115                 timestamp: 1000,
116                 node_id: NodeId::from_pubkey(&node.keys_manager.get_node_id(Recipient::Node).unwrap()),
117                 rgb,
118                 alias: NodeAlias([0u8; 32]),
119                 addresses: vec![address],
120                 excess_address_data: Vec::new(),
121                 excess_data: Vec::new(),
122         };
123         let signature = node.keys_manager.sign_gossip_message(
124                 UnsignedGossipMessage::NodeAnnouncement(&announcement)
125         ).unwrap();
126
127         let msg = NodeAnnouncement {
128                 signature,
129                 contents: announcement
130         };
131
132         node.gossip_sync.handle_node_announcement(&msg).unwrap();
133         for peer in peers {
134                 peer.gossip_sync.handle_node_announcement(&msg).unwrap();
135         }
136 }
137
138 fn resolve_introduction_node<'a, 'b, 'c>(node: &Node<'a, 'b, 'c>, path: &BlindedPath) -> PublicKey {
139         path.public_introduction_node_id(&node.network_graph.read_only())
140                 .and_then(|node_id| node_id.as_pubkey().ok())
141                 .unwrap()
142 }
143
144 fn route_bolt12_payment<'a, 'b, 'c>(
145         node: &Node<'a, 'b, 'c>, path: &[&Node<'a, 'b, 'c>], invoice: &Bolt12Invoice
146 ) {
147         // Monitor added when handling the invoice onion message.
148         check_added_monitors(node, 1);
149
150         let mut events = node.node.get_and_clear_pending_msg_events();
151         assert_eq!(events.len(), 1);
152         let ev = remove_first_msg_event_to_node(&path[0].node.get_our_node_id(), &mut events);
153
154         // Use a fake payment_hash and bypass checking for the PaymentClaimable event since the
155         // invoice contains the payment_hash but it was encrypted inside an onion message.
156         let amount_msats = invoice.amount_msats();
157         let payment_hash = invoice.payment_hash();
158         let args = PassAlongPathArgs::new(node, path, amount_msats, payment_hash, ev)
159                 .without_clearing_recipient_events();
160         do_pass_along_path(args);
161 }
162
163 fn claim_bolt12_payment<'a, 'b, 'c>(
164         node: &Node<'a, 'b, 'c>, path: &[&Node<'a, 'b, 'c>], expected_payment_context: PaymentContext
165 ) {
166         let recipient = &path[path.len() - 1];
167         let payment_purpose = match get_event!(recipient, Event::PaymentClaimable) {
168                 Event::PaymentClaimable { purpose, .. } => purpose,
169                 _ => panic!("No Event::PaymentClaimable"),
170         };
171         let payment_preimage = match payment_purpose.preimage() {
172                 Some(preimage) => preimage,
173                 None => panic!("No preimage in Event::PaymentClaimable"),
174         };
175         match payment_purpose {
176                 PaymentPurpose::Bolt12OfferPayment { payment_context, .. } => {
177                         assert_eq!(PaymentContext::Bolt12Offer(payment_context), expected_payment_context);
178                 },
179                 PaymentPurpose::Bolt12RefundPayment { payment_context, .. } => {
180                         assert_eq!(PaymentContext::Bolt12Refund(payment_context), expected_payment_context);
181                 },
182                 _ => panic!("Unexpected payment purpose: {:?}", payment_purpose),
183         }
184         claim_payment(node, path, payment_preimage);
185 }
186
187 fn extract_invoice_request<'a, 'b, 'c>(
188         node: &Node<'a, 'b, 'c>, message: &OnionMessage
189 ) -> (InvoiceRequest, BlindedPath) {
190         match node.onion_messenger.peel_onion_message(message) {
191                 Ok(PeeledOnion::Receive(message, _, reply_path)) => match message {
192                         ParsedOnionMessageContents::Offers(offers_message) => match offers_message {
193                                 OffersMessage::InvoiceRequest(invoice_request) => (invoice_request, reply_path.unwrap()),
194                                 OffersMessage::Invoice(invoice) => panic!("Unexpected invoice: {:?}", invoice),
195                                 #[cfg(async_payments)]
196                                 OffersMessage::StaticInvoice(invoice) => panic!("Unexpected static invoice: {:?}", invoice),
197                                 OffersMessage::InvoiceError(error) => panic!("Unexpected invoice_error: {:?}", error),
198                         },
199                         #[cfg(async_payments)]
200                         ParsedOnionMessageContents::AsyncPayments(message) => panic!("Unexpected async payments message: {:?}", message),
201                         ParsedOnionMessageContents::Custom(message) => panic!("Unexpected custom message: {:?}", message),
202                 },
203                 Ok(PeeledOnion::Forward(_, _)) => panic!("Unexpected onion message forward"),
204                 Err(e) => panic!("Failed to process onion message {:?}", e),
205         }
206 }
207
208 fn extract_invoice<'a, 'b, 'c>(node: &Node<'a, 'b, 'c>, message: &OnionMessage) -> Bolt12Invoice {
209         match node.onion_messenger.peel_onion_message(message) {
210                 Ok(PeeledOnion::Receive(message, _, _)) => match message {
211                         ParsedOnionMessageContents::Offers(offers_message) => match offers_message {
212                                 OffersMessage::InvoiceRequest(invoice_request) => panic!("Unexpected invoice_request: {:?}", invoice_request),
213                                 OffersMessage::Invoice(invoice) => invoice,
214                                 #[cfg(async_payments)]
215                                 OffersMessage::StaticInvoice(invoice) => panic!("Unexpected static invoice: {:?}", invoice),
216                                 OffersMessage::InvoiceError(error) => panic!("Unexpected invoice_error: {:?}", error),
217                         },
218                         #[cfg(async_payments)]
219                         ParsedOnionMessageContents::AsyncPayments(message) => panic!("Unexpected async payments message: {:?}", message),
220                         ParsedOnionMessageContents::Custom(message) => panic!("Unexpected custom message: {:?}", message),
221                 },
222                 Ok(PeeledOnion::Forward(_, _)) => panic!("Unexpected onion message forward"),
223                 Err(e) => panic!("Failed to process onion message {:?}", e),
224         }
225 }
226
227 fn extract_invoice_error<'a, 'b, 'c>(
228         node: &Node<'a, 'b, 'c>, message: &OnionMessage
229 ) -> InvoiceError {
230         match node.onion_messenger.peel_onion_message(message) {
231                 Ok(PeeledOnion::Receive(message, _, _)) => match message {
232                         ParsedOnionMessageContents::Offers(offers_message) => match offers_message {
233                                 OffersMessage::InvoiceRequest(invoice_request) => panic!("Unexpected invoice_request: {:?}", invoice_request),
234                                 OffersMessage::Invoice(invoice) => panic!("Unexpected invoice: {:?}", invoice),
235                                 #[cfg(async_payments)]
236                                 OffersMessage::StaticInvoice(invoice) => panic!("Unexpected invoice: {:?}", invoice),
237                                 OffersMessage::InvoiceError(error) => error,
238                         },
239                         #[cfg(async_payments)]
240                         ParsedOnionMessageContents::AsyncPayments(message) => panic!("Unexpected async payments message: {:?}", message),
241                         ParsedOnionMessageContents::Custom(message) => panic!("Unexpected custom message: {:?}", message),
242                 },
243                 Ok(PeeledOnion::Forward(_, _)) => panic!("Unexpected onion message forward"),
244                 Err(e) => panic!("Failed to process onion message {:?}", e),
245         }
246 }
247
248 /// Checks that blinded paths without Tor-only nodes are preferred when constructing an offer.
249 #[test]
250 fn prefers_non_tor_nodes_in_blinded_paths() {
251         let mut accept_forward_cfg = test_default_channel_config();
252         accept_forward_cfg.accept_forwards_to_priv_channels = true;
253
254         let mut features = channelmanager::provided_init_features(&accept_forward_cfg);
255         features.set_onion_messages_optional();
256         features.set_route_blinding_optional();
257
258         let chanmon_cfgs = create_chanmon_cfgs(6);
259         let node_cfgs = create_node_cfgs(6, &chanmon_cfgs);
260
261         *node_cfgs[1].override_init_features.borrow_mut() = Some(features);
262
263         let node_chanmgrs = create_node_chanmgrs(
264                 6, &node_cfgs, &[None, Some(accept_forward_cfg), None, None, None, None]
265         );
266         let nodes = create_network(6, &node_cfgs, &node_chanmgrs);
267
268         create_unannounced_chan_between_nodes_with_value(&nodes, 0, 1, 10_000_000, 1_000_000_000);
269         create_unannounced_chan_between_nodes_with_value(&nodes, 2, 3, 10_000_000, 1_000_000_000);
270         create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 10_000_000, 1_000_000_000);
271         create_announced_chan_between_nodes_with_value(&nodes, 1, 4, 10_000_000, 1_000_000_000);
272         create_announced_chan_between_nodes_with_value(&nodes, 1, 5, 10_000_000, 1_000_000_000);
273         create_announced_chan_between_nodes_with_value(&nodes, 2, 4, 10_000_000, 1_000_000_000);
274         create_announced_chan_between_nodes_with_value(&nodes, 2, 5, 10_000_000, 1_000_000_000);
275
276         // Add an extra channel so that more than one of Bob's peers have MIN_PEER_CHANNELS.
277         create_announced_chan_between_nodes_with_value(&nodes, 4, 5, 10_000_000, 1_000_000_000);
278
279         let (alice, bob, charlie, david) = (&nodes[0], &nodes[1], &nodes[2], &nodes[3]);
280         let bob_id = bob.node.get_our_node_id();
281         let charlie_id = charlie.node.get_our_node_id();
282
283         disconnect_peers(alice, &[charlie, david, &nodes[4], &nodes[5]]);
284         disconnect_peers(david, &[bob, &nodes[4], &nodes[5]]);
285
286         let tor = SocketAddress::OnionV2([255, 254, 253, 252, 251, 250, 249, 248, 247, 246, 38, 7]);
287         announce_node_address(charlie, &[alice, bob, david, &nodes[4], &nodes[5]], tor.clone());
288
289         let offer = bob.node
290                 .create_offer_builder(None).unwrap()
291                 .amount_msats(10_000_000)
292                 .build().unwrap();
293         assert_ne!(offer.signing_pubkey(), Some(bob_id));
294         assert!(!offer.paths().is_empty());
295         for path in offer.paths() {
296                 let introduction_node_id = resolve_introduction_node(david, &path);
297                 assert_ne!(introduction_node_id, bob_id);
298                 assert_ne!(introduction_node_id, charlie_id);
299         }
300
301         // Use a one-hop blinded path when Bob is announced and all his peers are Tor-only.
302         announce_node_address(&nodes[4], &[alice, bob, charlie, david, &nodes[5]], tor.clone());
303         announce_node_address(&nodes[5], &[alice, bob, charlie, david, &nodes[4]], tor.clone());
304
305         let offer = bob.node
306                 .create_offer_builder(None).unwrap()
307                 .amount_msats(10_000_000)
308                 .build().unwrap();
309         assert_ne!(offer.signing_pubkey(), Some(bob_id));
310         assert!(!offer.paths().is_empty());
311         for path in offer.paths() {
312                 let introduction_node_id = resolve_introduction_node(david, &path);
313                 assert_eq!(introduction_node_id, bob_id);
314         }
315 }
316
317 /// Checks that blinded paths prefer an introduction node that is the most connected.
318 #[test]
319 fn prefers_more_connected_nodes_in_blinded_paths() {
320         let mut accept_forward_cfg = test_default_channel_config();
321         accept_forward_cfg.accept_forwards_to_priv_channels = true;
322
323         let mut features = channelmanager::provided_init_features(&accept_forward_cfg);
324         features.set_onion_messages_optional();
325         features.set_route_blinding_optional();
326
327         let chanmon_cfgs = create_chanmon_cfgs(6);
328         let node_cfgs = create_node_cfgs(6, &chanmon_cfgs);
329
330         *node_cfgs[1].override_init_features.borrow_mut() = Some(features);
331
332         let node_chanmgrs = create_node_chanmgrs(
333                 6, &node_cfgs, &[None, Some(accept_forward_cfg), None, None, None, None]
334         );
335         let nodes = create_network(6, &node_cfgs, &node_chanmgrs);
336
337         create_unannounced_chan_between_nodes_with_value(&nodes, 0, 1, 10_000_000, 1_000_000_000);
338         create_unannounced_chan_between_nodes_with_value(&nodes, 2, 3, 10_000_000, 1_000_000_000);
339         create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 10_000_000, 1_000_000_000);
340         create_announced_chan_between_nodes_with_value(&nodes, 1, 4, 10_000_000, 1_000_000_000);
341         create_announced_chan_between_nodes_with_value(&nodes, 1, 5, 10_000_000, 1_000_000_000);
342         create_announced_chan_between_nodes_with_value(&nodes, 2, 4, 10_000_000, 1_000_000_000);
343         create_announced_chan_between_nodes_with_value(&nodes, 2, 5, 10_000_000, 1_000_000_000);
344
345         // Add extra channels so that more than one of Bob's peers have MIN_PEER_CHANNELS and one has
346         // more than the others.
347         create_announced_chan_between_nodes_with_value(&nodes, 0, 4, 10_000_000, 1_000_000_000);
348         create_announced_chan_between_nodes_with_value(&nodes, 3, 4, 10_000_000, 1_000_000_000);
349
350         let (alice, bob, charlie, david) = (&nodes[0], &nodes[1], &nodes[2], &nodes[3]);
351         let bob_id = bob.node.get_our_node_id();
352
353         disconnect_peers(alice, &[charlie, david, &nodes[4], &nodes[5]]);
354         disconnect_peers(david, &[bob, &nodes[4], &nodes[5]]);
355
356         let offer = bob.node
357                 .create_offer_builder(None).unwrap()
358                 .amount_msats(10_000_000)
359                 .build().unwrap();
360         assert_ne!(offer.signing_pubkey(), Some(bob_id));
361         assert!(!offer.paths().is_empty());
362         for path in offer.paths() {
363                 let introduction_node_id = resolve_introduction_node(david, &path);
364                 assert_eq!(introduction_node_id, nodes[4].node.get_our_node_id());
365         }
366 }
367
368 /// Checks that blinded paths are compact for short-lived offers.
369 #[test]
370 fn creates_short_lived_offer() {
371         let chanmon_cfgs = create_chanmon_cfgs(2);
372         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
373         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
374         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
375
376         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 10_000_000, 1_000_000_000);
377
378         let alice = &nodes[0];
379         let alice_id = alice.node.get_our_node_id();
380         let bob = &nodes[1];
381
382         let absolute_expiry = alice.node.duration_since_epoch() + MAX_SHORT_LIVED_RELATIVE_EXPIRY;
383         let offer = alice.node
384                 .create_offer_builder(Some(absolute_expiry)).unwrap()
385                 .build().unwrap();
386         assert_eq!(offer.absolute_expiry(), Some(absolute_expiry));
387         assert!(!offer.paths().is_empty());
388         for path in offer.paths() {
389                 let introduction_node_id = resolve_introduction_node(bob, &path);
390                 assert_eq!(introduction_node_id, alice_id);
391                 assert!(matches!(path.introduction_node, IntroductionNode::DirectedShortChannelId(..)));
392         }
393 }
394
395 /// Checks that blinded paths are not compact for long-lived offers.
396 #[test]
397 fn creates_long_lived_offer() {
398         let chanmon_cfgs = create_chanmon_cfgs(2);
399         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
400         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
401         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
402
403         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 10_000_000, 1_000_000_000);
404
405         let alice = &nodes[0];
406         let alice_id = alice.node.get_our_node_id();
407
408         let absolute_expiry = alice.node.duration_since_epoch() + MAX_SHORT_LIVED_RELATIVE_EXPIRY
409                 + Duration::from_secs(1);
410         let offer = alice.node
411                 .create_offer_builder(Some(absolute_expiry))
412                 .unwrap()
413                 .build().unwrap();
414         assert_eq!(offer.absolute_expiry(), Some(absolute_expiry));
415         assert!(!offer.paths().is_empty());
416         for path in offer.paths() {
417                 assert_eq!(path.introduction_node, IntroductionNode::NodeId(alice_id));
418         }
419
420         let offer = alice.node
421                 .create_offer_builder(None).unwrap()
422                 .build().unwrap();
423         assert_eq!(offer.absolute_expiry(), None);
424         assert!(!offer.paths().is_empty());
425         for path in offer.paths() {
426                 assert_eq!(path.introduction_node, IntroductionNode::NodeId(alice_id));
427         }
428 }
429
430 /// Checks that blinded paths are compact for short-lived refunds.
431 #[test]
432 fn creates_short_lived_refund() {
433         let chanmon_cfgs = create_chanmon_cfgs(2);
434         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
435         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
436         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
437
438         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 10_000_000, 1_000_000_000);
439
440         let alice = &nodes[0];
441         let bob = &nodes[1];
442         let bob_id = bob.node.get_our_node_id();
443
444         let absolute_expiry = bob.node.duration_since_epoch() + MAX_SHORT_LIVED_RELATIVE_EXPIRY;
445         let payment_id = PaymentId([1; 32]);
446         let refund = bob.node
447                 .create_refund_builder(10_000_000, absolute_expiry, payment_id, Retry::Attempts(0), None)
448                 .unwrap()
449                 .build().unwrap();
450         assert_eq!(refund.absolute_expiry(), Some(absolute_expiry));
451         assert!(!refund.paths().is_empty());
452         for path in refund.paths() {
453                 let introduction_node_id = resolve_introduction_node(alice, &path);
454                 assert_eq!(introduction_node_id, bob_id);
455                 assert!(matches!(path.introduction_node, IntroductionNode::DirectedShortChannelId(..)));
456         }
457 }
458
459 /// Checks that blinded paths are not compact for long-lived refunds.
460 #[test]
461 fn creates_long_lived_refund() {
462         let chanmon_cfgs = create_chanmon_cfgs(2);
463         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
464         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
465         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
466
467         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 10_000_000, 1_000_000_000);
468
469         let bob = &nodes[1];
470         let bob_id = bob.node.get_our_node_id();
471
472         let absolute_expiry = bob.node.duration_since_epoch() + MAX_SHORT_LIVED_RELATIVE_EXPIRY
473                 + Duration::from_secs(1);
474         let payment_id = PaymentId([1; 32]);
475         let refund = bob.node
476                 .create_refund_builder(10_000_000, absolute_expiry, payment_id, Retry::Attempts(0), None)
477                 .unwrap()
478                 .build().unwrap();
479         assert_eq!(refund.absolute_expiry(), Some(absolute_expiry));
480         assert!(!refund.paths().is_empty());
481         for path in refund.paths() {
482                 assert_eq!(path.introduction_node, IntroductionNode::NodeId(bob_id));
483         }
484 }
485
486 /// Checks that an offer can be paid through blinded paths and that ephemeral pubkeys are used
487 /// rather than exposing a node's pubkey.
488 #[test]
489 fn creates_and_pays_for_offer_using_two_hop_blinded_path() {
490         let mut accept_forward_cfg = test_default_channel_config();
491         accept_forward_cfg.accept_forwards_to_priv_channels = true;
492
493         let mut features = channelmanager::provided_init_features(&accept_forward_cfg);
494         features.set_onion_messages_optional();
495         features.set_route_blinding_optional();
496
497         let chanmon_cfgs = create_chanmon_cfgs(6);
498         let node_cfgs = create_node_cfgs(6, &chanmon_cfgs);
499
500         *node_cfgs[1].override_init_features.borrow_mut() = Some(features);
501
502         let node_chanmgrs = create_node_chanmgrs(
503                 6, &node_cfgs, &[None, Some(accept_forward_cfg), None, None, None, None]
504         );
505         let nodes = create_network(6, &node_cfgs, &node_chanmgrs);
506
507         create_unannounced_chan_between_nodes_with_value(&nodes, 0, 1, 10_000_000, 1_000_000_000);
508         create_unannounced_chan_between_nodes_with_value(&nodes, 2, 3, 10_000_000, 1_000_000_000);
509         create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 10_000_000, 1_000_000_000);
510         create_announced_chan_between_nodes_with_value(&nodes, 1, 4, 10_000_000, 1_000_000_000);
511         create_announced_chan_between_nodes_with_value(&nodes, 1, 5, 10_000_000, 1_000_000_000);
512         create_announced_chan_between_nodes_with_value(&nodes, 2, 4, 10_000_000, 1_000_000_000);
513         create_announced_chan_between_nodes_with_value(&nodes, 2, 5, 10_000_000, 1_000_000_000);
514
515         let (alice, bob, charlie, david) = (&nodes[0], &nodes[1], &nodes[2], &nodes[3]);
516         let alice_id = alice.node.get_our_node_id();
517         let bob_id = bob.node.get_our_node_id();
518         let charlie_id = charlie.node.get_our_node_id();
519         let david_id = david.node.get_our_node_id();
520
521         disconnect_peers(alice, &[charlie, david, &nodes[4], &nodes[5]]);
522         disconnect_peers(david, &[bob, &nodes[4], &nodes[5]]);
523
524         let offer = alice.node
525                 .create_offer_builder(None)
526                 .unwrap()
527                 .amount_msats(10_000_000)
528                 .build().unwrap();
529         assert_ne!(offer.signing_pubkey(), Some(alice_id));
530         assert!(!offer.paths().is_empty());
531         for path in offer.paths() {
532                 assert_eq!(path.introduction_node, IntroductionNode::NodeId(bob_id));
533         }
534
535         let payment_id = PaymentId([1; 32]);
536         david.node.pay_for_offer(&offer, None, None, None, payment_id, Retry::Attempts(0), None)
537                 .unwrap();
538         expect_recent_payment!(david, RecentPaymentDetails::AwaitingInvoice, payment_id);
539
540         connect_peers(david, bob);
541
542         let onion_message = david.onion_messenger.next_onion_message_for_peer(bob_id).unwrap();
543         bob.onion_messenger.handle_onion_message(&david_id, &onion_message);
544
545         connect_peers(alice, charlie);
546
547         let onion_message = bob.onion_messenger.next_onion_message_for_peer(alice_id).unwrap();
548         alice.onion_messenger.handle_onion_message(&bob_id, &onion_message);
549
550         let (invoice_request, reply_path) = extract_invoice_request(alice, &onion_message);
551         let payment_context = PaymentContext::Bolt12Offer(Bolt12OfferContext {
552                 offer_id: offer.id(),
553                 invoice_request: InvoiceRequestFields {
554                         payer_id: invoice_request.payer_id(),
555                         quantity: None,
556                         payer_note_truncated: None,
557                 },
558         });
559         assert_eq!(invoice_request.amount_msats(), None);
560         assert_ne!(invoice_request.payer_id(), david_id);
561         assert_eq!(reply_path.introduction_node, IntroductionNode::NodeId(charlie_id));
562
563         let onion_message = alice.onion_messenger.next_onion_message_for_peer(charlie_id).unwrap();
564         charlie.onion_messenger.handle_onion_message(&alice_id, &onion_message);
565
566         let onion_message = charlie.onion_messenger.next_onion_message_for_peer(david_id).unwrap();
567         david.onion_messenger.handle_onion_message(&charlie_id, &onion_message);
568
569         let invoice = extract_invoice(david, &onion_message);
570         assert_eq!(invoice.amount_msats(), 10_000_000);
571         assert_ne!(invoice.signing_pubkey(), alice_id);
572         assert!(!invoice.payment_paths().is_empty());
573         for (_, path) in invoice.payment_paths() {
574                 assert_eq!(path.introduction_node, IntroductionNode::NodeId(bob_id));
575         }
576
577         route_bolt12_payment(david, &[charlie, bob, alice], &invoice);
578         expect_recent_payment!(david, RecentPaymentDetails::Pending, payment_id);
579
580         claim_bolt12_payment(david, &[charlie, bob, alice], payment_context);
581         expect_recent_payment!(david, RecentPaymentDetails::Fulfilled, payment_id);
582 }
583
584 /// Checks that a refund can be paid through blinded paths and that ephemeral pubkeys are used
585 /// rather than exposing a node's pubkey.
586 #[test]
587 fn creates_and_pays_for_refund_using_two_hop_blinded_path() {
588         let mut accept_forward_cfg = test_default_channel_config();
589         accept_forward_cfg.accept_forwards_to_priv_channels = true;
590
591         let mut features = channelmanager::provided_init_features(&accept_forward_cfg);
592         features.set_onion_messages_optional();
593         features.set_route_blinding_optional();
594
595         let chanmon_cfgs = create_chanmon_cfgs(6);
596         let node_cfgs = create_node_cfgs(6, &chanmon_cfgs);
597
598         *node_cfgs[1].override_init_features.borrow_mut() = Some(features);
599
600         let node_chanmgrs = create_node_chanmgrs(
601                 6, &node_cfgs, &[None, Some(accept_forward_cfg), None, None, None, None]
602         );
603         let nodes = create_network(6, &node_cfgs, &node_chanmgrs);
604
605         create_unannounced_chan_between_nodes_with_value(&nodes, 0, 1, 10_000_000, 1_000_000_000);
606         create_unannounced_chan_between_nodes_with_value(&nodes, 2, 3, 10_000_000, 1_000_000_000);
607         create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 10_000_000, 1_000_000_000);
608         create_announced_chan_between_nodes_with_value(&nodes, 1, 4, 10_000_000, 1_000_000_000);
609         create_announced_chan_between_nodes_with_value(&nodes, 1, 5, 10_000_000, 1_000_000_000);
610         create_announced_chan_between_nodes_with_value(&nodes, 2, 4, 10_000_000, 1_000_000_000);
611         create_announced_chan_between_nodes_with_value(&nodes, 2, 5, 10_000_000, 1_000_000_000);
612
613         let (alice, bob, charlie, david) = (&nodes[0], &nodes[1], &nodes[2], &nodes[3]);
614         let alice_id = alice.node.get_our_node_id();
615         let bob_id = bob.node.get_our_node_id();
616         let charlie_id = charlie.node.get_our_node_id();
617         let david_id = david.node.get_our_node_id();
618
619         disconnect_peers(alice, &[charlie, david, &nodes[4], &nodes[5]]);
620         disconnect_peers(david, &[bob, &nodes[4], &nodes[5]]);
621
622         let absolute_expiry = Duration::from_secs(u64::MAX);
623         let payment_id = PaymentId([1; 32]);
624         let refund = david.node
625                 .create_refund_builder(10_000_000, absolute_expiry, payment_id, Retry::Attempts(0), None)
626                 .unwrap()
627                 .build().unwrap();
628         assert_eq!(refund.amount_msats(), 10_000_000);
629         assert_eq!(refund.absolute_expiry(), Some(absolute_expiry));
630         assert_ne!(refund.payer_id(), david_id);
631         assert!(!refund.paths().is_empty());
632         for path in refund.paths() {
633                 assert_eq!(path.introduction_node, IntroductionNode::NodeId(charlie_id));
634         }
635         expect_recent_payment!(david, RecentPaymentDetails::AwaitingInvoice, payment_id);
636
637         let payment_context = PaymentContext::Bolt12Refund(Bolt12RefundContext {});
638         let expected_invoice = alice.node.request_refund_payment(&refund).unwrap();
639
640         connect_peers(alice, charlie);
641
642         let onion_message = alice.onion_messenger.next_onion_message_for_peer(charlie_id).unwrap();
643         charlie.onion_messenger.handle_onion_message(&alice_id, &onion_message);
644
645         let onion_message = charlie.onion_messenger.next_onion_message_for_peer(david_id).unwrap();
646         david.onion_messenger.handle_onion_message(&charlie_id, &onion_message);
647
648         let invoice = extract_invoice(david, &onion_message);
649         assert_eq!(invoice, expected_invoice);
650
651         assert_eq!(invoice.amount_msats(), 10_000_000);
652         assert_ne!(invoice.signing_pubkey(), alice_id);
653         assert!(!invoice.payment_paths().is_empty());
654         for (_, path) in invoice.payment_paths() {
655                 assert_eq!(path.introduction_node, IntroductionNode::NodeId(bob_id));
656         }
657
658         route_bolt12_payment(david, &[charlie, bob, alice], &invoice);
659         expect_recent_payment!(david, RecentPaymentDetails::Pending, payment_id);
660
661         claim_bolt12_payment(david, &[charlie, bob, alice], payment_context);
662         expect_recent_payment!(david, RecentPaymentDetails::Fulfilled, payment_id);
663 }
664
665 /// Checks that an offer can be paid through a one-hop blinded path and that ephemeral pubkeys are
666 /// used rather than exposing a node's pubkey. However, the node's pubkey is still used as the
667 /// introduction node of the blinded path.
668 #[test]
669 fn creates_and_pays_for_offer_using_one_hop_blinded_path() {
670         let chanmon_cfgs = create_chanmon_cfgs(2);
671         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
672         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
673         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
674
675         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 10_000_000, 1_000_000_000);
676
677         let alice = &nodes[0];
678         let alice_id = alice.node.get_our_node_id();
679         let bob = &nodes[1];
680         let bob_id = bob.node.get_our_node_id();
681
682         let offer = alice.node
683                 .create_offer_builder(None).unwrap()
684                 .amount_msats(10_000_000)
685                 .build().unwrap();
686         assert_ne!(offer.signing_pubkey(), Some(alice_id));
687         assert!(!offer.paths().is_empty());
688         for path in offer.paths() {
689                 assert_eq!(path.introduction_node, IntroductionNode::NodeId(alice_id));
690         }
691
692         let payment_id = PaymentId([1; 32]);
693         bob.node.pay_for_offer(&offer, None, None, None, payment_id, Retry::Attempts(0), None).unwrap();
694         expect_recent_payment!(bob, RecentPaymentDetails::AwaitingInvoice, payment_id);
695
696         let onion_message = bob.onion_messenger.next_onion_message_for_peer(alice_id).unwrap();
697         alice.onion_messenger.handle_onion_message(&bob_id, &onion_message);
698
699         let (invoice_request, reply_path) = extract_invoice_request(alice, &onion_message);
700         let payment_context = PaymentContext::Bolt12Offer(Bolt12OfferContext {
701                 offer_id: offer.id(),
702                 invoice_request: InvoiceRequestFields {
703                         payer_id: invoice_request.payer_id(),
704                         quantity: None,
705                         payer_note_truncated: None,
706                 },
707         });
708         assert_eq!(invoice_request.amount_msats(), None);
709         assert_ne!(invoice_request.payer_id(), bob_id);
710         assert_eq!(reply_path.introduction_node, IntroductionNode::NodeId(bob_id));
711
712         let onion_message = alice.onion_messenger.next_onion_message_for_peer(bob_id).unwrap();
713         bob.onion_messenger.handle_onion_message(&alice_id, &onion_message);
714
715         let invoice = extract_invoice(bob, &onion_message);
716         assert_eq!(invoice.amount_msats(), 10_000_000);
717         assert_ne!(invoice.signing_pubkey(), alice_id);
718         assert!(!invoice.payment_paths().is_empty());
719         for (_, path) in invoice.payment_paths() {
720                 assert_eq!(path.introduction_node, IntroductionNode::NodeId(alice_id));
721         }
722
723         route_bolt12_payment(bob, &[alice], &invoice);
724         expect_recent_payment!(bob, RecentPaymentDetails::Pending, payment_id);
725
726         claim_bolt12_payment(bob, &[alice], payment_context);
727         expect_recent_payment!(bob, RecentPaymentDetails::Fulfilled, payment_id);
728 }
729
730 /// Checks that a refund can be paid through a one-hop blinded path and that ephemeral pubkeys are
731 /// used rather than exposing a node's pubkey. However, the node's pubkey is still used as the
732 /// introduction node of the blinded path.
733 #[test]
734 fn creates_and_pays_for_refund_using_one_hop_blinded_path() {
735         let chanmon_cfgs = create_chanmon_cfgs(2);
736         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
737         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
738         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
739
740         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 10_000_000, 1_000_000_000);
741
742         let alice = &nodes[0];
743         let alice_id = alice.node.get_our_node_id();
744         let bob = &nodes[1];
745         let bob_id = bob.node.get_our_node_id();
746
747         let absolute_expiry = Duration::from_secs(u64::MAX);
748         let payment_id = PaymentId([1; 32]);
749         let refund = bob.node
750                 .create_refund_builder(10_000_000, absolute_expiry, payment_id, Retry::Attempts(0), None)
751                 .unwrap()
752                 .build().unwrap();
753         assert_eq!(refund.amount_msats(), 10_000_000);
754         assert_eq!(refund.absolute_expiry(), Some(absolute_expiry));
755         assert_ne!(refund.payer_id(), bob_id);
756         assert!(!refund.paths().is_empty());
757         for path in refund.paths() {
758                 assert_eq!(path.introduction_node, IntroductionNode::NodeId(bob_id));
759         }
760         expect_recent_payment!(bob, RecentPaymentDetails::AwaitingInvoice, payment_id);
761
762         let payment_context = PaymentContext::Bolt12Refund(Bolt12RefundContext {});
763         let expected_invoice = alice.node.request_refund_payment(&refund).unwrap();
764
765         let onion_message = alice.onion_messenger.next_onion_message_for_peer(bob_id).unwrap();
766         bob.onion_messenger.handle_onion_message(&alice_id, &onion_message);
767
768         let invoice = extract_invoice(bob, &onion_message);
769         assert_eq!(invoice, expected_invoice);
770
771         assert_eq!(invoice.amount_msats(), 10_000_000);
772         assert_ne!(invoice.signing_pubkey(), alice_id);
773         assert!(!invoice.payment_paths().is_empty());
774         for (_, path) in invoice.payment_paths() {
775                 assert_eq!(path.introduction_node, IntroductionNode::NodeId(alice_id));
776         }
777
778         route_bolt12_payment(bob, &[alice], &invoice);
779         expect_recent_payment!(bob, RecentPaymentDetails::Pending, payment_id);
780
781         claim_bolt12_payment(bob, &[alice], payment_context);
782         expect_recent_payment!(bob, RecentPaymentDetails::Fulfilled, payment_id);
783 }
784
785 /// Checks that an invoice for an offer without any blinded paths can be requested. Note that while
786 /// the requested is sent directly using the node's pubkey, the response and the payment still use
787 /// blinded paths as required by the spec.
788 #[test]
789 fn pays_for_offer_without_blinded_paths() {
790         let chanmon_cfgs = create_chanmon_cfgs(2);
791         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
792         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
793         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
794
795         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 10_000_000, 1_000_000_000);
796
797         let alice = &nodes[0];
798         let alice_id = alice.node.get_our_node_id();
799         let bob = &nodes[1];
800         let bob_id = bob.node.get_our_node_id();
801
802         let offer = alice.node
803                 .create_offer_builder(None).unwrap()
804                 .clear_paths()
805                 .amount_msats(10_000_000)
806                 .build().unwrap();
807         assert_eq!(offer.signing_pubkey(), Some(alice_id));
808         assert!(offer.paths().is_empty());
809
810         let payment_id = PaymentId([1; 32]);
811         bob.node.pay_for_offer(&offer, None, None, None, payment_id, Retry::Attempts(0), None).unwrap();
812         expect_recent_payment!(bob, RecentPaymentDetails::AwaitingInvoice, payment_id);
813
814         let onion_message = bob.onion_messenger.next_onion_message_for_peer(alice_id).unwrap();
815         alice.onion_messenger.handle_onion_message(&bob_id, &onion_message);
816
817         let (invoice_request, _) = extract_invoice_request(alice, &onion_message);
818         let payment_context = PaymentContext::Bolt12Offer(Bolt12OfferContext {
819                 offer_id: offer.id(),
820                 invoice_request: InvoiceRequestFields {
821                         payer_id: invoice_request.payer_id(),
822                         quantity: None,
823                         payer_note_truncated: None,
824                 },
825         });
826
827         let onion_message = alice.onion_messenger.next_onion_message_for_peer(bob_id).unwrap();
828         bob.onion_messenger.handle_onion_message(&alice_id, &onion_message);
829
830         let invoice = extract_invoice(bob, &onion_message);
831         route_bolt12_payment(bob, &[alice], &invoice);
832         expect_recent_payment!(bob, RecentPaymentDetails::Pending, payment_id);
833
834         claim_bolt12_payment(bob, &[alice], payment_context);
835         expect_recent_payment!(bob, RecentPaymentDetails::Fulfilled, payment_id);
836 }
837
838 /// Checks that a refund without any blinded paths can be paid. Note that while the invoice is sent
839 /// directly using the node's pubkey, the payment still use blinded paths as required by the spec.
840 #[test]
841 fn pays_for_refund_without_blinded_paths() {
842         let chanmon_cfgs = create_chanmon_cfgs(2);
843         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
844         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
845         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
846
847         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 10_000_000, 1_000_000_000);
848
849         let alice = &nodes[0];
850         let alice_id = alice.node.get_our_node_id();
851         let bob = &nodes[1];
852         let bob_id = bob.node.get_our_node_id();
853
854         let absolute_expiry = Duration::from_secs(u64::MAX);
855         let payment_id = PaymentId([1; 32]);
856         let refund = bob.node
857                 .create_refund_builder(10_000_000, absolute_expiry, payment_id, Retry::Attempts(0), None)
858                 .unwrap()
859                 .clear_paths()
860                 .build().unwrap();
861         assert_eq!(refund.payer_id(), bob_id);
862         assert!(refund.paths().is_empty());
863         expect_recent_payment!(bob, RecentPaymentDetails::AwaitingInvoice, payment_id);
864
865         let payment_context = PaymentContext::Bolt12Refund(Bolt12RefundContext {});
866         let expected_invoice = alice.node.request_refund_payment(&refund).unwrap();
867
868         let onion_message = alice.onion_messenger.next_onion_message_for_peer(bob_id).unwrap();
869         bob.onion_messenger.handle_onion_message(&alice_id, &onion_message);
870
871         let invoice = extract_invoice(bob, &onion_message);
872         assert_eq!(invoice, expected_invoice);
873
874         route_bolt12_payment(bob, &[alice], &invoice);
875         expect_recent_payment!(bob, RecentPaymentDetails::Pending, payment_id);
876
877         claim_bolt12_payment(bob, &[alice], payment_context);
878         expect_recent_payment!(bob, RecentPaymentDetails::Fulfilled, payment_id);
879 }
880
881 /// Checks that a deferred invoice can be paid asynchronously from an Event::InvoiceReceived.
882 #[test]
883 fn pays_bolt12_invoice_asynchronously() {
884         let mut manually_pay_cfg = test_default_channel_config();
885         manually_pay_cfg.manually_handle_bolt12_invoices = true;
886
887         let chanmon_cfgs = create_chanmon_cfgs(2);
888         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
889         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_pay_cfg)]);
890         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
891
892         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 10_000_000, 1_000_000_000);
893
894         let alice = &nodes[0];
895         let alice_id = alice.node.get_our_node_id();
896         let bob = &nodes[1];
897         let bob_id = bob.node.get_our_node_id();
898
899         let offer = alice.node
900                 .create_offer_builder(None).unwrap()
901                 .amount_msats(10_000_000)
902                 .build().unwrap();
903
904         let payment_id = PaymentId([1; 32]);
905         bob.node.pay_for_offer(&offer, None, None, None, payment_id, Retry::Attempts(0), None).unwrap();
906         expect_recent_payment!(bob, RecentPaymentDetails::AwaitingInvoice, payment_id);
907
908         let onion_message = bob.onion_messenger.next_onion_message_for_peer(alice_id).unwrap();
909         alice.onion_messenger.handle_onion_message(&bob_id, &onion_message);
910
911         let (invoice_request, _) = extract_invoice_request(alice, &onion_message);
912         let payment_context = PaymentContext::Bolt12Offer(Bolt12OfferContext {
913                 offer_id: offer.id(),
914                 invoice_request: InvoiceRequestFields {
915                         payer_id: invoice_request.payer_id(),
916                         quantity: None,
917                         payer_note_truncated: None,
918                 },
919         });
920
921         let onion_message = alice.onion_messenger.next_onion_message_for_peer(bob_id).unwrap();
922         bob.onion_messenger.handle_onion_message(&alice_id, &onion_message);
923
924         let invoice = match get_event!(bob, Event::InvoiceReceived) {
925                 Event::InvoiceReceived { payment_id: actual_payment_id, invoice, .. } => {
926                         assert_eq!(actual_payment_id, payment_id);
927                         invoice
928                 },
929                 _ => panic!("No Event::InvoiceReceived"),
930         };
931         assert_eq!(invoice.amount_msats(), 10_000_000);
932         assert_ne!(invoice.signing_pubkey(), alice_id);
933         assert!(!invoice.payment_paths().is_empty());
934         for (_, path) in invoice.payment_paths() {
935                 assert_eq!(path.introduction_node, IntroductionNode::NodeId(alice_id));
936         }
937
938         assert!(bob.node.send_payment_for_bolt12_invoice(&invoice).is_ok());
939         assert_eq!(
940                 bob.node.send_payment_for_bolt12_invoice(&invoice),
941                 Err(Bolt12PaymentError::DuplicateInvoice),
942         );
943
944         route_bolt12_payment(bob, &[alice], &invoice);
945         expect_recent_payment!(bob, RecentPaymentDetails::Pending, payment_id);
946
947         claim_bolt12_payment(bob, &[alice], payment_context);
948         expect_recent_payment!(bob, RecentPaymentDetails::Fulfilled, payment_id);
949
950         assert_eq!(
951                 bob.node.send_payment_for_bolt12_invoice(&invoice),
952                 Err(Bolt12PaymentError::DuplicateInvoice),
953         );
954
955         for _ in 0..=IDEMPOTENCY_TIMEOUT_TICKS {
956                 bob.node.timer_tick_occurred();
957         }
958
959         assert_eq!(
960                 bob.node.send_payment_for_bolt12_invoice(&invoice),
961                 Err(Bolt12PaymentError::UnexpectedInvoice),
962         );
963 }
964
965 /// Checks that an offer can be created using an unannounced node as a blinded path's introduction
966 /// node. This is only preferred if there are no other options which may indicated either the offer
967 /// is intended for the unannounced node or that the node is actually announced (e.g., an LSP) but
968 /// the recipient doesn't have a network graph.
969 #[test]
970 fn creates_offer_with_blinded_path_using_unannounced_introduction_node() {
971         let chanmon_cfgs = create_chanmon_cfgs(2);
972         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
973         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
974         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
975
976         create_unannounced_chan_between_nodes_with_value(&nodes, 0, 1, 10_000_000, 1_000_000_000);
977
978         let alice = &nodes[0];
979         let alice_id = alice.node.get_our_node_id();
980         let bob = &nodes[1];
981         let bob_id = bob.node.get_our_node_id();
982
983         let offer = alice.node
984                 .create_offer_builder(None).unwrap()
985                 .amount_msats(10_000_000)
986                 .build().unwrap();
987         assert_ne!(offer.signing_pubkey(), Some(alice_id));
988         assert!(!offer.paths().is_empty());
989         for path in offer.paths() {
990                 assert_eq!(path.introduction_node, IntroductionNode::NodeId(bob_id));
991         }
992
993         let payment_id = PaymentId([1; 32]);
994         bob.node.pay_for_offer(&offer, None, None, None, payment_id, Retry::Attempts(0), None).unwrap();
995         expect_recent_payment!(bob, RecentPaymentDetails::AwaitingInvoice, payment_id);
996
997         let onion_message = bob.onion_messenger.next_onion_message_for_peer(alice_id).unwrap();
998         alice.onion_messenger.handle_onion_message(&bob_id, &onion_message);
999
1000         let (invoice_request, reply_path) = extract_invoice_request(alice, &onion_message);
1001         let payment_context = PaymentContext::Bolt12Offer(Bolt12OfferContext {
1002                 offer_id: offer.id(),
1003                 invoice_request: InvoiceRequestFields {
1004                         payer_id: invoice_request.payer_id(),
1005                         quantity: None,
1006                         payer_note_truncated: None,
1007                 },
1008         });
1009         assert_ne!(invoice_request.payer_id(), bob_id);
1010         assert_eq!(reply_path.introduction_node, IntroductionNode::NodeId(alice_id));
1011
1012         let onion_message = alice.onion_messenger.next_onion_message_for_peer(bob_id).unwrap();
1013         bob.onion_messenger.handle_onion_message(&alice_id, &onion_message);
1014
1015         let invoice = extract_invoice(bob, &onion_message);
1016         assert_ne!(invoice.signing_pubkey(), alice_id);
1017         assert!(!invoice.payment_paths().is_empty());
1018         for (_, path) in invoice.payment_paths() {
1019                 assert_eq!(path.introduction_node, IntroductionNode::NodeId(bob_id));
1020         }
1021
1022         route_bolt12_payment(bob, &[alice], &invoice);
1023         expect_recent_payment!(bob, RecentPaymentDetails::Pending, payment_id);
1024
1025         claim_bolt12_payment(bob, &[alice], payment_context);
1026         expect_recent_payment!(bob, RecentPaymentDetails::Fulfilled, payment_id);
1027 }
1028
1029 /// Checks that a refund can be created using an unannounced node as a blinded path's introduction
1030 /// node. This is only preferred if there are no other options which may indicated either the refund
1031 /// is intended for the unannounced node or that the node is actually announced (e.g., an LSP) but
1032 /// the sender doesn't have a network graph.
1033 #[test]
1034 fn creates_refund_with_blinded_path_using_unannounced_introduction_node() {
1035         let chanmon_cfgs = create_chanmon_cfgs(2);
1036         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1037         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1038         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1039
1040         create_unannounced_chan_between_nodes_with_value(&nodes, 0, 1, 10_000_000, 1_000_000_000);
1041
1042         let alice = &nodes[0];
1043         let alice_id = alice.node.get_our_node_id();
1044         let bob = &nodes[1];
1045         let bob_id = bob.node.get_our_node_id();
1046
1047         let absolute_expiry = Duration::from_secs(u64::MAX);
1048         let payment_id = PaymentId([1; 32]);
1049         let refund = bob.node
1050                 .create_refund_builder(10_000_000, absolute_expiry, payment_id, Retry::Attempts(0), None)
1051                 .unwrap()
1052                 .build().unwrap();
1053         assert_ne!(refund.payer_id(), bob_id);
1054         assert!(!refund.paths().is_empty());
1055         for path in refund.paths() {
1056                 assert_eq!(path.introduction_node, IntroductionNode::NodeId(alice_id));
1057         }
1058         expect_recent_payment!(bob, RecentPaymentDetails::AwaitingInvoice, payment_id);
1059
1060         let expected_invoice = alice.node.request_refund_payment(&refund).unwrap();
1061
1062         let onion_message = alice.onion_messenger.next_onion_message_for_peer(bob_id).unwrap();
1063
1064         let invoice = extract_invoice(bob, &onion_message);
1065         assert_eq!(invoice, expected_invoice);
1066         assert_ne!(invoice.signing_pubkey(), alice_id);
1067         assert!(!invoice.payment_paths().is_empty());
1068         for (_, path) in invoice.payment_paths() {
1069                 assert_eq!(path.introduction_node, IntroductionNode::NodeId(bob_id));
1070         }
1071 }
1072
1073 /// Fails creating or paying an offer when a blinded path cannot be created because no peers are
1074 /// connected.
1075 #[test]
1076 fn fails_creating_or_paying_for_offer_without_connected_peers() {
1077         let chanmon_cfgs = create_chanmon_cfgs(6);
1078         let node_cfgs = create_node_cfgs(6, &chanmon_cfgs);
1079         let node_chanmgrs = create_node_chanmgrs(6, &node_cfgs, &[None, None, None, None, None, None]);
1080         let nodes = create_network(6, &node_cfgs, &node_chanmgrs);
1081
1082         create_unannounced_chan_between_nodes_with_value(&nodes, 0, 1, 10_000_000, 1_000_000_000);
1083         create_unannounced_chan_between_nodes_with_value(&nodes, 2, 3, 10_000_000, 1_000_000_000);
1084         create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 10_000_000, 1_000_000_000);
1085         create_announced_chan_between_nodes_with_value(&nodes, 1, 4, 10_000_000, 1_000_000_000);
1086         create_announced_chan_between_nodes_with_value(&nodes, 1, 5, 10_000_000, 1_000_000_000);
1087         create_announced_chan_between_nodes_with_value(&nodes, 2, 4, 10_000_000, 1_000_000_000);
1088         create_announced_chan_between_nodes_with_value(&nodes, 2, 5, 10_000_000, 1_000_000_000);
1089
1090         let (alice, bob, charlie, david) = (&nodes[0], &nodes[1], &nodes[2], &nodes[3]);
1091
1092         disconnect_peers(alice, &[bob, charlie, david, &nodes[4], &nodes[5]]);
1093         disconnect_peers(david, &[bob, charlie, &nodes[4], &nodes[5]]);
1094
1095         let absolute_expiry = alice.node.duration_since_epoch() + MAX_SHORT_LIVED_RELATIVE_EXPIRY;
1096         match alice.node.create_offer_builder(Some(absolute_expiry)) {
1097                 Ok(_) => panic!("Expected error"),
1098                 Err(e) => assert_eq!(e, Bolt12SemanticError::MissingPaths),
1099         }
1100
1101         let mut args = ReconnectArgs::new(alice, bob);
1102         args.send_channel_ready = (true, true);
1103         reconnect_nodes(args);
1104
1105         let offer = alice.node
1106                 .create_offer_builder(Some(absolute_expiry)).unwrap()
1107                 .amount_msats(10_000_000)
1108                 .build().unwrap();
1109
1110         let payment_id = PaymentId([1; 32]);
1111
1112         match david.node.pay_for_offer(&offer, None, None, None, payment_id, Retry::Attempts(0), None) {
1113                 Ok(_) => panic!("Expected error"),
1114                 Err(e) => assert_eq!(e, Bolt12SemanticError::MissingPaths),
1115         }
1116
1117         assert!(nodes[0].node.list_recent_payments().is_empty());
1118
1119         let mut args = ReconnectArgs::new(charlie, david);
1120         args.send_channel_ready = (true, true);
1121         reconnect_nodes(args);
1122
1123         assert!(
1124                 david.node.pay_for_offer(
1125                         &offer, None, None, None, payment_id, Retry::Attempts(0), None
1126                 ).is_ok()
1127         );
1128
1129         expect_recent_payment!(david, RecentPaymentDetails::AwaitingInvoice, payment_id);
1130 }
1131
1132 /// Fails creating or sending an invoice for a refund when a blinded path cannot be created because
1133 /// no peers are connected.
1134 #[test]
1135 fn fails_creating_refund_or_sending_invoice_without_connected_peers() {
1136         let mut accept_forward_cfg = test_default_channel_config();
1137         accept_forward_cfg.accept_forwards_to_priv_channels = true;
1138
1139         let mut features = channelmanager::provided_init_features(&accept_forward_cfg);
1140         features.set_onion_messages_optional();
1141         features.set_route_blinding_optional();
1142
1143         let chanmon_cfgs = create_chanmon_cfgs(6);
1144         let node_cfgs = create_node_cfgs(6, &chanmon_cfgs);
1145
1146         *node_cfgs[1].override_init_features.borrow_mut() = Some(features);
1147
1148         let node_chanmgrs = create_node_chanmgrs(
1149                 6, &node_cfgs, &[None, Some(accept_forward_cfg), None, None, None, None]
1150         );
1151         let nodes = create_network(6, &node_cfgs, &node_chanmgrs);
1152
1153         create_unannounced_chan_between_nodes_with_value(&nodes, 0, 1, 10_000_000, 1_000_000_000);
1154         create_unannounced_chan_between_nodes_with_value(&nodes, 2, 3, 10_000_000, 1_000_000_000);
1155         create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 10_000_000, 1_000_000_000);
1156         create_announced_chan_between_nodes_with_value(&nodes, 1, 4, 10_000_000, 1_000_000_000);
1157         create_announced_chan_between_nodes_with_value(&nodes, 1, 5, 10_000_000, 1_000_000_000);
1158         create_announced_chan_between_nodes_with_value(&nodes, 2, 4, 10_000_000, 1_000_000_000);
1159         create_announced_chan_between_nodes_with_value(&nodes, 2, 5, 10_000_000, 1_000_000_000);
1160
1161         let (alice, bob, charlie, david) = (&nodes[0], &nodes[1], &nodes[2], &nodes[3]);
1162
1163         disconnect_peers(alice, &[bob, charlie, david, &nodes[4], &nodes[5]]);
1164         disconnect_peers(david, &[bob, charlie, &nodes[4], &nodes[5]]);
1165
1166         let absolute_expiry = david.node.duration_since_epoch() + MAX_SHORT_LIVED_RELATIVE_EXPIRY;
1167         let payment_id = PaymentId([1; 32]);
1168         match david.node.create_refund_builder(
1169                 10_000_000, absolute_expiry, payment_id, Retry::Attempts(0), None
1170         ) {
1171                 Ok(_) => panic!("Expected error"),
1172                 Err(e) => assert_eq!(e, Bolt12SemanticError::MissingPaths),
1173         }
1174
1175         let mut args = ReconnectArgs::new(charlie, david);
1176         args.send_channel_ready = (true, true);
1177         reconnect_nodes(args);
1178
1179         let refund = david.node
1180                 .create_refund_builder(10_000_000, absolute_expiry, payment_id, Retry::Attempts(0), None)
1181                 .unwrap()
1182                 .build().unwrap();
1183
1184         match alice.node.request_refund_payment(&refund) {
1185                 Ok(_) => panic!("Expected error"),
1186                 Err(e) => assert_eq!(e, Bolt12SemanticError::MissingPaths),
1187         }
1188
1189         let mut args = ReconnectArgs::new(alice, bob);
1190         args.send_channel_ready = (true, true);
1191         reconnect_nodes(args);
1192
1193         assert!(alice.node.request_refund_payment(&refund).is_ok());
1194 }
1195
1196 /// Fails creating an invoice request when the offer contains an unsupported chain.
1197 #[test]
1198 fn fails_creating_invoice_request_for_unsupported_chain() {
1199         let chanmon_cfgs = create_chanmon_cfgs(2);
1200         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1201         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1202         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1203
1204         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 10_000_000, 1_000_000_000);
1205
1206         let alice = &nodes[0];
1207         let bob = &nodes[1];
1208
1209         let offer = alice.node
1210                 .create_offer_builder(None).unwrap()
1211                 .clear_chains()
1212                 .chain(Network::Signet)
1213                 .build().unwrap();
1214
1215         let payment_id = PaymentId([1; 32]);
1216         match bob.node.pay_for_offer(&offer, None, None, None, payment_id, Retry::Attempts(0), None) {
1217                 Ok(_) => panic!("Expected error"),
1218                 Err(e) => assert_eq!(e, Bolt12SemanticError::UnsupportedChain),
1219         }
1220 }
1221
1222 /// Fails requesting a payment when the refund contains an unsupported chain.
1223 #[test]
1224 fn fails_sending_invoice_with_unsupported_chain_for_refund() {
1225         let chanmon_cfgs = create_chanmon_cfgs(2);
1226         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1227         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1228         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1229
1230         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 10_000_000, 1_000_000_000);
1231
1232         let alice = &nodes[0];
1233         let bob = &nodes[1];
1234
1235         let absolute_expiry = Duration::from_secs(u64::MAX);
1236         let payment_id = PaymentId([1; 32]);
1237         let refund = bob.node
1238                 .create_refund_builder(10_000_000, absolute_expiry, payment_id, Retry::Attempts(0), None)
1239                 .unwrap()
1240                 .chain(Network::Signet)
1241                 .build().unwrap();
1242
1243         match alice.node.request_refund_payment(&refund) {
1244                 Ok(_) => panic!("Expected error"),
1245                 Err(e) => assert_eq!(e, Bolt12SemanticError::UnsupportedChain),
1246         }
1247 }
1248
1249 /// Fails creating an invoice request when a blinded reply path cannot be created.
1250 #[test]
1251 fn fails_creating_invoice_request_without_blinded_reply_path() {
1252         let chanmon_cfgs = create_chanmon_cfgs(6);
1253         let node_cfgs = create_node_cfgs(6, &chanmon_cfgs);
1254         let node_chanmgrs = create_node_chanmgrs(6, &node_cfgs, &[None, None, None, None, None, None]);
1255         let nodes = create_network(6, &node_cfgs, &node_chanmgrs);
1256
1257         create_unannounced_chan_between_nodes_with_value(&nodes, 0, 1, 10_000_000, 1_000_000_000);
1258         create_unannounced_chan_between_nodes_with_value(&nodes, 2, 3, 10_000_000, 1_000_000_000);
1259         create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 10_000_000, 1_000_000_000);
1260         create_announced_chan_between_nodes_with_value(&nodes, 1, 4, 10_000_000, 1_000_000_000);
1261         create_announced_chan_between_nodes_with_value(&nodes, 1, 5, 10_000_000, 1_000_000_000);
1262
1263         let (alice, bob, charlie, david) = (&nodes[0], &nodes[1], &nodes[2], &nodes[3]);
1264
1265         disconnect_peers(alice, &[charlie, david, &nodes[4], &nodes[5]]);
1266         disconnect_peers(david, &[bob, charlie, &nodes[4], &nodes[5]]);
1267
1268         let offer = alice.node
1269                 .create_offer_builder(None).unwrap()
1270                 .amount_msats(10_000_000)
1271                 .build().unwrap();
1272
1273         let payment_id = PaymentId([1; 32]);
1274
1275         match david.node.pay_for_offer(&offer, None, None, None, payment_id, Retry::Attempts(0), None) {
1276                 Ok(_) => panic!("Expected error"),
1277                 Err(e) => assert_eq!(e, Bolt12SemanticError::MissingPaths),
1278         }
1279
1280         assert!(nodes[0].node.list_recent_payments().is_empty());
1281 }
1282
1283 #[test]
1284 fn fails_creating_invoice_request_with_duplicate_payment_id() {
1285         let chanmon_cfgs = create_chanmon_cfgs(6);
1286         let node_cfgs = create_node_cfgs(6, &chanmon_cfgs);
1287         let node_chanmgrs = create_node_chanmgrs(6, &node_cfgs, &[None, None, None, None, None, None]);
1288         let nodes = create_network(6, &node_cfgs, &node_chanmgrs);
1289
1290         create_unannounced_chan_between_nodes_with_value(&nodes, 0, 1, 10_000_000, 1_000_000_000);
1291         create_unannounced_chan_between_nodes_with_value(&nodes, 2, 3, 10_000_000, 1_000_000_000);
1292         create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 10_000_000, 1_000_000_000);
1293         create_announced_chan_between_nodes_with_value(&nodes, 1, 4, 10_000_000, 1_000_000_000);
1294         create_announced_chan_between_nodes_with_value(&nodes, 1, 5, 10_000_000, 1_000_000_000);
1295         create_announced_chan_between_nodes_with_value(&nodes, 2, 4, 10_000_000, 1_000_000_000);
1296         create_announced_chan_between_nodes_with_value(&nodes, 2, 5, 10_000_000, 1_000_000_000);
1297
1298         let (alice, _bob, charlie, david) = (&nodes[0], &nodes[1], &nodes[2], &nodes[3]);
1299
1300         disconnect_peers(alice, &[charlie, david, &nodes[4], &nodes[5]]);
1301
1302         let offer = alice.node
1303                 .create_offer_builder(None).unwrap()
1304                 .amount_msats(10_000_000)
1305                 .build().unwrap();
1306
1307         let payment_id = PaymentId([1; 32]);
1308         assert!(
1309                 david.node.pay_for_offer(
1310                         &offer, None, None, None, payment_id, Retry::Attempts(0), None
1311                 ).is_ok()
1312         );
1313         expect_recent_payment!(david, RecentPaymentDetails::AwaitingInvoice, payment_id);
1314
1315         match david.node.pay_for_offer(&offer, None, None, None, payment_id, Retry::Attempts(0), None) {
1316                 Ok(_) => panic!("Expected error"),
1317                 Err(e) => assert_eq!(e, Bolt12SemanticError::DuplicatePaymentId),
1318         }
1319
1320         expect_recent_payment!(david, RecentPaymentDetails::AwaitingInvoice, payment_id);
1321 }
1322
1323 #[test]
1324 fn fails_creating_refund_with_duplicate_payment_id() {
1325         let chanmon_cfgs = create_chanmon_cfgs(2);
1326         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1327         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1328         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1329
1330         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 10_000_000, 1_000_000_000);
1331
1332         let absolute_expiry = Duration::from_secs(u64::MAX);
1333         let payment_id = PaymentId([1; 32]);
1334         assert!(
1335                 nodes[0].node.create_refund_builder(
1336                         10_000, absolute_expiry, payment_id, Retry::Attempts(0), None
1337                 ).is_ok()
1338         );
1339         expect_recent_payment!(nodes[0], RecentPaymentDetails::AwaitingInvoice, payment_id);
1340
1341         match nodes[0].node.create_refund_builder(
1342                 10_000, absolute_expiry, payment_id, Retry::Attempts(0), None
1343         ) {
1344                 Ok(_) => panic!("Expected error"),
1345                 Err(e) => assert_eq!(e, Bolt12SemanticError::DuplicatePaymentId),
1346         }
1347
1348         expect_recent_payment!(nodes[0], RecentPaymentDetails::AwaitingInvoice, payment_id);
1349 }
1350
1351 #[test]
1352 fn fails_sending_invoice_without_blinded_payment_paths_for_offer() {
1353         let mut accept_forward_cfg = test_default_channel_config();
1354         accept_forward_cfg.accept_forwards_to_priv_channels = true;
1355
1356         // Clearing route_blinding prevents forming any payment paths since the node is unannounced.
1357         let mut features = channelmanager::provided_init_features(&accept_forward_cfg);
1358         features.set_onion_messages_optional();
1359         features.clear_route_blinding();
1360
1361         let chanmon_cfgs = create_chanmon_cfgs(6);
1362         let node_cfgs = create_node_cfgs(6, &chanmon_cfgs);
1363
1364         *node_cfgs[1].override_init_features.borrow_mut() = Some(features);
1365
1366         let node_chanmgrs = create_node_chanmgrs(
1367                 6, &node_cfgs, &[None, Some(accept_forward_cfg), None, None, None, None]
1368         );
1369         let nodes = create_network(6, &node_cfgs, &node_chanmgrs);
1370
1371         create_unannounced_chan_between_nodes_with_value(&nodes, 0, 1, 10_000_000, 1_000_000_000);
1372         create_unannounced_chan_between_nodes_with_value(&nodes, 2, 3, 10_000_000, 1_000_000_000);
1373         create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 10_000_000, 1_000_000_000);
1374         create_announced_chan_between_nodes_with_value(&nodes, 1, 4, 10_000_000, 1_000_000_000);
1375         create_announced_chan_between_nodes_with_value(&nodes, 1, 5, 10_000_000, 1_000_000_000);
1376         create_announced_chan_between_nodes_with_value(&nodes, 2, 4, 10_000_000, 1_000_000_000);
1377         create_announced_chan_between_nodes_with_value(&nodes, 2, 5, 10_000_000, 1_000_000_000);
1378
1379         let (alice, bob, charlie, david) = (&nodes[0], &nodes[1], &nodes[2], &nodes[3]);
1380         let alice_id = alice.node.get_our_node_id();
1381         let bob_id = bob.node.get_our_node_id();
1382         let charlie_id = charlie.node.get_our_node_id();
1383         let david_id = david.node.get_our_node_id();
1384
1385         disconnect_peers(alice, &[charlie, david, &nodes[4], &nodes[5]]);
1386         disconnect_peers(david, &[bob, &nodes[4], &nodes[5]]);
1387
1388         let offer = alice.node
1389                 .create_offer_builder(None).unwrap()
1390                 .amount_msats(10_000_000)
1391                 .build().unwrap();
1392
1393         let payment_id = PaymentId([1; 32]);
1394         david.node.pay_for_offer(&offer, None, None, None, payment_id, Retry::Attempts(0), None)
1395                 .unwrap();
1396
1397         connect_peers(david, bob);
1398
1399         let onion_message = david.onion_messenger.next_onion_message_for_peer(bob_id).unwrap();
1400         bob.onion_messenger.handle_onion_message(&david_id, &onion_message);
1401
1402         connect_peers(alice, charlie);
1403
1404         let onion_message = bob.onion_messenger.next_onion_message_for_peer(alice_id).unwrap();
1405         alice.onion_messenger.handle_onion_message(&bob_id, &onion_message);
1406
1407         let onion_message = alice.onion_messenger.next_onion_message_for_peer(charlie_id).unwrap();
1408         charlie.onion_messenger.handle_onion_message(&alice_id, &onion_message);
1409
1410         let onion_message = charlie.onion_messenger.next_onion_message_for_peer(david_id).unwrap();
1411         david.onion_messenger.handle_onion_message(&charlie_id, &onion_message);
1412
1413         let invoice_error = extract_invoice_error(david, &onion_message);
1414         assert_eq!(invoice_error, InvoiceError::from(Bolt12SemanticError::MissingPaths));
1415 }
1416
1417 #[test]
1418 fn fails_sending_invoice_without_blinded_payment_paths_for_refund() {
1419         let mut accept_forward_cfg = test_default_channel_config();
1420         accept_forward_cfg.accept_forwards_to_priv_channels = true;
1421
1422         // Clearing route_blinding prevents forming any payment paths since the node is unannounced.
1423         let mut features = channelmanager::provided_init_features(&accept_forward_cfg);
1424         features.set_onion_messages_optional();
1425         features.clear_route_blinding();
1426
1427         let chanmon_cfgs = create_chanmon_cfgs(6);
1428         let node_cfgs = create_node_cfgs(6, &chanmon_cfgs);
1429
1430         *node_cfgs[1].override_init_features.borrow_mut() = Some(features);
1431
1432         let node_chanmgrs = create_node_chanmgrs(
1433                 6, &node_cfgs, &[None, Some(accept_forward_cfg), None, None, None, None]
1434         );
1435         let nodes = create_network(6, &node_cfgs, &node_chanmgrs);
1436
1437         create_unannounced_chan_between_nodes_with_value(&nodes, 0, 1, 10_000_000, 1_000_000_000);
1438         create_unannounced_chan_between_nodes_with_value(&nodes, 2, 3, 10_000_000, 1_000_000_000);
1439         create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 10_000_000, 1_000_000_000);
1440         create_announced_chan_between_nodes_with_value(&nodes, 1, 4, 10_000_000, 1_000_000_000);
1441         create_announced_chan_between_nodes_with_value(&nodes, 1, 5, 10_000_000, 1_000_000_000);
1442         create_announced_chan_between_nodes_with_value(&nodes, 2, 4, 10_000_000, 1_000_000_000);
1443         create_announced_chan_between_nodes_with_value(&nodes, 2, 5, 10_000_000, 1_000_000_000);
1444
1445         let (alice, bob, charlie, david) = (&nodes[0], &nodes[1], &nodes[2], &nodes[3]);
1446
1447         disconnect_peers(alice, &[charlie, david, &nodes[4], &nodes[5]]);
1448         disconnect_peers(david, &[bob, &nodes[4], &nodes[5]]);
1449
1450         let absolute_expiry = Duration::from_secs(u64::MAX);
1451         let payment_id = PaymentId([1; 32]);
1452         let refund = david.node
1453                 .create_refund_builder(10_000_000, absolute_expiry, payment_id, Retry::Attempts(0), None)
1454                 .unwrap()
1455                 .build().unwrap();
1456
1457         match alice.node.request_refund_payment(&refund) {
1458                 Ok(_) => panic!("Expected error"),
1459                 Err(e) => assert_eq!(e, Bolt12SemanticError::MissingPaths),
1460         }
1461 }
1462
1463 #[test]
1464 fn fails_paying_invoice_more_than_once() {
1465         let mut accept_forward_cfg = test_default_channel_config();
1466         accept_forward_cfg.accept_forwards_to_priv_channels = true;
1467
1468         let mut features = channelmanager::provided_init_features(&accept_forward_cfg);
1469         features.set_onion_messages_optional();
1470         features.set_route_blinding_optional();
1471
1472         let chanmon_cfgs = create_chanmon_cfgs(6);
1473         let node_cfgs = create_node_cfgs(6, &chanmon_cfgs);
1474
1475         *node_cfgs[1].override_init_features.borrow_mut() = Some(features);
1476
1477         let node_chanmgrs = create_node_chanmgrs(
1478                 6, &node_cfgs, &[None, Some(accept_forward_cfg), None, None, None, None]
1479         );
1480         let nodes = create_network(6, &node_cfgs, &node_chanmgrs);
1481
1482         create_unannounced_chan_between_nodes_with_value(&nodes, 0, 1, 10_000_000, 1_000_000_000);
1483         create_unannounced_chan_between_nodes_with_value(&nodes, 2, 3, 10_000_000, 1_000_000_000);
1484         create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 10_000_000, 1_000_000_000);
1485         create_announced_chan_between_nodes_with_value(&nodes, 1, 4, 10_000_000, 1_000_000_000);
1486         create_announced_chan_between_nodes_with_value(&nodes, 1, 5, 10_000_000, 1_000_000_000);
1487         create_announced_chan_between_nodes_with_value(&nodes, 2, 4, 10_000_000, 1_000_000_000);
1488         create_announced_chan_between_nodes_with_value(&nodes, 2, 5, 10_000_000, 1_000_000_000);
1489
1490         let (alice, bob, charlie, david) = (&nodes[0], &nodes[1], &nodes[2], &nodes[3]);
1491         let alice_id = alice.node.get_our_node_id();
1492         let bob_id = bob.node.get_our_node_id();
1493         let charlie_id = charlie.node.get_our_node_id();
1494         let david_id = david.node.get_our_node_id();
1495
1496         disconnect_peers(alice, &[charlie, david, &nodes[4], &nodes[5]]);
1497         disconnect_peers(david, &[bob, &nodes[4], &nodes[5]]);
1498
1499         let absolute_expiry = Duration::from_secs(u64::MAX);
1500         let payment_id = PaymentId([1; 32]);
1501         let refund = david.node
1502                 .create_refund_builder(10_000_000, absolute_expiry, payment_id, Retry::Attempts(0), None)
1503                 .unwrap()
1504                 .build().unwrap();
1505         expect_recent_payment!(david, RecentPaymentDetails::AwaitingInvoice, payment_id);
1506
1507         // Alice sends the first invoice
1508         alice.node.request_refund_payment(&refund).unwrap();
1509
1510         connect_peers(alice, charlie);
1511
1512         let onion_message = alice.onion_messenger.next_onion_message_for_peer(charlie_id).unwrap();
1513         charlie.onion_messenger.handle_onion_message(&alice_id, &onion_message);
1514
1515         let onion_message = charlie.onion_messenger.next_onion_message_for_peer(david_id).unwrap();
1516         david.onion_messenger.handle_onion_message(&charlie_id, &onion_message);
1517
1518         // David pays the first invoice
1519         let payment_context = PaymentContext::Bolt12Refund(Bolt12RefundContext {});
1520         let invoice1 = extract_invoice(david, &onion_message);
1521
1522         route_bolt12_payment(david, &[charlie, bob, alice], &invoice1);
1523         expect_recent_payment!(david, RecentPaymentDetails::Pending, payment_id);
1524
1525         claim_bolt12_payment(david, &[charlie, bob, alice], payment_context);
1526         expect_recent_payment!(david, RecentPaymentDetails::Fulfilled, payment_id);
1527
1528         disconnect_peers(alice, &[charlie]);
1529
1530         // Alice sends the second invoice
1531         alice.node.request_refund_payment(&refund).unwrap();
1532
1533         connect_peers(alice, charlie);
1534         connect_peers(david, bob);
1535
1536         let onion_message = alice.onion_messenger.next_onion_message_for_peer(charlie_id).unwrap();
1537         charlie.onion_messenger.handle_onion_message(&alice_id, &onion_message);
1538
1539         let onion_message = charlie.onion_messenger.next_onion_message_for_peer(david_id).unwrap();
1540         david.onion_messenger.handle_onion_message(&charlie_id, &onion_message);
1541
1542         let invoice2 = extract_invoice(david, &onion_message);
1543         assert_eq!(invoice1.payer_metadata(), invoice2.payer_metadata());
1544
1545         // David sends an error instead of paying the second invoice
1546         let onion_message = david.onion_messenger.next_onion_message_for_peer(bob_id).unwrap();
1547         bob.onion_messenger.handle_onion_message(&david_id, &onion_message);
1548
1549         let onion_message = bob.onion_messenger.next_onion_message_for_peer(alice_id).unwrap();
1550         alice.onion_messenger.handle_onion_message(&bob_id, &onion_message);
1551
1552         let invoice_error = extract_invoice_error(alice, &onion_message);
1553         assert_eq!(invoice_error, InvoiceError::from_string("DuplicateInvoice".to_string()));
1554 }