All files / src/crypto public-key.ts

52.94% Statements 9/17
0% Branches 0/7
0% Functions 0/4
45.45% Lines 5/11

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 2742x 42x       42x         42x                           42x    
import { CURVE, Point } from '@noble/secp256k1';
import { bytesToBigInt, bytesToHex, intToBytes } from 'micro-stacks/common';
 
export { getPublicKey } from '@noble/secp256k1';
 
export const isCompressedPublicKey = (bytes: Uint8Array) => {
  const header = bytes[0];
  return bytes.length === 32 || (bytes.length === 33 && (header === 0x02 || header === 0x03));
};
 
export const derivePublicKey = (pubKey: Uint8Array, il: Uint8Array) => {
  const publicKeyPoint = Point.fromHex(bytesToHex(pubKey));
  const ecCurvePoint = new Point(CURVE.Gx, CURVE.Gy)
    .multiply(bytesToBigInt(il))
    .add(publicKeyPoint);
 
  return ecCurvePoint.toRawBytes(isCompressedPublicKey(pubKey));
};
 
function mod(a: bigint, b: bigint = CURVE.P): bigint {
  const result = a % b;
  return result >= 0 ? result : b + result;
}
 
export const derivePrivateKey = (privateKey: Uint8Array, il: Uint8Array) =>
  intToBytes(mod(bytesToBigInt(il) + bytesToBigInt(privateKey), CURVE.n), false, 32);