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') + } +}