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

refactor: cleanup networking, get clippy --tests for networking passing #10

Merged
merged 5 commits into from
Dec 18, 2024
Merged
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
767 changes: 25 additions & 742 deletions Cargo.lock

Large diffs are not rendered by default.

2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -256,7 +256,7 @@ dashmap = { version = "6.1.0", default-features = false }
lru-mem = { version = "0.3.0", default-features = false }

# Metrics
metrics = { version = "0.24" }
metrics = { version = "0.24.1", default-features = false }
metrics-exporter-prometheus = { version = "0.16" }
prometheus = { version = "0.13.4", default-features = false }

Expand Down
3 changes: 2 additions & 1 deletion crates/crypto/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ gadget-crypto-sp-core = { path = "sp-core", optional = true }
gadget-crypto-tangle-pair-signer = { workspace = true, optional = true }
sha2 = { workspace = true, optional = true }
sha3 = { workspace = true, optional = true }
blake3 = { workspace = true, optional = true }
thiserror = { workspace = true }

[features]
Expand All @@ -37,4 +38,4 @@ sp-core = ["gadget-crypto-sp-core", "gadget-crypto-core/tangle"]
sp-core-bls = ["gadget-crypto-sp-core/bls", "gadget-crypto-core/tangle"]
tangle-pair-signer = ["gadget-crypto-tangle-pair-signer"]

hashing = ["sha2", "sha3"]
hashing = ["sha2", "sha3", "blake3"]
17 changes: 15 additions & 2 deletions crates/crypto/bls/src/w3f_bls.rs
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,8 @@ macro_rules! impl_w3f_serde {
&self,
serializer: S,
) -> core::result::Result<S::Ok, S::Error> {
serializer.serialize_bytes(&to_bytes(self.0.clone()))
let bytes = to_bytes(self.0.clone());
Vec::serialize(&bytes, serializer)
}
}

Expand All @@ -45,7 +46,7 @@ macro_rules! impl_w3f_serde {
where
D: serde::Deserializer<'de>,
{
// Deserialize as bytes
// Deserialize as Vec
let bytes = <gadget_std::vec::Vec<u8>>::deserialize(deserializer)?;

// Convert bytes back to inner type
Expand Down Expand Up @@ -137,3 +138,15 @@ macro_rules! define_bls_key {
}

define_bls_key!(Bls377, Bls381);

#[cfg(test)]
mod test_bls377 {
use super::bls377::{Secret, W3fBls377, W3fBls377Signature};
gadget_crypto_core::impl_crypto_tests!(W3fBls377, Secret, W3fBls377Signature);
}

#[cfg(test)]
mod test_bls381 {
use super::bls381::{Secret, W3fBls381, W3fBls381Signature};
gadget_crypto_core::impl_crypto_tests!(W3fBls381, Secret, W3fBls381Signature);
}
1 change: 1 addition & 0 deletions crates/crypto/bn254/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ thiserror = { workspace = true }
num-bigint = { workspace = true, features = ["serde"] }
num-traits = { workspace = true }
sha2 = { workspace = true }
hex = { workspace = true, features = ["alloc"] }

[features]
default = ["std"]
Expand Down
9 changes: 7 additions & 2 deletions crates/crypto/bn254/src/arkworks_bn254.rs
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,8 @@ macro_rules! impl_ark_serde {
&self,
serializer: S,
) -> core::result::Result<S::Ok, S::Error> {
serializer.serialize_bytes(&to_bytes(self.0))
let bytes = to_bytes(self.0);
Vec::serialize(&bytes, serializer)
}
}

Expand Down Expand Up @@ -114,4 +115,8 @@ impl KeyType for ArkBlsBn254 {
}
}

// Continue with KeyType implementation...
#[cfg(test)]
mod tests {
use super::*;
gadget_crypto_core::impl_crypto_tests!(ArkBlsBn254, ArkBlsBn254Secret, ArkBlsBn254Signature);
}
91 changes: 91 additions & 0 deletions crates/crypto/core/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -130,3 +130,94 @@ pub trait KeyType: Sized + 'static {
) -> Result<Self::Signature, Self::Error>;
fn verify(public: &Self::Public, msg: &[u8], signature: &Self::Signature) -> bool;
}

