Cesar Rodas 1 月之前
父节点
当前提交
edf55ade3b

+ 77 - 88
crates/cdk-signatory/proto/signatory.proto

@@ -2,167 +2,156 @@ syntax = "proto3";
 
 
 package signatory;
 package signatory;
 
 
-/// TODO: research about the stream, to notify when RotateKeyset is triggered.
 service Signatory {
 service Signatory {
-  rpc BlindSign (BlindedMessages) returns (BlindSignResponse);
-
-  rpc VerifyProofs (Proofs) returns (BooleanResponse);
-
-  rpc Keysets (EmptyRequest) returns (KeysResponse);
-
-  rpc RotateKeyset (RotationRequest) returns (KeyRotationResponse);
+  rpc BlindSign(BlindedMessages) returns (BlindSignResponse);
+  rpc VerifyProofs(Proofs) returns (BooleanResponse);
+  // returns all the keysets for the mint
+  rpc Keysets(EmptyRequest) returns (KeysResponse);
+  // rotates the keysets
+  rpc RotateKeyset(RotationRequest) returns (KeyRotationResponse);
 }
 }
 
 
 message BlindSignResponse {
 message BlindSignResponse {
-    oneof result {
-        BlindSignatures sigs  = 1;
-        Error error = 2;
-    }
+  Error error = 1;
+  BlindSignatures sigs = 2;
 }
 }
 
 
 message BlindedMessages {
 message BlindedMessages {
-    repeated BlindedMessage blinded_messages = 1;
+  repeated BlindedMessage blinded_messages = 1;
 }
 }
 
 
 // Represents a blinded message
 // Represents a blinded message
 message BlindedMessage {
 message BlindedMessage {
-    uint64 amount = 1;
-    string keyset_id = 2;
-    bytes blinded_secret = 3;
+  uint64 amount = 1;
+  string keyset_id = 2;
+  bytes blinded_secret = 3;
 }
 }
 
 
 message BooleanResponse {
 message BooleanResponse {
-    oneof result {
-        bool success  = 1;
-        Error error = 2;
-    }
+  Error error = 1;
+  bool success = 2;
 }
 }
 
 
 message KeyRotationResponse {
 message KeyRotationResponse {
-    oneof result {
-        KeySet keyset  = 1;
-        Error error = 2;
-    }
+  Error error = 1;
+  KeySet keyset = 2;
 }
 }
 
 
 message KeysResponse {
 message KeysResponse {
-    oneof result {
-        SignatoryKeysets keysets = 1;
-        Error error = 2;
-    }
+  Error error = 1;
+  SignatoryKeysets keysets = 2;
 }
 }
 
 
 message SignatoryKeysets {
 message SignatoryKeysets {
-    bytes pubkey = 1;
-    repeated KeySet keysets = 2;
+  bytes pubkey = 1;
+  repeated KeySet keysets = 2;
 }
 }
 
 
 message KeySet {
 message KeySet {
-    string id = 1;
-    CurrencyUnit unit = 2;
-    bool active = 3;
-    uint64 input_fee_ppk = 4;
-    Keys keys = 5;
+  string id = 1;
+  CurrencyUnit unit = 2;
+  bool active = 3;
+  uint64 input_fee_ppk = 4;
+  Keys keys = 5;
 }
 }
 
 
 message Keys {
 message Keys {
-    map<uint64, bytes> keys = 1;
+  map<uint64, bytes> keys = 1;
 }
 }
 
 
 message RotationRequest {
 message RotationRequest {
-    CurrencyUnit unit  = 1;
-    uint64 input_fee_ppk  = 2;
-    uint64 max_order = 3;
+  CurrencyUnit unit = 1;
+  uint64 input_fee_ppk = 2;
+  repeated uint64 amounts = 3;
 }
 }
 
 
 enum CurrencyUnitType {
 enum CurrencyUnitType {
-    SAT = 0;
-    MSAT = 1;
-    USD = 2;
-    EUR = 3;
-    AUTH = 4;
+  SAT = 0;
+  MSAT = 1;
+  USD = 2;
+  EUR = 3;
+  AUTH = 4;
 }
 }
 
 
 message CurrencyUnit {
 message CurrencyUnit {
-    oneof currency_unit {
-        CurrencyUnitType unit = 1;
-        string custom_unit = 2;
-    }
+  oneof currency_unit {
+    CurrencyUnitType unit = 1;
+    string custom_unit = 2;
+  }
 }
 }
 
 
 message Proofs {
 message Proofs {
-    repeated Proof proof = 1;
+  repeated Proof proof = 1;
 }
 }
 
 
 message Proof {
 message Proof {
-    uint64 amount = 1;
-    string keyset_id = 2;
-    bytes secret = 3;
-    bytes C = 4;
+  uint64 amount = 1;
+  string keyset_id = 2;
+  bytes secret = 3;
+  bytes C = 4;
+  optional Witness witness = 5;
 }
 }
 
 
 message ProofDLEQ {
 message ProofDLEQ {
-    bytes e = 1;
-    bytes s = 2;
-    bytes r = 3;
+  bytes e = 1;
+  bytes s = 2;
+  bytes r = 3;
 }
 }
 
 
 message SigningResponse {
 message SigningResponse {
-    oneof result {
-        BlindSignatures blind_signatures = 1;
-        Error error = 2;
-    }
+  Error error = 1;
+  BlindSignatures blind_signatures = 2;
 }
 }
 message BlindSignatures {
 message BlindSignatures {
-    repeated BlindSignature blind_signatures = 1;
+  repeated BlindSignature blind_signatures = 1;
 }
 }
 
 
 message BlindSignature {
 message BlindSignature {
-    uint64 amount = 1;
-    string keyset_id = 2;
-    bytes blinded_secret = 3;
-    optional BlindSignatureDLEQ dleq = 4;
+  uint64 amount = 1;
+  string keyset_id = 2;
+  bytes blinded_secret = 3;
+  optional BlindSignatureDLEQ dleq = 4;
 }
 }
 
 
 message BlindSignatureDLEQ {
 message BlindSignatureDLEQ {
-    bytes e = 1;
-    bytes s = 2;
+  bytes e = 1;
+  bytes s = 2;
 }
 }
 
 
 // Witness type
 // Witness type
 message Witness {
 message Witness {
-    oneof witness_type {
-        P2PKWitness p2pk_witness = 1;
-        HTLCWitness htlc_witness = 2;
-    }
+  oneof witness_type {
+    P2PKWitness p2pk_witness = 1;
+    HTLCWitness htlc_witness = 2;
+  }
 }
 }
 
 
 // P2PKWitness type
 // P2PKWitness type
 message P2PKWitness {
 message P2PKWitness {
-    // List of signatures
-    repeated string signatures = 1;
+  // List of signatures
+  repeated string signatures = 1;
 }
 }
 
 
 // HTLCWitness type
 // HTLCWitness type
 message HTLCWitness {
 message HTLCWitness {
-    // Preimage
-    string preimage = 1;
-    // List of signatures
-    repeated string signatures = 2;
+  // Preimage
+  string preimage = 1;
+  // List of signatures
+  repeated string signatures = 2;
 }
 }
 
 
 enum ErrorCode {
 enum ErrorCode {
-    UNKNOWN = 0;
-    AMOUNT_OUTSIDE_LIMIT = 1;
-    DUPLICATE_INPUTS_PROVIDED = 2;
-    DUPLICATE_OUTPUTS_PROVIDED = 3;
-    KEYSET_NOT_KNOWN = 4;
-    KEYSET_INACTIVE = 5;
-    MINTING_DISABLED = 6;
-    COULD_NOT_ROTATE_KEYSET = 7;
-    INVALID_PROOF = 8;
-    INVALID_BLIND_MESSAGE = 9;
-    UNIT_NOT_SUPPORTED = 10;
+  UNKNOWN = 0;
+  AMOUNT_OUTSIDE_LIMIT = 1;
+  DUPLICATE_INPUTS_PROVIDED = 2;
+  DUPLICATE_OUTPUTS_PROVIDED = 3;
+  KEYSET_NOT_KNOWN = 4;
+  KEYSET_INACTIVE = 5;
+  MINTING_DISABLED = 6;
+  COULD_NOT_ROTATE_KEYSET = 7;
+  INVALID_PROOF = 8;
+  INVALID_BLIND_MESSAGE = 9;
+  UNIT_NOT_SUPPORTED = 10;
 }
 }
 
 
 message Error {
 message Error {

+ 1 - 0
crates/cdk-signatory/src/db_signatory.rs

@@ -22,6 +22,7 @@ use crate::signatory::{RotateKeyArguments, Signatory, SignatoryKeySet, Signatory
 pub struct DbSignatory {
 pub struct DbSignatory {
     keysets: RwLock<HashMap<Id, (MintKeySetInfo, MintKeySet)>>,
     keysets: RwLock<HashMap<Id, (MintKeySetInfo, MintKeySet)>>,
     active_keysets: RwLock<HashMap<CurrencyUnit, Id>>,
     active_keysets: RwLock<HashMap<CurrencyUnit, Id>>,
+    /// TODO: Merge localstore with auth_localstore (use the same db). It makes sense in CDK but not here.
     localstore: Arc<dyn database::MintKeysDatabase<Err = database::Error> + Send + Sync>,
     localstore: Arc<dyn database::MintKeysDatabase<Err = database::Error> + Send + Sync>,
     auth_localstore:
     auth_localstore:
         Option<Arc<dyn database::MintAuthDatabase<Err = database::Error> + Send + Sync>>,
         Option<Arc<dyn database::MintAuthDatabase<Err = database::Error> + Send + Sync>>,

+ 18 - 12
crates/cdk-signatory/src/main.rs

@@ -22,6 +22,7 @@ mod cli {
     use tracing_subscriber::EnvFilter;
     use tracing_subscriber::EnvFilter;
 
 
     const DEFAULT_WORK_DIR: &str = ".cdk-signatory";
     const DEFAULT_WORK_DIR: &str = ".cdk-signatory";
+    const ENV_MNEMONIC: &str = "CDK_MINTD_MNEMONIC";
 
 
     /// Simple CLI application to interact with cashu
     /// Simple CLI application to interact with cashu
     #[derive(Parser)]
     #[derive(Parser)]
@@ -48,6 +49,7 @@ mod cli {
         listen_port: u32,
         listen_port: u32,
         #[arg(long, short)]
         #[arg(long, short)]
         certs: Option<String>,
         certs: Option<String>,
+        /// TODO: Add more documentation here
         #[arg(long, short, default_value = "sat,0,32")]
         #[arg(long, short, default_value = "sat,0,32")]
         units: Vec<String>,
         units: Vec<String>,
     }
     }
@@ -136,21 +138,25 @@ mod cli {
 
 
         let seed_path = work_dir.join("seed");
         let seed_path = work_dir.join("seed");
 
 
-        let mnemonic = match fs::metadata(seed_path.clone()) {
-            Ok(_) => {
-                let contents = fs::read_to_string(seed_path.clone())?;
-                Mnemonic::from_str(&contents)?
-            }
-            Err(_e) => {
-                let mut rng = thread_rng();
-                let random_bytes: [u8; 32] = rng.gen();
+        let mnemonic = if let Ok(mnemonic) = env::var(ENV_MNEMONIC) {
+            Mnemonic::from_str(mnemonic)?
+        } else {
+            match fs::metadata(seed_path.clone()) {
+                Ok(_) => {
+                    let contents = fs::read_to_string(seed_path.clone())?;
+                    Mnemonic::from_str(&contents)?
+                }
+                Err(_e) => {
+                    let mut rng = thread_rng();
+                    let random_bytes: [u8; 32] = rng.gen();
 
 
-                let mnemonic = Mnemonic::from_entropy(&random_bytes)?;
-                tracing::info!("Creating new seed");
+                    let mnemonic = Mnemonic::from_entropy(&random_bytes)?;
+                    tracing::info!("Creating new seed");
 
 
-                fs::write(seed_path, mnemonic.to_string())?;
+                    fs::write(seed_path, mnemonic.to_string())?;
 
 
-                mnemonic
+                    mnemonic
+                }
             }
             }
         };
         };
         let seed = mnemonic.to_seed_normalized("");
         let seed = mnemonic.to_seed_normalized("");

+ 32 - 46
crates/cdk-signatory/src/proto/client.rs

@@ -4,7 +4,6 @@ use cdk_common::error::Error;
 use cdk_common::{BlindSignature, BlindedMessage, Proof};
 use cdk_common::{BlindSignature, BlindedMessage, Proof};
 use tonic::transport::{Certificate, Channel, ClientTlsConfig, Identity};
 use tonic::transport::{Certificate, Channel, ClientTlsConfig, Identity};
 
 
-use super::{blind_sign_response, boolean_response, key_rotation_response, keys_response};
 use crate::proto::signatory_client::SignatoryClient;
 use crate::proto::signatory_client::SignatoryClient;
 use crate::signatory::{RotateKeyArguments, Signatory, SignatoryKeySet, SignatoryKeysets};
 use crate::signatory::{RotateKeyArguments, Signatory, SignatoryKeySet, SignatoryKeysets};
 
 
@@ -67,6 +66,27 @@ impl SignatoryRpcClient {
     }
     }
 }
 }
 
 
+macro_rules! handle_error {
+    ($x:expr, $y:ident, scalar) => {{
+        let mut obj = $x.into_inner();
+        if let Some(err) = obj.error.take() {
+            return Err(err.into());
+        }
+
+        obj.$y
+    }};
+    ($x:expr, $y:ident) => {{
+        let mut obj = $x.into_inner();
+        if let Some(err) = obj.error.take() {
+            return Err(err.into());
+        }
+
+        obj.$y
+            .take()
+            .ok_or(Error::Custom("Internal error".to_owned()))?
+    }};
+}
+
 #[async_trait::async_trait]
 #[async_trait::async_trait]
 impl Signatory for SignatoryRpcClient {
 impl Signatory for SignatoryRpcClient {
     fn name(&self) -> String {
     fn name(&self) -> String {
@@ -86,18 +106,11 @@ impl Signatory for SignatoryRpcClient {
             .blind_sign(req)
             .blind_sign(req)
             .await
             .await
             .map(|response| {
             .map(|response| {
-                match response
-                    .into_inner()
-                    .result
-                    .ok_or(Error::Custom("Internal error".to_owned()))?
-                {
-                    blind_sign_response::Result::Sigs(sigs) => sigs
-                        .blind_signatures
-                        .into_iter()
-                        .map(|blinded_signature| blinded_signature.try_into())
-                        .collect(),
-                    blind_sign_response::Result::Error(err) => Err(err.into()),
-                }
+                handle_error!(response, sigs)
+                    .blind_signatures
+                    .into_iter()
+                    .map(|blinded_signature| blinded_signature.try_into())
+                    .collect()
             })
             })
             .map_err(|e| Error::Custom(e.to_string()))?
             .map_err(|e| Error::Custom(e.to_string()))?
     }
     }
@@ -109,19 +122,10 @@ impl Signatory for SignatoryRpcClient {
             .verify_proofs(req)
             .verify_proofs(req)
             .await
             .await
             .map(|response| {
             .map(|response| {
-                match response
-                    .into_inner()
-                    .result
-                    .ok_or(Error::Custom("Internal error".to_owned()))?
-                {
-                    boolean_response::Result::Success(bool) => {
-                        if bool {
-                            Ok(())
-                        } else {
-                            Err(Error::SignatureMissingOrInvalid)
-                        }
-                    }
-                    boolean_response::Result::Error(err) => Err(err.into()),
+                if handle_error!(response, success, scalar) {
+                    Ok(())
+                } else {
+                    Err(Error::SignatureMissingOrInvalid)
                 }
                 }
             })
             })
             .map_err(|e| Error::Custom(e.to_string()))?
             .map_err(|e| Error::Custom(e.to_string()))?
@@ -132,16 +136,7 @@ impl Signatory for SignatoryRpcClient {
             .clone()
             .clone()
             .keysets(super::EmptyRequest {})
             .keysets(super::EmptyRequest {})
             .await
             .await
-            .map(|response| {
-                match response
-                    .into_inner()
-                    .result
-                    .ok_or(Error::Custom("Internal error".to_owned()))?
-                {
-                    keys_response::Result::Keysets(keyset) => keyset.try_into(),
-                    keys_response::Result::Error(err) => Err(err.into()),
-                }
-            })
+            .map(|response| handle_error!(response, keysets).try_into())
             .map_err(|e| Error::Custom(e.to_string()))?
             .map_err(|e| Error::Custom(e.to_string()))?
     }
     }
 
 
@@ -151,16 +146,7 @@ impl Signatory for SignatoryRpcClient {
             .clone()
             .clone()
             .rotate_keyset(req)
             .rotate_keyset(req)
             .await
             .await
-            .map(|response| {
-                match response
-                    .into_inner()
-                    .result
-                    .ok_or(Error::Custom("Internal error".to_owned()))?
-                {
-                    key_rotation_response::Result::Keyset(keyset) => keyset.try_into(),
-                    key_rotation_response::Result::Error(err) => Err(err.into()),
-                }
-            })
+            .map(|response| handle_error!(response, keyset).try_into())
             .map_err(|e| Error::Custom(e.to_string()))?
             .map_err(|e| Error::Custom(e.to_string()))?
     }
     }
 }
 }

+ 1 - 0
crates/cdk-signatory/src/proto/convert.rs

@@ -25,6 +25,7 @@ impl From<crate::signatory::SignatoryKeysets> for SignatoryKeysets {
 }
 }
 
 
 impl TryInto<crate::signatory::SignatoryKeysets> for SignatoryKeysets {
 impl TryInto<crate::signatory::SignatoryKeysets> for SignatoryKeysets {
+    /// TODO: Make sure that all type Error here are cdk_common::Error
     type Error = cdk_common::Error;
     type Error = cdk_common::Error;
 
 
     fn try_into(self) -> Result<crate::signatory::SignatoryKeysets, Self::Error> {
     fn try_into(self) -> Result<crate::signatory::SignatoryKeysets, Self::Error> {

+ 42 - 26
crates/cdk-signatory/src/proto/server.rs

@@ -4,7 +4,6 @@ use std::path::Path;
 use tonic::transport::{Certificate, Identity, Server, ServerTlsConfig};
 use tonic::transport::{Certificate, Identity, Server, ServerTlsConfig};
 use tonic::{Request, Response, Status};
 use tonic::{Request, Response, Status};
 
 
-use super::{boolean_response, key_rotation_response, keys_response, BooleanResponse};
 use crate::proto::{self, signatory_server};
 use crate::proto::{self, signatory_server};
 use crate::signatory::Signatory;
 use crate::signatory::Signatory;
 
 
@@ -36,20 +35,22 @@ where
             )
             )
             .await
             .await
         {
         {
-            Ok(blind_signatures) => {
-                proto::blind_sign_response::Result::Sigs(proto::BlindSignatures {
+            Ok(blind_signatures) => proto::BlindSignResponse {
+                sigs: Some(proto::BlindSignatures {
                     blind_signatures: blind_signatures
                     blind_signatures: blind_signatures
                         .into_iter()
                         .into_iter()
                         .map(|blind_sign| blind_sign.into())
                         .map(|blind_sign| blind_sign.into())
                         .collect(),
                         .collect(),
-                })
-            }
-            Err(err) => proto::blind_sign_response::Result::Error(err.into()),
+                }),
+                ..Default::default()
+            },
+            Err(err) => proto::BlindSignResponse {
+                error: Some(err.into()),
+                ..Default::default()
+            },
         };
         };
 
 
-        Ok(Response::new(proto::BlindSignResponse {
-            result: Some(result),
-        }))
+        Ok(Response::new(result))
     }
     }
 
 
     async fn verify_proofs(
     async fn verify_proofs(
@@ -68,15 +69,22 @@ where
             )
             )
             .await
             .await
         {
         {
-            Ok(()) => boolean_response::Result::Success(true),
-
-            Err(cdk_common::Error::DHKE(_)) => boolean_response::Result::Success(false),
-            Err(err) => boolean_response::Result::Error(err.into()),
+            Ok(()) => proto::BooleanResponse {
+                success: true,
+                ..Default::default()
+            },
+
+            Err(cdk_common::Error::DHKE(_)) => proto::BooleanResponse {
+                success: false,
+                ..Default::default()
+            },
+            Err(err) => proto::BooleanResponse {
+                error: Some(err.into()),
+                ..Default::default()
+            },
         };
         };
 
 
-        Ok(Response::new(BooleanResponse {
-            result: Some(result),
-        }))
+        Ok(Response::new(result))
     }
     }
 
 
     async fn keysets(
     async fn keysets(
@@ -84,13 +92,17 @@ where
         _request: Request<proto::EmptyRequest>,
         _request: Request<proto::EmptyRequest>,
     ) -> Result<Response<proto::KeysResponse>, Status> {
     ) -> Result<Response<proto::KeysResponse>, Status> {
         let result = match self.inner.keysets().await {
         let result = match self.inner.keysets().await {
-            Ok(result) => keys_response::Result::Keysets(result.into()),
-            Err(err) => keys_response::Result::Error(err.into()),
+            Ok(result) => proto::KeysResponse {
+                keysets: Some(result.into()),
+                ..Default::default()
+            },
+            Err(err) => proto::KeysResponse {
+                error: Some(err.into()),
+                ..Default::default()
+            },
         };
         };
 
 
-        Ok(Response::new(proto::KeysResponse {
-            result: Some(result),
-        }))
+        Ok(Response::new(result))
     }
     }
 
 
     async fn rotate_keyset(
     async fn rotate_keyset(
@@ -102,13 +114,17 @@ where
             .rotate_keyset(request.into_inner().try_into()?)
             .rotate_keyset(request.into_inner().try_into()?)
             .await
             .await
         {
         {
-            Ok(result) => key_rotation_response::Result::Keyset(result.into()),
-            Err(err) => key_rotation_response::Result::Error(err.into()),
+            Ok(result) => proto::KeyRotationResponse {
+                keyset: Some(result.into()),
+                ..Default::default()
+            },
+            Err(err) => proto::KeyRotationResponse {
+                error: Some(err.into()),
+                ..Default::default()
+            },
         };
         };
 
 
-        Ok(Response::new(proto::KeyRotationResponse {
-            result: Some(mint_keyset_info),
-        }))
+        Ok(Response::new(mint_keyset_info))
     }
     }
 }
 }
 
 

