mirror of
https://github.com/status-im/dappconnect-chat-sdk.git
synced 2025-01-26 22:29:13 +00:00
add decompress-public-key.ts
(#336)
This commit is contained in:
parent
591a9c61bd
commit
587a0786ad
30
packages/status-js/src/utils/decompress-public-key.test.ts
Normal file
30
packages/status-js/src/utils/decompress-public-key.test.ts
Normal 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"`)
|
||||
})
|
10
packages/status-js/src/utils/decompress-public-key.ts
Normal file
10
packages/status-js/src/utils/decompress-public-key.ts
Normal 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')
|
||||
}
|
||||
}
|
Loading…
x
Reference in New Issue
Block a user