forked from lightningdevkit/rust-lightning
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpersist.rs
More file actions
1516 lines (1421 loc) · 57.2 KB
/
persist.rs
File metadata and controls
1516 lines (1421 loc) · 57.2 KB
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
// 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.
//! This module contains a simple key-value store trait [`KVStoreSync`] that
//! allows one to implement the persistence for [`ChannelManager`], [`NetworkGraph`],
//! and [`ChannelMonitor`] all in one place.
//!
//! [`ChannelManager`]: crate::ln::channelmanager::ChannelManager
//! [`NetworkGraph`]: crate::routing::gossip::NetworkGraph
use bitcoin::hashes::hex::FromHex;
use bitcoin::{BlockHash, Txid};
use core::cmp;
use core::future::Future;
use core::ops::Deref;
use core::pin::Pin;
use core::str::FromStr;
use crate::prelude::*;
use crate::{io, log_error};
use crate::chain;
use crate::chain::chaininterface::{BroadcasterInterface, FeeEstimator};
use crate::chain::chainmonitor::Persist;
use crate::chain::channelmonitor::{ChannelMonitor, ChannelMonitorUpdate};
use crate::chain::transaction::OutPoint;
use crate::ln::types::ChannelId;
use crate::sign::{ecdsa::EcdsaChannelSigner, EntropySource, SignerProvider};
use crate::util::logger::Logger;
use crate::util::ser::{Readable, ReadableArgs, Writeable};
/// The alphabet of characters allowed for namespaces and keys.
pub const KVSTORE_NAMESPACE_KEY_ALPHABET: &str =
"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_-";
/// The maximum number of characters namespaces and keys may have.
pub const KVSTORE_NAMESPACE_KEY_MAX_LEN: usize = 120;
/// The primary namespace under which the [`ChannelManager`] will be persisted.
///
/// [`ChannelManager`]: crate::ln::channelmanager::ChannelManager
pub const CHANNEL_MANAGER_PERSISTENCE_PRIMARY_NAMESPACE: &str = "";
/// The secondary namespace under which the [`ChannelManager`] will be persisted.
///
/// [`ChannelManager`]: crate::ln::channelmanager::ChannelManager
pub const CHANNEL_MANAGER_PERSISTENCE_SECONDARY_NAMESPACE: &str = "";
/// The key under which the [`ChannelManager`] will be persisted.
///
/// [`ChannelManager`]: crate::ln::channelmanager::ChannelManager
pub const CHANNEL_MANAGER_PERSISTENCE_KEY: &str = "manager";
/// The primary namespace under which [`ChannelMonitor`]s will be persisted.
pub const CHANNEL_MONITOR_PERSISTENCE_PRIMARY_NAMESPACE: &str = "monitors";
/// The secondary namespace under which [`ChannelMonitor`]s will be persisted.
pub const CHANNEL_MONITOR_PERSISTENCE_SECONDARY_NAMESPACE: &str = "";
/// The primary namespace under which [`ChannelMonitorUpdate`]s will be persisted.
pub const CHANNEL_MONITOR_UPDATE_PERSISTENCE_PRIMARY_NAMESPACE: &str = "monitor_updates";
/// The primary namespace under which archived [`ChannelMonitor`]s will be persisted.
pub const ARCHIVED_CHANNEL_MONITOR_PERSISTENCE_PRIMARY_NAMESPACE: &str = "archived_monitors";
/// The secondary namespace under which archived [`ChannelMonitor`]s will be persisted.
pub const ARCHIVED_CHANNEL_MONITOR_PERSISTENCE_SECONDARY_NAMESPACE: &str = "";
/// The primary namespace under which the [`NetworkGraph`] will be persisted.
///
/// [`NetworkGraph`]: crate::routing::gossip::NetworkGraph
pub const NETWORK_GRAPH_PERSISTENCE_PRIMARY_NAMESPACE: &str = "";
/// The secondary namespace under which the [`NetworkGraph`] will be persisted.
///
/// [`NetworkGraph`]: crate::routing::gossip::NetworkGraph
pub const NETWORK_GRAPH_PERSISTENCE_SECONDARY_NAMESPACE: &str = "";
/// The key under which the [`NetworkGraph`] will be persisted.
///
/// [`NetworkGraph`]: crate::routing::gossip::NetworkGraph
pub const NETWORK_GRAPH_PERSISTENCE_KEY: &str = "network_graph";
/// The primary namespace under which the [`WriteableScore`] will be persisted.
///
/// [`WriteableScore`]: crate::routing::scoring::WriteableScore
pub const SCORER_PERSISTENCE_PRIMARY_NAMESPACE: &str = "";
/// The secondary namespace under which the [`WriteableScore`] will be persisted.
///
/// [`WriteableScore`]: crate::routing::scoring::WriteableScore
pub const SCORER_PERSISTENCE_SECONDARY_NAMESPACE: &str = "";
/// The key under which the [`WriteableScore`] will be persisted.
///
/// [`WriteableScore`]: crate::routing::scoring::WriteableScore
pub const SCORER_PERSISTENCE_KEY: &str = "scorer";
/// The primary namespace under which [`OutputSweeper`] state will be persisted.
///
/// [`OutputSweeper`]: crate::util::sweep::OutputSweeper
pub const OUTPUT_SWEEPER_PERSISTENCE_PRIMARY_NAMESPACE: &str = "";
/// The secondary namespace under which [`OutputSweeper`] state will be persisted.
///
/// [`OutputSweeper`]: crate::util::sweep::OutputSweeper
pub const OUTPUT_SWEEPER_PERSISTENCE_SECONDARY_NAMESPACE: &str = "";
/// The secondary namespace under which [`OutputSweeper`] state will be persisted.
/// The key under which [`OutputSweeper`] state will be persisted.
///
/// [`OutputSweeper`]: crate::util::sweep::OutputSweeper
pub const OUTPUT_SWEEPER_PERSISTENCE_KEY: &str = "output_sweeper";
/// A sentinel value to be prepended to monitors persisted by the [`MonitorUpdatingPersister`].
///
/// This serves to prevent someone from accidentally loading such monitors (which may need
/// updates applied to be current) with another implementation.
pub const MONITOR_UPDATING_PERSISTER_PREPEND_SENTINEL: &[u8] = &[0xFF; 2];
/// A synchronous version of the [`KVStore`] trait.
pub trait KVStoreSync {
/// A synchronous version of the [`KVStore::read`] method.
fn read(
&self, primary_namespace: &str, secondary_namespace: &str, key: &str,
) -> Result<Vec<u8>, io::Error>;
/// A synchronous version of the [`KVStore::write`] method.
fn write(
&self, primary_namespace: &str, secondary_namespace: &str, key: &str, buf: Vec<u8>,
) -> Result<(), io::Error>;
/// A synchronous version of the [`KVStore::remove`] method.
fn remove(
&self, primary_namespace: &str, secondary_namespace: &str, key: &str, lazy: bool,
) -> Result<(), io::Error>;
/// A synchronous version of the [`KVStore::list`] method.
fn list(
&self, primary_namespace: &str, secondary_namespace: &str,
) -> Result<Vec<String>, io::Error>;
}
/// A wrapper around a [`KVStoreSync`] that implements the [`KVStore`] trait. It is not necessary to use this type
/// directly.
pub struct KVStoreSyncWrapper<K: Deref>(pub K)
where
K::Target: KVStoreSync;
impl<K: Deref> Deref for KVStoreSyncWrapper<K>
where
K::Target: KVStoreSync,
{
type Target = Self;
fn deref(&self) -> &Self::Target {
self
}
}
impl<K: Deref> KVStore for KVStoreSyncWrapper<K>
where
K::Target: KVStoreSync,
{
fn read(
&self, primary_namespace: &str, secondary_namespace: &str, key: &str,
) -> Pin<Box<dyn Future<Output = Result<Vec<u8>, io::Error>> + 'static + Send>> {
let res = self.0.read(primary_namespace, secondary_namespace, key);
Box::pin(async move { res })
}
fn write(
&self, primary_namespace: &str, secondary_namespace: &str, key: &str, buf: Vec<u8>,
) -> Pin<Box<dyn Future<Output = Result<(), io::Error>> + 'static + Send>> {
let res = self.0.write(primary_namespace, secondary_namespace, key, buf);
Box::pin(async move { res })
}
fn remove(
&self, primary_namespace: &str, secondary_namespace: &str, key: &str, lazy: bool,
) -> Pin<Box<dyn Future<Output = Result<(), io::Error>> + 'static + Send>> {
let res = self.0.remove(primary_namespace, secondary_namespace, key, lazy);
Box::pin(async move { res })
}
fn list(
&self, primary_namespace: &str, secondary_namespace: &str,
) -> Pin<Box<dyn Future<Output = Result<Vec<String>, io::Error>> + 'static + Send>> {
let res = self.0.list(primary_namespace, secondary_namespace);
Box::pin(async move { res })
}
}
/// Provides an interface that allows storage and retrieval of persisted values that are associated
/// with given keys.
///
/// In order to avoid collisions the key space is segmented based on the given `primary_namespace`s
/// and `secondary_namespace`s. Implementations of this trait are free to handle them in different
/// ways, as long as per-namespace key uniqueness is asserted.
///
/// Keys and namespaces are required to be valid ASCII strings in the range of
/// [`KVSTORE_NAMESPACE_KEY_ALPHABET`] and no longer than [`KVSTORE_NAMESPACE_KEY_MAX_LEN`]. Empty
/// primary namespaces and secondary namespaces (`""`) are assumed to be a valid, however, if
/// `primary_namespace` is empty, `secondary_namespace` is required to be empty, too. This means
/// that concerns should always be separated by primary namespace first, before secondary
/// namespaces are used. While the number of primary namespaces will be relatively small and is
/// determined at compile time, there may be many secondary namespaces per primary namespace. Note
/// that per-namespace uniqueness needs to also hold for keys *and* namespaces in any given
/// namespace, i.e., conflicts between keys and equally named
/// primary namespaces/secondary namespaces must be avoided.
///
/// **Note:** Users migrating custom persistence backends from the pre-v0.0.117 `KVStorePersister`
/// interface can use a concatenation of `[{primary_namespace}/[{secondary_namespace}/]]{key}` to
/// recover a `key` compatible with the data model previously assumed by `KVStorePersister::persist`.
pub trait KVStore {
/// Returns the data stored for the given `primary_namespace`, `secondary_namespace`, and
/// `key`.
///
/// Returns an [`ErrorKind::NotFound`] if the given `key` could not be found in the given
/// `primary_namespace` and `secondary_namespace`.
///
/// [`ErrorKind::NotFound`]: io::ErrorKind::NotFound
fn read(
&self, primary_namespace: &str, secondary_namespace: &str, key: &str,
) -> Pin<Box<dyn Future<Output = Result<Vec<u8>, io::Error>> + 'static + Send>>;
/// Persists the given data under the given `key`.
///
/// The order of multiple writes to the same key needs to be retained while persisting
/// asynchronously. In other words, if two writes to the same key occur, the state (as seen by
/// [`Self::read`]) must either see the first write then the second, or only ever the second,
/// no matter when the futures complete (and must always contain the second write once the
/// second future completes). The state should never contain the first write after the second
/// write's future completes, nor should it contain the second write, then contain the first
/// write at any point thereafter (even if the second write's future hasn't yet completed).
///
/// One way to ensure this requirement is met is by assigning a version number to each write
/// before returning the future, and then during asynchronous execution, ensuring that the
/// writes are executed in the correct order.
///
/// Note that no ordering requirements exist for writes to different keys.
///
/// Will create the given `primary_namespace` and `secondary_namespace` if not already present in the store.
fn write(
&self, primary_namespace: &str, secondary_namespace: &str, key: &str, buf: Vec<u8>,
) -> Pin<Box<dyn Future<Output = Result<(), io::Error>> + 'static + Send>>;
/// Removes any data that had previously been persisted under the given `key`.
///
/// If the `lazy` flag is set to `true`, the backend implementation might choose to lazily
/// remove the given `key` at some point in time after the method returns, e.g., as part of an
/// eventual batch deletion of multiple keys. As a consequence, subsequent calls to
/// [`KVStoreSync::list`] might include the removed key until the changes are actually persisted.
///
/// Note that while setting the `lazy` flag reduces the I/O burden of multiple subsequent
/// `remove` calls, it also influences the atomicity guarantees as lazy `remove`s could
/// potentially get lost on crash after the method returns. Therefore, this flag should only be
/// set for `remove` operations that can be safely replayed at a later time.
///
/// Returns successfully if no data will be stored for the given `primary_namespace`,
/// `secondary_namespace`, and `key`, independently of whether it was present before its
/// invokation or not.
fn remove(
&self, primary_namespace: &str, secondary_namespace: &str, key: &str, lazy: bool,
) -> Pin<Box<dyn Future<Output = Result<(), io::Error>> + 'static + Send>>;
/// Returns a list of keys that are stored under the given `secondary_namespace` in
/// `primary_namespace`.
///
/// Returns the keys in arbitrary order, so users requiring a particular order need to sort the
/// returned keys. Returns an empty list if `primary_namespace` or `secondary_namespace` is unknown.
fn list(
&self, primary_namespace: &str, secondary_namespace: &str,
) -> Pin<Box<dyn Future<Output = Result<Vec<String>, io::Error>> + 'static + Send>>;
}
/// Provides additional interface methods that are required for [`KVStore`]-to-[`KVStore`]
/// data migration.
pub trait MigratableKVStore: KVStoreSync {
/// Returns *all* known keys as a list of `primary_namespace`, `secondary_namespace`, `key` tuples.
///
/// This is useful for migrating data from [`KVStoreSync`] implementation to [`KVStoreSync`]
/// implementation.
///
/// Must exhaustively return all entries known to the store to ensure no data is missed, but
/// may return the items in arbitrary order.
fn list_all_keys(&self) -> Result<Vec<(String, String, String)>, io::Error>;
}
/// Migrates all data from one store to another.
///
/// This operation assumes that `target_store` is empty, i.e., any data present under copied keys
/// might get overriden. User must ensure `source_store` is not modified during operation,
/// otherwise no consistency guarantees can be given.
///
/// Will abort and return an error if any IO operation fails. Note that in this case the
/// `target_store` might get left in an intermediate state.
pub fn migrate_kv_store_data<S: MigratableKVStore, T: MigratableKVStore>(
source_store: &mut S, target_store: &mut T,
) -> Result<(), io::Error> {
let keys_to_migrate = source_store.list_all_keys()?;
for (primary_namespace, secondary_namespace, key) in &keys_to_migrate {
let data = source_store.read(primary_namespace, secondary_namespace, key)?;
target_store.write(primary_namespace, secondary_namespace, key, data)?;
}
Ok(())
}
impl<ChannelSigner: EcdsaChannelSigner, K: KVStoreSync + ?Sized> Persist<ChannelSigner> for K {
// TODO: We really need a way for the persister to inform the user that its time to crash/shut
// down once these start returning failure.
// Then we should return InProgress rather than UnrecoverableError, implying we should probably
// just shut down the node since we're not retrying persistence!
fn persist_new_channel(
&self, monitor_name: MonitorName, monitor: &ChannelMonitor<ChannelSigner>,
) -> chain::ChannelMonitorUpdateStatus {
match self.write(
CHANNEL_MONITOR_PERSISTENCE_PRIMARY_NAMESPACE,
CHANNEL_MONITOR_PERSISTENCE_SECONDARY_NAMESPACE,
&monitor_name.to_string(),
monitor.encode(),
) {
Ok(()) => chain::ChannelMonitorUpdateStatus::Completed,
Err(_) => chain::ChannelMonitorUpdateStatus::UnrecoverableError,
}
}
fn update_persisted_channel(
&self, monitor_name: MonitorName, _update: Option<&ChannelMonitorUpdate>,
monitor: &ChannelMonitor<ChannelSigner>,
) -> chain::ChannelMonitorUpdateStatus {
match self.write(
CHANNEL_MONITOR_PERSISTENCE_PRIMARY_NAMESPACE,
CHANNEL_MONITOR_PERSISTENCE_SECONDARY_NAMESPACE,
&monitor_name.to_string(),
monitor.encode(),
) {
Ok(()) => chain::ChannelMonitorUpdateStatus::Completed,
Err(_) => chain::ChannelMonitorUpdateStatus::UnrecoverableError,
}
}
fn archive_persisted_channel(&self, monitor_name: MonitorName) {
let monitor_key = monitor_name.to_string();
let monitor = match self.read(
CHANNEL_MONITOR_PERSISTENCE_PRIMARY_NAMESPACE,
CHANNEL_MONITOR_PERSISTENCE_SECONDARY_NAMESPACE,
monitor_key.as_str(),
) {
Ok(monitor) => monitor,
Err(_) => return,
};
match self.write(
ARCHIVED_CHANNEL_MONITOR_PERSISTENCE_PRIMARY_NAMESPACE,
ARCHIVED_CHANNEL_MONITOR_PERSISTENCE_SECONDARY_NAMESPACE,
monitor_key.as_str(),
monitor,
) {
Ok(()) => {},
Err(_e) => return,
};
let _ = self.remove(
CHANNEL_MONITOR_PERSISTENCE_PRIMARY_NAMESPACE,
CHANNEL_MONITOR_PERSISTENCE_SECONDARY_NAMESPACE,
monitor_key.as_str(),
true,
);
}
}
/// Read previously persisted [`ChannelMonitor`]s from the store.
pub fn read_channel_monitors<K: Deref, ES: Deref, SP: Deref>(
kv_store: K, entropy_source: ES, signer_provider: SP,
) -> Result<Vec<(BlockHash, ChannelMonitor<<SP::Target as SignerProvider>::EcdsaSigner>)>, io::Error>
where
K::Target: KVStoreSync,
ES::Target: EntropySource + Sized,
SP::Target: SignerProvider + Sized,
{
let mut res = Vec::new();
for stored_key in kv_store.list(
CHANNEL_MONITOR_PERSISTENCE_PRIMARY_NAMESPACE,
CHANNEL_MONITOR_PERSISTENCE_SECONDARY_NAMESPACE,
)? {
match <(BlockHash, ChannelMonitor<<SP::Target as SignerProvider>::EcdsaSigner>)>::read(
&mut io::Cursor::new(kv_store.read(
CHANNEL_MONITOR_PERSISTENCE_PRIMARY_NAMESPACE,
CHANNEL_MONITOR_PERSISTENCE_SECONDARY_NAMESPACE,
&stored_key,
)?),
(&*entropy_source, &*signer_provider),
) {
Ok((block_hash, channel_monitor)) => {
let monitor_name = MonitorName::from_str(&stored_key)?;
if channel_monitor.persistence_key() != monitor_name {
return Err(io::Error::new(
io::ErrorKind::InvalidData,
"ChannelMonitor was stored under the wrong key",
));
}
res.push((block_hash, channel_monitor));
},
Err(_) => {
return Err(io::Error::new(
io::ErrorKind::InvalidData,
"Failed to read ChannelMonitor",
))
},
}
}
Ok(res)
}
/// Implements [`Persist`] in a way that writes and reads both [`ChannelMonitor`]s and
/// [`ChannelMonitorUpdate`]s.
///
/// # Overview
///
/// The main benefit this provides over the [`KVStoreSync`]'s [`Persist`] implementation is decreased
/// I/O bandwidth and storage churn, at the expense of more IOPS (including listing, reading, and
/// deleting) and complexity. This is because it writes channel monitor differential updates,
/// whereas the other (default) implementation rewrites the entire monitor on each update. For
/// routing nodes, updates can happen many times per second to a channel, and monitors can be tens
/// of megabytes (or more). Updates can be as small as a few hundred bytes.
///
/// Note that monitors written with `MonitorUpdatingPersister` are _not_ backward-compatible with
/// the default [`KVStoreSync`]'s [`Persist`] implementation. They have a prepended byte sequence,
/// [`MONITOR_UPDATING_PERSISTER_PREPEND_SENTINEL`], applied to prevent deserialization with other
/// persisters. This is because monitors written by this struct _may_ have unapplied updates. In
/// order to downgrade, you must ensure that all updates are applied to the monitor, and remove the
/// sentinel bytes.
///
/// # Storing monitors
///
/// Monitors are stored by implementing the [`Persist`] trait, which has two functions:
///
/// - [`Persist::persist_new_channel`], which persists whole [`ChannelMonitor`]s.
/// - [`Persist::update_persisted_channel`], which persists only a [`ChannelMonitorUpdate`]
///
/// Whole [`ChannelMonitor`]s are stored in the [`CHANNEL_MONITOR_PERSISTENCE_PRIMARY_NAMESPACE`],
/// using the familiar encoding of an [`OutPoint`] (e.g., `[SOME-64-CHAR-HEX-STRING]_1`) for v1
/// channels or a [`ChannelId`] (e.g., `[SOME-64-CHAR-HEX-STRING]`) for v2 channels.
///
/// Each [`ChannelMonitorUpdate`] is stored in a dynamic secondary namespace, as follows:
///
/// - primary namespace: [`CHANNEL_MONITOR_UPDATE_PERSISTENCE_PRIMARY_NAMESPACE`]
/// - secondary namespace: [the monitor's encoded outpoint or channel id name]
///
/// Under that secondary namespace, each update is stored with a number string, like `21`, which
/// represents its `update_id` value.
///
/// For example, consider this channel, named for its transaction ID and index, or [`OutPoint`]:
///
/// - Transaction ID: `deadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeef`
/// - Index: `1`
///
/// Full channel monitors would be stored at a single key:
///
/// `[CHANNEL_MONITOR_PERSISTENCE_PRIMARY_NAMESPACE]/deadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeef_1`
///
/// Updates would be stored as follows (with `/` delimiting primary_namespace/secondary_namespace/key):
///
/// ```text
/// [CHANNEL_MONITOR_UPDATE_PERSISTENCE_PRIMARY_NAMESPACE]/deadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeef_1/1
/// [CHANNEL_MONITOR_UPDATE_PERSISTENCE_PRIMARY_NAMESPACE]/deadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeef_1/2
/// [CHANNEL_MONITOR_UPDATE_PERSISTENCE_PRIMARY_NAMESPACE]/deadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeef_1/3
/// ```
/// ... and so on.
///
/// # Reading channel state from storage
///
/// Channel state can be reconstructed by calling
/// [`MonitorUpdatingPersister::read_all_channel_monitors_with_updates`]. Alternatively, users can
/// list channel monitors themselves and load channels individually using
/// [`MonitorUpdatingPersister::read_channel_monitor_with_updates`].
///
/// ## EXTREMELY IMPORTANT
///
/// It is extremely important that your [`KVStoreSync::read`] implementation uses the
/// [`io::ErrorKind::NotFound`] variant correctly: that is, when a file is not found, and _only_ in
/// that circumstance (not when there is really a permissions error, for example). This is because
/// neither channel monitor reading function lists updates. Instead, either reads the monitor, and
/// using its stored `update_id`, synthesizes update storage keys, and tries them in sequence until
/// one is not found. All _other_ errors will be bubbled up in the function's [`Result`].
///
/// # Pruning stale channel updates
///
/// Stale updates are pruned when the consolidation threshold is reached according to `maximum_pending_updates`.
/// Monitor updates in the range between the latest `update_id` and `update_id - maximum_pending_updates`
/// are deleted.
/// The `lazy` flag is used on the [`KVStoreSync::remove`] method, so there are no guarantees that the deletions
/// will complete. However, stale updates are not a problem for data integrity, since updates are
/// only read that are higher than the stored [`ChannelMonitor`]'s `update_id`.
///
/// If you have many stale updates stored (such as after a crash with pending lazy deletes), and
/// would like to get rid of them, consider using the
/// [`MonitorUpdatingPersister::cleanup_stale_updates`] function.
pub struct MonitorUpdatingPersister<K: Deref, L: Deref, ES: Deref, SP: Deref, BI: Deref, FE: Deref>
where
K::Target: KVStoreSync,
L::Target: Logger,
ES::Target: EntropySource + Sized,
SP::Target: SignerProvider + Sized,
BI::Target: BroadcasterInterface,
FE::Target: FeeEstimator,
{
kv_store: K,
logger: L,
maximum_pending_updates: u64,
entropy_source: ES,
signer_provider: SP,
broadcaster: BI,
fee_estimator: FE,
}
#[allow(dead_code)]
impl<K: Deref, L: Deref, ES: Deref, SP: Deref, BI: Deref, FE: Deref>
MonitorUpdatingPersister<K, L, ES, SP, BI, FE>
where
K::Target: KVStoreSync,
L::Target: Logger,
ES::Target: EntropySource + Sized,
SP::Target: SignerProvider + Sized,
BI::Target: BroadcasterInterface,
FE::Target: FeeEstimator,
{
/// Constructs a new [`MonitorUpdatingPersister`].
///
/// The `maximum_pending_updates` parameter controls how many updates may be stored before a
/// [`MonitorUpdatingPersister`] consolidates updates by writing a full monitor. Note that
/// consolidation will frequently occur with fewer updates than what you set here; this number
/// is merely the maximum that may be stored. When setting this value, consider that for higher
/// values of `maximum_pending_updates`:
///
/// - [`MonitorUpdatingPersister`] will tend to write more [`ChannelMonitorUpdate`]s than
/// [`ChannelMonitor`]s, approaching one [`ChannelMonitor`] write for every
/// `maximum_pending_updates` [`ChannelMonitorUpdate`]s.
/// - [`MonitorUpdatingPersister`] will issue deletes differently. Lazy deletes will come in
/// "waves" for each [`ChannelMonitor`] write. A larger `maximum_pending_updates` means bigger,
/// less frequent "waves."
/// - [`MonitorUpdatingPersister`] will potentially have more listing to do if you need to run
/// [`MonitorUpdatingPersister::cleanup_stale_updates`].
pub fn new(
kv_store: K, logger: L, maximum_pending_updates: u64, entropy_source: ES,
signer_provider: SP, broadcaster: BI, fee_estimator: FE,
) -> Self {
MonitorUpdatingPersister {
kv_store,
logger,
maximum_pending_updates,
entropy_source,
signer_provider,
broadcaster,
fee_estimator,
}
}
/// Reads all stored channel monitors, along with any stored updates for them.
///
/// It is extremely important that your [`KVStoreSync::read`] implementation uses the
/// [`io::ErrorKind::NotFound`] variant correctly. For more information, please see the
/// documentation for [`MonitorUpdatingPersister`].
pub fn read_all_channel_monitors_with_updates(
&self,
) -> Result<
Vec<(BlockHash, ChannelMonitor<<SP::Target as SignerProvider>::EcdsaSigner>)>,
io::Error,
> {
let monitor_list = self.kv_store.list(
CHANNEL_MONITOR_PERSISTENCE_PRIMARY_NAMESPACE,
CHANNEL_MONITOR_PERSISTENCE_SECONDARY_NAMESPACE,
)?;
let mut res = Vec::with_capacity(monitor_list.len());
for monitor_key in monitor_list {
res.push(self.read_channel_monitor_with_updates(monitor_key.as_str())?)
}
Ok(res)
}
/// Read a single channel monitor, along with any stored updates for it.
///
/// It is extremely important that your [`KVStoreSync::read`] implementation uses the
/// [`io::ErrorKind::NotFound`] variant correctly. For more information, please see the
/// documentation for [`MonitorUpdatingPersister`].
///
/// For `monitor_key`, channel storage keys can be the channel's funding [`OutPoint`], with an
/// underscore `_` between txid and index for v1 channels. For example, given:
///
/// - Transaction ID: `deadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeef`
/// - Index: `1`
///
/// The correct `monitor_key` would be:
/// `deadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeef_1`
///
/// For v2 channels, the hex-encoded [`ChannelId`] is used directly for `monitor_key` instead.
///
/// Loading a large number of monitors will be faster if done in parallel. You can use this
/// function to accomplish this. Take care to limit the number of parallel readers.
pub fn read_channel_monitor_with_updates(
&self, monitor_key: &str,
) -> Result<(BlockHash, ChannelMonitor<<SP::Target as SignerProvider>::EcdsaSigner>), io::Error>
{
let monitor_name = MonitorName::from_str(monitor_key)?;
let (block_hash, monitor) = self.read_monitor(&monitor_name, monitor_key)?;
let mut current_update_id = monitor.get_latest_update_id();
loop {
current_update_id = match current_update_id.checked_add(1) {
Some(next_update_id) => next_update_id,
None => break,
};
let update_name = UpdateName::from(current_update_id);
let update = match self.read_monitor_update(monitor_key, &update_name) {
Ok(update) => update,
Err(err) if err.kind() == io::ErrorKind::NotFound => {
// We can't find any more updates, so we are done.
break;
},
Err(err) => return Err(err),
};
monitor
.update_monitor(&update, &self.broadcaster, &self.fee_estimator, &self.logger)
.map_err(|e| {
log_error!(
self.logger,
"Monitor update failed. monitor: {} update: {} reason: {:?}",
monitor_key,
update_name.as_str(),
e
);
io::Error::new(io::ErrorKind::Other, "Monitor update failed")
})?;
}
Ok((block_hash, monitor))
}
/// Read a channel monitor.
fn read_monitor(
&self, monitor_name: &MonitorName, monitor_key: &str,
) -> Result<(BlockHash, ChannelMonitor<<SP::Target as SignerProvider>::EcdsaSigner>), io::Error>
{
let mut monitor_cursor = io::Cursor::new(self.kv_store.read(
CHANNEL_MONITOR_PERSISTENCE_PRIMARY_NAMESPACE,
CHANNEL_MONITOR_PERSISTENCE_SECONDARY_NAMESPACE,
monitor_key,
)?);
// Discard the sentinel bytes if found.
if monitor_cursor.get_ref().starts_with(MONITOR_UPDATING_PERSISTER_PREPEND_SENTINEL) {
monitor_cursor.set_position(MONITOR_UPDATING_PERSISTER_PREPEND_SENTINEL.len() as u64);
}
match <(BlockHash, ChannelMonitor<<SP::Target as SignerProvider>::EcdsaSigner>)>::read(
&mut monitor_cursor,
(&*self.entropy_source, &*self.signer_provider),
) {
Ok((blockhash, channel_monitor)) => {
if channel_monitor.persistence_key() != *monitor_name {
log_error!(
self.logger,
"ChannelMonitor {} was stored under the wrong key!",
monitor_key,
);
Err(io::Error::new(
io::ErrorKind::InvalidData,
"ChannelMonitor was stored under the wrong key",
))
} else {
Ok((blockhash, channel_monitor))
}
},
Err(e) => {
log_error!(
self.logger,
"Failed to read ChannelMonitor {}, reason: {}",
monitor_key,
e,
);
Err(io::Error::new(io::ErrorKind::InvalidData, "Failed to read ChannelMonitor"))
},
}
}
/// Read a channel monitor update.
fn read_monitor_update(
&self, monitor_key: &str, update_name: &UpdateName,
) -> Result<ChannelMonitorUpdate, io::Error> {
let update_bytes = self.kv_store.read(
CHANNEL_MONITOR_UPDATE_PERSISTENCE_PRIMARY_NAMESPACE,
monitor_key,
update_name.as_str(),
)?;
ChannelMonitorUpdate::read(&mut io::Cursor::new(update_bytes)).map_err(|e| {
log_error!(
self.logger,
"Failed to read ChannelMonitorUpdate {}/{}/{}, reason: {}",
CHANNEL_MONITOR_UPDATE_PERSISTENCE_PRIMARY_NAMESPACE,
monitor_key,
update_name.as_str(),
e,
);
io::Error::new(io::ErrorKind::InvalidData, "Failed to read ChannelMonitorUpdate")
})
}
/// Cleans up stale updates for all monitors.
///
/// This function works by first listing all monitors, and then for each of them, listing all
/// updates. The updates that have an `update_id` less than or equal to than the stored monitor
/// are deleted. The deletion can either be lazy or non-lazy based on the `lazy` flag; this will
/// be passed to [`KVStoreSync::remove`].
pub fn cleanup_stale_updates(&self, lazy: bool) -> Result<(), io::Error> {
let monitor_keys = self.kv_store.list(
CHANNEL_MONITOR_PERSISTENCE_PRIMARY_NAMESPACE,
CHANNEL_MONITOR_PERSISTENCE_SECONDARY_NAMESPACE,
)?;
for monitor_key in monitor_keys {
let monitor_name = MonitorName::from_str(&monitor_key)?;
let (_, current_monitor) = self.read_monitor(&monitor_name, &monitor_key)?;
let updates = self
.kv_store
.list(CHANNEL_MONITOR_UPDATE_PERSISTENCE_PRIMARY_NAMESPACE, monitor_key.as_str())?;
for update in updates {
let update_name = UpdateName::new(update)?;
// if the update_id is lower than the stored monitor, delete
if update_name.0 <= current_monitor.get_latest_update_id() {
self.kv_store.remove(
CHANNEL_MONITOR_UPDATE_PERSISTENCE_PRIMARY_NAMESPACE,
monitor_key.as_str(),
update_name.as_str(),
lazy,
)?;
}
}
}
Ok(())
}
}
impl<
ChannelSigner: EcdsaChannelSigner,
K: Deref,
L: Deref,
ES: Deref,
SP: Deref,
BI: Deref,
FE: Deref,
> Persist<ChannelSigner> for MonitorUpdatingPersister<K, L, ES, SP, BI, FE>
where
K::Target: KVStoreSync,
L::Target: Logger,
ES::Target: EntropySource + Sized,
SP::Target: SignerProvider + Sized,
BI::Target: BroadcasterInterface,
FE::Target: FeeEstimator,
{
/// Persists a new channel. This means writing the entire monitor to the
/// parametrized [`KVStoreSync`].
fn persist_new_channel(
&self, monitor_name: MonitorName, monitor: &ChannelMonitor<ChannelSigner>,
) -> chain::ChannelMonitorUpdateStatus {
// Determine the proper key for this monitor
let monitor_key = monitor_name.to_string();
// Serialize and write the new monitor
let mut monitor_bytes = Vec::with_capacity(
MONITOR_UPDATING_PERSISTER_PREPEND_SENTINEL.len() + monitor.serialized_length(),
);
monitor_bytes.extend_from_slice(MONITOR_UPDATING_PERSISTER_PREPEND_SENTINEL);
monitor.write(&mut monitor_bytes).unwrap();
match self.kv_store.write(
CHANNEL_MONITOR_PERSISTENCE_PRIMARY_NAMESPACE,
CHANNEL_MONITOR_PERSISTENCE_SECONDARY_NAMESPACE,
monitor_key.as_str(),
monitor_bytes,
) {
Ok(_) => chain::ChannelMonitorUpdateStatus::Completed,
Err(e) => {
log_error!(
self.logger,
"Failed to write ChannelMonitor {}/{}/{} reason: {}",
CHANNEL_MONITOR_PERSISTENCE_PRIMARY_NAMESPACE,
CHANNEL_MONITOR_PERSISTENCE_SECONDARY_NAMESPACE,
monitor_key.as_str(),
e
);
chain::ChannelMonitorUpdateStatus::UnrecoverableError
},
}
}
/// Persists a channel update, writing only the update to the parameterized [`KVStoreSync`] if possible.
///
/// In some cases, this will forward to [`MonitorUpdatingPersister::persist_new_channel`]:
///
/// - No full monitor is found in [`KVStoreSync`]
/// - The number of pending updates exceeds `maximum_pending_updates` as given to [`Self::new`]
/// - LDK commands re-persisting the entire monitor through this function, specifically when
/// `update` is `None`.
/// - The update is at [`u64::MAX`], indicating an update generated by pre-0.1 LDK.
fn update_persisted_channel(
&self, monitor_name: MonitorName, update: Option<&ChannelMonitorUpdate>,
monitor: &ChannelMonitor<ChannelSigner>,
) -> chain::ChannelMonitorUpdateStatus {
const LEGACY_CLOSED_CHANNEL_UPDATE_ID: u64 = u64::MAX;
if let Some(update) = update {
let persist_update = update.update_id != LEGACY_CLOSED_CHANNEL_UPDATE_ID
&& update.update_id % self.maximum_pending_updates != 0;
if persist_update {
let monitor_key = monitor_name.to_string();
let update_name = UpdateName::from(update.update_id);
match self.kv_store.write(
CHANNEL_MONITOR_UPDATE_PERSISTENCE_PRIMARY_NAMESPACE,
monitor_key.as_str(),
update_name.as_str(),
update.encode(),
) {
Ok(()) => chain::ChannelMonitorUpdateStatus::Completed,
Err(e) => {
log_error!(
self.logger,
"Failed to write ChannelMonitorUpdate {}/{}/{} reason: {}",
CHANNEL_MONITOR_UPDATE_PERSISTENCE_PRIMARY_NAMESPACE,
monitor_key.as_str(),
update_name.as_str(),
e
);
chain::ChannelMonitorUpdateStatus::UnrecoverableError
},
}
} else {
// In case of channel-close monitor update, we need to read old monitor before persisting
// the new one in order to determine the cleanup range.
let maybe_old_monitor = match monitor.get_latest_update_id() {
LEGACY_CLOSED_CHANNEL_UPDATE_ID => {
let monitor_key = monitor_name.to_string();
self.read_monitor(&monitor_name, &monitor_key).ok()
},
_ => None,
};
// We could write this update, but it meets criteria of our design that calls for a full monitor write.
let monitor_update_status = self.persist_new_channel(monitor_name, monitor);
if let chain::ChannelMonitorUpdateStatus::Completed = monitor_update_status {
let channel_closed_legacy =
monitor.get_latest_update_id() == LEGACY_CLOSED_CHANNEL_UPDATE_ID;
let cleanup_range = if channel_closed_legacy {
// If there is an error while reading old monitor, we skip clean up.
maybe_old_monitor.map(|(_, ref old_monitor)| {
let start = old_monitor.get_latest_update_id();
// We never persist an update with the legacy closed update_id
let end = cmp::min(
start.saturating_add(self.maximum_pending_updates),
LEGACY_CLOSED_CHANNEL_UPDATE_ID - 1,
);
(start, end)
})
} else {
let end = monitor.get_latest_update_id();
let start = end.saturating_sub(self.maximum_pending_updates);
Some((start, end))
};
if let Some((start, end)) = cleanup_range {
self.cleanup_in_range(monitor_name, start, end);
}
}
monitor_update_status
}
} else {
// There is no update given, so we must persist a new monitor.
self.persist_new_channel(monitor_name, monitor)
}
}
fn archive_persisted_channel(&self, monitor_name: MonitorName) {
let monitor_key = monitor_name.to_string();
let monitor = match self.read_channel_monitor_with_updates(&monitor_key) {
Ok((_block_hash, monitor)) => monitor,
Err(_) => return,
};
match self.kv_store.write(
ARCHIVED_CHANNEL_MONITOR_PERSISTENCE_PRIMARY_NAMESPACE,
ARCHIVED_CHANNEL_MONITOR_PERSISTENCE_SECONDARY_NAMESPACE,
monitor_key.as_str(),
monitor.encode(),
) {
Ok(()) => {},
Err(_e) => return,
};
let _ = self.kv_store.remove(
CHANNEL_MONITOR_PERSISTENCE_PRIMARY_NAMESPACE,
CHANNEL_MONITOR_PERSISTENCE_SECONDARY_NAMESPACE,
monitor_key.as_str(),
true,
);
}
}
impl<K: Deref, L: Deref, ES: Deref, SP: Deref, BI: Deref, FE: Deref>
MonitorUpdatingPersister<K, L, ES, SP, BI, FE>
where
ES::Target: EntropySource + Sized,
K::Target: KVStoreSync,
L::Target: Logger,
SP::Target: SignerProvider + Sized,
BI::Target: BroadcasterInterface,
FE::Target: FeeEstimator,
{
// Cleans up monitor updates for given monitor in range `start..=end`.
fn cleanup_in_range(&self, monitor_name: MonitorName, start: u64, end: u64) {
let monitor_key = monitor_name.to_string();
for update_id in start..=end {
let update_name = UpdateName::from(update_id);
if let Err(e) = self.kv_store.remove(
CHANNEL_MONITOR_UPDATE_PERSISTENCE_PRIMARY_NAMESPACE,
monitor_key.as_str(),
update_name.as_str(),
true,
) {
log_error!(
self.logger,
"Failed to clean up channel monitor updates for monitor {}, reason: {}",
monitor_key.as_str(),
e
);
};
}
}
}
/// A struct representing a name for a channel monitor.
///
/// `MonitorName` is primarily used within the [`MonitorUpdatingPersister`]
/// in functions that store or retrieve [`ChannelMonitor`] snapshots.
/// It provides a consistent way to generate a unique key for channel
/// monitors based on the channel's funding [`OutPoint`] for v1 channels or
/// [`ChannelId`] for v2 channels. Use [`ChannelMonitor::persistence_key`] to
/// obtain the correct `MonitorName`.
///
/// While users of the Lightning Dev Kit library generally won't need
/// to interact with [`MonitorName`] directly, it can be useful for:
/// - Custom persistence implementations
/// - Debugging or logging channel monitor operations
/// - Extending the functionality of the `MonitorUpdatingPersister`
///
/// # Examples
///
/// ```
/// use std::str::FromStr;
///
/// use bitcoin::Txid;
/// use bitcoin::hashes::hex::FromHex;
///
/// use lightning::util::persist::MonitorName;
/// use lightning::chain::transaction::OutPoint;
/// use lightning::ln::types::ChannelId;
///
/// // v1 channel
/// let outpoint = OutPoint {
/// txid: Txid::from_str("deadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeef").unwrap(),
/// index: 1,
/// };
/// let monitor_name = MonitorName::V1Channel(outpoint);
/// assert_eq!(&monitor_name.to_string(), "deadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeef_1");
///
/// // v2 channel
/// let channel_id = ChannelId(<[u8; 32]>::from_hex("deadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeef").unwrap());
/// let monitor_name = MonitorName::V2Channel(channel_id);
/// assert_eq!(&monitor_name.to_string(), "deadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeef");
///
/// // Using MonitorName to generate a storage key
/// let storage_key = format!("channel_monitors/{}", monitor_name);
/// ```
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
pub enum MonitorName {
/// The outpoint of the channel's funding transaction.
V1Channel(OutPoint),
/// The id of the channel produced by [`ChannelId::v2_from_revocation_basepoints`].
V2Channel(ChannelId),
}
impl MonitorName {
/// Attempts to construct a `MonitorName` from a storage key returned by [`KVStoreSync::list`].
///
/// This is useful when you need to reconstruct the original data the key represents.
fn from_str(monitor_key: &str) -> Result<Self, io::Error> {
let mut parts = monitor_key.splitn(2, '_');
let id = parts
.next()
.ok_or_else(|| io::Error::new(io::ErrorKind::InvalidData, "Empty stored key"))?;
if let Some(part) = parts.next() {
let txid = Txid::from_str(id).map_err(|_| {
io::Error::new(io::ErrorKind::InvalidData, "Invalid tx ID in stored key")
})?;
let index: u16 = part.parse().map_err(|_| {
io::Error::new(io::ErrorKind::InvalidData, "Invalid tx index in stored key")
})?;
let outpoint = OutPoint { txid, index };
Ok(MonitorName::V1Channel(outpoint))
} else {
let bytes = <[u8; 32]>::from_hex(id).map_err(|_| {
io::Error::new(io::ErrorKind::InvalidData, "Invalid channel ID in stored key")
})?;
Ok(MonitorName::V2Channel(ChannelId(bytes)))