@@ -34,11 +34,13 @@ use crate::chain::transaction::{OutPoint, TransactionData};
34
34
use crate :: ln:: types:: ChannelId ;
35
35
use crate :: sign:: ecdsa:: EcdsaChannelSigner ;
36
36
use crate :: events:: { self , Event , EventHandler , ReplayEvent } ;
37
+ use crate :: util:: async_poll:: { poll_or_spawn, AsyncResult , FutureSpawner } ;
37
38
use crate :: util:: logger:: { Logger , WithContext } ;
38
39
use crate :: util:: errors:: APIError ;
39
40
use crate :: util:: persist:: MonitorName ;
40
41
use crate :: util:: wakers:: { Future , Notifier } ;
41
42
use crate :: ln:: channel_state:: ChannelDetails ;
43
+ use crate :: sync:: { Arc } ;
42
44
43
45
use crate :: prelude:: * ;
44
46
use crate :: sync:: { RwLock , RwLockReadGuard , Mutex , MutexGuard } ;
@@ -120,7 +122,7 @@ pub trait Persist<ChannelSigner: EcdsaChannelSigner> {
120
122
///
121
123
/// [`ChannelManager`]: crate::ln::channelmanager::ChannelManager
122
124
/// [`Writeable::write`]: crate::util::ser::Writeable::write
123
- fn persist_new_channel ( & self , monitor_name : MonitorName , monitor : & ChannelMonitor < ChannelSigner > ) -> ChannelMonitorUpdateStatus ;
125
+ fn persist_new_channel ( & self , monitor_name : MonitorName , monitor : & ChannelMonitor < ChannelSigner > ) -> AsyncResult < ' static , ( ) > ;
124
126
125
127
/// Update one channel's data. The provided [`ChannelMonitor`] has already applied the given
126
128
/// update.
@@ -159,7 +161,7 @@ pub trait Persist<ChannelSigner: EcdsaChannelSigner> {
159
161
/// [`ChannelMonitorUpdateStatus`] for requirements when returning errors.
160
162
///
161
163
/// [`Writeable::write`]: crate::util::ser::Writeable::write
162
- fn update_persisted_channel ( & self , monitor_name : MonitorName , monitor_update : Option < & ChannelMonitorUpdate > , monitor : & ChannelMonitor < ChannelSigner > ) -> ChannelMonitorUpdateStatus ;
164
+ fn update_persisted_channel ( & self , monitor_name : MonitorName , monitor_update : Option < & ChannelMonitorUpdate > , monitor : & ChannelMonitor < ChannelSigner > ) -> AsyncResult < ' static , ( ) > ;
163
165
/// Prevents the channel monitor from being loaded on startup.
164
166
///
165
167
/// Archiving the data in a backup location (rather than deleting it fully) is useful for
@@ -231,31 +233,33 @@ impl<ChannelSigner: EcdsaChannelSigner> Deref for LockedChannelMonitor<'_, Chann
231
233
/// [`ChannelManager`]: crate::ln::channelmanager::ChannelManager
232
234
/// [module-level documentation]: crate::chain::chainmonitor
233
235
/// [`rebroadcast_pending_claims`]: Self::rebroadcast_pending_claims
234
- pub struct ChainMonitor < ChannelSigner : EcdsaChannelSigner , C : Deref , T : Deref , F : Deref , L : Deref , P : Deref >
236
+ pub struct ChainMonitor < ChannelSigner : EcdsaChannelSigner , C : Deref , T : Deref , F : Deref , L : Deref , P : Deref , FS : FutureSpawner >
235
237
where C :: Target : chain:: Filter ,
236
238
T :: Target : BroadcasterInterface ,
237
239
F :: Target : FeeEstimator ,
238
240
L :: Target : Logger ,
239
241
P :: Target : Persist < ChannelSigner > ,
240
242
{
241
- monitors : RwLock < HashMap < ChannelId , MonitorHolder < ChannelSigner > > > ,
243
+ monitors : Arc < RwLock < HashMap < ChannelId , MonitorHolder < ChannelSigner > > > > ,
242
244
chain_source : Option < C > ,
243
245
broadcaster : T ,
244
246
logger : L ,
245
247
fee_estimator : F ,
246
248
persister : P ,
247
249
/// "User-provided" (ie persistence-completion/-failed) [`MonitorEvent`]s. These came directly
248
250
/// from the user and not from a [`ChannelMonitor`].
249
- pending_monitor_events : Mutex < Vec < ( OutPoint , ChannelId , Vec < MonitorEvent > , PublicKey ) > > ,
251
+ pending_monitor_events : Arc < Mutex < Vec < ( OutPoint , ChannelId , Vec < MonitorEvent > , PublicKey ) > > > ,
250
252
/// The best block height seen, used as a proxy for the passage of time.
251
253
highest_chain_height : AtomicUsize ,
252
254
253
255
/// A [`Notifier`] used to wake up the background processor in case we have any [`Event`]s for
254
256
/// it to give to users (or [`MonitorEvent`]s for `ChannelManager` to process).
255
- event_notifier : Notifier ,
257
+ event_notifier : Arc < Notifier > ,
258
+
259
+ future_spawner : Arc < FS > ,
256
260
}
257
261
258
- impl < ChannelSigner : EcdsaChannelSigner , C : Deref , T : Deref , F : Deref , L : Deref , P : Deref > ChainMonitor < ChannelSigner , C , T , F , L , P >
262
+ impl < ChannelSigner : EcdsaChannelSigner + ' static , C : Deref , T : Deref , F : Deref , L : Deref , P : Deref , FS : FutureSpawner > ChainMonitor < ChannelSigner , C , T , F , L , P , FS >
259
263
where C :: Target : chain:: Filter ,
260
264
T :: Target : BroadcasterInterface ,
261
265
F :: Target : FeeEstimator ,
@@ -345,18 +349,31 @@ where C::Target: chain::Filter,
345
349
// `ChannelMonitorUpdate` after a channel persist for a channel with the same
346
350
// `latest_update_id`.
347
351
let _pending_monitor_updates = monitor_state. pending_monitor_updates . lock ( ) . unwrap ( ) ;
348
- match self . persister . update_persisted_channel ( monitor. persistence_key ( ) , None , monitor) {
349
- ChannelMonitorUpdateStatus :: Completed =>
350
- log_trace ! ( logger, "Finished syncing Channel Monitor for channel {} for block-data" ,
351
- log_funding_info!( monitor)
352
- ) ,
353
- ChannelMonitorUpdateStatus :: InProgress => {
354
- log_trace ! ( logger, "Channel Monitor sync for channel {} in progress." , log_funding_info!( monitor) ) ;
355
- }
356
- ChannelMonitorUpdateStatus :: UnrecoverableError => {
357
- return Err ( ( ) ) ;
352
+ let max_update_id = _pending_monitor_updates. iter ( ) . copied ( ) . max ( ) . unwrap_or ( 0 ) ;
353
+
354
+ let persist_res = self . persister . update_persisted_channel ( monitor. persistence_key ( ) , None , monitor) ;
355
+
356
+ let monitors = self . monitors . clone ( ) ;
357
+ let pending_monitor_updates_cb = self . pending_monitor_events . clone ( ) ;
358
+ let event_notifier = self . event_notifier . clone ( ) ;
359
+ let future_spawner = self . future_spawner . clone ( ) ;
360
+ let channel_id = * channel_id;
361
+
362
+ match poll_or_spawn ( persist_res, move || {
363
+ // TODO: Log error if the monitor is not persisted.
364
+ let _ = ChainMonitor :: < ChannelSigner , C , T , F , L , P , FS > :: channel_monitor_updated_internal ( & monitors, & pending_monitor_updates_cb, & event_notifier,
365
+ channel_id, max_update_id) ;
366
+ } , future_spawner. deref ( ) ) {
367
+ Ok ( true ) => {
368
+ // log
369
+ } ,
370
+ Ok ( false ) => {
371
+ // log
372
+ }
373
+ Err ( _) => {
374
+ return Err ( ( ) ) ;
375
+ } ,
358
376
}
359
- }
360
377
}
361
378
362
379
// Register any new outputs with the chain source for filtering, storing any dependent
@@ -386,17 +403,18 @@ where C::Target: chain::Filter,
386
403
/// pre-filter blocks or only fetch blocks matching a compact filter. Otherwise, clients may
387
404
/// always need to fetch full blocks absent another means for determining which blocks contain
388
405
/// transactions relevant to the watched channels.
389
- pub fn new ( chain_source : Option < C > , broadcaster : T , logger : L , feeest : F , persister : P ) -> Self {
406
+ pub fn new ( chain_source : Option < C > , broadcaster : T , logger : L , feeest : F , persister : P , future_spawner : FS ) -> Self {
390
407
Self {
391
- monitors : RwLock :: new ( new_hash_map ( ) ) ,
408
+ monitors : Arc :: new ( RwLock :: new ( new_hash_map ( ) ) ) ,
392
409
chain_source,
393
410
broadcaster,
394
411
logger,
395
412
fee_estimator : feeest,
396
413
persister,
397
- pending_monitor_events : Mutex :: new ( Vec :: new ( ) ) ,
414
+ pending_monitor_events : Arc :: new ( Mutex :: new ( Vec :: new ( ) ) ) ,
398
415
highest_chain_height : AtomicUsize :: new ( 0 ) ,
399
- event_notifier : Notifier :: new ( ) ,
416
+ event_notifier : Arc :: new ( Notifier :: new ( ) ) ,
417
+ future_spawner : Arc :: new ( future_spawner) ,
400
418
}
401
419
}
402
420
@@ -529,6 +547,40 @@ where C::Target: chain::Filter,
529
547
Ok ( ( ) )
530
548
}
531
549
550
+ fn channel_monitor_updated_internal (
551
+ monitors : & RwLock < HashMap < ChannelId , MonitorHolder < ChannelSigner > > > ,
552
+ pending_monitor_events : & Mutex < Vec < ( OutPoint , ChannelId , Vec < MonitorEvent > , PublicKey ) > > ,
553
+ event_notifier : & Notifier ,
554
+ channel_id : ChannelId , completed_update_id : u64 ) -> Result < ( ) , APIError > {
555
+ let monitors = monitors. read ( ) . unwrap ( ) ;
556
+ let monitor_data = if let Some ( mon) = monitors. get ( & channel_id) { mon } else {
557
+ return Err ( APIError :: APIMisuseError { err : format ! ( "No ChannelMonitor matching channel ID {} found" , channel_id) } ) ;
558
+ } ;
559
+ let mut pending_monitor_updates = monitor_data. pending_monitor_updates . lock ( ) . unwrap ( ) ;
560
+ pending_monitor_updates. retain ( |update_id| * update_id != completed_update_id) ;
561
+
562
+ // Note that we only check for pending non-chainsync monitor updates and we don't track monitor
563
+ // updates resulting from chainsync in `pending_monitor_updates`.
564
+ let monitor_is_pending_updates = monitor_data. has_pending_updates ( & pending_monitor_updates) ;
565
+
566
+ // TODO: Add logger
567
+
568
+ if monitor_is_pending_updates {
569
+ // If there are still monitor updates pending, we cannot yet construct a
570
+ // Completed event.
571
+ return Ok ( ( ) ) ;
572
+ }
573
+ let funding_txo = monitor_data. monitor . get_funding_txo ( ) ;
574
+ pending_monitor_events. lock ( ) . unwrap ( ) . push ( ( funding_txo, channel_id, vec ! [ MonitorEvent :: Completed {
575
+ funding_txo,
576
+ channel_id,
577
+ monitor_update_id: monitor_data. monitor. get_latest_update_id( ) ,
578
+ } ] , monitor_data. monitor . get_counterparty_node_id ( ) ) ) ;
579
+
580
+ event_notifier. notify ( ) ;
581
+ Ok ( ( ) )
582
+ }
583
+
532
584
/// This wrapper avoids having to update some of our tests for now as they assume the direct
533
585
/// chain::Watch API wherein we mark a monitor fully-updated by just calling
534
586
/// channel_monitor_updated once with the highest ID.
@@ -667,8 +719,8 @@ where C::Target: chain::Filter,
667
719
}
668
720
}
669
721
670
- impl < ChannelSigner : EcdsaChannelSigner , C : Deref , T : Deref , F : Deref , L : Deref , P : Deref >
671
- chain:: Listen for ChainMonitor < ChannelSigner , C , T , F , L , P >
722
+ impl < ChannelSigner : EcdsaChannelSigner + Send + Sync + ' static , C : Deref , T : Deref , F : Deref , L : Deref , P : Deref , FS : FutureSpawner >
723
+ chain:: Listen for ChainMonitor < ChannelSigner , C , T , F , L , P , FS >
672
724
where
673
725
C :: Target : chain:: Filter ,
674
726
T :: Target : BroadcasterInterface ,
@@ -696,8 +748,8 @@ where
696
748
}
697
749
}
698
750
699
- impl < ChannelSigner : EcdsaChannelSigner , C : Deref , T : Deref , F : Deref , L : Deref , P : Deref >
700
- chain:: Confirm for ChainMonitor < ChannelSigner , C , T , F , L , P >
751
+ impl < ChannelSigner : EcdsaChannelSigner + Sync + Send + ' static , C : Deref , T : Deref , F : Deref , L : Deref , P : Deref , FS : FutureSpawner >
752
+ chain:: Confirm for ChainMonitor < ChannelSigner , C , T , F , L , P , FS >
701
753
where
702
754
C :: Target : chain:: Filter ,
703
755
T :: Target : BroadcasterInterface ,
@@ -750,8 +802,8 @@ where
750
802
}
751
803
}
752
804
753
- impl < ChannelSigner : EcdsaChannelSigner , C : Deref , T : Deref , F : Deref , L : Deref , P : Deref >
754
- chain:: Watch < ChannelSigner > for ChainMonitor < ChannelSigner , C , T , F , L , P >
805
+ impl < ChannelSigner : EcdsaChannelSigner + Sync + Send + ' static , C : Deref , T : Deref , F : Deref , L : Deref , P : Deref , FS : FutureSpawner + Clone >
806
+ chain:: Watch < ChannelSigner > for ChainMonitor < ChannelSigner , C , T , F , L , P , FS >
755
807
where C :: Target : chain:: Filter ,
756
808
T :: Target : BroadcasterInterface ,
757
809
F :: Target : FeeEstimator ,
@@ -772,15 +824,28 @@ where C::Target: chain::Filter,
772
824
let update_id = monitor. get_latest_update_id ( ) ;
773
825
let mut pending_monitor_updates = Vec :: new ( ) ;
774
826
let persist_res = self . persister . persist_new_channel ( monitor. persistence_key ( ) , & monitor) ;
775
- match persist_res {
776
- ChannelMonitorUpdateStatus :: InProgress => {
777
- log_info ! ( logger, "Persistence of new ChannelMonitor for channel {} in progress" , log_funding_info!( monitor) ) ;
778
- pending_monitor_updates. push ( update_id) ;
779
- } ,
780
- ChannelMonitorUpdateStatus :: Completed => {
827
+
828
+ let update_status;
829
+ let monitors = self . monitors . clone ( ) ;
830
+ let pending_monitor_updates_cb = self . pending_monitor_events . clone ( ) ;
831
+ let event_notifier = self . event_notifier . clone ( ) ;
832
+ let future_spawner = self . future_spawner . clone ( ) ;
833
+
834
+ match poll_or_spawn ( persist_res, move || {
835
+ // TODO: Log error if the monitor is not persisted.
836
+ let _ = ChainMonitor :: < ChannelSigner , C , T , F , L , P , FS > :: channel_monitor_updated_internal ( & monitors, & pending_monitor_updates_cb, & event_notifier,
837
+ channel_id, update_id) ;
838
+ } , future_spawner. deref ( ) ) {
839
+ Ok ( true ) => {
781
840
log_info ! ( logger, "Persistence of new ChannelMonitor for channel {} completed" , log_funding_info!( monitor) ) ;
841
+ update_status = ChannelMonitorUpdateStatus :: Completed ;
782
842
} ,
783
- ChannelMonitorUpdateStatus :: UnrecoverableError => {
843
+ Ok ( false ) => {
844
+ log_info ! ( logger, "Persistence of new ChannelMonitor for channel {} in progress" , log_funding_info!( monitor) ) ;
845
+ pending_monitor_updates. push ( update_id) ;
846
+ update_status = ChannelMonitorUpdateStatus :: InProgress ;
847
+ }
848
+ Err ( _) => {
784
849
let err_str = "ChannelMonitor[Update] persistence failed unrecoverably. This indicates we cannot continue normal operation and must shut down." ;
785
850
log_error ! ( logger, "{}" , err_str) ;
786
851
panic ! ( "{}" , err_str) ;
@@ -793,7 +858,7 @@ where C::Target: chain::Filter,
793
858
monitor,
794
859
pending_monitor_updates : Mutex :: new ( pending_monitor_updates) ,
795
860
} ) ;
796
- Ok ( persist_res )
861
+ Ok ( update_status )
797
862
}
798
863
799
864
fn update_channel ( & self , channel_id : ChannelId , update : & ChannelMonitorUpdate ) -> ChannelMonitorUpdateStatus {
@@ -838,27 +903,40 @@ where C::Target: chain::Filter,
838
903
} else {
839
904
self . persister . update_persisted_channel ( monitor. persistence_key ( ) , Some ( update) , monitor)
840
905
} ;
841
- match persist_res {
842
- ChannelMonitorUpdateStatus :: InProgress => {
843
- pending_monitor_updates. push ( update_id) ;
906
+
907
+ let monitors = self . monitors . clone ( ) ;
908
+ let pending_monitor_updates_cb = self . pending_monitor_events . clone ( ) ;
909
+ let event_notifier = self . event_notifier . clone ( ) ;
910
+ let future_spawner = self . future_spawner . clone ( ) ;
911
+
912
+ let update_status;
913
+ match poll_or_spawn ( persist_res, move || {
914
+ // TODO: Log error if the monitor is not persisted.
915
+ let _ = ChainMonitor :: < ChannelSigner , C , T , F , L , P , FS > :: channel_monitor_updated_internal ( & monitors, & pending_monitor_updates_cb, & event_notifier,
916
+ channel_id, update_id) ;
917
+ } , future_spawner. deref ( ) ) {
918
+ Ok ( true ) => {
844
919
log_debug ! ( logger,
845
- "Persistence of ChannelMonitorUpdate id {:?} for channel {} in progress " ,
920
+ "Persistence of ChannelMonitorUpdate id {:?} for channel {} completed " ,
846
921
update_id,
847
922
log_funding_info!( monitor)
848
923
) ;
924
+ update_status = ChannelMonitorUpdateStatus :: Completed ;
849
925
} ,
850
- ChannelMonitorUpdateStatus :: Completed => {
926
+ Ok ( false ) => {
851
927
log_debug ! ( logger,
852
- "Persistence of ChannelMonitorUpdate id {:?} for channel {} completed " ,
928
+ "Persistence of ChannelMonitorUpdate id {:?} for channel {} in progress " ,
853
929
update_id,
854
930
log_funding_info!( monitor)
855
931
) ;
856
- } ,
857
- ChannelMonitorUpdateStatus :: UnrecoverableError => {
932
+ pending_monitor_updates. push ( update_id) ;
933
+ update_status = ChannelMonitorUpdateStatus :: InProgress ;
934
+ }
935
+ Err ( _) => {
858
936
// Take the monitors lock for writing so that we poison it and any future
859
937
// operations going forward fail immediately.
860
938
core:: mem:: drop ( pending_monitor_updates) ;
861
- core:: mem:: drop ( monitors) ;
939
+ // core::mem::drop(monitors);
862
940
let _poison = self . monitors . write ( ) . unwrap ( ) ;
863
941
let err_str = "ChannelMonitor[Update] persistence failed unrecoverably. This indicates we cannot continue normal operation and must shut down." ;
864
942
log_error ! ( logger, "{}" , err_str) ;
@@ -868,7 +946,7 @@ where C::Target: chain::Filter,
868
946
if update_res. is_err ( ) {
869
947
ChannelMonitorUpdateStatus :: InProgress
870
948
} else {
871
- persist_res
949
+ update_status
872
950
}
873
951
}
874
952
}
@@ -889,7 +967,7 @@ where C::Target: chain::Filter,
889
967
}
890
968
}
891
969
892
- impl < ChannelSigner : EcdsaChannelSigner , C : Deref , T : Deref , F : Deref , L : Deref , P : Deref > events:: EventsProvider for ChainMonitor < ChannelSigner , C , T , F , L , P >
970
+ impl < ChannelSigner : EcdsaChannelSigner , C : Deref , T : Deref , F : Deref , L : Deref , P : Deref , FS : FutureSpawner > events:: EventsProvider for ChainMonitor < ChannelSigner , C , T , F , L , P , FS >
893
971
where C :: Target : chain:: Filter ,
894
972
T :: Target : BroadcasterInterface ,
895
973
F :: Target : FeeEstimator ,
@@ -1136,4 +1214,3 @@ mod tests {
1136
1214
} ) . is_err( ) ) ;
1137
1215
}
1138
1216
}
1139
-
0 commit comments