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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
// 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.

//! Logic to connect off-chain channel management with on-chain transaction monitoring.
//!
//! [`ChainMonitor`] is an implementation of [`chain::Watch`] used both to process blocks and to
//! update [`ChannelMonitor`]s accordingly. If any on-chain events need further processing, it will
//! make those available as [`MonitorEvent`]s to be consumed.
//!
//! [`ChainMonitor`] is parameterized by an optional chain source, which must implement the
//! [`chain::Filter`] trait. This provides a mechanism to signal new relevant outputs back to light
//! clients, such that transactions spending those outputs are included in block data.
//!
//! [`ChainMonitor`] may be used directly to monitor channels locally or as a part of a distributed
//! setup to monitor channels remotely. In the latter case, a custom [`chain::Watch`] implementation
//! would be responsible for routing each update to a remote server and for retrieving monitor
//! events. The remote server would make use of [`ChainMonitor`] for block processing and for
//! servicing [`ChannelMonitor`] updates from the client.

use bitcoin::blockdata::block::Header;
use bitcoin::hash_types::{Txid, BlockHash};

use crate::chain;
use crate::chain::{ChannelMonitorUpdateStatus, Filter, WatchedOutput};
use crate::chain::chaininterface::{BroadcasterInterface, FeeEstimator};
use crate::chain::channelmonitor::{ChannelMonitor, ChannelMonitorUpdate, Balance, MonitorEvent, TransactionOutputs, WithChannelMonitor, LATENCY_GRACE_PERIOD_BLOCKS};
use crate::chain::transaction::{OutPoint, TransactionData};
use crate::sign::ecdsa::WriteableEcdsaChannelSigner;
use crate::events;
use crate::events::{Event, EventHandler};
use crate::util::atomic_counter::AtomicCounter;
use crate::util::logger::{Logger, WithContext};
use crate::util::errors::APIError;
use crate::util::wakers::{Future, Notifier};
use crate::ln::channelmanager::ChannelDetails;

use crate::prelude::*;
use crate::sync::{RwLock, RwLockReadGuard, Mutex, MutexGuard};
use core::iter::FromIterator;
use core::ops::Deref;
use core::sync::atomic::{AtomicUsize, Ordering};
use bitcoin::secp256k1::PublicKey;

mod update_origin {
	#[derive(Debug, Clone, Copy, Hash, PartialEq, Eq)]
	/// A specific update's ID stored in a `MonitorUpdateId`, separated out to make the contents
	/// entirely opaque.
	pub(crate) enum UpdateOrigin {
		/// An update that was generated by the `ChannelManager` (via our [`crate::chain::Watch`]
		/// implementation). This corresponds to an actual [ChannelMonitorUpdate::update_id] field
		/// and [ChannelMonitor::get_latest_update_id].
		///
		/// [ChannelMonitor::get_latest_update_id]: crate::chain::channelmonitor::ChannelMonitor::get_latest_update_id
		/// [ChannelMonitorUpdate::update_id]: crate::chain::channelmonitor::ChannelMonitorUpdate::update_id
		OffChain(u64),
		/// An update that was generated during blockchain processing. The ID here is specific to the
		/// generating [ChannelMonitor] and does *not* correspond to any on-disk IDs.
		///
		/// [ChannelMonitor]: crate::chain::channelmonitor::ChannelMonitor
		ChainSync(u64),
	}
}

#[cfg(any(feature = "_test_utils", test))]
pub(crate) use update_origin::UpdateOrigin;
#[cfg(not(any(feature = "_test_utils", test)))]
use update_origin::UpdateOrigin;

/// An opaque identifier describing a specific [`Persist`] method call.
#[derive(Debug, Clone, Copy, Hash, PartialEq, Eq)]
pub struct MonitorUpdateId {
	pub(crate) contents: UpdateOrigin,
}

impl MonitorUpdateId {
	pub(crate) fn from_monitor_update(update: &ChannelMonitorUpdate) -> Self {
		Self { contents: UpdateOrigin::OffChain(update.update_id) }
	}
	pub(crate) fn from_new_monitor<ChannelSigner: WriteableEcdsaChannelSigner>(monitor: &ChannelMonitor<ChannelSigner>) -> Self {
		Self { contents: UpdateOrigin::OffChain(monitor.get_latest_update_id()) }
	}
}

/// `Persist` defines behavior for persisting channel monitors: this could mean
/// writing once to disk, and/or uploading to one or more backup services.
///
/// Persistence can happen in one of two ways - synchronously completing before the trait method
/// calls return or asynchronously in the background.
///
/// # For those implementing synchronous persistence
///
///  * If persistence completes fully (including any relevant `fsync()` calls), the implementation
///    should return [`ChannelMonitorUpdateStatus::Completed`], indicating normal channel operation
///    should continue.
///
///  * If persistence fails for some reason, implementations should consider returning
///    [`ChannelMonitorUpdateStatus::InProgress`] and retry all pending persistence operations in
///    the background with [`ChainMonitor::list_pending_monitor_updates`] and
///    [`ChainMonitor::get_monitor`].
///
///    Once a full [`ChannelMonitor`] has been persisted, all pending updates for that channel can
///    be marked as complete via [`ChainMonitor::channel_monitor_updated`].
///
///    If at some point no further progress can be made towards persisting the pending updates, the
///    node should simply shut down.
///
///  * If the persistence has failed and cannot be retried further (e.g. because of an outage),
///    [`ChannelMonitorUpdateStatus::UnrecoverableError`] can be used, though this will result in
///    an immediate panic and future operations in LDK generally failing.
///
/// # For those implementing asynchronous persistence
///
///  All calls should generally spawn a background task and immediately return
///  [`ChannelMonitorUpdateStatus::InProgress`]. Once the update completes,
///  [`ChainMonitor::channel_monitor_updated`] should be called with the corresponding
///  [`MonitorUpdateId`].
///
///  Note that unlike the direct [`chain::Watch`] interface,
///  [`ChainMonitor::channel_monitor_updated`] must be called once for *each* update which occurs.
///
///  If at some point no further progress can be made towards persisting a pending update, the node
///  should simply shut down. Until then, the background task should either loop indefinitely, or
///  persistence should be regularly retried with [`ChainMonitor::list_pending_monitor_updates`]
///  and [`ChainMonitor::get_monitor`] (note that if a full monitor is persisted all pending
///  monitor updates may be marked completed).
///
/// # Using remote watchtowers
///
/// Watchtowers may be updated as a part of an implementation of this trait, utilizing the async
/// update process described above while the watchtower is being updated. The following methods are
/// provided for bulding transactions for a watchtower:
/// [`ChannelMonitor::initial_counterparty_commitment_tx`],
/// [`ChannelMonitor::counterparty_commitment_txs_from_update`],
/// [`ChannelMonitor::sign_to_local_justice_tx`], [`TrustedCommitmentTransaction::revokeable_output_index`],
/// [`TrustedCommitmentTransaction::build_to_local_justice_tx`].
///
/// [`TrustedCommitmentTransaction::revokeable_output_index`]: crate::ln::chan_utils::TrustedCommitmentTransaction::revokeable_output_index
/// [`TrustedCommitmentTransaction::build_to_local_justice_tx`]: crate::ln::chan_utils::TrustedCommitmentTransaction::build_to_local_justice_tx
pub trait Persist<ChannelSigner: WriteableEcdsaChannelSigner> {
	/// Persist a new channel's data in response to a [`chain::Watch::watch_channel`] call. This is
	/// called by [`ChannelManager`] for new channels, or may be called directly, e.g. on startup.
	///
	/// The data can be stored any way you want, but the identifier provided by LDK is the
	/// channel's outpoint (and it is up to you to maintain a correct mapping between the outpoint
	/// and the stored channel data). Note that you **must** persist every new monitor to disk.
	///
	/// The `update_id` is used to identify this call to [`ChainMonitor::channel_monitor_updated`],
	/// if you return [`ChannelMonitorUpdateStatus::InProgress`].
	///
	/// See [`Writeable::write`] on [`ChannelMonitor`] for writing out a `ChannelMonitor`
	/// and [`ChannelMonitorUpdateStatus`] for requirements when returning errors.
	///
	/// [`ChannelManager`]: crate::ln::channelmanager::ChannelManager
	/// [`Writeable::write`]: crate::util::ser::Writeable::write
	fn persist_new_channel(&self, channel_id: OutPoint, data: &ChannelMonitor<ChannelSigner>, update_id: MonitorUpdateId) -> ChannelMonitorUpdateStatus;

