Skip to content

Commit

Permalink
More tests.
Browse files Browse the repository at this point in the history
  • Loading branch information
brunoffranca committed Oct 20, 2024
1 parent 6ad2420 commit 1252631
Show file tree
Hide file tree
Showing 23 changed files with 1,314 additions and 893 deletions.
2 changes: 1 addition & 1 deletion node/actors/bft/src/leader/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -564,7 +564,7 @@ async fn replica_commit_bad_chain() {
assert_matches!(
res,
Err(replica_commit::Error::InvalidMessage(
validator::ReplicaCommitVerifyError::View(_)
validator::ReplicaCommitVerifyError::BadView(_)
))
);
Ok(())
Expand Down
2 changes: 1 addition & 1 deletion node/actors/bft/src/replica/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -550,7 +550,7 @@ async fn leader_commit_bad_chain() {
res,
Err(leader_commit::Error::InvalidMessage(
validator::CommitQCVerifyError::InvalidMessage(
validator::ReplicaCommitVerifyError::View(_)
validator::ReplicaCommitVerifyError::BadView(_)
)
))
);
Expand Down
2 changes: 1 addition & 1 deletion node/libs/crypto/src/keccak256/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ mod test;
pub mod testonly;

/// Keccak256 hash.
#[derive(Copy, Clone, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[derive(Copy, Clone, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Keccak256(pub(crate) [u8; 32]);

impl Keccak256 {
Expand Down
2 changes: 2 additions & 0 deletions node/libs/roles/src/validator/keys/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@ mod aggregate_signature;
mod public_key;
mod secret_key;
mod signature;
#[cfg(test)]
mod tests;

pub use aggregate_signature::AggregateSignature;
pub use public_key::PublicKey;
Expand Down
58 changes: 29 additions & 29 deletions node/libs/roles/src/validator/keys/signature.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,14 +19,9 @@ impl Signature {
}
}

/// Proof of possession of a validator secret key.
#[derive(Clone, PartialEq, Eq)]
pub struct ProofOfPossession(pub(crate) bls12_381::ProofOfPossession);

impl ProofOfPossession {
/// Verifies the proof against the public key.
pub fn verify(&self, pk: &PublicKey) -> anyhow::Result<()> {
self.0.verify(&pk.0)
impl fmt::Debug for Signature {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
fmt.write_str(&TextFmt::encode(self))
}
}

Expand All @@ -39,15 +34,6 @@ impl ByteFmt for Signature {
}
}

impl ByteFmt for ProofOfPossession {
fn encode(&self) -> Vec<u8> {
ByteFmt::encode(&self.0)
}
fn decode(bytes: &[u8]) -> anyhow::Result<Self> {
ByteFmt::decode(bytes).map(Self)
}
}

impl TextFmt for Signature {
fn encode(&self) -> String {
format!(
Expand All @@ -62,6 +48,32 @@ impl TextFmt for Signature {
}
}

/// Proof of possession of a validator secret key.
#[derive(Clone, PartialEq, Eq)]
pub struct ProofOfPossession(pub(crate) bls12_381::ProofOfPossession);

impl ProofOfPossession {
/// Verifies the proof against the public key.
pub fn verify(&self, pk: &PublicKey) -> anyhow::Result<()> {
self.0.verify(&pk.0)
}
}

impl fmt::Debug for ProofOfPossession {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
fmt.write_str(&TextFmt::encode(self))
}
}

impl ByteFmt for ProofOfPossession {
fn encode(&self) -> Vec<u8> {
ByteFmt::encode(&self.0)
}
fn decode(bytes: &[u8]) -> anyhow::Result<Self> {
ByteFmt::decode(bytes).map(Self)
}
}

impl TextFmt for ProofOfPossession {
fn encode(&self) -> String {
format!(
Expand All @@ -75,15 +87,3 @@ impl TextFmt for ProofOfPossession {
.map(Self)
}
}

impl fmt::Debug for ProofOfPossession {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
fmt.write_str(&TextFmt::encode(self))
}
}

impl fmt::Debug for Signature {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
fmt.write_str(&TextFmt::encode(self))
}
}
60 changes: 60 additions & 0 deletions node/libs/roles/src/validator/keys/tests.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
use super::*;
use crate::validator::MsgHash;
use rand::Rng as _;
use std::vec;
use zksync_concurrency::ctx;

#[test]
fn test_signature_verify() {
let ctx = ctx::test_root(&ctx::RealClock);
let rng = &mut ctx.rng();

let msg1: MsgHash = rng.gen();
let msg2: MsgHash = rng.gen();

let key1: SecretKey = rng.gen();
let key2: SecretKey = rng.gen();

let sig1 = key1.sign_hash(&msg1);

// Matching key and message.
sig1.verify_hash(&msg1, &key1.public()).unwrap();

// Mismatching message.
assert!(sig1.verify_hash(&msg2, &key1.public()).is_err());

// Mismatching key.
assert!(sig1.verify_hash(&msg1, &key2.public()).is_err());
}

#[test]
fn test_agg_signature_verify() {
let ctx = ctx::test_root(&ctx::RealClock);
let rng = &mut ctx.rng();

let msg1: MsgHash = rng.gen();
let msg2: MsgHash = rng.gen();

let key1: SecretKey = rng.gen();
let key2: SecretKey = rng.gen();

let sig1 = key1.sign_hash(&msg1);
let sig2 = key2.sign_hash(&msg2);

let agg_sig = AggregateSignature::aggregate(vec![&sig1, &sig2]);

// Matching key and message.
agg_sig
.verify_hash([(msg1, &key1.public()), (msg2, &key2.public())].into_iter())
.unwrap();

// Mismatching message.
assert!(agg_sig
.verify_hash([(msg2, &key1.public()), (msg1, &key2.public())].into_iter())
.is_err());

// Mismatching key.
assert!(agg_sig
.verify_hash([(msg1, &key2.public()), (msg2, &key1.public())].into_iter())
.is_err());
}
1 change: 1 addition & 0 deletions node/libs/roles/src/validator/messages/block.rs
Original file line number Diff line number Diff line change
Expand Up @@ -102,6 +102,7 @@ impl FinalBlock {
/// Creates a new finalized block.
pub fn new(payload: Payload, justification: CommitQC) -> Self {
assert_eq!(justification.header().payload, payload.hash());

Self {
payload,
justification,
Expand Down
3 changes: 2 additions & 1 deletion node/libs/roles/src/validator/messages/committee.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,8 @@ impl std::ops::Deref for Committee {
}

impl Committee {
/// Creates a new Committee from a list of validator public keys.
/// Creates a new Committee from a list of validator public keys. Note that the order of the given validators
/// is NOT preserved in the committee.
pub fn new(validators: impl IntoIterator<Item = WeightedValidator>) -> anyhow::Result<Self> {
let mut map = BTreeMap::new();
let mut total_weight: u64 = 0;
Expand Down
13 changes: 13 additions & 0 deletions node/libs/roles/src/validator/messages/consensus.rs
Original file line number Diff line number Diff line change
Expand Up @@ -114,6 +114,14 @@ impl View {
number: ViewNumber(self.number.0 + 1),
}
}

/// Decrements the view number.
pub fn prev(self) -> Option<Self> {
self.number.prev().map(|number| Self {
genesis: self.genesis,
number,
})
}
}

/// A struct that represents a view number.
Expand All @@ -125,6 +133,11 @@ impl ViewNumber {
pub fn next(self) -> Self {
Self(self.0 + 1)
}

/// Get the previous view number.
pub fn prev(self) -> Option<Self> {
self.0.checked_sub(1).map(Self)
}
}

impl fmt::Display for ViewNumber {
Expand Down
6 changes: 3 additions & 3 deletions node/libs/roles/src/validator/messages/genesis.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
//! Messages related to the consensus protocol.
use super::{BlockNumber, Committee, LeaderSelectionMode, ViewNumber};
use super::{BlockNumber, LeaderSelectionMode, ViewNumber};
use crate::{attester, validator};
use std::{fmt, hash::Hash};
use zksync_consensus_crypto::{keccak256::Keccak256, ByteFmt, Text, TextFmt};
Expand All @@ -17,7 +17,7 @@ pub struct GenesisRaw {
/// First block of a fork.
pub first_block: BlockNumber,
/// Set of validators of the chain.
pub validators: Committee,
pub validators: validator::Committee,
/// Set of attesters of the chain.
pub attesters: Option<attester::Committee>,
/// The mode used for selecting leader for a given view.
Expand All @@ -33,7 +33,7 @@ impl GenesisRaw {
}

/// Hash of the genesis specification.
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[derive(Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct GenesisHash(pub(crate) Keccak256);

impl TextFmt for GenesisHash {
Expand Down
4 changes: 2 additions & 2 deletions node/libs/roles/src/validator/messages/replica_commit.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ impl ReplicaCommit {
pub fn verify(&self, genesis: &Genesis) -> Result<(), ReplicaCommitVerifyError> {
self.view
.verify(genesis)
.map_err(ReplicaCommitVerifyError::View)?;
.map_err(ReplicaCommitVerifyError::BadView)?;

if self.proposal.number < genesis.first_block {
return Err(ReplicaCommitVerifyError::BadBlockNumber);
Expand All @@ -30,7 +30,7 @@ impl ReplicaCommit {
pub enum ReplicaCommitVerifyError {
/// Invalid view.
#[error("view: {0:#}")]
View(anyhow::Error),
BadView(anyhow::Error),
/// Bad block number.
#[error("block number < first block")]
BadBlockNumber,
Expand Down
Loading

0 comments on commit 1252631

Please sign in to comment.