/
messageSignature.ts
27 lines (23 loc) · 1.12 KB
/
messageSignature.ts
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
import { sha256 } from '@noble/hashes/sha256';
import { Buffer } from '@stacks/common';
import { decode, encode, encodingLength } from 'varuint-bitcoin';
// 'Stacks Signed Message:\n'.length === 23
// 'Stacks Signed Message:\n'.length.toString(16) === 17
const chainPrefix = '\x17Stacks Signed Message:\n';
export function hashMessage(message: string): Buffer {
return Buffer.from(sha256(encodeMessage(message)));
}
export function encodeMessage(message: string | Buffer): Buffer {
const encoded = encode(Buffer.from(message).length);
return Buffer.concat([Buffer.from(chainPrefix), encoded, Buffer.from(message)]);
}
export function decodeMessage(encodedMessage: Buffer): Buffer {
// Remove the chain prefix: 1 for the varuint and 23 for the length of the string
// 'Stacks Signed Message:\n'
const prefixByteLength = Buffer.from(chainPrefix, 'utf8').byteLength;
const messageWithoutChainPrefix = encodedMessage.subarray(prefixByteLength);
const decoded = decode(messageWithoutChainPrefix);
const varIntLength = encodingLength(decoded);
// Remove the varint prefix
return messageWithoutChainPrefix.slice(varIntLength);
}