-
Notifications
You must be signed in to change notification settings - Fork 386
/
Copy pathchanmon_consistency.rs
1886 lines (1767 loc) · 67.5 KB
/
chanmon_consistency.rs
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.
//! Test that monitor update failures don't get our channel state out of sync.
//! One of the biggest concern with the monitor update failure handling code is that messages
//! resent after monitor updating is restored are delivered out-of-order, resulting in
//! commitment_signed messages having "invalid signatures".
//! To test this we stand up a network of three nodes and read bytes from the fuzz input to denote
//! actions such as sending payments, handling events, or changing monitor update return values on
//! a per-node basis. This should allow it to find any cases where the ordering of actions results
//! in us getting out of sync with ourselves, and, assuming at least one of our recieve- or
//! send-side handling is correct, other peers. We consider it a failure if any action results in a
//! channel being force-closed.
use bitcoin::amount::Amount;
use bitcoin::constants::genesis_block;
use bitcoin::locktime::absolute::LockTime;
use bitcoin::network::Network;
use bitcoin::opcodes;
use bitcoin::script::{Builder, ScriptBuf};
use bitcoin::transaction::Version;
use bitcoin::transaction::{Transaction, TxOut};
use bitcoin::hash_types::BlockHash;
use bitcoin::hashes::sha256::Hash as Sha256;
use bitcoin::hashes::sha256d::Hash as Sha256dHash;
use bitcoin::hashes::Hash as TraitImport;
use bitcoin::WPubkeyHash;
use lightning::blinded_path::message::{BlindedMessagePath, MessageContext};
use lightning::blinded_path::payment::{BlindedPaymentPath, ReceiveTlvs};
use lightning::chain;
use lightning::chain::chaininterface::{BroadcasterInterface, ConfirmationTarget, FeeEstimator};
use lightning::chain::channelmonitor::{ChannelMonitor, MonitorEvent};
use lightning::chain::transaction::OutPoint;
use lightning::chain::{
chainmonitor, channelmonitor, BestBlock, ChannelMonitorUpdateStatus, Confirm, Watch,
};
use lightning::events;
use lightning::ln::channel::FEE_SPIKE_BUFFER_FEE_INCREASE_MULTIPLE;
use lightning::ln::channel_state::ChannelDetails;
use lightning::ln::channelmanager::{
ChainParameters, ChannelManager, ChannelManagerReadArgs, PaymentId, RecentPaymentDetails,
RecipientOnionFields,
};
use lightning::ln::functional_test_utils::*;
use lightning::ln::inbound_payment::ExpandedKey;
use lightning::ln::msgs::{
BaseMessageHandler, ChannelMessageHandler, CommitmentUpdate, Init, MessageSendEvent,
UpdateAddHTLC,
};
use lightning::ln::script::ShutdownScript;
use lightning::ln::types::ChannelId;
use lightning::offers::invoice::UnsignedBolt12Invoice;
use lightning::onion_message::messenger::{Destination, MessageRouter, OnionMessagePath};
use lightning::routing::router::{
InFlightHtlcs, Path, PaymentParameters, Route, RouteHop, RouteParameters, Router,
};
use lightning::sign::{EntropySource, InMemorySigner, NodeSigner, Recipient, SignerProvider};
use lightning::types::payment::{PaymentHash, PaymentPreimage, PaymentSecret};
use lightning::util::config::UserConfig;
use lightning::util::hash_tables::*;
use lightning::util::logger::Logger;
use lightning::util::ser::{Readable, ReadableArgs, Writeable, Writer};
use lightning::util::test_channel_signer::{EnforcementState, TestChannelSigner};
use lightning_invoice::RawBolt11Invoice;
use crate::utils::test_logger::{self, Output};
use crate::utils::test_persister::TestPersister;
use bitcoin::secp256k1::ecdh::SharedSecret;
use bitcoin::secp256k1::ecdsa::{RecoverableSignature, Signature};
use bitcoin::secp256k1::schnorr;
use bitcoin::secp256k1::{self, Message, PublicKey, Scalar, Secp256k1, SecretKey};
use lightning::io::Cursor;
use lightning::util::dyn_signer::DynSigner;
use std::cmp::{self, Ordering};
use std::mem;
use std::sync::atomic;
use std::sync::{Arc, Mutex};
const MAX_FEE: u32 = 10_000;
struct FuzzEstimator {
ret_val: atomic::AtomicU32,
}
impl FeeEstimator for FuzzEstimator {
fn get_est_sat_per_1000_weight(&self, conf_target: ConfirmationTarget) -> u32 {
// We force-close channels if our counterparty sends us a feerate which is a small multiple
// of our HighPriority fee estimate or smaller than our Background fee estimate. Thus, we
// always return a HighPriority feerate here which is >= the maximum Normal feerate and a
// Background feerate which is <= the minimum Normal feerate.
match conf_target {
ConfirmationTarget::MaximumFeeEstimate | ConfirmationTarget::UrgentOnChainSweep => {
MAX_FEE
},
ConfirmationTarget::ChannelCloseMinimum
| ConfirmationTarget::AnchorChannelFee
| ConfirmationTarget::MinAllowedAnchorChannelRemoteFee
| ConfirmationTarget::MinAllowedNonAnchorChannelRemoteFee
| ConfirmationTarget::OutputSpendingFee => 253,
ConfirmationTarget::NonAnchorChannelFee => {
cmp::min(self.ret_val.load(atomic::Ordering::Acquire), MAX_FEE)
},
}
}
}
struct FuzzRouter {}
impl Router for FuzzRouter {
fn find_route(
&self, _payer: &PublicKey, _params: &RouteParameters,
_first_hops: Option<&[&ChannelDetails]>, _inflight_htlcs: InFlightHtlcs,
) -> Result<Route, &'static str> {
unreachable!()
}
fn create_blinded_payment_paths<T: secp256k1::Signing + secp256k1::Verification>(
&self, _recipient: PublicKey, _first_hops: Vec<ChannelDetails>, _tlvs: ReceiveTlvs,
_amount_msats: Option<u64>, _secp_ctx: &Secp256k1<T>,
) -> Result<Vec<BlindedPaymentPath>, ()> {
unreachable!()
}
}
impl MessageRouter for FuzzRouter {
fn find_path(
&self, _sender: PublicKey, _peers: Vec<PublicKey>, _destination: Destination,
) -> Result<OnionMessagePath, ()> {
unreachable!()
}
fn create_blinded_paths<T: secp256k1::Signing + secp256k1::Verification>(
&self, _recipient: PublicKey, _context: MessageContext, _peers: Vec<PublicKey>,
_secp_ctx: &Secp256k1<T>,
) -> Result<Vec<BlindedMessagePath>, ()> {
unreachable!()
}
}
pub struct TestBroadcaster {}
impl BroadcasterInterface for TestBroadcaster {
fn broadcast_transactions(&self, _txs: &[&Transaction]) {}
}
pub struct VecWriter(pub Vec<u8>);
impl Writer for VecWriter {
fn write_all(&mut self, buf: &[u8]) -> Result<(), ::lightning::io::Error> {
self.0.extend_from_slice(buf);
Ok(())
}
}
/// The LDK API requires that any time we tell it we're done persisting a `ChannelMonitor[Update]`
/// we never pass it in as the "latest" `ChannelMonitor` on startup. However, we can pass
/// out-of-date monitors as long as we never told LDK we finished persisting them, which we do by
/// storing both old `ChannelMonitor`s and ones that are "being persisted" here.
///
/// Note that such "being persisted" `ChannelMonitor`s are stored in `ChannelManager` and will
/// simply be replayed on startup.
struct LatestMonitorState {
/// The latest monitor id which we told LDK we've persisted
persisted_monitor_id: u64,
/// The latest serialized `ChannelMonitor` that we told LDK we persisted.
persisted_monitor: Vec<u8>,
/// A set of (monitor id, serialized `ChannelMonitor`)s which we're currently "persisting",
/// from LDK's perspective.
pending_monitors: Vec<(u64, Vec<u8>)>,
}
struct TestChainMonitor {
pub logger: Arc<dyn Logger>,
pub keys: Arc<KeyProvider>,
pub persister: Arc<TestPersister>,
pub chain_monitor: Arc<
chainmonitor::ChainMonitor<
TestChannelSigner,
Arc<dyn chain::Filter>,
Arc<TestBroadcaster>,
Arc<FuzzEstimator>,
Arc<dyn Logger>,
Arc<TestPersister>,
>,
>,
pub latest_monitors: Mutex<HashMap<ChannelId, LatestMonitorState>>,
}
impl TestChainMonitor {
pub fn new(
broadcaster: Arc<TestBroadcaster>, logger: Arc<dyn Logger>, feeest: Arc<FuzzEstimator>,
persister: Arc<TestPersister>, keys: Arc<KeyProvider>,
) -> Self {
Self {
chain_monitor: Arc::new(chainmonitor::ChainMonitor::new(
None,
broadcaster,
logger.clone(),
feeest,
Arc::clone(&persister),
keys.get_peer_storage_key(),
)),
logger,
keys,
persister,
latest_monitors: Mutex::new(new_hash_map()),
}
}
}
impl chain::Watch<TestChannelSigner> for TestChainMonitor {
fn watch_channel(
&self, channel_id: ChannelId, monitor: channelmonitor::ChannelMonitor<TestChannelSigner>,
) -> Result<chain::ChannelMonitorUpdateStatus, ()> {
let mut ser = VecWriter(Vec::new());
monitor.write(&mut ser).unwrap();
let monitor_id = monitor.get_latest_update_id();
let res = self.chain_monitor.watch_channel(channel_id, monitor);
let state = match res {
Ok(chain::ChannelMonitorUpdateStatus::Completed) => LatestMonitorState {
persisted_monitor_id: monitor_id,
persisted_monitor: ser.0,
pending_monitors: Vec::new(),
},
Ok(chain::ChannelMonitorUpdateStatus::InProgress) => {
panic!("The test currently doesn't test initial-persistence via the async pipeline")
},
Ok(chain::ChannelMonitorUpdateStatus::UnrecoverableError) => panic!(),
Err(()) => panic!(),
};
if self.latest_monitors.lock().unwrap().insert(channel_id, state).is_some() {
panic!("Already had monitor pre-watch_channel");
}
res
}
fn update_channel(
&self, channel_id: ChannelId, update: &channelmonitor::ChannelMonitorUpdate,
) -> chain::ChannelMonitorUpdateStatus {
let mut map_lock = self.latest_monitors.lock().unwrap();
let map_entry = map_lock.get_mut(&channel_id).expect("Didn't have monitor on update call");
let latest_monitor_data = map_entry
.pending_monitors
.last()
.as_ref()
.map(|(_, data)| data)
.unwrap_or(&map_entry.persisted_monitor);
let deserialized_monitor =
<(BlockHash, channelmonitor::ChannelMonitor<TestChannelSigner>)>::read(
&mut Cursor::new(&latest_monitor_data),
(&*self.keys, &*self.keys),
)
.unwrap()
.1;
deserialized_monitor
.update_monitor(
update,
&&TestBroadcaster {},
&&FuzzEstimator { ret_val: atomic::AtomicU32::new(253) },
&self.logger,
)
.unwrap();
let mut ser = VecWriter(Vec::new());
deserialized_monitor.write(&mut ser).unwrap();
let res = self.chain_monitor.update_channel(channel_id, update);
match res {
chain::ChannelMonitorUpdateStatus::Completed => {
map_entry.persisted_monitor_id = update.update_id;
map_entry.persisted_monitor = ser.0;
},
chain::ChannelMonitorUpdateStatus::InProgress => {
map_entry.pending_monitors.push((update.update_id, ser.0));
},
chain::ChannelMonitorUpdateStatus::UnrecoverableError => panic!(),
}
res
}
fn release_pending_monitor_events(
&self,
) -> Vec<(OutPoint, ChannelId, Vec<MonitorEvent>, PublicKey)> {
return self.chain_monitor.release_pending_monitor_events();
}
}
struct KeyProvider {
node_secret: SecretKey,
rand_bytes_id: atomic::AtomicU32,
enforcement_states: Mutex<HashMap<[u8; 32], Arc<Mutex<EnforcementState>>>>,
}
impl EntropySource for KeyProvider {
fn get_secure_random_bytes(&self) -> [u8; 32] {
let id = self.rand_bytes_id.fetch_add(1, atomic::Ordering::Relaxed);
#[rustfmt::skip]
let mut res = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 11, self.node_secret[31]];
res[30 - 4..30].copy_from_slice(&id.to_le_bytes());
res
}
}
impl NodeSigner for KeyProvider {
fn get_node_id(&self, recipient: Recipient) -> Result<PublicKey, ()> {
let node_secret = match recipient {
Recipient::Node => Ok(&self.node_secret),
Recipient::PhantomNode => Err(()),
}?;
Ok(PublicKey::from_secret_key(&Secp256k1::signing_only(), node_secret))
}
fn ecdh(
&self, recipient: Recipient, other_key: &PublicKey, tweak: Option<&Scalar>,
) -> Result<SharedSecret, ()> {
let mut node_secret = match recipient {
Recipient::Node => Ok(self.node_secret.clone()),
Recipient::PhantomNode => Err(()),
}?;
if let Some(tweak) = tweak {
node_secret = node_secret.mul_tweak(tweak).map_err(|_| ())?;
}
Ok(SharedSecret::new(other_key, &node_secret))
}
fn get_inbound_payment_key(&self) -> ExpandedKey {
#[rustfmt::skip]
let random_bytes = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, self.node_secret[31]];
ExpandedKey::new(random_bytes)
}
fn sign_invoice(
&self, _invoice: &RawBolt11Invoice, _recipient: Recipient,
) -> Result<RecoverableSignature, ()> {
unreachable!()
}
fn get_peer_storage_key(&self) -> SecretKey {
SecretKey::from_slice(&[42; 32]).unwrap()
}
fn sign_bolt12_invoice(
&self, _invoice: &UnsignedBolt12Invoice,
) -> Result<schnorr::Signature, ()> {
unreachable!()
}
fn sign_gossip_message(
&self, msg: lightning::ln::msgs::UnsignedGossipMessage,
) -> Result<Signature, ()> {
let msg_hash = Message::from_digest(Sha256dHash::hash(&msg.encode()[..]).to_byte_array());
let secp_ctx = Secp256k1::signing_only();
Ok(secp_ctx.sign_ecdsa(&msg_hash, &self.node_secret))
}
}
impl SignerProvider for KeyProvider {
type EcdsaSigner = TestChannelSigner;
#[cfg(taproot)]
type TaprootSigner = TestChannelSigner;
fn generate_channel_keys_id(&self, _inbound: bool, _user_channel_id: u128) -> [u8; 32] {
let id = self.rand_bytes_id.fetch_add(1, atomic::Ordering::Relaxed) as u8;
[id; 32]
}
fn derive_channel_signer(&self, channel_keys_id: [u8; 32]) -> Self::EcdsaSigner {
let secp_ctx = Secp256k1::signing_only();
let id = channel_keys_id[0];
#[rustfmt::skip]
let keys = InMemorySigner::new(
&secp_ctx,
SecretKey::from_slice(&[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, self.node_secret[31]]).unwrap(),
SecretKey::from_slice(&[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, self.node_secret[31]]).unwrap(),
SecretKey::from_slice(&[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, self.node_secret[31]]).unwrap(),
SecretKey::from_slice(&[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, self.node_secret[31]]).unwrap(),
SecretKey::from_slice(&[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8, self.node_secret[31]]).unwrap(),
[id, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9, self.node_secret[31]],
channel_keys_id,
channel_keys_id,
);
let revoked_commitment = self.make_enforcement_state_cell(keys.commitment_seed);
let keys = DynSigner::new(keys);
TestChannelSigner::new_with_revoked(keys, revoked_commitment, false)
}
fn get_destination_script(&self, _channel_keys_id: [u8; 32]) -> Result<ScriptBuf, ()> {
let secp_ctx = Secp256k1::signing_only();
#[rustfmt::skip]
let channel_monitor_claim_key = SecretKey::from_slice(&[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, self.node_secret[31]]).unwrap();
let our_channel_monitor_claim_key_hash = WPubkeyHash::hash(
&PublicKey::from_secret_key(&secp_ctx, &channel_monitor_claim_key).serialize(),
);
Ok(Builder::new()
.push_opcode(opcodes::all::OP_PUSHBYTES_0)
.push_slice(our_channel_monitor_claim_key_hash)
.into_script())
}
fn get_shutdown_scriptpubkey(&self) -> Result<ShutdownScript, ()> {
let secp_ctx = Secp256k1::signing_only();
#[rustfmt::skip]
let secret_key = SecretKey::from_slice(&[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, self.node_secret[31]]).unwrap();
let pubkey_hash =
WPubkeyHash::hash(&PublicKey::from_secret_key(&secp_ctx, &secret_key).serialize());
Ok(ShutdownScript::new_p2wpkh(&pubkey_hash))
}
}
impl KeyProvider {
fn make_enforcement_state_cell(
&self, commitment_seed: [u8; 32],
) -> Arc<Mutex<EnforcementState>> {
let mut revoked_commitments = self.enforcement_states.lock().unwrap();
if !revoked_commitments.contains_key(&commitment_seed) {
revoked_commitments
.insert(commitment_seed, Arc::new(Mutex::new(EnforcementState::new())));
}
let cell = revoked_commitments.get(&commitment_seed).unwrap();
Arc::clone(cell)
}
}
// Returns a bool indicating whether the payment failed.
#[inline]
fn check_payment_send_events(source: &ChanMan, sent_payment_id: PaymentId) -> bool {
for payment in source.list_recent_payments() {
match payment {
RecentPaymentDetails::Pending { payment_id, .. } if payment_id == sent_payment_id => {
return true;
},
RecentPaymentDetails::Abandoned { payment_id, .. } if payment_id == sent_payment_id => {
return false;
},
_ => {},
}
}
return false;
}
type ChanMan<'a> = ChannelManager<
Arc<TestChainMonitor>,
Arc<TestBroadcaster>,
Arc<KeyProvider>,
Arc<KeyProvider>,
Arc<KeyProvider>,
Arc<FuzzEstimator>,
&'a FuzzRouter,
&'a FuzzRouter,
Arc<dyn Logger>,
>;
#[inline]
fn get_payment_secret_hash(
dest: &ChanMan, payment_id: &mut u8,
) -> Option<(PaymentSecret, PaymentHash)> {
let mut payment_hash;
for _ in 0..256 {
payment_hash = PaymentHash(Sha256::hash(&[*payment_id; 1]).to_byte_array());
if let Ok(payment_secret) =
dest.create_inbound_payment_for_hash(payment_hash, None, 3600, None)
{
return Some((payment_secret, payment_hash));
}
*payment_id = payment_id.wrapping_add(1);
}
None
}
#[inline]
fn send_noret(
source: &ChanMan, dest: &ChanMan, dest_chan_id: u64, amt: u64, payment_id: &mut u8,
payment_idx: &mut u64,
) {
send_payment(source, dest, dest_chan_id, amt, payment_id, payment_idx);
}
#[inline]
fn send_payment(
source: &ChanMan, dest: &ChanMan, dest_chan_id: u64, amt: u64, payment_id: &mut u8,
payment_idx: &mut u64,
) -> bool {
let (payment_secret, payment_hash) =
if let Some((secret, hash)) = get_payment_secret_hash(dest, payment_id) {
(secret, hash)
} else {
return true;
};
let mut payment_id = [0; 32];
payment_id[0..8].copy_from_slice(&payment_idx.to_ne_bytes());
*payment_idx += 1;
let (min_value_sendable, max_value_sendable) = source
.list_usable_channels()
.iter()
.find(|chan| chan.short_channel_id == Some(dest_chan_id))
.map(|chan| (chan.next_outbound_htlc_minimum_msat, chan.next_outbound_htlc_limit_msat))
.unwrap_or((0, 0));
let route_params = RouteParameters::from_payment_params_and_value(
PaymentParameters::from_node_id(source.get_our_node_id(), TEST_FINAL_CLTV),
amt,
);
let route = Route {
paths: vec![Path {
hops: vec![RouteHop {
pubkey: dest.get_our_node_id(),
node_features: dest.node_features(),
short_channel_id: dest_chan_id,
channel_features: dest.channel_features(),
fee_msat: amt,
cltv_expiry_delta: 200,
maybe_announced_channel: true,
}],
blinded_tail: None,
}],
route_params: Some(route_params.clone()),
};
let onion = RecipientOnionFields::secret_only(payment_secret);
let payment_id = PaymentId(payment_id);
let res = source.send_payment_with_route(route, payment_hash, onion, payment_id);
match res {
Err(err) => {
panic!("Errored with {:?} on initial payment send", err);
},
Ok(()) => {
let expect_failure = amt < min_value_sendable || amt > max_value_sendable;
let succeeded = check_payment_send_events(source, payment_id);
assert_eq!(succeeded, !expect_failure);
succeeded
},
}
}
#[inline]
fn send_hop_noret(
source: &ChanMan, middle: &ChanMan, middle_chan_id: u64, dest: &ChanMan, dest_chan_id: u64,
amt: u64, payment_id: &mut u8, payment_idx: &mut u64,
) {
send_hop_payment(
source,
middle,
middle_chan_id,
dest,
dest_chan_id,
amt,
payment_id,
payment_idx,
);
}
#[inline]
fn send_hop_payment(
source: &ChanMan, middle: &ChanMan, middle_chan_id: u64, dest: &ChanMan, dest_chan_id: u64,
amt: u64, payment_id: &mut u8, payment_idx: &mut u64,
) -> bool {
let (payment_secret, payment_hash) =
if let Some((secret, hash)) = get_payment_secret_hash(dest, payment_id) {
(secret, hash)
} else {
return true;
};
let mut payment_id = [0; 32];
payment_id[0..8].copy_from_slice(&payment_idx.to_ne_bytes());
*payment_idx += 1;
let (min_value_sendable, max_value_sendable) = source
.list_usable_channels()
.iter()
.find(|chan| chan.short_channel_id == Some(middle_chan_id))
.map(|chan| (chan.next_outbound_htlc_minimum_msat, chan.next_outbound_htlc_limit_msat))
.unwrap_or((0, 0));
let first_hop_fee = 50_000;
let route_params = RouteParameters::from_payment_params_and_value(
PaymentParameters::from_node_id(source.get_our_node_id(), TEST_FINAL_CLTV),
amt,
);
let route = Route {
paths: vec![Path {
hops: vec![
RouteHop {
pubkey: middle.get_our_node_id(),
node_features: middle.node_features(),
short_channel_id: middle_chan_id,
channel_features: middle.channel_features(),
fee_msat: first_hop_fee,
cltv_expiry_delta: 100,
maybe_announced_channel: true,
},
RouteHop {
pubkey: dest.get_our_node_id(),
node_features: dest.node_features(),
short_channel_id: dest_chan_id,
channel_features: dest.channel_features(),
fee_msat: amt,
cltv_expiry_delta: 200,
maybe_announced_channel: true,
},
],
blinded_tail: None,
}],
route_params: Some(route_params.clone()),
};
let onion = RecipientOnionFields::secret_only(payment_secret);
let payment_id = PaymentId(payment_id);
let res = source.send_payment_with_route(route, payment_hash, onion, payment_id);
match res {
Err(err) => {
panic!("Errored with {:?} on initial payment send", err);
},
Ok(()) => {
let sent_amt = amt + first_hop_fee;
let expect_failure = sent_amt < min_value_sendable || sent_amt > max_value_sendable;
let succeeded = check_payment_send_events(source, payment_id);
assert_eq!(succeeded, !expect_failure);
succeeded
},
}
}
#[inline]
pub fn do_test<Out: Output>(data: &[u8], underlying_out: Out, anchors: bool) {
let out = SearchingOutput::new(underlying_out);
let broadcast = Arc::new(TestBroadcaster {});
let router = FuzzRouter {};
macro_rules! make_node {
($node_id: expr, $fee_estimator: expr) => {{
let logger: Arc<dyn Logger> =
Arc::new(test_logger::TestLogger::new($node_id.to_string(), out.clone()));
let node_secret = SecretKey::from_slice(&[
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 1, $node_id,
])
.unwrap();
let keys_manager = Arc::new(KeyProvider {
node_secret,
rand_bytes_id: atomic::AtomicU32::new(0),
enforcement_states: Mutex::new(new_hash_map()),
});
let monitor = Arc::new(TestChainMonitor::new(
broadcast.clone(),
logger.clone(),
$fee_estimator.clone(),
Arc::new(TestPersister {
update_ret: Mutex::new(ChannelMonitorUpdateStatus::Completed),
}),
Arc::clone(&keys_manager),
));
let mut config = UserConfig::default();
config.channel_config.forwarding_fee_proportional_millionths = 0;
config.channel_handshake_config.announce_for_forwarding = true;
if anchors {
config.channel_handshake_config.negotiate_anchors_zero_fee_htlc_tx = true;
config.manually_accept_inbound_channels = true;
}
let network = Network::Bitcoin;
let best_block_timestamp = genesis_block(network).header.time;
let params = ChainParameters { network, best_block: BestBlock::from_network(network) };
(
ChannelManager::new(
$fee_estimator.clone(),
monitor.clone(),
broadcast.clone(),
&router,
&router,
Arc::clone(&logger),
keys_manager.clone(),
keys_manager.clone(),
keys_manager.clone(),
config,
params,
best_block_timestamp,
),
monitor,
keys_manager,
)
}};
}
macro_rules! reload_node {
($ser: expr, $node_id: expr, $old_monitors: expr, $keys_manager: expr, $fee_estimator: expr) => {{
let keys_manager = Arc::clone(&$keys_manager);
let logger: Arc<dyn Logger> =
Arc::new(test_logger::TestLogger::new($node_id.to_string(), out.clone()));
let chain_monitor = Arc::new(TestChainMonitor::new(
broadcast.clone(),
logger.clone(),
$fee_estimator.clone(),
Arc::new(TestPersister {
update_ret: Mutex::new(ChannelMonitorUpdateStatus::Completed),
}),
Arc::clone(&$keys_manager),
));
let mut config = UserConfig::default();
config.channel_config.forwarding_fee_proportional_millionths = 0;
config.channel_handshake_config.announce_for_forwarding = true;
if anchors {
config.channel_handshake_config.negotiate_anchors_zero_fee_htlc_tx = true;
config.manually_accept_inbound_channels = true;
}
let mut monitors = new_hash_map();
let mut old_monitors = $old_monitors.latest_monitors.lock().unwrap();
for (channel_id, mut prev_state) in old_monitors.drain() {
monitors.insert(
channel_id,
<(BlockHash, ChannelMonitor<TestChannelSigner>)>::read(
&mut Cursor::new(&prev_state.persisted_monitor),
(&*$keys_manager, &*$keys_manager),
)
.expect("Failed to read monitor")
.1,
);
// Wipe any `ChannelMonitor`s which we never told LDK we finished persisting,
// considering them discarded. LDK should replay these for us as they're stored in
// the `ChannelManager`.
prev_state.pending_monitors.clear();
chain_monitor.latest_monitors.lock().unwrap().insert(channel_id, prev_state);
}
let mut monitor_refs = new_hash_map();
for (channel_id, monitor) in monitors.iter() {
monitor_refs.insert(*channel_id, monitor);
}
let read_args = ChannelManagerReadArgs {
entropy_source: keys_manager.clone(),
node_signer: keys_manager.clone(),
signer_provider: keys_manager.clone(),
fee_estimator: $fee_estimator.clone(),
chain_monitor: chain_monitor.clone(),
tx_broadcaster: broadcast.clone(),
router: &router,
message_router: &router,
logger,
default_config: config,
channel_monitors: monitor_refs,
};
let res = (
<(BlockHash, ChanMan)>::read(&mut Cursor::new(&$ser.0), read_args)
.expect("Failed to read manager")
.1,
chain_monitor.clone(),
);
for (channel_id, mon) in monitors.drain() {
assert_eq!(
chain_monitor.chain_monitor.watch_channel(channel_id, mon),
Ok(ChannelMonitorUpdateStatus::Completed)
);
}
res
}};
}
let mut channel_txn = Vec::new();
macro_rules! make_channel {
($source: expr, $dest: expr, $dest_keys_manager: expr, $chan_id: expr) => {{
let init_dest = Init {
features: $dest.init_features(),
networks: None,
remote_network_address: None,
};
$source.peer_connected($dest.get_our_node_id(), &init_dest, true).unwrap();
let init_src = Init {
features: $source.init_features(),
networks: None,
remote_network_address: None,
};
$dest.peer_connected($source.get_our_node_id(), &init_src, false).unwrap();
$source.create_channel($dest.get_our_node_id(), 100_000, 42, 0, None, None).unwrap();
let open_channel = {
let events = $source.get_and_clear_pending_msg_events();
assert_eq!(events.len(), 1);
if let MessageSendEvent::SendOpenChannel { ref msg, .. } = events[0] {
msg.clone()
} else {
panic!("Wrong event type");
}
};
$dest.handle_open_channel($source.get_our_node_id(), &open_channel);
let accept_channel = {
if anchors {
let events = $dest.get_and_clear_pending_events();
assert_eq!(events.len(), 1);
if let events::Event::OpenChannelRequest {
ref temporary_channel_id,
ref counterparty_node_id,
..
} = events[0]
{
let mut random_bytes = [0u8; 16];
random_bytes
.copy_from_slice(&$dest_keys_manager.get_secure_random_bytes()[..16]);
let user_channel_id = u128::from_be_bytes(random_bytes);
$dest
.accept_inbound_channel(
temporary_channel_id,
counterparty_node_id,
user_channel_id,
None,
)
.unwrap();
} else {
panic!("Wrong event type");
}
}
let events = $dest.get_and_clear_pending_msg_events();
assert_eq!(events.len(), 1);
if let MessageSendEvent::SendAcceptChannel { ref msg, .. } = events[0] {
msg.clone()
} else {
panic!("Wrong event type");
}
};
$source.handle_accept_channel($dest.get_our_node_id(), &accept_channel);
{
let mut events = $source.get_and_clear_pending_events();
assert_eq!(events.len(), 1);
if let events::Event::FundingGenerationReady {
temporary_channel_id,
channel_value_satoshis,
output_script,
..
} = events.pop().unwrap()
{
let tx = Transaction {
version: Version($chan_id),
lock_time: LockTime::ZERO,
input: Vec::new(),
output: vec![TxOut {
value: Amount::from_sat(channel_value_satoshis),
script_pubkey: output_script,
}],
};
$source
.funding_transaction_generated(
temporary_channel_id,
$dest.get_our_node_id(),
tx.clone(),
)
.unwrap();
channel_txn.push(tx);
} else {
panic!("Wrong event type");
}
}
let funding_created = {
let events = $source.get_and_clear_pending_msg_events();
assert_eq!(events.len(), 1);
if let MessageSendEvent::SendFundingCreated { ref msg, .. } = events[0] {
msg.clone()
} else {
panic!("Wrong event type");
}
};
$dest.handle_funding_created($source.get_our_node_id(), &funding_created);
let funding_signed = {
let events = $dest.get_and_clear_pending_msg_events();
assert_eq!(events.len(), 1);
if let MessageSendEvent::SendFundingSigned { ref msg, .. } = events[0] {
msg.clone()
} else {
panic!("Wrong event type");
}
};
let events = $dest.get_and_clear_pending_events();
assert_eq!(events.len(), 1);
if let events::Event::ChannelPending { ref counterparty_node_id, .. } = events[0] {
assert_eq!(counterparty_node_id, &$source.get_our_node_id());
} else {
panic!("Wrong event type");
}
$source.handle_funding_signed($dest.get_our_node_id(), &funding_signed);
let events = $source.get_and_clear_pending_events();
assert_eq!(events.len(), 1);
let channel_id = if let events::Event::ChannelPending {
ref counterparty_node_id,
ref channel_id,
..
} = events[0]
{
assert_eq!(counterparty_node_id, &$dest.get_our_node_id());
channel_id.clone()
} else {
panic!("Wrong event type");
};
channel_id
}};
}
macro_rules! confirm_txn {
($node: expr) => {{
let chain_hash = genesis_block(Network::Bitcoin).block_hash();
let mut header = create_dummy_header(chain_hash, 42);
let txdata: Vec<_> =
channel_txn.iter().enumerate().map(|(i, tx)| (i + 1, tx)).collect();
$node.transactions_confirmed(&header, &txdata, 1);
for _ in 2..100 {
header = create_dummy_header(header.block_hash(), 42);
}
$node.best_block_updated(&header, 99);
}};
}
macro_rules! lock_fundings {
($nodes: expr) => {{
let mut node_events = Vec::new();
for node in $nodes.iter() {
node_events.push(node.get_and_clear_pending_msg_events());
}
for (idx, node_event) in node_events.iter().enumerate() {
for event in node_event {
if let MessageSendEvent::SendChannelReady { ref node_id, ref msg } = event {
for node in $nodes.iter() {
if node.get_our_node_id() == *node_id {
node.handle_channel_ready($nodes[idx].get_our_node_id(), msg);
}
}
} else {
panic!("Wrong event type");
}
}
}
for node in $nodes.iter() {
let events = node.get_and_clear_pending_msg_events();
for event in events {
if let MessageSendEvent::SendAnnouncementSignatures { .. } = event {
} else {
panic!("Wrong event type");
}
}
}
}};
}
let fee_est_a = Arc::new(FuzzEstimator { ret_val: atomic::AtomicU32::new(253) });
let mut last_htlc_clear_fee_a = 253;
let fee_est_b = Arc::new(FuzzEstimator { ret_val: atomic::AtomicU32::new(253) });
let mut last_htlc_clear_fee_b = 253;
let fee_est_c = Arc::new(FuzzEstimator { ret_val: atomic::AtomicU32::new(253) });
let mut last_htlc_clear_fee_c = 253;
// 3 nodes is enough to hit all the possible cases, notably unknown-source-unknown-dest
// forwarding.
let (node_a, mut monitor_a, keys_manager_a) = make_node!(0, fee_est_a);
let (node_b, mut monitor_b, keys_manager_b) = make_node!(1, fee_est_b);
let (node_c, mut monitor_c, keys_manager_c) = make_node!(2, fee_est_c);
let mut nodes = [node_a, node_b, node_c];
let chan_1_id = make_channel!(nodes[0], nodes[1], keys_manager_b, 0);
let chan_2_id = make_channel!(nodes[1], nodes[2], keys_manager_c, 1);
for node in nodes.iter() {
confirm_txn!(node);
}
lock_fundings!(nodes);
let chan_a = nodes[0].list_usable_channels()[0].short_channel_id.unwrap();
let chan_a_id = nodes[0].list_usable_channels()[0].channel_id;
let chan_b = nodes[2].list_usable_channels()[0].short_channel_id.unwrap();
let chan_b_id = nodes[2].list_usable_channels()[0].channel_id;
let mut p_id: u8 = 0;
let mut p_idx: u64 = 0;
let mut chan_a_disconnected = false;
let mut chan_b_disconnected = false;
let mut ab_events = Vec::new();
let mut ba_events = Vec::new();
let mut bc_events = Vec::new();
let mut cb_events = Vec::new();
let mut node_a_ser = VecWriter(Vec::new());
nodes[0].write(&mut node_a_ser).unwrap();
let mut node_b_ser = VecWriter(Vec::new());
nodes[1].write(&mut node_b_ser).unwrap();
let mut node_c_ser = VecWriter(Vec::new());
nodes[2].write(&mut node_c_ser).unwrap();
macro_rules! test_return {
() => {{
assert_eq!(nodes[0].list_channels().len(), 1);
assert_eq!(nodes[1].list_channels().len(), 2);
assert_eq!(nodes[2].list_channels().len(), 1);
return;
}};
}