Skip to content

Commit

Permalink
refactor: add more tests, use blake3
Browse files Browse the repository at this point in the history
  • Loading branch information
tbraun96 committed Dec 17, 2024
1 parent 4f1f56f commit 525e183
Show file tree
Hide file tree
Showing 20 changed files with 141 additions and 75 deletions.
2 changes: 2 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

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

[features]
Expand All @@ -34,4 +35,4 @@ bn254 = ["gadget-crypto-bn254", "gadget-crypto-core/bn254"]
sp-core = ["gadget-crypto-sp-core", "gadget-crypto-core/tangle"]
sp-core-bls = ["gadget-crypto-sp-core/bls", "gadget-crypto-core/tangle"]

hashing = ["sha2", "sha3"]
hashing = ["sha2", "sha3", "blake3"]
12 changes: 12 additions & 0 deletions crates/crypto/bls/src/w3f_bls.rs
Original file line number Diff line number Diff line change
Expand Up @@ -138,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);
}
43 changes: 23 additions & 20 deletions crates/crypto/core/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -140,17 +140,6 @@ macro_rules! impl_crypto_tests {
// Test random key generation
let secret = <$ecdsa_type>::generate_with_seed(None).unwrap();
let _public = <$ecdsa_type>::public_from_secret(&secret);

// Test deterministic key generation with seed
let seed = [1u8; 32];
let secret1 = <$ecdsa_type>::generate_with_seed(Some(&seed)).unwrap();
let secret2 = <$ecdsa_type>::generate_with_seed(Some(&seed)).unwrap();
assert_eq!(secret1, secret2, "Deterministic key generation should produce same keys");

// Test key generation from string
let hex_string = hex::encode(&seed);
let secret3 = <$ecdsa_type>::generate_with_string(hex_string).unwrap();
assert_eq!(secret1, secret3, "String-based key generation should match seed-based");
}

#[test]
Expand All @@ -161,17 +150,22 @@ macro_rules! impl_crypto_tests {
// Test normal signing
let message = b"Hello, world!";
let signature = <$ecdsa_type>::sign_with_secret(&mut secret, message).unwrap();
assert!(<$ecdsa_type>::verify(&public, message, &signature),
"Signature verification failed");
assert!(
<$ecdsa_type>::verify(&public, message, &signature),
"Signature verification failed"
);

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

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

#[test]
Expand All @@ -182,12 +176,18 @@ macro_rules! impl_crypto_tests {
// 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");
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");
assert_eq!(
public, deserialized,
"VerifyingKey serialization roundtrip failed"
);
}

#[test]
Expand All @@ -199,7 +199,10 @@ macro_rules! impl_crypto_tests {
// 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");
assert_eq!(
signature, deserialized,
"Signature serialization roundtrip failed"
);
}

#[test]
Expand All @@ -217,4 +220,4 @@ macro_rules! impl_crypto_tests {
assert_eq!(public1.partial_cmp(&public2), Some(public1.cmp(&public2)));
}
};
}
}
1 change: 0 additions & 1 deletion crates/crypto/ed25519/src/zebra_ed25519.rs
Original file line number Diff line number Diff line change
Expand Up @@ -163,6 +163,5 @@ impl KeyType for Ed25519Zebra {
#[cfg(test)]
mod tests {
use super::*;
// Generate tests for K256 ECDSA
gadget_crypto_core::impl_crypto_tests!(Ed25519Zebra, Ed25519SigningKey, Ed25519Signature);
}
8 changes: 3 additions & 5 deletions crates/crypto/k256/src/k256_ecdsa.rs
Original file line number Diff line number Diff line change
@@ -1,11 +1,9 @@
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},
};
use k256::ecdsa::signature::SignerMut;
use serde::{Deserialize, Serialize};
use crate::error::{K256Error, Result};