	/// Update one channel's data. The provided [`ChannelMonitor`] has already applied the given
	/// update.
	///
	/// Note that on every update, you **must** persist either the [`ChannelMonitorUpdate`] or the
	/// updated monitor itself to disk/backups. See the [`Persist`] trait documentation for more
	/// details.
	///
	/// During blockchain synchronization operations, and in some rare cases, this may be called with
	/// no [`ChannelMonitorUpdate`], in which case the full [`ChannelMonitor`] needs to be persisted.
	/// Note that after the full [`ChannelMonitor`] is persisted any previous
	/// [`ChannelMonitorUpdate`]s which were persisted should be discarded - they can no longer be
	/// applied to the persisted [`ChannelMonitor`] as they were already applied.
	///
	/// If an implementer chooses to persist the updates only, they need to make
	/// sure that all the updates are applied to the `ChannelMonitors` *before*
	/// the set of channel monitors is given to the `ChannelManager`
	/// deserialization routine. See [`ChannelMonitor::update_monitor`] for
	/// applying a monitor update to a monitor. If full `ChannelMonitors` are
	/// persisted, then there is no need to persist individual updates.
	///
	/// Note that there could be a performance tradeoff between persisting complete
	/// channel monitors on every update vs. persisting only updates and applying
	/// them in batches. The size of each monitor grows `O(number of state updates)`
	/// whereas updates are small and `O(1)`.
	///
	/// The `update_id` is used to identify this call to [`ChainMonitor::channel_monitor_updated`],
	/// if you return [`ChannelMonitorUpdateStatus::InProgress`].
	///
	/// See [`Writeable::write`] on [`ChannelMonitor`] for writing out a `ChannelMonitor`,
	/// [`Writeable::write`] on [`ChannelMonitorUpdate`] for writing out an update, and
	/// [`ChannelMonitorUpdateStatus`] for requirements when returning errors.
	///
	/// [`Writeable::write`]: crate::util::ser::Writeable::write
	fn update_persisted_channel(&self, channel_id: OutPoint, update: Option<&ChannelMonitorUpdate>, data: &ChannelMonitor<ChannelSigner>, update_id: MonitorUpdateId) -> ChannelMonitorUpdateStatus;
}

struct MonitorHolder<ChannelSigner: WriteableEcdsaChannelSigner> {
	monitor: ChannelMonitor<ChannelSigner>,
	/// The full set of pending monitor updates for this Channel.
	///
	/// Note that this lock must be held during updates to prevent a race where we call
	/// update_persisted_channel, the user returns a
	/// [`ChannelMonitorUpdateStatus::InProgress`], and then calls channel_monitor_updated
	/// immediately, racing our insertion of the pending update into the contained Vec.
	///
	/// Beyond the synchronization of updates themselves, we cannot handle user events until after
	/// any chain updates have been stored on disk. Thus, we scan this list when returning updates
	/// to the ChannelManager, refusing to return any updates for a ChannelMonitor which is still
	/// being persisted fully to disk after a chain update.
	///
	/// This avoids the possibility of handling, e.g. an on-chain claim, generating a claim monitor
	/// event, resulting in the relevant ChannelManager generating a PaymentSent event and dropping
	/// the pending payment entry, and then reloading before the monitor is persisted, resulting in
	/// the ChannelManager re-adding the same payment entry, before the same block is replayed,
	/// resulting in a duplicate PaymentSent event.
	pending_monitor_updates: Mutex<Vec<MonitorUpdateId>>,
	/// The last block height at which no [`UpdateOrigin::ChainSync`] monitor updates were present
	/// in `pending_monitor_updates`.
	/// If it's been more than [`LATENCY_GRACE_PERIOD_BLOCKS`] since we started waiting on a chain
	/// sync event, we let monitor events return to `ChannelManager` because we cannot hold them up
	/// forever or we'll end up with HTLC preimages waiting to feed back into an upstream channel
	/// forever, risking funds loss.
	last_chain_persist_height: AtomicUsize,
}

impl<ChannelSigner: WriteableEcdsaChannelSigner> MonitorHolder<ChannelSigner> {
	fn has_pending_offchain_updates(&self, pending_monitor_updates_lock: &MutexGuard<Vec<MonitorUpdateId>>) -> bool {
		pending_monitor_updates_lock.iter().any(|update_id|
			if let UpdateOrigin::OffChain(_) = update_id.contents { true } else { false })
	}
	fn has_pending_chainsync_updates(&self, pending_monitor_updates_lock: &MutexGuard<Vec<MonitorUpdateId>>) -> bool {
		pending_monitor_updates_lock.iter().any(|update_id|
			if let UpdateOrigin::ChainSync(_) = update_id.contents { true } else { false })
	}
}

/// A read-only reference to a current ChannelMonitor.
///
/// Note that this holds a mutex in [`ChainMonitor`] and may block other events until it is
/// released.
pub struct LockedChannelMonitor<'a, ChannelSigner: WriteableEcdsaChannelSigner> {
	lock: RwLockReadGuard<'a, HashMap<OutPoint, MonitorHolder<ChannelSigner>>>,
	funding_txo: OutPoint,
}

impl<ChannelSigner: WriteableEcdsaChannelSigner> Deref for LockedChannelMonitor<'_, ChannelSigner> {
	type Target = ChannelMonitor<ChannelSigner>;
	fn deref(&self) -> &ChannelMonitor<ChannelSigner> {
		&self.lock.get(&self.funding_txo).expect("Checked at construction").monitor
	}
}