#[macro_export]
macro_rules! impl_crypto_tests {
($crypto_type:ty, $signing_key:ty, $signature:ty) => {
use $crate::KeyType;
#[test]
fn test_key_generation() {
// Test random key generation
let secret = <$crypto_type>::generate_with_seed(None).unwrap();
let _public = <$crypto_type>::public_from_secret(&secret);
}

#[test]
fn test_signing_and_verification() {
let mut secret = <$crypto_type>::generate_with_seed(None).unwrap();
let public = <$crypto_type>::public_from_secret(&secret);

// Test normal signing
let message = b"Hello, world!";
let signature = <$crypto_type>::sign_with_secret(&mut secret, message).unwrap();
assert!(
<$crypto_type>::verify(&public, message, &signature),
"Signature verification failed"
);

// Test pre-hashed signing
let hashed_msg = [42u8; 32];
let signature =
<$crypto_type>::sign_with_secret_pre_hashed(&mut secret, &hashed_msg).unwrap();

// Verify with wrong message should fail
let wrong_message = b"Wrong message";
assert!(
!<$crypto_type>::verify(&public, wrong_message, &signature),
"Verification should fail with wrong message"
);
}

#[test]
fn test_key_serialization() {
let secret = <$crypto_type>::generate_with_seed(None).unwrap();
let public = <$crypto_type>::public_from_secret(&secret);

// Test signing key serialization
let serialized = serde_json::to_string(&secret).unwrap();
let deserialized: $signing_key = serde_json::from_str(&serialized).unwrap();
assert_eq!(
secret, deserialized,
"SigningKey serialization roundtrip failed"
);

// Test verifying key serialization
let serialized = serde_json::to_string(&public).unwrap();
let deserialized = serde_json::from_str(&serialized).unwrap();
assert_eq!(
public, deserialized,
"VerifyingKey serialization roundtrip failed"
);
}

#[test]
fn test_signature_serialization() {
let mut secret = <$crypto_type>::generate_with_seed(None).unwrap();
let message = b"Test message";
let signature = <$crypto_type>::sign_with_secret(&mut secret, message).unwrap();

// Test signature serialization
let serialized = serde_json::to_string(&signature).unwrap();
let deserialized: $signature = serde_json::from_str(&serialized).unwrap();
assert_eq!(
signature, deserialized,
"Signature serialization roundtrip failed"
);
}

#[test]
fn test_key_comparison() {
let secret1 = <$crypto_type>::generate_with_seed(None).unwrap();
let secret2 = <$crypto_type>::generate_with_seed(None).unwrap();
let public1 = <$crypto_type>::public_from_secret(&secret1);
let public2 = <$crypto_type>::public_from_secret(&secret2);

// Test Ord implementation
assert!(public1 != public2, "Different keys should not be equal");
assert_eq!(public1.cmp(&public1), gadget_std::cmp::Ordering::Equal);

// Verify consistency between PartialOrd and Ord
assert_eq!(public1.partial_cmp(&public2), Some(public1.cmp(&public2)));
}
};
}
12 changes: 9 additions & 3 deletions crates/crypto/ed25519/src/zebra_ed25519.rs
Original file line number Diff line number Diff line change
Expand Up @@ -45,8 +45,8 @@ macro_rules! impl_zebra_serde {
S: serde::Serializer,
{
// Get the raw bytes
let bytes = self.0.as_ref();
serializer.serialize_bytes(bytes)
let bytes = self.0.as_ref().to_vec();
Vec::serialize(&bytes, serializer)
}
}

Expand Down Expand Up @@ -75,7 +75,7 @@ pub struct Ed25519Signature(pub ed25519_zebra::Signature);

impl PartialOrd for Ed25519Signature {
fn partial_cmp(&self, other: &Self) -> Option<gadget_std::cmp::Ordering> {
self.0.to_bytes().partial_cmp(&other.0.to_bytes())
Some(self.cmp(other))
}
}

Expand Down Expand Up @@ -159,3 +159,9 @@ impl KeyType for Ed25519Zebra {
public.0.verify(&signature.0, msg).is_ok()
}
}

#[cfg(test)]
mod tests {
use super::*;
gadget_crypto_core::impl_crypto_tests!(Ed25519Zebra, Ed25519SigningKey, Ed25519Signature);
}
4 changes: 2 additions & 2 deletions crates/crypto/k256/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,9 @@ edition = "2021"
[dependencies]
gadget-crypto-core = { workspace = true, features = ["k256"] }
gadget-std = { workspace = true }
k256 = { workspace = true, features = ["ecdsa", "alloc"] }
k256 = { workspace = true, features = ["ecdsa", "alloc", "serde", "pem"] }
serde = { workspace = true }
serde_json = { workspace = true, features = ["alloc"] }
serde_json = { workspace = true }
thiserror = { workspace = true }
hex = { workspace = true, features = ["alloc"] }

Expand Down
59 changes: 23 additions & 36 deletions crates/crypto/k256/src/k256_ecdsa.rs
Original file line number Diff line number Diff line change
@@ -1,22 +1,19 @@
use crate::error::{K256Error, Result};
use gadget_crypto_core::{KeyType, KeyTypeId};
use gadget_std::string::{String, ToString};
use gadget_std::UniformRand;
use gadget_std::{
string::{String, ToString},
vec::Vec,
};
use k256::ecdsa::signature::SignerMut;

use crate::error::{K256Error, Result};
use serde::{Deserialize, Serialize};

/// ECDSA key type
pub struct K256Ecdsa;

