add `decompress-public-key.ts` (#336)
This commit is contained in:
parent
591a9c61bd
commit
587a0786ad
|
@ -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"`)
|
||||||
|
})
|
|
@ -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')
|
||||||
|
}
|
||||||
|
}
|
Loading…
Reference in New Issue