Remove InvoiceRequestFields::amount_msats
[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::constants::Network;
44 use core::time::Duration;
45 use crate::blinded_path::{BlindedPath, IntroductionNode};
46 use crate::blinded_path::payment::{Bolt12OfferContext, Bolt12RefundContext, PaymentContext};
47 use crate::events::{Event, MessageSendEventsProvider, PaymentPurpose};
48 use crate::ln::channelmanager::{PaymentId, RecentPaymentDetails, Retry, self};
49 use crate::ln::features::InvoiceRequestFeatures;
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 route_bolt12_payment<'a, 'b, 'c>(
138         node: &Node<'a, 'b, 'c>, path: &[&Node<'a, 'b, 'c>], invoice: &Bolt12Invoice
139 ) {
140         // Monitor added when handling the invoice onion message.
141         check_added_monitors(node, 1);
142
143         let mut events = node.node.get_and_clear_pending_msg_events();
144         assert_eq!(events.len(), 1);
145         let ev = remove_first_msg_event_to_node(&path[0].node.get_our_node_id(), &mut events);
146
147         // Use a fake payment_hash and bypass checking for the PaymentClaimable event since the
148         // invoice contains the payment_hash but it was encrypted inside an onion message.
149         let amount_msats = invoice.amount_msats();
150         let payment_hash = invoice.payment_hash();
151         let args = PassAlongPathArgs::new(node, path, amount_msats, payment_hash, ev)
152                 .without_clearing_recipient_events();
153         do_pass_along_path(args);
154 }
155
156 fn claim_bolt12_payment<'a, 'b, 'c>(
157         node: &Node<'a, 'b, 'c>, path: &[&Node<'a, 'b, 'c>], expected_payment_context: PaymentContext
158 ) {
159         let recipient = &path[path.len() - 1];
160         let payment_purpose = match get_event!(recipient, Event::PaymentClaimable) {
161                 Event::PaymentClaimable { purpose, .. } => purpose,
162                 _ => panic!("No Event::PaymentClaimable"),
163         };
164         let payment_preimage = match payment_purpose.preimage() {
165                 Some(preimage) => preimage,
166                 None => panic!("No preimage in Event::PaymentClaimable"),
167         };
168         match payment_purpose {
169                 PaymentPurpose::Bolt12OfferPayment { payment_context, .. } => {
170                         assert_eq!(PaymentContext::Bolt12Offer(payment_context), expected_payment_context);
171                 },
172                 PaymentPurpose::Bolt12RefundPayment { payment_context, .. } => {
173                         assert_eq!(PaymentContext::Bolt12Refund(payment_context), expected_payment_context);
174                 },
175                 _ => panic!("Unexpected payment purpose: {:?}", payment_purpose),
176         }
177         claim_payment(node, path, payment_preimage);
178 }
179
180 fn extract_invoice_request<'a, 'b, 'c>(
181         node: &Node<'a, 'b, 'c>, message: &OnionMessage
182 ) -> (InvoiceRequest, Option<BlindedPath>) {
183         match node.onion_messenger.peel_onion_message(message) {
184                 Ok(PeeledOnion::Receive(message, _, reply_path)) => match message {
185                         ParsedOnionMessageContents::Offers(offers_message) => match offers_message {
186                                 OffersMessage::InvoiceRequest(invoice_request) => (invoice_request, reply_path),
187                                 OffersMessage::Invoice(invoice) => panic!("Unexpected invoice: {:?}", invoice),
188                                 OffersMessage::InvoiceError(error) => panic!("Unexpected invoice_error: {:?}", error),
189                         },
190                         ParsedOnionMessageContents::Custom(message) => panic!("Unexpected custom message: {:?}", message),
191                 },
192                 Ok(PeeledOnion::Forward(_, _)) => panic!("Unexpected onion message forward"),
193                 Err(e) => panic!("Failed to process onion message {:?}", e),
194         }
195 }
196
197 fn extract_invoice<'a, 'b, 'c>(node: &Node<'a, 'b, 'c>, message: &OnionMessage) -> Bolt12Invoice {
198         match node.onion_messenger.peel_onion_message(message) {
199                 Ok(PeeledOnion::Receive(message, _, _)) => match message {
200                         ParsedOnionMessageContents::Offers(offers_message) => match offers_message {
201                                 OffersMessage::InvoiceRequest(invoice_request) => panic!("Unexpected invoice_request: {:?}", invoice_request),
202                                 OffersMessage::Invoice(invoice) => invoice,
203                                 OffersMessage::InvoiceError(error) => panic!("Unexpected invoice_error: {:?}", error),
204                         },
205                         ParsedOnionMessageContents::Custom(message) => panic!("Unexpected custom message: {:?}", message),
206                 },
207                 Ok(PeeledOnion::Forward(_, _)) => panic!("Unexpected onion message forward"),
208                 Err(e) => panic!("Failed to process onion message {:?}", e),
209         }
210 }
211
212 fn extract_invoice_error<'a, 'b, 'c>(
213         node: &Node<'a, 'b, 'c>, message: &OnionMessage
214 ) -> InvoiceError {
215         match node.onion_messenger.peel_onion_message(message) {
216                 Ok(PeeledOnion::Receive(message, _, _)) => match message {
217                         ParsedOnionMessageContents::Offers(offers_message) => match offers_message {
218                                 OffersMessage::InvoiceRequest(invoice_request) => panic!("Unexpected invoice_request: {:?}", invoice_request),
219                                 OffersMessage::Invoice(invoice) => panic!("Unexpected invoice: {:?}", invoice),
220                                 OffersMessage::InvoiceError(error) => error,
221                         },
222                         ParsedOnionMessageContents::Custom(message) => panic!("Unexpected custom message: {:?}", message),
223                 },
224                 Ok(PeeledOnion::Forward(_, _)) => panic!("Unexpected onion message forward"),
225                 Err(e) => panic!("Failed to process onion message {:?}", e),
226         }
227 }
228
229 /// Checks that blinded paths without Tor-only nodes are preferred when constructing an offer.
230 #[test]
231 fn prefers_non_tor_nodes_in_blinded_paths() {
232         let mut accept_forward_cfg = test_default_channel_config();
233         accept_forward_cfg.accept_forwards_to_priv_channels = true;
234
235         let mut features = channelmanager::provided_init_features(&accept_forward_cfg);
236         features.set_onion_messages_optional();
237         features.set_route_blinding_optional();
238
239         let chanmon_cfgs = create_chanmon_cfgs(6);
240         let node_cfgs = create_node_cfgs(6, &chanmon_cfgs);
241
242         *node_cfgs[1].override_init_features.borrow_mut() = Some(features);
243
244         let node_chanmgrs = create_node_chanmgrs(
245                 6, &node_cfgs, &[None, Some(accept_forward_cfg), None, None, None, None]
246         );
247         let nodes = create_network(6, &node_cfgs, &node_chanmgrs);
248
249         create_unannounced_chan_between_nodes_with_value(&nodes, 0, 1, 10_000_000, 1_000_000_000);
250         create_unannounced_chan_between_nodes_with_value(&nodes, 2, 3, 10_000_000, 1_000_000_000);
251         create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 10_000_000, 1_000_000_000);
252         create_announced_chan_between_nodes_with_value(&nodes, 1, 4, 10_000_000, 1_000_000_000);
253         create_announced_chan_between_nodes_with_value(&nodes, 1, 5, 10_000_000, 1_000_000_000);
254         create_announced_chan_between_nodes_with_value(&nodes, 2, 4, 10_000_000, 1_000_000_000);
255         create_announced_chan_between_nodes_with_value(&nodes, 2, 5, 10_000_000, 1_000_000_000);
256
257         // Add an extra channel so that more than one of Bob's peers have MIN_PEER_CHANNELS.
258         create_announced_chan_between_nodes_with_value(&nodes, 4, 5, 10_000_000, 1_000_000_000);
259
260         let (alice, bob, charlie, david) = (&nodes[0], &nodes[1], &nodes[2], &nodes[3]);
261         let bob_id = bob.node.get_our_node_id();
262         let charlie_id = charlie.node.get_our_node_id();
263
264         disconnect_peers(alice, &[charlie, david, &nodes[4], &nodes[5]]);
265         disconnect_peers(david, &[bob, &nodes[4], &nodes[5]]);
266
267         let tor = SocketAddress::OnionV2([255, 254, 253, 252, 251, 250, 249, 248, 247, 246, 38, 7]);
268         announce_node_address(charlie, &[alice, bob, david, &nodes[4], &nodes[5]], tor.clone());
269
270         let offer = bob.node
271                 .create_offer_builder("coffee".to_string()).unwrap()
272                 .amount_msats(10_000_000)
273                 .build().unwrap();
274         assert_ne!(offer.signing_pubkey(), bob_id);
275         assert!(!offer.paths().is_empty());
276         for path in offer.paths() {
277                 assert_ne!(path.introduction_node, IntroductionNode::NodeId(bob_id));
278                 assert_ne!(path.introduction_node, IntroductionNode::NodeId(charlie_id));
279         }
280
281         // Use a one-hop blinded path when Bob is announced and all his peers are Tor-only.
282         announce_node_address(&nodes[4], &[alice, bob, charlie, david, &nodes[5]], tor.clone());
283         announce_node_address(&nodes[5], &[alice, bob, charlie, david, &nodes[4]], tor.clone());
284
285         let offer = bob.node
286                 .create_offer_builder("coffee".to_string()).unwrap()
287                 .amount_msats(10_000_000)
288                 .build().unwrap();
289         assert_ne!(offer.signing_pubkey(), bob_id);
290         assert!(!offer.paths().is_empty());
291         for path in offer.paths() {
292                 assert_eq!(path.introduction_node, IntroductionNode::NodeId(bob_id));
293         }
294 }
295
296 /// Checks that blinded paths prefer an introduction node that is the most connected.
297 #[test]
298 fn prefers_more_connected_nodes_in_blinded_paths() {
299         let mut accept_forward_cfg = test_default_channel_config();
300         accept_forward_cfg.accept_forwards_to_priv_channels = true;
301
302         let mut features = channelmanager::provided_init_features(&accept_forward_cfg);
303         features.set_onion_messages_optional();
304         features.set_route_blinding_optional();
305
306         let chanmon_cfgs = create_chanmon_cfgs(6);
307         let node_cfgs = create_node_cfgs(6, &chanmon_cfgs);
308
309         *node_cfgs[1].override_init_features.borrow_mut() = Some(features);
310
311         let node_chanmgrs = create_node_chanmgrs(
312                 6, &node_cfgs, &[None, Some(accept_forward_cfg), None, None, None, None]
313         );
314         let nodes = create_network(6, &node_cfgs, &node_chanmgrs);
315
316         create_unannounced_chan_between_nodes_with_value(&nodes, 0, 1, 10_000_000, 1_000_000_000);
317         create_unannounced_chan_between_nodes_with_value(&nodes, 2, 3, 10_000_000, 1_000_000_000);
318         create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 10_000_000, 1_000_000_000);
319         create_announced_chan_between_nodes_with_value(&nodes, 1, 4, 10_000_000, 1_000_000_000);
320         create_announced_chan_between_nodes_with_value(&nodes, 1, 5, 10_000_000, 1_000_000_000);
321         create_announced_chan_between_nodes_with_value(&nodes, 2, 4, 10_000_000, 1_000_000_000);
322         create_announced_chan_between_nodes_with_value(&nodes, 2, 5, 10_000_000, 1_000_000_000);
323
324         // Add extra channels so that more than one of Bob's peers have MIN_PEER_CHANNELS and one has
325         // more than the others.
326         create_announced_chan_between_nodes_with_value(&nodes, 0, 4, 10_000_000, 1_000_000_000);
327         create_announced_chan_between_nodes_with_value(&nodes, 3, 4, 10_000_000, 1_000_000_000);
328
329         let (alice, bob, charlie, david) = (&nodes[0], &nodes[1], &nodes[2], &nodes[3]);
330         let bob_id = bob.node.get_our_node_id();
331
332         disconnect_peers(alice, &[charlie, david, &nodes[4], &nodes[5]]);
333         disconnect_peers(david, &[bob, &nodes[4], &nodes[5]]);
334
335         let offer = bob.node
336                 .create_offer_builder("coffee".to_string()).unwrap()
337                 .amount_msats(10_000_000)
338                 .build().unwrap();
339         assert_ne!(offer.signing_pubkey(), bob_id);
340         assert!(!offer.paths().is_empty());
341         for path in offer.paths() {
342                 assert_eq!(path.introduction_node, IntroductionNode::NodeId(nodes[4].node.get_our_node_id()));
343         }
344 }
345
346 /// Checks that an offer can be paid through blinded paths and that ephemeral pubkeys are used
347 /// rather than exposing a node's pubkey.
348 #[test]
349 fn creates_and_pays_for_offer_using_two_hop_blinded_path() {
350         let mut accept_forward_cfg = test_default_channel_config();
351         accept_forward_cfg.accept_forwards_to_priv_channels = true;
352
353         let mut features = channelmanager::provided_init_features(&accept_forward_cfg);
354         features.set_onion_messages_optional();
355         features.set_route_blinding_optional();
356
357         let chanmon_cfgs = create_chanmon_cfgs(6);
358         let node_cfgs = create_node_cfgs(6, &chanmon_cfgs);
359
360         *node_cfgs[1].override_init_features.borrow_mut() = Some(features);
361
362         let node_chanmgrs = create_node_chanmgrs(
363                 6, &node_cfgs, &[None, Some(accept_forward_cfg), None, None, None, None]
364         );
365         let nodes = create_network(6, &node_cfgs, &node_chanmgrs);
366
367         create_unannounced_chan_between_nodes_with_value(&nodes, 0, 1, 10_000_000, 1_000_000_000);
368         create_unannounced_chan_between_nodes_with_value(&nodes, 2, 3, 10_000_000, 1_000_000_000);
369         create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 10_000_000, 1_000_000_000);
370         create_announced_chan_between_nodes_with_value(&nodes, 1, 4, 10_000_000, 1_000_000_000);
371         create_announced_chan_between_nodes_with_value(&nodes, 1, 5, 10_000_000, 1_000_000_000);
372         create_announced_chan_between_nodes_with_value(&nodes, 2, 4, 10_000_000, 1_000_000_000);
373         create_announced_chan_between_nodes_with_value(&nodes, 2, 5, 10_000_000, 1_000_000_000);
374
375         let (alice, bob, charlie, david) = (&nodes[0], &nodes[1], &nodes[2], &nodes[3]);
376         let alice_id = alice.node.get_our_node_id();
377         let bob_id = bob.node.get_our_node_id();
378         let charlie_id = charlie.node.get_our_node_id();
379         let david_id = david.node.get_our_node_id();
380
381         disconnect_peers(alice, &[charlie, david, &nodes[4], &nodes[5]]);
382         disconnect_peers(david, &[bob, &nodes[4], &nodes[5]]);
383
384         let offer = alice.node
385                 .create_offer_builder("coffee".to_string())
386                 .unwrap()
387                 .amount_msats(10_000_000)
388                 .build().unwrap();
389         assert_ne!(offer.signing_pubkey(), alice_id);
390         assert!(!offer.paths().is_empty());
391         for path in offer.paths() {
392                 assert_eq!(path.introduction_node, IntroductionNode::NodeId(bob_id));
393         }
394
395         let payment_id = PaymentId([1; 32]);
396         david.node.pay_for_offer(&offer, None, None, None, payment_id, Retry::Attempts(0), None)
397                 .unwrap();
398         expect_recent_payment!(david, RecentPaymentDetails::AwaitingInvoice, payment_id);
399
400         connect_peers(david, bob);
401
402         let onion_message = david.onion_messenger.next_onion_message_for_peer(bob_id).unwrap();
403         bob.onion_messenger.handle_onion_message(&david_id, &onion_message);
404
405         connect_peers(alice, charlie);
406
407         let onion_message = bob.onion_messenger.next_onion_message_for_peer(alice_id).unwrap();
408         alice.onion_messenger.handle_onion_message(&bob_id, &onion_message);
409
410         let (invoice_request, reply_path) = extract_invoice_request(alice, &onion_message);
411         let payment_context = PaymentContext::Bolt12Offer(Bolt12OfferContext {
412                 offer_id: offer.id(),
413                 invoice_request: InvoiceRequestFields {
414                         payer_id: invoice_request.payer_id(),
415                         features: InvoiceRequestFeatures::empty(),
416                         quantity: None,
417                         payer_note_truncated: None,
418                 },
419         });
420         assert_eq!(invoice_request.amount_msats(), None);
421         assert_ne!(invoice_request.payer_id(), david_id);
422         assert_eq!(reply_path.unwrap().introduction_node, IntroductionNode::NodeId(charlie_id));
423
424         let onion_message = alice.onion_messenger.next_onion_message_for_peer(charlie_id).unwrap();
425         charlie.onion_messenger.handle_onion_message(&alice_id, &onion_message);
426
427         let onion_message = charlie.onion_messenger.next_onion_message_for_peer(david_id).unwrap();
428         david.onion_messenger.handle_onion_message(&charlie_id, &onion_message);
429
430         let invoice = extract_invoice(david, &onion_message);
431         assert_eq!(invoice.amount_msats(), 10_000_000);
432         assert_ne!(invoice.signing_pubkey(), alice_id);
433         assert!(!invoice.payment_paths().is_empty());
434         for (_, path) in invoice.payment_paths() {
435                 assert_eq!(path.introduction_node, IntroductionNode::NodeId(bob_id));
436         }
437
438         route_bolt12_payment(david, &[charlie, bob, alice], &invoice);
439         expect_recent_payment!(david, RecentPaymentDetails::Pending, payment_id);
440
441         claim_bolt12_payment(david, &[charlie, bob, alice], payment_context);
442         expect_recent_payment!(david, RecentPaymentDetails::Fulfilled, payment_id);
443 }
444
445 /// Checks that a refund can be paid through blinded paths and that ephemeral pubkeys are used
446 /// rather than exposing a node's pubkey.
447 #[test]
448 fn creates_and_pays_for_refund_using_two_hop_blinded_path() {
449         let mut accept_forward_cfg = test_default_channel_config();
450         accept_forward_cfg.accept_forwards_to_priv_channels = true;
451
452         let mut features = channelmanager::provided_init_features(&accept_forward_cfg);
453         features.set_onion_messages_optional();
454         features.set_route_blinding_optional();
455
456         let chanmon_cfgs = create_chanmon_cfgs(6);
457         let node_cfgs = create_node_cfgs(6, &chanmon_cfgs);
458
459         *node_cfgs[1].override_init_features.borrow_mut() = Some(features);
460
461         let node_chanmgrs = create_node_chanmgrs(
462                 6, &node_cfgs, &[None, Some(accept_forward_cfg), None, None, None, None]
463         );
464         let nodes = create_network(6, &node_cfgs, &node_chanmgrs);
465
466         create_unannounced_chan_between_nodes_with_value(&nodes, 0, 1, 10_000_000, 1_000_000_000);
467         create_unannounced_chan_between_nodes_with_value(&nodes, 2, 3, 10_000_000, 1_000_000_000);
468         create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 10_000_000, 1_000_000_000);
469         create_announced_chan_between_nodes_with_value(&nodes, 1, 4, 10_000_000, 1_000_000_000);
470         create_announced_chan_between_nodes_with_value(&nodes, 1, 5, 10_000_000, 1_000_000_000);
471         create_announced_chan_between_nodes_with_value(&nodes, 2, 4, 10_000_000, 1_000_000_000);
472         create_announced_chan_between_nodes_with_value(&nodes, 2, 5, 10_000_000, 1_000_000_000);
473
474         let (alice, bob, charlie, david) = (&nodes[0], &nodes[1], &nodes[2], &nodes[3]);
475         let alice_id = alice.node.get_our_node_id();
476         let bob_id = bob.node.get_our_node_id();
477         let charlie_id = charlie.node.get_our_node_id();
478         let david_id = david.node.get_our_node_id();
479
480         disconnect_peers(alice, &[charlie, david, &nodes[4], &nodes[5]]);
481         disconnect_peers(david, &[bob, &nodes[4], &nodes[5]]);
482
483         let absolute_expiry = Duration::from_secs(u64::MAX);
484         let payment_id = PaymentId([1; 32]);
485         let refund = david.node
486                 .create_refund_builder(
487                         "refund".to_string(), 10_000_000, absolute_expiry, payment_id, Retry::Attempts(0), None
488                 )
489                 .unwrap()
490                 .build().unwrap();
491         assert_eq!(refund.amount_msats(), 10_000_000);
492         assert_eq!(refund.absolute_expiry(), Some(absolute_expiry));
493         assert_ne!(refund.payer_id(), david_id);
494         assert!(!refund.paths().is_empty());
495         for path in refund.paths() {
496                 assert_eq!(path.introduction_node, IntroductionNode::NodeId(charlie_id));
497         }
498         expect_recent_payment!(david, RecentPaymentDetails::AwaitingInvoice, payment_id);
499
500         let payment_context = PaymentContext::Bolt12Refund(Bolt12RefundContext {});
501         let expected_invoice = alice.node.request_refund_payment(&refund).unwrap();
502
503         connect_peers(alice, charlie);
504
505         let onion_message = alice.onion_messenger.next_onion_message_for_peer(charlie_id).unwrap();
506         charlie.onion_messenger.handle_onion_message(&alice_id, &onion_message);
507
508         let onion_message = charlie.onion_messenger.next_onion_message_for_peer(david_id).unwrap();
509         david.onion_messenger.handle_onion_message(&charlie_id, &onion_message);
510
511         let invoice = extract_invoice(david, &onion_message);
512         assert_eq!(invoice, expected_invoice);
513
514         assert_eq!(invoice.amount_msats(), 10_000_000);
515         assert_ne!(invoice.signing_pubkey(), alice_id);
516         assert!(!invoice.payment_paths().is_empty());
517         for (_, path) in invoice.payment_paths() {
518                 assert_eq!(path.introduction_node, IntroductionNode::NodeId(bob_id));
519         }
520
521         route_bolt12_payment(david, &[charlie, bob, alice], &invoice);
522         expect_recent_payment!(david, RecentPaymentDetails::Pending, payment_id);
523
524         claim_bolt12_payment(david, &[charlie, bob, alice], payment_context);
525         expect_recent_payment!(david, RecentPaymentDetails::Fulfilled, payment_id);
526 }
527
528 /// Checks that an offer can be paid through a one-hop blinded path and that ephemeral pubkeys are
529 /// used rather than exposing a node's pubkey. However, the node's pubkey is still used as the
530 /// introduction node of the blinded path.
531 #[test]
532 fn creates_and_pays_for_offer_using_one_hop_blinded_path() {
533         let chanmon_cfgs = create_chanmon_cfgs(2);
534         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
535         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
536         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
537
538         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 10_000_000, 1_000_000_000);
539
540         let alice = &nodes[0];
541         let alice_id = alice.node.get_our_node_id();
542         let bob = &nodes[1];
543         let bob_id = bob.node.get_our_node_id();
544
545         let offer = alice.node
546                 .create_offer_builder("coffee".to_string()).unwrap()
547                 .amount_msats(10_000_000)
548                 .build().unwrap();
549         assert_ne!(offer.signing_pubkey(), alice_id);
550         assert!(!offer.paths().is_empty());
551         for path in offer.paths() {
552                 assert_eq!(path.introduction_node, IntroductionNode::NodeId(alice_id));
553         }
554
555         let payment_id = PaymentId([1; 32]);
556         bob.node.pay_for_offer(&offer, None, None, None, payment_id, Retry::Attempts(0), None).unwrap();
557         expect_recent_payment!(bob, RecentPaymentDetails::AwaitingInvoice, payment_id);
558
559         let onion_message = bob.onion_messenger.next_onion_message_for_peer(alice_id).unwrap();
560         alice.onion_messenger.handle_onion_message(&bob_id, &onion_message);
561
562         let (invoice_request, reply_path) = extract_invoice_request(alice, &onion_message);
563         let payment_context = PaymentContext::Bolt12Offer(Bolt12OfferContext {
564                 offer_id: offer.id(),
565                 invoice_request: InvoiceRequestFields {
566                         payer_id: invoice_request.payer_id(),
567                         features: InvoiceRequestFeatures::empty(),
568                         quantity: None,
569                         payer_note_truncated: None,
570                 },
571         });
572         assert_eq!(invoice_request.amount_msats(), None);
573         assert_ne!(invoice_request.payer_id(), bob_id);
574         assert_eq!(reply_path.unwrap().introduction_node, IntroductionNode::NodeId(bob_id));
575
576         let onion_message = alice.onion_messenger.next_onion_message_for_peer(bob_id).unwrap();
577         bob.onion_messenger.handle_onion_message(&alice_id, &onion_message);
578
579         let invoice = extract_invoice(bob, &onion_message);
580         assert_eq!(invoice.amount_msats(), 10_000_000);
581         assert_ne!(invoice.signing_pubkey(), alice_id);
582         assert!(!invoice.payment_paths().is_empty());
583         for (_, path) in invoice.payment_paths() {
584                 assert_eq!(path.introduction_node, IntroductionNode::NodeId(alice_id));
585         }
586
587         route_bolt12_payment(bob, &[alice], &invoice);
588         expect_recent_payment!(bob, RecentPaymentDetails::Pending, payment_id);
589
590         claim_bolt12_payment(bob, &[alice], payment_context);
591         expect_recent_payment!(bob, RecentPaymentDetails::Fulfilled, payment_id);
592 }
593
594 /// Checks that a refund can be paid through a one-hop blinded path and that ephemeral pubkeys are
595 /// used rather than exposing a node's pubkey. However, the node's pubkey is still used as the
596 /// introduction node of the blinded path.
597 #[test]
598 fn creates_and_pays_for_refund_using_one_hop_blinded_path() {
599         let chanmon_cfgs = create_chanmon_cfgs(2);
600         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
601         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
602         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
603
604         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 10_000_000, 1_000_000_000);
605
606         let alice = &nodes[0];
607         let alice_id = alice.node.get_our_node_id();
608         let bob = &nodes[1];
609         let bob_id = bob.node.get_our_node_id();
610
611         let absolute_expiry = Duration::from_secs(u64::MAX);
612         let payment_id = PaymentId([1; 32]);
613         let refund = bob.node
614                 .create_refund_builder(
615                         "refund".to_string(), 10_000_000, absolute_expiry, payment_id, Retry::Attempts(0), None
616                 )
617                 .unwrap()
618                 .build().unwrap();
619         assert_eq!(refund.amount_msats(), 10_000_000);
620         assert_eq!(refund.absolute_expiry(), Some(absolute_expiry));
621         assert_ne!(refund.payer_id(), bob_id);
622         assert!(!refund.paths().is_empty());
623         for path in refund.paths() {
624                 assert_eq!(path.introduction_node, IntroductionNode::NodeId(bob_id));
625         }
626         expect_recent_payment!(bob, RecentPaymentDetails::AwaitingInvoice, payment_id);
627
628         let payment_context = PaymentContext::Bolt12Refund(Bolt12RefundContext {});
629         let expected_invoice = alice.node.request_refund_payment(&refund).unwrap();
630
631         let onion_message = alice.onion_messenger.next_onion_message_for_peer(bob_id).unwrap();
632         bob.onion_messenger.handle_onion_message(&alice_id, &onion_message);
633
634         let invoice = extract_invoice(bob, &onion_message);
635         assert_eq!(invoice, expected_invoice);
636
637         assert_eq!(invoice.amount_msats(), 10_000_000);
638         assert_ne!(invoice.signing_pubkey(), alice_id);
639         assert!(!invoice.payment_paths().is_empty());
640         for (_, path) in invoice.payment_paths() {
641                 assert_eq!(path.introduction_node, IntroductionNode::NodeId(alice_id));
642         }
643
644         route_bolt12_payment(bob, &[alice], &invoice);
645         expect_recent_payment!(bob, RecentPaymentDetails::Pending, payment_id);
646
647         claim_bolt12_payment(bob, &[alice], payment_context);
648         expect_recent_payment!(bob, RecentPaymentDetails::Fulfilled, payment_id);
649 }
650
651 /// Checks that an invoice for an offer without any blinded paths can be requested. Note that while
652 /// the requested is sent directly using the node's pubkey, the response and the payment still use
653 /// blinded paths as required by the spec.
654 #[test]
655 fn pays_for_offer_without_blinded_paths() {
656         let chanmon_cfgs = create_chanmon_cfgs(2);
657         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
658         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
659         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
660
661         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 10_000_000, 1_000_000_000);
662
663         let alice = &nodes[0];
664         let alice_id = alice.node.get_our_node_id();
665         let bob = &nodes[1];
666         let bob_id = bob.node.get_our_node_id();
667
668         let offer = alice.node
669                 .create_offer_builder("coffee".to_string()).unwrap()
670                 .clear_paths()
671                 .amount_msats(10_000_000)
672                 .build().unwrap();
673         assert_eq!(offer.signing_pubkey(), alice_id);
674         assert!(offer.paths().is_empty());
675
676         let payment_id = PaymentId([1; 32]);
677         bob.node.pay_for_offer(&offer, None, None, None, payment_id, Retry::Attempts(0), None).unwrap();
678         expect_recent_payment!(bob, RecentPaymentDetails::AwaitingInvoice, payment_id);
679
680         let onion_message = bob.onion_messenger.next_onion_message_for_peer(alice_id).unwrap();
681         alice.onion_messenger.handle_onion_message(&bob_id, &onion_message);
682
683         let (invoice_request, _) = extract_invoice_request(alice, &onion_message);
684         let payment_context = PaymentContext::Bolt12Offer(Bolt12OfferContext {
685                 offer_id: offer.id(),
686                 invoice_request: InvoiceRequestFields {
687                         payer_id: invoice_request.payer_id(),
688                         features: InvoiceRequestFeatures::empty(),
689                         quantity: None,
690                         payer_note_truncated: None,
691                 },
692         });
693
694         let onion_message = alice.onion_messenger.next_onion_message_for_peer(bob_id).unwrap();
695         bob.onion_messenger.handle_onion_message(&alice_id, &onion_message);
696
697         let invoice = extract_invoice(bob, &onion_message);
698         route_bolt12_payment(bob, &[alice], &invoice);
699         expect_recent_payment!(bob, RecentPaymentDetails::Pending, payment_id);
700
701         claim_bolt12_payment(bob, &[alice], payment_context);
702         expect_recent_payment!(bob, RecentPaymentDetails::Fulfilled, payment_id);
703 }
704
705 /// Checks that a refund without any blinded paths can be paid. Note that while the invoice is sent
706 /// directly using the node's pubkey, the payment still use blinded paths as required by the spec.
707 #[test]
708 fn pays_for_refund_without_blinded_paths() {
709         let chanmon_cfgs = create_chanmon_cfgs(2);
710         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
711         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
712         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
713
714         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 10_000_000, 1_000_000_000);
715
716         let alice = &nodes[0];
717         let alice_id = alice.node.get_our_node_id();
718         let bob = &nodes[1];
719         let bob_id = bob.node.get_our_node_id();
720
721         let absolute_expiry = Duration::from_secs(u64::MAX);
722         let payment_id = PaymentId([1; 32]);
723         let refund = bob.node
724                 .create_refund_builder(
725                         "refund".to_string(), 10_000_000, absolute_expiry, payment_id, Retry::Attempts(0), None
726                 )
727                 .unwrap()
728                 .clear_paths()
729                 .build().unwrap();
730         assert_eq!(refund.payer_id(), bob_id);
731         assert!(refund.paths().is_empty());
732         expect_recent_payment!(bob, RecentPaymentDetails::AwaitingInvoice, payment_id);
733
734         let payment_context = PaymentContext::Bolt12Refund(Bolt12RefundContext {});
735         let expected_invoice = alice.node.request_refund_payment(&refund).unwrap();
736
737         let onion_message = alice.onion_messenger.next_onion_message_for_peer(bob_id).unwrap();
738         bob.onion_messenger.handle_onion_message(&alice_id, &onion_message);
739
740         let invoice = extract_invoice(bob, &onion_message);
741         assert_eq!(invoice, expected_invoice);
742
743         route_bolt12_payment(bob, &[alice], &invoice);
744         expect_recent_payment!(bob, RecentPaymentDetails::Pending, payment_id);
745
746         claim_bolt12_payment(bob, &[alice], payment_context);
747         expect_recent_payment!(bob, RecentPaymentDetails::Fulfilled, payment_id);
748 }
749
750 /// Fails creating an offer when a blinded path cannot be created without exposing the node's id.
751 #[test]
752 fn fails_creating_offer_without_blinded_paths() {
753         let chanmon_cfgs = create_chanmon_cfgs(2);
754         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
755         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
756         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
757
758         create_unannounced_chan_between_nodes_with_value(&nodes, 0, 1, 10_000_000, 1_000_000_000);
759
760         match nodes[0].node.create_offer_builder("coffee".to_string()) {
761                 Ok(_) => panic!("Expected error"),
762                 Err(e) => assert_eq!(e, Bolt12SemanticError::MissingPaths),
763         }
764 }
765
766 /// Fails creating a refund when a blinded path cannot be created without exposing the node's id.
767 #[test]
768 fn fails_creating_refund_without_blinded_paths() {
769         let chanmon_cfgs = create_chanmon_cfgs(2);
770         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
771         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
772         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
773
774         create_unannounced_chan_between_nodes_with_value(&nodes, 0, 1, 10_000_000, 1_000_000_000);
775
776         let absolute_expiry = Duration::from_secs(u64::MAX);
777         let payment_id = PaymentId([1; 32]);
778
779         match nodes[0].node.create_refund_builder(
780                 "refund".to_string(), 10_000, absolute_expiry, payment_id, Retry::Attempts(0), None
781         ) {
782                 Ok(_) => panic!("Expected error"),
783                 Err(e) => assert_eq!(e, Bolt12SemanticError::MissingPaths),
784         }
785
786         assert!(nodes[0].node.list_recent_payments().is_empty());
787 }
788
789 /// Fails creating an invoice request when the offer contains an unsupported chain.
790 #[test]
791 fn fails_creating_invoice_request_for_unsupported_chain() {
792         let chanmon_cfgs = create_chanmon_cfgs(2);
793         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
794         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
795         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
796
797         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 10_000_000, 1_000_000_000);
798
799         let alice = &nodes[0];
800         let bob = &nodes[1];
801
802         let offer = alice.node
803                 .create_offer_builder("coffee".to_string()).unwrap()
804                 .clear_chains()
805                 .chain(Network::Signet)
806                 .build().unwrap();
807
808         let payment_id = PaymentId([1; 32]);
809         match bob.node.pay_for_offer(&offer, None, None, None, payment_id, Retry::Attempts(0), None) {
810                 Ok(_) => panic!("Expected error"),
811                 Err(e) => assert_eq!(e, Bolt12SemanticError::UnsupportedChain),
812         }
813 }
814
815 /// Fails requesting a payment when the refund contains an unsupported chain.
816 #[test]
817 fn fails_sending_invoice_with_unsupported_chain_for_refund() {
818         let chanmon_cfgs = create_chanmon_cfgs(2);
819         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
820         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
821         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
822
823         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 10_000_000, 1_000_000_000);
824
825         let alice = &nodes[0];
826         let bob = &nodes[1];
827
828         let absolute_expiry = Duration::from_secs(u64::MAX);
829         let payment_id = PaymentId([1; 32]);
830         let refund = bob.node
831                 .create_refund_builder(
832                         "refund".to_string(), 10_000_000, absolute_expiry, payment_id, Retry::Attempts(0), None
833                 )
834                 .unwrap()
835                 .chain(Network::Signet)
836                 .build().unwrap();
837
838         match alice.node.request_refund_payment(&refund) {
839                 Ok(_) => panic!("Expected error"),
840                 Err(e) => assert_eq!(e, Bolt12SemanticError::UnsupportedChain),
841         }
842 }
843
844 /// Fails creating an invoice request when a blinded reply path cannot be created without exposing
845 /// the node's id.
846 #[test]
847 fn fails_creating_invoice_request_without_blinded_reply_path() {
848         let chanmon_cfgs = create_chanmon_cfgs(6);
849         let node_cfgs = create_node_cfgs(6, &chanmon_cfgs);
850         let node_chanmgrs = create_node_chanmgrs(6, &node_cfgs, &[None, None, None, None, None, None]);
851         let nodes = create_network(6, &node_cfgs, &node_chanmgrs);
852
853         create_unannounced_chan_between_nodes_with_value(&nodes, 0, 1, 10_000_000, 1_000_000_000);
854         create_unannounced_chan_between_nodes_with_value(&nodes, 2, 3, 10_000_000, 1_000_000_000);
855         create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 10_000_000, 1_000_000_000);
856         create_announced_chan_between_nodes_with_value(&nodes, 1, 4, 10_000_000, 1_000_000_000);
857         create_announced_chan_between_nodes_with_value(&nodes, 1, 5, 10_000_000, 1_000_000_000);
858
859         let (alice, bob, charlie, david) = (&nodes[0], &nodes[1], &nodes[2], &nodes[3]);
860
861         disconnect_peers(alice, &[charlie, david, &nodes[4], &nodes[5]]);
862         disconnect_peers(david, &[bob, &nodes[4], &nodes[5]]);
863
864         let offer = alice.node
865                 .create_offer_builder("coffee".to_string()).unwrap()
866                 .amount_msats(10_000_000)
867                 .build().unwrap();
868
869         let payment_id = PaymentId([1; 32]);
870
871         match david.node.pay_for_offer(&offer, None, None, None, payment_id, Retry::Attempts(0), None) {
872                 Ok(_) => panic!("Expected error"),
873                 Err(e) => assert_eq!(e, Bolt12SemanticError::MissingPaths),
874         }
875
876         assert!(nodes[0].node.list_recent_payments().is_empty());
877 }
878
879 #[test]
880 fn fails_creating_invoice_request_with_duplicate_payment_id() {
881         let chanmon_cfgs = create_chanmon_cfgs(6);
882         let node_cfgs = create_node_cfgs(6, &chanmon_cfgs);
883         let node_chanmgrs = create_node_chanmgrs(6, &node_cfgs, &[None, None, None, None, None, None]);
884         let nodes = create_network(6, &node_cfgs, &node_chanmgrs);
885
886         create_unannounced_chan_between_nodes_with_value(&nodes, 0, 1, 10_000_000, 1_000_000_000);
887         create_unannounced_chan_between_nodes_with_value(&nodes, 2, 3, 10_000_000, 1_000_000_000);
888         create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 10_000_000, 1_000_000_000);
889         create_announced_chan_between_nodes_with_value(&nodes, 1, 4, 10_000_000, 1_000_000_000);
890         create_announced_chan_between_nodes_with_value(&nodes, 1, 5, 10_000_000, 1_000_000_000);
891         create_announced_chan_between_nodes_with_value(&nodes, 2, 4, 10_000_000, 1_000_000_000);
892         create_announced_chan_between_nodes_with_value(&nodes, 2, 5, 10_000_000, 1_000_000_000);
893
894         let (alice, _bob, charlie, david) = (&nodes[0], &nodes[1], &nodes[2], &nodes[3]);
895
896         disconnect_peers(alice, &[charlie, david, &nodes[4], &nodes[5]]);
897
898         let offer = alice.node
899                 .create_offer_builder("coffee".to_string()).unwrap()
900                 .amount_msats(10_000_000)
901                 .build().unwrap();
902
903         let payment_id = PaymentId([1; 32]);
904         assert!(
905                 david.node.pay_for_offer(
906                         &offer, None, None, None, payment_id, Retry::Attempts(0), None
907                 ).is_ok()
908         );
909         expect_recent_payment!(david, RecentPaymentDetails::AwaitingInvoice, payment_id);
910
911         match david.node.pay_for_offer(&offer, None, None, None, payment_id, Retry::Attempts(0), None) {
912                 Ok(_) => panic!("Expected error"),
913                 Err(e) => assert_eq!(e, Bolt12SemanticError::DuplicatePaymentId),
914         }
915
916         expect_recent_payment!(david, RecentPaymentDetails::AwaitingInvoice, payment_id);
917 }
918
919 #[test]
920 fn fails_creating_refund_with_duplicate_payment_id() {
921         let chanmon_cfgs = create_chanmon_cfgs(2);
922         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
923         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
924         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
925
926         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 10_000_000, 1_000_000_000);
927
928         let absolute_expiry = Duration::from_secs(u64::MAX);
929         let payment_id = PaymentId([1; 32]);
930         assert!(
931                 nodes[0].node.create_refund_builder(
932                         "refund".to_string(), 10_000, absolute_expiry, payment_id, Retry::Attempts(0), None
933                 ).is_ok()
934         );
935         expect_recent_payment!(nodes[0], RecentPaymentDetails::AwaitingInvoice, payment_id);
936
937         match nodes[0].node.create_refund_builder(
938                 "refund".to_string(), 10_000, absolute_expiry, payment_id, Retry::Attempts(0), None
939         ) {
940                 Ok(_) => panic!("Expected error"),
941                 Err(e) => assert_eq!(e, Bolt12SemanticError::DuplicatePaymentId),
942         }
943
944         expect_recent_payment!(nodes[0], RecentPaymentDetails::AwaitingInvoice, payment_id);
945 }
946
947 #[test]
948 fn fails_sending_invoice_without_blinded_payment_paths_for_offer() {
949         let mut accept_forward_cfg = test_default_channel_config();
950         accept_forward_cfg.accept_forwards_to_priv_channels = true;
951
952         // Clearing route_blinding prevents forming any payment paths since the node is unannounced.
953         let mut features = channelmanager::provided_init_features(&accept_forward_cfg);
954         features.set_onion_messages_optional();
955         features.clear_route_blinding();
956
957         let chanmon_cfgs = create_chanmon_cfgs(6);
958         let node_cfgs = create_node_cfgs(6, &chanmon_cfgs);
959
960         *node_cfgs[1].override_init_features.borrow_mut() = Some(features);
961
962         let node_chanmgrs = create_node_chanmgrs(
963                 6, &node_cfgs, &[None, Some(accept_forward_cfg), None, None, None, None]
964         );
965         let nodes = create_network(6, &node_cfgs, &node_chanmgrs);
966
967         create_unannounced_chan_between_nodes_with_value(&nodes, 0, 1, 10_000_000, 1_000_000_000);
968         create_unannounced_chan_between_nodes_with_value(&nodes, 2, 3, 10_000_000, 1_000_000_000);
969         create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 10_000_000, 1_000_000_000);
970         create_announced_chan_between_nodes_with_value(&nodes, 1, 4, 10_000_000, 1_000_000_000);
971         create_announced_chan_between_nodes_with_value(&nodes, 1, 5, 10_000_000, 1_000_000_000);
972         create_announced_chan_between_nodes_with_value(&nodes, 2, 4, 10_000_000, 1_000_000_000);
973         create_announced_chan_between_nodes_with_value(&nodes, 2, 5, 10_000_000, 1_000_000_000);
974
975         let (alice, bob, charlie, david) = (&nodes[0], &nodes[1], &nodes[2], &nodes[3]);
976         let alice_id = alice.node.get_our_node_id();
977         let bob_id = bob.node.get_our_node_id();
978         let charlie_id = charlie.node.get_our_node_id();
979         let david_id = david.node.get_our_node_id();
980
981         disconnect_peers(alice, &[charlie, david, &nodes[4], &nodes[5]]);
982         disconnect_peers(david, &[bob, &nodes[4], &nodes[5]]);
983
984         let offer = alice.node
985                 .create_offer_builder("coffee".to_string()).unwrap()
986                 .amount_msats(10_000_000)
987                 .build().unwrap();
988
989         let payment_id = PaymentId([1; 32]);
990         david.node.pay_for_offer(&offer, None, None, None, payment_id, Retry::Attempts(0), None)
991                 .unwrap();
992
993         connect_peers(david, bob);
994
995         let onion_message = david.onion_messenger.next_onion_message_for_peer(bob_id).unwrap();
996         bob.onion_messenger.handle_onion_message(&david_id, &onion_message);
997
998         connect_peers(alice, charlie);
999
1000         let onion_message = bob.onion_messenger.next_onion_message_for_peer(alice_id).unwrap();
1001         alice.onion_messenger.handle_onion_message(&bob_id, &onion_message);
1002
1003         let onion_message = alice.onion_messenger.next_onion_message_for_peer(charlie_id).unwrap();
1004         charlie.onion_messenger.handle_onion_message(&alice_id, &onion_message);
1005
1006         let onion_message = charlie.onion_messenger.next_onion_message_for_peer(david_id).unwrap();
1007         david.onion_messenger.handle_onion_message(&charlie_id, &onion_message);
1008
1009         let invoice_error = extract_invoice_error(david, &onion_message);
1010         assert_eq!(invoice_error, InvoiceError::from(Bolt12SemanticError::MissingPaths));
1011 }
1012
1013 #[test]
1014 fn fails_sending_invoice_without_blinded_payment_paths_for_refund() {
1015         let mut accept_forward_cfg = test_default_channel_config();
1016         accept_forward_cfg.accept_forwards_to_priv_channels = true;
1017
1018         // Clearing route_blinding prevents forming any payment paths since the node is unannounced.
1019         let mut features = channelmanager::provided_init_features(&accept_forward_cfg);
1020         features.set_onion_messages_optional();
1021         features.clear_route_blinding();
1022
1023         let chanmon_cfgs = create_chanmon_cfgs(6);
1024         let node_cfgs = create_node_cfgs(6, &chanmon_cfgs);
1025
1026         *node_cfgs[1].override_init_features.borrow_mut() = Some(features);
1027
1028         let node_chanmgrs = create_node_chanmgrs(
1029                 6, &node_cfgs, &[None, Some(accept_forward_cfg), None, None, None, None]
1030         );
1031         let nodes = create_network(6, &node_cfgs, &node_chanmgrs);
1032
1033         create_unannounced_chan_between_nodes_with_value(&nodes, 0, 1, 10_000_000, 1_000_000_000);
1034         create_unannounced_chan_between_nodes_with_value(&nodes, 2, 3, 10_000_000, 1_000_000_000);
1035         create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 10_000_000, 1_000_000_000);
1036         create_announced_chan_between_nodes_with_value(&nodes, 1, 4, 10_000_000, 1_000_000_000);
1037         create_announced_chan_between_nodes_with_value(&nodes, 1, 5, 10_000_000, 1_000_000_000);
1038         create_announced_chan_between_nodes_with_value(&nodes, 2, 4, 10_000_000, 1_000_000_000);
1039         create_announced_chan_between_nodes_with_value(&nodes, 2, 5, 10_000_000, 1_000_000_000);
1040
1041         let (alice, bob, charlie, david) = (&nodes[0], &nodes[1], &nodes[2], &nodes[3]);
1042
1043         disconnect_peers(alice, &[charlie, david, &nodes[4], &nodes[5]]);
1044         disconnect_peers(david, &[bob, &nodes[4], &nodes[5]]);
1045
1046         let absolute_expiry = Duration::from_secs(u64::MAX);
1047         let payment_id = PaymentId([1; 32]);
1048         let refund = david.node
1049                 .create_refund_builder(
1050                         "refund".to_string(), 10_000_000, absolute_expiry, payment_id, Retry::Attempts(0), None
1051                 )
1052                 .unwrap()
1053                 .build().unwrap();
1054
1055         match alice.node.request_refund_payment(&refund) {
1056                 Ok(_) => panic!("Expected error"),
1057                 Err(e) => assert_eq!(e, Bolt12SemanticError::MissingPaths),
1058         }
1059 }
1060
1061 #[test]
1062 fn fails_paying_invoice_more_than_once() {
1063         let mut accept_forward_cfg = test_default_channel_config();
1064         accept_forward_cfg.accept_forwards_to_priv_channels = true;
1065
1066         let mut features = channelmanager::provided_init_features(&accept_forward_cfg);
1067         features.set_onion_messages_optional();
1068         features.set_route_blinding_optional();
1069
1070         let chanmon_cfgs = create_chanmon_cfgs(6);
1071         let node_cfgs = create_node_cfgs(6, &chanmon_cfgs);
1072
1073         *node_cfgs[1].override_init_features.borrow_mut() = Some(features);
1074
1075         let node_chanmgrs = create_node_chanmgrs(
1076                 6, &node_cfgs, &[None, Some(accept_forward_cfg), None, None, None, None]
1077         );
1078         let nodes = create_network(6, &node_cfgs, &node_chanmgrs);
1079
1080         create_unannounced_chan_between_nodes_with_value(&nodes, 0, 1, 10_000_000, 1_000_000_000);
1081         create_unannounced_chan_between_nodes_with_value(&nodes, 2, 3, 10_000_000, 1_000_000_000);
1082         create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 10_000_000, 1_000_000_000);
1083         create_announced_chan_between_nodes_with_value(&nodes, 1, 4, 10_000_000, 1_000_000_000);
1084         create_announced_chan_between_nodes_with_value(&nodes, 1, 5, 10_000_000, 1_000_000_000);
1085         create_announced_chan_between_nodes_with_value(&nodes, 2, 4, 10_000_000, 1_000_000_000);
1086         create_announced_chan_between_nodes_with_value(&nodes, 2, 5, 10_000_000, 1_000_000_000);
1087
1088         let (alice, bob, charlie, david) = (&nodes[0], &nodes[1], &nodes[2], &nodes[3]);
1089         let alice_id = alice.node.get_our_node_id();
1090         let bob_id = bob.node.get_our_node_id();
1091         let charlie_id = charlie.node.get_our_node_id();
1092         let david_id = david.node.get_our_node_id();
1093
1094         disconnect_peers(alice, &[charlie, david, &nodes[4], &nodes[5]]);
1095         disconnect_peers(david, &[bob, &nodes[4], &nodes[5]]);
1096
1097         let absolute_expiry = Duration::from_secs(u64::MAX);
1098         let payment_id = PaymentId([1; 32]);
1099         let refund = david.node
1100                 .create_refund_builder(
1101                         "refund".to_string(), 10_000_000, absolute_expiry, payment_id, Retry::Attempts(0), None
1102                 )
1103                 .unwrap()
1104                 .build().unwrap();
1105         expect_recent_payment!(david, RecentPaymentDetails::AwaitingInvoice, payment_id);
1106
1107         // Alice sends the first invoice
1108         alice.node.request_refund_payment(&refund).unwrap();
1109
1110         connect_peers(alice, charlie);
1111
1112         let onion_message = alice.onion_messenger.next_onion_message_for_peer(charlie_id).unwrap();
1113         charlie.onion_messenger.handle_onion_message(&alice_id, &onion_message);
1114
1115         let onion_message = charlie.onion_messenger.next_onion_message_for_peer(david_id).unwrap();
1116         david.onion_messenger.handle_onion_message(&charlie_id, &onion_message);
1117
1118         // David pays the first invoice
1119         let payment_context = PaymentContext::Bolt12Refund(Bolt12RefundContext {});
1120         let invoice1 = extract_invoice(david, &onion_message);
1121
1122         route_bolt12_payment(david, &[charlie, bob, alice], &invoice1);
1123         expect_recent_payment!(david, RecentPaymentDetails::Pending, payment_id);
1124
1125         claim_bolt12_payment(david, &[charlie, bob, alice], payment_context);
1126         expect_recent_payment!(david, RecentPaymentDetails::Fulfilled, payment_id);
1127
1128         disconnect_peers(alice, &[charlie]);
1129
1130         // Alice sends the second invoice
1131         alice.node.request_refund_payment(&refund).unwrap();
1132
1133         connect_peers(alice, charlie);
1134         connect_peers(david, bob);
1135
1136         let onion_message = alice.onion_messenger.next_onion_message_for_peer(charlie_id).unwrap();
1137         charlie.onion_messenger.handle_onion_message(&alice_id, &onion_message);
1138
1139         let onion_message = charlie.onion_messenger.next_onion_message_for_peer(david_id).unwrap();
1140         david.onion_messenger.handle_onion_message(&charlie_id, &onion_message);
1141
1142         let invoice2 = extract_invoice(david, &onion_message);
1143         assert_eq!(invoice1.payer_metadata(), invoice2.payer_metadata());
1144
1145         // David sends an error instead of paying the second invoice
1146         let onion_message = david.onion_messenger.next_onion_message_for_peer(bob_id).unwrap();
1147         bob.onion_messenger.handle_onion_message(&david_id, &onion_message);
1148
1149         let onion_message = bob.onion_messenger.next_onion_message_for_peer(alice_id).unwrap();
1150         alice.onion_messenger.handle_onion_message(&bob_id, &onion_message);
1151
1152         let invoice_error = extract_invoice_error(alice, &onion_message);
1153         assert_eq!(invoice_error, InvoiceError::from_string("DuplicateInvoice".to_string()));
1154 }