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