Skip to content

Commit

Permalink
Merge pull request #569 from thesimplekid/move_config_to_db
Browse files Browse the repository at this point in the history
refactor: Move mint info and quote ttl to database
  • Loading branch information
thesimplekid authored Jan 30, 2025
2 parents e3fb7f9 + 9497142 commit afb7633
Show file tree
Hide file tree
Showing 24 changed files with 336 additions and 266 deletions.
5 changes: 0 additions & 5 deletions crates/cashu/src/mint.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ use bitcoin::bip32::DerivationPath;
use serde::{Deserialize, Serialize};
use uuid::Uuid;

use crate::mint_url::MintUrl;
use crate::nuts::{MeltQuoteState, MintQuoteState};
use crate::{Amount, CurrencyUnit, Id, KeySetInfo, PublicKey};

Expand All @@ -13,8 +12,6 @@ use crate::{Amount, CurrencyUnit, Id, KeySetInfo, PublicKey};
pub struct MintQuote {
/// Quote id
pub id: Uuid,
/// Mint Url
pub mint_url: MintUrl,
/// Amount of quote
pub amount: Amount,
/// Unit of quote
Expand All @@ -34,7 +31,6 @@ pub struct MintQuote {
impl MintQuote {
/// Create new [`MintQuote`]
pub fn new(
mint_url: MintUrl,
request: String,
unit: CurrencyUnit,
amount: Amount,
Expand All @@ -45,7 +41,6 @@ impl MintQuote {
let id = Uuid::new_v4();

Self {
mint_url,
id,
amount,
unit,
Expand Down
13 changes: 12 additions & 1 deletion crates/cdk-axum/src/router_handlers.rs
Original file line number Diff line number Diff line change
Expand Up @@ -342,7 +342,18 @@ pub async fn post_check(
))]
/// Mint information, operator contact information, and other info
pub async fn get_mint_info(State(state): State<MintState>) -> Result<Json<MintInfo>, Response> {
Ok(Json(state.mint.mint_info().clone().time(unix_time())))
Ok(Json(
state
.mint
.mint_info()
.await
.map_err(|err| {
tracing::error!("Could not get mint info: {}", err);
into_response(err)
})?
.clone()
.time(unix_time()),
))
}

#[cfg_attr(feature = "swagger", utoipa::path(
Expand Down
13 changes: 12 additions & 1 deletion crates/cdk-common/src/database/mint.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,11 @@
use std::collections::HashMap;

use async_trait::async_trait;
use cashu::MintInfo;
use uuid::Uuid;

use super::Error;
use crate::common::LnKey;
use crate::common::{LnKey, QuoteTTL};
use crate::mint::{self, MintKeySetInfo, MintQuote as MintMintQuote};
use crate::nuts::{
BlindSignature, CurrencyUnit, Id, MeltBolt11Request, MeltQuoteState, MintQuoteState, Proof,
Expand Down Expand Up @@ -127,4 +128,14 @@ pub trait Database {
&self,
quote_id: &Uuid,
) -> Result<Vec<BlindSignature>, Self::Err>;

/// Set [`MintInfo`]
async fn set_mint_info(&self, mint_info: MintInfo) -> Result<(), Self::Err>;
/// Get [`MintInfo`]
async fn get_mint_info(&self) -> Result<MintInfo, Self::Err>;

/// Set [`QuoteTTL`]
async fn set_quote_ttl(&self, quote_ttl: QuoteTTL) -> Result<(), Self::Err>;
/// Get [`QuoteTTL`]
async fn get_quote_ttl(&self) -> Result<QuoteTTL, Self::Err>;
}
1 change: 0 additions & 1 deletion crates/cdk-integration-tests/src/init_fake_wallet.rs
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,6 @@ where

mint_builder = mint_builder
.with_name("fake test mint".to_string())
.with_mint_url(format!("http://{addr}:{port}"))
.with_description("fake test mint".to_string())
.with_quote_ttl(10000, 10000)
.with_seed(mnemonic.to_seed_normalized("").to_vec());
Expand Down
11 changes: 3 additions & 8 deletions crates/cdk-integration-tests/src/init_pure_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -38,11 +38,7 @@ impl DirectMintConnection {

impl Debug for DirectMintConnection {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
write!(
f,
"DirectMintConnection {{ mint_info: {:?} }}",
self.mint.config.mint_info()
)
write!(f, "DirectMintConnection",)
}
}

Expand Down Expand Up @@ -130,7 +126,7 @@ impl MintConnector for DirectMintConnection {
}

async fn get_mint_info(&self) -> Result<MintInfo, Error> {
Ok(self.mint.mint_info().clone().time(unix_time()))
Ok(self.mint.mint_info().await?.clone().time(unix_time()))
}

async fn post_check_state(
Expand Down Expand Up @@ -175,7 +171,6 @@ pub async fn create_and_start_test_mint() -> anyhow::Result<Arc<Mint>> {

mint_builder = mint_builder
.with_name("pure test mint".to_string())
.with_mint_url("http://aa".to_string())
.with_description("pure test mint".to_string())
.with_quote_ttl(10000, 10000)
.with_seed(mnemonic.to_seed_normalized("").to_vec());
Expand All @@ -198,7 +193,7 @@ pub fn create_test_wallet_for_mint(mint: Arc<Mint>) -> anyhow::Result<Arc<Wallet
let connector = DirectMintConnection::new(mint);

let seed = Mnemonic::generate(12)?.to_seed_normalized("");
let mint_url = connector.mint.config.mint_url().to_string();
let mint_url = "http://aa".to_string();
let unit = CurrencyUnit::Sat;
let localstore = WalletMemoryDatabase::default();
let mut wallet = Wallet::new(&mint_url, unit, Arc::new(localstore), &seed, None)?;
Expand Down
1 change: 0 additions & 1 deletion crates/cdk-integration-tests/src/init_regtest.rs
Original file line number Diff line number Diff line change
Expand Up @@ -169,7 +169,6 @@ where

mint_builder = mint_builder
.with_name("regtest mint".to_string())
.with_mint_url(format!("http://{addr}:{port}"))
.with_description("regtest mint".to_string())
.with_quote_ttl(10000, 10000)
.with_seed(mnemonic.to_seed_normalized("").to_vec());
Expand Down
16 changes: 8 additions & 8 deletions crates/cdk-integration-tests/tests/mint.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ use anyhow::{bail, Result};
use bip39::Mnemonic;
use cdk::amount::{Amount, SplitTarget};
use cdk::cdk_database::mint_memory::MintMemoryDatabase;
use cdk::cdk_database::MintDatabase;
use cdk::dhke::construct_proofs;
use cdk::mint::MintQuote;
use cdk::nuts::nut00::ProofsMethods;
Expand All @@ -16,7 +17,6 @@ use cdk::nuts::{
ProofState, Proofs, SecretKey, SpendingConditions, State, SwapRequest,
};
use cdk::subscription::{IndexableParams, Params};
use cdk::types::QuoteTTL;
use cdk::util::unix_time;
use cdk::Mint;
use tokio::sync::OnceCell;
Expand All @@ -41,16 +41,17 @@ async fn new_mint(fee: u64) -> Mint {

let mint_info = MintInfo::new().nuts(nuts);

let mnemonic = Mnemonic::generate(12).unwrap();
let localstore = MintMemoryDatabase::default();

let quote_ttl = QuoteTTL::new(10000, 10000);
localstore
.set_mint_info(mint_info)
.await
.expect("Could not set mint info");
let mnemonic = Mnemonic::generate(12).unwrap();

Mint::new(
MINT_URL,
&mnemonic.to_seed_normalized(""),
mint_info,
quote_ttl,
Arc::new(MintMemoryDatabase::default()),
Arc::new(localstore),
HashMap::new(),
supported_units,
HashMap::new(),
Expand All @@ -72,7 +73,6 @@ async fn mint_proofs(
let request_lookup = uuid::Uuid::new_v4().to_string();

let quote = MintQuote::new(
mint.config.mint_url(),
"".to_string(),
CurrencyUnit::Sat,
amount,
Expand Down
1 change: 0 additions & 1 deletion crates/cdk-mintd/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -301,7 +301,6 @@ async fn main() -> anyhow::Result<()> {

mint_builder = mint_builder
.with_name(settings.mint_info.name)
.with_mint_url(settings.info.url)
.with_version(mint_version)
.with_description(settings.mint_info.description)
.with_quote_ttl(10000, 10000)
Expand Down
3 changes: 3 additions & 0 deletions crates/cdk-redb/src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,9 @@ pub enum Error {
/// Unknown Mint Info
#[error("Unknown mint info")]
UnknownMintInfo,
/// Unknown quote ttl
#[error("Unknown quote ttl")]
UnknownQuoteTTL,
/// Unknown Proof Y
#[error("Unknown proof Y")]
UnknownY,
Expand Down
1 change: 0 additions & 1 deletion crates/cdk-redb/src/mint/migrations.rs
Original file line number Diff line number Diff line change
Expand Up @@ -202,7 +202,6 @@ impl From<V1MintQuote> for MintQuote {
fn from(quote: V1MintQuote) -> MintQuote {
MintQuote {
id: quote.id,
mint_url: quote.mint_url,
amount: quote.amount,
unit: quote.unit,
request: quote.request.clone(),
Expand Down
58 changes: 55 additions & 3 deletions crates/cdk-redb/src/mint/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,14 +7,14 @@ use std::str::FromStr;
use std::sync::Arc;

use async_trait::async_trait;
use cdk_common::common::LnKey;
use cdk_common::common::{LnKey, QuoteTTL};
use cdk_common::database::{self, MintDatabase};
use cdk_common::dhke::hash_to_curve;
use cdk_common::mint::{self, MintKeySetInfo, MintQuote};
use cdk_common::nut00::ProofsMethods;
use cdk_common::{
BlindSignature, CurrencyUnit, Id, MeltBolt11Request, MeltQuoteState, MintQuoteState, Proof,
Proofs, PublicKey, State,
BlindSignature, CurrencyUnit, Id, MeltBolt11Request, MeltQuoteState, MintInfo, MintQuoteState,
Proof, Proofs, PublicKey, State,
};
use migrations::{migrate_01_to_02, migrate_04_to_05};
use redb::{Database, MultimapTableDefinition, ReadableTable, TableDefinition};
Expand Down Expand Up @@ -812,4 +812,56 @@ impl MintDatabase for MintRedbDatabase {

Ok(signatures)
}

async fn set_mint_info(&self, mint_info: MintInfo) -> Result<(), Self::Err> {
let write_txn = self.db.begin_write().map_err(Error::from)?;

{
let mut table = write_txn.open_table(CONFIG_TABLE).map_err(Error::from)?;
table
.insert("mint_info", serde_json::to_string(&mint_info)?.as_str())
.map_err(Error::from)?;
}
write_txn.commit().map_err(Error::from)?;

Ok(())
}
async fn get_mint_info(&self) -> Result<MintInfo, Self::Err> {
let read_txn = self.db.begin_read().map_err(Error::from)?;
let table = read_txn.open_table(CONFIG_TABLE).map_err(Error::from)?;

if let Some(mint_info) = table.get("mint_info").map_err(Error::from)? {
let mint_info = serde_json::from_str(mint_info.value())?;

return Ok(mint_info);
}

Err(Error::UnknownMintInfo.into())
}

async fn set_quote_ttl(&self, quote_ttl: QuoteTTL) -> Result<(), Self::Err> {
let write_txn = self.db.begin_write().map_err(Error::from)?;

{
let mut table = write_txn.open_table(CONFIG_TABLE).map_err(Error::from)?;
table
.insert("quote_ttl", serde_json::to_string(&quote_ttl)?.as_str())
.map_err(Error::from)?;
}
write_txn.commit().map_err(Error::from)?;

Ok(())
}
async fn get_quote_ttl(&self) -> Result<QuoteTTL, Self::Err> {
let read_txn = self.db.begin_read().map_err(Error::from)?;
let table = read_txn.open_table(CONFIG_TABLE).map_err(Error::from)?;

if let Some(quote_ttl) = table.get("quote_ttl").map_err(Error::from)? {
let quote_ttl = serde_json::from_str(quote_ttl.value())?;

return Ok(quote_ttl);
}

Err(Error::UnknownQuoteTTL.into())
}
}
6 changes: 6 additions & 0 deletions crates/cdk-sqlite/src/mint/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,12 @@ pub enum Error {
/// Serde Error
#[error(transparent)]
Serde(#[from] serde_json::Error),
/// Unknown Mint Info
#[error("Unknown mint info")]
UnknownMintInfo,
/// Unknown quote TTL
#[error("Unknown quote TTL")]
UnknownQuoteTTL,
}

impl From<Error> for cdk_common::database::Error {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
ALTER TABLE mint_quote DROP COLUMN mint_url;
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
CREATE TABLE IF NOT EXISTS config (
id TEXT PRIMARY KEY,
value TEXT NOT NULL
);
Loading

0 comments on commit afb7633

Please sign in to comment.