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