/// An implementation of [`chain::Watch`] for monitoring channels.
///
/// Connected and disconnected blocks must be provided to `ChainMonitor` as documented by
/// [`chain::Watch`]. May be used in conjunction with [`ChannelManager`] to monitor channels locally
/// or used independently to monitor channels remotely. See the [module-level documentation] for
/// details.
///
/// Note that `ChainMonitor` should regularly trigger rebroadcasts/fee bumps of pending claims from
/// a force-closed channel. This is crucial in preventing certain classes of pinning attacks,
/// detecting substantial mempool feerate changes between blocks, and ensuring reliability if
/// broadcasting fails. We recommend invoking this every 30 seconds, or lower if running in an
/// environment with spotty connections, like on mobile.
///
/// [`ChannelManager`]: crate::ln::channelmanager::ChannelManager
/// [module-level documentation]: crate::chain::chainmonitor
/// [`rebroadcast_pending_claims`]: Self::rebroadcast_pending_claims
pub struct ChainMonitor<ChannelSigner: WriteableEcdsaChannelSigner, C: Deref, T: Deref, F: Deref, L: Deref, P: Deref>
	where C::Target: chain::Filter,
        T::Target: BroadcasterInterface,
        F::Target: FeeEstimator,
        L::Target: Logger,
        P::Target: Persist<ChannelSigner>,
{
	monitors: RwLock<HashMap<OutPoint, MonitorHolder<ChannelSigner>>>,
	/// When we generate a [`MonitorUpdateId`] for a chain-event monitor persistence, we need a
	/// unique ID, which we calculate by simply getting the next value from this counter. Note that
	/// the ID is never persisted so it's ok that they reset on restart.
	sync_persistence_id: AtomicCounter,
	chain_source: Option<C>,
	broadcaster: T,
	logger: L,
	fee_estimator: F,
	persister: P,
	/// "User-provided" (ie persistence-completion/-failed) [`MonitorEvent`]s. These came directly
	/// from the user and not from a [`ChannelMonitor`].
	pending_monitor_events: Mutex<Vec<(OutPoint, Vec<MonitorEvent>, Option<PublicKey>)>>,
	/// The best block height seen, used as a proxy for the passage of time.
	highest_chain_height: AtomicUsize,

	event_notifier: Notifier,
}

