Skip to content

Commit

Permalink
refactor: improve code organization
Browse files Browse the repository at this point in the history
  • Loading branch information
wenyuanhust committed Nov 2, 2023
1 parent 6edeb43 commit 1c0f31f
Show file tree
Hide file tree
Showing 4 changed files with 115 additions and 111 deletions.
58 changes: 58 additions & 0 deletions devtools/axon-tools/src/error.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
use derive_more::{Display, From};
use ethereum_types::H256;
use std::fmt::{self, Display};

#[allow(dead_code)]
Expand Down Expand Up @@ -61,3 +63,59 @@ impl Display for Error {
}
}
}

#[derive(Debug, Display, From)]
pub enum TypesError {
#[display(fmt = "Expect {:?}, get {:?}.", expect, real)]
LengthMismatch { expect: usize, real: usize },

#[display(
fmt = "Eip1559Transaction hash mismatch origin {:?}, computed {:?}",
origin,
calc
)]
TxHashMismatch { origin: H256, calc: H256 },

#[display(fmt = "{:?}", _0)]
FromHex(faster_hex::Error),

#[display(fmt = "{:?} is an invalid address", _0)]
InvalidAddress(String),

#[display(fmt = "Hex should start with 0x")]
HexPrefix,

#[display(fmt = "Invalid public key")]
InvalidPublicKey,

#[display(fmt = "Invalid check sum")]
InvalidCheckSum,

#[display(fmt = "Unsigned")]
Unsigned,

// #[display(fmt = "Crypto error {:?}", _0)]
// Crypto(CryptoError),
#[display(fmt = "Missing signature")]
MissingSignature,

#[display(fmt = "Invalid crosschain direction")]
InvalidDirection,

#[display(fmt = "Signature R is empty")]
SignatureRIsEmpty,

#[display(fmt = "Invalid signature R type")]
InvalidSignatureRType,

#[display(fmt = "Invalid address source type")]
InvalidAddressSourceType,

#[display(fmt = "Missing interoperation sender")]
MissingInteroperationSender,

#[display(fmt = "InvalidBlockVersion {:?}", _0)]
InvalidBlockVersion(u8),
}

impl std::error::Error for TypesError {}
1 change: 1 addition & 0 deletions devtools/axon-tools/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ pub mod hash;
pub mod hex;
#[cfg(feature = "proof")]
mod proof;
mod rlp_codec;
pub mod types;

pub use error::Error;
Expand Down
52 changes: 52 additions & 0 deletions devtools/axon-tools/src/rlp_codec.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
use crate::types::{BlockVersion, Proposal, Vote};
#[cfg(feature = "impl-rlp")]
use rlp::{Decodable, DecoderError, Encodable, Rlp, RlpStream};

#[cfg(feature = "impl-rlp")]
impl Encodable for BlockVersion {
fn rlp_append(&self, s: &mut RlpStream) {
let ver: u8 = (*self).into();
s.begin_list(1).append(&ver);
}
}

#[cfg(feature = "impl-rlp")]
impl Decodable for BlockVersion {
fn decode(r: &Rlp) -> Result<Self, DecoderError> {
let ver: u8 = r.val_at(0)?;
ver.try_into()
.map_err(|_| DecoderError::Custom("Invalid block version"))
}
}

#[cfg(feature = "impl-rlp")]
impl Encodable for Vote {
fn rlp_append(&self, s: &mut RlpStream) {
let vote_type: u8 = self.vote_type;
s.begin_list(4)
.append(&self.height)
.append(&self.round)
.append(&vote_type)
.append(&self.block_hash.to_vec());
}
}

#[cfg(feature = "impl-rlp")]
impl Encodable for Proposal {
fn rlp_append(&self, s: &mut RlpStream) {
s.begin_list(13)
.append(&self.version)
.append(&self.prev_hash)
.append(&self.proposer)
.append(&self.prev_state_root)
.append(&self.transactions_root)
.append(&self.signed_txs_hash)
.append(&self.timestamp)
.append(&self.number)
.append(&self.gas_limit.as_u64())
.append_list(&self.extra_data)
.append(&self.proof)
.append(&self.call_system_script_count)
.append_list(&self.tx_hashes);
}
}
115 changes: 4 additions & 111 deletions devtools/axon-tools/src/types.rs
Original file line number Diff line number Diff line change
@@ -1,19 +1,15 @@
use core::cmp::Ordering;

use crate::error::TypesError;
use alloc::vec::Vec;
use bytes::{Bytes, BytesMut};
use core::cmp::Ordering;
use core::str::FromStr;
use derive_more::{Display, From};
use ethereum_types::{Bloom, H160, H256, U256};
use faster_hex::withpfx_lowercase;
use rlp::{Decodable, DecoderError, Rlp};

