Skip to content

Commit

Permalink
add PrivateKey.FromString method
Browse files Browse the repository at this point in the history
  • Loading branch information
BlowaterNostr committed Jun 14, 2023
1 parent 9548577 commit a21fa2c
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 0 deletions.
8 changes: 8 additions & 0 deletions key.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;

Expand Down
8 changes: 8 additions & 0 deletions nip19.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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);
});
});

0 comments on commit a21fa2c

Please sign in to comment.