impl<ChannelSigner: WriteableEcdsaChannelSigner, C: Deref, T: Deref, F: Deref, L: Deref, P: Deref> ChainMonitor<ChannelSigner, C, T, F, L, P>
where C::Target: chain::Filter,
	    T::Target: BroadcasterInterface,
	    F::Target: FeeEstimator,
	    L::Target: Logger,
	    P::Target: Persist<ChannelSigner>,
{
	/// Dispatches to per-channel monitors, which are responsible for updating their on-chain view
	/// of a channel and reacting accordingly based on transactions in the given chain data. See
	/// [`ChannelMonitor::block_connected`] for details. Any HTLCs that were resolved on chain will
	/// be returned by [`chain::Watch::release_pending_monitor_events`].
	///
	/// Calls back to [`chain::Filter`] if any monitor indicated new outputs to watch. Subsequent
	/// calls must not exclude any transactions matching the new outputs nor any in-block
	/// descendants of such transactions. It is not necessary to re-fetch the block to obtain
	/// updated `txdata`.
	///
	/// Calls which represent a new blockchain tip height should set `best_height`.
	fn process_chain_data<FN>(&self, header: &Header, best_height: Option<u32>, txdata: &TransactionData, process: FN)
	where
		FN: Fn(&ChannelMonitor<ChannelSigner>, &TransactionData) -> Vec<TransactionOutputs>
	{
		let err_str = "ChannelMonitor[Update] persistence failed unrecoverably. This indicates we cannot continue normal operation and must shut down.";
		let funding_outpoints: HashSet<OutPoint> = HashSet::from_iter(self.monitors.read().unwrap().keys().cloned());
		for funding_outpoint in funding_outpoints.iter() {
			let monitor_lock = self.monitors.read().unwrap();
			if let Some(monitor_state) = monitor_lock.get(funding_outpoint) {
				if self.update_monitor_with_chain_data(header, best_height, txdata, &process, funding_outpoint, &monitor_state).is_err() {
					// Take the monitors lock for writing so that we poison it and any future
					// operations going forward fail immediately.
					core::mem::drop(monitor_lock);
					let _poison = self.monitors.write().unwrap();
					log_error!(self.logger, "{}", err_str);
					panic!("{}", err_str);
				}
			}
		}

		// do some followup cleanup if any funding outpoints were added in between iterations
		let monitor_states = self.monitors.write().unwrap();
		for (funding_outpoint, monitor_state) in monitor_states.iter() {
			if !funding_outpoints.contains(funding_outpoint) {
				if self.update_monitor_with_chain_data(header, best_height, txdata, &process, funding_outpoint, &monitor_state).is_err() {
					log_error!(self.logger, "{}", err_str);
					panic!("{}", err_str);
				}
			}
		}

		if let Some(height) = best_height {
			// If the best block height is being updated, update highest_chain_height under the
			// monitors write lock.
			let old_height = self.highest_chain_height.load(Ordering::Acquire);
			let new_height = height as usize;
			if new_height > old_height {
				self.highest_chain_height.store(new_height, Ordering::Release);
			}
		}
	}

	fn update_monitor_with_chain_data<FN>(
		&self, header: &Header, best_height: Option<u32>, txdata: &TransactionData,
		process: FN, funding_outpoint: &OutPoint, monitor_state: &MonitorHolder<ChannelSigner>
	) -> Result<(), ()> where FN: Fn(&ChannelMonitor<ChannelSigner>, &TransactionData) -> Vec<TransactionOutputs> {
		let monitor = &monitor_state.monitor;
		let logger = WithChannelMonitor::from(&self.logger, &monitor);
		let mut txn_outputs;
		{
			txn_outputs = process(monitor, txdata);
			let update_id = MonitorUpdateId {
				contents: UpdateOrigin::ChainSync(self.sync_persistence_id.get_increment()),
			};
			let mut pending_monitor_updates = monitor_state.pending_monitor_updates.lock().unwrap();
			if let Some(height) = best_height {
				if !monitor_state.has_pending_chainsync_updates(&pending_monitor_updates) {
					// If there are not ChainSync persists awaiting completion, go ahead and
					// set last_chain_persist_height here - we wouldn't want the first
					// InProgress to always immediately be considered "overly delayed".
					monitor_state.last_chain_persist_height.store(height as usize, Ordering::Release);
				}
			}

			log_trace!(logger, "Syncing Channel Monitor for channel {}", log_funding_info!(monitor));
			match self.persister.update_persisted_channel(*funding_outpoint, None, monitor, update_id) {
				ChannelMonitorUpdateStatus::Completed =>
					log_trace!(logger, "Finished syncing Channel Monitor for channel {}", log_funding_info!(monitor)),
				ChannelMonitorUpdateStatus::InProgress => {
					log_debug!(logger, "Channel Monitor sync for channel {} in progress, holding events until completion!", log_funding_info!(monitor));
					pending_monitor_updates.push(update_id);
				},
				ChannelMonitorUpdateStatus::UnrecoverableError => {
					return Err(());
				},
			}
		}

		// Register any new outputs with the chain source for filtering, storing any dependent
		// transactions from within the block that previously had not been included in txdata.
		if let Some(ref chain_source) = self.chain_source {
			let block_hash = header.block_hash();
			for (txid, mut outputs) in txn_outputs.drain(..) {
				for (idx, output) in outputs.drain(..) {
					// Register any new outputs with the chain source for filtering
					let output = WatchedOutput {
						block_hash: Some(block_hash),
						outpoint: OutPoint { txid, index: idx as u16 },
						script_pubkey: output.script_pubkey,
					};
					log_trace!(logger, "Adding monitoring for spends of outpoint {} to the filter", output.outpoint);
					chain_source.register_output(output);
				}
			}
		}
		Ok(())
	}

	/// Creates a new `ChainMonitor` used to watch on-chain activity pertaining to channels.
	///
	/// When an optional chain source implementing [`chain::Filter`] is provided, the chain monitor
	/// will call back to it indicating transactions and outputs of interest. This allows clients to
	/// pre-filter blocks or only fetch blocks matching a compact filter. Otherwise, clients may
	/// always need to fetch full blocks absent another means for determining which blocks contain
	/// transactions relevant to the watched channels.
	pub fn new(chain_source: Option<C>, broadcaster: T, logger: L, feeest: F, persister: P) -> Self {
		Self {
			monitors: RwLock::new(HashMap::new()),
			sync_persistence_id: AtomicCounter::new(),
			chain_source,
			broadcaster,
			logger,
			fee_estimator: feeest,
			persister,
			pending_monitor_events: Mutex::new(Vec::new()),
			highest_chain_height: AtomicUsize::new(0),
			event_notifier: Notifier::new(),
		}
	}

	/// Gets the balances in the contained [`ChannelMonitor`]s which are claimable on-chain or
	/// claims which are awaiting confirmation.
	///
	/// Includes the balances from each [`ChannelMonitor`] *except* those included in
	/// `ignored_channels`, allowing you to filter out balances from channels which are still open
	/// (and whose balance should likely be pulled from the [`ChannelDetails`]).
	///
	/// See [`ChannelMonitor::get_claimable_balances`] for more details on the exact criteria for
	/// inclusion in the return value.
	pub fn get_claimable_balances(&self, ignored_channels: &[&ChannelDetails]) -> Vec<Balance> {
		let mut ret = Vec::new();
		let monitor_states = self.monitors.read().unwrap();
		for (_, monitor_state) in monitor_states.iter().filter(|(funding_outpoint, _)| {
			for chan in ignored_channels {
				if chan.funding_txo.as_ref() == Some(funding_outpoint) {
					return false;
				}
			}
			true
		}) {
			ret.append(&mut monitor_state.monitor.get_claimable_balances());
		}
		ret
	}

	/// Gets the [`LockedChannelMonitor`] for a given funding outpoint, returning an `Err` if no
	/// such [`ChannelMonitor`] is currently being monitored for.
	///
	/// Note that the result holds a mutex over our monitor set, and should not be held
	/// indefinitely.
	pub fn get_monitor(&self, funding_txo: OutPoint) -> Result<LockedChannelMonitor<'_, ChannelSigner>, ()> {
		let lock = self.monitors.read().unwrap();
		if lock.get(&funding_txo).is_some() {
			Ok(LockedChannelMonitor { lock, funding_txo })
		} else {
			Err(())
		}
	}

	/// Lists the funding outpoint of each [`ChannelMonitor`] being monitored.
	///
	/// Note that [`ChannelMonitor`]s are not removed when a channel is closed as they are always
	/// monitoring for on-chain state resolutions.
	pub fn list_monitors(&self) -> Vec<OutPoint> {
		self.monitors.read().unwrap().keys().map(|outpoint| *outpoint).collect()
	}

	#[cfg(not(c_bindings))]
	/// Lists the pending updates for each [`ChannelMonitor`] (by `OutPoint` being monitored).
	pub fn list_pending_monitor_updates(&self) -> HashMap<OutPoint, Vec<MonitorUpdateId>> {
		self.monitors.read().unwrap().iter().map(|(outpoint, holder)| {
			(*outpoint, holder.pending_monitor_updates.lock().unwrap().clone())
		}).collect()
	}

	#[cfg(c_bindings)]
	/// Lists the pending updates for each [`ChannelMonitor`] (by `OutPoint` being monitored).
	pub fn list_pending_monitor_updates(&self) -> Vec<(OutPoint, Vec<MonitorUpdateId>)> {
		self.monitors.read().unwrap().iter().map(|(outpoint, holder)| {
			(*outpoint, holder.pending_monitor_updates.lock().unwrap().clone())
		}).collect()
	}


	#[cfg(test)]
	pub fn remove_monitor(&self, funding_txo: &OutPoint) -> ChannelMonitor<ChannelSigner> {
		self.monitors.write().unwrap().remove(funding_txo).unwrap().monitor
	}

	/// Indicates the persistence of a [`ChannelMonitor`] has completed after
	/// [`ChannelMonitorUpdateStatus::InProgress`] was returned from an update operation.
	///
	/// Thus, the anticipated use is, at a high level:
	///  1) This [`ChainMonitor`] calls [`Persist::update_persisted_channel`] which stores the
	///     update to disk and begins updating any remote (e.g. watchtower/backup) copies,
	///     returning [`ChannelMonitorUpdateStatus::InProgress`],
	///  2) once all remote copies are updated, you call this function with the
	///     `completed_update_id` that completed, and once all pending updates have completed the
	///     channel will be re-enabled.
	//      Note that we re-enable only after `UpdateOrigin::OffChain` updates complete, we don't
	//      care about `UpdateOrigin::ChainSync` updates for the channel state being updated. We
	//      only care about `UpdateOrigin::ChainSync` for returning `MonitorEvent`s.
	///
	/// Returns an [`APIError::APIMisuseError`] if `funding_txo` does not match any currently
	/// registered [`ChannelMonitor`]s.
	pub fn channel_monitor_updated(&self, funding_txo: OutPoint, completed_update_id: MonitorUpdateId) -> Result<(), APIError> {
		let monitors = self.monitors.read().unwrap();
		let monitor_data = if let Some(mon) = monitors.get(&funding_txo) { mon } else {
			return Err(APIError::APIMisuseError { err: format!("No ChannelMonitor matching funding outpoint {:?} found", funding_txo) });
		};
		let mut pending_monitor_updates = monitor_data.pending_monitor_updates.lock().unwrap();
		pending_monitor_updates.retain(|update_id| *update_id != completed_update_id);

		match completed_update_id {
			MonitorUpdateId { contents: UpdateOrigin::OffChain(_) } => {
				// Note that we only check for `UpdateOrigin::OffChain` failures here - if
				// we're being told that a `UpdateOrigin::OffChain` monitor update completed,
				// we only care about ensuring we don't tell the `ChannelManager` to restore
				// the channel to normal operation until all `UpdateOrigin::OffChain` updates
				// complete.
				// If there's some `UpdateOrigin::ChainSync` update still pending that's okay
				// - we can still update our channel state, just as long as we don't return
				// `MonitorEvent`s from the monitor back to the `ChannelManager` until they
				// complete.
				let monitor_is_pending_updates = monitor_data.has_pending_offchain_updates(&pending_monitor_updates);
				if monitor_is_pending_updates {
					// If there are still monitor updates pending, we cannot yet construct a
					// Completed event.
					return Ok(());
				}
				self.pending_monitor_events.lock().unwrap().push((funding_txo, vec![MonitorEvent::Completed {
					funding_txo,
					monitor_update_id: monitor_data.monitor.get_latest_update_id(),
				}], monitor_data.monitor.get_counterparty_node_id()));
			},
			MonitorUpdateId { contents: UpdateOrigin::ChainSync(_) } => {
				if !monitor_data.has_pending_chainsync_updates(&pending_monitor_updates) {
					monitor_data.last_chain_persist_height.store(self.highest_chain_height.load(Ordering::Acquire), Ordering::Release);
					// The next time release_pending_monitor_events is called, any events for this
					// ChannelMonitor will be returned.
				}
			},
		}
		self.event_notifier.notify();
		Ok(())
	}

	/// This wrapper avoids having to update some of our tests for now as they assume the direct
	/// chain::Watch API wherein we mark a monitor fully-updated by just calling
	/// channel_monitor_updated once with the highest ID.
	#[cfg(any(test, fuzzing))]
	pub fn force_channel_monitor_updated(&self, funding_txo: OutPoint, monitor_update_id: u64) {
		let monitors = self.monitors.read().unwrap();
		let counterparty_node_id = monitors.get(&funding_txo).and_then(|m| m.monitor.get_counterparty_node_id());
		self.pending_monitor_events.lock().unwrap().push((funding_txo, vec![MonitorEvent::Completed {
			funding_txo,
			monitor_update_id,
		}], counterparty_node_id));
		self.event_notifier.notify();
	}

	#[cfg(any(test, feature = "_test_utils"))]
	pub fn get_and_clear_pending_events(&self) -> Vec<events::Event> {
		use crate::events::EventsProvider;
		let events = core::cell::RefCell::new(Vec::new());
		let event_handler = |event: events::Event| events.borrow_mut().push(event);
		self.process_pending_events(&event_handler);
		events.into_inner()
	}

	/// Processes any events asynchronously in the order they were generated since the last call
	/// using the given event handler.
	///
	/// See the trait-level documentation of [`EventsProvider`] for requirements.
	///
	/// [`EventsProvider`]: crate::events::EventsProvider
	pub async fn process_pending_events_async<Future: core::future::Future, H: Fn(Event) -> Future>(
		&self, handler: H
	) {
		// Sadly we can't hold the monitors read lock through an async call. Thus we have to do a
		// crazy dance to process a monitor's events then only remove them once we've done so.
		let mons_to_process = self.monitors.read().unwrap().keys().cloned().collect::<Vec<_>>();
		for funding_txo in mons_to_process {
			let mut ev;
			super::channelmonitor::process_events_body!(
				self.monitors.read().unwrap().get(&funding_txo).map(|m| &m.monitor), ev, handler(ev).await);
		}
	}

	/// Gets a [`Future`] that completes when an event is available either via
	/// [`chain::Watch::release_pending_monitor_events`] or
	/// [`EventsProvider::process_pending_events`].
	///
	/// Note that callbacks registered on the [`Future`] MUST NOT call back into this
	/// [`ChainMonitor`] and should instead register actions to be taken later.
	///
	/// [`EventsProvider::process_pending_events`]: crate::events::EventsProvider::process_pending_events
	pub fn get_update_future(&self) -> Future {
		self.event_notifier.get_future()
	}

	/// Triggers rebroadcasts/fee-bumps of pending claims from a force-closed channel. This is
	/// crucial in preventing certain classes of pinning attacks, detecting substantial mempool
	/// feerate changes between blocks, and ensuring reliability if broadcasting fails. We recommend
	/// invoking this every 30 seconds, or lower if running in an environment with spotty
	/// connections, like on mobile.
	pub fn rebroadcast_pending_claims(&self) {
		let monitors = self.monitors.read().unwrap();
		for (_, monitor_holder) in &*monitors {
			monitor_holder.monitor.rebroadcast_pending_claims(
				&*self.broadcaster, &*self.fee_estimator, &self.logger
			)
		}
	}
}

