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 Feb 5, 2025
1 parent dcb9ab3 commit 3e16038
Show file tree
Hide file tree
Showing 34 changed files with 1,531 additions and 562 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
2 changes: 1 addition & 1 deletion crates/cdk-axum/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ moka = { version = "0.11.1", features = ["future"] }
serde_json = "1"
paste = "1.0.15"
serde = { version = "1.0.210", features = ["derive"] }
uuid = { version = "1", features = ["v4", "serde"] }
uuid = { version = "=1.12.1", features = ["v4", "serde"] }
sha2 = "0.10.8"
redis = { version = "0.23.3", features = [
"tokio-rustls-comp",
Expand Down
13 changes: 9 additions & 4 deletions crates/cdk-cln/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -6,17 +6,22 @@ authors = ["CDK Developers"]
license = "MIT"
homepage = "https://github.com/cashubtc/cdk"
repository = "https://github.com/cashubtc/cdk.git"
rust-version = "1.63.0" # MSRV
rust-version = "1.63.0" # MSRV
description = "CDK ln backend for cln"

[dependencies]
async-trait = "0.1"
bitcoin = { version = "0.32.2", default-features = false }
cdk = { path = "../cdk", version = "0.6.0", default-features = false, features = ["mint"] }
cdk = { path = "../cdk", version = "0.6.0", default-features = false, features = [
"mint",
] }
cln-rpc = "0.3.0"
futures = { version = "0.3.28", default-features = false }
tokio = { version = "1", default-features = false }
tokio-util = { version = "0.7.11", default-features = false }
tracing = { version = "0.1", default-features = false, features = ["attributes", "log"] }
tracing = { version = "0.1", default-features = false, features = [
"attributes",
"log",
] }
thiserror = "1"
uuid = { version = "1", features = ["v4"] }
uuid = { version = "=1.12.1", features = ["v4"] }
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
74 changes: 74 additions & 0 deletions crates/cdk-common/src/signatory.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
//! 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::mint::MintKeySetInfo;
use cashu::{
BlindSignature, BlindedMessage, CurrencyUnit, Id, KeySet, KeysResponse, KeysetResponse, Proof,
};

use super::error::Error;

/// Type alias to make the keyset info API more useful, queryable by unit and Id
pub enum KeysetIdentifier {
/// Mint Keyset by unit
Unit(CurrencyUnit),
/// Mint Keyset by Id
Id(Id),
}

impl From<Id> for KeysetIdentifier {
fn from(id: Id) -> Self {
Self::Id(id)
}
}

impl From<CurrencyUnit> for KeysetIdentifier {
fn from(unit: CurrencyUnit) -> Self {
Self::Unit(unit)
}
}

#[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<MintKeySetInfo, Error>;

/// Get Mint Keyset Info by Unit or Id
async fn get_keyset_info(&self, keyset_id: KeysetIdentifier) -> Result<MintKeySetInfo, Error>;
}
2 changes: 1 addition & 1 deletion crates/cdk-integration-tests/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ futures = { version = "0.3.28", default-features = false, features = [
"executor",
] }
once_cell = "1.19.0"
uuid = { version = "1", features = ["v4"] }
uuid = { version = "=1.12.1", features = ["v4"] }
serde = "1"
serde_json = "1"
# ln-regtest-rs = { path = "../../../../ln-regtest-rs" }
Expand Down
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
41 changes: 28 additions & 13 deletions crates/cdk-integration-tests/tests/mint.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
//! Mint tests
use std::collections::{HashMap, HashSet};
use std::ops::Deref;
use std::sync::Arc;
use std::time::Duration;

Expand All @@ -10,7 +11,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::{FeeReserve, MintBuilder, MintMeltLimits, MintQuote};
use cdk::mint::signatory::SignatoryManager;
use cdk::mint::{FeeReserve, MemorySignatory, MintBuilder, MintMeltLimits, MintQuote};
use cdk::nuts::nut00::ProofsMethods;
use cdk::nuts::{
CurrencyUnit, Id, MintBolt11Request, MintInfo, NotificationPayload, Nuts, PaymentMethod,
Expand All @@ -25,7 +27,7 @@ use tokio::time::sleep;

pub const MINT_URL: &str = "http://127.0.0.1:8088";

static INSTANCE: OnceCell<Mint> = OnceCell::const_new();
static INSTANCE: OnceCell<Arc<Mint>> = OnceCell::const_new();

async fn new_mint(fee: u64) -> Mint {
let mut supported_units = HashMap::new();
Expand All @@ -50,19 +52,29 @@ async fn new_mint(fee: u64) -> Mint {
.expect("Could not set mint info");
let mnemonic = Mnemonic::generate(12).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(
&mnemonic.to_seed_normalized(""),
Arc::new(localstore),
localstore,
HashMap::new(),
supported_units,
signatory_manager,
HashMap::new(),
)
.await
.unwrap()
}

async fn initialize() -> &'static Mint {
INSTANCE.get_or_init(|| new_mint(0)).await
async fn initialize() -> Arc<Mint> {
INSTANCE
.get_or_init(|| async { Arc::new(new_mint(0).await) })
.await
.clone()
}

async fn mint_proofs(
Expand Down Expand Up @@ -114,7 +126,7 @@ async fn test_mint_double_spend() -> Result<()> {
let keys = mint.pubkeys().await?.keysets.first().unwrap().clone().keys;
let keyset_id = Id::from(&keys);

let proofs = mint_proofs(mint, 100.into(), &SplitTarget::default(), keys).await?;
let proofs = mint_proofs(&mint, 100.into(), &SplitTarget::default(), keys).await?;

let preswap = PreMintSecrets::random(keyset_id, 100.into(), &SplitTarget::default())?;

Expand Down Expand Up @@ -148,7 +160,7 @@ async fn test_attempt_to_swap_by_overflowing() -> Result<()> {
let keys = mint.pubkeys().await?.keysets.first().unwrap().clone().keys;
let keyset_id = Id::from(&keys);

let proofs = mint_proofs(mint, 100.into(), &SplitTarget::default(), keys).await?;
let proofs = mint_proofs(&mint, 100.into(), &SplitTarget::default(), keys).await?;

let amount = 2_u64.pow(63);

Expand Down Expand Up @@ -185,7 +197,7 @@ pub async fn test_p2pk_swap() -> Result<()> {
let keys = mint.pubkeys().await?.keysets.first().unwrap().clone().keys;
let keyset_id = Id::from(&keys);

let proofs = mint_proofs(mint, 100.into(), &SplitTarget::default(), keys).await?;
let proofs = mint_proofs(&mint, 100.into(), &SplitTarget::default(), keys).await?;

let secret = SecretKey::generate();

Expand Down Expand Up @@ -303,7 +315,7 @@ async fn test_swap_unbalanced() -> Result<()> {
let keys = mint.pubkeys().await?.keysets.first().unwrap().clone().keys;
let keyset_id = Id::from(&keys);

let proofs = mint_proofs(mint, 100.into(), &SplitTarget::default(), keys).await?;
let proofs = mint_proofs(&mint, 100.into(), &SplitTarget::default(), keys).await?;

let preswap = PreMintSecrets::random(keyset_id, 95.into(), &SplitTarget::default())?;

Expand Down Expand Up @@ -468,7 +480,7 @@ async fn test_correct_keyset() -> Result<()> {
.with_quote_ttl(10000, 1000)
.with_seed(mnemonic.to_seed_normalized("").to_vec());

let mint = mint_builder.build().await?;
let mint = mint_builder.clone().build().await?;

mint.rotate_next_keyset(CurrencyUnit::Sat, 32, 0).await?;
mint.rotate_next_keyset(CurrencyUnit::Sat, 32, 0).await?;
Expand All @@ -487,7 +499,10 @@ async fn test_correct_keyset() -> Result<()> {

assert!(keyset_info.derivation_path_index == Some(2));

let mint = mint_builder.build().await?;
let mint = mint_builder
.with_signatory(mint.signatory.deref().deref().to_owned())
.build()
.await?;

let active = mint.localstore.get_active_keysets().await?;

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
Loading

0 comments on commit 3e16038

Please sign in to comment.