UNPKG

1.04 kBJavaScriptView Raw
1import { secp256k1 } from '@noble/curves/secp256k1';
2import { hasBigInt, u8aToU8a } from '@polkadot/util';
3import { isReady, secp256k1Recover as wasm } from '@polkadot/wasm-crypto';
4import { secp256k1Compress } from './compress.js';
5import { secp256k1Expand } from './expand.js';
6/**
7 * @name secp256k1Recover
8 * @description Recovers a publicKey from the supplied signature
9 */
10export function secp256k1Recover(msgHash, signature, recovery, hashType = 'blake2', onlyJs) {
11 const sig = u8aToU8a(signature).subarray(0, 64);
12 const msg = u8aToU8a(msgHash);
13 const publicKey = !hasBigInt || (!onlyJs && isReady())
14 ? wasm(msg, sig, recovery)
15 : secp256k1.Signature
16 .fromCompact(sig)
17 .addRecoveryBit(recovery)
18 .recoverPublicKey(msg)
19 .toRawBytes();
20 if (!publicKey) {
21 throw new Error('Unable to recover publicKey from signature');
22 }
23 return hashType === 'keccak'
24 ? secp256k1Expand(publicKey, onlyJs)
25 : secp256k1Compress(publicKey, onlyJs);
26}