Add Deserialize for ed25519::PublicKey (#21)

This commit is contained in:
folex 2020-06-25 13:15:33 +03:00 committed by GitHub
parent d7c1989340
commit ea45550d61
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 48 additions and 0 deletions

View File

@ -34,6 +34,7 @@ thiserror = "1.0"
unsigned-varint = "0.3"
void = "1"
zeroize = "1"
serde = { version = "1.0.114", default-features = false }
[target.'cfg(not(any(target_os = "emscripten", target_os = "unknown")))'.dependencies]
ring = { version = "0.16.9", features = ["alloc", "std"], default-features = false }

View File

@ -84,6 +84,13 @@ impl Clone for Keypair {
}
}
/// Build keypair from existing ed25519 keypair
impl From<ed25519::Keypair> for Keypair {
fn from(kp: ed25519::Keypair) -> Self {
Keypair(kp)
}
}
/// Demote an Ed25519 keypair to a secret key.
impl From<Keypair> for SecretKey {
fn from(kp: Keypair) -> SecretKey {
@ -124,6 +131,46 @@ impl PublicKey {
}
}
impl<'de> serde::Deserialize<'de> for PublicKey {
fn deserialize<D>(deserializer: D) -> Result<PublicKey, D::Error>
where
D: serde::Deserializer<'de>,
{
use serde::de::{Error, Visitor};
struct PKVisitor;
impl<'de> Visitor<'de> for PKVisitor {
type Value = PublicKey;
fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("byte array or base58 string")
}
fn visit_str<E>(self, s: &str) -> Result<Self::Value, E>
where
E: Error,
{
bs58::decode(s)
.into_vec()
.map_err(|err| Error::custom(format!("Invalid string '{}': {}", s, err)))
.and_then(|v| self.visit_bytes(v.as_slice()))
.map_err(|err: E| Error::custom(format!("Parsed string '{}' as base58, but {}", s, err)))
}
fn visit_bytes<E>(self, b: &[u8]) -> Result<Self::Value, E>
where
E: Error,
{
PublicKey::decode(b)
.map_err(|err| Error::custom(format!("Invalid bytes {:?}: {}", b, err)))
}
}
deserializer.deserialize_str(PKVisitor)
}
}
/// An Ed25519 secret key.
pub struct SecretKey(ed25519::SecretKey);