Skip to content

Commit

Permalink
Merge pull request #131 from Kodylow:module-lightning
Browse files Browse the repository at this point in the history
feat: lightning module refactor
  • Loading branch information
ngutech21 authored Sep 25, 2023
2 parents 38119da + 3ea8e95 commit 93fd74c
Show file tree
Hide file tree
Showing 9 changed files with 123 additions and 152 deletions.
9 changes: 8 additions & 1 deletion moksha-mint/src/bin/moksha-mint.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ use mokshamint::{
info::MintInfoSettings,
lightning::{
AlbyLightningSettings, LightningType, LnbitsLightningSettings, LndLightningSettings,
StrikeLightningSettings,
},
MintBuilder,
};
Expand Down Expand Up @@ -52,8 +53,14 @@ pub async fn main() -> anyhow::Result<()> {
.expect("Please provide alby info");
LightningType::Alby(alby_settings)
}
"Strike" => {
let strike_settings = envy::prefixed("STRIKE_")
.from_env::<StrikeLightningSettings>()
.expect("Please provide strike info");
LightningType::Strike(strike_settings)
}
_ => panic!(
"env MINT_LIGHTNING_BACKEND not found or invalid values. Valid values are Lnbits and Lnd"
"env MINT_LIGHTNING_BACKEND not found or invalid values. Valid values are Lnbits, Lnd, Alby, and Strike"
),
};

Expand Down
18 changes: 3 additions & 15 deletions moksha-mint/src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ use thiserror::Error;
use tonic_lnd::ConnectError;
use tracing::{event, Level};

use crate::{alby::AlbyError, lnbits::LNBitsError, strike::StrikeError};
use crate::lightning::error::LightningError;

