UNPKG

libnexa-ts

Version:

A pure and powerful Nexa SDK library.

1,317 lines (1,255 loc) 319 kB
import $hgUW1$crypto from "crypto"; import {isString as $hgUW1$isString, isNumber as $hgUW1$isNumber, isUndefined as $hgUW1$isUndefined, isObject as $hgUW1$isObject, isNil as $hgUW1$isNil, isInteger as $hgUW1$isInteger, isArray as $hgUW1$isArray, inRange as $hgUW1$inRange, isNull as $hgUW1$isNull, isEmpty as $hgUW1$isEmpty, isDate as $hgUW1$isDate} from "lodash-es"; import $hgUW1$bnjs from "bn.js"; import $hgUW1$jsbigdecimal from "js-big-decimal"; import $hgUW1$elliptic from "elliptic"; import $hgUW1$bs58 from "bs58"; var $parcel$global = globalThis; var $df64573ef6d51081$exports = {}; $df64573ef6d51081$exports = JSON.parse("{\"name\":\"libnexa-ts\",\"version\":\"1.0.6\",\"description\":\"A pure and powerful Nexa SDK library.\",\"type\":\"module\",\"source\":\"src/index.ts\",\"types\":\"dist/index.d.ts\",\"main\":\"dist/index.cjs\",\"module\":\"dist/index.mjs\",\"browser\":\"dist/index.web.mjs\",\"exports\":{\"types\":\"./dist/index.d.ts\",\"node\":{\"import\":\"./dist/index.mjs\",\"require\":\"./dist/index.cjs\"},\"browser\":\"./dist/index.web.mjs\",\"default\":\"./dist/index.mjs\"},\"targets\":{\"main\":{\"context\":\"node\",\"outputFormat\":\"commonjs\",\"distDir\":\"dist\",\"isLibrary\":true,\"includeNodeModules\":[\"lodash-es\"]},\"module\":{\"context\":\"node\",\"outputFormat\":\"esmodule\",\"distDir\":\"dist\",\"isLibrary\":true},\"browser\":{\"context\":\"browser\",\"outputFormat\":\"esmodule\",\"distDir\":\"dist\",\"isLibrary\":true}},\"files\":[\"dist\"],\"scripts\":{\"check\":\"tsc --noEmit && npm run madge\",\"build\":\"del-cli ./dist && parcel build\",\"lint\":\"eslint .\",\"madge\":\"madge --circular src/index.ts\",\"test\":\"vitest run --dir tests\",\"coverage\":\"del-cli ./coverage && npm test -- --coverage --reporter=verbose --reporter=junit\",\"docs\":\"typedoc\"},\"keywords\":[\"nexa\",\"blockchain\"],\"repository\":{\"type\":\"git\",\"url\":\"https://gitlab.com/nexa/libnexa-ts\"},\"author\":\"vgrunner\",\"license\":\"MIT\",\"dependencies\":{\"bn.js\":\"^5.2.2\",\"bs58\":\"^6.0.0\",\"elliptic\":\"^6.6.1\",\"js-big-decimal\":\"^2.2.0\",\"lodash-es\":\"^4.17.21\"},\"devDependencies\":{\"@parcel/packager-ts\":\"^2.15.4\",\"@parcel/transformer-typescript-types\":\"^2.15.4\",\"@types/bn.js\":\"^5.2.0\",\"@types/elliptic\":\"^6.4.18\",\"@types/lodash-es\":\"^4.17.12\",\"@types/node\":\"^24.0.8\",\"@vitest/coverage-v8\":\"^3.2.4\",\"del-cli\":\"^6.0.0\",\"eslint\":\"^9.30.0\",\"madge\":\"^8.0.0\",\"parcel\":\"^2.15.4\",\"typedoc\":\"^0.28.7\",\"typedoc-plugin-markdown\":\"^4.7.0\",\"typedoc-plugin-rename-defaults\":\"^0.7.3\",\"typescript\":\"^5.8.3\",\"typescript-eslint\":\"^8.35.1\",\"vitest\":\"^3.0.6\"},\"@parcel/resolver-default\":{\"packageExports\":true},\"madge\":{\"detectiveOptions\":{\"ts\":{\"skipTypeImports\":true}}}}"); class $e44f707fde477092$export$2e2bcd8739ae039 { static validateState(condition, message) { if (!condition) throw new Error(`Invalid State: ${message}`); } static validateArgument(condition, argumentName, message = "") { if (!condition) throw new Error(`Invalid Argument: ${argumentName}. ${message}`); } static validateArgumentType(argument, type, argumentName) { argumentName = argumentName || '(unknown name)'; if ((0, $hgUW1$isString)(type)) { if (type === 'Buffer') { if (!Buffer.isBuffer(argument)) throw new TypeError(`Invalid Argument for ${argumentName}, expected ${type} but got ${typeof argument}`); } else if (typeof argument !== type) throw new TypeError(`Invalid Argument for ${argumentName}, expected ${type} but got ${typeof argument}`); } else { if (!(argument instanceof type)) throw new TypeError(`Invalid Argument for ${argumentName}, expected ${type} but got ${typeof argument}`); } } } class $9f918c10ad4fef51$export$2e2bcd8739ae039 { /** * Fill a buffer with a value. * * @param buffer * @param value * @return filled buffer * * @deprecated use `buffer.fill(value)` */ static fill(buffer, value) { (0, $e44f707fde477092$export$2e2bcd8739ae039).validateArgumentType(buffer, 'Buffer', 'buffer'); (0, $e44f707fde477092$export$2e2bcd8739ae039).validateArgumentType(value, 'number', 'value'); return buffer.fill(value); } /** * * @param original buffer * @return Return a copy of a buffer * * @deprecated use `Buffer.from(original) or Buffer.copyBytesFrom(original)` */ static copy(original) { let buffer = Buffer.alloc(original.length); original.copy(buffer); return buffer; } /** * Tests for both node's Buffer and Uint8Array * * @param arg * @return Returns true if the given argument is an instance of a buffer. */ static isBuffer(arg) { return Buffer.isBuffer(arg) || arg instanceof Uint8Array; } /** * Tests for both node's Buffer and Uint8Array * * @param arg * @return Returns true if the given argument is an instance of a hash160 or hash256 buffer. */ static isHashBuffer(arg) { return this.isBuffer(arg) && (arg.length === 20 || arg.length === 32); } /** * Returns a zero-filled byte array * * @param length * * @deprecated use `Buffer.alloc(length)` */ static emptyBuffer(length) { (0, $e44f707fde477092$export$2e2bcd8739ae039).validateArgumentType(length, 'number', 'length'); return Buffer.alloc(length); } /** * Reverse a buffer * @param param * @return new reversed buffer */ static reverse(param) { return Buffer.from(param).reverse(); } /** * Transforms a buffer into a string with a number in hexa representation * * Shorthand for <tt>buffer.toString('hex')</tt> * * @param buffer * @return string */ static bufferToHex(buffer) { (0, $e44f707fde477092$export$2e2bcd8739ae039).validateArgumentType(buffer, 'Buffer', 'buffer'); return buffer.toString('hex'); } /** * Transforms a number from 0 to 255 into a Buffer of size 1 with that value * * @param integer * @return Buffer */ static integerAsSingleByteBuffer(integer) { (0, $e44f707fde477092$export$2e2bcd8739ae039).validateArgumentType(integer, 'number', 'integer'); return Buffer.from([ integer & 0xff ]); } /** * Transforms the first byte of an array into a number ranging from -128 to 127 * * @param buffer * @return number */ static integerFromSingleByteBuffer(buffer) { (0, $e44f707fde477092$export$2e2bcd8739ae039).validateArgumentType(buffer, 'Buffer', 'buffer'); return buffer[0]; } /** * Transform a 4-byte integer into a Buffer of length 4. * * @param integer * @return Buffer */ static integerAsBuffer(integer) { (0, $e44f707fde477092$export$2e2bcd8739ae039).validateArgumentType(integer, 'number', 'integer'); let bytes = []; bytes.push(integer >> 24 & 0xff); bytes.push(integer >> 16 & 0xff); bytes.push(integer >> 8 & 0xff); bytes.push(integer & 0xff); return Buffer.from(bytes); } /** * Transform the first 4 values of a Buffer into a number, in little endian encoding * * @param buffer * @return integer */ static integerFromBuffer(buffer) { (0, $e44f707fde477092$export$2e2bcd8739ae039).validateArgumentType(buffer, 'Buffer', 'buffer'); return buffer[0] << 24 | buffer[1] << 16 | buffer[2] << 8 | buffer[3]; } /* secure random bytes that sometimes throws an error due to lack of entropy */ static getRandomBuffer(size) { return (0, $hgUW1$crypto).randomBytes(size); } } var $62ca61b6ba036e1b$var$SHA_BLOCKSIZE = /*#__PURE__*/ function(SHA_BLOCKSIZE) { SHA_BLOCKSIZE[SHA_BLOCKSIZE["SHA256"] = 512] = "SHA256"; SHA_BLOCKSIZE[SHA_BLOCKSIZE["SHA512"] = 1024] = "SHA512"; return SHA_BLOCKSIZE; }($62ca61b6ba036e1b$var$SHA_BLOCKSIZE || {}); class $62ca61b6ba036e1b$export$2e2bcd8739ae039 { static sha1(buf) { (0, $e44f707fde477092$export$2e2bcd8739ae039).validateArgument((0, $9f918c10ad4fef51$export$2e2bcd8739ae039).isBuffer(buf), "buf", "Must be Buffer"); return (0, $hgUW1$crypto).createHash('sha1').update(buf).digest(); } static sha256(buf) { (0, $e44f707fde477092$export$2e2bcd8739ae039).validateArgument((0, $9f918c10ad4fef51$export$2e2bcd8739ae039).isBuffer(buf), "buf", "Must be Buffer"); return (0, $hgUW1$crypto).createHash('sha256').update(buf).digest(); } static sha512(buf) { (0, $e44f707fde477092$export$2e2bcd8739ae039).validateArgument((0, $9f918c10ad4fef51$export$2e2bcd8739ae039).isBuffer(buf), "buf", "Must be Buffer"); return (0, $hgUW1$crypto).createHash('sha512').update(buf).digest(); } static ripemd160(buf) { (0, $e44f707fde477092$export$2e2bcd8739ae039).validateArgument((0, $9f918c10ad4fef51$export$2e2bcd8739ae039).isBuffer(buf), "buf", "Must be Buffer"); return (0, $hgUW1$crypto).createHash('ripemd160').update(buf).digest(); } static sha256sha256(buf) { (0, $e44f707fde477092$export$2e2bcd8739ae039).validateArgument((0, $9f918c10ad4fef51$export$2e2bcd8739ae039).isBuffer(buf), "buf", "Must be Buffer"); return this.sha256(this.sha256(buf)); } static sha256ripemd160(buf) { (0, $e44f707fde477092$export$2e2bcd8739ae039).validateArgument((0, $9f918c10ad4fef51$export$2e2bcd8739ae039).isBuffer(buf), "buf", "Must be Buffer"); return this.ripemd160(this.sha256(buf)); } static sha256hmac(data, key) { return $62ca61b6ba036e1b$export$2e2bcd8739ae039.hmac($62ca61b6ba036e1b$export$2e2bcd8739ae039.sha256, 512, data, key); } static sha512hmac(data, key) { return $62ca61b6ba036e1b$export$2e2bcd8739ae039.hmac($62ca61b6ba036e1b$export$2e2bcd8739ae039.sha512, 1024, data, key); } static hmac(hashf, size, data, key) { //http://en.wikipedia.org/wiki/Hash-based_message_authentication_code //http://tools.ietf.org/html/rfc4868#section-2 (0, $e44f707fde477092$export$2e2bcd8739ae039).validateArgument((0, $9f918c10ad4fef51$export$2e2bcd8739ae039).isBuffer(data), "data", "Must be Buffer"); (0, $e44f707fde477092$export$2e2bcd8739ae039).validateArgument((0, $9f918c10ad4fef51$export$2e2bcd8739ae039).isBuffer(key), "key", "Must be Buffer"); let blocksize = size / 8; if (key.length > blocksize) key = hashf(key); else if (key.length < blocksize) { let fill = Buffer.alloc(blocksize); fill.fill(0); key.copy(fill); key = fill; } let o_key = Buffer.alloc(blocksize); o_key.fill(0x5c); let i_key = Buffer.alloc(blocksize); i_key.fill(0x36); let o_key_pad = Buffer.alloc(blocksize); let i_key_pad = Buffer.alloc(blocksize); for(let i = 0; i < blocksize; i++){ o_key_pad[i] = o_key[i] ^ key[i]; i_key_pad[i] = i_key[i] ^ key[i]; } return hashf(Buffer.concat([ o_key_pad, hashf(Buffer.concat([ i_key_pad, data ])) ])); } } class $c337f7a9455509cf$export$2e2bcd8739ae039 { /** * Determines whether a string contains only hexadecimal values * * @param value * @returns true if the string is the hexa representation of a number */ static isHexa(value) { return (0, $hgUW1$isString)(value) && value.length % 2 === 0 && /^[0-9a-fA-F]+$/.test(value); } /** * Test if an argument is a valid JSON object. If it is, returns a truthy * value (the json object decoded), so no double JSON.parse call is necessary * * @param arg * @return false if the argument is not a JSON string. */ static isValidJSON(arg) { if (!(0, $hgUW1$isString)(arg)) return false; try { return JSON.parse(arg); } catch { return false; } } static cloneArray(array) { return [ ...array ]; } /** * Checks that a value is a natural number. * * @param value * @return true if a positive integer or zero. */ static isNaturalNumber(value) { return typeof value === 'number' && isFinite(value) && Math.floor(value) === value && value >= 0; } /** * Checks that a value is a natural number. * * @param value * @return true if a positive integer or zero. */ static isNaturalBigInt(value) { return typeof value === 'bigint' && value >= 0n; } } class $5aa97aebe18a7924$export$2e2bcd8739ae039 extends (0, $hgUW1$bnjs) { static{ this.Zero = new $5aa97aebe18a7924$export$2e2bcd8739ae039(0); } static{ this.One = new $5aa97aebe18a7924$export$2e2bcd8739ae039(1); } static{ this.Minus1 = new $5aa97aebe18a7924$export$2e2bcd8739ae039(-1); } static fromNumber(num) { (0, $e44f707fde477092$export$2e2bcd8739ae039).validateArgument((0, $hgUW1$isNumber)(num), "num"); return new $5aa97aebe18a7924$export$2e2bcd8739ae039(num); } static fromBigInt(num) { (0, $e44f707fde477092$export$2e2bcd8739ae039).validateArgument(typeof num === 'bigint', "num"); return new $5aa97aebe18a7924$export$2e2bcd8739ae039(num.toString()); } static fromString(str, base) { (0, $e44f707fde477092$export$2e2bcd8739ae039).validateArgument((0, $hgUW1$isString)(str), "str"); return new $5aa97aebe18a7924$export$2e2bcd8739ae039(str, base); } static fromBuffer(buf, opts) { (0, $e44f707fde477092$export$2e2bcd8739ae039).validateArgument((0, $9f918c10ad4fef51$export$2e2bcd8739ae039).isBuffer(buf), "buf"); if (opts?.endian === 'little') buf = (0, $9f918c10ad4fef51$export$2e2bcd8739ae039).reverse(buf); return new $5aa97aebe18a7924$export$2e2bcd8739ae039(buf.toString('hex'), 16); } /** * Create a BN from a "ScriptNum": * This is analogous to the constructor for CScriptNum in nexad. Many ops in * nexad's script interpreter use CScriptNum, which is not really a proper * bignum. Instead, an error is thrown if trying to input a number bigger than * 4 bytes. We copy that behavior here. A third argument, `size`, is provided to * extend the hard limit of 4 bytes, as some usages require more than 4 bytes. */ static fromScriptNumBuffer(buf, fRequireMinimal, size) { let nMaxNumSize = size || 4; (0, $e44f707fde477092$export$2e2bcd8739ae039).validateArgument(buf.length <= nMaxNumSize, 'script number overflow'); if (fRequireMinimal && buf.length > 0) // Check that the number is encoded with the minimum possible // number of bytes. // // If the most-significant-byte - excluding the sign bit - is zero // then we're not minimal. Note how this test also rejects the // negative-zero encoding, 0x80. { if ((buf[buf.length - 1] & 0x7f) === 0) { // One exception: if there's more than one byte and the most // significant bit of the second-most-significant-byte is set // it would conflict with the sign bit. An example of this case // is +-255, which encode to 0xff00 and 0xff80 respectively. // (big-endian). if (buf.length <= 1 || (buf[buf.length - 2] & 0x80) === 0) throw new Error('non-minimally encoded script number'); } } return $5aa97aebe18a7924$export$2e2bcd8739ae039.fromSM(buf, { endian: 'little' }); } // Override arithmetic methods to ensure they return BNExtended instances add(b) { const result = super.add(b).toString(); return new $5aa97aebe18a7924$export$2e2bcd8739ae039(result); } sub(b) { const result = super.sub(b).toString(); return new $5aa97aebe18a7924$export$2e2bcd8739ae039(result); } mul(b) { const result = super.mul(b).toString(); return new $5aa97aebe18a7924$export$2e2bcd8739ae039(result); } mod(b) { const result = super.mod(b).toString(); return new $5aa97aebe18a7924$export$2e2bcd8739ae039(result); } umod(b) { const result = super.umod(b).toString(); return new $5aa97aebe18a7924$export$2e2bcd8739ae039(result); } toNumber() { return parseInt(this.toString(10), 10); } toBigInt() { return BigInt(this.toString(10)); } toBuffer(opts, length) { if ((0, $hgUW1$isString)(opts)) // compatability with override return super.toBuffer(opts, length); let hex = this.toString(16, 2); let buf = Buffer.from(hex, 'hex'); if (opts?.size) { let natlen = hex.length / 2; if (natlen > opts.size) buf = $5aa97aebe18a7924$export$2e2bcd8739ae039.trim(buf, natlen); else if (natlen < opts.size) buf = $5aa97aebe18a7924$export$2e2bcd8739ae039.pad(buf, natlen, opts.size); } if (opts?.endian === 'little') buf = (0, $9f918c10ad4fef51$export$2e2bcd8739ae039).reverse(buf); return buf; } /** * The corollary to the above, with the notable exception that we do not throw * an error if the output is larger than four bytes. (Which can happen if * performing a numerical operation that results in an overflow to more than 4 * bytes). */ toScriptNumBuffer() { return this.toSM({ endian: 'little' }); } toScriptBigNumBuffer() { return this.toSM({ endian: 'little', bignum: true }); } getSize() { const bin = this.toString(2).replace('-', ''); const numBits = bin.length + 1; return numBits / 8; } safeAdd(bigNumToAdd, maxSize) { const sum = this.add(bigNumToAdd); this.checkOperationForOverflow(bigNumToAdd, sum, maxSize); return sum; } safeSub(bigNumToSubtract, maxSize) { const difference = this.sub(bigNumToSubtract); this.checkOperationForOverflow(bigNumToSubtract, difference, maxSize); return difference; } safeMul(bigNumToMultiply, maxSize) { const product = this.mul(bigNumToMultiply); this.checkOperationForOverflow(bigNumToMultiply, product, maxSize); return product; } checkOperationForOverflow(operand, result, maxSize) { if (this.getSize() > maxSize || operand.getSize() > maxSize || result.getSize() > 8) throw new Error('overflow'); } toSMBigEndian() { let buf; if (this.cmp($5aa97aebe18a7924$export$2e2bcd8739ae039.Zero) === -1) { buf = this.neg().toBuffer(); if (buf[0] & 0x80) buf = Buffer.concat([ Buffer.from([ 0x80 ]), buf ]); else buf[0] = buf[0] | 0x80; } else { buf = this.toBuffer(); if (buf[0] & 0x80) buf = Buffer.concat([ Buffer.from([ 0x00 ]), buf ]); } if (buf.length === 1 && buf[0] === 0) buf = Buffer.from([]); return buf; } toBigNumSMBigEndian() { let buf; if (this.cmp($5aa97aebe18a7924$export$2e2bcd8739ae039.Zero) === -1) { buf = this.neg().toBuffer(); buf = Buffer.concat([ Buffer.from([ 0x80 ]), buf ]); } else { buf = this.toBuffer(); buf = Buffer.concat([ Buffer.from([ 0x00 ]), buf ]); } return buf; } toSM(opts) { let buf = opts?.bignum ? this.toBigNumSMBigEndian() : this.toSMBigEndian(); if (opts?.endian === 'little') buf = (0, $9f918c10ad4fef51$export$2e2bcd8739ae039).reverse(buf); return buf; } /** * Instantiate a BigNumber from a "signed magnitude buffer" * (a buffer where the most significant bit represents the sign (0 = positive, -1 = negative)) */ static fromSM(buf, opts) { if (buf.length === 0) return this.fromBuffer(Buffer.from([ 0 ])); if (opts?.endian === 'little') buf = (0, $9f918c10ad4fef51$export$2e2bcd8739ae039).reverse(buf); let ret; if (buf[0] & 0x80) { buf[0] = buf[0] & 0x7f; ret = this.fromBuffer(buf); ret.neg().copy(ret); } else ret = this.fromBuffer(buf); return ret; } static trim(buf, natlen) { return buf.subarray(natlen - buf.length, natlen); } static pad(buf, natlen, size) { let rbuf = Buffer.alloc(size); for(let i = 0; i < buf.length; i++)rbuf[rbuf.length - 1 - i] = buf[buf.length - 1 - i]; for(let i = 0; i < size - natlen; i++)rbuf[i] = 0; return rbuf; } } class $12fea2c2eb591556$export$2e2bcd8739ae039 { constructor(buf){ this.finished = this.eof; this.buf = Buffer.from([]); this.pos = 0; if ((0, $hgUW1$isUndefined)(buf)) return; if (Buffer.isBuffer(buf)) this.set({ buf: buf }); else if ((0, $hgUW1$isString)(buf)) { let b = Buffer.from(buf, 'hex'); if (b.length * 2 != buf.length) throw new TypeError('Invalid hex string'); this.set({ buf: b }); } else if ((0, $hgUW1$isObject)(buf)) { let obj = buf; this.set(obj); } else throw new TypeError('Unrecognized argument for BufferReader'); } set(obj) { this.buf = obj.buf || this.buf; this.pos = obj.pos || this.pos || 0; return this; } eof() { return this.pos >= this.buf.length; } read(len) { (0, $e44f707fde477092$export$2e2bcd8739ae039).validateArgument(!(0, $hgUW1$isUndefined)(len), 'Must specify a length'); let buf = this.buf.subarray(this.pos, this.pos + len); this.pos = this.pos + len; return buf; } readAll() { let buf = this.buf.subarray(this.pos, this.buf.length); this.pos = this.buf.length; return buf; } readUInt8() { let val = this.buf.readUInt8(this.pos); this.pos = this.pos + 1; return val; } readUInt16BE() { let val = this.buf.readUInt16BE(this.pos); this.pos = this.pos + 2; return val; } readUInt16LE() { let val = this.buf.readUInt16LE(this.pos); this.pos = this.pos + 2; return val; } readUInt32BE() { let val = this.buf.readUInt32BE(this.pos); this.pos = this.pos + 4; return val; } readUInt32LE() { let val = this.buf.readUInt32LE(this.pos); this.pos = this.pos + 4; return val; } readInt32LE() { let val = this.buf.readInt32LE(this.pos); this.pos = this.pos + 4; return val; } readUInt64BEBN() { let buf = this.buf.subarray(this.pos, this.pos + 8); let bn = (0, $5aa97aebe18a7924$export$2e2bcd8739ae039).fromBuffer(buf); this.pos = this.pos + 8; return bn; } readUInt64LEBN() { let second = this.buf.readUInt32LE(this.pos); let first = this.buf.readUInt32LE(this.pos + 4); let combined = first * 0x100000000 + second; // Instantiating an instance of BN with a number is faster than with an // array or string. However, the maximum safe number for a double precision // floating point is 2 ^ 52 - 1 (0x1fffffffffffff), thus we can safely use // non-floating point numbers less than this amount (52 bits). And in the case // that the number is larger, we can instatiate an instance of BN by passing // an array from the buffer (slower) and specifying the endianness. let bn; if (combined <= 0x1fffffffffffff) bn = new (0, $5aa97aebe18a7924$export$2e2bcd8739ae039)(combined); else { let data = this.buf.subarray(this.pos, this.pos + 8); bn = new (0, $5aa97aebe18a7924$export$2e2bcd8739ae039)(data, 10, 'le'); } this.pos = this.pos + 8; return bn; } readVarintNum() { let first = this.readUInt8(); switch(first){ case 0xFD: return this.readUInt16LE(); case 0xFE: return this.readUInt32LE(); case 0xFF: let bn = this.readUInt64LEBN(); let n = bn.toNumber(); if (n <= Math.pow(2, 53)) return n; else throw new Error('number too large to retain precision - use readVarintBN'); } return first; } /** * reads a length prepended buffer */ readVarLengthBuffer() { let len = this.readVarintNum(); let buf = this.read(len); (0, $e44f707fde477092$export$2e2bcd8739ae039).validateState(buf.length === len, "Invalid length while reading varlength buffer. Expected to read: " + len + ' and read ' + buf.length); return buf; } readVarintBuf() { let first = this.buf.readUInt8(this.pos); switch(first){ case 0xFD: return this.read(3); case 0xFE: return this.read(5); case 0xFF: return this.read(9); default: return this.read(1); } } readVarintBN() { let first = this.readUInt8(); switch(first){ case 0xFD: return new (0, $5aa97aebe18a7924$export$2e2bcd8739ae039)(this.readUInt16LE()); case 0xFE: return new (0, $5aa97aebe18a7924$export$2e2bcd8739ae039)(this.readUInt32LE()); case 0xFF: return this.readUInt64LEBN(); default: return new (0, $5aa97aebe18a7924$export$2e2bcd8739ae039)(first); } } reverse() { let buf = (0, $9f918c10ad4fef51$export$2e2bcd8739ae039).reverse(this.buf); this.buf = buf; return this; } readReverse(len) { if ((0, $hgUW1$isUndefined)(len)) len = this.buf.length; let buf = this.buf.subarray(this.pos, this.pos + len); this.pos = this.pos + len; return (0, $9f918c10ad4fef51$export$2e2bcd8739ae039).reverse(buf); } readCoreVarintNum() { let n = 0; while(true){ let chData = this.readUInt8(); n = n << 7 | chData & 0x7F; if (chData & 0x80) n++; else return n; } } } class $35852622c8c617e8$export$2e2bcd8739ae039 { constructor(obj){ this.bufs = []; this.bufLen = 0; if (obj) this.set(obj); } set(obj) { this.bufs = obj.bufs || this.bufs; this.bufLen = this.bufs.reduce((prev, buf)=>prev + buf.length, 0); return this; } toBuffer() { return this.concat(); } concat() { return Buffer.concat(this.bufs, this.bufLen); } write(buf) { (0, $e44f707fde477092$export$2e2bcd8739ae039).validateArgument((0, $9f918c10ad4fef51$export$2e2bcd8739ae039).isBuffer(buf), "buf"); this.bufs.push(buf); this.bufLen += buf.length; return this; } writeReverse(buf) { (0, $e44f707fde477092$export$2e2bcd8739ae039).validateArgument((0, $9f918c10ad4fef51$export$2e2bcd8739ae039).isBuffer(buf), "buf"); this.bufs.push((0, $9f918c10ad4fef51$export$2e2bcd8739ae039).reverse(buf)); this.bufLen += buf.length; return this; } writeUInt8(n) { let buf = Buffer.alloc(1); buf.writeUInt8(n, 0); this.write(buf); return this; } writeUInt16BE(n) { let buf = Buffer.alloc(2); buf.writeUInt16BE(n, 0); this.write(buf); return this; } writeUInt16LE(n) { let buf = Buffer.alloc(2); buf.writeUInt16LE(n, 0); this.write(buf); return this; } writeUInt32BE(n) { let buf = Buffer.alloc(4); buf.writeUInt32BE(n, 0); this.write(buf); return this; } writeInt32LE(n) { let buf = Buffer.alloc(4); buf.writeInt32LE(n, 0); this.write(buf); return this; } writeUInt32LE(n) { let buf = Buffer.alloc(4); buf.writeUInt32LE(n, 0); this.write(buf); return this; } writeUInt64BEBN(bn) { let buf = bn.toBuffer({ size: 8 }); this.write(buf); return this; } writeUInt64LEBN(bn) { let buf = bn.toBuffer({ size: 8 }); this.writeReverse(buf); return this; } writeVarintNum(n) { let buf = $35852622c8c617e8$export$2e2bcd8739ae039.varintBufNum(n); this.write(buf); return this; } writeVarintBN(bn) { let buf = $35852622c8c617e8$export$2e2bcd8739ae039.varintBufBN(bn); this.write(buf); return this; } writeVarLengthBuf(buf) { (0, $e44f707fde477092$export$2e2bcd8739ae039).validateArgument((0, $9f918c10ad4fef51$export$2e2bcd8739ae039).isBuffer(buf), "buf"); this.writeVarintNum(buf.length); this.write(buf); return this; } writeCoreVarintNum(n) { let tmp = []; let len = 0; while(true){ tmp.push(n & 0x7F | (len ? 0x80 : 0x00)); if (n <= 0x7F) break; n = (n >> 7) - 1; len++; } this.write(Buffer.from(tmp).reverse()); return this; } static varintBufNum(n) { let buf = undefined; if (n < 253) { buf = Buffer.alloc(1); buf.writeUInt8(n, 0); } else if (n < 0x10000) { buf = Buffer.alloc(3); buf.writeUInt8(253, 0); buf.writeUInt16LE(n, 1); } else if (n < 0x100000000) { buf = Buffer.alloc(5); buf.writeUInt8(254, 0); buf.writeUInt32LE(n, 1); } else { buf = Buffer.alloc(9); buf.writeUInt8(255, 0); buf.writeInt32LE(n & -1, 1); buf.writeUInt32LE(Math.floor(n / 0x100000000), 5); } return buf; } static varintBufBN(bn) { let buf = undefined; let n = bn.toNumber(); if (n < 253) { buf = Buffer.alloc(1); buf.writeUInt8(n, 0); } else if (n < 0x10000) { buf = Buffer.alloc(3); buf.writeUInt8(253, 0); buf.writeUInt16LE(n, 1); } else if (n < 0x100000000) { buf = Buffer.alloc(5); buf.writeUInt8(254, 0); buf.writeUInt32LE(n, 1); } else { let bw = new $35852622c8c617e8$export$2e2bcd8739ae039(); bw.writeUInt8(255); bw.writeUInt64LEBN(bn); buf = bw.concat(); } return buf; } } var $05e660d5daa855e4$export$80d48287646c9e3b = /*#__PURE__*/ function(UnitType) { UnitType[UnitType["MEX"] = 8] = "MEX"; UnitType[UnitType["KEX"] = 5] = "KEX"; UnitType[UnitType["NEXA"] = 2] = "NEXA"; return UnitType; }({}); class $05e660d5daa855e4$export$2e2bcd8739ae039 { /** * Converts `value` into a decimal string, assuming `unit` decimal * places. The `unit` may be the number of decimal places or the enum of * a unit (e.g. ``UnitType.MEX`` for 8 decimal places). * */ static formatUnits(value, unit) { let decimals = 2; if (!(0, $hgUW1$isNil)(unit)) { (0, $e44f707fde477092$export$2e2bcd8739ae039).validateArgument((0, $hgUW1$isInteger)(unit) && unit >= 0, "unit", "invalid unit"); decimals = unit; } return (0, $hgUW1$jsbigdecimal).divide(value, Math.pow(10, decimals), decimals); } /** * Converts the decimal string `value` to a BigInt, assuming * `unit` decimal places. The `unit` may the number of decimal places * or the name of a unit (e.g. ``UnitType.KEX`` for 5 decimal places). */ static parseUnits(value, unit) { (0, $e44f707fde477092$export$2e2bcd8739ae039).validateArgument((0, $hgUW1$isString)(value), "value", "must be a string"); let decimals = 2; if (!(0, $hgUW1$isNil)(unit)) { (0, $e44f707fde477092$export$2e2bcd8739ae039).validateArgument((0, $hgUW1$isInteger)(unit) && unit >= 0, "unit", "invalid unit"); decimals = unit; } return BigInt((0, $hgUW1$jsbigdecimal).multiply(value, Math.pow(10, decimals))); } /** * Converts `value` into a decimal string using 2 decimal places. */ static formatNEXA(sats) { return this.formatUnits(sats, 2); } /** * Converts the decimal string `NEXA` to a BigInt, using 2 decimal places. */ static parseNEXA(nexa) { return this.parseUnits(nexa, 2); } } class $ddbf68ec49150fba$export$95be4ae94445245a { constructor(params){ this.name = params.name; this.alias = params.alias; this.prefix = params.prefix; this.pubkeyhash = params.pubkeyhash; this.privatekey = params.privatekey; this.scripthash = params.scripthash; this.xpubkey = params.xpubkey; this.xprivkey = params.xprivkey; this.networkMagic = (0, $9f918c10ad4fef51$export$2e2bcd8739ae039).integerAsBuffer(params.networkMagic); this.port = params.port; this.dnsSeeds = params.dnsSeeds; } toString() { return this.name; } } const $ddbf68ec49150fba$export$673894bea0cfc1c8 = new $ddbf68ec49150fba$export$95be4ae94445245a({ name: 'mainnet', alias: 'livenet', prefix: 'nexa', pubkeyhash: 0x19, privatekey: 0x23, scripthash: 0x44, xpubkey: 0x42696720, xprivkey: 0x426c6b73, networkMagic: 0x72271221, port: 7228, dnsSeeds: [ 'seed.nextchain.cash', 'seeder.nexa.org', 'nexa-seeder.bitcoinunlimited.info' ] }); const $ddbf68ec49150fba$export$2cc9cef11fee0dca = new $ddbf68ec49150fba$export$95be4ae94445245a({ name: 'testnet', alias: 'testnet', prefix: 'nexatest', pubkeyhash: 0x6f, privatekey: 0xef, scripthash: 0xc4, xpubkey: 0x043587cf, xprivkey: 0x04358394, networkMagic: 0x72271222, port: 7230, dnsSeeds: [ 'nexa-testnet-seeder.bitcoinunlimited.info', 'testnetseeder.nexa.org' ] }); class $a89918d61ea4dca0$export$2e2bcd8739ae039 { static{ this._instance = new $a89918d61ea4dca0$export$2e2bcd8739ae039(); } get mainnet() { return 0, $ddbf68ec49150fba$export$673894bea0cfc1c8; } /** @deprecated use mainnet */ get livenet() { return 0, $ddbf68ec49150fba$export$673894bea0cfc1c8; } get testnet() { return 0, $ddbf68ec49150fba$export$2cc9cef11fee0dca; } get defaultNetwork() { return this._defaultNetwork; } set defaultNetwork(network) { this._defaultNetwork = network; } /** * @returns the singleton instance of NetworkManager */ static getInstance() { return this._instance; } get(arg, key) { if (arg instanceof (0, $ddbf68ec49150fba$export$95be4ae94445245a)) { if (this.networks.includes(arg)) return arg; if (this.networks.map((n)=>n.name).includes(arg.name)) return this.networks.find((n)=>n.name == arg.name); } if (key) return this.networks.find((network)=>{ if (key == 'networkMagic') return (0, $9f918c10ad4fef51$export$2e2bcd8739ae039).integerFromBuffer(network[key]) == arg; else return network[key] == arg; }); else return this.networks.find((network)=>Object.keys(network).some((prop)=>{ let _prop = prop; if (_prop == 'networkMagic') return (0, $9f918c10ad4fef51$export$2e2bcd8739ae039).integerFromBuffer(network[_prop]) == arg; else return network[_prop] == arg; })); } create(network) { return new (0, $ddbf68ec49150fba$export$95be4ae94445245a)(network); } add(network) { if (!(network instanceof (0, $ddbf68ec49150fba$export$95be4ae94445245a))) network = new (0, $ddbf68ec49150fba$export$95be4ae94445245a)(network); this.networks.push(network); } remove(network) { if (typeof network !== 'object') { network = this.get(network); if (!network) return; } for(let i = 0; i < this.networks.length; i++)if (this.networks[i] === network || JSON.stringify(this.networks[i]) == JSON.stringify(network)) this.networks.splice(i, 1); } constructor(){ this.networks = [ (0, $ddbf68ec49150fba$export$673894bea0cfc1c8), (0, $ddbf68ec49150fba$export$2cc9cef11fee0dca) ]; this._defaultNetwork = (0, $ddbf68ec49150fba$export$673894bea0cfc1c8); } } const $a89918d61ea4dca0$export$f09b1917886389c3 = $a89918d61ea4dca0$export$2e2bcd8739ae039.getInstance(); class $369a157b63fbc3fd$export$2e2bcd8739ae039 { constructor(params){ this.r = params.r; this.s = params.s; this.i = params.i; this.compressed = params.compressed; } toBuffer(isSchnorr = true) { if (isSchnorr) // Schnorr signatures use a 64 byte r,s format. return Buffer.concat([ this.r.toBuffer({ size: 32 }), this.s.toBuffer({ size: 32 }) ]); let rnbuf = this.r.toBuffer(); let snbuf = this.s.toBuffer(); let rneg = rnbuf[0] & 0x80 ? true : false; /* c8 ignore next */ let sneg = snbuf[0] & 0x80 ? true : false; let rbuf = rneg ? Buffer.concat([ Buffer.from([ 0x00 ]), rnbuf ]) : rnbuf; /* c8 ignore next */ let sbuf = sneg ? Buffer.concat([ Buffer.from([ 0x00 ]), snbuf ]) : snbuf; let rlength = rbuf.length; let slength = sbuf.length; let length = 2 + rlength + 2 + slength; let rheader = 0x02; let sheader = 0x02; let header = 0x30; let der = Buffer.concat([ Buffer.from([ header, length, rheader, rlength ]), rbuf, Buffer.from([ sheader, slength ]), sbuf ]); return der; } toTxFormat(sighashBuf) { let sigbuf = this.toBuffer(); if ((0, $9f918c10ad4fef51$export$2e2bcd8739ae039).isBuffer(sighashBuf)) return Buffer.concat([ sigbuf, sighashBuf ]); return sigbuf; } toString() { return this.toBuffer().toString('hex'); } /** * Schnorr signatures are 64 bytes: r [len] 32 || s [len] 32. * * There can be a few more bytes that is the sighashtype. It needs to be trimmed before calling this. */ static fromBuffer(buf, strict) { if (buf.length === 64) { let params = this.parseSchnorrEncodedSig(buf); return new $369a157b63fbc3fd$export$2e2bcd8739ae039(params); } let obj = $369a157b63fbc3fd$export$2e2bcd8739ae039.parseDER(buf, strict); return new $369a157b63fbc3fd$export$2e2bcd8739ae039({ r: obj.r, s: obj.s }); } /** * The format used in a tx. * schnorr is 64 bytes, the rest are sighashtype bytes * * @param buf */ static fromTxFormat(buf) { let sigbuf = buf.subarray(0, 64); return $369a157b63fbc3fd$export$2e2bcd8739ae039.fromBuffer(sigbuf); } /** * This assumes the str is a raw signature and does not have sighashtype. * Use {@link Signature.fromTxString} when decoding a tx * * @param str the signature hex string * @see fromTxString */ static fromString(str) { let buf = Buffer.from(str, 'hex'); return $369a157b63fbc3fd$export$2e2bcd8739ae039.fromBuffer(buf); } /** * This assumes the str might have sighashtype bytes and will trim it if needed. * Use this when decoding a tx signature string * * @param str the tx signature hex string */ static fromTxString(str, encoding = 'hex') { return $369a157b63fbc3fd$export$2e2bcd8739ae039.fromTxFormat(Buffer.from(str, encoding)); } static parseSchnorrEncodedSig(buf) { let r = buf.subarray(0, 32); let s = buf.subarray(32, 64); return { r: (0, $5aa97aebe18a7924$export$2e2bcd8739ae039).fromBuffer(r), s: (0, $5aa97aebe18a7924$export$2e2bcd8739ae039).fromBuffer(s) }; } /** * For ECDSA. In order to mimic the non-strict DER encoding of OpenSSL, set strict = false. */ static parseDER(buf, strict) { (0, $e44f707fde477092$export$2e2bcd8739ae039).validateArgument((0, $9f918c10ad4fef51$export$2e2bcd8739ae039).isBuffer(buf), 'DER formatted signature should be a buffer'); if ((0, $hgUW1$isUndefined)(strict)) strict = true; let header = buf[0]; (0, $e44f707fde477092$export$2e2bcd8739ae039).validateArgument(header === 0x30, 'Header byte should be 0x30'); let length = buf[1]; let buflength = buf.subarray(2).length; (0, $e44f707fde477092$export$2e2bcd8739ae039).validateArgument(!strict || length === buflength, 'Length byte should length of what follows'); length = length < buflength ? length : buflength; let rheader = buf[2]; (0, $e44f707fde477092$export$2e2bcd8739ae039).validateArgument(rheader === 0x02, 'Integer byte for r should be 0x02'); let rlength = buf[3]; let rbuf = buf.subarray(4, 4 + rlength); let r = (0, $5aa97aebe18a7924$export$2e2bcd8739ae039).fromBuffer(rbuf); let rneg = buf[4] === 0x00 ? true : false; (0, $e44f707fde477092$export$2e2bcd8739ae039).validateArgument(rlength === rbuf.length, 'Length of r incorrect'); let sheader = buf[4 + rlength + 0]; (0, $e44f707fde477092$export$2e2bcd8739ae039).validateArgument(sheader === 0x02, 'Integer byte for s should be 0x02'); let slength = buf[4 + rlength + 1]; let sbuf = buf.subarray(4 + rlength + 2, 4 + rlength + 2 + slength); let s = (0, $5aa97aebe18a7924$export$2e2bcd8739ae039).fromBuffer(sbuf); /* c8 ignore next */ let sneg = buf[4 + rlength + 2 + 2] === 0x00 ? true : false; (0, $e44f707fde477092$export$2e2bcd8739ae039).validateArgument(slength === sbuf.length, 'Length of s incorrect'); let sumlength = 4 + rlength + 2 + slength; (0, $e44f707fde477092$export$2e2bcd8739ae039).validateArgument(length === sumlength - 2, 'Length of signature incorrect'); let obj = { header: header, length: length, rheader: rheader, rlength: rlength, rneg: rneg, rbuf: rbuf, r: r, sheader: sheader, slength: slength, sneg: sneg, sbuf: sbuf, s: s }; return obj; } /** * ECDSA format. used for sign messages */ toCompact(i, compressed) { i = typeof i === 'number' ? i : this.i; compressed = typeof compressed === 'boolean' ? compressed : this.compressed; (0, $e44f707fde477092$export$2e2bcd8739ae039).validateArgument(i === 0 || i === 1 || i === 2 || i === 3, 'i must be equal to 0, 1, 2, or 3'); let val = i + 27 + 4; if (compressed === false) val = val - 4; let b1 = Buffer.from([ val ]); let b2 = this.r.toBuffer({ size: 32 }); let b3 = this.s.toBuffer({ size: 32 }); return Buffer.concat([ b1, b2, b3 ]); } static fromCompact(buf) { (0, $e44f707fde477092$export$2e2bcd8739ae039).validateArgument((0, $9f918c10ad4fef51$export$2e2bcd8739ae039).isBuffer(buf), 'Argument is expected to be a Buffer'); let compressed = true; let i = buf.subarray(0, 1)[0] - 27 - 4; if (i < 0) { compressed = false; i = i + 4; } let b2 = buf.subarray(1, 33); let b3 = buf.subarray(33, 65); (0, $e44f707fde477092$export$2e2bcd8739ae039).validateArgument(i === 0 || i === 1 || i === 2 || i === 3, 'i must be 0, 1, 2, or 3'); (0, $e44f707fde477092$export$2e2bcd8739ae039).validateArgument(b2.length === 32, 'r must be 32 bytes'); (0, $e44f707fde477092$export$2e2bcd8739ae039).validateArgument(b3.length === 32, 's must be 32 bytes'); return new $369a157b63fbc3fd$export$2e2bcd8739ae039({ r: (0, $5aa97aebe18a7924$export$2e2bcd8739ae039).fromBuffer(b2), s: (0, $5aa97aebe18a7924$export$2e2bcd8739ae039).fromBuffer(b3), i: i, compressed: compressed }); } } class $2a1cae3adbd93346$export$2e2bcd8739ae039 { constructor(obj){ if (obj) this.set(obj); } set(obj) { this.hashbuf = obj.hashbuf || this.hashbuf; this.endian = obj.endian || this.endian; this.privkey = obj.privkey || this.privkey; this.pubkey = obj.pubkey || (this.privkey ? this.privkey.publicKey : this.pubkey); this.sig = obj.sig || this.sig; this.verified = obj.verified || this.verified; return this; } sign() { let hashbuf = this.hashbuf; let privkey = this.privkey; let d = privkey.bn; (0, $e44f707fde477092$export$2e2bcd8739ae039).validateState(!(0, $hgUW1$isNil)(hashbuf) && !(0, $hgUW1$isNil)(privkey) && !(0, $hgUW1$isNil)(d), 'invalid parameters'); (0, $e44f707fde477092$export$2e2bcd8739ae039).validateState((0, $9f918c10ad4fef51$export$2e2bcd8739ae039).isBuffer(hashbuf) && hashbuf.length === 32, 'hashbuf must be a 32 byte buffer'); let e = (0, $5aa97aebe18a7924$export$2e2bcd8739ae039).fromBuffer(hashbuf, this.endian ? { endian: this.endian } : undefined); let obj = this._findSignature(d, e); obj.compressed = this.pubkey.compressed; this.sig = new (0, $369a157b63fbc3fd$export$2e2bcd8739ae039)(obj); return this; } verify() { this.verified = !this.sigError(); return this; } toPublicKey() { return this.privkey.toPublicKey(); } privkey2pubkey() { this.pubkey = this.privkey.toPublicKey(); } } const $ba7e1a38972b2d09$var$EC = (0, $hgUW1$elliptic).ec; class $ba7e1a38972b2d09$export$2e2bcd8739ae039 { static{ this.ec = new $ba7e1a38972b2d09$var$EC('secp256k1').curve; } static{ this._g = new $ba7e1a38972b2d09$export$2e2bcd8739ae039(this.ec.g); } constructor(point, skipValidation = false){ this.ecPoint = point; if (!skipValidation) this.validate(); } /** * Will return the X coordinate of the Point * * @returns A BN instance of the X coordinate */ getX() { return new (0, $5aa97aebe18a7924$export$2e2bcd8739ae039)(this.ecPoint.getX().toArray()); } /** * Will return the Y coordinate of the Point * * @returns A BN instance of the Y coordinate */ getY() { return new (0, $5aa97aebe18a7924$export$2e2bcd8739ae039)(this.ecPoint.getY().toArray()); } add(p) { return new $ba7e1a38972b2d09$export$2e2bcd8739ae039(this.ecPoint.add(p.ecPoint), true); } mul(k) { let p = this.ecPoint.mul(k); return new $ba7e1a38972b2d09$export$2e2bcd8739ae039(p, true); } mulAdd(k1, p2, k2) { let p = this.ecPoint.mulAdd(k1, p2.ecPoint, k2); // eslint-disable-line @typescript-eslint/no-explicit-any return new $ba7e1a38972b2d09$export$2e2bcd8739ae039(p, true); } eq(p) { return this.ecPoint.eq(p.ecPoint); } /** * Will determine if the point is valid * * @see {@link https://www.iacr.org/archive/pkc2003/25670211/25670211.pdf} * @throws A validation error if exists * @returns An instance of the same Point */ validate() { if (this.ecPoint.isInfinity()) throw new Error('Point cannot be equal to Infinity'); let p2; try { p2 = $ba7e1a38972b2d09$export$2e2bcd8739ae039.ec.pointFromX(this.getX(), this.getY().isOdd()); } catch { throw new Error('Point does not lie on the curve'); } if (p2.y.cmp(this.ecPoint.y) !== 0) throw new Error('Invalid y value for curve.'); if (!this.ecPoint.mul($ba7e1a38972b2d09$export$2e2bcd8739ae039.getN()).isInfinity()) throw new Error('Point times N must be infinity'); return this; } hasSquare() { return !this.ecPoint.isInfinity() && $ba7e1a38972b2d09$export$2e2bcd8739ae039.isSquare(this.getY()); } static isSquare(x) { let p = new (0, $5aa97aebe18a7924$export$2e2bcd8739ae039)('FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFC2F', 'hex'); let x0 = new (0, $5aa97aebe18a7924$export$2e2bcd8739ae039)(x); let base = x0.toRed((0, $5aa97aebe18a7924$export$2e2bcd8739ae039).red(p)); let res = base.redPow(p.sub((0, $5aa97aebe18a7924$export$2e2bcd8739ae039).One).div(new (0, $5aa97aebe18a7924$export$2e2bcd8739ae039)(2))).fromRed(); return res.eq(new (0, $5aa97aebe18a7924$export$2e2bcd8739ae039)(1)); } /** * Instantiate a valid secp256k1 Point from the X and Y coordinates. * * @param x - The X coordinate * @param y - The Y coordinate * @see {@link https://github.com/indutny/elliptic} *