thesimplekid 3 недель назад
Родитель
Сommit
52bfc8c9ce

+ 26 - 0
.github/workflows/nutshell_itest.yml

@@ -0,0 +1,26 @@
+name: Nutshell integration
+
+on: [push, pull_request]
+
+jobs:
+  integration-tests:
+    runs-on: ubuntu-latest
+    steps:
+      - name: Pull and start mint
+        run: |
+          docker run -d -p 3338:3338 --name nutshell -e MINT_LIGHTNING_BACKEND=FakeWallet -e MINT_LISTEN_HOST=0.0.0.0 -e MINT_LISTEN_PORT=3338 -e MINT_PRIVATE_KEY=TEST_PRIVATE_KEY cashubtc/nutshell:latest poetry run mint
+      - name: Check running containers
+        run: docker ps
+      - name: checkout
+        uses: actions/checkout@v4
+      - name: Install Nix
+        uses: DeterminateSystems/nix-installer-action@v11
+      - name: Nix Cache
+        uses: DeterminateSystems/magic-nix-cache-action@v6
+      - name: Rust Cache
+        uses: Swatinem/rust-cache@v2
+      - name: Test
+        run: nix develop -i -L .#stable --command just test-nutshell
+      - name: Show logs if tests fail
+        if: failure()
+        run: docker logs nutshell

+ 1 - 0
crates/cdk-integration-tests/Cargo.toml

@@ -43,6 +43,7 @@ tokio-tungstenite.workspace = true
 tower-http = { workspace = true, features = ["cors"] }
 tower-http = { workspace = true, features = ["cors"] }
 tower-service = "0.3.3"
 tower-service = "0.3.3"
 reqwest.workspace = true
 reqwest.workspace = true
+bitcoin = "0.32.0"
 
 
 [target.'cfg(not(target_arch = "wasm32"))'.dependencies]
 [target.'cfg(not(target_arch = "wasm32"))'.dependencies]
 tokio.workspace = true
 tokio.workspace = true

+ 3 - 3
crates/cdk-integration-tests/src/init_regtest.rs

@@ -32,11 +32,11 @@ pub const CLN_ADDR: &str = "127.0.0.1:19846";
 pub const CLN_TWO_ADDR: &str = "127.0.0.1:19847";
 pub const CLN_TWO_ADDR: &str = "127.0.0.1:19847";
 
 
 pub fn get_mint_addr() -> String {
 pub fn get_mint_addr() -> String {
-    env::var("cdk_itests_mint_addr").expect("Temp dir set")
+    env::var("CDK_ITESTS_MINT_ADDR").expect("Mint address not set")
 }
 }
 
 
 pub fn get_mint_port(which: &str) -> u16 {
 pub fn get_mint_port(which: &str) -> u16 {
-    let dir = env::var(format!("cdk_itests_mint_port_{}", which)).expect("Temp dir set");
+    let dir = env::var(format!("CDK_ITESTS_MINT_PORT_{}", which)).expect("Mint port not set");
     dir.parse().unwrap()
     dir.parse().unwrap()
 }
 }
 
 
@@ -49,7 +49,7 @@ pub fn get_mint_ws_url(which: &str) -> String {
 }
 }
 
 
 pub fn get_temp_dir() -> PathBuf {
 pub fn get_temp_dir() -> PathBuf {
-    let dir = env::var("cdk_itests").expect("Temp dir set");
+    let dir = env::var("CDK_ITESTS_DIR").expect("Temp dir not set");
     std::fs::create_dir_all(&dir).unwrap();
     std::fs::create_dir_all(&dir).unwrap();
     dir.parse().expect("Valid path buf")
     dir.parse().expect("Valid path buf")
 }
 }

+ 26 - 0
crates/cdk-integration-tests/src/lib.rs

@@ -1,3 +1,4 @@
+use std::env;
 use std::sync::Arc;
 use std::sync::Arc;
 
 
 use anyhow::{anyhow, bail, Result};
 use anyhow::{anyhow, bail, Result};
@@ -5,6 +6,7 @@ use cdk::amount::{Amount, SplitTarget};
 use cdk::nuts::{MintQuoteState, NotificationPayload, State};
 use cdk::nuts::{MintQuoteState, NotificationPayload, State};
 use cdk::wallet::WalletSubscription;
 use cdk::wallet::WalletSubscription;
 use cdk::Wallet;
 use cdk::Wallet;
+use init_regtest::get_mint_url;
 use tokio::time::{sleep, timeout, Duration};
 use tokio::time::{sleep, timeout, Duration};
 
 
 pub mod init_auth_mint;
 pub mod init_auth_mint;
@@ -119,3 +121,27 @@ pub async fn wait_for_mint_to_be_paid(
         }
         }
     }
     }
 }
 }
+
+/// Gets the mint URL from environment variable or falls back to default
+///
+/// Checks the CDK_TEST_MINT_URL environment variable:
+/// - If set, returns that URL
+/// - Otherwise falls back to the default URL from get_mint_url("0")
+pub fn get_mint_url_from_env() -> String {
+    match env::var("CDK_TEST_MINT_URL") {
+        Ok(url) => url,
+        Err(_) => get_mint_url("0"),
+    }
+}
+
+/// Gets the second mint URL from environment variable or falls back to default
+///
+/// Checks the CDK_TEST_MINT_URL_2 environment variable:
+/// - If set, returns that URL
+/// - Otherwise falls back to the default URL from get_mint_url("1")
+pub fn get_second_mint_url_from_env() -> String {
+    match env::var("CDK_TEST_MINT_URL_2") {
+        Ok(url) => url,
+        Err(_) => get_mint_url("1"),
+    }
+}

+ 1 - 55
crates/cdk-integration-tests/tests/fake_wallet.rs

@@ -322,65 +322,11 @@ async fn test_fake_melt_payment_err_paid() -> Result<()> {
     Ok(())
     Ok(())
 }
 }
 
 
