|
| 1 | +import { decodeMessage, encodeMessage, hashMessage } from '../src/messageSignature'; |
| 2 | + |
| 3 | +test('encodeMessage / decodeMessage', () => { |
| 4 | + // array of messages and their expected encoded message |
| 5 | + const messages = [ |
| 6 | + ['hello world', '\x18Stacks Message Signing:\n\x0bhello world'], |
| 7 | + ['', '\x18Stacks Message Signing:\n\x00'], |
| 8 | + // Longer message (to test a different length for the var_int prefix) |
| 9 | + ['This is a really long message to test the var_int prefix This is a really long message to test the var_int prefix This is a really long message to test the var_int prefix This is a really long message to test the var_int prefix This is a really long message to test the var_int prefix', |
| 10 | + Buffer.concat([ |
| 11 | + Buffer.from('\x18Stacks Message Signing:\n'), |
| 12 | + // message length = 284 (decimal) = 011c (hex) <=> \x1c\x01 (little endian encoding) |
| 13 | + // Since length = 284 is < 0xFFFF, prefix the int with 0xFD followed by 2 bytes for a total of 3 bytes (see https://en.bitcoin.it/wiki/Protocol_documentation#Variable_length_integer) |
| 14 | + Buffer.from(new Uint8Array([253, 28, 1])), |
| 15 | + Buffer.from('This is a really long message to test the var_int prefix This is a really long message to test the var_int prefix This is a really long message to test the var_int prefix This is a really long message to test the var_int prefix This is a really long message to test the var_int prefix') |
| 16 | + ])], |
| 17 | + ] |
| 18 | + for (let messageArr of messages) { |
| 19 | + const [message, expectedEncodedMessage] = messageArr; |
| 20 | + const encodedMessage = encodeMessage(message); |
| 21 | + expect(encodedMessage.equals(Buffer.from(expectedEncodedMessage))).toBeTruthy(); |
| 22 | + const decodedMessage = decodeMessage(encodedMessage); |
| 23 | + expect(decodedMessage.toString()).toEqual(message); |
| 24 | + } |
| 25 | + |
| 26 | + |
| 27 | +}); |
| 28 | + |
| 29 | +test('hash message vs hash of manually constructed message', () => { |
| 30 | + // echo -n '\x18Stacks Message Signing:\n\x0bhello world' | openssl dgst -sha256 |
| 31 | + // 664d1478d36935361c1a8eda75fce73c49a93b58e55ed7cb45c3860317814991 |
| 32 | + |
| 33 | + const message1 = 'hello world'; |
| 34 | + const hash1 = hashMessage(message1); |
| 35 | + const expectedHash = '664d1478d36935361c1a8eda75fce73c49a93b58e55ed7cb45c3860317814991'; |
| 36 | + expect(hash1.length).toEqual(32); // 32 bytes of sha256 |
| 37 | + expect(hash1.toString('hex')).toEqual(expectedHash); |
| 38 | +}); |
0 commit comments