Skip to content

Commit

Permalink
Cleanup channel closure handling
Browse files Browse the repository at this point in the history
  • Loading branch information
benthecarman committed Feb 3, 2024
1 parent 8337681 commit 074a546
Show file tree
Hide file tree
Showing 5 changed files with 37 additions and 43 deletions.
23 changes: 6 additions & 17 deletions mutiny-core/src/ldkstorage.rs
Original file line number Diff line number Diff line change
Expand Up @@ -388,28 +388,17 @@ impl<S: MutinyStorage> MutinyNodePersister<S> {
"{CHANNEL_CLOSURE_PREFIX}{}",
user_channel_id.to_be_bytes().to_hex()
));
self.storage.get_data(key)
self.storage.get_channel_closure(&key)
}

pub(crate) fn list_channel_closures(&self) -> Result<Vec<(u128, ChannelClosure)>, MutinyError> {
pub(crate) fn list_channel_closures(&self) -> Result<Vec<ChannelClosure>, MutinyError> {
let suffix = format!("_{}", self.node_id);
let map: HashMap<String, ChannelClosure> =
self.storage.scan(CHANNEL_CLOSURE_PREFIX, Some(&suffix))?;

Ok(map
.into_iter()
.map(|(key, value)| {
// convert keys to u128
let user_channel_id_str = key
.trim_start_matches(CHANNEL_CLOSURE_PREFIX)
.trim_end_matches(&suffix);
let user_channel_id: [u8; 16] = FromHex::from_hex(user_channel_id_str)
.unwrap_or_else(|_| panic!("key should be a u128 got {user_channel_id_str}"));

let user_channel_id = u128::from_be_bytes(user_channel_id);
(user_channel_id, value)
})
.collect())
map.into_iter()
.map(|(key, mut closure)| closure.set_user_channel_id_from_key(&key).map(|_| closure))
.collect::<Result<Vec<_>, _>>()
}

/// Persists the failed spendable outputs to storage.
Expand Down Expand Up @@ -806,7 +795,7 @@ mod test {
assert!(result.is_ok());

let result = persister.list_channel_closures().unwrap();
assert_eq!(result, vec![(user_channel_id, closure.clone())]);
assert_eq!(result, vec![closure.clone()]);

let result = persister.get_channel_closure(user_channel_id).unwrap();
assert_eq!(result, Some(closure));
Expand Down
12 changes: 1 addition & 11 deletions mutiny-core/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1506,17 +1506,7 @@ impl<S: MutinyStorage> MutinyWallet<S> {
activities.push(ActivityItem::Lightning(Box::new(mutiny_invoice)));
}
} else if item.key.starts_with(CHANNEL_CLOSURE_PREFIX) {
if let Some(mut closure) = self.storage.get_data::<ChannelClosure>(&item.key)? {
if closure.user_channel_id.is_none() {
// convert keys to u128
let user_channel_id_str = item
.key
.trim_start_matches(CHANNEL_CLOSURE_PREFIX)
.splitn(2, '_') // Channel closures have `_{node_id}` at the end
.collect::<Vec<&str>>()[0];
let user_channel_id: [u8; 16] = FromHex::from_hex(user_channel_id_str)?;
closure.user_channel_id = Some(user_channel_id);
}
if let Some(closure) = self.storage.get_channel_closure(&item.key)? {
activities.push(ActivityItem::ChannelClosed(closure));
}
} else if item.key.starts_with(ONCHAIN_PREFIX) {
Expand Down
14 changes: 1 addition & 13 deletions mutiny-core/src/node.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1295,19 +1295,7 @@ impl<S: MutinyStorage> Node<S> {

/// Gets all the closed channels for this node
pub fn get_channel_closures(&self) -> Result<Vec<ChannelClosure>, MutinyError> {
Ok(self
.persister
.list_channel_closures()?
.into_iter()
.map(|(id, mut c)| {
// some old closures might not have the user_channel_id set
// we set it here to avoid breaking the API
if c.user_channel_id.is_none() {
c.user_channel_id = Some(id.to_be_bytes())
}
c
})
.collect())
self.persister.list_channel_closures()
}

pub fn get_payment_info_from_persisters(
Expand Down
19 changes: 18 additions & 1 deletion mutiny-core/src/nodemanager.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
use crate::event::HTLCStatus;
use crate::labels::LabelStorage;
use crate::ldkstorage::CHANNEL_CLOSURE_PREFIX;
use crate::logging::LOGGING_KEY;
use crate::utils::{sleep, spawn};
use crate::ActivityItem;
Expand Down Expand Up @@ -27,7 +28,7 @@ use anyhow::anyhow;
use bdk::chain::{BlockId, ConfirmationTime};
use bdk::{wallet::AddressIndex, FeeRate, LocalUtxo};
use bitcoin::blockdata::script;
use bitcoin::hashes::hex::ToHex;
use bitcoin::hashes::hex::{FromHex, ToHex};
use bitcoin::hashes::sha256;
use bitcoin::psbt::PartiallySignedTransaction;
use bitcoin::secp256k1::PublicKey;
Expand Down Expand Up @@ -247,6 +248,22 @@ impl ChannelClosure {
timestamp: utils::now().as_secs(),
}
}

pub(crate) fn set_user_channel_id_from_key(&mut self, key: &str) -> Result<(), MutinyError> {
if self.user_channel_id.is_some() {
return Ok(());
}

// convert keys to u128
let user_channel_id_str = key
.trim_start_matches(CHANNEL_CLOSURE_PREFIX)
.splitn(2, '_') // Channel closures have `_{node_id}` at the end
.collect::<Vec<&str>>()[0];
let user_channel_id: [u8; 16] = FromHex::from_hex(user_channel_id_str)?;
self.user_channel_id = Some(user_channel_id);

Ok(())
}
}

impl PartialOrd for ChannelClosure {
Expand Down
12 changes: 11 additions & 1 deletion mutiny-core/src/storage.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use crate::event::HTLCStatus;
use crate::logging::MutinyLogger;
use crate::nodemanager::{NodeStorage, DEVICE_LOCK_INTERVAL_SECS};
use crate::nodemanager::{ChannelClosure, NodeStorage, DEVICE_LOCK_INTERVAL_SECS};
use crate::utils::{now, spawn};
use crate::vss::{MutinyVssClient, VssKeyValueItem};
use crate::{
Expand Down Expand Up @@ -500,6 +500,16 @@ pub trait MutinyStorage: Clone + Sized + Send + Sync + 'static {
self.set_data(FEE_ESTIMATES_KEY.to_string(), fees, None)
}

/// Gets a channel closure and handles setting the user_channel_id if needed
fn get_channel_closure(&self, key: &str) -> Result<Option<ChannelClosure>, MutinyError> {
if let Some(mut closure) = self.get_data::<ChannelClosure>(key)? {
closure.set_user_channel_id_from_key(key)?;
Ok(Some(closure))
} else {
Ok(None)
}
}

/// Get the current bitcoin price cache from storage
fn get_bitcoin_price_cache(&self) -> Result<HashMap<String, f32>, MutinyError> {
Ok(self.get_data(BITCOIN_PRICE_CACHE_KEY)?.unwrap_or_default())
Expand Down

0 comments on commit 074a546

Please sign in to comment.