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 3a267d5 commit e06ec34
Show file tree
Hide file tree
Showing 29 changed files with 1,517 additions and 566 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
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>;
}
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
28 changes: 14 additions & 14 deletions crates/cdk-integration-tests/tests/fake_wallet.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ use cdk_integration_tests::{attempt_to_swap_pending, wait_for_mint_to_be_paid};
const MINT_URL: &str = "http://127.0.0.1:8086";

// If both pay and check return pending input proofs should remain pending
#[tokio::test(flavor = "multi_thread", worker_threads = 1)]
#[tokio::test(flavor = "multi_thread")]
async fn test_fake_tokens_pending() -> Result<()> {
let wallet = Wallet::new(
MINT_URL,
Expand Down Expand Up @@ -57,7 +57,7 @@ async fn test_fake_tokens_pending() -> Result<()> {

// If the pay error fails and the check returns unknown or failed
// The inputs proofs should be unset as spending
#[tokio::test(flavor = "multi_thread", worker_threads = 1)]
#[tokio::test(flavor = "multi_thread")]
async fn test_fake_melt_payment_fail() -> Result<()> {
let wallet = Wallet::new(
MINT_URL,
Expand Down Expand Up @@ -120,7 +120,7 @@ async fn test_fake_melt_payment_fail() -> Result<()> {

// When both the pay_invoice and check_invoice both fail
// the proofs should remain as pending
#[tokio::test(flavor = "multi_thread", worker_threads = 1)]
#[tokio::test(flavor = "multi_thread")]
async fn test_fake_melt_payment_fail_and_check() -> Result<()> {
let wallet = Wallet::new(
MINT_URL,
Expand Down Expand Up @@ -165,7 +165,7 @@ async fn test_fake_melt_payment_fail_and_check() -> Result<()> {

// In the case that the ln backend returns a failed status but does not error
// The mint should do a second check, then remove proofs from pending
#[tokio::test(flavor = "multi_thread", worker_threads = 1)]
#[tokio::test(flavor = "multi_thread")]
async fn test_fake_melt_payment_return_fail_status() -> Result<()> {
let wallet = Wallet::new(
MINT_URL,
Expand Down Expand Up @@ -225,7 +225,7 @@ async fn test_fake_melt_payment_return_fail_status() -> Result<()> {

// In the case that the ln backend returns a failed status but does not error
// The mint should do a second check, then remove proofs from pending
#[tokio::test(flavor = "multi_thread", worker_threads = 1)]
#[tokio::test(flavor = "multi_thread")]
async fn test_fake_melt_payment_error_unknown() -> Result<()> {
let wallet = Wallet::new(
MINT_URL,
Expand Down Expand Up @@ -286,7 +286,7 @@ async fn test_fake_melt_payment_error_unknown() -> Result<()> {
// In the case that the ln backend returns an err
// The mint should do a second check, that returns paid
// Proofs should remain pending
#[tokio::test(flavor = "multi_thread", worker_threads = 1)]
#[tokio::test(flavor = "multi_thread")]
async fn test_fake_melt_payment_err_paid() -> Result<()> {
let wallet = Wallet::new(
MINT_URL,
Expand Down Expand Up @@ -324,7 +324,7 @@ async fn test_fake_melt_payment_err_paid() -> Result<()> {
Ok(())
}

#[tokio::test(flavor = "multi_thread", worker_threads = 1)]
#[tokio::test(flavor = "multi_thread")]
async fn test_fake_melt_change_in_quote() -> Result<()> {
let wallet = Wallet::new(
MINT_URL,
Expand Down Expand Up @@ -377,7 +377,7 @@ async fn test_fake_melt_change_in_quote() -> Result<()> {
Ok(())
}

#[tokio::test(flavor = "multi_thread", worker_threads = 1)]
#[tokio::test(flavor = "multi_thread")]
async fn test_fake_mint_with_witness() -> Result<()> {
let wallet = Wallet::new(
MINT_URL,
Expand All @@ -401,7 +401,7 @@ async fn test_fake_mint_with_witness() -> Result<()> {
Ok(())
}

#[tokio::test(flavor = "multi_thread", worker_threads = 1)]
#[tokio::test(flavor = "multi_thread")]
async fn test_fake_mint_without_witness() -> Result<()> {
let wallet = Wallet::new(
MINT_URL,
Expand Down Expand Up @@ -437,7 +437,7 @@ async fn test_fake_mint_without_witness() -> Result<()> {
}
}

#[tokio::test(flavor = "multi_thread", worker_threads = 1)]
#[tokio::test(flavor = "multi_thread")]
async fn test_fake_mint_with_wrong_witness() -> Result<()> {
let wallet = Wallet::new(
MINT_URL,
Expand Down Expand Up @@ -477,7 +477,7 @@ async fn test_fake_mint_with_wrong_witness() -> Result<()> {
}
}

#[tokio::test(flavor = "multi_thread", worker_threads = 1)]
#[tokio::test(flavor = "multi_thread")]
async fn test_fake_mint_inflated() -> Result<()> {
let wallet = Wallet::new(
MINT_URL,
Expand Down Expand Up @@ -529,7 +529,7 @@ async fn test_fake_mint_inflated() -> Result<()> {
Ok(())
}

#[tokio::test(flavor = "multi_thread", worker_threads = 1)]
#[tokio::test(flavor = "multi_thread")]
async fn test_fake_mint_multiple_units() -> Result<()> {
let wallet = Wallet::new(
MINT_URL,
Expand Down Expand Up @@ -599,7 +599,7 @@ async fn test_fake_mint_multiple_units() -> Result<()> {
Ok(())
}

#[tokio::test(flavor = "multi_thread", worker_threads = 1)]
#[tokio::test(flavor = "multi_thread")]
async fn test_fake_mint_multiple_unit_swap() -> Result<()> {
let wallet = Wallet::new(
MINT_URL,
Expand Down Expand Up @@ -703,7 +703,7 @@ async fn test_fake_mint_multiple_unit_swap() -> Result<()> {
Ok(())
}

#[tokio::test(flavor = "multi_thread", worker_threads = 1)]
#[tokio::test(flavor = "multi_thread")]
async fn test_fake_mint_multiple_unit_melt() -> Result<()> {
let wallet = Wallet::new(
MINT_URL,
Expand Down
Loading

0 comments on commit e06ec34

Please sign in to comment.