#[derive(Clone, Copy, PartialEq, Eq, Debug)]
#[derive(Clone, Copy, PartialEq, Eq, Debug, Serialize, Deserialize)]
pub struct K256VerifyingKey(pub k256::ecdsa::VerifyingKey);

impl PartialOrd for K256VerifyingKey {
fn partial_cmp(&self, other: &Self) -> Option<gadget_std::cmp::Ordering> {
self.0.to_sec1_bytes().partial_cmp(&other.0.to_sec1_bytes())
Some(self.cmp(other))
}
}

Expand All @@ -26,36 +23,14 @@ impl Ord for K256VerifyingKey {
}
}

impl serde::Serialize for K256VerifyingKey {
fn serialize<S>(&self, serializer: S) -> core::result::Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
let bytes = self.0.to_sec1_bytes();
serializer.serialize_bytes(&bytes)
}
}

impl<'de> serde::Deserialize<'de> for K256VerifyingKey {
fn deserialize<D>(deserializer: D) -> core::result::Result<Self, D::Error>
where
D: serde::Deserializer<'de>,
{
let bytes = <Vec<u8>>::deserialize(deserializer)?;
let verifying_key = k256::ecdsa::VerifyingKey::from_sec1_bytes(&bytes)
.map_err(|e| serde::de::Error::custom(e.to_string()))?;
Ok(K256VerifyingKey(verifying_key))
}
}

macro_rules! impl_serde_bytes {
($wrapper:ident, $inner:path) => {
#[derive(Clone, PartialEq, Eq, Debug)]
pub struct $wrapper(pub $inner);

impl PartialOrd for $wrapper {
fn partial_cmp(&self, other: &Self) -> Option<gadget_std::cmp::Ordering> {
self.0.to_bytes().partial_cmp(&other.0.to_bytes())
Some(self.cmp(other))
}
}

Expand All @@ -70,8 +45,8 @@ macro_rules! impl_serde_bytes {
where
S: serde::Serializer,
{
let bytes = self.0.to_bytes();
serializer.serialize_bytes(&bytes)
let bytes = self.0.to_bytes().to_vec();
Vec::serialize(&bytes, serializer)
}
}

Expand All @@ -93,8 +68,8 @@ impl_serde_bytes!(K256SigningKey, k256::ecdsa::SigningKey);
impl_serde_bytes!(K256Signature, k256::ecdsa::Signature);

impl KeyType for K256Ecdsa {
type Public = K256VerifyingKey;
type Secret = K256SigningKey;
type Public = K256VerifyingKey;
type Signature = K256Signature;
type Error = K256Error;

Expand Down Expand Up @@ -124,7 +99,7 @@ impl KeyType for K256Ecdsa {
}

fn public_from_secret(secret: &Self::Secret) -> Self::Public {
K256VerifyingKey(secret.0.verifying_key().clone())
K256VerifyingKey(*secret.0.verifying_key())
}

fn sign_with_secret(secret: &mut Self::Secret, msg: &[u8]) -> Result<Self::Signature> {
Expand All @@ -151,6 +126,18 @@ impl KeyType for K256Ecdsa {

impl K256SigningKey {
pub fn verifying_key(&self) -> K256VerifyingKey {
K256VerifyingKey(self.0.verifying_key().clone())
K256VerifyingKey(*self.0.verifying_key())
}

/// Alias for `verifying_key` for consistency
pub fn public(&self) -> K256VerifyingKey {
self.verifying_key()
}
}

#[cfg(test)]
mod tests {
use super::*;
// Generate tests for K256 ECDSA
gadget_crypto_core::impl_crypto_tests!(K256Ecdsa, K256SigningKey, K256Signature);
}
23 changes: 1 addition & 22 deletions crates/crypto/sp-core/src/sp_core_bls_util.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ use crate::{impl_sp_core_key_type, impl_sp_core_pair_public};
macro_rules! impl_sp_core_bls_signature {
($key_type:ident, $signature:ty) => {
paste::paste! {
#[derive(Clone, PartialEq, Eq)]
#[derive(Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub struct [<$key_type Signature>](pub $signature);

impl PartialOrd for [<$key_type Signature>] {
Expand All @@ -37,27 +37,6 @@ macro_rules! impl_sp_core_bls_signature {
write!(f, "{:?}", bytes)
}
}

impl serde::Serialize for [<$key_type Signature>] {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
serializer.serialize_bytes(self.0.as_ref())
}
}

impl<'de> serde::Deserialize<'de> for [<$key_type Signature>] {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: serde::Deserializer<'de>,
{
let bytes = <Vec<u8>>::deserialize(deserializer)?;
let sig = <$signature>::from_slice(&bytes)
.map_err(|_| serde::de::Error::custom("Invalid signature length"))?;
Ok([<$key_type Signature>](sig))
}
}
}
};
}
Expand Down
Loading
Loading