diff --git a/core/api/src/jsonrpc/impl/node.rs b/core/api/src/jsonrpc/impl/node.rs index 81f76a792..a48adc850 100644 --- a/core/api/src/jsonrpc/impl/node.rs +++ b/core/api/src/jsonrpc/impl/node.rs @@ -2,8 +2,6 @@ use std::path::PathBuf; use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::Arc; -use jsonrpsee::core::Error; - use core_consensus::SYNC_STATUS; use protocol::lazy::CHAIN_ID; use protocol::types::{Hash, Hasher, Hex, H160, H256, U256}; @@ -116,9 +114,7 @@ impl AxonNodeRpcServer for NodeRpcImpl { } fn sha3(&self, data: Hex) -> RpcResult { - let decode_data = - Hex::decode(data.as_string()).map_err(|e| Error::Custom(e.to_string()))?; - Ok(Hasher::digest(decode_data.as_ref())) + Ok(Hasher::digest(data.as_ref())) } } diff --git a/core/api/src/jsonrpc/web3_types.rs b/core/api/src/jsonrpc/web3_types.rs index 07b9898ab..b69d363e4 100644 --- a/core/api/src/jsonrpc/web3_types.rs +++ b/core/api/src/jsonrpc/web3_types.rs @@ -1,4 +1,4 @@ -use std::fmt; +use std::{fmt, str::FromStr}; use either::Either; use serde::de::{Error, MapAccess, Visitor}; @@ -455,13 +455,13 @@ impl<'a> Visitor<'a> for BlockIdVisitor { } "blockHash" => { let value: String = visitor.next_value()?; - let raw_value = Hex::decode(value.clone()) + let raw_value = Hex::from_str(&value) .map_err(|e| Error::custom(format!("Invalid hex code: {}", e)))?; if raw_value.len() != 32 { return Err(Error::custom(format!("Invalid block hash: {}", value))); } else { let mut v = [0u8; 32]; - v.copy_from_slice(&raw_value); + v.copy_from_slice(raw_value.as_ref()); block_hash = Some(v.into()); break; } @@ -899,7 +899,7 @@ mod tests { #[test] fn test_web3_transaction_json() { // https://etherscan.io/getRawTx?tx=0x07c7388b03ab8403deeaefc551efbc632f8531f04dc9993a274dbba9bbb98cbf - let tx = Hex::decode("0x02f902f801728405f5e1008509898edcf78302ffb8943fc91a3afd70395cd496c647d5a6cc9d4b2b7fad8802c68af0bb140000b902843593564c000000000000000000000000000000000000000000000000000000000000006000000000000000000000000000000000000000000000000000000000000000a0000000000000000000000000000000000000000000000000000000006480c64700000000000000000000000000000000000000000000000000000000000000020b080000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000002000000000000000000000000000000000000000000000000000000000000004000000000000000000000000000000000000000000000000000000000000000a00000000000000000000000000000000000000000000000000000000000000040000000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000002c68af0bb1400000000000000000000000000000000000000000000000000000000000000000100000000000000000000000000000000000000000000000000000000000000000100000000000000000000000000000000000000000000000002c68af0bb1400000000000000000000000000000000000000000004a715ce36374beaa635218d9700000000000000000000000000000000000000000000000000000000000000a000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000002000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc2000000000000000000000000c3681a720605bd6f8fe9a2fabff6a7cdecdc605dc080a0d253ee687ab2d9734a5073d64a0ba26bc3bc1cf4582005137bba05ef88616ea89e8ba79925267b17403fdf3ab47641b4aa52322dc385429cc92a7003c5d7c2".into()).unwrap(); + let tx = Hex::from_str("0x02f902f801728405f5e1008509898edcf78302ffb8943fc91a3afd70395cd496c647d5a6cc9d4b2b7fad8802c68af0bb140000b902843593564c000000000000000000000000000000000000000000000000000000000000006000000000000000000000000000000000000000000000000000000000000000a0000000000000000000000000000000000000000000000000000000006480c64700000000000000000000000000000000000000000000000000000000000000020b080000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000002000000000000000000000000000000000000000000000000000000000000004000000000000000000000000000000000000000000000000000000000000000a00000000000000000000000000000000000000000000000000000000000000040000000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000002c68af0bb1400000000000000000000000000000000000000000000000000000000000000000100000000000000000000000000000000000000000000000000000000000000000100000000000000000000000000000000000000000000000002c68af0bb1400000000000000000000000000000000000000000004a715ce36374beaa635218d9700000000000000000000000000000000000000000000000000000000000000a000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000002000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc2000000000000000000000000c3681a720605bd6f8fe9a2fabff6a7cdecdc605dc080a0d253ee687ab2d9734a5073d64a0ba26bc3bc1cf4582005137bba05ef88616ea89e8ba79925267b17403fdf3ab47641b4aa52322dc385429cc92a7003c5d7c2").unwrap(); let tx = UnverifiedTransaction::decode(tx).unwrap(); let tx = SignedTransaction::from_unverified(tx, None).unwrap(); let tx_json = serde_json::to_value(Web3Transaction::from(tx)).unwrap(); diff --git a/core/consensus/src/tests/mod.rs b/core/consensus/src/tests/mod.rs index bca3bf3b1..fd3aea22a 100644 --- a/core/consensus/src/tests/mod.rs +++ b/core/consensus/src/tests/mod.rs @@ -90,10 +90,7 @@ fn _get_random_bytes(len: usize) -> Bytes { } fn _mock_pub_key() -> Hex { - Hex::from_string( - "0x026c184a9016f6f71a234c86b141621f38b68c78602ab06768db4d83682c616004".to_owned(), - ) - .unwrap() + Hex::from_str("0x026c184a9016f6f71a234c86b141621f38b68c78602ab06768db4d83682c616004").unwrap() } fn _mock_validators(len: usize) -> Vec { diff --git a/core/consensus/src/util.rs b/core/consensus/src/util.rs index 1a4bdcedb..9364b2d0c 100644 --- a/core/consensus/src/util.rs +++ b/core/consensus/src/util.rs @@ -189,6 +189,8 @@ pub fn convert_hex_to_bls_pubkeys(hex: Hex) -> ProtocolResult { #[cfg(test)] mod tests { + use std::str::FromStr; + use super::*; use protocol::codec::hex_decode; @@ -253,8 +255,6 @@ mod tests { #[test] fn test_convert_from_hex() { let hex_str = "0xa694f4e48a5a173b61731998f8f1204342dc5c8eb1e32cdae37415c20d11ae035ddac4a39f105e9c2d4d3691024d385d"; - assert!( - convert_hex_to_bls_pubkeys(Hex::from_string(String::from(hex_str)).unwrap()).is_ok() - ); + assert!(convert_hex_to_bls_pubkeys(Hex::from_str(hex_str).unwrap()).is_ok()); } } diff --git a/protocol/src/codec/mod.rs b/protocol/src/codec/mod.rs index b9ca08462..e312d9db7 100644 --- a/protocol/src/codec/mod.rs +++ b/protocol/src/codec/mod.rs @@ -4,13 +4,15 @@ pub mod executor; pub mod receipt; pub mod transaction; +use std::str::FromStr; + pub use transaction::truncate_slice; use ethers_core::utils::parse_checksummed; use rlp::{Decodable, DecoderError, Encodable, Rlp, RlpStream}; use serde::{Deserialize as _, Deserializer, Serializer}; -use crate::types::{Address, Bytes, DBBytes, Hex, Key256Bits, TypesError, H160, U256}; +use crate::types::{Address, Bytes, DBBytes, Hex, Key256Bits, TypesError, H160, U256, HEX_PREFIX}; use crate::ProtocolResult; static CHARS: &[u8] = b"0123456789abcdef"; @@ -63,7 +65,9 @@ impl Encodable for Hex { impl Decodable for Hex { fn decode(r: &Rlp) -> Result { - Hex::from_string(r.val_at(0)?).map_err(|_| DecoderError::Custom("hex check")) + let s: String = r.val_at(0)?; + let s = HEX_PREFIX.to_string() + &s; + Hex::from_str(s.as_str()).map_err(|_| DecoderError::Custom("hex check")) } } @@ -188,7 +192,7 @@ mod tests { impl Hex { fn random() -> Self { let data = (0..128).map(|_| random()).collect::>(); - Self::from_string(hex_encode(data)).unwrap() + Hex::encode(data) } } diff --git a/protocol/src/types/block.rs b/protocol/src/types/block.rs index da28030c3..e0725fcd5 100644 --- a/protocol/src/types/block.rs +++ b/protocol/src/types/block.rs @@ -272,7 +272,10 @@ mod tests { Block, BlockVersion, ConsensusConfig, Header, Hex, Metadata, MetadataVersion, ProposeCount, RichBlock, ValidatorExtend, H160, }; - use std::time::{SystemTime, UNIX_EPOCH}; + use std::{ + str::FromStr, + time::{SystemTime, UNIX_EPOCH}, + }; pub fn time_now() -> u64 { SystemTime::now() @@ -328,8 +331,8 @@ mod tests { version: MetadataVersion::new(0, 1000000000), epoch: 0, verifier_list: vec![ValidatorExtend { - bls_pub_key: Hex::from_string("0x04102947214862a503c73904deb5818298a186d68c7907bb609583192a7de6331493835e5b8281f4d9ee705537c0e765580e06f86ddce5867812fceb42eecefd209f0eddd0389d6b7b0100f00fb119ef9ab23826c6ea09aadcc76fa6cea6a32724".to_string()).unwrap(), - pub_key: Hex::from_string("0x02ef0cb0d7bc6c18b4bea1f5908d9106522b35ab3c399369605d4242525bda7e60".to_string()).unwrap(), + bls_pub_key: Hex::from_str("0x04102947214862a503c73904deb5818298a186d68c7907bb609583192a7de6331493835e5b8281f4d9ee705537c0e765580e06f86ddce5867812fceb42eecefd209f0eddd0389d6b7b0100f00fb119ef9ab23826c6ea09aadcc76fa6cea6a32724").unwrap(), + pub_key: Hex::from_str("0x02ef0cb0d7bc6c18b4bea1f5908d9106522b35ab3c399369605d4242525bda7e60").unwrap(), address: H160::default(), propose_weight: 1, vote_weight: 1, diff --git a/protocol/src/types/primitive.rs b/protocol/src/types/primitive.rs index aa262373a..31b15b5ff 100644 --- a/protocol/src/types/primitive.rs +++ b/protocol/src/types/primitive.rs @@ -1,30 +1,30 @@ -use std::cmp::Ordering; -use std::{fmt, str::FromStr}; - pub use ethereum_types::{ BigEndianHash, Bloom, Public, Secret, Signature, H128, H160, H256, H512, H520, H64, U128, U256, U512, U64, }; use zeroize::Zeroizing; +use std::cmp::Ordering; +use std::{fmt, str::FromStr}; + +use faster_hex::withpfx_lowercase; use ophelia::{PublicKey, UncompressedPublicKey}; use overlord::DurationConfig; use rlp_derive::{RlpDecodable, RlpEncodable}; -use serde::{de, Deserialize, Serialize}; +use serde::{de, ser, Deserialize, Serialize}; use common_crypto::Secp256k1PublicKey; use common_hasher::keccak256; -use crate::codec::{hex_decode, hex_encode, serialize_uint}; -use crate::types::{BlockNumber, Bytes, TypesError}; +use crate::codec::{deserialize_address, hex_decode, hex_encode, serialize_uint}; +use crate::types::{BlockNumber, Bytes, BytesMut, TypesError}; use crate::{ProtocolError, ProtocolResult}; pub type Hash = H256; pub type MerkleRoot = Hash; const ADDRESS_LEN: usize = 20; -const HEX_PREFIX: &str = "0x"; -const HEX_PREFIX_UPPER: &str = "0X"; +pub(crate) const HEX_PREFIX: &str = "0x"; pub const NIL_DATA: H256 = H256([ 0xc5, 0xd2, 0x46, 0x01, 0x86, 0xf7, 0x23, 0x3c, 0x92, 0x7e, 0x7d, 0xb2, 0xdc, 0xc7, 0x03, 0xc0, @@ -72,97 +72,78 @@ impl Hasher { } #[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)] -pub struct Hex(String); +pub struct Hex(Bytes); impl Hex { pub fn empty() -> Self { - Hex(String::from(HEX_PREFIX)) + Hex(Bytes::default()) } pub fn is_empty(&self) -> bool { - self.0.len() == 2 + self.0.is_empty() } - pub fn encode>(src: T) -> Self { - let mut s = HEX_PREFIX.to_string(); - s.push_str(&hex_encode(src)); - Hex(s) - } - - pub fn decode(s: String) -> ProtocolResult { - let s = if Self::is_prefixed(s.as_str()) { - &s[2..] - } else { - s.as_str() - }; - - Ok(Bytes::from(hex_decode(s)?)) + pub fn len(&self) -> usize { + self.0.len() } - pub fn from_string(s: String) -> ProtocolResult { - let s = if Self::is_prefixed(s.as_str()) { - s - } else { - HEX_PREFIX.to_string() + &s - }; - - let _ = hex_decode(&s[2..])?; - Ok(Hex(s)) + pub fn encode>(src: T) -> Self { + Hex(BytesMut::from(src.as_ref()).freeze()) } pub fn as_string(&self) -> String { - self.0.to_owned() + HEX_PREFIX.to_string() + &hex_encode(self.0.as_ref()) } pub fn as_string_trim0x(&self) -> String { - (self.0[2..]).to_owned() + hex_encode(self.0.as_ref()) } pub fn as_bytes(&self) -> Bytes { - Bytes::from(hex_decode(&self.0[2..]).expect("impossible, already checked in from_string")) + self.0.clone() } fn is_prefixed(s: &str) -> bool { - s.starts_with(HEX_PREFIX) || s.starts_with(HEX_PREFIX_UPPER) + s.starts_with(HEX_PREFIX) } } impl Default for Hex { fn default() -> Self { - Hex(String::from("0x0000000000000000")) + Hex(vec![0u8; 8].into()) } } -impl Serialize for Hex { - fn serialize(&self, serializer: S) -> Result - where - S: serde::ser::Serializer, - { - serializer.serialize_str(&self.0) +impl AsRef<[u8]> for Hex { + fn as_ref(&self) -> &[u8] { + &self.0 } } -struct HexVisitor; +impl FromStr for Hex { + type Err = ProtocolError; -impl<'de> de::Visitor<'de> for HexVisitor { - type Value = Hex; + fn from_str(s: &str) -> Result { + if !Self::is_prefixed(s) { + return Err(TypesError::HexPrefix.into()); + } - fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - formatter.write_str("Expect a hex string") + Ok(Hex(hex_decode(&s[2..])?.into())) } +} - fn visit_string(self, v: String) -> Result - where - E: de::Error, - { - Hex::from_string(v).map_err(|e| de::Error::custom(e.to_string())) +impl From for Bytes { + fn from(bytes: Hex) -> Self { + bytes.0 } +} - fn visit_str(self, v: &str) -> Result +impl Serialize for Hex { + fn serialize(&self, serializer: S) -> Result where - E: de::Error, + S: ser::Serializer, { - Hex::from_string(v.to_owned()).map_err(|e| de::Error::custom(e.to_string())) + withpfx_lowercase::serialize(&self.0, serializer) } } @@ -171,7 +152,7 @@ impl<'de> Deserialize<'de> for Hex { where D: de::Deserializer<'de>, { - deserializer.deserialize_string(HexVisitor) + Ok(Hex(withpfx_lowercase::deserialize(deserializer)?)) } } @@ -197,42 +178,18 @@ impl Serialize for Address { where S: serde::ser::Serializer, { - serializer.serialize_bytes(self.0.as_bytes()) + serializer.serialize_str(&self.eip55()) } } -// struct AddressVisitor; - -// impl<'de> de::Visitor<'de> for AddressVisitor { -// type Value = Address; - -// fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { -// formatter.write_str("Expect a bech32 string") -// } - -// fn visit_string(self, v: String) -> Result -// where -// E: de::Error, -// { -// Address::from_str(&v).map_err(|e| de::Error::custom(e.to_string())) -// } - -// fn visit_str(self, v: &str) -> Result -// where -// E: de::Error, -// { -// Address::from_str(&v).map_err(|e| de::Error::custom(e.to_string())) -// } -// } - -// impl<'de> Deserialize<'de> for Address { -// fn deserialize(deserializer: D) -> Result -// where -// D: de::Deserializer<'de>, -// { -// deserializer.deserialize_string(AddressVisitor) -// } -// } +impl<'de> Deserialize<'de> for Address { + fn deserialize(deserializer: D) -> Result + where + D: de::Deserializer<'de>, + { + Ok(Address(deserialize_address(deserializer)?)) + } +} impl Address { pub fn from_pubkey_bytes>(bytes: B) -> ProtocolResult { @@ -529,20 +486,21 @@ mod tests { #[test] fn test_hex_decode() { - let hex = String::from("0x"); - let res = Hex::from_string(hex.clone()).unwrap(); + let res = Hex::from_str("0x").unwrap(); assert!(res.is_empty()); - let res = Hex::decode(hex).unwrap(); - assert!(res.is_empty()); - - let hex = String::from("123456"); - let _ = Hex::from_string(hex.clone()).unwrap(); - let _ = Hex::decode(hex).unwrap(); + assert!(Hex::from_str("123456").is_err()); + assert!(Hex::from_str("0x123f").is_ok()); + } - let hex = String::from("0x123f"); - let _ = Hex::from_string(hex.clone()).unwrap(); - let _ = Hex::decode(hex).unwrap(); + #[test] + fn test_hex_codec() { + let data = H256::random(); + let hex = Hex::encode(data.0); + assert_eq!( + serde_json::to_string(&hex).unwrap(), + serde_json::to_string(&data).unwrap() + ); } #[test]