Skip to content

Commit

Permalink
Merge pull request #485 from Concordium/impl-fromstr-display-prf-key
Browse files Browse the repository at this point in the history
Add FromStr and Display impls for PRF keys
  • Loading branch information
abizjak authored Jan 2, 2024
2 parents de1bacd + f3bead2 commit 63730ca
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 1 deletion.
2 changes: 2 additions & 0 deletions rust-src/concordium_base/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@
- Support `P7` protocol version.
- The `Debug` implementation for `ContractEvent` displays the value in `hex`.
The alternate formatter (using `#`) displays it as a list of bytes.
- Add `FromStr` and `Display` instances to `dodis_yampolskiy_prf::SecretKey`.
- Change `Debug` instance of `dodis_yampolskiy_prf::SecretKey` to hide the value.

## 3.2.0 (2023-11-22)

Expand Down
32 changes: 31 additions & 1 deletion rust-src/concordium_base/src/dodis_yampolskiy_prf/secret.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ use rand::*;
use std::rc::Rc;

/// A PRF key.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, SerdeBase16Serialize)]
#[derive(Clone, PartialEq, Eq, Serialize, SerdeBase16Serialize)]
pub struct SecretKey<C: Curve>(Rc<Secret<C::Scalar>>);

/// This trait allows automatic conversion of `&SecretKey<C>` to `&C::Scalar`.
Expand Down Expand Up @@ -74,6 +74,36 @@ impl<C: Curve> SecretKey<C> {
}
}

impl<C: Curve> std::fmt::Display for SecretKey<C> {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
write!(f, "<Dodis Yampolskiy SecretKey>")
}
}

impl<C: Curve> std::fmt::Debug for SecretKey<C> {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
write!(f, "<Dodis Yampolskiy SecretKey>")
}
}

#[derive(Debug, thiserror::Error)]
pub enum SecretKeyFromStrError {
#[error("Invalid secret key: {0}")]
InvalidKey(#[from] anyhow::Error),
#[error("Invalid hex string: {0}")]
InvalidHex(#[from] hex::FromHexError),
}

impl<C: Curve> std::str::FromStr for SecretKey<C> {
type Err = SecretKeyFromStrError;

fn from_str(s: &str) -> Result<Self, Self::Err> {
let mut bytes = std::io::Cursor::new(hex::decode(s)?);
let key = from_bytes(&mut bytes)?;
Ok(key)
}
}

#[cfg(test)]
mod tests {
use super::*;
Expand Down

0 comments on commit 63730ca

Please sign in to comment.