Don't use compact blinded paths for reply paths
[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::{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().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().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().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 an offer can be paid through blinded paths and that ephemeral pubkeys are used
356 /// rather than exposing a node's pubkey.
357 #[test]
358 fn creates_and_pays_for_offer_using_two_hop_blinded_path() {
359         let mut accept_forward_cfg = test_default_channel_config();
360         accept_forward_cfg.accept_forwards_to_priv_channels = true;
361
362         let mut features = channelmanager::provided_init_features(&accept_forward_cfg);
363         features.set_onion_messages_optional();
364         features.set_route_blinding_optional();
365
366         let chanmon_cfgs = create_chanmon_cfgs(6);
367         let node_cfgs = create_node_cfgs(6, &chanmon_cfgs);
368
369         *node_cfgs[1].override_init_features.borrow_mut() = Some(features);
370
371         let node_chanmgrs = create_node_chanmgrs(
372                 6, &node_cfgs, &[None, Some(accept_forward_cfg), None, None, None, None]
373         );
374         let nodes = create_network(6, &node_cfgs, &node_chanmgrs);
375
376         create_unannounced_chan_between_nodes_with_value(&nodes, 0, 1, 10_000_000, 1_000_000_000);
377         create_unannounced_chan_between_nodes_with_value(&nodes, 2, 3, 10_000_000, 1_000_000_000);
378         create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 10_000_000, 1_000_000_000);
379         create_announced_chan_between_nodes_with_value(&nodes, 1, 4, 10_000_000, 1_000_000_000);
380         create_announced_chan_between_nodes_with_value(&nodes, 1, 5, 10_000_000, 1_000_000_000);
381         create_announced_chan_between_nodes_with_value(&nodes, 2, 4, 10_000_000, 1_000_000_000);
382         create_announced_chan_between_nodes_with_value(&nodes, 2, 5, 10_000_000, 1_000_000_000);
383
384         let (alice, bob, charlie, david) = (&nodes[0], &nodes[1], &nodes[2], &nodes[3]);
385         let alice_id = alice.node.get_our_node_id();
386         let bob_id = bob.node.get_our_node_id();
387         let charlie_id = charlie.node.get_our_node_id();
388         let david_id = david.node.get_our_node_id();
389
390         disconnect_peers(alice, &[charlie, david, &nodes[4], &nodes[5]]);
391         disconnect_peers(david, &[bob, &nodes[4], &nodes[5]]);
392
393         let offer = alice.node
394                 .create_offer_builder()
395                 .unwrap()
396                 .amount_msats(10_000_000)
397                 .build().unwrap();
398         assert_ne!(offer.signing_pubkey(), Some(alice_id));
399         assert!(!offer.paths().is_empty());
400         for path in offer.paths() {
401                 let introduction_node_id = resolve_introduction_node(david, &path);
402                 assert_eq!(introduction_node_id, bob_id);
403                 assert!(matches!(path.introduction_node, IntroductionNode::DirectedShortChannelId(..)));
404         }
405
406         let payment_id = PaymentId([1; 32]);
407         david.node.pay_for_offer(&offer, None, None, None, payment_id, Retry::Attempts(0), None)
408                 .unwrap();
409         expect_recent_payment!(david, RecentPaymentDetails::AwaitingInvoice, payment_id);
410
411         connect_peers(david, bob);
412
413         let onion_message = david.onion_messenger.next_onion_message_for_peer(bob_id).unwrap();
414         bob.onion_messenger.handle_onion_message(&david_id, &onion_message);
415
416         connect_peers(alice, charlie);
417
418         let onion_message = bob.onion_messenger.next_onion_message_for_peer(alice_id).unwrap();
419         alice.onion_messenger.handle_onion_message(&bob_id, &onion_message);
420
421         let (invoice_request, reply_path) = extract_invoice_request(alice, &onion_message);
422         let payment_context = PaymentContext::Bolt12Offer(Bolt12OfferContext {
423                 offer_id: offer.id(),
424                 invoice_request: InvoiceRequestFields {
425                         payer_id: invoice_request.payer_id(),
426                         quantity: None,
427                         payer_note_truncated: None,
428                 },
429         });
430         assert_eq!(invoice_request.amount_msats(), None);
431         assert_ne!(invoice_request.payer_id(), david_id);
432         assert_eq!(reply_path.introduction_node, IntroductionNode::NodeId(charlie_id));
433
434         let onion_message = alice.onion_messenger.next_onion_message_for_peer(charlie_id).unwrap();
435         charlie.onion_messenger.handle_onion_message(&alice_id, &onion_message);
436
437         let onion_message = charlie.onion_messenger.next_onion_message_for_peer(david_id).unwrap();
438         david.onion_messenger.handle_onion_message(&charlie_id, &onion_message);
439
440         let invoice = extract_invoice(david, &onion_message);
441         assert_eq!(invoice.amount_msats(), 10_000_000);
442         assert_ne!(invoice.signing_pubkey(), alice_id);
443         assert!(!invoice.payment_paths().is_empty());
444         for (_, path) in invoice.payment_paths() {
445                 assert_eq!(path.introduction_node, IntroductionNode::NodeId(bob_id));
446         }
447
448         route_bolt12_payment(david, &[charlie, bob, alice], &invoice);
449         expect_recent_payment!(david, RecentPaymentDetails::Pending, payment_id);
450
451         claim_bolt12_payment(david, &[charlie, bob, alice], payment_context);
452         expect_recent_payment!(david, RecentPaymentDetails::Fulfilled, payment_id);
453 }
454
455 /// Checks that a refund can be paid through blinded paths and that ephemeral pubkeys are used
456 /// rather than exposing a node's pubkey.
457 #[test]
458 fn creates_and_pays_for_refund_using_two_hop_blinded_path() {
459         let mut accept_forward_cfg = test_default_channel_config();
460         accept_forward_cfg.accept_forwards_to_priv_channels = true;
461
462         let mut features = channelmanager::provided_init_features(&accept_forward_cfg);
463         features.set_onion_messages_optional();
464         features.set_route_blinding_optional();
465
466         let chanmon_cfgs = create_chanmon_cfgs(6);
467         let node_cfgs = create_node_cfgs(6, &chanmon_cfgs);
468
469         *node_cfgs[1].override_init_features.borrow_mut() = Some(features);
470
471         let node_chanmgrs = create_node_chanmgrs(
472                 6, &node_cfgs, &[None, Some(accept_forward_cfg), None, None, None, None]
473         );
474         let nodes = create_network(6, &node_cfgs, &node_chanmgrs);
475
476         create_unannounced_chan_between_nodes_with_value(&nodes, 0, 1, 10_000_000, 1_000_000_000);
477         create_unannounced_chan_between_nodes_with_value(&nodes, 2, 3, 10_000_000, 1_000_000_000);
478         create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 10_000_000, 1_000_000_000);
479         create_announced_chan_between_nodes_with_value(&nodes, 1, 4, 10_000_000, 1_000_000_000);
480         create_announced_chan_between_nodes_with_value(&nodes, 1, 5, 10_000_000, 1_000_000_000);
481         create_announced_chan_between_nodes_with_value(&nodes, 2, 4, 10_000_000, 1_000_000_000);
482         create_announced_chan_between_nodes_with_value(&nodes, 2, 5, 10_000_000, 1_000_000_000);
483
484         let (alice, bob, charlie, david) = (&nodes[0], &nodes[1], &nodes[2], &nodes[3]);
485         let alice_id = alice.node.get_our_node_id();
486         let bob_id = bob.node.get_our_node_id();
487         let charlie_id = charlie.node.get_our_node_id();
488         let david_id = david.node.get_our_node_id();
489
490         disconnect_peers(alice, &[charlie, david, &nodes[4], &nodes[5]]);
491         disconnect_peers(david, &[bob, &nodes[4], &nodes[5]]);
492
493         let absolute_expiry = Duration::from_secs(u64::MAX);
494         let payment_id = PaymentId([1; 32]);
495         let refund = david.node
496                 .create_refund_builder(10_000_000, absolute_expiry, payment_id, Retry::Attempts(0), None)
497                 .unwrap()
498                 .build().unwrap();
499         assert_eq!(refund.amount_msats(), 10_000_000);
500         assert_eq!(refund.absolute_expiry(), Some(absolute_expiry));
501         assert_ne!(refund.payer_id(), david_id);
502         assert!(!refund.paths().is_empty());
503         for path in refund.paths() {
504                 let introduction_node_id = resolve_introduction_node(alice, &path);
505                 assert_eq!(introduction_node_id, charlie_id);
506                 assert!(matches!(path.introduction_node, IntroductionNode::DirectedShortChannelId(..)));
507         }
508         expect_recent_payment!(david, RecentPaymentDetails::AwaitingInvoice, payment_id);
509
510         let payment_context = PaymentContext::Bolt12Refund(Bolt12RefundContext {});
511         let expected_invoice = alice.node.request_refund_payment(&refund).unwrap();
512
513         connect_peers(alice, charlie);
514
515         let onion_message = alice.onion_messenger.next_onion_message_for_peer(charlie_id).unwrap();
516         charlie.onion_messenger.handle_onion_message(&alice_id, &onion_message);
517
518         let onion_message = charlie.onion_messenger.next_onion_message_for_peer(david_id).unwrap();
519         david.onion_messenger.handle_onion_message(&charlie_id, &onion_message);
520
521         let invoice = extract_invoice(david, &onion_message);
522         assert_eq!(invoice, expected_invoice);
523
524         assert_eq!(invoice.amount_msats(), 10_000_000);
525         assert_ne!(invoice.signing_pubkey(), alice_id);
526         assert!(!invoice.payment_paths().is_empty());
527         for (_, path) in invoice.payment_paths() {
528                 assert_eq!(path.introduction_node, IntroductionNode::NodeId(bob_id));
529         }
530
531         route_bolt12_payment(david, &[charlie, bob, alice], &invoice);
532         expect_recent_payment!(david, RecentPaymentDetails::Pending, payment_id);
533
534         claim_bolt12_payment(david, &[charlie, bob, alice], payment_context);
535         expect_recent_payment!(david, RecentPaymentDetails::Fulfilled, payment_id);
536 }
537
538 /// Checks that an offer can be paid through a one-hop blinded path and that ephemeral pubkeys are
539 /// used rather than exposing a node's pubkey. However, the node's pubkey is still used as the
540 /// introduction node of the blinded path.
541 #[test]
542 fn creates_and_pays_for_offer_using_one_hop_blinded_path() {
543         let chanmon_cfgs = create_chanmon_cfgs(2);
544         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
545         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
546         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
547
548         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 10_000_000, 1_000_000_000);
549
550         let alice = &nodes[0];
551         let alice_id = alice.node.get_our_node_id();
552         let bob = &nodes[1];
553         let bob_id = bob.node.get_our_node_id();
554
555         let offer = alice.node
556                 .create_offer_builder().unwrap()
557                 .amount_msats(10_000_000)
558                 .build().unwrap();
559         assert_ne!(offer.signing_pubkey(), Some(alice_id));
560         assert!(!offer.paths().is_empty());
561         for path in offer.paths() {
562                 let introduction_node_id = resolve_introduction_node(bob, &path);
563                 assert_eq!(introduction_node_id, alice_id);
564                 assert!(matches!(path.introduction_node, IntroductionNode::DirectedShortChannelId(..)));
565         }
566
567         let payment_id = PaymentId([1; 32]);
568         bob.node.pay_for_offer(&offer, None, None, None, payment_id, Retry::Attempts(0), None).unwrap();
569         expect_recent_payment!(bob, RecentPaymentDetails::AwaitingInvoice, payment_id);
570
571         let onion_message = bob.onion_messenger.next_onion_message_for_peer(alice_id).unwrap();
572         alice.onion_messenger.handle_onion_message(&bob_id, &onion_message);
573
574         let (invoice_request, reply_path) = extract_invoice_request(alice, &onion_message);
575         let payment_context = PaymentContext::Bolt12Offer(Bolt12OfferContext {
576                 offer_id: offer.id(),
577                 invoice_request: InvoiceRequestFields {
578                         payer_id: invoice_request.payer_id(),
579                         quantity: None,
580                         payer_note_truncated: None,
581                 },
582         });
583         assert_eq!(invoice_request.amount_msats(), None);
584         assert_ne!(invoice_request.payer_id(), bob_id);
585         assert_eq!(reply_path.introduction_node, IntroductionNode::NodeId(bob_id));
586
587         let onion_message = alice.onion_messenger.next_onion_message_for_peer(bob_id).unwrap();
588         bob.onion_messenger.handle_onion_message(&alice_id, &onion_message);
589
590         let invoice = extract_invoice(bob, &onion_message);
591         assert_eq!(invoice.amount_msats(), 10_000_000);
592         assert_ne!(invoice.signing_pubkey(), alice_id);
593         assert!(!invoice.payment_paths().is_empty());
594         for (_, path) in invoice.payment_paths() {
595                 assert_eq!(path.introduction_node, IntroductionNode::NodeId(alice_id));
596         }
597
598         route_bolt12_payment(bob, &[alice], &invoice);
599         expect_recent_payment!(bob, RecentPaymentDetails::Pending, payment_id);
600
601         claim_bolt12_payment(bob, &[alice], payment_context);
602         expect_recent_payment!(bob, RecentPaymentDetails::Fulfilled, payment_id);
603 }
604
605 /// Checks that a refund can be paid through a one-hop blinded path and that ephemeral pubkeys are
606 /// used rather than exposing a node's pubkey. However, the node's pubkey is still used as the
607 /// introduction node of the blinded path.
608 #[test]
609 fn creates_and_pays_for_refund_using_one_hop_blinded_path() {
610         let chanmon_cfgs = create_chanmon_cfgs(2);
611         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
612         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
613         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
614
615         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 10_000_000, 1_000_000_000);
616
617         let alice = &nodes[0];
618         let alice_id = alice.node.get_our_node_id();
619         let bob = &nodes[1];
620         let bob_id = bob.node.get_our_node_id();
621
622         let absolute_expiry = Duration::from_secs(u64::MAX);
623         let payment_id = PaymentId([1; 32]);
624         let refund = bob.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(), bob_id);
631         assert!(!refund.paths().is_empty());
632         for path in refund.paths() {
633                 let introduction_node_id = resolve_introduction_node(alice, &path);
634                 assert_eq!(introduction_node_id, bob_id);
635                 assert!(matches!(path.introduction_node, IntroductionNode::DirectedShortChannelId(..)));
636         }
637         expect_recent_payment!(bob, RecentPaymentDetails::AwaitingInvoice, payment_id);
638
639         let payment_context = PaymentContext::Bolt12Refund(Bolt12RefundContext {});
640         let expected_invoice = alice.node.request_refund_payment(&refund).unwrap();
641
642         let onion_message = alice.onion_messenger.next_onion_message_for_peer(bob_id).unwrap();
643         bob.onion_messenger.handle_onion_message(&alice_id, &onion_message);
644
645         let invoice = extract_invoice(bob, &onion_message);
646         assert_eq!(invoice, expected_invoice);
647
648         assert_eq!(invoice.amount_msats(), 10_000_000);
649         assert_ne!(invoice.signing_pubkey(), alice_id);
650         assert!(!invoice.payment_paths().is_empty());
651         for (_, path) in invoice.payment_paths() {
652                 assert_eq!(path.introduction_node, IntroductionNode::NodeId(alice_id));
653         }
654
655         route_bolt12_payment(bob, &[alice], &invoice);
656         expect_recent_payment!(bob, RecentPaymentDetails::Pending, payment_id);
657
658         claim_bolt12_payment(bob, &[alice], payment_context);
659         expect_recent_payment!(bob, RecentPaymentDetails::Fulfilled, payment_id);
660 }
661
662 /// Checks that an invoice for an offer without any blinded paths can be requested. Note that while
663 /// the requested is sent directly using the node's pubkey, the response and the payment still use
664 /// blinded paths as required by the spec.
665 #[test]
666 fn pays_for_offer_without_blinded_paths() {
667         let chanmon_cfgs = create_chanmon_cfgs(2);
668         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
669         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
670         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
671
672         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 10_000_000, 1_000_000_000);
673
674         let alice = &nodes[0];
675         let alice_id = alice.node.get_our_node_id();
676         let bob = &nodes[1];
677         let bob_id = bob.node.get_our_node_id();
678
679         let offer = alice.node
680                 .create_offer_builder().unwrap()
681                 .clear_paths()
682                 .amount_msats(10_000_000)
683                 .build().unwrap();
684         assert_eq!(offer.signing_pubkey(), Some(alice_id));
685         assert!(offer.paths().is_empty());
686
687         let payment_id = PaymentId([1; 32]);
688         bob.node.pay_for_offer(&offer, None, None, None, payment_id, Retry::Attempts(0), None).unwrap();
689         expect_recent_payment!(bob, RecentPaymentDetails::AwaitingInvoice, payment_id);
690
691         let onion_message = bob.onion_messenger.next_onion_message_for_peer(alice_id).unwrap();
692         alice.onion_messenger.handle_onion_message(&bob_id, &onion_message);
693
694         let (invoice_request, _) = extract_invoice_request(alice, &onion_message);
695         let payment_context = PaymentContext::Bolt12Offer(Bolt12OfferContext {
696                 offer_id: offer.id(),
697                 invoice_request: InvoiceRequestFields {
698                         payer_id: invoice_request.payer_id(),
699                         quantity: None,
700                         payer_note_truncated: None,
701                 },
702         });
703
704         let onion_message = alice.onion_messenger.next_onion_message_for_peer(bob_id).unwrap();
705         bob.onion_messenger.handle_onion_message(&alice_id, &onion_message);
706
707         let invoice = extract_invoice(bob, &onion_message);
708         route_bolt12_payment(bob, &[alice], &invoice);
709         expect_recent_payment!(bob, RecentPaymentDetails::Pending, payment_id);
710
711         claim_bolt12_payment(bob, &[alice], payment_context);
712         expect_recent_payment!(bob, RecentPaymentDetails::Fulfilled, payment_id);
713 }
714
715 /// Checks that a refund without any blinded paths can be paid. Note that while the invoice is sent
716 /// directly using the node's pubkey, the payment still use blinded paths as required by the spec.
717 #[test]
718 fn pays_for_refund_without_blinded_paths() {
719         let chanmon_cfgs = create_chanmon_cfgs(2);
720         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
721         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
722         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
723
724         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 10_000_000, 1_000_000_000);
725
726         let alice = &nodes[0];
727         let alice_id = alice.node.get_our_node_id();
728         let bob = &nodes[1];
729         let bob_id = bob.node.get_our_node_id();
730
731         let absolute_expiry = Duration::from_secs(u64::MAX);
732         let payment_id = PaymentId([1; 32]);
733         let refund = bob.node
734                 .create_refund_builder(10_000_000, absolute_expiry, payment_id, Retry::Attempts(0), None)
735                 .unwrap()
736                 .clear_paths()
737                 .build().unwrap();
738         assert_eq!(refund.payer_id(), bob_id);
739         assert!(refund.paths().is_empty());
740         expect_recent_payment!(bob, RecentPaymentDetails::AwaitingInvoice, payment_id);
741
742         let payment_context = PaymentContext::Bolt12Refund(Bolt12RefundContext {});
743         let expected_invoice = alice.node.request_refund_payment(&refund).unwrap();
744
745         let onion_message = alice.onion_messenger.next_onion_message_for_peer(bob_id).unwrap();
746         bob.onion_messenger.handle_onion_message(&alice_id, &onion_message);
747
748         let invoice = extract_invoice(bob, &onion_message);
749         assert_eq!(invoice, expected_invoice);
750
751         route_bolt12_payment(bob, &[alice], &invoice);
752         expect_recent_payment!(bob, RecentPaymentDetails::Pending, payment_id);
753
754         claim_bolt12_payment(bob, &[alice], payment_context);
755         expect_recent_payment!(bob, RecentPaymentDetails::Fulfilled, payment_id);
756 }
757
758 /// Fails creating an offer when a blinded path cannot be created without exposing the node's id.
759 #[test]
760 fn fails_creating_offer_without_blinded_paths() {
761         let chanmon_cfgs = create_chanmon_cfgs(2);
762         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
763         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
764         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
765
766         create_unannounced_chan_between_nodes_with_value(&nodes, 0, 1, 10_000_000, 1_000_000_000);
767
768         match nodes[0].node.create_offer_builder() {
769                 Ok(_) => panic!("Expected error"),
770                 Err(e) => assert_eq!(e, Bolt12SemanticError::MissingPaths),
771         }
772 }
773
774 /// Fails creating a refund when a blinded path cannot be created without exposing the node's id.
775 #[test]
776 fn fails_creating_refund_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_unannounced_chan_between_nodes_with_value(&nodes, 0, 1, 10_000_000, 1_000_000_000);
783
784         let absolute_expiry = Duration::from_secs(u64::MAX);
785         let payment_id = PaymentId([1; 32]);
786
787         match nodes[0].node.create_refund_builder(
788                 10_000, absolute_expiry, payment_id, Retry::Attempts(0), None
789         ) {
790                 Ok(_) => panic!("Expected error"),
791                 Err(e) => assert_eq!(e, Bolt12SemanticError::MissingPaths),
792         }
793
794         assert!(nodes[0].node.list_recent_payments().is_empty());
795 }
796
797 /// Fails creating an invoice request when the offer contains an unsupported chain.
798 #[test]
799 fn fails_creating_invoice_request_for_unsupported_chain() {
800         let chanmon_cfgs = create_chanmon_cfgs(2);
801         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
802         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
803         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
804
805         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 10_000_000, 1_000_000_000);
806
807         let alice = &nodes[0];
808         let bob = &nodes[1];
809
810         let offer = alice.node
811                 .create_offer_builder().unwrap()
812                 .clear_chains()
813                 .chain(Network::Signet)
814                 .build().unwrap();
815
816         let payment_id = PaymentId([1; 32]);
817         match bob.node.pay_for_offer(&offer, None, None, None, payment_id, Retry::Attempts(0), None) {
818                 Ok(_) => panic!("Expected error"),
819                 Err(e) => assert_eq!(e, Bolt12SemanticError::UnsupportedChain),
820         }
821 }
822
823 /// Fails requesting a payment when the refund contains an unsupported chain.
824 #[test]
825 fn fails_sending_invoice_with_unsupported_chain_for_refund() {
826         let chanmon_cfgs = create_chanmon_cfgs(2);
827         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
828         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
829         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
830
831         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 10_000_000, 1_000_000_000);
832
833         let alice = &nodes[0];
834         let bob = &nodes[1];
835
836         let absolute_expiry = Duration::from_secs(u64::MAX);
837         let payment_id = PaymentId([1; 32]);
838         let refund = bob.node
839                 .create_refund_builder(10_000_000, absolute_expiry, payment_id, Retry::Attempts(0), None)
840                 .unwrap()
841                 .chain(Network::Signet)
842                 .build().unwrap();
843
844         match alice.node.request_refund_payment(&refund) {
845                 Ok(_) => panic!("Expected error"),
846                 Err(e) => assert_eq!(e, Bolt12SemanticError::UnsupportedChain),
847         }
848 }
849
850 /// Fails creating an invoice request when a blinded reply path cannot be created without exposing
851 /// the node's id.
852 #[test]
853 fn fails_creating_invoice_request_without_blinded_reply_path() {
854         let chanmon_cfgs = create_chanmon_cfgs(6);
855         let node_cfgs = create_node_cfgs(6, &chanmon_cfgs);
856         let node_chanmgrs = create_node_chanmgrs(6, &node_cfgs, &[None, None, None, None, None, None]);
857         let nodes = create_network(6, &node_cfgs, &node_chanmgrs);
858
859         create_unannounced_chan_between_nodes_with_value(&nodes, 0, 1, 10_000_000, 1_000_000_000);
860         create_unannounced_chan_between_nodes_with_value(&nodes, 2, 3, 10_000_000, 1_000_000_000);
861         create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 10_000_000, 1_000_000_000);
862         create_announced_chan_between_nodes_with_value(&nodes, 1, 4, 10_000_000, 1_000_000_000);
863         create_announced_chan_between_nodes_with_value(&nodes, 1, 5, 10_000_000, 1_000_000_000);
864
865         let (alice, bob, charlie, david) = (&nodes[0], &nodes[1], &nodes[2], &nodes[3]);
866
867         disconnect_peers(alice, &[charlie, david, &nodes[4], &nodes[5]]);
868         disconnect_peers(david, &[bob, &nodes[4], &nodes[5]]);
869
870         let offer = alice.node
871                 .create_offer_builder().unwrap()
872                 .amount_msats(10_000_000)
873                 .build().unwrap();
874
875         let payment_id = PaymentId([1; 32]);
876
877         match david.node.pay_for_offer(&offer, None, None, None, payment_id, Retry::Attempts(0), None) {
878                 Ok(_) => panic!("Expected error"),
879                 Err(e) => assert_eq!(e, Bolt12SemanticError::MissingPaths),
880         }
881
882         assert!(nodes[0].node.list_recent_payments().is_empty());
883 }
884
885 #[test]
886 fn fails_creating_invoice_request_with_duplicate_payment_id() {
887         let chanmon_cfgs = create_chanmon_cfgs(6);
888         let node_cfgs = create_node_cfgs(6, &chanmon_cfgs);
889         let node_chanmgrs = create_node_chanmgrs(6, &node_cfgs, &[None, None, None, None, None, None]);
890         let nodes = create_network(6, &node_cfgs, &node_chanmgrs);
891
892         create_unannounced_chan_between_nodes_with_value(&nodes, 0, 1, 10_000_000, 1_000_000_000);
893         create_unannounced_chan_between_nodes_with_value(&nodes, 2, 3, 10_000_000, 1_000_000_000);
894         create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 10_000_000, 1_000_000_000);
895         create_announced_chan_between_nodes_with_value(&nodes, 1, 4, 10_000_000, 1_000_000_000);
896         create_announced_chan_between_nodes_with_value(&nodes, 1, 5, 10_000_000, 1_000_000_000);
897         create_announced_chan_between_nodes_with_value(&nodes, 2, 4, 10_000_000, 1_000_000_000);
898         create_announced_chan_between_nodes_with_value(&nodes, 2, 5, 10_000_000, 1_000_000_000);
899
900         let (alice, _bob, charlie, david) = (&nodes[0], &nodes[1], &nodes[2], &nodes[3]);
901
902         disconnect_peers(alice, &[charlie, david, &nodes[4], &nodes[5]]);
903
904         let offer = alice.node
905                 .create_offer_builder().unwrap()
906                 .amount_msats(10_000_000)
907                 .build().unwrap();
908
909         let payment_id = PaymentId([1; 32]);
910         assert!(
911                 david.node.pay_for_offer(
912                         &offer, None, None, None, payment_id, Retry::Attempts(0), None
913                 ).is_ok()
914         );
915         expect_recent_payment!(david, RecentPaymentDetails::AwaitingInvoice, payment_id);
916
917         match david.node.pay_for_offer(&offer, None, None, None, payment_id, Retry::Attempts(0), None) {
918                 Ok(_) => panic!("Expected error"),
919                 Err(e) => assert_eq!(e, Bolt12SemanticError::DuplicatePaymentId),
920         }
921
922         expect_recent_payment!(david, RecentPaymentDetails::AwaitingInvoice, payment_id);
923 }
924
925 #[test]
926 fn fails_creating_refund_with_duplicate_payment_id() {
927         let chanmon_cfgs = create_chanmon_cfgs(2);
928         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
929         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
930         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
931
932         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 10_000_000, 1_000_000_000);
933
934         let absolute_expiry = Duration::from_secs(u64::MAX);
935         let payment_id = PaymentId([1; 32]);
936         assert!(
937                 nodes[0].node.create_refund_builder(
938                         10_000, absolute_expiry, payment_id, Retry::Attempts(0), None
939                 ).is_ok()
940         );
941         expect_recent_payment!(nodes[0], RecentPaymentDetails::AwaitingInvoice, payment_id);
942
943         match nodes[0].node.create_refund_builder(
944                 10_000, absolute_expiry, payment_id, Retry::Attempts(0), None
945         ) {
946                 Ok(_) => panic!("Expected error"),
947                 Err(e) => assert_eq!(e, Bolt12SemanticError::DuplicatePaymentId),
948         }
949
950         expect_recent_payment!(nodes[0], RecentPaymentDetails::AwaitingInvoice, payment_id);
951 }
952
953 #[test]
954 fn fails_sending_invoice_without_blinded_payment_paths_for_offer() {
955         let mut accept_forward_cfg = test_default_channel_config();
956         accept_forward_cfg.accept_forwards_to_priv_channels = true;
957
958         // Clearing route_blinding prevents forming any payment paths since the node is unannounced.
959         let mut features = channelmanager::provided_init_features(&accept_forward_cfg);
960         features.set_onion_messages_optional();
961         features.clear_route_blinding();
962
963         let chanmon_cfgs = create_chanmon_cfgs(6);
964         let node_cfgs = create_node_cfgs(6, &chanmon_cfgs);
965
966         *node_cfgs[1].override_init_features.borrow_mut() = Some(features);
967
968         let node_chanmgrs = create_node_chanmgrs(
969                 6, &node_cfgs, &[None, Some(accept_forward_cfg), None, None, None, None]
970         );
971         let nodes = create_network(6, &node_cfgs, &node_chanmgrs);
972
973         create_unannounced_chan_between_nodes_with_value(&nodes, 0, 1, 10_000_000, 1_000_000_000);
974         create_unannounced_chan_between_nodes_with_value(&nodes, 2, 3, 10_000_000, 1_000_000_000);
975         create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 10_000_000, 1_000_000_000);
976         create_announced_chan_between_nodes_with_value(&nodes, 1, 4, 10_000_000, 1_000_000_000);
977         create_announced_chan_between_nodes_with_value(&nodes, 1, 5, 10_000_000, 1_000_000_000);
978         create_announced_chan_between_nodes_with_value(&nodes, 2, 4, 10_000_000, 1_000_000_000);
979         create_announced_chan_between_nodes_with_value(&nodes, 2, 5, 10_000_000, 1_000_000_000);
980
981         let (alice, bob, charlie, david) = (&nodes[0], &nodes[1], &nodes[2], &nodes[3]);
982         let alice_id = alice.node.get_our_node_id();
983         let bob_id = bob.node.get_our_node_id();
984         let charlie_id = charlie.node.get_our_node_id();
985         let david_id = david.node.get_our_node_id();
986
987         disconnect_peers(alice, &[charlie, david, &nodes[4], &nodes[5]]);
988         disconnect_peers(david, &[bob, &nodes[4], &nodes[5]]);
989
990         let offer = alice.node
991                 .create_offer_builder().unwrap()
992                 .amount_msats(10_000_000)
993                 .build().unwrap();
994
995         let payment_id = PaymentId([1; 32]);
996         david.node.pay_for_offer(&offer, None, None, None, payment_id, Retry::Attempts(0), None)
997                 .unwrap();
998
999         connect_peers(david, bob);
1000
1001         let onion_message = david.onion_messenger.next_onion_message_for_peer(bob_id).unwrap();
1002         bob.onion_messenger.handle_onion_message(&david_id, &onion_message);
1003
1004         connect_peers(alice, charlie);
1005
1006         let onion_message = bob.onion_messenger.next_onion_message_for_peer(alice_id).unwrap();
1007         alice.onion_messenger.handle_onion_message(&bob_id, &onion_message);
1008
1009         let onion_message = alice.onion_messenger.next_onion_message_for_peer(charlie_id).unwrap();
1010         charlie.onion_messenger.handle_onion_message(&alice_id, &onion_message);
1011
1012         let onion_message = charlie.onion_messenger.next_onion_message_for_peer(david_id).unwrap();
1013         david.onion_messenger.handle_onion_message(&charlie_id, &onion_message);
1014
1015         let invoice_error = extract_invoice_error(david, &onion_message);
1016         assert_eq!(invoice_error, InvoiceError::from(Bolt12SemanticError::MissingPaths));
1017 }
1018
1019 #[test]
1020 fn fails_sending_invoice_without_blinded_payment_paths_for_refund() {
1021         let mut accept_forward_cfg = test_default_channel_config();
1022         accept_forward_cfg.accept_forwards_to_priv_channels = true;
1023
1024         // Clearing route_blinding prevents forming any payment paths since the node is unannounced.
1025         let mut features = channelmanager::provided_init_features(&accept_forward_cfg);
1026         features.set_onion_messages_optional();
1027         features.clear_route_blinding();
1028
1029         let chanmon_cfgs = create_chanmon_cfgs(6);
1030         let node_cfgs = create_node_cfgs(6, &chanmon_cfgs);
1031
1032         *node_cfgs[1].override_init_features.borrow_mut() = Some(features);
1033
1034         let node_chanmgrs = create_node_chanmgrs(
1035                 6, &node_cfgs, &[None, Some(accept_forward_cfg), None, None, None, None]
1036         );
1037         let nodes = create_network(6, &node_cfgs, &node_chanmgrs);
1038
1039         create_unannounced_chan_between_nodes_with_value(&nodes, 0, 1, 10_000_000, 1_000_000_000);
1040         create_unannounced_chan_between_nodes_with_value(&nodes, 2, 3, 10_000_000, 1_000_000_000);
1041         create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 10_000_000, 1_000_000_000);
1042         create_announced_chan_between_nodes_with_value(&nodes, 1, 4, 10_000_000, 1_000_000_000);
1043         create_announced_chan_between_nodes_with_value(&nodes, 1, 5, 10_000_000, 1_000_000_000);
1044         create_announced_chan_between_nodes_with_value(&nodes, 2, 4, 10_000_000, 1_000_000_000);
1045         create_announced_chan_between_nodes_with_value(&nodes, 2, 5, 10_000_000, 1_000_000_000);
1046
1047         let (alice, bob, charlie, david) = (&nodes[0], &nodes[1], &nodes[2], &nodes[3]);
1048
1049         disconnect_peers(alice, &[charlie, david, &nodes[4], &nodes[5]]);
1050         disconnect_peers(david, &[bob, &nodes[4], &nodes[5]]);
1051
1052         let absolute_expiry = Duration::from_secs(u64::MAX);
1053         let payment_id = PaymentId([1; 32]);
1054         let refund = david.node
1055                 .create_refund_builder(10_000_000, absolute_expiry, payment_id, Retry::Attempts(0), None)
1056                 .unwrap()
1057                 .build().unwrap();
1058
1059         match alice.node.request_refund_payment(&refund) {
1060                 Ok(_) => panic!("Expected error"),
1061                 Err(e) => assert_eq!(e, Bolt12SemanticError::MissingPaths),
1062         }
1063 }
1064
1065 #[test]
1066 fn fails_paying_invoice_more_than_once() {
1067         let mut accept_forward_cfg = test_default_channel_config();
1068         accept_forward_cfg.accept_forwards_to_priv_channels = true;
1069
1070         let mut features = channelmanager::provided_init_features(&accept_forward_cfg);
1071         features.set_onion_messages_optional();
1072         features.set_route_blinding_optional();
1073
1074         let chanmon_cfgs = create_chanmon_cfgs(6);
1075         let node_cfgs = create_node_cfgs(6, &chanmon_cfgs);
1076
1077         *node_cfgs[1].override_init_features.borrow_mut() = Some(features);
1078
1079         let node_chanmgrs = create_node_chanmgrs(
1080                 6, &node_cfgs, &[None, Some(accept_forward_cfg), None, None, None, None]
1081         );
1082         let nodes = create_network(6, &node_cfgs, &node_chanmgrs);
1083
1084         create_unannounced_chan_between_nodes_with_value(&nodes, 0, 1, 10_000_000, 1_000_000_000);
1085         create_unannounced_chan_between_nodes_with_value(&nodes, 2, 3, 10_000_000, 1_000_000_000);
1086         create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 10_000_000, 1_000_000_000);
1087         create_announced_chan_between_nodes_with_value(&nodes, 1, 4, 10_000_000, 1_000_000_000);
1088         create_announced_chan_between_nodes_with_value(&nodes, 1, 5, 10_000_000, 1_000_000_000);
1089         create_announced_chan_between_nodes_with_value(&nodes, 2, 4, 10_000_000, 1_000_000_000);
1090         create_announced_chan_between_nodes_with_value(&nodes, 2, 5, 10_000_000, 1_000_000_000);
1091
1092         let (alice, bob, charlie, david) = (&nodes[0], &nodes[1], &nodes[2], &nodes[3]);
1093         let alice_id = alice.node.get_our_node_id();
1094         let bob_id = bob.node.get_our_node_id();
1095         let charlie_id = charlie.node.get_our_node_id();
1096         let david_id = david.node.get_our_node_id();
1097
1098         disconnect_peers(alice, &[charlie, david, &nodes[4], &nodes[5]]);
1099         disconnect_peers(david, &[bob, &nodes[4], &nodes[5]]);
1100
1101         let absolute_expiry = Duration::from_secs(u64::MAX);
1102         let payment_id = PaymentId([1; 32]);
1103         let refund = david.node
1104                 .create_refund_builder(10_000_000, absolute_expiry, payment_id, Retry::Attempts(0), None)
1105                 .unwrap()
1106                 .build().unwrap();
1107         expect_recent_payment!(david, RecentPaymentDetails::AwaitingInvoice, payment_id);
1108
1109         // Alice sends the first invoice
1110         alice.node.request_refund_payment(&refund).unwrap();
1111
1112         connect_peers(alice, charlie);
1113
1114         let onion_message = alice.onion_messenger.next_onion_message_for_peer(charlie_id).unwrap();
1115         charlie.onion_messenger.handle_onion_message(&alice_id, &onion_message);
1116
1117         let onion_message = charlie.onion_messenger.next_onion_message_for_peer(david_id).unwrap();
1118         david.onion_messenger.handle_onion_message(&charlie_id, &onion_message);
1119
1120         // David pays the first invoice
1121         let payment_context = PaymentContext::Bolt12Refund(Bolt12RefundContext {});
1122         let invoice1 = extract_invoice(david, &onion_message);
1123
1124         route_bolt12_payment(david, &[charlie, bob, alice], &invoice1);
1125         expect_recent_payment!(david, RecentPaymentDetails::Pending, payment_id);
1126
1127         claim_bolt12_payment(david, &[charlie, bob, alice], payment_context);
1128         expect_recent_payment!(david, RecentPaymentDetails::Fulfilled, payment_id);
1129
1130         disconnect_peers(alice, &[charlie]);
1131
1132         // Alice sends the second invoice
1133         alice.node.request_refund_payment(&refund).unwrap();
1134
1135         connect_peers(alice, charlie);
1136         connect_peers(david, bob);
1137
1138         let onion_message = alice.onion_messenger.next_onion_message_for_peer(charlie_id).unwrap();
1139         charlie.onion_messenger.handle_onion_message(&alice_id, &onion_message);
1140
1141         let onion_message = charlie.onion_messenger.next_onion_message_for_peer(david_id).unwrap();
1142         david.onion_messenger.handle_onion_message(&charlie_id, &onion_message);
1143
1144         let invoice2 = extract_invoice(david, &onion_message);
1145         assert_eq!(invoice1.payer_metadata(), invoice2.payer_metadata());
1146
1147         // David sends an error instead of paying the second invoice
1148         let onion_message = david.onion_messenger.next_onion_message_for_peer(bob_id).unwrap();
1149         bob.onion_messenger.handle_onion_message(&david_id, &onion_message);
1150
1151         let onion_message = bob.onion_messenger.next_onion_message_for_peer(alice_id).unwrap();
1152         alice.onion_messenger.handle_onion_message(&bob_id, &onion_message);
1153
1154         let invoice_error = extract_invoice_error(alice, &onion_message);
1155         assert_eq!(invoice_error, InvoiceError::from_string("DuplicateInvoice".to_string()));
1156 }