Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Introduce a SignatoryManager service. #509

Draft
wants to merge 1 commit into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions crates/cashu/src/nuts/nut00/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -200,6 +200,18 @@ pub enum Witness {
HTLCWitness(HTLCWitness),
}

impl From<P2PKWitness> for Witness {
fn from(witness: P2PKWitness) -> Self {
Self::P2PKWitness(witness)
}
}

impl From<HTLCWitness> for Witness {
fn from(witness: HTLCWitness) -> Self {
Self::HTLCWitness(witness)
}
}

impl Witness {
/// Add signatures to [`Witness`]
pub fn add_signatures(&mut self, signatues: Vec<String>) {
Expand Down
8 changes: 8 additions & 0 deletions crates/cashu/src/nuts/nut01/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,14 @@ pub enum Error {
#[cfg_attr(feature = "swagger", derive(utoipa::ToSchema))]
pub struct Keys(BTreeMap<AmountStr, PublicKey>);

impl Deref for Keys {
type Target = BTreeMap<AmountStr, PublicKey>;

fn deref(&self) -> &Self::Target {
&self.0
}
}

impl From<MintKeys> for Keys {
fn from(keys: MintKeys) -> Self {
Self(
Expand Down
8 changes: 8 additions & 0 deletions crates/cdk-common/src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,14 @@ pub enum Error {
#[error("Amount Less Invoice is not allowed")]
AmountLessNotAllowed,

/// Internal Error - Send error
#[error("Internal send error: {0}")]
SendError(String),

/// Internal Error - Recv error
#[error("Internal receive error: {0}")]
RecvError(String),

// Mint Errors
/// Minting is disabled
#[error("Minting is disabled")]
Expand Down
2 changes: 2 additions & 0 deletions crates/cdk-common/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,8 @@ pub mod error;
pub mod lightning;
pub mod pub_sub;
#[cfg(feature = "mint")]
pub mod signatory;
#[cfg(feature = "mint")]
pub mod subscription;
pub mod ws;

Expand Down
50 changes: 50 additions & 0 deletions crates/cdk-common/src/signatory.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
//! Signatory mod
//!
//! This module abstract all the key related operations, defining an interface for the necessary
//! operations, to be implemented by the different signatory implementations.
//!
//! There is an in memory implementation, when the keys are stored in memory, in the same process,
//! but it is isolated from the rest of the application, and they communicate through a channel with
//! the defined API.
use std::collections::HashMap;

use bitcoin::bip32::DerivationPath;
use cashu::{
BlindSignature, BlindedMessage, CurrencyUnit, Id, KeySet, KeysResponse, KeysetResponse, Proof,
};

use super::error::Error;

#[async_trait::async_trait]
/// Signatory trait
pub trait Signatory {
/// Blind sign a message
async fn blind_sign(&self, blinded_message: BlindedMessage) -> Result<BlindSignature, Error>;

/// Verify [`Proof`] meets conditions and is signed
async fn verify_proof(&self, proof: Proof) -> Result<(), Error>;

/// Retrieve a keyset by id
async fn keyset(&self, keyset_id: Id) -> Result<Option<KeySet>, Error>;

/// Retrieve the public keys of a keyset
async fn keyset_pubkeys(&self, keyset_id: Id) -> Result<KeysResponse, Error>;

/// Retrieve the public keys of the active keyset for distribution to wallet
/// clients
async fn pubkeys(&self) -> Result<KeysResponse, Error>;

/// Return a list of all supported keysets
async fn keysets(&self) -> Result<KeysetResponse, Error>;

/// Add current keyset to inactive keysets
/// Generate new keyset
async fn rotate_keyset(
&self,
unit: CurrencyUnit,
derivation_path_index: u32,
max_order: u8,
input_fee_ppk: u64,
custom_paths: HashMap<CurrencyUnit, DerivationPath>,
) -> Result<(), Error>;
}
17 changes: 15 additions & 2 deletions crates/cdk-integration-tests/src/init_regtest.rs
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
use std::collections::HashMap;
use std::env;
use std::path::PathBuf;
use std::sync::Arc;

use anyhow::Result;
use bip39::Mnemonic;
use cdk::cdk_database::{self, MintDatabase};
use cdk::mint::{FeeReserve, MintBuilder, MintMeltLimits};
use cdk::mint::{FeeReserve, MemorySignatory, MintBuilder, MintMeltLimits};
use cdk::nuts::{CurrencyUnit, PaymentMethod};
use cdk_cln::Cln as CdkCln;
use ln_regtest_rs::bitcoin_client::BitcoinClient;
Expand Down Expand Up @@ -134,7 +135,9 @@ where

let mut mint_builder = MintBuilder::new();

mint_builder = mint_builder.with_localstore(Arc::new(database));
let localstore = Arc::new(database);

mint_builder = mint_builder.with_localstore(localstore.clone());

mint_builder = mint_builder.add_ln_backend(
CurrencyUnit::Sat,
Expand All @@ -145,8 +148,18 @@ where

let mnemonic = Mnemonic::generate(12)?;

let signatory_manager = MemorySignatory::new(
localstore,
&mnemonic.to_seed_normalized(""),
mint_builder.supported_units.clone(),
HashMap::new(),
)
.await
.expect("valid signatory");

mint_builder = mint_builder
.with_name("regtest mint".to_string())
.with_signatory(Arc::new(signatory_manager))
.with_mint_url(format!("http://{addr}:{port}"))
.with_description("regtest mint".to_string())
.with_quote_ttl(10000, 10000)
Expand Down
17 changes: 12 additions & 5 deletions crates/cdk-integration-tests/tests/mint.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,8 @@ use bip39::Mnemonic;
use cdk::amount::{Amount, SplitTarget};
use cdk::cdk_database::mint_memory::MintMemoryDatabase;
use cdk::dhke::construct_proofs;
use cdk::mint::MintQuote;
use cdk::mint::signatory::SignatoryManager;
use cdk::mint::{MemorySignatory, MintQuote};
use cdk::nuts::nut00::ProofsMethods;
use cdk::nuts::{
CurrencyUnit, Id, MintBolt11Request, MintInfo, NotificationPayload, Nuts, PreMintSecrets,
Expand Down Expand Up @@ -45,15 +46,21 @@ async fn new_mint(fee: u64) -> Mint {

let quote_ttl = QuoteTTL::new(10000, 10000);

let localstore = Arc::new(MintMemoryDatabase::default());
let seed = mnemonic.to_seed_normalized("");
let signatory_manager = Arc::new(SignatoryManager::new(Arc::new(
MemorySignatory::new(localstore.clone(), &seed, supported_units, HashMap::new())
.await
.expect("valid signatory"),
)));

Mint::new(
MINT_URL,
&mnemonic.to_seed_normalized(""),
mint_info,
quote_ttl,
Arc::new(MintMemoryDatabase::default()),
HashMap::new(),
supported_units,
localstore,
HashMap::new(),
signatory_manager,
)
.await
.unwrap()
Expand Down
3 changes: 3 additions & 0 deletions crates/cdk-mintd/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,9 @@ cdk-lnbits = { path = "../cdk-lnbits", version = "0.6.0", default-features = fal
cdk-phoenixd = { path = "../cdk-phoenixd", version = "0.6.0", default-features = false }
cdk-lnd = { path = "../cdk-lnd", version = "0.6.0", default-features = false }
cdk-fake-wallet = { path = "../cdk-fake-wallet", version = "0.6.0", default-features = false }
cdk-signatory = { path = "../cdk-signatory", default-features = false, features = [
"grpc",
] }
cdk-strike = { path = "../cdk-strike", version = "0.6.0" }
cdk-axum = { path = "../cdk-axum", version = "0.6.0", default-features = false }
config = { version = "0.13.3", features = ["toml"] }
Expand Down
61 changes: 61 additions & 0 deletions crates/cdk-mintd/src/bin/signatory.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
use std::collections::HashMap;
use std::env;
use std::str::FromStr;

use bip39::Mnemonic;
use cdk::nuts::CurrencyUnit;
use cdk_mintd::cli::CLIArgs;
use cdk_mintd::env_vars::ENV_WORK_DIR;
use cdk_mintd::{config, work_dir};
use cdk_signatory::proto::server::grpc_server;
use cdk_signatory::MemorySignatory;
use clap::Parser;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let args = CLIArgs::parse();
let work_dir = if let Some(work_dir) = args.work_dir {
tracing::info!("Using work dir from cmd arg");
work_dir
} else if let Ok(env_work_dir) = env::var(ENV_WORK_DIR) {
tracing::info!("Using work dir from env var");
env_work_dir.into()
} else {
work_dir()?
};

let config_file_arg = match args.config {
Some(c) => c,
None => work_dir.join("config.toml"),
};

let settings = if config_file_arg.exists() {
config::Settings::new(Some(config_file_arg))
} else {
tracing::info!("Config file does not exist. Attempting to read env vars");
config::Settings::default()
};

// This check for any settings defined in ENV VARs
// ENV VARS will take **priority** over those in the config
let mut settings = settings.from_env()?;
let mnemonic = Mnemonic::from_str(&settings.info.mnemonic)?;

let signatory = MemorySignatory::new(
settings.database.engine.clone().mint(&work_dir).await?,
&mnemonic.to_seed_normalized(""),
settings
.supported_units
.take()
.unwrap_or(vec![CurrencyUnit::default()])
.into_iter()
.map(|u| (u, (0, 32)))
.collect::<HashMap<_, _>>(),
HashMap::new(),
)
.await?;

grpc_server(signatory, "[::1]:50051".parse().unwrap()).await?;

Ok(())
}
31 changes: 30 additions & 1 deletion crates/cdk-mintd/src/config.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,11 @@
use std::path::PathBuf;
use std::sync::Arc;

use cdk::nuts::{CurrencyUnit, PublicKey};
use cdk::Amount;
use cdk::{cdk_database, Amount};
use cdk_axum::cache;
use cdk_redb::MintRedbDatabase;
use cdk_sqlite::MintSqliteDatabase;
use config::{Config, ConfigError, File};
use serde::{Deserialize, Serialize};

Expand Down Expand Up @@ -169,6 +172,30 @@ impl std::str::FromStr for DatabaseEngine {
}
}

impl DatabaseEngine {
/// Convert the database instance into a mint database
pub async fn mint<P: Into<PathBuf>>(
self,
work_dir: P,
) -> Result<
Arc<dyn cdk_database::MintDatabase<Err = cdk_database::Error> + Sync + Send + 'static>,
cdk_database::Error,
> {
match self {
DatabaseEngine::Sqlite => {
let sql_db_path = work_dir.into().join("cdk-mintd.sqlite");
let db = MintSqliteDatabase::new(&sql_db_path).await?;
db.migrate().await;
Ok(Arc::new(db))
}
DatabaseEngine::Redb => {
let redb_path = work_dir.into().join("cdk-mintd.redb");
Ok(Arc::new(MintRedbDatabase::new(&redb_path)?))
}
}
}
}

#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct Database {
pub engine: DatabaseEngine,
Expand All @@ -187,6 +214,8 @@ pub struct Settings {
pub lnd: Option<Lnd>,
pub fake_wallet: Option<FakeWallet>,
pub database: Database,
pub supported_units: Option<Vec<CurrencyUnit>>,
pub remote_signatory: Option<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize, Default)]
Expand Down
10 changes: 5 additions & 5 deletions crates/cdk-mintd/src/env_vars.rs
Original file line number Diff line number Diff line change
Expand Up @@ -72,15 +72,15 @@ pub const ENV_FAKE_WALLET_MIN_DELAY: &str = "CDK_MINTD_FAKE_WALLET_MIN_DELAY";
pub const ENV_FAKE_WALLET_MAX_DELAY: &str = "CDK_MINTD_FAKE_WALLET_MAX_DELAY";

impl Settings {
pub fn from_env(&mut self) -> Result<Self> {
pub fn from_env(mut self) -> Result<Self> {
if let Ok(database) = env::var(DATABASE_ENV_VAR) {
let engine = DatabaseEngine::from_str(&database).map_err(|err| anyhow!(err))?;
self.database = Database { engine };
}

self.info = self.info.clone().from_env();
self.mint_info = self.mint_info.clone().from_env();
self.ln = self.ln.clone().from_env();
self.info = self.info.from_env();
self.mint_info = self.mint_info.from_env();
self.ln = self.ln.from_env();

match self.ln.ln_backend {
LnBackend::Cln => {
Expand All @@ -104,7 +104,7 @@ impl Settings {
LnBackend::None => bail!("Ln backend must be set"),
}

Ok(self.clone())
Ok(self)
}
}

Expand Down
12 changes: 12 additions & 0 deletions crates/cdk-mintd/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@

use std::path::PathBuf;

use anyhow::anyhow;

pub mod cli;
pub mod config;
pub mod env_vars;
Expand All @@ -22,6 +24,16 @@ fn expand_path(path: &str) -> Option<PathBuf> {
}
}

/// Work dir
pub fn work_dir() -> anyhow::Result<PathBuf> {
let home_dir = home::home_dir().ok_or(anyhow!("Unknown home dir"))?;
let dir = home_dir.join(".cdk-mintd");

std::fs::create_dir_all(&dir)?;

Ok(dir)
}

#[cfg(test)]
mod test {
use std::env::current_dir;
Expand Down
Loading
Loading