From a21fa2c22b4993e0829ae8c4622b418479a5905c Mon Sep 17 00:00:00 2001 From: BlowaterNostr Date: Wed, 14 Jun 2023 06:44:38 +0000 Subject: [PATCH] add PrivateKey.FromString method --- key.ts | 8 ++++++++ nip19.test.ts | 8 ++++++++ 2 files changed, 16 insertions(+) diff --git a/key.ts b/key.ts index 4f6a7a9..04a38ce 100644 --- a/key.ts +++ b/key.ts @@ -32,6 +32,14 @@ export class PrivateKey { return new Error(`${key} is not valid`); } + static FromString(raw: string) { + const key = PrivateKey.FromBech32(raw); + if (key instanceof Error) { + return PrivateKey.FromHex(raw); + } + return key; + } + public readonly bech32: string; public readonly hex: string; diff --git a/nip19.test.ts b/nip19.test.ts index ef13422..28b7784 100644 --- a/nip19.test.ts +++ b/nip19.test.ts @@ -56,4 +56,12 @@ Deno.test("nip19 private key", async (t) => { `Invalid checksum in nsec1alwevw7n7xxapp4g7c2v3l5qr7zkmxjrhlwqteh6rkh2527gm3qqgj3jh: expected "29r5am"`, ); }); + + await t.step("private key from string", () => { + const pri = PrivateKey.Generate(); + const pri_1 = PrivateKey.FromString(pri.bech32) as PrivateKey; + const pri_2 = PrivateKey.FromString(pri.hex) as PrivateKey; + assertEquals(pri_1.hex, pri_2.hex); + assertEquals(pri_1.bech32, pri_2.bech32); + }); });