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