pub use ethereum_types::{Bloom, H160, H256, H64, U256};

#[cfg(feature = "impl-serde")]
use serde::{Deserialize, Serialize};

#[cfg(feature = "impl-rlp")]
use rlp::{Encodable, RlpStream};
use rlp_derive::{RlpDecodable, RlpEncodable};

#[cfg(feature = "hex")]
Expand Down Expand Up @@ -111,62 +107,6 @@ impl<'de> Deserialize<'de> for Hex {
}
}

#[derive(Debug, Display, From)]
pub enum TypesError {
#[display(fmt = "Expect {:?}, get {:?}.", expect, real)]
LengthMismatch { expect: usize, real: usize },

#[display(
fmt = "Eip1559Transaction hash mismatch origin {:?}, computed {:?}",
origin,
calc
)]
TxHashMismatch { origin: H256, calc: H256 },

#[display(fmt = "{:?}", _0)]
FromHex(faster_hex::Error),

#[display(fmt = "{:?} is an invalid address", _0)]
InvalidAddress(String),

#[display(fmt = "Hex should start with 0x")]
HexPrefix,

#[display(fmt = "Invalid public key")]
InvalidPublicKey,

#[display(fmt = "Invalid check sum")]
InvalidCheckSum,

#[display(fmt = "Unsigned")]
Unsigned,

// #[display(fmt = "Crypto error {:?}", _0)]
// Crypto(CryptoError),
#[display(fmt = "Missing signature")]
MissingSignature,

#[display(fmt = "Invalid crosschain direction")]
InvalidDirection,

#[display(fmt = "Signature R is empty")]
SignatureRIsEmpty,

#[display(fmt = "Invalid signature R type")]
InvalidSignatureRType,

#[display(fmt = "Invalid address source type")]
InvalidAddressSourceType,

#[display(fmt = "Missing interoperation sender")]
MissingInteroperationSender,

#[display(fmt = "InvalidBlockVersion {:?}", _0)]
InvalidBlockVersion(u8),
}

impl std::error::Error for TypesError {}

#[derive(Default, Copy, Clone, Debug, PartialEq, Eq)]
#[cfg(feature = "impl-serde")]
#[derive(Serialize, Deserialize)]
Expand All @@ -186,29 +126,14 @@ impl From<BlockVersion> for u8 {
impl TryFrom<u8> for BlockVersion {
type Error = TypesError;

fn try_from(value: u8) -> Result<Self, Self::Error> {
fn try_from(value: u8) -> Result<Self, TypesError> {
match value {
0 => Ok(BlockVersion::V0),
_ => Err(TypesError::InvalidBlockVersion(value)),
}
}
}

impl Encodable for BlockVersion {
fn rlp_append(&self, s: &mut RlpStream) {
let ver: u8 = (*self).into();
s.begin_list(1).append(&ver);
}
}

impl Decodable for BlockVersion {
fn decode(r: &Rlp) -> Result<Self, DecoderError> {
let ver: u8 = r.val_at(0)?;
ver.try_into()
.map_err(|_| DecoderError::Custom("Invalid block version"))
}
}

pub type Hash = H256;
pub type MerkleRoot = Hash;
pub type BlockNumber = u64;
Expand Down Expand Up @@ -336,26 +261,6 @@ pub struct Proposal {
pub tx_hashes: Vec<Hash>,
}

#[cfg(feature = "impl-rlp")]
impl Encodable for Proposal {
fn rlp_append(&self, s: &mut RlpStream) {
s.begin_list(13)
.append(&self.version)
.append(&self.prev_hash)
.append(&self.proposer)
.append(&self.prev_state_root)
.append(&self.transactions_root)
.append(&self.signed_txs_hash)
.append(&self.timestamp)
.append(&self.number)
.append(&self.gas_limit.as_u64())
.append_list(&self.extra_data)
.append(&self.proof)
.append(&self.call_system_script_count)
.append_list(&self.tx_hashes);
}
}

#[derive(Clone, Debug, Default, PartialEq, Eq)]
#[cfg_attr(
feature = "impl-rlp",
Expand Down Expand Up @@ -435,18 +340,6 @@ pub struct Vote {
pub block_hash: Bytes,
}

#[cfg(feature = "impl-rlp")]
impl Encodable for Vote {
fn rlp_append(&self, s: &mut RlpStream) {
let vote_type: u8 = self.vote_type;
s.begin_list(4)
.append(&self.height)
.append(&self.round)
.append(&vote_type)
.append(&self.block_hash.to_vec());
}
}

#[cfg(test)]
impl Vote {
fn random() -> Self {
Expand Down

0 comments on commit 1c0f31f

Please sign in to comment.