impl<ChannelSigner: WriteableEcdsaChannelSigner, C: Deref, T: Deref, F: Deref, L: Deref, P: Deref>
chain::Listen for ChainMonitor<ChannelSigner, C, T, F, L, P>
where
	C::Target: chain::Filter,
	T::Target: BroadcasterInterface,
	F::Target: FeeEstimator,
	L::Target: Logger,
	P::Target: Persist<ChannelSigner>,
{
	fn filtered_block_connected(&self, header: &Header, txdata: &TransactionData, height: u32) {
		log_debug!(self.logger, "New best block {} at height {} provided via block_connected", header.block_hash(), height);
		self.process_chain_data(header, Some(height), &txdata, |monitor, txdata| {
			monitor.block_connected(
				header, txdata, height, &*self.broadcaster, &*self.fee_estimator, &self.logger)
		});
	}

	fn block_disconnected(&self, header: &Header, height: u32) {
		let monitor_states = self.monitors.read().unwrap();
		log_debug!(self.logger, "Latest block {} at height {} removed via block_disconnected", header.block_hash(), height);
		for monitor_state in monitor_states.values() {
			monitor_state.monitor.block_disconnected(
				header, height, &*self.broadcaster, &*self.fee_estimator, &self.logger);
		}
	}
}

impl<ChannelSigner: WriteableEcdsaChannelSigner, C: Deref, T: Deref, F: Deref, L: Deref, P: Deref>
chain::Confirm for ChainMonitor<ChannelSigner, C, T, F, L, P>
where
	C::Target: chain::Filter,
	T::Target: BroadcasterInterface,
	F::Target: FeeEstimator,
	L::Target: Logger,
	P::Target: Persist<ChannelSigner>,
{
	fn transactions_confirmed(&self, header: &Header, txdata: &TransactionData, height: u32) {
		log_debug!(self.logger, "{} provided transactions confirmed at height {} in block {}", txdata.len(), height, header.block_hash());
		self.process_chain_data(header, None, txdata, |monitor, txdata| {
			monitor.transactions_confirmed(
				header, txdata, height, &*self.broadcaster, &*self.fee_estimator, &self.logger)
		});
	}

	fn transaction_unconfirmed(&self, txid: &Txid) {
		log_debug!(self.logger, "Transaction {} reorganized out of chain", txid);
		let monitor_states = self.monitors.read().unwrap();
		for monitor_state in monitor_states.values() {
			monitor_state.monitor.transaction_unconfirmed(txid, &*self.broadcaster, &*self.fee_estimator, &self.logger);
		}
	}

	fn best_block_updated(&self, header: &Header, height: u32) {
		log_debug!(self.logger, "New best block {} at height {} provided via best_block_updated", header.block_hash(), height);
		self.process_chain_data(header, Some(height), &[], |monitor, txdata| {
			// While in practice there shouldn't be any recursive calls when given empty txdata,
			// it's still possible if a chain::Filter implementation returns a transaction.
			debug_assert!(txdata.is_empty());
			monitor.best_block_updated(
				header, height, &*self.broadcaster, &*self.fee_estimator, &self.logger
			)
		});
	}

	fn get_relevant_txids(&self) -> Vec<(Txid, u32, Option<BlockHash>)> {
		let mut txids = Vec::new();
		let monitor_states = self.monitors.read().unwrap();
		for monitor_state in monitor_states.values() {
			txids.append(&mut monitor_state.monitor.get_relevant_txids());
		}

		txids.sort_unstable_by(|a, b| a.0.cmp(&b.0).then(b.1.cmp(&a.1)));
		txids.dedup_by_key(|(txid, _, _)| *txid);
		txids
	}
}

