Add ed25519 support to encodePubkey

This commit is contained in:
Simon Warta 2022-10-13 14:57:16 +02:00
parent 3067ab09ed
commit 472f78a4f6
3 changed files with 27 additions and 2 deletions

View File

@ -10,8 +10,8 @@ and this project adheres to
- @cosmjs/amino: Add `encodeEd25519Pubkey` analogue to the existing
`encodeSecp256k1Pubkey`.
- @cosmjs/proto-signing: Add Ed25519 support to `anyToSinglePubkey` and make
export `anyToSinglePubkey`.
- @cosmjs/proto-signing: Add Ed25519 support to `encodePubkey` and
`anyToSinglePubkey`. Export `anyToSinglePubkey`.
- @cosmjs/utils: Add `isDefined` which checks for `undefined` in a
TypeScript-friendly way.

View File

@ -23,6 +23,16 @@ describe("pubkey", () => {
);
});
it("works for ed25519", () => {
const pubkey = { type: "tendermint/PubKeyEd25519", value: ed25519PubkeyBase64 };
expect(encodePubkey(pubkey)).toEqual(
Any.fromPartial({
typeUrl: "/cosmos.crypto.ed25519.PubKey",
value: ed25519PubkeyProtoBytes,
}),
);
});
it("throws for unsupported pubkey types", () => {
const pubkey = {
type: "tendermint/PubKeyUnknown",

View File

@ -2,6 +2,7 @@
import {
encodeEd25519Pubkey,
encodeSecp256k1Pubkey,
isEd25519Pubkey,
isMultisigThresholdPubkey,
isSecp256k1Pubkey,
MultisigThresholdPubkey,
@ -15,6 +16,12 @@ import { LegacyAminoPubKey } from "cosmjs-types/cosmos/crypto/multisig/keys";
import { PubKey as CosmosCryptoSecp256k1Pubkey } from "cosmjs-types/cosmos/crypto/secp256k1/keys";
import { Any } from "cosmjs-types/google/protobuf/any";
/**
* Takes a pubkey in the Amino JSON object style (type/value wrapper)
* and convertes it into a protobuf `Any`.
*
* This is the reverse operation to `decodePubkey`.
*/
export function encodePubkey(pubkey: Pubkey): Any {
if (isSecp256k1Pubkey(pubkey)) {
const pubkeyProto = CosmosCryptoSecp256k1Pubkey.fromPartial({
@ -24,6 +31,14 @@ export function encodePubkey(pubkey: Pubkey): Any {
typeUrl: "/cosmos.crypto.secp256k1.PubKey",
value: Uint8Array.from(CosmosCryptoSecp256k1Pubkey.encode(pubkeyProto).finish()),
});
} else if (isEd25519Pubkey(pubkey)) {
const pubkeyProto = CosmosCryptoEd25519Pubkey.fromPartial({
key: fromBase64(pubkey.value),
});
return Any.fromPartial({
typeUrl: "/cosmos.crypto.ed25519.PubKey",
value: Uint8Array.from(CosmosCryptoEd25519Pubkey.encode(pubkeyProto).finish()),
});
} else if (isMultisigThresholdPubkey(pubkey)) {
const pubkeyProto = LegacyAminoPubKey.fromPartial({
threshold: Uint53.fromString(pubkey.value.threshold).toNumber(),