Skip to content

Commit

Permalink
Fix panic ln node (#353)
Browse files Browse the repository at this point in the history
* removing expect from ln

* Working on it

* removed critical except from ln node functions - to be tested!
  • Loading branch information
arkanoider authored Sep 11, 2024
1 parent 41f182c commit 66fc27f
Show file tree
Hide file tree
Showing 7 changed files with 54 additions and 29 deletions.
6 changes: 4 additions & 2 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion src/app/release.rs
Original file line number Diff line number Diff line change
Expand Up @@ -145,7 +145,7 @@ pub async fn do_payment(mut order: Order) -> Result<()> {
} else {
payment_request
};
let mut ln_client_payment = LndConnector::new().await;
let mut ln_client_payment = LndConnector::new().await?;
let (tx, mut rx) = channel(100);

let payment_task = ln_client_payment.send_payment(&payment_request, amount as i64, tx);
Expand Down
2 changes: 2 additions & 0 deletions src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ pub enum MostroError {
LnAddressParseError,
LnAddressWrongAmount,
LnPaymentError(String),
LnNodeError(String),
}

impl std::error::Error for MostroError {}
Expand All @@ -35,6 +36,7 @@ impl fmt::Display for MostroError {
MostroError::LnAddressWrongAmount => write!(f, "Ln address need amount of 0 sats - please check your order"),
MostroError::LnAddressParseError => write!(f, "Ln address parsing error - please check your address"),
MostroError::LnPaymentError(e) => write!(f, "Lightning payment failure cause: {}",e),
MostroError::LnNodeError(e) => write!(f, "Lightning node connection failure caused by: {}",e),
}
}
}
Expand Down
44 changes: 29 additions & 15 deletions src/lightning/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ pub struct PaymentMessage {
}

