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

75% Statements 12/16
50% Branches 1/2
66.66% Functions 2/3
75% Lines 12/16

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 274x 4x 4x 4x   4x   4x 10x     4x 11x 11x 11x     4x                  
import { hashSha256 } from 'micro-stacks/crypto-sha';
import { decode, encode, encodingLength } from './varuint';
import { utf8ToBytes } from '@noble/hashes/utils';
import { concatByteArrays } from 'micro-stacks/common';
 
const chainPrefix = '\x18Stacks Message Signing:\n';
 
export function hashMessage(message: string | Uint8Array) {
  return hashSha256(encodeMessage(message));
}
 
export function encodeMessage(message: string | Uint8Array): Uint8Array {
  const bytes = typeof message === 'string' ? utf8ToBytes(message) : message;
  const encoded = encode(bytes.length);
  return concatByteArrays([utf8ToBytes(chainPrefix), encoded, bytes]);
}
 
export function decodeMessage(encodedMessage: Uint8Array): Uint8Array {
  // Remove the chain prefix: 1 for the varint and 24 for the length of the string
  // 'Stacks Message Signing:\n'
  const messageWithoutChainPrefix = encodedMessage.subarray(1 + 24);
  const decoded = decode(messageWithoutChainPrefix);
  const varIntLength = encodingLength(decoded);
  // Remove the varuint prefix
  return messageWithoutChainPrefix.slice(varIntLength);
}