@@ -39,11 +39,14 @@ use crate::chain::{ChannelMonitorUpdateStatus, Filter, WatchedOutput};
3939use crate :: events:: { self , Event , EventHandler , ReplayEvent } ;
4040use crate :: ln:: channel_state:: ChannelDetails ;
4141use crate :: ln:: msgs:: { self , BaseMessageHandler , Init , MessageSendEvent , SendOnlyMessageHandler } ;
42+ #[ cfg( peer_storage) ]
4243use crate :: ln:: our_peer_storage:: { DecryptedOurPeerStorage , PeerStorageMonitorHolder } ;
4344use crate :: ln:: types:: ChannelId ;
4445use crate :: prelude:: * ;
4546use crate :: sign:: ecdsa:: EcdsaChannelSigner ;
46- use crate :: sign:: { EntropySource , PeerStorageKey } ;
47+ #[ cfg( peer_storage) ]
48+ use crate :: sign:: PeerStorageKey ;
49+ use crate :: sign:: EntropySource ;
4750use crate :: sync:: { Mutex , MutexGuard , RwLock , RwLockReadGuard } ;
4851use crate :: types:: features:: { InitFeatures , NodeFeatures } ;
4952use crate :: util:: errors:: APIError ;
@@ -53,6 +56,8 @@ use crate::util::persist::MonitorName;
5356use crate :: util:: ser:: { VecWriter , Writeable } ;
5457use crate :: util:: wakers:: { Future , Notifier } ;
5558use bitcoin:: secp256k1:: PublicKey ;
59+ #[ cfg( peer_storage) ]
60+ use core:: iter:: Cycle ;
5661use core:: ops:: Deref ;
5762use core:: sync:: atomic:: { AtomicUsize , Ordering } ;
5863
@@ -268,6 +273,8 @@ pub struct ChainMonitor<
268273 logger : L ,
269274 fee_estimator : F ,
270275 persister : P ,
276+
277+ #[ cfg( peer_storage) ]
271278 entropy_source : ES ,
272279 /// "User-provided" (ie persistence-completion/-failed) [`MonitorEvent`]s. These came directly
273280 /// from the user and not from a [`ChannelMonitor`].
@@ -282,7 +289,9 @@ pub struct ChainMonitor<
282289 /// Messages to send to the peer. This is currently used to distribute PeerStorage to channel partners.
283290 pending_send_only_events : Mutex < Vec < MessageSendEvent > > ,
284291
292+ #[ cfg( peer_storage) ]
285293 our_peerstorage_encryption_key : PeerStorageKey ,
294+ _phantom : std:: marker:: PhantomData < ES > ,
286295}
287296
288297impl <
@@ -479,6 +488,7 @@ where
479488 /// [`NodeSigner`]: crate::sign::NodeSigner
480489 /// [`NodeSigner::get_peer_storage_key`]: crate::sign::NodeSigner::get_peer_storage_key
481490 /// [`ChannelManager`]: crate::ln::channelmanager::ChannelManager
491+ #[ cfg( peer_storage) ]
482492 pub fn new (
483493 chain_source : Option < C > , broadcaster : T , logger : L , feeest : F , persister : P ,
484494 entropy_source : ES , our_peerstorage_encryption_key : PeerStorageKey ,
@@ -496,9 +506,28 @@ where
496506 event_notifier : Notifier :: new ( ) ,
497507 pending_send_only_events : Mutex :: new ( Vec :: new ( ) ) ,
498508 our_peerstorage_encryption_key,
509+ _phantom : std:: marker:: PhantomData ,
499510 }
500511 }
501512
513+ #[ cfg( not( peer_storage) ) ]
514+ pub fn new (
515+ chain_source : Option < C > , broadcaster : T , logger : L , feeest : F , persister : P ,
516+ ) -> Self {
517+ Self {
518+ monitors : RwLock :: new ( new_hash_map ( ) ) ,
519+ chain_source,
520+ broadcaster,
521+ logger,
522+ fee_estimator : feeest,
523+ persister,
524+ pending_monitor_events : Mutex :: new ( Vec :: new ( ) ) ,
525+ highest_chain_height : AtomicUsize :: new ( 0 ) ,
526+ event_notifier : Notifier :: new ( ) ,
527+ pending_send_only_events : Mutex :: new ( Vec :: new ( ) ) ,
528+ _phantom : std:: marker:: PhantomData ,
529+ }
530+ }
502531 /// Gets the balances in the contained [`ChannelMonitor`]s which are claimable on-chain or
503532 /// claims which are awaiting confirmation.
504533 ///
@@ -808,59 +837,80 @@ where
808837
809838 /// This function collects the counterparty node IDs from all monitors into a `HashSet`,
810839 /// ensuring unique IDs are returned.
840+ #[ cfg( peer_storage) ]
811841 fn all_counterparty_node_ids ( & self ) -> HashSet < PublicKey > {
812842 let mon = self . monitors . read ( ) . unwrap ( ) ;
813843 mon. values ( ) . map ( |monitor| monitor. monitor . get_counterparty_node_id ( ) ) . collect ( )
814844 }
815845
816846 #[ cfg( peer_storage) ]
817847 fn send_peer_storage ( & self , their_node_id : PublicKey ) {
818- #[ allow( unused_mut) ]
819848 let mut monitors_list: Vec < PeerStorageMonitorHolder > = Vec :: new ( ) ;
820849 let random_bytes = self . entropy_source . get_secure_random_bytes ( ) ;
821850
822851 const MAX_PEER_STORAGE_SIZE : usize = 65531 ;
823852 const USIZE_LEN : usize = core:: mem:: size_of :: < usize > ( ) ;
824- let mut usize_bytes = [ 0u8 ; USIZE_LEN ] ;
825- usize_bytes. copy_from_slice ( & random_bytes[ 0 ..USIZE_LEN ] ) ;
826- let random_usize = usize:: from_le_bytes ( usize_bytes) ;
827-
828- let mut curr_size = 0 ;
829- let monitors = self . monitors . read ( ) . unwrap ( ) ;
830- let mut stored_chanmon_idx = alloc:: collections:: BTreeSet :: < usize > :: new ( ) ;
831- // Used as a fallback reference if the set is empty
832- let zero = 0 ;
853+ let mut random_bytes_cycle_iter = random_bytes. iter ( ) . cycle ( ) ;
854+
855+ let mut current_size = 0 ;
856+ let monitors_lock = self . monitors . read ( ) . unwrap ( ) ;
857+ let mut channel_ids = monitors_lock. keys ( ) . copied ( ) . collect ( ) ;
858+
859+ fn next_random_id (
860+ channel_ids : & mut Vec < ChannelId > ,
861+ random_bytes_cycle_iter : & mut Cycle < core:: slice:: Iter < u8 > > ,
862+ ) -> Option < ChannelId > {
863+ if channel_ids. is_empty ( ) {
864+ return None ;
865+ }
866+ let random_idx = {
867+ let mut usize_bytes = [ 0u8 ; USIZE_LEN ] ;
868+ usize_bytes. iter_mut ( ) . for_each ( |b| {
869+ * b = * random_bytes_cycle_iter. next ( ) . expect ( "A cycle never ends" )
870+ } ) ;
871+ // Take one more to introduce a slight misalignment.
872+ random_bytes_cycle_iter. next ( ) . expect ( "A cycle never ends" ) ;
873+ usize:: from_le_bytes ( usize_bytes) % channel_ids. len ( )
874+ } ;
875+ Some ( channel_ids. swap_remove ( random_idx) )
876+ }
833877
834- while curr_size < MAX_PEER_STORAGE_SIZE
835- && * stored_chanmon_idx. last ( ) . unwrap_or ( & zero) < monitors. len ( )
878+ while let Some ( channel_id) = next_random_id ( & mut channel_ids, & mut random_bytes_cycle_iter)
836879 {
837- let idx = random_usize % monitors. len ( ) ;
838- stored_chanmon_idx. insert ( idx + 1 ) ;
839- let ( cid, mon) = monitors. iter ( ) . skip ( idx) . next ( ) . unwrap ( ) ;
880+ let monitor_holder = if let Some ( monitor_holder) = monitors_lock. get ( & channel_id) {
881+ monitor_holder
882+ } else {
883+ debug_assert ! (
884+ false ,
885+ "Tried to access non-existing monitor, this should never happen"
886+ ) ;
887+ break ;
888+ } ;
840889
841- let mut ser_chan = VecWriter ( Vec :: new ( ) ) ;
842- let min_seen_secret = mon . monitor . get_min_seen_secret ( ) ;
843- let counterparty_node_id = mon . monitor . get_counterparty_node_id ( ) ;
890+ let mut serialized_channel = VecWriter ( Vec :: new ( ) ) ;
891+ let min_seen_secret = monitor_holder . monitor . get_min_seen_secret ( ) ;
892+ let counterparty_node_id = monitor_holder . monitor . get_counterparty_node_id ( ) ;
844893 {
845- let chan_mon = mon . monitor . inner . lock ( ) . unwrap ( ) ;
894+ let inner_lock = monitor_holder . monitor . inner . lock ( ) . unwrap ( ) ;
846895
847- write_chanmon_internal ( & chan_mon , true , & mut ser_chan )
896+ write_chanmon_internal ( & inner_lock , true , & mut serialized_channel )
848897 . expect ( "can not write Channel Monitor for peer storage message" ) ;
849898 }
850899 let peer_storage_monitor = PeerStorageMonitorHolder {
851- channel_id : * cid ,
900+ channel_id,
852901 min_seen_secret,
853902 counterparty_node_id,
854- monitor_bytes : ser_chan . 0 ,
903+ monitor_bytes : serialized_channel . 0 ,
855904 } ;
856905
857- // Adding size of peer_storage_monitor.
858- curr_size += peer_storage_monitor. serialized_length ( ) ;
906+ let serialized_length = peer_storage_monitor. serialized_length ( ) ;
859907
860- if curr_size > MAX_PEER_STORAGE_SIZE {
861- break ;
908+ if current_size + serialized_length > MAX_PEER_STORAGE_SIZE {
909+ continue ;
910+ } else {
911+ current_size += serialized_length;
912+ monitors_list. push ( peer_storage_monitor) ;
862913 }
863- monitors_list. push ( peer_storage_monitor) ;
864914 }
865915
866916 let serialised_channels = monitors_list. encode ( ) ;
0 commit comments