From 72c58aacfc7266b80b7deea967683bcdc6d915b3 Mon Sep 17 00:00:00 2001 From: Felicio Mununga Date: Fri, 10 Feb 2023 10:09:42 +0100 Subject: [PATCH] add `decompress-public-key.ts` (#336) --- .../src/utils/decompress-public-key.test.ts | 30 +++++++++++++++++++ .../src/utils/decompress-public-key.ts | 10 +++++++ 2 files changed, 40 insertions(+) create mode 100644 packages/status-js/src/utils/decompress-public-key.test.ts create mode 100644 packages/status-js/src/utils/decompress-public-key.ts diff --git a/packages/status-js/src/utils/decompress-public-key.test.ts b/packages/status-js/src/utils/decompress-public-key.test.ts new file mode 100644 index 0000000..8223cae --- /dev/null +++ b/packages/status-js/src/utils/decompress-public-key.test.ts @@ -0,0 +1,30 @@ +import * as secp from 'ethereum-cryptography/secp256k1' +import { bytesToHex } from 'ethereum-cryptography/utils' +import { expect, test } from 'vitest' + +import { decompressPublicKey } from './decompress-public-key' + +test('should return decompressed public key', () => { + const privateKey = secp.utils.randomPrivateKey() + + const publicKey = bytesToHex(secp.getPublicKey(privateKey)) + const compressedPublicKey = bytesToHex(secp.getPublicKey(privateKey, true)) + + expect(decompressPublicKey(compressedPublicKey)).toEqual(publicKey) +}) + +test('should accept public key with a base prefix', () => { + const privateKey = secp.utils.randomPrivateKey() + + const publicKey = bytesToHex(secp.getPublicKey(privateKey)) + const compressedPublicKey = + '0x' + bytesToHex(secp.getPublicKey(privateKey, true)) + + expect(decompressPublicKey(compressedPublicKey)).toEqual(publicKey) +}) + +test('should throw error if public key is not a valid hex', () => { + expect(() => { + decompressPublicKey('not a valid public key') + }).toThrowErrorMatchingInlineSnapshot(`"Invalid public key"`) +}) diff --git a/packages/status-js/src/utils/decompress-public-key.ts b/packages/status-js/src/utils/decompress-public-key.ts new file mode 100644 index 0000000..a0eb345 --- /dev/null +++ b/packages/status-js/src/utils/decompress-public-key.ts @@ -0,0 +1,10 @@ +import * as secp from 'ethereum-cryptography/secp256k1' + +export function decompressPublicKey(publicKey: string): string { + try { + const pk = publicKey.replace(/^0[xX]/, '') // ensures hexadecimal digits without "base prefix" + return secp.Point.fromHex(pk).toHex() + } catch (error) { + throw new Error('Invalid public key') + } +}