1 | 'use strict';
|
2 | Object.defineProperty(exports, '__esModule', { value: true });
|
3 | const types = require('./types');
|
4 | const bip66 = require('bip66');
|
5 | const typeforce = require('typeforce');
|
6 | const ZERO = Buffer.alloc(1, 0);
|
7 | function toDER(x) {
|
8 | let i = 0;
|
9 | while (x[i] === 0) ++i;
|
10 | if (i === x.length) return ZERO;
|
11 | x = x.slice(i);
|
12 | if (x[0] & 0x80) return Buffer.concat([ZERO, x], 1 + x.length);
|
13 | return x;
|
14 | }
|
15 | function fromDER(x) {
|
16 | if (x[0] === 0x00) x = x.slice(1);
|
17 | const buffer = Buffer.alloc(32, 0);
|
18 | const bstart = Math.max(0, 32 - x.length);
|
19 | x.copy(buffer, bstart);
|
20 | return buffer;
|
21 | }
|
22 |
|
23 | function decode(buffer) {
|
24 | const hashType = buffer.readUInt8(buffer.length - 1);
|
25 | const hashTypeMod = hashType & ~0x80;
|
26 | if (hashTypeMod <= 0 || hashTypeMod >= 4)
|
27 | throw new Error('Invalid hashType ' + hashType);
|
28 | const decoded = bip66.decode(buffer.slice(0, -1));
|
29 | const r = fromDER(decoded.r);
|
30 | const s = fromDER(decoded.s);
|
31 | const signature = Buffer.concat([r, s], 64);
|
32 | return { signature, hashType };
|
33 | }
|
34 | exports.decode = decode;
|
35 | function encode(signature, hashType) {
|
36 | typeforce(
|
37 | {
|
38 | signature: types.BufferN(64),
|
39 | hashType: types.UInt8,
|
40 | },
|
41 | { signature, hashType },
|
42 | );
|
43 | const hashTypeMod = hashType & ~0x80;
|
44 | if (hashTypeMod <= 0 || hashTypeMod >= 4)
|
45 | throw new Error('Invalid hashType ' + hashType);
|
46 | const hashTypeBuffer = Buffer.allocUnsafe(1);
|
47 | hashTypeBuffer.writeUInt8(hashType, 0);
|
48 | const r = toDER(signature.slice(0, 32));
|
49 | const s = toDER(signature.slice(32, 64));
|
50 | return Buffer.concat([bip66.encode(r, s), hashTypeBuffer]);
|
51 | }
|
52 | exports.encode = encode;
|