Skip to content

Commit

Permalink
refactor(crypto): impl FromStr instead of TryFrom<&str> for near_cryp…
Browse files Browse the repository at this point in the history
…to::Signature and CryptoHash (#4151)

I keep refactoring traits usage in near-crypto. `FromStr` is what is used whenever someone wants to parse strings into a structure. I need `near_crypto::Signature` to be parsable in order to use it with clap (CLI parsing).
  • Loading branch information
frol authored Mar 23, 2021
1 parent cfc5a27 commit f4636e0
Show file tree
Hide file tree
Showing 9 changed files with 144 additions and 95 deletions.
4 changes: 2 additions & 2 deletions chain/client/tests/process_blocks.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
use std::collections::HashSet;
use std::convert::TryFrom;
use std::iter::FromIterator;
use std::path::Path;
use std::str::FromStr;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::{Arc, RwLock};

Expand Down Expand Up @@ -1802,7 +1802,7 @@ fn test_sync_hash_validity() {
assert!(!res.unwrap())
}
}
let bad_hash = CryptoHash::try_from("7tkzFg8RHBmMw1ncRJZCCZAizgq4rwCftTKYLce8RU8t").unwrap();
let bad_hash = CryptoHash::from_str("7tkzFg8RHBmMw1ncRJZCCZAizgq4rwCftTKYLce8RU8t").unwrap();
let res = env.clients[0].chain.check_sync_hash_validity(&bad_hash);
println!("bad hash -> {:?}", res.is_ok());
match res {
Expand Down
8 changes: 4 additions & 4 deletions chain/jsonrpc/tests/rpc_query.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use std::convert::TryFrom;
use std::str::FromStr;

use actix::{Actor, System};
use futures::{future, FutureExt};
Expand Down Expand Up @@ -32,7 +32,7 @@ fn test_block_by_id_height() {
assert_eq!(block.header.prev_hash.0.as_ref(), &[0; 32]);
assert_eq!(
block.header.prev_state_root,
CryptoHash::try_from("7tkzFg8RHBmMw1ncRJZCCZAizgq4rwCftTKYLce8RU8t").unwrap()
CryptoHash::from_str("7tkzFg8RHBmMw1ncRJZCCZAizgq4rwCftTKYLce8RU8t").unwrap()
);
assert!(block.header.timestamp > 0);
assert_eq!(block.header.validator_proposals.len(), 0);
Expand Down Expand Up @@ -77,7 +77,7 @@ fn test_block_query() {
assert_eq!(block.header.prev_hash.as_ref(), &[0; 32]);
assert_eq!(
block.header.prev_state_root,
CryptoHash::try_from("7tkzFg8RHBmMw1ncRJZCCZAizgq4rwCftTKYLce8RU8t").unwrap()
CryptoHash::from_str("7tkzFg8RHBmMw1ncRJZCCZAizgq4rwCftTKYLce8RU8t").unwrap()
);
assert!(block.header.timestamp > 0);
assert_eq!(block.header.validator_proposals.len(), 0);
Expand Down Expand Up @@ -669,7 +669,7 @@ fn test_validators_non_existing_block_hash() {
test_with_client!(test_utils::NodeType::NonValidator, client, async move {
let validators_response = client
.validators(Some(near_primitives::types::BlockId::Hash(
near_primitives::hash::CryptoHash::try_from(
near_primitives::hash::CryptoHash::from_str(
"123PXBoQKnTnARA49ctEzAiradrAAAEtLRCJGpjH24qC",
)
.unwrap(),
Expand Down
2 changes: 1 addition & 1 deletion chain/rosetta-rpc/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -642,7 +642,7 @@ async fn construction_payloads(
let models::ConstructionMetadata { recent_block_hash, signer_public_access_key_nonce } =
metadata;
let unsigned_transaction = near_primitives::transaction::Transaction {
block_hash: recent_block_hash.try_into().map_err(|err| {
block_hash: recent_block_hash.parse().map_err(|err| {
errors::ErrorKind::InvalidInput(format!(
"block hash could not be parsed due to: {:?}",
err
Expand Down
4 changes: 2 additions & 2 deletions chain/rosetta-rpc/src/models.rs
Original file line number Diff line number Diff line change
Expand Up @@ -868,7 +868,7 @@ impl TryFrom<PartialBlockIdentifier> for near_primitives::types::BlockReference
.into()
}
(_, Some(hash)) => {
near_primitives::types::BlockId::Hash(hash.try_into().map_err(|err| {
near_primitives::types::BlockId::Hash(hash.parse().map_err(|err| {
Self::Error::InvalidInput(format!("Failed to parse Block Hash: {}", err))
})?)
.into()
Expand Down Expand Up @@ -1022,7 +1022,7 @@ impl From<&near_crypto::PublicKey> for PublicKey {
}

impl TryFrom<&PublicKey> for near_crypto::PublicKey {
type Error = near_crypto::TryFromSliceError;
type Error = near_crypto::ParseKeyError;

fn try_from(PublicKey { curve_type, hex_bytes }: &PublicKey) -> Result<Self, Self::Error> {
Ok(match curve_type {
Expand Down
51 changes: 39 additions & 12 deletions core/crypto/src/errors.rs
Original file line number Diff line number Diff line change
@@ -1,18 +1,45 @@
#[derive(Debug, Copy, Clone)]
pub struct TryFromSliceError(pub(crate) ());

#[derive(Debug, Clone, thiserror::Error)]
pub enum ParseSignatureError {
#[error("invalid signature data: {0}")]
InvalidData(String),
pub enum ParseKeyTypeError {
#[error("unknown key type '{unknown_key_type}'")]
UnknownKeyType { unknown_key_type: String },
}

#[derive(Debug, Clone, thiserror::Error)]
pub enum ParseKeyError {
#[error("unknown curve kind: {0}")]
UnknownCurve(String),
#[error("invalid key length: {0}")]
InvalidLength(usize),
#[error("invalid key data: {0}")]
InvalidData(String),
#[error("unknown key type '{unknown_key_type}'")]
UnknownKeyType { unknown_key_type: String },
#[error("invalid key length: expected the input of {expected_length} bytes, but {received_length} was given")]
InvalidLength { expected_length: usize, received_length: usize },
#[error("invalid key data: {error_message}")]
InvalidData { error_message: String },
}

impl From<ParseKeyTypeError> for ParseKeyError {
fn from(err: ParseKeyTypeError) -> Self {
match err {
ParseKeyTypeError::UnknownKeyType { unknown_key_type } => {
Self::UnknownKeyType { unknown_key_type }
}
}
}
}

#[derive(Debug, Clone, thiserror::Error)]
pub enum ParseSignatureError {
#[error("unknown key type '{unknown_key_type}'")]
UnknownKeyType { unknown_key_type: String },
#[error("invalid signature length: expected the input of {expected_length} bytes, but {received_length} was given")]
InvalidLength { expected_length: usize, received_length: usize },
#[error("invalid signature data: {error_message}")]
InvalidData { error_message: String },
}

impl From<ParseKeyTypeError> for ParseSignatureError {
fn from(err: ParseKeyTypeError) -> Self {
match err {
ParseKeyTypeError::UnknownKeyType { unknown_key_type } => {
Self::UnknownKeyType { unknown_key_type }
}
}
}
}
2 changes: 1 addition & 1 deletion core/crypto/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
pub use errors::{ParseKeyError, ParseSignatureError, TryFromSliceError};
pub use errors::{ParseKeyError, ParseKeyTypeError, ParseSignatureError};
pub use key_file::KeyFile;
pub use signature::{
ED25519PublicKey, KeyType, PublicKey, Secp256K1PublicKey, SecretKey, Signature,
Expand Down
Loading

0 comments on commit f4636e0

Please sign in to comment.