All files / src/connect/message-signing verify.ts

92.15% Statements 47/51
93.33% Branches 14/15
85.71% Functions 6/7
91.48% Lines 43/47

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 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 1403x 3x 3x   3x   3x   3x     13x     13x 13x 13x 13x             3x       3x 9x     3x                 6x     3x 13x 13x     13x   13x           3x               11x 1x       10x 10x   10x 10x 10x         10x 4x   4x               4x   4x 1x     1x             9x             3x               3x 1x       2x         2x   2x                
import { recoverPublicKey, Signature, verify } from '@noble/secp256k1';
import { bytesToHex, hexToBigInt } from 'micro-stacks/common';
import { hashMessage } from './encoding';
 
import { getStructuredDataHashes, makeStructuredDataHash } from './structured-message';
import { StructuredSignatureRequestOptions } from './types';
import { c32addressDecode, publicKeyToStxAddress } from 'micro-stacks/crypto';
 
const COORDINATE_BYTES = 32;
 
function parseRecoverableSignatureVrs(signature: string) {
  Iif (signature.length < COORDINATE_BYTES * 2 * 2 + 1) {
    throw new Error('Invalid signature');
  }
  const recoveryIdHex = signature.slice(0, 2);
  const r = signature.slice(2, 2 + COORDINATE_BYTES * 2);
  const s = signature.slice(2 + COORDINATE_BYTES * 2);
  return {
    recoveryBytes: hexToBigInt(recoveryIdHex),
    r,
    s,
  };
}
 
export function signatureVrsToRsv(signature: string) {
  return signature.slice(2) + signature.slice(0, 2);
}
 
export function signatureRsvToVrs(signature: string) {
  return signature.slice(-2) + signature.slice(0, -2);
}
 
export const getPublicKeyFromSignature = ({
  hash,
  signature,
  recoveryBytes,
}: {
  hash: Uint8Array;
  signature: Signature;
  recoveryBytes: number | BigInt;
}) => {
  return recoverPublicKey(hash, signature, Number(recoveryBytes), true);
};
 
export const recoverSignature = (options: { signature: string; mode?: 'vrs' | 'rsv' }) => {
  const { signature, mode = 'rsv' } = options;
  const { r, s, recoveryBytes } = parseRecoverableSignatureVrs(
    mode === 'rsv' ? signatureRsvToVrs(signature) : signature
  );
  const sig = new Signature(hexToBigInt(r), hexToBigInt(s));
 
  return {
    signature: sig,
    recoveryBytes,
  };
};
 
export const verifyMessageSignature = (options: {
  // string = message, bytes = hash
  message: string | Uint8Array;
  signature: string;
  publicKey?: string;
  stxAddress?: string;
  mode?: 'vrs' | 'rsv';
}) => {
  if (!options.publicKey && !options.stxAddress)
    throw Error(
      '[micro-stacks/connect[ verifyMessageSignature -- You must pass `stxAddress` if you are recovering the public key from the signature'
    );
 
  const { message, mode = 'rsv' } = options;
  let publicKey = options.publicKey;
 
  try {
    const hash = typeof message === 'string' ? hashMessage(message) : message;
    const { signature, recoveryBytes } = recoverSignature({
      signature: options.signature,
      mode,
    });
 
    if (!publicKey) {
      const [version] = c32addressDecode(options.stxAddress!);
 
      publicKey = bytesToHex(
        getPublicKeyFromSignature({
          hash,
          signature,
          recoveryBytes,
        })
      );
 
      const publicKeyAddress = publicKeyToStxAddress(publicKey, version);
 
      if (publicKeyAddress !== options.stxAddress) {
        console.error(
          `[micro-stacks/connect] verifyMessageSignature Stacks address is not correct. expected: ${options.stxAddress}, received: ${publicKeyAddress}`
        );
        return false;
      }
    }
 
    // verify() is strict: true by default. High-s signatures are rejected, which mirrors libsecp behavior
    // Set verify options to strict: false, to support the legacy stacks implementations
    // Reference: https://github.com/paulmillr/noble-secp256k1/releases/tag/1.4.0
    return verify(signature, hash, publicKey, { strict: false });
  } catch (e) {
    console.error('[micro-stacks/connect] verifyMessageSignature failed', e);
    return false;
  }
};
 
export const verifyStructuredMessageSignature = (options: {
  message: StructuredSignatureRequestOptions['message'];
  domain: StructuredSignatureRequestOptions['domain'];
  signature: string;
  publicKey?: string;
  stxAddress?: string;
  mode?: 'vrs' | 'rsv';
}) => {
  if (!options.publicKey && !options.stxAddress)
    throw Error(
      '[micro-stacks/connect[ verifyStructuredMessageSignature -- You must pass `stxAddress` if you are recovering the public key from the signature'
    );
 
  const { domain, message } = getStructuredDataHashes({
    domain: options.domain,
    message: options.message,
  });
 
  const hashBytes = makeStructuredDataHash(domain, message);
 
  return verifyMessageSignature({
    message: hashBytes,
    signature: options.signature,
    publicKey: options.publicKey,
    stxAddress: options.stxAddress,
    mode: options.mode,
  });
};