UNPKG

1.73 kBJavaScriptView Raw
1'use strict';
2Object.defineProperty(exports, '__esModule', { value: true });
3exports.decode = exports.encode = exports.encodingLength = void 0;
4const ops_1 = require('./ops');
5function encodingLength(i) {
6 return i < ops_1.OPS.OP_PUSHDATA1 ? 1 : i <= 0xff ? 2 : i <= 0xffff ? 3 : 5;
7}
8exports.encodingLength = encodingLength;
9function encode(buffer, num, offset) {
10 const size = encodingLength(num);
11 // ~6 bit
12 if (size === 1) {
13 buffer.writeUInt8(num, offset);
14 // 8 bit
15 } else if (size === 2) {
16 buffer.writeUInt8(ops_1.OPS.OP_PUSHDATA1, offset);
17 buffer.writeUInt8(num, offset + 1);
18 // 16 bit
19 } else if (size === 3) {
20 buffer.writeUInt8(ops_1.OPS.OP_PUSHDATA2, offset);
21 buffer.writeUInt16LE(num, offset + 1);
22 // 32 bit
23 } else {
24 buffer.writeUInt8(ops_1.OPS.OP_PUSHDATA4, offset);
25 buffer.writeUInt32LE(num, offset + 1);
26 }
27 return size;
28}
29exports.encode = encode;
30function decode(buffer, offset) {
31 const opcode = buffer.readUInt8(offset);
32 let num;
33 let size;
34 // ~6 bit
35 if (opcode < ops_1.OPS.OP_PUSHDATA1) {
36 num = opcode;
37 size = 1;
38 // 8 bit
39 } else if (opcode === ops_1.OPS.OP_PUSHDATA1) {
40 if (offset + 2 > buffer.length) return null;
41 num = buffer.readUInt8(offset + 1);
42 size = 2;
43 // 16 bit
44 } else if (opcode === ops_1.OPS.OP_PUSHDATA2) {
45 if (offset + 3 > buffer.length) return null;
46 num = buffer.readUInt16LE(offset + 1);
47 size = 3;
48 // 32 bit
49 } else {
50 if (offset + 5 > buffer.length) return null;
51 if (opcode !== ops_1.OPS.OP_PUSHDATA4) throw new Error('Unexpected opcode');
52 num = buffer.readUInt32LE(offset + 1);
53 size = 5;
54 }
55 return {
56 opcode,
57 number: num,
58 size,
59 };
60}
61exports.decode = decode;