libnexa-ts
Version:
A pure and powerful Nexa SDK library.
1,551 lines • 204 kB
JavaScript
import * as lt from "base64-js";
import Et from "bn.js";
import It from "elliptic";
import { sha256 as ct, sha512 as mt } from "@noble/hashes/sha2.js";
import { sha1 as _t, ripemd160 as Ot } from "@noble/hashes/legacy.js";
import { hmac as gt } from "@noble/hashes/hmac.js";
import pt from "js-big-decimal";
import dt from "bs58";
class I {
/**
* Determines whether a string contains only hexadecimal values
*
* @param value
* @returns true if the string is the hexa representation of a number
*/
static isHexa(t) {
return typeof t == "string" && t.length % 2 === 0 && /^[0-9a-fA-F]+$/.test(t);
}
/**
* 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(t) {
if (typeof t != "string")
return !1;
try {
return JSON.parse(t);
} catch {
return !1;
}
}
/**
* Checks that a value is a natural number.
*
* @param value
* @return true if a positive integer or zero.
*/
static isNaturalNumber(t) {
return typeof t == "number" && isFinite(t) && Math.floor(t) === t && t >= 0;
}
/**
* Checks that a value is a natural number.
*
* @param value
* @return true if a positive integer or zero.
*/
static isNaturalBigInt(t) {
return typeof t == "bigint" && t >= 0n;
}
}
class a {
static validateState(t, e) {
if (!t)
throw new Error(`Invalid State: ${e}`);
}
static validateArgument(t, e, r = "") {
if (!t)
throw new Error(`Invalid Argument: ${e}. ${r}`);
}
static validateArgumentType(t, e, r) {
if (r = r || "(unknown name)", typeof e == "string") {
if (typeof t !== e)
throw new TypeError(`Invalid Argument for ${r}, expected ${e} but got ${typeof t}`);
} else if (!(t instanceof e))
throw new TypeError(`Invalid Argument for ${r}, expected ${e} but got ${typeof t}`);
}
}
class s {
/**
* Tests for both node's Buffer and Uint8Array
*
* @param arg
* @return Returns true if the given argument is an instance of a Uint8Array.
*/
static isBuffer(t) {
return t 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(t) {
return this.isBuffer(t) && (t.length === 20 || t.length === 32);
}
/**
* Reverse a Uint8Array
* @param param
* @return new reversed Uint8Array
*/
static reverse(t) {
return Uint8Array.from(t).reverse();
}
/**
* Convert a Uint8Array to a UTF-8 string.
*
* @param buffer - Uint8Array containing UTF-8 encoded bytes
* @returns Decoded string
*/
static bufferToUtf8(t) {
return new TextDecoder("utf-8").decode(t);
}
/**
* Convert a UTF-8 string to a Uint8Array.
*
* @param str - UTF-8 string
* @returns Encoded Uint8Array
*/
static utf8ToBuffer(t) {
return new TextEncoder().encode(t);
}
/**
* Convert a Uint8Array to a Base64 string.
*
* @param buffer - Uint8Array containing Base64 encoded bytes
* @returns Decoded string
*/
static bufferToBase64(t) {
return lt.fromByteArray(t);
}
/**
* Convert a Base64 string to a Uint8Array.
*
* @param str - Base64 string
* @returns Encoded Uint8Array
*/
static base64ToBuffer(t) {
return lt.toByteArray(t);
}
/**
* Transforms a buffer into a string with a number in hexa representation
*
* Similar for <tt>buffer.toString('hex')</tt>
*
* @param buffer
* @return string
*/
static bufferToHex(t) {
return a.validateArgumentType(t, Uint8Array, "buffer"), Array.from(t).map((e) => e.toString(16).padStart(2, "0")).join("");
}
/**
* Convert a hexadecimal string into a Uint8Array.
*
* @param hex - Hex string (must have even length)
* @returns Uint8Array representing the bytes
*/
static hexToBuffer(t) {
if (!I.isHexa(t))
return new Uint8Array();
const e = t.length / 2, r = new Uint8Array(e);
for (let i = 0; i < e; i++)
r[i] = parseInt(t.slice(i * 2, i * 2 + 2), 16);
return r;
}
/**
* Concatenate multiple Uint8Arrays into a single Uint8Array.
*
* Mimics Node.js Buffer.concat(list, totalLength?):
* - list: Array of Uint8Arrays
* - totalLength: Optional precomputed total length
*
* @param list - Array of Uint8Arrays to concatenate
* @param totalLength - Optional total length to preallocate
* @returns New Uint8Array containing all bytes from input arrays
*
* @example
* const a = new Uint8Array([1,2]);
* const b = new Uint8Array([3,4]);
* const result = Uint8ArrayUtils.concat([a,b]);
* console.log(result); // Uint8Array(4) [1,2,3,4]
*/
static concat(t, e) {
const r = e ?? t.reduce((f, o) => f + o.length, 0), i = new Uint8Array(r);
let u = 0;
for (const f of t)
i.set(f, u), u += f.length;
return i;
}
/**
* Compares two Uint8Arrays for byte-wise equality.
*
* This function checks whether the two arrays have the same length
* and the same content.
*
* @param a - The first Uint8Array to compare.
* @param b - The second Uint8Array to compare.
* @returns `true` if the arrays have the same length and contents, `false` otherwise.
*/
static equals(t, e) {
if (t === e) return !0;
if (t.byteLength !== e.byteLength) return !1;
for (let r = 0; r < t.byteLength; r++)
if (t[r] !== e[r]) return !1;
return !0;
}
/**
* Transforms a number from 0 to 255 into a Uint8Array of size 1 with that value
*
* @param integer
* @return Uint8Array
*/
static integerAsSingleByteBuffer(t) {
return a.validateArgumentType(t, "number", "integer"), new Uint8Array([t & 255]);
}
/**
* Transforms the first byte of an array into a number ranging from -128 to 127
*
* @param buffer
* @return number
*/
static integerFromSingleByteBuffer(t) {
return a.validateArgumentType(t, Uint8Array, "buffer"), t[0];
}
/**
* Transform a 4-byte integer into a Uint8Array of length 4.
*
* @param integer
* @return Uint8Array
*/
static integerAsBuffer(t) {
a.validateArgumentType(t, "number", "integer");
const e = new Uint8Array(4);
return e[0] = t >> 24 & 255, e[1] = t >> 16 & 255, e[2] = t >> 8 & 255, e[3] = t & 255, e;
}
/**
* Transform the first 4 values of a Uint8Array into a number, in little endian encoding
*
* @param buffer
* @return integer
*/
static integerFromBuffer(t) {
return a.validateArgumentType(t, Uint8Array, "buffer"), t[0] << 24 | t[1] << 16 | t[2] << 8 | t[3];
}
/**
* @return secure random bytes
*/
static getRandomBuffer(t) {
const e = new Uint8Array(t);
return crypto.getRandomValues(e), e;
}
}
class Y {
name;
alias;
prefix;
pubkeyhash;
privatekey;
scripthash;
xpubkey;
xprivkey;
networkMagic;
port;
dnsSeeds;
constructor(t) {
this.name = t.name, this.alias = t.alias, this.prefix = t.prefix, this.pubkeyhash = t.pubkeyhash, this.privatekey = t.privatekey, this.scripthash = t.scripthash, this.xpubkey = t.xpubkey, this.xprivkey = t.xprivkey, this.networkMagic = s.integerAsBuffer(t.networkMagic), this.port = t.port, this.dnsSeeds = t.dnsSeeds;
}
toString() {
return this.name;
}
}
const nt = new Y({
name: "mainnet",
alias: "livenet",
prefix: "nexa",
pubkeyhash: 25,
privatekey: 35,
scripthash: 68,
xpubkey: 1114203936,
xprivkey: 1114401651,
networkMagic: 1915163169,
port: 7228,
dnsSeeds: [
// from https://gitlab.com/nexa/nexa/-/blob/dev/src/chainparams.cpp#L592
"seed.nextchain.cash",
"seeder.nexa.org",
"nexa-seeder.bitcoinunlimited.info"
]
}), yt = new Y({
name: "testnet",
alias: "testnet",
prefix: "nexatest",
pubkeyhash: 111,
privatekey: 239,
scripthash: 196,
xpubkey: 70617039,
xprivkey: 70615956,
networkMagic: 1915163170,
port: 7230,
dnsSeeds: [
"nexa-testnet-seeder.bitcoinunlimited.info",
"testnetseeder.nexa.org"
]
}), bt = new Y({
name: "regtest",
alias: "regtest",
prefix: "nexareg",
pubkeyhash: 111,
privatekey: 239,
scripthash: 196,
xpubkey: 70617039,
xprivkey: 70615956,
networkMagic: 3940937706,
port: 18444,
dnsSeeds: [
// Regtest mode doesn't have any DNS seeds.
]
});
class tt {
static _instance = new tt();
networks = [nt, yt, bt];
_defaultNetwork = nt;
get mainnet() {
return nt;
}
get testnet() {
return yt;
}
get regtest() {
return bt;
}
get defaultNetwork() {
return this._defaultNetwork;
}
set defaultNetwork(t) {
this._defaultNetwork = t;
}
/**
* @returns the singleton instance of NetworkManager
*/
static getInstance() {
return this._instance;
}
get(t, e) {
if (t instanceof Y) {
if (this.networks.includes(t))
return t;
if (this.networks.map((r) => r.name).includes(t.name))
return this.networks.find((r) => r.name == t.name);
}
return e ? this.networks.find((r) => e == "networkMagic" ? s.integerFromBuffer(r[e]) == t : r[e] == t) : this.networks.find((r) => Object.keys(r).some((i) => {
let u = i;
return u == "networkMagic" ? s.integerFromBuffer(r[u]) == t : r[u] == t;
}));
}
create(t) {
return new Y(t);
}
add(t) {
t instanceof Y || (t = new Y(t)), this.networks.push(t);
}
remove(t) {
if (!(typeof t != "object" && (t = this.get(t), !t)))
for (let e = 0; e < this.networks.length; e++)
(this.networks[e] === t || JSON.stringify(this.networks[e]) == JSON.stringify(t)) && this.networks.splice(e, 1);
}
}
const y = tt.getInstance();
class h extends Et {
static Zero = new h(0);
static One = new h(1);
static Minus1 = new h(-1);
static fromNumber(t) {
return a.validateArgument(typeof t == "number", "num"), new h(t);
}
static fromBigInt(t) {
return a.validateArgument(typeof t == "bigint", "num"), new h(t.toString());
}
static fromString(t, e) {
return a.validateArgument(typeof t == "string", "str"), new h(t, e);
}
static fromBuffer(t, e) {
return a.validateArgument(s.isBuffer(t), "buf"), e?.endian === "little" && (t = s.reverse(t)), new h(s.bufferToHex(t), 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(t, e, r) {
let i = r || 4;
if (a.validateArgument(t.length <= i, "script number overflow"), e && t.length > 0 && (t[t.length - 1] & 127) === 0 && (t.length <= 1 || (t[t.length - 2] & 128) === 0))
throw new Error("non-minimally encoded script number");
return h.fromSM(t, { endian: "little" });
}
// Override arithmetic methods to ensure they return BNExtended instances
add(t) {
const e = super.add(t).toString();
return new h(e);
}
sub(t) {
const e = super.sub(t).toString();
return new h(e);
}
mul(t) {
const e = super.mul(t).toString();
return new h(e);
}
mod(t) {
const e = super.mod(t).toString();
return new h(e);
}
umod(t) {
const e = super.umod(t).toString();
return new h(e);
}
invm(t) {
const e = super.invm(t).toString();
return new h(e);
}
neg() {
const t = super.neg().toString();
return new h(t);
}
toNumber() {
return parseInt(this.toString(10), 10);
}
toBigInt() {
return BigInt(this.toString(10));
}
toByteArray(t, e) {
if (typeof t == "string")
return Uint8Array.from(super.toArray(t, e));
let r = this.toString(16, 2), i = s.hexToBuffer(r);
if (t?.size) {
let u = r.length / 2;
u > t.size ? i = h.trim(i, u) : u < t.size && (i = h.pad(i, u, t.size));
}
return t?.endian === "little" && (i = s.reverse(i)), i;
}
/**
* 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: !0 });
}
getSize() {
return (this.toString(2).replace("-", "").length + 1) / 8;
}
safeAdd(t, e) {
const r = this.add(t);
return this.checkOperationForOverflow(t, r, e), r;
}
safeSub(t, e) {
const r = this.sub(t);
return this.checkOperationForOverflow(t, r, e), r;
}
safeMul(t, e) {
const r = this.mul(t);
return this.checkOperationForOverflow(t, r, e), r;
}
checkOperationForOverflow(t, e, r) {
if (this.getSize() > r || t.getSize() > r || e.getSize() > 8)
throw new Error("overflow");
}
toSMBigEndian() {
let t;
return this.cmp(h.Zero) === -1 ? (t = this.neg().toByteArray(), t[0] & 128 ? t = s.concat([Uint8Array.from([128]), t]) : t[0] = t[0] | 128) : (t = this.toByteArray(), t[0] & 128 && (t = s.concat([Uint8Array.from([0]), t]))), t.length === 1 && t[0] === 0 && (t = Uint8Array.from([])), t;
}
toBigNumSMBigEndian() {
let t;
return this.cmp(h.Zero) === -1 ? (t = this.neg().toByteArray(), t = s.concat([Uint8Array.from([128]), t])) : (t = this.toByteArray(), t = s.concat([Uint8Array.from([0]), t])), t;
}
toSM(t) {
let e = t?.bignum ? this.toBigNumSMBigEndian() : this.toSMBigEndian();
return t?.endian === "little" && (e = s.reverse(e)), e;
}
/**
* Instantiate a BigNumber from a "signed magnitude buffer"
* (a buffer where the most significant bit represents the sign (0 = positive, -1 = negative))
*/
static fromSM(t, e) {
if (t.length === 0)
return this.fromBuffer(Uint8Array.from([0]));
e?.endian === "little" && (t = s.reverse(t));
let r;
return t[0] & 128 ? (t[0] = t[0] & 127, r = this.fromBuffer(t), r.neg().copy(r)) : r = this.fromBuffer(t), r;
}
static trim(t, e) {
return t.subarray(e - t.length, e);
}
static pad(t, e, r) {
let i = new Uint8Array(r);
for (let u = 0; u < t.length; u++)
i[i.length - 1 - u] = t[t.length - 1 - u];
for (let u = 0; u < r - e; u++)
i[u] = 0;
return i;
}
}
const kt = It.ec;
class d {
static ec = new kt("secp256k1").curve;
ecPoint;
static _g = new d(this.ec.g);
constructor(t, e = !1) {
this.ecPoint = t, e || this.validate();
}
/**
* Will return the X coordinate of the Point
*
* @returns A BN instance of the X coordinate
*/
getX() {
return new h(this.ecPoint.getX().toArray());
}
/**
* Will return the Y coordinate of the Point
*
* @returns A BN instance of the Y coordinate
*/
getY() {
return new h(this.ecPoint.getY().toArray());
}
add(t) {
return new d(this.ecPoint.add(t.ecPoint), !0);
}
mul(t) {
let e = this.ecPoint.mul(t);
return new d(e, !0);
}
mulAdd(t, e, r) {
let i = this.ecPoint.mulAdd(t, e.ecPoint, r);
return new d(i, !0);
}
eq(t) {
return this.ecPoint.eq(t.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 t;
try {
t = d.ec.pointFromX(this.getX(), this.getY().isOdd());
} catch {
throw new Error("Point does not lie on the curve");
}
if (t.y.cmp(this.ecPoint.y) !== 0)
throw new Error("Invalid y value for curve.");
if (!this.ecPoint.mul(d.getN()).isInfinity())
throw new Error("Point times N must be infinity");
return this;
}
hasSquare() {
return !this.ecPoint.isInfinity() && d.isSquare(this.getY());
}
static isSquare(t) {
let e = new h("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFC2F", "hex");
return new h(t).toRed(h.red(e)).redPow(e.sub(h.One).div(new h(2))).fromRed().eq(new h(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}
* @throws A validation error if exists
*/
static ecPoint(t, e, r) {
return new d(this.ec.point(t, e, r));
}
/**
*
* Instantiate a valid secp256k1 Point from only the X coordinate
*
* @param odd - If the Y coordinate is odd
* @param x - The X coordinate
* @throws A validation error if exists
*/
static ecPointFromX(t, e) {
let r;
try {
r = this.ec.pointFromX(e, t);
} catch {
throw new Error("Invalid X");
}
return new d(r);
}
/**
*
* Will return a secp256k1 ECDSA base point.
*
* @see {@link https://en.bitcoin.it/wiki/Secp256k1}
* @returns An instance of the base point.
*/
static getG() {
return this._g;
}
/**
*
* Will return the max of range of valid private keys as governed by the secp256k1 ECDSA standard.
*
* @see {@link https://en.bitcoin.it/wiki/Private_key#Range_of_valid_ECDSA_private_keys}
* @returns A BN instance of the number of points on the curve
*/
static getN() {
return new h(this.ec.n.toArray());
}
static pointToCompressed(t) {
let e = t.getX().toByteArray({ size: 32 }), r = t.getY().toByteArray({ size: 32 }), i = r[r.length - 1] % 2, u = Uint8Array.from(i ? [3] : [2]);
return s.concat([u, e]);
}
}
class p {
static sha1(t) {
return a.validateArgument(s.isBuffer(t), "buf", "Must be Buffer"), _t(t);
}
static sha256(t) {
return a.validateArgument(s.isBuffer(t), "buf", "Must be Buffer"), ct(t);
}
static sha512(t) {
return a.validateArgument(s.isBuffer(t), "buf", "Must be Buffer"), mt(t);
}
static ripemd160(t) {
return a.validateArgument(s.isBuffer(t), "buf", "Must be Buffer"), Ot(t);
}
static sha256sha256(t) {
return a.validateArgument(s.isBuffer(t), "buf", "Must be Buffer"), this.sha256(this.sha256(t));
}
static sha256ripemd160(t) {
return a.validateArgument(s.isBuffer(t), "buf", "Must be Buffer"), this.ripemd160(this.sha256(t));
}
static sha256hmac(t, e) {
return gt(ct, e, t);
}
static sha512hmac(t, e) {
return gt(mt, e, t);
}
}
class N {
r;
s;
i;
compressed;
constructor(t) {
this.r = t.r, this.s = t.s, this.i = t.i, this.compressed = t.compressed;
}
toBuffer(t = !0) {
if (t)
return s.concat([this.r.toByteArray({ size: 32 }), this.s.toByteArray({ size: 32 })]);
let e = this.r.toByteArray(), r = this.s.toByteArray(), i = !!(e[0] & 128), u = !!(r[0] & 128), f = i ? s.concat([Uint8Array.from([0]), e]) : e, o = u ? s.concat([Uint8Array.from([0]), r]) : r, g = f.length, b = o.length, A = 2 + g + 2 + b;
return s.concat([Uint8Array.from([48, A, 2, g]), f, Uint8Array.from([2, b]), o]);
}
toTxFormat(t) {
let e = this.toBuffer();
return s.isBuffer(t) ? s.concat([e, t]) : e;
}
toString(t = !0) {
return s.bufferToHex(this.toBuffer(t));
}
/**
* 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(t, e) {
if (t.length === 64) {
let i = this.parseSchnorrEncodedSig(t);
return new N(i);
}
let r = N.parseDER(t, e);
return new N({ r: r.r, s: r.s });
}
/**
* The format used in a tx.
* schnorr is 64 bytes, the rest are sighashtype bytes
*
* @param buf
*/
static fromTxFormat(t) {
let e = t.subarray(0, 64);
return N.fromBuffer(e);
}
/**
* 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(t) {
let e = s.hexToBuffer(t);
return N.fromBuffer(e);
}
/**
* 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(t) {
return N.fromTxFormat(s.hexToBuffer(t));
}
static parseSchnorrEncodedSig(t) {
let e = t.subarray(0, 32), r = t.subarray(32, 64);
return {
r: h.fromBuffer(e),
s: h.fromBuffer(r)
};
}
/**
* For ECDSA. In order to mimic the non-strict DER encoding of OpenSSL, set strict = false.
*/
static parseDER(t, e) {
a.validateArgument(s.isBuffer(t), "DER formatted signature should be a buffer"), e == null && (e = !0);
let r = t[0];
a.validateArgument(r === 48, "Header byte should be 0x30");
let i = t[1], u = t.subarray(2).length;
a.validateArgument(!e || i === u, "Length byte should length of what follows"), i = i < u ? i : u;
let f = t[2];
a.validateArgument(f === 2, "Integer byte for r should be 0x02");
let o = t[3], g = t.subarray(4, 4 + o), b = h.fromBuffer(g), A = t[4] === 0;
a.validateArgument(o === g.length, "Length of r incorrect");
let C = t[4 + o + 0];
a.validateArgument(C === 2, "Integer byte for s should be 0x02");
let R = t[4 + o + 1], D = t.subarray(4 + o + 2, 4 + o + 2 + R), $ = h.fromBuffer(D), W = t[4 + o + 2 + 2] === 0;
a.validateArgument(R === D.length, "Length of s incorrect");
let Tt = 4 + o + 2 + R;
return a.validateArgument(i === Tt - 2, "Length of signature incorrect"), {
header: r,
length: i,
rheader: f,
rlength: o,
rneg: A,
rbuf: g,
r: b,
sheader: C,
slength: R,
sneg: W,
sbuf: D,
s: $
};
}
/**
* ECDSA format. used for sign messages
*/
toCompact(t, e) {
t = typeof t == "number" ? t : this.i, e = typeof e == "boolean" ? e : this.compressed, a.validateArgument(t === 0 || t === 1 || t === 2 || t === 3, "i must be equal to 0, 1, 2, or 3");
let r = t + 27 + 4;
e === !1 && (r = r - 4);
let i = Uint8Array.from([r]), u = this.r.toByteArray({ size: 32 }), f = this.s.toByteArray({ size: 32 });
return s.concat([i, u, f]);
}
static fromCompact(t) {
a.validateArgument(s.isBuffer(t), "Argument is expected to be a Buffer");
let e = !0, r = t.subarray(0, 1)[0] - 27 - 4;
r < 0 && (e = !1, r = r + 4);
let i = t.subarray(1, 33), u = t.subarray(33, 65);
return a.validateArgument(r === 0 || r === 1 || r === 2 || r === 3, "i must be 0, 1, 2, or 3"), a.validateArgument(i.length === 32, "r must be 32 bytes"), a.validateArgument(u.length === 32, "s must be 32 bytes"), new N({ r: h.fromBuffer(i), s: h.fromBuffer(u), i: r, compressed: e });
}
}
class At {
hashbuf;
endian;
privkey;
pubkey;
sig;
verified;
constructor(t) {
t && this.set(t);
}
set(t) {
return this.hashbuf = t.hashbuf || this.hashbuf, this.endian = t.endian || this.endian, this.privkey = t.privkey || this.privkey, this.pubkey = t.pubkey || (this.privkey ? this.privkey.publicKey : this.pubkey), this.sig = t.sig || this.sig, this.verified = t.verified || this.verified, this;
}
sign() {
let t = this.hashbuf, e = this.privkey, r = e.bn;
a.validateState(t != null && e != null && r != null, "invalid parameters"), a.validateState(s.isBuffer(t) && t.length === 32, "hashbuf must be a 32 byte buffer");
let i = h.fromBuffer(t, this.endian ? { endian: this.endian } : void 0), u = this._findSignature(r, i);
return u.compressed = this.pubkey.compressed, this.sig = new N(u), this;
}
verify() {
return this.verified = !this.sigError(), this;
}
toPublicKey() {
return this.privkey.toPublicKey();
}
privkey2pubkey() {
this.pubkey = this.privkey.toPublicKey();
}
}
class S {
point;
compressed;
network;
/**
* @param data - The pubkey data
*/
constructor(t) {
if (a.validateArgument(t != null, "First argument is required, please include public key data."), t instanceof S)
return t;
if (S._isPublicKeyData(t))
t.point.validate(), this.point = t.point, this.compressed = t.compressed == null || t.compressed, this.network = t.network || y.defaultNetwork;
else
throw new TypeError("First argument is an unrecognized data format.");
}
toObject = this.toJSON;
toDER = this.toBuffer;
/**
* @returns A plain object of the PublicKey
*/
toJSON() {
return {
x: this.point.getX().toString("hex", 2),
y: this.point.getY().toString("hex", 2),
compressed: this.compressed,
network: this.network.toString()
};
}
/**
* Will output the PublicKey to a DER Uint8Array
*
* @returns A DER encoded buffer
*/
toBuffer() {
let t = this.point.getX(), e = this.point.getY(), r = t.toByteArray({ size: 32 }), i = e.toByteArray({ size: 32 }), u;
return this.compressed ? (i[i.length - 1] % 2 ? u = Uint8Array.from([3]) : u = Uint8Array.from([2]), s.concat([u, r])) : (u = Uint8Array.from([4]), s.concat([u, r, i]));
}
/**
* Will output the PublicKey to a DER encoded hex string
*
* @returns A DER hex encoded string
*/
toString() {
return s.bufferToHex(this.toBuffer());
}
/**
* Will return a string formatted for the console
*
* @returns Public key string inspection
*/
inspect() {
return "<PublicKey: " + this.toString() + (this.compressed ? "" : ", uncompressed") + ">";
}
/**
* Instantiate a PublicKey from various formats
*
* @param data The encoded data in various formats
* @param compressed If the public key is compressed
* @param network The key network
* @returns New PublicKey instance
*/
static from(t, e, r) {
if (t instanceof S)
return t;
if (t instanceof d)
return this.fromPoint(t, e, r);
if (this._isPublicKeyDto(t))
return this.fromObject(t);
if (this._isPublicKeyData(t))
return new S(t);
if (this._isPrivateKeyData(t))
return this.fromPrivateKey(t);
if (s.isBuffer(t))
return this.fromBuffer(t, !0, r);
if (I.isHexa(t))
return this.fromString(t, r);
throw new TypeError("First argument is an unrecognized data format.");
}
static fromDER = this.fromBuffer;
static fromObject = this.fromJSON;
/**
* Instantiate a PublicKey from a Uint8Array
*
* @param buf - A DER hex buffer
* @param strict - if set to false, will loosen some conditions
* @param network - the network of the key
* @returns A new valid instance of PublicKey
*/
static fromBuffer(t, e, r) {
a.validateArgument(s.isBuffer(t), "Must be a hex buffer of DER encoded public key");
let i = S._transformDER(t, e);
return new S({ point: i.point, compressed: i.compressed, network: r });
}
/**
* Instantiate a PublicKey from a Point
*
* @param point - A Point instance
* @param compressed - whether to store this public key as compressed format
* @param network - the network of the key
* @returns A new valid instance of PublicKey
*/
static fromPoint(t, e, r) {
return a.validateArgument(t instanceof d, "First argument must be an instance of Point."), new S({ point: t, compressed: e, network: r });
}
/**
* Instantiate a PublicKey from a DER hex encoded string
*
* @param str - A DER hex string
* @param network - the network of the key
* @returns A new valid instance of PublicKey
*/
static fromString(t, e) {
let r = s.hexToBuffer(t), i = S._transformDER(r);
return new S({ point: i.point, compressed: i.compressed, network: e });
}
/**
* Instantiate a PublicKey from PrivateKey data
*
* @param data - Object contains data of PrivateKey
* @returns A new valid instance of PublicKey
*/
static fromPrivateKey(t) {
a.validateArgument(this._isPrivateKeyData(t), "data", "Must be data of PrivateKey");
let e = d.getG().mul(t.bn);
return new S({ point: e, compressed: t.compressed, network: t.network });
}
static fromJSON(t) {
let e = S._transformObject(t);
return new S(e);
}
/**
* Check if there would be any errors when initializing a PublicKey
*
* @param data - The encoded data in various formats
* @returns An error if exists
*/
static getValidationError(t) {
try {
this.from(t);
} catch (e) {
return e;
}
}
/**
* Check if the parameters are valid
*
* @param data - The encoded data in various formats
* @returns true If the public key would be valid
*/
static isValid(t) {
return !S.getValidationError(t);
}
static _isPublicKeyData(t) {
return typeof t == "object" && t !== null && "point" in t && t.point instanceof d;
}
static _isPublicKeyDto(t) {
return typeof t == "object" && t !== null && "x" in t && "y" in t;
}
static _isPrivateKeyData(t) {
return typeof t == "object" && t !== null && "bn" in t && "network" in t;
}
/**
* Internal function to transform DER into a public key point
*
* @param buf - An hex encoded buffer
* @param strict - if set to false, will loosen some conditions
* @returns An object with keys: point and compressed
*/
static _transformDER(t, e) {
if (a.validateArgument(s.isBuffer(t), "Must be a hex buffer of DER encoded public key"), e = e ?? !0, t[0] === 4 || !e && (t[0] === 6 || t[0] === 7)) {
let r = t.subarray(1, 33), i = t.subarray(33, 65);
if (r.length !== 32 || i.length !== 32 || t.length !== 65)
throw new TypeError("Length of x and y must be 32 bytes");
let u = new h(r), f = new h(i);
return { point: d.ecPoint(u, f), compressed: !1 };
} else if (t[0] === 3) {
let r = t.subarray(1), i = new h(r);
return { point: d.ecPointFromX(!0, i), compressed: !0 };
} else if (t[0] === 2) {
let r = t.subarray(1), i = new h(r);
return { point: d.ecPointFromX(!1, i), compressed: !0 };
} else
throw new TypeError("Invalid DER format public key");
}
/**
* Internal function to transform a JSON into a public key point
*/
static _transformObject(t) {
a.validateArgument(typeof t.x == "string", "x", "must be a hex string"), a.validateArgument(typeof t.y == "string", "y", "must be a hex string");
let e = new h(t.x, "hex"), r = new h(t.y, "hex");
return { point: d.ecPoint(e, r), compressed: t.compressed, network: y.get(t.network) };
}
}
class V extends At {
k;
set(t) {
return this.k = t.k || this.k, super.set(t);
}
sigError() {
if (!s.isBuffer(this.hashbuf) || this.hashbuf.length !== 32)
return "hashbuf must be a 32 byte buffer";
let t = this.sig.r, e = this.sig.s;
if (!(t.gt(h.Zero) && t.lt(d.getN())) || !(e.gt(h.Zero) && e.lt(d.getN())))
return "r and s not in range";
let r = h.fromBuffer(this.hashbuf, this.endian ? { endian: this.endian } : void 0), i = d.getN(), u = e.invm(i), f = u.mul(r).umod(i), o = u.mul(t).umod(i), g = d.getG().mulAdd(new h(f), this.pubkey.point, new h(o));
return g.ecPoint.isInfinity() ? "p is infinity" : g.getX().umod(i).cmp(t) !== 0 ? "Invalid signature" : !1;
}
_findSignature(t, e) {
let r = d.getN(), i = d.getG(), u = 0, f, o, g, b;
do
(!this.k || u > 0) && this.deterministicK(u), u++, f = this.k, o = i.mul(f), g = o.getX().umod(r), b = f.invm(r).mul(e.add(t.mul(g))).umod(r);
while (g.cmp(h.Zero) <= 0 || b.cmp(h.Zero) <= 0);
return b = V.toLowS(new h(b)), { s: b, r: new h(g) };
}
static toLowS(t) {
return t.gt(h.fromBuffer(s.hexToBuffer("7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0"))) && (t = d.getN().sub(t)), t;
}
calcI() {
for (let t = 0; t < 4; t++) {
this.sig.i = t;
let e;
try {
e = this.toPublicKey();
} catch {
continue;
}
if (e.point.eq(this.pubkey.point))
return this.sig.compressed = this.pubkey.compressed, this;
}
throw this.sig.i = void 0, new Error("Unable to find valid recovery factor");
}
randomK() {
let t = d.getN(), e;
do
e = h.fromBuffer(s.getRandomBuffer(32));
while (!(e.lt(t) && e.gt(h.Zero)));
return this.k = e, this;
}
// https://tools.ietf.org/html/rfc6979#section-3.2
deterministicK(t) {
t == null && (t = 0);
let e = new Uint8Array(32);
e.fill(1);
let r = new Uint8Array(32);
r.fill(0);
let i = this.privkey.bn.toByteArray({ size: 32 }), u = this.endian === "little" ? s.reverse(this.hashbuf) : this.hashbuf;
r = p.sha256hmac(s.concat([e, Uint8Array.from([0]), i, u]), r), e = p.sha256hmac(e, r), r = p.sha256hmac(s.concat([e, Uint8Array.from([1]), i, u]), r), e = p.sha256hmac(e, r), e = p.sha256hmac(e, r);
let f = h.fromBuffer(e), o = d.getN();
for (let g = 0; g < t || !(f.lt(o) && f.gt(h.Zero)); g++)
r = p.sha256hmac(s.concat([e, Uint8Array.from([0])]), r), e = p.sha256hmac(e, r), e = p.sha256hmac(e, r), f = h.fromBuffer(e);
return this.k = f, this;
}
signRandomK() {
return this.randomK(), this.sign();
}
toString() {
let t = {};
return this.hashbuf && (t.hashbuf = s.bufferToHex(this.hashbuf)), this.privkey && (t.privkey = this.privkey.toString()), this.pubkey && (t.pubkey = this.pubkey.toString()), this.sig && (t.sig = this.sig.toString()), this.k && (t.k = this.k.toString()), JSON.stringify(t);
}
// Information about public key recovery:
// https://bitcointalk.org/index.php?topic=6430.0
// http://stackoverflow.com/questions/19665491/how-do-i-get-an-ecdsa-public-key-from-just-a-bitcoin-signature-sec1-4-1-6-k
toPublicKey() {
let t = this.sig.i;
a.validateArgument(t === 0 || t === 1 || t === 2 || t === 3, "i must be equal to 0, 1, 2, or 3");
let e = h.fromBuffer(this.hashbuf), r = this.sig.r, i = this.sig.s, u = t & 1, f = t >> 1, o = d.getN(), g = d.getG(), b = f ? r.add(o) : r, A = d.ecPointFromX(!!u, b);
if (!A.mul(o).ecPoint.isInfinity())
throw new Error("nR is not a valid curve point");
let R = e.neg().umod(o), D = r.invm(o), $ = A.mul(i).add(g.mul(new h(R))).mul(new h(D));
return S.fromPoint($, this.sig.compressed);
}
static fromString(t) {
let e = JSON.parse(t);
return new V(e);
}
static sign(t, e, r) {
return new V({
hashbuf: t,
endian: r,
privkey: e
}).sign().sig;
}
static verify(t, e, r, i) {
return new V({
hashbuf: t,
endian: i,
sig: e,
pubkey: r
}).verify().verified;
}
}
class L extends At {
sigError() {
if (!s.isBuffer(this.hashbuf) || this.hashbuf.length !== 32)
return "hashbuf must be a 32 byte buffer";
let t = L.getProperSizeBuffer(this.sig.r).length + L.getProperSizeBuffer(this.sig.s).length;
if (!(t === 64 || t === 65))
return "signature must be a 64 byte or 65 byte array";
let e = this.endian === "little" ? s.reverse(this.hashbuf) : this.hashbuf, r = this.pubkey.point, i = d.getG();
if (r.ecPoint.isInfinity()) return !0;
let u = this.sig.r, f = this.sig.s, o = new h("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFC2F", "hex"), g = d.getN();
if (u.gte(o) || f.gte(g))
return !0;
let b = L.getProperSizeBuffer(this.sig.r), A = d.pointToCompressed(r), C = p.sha256(s.concat([b, A, e])), R = h.fromBuffer(C, { endian: "big" }).umod(g), D = i.mul(f), $ = r.mul(g.sub(R)), W = D.add($);
return !!(W.ecPoint.isInfinity() || !W.hasSquare() || !W.getX().eq(u));
}
/**
* RFC6979 deterministic nonce generation used from https://reviews.bitcoinabc.org/D2501
*
* @param privkeybuf
* @param msgbuf
* @return BN nonce
*/
nonceFunctionRFC6979(t, e) {
let r = s.hexToBuffer("0101010101010101010101010101010101010101010101010101010101010101"), i = s.hexToBuffer("0000000000000000000000000000000000000000000000000000000000000000"), u = s.concat([t, e, new Uint8Array(0), Uint8Array.from("Schnorr+SHA256 ", (g) => g.charCodeAt(0))]);
i = p.sha256hmac(s.concat([r, s.hexToBuffer("00"), u]), i), r = p.sha256hmac(r, i), i = p.sha256hmac(s.concat([r, s.hexToBuffer("01"), u]), i), r = p.sha256hmac(r, i);
let f = new h(0), o;
for (; r = p.sha256hmac(r, i), o = h.fromBuffer(r), f = o, a.validateState(r.length >= 32, "V length should be >= 32"), !(f.gt(new h(0)) && f.lt(d.getN())); )
i = p.sha256hmac(s.concat([r, s.hexToBuffer("00")]), i), r = p.sha256hmac(r, i);
return f;
}
/**
* @remarks
* Important references for schnorr implementation {@link https://spec.nexa.org/forks/2019-05-15-schnorr/}
*
* @param d the private key
* @param e the message to be signed
*/
_findSignature(t, e) {
let r = d.getN(), i = d.getG();
a.validateState(!t.lte(new h(0)), "privkey out of field of curve"), a.validateState(!t.gte(r), "privkey out of field of curve");
let u = this.nonceFunctionRFC6979(t.toByteArray({ size: 32 }), e.toByteArray({ size: 32 })), f = i.mul(t), o = i.mul(u);
o.hasSquare() ? u = u : u = r.sub(u);
let g = o.getX(), A = h.fromBuffer(p.sha256(s.concat([L.getProperSizeBuffer(g), d.pointToCompressed(f), e.toByteArray({ size: 32 })]))).mul(t).add(u).mod(r);
return { r: g, s: A };
}
/**
* Function written to ensure s or r parts of signature is at least 32 bytes, when converting
* from a BN to type Uint8Array.
* The BN type naturally cuts off leading zeros, e.g.
* <BN: 4f92d8094f710bc11b93935ac157730dda26c5c2a856650dbd8ebcd730d2d4> 31 bytes
* Buffer <00 4f 92 d8 09 4f 71 0b c1 1b 93 93 5a c1 57 73 0d da 26 c5 c2 a8 56 65 0d bd 8e bc d7 30 d2 d4> 32 bytes
* Both types are equal, however Schnorr signatures must be a minimum of 64 bytes.
* In a previous implementation of this schnorr module, was resulting in 63 byte signatures.
* (Although it would have been verified, it's proper to ensure the min requirement)
*
* @param bn the r or s signature part
*/
static getProperSizeBuffer(t) {
return t.toByteArray().length < 32 ? t.toByteArray({ size: 32 }) : t.toByteArray();
}
static sign(t, e, r) {
return new L({
hashbuf: t,
endian: r,
privkey: e
}).sign().sig;
}
static verify(t, e, r, i) {
return new L({
hashbuf: t,
endian: i,
sig: e,
pubkey: r
}).verify().verified;
}
}
class z {
buf;
pos;
constructor(t) {
if (this.buf = new Uint8Array(), this.pos = 0, t != null)
if (s.isBuffer(t))
this.set({ buf: t });
else if (typeof t == "string") {
let e = s.hexToBuffer(t);
if (e.length * 2 != t.length)
throw new TypeError("Invalid hex string");
this.set({ buf: e });
} else if (typeof t == "object") {
let e = t;
this.set(e);
} else
throw new TypeError("Unrecognized argument for BufferReader");
}
set(t) {
return this.buf = t.buf || this.buf, this.pos = t.pos || this.pos || 0, this;
}
eof() {
return this.pos >= this.buf.length;
}
finished = this.eof;
read(t) {
a.validateArgument(t != null, "Must specify a length");
let e = this.buf.subarray(this.pos, this.pos + t);
return this.pos = this.pos + t, e;
}
readAll() {
let t = this.buf.subarray(this.pos, this.buf.length);
return this.pos = this.buf.length, t;
}
readUInt8() {
const e = new DataView(this.buf.buffer, this.buf.byteOffset, this.buf.byteLength).getUint8(this.pos);
return this.pos += 1, e;
}
readUInt16BE() {
const e = new DataView(this.buf.buffer, this.buf.byteOffset, this.buf.byteLength).getUint16(this.pos);
return this.pos += 2, e;
}
readUInt16LE() {
const e = new DataView(this.buf.buffer, this.buf.byteOffset, this.buf.byteLength).getUint16(this.pos, !0);
return this.pos += 2, e;
}
readUInt32BE() {
const e = new DataView(this.buf.buffer, this.buf.byteOffset, this.buf.byteLength).getUint32(this.pos);
return this.pos += 4, e;
}
readUInt32LE() {
const e = new DataView(this.buf.buffer, this.buf.byteOffset, this.buf.byteLength).getUint32(this.pos, !0);
return this.pos += 4, e;
}
readInt32LE() {
const e = new DataView(this.buf.buffer, this.buf.byteOffset, this.buf.byteLength).getInt32(this.pos, !0);
return this.pos += 4, e;
}
readUInt64BEBN() {
const e = new DataView(this.buf.buffer, this.buf.byteOffset, this.buf.byteLength).getBigUint64(this.pos);
return this.pos += 8, h.fromBigInt(e);
}
readUInt64LEBN() {
const e = new DataView(this.buf.buffer, this.buf.byteOffset, this.buf.byteLength).getBigUint64(this.pos, !0);
return this.pos += 8, h.fromBigInt(e);
}
readVarintNum() {
let t = this.readUInt8();
switch (t) {
case 253:
return this.readUInt16LE();
case 254:
return this.readUInt32LE();
case 255:
let r = this.readUInt64LEBN().toNumber();
if (r <= Math.pow(2, 53))
return r;
throw new Error("number too large to retain precision - use readVarintBN");
}
return t;
}
/**
* reads a length prepended buffer
*/
readVarLengthBuffer() {
let t = this.readVarintNum(), e = this.read(t);
return a.validateState(e.length === t, "Invalid length while reading varlength buffer. Expected to read: " + t + " and read " + e.length), e;
}
readVarintBuf() {
switch (this.buf[this.pos]) {
case 253:
return this.read(3);
case 254:
return this.read(5);
case 255:
return this.read(9);
default:
return this.read(1);
}
}
readVarintBN() {
let t = this.readUInt8();
switch (t) {
case 253:
return new h(this.readUInt16LE());
case 254:
return new h(this.readUInt32LE());
case 255:
return this.readUInt64LEBN();
default:
return new h(t);
}
}
reverse() {
let t = s.reverse(this.buf);
return this.buf = t, this;
}
readReverse(t) {
t == null && (t = this.buf.length);
let e = this.buf.subarray(this.pos, this.pos + t);
return this.pos = this.pos + t, s.reverse(e);
}
readCoreVarintNum() {
let t = 0;
for (; ; ) {
let e = this.readUInt8();
if (t = t << 7 | e & 127, e & 128)
t++;
else
return t;
}
}
}
class P {
bufs;
bufLen;
constructor(t) {
this.bufs = [], this.bufLen = 0, t && this.set(t);
}
set(t) {
return this.bufs = t.bufs || this.bufs, this.bufLen = this.bufs.reduce((e, r) => e + r.length, 0), this;
}
toBuffer() {
return this.concat();
}
concat() {
return s.concat(this.bufs, this.bufLen);
}
write(t) {
return a.validateArgument(s.isBuffer(t), "buf"), this.bufs.push(t), this.bufLen += t.length, this;
}
writeReverse(t) {
return a.validateArgument(s.isBuffer(t), "buf"), this.bufs.push(s.reverse(t)), this.bufLen += t.length, this;
}
writeUInt8(t) {
const e = new Uint8Array(1);
return new DataView(e.buffer).setUint8(0, t), this.write(e), this;
}
writeUInt16BE(t) {
const e = new Uint8Array(2);
return new DataView(e.buffer).setUint16(0, t), this.write(e), this;
}
writeUInt16LE(t) {
const e = new Uint8Array(2);
return new DataView(e.buffer).setUint16(0, t, !0), this.write(e), this;
}
writeUInt32BE(t) {
const e = new Uint8Array(4);
return new DataView(e.buffer).setUint32(0, t), this.write(e), this;
}
writeInt32LE(t) {
const e = new Uint8Array(4);
return new DataView(e.buffer).setInt32(0, t, !0), this.write(e), this;
}
writeUInt32LE(t) {
const e = new Uint8Array(4);
return new DataView(e.buffer).setUint32(0, t, !0), this.write(e), this;
}
writeUInt64BEBN(t) {
let e = t.toByteArray({ size: 8 });
return this.write(e), this;
}
writeUInt64LEBN(t) {
let e = t.toByteArray({ size: 8 });
return this.writeReverse(e), this;
}
writeVarintNum(t) {
let e = P.varintBufNum(t);
return this.write(e), this;
}
writeVarintBN(t) {
let e = P.varintBufBN(t);
return this.write(e), this;
}
writeVarLengthBuf(t) {
return a.validateArgument(s.isBuffer(t), "buf"), this.writeVarintNum(t.length), this.write(t), this;
}
writeCoreVarintNum(t) {
let e = [], r = 0;
for (; e.push(t & 127 | (r ? 128 : 0)), !(t <= 127); )
t = (t >> 7) - 1, r++;
return this.write(Uint8Array.from(e).reverse()), this;
}
static varintBufNum(t) {
let e;
if (t < 253)
e = new Uint8Array(1), e[0] = t & 255;
else if (t < 65536) {
e = new Uint8Array(3);
const r = new DataView(e.buffer);
e[0] = 253, r.setUint16(1, t, !0);
} else if (t < 4294967296) {
e = new Uint8Array(5);
const r = new DataView(e.buffer);
e[0] = 254, r.setUint32(1, t, !0);
} else {
e = new Uint8Array(9);
const r = new DataView(e.buffer);
e[0] = 255, r.setBigUint64(1, BigInt(t), !0);
}
return e;
}
static varintBufBN(t) {
let e, r = t.toNumber();
if (r < 253)
e = new Uint8Array(1), e[0] = r & 255;
else if (r < 65536) {
e = new Uint8Array(3);
const i = new DataView(e.buffer);
e[0] = 253, i.setUint16(1, r, !0);
} else if (r < 4294967296) {
e = new Uint8Array(5);
const i = new DataView(e.buffer);
e[0] = 254, i.setUint32(1, r, !0);
} else {
e = new Uint8Array(9);
const i = new DataView(e.buffer);
e[0] = 255, i.setBigUint64(1, t.toBigInt(), !0);
}
return e;
}
}
var Nt = /* @__PURE__ */ ((n) => (n[n.MEX = 8] = "MEX", n[n.KEX = 5] = "KEX", n[n.NEXA = 2] = "NEXA", n))(Nt || {});
class Pt {
/**
* 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(t, e) {
let r = 2;
return e != null && (a.validateArgument(Number.isInteger(e) && e >= 0, "unit", "invalid unit"), r = e), pt.divide(t, Math.pow(10, r), r);
}
/**
* 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(t, e) {
a.validateArgument(typeof t == "string", "value", "must be a string");
let r = 2;
return e != null && (a.validateArgument(Number.isInteger(e) && e >= 0, "unit", "invalid unit"), r = e), BigInt(pt.multiply(t, Math.pow(10, r)));
}
/**
* Converts `value` into a decimal string using 2 decimal places.
*/
static formatNEXA(t) {
return this.formatUnits(
t,
2
/* NEXA */
);
}
/**
* Converts the decimal string `NEXA` to a BigInt, using 2 decimal places.
*/
static parseNEXA(t) {
return this.parseUnits(
t,
2
/* NEXA */
);
}
}
class H {
static ALPHABET = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz".split("");
buf;
constructor(t) {
if (s.isBuffer(t)) {
let e = t;
this.fromBuffer(e);
} else if (typeof t == "string") {
let e = t;
this.fromString(e);
} else t && this.set(t);
}
toBuffer() {
return this.buf;
}
toString() {
return this.buf ? H.encode(this.buf) : "";
}
fromBuffer(t) {
return this.buf = t, this;
}
fromString(t) {
let e = H.decode(t);
return this.buf = e, this;
}
set(t) {
return this.buf = t.buf || this.buf || void 0, this;
}
static encode(t) {
if (!s.isBuffer(t))
throw new Error("Input should be a buffer");
return dt.encode(t);
}
static decode(t) {
if (typeof t != "string")
throw new Error("Input should be a string");
return Uint8Array.from(dt.decode(t));
}
static validCharacters(t) {
return s.isBuffer(t) && (t = s.bufferToUtf8(t)), t.split("").every((e) => H.ALPHABET.includes(e));
}
}
class F {
buf;
constructor(t) {
if (s.isBuffer(t)) {
let e = t;
this.fromBuffer(e);
} else if (typeof t == "string") {
let e = t;
this.fromString(e);
} else t && this.set(t);
}
static validChecksum(t, e) {
return typeof t == "string" && (t = Uint8Array.from(H.decode(t))), typeof e == "string" && (e = Uint8Array.from(H.decode(e))), e || (e = t.subarray(-4), t = t.subarray(0, -4)), s.bufferToHex(F.checksum(t)) === s.bufferToHex(e);
}
static decode(t) {
if (typeof t != "string")
throw new Error("Input must be a string");
let e = Uint8Array.from(H.decode(t));
if (e.length < 4)
throw new Error("Input string too short");
let r = e.subarray(0, -4), i = e.subarray(-4), f = p.sha256sha256(r).subarray(0, 4);
if (s.bufferToHex(i) !== s.bufferToHex(f))
throw new Error("Checksum mismatch");
return r;
}
static checksum(t) {
return p.sha256sha256(t).subarray(0, 4);
}
static encode(t) {
if (!s.isBuffer(t))
throw new Error("Input must be a buffer");
const e = new Uint8Array(t.length + 4), r = F.checksum(t);
return e.set(t, 0), e.set(r, t.length), H.encode(e);
}
toBuffer() {
return this.buf;
}
toString() {
return this.buf ? F.encode(this.buf) : "";
}
fromBuffer(t) {
return this.buf = t, this;
}
fromString(t) {
let e = F.decode(t);
return this.buf = e, this;
}
set(t) {
return this.buf = t.buf || this.buf || void 0, this;
}
}
class St {
/***
* Charset containing the 32 symbols used in the base32 encoding.
*/
static CHARSET = "qpzry9x8gf2tvdw0s3jn54khce6mua7l";
/***
* Inverted index mapping each symbol into its index wit