-
Notifications
You must be signed in to change notification settings - Fork 476
Expand file tree
/
Copy pathchanmon_consistency.rs
More file actions
3868 lines (3596 loc) · 128 KB
/
Copy pathchanmon_consistency.rs
File metadata and controls
3868 lines (3596 loc) · 128 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.
//! 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 receive- or
//! send-side handling is correct, other peers. We consider it a failure if any action results in
//! a channel being force-closed. The fuzzer also models transaction relay through a harness
//! mempool, making transaction confirmation and block delivery closer to normal node behavior.
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::FeeRate;
use bitcoin::OutPoint as BitcoinOutPoint;
use bitcoin::block::Header;
use bitcoin::hash_types::Txid;
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, MessageForwardNode};
use lightning::blinded_path::payment::{BlindedPaymentPath, ReceiveTlvs};
use lightning::chain;
use lightning::chain::chaininterface::{
BroadcasterInterface, ConfirmationTarget, FeeEstimator, TransactionType,
};
use lightning::chain::channelmonitor::{ChannelMonitor, ANTI_REORG_DELAY};
use lightning::chain::{
chainmonitor, channelmonitor, BlockLocator, ChannelMonitorUpdateStatus, Confirm, Watch,
};
use lightning::events;
use lightning::ln::channel::{
FEE_SPIKE_BUFFER_FEE_INCREASE_MULTIPLE, MAX_STD_OUTPUT_DUST_LIMIT_SATOSHIS,
};
use lightning::ln::channel_state::ChannelDetails;
use lightning::ln::channelmanager::{
ChainParameters, ChannelManager, ChannelManagerReadArgs, PaymentId, RecentPaymentDetails,
TrustedChannelFeatures,
};
use lightning::ln::functional_test_utils::*;
use lightning::ln::inbound_payment::ExpandedKey;
use lightning::ln::msgs::{
self, BaseMessageHandler, ChannelMessageHandler, CommitmentUpdate, Init, MessageSendEvent,
UpdateAddHTLC,
};
use lightning::ln::outbound_payment::RecipientOnionFields;
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, PeerStorageKey, ReceiveAuthKey, Recipient,
SignerProvider,
};
use lightning::types::payment::{PaymentHash, PaymentPreimage, PaymentSecret};
use lightning::util::config::UserConfig;
use lightning::util::errors::APIError;
use lightning::util::hash_tables::*;
use lightning::util::logger::Logger;
use lightning::util::native_async::{MaybeSend, MaybeSync};
use lightning::util::ser::{LengthReadable, ReadableArgs, Writeable, Writer};
use lightning::util::test_channel_signer::{EnforcementState, SignerOp, TestChannelSigner};
use lightning::util::test_utils::TestWalletSource;
use lightning::util::wallet_utils::{WalletSourceSync, WalletSync};
use lightning_invoice::RawBolt11Invoice;
use crate::utils::test_logger::{self, Output};
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::util::dyn_signer::DynSigner;
use std::cell::RefCell;
use std::cmp;
use std::collections::HashSet;
use std::mem;
use std::sync::atomic;
use std::sync::{Arc, Mutex};
const MAX_FEE: u32 = 10_000;
const MAX_SETTLE_ITERATIONS: usize = 256;
// Each wallet is seeded with enough confirmed UTXOs that repeated splice
// transactions don't run out of inputs mid-run.
const NUM_WALLET_UTXOS: u32 = 50;
// A single fuzz byte can mine more than one block so a corpus entry does not
// need long runs of identical "mine one block" commands to reach CSV or CLTV
// boundaries. Mining commands are capped in `safe_mine_block_count` if
// unresolved HTLCs are near expiry.
const MINE_BLOCK_COUNTS: [u32; 8] = [1, 2, 3, 6, 12, 24, 48, 144];
// Finish-time relay/mining rounds are capped so cleanup cannot spin forever.
const MAX_FINISH_RELAY_MINE_ROUNDS: usize = 32;
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)
},
}
}
}
impl FuzzEstimator {
fn feerate_sat_per_kw(&self) -> FeeRate {
let feerate = self.ret_val.load(atomic::Ordering::Acquire);
FeeRate::from_sat_per_kwu(feerate as u64)
}
}
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, _local_node_receive_key: ReceiveAuthKey,
_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, _local_node_receive_key: ReceiveAuthKey,
_context: MessageContext, _peers: Vec<MessageForwardNode>, _secp_ctx: &Secp256k1<T>,
) -> Result<Vec<BlindedMessagePath>, ()> {
unreachable!()
}
}
pub struct TestBroadcaster {
txn_broadcasted: RefCell<Vec<Transaction>>,
}
impl BroadcasterInterface for TestBroadcaster {
fn broadcast_transactions(&self, txs: &[(&Transaction, TransactionType)]) {
for (tx, _broadcast_type) in txs {
self.txn_broadcasted.borrow_mut().push((*tx).clone());
}
}
}
struct ChainState {
blocks: Vec<(Header, Vec<Transaction>)>,
confirmed_txids: HashSet<Txid>,
/// Unconfirmed transactions admitted to the mempool, in valid block order:
/// every input is either confirmed already or created by an earlier
/// transaction in this vector.
pending_txs: Vec<(Txid, Transaction)>,
/// Unspent outputs created by confirmed transactions. Mempool admission
/// checks inputs against this set, adjusted for outputs created and spent
/// by the transactions already in `pending_txs`.
utxos: HashSet<BitcoinOutPoint>,
}
impl ChainState {
fn new() -> Self {
let genesis_hash = genesis_block(Network::Bitcoin).block_hash();
let genesis_header = create_dummy_header(genesis_hash, 42);
Self {
blocks: vec![(genesis_header, Vec::new())],
confirmed_txids: HashSet::new(),
pending_txs: Vec::new(),
utxos: HashSet::new(),
}
}
fn tip_height(&self) -> u32 {
(self.blocks.len() - 1) as u32
}
fn is_unspent(&self, outpoint: &BitcoinOutPoint) -> bool {
self.utxos.contains(outpoint)
}
fn confirmed_output(&self, outpoint: &BitcoinOutPoint) -> Option<&TxOut> {
if !self.confirmed_txids.contains(&outpoint.txid) {
return None;
}
self.blocks.iter().find_map(|(_, txs)| {
txs.iter().find_map(|tx| {
if tx.compute_txid() == outpoint.txid {
tx.output.get(outpoint.vout as usize)
} else {
None
}
})
})
}
// Initial channel funding is represented by a no-input transaction. It is
// not a valid Bitcoin transaction, but it gives LDK a stable funding
// outpoint without modeling coin selection during channel setup.
fn is_synthetic_funding_tx(tx: &Transaction) -> bool {
!tx.is_coinbase() && tx.input.is_empty()
}
// Checks whether a transaction spends an input twice or spends an output
// not present in `utxos`.
fn has_invalid_inputs(tx: &Transaction, utxos: &HashSet<BitcoinOutPoint>) -> bool {
let mut spent_inputs = HashSet::new();
for input in &tx.input {
if !spent_inputs.insert(input.previous_output) {
return true;
}
if !utxos.contains(&input.previous_output) {
return true;
}
}
false
}
fn apply_tx_to_utxos(&mut self, txid: Txid, tx: &Transaction) {
for input in &tx.input {
self.utxos.remove(&input.previous_output);
}
for idx in 0..tx.output.len() {
self.utxos.insert(BitcoinOutPoint { txid, vout: idx as u32 });
}
}
fn mine_block(&mut self, txs: Vec<Transaction>) {
let prev_hash = self.blocks.last().unwrap().0.block_hash();
let header = create_dummy_header(prev_hash, 42);
self.blocks.push((header, txs));
}
fn mine_empty_blocks(&mut self, count: u32) {
for _ in 0..count {
self.mine_block(Vec::new());
}
}
// Mines a setup transaction directly into a block, bypassing the mempool,
// and buries it to `depth`. Wallet seeding and synthetic funding
// transactions are not relayable, so they cannot go through normal
// admission.
fn mine_setup_tx_to_depth(&mut self, tx: Transaction, depth: u32) {
assert!(
tx.is_coinbase() || Self::is_synthetic_funding_tx(&tx),
"direct setup mining is only for coinbase and synthetic funding transactions: {:?}",
tx,
);
let txid = tx.compute_txid();
assert!(
self.confirmed_txids.insert(txid),
"direct setup transaction was already confirmed: {:?}",
tx,
);
self.apply_tx_to_utxos(txid, &tx);
self.mine_block(vec![tx]);
self.mine_empty_blocks(depth.saturating_sub(1));
}
// Attempts to admit a broadcast transaction to the mempool, enforcing
// locktime, input, and RBF rules. Mining later confirms the whole mempool
// without further selection.
fn admit_tx_to_mempool(&mut self, tx: Transaction) {
let txid = tx.compute_txid();
let lock_time = tx.lock_time.to_consensus_u32();
let locktime_enabled =
tx.input.iter().any(|input| input.sequence.enables_absolute_lock_time());
let is_ldk_commitment_obscured_locktime =
tx.input.len() == 1 && tx.input[0].sequence.0 >> 24 == 0x80 && lock_time >> 24 == 0x20;
let immature_absolute_locktime =
locktime_enabled && tx.lock_time.is_block_height() && self.tip_height() < lock_time;
assert!(
!immature_absolute_locktime,
"broadcast immature locktime transaction into chanmon harness mempool: {:?}",
tx,
);
let unmodeled_time_locktime = locktime_enabled
&& tx.lock_time.is_block_time()
&& !is_ldk_commitment_obscured_locktime;
assert!(
!unmodeled_time_locktime,
"broadcast time-locked transaction into chanmon harness mempool: {:?}",
tx,
);
assert!(
!tx.is_coinbase() && !Self::is_synthetic_funding_tx(&tx),
"setup-only transaction entered chanmon harness mempool: {:?}",
tx,
);
if self.confirmed_txids.contains(&txid) {
return;
}
if self.pending_txs.iter().any(|(pending_txid, _)| *pending_txid == txid) {
return;
}
// Fee-rate policy is not modeled, so among conflicting RBF candidates
// the last one relayed wins.
let mut conflicting_pending_txids = HashSet::new();
for (pending_txid, pending_tx) in &self.pending_txs {
let signals_rbf = pending_tx.input.iter().any(|input| input.sequence.is_rbf());
let conflicts_with_new_tx = pending_tx.input.iter().any(|pending_input| {
tx.input.iter().any(|input| input.previous_output == pending_input.previous_output)
});
if conflicts_with_new_tx {
if !signals_rbf {
return;
}
conflicting_pending_txids.insert(*pending_txid);
}
}
if !conflicting_pending_txids.is_empty() {
let mut removed_outputs = HashSet::new();
let mut retained_txs = Vec::new();
for (pending_txid, pending_tx) in self.pending_txs.drain(..) {
let direct_conflict = conflicting_pending_txids.contains(&pending_txid);
let spends_removed_tx = pending_tx
.input
.iter()
.any(|input| removed_outputs.contains(&input.previous_output));
if direct_conflict || spends_removed_tx {
for idx in 0..pending_tx.output.len() {
removed_outputs
.insert(BitcoinOutPoint { txid: pending_txid, vout: idx as u32 });
}
} else {
retained_txs.push((pending_txid, pending_tx));
}
}
self.pending_txs = retained_txs;
}
// Build the UTXO set this transaction would see if the current mempool
// confirmed.
let mut available_utxos = self.utxos.clone();
for (pending_txid, pending_tx) in &self.pending_txs {
for input in &pending_tx.input {
available_utxos.remove(&input.previous_output);
}
for idx in 0..pending_tx.output.len() {
available_utxos.insert(BitcoinOutPoint { txid: *pending_txid, vout: idx as u32 });
}
}
if Self::has_invalid_inputs(&tx, &available_utxos) {
return;
}
self.pending_txs.push((txid, tx));
}
fn relay_transactions(&mut self, txs: Vec<Transaction>) {
for tx in txs {
self.admit_tx_to_mempool(tx);
}
}
// Mines `count` blocks, confirming the current mempool in the first block.
fn mine_blocks(&mut self, count: u32) -> Vec<Transaction> {
assert!(count > 0, "mining zero blocks should not be requested");
let mempool_txs = std::mem::take(&mut self.pending_txs);
let confirmed_txs = if mempool_txs.is_empty() {
self.mine_empty_blocks(1);
Vec::new()
} else {
let mut confirmed = Vec::new();
for (txid, tx) in mempool_txs {
assert!(
!Self::has_invalid_inputs(&tx, &self.utxos),
"mempool transaction was no longer valid at mining time: {:?}",
tx,
);
assert!(
self.confirmed_txids.insert(txid),
"mempool transaction was already confirmed at mining time: {:?}",
tx,
);
self.apply_tx_to_utxos(txid, &tx);
confirmed.push(tx);
}
let confirmed_txs = confirmed.clone();
self.mine_block(confirmed);
confirmed_txs
};
self.mine_empty_blocks(count - 1);
confirmed_txs
}
fn block_at(&self, height: u32) -> &(Header, Vec<Transaction>) {
&self.blocks[height as usize]
}
}
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(())
}
}
fn serialize_monitor(monitor: &ChannelMonitor<TestChannelSigner>) -> Vec<u8> {
let mut ser = VecWriter(Vec::new());
monitor.write(&mut ser).unwrap();
ser.0
}
/// LDK requires the `ChannelMonitor` loaded on startup to be at least as current as the
/// `ChannelManager` state, except for monitor updates that `ChannelManager` still records as
/// in-flight and can replay. This harness tracks the monitor blobs that remain valid restart
/// candidates under that rule.
///
/// Separately, we track every `InProgress` persistence operation that still needs a
/// `channel_monitor_updated` call. A newer persisted monitor can make an older monitor invalid for
/// restart while the older update still needs to be completed to unblock the live `ChainMonitor`.
///
/// Off-chain monitor updates that are still "being persisted" are stored in `ChannelManager` and
/// will be replayed on startup. Full-monitor snapshots from chain sync or archive paths that return
/// `InProgress` are only restart candidates; losing one on restart does not require a
/// `channel_monitor_updated` callback.
struct LatestMonitorState {
/// The latest monitor id which we told LDK we've persisted.
///
/// Note that earlier updates may still need a `channel_monitor_updated` callback via
/// [`Self::pending_monitor_completions`].
persisted_monitor_id: u64,
/// The latest serialized `ChannelMonitor` that we told LDK we persisted.
persisted_monitor: Vec<u8>,
/// An ordered list of (monitor id, serialized `ChannelMonitor`)s which remain safe to use as
/// stale monitors on reload.
pending_monitors: Vec<(u64, Vec<u8>)>,
/// An ordered list of (monitor id, serialized `ChannelMonitor`)s which still need a
/// `channel_monitor_updated` callback.
pending_monitor_completions: Vec<(u64, Vec<u8>)>,
}
impl LatestMonitorState {
fn insert_pending_entry(
pending: &mut Vec<(u64, Vec<u8>)>, monitor_id: u64, serialized_monitor: Vec<u8>,
) {
// Monitor update ids must arrive in order. Assert at insertion time so duplicates or
// out-of-order updates fail close to the write that caused them instead of being sorted
// into place.
assert!(
pending.last().map_or(true, |(last_id, _)| *last_id < monitor_id),
"pending monitor updates should arrive in order"
);
pending.push((monitor_id, serialized_monitor));
}
fn insert_pending_monitor_candidate(&mut self, monitor_id: u64, serialized_monitor: Vec<u8>) {
// Full-monitor persists from chain sync or archive paths use the monitor's current
// latest_update_id rather than a fresh ChannelMonitorUpdate id. Keep duplicate ids so
// reload can choose between multiple same-id full snapshots that were in flight together.
if let Some((last_id, _)) = self.pending_monitors.last() {
assert!(*last_id <= monitor_id, "pending monitor updates should arrive in order");
}
self.pending_monitors.push((monitor_id, serialized_monitor));
}
fn mark_persisted(&mut self, monitor_id: u64, serialized_monitor: Vec<u8>) {
// Once a monitor is durable, use it as the restart baseline and stop tracking candidates
// at or behind that update id. Completion obligations are tracked separately and are
// deliberately not pruned here.
self.pending_monitors.retain(|(id, _)| *id > monitor_id);
if monitor_id >= self.persisted_monitor_id {
self.persisted_monitor_id = monitor_id;
self.persisted_monitor = serialized_monitor;
}
}
fn insert_pending(
&mut self, monitor_id: u64, serialized_monitor: Vec<u8>, needs_completion: bool,
) {
if needs_completion {
// persist_new_channel and update_persisted_channel(Some(_)) require a later
// channel_monitor_updated callback if persistence returns InProgress.
Self::insert_pending_entry(
&mut self.pending_monitors,
monitor_id,
serialized_monitor.clone(),
);
Self::insert_pending_entry(
&mut self.pending_monitor_completions,
monitor_id,
serialized_monitor,
);
} else {
// This harness treats update_persisted_channel(None, ...) as the chain-sync/archive
// case: the full monitor may be used on restart, but ChainMonitor does not wait for a
// channel_monitor_updated callback.
self.insert_pending_monitor_candidate(monitor_id, serialized_monitor);
}
}
fn mark_completed_update_persisted(&mut self, monitor_id: u64, serialized_monitor: Vec<u8>) {
// The selector/drain path should already have removed this entry before
// finish_monitor_update calls channel_monitor_updated. This check catches accidental
// double-completion or pruning of the wrong list.
assert!(
self.pending_monitor_completions.iter().all(|(id, _)| *id != monitor_id),
"completed monitor update should already be removed from the completion queue"
);
self.mark_persisted(monitor_id, serialized_monitor);
}
fn drain_pending_completions(&mut self) -> Vec<(u64, Vec<u8>)> {
std::mem::take(&mut self.pending_monitor_completions)
}
fn take_pending_completion(
&mut self, selector: MonitorUpdateSelector,
) -> Option<(u64, Vec<u8>)> {
// The fuzzer chooses which outstanding callback to deliver. These choices apply to
// completion obligations, not to the set of monitors that may be used on restart.
match selector {
MonitorUpdateSelector::First => {
if self.pending_monitor_completions.is_empty() {
None
} else {
Some(self.pending_monitor_completions.remove(0))
}
},
MonitorUpdateSelector::Second => {
if self.pending_monitor_completions.len() > 1 {
Some(self.pending_monitor_completions.remove(1))
} else {
None
}
},
MonitorUpdateSelector::Last => self.pending_monitor_completions.pop(),
}
}
fn select_monitor_for_reload(&mut self, selector: MonitorReloadSelector) {
// A restart can load the last monitor we told LDK was persisted, or a monitor snapshot
// whose write was started before the simulated crash.
let old_mon = (self.persisted_monitor_id, std::mem::take(&mut self.persisted_monitor));
let (monitor_id, serialized_monitor) = match selector {
MonitorReloadSelector::Persisted => old_mon,
MonitorReloadSelector::FirstPending => {
if self.pending_monitors.is_empty() {
old_mon
} else {
self.pending_monitors.remove(0)
}
},
MonitorReloadSelector::LastPending => self.pending_monitors.pop().unwrap_or(old_mon),
};
self.persisted_monitor_id = monitor_id;
self.persisted_monitor = serialized_monitor;
// After restart, stop tracking pre-restart in-flight writes. ChannelManager will replay
// off-chain monitor updates that still matter; full-monitor snapshots may simply be absent.
self.pending_monitors.clear();
self.pending_monitor_completions.clear();
}
}
struct HarnessPersister {
pub update_ret: Mutex<chain::ChannelMonitorUpdateStatus>,
pub latest_monitors: Mutex<HashMap<ChannelId, LatestMonitorState>>,
}
impl HarnessPersister {
fn track_monitor_update(
&self, channel_id: ChannelId, monitor_id: u64, serialized_monitor: Vec<u8>,
status: chain::ChannelMonitorUpdateStatus, needs_completion: bool,
) {
let mut latest_monitors = self.latest_monitors.lock().unwrap();
if let Some(state) = latest_monitors.get_mut(&channel_id) {
match status {
chain::ChannelMonitorUpdateStatus::Completed => {
// A completed write advances the restart baseline. Once LDK can rely on that
// monitor state being durable, the harness stops offering candidates at or
// behind that update id.
state.mark_persisted(monitor_id, serialized_monitor);
},
chain::ChannelMonitorUpdateStatus::InProgress => {
// InProgress always creates a restart candidate, but only some calls also need
// an explicit channel_monitor_updated completion.
state.insert_pending(monitor_id, serialized_monitor, needs_completion);
},
chain::ChannelMonitorUpdateStatus::UnrecoverableError => {},
}
} else {
let state = match status {
chain::ChannelMonitorUpdateStatus::Completed => LatestMonitorState {
persisted_monitor_id: monitor_id,
persisted_monitor: serialized_monitor,
pending_monitors: Vec::new(),
pending_monitor_completions: Vec::new(),
},
chain::ChannelMonitorUpdateStatus::InProgress => {
// The first persist for a channel is persist_new_channel, which always needs a
// completion callback when it returns InProgress. A full-monitor update without
// existing state would mean the harness missed the channel's initial monitor.
assert!(needs_completion, "missing monitor state for full monitor update");
LatestMonitorState {
persisted_monitor_id: monitor_id,
persisted_monitor: Vec::new(),
pending_monitors: vec![(monitor_id, serialized_monitor.clone())],
pending_monitor_completions: vec![(monitor_id, serialized_monitor)],
}
},
chain::ChannelMonitorUpdateStatus::UnrecoverableError => return,
};
assert!(
latest_monitors.insert(channel_id, state).is_none(),
"Already had monitor state pre-persist"
);
}
}
fn mark_update_completed(
&self, channel_id: ChannelId, monitor_id: u64, serialized_monitor: Vec<u8>,
) {
let mut latest_monitors = self.latest_monitors.lock().unwrap();
let state = latest_monitors
.get_mut(&channel_id)
.expect("missing monitor state for completed update");
// Once we tell LDK update N is completed, use the completed monitor as the restart
// baseline and drop restart candidates at or behind N.
state.mark_completed_update_persisted(monitor_id, serialized_monitor);
}
fn drain_pending_updates(&self, channel_id: &ChannelId) -> Vec<(u64, Vec<u8>)> {
self.latest_monitors
.lock()
.unwrap()
.get_mut(channel_id)
.map_or_else(Vec::new, |state| state.drain_pending_completions())
}
fn drain_all_pending_updates(&self) -> Vec<(ChannelId, u64, Vec<u8>)> {
let mut completed_updates = Vec::new();
for (channel_id, state) in self.latest_monitors.lock().unwrap().iter_mut() {
for (monitor_id, data) in state.drain_pending_completions() {
completed_updates.push((*channel_id, monitor_id, data));
}
}
completed_updates
}
fn take_pending_update(
&self, channel_id: &ChannelId, selector: MonitorUpdateSelector,
) -> Option<(u64, Vec<u8>)> {
self.latest_monitors
.lock()
.unwrap()
.get_mut(channel_id)
.and_then(|state| state.take_pending_completion(selector))
}
}
impl chainmonitor::Persist<TestChannelSigner> for HarnessPersister {
fn persist_new_channel(
&self, _monitor_name: lightning::util::persist::MonitorName,
data: &channelmonitor::ChannelMonitor<TestChannelSigner>,
) -> chain::ChannelMonitorUpdateStatus {
let status = self.update_ret.lock().unwrap().clone();
let monitor_id = data.get_latest_update_id();
let serialized_monitor = serialize_monitor(data);
self.track_monitor_update(data.channel_id(), monitor_id, serialized_monitor, status, true);
status
}
fn update_persisted_channel(
&self, _monitor_name: lightning::util::persist::MonitorName,
update: Option<&channelmonitor::ChannelMonitorUpdate>,
data: &channelmonitor::ChannelMonitor<TestChannelSigner>,
) -> chain::ChannelMonitorUpdateStatus {
let status = self.update_ret.lock().unwrap().clone();
let monitor_id = update.map_or_else(|| data.get_latest_update_id(), |upd| upd.update_id);
let serialized_monitor = serialize_monitor(data);
self.track_monitor_update(
data.channel_id(),
monitor_id,
serialized_monitor,
status,
// `None` normally comes from chain-sync or archive writes, which need no completion
// callback. `update_channel_internal` can also use `None` after `update_monitor`
// fails, but this harness does not model that error-recovery path.
update.is_some(),
);
status
}
fn archive_persisted_channel(&self, _monitor_name: lightning::util::persist::MonitorName) {}
}
type TestChainMonitor = chainmonitor::ChainMonitor<
TestChannelSigner,
Arc<dyn chain::Filter>,
Arc<TestBroadcaster>,
Arc<FuzzEstimator>,
Arc<dyn Logger + MaybeSend + MaybeSync>,
Arc<HarnessPersister>,
Arc<KeyProvider>,
>;
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 = [self.node_secret[31], 11, 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[2..6].copy_from_slice(&id.to_le_bytes());
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_expanded_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) -> PeerStorageKey {
PeerStorageKey { inner: [42; 32] }
}
fn get_receive_auth_key(&self) -> ReceiveAuthKey {
ReceiveAuthKey([41; 32])
}
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))
}
fn sign_message(&self, msg: &[u8]) -> Result<String, ()> {
Ok(lightning::util::message_signing::sign(msg, &self.node_secret))
}
}
impl SignerProvider for KeyProvider {
type EcdsaSigner = 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 id = channel_keys_id[0];
#[rustfmt::skip]
let keys = InMemorySigner::new(
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(),
// We leave both the v1 and v2 derivation to_remote keys the same as there's not any
// real reason to fuzz differences here.
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, 6, self.node_secret[31]]).unwrap(),
true,
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, 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, _channel_keys_id: [u8; 32]) -> 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))
}
}
// Since this fuzzer is only concerned with live-channel operations, we don't need to worry about
// any signer operations that come after a force close.
const SUPPORTED_SIGNER_OPS: [SignerOp; 4] = [
SignerOp::SignCounterpartyCommitment,
SignerOp::GetPerCommitmentPoint,
SignerOp::ReleaseCommitmentSecret,
SignerOp::SignSpliceSharedInput,
];
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)
}
fn disable_supported_ops_for_all_signers(&self) {
let enforcement_states = self.enforcement_states.lock().unwrap();
for (_, state) in enforcement_states.iter() {
for signer_op in SUPPORTED_SIGNER_OPS {
state.lock().unwrap().disabled_signer_ops.insert(signer_op);
}
}
}
fn enable_op_for_all_signers(&self, signer_op: SignerOp) {
let enforcement_states = self.enforcement_states.lock().unwrap();
for (_, state) in enforcement_states.iter() {
state.lock().unwrap().disabled_signer_ops.remove(&signer_op);
}
}
}
type ChanMan<'a> = ChannelManager<
Arc<TestChainMonitor>,
Arc<TestBroadcaster>,
Arc<KeyProvider>,
Arc<KeyProvider>,
Arc<KeyProvider>,
Arc<FuzzEstimator>,
&'a FuzzRouter,
&'a FuzzRouter,
Arc<dyn Logger + MaybeSend + MaybeSync>,
>;
#[inline]
fn assert_disconnect_action(action: &msgs::ErrorAction) -> (&msgs::WarningMessage, bool) {
// Since sending/receiving messages may be delayed, `timer_tick_occurred` may cause a node to
// disconnect their counterparty if they're expecting a timely response.
if let msgs::ErrorAction::DisconnectPeerWithWarning { ref msg } = action {
let is_quiescent_msg = msg.data.contains("already sent splice_locked, cannot RBF");
if !msg.data.contains("Disconnecting due to timeout awaiting response") && !is_quiescent_msg
{
panic!("Unexpected disconnect case: {}", msg.data);
}
(msg, is_quiescent_msg)
} else {
panic!("Expected disconnect, got: {:?}", action);
}
}
#[derive(Clone, Copy, PartialEq)]
enum ChanType {
Legacy,
KeyedAnchors,
ZeroFeeCommitments,
}
// While delivering messages, select across three possible message selection
// processes to maximize coverage. See the individual enum variants for details.
#[derive(Copy, Clone, PartialEq, Eq)]
enum ProcessMessages {
/// Deliver all available messages, including fetching any new messages from
/// `get_and_clear_pending_msg_events()` which may have side effects.
AllMessages,
/// Call `get_and_clear_pending_msg_events()` first, then deliver up to one
/// message, which may already be queued.
OneMessage,
/// Deliver up to one already-queued message. This avoids the side effects of
/// `get_and_clear_pending_msg_events()`, such as freeing the HTLC holding cell.
OnePendingMessage,
}
struct HarnessNode<'a> {
node_id: u8,
node: ChanMan<'a>,
monitor: Arc<TestChainMonitor>,
persister: Arc<HarnessPersister>,
keys_manager: Arc<KeyProvider>,
logger: Arc<dyn Logger + MaybeSend + MaybeSync>,
broadcaster: Arc<TestBroadcaster>,
fee_estimator: Arc<FuzzEstimator>,
wallet: Arc<TestWalletSource>,
wallet_sync: WalletSync<Arc<TestWalletSource>, Arc<dyn Logger + MaybeSend + MaybeSync>>,
persistence_style: ChannelMonitorUpdateStatus,
deferred: bool,
serialized_manager: Vec<u8>,
serialized_manager_generation: u64,
last_htlc_clear_fee: u32,
}
impl<'a> std::ops::Deref for HarnessNode<'a> {
type Target = ChanMan<'a>;
fn deref(&self) -> &Self::Target {
&self.node
}
}
impl<'a> HarnessNode<'a> {
fn build_logger<Out: Output + MaybeSend + MaybeSync>(
node_id: u8, out: &Out,