From ea21b5bbc583c4e5ab550f996593f6cbc87f7653 Mon Sep 17 00:00:00 2001 From: Collin Date: Wed, 20 Apr 2022 16:06:22 -0500 Subject: [PATCH] cosmrs: add `TryFrom` impls for tendermint public key types (#203) --- cosmrs/src/crypto/public_key.rs | 42 ++++++++++++++++++++++++--------- 1 file changed, 31 insertions(+), 11 deletions(-) diff --git a/cosmrs/src/crypto/public_key.rs b/cosmrs/src/crypto/public_key.rs index bf41954b..6e23d109 100644 --- a/cosmrs/src/crypto/public_key.rs +++ b/cosmrs/src/crypto/public_key.rs @@ -101,22 +101,36 @@ impl TryFrom<&Any> for PublicKey { type Error = ErrorReport; fn try_from(any: &Any) -> Result { - let tm_key = match any.type_url.as_str() { + match any.type_url.as_str() { Self::ED25519_TYPE_URL => { - let proto = proto::cosmos::crypto::ed25519::PubKey::decode(&*any.value)?; - tendermint::PublicKey::from_raw_ed25519(&proto.key) + proto::cosmos::crypto::ed25519::PubKey::decode(&*any.value)?.try_into() } Self::SECP256K1_TYPE_URL => { - let proto = proto::cosmos::crypto::secp256k1::PubKey::decode(&*any.value)?; - tendermint::PublicKey::from_raw_secp256k1(&proto.key) + proto::cosmos::crypto::secp256k1::PubKey::decode(&*any.value)?.try_into() } - other => { - return Err(Error::Crypto) - .wrap_err_with(|| format!("invalid type URL for public key: {}", other)) - } - }; + other => Err(Error::Crypto) + .wrap_err_with(|| format!("invalid type URL for public key: {}", other)), + } + } +} - tm_key.map(Into::into).ok_or_else(|| Error::Crypto.into()) +impl TryFrom for PublicKey { + type Error = ErrorReport; + + fn try_from(public_key: proto::cosmos::crypto::ed25519::PubKey) -> Result { + tendermint::public_key::PublicKey::from_raw_ed25519(&public_key.key) + .map(Into::into) + .ok_or_else(|| Error::Crypto.into()) + } +} + +impl TryFrom for PublicKey { + type Error = ErrorReport; + + fn try_from(public_key: proto::cosmos::crypto::secp256k1::PubKey) -> Result { + tendermint::public_key::PublicKey::from_raw_secp256k1(&public_key.key) + .map(Into::into) + .ok_or_else(|| Error::Crypto.into()) } } @@ -217,6 +231,12 @@ mod tests { #[test] fn json_round_trip() { let example_key = EXAMPLE_JSON.parse::().unwrap(); + + // test try_from + let tm_key: tendermint::public_key::PublicKey = + example_key.try_into().expect("try_into failure"); + let example_key = PublicKey::try_from(tm_key).expect("try_from failure"); + assert_eq!(example_key.type_url(), "/cosmos.crypto.ed25519.PubKey"); assert_eq!( example_key.to_bytes().as_slice(),