Skip to content

Commit

Permalink
chore: remove legacy keysets
Browse files Browse the repository at this point in the history
  • Loading branch information
ngutech21 committed Apr 9, 2024
1 parent ac86d4c commit 14dc1e5
Show file tree
Hide file tree
Showing 7 changed files with 30 additions and 142 deletions.
119 changes: 7 additions & 112 deletions moksha-core/src/keyset.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use utoipa::ToSchema;

use base64::{engine::general_purpose, Engine as _};

use bitcoin_hashes::{sha256, Hash};

use itertools::Itertools;
Expand All @@ -42,17 +42,6 @@ pub struct MintKeyset {
}

impl MintKeyset {
pub fn legacy_new(seed: &str, derivation_path: &str) -> Self {
let priv_keys = derive_keys(seed, derivation_path);
let pub_keys = derive_pubkeys(&priv_keys);
Self {
private_keys: priv_keys,
keyset_id: legacy_derive_keyset_id(&pub_keys),
public_keys: pub_keys,
mint_pubkey: derive_pubkey(seed).expect("invalid seed"),
}
}

pub fn new(seed: &str, derivation_path: &str) -> Self {
let priv_keys = derive_keys(seed, derivation_path);
let pub_keys = derive_pubkeys(&priv_keys);
Expand All @@ -65,47 +54,24 @@ impl MintKeyset {
}
}

#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq, Default)]
pub struct Keysets {
pub keysets: Vec<String>,
}

impl Keysets {
pub fn new(keysets: Vec<String>) -> Self {
Self { keysets }
}

pub fn current_keyset(
&self,
mint_keys: &HashMap<u64, PublicKey>,
) -> Result<String, MokshaCoreError> {
let computed_id = legacy_derive_keyset_id(mint_keys);
if self.keysets.contains(&computed_id) {
Ok(computed_id)
} else {
Err(MokshaCoreError::InvalidKeysetid)
}
}
}

// FIXME rename to keysets
#[derive(Clone, Debug, Serialize, Deserialize, Default, ToSchema, PartialEq, Eq)]
pub struct V1Keysets {
pub keysets: Vec<V1Keyset>,
pub struct Keysets {
pub keysets: Vec<Keyset>,
}

// FIXME rename to keyset
#[derive(Clone, Debug, Serialize, Deserialize, ToSchema, PartialEq, Eq)]
pub struct V1Keyset {
pub struct Keyset {
pub id: String, // FIXME use KeysetId
pub unit: CurrencyUnit,
pub active: bool,
}

impl V1Keysets {
impl Keysets {
pub fn new(id: String, unit: CurrencyUnit, active: bool) -> Self {
Self {
keysets: vec![V1Keyset { id, unit, active }],
keysets: vec![Keyset { id, unit, active }],
}
}

Expand Down Expand Up @@ -212,25 +178,6 @@ pub fn derive_pubkeys(keys: &HashMap<u64, SecretKey>) -> HashMap<u64, PublicKey>
.collect()
}

/// Derives a keyset ID from a HashMap of public keys.
///
/// # Arguments
///
/// * `keys` - A HashMap of public keys.
///
/// # Returns
///
/// A string representing the derived keyset ID.
pub fn legacy_derive_keyset_id(keys: &HashMap<u64, PublicKey>) -> String {
let pubkeys_concat = keys
.iter()
.sorted_by(|(amt_a, _), (amt_b, _)| amt_a.cmp(amt_b))
.map(|(_, pubkey)| pubkey)
.join("");
let hashed_pubkeys = sha256::Hash::hash(pubkeys_concat.as_bytes()).to_byte_array();
general_purpose::STANDARD.encode(hashed_pubkeys)[..12].to_string()
}

fn derive_keyset_id(keys: &HashMap<u64, PublicKey>) -> String {
let pubkeys = keys
.iter()
Expand Down Expand Up @@ -263,11 +210,6 @@ mod tests {
use secp256k1::PublicKey;
use std::collections::HashMap;

fn public_key_from_hex(hex: &str) -> secp256k1::PublicKey {
use hex::FromHex;
let input_vec: Vec<u8> = Vec::from_hex(hex).expect("Invalid Hex String");
secp256k1::PublicKey::from_slice(&input_vec).expect("Invalid Public Key")
}

#[test]
fn test_keyset_id() -> anyhow::Result<()> {
Expand All @@ -292,18 +234,7 @@ mod tests {
Ok(())
}

#[test]
fn test_derive_keys_master() -> anyhow::Result<()> {
let keys = super::derive_keys("master", "0/0/0/0");
assert_eq!(keys.len(), 64);

let pub_keys = super::derive_pubkeys(&keys);
let id = super::legacy_derive_keyset_id(&pub_keys);
assert_eq!("JHV8eUnoAln/", id);
assert_eq!(id.len(), 12);
Ok(())
}


#[test]
fn test_derive_keys_master_v1() -> anyhow::Result<()> {
let keys = super::derive_keys("supersecretprivatekey", "");
Expand All @@ -316,42 +247,6 @@ mod tests {
Ok(())
}

// uses values from cashu test_mint.py
#[test]
fn test_derive_keys_cashu_py() -> anyhow::Result<()> {
let keys = super::derive_keys("TEST_PRIVATE_KEY", "0/0/0/0");
assert_eq!(keys.len(), 64);

let pub_keys = super::derive_pubkeys(&keys);
let id = super::legacy_derive_keyset_id(&pub_keys);
assert_eq!("1cCNIAZ2X/w1", id);
assert_eq!(id.len(), 12);
Ok(())
}

#[test]
fn test_legacy_derive_keyset_id() -> anyhow::Result<()> {
let mut pubs = HashMap::new();
pubs.insert(
1,
public_key_from_hex(
"02a9acc1e48c25eeeb9289b5031cc57da9fe72f3fe2861d264bdc074209b107ba2",
),
);

pubs.insert(
2,
public_key_from_hex(
"020000000000000000000000000000000000000000000000000000000000000001",
),
);

let keyset_id = super::legacy_derive_keyset_id(&pubs);

assert_eq!(keyset_id.len(), 12);
assert_eq!(keyset_id, "cNbjM0O6V/Kl");
Ok(())
}

#[test]
fn test_derive_keyset_id() -> anyhow::Result<()> {
Expand Down
17 changes: 5 additions & 12 deletions moksha-mint/src/mint.rs
Original file line number Diff line number Diff line change
Expand Up @@ -32,8 +32,6 @@ use crate::lightning::cln::ClnLightning;
pub struct Mint<DB: Database = PostgresDB> {
pub lightning: Arc<dyn Lightning + Send + Sync>,
pub lightning_type: LightningType,
// FIXME remove after v1 api release
pub keyset_legacy: MintKeyset,
pub keyset: MintKeyset,
pub db: DB,
pub dhke: Dhke,
Expand All @@ -57,11 +55,6 @@ where
Self {
lightning,
lightning_type,
keyset_legacy: MintKeyset::legacy_new(
// FIXME
&config.privatekey.clone(),
&config.derivation_path.clone().unwrap_or_default(),
),
keyset: MintKeyset::new(
&config.privatekey.clone(),
&config.derivation_path.clone().unwrap_or_default(),
Expand Down Expand Up @@ -171,7 +164,7 @@ where
let amount_promises = promises.total_amount();
if sum_proofs != amount_promises {
return Err(MokshaMintError::SwapAmountMismatch(format!(
"Split amount mismatch: {sum_proofs} != {amount_promises}"
"Swap amount mismatch: {sum_proofs} != {amount_promises}"
)));
}

Expand Down Expand Up @@ -532,7 +525,7 @@ mod tests {
moksha_core::primitives::PaymentMethod::Bolt11,
"somehash".to_string(),
&outputs,
&mint.keyset_legacy,
&mint.keyset,
true,
)
.await?;
Expand Down Expand Up @@ -562,7 +555,7 @@ mod tests {
moksha_core::primitives::PaymentMethod::Bolt11,
"somehash".to_string(),
&outputs,
&mint.keyset_legacy,
&mint.keyset,
true,
)
.await?;
Expand All @@ -585,7 +578,7 @@ mod tests {

let proofs = Proofs::empty();
let result = mint
.swap(&proofs, &blinded_messages, &mint.keyset_legacy)
.swap(&proofs, &blinded_messages, &mint.keyset)
.await?;

assert!(result.is_empty());
Expand Down Expand Up @@ -688,7 +681,7 @@ mod tests {
4,
&tokens.proofs(),
&change,
&mint.keyset_legacy,
&mint.keyset,
)
.await?;

Expand Down
8 changes: 4 additions & 4 deletions moksha-mint/src/routes/default.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ use axum::{
Json,
};
use moksha_core::{
keyset::V1Keysets,
keyset::Keysets,
primitives::{
Bolt11MeltQuote, Bolt11MintQuote, CurrencyUnit, KeyResponse, KeysResponse,
MintInfoResponse, Nuts, PaymentMethod, PostMeltBolt11Request, PostMeltBolt11Response,
Expand Down Expand Up @@ -96,12 +96,12 @@ pub async fn get_keys_by_id(
get,
path = "/v1/keysets",
responses(
(status = 200, description = "get keysets", body = [V1Keysets])
(status = 200, description = "get keysets", body = [Keysets])
),
)]
#[instrument(skip(mint), err)]
pub async fn get_keysets(State(mint): State<Mint>) -> Result<Json<V1Keysets>, MokshaMintError> {
Ok(Json(V1Keysets::new(
pub async fn get_keysets(State(mint): State<Mint>) -> Result<Json<Keysets>, MokshaMintError> {
Ok(Json(Keysets::new(
mint.keyset.keyset_id,
CurrencyUnit::Sat,
true,
Expand Down
16 changes: 8 additions & 8 deletions moksha-mint/src/server.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ use axum::routing::{get_service, post, get};
use axum::{middleware, Router};


use moksha_core::keyset::{V1Keyset, V1Keysets};
use moksha_core::keyset::{Keyset, Keysets};
use moksha_core::proof::Proofs;
use moksha_core::proof::{P2SHScript, Proof};

Expand Down Expand Up @@ -130,8 +130,8 @@ pub async fn run_server(mint: Mint) -> anyhow::Result<()> {
PaymentMethod,
KeysResponse,
KeyResponse,
V1Keysets,
V1Keyset,
Keysets,
Keyset,
BlindedMessage,
BlindedSignature,
Proof,
Expand Down Expand Up @@ -283,7 +283,7 @@ mod tests {
};
use http_body_util::BodyExt;
use moksha_core::{
keyset::V1Keysets,
keyset::Keysets,
primitives::{CurrencyUnit, KeysResponse, MintInfoResponse},
};

Expand Down Expand Up @@ -328,8 +328,8 @@ mod tests {
.await?;
assert_eq!(response.status(), StatusCode::OK);
let body = response.into_body().collect().await?.to_bytes();
let keysets = serde_json::from_slice::<V1Keysets>(&body)?;
assert_eq!(V1Keysets::new("00f545318e4fad2b".to_owned(), CurrencyUnit::Sat, true), keysets);
let keysets = serde_json::from_slice::<Keysets>(&body)?;
assert_eq!(Keysets::new("00f545318e4fad2b".to_owned(), CurrencyUnit::Sat, true), keysets);
Ok(())
}

Expand Down Expand Up @@ -408,7 +408,7 @@ mod tests {

assert_eq!(response.status(), StatusCode::OK);
let body = response.into_body().collect().await?.to_bytes();
let keysets = serde_json::from_slice::<V1Keysets>(&body)?;
let keysets = serde_json::from_slice::<Keysets>(&body)?;
assert_eq!(1, keysets.keysets.len());
assert_eq!(16, keysets.keysets[0].id.len());
Ok(())
Expand Down Expand Up @@ -500,7 +500,7 @@ mod tests {

assert_eq!(response.status(), StatusCode::OK);
let body = response.into_body().collect().await?.to_bytes();
let keys: V1Keysets = serde_json::from_slice(&body)?;
let keys: Keysets = serde_json::from_slice(&body)?;
assert_eq!(1, keys.keysets.len());
let keyset = keys.keysets.first().expect("keyset not found");
assert!(keyset.active);
Expand Down
4 changes: 2 additions & 2 deletions moksha-wallet/src/client/crossplatform.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ use async_trait::async_trait;

use moksha_core::{
blind::BlindedMessage,
keyset::V1Keysets,
keyset::Keysets,
primitives::{
CurrencyUnit, GetMeltBtcOnchainResponse, KeysResponse, MintInfoResponse,
PostMeltBolt11Request, PostMeltBolt11Response, PostMeltBtcOnchainRequest,
Expand Down Expand Up @@ -36,7 +36,7 @@ impl CashuClient for CrossPlatformHttpClient {
.await
}

async fn get_keysets(&self, mint_url: &Url) -> Result<V1Keysets, MokshaWalletError> {
async fn get_keysets(&self, mint_url: &Url) -> Result<Keysets, MokshaWalletError> {
self.do_get(&mint_url.join("v1/keysets")?).await
}

Expand Down
4 changes: 2 additions & 2 deletions moksha-wallet/src/client/mod.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
use async_trait::async_trait;
use moksha_core::{
blind::BlindedMessage,
keyset::V1Keysets,
keyset::Keysets,
primitives::{
CurrencyUnit, GetMeltBtcOnchainResponse, KeysResponse, MintInfoResponse,
PostMeltBolt11Response, PostMeltBtcOnchainResponse, PostMeltQuoteBolt11Response,
Expand Down Expand Up @@ -31,7 +31,7 @@ pub trait CashuClient {
keyset_id: String,
) -> Result<KeysResponse, MokshaWalletError>;

async fn get_keysets(&self, mint_url: &Url) -> Result<V1Keysets, MokshaWalletError>;
async fn get_keysets(&self, mint_url: &Url) -> Result<Keysets, MokshaWalletError>;

async fn post_swap(
&self,
Expand Down
4 changes: 2 additions & 2 deletions moksha-wallet/src/wallet.rs
Original file line number Diff line number Diff line change
Expand Up @@ -839,7 +839,7 @@ mod tests {
use crate::wallet::WalletBuilder;

use moksha_core::fixture::{read_fixture, read_fixture_as};
use moksha_core::keyset::{KeysetId, MintKeyset, V1Keysets};
use moksha_core::keyset::{KeysetId, MintKeyset, Keysets};
use moksha_core::primitives::{
CurrencyUnit, KeyResponse, KeysResponse, PaymentMethod, PostMeltBolt11Response,
PostMeltQuoteBolt11Response, PostMintBolt11Response, PostSwapResponse,
Expand All @@ -858,7 +858,7 @@ mod tests {
};
let keys_response = KeysResponse::new(key_response.clone());
let keys_by_id_response = keys_response.clone();
let keysets = V1Keysets::new(keys.keyset_id, CurrencyUnit::Sat, true);
let keysets = Keysets::new(keys.keyset_id, CurrencyUnit::Sat, true);

let mut client = MockCashuClient::default();
client
Expand Down

0 comments on commit 14dc1e5

Please sign in to comment.