impl<ChannelSigner: WriteableEcdsaChannelSigner, C: Deref , T: Deref , F: Deref , L: Deref , P: Deref >
chain::Watch<ChannelSigner> for ChainMonitor<ChannelSigner, C, T, F, L, P>
where C::Target: chain::Filter,
	    T::Target: BroadcasterInterface,
	    F::Target: FeeEstimator,
	    L::Target: Logger,
	    P::Target: Persist<ChannelSigner>,
{
	fn watch_channel(&self, funding_outpoint: OutPoint, monitor: ChannelMonitor<ChannelSigner>) -> Result<ChannelMonitorUpdateStatus, ()> {
		let logger = WithChannelMonitor::from(&self.logger, &monitor);
		let mut monitors = self.monitors.write().unwrap();
		let entry = match monitors.entry(funding_outpoint) {
			hash_map::Entry::Occupied(_) => {
				log_error!(logger, "Failed to add new channel data: channel monitor for given outpoint is already present");
				return Err(());
			},
			hash_map::Entry::Vacant(e) => e,
		};
		log_trace!(logger, "Got new ChannelMonitor for channel {}", log_funding_info!(monitor));
		let update_id = MonitorUpdateId::from_new_monitor(&monitor);
		let mut pending_monitor_updates = Vec::new();
		let persist_res = self.persister.persist_new_channel(funding_outpoint, &monitor, update_id);
		match persist_res {
			ChannelMonitorUpdateStatus::InProgress => {
				log_info!(logger, "Persistence of new ChannelMonitor for channel {} in progress", log_funding_info!(monitor));
				pending_monitor_updates.push(update_id);
			},
			ChannelMonitorUpdateStatus::Completed => {
				log_info!(logger, "Persistence of new ChannelMonitor for channel {} completed", log_funding_info!(monitor));
			},
			ChannelMonitorUpdateStatus::UnrecoverableError => {
				let err_str = "ChannelMonitor[Update] persistence failed unrecoverably. This indicates we cannot continue normal operation and must shut down.";
				log_error!(logger, "{}", err_str);
				panic!("{}", err_str);
			},
		}
		if let Some(ref chain_source) = self.chain_source {
			monitor.load_outputs_to_watch(chain_source , &self.logger);
		}
		entry.insert(MonitorHolder {
			monitor,
			pending_monitor_updates: Mutex::new(pending_monitor_updates),
			last_chain_persist_height: AtomicUsize::new(self.highest_chain_height.load(Ordering::Acquire)),
		});
		Ok(persist_res)
	}

	fn update_channel(&self, funding_txo: OutPoint, update: &ChannelMonitorUpdate) -> ChannelMonitorUpdateStatus {
		// Update the monitor that watches the channel referred to by the given outpoint.
		let monitors = self.monitors.read().unwrap();
		match monitors.get(&funding_txo) {
			None => {
				let logger = WithContext::from(&self.logger, update.counterparty_node_id, Some(funding_txo.to_channel_id()));
				log_error!(logger, "Failed to update channel monitor: no such monitor registered");

				// We should never ever trigger this from within ChannelManager. Technically a
				// user could use this object with some proxying in between which makes this
				// possible, but in tests and fuzzing, this should be a panic.
				#[cfg(debug_assertions)]
				panic!("ChannelManager generated a channel update for a channel that was not yet registered!");
				#[cfg(not(debug_assertions))]
				ChannelMonitorUpdateStatus::InProgress
			},
			Some(monitor_state) => {
				let monitor = &monitor_state.monitor;
				let logger = WithChannelMonitor::from(&self.logger, &monitor);
				log_trace!(logger, "Updating ChannelMonitor for channel {}", log_funding_info!(monitor));
				let update_res = monitor.update_monitor(update, &self.broadcaster, &self.fee_estimator, &self.logger);

				let update_id = MonitorUpdateId::from_monitor_update(update);
				let mut pending_monitor_updates = monitor_state.pending_monitor_updates.lock().unwrap();
				let persist_res = if update_res.is_err() {
					// Even if updating the monitor returns an error, the monitor's state will
					// still be changed. Therefore, we should persist the updated monitor despite the error.
					// We don't want to persist a `monitor_update` which results in a failure to apply later
					// while reading `channel_monitor` with updates from storage. Instead, we should persist
					// the entire `channel_monitor` here.
					log_warn!(logger, "Failed to update ChannelMonitor for channel {}. Going ahead and persisting the entire ChannelMonitor", log_funding_info!(monitor));
					self.persister.update_persisted_channel(funding_txo, None, monitor, update_id)
				} else {
					self.persister.update_persisted_channel(funding_txo, Some(update), monitor, update_id)
				};
				match persist_res {
					ChannelMonitorUpdateStatus::InProgress => {
						pending_monitor_updates.push(update_id);
						log_debug!(logger, "Persistence of ChannelMonitorUpdate for channel {} in progress", log_funding_info!(monitor));
					},
					ChannelMonitorUpdateStatus::Completed => {
						log_debug!(logger, "Persistence of ChannelMonitorUpdate for channel {} completed", log_funding_info!(monitor));
					},
					ChannelMonitorUpdateStatus::UnrecoverableError => {
						// Take the monitors lock for writing so that we poison it and any future
						// operations going forward fail immediately.
						core::mem::drop(pending_monitor_updates);
						core::mem::drop(monitors);
						let _poison = self.monitors.write().unwrap();
						let err_str = "ChannelMonitor[Update] persistence failed unrecoverably. This indicates we cannot continue normal operation and must shut down.";
						log_error!(logger, "{}", err_str);
						panic!("{}", err_str);
					},
				}
				if update_res.is_err() {
					ChannelMonitorUpdateStatus::InProgress
				} else {
					persist_res
				}
			}
		}
	}

	fn release_pending_monitor_events(&self) -> Vec<(OutPoint, Vec<MonitorEvent>, Option<PublicKey>)> {
		let mut pending_monitor_events = self.pending_monitor_events.lock().unwrap().split_off(0);
		for monitor_state in self.monitors.read().unwrap().values() {
			let logger = WithChannelMonitor::from(&self.logger, &monitor_state.monitor);
			let is_pending_monitor_update = monitor_state.has_pending_chainsync_updates(&monitor_state.pending_monitor_updates.lock().unwrap());
			if !is_pending_monitor_update || monitor_state.last_chain_persist_height.load(Ordering::Acquire) + LATENCY_GRACE_PERIOD_BLOCKS as usize <= self.highest_chain_height.load(Ordering::Acquire) {
				if is_pending_monitor_update {
					log_error!(logger, "A ChannelMonitor sync took longer than {} blocks to complete.", LATENCY_GRACE_PERIOD_BLOCKS);
					log_error!(logger, "   To avoid funds-loss, we are allowing monitor updates to be released.");
					log_error!(logger, "   This may cause duplicate payment events to be generated.");
				}
				let monitor_events = monitor_state.monitor.get_and_clear_pending_monitor_events();
				if monitor_events.len() > 0 {
					let monitor_outpoint = monitor_state.monitor.get_funding_txo().0;
					let counterparty_node_id = monitor_state.monitor.get_counterparty_node_id();
					pending_monitor_events.push((monitor_outpoint, monitor_events, counterparty_node_id));
				}
			}
		}
		pending_monitor_events
	}
}

