Skip to content

Commit

Permalink
Implement Hash trait for VerifyingKey
Browse files Browse the repository at this point in the history
  • Loading branch information
returntoreality committed Jan 15, 2023
1 parent b5dc40b commit d55cc35
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 1 deletion.
15 changes: 14 additions & 1 deletion src/verifying.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@

use core::convert::TryFrom;
use core::fmt::Debug;
use core::hash::{Hash, Hasher};

use curve25519_dalek::digest::generic_array::typenum::U64;
use curve25519_dalek::digest::Digest;
Expand Down Expand Up @@ -39,7 +40,7 @@ use crate::signing::*;

/// An ed25519 public key.
// Invariant: VerifyingKey.1 is always the decompression of VerifyingKey.0
#[derive(Copy, Clone, Default, Eq, PartialEq)]
#[derive(Copy, Clone, Default, Eq)]
pub struct VerifyingKey(pub(crate) CompressedEdwardsY, pub(crate) EdwardsPoint);

impl Debug for VerifyingKey {
Expand All @@ -54,6 +55,18 @@ impl AsRef<[u8]> for VerifyingKey {
}
}

impl Hash for VerifyingKey {
fn hash<H: Hasher>(&self, state: &mut H) {
self.as_bytes().hash(state);
}
}

impl PartialEq<VerifyingKey> for VerifyingKey {
fn eq(&self, other: &VerifyingKey) -> bool {
self.as_bytes() == other.as_bytes()
}
}

impl From<&ExpandedSecretKey> for VerifyingKey {
/// Derive this public key from its corresponding `ExpandedSecretKey`.
fn from(expanded_secret_key: &ExpandedSecretKey) -> VerifyingKey {
Expand Down
28 changes: 28 additions & 0 deletions tests/ed25519.rs
Original file line number Diff line number Diff line change
Expand Up @@ -285,6 +285,7 @@ mod vectors {
mod integrations {
use super::*;
use rand::rngs::OsRng;
use std::collections::HashMap;

#[test]
fn sign_verify() {
Expand Down Expand Up @@ -429,6 +430,33 @@ mod integrations {

assert!(result.is_ok());
}

#[test]
fn public_key_hash_trait_check() {
let mut csprng = OsRng {};
let secret: SigningKey = SigningKey::generate(&mut csprng);
let public_from_secret: VerifyingKey = (&secret).into();

let mut m = HashMap::new();
m.insert(public_from_secret, "Example_Public_Key");

m.insert(public_from_secret, "Updated Value");

let (k, v) = m.get_key_value(&public_from_secret).unwrap();
assert_eq!(k, &public_from_secret);
assert_eq!(v.clone(), "Updated Value");
assert_eq!(m.len(), 1usize);

let second_secret: SigningKey = SigningKey::generate(&mut csprng);
let public_from_second_secret: VerifyingKey = (&second_secret).into();
assert_ne!(public_from_secret, public_from_second_secret);
m.insert(public_from_second_secret, "Second public key");

let (k, v) = m.get_key_value(&public_from_second_secret).unwrap();
assert_eq!(k, &public_from_second_secret);
assert_eq!(v.clone(), "Second public key");
assert_eq!(m.len(), 2usize);
}
}

#[cfg(all(test, feature = "serde"))]
Expand Down

0 comments on commit d55cc35

Please sign in to comment.