Make AuthorityId serialize/deserialize to/from ss58 (#1180)

* Make `AuthorityId` serialize/deserialize to/from `ss58`

* Updates the wasm files
This commit is contained in:
Bastian Köcher
2018-11-30 16:52:48 +01:00
committed by GitHub
parent ed421c56ee
commit 1dc56b48ab
4 changed files with 24 additions and 13 deletions
+2 -13
View File
@@ -23,16 +23,6 @@ use H256;
#[derive(Clone, Copy, PartialEq, Eq, Default, Encode, Decode)]
pub struct AuthorityId(pub [u8; 32]);
impl AuthorityId {
/// Create an id from a 32-byte slice. Panics with other lengths.
#[cfg(feature = "std")]
fn from_slice(data: &[u8]) -> Self {
let mut r = [0u8; 32];
r.copy_from_slice(data);
AuthorityId(r)
}
}
#[cfg(feature = "std")]
impl ::std::fmt::Display for AuthorityId {
fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {
@@ -94,14 +84,13 @@ impl Into<H256> for AuthorityId {
#[cfg(feature = "std")]
impl Serialize for AuthorityId {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer {
::bytes::serialize(&self.0, serializer)
::ed25519::serialize(&self, serializer)
}
}
#[cfg(feature = "std")]
impl<'de> Deserialize<'de> for AuthorityId {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: Deserializer<'de> {
::bytes::deserialize_check_len(deserializer, ::bytes::ExpectedLen::Exact(32))
.map(|x| AuthorityId::from_slice(&x))
::ed25519::deserialize(deserializer)
}
}
+22
View File
@@ -24,6 +24,9 @@ use ring::{rand, signature};
use {hash::H512, AuthorityId};
use base58::{ToBase58, FromBase58};
#[cfg(feature = "std")]
use serde::{de, Serializer, Deserializer, Deserialize};
/// Alias to 512-bit hash when used in the context of a signature on the relay chain.
pub type Signature = H512;
@@ -278,6 +281,25 @@ impl Verifiable for LocalizedSignature {
}
}
/// Deserialize from `ss58` into something that can be constructed from `[u8; 32]`.
#[cfg(feature = "std")]
pub fn deserialize<'de, D, T: From<[u8; 32]>>(deserializer: D) -> Result<T, D::Error> where
D: Deserializer<'de>,
{
let ss58 = String::deserialize(deserializer)?;
Public::from_ss58check(&ss58)
.map_err(|e| de::Error::custom(format!("{:?}", e)))
.map(|v| v.0.into())
}
/// Serializes something that implements `AsRef<[u8; 32]>` into `ss58`.
#[cfg(feature = "std")]
pub fn serialize<S, T: AsRef<[u8; 32]>>(data: &T, serializer: S) -> Result<S::Ok, S::Error> where
S: Serializer,
{
serializer.serialize_str(&Public(*data.as_ref()).to_ss58check())
}
#[cfg(test)]
mod test {
use super::*;