Skip to content

Commit

Permalink
Introduce a SignatoryManager service.
Browse files Browse the repository at this point in the history
The SignatoryManager manager provides an API to interact with keysets, private
keys, and all key-related operations, offering segregation between the mint and
the most sensible part of the mind: the private keys.

Although the default signatory runs in memory, it is completely isolated from
the rest of the system and can only be communicated through the interface
offered by the signatory manager. Only messages can be sent from the mintd to
the Signatory trait through the Signatory Manager.

This pull request sets the foundation for eventually being able to run the
Signatory and all the key-related operations in a separate service, possibly in
a foreign service, to offload risks, as described in #476.

The Signatory manager is concurrent and deferred any mechanism needed to handle
concurrency to the Signatory trait.
  • Loading branch information
crodas committed Jan 31, 2025
1 parent 017f88e commit 63a18a3
Show file tree
Hide file tree
Showing 27 changed files with 1,409 additions and 531 deletions.
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 @@ -59,6 +59,14 @@ pub enum Error {
#[error("Multi-Part payment is not supported for unit `{0}` and method `{1}`")]
MppUnitMethodNotSupported(CurrencyUnit, PaymentMethod),

/// 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,3 +1,4 @@
use std::collections::HashMap;
use std::env;
use std::path::{Path, PathBuf};
use std::sync::Arc;
Expand All @@ -6,7 +7,7 @@ use anyhow::Result;
use bip39::Mnemonic;
use cdk::cdk_database::{self, MintDatabase};
use cdk::cdk_lightning::{self, MintLightning};
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 cdk_lnd::Lnd as CdkLnd;
Expand Down Expand Up @@ -156,7 +157,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 @@ -167,8 +170,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_description("regtest mint".to_string())
.with_quote_ttl(10000, 10000)
.with_seed(mnemonic.to_seed_normalized("").to_vec());
Expand Down
23 changes: 13 additions & 10 deletions crates/cdk-integration-tests/tests/mint.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,8 @@ 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::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 @@ -49,15 +50,17 @@ async fn new_mint(fee: u64) -> Mint {
.expect("Could not set mint info");
let mnemonic = Mnemonic::generate(12).unwrap();

Mint::new(
&mnemonic.to_seed_normalized(""),
Arc::new(localstore),
HashMap::new(),
supported_units,
HashMap::new(),
)
.await
.unwrap()
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(localstore, HashMap::new(), signatory_manager)
.await
.unwrap()
}

async fn initialize() -> &'static Mint {
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

0 comments on commit 63a18a3

Please sign in to comment.