-/// Tests that change outputs in a melt quote are correctly handled
-#[tokio::test(flavor = "multi_thread", worker_threads = 1)]
-async fn test_fake_melt_change_in_quote() -> Result<()> {
-    let wallet = Wallet::new(
-        MINT_URL,
-        CurrencyUnit::Sat,
-        Arc::new(memory::empty().await?),
-        &Mnemonic::generate(12)?.to_seed_normalized(""),
-        None,
-    )?;
-
-    let mint_quote = wallet.mint_quote(100.into(), None).await?;
-
-    wait_for_mint_to_be_paid(&wallet, &mint_quote.id, 60).await?;
-
-    let _mint_amount = wallet
-        .mint(&mint_quote.id, SplitTarget::default(), None)
-        .await?;
-
-    let fake_description = FakeInvoiceDescription::default();
-
-    let invoice = create_fake_invoice(9000, serde_json::to_string(&fake_description).unwrap());
-
-    let proofs = wallet.get_unspent_proofs().await?;
-
-    let melt_quote = wallet.melt_quote(invoice.to_string(), None).await?;
-
-    let keyset = wallet.get_active_mint_keyset().await?;
-
-    let premint_secrets = PreMintSecrets::random(keyset.id, 100.into(), &SplitTarget::default())?;
-
-    let client = HttpClient::new(MINT_URL.parse()?, None);
-
-    let melt_request = MeltBolt11Request::new(
-        melt_quote.id.clone(),
-        proofs.clone(),
-        Some(premint_secrets.blinded_messages()),
-    );
-
-    let melt_response = client.post_melt(melt_request).await?;
-
-    assert!(melt_response.change.is_some());
-
-    let check = wallet.melt_quote_status(&melt_quote.id).await?;
-    let mut melt_change = melt_response.change.unwrap();
-    melt_change.sort_by(|a, b| a.amount.cmp(&b.amount));
-
-    let mut check = check.change.unwrap();
-    check.sort_by(|a, b| a.amount.cmp(&b.amount));
-
-    assert_eq!(melt_change, check);
-    Ok(())
-}
-
 /// Tests that the correct database type is used based on environment variables
 /// Tests that the correct database type is used based on environment variables
 #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
 #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
 async fn test_database_type() -> Result<()> {
 async fn test_database_type() -> Result<()> {
     // Get the database type and work dir from environment
     // Get the database type and work dir from environment
-    let db_type = std::env::var("MINT_DATABASE").expect("MINT_DATABASE env var should be set");
+    let db_type = std::env::var("CDK_MINTD_DATABASE").expect("MINT_DATABASE env var should be set");
     let work_dir =
     let work_dir =
         std::env::var("CDK_MINTD_WORK_DIR").expect("CDK_MINTD_WORK_DIR env var should be set");
         std::env::var("CDK_MINTD_WORK_DIR").expect("CDK_MINTD_WORK_DIR env var should be set");
 
 

+ 495 - 0
crates/cdk-integration-tests/tests/happy_path_mint_wallet.rs

@@ -0,0 +1,495 @@
+//! Integration tests for mint-wallet interactions that should work across all mint implementations
+//!
+//! These tests verify the core functionality of the wallet-mint interaction protocol,
+//! including minting, melting, and wallet restoration. They are designed to be
+//! implementation-agnostic and should pass against any compliant Cashu mint,
+//! including Nutshell, CDK, and other implementations that follow the Cashu NUTs.
+//!
+//! The tests use environment variables to determine which mint to connect to and
+//! whether to use real Lightning Network payments (regtest mode) or simulated payments.
+
+use core::panic;
+use std::fmt::Debug;
+use std::str::FromStr;
+use std::sync::Arc;
+use std::time::Duration;
+use std::{char, env};
+
+use anyhow::{anyhow, bail, Result};
+use bip39::Mnemonic;
+use cashu::{MeltBolt11Request, PreMintSecrets};
+use cdk::amount::{Amount, SplitTarget};
+use cdk::nuts::nut00::ProofsMethods;
+use cdk::nuts::{CurrencyUnit, MeltQuoteState, NotificationPayload, State};
+use cdk::wallet::{HttpClient, MintConnector, Wallet};
+use cdk_fake_wallet::create_fake_invoice;
+use cdk_integration_tests::init_regtest::{get_lnd_dir, LND_RPC_ADDR};
+use cdk_integration_tests::{get_mint_url_from_env, wait_for_mint_to_be_paid};
+use cdk_sqlite::wallet::memory;
+use futures::{SinkExt, StreamExt};
+use lightning_invoice::Bolt11Invoice;
+use ln_regtest_rs::ln_client::{LightningClient, LndClient};
+use serde_json::json;
+use tokio::time::timeout;
+use tokio_tungstenite::connect_async;
+use tokio_tungstenite::tungstenite::protocol::Message;
+
+// This is the ln wallet we use to send/receive ln payements as the wallet
+async fn init_lnd_client() -> LndClient {
+    let lnd_dir = get_lnd_dir("one");
+    let cert_file = lnd_dir.join("tls.cert");
+    let macaroon_file = lnd_dir.join("data/chain/bitcoin/regtest/admin.macaroon");
+    LndClient::new(
+        format!("https://{}", LND_RPC_ADDR),
+        cert_file,
+        macaroon_file,
+    )
+    .await
+    .unwrap()
+}
+
+/// Pays a Bolt11Invoice if it's on the regtest network, otherwise returns Ok
+///
+/// This is useful for tests that need to pay invoices in regtest mode but
+/// should be skipped in other environments.
+async fn pay_if_regtest(invoice: &Bolt11Invoice) -> Result<()> {
+    // Check if the invoice is for the regtest network
+    if invoice.network() == bitcoin::Network::Regtest {
+        println!("Regtest invoice");
+        let lnd_client = init_lnd_client().await;
+        lnd_client.pay_invoice(invoice.to_string()).await?;
+        Ok(())
+    } else {
+        // Not a regtest invoice, just return Ok
+        Ok(())
+    }
+}
+
+/// Determines if we're running in regtest mode based on environment variable
+///
+/// Checks the CDK_TEST_REGTEST environment variable:
+/// - If set to "1", "true", or "yes" (case insensitive), returns true
+/// - Otherwise returns false
+fn is_regtest_env() -> bool {
+    match env::var("CDK_TEST_REGTEST") {
+        Ok(val) => {
+            let val = val.to_lowercase();
+            val == "1" || val == "true" || val == "yes"
+        }
+        Err(_) => false,
+    }
+}
+
+/// Creates a real invoice if in regtest mode, otherwise returns a fake invoice
+///
+/// Uses the is_regtest_env() function to determine whether to
+/// create a real regtest invoice or a fake one for testing.
+async fn create_invoice_for_env(amount_sat: Option<u64>) -> Result<String> {
+    if is_regtest_env() {
+        // In regtest mode, create a real invoice
+        let lnd_client = init_lnd_client().await;
+        lnd_client
+            .create_invoice(amount_sat)
+            .await
+            .map_err(|e| anyhow!("Failed to create regtest invoice: {}", e))
+    } else {
+        // Not in regtest mode, create a fake invoice
+        let fake_invoice = create_fake_invoice(
+            amount_sat.expect("Amount must be defined") * 1_000,
+            "".to_string(),
+        );
+        Ok(fake_invoice.to_string())
+    }
+}
+
+async fn get_notification<T: StreamExt<Item = Result<Message, E>> + Unpin, E: Debug>(
+    reader: &mut T,
+    timeout_to_wait: Duration,
+) -> (String, NotificationPayload<String>) {
+    let msg = timeout(timeout_to_wait, reader.next())
+        .await
+        .expect("timeout")
+        .unwrap()
+        .unwrap();
+
+    let mut response: serde_json::Value =
+        serde_json::from_str(msg.to_text().unwrap()).expect("valid json");
+
+    let mut params_raw = response
+        .as_object_mut()
+        .expect("object")
+        .remove("params")
+        .expect("valid params");
+
+    let params_map = params_raw.as_object_mut().expect("params is object");
+
+    (
+        params_map
+            .remove("subId")
+            .unwrap()
+            .as_str()
+            .unwrap()
+            .to_string(),
+        serde_json::from_value(params_map.remove("payload").unwrap()).unwrap(),
+    )
+}
+
+/// Tests a complete mint-melt round trip with WebSocket notifications
+///
+/// This test verifies the full lifecycle of tokens:
+/// 1. Creates a mint quote and pays the invoice
+/// 2. Mints tokens and verifies the correct amount
+/// 3. Creates a melt quote to spend tokens
+/// 4. Subscribes to WebSocket notifications for the melt process
+/// 5. Executes the melt and verifies the payment was successful
+/// 6. Validates all WebSocket notifications received during the process
+///
+/// This ensures the entire mint-melt flow works correctly and that
+/// WebSocket notifications are properly sent at each state transition.
+#[tokio::test(flavor = "multi_thread", worker_threads = 1)]
+async fn test_happy_mint_melt_round_trip() -> Result<()> {
+    let wallet = Wallet::new(
+        &get_mint_url_from_env(),
+        CurrencyUnit::Sat,
+        Arc::new(memory::empty().await?),
+        &Mnemonic::generate(12)?.to_seed_normalized(""),
+        None,
+    )?;
+
+    let (ws_stream, _) = connect_async(format!(
+        "{}/v1/ws",
+        get_mint_url_from_env().replace("http", "ws")
+    ))
+    .await
+    .expect("Failed to connect");
+    let (mut write, mut reader) = ws_stream.split();
+
+    let mint_quote = wallet.mint_quote(100.into(), None).await?;
+
+    let invoice = Bolt11Invoice::from_str(&mint_quote.request)?;
+    pay_if_regtest(&invoice).await.unwrap();
+
+    let proofs = wallet
+        .mint(&mint_quote.id, SplitTarget::default(), None)
+        .await?;
+
+    let mint_amount = proofs.total_amount()?;
+
+    assert!(mint_amount == 100.into());
+
+    let invoice = create_invoice_for_env(Some(50)).await.unwrap();
+
+    let melt = wallet.melt_quote(invoice, None).await?;
+
+    write
+        .send(Message::Text(
+            serde_json::to_string(&json!({
+                    "jsonrpc": "2.0",
+                    "id": 2,
+                    "method": "subscribe",
+                    "params": {
+                      "kind": "bolt11_melt_quote",
+                      "filters": [
+                        melt.id.clone(),
+                      ],
+                      "subId": "test-sub",
+                    }
+
+            }))?
+            .into(),
+        ))
+        .await?;
+
+    assert_eq!(
+        reader
+            .next()
+            .await
+            .unwrap()
+            .unwrap()
+            .to_text()
+            .unwrap()
+            .replace(char::is_whitespace, ""),
+        r#"{"jsonrpc":"2.0","result":{"status":"OK","subId":"test-sub"},"id":2}"#
+    );
+
+    let melt_response = wallet.melt(&melt.id).await.unwrap();
+    assert!(melt_response.preimage.is_some());
+    assert!(melt_response.state == MeltQuoteState::Paid);
+
+    let (sub_id, payload) = get_notification(&mut reader, Duration::from_millis(15000)).await;
+    // first message is the current state
+    assert_eq!("test-sub", sub_id);
+    let payload = match payload {
+        NotificationPayload::MeltQuoteBolt11Response(melt) => melt,
+        _ => panic!("Wrong payload"),
+    };
+
+    // assert_eq!(payload.amount + payload.fee_reserve, 50.into());
+    assert_eq!(payload.quote.to_string(), melt.id);
+    assert_eq!(payload.state, MeltQuoteState::Unpaid);
+
+    // get current state
+    let (sub_id, payload) = get_notification(&mut reader, Duration::from_millis(15000)).await;
+    assert_eq!("test-sub", sub_id);
+    let payload = match payload {
+        NotificationPayload::MeltQuoteBolt11Response(melt) => melt,
+        _ => panic!("Wrong payload"),
+    };
+    assert_eq!(payload.quote.to_string(), melt.id);
+    assert_eq!(payload.state, MeltQuoteState::Pending);
+
+    // get current state
+    let (sub_id, payload) = get_notification(&mut reader, Duration::from_millis(15000)).await;
+    assert_eq!("test-sub", sub_id);
+    let payload = match payload {
+        NotificationPayload::MeltQuoteBolt11Response(melt) => melt,
+        _ => panic!("Wrong payload"),
+    };
+    assert_eq!(payload.amount, 50.into());
+    assert_eq!(payload.quote.to_string(), melt.id);
+    assert_eq!(payload.state, MeltQuoteState::Paid);
+
+    Ok(())
+}
+
+/// Tests basic minting functionality with payment verification
+///
+/// This test focuses on the core minting process:
+/// 1. Creates a mint quote for a specific amount (100 sats)
+/// 2. Verifies the quote has the correct amount
+/// 3. Pays the invoice (or simulates payment in non-regtest environments)
+/// 4. Waits for the mint to recognize the payment
+/// 5. Mints tokens and verifies the correct amount was received
+///
+/// This ensures the basic minting flow works correctly from quote to token issuance.
+#[tokio::test(flavor = "multi_thread", worker_threads = 1)]
+async fn test_happy_mint_melt() -> Result<()> {
+    let wallet = Wallet::new(
+        &get_mint_url_from_env(),
+        CurrencyUnit::Sat,
+        Arc::new(memory::empty().await?),
+        &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);
+
+    let invoice = Bolt11Invoice::from_str(&mint_quote.request)?;
+    pay_if_regtest(&invoice).await?;
+
+    wait_for_mint_to_be_paid(&wallet, &mint_quote.id, 60).await?;
+
+    let proofs = wallet
+        .mint(&mint_quote.id, SplitTarget::default(), None)
+        .await?;
+
+    let mint_amount = proofs.total_amount()?;
+
+    assert!(mint_amount == 100.into());
+
+    Ok(())
+}
+
+/// Tests wallet restoration and proof state verification
+///
+/// This test verifies the wallet restoration process:
+/// 1. Creates a wallet with a specific seed and mints tokens
+/// 2. Verifies the wallet has the expected balance
+/// 3. Creates a new wallet instance with the same seed but empty storage
+/// 4. Confirms the new wallet starts with zero balance
+/// 5. Restores the wallet state from the mint
+/// 6. Swaps the proofs to ensure they're valid
+/// 7. Verifies the restored wallet has the correct balance
+/// 8. Checks that the original proofs are now marked as spent
+///
+/// This ensures wallet restoration works correctly and that
+/// the mint properly tracks spent proofs across wallet instances.
+#[tokio::test(flavor = "multi_thread", worker_threads = 1)]
+async fn test_restore() -> Result<()> {
+    let seed = Mnemonic::generate(12)?.to_seed_normalized("");
+    let wallet = Wallet::new(
+        &get_mint_url_from_env(),
+        CurrencyUnit::Sat,
+        Arc::new(memory::empty().await?),
+        &seed,
+        None,
+    )?;
+
+    let mint_quote = wallet.mint_quote(100.into(), None).await?;
+
+    let invoice = Bolt11Invoice::from_str(&mint_quote.request)?;
+    pay_if_regtest(&invoice).await?;
+
+    wait_for_mint_to_be_paid(&wallet, &mint_quote.id, 60).await?;
+
+    let _mint_amount = wallet
+        .mint(&mint_quote.id, SplitTarget::default(), None)
+        .await?;
+
+    assert!(wallet.total_balance().await? == 100.into());
+
+    let wallet_2 = Wallet::new(
+        &get_mint_url_from_env(),
+        CurrencyUnit::Sat,
+        Arc::new(memory::empty().await?),
+        &seed,
+        None,
+    )?;
+
+    assert!(wallet_2.total_balance().await? == 0.into());
+
+    let restored = wallet_2.restore().await?;
+    let proofs = wallet_2.get_unspent_proofs().await?;
+
+    wallet_2
+        .swap(None, SplitTarget::default(), proofs, None, false)
+        .await?;
+
+    assert!(restored == 100.into());
+
+    assert_eq!(wallet_2.total_balance().await?, 100.into());
+
+    let proofs = wallet.get_unspent_proofs().await?;
+
+    let states = wallet.check_proofs_spent(proofs).await?;
+
+    for state in states {
+        if state.state != State::Spent {
+            bail!("All proofs should be spent");
+        }
+    }
+
+    Ok(())
+}
+
+/// Tests that change outputs in a melt quote are correctly handled
+///
+/// This test verifies the following workflow:
+/// 1. Mint 100 sats of tokens
+/// 2. Create a melt quote for 9 sats (which requires 100 sats input with 91 sats change)
+/// 3. Manually construct a melt request with proofs and blinded messages for change
+/// 4. Verify that the change proofs in the response match what's reported by the quote status
+///
+/// This ensures the mint correctly processes change outputs during melting operations
+/// and that the wallet can properly verify the change amounts match expectations.
+#[tokio::test(flavor = "multi_thread", worker_threads = 1)]
+async fn test_fake_melt_change_in_quote() -> Result<()> {
+    let wallet = Wallet::new(
+        &get_mint_url_from_env(),
+        CurrencyUnit::Sat,
+        Arc::new(memory::empty().await?),
+        &Mnemonic::generate(12)?.to_seed_normalized(""),
+        None,
+    )?;
+
+    let mint_quote = wallet.mint_quote(100.into(), None).await?;
+
+    let bolt11 = Bolt11Invoice::from_str(&mint_quote.request)?;
+
+    pay_if_regtest(&bolt11).await?;
+
+    wait_for_mint_to_be_paid(&wallet, &mint_quote.id, 60).await?;
+
+    let _mint_amount = wallet
+        .mint(&mint_quote.id, SplitTarget::default(), None)
+        .await?;
+
+    let invoice = create_invoice_for_env(Some(9)).await?;
+
+    let proofs = wallet.get_unspent_proofs().await?;
+
+    let melt_quote = wallet.melt_quote(invoice.to_string(), None).await?;
+
+    let keyset = wallet.get_active_mint_keyset().await?;
+
+    let premint_secrets = PreMintSecrets::random(keyset.id, 100.into(), &SplitTarget::default())?;
+
+    let client = HttpClient::new(get_mint_url_from_env().parse()?, None);
+
+    let melt_request = MeltBolt11Request::new(
+        melt_quote.id.clone(),
+        proofs.clone(),
+        Some(premint_secrets.blinded_messages()),
+    );
+
+    let melt_response = client.post_melt(melt_request).await?;
+
+    assert!(melt_response.change.is_some());
+
+    let check = wallet.melt_quote_status(&melt_quote.id).await?;
+    let mut melt_change = melt_response.change.unwrap();
+    melt_change.sort_by(|a, b| a.amount.cmp(&b.amount));
+
+    let mut check = check.change.unwrap();
+    check.sort_by(|a, b| a.amount.cmp(&b.amount));
+
+    assert_eq!(melt_change, check);
+    Ok(())
+}
+
+#[tokio::test(flavor = "multi_thread", worker_threads = 1)]
+async fn test_pay_invoice_twice() -> Result<()> {
+    let ln_backend = match env::var("LN_BACKEND") {
+        Ok(val) => Some(val),
+        Err(_) => env::var("CDK_MINTD_LN_BACKEND").ok(),
+    };
+
+    if ln_backend.map(|ln| ln.to_uppercase()) == Some("FAKEWALLET".to_string()) {
+        // We can only preform this test on regtest backends as fake wallet just marks the quote as paid
+        return Ok(());
+    }
+
+    let wallet = Wallet::new(
+        &get_mint_url_from_env(),
+        CurrencyUnit::Sat,
+        Arc::new(memory::empty().await?),
+        &Mnemonic::generate(12)?.to_seed_normalized(""),
+        None,
+    )?;
+
+    let mint_quote = wallet.mint_quote(100.into(), None).await?;
+
+    pay_if_regtest(&mint_quote.request.parse()?).await?;
+
+    wait_for_mint_to_be_paid(&wallet, &mint_quote.id, 60).await?;
+
+    let proofs = wallet
+        .mint(&mint_quote.id, SplitTarget::default(), None)
+        .await?;
+
+    let mint_amount = proofs.total_amount()?;
+
+    assert_eq!(mint_amount, 100.into());
+
+    let invoice = create_invoice_for_env(Some(25)).await?;
+
+    let melt_quote = wallet.melt_quote(invoice.clone(), None).await?;
+
+    let melt = wallet.melt(&melt_quote.id).await.unwrap();
+
+    let melt_two = wallet.melt_quote(invoice, None).await?;
+
+    let melt_two = wallet.melt(&melt_two.id).await;
+
+    match melt_two {
+        Err(err) => match err {
+            cdk::Error::RequestAlreadyPaid => (),
+            err => {
+                bail!("Wrong invoice already paid: {}", err.to_string());
+            }
+        },
+        Ok(_) => {
+            bail!("Should not have allowed second payment");
+        }
+    }
+
+    let balance = wallet.total_balance().await?;
+
+    assert_eq!(balance, (Amount::from(100) - melt.fee_paid - melt.amount));
+
+    Ok(())
+}

+ 0 - 175
crates/cdk-integration-tests/tests/payment_processor.rs

@@ -1,175 +0,0 @@
-//! Tests where we expect the payment processor to respond with an error or pass
-
-use std::env;
-use std::sync::Arc;
-
-use anyhow::{bail, Result};
-use bip39::Mnemonic;
-use cdk::amount::{Amount, SplitTarget};
-use cdk::nuts::nut00::ProofsMethods;
-use cdk::nuts::CurrencyUnit;
-use cdk::wallet::Wallet;
-use cdk_fake_wallet::create_fake_invoice;
-use cdk_integration_tests::init_regtest::{get_lnd_dir, get_mint_url, LND_RPC_ADDR};
-use cdk_integration_tests::wait_for_mint_to_be_paid;
-use cdk_sqlite::wallet::memory;
-use ln_regtest_rs::ln_client::{LightningClient, LndClient};
-
-// This is the ln wallet we use to send/receive ln payements as the wallet
-async fn init_lnd_client() -> LndClient {
-    let lnd_dir = get_lnd_dir("one");
-    let cert_file = lnd_dir.join("tls.cert");
-    let macaroon_file = lnd_dir.join("data/chain/bitcoin/regtest/admin.macaroon");
-    LndClient::new(
-        format!("https://{}", LND_RPC_ADDR),
-        cert_file,
-        macaroon_file,
-    )
-    .await
-    .unwrap()
-}
-
-#[tokio::test(flavor = "multi_thread", worker_threads = 1)]
-async fn test_regtest_mint() -> Result<()> {
-    let wallet = Wallet::new(
-        &get_mint_url("0"),
-        CurrencyUnit::Sat,
-        Arc::new(memory::empty().await?),
-        &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);
-
-    let ln_backend = env::var("LN_BACKEND")?;
-
-    if ln_backend != "FAKEWALLET" {
-        let lnd_client = init_lnd_client().await;
-
-        lnd_client.pay_invoice(mint_quote.request).await?;
-    }
-
-    wait_for_mint_to_be_paid(&wallet, &mint_quote.id, 60).await?;
-
-    let proofs = wallet
-        .mint(&mint_quote.id, SplitTarget::default(), None)
-        .await?;
-
-    let mint_amount = proofs.total_amount()?;
-
-    assert!(mint_amount == 100.into());
-
-    Ok(())
-}
-
-#[tokio::test(flavor = "multi_thread", worker_threads = 1)]
-async fn test_regtest_mint_melt() -> Result<()> {
-    let wallet = Wallet::new(
-        &get_mint_url("0"),
-        CurrencyUnit::Sat,
-        Arc::new(memory::empty().await?),
-        &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);
-
-    let ln_backend = env::var("LN_BACKEND")?;
-    if ln_backend != "FAKEWALLET" {
-        let lnd_client = init_lnd_client().await;
-
-        lnd_client.pay_invoice(mint_quote.request).await?;
-    }
-
-    wait_for_mint_to_be_paid(&wallet, &mint_quote.id, 60).await?;
-
-    let proofs = wallet
-        .mint(&mint_quote.id, SplitTarget::default(), None)
-        .await?;
-
-    let mint_amount = proofs.total_amount()?;
-
-    assert!(mint_amount == 100.into());
-
-    let invoice = if ln_backend != "FAKEWALLET" {
-        let lnd_client = init_lnd_client().await;
-        lnd_client.create_invoice(Some(50)).await?
-    } else {
-        create_fake_invoice(50000, "".to_string()).to_string()
-    };
-
-    let melt_quote = wallet.melt_quote(invoice, None).await?;
-
-    wallet.melt(&melt_quote.id).await?;
-
-    Ok(())
-}
-
-#[tokio::test(flavor = "multi_thread", worker_threads = 1)]
-async fn test_pay_invoice_twice() -> Result<()> {
-    let ln_backend = env::var("LN_BACKEND")?;
-    if ln_backend == "FAKEWALLET" {
-        // We can only preform this test on regtest backends as fake wallet just marks the quote as paid
-        return Ok(());
-    }
-
-    let wallet = Wallet::new(
-        &get_mint_url("0"),
-        CurrencyUnit::Sat,
-        Arc::new(memory::empty().await?),
-        &Mnemonic::generate(12)?.to_seed_normalized(""),
-        None,
-    )?;
-
-    let mint_quote = wallet.mint_quote(100.into(), None).await?;
-
-    let lnd_client = init_lnd_client().await;
-
-    lnd_client.pay_invoice(mint_quote.request).await?;
-
-    wait_for_mint_to_be_paid(&wallet, &mint_quote.id, 60).await?;
-
-    let proofs = wallet
-        .mint(&mint_quote.id, SplitTarget::default(), None)
-        .await?;
-
-    let mint_amount = proofs.total_amount()?;
-
-    assert_eq!(mint_amount, 100.into());
-
-    let invoice = lnd_client.create_invoice(Some(25)).await?;
-
-    let melt_quote = wallet.melt_quote(invoice.clone(), None).await?;
-
-    let melt = wallet.melt(&melt_quote.id).await.unwrap();
-
-    let melt_two = wallet.melt_quote(invoice, None).await?;
-
-    let melt_two = wallet.melt(&melt_two.id).await;
-
-    match melt_two {
-        Err(err) => match err {
-            cdk::Error::RequestAlreadyPaid => (),
-            err => {
-                bail!("Wrong invoice already paid: {}", err.to_string());
-            }
-        },
-        Ok(_) => {
-            bail!("Should not have allowed second payment");
-        }
-    }
-
-    let balance = wallet.total_balance().await?;
-
-    assert_eq!(balance, (Amount::from(100) - melt.fee_paid - melt.amount));
-
-    Ok(())
-}

+ 46 - 366
crates/cdk-integration-tests/tests/regtest.rs

@@ -1,4 +1,3 @@
-use std::fmt::Debug;
 use std::str::FromStr;
 use std::str::FromStr;
 use std::sync::Arc;
 use std::sync::Arc;
 use std::time::Duration;
 use std::time::Duration;
@@ -7,26 +6,24 @@ use anyhow::{bail, Result};
 use bip39::Mnemonic;
 use bip39::Mnemonic;
 use cashu::{MeltOptions, Mpp};
 use cashu::{MeltOptions, Mpp};
 use cdk::amount::{Amount, SplitTarget};
 use cdk::amount::{Amount, SplitTarget};
-use cdk::nuts::nut00::ProofsMethods;
 use cdk::nuts::{
 use cdk::nuts::{
     CurrencyUnit, MeltQuoteState, MintBolt11Request, MintQuoteState, NotificationPayload,
     CurrencyUnit, MeltQuoteState, MintBolt11Request, MintQuoteState, NotificationPayload,
-    PreMintSecrets, State,
+    PreMintSecrets,
 };
 };
 use cdk::wallet::{HttpClient, MintConnector, Wallet, WalletSubscription};
 use cdk::wallet::{HttpClient, MintConnector, Wallet, WalletSubscription};
 use cdk_integration_tests::init_regtest::{
 use cdk_integration_tests::init_regtest::{
     get_cln_dir, get_lnd_cert_file_path, get_lnd_dir, get_lnd_macaroon_path, get_mint_port,
     get_cln_dir, get_lnd_cert_file_path, get_lnd_dir, get_lnd_macaroon_path, get_mint_port,
-    get_mint_url, get_mint_ws_url, LND_RPC_ADDR, LND_TWO_RPC_ADDR,
+    LND_RPC_ADDR, LND_TWO_RPC_ADDR,
+};
+use cdk_integration_tests::{
+    get_mint_url_from_env, get_second_mint_url_from_env, wait_for_mint_to_be_paid,
 };
 };
-use cdk_integration_tests::wait_for_mint_to_be_paid;
 use cdk_sqlite::wallet::{self, memory};
 use cdk_sqlite::wallet::{self, memory};
-use futures::{join, SinkExt, StreamExt};
+use futures::join;
 use lightning_invoice::Bolt11Invoice;
 use lightning_invoice::Bolt11Invoice;
 use ln_regtest_rs::ln_client::{ClnClient, LightningClient, LndClient};
 use ln_regtest_rs::ln_client::{ClnClient, LightningClient, LndClient};
 use ln_regtest_rs::InvoiceStatus;
 use ln_regtest_rs::InvoiceStatus;
-use serde_json::json;
 use tokio::time::timeout;
 use tokio::time::timeout;
-use tokio_tungstenite::connect_async;
-use tokio_tungstenite::tungstenite::protocol::Message;
 
 
 // This is the ln wallet we use to send/receive ln payements as the wallet
 // This is the ln wallet we use to send/receive ln payements as the wallet
 async fn init_lnd_client() -> LndClient {
 async fn init_lnd_client() -> LndClient {
@@ -42,293 +39,12 @@ async fn init_lnd_client() -> LndClient {
     .unwrap()
     .unwrap()
 }
 }
 
 
-async fn get_notification<T: StreamExt<Item = Result<Message, E>> + Unpin, E: Debug>(
-    reader: &mut T,
-    timeout_to_wait: Duration,
-) -> (String, NotificationPayload<String>) {
-    let msg = timeout(timeout_to_wait, reader.next())
-        .await
-        .expect("timeout")
-        .unwrap()
-        .unwrap();
-
-    let mut response: serde_json::Value =
-        serde_json::from_str(msg.to_text().unwrap()).expect("valid json");
-
-    let mut params_raw = response
-        .as_object_mut()
-        .expect("object")
-        .remove("params")
-        .expect("valid params");
-
-    let params_map = params_raw.as_object_mut().expect("params is object");
-
-    (
-        params_map
-            .remove("subId")
-            .unwrap()
-            .as_str()
-            .unwrap()
-            .to_string(),
-        serde_json::from_value(params_map.remove("payload").unwrap()).unwrap(),
-    )
-}
-
-#[tokio::test(flavor = "multi_thread", worker_threads = 1)]
-async fn test_regtest_mint_melt_round_trip() -> Result<()> {
-    let lnd_client = init_lnd_client().await;
-
-    let wallet = Wallet::new(
-        &get_mint_url("0"),
-        CurrencyUnit::Sat,
-        Arc::new(memory::empty().await?),
-        &Mnemonic::generate(12)?.to_seed_normalized(""),
-        None,
-    )?;
-
-    let (ws_stream, _) = connect_async(get_mint_ws_url("0"))
-        .await
-        .expect("Failed to connect");
-    let (mut write, mut reader) = ws_stream.split();
-
-    let mint_quote = wallet.mint_quote(100.into(), None).await?;
-
-    lnd_client.pay_invoice(mint_quote.request).await.unwrap();
-
-    let proofs = wallet
-        .mint(&mint_quote.id, SplitTarget::default(), None)
-        .await?;
-
-    let mint_amount = proofs.total_amount()?;
-
-    assert!(mint_amount == 100.into());
-
-    let invoice = lnd_client.create_invoice(Some(50)).await?;
-
-    let melt = wallet.melt_quote(invoice, None).await?;
-
-    write
-        .send(Message::Text(
-            serde_json::to_string(&json!({
-                    "jsonrpc": "2.0",
-                    "id": 2,
-                    "method": "subscribe",
-                    "params": {
-                      "kind": "bolt11_melt_quote",
-                      "filters": [
-                        melt.id.clone(),
-                      ],
-                      "subId": "test-sub",
-                    }
-
-            }))?
-            .into(),
-        ))
-        .await?;
-
-    assert_eq!(
-        reader.next().await.unwrap().unwrap().to_text().unwrap(),
-        r#"{"jsonrpc":"2.0","result":{"status":"OK","subId":"test-sub"},"id":2}"#
-    );
-
-    let melt_response = wallet.melt(&melt.id).await.unwrap();
-    assert!(melt_response.preimage.is_some());
-    assert!(melt_response.state == MeltQuoteState::Paid);
-
-    let (sub_id, payload) = get_notification(&mut reader, Duration::from_millis(15000)).await;
-    // first message is the current state
-    assert_eq!("test-sub", sub_id);
-    let payload = match payload {
-        NotificationPayload::MeltQuoteBolt11Response(melt) => melt,
-        _ => panic!("Wrong payload"),
-    };
-
-    assert_eq!(payload.amount + payload.fee_reserve, 50.into());
-    assert_eq!(payload.quote.to_string(), melt.id);
-    assert_eq!(payload.state, MeltQuoteState::Unpaid);
-
-    // get current state
-    let (sub_id, payload) = get_notification(&mut reader, Duration::from_millis(15000)).await;
-    assert_eq!("test-sub", sub_id);
-    let payload = match payload {
-        NotificationPayload::MeltQuoteBolt11Response(melt) => melt,
-        _ => panic!("Wrong payload"),
-    };
-    assert_eq!(payload.amount + payload.fee_reserve, 50.into());
-    assert_eq!(payload.quote.to_string(), melt.id);
-    assert_eq!(payload.state, MeltQuoteState::Paid);
-
-    Ok(())
-}
-
-#[tokio::test(flavor = "multi_thread", worker_threads = 1)]
-async fn test_regtest_mint_melt() -> Result<()> {
-    let lnd_client = init_lnd_client().await;
-
-    let wallet = Wallet::new(
-        &get_mint_url("0"),
-        CurrencyUnit::Sat,
-        Arc::new(memory::empty().await?),
-        &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?;
-
-    wait_for_mint_to_be_paid(&wallet, &mint_quote.id, 60).await?;
-
-    let proofs = wallet
-        .mint(&mint_quote.id, SplitTarget::default(), None)
-        .await?;
-
-    let mint_amount = proofs.total_amount()?;
-
-    assert!(mint_amount == 100.into());
-
-    Ok(())
-}
-
-#[tokio::test(flavor = "multi_thread", worker_threads = 1)]
-async fn test_restore() -> Result<()> {
-    let lnd_client = init_lnd_client().await;
-
-    let seed = Mnemonic::generate(12)?.to_seed_normalized("");
-    let wallet = Wallet::new(
-        &get_mint_url("0"),
-        CurrencyUnit::Sat,
-        Arc::new(memory::empty().await?),
-        &seed,
-        None,
-    )?;
-
-    let mint_quote = wallet.mint_quote(100.into(), None).await?;
-
-    lnd_client.pay_invoice(mint_quote.request).await?;
-
-    wait_for_mint_to_be_paid(&wallet, &mint_quote.id, 60).await?;
-
-    let _mint_amount = wallet
-        .mint(&mint_quote.id, SplitTarget::default(), None)
-        .await?;
-
-    assert!(wallet.total_balance().await? == 100.into());
-
-    let wallet_2 = Wallet::new(
-        &get_mint_url("0"),
-        CurrencyUnit::Sat,
-        Arc::new(memory::empty().await?),
-        &seed,
-        None,
-    )?;
-
-    assert!(wallet_2.total_balance().await? == 0.into());
-
-    let restored = wallet_2.restore().await?;
-    let proofs = wallet_2.get_unspent_proofs().await?;
-
-    wallet_2
-        .swap(None, SplitTarget::default(), proofs, None, false)
-        .await?;
-
-    assert!(restored == 100.into());
-
-    assert!(wallet_2.total_balance().await? == 100.into());
-
-    let proofs = wallet.get_unspent_proofs().await?;
-
-    let states = wallet.check_proofs_spent(proofs).await?;
-
-    for state in states {
-        if state.state != State::Spent {
-            bail!("All proofs should be spent");
-        }
-    }
-
-    Ok(())
-}
-
-#[tokio::test(flavor = "multi_thread", worker_threads = 1)]
-async fn test_pay_invoice_twice() -> anyhow::Result<()> {
-    let lnd_client = init_lnd_client().await;
-
-    let wallet = Wallet::new(
-        &get_mint_url("0"),
-        CurrencyUnit::Sat,
-        Arc::new(memory::empty().await.unwrap()),
-        &Mnemonic::generate(12).unwrap().to_seed_normalized(""),
-        None,
-    )?;
-
-    let mint_quote = wallet
-        .mint_quote(100.into(), None)
-        .await
-        .expect("Get mint quote");
-
-    lnd_client
-        .pay_invoice(mint_quote.request)
-        .await
-        .expect("Could not pay invoice");
-
-    wait_for_mint_to_be_paid(&wallet, &mint_quote.id, 60)
-        .await
-        .expect("Mint invoice timeout not paid");
-
-    let proofs = wallet
-        .mint(&mint_quote.id, SplitTarget::default(), None)
-        .await
-        .expect("Could not mint");
-
-    let mint_amount = proofs.total_amount().unwrap();
-
-    assert_eq!(mint_amount, 100.into());
-
-    let invoice = lnd_client
-        .create_invoice(Some(10))
-        .await
-        .expect("Could not create invoice");
-
-    let melt_quote = wallet
-        .melt_quote(invoice.clone(), None)
-        .await
-        .expect("Could not get melt quote");
-
-    let melt = wallet.melt(&melt_quote.id).await.unwrap();
-
-    let melt_two = wallet.melt_quote(invoice, None).await.unwrap();
-
-    let melt_two = wallet.melt(&melt_two.id).await;
-
-    match melt_two {
-        Err(err) => match err {
-            cdk::Error::RequestAlreadyPaid => (),
-            err => {
-                bail!("Wrong invoice already paid: {}", err.to_string());
-            }
-        },
-        Ok(_) => {
-            bail!("Should not have allowed second payment");
-        }
-    }
-
-    let balance = wallet.total_balance().await.unwrap();
-
-    assert_eq!(balance, (Amount::from(100) - melt.fee_paid - melt.amount));
-
-    Ok(())
-}
-
 #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
 #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
 async fn test_internal_payment() -> Result<()> {
 async fn test_internal_payment() -> Result<()> {
     let lnd_client = init_lnd_client().await;
     let lnd_client = init_lnd_client().await;
 
 
     let wallet = Wallet::new(
     let wallet = Wallet::new(
-        &get_mint_url("0"),
+        &get_mint_url_from_env(),
         CurrencyUnit::Sat,
         CurrencyUnit::Sat,
         Arc::new(memory::empty().await?),
         Arc::new(memory::empty().await?),
         &Mnemonic::generate(12)?.to_seed_normalized(""),
         &Mnemonic::generate(12)?.to_seed_normalized(""),
@@ -348,7 +64,7 @@ async fn test_internal_payment() -> Result<()> {
     assert!(wallet.total_balance().await? == 100.into());
     assert!(wallet.total_balance().await? == 100.into());
 
 
     let wallet_2 = Wallet::new(
     let wallet_2 = Wallet::new(
-        &get_mint_url("0"),
+        &get_mint_url_from_env(),
         CurrencyUnit::Sat,
         CurrencyUnit::Sat,
         Arc::new(memory::empty().await?),
         Arc::new(memory::empty().await?),
         &Mnemonic::generate(12)?.to_seed_normalized(""),
         &Mnemonic::generate(12)?.to_seed_normalized(""),
@@ -417,50 +133,9 @@ async fn test_internal_payment() -> Result<()> {
 }
 }
 
 
 #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
 #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
-async fn test_cached_mint() -> Result<()> {
-    let lnd_client = init_lnd_client().await;
-
-    let wallet = Wallet::new(
-        &get_mint_url("0"),
-        CurrencyUnit::Sat,
-        Arc::new(memory::empty().await?),
-        &Mnemonic::generate(12)?.to_seed_normalized(""),
-        None,
-    )?;
-
-    let mint_amount = Amount::from(100);
-
-    let quote = wallet.mint_quote(mint_amount, None).await?;
-    lnd_client.pay_invoice(quote.request).await?;
-
-    wait_for_mint_to_be_paid(&wallet, &quote.id, 60).await?;
-
-    let active_keyset_id = wallet.get_active_mint_keyset().await?.id;
-    let http_client = HttpClient::new(get_mint_url("0").as_str().parse()?, None);
-    let premint_secrets =
-        PreMintSecrets::random(active_keyset_id, 100.into(), &SplitTarget::default()).unwrap();
-
-    let mut request = MintBolt11Request {
-        quote: quote.id,
-        outputs: premint_secrets.blinded_messages(),
-        signature: None,
-    };
-
-    let secret_key = quote.secret_key;
-
-    request.sign(secret_key.expect("Secret key on quote"))?;
-
-    let response = http_client.post_mint(request.clone()).await?;
-    let response1 = http_client.post_mint(request).await?;
-
-    assert!(response == response1);
-    Ok(())
-}
-
-#[tokio::test(flavor = "multi_thread", worker_threads = 1)]
 async fn test_websocket_connection() -> Result<()> {
 async fn test_websocket_connection() -> Result<()> {
     let wallet = Wallet::new(
     let wallet = Wallet::new(
-        &get_mint_url("0"),
+        &get_mint_url_from_env(),
         CurrencyUnit::Sat,
         CurrencyUnit::Sat,
         Arc::new(wallet::memory::empty().await?),
         Arc::new(wallet::memory::empty().await?),
         &Mnemonic::generate(12)?.to_seed_normalized(""),
         &Mnemonic::generate(12)?.to_seed_normalized(""),
@@ -515,14 +190,14 @@ async fn test_multimint_melt() -> Result<()> {
     let lnd_client = init_lnd_client().await;
     let lnd_client = init_lnd_client().await;
 
 
     let wallet1 = Wallet::new(
     let wallet1 = Wallet::new(
-        &get_mint_url("0"),
+        &get_mint_url_from_env(),
         CurrencyUnit::Sat,
         CurrencyUnit::Sat,
         Arc::new(memory::empty().await?),
         Arc::new(memory::empty().await?),
         &Mnemonic::generate(12)?.to_seed_normalized(""),
         &Mnemonic::generate(12)?.to_seed_normalized(""),
         None,
         None,
     )?;
     )?;
     let wallet2 = Wallet::new(
     let wallet2 = Wallet::new(
-        &get_mint_url("1"),
+        &get_second_mint_url_from_env(),
         CurrencyUnit::Sat,
         CurrencyUnit::Sat,
         Arc::new(memory::empty().await?),
         Arc::new(memory::empty().await?),
         &Mnemonic::generate(12)?.to_seed_normalized(""),
         &Mnemonic::generate(12)?.to_seed_normalized(""),
@@ -580,36 +255,41 @@ async fn test_multimint_melt() -> Result<()> {
 }
 }
 
 
 #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
 #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
-async fn test_database_type() -> Result<()> {
-    // Get the database type and work dir from environment
-    let db_type = std::env::var("MINT_DATABASE").expect("MINT_DATABASE env var should be set");
-    let work_dir =
-        std::env::var("CDK_MINTD_WORK_DIR").expect("CDK_MINTD_WORK_DIR env var should be set");
-
-    // Check that the correct database file exists
-    match db_type.as_str() {
-        "REDB" => {
-            let db_path = std::path::Path::new(&work_dir).join("cdk-mintd.redb");
-            assert!(
-                db_path.exists(),
-                "Expected redb database file to exist at {:?}",
-                db_path
-            );
-        }
-        "SQLITE" => {
-            let db_path = std::path::Path::new(&work_dir).join("cdk-mintd.sqlite");
-            assert!(
-                db_path.exists(),
-                "Expected sqlite database file to exist at {:?}",
-                db_path
-            );
-        }
-        "MEMORY" => {
-            // Memory database has no file to check
-            println!("Memory database in use - no file to check");
-        }
-        _ => bail!("Unknown database type: {}", db_type),
-    }
+async fn test_cached_mint() -> Result<()> {
+    let lnd_client = init_lnd_client().await;
+    let wallet = Wallet::new(
+        &get_mint_url_from_env(),
+        CurrencyUnit::Sat,
+        Arc::new(memory::empty().await?),
+        &Mnemonic::generate(12)?.to_seed_normalized(""),
+        None,
+    )?;
+
+    let mint_amount = Amount::from(100);
+
+    let quote = wallet.mint_quote(mint_amount, None).await?;
+    lnd_client.pay_invoice(quote.request.clone()).await?;
 
 
+    wait_for_mint_to_be_paid(&wallet, &quote.id, 60).await?;
+
+    let active_keyset_id = wallet.get_active_mint_keyset().await?.id;
+    let http_client = HttpClient::new(get_mint_url_from_env().parse().unwrap(), None);
+    let premint_secrets =
+        PreMintSecrets::random(active_keyset_id, 100.into(), &SplitTarget::default()).unwrap();
+
+    let mut request = MintBolt11Request {
+        quote: quote.id,
+        outputs: premint_secrets.blinded_messages(),
+        signature: None,
+    };
+
+    let secret_key = quote.secret_key;
+
+    request.sign(secret_key.expect("Secret key on quote"))?;
+
+    let response = http_client.post_mint(request.clone()).await?;
+    let response1 = http_client.post_mint(request).await?;
+
+    assert!(response == response1);
     Ok(())
     Ok(())
 }
 }

+ 7 - 0
crates/cdk/src/mint/melt.rs

@@ -305,6 +305,9 @@ impl Mint {
             .await?
             .await?
             .ok_or(Error::UnknownQuote)?;
             .ok_or(Error::UnknownQuote)?;
 
 
+        self.pubsub_manager
+            .melt_quote_status(&quote, None, None, MeltQuoteState::Pending);
+
         let Verification {
         let Verification {
             amount: input_amount,
             amount: input_amount,
             unit: input_unit,
             unit: input_unit,
@@ -339,6 +342,10 @@ impl Mint {
             .await?;
             .await?;
 
 
         self.check_ys_spendable(&input_ys, State::Pending).await?;
         self.check_ys_spendable(&input_ys, State::Pending).await?;
+        for proof in melt_request.inputs() {
+            self.pubsub_manager
+                .proof_state((proof.y()?, State::Pending));
+        }
 
 
         let EnforceSigFlag { sig_flag, .. } = enforce_sig_flag(melt_request.inputs().clone());
         let EnforceSigFlag { sig_flag, .. } = enforce_sig_flag(melt_request.inputs().clone());
 
 

+ 8 - 0
justfile

@@ -65,6 +65,14 @@ test-all db="memory":
     ./misc/itests.sh "{{db}}"
     ./misc/itests.sh "{{db}}"
     ./misc/fake_itests.sh "{{db}}"
     ./misc/fake_itests.sh "{{db}}"
     
     
+test-nutshell:
+    #!/usr/bin/env bash
+    export CDK_TEST_MINT_URL=http://127.0.0.1:3338
+    export LN_BACKEND=FAKEWALLET
+    cargo test -p cdk-integration-tests --test happy_path_mint_wallet
+    unset CDK_TEST_MINT_URL
+    unset LN_BACKEND
+    
 
 
 # run `cargo clippy` on everything
 # run `cargo clippy` on everything
 clippy *ARGS="--locked --offline --workspace --all-targets":
 clippy *ARGS="--locked --offline --workspace --all-targets":

+ 15 - 15
misc/fake_auth_itests.sh

@@ -12,37 +12,37 @@ cleanup() {
     echo "Mint binary terminated"
     echo "Mint binary terminated"
     
     
     # Remove the temporary directory
     # Remove the temporary directory
-    rm -rf "$cdk_itests"
-    echo "Temp directory removed: $cdk_itests"
-    unset cdk_itests
-    unset cdk_itests_mint_addr
-    unset cdk_itests_mint_port
+    rm -rf "$CDK_ITESTS_DIR"
+    echo "Temp directory removed: $CDK_ITESTS_DIR"
+    unset CDK_ITESTS_DIR
+    unset CDK_ITESTS_MINT_ADDR
+    unset CDK_ITESTS_MINT_PORT
 }
 }
 
 
 # Set up trap to call cleanup on script exit
 # Set up trap to call cleanup on script exit
 trap cleanup EXIT
 trap cleanup EXIT
 
 
 # Create a temporary directory
 # Create a temporary directory
-export cdk_itests=$(mktemp -d)
-export cdk_itests_mint_addr="127.0.0.1";
-export cdk_itests_mint_port=8087;
+export CDK_ITESTS_DIR=$(mktemp -d)
+export CDK_ITESTS_MINT_ADDR="127.0.0.1";
+export CDK_ITESTS_MINT_PORT=8087;
 
 
 # Check if the temporary directory was created successfully
 # Check if the temporary directory was created successfully
-if [[ ! -d "$cdk_itests" ]]; then
+if [[ ! -d "$CDK_ITESTS_DIR" ]]; then
     echo "Failed to create temp directory"
     echo "Failed to create temp directory"
     exit 1
     exit 1
 fi
 fi
 
 
-echo "Temp directory created: $cdk_itests"
+echo "Temp directory created: $CDK_ITESTS_DIR"
 export MINT_DATABASE="$1";
 export MINT_DATABASE="$1";
 export OPENID_DISCOVERY="$2";
 export OPENID_DISCOVERY="$2";
 
 
 cargo build -p cdk-integration-tests 
 cargo build -p cdk-integration-tests 
 
 
-export CDK_MINTD_URL="http://$cdk_itests_mint_addr:$cdk_itests_mint_port";
-export CDK_MINTD_WORK_DIR="$cdk_itests";
-export CDK_MINTD_LISTEN_HOST=$cdk_itests_mint_addr;
-export CDK_MINTD_LISTEN_PORT=$cdk_itests_mint_port;
+export CDK_MINTD_URL="http://$CDK_ITESTS_MINT_ADDR:$CDK_ITESTS_MINT_PORT";
+export CDK_MINTD_WORK_DIR="$CDK_ITESTS_DIR";
+export CDK_MINTD_LISTEN_HOST=$CDK_ITESTS_MINT_ADDR;
+export CDK_MINTD_LISTEN_PORT=$CDK_ITESTS_MINT_PORT;
 export CDK_MINTD_LN_BACKEND="fakewallet";
 export CDK_MINTD_LN_BACKEND="fakewallet";
 export CDK_MINTD_FAKE_WALLET_SUPPORTED_UNITS="sat";
 export CDK_MINTD_FAKE_WALLET_SUPPORTED_UNITS="sat";
 export CDK_MINTD_MNEMONIC="eye survey guilt napkin crystal cup whisper salt luggage manage unveil loyal";
 export CDK_MINTD_MNEMONIC="eye survey guilt napkin crystal cup whisper salt luggage manage unveil loyal";
@@ -69,7 +69,7 @@ echo "Starting auth mintd";
 cargo run --bin cdk-mintd --features redb &
 cargo run --bin cdk-mintd --features redb &
 cdk_mintd_pid=$!
 cdk_mintd_pid=$!
 
 
-URL="http://$cdk_itests_mint_addr:$cdk_itests_mint_port/v1/info"
+URL="http://$CDK_ITESTS_MINT_ADDR:$CDK_ITESTS_MINT_PORT/v1/info"
 TIMEOUT=100
 TIMEOUT=100
 START_TIME=$(date +%s)
 START_TIME=$(date +%s)
 # Loop until the endpoint returns a 200 OK status or timeout is reached
 # Loop until the endpoint returns a 200 OK status or timeout is reached

+ 61 - 32
misc/fake_itests.sh

@@ -5,56 +5,69 @@ cleanup() {
     echo "Cleaning up..."
     echo "Cleaning up..."
 
 
     echo "Killing the cdk mintd"
     echo "Killing the cdk mintd"
-    kill -2 $cdk_mintd_pid
-    wait $cdk_mintd_pid
+    kill -2 $CDK_MINTD_PID
+    wait $CDK_MINTD_PID
 
 
     echo "Mint binary terminated"
     echo "Mint binary terminated"
     
     
     # Remove the temporary directory
     # Remove the temporary directory
-    rm -rf "$cdk_itests"
-    echo "Temp directory removed: $cdk_itests"
-    unset cdk_itests
-    unset cdk_itests_mint_addr
-    unset cdk_itests_mint_port
+    rm -rf "$CDK_ITESTS_DIR"
+    echo "Temp directory removed: $CDK_ITESTS_DIR"
+    
+    # Unset all environment variables
+    unset CDK_ITESTS_DIR
+    unset CDK_ITESTS_MINT_ADDR
+    unset CDK_ITESTS_MINT_PORT
+    unset CDK_MINTD_DATABASE
+    unset CDK_TEST_MINT_URL
+    unset CDK_MINTD_URL
+    unset CDK_MINTD_WORK_DIR
+    unset CDK_MINTD_LISTEN_HOST
+    unset CDK_MINTD_LISTEN_PORT
+    unset CDK_MINTD_LN_BACKEND
+    unset CDK_MINTD_FAKE_WALLET_SUPPORTED_UNITS
+    unset CDK_MINTD_MNEMONIC
+    unset CDK_MINTD_FAKE_WALLET_FEE_PERCENT
+    unset CDK_MINTD_FAKE_WALLET_RESERVE_FEE_MIN
+    unset CDK_MINTD_PID
 }
 }
 
 
 # Set up trap to call cleanup on script exit
 # Set up trap to call cleanup on script exit
 trap cleanup EXIT
 trap cleanup EXIT
 
 
 # Create a temporary directory
 # Create a temporary directory
-export cdk_itests=$(mktemp -d)
-export cdk_itests_mint_addr="127.0.0.1";
-export cdk_itests_mint_port=8086;
+export CDK_ITESTS_DIR=$(mktemp -d)
+export CDK_ITESTS_MINT_ADDR="127.0.0.1"
+export CDK_ITESTS_MINT_PORT=8086
 
 
 # Check if the temporary directory was created successfully
 # Check if the temporary directory was created successfully
-if [[ ! -d "$cdk_itests" ]]; then
+if [[ ! -d "$CDK_ITESTS_DIR" ]]; then
     echo "Failed to create temp directory"
     echo "Failed to create temp directory"
     exit 1
     exit 1
 fi
 fi
 
 
-echo "Temp directory created: $cdk_itests"
-export MINT_DATABASE="$1";
+echo "Temp directory created: $CDK_ITESTS_DIR"
+export CDK_MINTD_DATABASE="$1"
 
 
 cargo build -p cdk-integration-tests 
 cargo build -p cdk-integration-tests 
 
 
 
 
-export CDK_MINTD_URL="http://$cdk_itests_mint_addr:$cdk_itests_mint_port";
-export CDK_MINTD_WORK_DIR="$cdk_itests";
-export CDK_MINTD_LISTEN_HOST=$cdk_itests_mint_addr;
-export CDK_MINTD_LISTEN_PORT=$cdk_itests_mint_port;
-export CDK_MINTD_LN_BACKEND="fakewallet";
-export CDK_MINTD_FAKE_WALLET_SUPPORTED_UNITS="sat,usd";
-export CDK_MINTD_MNEMONIC="eye survey guilt napkin crystal cup whisper salt luggage manage unveil loyal";
-export CDK_MINTD_FAKE_WALLET_FEE_PERCENT="0";
-export CDK_MINTD_FAKE_WALLET_RESERVE_FEE_MIN="1";
-export CDK_MINTD_DATABASE=$MINT_DATABASE;
+export CDK_MINTD_URL="http://$CDK_ITESTS_MINT_ADDR:$CDK_ITESTS_MINT_PORT"
+export CDK_MINTD_WORK_DIR="$CDK_ITESTS_DIR"
+export CDK_MINTD_LISTEN_HOST=$CDK_ITESTS_MINT_ADDR
+export CDK_MINTD_LISTEN_PORT=$CDK_ITESTS_MINT_PORT
+export CDK_MINTD_LN_BACKEND="fakewallet"
+export CDK_MINTD_FAKE_WALLET_SUPPORTED_UNITS="sat,usd"
+export CDK_MINTD_MNEMONIC="eye survey guilt napkin crystal cup whisper salt luggage manage unveil loyal"
+export CDK_MINTD_FAKE_WALLET_FEE_PERCENT="0"
+export CDK_MINTD_FAKE_WALLET_RESERVE_FEE_MIN="1"
 
 
 
 
-echo "Starting fake mintd";
+echo "Starting fake mintd"
 cargo run --bin cdk-mintd --features "redb" &
 cargo run --bin cdk-mintd --features "redb" &
-cdk_mintd_pid=$!
+export CDK_MINTD_PID=$!
 
 
-URL="http://$cdk_itests_mint_addr:$cdk_itests_mint_port/v1/info"
+URL="http://$CDK_ITESTS_MINT_ADDR:$CDK_ITESTS_MINT_PORT/v1/info"
 TIMEOUT=100
 TIMEOUT=100
 START_TIME=$(date +%s)
 START_TIME=$(date +%s)
 # Loop until the endpoint returns a 200 OK status or timeout is reached
 # Loop until the endpoint returns a 200 OK status or timeout is reached
@@ -85,12 +98,28 @@ while true; do
 done
 done
 
 
 
 
-# Run cargo test
+export CDK_TEST_MINT_URL="http://$CDK_ITESTS_MINT_ADDR:$CDK_ITESTS_MINT_PORT"
+
+# Run first test
 cargo test -p cdk-integration-tests --test fake_wallet
 cargo test -p cdk-integration-tests --test fake_wallet
-# cargo test -p cdk-integration-tests --test mint
+status1=$?
+
+# Exit immediately if the first test failed
+if [ $status1 -ne 0 ]; then
+    echo "First test failed with status $status1, exiting"
+    exit $status1
+fi
+
+# Run second test only if the first one succeeded
+cargo test -p cdk-integration-tests --test happy_path_mint_wallet
+status2=$?
 
 
-# Capture the exit status of cargo test
-test_status=$?
+# Exit with the status of the second test
+if [ $status2 -ne 0 ]; then
+    echo "Second test failed with status $status2, exiting"
+    exit $status2
+fi
 
 
-# Exit with the status of the testexit $test_status
-exit $test_status
+# Both tests passed
+echo "All tests passed successfully"
+exit 0

+ 114 - 56
misc/itests.sh

@@ -5,67 +5,90 @@ cleanup() {
     echo "Cleaning up..."
     echo "Cleaning up..."
 
 
     echo "Killing the cdk mintd"
     echo "Killing the cdk mintd"
-    kill -2 $cdk_mintd_pid
-    wait $cdk_mintd_pid
+    kill -2 $CDK_MINTD_PID
+    wait $CDK_MINTD_PID
 
 
     
     
     echo "Killing the cdk lnd mintd"
     echo "Killing the cdk lnd mintd"
-    kill -2 $cdk_mintd_lnd_pid
-    wait $cdk_mintd_lnd_pid
+    kill -2 $CDK_MINTD_LND_PID
+    wait $CDK_MINTD_LND_PID
 
 
     echo "Killing the cdk regtest"
     echo "Killing the cdk regtest"
-    kill -2 $cdk_regtest_pid
-    wait $cdk_regtest_pid
+    kill -2 $CDK_REGTEST_PID
+    wait $CDK_REGTEST_PID
 
 
 
 
     echo "Mint binary terminated"
     echo "Mint binary terminated"
 
 
     # Remove the temporary directory
     # Remove the temporary directory
-    rm -rf "$cdk_itests"
-    echo "Temp directory removed: $cdk_itests"
-    unset cdk_itests
-    unset cdk_itests_mint_addr
-    unset cdk_itests_mint_port
+    rm -rf "$CDK_ITESTS_DIR"
+    echo "Temp directory removed: $CDK_ITESTS_DIR"
+    
+    # Unset all environment variables
+    unset CDK_ITESTS_DIR
+    unset CDK_ITESTS_MINT_ADDR
+    unset CDK_ITESTS_MINT_PORT_0
+    unset CDK_ITESTS_MINT_PORT_1
+    unset CDK_MINTD_DATABASE
+    unset CDK_TEST_MINT_URL
+    unset CDK_TEST_MINT_URL_2
+    unset CDK_MINTD_URL
+    unset CDK_MINTD_WORK_DIR
+    unset CDK_MINTD_LISTEN_HOST
+    unset CDK_MINTD_LISTEN_PORT
+    unset CDK_MINTD_LN_BACKEND
+    unset CDK_MINTD_MNEMONIC
+    unset CDK_MINTD_CLN_RPC_PATH
+    unset CDK_MINTD_LND_ADDRESS
+    unset CDK_MINTD_LND_CERT_FILE
+    unset CDK_MINTD_LND_MACAROON_FILE
+    unset CDK_MINTD_PID
+    unset CDK_MINTD_LND_PID
+    unset CDK_REGTEST_PID
+    unset RUST_BACKTRACE
+    unset CDK_TEST_REGTEST
 }
 }
 
 
 # Set up trap to call cleanup on script exit
 # Set up trap to call cleanup on script exit
 trap cleanup EXIT
 trap cleanup EXIT
 
 
+export CDK_TEST_REGTEST=1
+
 # Create a temporary directory
 # Create a temporary directory
-export cdk_itests=$(mktemp -d)
-export cdk_itests_mint_addr="127.0.0.1";
-export cdk_itests_mint_port_0=8085;
-export cdk_itests_mint_port_1=8087;
+export CDK_ITESTS_DIR=$(mktemp -d)
+export CDK_ITESTS_MINT_ADDR="127.0.0.1"
+export CDK_ITESTS_MINT_PORT_0=8085
+export CDK_ITESTS_MINT_PORT_1=8087
 
 
 # Check if the temporary directory was created successfully
 # Check if the temporary directory was created successfully
-if [[ ! -d "$cdk_itests" ]]; then
+if [[ ! -d "$CDK_ITESTS_DIR" ]]; then
     echo "Failed to create temp directory"
     echo "Failed to create temp directory"
     exit 1
     exit 1
 fi
 fi
 
 
-echo "Temp directory created: $cdk_itests"
-export MINT_DATABASE="$1";
+echo "Temp directory created: $CDK_ITESTS_DIR"
+export CDK_MINTD_DATABASE="$1"
 
 
 cargo build -p cdk-integration-tests 
 cargo build -p cdk-integration-tests 
 
 
 cargo run --bin start_regtest &
 cargo run --bin start_regtest &
 
 
-cdk_regtest_pid=$!
-mkfifo "$cdk_itests/progress_pipe"
-rm -f "$cdk_itests/signal_received"  # Ensure clean state
+export CDK_REGTEST_PID=$!
+mkfifo "$CDK_ITESTS_DIR/progress_pipe"
+rm -f "$CDK_ITESTS_DIR/signal_received"  # Ensure clean state
 # Start reading from pipe in background
 # Start reading from pipe in background
 (while read line; do
 (while read line; do
     case "$line" in
     case "$line" in
         "checkpoint1")
         "checkpoint1")
             echo "Reached first checkpoint"
             echo "Reached first checkpoint"
-            touch "$cdk_itests/signal_received"
+            touch "$CDK_ITESTS_DIR/signal_received"
             exit 0
             exit 0
             ;;
             ;;
     esac
     esac
-done < "$cdk_itests/progress_pipe") &
+done < "$CDK_ITESTS_DIR/progress_pipe") &
 # Wait for up to 120 seconds
 # Wait for up to 120 seconds
 for ((i=0; i<120; i++)); do
 for ((i=0; i<120; i++)); do
-    if [ -f "$cdk_itests/signal_received" ]; then
+    if [ -f "$CDK_ITESTS_DIR/signal_received" ]; then
         echo "break signal received"
         echo "break signal received"
         break
         break
     fi
     fi
@@ -76,24 +99,23 @@ echo "Regtest set up continuing"
 echo "Starting regtest mint"
 echo "Starting regtest mint"
 # cargo run --bin regtest_mint &
 # cargo run --bin regtest_mint &
 
 
-export CDK_MINTD_CLN_RPC_PATH="$cdk_itests/cln/one/regtest/lightning-rpc";
-export CDK_MINTD_URL="http://$cdk_itests_mint_addr:$cdk_itests_mint_port_0";
-export CDK_MINTD_WORK_DIR="$cdk_itests";
-export CDK_MINTD_LISTEN_HOST=$cdk_itests_mint_addr;
-export CDK_MINTD_LISTEN_PORT=$cdk_itests_mint_port_0;
-export CDK_MINTD_LN_BACKEND="cln";
-export CDK_MINTD_MNEMONIC="eye survey guilt napkin crystal cup whisper salt luggage manage unveil loyal";
-export CDK_MINTD_DATABASE=$MINT_DATABASE;
+export CDK_MINTD_CLN_RPC_PATH="$CDK_ITESTS_DIR/cln/one/regtest/lightning-rpc"
+export CDK_MINTD_URL="http://$CDK_ITESTS_MINT_ADDR:$CDK_ITESTS_MINT_PORT_0"
+export CDK_MINTD_WORK_DIR="$CDK_ITESTS_DIR"
+export CDK_MINTD_LISTEN_HOST=$CDK_ITESTS_MINT_ADDR
+export CDK_MINTD_LISTEN_PORT=$CDK_ITESTS_MINT_PORT_0
+export CDK_MINTD_LN_BACKEND="cln"
+export CDK_MINTD_MNEMONIC="eye survey guilt napkin crystal cup whisper salt luggage manage unveil loyal"
 export RUST_BACKTRACE=1
 export RUST_BACKTRACE=1
 
 
-echo "Starting cln mintd";
+echo "Starting cln mintd"
 cargo run --bin cdk-mintd --features "redb" &
 cargo run --bin cdk-mintd --features "redb" &
-cdk_mintd_pid=$!
+export CDK_MINTD_PID=$!
 
 
 
 
-echo $cdk_itests
+echo $CDK_ITESTS_DIR
 
 
-URL="http://$cdk_itests_mint_addr:$cdk_itests_mint_port_0/v1/info"
+URL="http://$CDK_ITESTS_MINT_ADDR:$CDK_ITESTS_MINT_PORT_0/v1/info"
 
 
 TIMEOUT=100
 TIMEOUT=100
 START_TIME=$(date +%s)
 START_TIME=$(date +%s)
@@ -125,23 +147,23 @@ while true; do
 done
 done
 
 
 
 
-export CDK_MINTD_LND_ADDRESS="https://localhost:10010";
-export CDK_MINTD_LND_CERT_FILE="$cdk_itests/lnd/two/tls.cert";
-export CDK_MINTD_LND_MACAROON_FILE="$cdk_itests/lnd/two/data/chain/bitcoin/regtest/admin.macaroon";
+export CDK_MINTD_LND_ADDRESS="https://localhost:10010"
+export CDK_MINTD_LND_CERT_FILE="$CDK_ITESTS_DIR/lnd/two/tls.cert"
+export CDK_MINTD_LND_MACAROON_FILE="$CDK_ITESTS_DIR/lnd/two/data/chain/bitcoin/regtest/admin.macaroon"
 
 
-export CDK_MINTD_URL="http://$cdk_itests_mint_addr:$cdk_itests_mint_port_1";
-mkdir -p "$cdk_itests/lnd_mint"
-export CDK_MINTD_WORK_DIR="$cdk_itests/lnd_mint";
-export CDK_MINTD_LISTEN_HOST=$cdk_itests_mint_addr;
-export CDK_MINTD_LISTEN_PORT=$cdk_itests_mint_port_1;
-export CDK_MINTD_LN_BACKEND="lnd";
-export CDK_MINTD_MNEMONIC="eye survey guilt napkin crystal cup whisper salt luggage manage unveil loyal";
+export CDK_MINTD_URL="http://$CDK_ITESTS_MINT_ADDR:$CDK_ITESTS_MINT_PORT_1"
+mkdir -p "$CDK_ITESTS_DIR/lnd_mint"
+export CDK_MINTD_WORK_DIR="$CDK_ITESTS_DIR/lnd_mint"
+export CDK_MINTD_LISTEN_HOST=$CDK_ITESTS_MINT_ADDR
+export CDK_MINTD_LISTEN_PORT=$CDK_ITESTS_MINT_PORT_1
+export CDK_MINTD_LN_BACKEND="lnd"
+export CDK_MINTD_MNEMONIC="cattle gold bind busy sound reduce tone addict baby spend february strategy"
 
 
-echo "Starting lnd mintd";
+echo "Starting lnd mintd"
 cargo run --bin cdk-mintd --features "redb" &
 cargo run --bin cdk-mintd --features "redb" &
-cdk_mintd_lnd_pid=$!
+export CDK_MINTD_LND_PID=$!
 
 
-URL="http://$cdk_itests_mint_addr:$cdk_itests_mint_port_1/v1/info"
+URL="http://$CDK_ITESTS_MINT_ADDR:$CDK_ITESTS_MINT_PORT_1/v1/info"
 
 
 TIMEOUT=100
 TIMEOUT=100
 START_TIME=$(date +%s)
 START_TIME=$(date +%s)
@@ -173,19 +195,55 @@ while true; do
 done
 done
 
 
 
 
+
+export CDK_TEST_MINT_URL="http://$CDK_ITESTS_MINT_ADDR:$CDK_ITESTS_MINT_PORT_0"
+export CDK_TEST_MINT_URL_2="http://$CDK_ITESTS_MINT_ADDR:$CDK_ITESTS_MINT_PORT_1"
+
+# Run tests and exit immediately on failure
+
 # Run cargo test
 # Run cargo test
+echo "Running regtest test with CLN mint"
 cargo test -p cdk-integration-tests --test regtest
 cargo test -p cdk-integration-tests --test regtest
+if [ $? -ne 0 ]; then
+    echo "regtest test failed, exiting"
+    exit 1
+fi
 
 
-# Run cargo test with the http_subscription feature
+echo "Running happy_path_mint_wallet test with CLN mint"
+cargo test -p cdk-integration-tests --test happy_path_mint_wallet test_happy_mint_melt_round_trip
+if [ $? -ne 0 ]; then
+    echo "happy_path_mint_wallet test failed, exiting"
+    exit 1
+fi
+
+# # Run cargo test with the http_subscription feature
+echo "Running regtest test with http_subscription feature"
 cargo test -p cdk-integration-tests --test regtest --features http_subscription
 cargo test -p cdk-integration-tests --test regtest --features http_subscription
+if [ $? -ne 0 ]; then
+    echo "regtest test with http_subscription failed, exiting"
+    exit 1
+fi
 
 
 # Switch Mints: Run tests with LND mint
 # Switch Mints: Run tests with LND mint
-export cdk_itests_mint_port_0=8087;
-export cdk_itests_mint_port_1=8085;
+echo "Switching to LND mint for tests"
+export CDK_ITESTS_MINT_PORT_0=8087
+export CDK_ITESTS_MINT_PORT_1=8085
+export CDK_TEST_MINT_URL="http://$CDK_ITESTS_MINT_ADDR:$CDK_ITESTS_MINT_PORT_0"
+export CDK_TEST_MINT_URL_2="http://$CDK_ITESTS_MINT_ADDR:$CDK_ITESTS_MINT_PORT_1"
+
+echo "Running regtest test with LND mint"
 cargo test -p cdk-integration-tests --test regtest
 cargo test -p cdk-integration-tests --test regtest
+if [ $? -ne 0 ]; then
+    echo "regtest test with LND mint failed, exiting"
+    exit 1
+fi
 
 
-# Capture the exit status of cargo test
-test_status=$?
+echo "Running happy_path_mint_wallet test with LND mint"
+cargo test -p cdk-integration-tests --test happy_path_mint_wallet
+if [ $? -ne 0 ]; then
+    echo "happy_path_mint_wallet test with LND mint failed, exiting"
+    exit 1
+fi
 
 
-# Exit with the status of the tests
-exit $test_status
+echo "All tests passed successfully"
+exit 0

+ 63 - 36
misc/mintd_payment_processor.sh

@@ -6,69 +6,96 @@ cleanup() {
 
 
 
 
     echo "Killing the cdk payment processor"
     echo "Killing the cdk payment processor"
-    kill -2 $cdk_payment_processor_pid
-    wait $cdk_payment_processor_pid
+    kill -2 $CDK_PAYMENT_PROCESSOR_PID
+    wait $CDK_PAYMENT_PROCESSOR_PID
 
 
     echo "Killing the cdk mintd"
     echo "Killing the cdk mintd"
-    kill -2 $cdk_mintd_pid
-    wait $cdk_mintd_pid
+    kill -2 $CDK_MINTD_PID
+    wait $CDK_MINTD_PID
 
 
     echo "Killing the cdk regtest"
     echo "Killing the cdk regtest"
-    kill -2 $cdk_regtest_pid
-    wait $cdk_regtest_pid
+    kill -2 $CDK_REGTEST_PID
+    wait $CDK_REGTEST_PID
 
 
     echo "Mint binary terminated"
     echo "Mint binary terminated"
 
 
     # Remove the temporary directory
     # Remove the temporary directory
-    rm -rf "$cdk_itests"
-    echo "Temp directory removed: $cdk_itests"
-    unset cdk_itests
-    unset cdk_itests_mint_addr
-    unset cdk_itests_mint_port
+    rm -rf "$CDK_ITESTS_DIR"
+    echo "Temp directory removed: $CDK_ITESTS_DIR"
+    
+    # Unset all environment variables that were set
+    unset CDK_ITESTS_DIR
+    unset CDK_ITESTS_MINT_ADDR
+    unset CDK_ITESTS_MINT_PORT_0
+    unset CDK_REGTEST_PID
+    unset LN_BACKEND
+    unset MINT_DATABASE
+    unset CDK_TEST_REGTEST
+    unset CDK_TEST_MINT_URL
+    unset CDK_PAYMENT_PROCESSOR_CLN_RPC_PATH
+    unset CDK_PAYMENT_PROCESSOR_LND_ADDRESS
+    unset CDK_PAYMENT_PROCESSOR_LND_CERT_FILE
+    unset CDK_PAYMENT_PROCESSOR_LND_MACAROON_FILE
+    unset CDK_PAYMENT_PROCESSOR_LN_BACKEND
+    unset CDK_PAYMENT_PROCESSOR_LISTEN_HOST
+    unset CDK_PAYMENT_PROCESSOR_LISTEN_PORT
+    unset CDK_PAYMENT_PROCESSOR_PID
+    unset CDK_MINTD_URL
+    unset CDK_MINTD_WORK_DIR
+    unset CDK_MINTD_LISTEN_HOST
+    unset CDK_MINTD_LISTEN_PORT
+    unset CDK_MINTD_LN_BACKEND
+    unset CDK_MINTD_GRPC_PAYMENT_PROCESSOR_ADDRESS
+    unset CDK_MINTD_GRPC_PAYMENT_PROCESSOR_PORT
+    unset CDK_MINTD_GRPC_PAYMENT_PROCESSOR_SUPPORTED_UNITS
+    unset CDK_MINTD_MNEMONIC
+    unset CDK_MINTD_PID
 }
 }
 
 
 # Set up trap to call cleanup on script exit
 # Set up trap to call cleanup on script exit
 trap cleanup EXIT
 trap cleanup EXIT
 
 
 # Create a temporary directory
 # Create a temporary directory
-export cdk_itests=$(mktemp -d)
-export cdk_itests_mint_addr="127.0.0.1";
-export cdk_itests_mint_port_0=8086;
+export CDK_ITESTS_DIR=$(mktemp -d)
+export CDK_ITESTS_MINT_ADDR="127.0.0.1";
+export CDK_ITESTS_MINT_PORT_0=8086;
 
 
 
 
 export LN_BACKEND="$1";
 export LN_BACKEND="$1";
 
 
-URL="http://$cdk_itests_mint_addr:$cdk_itests_mint_port_0/v1/info"
+URL="http://$CDK_ITESTS_MINT_ADDR:$CDK_ITESTS_MINT_PORT_0/v1/info"
 # Check if the temporary directory was created successfully
 # Check if the temporary directory was created successfully
-if [[ ! -d "$cdk_itests" ]]; then
+if [[ ! -d "$CDK_ITESTS_DIR" ]]; then
     echo "Failed to create temp directory"
     echo "Failed to create temp directory"
     exit 1
     exit 1
 fi
 fi
 
 
-echo "Temp directory created: $cdk_itests"
+echo "Temp directory created: $CDK_ITESTS_DIR"
 export MINT_DATABASE="$1";
 export MINT_DATABASE="$1";
 
 
 cargo build -p cdk-integration-tests 
 cargo build -p cdk-integration-tests 
 
 
 
 
+export CDK_TEST_REGTEST=0
 if [ "$LN_BACKEND" != "FAKEWALLET" ]; then
 if [ "$LN_BACKEND" != "FAKEWALLET" ]; then
+    export CDK_TEST_REGTEST=1
     cargo run --bin start_regtest &
     cargo run --bin start_regtest &
-    cdk_regtest_pid=$!
-    mkfifo "$cdk_itests/progress_pipe"
-    rm -f "$cdk_itests/signal_received"  # Ensure clean state
+    CDK_REGTEST_PID=$!
+    mkfifo "$CDK_ITESTS_DIR/progress_pipe"
+    rm -f "$CDK_ITESTS_DIR/signal_received"  # Ensure clean state
     # Start reading from pipe in background
     # Start reading from pipe in background
     (while read line; do
     (while read line; do
         case "$line" in
         case "$line" in
             "checkpoint1")
             "checkpoint1")
                 echo "Reached first checkpoint"
                 echo "Reached first checkpoint"
-                touch "$cdk_itests/signal_received"
+                touch "$CDK_ITESTS_DIR/signal_received"
                 exit 0
                 exit 0
                 ;;
                 ;;
         esac
         esac
-    done < "$cdk_itests/progress_pipe") &
+    done < "$CDK_ITESTS_DIR/progress_pipe") &
     # Wait for up to 120 seconds
     # Wait for up to 120 seconds
     for ((i=0; i<120; i++)); do
     for ((i=0; i<120; i++)); do
-        if [ -f "$cdk_itests/signal_received" ]; then
+        if [ -f "$CDK_ITESTS_DIR/signal_received" ]; then
             echo "break signal received"
             echo "break signal received"
             break
             break
         fi
         fi
@@ -80,11 +107,13 @@ fi
 # Start payment processor
 # Start payment processor
 
 
 
 
-export CDK_PAYMENT_PROCESSOR_CLN_RPC_PATH="$cdk_itests/cln/one/regtest/lightning-rpc";
+export CDK_TEST_MINT_URL="http://$CDK_ITESTS_MINT_ADDR:$CDK_ITESTS_MINT_PORT_0"
+
+export CDK_PAYMENT_PROCESSOR_CLN_RPC_PATH="$CDK_ITESTS_DIR/cln/one/regtest/lightning-rpc";
 
 
 export CDK_PAYMENT_PROCESSOR_LND_ADDRESS="https://localhost:10010";
 export CDK_PAYMENT_PROCESSOR_LND_ADDRESS="https://localhost:10010";
-export CDK_PAYMENT_PROCESSOR_LND_CERT_FILE="$cdk_itests/lnd/two/tls.cert";
-export CDK_PAYMENT_PROCESSOR_LND_MACAROON_FILE="$cdk_itests/lnd/two/data/chain/bitcoin/regtest/admin.macaroon";
+export CDK_PAYMENT_PROCESSOR_LND_CERT_FILE="$CDK_ITESTS_DIR/lnd/two/tls.cert";
+export CDK_PAYMENT_PROCESSOR_LND_MACAROON_FILE="$CDK_ITESTS_DIR/lnd/two/data/chain/bitcoin/regtest/admin.macaroon";
 
 
 export CDK_PAYMENT_PROCESSOR_LN_BACKEND=$LN_BACKEND;
 export CDK_PAYMENT_PROCESSOR_LN_BACKEND=$LN_BACKEND;
 export CDK_PAYMENT_PROCESSOR_LISTEN_HOST="127.0.0.1";
 export CDK_PAYMENT_PROCESSOR_LISTEN_HOST="127.0.0.1";
@@ -94,14 +123,14 @@ echo "$CDK_PAYMENT_PROCESSOR_CLN_RPC_PATH"
 
 
 cargo run --bin cdk-payment-processor &
 cargo run --bin cdk-payment-processor &
 
 
-cdk_payment_processor_pid=$!
+CDK_PAYMENT_PROCESSOR_PID=$!
 
 
 sleep 10;
 sleep 10;
 
 
-export CDK_MINTD_URL="http://$cdk_itests_mint_addr:$cdk_itests_mint_port_0";
-export CDK_MINTD_WORK_DIR="$cdk_itests";
-export CDK_MINTD_LISTEN_HOST=$cdk_itests_mint_addr;
-export CDK_MINTD_LISTEN_PORT=$cdk_itests_mint_port_0;
+export CDK_MINTD_URL="http://$CDK_ITESTS_MINT_ADDR:$CDK_ITESTS_MINT_PORT_0";
+export CDK_MINTD_WORK_DIR="$CDK_ITESTS_DIR";
+export CDK_MINTD_LISTEN_HOST=$CDK_ITESTS_MINT_ADDR;
+export CDK_MINTD_LISTEN_PORT=$CDK_ITESTS_MINT_PORT_0;
 export CDK_MINTD_LN_BACKEND="grpcprocessor";
 export CDK_MINTD_LN_BACKEND="grpcprocessor";
 export CDK_MINTD_GRPC_PAYMENT_PROCESSOR_ADDRESS="http://127.0.0.1";
 export CDK_MINTD_GRPC_PAYMENT_PROCESSOR_ADDRESS="http://127.0.0.1";
 export CDK_MINTD_GRPC_PAYMENT_PROCESSOR_PORT="8090";
 export CDK_MINTD_GRPC_PAYMENT_PROCESSOR_PORT="8090";
@@ -109,9 +138,9 @@ export CDK_MINTD_GRPC_PAYMENT_PROCESSOR_SUPPORTED_UNITS="sat";
 export CDK_MINTD_MNEMONIC="eye survey guilt napkin crystal cup whisper salt luggage manage unveil loyal";
 export CDK_MINTD_MNEMONIC="eye survey guilt napkin crystal cup whisper salt luggage manage unveil loyal";
  
  
 cargo run --bin cdk-mintd --no-default-features --features grpc-processor &
 cargo run --bin cdk-mintd --no-default-features --features grpc-processor &
-cdk_mintd_pid=$!
+CDK_MINTD_PID=$!
 
 
-echo $cdk_itests
+echo $CDK_ITESTS_DIR
 
 
 TIMEOUT=100
 TIMEOUT=100
 START_TIME=$(date +%s)
 START_TIME=$(date +%s)
@@ -143,10 +172,8 @@ while true; do
 done
 done
 
 
 
 
-cargo test -p cdk-integration-tests --test payment_processor
+cargo test -p cdk-integration-tests --test happy_path_mint_wallet
 
 
-# Run cargo test
-# cargo test -p cdk-integration-tests --test fake_wallet
 # Capture the exit status of cargo test
 # Capture the exit status of cargo test
 test_status=$?
 test_status=$?