UNPKG

1.69 kBJavaScriptView Raw
1'use strict';
2Object.defineProperty(exports, '__esModule', { value: true });
3const types = require('./types');
4const bip66 = require('bip66');
5const typeforce = require('typeforce');
6const ZERO = Buffer.alloc(1, 0);
7function 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}
15function 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// BIP62: 1 byte hashType flag (only 0x01, 0x02, 0x03, 0x81, 0x82 and 0x83 are allowed)
23function 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}
34exports.decode = decode;
35function 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}
52exports.encode = encode;