Skip to content

Commit

Permalink
fromStr for private and public keys
Browse files Browse the repository at this point in the history
  • Loading branch information
bodrych committed Dec 8, 2023
1 parent 11b6cdf commit cd7590f
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 0 deletions.
21 changes: 21 additions & 0 deletions src/model/account/private_key.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,16 @@ pub struct PrivateKey {
public_key: PublicKey,
}

impl std::str::FromStr for PrivateKey {
type Err = Error;

fn from_str(base58string: &str) -> Result<PrivateKey> {
let bytes = Base58::decode(base58string)?;
let bytes_array: [u8; 32] = bytes.try_into()?;
PrivateKey::from_bytes(bytes_array)
}
}

impl PrivateKey {
pub fn from_seed(seed_phrase: &str, nonce: u8) -> Result<Self> {
let hash_seed = Crypto::get_account_seed(seed_phrase.as_bytes(), nonce)?;
Expand Down Expand Up @@ -79,6 +89,8 @@ impl PrivateKey {

#[cfg(test)]
mod tests {
use std::str::FromStr;

use crate::error::Error::InvalidBytesLength;
use crate::error::Result;
use crate::model::account::PrivateKey;
Expand Down Expand Up @@ -149,4 +161,13 @@ mod tests {
assert_eq!(private_key.bytes(), [0_u8; 32]);
Ok(())
}

#[test]
fn test_private_key_std_from_str() -> Result<()> {
let seed_phrase = "blame vacant regret company chase trip grant funny brisk innocent";
let private_key_from_seed = PrivateKey::from_seed(seed_phrase, 0)?;
let private_key_from_str = PrivateKey::from_str(&private_key_from_seed.encoded())?;
assert_eq!(private_key_from_seed.bytes(), private_key_from_str.bytes());
Ok(())
}
}
19 changes: 19 additions & 0 deletions src/model/account/public_key.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,15 @@ impl fmt::Debug for PublicKey {
}
}

impl std::str::FromStr for PublicKey {
type Err = Error;

fn from_str(base58string: &str) -> Result<PublicKey> {
let bytes = Base58::decode(base58string)?;
Ok(PublicKey { bytes })
}
}

impl PublicKey {
pub fn from_bytes(bytes: &[u8]) -> Result<PublicKey> {
if bytes.len() != 32 {
Expand Down Expand Up @@ -71,6 +80,8 @@ impl TryFrom<String> for PublicKey {

#[cfg(test)]
mod tests {
use std::str::FromStr;

use crate::error::Error::InvalidBytesLength;
use crate::error::Result;
use crate::model::account::{PrivateKey, PublicKey};
Expand Down Expand Up @@ -136,6 +147,14 @@ mod tests {
Ok(())
}

#[test]
fn test_public_key_std_from_str() -> Result<()> {
let expected_string = "8cj6YzvQPhSHGvnjupNTW8zrADTT8CMAAd2xTuej84gB".to_owned();
let public_key = PublicKey::from_str(&expected_string)?;
assert_eq!(expected_string, public_key.encoded());
Ok(())
}

#[test]
fn test_byte_string_for_public_key() -> Result<()> {
let public_key: PublicKey = "8cj6YzvQPhSHGvnjupNTW8zrADTT8CMAAd2xTuej84gB".try_into()?;
Expand Down

0 comments on commit cd7590f

Please sign in to comment.