UNPKG

939 BJavaScriptView Raw
1import { secp256k1 } from '@noble/curves/secp256k1';
2import { bnToU8a, hasBigInt, u8aConcat } from '@polkadot/util';
3import { isReady, secp256k1Sign as wasm } from '@polkadot/wasm-crypto';
4import { BN_BE_256_OPTS } from '../bn.js';
5import { hasher } from './hasher.js';
6/**
7 * @name secp256k1Sign
8 * @description Returns message signature of `message`, using the supplied pair
9 */
10export function secp256k1Sign(message, { secretKey }, hashType = 'blake2', onlyJs) {
11 if (secretKey?.length !== 32) {
12 throw new Error('Expected valid secp256k1 secretKey, 32-bytes');
13 }
14 const data = hasher(hashType, message, onlyJs);
15 if (!hasBigInt || (!onlyJs && isReady())) {
16 return wasm(data, secretKey);
17 }
18 const signature = secp256k1.sign(data, secretKey, { lowS: true });
19 return u8aConcat(bnToU8a(signature.r, BN_BE_256_OPTS), bnToU8a(signature.s, BN_BE_256_OPTS), new Uint8Array([signature.recovery || 0]));
20}