UNPKG

@muirglacier/jellyfish-transaction

Version:

A collection of TypeScript + JavaScript tools and libraries for DeFi Blockchain developers to build decentralized finance for Bitcoin

96 lines 3.42 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.OP_PUSHDATA = void 0; const smart_buffer_1 = require("smart-buffer"); const opcode_1 = require("./opcode"); /** * These are opcode from 1-75, 76, 77, 78. * Effectively this opcode carry data. * * OP_CODE | HEX | DESCRIPTION * -------------|-------------|---------------------------------------------------------------------- * N/A | 0x01-0x4b | The next opcode bytes is data to be pushed onto the stack * OP_PUSHDATA1 | 0x4c | The next byte contains the number of bytes to be pushed onto the stack. * OP_PUSHDATA2 | 0x4d | The next 2 bytes contain the number of bytes to be pushed onto the stack in LE order. * OP_PUSHDATA4 | 0x4e | The next 4 bytes contain the number of bytes to be pushed onto the stack in LE order. * * OPCODE will automatically be appended in asBuffer(). * The constructor only accepts the bytes to be pushed in the stack. */ class OP_PUSHDATA extends opcode_1.OPCode { constructor(p1, p2) { super('OP_PUSHDATA'); if (Buffer.isBuffer(p1) && (p2 === 'little' || p2 === 'big')) { if (p2 === 'big') { this.hex = Buffer.from(p1).reverse().toString('hex'); } else { this.hex = Buffer.from(p1).toString('hex'); } return; } if (typeof p1 === 'number' && p2 instanceof smart_buffer_1.SmartBuffer) { const buff = OP_PUSHDATA.readData(p1, p2); this.hex = Buffer.from(buff).toString('hex'); return; } throw new Error('OP_PUSHDATA invalid constructor parameters'); } /** * Read data from buffer */ static readData(code, buffer) { if (code < 0x4c) { return buffer.readBuffer(code); } if (code === 0x4c) { return buffer.readBuffer(buffer.readUInt8()); } if (code === 0x4d) { return buffer.readBuffer(buffer.readUInt16LE()); } if (code === 0x4e) { return buffer.readBuffer(buffer.readUInt32LE()); } throw new RangeError(`OP_PUSHDATA ${code} is not between 0x01 or 0x4e inclusive`); } /** * Length of bytes */ length() { return this.hex.length / 2; } /** * @return [0x01-0x4e, [>0x4b ?? length], [push data]] */ asBuffer() { const buffer = new smart_buffer_1.SmartBuffer(); buffer.writeBuffer(OP_PUSHDATA.getLenOpBuffer(this.length())); buffer.writeString(this.hex, 'hex'); return buffer.toBuffer(); } static getLenOpBuffer(length) { const buffer = new smart_buffer_1.SmartBuffer(); if (length < 76) { buffer.writeUInt8(length); } else if (length <= 255) { buffer.writeUInt8(0x4c); buffer.writeUInt8(length); } else if (length <= 65535) { buffer.writeUInt8(0x4d); buffer.writeUInt16LE(length); } else if (length <= 16777215) { buffer.writeUInt8(0x4e); buffer.writeUInt32LE(length); } else { throw new RangeError('OP_PUSHDATA buffer is larger than 16777215'); } return buffer.toBuffer(); } } exports.OP_PUSHDATA = OP_PUSHDATA; //# sourceMappingURL=data.js.map