Skip to content

Commit

Permalink
change hashvalue and account address
Browse files Browse the repository at this point in the history
  • Loading branch information
nanne007 authored and guangyuz committed Nov 16, 2020
1 parent d84ee38 commit 523b226
Show file tree
Hide file tree
Showing 4 changed files with 44 additions and 35 deletions.
5 changes: 2 additions & 3 deletions crypto/crypto-derive/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -154,8 +154,7 @@ pub fn deserialize_key(source: TokenStream) -> TokenStream {
{
if deserializer.is_human_readable() {
let encoded_key = <String>::deserialize(deserializer)?;
let encoded_key = encoded_key.strip_prefix("0x").unwrap_or(encoded_key.as_str());
ValidCryptoMaterialStringExt::from_encoded_string(encoded_key)
ValidCryptoMaterialStringExt::from_encoded_string(encoded_key.as_str())
.map_err(<D::Error as ::serde::de::Error>::custom)
} else {
// In order to preserve the Serde data model and help analysis tools,
Expand Down Expand Up @@ -191,7 +190,7 @@ pub fn serialize_key(source: TokenStream) -> TokenStream {
if serializer.is_human_readable() {
self.to_encoded_string()
.map_err(<S::Error as ::serde::ser::Error>::custom)
.and_then(|str| serializer.serialize_str(&format!("0x{}", &str[..])))
.and_then(|str| serializer.serialize_str(&str[..]))
} else {
// See comment in deserialize_key.
serializer.serialize_newtype_struct(
Expand Down
41 changes: 25 additions & 16 deletions crypto/crypto/src/hash.rs
Original file line number Diff line number Diff line change
Expand Up @@ -276,15 +276,15 @@ impl HashValue {

/// Parse a given hex string to a hash value
pub fn from_hex_literal(literal: &str) -> Result<Self> {
ensure!(literal.starts_with("0x"), "literal must start with 0x.");
let hex_len = literal.len() - 2;
let literal = literal.strip_prefix("0x").unwrap_or_else(|| literal);
let hex_len = literal.len();
let mut result = if hex_len % 2 != 0 {
let mut hex_str = String::with_capacity(hex_len + 1);
hex_str.push('0');
hex_str.push_str(&literal[2..]);
hex_str.push_str(literal);
hex::decode(&hex_str)?
} else {
hex::decode(&literal[2..])?
hex::decode(literal)?
};

let len = result.len();
Expand All @@ -308,7 +308,7 @@ impl ser::Serialize for HashValue {
S: ser::Serializer,
{
if serializer.is_human_readable() {
serializer.serialize_str(&format!("0x{}", self.to_hex()))
serializer.serialize_str(&self.to_string())
} else {
// In order to preserve the Serde data model and help analysis tools,
// make sure to wrap our value in a container with the same name
Expand All @@ -326,7 +326,7 @@ impl<'de> de::Deserialize<'de> for HashValue {
{
if deserializer.is_human_readable() {
let encoded_hash = <String>::deserialize(deserializer)?;
HashValue::from_hex_literal(encoded_hash.as_str())
HashValue::from_str(encoded_hash.as_str())
.map_err(<D::Error as ::serde::de::Error>::custom)
} else {
// See comment in serialize.
Expand Down Expand Up @@ -380,20 +380,13 @@ impl fmt::LowerHex for HashValue {

impl fmt::Debug for HashValue {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "HashValue(")?;
<Self as fmt::LowerHex>::fmt(self, f)?;
write!(f, ")")?;
Ok(())
write!(f, "HashValue(0x{:#x})", self)
}
}

/// Will print shortened (4 bytes) hash
impl fmt::Display for HashValue {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
for byte in self.hash.iter().take(4) {
write!(f, "{:02x}", byte)?;
}
Ok(())
write!(f, "0x{:#x}", self)
}
}

Expand All @@ -407,7 +400,7 @@ impl FromStr for HashValue {
type Err = Error;

fn from_str(s: &str) -> Result<Self> {
HashValue::from_hex(s)
HashValue::from_hex_literal(s)
}
}

Expand Down Expand Up @@ -683,3 +676,19 @@ impl<T: ser::Serialize + ?Sized> TestOnlyHash for T {
hasher.finish()
}
}

#[cfg(test)]
mod tests {
use crate::HashValue;

#[test]
fn test_serialize() {
let hash = HashValue::random();

let json_value = serde_json::to_string(&hash).unwrap();
println!("{}", json_value);
assert_eq!(json_value, format!("\"{}\"", hash.to_string()));
let de_hash = serde_json::from_slice::<HashValue>(json_value.as_bytes()).unwrap();
assert_eq!(hash, de_hash);
}
}
5 changes: 4 additions & 1 deletion crypto/crypto/src/traits.rs
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,9 @@ 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> {
let encoded_str = encoded_str
.strip_prefix("0x")
.unwrap_or_else(|| 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
Expand All @@ -83,7 +86,7 @@ pub trait ValidCryptoMaterialStringExt: ValidCryptoMaterial {
}
/// 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
28 changes: 13 additions & 15 deletions language/move-core/types/src/account_address.rs
Original file line number Diff line number Diff line change
Expand Up @@ -63,16 +63,15 @@ impl AccountAddress {
}

pub fn from_hex_literal(literal: &str) -> Result<Self> {
ensure!(literal.starts_with("0x"), "literal must start with 0x.");

let hex_len = literal.len() - 2;
let literal = literal.strip_prefix("0x").unwrap_or_else(|| literal);
let hex_len = literal.len();
let mut result = if hex_len % 2 != 0 {
let mut hex_str = String::with_capacity(hex_len + 1);
hex_str.push('0');
hex_str.push_str(&literal[2..]);
hex_str.push_str(literal);
hex::decode(&hex_str)?
} else {
hex::decode(&literal[2..])?
hex::decode(literal)?
};

let len = result.len();
Expand Down Expand Up @@ -120,15 +119,15 @@ impl AsRef<[u8]> for AccountAddress {

impl fmt::Display for AccountAddress {
fn fmt(&self, f: &mut fmt::Formatter) -> std::fmt::Result {
// Forward to the UpperHex impl with a "0x" prepended (the # flag).
write!(f, "{:#X}", self)
// Forward to the LowerHex impl with a "0x" prepended (the # flag).
write!(f, "0x{:#x}", self)
}
}

impl fmt::Debug for AccountAddress {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
// Forward to the UpperHex impl with a "0x" prepended (the # flag).
write!(f, "{:#X}", self)
// Forward to the LowerHex impl with a "0x" prepended (the # flag).
write!(f, "0x{:#x}", self)
}
}

Expand Down Expand Up @@ -212,17 +211,15 @@ impl TryFrom<String> for AccountAddress {
type Error = Error;

fn try_from(s: String) -> Result<AccountAddress> {
let bytes_out = ::hex::decode(s)?;
AccountAddress::try_from(bytes_out.as_slice())
AccountAddress::from_str(s.as_str())
}
}

impl FromStr for AccountAddress {
type Err = Error;

fn from_str(s: &str) -> Result<Self> {
let bytes_out = ::hex::decode(s)?;
AccountAddress::try_from(bytes_out.as_slice())
AccountAddress::from_hex_literal(s)
}
}

Expand All @@ -233,7 +230,7 @@ impl<'de> Deserialize<'de> for AccountAddress {
{
if deserializer.is_human_readable() {
let s = <String>::deserialize(deserializer)?;
AccountAddress::from_hex_literal(&s).map_err(D::Error::custom)
AccountAddress::from_str(&s).map_err(D::Error::custom)
} else {
// In order to preserve the Serde data model and help analysis tools,
// make sure to wrap our value in a container with the same name
Expand All @@ -254,7 +251,7 @@ impl Serialize for AccountAddress {
S: Serializer,
{
if serializer.is_human_readable() {
format!("0x{:#x}", self).serialize(serializer)
self.to_string().serialize(serializer)
} else {
// See comment in deserialize.
serializer.serialize_newtype_struct("AccountAddress", &self.0)
Expand All @@ -274,6 +271,7 @@ mod tests {

let json_value = serde_json::to_string(&addr).unwrap();
println!("{}", json_value);
assert_eq!(json_value, format!("\"{}\"", addr.to_string()));
let de_addr = serde_json::from_slice::<AccountAddress>(json_value.as_bytes()).unwrap();
assert_eq!(addr, de_addr);
}
Expand Down

0 comments on commit 523b226

Please sign in to comment.