99//! and [`ChannelMonitor`] all in one place.
1010
1111use core:: ops:: Deref ;
12- use bitcoin:: hashes:: hex:: ToHex ;
12+ use bitcoin:: hashes:: hex:: { FromHex , ToHex } ;
13+ use bitcoin:: { BlockHash , Txid } ;
14+
1315use crate :: io;
1416use crate :: prelude:: { Vec , String } ;
1517use crate :: routing:: scoring:: WriteableScore ;
@@ -24,7 +26,7 @@ use crate::ln::channelmanager::ChannelManager;
2426use crate :: routing:: router:: Router ;
2527use crate :: routing:: gossip:: NetworkGraph ;
2628use crate :: util:: logger:: Logger ;
27- use crate :: util:: ser:: Writeable ;
29+ use crate :: util:: ser:: { ReadableArgs , Writeable } ;
2830
2931/// The alphabet of characters allowed for namespaces and keys.
3032pub const KVSTORE_NAMESPACE_KEY_ALPHABET : & str = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_-" ;
@@ -190,3 +192,52 @@ impl<ChannelSigner: WriteableEcdsaChannelSigner, K: KVStorePersister> Persist<Ch
190192 }
191193 }
192194}
195+
196+ /// Read previously persisted [`ChannelMonitor`]s from the store.
197+ pub fn read_channel_monitors < K : Deref , ES : Deref , SP : Deref > (
198+ kv_store : K , entropy_source : ES , signer_provider : SP ,
199+ ) -> io:: Result < Vec < ( BlockHash , ChannelMonitor < <SP :: Target as SignerProvider >:: Signer > ) > >
200+ where
201+ K :: Target : KVStore ,
202+ ES :: Target : EntropySource + Sized ,
203+ SP :: Target : SignerProvider + Sized ,
204+ {
205+ let mut res = Vec :: new ( ) ;
206+
207+ for stored_key in kv_store. list (
208+ CHANNEL_MONITOR_PERSISTENCE_NAMESPACE , CHANNEL_MONITOR_PERSISTENCE_SUB_NAMESPACE ) ?
209+ {
210+ let txid = Txid :: from_hex ( stored_key. split_at ( 64 ) . 0 ) . map_err ( |_| {
211+ io:: Error :: new ( io:: ErrorKind :: InvalidData , "Invalid tx ID in stored key" )
212+ } ) ?;
213+
214+ let index: u16 = stored_key. split_at ( 65 ) . 1 . parse ( ) . map_err ( |_| {
215+ io:: Error :: new ( io:: ErrorKind :: InvalidData , "Invalid tx index in stored key" )
216+ } ) ?;
217+
218+ match <( BlockHash , ChannelMonitor < <SP :: Target as SignerProvider >:: Signer > ) >:: read (
219+ & mut io:: Cursor :: new (
220+ kv_store. read ( CHANNEL_MONITOR_PERSISTENCE_NAMESPACE , CHANNEL_MONITOR_PERSISTENCE_SUB_NAMESPACE , & stored_key) ?) ,
221+ ( & * entropy_source, & * signer_provider) ,
222+ ) {
223+ Ok ( ( block_hash, channel_monitor) ) => {
224+ if channel_monitor. get_funding_txo ( ) . 0 . txid != txid
225+ || channel_monitor. get_funding_txo ( ) . 0 . index != index
226+ {
227+ return Err ( io:: Error :: new (
228+ io:: ErrorKind :: InvalidData ,
229+ "ChannelMonitor was stored under the wrong key" ,
230+ ) ) ;
231+ }
232+ res. push ( ( block_hash, channel_monitor) ) ;
233+ }
234+ Err ( _) => {
235+ return Err ( io:: Error :: new (
236+ io:: ErrorKind :: InvalidData ,
237+ "Failed to deserialize ChannelMonitor"
238+ ) )
239+ }
240+ }
241+ }
242+ Ok ( res)
243+ }
0 commit comments