-
Notifications
You must be signed in to change notification settings - Fork 456
Expand file tree
/
Copy pathasync_payments_tests.rs
More file actions
3462 lines (3094 loc) · 134 KB
/
async_payments_tests.rs
File metadata and controls
3462 lines (3094 loc) · 134 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// This file is Copyright its original authors, visible in version control
// history.
//
// This file is licensed under the Apache License, Version 2.0 <LICENSE-APACHE
// or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option.
// You may not use this file except in accordance with one or both of these
// licenses.
use crate::blinded_path::message::{
BlindedMessagePath, MessageContext, NextMessageHop, OffersContext,
};
use crate::blinded_path::payment::{AsyncBolt12OfferContext, BlindedPaymentTlvs};
use crate::blinded_path::payment::{DummyTlvs, PaymentContext};
use crate::chain::channelmonitor::{HTLC_FAIL_BACK_BUFFER, LATENCY_GRACE_PERIOD_BLOCKS};
use crate::events::{
Event, EventsProvider, HTLCHandlingFailureReason, HTLCHandlingFailureType, PaidBolt12Invoice,
PaymentFailureReason, PaymentPurpose,
};
use crate::ln::blinded_payment_tests::{fail_blinded_htlc_backwards, get_blinded_route_parameters};
use crate::ln::channelmanager::{OptionalOfferPaymentParams, PaymentId, MIN_CLTV_EXPIRY_DELTA};
use crate::ln::functional_test_utils::*;
use crate::ln::inbound_payment;
use crate::ln::msgs;
use crate::ln::msgs::{
BaseMessageHandler, ChannelMessageHandler, MessageSendEvent, OnionMessageHandler,
};
use crate::ln::offers_tests;
use crate::ln::onion_utils::LocalHTLCFailureReason;
use crate::ln::outbound_payment::{Bolt12PaymentError, RecipientOnionFields};
use crate::ln::outbound_payment::{
PendingOutboundPayment, Retry, TEST_ASYNC_PAYMENT_TIMEOUT_RELATIVE_EXPIRY,
};
use crate::offers::async_receive_offer_cache::{
TEST_INVOICE_REFRESH_THRESHOLD, TEST_MAX_CACHED_OFFERS_TARGET, TEST_MAX_UPDATE_ATTEMPTS,
TEST_MIN_OFFER_PATHS_RELATIVE_EXPIRY_SECS, TEST_OFFER_REFRESH_THRESHOLD,
};
use crate::offers::flow::{
TEST_DEFAULT_ASYNC_RECEIVE_OFFER_EXPIRY, TEST_OFFERS_MESSAGE_REQUEST_LIMIT,
TEST_TEMP_REPLY_PATH_RELATIVE_EXPIRY,
};
use crate::offers::invoice_request::InvoiceRequest;
use crate::offers::nonce::Nonce;
use crate::offers::offer::{Amount, Offer};
use crate::offers::static_invoice::{
StaticInvoice, StaticInvoiceBuilder,
DEFAULT_RELATIVE_EXPIRY as STATIC_INVOICE_DEFAULT_RELATIVE_EXPIRY,
};
use crate::onion_message::async_payments::{AsyncPaymentsMessage, AsyncPaymentsMessageHandler};
use crate::onion_message::messenger::{
Destination, MessageRouter, MessageSendInstructions, PeeledOnion,
};
use crate::onion_message::offers::OffersMessage;
use crate::onion_message::packet::ParsedOnionMessageContents;
use crate::prelude::*;
use crate::routing::router::{Payee, PaymentParameters, DEFAULT_PAYMENT_DUMMY_HOPS};
use crate::sign::NodeSigner;
use crate::sync::Mutex;
use crate::types::features::Bolt12InvoiceFeatures;
use crate::types::payment::{PaymentHash, PaymentPreimage, PaymentSecret};
use crate::util::config::{HTLCInterceptionFlags, UserConfig};
use crate::util::ser::Writeable;
use bitcoin::constants::ChainHash;
use bitcoin::network::Network;
use bitcoin::secp256k1;
use bitcoin::secp256k1::{PublicKey, Secp256k1};
use core::convert::Infallible;
use core::time::Duration;
struct StaticInvoiceServerFlowResult {
invoice: StaticInvoice,
invoice_slot: u16,
invoice_request_path: BlindedMessagePath,
// Returning messages that were sent along the way allows us to test handling duplicate messages.
offer_paths_request: msgs::OnionMessage,
static_invoice_persisted_message: msgs::OnionMessage,
}
// Go through the flow of interactively building a `StaticInvoice`, returning the
// AsyncPaymentsMessage::ServeStaticInvoice that has yet to be provided to the server node.
// Assumes that the sender and recipient are only peers with each other.
//
// Returns (offer_paths_req, serve_static_invoice)
fn invoice_flow_up_to_send_serve_static_invoice(
server: &Node, recipient: &Node,
) -> (msgs::OnionMessage, msgs::OnionMessage) {
// First provide an OfferPathsRequest from the recipient to the server.
recipient.node.timer_tick_occurred();
let offer_paths_req = loop {
let msg = recipient
.onion_messenger
.next_onion_message_for_peer(server.node.get_our_node_id())
.unwrap();
// Ignore any messages that are updating the static invoice stored with the server here
if matches!(
server.onion_messenger.peel_onion_message(&msg).unwrap(),
PeeledOnion::AsyncPayments(AsyncPaymentsMessage::OfferPathsRequest(_), _, _)
) {
break msg;
}
};
server.onion_messenger.handle_onion_message(recipient.node.get_our_node_id(), &offer_paths_req);
// Check that the right number of requests were queued and that they were only queued for the
// server node.
let mut pending_oms = recipient.onion_messenger.release_pending_msgs();
let mut offer_paths_req_msgs = pending_oms.remove(&server.node.get_our_node_id()).unwrap();
assert!(offer_paths_req_msgs.len() <= TEST_OFFERS_MESSAGE_REQUEST_LIMIT);
for (_, msgs) in pending_oms {
assert!(msgs.is_empty());
}
// The server responds with OfferPaths.
let offer_paths = server
.onion_messenger
.next_onion_message_for_peer(recipient.node.get_our_node_id())
.unwrap();
recipient.onion_messenger.handle_onion_message(server.node.get_our_node_id(), &offer_paths);
// Only one OfferPaths response should be queued.
let mut pending_oms = server.onion_messenger.release_pending_msgs();
for (_, msgs) in pending_oms {
assert!(msgs.is_empty());
}
// After receiving the offer paths, the recipient constructs the static invoice and sends
// ServeStaticInvoice to the server.
let serve_static_invoice_om = recipient
.onion_messenger
.next_onion_message_for_peer(server.node.get_our_node_id())
.unwrap();
(offer_paths_req, serve_static_invoice_om)
}
// Go through the flow of interactively building a `StaticInvoice` and storing it with the static
// invoice server, returning the invoice and messages that were exchanged along the way at the end.
fn pass_static_invoice_server_messages(
server: &Node, recipient: &Node, recipient_id: Vec<u8>,
) -> StaticInvoiceServerFlowResult {
// Force the server and recipient to send OMs directly to each other for testing simplicity.
server.message_router.peers_override.lock().unwrap().push(recipient.node.get_our_node_id());
recipient.message_router.peers_override.lock().unwrap().push(server.node.get_our_node_id());
let (offer_paths_req, serve_static_invoice_om) =
invoice_flow_up_to_send_serve_static_invoice(server, recipient);
server
.onion_messenger
.handle_onion_message(recipient.node.get_our_node_id(), &serve_static_invoice_om);
// Upon handling the ServeStaticInvoice message, the server's node surfaces an event indicating
// that the static invoice should be persisted.
let mut events = server.node.get_and_clear_pending_events();
assert_eq!(events.len(), 1);
let (invoice, invoice_slot, ack_path, invoice_request_path) = match events.pop().unwrap() {
Event::PersistStaticInvoice {
invoice,
invoice_persisted_path,
recipient_id: ev_id,
invoice_slot,
invoice_request_path,
} => {
assert_eq!(recipient_id, ev_id);
(invoice, invoice_slot, invoice_persisted_path, invoice_request_path)
},
_ => panic!(),
};
// Once the static invoice is persisted, the server needs to call `static_invoice_persisted` with
// the reply path to the ServeStaticInvoice message, to tell the recipient that their offer is
// ready to be used for async payments.
server.node.static_invoice_persisted(ack_path);
let invoice_persisted_om = server
.onion_messenger
.next_onion_message_for_peer(recipient.node.get_our_node_id())
.unwrap();
recipient
.onion_messenger
.handle_onion_message(server.node.get_our_node_id(), &invoice_persisted_om);
// Remove the peer restriction added above.
server.message_router.peers_override.lock().unwrap().clear();
recipient.message_router.peers_override.lock().unwrap().clear();
StaticInvoiceServerFlowResult {
offer_paths_request: offer_paths_req,
static_invoice_persisted_message: invoice_persisted_om,
invoice_request_path,
invoice,
invoice_slot,
}
}
// Goes through the async receive onion message flow, returning the final release_held_htlc OM.
//
// Assumes the held_htlc_available message will be sent:
// sender -> always_online_recipient_counterparty -> recipient.
//
// Returns: (held_htlc_available_om, release_held_htlc_om)
fn pass_async_payments_oms(
static_invoice: StaticInvoice, sender: &Node, always_online_recipient_counterparty: &Node,
recipient: &Node, recipient_id: Vec<u8>, invoice_request_path: BlindedMessagePath,
) -> (msgs::OnionMessage, msgs::OnionMessage) {
let sender_node_id = sender.node.get_our_node_id();
let always_online_node_id = always_online_recipient_counterparty.node.get_our_node_id();
let invreq_om =
sender.onion_messenger.next_onion_message_for_peer(always_online_node_id).unwrap();
always_online_recipient_counterparty
.onion_messenger
.handle_onion_message(sender_node_id, &invreq_om);
let mut events = always_online_recipient_counterparty.node.get_and_clear_pending_events();
assert_eq!(events.len(), 1);
let (reply_path, invoice_request) = match events.pop().unwrap() {
Event::StaticInvoiceRequested {
recipient_id: ev_id,
invoice_slot: _,
reply_path,
invoice_request,
} => {
assert_eq!(recipient_id, ev_id);
(reply_path, invoice_request)
},
_ => panic!(),
};
always_online_recipient_counterparty
.node
.respond_to_static_invoice_request(
static_invoice,
reply_path,
invoice_request,
invoice_request_path,
)
.unwrap();
let _invreq_om = always_online_recipient_counterparty
.onion_messenger
.next_onion_message_for_peer(recipient.node.get_our_node_id())
.unwrap();
let static_invoice_om = always_online_recipient_counterparty
.onion_messenger
.next_onion_message_for_peer(sender_node_id)
.unwrap();
sender.onion_messenger.handle_onion_message(always_online_node_id, &static_invoice_om);
// Check that the node will not lock in HTLCs yet.
sender.node.process_pending_htlc_forwards();
assert!(sender.node.get_and_clear_pending_msg_events().is_empty());
let held_htlc_available_om_0_1 =
sender.onion_messenger.next_onion_message_for_peer(always_online_node_id).unwrap();
always_online_recipient_counterparty
.onion_messenger
.handle_onion_message(sender_node_id, &held_htlc_available_om_0_1);
let held_htlc_available_om_1_2 = always_online_recipient_counterparty
.onion_messenger
.next_onion_message_for_peer(recipient.node.get_our_node_id())
.unwrap();
recipient
.onion_messenger
.handle_onion_message(always_online_node_id, &held_htlc_available_om_1_2);
let release_held_htlc =
recipient.onion_messenger.next_onion_message_for_peer(sender_node_id).unwrap();
(held_htlc_available_om_1_2, release_held_htlc)
}
fn create_static_invoice_builder<'a>(
recipient: &Node, offer: &'a Offer, offer_nonce: Nonce, relative_expiry: Option<Duration>,
) -> StaticInvoiceBuilder<'a> {
let amount_msat = offer.amount().and_then(|amount| match amount {
Amount::Bitcoin { amount_msats } => Some(amount_msats),
Amount::Currency { .. } => None,
});
let relative_expiry = relative_expiry.unwrap_or(STATIC_INVOICE_DEFAULT_RELATIVE_EXPIRY);
let relative_expiry_secs: u32 = relative_expiry.as_secs().try_into().unwrap_or(u32::MAX);
let created_at = recipient.node.duration_since_epoch();
let payment_secret = inbound_payment::create_for_spontaneous_payment(
&recipient.keys_manager.get_expanded_key(),
amount_msat,
relative_expiry_secs,
created_at.as_secs(),
None,
)
.unwrap();
recipient
.node
.flow
.create_static_invoice_builder(
&recipient.router,
offer,
offer_nonce,
payment_secret,
relative_expiry_secs,
recipient.node.list_usable_channels(),
recipient.node.test_get_peers_for_blinded_path(),
recipient.node.currency_conversion,
)
.unwrap()
}
fn create_static_invoice<T: secp256k1::Signing + secp256k1::Verification>(
always_online_counterparty: &Node, recipient: &Node, relative_expiry: Option<Duration>,
secp_ctx: &Secp256k1<T>,
) -> (Offer, StaticInvoice) {
let entropy_source = recipient.keys_manager;
let blinded_paths_to_always_online_node = always_online_counterparty
.message_router
.create_blinded_paths(
always_online_counterparty.node.get_our_node_id(),
always_online_counterparty.keys_manager.get_receive_auth_key(),
MessageContext::Offers(OffersContext::InvoiceRequest { nonce: Nonce([42; 16]) }),
Vec::new(),
&secp_ctx,
)
.unwrap();
let (offer_builder, offer_nonce) = recipient
.node
.flow
.create_async_receive_offer_builder(entropy_source, blinded_paths_to_always_online_node)
.unwrap();
let offer = offer_builder.build();
let static_invoice =
create_static_invoice_builder(recipient, &offer, offer_nonce, relative_expiry)
.build_and_sign(&secp_ctx)
.unwrap();
(offer, static_invoice)
}
fn extract_payment_hash(event: &MessageSendEvent) -> PaymentHash {
match event {
MessageSendEvent::UpdateHTLCs { ref updates, .. } => {
updates.update_add_htlcs[0].payment_hash
},
_ => panic!(),
}
}
fn extract_payment_preimage(event: &Event) -> PaymentPreimage {
match event {
Event::PaymentClaimable {
purpose: PaymentPurpose::Bolt12OfferPayment { payment_preimage, .. },
..
} => payment_preimage.unwrap(),
_ => panic!(),
}
}
fn expect_offer_paths_requests(recipient: &Node, next_hop_nodes: &[&Node]) {
// We want to check that the async recipient has enqueued at least one `OfferPathsRequest` and no
// other message types. Check this by iterating through all their outbound onion messages, peeling
// multiple times if the messages are forwarded through other nodes.
let offer_paths_reqs = extract_expected_om(
recipient,
next_hop_nodes,
|peeled_onion| {
matches!(
peeled_onion,
PeeledOnion::AsyncPayments(AsyncPaymentsMessage::OfferPathsRequest(_), _, _)
)
},
|_| false,
);
assert!(!offer_paths_reqs.is_empty());
}
fn extract_invoice_request_om<'a>(
payer: &'a Node, next_hop_nodes: &[&'a Node],
) -> (PublicKey, msgs::OnionMessage) {
extract_expected_om(
payer,
next_hop_nodes,
|peeled_onion| {
matches!(peeled_onion, &PeeledOnion::Offers(OffersMessage::InvoiceRequest(_), _, _))
},
|_| false,
)
.pop()
.unwrap()
}
fn extract_static_invoice_om<'a>(
invoice_server: &'a Node, next_hop_nodes: &[&'a Node],
) -> (PublicKey, msgs::OnionMessage, StaticInvoice) {
let mut static_invoice = None;
let mut expected_msg_type = |peeled_onion: &_| {
if let PeeledOnion::Offers(OffersMessage::StaticInvoice(inv), _, _) = peeled_onion {
static_invoice = Some(inv.clone());
true
} else {
false
}
};
let expected_msg_type_to_ignore = |peeled_onion: &_| {
matches!(peeled_onion, &PeeledOnion::Offers(OffersMessage::InvoiceRequest(_), _, _))
};
let (peer_id, om) = extract_expected_om(
invoice_server,
next_hop_nodes,
expected_msg_type,
expected_msg_type_to_ignore,
)
.pop()
.unwrap();
(peer_id, om, static_invoice.unwrap())
}
fn extract_held_htlc_available_oms<'a>(
payer: &'a Node, next_hop_nodes: &[&'a Node],
) -> Vec<(PublicKey, msgs::OnionMessage)> {
extract_expected_om(
payer,
next_hop_nodes,
|peeled_onion| {
matches!(
peeled_onion,
&PeeledOnion::AsyncPayments(AsyncPaymentsMessage::HeldHtlcAvailable(_), _, _)
)
},
|_| false,
)
}
fn extract_release_htlc_oms<'a>(
recipient: &'a Node, next_hop_nodes: &[&'a Node],
) -> Vec<(PublicKey, msgs::OnionMessage)> {
extract_expected_om(
recipient,
next_hop_nodes,
|peeled_onion| {
matches!(
peeled_onion,
&PeeledOnion::AsyncPayments(AsyncPaymentsMessage::ReleaseHeldHtlc(_), _, _)
)
},
|_| false,
)
}
fn extract_expected_om<F1, F2>(
msg_sender: &Node, next_hop_nodes: &[&Node], mut expected_msg_type: F1,
expected_msg_type_to_ignore: F2,
) -> Vec<(PublicKey, msgs::OnionMessage)>
where
F1: FnMut(&PeeledOnion<Infallible>) -> bool,
F2: Fn(&PeeledOnion<Infallible>) -> bool,
{
let per_msg_recipient_msgs = msg_sender.onion_messenger.release_pending_msgs();
let mut pk_to_msg = Vec::new();
for (pk, msgs) in per_msg_recipient_msgs {
for msg in msgs {
pk_to_msg.push((pk, msg));
}
}
let mut msgs = Vec::new();
while let Some((pk, msg)) = pk_to_msg.pop() {
let node = next_hop_nodes.iter().find(|node| node.node.get_our_node_id() == pk).unwrap();
let peeled_msg = node.onion_messenger.peel_onion_message(&msg).unwrap();
match peeled_msg {
PeeledOnion::Forward(next_hop, msg) => {
let next_pk = match next_hop {
NextMessageHop::NodeId(pk) => pk,
NextMessageHop::ShortChannelId(scid) => {
let mut next_pk = None;
for node in next_hop_nodes {
if node.node.get_our_node_id() == pk {
continue;
}
for channel in node.node.list_channels() {
if channel.short_channel_id.unwrap() == scid
|| channel.inbound_scid_alias.unwrap_or(0) == scid
{
next_pk = Some(node.node.get_our_node_id());
}
}
}
next_pk.unwrap()
},
};
pk_to_msg.push((next_pk, msg));
},
peeled_onion if expected_msg_type(&peeled_onion) => msgs.push((pk, msg)),
peeled_onion if expected_msg_type_to_ignore(&peeled_onion) => {},
peeled_onion => panic!("Unexpected message: {:?}", peeled_onion),
}
}
assert!(!msgs.is_empty());
msgs
}
fn advance_time_by(duration: Duration, node: &Node) {
let target_time = (node.node.duration_since_epoch() + duration).as_secs() as u32;
let block = create_dummy_block(node.best_block_hash(), target_time, Vec::new());
connect_block(node, &block);
}
fn often_offline_node_cfg() -> UserConfig {
let mut cfg = test_default_channel_config();
cfg.channel_handshake_config.announce_for_forwarding = false;
cfg.channel_handshake_limits.force_announced_channel_preference = true;
cfg.hold_outbound_htlcs_at_next_hop = true;
// Use the setting that matches the default at the time these tests were written
cfg.channel_handshake_config.unannounced_channel_max_inbound_htlc_value_in_flight_percentage =
10;
cfg
}
fn unify_blockheight_across_nodes(nodes: &[Node]) {
// Make sure all nodes are at the same block height
let node_max_height =
nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
for node in nodes.iter() {
connect_blocks(node, node_max_height - node.best_block_info().1);
}
}
// Interactively builds an async offer and initiates payment to it from an often-offline sender,
// up to but not including providing the static invoice to the sender.
//
// Assumes that the first node is the async sender and the last hop is the async recipient, with the
// middle node(s) being announced nodes acting as LSP and/or invoice server. At least 1 middle node
// must be present.
//
// Returns the `StaticInvoice` and the onion message containing it, as well as the direct peer
// sending the static invoice OM to the sender.
fn build_async_offer_and_init_payment(
amt_msat: u64, nodes: &[Node],
) -> (StaticInvoice, PublicKey, msgs::OnionMessage) {
let sender = &nodes[0];
let sender_lsp = &nodes[1];
let invoice_server = &nodes[nodes.len() - 2];
let recipient = nodes.last().unwrap();
let recipient_id = vec![42; 32];
let inv_server_paths =
invoice_server.node.blinded_paths_for_async_recipient(recipient_id.clone(), None).unwrap();
recipient.node.set_paths_to_static_invoice_server(inv_server_paths).unwrap();
expect_offer_paths_requests(recipient, &[sender, sender_lsp, invoice_server]);
let invoice_flow_res =
pass_static_invoice_server_messages(invoice_server, recipient, recipient_id.clone());
let invoice = invoice_flow_res.invoice;
let invreq_path = invoice_flow_res.invoice_request_path;
let offer = recipient.node.get_async_receive_offer().unwrap();
let payment_id = PaymentId([1; 32]);
sender.node.pay_for_offer(&offer, Some(amt_msat), payment_id, Default::default()).unwrap();
// Forward invreq to server, pass static invoice back
let (peer_id, invreq_om) = extract_invoice_request_om(sender, &[sender_lsp, invoice_server]);
invoice_server.onion_messenger.handle_onion_message(peer_id, &invreq_om);
let mut events = invoice_server.node.get_and_clear_pending_events();
assert_eq!(events.len(), 1);
let (reply_path, invreq) = match events.pop().unwrap() {
Event::StaticInvoiceRequested {
recipient_id: ev_id, reply_path, invoice_request, ..
} => {
assert_eq!(recipient_id, ev_id);
(reply_path, invoice_request)
},
_ => panic!(),
};
invoice_server
.node
.respond_to_static_invoice_request(invoice.clone(), reply_path, invreq, invreq_path)
.unwrap();
let (peer_node_id, static_invoice_om, _) =
extract_static_invoice_om(invoice_server, &[sender_lsp, sender, recipient]);
(invoice, peer_node_id, static_invoice_om)
}
fn lock_in_htlc_for_static_invoice(
static_invoice_om: &msgs::OnionMessage, om_peer: PublicKey, sender: &Node, sender_lsp: &Node,
) -> PaymentHash {
// The sender should lock in the held HTLC with their LSP right after receiving the static invoice.
sender.onion_messenger.handle_onion_message(om_peer, &static_invoice_om);
check_added_monitors(sender, 1);
let commitment_update = get_htlc_update_msgs(&sender, &sender_lsp.node.get_our_node_id());
let update_add = commitment_update.update_add_htlcs[0].clone();
let payment_hash = update_add.payment_hash;
assert!(update_add.hold_htlc.is_some());
sender_lsp.node.handle_update_add_htlc(sender.node.get_our_node_id(), &update_add);
let commitment = &commitment_update.commitment_signed;
do_commitment_signed_dance(sender_lsp, sender, commitment, false, true);
payment_hash
}
#[test]
fn invalid_keysend_payment_secret() {
let chanmon_cfgs = create_chanmon_cfgs(3);
let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0);
let chan_upd_1_2 =
create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 1_000_000, 0).0.contents;
let invalid_payment_secret = PaymentSecret([42; 32]);
let amt_msat = 5000;
let keysend_preimage = PaymentPreimage([42; 32]);
let route_params = get_blinded_route_parameters(
amt_msat,
invalid_payment_secret,
1,
1_0000_0000,
nodes.iter().skip(1).map(|n| n.node.get_our_node_id()).collect(),
&[&chan_upd_1_2],
&chanmon_cfgs[2].keys_manager,
);
let payment_hash = nodes[0]
.node
.send_spontaneous_payment(
Some(keysend_preimage),
RecipientOnionFields::spontaneous_empty(amt_msat),
PaymentId(keysend_preimage.0),
route_params,
Retry::Attempts(0),
)
.unwrap();
check_added_monitors(&nodes[0], 1);
let expected_route: &[&[&Node]] = &[&[&nodes[1], &nodes[2]]];
let mut events = nodes[0].node.get_and_clear_pending_msg_events();
assert_eq!(events.len(), 1);
let ev = remove_first_msg_event_to_node(&nodes[1].node.get_our_node_id(), &mut events);
let args =
PassAlongPathArgs::new(&nodes[0], &expected_route[0], amt_msat, payment_hash, ev.clone())
.with_payment_secret(invalid_payment_secret)
.with_payment_preimage(keysend_preimage)
.expect_failure(HTLCHandlingFailureType::Receive { payment_hash });
do_pass_along_path(args);
let updates_2_1 = get_htlc_update_msgs(&nodes[2], &nodes[1].node.get_our_node_id());
assert_eq!(updates_2_1.update_fail_malformed_htlcs.len(), 1);
let update_malformed = &updates_2_1.update_fail_malformed_htlcs[0];
assert_eq!(update_malformed.sha256_of_onion, [0; 32]);
assert_eq!(
update_malformed.failure_code,
LocalHTLCFailureReason::InvalidOnionBlinding.failure_code()
);
nodes[1]
.node
.handle_update_fail_malformed_htlc(nodes[2].node.get_our_node_id(), update_malformed);
do_commitment_signed_dance(&nodes[1], &nodes[2], &updates_2_1.commitment_signed, true, false);
let updates_1_0 = get_htlc_update_msgs(&nodes[1], &nodes[0].node.get_our_node_id());
assert_eq!(updates_1_0.update_fail_htlcs.len(), 1);
nodes[0].node.handle_update_fail_htlc(
nodes[1].node.get_our_node_id(),
&updates_1_0.update_fail_htlcs[0],
);
do_commitment_signed_dance(&nodes[0], &nodes[1], &updates_1_0.commitment_signed, false, false);
expect_payment_failed_conditions(
&nodes[0],
payment_hash,
false,
PaymentFailedConditions::new()
.expected_htlc_error_data(LocalHTLCFailureReason::InvalidOnionBlinding, &[0; 32]),
);
}
#[test]
fn static_invoice_unknown_required_features() {
// Test that we will fail to pay a static invoice with unsupported required features.
let secp_ctx = Secp256k1::new();
let chanmon_cfgs = create_chanmon_cfgs(3);
let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
let entropy_source = nodes[2].keys_manager;
create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0);
create_unannounced_chan_between_nodes_with_value(&nodes, 1, 2, 1_000_000, 0);
// Manually construct a static invoice so we can set unknown required features.
let blinded_paths_to_always_online_node = nodes[1]
.message_router
.create_blinded_paths(
nodes[1].node.get_our_node_id(),
nodes[1].keys_manager.get_receive_auth_key(),
MessageContext::Offers(OffersContext::InvoiceRequest { nonce: Nonce([42; 16]) }),
Vec::new(),
&secp_ctx,
)
.unwrap();
let (offer_builder, nonce) = nodes[2]
.node
.flow
.create_async_receive_offer_builder(entropy_source, blinded_paths_to_always_online_node)
.unwrap();
let offer = offer_builder.build();
let static_invoice_unknown_req_features =
create_static_invoice_builder(&nodes[2], &offer, nonce, None)
.features_unchecked(Bolt12InvoiceFeatures::unknown())
.build_and_sign(&secp_ctx)
.unwrap();
// Initiate payment to the offer corresponding to the manually-constructed invoice that has
// unknown required features.
let amt_msat = 5000;
let payment_id = PaymentId([1; 32]);
nodes[0].node.pay_for_offer(&offer, Some(amt_msat), payment_id, Default::default()).unwrap();
// Don't forward the invreq since the invoice was created outside of the normal flow, instead
// manually construct the response.
let invreq_om = nodes[0]
.onion_messenger
.next_onion_message_for_peer(nodes[1].node.get_our_node_id())
.unwrap();
let invreq_reply_path = offers_tests::extract_invoice_request(&nodes[1], &invreq_om).1;
nodes[1]
.onion_messenger
.send_onion_message(
ParsedOnionMessageContents::<Infallible>::Offers(OffersMessage::StaticInvoice(
static_invoice_unknown_req_features,
)),
MessageSendInstructions::WithoutReplyPath {
destination: Destination::BlindedPath(invreq_reply_path),
},
)
.unwrap();
// Check that paying the static invoice fails as expected with
// `PaymentFailureReason::UnknownRequiredFeatures`.
let static_invoice_om = nodes[1]
.onion_messenger
.next_onion_message_for_peer(nodes[0].node.get_our_node_id())
.unwrap();
nodes[0]
.onion_messenger
.handle_onion_message(nodes[1].node.get_our_node_id(), &static_invoice_om);
let events = nodes[0].node.get_and_clear_pending_events();
assert_eq!(events.len(), 1);
match events[0] {
Event::PaymentFailed { payment_hash, payment_id: ev_payment_id, reason } => {
assert_eq!(payment_hash, None);
assert_eq!(payment_id, ev_payment_id);
assert_eq!(reason, Some(PaymentFailureReason::UnknownRequiredFeatures));
},
_ => panic!(),
}
}
#[test]
fn ignore_unexpected_static_invoice() {
// Test that we'll ignore unexpected static invoices, invoices that don't match our invoice
// request, and duplicate invoices.
let chanmon_cfgs = create_chanmon_cfgs(3);
let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0);
create_unannounced_chan_between_nodes_with_value(&nodes, 1, 2, 1_000_000, 0);
let recipient_id = vec![42; 32];
let inv_server_paths =
nodes[1].node.blinded_paths_for_async_recipient(recipient_id.clone(), None).unwrap();
nodes[2].node.set_paths_to_static_invoice_server(inv_server_paths).unwrap();
expect_offer_paths_requests(&nodes[2], &[&nodes[0], &nodes[1]]);
// Initiate payment to the sender's intended offer.
let valid_static_invoice =
pass_static_invoice_server_messages(&nodes[1], &nodes[2], recipient_id.clone()).invoice;
let offer = nodes[2].node.get_async_receive_offer().unwrap();
// Create a static invoice to be sent over the reply path containing the original payment_id, but
// the static invoice corresponds to a different offer than was originally paid.
let invoice_flow_res =
pass_static_invoice_server_messages(&nodes[1], &nodes[2], recipient_id.clone());
let unexpected_static_invoice = invoice_flow_res.invoice;
let amt_msat = 5000;
let payment_id = PaymentId([1; 32]);
nodes[0].node.pay_for_offer(&offer, Some(amt_msat), payment_id, Default::default()).unwrap();
let invreq_om = nodes[0]
.onion_messenger
.next_onion_message_for_peer(nodes[1].node.get_our_node_id())
.unwrap();
nodes[1].onion_messenger.handle_onion_message(nodes[0].node.get_our_node_id(), &invreq_om);
let mut events = nodes[1].node.get_and_clear_pending_events();
assert_eq!(events.len(), 1);
let (reply_path, invoice_request) = match events.pop().unwrap() {
Event::StaticInvoiceRequested {
recipient_id: ev_id,
invoice_slot: _,
reply_path,
invoice_request,
} => {
assert_eq!(recipient_id, ev_id);
(reply_path, invoice_request)
},
_ => panic!(),
};
// Check that the sender will ignore the unexpected static invoice.
nodes[1]
.node
.respond_to_static_invoice_request(
unexpected_static_invoice,
reply_path.clone(),
invoice_request.clone(),
invoice_flow_res.invoice_request_path.clone(),
)
.unwrap();
let unexpected_static_invoice_om = nodes[1]
.onion_messenger
.next_onion_message_for_peer(nodes[0].node.get_our_node_id())
.unwrap();
nodes[0]
.onion_messenger
.handle_onion_message(nodes[1].node.get_our_node_id(), &unexpected_static_invoice_om);
let async_pmts_msgs = AsyncPaymentsMessageHandler::release_pending_messages(nodes[0].node);
assert!(async_pmts_msgs.is_empty());
assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
// A valid static invoice corresponding to the correct offer will succeed and cause us to send a
// held_htlc_available onion message.
nodes[1]
.node
.respond_to_static_invoice_request(
valid_static_invoice.clone(),
reply_path.clone(),
invoice_request.clone(),
invoice_flow_res.invoice_request_path.clone(),
)
.unwrap();
let static_invoice_om = nodes[1]
.onion_messenger
.next_onion_message_for_peer(nodes[0].node.get_our_node_id())
.unwrap();
nodes[0]
.onion_messenger
.handle_onion_message(nodes[1].node.get_our_node_id(), &static_invoice_om);
let async_pmts_msgs = AsyncPaymentsMessageHandler::release_pending_messages(nodes[0].node);
assert!(!async_pmts_msgs.is_empty());
assert!(async_pmts_msgs
.into_iter()
.all(|(msg, _)| matches!(msg, AsyncPaymentsMessage::HeldHtlcAvailable(_))));
// Receiving a duplicate invoice will have no effect.
nodes[1]
.node
.respond_to_static_invoice_request(
valid_static_invoice,
reply_path,
invoice_request,
invoice_flow_res.invoice_request_path,
)
.unwrap();
let dup_static_invoice_om = nodes[1]
.onion_messenger
.next_onion_message_for_peer(nodes[0].node.get_our_node_id())
.unwrap();
nodes[0]
.onion_messenger
.handle_onion_message(nodes[1].node.get_our_node_id(), &dup_static_invoice_om);
let async_pmts_msgs = AsyncPaymentsMessageHandler::release_pending_messages(nodes[0].node);
assert!(async_pmts_msgs.is_empty());
}
#[test]
fn ignore_duplicate_invoice() {
// When a sender tries to pay an async recipient it could potentially end up receiving two
// invoices: one static invoice that it received from always-online node and a fresh invoice
// received from async recipient in case it was online to reply to request. Test that it
// will only pay one of the two invoices.
let chanmon_cfgs = create_chanmon_cfgs(3);
let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
let mut allow_priv_chan_fwds_cfg = test_default_channel_config();
allow_priv_chan_fwds_cfg.accept_forwards_to_priv_channels = true;
let node_chanmgrs =
create_node_chanmgrs(3, &node_cfgs, &[None, Some(allow_priv_chan_fwds_cfg), None]);
let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0);
create_unannounced_chan_between_nodes_with_value(&nodes, 1, 2, 1_000_000, 0);
let sender = &nodes[0];
let always_online_node = &nodes[1];
let async_recipient = &nodes[2];
let recipient_id = vec![42; 32];
let inv_server_paths = always_online_node
.node
.blinded_paths_for_async_recipient(recipient_id.clone(), None)
.unwrap();
async_recipient.node.set_paths_to_static_invoice_server(inv_server_paths).unwrap();
expect_offer_paths_requests(async_recipient, &[sender, always_online_node]);
let invoice_flow_res = pass_static_invoice_server_messages(
always_online_node,
async_recipient,
recipient_id.clone(),
);
let static_invoice = invoice_flow_res.invoice;
assert!(static_invoice.invoice_features().supports_basic_mpp());
let offer = async_recipient.node.get_async_receive_offer().unwrap();
let amt_msat = 5000;
let payment_id = PaymentId([1; 32]);
sender.node.pay_for_offer(&offer, Some(amt_msat), payment_id, Default::default()).unwrap();
let sender_node_id = sender.node.get_our_node_id();
let always_online_node_id = always_online_node.node.get_our_node_id();
let async_recipient_id = async_recipient.node.get_our_node_id();
let invreq_om =
sender.onion_messenger.next_onion_message_for_peer(always_online_node_id).unwrap();
always_online_node.onion_messenger.handle_onion_message(sender_node_id, &invreq_om);
let mut events = always_online_node.node.get_and_clear_pending_events();
assert_eq!(events.len(), 1);
let (reply_path, invoice_request) = match events.pop().unwrap() {
Event::StaticInvoiceRequested {
recipient_id: ev_id,
invoice_slot: _,
reply_path,
invoice_request,
} => {
assert_eq!(recipient_id, ev_id);
(reply_path, invoice_request)
},
_ => panic!(),
};
always_online_node
.node
.respond_to_static_invoice_request(
static_invoice.clone(),
reply_path,
invoice_request,
invoice_flow_res.invoice_request_path.clone(),
)
.unwrap();
// After calling `respond_to_static_invoice_request` the next two messages should be the
// invoice request to the intended for the async recipient and the static invoice to the
// payer.
let invreq_om =
always_online_node.onion_messenger.next_onion_message_for_peer(async_recipient_id).unwrap();
let peeled_msg = async_recipient.onion_messenger.peel_onion_message(&invreq_om).unwrap();
assert!(matches!(peeled_msg, PeeledOnion::Offers(OffersMessage::InvoiceRequest(_), _, _)));
let static_invoice_om =
always_online_node.onion_messenger.next_onion_message_for_peer(sender_node_id).unwrap();
let peeled_msg = sender.onion_messenger.peel_onion_message(&static_invoice_om).unwrap();
assert!(matches!(peeled_msg, PeeledOnion::Offers(OffersMessage::StaticInvoice(_), _, _)));
// Handling the `invoice_request` from the async recipient we should get back an invoice.
async_recipient.onion_messenger.handle_onion_message(always_online_node_id, &invreq_om);
let invoice_om =
async_recipient.onion_messenger.next_onion_message_for_peer(sender_node_id).unwrap();
// First pay the static invoice.
sender.onion_messenger.handle_onion_message(always_online_node_id, &static_invoice_om);
let held_htlc_available_om_0_1 =
sender.onion_messenger.next_onion_message_for_peer(always_online_node_id).unwrap();
always_online_node
.onion_messenger
.handle_onion_message(sender_node_id, &held_htlc_available_om_0_1);
let held_htlc_available_om_1_2 =
always_online_node.onion_messenger.next_onion_message_for_peer(async_recipient_id).unwrap();
async_recipient
.onion_messenger
.handle_onion_message(always_online_node_id, &held_htlc_available_om_1_2);
let release_held_htlc_om =
async_recipient.onion_messenger.next_onion_message_for_peer(sender_node_id).unwrap();
sender.onion_messenger.handle_onion_message(async_recipient_id, &release_held_htlc_om);
let mut events = sender.node.get_and_clear_pending_msg_events();
assert_eq!(events.len(), 1);
let ev = remove_first_msg_event_to_node(&always_online_node_id, &mut events);
let payment_hash = extract_payment_hash(&ev);
check_added_monitors(&sender, 1);
let route: &[&[&Node]] = &[&[always_online_node, async_recipient]];
let args = PassAlongPathArgs::new(sender, route[0], amt_msat, payment_hash, ev)
.with_dummy_tlvs(&[DummyTlvs::default(); DEFAULT_PAYMENT_DUMMY_HOPS]);
let claimable_ev = do_pass_along_path(args).unwrap();
let keysend_preimage = extract_payment_preimage(&claimable_ev);
let (res, _) =
claim_payment_along_route(ClaimAlongRouteArgs::new(sender, route, keysend_preimage));
assert_eq!(res, Some(PaidBolt12Invoice::StaticInvoice(static_invoice.clone())));
// After paying the static invoice, check that regular invoice received from async recipient is ignored.
match sender.onion_messenger.peel_onion_message(&invoice_om) {
Ok(PeeledOnion::Offers(OffersMessage::Invoice(invoice), context, _)) => {
assert!(matches!(