impl<ChannelSigner: WriteableEcdsaChannelSigner, C: Deref, T: Deref, F: Deref, L: Deref, P: Deref> events::EventsProvider for ChainMonitor<ChannelSigner, C, T, F, L, P>
	where C::Target: chain::Filter,
	      T::Target: BroadcasterInterface,
	      F::Target: FeeEstimator,
	      L::Target: Logger,
	      P::Target: Persist<ChannelSigner>,
{
	/// Processes [`SpendableOutputs`] events produced from each [`ChannelMonitor`] upon maturity.
	///
	/// For channels featuring anchor outputs, this method will also process [`BumpTransaction`]
	/// events produced from each [`ChannelMonitor`] while there is a balance to claim onchain
	/// within each channel. As the confirmation of a commitment transaction may be critical to the
	/// safety of funds, we recommend invoking this every 30 seconds, or lower if running in an
	/// environment with spotty connections, like on mobile.
	///
	/// An [`EventHandler`] may safely call back to the provider, though this shouldn't be needed in
	/// order to handle these events.
	///
	/// [`SpendableOutputs`]: events::Event::SpendableOutputs
	/// [`BumpTransaction`]: events::Event::BumpTransaction
	fn process_pending_events<H: Deref>(&self, handler: H) where H::Target: EventHandler {
		for monitor_state in self.monitors.read().unwrap().values() {
			monitor_state.monitor.process_pending_events(&handler);
		}
	}
}

#[cfg(test)]
mod tests {
	use crate::check_added_monitors;
	use crate::{expect_payment_claimed, expect_payment_path_successful, get_event_msg};
	use crate::{get_htlc_update_msgs, get_local_commitment_txn, get_revoke_commit_msgs, get_route_and_payment_hash, unwrap_send_err};
	use crate::chain::{ChannelMonitorUpdateStatus, Confirm, Watch};
	use crate::chain::channelmonitor::LATENCY_GRACE_PERIOD_BLOCKS;
	use crate::events::{Event, MessageSendEvent, MessageSendEventsProvider};
	use crate::ln::channelmanager::{PaymentSendFailure, PaymentId, RecipientOnionFields};
	use crate::ln::functional_test_utils::*;
	use crate::ln::msgs::ChannelMessageHandler;
	use crate::util::errors::APIError;

