Skip to content

Commit

Permalink
[crypto] Input and output hex with a 0x
Browse files Browse the repository at this point in the history
The 0x is optional for now as an input, but it will be outputted
with a 0x.
  • Loading branch information
gregnazario authored and aptos-bot committed Apr 14, 2022
1 parent eaf3c76 commit eddf1e9
Show file tree
Hide file tree
Showing 8 changed files with 35 additions and 24 deletions.
20 changes: 3 additions & 17 deletions config/management/operational/src/network_checker.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,10 +9,9 @@ use aptos_config::{
config::{RoleType, HANDSHAKE_VERSION},
network_id::{NetworkContext, NetworkId},
};
use aptos_crypto::{x25519, x25519::PRIVATE_KEY_SIZE};
use aptos_crypto::{x25519, x25519::PRIVATE_KEY_SIZE, ValidCryptoMaterialStringExt};
use aptos_management::error::Error;
use aptos_types::{account_address, chain_id::ChainId, network_address::NetworkAddress, PeerId};
use fallible::copy_from_slice::copy_slice_to_vec;
use futures::{AsyncReadExt, AsyncWriteExt};
use netcore::transport::tcp::{resolve_and_connect, TcpSocket};
use network::{
Expand Down Expand Up @@ -49,21 +48,8 @@ pub struct CheckEndpoint {
}

fn parse_private_key_hex(src: &str) -> Result<x25519::PrivateKey, Error> {
let input = src.trim();
if input.len() != 64 {
return Err(Error::CommandArgumentError(
"Invalid private key length, must be 64 hex characters".to_string(),
));
}

let value_slice = hex::decode(src.trim())
.map_err(|_| Error::CommandArgumentError(format!("Not a valid private key: {}", src)))?;

let mut value = [0; PRIVATE_KEY_SIZE];
copy_slice_to_vec(&value_slice, &mut value)
.map_err(|e| Error::CommandArgumentError(format!("{}", e)))?;

Ok(x25519::PrivateKey::from(value))
x25519::PrivateKey::from_encoded_string(src.trim())
.map_err(|err| Error::UnexpectedError(err.to_string()))
}

impl CheckEndpoint {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
# Seeds for failure cases proptest has generated in the past. It is
# automatically read and these particular cases re-run before any
# novel cases are generated.
#
# It is recommended to check this file in to source control so that
# everyone who runs the test benefits from these saved cases.
cc ec13da969415616146d63ef5719c1b85edeaf577302acaedf74a9d9a6a713947 # shrinks to keypair = 20c93f42f85ddd35b05921dd19579d8d8e6d7d83003a93f1b319c14ba831871284203ef96d6c355e386860f9fe4b0bff9df8254c5866025c594ce57674111597b693
7 changes: 7 additions & 0 deletions crates/aptos-crypto/proptest-regressions/validatable.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
# Seeds for failure cases proptest has generated in the past. It is
# automatically read and these particular cases re-run before any
# novel cases are generated.
#
# It is recommended to check this file in to source control so that
# everyone who runs the test benefits from these saved cases.
cc 77446f528abcb9c465e6aca665bd6b12fb222cf626f318f797e8c1da36ab1001 # shrinks to keypair = 20019122bb4967c043bfc03ec8978ebd6d3256569c4449d3fecd19ab6309636ae0208cc1429ae6353e776a76aaa23c09f188e901d24521544df0beddfe4b0bf09684
8 changes: 6 additions & 2 deletions crates/aptos-crypto/src/traits.rs
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ pub trait Length {
/// round-trip to bytes and corresponding [`TryFrom`][TryFrom].
pub trait ValidCryptoMaterial:
// The for<'a> exactly matches the assumption "deserializable from any lifetime".
for<'a> TryFrom<&'a [u8], Error = CryptoMaterialError> + Serialize + DeserializeOwned
for<'a> TryFrom<&'a [u8], Error=CryptoMaterialError> + Serialize + DeserializeOwned
{
/// Convert the valid crypto material to bytes.
fn to_bytes(&self) -> Vec<u8>;
Expand All @@ -74,16 +74,20 @@ pub trait ValidCryptoMaterialStringExt: ValidCryptoMaterial {
/// When trying to convert from bytes, we simply decode the string into
/// bytes before checking if we can convert.
fn from_encoded_string(encoded_str: &str) -> std::result::Result<Self, CryptoMaterialError> {
// Strip 0x at beginning if there is one
let encoded_str = encoded_str.strip_prefix("0x").unwrap_or(encoded_str);

let bytes_out = ::hex::decode(encoded_str);
// We defer to `try_from` to make sure we only produce valid crypto materials.
bytes_out
// We reinterpret a failure to serialize: key is mangled someway.
.or(Err(CryptoMaterialError::DeserializationError))
.and_then(|ref bytes| Self::try_from(bytes))
}

/// A function to encode into hex-string after serializing.
fn to_encoded_string(&self) -> Result<String> {
Ok(::hex::encode(&self.to_bytes()))
Ok(format!("0x{}", ::hex::encode(&self.to_bytes())))
}
}

Expand Down
4 changes: 2 additions & 2 deletions crates/aptos-crypto/src/unit_tests/ed25519_test.rs
Original file line number Diff line number Diff line change
Expand Up @@ -289,14 +289,14 @@ proptest! {
{
let encoded = keypair.private_key.to_encoded_string().unwrap();
// Hex encoding of a 32-bytes key is 64 (2 x 32) characters.
prop_assert_eq!(2 * ED25519_PRIVATE_KEY_LENGTH, encoded.len());
prop_assert_eq!(2 + 2 * ED25519_PRIVATE_KEY_LENGTH, encoded.len());
let decoded = Ed25519PrivateKey::from_encoded_string(&encoded);
prop_assert_eq!(Some(keypair.private_key), decoded.ok());
}
{
let encoded = keypair.public_key.to_encoded_string().unwrap();
// Hex encoding of a 32-bytes key is 64 (2 x 32) characters.
prop_assert_eq!(2 * ED25519_PUBLIC_KEY_LENGTH, encoded.len());
prop_assert_eq!(2 + 2 * ED25519_PUBLIC_KEY_LENGTH, encoded.len());
let decoded = Ed25519PublicKey::from_encoded_string(&encoded);
prop_assert_eq!(Some(keypair.public_key), decoded.ok());
}
Expand Down
4 changes: 2 additions & 2 deletions crates/aptos-crypto/src/validatable.rs
Original file line number Diff line number Diff line change
Expand Up @@ -158,7 +158,7 @@ impl Serialize for UnvalidatedEd25519PublicKey {
{
if serializer.is_human_readable() {
let encoded = ::hex::encode(&self.0);
serializer.serialize_str(&encoded)
serializer.serialize_str(&format!("0x{}", encoded))
} else {
// See comment in deserialize_key.
serializer.serialize_newtype_struct(
Expand All @@ -178,7 +178,7 @@ impl<'de> Deserialize<'de> for UnvalidatedEd25519PublicKey {

if deserializer.is_human_readable() {
let encoded_key = <String>::deserialize(deserializer)?;
let bytes_out = ::hex::decode(encoded_key).map_err(D::Error::custom)?;
let bytes_out = ::hex::decode(&encoded_key[2..]).map_err(D::Error::custom)?;
<[u8; ED25519_PUBLIC_KEY_LENGTH]>::try_from(bytes_out.as_ref())
.map(UnvalidatedEd25519PublicKey)
.map_err(D::Error::custom)
Expand Down
7 changes: 7 additions & 0 deletions types/proptest-regressions/network_address/mod.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
# Seeds for failure cases proptest has generated in the past. It is
# automatically read and these particular cases re-run before any
# novel cases are generated.
#
# It is recommended to check this file in to source control so that
# everyone who runs the test benefits from these saved cases.
cc 303a538188114d3113f334b60ca203fbff751bc975dc6a79148e03a454ef2374 # shrinks to addr = /ln-noise-ik/0x[00000000000000000000000000000000, 00000000000000000000000000000000, 00000000000000000000000000000000, 00000000000000000000000000000000, 00000000000000000000000000000000, 00000000000000000000000000000000, 00000000000000000000000000000000, 00000000000000000000000000000000, 00000000000000000000000000000000, 00000000000000000000000000000000, 00000000000000000000000000000000, 00000000000000000000000000000000, 00000000000000000000000000000000, 00000000000000000000000000000000, 00000000000000000000000000000000, 00000000000000000000000000000000, 00000000000000000000000000000000, 00000000000000000000000000000000, 00000000000000000000000000000000, 00000000000000000000000000000000, 00000000000000000000000000000000, 00000000000000000000000000000000, 00000000000000000000000000000000, 00000000000000000000000000000000, 00000000000000000000000000000000, 00000000000000000000000000000000, 00000000000000000000000000000000, 00000000000000000000000000000000, 00000000000000000000000000000000, 00000000000000000000000000000000, 00000000000000000000000000000000, 00000000000000000000000000000000]
2 changes: 1 addition & 1 deletion types/src/network_address/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -228,7 +228,7 @@ impl NetworkAddress {
/// let addr = addr.append_prod_protos(pubkey, 0);
/// assert_eq!(
/// addr.to_string(),
/// "/dns/example.com/tcp/6180/ln-noise-ik/080e287879c918794170e258bfaddd75acac5b3e350419044655e4983a487120/ln-handshake/0",
/// "/dns/example.com/tcp/6180/ln-noise-ik/0x080e287879c918794170e258bfaddd75acac5b3e350419044655e4983a487120/ln-handshake/0",
/// );
/// ```
// TODO(philiphayes): use handshake version enum
Expand Down

0 comments on commit eddf1e9

Please sign in to comment.