mirror of
https://github.com/pezkuwichain/pezkuwi-subxt.git
synced 2026-06-09 20:11:09 +00:00
Serialization with serde.
This commit is contained in:
@@ -24,7 +24,7 @@ pub type HeaderHash = H256;
|
||||
pub type ProofHash = H256;
|
||||
|
||||
/// Unique identifier of a parachain.
|
||||
#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Clone, Copy)]
|
||||
#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Clone, Copy, Serialize, Deserialize)]
|
||||
pub struct ParachainId(u64);
|
||||
|
||||
impl From<ParachainId> for u64 {
|
||||
@@ -35,19 +35,23 @@ impl From<u64> for ParachainId {
|
||||
fn from(x: u64) -> Self { ParachainId(x) }
|
||||
}
|
||||
|
||||
/// A wrapper type for parachain block header raw bytes.
|
||||
#[derive(Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct ParachainBlockHeader(pub Vec<u8>);
|
||||
|
||||
/// A parachain block proposal.
|
||||
#[derive(Debug, PartialEq, Eq)]
|
||||
#[derive(Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct ParachainProposal {
|
||||
/// The ID of the parachain this is a proposal for.
|
||||
pub parachain: ParachainId,
|
||||
/// Parachain block header bytes.
|
||||
pub header: Vec<u8>,
|
||||
pub header: ParachainBlockHeader,
|
||||
/// Hash of data necessary to prove validity of the header.
|
||||
pub proof_hash: ProofHash,
|
||||
}
|
||||
|
||||
/// A relay chain block header.
|
||||
#[derive(Debug, PartialEq, Eq)]
|
||||
#[derive(Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct Header {
|
||||
/// Block parent's hash.
|
||||
pub parent_hash: HeaderHash,
|
||||
@@ -63,8 +67,56 @@ pub struct Header {
|
||||
///
|
||||
/// Included candidates should be sorted by parachain ID, and without duplicate
|
||||
/// IDs.
|
||||
#[derive(Debug, PartialEq, Eq)]
|
||||
#[derive(Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct Body {
|
||||
/// Parachain proposal blocks.
|
||||
pub para_blocks: Vec<ParachainProposal>,
|
||||
}
|
||||
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use polkadot_serializer as ser;
|
||||
|
||||
#[test]
|
||||
fn test_header_serialization() {
|
||||
assert_eq!(ser::to_string_pretty(&Header {
|
||||
parent_hash: 5.into(),
|
||||
state_root: 3.into(),
|
||||
timestamp: 10,
|
||||
number: 67,
|
||||
}), r#"{
|
||||
"parent_hash": "0x0000000000000000000000000000000000000000000000000000000000000005",
|
||||
"state_root": "0x0000000000000000000000000000000000000000000000000000000000000003",
|
||||
"timestamp": 10,
|
||||
"number": 67
|
||||
}"#);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_body_serialization() {
|
||||
assert_eq!(ser::to_string_pretty(&Body {
|
||||
para_blocks: vec![
|
||||
ParachainProposal {
|
||||
parachain: 5.into(),
|
||||
header: ParachainBlockHeader(vec![1, 2, 3, 4]),
|
||||
proof_hash: 5.into(),
|
||||
}
|
||||
],
|
||||
}), r#"{
|
||||
"para_blocks": [
|
||||
{
|
||||
"parachain": 5,
|
||||
"header": [
|
||||
1,
|
||||
2,
|
||||
3,
|
||||
4
|
||||
],
|
||||
"proof_hash": "0x0000000000000000000000000000000000000000000000000000000000000005"
|
||||
}
|
||||
]
|
||||
}"#);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -16,5 +16,100 @@
|
||||
|
||||
//! A fixed hash type.
|
||||
|
||||
use std::fmt;
|
||||
use serde::{de, Serialize, Serializer, Deserialize, Deserializer};
|
||||
|
||||
macro_rules! impl_serde {
|
||||
($name: ident, $len: expr) => {
|
||||
impl Serialize for $name {
|
||||
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer {
|
||||
// TODO [ToDr] Use raw bytes if we switch to RLP / binencoding
|
||||
// (serialize_bytes)
|
||||
serializer.serialize_str(&format!("0x{:?}", self))
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
impl<'de> Deserialize<'de> for $name {
|
||||
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: Deserializer<'de> {
|
||||
struct Visitor;
|
||||
impl<'a> de::Visitor<'a> for Visitor {
|
||||
type Value = $name;
|
||||
|
||||
fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
|
||||
write!(formatter, "a 0x-prefixed hex string of {} bytes", $len)
|
||||
}
|
||||
|
||||
fn visit_str<E: de::Error>(self, v: &str) -> Result<Self::Value, E> {
|
||||
if v.len() < 2 || &v[0..2] != "0x" {
|
||||
return Err(E::custom("prefix is missing"))
|
||||
}
|
||||
|
||||
// 0x + len
|
||||
if v.len() != 2 + $len * 2 {
|
||||
return Err(E::invalid_length(v.len() - 2, &self));
|
||||
}
|
||||
|
||||
let bytes = ::rustc_hex::FromHex::from_hex(&v[2..])
|
||||
.map_err(|e| E::custom(&format!("invalid hex value: {:?}", e)))?;
|
||||
Ok((&*bytes).into())
|
||||
}
|
||||
|
||||
fn visit_string<E: de::Error>(self, v: String) -> Result<Self::Value, E> {
|
||||
self.visit_str(&v)
|
||||
}
|
||||
}
|
||||
// TODO [ToDr] Use raw bytes if we switch to RLP / binencoding
|
||||
// (visit_bytes, visit_bytes_buf)
|
||||
deserializer.deserialize_str(Visitor)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl_hash!(H160, 20);
|
||||
impl_serde!(H160, 20);
|
||||
impl_hash!(H256, 32);
|
||||
impl_serde!(H256, 32);
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use polkadot_serializer as ser;
|
||||
|
||||
#[test]
|
||||
fn test_h160() {
|
||||
let tests = vec![
|
||||
(H160::from(0), "0x0000000000000000000000000000000000000000"),
|
||||
(H160::from(2), "0x0000000000000000000000000000000000000002"),
|
||||
(H160::from(15), "0x000000000000000000000000000000000000000f"),
|
||||
(H160::from(16), "0x0000000000000000000000000000000000000010"),
|
||||
(H160::from(1_000), "0x00000000000000000000000000000000000003e8"),
|
||||
(H160::from(100_000), "0x00000000000000000000000000000000000186a0"),
|
||||
(H160::from(u64::max_value()), "0x000000000000000000000000ffffffffffffffff"),
|
||||
];
|
||||
|
||||
for (number, expected) in tests {
|
||||
assert_eq!(format!("{:?}", expected), ser::to_string_pretty(&number));
|
||||
assert_eq!(number, ser::from_str(&format!("{:?}", expected)).unwrap());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_h256() {
|
||||
let tests = vec![
|
||||
(H256::from(0), "0x0000000000000000000000000000000000000000000000000000000000000000"),
|
||||
(H256::from(2), "0x0000000000000000000000000000000000000000000000000000000000000002"),
|
||||
(H256::from(15), "0x000000000000000000000000000000000000000000000000000000000000000f"),
|
||||
(H256::from(16), "0x0000000000000000000000000000000000000000000000000000000000000010"),
|
||||
(H256::from(1_000), "0x00000000000000000000000000000000000000000000000000000000000003e8"),
|
||||
(H256::from(100_000), "0x00000000000000000000000000000000000000000000000000000000000186a0"),
|
||||
(H256::from(u64::max_value()), "0x000000000000000000000000000000000000000000000000ffffffffffffffff"),
|
||||
];
|
||||
|
||||
for (number, expected) in tests {
|
||||
assert_eq!(format!("{:?}", expected), ser::to_string_pretty(&number));
|
||||
assert_eq!(number, ser::from_str(&format!("{:?}", expected)).unwrap());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -18,27 +18,29 @@
|
||||
|
||||
#![warn(missing_docs)]
|
||||
|
||||
#[cfg(feature="std")]
|
||||
extern crate core;
|
||||
extern crate serde;
|
||||
extern crate rustc_hex;
|
||||
|
||||
#[macro_use]
|
||||
extern crate crunchy;
|
||||
#[macro_use]
|
||||
extern crate fixed_hash;
|
||||
#[macro_use]
|
||||
extern crate serde_derive;
|
||||
#[macro_use]
|
||||
extern crate uint as uint_crate;
|
||||
|
||||
#[cfg(feature="std")]
|
||||
extern crate core;
|
||||
#[cfg(test)]
|
||||
extern crate polkadot_serializer;
|
||||
#[cfg(test)]
|
||||
#[macro_use]
|
||||
extern crate pretty_assertions;
|
||||
|
||||
pub mod block;
|
||||
pub mod hash;
|
||||
pub mod uint;
|
||||
|
||||
/// Alias to 160-bit hash when used in the context of an account address.
|
||||
pub type Address = hash::H160;
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
#[test]
|
||||
fn it_works() {
|
||||
assert_eq!(2 + 2, 4);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -16,5 +16,98 @@
|
||||
|
||||
//! An unsigned fixed-size integer.
|
||||
|
||||
use std::fmt;
|
||||
use serde::{de, Serialize, Serializer, Deserialize, Deserializer};
|
||||
|
||||
macro_rules! impl_serde {
|
||||
($name: ident, $len: expr) => {
|
||||
impl Serialize for $name {
|
||||
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer {
|
||||
// TODO [ToDr] Use raw bytes if we switch to RLP / binencoding
|
||||
// (serialize_bytes)
|
||||
if self.is_zero() {
|
||||
// TODO [ToDr] LowerHex of 0 is broken
|
||||
serializer.serialize_str("0x0")
|
||||
} else {
|
||||
serializer.serialize_str(&format!("{:#x}", self))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<'de> Deserialize<'de> for $name {
|
||||
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: Deserializer<'de> {
|
||||
struct Visitor;
|
||||
impl<'a> de::Visitor<'a> for Visitor {
|
||||
type Value = $name;
|
||||
|
||||
fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
|
||||
write!(formatter, "a 0x-prefixed hex string")
|
||||
}
|
||||
|
||||
fn visit_str<E: de::Error>(self, v: &str) -> Result<Self::Value, E> {
|
||||
if v.len() < 2 || &v[0..2] != "0x" {
|
||||
return Err(E::custom("prefix is missing"))
|
||||
}
|
||||
|
||||
// 0x + len
|
||||
if v.len() > 2 + $len * 16 {
|
||||
return Err(E::invalid_length(v.len() - 2, &self));
|
||||
}
|
||||
|
||||
let v = if v.len() % 2 == 0 { v[2..].to_owned() } else { format!("0{}", &v[2..]) };
|
||||
let bytes = ::rustc_hex::FromHex::from_hex(v.as_str())
|
||||
.map_err(|e| E::custom(&format!("invalid hex value: {:?}", e)))?;
|
||||
Ok((&*bytes).into())
|
||||
}
|
||||
|
||||
fn visit_string<E: de::Error>(self, v: String) -> Result<Self::Value, E> {
|
||||
self.visit_str(&v)
|
||||
}
|
||||
}
|
||||
// TODO [ToDr] Use raw bytes if we switch to RLP / binencoding
|
||||
// (visit_bytes, visit_bytes_buf)
|
||||
deserializer.deserialize_str(Visitor)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
construct_uint!(U256, 4);
|
||||
impl_serde!(U256, 4);
|
||||
construct_uint!(U512, 8);
|
||||
impl_serde!(U512, 8);
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use polkadot_serializer as ser;
|
||||
|
||||
macro_rules! test {
|
||||
($name: ident, $test_name: ident) => {
|
||||
#[test]
|
||||
fn $test_name() {
|
||||
let tests = vec![
|
||||
($name::from(0), "0x0"),
|
||||
($name::from(1), "0x1"),
|
||||
($name::from(2), "0x2"),
|
||||
($name::from(10), "0xa"),
|
||||
($name::from(15), "0xf"),
|
||||
($name::from(15), "0xf"),
|
||||
($name::from(16), "0x10"),
|
||||
($name::from(1_000), "0x3e8"),
|
||||
($name::from(100_000), "0x186a0"),
|
||||
($name::from(u64::max_value()), "0xffffffffffffffff"),
|
||||
($name::from(u64::max_value()) + 1.into(), "0x10000000000000000"),
|
||||
];
|
||||
|
||||
for (number, expected) in tests {
|
||||
assert_eq!(format!("{:?}", expected), ser::to_string_pretty(&number));
|
||||
assert_eq!(number, ser::from_str(&format!("{:?}", expected)).unwrap());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
test!(U256, test_u256);
|
||||
test!(U512, test_u512);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user