Skip to content

Commit ea21b5b

Browse files
authored
cosmrs: add TryFrom impls for tendermint public key types (#203)
1 parent b9c9caa commit ea21b5b

File tree

1 file changed

+31
-11
lines changed

1 file changed

+31
-11
lines changed

cosmrs/src/crypto/public_key.rs

Lines changed: 31 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -101,22 +101,36 @@ impl TryFrom<&Any> for PublicKey {
101101
type Error = ErrorReport;
102102

103103
fn try_from(any: &Any) -> Result<PublicKey> {
104-
let tm_key = match any.type_url.as_str() {
104+
match any.type_url.as_str() {
105105
Self::ED25519_TYPE_URL => {
106-
let proto = proto::cosmos::crypto::ed25519::PubKey::decode(&*any.value)?;
107-
tendermint::PublicKey::from_raw_ed25519(&proto.key)
106+
proto::cosmos::crypto::ed25519::PubKey::decode(&*any.value)?.try_into()
108107
}
109108
Self::SECP256K1_TYPE_URL => {
110-
let proto = proto::cosmos::crypto::secp256k1::PubKey::decode(&*any.value)?;
111-
tendermint::PublicKey::from_raw_secp256k1(&proto.key)
109+
proto::cosmos::crypto::secp256k1::PubKey::decode(&*any.value)?.try_into()
112110
}
113-
other => {
114-
return Err(Error::Crypto)
115-
.wrap_err_with(|| format!("invalid type URL for public key: {}", other))
116-
}
117-
};
111+
other => Err(Error::Crypto)
112+
.wrap_err_with(|| format!("invalid type URL for public key: {}", other)),
113+
}
114+
}
115+
}
118116

119-
tm_key.map(Into::into).ok_or_else(|| Error::Crypto.into())
117+
impl TryFrom<proto::cosmos::crypto::ed25519::PubKey> for PublicKey {
118+
type Error = ErrorReport;
119+
120+
fn try_from(public_key: proto::cosmos::crypto::ed25519::PubKey) -> Result<PublicKey> {
121+
tendermint::public_key::PublicKey::from_raw_ed25519(&public_key.key)
122+
.map(Into::into)
123+
.ok_or_else(|| Error::Crypto.into())
124+
}
125+
}
126+
127+
impl TryFrom<proto::cosmos::crypto::secp256k1::PubKey> for PublicKey {
128+
type Error = ErrorReport;
129+
130+
fn try_from(public_key: proto::cosmos::crypto::secp256k1::PubKey) -> Result<PublicKey> {
131+
tendermint::public_key::PublicKey::from_raw_secp256k1(&public_key.key)
132+
.map(Into::into)
133+
.ok_or_else(|| Error::Crypto.into())
120134
}
121135
}
122136

@@ -217,6 +231,12 @@ mod tests {
217231
#[test]
218232
fn json_round_trip() {
219233
let example_key = EXAMPLE_JSON.parse::<PublicKey>().unwrap();
234+
235+
// test try_from
236+
let tm_key: tendermint::public_key::PublicKey =
237+
example_key.try_into().expect("try_into failure");
238+
let example_key = PublicKey::try_from(tm_key).expect("try_from failure");
239+
220240
assert_eq!(example_key.type_url(), "/cosmos.crypto.ed25519.PubKey");
221241
assert_eq!(
222242
example_key.to_bytes().as_slice(),

0 commit comments

Comments
 (0)