Add encodeBech32Pubkey

This commit is contained in:
Simon Warta 2020-02-09 13:27:53 +01:00
parent b2fcb0b105
commit af5e5a76a9
5 changed files with 33 additions and 3 deletions

View File

@ -7,4 +7,4 @@ export { unmarshalTx } from "./decoding";
export { encodeSecp256k1Signature, makeSignBytes, marshalTx } from "./encoding";
export { RestClient, TxsResponse } from "./restclient";
export { makeCosmoshubPath, Pen, PrehashType, Secp256k1Pen } from "./pen";
export { decodeBech32Pubkey, encodeSecp256k1Pubkey } from "./pubkey";
export { decodeBech32Pubkey, encodeBech32Pubkey, encodeSecp256k1Pubkey } from "./pubkey";

View File

@ -1,6 +1,7 @@
import { Encoding } from "@iov/encoding";
import { decodeBech32Pubkey, encodeSecp256k1Pubkey } from "./pubkey";
import { decodeBech32Pubkey, encodeBech32Pubkey, encodeSecp256k1Pubkey } from "./pubkey";
import { PubKey } from "./types";
const { fromBase64 } = Encoding;
@ -35,4 +36,16 @@ describe("pubkey", () => {
});
});
});
describe("encodeBech32Pubkey", () => {
it("works for secp256k1", () => {
const pubkey: PubKey = {
type: "tendermint/PubKeySecp256k1",
value: "A08EGB7ro1ORuFhjOnZcSgwYlpe0DSFjVNUIkNNQxwKQ",
};
expect(encodeBech32Pubkey(pubkey, "cosmospub")).toEqual(
"cosmospub1addwnpepqd8sgxq7aw348ydctp3n5ajufgxp395hksxjzc6565yfp56scupfqhlgyg5",
);
});
});
});

View File

@ -60,3 +60,18 @@ export function decodeBech32Pubkey(bech: Bech32PubKey): PubKey {
throw new Error("Unsupported Pubkey type. Amino prefix: " + Encoding.toHex(aminoPrefix));
}
}
export function encodeBech32Pubkey(pubkey: PubKey, prefix: CosmosPubkeyBech32Prefix): Bech32PubKey {
let aminoPrefix: Uint8Array;
switch (pubkey.type) {
// Note: please don't add cases here without writing additional unit tests
case pubkeyType.secp256k1:
aminoPrefix = pubkeyAminoPrefixSecp256k1;
break;
default:
throw new Error("Unsupported pubkey type");
}
const data = new Uint8Array([...aminoPrefix, ...Encoding.fromBase64(pubkey.value)]);
return Bech32.encode(prefix, data);
}

View File

@ -6,4 +6,4 @@ export { unmarshalTx } from "./decoding";
export { encodeSecp256k1Signature, makeSignBytes, marshalTx } from "./encoding";
export { RestClient, TxsResponse } from "./restclient";
export { makeCosmoshubPath, Pen, PrehashType, Secp256k1Pen } from "./pen";
export { decodeBech32Pubkey, encodeSecp256k1Pubkey } from "./pubkey";
export { decodeBech32Pubkey, encodeBech32Pubkey, encodeSecp256k1Pubkey } from "./pubkey";

View File

@ -1,3 +1,5 @@
import { CosmosPubkeyBech32Prefix } from "./address";
import { Bech32PubKey, PubKey } from "./types";
export declare function encodeSecp256k1Pubkey(pubkey: Uint8Array): PubKey;
export declare function decodeBech32Pubkey(bech: Bech32PubKey): PubKey;
export declare function encodeBech32Pubkey(pubkey: PubKey, prefix: CosmosPubkeyBech32Prefix): Bech32PubKey;