From f6f8720c7424ddd485bb9c0a2ad42df90287127c Mon Sep 17 00:00:00 2001 From: Alexander Simmerl Date: Tue, 15 Jun 2021 13:27:18 +0200 Subject: [PATCH] tendermint: Add TryFrom for node::Id from PublicKey (#903) Convenience to obtain a `node::Id` from a PublicKey, which is especially useful in the context p2p and protocols built on top of it as the main reference a peer is catalogued by is the `node::Id`. Signed-off-by: Alexander Simmerl --- tendermint/src/error.rs | 4 ++++ tendermint/src/node/id.rs | 28 +++++++++++++++++++++------- 2 files changed, 25 insertions(+), 7 deletions(-) diff --git a/tendermint/src/error.rs b/tendermint/src/error.rs index f5c678a48..0df48310d 100644 --- a/tendermint/src/error.rs +++ b/tendermint/src/error.rs @@ -20,6 +20,10 @@ pub enum Kind { #[error("invalid key")] InvalidKey, + /// Unsupported public key type. + #[error("unsupported key type")] + UnsupportedKeyType, + /// Input/output error #[error("I/O error")] Io, diff --git a/tendermint/src/node/id.rs b/tendermint/src/node/id.rs index 675181aa7..7cedc02e9 100644 --- a/tendermint/src/node/id.rs +++ b/tendermint/src/node/id.rs @@ -1,19 +1,21 @@ //! Tendermint node IDs -use crate::{ - error::{Error, Kind}, - public_key::Ed25519, -}; - -use serde::{de, Deserialize, Deserializer, Serialize, Serializer}; -use sha2::{Digest, Sha256}; use std::{ + convert::TryFrom, fmt::{self, Debug, Display}, str::FromStr, }; + +use serde::{de, Deserialize, Deserializer, Serialize, Serializer}; +use sha2::{Digest, Sha256}; use subtle::{self, ConstantTimeEq}; use subtle_encoding::hex; +use crate::{ + error::{Error, Kind}, + public_key::{Ed25519, PublicKey}, +}; + /// Length of a Node ID in bytes pub const LENGTH: usize = 20; @@ -96,6 +98,18 @@ impl PartialEq for Id { } } +impl TryFrom for Id { + type Error = Error; + + fn try_from(pk: PublicKey) -> Result { + match pk { + PublicKey::Ed25519(ed25519) => Ok(Id::from(ed25519)), + #[cfg(feature = "secp256k1")] + _ => Err(Kind::UnsupportedKeyType.into()), + } + } +} + impl<'de> Deserialize<'de> for Id { fn deserialize(deserializer: D) -> Result where