Skip to content

Commit

Permalink
feat: amountless itests
Browse files Browse the repository at this point in the history
  • Loading branch information
thesimplekid committed Dec 11, 2024
1 parent d16c225 commit 050e4fa
Show file tree
Hide file tree
Showing 18 changed files with 101 additions and 59 deletions.
1 change: 0 additions & 1 deletion Cargo.lock

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

7 changes: 5 additions & 2 deletions crates/cdk-cln/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ use std::sync::Arc;
use std::time::Duration;

use async_trait::async_trait;
use cdk::amount::{to_unit, Amount};
use cdk::amount::{to_unit, Amount, MSAT_IN_SAT};
use cdk::cdk_lightning::{
self, CreateInvoiceResponse, MintLightning, PayInvoiceResponse, PaymentQuoteResponse, Settings,
};
Expand Down Expand Up @@ -197,7 +197,9 @@ impl MintLightning for Cln {
&self,
melt_quote_request: &MeltQuoteBolt11Request,
) -> Result<PaymentQuoteResponse, Self::Err> {
let amount = melt_quote_request.amount()?;
let amount = melt_quote_request.amount_msat()?;

let amount = amount / MSAT_IN_SAT.into();

let relative_fee_reserve =
(self.fee_reserve.percent_fee_reserve * u64::from(amount) as f32) as u64;
Expand Down Expand Up @@ -283,6 +285,7 @@ impl MintLightning for Cln {
PayStatus::PENDING => MeltQuoteState::Pending,
PayStatus::FAILED => MeltQuoteState::Failed,
};

PayInvoiceResponse {
payment_preimage: Some(hex::encode(pay_response.payment_preimage.to_vec())),
payment_lookup_id: pay_response.payment_hash.to_string(),
Expand Down
6 changes: 4 additions & 2 deletions crates/cdk-fake-wallet/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ use std::sync::Arc;
use async_trait::async_trait;
use bitcoin::hashes::{sha256, Hash};
use bitcoin::secp256k1::{Secp256k1, SecretKey};
use cdk::amount::{to_unit, Amount};
use cdk::amount::{to_unit, Amount, MSAT_IN_SAT};
use cdk::cdk_lightning::{
self, CreateInvoiceResponse, MintLightning, PayInvoiceResponse, PaymentQuoteResponse, Settings,
};
Expand Down Expand Up @@ -128,7 +128,9 @@ impl MintLightning for FakeWallet {
&self,
melt_quote_request: &MeltQuoteBolt11Request,
) -> Result<PaymentQuoteResponse, Self::Err> {
let amount = melt_quote_request.amount()?;
let amount = melt_quote_request.amount_msat()?;

let amount = amount / MSAT_IN_SAT.into();

let relative_fee_reserve =
(self.fee_reserve.percent_fee_reserve * u64::from(amount) as f32) as u64;
Expand Down
4 changes: 2 additions & 2 deletions crates/cdk-integration-tests/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -32,8 +32,8 @@ once_cell = "1.19.0"
uuid = { version = "1", features = ["v4"] }
serde = "1"
serde_json = "1"
# ln-regtest-rs = { path = "../../../../ln-regtest-rs" }
ln-regtest-rs = { git = "https://github.com/thesimplekid/ln-regtest-rs", rev = "e0ac418675" }
ln-regtest-rs = { path = "../../../../ln-regtest-rs" }
# ln-regtest-rs = { git = "https://github.com/thesimplekid/ln-regtest-rs", rev = "e0ac418675" }
lightning-invoice = { version = "0.32.0", features = ["serde", "std"] }
tracing = { version = "0.1", default-features = false, features = [
"attributes",
Expand Down
14 changes: 0 additions & 14 deletions crates/cdk-integration-tests/src/init_regtest.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,6 @@ use ln_regtest_rs::ln_client::{ClnClient, LightningClient, LndClient};
use ln_regtest_rs::lnd::Lnd;
use tokio::sync::Notify;
use tower_http::cors::CorsLayer;
use tracing_subscriber::EnvFilter;

const BITCOIND_ADDR: &str = "127.0.0.1:18443";
const ZMQ_RAW_BLOCK: &str = "tcp://127.0.0.1:28332";
Expand Down Expand Up @@ -193,19 +192,6 @@ pub async fn start_cln_mint<D>(addr: &str, port: u16, database: D) -> Result<()>
where
D: MintDatabase<Err = cdk_database::Error> + Send + Sync + 'static,
{
let default_filter = "debug";

let sqlx_filter = "sqlx=warn";
let hyper_filter = "hyper=warn";

let env_filter = EnvFilter::new(format!(
"{},{},{}",
default_filter, sqlx_filter, hyper_filter
));

// Parse input
tracing_subscriber::fmt().with_env_filter(env_filter).init();

let cln_client = init_cln_client().await?;

let cln_backend = create_cln_backend(&cln_client).await?;
Expand Down
15 changes: 15 additions & 0 deletions crates/cdk-integration-tests/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,24 @@ use cdk_integration_tests::init_regtest::{
};
use cdk_redb::MintRedbDatabase;
use cdk_sqlite::MintSqliteDatabase;
use tracing_subscriber::EnvFilter;

#[tokio::main]
async fn main() -> Result<()> {
let default_filter = "debug";

let sqlx_filter = "sqlx=warn";
let hyper_filter = "hyper=warn";
let h2_filter = "h2=warn";

let env_filter = EnvFilter::new(format!(
"{},{},{},{}",
default_filter, sqlx_filter, hyper_filter, h2_filter
));

// Parse input
tracing_subscriber::fmt().with_env_filter(env_filter).init();

let mut bitcoind = init_bitcoind();
bitcoind.start_bitcoind()?;

Expand Down
42 changes: 41 additions & 1 deletion crates/cdk-integration-tests/tests/regtest.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ use anyhow::{bail, Result};
use bip39::Mnemonic;
use cdk::amount::{Amount, SplitTarget};
use cdk::cdk_database::WalletMemoryDatabase;
use cdk::nuts::nut05::Options;
use cdk::nuts::{
CurrencyUnit, MeltQuoteState, MintBolt11Request, MintQuoteState, NotificationPayload,
PreMintSecrets, State,
Expand Down Expand Up @@ -76,7 +77,7 @@ async fn test_regtest_mint_melt_round_trip() -> Result<()> {

let mint_quote = wallet.mint_quote(100.into(), None).await?;

lnd_client.pay_invoice(mint_quote.request).await?;
lnd_client.pay_invoice(mint_quote.request).await.unwrap();

let mint_amount = wallet
.mint(&mint_quote.id, SplitTarget::default(), None)
Expand Down Expand Up @@ -392,3 +393,42 @@ async fn test_cached_mint() -> Result<()> {
assert!(response == response1);
Ok(())
}

#[tokio::test(flavor = "multi_thread", worker_threads = 1)]
async fn test_regtest_melt_amountless() -> Result<()> {
let lnd_client = init_lnd_client().await?;

let wallet = Wallet::new(
&get_mint_url(),
CurrencyUnit::Sat,
Arc::new(WalletMemoryDatabase::default()),
&Mnemonic::generate(12)?.to_seed_normalized(""),
None,
)?;

let mint_amount = Amount::from(100);

let mint_quote = wallet.mint_quote(mint_amount, None).await?;

assert_eq!(mint_quote.amount, mint_amount);

lnd_client.pay_invoice(mint_quote.request).await?;

let mint_amount = wallet
.mint(&mint_quote.id, SplitTarget::default(), None)
.await?;

assert!(mint_amount == 100.into());

let invoice = lnd_client.create_invoice(None).await?;

let options = Options::new_amountless(5_000);

let melt_quote = wallet.melt_quote(invoice.clone(), Some(options)).await?;

let melt = wallet.melt(&melt_quote.id).await.unwrap();

assert!(melt.amount == 5.into());

Ok(())
}
4 changes: 3 additions & 1 deletion crates/cdk-lnbits/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -153,7 +153,9 @@ impl MintLightning for LNbits {
return Err(Self::Err::Anyhow(anyhow!("Unsupported unit")));
}

let amount = melt_quote_request.amount()?;
let amount = melt_quote_request.amount_msat()?;

let amount = amount / MSAT_IN_SAT.into();

let relative_fee_reserve =
(self.fee_reserve.percent_fee_reserve * u64::from(amount) as f32) as u64;
Expand Down
4 changes: 3 additions & 1 deletion crates/cdk-lnd/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -165,7 +165,9 @@ impl MintLightning for Lnd {
&self,
melt_quote_request: &MeltQuoteBolt11Request,
) -> Result<PaymentQuoteResponse, Self::Err> {
let amount = melt_quote_request.amount()?;
let amount = melt_quote_request.amount_msat()?;

let amount = amount / MSAT_IN_SAT.into();

let relative_fee_reserve =
(self.fee_reserve.percent_fee_reserve * u64::from(amount) as f32) as u64;
Expand Down
2 changes: 0 additions & 2 deletions crates/cdk-mintd/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -140,8 +140,6 @@ async fn main() -> anyhow::Result<()> {
melt_max: settings.ln.max_melt,
};

println!("{:?}", settings);

match settings.ln.ln_backend {
LnBackend::Cln => {
let cln_settings = settings
Expand Down
4 changes: 3 additions & 1 deletion crates/cdk-phoenixd/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -162,7 +162,9 @@ impl MintLightning for Phoenixd {
return Err(Error::UnsupportedUnit.into());
}

let amount = melt_quote_request.amount()?;
let amount = melt_quote_request.amount_msat()?;

let amount = amount / MSAT_IN_SAT.into();

let relative_fee_reserve =
(self.fee_reserve.percent_fee_reserve * u64::from(amount) as f32) as u64;
Expand Down
2 changes: 1 addition & 1 deletion crates/cdk-strike/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -163,7 +163,7 @@ impl MintLightning for Strike {
ln_invoice: melt_quote_request.request.to_string(),
source_currency,
amount: melt_quote_request.options.map(|a| RequestAmount {
amount: (<cdk::Amount as Into<u64>>::into(a.amount()) / MSAT_IN_SAT) as f32,
amount: (<cdk::Amount as Into<u64>>::into(a.amount_msat()) / MSAT_IN_SAT) as f32,
currency: StrikeCurrencyUnit::BTC,
fee_policy: FeePolicy::Inclusive,
}),
Expand Down
2 changes: 0 additions & 2 deletions crates/cdk/src/cdk_database/mint_memory.rs
Original file line number Diff line number Diff line change
Expand Up @@ -367,8 +367,6 @@ impl MintDatabase for MintMemoryDatabase {
if let Some(quote_id) = quote_id {
let mut current_quote_signatures = self.quote_signatures.write().await;
current_quote_signatures.insert(quote_id, blind_signatures.to_vec());
let t = current_quote_signatures.get(&quote_id);
println!("after insert: {:?}", t);
}

Ok(())
Expand Down
9 changes: 4 additions & 5 deletions crates/cdk/src/mint/melt.rs
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,9 @@ impl Mint {
..
} = melt_request;

let amount = melt_request.amount()?;
let amount = melt_request.amount_msat()?;

let amount = to_unit(amount, &CurrencyUnit::Msat, unit)?;

self.check_melt_request_acceptable(amount, unit.clone(), PaymentMethod::Bolt11)?;

Expand All @@ -88,7 +90,7 @@ impl Mint {
let msats_to_pay = if request.amount_milli_satoshis().is_some() {
None
} else {
Some(amount)
Some(melt_request.amount_msat()?)
};

let quote = MeltQuote::new(
Expand Down Expand Up @@ -179,8 +181,6 @@ impl Mint {
let quote_msats = to_unit(melt_quote.amount, &melt_quote.unit, &CurrencyUnit::Msat)
.expect("Quote unit is checked above that it can convert to msat");

println!("{:?}", melt_quote);

let invoice_amount_msats: Amount = match melt_quote.msat_to_pay {
Some(amount) => amount,
None => invoice
Expand Down Expand Up @@ -584,7 +584,6 @@ impl Mint {

Ok(res)
}

/// Process melt request marking [`Proofs`] as spent
/// The melt request must be verifyed using [`Self::verify_melt_request`]
/// before calling [`Self::process_melt_request`]
Expand Down
19 changes: 7 additions & 12 deletions crates/cdk/src/nuts/nut05.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,6 @@ use uuid::Uuid;

use super::nut00::{BlindSignature, BlindedMessage, CurrencyUnit, PaymentMethod, Proofs};
use super::nut15::Mpp;
use crate::amount::to_unit;
#[cfg(feature = "mint")]
use crate::mint::{self, MeltQuote};
use crate::nuts::MeltQuoteState;
Expand Down Expand Up @@ -93,7 +92,7 @@ impl Options {
}

/// Payment amount
pub fn amount(&self) -> Amount {
pub fn amount_msat(&self) -> Amount {
match self {
Self::Mpp { mpp } => mpp.amount,
Self::Amountless { amountless } => amountless.amount_msat,
Expand All @@ -114,23 +113,19 @@ impl MeltQuoteBolt11Request {
///
/// Amount can either be defined in the bolt11 invoice,
/// in the request for an amountless bolt11 or in MPP option.
pub fn amount(&self) -> Result<Amount, Error> {
pub fn amount_msat(&self) -> Result<Amount, Error> {
let MeltQuoteBolt11Request {
request,
unit,
unit: _,
options,
..
} = self;

match options {
None => {
let amount_msat = request
.amount_milli_satoshis()
.ok_or(Error::InvalidAmountRequest)?;

Ok(to_unit(amount_msat, &CurrencyUnit::Msat, unit)
.map_err(|_err| Error::UnsupportedUnit)?)
}
None => Ok(request
.amount_milli_satoshis()
.ok_or(Error::InvalidAmountRequest)?
.into()),
Some(Options::Mpp { mpp }) => Ok(mpp.amount),
Some(Options::Amountless { amountless }) => {
let amount = amountless.amount_msat;
Expand Down
4 changes: 3 additions & 1 deletion crates/cdk/src/types.rs
Original file line number Diff line number Diff line change
Expand Up @@ -40,9 +40,11 @@ impl Melted {
Some(change_proofs) => change_proofs.total_amount()?,
None => Amount::ZERO,
};

let fee_paid = proofs_amount
.checked_sub(amount + change_amount)
.ok_or(Error::AmountOverflow)?;
.ok_or(Error::AmountOverflow)
.unwrap();

Ok(Self {
state,
Expand Down
2 changes: 0 additions & 2 deletions crates/cdk/src/wallet/client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -193,8 +193,6 @@ impl MintConnector for HttpClient {
.text()
.await?;

println!("{}", res);

convert_http_response!(MeltQuoteBolt11Response<String>, res)
}

Expand Down
19 changes: 10 additions & 9 deletions crates/cdk/src/wallet/melt.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ use lightning_invoice::Bolt11Invoice;
use tracing::instrument;

use super::MeltQuote;
use crate::amount::MSAT_IN_SAT;
use crate::amount::to_unit;
use crate::dhke::construct_proofs;
use crate::nuts::nut00::ProofsMethods;
use crate::nuts::nut05::Options;
Expand All @@ -14,7 +14,7 @@ use crate::nuts::{
};
use crate::types::{Melted, ProofInfo};
use crate::util::unix_time;
use crate::{Amount, Error, Wallet};
use crate::{Error, Wallet};

impl Wallet {
/// Melt Quote
Expand Down Expand Up @@ -63,25 +63,26 @@ impl Wallet {
}
None => options
.ok_or(Error::InvoiceAmountUndefined)?
.amount()
.amount_msat()
.into(),
};

let amount = match self.unit {
CurrencyUnit::Sat => Amount::from(request_amount / MSAT_IN_SAT),
CurrencyUnit::Msat => Amount::from(request_amount),
_ => return Err(Error::UnitUnsupported),
};
let amount = to_unit(request_amount, &CurrencyUnit::Msat, &self.unit).unwrap();

let quote_request = MeltQuoteBolt11Request {
request: Bolt11Invoice::from_str(&request)?,
unit: self.unit.clone(),
options,
};

let quote_res = self.client.post_melt_quote(quote_request).await?;
let quote_res = self.client.post_melt_quote(quote_request).await.unwrap();

if quote_res.amount != amount {
tracing::warn!(
"Mint returned incorrect quote amount. Expected {}, got {}",
amount,
quote_res.amount
);
return Err(Error::IncorrectQuoteAmount);
}

Expand Down

0 comments on commit 050e4fa

Please sign in to comment.