+ Err(_) => chain::ChannelMonitorUpdateStatus::UnrecoverableError
+ }
+ }
+}
+
+/// 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: KVStore,
+ 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)?
+ {
+ if stored_key.len() < 66 {
+ return Err(io::Error::new(
+ io::ErrorKind::InvalidData,
+ "Stored key has invalid length"));
+ }
+
+ let txid = Txid::from_str(stored_key.split_at(64).0).map_err(|_| {
+ io::Error::new(io::ErrorKind::InvalidData, "Invalid tx ID in stored key")
+ })?;
+
+ let index: u16 = stored_key.split_at(65).1.parse().map_err(|_| {
+ io::Error::new(io::ErrorKind::InvalidData, "Invalid tx index in stored key")
+ })?;
+
+ 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)) => {
+ if channel_monitor.get_funding_txo().0.txid != txid
+ || channel_monitor.get_funding_txo().0.index != index
+ {
+ 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 [`KVStore`]'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 [`KVStore`]'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`] (for example, `[SOME-64-CHAR-HEX-STRING]_1`).
+///
+/// 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 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 [`KVStore::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 [`KVStore::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>
+where
+ K::Target: KVStore,
+ L::Target: Logger,
+ ES::Target: EntropySource + Sized,
+ SP::Target: SignerProvider + Sized,
+{
+ kv_store: K,
+ logger: L,
+ maximum_pending_updates: u64,
+ entropy_source: ES,
+ signer_provider: SP,
+}
+
+#[allow(dead_code)]
+impl<K: Deref, L: Deref, ES: Deref, SP: Deref>
+ MonitorUpdatingPersister<K, L, ES, SP>
+where
+ K::Target: KVStore,
+ L::Target: Logger,
+ ES::Target: EntropySource + Sized,
+ SP::Target: SignerProvider + Sized,
+{
+ /// 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,
+ ) -> Self {
+ MonitorUpdatingPersister {
+ kv_store,
+ logger,
+ maximum_pending_updates,
+ entropy_source,
+ signer_provider,
+ }
+ }
+
+ /// Reads all stored channel monitors, along with any stored updates for them.
+ ///
+ /// It is extremely important that your [`KVStore::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<B: Deref, F: Deref>(
+ &self, broadcaster: &B, fee_estimator: &F,
+ ) -> Result<Vec<(BlockHash, ChannelMonitor<<SP::Target as SignerProvider>::EcdsaSigner>)>, io::Error>
+ where
+ B::Target: BroadcasterInterface,
+ F::Target: FeeEstimator,
+ {
+ 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(
+ broadcaster,
+ fee_estimator,
+ monitor_key,
+ )?)
+ }
+ Ok(res)
+ }
+
+ /// Read a single channel monitor, along with any stored updates for it.
+ ///
+ /// It is extremely important that your [`KVStore::read`] implementation uses the
+ /// [`io::ErrorKind::NotFound`] variant correctly. For more information, please see the
+ /// documentation for [`MonitorUpdatingPersister`].
+ ///
+ /// For `monitor_key`, channel storage keys be the channel's transaction ID and index, or
+ /// [`OutPoint`], with an underscore `_` between them. For example, given:
+ ///
+ /// - Transaction ID: `deadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeef`
+ /// - Index: `1`
+ ///
+ /// The correct `monitor_key` would be:
+ /// `deadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeef_1`
+ ///
+ /// 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<B: Deref, F: Deref>(
+ &self, broadcaster: &B, fee_estimator: &F, monitor_key: String,
+ ) -> Result<(BlockHash, ChannelMonitor<<SP::Target as SignerProvider>::EcdsaSigner>), io::Error>
+ where
+ B::Target: BroadcasterInterface,
+ F::Target: FeeEstimator,
+ {
+ let monitor_name = MonitorName::new(monitor_key)?;
+ let (block_hash, monitor) = self.read_monitor(&monitor_name)?;
+ 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_name, &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, broadcaster, fee_estimator, &self.logger)
+ .map_err(|e| {
+ log_error!(
+ self.logger,
+ "Monitor update failed. monitor: {} update: {} reason: {:?}",
+ monitor_name.as_str(),
+ 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,
+ ) -> Result<(BlockHash, ChannelMonitor<<SP::Target as SignerProvider>::EcdsaSigner>), io::Error> {
+ let outpoint: OutPoint = monitor_name.try_into()?;
+ let mut monitor_cursor = io::Cursor::new(self.kv_store.read(
+ CHANNEL_MONITOR_PERSISTENCE_PRIMARY_NAMESPACE,
+ CHANNEL_MONITOR_PERSISTENCE_SECONDARY_NAMESPACE,
+ monitor_name.as_str(),
+ )?);
+ // 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.get_funding_txo().0.txid != outpoint.txid
+ || channel_monitor.get_funding_txo().0.index != outpoint.index
+ {
+ log_error!(
+ self.logger,
+ "ChannelMonitor {} was stored under the wrong key!",
+ monitor_name.as_str()
+ );
+ 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_name.as_str(),
+ e,
+ );
+ Err(io::Error::new(io::ErrorKind::InvalidData, "Failed to read ChannelMonitor"))
+ }
+ }
+ }
+
+ /// Read a channel monitor update.
+ fn read_monitor_update(
+ &self, monitor_name: &MonitorName, update_name: &UpdateName,
+ ) -> Result<ChannelMonitorUpdate, io::Error> {
+ let update_bytes = self.kv_store.read(
+ CHANNEL_MONITOR_UPDATE_PERSISTENCE_PRIMARY_NAMESPACE,
+ monitor_name.as_str(),
+ 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_name.as_str(),
+ 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 [`KVStore::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::new(monitor_key)?;
+ let (_, current_monitor) = self.read_monitor(&monitor_name)?;
+ let updates = self
+ .kv_store
+ .list(CHANNEL_MONITOR_UPDATE_PERSISTENCE_PRIMARY_NAMESPACE, monitor_name.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_name.as_str(),
+ update_name.as_str(),
+ lazy,
+ )?;
+ }
+ }
+ }
+ Ok(())
+ }
+}
+
+impl<ChannelSigner: WriteableEcdsaChannelSigner, K: Deref, L: Deref, ES: Deref, SP: Deref>
+ Persist<ChannelSigner> for MonitorUpdatingPersister<K, L, ES, SP>
+where
+ K::Target: KVStore,
+ L::Target: Logger,
+ ES::Target: EntropySource + Sized,
+ SP::Target: SignerProvider + Sized,
+{
+ /// Persists a new channel. This means writing the entire monitor to the
+ /// parametrized [`KVStore`].
+ fn persist_new_channel(
+ &self, funding_txo: OutPoint, monitor: &ChannelMonitor<ChannelSigner>,
+ _monitor_update_call_id: MonitorUpdateId,
+ ) -> chain::ChannelMonitorUpdateStatus {
+ // Determine the proper key for this monitor
+ let monitor_name = MonitorName::from(funding_txo);
+ // 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_name.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_name.as_str(),
+ e
+ );
+ chain::ChannelMonitorUpdateStatus::UnrecoverableError
+ }
+ }
+ }
+
+ /// Persists a channel update, writing only the update to the parameterized [`KVStore`] if possible.
+ ///
+ /// In some cases, this will forward to [`MonitorUpdatingPersister::persist_new_channel`]:
+ ///
+ /// - No full monitor is found in [`KVStore`]
+ /// - 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 [`CLOSED_CHANNEL_UPDATE_ID`]
+ fn update_persisted_channel(
+ &self, funding_txo: OutPoint, update: Option<&ChannelMonitorUpdate>,
+ monitor: &ChannelMonitor<ChannelSigner>, monitor_update_call_id: MonitorUpdateId,
+ ) -> chain::ChannelMonitorUpdateStatus {
+ // IMPORTANT: monitor_update_call_id: MonitorUpdateId is not to be confused with
+ // ChannelMonitorUpdate's update_id.
+ if let Some(update) = update {
+ if update.update_id != CLOSED_CHANNEL_UPDATE_ID
+ && update.update_id % self.maximum_pending_updates != 0
+ {
+ let monitor_name = MonitorName::from(funding_txo);
+ let update_name = UpdateName::from(update.update_id);
+ match self.kv_store.write(
+ CHANNEL_MONITOR_UPDATE_PERSISTENCE_PRIMARY_NAMESPACE,
+ monitor_name.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_name.as_str(),
+ update_name.as_str(),
+ e
+ );
+ chain::ChannelMonitorUpdateStatus::UnrecoverableError
+ }
+ }
+ } else {
+ let monitor_name = MonitorName::from(funding_txo);
+ // 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() {
+ CLOSED_CHANNEL_UPDATE_ID => self.read_monitor(&monitor_name).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(funding_txo, monitor, monitor_update_call_id);
+
+ if let chain::ChannelMonitorUpdateStatus::Completed = monitor_update_status {
+ let cleanup_range = if monitor.get_latest_update_id() == CLOSED_CHANNEL_UPDATE_ID {
+ // 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 update_id = CLOSED_CHANNEL_UPDATE_ID
+ let end = cmp::min(
+ start.saturating_add(self.maximum_pending_updates),
+ 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(funding_txo, monitor, monitor_update_call_id)
+ }
+ }
+}
+
+impl<K: Deref, L: Deref, ES: Deref, SP: Deref> MonitorUpdatingPersister<K, L, ES, SP>
+where
+ ES::Target: EntropySource + Sized,
+ K::Target: KVStore,
+ L::Target: Logger,
+ SP::Target: SignerProvider + Sized
+{
+ // Cleans up monitor updates for given monitor in range `start..=end`.
+ fn cleanup_in_range(&self, monitor_name: MonitorName, start: u64, end: u64) {
+ 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_name.as_str(),
+ update_name.as_str(),
+ true,
+ ) {
+ log_error!(
+ self.logger,
+ "Failed to clean up channel monitor updates for monitor {}, reason: {}",
+ monitor_name.as_str(),
+ e
+ );
+ };
+ }
+ }
+}
+
+/// A struct representing a name for a monitor.
+#[derive(Debug)]
+struct MonitorName(String);
+
+impl MonitorName {
+ /// Constructs a [`MonitorName`], after verifying that an [`OutPoint`] can
+ /// be formed from the given `name`.
+ pub fn new(name: String) -> Result<Self, io::Error> {
+ MonitorName::do_try_into_outpoint(&name)?;
+ Ok(Self(name))
+ }
+ /// Convert this monitor name to a str.
+ pub fn as_str(&self) -> &str {
+ &self.0
+ }
+ /// Attempt to form a valid [`OutPoint`] from a given name string.
+ fn do_try_into_outpoint(name: &str) -> Result<OutPoint, io::Error> {
+ let mut parts = name.splitn(2, '_');
+ let txid = if let Some(part) = parts.next() {
+ Txid::from_str(part).map_err(|_| {
+ io::Error::new(io::ErrorKind::InvalidData, "Invalid tx ID in stored key")
+ })?
+ } else {
+ return Err(io::Error::new(
+ io::ErrorKind::InvalidData,
+ "Stored monitor key is not a splittable string",
+ ));
+ };
+ let index = if let Some(part) = parts.next() {
+ part.parse().map_err(|_| {
+ io::Error::new(io::ErrorKind::InvalidData, "Invalid tx index in stored key")
+ })?
+ } else {
+ return Err(io::Error::new(
+ io::ErrorKind::InvalidData,
+ "No tx index value found after underscore in stored key",
+ ));
+ };
+ Ok(OutPoint { txid, index })
+ }
+}
+
+impl TryFrom<&MonitorName> for OutPoint {
+ type Error = io::Error;
+
+ fn try_from(value: &MonitorName) -> Result<Self, io::Error> {
+ MonitorName::do_try_into_outpoint(&value.0)
+ }
+}
+
+impl From<OutPoint> for MonitorName {
+ fn from(value: OutPoint) -> Self {
+ MonitorName(format!("{}_{}", value.txid.to_string(), value.index))
+ }
+}
+
+/// A struct representing a name for an update.
+#[derive(Debug)]
+struct UpdateName(u64, String);
+
+impl UpdateName {
+ /// Constructs an [`UpdateName`], after verifying that an update sequence ID
+ /// can be derived from the given `name`.
+ pub fn new(name: String) -> Result<Self, io::Error> {
+ match name.parse::<u64>() {
+ Ok(u) => Ok(u.into()),
+ Err(_) => {
+ Err(io::Error::new(io::ErrorKind::InvalidData, "cannot parse u64 from update name"))
+ }