1 | 'use strict';
|
2 | Object.defineProperty(exports, '__esModule', { value: true });
|
3 | exports.decode = exports.encode = exports.encodingLength = void 0;
|
4 | const ops_1 = require('./ops');
|
5 | function encodingLength(i) {
|
6 | return i < ops_1.OPS.OP_PUSHDATA1 ? 1 : i <= 0xff ? 2 : i <= 0xffff ? 3 : 5;
|
7 | }
|
8 | exports.encodingLength = encodingLength;
|
9 | function encode(buffer, num, offset) {
|
10 | const size = encodingLength(num);
|
11 |
|
12 | if (size === 1) {
|
13 | buffer.writeUInt8(num, offset);
|
14 |
|
15 | } else if (size === 2) {
|
16 | buffer.writeUInt8(ops_1.OPS.OP_PUSHDATA1, offset);
|
17 | buffer.writeUInt8(num, offset + 1);
|
18 |
|
19 | } else if (size === 3) {
|
20 | buffer.writeUInt8(ops_1.OPS.OP_PUSHDATA2, offset);
|
21 | buffer.writeUInt16LE(num, offset + 1);
|
22 |
|
23 | } else {
|
24 | buffer.writeUInt8(ops_1.OPS.OP_PUSHDATA4, offset);
|
25 | buffer.writeUInt32LE(num, offset + 1);
|
26 | }
|
27 | return size;
|
28 | }
|
29 | exports.encode = encode;
|
30 | function decode(buffer, offset) {
|
31 | const opcode = buffer.readUInt8(offset);
|
32 | let num;
|
33 | let size;
|
34 |
|
35 | if (opcode < ops_1.OPS.OP_PUSHDATA1) {
|
36 | num = opcode;
|
37 | size = 1;
|
38 |
|
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 |
|
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 |
|
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 | }
|
61 | exports.decode = decode;
|