add `decompress-public-key.ts` (#336)

This commit is contained in:
Felicio Mununga 2023-02-10 10:09:42 +01:00 committed by GitHub
parent 691f90f81b
commit 72c58aacfc
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 40 additions and 0 deletions

View File

@ -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"`)
})

View File

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