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 3 commits 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 @@ -202,6 +202,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 @@ -91,6 +91,14 @@ impl<'de> Deserialize<'de> for Keys {
}
}

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

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

impl From<MintKeys> for Keys {
fn from(keys: MintKeys) -> Self {
Self(
Expand Down
6 changes: 6 additions & 0 deletions crates/cashu/src/secret.rs
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,12 @@ impl Secret {
Self(secret.into())
}

/// Creates a new [`Secret`] from bytes
pub fn from_bytes(bytes: Vec<u8>) -> Self {
let secret = hex::encode(bytes);
Self(secret)
}

/// Create secret value
/// Generate a new random secret as the recommended 32 byte hex
pub fn generate() -> Self {
Expand Down
4 changes: 2 additions & 2 deletions crates/cdk-axum/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -28,8 +28,8 @@ futures = { version = "0.3.28", default-features = false }
moka = { version = "0.11.1", features = ["future"] }
serde_json = "1"
paste = "1.0.15"
serde = { version = "1", features = ["derive"] }
uuid = { version = "1", features = ["v4", "serde"] }
serde = { version = "1.0.210", features = ["derive"] }
uuid = { version = "=1.12.1", features = ["v4", "serde"] }
Comment on lines +31 to +32
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

can we week serde at 1? I know we changed uuid bc of the wasm build issue

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.7.1", default-features = false, features = ["mint"] }
cdk = { path = "../cdk", version = "0.7.1", 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 @@ -32,7 +32,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
40 changes: 23 additions & 17 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 @@ -9,7 +10,8 @@ use bip39::Mnemonic;
use cdk::amount::{Amount, SplitTarget};
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 Down Expand Up @@ -48,21 +50,24 @@ async fn new_mint(fee: u64) -> Mint {
.expect("Could not set mint info");
let mnemonic = Mnemonic::generate(12).unwrap();

let localstore = Arc::new(memory::empty().await.expect("valid db instance"));
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() -> Mint {
new_mint(0).await
}

async fn mint_proofs(
mint: &Mint,
amount: Amount,
Expand Down Expand Up @@ -107,7 +112,7 @@ async fn mint_proofs(

#[tokio::test(flavor = "multi_thread", worker_threads = 1)]
async fn test_mint_double_spend() -> Result<()> {
let mint = initialize().await;
let mint = new_mint(0).await;

let keys = mint.pubkeys().await?.keysets.first().unwrap().clone().keys;
let keyset_id = Id::from(&keys);
Expand All @@ -118,9 +123,7 @@ async fn test_mint_double_spend() -> Result<()> {

let swap_request = SwapRequest::new(proofs.clone(), preswap.blinded_messages());

let swap = mint.process_swap_request(swap_request).await;

assert!(swap.is_ok());
mint.process_swap_request(swap_request).await?;

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

Expand All @@ -141,7 +144,7 @@ async fn test_mint_double_spend() -> Result<()> {
/// This will work if the mint does not check for outputs amounts overflowing
#[tokio::test(flavor = "multi_thread", worker_threads = 1)]
async fn test_attempt_to_swap_by_overflowing() -> Result<()> {
let mint = initialize().await;
let mint = new_mint(0).await;

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

#[tokio::test(flavor = "multi_thread", worker_threads = 1)]
pub async fn test_p2pk_swap() -> Result<()> {
let mint = initialize().await;
let mint = new_mint(0).await;

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

#[tokio::test(flavor = "multi_thread", worker_threads = 1)]
async fn test_swap_unbalanced() -> Result<()> {
let mint = initialize().await;
let mint = new_mint(0).await;

let keys = mint.pubkeys().await?.keysets.first().unwrap().clone().keys;
let keyset_id = Id::from(&keys);
Expand Down Expand Up @@ -467,7 +470,7 @@ async fn test_correct_keyset() -> Result<()> {
.with_description("regtest mint".to_string())
.with_seed(mnemonic.to_seed_normalized("").to_vec());

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

localstore
.set_mint_info(mint_builder.mint_info.clone())
Expand All @@ -492,7 +495,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
19 changes: 11 additions & 8 deletions crates/cdk-mintd/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -26,14 +26,17 @@ cdk-redb = { path = "../cdk-redb", version = "0.7.1", default-features = false,
cdk-sqlite = { path = "../cdk-sqlite", version = "0.7.1", default-features = false, features = [
"mint",
] }
cdk-cln = { path = "../cdk-cln", version = "0.7.1", default-features = false }
cdk-lnbits = { path = "../cdk-lnbits", version = "0.7.1", default-features = false }
cdk-phoenixd = { path = "../cdk-phoenixd", version = "0.7.1", default-features = false }
cdk-lnd = { path = "../cdk-lnd", version = "0.7.1", default-features = false }
cdk-fake-wallet = { path = "../cdk-fake-wallet", version = "0.7.1", default-features = false }
cdk-strike = { path = "../cdk-strike", version = "0.7.1" }
cdk-axum = { path = "../cdk-axum", version = "0.7.1", default-features = false }
cdk-mint-rpc = { path = "../cdk-mint-rpc", version = "0.7.1", default-features = false, optional = true }
cdk-cln = { path = "../cdk-cln", version = "0.7.0", default-features = false }
cdk-lnbits = { path = "../cdk-lnbits", version = "0.7.0", default-features = false }
cdk-phoenixd = { path = "../cdk-phoenixd", version = "0.7.0", default-features = false }
cdk-lnd = { path = "../cdk-lnd", version = "0.7.0", default-features = false }
cdk-fake-wallet = { path = "../cdk-fake-wallet", version = "0.7.0", default-features = false }
cdk-strike = { path = "../cdk-strike", version = "0.7.0" }
cdk-axum = { path = "../cdk-axum", version = "0.7.0", default-features = false }
cdk-mint-rpc = { path = "../cdk-mint-rpc", version = "0.7.0", default-features = false, optional = true }
cdk-signatory = { path = "../cdk-signatory", default-features = false, features = [
"grpc",
] }
Comment on lines +29 to +39
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

these should all be version 0.7.1

config = { version = "0.13.3", features = ["toml"] }
clap = { version = "~4.0.32", features = ["derive"] }
bitcoin = { version = "0.32.2", features = [
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(())
}
Loading
Loading