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