forked from lightningdevkit/rust-lightning
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathasync_payments_tests.rs
More file actions
2208 lines (1980 loc) · 86.5 KB
/
async_payments_tests.rs
File metadata and controls
2208 lines (1980 loc) · 86.5 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::{MessageContext, OffersContext};
use crate::blinded_path::payment::PaymentContext;
use crate::blinded_path::payment::{AsyncBolt12OfferContext, BlindedPaymentTlvs};
use crate::chain::channelmonitor::{HTLC_FAIL_BACK_BUFFER, LATENCY_GRACE_PERIOD_BLOCKS};
use crate::events::{
Event, HTLCHandlingFailureType, PaidBolt12Invoice, PaymentFailureReason, PaymentPurpose,
};
use crate::ln::blinded_payment_tests::{fail_blinded_htlc_backwards, get_blinded_route_parameters};
use crate::ln::channelmanager::{PaymentId, RecipientOnionFields};
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::{
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, RouteParametersConfig};
use crate::sign::NodeSigner;
use crate::sync::Mutex;
use crate::types::features::Bolt12InvoiceFeatures;
use crate::types::payment::{PaymentHash, PaymentPreimage, PaymentSecret};
use crate::util::ser::Writeable;
use bitcoin::constants::ChainHash;
use bitcoin::network::Network;
use bitcoin::secp256k1;
use bitcoin::secp256k1::Secp256k1;
use core::convert::Infallible;
use core::time::Duration;
struct StaticInvoiceServerFlowResult {
invoice: StaticInvoice,
invoice_slot: u16,
// 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) = match events.pop().unwrap() {
Event::PersistStaticInvoice {
invoice,
invoice_persisted_path,
recipient_id: ev_id,
invoice_slot,
} => {
assert_eq!(recipient_id, ev_id);
(invoice, invoice_slot, invoice_persisted_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,
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>,
) -> (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 = match events.pop().unwrap() {
Event::StaticInvoiceRequested { recipient_id: ev_id, invoice_slot: _, reply_path } => {
assert_eq!(recipient_id, ev_id);
reply_path
},
_ => panic!(),
};
always_online_recipient_counterparty
.node
.send_static_invoice(static_invoice, reply_path)
.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);
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 entropy = recipient.keys_manager;
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,
entropy,
offer,
offer_nonce,
payment_secret,
relative_expiry_secs,
recipient.node.list_usable_channels(),
recipient.node.test_get_peers_for_blinded_path(),
)
.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().unwrap();
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 per_msg_recipient_msgs = recipient.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 num_offer_paths_reqs: u8 = 0;
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::AsyncPayments(AsyncPaymentsMessage::OfferPathsRequest(_), _, _) => {
num_offer_paths_reqs += 1;
},
PeeledOnion::Forward(next_hop, msg) => {
let next_pk = match next_hop {
crate::blinded_path::message::NextMessageHop::NodeId(pk) => pk,
_ => panic!(),
};
pk_to_msg.push((next_pk, msg));
},
_ => panic!("Unexpected message"),
}
}
assert!(num_offer_paths_reqs > 0);
}
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);
}
#[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(),
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().unwrap();
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]);
let params = RouteParametersConfig::default();
nodes[0]
.node
.pay_for_offer(&offer, None, Some(amt_msat), None, payment_id, Retry::Attempts(0), params)
.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 unexpected_static_invoice =
pass_static_invoice_server_messages(&nodes[1], &nodes[2], recipient_id.clone()).invoice;
let amt_msat = 5000;
let payment_id = PaymentId([1; 32]);
let params = RouteParametersConfig::default();
nodes[0]
.node
.pay_for_offer(&offer, None, Some(amt_msat), None, payment_id, Retry::Attempts(0), params)
.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 = match events.pop().unwrap() {
Event::StaticInvoiceRequested { recipient_id: ev_id, invoice_slot: _, reply_path } => {
assert_eq!(recipient_id, ev_id);
reply_path
},
_ => panic!(),
};
// Check that the sender will ignore the unexpected static invoice.
nodes[1].node.send_static_invoice(unexpected_static_invoice, reply_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.send_static_invoice(valid_static_invoice.clone(), reply_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.send_static_invoice(valid_static_invoice, reply_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 async_receive_flow_success() {
// Test that an always-online sender can successfully pay an async receiver.
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 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]]);
let invoice_flow_res =
pass_static_invoice_server_messages(&nodes[1], &nodes[2], recipient_id.clone());
let static_invoice = invoice_flow_res.invoice;
assert!(static_invoice.invoice_features().supports_basic_mpp());
let offer = nodes[2].node.get_async_receive_offer().unwrap();
let amt_msat = 5000;
let payment_id = PaymentId([1; 32]);
let params = RouteParametersConfig::default();
nodes[0]
.node
.pay_for_offer(&offer, None, Some(amt_msat), None, payment_id, Retry::Attempts(0), params)
.unwrap();
let release_held_htlc_om = pass_async_payments_oms(
static_invoice.clone(),
&nodes[0],
&nodes[1],
&nodes[2],
recipient_id,
)
.1;
nodes[0]
.onion_messenger
.handle_onion_message(nodes[2].node.get_our_node_id(), &release_held_htlc_om);
// Check that we've queued the HTLCs of the async keysend payment.
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 payment_hash = extract_payment_hash(&ev);
check_added_monitors!(nodes[0], 1);
// Receiving a duplicate release_htlc message doesn't result in duplicate payment.
nodes[0]
.onion_messenger
.handle_onion_message(nodes[2].node.get_our_node_id(), &release_held_htlc_om);
assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
let route: &[&[&Node]] = &[&[&nodes[1], &nodes[2]]];
let args = PassAlongPathArgs::new(&nodes[0], route[0], amt_msat, payment_hash, ev);
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(&nodes[0], route, keysend_preimage));
assert_eq!(res, Some(PaidBolt12Invoice::StaticInvoice(static_invoice)));
}
#[cfg_attr(feature = "std", ignore)]
#[test]
fn expired_static_invoice_fail() {
// Test that if we receive an expired static invoice we'll fail the payment.
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]]);
let 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();
let amt_msat = 5000;
let payment_id = PaymentId([1; 32]);
let params = RouteParametersConfig::default();
nodes[0]
.node
.pay_for_offer(&offer, None, Some(amt_msat), None, payment_id, Retry::Attempts(0), params)
.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 = match events.pop().unwrap() {
Event::StaticInvoiceRequested { reply_path, .. } => reply_path,
_ => panic!(),
};
nodes[1].node.send_static_invoice(static_invoice.clone(), reply_path).unwrap();
let static_invoice_om = nodes[1]
.onion_messenger
.next_onion_message_for_peer(nodes[0].node.get_our_node_id())
.unwrap();
// Wait until the static invoice expires before providing it to the sender.
let block = create_dummy_block(
nodes[0].best_block_hash(),
(static_invoice.created_at() + static_invoice.relative_expiry()).as_secs() as u32 + 1u32,
Vec::new(),
);
connect_block(&nodes[0], &block);
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_id: ev_payment_id, reason, .. } => {
assert_eq!(reason.unwrap(), PaymentFailureReason::PaymentExpired);
assert_eq!(ev_payment_id, payment_id);
},
_ => panic!(),
}
// TODO: the sender doesn't reply with InvoiceError right now because the always-online node
// doesn't currently provide them with a reply path to do so.
}
#[cfg_attr(feature = "std", ignore)]
#[test]
fn timeout_unreleased_payment() {
// If a server holds a pending HTLC for too long, payment is considered expired.
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 sender = &nodes[0];
let server = &nodes[1];
let recipient = &nodes[2];
let recipient_id = vec![42; 32];
let inv_server_paths =
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(&nodes[2], &[&nodes[0], &nodes[1]]);
let static_invoice =
pass_static_invoice_server_messages(server, recipient, recipient_id.clone()).invoice;
let offer = recipient.node.get_async_receive_offer().unwrap();
let amt_msat = 5000;
let payment_id = PaymentId([1; 32]);
let params = RouteParametersConfig::default();
sender
.node
.pay_for_offer(&offer, None, Some(amt_msat), None, payment_id, Retry::Attempts(0), params)
.unwrap();
let invreq_om =
sender.onion_messenger.next_onion_message_for_peer(server.node.get_our_node_id()).unwrap();
server.onion_messenger.handle_onion_message(sender.node.get_our_node_id(), &invreq_om);
let mut events = server.node.get_and_clear_pending_events();
assert_eq!(events.len(), 1);
let reply_path = match events.pop().unwrap() {
Event::StaticInvoiceRequested { reply_path, .. } => reply_path,
_ => panic!(),
};
server.node.send_static_invoice(static_invoice.clone(), reply_path).unwrap();
let static_invoice_om =
server.onion_messenger.next_onion_message_for_peer(sender.node.get_our_node_id()).unwrap();
// We handle the static invoice to held the pending HTLC
sender.onion_messenger.handle_onion_message(server.node.get_our_node_id(), &static_invoice_om);
// We advance enough time to expire the payment.
// We add 2 hours as is the margin added to remove stale payments in non-std implementation.
let timeout_time_expiry = TEST_ASYNC_PAYMENT_TIMEOUT_RELATIVE_EXPIRY
+ Duration::from_secs(7200)
+ Duration::from_secs(1);
advance_time_by(timeout_time_expiry, sender);
sender.node.timer_tick_occurred();
let events = sender.node.get_and_clear_pending_events();
assert_eq!(events.len(), 1);
match events[0] {
Event::PaymentFailed { payment_id: ev_payment_id, reason, .. } => {
assert_eq!(reason.unwrap(), PaymentFailureReason::PaymentExpired);
assert_eq!(ev_payment_id, payment_id);
},
_ => panic!(),
}
}
#[test]
fn async_receive_mpp() {
let chanmon_cfgs = create_chanmon_cfgs(4);
let node_cfgs = create_node_cfgs(4, &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(
4,
&node_cfgs,
&[None, Some(allow_priv_chan_fwds_cfg.clone()), Some(allow_priv_chan_fwds_cfg), None],
);
let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
// Create this network topology:
// n1
// / \
// n0 n3
// \ /
// n2
create_announced_chan_between_nodes(&nodes, 0, 1);
create_announced_chan_between_nodes(&nodes, 0, 2);
create_unannounced_chan_between_nodes_with_value(&nodes, 1, 3, 1_000_000, 0);
create_unannounced_chan_between_nodes_with_value(&nodes, 2, 3, 1_000_000, 0);
// Ensure all nodes start at the same height.
connect_blocks(&nodes[0], 4 * CHAN_CONFIRM_DEPTH + 1 - nodes[0].best_block_info().1);
connect_blocks(&nodes[1], 4 * CHAN_CONFIRM_DEPTH + 1 - nodes[1].best_block_info().1);
connect_blocks(&nodes[2], 4 * CHAN_CONFIRM_DEPTH + 1 - nodes[2].best_block_info().1);
connect_blocks(&nodes[3], 4 * CHAN_CONFIRM_DEPTH + 1 - nodes[3].best_block_info().1);
let recipient_id = vec![42; 32];
let inv_server_paths =
nodes[1].node.blinded_paths_for_async_recipient(recipient_id.clone(), None).unwrap();
nodes[3].node.set_paths_to_static_invoice_server(inv_server_paths).unwrap();
expect_offer_paths_requests(&nodes[3], &[&nodes[0], &nodes[1], &nodes[2]]);
let static_invoice =
pass_static_invoice_server_messages(&nodes[1], &nodes[3], recipient_id.clone()).invoice;
let offer = nodes[3].node.get_async_receive_offer().unwrap();
let amt_msat = 15_000_000;
let payment_id = PaymentId([1; 32]);
let params = RouteParametersConfig::default();
nodes[0]
.node
.pay_for_offer(&offer, None, Some(amt_msat), None, payment_id, Retry::Attempts(1), params)
.unwrap();
let release_held_htlc_om_3_0 =
pass_async_payments_oms(static_invoice, &nodes[0], &nodes[1], &nodes[3], recipient_id).1;
nodes[0]
.onion_messenger
.handle_onion_message(nodes[3].node.get_our_node_id(), &release_held_htlc_om_3_0);
check_added_monitors(&nodes[0], 2);
let expected_route: &[&[&Node]] = &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]];
let mut events = nodes[0].node.get_and_clear_pending_msg_events();
assert_eq!(events.len(), 2);
let ev = remove_first_msg_event_to_node(&nodes[1].node.get_our_node_id(), &mut events);
let payment_hash = match ev {
MessageSendEvent::UpdateHTLCs { ref updates, .. } => {
updates.update_add_htlcs[0].payment_hash
},
_ => panic!(),
};
let args = PassAlongPathArgs::new(&nodes[0], expected_route[0], amt_msat, payment_hash, ev)
.without_claimable_event();
do_pass_along_path(args);
let ev = remove_first_msg_event_to_node(&nodes[2].node.get_our_node_id(), &mut events);
let args = PassAlongPathArgs::new(&nodes[0], expected_route[1], amt_msat, payment_hash, ev);
let claimable_ev = do_pass_along_path(args).unwrap();
let keysend_preimage = match claimable_ev {
Event::PaymentClaimable {
purpose: PaymentPurpose::Bolt12OfferPayment { payment_preimage, .. },
..
} => payment_preimage.unwrap(),
_ => panic!(),
};
claim_payment_along_route(ClaimAlongRouteArgs::new(
&nodes[0],
expected_route,
keysend_preimage,
));
}
#[test]
fn amount_doesnt_match_invreq() {
// Ensure that we'll fail an async payment backwards if the amount in the HTLC is lower than the
// amount from the original invoice request.
let secp_ctx = Secp256k1::new();
let chanmon_cfgs = create_chanmon_cfgs(4);
let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
let mut allow_priv_chan_fwds_cfg = test_default_channel_config();
allow_priv_chan_fwds_cfg.accept_forwards_to_priv_channels = true;
// Make one blinded path's fees slightly higher so they are tried in a deterministic order.
let mut higher_fee_chan_cfg = allow_priv_chan_fwds_cfg.clone();
higher_fee_chan_cfg.channel_config.forwarding_fee_base_msat += 5000;
let node_chanmgrs = create_node_chanmgrs(
4,
&node_cfgs,
&[None, Some(allow_priv_chan_fwds_cfg), Some(higher_fee_chan_cfg), None],
);
let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
// Create this network topology so nodes[0] has a blinded route hint to retry over.
// n1
// / \
// n0 n3
// \ /
// n2
create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0);
create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 1_000_000, 0);
create_unannounced_chan_between_nodes_with_value(&nodes, 1, 3, 1_000_000, 0);
create_unannounced_chan_between_nodes_with_value(&nodes, 2, 3, 1_000_000, 0);
// Ensure all nodes start at the same height.
connect_blocks(&nodes[0], 4 * CHAN_CONFIRM_DEPTH + 1 - nodes[0].best_block_info().1);
connect_blocks(&nodes[1], 4 * CHAN_CONFIRM_DEPTH + 1 - nodes[1].best_block_info().1);
connect_blocks(&nodes[2], 4 * CHAN_CONFIRM_DEPTH + 1 - nodes[2].best_block_info().1);
connect_blocks(&nodes[3], 4 * CHAN_CONFIRM_DEPTH + 1 - nodes[3].best_block_info().1);
let recipient_id = vec![42; 32];
let inv_server_paths =
nodes[1].node.blinded_paths_for_async_recipient(recipient_id.clone(), None).unwrap();
nodes[3].node.set_paths_to_static_invoice_server(inv_server_paths).unwrap();
expect_offer_paths_requests(&nodes[3], &[&nodes[0], &nodes[1], &nodes[2]]);
let static_invoice =
pass_static_invoice_server_messages(&nodes[1], &nodes[3], recipient_id.clone()).invoice;
let offer = nodes[3].node.get_async_receive_offer().unwrap();
let amt_msat = 5000;
let payment_id = PaymentId([1; 32]);
let params = RouteParametersConfig::default();
nodes[0]
.node
.pay_for_offer(&offer, None, Some(amt_msat), None, payment_id, Retry::Attempts(1), params)
.unwrap();
let release_held_htlc_om_3_0 =
pass_async_payments_oms(static_invoice, &nodes[0], &nodes[1], &nodes[3], recipient_id).1;
// Replace the invoice request contained within outbound_payments before sending so the invreq
// amount doesn't match the onion amount when the HTLC gets to the recipient.
let mut valid_invreq = None;
nodes[0].node.test_modify_pending_payment(&payment_id, |pmt| {
if let PendingOutboundPayment::StaticInvoiceReceived { invoice_request, .. } = pmt {
valid_invreq = Some(invoice_request.clone());
*invoice_request = offer
.request_invoice(
&nodes[0].keys_manager.get_expanded_key(),
Nonce::from_entropy_source(nodes[0].keys_manager),
&secp_ctx,
payment_id,
)
.unwrap()
.amount_msats(amt_msat + 1)
.unwrap()
.chain_hash(ChainHash::using_genesis_block(Network::Testnet))
.unwrap()
.build_and_sign()
.unwrap();
} else {
panic!()
}
});