Skip to content

Commit

Permalink
cosmrs: add TryFrom impls for tendermint public key types (#203)
Browse files Browse the repository at this point in the history
  • Loading branch information
cbrit authored Apr 20, 2022
1 parent b9c9caa commit ea21b5b
Showing 1 changed file with 31 additions and 11 deletions.
42 changes: 31 additions & 11 deletions cosmrs/src/crypto/public_key.rs
Original file line number Diff line number Diff line change
Expand Up @@ -101,22 +101,36 @@ impl TryFrom<&Any> for PublicKey {
type Error = ErrorReport;

fn try_from(any: &Any) -> Result<PublicKey> {
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<proto::cosmos::crypto::ed25519::PubKey> for PublicKey {
type Error = ErrorReport;

fn try_from(public_key: proto::cosmos::crypto::ed25519::PubKey) -> Result<PublicKey> {
tendermint::public_key::PublicKey::from_raw_ed25519(&public_key.key)
.map(Into::into)
.ok_or_else(|| Error::Crypto.into())
}
}

impl TryFrom<proto::cosmos::crypto::secp256k1::PubKey> for PublicKey {
type Error = ErrorReport;

fn try_from(public_key: proto::cosmos::crypto::secp256k1::PubKey) -> Result<PublicKey> {
tendermint::public_key::PublicKey::from_raw_secp256k1(&public_key.key)
.map(Into::into)
.ok_or_else(|| Error::Crypto.into())
}
}

Expand Down Expand Up @@ -217,6 +231,12 @@ mod tests {
#[test]
fn json_round_trip() {
let example_key = EXAMPLE_JSON.parse::<PublicKey>().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(),
Expand Down

0 comments on commit ea21b5b

Please sign in to comment.