#[derive(Error, Debug)]
pub enum MokshaMintError {
Expand All @@ -22,13 +22,7 @@ pub enum MokshaMintError {
DecodeInvoice(String, ParseOrSemanticError),

#[error("Failed to pay invoice {0} - Error {1}")]
PayInvoice(String, LNBitsError),

#[error("Failed to pay invoice {0} - Error {1}")]
PayInvoiceAlby(String, AlbyError),

#[error("Failed to pay invoice {0} - Error {1}")]
PayInvoiceStrike(String, StrikeError),
PayInvoice(String, LightningError),

#[error("DB Error {0}")]
Db(#[from] rocksdb::Error),
Expand Down Expand Up @@ -64,13 +58,7 @@ pub enum MokshaMintError {
InvalidAmount,

#[error("Lightning Error {0}")]
LightningLNBits(#[from] LNBitsError),

#[error("Lightning Error {0}")]
LightningAlby(#[from] AlbyError),

#[error("Lightning Error {0}")]
LightningStrike(#[from] StrikeError),
Lightning(#[from] LightningError),
}

impl IntoResponse for MokshaMintError {
Expand Down
3 changes: 0 additions & 3 deletions moksha-mint/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -33,15 +33,12 @@ use tracing::{event, info, Level};
use tracing_subscriber::prelude::__tracing_subscriber_SubscriberExt;
use tracing_subscriber::util::SubscriberInitExt;

mod alby;
mod database;
mod error;
pub mod info;
pub mod lightning;
mod lnbits;
pub mod mint;
mod model;
mod strike;

#[derive(Debug, Default)]
pub struct MintBuilder {
Expand Down
49 changes: 19 additions & 30 deletions moksha-mint/src/alby.rs → moksha-mint/src/lightning/alby.rs
Original file line number Diff line number Diff line change
@@ -1,25 +1,12 @@
use hyper::{header::CONTENT_TYPE, http::HeaderValue};
use url::Url;

use crate::model::{CreateInvoiceParams, CreateInvoiceResult, PayInvoiceResult};
use crate::{
info,
model::{CreateInvoiceParams, CreateInvoiceResult, PayInvoiceResult},
};

#[derive(Debug, thiserror::Error)]
pub enum AlbyError {
#[error("reqwest error: {0}")]
ReqwestError(#[from] reqwest::Error),

#[error("url error: {0}")]
UrlError(#[from] url::ParseError),

#[error("serde error: {0}")]
SerdeError(#[from] serde_json::Error),

#[error("Not found")]
NotFound,

#[error("Unauthorized")]
Unauthorized,
}
use super::error::LightningError;

#[derive(Clone)]
pub struct AlbyClient {
Expand All @@ -29,7 +16,7 @@ pub struct AlbyClient {
}

impl AlbyClient {
pub fn new(api_key: &str) -> Result<AlbyClient, AlbyError> {
pub fn new(api_key: &str) -> Result<AlbyClient, LightningError> {
let alby_url = Url::parse("https://api.getalby.com")?;

let reqwest_client = reqwest::Client::builder().build()?;
Expand All @@ -43,7 +30,7 @@ impl AlbyClient {
}

impl AlbyClient {
pub async fn make_get(&self, endpoint: &str) -> Result<String, AlbyError> {
pub async fn make_get(&self, endpoint: &str) -> Result<String, LightningError> {
let url = self.alby_url.join(endpoint)?;
let response = self
.reqwest_client
Expand All @@ -52,14 +39,15 @@ impl AlbyClient {
.send()
.await?;

if response.status() == reqwest::StatusCode::NOT_FOUND {
return Err(AlbyError::NotFound);
}
// Alby API returns a 404 for invoices that aren't settled yet
// if response.status() == reqwest::StatusCode::NOT_FOUND {
// return Err(LightningError::NotFound);
// }

Ok(response.text().await?)
}

pub async fn make_post(&self, endpoint: &str, body: &str) -> Result<String, AlbyError> {
pub async fn make_post(&self, endpoint: &str, body: &str) -> Result<String, LightningError> {
let url = self.alby_url.join(endpoint)?;
let response = self
.reqwest_client
Expand All @@ -74,11 +62,11 @@ impl AlbyClient {
.await?;

if response.status() == reqwest::StatusCode::NOT_FOUND {
return Err(AlbyError::NotFound);
return Err(LightningError::NotFound);
}

if response.status() == reqwest::StatusCode::UNAUTHORIZED {
return Err(AlbyError::Unauthorized);
return Err(LightningError::Unauthorized);
}

Ok(response.text().await?)
Expand All @@ -89,7 +77,7 @@ impl AlbyClient {
pub async fn create_invoice(
&self,
params: &CreateInvoiceParams,
) -> Result<CreateInvoiceResult, AlbyError> {
) -> Result<CreateInvoiceResult, LightningError> {
let params = serde_json::json!({
"amount": params.amount,
"description": params.memo,
Expand All @@ -115,7 +103,7 @@ impl AlbyClient {
})
}

pub async fn pay_invoice(&self, bolt11: &str) -> Result<PayInvoiceResult, AlbyError> {
pub async fn pay_invoice(&self, bolt11: &str) -> Result<PayInvoiceResult, LightningError> {
let body = self
.make_post(
"payments/bolt11",
Expand All @@ -133,9 +121,10 @@ impl AlbyClient {
})
}

pub async fn is_invoice_paid(&self, payment_hash: &str) -> Result<bool, AlbyError> {
pub async fn is_invoice_paid(&self, payment_hash: &str) -> Result<bool, LightningError> {
info!("KODY checking if invoice is paid: {}", payment_hash);
let body = self.make_get(&format!("invoices/{payment_hash}")).await?;

info!("KODY body: {}", body);
Ok(serde_json::from_str::<serde_json::Value>(&body)?["settled"]
.as_bool()
.unwrap_or(false))
Expand Down
20 changes: 20 additions & 0 deletions moksha-mint/src/lightning/error.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
#[derive(Debug, thiserror::Error)]
pub enum LightningError {
#[error("reqwest error: {0}")]
ReqwestError(#[from] reqwest::Error),

#[error("url error: {0}")]
UrlError(#[from] url::ParseError),

#[error("serde error: {0}")]
SerdeError(#[from] serde_json::Error),

#[error("Not found")]
NotFound,

#[error("Unauthorized")]
Unauthorized,

#[error("Payment failed")]
PaymentFailed,
}
36 changes: 10 additions & 26 deletions moksha-mint/src/lnbits.rs → moksha-mint/src/lightning/lnbits.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,23 +3,7 @@ use url::Url;

use crate::model::{CreateInvoiceParams, CreateInvoiceResult, PayInvoiceResult};

#[derive(Debug, thiserror::Error)]
pub enum LNBitsError {
#[error("reqwest error: {0}")]
ReqwestError(#[from] reqwest::Error),

#[error("url error: {0}")]
UrlError(#[from] url::ParseError),

#[error("serde error: {0}")]
SerdeError(#[from] serde_json::Error),

#[error("Not found")]
NotFound,

#[error("Unauthorized")]
Unauthorized,
}
use super::error::LightningError;

#[derive(Clone)]
pub struct LNBitsClient {
Expand All @@ -33,7 +17,7 @@ impl LNBitsClient {
admin_key: &str,
lnbits_url: &str,
tor_socket: Option<&str>,
) -> Result<LNBitsClient, LNBitsError> {
) -> Result<LNBitsClient, LightningError> {
let lnbits_url = Url::parse(lnbits_url)?;

let reqwest_client = {
Expand All @@ -54,7 +38,7 @@ impl LNBitsClient {
}

impl LNBitsClient {
pub async fn make_get(&self, endpoint: &str) -> Result<String, LNBitsError> {
pub async fn make_get(&self, endpoint: &str) -> Result<String, LightningError> {
let url = self.lnbits_url.join(endpoint)?;
let response = self
.reqwest_client
Expand All @@ -64,13 +48,13 @@ impl LNBitsClient {
.await?;

if response.status() == reqwest::StatusCode::NOT_FOUND {
return Err(LNBitsError::NotFound);
return Err(LightningError::NotFound);
}

Ok(response.text().await?)
}

pub async fn make_post(&self, endpoint: &str, body: &str) -> Result<String, LNBitsError> {
pub async fn make_post(&self, endpoint: &str, body: &str) -> Result<String, LightningError> {
let url = self.lnbits_url.join(endpoint)?;
let response = self
.reqwest_client
Expand All @@ -85,11 +69,11 @@ impl LNBitsClient {
.await?;

if response.status() == reqwest::StatusCode::NOT_FOUND {
return Err(LNBitsError::NotFound);
return Err(LightningError::NotFound);
}

if response.status() == reqwest::StatusCode::UNAUTHORIZED {
return Err(LNBitsError::Unauthorized);
return Err(LightningError::Unauthorized);
}

Ok(response.text().await?)
Expand All @@ -100,7 +84,7 @@ impl LNBitsClient {
pub async fn create_invoice(
&self,
params: &CreateInvoiceParams,
) -> Result<CreateInvoiceResult, LNBitsError> {
) -> Result<CreateInvoiceResult, LightningError> {
// Add out: true to the params
let params = serde_json::json!({
"out": false,
Expand Down Expand Up @@ -132,7 +116,7 @@ impl LNBitsClient {
})
}

pub async fn pay_invoice(&self, bolt11: &str) -> Result<PayInvoiceResult, LNBitsError> {
pub async fn pay_invoice(&self, bolt11: &str) -> Result<PayInvoiceResult, LightningError> {
let body = self
.make_post(
"api/v1/payments",
Expand All @@ -143,7 +127,7 @@ impl LNBitsClient {
Ok(serde_json::from_str(&body)?)
}

pub async fn is_invoice_paid(&self, payment_hash: &str) -> Result<bool, LNBitsError> {
pub async fn is_invoice_paid(&self, payment_hash: &str) -> Result<bool, LightningError> {
let body = self
.make_get(&format!("api/v1/payments/{payment_hash}"))
.await?;
Expand Down
Loading

0 comments on commit 93fd74c

Please sign in to comment.