	#[test]
	fn test_async_ooo_offchain_updates() {
		// Test that if we have multiple offchain updates being persisted and they complete
		// out-of-order, the ChainMonitor waits until all have completed before informing the
		// ChannelManager.
		let chanmon_cfgs = create_chanmon_cfgs(2);
		let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
		let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
		let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
		create_announced_chan_between_nodes(&nodes, 0, 1);

		// Route two payments to be claimed at the same time.
		let (payment_preimage_1, payment_hash_1, ..) = route_payment(&nodes[0], &[&nodes[1]], 1_000_000);
		let (payment_preimage_2, payment_hash_2, ..) = route_payment(&nodes[0], &[&nodes[1]], 1_000_000);

		chanmon_cfgs[1].persister.offchain_monitor_updates.lock().unwrap().clear();
		chanmon_cfgs[1].persister.set_update_ret(ChannelMonitorUpdateStatus::InProgress);
		chanmon_cfgs[1].persister.set_update_ret(ChannelMonitorUpdateStatus::InProgress);

		nodes[1].node.claim_funds(payment_preimage_1);
		check_added_monitors!(nodes[1], 1);
		nodes[1].node.claim_funds(payment_preimage_2);
		check_added_monitors!(nodes[1], 1);

		let persistences = chanmon_cfgs[1].persister.offchain_monitor_updates.lock().unwrap().clone();
		assert_eq!(persistences.len(), 1);
		let (funding_txo, updates) = persistences.iter().next().unwrap();
		assert_eq!(updates.len(), 2);

		// Note that updates is a HashMap so the ordering here is actually random. This shouldn't
		// fail either way but if it fails intermittently it's depending on the ordering of updates.
		let mut update_iter = updates.iter();
		let next_update = update_iter.next().unwrap().clone();
		// Should contain next_update when pending updates listed.
		#[cfg(not(c_bindings))]
		assert!(nodes[1].chain_monitor.chain_monitor.list_pending_monitor_updates().get(funding_txo)
			.unwrap().contains(&next_update));
		#[cfg(c_bindings)]
		assert!(nodes[1].chain_monitor.chain_monitor.list_pending_monitor_updates().iter()
			.find(|(txo, _)| txo == funding_txo).unwrap().1.contains(&next_update));
		nodes[1].chain_monitor.chain_monitor.channel_monitor_updated(*funding_txo, next_update.clone()).unwrap();
		// Should not contain the previously pending next_update when pending updates listed.
		#[cfg(not(c_bindings))]
		assert!(!nodes[1].chain_monitor.chain_monitor.list_pending_monitor_updates().get(funding_txo)
			.unwrap().contains(&next_update));
		#[cfg(c_bindings)]
		assert!(!nodes[1].chain_monitor.chain_monitor.list_pending_monitor_updates().iter()
			.find(|(txo, _)| txo == funding_txo).unwrap().1.contains(&next_update));
		assert!(nodes[1].chain_monitor.release_pending_monitor_events().is_empty());
		assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
		assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
		nodes[1].chain_monitor.chain_monitor.channel_monitor_updated(*funding_txo, update_iter.next().unwrap().clone()).unwrap();

		let claim_events = nodes[1].node.get_and_clear_pending_events();
		assert_eq!(claim_events.len(), 2);
		match claim_events[0] {
			Event::PaymentClaimed { ref payment_hash, amount_msat: 1_000_000, .. } => {
				assert_eq!(payment_hash_1, *payment_hash);
			},
			_ => panic!("Unexpected event"),
		}
		match claim_events[1] {
			Event::PaymentClaimed { ref payment_hash, amount_msat: 1_000_000, .. } => {
				assert_eq!(payment_hash_2, *payment_hash);
			},
			_ => panic!("Unexpected event"),
		}

		// Now manually walk the commitment signed dance - because we claimed two payments
		// back-to-back it doesn't fit into the neat walk commitment_signed_dance does.

		let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
		nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
		expect_payment_sent(&nodes[0], payment_preimage_1, None, false, false);
		nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &updates.commitment_signed);
		check_added_monitors!(nodes[0], 1);
		let (as_first_raa, as_first_update) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());

		nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_first_raa);
		check_added_monitors!(nodes[1], 1);
		let bs_second_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
		nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_first_update);
		check_added_monitors!(nodes[1], 1);
		let bs_first_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());

		nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_second_updates.update_fulfill_htlcs[0]);
		expect_payment_sent(&nodes[0], payment_preimage_2, None, false, false);
		nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_updates.commitment_signed);
		check_added_monitors!(nodes[0], 1);
		nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_first_raa);
		expect_payment_path_successful!(nodes[0]);
		check_added_monitors!(nodes[0], 1);
		let (as_second_raa, as_second_update) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());

		nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_raa);
		check_added_monitors!(nodes[1], 1);
		nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_second_update);
		check_added_monitors!(nodes[1], 1);
		let bs_second_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());

		nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_raa);
		expect_payment_path_successful!(nodes[0]);
		check_added_monitors!(nodes[0], 1);
	}

	fn do_chainsync_pauses_events(block_timeout: bool) {
		// When a chainsync monitor update occurs, any MonitorUpdates should be held before being
		// passed upstream to a `ChannelManager` via `Watch::release_pending_monitor_events`. This
		// tests that behavior, as well as some ways it might go wrong.
		let chanmon_cfgs = create_chanmon_cfgs(2);
		let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
		let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
		let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
		let channel = create_announced_chan_between_nodes(&nodes, 0, 1);

		// Get a route for later and rebalance the channel somewhat
		send_payment(&nodes[0], &[&nodes[1]], 10_000_000);
		let (route, second_payment_hash, _, second_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);

		// First route a payment that we will claim on chain and give the recipient the preimage.
		let (payment_preimage, payment_hash, ..) = route_payment(&nodes[0], &[&nodes[1]], 1_000_000);
		nodes[1].node.claim_funds(payment_preimage);
		expect_payment_claimed!(nodes[1], payment_hash, 1_000_000);
		nodes[1].node.get_and_clear_pending_msg_events();
		check_added_monitors!(nodes[1], 1);
		let remote_txn = get_local_commitment_txn!(nodes[1], channel.2);
		assert_eq!(remote_txn.len(), 2);

		// Temp-fail the block connection which will hold the channel-closed event
		chanmon_cfgs[0].persister.chain_sync_monitor_persistences.lock().unwrap().clear();
		chanmon_cfgs[0].persister.set_update_ret(ChannelMonitorUpdateStatus::InProgress);

		// Connect B's commitment transaction, but only to the ChainMonitor/ChannelMonitor. The
		// channel is now closed, but the ChannelManager doesn't know that yet.
		let new_header = create_dummy_header(nodes[0].best_block_info().0, 0);
		nodes[0].chain_monitor.chain_monitor.transactions_confirmed(&new_header,
			&[(0, &remote_txn[0]), (1, &remote_txn[1])], nodes[0].best_block_info().1 + 1);
		assert!(nodes[0].chain_monitor.release_pending_monitor_events().is_empty());
		nodes[0].chain_monitor.chain_monitor.best_block_updated(&new_header, nodes[0].best_block_info().1 + 1);
		assert!(nodes[0].chain_monitor.release_pending_monitor_events().is_empty());

		// If the ChannelManager tries to update the channel, however, the ChainMonitor will pass
		// the update through to the ChannelMonitor which will refuse it (as the channel is closed).
		chanmon_cfgs[0].persister.set_update_ret(ChannelMonitorUpdateStatus::Completed);
		unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, second_payment_hash,
				RecipientOnionFields::secret_only(second_payment_secret), PaymentId(second_payment_hash.0)
			), false, APIError::MonitorUpdateInProgress, {});
		check_added_monitors!(nodes[0], 1);

		// However, as the ChainMonitor is still waiting for the original persistence to complete,
		// it won't yet release the MonitorEvents.
		assert!(nodes[0].chain_monitor.release_pending_monitor_events().is_empty());

		if block_timeout {
			// After three blocks, pending MontiorEvents should be released either way.
			let latest_header = create_dummy_header(nodes[0].best_block_info().0, 0);
			nodes[0].chain_monitor.chain_monitor.best_block_updated(&latest_header, nodes[0].best_block_info().1 + LATENCY_GRACE_PERIOD_BLOCKS);
		} else {
			let persistences = chanmon_cfgs[0].persister.chain_sync_monitor_persistences.lock().unwrap().clone();
			for (funding_outpoint, update_ids) in persistences {
				for update_id in update_ids {
					nodes[0].chain_monitor.chain_monitor.channel_monitor_updated(funding_outpoint, update_id).unwrap();
				}
			}
		}

		expect_payment_sent(&nodes[0], payment_preimage, None, true, false);
	}

	#[test]
	fn chainsync_pauses_events() {
		do_chainsync_pauses_events(false);
		do_chainsync_pauses_events(true);
	}

	#[test]
	#[cfg(feature = "std")]
	fn update_during_chainsync_poisons_channel() {
		let chanmon_cfgs = create_chanmon_cfgs(2);
		let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
		let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
		let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
		create_announced_chan_between_nodes(&nodes, 0, 1);

		chanmon_cfgs[0].persister.chain_sync_monitor_persistences.lock().unwrap().clear();
		chanmon_cfgs[0].persister.set_update_ret(ChannelMonitorUpdateStatus::UnrecoverableError);

		assert!(std::panic::catch_unwind(|| {
			// Returning an UnrecoverableError should always panic immediately
			connect_blocks(&nodes[0], 1);
		}).is_err());
		assert!(std::panic::catch_unwind(|| {
			// ...and also poison our locks causing later use to panic as well
			core::mem::drop(nodes);
		}).is_err());
	}
}