impl LndConnector {
pub async fn new() -> Self {
pub async fn new() -> anyhow::Result<Self> {
let ln_settings = Settings::get_ln();

// Connecting to LND requires only host, port, cert file, and macaroon file
Expand All @@ -47,9 +47,10 @@ impl LndConnector {
ln_settings.lnd_macaroon_file,
)
.await
.expect("Failed connecting to LND");
.map_err(|e| MostroError::LnNodeError(e.to_string()))?;

Self { client }
// Safe unwrap here
Ok(Self { client })
}

pub async fn create_hold_invoice(
Expand All @@ -75,14 +76,20 @@ impl LndConnector {
.invoices()
.add_hold_invoice(invoice)
.await
.expect("Failed to add hold invoice")
.into_inner();
.map_err(|e| e.to_string());

Ok((holdinvoice, preimage.to_vec(), hash.to_vec()))
match holdinvoice {
Ok(holdinvoice) => Ok((holdinvoice.into_inner(), preimage.to_vec(), hash.to_vec())),
Err(e) => Err(LndClientError::cancelled(e)),
}
}

pub async fn subscribe_invoice(&mut self, r_hash: Vec<u8>, listener: Sender<InvoiceMessage>) {
let mut invoice_stream = self
pub async fn subscribe_invoice(
&mut self,
r_hash: Vec<u8>,
listener: Sender<InvoiceMessage>,
) -> anyhow::Result<()> {
let invoice_stream = self
.client
.invoices()
.subscribe_single_invoice(
Expand All @@ -91,13 +98,14 @@ impl LndConnector {
},
)
.await
.expect("Failed to call subscribe_single_invoice")
.into_inner();
.map_err(|e| MostroError::LnNodeError(e.to_string()))?;

while let Some(invoice) = invoice_stream
let mut inner_invoice = invoice_stream.into_inner();

while let Some(invoice) = inner_invoice
.message()
.await
.expect("Failed to receive invoices")
.map_err(|e| MostroError::LnNodeError(e.to_string()))?
{
if let Some(state) =
tonic_openssl_lnd::lnrpc::invoice::InvoiceState::from_i32(invoice.state)
Expand All @@ -110,9 +118,10 @@ impl LndConnector {
.clone()
.send(msg)
.await
.expect("Failed to send a message");
.map_err(|e| MostroError::LnNodeError(e.to_string()))?
}
}
Ok(())
}

pub async fn settle_hold_invoice(
Expand Down Expand Up @@ -229,13 +238,18 @@ impl LndConnector {
.map_err(|e| MostroError::LnPaymentError(e.to_string()))?
.into_inner();

while let Some(payment) = stream.message().await.expect("Failed paying invoice") {
while let Ok(Some(payment)) = stream
.message()
.await
.map_err(|e| MostroError::LnPaymentError(e.to_string()))
{
// ("Failed paying invoice") {
let msg = PaymentMessage { payment };
listener
.clone()
.send(msg)
.await
.expect("Failed to send a message");
.map_err(|e| MostroError::LnNodeError(e.to_string()))?
}

Ok(())
Expand Down
6 changes: 4 additions & 2 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -75,13 +75,15 @@ async fn main() -> Result<()> {
.unwrap()
.subscribe(vec![subscription], None)
.await;
let mut ln_client = LndConnector::new().await;
let mut ln_client = LndConnector::new().await?;

if let Ok(held_invoices) = find_held_invoices(&pool).await {
for invoice in held_invoices.iter() {
if let Some(hash) = &invoice.hash {
info!("Resubscribing order id - {}", invoice.id);
invoice_subscribe(hash.as_bytes().to_vec()).await;
if let Err(e) = invoice_subscribe(hash.as_bytes().to_vec()).await {
tracing::error!("Ln node error {e}")
}
}
}
}
Expand Down
11 changes: 6 additions & 5 deletions src/scheduler.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ pub async fn start_scheduler(rate_list: Arc<Mutex<Vec<Event>>>) {

job_expire_pending_older_orders().await;
job_update_rate_events(rate_list).await;
job_cancel_orders().await;
let _ = job_cancel_orders().await;
job_retry_failed_payments().await;
job_info_event_send().await;
job_relay_list().await;
Expand Down Expand Up @@ -160,19 +160,19 @@ async fn job_update_rate_events(rate_list: Arc<Mutex<Vec<Event>>>) {
});
}

async fn job_cancel_orders() {
async fn job_cancel_orders() -> anyhow::Result<()> {
info!("Create a pool to connect to db");

let pool = match connect().await {
Ok(p) => p,
Err(e) => return error!("{e}"),
Err(e) => return Err(anyhow::Error::msg(e.to_string())),
};
let keys = match get_keys() {
Ok(keys) => keys,
Err(e) => return error!("{e}"),
Err(e) => return Err(anyhow::Error::msg(e.to_string())),
};

let mut ln_client = LndConnector::new().await;
let mut ln_client = LndConnector::new().await?;
let mostro_settings = Settings::get_mostro();
let exp_seconds = mostro_settings.expiration_seconds;

Expand Down Expand Up @@ -301,6 +301,7 @@ async fn job_cancel_orders() {
tokio::time::sleep(tokio::time::Duration::from_secs(exp_seconds as u64)).await;
}
});
Ok(())
}

async fn job_expire_pending_older_orders() {
Expand Down
12 changes: 8 additions & 4 deletions src/util.rs
Original file line number Diff line number Diff line change
Expand Up @@ -352,7 +352,7 @@ pub async fn show_hold_invoice(
seller_pubkey: &PublicKey,
mut order: Order,
) -> anyhow::Result<()> {
let mut ln_client = lightning::LndConnector::new().await;
let mut ln_client = lightning::LndConnector::new().await?;
// Add fee of seller to hold invoice
let new_amount = order.amount + order.fee;

Expand Down Expand Up @@ -412,13 +412,16 @@ pub async fn show_hold_invoice(
}

// Create function to reuse in case of resubscription
pub async fn invoice_subscribe(hash: Vec<u8>) {
let mut ln_client_invoices = lightning::LndConnector::new().await;
pub async fn invoice_subscribe(hash: Vec<u8>) -> anyhow::Result<()> {
let mut ln_client_invoices = lightning::LndConnector::new().await?;
let (tx, mut rx) = channel(100);

let invoice_task = {
async move {
ln_client_invoices.subscribe_invoice(hash, tx).await;
let _ = ln_client_invoices
.subscribe_invoice(hash, tx)
.await
.map_err(|e| MostroError::LnNodeError(e.to_string()));
}
};
tokio::spawn(invoice_task);
Expand Down Expand Up @@ -451,6 +454,7 @@ pub async fn invoice_subscribe(hash: Vec<u8>) {
}
};
tokio::spawn(subs);
Ok(())
}

pub async fn get_market_amount_and_fee(
Expand Down

0 comments on commit 66fc27f

Please sign in to comment.