Skip to content

Commit

Permalink
tendermint: Add TryFrom for node::Id from PublicKey (#903)
Browse files Browse the repository at this point in the history
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 <[email protected]>
  • Loading branch information
xla authored Jun 15, 2021
1 parent b262d0b commit f6f8720
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 7 deletions.
4 changes: 4 additions & 0 deletions tendermint/src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
28 changes: 21 additions & 7 deletions tendermint/src/node/id.rs
Original file line number Diff line number Diff line change
@@ -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;

Expand Down Expand Up @@ -96,6 +98,18 @@ impl PartialEq for Id {
}
}

impl TryFrom<PublicKey> for Id {
type Error = Error;

fn try_from(pk: PublicKey) -> Result<Self, Self::Error> {
match pk {
PublicKey::Ed25519(ed25519) => Ok(Id::from(ed25519)),
#[cfg(feature = "secp256k1")]
_ => Err(Kind::UnsupportedKeyType.into()),
}
}
}

impl<'de> Deserialize<'de> for Id {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
Expand Down

0 comments on commit f6f8720

Please sign in to comment.