/// ECDSA key type
pub struct K256Ecdsa;
Expand Down Expand Up @@ -142,4 +140,4 @@ mod tests {
use super::*;
// Generate tests for K256 ECDSA
gadget_crypto_core::impl_crypto_tests!(K256Ecdsa, K256SigningKey, K256Signature);
}
}
18 changes: 18 additions & 0 deletions crates/crypto/sp-core/src/sp_core_util.rs
Original file line number Diff line number Diff line change
Expand Up @@ -238,3 +238,21 @@ impl_sp_core_crypto!(SpSr25519, sr25519);
impl Copy for SpEcdsaPublic {}
impl Copy for SpEd25519Public {}
impl Copy for SpSr25519Public {}

#[cfg(test)]
mod tests_ecdsa {
use super::*;
gadget_crypto_core::impl_crypto_tests!(SpEcdsa, SpEcdsaPair, SpEcdsaSignature);
}

#[cfg(test)]
mod tests_ed25519 {
use super::*;
gadget_crypto_core::impl_crypto_tests!(SpEd25519, SpEd25519Pair, SpEd25519Signature);
}

#[cfg(test)]
mod tests_sr25519 {
use super::*;
gadget_crypto_core::impl_crypto_tests!(SpSr25519, SpSr25519Pair, SpSr25519Signature);
}
8 changes: 7 additions & 1 deletion crates/crypto/sr25519/src/schnorrkel_sr25519.rs
Original file line number Diff line number Diff line change
Expand Up @@ -54,8 +54,8 @@ impl_schnorrkel_serde!(Secret, schnorrkel::SecretKey);
impl_schnorrkel_serde!(SchnorrkelSignature, schnorrkel::Signature);

impl KeyType for SchnorrkelSr25519 {
type Public = Public;
type Secret = Secret;
type Public = Public;
type Signature = SchnorrkelSignature;
type Error = Sr25519Error;

Expand Down Expand Up @@ -114,3 +114,9 @@ impl KeyType for SchnorrkelSr25519 {
}
}
}

#[cfg(test)]
mod tests {
use super::*;
gadget_crypto_core::impl_crypto_tests!(SchnorrkelSr25519, Secret, SchnorrkelSignature);
}
7 changes: 7 additions & 0 deletions crates/crypto/src/hashing.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,3 +24,10 @@ pub fn keccak_256(data: &[u8]) -> [u8; 32] {
let output = hasher.finalize();
output.into()
}

pub fn blake3_256(data: &[u8]) -> [u8; 32] {
let mut hasher = blake3::Hasher::new();
hasher.update(data);
let output = hasher.finalize();
output.into()
}
6 changes: 4 additions & 2 deletions crates/networking/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ gadget-crypto = { workspace = true, features = ["k256", "hashing"] }
k256 = { workspace = true }

# Round-based protocol support
round-based = { workspace = true }
round-based = { workspace = true, optional = true }

[dev-dependencies]

Expand Down Expand Up @@ -72,9 +72,11 @@ std = [
"tokio/full",
"serde/std",
"serde_json/std",
"round-based/std",
"round-based?/std",
]

round-based-compat = ["round-based"]

# Only one of these features should be enabled at a time.
# If none are enabled, k256 ECDSA will be used by default.
sp-core-ecdsa = ["gadget-crypto/sp-core"]
Expand Down
9 changes: 5 additions & 4 deletions crates/networking/src/gossip.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,10 @@
clippy::exhaustive_enums
)]

use std::sync::atomic::AtomicUsize;
use crate::key_types::{CryptoKeyPair, CryptoPublicKey, CryptoSignature};
use crate::Error;
use async_trait::async_trait;
use gadget_crypto::hashing::keccak_256;
use gadget_crypto::hashing::blake3_256;
use gadget_std::collections::BTreeMap;
use gadget_std::string::ToString;
use gadget_std::sync::Arc;
Expand All @@ -20,6 +19,7 @@ use libp2p::{
};
use lru_mem::LruCache;
use serde::{Deserialize, Serialize};
use std::sync::atomic::AtomicUsize;
use tokio::sync::mpsc::UnboundedSender;
use tokio::sync::{Mutex, RwLock};

