Skip to content

Commit

Permalink
Refactor NWC to take MutinyWallet
Browse files Browse the repository at this point in the history
  • Loading branch information
TonyGiorgio committed Dec 20, 2023
1 parent 5a78fc2 commit 1f1a398
Show file tree
Hide file tree
Showing 7 changed files with 146 additions and 105 deletions.
36 changes: 31 additions & 5 deletions mutiny-core/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,7 @@ use bip39::Mnemonic;
use bitcoin::util::bip32::ExtendedPrivKey;
use bitcoin::Network;
use bitcoin::{hashes::sha256, secp256k1::PublicKey};
use fedimint_core::{api::InviteCode, config::FederationId};
use fedimint_core::{api::InviteCode, config::FederationId, BitcoinHash};
use futures::{pin_mut, select, FutureExt};
use futures_util::lock::Mutex;
use lightning::{log_debug, util::logger::Logger};
Expand All @@ -93,15 +93,14 @@ use mockall::{automock, predicate::*};
const DEFAULT_PAYMENT_TIMEOUT: u64 = 30;

#[cfg_attr(test, automock)]
pub(crate) trait LnPayer {
pub trait LnPayer {
fn logger(&self) -> &MutinyLogger;
fn skip_hodl_invoices(&self) -> bool;
fn get_outbound_payment_status(&self, payment_hash: &[u8; 32]) -> Option<HTLCStatus>;
async fn get_outbound_payment_status(&self, payment_hash: &[u8; 32]) -> Option<HTLCStatus>;
async fn pay_invoice_with_timeout(
&self,
invoice: &Bolt11Invoice,
amt_sats: Option<u64>,
timeout_secs: Option<u64>,
labels: Vec<String>,
) -> Result<MutinyInvoice, MutinyError>;
}
Expand Down Expand Up @@ -440,6 +439,7 @@ impl<S: MutinyStorage> MutinyWallet<S> {
pub(crate) async fn start_nostr_wallet_connect(&self, from_node: PublicKey) {
let nostr = self.nostr.clone();
let nm = self.node_manager.clone();
let self_clone = self.clone();
utils::spawn(async move {
loop {
if nm.stop.load(Ordering::Relaxed) {
Expand Down Expand Up @@ -514,7 +514,7 @@ impl<S: MutinyStorage> MutinyWallet<S> {
match notification {
Ok(RelayPoolNotification::Event(_url, event)) => {
if event.kind == Kind::WalletConnectRequest && event.verify().is_ok() {
match nostr.handle_nwc_request(event, &nm, &from_node).await {
match nostr.handle_nwc_request(event, &self_clone).await {
Ok(Some(event)) => {
if let Err(e) = client.send_event(event).await {
log_warn!(nm.logger, "Error sending NWC event: {e}");
Expand Down Expand Up @@ -1133,6 +1133,32 @@ impl<S: MutinyStorage> MutinyWallet<S> {
}
}

impl<S: MutinyStorage> LnPayer for MutinyWallet<S> {
fn logger(&self) -> &MutinyLogger {
self.logger.as_ref()
}

fn skip_hodl_invoices(&self) -> bool {
self.config.skip_hodl_invoices
}

async fn get_outbound_payment_status(&self, payment_hash: &[u8; 32]) -> Option<HTLCStatus> {
self.get_invoice_by_hash(&sha256::Hash::hash(payment_hash))
.await
.ok()
.map(|p| p.status)
}

async fn pay_invoice_with_timeout(
&self,
invoice: &Bolt11Invoice,
amt_sats: Option<u64>,
labels: Vec<String>,
) -> Result<MutinyInvoice, MutinyError> {
self.pay_invoice(invoice, amt_sats, labels).await
}
}

async fn create_federations<S: MutinyStorage>(
storage: &S,
c: &MutinyWalletConfig,
Expand Down
35 changes: 1 addition & 34 deletions mutiny-core/src/node.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
use crate::ldkstorage::{persist_monitor, ChannelOpenParams};
use crate::lsp::{InvoiceRequest, LspConfig};
use crate::messagehandler::MutinyMessageHandler;
use crate::nodemanager::ChannelClosure;
Expand All @@ -22,10 +23,6 @@ use crate::{
use crate::{fees::P2WSH_OUTPUT_SIZE, peermanager::connect_peer_if_necessary};
use crate::{keymanager::PhantomKeysManager, scorer::HubPreferentialScorer};
use crate::{labels::LabelStorage, DEFAULT_PAYMENT_TIMEOUT};
use crate::{
ldkstorage::{persist_monitor, ChannelOpenParams},
LnPayer,
};
use anyhow::{anyhow, Context};
use bdk::FeeRate;
use bitcoin::hashes::{hex::ToHex, sha256::Hash as Sha256};
Expand Down Expand Up @@ -186,7 +183,6 @@ pub(crate) struct Node<S: MutinyStorage> {
pub(crate) lsp_client: Option<AnyLsp<S>>,
pub(crate) sync_lock: Arc<Mutex<()>>,
stop: Arc<AtomicBool>,
pub skip_hodl_invoices: bool,
#[cfg(target_arch = "wasm32")]
websocket_proxy_addr: String,
}
Expand All @@ -209,7 +205,6 @@ impl<S: MutinyStorage> Node<S> {
logger: Arc<MutinyLogger>,
do_not_connect_peers: bool,
empty_state: bool,
skip_hodl_invoices: bool,
#[cfg(target_arch = "wasm32")] websocket_proxy_addr: String,
) -> Result<Self, MutinyError> {
log_info!(logger, "initializing a new node: {uuid}");
Expand Down Expand Up @@ -728,7 +723,6 @@ impl<S: MutinyStorage> Node<S> {
lsp_client,
sync_lock,
stop,
skip_hodl_invoices,
#[cfg(target_arch = "wasm32")]
websocket_proxy_addr,
})
Expand Down Expand Up @@ -2057,33 +2051,6 @@ pub(crate) fn default_user_config() -> UserConfig {
}
}

impl<S: MutinyStorage> LnPayer for Node<S> {
fn logger(&self) -> &MutinyLogger {
self.logger.as_ref()
}

fn skip_hodl_invoices(&self) -> bool {
self.skip_hodl_invoices
}

fn get_outbound_payment_status(&self, payment_hash: &[u8; 32]) -> Option<HTLCStatus> {
self.persister
.read_payment_info(payment_hash, false, &self.logger)
.map(|p| p.status)
}

async fn pay_invoice_with_timeout(
&self,
invoice: &Bolt11Invoice,
amt_sats: Option<u64>,
timeout_secs: Option<u64>,
labels: Vec<String>,
) -> Result<MutinyInvoice, MutinyError> {
self.pay_invoice_with_timeout(invoice, amt_sats, timeout_secs, labels)
.await
}
}

#[cfg(test)]
#[cfg(not(target_arch = "wasm32"))]
mod tests {
Expand Down
4 changes: 0 additions & 4 deletions mutiny-core/src/nodemanager.rs
Original file line number Diff line number Diff line change
Expand Up @@ -433,7 +433,6 @@ pub struct NodeManager<S: MutinyStorage> {
pub(crate) logger: Arc<MutinyLogger>,
bitcoin_price_cache: Arc<Mutex<HashMap<String, (f32, Duration)>>>,
do_not_connect_peers: bool,
skip_hodl_invoices: bool,
pub safe_mode: bool,
}

Expand Down Expand Up @@ -580,7 +579,6 @@ impl<S: MutinyStorage> NodeManager<S> {
logger.clone(),
c.do_not_connect_peers,
false,
c.skip_hodl_invoices,
#[cfg(target_arch = "wasm32")]
websocket_proxy_addr.clone(),
)
Expand Down Expand Up @@ -667,7 +665,6 @@ impl<S: MutinyStorage> NodeManager<S> {
bitcoin_price_cache: Arc::new(Mutex::new(price_cache)),
do_not_connect_peers: c.do_not_connect_peers,
safe_mode: c.safe_mode,
skip_hodl_invoices: c.skip_hodl_invoices,
};

Ok(nm)
Expand Down Expand Up @@ -2382,7 +2379,6 @@ pub(crate) async fn create_new_node_from_node_manager<S: MutinyStorage>(
node_manager.logger.clone(),
node_manager.do_not_connect_peers,
false,
node_manager.skip_hodl_invoices,
#[cfg(target_arch = "wasm32")]
node_manager.websocket_proxy_addr.clone(),
)
Expand Down
16 changes: 6 additions & 10 deletions mutiny-core/src/nostr/mod.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
use crate::labels::LabelStorage;
use crate::logging::MutinyLogger;
use crate::node::Node;
use crate::nodemanager::NodeManager;
Expand All @@ -10,10 +9,11 @@ use crate::nostr::nwc::{
};
use crate::storage::MutinyStorage;
use crate::{error::MutinyError, utils::get_random_bip32_child_index};
use crate::{labels::LabelStorage, LnPayer};
use crate::{utils, HTLCStatus};
use bitcoin::hashes::hex::{FromHex, ToHex};
use bitcoin::hashes::{sha256, Hash};
use bitcoin::secp256k1::{PublicKey, Secp256k1, Signing};
use bitcoin::secp256k1::{Secp256k1, Signing};
use bitcoin::util::bip32::{ChildNumber, DerivationPath, ExtendedPrivKey};
use futures::{pin_mut, select, FutureExt};
use futures_util::lock::Mutex;
Expand Down Expand Up @@ -586,13 +586,11 @@ impl<S: MutinyStorage> NostrManager<S> {
pub async fn approve_invoice(
&self,
hash: sha256::Hash,
node_manager: &NodeManager<S>,
from_node: &PublicKey,
payer: &impl LnPayer,
) -> Result<EventId, MutinyError> {
let (nwc, inv) = self.find_nwc_data(&hash)?;

let node = node_manager.get_node(from_node).await?;
let resp = nwc.pay_nwc_invoice(node.as_ref(), &inv.invoice).await?;
let resp = nwc.pay_nwc_invoice(payer, &inv.invoice).await?;

let event_id = self.broadcast_nwc_response(resp, nwc, inv).await?;

Expand Down Expand Up @@ -746,8 +744,7 @@ impl<S: MutinyStorage> NostrManager<S> {
pub async fn handle_nwc_request(
&self,
event: Event,
node_manager: &NodeManager<S>,
from_node: &PublicKey,
payer: &impl LnPayer,
) -> anyhow::Result<Option<Event>> {
let nwc = {
let vec = self.nwc.read().unwrap();
Expand All @@ -757,8 +754,7 @@ impl<S: MutinyStorage> NostrManager<S> {
};

if let Some(mut nwc) = nwc {
let node = node_manager.get_node(from_node).await?;
let event = nwc.handle_nwc_request(event, node.as_ref(), self).await?;
let event = nwc.handle_nwc_request(event, payer, self).await?;
Ok(event)
} else {
Ok(None)
Expand Down
Loading

0 comments on commit 1f1a398

Please sign in to comment.