+ 3 - 0
crates/cdk-signatory/src/signatory.rs

@@ -36,6 +36,8 @@ impl From<CurrencyUnit> for KeysetIdentifier {
 /// RotateKeyArguments
 /// RotateKeyArguments
 ///
 ///
 /// This struct is used to pass the arguments to the rotate_keyset function
 /// This struct is used to pass the arguments to the rotate_keyset function
+///
+/// TODO: Change argument to accept a vector of Amount instead of max_order.
 #[derive(Debug, Clone)]
 #[derive(Debug, Clone)]
 pub struct RotateKeyArguments {
 pub struct RotateKeyArguments {
     /// Unit
     /// Unit
@@ -44,6 +46,7 @@ pub struct RotateKeyArguments {
     pub max_order: u8,
     pub max_order: u8,
     /// Input fee
     /// Input fee
     pub input_fee_ppk: u64,
     pub input_fee_ppk: u64,
+    pub amounts: Vec<Amount>,
 }
 }
 
 
 #[derive(Debug, Clone)]
 #[derive(Debug, Clone)]

+ 2 - 0
crates/cdk/src/mint/mod.rs

@@ -160,6 +160,8 @@ impl Mint {
             return Err(Error::NoActiveKeyset);
             return Err(Error::NoActiveKeyset);
         }
         }
 
 
+        /// TODO: Subscribe to `update_keysets`
+
         tracing::info!(
         tracing::info!(
             "Using Signatory {} with {} active keys",
             "Using Signatory {} with {} active keys",
             signatory.name(),
             signatory.name(),