Replace switch with type checks

This commit is contained in:
Simon Warta 2021-03-22 15:50:54 +01:00
parent 7819836387
commit 09ce133331
3 changed files with 30 additions and 15 deletions

View File

@ -2,7 +2,14 @@ import { Bech32, fromBase64, fromHex, toBase64, toHex } from "@cosmjs/encoding";
import { Uint53 } from "@cosmjs/math";
import { arrayContentStartsWith } from "@cosmjs/utils";
import { isMultisigThresholdPubkey, Pubkey, pubkeyType, Secp256k1Pubkey } from "./pubkeys";
import {
isEd25519Pubkey,
isMultisigThresholdPubkey,
isSecp256k1Pubkey,
Pubkey,
pubkeyType,
Secp256k1Pubkey,
} from "./pubkeys";
export function encodeSecp256k1Pubkey(pubkey: Uint8Array): Secp256k1Pubkey {
if (pubkey.length !== 33 || (pubkey[0] !== 0x02 && pubkey[0] !== 0x03)) {
@ -100,21 +107,13 @@ export function encodeAminoPubkey(pubkey: Pubkey): Uint8Array {
out.push(...pubkeyData);
}
return new Uint8Array(out);
} else if (isEd25519Pubkey(pubkey)) {
return new Uint8Array([...pubkeyAminoPrefixEd25519, ...fromBase64(pubkey.value)]);
} else if (isSecp256k1Pubkey(pubkey)) {
return new Uint8Array([...pubkeyAminoPrefixSecp256k1, ...fromBase64(pubkey.value)]);
} else {
throw new Error("Unsupported pubkey type");
}
let aminoPrefix: Uint8Array;
switch (pubkey.type) {
// Note: please don't add cases here without writing additional unit tests
case pubkeyType.secp256k1:
aminoPrefix = pubkeyAminoPrefixSecp256k1;
break;
case pubkeyType.ed25519:
aminoPrefix = pubkeyAminoPrefixEd25519;
break;
default:
throw new Error("Unsupported pubkey type");
}
return new Uint8Array([...aminoPrefix, ...fromBase64(pubkey.value)]);
}
/**

View File

@ -8,9 +8,12 @@ export {
export {
MultisigThresholdPubkey,
Pubkey,
Ed25519Pubkey,
Secp256k1Pubkey,
SinglePubkey,
isMultisigThresholdPubkey,
isEd25519Pubkey,
isSecp256k1Pubkey,
isSinglePubkey,
pubkeyType,
} from "./pubkeys";

View File

@ -6,11 +6,24 @@ export interface Pubkey {
readonly value: any;
}
export interface Ed25519Pubkey extends SinglePubkey {
readonly type: "tendermint/PubKeyEd25519";
readonly value: string;
}
export function isEd25519Pubkey(pubkey: Pubkey): pubkey is Ed25519Pubkey {
return (pubkey as Ed25519Pubkey).type === "tendermint/PubKeyEd25519";
}
export interface Secp256k1Pubkey extends SinglePubkey {
readonly type: "tendermint/PubKeySecp256k1";
readonly value: string;
}
export function isSecp256k1Pubkey(pubkey: Pubkey): pubkey is Secp256k1Pubkey {
return (pubkey as Secp256k1Pubkey).type === "tendermint/PubKeySecp256k1";
}
export const pubkeyType = {
/** @see https://github.com/tendermint/tendermint/blob/v0.33.0/crypto/ed25519/ed25519.go#L22 */
secp256k1: "tendermint/PubKeySecp256k1" as const,