identity-based-encryption-bn254
Version:

9,790 lines • 351 kB
JavaScript
"use strict";
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __commonJS = (cb, mod2) => function __require() {
return mod2 || (0, cb[__getOwnPropNames(cb)[0]])((mod2 = { exports: {} }).exports, mod2), mod2.exports;
};
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toESM = (mod2, isNodeMode, target) => (target = mod2 != null ? __create(__getProtoOf(mod2)) : {}, __copyProps(
// If the importer is in node compatibility mode or this is not an ESM
// file that has been converted to a CommonJS file using a Babel-
// compatible transform (i.e. "__esModule" has not been set), then set
// "default" to the CommonJS "module.exports" for node compatibility.
isNodeMode || !mod2 || !mod2.__esModule ? __defProp(target, "default", { value: mod2, enumerable: true }) : target,
mod2
));
var __toCommonJS = (mod2) => __copyProps(__defProp({}, "__esModule", { value: true }), mod2);
// node_modules/@noble/hashes/cryptoNode.js
var require_cryptoNode = __commonJS({
"node_modules/@noble/hashes/cryptoNode.js"(exports2) {
"use strict";
Object.defineProperty(exports2, "__esModule", { value: true });
exports2.crypto = void 0;
var nc2 = require("node:crypto");
exports2.crypto = nc2 && typeof nc2 === "object" && "webcrypto" in nc2 ? nc2.webcrypto : nc2 && typeof nc2 === "object" && "randomBytes" in nc2 ? nc2 : void 0;
}
});
// node_modules/@noble/hashes/utils.js
var require_utils = __commonJS({
"node_modules/@noble/hashes/utils.js"(exports2) {
"use strict";
Object.defineProperty(exports2, "__esModule", { value: true });
exports2.wrapXOFConstructorWithOpts = exports2.wrapConstructorWithOpts = exports2.wrapConstructor = exports2.Hash = exports2.nextTick = exports2.swap32IfBE = exports2.byteSwapIfBE = exports2.swap8IfBE = exports2.isLE = void 0;
exports2.isBytes = isBytes3;
exports2.anumber = anumber2;
exports2.abytes = abytes3;
exports2.ahash = ahash;
exports2.aexists = aexists2;
exports2.aoutput = aoutput2;
exports2.u8 = u8;
exports2.u32 = u322;
exports2.clean = clean2;
exports2.createView = createView;
exports2.rotr = rotr;
exports2.rotl = rotl;
exports2.byteSwap = byteSwap2;
exports2.byteSwap32 = byteSwap322;
exports2.bytesToHex = bytesToHex2;
exports2.hexToBytes = hexToBytes2;
exports2.asyncLoop = asyncLoop;
exports2.utf8ToBytes = utf8ToBytes3;
exports2.bytesToUtf8 = bytesToUtf8;
exports2.toBytes = toBytes2;
exports2.kdfInputToBytes = kdfInputToBytes;
exports2.concatBytes = concatBytes2;
exports2.checkOpts = checkOpts;
exports2.createHasher = createHasher3;
exports2.createOptHasher = createOptHasher;
exports2.createXOFer = createXOFer2;
exports2.randomBytes = randomBytes2;
var crypto_1 = require_cryptoNode();
function isBytes3(a) {
return a instanceof Uint8Array || ArrayBuffer.isView(a) && a.constructor.name === "Uint8Array";
}
function anumber2(n) {
if (!Number.isSafeInteger(n) || n < 0)
throw new Error("positive integer expected, got " + n);
}
function abytes3(b, ...lengths) {
if (!isBytes3(b))
throw new Error("Uint8Array expected");
if (lengths.length > 0 && !lengths.includes(b.length))
throw new Error("Uint8Array expected of length " + lengths + ", got length=" + b.length);
}
function ahash(h) {
if (typeof h !== "function" || typeof h.create !== "function")
throw new Error("Hash should be wrapped by utils.createHasher");
anumber2(h.outputLen);
anumber2(h.blockLen);
}
function aexists2(instance, checkFinished = true) {
if (instance.destroyed)
throw new Error("Hash instance has been destroyed");
if (checkFinished && instance.finished)
throw new Error("Hash#digest() has already been called");
}
function aoutput2(out, instance) {
abytes3(out);
const min = instance.outputLen;
if (out.length < min) {
throw new Error("digestInto() expects output buffer of length at least " + min);
}
}
function u8(arr) {
return new Uint8Array(arr.buffer, arr.byteOffset, arr.byteLength);
}
function u322(arr) {
return new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4));
}
function clean2(...arrays) {
for (let i = 0; i < arrays.length; i++) {
arrays[i].fill(0);
}
}
function createView(arr) {
return new DataView(arr.buffer, arr.byteOffset, arr.byteLength);
}
function rotr(word, shift) {
return word << 32 - shift | word >>> shift;
}
function rotl(word, shift) {
return word << shift | word >>> 32 - shift >>> 0;
}
exports2.isLE = (() => new Uint8Array(new Uint32Array([287454020]).buffer)[0] === 68)();
function byteSwap2(word) {
return word << 24 & 4278190080 | word << 8 & 16711680 | word >>> 8 & 65280 | word >>> 24 & 255;
}
exports2.swap8IfBE = exports2.isLE ? (n) => n : (n) => byteSwap2(n);
exports2.byteSwapIfBE = exports2.swap8IfBE;
function byteSwap322(arr) {
for (let i = 0; i < arr.length; i++) {
arr[i] = byteSwap2(arr[i]);
}
return arr;
}
exports2.swap32IfBE = exports2.isLE ? (u) => u : byteSwap322;
var hasHexBuiltin = /* @__PURE__ */ (() => (
// @ts-ignore
typeof Uint8Array.from([]).toHex === "function" && typeof Uint8Array.fromHex === "function"
))();
var hexes2 = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, "0"));
function bytesToHex2(bytes) {
abytes3(bytes);
if (hasHexBuiltin)
return bytes.toHex();
let hex = "";
for (let i = 0; i < bytes.length; i++) {
hex += hexes2[bytes[i]];
}
return hex;
}
var asciis2 = { _0: 48, _9: 57, A: 65, F: 70, a: 97, f: 102 };
function asciiToBase162(ch) {
if (ch >= asciis2._0 && ch <= asciis2._9)
return ch - asciis2._0;
if (ch >= asciis2.A && ch <= asciis2.F)
return ch - (asciis2.A - 10);
if (ch >= asciis2.a && ch <= asciis2.f)
return ch - (asciis2.a - 10);
return;
}
function hexToBytes2(hex) {
if (typeof hex !== "string")
throw new Error("hex string expected, got " + typeof hex);
if (hasHexBuiltin)
return Uint8Array.fromHex(hex);
const hl = hex.length;
const al = hl / 2;
if (hl % 2)
throw new Error("hex string expected, got unpadded hex of length " + hl);
const array = new Uint8Array(al);
for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) {
const n1 = asciiToBase162(hex.charCodeAt(hi));
const n2 = asciiToBase162(hex.charCodeAt(hi + 1));
if (n1 === void 0 || n2 === void 0) {
const char = hex[hi] + hex[hi + 1];
throw new Error('hex string expected, got non-hex character "' + char + '" at index ' + hi);
}
array[ai] = n1 * 16 + n2;
}
return array;
}
var nextTick = async () => {
};
exports2.nextTick = nextTick;
async function asyncLoop(iters, tick, cb) {
let ts = Date.now();
for (let i = 0; i < iters; i++) {
cb(i);
const diff = Date.now() - ts;
if (diff >= 0 && diff < tick)
continue;
await (0, exports2.nextTick)();
ts += diff;
}
}
function utf8ToBytes3(str) {
if (typeof str !== "string")
throw new Error("string expected");
return new Uint8Array(new TextEncoder().encode(str));
}
function bytesToUtf8(bytes) {
return new TextDecoder().decode(bytes);
}
function toBytes2(data) {
if (typeof data === "string")
data = utf8ToBytes3(data);
abytes3(data);
return data;
}
function kdfInputToBytes(data) {
if (typeof data === "string")
data = utf8ToBytes3(data);
abytes3(data);
return data;
}
function concatBytes2(...arrays) {
let sum = 0;
for (let i = 0; i < arrays.length; i++) {
const a = arrays[i];
abytes3(a);
sum += a.length;
}
const res = new Uint8Array(sum);
for (let i = 0, pad = 0; i < arrays.length; i++) {
const a = arrays[i];
res.set(a, pad);
pad += a.length;
}
return res;
}
function checkOpts(defaults, opts) {
if (opts !== void 0 && {}.toString.call(opts) !== "[object Object]")
throw new Error("options should be object or undefined");
const merged = Object.assign(defaults, opts);
return merged;
}
var Hash2 = class {
};
exports2.Hash = Hash2;
function createHasher3(hashCons) {
const hashC = (msg) => hashCons().update(toBytes2(msg)).digest();
const tmp = hashCons();
hashC.outputLen = tmp.outputLen;
hashC.blockLen = tmp.blockLen;
hashC.create = () => hashCons();
return hashC;
}
function createOptHasher(hashCons) {
const hashC = (msg, opts) => hashCons(opts).update(toBytes2(msg)).digest();
const tmp = hashCons({});
hashC.outputLen = tmp.outputLen;
hashC.blockLen = tmp.blockLen;
hashC.create = (opts) => hashCons(opts);
return hashC;
}
function createXOFer2(hashCons) {
const hashC = (msg, opts) => hashCons(opts).update(toBytes2(msg)).digest();
const tmp = hashCons({});
hashC.outputLen = tmp.outputLen;
hashC.blockLen = tmp.blockLen;
hashC.create = (opts) => hashCons(opts);
return hashC;
}
exports2.wrapConstructor = createHasher3;
exports2.wrapConstructorWithOpts = createOptHasher;
exports2.wrapXOFConstructorWithOpts = createXOFer2;
function randomBytes2(bytesLength = 32) {
if (crypto_1.crypto && typeof crypto_1.crypto.getRandomValues === "function") {
return crypto_1.crypto.getRandomValues(new Uint8Array(bytesLength));
}
if (crypto_1.crypto && typeof crypto_1.crypto.randomBytes === "function") {
return Uint8Array.from(crypto_1.crypto.randomBytes(bytesLength));
}
throw new Error("crypto.getRandomValues must be defined");
}
}
});
// node_modules/@noble/curves/abstract/utils.js
var require_utils2 = __commonJS({
"node_modules/@noble/curves/abstract/utils.js"(exports2) {
"use strict";
Object.defineProperty(exports2, "__esModule", { value: true });
exports2.notImplemented = exports2.bitMask = void 0;
exports2.isBytes = isBytes3;
exports2.abytes = abytes3;
exports2.abool = abool2;
exports2.bytesToHex = bytesToHex2;
exports2.numberToHexUnpadded = numberToHexUnpadded2;
exports2.hexToNumber = hexToNumber2;
exports2.hexToBytes = hexToBytes2;
exports2.bytesToNumberBE = bytesToNumberBE2;
exports2.bytesToNumberLE = bytesToNumberLE2;
exports2.numberToBytesBE = numberToBytesBE2;
exports2.numberToBytesLE = numberToBytesLE2;
exports2.numberToVarBytesBE = numberToVarBytesBE2;
exports2.ensureBytes = ensureBytes2;
exports2.concatBytes = concatBytes2;
exports2.equalBytes = equalBytes2;
exports2.utf8ToBytes = utf8ToBytes3;
exports2.inRange = inRange2;
exports2.aInRange = aInRange2;
exports2.bitLen = bitLen2;
exports2.bitGet = bitGet2;
exports2.bitSet = bitSet2;
exports2.createHmacDrbg = createHmacDrbg2;
exports2.validateObject = validateObject2;
exports2.memoized = memoized2;
var _0n8 = /* @__PURE__ */ BigInt(0);
var _1n8 = /* @__PURE__ */ BigInt(1);
var _2n7 = /* @__PURE__ */ BigInt(2);
function isBytes3(a) {
return a instanceof Uint8Array || a != null && typeof a === "object" && a.constructor.name === "Uint8Array";
}
function abytes3(item) {
if (!isBytes3(item))
throw new Error("Uint8Array expected");
}
function abool2(title, value) {
if (typeof value !== "boolean")
throw new Error(`${title} must be valid boolean, got "${value}".`);
}
var hexes2 = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, "0"));
function bytesToHex2(bytes) {
abytes3(bytes);
let hex = "";
for (let i = 0; i < bytes.length; i++) {
hex += hexes2[bytes[i]];
}
return hex;
}
function numberToHexUnpadded2(num) {
const hex = num.toString(16);
return hex.length & 1 ? `0${hex}` : hex;
}
function hexToNumber2(hex) {
if (typeof hex !== "string")
throw new Error("hex string expected, got " + typeof hex);
return BigInt(hex === "" ? "0" : `0x${hex}`);
}
var asciis2 = { _0: 48, _9: 57, _A: 65, _F: 70, _a: 97, _f: 102 };
function asciiToBase162(char) {
if (char >= asciis2._0 && char <= asciis2._9)
return char - asciis2._0;
if (char >= asciis2._A && char <= asciis2._F)
return char - (asciis2._A - 10);
if (char >= asciis2._a && char <= asciis2._f)
return char - (asciis2._a - 10);
return;
}
function hexToBytes2(hex) {
if (typeof hex !== "string")
throw new Error("hex string expected, got " + typeof hex);
const hl = hex.length;
const al = hl / 2;
if (hl % 2)
throw new Error("padded hex string expected, got unpadded hex of length " + hl);
const array = new Uint8Array(al);
for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) {
const n1 = asciiToBase162(hex.charCodeAt(hi));
const n2 = asciiToBase162(hex.charCodeAt(hi + 1));
if (n1 === void 0 || n2 === void 0) {
const char = hex[hi] + hex[hi + 1];
throw new Error('hex string expected, got non-hex character "' + char + '" at index ' + hi);
}
array[ai] = n1 * 16 + n2;
}
return array;
}
function bytesToNumberBE2(bytes) {
return hexToNumber2(bytesToHex2(bytes));
}
function bytesToNumberLE2(bytes) {
abytes3(bytes);
return hexToNumber2(bytesToHex2(Uint8Array.from(bytes).reverse()));
}
function numberToBytesBE2(n, len) {
return hexToBytes2(n.toString(16).padStart(len * 2, "0"));
}
function numberToBytesLE2(n, len) {
return numberToBytesBE2(n, len).reverse();
}
function numberToVarBytesBE2(n) {
return hexToBytes2(numberToHexUnpadded2(n));
}
function ensureBytes2(title, hex, expectedLength) {
let res;
if (typeof hex === "string") {
try {
res = hexToBytes2(hex);
} catch (e) {
throw new Error(`${title} must be valid hex string, got "${hex}". Cause: ${e}`);
}
} else if (isBytes3(hex)) {
res = Uint8Array.from(hex);
} else {
throw new Error(`${title} must be hex string or Uint8Array`);
}
const len = res.length;
if (typeof expectedLength === "number" && len !== expectedLength)
throw new Error(`${title} expected ${expectedLength} bytes, got ${len}`);
return res;
}
function concatBytes2(...arrays) {
let sum = 0;
for (let i = 0; i < arrays.length; i++) {
const a = arrays[i];
abytes3(a);
sum += a.length;
}
const res = new Uint8Array(sum);
for (let i = 0, pad = 0; i < arrays.length; i++) {
const a = arrays[i];
res.set(a, pad);
pad += a.length;
}
return res;
}
function equalBytes2(a, b) {
if (a.length !== b.length)
return false;
let diff = 0;
for (let i = 0; i < a.length; i++)
diff |= a[i] ^ b[i];
return diff === 0;
}
function utf8ToBytes3(str) {
if (typeof str !== "string")
throw new Error(`utf8ToBytes expected string, got ${typeof str}`);
return new Uint8Array(new TextEncoder().encode(str));
}
var isPosBig2 = (n) => typeof n === "bigint" && _0n8 <= n;
function inRange2(n, min, max) {
return isPosBig2(n) && isPosBig2(min) && isPosBig2(max) && min <= n && n < max;
}
function aInRange2(title, n, min, max) {
if (!inRange2(n, min, max))
throw new Error(`expected valid ${title}: ${min} <= n < ${max}, got ${typeof n} ${n}`);
}
function bitLen2(n) {
let len;
for (len = 0; n > _0n8; n >>= _1n8, len += 1)
;
return len;
}
function bitGet2(n, pos) {
return n >> BigInt(pos) & _1n8;
}
function bitSet2(n, pos, value) {
return n | (value ? _1n8 : _0n8) << BigInt(pos);
}
var bitMask2 = (n) => (_2n7 << BigInt(n - 1)) - _1n8;
exports2.bitMask = bitMask2;
var u8n2 = (data) => new Uint8Array(data);
var u8fr2 = (arr) => Uint8Array.from(arr);
function createHmacDrbg2(hashLen, qByteLen, hmacFn) {
if (typeof hashLen !== "number" || hashLen < 2)
throw new Error("hashLen must be a number");
if (typeof qByteLen !== "number" || qByteLen < 2)
throw new Error("qByteLen must be a number");
if (typeof hmacFn !== "function")
throw new Error("hmacFn must be a function");
let v = u8n2(hashLen);
let k = u8n2(hashLen);
let i = 0;
const reset = () => {
v.fill(1);
k.fill(0);
i = 0;
};
const h = (...b) => hmacFn(k, v, ...b);
const reseed = (seed = u8n2()) => {
k = h(u8fr2([0]), seed);
v = h();
if (seed.length === 0)
return;
k = h(u8fr2([1]), seed);
v = h();
};
const gen2 = () => {
if (i++ >= 1e3)
throw new Error("drbg: tried 1000 values");
let len = 0;
const out = [];
while (len < qByteLen) {
v = h();
const sl = v.slice();
out.push(sl);
len += v.length;
}
return concatBytes2(...out);
};
const genUntil = (seed, pred) => {
reset();
reseed(seed);
let res = void 0;
while (!(res = pred(gen2())))
reseed();
reset();
return res;
};
return genUntil;
}
var validatorFns2 = {
bigint: (val) => typeof val === "bigint",
function: (val) => typeof val === "function",
boolean: (val) => typeof val === "boolean",
string: (val) => typeof val === "string",
stringOrUint8Array: (val) => typeof val === "string" || isBytes3(val),
isSafeInteger: (val) => Number.isSafeInteger(val),
array: (val) => Array.isArray(val),
field: (val, object) => object.Fp.isValid(val),
hash: (val) => typeof val === "function" && Number.isSafeInteger(val.outputLen)
};
function validateObject2(object, validators, optValidators = {}) {
const checkField = (fieldName, type, isOptional) => {
const checkVal = validatorFns2[type];
if (typeof checkVal !== "function")
throw new Error(`Invalid validator "${type}", expected function`);
const val = object[fieldName];
if (isOptional && val === void 0)
return;
if (!checkVal(val, object)) {
throw new Error(`Invalid param ${String(fieldName)}=${val} (${typeof val}), expected ${type}`);
}
};
for (const [fieldName, type] of Object.entries(validators))
checkField(fieldName, type, false);
for (const [fieldName, type] of Object.entries(optValidators))
checkField(fieldName, type, true);
return object;
}
var notImplemented2 = () => {
throw new Error("not implemented");
};
exports2.notImplemented = notImplemented2;
function memoized2(fn) {
const map = /* @__PURE__ */ new WeakMap();
return (arg, ...args) => {
const val = map.get(arg);
if (val !== void 0)
return val;
const computed = fn(arg, ...args);
map.set(arg, computed);
return computed;
};
}
}
});
// node_modules/@noble/curves/abstract/modular.js
var require_modular = __commonJS({
"node_modules/@noble/curves/abstract/modular.js"(exports2) {
"use strict";
Object.defineProperty(exports2, "__esModule", { value: true });
exports2.isNegativeLE = void 0;
exports2.mod = mod2;
exports2.pow = pow2;
exports2.pow2 = pow22;
exports2.invert = invert2;
exports2.tonelliShanks = tonelliShanks2;
exports2.FpSqrt = FpSqrt2;
exports2.validateField = validateField2;
exports2.FpPow = FpPow2;
exports2.FpInvertBatch = FpInvertBatch2;
exports2.FpDiv = FpDiv;
exports2.FpLegendre = FpLegendre2;
exports2.FpIsSquare = FpIsSquare2;
exports2.nLength = nLength2;
exports2.Field = Field2;
exports2.FpSqrtOdd = FpSqrtOdd;
exports2.FpSqrtEven = FpSqrtEven;
exports2.hashToPrivateScalar = hashToPrivateScalar;
exports2.getFieldBytesLength = getFieldBytesLength2;
exports2.getMinHashLength = getMinHashLength2;
exports2.mapHashToField = mapHashToField2;
var utils_js_1 = require_utils2();
var _0n8 = BigInt(0);
var _1n8 = BigInt(1);
var _2n7 = BigInt(2);
var _3n5 = BigInt(3);
var _4n3 = BigInt(4);
var _5n2 = BigInt(5);
var _8n2 = BigInt(8);
var _9n2 = BigInt(9);
var _16n2 = BigInt(16);
function mod2(a, b) {
const result = a % b;
return result >= _0n8 ? result : b + result;
}
function pow2(num, power, modulo) {
if (modulo <= _0n8 || power < _0n8)
throw new Error("Expected power/modulo > 0");
if (modulo === _1n8)
return _0n8;
let res = _1n8;
while (power > _0n8) {
if (power & _1n8)
res = res * num % modulo;
num = num * num % modulo;
power >>= _1n8;
}
return res;
}
function pow22(x, power, modulo) {
let res = x;
while (power-- > _0n8) {
res *= res;
res %= modulo;
}
return res;
}
function invert2(number, modulo) {
if (number === _0n8 || modulo <= _0n8) {
throw new Error(`invert: expected positive integers, got n=${number} mod=${modulo}`);
}
let a = mod2(number, modulo);
let b = modulo;
let x = _0n8, y = _1n8, u = _1n8, v = _0n8;
while (a !== _0n8) {
const q = b / a;
const r = b % a;
const m = x - u * q;
const n = y - v * q;
b = a, a = r, x = u, y = v, u = m, v = n;
}
const gcd = b;
if (gcd !== _1n8)
throw new Error("invert: does not exist");
return mod2(x, modulo);
}
function tonelliShanks2(P) {
const legendreC = (P - _1n8) / _2n7;
let Q, S, Z;
for (Q = P - _1n8, S = 0; Q % _2n7 === _0n8; Q /= _2n7, S++)
;
for (Z = _2n7; Z < P && pow2(Z, legendreC, P) !== P - _1n8; Z++)
;
if (S === 1) {
const p1div4 = (P + _1n8) / _4n3;
return function tonelliFast(Fp, n) {
const root = Fp.pow(n, p1div4);
if (!Fp.eql(Fp.sqr(root), n))
throw new Error("Cannot find square root");
return root;
};
}
const Q1div2 = (Q + _1n8) / _2n7;
return function tonelliSlow(Fp, n) {
if (Fp.pow(n, legendreC) === Fp.neg(Fp.ONE))
throw new Error("Cannot find square root");
let r = S;
let g = Fp.pow(Fp.mul(Fp.ONE, Z), Q);
let x = Fp.pow(n, Q1div2);
let b = Fp.pow(n, Q);
while (!Fp.eql(b, Fp.ONE)) {
if (Fp.eql(b, Fp.ZERO))
return Fp.ZERO;
let m = 1;
for (let t2 = Fp.sqr(b); m < r; m++) {
if (Fp.eql(t2, Fp.ONE))
break;
t2 = Fp.sqr(t2);
}
const ge = Fp.pow(g, _1n8 << BigInt(r - m - 1));
g = Fp.sqr(ge);
x = Fp.mul(x, ge);
b = Fp.mul(b, g);
r = m;
}
return x;
};
}
function FpSqrt2(P) {
if (P % _4n3 === _3n5) {
const p1div4 = (P + _1n8) / _4n3;
return function sqrt3mod4(Fp, n) {
const root = Fp.pow(n, p1div4);
if (!Fp.eql(Fp.sqr(root), n))
throw new Error("Cannot find square root");
return root;
};
}
if (P % _8n2 === _5n2) {
const c1 = (P - _5n2) / _8n2;
return function sqrt5mod8(Fp, n) {
const n2 = Fp.mul(n, _2n7);
const v = Fp.pow(n2, c1);
const nv = Fp.mul(n, v);
const i = Fp.mul(Fp.mul(nv, _2n7), v);
const root = Fp.mul(nv, Fp.sub(i, Fp.ONE));
if (!Fp.eql(Fp.sqr(root), n))
throw new Error("Cannot find square root");
return root;
};
}
if (P % _16n2 === _9n2) {
}
return tonelliShanks2(P);
}
var isNegativeLE = (num, modulo) => (mod2(num, modulo) & _1n8) === _1n8;
exports2.isNegativeLE = isNegativeLE;
var FIELD_FIELDS2 = [
"create",
"isValid",
"is0",
"neg",
"inv",
"sqrt",
"sqr",
"eql",
"add",
"sub",
"mul",
"pow",
"div",
"addN",
"subN",
"mulN",
"sqrN"
];
function validateField2(field) {
const initial = {
ORDER: "bigint",
MASK: "bigint",
BYTES: "isSafeInteger",
BITS: "isSafeInteger"
};
const opts = FIELD_FIELDS2.reduce((map, val) => {
map[val] = "function";
return map;
}, initial);
return (0, utils_js_1.validateObject)(field, opts);
}
function FpPow2(f, num, power) {
if (power < _0n8)
throw new Error("Expected power > 0");
if (power === _0n8)
return f.ONE;
if (power === _1n8)
return num;
let p = f.ONE;
let d = num;
while (power > _0n8) {
if (power & _1n8)
p = f.mul(p, d);
d = f.sqr(d);
power >>= _1n8;
}
return p;
}
function FpInvertBatch2(f, nums) {
const tmp = new Array(nums.length);
const lastMultiplied = nums.reduce((acc, num, i) => {
if (f.is0(num))
return acc;
tmp[i] = acc;
return f.mul(acc, num);
}, f.ONE);
const inverted = f.inv(lastMultiplied);
nums.reduceRight((acc, num, i) => {
if (f.is0(num))
return acc;
tmp[i] = f.mul(acc, tmp[i]);
return f.mul(acc, num);
}, inverted);
return tmp;
}
function FpDiv(f, lhs, rhs) {
return f.mul(lhs, typeof rhs === "bigint" ? invert2(rhs, f.ORDER) : f.inv(rhs));
}
function FpLegendre2(order) {
const legendreConst = (order - _1n8) / _2n7;
return (f, x) => f.pow(x, legendreConst);
}
function FpIsSquare2(f) {
const legendre = FpLegendre2(f.ORDER);
return (x) => {
const p = legendre(f, x);
return f.eql(p, f.ZERO) || f.eql(p, f.ONE);
};
}
function nLength2(n, nBitLength) {
const _nBitLength = nBitLength !== void 0 ? nBitLength : n.toString(2).length;
const nByteLength = Math.ceil(_nBitLength / 8);
return { nBitLength: _nBitLength, nByteLength };
}
function Field2(ORDER, bitLen2, isLE2 = false, redef = {}) {
if (ORDER <= _0n8)
throw new Error(`Expected Field ORDER > 0, got ${ORDER}`);
const { nBitLength: BITS, nByteLength: BYTES } = nLength2(ORDER, bitLen2);
if (BYTES > 2048)
throw new Error("Field lengths over 2048 bytes are not supported");
const sqrtP = FpSqrt2(ORDER);
const f = Object.freeze({
ORDER,
BITS,
BYTES,
MASK: (0, utils_js_1.bitMask)(BITS),
ZERO: _0n8,
ONE: _1n8,
create: (num) => mod2(num, ORDER),
isValid: (num) => {
if (typeof num !== "bigint")
throw new Error(`Invalid field element: expected bigint, got ${typeof num}`);
return _0n8 <= num && num < ORDER;
},
is0: (num) => num === _0n8,
isOdd: (num) => (num & _1n8) === _1n8,
neg: (num) => mod2(-num, ORDER),
eql: (lhs, rhs) => lhs === rhs,
sqr: (num) => mod2(num * num, ORDER),
add: (lhs, rhs) => mod2(lhs + rhs, ORDER),
sub: (lhs, rhs) => mod2(lhs - rhs, ORDER),
mul: (lhs, rhs) => mod2(lhs * rhs, ORDER),
pow: (num, power) => FpPow2(f, num, power),
div: (lhs, rhs) => mod2(lhs * invert2(rhs, ORDER), ORDER),
// Same as above, but doesn't normalize
sqrN: (num) => num * num,
addN: (lhs, rhs) => lhs + rhs,
subN: (lhs, rhs) => lhs - rhs,
mulN: (lhs, rhs) => lhs * rhs,
inv: (num) => invert2(num, ORDER),
sqrt: redef.sqrt || ((n) => sqrtP(f, n)),
invertBatch: (lst) => FpInvertBatch2(f, lst),
// TODO: do we really need constant cmov?
// We don't have const-time bigints anyway, so probably will be not very useful
cmov: (a, b, c) => c ? b : a,
toBytes: (num) => isLE2 ? (0, utils_js_1.numberToBytesLE)(num, BYTES) : (0, utils_js_1.numberToBytesBE)(num, BYTES),
fromBytes: (bytes) => {
if (bytes.length !== BYTES)
throw new Error(`Fp.fromBytes: expected ${BYTES}, got ${bytes.length}`);
return isLE2 ? (0, utils_js_1.bytesToNumberLE)(bytes) : (0, utils_js_1.bytesToNumberBE)(bytes);
}
});
return Object.freeze(f);
}
function FpSqrtOdd(Fp, elm) {
if (!Fp.isOdd)
throw new Error(`Field doesn't have isOdd`);
const root = Fp.sqrt(elm);
return Fp.isOdd(root) ? root : Fp.neg(root);
}
function FpSqrtEven(Fp, elm) {
if (!Fp.isOdd)
throw new Error(`Field doesn't have isOdd`);
const root = Fp.sqrt(elm);
return Fp.isOdd(root) ? Fp.neg(root) : root;
}
function hashToPrivateScalar(hash, groupOrder, isLE2 = false) {
hash = (0, utils_js_1.ensureBytes)("privateHash", hash);
const hashLen = hash.length;
const minLen = nLength2(groupOrder).nByteLength + 8;
if (minLen < 24 || hashLen < minLen || hashLen > 1024)
throw new Error(`hashToPrivateScalar: expected ${minLen}-1024 bytes of input, got ${hashLen}`);
const num = isLE2 ? (0, utils_js_1.bytesToNumberLE)(hash) : (0, utils_js_1.bytesToNumberBE)(hash);
return mod2(num, groupOrder - _1n8) + _1n8;
}
function getFieldBytesLength2(fieldOrder) {
if (typeof fieldOrder !== "bigint")
throw new Error("field order must be bigint");
const bitLength = fieldOrder.toString(2).length;
return Math.ceil(bitLength / 8);
}
function getMinHashLength2(fieldOrder) {
const length = getFieldBytesLength2(fieldOrder);
return length + Math.ceil(length / 2);
}
function mapHashToField2(key, fieldOrder, isLE2 = false) {
const len = key.length;
const fieldLen = getFieldBytesLength2(fieldOrder);
const minLen = getMinHashLength2(fieldOrder);
if (len < 16 || len < minLen || len > 1024)
throw new Error(`expected ${minLen}-1024 bytes of input, got ${len}`);
const num = isLE2 ? (0, utils_js_1.bytesToNumberBE)(key) : (0, utils_js_1.bytesToNumberLE)(key);
const reduced = mod2(num, fieldOrder - _1n8) + _1n8;
return isLE2 ? (0, utils_js_1.numberToBytesLE)(reduced, fieldLen) : (0, utils_js_1.numberToBytesBE)(reduced, fieldLen);
}
}
});
// node_modules/@noble/curves/abstract/hash-to-curve.js
var require_hash_to_curve = __commonJS({
"node_modules/@noble/curves/abstract/hash-to-curve.js"(exports2) {
"use strict";
Object.defineProperty(exports2, "__esModule", { value: true });
exports2.expand_message_xmd = expand_message_xmd2;
exports2.expand_message_xof = expand_message_xof2;
exports2.hash_to_field = hash_to_field2;
exports2.isogenyMap = isogenyMap;
exports2.createHasher = createHasher3;
var modular_js_1 = require_modular();
var utils_js_1 = require_utils2();
var os2ip2 = utils_js_1.bytesToNumberBE;
function i2osp2(value, length) {
anum2(value);
anum2(length);
if (value < 0 || value >= 1 << 8 * length) {
throw new Error(`bad I2OSP call: value=${value} length=${length}`);
}
const res = Array.from({ length }).fill(0);
for (let i = length - 1; i >= 0; i--) {
res[i] = value & 255;
value >>>= 8;
}
return new Uint8Array(res);
}
function strxor2(a, b) {
const arr = new Uint8Array(a.length);
for (let i = 0; i < a.length; i++) {
arr[i] = a[i] ^ b[i];
}
return arr;
}
function anum2(item) {
if (!Number.isSafeInteger(item))
throw new Error("number expected");
}
function expand_message_xmd2(msg, DST, lenInBytes, H) {
(0, utils_js_1.abytes)(msg);
(0, utils_js_1.abytes)(DST);
anum2(lenInBytes);
if (DST.length > 255)
DST = H((0, utils_js_1.concatBytes)((0, utils_js_1.utf8ToBytes)("H2C-OVERSIZE-DST-"), DST));
const { outputLen: b_in_bytes, blockLen: r_in_bytes } = H;
const ell = Math.ceil(lenInBytes / b_in_bytes);
if (lenInBytes > 65535 || ell > 255)
throw new Error("expand_message_xmd: invalid lenInBytes");
const DST_prime = (0, utils_js_1.concatBytes)(DST, i2osp2(DST.length, 1));
const Z_pad = i2osp2(0, r_in_bytes);
const l_i_b_str = i2osp2(lenInBytes, 2);
const b = new Array(ell);
const b_0 = H((0, utils_js_1.concatBytes)(Z_pad, msg, l_i_b_str, i2osp2(0, 1), DST_prime));
b[0] = H((0, utils_js_1.concatBytes)(b_0, i2osp2(1, 1), DST_prime));
for (let i = 1; i <= ell; i++) {
const args = [strxor2(b_0, b[i - 1]), i2osp2(i + 1, 1), DST_prime];
b[i] = H((0, utils_js_1.concatBytes)(...args));
}
const pseudo_random_bytes = (0, utils_js_1.concatBytes)(...b);
return pseudo_random_bytes.slice(0, lenInBytes);
}
function expand_message_xof2(msg, DST, lenInBytes, k, H) {
(0, utils_js_1.abytes)(msg);
(0, utils_js_1.abytes)(DST);
anum2(lenInBytes);
if (DST.length > 255) {
const dkLen = Math.ceil(2 * k / 8);
DST = H.create({ dkLen }).update((0, utils_js_1.utf8ToBytes)("H2C-OVERSIZE-DST-")).update(DST).digest();
}
if (lenInBytes > 65535 || DST.length > 255)
throw new Error("expand_message_xof: invalid lenInBytes");
return H.create({ dkLen: lenInBytes }).update(msg).update(i2osp2(lenInBytes, 2)).update(DST).update(i2osp2(DST.length, 1)).digest();
}
function hash_to_field2(msg, count, options) {
(0, utils_js_1.validateObject)(options, {
DST: "stringOrUint8Array",
p: "bigint",
m: "isSafeInteger",
k: "isSafeInteger",
hash: "hash"
});
const { p, k, m, hash, expand, DST: _DST } = options;
(0, utils_js_1.abytes)(msg);
anum2(count);
const DST = typeof _DST === "string" ? (0, utils_js_1.utf8ToBytes)(_DST) : _DST;
const log2p = p.toString(2).length;
const L = Math.ceil((log2p + k) / 8);
const len_in_bytes = count * m * L;
let prb;
if (expand === "xmd") {
prb = expand_message_xmd2(msg, DST, len_in_bytes, hash);
} else if (expand === "xof") {
prb = expand_message_xof2(msg, DST, len_in_bytes, k, hash);
} else if (expand === "_internal_pass") {
prb = msg;
} else {
throw new Error('expand must be "xmd" or "xof"');
}
const u = new Array(count);
for (let i = 0; i < count; i++) {
const e = new Array(m);
for (let j = 0; j < m; j++) {
const elm_offset = L * (j + i * m);
const tv = prb.subarray(elm_offset, elm_offset + L);
e[j] = (0, modular_js_1.mod)(os2ip2(tv), p);
}
u[i] = e;
}
return u;
}
function isogenyMap(field, map) {
const COEFF = map.map((i) => Array.from(i).reverse());
return (x, y) => {
const [xNum, xDen, yNum, yDen] = COEFF.map((val) => val.reduce((acc, i) => field.add(field.mul(acc, x), i)));
x = field.div(xNum, xDen);
y = field.mul(y, field.div(yNum, yDen));
return { x, y };
};
}
function createHasher3(Point, mapToCurve, def) {
if (typeof mapToCurve !== "function")
throw new Error("mapToCurve() must be defined");
return {
// Encodes byte string to elliptic curve.
// hash_to_curve from https://www.rfc-editor.org/rfc/rfc9380#section-3
hashToCurve(msg, options) {
const u = hash_to_field2(msg, 2, { ...def, DST: def.DST, ...options });
const u0 = Point.fromAffine(mapToCurve(u[0]));
const u1 = Point.fromAffine(mapToCurve(u[1]));
const P = u0.add(u1).clearCofactor();
P.assertValidity();
return P;
},
// Encodes byte string to elliptic curve.
// encode_to_curve from https://www.rfc-editor.org/rfc/rfc9380#section-3
encodeToCurve(msg, options) {
const u = hash_to_field2(msg, 1, { ...def, DST: def.encodeDST, ...options });
const P = Point.fromAffine(mapToCurve(u[0])).clearCofactor();
P.assertValidity();
return P;
},
// Same as encodeToCurve, but without hash
mapToCurve(scalars) {
if (!Array.isArray(scalars))
throw new Error("mapToCurve: expected array of bigints");
for (const i of scalars)
if (typeof i !== "bigint")
throw new Error(`mapToCurve: expected array of bigints, got ${i} in array`);
const P = Point.fromAffine(mapToCurve(scalars)).clearCofactor();
P.assertValidity();
return P;
}
};
}
}
});
// node_modules/@noble/curves/abstract/curve.js
var require_curve = __commonJS({
"node_modules/@noble/curves/abstract/curve.js"(exports2) {
"use strict";
Object.defineProperty(exports2, "__esModule", { value: true });
exports2.wNAF = wNAF2;
exports2.pippenger = pippenger2;
exports2.validateBasic = validateBasic2;
var modular_js_1 = require_modular();
var utils_js_1 = require_utils2();
var _0n8 = BigInt(0);
var _1n8 = BigInt(1);
var pointPrecomputes2 = /* @__PURE__ */ new WeakMap();
var pointWindowSizes2 = /* @__PURE__ */ new WeakMap();
function wNAF2(c, bits) {
const constTimeNegate = (condition, item) => {
const neg = item.negate();
return condition ? neg : item;
};
const validateW = (W) => {
if (!Number.isSafeInteger(W) || W <= 0 || W > bits)
throw new Error(`Wrong window size=${W}, should be [1..${bits}]`);
};
const opts = (W) => {
validateW(W);
const windows = Math.ceil(bits / W) + 1;
const windowSize = 2 ** (W - 1);
return { windows, windowSize };
};
return {
constTimeNegate,
// non-const time multiplication ladder
unsafeLadder(elm, n) {
let p = c.ZERO;
let d = elm;
while (n > _0n8) {
if (n & _1n8)
p = p.add(d);
d = d.double();
n >>= _1n8;
}
return p;
},
/**
* Creates a wNAF precomputation window. Used for caching.
* Default window size is set by `utils.precompute()` and is equal to 8.
* Number of precomputed points depends on the curve size:
* 2^(𝑊−1) * (Math.ceil(𝑛 / 𝑊) + 1), where:
* - 𝑊 is the window size
* - 𝑛 is the bitlength of the curve order.
* For a 256-bit curve and window size 8, the number of precomputed points is 128 * 33 = 4224.
* @returns precomputed point tables flattened to a single array
*/
precomputeWindow(elm, W) {
const { windows, windowSize } = opts(W);
const points = [];
let p = elm;
let base = p;
for (let window = 0; window < windows; window++) {
base = p;
points.push(base);
for (let i = 1; i < windowSize; i++) {
base = base.add(p);
points.push(base);
}
p = base.double();
}
return points;
},
/**
* Implements ec multiplication using precomputed tables and w-ary non-adjacent form.
* @param W window size
* @param precomputes precomputed tables
* @param n scalar (we don't check here, but should be less than curve order)
* @returns real and fake (for const-time) points
*/
wNAF(W, precomputes, n) {
const { windows, windowSize } = opts(W);
let p = c.ZERO;
let f = c.BASE;
const mask = BigInt(2 ** W - 1);
const maxNumber = 2 ** W;
const shiftBy = BigInt(W);
for (let window = 0; window < windows; window++) {
const offset = window * windowSize;
let wbits = Number(n & mask);
n >>= shiftBy;
if (wbits > windowSize) {
wbits -= maxNumber;
n += _1n8;
}
const offset1 = offset;
const offset2 = offset + Math.abs(wbits) - 1;
const cond1 = window % 2 !== 0;
const cond2 = wbits < 0;
if (wbits === 0) {
f = f.add(constTimeNegate(cond1, precomputes[offset1]));
} else {
p = p.add(constTimeNegate(cond2, precomputes[offset2]));
}
}
return { p, f };
},
wNAFCached(P, n, transform) {
const W = pointWindowSizes2.get(P) || 1;
let comp = pointPrecomputes2.get(P);
if (!comp) {
comp = this.precomputeWindow(P, W);
if (W !== 1)
pointPrecomputes2.set(P, transform(comp));
}
return this.wNAF(W, comp, n);
},
// We calculate precomputes for elliptic curve point multiplication
// using windowed method. This specifies window size and
// stores precomputed values. Usually only base point would be precomputed.
setWindowSize(P, W) {
validateW(W);
pointWindowSizes2.set(P, W);
pointPrecomputes2.delete(P);
}
};
}
function pippenger2(c, field, points, scalars) {
if (!Array.isArray(points) || !Array.isArray(scalars) || scalars.length !== points.length)
throw new Error("arrays of points and scalars must have equal length");
scalars.forEach((s, i) => {
if (!field.isValid(s))
throw new Error(`wrong scalar at index ${i}`);
});
points.forEach((p, i) => {
if (!(p instanceof c))
throw new Error(`wrong point at index ${i}`);
});
const wbits = (0, utils_js_1.bitLen)(BigInt(points.length));
const windowSize = wbits > 12 ? wbits - 3 : wbits > 4 ? wbits - 2 : wbits ? 2 : 1;
const MASK = (1 << windowSize) - 1;
const buckets = new Array(MASK + 1).fill(c.ZERO);
const lastBits = Math.floor((field.BITS - 1) / windowSize) * windowSize;
let sum = c.ZERO;
for (let i = lastBits; i >= 0; i -= windowSize) {
buckets.fill(c.ZERO);
for (let j = 0; j < scalars.length; j++) {
const scalar = scalars[j];
const wbits2 = Number(scalar >> BigInt(i) & BigInt(MASK));
buckets[wbits2] = buckets[wbits2].add(points[j]);
}
let resI = c.ZERO;
for (let j = buckets.length - 1, sumI = c.ZERO; j > 0; j--) {
sumI = sumI.add(buckets[j]);
resI = resI.add(sumI);
}
sum = sum.add(resI);
if (i !== 0)
for (let j = 0; j < windowSize; j++)
sum = sum.double();
}
return sum;
}
function validateBasic2(curve) {
(0, modular_js_1.validateField)(curve.Fp);
(0, utils_js_1.validateObject)(curve, {
n: "bigint",
h: "bigint",
Gx: "field",
Gy: "field"
}, {
nBitLength: "isSafeInteger",
nByteLength: "isSafeInteger"
});
return Object.freeze({
...(0, modular_js_1.nLength)(curve.n, curve.nBitLength),
...curve,
...{ p: curve.Fp.ORDER }
});
}
}
});
// node_modules/@noble/curves/abstract/weierstrass.js
var require_weierstrass = __commonJS({
"node_modules/@noble/curves/abstract/weierstrass.js"(exports2) {
"use strict";
Object.defineProperty(exports2, "__esModule", { value: true });
exports2.DER = void 0;
exports2.weierstrassPoints = weierstrassPoints2;
exports2.weierstrass = weierstrass;
exports2.SWUFpSqrtRatio = SWUFpSqrtRatio;
exports2.mapToCurveSimpleSWU = mapToCurveSimpleSWU;
var curve_js_1 = require_curve();
var mod2 = require_modular();
var ut = require_utils2();
var utils_js_1 = require_utils2();
function validateSigVerOpts(opts) {
if (opts.lowS !== void 0)
(0, utils_js_1.abool)("lowS", opts.lowS);
if (opts.prehash !== void 0)
(0, utils_js_1.abool)("prehash", opts.prehash);
}
function validatePointOpts2(curve) {
const opts = (0, curve_js_1.validateBasic)(curve);
ut.validateObject(opts, {
a: "field",
b: "field"
}, {
allowedPrivateKeyLengths: "array",
wrapPrivateKey: "boolean",
isTorsionFree: "function",
clearCofactor: "function",
allowInfinityPoint: "boolean",
fromBytes: "function",
toBytes: "function"
});
const { endo, Fp, a } = opts;
if (endo) {
if (!Fp.eql(a, Fp.ZERO)) {
throw new Error("Endomorphism can only be defined for Koblitz curves that have a=0");
}
if (typeof endo !== "object" || typeof endo.beta !== "bigint" || typeof endo.splitScalar !== "function") {
throw new Error("Expected endomorphism with beta: bigint and splitScalar: function");
}
}
return Object.freeze({ ...opts });
}
var { bytesToNumberBE: b2n2, hexToBytes: h2b2 } = ut;
exports2.DER = {
// asn.1 DER encoding utils
Err: class DERErr extends Error {
constructor(m = "") {
super(m);
}
},
// Basic building block is TLV (Tag-Length-Value)
_tlv: {
encode: (tag, data) => {
const { Err: E } = exports2.DER;
if (tag < 0 || tag > 256)
throw new E("tlv.encode: wrong tag");
if (data.length & 1)
throw new E("tlv.encode: unpadded data");
const dataLen = data.length / 2;
const len = ut.numberToHexUnpadded(dataLen);
if (len.length / 2 & 128)
throw new E("tlv.encode: long form length too big");
const lenLen = dataLen > 127 ? ut.numberToHexUnpadded(len.length / 2 | 128) : "";
return `${ut.numberToHexUnpadded(tag)}${lenLen}${len}${data}`;
},
// v - value, l - left bytes (unparsed)
decode(tag, data) {
const { Err: E } = exports2.DER;
let pos = 0;
if (tag < 0 || tag > 256)
throw new E("tlv.encode: wrong tag");
if (data.length < 2 || data[pos++] !== tag)
throw new E("tlv.decode: wrong tlv");
const first = data[pos++];
const isLong = !!(first & 128);
let length = 0;
if (!isLong)
length = first;
else {
const lenLen = first & 127;
if (!lenLen)
throw new E("tlv.decode(long): indefinite length not supported");
if (lenLen > 4)
throw new E("tlv.decode(long): byte length is too big");
const lengthBytes = data.subarray(pos, pos + lenLen);
if (lengthBytes.length !== lenLen)
throw new E("tlv.decode: length bytes not complete");
if (lengthBytes[0] === 0)
throw new E("tlv.decode(long): zero leftmost byte");
for (const b of lengthBytes)
length = length << 8 | b;
pos += lenLen;
if (length < 128)
throw new E("tlv.decode(long): not minimal encoding");
}
const v = data.subarray(pos, pos + length);
if (v.length !== length)
throw new E("tlv.decode: wrong value length");
return { v, l: data.subarray(pos + length) };
}
},
// https://crypto.stackexchange.com/a/57734 Leftmost bit of first byte is 'negative' flag,
// since we always use positive integers here. It must always be empty:
// - add zero byte if exists
// - if next byte doesn't have a flag, leading zero is not allowed (minimal encoding)
_int: {
encode(num) {
const { Err: E } = exports2.DER;
if (num < _0n8)
throw new E("integer: negative integers are not allowed");
let hex = ut.numberToHexUnpadded(num);
if (Number.parseInt(hex[0], 16) & 8)
hex = "00" + hex;
if (hex.length & 1)
throw new E("unexpected assertion");
return hex;
},
decode(data) {
const { Err: E } = exports2.DER;
if (data[0] & 128)
throw new E("Invalid signature integer: negative");
if (data[0] === 0 && !(data[1] & 128))
throw new E("Invalid signature integer: unnecessary leading zero");
return b2n2(data);
}
},
toSig(hex) {
const { Err: E, _int: int, _tlv: tlv } = exports2.DER;
const data = typeof hex === "string" ? h2b2(hex) : hex;
ut.abytes(data);
const { v: seqBytes, l: seqLeftBytes } = tlv.decode(48, data);
if (seqLeftBytes.length)
throw new E("Invalid signature: left bytes after parsing");
const { v: rBytes, l: rLeftBytes } = tlv.decode(2, seqBytes);
const { v: sBytes, l: sLeftBytes } = tlv.decode(2, rLeftBytes);
if (sLeftBytes.length)
throw new E("Invalid signature: left bytes after parsing");
return { r: int.decode(rBytes), s: int.decode(sBytes) };
},
hexFromSig(sig) {
const { _tlv: tlv, _int: int } = exports2.DER;
const seq = `${tlv.encode(2, int.encode(sig.r))}${tlv.encode(2, int.encode(sig.s))}`;
return tlv.encode(48, seq);
}
};
var _0n8 = BigInt(0);
var _1n8 = BigInt(1);
var _2n7 = BigInt(2);
var _3n5 = BigInt(3);
var _4n3 = BigInt(4);
function weierstrassPoints2(opts) {
const CURVE = validatePointOpts2(opts);
const { Fp } = CURVE;
const Fn = mod2.Field(CURVE.n, CURVE.nBitLength);
const toBytes2 = CURVE.toBytes || ((_c, point, _isCompressed) => {
const a = point.toAffine();
return ut.concatBytes(Uint8Array.from([4]), Fp.toBytes(a.x), Fp.toBytes(a.y));
});
const fromBytes = CURVE.fromBytes || ((bytes) => {
const tail = bytes.subarray(1);
const x = Fp.fromBytes(tail.subarray(0, Fp.BYTES));
const y = Fp.fromBytes(tail.subarray(Fp.BYTES, 2 * Fp.BYTES));
return { x, y };
});
function weierstrassEquation(x) {
const { a, b } = CURVE;
const x2 = Fp.sqr(x);
const x3 = Fp.mul(x2, x);
return Fp.add(Fp.add(x3, Fp.mul(x, a)), b);
}
if (!Fp.eql(Fp.sqr(CURVE.Gy), weierstrassEquation(CURVE.Gx)))
throw new Error("bad generator point: equation left != right");
function isWithinCurveOrder(num) {
return ut.inRange(num, _1n8, CURVE.n);
}
function normPrivateKeyToScalar(key) {
const { allowedPrivateKeyLengths: lengths, nByteLength, wrapPrivateKey, n: N } = CURVE;
if (lengths && typeof key !== "bigint") {
if (ut.isBytes(key))
key = ut.bytesToHex(key);
if (typeof key !== "string" || !lengths.includes(key.length))
throw new Error("Invalid key");
key = key.padStart(nByteLength * 2, "0");
}
let num;
try {
num = typeof key === "bigint" ? key : ut.bytesToNumberBE((0, utils_js_1.ensureBytes)("private key", key, nByteLength));
} catch (error) {
throw new Error(`private key must be ${nByteLength} bytes, hex or bigint, not ${typeof key}`);
}
if (wrapPrivateKey)
num = mod2.mod(num, N);
ut.aInRange("private key", num, _1n8, N);
return num;
}
function assertPrjPoint(other) {
if (!(other instanceof Point))
throw new Error("ProjectivePoint expected");
}
const toAffineMemo = (0, utils_js_1.memoized)((p, iz) => {
const { px: x, py: y, pz: z } = p;
if (Fp.eql(z, Fp.ONE))
return { x, y };
const is0 = p.is0();
if (iz == null)
iz = is0 ? Fp.ONE : Fp.inv(z);
const ax = Fp.mul(x, iz);
const ay = Fp.mul(y, iz);
const zz = Fp.mul(z, iz);
if (is0)
return { x: Fp.ZERO, y: Fp.ZERO };
if (!Fp.eql(zz, Fp.ONE))
throw new Error("invZ was invalid");
return { x: ax, y: ay };
});
const assertValidMemo = (0, utils_js_1.memoized)((p) => {
if (p.is0()) {
if (CURVE.allowInfinityPoint && !Fp.is0(p.py))
return;
throw new Error("bad point: ZERO");
}
const { x, y } = p.toAffine();
if (!Fp.isValid(x) || !Fp.isValid(y))
throw new Error("bad point: x or y not FE");
const left = Fp.sqr(y);
const right = weierstrassEquation(x);
if (!Fp.eql(left, right))
throw new Error("bad point: equation left != right");
if (!p.isTorsionFree())
throw new Error("bad point: not in prime-order subgroup");
return true;
});
class Point {
constructor(px, py, pz) {
this.px = px;
this.py = py;
this.pz = pz;
if (px == null || !Fp.isValid(px))
throw new Error("x required");
if (py == null || !Fp.isValid(py))
throw new Error("y required");
if (pz == null || !Fp.isValid(pz))
throw new Error("z required");
Object.freeze(this);
}
// Does not validate if the point is on-curve.
// Use fromHex instead, or call assertValidity() later.
static fromAffine(p) {
const { x, y } = p || {};
if (!p || !Fp.isValid(x) || !Fp.isValid(y))
throw new Error("invalid affine point");
if (p instanceof Point)
throw new Error("projective point not allowed");
const is0 = (i) => Fp.eql(i, Fp.ZERO);
if (is0(x) && is0(y))
return Point.ZERO;
return new Point(x, y, Fp.ONE);
}
get x() {
return this.toAffine().x;
}
get y() {
return this.toAffine().y;
}
/**
* Takes a bunch of Projective Points but executes only one
* inversion on all of them. Inversion is very slow operation,
* so this improves performance massively.
* Optimization: converts a list of projective points to a list of identical points with Z=1.
*/
static normalizeZ(points) {
const toInv = Fp.invertBatch(points.map((p) => p.pz));
return points.map((p, i) => p.toAffine(toInv[i])).map(Point.fromAffine);
}
/**
* Converts hash string or Uint8Array to Point.
* @param hex short/long ECDSA hex
*/
static fromHex(hex) {
const P = Point.fromAffine(fromBytes((0, utils_js_1.ensureBytes)("pointHex", hex)));
P.assertValidity();
return P;
}
// Multiplies generator point by privateKey.
static fromPrivateKey(privateKey) {
return Point.BASE.multiply(normPrivateKeyToScalar(privateKey));
}
// Multiscalar Multiplication
static msm(points, scalars) {
return (0, curve_js_1.pippenger)(Point, Fn, points, scalars);
}
// "Private method", don't use it directly
_setWindowSize(windowSize) {
wnaf.setWindowSize(this, windowSize);
}
// A point on curve is valid if it conforms to equation.
assertValidity() {
assertValidMemo(this);
}
hasEvenY() {
const { y } = this.toAffine();
if (Fp.isOdd)
return !Fp.isOdd(y);
throw new Error("Field doesn't support isOdd");
}
/**
* Compare one point to another.
*/
equals(other) {
assertPrjPoint(other);
const { px: X1, py: Y1, pz: Z1 } = this;
const { px: X2, py: Y2, pz: Z2 } = other;
const U1 = Fp.eql(Fp.mul(X1, Z2), Fp.mul(X2, Z1));
const U2 = Fp.eql(Fp.mul(Y1, Z2), Fp.mul(Y2, Z1));
return U1 && U2;
}
/**
* Flips point to one corresponding to (x, -y) in Affine coordinates.
*/
negate() {
return new Point(this.px, Fp.neg(this.py), this.pz);
}
// Renes-Costello-Batina exception-free doubling formula.
// There is 30% faster Jacobian formula, but it is not complete.
// https://eprint.iacr.org/2015/1060, algorithm 3
// Cost: 8M + 3S + 3*a + 2*b3 + 15add.
double() {
const { a, b } = CURVE;
const b3 = Fp.mul(b, _3n5);
const { px: X1, py: Y1, pz: Z1 } = this;
let X3 = Fp.ZERO, Y3 = Fp.ZERO, Z3 = Fp.ZERO;
let t0 = Fp.mul(X1, X1);
let t1 = Fp.mul(Y1, Y1);
let t2 = Fp.mul(Z1, Z1);
let t3 = Fp.mul(X1, Y1);
t3 = Fp.add(t3, t3);
Z3 = Fp.mul(X1, Z1);
Z3 = Fp.add(Z3, Z3);
X3 = Fp.mul(a, Z3);
Y3 = Fp.mul(b3, t2);
Y3 = Fp.add(X3, Y3);
X3 = Fp.sub(t1, Y3);
Y3 = Fp.add(t1, Y3);
Y3 = Fp.mul(X3, Y3);
X3 = Fp.mul(t3, X3);
Z3 = Fp.mul(b3, Z3);
t2 = Fp.mul(a, t2);
t3 = Fp.sub(t0, t2);
t3 = Fp.mul(a, t3);
t3 = Fp.add(t3, Z3);
Z3 = Fp.add(t0, t0);
t0 = Fp.add(Z3, t0);
t0 = Fp.add(t0, t2);
t0 = Fp.mul(t0, t3);
Y3 = Fp.add(Y3, t0);
t2 = Fp.mul(Y1, Z1);
t2 = Fp.add(t2, t2);
t0 = Fp.mul(t2, t3);
X3 = Fp.sub(X3, t0);
Z3 = Fp.mul(t2, t1);
Z3 = Fp.add(Z3, Z3);
Z3 = Fp.add(Z3, Z3);
return new Point(X3, Y3, Z3);
}
// Renes-Costello-Batina exception-free addition formula.
// There is 30% faster Jacobian formula, but it is not complete.
// https://eprint.iacr.org/2015/1060, algorithm 1
// Cost: 12M + 0S + 3*a + 3*b3 + 23add.
add(other) {
assertPrjPoint(other);
const { px: X1, py: Y1, pz: Z1 } = this;
const { px: X2, py: Y2, pz: Z2 } = other;
let X3 = Fp.ZERO, Y3 = Fp.ZERO, Z3 = Fp.ZERO;
const a = CURVE.a;
const b3 = Fp.mul(CURVE.b, _3n5);
let t0 = Fp.mul(X1, X2);
let t1 = Fp.mul(Y1, Y2);
let t2 = Fp.mul(Z1, Z2);
let t3 = Fp.add(X1, Y1);
let t4 = Fp.add(X2, Y2);
t3 = Fp.mul(t3, t4);
t4 = Fp.add(t0, t1);
t3 = Fp.sub(t3, t4);
t4 = Fp.add(X1, Z1);
let t5 = Fp.add(X2, Z2);
t4 = Fp.mul(t4, t5);
t5 = Fp.add(t0, t2);
t4 = Fp.sub(t4, t5);
t5 = Fp.add(Y1, Z1);
X3 = Fp.add(Y2, Z2);
t5 = Fp.mul(t5, X3);
X3 = Fp.add(t1, t2);
t5 = Fp.sub(t5, X3);
Z3 = Fp.mul(a, t4);
X3 = Fp.mul(b3, t2);
Z3 = Fp.add(X3, Z3);
X3 = Fp.sub(t1, Z3);
Z3 = Fp.add(t1, Z3);
Y3 = Fp.mul(X3, Z3);
t1 = Fp.add(t0, t0);
t1 = Fp.add(t1, t0);
t2 = Fp.mul(a, t2);
t4 = Fp.mul(b3, t4);
t1 = Fp.add(t1, t2);
t2 = Fp.sub(t0, t2);
t2 = Fp.mul(a, t2);
t4 = Fp.add(t4, t2);
t0 = Fp.mul(t1, t4);
Y3 = Fp.add(Y3, t0);
t0 = Fp.mul(t5, t4);
X3 = Fp.mul(t3, X3);
X3 = Fp.sub(X3, t0);
t0 = Fp.mul(t3, t1);
Z3 = Fp.mul(t5, Z3);
Z3 = Fp.add(Z3, t0);
return new Point(X3, Y3, Z3);
}
subtract(other) {
return this.add(other.negate());
}
is0() {
return this.equals(Point.ZERO);
}
wNAF(n) {
return wnaf.wNAFCached(this, n, Point.normalizeZ);
}
/**
* Non-constant-time multiplication. Uses double-and-add algorithm.
* It's faster, but should only be used when you don't care about
* an exposed private key e.g. sig verification, which works over *public* keys.
*/
multiplyUnsafe(sc) {
ut.aInRange("scalar", sc, _0n8, CURVE.n);
const I = Point.ZERO;
if (sc === _0n8)
return I;
if (sc === _1n8)
return this;
const { endo } = CURVE;
if (!endo)
return wnaf.unsafeLadder(this, sc);
let { k1neg, k1, k2neg, k2 } = endo.splitScalar(sc);
let k1p = I;
let k2p = I;
let d = this;
while (k1 > _0n8 || k2 > _0n8) {
if (k1 & _1n8)
k1p = k1p.add(d);
if (k2 & _1n8)
k2p = k2p.add(d);
d = d.double();
k1 >>= _1n8;
k2 >>= _1n8;
}
if (k1neg)
k1p = k1p.negate();
if (k2neg)
k2p = k2p.negate();
k2p = new Point(Fp.mul(k2p.px, endo.beta), k2p.py, k2p.pz);
return k1p.add(k2p);
}
/**
* Constant time multiplication.
* Uses wNAF method. Windowed method may be 10% faster,
* but takes 2x longer to generate and consumes 2x memory.
* Uses precomputes when available.
* Uses endomorphism for Koblitz curves.
* @param scalar by which the point would be multiplied
* @returns New point
*/
multiply(scalar) {
const { endo, n: N } = CURVE;
ut.aInRange("scalar", scalar, _1n8, N);
let point, fake;
if (endo) {
const { k1neg, k1, k2neg, k2 } = endo.splitScalar(scalar);
let { p: k1p, f: f1p } = this.wNAF(k1);
let { p: k2p, f: f2p } = this.wNAF(k2);
k1p = wnaf.constTimeNegate(k1neg, k1p);
k2p = wnaf.constTimeNegate(k2neg, k2p);
k2p = new Point(Fp.mul(k2p.px, endo.beta), k2p.py, k2p.pz);
point = k1p.add(k2p);
fake = f1p.add(f2p);
} else {
const { p, f } = this.wNAF(scalar);
point = p;
fake = f;
}
return Point.normalizeZ([point, fake])[0];
}
/**
* Efficiently calculate `aP + bQ`. Unsafe, can expose private key, if used incorrectly.
* Not using Strauss-Shamir trick: precomputation tables are faster.
* The trick could be useful if both P and Q are not G (not in our case).
* @returns non-zero affine point
*/
multiplyAndAddUnsafe(Q, a, b) {
const G = Point.BASE;
const mul = (P, a2) => a2 === _0n8 || a2 === _1n8 || !P.equals(G) ? P.multiplyUnsafe(a2) : P.multiply(a2);
const sum = mul(this, a).add(mul(Q, b));
return sum.is0() ? void 0 : sum;
}
// Converts Projective point to affine (x, y) coordinates.
// Can accept precomputed Z^-1 - for example, from invertBatch.
// (x, y, z) ∋ (x=x/z, y=y/z)
toAffine(iz) {
return toAffineMemo(this, iz);
}
isTorsionFree() {
const { h: cofactor, isTorsionFree } = CURVE;
if (cofactor === _1n8)
return true;
if (isTorsionFree)
return isTorsionFree(Point, this);
throw new Error("isTorsionFree() has not been declared for the elliptic curve");
}
clearCofactor() {
const { h: cofactor, clearCofactor } = CURVE;
if (cofactor === _1n8)
return this;
if (clearCofactor)
return clearCofactor(Point, this);
return this.multiplyUnsafe(CURVE.h);
}
toRawBytes(isCompressed = true) {
(0, utils_js_1.abool)("isCompressed", isCompressed);
this.assertValidity();
return toBytes2(Point, this, isCompressed);
}
toHex(isCompressed = true) {
(0, utils_js_1.abool)("isCompressed", isCompressed);
return ut.bytesToHex(this.toRawBytes(isCompressed));
}
}
Point.BASE = new Point(CURVE.Gx, CURVE.Gy, Fp.ONE);
Point.ZERO = new Point(Fp.ZERO, Fp.ONE, Fp.ZERO);
const _bits = CURVE.nBitLength;
const wnaf = (0, curve_js_1.wNAF)(Point, CURVE.endo ? Math.ceil(_bits / 2) : _bits);
return {
CURVE,
ProjectivePoint: Point,
normPrivateKeyToScalar,
weierstrassEquation,
isWithinCurveOrder
};
}
function validateOpts(curve) {
const opts = (0, curve_js_1.validateBasic)(curve);
ut.validateObject(opts, {
hash: "hash",
hmac: "function",
randomBytes: "function"
}, {
bits2int: "function",
bits2int_modN: "function",
lowS: "boolean"
});
return Object.freeze({ lowS: true, ...opts });
}
function weierstrass(curveDef) {
const CURVE = validateOpts(curveDef);
const { Fp, n: CURVE_ORDER } = CURVE;
const compressedLen = Fp.BYTES + 1;
const uncompressedLen = 2 * Fp.BYTES + 1;
function modN(a) {
return mod2.mod(a, CURVE_ORDER);
}
function invN(a) {
return mod2.invert(a, CURVE_ORDER);
}
const { ProjectivePoint: Point, normPrivateKeyToScalar, weierstrassEquation, isWithinCurveOrder } = weierstrassPoints2({
...CURVE,
toBytes(_c, point, isCompressed) {
const a = point.toAffine();
const x = Fp.toBytes(a.x);
const cat = ut.concatBytes;
(0, utils_js_1.abool)("isCompressed", isCompressed);
if (isCompressed) {
return cat(Uint8Array.from([point.hasEvenY() ? 2 : 3]), x);
} else {
return cat(Uint8Array.from([4]), x, Fp.toBytes(a.y));
}
},
fromBytes(bytes) {
const len = bytes.length;
const head = bytes[0];
const tail = bytes.subarray(1);
if (len === compressedLen && (head === 2 || head === 3)) {
const x = ut.bytesToNumberBE(tail);
if (!ut.inRange(x, _1n8, Fp.ORDER))
throw new Error("Point is not on curve");
const y2 = weierstrassEquation(x);
let y;
try {
y = Fp.sqrt(y2);
} catch (sqrtError) {
const suffix = sqrtError instanceof Error ? ": " + sqrtError.message : "";
throw new Error("Point is not on curve" + suffix);
}
const isYOdd = (y & _1n8) === _1n8;
const isHeadOdd = (head & 1) === 1;
if (isHeadOdd !== isYOdd)
y = Fp.neg(y);
return { x, y };
} else if (len === uncompressedLen && head === 4) {
const x = Fp.fromBytes(tail.subarray(0, Fp.BYTES));
const y = Fp.fromBytes(tail.subarray(Fp.BYTES, 2 * Fp.BYTES));
return { x, y };
} else {
throw new Error(`Point of length ${len} was invalid. Expected ${compressedLen} compressed bytes or ${uncompressedLen} uncompressed bytes`);
}
}
});
const numToNByteStr = (num) => ut.bytesToHex(ut.numberToBytesBE(num, CURVE.nByteLength));
function isBiggerThanHalfOrder(number) {
const HALF = CURVE_ORDER >> _1n8;
return number > HALF;
}
function normalizeS(s) {
return isBiggerThanHalfOrder(s) ? modN(-s) : s;
}
const slcNum = (b, from, to) => ut.bytesToNumberBE(b.slice(from, to));
class Signature {
constructor(r, s, recovery) {
this.r = r;
this.s = s;
this.recovery = recovery;
this.assertValidity();
}
// pair (bytes of r, bytes of s)
static fromCompact(hex) {
const l = CURVE.nByteLength;
hex = (0, utils_js_1.ensureBytes)("compactSignature", hex, l * 2);
return new Signature(slcNum(hex, 0, l), slcNum(hex, l, 2 * l));
}
// DER encoded ECDSA signature
// https://bitcoin.stackexchange.com/questions/57644/what-are-the-parts-of-a-bitcoin-transaction-input-script
static fromDER(hex) {
const { r, s } = exports2.DER.toSig((0, utils_js_1.ensureBytes)("DER", hex));
return new Signature(r, s);
}
assertValidity() {
ut.aInRange("r", this.r, _1n8, CURVE_ORDER);
ut.aInRange("s", this.s, _1n8, CURVE_ORDER);
}
addRecoveryBit(recovery) {
return new Signature(this.r, this.s, recovery);
}
recoverPublicKey(msgHash) {
const { r, s, recovery: rec } = this;
const h = bits2int_modN((0, utils_js_1.ensureBytes)("msgHash", msgHash));
if (rec == null || ![0, 1, 2, 3].includes(rec))
throw new Error("recovery id invalid");
const radj = rec === 2 || rec === 3 ? r + CURVE.n : r;
if (radj >= Fp.ORDER)
throw new Error("recovery id 2 or 3 invalid");
const prefix = (rec & 1) === 0 ? "02" : "03";
const R = Point.fromHex(prefix + numToNByteStr(radj));
const ir = invN(radj);
const u1 = modN(-h * ir);
const u2 = modN(s * ir);
const Q = Point.BASE.multiplyAndAddUnsafe(R, u1, u2);
if (!Q)
throw new Error("point at infinify");
Q.assertValidity();
return Q;
}
// Signatures should be low-s, to prevent malleability.
hasHighS() {
return isBiggerThanHalfOrder(this.s);
}
normalizeS() {
return this.hasHighS() ? new Signature(this.r, modN(-this.s), this.recovery) : this;
}
// DER-encoded
toDERRawBytes() {
return ut.hexToBytes(this.toDERHex());
}
toDERHex() {
return exports2.DER.hexFromSig({ r: this.r, s: this.s });
}
// padded bytes of r, then padded bytes of s
toCompactRawBytes() {
return ut.hexToBytes(this.toCompactHex());
}
toCompactHex() {
return numToNByteStr(this.r) + numToNByteStr(this.s);
}
}
const utils = {
isValidPrivateKey(privateKey) {
try {
normPrivateKeyToScalar(privateKey);
return true;
} catch (error) {
return false;
}
},
normPrivateKeyToScalar,
/**
* Produces cryptographically secure private key from random of size
* (groupLen + ceil(groupLen / 2)) with modulo bias being negligible.
*/
randomPrivateKey: () => {
const length = mod2.getMinHashLength(CURVE.n);
return mod2.mapHashToField(CURVE.randomBytes(length), CURVE.n);
},
/**
* Creates precompute table for an arbitrary EC point. Makes point "cached".
* Allows to massively speed-up `point.multiply(scalar)`.
* @returns cached point
* @example
* const fast = utils.precompute(8, ProjectivePoint.fromHex(someonesPubKey));
* fast.multiply(privKey); // much faster ECDH now
*/
precompute(windowSize = 8, point = Point.BASE) {
point._setWindowSize(windowSize);
point.multiply(BigInt(3));
return point;
}
};
function getPublicKey(privateKey, isCompressed = true) {
return Point.fromPrivateKey(privateKey).toRawBytes(isCompressed);
}
function isProbPub(item) {
const arr = ut.isBytes(item);
const str = typeof item === "string";
const len = (arr || str) && item.length;
if (arr)
return len === compressedLen || len === uncompressedLen;
if (str)
return len === 2 * compressedLen || len === 2 * uncompressedLen;
if (item instanceof Point)
return true;
return false;
}
function getSharedSecret(privateA, publicB, isCompressed = true) {
if (isProbPub(privateA))
throw new Error("first arg must be private key");
if (!isProbPub(publicB))
throw new Error("second arg must be public key");
const b = Point.fromHex(publicB);
return b.multiply(normPrivateKeyToScalar(privateA)).toRawBytes(isCompressed);
}
const bits2int = CURVE.bits2int || function(bytes) {
const num = ut.bytesToNumberBE(bytes);
const delta = bytes.length * 8 - CURVE.nBitLength;
return delta > 0 ? num >> BigInt(delta) : num;
};
const bits2int_modN = CURVE.bits2int_modN || function(bytes) {
return modN(bits2int(bytes));
};
const ORDER_MASK = ut.bitMask(CURVE.nBitLength);
function int2octets(num) {
ut.aInRange(`num < 2^${CURVE.nBitLength}`, num, _0n8, ORDER_MASK);
return ut.numberToBytesBE(num, CURVE.nByteLength);
}
function prepSig(msgHash, privateKey, opts = defaultSigOpts) {
if (["recovered", "canonical"].some((k) => k in opts))
throw new Error("sign() legacy options not supported");
const { hash, randomBytes: randomBytes2 } = CURVE;
let { lowS, prehash, extraEntropy: ent } = opts;
if (lowS == null)
lowS = true;
msgHash = (0, utils_js_1.ensureBytes)("msgHash", msgHash);
validateSigVerOpts(opts);
if (prehash)
msgHash = (0, utils_js_1.ensureBytes)("prehashed msgHash", hash(msgHash));
const h1int = bits2int_modN(msgHash);
const d = normPrivateKeyToScalar(privateKey);
const seedArgs = [int2octets(d), int2octets(h1int)];
if (ent != null && ent !== false) {
const e = ent === true ? randomBytes2(Fp.BYTES) : ent;
seedArgs.push((0, utils_js_1.ensureBytes)("extraEntropy", e));
}
const seed = ut.concatBytes(...seedArgs);
const m = h1int;
function k2sig(kBytes) {
const k = bits2int(kBytes);
if (!isWithinCurveOrder(k))
return;
const ik = invN(k);
const q = Point.BASE.multiply(k).toAffine();
const r = modN(q.x);
if (r === _0n8)
return;
const s = modN(ik * modN(m + r * d));
if (s === _0n8)
return;
let recovery = (q.x === r ? 0 : 2) | Number(q.y & _1n8);
let normS = s;
if (lowS && isBiggerThanHalfOrder(s)) {
normS = normalizeS(s);
recovery ^= 1;
}
return new Signature(r, normS, recovery);
}
return { seed, k2sig };
}
const defaultSigOpts = { lowS: CURVE.lowS, prehash: false };
const defaultVerOpts = { lowS: CURVE.lowS, prehash: false };
function sign(msgHash, privKey, opts = defaultSigOpts) {
const { seed, k2sig } = prepSig(msgHash, privKey, opts);
const C = CURVE;
const drbg = ut.createHmacDrbg(C.hash.outputLen, C.nByteLength, C.hmac);
return drbg(seed, k2sig);
}
Point.BASE._setWindowSize(8);
function verify(signature, msgHash, publicKey, opts = defaultVerOpts) {
const sg = signature;
msgHash = (0, utils_js_1.ensureBytes)("msgHash", msgHash);
publicKey = (0, utils_js_1.ensureBytes)("publicKey", publicKey);
if ("strict" in opts)
throw new Error("options.strict was renamed to lowS");
validateSigVerOpts(opts);
const { lowS, prehash } = opts;
let _sig = void 0;
let P;
try {
if (typeof sg === "string" || ut.isBytes(sg)) {
try {
_sig = Signature.fromDER(sg);
} catch (derError) {
if (!(derError instanceof exports2.DER.Err))
throw derError;
_sig = Signature.fromCompact(sg);
}
} else if (typeof sg === "object" && typeof sg.r === "bigint" && typeof sg.s === "bigint") {
const { r: r2, s: s2 } = sg;
_sig = new Signature(r2, s2);
} else {
throw new Error("PARSE");
}
P = Point.fromHex(publicKey);
} catch (error) {
if (error.message === "PARSE")
throw new Error(`signature must be Signature instance, Uint8Array or hex string`);
return false;
}
if (lowS && _sig.hasHighS())
return false;
if (prehash)
msgHash = CURVE.hash(msgHash);
const { r, s } = _sig;
const h = bits2int_modN(msgHash);
const is = invN(s);
const u1 = modN(h * is);
const u2 = modN(r * is);
const R = Point.BASE.multiplyAndAddUnsafe(P, u1, u2)?.toAffine();
if (!R)
return false;
const v = modN(R.x);
return v === r;
}
return {
CURVE,
getPublicKey,
getSharedSecret,
sign,
verify,
ProjectivePoint: Point,
Signature,
utils
};
}
function SWUFpSqrtRatio(Fp, Z) {
const q = Fp.ORDER;
let l = _0n8;
for (let o = q - _1n8; o % _2n7 === _0n8; o /= _2n7)
l += _1n8;
const c1 = l;
const _2n_pow_c1_1 = _2n7 << c1 - _1n8 - _1n8;
const _2n_pow_c1 = _2n_pow_c1_1 * _2n7;
const c2 = (q - _1n8) / _2n_pow_c1;
const c3 = (c2 - _1n8) / _2n7;
const c4 = _2n_pow_c1 - _1n8;
const c5 = _2n_pow_c1_1;
const c6 = Fp.pow(Z, c2);
const c7 = Fp.pow(Z, (c2 + _1n8) / _2n7);
let sqrtRatio = (u, v) => {
let tv1 = c6;
let tv2 = Fp.pow(v, c4);
let tv3 = Fp.sqr(tv2);
tv3 = Fp.mul(tv3, v);
let tv5 = Fp.mul(u, tv3);
tv5 = Fp.pow(tv5, c3);
tv5 = Fp.mul(tv5, tv2);
tv2 = Fp.mul(tv5, v);
tv3 = Fp.mul(tv5, u);
let tv4 = Fp.mul(tv3, tv2);
tv5 = Fp.pow(tv4, c5);
let isQR = Fp.eql(tv5, Fp.ONE);
tv2 = Fp.mul(tv3, c7);
tv5 = Fp.mul(tv4, tv1);
tv3 = Fp.cmov(tv2, tv3, isQR);
tv4 = Fp.cmov(tv5, tv4, isQR);
for (let i = c1; i > _1n8; i--) {
let tv52 = i - _2n7;
tv52 = _2n7 << tv52 - _1n8;
let tvv5 = Fp.pow(tv4, tv52);
const e1 = Fp.eql(tvv5, Fp.ONE);
tv2 = Fp.mul(tv3, tv1);
tv1 = Fp.mul(tv1, tv1);
tvv5 = Fp.mul(tv4, tv1);
tv3 = Fp.cmov(tv2, tv3, e1);
tv4 = Fp.cmov(tvv5, tv4, e1);
}
return { isValid: isQR, value: tv3 };
};
if (Fp.ORDER % _4n3 === _3n5) {
const c12 = (Fp.ORDER - _3n5) / _4n3;
const c22 = Fp.sqrt(Fp.neg(Z));
sqrtRatio = (u, v) => {
let tv1 = Fp.sqr(v);
const tv2 = Fp.mul(u, v);
tv1 = Fp.mul(tv1, tv2);
let y1 = Fp.pow(tv1, c12);
y1 = Fp.mul(y1, tv2);
const y2 = Fp.mul(y1, c22);
const tv3 = Fp.mul(Fp.sqr(y1), v);
const isQR = Fp.eql(tv3, u);
let y = Fp.cmov(y2, y1, isQR);
return { isValid: isQR, value: y };
};
}
return sqrtRatio;
}
function mapToCurveSimpleSWU(Fp, opts) {
mod2.validateField(Fp);
if (!Fp.isValid(opts.A) || !Fp.isValid(opts.B) || !Fp.isValid(opts.Z))
throw new Error("mapToCurveSimpleSWU: invalid opts");
const sqrtRatio = SWUFpSqrtRatio(Fp, opts.Z);
if (!Fp.isOdd)
throw new Error("Fp.isOdd is not implemented!");
return (u) => {
let tv1, tv2, tv3, tv4, tv5, tv6, x, y;
tv1 = Fp.sqr(u);
tv1 = Fp.mul(tv1, opts.Z);
tv2 = Fp.sqr(tv1);
tv2 = Fp.add(tv2, tv1);
tv3 = Fp.add(tv2, Fp.ONE);
tv3 = Fp.mul(tv3, opts.B);
tv4 = Fp.cmov(opts.Z, Fp.neg(tv2), !Fp.eql(tv2, Fp.ZERO));
tv4 = Fp.mul(tv4, opts.A);
tv2 = Fp.sqr(tv3);
tv6 = Fp.sqr(tv4);
tv5 = Fp.mul(tv6, opts.A);
tv2 = Fp.add(tv2, tv5);
tv2 = Fp.mul(tv2, tv3);
tv6 = Fp.mul(tv6, tv4);
tv5 = Fp.mul(tv6, opts.B);
tv2 = Fp.add(tv2, tv5);
x = Fp.mul(tv1, tv3);
const { isValid, value } = sqrtRatio(tv2, tv6);
y = Fp.mul(tv1, u);
y = Fp.mul(y, value);
x = Fp.cmov(x, tv3, isValid);
y = Fp.cmov(y, value, isValid);
const e1 = Fp.isOdd(u) === Fp.isOdd(y);
y = Fp.cmov(Fp.neg(y), y, e1);
x = Fp.div(x, tv4);
return { x, y };
};
}
}
});
// node_modules/@noble/curves/abstract/bls.js
var require_bls = __commonJS({
"node_modules/@noble/curves/abstract/bls.js"(exports2) {
"use strict";
Object.defineProperty(exports2, "__esModule", { value: true });
exports2.bls = bls2;
var modular_js_1 = require_modular();
var utils_js_1 = require_utils2();
var hash_to_curve_js_1 = require_hash_to_curve();
var weierstrass_js_1 = require_weierstrass();
var _0n8 = BigInt(0);
var _1n8 = BigInt(1);
var _2n7 = BigInt(2);
var _3n5 = BigInt(3);
function NAfDecomposition2(a) {
const res = [];
for (; a > _1n8; a >>= _1n8) {
if ((a & _1n8) === _0n8)
res.unshift(0);
else if ((a & _3n5) === _3n5) {
res.unshift(-1);
a += _1n8;
} else
res.unshift(1);
}
return res;
}
function bls2(CURVE) {
const { Fp, Fr, Fp2, Fp6, Fp12 } = CURVE.fields;
const BLS_X_IS_NEGATIVE = CURVE.params.xNegative;
const TWIST = CURVE.params.twistType;
const G1_ = (0, weierstrass_js_1.weierstrassPoints)({ n: Fr.ORDER, ...CURVE.G1 });
const G1 = Object.assign(G1_, (0, hash_to_curve_js_1.createHasher)(G1_.ProjectivePoint, CURVE.G1.mapToCurve, {
...CURVE.htfDefaults,
...CURVE.G1.htfDefaults
}));
const G2_ = (0, weierstrass_js_1.weierstrassPoints)({ n: Fr.ORDER, ...CURVE.G2 });
const G22 = Object.assign(G2_, (0, hash_to_curve_js_1.createHasher)(G2_.ProjectivePoint, CURVE.G2.mapToCurve, {
...CURVE.htfDefaults,
...CURVE.G2.htfDefaults
}));
let lineFunction;
if (TWIST === "multiplicative") {
lineFunction = (c0, c1, c2, f, Px, Py) => Fp12.mul014(f, c0, Fp2.mul(c1, Px), Fp2.mul(c2, Py));
} else if (TWIST === "divisive") {
lineFunction = (c0, c1, c2, f, Px, Py) => Fp12.mul034(f, Fp2.mul(c2, Py), Fp2.mul(c1, Px), c0);
} else
throw new Error("bls: unknown twist type");
const Fp2div2 = Fp2.div(Fp2.ONE, Fp2.mul(Fp2.ONE, _2n7));
function pointDouble(ell, Rx, Ry, Rz) {
const t0 = Fp2.sqr(Ry);
const t1 = Fp2.sqr(Rz);
const t2 = Fp2.mulByB(Fp2.mul(t1, _3n5));
const t3 = Fp2.mul(t2, _3n5);
const t4 = Fp2.sub(Fp2.sub(Fp2.sqr(Fp2.add(Ry, Rz)), t1), t0);
const c0 = Fp2.sub(t2, t0);
const c1 = Fp2.mul(Fp2.sqr(Rx), _3n5);
const c2 = Fp2.neg(t4);
ell.push([c0, c1, c2]);
Rx = Fp2.mul(Fp2.mul(Fp2.mul(Fp2.sub(t0, t3), Rx), Ry), Fp2div2);
Ry = Fp2.sub(Fp2.sqr(Fp2.mul(Fp2.add(t0, t3), Fp2div2)), Fp2.mul(Fp2.sqr(t2), _3n5));
Rz = Fp2.mul(t0, t4);
return { Rx, Ry, Rz };
}
function pointAdd(ell, Rx, Ry, Rz, Qx, Qy) {
const t0 = Fp2.sub(Ry, Fp2.mul(Qy, Rz));
const t1 = Fp2.sub(Rx, Fp2.mul(Qx, Rz));
const c0 = Fp2.sub(Fp2.mul(t0, Qx), Fp2.mul(t1, Qy));
const c1 = Fp2.neg(t0);
const c2 = t1;
ell.push([c0, c1, c2]);
const t2 = Fp2.sqr(t1);
const t3 = Fp2.mul(t2, t1);
const t4 = Fp2.mul(t2, Rx);
const t5 = Fp2.add(Fp2.sub(t3, Fp2.mul(t4, _2n7)), Fp2.mul(Fp2.sqr(t0), Rz));
Rx = Fp2.mul(t1, t5);
Ry = Fp2.sub(Fp2.mul(Fp2.sub(t4, t5), t0), Fp2.mul(t3, Ry));
Rz = Fp2.mul(Rz, t3);
return { Rx, Ry, Rz };
}
const ATE_NAF = NAfDecomposition2(CURVE.params.ateLoopSize);
const calcPairingPrecomputes = (0, utils_js_1.memoized)((point) => {
const p = point;
const { x, y } = p.toAffine();
const Qx = x, Qy = y, negQy = Fp2.neg(y);
let Rx = Qx, Ry = Qy, Rz = Fp2.ONE;
const ell = [];
for (const bit of ATE_NAF) {
const cur = [];
({ Rx, Ry, Rz } = pointDouble(cur, Rx, Ry, Rz));
if (bit)
({ Rx, Ry, Rz } = pointAdd(cur, Rx, Ry, Rz, Qx, bit === -1 ? negQy : Qy));
ell.push(cur);
}
if (CURVE.postPrecompute) {
const last = ell[ell.length - 1];
CURVE.postPrecompute(Rx, Ry, Rz, Qx, Qy, pointAdd.bind(null, last));
}
return ell;
});
function millerLoopBatch(pairs, withFinalExponent = false) {
let f12 = Fp12.ONE;
if (pairs.length) {
const ellLen = pairs[0][0].length;
for (let i = 0; i < ellLen; i++) {
f12 = Fp12.sqr(f12);
for (const [ell, Px, Py] of pairs) {
for (const [c0, c1, c2] of ell[i])
f12 = lineFunction(c0, c1, c2, f12, Px, Py);
}
}
}
if (BLS_X_IS_NEGATIVE)
f12 = Fp12.conjugate(f12);
return withFinalExponent ? Fp12.finalExponentiate(f12) : f12;
}
function pairingBatch(pairs, withFinalExponent = true) {
const res = [];
G1.ProjectivePoint.normalizeZ(pairs.map(({ g1 }) => g1));
G22.ProjectivePoint.normalizeZ(pairs.map(({ g2 }) => g2));
for (const { g1, g2 } of pairs) {
if (g1.equals(G1.ProjectivePoint.ZERO) || g2.equals(G22.ProjectivePoint.ZERO))
throw new Error("pairing is not available for ZERO point");
g1.assertValidity();
g2.assertValidity();
const Qa = g1.toAffine();
res.push([calcPairingPrecomputes(g2), Qa.x, Qa.y]);
}
return millerLoopBatch(res, withFinalExponent);
}
function pairing(Q, P, withFinalExponent = true) {
return pairingBatch([{ g1: Q, g2: P }], withFinalExponent);
}
const utils = {
randomPrivateKey: () => {
const length = (0, modular_js_1.getMinHashLength)(Fr.ORDER);
return (0, modular_js_1.mapHashToField)(CURVE.randomBytes(length), Fr.ORDER);
},
calcPairingPrecomputes
};
const { ShortSignature } = CURVE.G1;
const { Signature } = CURVE.G2;
function normP1(point) {
return point instanceof G1.ProjectivePoint ? point : G1.ProjectivePoint.fromHex(point);
}
function normP1Hash(point, htfOpts) {
return point instanceof G1.ProjectivePoint ? point : G1.hashToCurve((0, utils_js_1.ensureBytes)("point", point), htfOpts);
}
function normP2(point) {
return point instanceof G22.ProjectivePoint ? point : Signature.fromHex(point);
}
function normP2Hash(point, htfOpts) {
return point instanceof G22.ProjectivePoint ? point : G22.hashToCurve((0, utils_js_1.ensureBytes)("point", point), htfOpts);
}
function getPublicKey(privateKey) {
return G1.ProjectivePoint.fromPrivateKey(privateKey).toRawBytes(true);
}
function getPublicKeyForShortSignatures(privateKey) {
return G22.ProjectivePoint.fromPrivateKey(privateKey).toRawBytes(true);
}
function sign(message, privateKey, htfOpts) {
const msgPoint = normP2Hash(message, htfOpts);
msgPoint.assertValidity();
const sigPoint = msgPoint.multiply(G1.normPrivateKeyToScalar(privateKey));
if (message instanceof G22.ProjectivePoint)
return sigPoint;
return Signature.toRawBytes(sigPoint);
}
function signShortSignature(message, privateKey, htfOpts) {
const msgPoint = normP1Hash(message, htfOpts);
msgPoint.assertValidity();
const sigPoint = msgPoint.multiply(G1.normPrivateKeyToScalar(privateKey));
if (message instanceof G1.ProjectivePoint)
return sigPoint;
return ShortSignature.toRawBytes(sigPoint);
}
function verify(signature, message, publicKey, htfOpts) {
const P = normP1(publicKey);
const Hm = normP2Hash(message, htfOpts);
const G = G1.ProjectivePoint.BASE;
const S = normP2(signature);
const exp = pairingBatch([
{ g1: P.negate(), g2: Hm },
// ePHM = pairing(P.negate(), Hm, false);
{ g1: G, g2: S }
// eGS = pairing(G, S, false);
]);
return Fp12.eql(exp, Fp12.ONE);
}
function verifyShortSignature(signature, message, publicKey, htfOpts) {
const P = normP2(publicKey);
const Hm = normP1Hash(message, htfOpts);
const G = G22.ProjectivePoint.BASE;
const S = normP1(signature);
const exp = pairingBatch([
{ g1: Hm, g2: P },
// eHmP = pairing(Hm, P, false);
{ g1: S, g2: G.negate() }
// eSG = pairing(S, G.negate(), false);
]);
return Fp12.eql(exp, Fp12.ONE);
}
function aggregatePublicKeys(publicKeys) {
if (!publicKeys.length)
throw new Error("Expected non-empty array");
const agg = publicKeys.map(normP1).reduce((sum, p) => sum.add(p), G1.ProjectivePoint.ZERO);
const aggAffine = agg;
if (publicKeys[0] instanceof G1.ProjectivePoint) {
aggAffine.assertValidity();
return aggAffine;
}
return aggAffine.toRawBytes(true);
}
function aggregateSignatures(signatures) {
if (!signatures.length)
throw new Error("Expected non-empty array");
const agg = signatures.map(normP2).reduce((sum, s) => sum.add(s), G22.ProjectivePoint.ZERO);
const aggAffine = agg;
if (signatures[0] instanceof G22.ProjectivePoint) {
aggAffine.assertValidity();
return aggAffine;
}
return Signature.toRawBytes(aggAffine);
}
function aggregateShortSignatures(signatures) {
if (!signatures.length)
throw new Error("Expected non-empty array");
const agg = signatures.map(normP1).reduce((sum, s) => sum.add(s), G1.ProjectivePoint.ZERO);
const aggAffine = agg;
if (signatures[0] instanceof G1.ProjectivePoint) {
aggAffine.assertValidity();
return aggAffine;
}
return ShortSignature.toRawBytes(aggAffine);
}
function verifyBatch(signature, messages, publicKeys, htfOpts) {
if (!messages.length)
throw new Error("Expected non-empty messages array");
if (publicKeys.length !== messages.length)
throw new Error("Pubkey count should equal msg count");
const sig = normP2(signature);
const nMessages = messages.map((i) => normP2Hash(i, htfOpts));
const nPublicKeys = publicKeys.map(normP1);
const messagePubKeyMap = /* @__PURE__ */ new Map();
for (let i = 0; i < nPublicKeys.length; i++) {
const pub = nPublicKeys[i];
const msg = nMessages[i];
let keys = messagePubKeyMap.get(msg);
if (keys === void 0) {
keys = [];
messagePubKeyMap.set(msg, keys);
}
keys.push(pub);
}
const paired = [];
try {
for (const [msg, keys] of messagePubKeyMap) {
const groupPublicKey = keys.reduce((acc, msg2) => acc.add(msg2));
paired.push({ g1: groupPublicKey, g2: msg });
}
paired.push({ g1: G1.ProjectivePoint.BASE.negate(), g2: sig });
return Fp12.eql(pairingBatch(paired), Fp12.ONE);
} catch {
return false;
}
}
G1.ProjectivePoint.BASE._setWindowSize(4);
return {
getPublicKey,
getPublicKeyForShortSignatures,
sign,
signShortSignature,
verify,
verifyBatch,
verifyShortSignature,
aggregatePublicKeys,
aggregateSignatures,
aggregateShortSignatures,
millerLoopBatch,
pairing,
pairingBatch,
G1,
G2: G22,
Signature,
ShortSignature,
fields: {
Fr,
Fp,
Fp2,
Fp6,
Fp12
},
params: {
ateLoopSize: CURVE.params.ateLoopSize,
r: CURVE.params.r,
G1b: CURVE.G1.b,
G2b: CURVE.G2.b
},
utils
};
}
}
});
// node_modules/@noble/curves/abstract/tower.js
var require_tower = __commonJS({
"node_modules/@noble/curves/abstract/tower.js"(exports2) {
"use strict";
Object.defineProperty(exports2, "__esModule", { value: true });
exports2.psiFrobenius = psiFrobenius2;
exports2.tower12 = tower12;
var mod2 = require_modular();
var utils_js_1 = require_utils2();
var _0n8 = BigInt(0);
var _1n8 = BigInt(1);
var _2n7 = BigInt(2);
var _3n5 = BigInt(3);
function calcFrobeniusCoefficients(Fp, nonResidue, modulus, degree, num = 1, divisor) {
const _divisor = BigInt(divisor === void 0 ? degree : divisor);
const towerModulus = modulus ** BigInt(degree);
const res = [];
for (let i = 0; i < num; i++) {
const a = BigInt(i + 1);
const powers = [];
for (let j = 0, qPower = _1n8; j < degree; j++) {
const power = (a * qPower - a) / _divisor % towerModulus;
powers.push(Fp.pow(nonResidue, power));
qPower *= modulus;
}
res.push(powers);
}
return res;
}
function psiFrobenius2(Fp, Fp2, base) {
const PSI_X = Fp2.pow(base, (Fp.ORDER - _1n8) / _3n5);
const PSI_Y = Fp2.pow(base, (Fp.ORDER - _1n8) / _2n7);
function psi2(x, y) {
const x2 = Fp2.mul(Fp2.frobeniusMap(x, 1), PSI_X);
const y2 = Fp2.mul(Fp2.frobeniusMap(y, 1), PSI_Y);
return [x2, y2];
}
const PSI2_X = Fp2.pow(base, (Fp.ORDER ** _2n7 - _1n8) / _3n5);
const PSI2_Y = Fp2.pow(base, (Fp.ORDER ** _2n7 - _1n8) / _2n7);
if (!Fp2.eql(PSI2_Y, Fp2.neg(Fp2.ONE)))
throw new Error("psiFrobenius: PSI2_Y!==-1");
function psi22(x, y) {
return [Fp2.mul(x, PSI2_X), Fp2.neg(y)];
}
const mapAffine = (fn) => (c, P) => {
const affine = P.toAffine();
const p = fn(affine.x, affine.y);
return c.fromAffine({ x: p[0], y: p[1] });
};
const G2psi3 = mapAffine(psi2);
const G2psi22 = mapAffine(psi22);
return { psi: psi2, psi2: psi22, G2psi: G2psi3, G2psi2: G2psi22, PSI_X, PSI_Y, PSI2_X, PSI2_Y };
}
function tower12(opts) {
const { ORDER } = opts;
const Fp = mod2.Field(ORDER);
const FpNONRESIDUE = Fp.create(opts.NONRESIDUE || BigInt(-1));
const FpLegendre2 = mod2.FpLegendre(ORDER);
const Fpdiv2 = Fp.div(Fp.ONE, _2n7);
const FP2_FROBENIUS_COEFFICIENTS = calcFrobeniusCoefficients(Fp, FpNONRESIDUE, Fp.ORDER, 2)[0];
const Fp2Add = ({ c0, c1 }, { c0: r0, c1: r1 }) => ({
c0: Fp.add(c0, r0),
c1: Fp.add(c1, r1)
});
const Fp2Subtract = ({ c0, c1 }, { c0: r0, c1: r1 }) => ({
c0: Fp.sub(c0, r0),
c1: Fp.sub(c1, r1)
});
const Fp2Multiply = ({ c0, c1 }, rhs) => {
if (typeof rhs === "bigint")
return { c0: Fp.mul(c0, rhs), c1: Fp.mul(c1, rhs) };
const { c0: r0, c1: r1 } = rhs;
let t1 = Fp.mul(c0, r0);
let t2 = Fp.mul(c1, r1);
const o0 = Fp.sub(t1, t2);
const o1 = Fp.sub(Fp.mul(Fp.add(c0, c1), Fp.add(r0, r1)), Fp.add(t1, t2));
return { c0: o0, c1: o1 };
};
const Fp2Square = ({ c0, c1 }) => {
const a = Fp.add(c0, c1);
const b = Fp.sub(c0, c1);
const c = Fp.add(c0, c0);
return { c0: Fp.mul(a, b), c1: Fp.mul(c, c1) };
};
const Fp2fromBigTuple = (tuple) => {
if (tuple.length !== 2)
throw new Error("Invalid tuple");
const fps = tuple.map((n) => Fp.create(n));
return { c0: fps[0], c1: fps[1] };
};
const FP2_ORDER = ORDER * ORDER;
const Fp2Nonresidue = Fp2fromBigTuple(opts.FP2_NONRESIDUE);
const Fp2 = {
ORDER: FP2_ORDER,
NONRESIDUE: Fp2Nonresidue,
BITS: (0, utils_js_1.bitLen)(FP2_ORDER),
BYTES: Math.ceil((0, utils_js_1.bitLen)(FP2_ORDER) / 8),
MASK: (0, utils_js_1.bitMask)((0, utils_js_1.bitLen)(FP2_ORDER)),
ZERO: { c0: Fp.ZERO, c1: Fp.ZERO },
ONE: { c0: Fp.ONE, c1: Fp.ZERO },
create: (num) => num,
isValid: ({ c0, c1 }) => typeof c0 === "bigint" && typeof c1 === "bigint",
is0: ({ c0, c1 }) => Fp.is0(c0) && Fp.is0(c1),
eql: ({ c0, c1 }, { c0: r0, c1: r1 }) => Fp.eql(c0, r0) && Fp.eql(c1, r1),
neg: ({ c0, c1 }) => ({ c0: Fp.neg(c0), c1: Fp.neg(c1) }),
pow: (num, power) => mod2.FpPow(Fp2, num, power),
invertBatch: (nums) => mod2.FpInvertBatch(Fp2, nums),
// Normalized
add: Fp2Add,
sub: Fp2Subtract,
mul: Fp2Multiply,
sqr: Fp2Square,
// NonNormalized stuff
addN: Fp2Add,
subN: Fp2Subtract,
mulN: Fp2Multiply,
sqrN: Fp2Square,
// Why inversion for bigint inside Fp instead of Fp2? it is even used in that context?
div: (lhs, rhs) => Fp2.mul(lhs, typeof rhs === "bigint" ? Fp.inv(Fp.create(rhs)) : Fp2.inv(rhs)),
inv: ({ c0: a, c1: b }) => {
const factor = Fp.inv(Fp.create(a * a + b * b));
return { c0: Fp.mul(factor, Fp.create(a)), c1: Fp.mul(factor, Fp.create(-b)) };
},
sqrt: (num) => {
if (opts.Fp2sqrt)
return opts.Fp2sqrt(num);
const { c0, c1 } = num;
if (Fp.is0(c1)) {
if (Fp.eql(FpLegendre2(Fp, c0), Fp.ONE))
return Fp2.create({ c0: Fp.sqrt(c0), c1: Fp.ZERO });
else
return Fp2.create({ c0: Fp.ZERO, c1: Fp.sqrt(Fp.div(c0, FpNONRESIDUE)) });
}
const a = Fp.sqrt(Fp.sub(Fp.sqr(c0), Fp.mul(Fp.sqr(c1), FpNONRESIDUE)));
let d = Fp.mul(Fp.add(a, c0), Fpdiv2);
const legendre = FpLegendre2(Fp, d);
if (!Fp.is0(legendre) && !Fp.eql(legendre, Fp.ONE))
d = Fp.sub(d, a);
const a0 = Fp.sqrt(d);
const candidateSqrt = Fp2.create({ c0: a0, c1: Fp.div(Fp.mul(c1, Fpdiv2), a0) });
if (!Fp2.eql(Fp2.sqr(candidateSqrt), num))
throw new Error("Cannot find square root");
const x1 = candidateSqrt;
const x2 = Fp2.neg(x1);
const { re: re1, im: im1 } = Fp2.reim(x1);
const { re: re2, im: im2 } = Fp2.reim(x2);
if (im1 > im2 || im1 === im2 && re1 > re2)
return x1;
return x2;
},
// Same as sgn0_m_eq_2 in RFC 9380
isOdd: (x) => {
const { re: x0, im: x1 } = Fp2.reim(x);
const sign_0 = x0 % _2n7;
const zero_0 = x0 === _0n8;
const sign_1 = x1 % _2n7;
return BigInt(sign_0 || zero_0 && sign_1) == _1n8;
},
// Bytes util
fromBytes(b) {
if (b.length !== Fp2.BYTES)
throw new Error(`fromBytes wrong length=${b.length}`);
return { c0: Fp.fromBytes(b.subarray(0, Fp.BYTES)), c1: Fp.fromBytes(b.subarray(Fp.BYTES)) };
},
toBytes: ({ c0, c1 }) => (0, utils_js_1.concatBytes)(Fp.toBytes(c0), Fp.toBytes(c1)),
cmov: ({ c0, c1 }, { c0: r0, c1: r1 }, c) => ({
c0: Fp.cmov(c0, r0, c),
c1: Fp.cmov(c1, r1, c)
}),
reim: ({ c0, c1 }) => ({ re: c0, im: c1 }),
// multiply by u + 1
mulByNonresidue: ({ c0, c1 }) => Fp2.mul({ c0, c1 }, Fp2Nonresidue),
mulByB: opts.Fp2mulByB,
fromBigTuple: Fp2fromBigTuple,
frobeniusMap: ({ c0, c1 }, power) => ({
c0,
c1: Fp.mul(c1, FP2_FROBENIUS_COEFFICIENTS[power % 2])
})
};
const Fp6Add = ({ c0, c1, c2 }, { c0: r0, c1: r1, c2: r2 }) => ({
c0: Fp2.add(c0, r0),
c1: Fp2.add(c1, r1),
c2: Fp2.add(c2, r2)
});
const Fp6Subtract = ({ c0, c1, c2 }, { c0: r0, c1: r1, c2: r2 }) => ({
c0: Fp2.sub(c0, r0),
c1: Fp2.sub(c1, r1),
c2: Fp2.sub(c2, r2)
});
const Fp6Multiply = ({ c0, c1, c2 }, rhs) => {
if (typeof rhs === "bigint") {
return {
c0: Fp2.mul(c0, rhs),
c1: Fp2.mul(c1, rhs),
c2: Fp2.mul(c2, rhs)
};
}
const { c0: r0, c1: r1, c2: r2 } = rhs;
const t0 = Fp2.mul(c0, r0);
const t1 = Fp2.mul(c1, r1);
const t2 = Fp2.mul(c2, r2);
return {
// t0 + (c1 + c2) * (r1 * r2) - (T1 + T2) * (u + 1)
c0: Fp2.add(t0, Fp2.mulByNonresidue(Fp2.sub(Fp2.mul(Fp2.add(c1, c2), Fp2.add(r1, r2)), Fp2.add(t1, t2)))),
// (c0 + c1) * (r0 + r1) - (T0 + T1) + T2 * (u + 1)
c1: Fp2.add(Fp2.sub(Fp2.mul(Fp2.add(c0, c1), Fp2.add(r0, r1)), Fp2.add(t0, t1)), Fp2.mulByNonresidue(t2)),
// T1 + (c0 + c2) * (r0 + r2) - T0 + T2
c2: Fp2.sub(Fp2.add(t1, Fp2.mul(Fp2.add(c0, c2), Fp2.add(r0, r2))), Fp2.add(t0, t2))
};
};
const Fp6Square = ({ c0, c1, c2 }) => {
let t0 = Fp2.sqr(c0);
let t1 = Fp2.mul(Fp2.mul(c0, c1), _2n7);
let t3 = Fp2.mul(Fp2.mul(c1, c2), _2n7);
let t4 = Fp2.sqr(c2);
return {
c0: Fp2.add(Fp2.mulByNonresidue(t3), t0),
// T3 * (u + 1) + T0
c1: Fp2.add(Fp2.mulByNonresidue(t4), t1),
// T4 * (u + 1) + T1
// T1 + (c0 - c1 + c2)² + T3 - T0 - T4
c2: Fp2.sub(Fp2.sub(Fp2.add(Fp2.add(t1, Fp2.sqr(Fp2.add(Fp2.sub(c0, c1), c2))), t3), t0), t4)
};
};
const [FP6_FROBENIUS_COEFFICIENTS_1, FP6_FROBENIUS_COEFFICIENTS_2] = calcFrobeniusCoefficients(Fp2, Fp2Nonresidue, Fp.ORDER, 6, 2, 3);
const Fp6 = {
ORDER: Fp2.ORDER,
// TODO: unused, but need to verify
BITS: 3 * Fp2.BITS,
BYTES: 3 * Fp2.BYTES,
MASK: (0, utils_js_1.bitMask)(3 * Fp2.BITS),
ZERO: { c0: Fp2.ZERO, c1: Fp2.ZERO, c2: Fp2.ZERO },
ONE: { c0: Fp2.ONE, c1: Fp2.ZERO, c2: Fp2.ZERO },
create: (num) => num,
isValid: ({ c0, c1, c2 }) => Fp2.isValid(c0) && Fp2.isValid(c1) && Fp2.isValid(c2),
is0: ({ c0, c1, c2 }) => Fp2.is0(c0) && Fp2.is0(c1) && Fp2.is0(c2),
neg: ({ c0, c1, c2 }) => ({ c0: Fp2.neg(c0), c1: Fp2.neg(c1), c2: Fp2.neg(c2) }),
eql: ({ c0, c1, c2 }, { c0: r0, c1: r1, c2: r2 }) => Fp2.eql(c0, r0) && Fp2.eql(c1, r1) && Fp2.eql(c2, r2),
sqrt: utils_js_1.notImplemented,
// Do we need division by bigint at all? Should be done via order:
div: (lhs, rhs) => Fp6.mul(lhs, typeof rhs === "bigint" ? Fp.inv(Fp.create(rhs)) : Fp6.inv(rhs)),
pow: (num, power) => mod2.FpPow(Fp6, num, power),
invertBatch: (nums) => mod2.FpInvertBatch(Fp6, nums),
// Normalized
add: Fp6Add,
sub: Fp6Subtract,
mul: Fp6Multiply,
sqr: Fp6Square,
// NonNormalized stuff
addN: Fp6Add,
subN: Fp6Subtract,
mulN: Fp6Multiply,
sqrN: Fp6Square,
inv: ({ c0, c1, c2 }) => {
let t0 = Fp2.sub(Fp2.sqr(c0), Fp2.mulByNonresidue(Fp2.mul(c2, c1)));
let t1 = Fp2.sub(Fp2.mulByNonresidue(Fp2.sqr(c2)), Fp2.mul(c0, c1));
let t2 = Fp2.sub(Fp2.sqr(c1), Fp2.mul(c0, c2));
let t4 = Fp2.inv(Fp2.add(Fp2.mulByNonresidue(Fp2.add(Fp2.mul(c2, t1), Fp2.mul(c1, t2))), Fp2.mul(c0, t0)));
return { c0: Fp2.mul(t4, t0), c1: Fp2.mul(t4, t1), c2: Fp2.mul(t4, t2) };
},
// Bytes utils
fromBytes: (b) => {
if (b.length !== Fp6.BYTES)
throw new Error(`fromBytes wrong length=${b.length}`);
return {
c0: Fp2.fromBytes(b.subarray(0, Fp2.BYTES)),
c1: Fp2.fromBytes(b.subarray(Fp2.BYTES, 2 * Fp2.BYTES)),
c2: Fp2.fromBytes(b.subarray(2 * Fp2.BYTES))
};
},
toBytes: ({ c0, c1, c2 }) => (0, utils_js_1.concatBytes)(Fp2.toBytes(c0), Fp2.toBytes(c1), Fp2.toBytes(c2)),
cmov: ({ c0, c1, c2 }, { c0: r0, c1: r1, c2: r2 }, c) => ({
c0: Fp2.cmov(c0, r0, c),
c1: Fp2.cmov(c1, r1, c),
c2: Fp2.cmov(c2, r2, c)
}),
fromBigSix: (t) => {
if (!Array.isArray(t) || t.length !== 6)
throw new Error("Invalid Fp6 usage");
return {
c0: Fp2.fromBigTuple(t.slice(0, 2)),
c1: Fp2.fromBigTuple(t.slice(2, 4)),
c2: Fp2.fromBigTuple(t.slice(4, 6))
};
},
frobeniusMap: ({ c0, c1, c2 }, power) => ({
c0: Fp2.frobeniusMap(c0, power),
c1: Fp2.mul(Fp2.frobeniusMap(c1, power), FP6_FROBENIUS_COEFFICIENTS_1[power % 6]),
c2: Fp2.mul(Fp2.frobeniusMap(c2, power), FP6_FROBENIUS_COEFFICIENTS_2[power % 6])
}),
mulByFp2: ({ c0, c1, c2 }, rhs) => ({
c0: Fp2.mul(c0, rhs),
c1: Fp2.mul(c1, rhs),
c2: Fp2.mul(c2, rhs)
}),
mulByNonresidue: ({ c0, c1, c2 }) => ({ c0: Fp2.mulByNonresidue(c2), c1: c0, c2: c1 }),
// Sparse multiplication
mul1: ({ c0, c1, c2 }, b1) => ({
c0: Fp2.mulByNonresidue(Fp2.mul(c2, b1)),
c1: Fp2.mul(c0, b1),
c2: Fp2.mul(c1, b1)
}),
// Sparse multiplication
mul01({ c0, c1, c2 }, b0, b1) {
let t0 = Fp2.mul(c0, b0);
let t1 = Fp2.mul(c1, b1);
return {
// ((c1 + c2) * b1 - T1) * (u + 1) + T0
c0: Fp2.add(Fp2.mulByNonresidue(Fp2.sub(Fp2.mul(Fp2.add(c1, c2), b1), t1)), t0),
// (b0 + b1) * (c0 + c1) - T0 - T1
c1: Fp2.sub(Fp2.sub(Fp2.mul(Fp2.add(b0, b1), Fp2.add(c0, c1)), t0), t1),
// (c0 + c2) * b0 - T0 + T1
c2: Fp2.add(Fp2.sub(Fp2.mul(Fp2.add(c0, c2), b0), t0), t1)
};
}
};
const FP12_FROBENIUS_COEFFICIENTS = calcFrobeniusCoefficients(Fp2, Fp2Nonresidue, Fp.ORDER, 12, 1, 6)[0];
const Fp12Add = ({ c0, c1 }, { c0: r0, c1: r1 }) => ({
c0: Fp6.add(c0, r0),
c1: Fp6.add(c1, r1)
});
const Fp12Subtract = ({ c0, c1 }, { c0: r0, c1: r1 }) => ({
c0: Fp6.sub(c0, r0),
c1: Fp6.sub(c1, r1)
});
const Fp12Multiply = ({ c0, c1 }, rhs) => {
if (typeof rhs === "bigint")
return { c0: Fp6.mul(c0, rhs), c1: Fp6.mul(c1, rhs) };
let { c0: r0, c1: r1 } = rhs;
let t1 = Fp6.mul(c0, r0);
let t2 = Fp6.mul(c1, r1);
return {
c0: Fp6.add(t1, Fp6.mulByNonresidue(t2)),
// T1 + T2 * v
// (c0 + c1) * (r0 + r1) - (T1 + T2)
c1: Fp6.sub(Fp6.mul(Fp6.add(c0, c1), Fp6.add(r0, r1)), Fp6.add(t1, t2))
};
};
const Fp12Square = ({ c0, c1 }) => {
let ab = Fp6.mul(c0, c1);
return {
// (c1 * v + c0) * (c0 + c1) - AB - AB * v
c0: Fp6.sub(Fp6.sub(Fp6.mul(Fp6.add(Fp6.mulByNonresidue(c1), c0), Fp6.add(c0, c1)), ab), Fp6.mulByNonresidue(ab)),
c1: Fp6.add(ab, ab)
};
};
function Fp4Square(a, b) {
const a2 = Fp2.sqr(a);
const b2 = Fp2.sqr(b);
return {
first: Fp2.add(Fp2.mulByNonresidue(b2), a2),
// b² * Nonresidue + a²
second: Fp2.sub(Fp2.sub(Fp2.sqr(Fp2.add(a, b)), a2), b2)
// (a + b)² - a² - b²
};
}
const Fp12 = {
ORDER: Fp2.ORDER,
// TODO: unused, but need to verify
BITS: 2 * Fp2.BITS,
BYTES: 2 * Fp2.BYTES,
MASK: (0, utils_js_1.bitMask)(2 * Fp2.BITS),
ZERO: { c0: Fp6.ZERO, c1: Fp6.ZERO },
ONE: { c0: Fp6.ONE, c1: Fp6.ZERO },
create: (num) => num,
isValid: ({ c0, c1 }) => Fp6.isValid(c0) && Fp6.isValid(c1),
is0: ({ c0, c1 }) => Fp6.is0(c0) && Fp6.is0(c1),
neg: ({ c0, c1 }) => ({ c0: Fp6.neg(c0), c1: Fp6.neg(c1) }),
eql: ({ c0, c1 }, { c0: r0, c1: r1 }) => Fp6.eql(c0, r0) && Fp6.eql(c1, r1),
sqrt: utils_js_1.notImplemented,
inv: ({ c0, c1 }) => {
let t = Fp6.inv(Fp6.sub(Fp6.sqr(c0), Fp6.mulByNonresidue(Fp6.sqr(c1))));
return { c0: Fp6.mul(c0, t), c1: Fp6.neg(Fp6.mul(c1, t)) };
},
div: (lhs, rhs) => Fp12.mul(lhs, typeof rhs === "bigint" ? Fp.inv(Fp.create(rhs)) : Fp12.inv(rhs)),
pow: (num, power) => mod2.FpPow(Fp12, num, power),
invertBatch: (nums) => mod2.FpInvertBatch(Fp12, nums),
// Normalized
add: Fp12Add,
sub: Fp12Subtract,
mul: Fp12Multiply,
sqr: Fp12Square,
// NonNormalized stuff
addN: Fp12Add,
subN: Fp12Subtract,
mulN: Fp12Multiply,
sqrN: Fp12Square,
// Bytes utils
fromBytes: (b) => {
if (b.length !== Fp12.BYTES)
throw new Error(`fromBytes wrong length=${b.length}`);
return {
c0: Fp6.fromBytes(b.subarray(0, Fp6.BYTES)),
c1: Fp6.fromBytes(b.subarray(Fp6.BYTES))
};
},
toBytes: ({ c0, c1 }) => (0, utils_js_1.concatBytes)(Fp6.toBytes(c0), Fp6.toBytes(c1)),
cmov: ({ c0, c1 }, { c0: r0, c1: r1 }, c) => ({
c0: Fp6.cmov(c0, r0, c),
c1: Fp6.cmov(c1, r1, c)
}),
// Utils
// toString() {
// return `Fp12(${this.c0} + ${this.c1} * w)`;
// },
// fromTuple(c: [Fp6, Fp6]) {
// return new Fp12(...c);
// }
fromBigTwelve: (t) => ({
c0: Fp6.fromBigSix(t.slice(0, 6)),
c1: Fp6.fromBigSix(t.slice(6, 12))
}),
// Raises to q**i -th power
frobeniusMap(lhs, power) {
const { c0, c1, c2 } = Fp6.frobeniusMap(lhs.c1, power);
const coeff = FP12_FROBENIUS_COEFFICIENTS[power % 12];
return {
c0: Fp6.frobeniusMap(lhs.c0, power),
c1: Fp6.create({
c0: Fp2.mul(c0, coeff),
c1: Fp2.mul(c1, coeff),
c2: Fp2.mul(c2, coeff)
})
};
},
mulByFp2: ({ c0, c1 }, rhs) => ({
c0: Fp6.mulByFp2(c0, rhs),
c1: Fp6.mulByFp2(c1, rhs)
}),
conjugate: ({ c0, c1 }) => ({ c0, c1: Fp6.neg(c1) }),
// Sparse multiplication
mul014: ({ c0, c1 }, o0, o1, o4) => {
let t0 = Fp6.mul01(c0, o0, o1);
let t1 = Fp6.mul1(c1, o4);
return {
c0: Fp6.add(Fp6.mulByNonresidue(t1), t0),
// T1 * v + T0
// (c1 + c0) * [o0, o1+o4] - T0 - T1
c1: Fp6.sub(Fp6.sub(Fp6.mul01(Fp6.add(c1, c0), o0, Fp2.add(o1, o4)), t0), t1)
};
},
mul034: ({ c0, c1 }, o0, o3, o4) => {
const a = Fp6.create({
c0: Fp2.mul(c0.c0, o0),
c1: Fp2.mul(c0.c1, o0),
c2: Fp2.mul(c0.c2, o0)
});
const b = Fp6.mul01(c1, o3, o4);
const e = Fp6.mul01(Fp6.add(c0, c1), Fp2.add(o0, o3), o4);
return {
c0: Fp6.add(Fp6.mulByNonresidue(b), a),
c1: Fp6.sub(e, Fp6.add(a, b))
};
},
// A cyclotomic group is a subgroup of Fp^n defined by
// GΦₙ(p) = {α ∈ Fpⁿ : α^Φₙ(p) = 1}
// The result of any pairing is in a cyclotomic subgroup
// https://eprint.iacr.org/2009/565.pdf
_cyclotomicSquare: opts.Fp12cyclotomicSquare,
_cyclotomicExp: opts.Fp12cyclotomicExp,
// https://eprint.iacr.org/2010/354.pdf
// https://eprint.iacr.org/2009/565.pdf
finalExponentiate: opts.Fp12finalExponentiate
};
return { Fp, Fp2, Fp6, Fp4Square, Fp12 };
}
}
});
// node_modules/@noble/hashes/_u64.js
var require_u64 = __commonJS({
"node_modules/@noble/hashes/_u64.js"(exports2) {
"use strict";
Object.defineProperty(exports2, "__esModule", { value: true });
exports2.toBig = exports2.shrSL = exports2.shrSH = exports2.rotrSL = exports2.rotrSH = exports2.rotrBL = exports2.rotrBH = exports2.rotr32L = exports2.rotr32H = exports2.rotlSL = exports2.rotlSH = exports2.rotlBL = exports2.rotlBH = exports2.add5L = exports2.add5H = exports2.add4L = exports2.add4H = exports2.add3L = exports2.add3H = void 0;
exports2.add = add;
exports2.fromBig = fromBig2;
exports2.split = split2;
var U32_MASK642 = /* @__PURE__ */ BigInt(2 ** 32 - 1);
var _32n2 = /* @__PURE__ */ BigInt(32);
function fromBig2(n, le = false) {
if (le)
return { h: Number(n & U32_MASK642), l: Number(n >> _32n2 & U32_MASK642) };
return { h: Number(n >> _32n2 & U32_MASK642) | 0, l: Number(n & U32_MASK642) | 0 };
}
function split2(lst, le = false) {
const len = lst.length;
let Ah = new Uint32Array(len);
let Al = new Uint32Array(len);
for (let i = 0; i < len; i++) {
const { h, l } = fromBig2(lst[i], le);
[Ah[i], Al[i]] = [h, l];
}
return [Ah, Al];
}
var toBig = (h, l) => BigInt(h >>> 0) << _32n2 | BigInt(l >>> 0);
exports2.toBig = toBig;
var shrSH = (h, _l, s) => h >>> s;
exports2.shrSH = shrSH;
var shrSL = (h, l, s) => h << 32 - s | l >>> s;
exports2.shrSL = shrSL;
var rotrSH = (h, l, s) => h >>> s | l << 32 - s;
exports2.rotrSH = rotrSH;
var rotrSL = (h, l, s) => h << 32 - s | l >>> s;
exports2.rotrSL = rotrSL;
var rotrBH = (h, l, s) => h << 64 - s | l >>> s - 32;
exports2.rotrBH = rotrBH;
var rotrBL = (h, l, s) => h >>> s - 32 | l << 64 - s;
exports2.rotrBL = rotrBL;
var rotr32H = (_h, l) => l;
exports2.rotr32H = rotr32H;
var rotr32L = (h, _l) => h;
exports2.rotr32L = rotr32L;
var rotlSH2 = (h, l, s) => h << s | l >>> 32 - s;
exports2.rotlSH = rotlSH2;
var rotlSL2 = (h, l, s) => l << s | h >>> 32 - s;
exports2.rotlSL = rotlSL2;
var rotlBH2 = (h, l, s) => l << s - 32 | h >>> 64 - s;
exports2.rotlBH = rotlBH2;
var rotlBL2 = (h, l, s) => h << s - 32 | l >>> 64 - s;
exports2.rotlBL = rotlBL2;
function add(Ah, Al, Bh, Bl) {
const l = (Al >>> 0) + (Bl >>> 0);
return { h: Ah + Bh + (l / 2 ** 32 | 0) | 0, l: l | 0 };
}
var add3L = (Al, Bl, Cl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0);
exports2.add3L = add3L;
var add3H = (low, Ah, Bh, Ch) => Ah + Bh + Ch + (low / 2 ** 32 | 0) | 0;
exports2.add3H = add3H;
var add4L = (Al, Bl, Cl, Dl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0);
exports2.add4L = add4L;
var add4H = (low, Ah, Bh, Ch, Dh) => Ah + Bh + Ch + Dh + (low / 2 ** 32 | 0) | 0;
exports2.add4H = add4H;
var add5L = (Al, Bl, Cl, Dl, El) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0) + (El >>> 0);
exports2.add5L = add5L;
var add5H = (low, Ah, Bh, Ch, Dh, Eh) => Ah + Bh + Ch + Dh + Eh + (low / 2 ** 32 | 0) | 0;
exports2.add5H = add5H;
var u64 = {
fromBig: fromBig2,
split: split2,
toBig,
shrSH,
shrSL,
rotrSH,
rotrSL,
rotrBH,
rotrBL,
rotr32H,
rotr32L,
rotlSH: rotlSH2,
rotlSL: rotlSL2,
rotlBH: rotlBH2,
rotlBL: rotlBL2,
add,
add3L,
add3H,
add4L,
add4H,
add5H,
add5L
};
exports2.default = u64;
}
});
// node_modules/@noble/hashes/sha3.js
var require_sha3 = __commonJS({
"node_modules/@noble/hashes/sha3.js"(exports2) {
"use strict";
Object.defineProperty(exports2, "__esModule", { value: true });
exports2.shake256 = exports2.shake128 = exports2.keccak_512 = exports2.keccak_384 = exports2.keccak_256 = exports2.keccak_224 = exports2.sha3_512 = exports2.sha3_384 = exports2.sha3_256 = exports2.sha3_224 = exports2.Keccak = void 0;
exports2.keccakP = keccakP2;
var _u64_ts_1 = require_u64();
var utils_ts_1 = require_utils();
var _0n8 = BigInt(0);
var _1n8 = BigInt(1);
var _2n7 = BigInt(2);
var _7n2 = BigInt(7);
var _256n2 = BigInt(256);
var _0x71n2 = BigInt(113);
var SHA3_PI2 = [];
var SHA3_ROTL2 = [];
var _SHA3_IOTA2 = [];
for (let round = 0, R = _1n8, x = 1, y = 0; round < 24; round++) {
[x, y] = [y, (2 * x + 3 * y) % 5];
SHA3_PI2.push(2 * (5 * y + x));
SHA3_ROTL2.push((round + 1) * (round + 2) / 2 % 64);
let t = _0n8;
for (let j = 0; j < 7; j++) {
R = (R << _1n8 ^ (R >> _7n2) * _0x71n2) % _256n2;
if (R & _2n7)
t ^= _1n8 << (_1n8 << /* @__PURE__ */ BigInt(j)) - _1n8;
}
_SHA3_IOTA2.push(t);
}
var IOTAS2 = (0, _u64_ts_1.split)(_SHA3_IOTA2, true);
var SHA3_IOTA_H2 = IOTAS2[0];
var SHA3_IOTA_L2 = IOTAS2[1];
var rotlH2 = (h, l, s) => s > 32 ? (0, _u64_ts_1.rotlBH)(h, l, s) : (0, _u64_ts_1.rotlSH)(h, l, s);
var rotlL2 = (h, l, s) => s > 32 ? (0, _u64_ts_1.rotlBL)(h, l, s) : (0, _u64_ts_1.rotlSL)(h, l, s);
function keccakP2(s, rounds = 24) {
const B = new Uint32Array(5 * 2);
for (let round = 24 - rounds; round < 24; round++) {
for (let x = 0; x < 10; x++)
B[x] = s[x] ^ s[x + 10] ^ s[x + 20] ^ s[x + 30] ^ s[x + 40];
for (let x = 0; x < 10; x += 2) {
const idx1 = (x + 8) % 10;
const idx0 = (x + 2) % 10;
const B0 = B[idx0];
const B1 = B[idx0 + 1];
const Th = rotlH2(B0, B1, 1) ^ B[idx1];
const Tl = rotlL2(B0, B1, 1) ^ B[idx1 + 1];
for (let y = 0; y < 50; y += 10) {
s[x + y] ^= Th;
s[x + y + 1] ^= Tl;
}
}
let curH = s[2];
let curL = s[3];
for (let t = 0; t < 24; t++) {
const shift = SHA3_ROTL2[t];
const Th = rotlH2(curH, curL, shift);
const Tl = rotlL2(curH, curL, shift);
const PI = SHA3_PI2[t];
curH = s[PI];
curL = s[PI + 1];
s[PI] = Th;
s[PI + 1] = Tl;
}
for (let y = 0; y < 50; y += 10) {
for (let x = 0; x < 10; x++)
B[x] = s[y + x];
for (let x = 0; x < 10; x++)
s[y + x] ^= ~B[(x + 2) % 10] & B[(x + 4) % 10];
}
s[0] ^= SHA3_IOTA_H2[round];
s[1] ^= SHA3_IOTA_L2[round];
}
(0, utils_ts_1.clean)(B);
}
var Keccak2 = class _Keccak extends utils_ts_1.Hash {
// NOTE: we accept arguments in bytes instead of bits here.
constructor(blockLen, suffix, outputLen, enableXOF = false, rounds = 24) {
super();
this.pos = 0;
this.posOut = 0;
this.finished = false;
this.destroyed = false;
this.enableXOF = false;
this.blockLen = blockLen;
this.suffix = suffix;
this.outputLen = outputLen;
this.enableXOF = enableXOF;
this.rounds = rounds;
(0, utils_ts_1.anumber)(outputLen);
if (!(0 < blockLen && blockLen < 200))
throw new Error("only keccak-f1600 function is supported");
this.state = new Uint8Array(200);
this.state32 = (0, utils_ts_1.u32)(this.state);
}
clone() {
return this._cloneInto();
}
keccak() {
(0, utils_ts_1.swap32IfBE)(this.state32);
keccakP2(this.state32, this.rounds);
(0, utils_ts_1.swap32IfBE)(this.state32);
this.posOut = 0;
this.pos = 0;
}
update(data) {
(0, utils_ts_1.aexists)(this);
data = (0, utils_ts_1.toBytes)(data);
(0, utils_ts_1.abytes)(data);
const { blockLen, state } = this;
const len = data.length;
for (let pos = 0; pos < len; ) {
const take = Math.min(blockLen - this.pos, len - pos);
for (let i = 0; i < take; i++)
state[this.pos++] ^= data[pos++];
if (this.pos === blockLen)
this.keccak();
}
return this;
}
finish() {
if (this.finished)
return;
this.finished = true;
const { state, suffix, pos, blockLen } = this;
state[pos] ^= suffix;
if ((suffix & 128) !== 0 && pos === blockLen - 1)
this.keccak();
state[blockLen - 1] ^= 128;
this.keccak();
}
writeInto(out) {
(0, utils_ts_1.aexists)(this, false);
(0, utils_ts_1.abytes)(out);
this.finish();
const bufferOut = this.state;
const { blockLen } = this;
for (let pos = 0, len = out.length; pos < len; ) {
if (this.posOut >= blockLen)
this.keccak();
const take = Math.min(blockLen - this.posOut, len - pos);
out.set(bufferOut.subarray(this.posOut, this.posOut + take), pos);
this.posOut += take;
pos += take;
}
return out;
}
xofInto(out) {
if (!this.enableXOF)
throw new Error("XOF is not possible for this instance");
return this.writeInto(out);
}
xof(bytes) {
(0, utils_ts_1.anumber)(bytes);
return this.xofInto(new Uint8Array(bytes));
}
digestInto(out) {
(0, utils_ts_1.aoutput)(out, this);
if (this.finished)
throw new Error("digest() was already called");
this.writeInto(out);
this.destroy();
return out;
}
digest() {
return this.digestInto(new Uint8Array(this.outputLen));
}
destroy() {
this.destroyed = true;
(0, utils_ts_1.clean)(this.state);
}
_cloneInto(to) {
const { blockLen, suffix, outputLen, rounds, enableXOF } = this;
to || (to = new _Keccak(blockLen, suffix, outputLen, enableXOF, rounds));
to.state32.set(this.state32);
to.pos = this.pos;
to.posOut = this.posOut;
to.finished = this.finished;
to.rounds = rounds;
to.suffix = suffix;
to.outputLen = outputLen;
to.enableXOF = enableXOF;
to.destroyed = this.destroyed;
return to;
}
};
exports2.Keccak = Keccak2;
var gen2 = (suffix, blockLen, outputLen) => (0, utils_ts_1.createHasher)(() => new Keccak2(blockLen, suffix, outputLen));
exports2.sha3_224 = (() => gen2(6, 144, 224 / 8))();
exports2.sha3_256 = (() => gen2(6, 136, 256 / 8))();
exports2.sha3_384 = (() => gen2(6, 104, 384 / 8))();
exports2.sha3_512 = (() => gen2(6, 72, 512 / 8))();
exports2.keccak_224 = (() => gen2(1, 144, 224 / 8))();
exports2.keccak_256 = (() => gen2(1, 136, 256 / 8))();
exports2.keccak_384 = (() => gen2(1, 104, 384 / 8))();
exports2.keccak_512 = (() => gen2(1, 72, 512 / 8))();
var genShake = (suffix, blockLen, outputLen) => (0, utils_ts_1.createXOFer)((opts = {}) => new Keccak2(blockLen, suffix, opts.dkLen === void 0 ? outputLen : opts.dkLen, true));
exports2.shake128 = (() => genShake(31, 168, 128 / 8))();
exports2.shake256 = (() => genShake(31, 136, 256 / 8))();
}
});
// node_modules/@kevincharm/noble-bn254-drand/dist/src/bn254.js
var require_bn254 = __commonJS({
"node_modules/@kevincharm/noble-bn254-drand/dist/src/bn254.js"(exports2) {
"use strict";
var __createBinding = exports2 && exports2.__createBinding || (Object.create ? function(o, m, k, k2) {
if (k2 === void 0) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() {
return m[k];
} };
}
Object.defineProperty(o, k2, desc);
} : function(o, m, k, k2) {
if (k2 === void 0) k2 = k;
o[k2] = m[k];
});
var __setModuleDefault = exports2 && exports2.__setModuleDefault || (Object.create ? function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
} : function(o, v) {
o["default"] = v;
});
var __importStar = exports2 && exports2.__importStar || function(mod3) {
if (mod3 && mod3.__esModule) return mod3;
var result = {};
if (mod3 != null) {
for (var k in mod3) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod3, k)) __createBinding(result, mod3, k);
}
__setModuleDefault(result, mod3);
return result;
};
Object.defineProperty(exports2, "__esModule", { value: true });
exports2.bn254 = void 0;
exports2.mapToCurveSVDW = mapToCurveSVDW2;
var utils_1 = require_utils();
var bls_1 = require_bls();
var modular_1 = require_modular();
var utils_2 = require_utils2();
var tower_1 = require_tower();
var mod2 = __importStar(require_modular());
var sha3_1 = require_sha3();
var utils_3 = require_utils2();
var _1n8 = BigInt(1);
var _2n7 = BigInt(2);
var _3n5 = BigInt(3);
var _6n = BigInt(6);
var BN_X = BigInt("4965661367192848881");
var BN_X_LEN = (0, utils_2.bitLen)(BN_X);
var SIX_X_SQUARED = _6n * BN_X ** _2n7;
var Fr = (0, modular_1.Field)(BigInt("21888242871839275222246405745257275088548364400416034343698204186575808495617"));
var Fp2B = {
c0: BigInt("19485874751759354771024239261021720505790618469301721065564631296452457478373"),
c1: BigInt("266929791119991161246907387137283842545076965332900288569378510910307636690")
};
var { Fp, Fp2, Fp6, Fp4Square, Fp12 } = (0, tower_1.tower12)({
ORDER: BigInt("21888242871839275222246405745257275088696311157297823662689037894645226208583"),
FP2_NONRESIDUE: [BigInt(9), _1n8],
Fp2mulByB: (num) => Fp2.mul(num, Fp2B),
// The result of any pairing is in a cyclotomic subgroup
// https://eprint.iacr.org/2009/565.pdf
Fp12cyclotomicSquare: ({ c0, c1 }) => {
const { c0: c0c0, c1: c0c1, c2: c0c2 } = c0;
const { c0: c1c0, c1: c1c1, c2: c1c2 } = c1;
const { first: t3, second: t4 } = Fp4Square(c0c0, c1c1);
const { first: t5, second: t6 } = Fp4Square(c1c0, c0c2);
const { first: t7, second: t8 } = Fp4Square(c0c1, c1c2);
let t9 = Fp2.mulByNonresidue(t8);
return {
c0: Fp6.create({
c0: Fp2.add(Fp2.mul(Fp2.sub(t3, c0c0), _2n7), t3),
// 2 * (T3 - c0c0) + T3
c1: Fp2.add(Fp2.mul(Fp2.sub(t5, c0c1), _2n7), t5),
// 2 * (T5 - c0c1) + T5
c2: Fp2.add(Fp2.mul(Fp2.sub(t7, c0c2), _2n7), t7)
}),
// 2 * (T7 - c0c2) + T7
c1: Fp6.create({
c0: Fp2.add(Fp2.mul(Fp2.add(t9, c1c0), _2n7), t9),
// 2 * (T9 + c1c0) + T9
c1: Fp2.add(Fp2.mul(Fp2.add(t4, c1c1), _2n7), t4),
// 2 * (T4 + c1c1) + T4
c2: Fp2.add(Fp2.mul(Fp2.add(t6, c1c2), _2n7), t6)
})
};
},
Fp12cyclotomicExp(num, n) {
let z = Fp12.ONE;
for (let i = BN_X_LEN - 1; i >= 0; i--) {
z = Fp12._cyclotomicSquare(z);
if ((0, utils_2.bitGet)(n, i))
z = Fp12.mul(z, num);
}
return z;
},
// https://eprint.iacr.org/2010/354.pdf
// https://eprint.iacr.org/2009/565.pdf
Fp12finalExponentiate: (num) => {
const powMinusX = (num2) => Fp12.conjugate(Fp12._cyclotomicExp(num2, BN_X));
const r0 = Fp12.mul(Fp12.conjugate(num), Fp12.inv(num));
const r = Fp12.mul(Fp12.frobeniusMap(r0, 2), r0);
const y1 = Fp12._cyclotomicSquare(powMinusX(r));
const y2 = Fp12.mul(Fp12._cyclotomicSquare(y1), y1);
const y4 = powMinusX(y2);
const y6 = powMinusX(Fp12._cyclotomicSquare(y4));
const y8 = Fp12.mul(Fp12.mul(Fp12.conjugate(y6), y4), Fp12.conjugate(y2));
const y9 = Fp12.mul(y8, y1);
return Fp12.mul(Fp12.frobeniusMap(Fp12.mul(Fp12.conjugate(r), y9), 3), Fp12.mul(Fp12.frobeniusMap(y8, 2), Fp12.mul(Fp12.frobeniusMap(y9, 1), Fp12.mul(Fp12.mul(y8, y4), r))));
}
});
var { G2psi: G2psi3, psi: psi2 } = (0, tower_1.psiFrobenius)(Fp, Fp2, Fp2.NONRESIDUE);
function SVDWFpIsSquare(Fp3) {
return (u) => {
const x = Fp3.pow(u, (Fp3.ORDER - 1n) / 2n);
let legendre;
if (Fp3.eql(x, Fp3.neg(Fp3.ONE))) {
legendre = -1n;
} else if (Fp3.eql(x, Fp3.ZERO)) {
legendre = 0n;
} else if (Fp3.eql(x, Fp3.ONE)) {
legendre = 1n;
} else {
throw new Error("Legendre failed");
}
return legendre === 1n;
};
}
function mapToCurveSVDW2(Fp3, opts) {
mod2.validateField(Fp3);
if (!Fp3.isValid(opts.A) || !Fp3.isValid(opts.B) || !Fp3.isValid(opts.Z))
throw new Error("mapToCurveSimpleSVDW: invalid opts");
const isSquare = SVDWFpIsSquare(Fp3);
if (!Fp3.isOdd)
throw new Error("Fp.isOdd is not implemented!");
const g = (x) => Fp3.add(Fp3.add(Fp3.mul(Fp3.mul(x, x), x), Fp3.mul(opts.A, x)), opts.B);
const two = Fp3.add(Fp3.ONE, Fp3.ONE);
const three = Fp3.add(two, Fp3.ONE);
const four = Fp3.add(three, Fp3.ONE);
const c1 = g(opts.Z);
const c2 = Fp3.mul(Fp3.neg(opts.Z), Fp3.inv(Fp3.add(Fp3.ONE, Fp3.ONE)));
const c3 = Fp3.sqrt(Fp3.mul(Fp3.neg(c1), Fp3.add(Fp3.mul(three, Fp3.mul(opts.Z, opts.Z)), Fp3.mul(four, opts.A))));
const c4 = Fp3.mul(Fp3.mul(four, Fp3.neg(c1)), Fp3.inv(Fp3.add(Fp3.mul(three, Fp3.mul(opts.Z, opts.Z)), Fp3.mul(four, opts.A))));
return (u) => {
let tv1, tv2, tv3, tv4, x1, gx1, e1, x2, gx2, e2, x3, x, gx, y, e3;
tv1 = Fp3.mul(u, u);
tv1 = Fp3.mul(tv1, c1);
tv2 = Fp3.add(Fp3.ONE, tv1);
tv1 = Fp3.sub(Fp3.ONE, tv1);
tv3 = Fp3.mul(tv1, tv2);
tv3 = Fp3.inv(tv3);
tv4 = Fp3.mul(u, tv1);
tv4 = Fp3.mul(tv4, tv3);
tv4 = Fp3.mul(tv4, c3);
x1 = Fp3.sub(c2, tv4);
gx1 = Fp3.mul(x1, x1);
gx1 = Fp3.add(gx1, opts.A);
gx1 = Fp3.mul(gx1, x1);
gx1 = Fp3.add(gx1, opts.B);
e1 = isSquare(gx1);
x2 = Fp3.add(c2, tv4);
gx2 = Fp3.mul(x2, x2);
gx2 = Fp3.add(gx2, opts.A);
gx2 = Fp3.mul(gx2, x2);
gx2 = Fp3.add(gx2, opts.B);
e2 = isSquare(gx2) && !e1;
x3 = Fp3.mul(tv2, tv2);
x3 = Fp3.mul(x3, tv3);
x3 = Fp3.mul(x3, x3);
x3 = Fp3.mul(x3, c4);
x3 = Fp3.add(x3, opts.Z);
x = Fp3.cmov(x3, x1, !!e1);
x = Fp3.cmov(x, x2, !!e2);
gx = Fp3.mul(x, x);
gx = Fp3.add(gx, opts.A);
gx = Fp3.mul(gx, x);
gx = Fp3.add(gx, opts.B);
y = Fp3.sqrt(gx);
e3 = Fp3.isOdd(u) === Fp3.isOdd(y);
y = Fp3.cmov(Fp3.neg(y), y, e3);
return { x, y };
};
}
var G1_SVDW2 = mapToCurveSVDW2(Fp, {
A: Fp.ZERO,
B: _3n5,
Z: Fp.ONE
});
var mapToCurveG1 = (scalars) => G1_SVDW2(scalars[0]);
var drandHtf = Object.freeze({
// DST: a domain separation tag
// defined in section 2.2.5
// Use utils.getDSTLabel(), utils.setDSTLabel(value)
DST: "BLS_SIG_BN254G1_XMD:KECCAK-256_SVDW_RO_NUL_",
encodeDST: "BLS_SIG_BN254G1_XMD:KECCAK-256_SVDW_RO_NUL_",
// p: the characteristic of F
// where F is a finite field of characteristic p and order q = p^m
p: Fp.ORDER,
// m: the extension degree of F, m >= 1
// where F is a finite field of characteristic p and order q = p^m
m: 1,
// k: the target security level for the suite in bits
// defined in section 5.1
k: 128,
// option to use a message that has already been processed by
// expand_message_xmd
expand: "xmd",
// NB: We use keccak_256 to hash-to-curve for bn254 drand, as it is the
// cheapest hash function in the EVM.
hash: sha3_1.keccak_256
});
exports2.bn254 = (0, bls_1.bls)({
// Fields
fields: { Fp, Fp2, Fp6, Fp12, Fr },
G1: {
Fp,
h: BigInt(1),
Gx: BigInt(1),
Gy: BigInt(2),
a: Fp.ZERO,
b: _3n5,
htfDefaults: { ...drandHtf, m: 1 },
wrapPrivateKey: true,
allowInfinityPoint: true,
mapToCurve: mapToCurveG1,
fromBytes: (bytes) => {
const p = [bytes.slice(0, 32), bytes.slice(32, 64)].map((buf) => (0, utils_3.bytesToNumberBE)(buf));
const point = { x: Fp.create(p[0]), y: Fp.create(p[1]) };
exports2.bn254.G1.ProjectivePoint.fromAffine(point).assertValidity();
return point;
},
toBytes: (c, point, _isCompressed) => {
const isZero = point.equals(c.ZERO);
const { x, y } = point.toAffine();
const { BYTES: len } = Fp;
if (isZero) {
return new Uint8Array(len);
}
return (0, utils_2.concatBytes)((0, utils_3.numberToBytesBE)(x, len), (0, utils_3.numberToBytesBE)(y, len));
},
ShortSignature: {
fromHex(hex) {
return exports2.bn254.G1.ProjectivePoint.fromHex(hex);
},
toRawBytes(point) {
return point.toRawBytes();
},
toHex(point) {
return point.toHex();
}
}
},
G2: {
Fp: Fp2,
// cofactor: (36 * X^4) + (36 * X^3) + (30 * X^2) + 6*X + 1
h: BigInt("21888242871839275222246405745257275088844257914179612981679871602714643921549"),
Gx: Fp2.fromBigTuple([
BigInt("10857046999023057135944570762232829481370756359578518086990519993285655852781"),
BigInt("11559732032986387107991004021392285783925812861821192530917403151452391805634")
]),
Gy: Fp2.fromBigTuple([
BigInt("8495653923123431417604973247489272438418190587263600148770280649306958101930"),
BigInt("4082367875863433681332203403145435568316851327593401208105741076214120093531")
]),
a: Fp2.ZERO,
b: Fp2B,
hEff: BigInt("21888242871839275222246405745257275088844257914179612981679871602714643921549"),
htfDefaults: { ...drandHtf, m: 2 },
wrapPrivateKey: true,
allowInfinityPoint: true,
isTorsionFree: (c, P) => P.multiplyUnsafe(SIX_X_SQUARED).equals(G2psi3(c, P)),
// [p]P = [6X^2]P
mapToCurve: utils_2.notImplemented,
fromBytes: (bytes) => {
const p = [
bytes.slice(32, 64),
bytes.slice(0, 32),
bytes.slice(96, 128),
bytes.slice(64, 96)
].map((buf) => (0, utils_3.bytesToNumberBE)(buf));
const x = Fp2.create({ c0: p[0], c1: p[1] });
const y = Fp2.create({ c0: p[2], c1: p[3] });
exports2.bn254.G2.ProjectivePoint.fromAffine({ x, y }).assertValidity();
return { x, y };
},
toBytes: (c, point, _isCompressed) => {
const { BYTES: len } = Fp;
const isZero = point.equals(c.ZERO);
const { x, y } = point.toAffine();
const marshalSize = 4 * len;
if (isZero) {
return new Uint8Array(marshalSize);
}
const { re: x0, im: x1 } = Fp2.reim(x);
const { re: y0, im: y1 } = Fp2.reim(y);
return (0, utils_2.concatBytes)((0, utils_3.numberToBytesBE)(x1, len), (0, utils_3.numberToBytesBE)(x0, len), (0, utils_3.numberToBytesBE)(y1, len), (0, utils_3.numberToBytesBE)(y0, len));
},
Signature: {
fromHex(hex) {
return exports2.bn254.G2.ProjectivePoint.fromHex(hex);
},
toRawBytes(point) {
return point.toRawBytes();
},
toHex(point) {
return point.toHex();
}
}
},
params: {
ateLoopSize: BN_X * _6n + _2n7,
r: Fr.ORDER,
xNegative: false,
twistType: "divisive"
},
htfDefaults: drandHtf,
hash: sha3_1.keccak_256,
randomBytes: utils_1.randomBytes,
postPrecompute: (Rx, Ry, Rz, Qx, Qy, pointAdd) => {
const q = psi2(Qx, Qy);
({ Rx, Ry, Rz } = pointAdd(Rx, Ry, Rz, q[0], q[1]));
const q2 = psi2(q[0], q[1]);
pointAdd(Rx, Ry, Rz, q2[0], Fp2.neg(q2[1]));
}
});
}
});
// node_modules/@kevincharm/noble-bn254-drand/dist/src/index.js
var require_src = __commonJS({
"node_modules/@kevincharm/noble-bn254-drand/dist/src/index.js"(exports2) {
"use strict";
var __createBinding = exports2 && exports2.__createBinding || (Object.create ? function(o, m, k, k2) {
if (k2 === void 0) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() {
return m[k];
} };
}
Object.defineProperty(o, k2, desc);
} : function(o, m, k, k2) {
if (k2 === void 0) k2 = k;
o[k2] = m[k];
});
var __exportStar = exports2 && exports2.__exportStar || function(m, exports3) {
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports3, p)) __createBinding(exports3, m, p);
};
Object.defineProperty(exports2, "__esModule", { value: true });
__exportStar(require_bn254(), exports2);
}
});
// node_modules/pvtsutils/build/index.js
var require_build = __commonJS({
"node_modules/pvtsutils/build/index.js"(exports2) {
"use strict";
var ARRAY_BUFFER_NAME = "[object ArrayBuffer]";
var BufferSourceConverter = class _BufferSourceConverter {
static isArrayBuffer(data) {
return Object.prototype.toString.call(data) === ARRAY_BUFFER_NAME;
}
static toArrayBuffer(data) {
if (this.isArrayBuffer(data)) {
return data;
}
if (data.byteLength === data.buffer.byteLength) {
return data.buffer;
}
if (data.byteOffset === 0 && data.byteLength === data.buffer.byteLength) {
return data.buffer;
}
return this.toUint8Array(data.buffer).slice(data.byteOffset, data.byteOffset + data.byteLength).buffer;
}
static toUint8Array(data) {
return this.toView(data, Uint8Array);
}
static toView(data, type) {
if (data.constructor === type) {
return data;
}
if (this.isArrayBuffer(data)) {
return new type(data);
}
if (this.isArrayBufferView(data)) {
return new type(data.buffer, data.byteOffset, data.byteLength);
}
throw new TypeError("The provided value is not of type '(ArrayBuffer or ArrayBufferView)'");
}
static isBufferSource(data) {
return this.isArrayBufferView(data) || this.isArrayBuffer(data);
}
static isArrayBufferView(data) {
return ArrayBuffer.isView(data) || data && this.isArrayBuffer(data.buffer);
}
static isEqual(a, b) {
const aView = _BufferSourceConverter.toUint8Array(a);
const bView = _BufferSourceConverter.toUint8Array(b);
if (aView.length !== bView.byteLength) {
return false;
}
for (let i = 0; i < aView.length; i++) {
if (aView[i] !== bView[i]) {
return false;
}
}
return true;
}
static concat(...args) {
let buffers;
if (Array.isArray(args[0]) && !(args[1] instanceof Function)) {
buffers = args[0];
} else if (Array.isArray(args[0]) && args[1] instanceof Function) {
buffers = args[0];
} else {
if (args[args.length - 1] instanceof Function) {
buffers = args.slice(0, args.length - 1);
} else {
buffers = args;
}
}
let size = 0;
for (const buffer of buffers) {
size += buffer.byteLength;
}
const res = new Uint8Array(size);
let offset = 0;
for (const buffer of buffers) {
const view = this.toUint8Array(buffer);
res.set(view, offset);
offset += view.length;
}
if (args[args.length - 1] instanceof Function) {
return this.toView(res, args[args.length - 1]);
}
return res.buffer;
}
};
var STRING_TYPE = "string";
var HEX_REGEX = /^[0-9a-f\s]+$/i;
var BASE64_REGEX = /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/;
var BASE64URL_REGEX = /^[a-zA-Z0-9-_]+$/;
var Utf8Converter = class {
static fromString(text) {
const s = unescape(encodeURIComponent(text));
const uintArray = new Uint8Array(s.length);
for (let i = 0; i < s.length; i++) {
uintArray[i] = s.charCodeAt(i);
}
return uintArray.buffer;
}
static toString(buffer) {
const buf = BufferSourceConverter.toUint8Array(buffer);
let encodedString = "";
for (let i = 0; i < buf.length; i++) {
encodedString += String.fromCharCode(buf[i]);
}
const decodedString = decodeURIComponent(escape(encodedString));
return decodedString;
}
};
var Utf16Converter = class {
static toString(buffer, littleEndian = false) {
const arrayBuffer = BufferSourceConverter.toArrayBuffer(buffer);
const dataView = new DataView(arrayBuffer);
let res = "";
for (let i = 0; i < arrayBuffer.byteLength; i += 2) {
const code = dataView.getUint16(i, littleEndian);
res += String.fromCharCode(code);
}
return res;
}
static fromString(text, littleEndian = false) {
const res = new ArrayBuffer(text.length * 2);
const dataView = new DataView(res);
for (let i = 0; i < text.length; i++) {
dataView.setUint16(i * 2, text.charCodeAt(i), littleEndian);
}
return res;
}
};
var Convert = class _Convert {
static isHex(data) {
return typeof data === STRING_TYPE && HEX_REGEX.test(data);
}
static isBase64(data) {
return typeof data === STRING_TYPE && BASE64_REGEX.test(data);
}
static isBase64Url(data) {
return typeof data === STRING_TYPE && BASE64URL_REGEX.test(data);
}
static ToString(buffer, enc = "utf8") {
const buf = BufferSourceConverter.toUint8Array(buffer);
switch (enc.toLowerCase()) {
case "utf8":
return this.ToUtf8String(buf);
case "binary":
return this.ToBinary(buf);
case "hex":
return this.ToHex(buf);
case "base64":
return this.ToBase64(buf);
case "base64url":
return this.ToBase64Url(buf);
case "utf16le":
return Utf16Converter.toString(buf, true);
case "utf16":
case "utf16be":
return Utf16Converter.toString(buf);
default:
throw new Error(`Unknown type of encoding '${enc}'`);
}
}
static FromString(str, enc = "utf8") {
if (!str) {
return new ArrayBuffer(0);
}
switch (enc.toLowerCase()) {
case "utf8":
return this.FromUtf8String(str);
case "binary":
return this.FromBinary(str);
case "hex":
return this.FromHex(str);
case "base64":
return this.FromBase64(str);
case "base64url":
return this.FromBase64Url(str);
case "utf16le":
return Utf16Converter.fromString(str, true);
case "utf16":
case "utf16be":
return Utf16Converter.fromString(str);
default:
throw new Error(`Unknown type of encoding '${enc}'`);
}
}
static ToBase64(buffer) {
const buf = BufferSourceConverter.toUint8Array(buffer);
if (typeof btoa !== "undefined") {
const binary = this.ToString(buf, "binary");
return btoa(binary);
} else {
return Buffer.from(buf).toString("base64");
}
}
static FromBase64(base64) {
const formatted = this.formatString(base64);
if (!formatted) {
return new ArrayBuffer(0);
}
if (!_Convert.isBase64(formatted)) {
throw new TypeError("Argument 'base64Text' is not Base64 encoded");
}
if (typeof atob !== "undefined") {
return this.FromBinary(atob(formatted));
} else {
return new Uint8Array(Buffer.from(formatted, "base64")).buffer;
}
}
static FromBase64Url(base64url) {
const formatted = this.formatString(base64url);
if (!formatted) {
return new ArrayBuffer(0);
}
if (!_Convert.isBase64Url(formatted)) {
throw new TypeError("Argument 'base64url' is not Base64Url encoded");
}
return this.FromBase64(this.Base64Padding(formatted.replace(/\-/g, "+").replace(/\_/g, "/")));
}
static ToBase64Url(data) {
return this.ToBase64(data).replace(/\+/g, "-").replace(/\//g, "_").replace(/\=/g, "");
}
static FromUtf8String(text, encoding = _Convert.DEFAULT_UTF8_ENCODING) {
switch (encoding) {
case "ascii":
return this.FromBinary(text);
case "utf8":
return Utf8Converter.fromString(text);
case "utf16":
case "utf16be":
return Utf16Converter.fromString(text);
case "utf16le":
case "usc2":
return Utf16Converter.fromString(text, true);
default:
throw new Error(`Unknown type of encoding '${encoding}'`);
}
}
static ToUtf8String(buffer, encoding = _Convert.DEFAULT_UTF8_ENCODING) {
switch (encoding) {
case "ascii":
return this.ToBinary(buffer);
case "utf8":
return Utf8Converter.toString(buffer);
case "utf16":
case "utf16be":
return Utf16Converter.toString(buffer);
case "utf16le":
case "usc2":
return Utf16Converter.toString(buffer, true);
default:
throw new Error(`Unknown type of encoding '${encoding}'`);
}
}
static FromBinary(text) {
const stringLength = text.length;
const resultView = new Uint8Array(stringLength);
for (let i = 0; i < stringLength; i++) {
resultView[i] = text.charCodeAt(i);
}
return resultView.buffer;
}
static ToBinary(buffer) {
const buf = BufferSourceConverter.toUint8Array(buffer);
let res = "";
for (let i = 0; i < buf.length; i++) {
res += String.fromCharCode(buf[i]);
}
return res;
}
static ToHex(buffer) {
const buf = BufferSourceConverter.toUint8Array(buffer);
let result = "";
const len = buf.length;
for (let i = 0; i < len; i++) {
const byte = buf[i];
if (byte < 16) {
result += "0";
}
result += byte.toString(16);
}
return result;
}
static FromHex(hexString) {
let formatted = this.formatString(hexString);
if (!formatted) {
return new ArrayBuffer(0);
}
if (!_Convert.isHex(formatted)) {
throw new TypeError("Argument 'hexString' is not HEX encoded");
}
if (formatted.length % 2) {
formatted = `0${formatted}`;
}
const res = new Uint8Array(formatted.length / 2);
for (let i = 0; i < formatted.length; i = i + 2) {
const c = formatted.slice(i, i + 2);
res[i / 2] = parseInt(c, 16);
}
return res.buffer;
}
static ToUtf16String(buffer, littleEndian = false) {
return Utf16Converter.toString(buffer, littleEndian);
}
static FromUtf16String(text, littleEndian = false) {
return Utf16Converter.fromString(text, littleEndian);
}
static Base64Padding(base64) {
const padCount = 4 - base64.length % 4;
if (padCount < 4) {
for (let i = 0; i < padCount; i++) {
base64 += "=";
}
}
return base64;
}
static formatString(data) {
return (data === null || data === void 0 ? void 0 : data.replace(/[\n\r\t ]/g, "")) || "";
}
};
Convert.DEFAULT_UTF8_ENCODING = "utf8";
function assign(target, ...sources) {
const res = arguments[0];
for (let i = 1; i < arguments.length; i++) {
const obj = arguments[i];
for (const prop in obj) {
res[prop] = obj[prop];
}
}
return res;
}
function combine(...buf) {
const totalByteLength = buf.map((item) => item.byteLength).reduce((prev, cur) => prev + cur);
const res = new Uint8Array(totalByteLength);
let currentPos = 0;
buf.map((item) => new Uint8Array(item)).forEach((arr) => {
for (const item2 of arr) {
res[currentPos++] = item2;
}
});
return res.buffer;
}
function isEqual(bytes1, bytes2) {
if (!(bytes1 && bytes2)) {
return false;
}
if (bytes1.byteLength !== bytes2.byteLength) {
return false;
}
const b1 = new Uint8Array(bytes1);
const b2 = new Uint8Array(bytes2);
for (let i = 0; i < bytes1.byteLength; i++) {
if (b1[i] !== b2[i]) {
return false;
}
}
return true;
}
exports2.BufferSourceConverter = BufferSourceConverter;
exports2.Convert = Convert;
exports2.assign = assign;
exports2.combine = combine;
exports2.isEqual = isEqual;
}
});
// node_modules/pvutils/build/utils.js
var require_utils3 = __commonJS({
"node_modules/pvutils/build/utils.js"(exports2) {
"use strict";
Object.defineProperty(exports2, "__esModule", { value: true });
function getUTCDate(date) {
return new Date(date.getTime() + date.getTimezoneOffset() * 6e4);
}
function getParametersValue(parameters, name, defaultValue) {
var _a;
if (parameters instanceof Object === false) {
return defaultValue;
}
return (_a = parameters[name]) !== null && _a !== void 0 ? _a : defaultValue;
}
function bufferToHexCodes(inputBuffer, inputOffset = 0, inputLength = inputBuffer.byteLength - inputOffset, insertSpace = false) {
let result = "";
for (const item of new Uint8Array(inputBuffer, inputOffset, inputLength)) {
const str = item.toString(16).toUpperCase();
if (str.length === 1) {
result += "0";
}
result += str;
if (insertSpace) {
result += " ";
}
}
return result.trim();
}
function checkBufferParams(baseBlock, inputBuffer, inputOffset, inputLength) {
if (!(inputBuffer instanceof ArrayBuffer)) {
baseBlock.error = 'Wrong parameter: inputBuffer must be "ArrayBuffer"';
return false;
}
if (!inputBuffer.byteLength) {
baseBlock.error = "Wrong parameter: inputBuffer has zero length";
return false;
}
if (inputOffset < 0) {
baseBlock.error = "Wrong parameter: inputOffset less than zero";
return false;
}
if (inputLength < 0) {
baseBlock.error = "Wrong parameter: inputLength less than zero";
return false;
}
if (inputBuffer.byteLength - inputOffset - inputLength < 0) {
baseBlock.error = "End of input reached before message was fully decoded (inconsistent offset and length values)";
return false;
}
return true;
}
function utilFromBase(inputBuffer, inputBase) {
let result = 0;
if (inputBuffer.length === 1) {
return inputBuffer[0];
}
for (let i = inputBuffer.length - 1; i >= 0; i--) {
result += inputBuffer[inputBuffer.length - 1 - i] * Math.pow(2, inputBase * i);
}
return result;
}
function utilToBase(value, base, reserved = -1) {
const internalReserved = reserved;
let internalValue = value;
let result = 0;
let biggest = Math.pow(2, base);
for (let i = 1; i < 8; i++) {
if (value < biggest) {
let retBuf;
if (internalReserved < 0) {
retBuf = new ArrayBuffer(i);
result = i;
} else {
if (internalReserved < i) {
return new ArrayBuffer(0);
}
retBuf = new ArrayBuffer(internalReserved);
result = internalReserved;
}
const retView = new Uint8Array(retBuf);
for (let j = i - 1; j >= 0; j--) {
const basis = Math.pow(2, j * base);
retView[result - j - 1] = Math.floor(internalValue / basis);
internalValue -= retView[result - j - 1] * basis;
}
return retBuf;
}
biggest *= Math.pow(2, base);
}
return new ArrayBuffer(0);
}
function utilConcatBuf(...buffers) {
let outputLength = 0;
let prevLength = 0;
for (const buffer of buffers) {
outputLength += buffer.byteLength;
}
const retBuf = new ArrayBuffer(outputLength);
const retView = new Uint8Array(retBuf);
for (const buffer of buffers) {
retView.set(new Uint8Array(buffer), prevLength);
prevLength += buffer.byteLength;
}
return retBuf;
}
function utilConcatView(...views) {
let outputLength = 0;
let prevLength = 0;
for (const view of views) {
outputLength += view.length;
}
const retBuf = new ArrayBuffer(outputLength);
const retView = new Uint8Array(retBuf);
for (const view of views) {
retView.set(view, prevLength);
prevLength += view.length;
}
return retView;
}
function utilDecodeTC() {
const buf = new Uint8Array(this.valueHex);
if (this.valueHex.byteLength >= 2) {
const condition1 = buf[0] === 255 && buf[1] & 128;
const condition2 = buf[0] === 0 && (buf[1] & 128) === 0;
if (condition1 || condition2) {
this.warnings.push("Needlessly long format");
}
}
const bigIntBuffer = new ArrayBuffer(this.valueHex.byteLength);
const bigIntView = new Uint8Array(bigIntBuffer);
for (let i = 0; i < this.valueHex.byteLength; i++) {
bigIntView[i] = 0;
}
bigIntView[0] = buf[0] & 128;
const bigInt = utilFromBase(bigIntView, 8);
const smallIntBuffer = new ArrayBuffer(this.valueHex.byteLength);
const smallIntView = new Uint8Array(smallIntBuffer);
for (let j = 0; j < this.valueHex.byteLength; j++) {
smallIntView[j] = buf[j];
}
smallIntView[0] &= 127;
const smallInt = utilFromBase(smallIntView, 8);
return smallInt - bigInt;
}
function utilEncodeTC(value) {
const modValue = value < 0 ? value * -1 : value;
let bigInt = 128;
for (let i = 1; i < 8; i++) {
if (modValue <= bigInt) {
if (value < 0) {
const smallInt = bigInt - modValue;
const retBuf2 = utilToBase(smallInt, 8, i);
const retView2 = new Uint8Array(retBuf2);
retView2[0] |= 128;
return retBuf2;
}
let retBuf = utilToBase(modValue, 8, i);
let retView = new Uint8Array(retBuf);
if (retView[0] & 128) {
const tempBuf = retBuf.slice(0);
const tempView = new Uint8Array(tempBuf);
retBuf = new ArrayBuffer(retBuf.byteLength + 1);
retView = new Uint8Array(retBuf);
for (let k = 0; k < tempBuf.byteLength; k++) {
retView[k + 1] = tempView[k];
}
retView[0] = 0;
}
return retBuf;
}
bigInt *= Math.pow(2, 8);
}
return new ArrayBuffer(0);
}
function isEqualBuffer(inputBuffer1, inputBuffer2) {
if (inputBuffer1.byteLength !== inputBuffer2.byteLength) {
return false;
}
const view1 = new Uint8Array(inputBuffer1);
const view2 = new Uint8Array(inputBuffer2);
for (let i = 0; i < view1.length; i++) {
if (view1[i] !== view2[i]) {
return false;
}
}
return true;
}
function padNumber(inputNumber, fullLength) {
const str = inputNumber.toString(10);
if (fullLength < str.length) {
return "";
}
const dif = fullLength - str.length;
const padding = new Array(dif);
for (let i = 0; i < dif; i++) {
padding[i] = "0";
}
const paddingString = padding.join("");
return paddingString.concat(str);
}
var base64Template = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
var base64UrlTemplate = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=";
function toBase64(input, useUrlTemplate = false, skipPadding = false, skipLeadingZeros = false) {
let i = 0;
let flag1 = 0;
let flag2 = 0;
let output = "";
const template = useUrlTemplate ? base64UrlTemplate : base64Template;
if (skipLeadingZeros) {
let nonZeroPosition = 0;
for (let i2 = 0; i2 < input.length; i2++) {
if (input.charCodeAt(i2) !== 0) {
nonZeroPosition = i2;
break;
}
}
input = input.slice(nonZeroPosition);
}
while (i < input.length) {
const chr1 = input.charCodeAt(i++);
if (i >= input.length) {
flag1 = 1;
}
const chr2 = input.charCodeAt(i++);
if (i >= input.length) {
flag2 = 1;
}
const chr3 = input.charCodeAt(i++);
const enc1 = chr1 >> 2;
const enc2 = (chr1 & 3) << 4 | chr2 >> 4;
let enc3 = (chr2 & 15) << 2 | chr3 >> 6;
let enc4 = chr3 & 63;
if (flag1 === 1) {
enc3 = enc4 = 64;
} else {
if (flag2 === 1) {
enc4 = 64;
}
}
if (skipPadding) {
if (enc3 === 64) {
output += `${template.charAt(enc1)}${template.charAt(enc2)}`;
} else {
if (enc4 === 64) {
output += `${template.charAt(enc1)}${template.charAt(enc2)}${template.charAt(enc3)}`;
} else {
output += `${template.charAt(enc1)}${template.charAt(enc2)}${template.charAt(enc3)}${template.charAt(enc4)}`;
}
}
} else {
output += `${template.charAt(enc1)}${template.charAt(enc2)}${template.charAt(enc3)}${template.charAt(enc4)}`;
}
}
return output;
}
function fromBase64(input, useUrlTemplate = false, cutTailZeros = false) {
const template = useUrlTemplate ? base64UrlTemplate : base64Template;
function indexOf(toSearch) {
for (let i2 = 0; i2 < 64; i2++) {
if (template.charAt(i2) === toSearch)
return i2;
}
return 64;
}
function test(incoming) {
return incoming === 64 ? 0 : incoming;
}
let i = 0;
let output = "";
while (i < input.length) {
const enc1 = indexOf(input.charAt(i++));
const enc2 = i >= input.length ? 0 : indexOf(input.charAt(i++));
const enc3 = i >= input.length ? 0 : indexOf(input.charAt(i++));
const enc4 = i >= input.length ? 0 : indexOf(input.charAt(i++));
const chr1 = test(enc1) << 2 | test(enc2) >> 4;
const chr2 = (test(enc2) & 15) << 4 | test(enc3) >> 2;
const chr3 = (test(enc3) & 3) << 6 | test(enc4);
output += String.fromCharCode(chr1);
if (enc3 !== 64) {
output += String.fromCharCode(chr2);
}
if (enc4 !== 64) {
output += String.fromCharCode(chr3);
}
}
if (cutTailZeros) {
const outputLength = output.length;
let nonZeroStart = -1;
for (let i2 = outputLength - 1; i2 >= 0; i2--) {
if (output.charCodeAt(i2) !== 0) {
nonZeroStart = i2;
break;
}
}
if (nonZeroStart !== -1) {
output = output.slice(0, nonZeroStart + 1);
} else {
output = "";
}
}
return output;
}
function arrayBufferToString(buffer) {
let resultString = "";
const view = new Uint8Array(buffer);
for (const element of view) {
resultString += String.fromCharCode(element);
}
return resultString;
}
function stringToArrayBuffer(str) {
const stringLength = str.length;
const resultBuffer = new ArrayBuffer(stringLength);
const resultView = new Uint8Array(resultBuffer);
for (let i = 0; i < stringLength; i++) {
resultView[i] = str.charCodeAt(i);
}
return resultBuffer;
}
var log2 = Math.log(2);
function nearestPowerOf2(length) {
const base = Math.log(length) / log2;
const floor = Math.floor(base);
const round = Math.round(base);
return floor === round ? floor : round;
}
function clearProps(object, propsArray) {
for (const prop of propsArray) {
delete object[prop];
}
}
exports2.arrayBufferToString = arrayBufferToString;
exports2.bufferToHexCodes = bufferToHexCodes;
exports2.checkBufferParams = checkBufferParams;
exports2.clearProps = clearProps;
exports2.fromBase64 = fromBase64;
exports2.getParametersValue = getParametersValue;
exports2.getUTCDate = getUTCDate;
exports2.isEqualBuffer = isEqualBuffer;
exports2.nearestPowerOf2 = nearestPowerOf2;
exports2.padNumber = padNumber;
exports2.stringToArrayBuffer = stringToArrayBuffer;
exports2.toBase64 = toBase64;
exports2.utilConcatBuf = utilConcatBuf;
exports2.utilConcatView = utilConcatView;
exports2.utilDecodeTC = utilDecodeTC;
exports2.utilEncodeTC = utilEncodeTC;
exports2.utilFromBase = utilFromBase;
exports2.utilToBase = utilToBase;
}
});
// node_modules/asn1js/build/index.js
var require_build2 = __commonJS({
"node_modules/asn1js/build/index.js"(exports2) {
"use strict";
var pvtsutils = require_build();
var pvutils = require_utils3();
function _interopNamespaceDefault(e) {
var n = /* @__PURE__ */ Object.create(null);
if (e) {
Object.keys(e).forEach(function(k) {
if (k !== "default") {
var d = Object.getOwnPropertyDescriptor(e, k);
Object.defineProperty(n, k, d.get ? d : {
enumerable: true,
get: function() {
return e[k];
}
});
}
});
}
n.default = e;
return Object.freeze(n);
}
var pvtsutils__namespace = /* @__PURE__ */ _interopNamespaceDefault(pvtsutils);
var pvutils__namespace = /* @__PURE__ */ _interopNamespaceDefault(pvutils);
function assertBigInt() {
if (typeof BigInt === "undefined") {
throw new Error("BigInt is not defined. Your environment doesn't implement BigInt.");
}
}
function concat(buffers) {
let outputLength = 0;
let prevLength = 0;
for (let i = 0; i < buffers.length; i++) {
const buffer = buffers[i];
outputLength += buffer.byteLength;
}
const retView = new Uint8Array(outputLength);
for (let i = 0; i < buffers.length; i++) {
const buffer = buffers[i];
retView.set(new Uint8Array(buffer), prevLength);
prevLength += buffer.byteLength;
}
return retView.buffer;
}
function checkBufferParams(baseBlock, inputBuffer, inputOffset, inputLength) {
if (!(inputBuffer instanceof Uint8Array)) {
baseBlock.error = "Wrong parameter: inputBuffer must be 'Uint8Array'";
return false;
}
if (!inputBuffer.byteLength) {
baseBlock.error = "Wrong parameter: inputBuffer has zero length";
return false;
}
if (inputOffset < 0) {
baseBlock.error = "Wrong parameter: inputOffset less than zero";
return false;
}
if (inputLength < 0) {
baseBlock.error = "Wrong parameter: inputLength less than zero";
return false;
}
if (inputBuffer.byteLength - inputOffset - inputLength < 0) {
baseBlock.error = "End of input reached before message was fully decoded (inconsistent offset and length values)";
return false;
}
return true;
}
var ViewWriter = class {
constructor() {
this.items = [];
}
write(buf) {
this.items.push(buf);
}
final() {
return concat(this.items);
}
};
var powers2 = [new Uint8Array([1])];
var digitsString = "0123456789";
var NAME = "name";
var VALUE_HEX_VIEW = "valueHexView";
var IS_HEX_ONLY = "isHexOnly";
var ID_BLOCK = "idBlock";
var TAG_CLASS = "tagClass";
var TAG_NUMBER = "tagNumber";
var IS_CONSTRUCTED = "isConstructed";
var FROM_BER = "fromBER";
var TO_BER = "toBER";
var LOCAL = "local";
var EMPTY_STRING = "";
var EMPTY_BUFFER = new ArrayBuffer(0);
var EMPTY_VIEW = new Uint8Array(0);
var END_OF_CONTENT_NAME = "EndOfContent";
var OCTET_STRING_NAME = "OCTET STRING";
var BIT_STRING_NAME = "BIT STRING";
function HexBlock(BaseClass) {
var _a2;
return _a2 = class Some extends BaseClass {
get valueHex() {
return this.valueHexView.slice().buffer;
}
set valueHex(value) {
this.valueHexView = new Uint8Array(value);
}
constructor(...args) {
var _b;
super(...args);
const params = args[0] || {};
this.isHexOnly = (_b = params.isHexOnly) !== null && _b !== void 0 ? _b : false;
this.valueHexView = params.valueHex ? pvtsutils__namespace.BufferSourceConverter.toUint8Array(params.valueHex) : EMPTY_VIEW;
}
fromBER(inputBuffer, inputOffset, inputLength) {
const view = inputBuffer instanceof ArrayBuffer ? new Uint8Array(inputBuffer) : inputBuffer;
if (!checkBufferParams(this, view, inputOffset, inputLength)) {
return -1;
}
const endLength = inputOffset + inputLength;
this.valueHexView = view.subarray(inputOffset, endLength);
if (!this.valueHexView.length) {
this.warnings.push("Zero buffer length");
return inputOffset;
}
this.blockLength = inputLength;
return endLength;
}
toBER(sizeOnly = false) {
if (!this.isHexOnly) {
this.error = "Flag 'isHexOnly' is not set, abort";
return EMPTY_BUFFER;
}
if (sizeOnly) {
return new ArrayBuffer(this.valueHexView.byteLength);
}
return this.valueHexView.byteLength === this.valueHexView.buffer.byteLength ? this.valueHexView.buffer : this.valueHexView.slice().buffer;
}
toJSON() {
return {
...super.toJSON(),
isHexOnly: this.isHexOnly,
valueHex: pvtsutils__namespace.Convert.ToHex(this.valueHexView)
};
}
}, _a2.NAME = "hexBlock", _a2;
}
var LocalBaseBlock = class {
static blockName() {
return this.NAME;
}
get valueBeforeDecode() {
return this.valueBeforeDecodeView.slice().buffer;
}
set valueBeforeDecode(value) {
this.valueBeforeDecodeView = new Uint8Array(value);
}
constructor({ blockLength = 0, error = EMPTY_STRING, warnings = [], valueBeforeDecode = EMPTY_VIEW } = {}) {
this.blockLength = blockLength;
this.error = error;
this.warnings = warnings;
this.valueBeforeDecodeView = pvtsutils__namespace.BufferSourceConverter.toUint8Array(valueBeforeDecode);
}
toJSON() {
return {
blockName: this.constructor.NAME,
blockLength: this.blockLength,
error: this.error,
warnings: this.warnings,
valueBeforeDecode: pvtsutils__namespace.Convert.ToHex(this.valueBeforeDecodeView)
};
}
};
LocalBaseBlock.NAME = "baseBlock";
var ValueBlock = class extends LocalBaseBlock {
fromBER(_inputBuffer, _inputOffset, _inputLength) {
throw TypeError("User need to make a specific function in a class which extends 'ValueBlock'");
}
toBER(_sizeOnly, _writer) {
throw TypeError("User need to make a specific function in a class which extends 'ValueBlock'");
}
};
ValueBlock.NAME = "valueBlock";
var LocalIdentificationBlock = class extends HexBlock(LocalBaseBlock) {
constructor({ idBlock = {} } = {}) {
var _a2, _b, _c, _d;
super();
if (idBlock) {
this.isHexOnly = (_a2 = idBlock.isHexOnly) !== null && _a2 !== void 0 ? _a2 : false;
this.valueHexView = idBlock.valueHex ? pvtsutils__namespace.BufferSourceConverter.toUint8Array(idBlock.valueHex) : EMPTY_VIEW;
this.tagClass = (_b = idBlock.tagClass) !== null && _b !== void 0 ? _b : -1;
this.tagNumber = (_c = idBlock.tagNumber) !== null && _c !== void 0 ? _c : -1;
this.isConstructed = (_d = idBlock.isConstructed) !== null && _d !== void 0 ? _d : false;
} else {
this.tagClass = -1;
this.tagNumber = -1;
this.isConstructed = false;
}
}
toBER(sizeOnly = false) {
let firstOctet = 0;
switch (this.tagClass) {
case 1:
firstOctet |= 0;
break;
case 2:
firstOctet |= 64;
break;
case 3:
firstOctet |= 128;
break;
case 4:
firstOctet |= 192;
break;
default:
this.error = "Unknown tag class";
return EMPTY_BUFFER;
}
if (this.isConstructed)
firstOctet |= 32;
if (this.tagNumber < 31 && !this.isHexOnly) {
const retView2 = new Uint8Array(1);
if (!sizeOnly) {
let number = this.tagNumber;
number &= 31;
firstOctet |= number;
retView2[0] = firstOctet;
}
return retView2.buffer;
}
if (!this.isHexOnly) {
const encodedBuf = pvutils__namespace.utilToBase(this.tagNumber, 7);
const encodedView = new Uint8Array(encodedBuf);
const size = encodedBuf.byteLength;
const retView2 = new Uint8Array(size + 1);
retView2[0] = firstOctet | 31;
if (!sizeOnly) {
for (let i = 0; i < size - 1; i++)
retView2[i + 1] = encodedView[i] | 128;
retView2[size] = encodedView[size - 1];
}
return retView2.buffer;
}
const retView = new Uint8Array(this.valueHexView.byteLength + 1);
retView[0] = firstOctet | 31;
if (!sizeOnly) {
const curView = this.valueHexView;
for (let i = 0; i < curView.length - 1; i++)
retView[i + 1] = curView[i] | 128;
retView[this.valueHexView.byteLength] = curView[curView.length - 1];
}
return retView.buffer;
}
fromBER(inputBuffer, inputOffset, inputLength) {
const inputView = pvtsutils__namespace.BufferSourceConverter.toUint8Array(inputBuffer);
if (!checkBufferParams(this, inputView, inputOffset, inputLength)) {
return -1;
}
const intBuffer = inputView.subarray(inputOffset, inputOffset + inputLength);
if (intBuffer.length === 0) {
this.error = "Zero buffer length";
return -1;
}
const tagClassMask = intBuffer[0] & 192;
switch (tagClassMask) {
case 0:
this.tagClass = 1;
break;
case 64:
this.tagClass = 2;
break;
case 128:
this.tagClass = 3;
break;
case 192:
this.tagClass = 4;
break;
default:
this.error = "Unknown tag class";
return -1;
}
this.isConstructed = (intBuffer[0] & 32) === 32;
this.isHexOnly = false;
const tagNumberMask = intBuffer[0] & 31;
if (tagNumberMask !== 31) {
this.tagNumber = tagNumberMask;
this.blockLength = 1;
} else {
let count = 1;
let intTagNumberBuffer = this.valueHexView = new Uint8Array(255);
let tagNumberBufferMaxLength = 255;
while (intBuffer[count] & 128) {
intTagNumberBuffer[count - 1] = intBuffer[count] & 127;
count++;
if (count >= intBuffer.length) {
this.error = "End of input reached before message was fully decoded";
return -1;
}
if (count === tagNumberBufferMaxLength) {
tagNumberBufferMaxLength += 255;
const tempBufferView2 = new Uint8Array(tagNumberBufferMaxLength);
for (let i = 0; i < intTagNumberBuffer.length; i++)
tempBufferView2[i] = intTagNumberBuffer[i];
intTagNumberBuffer = this.valueHexView = new Uint8Array(tagNumberBufferMaxLength);
}
}
this.blockLength = count + 1;
intTagNumberBuffer[count - 1] = intBuffer[count] & 127;
const tempBufferView = new Uint8Array(count);
for (let i = 0; i < count; i++)
tempBufferView[i] = intTagNumberBuffer[i];
intTagNumberBuffer = this.valueHexView = new Uint8Array(count);
intTagNumberBuffer.set(tempBufferView);
if (this.blockLength <= 9)
this.tagNumber = pvutils__namespace.utilFromBase(intTagNumberBuffer, 7);
else {
this.isHexOnly = true;
this.warnings.push("Tag too long, represented as hex-coded");
}
}
if (this.tagClass === 1 && this.isConstructed) {
switch (this.tagNumber) {
case 1:
case 2:
case 5:
case 6:
case 9:
case 13:
case 14:
case 23:
case 24:
case 31:
case 32:
case 33:
case 34:
this.error = "Constructed encoding used for primitive type";
return -1;
}
}
return inputOffset + this.blockLength;
}
toJSON() {
return {
...super.toJSON(),
tagClass: this.tagClass,
tagNumber: this.tagNumber,
isConstructed: this.isConstructed
};
}
};
LocalIdentificationBlock.NAME = "identificationBlock";
var LocalLengthBlock = class extends LocalBaseBlock {
constructor({ lenBlock = {} } = {}) {
var _a2, _b, _c;
super();
this.isIndefiniteForm = (_a2 = lenBlock.isIndefiniteForm) !== null && _a2 !== void 0 ? _a2 : false;
this.longFormUsed = (_b = lenBlock.longFormUsed) !== null && _b !== void 0 ? _b : false;
this.length = (_c = lenBlock.length) !== null && _c !== void 0 ? _c : 0;
}
fromBER(inputBuffer, inputOffset, inputLength) {
const view = pvtsutils__namespace.BufferSourceConverter.toUint8Array(inputBuffer);
if (!checkBufferParams(this, view, inputOffset, inputLength)) {
return -1;
}
const intBuffer = view.subarray(inputOffset, inputOffset + inputLength);
if (intBuffer.length === 0) {
this.error = "Zero buffer length";
return -1;
}
if (intBuffer[0] === 255) {
this.error = "Length block 0xFF is reserved by standard";
return -1;
}
this.isIndefiniteForm = intBuffer[0] === 128;
if (this.isIndefiniteForm) {
this.blockLength = 1;
return inputOffset + this.blockLength;
}
this.longFormUsed = !!(intBuffer[0] & 128);
if (this.longFormUsed === false) {
this.length = intBuffer[0];
this.blockLength = 1;
return inputOffset + this.blockLength;
}
const count = intBuffer[0] & 127;
if (count > 8) {
this.error = "Too big integer";
return -1;
}
if (count + 1 > intBuffer.length) {
this.error = "End of input reached before message was fully decoded";
return -1;
}
const lenOffset = inputOffset + 1;
const lengthBufferView = view.subarray(lenOffset, lenOffset + count);
if (lengthBufferView[count - 1] === 0)
this.warnings.push("Needlessly long encoded length");
this.length = pvutils__namespace.utilFromBase(lengthBufferView, 8);
if (this.longFormUsed && this.length <= 127)
this.warnings.push("Unnecessary usage of long length form");
this.blockLength = count + 1;
return inputOffset + this.blockLength;
}
toBER(sizeOnly = false) {
let retBuf;
let retView;
if (this.length > 127)
this.longFormUsed = true;
if (this.isIndefiniteForm) {
retBuf = new ArrayBuffer(1);
if (sizeOnly === false) {
retView = new Uint8Array(retBuf);
retView[0] = 128;
}
return retBuf;
}
if (this.longFormUsed) {
const encodedBuf = pvutils__namespace.utilToBase(this.length, 8);
if (encodedBuf.byteLength > 127) {
this.error = "Too big length";
return EMPTY_BUFFER;
}
retBuf = new ArrayBuffer(encodedBuf.byteLength + 1);
if (sizeOnly)
return retBuf;
const encodedView = new Uint8Array(encodedBuf);
retView = new Uint8Array(retBuf);
retView[0] = encodedBuf.byteLength | 128;
for (let i = 0; i < encodedBuf.byteLength; i++)
retView[i + 1] = encodedView[i];
return retBuf;
}
retBuf = new ArrayBuffer(1);
if (sizeOnly === false) {
retView = new Uint8Array(retBuf);
retView[0] = this.length;
}
return retBuf;
}
toJSON() {
return {
...super.toJSON(),
isIndefiniteForm: this.isIndefiniteForm,
longFormUsed: this.longFormUsed,
length: this.length
};
}
};
LocalLengthBlock.NAME = "lengthBlock";
var typeStore = {};
var BaseBlock = class extends LocalBaseBlock {
constructor({ name = EMPTY_STRING, optional = false, primitiveSchema, ...parameters } = {}, valueBlockType) {
super(parameters);
this.name = name;
this.optional = optional;
if (primitiveSchema) {
this.primitiveSchema = primitiveSchema;
}
this.idBlock = new LocalIdentificationBlock(parameters);
this.lenBlock = new LocalLengthBlock(parameters);
this.valueBlock = valueBlockType ? new valueBlockType(parameters) : new ValueBlock(parameters);
}
fromBER(inputBuffer, inputOffset, inputLength) {
const resultOffset = this.valueBlock.fromBER(inputBuffer, inputOffset, this.lenBlock.isIndefiniteForm ? inputLength : this.lenBlock.length);
if (resultOffset === -1) {
this.error = this.valueBlock.error;
return resultOffset;
}
if (!this.idBlock.error.length)
this.blockLength += this.idBlock.blockLength;
if (!this.lenBlock.error.length)
this.blockLength += this.lenBlock.blockLength;
if (!this.valueBlock.error.length)
this.blockLength += this.valueBlock.blockLength;
return resultOffset;
}
toBER(sizeOnly, writer) {
const _writer = writer || new ViewWriter();
if (!writer) {
prepareIndefiniteForm(this);
}
const idBlockBuf = this.idBlock.toBER(sizeOnly);
_writer.write(idBlockBuf);
if (this.lenBlock.isIndefiniteForm) {
_writer.write(new Uint8Array([128]).buffer);
this.valueBlock.toBER(sizeOnly, _writer);
_writer.write(new ArrayBuffer(2));
} else {
const valueBlockBuf = this.valueBlock.toBER(sizeOnly);
this.lenBlock.length = valueBlockBuf.byteLength;
const lenBlockBuf = this.lenBlock.toBER(sizeOnly);
_writer.write(lenBlockBuf);
_writer.write(valueBlockBuf);
}
if (!writer) {
return _writer.final();
}
return EMPTY_BUFFER;
}
toJSON() {
const object = {
...super.toJSON(),
idBlock: this.idBlock.toJSON(),
lenBlock: this.lenBlock.toJSON(),
valueBlock: this.valueBlock.toJSON(),
name: this.name,
optional: this.optional
};
if (this.primitiveSchema)
object.primitiveSchema = this.primitiveSchema.toJSON();
return object;
}
toString(encoding = "ascii") {
if (encoding === "ascii") {
return this.onAsciiEncoding();
}
return pvtsutils__namespace.Convert.ToHex(this.toBER());
}
onAsciiEncoding() {
const name = this.constructor.NAME;
const value = pvtsutils__namespace.Convert.ToHex(this.valueBlock.valueBeforeDecodeView);
return `${name} : ${value}`;
}
isEqual(other) {
if (this === other) {
return true;
}
if (!(other instanceof this.constructor)) {
return false;
}
const thisRaw = this.toBER();
const otherRaw = other.toBER();
return pvutils__namespace.isEqualBuffer(thisRaw, otherRaw);
}
};
BaseBlock.NAME = "BaseBlock";
function prepareIndefiniteForm(baseBlock) {
var _a2;
if (baseBlock instanceof typeStore.Constructed) {
for (const value of baseBlock.valueBlock.value) {
if (prepareIndefiniteForm(value)) {
baseBlock.lenBlock.isIndefiniteForm = true;
}
}
}
return !!((_a2 = baseBlock.lenBlock) === null || _a2 === void 0 ? void 0 : _a2.isIndefiniteForm);
}
var BaseStringBlock = class extends BaseBlock {
getValue() {
return this.valueBlock.value;
}
setValue(value) {
this.valueBlock.value = value;
}
constructor({ value = EMPTY_STRING, ...parameters } = {}, stringValueBlockType) {
super(parameters, stringValueBlockType);
if (value) {
this.fromString(value);
}
}
fromBER(inputBuffer, inputOffset, inputLength) {
const resultOffset = this.valueBlock.fromBER(inputBuffer, inputOffset, this.lenBlock.isIndefiniteForm ? inputLength : this.lenBlock.length);
if (resultOffset === -1) {
this.error = this.valueBlock.error;
return resultOffset;
}
this.fromBuffer(this.valueBlock.valueHexView);
if (!this.idBlock.error.length)
this.blockLength += this.idBlock.blockLength;
if (!this.lenBlock.error.length)
this.blockLength += this.lenBlock.blockLength;
if (!this.valueBlock.error.length)
this.blockLength += this.valueBlock.blockLength;
return resultOffset;
}
onAsciiEncoding() {
return `${this.constructor.NAME} : '${this.valueBlock.value}'`;
}
};
BaseStringBlock.NAME = "BaseStringBlock";
var LocalPrimitiveValueBlock = class extends HexBlock(ValueBlock) {
constructor({ isHexOnly = true, ...parameters } = {}) {
super(parameters);
this.isHexOnly = isHexOnly;
}
};
LocalPrimitiveValueBlock.NAME = "PrimitiveValueBlock";
var _a$w;
var Primitive = class extends BaseBlock {
constructor(parameters = {}) {
super(parameters, LocalPrimitiveValueBlock);
this.idBlock.isConstructed = false;
}
};
_a$w = Primitive;
(() => {
typeStore.Primitive = _a$w;
})();
Primitive.NAME = "PRIMITIVE";
function localChangeType(inputObject, newType) {
if (inputObject instanceof newType) {
return inputObject;
}
const newObject = new newType();
newObject.idBlock = inputObject.idBlock;
newObject.lenBlock = inputObject.lenBlock;
newObject.warnings = inputObject.warnings;
newObject.valueBeforeDecodeView = inputObject.valueBeforeDecodeView;
return newObject;
}
function localFromBER(inputBuffer, inputOffset = 0, inputLength = inputBuffer.length) {
const incomingOffset = inputOffset;
let returnObject = new BaseBlock({}, ValueBlock);
const baseBlock = new LocalBaseBlock();
if (!checkBufferParams(baseBlock, inputBuffer, inputOffset, inputLength)) {
returnObject.error = baseBlock.error;
return {
offset: -1,
result: returnObject
};
}
const intBuffer = inputBuffer.subarray(inputOffset, inputOffset + inputLength);
if (!intBuffer.length) {
returnObject.error = "Zero buffer length";
return {
offset: -1,
result: returnObject
};
}
let resultOffset = returnObject.idBlock.fromBER(inputBuffer, inputOffset, inputLength);
if (returnObject.idBlock.warnings.length) {
returnObject.warnings.concat(returnObject.idBlock.warnings);
}
if (resultOffset === -1) {
returnObject.error = returnObject.idBlock.error;
return {
offset: -1,
result: returnObject
};
}
inputOffset = resultOffset;
inputLength -= returnObject.idBlock.blockLength;
resultOffset = returnObject.lenBlock.fromBER(inputBuffer, inputOffset, inputLength);
if (returnObject.lenBlock.warnings.length) {
returnObject.warnings.concat(returnObject.lenBlock.warnings);
}
if (resultOffset === -1) {
returnObject.error = returnObject.lenBlock.error;
return {
offset: -1,
result: returnObject
};
}
inputOffset = resultOffset;
inputLength -= returnObject.lenBlock.blockLength;
if (!returnObject.idBlock.isConstructed && returnObject.lenBlock.isIndefiniteForm) {
returnObject.error = "Indefinite length form used for primitive encoding form";
return {
offset: -1,
result: returnObject
};
}
let newASN1Type = BaseBlock;
switch (returnObject.idBlock.tagClass) {
case 1:
if (returnObject.idBlock.tagNumber >= 37 && returnObject.idBlock.isHexOnly === false) {
returnObject.error = "UNIVERSAL 37 and upper tags are reserved by ASN.1 standard";
return {
offset: -1,
result: returnObject
};
}
switch (returnObject.idBlock.tagNumber) {
case 0:
if (returnObject.idBlock.isConstructed && returnObject.lenBlock.length > 0) {
returnObject.error = "Type [UNIVERSAL 0] is reserved";
return {
offset: -1,
result: returnObject
};
}
newASN1Type = typeStore.EndOfContent;
break;
case 1:
newASN1Type = typeStore.Boolean;
break;
case 2:
newASN1Type = typeStore.Integer;
break;
case 3:
newASN1Type = typeStore.BitString;
break;
case 4:
newASN1Type = typeStore.OctetString;
break;
case 5:
newASN1Type = typeStore.Null;
break;
case 6:
newASN1Type = typeStore.ObjectIdentifier;
break;
case 10:
newASN1Type = typeStore.Enumerated;
break;
case 12:
newASN1Type = typeStore.Utf8String;
break;
case 13:
newASN1Type = typeStore.RelativeObjectIdentifier;
break;
case 14:
newASN1Type = typeStore.TIME;
break;
case 15:
returnObject.error = "[UNIVERSAL 15] is reserved by ASN.1 standard";
return {
offset: -1,
result: returnObject
};
case 16:
newASN1Type = typeStore.Sequence;
break;
case 17:
newASN1Type = typeStore.Set;
break;
case 18:
newASN1Type = typeStore.NumericString;
break;
case 19:
newASN1Type = typeStore.PrintableString;
break;
case 20:
newASN1Type = typeStore.TeletexString;
break;
case 21:
newASN1Type = typeStore.VideotexString;
break;
case 22:
newASN1Type = typeStore.IA5String;
break;
case 23:
newASN1Type = typeStore.UTCTime;
break;
case 24:
newASN1Type = typeStore.GeneralizedTime;
break;
case 25:
newASN1Type = typeStore.GraphicString;
break;
case 26:
newASN1Type = typeStore.VisibleString;
break;
case 27:
newASN1Type = typeStore.GeneralString;
break;
case 28:
newASN1Type = typeStore.UniversalString;
break;
case 29:
newASN1Type = typeStore.CharacterString;
break;
case 30:
newASN1Type = typeStore.BmpString;
break;
case 31:
newASN1Type = typeStore.DATE;
break;
case 32:
newASN1Type = typeStore.TimeOfDay;
break;
case 33:
newASN1Type = typeStore.DateTime;
break;
case 34:
newASN1Type = typeStore.Duration;
break;
default: {
const newObject = returnObject.idBlock.isConstructed ? new typeStore.Constructed() : new typeStore.Primitive();
newObject.idBlock = returnObject.idBlock;
newObject.lenBlock = returnObject.lenBlock;
newObject.warnings = returnObject.warnings;
returnObject = newObject;
}
}
break;
case 2:
case 3:
case 4:
default: {
newASN1Type = returnObject.idBlock.isConstructed ? typeStore.Constructed : typeStore.Primitive;
}
}
returnObject = localChangeType(returnObject, newASN1Type);
resultOffset = returnObject.fromBER(inputBuffer, inputOffset, returnObject.lenBlock.isIndefiniteForm ? inputLength : returnObject.lenBlock.length);
returnObject.valueBeforeDecodeView = inputBuffer.subarray(incomingOffset, incomingOffset + returnObject.blockLength);
return {
offset: resultOffset,
result: returnObject
};
}
function fromBER(inputBuffer) {
if (!inputBuffer.byteLength) {
const result = new BaseBlock({}, ValueBlock);
result.error = "Input buffer has zero length";
return {
offset: -1,
result
};
}
return localFromBER(pvtsutils__namespace.BufferSourceConverter.toUint8Array(inputBuffer).slice(), 0, inputBuffer.byteLength);
}
function checkLen(indefiniteLength, length) {
if (indefiniteLength) {
return 1;
}
return length;
}
var LocalConstructedValueBlock = class extends ValueBlock {
constructor({ value = [], isIndefiniteForm = false, ...parameters } = {}) {
super(parameters);
this.value = value;
this.isIndefiniteForm = isIndefiniteForm;
}
fromBER(inputBuffer, inputOffset, inputLength) {
const view = pvtsutils__namespace.BufferSourceConverter.toUint8Array(inputBuffer);
if (!checkBufferParams(this, view, inputOffset, inputLength)) {
return -1;
}
this.valueBeforeDecodeView = view.subarray(inputOffset, inputOffset + inputLength);
if (this.valueBeforeDecodeView.length === 0) {
this.warnings.push("Zero buffer length");
return inputOffset;
}
let currentOffset = inputOffset;
while (checkLen(this.isIndefiniteForm, inputLength) > 0) {
const returnObject = localFromBER(view, currentOffset, inputLength);
if (returnObject.offset === -1) {
this.error = returnObject.result.error;
this.warnings.concat(returnObject.result.warnings);
return -1;
}
currentOffset = returnObject.offset;
this.blockLength += returnObject.result.blockLength;
inputLength -= returnObject.result.blockLength;
this.value.push(returnObject.result);
if (this.isIndefiniteForm && returnObject.result.constructor.NAME === END_OF_CONTENT_NAME) {
break;
}
}
if (this.isIndefiniteForm) {
if (this.value[this.value.length - 1].constructor.NAME === END_OF_CONTENT_NAME) {
this.value.pop();
} else {
this.warnings.push("No EndOfContent block encoded");
}
}
return currentOffset;
}
toBER(sizeOnly, writer) {
const _writer = writer || new ViewWriter();
for (let i = 0; i < this.value.length; i++) {
this.value[i].toBER(sizeOnly, _writer);
}
if (!writer) {
return _writer.final();
}
return EMPTY_BUFFER;
}
toJSON() {
const object = {
...super.toJSON(),
isIndefiniteForm: this.isIndefiniteForm,
value: []
};
for (const value of this.value) {
object.value.push(value.toJSON());
}
return object;
}
};
LocalConstructedValueBlock.NAME = "ConstructedValueBlock";
var _a$v;
var Constructed = class extends BaseBlock {
constructor(parameters = {}) {
super(parameters, LocalConstructedValueBlock);
this.idBlock.isConstructed = true;
}
fromBER(inputBuffer, inputOffset, inputLength) {
this.valueBlock.isIndefiniteForm = this.lenBlock.isIndefiniteForm;
const resultOffset = this.valueBlock.fromBER(inputBuffer, inputOffset, this.lenBlock.isIndefiniteForm ? inputLength : this.lenBlock.length);
if (resultOffset === -1) {
this.error = this.valueBlock.error;
return resultOffset;
}
if (!this.idBlock.error.length)
this.blockLength += this.idBlock.blockLength;
if (!this.lenBlock.error.length)
this.blockLength += this.lenBlock.blockLength;
if (!this.valueBlock.error.length)
this.blockLength += this.valueBlock.blockLength;
return resultOffset;
}
onAsciiEncoding() {
const values = [];
for (const value of this.valueBlock.value) {
values.push(value.toString("ascii").split("\n").map((o) => ` ${o}`).join("\n"));
}
const blockName = this.idBlock.tagClass === 3 ? `[${this.idBlock.tagNumber}]` : this.constructor.NAME;
return values.length ? `${blockName} :
${values.join("\n")}` : `${blockName} :`;
}
};
_a$v = Constructed;
(() => {
typeStore.Constructed = _a$v;
})();
Constructed.NAME = "CONSTRUCTED";
var LocalEndOfContentValueBlock = class extends ValueBlock {
fromBER(inputBuffer, inputOffset, _inputLength) {
return inputOffset;
}
toBER(_sizeOnly) {
return EMPTY_BUFFER;
}
};
LocalEndOfContentValueBlock.override = "EndOfContentValueBlock";
var _a$u;
var EndOfContent = class extends BaseBlock {
constructor(parameters = {}) {
super(parameters, LocalEndOfContentValueBlock);
this.idBlock.tagClass = 1;
this.idBlock.tagNumber = 0;
}
};
_a$u = EndOfContent;
(() => {
typeStore.EndOfContent = _a$u;
})();
EndOfContent.NAME = END_OF_CONTENT_NAME;
var _a$t;
var Null = class extends BaseBlock {
constructor(parameters = {}) {
super(parameters, ValueBlock);
this.idBlock.tagClass = 1;
this.idBlock.tagNumber = 5;
}
fromBER(inputBuffer, inputOffset, inputLength) {
if (this.lenBlock.length > 0)
this.warnings.push("Non-zero length of value block for Null type");
if (!this.idBlock.error.length)
this.blockLength += this.idBlock.blockLength;
if (!this.lenBlock.error.length)
this.blockLength += this.lenBlock.blockLength;
this.blockLength += inputLength;
if (inputOffset + inputLength > inputBuffer.byteLength) {
this.error = "End of input reached before message was fully decoded (inconsistent offset and length values)";
return -1;
}
return inputOffset + inputLength;
}
toBER(sizeOnly, writer) {
const retBuf = new ArrayBuffer(2);
if (!sizeOnly) {
const retView = new Uint8Array(retBuf);
retView[0] = 5;
retView[1] = 0;
}
if (writer) {
writer.write(retBuf);
}
return retBuf;
}
onAsciiEncoding() {
return `${this.constructor.NAME}`;
}
};
_a$t = Null;
(() => {
typeStore.Null = _a$t;
})();
Null.NAME = "NULL";
var LocalBooleanValueBlock = class extends HexBlock(ValueBlock) {
get value() {
for (const octet of this.valueHexView) {
if (octet > 0) {
return true;
}
}
return false;
}
set value(value) {
this.valueHexView[0] = value ? 255 : 0;
}
constructor({ value, ...parameters } = {}) {
super(parameters);
if (parameters.valueHex) {
this.valueHexView = pvtsutils__namespace.BufferSourceConverter.toUint8Array(parameters.valueHex);
} else {
this.valueHexView = new Uint8Array(1);
}
if (value) {
this.value = value;
}
}
fromBER(inputBuffer, inputOffset, inputLength) {
const inputView = pvtsutils__namespace.BufferSourceConverter.toUint8Array(inputBuffer);
if (!checkBufferParams(this, inputView, inputOffset, inputLength)) {
return -1;
}
this.valueHexView = inputView.subarray(inputOffset, inputOffset + inputLength);
if (inputLength > 1)
this.warnings.push("Boolean value encoded in more then 1 octet");
this.isHexOnly = true;
pvutils__namespace.utilDecodeTC.call(this);
this.blockLength = inputLength;
return inputOffset + inputLength;
}
toBER() {
return this.valueHexView.slice();
}
toJSON() {
return {
...super.toJSON(),
value: this.value
};
}
};
LocalBooleanValueBlock.NAME = "BooleanValueBlock";
var _a$s;
var Boolean = class extends BaseBlock {
getValue() {
return this.valueBlock.value;
}
setValue(value) {
this.valueBlock.value = value;
}
constructor(parameters = {}) {
super(parameters, LocalBooleanValueBlock);
this.idBlock.tagClass = 1;
this.idBlock.tagNumber = 1;
}
onAsciiEncoding() {
return `${this.constructor.NAME} : ${this.getValue}`;
}
};
_a$s = Boolean;
(() => {
typeStore.Boolean = _a$s;
})();
Boolean.NAME = "BOOLEAN";
var LocalOctetStringValueBlock = class extends HexBlock(LocalConstructedValueBlock) {
constructor({ isConstructed = false, ...parameters } = {}) {
super(parameters);
this.isConstructed = isConstructed;
}
fromBER(inputBuffer, inputOffset, inputLength) {
let resultOffset = 0;
if (this.isConstructed) {
this.isHexOnly = false;
resultOffset = LocalConstructedValueBlock.prototype.fromBER.call(this, inputBuffer, inputOffset, inputLength);
if (resultOffset === -1)
return resultOffset;
for (let i = 0; i < this.value.length; i++) {
const currentBlockName = this.value[i].constructor.NAME;
if (currentBlockName === END_OF_CONTENT_NAME) {
if (this.isIndefiniteForm)
break;
else {
this.error = "EndOfContent is unexpected, OCTET STRING may consists of OCTET STRINGs only";
return -1;
}
}
if (currentBlockName !== OCTET_STRING_NAME) {
this.error = "OCTET STRING may consists of OCTET STRINGs only";
return -1;
}
}
} else {
this.isHexOnly = true;
resultOffset = super.fromBER(inputBuffer, inputOffset, inputLength);
this.blockLength = inputLength;
}
return resultOffset;
}
toBER(sizeOnly, writer) {
if (this.isConstructed)
return LocalConstructedValueBlock.prototype.toBER.call(this, sizeOnly, writer);
return sizeOnly ? new ArrayBuffer(this.valueHexView.byteLength) : this.valueHexView.slice().buffer;
}
toJSON() {
return {
...super.toJSON(),
isConstructed: this.isConstructed
};
}
};
LocalOctetStringValueBlock.NAME = "OctetStringValueBlock";
var _a$r;
var OctetString2 = class extends BaseBlock {
constructor({ idBlock = {}, lenBlock = {}, ...parameters } = {}) {
var _b, _c;
(_b = parameters.isConstructed) !== null && _b !== void 0 ? _b : parameters.isConstructed = !!((_c = parameters.value) === null || _c === void 0 ? void 0 : _c.length);
super({
idBlock: {
isConstructed: parameters.isConstructed,
...idBlock
},
lenBlock: {
...lenBlock,
isIndefiniteForm: !!parameters.isIndefiniteForm
},
...parameters
}, LocalOctetStringValueBlock);
this.idBlock.tagClass = 1;
this.idBlock.tagNumber = 4;
}
fromBER(inputBuffer, inputOffset, inputLength) {
this.valueBlock.isConstructed = this.idBlock.isConstructed;
this.valueBlock.isIndefiniteForm = this.lenBlock.isIndefiniteForm;
if (inputLength === 0) {
if (this.idBlock.error.length === 0)
this.blockLength += this.idBlock.blockLength;
if (this.lenBlock.error.length === 0)
this.blockLength += this.lenBlock.blockLength;
return inputOffset;
}
if (!this.valueBlock.isConstructed) {
const view = inputBuffer instanceof ArrayBuffer ? new Uint8Array(inputBuffer) : inputBuffer;
const buf = view.subarray(inputOffset, inputOffset + inputLength);
try {
if (buf.byteLength) {
const asn = localFromBER(buf, 0, buf.byteLength);
if (asn.offset !== -1 && asn.offset === inputLength) {
this.valueBlock.value = [asn.result];
}
}
} catch {
}
}
return super.fromBER(inputBuffer, inputOffset, inputLength);
}
onAsciiEncoding() {
if (this.valueBlock.isConstructed || this.valueBlock.value && this.valueBlock.value.length) {
return Constructed.prototype.onAsciiEncoding.call(this);
}
const name = this.constructor.NAME;
const value = pvtsutils__namespace.Convert.ToHex(this.valueBlock.valueHexView);
return `${name} : ${value}`;
}
getValue() {
if (!this.idBlock.isConstructed) {
return this.valueBlock.valueHexView.slice().buffer;
}
const array = [];
for (const content of this.valueBlock.value) {
if (content instanceof _a$r) {
array.push(content.valueBlock.valueHexView);
}
}
return pvtsutils__namespace.BufferSourceConverter.concat(array);
}
};
_a$r = OctetString2;
(() => {
typeStore.OctetString = _a$r;
})();
OctetString2.NAME = OCTET_STRING_NAME;
var LocalBitStringValueBlock = class extends HexBlock(LocalConstructedValueBlock) {
constructor({ unusedBits = 0, isConstructed = false, ...parameters } = {}) {
super(parameters);
this.unusedBits = unusedBits;
this.isConstructed = isConstructed;
this.blockLength = this.valueHexView.byteLength;
}
fromBER(inputBuffer, inputOffset, inputLength) {
if (!inputLength) {
return inputOffset;
}
let resultOffset = -1;
if (this.isConstructed) {
resultOffset = LocalConstructedValueBlock.prototype.fromBER.call(this, inputBuffer, inputOffset, inputLength);
if (resultOffset === -1)
return resultOffset;
for (const value of this.value) {
const currentBlockName = value.constructor.NAME;
if (currentBlockName === END_OF_CONTENT_NAME) {
if (this.isIndefiniteForm)
break;
else {
this.error = "EndOfContent is unexpected, BIT STRING may consists of BIT STRINGs only";
return -1;
}
}
if (currentBlockName !== BIT_STRING_NAME) {
this.error = "BIT STRING may consists of BIT STRINGs only";
return -1;
}
const valueBlock = value.valueBlock;
if (this.unusedBits > 0 && valueBlock.unusedBits > 0) {
this.error = 'Using of "unused bits" inside constructive BIT STRING allowed for least one only';
return -1;
}
this.unusedBits = valueBlock.unusedBits;
}
return resultOffset;
}
const inputView = pvtsutils__namespace.BufferSourceConverter.toUint8Array(inputBuffer);
if (!checkBufferParams(this, inputView, inputOffset, inputLength)) {
return -1;
}
const intBuffer = inputView.subarray(inputOffset, inputOffset + inputLength);
this.unusedBits = intBuffer[0];
if (this.unusedBits > 7) {
this.error = "Unused bits for BitString must be in range 0-7";
return -1;
}
if (!this.unusedBits) {
const buf = intBuffer.subarray(1);
try {
if (buf.byteLength) {
const asn = localFromBER(buf, 0, buf.byteLength);
if (asn.offset !== -1 && asn.offset === inputLength - 1) {
this.value = [asn.result];
}
}
} catch {
}
}
this.valueHexView = intBuffer.subarray(1);
this.blockLength = intBuffer.length;
return inputOffset + inputLength;
}
toBER(sizeOnly, writer) {
if (this.isConstructed) {
return LocalConstructedValueBlock.prototype.toBER.call(this, sizeOnly, writer);
}
if (sizeOnly) {
return new ArrayBuffer(this.valueHexView.byteLength + 1);
}
if (!this.valueHexView.byteLength) {
return EMPTY_BUFFER;
}
const retView = new Uint8Array(this.valueHexView.length + 1);
retView[0] = this.unusedBits;
retView.set(this.valueHexView, 1);
return retView.buffer;
}
toJSON() {
return {
...super.toJSON(),
unusedBits: this.unusedBits,
isConstructed: this.isConstructed
};
}
};
LocalBitStringValueBlock.NAME = "BitStringValueBlock";
var _a$q;
var BitString = class extends BaseBlock {
constructor({ idBlock = {}, lenBlock = {}, ...parameters } = {}) {
var _b, _c;
(_b = parameters.isConstructed) !== null && _b !== void 0 ? _b : parameters.isConstructed = !!((_c = parameters.value) === null || _c === void 0 ? void 0 : _c.length);
super({
idBlock: {
isConstructed: parameters.isConstructed,
...idBlock
},
lenBlock: {
...lenBlock,
isIndefiniteForm: !!parameters.isIndefiniteForm
},
...parameters
}, LocalBitStringValueBlock);
this.idBlock.tagClass = 1;
this.idBlock.tagNumber = 3;
}
fromBER(inputBuffer, inputOffset, inputLength) {
this.valueBlock.isConstructed = this.idBlock.isConstructed;
this.valueBlock.isIndefiniteForm = this.lenBlock.isIndefiniteForm;
return super.fromBER(inputBuffer, inputOffset, inputLength);
}
onAsciiEncoding() {
if (this.valueBlock.isConstructed || this.valueBlock.value && this.valueBlock.value.length) {
return Constructed.prototype.onAsciiEncoding.call(this);
} else {
const bits = [];
const valueHex = this.valueBlock.valueHexView;
for (const byte of valueHex) {
bits.push(byte.toString(2).padStart(8, "0"));
}
const bitsStr = bits.join("");
const name = this.constructor.NAME;
const value = bitsStr.substring(0, bitsStr.length - this.valueBlock.unusedBits);
return `${name} : ${value}`;
}
}
};
_a$q = BitString;
(() => {
typeStore.BitString = _a$q;
})();
BitString.NAME = BIT_STRING_NAME;
var _a$p;
function viewAdd(first, second) {
const c = new Uint8Array([0]);
const firstView = new Uint8Array(first);
const secondView = new Uint8Array(second);
let firstViewCopy = firstView.slice(0);
const firstViewCopyLength = firstViewCopy.length - 1;
const secondViewCopy = secondView.slice(0);
const secondViewCopyLength = secondViewCopy.length - 1;
let value = 0;
const max = secondViewCopyLength < firstViewCopyLength ? firstViewCopyLength : secondViewCopyLength;
let counter = 0;
for (let i = max; i >= 0; i--, counter++) {
switch (true) {
case counter < secondViewCopy.length:
value = firstViewCopy[firstViewCopyLength - counter] + secondViewCopy[secondViewCopyLength - counter] + c[0];
break;
default:
value = firstViewCopy[firstViewCopyLength - counter] + c[0];
}
c[0] = value / 10;
switch (true) {
case counter >= firstViewCopy.length:
firstViewCopy = pvutils__namespace.utilConcatView(new Uint8Array([value % 10]), firstViewCopy);
break;
default:
firstViewCopy[firstViewCopyLength - counter] = value % 10;
}
}
if (c[0] > 0)
firstViewCopy = pvutils__namespace.utilConcatView(c, firstViewCopy);
return firstViewCopy;
}
function power2(n) {
if (n >= powers2.length) {
for (let p = powers2.length; p <= n; p++) {
const c = new Uint8Array([0]);
let digits = powers2[p - 1].slice(0);
for (let i = digits.length - 1; i >= 0; i--) {
const newValue = new Uint8Array([(digits[i] << 1) + c[0]]);
c[0] = newValue[0] / 10;
digits[i] = newValue[0] % 10;
}
if (c[0] > 0)
digits = pvutils__namespace.utilConcatView(c, digits);
powers2.push(digits);
}
}
return powers2[n];
}
function viewSub(first, second) {
let b = 0;
const firstView = new Uint8Array(first);
const secondView = new Uint8Array(second);
const firstViewCopy = firstView.slice(0);
const firstViewCopyLength = firstViewCopy.length - 1;
const secondViewCopy = secondView.slice(0);
const secondViewCopyLength = secondViewCopy.length - 1;
let value;
let counter = 0;
for (let i = secondViewCopyLength; i >= 0; i--, counter++) {
value = firstViewCopy[firstViewCopyLength - counter] - secondViewCopy[secondViewCopyLength - counter] - b;
switch (true) {
case value < 0:
b = 1;
firstViewCopy[firstViewCopyLength - counter] = value + 10;
break;
default:
b = 0;
firstViewCopy[firstViewCopyLength - counter] = value;
}
}
if (b > 0) {
for (let i = firstViewCopyLength - secondViewCopyLength + 1; i >= 0; i--, counter++) {
value = firstViewCopy[firstViewCopyLength - counter] - b;
if (value < 0) {
b = 1;
firstViewCopy[firstViewCopyLength - counter] = value + 10;
} else {
b = 0;
firstViewCopy[firstViewCopyLength - counter] = value;
break;
}
}
}
return firstViewCopy.slice();
}
var LocalIntegerValueBlock = class extends HexBlock(ValueBlock) {
setValueHex() {
if (this.valueHexView.length >= 4) {
this.warnings.push("Too big Integer for decoding, hex only");
this.isHexOnly = true;
this._valueDec = 0;
} else {
this.isHexOnly = false;
if (this.valueHexView.length > 0) {
this._valueDec = pvutils__namespace.utilDecodeTC.call(this);
}
}
}
constructor({ value, ...parameters } = {}) {
super(parameters);
this._valueDec = 0;
if (parameters.valueHex) {
this.setValueHex();
}
if (value !== void 0) {
this.valueDec = value;
}
}
set valueDec(v) {
this._valueDec = v;
this.isHexOnly = false;
this.valueHexView = new Uint8Array(pvutils__namespace.utilEncodeTC(v));
}
get valueDec() {
return this._valueDec;
}
fromDER(inputBuffer, inputOffset, inputLength, expectedLength = 0) {
const offset = this.fromBER(inputBuffer, inputOffset, inputLength);
if (offset === -1)
return offset;
const view = this.valueHexView;
if (view[0] === 0 && (view[1] & 128) !== 0) {
this.valueHexView = view.subarray(1);
} else {
if (expectedLength !== 0) {
if (view.length < expectedLength) {
if (expectedLength - view.length > 1)
expectedLength = view.length + 1;
this.valueHexView = view.subarray(expectedLength - view.length);
}
}
}
return offset;
}
toDER(sizeOnly = false) {
const view = this.valueHexView;
switch (true) {
case (view[0] & 128) !== 0:
{
const updatedView = new Uint8Array(this.valueHexView.length + 1);
updatedView[0] = 0;
updatedView.set(view, 1);
this.valueHexView = updatedView;
}
break;
case (view[0] === 0 && (view[1] & 128) === 0):
{
this.valueHexView = this.valueHexView.subarray(1);
}
break;
}
return this.toBER(sizeOnly);
}
fromBER(inputBuffer, inputOffset, inputLength) {
const resultOffset = super.fromBER(inputBuffer, inputOffset, inputLength);
if (resultOffset === -1) {
return resultOffset;
}
this.setValueHex();
return resultOffset;
}
toBER(sizeOnly) {
return sizeOnly ? new ArrayBuffer(this.valueHexView.length) : this.valueHexView.slice().buffer;
}
toJSON() {
return {
...super.toJSON(),
valueDec: this.valueDec
};
}
toString() {
const firstBit = this.valueHexView.length * 8 - 1;
let digits = new Uint8Array(this.valueHexView.length * 8 / 3);
let bitNumber = 0;
let currentByte;
const asn1View = this.valueHexView;
let result = "";
let flag = false;
for (let byteNumber = asn1View.byteLength - 1; byteNumber >= 0; byteNumber--) {
currentByte = asn1View[byteNumber];
for (let i = 0; i < 8; i++) {
if ((currentByte & 1) === 1) {
switch (bitNumber) {
case firstBit:
digits = viewSub(power2(bitNumber), digits);
result = "-";
break;
default:
digits = viewAdd(digits, power2(bitNumber));
}
}
bitNumber++;
currentByte >>= 1;
}
}
for (let i = 0; i < digits.length; i++) {
if (digits[i])
flag = true;
if (flag)
result += digitsString.charAt(digits[i]);
}
if (flag === false)
result += digitsString.charAt(0);
return result;
}
};
_a$p = LocalIntegerValueBlock;
LocalIntegerValueBlock.NAME = "IntegerValueBlock";
(() => {
Object.defineProperty(_a$p.prototype, "valueHex", {
set: function(v) {
this.valueHexView = new Uint8Array(v);
this.setValueHex();
},
get: function() {
return this.valueHexView.slice().buffer;
}
});
})();
var _a$o;
var Integer2 = class extends BaseBlock {
constructor(parameters = {}) {
super(parameters, LocalIntegerValueBlock);
this.idBlock.tagClass = 1;
this.idBlock.tagNumber = 2;
}
toBigInt() {
assertBigInt();
return BigInt(this.valueBlock.toString());
}
static fromBigInt(value) {
assertBigInt();
const bigIntValue = BigInt(value);
const writer = new ViewWriter();
const hex = bigIntValue.toString(16).replace(/^-/, "");
const view = new Uint8Array(pvtsutils__namespace.Convert.FromHex(hex));
if (bigIntValue < 0) {
const first = new Uint8Array(view.length + (view[0] & 128 ? 1 : 0));
first[0] |= 128;
const firstInt = BigInt(`0x${pvtsutils__namespace.Convert.ToHex(first)}`);
const secondInt = firstInt + bigIntValue;
const second = pvtsutils__namespace.BufferSourceConverter.toUint8Array(pvtsutils__namespace.Convert.FromHex(secondInt.toString(16)));
second[0] |= 128;
writer.write(second);
} else {
if (view[0] & 128) {
writer.write(new Uint8Array([0]));
}
writer.write(view);
}
const res = new _a$o({ valueHex: writer.final() });
return res;
}
convertToDER() {
const integer = new _a$o({ valueHex: this.valueBlock.valueHexView });
integer.valueBlock.toDER();
return integer;
}
convertFromDER() {
return new _a$o({
valueHex: this.valueBlock.valueHexView[0] === 0 ? this.valueBlock.valueHexView.subarray(1) : this.valueBlock.valueHexView
});
}
onAsciiEncoding() {
return `${this.constructor.NAME} : ${this.valueBlock.toString()}`;
}
};
_a$o = Integer2;
(() => {
typeStore.Integer = _a$o;
})();
Integer2.NAME = "INTEGER";
var _a$n;
var Enumerated = class extends Integer2 {
constructor(parameters = {}) {
super(parameters);
this.idBlock.tagClass = 1;
this.idBlock.tagNumber = 10;
}
};
_a$n = Enumerated;
(() => {
typeStore.Enumerated = _a$n;
})();
Enumerated.NAME = "ENUMERATED";
var LocalSidValueBlock = class extends HexBlock(ValueBlock) {
constructor({ valueDec = -1, isFirstSid = false, ...parameters } = {}) {
super(parameters);
this.valueDec = valueDec;
this.isFirstSid = isFirstSid;
}
fromBER(inputBuffer, inputOffset, inputLength) {
if (!inputLength) {
return inputOffset;
}
const inputView = pvtsutils__namespace.BufferSourceConverter.toUint8Array(inputBuffer);
if (!checkBufferParams(this, inputView, inputOffset, inputLength)) {
return -1;
}
const intBuffer = inputView.subarray(inputOffset, inputOffset + inputLength);
this.valueHexView = new Uint8Array(inputLength);
for (let i = 0; i < inputLength; i++) {
this.valueHexView[i] = intBuffer[i] & 127;
this.blockLength++;
if ((intBuffer[i] & 128) === 0)
break;
}
const tempView = new Uint8Array(this.blockLength);
for (let i = 0; i < this.blockLength; i++) {
tempView[i] = this.valueHexView[i];
}
this.valueHexView = tempView;
if ((intBuffer[this.blockLength - 1] & 128) !== 0) {
this.error = "End of input reached before message was fully decoded";
return -1;
}
if (this.valueHexView[0] === 0)
this.warnings.push("Needlessly long format of SID encoding");
if (this.blockLength <= 8)
this.valueDec = pvutils__namespace.utilFromBase(this.valueHexView, 7);
else {
this.isHexOnly = true;
this.warnings.push("Too big SID for decoding, hex only");
}
return inputOffset + this.blockLength;
}
set valueBigInt(value) {
assertBigInt();
let bits = BigInt(value).toString(2);
while (bits.length % 7) {
bits = "0" + bits;
}
const bytes = new Uint8Array(bits.length / 7);
for (let i = 0; i < bytes.length; i++) {
bytes[i] = parseInt(bits.slice(i * 7, i * 7 + 7), 2) + (i + 1 < bytes.length ? 128 : 0);
}
this.fromBER(bytes.buffer, 0, bytes.length);
}
toBER(sizeOnly) {
if (this.isHexOnly) {
if (sizeOnly)
return new ArrayBuffer(this.valueHexView.byteLength);
const curView = this.valueHexView;
const retView2 = new Uint8Array(this.blockLength);
for (let i = 0; i < this.blockLength - 1; i++)
retView2[i] = curView[i] | 128;
retView2[this.blockLength - 1] = curView[this.blockLength - 1];
return retView2.buffer;
}
const encodedBuf = pvutils__namespace.utilToBase(this.valueDec, 7);
if (encodedBuf.byteLength === 0) {
this.error = "Error during encoding SID value";
return EMPTY_BUFFER;
}
const retView = new Uint8Array(encodedBuf.byteLength);
if (!sizeOnly) {
const encodedView = new Uint8Array(encodedBuf);
const len = encodedBuf.byteLength - 1;
for (let i = 0; i < len; i++)
retView[i] = encodedView[i] | 128;
retView[len] = encodedView[len];
}
return retView;
}
toString() {
let result = "";
if (this.isHexOnly)
result = pvtsutils__namespace.Convert.ToHex(this.valueHexView);
else {
if (this.isFirstSid) {
let sidValue = this.valueDec;
if (this.valueDec <= 39)
result = "0.";
else {
if (this.valueDec <= 79) {
result = "1.";
sidValue -= 40;
} else {
result = "2.";
sidValue -= 80;
}
}
result += sidValue.toString();
} else
result = this.valueDec.toString();
}
return result;
}
toJSON() {
return {
...super.toJSON(),
valueDec: this.valueDec,
isFirstSid: this.isFirstSid
};
}
};
LocalSidValueBlock.NAME = "sidBlock";
var LocalObjectIdentifierValueBlock = class extends ValueBlock {
constructor({ value = EMPTY_STRING, ...parameters } = {}) {
super(parameters);
this.value = [];
if (value) {
this.fromString(value);
}
}
fromBER(inputBuffer, inputOffset, inputLength) {
let resultOffset = inputOffset;
while (inputLength > 0) {
const sidBlock = new LocalSidValueBlock();
resultOffset = sidBlock.fromBER(inputBuffer, resultOffset, inputLength);
if (resultOffset === -1) {
this.blockLength = 0;
this.error = sidBlock.error;
return resultOffset;
}
if (this.value.length === 0)
sidBlock.isFirstSid = true;
this.blockLength += sidBlock.blockLength;
inputLength -= sidBlock.blockLength;
this.value.push(sidBlock);
}
return resultOffset;
}
toBER(sizeOnly) {
const retBuffers = [];
for (let i = 0; i < this.value.length; i++) {
const valueBuf = this.value[i].toBER(sizeOnly);
if (valueBuf.byteLength === 0) {
this.error = this.value[i].error;
return EMPTY_BUFFER;
}
retBuffers.push(valueBuf);
}
return concat(retBuffers);
}
fromString(string) {
this.value = [];
let pos1 = 0;
let pos2 = 0;
let sid = "";
let flag = false;
do {
pos2 = string.indexOf(".", pos1);
if (pos2 === -1)
sid = string.substring(pos1);
else
sid = string.substring(pos1, pos2);
pos1 = pos2 + 1;
if (flag) {
const sidBlock = this.value[0];
let plus = 0;
switch (sidBlock.valueDec) {
case 0:
break;
case 1:
plus = 40;
break;
case 2:
plus = 80;
break;
default:
this.value = [];
return;
}
const parsedSID = parseInt(sid, 10);
if (isNaN(parsedSID))
return;
sidBlock.valueDec = parsedSID + plus;
flag = false;
} else {
const sidBlock = new LocalSidValueBlock();
if (sid > Number.MAX_SAFE_INTEGER) {
assertBigInt();
const sidValue = BigInt(sid);
sidBlock.valueBigInt = sidValue;
} else {
sidBlock.valueDec = parseInt(sid, 10);
if (isNaN(sidBlock.valueDec))
return;
}
if (!this.value.length) {
sidBlock.isFirstSid = true;
flag = true;
}
this.value.push(sidBlock);
}
} while (pos2 !== -1);
}
toString() {
let result = "";
let isHexOnly = false;
for (let i = 0; i < this.value.length; i++) {
isHexOnly = this.value[i].isHexOnly;
let sidStr = this.value[i].toString();
if (i !== 0)
result = `${result}.`;
if (isHexOnly) {
sidStr = `{${sidStr}}`;
if (this.value[i].isFirstSid)
result = `2.{${sidStr} - 80}`;
else
result += sidStr;
} else
result += sidStr;
}
return result;
}
toJSON() {
const object = {
...super.toJSON(),
value: this.toString(),
sidArray: []
};
for (let i = 0; i < this.value.length; i++) {
object.sidArray.push(this.value[i].toJSON());
}
return object;
}
};
LocalObjectIdentifierValueBlock.NAME = "ObjectIdentifierValueBlock";
var _a$m;
var ObjectIdentifier = class extends BaseBlock {
getValue() {
return this.valueBlock.toString();
}
setValue(value) {
this.valueBlock.fromString(value);
}
constructor(parameters = {}) {
super(parameters, LocalObjectIdentifierValueBlock);
this.idBlock.tagClass = 1;
this.idBlock.tagNumber = 6;
}
onAsciiEncoding() {
return `${this.constructor.NAME} : ${this.valueBlock.toString() || "empty"}`;
}
toJSON() {
return {
...super.toJSON(),
value: this.getValue()
};
}
};
_a$m = ObjectIdentifier;
(() => {
typeStore.ObjectIdentifier = _a$m;
})();
ObjectIdentifier.NAME = "OBJECT IDENTIFIER";
var LocalRelativeSidValueBlock = class extends HexBlock(LocalBaseBlock) {
constructor({ valueDec = 0, ...parameters } = {}) {
super(parameters);
this.valueDec = valueDec;
}
fromBER(inputBuffer, inputOffset, inputLength) {
if (inputLength === 0)
return inputOffset;
const inputView = pvtsutils__namespace.BufferSourceConverter.toUint8Array(inputBuffer);
if (!checkBufferParams(this, inputView, inputOffset, inputLength))
return -1;
const intBuffer = inputView.subarray(inputOffset, inputOffset + inputLength);
this.valueHexView = new Uint8Array(inputLength);
for (let i = 0; i < inputLength; i++) {
this.valueHexView[i] = intBuffer[i] & 127;
this.blockLength++;
if ((intBuffer[i] & 128) === 0)
break;
}
const tempView = new Uint8Array(this.blockLength);
for (let i = 0; i < this.blockLength; i++)
tempView[i] = this.valueHexView[i];
this.valueHexView = tempView;
if ((intBuffer[this.blockLength - 1] & 128) !== 0) {
this.error = "End of input reached before message was fully decoded";
return -1;
}
if (this.valueHexView[0] === 0)
this.warnings.push("Needlessly long format of SID encoding");
if (this.blockLength <= 8)
this.valueDec = pvutils__namespace.utilFromBase(this.valueHexView, 7);
else {
this.isHexOnly = true;
this.warnings.push("Too big SID for decoding, hex only");
}
return inputOffset + this.blockLength;
}
toBER(sizeOnly) {
if (this.isHexOnly) {
if (sizeOnly)
return new ArrayBuffer(this.valueHexView.byteLength);
const curView = this.valueHexView;
const retView2 = new Uint8Array(this.blockLength);
for (let i = 0; i < this.blockLength - 1; i++)
retView2[i] = curView[i] | 128;
retView2[this.blockLength - 1] = curView[this.blockLength - 1];
return retView2.buffer;
}
const encodedBuf = pvutils__namespace.utilToBase(this.valueDec, 7);
if (encodedBuf.byteLength === 0) {
this.error = "Error during encoding SID value";
return EMPTY_BUFFER;
}
const retView = new Uint8Array(encodedBuf.byteLength);
if (!sizeOnly) {
const encodedView = new Uint8Array(encodedBuf);
const len = encodedBuf.byteLength - 1;
for (let i = 0; i < len; i++)
retView[i] = encodedView[i] | 128;
retView[len] = encodedView[len];
}
return retView.buffer;
}
toString() {
let result = "";
if (this.isHexOnly)
result = pvtsutils__namespace.Convert.ToHex(this.valueHexView);
else {
result = this.valueDec.toString();
}
return result;
}
toJSON() {
return {
...super.toJSON(),
valueDec: this.valueDec
};
}
};
LocalRelativeSidValueBlock.NAME = "relativeSidBlock";
var LocalRelativeObjectIdentifierValueBlock = class extends ValueBlock {
constructor({ value = EMPTY_STRING, ...parameters } = {}) {
super(parameters);
this.value = [];
if (value) {
this.fromString(value);
}
}
fromBER(inputBuffer, inputOffset, inputLength) {
let resultOffset = inputOffset;
while (inputLength > 0) {
const sidBlock = new LocalRelativeSidValueBlock();
resultOffset = sidBlock.fromBER(inputBuffer, resultOffset, inputLength);
if (resultOffset === -1) {
this.blockLength = 0;
this.error = sidBlock.error;
return resultOffset;
}
this.blockLength += sidBlock.blockLength;
inputLength -= sidBlock.blockLength;
this.value.push(sidBlock);
}
return resultOffset;
}
toBER(sizeOnly, _writer) {
const retBuffers = [];
for (let i = 0; i < this.value.length; i++) {
const valueBuf = this.value[i].toBER(sizeOnly);
if (valueBuf.byteLength === 0) {
this.error = this.value[i].error;
return EMPTY_BUFFER;
}
retBuffers.push(valueBuf);
}
return concat(retBuffers);
}
fromString(string) {
this.value = [];
let pos1 = 0;
let pos2 = 0;
let sid = "";
do {
pos2 = string.indexOf(".", pos1);
if (pos2 === -1)
sid = string.substring(pos1);
else
sid = string.substring(pos1, pos2);
pos1 = pos2 + 1;
const sidBlock = new LocalRelativeSidValueBlock();
sidBlock.valueDec = parseInt(sid, 10);
if (isNaN(sidBlock.valueDec))
return true;
this.value.push(sidBlock);
} while (pos2 !== -1);
return true;
}
toString() {
let result = "";
let isHexOnly = false;
for (let i = 0; i < this.value.length; i++) {
isHexOnly = this.value[i].isHexOnly;
let sidStr = this.value[i].toString();
if (i !== 0)
result = `${result}.`;
if (isHexOnly) {
sidStr = `{${sidStr}}`;
result += sidStr;
} else
result += sidStr;
}
return result;
}
toJSON() {
const object = {
...super.toJSON(),
value: this.toString(),
sidArray: []
};
for (let i = 0; i < this.value.length; i++)
object.sidArray.push(this.value[i].toJSON());
return object;
}
};
LocalRelativeObjectIdentifierValueBlock.NAME = "RelativeObjectIdentifierValueBlock";
var _a$l;
var RelativeObjectIdentifier = class extends BaseBlock {
getValue() {
return this.valueBlock.toString();
}
setValue(value) {
this.valueBlock.fromString(value);
}
constructor(parameters = {}) {
super(parameters, LocalRelativeObjectIdentifierValueBlock);
this.idBlock.tagClass = 1;
this.idBlock.tagNumber = 13;
}
onAsciiEncoding() {
return `${this.constructor.NAME} : ${this.valueBlock.toString() || "empty"}`;
}
toJSON() {
return {
...super.toJSON(),
value: this.getValue()
};
}
};
_a$l = RelativeObjectIdentifier;
(() => {
typeStore.RelativeObjectIdentifier = _a$l;
})();
RelativeObjectIdentifier.NAME = "RelativeObjectIdentifier";
var _a$k;
var Sequence2 = class extends Constructed {
constructor(parameters = {}) {
super(parameters);
this.idBlock.tagClass = 1;
this.idBlock.tagNumber = 16;
}
};
_a$k = Sequence2;
(() => {
typeStore.Sequence = _a$k;
})();
Sequence2.NAME = "SEQUENCE";
var _a$j;
var Set = class extends Constructed {
constructor(parameters = {}) {
super(parameters);
this.idBlock.tagClass = 1;
this.idBlock.tagNumber = 17;
}
};
_a$j = Set;
(() => {
typeStore.Set = _a$j;
})();
Set.NAME = "SET";
var LocalStringValueBlock = class extends HexBlock(ValueBlock) {
constructor({ ...parameters } = {}) {
super(parameters);
this.isHexOnly = true;
this.value = EMPTY_STRING;
}
toJSON() {
return {
...super.toJSON(),
value: this.value
};
}
};
LocalStringValueBlock.NAME = "StringValueBlock";
var LocalSimpleStringValueBlock = class extends LocalStringValueBlock {
};
LocalSimpleStringValueBlock.NAME = "SimpleStringValueBlock";
var LocalSimpleStringBlock = class extends BaseStringBlock {
constructor({ ...parameters } = {}) {
super(parameters, LocalSimpleStringValueBlock);
}
fromBuffer(inputBuffer) {
this.valueBlock.value = String.fromCharCode.apply(null, pvtsutils__namespace.BufferSourceConverter.toUint8Array(inputBuffer));
}
fromString(inputString) {
const strLen = inputString.length;
const view = this.valueBlock.valueHexView = new Uint8Array(strLen);
for (let i = 0; i < strLen; i++)
view[i] = inputString.charCodeAt(i);
this.valueBlock.value = inputString;
}
};
LocalSimpleStringBlock.NAME = "SIMPLE STRING";
var LocalUtf8StringValueBlock = class extends LocalSimpleStringBlock {
fromBuffer(inputBuffer) {
this.valueBlock.valueHexView = pvtsutils__namespace.BufferSourceConverter.toUint8Array(inputBuffer);
try {
this.valueBlock.value = pvtsutils__namespace.Convert.ToUtf8String(inputBuffer);
} catch (ex) {
this.warnings.push(`Error during "decodeURIComponent": ${ex}, using raw string`);
this.valueBlock.value = pvtsutils__namespace.Convert.ToBinary(inputBuffer);
}
}
fromString(inputString) {
this.valueBlock.valueHexView = new Uint8Array(pvtsutils__namespace.Convert.FromUtf8String(inputString));
this.valueBlock.value = inputString;
}
};
LocalUtf8StringValueBlock.NAME = "Utf8StringValueBlock";
var _a$i;
var Utf8String = class extends LocalUtf8StringValueBlock {
constructor(parameters = {}) {
super(parameters);
this.idBlock.tagClass = 1;
this.idBlock.tagNumber = 12;
}
};
_a$i = Utf8String;
(() => {
typeStore.Utf8String = _a$i;
})();
Utf8String.NAME = "UTF8String";
var LocalBmpStringValueBlock = class extends LocalSimpleStringBlock {
fromBuffer(inputBuffer) {
this.valueBlock.value = pvtsutils__namespace.Convert.ToUtf16String(inputBuffer);
this.valueBlock.valueHexView = pvtsutils__namespace.BufferSourceConverter.toUint8Array(inputBuffer);
}
fromString(inputString) {
this.valueBlock.value = inputString;
this.valueBlock.valueHexView = new Uint8Array(pvtsutils__namespace.Convert.FromUtf16String(inputString));
}
};
LocalBmpStringValueBlock.NAME = "BmpStringValueBlock";
var _a$h;
var BmpString = class extends LocalBmpStringValueBlock {
constructor({ ...parameters } = {}) {
super(parameters);
this.idBlock.tagClass = 1;
this.idBlock.tagNumber = 30;
}
};
_a$h = BmpString;
(() => {
typeStore.BmpString = _a$h;
})();
BmpString.NAME = "BMPString";
var LocalUniversalStringValueBlock = class extends LocalSimpleStringBlock {
fromBuffer(inputBuffer) {
const copyBuffer = ArrayBuffer.isView(inputBuffer) ? inputBuffer.slice().buffer : inputBuffer.slice(0);
const valueView = new Uint8Array(copyBuffer);
for (let i = 0; i < valueView.length; i += 4) {
valueView[i] = valueView[i + 3];
valueView[i + 1] = valueView[i + 2];
valueView[i + 2] = 0;
valueView[i + 3] = 0;
}
this.valueBlock.value = String.fromCharCode.apply(null, new Uint32Array(copyBuffer));
}
fromString(inputString) {
const strLength = inputString.length;
const valueHexView = this.valueBlock.valueHexView = new Uint8Array(strLength * 4);
for (let i = 0; i < strLength; i++) {
const codeBuf = pvutils__namespace.utilToBase(inputString.charCodeAt(i), 8);
const codeView = new Uint8Array(codeBuf);
if (codeView.length > 4)
continue;
const dif = 4 - codeView.length;
for (let j = codeView.length - 1; j >= 0; j--)
valueHexView[i * 4 + j + dif] = codeView[j];
}
this.valueBlock.value = inputString;
}
};
LocalUniversalStringValueBlock.NAME = "UniversalStringValueBlock";
var _a$g;
var UniversalString = class extends LocalUniversalStringValueBlock {
constructor({ ...parameters } = {}) {
super(parameters);
this.idBlock.tagClass = 1;
this.idBlock.tagNumber = 28;
}
};
_a$g = UniversalString;
(() => {
typeStore.UniversalString = _a$g;
})();
UniversalString.NAME = "UniversalString";
var _a$f;
var NumericString = class extends LocalSimpleStringBlock {
constructor(parameters = {}) {
super(parameters);
this.idBlock.tagClass = 1;
this.idBlock.tagNumber = 18;
}
};
_a$f = NumericString;
(() => {
typeStore.NumericString = _a$f;
})();
NumericString.NAME = "NumericString";
var _a$e;
var PrintableString = class extends LocalSimpleStringBlock {
constructor(parameters = {}) {
super(parameters);
this.idBlock.tagClass = 1;
this.idBlock.tagNumber = 19;
}
};
_a$e = PrintableString;
(() => {
typeStore.PrintableString = _a$e;
})();
PrintableString.NAME = "PrintableString";
var _a$d;
var TeletexString = class extends LocalSimpleStringBlock {
constructor(parameters = {}) {
super(parameters);
this.idBlock.tagClass = 1;
this.idBlock.tagNumber = 20;
}
};
_a$d = TeletexString;
(() => {
typeStore.TeletexString = _a$d;
})();
TeletexString.NAME = "TeletexString";
var _a$c;
var VideotexString = class extends LocalSimpleStringBlock {
constructor(parameters = {}) {
super(parameters);
this.idBlock.tagClass = 1;
this.idBlock.tagNumber = 21;
}
};
_a$c = VideotexString;
(() => {
typeStore.VideotexString = _a$c;
})();
VideotexString.NAME = "VideotexString";
var _a$b;
var IA5String = class extends LocalSimpleStringBlock {
constructor(parameters = {}) {
super(parameters);
this.idBlock.tagClass = 1;
this.idBlock.tagNumber = 22;
}
};
_a$b = IA5String;
(() => {
typeStore.IA5String = _a$b;
})();
IA5String.NAME = "IA5String";
var _a$a;
var GraphicString = class extends LocalSimpleStringBlock {
constructor(parameters = {}) {
super(parameters);
this.idBlock.tagClass = 1;
this.idBlock.tagNumber = 25;
}
};
_a$a = GraphicString;
(() => {
typeStore.GraphicString = _a$a;
})();
GraphicString.NAME = "GraphicString";
var _a$9;
var VisibleString = class extends LocalSimpleStringBlock {
constructor(parameters = {}) {
super(parameters);
this.idBlock.tagClass = 1;
this.idBlock.tagNumber = 26;
}
};
_a$9 = VisibleString;
(() => {
typeStore.VisibleString = _a$9;
})();
VisibleString.NAME = "VisibleString";
var _a$8;
var GeneralString = class extends LocalSimpleStringBlock {
constructor(parameters = {}) {
super(parameters);
this.idBlock.tagClass = 1;
this.idBlock.tagNumber = 27;
}
};
_a$8 = GeneralString;
(() => {
typeStore.GeneralString = _a$8;
})();
GeneralString.NAME = "GeneralString";
var _a$7;
var CharacterString = class extends LocalSimpleStringBlock {
constructor(parameters = {}) {
super(parameters);
this.idBlock.tagClass = 1;
this.idBlock.tagNumber = 29;
}
};
_a$7 = CharacterString;
(() => {
typeStore.CharacterString = _a$7;
})();
CharacterString.NAME = "CharacterString";
var _a$6;
var UTCTime = class extends VisibleString {
constructor({ value, valueDate, ...parameters } = {}) {
super(parameters);
this.year = 0;
this.month = 0;
this.day = 0;
this.hour = 0;
this.minute = 0;
this.second = 0;
if (value) {
this.fromString(value);
this.valueBlock.valueHexView = new Uint8Array(value.length);
for (let i = 0; i < value.length; i++)
this.valueBlock.valueHexView[i] = value.charCodeAt(i);
}
if (valueDate) {
this.fromDate(valueDate);
this.valueBlock.valueHexView = new Uint8Array(this.toBuffer());
}
this.idBlock.tagClass = 1;
this.idBlock.tagNumber = 23;
}
fromBuffer(inputBuffer) {
this.fromString(String.fromCharCode.apply(null, pvtsutils__namespace.BufferSourceConverter.toUint8Array(inputBuffer)));
}
toBuffer() {
const str = this.toString();
const buffer = new ArrayBuffer(str.length);
const view = new Uint8Array(buffer);
for (let i = 0; i < str.length; i++)
view[i] = str.charCodeAt(i);
return buffer;
}
fromDate(inputDate) {
this.year = inputDate.getUTCFullYear();
this.month = inputDate.getUTCMonth() + 1;
this.day = inputDate.getUTCDate();
this.hour = inputDate.getUTCHours();
this.minute = inputDate.getUTCMinutes();
this.second = inputDate.getUTCSeconds();
}
toDate() {
return new Date(Date.UTC(this.year, this.month - 1, this.day, this.hour, this.minute, this.second));
}
fromString(inputString) {
const parser = /(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})Z/ig;
const parserArray = parser.exec(inputString);
if (parserArray === null) {
this.error = "Wrong input string for conversion";
return;
}
const year = parseInt(parserArray[1], 10);
if (year >= 50)
this.year = 1900 + year;
else
this.year = 2e3 + year;
this.month = parseInt(parserArray[2], 10);
this.day = parseInt(parserArray[3], 10);
this.hour = parseInt(parserArray[4], 10);
this.minute = parseInt(parserArray[5], 10);
this.second = parseInt(parserArray[6], 10);
}
toString(encoding = "iso") {
if (encoding === "iso") {
const outputArray = new Array(7);
outputArray[0] = pvutils__namespace.padNumber(this.year < 2e3 ? this.year - 1900 : this.year - 2e3, 2);
outputArray[1] = pvutils__namespace.padNumber(this.month, 2);
outputArray[2] = pvutils__namespace.padNumber(this.day, 2);
outputArray[3] = pvutils__namespace.padNumber(this.hour, 2);
outputArray[4] = pvutils__namespace.padNumber(this.minute, 2);
outputArray[5] = pvutils__namespace.padNumber(this.second, 2);
outputArray[6] = "Z";
return outputArray.join("");
}
return super.toString(encoding);
}
onAsciiEncoding() {
return `${this.constructor.NAME} : ${this.toDate().toISOString()}`;
}
toJSON() {
return {
...super.toJSON(),
year: this.year,
month: this.month,
day: this.day,
hour: this.hour,
minute: this.minute,
second: this.second
};
}
};
_a$6 = UTCTime;
(() => {
typeStore.UTCTime = _a$6;
})();
UTCTime.NAME = "UTCTime";
var _a$5;
var GeneralizedTime = class extends UTCTime {
constructor(parameters = {}) {
var _b;
super(parameters);
(_b = this.millisecond) !== null && _b !== void 0 ? _b : this.millisecond = 0;
this.idBlock.tagClass = 1;
this.idBlock.tagNumber = 24;
}
fromDate(inputDate) {
super.fromDate(inputDate);
this.millisecond = inputDate.getUTCMilliseconds();
}
toDate() {
const utcDate = Date.UTC(this.year, this.month - 1, this.day, this.hour, this.minute, this.second, this.millisecond);
return new Date(utcDate);
}
fromString(inputString) {
let isUTC = false;
let timeString = "";
let dateTimeString = "";
let fractionPart = 0;
let parser;
let hourDifference = 0;
let minuteDifference = 0;
if (inputString[inputString.length - 1] === "Z") {
timeString = inputString.substring(0, inputString.length - 1);
isUTC = true;
} else {
const number = new Number(inputString[inputString.length - 1]);
if (isNaN(number.valueOf()))
throw new Error("Wrong input string for conversion");
timeString = inputString;
}
if (isUTC) {
if (timeString.indexOf("+") !== -1)
throw new Error("Wrong input string for conversion");
if (timeString.indexOf("-") !== -1)
throw new Error("Wrong input string for conversion");
} else {
let multiplier = 1;
let differencePosition = timeString.indexOf("+");
let differenceString = "";
if (differencePosition === -1) {
differencePosition = timeString.indexOf("-");
multiplier = -1;
}
if (differencePosition !== -1) {
differenceString = timeString.substring(differencePosition + 1);
timeString = timeString.substring(0, differencePosition);
if (differenceString.length !== 2 && differenceString.length !== 4)
throw new Error("Wrong input string for conversion");
let number = parseInt(differenceString.substring(0, 2), 10);
if (isNaN(number.valueOf()))
throw new Error("Wrong input string for conversion");
hourDifference = multiplier * number;
if (differenceString.length === 4) {
number = parseInt(differenceString.substring(2, 4), 10);
if (isNaN(number.valueOf()))
throw new Error("Wrong input string for conversion");
minuteDifference = multiplier * number;
}
}
}
let fractionPointPosition = timeString.indexOf(".");
if (fractionPointPosition === -1)
fractionPointPosition = timeString.indexOf(",");
if (fractionPointPosition !== -1) {
const fractionPartCheck = new Number(`0${timeString.substring(fractionPointPosition)}`);
if (isNaN(fractionPartCheck.valueOf()))
throw new Error("Wrong input string for conversion");
fractionPart = fractionPartCheck.valueOf();
dateTimeString = timeString.substring(0, fractionPointPosition);
} else
dateTimeString = timeString;
switch (true) {
case dateTimeString.length === 8:
parser = /(\d{4})(\d{2})(\d{2})/ig;
if (fractionPointPosition !== -1)
throw new Error("Wrong input string for conversion");
break;
case dateTimeString.length === 10:
parser = /(\d{4})(\d{2})(\d{2})(\d{2})/ig;
if (fractionPointPosition !== -1) {
let fractionResult = 60 * fractionPart;
this.minute = Math.floor(fractionResult);
fractionResult = 60 * (fractionResult - this.minute);
this.second = Math.floor(fractionResult);
fractionResult = 1e3 * (fractionResult - this.second);
this.millisecond = Math.floor(fractionResult);
}
break;
case dateTimeString.length === 12:
parser = /(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})/ig;
if (fractionPointPosition !== -1) {
let fractionResult = 60 * fractionPart;
this.second = Math.floor(fractionResult);
fractionResult = 1e3 * (fractionResult - this.second);
this.millisecond = Math.floor(fractionResult);
}
break;
case dateTimeString.length === 14:
parser = /(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})/ig;
if (fractionPointPosition !== -1) {
const fractionResult = 1e3 * fractionPart;
this.millisecond = Math.floor(fractionResult);
}
break;
default:
throw new Error("Wrong input string for conversion");
}
const parserArray = parser.exec(dateTimeString);
if (parserArray === null)
throw new Error("Wrong input string for conversion");
for (let j = 1; j < parserArray.length; j++) {
switch (j) {
case 1:
this.year = parseInt(parserArray[j], 10);
break;
case 2:
this.month = parseInt(parserArray[j], 10);
break;
case 3:
this.day = parseInt(parserArray[j], 10);
break;
case 4:
this.hour = parseInt(parserArray[j], 10) + hourDifference;
break;
case 5:
this.minute = parseInt(parserArray[j], 10) + minuteDifference;
break;
case 6:
this.second = parseInt(parserArray[j], 10);
break;
default:
throw new Error("Wrong input string for conversion");
}
}
if (isUTC === false) {
const tempDate = new Date(this.year, this.month, this.day, this.hour, this.minute, this.second, this.millisecond);
this.year = tempDate.getUTCFullYear();
this.month = tempDate.getUTCMonth();
this.day = tempDate.getUTCDay();
this.hour = tempDate.getUTCHours();
this.minute = tempDate.getUTCMinutes();
this.second = tempDate.getUTCSeconds();
this.millisecond = tempDate.getUTCMilliseconds();
}
}
toString(encoding = "iso") {
if (encoding === "iso") {
const outputArray = [];
outputArray.push(pvutils__namespace.padNumber(this.year, 4));
outputArray.push(pvutils__namespace.padNumber(this.month, 2));
outputArray.push(pvutils__namespace.padNumber(this.day, 2));
outputArray.push(pvutils__namespace.padNumber(this.hour, 2));
outputArray.push(pvutils__namespace.padNumber(this.minute, 2));
outputArray.push(pvutils__namespace.padNumber(this.second, 2));
if (this.millisecond !== 0) {
outputArray.push(".");
outputArray.push(pvutils__namespace.padNumber(this.millisecond, 3));
}
outputArray.push("Z");
return outputArray.join("");
}
return super.toString(encoding);
}
toJSON() {
return {
...super.toJSON(),
millisecond: this.millisecond
};
}
};
_a$5 = GeneralizedTime;
(() => {
typeStore.GeneralizedTime = _a$5;
})();
GeneralizedTime.NAME = "GeneralizedTime";
var _a$4;
var DATE = class extends Utf8String {
constructor(parameters = {}) {
super(parameters);
this.idBlock.tagClass = 1;
this.idBlock.tagNumber = 31;
}
};
_a$4 = DATE;
(() => {
typeStore.DATE = _a$4;
})();
DATE.NAME = "DATE";
var _a$3;
var TimeOfDay = class extends Utf8String {
constructor(parameters = {}) {
super(parameters);
this.idBlock.tagClass = 1;
this.idBlock.tagNumber = 32;
}
};
_a$3 = TimeOfDay;
(() => {
typeStore.TimeOfDay = _a$3;
})();
TimeOfDay.NAME = "TimeOfDay";
var _a$2;
var DateTime = class extends Utf8String {
constructor(parameters = {}) {
super(parameters);
this.idBlock.tagClass = 1;
this.idBlock.tagNumber = 33;
}
};
_a$2 = DateTime;
(() => {
typeStore.DateTime = _a$2;
})();
DateTime.NAME = "DateTime";
var _a$1;
var Duration = class extends Utf8String {
constructor(parameters = {}) {
super(parameters);
this.idBlock.tagClass = 1;
this.idBlock.tagNumber = 34;
}
};
_a$1 = Duration;
(() => {
typeStore.Duration = _a$1;
})();
Duration.NAME = "Duration";
var _a;
var TIME = class extends Utf8String {
constructor(parameters = {}) {
super(parameters);
this.idBlock.tagClass = 1;
this.idBlock.tagNumber = 14;
}
};
_a = TIME;
(() => {
typeStore.TIME = _a;
})();
TIME.NAME = "TIME";
var Any = class {
constructor({ name = EMPTY_STRING, optional = false } = {}) {
this.name = name;
this.optional = optional;
}
};
var Choice = class extends Any {
constructor({ value = [], ...parameters } = {}) {
super(parameters);
this.value = value;
}
};
var Repeated = class extends Any {
constructor({ value = new Any(), local = false, ...parameters } = {}) {
super(parameters);
this.value = value;
this.local = local;
}
};
var RawData = class {
get data() {
return this.dataView.slice().buffer;
}
set data(value) {
this.dataView = pvtsutils__namespace.BufferSourceConverter.toUint8Array(value);
}
constructor({ data = EMPTY_VIEW } = {}) {
this.dataView = pvtsutils__namespace.BufferSourceConverter.toUint8Array(data);
}
fromBER(inputBuffer, inputOffset, inputLength) {
const endLength = inputOffset + inputLength;
this.dataView = pvtsutils__namespace.BufferSourceConverter.toUint8Array(inputBuffer).subarray(inputOffset, endLength);
return endLength;
}
toBER(_sizeOnly) {
return this.dataView.slice().buffer;
}
};
function compareSchema(root, inputData, inputSchema) {
if (inputSchema instanceof Choice) {
for (const element of inputSchema.value) {
const result = compareSchema(root, inputData, element);
if (result.verified) {
return {
verified: true,
result: root
};
}
}
{
const _result = {
verified: false,
result: { error: "Wrong values for Choice type" }
};
if (inputSchema.hasOwnProperty(NAME))
_result.name = inputSchema.name;
return _result;
}
}
if (inputSchema instanceof Any) {
if (inputSchema.hasOwnProperty(NAME))
root[inputSchema.name] = inputData;
return {
verified: true,
result: root
};
}
if (root instanceof Object === false) {
return {
verified: false,
result: { error: "Wrong root object" }
};
}
if (inputData instanceof Object === false) {
return {
verified: false,
result: { error: "Wrong ASN.1 data" }
};
}
if (inputSchema instanceof Object === false) {
return {
verified: false,
result: { error: "Wrong ASN.1 schema" }
};
}
if (ID_BLOCK in inputSchema === false) {
return {
verified: false,
result: { error: "Wrong ASN.1 schema" }
};
}
if (FROM_BER in inputSchema.idBlock === false) {
return {
verified: false,
result: { error: "Wrong ASN.1 schema" }
};
}
if (TO_BER in inputSchema.idBlock === false) {
return {
verified: false,
result: { error: "Wrong ASN.1 schema" }
};
}
const encodedId = inputSchema.idBlock.toBER(false);
if (encodedId.byteLength === 0) {
return {
verified: false,
result: { error: "Error encoding idBlock for ASN.1 schema" }
};
}
const decodedOffset = inputSchema.idBlock.fromBER(encodedId, 0, encodedId.byteLength);
if (decodedOffset === -1) {
return {
verified: false,
result: { error: "Error decoding idBlock for ASN.1 schema" }
};
}
if (inputSchema.idBlock.hasOwnProperty(TAG_CLASS) === false) {
return {
verified: false,
result: { error: "Wrong ASN.1 schema" }
};
}
if (inputSchema.idBlock.tagClass !== inputData.idBlock.tagClass) {
return {
verified: false,
result: root
};
}
if (inputSchema.idBlock.hasOwnProperty(TAG_NUMBER) === false) {
return {
verified: false,
result: { error: "Wrong ASN.1 schema" }
};
}
if (inputSchema.idBlock.tagNumber !== inputData.idBlock.tagNumber) {
return {
verified: false,
result: root
};
}
if (inputSchema.idBlock.hasOwnProperty(IS_CONSTRUCTED) === false) {
return {
verified: false,
result: { error: "Wrong ASN.1 schema" }
};
}
if (inputSchema.idBlock.isConstructed !== inputData.idBlock.isConstructed) {
return {
verified: false,
result: root
};
}
if (!(IS_HEX_ONLY in inputSchema.idBlock)) {
return {
verified: false,
result: { error: "Wrong ASN.1 schema" }
};
}
if (inputSchema.idBlock.isHexOnly !== inputData.idBlock.isHexOnly) {
return {
verified: false,
result: root
};
}
if (inputSchema.idBlock.isHexOnly) {
if (VALUE_HEX_VIEW in inputSchema.idBlock === false) {
return {
verified: false,
result: { error: "Wrong ASN.1 schema" }
};
}
const schemaView = inputSchema.idBlock.valueHexView;
const asn1View = inputData.idBlock.valueHexView;
if (schemaView.length !== asn1View.length) {
return {
verified: false,
result: root
};
}
for (let i = 0; i < schemaView.length; i++) {
if (schemaView[i] !== asn1View[1]) {
return {
verified: false,
result: root
};
}
}
}
if (inputSchema.name) {
inputSchema.name = inputSchema.name.replace(/^\s+|\s+$/g, EMPTY_STRING);
if (inputSchema.name)
root[inputSchema.name] = inputData;
}
if (inputSchema instanceof typeStore.Constructed) {
let admission = 0;
let result = {
verified: false,
result: { error: "Unknown error" }
};
let maxLength = inputSchema.valueBlock.value.length;
if (maxLength > 0) {
if (inputSchema.valueBlock.value[0] instanceof Repeated) {
maxLength = inputData.valueBlock.value.length;
}
}
if (maxLength === 0) {
return {
verified: true,
result: root
};
}
if (inputData.valueBlock.value.length === 0 && inputSchema.valueBlock.value.length !== 0) {
let _optional = true;
for (let i = 0; i < inputSchema.valueBlock.value.length; i++)
_optional = _optional && (inputSchema.valueBlock.value[i].optional || false);
if (_optional) {
return {
verified: true,
result: root
};
}
if (inputSchema.name) {
inputSchema.name = inputSchema.name.replace(/^\s+|\s+$/g, EMPTY_STRING);
if (inputSchema.name)
delete root[inputSchema.name];
}
root.error = "Inconsistent object length";
return {
verified: false,
result: root
};
}
for (let i = 0; i < maxLength; i++) {
if (i - admission >= inputData.valueBlock.value.length) {
if (inputSchema.valueBlock.value[i].optional === false) {
const _result = {
verified: false,
result: root
};
root.error = "Inconsistent length between ASN.1 data and schema";
if (inputSchema.name) {
inputSchema.name = inputSchema.name.replace(/^\s+|\s+$/g, EMPTY_STRING);
if (inputSchema.name) {
delete root[inputSchema.name];
_result.name = inputSchema.name;
}
}
return _result;
}
} else {
if (inputSchema.valueBlock.value[0] instanceof Repeated) {
result = compareSchema(root, inputData.valueBlock.value[i], inputSchema.valueBlock.value[0].value);
if (result.verified === false) {
if (inputSchema.valueBlock.value[0].optional)
admission++;
else {
if (inputSchema.name) {
inputSchema.name = inputSchema.name.replace(/^\s+|\s+$/g, EMPTY_STRING);
if (inputSchema.name)
delete root[inputSchema.name];
}
return result;
}
}
if (NAME in inputSchema.valueBlock.value[0] && inputSchema.valueBlock.value[0].name.length > 0) {
let arrayRoot = {};
if (LOCAL in inputSchema.valueBlock.value[0] && inputSchema.valueBlock.value[0].local)
arrayRoot = inputData;
else
arrayRoot = root;
if (typeof arrayRoot[inputSchema.valueBlock.value[0].name] === "undefined")
arrayRoot[inputSchema.valueBlock.value[0].name] = [];
arrayRoot[inputSchema.valueBlock.value[0].name].push(inputData.valueBlock.value[i]);
}
} else {
result = compareSchema(root, inputData.valueBlock.value[i - admission], inputSchema.valueBlock.value[i]);
if (result.verified === false) {
if (inputSchema.valueBlock.value[i].optional)
admission++;
else {
if (inputSchema.name) {
inputSchema.name = inputSchema.name.replace(/^\s+|\s+$/g, EMPTY_STRING);
if (inputSchema.name)
delete root[inputSchema.name];
}
return result;
}
}
}
}
}
if (result.verified === false) {
const _result = {
verified: false,
result: root
};
if (inputSchema.name) {
inputSchema.name = inputSchema.name.replace(/^\s+|\s+$/g, EMPTY_STRING);
if (inputSchema.name) {
delete root[inputSchema.name];
_result.name = inputSchema.name;
}
}
return _result;
}
return {
verified: true,
result: root
};
}
if (inputSchema.primitiveSchema && VALUE_HEX_VIEW in inputData.valueBlock) {
const asn1 = localFromBER(inputData.valueBlock.valueHexView);
if (asn1.offset === -1) {
const _result = {
verified: false,
result: asn1.result
};
if (inputSchema.name) {
inputSchema.name = inputSchema.name.replace(/^\s+|\s+$/g, EMPTY_STRING);
if (inputSchema.name) {
delete root[inputSchema.name];
_result.name = inputSchema.name;
}
}
return _result;
}
return compareSchema(root, asn1.result, inputSchema.primitiveSchema);
}
return {
verified: true,
result: root
};
}
function verifySchema2(inputBuffer, inputSchema) {
if (inputSchema instanceof Object === false) {
return {
verified: false,
result: { error: "Wrong ASN.1 schema type" }
};
}
const asn1 = localFromBER(pvtsutils__namespace.BufferSourceConverter.toUint8Array(inputBuffer));
if (asn1.offset === -1) {
return {
verified: false,
result: asn1.result
};
}
return compareSchema(asn1.result, asn1.result, inputSchema);
}
exports2.Any = Any;
exports2.BaseBlock = BaseBlock;
exports2.BaseStringBlock = BaseStringBlock;
exports2.BitString = BitString;
exports2.BmpString = BmpString;
exports2.Boolean = Boolean;
exports2.CharacterString = CharacterString;
exports2.Choice = Choice;
exports2.Constructed = Constructed;
exports2.DATE = DATE;
exports2.DateTime = DateTime;
exports2.Duration = Duration;
exports2.EndOfContent = EndOfContent;
exports2.Enumerated = Enumerated;
exports2.GeneralString = GeneralString;
exports2.GeneralizedTime = GeneralizedTime;
exports2.GraphicString = GraphicString;
exports2.HexBlock = HexBlock;
exports2.IA5String = IA5String;
exports2.Integer = Integer2;
exports2.Null = Null;
exports2.NumericString = NumericString;
exports2.ObjectIdentifier = ObjectIdentifier;
exports2.OctetString = OctetString2;
exports2.Primitive = Primitive;
exports2.PrintableString = PrintableString;
exports2.RawData = RawData;
exports2.RelativeObjectIdentifier = RelativeObjectIdentifier;
exports2.Repeated = Repeated;
exports2.Sequence = Sequence2;
exports2.Set = Set;
exports2.TIME = TIME;
exports2.TeletexString = TeletexString;
exports2.TimeOfDay = TimeOfDay;
exports2.UTCTime = UTCTime;
exports2.UniversalString = UniversalString;
exports2.Utf8String = Utf8String;
exports2.ValueBlock = ValueBlock;
exports2.VideotexString = VideotexString;
exports2.ViewWriter = ViewWriter;
exports2.VisibleString = VisibleString;
exports2.compareSchema = compareSchema;
exports2.fromBER = fromBER;
exports2.verifySchema = verifySchema2;
}
});
// src/index.ts
var index_exports = {};
__export(index_exports, {
IBE: () => IBE,
deserializeCiphertext: () => deserializeCiphertext,
serializeCiphertext: () => serializeCiphertext
});
module.exports = __toCommonJS(index_exports);
// src/ibe.ts
var import_noble_bn254_drand2 = __toESM(require_src(), 1);
// node_modules/@noble/curves/esm/abstract/utils.js
var utils_exports = {};
__export(utils_exports, {
aInRange: () => aInRange,
abool: () => abool,
abytes: () => abytes,
bitGet: () => bitGet,
bitLen: () => bitLen,
bitMask: () => bitMask,
bitSet: () => bitSet,
bytesToHex: () => bytesToHex,
bytesToNumberBE: () => bytesToNumberBE,
bytesToNumberLE: () => bytesToNumberLE,
concatBytes: () => concatBytes,
createHmacDrbg: () => createHmacDrbg,
ensureBytes: () => ensureBytes,
equalBytes: () => equalBytes,
hexToBytes: () => hexToBytes,
hexToNumber: () => hexToNumber,
inRange: () => inRange,
isBytes: () => isBytes,
memoized: () => memoized,
notImplemented: () => notImplemented,
numberToBytesBE: () => numberToBytesBE,
numberToBytesLE: () => numberToBytesLE,
numberToHexUnpadded: () => numberToHexUnpadded,
numberToVarBytesBE: () => numberToVarBytesBE,
utf8ToBytes: () => utf8ToBytes,
validateObject: () => validateObject
});
var _0n = /* @__PURE__ */ BigInt(0);
var _1n = /* @__PURE__ */ BigInt(1);
var _2n = /* @__PURE__ */ BigInt(2);
function isBytes(a) {
return a instanceof Uint8Array || a != null && typeof a === "object" && a.constructor.name === "Uint8Array";
}
function abytes(item) {
if (!isBytes(item))
throw new Error("Uint8Array expected");
}
function abool(title, value) {
if (typeof value !== "boolean")
throw new Error(`${title} must be valid boolean, got "${value}".`);
}
var hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, "0"));
function bytesToHex(bytes) {
abytes(bytes);
let hex = "";
for (let i = 0; i < bytes.length; i++) {
hex += hexes[bytes[i]];
}
return hex;
}
function numberToHexUnpadded(num) {
const hex = num.toString(16);
return hex.length & 1 ? `0${hex}` : hex;
}
function hexToNumber(hex) {
if (typeof hex !== "string")
throw new Error("hex string expected, got " + typeof hex);
return BigInt(hex === "" ? "0" : `0x${hex}`);
}
var asciis = { _0: 48, _9: 57, _A: 65, _F: 70, _a: 97, _f: 102 };
function asciiToBase16(char) {
if (char >= asciis._0 && char <= asciis._9)
return char - asciis._0;
if (char >= asciis._A && char <= asciis._F)
return char - (asciis._A - 10);
if (char >= asciis._a && char <= asciis._f)
return char - (asciis._a - 10);
return;
}
function hexToBytes(hex) {
if (typeof hex !== "string")
throw new Error("hex string expected, got " + typeof hex);
const hl = hex.length;
const al = hl / 2;
if (hl % 2)
throw new Error("padded hex string expected, got unpadded hex of length " + hl);
const array = new Uint8Array(al);
for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) {
const n1 = asciiToBase16(hex.charCodeAt(hi));
const n2 = asciiToBase16(hex.charCodeAt(hi + 1));
if (n1 === void 0 || n2 === void 0) {
const char = hex[hi] + hex[hi + 1];
throw new Error('hex string expected, got non-hex character "' + char + '" at index ' + hi);
}
array[ai] = n1 * 16 + n2;
}
return array;
}
function bytesToNumberBE(bytes) {
return hexToNumber(bytesToHex(bytes));
}
function bytesToNumberLE(bytes) {
abytes(bytes);
return hexToNumber(bytesToHex(Uint8Array.from(bytes).reverse()));
}
function numberToBytesBE(n, len) {
return hexToBytes(n.toString(16).padStart(len * 2, "0"));
}
function numberToBytesLE(n, len) {
return numberToBytesBE(n, len).reverse();
}
function numberToVarBytesBE(n) {
return hexToBytes(numberToHexUnpadded(n));
}
function ensureBytes(title, hex, expectedLength) {
let res;
if (typeof hex === "string") {
try {
res = hexToBytes(hex);
} catch (e) {
throw new Error(`${title} must be valid hex string, got "${hex}". Cause: ${e}`);
}
} else if (isBytes(hex)) {
res = Uint8Array.from(hex);
} else {
throw new Error(`${title} must be hex string or Uint8Array`);
}
const len = res.length;
if (typeof expectedLength === "number" && len !== expectedLength)
throw new Error(`${title} expected ${expectedLength} bytes, got ${len}`);
return res;
}
function concatBytes(...arrays) {
let sum = 0;
for (let i = 0; i < arrays.length; i++) {
const a = arrays[i];
abytes(a);
sum += a.length;
}
const res = new Uint8Array(sum);
for (let i = 0, pad = 0; i < arrays.length; i++) {
const a = arrays[i];
res.set(a, pad);
pad += a.length;
}
return res;
}
function equalBytes(a, b) {
if (a.length !== b.length)
return false;
let diff = 0;
for (let i = 0; i < a.length; i++)
diff |= a[i] ^ b[i];
return diff === 0;
}
function utf8ToBytes(str) {
if (typeof str !== "string")
throw new Error(`utf8ToBytes expected string, got ${typeof str}`);
return new Uint8Array(new TextEncoder().encode(str));
}
var isPosBig = (n) => typeof n === "bigint" && _0n <= n;
function inRange(n, min, max) {
return isPosBig(n) && isPosBig(min) && isPosBig(max) && min <= n && n < max;
}
function aInRange(title, n, min, max) {
if (!inRange(n, min, max))
throw new Error(`expected valid ${title}: ${min} <= n < ${max}, got ${typeof n} ${n}`);
}
function bitLen(n) {
let len;
for (len = 0; n > _0n; n >>= _1n, len += 1)
;
return len;
}
function bitGet(n, pos) {
return n >> BigInt(pos) & _1n;
}
function bitSet(n, pos, value) {
return n | (value ? _1n : _0n) << BigInt(pos);
}
var bitMask = (n) => (_2n << BigInt(n - 1)) - _1n;
var u8n = (data) => new Uint8Array(data);
var u8fr = (arr) => Uint8Array.from(arr);
function createHmacDrbg(hashLen, qByteLen, hmacFn) {
if (typeof hashLen !== "number" || hashLen < 2)
throw new Error("hashLen must be a number");
if (typeof qByteLen !== "number" || qByteLen < 2)
throw new Error("qByteLen must be a number");
if (typeof hmacFn !== "function")
throw new Error("hmacFn must be a function");
let v = u8n(hashLen);
let k = u8n(hashLen);
let i = 0;
const reset = () => {
v.fill(1);
k.fill(0);
i = 0;
};
const h = (...b) => hmacFn(k, v, ...b);
const reseed = (seed = u8n()) => {
k = h(u8fr([0]), seed);
v = h();
if (seed.length === 0)
return;
k = h(u8fr([1]), seed);
v = h();
};
const gen2 = () => {
if (i++ >= 1e3)
throw new Error("drbg: tried 1000 values");
let len = 0;
const out = [];
while (len < qByteLen) {
v = h();
const sl = v.slice();
out.push(sl);
len += v.length;
}
return concatBytes(...out);
};
const genUntil = (seed, pred) => {
reset();
reseed(seed);
let res = void 0;
while (!(res = pred(gen2())))
reseed();
reset();
return res;
};
return genUntil;
}
var validatorFns = {
bigint: (val) => typeof val === "bigint",
function: (val) => typeof val === "function",
boolean: (val) => typeof val === "boolean",
string: (val) => typeof val === "string",
stringOrUint8Array: (val) => typeof val === "string" || isBytes(val),
isSafeInteger: (val) => Number.isSafeInteger(val),
array: (val) => Array.isArray(val),
field: (val, object) => object.Fp.isValid(val),
hash: (val) => typeof val === "function" && Number.isSafeInteger(val.outputLen)
};
function validateObject(object, validators, optValidators = {}) {
const checkField = (fieldName, type, isOptional) => {
const checkVal = validatorFns[type];
if (typeof checkVal !== "function")
throw new Error(`Invalid validator "${type}", expected function`);
const val = object[fieldName];
if (isOptional && val === void 0)
return;
if (!checkVal(val, object)) {
throw new Error(`Invalid param ${String(fieldName)}=${val} (${typeof val}), expected ${type}`);
}
};
for (const [fieldName, type] of Object.entries(validators))
checkField(fieldName, type, false);
for (const [fieldName, type] of Object.entries(optValidators))
checkField(fieldName, type, true);
return object;
}
var notImplemented = () => {
throw new Error("not implemented");
};
function memoized(fn) {
const map = /* @__PURE__ */ new WeakMap();
return (arg, ...args) => {
const val = map.get(arg);
if (val !== void 0)
return val;
const computed = fn(arg, ...args);
map.set(arg, computed);
return computed;
};
}
// node_modules/@noble/curves/esm/abstract/modular.js
var _0n2 = BigInt(0);
var _1n2 = BigInt(1);
var _2n2 = BigInt(2);
var _3n = BigInt(3);
var _4n = BigInt(4);
var _5n = BigInt(5);
var _8n = BigInt(8);
var _9n = BigInt(9);
var _16n = BigInt(16);
function mod(a, b) {
const result = a % b;
return result >= _0n2 ? result : b + result;
}
function pow(num, power, modulo) {
if (modulo <= _0n2 || power < _0n2)
throw new Error("Expected power/modulo > 0");
if (modulo === _1n2)
return _0n2;
let res = _1n2;
while (power > _0n2) {
if (power & _1n2)
res = res * num % modulo;
num = num * num % modulo;
power >>= _1n2;
}
return res;
}
function invert(number, modulo) {
if (number === _0n2 || modulo <= _0n2) {
throw new Error(`invert: expected positive integers, got n=${number} mod=${modulo}`);
}
let a = mod(number, modulo);
let b = modulo;
let x = _0n2, y = _1n2, u = _1n2, v = _0n2;
while (a !== _0n2) {
const q = b / a;
const r = b % a;
const m = x - u * q;
const n = y - v * q;
b = a, a = r, x = u, y = v, u = m, v = n;
}
const gcd = b;
if (gcd !== _1n2)
throw new Error("invert: does not exist");
return mod(x, modulo);
}
function tonelliShanks(P) {
const legendreC = (P - _1n2) / _2n2;
let Q, S, Z;
for (Q = P - _1n2, S = 0; Q % _2n2 === _0n2; Q /= _2n2, S++)
;
for (Z = _2n2; Z < P && pow(Z, legendreC, P) !== P - _1n2; Z++)
;
if (S === 1) {
const p1div4 = (P + _1n2) / _4n;
return function tonelliFast(Fp, n) {
const root = Fp.pow(n, p1div4);
if (!Fp.eql(Fp.sqr(root), n))
throw new Error("Cannot find square root");
return root;
};
}
const Q1div2 = (Q + _1n2) / _2n2;
return function tonelliSlow(Fp, n) {
if (Fp.pow(n, legendreC) === Fp.neg(Fp.ONE))
throw new Error("Cannot find square root");
let r = S;
let g = Fp.pow(Fp.mul(Fp.ONE, Z), Q);
let x = Fp.pow(n, Q1div2);
let b = Fp.pow(n, Q);
while (!Fp.eql(b, Fp.ONE)) {
if (Fp.eql(b, Fp.ZERO))
return Fp.ZERO;
let m = 1;
for (let t2 = Fp.sqr(b); m < r; m++) {
if (Fp.eql(t2, Fp.ONE))
break;
t2 = Fp.sqr(t2);
}
const ge = Fp.pow(g, _1n2 << BigInt(r - m - 1));
g = Fp.sqr(ge);
x = Fp.mul(x, ge);
b = Fp.mul(b, g);
r = m;
}
return x;
};
}
function FpSqrt(P) {
if (P % _4n === _3n) {
const p1div4 = (P + _1n2) / _4n;
return function sqrt3mod4(Fp, n) {
const root = Fp.pow(n, p1div4);
if (!Fp.eql(Fp.sqr(root), n))
throw new Error("Cannot find square root");
return root;
};
}
if (P % _8n === _5n) {
const c1 = (P - _5n) / _8n;
return function sqrt5mod8(Fp, n) {
const n2 = Fp.mul(n, _2n2);
const v = Fp.pow(n2, c1);
const nv = Fp.mul(n, v);
const i = Fp.mul(Fp.mul(nv, _2n2), v);
const root = Fp.mul(nv, Fp.sub(i, Fp.ONE));
if (!Fp.eql(Fp.sqr(root), n))
throw new Error("Cannot find square root");
return root;
};
}
if (P % _16n === _9n) {
}
return tonelliShanks(P);
}
var FIELD_FIELDS = [
"create",
"isValid",
"is0",
"neg",
"inv",
"sqrt",
"sqr",
"eql",
"add",
"sub",
"mul",
"pow",
"div",
"addN",
"subN",
"mulN",
"sqrN"
];
function validateField(field) {
const initial = {
ORDER: "bigint",
MASK: "bigint",
BYTES: "isSafeInteger",
BITS: "isSafeInteger"
};
const opts = FIELD_FIELDS.reduce((map, val) => {
map[val] = "function";
return map;
}, initial);
return validateObject(field, opts);
}
function FpPow(f, num, power) {
if (power < _0n2)
throw new Error("Expected power > 0");
if (power === _0n2)
return f.ONE;
if (power === _1n2)
return num;
let p = f.ONE;
let d = num;
while (power > _0n2) {
if (power & _1n2)
p = f.mul(p, d);
d = f.sqr(d);
power >>= _1n2;
}
return p;
}
function FpInvertBatch(f, nums) {
const tmp = new Array(nums.length);
const lastMultiplied = nums.reduce((acc, num, i) => {
if (f.is0(num))
return acc;
tmp[i] = acc;
return f.mul(acc, num);
}, f.ONE);
const inverted = f.inv(lastMultiplied);
nums.reduceRight((acc, num, i) => {
if (f.is0(num))
return acc;
tmp[i] = f.mul(acc, tmp[i]);
return f.mul(acc, num);
}, inverted);
return tmp;
}
function FpLegendre(order) {
const legendreConst = (order - _1n2) / _2n2;
return (f, x) => f.pow(x, legendreConst);
}
function FpIsSquare(f) {
const legendre = FpLegendre(f.ORDER);
return (x) => {
const p = legendre(f, x);
return f.eql(p, f.ZERO) || f.eql(p, f.ONE);
};
}
function nLength(n, nBitLength) {
const _nBitLength = nBitLength !== void 0 ? nBitLength : n.toString(2).length;
const nByteLength = Math.ceil(_nBitLength / 8);
return { nBitLength: _nBitLength, nByteLength };
}
function Field(ORDER, bitLen2, isLE2 = false, redef = {}) {
if (ORDER <= _0n2)
throw new Error(`Expected Field ORDER > 0, got ${ORDER}`);
const { nBitLength: BITS, nByteLength: BYTES } = nLength(ORDER, bitLen2);
if (BYTES > 2048)
throw new Error("Field lengths over 2048 bytes are not supported");
const sqrtP = FpSqrt(ORDER);
const f = Object.freeze({
ORDER,
BITS,
BYTES,
MASK: bitMask(BITS),
ZERO: _0n2,
ONE: _1n2,
create: (num) => mod(num, ORDER),
isValid: (num) => {
if (typeof num !== "bigint")
throw new Error(`Invalid field element: expected bigint, got ${typeof num}`);
return _0n2 <= num && num < ORDER;
},
is0: (num) => num === _0n2,
isOdd: (num) => (num & _1n2) === _1n2,
neg: (num) => mod(-num, ORDER),
eql: (lhs, rhs) => lhs === rhs,
sqr: (num) => mod(num * num, ORDER),
add: (lhs, rhs) => mod(lhs + rhs, ORDER),
sub: (lhs, rhs) => mod(lhs - rhs, ORDER),
mul: (lhs, rhs) => mod(lhs * rhs, ORDER),
pow: (num, power) => FpPow(f, num, power),
div: (lhs, rhs) => mod(lhs * invert(rhs, ORDER), ORDER),
// Same as above, but doesn't normalize
sqrN: (num) => num * num,
addN: (lhs, rhs) => lhs + rhs,
subN: (lhs, rhs) => lhs - rhs,
mulN: (lhs, rhs) => lhs * rhs,
inv: (num) => invert(num, ORDER),
sqrt: redef.sqrt || ((n) => sqrtP(f, n)),
invertBatch: (lst) => FpInvertBatch(f, lst),
// TODO: do we really need constant cmov?
// We don't have const-time bigints anyway, so probably will be not very useful
cmov: (a, b, c) => c ? b : a,
toBytes: (num) => isLE2 ? numberToBytesLE(num, BYTES) : numberToBytesBE(num, BYTES),
fromBytes: (bytes) => {
if (bytes.length !== BYTES)
throw new Error(`Fp.fromBytes: expected ${BYTES}, got ${bytes.length}`);
return isLE2 ? bytesToNumberLE(bytes) : bytesToNumberBE(bytes);
}
});
return Object.freeze(f);
}
function getFieldBytesLength(fieldOrder) {
if (typeof fieldOrder !== "bigint")
throw new Error("field order must be bigint");
const bitLength = fieldOrder.toString(2).length;
return Math.ceil(bitLength / 8);
}
function getMinHashLength(fieldOrder) {
const length = getFieldBytesLength(fieldOrder);
return length + Math.ceil(length / 2);
}
function mapHashToField(key, fieldOrder, isLE2 = false) {
const len = key.length;
const fieldLen = getFieldBytesLength(fieldOrder);
const minLen = getMinHashLength(fieldOrder);
if (len < 16 || len < minLen || len > 1024)
throw new Error(`expected ${minLen}-1024 bytes of input, got ${len}`);
const num = isLE2 ? bytesToNumberBE(key) : bytesToNumberLE(key);
const reduced = mod(num, fieldOrder - _1n2) + _1n2;
return isLE2 ? numberToBytesLE(reduced, fieldLen) : numberToBytesBE(reduced, fieldLen);
}
// node_modules/@noble/curves/esm/abstract/hash-to-curve.js
var os2ip = bytesToNumberBE;
function i2osp(value, length) {
anum(value);
anum(length);
if (value < 0 || value >= 1 << 8 * length) {
throw new Error(`bad I2OSP call: value=${value} length=${length}`);
}
const res = Array.from({ length }).fill(0);
for (let i = length - 1; i >= 0; i--) {
res[i] = value & 255;
value >>>= 8;
}
return new Uint8Array(res);
}
function strxor(a, b) {
const arr = new Uint8Array(a.length);
for (let i = 0; i < a.length; i++) {
arr[i] = a[i] ^ b[i];
}
return arr;
}
function anum(item) {
if (!Number.isSafeInteger(item))
throw new Error("number expected");
}
function expand_message_xmd(msg, DST, lenInBytes, H) {
abytes(msg);
abytes(DST);
anum(lenInBytes);
if (DST.length > 255)
DST = H(concatBytes(utf8ToBytes("H2C-OVERSIZE-DST-"), DST));
const { outputLen: b_in_bytes, blockLen: r_in_bytes } = H;
const ell = Math.ceil(lenInBytes / b_in_bytes);
if (lenInBytes > 65535 || ell > 255)
throw new Error("expand_message_xmd: invalid lenInBytes");
const DST_prime = concatBytes(DST, i2osp(DST.length, 1));
const Z_pad = i2osp(0, r_in_bytes);
const l_i_b_str = i2osp(lenInBytes, 2);
const b = new Array(ell);
const b_0 = H(concatBytes(Z_pad, msg, l_i_b_str, i2osp(0, 1), DST_prime));
b[0] = H(concatBytes(b_0, i2osp(1, 1), DST_prime));
for (let i = 1; i <= ell; i++) {
const args = [strxor(b_0, b[i - 1]), i2osp(i + 1, 1), DST_prime];
b[i] = H(concatBytes(...args));
}
const pseudo_random_bytes = concatBytes(...b);
return pseudo_random_bytes.slice(0, lenInBytes);
}
function expand_message_xof(msg, DST, lenInBytes, k, H) {
abytes(msg);
abytes(DST);
anum(lenInBytes);
if (DST.length > 255) {
const dkLen = Math.ceil(2 * k / 8);
DST = H.create({ dkLen }).update(utf8ToBytes("H2C-OVERSIZE-DST-")).update(DST).digest();
}
if (lenInBytes > 65535 || DST.length > 255)
throw new Error("expand_message_xof: invalid lenInBytes");
return H.create({ dkLen: lenInBytes }).update(msg).update(i2osp(lenInBytes, 2)).update(DST).update(i2osp(DST.length, 1)).digest();
}
function hash_to_field(msg, count, options) {
validateObject(options, {
DST: "stringOrUint8Array",
p: "bigint",
m: "isSafeInteger",
k: "isSafeInteger",
hash: "hash"
});
const { p, k, m, hash, expand, DST: _DST } = options;
abytes(msg);
anum(count);
const DST = typeof _DST === "string" ? utf8ToBytes(_DST) : _DST;
const log2p = p.toString(2).length;
const L = Math.ceil((log2p + k) / 8);
const len_in_bytes = count * m * L;
let prb;
if (expand === "xmd") {
prb = expand_message_xmd(msg, DST, len_in_bytes, hash);
} else if (expand === "xof") {
prb = expand_message_xof(msg, DST, len_in_bytes, k, hash);
} else if (expand === "_internal_pass") {
prb = msg;
} else {
throw new Error('expand must be "xmd" or "xof"');
}
const u = new Array(count);
for (let i = 0; i < count; i++) {
const e = new Array(m);
for (let j = 0; j < m; j++) {
const elm_offset = L * (j + i * m);
const tv = prb.subarray(elm_offset, elm_offset + L);
e[j] = mod(os2ip(tv), p);
}
u[i] = e;
}
return u;
}
function createHasher(Point, mapToCurve, def) {
if (typeof mapToCurve !== "function")
throw new Error("mapToCurve() must be defined");
return {
// Encodes byte string to elliptic curve.
// hash_to_curve from https://www.rfc-editor.org/rfc/rfc9380#section-3
hashToCurve(msg, options) {
const u = hash_to_field(msg, 2, { ...def, DST: def.DST, ...options });
const u0 = Point.fromAffine(mapToCurve(u[0]));
const u1 = Point.fromAffine(mapToCurve(u[1]));
const P = u0.add(u1).clearCofactor();
P.assertValidity();
return P;
},
// Encodes byte string to elliptic curve.
// encode_to_curve from https://www.rfc-editor.org/rfc/rfc9380#section-3
encodeToCurve(msg, options) {
const u = hash_to_field(msg, 1, { ...def, DST: def.encodeDST, ...options });
const P = Point.fromAffine(mapToCurve(u[0])).clearCofactor();
P.assertValidity();
return P;
},
// Same as encodeToCurve, but without hash
mapToCurve(scalars) {
if (!Array.isArray(scalars))
throw new Error("mapToCurve: expected array of bigints");
for (const i of scalars)
if (typeof i !== "bigint")
throw new Error(`mapToCurve: expected array of bigints, got ${i} in array`);
const P = Point.fromAffine(mapToCurve(scalars)).clearCofactor();
P.assertValidity();
return P;
}
};
}
// node_modules/@noble/hashes/esm/_u64.js
var U32_MASK64 = /* @__PURE__ */ BigInt(2 ** 32 - 1);
var _32n = /* @__PURE__ */ BigInt(32);
function fromBig(n, le = false) {
if (le)
return { h: Number(n & U32_MASK64), l: Number(n >> _32n & U32_MASK64) };
return { h: Number(n >> _32n & U32_MASK64) | 0, l: Number(n & U32_MASK64) | 0 };
}
function split(lst, le = false) {
const len = lst.length;
let Ah = new Uint32Array(len);
let Al = new Uint32Array(len);
for (let i = 0; i < len; i++) {
const { h, l } = fromBig(lst[i], le);
[Ah[i], Al[i]] = [h, l];
}
return [Ah, Al];
}
var rotlSH = (h, l, s) => h << s | l >>> 32 - s;
var rotlSL = (h, l, s) => l << s | h >>> 32 - s;
var rotlBH = (h, l, s) => l << s - 32 | h >>> 64 - s;
var rotlBL = (h, l, s) => h << s - 32 | l >>> 64 - s;
// node_modules/@noble/hashes/esm/cryptoNode.js
var nc = __toESM(require("node:crypto"), 1);
var crypto2 = nc && typeof nc === "object" && "webcrypto" in nc ? nc.webcrypto : nc && typeof nc === "object" && "randomBytes" in nc ? nc : void 0;
// node_modules/@noble/hashes/esm/utils.js
function isBytes2(a) {
return a instanceof Uint8Array || ArrayBuffer.isView(a) && a.constructor.name === "Uint8Array";
}
function anumber(n) {
if (!Number.isSafeInteger(n) || n < 0)
throw new Error("positive integer expected, got " + n);
}
function abytes2(b, ...lengths) {
if (!isBytes2(b))
throw new Error("Uint8Array expected");
if (lengths.length > 0 && !lengths.includes(b.length))
throw new Error("Uint8Array expected of length " + lengths + ", got length=" + b.length);
}
function aexists(instance, checkFinished = true) {
if (instance.destroyed)
throw new Error("Hash instance has been destroyed");
if (checkFinished && instance.finished)
throw new Error("Hash#digest() has already been called");
}
function aoutput(out, instance) {
abytes2(out);
const min = instance.outputLen;
if (out.length < min) {
throw new Error("digestInto() expects output buffer of length at least " + min);
}
}
function u32(arr) {
return new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4));
}
function clean(...arrays) {
for (let i = 0; i < arrays.length; i++) {
arrays[i].fill(0);
}
}
var isLE = /* @__PURE__ */ (() => new Uint8Array(new Uint32Array([287454020]).buffer)[0] === 68)();
function byteSwap(word) {
return word << 24 & 4278190080 | word << 8 & 16711680 | word >>> 8 & 65280 | word >>> 24 & 255;
}
function byteSwap32(arr) {
for (let i = 0; i < arr.length; i++) {
arr[i] = byteSwap(arr[i]);
}
return arr;
}
var swap32IfBE = isLE ? (u) => u : byteSwap32;
function utf8ToBytes2(str) {
if (typeof str !== "string")
throw new Error("string expected");
return new Uint8Array(new TextEncoder().encode(str));
}
function toBytes(data) {
if (typeof data === "string")
data = utf8ToBytes2(data);
abytes2(data);
return data;
}
var Hash = class {
};
function createHasher2(hashCons) {
const hashC = (msg) => hashCons().update(toBytes(msg)).digest();
const tmp = hashCons();
hashC.outputLen = tmp.outputLen;
hashC.blockLen = tmp.blockLen;
hashC.create = () => hashCons();
return hashC;
}
function randomBytes(bytesLength = 32) {
if (crypto2 && typeof crypto2.getRandomValues === "function") {
return crypto2.getRandomValues(new Uint8Array(bytesLength));
}
if (crypto2 && typeof crypto2.randomBytes === "function") {
return Uint8Array.from(crypto2.randomBytes(bytesLength));
}
throw new Error("crypto.getRandomValues must be defined");
}
// node_modules/@noble/hashes/esm/sha3.js
var _0n3 = BigInt(0);
var _1n3 = BigInt(1);
var _2n3 = BigInt(2);
var _7n = BigInt(7);
var _256n = BigInt(256);
var _0x71n = BigInt(113);
var SHA3_PI = [];
var SHA3_ROTL = [];
var _SHA3_IOTA = [];
for (let round = 0, R = _1n3, x = 1, y = 0; round < 24; round++) {
[x, y] = [y, (2 * x + 3 * y) % 5];
SHA3_PI.push(2 * (5 * y + x));
SHA3_ROTL.push((round + 1) * (round + 2) / 2 % 64);
let t = _0n3;
for (let j = 0; j < 7; j++) {
R = (R << _1n3 ^ (R >> _7n) * _0x71n) % _256n;
if (R & _2n3)
t ^= _1n3 << (_1n3 << /* @__PURE__ */ BigInt(j)) - _1n3;
}
_SHA3_IOTA.push(t);
}
var IOTAS = split(_SHA3_IOTA, true);
var SHA3_IOTA_H = IOTAS[0];
var SHA3_IOTA_L = IOTAS[1];
var rotlH = (h, l, s) => s > 32 ? rotlBH(h, l, s) : rotlSH(h, l, s);
var rotlL = (h, l, s) => s > 32 ? rotlBL(h, l, s) : rotlSL(h, l, s);
function keccakP(s, rounds = 24) {
const B = new Uint32Array(5 * 2);
for (let round = 24 - rounds; round < 24; round++) {
for (let x = 0; x < 10; x++)
B[x] = s[x] ^ s[x + 10] ^ s[x + 20] ^ s[x + 30] ^ s[x + 40];
for (let x = 0; x < 10; x += 2) {
const idx1 = (x + 8) % 10;
const idx0 = (x + 2) % 10;
const B0 = B[idx0];
const B1 = B[idx0 + 1];
const Th = rotlH(B0, B1, 1) ^ B[idx1];
const Tl = rotlL(B0, B1, 1) ^ B[idx1 + 1];
for (let y = 0; y < 50; y += 10) {
s[x + y] ^= Th;
s[x + y + 1] ^= Tl;
}
}
let curH = s[2];
let curL = s[3];
for (let t = 0; t < 24; t++) {
const shift = SHA3_ROTL[t];
const Th = rotlH(curH, curL, shift);
const Tl = rotlL(curH, curL, shift);
const PI = SHA3_PI[t];
curH = s[PI];
curL = s[PI + 1];
s[PI] = Th;
s[PI + 1] = Tl;
}
for (let y = 0; y < 50; y += 10) {
for (let x = 0; x < 10; x++)
B[x] = s[y + x];
for (let x = 0; x < 10; x++)
s[y + x] ^= ~B[(x + 2) % 10] & B[(x + 4) % 10];
}
s[0] ^= SHA3_IOTA_H[round];
s[1] ^= SHA3_IOTA_L[round];
}
clean(B);
}
var Keccak = class _Keccak extends Hash {
// NOTE: we accept arguments in bytes instead of bits here.
constructor(blockLen, suffix, outputLen, enableXOF = false, rounds = 24) {
super();
this.pos = 0;
this.posOut = 0;
this.finished = false;
this.destroyed = false;
this.enableXOF = false;
this.blockLen = blockLen;
this.suffix = suffix;
this.outputLen = outputLen;
this.enableXOF = enableXOF;
this.rounds = rounds;
anumber(outputLen);
if (!(0 < blockLen && blockLen < 200))
throw new Error("only keccak-f1600 function is supported");
this.state = new Uint8Array(200);
this.state32 = u32(this.state);
}
clone() {
return this._cloneInto();
}
keccak() {
swap32IfBE(this.state32);
keccakP(this.state32, this.rounds);
swap32IfBE(this.state32);
this.posOut = 0;
this.pos = 0;
}
update(data) {
aexists(this);
data = toBytes(data);
abytes2(data);
const { blockLen, state } = this;
const len = data.length;
for (let pos = 0; pos < len; ) {
const take = Math.min(blockLen - this.pos, len - pos);
for (let i = 0; i < take; i++)
state[this.pos++] ^= data[pos++];
if (this.pos === blockLen)
this.keccak();
}
return this;
}
finish() {
if (this.finished)
return;
this.finished = true;
const { state, suffix, pos, blockLen } = this;
state[pos] ^= suffix;
if ((suffix & 128) !== 0 && pos === blockLen - 1)
this.keccak();
state[blockLen - 1] ^= 128;
this.keccak();
}
writeInto(out) {
aexists(this, false);
abytes2(out);
this.finish();
const bufferOut = this.state;
const { blockLen } = this;
for (let pos = 0, len = out.length; pos < len; ) {
if (this.posOut >= blockLen)
this.keccak();
const take = Math.min(blockLen - this.posOut, len - pos);
out.set(bufferOut.subarray(this.posOut, this.posOut + take), pos);
this.posOut += take;
pos += take;
}
return out;
}
xofInto(out) {
if (!this.enableXOF)
throw new Error("XOF is not possible for this instance");
return this.writeInto(out);
}
xof(bytes) {
anumber(bytes);
return this.xofInto(new Uint8Array(bytes));
}
digestInto(out) {
aoutput(out, this);
if (this.finished)
throw new Error("digest() was already called");
this.writeInto(out);
this.destroy();
return out;
}
digest() {
return this.digestInto(new Uint8Array(this.outputLen));
}
destroy() {
this.destroyed = true;
clean(this.state);
}
_cloneInto(to) {
const { blockLen, suffix, outputLen, rounds, enableXOF } = this;
to || (to = new _Keccak(blockLen, suffix, outputLen, enableXOF, rounds));
to.state32.set(this.state32);
to.pos = this.pos;
to.posOut = this.posOut;
to.finished = this.finished;
to.rounds = rounds;
to.suffix = suffix;
to.outputLen = outputLen;
to.enableXOF = enableXOF;
to.destroyed = this.destroyed;
return to;
}
};
var gen = (suffix, blockLen, outputLen) => createHasher2(() => new Keccak(blockLen, suffix, outputLen));
var keccak_256 = /* @__PURE__ */ (() => gen(1, 136, 256 / 8))();
// src/bn254.ts
var import_noble_bn254_drand = __toESM(require_src(), 1);
// node_modules/@noble/curves/esm/abstract/tower.js
var _0n4 = BigInt(0);
var _1n4 = BigInt(1);
var _2n4 = BigInt(2);
var _3n2 = BigInt(3);
function psiFrobenius(Fp, Fp2, base) {
const PSI_X = Fp2.pow(base, (Fp.ORDER - _1n4) / _3n2);
const PSI_Y = Fp2.pow(base, (Fp.ORDER - _1n4) / _2n4);
function psi2(x, y) {
const x2 = Fp2.mul(Fp2.frobeniusMap(x, 1), PSI_X);
const y2 = Fp2.mul(Fp2.frobeniusMap(y, 1), PSI_Y);
return [x2, y2];
}
const PSI2_X = Fp2.pow(base, (Fp.ORDER ** _2n4 - _1n4) / _3n2);
const PSI2_Y = Fp2.pow(base, (Fp.ORDER ** _2n4 - _1n4) / _2n4);
if (!Fp2.eql(PSI2_Y, Fp2.neg(Fp2.ONE)))
throw new Error("psiFrobenius: PSI2_Y!==-1");
function psi22(x, y) {
return [Fp2.mul(x, PSI2_X), Fp2.neg(y)];
}
const mapAffine = (fn) => (c, P) => {
const affine = P.toAffine();
const p = fn(affine.x, affine.y);
return c.fromAffine({ x: p[0], y: p[1] });
};
const G2psi3 = mapAffine(psi2);
const G2psi22 = mapAffine(psi22);
return { psi: psi2, psi2: psi22, G2psi: G2psi3, G2psi2: G2psi22, PSI_X, PSI_Y, PSI2_X, PSI2_Y };
}
// node_modules/@noble/curves/esm/abstract/curve.js
var _0n5 = BigInt(0);
var _1n5 = BigInt(1);
var pointPrecomputes = /* @__PURE__ */ new WeakMap();
var pointWindowSizes = /* @__PURE__ */ new WeakMap();
function wNAF(c, bits) {
const constTimeNegate = (condition, item) => {
const neg = item.negate();
return condition ? neg : item;
};
const validateW = (W) => {
if (!Number.isSafeInteger(W) || W <= 0 || W > bits)
throw new Error(`Wrong window size=${W}, should be [1..${bits}]`);
};
const opts = (W) => {
validateW(W);
const windows = Math.ceil(bits / W) + 1;
const windowSize = 2 ** (W - 1);
return { windows, windowSize };
};
return {
constTimeNegate,
// non-const time multiplication ladder
unsafeLadder(elm, n) {
let p = c.ZERO;
let d = elm;
while (n > _0n5) {
if (n & _1n5)
p = p.add(d);
d = d.double();
n >>= _1n5;
}
return p;
},
/**
* Creates a wNAF precomputation window. Used for caching.
* Default window size is set by `utils.precompute()` and is equal to 8.
* Number of precomputed points depends on the curve size:
* 2^(𝑊−1) * (Math.ceil(𝑛 / 𝑊) + 1), where:
* - 𝑊 is the window size
* - 𝑛 is the bitlength of the curve order.
* For a 256-bit curve and window size 8, the number of precomputed points is 128 * 33 = 4224.
* @returns precomputed point tables flattened to a single array
*/
precomputeWindow(elm, W) {
const { windows, windowSize } = opts(W);
const points = [];
let p = elm;
let base = p;
for (let window = 0; window < windows; window++) {
base = p;
points.push(base);
for (let i = 1; i < windowSize; i++) {
base = base.add(p);
points.push(base);
}
p = base.double();
}
return points;
},
/**
* Implements ec multiplication using precomputed tables and w-ary non-adjacent form.
* @param W window size
* @param precomputes precomputed tables
* @param n scalar (we don't check here, but should be less than curve order)
* @returns real and fake (for const-time) points
*/
wNAF(W, precomputes, n) {
const { windows, windowSize } = opts(W);
let p = c.ZERO;
let f = c.BASE;
const mask = BigInt(2 ** W - 1);
const maxNumber = 2 ** W;
const shiftBy = BigInt(W);
for (let window = 0; window < windows; window++) {
const offset = window * windowSize;
let wbits = Number(n & mask);
n >>= shiftBy;
if (wbits > windowSize) {
wbits -= maxNumber;
n += _1n5;
}
const offset1 = offset;
const offset2 = offset + Math.abs(wbits) - 1;
const cond1 = window % 2 !== 0;
const cond2 = wbits < 0;
if (wbits === 0) {
f = f.add(constTimeNegate(cond1, precomputes[offset1]));
} else {
p = p.add(constTimeNegate(cond2, precomputes[offset2]));
}
}
return { p, f };
},
wNAFCached(P, n, transform) {
const W = pointWindowSizes.get(P) || 1;
let comp = pointPrecomputes.get(P);
if (!comp) {
comp = this.precomputeWindow(P, W);
if (W !== 1)
pointPrecomputes.set(P, transform(comp));
}
return this.wNAF(W, comp, n);
},
// We calculate precomputes for elliptic curve point multiplication
// using windowed method. This specifies window size and
// stores precomputed values. Usually only base point would be precomputed.
setWindowSize(P, W) {
validateW(W);
pointWindowSizes.set(P, W);
pointPrecomputes.delete(P);
}
};
}
function pippenger(c, field, points, scalars) {
if (!Array.isArray(points) || !Array.isArray(scalars) || scalars.length !== points.length)
throw new Error("arrays of points and scalars must have equal length");
scalars.forEach((s, i) => {
if (!field.isValid(s))
throw new Error(`wrong scalar at index ${i}`);
});
points.forEach((p, i) => {
if (!(p instanceof c))
throw new Error(`wrong point at index ${i}`);
});
const wbits = bitLen(BigInt(points.length));
const windowSize = wbits > 12 ? wbits - 3 : wbits > 4 ? wbits - 2 : wbits ? 2 : 1;
const MASK = (1 << windowSize) - 1;
const buckets = new Array(MASK + 1).fill(c.ZERO);
const lastBits = Math.floor((field.BITS - 1) / windowSize) * windowSize;
let sum = c.ZERO;
for (let i = lastBits; i >= 0; i -= windowSize) {
buckets.fill(c.ZERO);
for (let j = 0; j < scalars.length; j++) {
const scalar = scalars[j];
const wbits2 = Number(scalar >> BigInt(i) & BigInt(MASK));
buckets[wbits2] = buckets[wbits2].add(points[j]);
}
let resI = c.ZERO;
for (let j = buckets.length - 1, sumI = c.ZERO; j > 0; j--) {
sumI = sumI.add(buckets[j]);
resI = resI.add(sumI);
}
sum = sum.add(resI);
if (i !== 0)
for (let j = 0; j < windowSize; j++)
sum = sum.double();
}
return sum;
}
function validateBasic(curve) {
validateField(curve.Fp);
validateObject(curve, {
n: "bigint",
h: "bigint",
Gx: "field",
Gy: "field"
}, {
nBitLength: "isSafeInteger",
nByteLength: "isSafeInteger"
});
return Object.freeze({
...nLength(curve.n, curve.nBitLength),
...curve,
...{ p: curve.Fp.ORDER }
});
}
// node_modules/@noble/curves/esm/abstract/weierstrass.js
function validatePointOpts(curve) {
const opts = validateBasic(curve);
validateObject(opts, {
a: "field",
b: "field"
}, {
allowedPrivateKeyLengths: "array",
wrapPrivateKey: "boolean",
isTorsionFree: "function",
clearCofactor: "function",
allowInfinityPoint: "boolean",
fromBytes: "function",
toBytes: "function"
});
const { endo, Fp, a } = opts;
if (endo) {
if (!Fp.eql(a, Fp.ZERO)) {
throw new Error("Endomorphism can only be defined for Koblitz curves that have a=0");
}
if (typeof endo !== "object" || typeof endo.beta !== "bigint" || typeof endo.splitScalar !== "function") {
throw new Error("Expected endomorphism with beta: bigint and splitScalar: function");
}
}
return Object.freeze({ ...opts });
}
var { bytesToNumberBE: b2n, hexToBytes: h2b } = utils_exports;
var _0n6 = BigInt(0);
var _1n6 = BigInt(1);
var _2n5 = BigInt(2);
var _3n3 = BigInt(3);
var _4n2 = BigInt(4);
function weierstrassPoints(opts) {
const CURVE = validatePointOpts(opts);
const { Fp } = CURVE;
const Fn = Field(CURVE.n, CURVE.nBitLength);
const toBytes2 = CURVE.toBytes || ((_c, point, _isCompressed) => {
const a = point.toAffine();
return concatBytes(Uint8Array.from([4]), Fp.toBytes(a.x), Fp.toBytes(a.y));
});
const fromBytes = CURVE.fromBytes || ((bytes) => {
const tail = bytes.subarray(1);
const x = Fp.fromBytes(tail.subarray(0, Fp.BYTES));
const y = Fp.fromBytes(tail.subarray(Fp.BYTES, 2 * Fp.BYTES));
return { x, y };
});
function weierstrassEquation(x) {
const { a, b } = CURVE;
const x2 = Fp.sqr(x);
const x3 = Fp.mul(x2, x);
return Fp.add(Fp.add(x3, Fp.mul(x, a)), b);
}
if (!Fp.eql(Fp.sqr(CURVE.Gy), weierstrassEquation(CURVE.Gx)))
throw new Error("bad generator point: equation left != right");
function isWithinCurveOrder(num) {
return inRange(num, _1n6, CURVE.n);
}
function normPrivateKeyToScalar(key) {
const { allowedPrivateKeyLengths: lengths, nByteLength, wrapPrivateKey, n: N } = CURVE;
if (lengths && typeof key !== "bigint") {
if (isBytes(key))
key = bytesToHex(key);
if (typeof key !== "string" || !lengths.includes(key.length))
throw new Error("Invalid key");
key = key.padStart(nByteLength * 2, "0");
}
let num;
try {
num = typeof key === "bigint" ? key : bytesToNumberBE(ensureBytes("private key", key, nByteLength));
} catch (error) {
throw new Error(`private key must be ${nByteLength} bytes, hex or bigint, not ${typeof key}`);
}
if (wrapPrivateKey)
num = mod(num, N);
aInRange("private key", num, _1n6, N);
return num;
}
function assertPrjPoint(other) {
if (!(other instanceof Point))
throw new Error("ProjectivePoint expected");
}
const toAffineMemo = memoized((p, iz) => {
const { px: x, py: y, pz: z } = p;
if (Fp.eql(z, Fp.ONE))
return { x, y };
const is0 = p.is0();
if (iz == null)
iz = is0 ? Fp.ONE : Fp.inv(z);
const ax = Fp.mul(x, iz);
const ay = Fp.mul(y, iz);
const zz = Fp.mul(z, iz);
if (is0)
return { x: Fp.ZERO, y: Fp.ZERO };
if (!Fp.eql(zz, Fp.ONE))
throw new Error("invZ was invalid");
return { x: ax, y: ay };
});
const assertValidMemo = memoized((p) => {
if (p.is0()) {
if (CURVE.allowInfinityPoint && !Fp.is0(p.py))
return;
throw new Error("bad point: ZERO");
}
const { x, y } = p.toAffine();
if (!Fp.isValid(x) || !Fp.isValid(y))
throw new Error("bad point: x or y not FE");
const left = Fp.sqr(y);
const right = weierstrassEquation(x);
if (!Fp.eql(left, right))
throw new Error("bad point: equation left != right");
if (!p.isTorsionFree())
throw new Error("bad point: not in prime-order subgroup");
return true;
});
class Point {
constructor(px, py, pz) {
this.px = px;
this.py = py;
this.pz = pz;
if (px == null || !Fp.isValid(px))
throw new Error("x required");
if (py == null || !Fp.isValid(py))
throw new Error("y required");
if (pz == null || !Fp.isValid(pz))
throw new Error("z required");
Object.freeze(this);
}
// Does not validate if the point is on-curve.
// Use fromHex instead, or call assertValidity() later.
static fromAffine(p) {
const { x, y } = p || {};
if (!p || !Fp.isValid(x) || !Fp.isValid(y))
throw new Error("invalid affine point");
if (p instanceof Point)
throw new Error("projective point not allowed");
const is0 = (i) => Fp.eql(i, Fp.ZERO);
if (is0(x) && is0(y))
return Point.ZERO;
return new Point(x, y, Fp.ONE);
}
get x() {
return this.toAffine().x;
}
get y() {
return this.toAffine().y;
}
/**
* Takes a bunch of Projective Points but executes only one
* inversion on all of them. Inversion is very slow operation,
* so this improves performance massively.
* Optimization: converts a list of projective points to a list of identical points with Z=1.
*/
static normalizeZ(points) {
const toInv = Fp.invertBatch(points.map((p) => p.pz));
return points.map((p, i) => p.toAffine(toInv[i])).map(Point.fromAffine);
}
/**
* Converts hash string or Uint8Array to Point.
* @param hex short/long ECDSA hex
*/
static fromHex(hex) {
const P = Point.fromAffine(fromBytes(ensureBytes("pointHex", hex)));
P.assertValidity();
return P;
}
// Multiplies generator point by privateKey.
static fromPrivateKey(privateKey) {
return Point.BASE.multiply(normPrivateKeyToScalar(privateKey));
}
// Multiscalar Multiplication
static msm(points, scalars) {
return pippenger(Point, Fn, points, scalars);
}
// "Private method", don't use it directly
_setWindowSize(windowSize) {
wnaf.setWindowSize(this, windowSize);
}
// A point on curve is valid if it conforms to equation.
assertValidity() {
assertValidMemo(this);
}
hasEvenY() {
const { y } = this.toAffine();
if (Fp.isOdd)
return !Fp.isOdd(y);
throw new Error("Field doesn't support isOdd");
}
/**
* Compare one point to another.
*/
equals(other) {
assertPrjPoint(other);
const { px: X1, py: Y1, pz: Z1 } = this;
const { px: X2, py: Y2, pz: Z2 } = other;
const U1 = Fp.eql(Fp.mul(X1, Z2), Fp.mul(X2, Z1));
const U2 = Fp.eql(Fp.mul(Y1, Z2), Fp.mul(Y2, Z1));
return U1 && U2;
}
/**
* Flips point to one corresponding to (x, -y) in Affine coordinates.
*/
negate() {
return new Point(this.px, Fp.neg(this.py), this.pz);
}
// Renes-Costello-Batina exception-free doubling formula.
// There is 30% faster Jacobian formula, but it is not complete.
// https://eprint.iacr.org/2015/1060, algorithm 3
// Cost: 8M + 3S + 3*a + 2*b3 + 15add.
double() {
const { a, b } = CURVE;
const b3 = Fp.mul(b, _3n3);
const { px: X1, py: Y1, pz: Z1 } = this;
let X3 = Fp.ZERO, Y3 = Fp.ZERO, Z3 = Fp.ZERO;
let t0 = Fp.mul(X1, X1);
let t1 = Fp.mul(Y1, Y1);
let t2 = Fp.mul(Z1, Z1);
let t3 = Fp.mul(X1, Y1);
t3 = Fp.add(t3, t3);
Z3 = Fp.mul(X1, Z1);
Z3 = Fp.add(Z3, Z3);
X3 = Fp.mul(a, Z3);
Y3 = Fp.mul(b3, t2);
Y3 = Fp.add(X3, Y3);
X3 = Fp.sub(t1, Y3);
Y3 = Fp.add(t1, Y3);
Y3 = Fp.mul(X3, Y3);
X3 = Fp.mul(t3, X3);
Z3 = Fp.mul(b3, Z3);
t2 = Fp.mul(a, t2);
t3 = Fp.sub(t0, t2);
t3 = Fp.mul(a, t3);
t3 = Fp.add(t3, Z3);
Z3 = Fp.add(t0, t0);
t0 = Fp.add(Z3, t0);
t0 = Fp.add(t0, t2);
t0 = Fp.mul(t0, t3);
Y3 = Fp.add(Y3, t0);
t2 = Fp.mul(Y1, Z1);
t2 = Fp.add(t2, t2);
t0 = Fp.mul(t2, t3);
X3 = Fp.sub(X3, t0);
Z3 = Fp.mul(t2, t1);
Z3 = Fp.add(Z3, Z3);
Z3 = Fp.add(Z3, Z3);
return new Point(X3, Y3, Z3);
}
// Renes-Costello-Batina exception-free addition formula.
// There is 30% faster Jacobian formula, but it is not complete.
// https://eprint.iacr.org/2015/1060, algorithm 1
// Cost: 12M + 0S + 3*a + 3*b3 + 23add.
add(other) {
assertPrjPoint(other);
const { px: X1, py: Y1, pz: Z1 } = this;
const { px: X2, py: Y2, pz: Z2 } = other;
let X3 = Fp.ZERO, Y3 = Fp.ZERO, Z3 = Fp.ZERO;
const a = CURVE.a;
const b3 = Fp.mul(CURVE.b, _3n3);
let t0 = Fp.mul(X1, X2);
let t1 = Fp.mul(Y1, Y2);
let t2 = Fp.mul(Z1, Z2);
let t3 = Fp.add(X1, Y1);
let t4 = Fp.add(X2, Y2);
t3 = Fp.mul(t3, t4);
t4 = Fp.add(t0, t1);
t3 = Fp.sub(t3, t4);
t4 = Fp.add(X1, Z1);
let t5 = Fp.add(X2, Z2);
t4 = Fp.mul(t4, t5);
t5 = Fp.add(t0, t2);
t4 = Fp.sub(t4, t5);
t5 = Fp.add(Y1, Z1);
X3 = Fp.add(Y2, Z2);
t5 = Fp.mul(t5, X3);
X3 = Fp.add(t1, t2);
t5 = Fp.sub(t5, X3);
Z3 = Fp.mul(a, t4);
X3 = Fp.mul(b3, t2);
Z3 = Fp.add(X3, Z3);
X3 = Fp.sub(t1, Z3);
Z3 = Fp.add(t1, Z3);
Y3 = Fp.mul(X3, Z3);
t1 = Fp.add(t0, t0);
t1 = Fp.add(t1, t0);
t2 = Fp.mul(a, t2);
t4 = Fp.mul(b3, t4);
t1 = Fp.add(t1, t2);
t2 = Fp.sub(t0, t2);
t2 = Fp.mul(a, t2);
t4 = Fp.add(t4, t2);
t0 = Fp.mul(t1, t4);
Y3 = Fp.add(Y3, t0);
t0 = Fp.mul(t5, t4);
X3 = Fp.mul(t3, X3);
X3 = Fp.sub(X3, t0);
t0 = Fp.mul(t3, t1);
Z3 = Fp.mul(t5, Z3);
Z3 = Fp.add(Z3, t0);
return new Point(X3, Y3, Z3);
}
subtract(other) {
return this.add(other.negate());
}
is0() {
return this.equals(Point.ZERO);
}
wNAF(n) {
return wnaf.wNAFCached(this, n, Point.normalizeZ);
}
/**
* Non-constant-time multiplication. Uses double-and-add algorithm.
* It's faster, but should only be used when you don't care about
* an exposed private key e.g. sig verification, which works over *public* keys.
*/
multiplyUnsafe(sc) {
aInRange("scalar", sc, _0n6, CURVE.n);
const I = Point.ZERO;
if (sc === _0n6)
return I;
if (sc === _1n6)
return this;
const { endo } = CURVE;
if (!endo)
return wnaf.unsafeLadder(this, sc);
let { k1neg, k1, k2neg, k2 } = endo.splitScalar(sc);
let k1p = I;
let k2p = I;
let d = this;
while (k1 > _0n6 || k2 > _0n6) {
if (k1 & _1n6)
k1p = k1p.add(d);
if (k2 & _1n6)
k2p = k2p.add(d);
d = d.double();
k1 >>= _1n6;
k2 >>= _1n6;
}
if (k1neg)
k1p = k1p.negate();
if (k2neg)
k2p = k2p.negate();
k2p = new Point(Fp.mul(k2p.px, endo.beta), k2p.py, k2p.pz);
return k1p.add(k2p);
}
/**
* Constant time multiplication.
* Uses wNAF method. Windowed method may be 10% faster,
* but takes 2x longer to generate and consumes 2x memory.
* Uses precomputes when available.
* Uses endomorphism for Koblitz curves.
* @param scalar by which the point would be multiplied
* @returns New point
*/
multiply(scalar) {
const { endo, n: N } = CURVE;
aInRange("scalar", scalar, _1n6, N);
let point, fake;
if (endo) {
const { k1neg, k1, k2neg, k2 } = endo.splitScalar(scalar);
let { p: k1p, f: f1p } = this.wNAF(k1);
let { p: k2p, f: f2p } = this.wNAF(k2);
k1p = wnaf.constTimeNegate(k1neg, k1p);
k2p = wnaf.constTimeNegate(k2neg, k2p);
k2p = new Point(Fp.mul(k2p.px, endo.beta), k2p.py, k2p.pz);
point = k1p.add(k2p);
fake = f1p.add(f2p);
} else {
const { p, f } = this.wNAF(scalar);
point = p;
fake = f;
}
return Point.normalizeZ([point, fake])[0];
}
/**
* Efficiently calculate `aP + bQ`. Unsafe, can expose private key, if used incorrectly.
* Not using Strauss-Shamir trick: precomputation tables are faster.
* The trick could be useful if both P and Q are not G (not in our case).
* @returns non-zero affine point
*/
multiplyAndAddUnsafe(Q, a, b) {
const G = Point.BASE;
const mul = (P, a2) => a2 === _0n6 || a2 === _1n6 || !P.equals(G) ? P.multiplyUnsafe(a2) : P.multiply(a2);
const sum = mul(this, a).add(mul(Q, b));
return sum.is0() ? void 0 : sum;
}
// Converts Projective point to affine (x, y) coordinates.
// Can accept precomputed Z^-1 - for example, from invertBatch.
// (x, y, z) ∋ (x=x/z, y=y/z)
toAffine(iz) {
return toAffineMemo(this, iz);
}
isTorsionFree() {
const { h: cofactor, isTorsionFree } = CURVE;
if (cofactor === _1n6)
return true;
if (isTorsionFree)
return isTorsionFree(Point, this);
throw new Error("isTorsionFree() has not been declared for the elliptic curve");
}
clearCofactor() {
const { h: cofactor, clearCofactor } = CURVE;
if (cofactor === _1n6)
return this;
if (clearCofactor)
return clearCofactor(Point, this);
return this.multiplyUnsafe(CURVE.h);
}
toRawBytes(isCompressed = true) {
abool("isCompressed", isCompressed);
this.assertValidity();
return toBytes2(Point, this, isCompressed);
}
toHex(isCompressed = true) {
abool("isCompressed", isCompressed);
return bytesToHex(this.toRawBytes(isCompressed));
}
}
Point.BASE = new Point(CURVE.Gx, CURVE.Gy, Fp.ONE);
Point.ZERO = new Point(Fp.ZERO, Fp.ONE, Fp.ZERO);
const _bits = CURVE.nBitLength;
const wnaf = wNAF(Point, CURVE.endo ? Math.ceil(_bits / 2) : _bits);
return {
CURVE,
ProjectivePoint: Point,
normPrivateKeyToScalar,
weierstrassEquation,
isWithinCurveOrder
};
}
// node_modules/@noble/curves/esm/abstract/bls.js
var _0n7 = BigInt(0);
var _1n7 = BigInt(1);
var _2n6 = BigInt(2);
var _3n4 = BigInt(3);
function NAfDecomposition(a) {
const res = [];
for (; a > _1n7; a >>= _1n7) {
if ((a & _1n7) === _0n7)
res.unshift(0);
else if ((a & _3n4) === _3n4) {
res.unshift(-1);
a += _1n7;
} else
res.unshift(1);
}
return res;
}
function bls(CURVE) {
const { Fp, Fr, Fp2, Fp6, Fp12 } = CURVE.fields;
const BLS_X_IS_NEGATIVE = CURVE.params.xNegative;
const TWIST = CURVE.params.twistType;
const G1_ = weierstrassPoints({ n: Fr.ORDER, ...CURVE.G1 });
const G1 = Object.assign(G1_, createHasher(G1_.ProjectivePoint, CURVE.G1.mapToCurve, {
...CURVE.htfDefaults,
...CURVE.G1.htfDefaults
}));
const G2_ = weierstrassPoints({ n: Fr.ORDER, ...CURVE.G2 });
const G22 = Object.assign(G2_, createHasher(G2_.ProjectivePoint, CURVE.G2.mapToCurve, {
...CURVE.htfDefaults,
...CURVE.G2.htfDefaults
}));
let lineFunction;
if (TWIST === "multiplicative") {
lineFunction = (c0, c1, c2, f, Px, Py) => Fp12.mul014(f, c0, Fp2.mul(c1, Px), Fp2.mul(c2, Py));
} else if (TWIST === "divisive") {
lineFunction = (c0, c1, c2, f, Px, Py) => Fp12.mul034(f, Fp2.mul(c2, Py), Fp2.mul(c1, Px), c0);
} else
throw new Error("bls: unknown twist type");
const Fp2div2 = Fp2.div(Fp2.ONE, Fp2.mul(Fp2.ONE, _2n6));
function pointDouble(ell, Rx, Ry, Rz) {
const t0 = Fp2.sqr(Ry);
const t1 = Fp2.sqr(Rz);
const t2 = Fp2.mulByB(Fp2.mul(t1, _3n4));
const t3 = Fp2.mul(t2, _3n4);
const t4 = Fp2.sub(Fp2.sub(Fp2.sqr(Fp2.add(Ry, Rz)), t1), t0);
const c0 = Fp2.sub(t2, t0);
const c1 = Fp2.mul(Fp2.sqr(Rx), _3n4);
const c2 = Fp2.neg(t4);
ell.push([c0, c1, c2]);
Rx = Fp2.mul(Fp2.mul(Fp2.mul(Fp2.sub(t0, t3), Rx), Ry), Fp2div2);
Ry = Fp2.sub(Fp2.sqr(Fp2.mul(Fp2.add(t0, t3), Fp2div2)), Fp2.mul(Fp2.sqr(t2), _3n4));
Rz = Fp2.mul(t0, t4);
return { Rx, Ry, Rz };
}
function pointAdd(ell, Rx, Ry, Rz, Qx, Qy) {
const t0 = Fp2.sub(Ry, Fp2.mul(Qy, Rz));
const t1 = Fp2.sub(Rx, Fp2.mul(Qx, Rz));
const c0 = Fp2.sub(Fp2.mul(t0, Qx), Fp2.mul(t1, Qy));
const c1 = Fp2.neg(t0);
const c2 = t1;
ell.push([c0, c1, c2]);
const t2 = Fp2.sqr(t1);
const t3 = Fp2.mul(t2, t1);
const t4 = Fp2.mul(t2, Rx);
const t5 = Fp2.add(Fp2.sub(t3, Fp2.mul(t4, _2n6)), Fp2.mul(Fp2.sqr(t0), Rz));
Rx = Fp2.mul(t1, t5);
Ry = Fp2.sub(Fp2.mul(Fp2.sub(t4, t5), t0), Fp2.mul(t3, Ry));
Rz = Fp2.mul(Rz, t3);
return { Rx, Ry, Rz };
}
const ATE_NAF = NAfDecomposition(CURVE.params.ateLoopSize);
const calcPairingPrecomputes = memoized((point) => {
const p = point;
const { x, y } = p.toAffine();
const Qx = x, Qy = y, negQy = Fp2.neg(y);
let Rx = Qx, Ry = Qy, Rz = Fp2.ONE;
const ell = [];
for (const bit of ATE_NAF) {
const cur = [];
({ Rx, Ry, Rz } = pointDouble(cur, Rx, Ry, Rz));
if (bit)
({ Rx, Ry, Rz } = pointAdd(cur, Rx, Ry, Rz, Qx, bit === -1 ? negQy : Qy));
ell.push(cur);
}
if (CURVE.postPrecompute) {
const last = ell[ell.length - 1];
CURVE.postPrecompute(Rx, Ry, Rz, Qx, Qy, pointAdd.bind(null, last));
}
return ell;
});
function millerLoopBatch(pairs, withFinalExponent = false) {
let f12 = Fp12.ONE;
if (pairs.length) {
const ellLen = pairs[0][0].length;
for (let i = 0; i < ellLen; i++) {
f12 = Fp12.sqr(f12);
for (const [ell, Px, Py] of pairs) {
for (const [c0, c1, c2] of ell[i])
f12 = lineFunction(c0, c1, c2, f12, Px, Py);
}
}
}
if (BLS_X_IS_NEGATIVE)
f12 = Fp12.conjugate(f12);
return withFinalExponent ? Fp12.finalExponentiate(f12) : f12;
}
function pairingBatch(pairs, withFinalExponent = true) {
const res = [];
G1.ProjectivePoint.normalizeZ(pairs.map(({ g1 }) => g1));
G22.ProjectivePoint.normalizeZ(pairs.map(({ g2 }) => g2));
for (const { g1, g2 } of pairs) {
if (g1.equals(G1.ProjectivePoint.ZERO) || g2.equals(G22.ProjectivePoint.ZERO))
throw new Error("pairing is not available for ZERO point");
g1.assertValidity();
g2.assertValidity();
const Qa = g1.toAffine();
res.push([calcPairingPrecomputes(g2), Qa.x, Qa.y]);
}
return millerLoopBatch(res, withFinalExponent);
}
function pairing(Q, P, withFinalExponent = true) {
return pairingBatch([{ g1: Q, g2: P }], withFinalExponent);
}
const utils = {
randomPrivateKey: () => {
const length = getMinHashLength(Fr.ORDER);
return mapHashToField(CURVE.randomBytes(length), Fr.ORDER);
},
calcPairingPrecomputes
};
const { ShortSignature } = CURVE.G1;
const { Signature } = CURVE.G2;
function normP1(point) {
return point instanceof G1.ProjectivePoint ? point : G1.ProjectivePoint.fromHex(point);
}
function normP1Hash(point, htfOpts) {
return point instanceof G1.ProjectivePoint ? point : G1.hashToCurve(ensureBytes("point", point), htfOpts);
}
function normP2(point) {
return point instanceof G22.ProjectivePoint ? point : Signature.fromHex(point);
}
function normP2Hash(point, htfOpts) {
return point instanceof G22.ProjectivePoint ? point : G22.hashToCurve(ensureBytes("point", point), htfOpts);
}
function getPublicKey(privateKey) {
return G1.ProjectivePoint.fromPrivateKey(privateKey).toRawBytes(true);
}
function getPublicKeyForShortSignatures(privateKey) {
return G22.ProjectivePoint.fromPrivateKey(privateKey).toRawBytes(true);
}
function sign(message, privateKey, htfOpts) {
const msgPoint = normP2Hash(message, htfOpts);
msgPoint.assertValidity();
const sigPoint = msgPoint.multiply(G1.normPrivateKeyToScalar(privateKey));
if (message instanceof G22.ProjectivePoint)
return sigPoint;
return Signature.toRawBytes(sigPoint);
}
function signShortSignature(message, privateKey, htfOpts) {
const msgPoint = normP1Hash(message, htfOpts);
msgPoint.assertValidity();
const sigPoint = msgPoint.multiply(G1.normPrivateKeyToScalar(privateKey));
if (message instanceof G1.ProjectivePoint)
return sigPoint;
return ShortSignature.toRawBytes(sigPoint);
}
function verify(signature, message, publicKey, htfOpts) {
const P = normP1(publicKey);
const Hm = normP2Hash(message, htfOpts);
const G = G1.ProjectivePoint.BASE;
const S = normP2(signature);
const exp = pairingBatch([
{ g1: P.negate(), g2: Hm },
// ePHM = pairing(P.negate(), Hm, false);
{ g1: G, g2: S }
// eGS = pairing(G, S, false);
]);
return Fp12.eql(exp, Fp12.ONE);
}
function verifyShortSignature(signature, message, publicKey, htfOpts) {
const P = normP2(publicKey);
const Hm = normP1Hash(message, htfOpts);
const G = G22.ProjectivePoint.BASE;
const S = normP1(signature);
const exp = pairingBatch([
{ g1: Hm, g2: P },
// eHmP = pairing(Hm, P, false);
{ g1: S, g2: G.negate() }
// eSG = pairing(S, G.negate(), false);
]);
return Fp12.eql(exp, Fp12.ONE);
}
function aggregatePublicKeys(publicKeys) {
if (!publicKeys.length)
throw new Error("Expected non-empty array");
const agg = publicKeys.map(normP1).reduce((sum, p) => sum.add(p), G1.ProjectivePoint.ZERO);
const aggAffine = agg;
if (publicKeys[0] instanceof G1.ProjectivePoint) {
aggAffine.assertValidity();
return aggAffine;
}
return aggAffine.toRawBytes(true);
}
function aggregateSignatures(signatures) {
if (!signatures.length)
throw new Error("Expected non-empty array");
const agg = signatures.map(normP2).reduce((sum, s) => sum.add(s), G22.ProjectivePoint.ZERO);
const aggAffine = agg;
if (signatures[0] instanceof G22.ProjectivePoint) {
aggAffine.assertValidity();
return aggAffine;
}
return Signature.toRawBytes(aggAffine);
}
function aggregateShortSignatures(signatures) {
if (!signatures.length)
throw new Error("Expected non-empty array");
const agg = signatures.map(normP1).reduce((sum, s) => sum.add(s), G1.ProjectivePoint.ZERO);
const aggAffine = agg;
if (signatures[0] instanceof G1.ProjectivePoint) {
aggAffine.assertValidity();
return aggAffine;
}
return ShortSignature.toRawBytes(aggAffine);
}
function verifyBatch(signature, messages, publicKeys, htfOpts) {
if (!messages.length)
throw new Error("Expected non-empty messages array");
if (publicKeys.length !== messages.length)
throw new Error("Pubkey count should equal msg count");
const sig = normP2(signature);
const nMessages = messages.map((i) => normP2Hash(i, htfOpts));
const nPublicKeys = publicKeys.map(normP1);
const messagePubKeyMap = /* @__PURE__ */ new Map();
for (let i = 0; i < nPublicKeys.length; i++) {
const pub = nPublicKeys[i];
const msg = nMessages[i];
let keys = messagePubKeyMap.get(msg);
if (keys === void 0) {
keys = [];
messagePubKeyMap.set(msg, keys);
}
keys.push(pub);
}
const paired = [];
try {
for (const [msg, keys] of messagePubKeyMap) {
const groupPublicKey = keys.reduce((acc, msg2) => acc.add(msg2));
paired.push({ g1: groupPublicKey, g2: msg });
}
paired.push({ g1: G1.ProjectivePoint.BASE.negate(), g2: sig });
return Fp12.eql(pairingBatch(paired), Fp12.ONE);
} catch {
return false;
}
}
G1.ProjectivePoint.BASE._setWindowSize(4);
return {
getPublicKey,
getPublicKeyForShortSignatures,
sign,
signShortSignature,
verify,
verifyBatch,
verifyShortSignature,
aggregatePublicKeys,
aggregateSignatures,
aggregateShortSignatures,
millerLoopBatch,
pairing,
pairingBatch,
G1,
G2: G22,
Signature,
ShortSignature,
fields: {
Fr,
Fp,
Fp2,
Fp6,
Fp12
},
params: {
ateLoopSize: CURVE.params.ateLoopSize,
r: CURVE.params.r,
G1b: CURVE.G1.b,
G2b: CURVE.G2.b
},
utils
};
}
// src/bn254.ts
var SEED = BigInt("4965661367192848881");
var G1_SVDW = mapToCurveSVDW(import_noble_bn254_drand.bn254.G1.CURVE, {
// Z = 1 satisfies the conditions described in https://datatracker.ietf.org/doc/html/rfc9380#svdw
z: import_noble_bn254_drand.bn254.G1.CURVE.Fp.ONE,
// c1, c2, c3, c4 are the SvdW constants described in https://datatracker.ietf.org/doc/html/rfc9380#straightline-svdw
// c1 = g(Z)
c1: import_noble_bn254_drand.bn254.G1.CURVE.Fp.create(
BigInt(4)
),
// c2 = -Z / 2
c2: import_noble_bn254_drand.bn254.G1.CURVE.Fp.create(
BigInt(
"10944121435919637611123202872628637544348155578648911831344518947322613104291"
)
),
// c3 = sqrt(-g(Z) * (3 * Z^2 + 4 * A)) # sgn0(c3) MUST equal 0
c3: import_noble_bn254_drand.bn254.G1.CURVE.Fp.create(
BigInt(
"8815841940592487685674414971303048083897117035520822607866"
)
),
// c4 = -4 * g(Z) / (3 * Z^2 + 4 * A)
c4: import_noble_bn254_drand.bn254.G1.CURVE.Fp.create(
BigInt(
"7296080957279758407415468581752425029565437052432607887563012631548408736189"
)
)
});
var G2_SVDW = mapToCurveSVDW(import_noble_bn254_drand.bn254.G2.CURVE, {
// Z = 1 satisfies the conditions described in https://datatracker.ietf.org/doc/html/rfc9380#svdw
z: import_noble_bn254_drand.bn254.G2.CURVE.Fp.ONE,
// c1, c2, c3, c4 are the SvdW constants described in https://datatracker.ietf.org/doc/html/rfc9380#straightline-svdw
// c1 = g(Z)
c1: import_noble_bn254_drand.bn254.G2.CURVE.Fp.create(
{ c0: BigInt("19485874751759354771024239261021720505790618469301721065564631296452457478374"), c1: BigInt("266929791119991161246907387137283842545076965332900288569378510910307636690") }
),
// c2 = -Z / 2
c2: import_noble_bn254_drand.bn254.G2.CURVE.Fp.create(
{ c0: BigInt("10944121435919637611123202872628637544348155578648911831344518947322613104291"), c1: BigInt(0) }
),
// c3 = sqrt(-g(Z) * (3 * Z^2 + 4 * A)) # sgn0(c3) MUST equal 0
c3: import_noble_bn254_drand.bn254.G2.CURVE.Fp.create(
{ c0: BigInt("18992192239972082890849143911285057164064277369389217330423471574879236301292"), c1: BigInt("21819008332247140148575583693947636719449476128975323941588917397607662637108") }
),
// c4 = -4 * g(Z) / (3 * Z^2 + 4 * A)
c4: import_noble_bn254_drand.bn254.G2.CURVE.Fp.create(
{ c0: BigInt("10499238450719652342378357227399831140106360636427411350395554762472100376473"), c1: BigInt("6940174569119770192419592065569379906172001098655407502803841283667998553941") }
)
});
var htfDefaultsG1 = Object.freeze({
// DST: a domain separation tag defined in section 2.2.5
DST: "BN254G1_XMD:KECCAK-256_SVDW_RO_",
p: import_noble_bn254_drand.bn254.fields.Fp.ORDER,
m: 1,
k: 128,
expand: "xmd",
hash: keccak_256
});
var htfDefaultsG2 = Object.freeze({
// DST: a domain separation tag defined in section 2.2.5
DST: "BN254G2_XMD:KECCAK-256_SVDW_RO_",
p: import_noble_bn254_drand.bn254.fields.Fp.ORDER,
m: 2,
k: 128,
expand: "xmd",
hash: keccak_256
});
var { G2psi, G2psi2, psi } = psiFrobenius(import_noble_bn254_drand.bn254.fields.Fp, import_noble_bn254_drand.bn254.fields.Fp2, import_noble_bn254_drand.bn254.fields.Fp2.create({ c0: BigInt(9), c1: BigInt(1) }));
var bn254 = bls({
// Fields
fields: { Fp: import_noble_bn254_drand.bn254.fields.Fp, Fp2: import_noble_bn254_drand.bn254.fields.Fp2, Fp6: import_noble_bn254_drand.bn254.fields.Fp6, Fp12: import_noble_bn254_drand.bn254.fields.Fp12, Fr: import_noble_bn254_drand.bn254.fields.Fr },
G1: {
...import_noble_bn254_drand.bn254.G1.CURVE,
htfDefaults: htfDefaultsG1,
ShortSignature: import_noble_bn254_drand.bn254.ShortSignature,
mapToCurve: (scalars) => {
return G1_SVDW(import_noble_bn254_drand.bn254.G1.CURVE.Fp.create(scalars[0]));
}
},
G2: {
...import_noble_bn254_drand.bn254.G2.CURVE,
htfDefaults: htfDefaultsG2,
mapToCurve: (scalars) => {
const u = import_noble_bn254_drand.bn254.G2.CURVE.Fp.create(
{ c0: scalars[0], c1: scalars[1] }
);
return G2_SVDW(u);
},
// Maps the point into the prime-order subgroup G2.
/// Based on http://cacr.uwaterloo.ca/techreports/2011/cacr2011-26.pdf, 6.1
/// Adapted from: https://github.com/nikkolasg/bn254_hash2curve/blob/5995e36149b0119fa2a97dfcc00758729f00cc93/src/hash2g2.rs#L291
clearCofactor: (c, P) => {
const x = SEED;
const p0 = P.multiplyUnsafe(x);
const p1 = G2psi(c, p0.add(p0.double()));
const p2 = G2psi2(c, p0);
const p3 = G2psi(c, G2psi2(c, P));
return p0.add(p1.add(p2.add(p3)));
},
Signature: import_noble_bn254_drand.bn254.Signature
},
params: {
...import_noble_bn254_drand.bn254.params,
xNegative: false,
twistType: "divisive"
},
htfDefaults: htfDefaultsG1,
hash: htfDefaultsG1.hash,
randomBytes,
postPrecompute: (Rx, Ry, Rz, Qx, Qy, pointAdd) => {
const q = psi(Qx, Qy);
({ Rx, Ry, Rz } = pointAdd(Rx, Ry, Rz, q[0], q[1]));
const q2 = psi(q[0], q[1]);
pointAdd(Rx, Ry, Rz, q2[0], import_noble_bn254_drand.bn254.fields.Fp2.neg(q2[1]));
}
});
function mapToG1(scalars) {
return G1_SVDW(import_noble_bn254_drand.bn254.G1.CURVE.Fp.create(scalars[0]));
}
function mapToCurveSVDW(CG, opts) {
const Fp = CG.Fp;
const is_square = FpIsSquare(Fp);
validateField(Fp);
if (!Fp.isValid(CG.a) || !Fp.isValid(CG.b) || !Fp.isValid(opts.z))
throw new Error("mapToCurveSimpleSVDW: invalid opts");
if (!Fp.isOdd) throw new Error("Fp.isOdd is not implemented!");
const c1 = Fp.create(opts.c1);
const c2 = Fp.create(opts.c2);
const c3 = Fp.create(opts.c3);
const c4 = Fp.create(opts.c4);
return (_u) => {
const u = Fp.create(_u);
let tv1 = Fp.sqr(u);
tv1 = Fp.mul(tv1, c1);
const tv2 = Fp.add(Fp.ONE, tv1);
tv1 = Fp.sub(Fp.ONE, tv1);
let tv3 = Fp.mul(tv1, tv2);
tv3 = Fp.inv(tv3);
let tv4 = Fp.mul(u, tv1);
tv4 = Fp.mul(tv4, tv3);
tv4 = Fp.mul(tv4, c3);
const x1 = Fp.sub(c2, tv4);
let gx1 = Fp.sqr(x1);
gx1 = Fp.add(gx1, CG.a);
gx1 = Fp.mul(gx1, x1);
gx1 = Fp.add(gx1, CG.b);
const e1 = is_square(gx1);
const x2 = Fp.add(c2, tv4);
let gx2 = Fp.sqr(x2);
gx2 = Fp.add(gx2, CG.a);
gx2 = Fp.mul(gx2, x2);
gx2 = Fp.add(gx2, CG.b);
const e2 = is_square(gx2) && !e1;
let x3 = Fp.sqr(tv2);
x3 = Fp.mul(x3, tv3);
x3 = Fp.sqr(x3);
x3 = Fp.mul(x3, c4);
x3 = Fp.add(x3, opts.z);
let x = Fp.cmov(x3, x1, e1);
x = Fp.cmov(x, x2, e2);
let gx = Fp.sqr(x);
gx = Fp.add(gx, CG.a);
gx = Fp.mul(gx, x);
gx = Fp.add(gx, CG.b);
let y = Fp.sqrt(gx);
const e3 = Fp.isOdd?.(u) == Fp.isOdd?.(y);
y = Fp.cmov(Fp.neg(y), y, e3);
return { x, y };
};
}
// src/util.ts
function xor(a, b) {
if (a.length != b.length) {
throw new Error("Error: incompatible sizes");
}
const ret = new Uint8Array(a.length);
for (let i = 0; i < a.length; i++) {
ret[i] = a[i] ^ b[i];
}
return ret;
}
// src/crypto.ts
var textEncoder = new TextEncoder();
var DEFAULT_OPTS = {
hash: keccak_256,
k: 128,
expand_fn: "xmd",
dsts: {
H1_G1: textEncoder.encode("IBE_BN254G1_XMD:KECCAK-256_SVDW_RO_H1_"),
H2: textEncoder.encode("IBE_BN254_XMD:KECCAK-256_H2_"),
H3: textEncoder.encode("IBE_BN254_XMD:KECCAK-256_H3_"),
H4: textEncoder.encode("IBE_BN254_XMD:KECCAK-256_H4_")
}
};
var H4_MAX_OUTPUT_LEN = 65535;
function createIdentity(identity, opts) {
return hashIdentityToG1(identity, opts);
}
function encrypt(m, identity, publicKey, opts) {
const n_bytes = m.length;
if (n_bytes > H4_MAX_OUTPUT_LEN) {
throw new Error(`cannot encrypt messages larger than our hash output: ${H4_MAX_OUTPUT_LEN} bytes.`);
}
const pk_g2p = bn254.G2.ProjectivePoint.fromAffine(publicKey);
const pk_rho = bn254.pairing(identity, pk_g2p);
const sigma = new Uint8Array(32);
crypto.getRandomValues(sigma);
const r = hashSigmaMToField(sigma, m, opts);
const u_g2 = bn254.G2.ProjectivePoint.BASE.multiply(r).toAffine();
const sharedKey = bn254.fields.Fp12.pow(pk_rho, r);
const v = xor(sigma, hashToBytes(sharedKey, sigma.length, opts));
const w = xor(m, hashSigmaToBytes(sigma, n_bytes, opts));
return {
U: u_g2,
V: v,
W: w
};
}
function decrypt(ciphertext, decryptionKey, opts = DEFAULT_OPTS) {
const key = preprocessDecryptionKey(ciphertext, decryptionKey, opts);
return decryptWithPreprocess(ciphertext, key, opts);
}
function decryptWithPreprocess(ciphertext, preprocessedDecryptionKey, opts = DEFAULT_OPTS) {
if (ciphertext.W.length > H4_MAX_OUTPUT_LEN) {
throw new Error(`cannot decrypt messages larger than our hash output: ${H4_MAX_OUTPUT_LEN} bytes.`);
}
if (ciphertext.V.length !== opts.hash.outputLen) {
throw new Error(`cannot decrypt encryption key of invalid length != ${opts.hash.outputLen} bytes.`);
}
if (ciphertext.V.length !== preprocessedDecryptionKey.length) {
throw new Error(`preprocessed decryption key of invalid length`);
}
const ell_bytes = ciphertext.W.length;
const sigma2 = xor(ciphertext.V, preprocessedDecryptionKey);
const m2 = xor(ciphertext.W, hashSigmaToBytes(sigma2, ell_bytes, opts));
const r = hashSigmaMToField(sigma2, m2, opts);
const u_g2 = bn254.G2.ProjectivePoint.BASE.multiply(r);
if (bn254.G2.ProjectivePoint.fromAffine(ciphertext.U).equals(u_g2)) {
return m2;
} else {
throw new Error("invalid proof: rP check failed");
}
}
function preprocessDecryptionKey(ciphertext, decryptionKey, opts = DEFAULT_OPTS) {
const u_g2p = bn254.G2.ProjectivePoint.fromAffine(ciphertext.U);
u_g2p.assertValidity();
const decryptionKeyPoint = bn254.G1.ProjectivePoint.fromAffine(decryptionKey);
const sharedKey = bn254.pairing(decryptionKeyPoint, u_g2p);
return hashToBytes(sharedKey, ciphertext.V.length, opts);
}
function hashIdentityToG1(identity, opts) {
const hasher = createHasher(bn254.G1.ProjectivePoint, mapToG1, {
p: htfDefaultsG1.p,
m: htfDefaultsG1.m,
hash: opts.hash,
k: opts.k,
DST: opts.dsts.H1_G1,
expand: opts.expand_fn
});
return bn254.G1.ProjectivePoint.fromAffine(hasher.hashToCurve(identity).toAffine());
}
function hashToBytes(shared_key, n, opts) {
if (opts.expand_fn == "xmd") {
return expand_message_xmd(bn254.fields.Fp12.toBytes(shared_key), opts.dsts.H2, n, opts.hash);
} else {
return expand_message_xof(bn254.fields.Fp12.toBytes(shared_key), opts.dsts.H2, n, opts.k, opts.hash);
}
}
function hashSigmaMToField(sigma, m, opts) {
const input = new Uint8Array(sigma.length + m.length);
input.set(sigma);
input.set(m, sigma.length);
return hash_to_field(input, 1, {
p: htfDefaultsG1.p,
m: htfDefaultsG1.m,
hash: opts.hash,
k: opts.k,
DST: opts.dsts.H3,
expand: opts.expand_fn
})[0][0];
}
function hashSigmaToBytes(sigma, n, opts) {
if (opts.expand_fn == "xmd") {
return expand_message_xmd(sigma, opts.dsts.H4, n, opts.hash);
} else {
return expand_message_xof(sigma, opts.dsts.H4, n, opts.k, opts.hash);
}
}
// src/ibe.ts
var IBE = class _IBE {
constructor(opts = DEFAULT_OPTS) {
this.opts = opts;
}
createIdentity(bytes) {
return {
i: createIdentity(bytes, this.opts),
m: bytes
};
}
createDecryptionKey(secretKey, identity) {
const sk = secretKey instanceof Uint8Array ? import_noble_bn254_drand2.bn254.fields.Fr.fromBytes(secretKey) : secretKey.sk;
return { bytes: import_noble_bn254_drand2.bn254.ShortSignature.toRawBytes(identity.i.multiply(sk)) };
}
isValidDecryptionKey(publicKey, decryptionKey, identity) {
const sig = decryptionKey instanceof Uint8Array ? decryptionKey : decryptionKey.bytes;
const pk = publicKey instanceof Uint8Array ? _IBE.parsePublicKey(publicKey) : publicKey;
const m = identity instanceof Uint8Array ? identity : identity.m;
return import_noble_bn254_drand2.bn254.verifyShortSignature(sig, m, import_noble_bn254_drand2.bn254.G2.ProjectivePoint.fromAffine(pk.p), { DST: this.opts.dsts.H1_G1 });
}
encrypt(message, identity, publicKey) {
return encrypt(message, identity.i, publicKey.p, this.opts);
}
decrypt(ciphertext, decryptionKey) {
try {
const key = decryptionKey instanceof Uint8Array ? decryptionKey : decryptionKey.bytes;
return decrypt(ciphertext, import_noble_bn254_drand2.bn254.G1.ProjectivePoint.fromHex(key).toAffine(), this.opts);
} catch (err) {
throw new Error("failed to decrypt the ciphertext - did you use the correct key?");
}
}
static parsePublicKey(bytes) {
return { p: import_noble_bn254_drand2.bn254.G2.ProjectivePoint.fromHex(bytes).toAffine() };
}
static parseDecryptionKey(bytes) {
return { bytes };
}
static parseSecretKey(sk) {
return { sk: sk instanceof Uint8Array ? import_noble_bn254_drand2.bn254.fields.Fr.fromBytes(sk) : sk };
}
static createSecretKey() {
return { sk: import_noble_bn254_drand2.bn254.fields.Fr.fromBytes(import_noble_bn254_drand2.bn254.utils.randomPrivateKey()) };
}
static createPublicKey(secretKey) {
return { p: import_noble_bn254_drand2.bn254.G2.ProjectivePoint.BASE.multiply(secretKey.sk).toAffine() };
}
};
// src/serde.ts
var asn1js = __toESM(require_build2(), 1);
var import_noble_bn254_drand3 = __toESM(require_src(), 1);
function serializeCiphertext(ct) {
const sequence = new asn1js.Sequence({
value: [
new asn1js.Sequence({
value: [
new asn1js.Sequence({
value: [
asn1js.Integer.fromBigInt(ct.U.x.c0),
asn1js.Integer.fromBigInt(ct.U.x.c1)
]
}),
new asn1js.Sequence({
value: [
asn1js.Integer.fromBigInt(ct.U.y.c0),
asn1js.Integer.fromBigInt(ct.U.y.c1)
]
})
]
}),
new asn1js.OctetString({ valueHex: ct.V }),
new asn1js.OctetString({ valueHex: ct.W })
]
});
return new Uint8Array(sequence.toBER());
}
function deserializeCiphertext(ct) {
const schema = new asn1js.Sequence({
name: "ciphertext",
value: [
new asn1js.Sequence({
name: "U",
value: [
new asn1js.Sequence({
name: "x",
value: [
new asn1js.Integer(),
new asn1js.Integer()
]
}),
new asn1js.Sequence({
name: "y",
value: [
new asn1js.Integer(),
new asn1js.Integer()
]
})
]
}),
new asn1js.OctetString({ name: "V" }),
new asn1js.OctetString({ name: "W" })
]
});
const res = asn1js.verifySchema(ct, schema);
if (!res.verified) {
throw new Error("invalid ciphertext");
}
const V = new Uint8Array(res.result["V"].valueBlock.valueHex);
const W = new Uint8Array(res.result["W"].valueBlock.valueHex);
function bytesToBigInt(bytes) {
const byteArray = Array.from(new Uint8Array(bytes));
const hex = byteArray.map((e) => e.toString(16).padStart(2, "0")).join("");
return BigInt("0x" + hex);
}
const x = import_noble_bn254_drand3.bn254.fields.Fp2.create({
c0: bytesToBigInt(res.result["x"].valueBlock.value[0].valueBlock.valueHex),
c1: bytesToBigInt(res.result["x"].valueBlock.value[1].valueBlock.valueHex)
});
const y = import_noble_bn254_drand3.bn254.fields.Fp2.create({
c0: bytesToBigInt(res.result["y"].valueBlock.value[0].valueBlock.valueHex),
c1: bytesToBigInt(res.result["y"].valueBlock.value[1].valueBlock.valueHex)
});
const U = { x, y };
return {
U,
V,
W
};
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
IBE,
deserializeCiphertext,
serializeCiphertext
});
/*! Bundled license information:
@noble/hashes/utils.js:
@noble/hashes/esm/utils.js:
(*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) *)
@noble/curves/abstract/utils.js:
@noble/curves/abstract/modular.js:
@noble/curves/abstract/curve.js:
@noble/curves/abstract/weierstrass.js:
@noble/curves/abstract/bls.js:
@noble/curves/abstract/tower.js:
@noble/curves/esm/abstract/utils.js:
@noble/curves/esm/abstract/modular.js:
@noble/curves/esm/abstract/tower.js:
@noble/curves/esm/abstract/curve.js:
@noble/curves/esm/abstract/weierstrass.js:
@noble/curves/esm/abstract/bls.js:
(*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) *)
pvtsutils/build/index.js:
(*!
* MIT License
*
* Copyright (c) 2017-2024 Peculiar Ventures, LLC
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
*)
pvutils/build/utils.js:
(*!
Copyright (c) Peculiar Ventures, LLC
*)
asn1js/build/index.js:
(*!
* Copyright (c) 2014, GMO GlobalSign
* Copyright (c) 2015-2022, Peculiar Ventures
* All rights reserved.
*
* Author 2014-2019, Yury Strozhevsky
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright notice, this
* list of conditions and the following disclaimer in the documentation and/or
* other materials provided with the distribution.
*
* * Neither the name of the copyright holder nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*)
*/
//# sourceMappingURL=index.cjs.map