Expand Down Expand Up @@ -362,7 +362,7 @@ impl Network for GossipHandle {
drop(lock);
match bincode::deserialize::<ProtocolMessage>(&message_bytes) {
Ok(message) => {
let hash = keccak_256(&message_bytes);
let hash = blake3_256(&message_bytes);
let mut map = self.recent_messages.lock();
if map
.insert(hash, ())
Expand Down Expand Up @@ -402,7 +402,8 @@ impl Network for GossipHandle {
MessageType::Broadcast
};

let raw_payload = bincode::serialize(&message).map_err(|err| Error::MessagingError(err.to_string()))?;
let raw_payload =
bincode::serialize(&message).map_err(|err| Error::MessagingError(err.to_string()))?;
let payload_inner = match message_type {
MessageType::Broadcast => GossipOrRequestResponse::Gossip(GossipMessage {
topic: self.topic.to_string(),
Expand Down
21 changes: 14 additions & 7 deletions crates/networking/src/handlers/connections.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

use crate::gossip::{MyBehaviourRequest, NetworkService};
use crate::key_types::CryptoKeyCurve;
use gadget_crypto::{hashing::keccak_256, KeyType};
use gadget_crypto::{hashing::blake3_256, KeyType};
use itertools::Itertools;
use libp2p::PeerId;

Expand All @@ -14,10 +14,16 @@ impl NetworkService<'_> {
_num_established: u32,
) {
gadget_logging::debug!("Connection established");
if !self.crypto_peer_id_to_libp2p_id.read().await.iter().any(|(_, id)| id == &peer_id) {
let my_peer_id = self.swarm.local_peer_id().clone();
if !self
.crypto_peer_id_to_libp2p_id
.read()
.await
.iter()
.any(|(_, id)| id == &peer_id)
{
let my_peer_id = *self.swarm.local_peer_id();
let msg = my_peer_id.to_bytes();
let hash = keccak_256(&msg);
let hash = blake3_256(&msg);
match <CryptoKeyCurve as KeyType>::sign_with_secret_pre_hashed(
&mut self.crypto_secret_key.clone(),
&hash,
Expand All @@ -35,7 +41,7 @@ impl NetworkService<'_> {
.behaviour_mut()
.gossipsub
.add_explicit_peer(&peer_id);
gadget_logging::info!("Sent handshake from {my_peer_id} to {peer_id}")
gadget_logging::info!("Sent handshake from {my_peer_id} to {peer_id}");
}
Err(e) => {
gadget_logging::error!("Failed to sign handshake: {e}");
Expand All @@ -59,9 +65,10 @@ impl NetworkService<'_> {
.remove_explicit_peer(&peer_id);
let mut pub_key_to_libp2p_id = self.crypto_peer_id_to_libp2p_id.write().await;
let len_initial = 0;
pub_key_to_libp2p_id.retain(|_, id| &*id != &peer_id);
pub_key_to_libp2p_id.retain(|_, id| *id != peer_id);
if pub_key_to_libp2p_id.len() == len_initial + 1 {
self.connected_peers.fetch_sub(1, std::sync::atomic::Ordering::Relaxed);
self.connected_peers
.fetch_sub(1, std::sync::atomic::Ordering::Relaxed);
}
}
}
Expand Down
2 changes: 1 addition & 1 deletion crates/networking/src/handlers/gossip.rs
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
#![allow(unused_results)]

use std::sync::atomic::AtomicUsize;
use crate::gossip::{GossipMessage, NetworkService};
use gadget_std::string::ToString;
use gadget_std::sync::Arc;
use libp2p::gossipsub::TopicHash;
use libp2p::{gossipsub, PeerId};
use std::sync::atomic::AtomicUsize;

impl NetworkService<'_> {
#[tracing::instrument(skip(self, event))]
Expand Down
Loading

0 comments on commit 525e183

Please sign in to comment.