nostr-relaypool
Version:
A Nostr RelayPool implementation in TypeScript using only nostr-tools library as a dependency.
11,595 lines • 314 kB
JavaScript
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 __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
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 __publicField = (obj, key, value) => {
__defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
return value;
};
var __accessCheck = (obj, member, msg) => {
if (!member.has(obj))
throw TypeError("Cannot " + msg);
};
var __privateAdd = (obj, member, value) => {
if (member.has(obj))
throw TypeError("Cannot add the same private member more than once");
member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
};
var __privateMethod = (obj, member, method) => {
__accessCheck(obj, member, "access private method");
return method;
};
// node_modules/safe-stable-stringify/index.js
var require_safe_stable_stringify = __commonJS({
"node_modules/safe-stable-stringify/index.js"(exports, module) {
"use strict";
var { hasOwnProperty } = Object.prototype;
var stringify2 = configure2();
stringify2.configure = configure2;
stringify2.stringify = stringify2;
stringify2.default = stringify2;
exports.stringify = stringify2;
exports.configure = configure2;
module.exports = stringify2;
var strEscapeSequencesRegExp = /[\u0000-\u001f\u0022\u005c\ud800-\udfff]|[\ud800-\udbff](?![\udc00-\udfff])|(?:[^\ud800-\udbff]|^)[\udc00-\udfff]/;
function strEscape(str) {
if (str.length < 5e3 && !strEscapeSequencesRegExp.test(str)) {
return `"${str}"`;
}
return JSON.stringify(str);
}
function insertSort(array) {
if (array.length > 200) {
return array.sort();
}
for (let i = 1; i < array.length; i++) {
const currentValue = array[i];
let position = i;
while (position !== 0 && array[position - 1] > currentValue) {
array[position] = array[position - 1];
position--;
}
array[position] = currentValue;
}
return array;
}
var typedArrayPrototypeGetSymbolToStringTag = Object.getOwnPropertyDescriptor(
Object.getPrototypeOf(
Object.getPrototypeOf(
new Int8Array()
)
),
Symbol.toStringTag
).get;
function isTypedArrayWithEntries(value) {
return typedArrayPrototypeGetSymbolToStringTag.call(value) !== void 0 && value.length !== 0;
}
function stringifyTypedArray(array, separator, maximumBreadth) {
if (array.length < maximumBreadth) {
maximumBreadth = array.length;
}
const whitespace = separator === "," ? "" : " ";
let res = `"0":${whitespace}${array[0]}`;
for (let i = 1; i < maximumBreadth; i++) {
res += `${separator}"${i}":${whitespace}${array[i]}`;
}
return res;
}
function getCircularValueOption(options) {
if (hasOwnProperty.call(options, "circularValue")) {
const circularValue = options.circularValue;
if (typeof circularValue === "string") {
return `"${circularValue}"`;
}
if (circularValue == null) {
return circularValue;
}
if (circularValue === Error || circularValue === TypeError) {
return {
toString() {
throw new TypeError("Converting circular structure to JSON");
}
};
}
throw new TypeError('The "circularValue" argument must be of type string or the value null or undefined');
}
return '"[Circular]"';
}
function getBooleanOption(options, key) {
let value;
if (hasOwnProperty.call(options, key)) {
value = options[key];
if (typeof value !== "boolean") {
throw new TypeError(`The "${key}" argument must be of type boolean`);
}
}
return value === void 0 ? true : value;
}
function getPositiveIntegerOption(options, key) {
let value;
if (hasOwnProperty.call(options, key)) {
value = options[key];
if (typeof value !== "number") {
throw new TypeError(`The "${key}" argument must be of type number`);
}
if (!Number.isInteger(value)) {
throw new TypeError(`The "${key}" argument must be an integer`);
}
if (value < 1) {
throw new RangeError(`The "${key}" argument must be >= 1`);
}
}
return value === void 0 ? Infinity : value;
}
function getItemCount(number6) {
if (number6 === 1) {
return "1 item";
}
return `${number6} items`;
}
function getUniqueReplacerSet(replacerArray) {
const replacerSet = /* @__PURE__ */ new Set();
for (const value of replacerArray) {
if (typeof value === "string" || typeof value === "number") {
replacerSet.add(String(value));
}
}
return replacerSet;
}
function getStrictOption(options) {
if (hasOwnProperty.call(options, "strict")) {
const value = options.strict;
if (typeof value !== "boolean") {
throw new TypeError('The "strict" argument must be of type boolean');
}
if (value) {
return (value2) => {
let message = `Object can not safely be stringified. Received type ${typeof value2}`;
if (typeof value2 !== "function")
message += ` (${value2.toString()})`;
throw new Error(message);
};
}
}
}
function configure2(options) {
options = { ...options };
const fail = getStrictOption(options);
if (fail) {
if (options.bigint === void 0) {
options.bigint = false;
}
if (!("circularValue" in options)) {
options.circularValue = Error;
}
}
const circularValue = getCircularValueOption(options);
const bigint = getBooleanOption(options, "bigint");
const deterministic = getBooleanOption(options, "deterministic");
const maximumDepth = getPositiveIntegerOption(options, "maximumDepth");
const maximumBreadth = getPositiveIntegerOption(options, "maximumBreadth");
function stringifyFnReplacer(key, parent, stack, replacer, spacer, indentation) {
let value = parent[key];
if (typeof value === "object" && value !== null && typeof value.toJSON === "function") {
value = value.toJSON(key);
}
value = replacer.call(parent, key, value);
switch (typeof value) {
case "string":
return strEscape(value);
case "object": {
if (value === null) {
return "null";
}
if (stack.indexOf(value) !== -1) {
return circularValue;
}
let res = "";
let join4 = ",";
const originalIndentation = indentation;
if (Array.isArray(value)) {
if (value.length === 0) {
return "[]";
}
if (maximumDepth < stack.length + 1) {
return '"[Array]"';
}
stack.push(value);
if (spacer !== "") {
indentation += spacer;
res += `
${indentation}`;
join4 = `,
${indentation}`;
}
const maximumValuesToStringify = Math.min(value.length, maximumBreadth);
let i = 0;
for (; i < maximumValuesToStringify - 1; i++) {
const tmp2 = stringifyFnReplacer(String(i), value, stack, replacer, spacer, indentation);
res += tmp2 !== void 0 ? tmp2 : "null";
res += join4;
}
const tmp = stringifyFnReplacer(String(i), value, stack, replacer, spacer, indentation);
res += tmp !== void 0 ? tmp : "null";
if (value.length - 1 > maximumBreadth) {
const removedKeys = value.length - maximumBreadth - 1;
res += `${join4}"... ${getItemCount(removedKeys)} not stringified"`;
}
if (spacer !== "") {
res += `
${originalIndentation}`;
}
stack.pop();
return `[${res}]`;
}
let keys = Object.keys(value);
const keyLength = keys.length;
if (keyLength === 0) {
return "{}";
}
if (maximumDepth < stack.length + 1) {
return '"[Object]"';
}
let whitespace = "";
let separator = "";
if (spacer !== "") {
indentation += spacer;
join4 = `,
${indentation}`;
whitespace = " ";
}
const maximumPropertiesToStringify = Math.min(keyLength, maximumBreadth);
if (deterministic && !isTypedArrayWithEntries(value)) {
keys = insertSort(keys);
}
stack.push(value);
for (let i = 0; i < maximumPropertiesToStringify; i++) {
const key2 = keys[i];
const tmp = stringifyFnReplacer(key2, value, stack, replacer, spacer, indentation);
if (tmp !== void 0) {
res += `${separator}${strEscape(key2)}:${whitespace}${tmp}`;
separator = join4;
}
}
if (keyLength > maximumBreadth) {
const removedKeys = keyLength - maximumBreadth;
res += `${separator}"...":${whitespace}"${getItemCount(removedKeys)} not stringified"`;
separator = join4;
}
if (spacer !== "" && separator.length > 1) {
res = `
${indentation}${res}
${originalIndentation}`;
}
stack.pop();
return `{${res}}`;
}
case "number":
return isFinite(value) ? String(value) : fail ? fail(value) : "null";
case "boolean":
return value === true ? "true" : "false";
case "undefined":
return void 0;
case "bigint":
if (bigint) {
return String(value);
}
default:
return fail ? fail(value) : void 0;
}
}
function stringifyArrayReplacer(key, value, stack, replacer, spacer, indentation) {
if (typeof value === "object" && value !== null && typeof value.toJSON === "function") {
value = value.toJSON(key);
}
switch (typeof value) {
case "string":
return strEscape(value);
case "object": {
if (value === null) {
return "null";
}
if (stack.indexOf(value) !== -1) {
return circularValue;
}
const originalIndentation = indentation;
let res = "";
let join4 = ",";
if (Array.isArray(value)) {
if (value.length === 0) {
return "[]";
}
if (maximumDepth < stack.length + 1) {
return '"[Array]"';
}
stack.push(value);
if (spacer !== "") {
indentation += spacer;
res += `
${indentation}`;
join4 = `,
${indentation}`;
}
const maximumValuesToStringify = Math.min(value.length, maximumBreadth);
let i = 0;
for (; i < maximumValuesToStringify - 1; i++) {
const tmp2 = stringifyArrayReplacer(String(i), value[i], stack, replacer, spacer, indentation);
res += tmp2 !== void 0 ? tmp2 : "null";
res += join4;
}
const tmp = stringifyArrayReplacer(String(i), value[i], stack, replacer, spacer, indentation);
res += tmp !== void 0 ? tmp : "null";
if (value.length - 1 > maximumBreadth) {
const removedKeys = value.length - maximumBreadth - 1;
res += `${join4}"... ${getItemCount(removedKeys)} not stringified"`;
}
if (spacer !== "") {
res += `
${originalIndentation}`;
}
stack.pop();
return `[${res}]`;
}
stack.push(value);
let whitespace = "";
if (spacer !== "") {
indentation += spacer;
join4 = `,
${indentation}`;
whitespace = " ";
}
let separator = "";
for (const key2 of replacer) {
const tmp = stringifyArrayReplacer(key2, value[key2], stack, replacer, spacer, indentation);
if (tmp !== void 0) {
res += `${separator}${strEscape(key2)}:${whitespace}${tmp}`;
separator = join4;
}
}
if (spacer !== "" && separator.length > 1) {
res = `
${indentation}${res}
${originalIndentation}`;
}
stack.pop();
return `{${res}}`;
}
case "number":
return isFinite(value) ? String(value) : fail ? fail(value) : "null";
case "boolean":
return value === true ? "true" : "false";
case "undefined":
return void 0;
case "bigint":
if (bigint) {
return String(value);
}
default:
return fail ? fail(value) : void 0;
}
}
function stringifyIndent(key, value, stack, spacer, indentation) {
switch (typeof value) {
case "string":
return strEscape(value);
case "object": {
if (value === null) {
return "null";
}
if (typeof value.toJSON === "function") {
value = value.toJSON(key);
if (typeof value !== "object") {
return stringifyIndent(key, value, stack, spacer, indentation);
}
if (value === null) {
return "null";
}
}
if (stack.indexOf(value) !== -1) {
return circularValue;
}
const originalIndentation = indentation;
if (Array.isArray(value)) {
if (value.length === 0) {
return "[]";
}
if (maximumDepth < stack.length + 1) {
return '"[Array]"';
}
stack.push(value);
indentation += spacer;
let res2 = `
${indentation}`;
const join5 = `,
${indentation}`;
const maximumValuesToStringify = Math.min(value.length, maximumBreadth);
let i = 0;
for (; i < maximumValuesToStringify - 1; i++) {
const tmp2 = stringifyIndent(String(i), value[i], stack, spacer, indentation);
res2 += tmp2 !== void 0 ? tmp2 : "null";
res2 += join5;
}
const tmp = stringifyIndent(String(i), value[i], stack, spacer, indentation);
res2 += tmp !== void 0 ? tmp : "null";
if (value.length - 1 > maximumBreadth) {
const removedKeys = value.length - maximumBreadth - 1;
res2 += `${join5}"... ${getItemCount(removedKeys)} not stringified"`;
}
res2 += `
${originalIndentation}`;
stack.pop();
return `[${res2}]`;
}
let keys = Object.keys(value);
const keyLength = keys.length;
if (keyLength === 0) {
return "{}";
}
if (maximumDepth < stack.length + 1) {
return '"[Object]"';
}
indentation += spacer;
const join4 = `,
${indentation}`;
let res = "";
let separator = "";
let maximumPropertiesToStringify = Math.min(keyLength, maximumBreadth);
if (isTypedArrayWithEntries(value)) {
res += stringifyTypedArray(value, join4, maximumBreadth);
keys = keys.slice(value.length);
maximumPropertiesToStringify -= value.length;
separator = join4;
}
if (deterministic) {
keys = insertSort(keys);
}
stack.push(value);
for (let i = 0; i < maximumPropertiesToStringify; i++) {
const key2 = keys[i];
const tmp = stringifyIndent(key2, value[key2], stack, spacer, indentation);
if (tmp !== void 0) {
res += `${separator}${strEscape(key2)}: ${tmp}`;
separator = join4;
}
}
if (keyLength > maximumBreadth) {
const removedKeys = keyLength - maximumBreadth;
res += `${separator}"...": "${getItemCount(removedKeys)} not stringified"`;
separator = join4;
}
if (separator !== "") {
res = `
${indentation}${res}
${originalIndentation}`;
}
stack.pop();
return `{${res}}`;
}
case "number":
return isFinite(value) ? String(value) : fail ? fail(value) : "null";
case "boolean":
return value === true ? "true" : "false";
case "undefined":
return void 0;
case "bigint":
if (bigint) {
return String(value);
}
default:
return fail ? fail(value) : void 0;
}
}
function stringifySimple(key, value, stack) {
switch (typeof value) {
case "string":
return strEscape(value);
case "object": {
if (value === null) {
return "null";
}
if (typeof value.toJSON === "function") {
value = value.toJSON(key);
if (typeof value !== "object") {
return stringifySimple(key, value, stack);
}
if (value === null) {
return "null";
}
}
if (stack.indexOf(value) !== -1) {
return circularValue;
}
let res = "";
if (Array.isArray(value)) {
if (value.length === 0) {
return "[]";
}
if (maximumDepth < stack.length + 1) {
return '"[Array]"';
}
stack.push(value);
const maximumValuesToStringify = Math.min(value.length, maximumBreadth);
let i = 0;
for (; i < maximumValuesToStringify - 1; i++) {
const tmp2 = stringifySimple(String(i), value[i], stack);
res += tmp2 !== void 0 ? tmp2 : "null";
res += ",";
}
const tmp = stringifySimple(String(i), value[i], stack);
res += tmp !== void 0 ? tmp : "null";
if (value.length - 1 > maximumBreadth) {
const removedKeys = value.length - maximumBreadth - 1;
res += `,"... ${getItemCount(removedKeys)} not stringified"`;
}
stack.pop();
return `[${res}]`;
}
let keys = Object.keys(value);
const keyLength = keys.length;
if (keyLength === 0) {
return "{}";
}
if (maximumDepth < stack.length + 1) {
return '"[Object]"';
}
let separator = "";
let maximumPropertiesToStringify = Math.min(keyLength, maximumBreadth);
if (isTypedArrayWithEntries(value)) {
res += stringifyTypedArray(value, ",", maximumBreadth);
keys = keys.slice(value.length);
maximumPropertiesToStringify -= value.length;
separator = ",";
}
if (deterministic) {
keys = insertSort(keys);
}
stack.push(value);
for (let i = 0; i < maximumPropertiesToStringify; i++) {
const key2 = keys[i];
const tmp = stringifySimple(key2, value[key2], stack);
if (tmp !== void 0) {
res += `${separator}${strEscape(key2)}:${tmp}`;
separator = ",";
}
}
if (keyLength > maximumBreadth) {
const removedKeys = keyLength - maximumBreadth;
res += `${separator}"...":"${getItemCount(removedKeys)} not stringified"`;
}
stack.pop();
return `{${res}}`;
}
case "number":
return isFinite(value) ? String(value) : fail ? fail(value) : "null";
case "boolean":
return value === true ? "true" : "false";
case "undefined":
return void 0;
case "bigint":
if (bigint) {
return String(value);
}
default:
return fail ? fail(value) : void 0;
}
}
function stringify3(value, replacer, space) {
if (arguments.length > 1) {
let spacer = "";
if (typeof space === "number") {
spacer = " ".repeat(Math.min(space, 10));
} else if (typeof space === "string") {
spacer = space.slice(0, 10);
}
if (replacer != null) {
if (typeof replacer === "function") {
return stringifyFnReplacer("", { "": value }, [], replacer, spacer, "");
}
if (Array.isArray(replacer)) {
return stringifyArrayReplacer("", value, [], getUniqueReplacerSet(replacer), spacer, "");
}
}
if (spacer.length !== 0) {
return stringifyIndent("", value, [], spacer, "");
}
}
return stringifySimple("", value, []);
}
return stringify3;
}
}
});
// node_modules/safe-stable-stringify/esm/wrapper.js
var import__ = __toESM(require_safe_stable_stringify(), 1);
var configure = import__.default.configure;
var stringify = import__.default;
// merge-similar-filters.ts
function indexForFilter(filter, key) {
let new_filter = { ...filter };
delete new_filter[key];
return key + stringify(new_filter);
}
function mergeSimilarAndRemoveEmptyFilters(filters) {
let r = [];
let indexByFilter = /* @__PURE__ */ new Map();
let sets = [];
for (let filter of filters) {
let added = false;
for (let key in filter) {
if (
// @ts-ignore
filter[key] && (["ids", "authors", "kinds"].includes(key) || key.startsWith("#"))
) {
if (filter[key].length === 0) {
added = true;
break;
}
let index_by = indexForFilter(filter, key);
let index = indexByFilter.get(index_by);
if (index !== void 0) {
let extendedFilter = r[index];
for (let key2 in extendedFilter) {
if (key2 !== key) {
let index_by2 = indexForFilter(extendedFilter, key2);
indexByFilter.delete(index_by2);
}
}
if (r[index][key] instanceof Set) {
for (let v of filter[key]) {
r[index][key].add(v);
}
} else {
r[index][key] = new Set(r[index][key].concat(filter[key]));
sets.push([index, key]);
}
added = true;
break;
}
}
}
if (!added) {
for (let key in filter) {
if (
// @ts-ignore
filter[key] && (["ids", "authors", "kinds"].includes(key) || key.startsWith("#"))
) {
let index_by = indexForFilter(filter, key);
indexByFilter.set(index_by, r.length);
}
}
r.push({ ...filter });
}
}
for (let [index, key] of sets) {
r[index][key] = Array.from(r[index][key]);
}
return r;
}
// node_modules/@noble/curves/node_modules/@noble/hashes/esm/_assert.js
function number(n) {
if (!Number.isSafeInteger(n) || n < 0)
throw new Error(`Wrong positive integer: ${n}`);
}
function bool(b) {
if (typeof b !== "boolean")
throw new Error(`Expected boolean, not ${b}`);
}
function bytes(b, ...lengths) {
if (!(b instanceof Uint8Array))
throw new Error("Expected Uint8Array");
if (lengths.length > 0 && !lengths.includes(b.length))
throw new Error(`Expected Uint8Array of length ${lengths}, not of length=${b.length}`);
}
function hash(hash6) {
if (typeof hash6 !== "function" || typeof hash6.create !== "function")
throw new Error("Hash should be wrapped by utils.wrapConstructor");
number(hash6.outputLen);
number(hash6.blockLen);
}
function exists(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 output(out, instance) {
bytes(out);
const min = instance.outputLen;
if (out.length < min) {
throw new Error(`digestInto() expects output buffer of length at least ${min}`);
}
}
var assert = {
number,
bool,
bytes,
hash,
exists,
output
};
var assert_default = assert;
// node_modules/@noble/curves/node_modules/@noble/hashes/esm/crypto.js
var crypto2 = typeof globalThis === "object" && "crypto" in globalThis ? globalThis.crypto : void 0;
// node_modules/@noble/curves/node_modules/@noble/hashes/esm/utils.js
var u8a = (a) => a instanceof Uint8Array;
var createView = (arr) => new DataView(arr.buffer, arr.byteOffset, arr.byteLength);
var rotr = (word, shift) => word << 32 - shift | word >>> shift;
var isLE = new Uint8Array(new Uint32Array([287454020]).buffer)[0] === 68;
if (!isLE)
throw new Error("Non little-endian hardware is not supported");
var hexes = Array.from({ length: 256 }, (v, i) => i.toString(16).padStart(2, "0"));
function utf8ToBytes(str) {
if (typeof str !== "string")
throw new Error(`utf8ToBytes expected string, got ${typeof str}`);
return new Uint8Array(new TextEncoder().encode(str));
}
function toBytes(data) {
if (typeof data === "string")
data = utf8ToBytes(data);
if (!u8a(data))
throw new Error(`expected Uint8Array, got ${typeof data}`);
return data;
}
function concatBytes(...arrays) {
const r = new Uint8Array(arrays.reduce((sum, a) => sum + a.length, 0));
let pad = 0;
arrays.forEach((a) => {
if (!u8a(a))
throw new Error("Uint8Array expected");
r.set(a, pad);
pad += a.length;
});
return r;
}
var Hash = class {
// Safe version that clones internal state
clone() {
return this._cloneInto();
}
};
function wrapConstructor(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));
}
throw new Error("crypto.getRandomValues must be defined");
}
// node_modules/@noble/curves/node_modules/@noble/hashes/esm/_sha2.js
function setBigUint64(view, byteOffset, value, isLE6) {
if (typeof view.setBigUint64 === "function")
return view.setBigUint64(byteOffset, value, isLE6);
const _32n3 = BigInt(32);
const _u32_max = BigInt(4294967295);
const wh = Number(value >> _32n3 & _u32_max);
const wl = Number(value & _u32_max);
const h = isLE6 ? 4 : 0;
const l = isLE6 ? 0 : 4;
view.setUint32(byteOffset + h, wh, isLE6);
view.setUint32(byteOffset + l, wl, isLE6);
}
var SHA2 = class extends Hash {
constructor(blockLen, outputLen, padOffset, isLE6) {
super();
this.blockLen = blockLen;
this.outputLen = outputLen;
this.padOffset = padOffset;
this.isLE = isLE6;
this.finished = false;
this.length = 0;
this.pos = 0;
this.destroyed = false;
this.buffer = new Uint8Array(blockLen);
this.view = createView(this.buffer);
}
update(data) {
assert_default.exists(this);
const { view, buffer, blockLen } = this;
data = toBytes(data);
const len = data.length;
for (let pos = 0; pos < len; ) {
const take = Math.min(blockLen - this.pos, len - pos);
if (take === blockLen) {
const dataView = createView(data);
for (; blockLen <= len - pos; pos += blockLen)
this.process(dataView, pos);
continue;
}
buffer.set(data.subarray(pos, pos + take), this.pos);
this.pos += take;
pos += take;
if (this.pos === blockLen) {
this.process(view, 0);
this.pos = 0;
}
}
this.length += data.length;
this.roundClean();
return this;
}
digestInto(out) {
assert_default.exists(this);
assert_default.output(out, this);
this.finished = true;
const { buffer, view, blockLen, isLE: isLE6 } = this;
let { pos } = this;
buffer[pos++] = 128;
this.buffer.subarray(pos).fill(0);
if (this.padOffset > blockLen - pos) {
this.process(view, 0);
pos = 0;
}
for (let i = pos; i < blockLen; i++)
buffer[i] = 0;
setBigUint64(view, blockLen - 8, BigInt(this.length * 8), isLE6);
this.process(view, 0);
const oview = createView(out);
const len = this.outputLen;
if (len % 4)
throw new Error("_sha2: outputLen should be aligned to 32bit");
const outLen = len / 4;
const state = this.get();
if (outLen > state.length)
throw new Error("_sha2: outputLen bigger than state");
for (let i = 0; i < outLen; i++)
oview.setUint32(4 * i, state[i], isLE6);
}
digest() {
const { buffer, outputLen } = this;
this.digestInto(buffer);
const res = buffer.slice(0, outputLen);
this.destroy();
return res;
}
_cloneInto(to) {
to || (to = new this.constructor());
to.set(...this.get());
const { blockLen, buffer, length, finished, destroyed, pos } = this;
to.length = length;
to.pos = pos;
to.finished = finished;
to.destroyed = destroyed;
if (length % blockLen)
to.buffer.set(buffer);
return to;
}
};
// node_modules/@noble/curves/node_modules/@noble/hashes/esm/sha256.js
var Chi = (a, b, c) => a & b ^ ~a & c;
var Maj = (a, b, c) => a & b ^ a & c ^ b & c;
var SHA256_K = new Uint32Array([
1116352408,
1899447441,
3049323471,
3921009573,
961987163,
1508970993,
2453635748,
2870763221,
3624381080,
310598401,
607225278,
1426881987,
1925078388,
2162078206,
2614888103,
3248222580,
3835390401,
4022224774,
264347078,
604807628,
770255983,
1249150122,
1555081692,
1996064986,
2554220882,
2821834349,
2952996808,
3210313671,
3336571891,
3584528711,
113926993,
338241895,
666307205,
773529912,
1294757372,
1396182291,
1695183700,
1986661051,
2177026350,
2456956037,
2730485921,
2820302411,
3259730800,
3345764771,
3516065817,
3600352804,
4094571909,
275423344,
430227734,
506948616,
659060556,
883997877,
958139571,
1322822218,
1537002063,
1747873779,
1955562222,
2024104815,
2227730452,
2361852424,
2428436474,
2756734187,
3204031479,
3329325298
]);
var IV = new Uint32Array([
1779033703,
3144134277,
1013904242,
2773480762,
1359893119,
2600822924,
528734635,
1541459225
]);
var SHA256_W = new Uint32Array(64);
var SHA256 = class extends SHA2 {
constructor() {
super(64, 32, 8, false);
this.A = IV[0] | 0;
this.B = IV[1] | 0;
this.C = IV[2] | 0;
this.D = IV[3] | 0;
this.E = IV[4] | 0;
this.F = IV[5] | 0;
this.G = IV[6] | 0;
this.H = IV[7] | 0;
}
get() {
const { A, B, C, D, E, F, G, H } = this;
return [A, B, C, D, E, F, G, H];
}
// prettier-ignore
set(A, B, C, D, E, F, G, H) {
this.A = A | 0;
this.B = B | 0;
this.C = C | 0;
this.D = D | 0;
this.E = E | 0;
this.F = F | 0;
this.G = G | 0;
this.H = H | 0;
}
process(view, offset) {
for (let i = 0; i < 16; i++, offset += 4)
SHA256_W[i] = view.getUint32(offset, false);
for (let i = 16; i < 64; i++) {
const W15 = SHA256_W[i - 15];
const W2 = SHA256_W[i - 2];
const s0 = rotr(W15, 7) ^ rotr(W15, 18) ^ W15 >>> 3;
const s1 = rotr(W2, 17) ^ rotr(W2, 19) ^ W2 >>> 10;
SHA256_W[i] = s1 + SHA256_W[i - 7] + s0 + SHA256_W[i - 16] | 0;
}
let { A, B, C, D, E, F, G, H } = this;
for (let i = 0; i < 64; i++) {
const sigma1 = rotr(E, 6) ^ rotr(E, 11) ^ rotr(E, 25);
const T1 = H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i] | 0;
const sigma0 = rotr(A, 2) ^ rotr(A, 13) ^ rotr(A, 22);
const T2 = sigma0 + Maj(A, B, C) | 0;
H = G;
G = F;
F = E;
E = D + T1 | 0;
D = C;
C = B;
B = A;
A = T1 + T2 | 0;
}
A = A + this.A | 0;
B = B + this.B | 0;
C = C + this.C | 0;
D = D + this.D | 0;
E = E + this.E | 0;
F = F + this.F | 0;
G = G + this.G | 0;
H = H + this.H | 0;
this.set(A, B, C, D, E, F, G, H);
}
roundClean() {
SHA256_W.fill(0);
}
destroy() {
this.set(0, 0, 0, 0, 0, 0, 0, 0);
this.buffer.fill(0);
}
};
var SHA224 = class extends SHA256 {
constructor() {
super();
this.A = 3238371032 | 0;
this.B = 914150663 | 0;
this.C = 812702999 | 0;
this.D = 4144912697 | 0;
this.E = 4290775857 | 0;
this.F = 1750603025 | 0;
this.G = 1694076839 | 0;
this.H = 3204075428 | 0;
this.outputLen = 28;
}
};
var sha256 = wrapConstructor(() => new SHA256());
var sha224 = wrapConstructor(() => new SHA224());
// node_modules/@noble/curves/esm/abstract/utils.js
var utils_exports = {};
__export(utils_exports, {
bitGet: () => bitGet,
bitLen: () => bitLen,
bitMask: () => bitMask,
bitSet: () => bitSet,
bytesToHex: () => bytesToHex,
bytesToNumberBE: () => bytesToNumberBE,
bytesToNumberLE: () => bytesToNumberLE,
concatBytes: () => concatBytes2,
createHmacDrbg: () => createHmacDrbg,
ensureBytes: () => ensureBytes,
equalBytes: () => equalBytes,
hexToBytes: () => hexToBytes,
hexToNumber: () => hexToNumber,
numberToBytesBE: () => numberToBytesBE,
numberToBytesLE: () => numberToBytesLE,
numberToHexUnpadded: () => numberToHexUnpadded,
numberToVarBytesBE: () => numberToVarBytesBE,
utf8ToBytes: () => utf8ToBytes2,
validateObject: () => validateObject
});
var _0n = BigInt(0);
var _1n = BigInt(1);
var _2n = BigInt(2);
var u8a2 = (a) => a instanceof Uint8Array;
var hexes2 = Array.from({ length: 256 }, (v, i) => i.toString(16).padStart(2, "0"));
function bytesToHex(bytes6) {
if (!u8a2(bytes6))
throw new Error("Uint8Array expected");
let hex2 = "";
for (let i = 0; i < bytes6.length; i++) {
hex2 += hexes2[bytes6[i]];
}
return hex2;
}
function numberToHexUnpadded(num) {
const hex2 = num.toString(16);
return hex2.length & 1 ? `0${hex2}` : hex2;
}
function hexToNumber(hex2) {
if (typeof hex2 !== "string")
throw new Error("hex string expected, got " + typeof hex2);
return BigInt(hex2 === "" ? "0" : `0x${hex2}`);
}
function hexToBytes(hex2) {
if (typeof hex2 !== "string")
throw new Error("hex string expected, got " + typeof hex2);
const len = hex2.length;
if (len % 2)
throw new Error("padded hex string expected, got unpadded hex of length " + len);
const array = new Uint8Array(len / 2);
for (let i = 0; i < array.length; i++) {
const j = i * 2;
const hexByte = hex2.slice(j, j + 2);
const byte = Number.parseInt(hexByte, 16);
if (Number.isNaN(byte) || byte < 0)
throw new Error("Invalid byte sequence");
array[i] = byte;
}
return array;
}
function bytesToNumberBE(bytes6) {
return hexToNumber(bytesToHex(bytes6));
}
function bytesToNumberLE(bytes6) {
if (!u8a2(bytes6))
throw new Error("Uint8Array expected");
return hexToNumber(bytesToHex(Uint8Array.from(bytes6).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, hex2, expectedLength) {
let res;
if (typeof hex2 === "string") {
try {
res = hexToBytes(hex2);
} catch (e) {
throw new Error(`${title} must be valid hex string, got "${hex2}". Cause: ${e}`);
}
} else if (u8a2(hex2)) {
res = Uint8Array.from(hex2);
} 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) {
const r = new Uint8Array(arrays.reduce((sum, a) => sum + a.length, 0));
let pad = 0;
arrays.forEach((a) => {
if (!u8a2(a))
throw new Error("Uint8Array expected");
r.set(a, pad);
pad += a.length;
});
return r;
}
function equalBytes(b1, b2) {
if (b1.length !== b2.length)
return false;
for (let i = 0; i < b1.length; i++)
if (b1[i] !== b2[i])
return false;
return true;
}
function utf8ToBytes2(str) {
if (typeof str !== "string")
throw new Error(`utf8ToBytes expected string, got ${typeof str}`);
return new Uint8Array(new TextEncoder().encode(str));
}
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;
}
var 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 gen = () => {
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(gen())))
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",
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;
}
// 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 pow2(x, power, modulo) {
let res = x;
while (power-- > _0n2) {
res *= res;
res %= modulo;
}
return res;
}
function invert(number6, modulo) {
if (number6 === _0n2 || modulo <= _0n2) {
throw new Error(`invert: expected positive integers, got n=${number6} mod=${modulo}`);
}
let a = mod(number6, 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 gcd3 = b;
if (gcd3 !== _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(Fp2, n) {
const root = Fp2.pow(n, p1div4);
if (!Fp2.eql(Fp2.sqr(root), n))
throw new Error("Cannot find square root");
return root;
};
}
const Q1div2 = (Q + _1n2) / _2n2;
return function tonelliSlow(Fp2, n) {
if (Fp2.pow(n, legendreC) === Fp2.neg(Fp2.ONE))
throw new Error("Cannot find square root");
let r = S;
let g = Fp2.pow(Fp2.mul(Fp2.ONE, Z), Q);
let x = Fp2.pow(n, Q1div2);
let b = Fp2.pow(n, Q);
while (!Fp2.eql(b, Fp2.ONE)) {
if (Fp2.eql(b, Fp2.ZERO))
return Fp2.ZERO;
let m = 1;
for (let t2 = Fp2.sqr(b); m < r; m++) {
if (Fp2.eql(t2, Fp2.ONE))
break;
t2 = Fp2.sqr(t2);
}
const ge2 = Fp2.pow(g, _1n2 << BigInt(r - m - 1));
g = Fp2.sqr(ge2);
x = Fp2.mul(x, ge2);
b = Fp2.mul(b, g);
r = m;
}
return x;
};
}
function FpSqrt(P) {
if (P % _4n === _3n) {
const p1div4 = (P + _1n2) / _4n;
return function sqrt3mod4(Fp2, n) {
const root = Fp2.pow(n, p1div4);
if (!Fp2.eql(Fp2.sqr(root), n))
throw new Error("Cannot find square root");
return root;
};
}
if (P % _8n === _5n) {
const c1 = (P - _5n) / _8n;
return function sqrt5mod8(Fp2, n) {
const n2 = Fp2.mul(n, _2n2);
const v = Fp2.pow(n2, c1);
const nv = Fp2.mul(n, v);
const i = Fp2.mul(Fp2.mul(nv, _2n2), v);
const root = Fp2.mul(nv, Fp2.sub(i, Fp2.ONE));
if (!Fp2.eql(Fp2.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(f2, num, power) {
if (power < _0n2)
throw new Error("Expected power > 0");
if (power === _0n2)
return f2.ONE;
if (power === _1n2)
return num;
let p = f2.ONE;
let d = num;
while (power > _0n2) {
if (power & _1n2)
p = f2.mul(p, d);
d = f2.sqr(d);
power >>= _1n2;
}
return p;
}
function FpInvertBatch(f2, nums) {
const tmp = new Array(nums.length);
const lastMultiplied = nums.reduce((acc, num, i) => {
if (f2.is0(num))
return acc;
tmp[i] = acc;
return f2.mul(acc, num);
}, f2.ONE);
const inverted = f2.inv(lastMultiplied);
nums.reduceRight((acc, num, i) => {
if (f2.is0(num))
return acc;
tmp[i] = f2.mul(acc, tmp[i]);
return f2.mul(acc, num);
}, inverted);
return tmp;
}
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, isLE6 = false, redef = {}) {
if (ORDER <= _0n2)
throw new Error(`Expected Fp 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 f2 = 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(f2, 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(f2, n)),
invertBatch: (lst) => FpInvertBatch(f2, 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) => isLE6 ? numberToBytesLE(num, BYTES) : numberToBytesBE(num, BYTES),
fromBytes: (bytes6) => {
if (bytes6.length !== BYTES)
throw new Error(`Fp.fromBytes: expected ${BYTES}, got ${bytes6.length}`);
return isLE6 ? bytesToNumberLE(bytes6) : bytesToNumberBE(bytes6);
}
});
return Object.freeze(f2);
}
function hashToPrivateScalar(hash6, groupOrder, isLE6 = false) {
hash6 = ensureBytes("privateHash", hash6);
const hashLen = hash6.length;
const minLen = nLength(groupOrder).nByteLength + 8;
if (minLen < 24 || hashLen < minLen || hashLen > 1024)
throw new Error(`hashToPrivateScalar: expected ${minLen}-1024 bytes of input, got ${hashLen}`);
const num = isLE6 ? bytesToNumberLE(hash6) : bytesToNumberBE(hash6);
return mod(num, groupOrder - _1n2) + _1n2;
}
// node_modules/@noble/curves/esm/abstract/curve.js
var _0n3 = BigInt(0);
var _1n3 = BigInt(1);
function wNAF(c, bits) {
const constTimeNegate = (condition, item) => {
const neg = item.negate();
return condition ? neg : item;
};
const opts = (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 > _0n3) {
if (n & _1n3)
p = p.add(d);
d = d.double();
n >>= _1n3;
}
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 window2 = 0; window2 < windows; window2++) {
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 f2 = c.BASE;
const mask = BigInt(2 ** W - 1);
const maxNumber = 2 ** W;
const shiftBy = BigInt(W);
for (let window2 = 0; window2 < windows; window2++) {
const offset = window2 * windowSize;
let wbits = Number(n & mask);
n >>= shiftBy;
if (wbits > windowSize) {
wbits -= maxNumber;
n += _1n3;
}
const offset1 = offset;
const offset2 = offset + Math.abs(wbits) - 1;
const cond1 = window2 % 2 !== 0;
const cond2 = wbits < 0;
if (wbits === 0) {
f2 = f2.add(constTimeNegate(cond1, precomputes[offset1]));
} else {
p = p.add(constTimeNegate(cond2, precomputes[offset2]));
}
}
return { p, f: f2 };
},
wNAFCached(P, precomputesMap, n, transform) {
const W = P._WINDOW_SIZE || 1;
let comp = precomputesMap.get(P);
if (!comp) {
comp = this.precomputeWindow(P, W);
if (W !== 1) {
precomputesMap.set(P, transform(comp));
}
}
return this.wNAF(W, comp, n);
}
};
}
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: Fp2, a } = opts;
if (endo) {
if (!Fp2.eql(a, Fp2.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 DER = {
// asn.1 DER encoding utils
Err: class DERErr extends Error {
constructor(m = "") {
super(m);
}
},
_parseInt(data) {
const { Err: E } = DER;
if (data.length < 2 || data[0] !== 2)
throw new E("Invalid signature integer tag");
const len = data[1];
const res = data.subarray(2, len + 2);
if (!len || res.length !== len)
throw new E("Invalid signature integer: wrong length");
if (res[0] & 128)
throw new E("Invalid signature integer: negative");
if (res[0] === 0 && !(res[1] & 128))
throw new E("Invalid signature integer: unnecessary leading zero");
return { d: b2n(res), l: data.subarray(len + 2) };
},
toSig(hex2) {
const { Err: E } = DER;
const data = typeof hex2 === "string" ? h2b(hex2) : hex2;
if (!(data instanceof Uint8Array))
throw new Error("ui8a expected");
let l = data.length;
if (l < 2 || data[0] != 48)
throw new E("Invalid signature tag");
if (data[1] !== l - 2)
throw new E("Invalid signature: incorrect length");
const { d: r, l: sBytes } = DER._parseInt(data.subarray(2));
const { d: s, l: rBytesLeft } = DER._parseInt(sBytes);
if (rBytesLeft.length)
throw new E("Invalid signature: left bytes after parsing");
return { r, s };
},
hexFromSig(sig) {
const slice = (s2) => Number.parseInt(s2[0], 16) & 8 ? "00" + s2 : s2;
const h = (num) => {
const hex2 = num.toString(16);
return hex2.length & 1 ? `0${hex2}` : hex2;
};
const s = slice(h(sig.s));
const r = slice(h(sig.r));
const shl = s.length / 2;
const rhl = r.length / 2;
const sl = h(shl);
const rl = h(rhl);
return `30${h(rhl + shl + 4)}02${rl}${r}02${sl}${s}`;
}
};
var _0n4 = BigInt(0);
var _1n4 = BigInt(1);
var _2n3 = BigInt(2);
var _3n2 = BigInt(3);
var _4n2 = BigInt(4);
function weierstrassPoints(opts) {
const CURVE = validatePointOpts(opts);
const { Fp: Fp2 } = CURVE;
const toBytes6 = CURVE.toBytes || ((c, point, isCompressed) => {
const a = point.toAffine();
return concatBytes2(Uint8Array.from([4]), Fp2.toBytes(a.x), Fp2.toBytes(a.y));
});
const fromBytes = CURVE.fromBytes || ((bytes6) => {
const tail = bytes6.subarray(1);
const x = Fp2.fromBytes(tail.subarray(0, Fp2.BYTES));
const y = Fp2.fromBytes(tail.subarray(Fp2.BYTES, 2 * Fp2.BYTES));
return { x, y };
});
function weierstrassEquation(x) {
const { a, b } = CURVE;
const x2 = Fp2.sqr(x);
const x3 = Fp2.mul(x2, x);
return Fp2.add(Fp2.add(x3, Fp2.mul(x, a)), b);
}
if (!Fp2.eql(Fp2.sqr(CURVE.Gy), weierstrassEquation(CURVE.Gx)))
throw new Error("bad generator point: equation left != right");
function isWithinCurveOrder(num) {
return typeof num === "bigint" && _0n4 < num && num < CURVE.n;
}
function assertGE(num) {
if (!isWithinCurveOrder(num))
throw new Error("Expected valid bigint: 0 < bigint < curve.n");
}
function normPrivateKeyToScalar(key) {
const { allowedPrivateKeyLengths: lengths, nByteLength, wrapPrivateKey, n } = CURVE;
if (lengths && typeof key !== "bigint") {
if (key instanceof Uint8Array)
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);
assertGE(num);
return num;
}
const pointPrecomputes = /* @__PURE__ */ new Map();
function assertPrjPoint(other) {
if (!(other instanceof Point3))
throw new Error("ProjectivePoint expected");
}
class Point3 {
constructor(px, py, pz) {
this.px = px;
this.py = py;
this.pz = pz;
if (px == null || !Fp2.isValid(px))
throw new Error("x required");
if (py == null || !Fp2.isValid(py))
throw new Error("y required");
if (pz == null || !Fp2.isValid(pz))
throw new Error("z required");
}
// 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 || !Fp2.isValid(x) || !Fp2.isValid(y))
throw new Error("invalid affine point");
if (p instanceof Point3)
throw new Error("projective point not allowed");
const is0 = (i) => Fp2.eql(i, Fp2.ZERO);
if (is0(x) && is0(y))
return Point3.ZERO;
return new Point3(x, y, Fp2.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 = Fp2.invertBatch(points.map((p) => p.pz));
return points.map((p, i) => p.toAffine(toInv[i])).map(Point3.fromAffine);
}
/**
* Converts hash string or Uint8Array to Point.
* @param hex short/long ECDSA hex
*/
static fromHex(hex2) {
const P = Point3.fromAffine(fromBytes(ensureBytes("pointHex", hex2)));
P.assertValidity();
return P;
}
// Multiplies generator point by privateKey.
static fromPrivateKey(privateKey) {
return Point3.BASE.multiply(normPrivateKeyToScalar(privateKey));
}
// "Private method", don't use it directly
_setWindowSize(windowSize) {
this._WINDOW_SIZE = windowSize;
pointPrecomputes.delete(this);
}
// A point on curve is valid if it conforms to equation.
assertValidity() {
if (this.is0()) {
if (CURVE.allowInfinityPoint)
return;
throw new Error("bad point: ZERO");
}
const { x, y } = this.toAffine();
if (!Fp2.isValid(x) || !Fp2.isValid(y))
throw new Error("bad point: x or y not FE");
const left = Fp2.sqr(y);
const right = weierstrassEquation(x);
if (!Fp2.eql(left, right))
throw new Error("bad point: equation left != right");
if (!this.isTorsionFree())
throw new Error("bad point: not in prime-order subgroup");
}
hasEvenY() {
const { y } = this.toAffine();
if (Fp2.isOdd)
return !Fp2.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 = Fp2.eql(Fp2.mul(X1, Z2), Fp2.mul(X2, Z1));
const U2 = Fp2.eql(Fp2.mul(Y1, Z2), Fp2.mul(Y2, Z1));
return U1 && U2;
}
/**
* Flips point to one corresponding to (x, -y) in Affine coordinates.
*/
negate() {
return new Point3(this.px, Fp2.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 = Fp2.mul(b, _3n2);
const { px: X1, py: Y1, pz: Z1 } = this;
let X3 = Fp2.ZERO, Y3 = Fp2.ZERO, Z3 = Fp2.ZERO;
let t0 = Fp2.mul(X1, X1);
let t1 = Fp2.mul(Y1, Y1);
let t2 = Fp2.mul(Z1, Z1);
let t3 = Fp2.mul(X1, Y1);
t3 = Fp2.add(t3, t3);
Z3 = Fp2.mul(X1, Z1);
Z3 = Fp2.add(Z3, Z3);
X3 = Fp2.mul(a, Z3);
Y3 = Fp2.mul(b3, t2);
Y3 = Fp2.add(X3, Y3);
X3 = Fp2.sub(t1, Y3);
Y3 = Fp2.add(t1, Y3);
Y3 = Fp2.mul(X3, Y3);
X3 = Fp2.mul(t3, X3);
Z3 = Fp2.mul(b3, Z3);
t2 = Fp2.mul(a, t2);
t3 = Fp2.sub(t0, t2);
t3 = Fp2.mul(a, t3);
t3 = Fp2.add(t3, Z3);
Z3 = Fp2.add(t0, t0);
t0 = Fp2.add(Z3, t0);
t0 = Fp2.add(t0, t2);
t0 = Fp2.mul(t0, t3);
Y3 = Fp2.add(Y3, t0);
t2 = Fp2.mul(Y1, Z1);
t2 = Fp2.add(t2, t2);
t0 = Fp2.mul(t2, t3);
X3 = Fp2.sub(X3, t0);
Z3 = Fp2.mul(t2, t1);
Z3 = Fp2.add(Z3, Z3);
Z3 = Fp2.add(Z3, Z3);
return new Point3(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 = Fp2.ZERO, Y3 = Fp2.ZERO, Z3 = Fp2.ZERO;
const a = CURVE.a;
const b3 = Fp2.mul(CURVE.b, _3n2);
let t0 = Fp2.mul(X1, X2);
let t1 = Fp2.mul(Y1, Y2);
let t2 = Fp2.mul(Z1, Z2);
let t3 = Fp2.add(X1, Y1);
let t4 = Fp2.add(X2, Y2);
t3 = Fp2.mul(t3, t4);
t4 = Fp2.add(t0, t1);
t3 = Fp2.sub(t3, t4);
t4 = Fp2.add(X1, Z1);
let t5 = Fp2.add(X2, Z2);
t4 = Fp2.mul(t4, t5);
t5 = Fp2.add(t0, t2);
t4 = Fp2.sub(t4, t5);
t5 = Fp2.add(Y1, Z1);
X3 = Fp2.add(Y2, Z2);
t5 = Fp2.mul(t5, X3);
X3 = Fp2.add(t1, t2);
t5 = Fp2.sub(t5, X3);
Z3 = Fp2.mul(a, t4);
X3 = Fp2.mul(b3, t2);
Z3 = Fp2.add(X3, Z3);
X3 = Fp2.sub(t1, Z3);
Z3 = Fp2.add(t1, Z3);
Y3 = Fp2.mul(X3, Z3);
t1 = Fp2.add(t0, t0);
t1 = Fp2.add(t1, t0);
t2 = Fp2.mul(a, t2);
t4 = Fp2.mul(b3, t4);
t1 = Fp2.add(t1, t2);
t2 = Fp2.sub(t0, t2);
t2 = Fp2.mul(a, t2);
t4 = Fp2.add(t4, t2);
t0 = Fp2.mul(t1, t4);
Y3 = Fp2.add(Y3, t0);
t0 = Fp2.mul(t5, t4);
X3 = Fp2.mul(t3, X3);
X3 = Fp2.sub(X3, t0);
t0 = Fp2.mul(t3, t1);
Z3 = Fp2.mul(t5, Z3);
Z3 = Fp2.add(Z3, t0);
return new Point3(X3, Y3, Z3);
}
subtract(other) {
return this.add(other.negate());
}
is0() {
return this.equals(Point3.ZERO);
}
wNAF(n) {
return wnaf.wNAFCached(this, pointPrecomputes, n, (comp) => {
const toInv = Fp2.invertBatch(comp.map((p) => p.pz));
return comp.map((p, i) => p.toAffine(toInv[i])).map(Point3.fromAffine);
});
}
/**
* 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(n) {
const I = Point3.ZERO;
if (n === _0n4)
return I;
assertGE(n);
if (n === _1n4)
return this;
const { endo } = CURVE;
if (!endo)
return wnaf.unsafeLadder(this, n);
let { k1neg, k1, k2neg, k2 } = endo.splitScalar(n);
let k1p = I;
let k2p = I;
let d = this;
while (k1 > _0n4 || k2 > _0n4) {
if (k1 & _1n4)
k1p = k1p.add(d);
if (k2 & _1n4)
k2p = k2p.add(d);
d = d.double();
k1 >>= _1n4;
k2 >>= _1n4;
}
if (k1neg)
k1p = k1p.negate();
if (k2neg)
k2p = k2p.negate();
k2p = new Point3(Fp2.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) {
assertGE(scalar);
let n = scalar;
let point, fake;
const { endo } = CURVE;
if (endo) {
const { k1neg, k1, k2neg, k2 } = endo.splitScalar(n);
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 Point3(Fp2.mul(k2p.px, endo.beta), k2p.py, k2p.pz);
point = k1p.add(k2p);
fake = f1p.add(f2p);
} else {
const { p, f: f2 } = this.wNAF(n);
point = p;
fake = f2;
}
return Point3.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 = Point3.BASE;
const mul = (P, a2) => a2 === _0n4 || a2 === _1n4 || !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) {
const { px: x, py: y, pz: z } = this;
const is0 = this.is0();
if (iz == null)
iz = is0 ? Fp2.ONE : Fp2.inv(z);
const ax = Fp2.mul(x, iz);
const ay = Fp2.mul(y, iz);
const zz = Fp2.mul(z, iz);
if (is0)
return { x: Fp2.ZERO, y: Fp2.ZERO };
if (!Fp2.eql(zz, Fp2.ONE))
throw new Error("invZ was invalid");
return { x: ax, y: ay };
}
isTorsionFree() {
const { h: cofactor, isTorsionFree } = CURVE;
if (cofactor === _1n4)
return true;
if (isTorsionFree)
return isTorsionFree(Point3, this);
throw new Error("isTorsionFree() has not been declared for the elliptic curve");
}
clearCofactor() {
const { h: cofactor, clearCofactor } = CURVE;
if (cofactor === _1n4)
return this;
if (clearCofactor)
return clearCofactor(Point3, this);
return this.multiplyUnsafe(CURVE.h);
}
toRawBytes(isCompressed = true) {
this.assertValidity();
return toBytes6(Point3, this, isCompressed);
}
toHex(isCompressed = true) {
return bytesToHex(this.toRawBytes(isCompressed));
}
}
Point3.BASE = new Point3(CURVE.Gx, CURVE.Gy, Fp2.ONE);
Point3.ZERO = new Point3(Fp2.ZERO, Fp2.ONE, Fp2.ZERO);
const _bits = CURVE.nBitLength;
const wnaf = wNAF(Point3, CURVE.endo ? Math.ceil(_bits / 2) : _bits);
return {
CURVE,
ProjectivePoint: Point3,
normPrivateKeyToScalar,
weierstrassEquation,
isWithinCurveOrder
};
}
function validateOpts(curve) {
const opts = validateBasic(curve);
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: Fp2, n: CURVE_ORDER } = CURVE;
const compressedLen = Fp2.BYTES + 1;
const uncompressedLen = 2 * Fp2.BYTES + 1;
function isValidFieldElement(num) {
return _0n4 < num && num < Fp2.ORDER;
}
function modN2(a) {
return mod(a, CURVE_ORDER);
}
function invN(a) {
return invert(a, CURVE_ORDER);
}
const { ProjectivePoint: Point3, normPrivateKeyToScalar, weierstrassEquation, isWithinCurveOrder } = weierstrassPoints({
...CURVE,
toBytes(c, point, isCompressed) {
const a = point.toAffine();
const x = Fp2.toBytes(a.x);
const cat = concatBytes2;
if (isCompressed) {
return cat(Uint8Array.from([point.hasEvenY() ? 2 : 3]), x);
} else {
return cat(Uint8Array.from([4]), x, Fp2.toBytes(a.y));
}
},
fromBytes(bytes6) {
const len = bytes6.length;
const head = bytes6[0];
const tail = bytes6.subarray(1);
if (len === compressedLen && (head === 2 || head === 3)) {
const x = bytesToNumberBE(tail);
if (!isValidFieldElement(x))
throw new Error("Point is not on curve");
const y2 = weierstrassEquation(x);
let y = Fp2.sqrt(y2);
const isYOdd = (y & _1n4) === _1n4;
const isHeadOdd = (head & 1) === 1;
if (isHeadOdd !== isYOdd)
y = Fp2.neg(y);
return { x, y };
} else if (len === uncompressedLen && head === 4) {
const x = Fp2.fromBytes(tail.subarray(0, Fp2.BYTES));
const y = Fp2.fromBytes(tail.subarray(Fp2.BYTES, 2 * Fp2.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) => bytesToHex(numberToBytesBE(num, CURVE.nByteLength));
function isBiggerThanHalfOrder(number6) {
const HALF = CURVE_ORDER >> _1n4;
return number6 > HALF;
}
function normalizeS(s) {
return isBiggerThanHalfOrder(s) ? modN2(-s) : s;
}
const slcNum = (b, from, to) => 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(hex2) {
const l = CURVE.nByteLength;
hex2 = ensureBytes("compactSignature", hex2, l * 2);
return new Signature(slcNum(hex2, 0, l), slcNum(hex2, 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(hex2) {
const { r, s } = DER.toSig(ensureBytes("DER", hex2));
return new Signature(r, s);
}
assertValidity() {
if (!isWithinCurveOrder(this.r))
throw new Error("r must be 0 < r < CURVE.n");
if (!isWithinCurveOrder(this.s))
throw new Error("s must be 0 < s < CURVE.n");
}
addRecoveryBit(recovery) {
return new Signature(this.r, this.s, recovery);
}
recoverPublicKey(msgHash) {
const { r, s, recovery: rec } = this;
const h = bits2int_modN(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 >= Fp2.ORDER)
throw new Error("recovery id 2 or 3 invalid");
const prefix = (rec & 1) === 0 ? "02" : "03";
const R = Point3.fromHex(prefix + numToNByteStr(radj));
const ir = invN(radj);
const u1 = modN2(-h * ir);
const u2 = modN2(s * ir);
const Q = Point3.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, modN2(-this.s), this.recovery) : this;
}
// DER-encoded
toDERRawBytes() {
return hexToBytes(this.toDERHex());
}
toDERHex() {
return DER.hexFromSig({ r: this.r, s: this.s });
}
// padded bytes of r, then padded bytes of s
toCompactRawBytes() {
return hexToBytes(this.toCompactHex());
}
toCompactHex() {
return numToNByteStr(this.r) + numToNByteStr(this.s);
}
}
const utils3 = {
isValidPrivateKey(privateKey) {
try {
normPrivateKeyToScalar(privateKey);
return true;
} catch (error) {
return false;
}
},
normPrivateKeyToScalar,
/**
* Produces cryptographically secure private key from random of size (nBitLength+64)
* as per FIPS 186 B.4.1 with modulo bias being neglible.
*/
randomPrivateKey: () => {
const rand = CURVE.randomBytes(Fp2.BYTES + 8);
const num = hashToPrivateScalar(rand, CURVE_ORDER);
return numberToBytesBE(num, CURVE.nByteLength);
},
/**
* 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 = Point3.BASE) {
point._setWindowSize(windowSize);
point.multiply(BigInt(3));
return point;
}
};
function getPublicKey2(privateKey, isCompressed = true) {
return Point3.fromPrivateKey(privateKey).toRawBytes(isCompressed);
}
function isProbPub(item) {
const arr = item instanceof Uint8Array;
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 Point3)
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 = Point3.fromHex(publicB);
return b.multiply(normPrivateKeyToScalar(privateA)).toRawBytes(isCompressed);
}
const bits2int = CURVE.bits2int || function(bytes6) {
const num = bytesToNumberBE(bytes6);
const delta = bytes6.length * 8 - CURVE.nBitLength;
return delta > 0 ? num >> BigInt(delta) : num;
};
const bits2int_modN = CURVE.bits2int_modN || function(bytes6) {
return modN2(bits2int(bytes6));
};
const ORDER_MASK = bitMask(CURVE.nBitLength);
function int2octets(num) {
if (typeof num !== "bigint")
throw new Error("bigint expected");
if (!(_0n4 <= num && num < ORDER_MASK))
throw new Error(`bigint expected < 2^${CURVE.nBitLength}`);
return 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: hash6, randomBytes: randomBytes4 } = CURVE;
let { lowS, prehash, extraEntropy: ent } = opts;
if (lowS == null)
lowS = true;
msgHash = ensureBytes("msgHash", msgHash);
if (prehash)
msgHash = ensureBytes("prehashed msgHash", hash6(msgHash));
const h1int = bits2int_modN(msgHash);
const d = normPrivateKeyToScalar(privateKey);
const seedArgs = [int2octets(d), int2octets(h1int)];
if (ent != null) {
const e = ent === true ? randomBytes4(Fp2.BYTES) : ent;
seedArgs.push(ensureBytes("extraEntropy", e, Fp2.BYTES));
}
const seed = concatBytes2(...seedArgs);
const m = h1int;
function k2sig(kBytes) {
const k = bits2int(kBytes);
if (!isWithinCurveOrder(k))
return;
const ik = invN(k);
const q = Point3.BASE.multiply(k).toAffine();
const r = modN2(q.x);
if (r === _0n4)
return;
const s = modN2(ik * modN2(m + r * d));
if (s === _0n4)
return;
let recovery = (q.x === r ? 0 : 2) | Number(q.y & _1n4);
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 = createHmacDrbg(C.hash.outputLen, C.nByteLength, C.hmac);
return drbg(seed, k2sig);
}
Point3.BASE._setWindowSize(8);
function verify(signature, msgHash, publicKey, opts = defaultVerOpts) {
var _a;
const sg = signature;
msgHash = ensureBytes("msgHash", msgHash);
publicKey = ensureBytes("publicKey", publicKey);
if ("strict" in opts)
throw new Error("options.strict was renamed to lowS");
const { lowS, prehash } = opts;
let _sig = void 0;
let P;
try {
if (typeof sg === "string" || sg instanceof Uint8Array) {
try {
_sig = Signature.fromDER(sg);
} catch (derError) {
if (!(derError instanceof 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 = Point3.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 = modN2(h * is);
const u2 = modN2(r * is);
const R = (_a = Point3.BASE.multiplyAndAddUnsafe(P, u1, u2)) == null ? void 0 : _a.toAffine();
if (!R)
return false;
const v = modN2(R.x);
return v === r;
}
return {
CURVE,
getPublicKey: getPublicKey2,
getSharedSecret,
sign,
verify,
ProjectivePoint: Point3,
Signature,
utils: utils3
};
}
// node_modules/@noble/curves/node_modules/@noble/hashes/esm/hmac.js
var HMAC = class extends Hash {
constructor(hash6, _key) {
super();
this.finished = false;
this.destroyed = false;
assert_default.hash(hash6);
const key = toBytes(_key);
this.iHash = hash6.create();
if (typeof this.iHash.update !== "function")
throw new Error("Expected instance of class which extends utils.Hash");
this.blockLen = this.iHash.blockLen;
this.outputLen = this.iHash.outputLen;
const blockLen = this.blockLen;
const pad = new Uint8Array(blockLen);
pad.set(key.length > blockLen ? hash6.create().update(key).digest() : key);
for (let i = 0; i < pad.length; i++)
pad[i] ^= 54;
this.iHash.update(pad);
this.oHash = hash6.create();
for (let i = 0; i < pad.length; i++)
pad[i] ^= 54 ^ 92;
this.oHash.update(pad);
pad.fill(0);
}
update(buf) {
assert_default.exists(this);
this.iHash.update(buf);
return this;
}
digestInto(out) {
assert_default.exists(this);
assert_default.bytes(out, this.outputLen);
this.finished = true;
this.iHash.digestInto(out);
this.oHash.update(out);
this.oHash.digestInto(out);
this.destroy();
}
digest() {
const out = new Uint8Array(this.oHash.outputLen);
this.digestInto(out);
return out;
}
_cloneInto(to) {
to || (to = Object.create(Object.getPrototypeOf(this), {}));
const { oHash, iHash, finished, destroyed, blockLen, outputLen } = this;
to = to;
to.finished = finished;
to.destroyed = destroyed;
to.blockLen = blockLen;
to.outputLen = outputLen;
to.oHash = oHash._cloneInto(to.oHash);
to.iHash = iHash._cloneInto(to.iHash);
return to;
}
destroy() {
this.destroyed = true;
this.oHash.destroy();
this.iHash.destroy();
}
};
var hmac = (hash6, key, message) => new HMAC(hash6, key).update(message).digest();
hmac.create = (hash6, key) => new HMAC(hash6, key);
// node_modules/@noble/curves/esm/_shortw_utils.js
function getHash(hash6) {
return {
hash: hash6,
hmac: (key, ...msgs) => hmac(hash6, key, concatBytes(...msgs)),
randomBytes
};
}
function createCurve(curveDef, defHash) {
const create = (hash6) => weierstrass({ ...curveDef, ...getHash(hash6) });
return Object.freeze({ ...create(defHash), create });
}
// node_modules/@noble/curves/esm/secp256k1.js
var secp256k1P = BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f");
var secp256k1N = BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141");
var _1n5 = BigInt(1);
var _2n4 = BigInt(2);
var divNearest = (a, b) => (a + b / _2n4) / b;
function sqrtMod(y) {
const P = secp256k1P;
const _3n3 = BigInt(3), _6n = BigInt(6), _11n = BigInt(11), _22n = BigInt(22);
const _23n = BigInt(23), _44n = BigInt(44), _88n = BigInt(88);
const b2 = y * y * y % P;
const b3 = b2 * b2 * y % P;
const b6 = pow2(b3, _3n3, P) * b3 % P;
const b9 = pow2(b6, _3n3, P) * b3 % P;
const b11 = pow2(b9, _2n4, P) * b2 % P;
const b22 = pow2(b11, _11n, P) * b11 % P;
const b44 = pow2(b22, _22n, P) * b22 % P;
const b88 = pow2(b44, _44n, P) * b44 % P;
const b176 = pow2(b88, _88n, P) * b88 % P;
const b220 = pow2(b176, _44n, P) * b44 % P;
const b223 = pow2(b220, _3n3, P) * b3 % P;
const t1 = pow2(b223, _23n, P) * b22 % P;
const t2 = pow2(t1, _6n, P) * b2 % P;
const root = pow2(t2, _2n4, P);
if (!Fp.eql(Fp.sqr(root), y))
throw new Error("Cannot find square root");
return root;
}
var Fp = Field(secp256k1P, void 0, void 0, { sqrt: sqrtMod });
var secp256k1 = createCurve({
a: BigInt(0),
b: BigInt(7),
Fp,
n: secp256k1N,
// Base point (x, y) aka generator point
Gx: BigInt("55066263022277343669578718895168534326250603453777594175500187360389116729240"),
Gy: BigInt("32670510020758816978083085130507043184471273380659243275938904335757337482424"),
h: BigInt(1),
lowS: true,
/**
* secp256k1 belongs to Koblitz curves: it has efficiently computable endomorphism.
* Endomorphism uses 2x less RAM, speeds up precomputation by 2x and ECDH / key recovery by 20%.
* For precomputed wNAF it trades off 1/2 init time & 1/3 ram for 20% perf hit.
* Explanation: https://gist.github.com/paulmillr/eb670806793e84df628a7c434a873066
*/
endo: {
beta: BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),
splitScalar: (k) => {
const n = secp256k1N;
const a1 = BigInt("0x3086d221a7d46bcde86c90e49284eb15");
const b1 = -_1n5 * BigInt("0xe4437ed6010e88286f547fa90abfe4c3");
const a2 = BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8");
const b2 = a1;
const POW_2_128 = BigInt("0x100000000000000000000000000000000");
const c1 = divNearest(b2 * k, n);
const c2 = divNearest(-b1 * k, n);
let k1 = mod(k - c1 * a1 - c2 * a2, n);
let k2 = mod(-c1 * b1 - c2 * b2, n);
const k1neg = k1 > POW_2_128;
const k2neg = k2 > POW_2_128;
if (k1neg)
k1 = n - k1;
if (k2neg)
k2 = n - k2;
if (k1 > POW_2_128 || k2 > POW_2_128) {
throw new Error("splitScalar: Endomorphism failed, k=" + k);
}
return { k1neg, k1, k2neg, k2 };
}
}
}, sha256);
var _0n5 = BigInt(0);
var fe = (x) => typeof x === "bigint" && _0n5 < x && x < secp256k1P;
var ge = (x) => typeof x === "bigint" && _0n5 < x && x < secp256k1N;
var TAGGED_HASH_PREFIXES = {};
function taggedHash(tag, ...messages) {
let tagP = TAGGED_HASH_PREFIXES[tag];
if (tagP === void 0) {
const tagH = sha256(Uint8Array.from(tag, (c) => c.charCodeAt(0)));
tagP = concatBytes2(tagH, tagH);
TAGGED_HASH_PREFIXES[tag] = tagP;
}
return sha256(concatBytes2(tagP, ...messages));
}
var pointToBytes = (point) => point.toRawBytes(true).slice(1);
var numTo32b = (n) => numberToBytesBE(n, 32);
var modP = (x) => mod(x, secp256k1P);
var modN = (x) => mod(x, secp256k1N);
var Point = secp256k1.ProjectivePoint;
var GmulAdd = (Q, a, b) => Point.BASE.multiplyAndAddUnsafe(Q, a, b);
function schnorrGetExtPubKey(priv) {
let d_ = secp256k1.utils.normPrivateKeyToScalar(priv);
let p = Point.fromPrivateKey(d_);
const scalar = p.hasEvenY() ? d_ : modN(-d_);
return { scalar, bytes: pointToBytes(p) };
}
function lift_x(x) {
if (!fe(x))
throw new Error("bad x: need 0 < x < p");
const xx = modP(x * x);
const c = modP(xx * x + BigInt(7));
let y = sqrtMod(c);
if (y % _2n4 !== _0n5)
y = modP(-y);
const p = new Point(x, y, _1n5);
p.assertValidity();
return p;
}
function challenge(...args) {
return modN(bytesToNumberBE(taggedHash("BIP0340/challenge", ...args)));
}
function schnorrGetPublicKey(privateKey) {
return schnorrGetExtPubKey(privateKey).bytes;
}
function schnorrSign(message, privateKey, auxRand = randomBytes(32)) {
const m = ensureBytes("message", message);
const { bytes: px, scalar: d } = schnorrGetExtPubKey(privateKey);
const a = ensureBytes("auxRand", auxRand, 32);
const t = numTo32b(d ^ bytesToNumberBE(taggedHash("BIP0340/aux", a)));
const rand = taggedHash("BIP0340/nonce", t, px, m);
const k_ = modN(bytesToNumberBE(rand));
if (k_ === _0n5)
throw new Error("sign failed: k is zero");
const { bytes: rx, scalar: k } = schnorrGetExtPubKey(k_);
const e = challenge(rx, px, m);
const sig = new Uint8Array(64);
sig.set(rx, 0);
sig.set(numTo32b(modN(k + e * d)), 32);
if (!schnorrVerify(sig, m, px))
throw new Error("sign: Invalid signature produced");
return sig;
}
function schnorrVerify(signature, message, publicKey) {
const sig = ensureBytes("signature", signature, 64);
const m = ensureBytes("message", message);
const pub = ensureBytes("publicKey", publicKey, 32);
try {
const P = lift_x(bytesToNumberBE(pub));
const r = bytesToNumberBE(sig.subarray(0, 32));
if (!fe(r))
return false;
const s = bytesToNumberBE(sig.subarray(32, 64));
if (!ge(s))
return false;
const e = challenge(numTo32b(r), pointToBytes(P), m);
const R = GmulAdd(P, s, modN(-e));
if (!R || !R.hasEvenY() || R.toAffine().x !== r)
return false;
return true;
} catch (error) {
return false;
}
}
var schnorr = /* @__PURE__ */ (() => ({
getPublicKey: schnorrGetPublicKey,
sign: schnorrSign,
verify: schnorrVerify,
utils: {
randomPrivateKey: secp256k1.utils.randomPrivateKey,
lift_x,
pointToBytes,
numberToBytesBE,
bytesToNumberBE,
taggedHash,
mod
}
}))();
// node_modules/nostr-tools/node_modules/@noble/hashes/esm/crypto.js
var crypto3 = typeof globalThis === "object" && "crypto" in globalThis ? globalThis.crypto : void 0;
// node_modules/nostr-tools/node_modules/@noble/hashes/esm/utils.js
var u8a3 = (a) => a instanceof Uint8Array;
var createView2 = (arr) => new DataView(arr.buffer, arr.byteOffset, arr.byteLength);
var rotr2 = (word, shift) => word << 32 - shift | word >>> shift;
var isLE2 = new Uint8Array(new Uint32Array([287454020]).buffer)[0] === 68;
if (!isLE2)
throw new Error("Non little-endian hardware is not supported");
var hexes3 = Array.from({ length: 256 }, (v, i) => i.toString(16).padStart(2, "0"));
function bytesToHex2(bytes6) {
if (!u8a3(bytes6))
throw new Error("Uint8Array expected");
let hex2 = "";
for (let i = 0; i < bytes6.length; i++) {
hex2 += hexes3[bytes6[i]];
}
return hex2;
}
function hexToBytes2(hex2) {
if (typeof hex2 !== "string")
throw new Error("hex string expected, got " + typeof hex2);
const len = hex2.length;
if (len % 2)
throw new Error("padded hex string expected, got unpadded hex of length " + len);
const array = new Uint8Array(len / 2);
for (let i = 0; i < array.length; i++) {
const j = i * 2;
const hexByte = hex2.slice(j, j + 2);
const byte = Number.parseInt(hexByte, 16);
if (Number.isNaN(byte) || byte < 0)
throw new Error("Invalid byte sequence");
array[i] = byte;
}
return array;
}
function utf8ToBytes3(str) {
if (typeof str !== "string")
throw new Error(`utf8ToBytes expected string, got ${typeof str}`);
return new Uint8Array(new TextEncoder().encode(str));
}
function toBytes2(data) {
if (typeof data === "string")
data = utf8ToBytes3(data);
if (!u8a3(data))
throw new Error(`expected Uint8Array, got ${typeof data}`);
return data;
}
function concatBytes3(...arrays) {
const r = new Uint8Array(arrays.reduce((sum, a) => sum + a.length, 0));
let pad = 0;
arrays.forEach((a) => {
if (!u8a3(a))
throw new Error("Uint8Array expected");
r.set(a, pad);
pad += a.length;
});
return r;
}
var Hash2 = class {
// Safe version that clones internal state
clone() {
return this._cloneInto();
}
};
function wrapConstructor2(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 randomBytes2(bytesLength = 32) {
if (crypto3 && typeof crypto3.getRandomValues === "function") {
return crypto3.getRandomValues(new Uint8Array(bytesLength));
}
throw new Error("crypto.getRandomValues must be defined");
}
// node_modules/nostr-tools/node_modules/@noble/hashes/esm/_assert.js
function number2(n) {
if (!Number.isSafeInteger(n) || n < 0)
throw new Error(`Wrong positive integer: ${n}`);
}
function bool2(b) {
if (typeof b !== "boolean")
throw new Error(`Expected boolean, not ${b}`);
}
function bytes2(b, ...lengths) {
if (!(b instanceof Uint8Array))
throw new Error("Expected Uint8Array");
if (lengths.length > 0 && !lengths.includes(b.length))
throw new Error(`Expected Uint8Array of length ${lengths}, not of length=${b.length}`);
}
function hash2(hash6) {
if (typeof hash6 !== "function" || typeof hash6.create !== "function")
throw new Error("Hash should be wrapped by utils.wrapConstructor");
number2(hash6.outputLen);
number2(hash6.blockLen);
}
function exists2(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 output2(out, instance) {
bytes2(out);
const min = instance.outputLen;
if (out.length < min) {
throw new Error(`digestInto() expects output buffer of length at least ${min}`);
}
}
var assert2 = {
number: number2,
bool: bool2,
bytes: bytes2,
hash: hash2,
exists: exists2,
output: output2
};
var assert_default2 = assert2;
// node_modules/nostr-tools/node_modules/@noble/hashes/esm/_sha2.js
function setBigUint642(view, byteOffset, value, isLE6) {
if (typeof view.setBigUint64 === "function")
return view.setBigUint64(byteOffset, value, isLE6);
const _32n3 = BigInt(32);
const _u32_max = BigInt(4294967295);
const wh = Number(value >> _32n3 & _u32_max);
const wl = Number(value & _u32_max);
const h = isLE6 ? 4 : 0;
const l = isLE6 ? 0 : 4;
view.setUint32(byteOffset + h, wh, isLE6);
view.setUint32(byteOffset + l, wl, isLE6);
}
var SHA22 = class extends Hash2 {
constructor(blockLen, outputLen, padOffset, isLE6) {
super();
this.blockLen = blockLen;
this.outputLen = outputLen;
this.padOffset = padOffset;
this.isLE = isLE6;
this.finished = false;
this.length = 0;
this.pos = 0;
this.destroyed = false;
this.buffer = new Uint8Array(blockLen);
this.view = createView2(this.buffer);
}
update(data) {
assert_default2.exists(this);
const { view, buffer, blockLen } = this;
data = toBytes2(data);
const len = data.length;
for (let pos = 0; pos < len; ) {
const take = Math.min(blockLen - this.pos, len - pos);
if (take === blockLen) {
const dataView = createView2(data);
for (; blockLen <= len - pos; pos += blockLen)
this.process(dataView, pos);
continue;
}
buffer.set(data.subarray(pos, pos + take), this.pos);
this.pos += take;
pos += take;
if (this.pos === blockLen) {
this.process(view, 0);
this.pos = 0;
}
}
this.length += data.length;
this.roundClean();
return this;
}
digestInto(out) {
assert_default2.exists(this);
assert_default2.output(out, this);
this.finished = true;
const { buffer, view, blockLen, isLE: isLE6 } = this;
let { pos } = this;
buffer[pos++] = 128;
this.buffer.subarray(pos).fill(0);
if (this.padOffset > blockLen - pos) {
this.process(view, 0);
pos = 0;
}
for (let i = pos; i < blockLen; i++)
buffer[i] = 0;
setBigUint642(view, blockLen - 8, BigInt(this.length * 8), isLE6);
this.process(view, 0);
const oview = createView2(out);
const len = this.outputLen;
if (len % 4)
throw new Error("_sha2: outputLen should be aligned to 32bit");
const outLen = len / 4;
const state = this.get();
if (outLen > state.length)
throw new Error("_sha2: outputLen bigger than state");
for (let i = 0; i < outLen; i++)
oview.setUint32(4 * i, state[i], isLE6);
}
digest() {
const { buffer, outputLen } = this;
this.digestInto(buffer);
const res = buffer.slice(0, outputLen);
this.destroy();
return res;
}
_cloneInto(to) {
to || (to = new this.constructor());
to.set(...this.get());
const { blockLen, buffer, length, finished, destroyed, pos } = this;
to.length = length;
to.pos = pos;
to.finished = finished;
to.destroyed = destroyed;
if (length % blockLen)
to.buffer.set(buffer);
return to;
}
};
// node_modules/nostr-tools/node_modules/@noble/hashes/esm/sha256.js
var Chi2 = (a, b, c) => a & b ^ ~a & c;
var Maj2 = (a, b, c) => a & b ^ a & c ^ b & c;
var SHA256_K2 = new Uint32Array([
1116352408,
1899447441,
3049323471,
3921009573,
961987163,
1508970993,
2453635748,
2870763221,
3624381080,
310598401,
607225278,
1426881987,
1925078388,
2162078206,
2614888103,
3248222580,
3835390401,
4022224774,
264347078,
604807628,
770255983,
1249150122,
1555081692,
1996064986,
2554220882,
2821834349,
2952996808,
3210313671,
3336571891,
3584528711,
113926993,
338241895,
666307205,
773529912,
1294757372,
1396182291,
1695183700,
1986661051,
2177026350,
2456956037,
2730485921,
2820302411,
3259730800,
3345764771,
3516065817,
3600352804,
4094571909,
275423344,
430227734,
506948616,
659060556,
883997877,
958139571,
1322822218,
1537002063,
1747873779,
1955562222,
2024104815,
2227730452,
2361852424,
2428436474,
2756734187,
3204031479,
3329325298
]);
var IV2 = new Uint32Array([
1779033703,
3144134277,
1013904242,
2773480762,
1359893119,
2600822924,
528734635,
1541459225
]);
var SHA256_W2 = new Uint32Array(64);
var SHA2562 = class extends SHA22 {
constructor() {
super(64, 32, 8, false);
this.A = IV2[0] | 0;
this.B = IV2[1] | 0;
this.C = IV2[2] | 0;
this.D = IV2[3] | 0;
this.E = IV2[4] | 0;
this.F = IV2[5] | 0;
this.G = IV2[6] | 0;
this.H = IV2[7] | 0;
}
get() {
const { A, B, C, D, E, F, G, H } = this;
return [A, B, C, D, E, F, G, H];
}
// prettier-ignore
set(A, B, C, D, E, F, G, H) {
this.A = A | 0;
this.B = B | 0;
this.C = C | 0;
this.D = D | 0;
this.E = E | 0;
this.F = F | 0;
this.G = G | 0;
this.H = H | 0;
}
process(view, offset) {
for (let i = 0; i < 16; i++, offset += 4)
SHA256_W2[i] = view.getUint32(offset, false);
for (let i = 16; i < 64; i++) {
const W15 = SHA256_W2[i - 15];
const W2 = SHA256_W2[i - 2];
const s0 = rotr2(W15, 7) ^ rotr2(W15, 18) ^ W15 >>> 3;
const s1 = rotr2(W2, 17) ^ rotr2(W2, 19) ^ W2 >>> 10;
SHA256_W2[i] = s1 + SHA256_W2[i - 7] + s0 + SHA256_W2[i - 16] | 0;
}
let { A, B, C, D, E, F, G, H } = this;
for (let i = 0; i < 64; i++) {
const sigma1 = rotr2(E, 6) ^ rotr2(E, 11) ^ rotr2(E, 25);
const T1 = H + sigma1 + Chi2(E, F, G) + SHA256_K2[i] + SHA256_W2[i] | 0;
const sigma0 = rotr2(A, 2) ^ rotr2(A, 13) ^ rotr2(A, 22);
const T2 = sigma0 + Maj2(A, B, C) | 0;
H = G;
G = F;
F = E;
E = D + T1 | 0;
D = C;
C = B;
B = A;
A = T1 + T2 | 0;
}
A = A + this.A | 0;
B = B + this.B | 0;
C = C + this.C | 0;
D = D + this.D | 0;
E = E + this.E | 0;
F = F + this.F | 0;
G = G + this.G | 0;
H = H + this.H | 0;
this.set(A, B, C, D, E, F, G, H);
}
roundClean() {
SHA256_W2.fill(0);
}
destroy() {
this.set(0, 0, 0, 0, 0, 0, 0, 0);
this.buffer.fill(0);
}
};
var SHA2242 = class extends SHA2562 {
constructor() {
super();
this.A = 3238371032 | 0;
this.B = 914150663 | 0;
this.C = 812702999 | 0;
this.D = 4144912697 | 0;
this.E = 4290775857 | 0;
this.F = 1750603025 | 0;
this.G = 1694076839 | 0;
this.H = 3204075428 | 0;
this.outputLen = 28;
}
};
var sha2562 = wrapConstructor2(() => new SHA2562());
var sha2242 = wrapConstructor2(() => new SHA2242());
// node_modules/nostr-tools/node_modules/@scure/base/lib/esm/index.js
function assertNumber(n) {
if (!Number.isSafeInteger(n))
throw new Error(`Wrong integer: ${n}`);
}
function chain(...args) {
const wrap = (a, b) => (c) => a(b(c));
const encode = Array.from(args).reverse().reduce((acc, i) => acc ? wrap(acc, i.encode) : i.encode, void 0);
const decode2 = args.reduce((acc, i) => acc ? wrap(acc, i.decode) : i.decode, void 0);
return { encode, decode: decode2 };
}
function alphabet(alphabet4) {
return {
encode: (digits) => {
if (!Array.isArray(digits) || digits.length && typeof digits[0] !== "number")
throw new Error("alphabet.encode input should be an array of numbers");
return digits.map((i) => {
assertNumber(i);
if (i < 0 || i >= alphabet4.length)
throw new Error(`Digit index outside alphabet: ${i} (alphabet: ${alphabet4.length})`);
return alphabet4[i];
});
},
decode: (input) => {
if (!Array.isArray(input) || input.length && typeof input[0] !== "string")
throw new Error("alphabet.decode input should be array of strings");
return input.map((letter) => {
if (typeof letter !== "string")
throw new Error(`alphabet.decode: not string element=${letter}`);
const index = alphabet4.indexOf(letter);
if (index === -1)
throw new Error(`Unknown letter: "${letter}". Allowed: ${alphabet4}`);
return index;
});
}
};
}
function join(separator = "") {
if (typeof separator !== "string")
throw new Error("join separator should be string");
return {
encode: (from) => {
if (!Array.isArray(from) || from.length && typeof from[0] !== "string")
throw new Error("join.encode input should be array of strings");
for (let i of from)
if (typeof i !== "string")
throw new Error(`join.encode: non-string input=${i}`);
return from.join(separator);
},
decode: (to) => {
if (typeof to !== "string")
throw new Error("join.decode input should be string");
return to.split(separator);
}
};
}
function padding(bits, chr = "=") {
assertNumber(bits);
if (typeof chr !== "string")
throw new Error("padding chr should be string");
return {
encode(data) {
if (!Array.isArray(data) || data.length && typeof data[0] !== "string")
throw new Error("padding.encode input should be array of strings");
for (let i of data)
if (typeof i !== "string")
throw new Error(`padding.encode: non-string input=${i}`);
while (data.length * bits % 8)
data.push(chr);
return data;
},
decode(input) {
if (!Array.isArray(input) || input.length && typeof input[0] !== "string")
throw new Error("padding.encode input should be array of strings");
for (let i of input)
if (typeof i !== "string")
throw new Error(`padding.decode: non-string input=${i}`);
let end = input.length;
if (end * bits % 8)
throw new Error("Invalid padding: string should have whole number of bytes");
for (; end > 0 && input[end - 1] === chr; end--) {
if (!((end - 1) * bits % 8))
throw new Error("Invalid padding: string has too much padding");
}
return input.slice(0, end);
}
};
}
function normalize(fn) {
if (typeof fn !== "function")
throw new Error("normalize fn should be function");
return { encode: (from) => from, decode: (to) => fn(to) };
}
function convertRadix(data, from, to) {
if (from < 2)
throw new Error(`convertRadix: wrong from=${from}, base cannot be less than 2`);
if (to < 2)
throw new Error(`convertRadix: wrong to=${to}, base cannot be less than 2`);
if (!Array.isArray(data))
throw new Error("convertRadix: data should be array");
if (!data.length)
return [];
let pos = 0;
const res = [];
const digits = Array.from(data);
digits.forEach((d) => {
assertNumber(d);
if (d < 0 || d >= from)
throw new Error(`Wrong integer: ${d}`);
});
while (true) {
let carry = 0;
let done = true;
for (let i = pos; i < digits.length; i++) {
const digit = digits[i];
const digitBase = from * carry + digit;
if (!Number.isSafeInteger(digitBase) || from * carry / from !== carry || digitBase - digit !== from * carry) {
throw new Error("convertRadix: carry overflow");
}
carry = digitBase % to;
digits[i] = Math.floor(digitBase / to);
if (!Number.isSafeInteger(digits[i]) || digits[i] * to + carry !== digitBase)
throw new Error("convertRadix: carry overflow");
if (!done)
continue;
else if (!digits[i])
pos = i;
else
done = false;
}
res.push(carry);
if (done)
break;
}
for (let i = 0; i < data.length - 1 && data[i] === 0; i++)
res.push(0);
return res.reverse();
}
var gcd = (a, b) => !b ? a : gcd(b, a % b);
var radix2carry = (from, to) => from + (to - gcd(from, to));
function convertRadix2(data, from, to, padding3) {
if (!Array.isArray(data))
throw new Error("convertRadix2: data should be array");
if (from <= 0 || from > 32)
throw new Error(`convertRadix2: wrong from=${from}`);
if (to <= 0 || to > 32)
throw new Error(`convertRadix2: wrong to=${to}`);
if (radix2carry(from, to) > 32) {
throw new Error(`convertRadix2: carry overflow from=${from} to=${to} carryBits=${radix2carry(from, to)}`);
}
let carry = 0;
let pos = 0;
const mask = 2 ** to - 1;
const res = [];
for (const n of data) {
assertNumber(n);
if (n >= 2 ** from)
throw new Error(`convertRadix2: invalid data word=${n} from=${from}`);
carry = carry << from | n;
if (pos + from > 32)
throw new Error(`convertRadix2: carry overflow pos=${pos} from=${from}`);
pos += from;
for (; pos >= to; pos -= to)
res.push((carry >> pos - to & mask) >>> 0);
carry &= 2 ** pos - 1;
}
carry = carry << to - pos & mask;
if (!padding3 && pos >= from)
throw new Error("Excess padding");
if (!padding3 && carry)
throw new Error(`Non-zero padding: ${carry}`);
if (padding3 && pos > 0)
res.push(carry >>> 0);
return res;
}
function radix(num) {
assertNumber(num);
return {
encode: (bytes6) => {
if (!(bytes6 instanceof Uint8Array))
throw new Error("radix.encode input should be Uint8Array");
return convertRadix(Array.from(bytes6), 2 ** 8, num);
},
decode: (digits) => {
if (!Array.isArray(digits) || digits.length && typeof digits[0] !== "number")
throw new Error("radix.decode input should be array of strings");
return Uint8Array.from(convertRadix(digits, num, 2 ** 8));
}
};
}
function radix2(bits, revPadding = false) {
assertNumber(bits);
if (bits <= 0 || bits > 32)
throw new Error("radix2: bits should be in (0..32]");
if (radix2carry(8, bits) > 32 || radix2carry(bits, 8) > 32)
throw new Error("radix2: carry overflow");
return {
encode: (bytes6) => {
if (!(bytes6 instanceof Uint8Array))
throw new Error("radix2.encode input should be Uint8Array");
return convertRadix2(Array.from(bytes6), 8, bits, !revPadding);
},
decode: (digits) => {
if (!Array.isArray(digits) || digits.length && typeof digits[0] !== "number")
throw new Error("radix2.decode input should be array of strings");
return Uint8Array.from(convertRadix2(digits, bits, 8, revPadding));
}
};
}
function unsafeWrapper(fn) {
if (typeof fn !== "function")
throw new Error("unsafeWrapper fn should be function");
return function(...args) {
try {
return fn.apply(null, args);
} catch (e) {
}
};
}
var base16 = chain(radix2(4), alphabet("0123456789ABCDEF"), join(""));
var base32 = chain(radix2(5), alphabet("ABCDEFGHIJKLMNOPQRSTUVWXYZ234567"), padding(5), join(""));
var base32hex = chain(radix2(5), alphabet("0123456789ABCDEFGHIJKLMNOPQRSTUV"), padding(5), join(""));
var base32crockford = chain(radix2(5), alphabet("0123456789ABCDEFGHJKMNPQRSTVWXYZ"), join(""), normalize((s) => s.toUpperCase().replace(/O/g, "0").replace(/[IL]/g, "1")));
var base64 = chain(radix2(6), alphabet("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"), padding(6), join(""));
var base64url = chain(radix2(6), alphabet("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"), padding(6), join(""));
var genBase58 = (abc) => chain(radix(58), alphabet(abc), join(""));
var base58 = genBase58("123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz");
var base58flickr = genBase58("123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ");
var base58xrp = genBase58("rpshnaf39wBUDNEGHJKLM4PQRST7VWXYZ2bcdeCg65jkm8oFqi1tuvAxyz");
var XMR_BLOCK_LEN = [0, 2, 3, 5, 6, 7, 9, 10, 11];
var base58xmr = {
encode(data) {
let res = "";
for (let i = 0; i < data.length; i += 8) {
const block = data.subarray(i, i + 8);
res += base58.encode(block).padStart(XMR_BLOCK_LEN[block.length], "1");
}
return res;
},
decode(str) {
let res = [];
for (let i = 0; i < str.length; i += 11) {
const slice = str.slice(i, i + 11);
const blockLen = XMR_BLOCK_LEN.indexOf(slice.length);
const block = base58.decode(slice);
for (let j = 0; j < block.length - blockLen; j++) {
if (block[j] !== 0)
throw new Error("base58xmr: wrong padding");
}
res = res.concat(Array.from(block.slice(block.length - blockLen)));
}
return Uint8Array.from(res);
}
};
var BECH_ALPHABET = chain(alphabet("qpzry9x8gf2tvdw0s3jn54khce6mua7l"), join(""));
var POLYMOD_GENERATORS = [996825010, 642813549, 513874426, 1027748829, 705979059];
function bech32Polymod(pre) {
const b = pre >> 25;
let chk = (pre & 33554431) << 5;
for (let i = 0; i < POLYMOD_GENERATORS.length; i++) {
if ((b >> i & 1) === 1)
chk ^= POLYMOD_GENERATORS[i];
}
return chk;
}
function bechChecksum(prefix, words, encodingConst = 1) {
const len = prefix.length;
let chk = 1;
for (let i = 0; i < len; i++) {
const c = prefix.charCodeAt(i);
if (c < 33 || c > 126)
throw new Error(`Invalid prefix (${prefix})`);
chk = bech32Polymod(chk) ^ c >> 5;
}
chk = bech32Polymod(chk);
for (let i = 0; i < len; i++)
chk = bech32Polymod(chk) ^ prefix.charCodeAt(i) & 31;
for (let v of words)
chk = bech32Polymod(chk) ^ v;
for (let i = 0; i < 6; i++)
chk = bech32Polymod(chk);
chk ^= encodingConst;
return BECH_ALPHABET.encode(convertRadix2([chk % 2 ** 30], 30, 5, false));
}
function genBech32(encoding) {
const ENCODING_CONST = encoding === "bech32" ? 1 : 734539939;
const _words = radix2(5);
const fromWords = _words.decode;
const toWords = _words.encode;
const fromWordsUnsafe = unsafeWrapper(fromWords);
function encode(prefix, words, limit = 90) {
if (typeof prefix !== "string")
throw new Error(`bech32.encode prefix should be string, not ${typeof prefix}`);
if (!Array.isArray(words) || words.length && typeof words[0] !== "number")
throw new Error(`bech32.encode words should be array of numbers, not ${typeof words}`);
const actualLength = prefix.length + 7 + words.length;
if (limit !== false && actualLength > limit)
throw new TypeError(`Length ${actualLength} exceeds limit ${limit}`);
prefix = prefix.toLowerCase();
return `${prefix}1${BECH_ALPHABET.encode(words)}${bechChecksum(prefix, words, ENCODING_CONST)}`;
}
function decode2(str, limit = 90) {
if (typeof str !== "string")
throw new Error(`bech32.decode input should be string, not ${typeof str}`);
if (str.length < 8 || limit !== false && str.length > limit)
throw new TypeError(`Wrong string length: ${str.length} (${str}). Expected (8..${limit})`);
const lowered = str.toLowerCase();
if (str !== lowered && str !== str.toUpperCase())
throw new Error(`String must be lowercase or uppercase`);
str = lowered;
const sepIndex = str.lastIndexOf("1");
if (sepIndex === 0 || sepIndex === -1)
throw new Error(`Letter "1" must be present between prefix and data only`);
const prefix = str.slice(0, sepIndex);
const _words2 = str.slice(sepIndex + 1);
if (_words2.length < 6)
throw new Error("Data must be at least 6 characters long");
const words = BECH_ALPHABET.decode(_words2).slice(0, -6);
const sum = bechChecksum(prefix, words, ENCODING_CONST);
if (!_words2.endsWith(sum))
throw new Error(`Invalid checksum in ${str}: expected "${sum}"`);
return { prefix, words };
}
const decodeUnsafe = unsafeWrapper(decode2);
function decodeToBytes(str) {
const { prefix, words } = decode2(str, false);
return { prefix, words, bytes: fromWords(words) };
}
return { encode, decode: decode2, decodeToBytes, decodeUnsafe, fromWords, fromWordsUnsafe, toWords };
}
var bech32 = genBech32("bech32");
var bech32m = genBech32("bech32m");
var utf8 = {
encode: (data) => new TextDecoder().decode(data),
decode: (str) => new TextEncoder().encode(str)
};
var hex = chain(radix2(4), alphabet("0123456789abcdef"), join(""), normalize((s) => {
if (typeof s !== "string" || s.length % 2)
throw new TypeError(`hex.decode: expected string, got ${typeof s} with length ${s.length}`);
return s.toLowerCase();
}));
var CODERS = {
utf8,
hex,
base16,
base32,
base64,
base64url,
base58,
base58xmr
};
var coderTypeError = `Invalid encoding type. Available types: ${Object.keys(CODERS).join(", ")}`;
// node_modules/@scure/bip39/esm/wordlists/english.js
var wordlist = `abandon
ability
able
about
above
absent
absorb
abstract
absurd
abuse
access
accident
account
accuse
achieve
acid
acoustic
acquire
across
act
action
actor
actress
actual
adapt
add
addict
address
adjust
admit
adult
advance
advice
aerobic
affair
afford
afraid
again
age
agent
agree
ahead
aim
air
airport
aisle
alarm
album
alcohol
alert
alien
all
alley
allow
almost
alone
alpha
already
also
alter
always
amateur
amazing
among
amount
amused
analyst
anchor
ancient
anger
angle
angry
animal
ankle
announce
annual
another
answer
antenna
antique
anxiety
any
apart
apology
appear
apple
approve
april
arch
arctic
area
arena
argue
arm
armed
armor
army
around
arrange
arrest
arrive
arrow
art
artefact
artist
artwork
ask
aspect
assault
asset
assist
assume
asthma
athlete
atom
attack
attend
attitude
attract
auction
audit
august
aunt
author
auto
autumn
average
avocado
avoid
awake
aware
away
awesome
awful
awkward
axis
baby
bachelor
bacon
badge
bag
balance
balcony
ball
bamboo
banana
banner
bar
barely
bargain
barrel
base
basic
basket
battle
beach
bean
beauty
because
become
beef
before
begin
behave
behind
believe
below
belt
bench
benefit
best
betray
better
between
beyond
bicycle
bid
bike
bind
biology
bird
birth
bitter
black
blade
blame
blanket
blast
bleak
bless
blind
blood
blossom
blouse
blue
blur
blush
board
boat
body
boil
bomb
bone
bonus
book
boost
border
boring
borrow
boss
bottom
bounce
box
boy
bracket
brain
brand
brass
brave
bread
breeze
brick
bridge
brief
bright
bring
brisk
broccoli
broken
bronze
broom
brother
brown
brush
bubble
buddy
budget
buffalo
build
bulb
bulk
bullet
bundle
bunker
burden
burger
burst
bus
business
busy
butter
buyer
buzz
cabbage
cabin
cable
cactus
cage
cake
call
calm
camera
camp
can
canal
cancel
candy
cannon
canoe
canvas
canyon
capable
capital
captain
car
carbon
card
cargo
carpet
carry
cart
case
cash
casino
castle
casual
cat
catalog
catch
category
cattle
caught
cause
caution
cave
ceiling
celery
cement
census
century
cereal
certain
chair
chalk
champion
change
chaos
chapter
charge
chase
chat
cheap
check
cheese
chef
cherry
chest
chicken
chief
child
chimney
choice
choose
chronic
chuckle
chunk
churn
cigar
cinnamon
circle
citizen
city
civil
claim
clap
clarify
claw
clay
clean
clerk
clever
click
client
cliff
climb
clinic
clip
clock
clog
close
cloth
cloud
clown
club
clump
cluster
clutch
coach
coast
coconut
code
coffee
coil
coin
collect
color
column
combine
come
comfort
comic
common
company
concert
conduct
confirm
congress
connect
consider
control
convince
cook
cool
copper
copy
coral
core
corn
correct
cost
cotton
couch
country
couple
course
cousin
cover
coyote
crack
cradle
craft
cram
crane
crash
crater
crawl
crazy
cream
credit
creek
crew
cricket
crime
crisp
critic
crop
cross
crouch
crowd
crucial
cruel
cruise
crumble
crunch
crush
cry
crystal
cube
culture
cup
cupboard
curious
current
curtain
curve
cushion
custom
cute
cycle
dad
damage
damp
dance
danger
daring
dash
daughter
dawn
day
deal
debate
debris
decade
december
decide
decline
decorate
decrease
deer
defense
define
defy
degree
delay
deliver
demand
demise
denial
dentist
deny
depart
depend
deposit
depth
deputy
derive
describe
desert
design
desk
despair
destroy
detail
detect
develop
device
devote
diagram
dial
diamond
diary
dice
diesel
diet
differ
digital
dignity
dilemma
dinner
dinosaur
direct
dirt
disagree
discover
disease
dish
dismiss
disorder
display
distance
divert
divide
divorce
dizzy
doctor
document
dog
doll
dolphin
domain
donate
donkey
donor
door
dose
double
dove
draft
dragon
drama
drastic
draw
dream
dress
drift
drill
drink
drip
drive
drop
drum
dry
duck
dumb
dune
during
dust
dutch
duty
dwarf
dynamic
eager
eagle
early
earn
earth
easily
east
easy
echo
ecology
economy
edge
edit
educate
effort
egg
eight
either
elbow
elder
electric
elegant
element
elephant
elevator
elite
else
embark
embody
embrace
emerge
emotion
employ
empower
empty
enable
enact
end
endless
endorse
enemy
energy
enforce
engage
engine
enhance
enjoy
enlist
enough
enrich
enroll
ensure
enter
entire
entry
envelope
episode
equal
equip
era
erase
erode
erosion
error
erupt
escape
essay
essence
estate
eternal
ethics
evidence
evil
evoke
evolve
exact
example
excess
exchange
excite
exclude
excuse
execute
exercise
exhaust
exhibit
exile
exist
exit
exotic
expand
expect
expire
explain
expose
express
extend
extra
eye
eyebrow
fabric
face
faculty
fade
faint
faith
fall
false
fame
family
famous
fan
fancy
fantasy
farm
fashion
fat
fatal
father
fatigue
fault
favorite
feature
february
federal
fee
feed
feel
female
fence
festival
fetch
fever
few
fiber
fiction
field
figure
file
film
filter
final
find
fine
finger
finish
fire
firm
first
fiscal
fish
fit
fitness
fix
flag
flame
flash
flat
flavor
flee
flight
flip
float
flock
floor
flower
fluid
flush
fly
foam
focus
fog
foil
fold
follow
food
foot
force
forest
forget
fork
fortune
forum
forward
fossil
foster
found
fox
fragile
frame
frequent
fresh
friend
fringe
frog
front
frost
frown
frozen
fruit
fuel
fun
funny
furnace
fury
future
gadget
gain
galaxy
gallery
game
gap
garage
garbage
garden
garlic
garment
gas
gasp
gate
gather
gauge
gaze
general
genius
genre
gentle
genuine
gesture
ghost
giant
gift
giggle
ginger
giraffe
girl
give
glad
glance
glare
glass
glide
glimpse
globe
gloom
glory
glove
glow
glue
goat
goddess
gold
good
goose
gorilla
gospel
gossip
govern
gown
grab
grace
grain
grant
grape
grass
gravity
great
green
grid
grief
grit
grocery
group
grow
grunt
guard
guess
guide
guilt
guitar
gun
gym
habit
hair
half
hammer
hamster
hand
happy
harbor
hard
harsh
harvest
hat
have
hawk
hazard
head
health
heart
heavy
hedgehog
height
hello
helmet
help
hen
hero
hidden
high
hill
hint
hip
hire
history
hobby
hockey
hold
hole
holiday
hollow
home
honey
hood
hope
horn
horror
horse
hospital
host
hotel
hour
hover
hub
huge
human
humble
humor
hundred
hungry
hunt
hurdle
hurry
hurt
husband
hybrid
ice
icon
idea
identify
idle
ignore
ill
illegal
illness
image
imitate
immense
immune
impact
impose
improve
impulse
inch
include
income
increase
index
indicate
indoor
industry
infant
inflict
inform
inhale
inherit
initial
inject
injury
inmate
inner
innocent
input
inquiry
insane
insect
inside
inspire
install
intact
interest
into
invest
invite
involve
iron
island
isolate
issue
item
ivory
jacket
jaguar
jar
jazz
jealous
jeans
jelly
jewel
job
join
joke
journey
joy
judge
juice
jump
jungle
junior
junk
just
kangaroo
keen
keep
ketchup
key
kick
kid
kidney
kind
kingdom
kiss
kit
kitchen
kite
kitten
kiwi
knee
knife
knock
know
lab
label
labor
ladder
lady
lake
lamp
language
laptop
large
later
latin
laugh
laundry
lava
law
lawn
lawsuit
layer
lazy
leader
leaf
learn
leave
lecture
left
leg
legal
legend
leisure
lemon
lend
length
lens
leopard
lesson
letter
level
liar
liberty
library
license
life
lift
light
like
limb
limit
link
lion
liquid
list
little
live
lizard
load
loan
lobster
local
lock
logic
lonely
long
loop
lottery
loud
lounge
love
loyal
lucky
luggage
lumber
lunar
lunch
luxury
lyrics
machine
mad
magic
magnet
maid
mail
main
major
make
mammal
man
manage
mandate
mango
mansion
manual
maple
marble
march
margin
marine
market
marriage
mask
mass
master
match
material
math
matrix
matter
maximum
maze
meadow
mean
measure
meat
mechanic
medal
media
melody
melt
member
memory
mention
menu
mercy
merge
merit
merry
mesh
message
metal
method
middle
midnight
milk
million
mimic
mind
minimum
minor
minute
miracle
mirror
misery
miss
mistake
mix
mixed
mixture
mobile
model
modify
mom
moment
monitor
monkey
monster
month
moon
moral
more
morning
mosquito
mother
motion
motor
mountain
mouse
move
movie
much
muffin
mule
multiply
muscle
museum
mushroom
music
must
mutual
myself
mystery
myth
naive
name
napkin
narrow
nasty
nation
nature
near
neck
need
negative
neglect
neither
nephew
nerve
nest
net
network
neutral
never
news
next
nice
night
noble
noise
nominee
noodle
normal
north
nose
notable
note
nothing
notice
novel
now
nuclear
number
nurse
nut
oak
obey
object
oblige
obscure
observe
obtain
obvious
occur
ocean
october
odor
off
offer
office
often
oil
okay
old
olive
olympic
omit
once
one
onion
online
only
open
opera
opinion
oppose
option
orange
orbit
orchard
order
ordinary
organ
orient
original
orphan
ostrich
other
outdoor
outer
output
outside
oval
oven
over
own
owner
oxygen
oyster
ozone
pact
paddle
page
pair
palace
palm
panda
panel
panic
panther
paper
parade
parent
park
parrot
party
pass
patch
path
patient
patrol
pattern
pause
pave
payment
peace
peanut
pear
peasant
pelican
pen
penalty
pencil
people
pepper
perfect
permit
person
pet
phone
photo
phrase
physical
piano
picnic
picture
piece
pig
pigeon
pill
pilot
pink
pioneer
pipe
pistol
pitch
pizza
place
planet
plastic
plate
play
please
pledge
pluck
plug
plunge
poem
poet
point
polar
pole
police
pond
pony
pool
popular
portion
position
possible
post
potato
pottery
poverty
powder
power
practice
praise
predict
prefer
prepare
present
pretty
prevent
price
pride
primary
print
priority
prison
private
prize
problem
process
produce
profit
program
project
promote
proof
property
prosper
protect
proud
provide
public
pudding
pull
pulp
pulse
pumpkin
punch
pupil
puppy
purchase
purity
purpose
purse
push
put
puzzle
pyramid
quality
quantum
quarter
question
quick
quit
quiz
quote
rabbit
raccoon
race
rack
radar
radio
rail
rain
raise
rally
ramp
ranch
random
range
rapid
rare
rate
rather
raven
raw
razor
ready
real
reason
rebel
rebuild
recall
receive
recipe
record
recycle
reduce
reflect
reform
refuse
region
regret
regular
reject
relax
release
relief
rely
remain
remember
remind
remove
render
renew
rent
reopen
repair
repeat
replace
report
require
rescue
resemble
resist
resource
response
result
retire
retreat
return
reunion
reveal
review
reward
rhythm
rib
ribbon
rice
rich
ride
ridge
rifle
right
rigid
ring
riot
ripple
risk
ritual
rival
river
road
roast
robot
robust
rocket
romance
roof
rookie
room
rose
rotate
rough
round
route
royal
rubber
rude
rug
rule
run
runway
rural
sad
saddle
sadness
safe
sail
salad
salmon
salon
salt
salute
same
sample
sand
satisfy
satoshi
sauce
sausage
save
say
scale
scan
scare
scatter
scene
scheme
school
science
scissors
scorpion
scout
scrap
screen
script
scrub
sea
search
season
seat
second
secret
section
security
seed
seek
segment
select
sell
seminar
senior
sense
sentence
series
service
session
settle
setup
seven
shadow
shaft
shallow
share
shed
shell
sheriff
shield
shift
shine
ship
shiver
shock
shoe
shoot
shop
short
shoulder
shove
shrimp
shrug
shuffle
shy
sibling
sick
side
siege
sight
sign
silent
silk
silly
silver
similar
simple
since
sing
siren
sister
situate
six
size
skate
sketch
ski
skill
skin
skirt
skull
slab
slam
sleep
slender
slice
slide
slight
slim
slogan
slot
slow
slush
small
smart
smile
smoke
smooth
snack
snake
snap
sniff
snow
soap
soccer
social
sock
soda
soft
solar
soldier
solid
solution
solve
someone
song
soon
sorry
sort
soul
sound
soup
source
south
space
spare
spatial
spawn
speak
special
speed
spell
spend
sphere
spice
spider
spike
spin
spirit
split
spoil
sponsor
spoon
sport
spot
spray
spread
spring
spy
square
squeeze
squirrel
stable
stadium
staff
stage
stairs
stamp
stand
start
state
stay
steak
steel
stem
step
stereo
stick
still
sting
stock
stomach
stone
stool
story
stove
strategy
street
strike
strong
struggle
student
stuff
stumble
style
subject
submit
subway
success
such
sudden
suffer
sugar
suggest
suit
summer
sun
sunny
sunset
super
supply
supreme
sure
surface
surge
surprise
surround
survey
suspect
sustain
swallow
swamp
swap
swarm
swear
sweet
swift
swim
swing
switch
sword
symbol
symptom
syrup
system
table
tackle
tag
tail
talent
talk
tank
tape
target
task
taste
tattoo
taxi
teach
team
tell
ten
tenant
tennis
tent
term
test
text
thank
that
theme
then
theory
there
they
thing
this
thought
three
thrive
throw
thumb
thunder
ticket
tide
tiger
tilt
timber
time
tiny
tip
tired
tissue
title
toast
tobacco
today
toddler
toe
together
toilet
token
tomato
tomorrow
tone
tongue
tonight
tool
tooth
top
topic
topple
torch
tornado
tortoise
toss
total
tourist
toward
tower
town
toy
track
trade
traffic
tragic
train
transfer
trap
trash
travel
tray
treat
tree
trend
trial
tribe
trick
trigger
trim
trip
trophy
trouble
truck
true
truly
trumpet
trust
truth
try
tube
tuition
tumble
tuna
tunnel
turkey
turn
turtle
twelve
twenty
twice
twin
twist
two
type
typical
ugly
umbrella
unable
unaware
uncle
uncover
under
undo
unfair
unfold
unhappy
uniform
unique
unit
universe
unknown
unlock
until
unusual
unveil
update
upgrade
uphold
upon
upper
upset
urban
urge
usage
use
used
useful
useless
usual
utility
vacant
vacuum
vague
valid
valley
valve
van
vanish
vapor
various
vast
vault
vehicle
velvet
vendor
venture
venue
verb
verify
version
very
vessel
veteran
viable
vibrant
vicious
victory
video
view
village
vintage
violin
virtual
virus
visa
visit
visual
vital
vivid
vocal
voice
void
volcano
volume
vote
voyage
wage
wagon
wait
walk
wall
walnut
want
warfare
warm
warrior
wash
wasp
waste
water
wave
way
wealth
weapon
wear
weasel
weather
web
wedding
weekend
weird
welcome
west
wet
whale
what
wheat
wheel
when
where
whip
whisper
wide
width
wife
wild
will
win
window
wine
wing
wink
winner
winter
wire
wisdom
wise
wish
witness
wolf
woman
wonder
wood
wool
word
work
world
worry
worth
wrap
wreck
wrestle
wrist
write
wrong
yard
year
yellow
you
young
youth
zebra
zero
zone
zoo`.split("\n");
// node_modules/@noble/hashes/esm/_assert.js
function number3(n) {
if (!Number.isSafeInteger(n) || n < 0)
throw new Error(`Wrong positive integer: ${n}`);
}
function bool3(b) {
if (typeof b !== "boolean")
throw new Error(`Expected boolean, not ${b}`);
}
function bytes3(b, ...lengths) {
if (!(b instanceof Uint8Array))
throw new Error("Expected Uint8Array");
if (lengths.length > 0 && !lengths.includes(b.length))
throw new Error(`Expected Uint8Array of length ${lengths}, not of length=${b.length}`);
}
function hash3(hash6) {
if (typeof hash6 !== "function" || typeof hash6.create !== "function")
throw new Error("Hash should be wrapped by utils.wrapConstructor");
number3(hash6.outputLen);
number3(hash6.blockLen);
}
function exists3(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 output3(out, instance) {
bytes3(out);
const min = instance.outputLen;
if (out.length < min) {
throw new Error(`digestInto() expects output buffer of length at least ${min}`);
}
}
var assert3 = { number: number3, bool: bool3, bytes: bytes3, hash: hash3, exists: exists3, output: output3 };
var assert_default3 = assert3;
// node_modules/@noble/hashes/esm/crypto.js
var crypto4 = typeof globalThis === "object" && "crypto" in globalThis ? globalThis.crypto : void 0;
// node_modules/@noble/hashes/esm/utils.js
var u8a4 = (a) => a instanceof Uint8Array;
var createView3 = (arr) => new DataView(arr.buffer, arr.byteOffset, arr.byteLength);
var rotr3 = (word, shift) => word << 32 - shift | word >>> shift;
var isLE3 = new Uint8Array(new Uint32Array([287454020]).buffer)[0] === 68;
if (!isLE3)
throw new Error("Non little-endian hardware is not supported");
function utf8ToBytes4(str) {
if (typeof str !== "string")
throw new Error(`utf8ToBytes expected string, got ${typeof str}`);
return new Uint8Array(new TextEncoder().encode(str));
}
function toBytes3(data) {
if (typeof data === "string")
data = utf8ToBytes4(data);
if (!u8a4(data))
throw new Error(`expected Uint8Array, got ${typeof data}`);
return data;
}
var Hash3 = class {
// Safe version that clones internal state
clone() {
return this._cloneInto();
}
};
var toStr = {}.toString;
function checkOpts(defaults, opts) {
if (opts !== void 0 && toStr.call(opts) !== "[object Object]")
throw new Error("Options should be object or undefined");
const merged = Object.assign(defaults, opts);
return merged;
}
function wrapConstructor3(hashCons) {
const hashC = (msg) => hashCons().update(toBytes3(msg)).digest();
const tmp = hashCons();
hashC.outputLen = tmp.outputLen;
hashC.blockLen = tmp.blockLen;
hashC.create = () => hashCons();
return hashC;
}
function randomBytes3(bytesLength = 32) {
if (crypto4 && typeof crypto4.getRandomValues === "function") {
return crypto4.getRandomValues(new Uint8Array(bytesLength));
}
throw new Error("crypto.getRandomValues must be defined");
}
// node_modules/@noble/hashes/esm/hmac.js
var HMAC2 = class extends Hash3 {
constructor(hash6, _key) {
super();
this.finished = false;
this.destroyed = false;
hash3(hash6);
const key = toBytes3(_key);
this.iHash = hash6.create();
if (typeof this.iHash.update !== "function")
throw new Error("Expected instance of class which extends utils.Hash");
this.blockLen = this.iHash.blockLen;
this.outputLen = this.iHash.outputLen;
const blockLen = this.blockLen;
const pad = new Uint8Array(blockLen);
pad.set(key.length > blockLen ? hash6.create().update(key).digest() : key);
for (let i = 0; i < pad.length; i++)
pad[i] ^= 54;
this.iHash.update(pad);
this.oHash = hash6.create();
for (let i = 0; i < pad.length; i++)
pad[i] ^= 54 ^ 92;
this.oHash.update(pad);
pad.fill(0);
}
update(buf) {
exists3(this);
this.iHash.update(buf);
return this;
}
digestInto(out) {
exists3(this);
bytes3(out, this.outputLen);
this.finished = true;
this.iHash.digestInto(out);
this.oHash.update(out);
this.oHash.digestInto(out);
this.destroy();
}
digest() {
const out = new Uint8Array(this.oHash.outputLen);
this.digestInto(out);
return out;
}
_cloneInto(to) {
to || (to = Object.create(Object.getPrototypeOf(this), {}));
const { oHash, iHash, finished, destroyed, blockLen, outputLen } = this;
to = to;
to.finished = finished;
to.destroyed = destroyed;
to.blockLen = blockLen;
to.outputLen = outputLen;
to.oHash = oHash._cloneInto(to.oHash);
to.iHash = iHash._cloneInto(to.iHash);
return to;
}
destroy() {
this.destroyed = true;
this.oHash.destroy();
this.iHash.destroy();
}
};
var hmac2 = (hash6, key, message) => new HMAC2(hash6, key).update(message).digest();
hmac2.create = (hash6, key) => new HMAC2(hash6, key);
// node_modules/@noble/hashes/esm/pbkdf2.js
function pbkdf2Init(hash6, _password, _salt, _opts) {
hash3(hash6);
const opts = checkOpts({ dkLen: 32, asyncTick: 10 }, _opts);
const { c, dkLen, asyncTick } = opts;
number3(c);
number3(dkLen);
number3(asyncTick);
if (c < 1)
throw new Error("PBKDF2: iterations (c) should be >= 1");
const password = toBytes3(_password);
const salt2 = toBytes3(_salt);
const DK = new Uint8Array(dkLen);
const PRF = hmac2.create(hash6, password);
const PRFSalt = PRF._cloneInto().update(salt2);
return { c, dkLen, asyncTick, DK, PRF, PRFSalt };
}
function pbkdf2Output(PRF, PRFSalt, DK, prfW, u) {
PRF.destroy();
PRFSalt.destroy();
if (prfW)
prfW.destroy();
u.fill(0);
return DK;
}
function pbkdf2(hash6, password, salt2, opts) {
const { c, dkLen, DK, PRF, PRFSalt } = pbkdf2Init(hash6, password, salt2, opts);
let prfW;
const arr = new Uint8Array(4);
const view = createView3(arr);
const u = new Uint8Array(PRF.outputLen);
for (let ti = 1, pos = 0; pos < dkLen; ti++, pos += PRF.outputLen) {
const Ti = DK.subarray(pos, pos + PRF.outputLen);
view.setInt32(0, ti, false);
(prfW = PRFSalt._cloneInto(prfW)).update(arr).digestInto(u);
Ti.set(u.subarray(0, Ti.length));
for (let ui = 1; ui < c; ui++) {
PRF._cloneInto(prfW).update(u).digestInto(u);
for (let i = 0; i < Ti.length; i++)
Ti[i] ^= u[i];
}
}
return pbkdf2Output(PRF, PRFSalt, DK, prfW, u);
}
// node_modules/@noble/hashes/esm/_sha2.js
function setBigUint643(view, byteOffset, value, isLE6) {
if (typeof view.setBigUint64 === "function")
return view.setBigUint64(byteOffset, value, isLE6);
const _32n3 = BigInt(32);
const _u32_max = BigInt(4294967295);
const wh = Number(value >> _32n3 & _u32_max);
const wl = Number(value & _u32_max);
const h = isLE6 ? 4 : 0;
const l = isLE6 ? 0 : 4;
view.setUint32(byteOffset + h, wh, isLE6);
view.setUint32(byteOffset + l, wl, isLE6);
}
var SHA23 = class extends Hash3 {
constructor(blockLen, outputLen, padOffset, isLE6) {
super();
this.blockLen = blockLen;
this.outputLen = outputLen;
this.padOffset = padOffset;
this.isLE = isLE6;
this.finished = false;
this.length = 0;
this.pos = 0;
this.destroyed = false;
this.buffer = new Uint8Array(blockLen);
this.view = createView3(this.buffer);
}
update(data) {
exists3(this);
const { view, buffer, blockLen } = this;
data = toBytes3(data);
const len = data.length;
for (let pos = 0; pos < len; ) {
const take = Math.min(blockLen - this.pos, len - pos);
if (take === blockLen) {
const dataView = createView3(data);
for (; blockLen <= len - pos; pos += blockLen)
this.process(dataView, pos);
continue;
}
buffer.set(data.subarray(pos, pos + take), this.pos);
this.pos += take;
pos += take;
if (this.pos === blockLen) {
this.process(view, 0);
this.pos = 0;
}
}
this.length += data.length;
this.roundClean();
return this;
}
digestInto(out) {
exists3(this);
output3(out, this);
this.finished = true;
const { buffer, view, blockLen, isLE: isLE6 } = this;
let { pos } = this;
buffer[pos++] = 128;
this.buffer.subarray(pos).fill(0);
if (this.padOffset > blockLen - pos) {
this.process(view, 0);
pos = 0;
}
for (let i = pos; i < blockLen; i++)
buffer[i] = 0;
setBigUint643(view, blockLen - 8, BigInt(this.length * 8), isLE6);
this.process(view, 0);
const oview = createView3(out);
const len = this.outputLen;
if (len % 4)
throw new Error("_sha2: outputLen should be aligned to 32bit");
const outLen = len / 4;
const state = this.get();
if (outLen > state.length)
throw new Error("_sha2: outputLen bigger than state");
for (let i = 0; i < outLen; i++)
oview.setUint32(4 * i, state[i], isLE6);
}
digest() {
const { buffer, outputLen } = this;
this.digestInto(buffer);
const res = buffer.slice(0, outputLen);
this.destroy();
return res;
}
_cloneInto(to) {
to || (to = new this.constructor());
to.set(...this.get());
const { blockLen, buffer, length, finished, destroyed, pos } = this;
to.length = length;
to.pos = pos;
to.finished = finished;
to.destroyed = destroyed;
if (length % blockLen)
to.buffer.set(buffer);
return to;
}
};
// node_modules/@noble/hashes/esm/sha256.js
var Chi3 = (a, b, c) => a & b ^ ~a & c;
var Maj3 = (a, b, c) => a & b ^ a & c ^ b & c;
var SHA256_K3 = /* @__PURE__ */ new Uint32Array([
1116352408,
1899447441,
3049323471,
3921009573,
961987163,
1508970993,
2453635748,
2870763221,
3624381080,
310598401,
607225278,
1426881987,
1925078388,
2162078206,
2614888103,
3248222580,
3835390401,
4022224774,
264347078,
604807628,
770255983,
1249150122,
1555081692,
1996064986,
2554220882,
2821834349,
2952996808,
3210313671,
3336571891,
3584528711,
113926993,
338241895,
666307205,
773529912,
1294757372,
1396182291,
1695183700,
1986661051,
2177026350,
2456956037,
2730485921,
2820302411,
3259730800,
3345764771,
3516065817,
3600352804,
4094571909,
275423344,
430227734,
506948616,
659060556,
883997877,
958139571,
1322822218,
1537002063,
1747873779,
1955562222,
2024104815,
2227730452,
2361852424,
2428436474,
2756734187,
3204031479,
3329325298
]);
var IV3 = /* @__PURE__ */ new Uint32Array([
1779033703,
3144134277,
1013904242,
2773480762,
1359893119,
2600822924,
528734635,
1541459225
]);
var SHA256_W3 = /* @__PURE__ */ new Uint32Array(64);
var SHA2563 = class extends SHA23 {
constructor() {
super(64, 32, 8, false);
this.A = IV3[0] | 0;
this.B = IV3[1] | 0;
this.C = IV3[2] | 0;
this.D = IV3[3] | 0;
this.E = IV3[4] | 0;
this.F = IV3[5] | 0;
this.G = IV3[6] | 0;
this.H = IV3[7] | 0;
}
get() {
const { A, B, C, D, E, F, G, H } = this;
return [A, B, C, D, E, F, G, H];
}
// prettier-ignore
set(A, B, C, D, E, F, G, H) {
this.A = A | 0;
this.B = B | 0;
this.C = C | 0;
this.D = D | 0;
this.E = E | 0;
this.F = F | 0;
this.G = G | 0;
this.H = H | 0;
}
process(view, offset) {
for (let i = 0; i < 16; i++, offset += 4)
SHA256_W3[i] = view.getUint32(offset, false);
for (let i = 16; i < 64; i++) {
const W15 = SHA256_W3[i - 15];
const W2 = SHA256_W3[i - 2];
const s0 = rotr3(W15, 7) ^ rotr3(W15, 18) ^ W15 >>> 3;
const s1 = rotr3(W2, 17) ^ rotr3(W2, 19) ^ W2 >>> 10;
SHA256_W3[i] = s1 + SHA256_W3[i - 7] + s0 + SHA256_W3[i - 16] | 0;
}
let { A, B, C, D, E, F, G, H } = this;
for (let i = 0; i < 64; i++) {
const sigma1 = rotr3(E, 6) ^ rotr3(E, 11) ^ rotr3(E, 25);
const T1 = H + sigma1 + Chi3(E, F, G) + SHA256_K3[i] + SHA256_W3[i] | 0;
const sigma0 = rotr3(A, 2) ^ rotr3(A, 13) ^ rotr3(A, 22);
const T2 = sigma0 + Maj3(A, B, C) | 0;
H = G;
G = F;
F = E;
E = D + T1 | 0;
D = C;
C = B;
B = A;
A = T1 + T2 | 0;
}
A = A + this.A | 0;
B = B + this.B | 0;
C = C + this.C | 0;
D = D + this.D | 0;
E = E + this.E | 0;
F = F + this.F | 0;
G = G + this.G | 0;
H = H + this.H | 0;
this.set(A, B, C, D, E, F, G, H);
}
roundClean() {
SHA256_W3.fill(0);
}
destroy() {
this.set(0, 0, 0, 0, 0, 0, 0, 0);
this.buffer.fill(0);
}
};
var sha2563 = /* @__PURE__ */ wrapConstructor3(() => new SHA2563());
// 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) {
let Ah = new Uint32Array(lst.length);
let Al = new Uint32Array(lst.length);
for (let i = 0; i < lst.length; i++) {
const { h, l } = fromBig(lst[i], le);
[Ah[i], Al[i]] = [h, l];
}
return [Ah, Al];
}
var toBig = (h, l) => BigInt(h >>> 0) << _32n | BigInt(l >>> 0);
var shrSH = (h, _l, s) => h >>> s;
var shrSL = (h, l, s) => h << 32 - s | l >>> s;
var rotrSH = (h, l, s) => h >>> s | l << 32 - s;
var rotrSL = (h, l, s) => h << 32 - s | l >>> s;
var rotrBH = (h, l, s) => h << 64 - s | l >>> s - 32;
var rotrBL = (h, l, s) => h >>> s - 32 | l << 64 - s;
var rotr32H = (_h, l) => l;
var rotr32L = (h, _l) => h;
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;
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);
var add3H = (low, Ah, Bh, Ch) => Ah + Bh + Ch + (low / 2 ** 32 | 0) | 0;
var add4L = (Al, Bl, Cl, Dl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0);
var add4H = (low, Ah, Bh, Ch, Dh) => Ah + Bh + Ch + Dh + (low / 2 ** 32 | 0) | 0;
var add5L = (Al, Bl, Cl, Dl, El) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0) + (El >>> 0);
var add5H = (low, Ah, Bh, Ch, Dh, Eh) => Ah + Bh + Ch + Dh + Eh + (low / 2 ** 32 | 0) | 0;
var u64 = {
fromBig,
split,
toBig,
shrSH,
shrSL,
rotrSH,
rotrSL,
rotrBH,
rotrBL,
rotr32H,
rotr32L,
rotlSH,
rotlSL,
rotlBH,
rotlBL,
add,
add3L,
add3H,
add4L,
add4H,
add5H,
add5L
};
var u64_default = u64;
// node_modules/@noble/hashes/esm/sha512.js
var [SHA512_Kh, SHA512_Kl] = /* @__PURE__ */ (() => u64_default.split([
"0x428a2f98d728ae22",
"0x7137449123ef65cd",
"0xb5c0fbcfec4d3b2f",
"0xe9b5dba58189dbbc",
"0x3956c25bf348b538",
"0x59f111f1b605d019",
"0x923f82a4af194f9b",
"0xab1c5ed5da6d8118",
"0xd807aa98a3030242",
"0x12835b0145706fbe",
"0x243185be4ee4b28c",
"0x550c7dc3d5ffb4e2",
"0x72be5d74f27b896f",
"0x80deb1fe3b1696b1",
"0x9bdc06a725c71235",
"0xc19bf174cf692694",
"0xe49b69c19ef14ad2",
"0xefbe4786384f25e3",
"0x0fc19dc68b8cd5b5",
"0x240ca1cc77ac9c65",
"0x2de92c6f592b0275",
"0x4a7484aa6ea6e483",
"0x5cb0a9dcbd41fbd4",
"0x76f988da831153b5",
"0x983e5152ee66dfab",
"0xa831c66d2db43210",
"0xb00327c898fb213f",
"0xbf597fc7beef0ee4",
"0xc6e00bf33da88fc2",
"0xd5a79147930aa725",
"0x06ca6351e003826f",
"0x142929670a0e6e70",
"0x27b70a8546d22ffc",
"0x2e1b21385c26c926",
"0x4d2c6dfc5ac42aed",
"0x53380d139d95b3df",
"0x650a73548baf63de",
"0x766a0abb3c77b2a8",
"0x81c2c92e47edaee6",
"0x92722c851482353b",
"0xa2bfe8a14cf10364",
"0xa81a664bbc423001",
"0xc24b8b70d0f89791",
"0xc76c51a30654be30",
"0xd192e819d6ef5218",
"0xd69906245565a910",
"0xf40e35855771202a",
"0x106aa07032bbd1b8",
"0x19a4c116b8d2d0c8",
"0x1e376c085141ab53",
"0x2748774cdf8eeb99",
"0x34b0bcb5e19b48a8",
"0x391c0cb3c5c95a63",
"0x4ed8aa4ae3418acb",
"0x5b9cca4f7763e373",
"0x682e6ff3d6b2b8a3",
"0x748f82ee5defb2fc",
"0x78a5636f43172f60",
"0x84c87814a1f0ab72",
"0x8cc702081a6439ec",
"0x90befffa23631e28",
"0xa4506cebde82bde9",
"0xbef9a3f7b2c67915",
"0xc67178f2e372532b",
"0xca273eceea26619c",
"0xd186b8c721c0c207",
"0xeada7dd6cde0eb1e",
"0xf57d4f7fee6ed178",
"0x06f067aa72176fba",
"0x0a637dc5a2c898a6",
"0x113f9804bef90dae",
"0x1b710b35131c471b",
"0x28db77f523047d84",
"0x32caab7b40c72493",
"0x3c9ebe0a15c9bebc",
"0x431d67c49c100d4c",
"0x4cc5d4becb3e42b6",
"0x597f299cfc657e2a",
"0x5fcb6fab3ad6faec",
"0x6c44198c4a475817"
].map((n) => BigInt(n))))();
var SHA512_W_H = /* @__PURE__ */ new Uint32Array(80);
var SHA512_W_L = /* @__PURE__ */ new Uint32Array(80);
var SHA512 = class extends SHA23 {
constructor() {
super(128, 64, 16, false);
this.Ah = 1779033703 | 0;
this.Al = 4089235720 | 0;
this.Bh = 3144134277 | 0;
this.Bl = 2227873595 | 0;
this.Ch = 1013904242 | 0;
this.Cl = 4271175723 | 0;
this.Dh = 2773480762 | 0;
this.Dl = 1595750129 | 0;
this.Eh = 1359893119 | 0;
this.El = 2917565137 | 0;
this.Fh = 2600822924 | 0;
this.Fl = 725511199 | 0;
this.Gh = 528734635 | 0;
this.Gl = 4215389547 | 0;
this.Hh = 1541459225 | 0;
this.Hl = 327033209 | 0;
}
// prettier-ignore
get() {
const { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;
return [Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl];
}
// prettier-ignore
set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl) {
this.Ah = Ah | 0;
this.Al = Al | 0;
this.Bh = Bh | 0;
this.Bl = Bl | 0;
this.Ch = Ch | 0;
this.Cl = Cl | 0;
this.Dh = Dh | 0;
this.Dl = Dl | 0;
this.Eh = Eh | 0;
this.El = El | 0;
this.Fh = Fh | 0;
this.Fl = Fl | 0;
this.Gh = Gh | 0;
this.Gl = Gl | 0;
this.Hh = Hh | 0;
this.Hl = Hl | 0;
}
process(view, offset) {
for (let i = 0; i < 16; i++, offset += 4) {
SHA512_W_H[i] = view.getUint32(offset);
SHA512_W_L[i] = view.getUint32(offset += 4);
}
for (let i = 16; i < 80; i++) {
const W15h = SHA512_W_H[i - 15] | 0;
const W15l = SHA512_W_L[i - 15] | 0;
const s0h = u64_default.rotrSH(W15h, W15l, 1) ^ u64_default.rotrSH(W15h, W15l, 8) ^ u64_default.shrSH(W15h, W15l, 7);
const s0l = u64_default.rotrSL(W15h, W15l, 1) ^ u64_default.rotrSL(W15h, W15l, 8) ^ u64_default.shrSL(W15h, W15l, 7);
const W2h = SHA512_W_H[i - 2] | 0;
const W2l = SHA512_W_L[i - 2] | 0;
const s1h = u64_default.rotrSH(W2h, W2l, 19) ^ u64_default.rotrBH(W2h, W2l, 61) ^ u64_default.shrSH(W2h, W2l, 6);
const s1l = u64_default.rotrSL(W2h, W2l, 19) ^ u64_default.rotrBL(W2h, W2l, 61) ^ u64_default.shrSL(W2h, W2l, 6);
const SUMl = u64_default.add4L(s0l, s1l, SHA512_W_L[i - 7], SHA512_W_L[i - 16]);
const SUMh = u64_default.add4H(SUMl, s0h, s1h, SHA512_W_H[i - 7], SHA512_W_H[i - 16]);
SHA512_W_H[i] = SUMh | 0;
SHA512_W_L[i] = SUMl | 0;
}
let { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;
for (let i = 0; i < 80; i++) {
const sigma1h = u64_default.rotrSH(Eh, El, 14) ^ u64_default.rotrSH(Eh, El, 18) ^ u64_default.rotrBH(Eh, El, 41);
const sigma1l = u64_default.rotrSL(Eh, El, 14) ^ u64_default.rotrSL(Eh, El, 18) ^ u64_default.rotrBL(Eh, El, 41);
const CHIh = Eh & Fh ^ ~Eh & Gh;
const CHIl = El & Fl ^ ~El & Gl;
const T1ll = u64_default.add5L(Hl, sigma1l, CHIl, SHA512_Kl[i], SHA512_W_L[i]);
const T1h = u64_default.add5H(T1ll, Hh, sigma1h, CHIh, SHA512_Kh[i], SHA512_W_H[i]);
const T1l = T1ll | 0;
const sigma0h = u64_default.rotrSH(Ah, Al, 28) ^ u64_default.rotrBH(Ah, Al, 34) ^ u64_default.rotrBH(Ah, Al, 39);
const sigma0l = u64_default.rotrSL(Ah, Al, 28) ^ u64_default.rotrBL(Ah, Al, 34) ^ u64_default.rotrBL(Ah, Al, 39);
const MAJh = Ah & Bh ^ Ah & Ch ^ Bh & Ch;
const MAJl = Al & Bl ^ Al & Cl ^ Bl & Cl;
Hh = Gh | 0;
Hl = Gl | 0;
Gh = Fh | 0;
Gl = Fl | 0;
Fh = Eh | 0;
Fl = El | 0;
({ h: Eh, l: El } = u64_default.add(Dh | 0, Dl | 0, T1h | 0, T1l | 0));
Dh = Ch | 0;
Dl = Cl | 0;
Ch = Bh | 0;
Cl = Bl | 0;
Bh = Ah | 0;
Bl = Al | 0;
const All = u64_default.add3L(T1l, sigma0l, MAJl);
Ah = u64_default.add3H(All, T1h, sigma0h, MAJh);
Al = All | 0;
}
({ h: Ah, l: Al } = u64_default.add(this.Ah | 0, this.Al | 0, Ah | 0, Al | 0));
({ h: Bh, l: Bl } = u64_default.add(this.Bh | 0, this.Bl | 0, Bh | 0, Bl | 0));
({ h: Ch, l: Cl } = u64_default.add(this.Ch | 0, this.Cl | 0, Ch | 0, Cl | 0));
({ h: Dh, l: Dl } = u64_default.add(this.Dh | 0, this.Dl | 0, Dh | 0, Dl | 0));
({ h: Eh, l: El } = u64_default.add(this.Eh | 0, this.El | 0, Eh | 0, El | 0));
({ h: Fh, l: Fl } = u64_default.add(this.Fh | 0, this.Fl | 0, Fh | 0, Fl | 0));
({ h: Gh, l: Gl } = u64_default.add(this.Gh | 0, this.Gl | 0, Gh | 0, Gl | 0));
({ h: Hh, l: Hl } = u64_default.add(this.Hh | 0, this.Hl | 0, Hh | 0, Hl | 0));
this.set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl);
}
roundClean() {
SHA512_W_H.fill(0);
SHA512_W_L.fill(0);
}
destroy() {
this.buffer.fill(0);
this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
}
};
var sha512 = /* @__PURE__ */ wrapConstructor3(() => new SHA512());
// node_modules/@scure/base/lib/esm/index.js
// @__NO_SIDE_EFFECTS__
function assertNumber2(n) {
if (!Number.isSafeInteger(n))
throw new Error(`Wrong integer: ${n}`);
}
// @__NO_SIDE_EFFECTS__
function chain2(...args) {
const wrap = (a, b) => (c) => a(b(c));
const encode = Array.from(args).reverse().reduce((acc, i) => acc ? wrap(acc, i.encode) : i.encode, void 0);
const decode2 = args.reduce((acc, i) => acc ? wrap(acc, i.decode) : i.decode, void 0);
return { encode, decode: decode2 };
}
// @__NO_SIDE_EFFECTS__
function alphabet2(alphabet4) {
return {
encode: (digits) => {
if (!Array.isArray(digits) || digits.length && typeof digits[0] !== "number")
throw new Error("alphabet.encode input should be an array of numbers");
return digits.map((i) => {
/* @__PURE__ */ assertNumber2(i);
if (i < 0 || i >= alphabet4.length)
throw new Error(`Digit index outside alphabet: ${i} (alphabet: ${alphabet4.length})`);
return alphabet4[i];
});
},
decode: (input) => {
if (!Array.isArray(input) || input.length && typeof input[0] !== "string")
throw new Error("alphabet.decode input should be array of strings");
return input.map((letter) => {
if (typeof letter !== "string")
throw new Error(`alphabet.decode: not string element=${letter}`);
const index = alphabet4.indexOf(letter);
if (index === -1)
throw new Error(`Unknown letter: "${letter}". Allowed: ${alphabet4}`);
return index;
});
}
};
}
// @__NO_SIDE_EFFECTS__
function join2(separator = "") {
if (typeof separator !== "string")
throw new Error("join separator should be string");
return {
encode: (from) => {
if (!Array.isArray(from) || from.length && typeof from[0] !== "string")
throw new Error("join.encode input should be array of strings");
for (let i of from)
if (typeof i !== "string")
throw new Error(`join.encode: non-string input=${i}`);
return from.join(separator);
},
decode: (to) => {
if (typeof to !== "string")
throw new Error("join.decode input should be string");
return to.split(separator);
}
};
}
// @__NO_SIDE_EFFECTS__
function padding2(bits, chr = "=") {
/* @__PURE__ */ assertNumber2(bits);
if (typeof chr !== "string")
throw new Error("padding chr should be string");
return {
encode(data) {
if (!Array.isArray(data) || data.length && typeof data[0] !== "string")
throw new Error("padding.encode input should be array of strings");
for (let i of data)
if (typeof i !== "string")
throw new Error(`padding.encode: non-string input=${i}`);
while (data.length * bits % 8)
data.push(chr);
return data;
},
decode(input) {
if (!Array.isArray(input) || input.length && typeof input[0] !== "string")
throw new Error("padding.encode input should be array of strings");
for (let i of input)
if (typeof i !== "string")
throw new Error(`padding.decode: non-string input=${i}`);
let end = input.length;
if (end * bits % 8)
throw new Error("Invalid padding: string should have whole number of bytes");
for (; end > 0 && input[end - 1] === chr; end--) {
if (!((end - 1) * bits % 8))
throw new Error("Invalid padding: string has too much padding");
}
return input.slice(0, end);
}
};
}
// @__NO_SIDE_EFFECTS__
function convertRadix3(data, from, to) {
if (from < 2)
throw new Error(`convertRadix: wrong from=${from}, base cannot be less than 2`);
if (to < 2)
throw new Error(`convertRadix: wrong to=${to}, base cannot be less than 2`);
if (!Array.isArray(data))
throw new Error("convertRadix: data should be array");
if (!data.length)
return [];
let pos = 0;
const res = [];
const digits = Array.from(data);
digits.forEach((d) => {
/* @__PURE__ */ assertNumber2(d);
if (d < 0 || d >= from)
throw new Error(`Wrong integer: ${d}`);
});
while (true) {
let carry = 0;
let done = true;
for (let i = pos; i < digits.length; i++) {
const digit = digits[i];
const digitBase = from * carry + digit;
if (!Number.isSafeInteger(digitBase) || from * carry / from !== carry || digitBase - digit !== from * carry) {
throw new Error("convertRadix: carry overflow");
}
carry = digitBase % to;
const rounded = Math.floor(digitBase / to);
digits[i] = rounded;
if (!Number.isSafeInteger(rounded) || rounded * to + carry !== digitBase)
throw new Error("convertRadix: carry overflow");
if (!done)
continue;
else if (!rounded)
pos = i;
else
done = false;
}
res.push(carry);
if (done)
break;
}
for (let i = 0; i < data.length - 1 && data[i] === 0; i++)
res.push(0);
return res.reverse();
}
var gcd2 = /* @__NO_SIDE_EFFECTS__ */ (a, b) => !b ? a : /* @__PURE__ */ gcd2(b, a % b);
var radix2carry2 = /* @__NO_SIDE_EFFECTS__ */ (from, to) => from + (to - /* @__PURE__ */ gcd2(from, to));
// @__NO_SIDE_EFFECTS__
function convertRadix22(data, from, to, padding3) {
if (!Array.isArray(data))
throw new Error("convertRadix2: data should be array");
if (from <= 0 || from > 32)
throw new Error(`convertRadix2: wrong from=${from}`);
if (to <= 0 || to > 32)
throw new Error(`convertRadix2: wrong to=${to}`);
if (/* @__PURE__ */ radix2carry2(from, to) > 32) {
throw new Error(`convertRadix2: carry overflow from=${from} to=${to} carryBits=${/* @__PURE__ */ radix2carry2(from, to)}`);
}
let carry = 0;
let pos = 0;
const mask = 2 ** to - 1;
const res = [];
for (const n of data) {
/* @__PURE__ */ assertNumber2(n);
if (n >= 2 ** from)
throw new Error(`convertRadix2: invalid data word=${n} from=${from}`);
carry = carry << from | n;
if (pos + from > 32)
throw new Error(`convertRadix2: carry overflow pos=${pos} from=${from}`);
pos += from;
for (; pos >= to; pos -= to)
res.push((carry >> pos - to & mask) >>> 0);
carry &= 2 ** pos - 1;
}
carry = carry << to - pos & mask;
if (!padding3 && pos >= from)
throw new Error("Excess padding");
if (!padding3 && carry)
throw new Error(`Non-zero padding: ${carry}`);
if (padding3 && pos > 0)
res.push(carry >>> 0);
return res;
}
// @__NO_SIDE_EFFECTS__
function radix3(num) {
/* @__PURE__ */ assertNumber2(num);
return {
encode: (bytes6) => {
if (!(bytes6 instanceof Uint8Array))
throw new Error("radix.encode input should be Uint8Array");
return /* @__PURE__ */ convertRadix3(Array.from(bytes6), 2 ** 8, num);
},
decode: (digits) => {
if (!Array.isArray(digits) || digits.length && typeof digits[0] !== "number")
throw new Error("radix.decode input should be array of strings");
return Uint8Array.from(/* @__PURE__ */ convertRadix3(digits, num, 2 ** 8));
}
};
}
// @__NO_SIDE_EFFECTS__
function radix22(bits, revPadding = false) {
/* @__PURE__ */ assertNumber2(bits);
if (bits <= 0 || bits > 32)
throw new Error("radix2: bits should be in (0..32]");
if (/* @__PURE__ */ radix2carry2(8, bits) > 32 || /* @__PURE__ */ radix2carry2(bits, 8) > 32)
throw new Error("radix2: carry overflow");
return {
encode: (bytes6) => {
if (!(bytes6 instanceof Uint8Array))
throw new Error("radix2.encode input should be Uint8Array");
return /* @__PURE__ */ convertRadix22(Array.from(bytes6), 8, bits, !revPadding);
},
decode: (digits) => {
if (!Array.isArray(digits) || digits.length && typeof digits[0] !== "number")
throw new Error("radix2.decode input should be array of strings");
return Uint8Array.from(/* @__PURE__ */ convertRadix22(digits, bits, 8, revPadding));
}
};
}
// @__NO_SIDE_EFFECTS__
function checksum(len, fn) {
/* @__PURE__ */ assertNumber2(len);
if (typeof fn !== "function")
throw new Error("checksum fn should be function");
return {
encode(data) {
if (!(data instanceof Uint8Array))
throw new Error("checksum.encode: input should be Uint8Array");
const checksum3 = fn(data).slice(0, len);
const res = new Uint8Array(data.length + len);
res.set(data);
res.set(checksum3, data.length);
return res;
},
decode(data) {
if (!(data instanceof Uint8Array))
throw new Error("checksum.decode: input should be Uint8Array");
const payload = data.slice(0, -len);
const newChecksum = fn(payload).slice(0, len);
const oldChecksum = data.slice(-len);
for (let i = 0; i < len; i++)
if (newChecksum[i] !== oldChecksum[i])
throw new Error("Invalid checksum");
return payload;
}
};
}
var utils = { alphabet: alphabet2, chain: chain2, checksum, radix: radix3, radix2: radix22, join: join2, padding: padding2 };
// node_modules/@scure/bip39/esm/index.js
var isJapanese = (wordlist2) => wordlist2[0] === "\u3042\u3044\u3053\u304F\u3057\u3093";
function nfkd(str) {
if (typeof str !== "string")
throw new TypeError(`Invalid mnemonic type: ${typeof str}`);
return str.normalize("NFKD");
}
function normalize2(str) {
const norm = nfkd(str);
const words = norm.split(" ");
if (![12, 15, 18, 21, 24].includes(words.length))
throw new Error("Invalid mnemonic");
return { nfkd: norm, words };
}
function assertEntropy(entropy) {
assert_default3.bytes(entropy, 16, 20, 24, 28, 32);
}
function generateMnemonic(wordlist2, strength = 128) {
assert_default3.number(strength);
if (strength % 32 !== 0 || strength > 256)
throw new TypeError("Invalid entropy");
return entropyToMnemonic(randomBytes3(strength / 8), wordlist2);
}
var calcChecksum = (entropy) => {
const bitsLeft = 8 - entropy.length / 4;
return new Uint8Array([sha2563(entropy)[0] >> bitsLeft << bitsLeft]);
};
function getCoder(wordlist2) {
if (!Array.isArray(wordlist2) || wordlist2.length !== 2048 || typeof wordlist2[0] !== "string")
throw new Error("Worlist: expected array of 2048 strings");
wordlist2.forEach((i) => {
if (typeof i !== "string")
throw new Error(`Wordlist: non-string element: ${i}`);
});
return utils.chain(utils.checksum(1, calcChecksum), utils.radix2(11, true), utils.alphabet(wordlist2));
}
function mnemonicToEntropy(mnemonic, wordlist2) {
const { words } = normalize2(mnemonic);
const entropy = getCoder(wordlist2).decode(words);
assertEntropy(entropy);
return entropy;
}
function entropyToMnemonic(entropy, wordlist2) {
assertEntropy(entropy);
const words = getCoder(wordlist2).encode(entropy);
return words.join(isJapanese(wordlist2) ? "\u3000" : " ");
}
function validateMnemonic(mnemonic, wordlist2) {
try {
mnemonicToEntropy(mnemonic, wordlist2);
} catch (e) {
return false;
}
return true;
}
var salt = (passphrase) => nfkd(`mnemonic${passphrase}`);
function mnemonicToSeedSync(mnemonic, passphrase = "") {
return pbkdf2(sha512, normalize2(mnemonic).nfkd, salt(passphrase), { c: 2048, dkLen: 64 });
}
// node_modules/nostr-tools/node_modules/@scure/bip32/node_modules/@noble/hashes/esm/_assert.js
function number4(n) {
if (!Number.isSafeInteger(n) || n < 0)
throw new Error(`Wrong positive integer: ${n}`);
}
function bytes4(b, ...lengths) {
if (!(b instanceof Uint8Array))
throw new Error("Expected Uint8Array");
if (lengths.length > 0 && !lengths.includes(b.length))
throw new Error(`Expected Uint8Array of length ${lengths}, not of length=${b.length}`);
}
function hash4(hash6) {
if (typeof hash6 !== "function" || typeof hash6.create !== "function")
throw new Error("Hash should be wrapped by utils.wrapConstructor");
number4(hash6.outputLen);
number4(hash6.blockLen);
}
function exists4(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 output4(out, instance) {
bytes4(out);
const min = instance.outputLen;
if (out.length < min) {
throw new Error(`digestInto() expects output buffer of length at least ${min}`);
}
}
// node_modules/nostr-tools/node_modules/@scure/bip32/node_modules/@noble/hashes/esm/utils.js
var u8a5 = (a) => a instanceof Uint8Array;
var createView4 = (arr) => new DataView(arr.buffer, arr.byteOffset, arr.byteLength);
var rotr4 = (word, shift) => word << 32 - shift | word >>> shift;
var isLE4 = new Uint8Array(new Uint32Array([287454020]).buffer)[0] === 68;
if (!isLE4)
throw new Error("Non little-endian hardware is not supported");
var hexes4 = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, "0"));
function bytesToHex3(bytes6) {
if (!u8a5(bytes6))
throw new Error("Uint8Array expected");
let hex2 = "";
for (let i = 0; i < bytes6.length; i++) {
hex2 += hexes4[bytes6[i]];
}
return hex2;
}
function hexToBytes3(hex2) {
if (typeof hex2 !== "string")
throw new Error("hex string expected, got " + typeof hex2);
const len = hex2.length;
if (len % 2)
throw new Error("padded hex string expected, got unpadded hex of length " + len);
const array = new Uint8Array(len / 2);
for (let i = 0; i < array.length; i++) {
const j = i * 2;
const hexByte = hex2.slice(j, j + 2);
const byte = Number.parseInt(hexByte, 16);
if (Number.isNaN(byte) || byte < 0)
throw new Error("Invalid byte sequence");
array[i] = byte;
}
return array;
}
function utf8ToBytes5(str) {
if (typeof str !== "string")
throw new Error(`utf8ToBytes expected string, got ${typeof str}`);
return new Uint8Array(new TextEncoder().encode(str));
}
function toBytes4(data) {
if (typeof data === "string")
data = utf8ToBytes5(data);
if (!u8a5(data))
throw new Error(`expected Uint8Array, got ${typeof data}`);
return data;
}
function concatBytes4(...arrays) {
const r = new Uint8Array(arrays.reduce((sum, a) => sum + a.length, 0));
let pad = 0;
arrays.forEach((a) => {
if (!u8a5(a))
throw new Error("Uint8Array expected");
r.set(a, pad);
pad += a.length;
});
return r;
}
var Hash4 = class {
// Safe version that clones internal state
clone() {
return this._cloneInto();
}
};
var toStr2 = {}.toString;
function wrapConstructor4(hashCons) {
const hashC = (msg) => hashCons().update(toBytes4(msg)).digest();
const tmp = hashCons();
hashC.outputLen = tmp.outputLen;
hashC.blockLen = tmp.blockLen;
hashC.create = () => hashCons();
return hashC;
}
// node_modules/nostr-tools/node_modules/@scure/bip32/node_modules/@noble/hashes/esm/hmac.js
var HMAC3 = class extends Hash4 {
constructor(hash6, _key) {
super();
this.finished = false;
this.destroyed = false;
hash4(hash6);
const key = toBytes4(_key);
this.iHash = hash6.create();
if (typeof this.iHash.update !== "function")
throw new Error("Expected instance of class which extends utils.Hash");
this.blockLen = this.iHash.blockLen;
this.outputLen = this.iHash.outputLen;
const blockLen = this.blockLen;
const pad = new Uint8Array(blockLen);
pad.set(key.length > blockLen ? hash6.create().update(key).digest() : key);
for (let i = 0; i < pad.length; i++)
pad[i] ^= 54;
this.iHash.update(pad);
this.oHash = hash6.create();
for (let i = 0; i < pad.length; i++)
pad[i] ^= 54 ^ 92;
this.oHash.update(pad);
pad.fill(0);
}
update(buf) {
exists4(this);
this.iHash.update(buf);
return this;
}
digestInto(out) {
exists4(this);
bytes4(out, this.outputLen);
this.finished = true;
this.iHash.digestInto(out);
this.oHash.update(out);
this.oHash.digestInto(out);
this.destroy();
}
digest() {
const out = new Uint8Array(this.oHash.outputLen);
this.digestInto(out);
return out;
}
_cloneInto(to) {
to || (to = Object.create(Object.getPrototypeOf(this), {}));
const { oHash, iHash, finished, destroyed, blockLen, outputLen } = this;
to = to;
to.finished = finished;
to.destroyed = destroyed;
to.blockLen = blockLen;
to.outputLen = outputLen;
to.oHash = oHash._cloneInto(to.oHash);
to.iHash = iHash._cloneInto(to.iHash);
return to;
}
destroy() {
this.destroyed = true;
this.oHash.destroy();
this.iHash.destroy();
}
};
var hmac3 = (hash6, key, message) => new HMAC3(hash6, key).update(message).digest();
hmac3.create = (hash6, key) => new HMAC3(hash6, key);
// node_modules/nostr-tools/node_modules/@scure/bip32/node_modules/@noble/hashes/esm/_sha2.js
function setBigUint644(view, byteOffset, value, isLE6) {
if (typeof view.setBigUint64 === "function")
return view.setBigUint64(byteOffset, value, isLE6);
const _32n3 = BigInt(32);
const _u32_max = BigInt(4294967295);
const wh = Number(value >> _32n3 & _u32_max);
const wl = Number(value & _u32_max);
const h = isLE6 ? 4 : 0;
const l = isLE6 ? 0 : 4;
view.setUint32(byteOffset + h, wh, isLE6);
view.setUint32(byteOffset + l, wl, isLE6);
}
var SHA24 = class extends Hash4 {
constructor(blockLen, outputLen, padOffset, isLE6) {
super();
this.blockLen = blockLen;
this.outputLen = outputLen;
this.padOffset = padOffset;
this.isLE = isLE6;
this.finished = false;
this.length = 0;
this.pos = 0;
this.destroyed = false;
this.buffer = new Uint8Array(blockLen);
this.view = createView4(this.buffer);
}
update(data) {
exists4(this);
const { view, buffer, blockLen } = this;
data = toBytes4(data);
const len = data.length;
for (let pos = 0; pos < len; ) {
const take = Math.min(blockLen - this.pos, len - pos);
if (take === blockLen) {
const dataView = createView4(data);
for (; blockLen <= len - pos; pos += blockLen)
this.process(dataView, pos);
continue;
}
buffer.set(data.subarray(pos, pos + take), this.pos);
this.pos += take;
pos += take;
if (this.pos === blockLen) {
this.process(view, 0);
this.pos = 0;
}
}
this.length += data.length;
this.roundClean();
return this;
}
digestInto(out) {
exists4(this);
output4(out, this);
this.finished = true;
const { buffer, view, blockLen, isLE: isLE6 } = this;
let { pos } = this;
buffer[pos++] = 128;
this.buffer.subarray(pos).fill(0);
if (this.padOffset > blockLen - pos) {
this.process(view, 0);
pos = 0;
}
for (let i = pos; i < blockLen; i++)
buffer[i] = 0;
setBigUint644(view, blockLen - 8, BigInt(this.length * 8), isLE6);
this.process(view, 0);
const oview = createView4(out);
const len = this.outputLen;
if (len % 4)
throw new Error("_sha2: outputLen should be aligned to 32bit");
const outLen = len / 4;
const state = this.get();
if (outLen > state.length)
throw new Error("_sha2: outputLen bigger than state");
for (let i = 0; i < outLen; i++)
oview.setUint32(4 * i, state[i], isLE6);
}
digest() {
const { buffer, outputLen } = this;
this.digestInto(buffer);
const res = buffer.slice(0, outputLen);
this.destroy();
return res;
}
_cloneInto(to) {
to || (to = new this.constructor());
to.set(...this.get());
const { blockLen, buffer, length, finished, destroyed, pos } = this;
to.length = length;
to.pos = pos;
to.finished = finished;
to.destroyed = destroyed;
if (length % blockLen)
to.buffer.set(buffer);
return to;
}
};
// node_modules/nostr-tools/node_modules/@scure/bip32/node_modules/@noble/hashes/esm/ripemd160.js
var Rho = /* @__PURE__ */ new Uint8Array([7, 4, 13, 1, 10, 6, 15, 3, 12, 0, 9, 5, 2, 14, 11, 8]);
var Id = /* @__PURE__ */ Uint8Array.from({ length: 16 }, (_, i) => i);
var Pi = /* @__PURE__ */ Id.map((i) => (9 * i + 5) % 16);
var idxL = [Id];
var idxR = [Pi];
for (let i = 0; i < 4; i++)
for (let j of [idxL, idxR])
j.push(j[i].map((k) => Rho[k]));
var shifts = /* @__PURE__ */ [
[11, 14, 15, 12, 5, 8, 7, 9, 11, 13, 14, 15, 6, 7, 9, 8],
[12, 13, 11, 15, 6, 9, 9, 7, 12, 15, 11, 13, 7, 8, 7, 7],
[13, 15, 14, 11, 7, 7, 6, 8, 13, 14, 13, 12, 5, 5, 6, 9],
[14, 11, 12, 14, 8, 6, 5, 5, 15, 12, 15, 14, 9, 9, 8, 6],
[15, 12, 13, 13, 9, 5, 8, 6, 14, 11, 12, 11, 8, 6, 5, 5]
].map((i) => new Uint8Array(i));
var shiftsL = /* @__PURE__ */ idxL.map((idx, i) => idx.map((j) => shifts[i][j]));
var shiftsR = /* @__PURE__ */ idxR.map((idx, i) => idx.map((j) => shifts[i][j]));
var Kl = /* @__PURE__ */ new Uint32Array([
0,
1518500249,
1859775393,
2400959708,
2840853838
]);
var Kr = /* @__PURE__ */ new Uint32Array([
1352829926,
1548603684,
1836072691,
2053994217,
0
]);
var rotl = (word, shift) => word << shift | word >>> 32 - shift;
function f(group, x, y, z) {
if (group === 0)
return x ^ y ^ z;
else if (group === 1)
return x & y | ~x & z;
else if (group === 2)
return (x | ~y) ^ z;
else if (group === 3)
return x & z | y & ~z;
else
return x ^ (y | ~z);
}
var BUF = /* @__PURE__ */ new Uint32Array(16);
var RIPEMD160 = class extends SHA24 {
constructor() {
super(64, 20, 8, true);
this.h0 = 1732584193 | 0;
this.h1 = 4023233417 | 0;
this.h2 = 2562383102 | 0;
this.h3 = 271733878 | 0;
this.h4 = 3285377520 | 0;
}
get() {
const { h0, h1, h2, h3, h4 } = this;
return [h0, h1, h2, h3, h4];
}
set(h0, h1, h2, h3, h4) {
this.h0 = h0 | 0;
this.h1 = h1 | 0;
this.h2 = h2 | 0;
this.h3 = h3 | 0;
this.h4 = h4 | 0;
}
process(view, offset) {
for (let i = 0; i < 16; i++, offset += 4)
BUF[i] = view.getUint32(offset, true);
let al = this.h0 | 0, ar = al, bl = this.h1 | 0, br = bl, cl = this.h2 | 0, cr = cl, dl = this.h3 | 0, dr = dl, el = this.h4 | 0, er = el;
for (let group = 0; group < 5; group++) {
const rGroup = 4 - group;
const hbl = Kl[group], hbr = Kr[group];
const rl = idxL[group], rr = idxR[group];
const sl = shiftsL[group], sr = shiftsR[group];
for (let i = 0; i < 16; i++) {
const tl = rotl(al + f(group, bl, cl, dl) + BUF[rl[i]] + hbl, sl[i]) + el | 0;
al = el, el = dl, dl = rotl(cl, 10) | 0, cl = bl, bl = tl;
}
for (let i = 0; i < 16; i++) {
const tr = rotl(ar + f(rGroup, br, cr, dr) + BUF[rr[i]] + hbr, sr[i]) + er | 0;
ar = er, er = dr, dr = rotl(cr, 10) | 0, cr = br, br = tr;
}
}
this.set(this.h1 + cl + dr | 0, this.h2 + dl + er | 0, this.h3 + el + ar | 0, this.h4 + al + br | 0, this.h0 + bl + cr | 0);
}
roundClean() {
BUF.fill(0);
}
destroy() {
this.destroyed = true;
this.buffer.fill(0);
this.set(0, 0, 0, 0, 0);
}
};
var ripemd160 = /* @__PURE__ */ wrapConstructor4(() => new RIPEMD160());
// node_modules/nostr-tools/node_modules/@scure/bip32/node_modules/@noble/hashes/esm/sha256.js
var Chi4 = (a, b, c) => a & b ^ ~a & c;
var Maj4 = (a, b, c) => a & b ^ a & c ^ b & c;
var SHA256_K4 = /* @__PURE__ */ new Uint32Array([
1116352408,
1899447441,
3049323471,
3921009573,
961987163,
1508970993,
2453635748,
2870763221,
3624381080,
310598401,
607225278,
1426881987,
1925078388,
2162078206,
2614888103,
3248222580,
3835390401,
4022224774,
264347078,
604807628,
770255983,
1249150122,
1555081692,
1996064986,
2554220882,
2821834349,
2952996808,
3210313671,
3336571891,
3584528711,
113926993,
338241895,
666307205,
773529912,
1294757372,
1396182291,
1695183700,
1986661051,
2177026350,
2456956037,
2730485921,
2820302411,
3259730800,
3345764771,
3516065817,
3600352804,
4094571909,
275423344,
430227734,
506948616,
659060556,
883997877,
958139571,
1322822218,
1537002063,
1747873779,
1955562222,
2024104815,
2227730452,
2361852424,
2428436474,
2756734187,
3204031479,
3329325298
]);
var IV4 = /* @__PURE__ */ new Uint32Array([
1779033703,
3144134277,
1013904242,
2773480762,
1359893119,
2600822924,
528734635,
1541459225
]);
var SHA256_W4 = /* @__PURE__ */ new Uint32Array(64);
var SHA2564 = class extends SHA24 {
constructor() {
super(64, 32, 8, false);
this.A = IV4[0] | 0;
this.B = IV4[1] | 0;
this.C = IV4[2] | 0;
this.D = IV4[3] | 0;
this.E = IV4[4] | 0;
this.F = IV4[5] | 0;
this.G = IV4[6] | 0;
this.H = IV4[7] | 0;
}
get() {
const { A, B, C, D, E, F, G, H } = this;
return [A, B, C, D, E, F, G, H];
}
// prettier-ignore
set(A, B, C, D, E, F, G, H) {
this.A = A | 0;
this.B = B | 0;
this.C = C | 0;
this.D = D | 0;
this.E = E | 0;
this.F = F | 0;
this.G = G | 0;
this.H = H | 0;
}
process(view, offset) {
for (let i = 0; i < 16; i++, offset += 4)
SHA256_W4[i] = view.getUint32(offset, false);
for (let i = 16; i < 64; i++) {
const W15 = SHA256_W4[i - 15];
const W2 = SHA256_W4[i - 2];
const s0 = rotr4(W15, 7) ^ rotr4(W15, 18) ^ W15 >>> 3;
const s1 = rotr4(W2, 17) ^ rotr4(W2, 19) ^ W2 >>> 10;
SHA256_W4[i] = s1 + SHA256_W4[i - 7] + s0 + SHA256_W4[i - 16] | 0;
}
let { A, B, C, D, E, F, G, H } = this;
for (let i = 0; i < 64; i++) {
const sigma1 = rotr4(E, 6) ^ rotr4(E, 11) ^ rotr4(E, 25);
const T1 = H + sigma1 + Chi4(E, F, G) + SHA256_K4[i] + SHA256_W4[i] | 0;
const sigma0 = rotr4(A, 2) ^ rotr4(A, 13) ^ rotr4(A, 22);
const T2 = sigma0 + Maj4(A, B, C) | 0;
H = G;
G = F;
F = E;
E = D + T1 | 0;
D = C;
C = B;
B = A;
A = T1 + T2 | 0;
}
A = A + this.A | 0;
B = B + this.B | 0;
C = C + this.C | 0;
D = D + this.D | 0;
E = E + this.E | 0;
F = F + this.F | 0;
G = G + this.G | 0;
H = H + this.H | 0;
this.set(A, B, C, D, E, F, G, H);
}
roundClean() {
SHA256_W4.fill(0);
}
destroy() {
this.set(0, 0, 0, 0, 0, 0, 0, 0);
this.buffer.fill(0);
}
};
var sha2564 = /* @__PURE__ */ wrapConstructor4(() => new SHA2564());
// node_modules/nostr-tools/node_modules/@scure/bip32/node_modules/@noble/hashes/esm/_u64.js
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) {
let Ah = new Uint32Array(lst.length);
let Al = new Uint32Array(lst.length);
for (let i = 0; i < lst.length; i++) {
const { h, l } = fromBig2(lst[i], le);
[Ah[i], Al[i]] = [h, l];
}
return [Ah, Al];
}
var toBig2 = (h, l) => BigInt(h >>> 0) << _32n2 | BigInt(l >>> 0);
var shrSH2 = (h, _l, s) => h >>> s;
var shrSL2 = (h, l, s) => h << 32 - s | l >>> s;
var rotrSH2 = (h, l, s) => h >>> s | l << 32 - s;
var rotrSL2 = (h, l, s) => h << 32 - s | l >>> s;
var rotrBH2 = (h, l, s) => h << 64 - s | l >>> s - 32;
var rotrBL2 = (h, l, s) => h >>> s - 32 | l << 64 - s;
var rotr32H2 = (_h, l) => l;
var rotr32L2 = (h, _l) => h;
var rotlSH2 = (h, l, s) => h << s | l >>> 32 - s;
var rotlSL2 = (h, l, s) => l << s | h >>> 32 - s;
var rotlBH2 = (h, l, s) => l << s - 32 | h >>> 64 - s;
var rotlBL2 = (h, l, s) => h << s - 32 | l >>> 64 - s;
function add2(Ah, Al, Bh, Bl) {
const l = (Al >>> 0) + (Bl >>> 0);
return { h: Ah + Bh + (l / 2 ** 32 | 0) | 0, l: l | 0 };
}
var add3L2 = (Al, Bl, Cl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0);
var add3H2 = (low, Ah, Bh, Ch) => Ah + Bh + Ch + (low / 2 ** 32 | 0) | 0;
var add4L2 = (Al, Bl, Cl, Dl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0);
var add4H2 = (low, Ah, Bh, Ch, Dh) => Ah + Bh + Ch + Dh + (low / 2 ** 32 | 0) | 0;
var add5L2 = (Al, Bl, Cl, Dl, El) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0) + (El >>> 0);
var add5H2 = (low, Ah, Bh, Ch, Dh, Eh) => Ah + Bh + Ch + Dh + Eh + (low / 2 ** 32 | 0) | 0;
var u642 = {
fromBig: fromBig2,
split: split2,
toBig: toBig2,
shrSH: shrSH2,
shrSL: shrSL2,
rotrSH: rotrSH2,
rotrSL: rotrSL2,
rotrBH: rotrBH2,
rotrBL: rotrBL2,
rotr32H: rotr32H2,
rotr32L: rotr32L2,
rotlSH: rotlSH2,
rotlSL: rotlSL2,
rotlBH: rotlBH2,
rotlBL: rotlBL2,
add: add2,
add3L: add3L2,
add3H: add3H2,
add4L: add4L2,
add4H: add4H2,
add5H: add5H2,
add5L: add5L2
};
var u64_default2 = u642;
// node_modules/nostr-tools/node_modules/@scure/bip32/node_modules/@noble/hashes/esm/sha512.js
var [SHA512_Kh2, SHA512_Kl2] = /* @__PURE__ */ (() => u64_default2.split([
"0x428a2f98d728ae22",
"0x7137449123ef65cd",
"0xb5c0fbcfec4d3b2f",
"0xe9b5dba58189dbbc",
"0x3956c25bf348b538",
"0x59f111f1b605d019",
"0x923f82a4af194f9b",
"0xab1c5ed5da6d8118",
"0xd807aa98a3030242",
"0x12835b0145706fbe",
"0x243185be4ee4b28c",
"0x550c7dc3d5ffb4e2",
"0x72be5d74f27b896f",
"0x80deb1fe3b1696b1",
"0x9bdc06a725c71235",
"0xc19bf174cf692694",
"0xe49b69c19ef14ad2",
"0xefbe4786384f25e3",
"0x0fc19dc68b8cd5b5",
"0x240ca1cc77ac9c65",
"0x2de92c6f592b0275",
"0x4a7484aa6ea6e483",
"0x5cb0a9dcbd41fbd4",
"0x76f988da831153b5",
"0x983e5152ee66dfab",
"0xa831c66d2db43210",
"0xb00327c898fb213f",
"0xbf597fc7beef0ee4",
"0xc6e00bf33da88fc2",
"0xd5a79147930aa725",
"0x06ca6351e003826f",
"0x142929670a0e6e70",
"0x27b70a8546d22ffc",
"0x2e1b21385c26c926",
"0x4d2c6dfc5ac42aed",
"0x53380d139d95b3df",
"0x650a73548baf63de",
"0x766a0abb3c77b2a8",
"0x81c2c92e47edaee6",
"0x92722c851482353b",
"0xa2bfe8a14cf10364",
"0xa81a664bbc423001",
"0xc24b8b70d0f89791",
"0xc76c51a30654be30",
"0xd192e819d6ef5218",
"0xd69906245565a910",
"0xf40e35855771202a",
"0x106aa07032bbd1b8",
"0x19a4c116b8d2d0c8",
"0x1e376c085141ab53",
"0x2748774cdf8eeb99",
"0x34b0bcb5e19b48a8",
"0x391c0cb3c5c95a63",
"0x4ed8aa4ae3418acb",
"0x5b9cca4f7763e373",
"0x682e6ff3d6b2b8a3",
"0x748f82ee5defb2fc",
"0x78a5636f43172f60",
"0x84c87814a1f0ab72",
"0x8cc702081a6439ec",
"0x90befffa23631e28",
"0xa4506cebde82bde9",
"0xbef9a3f7b2c67915",
"0xc67178f2e372532b",
"0xca273eceea26619c",
"0xd186b8c721c0c207",
"0xeada7dd6cde0eb1e",
"0xf57d4f7fee6ed178",
"0x06f067aa72176fba",
"0x0a637dc5a2c898a6",
"0x113f9804bef90dae",
"0x1b710b35131c471b",
"0x28db77f523047d84",
"0x32caab7b40c72493",
"0x3c9ebe0a15c9bebc",
"0x431d67c49c100d4c",
"0x4cc5d4becb3e42b6",
"0x597f299cfc657e2a",
"0x5fcb6fab3ad6faec",
"0x6c44198c4a475817"
].map((n) => BigInt(n))))();
var SHA512_W_H2 = /* @__PURE__ */ new Uint32Array(80);
var SHA512_W_L2 = /* @__PURE__ */ new Uint32Array(80);
var SHA5122 = class extends SHA24 {
constructor() {
super(128, 64, 16, false);
this.Ah = 1779033703 | 0;
this.Al = 4089235720 | 0;
this.Bh = 3144134277 | 0;
this.Bl = 2227873595 | 0;
this.Ch = 1013904242 | 0;
this.Cl = 4271175723 | 0;
this.Dh = 2773480762 | 0;
this.Dl = 1595750129 | 0;
this.Eh = 1359893119 | 0;
this.El = 2917565137 | 0;
this.Fh = 2600822924 | 0;
this.Fl = 725511199 | 0;
this.Gh = 528734635 | 0;
this.Gl = 4215389547 | 0;
this.Hh = 1541459225 | 0;
this.Hl = 327033209 | 0;
}
// prettier-ignore
get() {
const { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;
return [Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl];
}
// prettier-ignore
set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl) {
this.Ah = Ah | 0;
this.Al = Al | 0;
this.Bh = Bh | 0;
this.Bl = Bl | 0;
this.Ch = Ch | 0;
this.Cl = Cl | 0;
this.Dh = Dh | 0;
this.Dl = Dl | 0;
this.Eh = Eh | 0;
this.El = El | 0;
this.Fh = Fh | 0;
this.Fl = Fl | 0;
this.Gh = Gh | 0;
this.Gl = Gl | 0;
this.Hh = Hh | 0;
this.Hl = Hl | 0;
}
process(view, offset) {
for (let i = 0; i < 16; i++, offset += 4) {
SHA512_W_H2[i] = view.getUint32(offset);
SHA512_W_L2[i] = view.getUint32(offset += 4);
}
for (let i = 16; i < 80; i++) {
const W15h = SHA512_W_H2[i - 15] | 0;
const W15l = SHA512_W_L2[i - 15] | 0;
const s0h = u64_default2.rotrSH(W15h, W15l, 1) ^ u64_default2.rotrSH(W15h, W15l, 8) ^ u64_default2.shrSH(W15h, W15l, 7);
const s0l = u64_default2.rotrSL(W15h, W15l, 1) ^ u64_default2.rotrSL(W15h, W15l, 8) ^ u64_default2.shrSL(W15h, W15l, 7);
const W2h = SHA512_W_H2[i - 2] | 0;
const W2l = SHA512_W_L2[i - 2] | 0;
const s1h = u64_default2.rotrSH(W2h, W2l, 19) ^ u64_default2.rotrBH(W2h, W2l, 61) ^ u64_default2.shrSH(W2h, W2l, 6);
const s1l = u64_default2.rotrSL(W2h, W2l, 19) ^ u64_default2.rotrBL(W2h, W2l, 61) ^ u64_default2.shrSL(W2h, W2l, 6);
const SUMl = u64_default2.add4L(s0l, s1l, SHA512_W_L2[i - 7], SHA512_W_L2[i - 16]);
const SUMh = u64_default2.add4H(SUMl, s0h, s1h, SHA512_W_H2[i - 7], SHA512_W_H2[i - 16]);
SHA512_W_H2[i] = SUMh | 0;
SHA512_W_L2[i] = SUMl | 0;
}
let { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;
for (let i = 0; i < 80; i++) {
const sigma1h = u64_default2.rotrSH(Eh, El, 14) ^ u64_default2.rotrSH(Eh, El, 18) ^ u64_default2.rotrBH(Eh, El, 41);
const sigma1l = u64_default2.rotrSL(Eh, El, 14) ^ u64_default2.rotrSL(Eh, El, 18) ^ u64_default2.rotrBL(Eh, El, 41);
const CHIh = Eh & Fh ^ ~Eh & Gh;
const CHIl = El & Fl ^ ~El & Gl;
const T1ll = u64_default2.add5L(Hl, sigma1l, CHIl, SHA512_Kl2[i], SHA512_W_L2[i]);
const T1h = u64_default2.add5H(T1ll, Hh, sigma1h, CHIh, SHA512_Kh2[i], SHA512_W_H2[i]);
const T1l = T1ll | 0;
const sigma0h = u64_default2.rotrSH(Ah, Al, 28) ^ u64_default2.rotrBH(Ah, Al, 34) ^ u64_default2.rotrBH(Ah, Al, 39);
const sigma0l = u64_default2.rotrSL(Ah, Al, 28) ^ u64_default2.rotrBL(Ah, Al, 34) ^ u64_default2.rotrBL(Ah, Al, 39);
const MAJh = Ah & Bh ^ Ah & Ch ^ Bh & Ch;
const MAJl = Al & Bl ^ Al & Cl ^ Bl & Cl;
Hh = Gh | 0;
Hl = Gl | 0;
Gh = Fh | 0;
Gl = Fl | 0;
Fh = Eh | 0;
Fl = El | 0;
({ h: Eh, l: El } = u64_default2.add(Dh | 0, Dl | 0, T1h | 0, T1l | 0));
Dh = Ch | 0;
Dl = Cl | 0;
Ch = Bh | 0;
Cl = Bl | 0;
Bh = Ah | 0;
Bl = Al | 0;
const All = u64_default2.add3L(T1l, sigma0l, MAJl);
Ah = u64_default2.add3H(All, T1h, sigma0h, MAJh);
Al = All | 0;
}
({ h: Ah, l: Al } = u64_default2.add(this.Ah | 0, this.Al | 0, Ah | 0, Al | 0));
({ h: Bh, l: Bl } = u64_default2.add(this.Bh | 0, this.Bl | 0, Bh | 0, Bl | 0));
({ h: Ch, l: Cl } = u64_default2.add(this.Ch | 0, this.Cl | 0, Ch | 0, Cl | 0));
({ h: Dh, l: Dl } = u64_default2.add(this.Dh | 0, this.Dl | 0, Dh | 0, Dl | 0));
({ h: Eh, l: El } = u64_default2.add(this.Eh | 0, this.El | 0, Eh | 0, El | 0));
({ h: Fh, l: Fl } = u64_default2.add(this.Fh | 0, this.Fl | 0, Fh | 0, Fl | 0));
({ h: Gh, l: Gl } = u64_default2.add(this.Gh | 0, this.Gl | 0, Gh | 0, Gl | 0));
({ h: Hh, l: Hl } = u64_default2.add(this.Hh | 0, this.Hl | 0, Hh | 0, Hl | 0));
this.set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl);
}
roundClean() {
SHA512_W_H2.fill(0);
SHA512_W_L2.fill(0);
}
destroy() {
this.buffer.fill(0);
this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
}
};
var sha5122 = /* @__PURE__ */ wrapConstructor4(() => new SHA5122());
// node_modules/nostr-tools/node_modules/@scure/bip32/node_modules/@scure/base/lib/esm/index.js
// @__NO_SIDE_EFFECTS__
function assertNumber3(n) {
if (!Number.isSafeInteger(n))
throw new Error(`Wrong integer: ${n}`);
}
// @__NO_SIDE_EFFECTS__
function chain3(...args) {
const wrap = (a, b) => (c) => a(b(c));
const encode = Array.from(args).reverse().reduce((acc, i) => acc ? wrap(acc, i.encode) : i.encode, void 0);
const decode2 = args.reduce((acc, i) => acc ? wrap(acc, i.decode) : i.decode, void 0);
return { encode, decode: decode2 };
}
// @__NO_SIDE_EFFECTS__
function alphabet3(alphabet4) {
return {
encode: (digits) => {
if (!Array.isArray(digits) || digits.length && typeof digits[0] !== "number")
throw new Error("alphabet.encode input should be an array of numbers");
return digits.map((i) => {
/* @__PURE__ */ assertNumber3(i);
if (i < 0 || i >= alphabet4.length)
throw new Error(`Digit index outside alphabet: ${i} (alphabet: ${alphabet4.length})`);
return alphabet4[i];
});
},
decode: (input) => {
if (!Array.isArray(input) || input.length && typeof input[0] !== "string")
throw new Error("alphabet.decode input should be array of strings");
return input.map((letter) => {
if (typeof letter !== "string")
throw new Error(`alphabet.decode: not string element=${letter}`);
const index = alphabet4.indexOf(letter);
if (index === -1)
throw new Error(`Unknown letter: "${letter}". Allowed: ${alphabet4}`);
return index;
});
}
};
}
// @__NO_SIDE_EFFECTS__
function join3(separator = "") {
if (typeof separator !== "string")
throw new Error("join separator should be string");
return {
encode: (from) => {
if (!Array.isArray(from) || from.length && typeof from[0] !== "string")
throw new Error("join.encode input should be array of strings");
for (let i of from)
if (typeof i !== "string")
throw new Error(`join.encode: non-string input=${i}`);
return from.join(separator);
},
decode: (to) => {
if (typeof to !== "string")
throw new Error("join.decode input should be string");
return to.split(separator);
}
};
}
// @__NO_SIDE_EFFECTS__
function convertRadix4(data, from, to) {
if (from < 2)
throw new Error(`convertRadix: wrong from=${from}, base cannot be less than 2`);
if (to < 2)
throw new Error(`convertRadix: wrong to=${to}, base cannot be less than 2`);
if (!Array.isArray(data))
throw new Error("convertRadix: data should be array");
if (!data.length)
return [];
let pos = 0;
const res = [];
const digits = Array.from(data);
digits.forEach((d) => {
/* @__PURE__ */ assertNumber3(d);
if (d < 0 || d >= from)
throw new Error(`Wrong integer: ${d}`);
});
while (true) {
let carry = 0;
let done = true;
for (let i = pos; i < digits.length; i++) {
const digit = digits[i];
const digitBase = from * carry + digit;
if (!Number.isSafeInteger(digitBase) || from * carry / from !== carry || digitBase - digit !== from * carry) {
throw new Error("convertRadix: carry overflow");
}
carry = digitBase % to;
const rounded = Math.floor(digitBase / to);
digits[i] = rounded;
if (!Number.isSafeInteger(rounded) || rounded * to + carry !== digitBase)
throw new Error("convertRadix: carry overflow");
if (!done)
continue;
else if (!rounded)
pos = i;
else
done = false;
}
res.push(carry);
if (done)
break;
}
for (let i = 0; i < data.length - 1 && data[i] === 0; i++)
res.push(0);
return res.reverse();
}
// @__NO_SIDE_EFFECTS__
function radix4(num) {
/* @__PURE__ */ assertNumber3(num);
return {
encode: (bytes6) => {
if (!(bytes6 instanceof Uint8Array))
throw new Error("radix.encode input should be Uint8Array");
return /* @__PURE__ */ convertRadix4(Array.from(bytes6), 2 ** 8, num);
},
decode: (digits) => {
if (!Array.isArray(digits) || digits.length && typeof digits[0] !== "number")
throw new Error("radix.decode input should be array of strings");
return Uint8Array.from(/* @__PURE__ */ convertRadix4(digits, num, 2 ** 8));
}
};
}
// @__NO_SIDE_EFFECTS__
function checksum2(len, fn) {
/* @__PURE__ */ assertNumber3(len);
if (typeof fn !== "function")
throw new Error("checksum fn should be function");
return {
encode(data) {
if (!(data instanceof Uint8Array))
throw new Error("checksum.encode: input should be Uint8Array");
const checksum3 = fn(data).slice(0, len);
const res = new Uint8Array(data.length + len);
res.set(data);
res.set(checksum3, data.length);
return res;
},
decode(data) {
if (!(data instanceof Uint8Array))
throw new Error("checksum.decode: input should be Uint8Array");
const payload = data.slice(0, -len);
const newChecksum = fn(payload).slice(0, len);
const oldChecksum = data.slice(-len);
for (let i = 0; i < len; i++)
if (newChecksum[i] !== oldChecksum[i])
throw new Error("Invalid checksum");
return payload;
}
};
}
var genBase582 = (abc) => /* @__PURE__ */ chain3(/* @__PURE__ */ radix4(58), /* @__PURE__ */ alphabet3(abc), /* @__PURE__ */ join3(""));
var base582 = /* @__PURE__ */ genBase582("123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz");
var base58check = (sha2565) => /* @__PURE__ */ chain3(/* @__PURE__ */ checksum2(4, (data) => sha2565(sha2565(data))), base582);
// node_modules/nostr-tools/node_modules/@scure/bip32/lib/esm/index.js
var Point2 = secp256k1.ProjectivePoint;
var base58check2 = base58check(sha2564);
function bytesToNumber(bytes6) {
return BigInt(`0x${bytesToHex3(bytes6)}`);
}
function numberToBytes(num) {
return hexToBytes3(num.toString(16).padStart(64, "0"));
}
var MASTER_SECRET = utf8ToBytes5("Bitcoin seed");
var BITCOIN_VERSIONS = { private: 76066276, public: 76067358 };
var HARDENED_OFFSET = 2147483648;
var hash160 = (data) => ripemd160(sha2564(data));
var fromU32 = (data) => createView4(data).getUint32(0, false);
var toU32 = (n) => {
if (!Number.isSafeInteger(n) || n < 0 || n > 2 ** 32 - 1) {
throw new Error(`Invalid number=${n}. Should be from 0 to 2 ** 32 - 1`);
}
const buf = new Uint8Array(4);
createView4(buf).setUint32(0, n, false);
return buf;
};
var HDKey = class _HDKey {
get fingerprint() {
if (!this.pubHash) {
throw new Error("No publicKey set!");
}
return fromU32(this.pubHash);
}
get identifier() {
return this.pubHash;
}
get pubKeyHash() {
return this.pubHash;
}
get privateKey() {
return this.privKeyBytes || null;
}
get publicKey() {
return this.pubKey || null;
}
get privateExtendedKey() {
const priv = this.privateKey;
if (!priv) {
throw new Error("No private key");
}
return base58check2.encode(this.serialize(this.versions.private, concatBytes4(new Uint8Array([0]), priv)));
}
get publicExtendedKey() {
if (!this.pubKey) {
throw new Error("No public key");
}
return base58check2.encode(this.serialize(this.versions.public, this.pubKey));
}
static fromMasterSeed(seed, versions = BITCOIN_VERSIONS) {
bytes4(seed);
if (8 * seed.length < 128 || 8 * seed.length > 512) {
throw new Error(`HDKey: wrong seed length=${seed.length}. Should be between 128 and 512 bits; 256 bits is advised)`);
}
const I = hmac3(sha5122, MASTER_SECRET, seed);
return new _HDKey({
versions,
chainCode: I.slice(32),
privateKey: I.slice(0, 32)
});
}
static fromExtendedKey(base58key, versions = BITCOIN_VERSIONS) {
const keyBuffer = base58check2.decode(base58key);
const keyView = createView4(keyBuffer);
const version = keyView.getUint32(0, false);
const opt = {
versions,
depth: keyBuffer[4],
parentFingerprint: keyView.getUint32(5, false),
index: keyView.getUint32(9, false),
chainCode: keyBuffer.slice(13, 45)
};
const key = keyBuffer.slice(45);
const isPriv = key[0] === 0;
if (version !== versions[isPriv ? "private" : "public"]) {
throw new Error("Version mismatch");
}
if (isPriv) {
return new _HDKey({ ...opt, privateKey: key.slice(1) });
} else {
return new _HDKey({ ...opt, publicKey: key });
}
}
static fromJSON(json) {
return _HDKey.fromExtendedKey(json.xpriv);
}
constructor(opt) {
this.depth = 0;
this.index = 0;
this.chainCode = null;
this.parentFingerprint = 0;
if (!opt || typeof opt !== "object") {
throw new Error("HDKey.constructor must not be called directly");
}
this.versions = opt.versions || BITCOIN_VERSIONS;
this.depth = opt.depth || 0;
this.chainCode = opt.chainCode;
this.index = opt.index || 0;
this.parentFingerprint = opt.parentFingerprint || 0;
if (!this.depth) {
if (this.parentFingerprint || this.index) {
throw new Error("HDKey: zero depth with non-zero index/parent fingerprint");
}
}
if (opt.publicKey && opt.privateKey) {
throw new Error("HDKey: publicKey and privateKey at same time.");
}
if (opt.privateKey) {
if (!secp256k1.utils.isValidPrivateKey(opt.privateKey)) {
throw new Error("Invalid private key");
}
this.privKey = typeof opt.privateKey === "bigint" ? opt.privateKey : bytesToNumber(opt.privateKey);
this.privKeyBytes = numberToBytes(this.privKey);
this.pubKey = secp256k1.getPublicKey(opt.privateKey, true);
} else if (opt.publicKey) {
this.pubKey = Point2.fromHex(opt.publicKey).toRawBytes(true);
} else {
throw new Error("HDKey: no public or private key provided");
}
this.pubHash = hash160(this.pubKey);
}
derive(path) {
if (!/^[mM]'?/.test(path)) {
throw new Error('Path must start with "m" or "M"');
}
if (/^[mM]'?$/.test(path)) {
return this;
}
const parts = path.replace(/^[mM]'?\//, "").split("/");
let child = this;
for (const c of parts) {
const m = /^(\d+)('?)$/.exec(c);
if (!m || m.length !== 3) {
throw new Error(`Invalid child index: ${c}`);
}
let idx = +m[1];
if (!Number.isSafeInteger(idx) || idx >= HARDENED_OFFSET) {
throw new Error("Invalid index");
}
if (m[2] === "'") {
idx += HARDENED_OFFSET;
}
child = child.deriveChild(idx);
}
return child;
}
deriveChild(index) {
if (!this.pubKey || !this.chainCode) {
throw new Error("No publicKey or chainCode set");
}
let data = toU32(index);
if (index >= HARDENED_OFFSET) {
const priv = this.privateKey;
if (!priv) {
throw new Error("Could not derive hardened child key");
}
data = concatBytes4(new Uint8Array([0]), priv, data);
} else {
data = concatBytes4(this.pubKey, data);
}
const I = hmac3(sha5122, this.chainCode, data);
const childTweak = bytesToNumber(I.slice(0, 32));
const chainCode = I.slice(32);
if (!secp256k1.utils.isValidPrivateKey(childTweak)) {
throw new Error("Tweak bigger than curve order");
}
const opt = {
versions: this.versions,
chainCode,
depth: this.depth + 1,
parentFingerprint: this.fingerprint,
index
};
try {
if (this.privateKey) {
const added = mod(this.privKey + childTweak, secp256k1.CURVE.n);
if (!secp256k1.utils.isValidPrivateKey(added)) {
throw new Error("The tweak was out of range or the resulted private key is invalid");
}
opt.privateKey = added;
} else {
const added = Point2.fromHex(this.pubKey).add(Point2.fromPrivateKey(childTweak));
if (added.equals(Point2.ZERO)) {
throw new Error("The tweak was equal to negative P, which made the result key invalid");
}
opt.publicKey = added.toRawBytes(true);
}
return new _HDKey(opt);
} catch (err) {
return this.deriveChild(index + 1);
}
}
sign(hash6) {
if (!this.privateKey) {
throw new Error("No privateKey set!");
}
bytes4(hash6, 32);
return secp256k1.sign(hash6, this.privKey).toCompactRawBytes();
}
verify(hash6, signature) {
bytes4(hash6, 32);
bytes4(signature, 64);
if (!this.publicKey) {
throw new Error("No publicKey set!");
}
let sig;
try {
sig = secp256k1.Signature.fromCompact(signature);
} catch (error) {
return false;
}
return secp256k1.verify(sig, hash6, this.publicKey);
}
wipePrivateData() {
this.privKey = void 0;
if (this.privKeyBytes) {
this.privKeyBytes.fill(0);
this.privKeyBytes = void 0;
}
return this;
}
toJSON() {
return {
xpriv: this.privateExtendedKey,
xpub: this.publicExtendedKey
};
}
serialize(version, key) {
if (!this.chainCode) {
throw new Error("No chainCode set");
}
bytes4(key, 33);
return concatBytes4(toU32(version), new Uint8Array([this.depth]), toU32(this.parentFingerprint), toU32(this.index), this.chainCode, key);
}
};
// node_modules/@noble/ciphers/esm/utils.js
var u8a6 = (a) => a instanceof Uint8Array;
var u32 = (arr) => new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4));
var isLE5 = new Uint8Array(new Uint32Array([287454020]).buffer)[0] === 68;
if (!isLE5)
throw new Error("Non little-endian hardware is not supported");
function utf8ToBytes6(str) {
if (typeof str !== "string")
throw new Error(`utf8ToBytes expected string, got ${typeof str}`);
return new Uint8Array(new TextEncoder().encode(str));
}
function toBytes5(data) {
if (typeof data === "string")
data = utf8ToBytes6(data);
if (!u8a6(data))
throw new Error(`expected Uint8Array, got ${typeof data}`);
return data;
}
var isPlainObject = (obj) => Object.prototype.toString.call(obj) === "[object Object]" && obj.constructor === Object;
function checkOpts2(defaults, opts) {
if (opts !== void 0 && (typeof opts !== "object" || !isPlainObject(opts)))
throw new Error("options must be object or undefined");
const merged = Object.assign(defaults, opts);
return merged;
}
function ensureBytes2(b, len) {
if (!(b instanceof Uint8Array))
throw new Error("Uint8Array expected");
if (typeof len === "number") {
if (b.length !== len)
throw new Error(`Uint8Array length ${len} expected`);
}
}
function equalBytes2(a, b) {
if (a.length !== b.length)
throw new Error("equalBytes: Different size of Uint8Arrays");
let isSame = true;
for (let i = 0; i < a.length; i++)
isSame && (isSame = a[i] === b[i]);
return isSame;
}
// node_modules/@noble/ciphers/esm/_assert.js
function number5(n) {
if (!Number.isSafeInteger(n) || n < 0)
throw new Error(`Wrong positive integer: ${n}`);
}
function bool4(b) {
if (typeof b !== "boolean")
throw new Error(`Expected boolean, not ${b}`);
}
function bytes5(b, ...lengths) {
if (!(b instanceof Uint8Array))
throw new Error("Expected Uint8Array");
if (lengths.length > 0 && !lengths.includes(b.length))
throw new Error(`Expected Uint8Array of length ${lengths}, not of length=${b.length}`);
}
function hash5(hash6) {
if (typeof hash6 !== "function" || typeof hash6.create !== "function")
throw new Error("hash must be wrapped by utils.wrapConstructor");
number5(hash6.outputLen);
number5(hash6.blockLen);
}
function exists5(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 output5(out, instance) {
bytes5(out);
const min = instance.outputLen;
if (out.length < min) {
throw new Error(`digestInto() expects output buffer of length at least ${min}`);
}
}
var assert4 = { number: number5, bool: bool4, bytes: bytes5, hash: hash5, exists: exists5, output: output5 };
var assert_default4 = assert4;
// node_modules/@noble/ciphers/esm/_poly1305.js
var u8to16 = (a, i) => a[i++] & 255 | (a[i++] & 255) << 8;
var Poly1305 = class {
constructor(key) {
this.blockLen = 16;
this.outputLen = 16;
this.buffer = new Uint8Array(16);
this.r = new Uint16Array(10);
this.h = new Uint16Array(10);
this.pad = new Uint16Array(8);
this.pos = 0;
this.finished = false;
key = toBytes5(key);
ensureBytes2(key, 32);
const t0 = u8to16(key, 0);
const t1 = u8to16(key, 2);
const t2 = u8to16(key, 4);
const t3 = u8to16(key, 6);
const t4 = u8to16(key, 8);
const t5 = u8to16(key, 10);
const t6 = u8to16(key, 12);
const t7 = u8to16(key, 14);
this.r[0] = t0 & 8191;
this.r[1] = (t0 >>> 13 | t1 << 3) & 8191;
this.r[2] = (t1 >>> 10 | t2 << 6) & 7939;
this.r[3] = (t2 >>> 7 | t3 << 9) & 8191;
this.r[4] = (t3 >>> 4 | t4 << 12) & 255;
this.r[5] = t4 >>> 1 & 8190;
this.r[6] = (t4 >>> 14 | t5 << 2) & 8191;
this.r[7] = (t5 >>> 11 | t6 << 5) & 8065;
this.r[8] = (t6 >>> 8 | t7 << 8) & 8191;
this.r[9] = t7 >>> 5 & 127;
for (let i = 0; i < 8; i++)
this.pad[i] = u8to16(key, 16 + 2 * i);
}
process(data, offset, isLast = false) {
const hibit = isLast ? 0 : 1 << 11;
const { h, r } = this;
const r0 = r[0];
const r1 = r[1];
const r2 = r[2];
const r3 = r[3];
const r4 = r[4];
const r5 = r[5];
const r6 = r[6];
const r7 = r[7];
const r8 = r[8];
const r9 = r[9];
const t0 = u8to16(data, offset + 0);
const t1 = u8to16(data, offset + 2);
const t2 = u8to16(data, offset + 4);
const t3 = u8to16(data, offset + 6);
const t4 = u8to16(data, offset + 8);
const t5 = u8to16(data, offset + 10);
const t6 = u8to16(data, offset + 12);
const t7 = u8to16(data, offset + 14);
let h0 = h[0] + (t0 & 8191);
let h1 = h[1] + ((t0 >>> 13 | t1 << 3) & 8191);
let h2 = h[2] + ((t1 >>> 10 | t2 << 6) & 8191);
let h3 = h[3] + ((t2 >>> 7 | t3 << 9) & 8191);
let h4 = h[4] + ((t3 >>> 4 | t4 << 12) & 8191);
let h5 = h[5] + (t4 >>> 1 & 8191);
let h6 = h[6] + ((t4 >>> 14 | t5 << 2) & 8191);
let h7 = h[7] + ((t5 >>> 11 | t6 << 5) & 8191);
let h8 = h[8] + ((t6 >>> 8 | t7 << 8) & 8191);
let h9 = h[9] + (t7 >>> 5 | hibit);
let c = 0;
let d0 = c + h0 * r0 + h1 * (5 * r9) + h2 * (5 * r8) + h3 * (5 * r7) + h4 * (5 * r6);
c = d0 >>> 13;
d0 &= 8191;
d0 += h5 * (5 * r5) + h6 * (5 * r4) + h7 * (5 * r3) + h8 * (5 * r2) + h9 * (5 * r1);
c += d0 >>> 13;
d0 &= 8191;
let d1 = c + h0 * r1 + h1 * r0 + h2 * (5 * r9) + h3 * (5 * r8) + h4 * (5 * r7);
c = d1 >>> 13;
d1 &= 8191;
d1 += h5 * (5 * r6) + h6 * (5 * r5) + h7 * (5 * r4) + h8 * (5 * r3) + h9 * (5 * r2);
c += d1 >>> 13;
d1 &= 8191;
let d2 = c + h0 * r2 + h1 * r1 + h2 * r0 + h3 * (5 * r9) + h4 * (5 * r8);
c = d2 >>> 13;
d2 &= 8191;
d2 += h5 * (5 * r7) + h6 * (5 * r6) + h7 * (5 * r5) + h8 * (5 * r4) + h9 * (5 * r3);
c += d2 >>> 13;
d2 &= 8191;
let d3 = c + h0 * r3 + h1 * r2 + h2 * r1 + h3 * r0 + h4 * (5 * r9);
c = d3 >>> 13;
d3 &= 8191;
d3 += h5 * (5 * r8) + h6 * (5 * r7) + h7 * (5 * r6) + h8 * (5 * r5) + h9 * (5 * r4);
c += d3 >>> 13;
d3 &= 8191;
let d4 = c + h0 * r4 + h1 * r3 + h2 * r2 + h3 * r1 + h4 * r0;
c = d4 >>> 13;
d4 &= 8191;
d4 += h5 * (5 * r9) + h6 * (5 * r8) + h7 * (5 * r7) + h8 * (5 * r6) + h9 * (5 * r5);
c += d4 >>> 13;
d4 &= 8191;
let d5 = c + h0 * r5 + h1 * r4 + h2 * r3 + h3 * r2 + h4 * r1;
c = d5 >>> 13;
d5 &= 8191;
d5 += h5 * r0 + h6 * (5 * r9) + h7 * (5 * r8) + h8 * (5 * r7) + h9 * (5 * r6);
c += d5 >>> 13;
d5 &= 8191;
let d6 = c + h0 * r6 + h1 * r5 + h2 * r4 + h3 * r3 + h4 * r2;
c = d6 >>> 13;
d6 &= 8191;
d6 += h5 * r1 + h6 * r0 + h7 * (5 * r9) + h8 * (5 * r8) + h9 * (5 * r7);
c += d6 >>> 13;
d6 &= 8191;
let d7 = c + h0 * r7 + h1 * r6 + h2 * r5 + h3 * r4 + h4 * r3;
c = d7 >>> 13;
d7 &= 8191;
d7 += h5 * r2 + h6 * r1 + h7 * r0 + h8 * (5 * r9) + h9 * (5 * r8);
c += d7 >>> 13;
d7 &= 8191;
let d8 = c + h0 * r8 + h1 * r7 + h2 * r6 + h3 * r5 + h4 * r4;
c = d8 >>> 13;
d8 &= 8191;
d8 += h5 * r3 + h6 * r2 + h7 * r1 + h8 * r0 + h9 * (5 * r9);
c += d8 >>> 13;
d8 &= 8191;
let d9 = c + h0 * r9 + h1 * r8 + h2 * r7 + h3 * r6 + h4 * r5;
c = d9 >>> 13;
d9 &= 8191;
d9 += h5 * r4 + h6 * r3 + h7 * r2 + h8 * r1 + h9 * r0;
c += d9 >>> 13;
d9 &= 8191;
c = (c << 2) + c | 0;
c = c + d0 | 0;
d0 = c & 8191;
c = c >>> 13;
d1 += c;
h[0] = d0;
h[1] = d1;
h[2] = d2;
h[3] = d3;
h[4] = d4;
h[5] = d5;
h[6] = d6;
h[7] = d7;
h[8] = d8;
h[9] = d9;
}
finalize() {
const { h, pad } = this;
const g = new Uint16Array(10);
let c = h[1] >>> 13;
h[1] &= 8191;
for (let i = 2; i < 10; i++) {
h[i] += c;
c = h[i] >>> 13;
h[i] &= 8191;
}
h[0] += c * 5;
c = h[0] >>> 13;
h[0] &= 8191;
h[1] += c;
c = h[1] >>> 13;
h[1] &= 8191;
h[2] += c;
g[0] = h[0] + 5;
c = g[0] >>> 13;
g[0] &= 8191;
for (let i = 1; i < 10; i++) {
g[i] = h[i] + c;
c = g[i] >>> 13;
g[i] &= 8191;
}
g[9] -= 1 << 13;
let mask = (c ^ 1) - 1;
for (let i = 0; i < 10; i++)
g[i] &= mask;
mask = ~mask;
for (let i = 0; i < 10; i++)
h[i] = h[i] & mask | g[i];
h[0] = (h[0] | h[1] << 13) & 65535;
h[1] = (h[1] >>> 3 | h[2] << 10) & 65535;
h[2] = (h[2] >>> 6 | h[3] << 7) & 65535;
h[3] = (h[3] >>> 9 | h[4] << 4) & 65535;
h[4] = (h[4] >>> 12 | h[5] << 1 | h[6] << 14) & 65535;
h[5] = (h[6] >>> 2 | h[7] << 11) & 65535;
h[6] = (h[7] >>> 5 | h[8] << 8) & 65535;
h[7] = (h[8] >>> 8 | h[9] << 5) & 65535;
let f2 = h[0] + pad[0];
h[0] = f2 & 65535;
for (let i = 1; i < 8; i++) {
f2 = (h[i] + pad[i] | 0) + (f2 >>> 16) | 0;
h[i] = f2 & 65535;
}
}
update(data) {
assert_default4.exists(this);
const { buffer, blockLen } = this;
data = toBytes5(data);
const len = data.length;
for (let pos = 0; pos < len; ) {
const take = Math.min(blockLen - this.pos, len - pos);
if (take === blockLen) {
for (; blockLen <= len - pos; pos += blockLen)
this.process(data, pos);
continue;
}
buffer.set(data.subarray(pos, pos + take), this.pos);
this.pos += take;
pos += take;
if (this.pos === blockLen) {
this.process(buffer, 0, false);
this.pos = 0;
}
}
return this;
}
destroy() {
this.h.fill(0);
this.r.fill(0);
this.buffer.fill(0);
this.pad.fill(0);
}
digestInto(out) {
assert_default4.exists(this);
assert_default4.output(out, this);
this.finished = true;
const { buffer, h } = this;
let { pos } = this;
if (pos) {
buffer[pos++] = 1;
for (; pos < 16; pos++)
buffer[pos] = 0;
this.process(buffer, 0, true);
}
this.finalize();
let opos = 0;
for (let i = 0; i < 8; i++) {
out[opos++] = h[i] >>> 0;
out[opos++] = h[i] >>> 8;
}
return out;
}
digest() {
const { buffer, outputLen } = this;
this.digestInto(buffer);
const res = buffer.slice(0, outputLen);
this.destroy();
return res;
}
};
function wrapConstructorWithKey(hashCons) {
const hashC = (msg, key) => hashCons(key).update(toBytes5(msg)).digest();
const tmp = hashCons(new Uint8Array(32));
hashC.outputLen = tmp.outputLen;
hashC.blockLen = tmp.blockLen;
hashC.create = (key) => hashCons(key);
return hashC;
}
var poly1305 = wrapConstructorWithKey((key) => new Poly1305(key));
// node_modules/@noble/ciphers/esm/_salsa.js
var sigma16 = utf8ToBytes6("expand 16-byte k");
var sigma32 = utf8ToBytes6("expand 32-byte k");
var sigma16_32 = u32(sigma16);
var sigma32_32 = u32(sigma32);
var isAligned32 = (b) => !(b.byteOffset % 4);
var salsaBasic = (opts) => {
const { core, rounds, counterRight, counterLen, allow128bitKeys, extendNonceFn, blockLen } = checkOpts2({ rounds: 20, counterRight: false, counterLen: 8, allow128bitKeys: true, blockLen: 64 }, opts);
assert_default4.number(counterLen);
assert_default4.number(rounds);
assert_default4.number(blockLen);
assert_default4.bool(counterRight);
assert_default4.bool(allow128bitKeys);
const blockLen32 = blockLen / 4;
if (blockLen % 4 !== 0)
throw new Error("Salsa/ChaCha: blockLen must be aligned to 4 bytes");
return (key, nonce, data, output6, counter = 0) => {
assert_default4.bytes(key);
assert_default4.bytes(nonce);
assert_default4.bytes(data);
if (!output6)
output6 = new Uint8Array(data.length);
assert_default4.bytes(output6);
assert_default4.number(counter);
if (counter < 0 || counter >= 2 ** 32 - 1)
throw new Error("Salsa/ChaCha: counter overflow");
if (output6.length < data.length) {
throw new Error(`Salsa/ChaCha: output (${output6.length}) is shorter than data (${data.length})`);
}
const toClean = [];
let k, sigma;
if (key.length === 32) {
k = key;
sigma = sigma32_32;
} else if (key.length === 16 && allow128bitKeys) {
k = new Uint8Array(32);
k.set(key);
k.set(key, 16);
sigma = sigma16_32;
toClean.push(k);
} else
throw new Error(`Salsa/ChaCha: invalid 32-byte key, got length=${key.length}`);
if (extendNonceFn) {
if (nonce.length <= 16)
throw new Error(`Salsa/ChaCha: extended nonce must be bigger than 16 bytes`);
k = extendNonceFn(sigma, k, nonce.subarray(0, 16), new Uint8Array(32));
toClean.push(k);
nonce = nonce.subarray(16);
}
const nonceLen = 16 - counterLen;
if (nonce.length !== nonceLen)
throw new Error(`Salsa/ChaCha: nonce must be ${nonceLen} or 16 bytes`);
if (nonceLen !== 12) {
const nc = new Uint8Array(12);
nc.set(nonce, counterRight ? 0 : 12 - nonce.length);
toClean.push(nonce = nc);
}
const block = new Uint8Array(blockLen);
const b32 = u32(block);
const k32 = u32(k);
const n32 = u32(nonce);
const d32 = isAligned32(data) && u32(data);
const o32 = isAligned32(output6) && u32(output6);
toClean.push(b32);
const len = data.length;
for (let pos = 0, ctr = counter; pos < len; ctr++) {
core(sigma, k32, n32, b32, ctr, rounds);
if (ctr >= 2 ** 32 - 1)
throw new Error("Salsa/ChaCha: counter overflow");
const take = Math.min(blockLen, len - pos);
if (take === blockLen && o32 && d32) {
const pos32 = pos / 4;
if (pos % 4 !== 0)
throw new Error("Salsa/ChaCha: invalid block position");
for (let j = 0; j < blockLen32; j++)
o32[pos32 + j] = d32[pos32 + j] ^ b32[j];
pos += blockLen;
continue;
}
for (let j = 0; j < take; j++)
output6[pos + j] = data[pos + j] ^ block[j];
pos += take;
}
for (let i = 0; i < toClean.length; i++)
toClean[i].fill(0);
return output6;
};
};
// node_modules/@noble/ciphers/esm/chacha.js
var rotl2 = (a, b) => a << b | a >>> 32 - b;
function chachaCore(c, k, n, out, cnt, rounds = 20) {
let y00 = c[0], y01 = c[1], y02 = c[2], y03 = c[3];
let y04 = k[0], y05 = k[1], y06 = k[2], y07 = k[3];
let y08 = k[4], y09 = k[5], y10 = k[6], y11 = k[7];
let y12 = cnt, y13 = n[0], y14 = n[1], y15 = n[2];
let x00 = y00, x01 = y01, x02 = y02, x03 = y03, x04 = y04, x05 = y05, x06 = y06, x07 = y07, x08 = y08, x09 = y09, x10 = y10, x11 = y11, x12 = y12, x13 = y13, x14 = y14, x15 = y15;
for (let i = 0; i < rounds; i += 2) {
x00 = x00 + x04 | 0;
x12 = rotl2(x12 ^ x00, 16);
x08 = x08 + x12 | 0;
x04 = rotl2(x04 ^ x08, 12);
x00 = x00 + x04 | 0;
x12 = rotl2(x12 ^ x00, 8);
x08 = x08 + x12 | 0;
x04 = rotl2(x04 ^ x08, 7);
x01 = x01 + x05 | 0;
x13 = rotl2(x13 ^ x01, 16);
x09 = x09 + x13 | 0;
x05 = rotl2(x05 ^ x09, 12);
x01 = x01 + x05 | 0;
x13 = rotl2(x13 ^ x01, 8);
x09 = x09 + x13 | 0;
x05 = rotl2(x05 ^ x09, 7);
x02 = x02 + x06 | 0;
x14 = rotl2(x14 ^ x02, 16);
x10 = x10 + x14 | 0;
x06 = rotl2(x06 ^ x10, 12);
x02 = x02 + x06 | 0;
x14 = rotl2(x14 ^ x02, 8);
x10 = x10 + x14 | 0;
x06 = rotl2(x06 ^ x10, 7);
x03 = x03 + x07 | 0;
x15 = rotl2(x15 ^ x03, 16);
x11 = x11 + x15 | 0;
x07 = rotl2(x07 ^ x11, 12);
x03 = x03 + x07 | 0;
x15 = rotl2(x15 ^ x03, 8);
x11 = x11 + x15 | 0;
x07 = rotl2(x07 ^ x11, 7);
x00 = x00 + x05 | 0;
x15 = rotl2(x15 ^ x00, 16);
x10 = x10 + x15 | 0;
x05 = rotl2(x05 ^ x10, 12);
x00 = x00 + x05 | 0;
x15 = rotl2(x15 ^ x00, 8);
x10 = x10 + x15 | 0;
x05 = rotl2(x05 ^ x10, 7);
x01 = x01 + x06 | 0;
x12 = rotl2(x12 ^ x01, 16);
x11 = x11 + x12 | 0;
x06 = rotl2(x06 ^ x11, 12);
x01 = x01 + x06 | 0;
x12 = rotl2(x12 ^ x01, 8);
x11 = x11 + x12 | 0;
x06 = rotl2(x06 ^ x11, 7);
x02 = x02 + x07 | 0;
x13 = rotl2(x13 ^ x02, 16);
x08 = x08 + x13 | 0;
x07 = rotl2(x07 ^ x08, 12);
x02 = x02 + x07 | 0;
x13 = rotl2(x13 ^ x02, 8);
x08 = x08 + x13 | 0;
x07 = rotl2(x07 ^ x08, 7);
x03 = x03 + x04 | 0;
x14 = rotl2(x14 ^ x03, 16);
x09 = x09 + x14 | 0;
x04 = rotl2(x04 ^ x09, 12);
x03 = x03 + x04 | 0;
x14 = rotl2(x14 ^ x03, 8);
x09 = x09 + x14 | 0;
x04 = rotl2(x04 ^ x09, 7);
}
let oi = 0;
out[oi++] = y00 + x00 | 0;
out[oi++] = y01 + x01 | 0;
out[oi++] = y02 + x02 | 0;
out[oi++] = y03 + x03 | 0;
out[oi++] = y04 + x04 | 0;
out[oi++] = y05 + x05 | 0;
out[oi++] = y06 + x06 | 0;
out[oi++] = y07 + x07 | 0;
out[oi++] = y08 + x08 | 0;
out[oi++] = y09 + x09 | 0;
out[oi++] = y10 + x10 | 0;
out[oi++] = y11 + x11 | 0;
out[oi++] = y12 + x12 | 0;
out[oi++] = y13 + x13 | 0;
out[oi++] = y14 + x14 | 0;
out[oi++] = y15 + x15 | 0;
}
var chacha20 = /* @__PURE__ */ salsaBasic({
core: chachaCore,
counterRight: false,
counterLen: 4,
allow128bitKeys: false
});
// node_modules/nostr-tools/node_modules/@noble/hashes/esm/hmac.js
var HMAC4 = class extends Hash2 {
constructor(hash6, _key) {
super();
this.finished = false;
this.destroyed = false;
assert_default2.hash(hash6);
const key = toBytes2(_key);
this.iHash = hash6.create();
if (typeof this.iHash.update !== "function")
throw new Error("Expected instance of class which extends utils.Hash");
this.blockLen = this.iHash.blockLen;
this.outputLen = this.iHash.outputLen;
const blockLen = this.blockLen;
const pad = new Uint8Array(blockLen);
pad.set(key.length > blockLen ? hash6.create().update(key).digest() : key);
for (let i = 0; i < pad.length; i++)
pad[i] ^= 54;
this.iHash.update(pad);
this.oHash = hash6.create();
for (let i = 0; i < pad.length; i++)
pad[i] ^= 54 ^ 92;
this.oHash.update(pad);
pad.fill(0);
}
update(buf) {
assert_default2.exists(this);
this.iHash.update(buf);
return this;
}
digestInto(out) {
assert_default2.exists(this);
assert_default2.bytes(out, this.outputLen);
this.finished = true;
this.iHash.digestInto(out);
this.oHash.update(out);
this.oHash.digestInto(out);
this.destroy();
}
digest() {
const out = new Uint8Array(this.oHash.outputLen);
this.digestInto(out);
return out;
}
_cloneInto(to) {
to || (to = Object.create(Object.getPrototypeOf(this), {}));
const { oHash, iHash, finished, destroyed, blockLen, outputLen } = this;
to = to;
to.finished = finished;
to.destroyed = destroyed;
to.blockLen = blockLen;
to.outputLen = outputLen;
to.oHash = oHash._cloneInto(to.oHash);
to.iHash = iHash._cloneInto(to.iHash);
return to;
}
destroy() {
this.destroyed = true;
this.oHash.destroy();
this.iHash.destroy();
}
};
var hmac4 = (hash6, key, message) => new HMAC4(hash6, key).update(message).digest();
hmac4.create = (hash6, key) => new HMAC4(hash6, key);
// node_modules/nostr-tools/node_modules/@noble/hashes/esm/hkdf.js
function extract(hash6, ikm, salt2) {
assert_default2.hash(hash6);
if (salt2 === void 0)
salt2 = new Uint8Array(hash6.outputLen);
return hmac4(hash6, toBytes2(salt2), toBytes2(ikm));
}
var HKDF_COUNTER = new Uint8Array([0]);
var EMPTY_BUFFER = new Uint8Array();
function expand(hash6, prk, info, length = 32) {
assert_default2.hash(hash6);
assert_default2.number(length);
if (length > 255 * hash6.outputLen)
throw new Error("Length should be <= 255*HashLen");
const blocks = Math.ceil(length / hash6.outputLen);
if (info === void 0)
info = EMPTY_BUFFER;
const okm = new Uint8Array(blocks * hash6.outputLen);
const HMAC5 = hmac4.create(hash6, prk);
const HMACTmp = HMAC5._cloneInto();
const T = new Uint8Array(HMAC5.outputLen);
for (let counter = 0; counter < blocks; counter++) {
HKDF_COUNTER[0] = counter + 1;
HMACTmp.update(counter === 0 ? EMPTY_BUFFER : T).update(info).update(HKDF_COUNTER).digestInto(T);
okm.set(T, hash6.outputLen * counter);
HMAC5._cloneInto(HMACTmp);
}
HMAC5.destroy();
HMACTmp.destroy();
T.fill(0);
HKDF_COUNTER.fill(0);
return okm.slice(0, length);
}
var hkdf = (hash6, ikm, salt2, info, length) => expand(hash6, extract(hash6, ikm, salt2), info, length);
// node_modules/nostr-tools/lib/esm/index.js
var __defProp2 = Object.defineProperty;
var __export2 = (target, all) => {
for (var name in all)
__defProp2(target, name, { get: all[name], enumerable: true });
};
function getPublicKey(privateKey) {
return bytesToHex2(schnorr.getPublicKey(privateKey));
}
var utils_exports2 = {};
__export2(utils_exports2, {
MessageNode: () => MessageNode,
MessageQueue: () => MessageQueue,
insertEventIntoAscendingList: () => insertEventIntoAscendingList,
insertEventIntoDescendingList: () => insertEventIntoDescendingList,
normalizeURL: () => normalizeURL,
utf8Decoder: () => utf8Decoder,
utf8Encoder: () => utf8Encoder
});
var utf8Decoder = new TextDecoder("utf-8");
var utf8Encoder = new TextEncoder();
function normalizeURL(url) {
let p = new URL(url);
p.pathname = p.pathname.replace(/\/+/g, "/");
if (p.pathname.endsWith("/"))
p.pathname = p.pathname.slice(0, -1);
if (p.port === "80" && p.protocol === "ws:" || p.port === "443" && p.protocol === "wss:")
p.port = "";
p.searchParams.sort();
p.hash = "";
return p.toString();
}
function insertEventIntoDescendingList(sortedArray, event) {
var _a;
let start = 0;
let end = sortedArray.length - 1;
let midPoint;
let position = start;
if (end < 0) {
position = 0;
} else if (event.created_at < sortedArray[end].created_at) {
position = end + 1;
} else if (event.created_at >= sortedArray[start].created_at) {
position = start;
} else
while (true) {
if (end <= start + 1) {
position = end;
break;
}
midPoint = Math.floor(start + (end - start) / 2);
if (sortedArray[midPoint].created_at > event.created_at) {
start = midPoint;
} else if (sortedArray[midPoint].created_at < event.created_at) {
end = midPoint;
} else {
position = midPoint;
break;
}
}
if (((_a = sortedArray[position]) == null ? void 0 : _a.id) !== event.id) {
return [...sortedArray.slice(0, position), event, ...sortedArray.slice(position)];
}
return sortedArray;
}
function insertEventIntoAscendingList(sortedArray, event) {
var _a;
let start = 0;
let end = sortedArray.length - 1;
let midPoint;
let position = start;
if (end < 0) {
position = 0;
} else if (event.created_at > sortedArray[end].created_at) {
position = end + 1;
} else if (event.created_at <= sortedArray[start].created_at) {
position = start;
} else
while (true) {
if (end <= start + 1) {
position = end;
break;
}
midPoint = Math.floor(start + (end - start) / 2);
if (sortedArray[midPoint].created_at < event.created_at) {
start = midPoint;
} else if (sortedArray[midPoint].created_at > event.created_at) {
end = midPoint;
} else {
position = midPoint;
break;
}
}
if (((_a = sortedArray[position]) == null ? void 0 : _a.id) !== event.id) {
return [...sortedArray.slice(0, position), event, ...sortedArray.slice(position)];
}
return sortedArray;
}
var MessageNode = class {
constructor(message) {
__publicField(this, "_value");
__publicField(this, "_next");
this._value = message;
this._next = null;
}
get value() {
return this._value;
}
set value(message) {
this._value = message;
}
get next() {
return this._next;
}
set next(node) {
this._next = node;
}
};
var MessageQueue = class {
constructor() {
__publicField(this, "_first");
__publicField(this, "_last");
__publicField(this, "_size");
this._first = null;
this._last = null;
this._size = 0;
}
get first() {
return this._first;
}
set first(messageNode) {
this._first = messageNode;
}
get last() {
return this._last;
}
set last(messageNode) {
this._last = messageNode;
}
get size() {
return this._size;
}
set size(v) {
this._size = v;
}
enqueue(message) {
const newNode = new MessageNode(message);
if (this._size === 0 || !this._last) {
this._first = newNode;
this._last = newNode;
} else {
this._last.next = newNode;
this._last = newNode;
}
this._size++;
return true;
}
dequeue() {
if (this._size === 0 || !this._first)
return null;
let prev = this._first;
this._first = prev.next;
prev.next = null;
this._size--;
return prev.value;
}
};
var verifiedSymbol = Symbol("verified");
var Kind = /* @__PURE__ */ ((Kind3) => {
Kind3[Kind3["Metadata"] = 0] = "Metadata";
Kind3[Kind3["Text"] = 1] = "Text";
Kind3[Kind3["RecommendRelay"] = 2] = "RecommendRelay";
Kind3[Kind3["Contacts"] = 3] = "Contacts";
Kind3[Kind3["EncryptedDirectMessage"] = 4] = "EncryptedDirectMessage";
Kind3[Kind3["EventDeletion"] = 5] = "EventDeletion";
Kind3[Kind3["Repost"] = 6] = "Repost";
Kind3[Kind3["Reaction"] = 7] = "Reaction";
Kind3[Kind3["BadgeAward"] = 8] = "BadgeAward";
Kind3[Kind3["ChannelCreation"] = 40] = "ChannelCreation";
Kind3[Kind3["ChannelMetadata"] = 41] = "ChannelMetadata";
Kind3[Kind3["ChannelMessage"] = 42] = "ChannelMessage";
Kind3[Kind3["ChannelHideMessage"] = 43] = "ChannelHideMessage";
Kind3[Kind3["ChannelMuteUser"] = 44] = "ChannelMuteUser";
Kind3[Kind3["Blank"] = 255] = "Blank";
Kind3[Kind3["Report"] = 1984] = "Report";
Kind3[Kind3["ZapRequest"] = 9734] = "ZapRequest";
Kind3[Kind3["Zap"] = 9735] = "Zap";
Kind3[Kind3["RelayList"] = 10002] = "RelayList";
Kind3[Kind3["ClientAuth"] = 22242] = "ClientAuth";
Kind3[Kind3["NwcRequest"] = 23194] = "NwcRequest";
Kind3[Kind3["HttpAuth"] = 27235] = "HttpAuth";
Kind3[Kind3["ProfileBadge"] = 30008] = "ProfileBadge";
Kind3[Kind3["BadgeDefinition"] = 30009] = "BadgeDefinition";
Kind3[Kind3["Article"] = 30023] = "Article";
Kind3[Kind3["FileMetadata"] = 1063] = "FileMetadata";
return Kind3;
})(Kind || {});
function getBlankEvent(kind = 255) {
return {
kind,
content: "",
tags: [],
created_at: 0
};
}
function finishEvent(t, privateKey) {
const event = t;
event.pubkey = getPublicKey(privateKey);
event.id = getEventHash(event);
event.sig = getSignature(event, privateKey);
event[verifiedSymbol] = true;
return event;
}
function serializeEvent(evt) {
if (!validateEvent(evt))
throw new Error("can't serialize event with wrong or missing properties");
return JSON.stringify([0, evt.pubkey, evt.created_at, evt.kind, evt.tags, evt.content]);
}
function getEventHash(event) {
let eventHash = sha2562(utf8Encoder.encode(serializeEvent(event)));
return bytesToHex2(eventHash);
}
var isRecord = (obj) => obj instanceof Object;
function validateEvent(event) {
if (!isRecord(event))
return false;
if (typeof event.kind !== "number")
return false;
if (typeof event.content !== "string")
return false;
if (typeof event.created_at !== "number")
return false;
if (typeof event.pubkey !== "string")
return false;
if (!event.pubkey.match(/^[a-f0-9]{64}$/))
return false;
if (!Array.isArray(event.tags))
return false;
for (let i = 0; i < event.tags.length; i++) {
let tag = event.tags[i];
if (!Array.isArray(tag))
return false;
for (let j = 0; j < tag.length; j++) {
if (typeof tag[j] === "object")
return false;
}
}
return true;
}
function verifySignature(event) {
if (typeof event[verifiedSymbol] === "boolean")
return event[verifiedSymbol];
const hash6 = getEventHash(event);
if (hash6 !== event.id) {
return event[verifiedSymbol] = false;
}
try {
return event[verifiedSymbol] = schnorr.verify(event.sig, hash6, event.pubkey);
} catch (err) {
return event[verifiedSymbol] = false;
}
}
function getSignature(event, key) {
return bytesToHex2(schnorr.sign(getEventHash(event), key));
}
function matchFilter(filter, event) {
if (filter.ids && filter.ids.indexOf(event.id) === -1) {
if (!filter.ids.some((prefix) => event.id.startsWith(prefix))) {
return false;
}
}
if (filter.kinds && filter.kinds.indexOf(event.kind) === -1)
return false;
if (filter.authors && filter.authors.indexOf(event.pubkey) === -1) {
if (!filter.authors.some((prefix) => event.pubkey.startsWith(prefix))) {
return false;
}
}
for (let f2 in filter) {
if (f2[0] === "#") {
let tagName = f2.slice(1);
let values = filter[`#${tagName}`];
if (values && !event.tags.find(([t, v]) => t === f2.slice(1) && values.indexOf(v) !== -1))
return false;
}
}
if (filter.since && event.created_at < filter.since)
return false;
if (filter.until && event.created_at > filter.until)
return false;
return true;
}
function matchFilters(filters, event) {
for (let i = 0; i < filters.length; i++) {
if (matchFilter(filters[i], event))
return true;
}
return false;
}
var fakejson_exports = {};
__export2(fakejson_exports, {
getHex64: () => getHex64,
getInt: () => getInt,
getSubscriptionId: () => getSubscriptionId,
matchEventId: () => matchEventId,
matchEventKind: () => matchEventKind,
matchEventPubkey: () => matchEventPubkey
});
function getHex64(json, field) {
let len = field.length + 3;
let idx = json.indexOf(`"${field}":`) + len;
let s = json.slice(idx).indexOf(`"`) + idx + 1;
return json.slice(s, s + 64);
}
function getInt(json, field) {
let len = field.length;
let idx = json.indexOf(`"${field}":`) + len + 3;
let sliced = json.slice(idx);
let end = Math.min(sliced.indexOf(","), sliced.indexOf("}"));
return parseInt(sliced.slice(0, end), 10);
}
function getSubscriptionId(json) {
let idx = json.slice(0, 22).indexOf(`"EVENT"`);
if (idx === -1)
return null;
let pstart = json.slice(idx + 7 + 1).indexOf(`"`);
if (pstart === -1)
return null;
let start = idx + 7 + 1 + pstart;
let pend = json.slice(start + 1, 80).indexOf(`"`);
if (pend === -1)
return null;
let end = start + 1 + pend;
return json.slice(start + 1, end);
}
function matchEventId(json, id) {
return id === getHex64(json, "id");
}
function matchEventPubkey(json, pubkey) {
return pubkey === getHex64(json, "pubkey");
}
function matchEventKind(json, kind) {
return kind === getInt(json, "kind");
}
var nip19_exports = {};
__export2(nip19_exports, {
BECH32_REGEX: () => BECH32_REGEX,
decode: () => decode,
naddrEncode: () => naddrEncode,
neventEncode: () => neventEncode,
noteEncode: () => noteEncode,
nprofileEncode: () => nprofileEncode,
npubEncode: () => npubEncode,
nrelayEncode: () => nrelayEncode,
nsecEncode: () => nsecEncode
});
var Bech32MaxSize = 5e3;
var BECH32_REGEX = /[\x21-\x7E]{1,83}1[023456789acdefghjklmnpqrstuvwxyz]{6,}/;
function integerToUint8Array(number6) {
const uint8Array = new Uint8Array(4);
uint8Array[0] = number6 >> 24 & 255;
uint8Array[1] = number6 >> 16 & 255;
uint8Array[2] = number6 >> 8 & 255;
uint8Array[3] = number6 & 255;
return uint8Array;
}
function decode(nip19) {
var _a, _b, _c, _d, _e, _f, _g, _h;
let { prefix, words } = bech32.decode(nip19, Bech32MaxSize);
let data = new Uint8Array(bech32.fromWords(words));
switch (prefix) {
case "nprofile": {
let tlv = parseTLV(data);
if (!((_a = tlv[0]) == null ? void 0 : _a[0]))
throw new Error("missing TLV 0 for nprofile");
if (tlv[0][0].length !== 32)
throw new Error("TLV 0 should be 32 bytes");
return {
type: "nprofile",
data: {
pubkey: bytesToHex2(tlv[0][0]),
relays: tlv[1] ? tlv[1].map((d) => utf8Decoder.decode(d)) : []
}
};
}
case "nevent": {
let tlv = parseTLV(data);
if (!((_b = tlv[0]) == null ? void 0 : _b[0]))
throw new Error("missing TLV 0 for nevent");
if (tlv[0][0].length !== 32)
throw new Error("TLV 0 should be 32 bytes");
if (tlv[2] && tlv[2][0].length !== 32)
throw new Error("TLV 2 should be 32 bytes");
if (tlv[3] && tlv[3][0].length !== 4)
throw new Error("TLV 3 should be 4 bytes");
return {
type: "nevent",
data: {
id: bytesToHex2(tlv[0][0]),
relays: tlv[1] ? tlv[1].map((d) => utf8Decoder.decode(d)) : [],
author: ((_c = tlv[2]) == null ? void 0 : _c[0]) ? bytesToHex2(tlv[2][0]) : void 0,
kind: ((_d = tlv[3]) == null ? void 0 : _d[0]) ? parseInt(bytesToHex2(tlv[3][0]), 16) : void 0
}
};
}
case "naddr": {
let tlv = parseTLV(data);
if (!((_e = tlv[0]) == null ? void 0 : _e[0]))
throw new Error("missing TLV 0 for naddr");
if (!((_f = tlv[2]) == null ? void 0 : _f[0]))
throw new Error("missing TLV 2 for naddr");
if (tlv[2][0].length !== 32)
throw new Error("TLV 2 should be 32 bytes");
if (!((_g = tlv[3]) == null ? void 0 : _g[0]))
throw new Error("missing TLV 3 for naddr");
if (tlv[3][0].length !== 4)
throw new Error("TLV 3 should be 4 bytes");
return {
type: "naddr",
data: {
identifier: utf8Decoder.decode(tlv[0][0]),
pubkey: bytesToHex2(tlv[2][0]),
kind: parseInt(bytesToHex2(tlv[3][0]), 16),
relays: tlv[1] ? tlv[1].map((d) => utf8Decoder.decode(d)) : []
}
};
}
case "nrelay": {
let tlv = parseTLV(data);
if (!((_h = tlv[0]) == null ? void 0 : _h[0]))
throw new Error("missing TLV 0 for nrelay");
return {
type: "nrelay",
data: utf8Decoder.decode(tlv[0][0])
};
}
case "nsec":
case "npub":
case "note":
return { type: prefix, data: bytesToHex2(data) };
default:
throw new Error(`unknown prefix ${prefix}`);
}
}
function parseTLV(data) {
let result = {};
let rest = data;
while (rest.length > 0) {
let t = rest[0];
let l = rest[1];
if (!l)
throw new Error(`malformed TLV ${t}`);
let v = rest.slice(2, 2 + l);
rest = rest.slice(2 + l);
if (v.length < l)
throw new Error(`not enough data to read on TLV ${t}`);
result[t] = result[t] || [];
result[t].push(v);
}
return result;
}
function nsecEncode(hex2) {
return encodeBytes("nsec", hex2);
}
function npubEncode(hex2) {
return encodeBytes("npub", hex2);
}
function noteEncode(hex2) {
return encodeBytes("note", hex2);
}
function encodeBech32(prefix, data) {
let words = bech32.toWords(data);
return bech32.encode(prefix, words, Bech32MaxSize);
}
function encodeBytes(prefix, hex2) {
let data = hexToBytes2(hex2);
return encodeBech32(prefix, data);
}
function nprofileEncode(profile) {
let data = encodeTLV({
0: [hexToBytes2(profile.pubkey)],
1: (profile.relays || []).map((url) => utf8Encoder.encode(url))
});
return encodeBech32("nprofile", data);
}
function neventEncode(event) {
let kindArray;
if (event.kind != void 0) {
kindArray = integerToUint8Array(event.kind);
}
let data = encodeTLV({
0: [hexToBytes2(event.id)],
1: (event.relays || []).map((url) => utf8Encoder.encode(url)),
2: event.author ? [hexToBytes2(event.author)] : [],
3: kindArray ? [new Uint8Array(kindArray)] : []
});
return encodeBech32("nevent", data);
}
function naddrEncode(addr) {
let kind = new ArrayBuffer(4);
new DataView(kind).setUint32(0, addr.kind, false);
let data = encodeTLV({
0: [utf8Encoder.encode(addr.identifier)],
1: (addr.relays || []).map((url) => utf8Encoder.encode(url)),
2: [hexToBytes2(addr.pubkey)],
3: [new Uint8Array(kind)]
});
return encodeBech32("naddr", data);
}
function nrelayEncode(url) {
let data = encodeTLV({
0: [utf8Encoder.encode(url)]
});
return encodeBech32("nrelay", data);
}
function encodeTLV(tlv) {
let entries = [];
Object.entries(tlv).forEach(([t, vs]) => {
vs.forEach((v) => {
let entry = new Uint8Array(v.length + 2);
entry.set([parseInt(t)], 0);
entry.set([v.length], 1);
entry.set(v, 2);
entries.push(entry);
});
});
return concatBytes3(...entries);
}
var nip04_exports = {};
__export2(nip04_exports, {
decrypt: () => decrypt,
encrypt: () => encrypt
});
if (typeof crypto !== "undefined" && !crypto.subtle && crypto.webcrypto) {
crypto.subtle = crypto.webcrypto.subtle;
}
async function encrypt(privkey, pubkey, text) {
const key = secp256k1.getSharedSecret(privkey, "02" + pubkey);
const normalizedKey = getNormalizedX(key);
let iv = Uint8Array.from(randomBytes2(16));
let plaintext = utf8Encoder.encode(text);
let cryptoKey = await crypto.subtle.importKey("raw", normalizedKey, { name: "AES-CBC" }, false, ["encrypt"]);
let ciphertext = await crypto.subtle.encrypt({ name: "AES-CBC", iv }, cryptoKey, plaintext);
let ctb64 = base64.encode(new Uint8Array(ciphertext));
let ivb64 = base64.encode(new Uint8Array(iv.buffer));
return `${ctb64}?iv=${ivb64}`;
}
async function decrypt(privkey, pubkey, data) {
let [ctb64, ivb64] = data.split("?iv=");
let key = secp256k1.getSharedSecret(privkey, "02" + pubkey);
let normalizedKey = getNormalizedX(key);
let cryptoKey = await crypto.subtle.importKey("raw", normalizedKey, { name: "AES-CBC" }, false, ["decrypt"]);
let ciphertext = base64.decode(ctb64);
let iv = base64.decode(ivb64);
let plaintext = await crypto.subtle.decrypt({ name: "AES-CBC", iv }, cryptoKey, ciphertext);
let text = utf8Decoder.decode(plaintext);
return text;
}
function getNormalizedX(key) {
return key.slice(1, 33);
}
var nip05_exports = {};
__export2(nip05_exports, {
NIP05_REGEX: () => NIP05_REGEX,
queryProfile: () => queryProfile,
searchDomain: () => searchDomain,
useFetchImplementation: () => useFetchImplementation
});
var NIP05_REGEX = /^(?:([\w.+-]+)@)?([\w.-]+)$/;
var _fetch;
try {
_fetch = fetch;
} catch (e) {
}
function useFetchImplementation(fetchImplementation) {
_fetch = fetchImplementation;
}
async function searchDomain(domain, query = "") {
try {
let res = await (await _fetch(`https://${domain}/.well-known/nostr.json?name=${query}`)).json();
return res.names;
} catch (_) {
return {};
}
}
async function queryProfile(fullname) {
const match = fullname.match(NIP05_REGEX);
if (!match)
return null;
const [_, name = "_", domain] = match;
try {
const res = await _fetch(`https://${domain}/.well-known/nostr.json?name=${name}`);
const { names, relays } = parseNIP05Result(await res.json());
const pubkey = names[name];
return pubkey ? { pubkey, relays: relays == null ? void 0 : relays[pubkey] } : null;
} catch (_e) {
return null;
}
}
function parseNIP05Result(json) {
const result = {
names: {}
};
for (const [name, pubkey] of Object.entries(json.names)) {
if (typeof name === "string" && typeof pubkey === "string") {
result.names[name] = pubkey;
}
}
if (json.relays) {
result.relays = {};
for (const [pubkey, relays] of Object.entries(json.relays)) {
if (typeof pubkey === "string" && Array.isArray(relays)) {
result.relays[pubkey] = relays.filter((relay) => typeof relay === "string");
}
}
}
return result;
}
var nip06_exports = {};
__export2(nip06_exports, {
generateSeedWords: () => generateSeedWords,
privateKeyFromSeedWords: () => privateKeyFromSeedWords,
validateWords: () => validateWords
});
function privateKeyFromSeedWords(mnemonic, passphrase) {
let root = HDKey.fromMasterSeed(mnemonicToSeedSync(mnemonic, passphrase));
let privateKey = root.derive(`m/44'/1237'/0'/0/0`).privateKey;
if (!privateKey)
throw new Error("could not derive private key");
return bytesToHex2(privateKey);
}
function generateSeedWords() {
return generateMnemonic(wordlist);
}
function validateWords(words) {
return validateMnemonic(words, wordlist);
}
var nip10_exports = {};
__export2(nip10_exports, {
parse: () => parse
});
function parse(event) {
const result = {
reply: void 0,
root: void 0,
mentions: [],
profiles: []
};
const eTags = [];
for (const tag of event.tags) {
if (tag[0] === "e" && tag[1]) {
eTags.push(tag);
}
if (tag[0] === "p" && tag[1]) {
result.profiles.push({
pubkey: tag[1],
relays: tag[2] ? [tag[2]] : []
});
}
}
for (let eTagIndex = 0; eTagIndex < eTags.length; eTagIndex++) {
const eTag = eTags[eTagIndex];
const [_, eTagEventId, eTagRelayUrl, eTagMarker] = eTag;
const eventPointer = {
id: eTagEventId,
relays: eTagRelayUrl ? [eTagRelayUrl] : []
};
const isFirstETag = eTagIndex === 0;
const isLastETag = eTagIndex === eTags.length - 1;
if (eTagMarker === "root") {
result.root = eventPointer;
continue;
}
if (eTagMarker === "reply") {
result.reply = eventPointer;
continue;
}
if (eTagMarker === "mention") {
result.mentions.push(eventPointer);
continue;
}
if (isFirstETag) {
result.root = eventPointer;
continue;
}
if (isLastETag) {
result.reply = eventPointer;
continue;
}
result.mentions.push(eventPointer);
}
return result;
}
var nip13_exports = {};
__export2(nip13_exports, {
getPow: () => getPow,
minePow: () => minePow
});
function getPow(hex2) {
let count = 0;
for (let i = 0; i < hex2.length; i++) {
const nibble = parseInt(hex2[i], 16);
if (nibble === 0) {
count += 4;
} else {
count += Math.clz32(nibble) - 28;
break;
}
}
return count;
}
function minePow(unsigned, difficulty) {
let count = 0;
const event = unsigned;
const tag = ["nonce", count.toString(), difficulty.toString()];
event.tags.push(tag);
while (true) {
const now = Math.floor((/* @__PURE__ */ new Date()).getTime() / 1e3);
if (now !== event.created_at) {
count = 0;
event.created_at = now;
}
tag[1] = (++count).toString();
event.id = getEventHash(event);
if (getPow(event.id) >= difficulty) {
break;
}
}
return event;
}
var nip18_exports = {};
__export2(nip18_exports, {
finishRepostEvent: () => finishRepostEvent,
getRepostedEvent: () => getRepostedEvent,
getRepostedEventPointer: () => getRepostedEventPointer
});
function finishRepostEvent(t, reposted, relayUrl, privateKey) {
var _a;
return finishEvent(
{
kind: 6,
tags: [...(_a = t.tags) != null ? _a : [], ["e", reposted.id, relayUrl], ["p", reposted.pubkey]],
content: t.content === "" ? "" : JSON.stringify(reposted),
created_at: t.created_at
},
privateKey
);
}
function getRepostedEventPointer(event) {
if (event.kind !== 6) {
return void 0;
}
let lastETag;
let lastPTag;
for (let i = event.tags.length - 1; i >= 0 && (lastETag === void 0 || lastPTag === void 0); i--) {
const tag = event.tags[i];
if (tag.length >= 2) {
if (tag[0] === "e" && lastETag === void 0) {
lastETag = tag;
} else if (tag[0] === "p" && lastPTag === void 0) {
lastPTag = tag;
}
}
}
if (lastETag === void 0) {
return void 0;
}
return {
id: lastETag[1],
relays: [lastETag[2], lastPTag == null ? void 0 : lastPTag[2]].filter((x) => typeof x === "string"),
author: lastPTag == null ? void 0 : lastPTag[1]
};
}
function getRepostedEvent(event, { skipVerification } = {}) {
const pointer = getRepostedEventPointer(event);
if (pointer === void 0 || event.content === "") {
return void 0;
}
let repostedEvent;
try {
repostedEvent = JSON.parse(event.content);
} catch (error) {
return void 0;
}
if (repostedEvent.id !== pointer.id) {
return void 0;
}
if (!skipVerification && !verifySignature(repostedEvent)) {
return void 0;
}
return repostedEvent;
}
var nip21_exports = {};
__export2(nip21_exports, {
NOSTR_URI_REGEX: () => NOSTR_URI_REGEX,
parse: () => parse2,
test: () => test
});
var NOSTR_URI_REGEX = new RegExp(`nostr:(${BECH32_REGEX.source})`);
function test(value) {
return typeof value === "string" && new RegExp(`^${NOSTR_URI_REGEX.source}$`).test(value);
}
function parse2(uri) {
const match = uri.match(new RegExp(`^${NOSTR_URI_REGEX.source}$`));
if (!match)
throw new Error(`Invalid Nostr URI: ${uri}`);
return {
uri: match[0],
value: match[1],
decoded: decode(match[1])
};
}
var nip25_exports = {};
__export2(nip25_exports, {
finishReactionEvent: () => finishReactionEvent,
getReactedEventPointer: () => getReactedEventPointer
});
function finishReactionEvent(t, reacted, privateKey) {
var _a, _b;
const inheritedTags = reacted.tags.filter((tag) => tag.length >= 2 && (tag[0] === "e" || tag[0] === "p"));
return finishEvent(
{
...t,
kind: 7,
tags: [...(_a = t.tags) != null ? _a : [], ...inheritedTags, ["e", reacted.id], ["p", reacted.pubkey]],
content: (_b = t.content) != null ? _b : "+"
},
privateKey
);
}
function getReactedEventPointer(event) {
if (event.kind !== 7) {
return void 0;
}
let lastETag;
let lastPTag;
for (let i = event.tags.length - 1; i >= 0 && (lastETag === void 0 || lastPTag === void 0); i--) {
const tag = event.tags[i];
if (tag.length >= 2) {
if (tag[0] === "e" && lastETag === void 0) {
lastETag = tag;
} else if (tag[0] === "p" && lastPTag === void 0) {
lastPTag = tag;
}
}
}
if (lastETag === void 0 || lastPTag === void 0) {
return void 0;
}
return {
id: lastETag[1],
relays: [lastETag[2], lastPTag[2]].filter((x) => x !== void 0),
author: lastPTag[1]
};
}
var nip26_exports = {};
__export2(nip26_exports, {
createDelegation: () => createDelegation,
getDelegator: () => getDelegator
});
function createDelegation(privateKey, parameters) {
let conditions = [];
if ((parameters.kind || -1) >= 0)
conditions.push(`kind=${parameters.kind}`);
if (parameters.until)
conditions.push(`created_at<${parameters.until}`);
if (parameters.since)
conditions.push(`created_at>${parameters.since}`);
let cond = conditions.join("&");
if (cond === "")
throw new Error("refusing to create a delegation without any conditions");
let sighash = sha2562(utf8Encoder.encode(`nostr:delegation:${parameters.pubkey}:${cond}`));
let sig = bytesToHex2(schnorr.sign(sighash, privateKey));
return {
from: getPublicKey(privateKey),
to: parameters.pubkey,
cond,
sig
};
}
function getDelegator(event) {
let tag = event.tags.find((tag2) => tag2[0] === "delegation" && tag2.length >= 4);
if (!tag)
return null;
let pubkey = tag[1];
let cond = tag[2];
let sig = tag[3];
let conditions = cond.split("&");
for (let i = 0; i < conditions.length; i++) {
let [key, operator, value] = conditions[i].split(/\b/);
if (key === "kind" && operator === "=" && event.kind === parseInt(value))
continue;
else if (key === "created_at" && operator === "<" && event.created_at < parseInt(value))
continue;
else if (key === "created_at" && operator === ">" && event.created_at > parseInt(value))
continue;
else
return null;
}
let sighash = sha2562(utf8Encoder.encode(`nostr:delegation:${event.pubkey}:${cond}`));
if (!schnorr.verify(sig, sighash, pubkey))
return null;
return pubkey;
}
var nip27_exports = {};
__export2(nip27_exports, {
matchAll: () => matchAll,
regex: () => regex,
replaceAll: () => replaceAll
});
var regex = () => new RegExp(`\\b${NOSTR_URI_REGEX.source}\\b`, "g");
function* matchAll(content) {
const matches = content.matchAll(regex());
for (const match of matches) {
try {
const [uri, value] = match;
yield {
uri,
value,
decoded: decode(value),
start: match.index,
end: match.index + uri.length
};
} catch (_e) {
}
}
}
function replaceAll(content, replacer) {
return content.replaceAll(regex(), (uri, value) => {
return replacer({
uri,
value,
decoded: decode(value)
});
});
}
var nip28_exports = {};
__export2(nip28_exports, {
channelCreateEvent: () => channelCreateEvent,
channelHideMessageEvent: () => channelHideMessageEvent,
channelMessageEvent: () => channelMessageEvent,
channelMetadataEvent: () => channelMetadataEvent,
channelMuteUserEvent: () => channelMuteUserEvent
});
var channelCreateEvent = (t, privateKey) => {
var _a;
let content;
if (typeof t.content === "object") {
content = JSON.stringify(t.content);
} else if (typeof t.content === "string") {
content = t.content;
} else {
return void 0;
}
return finishEvent(
{
kind: 40,
tags: [...(_a = t.tags) != null ? _a : []],
content,
created_at: t.created_at
},
privateKey
);
};
var channelMetadataEvent = (t, privateKey) => {
var _a;
let content;
if (typeof t.content === "object") {
content = JSON.stringify(t.content);
} else if (typeof t.content === "string") {
content = t.content;
} else {
return void 0;
}
return finishEvent(
{
kind: 41,
tags: [["e", t.channel_create_event_id], ...(_a = t.tags) != null ? _a : []],
content,
created_at: t.created_at
},
privateKey
);
};
var channelMessageEvent = (t, privateKey) => {
var _a;
const tags = [["e", t.channel_create_event_id, t.relay_url, "root"]];
if (t.reply_to_channel_message_event_id) {
tags.push(["e", t.reply_to_channel_message_event_id, t.relay_url, "reply"]);
}
return finishEvent(
{
kind: 42,
tags: [...tags, ...(_a = t.tags) != null ? _a : []],
content: t.content,
created_at: t.created_at
},
privateKey
);
};
var channelHideMessageEvent = (t, privateKey) => {
var _a;
let content;
if (typeof t.content === "object") {
content = JSON.stringify(t.content);
} else if (typeof t.content === "string") {
content = t.content;
} else {
return void 0;
}
return finishEvent(
{
kind: 43,
tags: [["e", t.channel_message_event_id], ...(_a = t.tags) != null ? _a : []],
content,
created_at: t.created_at
},
privateKey
);
};
var channelMuteUserEvent = (t, privateKey) => {
var _a;
let content;
if (typeof t.content === "object") {
content = JSON.stringify(t.content);
} else if (typeof t.content === "string") {
content = t.content;
} else {
return void 0;
}
return finishEvent(
{
kind: 44,
tags: [["p", t.pubkey_to_mute], ...(_a = t.tags) != null ? _a : []],
content,
created_at: t.created_at
},
privateKey
);
};
var nip39_exports = {};
__export2(nip39_exports, {
useFetchImplementation: () => useFetchImplementation2,
validateGithub: () => validateGithub
});
var _fetch2;
try {
_fetch2 = fetch;
} catch (e) {
}
function useFetchImplementation2(fetchImplementation) {
_fetch2 = fetchImplementation;
}
async function validateGithub(pubkey, username, proof) {
try {
let res = await (await _fetch2(`https://gist.github.com/${username}/${proof}/raw`)).text();
return res === `Verifying that I control the following Nostr public key: ${pubkey}`;
} catch (_) {
return false;
}
}
var nip42_exports = {};
__export2(nip42_exports, {
authenticate: () => authenticate
});
var authenticate = async ({
challenge: challenge2,
relay,
sign
}) => {
const e = {
kind: 22242,
created_at: Math.floor(Date.now() / 1e3),
tags: [
["relay", relay.url],
["challenge", challenge2]
],
content: ""
};
return relay.auth(await sign(e));
};
var nip44_exports = {};
__export2(nip44_exports, {
decrypt: () => decrypt2,
encrypt: () => encrypt2,
utils: () => utils2
});
var utils2 = {
v2: {
maxPlaintextSize: 65536 - 128,
minCiphertextSize: 100,
maxCiphertextSize: 102400,
getConversationKey(privkeyA, pubkeyB) {
const key = secp256k1.getSharedSecret(privkeyA, "02" + pubkeyB);
return key.subarray(1, 33);
},
getMessageKeys(conversationKey, salt2) {
const keys = hkdf(sha2562, conversationKey, salt2, "nip44-v2", 76);
return {
encryption: keys.subarray(0, 32),
nonce: keys.subarray(32, 44),
auth: keys.subarray(44, 76)
};
},
calcPadding(len) {
if (!Number.isSafeInteger(len) || len < 0)
throw new Error("expected positive integer");
if (len <= 32)
return 32;
const nextpower = 1 << Math.floor(Math.log2(len - 1)) + 1;
const chunk = nextpower <= 256 ? 32 : nextpower / 8;
return chunk * (Math.floor((len - 1) / chunk) + 1);
},
pad(unpadded) {
const unpaddedB = utf8Encoder.encode(unpadded);
const len = unpaddedB.length;
if (len < 1 || len >= utils2.v2.maxPlaintextSize)
throw new Error("invalid plaintext length: must be between 1b and 64KB");
const paddedLen = utils2.v2.calcPadding(len);
const zeros = new Uint8Array(paddedLen - len);
const lenBuf = new Uint8Array(2);
new DataView(lenBuf.buffer).setUint16(0, len);
return concatBytes3(lenBuf, unpaddedB, zeros);
},
unpad(padded) {
const unpaddedLen = new DataView(padded.buffer).getUint16(0);
const unpadded = padded.subarray(2, 2 + unpaddedLen);
if (unpaddedLen === 0 || unpadded.length !== unpaddedLen || padded.length !== 2 + utils2.v2.calcPadding(unpaddedLen))
throw new Error("invalid padding");
return utf8Decoder.decode(unpadded);
}
}
};
function encrypt2(key, plaintext, options = {}) {
var _a, _b;
const version = (_a = options.version) != null ? _a : 2;
if (version !== 2)
throw new Error("unknown encryption version " + version);
const salt2 = (_b = options.salt) != null ? _b : randomBytes2(32);
ensureBytes2(salt2, 32);
const keys = utils2.v2.getMessageKeys(key, salt2);
const padded = utils2.v2.pad(plaintext);
const ciphertext = chacha20(keys.encryption, keys.nonce, padded);
const mac = hmac4(sha2562, keys.auth, ciphertext);
return base64.encode(concatBytes3(new Uint8Array([version]), salt2, ciphertext, mac));
}
function decrypt2(key, ciphertext) {
const u = utils2.v2;
ensureBytes2(key, 32);
const clen = ciphertext.length;
if (clen < u.minCiphertextSize || clen >= u.maxCiphertextSize)
throw new Error("invalid ciphertext length: " + clen);
if (ciphertext[0] === "#")
throw new Error("unknown encryption version");
let data;
try {
data = base64.decode(ciphertext);
} catch (error) {
throw new Error("invalid base64: " + error.message);
}
const vers = data.subarray(0, 1)[0];
if (vers !== 2)
throw new Error("unknown encryption version " + vers);
const salt2 = data.subarray(1, 33);
const ciphertext_ = data.subarray(33, -32);
const mac = data.subarray(-32);
const keys = u.getMessageKeys(key, salt2);
const calculatedMac = hmac4(sha2562, keys.auth, ciphertext_);
if (!equalBytes2(calculatedMac, mac))
throw new Error("invalid MAC");
const padded = chacha20(keys.encryption, keys.nonce, ciphertext_);
return u.unpad(padded);
}
var nip47_exports = {};
__export2(nip47_exports, {
makeNwcRequestEvent: () => makeNwcRequestEvent,
parseConnectionString: () => parseConnectionString
});
function parseConnectionString(connectionString) {
const { pathname, searchParams } = new URL(connectionString);
const pubkey = pathname;
const relay = searchParams.get("relay");
const secret = searchParams.get("secret");
if (!pubkey || !relay || !secret) {
throw new Error("invalid connection string");
}
return { pubkey, relay, secret };
}
async function makeNwcRequestEvent({
pubkey,
secret,
invoice
}) {
const content = {
method: "pay_invoice",
params: {
invoice
}
};
const encryptedContent = await encrypt(secret, pubkey, JSON.stringify(content));
const eventTemplate = {
kind: 23194,
created_at: Math.round(Date.now() / 1e3),
content: encryptedContent,
tags: [["p", pubkey]]
};
return finishEvent(eventTemplate, secret);
}
var nip57_exports = {};
__export2(nip57_exports, {
getZapEndpoint: () => getZapEndpoint,
makeZapReceipt: () => makeZapReceipt,
makeZapRequest: () => makeZapRequest,
useFetchImplementation: () => useFetchImplementation3,
validateZapRequest: () => validateZapRequest
});
var _fetch3;
try {
_fetch3 = fetch;
} catch (e) {
}
function useFetchImplementation3(fetchImplementation) {
_fetch3 = fetchImplementation;
}
async function getZapEndpoint(metadata) {
try {
let lnurl = "";
let { lud06, lud16 } = JSON.parse(metadata.content);
if (lud06) {
let { words } = bech32.decode(lud06, 1e3);
let data = bech32.fromWords(words);
lnurl = utf8Decoder.decode(data);
} else if (lud16) {
let [name, domain] = lud16.split("@");
lnurl = `https://${domain}/.well-known/lnurlp/${name}`;
} else {
return null;
}
let res = await _fetch3(lnurl);
let body = await res.json();
if (body.allowsNostr && body.nostrPubkey) {
return body.callback;
}
} catch (err) {
}
return null;
}
function makeZapRequest({
profile,
event,
amount,
relays,
comment = ""
}) {
if (!amount)
throw new Error("amount not given");
if (!profile)
throw new Error("profile not given");
let zr = {
kind: 9734,
created_at: Math.round(Date.now() / 1e3),
content: comment,
tags: [
["p", profile],
["amount", amount.toString()],
["relays", ...relays]
]
};
if (event) {
zr.tags.push(["e", event]);
}
return zr;
}
function validateZapRequest(zapRequestString) {
let zapRequest;
try {
zapRequest = JSON.parse(zapRequestString);
} catch (err) {
return "Invalid zap request JSON.";
}
if (!validateEvent(zapRequest))
return "Zap request is not a valid Nostr event.";
if (!verifySignature(zapRequest))
return "Invalid signature on zap request.";
let p = zapRequest.tags.find(([t, v]) => t === "p" && v);
if (!p)
return "Zap request doesn't have a 'p' tag.";
if (!p[1].match(/^[a-f0-9]{64}$/))
return "Zap request 'p' tag is not valid hex.";
let e = zapRequest.tags.find(([t, v]) => t === "e" && v);
if (e && !e[1].match(/^[a-f0-9]{64}$/))
return "Zap request 'e' tag is not valid hex.";
let relays = zapRequest.tags.find(([t, v]) => t === "relays" && v);
if (!relays)
return "Zap request doesn't have a 'relays' tag.";
return null;
}
function makeZapReceipt({
zapRequest,
preimage,
bolt11,
paidAt
}) {
let zr = JSON.parse(zapRequest);
let tagsFromZapRequest = zr.tags.filter(([t]) => t === "e" || t === "p" || t === "a");
let zap = {
kind: 9735,
created_at: Math.round(paidAt.getTime() / 1e3),
content: "",
tags: [...tagsFromZapRequest, ["bolt11", bolt11], ["description", zapRequest]]
};
if (preimage) {
zap.tags.push(["preimage", preimage]);
}
return zap;
}
var nip98_exports = {};
__export2(nip98_exports, {
getToken: () => getToken,
unpackEventFromToken: () => unpackEventFromToken,
validateEvent: () => validateEvent2,
validateToken: () => validateToken
});
var _authorizationScheme = "Nostr ";
async function getToken(loginUrl, httpMethod, sign, includeAuthorizationScheme = false) {
if (!loginUrl || !httpMethod)
throw new Error("Missing loginUrl or httpMethod");
const event = getBlankEvent(
27235
/* HttpAuth */
);
event.tags = [
["u", loginUrl],
["method", httpMethod]
];
event.created_at = Math.round((/* @__PURE__ */ new Date()).getTime() / 1e3);
const signedEvent = await sign(event);
const authorizationScheme = includeAuthorizationScheme ? _authorizationScheme : "";
return authorizationScheme + base64.encode(utf8Encoder.encode(JSON.stringify(signedEvent)));
}
async function validateToken(token, url, method) {
const event = await unpackEventFromToken(token).catch((error) => {
throw error;
});
const valid = await validateEvent2(event, url, method).catch((error) => {
throw error;
});
return valid;
}
async function unpackEventFromToken(token) {
if (!token) {
throw new Error("Missing token");
}
token = token.replace(_authorizationScheme, "");
const eventB64 = utf8Decoder.decode(base64.decode(token));
if (!eventB64 || eventB64.length === 0 || !eventB64.startsWith("{")) {
throw new Error("Invalid token");
}
const event = JSON.parse(eventB64);
return event;
}
async function validateEvent2(event, url, method) {
if (!event) {
throw new Error("Invalid nostr event");
}
if (!verifySignature(event)) {
throw new Error("Invalid nostr event, signature invalid");
}
if (event.kind !== 27235) {
throw new Error("Invalid nostr event, kind invalid");
}
if (!event.created_at) {
throw new Error("Invalid nostr event, created_at invalid");
}
if (Math.round((/* @__PURE__ */ new Date()).getTime() / 1e3) - event.created_at > 60) {
throw new Error("Invalid nostr event, expired");
}
const urlTag = event.tags.find((t) => t[0] === "u");
if ((urlTag == null ? void 0 : urlTag.length) !== 1 && (urlTag == null ? void 0 : urlTag[1]) !== url) {
throw new Error("Invalid nostr event, url tag invalid");
}
const methodTag = event.tags.find((t) => t[0] === "method");
if ((methodTag == null ? void 0 : methodTag.length) !== 1 && (methodTag == null ? void 0 : methodTag[1].toLowerCase()) !== method.toLowerCase()) {
throw new Error("Invalid nostr event, method tag invalid");
}
return true;
}
// node_modules/isomorphic-ws/browser.js
var ws = null;
if (typeof WebSocket !== "undefined") {
ws = WebSocket;
} else if (typeof MozWebSocket !== "undefined") {
ws = MozWebSocket;
} else if (typeof global !== "undefined") {
ws = global.WebSocket || global.MozWebSocket;
} else if (typeof window !== "undefined") {
ws = window.WebSocket || window.MozWebSocket;
} else if (typeof self !== "undefined") {
ws = self.WebSocket || self.MozWebSocket;
}
var browser_default = ws;
// fakejson.ts
function getHex642(json, field) {
let len = field.length + 3;
let idx = json.indexOf(`"${field}":`) + len;
let s = json.slice(idx).indexOf(`"`) + idx + 1;
return json.slice(s, s + 64);
}
function getSubName(json) {
let idx = json.indexOf(`"EVENT"`) + 7;
let sliced = json.slice(idx);
let idx2 = sliced.indexOf(`"`) + 1;
let sliced2 = sliced.slice(idx2);
return sliced2.slice(0, sliced2.indexOf(`"`));
}
// relay.ts
function relayInit(url, alreadyHaveEvent, autoReconnect) {
return new RelayC(url, alreadyHaveEvent, autoReconnect).relayInit();
}
var _handleNext, handleNext_fn, _onclose, onclose_fn, _reconnect, reconnect_fn, _onmessage, onmessage_fn, _handleMessage, handleMessage_fn, _onopen, onopen_fn;
var RelayC = class {
constructor(url, alreadyHaveEvent, autoReconnect) {
__privateAdd(this, _handleNext);
__privateAdd(this, _onclose);
__privateAdd(this, _reconnect);
__privateAdd(this, _onmessage);
__privateAdd(this, _handleMessage);
__privateAdd(this, _onopen);
__publicField(this, "url");
__publicField(this, "alreadyHaveEvent");
__publicField(this, "logging", false);
__publicField(this, "autoReconnect");
__publicField(this, "ws");
__publicField(this, "sendOnConnect", []);
__publicField(this, "openSubs", {});
__publicField(this, "closedByClient", false);
__publicField(this, "listeners", {
connect: [],
disconnect: [],
error: [],
notice: [],
auth: []
});
__publicField(this, "subListeners", {});
__publicField(this, "pubListeners", {});
__publicField(this, "incomingMessageQueue", []);
__publicField(this, "handleNextInterval");
__publicField(this, "resolveClose");
__publicField(this, "reconnectTimeout", 0);
this.url = url;
this.alreadyHaveEvent = alreadyHaveEvent;
this.autoReconnect = autoReconnect;
}
async trySend(params) {
var _a;
const msg = JSON.stringify(params);
if (this.connected) {
(_a = this.ws) == null ? void 0 : _a.send(msg);
} else {
this.sendOnConnect.push(msg);
}
}
async connectRelay() {
return new Promise((resolve, reject) => {
try {
const ws2 = new browser_default(this.url);
this.ws = ws2;
} catch (err) {
reject(err);
return;
}
this.ws.onopen = __privateMethod(this, _onopen, onopen_fn).bind(this, resolve);
this.ws.onerror = (e) => {
this.listeners.error.forEach((cb) => cb());
reject(e);
};
this.ws.onclose = __privateMethod(this, _onclose, onclose_fn).bind(this);
this.ws.onmessage = __privateMethod(this, _onmessage, onmessage_fn).bind(this);
});
}
async connect() {
var _a, _b;
if (((_a = this.ws) == null ? void 0 : _a.readyState) && this.ws.readyState < 2)
return;
if (((_b = this.ws) == null ? void 0 : _b.readyState) === 2) {
this.ws.close();
}
this.ws = void 0;
await this.connectRelay();
}
relayInit() {
const this2 = this;
return {
url: this2.url,
sub: this2.sub.bind(this2),
on: this2.on.bind(this2),
off: this2.off.bind(this2),
auth: this2.auth.bind(this2),
publish: this2.publish.bind(this2),
connect: this2.connect.bind(this2),
close() {
return this2.close();
},
get status() {
return this2.status;
},
// @ts-ignore
relay: this2
};
}
get status() {
var _a, _b;
return (_b = (_a = this.ws) == null ? void 0 : _a.readyState) != null ? _b : 3;
}
get connected() {
var _a;
return ((_a = this.ws) == null ? void 0 : _a.readyState) === 1;
}
close() {
var _a;
this.closedByClient = true;
(_a = this.ws) == null ? void 0 : _a.close();
return new Promise((resolve) => {
this.resolveClose = resolve;
});
}
on(type, cb) {
var _a;
this.listeners[type].push(cb);
if (type === "connect" && ((_a = this.ws) == null ? void 0 : _a.readyState) === 1) {
cb();
}
}
off(type, cb) {
const index = this.listeners[type].indexOf(cb);
if (index !== -1)
this.listeners[type].splice(index, 1);
}
publish(event) {
return this._publish(event, "EVENT");
}
auth(event) {
return this._publish(event, "AUTH");
}
_publish(event, type) {
const this2 = this;
if (!event.id)
throw new Error(`event ${event} has no id`);
const id = event.id;
let sent = false;
let mustMonitor = false;
this2.trySend([type, event]).then(() => {
sent = true;
if (mustMonitor) {
startMonitoring();
mustMonitor = false;
}
}).catch(() => {
});
const startMonitoring = () => {
const monitor = this.sub([{ ids: [id] }], {
id: `monitor-${id.slice(0, 5)}`
});
const willUnsub = setTimeout(() => {
var _a;
(((_a = this2.pubListeners[id]) == null ? void 0 : _a.failed) || []).forEach(
(cb) => cb("event not seen after 5 seconds")
);
monitor.unsub();
}, 5e3);
monitor.on("event", () => {
var _a;
clearTimeout(willUnsub);
(((_a = this2.pubListeners[id]) == null ? void 0 : _a.seen) || []).forEach((cb) => cb());
});
};
return {
on: (type2, cb) => {
this2.pubListeners[id] = this2.pubListeners[id] || {
ok: [],
seen: [],
failed: []
};
this2.pubListeners[id][type2].push(cb);
if (type2 === "seen") {
if (sent)
startMonitoring();
else
mustMonitor = true;
}
},
off: (type2, cb) => {
const listeners = this2.pubListeners[id];
if (!listeners)
return;
const idx = listeners[type2].indexOf(cb);
if (idx >= 0)
listeners[type2].splice(idx, 1);
}
};
}
sub(filters, opts = {}) {
const this2 = this;
const subid = opts.id || Math.random().toString().slice(2);
const skipVerification = opts.skipVerification || false;
this2.openSubs[subid] = {
id: subid,
filters,
skipVerification
};
if (this2.connected) {
if (this.logging) {
console.log("REQ2", this.url, subid, ...filters);
}
this2.trySend(["REQ", subid, ...filters]);
}
return {
sub: (newFilters, newOpts = {}) => this.sub(newFilters || filters, {
skipVerification: newOpts.skipVerification || skipVerification,
id: subid
}),
unsub: () => {
delete this2.openSubs[subid];
delete this2.subListeners[subid];
if (this2.connected) {
if (this2.logging) {
console.log("CLOSE", this.url, subid);
}
this2.trySend(["CLOSE", subid]);
}
},
on: (type, cb) => {
this2.subListeners[subid] = this2.subListeners[subid] || {
event: [],
eose: []
};
this2.subListeners[subid][type].push(cb);
},
off: (type, cb) => {
const listeners = this2.subListeners[subid];
if (!listeners)
return;
const idx = listeners[type].indexOf(cb);
if (idx >= 0)
listeners[type].splice(idx, 1);
}
};
}
};
_handleNext = new WeakSet();
handleNext_fn = function() {
if (this.incomingMessageQueue.length === 0) {
clearInterval(this.handleNextInterval);
this.handleNextInterval = null;
return;
}
__privateMethod(this, _handleMessage, handleMessage_fn).call(this, { data: this.incomingMessageQueue.shift() });
};
_onclose = new WeakSet();
onclose_fn = async function() {
if (this.closedByClient) {
this.listeners.disconnect.forEach((cb) => cb());
this.resolveClose && this.resolveClose();
} else {
if (this.autoReconnect) {
__privateMethod(this, _reconnect, reconnect_fn).call(this);
}
}
};
_reconnect = new WeakSet();
reconnect_fn = function() {
setTimeout(() => {
this.reconnectTimeout = Math.max(2e3, this.reconnectTimeout * 3);
console.log(
this.url,
"reconnecting after " + this.reconnectTimeout / 1e3 + "s"
);
this.connect();
}, this.reconnectTimeout);
};
_onmessage = new WeakSet();
onmessage_fn = async function(e) {
this.incomingMessageQueue.push(e.data);
if (!this.handleNextInterval) {
this.handleNextInterval = setInterval(() => __privateMethod(this, _handleNext, handleNext_fn).call(this), 0);
}
};
_handleMessage = new WeakSet();
handleMessage_fn = async function(e) {
var _a, _b, _c, _d, _e, _f, _g;
let data;
let json = e.data.toString();
if (!json) {
return;
}
let eventId = getHex642(json, "id");
let event = (_a = this.alreadyHaveEvent) == null ? void 0 : _a.call(this, eventId);
if (event) {
const listener = this.subListeners[getSubName(json)];
if (!listener) {
return;
}
return listener.event.forEach((cb) => cb(event));
}
try {
data = JSON.parse(json);
} catch (err) {
data = e.data;
}
if (data.length >= 1) {
switch (data[0]) {
case "EVENT":
if (this.logging) {
console.log(data);
}
if (data.length !== 3)
return;
const id = data[1];
const event2 = data[2];
if (!this.openSubs[id]) {
return;
}
if ((_b = this.openSubs[id].eventIds) == null ? void 0 : _b.has(eventId)) {
return;
}
(_c = this.openSubs[id].eventIds) == null ? void 0 : _c.add(eventId);
if (validateEvent(event2) && this.openSubs[id] && (this.openSubs[id].skipVerification || verifySignature(event2)) && matchFilters(this.openSubs[id].filters, event2)) {
this.openSubs[id];
(((_d = this.subListeners[id]) == null ? void 0 : _d.event) || []).forEach((cb) => cb(event2));
}
return;
case "EOSE": {
if (data.length !== 2)
return;
const id2 = data[1];
if (this.logging) {
console.log("EOSE", this.url, id2);
}
(((_e = this.subListeners[id2]) == null ? void 0 : _e.eose) || []).forEach((cb) => cb());
return;
}
case "OK": {
if (data.length < 3)
return;
const id2 = data[1];
const ok = data[2];
const reason = data[3] || "";
if (ok)
(_f = this.pubListeners[id2]) == null ? void 0 : _f.ok.forEach((cb) => cb());
else
(_g = this.pubListeners[id2]) == null ? void 0 : _g.failed.forEach((cb) => cb(reason));
return;
}
case "NOTICE":
if (data.length !== 2)
return;
const notice = data[1];
this.listeners.notice.forEach((cb) => cb(notice));
return;
case "AUTH":
if (data.length !== 2)
return;
const challenge2 = data[1];
this.listeners.auth.forEach((cb) => cb(challenge2));
return;
}
}
};
_onopen = new WeakSet();
onopen_fn = function(opened) {
var _a;
if (this.resolveClose) {
this.resolveClose();
return;
}
for (const subid in this.openSubs) {
if (this.logging) {
console.log("REQ", this.url, subid, ...this.openSubs[subid].filters);
}
this.trySend(["REQ", subid, ...this.openSubs[subid].filters]);
}
for (const msg of this.sendOnConnect) {
if (this.logging) {
console.log("(Relay msg)", this.url, msg);
}
(_a = this.ws) == null ? void 0 : _a.send(msg);
}
this.sendOnConnect = [];
this.listeners.connect.forEach((cb) => cb());
opened();
};
// event-cache.ts
var _addEventToAuthorKindsByPubKey, addEventToAuthorKindsByPubKey_fn, _addEventToEventsByTags, addEventToEventsByTags_fn, _getCachedEventsByPubKeyWithUpdatedFilter, getCachedEventsByPubKeyWithUpdatedFilter_fn, _getCachedEventsByPubKeyWithUpdatedFilter2, getCachedEventsByPubKeyWithUpdatedFilter2_fn, _getCachedEventsByTagsWithUpdatedFilter, getCachedEventsByTagsWithUpdatedFilter_fn, _getCachedEventsByIdWithUpdatedFilter, getCachedEventsByIdWithUpdatedFilter_fn;
var EventCache = class {
constructor() {
__privateAdd(this, _addEventToAuthorKindsByPubKey);
__privateAdd(this, _addEventToEventsByTags);
__privateAdd(this, _getCachedEventsByPubKeyWithUpdatedFilter);
__privateAdd(this, _getCachedEventsByPubKeyWithUpdatedFilter2);
__privateAdd(this, _getCachedEventsByTagsWithUpdatedFilter);
__privateAdd(this, _getCachedEventsByIdWithUpdatedFilter);
__publicField(this, "eventsById", /* @__PURE__ */ new Map());
__publicField(this, "metadataByPubKey", /* @__PURE__ */ new Map());
__publicField(this, "contactsByPubKey", /* @__PURE__ */ new Map());
__publicField(this, "authorsKindsByPubKey", /* @__PURE__ */ new Map());
__publicField(this, "eventsByTags", /* @__PURE__ */ new Map());
}
addEvent(event) {
if (this.getEventById(event.id)) {
return;
}
this.eventsById.set(event.id, event);
if (event.kind === Kind.Metadata) {
this.metadataByPubKey.set(event.pubkey, event);
}
if (event.kind === Kind.Contacts) {
this.contactsByPubKey.set(event.pubkey, event);
}
__privateMethod(this, _addEventToAuthorKindsByPubKey, addEventToAuthorKindsByPubKey_fn).call(this, event);
__privateMethod(this, _addEventToEventsByTags, addEventToEventsByTags_fn).call(this, event);
}
getEventById(id) {
return this.eventsById.get(id);
}
hasEventById(id) {
return this.eventsById.has(id);
}
getCachedEventsWithUpdatedFilters(filters, relays) {
const events = /* @__PURE__ */ new Set();
const new_filters = [];
for (const filter of filters) {
const new_data = __privateMethod(this, _getCachedEventsByIdWithUpdatedFilter, getCachedEventsByIdWithUpdatedFilter_fn).call(this, filter) || // this.#getCachedEventsByPubKeyWithUpdatedFilter(filter) ||
__privateMethod(this, _getCachedEventsByPubKeyWithUpdatedFilter2, getCachedEventsByPubKeyWithUpdatedFilter2_fn).call(this, filter) || __privateMethod(this, _getCachedEventsByTagsWithUpdatedFilter, getCachedEventsByTagsWithUpdatedFilter_fn).call(this, filter) || {
filter,
events: []
};
for (const event of new_data.events) {
events.add(event);
}
new_filters.push(new_data.filter);
}
return { filters: new_filters, events: [...events] };
}
};
_addEventToAuthorKindsByPubKey = new WeakSet();
addEventToAuthorKindsByPubKey_fn = function(event) {
const kindsByPubKey = this.authorsKindsByPubKey.get(event.pubkey);
if (!kindsByPubKey) {
this.authorsKindsByPubKey.set(
event.pubkey,
/* @__PURE__ */ new Map([[event.kind, [event]]])
);
} else {
const events = kindsByPubKey.get(event.kind);
if (!events) {
kindsByPubKey.set(event.kind, [event]);
} else {
if (event.kind === Kind.Metadata || event.kind === Kind.Contacts) {
if (event.created_at > events[0].created_at) {
events[0] = event;
}
} else {
events.push(event);
}
}
}
};
_addEventToEventsByTags = new WeakSet();
addEventToEventsByTags_fn = function(event) {
for (const tag of event.tags) {
let tag2 = tag[0] + ":" + tag[1];
const events = this.eventsByTags.get(tag2);
if (events) {
events.push(event);
} else {
this.eventsByTags.set(tag2, [event]);
}
}
};
_getCachedEventsByPubKeyWithUpdatedFilter = new WeakSet();
getCachedEventsByPubKeyWithUpdatedFilter_fn = function(filter) {
if (filter.noCache || !filter.authors || !filter.kinds || filter.kinds.find(
(kind) => kind !== Kind.Contacts && kind !== Kind.Metadata
) !== void 0) {
return void 0;
}
const authors = [];
const events = /* @__PURE__ */ new Set();
for (const author of filter.authors) {
let contactEvent;
if (filter.kinds.includes(Kind.Contacts)) {
contactEvent = this.contactsByPubKey.get(author);
if (!contactEvent) {
authors.push(author);
continue;
}
}
let metadataEvent;
if (filter.kinds.includes(Kind.Metadata)) {
metadataEvent = this.metadataByPubKey.get(author);
if (!metadataEvent) {
authors.push(author);
continue;
}
}
if (contactEvent) {
events.add(contactEvent);
}
if (metadataEvent) {
events.add(metadataEvent);
}
}
return { filter: { ...filter, authors }, events };
};
_getCachedEventsByPubKeyWithUpdatedFilter2 = new WeakSet();
getCachedEventsByPubKeyWithUpdatedFilter2_fn = function(filter) {
if (filter.noCache || !filter.authors) {
return void 0;
}
const events = /* @__PURE__ */ new Set();
for (const author of filter.authors) {
if (filter.kinds) {
const kindsByPubKey = this.authorsKindsByPubKey.get(author);
if (kindsByPubKey) {
for (const kind of filter.kinds) {
const events2 = kindsByPubKey.get(kind);
if (events2) {
for (const event of events2) {
events.add(event);
}
}
}
}
} else {
const kindsByPubKey = this.authorsKindsByPubKey.get(author);
if (kindsByPubKey) {
for (const events2 of kindsByPubKey.values()) {
for (const event3 of events2) {
events.add(event3);
}
}
}
}
}
return { filter, events };
};
_getCachedEventsByTagsWithUpdatedFilter = new WeakSet();
getCachedEventsByTagsWithUpdatedFilter_fn = function(filter) {
if (filter.noCache) {
return void 0;
}
const events = /* @__PURE__ */ new Set();
for (const tag in filter) {
if (tag[0] !== "#") {
continue;
}
let tag2 = tag.slice(1) + ":" + filter[tag][0];
const events2 = this.eventsByTags.get(tag2);
if (events2) {
for (const event of events2) {
events.add(event);
}
}
}
return { filter, events };
};
_getCachedEventsByIdWithUpdatedFilter = new WeakSet();
getCachedEventsByIdWithUpdatedFilter_fn = function(filter) {
if (!filter.ids) {
return void 0;
}
const events = /* @__PURE__ */ new Set();
const ids = [];
for (const id of filter.ids) {
const event = this.getEventById(id);
if (event) {
events.add(event);
} else {
ids.push(id);
}
}
return { filter: { ...filter, ids }, events };
};
// author.ts
var Author = class _Author {
constructor(relayPool2, relays, pubkey) {
__publicField(this, "pubkey");
__publicField(this, "relayPool");
__publicField(this, "relays");
this.pubkey = pubkey;
this.relayPool = relayPool2;
this.relays = relays;
}
metaData(cb, maxDelayms) {
return this.relayPool.subscribeEventObject(
[
{
authors: [this.pubkey],
kinds: [Kind.Metadata]
}
],
this.relays,
cb,
maxDelayms
);
}
subscribe(filters, cb, maxDelayms) {
return this.relayPool.subscribeEventObject(
filters.map((filter) => ({
authors: [this.pubkey],
...filter
})),
this.relays,
cb,
maxDelayms
);
}
followsPubkeys(cb, maxDelayms) {
return this.relayPool.subscribeEventObject(
[
{
authors: [this.pubkey],
kinds: [Kind.Contacts]
}
],
this.relays,
(event) => {
let r = [];
for (const tag of event.tags) {
if (tag[0] === "p") {
r.push(tag[1]);
}
}
cb(r);
},
maxDelayms
);
}
// TODO: prioritize relay over other relays for specific authors
follows(cb, maxDelayms) {
return this.relayPool.subscribeEventObject(
[
{
authors: [this.pubkey],
kinds: [Kind.Contacts]
}
],
this.relays,
(event) => {
let r = [];
for (const tag of event.tags) {
if (tag[0] === "p") {
let relays = this.relays;
if (tag[1]) {
relays = [tag[1], ...this.relays || []];
}
r.push(new _Author(this.relayPool, relays, tag[1]));
}
}
cb(r);
},
maxDelayms
);
}
secondFollows(cb, maxDelayms, removeDirectFollows = true) {
return this.followsPubkeys((pubkeys) => {
let sfollows = /* @__PURE__ */ new Map();
for (const pubkey of pubkeys) {
this.relayPool.subscribeEventObject(
[
{
authors: [pubkey],
kinds: [Kind.Contacts]
}
],
this.relays,
(event) => {
let dweight = 1 / event.tags.length;
for (const tag of event.tags) {
if (tag[0] === "p") {
let weight = sfollows.get(tag[1]);
if (weight) {
weight += dweight;
} else {
weight = dweight;
}
sfollows.set(tag[1], weight);
}
}
if (removeDirectFollows) {
for (const pubkey2 of pubkeys) {
sfollows.delete(pubkey2);
}
}
cb(Array.from(sfollows.entries()).sort((a, b) => b[1] - a[1]));
},
maxDelayms
);
}
}, maxDelayms);
}
allEvents(cb, limit = 100, maxDelayms) {
return this.relayPool.subscribe(
[
{
authors: [this.pubkey],
limit
}
],
this.relays,
cb,
maxDelayms
);
}
referenced(cb, limit = 100, maxDelayms) {
return this.relayPool.subscribe(
[
{
"#p": [this.pubkey],
limit
}
],
this.relays,
cb,
maxDelayms
);
}
followers(cb, limit = 100, maxDelayms) {
return this.relayPool.subscribe(
[
{
"#p": [this.pubkey],
kinds: [Kind.Contacts],
limit
}
],
this.relays,
cb,
maxDelayms
);
}
sentAndRecievedDMs(cb, limit = 100, maxDelayms) {
return this.relayPool.subscribe(
[
{
authors: [this.pubkey],
kinds: [Kind.EncryptedDirectMessage],
limit
},
{
"#p": [this.pubkey],
kinds: [Kind.EncryptedDirectMessage],
limit
}
],
this.relays,
cb,
maxDelayms
);
}
text(cb, limit = 100, maxDelayms) {
return this.relayPool.subscribe(
[
{
authors: [this.pubkey],
kinds: [Kind.Text],
limit
}
],
this.relays,
cb,
maxDelayms
);
}
};
// event.ts
var EventObject = class _EventObject {
constructor(event, relayPool2, relays) {
__publicField(this, "id");
__publicField(this, "kind");
__publicField(this, "pubkey");
__publicField(this, "tags");
__publicField(this, "created_at");
__publicField(this, "content");
__publicField(this, "relayPool");
__publicField(this, "relays");
__publicField(this, "sig");
this.id = event.id;
this.kind = event.kind;
this.pubkey = event.pubkey;
this.tags = event.tags;
this.created_at = event.created_at;
this.content = event.content;
this.relayPool = relayPool2;
this.relays = relays;
this.sig = event.sig;
}
referencedAuthors() {
const r = [];
for (const tag of this.tags) {
if (tag[0] === "p") {
r.push(new Author(this.relayPool, void 0, tag[1]));
}
}
return r;
}
referencedEvents(maxDelayms) {
const r = [];
for (const tag of this.tags) {
if (tag[0] === "e") {
let relays = this.relays;
if (tag[2]) {
relays = [tag[2], ...relays || []];
}
r.push(
this.relayPool.getEventById(tag[1], relays, maxDelayms).then((e) => new _EventObject(e, this.relayPool, this.relays))
);
}
}
return r;
}
thread(cb, maxDelayms) {
let relays = this.relays;
let ids = [];
for (const tag of this.tags) {
if (tag[0] === "e") {
if (tag[2]) {
relays = [tag[2], ...relays || []];
}
ids.push(tag[1]);
}
}
return this.relayPool.subscribe(
[{ ids }, { "#e": ids }],
relays,
cb,
maxDelayms
);
}
};
// on-event-filters.ts
function doNotEmitDuplicateEvents(onEvent) {
let event_ids = /* @__PURE__ */ new Set();
return (event, afterEose, url) => {
if (event_ids.has(event.id))
return;
event_ids.add(event.id);
onEvent(event, afterEose, url);
};
}
function doNotEmitOlderEvents(onEvent) {
let created_at_by_events_kinds = /* @__PURE__ */ new Map();
return (event, afterEose, url) => {
if (event.kind === Kind.Metadata || event.kind === Kind.Contacts) {
let event_kind = event.pubkey + " " + event.kind;
if ((created_at_by_events_kinds.get(event_kind) || 0) > event.created_at)
return;
created_at_by_events_kinds.set(event_kind, event.created_at);
}
onEvent(event, afterEose, url);
};
}
function matchOnEventFilters(onEvent, filters) {
return (event, afterEose, url) => {
for (let filter of filters) {
if (matchFilter(filter, event)) {
onEvent(event, afterEose, url);
break;
}
}
};
}
// callback-replayer.ts
var CallbackReplayer = class {
constructor(onunsub) {
__publicField(this, "subs", []);
__publicField(this, "events", []);
__publicField(this, "onunsub");
this.onunsub = onunsub;
}
event(...args) {
this.events.push(args);
this.subs.forEach((sub) => sub(...args));
}
sub(callback) {
this.events.forEach((event) => callback(...event));
this.subs.push(callback);
return () => {
var _a;
this.subs = this.subs.filter((sub) => sub !== callback);
if (this.subs.length === 0) {
(_a = this.onunsub) == null ? void 0 : _a.call(this);
this.onunsub = void 0;
}
};
}
};
// group-filters-by-relay.ts
var unique = (arr) => [...new Set(arr)];
function groupFiltersByRelayAndEmitCacheHits(filters, relays, onEvent, options = {}, eventCache) {
let events = [];
if (eventCache) {
const cachedEventsWithUpdatedFilters = eventCache.getCachedEventsWithUpdatedFilters(filters, relays);
filters = cachedEventsWithUpdatedFilters.filters;
events = cachedEventsWithUpdatedFilters.events;
}
if (options.logAllEvents) {
const onEventNow = onEvent;
onEvent = (event, afterEose, url) => {
onEventNow(event, afterEose, url);
};
}
if (!options.allowDuplicateEvents) {
onEvent = doNotEmitDuplicateEvents(onEvent);
}
if (!options.allowOlderEvents) {
onEvent = doNotEmitOlderEvents(onEvent);
}
for (const event of events) {
onEvent(event, false, void 0);
}
filters = mergeSimilarAndRemoveEmptyFilters(filters);
onEvent = matchOnEventFilters(onEvent, filters);
relays = unique(relays);
const filtersByRelay = getFiltersByRelay(filters, relays);
return [onEvent, filtersByRelay];
}
function getFiltersByRelay(filters, relays) {
const filtersByRelay = /* @__PURE__ */ new Map();
const filtersWithoutRelay = [];
for (const filter of filters) {
const relay = filter.relay;
if (relay) {
const relayFilters = filtersByRelay.get(relay);
if (relayFilters) {
relayFilters.push(withoutRelay(filter));
} else {
filtersByRelay.set(relay, [withoutRelay(filter)]);
}
} else {
filtersWithoutRelay.push(filter);
}
}
if (filtersWithoutRelay.length > 0) {
for (const relay of relays) {
const filters2 = filtersByRelay.get(relay);
if (filters2) {
filtersByRelay.set(relay, filters2.concat(filtersWithoutRelay));
} else {
filtersByRelay.set(relay, filtersWithoutRelay);
}
}
}
return filtersByRelay;
}
function withoutRelay(filter) {
filter = { ...filter };
delete filter.relay;
return filter;
}
function batchFiltersByRelay(subscribedFilters, subscriptionCache) {
const filtersByRelay = /* @__PURE__ */ new Map();
const onEvents = [];
let counter = 0;
let unsubOnEoseCounter = 0;
let allUnsub = { unsubcb: () => {
}, unsuboneosecb: () => {
} };
let unsubVirtualSubscription = () => {
counter--;
if (counter === 0) {
allUnsub.unsubcb();
} else if (unsubOnEoseCounter === 0) {
allUnsub.unsuboneosecb();
}
};
for (const [
onEvent2,
filtersByRelayBySub,
unsub,
unsubscribeOnEose,
subscriptionCacheKey
] of subscribedFilters) {
if (!unsub.unsubcb) {
continue;
}
for (const [relay, filters] of filtersByRelayBySub) {
const filtersByRelayFilters = filtersByRelay.get(relay);
if (filtersByRelayFilters) {
filtersByRelay.set(relay, filtersByRelayFilters.concat(filters));
} else {
filtersByRelay.set(relay, filters);
}
}
let onEventWithUnsub = (event, afterEose, url) => {
if (unsub.unsubcb) {
onEvent2(event, afterEose, url);
}
};
if (subscriptionCache && subscriptionCacheKey) {
const callbackReplayer = new CallbackReplayer(unsubVirtualSubscription);
onEvents.push((event, afterEose, url) => {
callbackReplayer.event(event, afterEose, url);
});
let unsubReplayerVirtualSubscription = callbackReplayer.sub(onEventWithUnsub);
subscriptionCache.set(subscriptionCacheKey, callbackReplayer);
unsub.unsubcb = () => {
unsub.unsubcb = void 0;
unsubReplayerVirtualSubscription();
if (!unsubscribeOnEose) {
unsubOnEoseCounter--;
}
};
} else {
onEvents.push(onEventWithUnsub);
unsub.unsubcb = () => {
unsub.unsubcb = void 0;
unsubVirtualSubscription();
if (!unsubscribeOnEose) {
unsubOnEoseCounter--;
}
};
}
counter++;
if (!unsubscribeOnEose) {
unsubOnEoseCounter++;
}
}
if (unsubOnEoseCounter === 0) {
setTimeout(() => {
allUnsub.unsuboneosecb();
}, 0);
} else {
}
const onEvent = (event, afterEose, url) => {
for (const onEvent2 of onEvents) {
onEvent2(event, afterEose, url);
}
};
subscribedFilters.length = 0;
return [onEvent, filtersByRelay, allUnsub];
}
// newest-event-cache.ts
var NewestEventCache = class {
constructor(kind, relayPool2, relays, useps) {
__publicField(this, "data");
__publicField(this, "promises");
__publicField(this, "relays");
__publicField(this, "kind");
__publicField(this, "relayPool");
__publicField(this, "useps");
this.data = /* @__PURE__ */ new Map();
this.promises = /* @__PURE__ */ new Map();
this.kind = kind;
this.relayPool = relayPool2;
this.relays = relays || ["wss://us.rbr.bio", "wss://eu.rbr.bio"];
this.useps = useps || false;
}
async get(pubkey) {
let value = this.data.get(pubkey);
if (value) {
return Promise.resolve(value);
}
const promise = this.promises.get(pubkey);
if (promise) {
return promise;
}
return new Promise((resolve, reject) => {
let tries = 0;
const filter = this.useps ? { kinds: [this.kind], "#p": [pubkey] } : { kinds: [this.kind], authors: [pubkey] };
const logSubscriptions = this.relayPool.logSubscriptions;
this.relayPool.logSubscriptions = false;
this.relayPool.subscribe(
[filter],
this.relays,
(event) => {
this.data.set(pubkey, event);
this.promises.delete(pubkey);
resolve(event);
},
void 0,
(relayUrl) => {
if (this.relays.includes(relayUrl)) {
tries++;
}
if (tries === this.relays.length) {
this.promises.delete(pubkey);
reject(
`Can't find data2 for ${pubkey} with kind ${this.kind} on RelayInfoServers ${this.relays.join(",")}, ${tries} tries`
);
}
},
{ dontSendOtherFilters: true }
);
this.relayPool.logSubscriptions = logSubscriptions;
});
}
};
// relay-pool.ts
var unique2 = (arr) => [...new Set(arr)];
function parseJSON(json) {
if (json) {
return JSON.parse(json);
}
}
var _maybeLogErrorsAndNotices, maybeLogErrorsAndNotices_fn, _subscribeRelay, subscribeRelay_fn, _mergeAndRemoveEmptyFiltersByRelay, mergeAndRemoveEmptyFiltersByRelay_fn, _subscribeRelays, subscribeRelays_fn, _resetTimer, resetTimer_fn, _getRelaysAndSubscribe, getRelaysAndSubscribe_fn;
var RelayPool = class {
constructor(relays, options = {}) {
__privateAdd(this, _maybeLogErrorsAndNotices);
__privateAdd(this, _subscribeRelay);
__privateAdd(this, _mergeAndRemoveEmptyFiltersByRelay);
__privateAdd(this, _subscribeRelays);
__privateAdd(this, _resetTimer);
__privateAdd(this, _getRelaysAndSubscribe);
__publicField(this, "relayByUrl", /* @__PURE__ */ new Map());
__publicField(this, "noticecbs", []);
__publicField(this, "errorcbs", []);
__publicField(this, "authcbs", []);
__publicField(this, "eventCache");
__publicField(this, "minMaxDelayms", Infinity);
__publicField(this, "filtersToSubscribe", []);
__publicField(this, "timer");
__publicField(this, "externalGetEventById");
__publicField(this, "logSubscriptions", false);
__publicField(this, "autoReconnect", false);
__publicField(this, "startTime", (/* @__PURE__ */ new Date()).getTime());
__publicField(this, "deleteSignatures");
__publicField(this, "subscriptionCache");
__publicField(this, "skipVerification");
__publicField(this, "writeRelays");
__publicField(this, "metadataCache");
__publicField(this, "contactListCache");
__publicField(this, "logErrorsAndNotices");
__publicField(this, "errorsAndNoticesInterval");
__publicField(this, "errorsAndNotices", []);
var _a;
this.externalGetEventById = options.externalGetEventById;
this.logSubscriptions = options.logSubscriptions;
this.autoReconnect = options.autoReconnect;
this.deleteSignatures = options.deleteSignatures;
this.skipVerification = options.skipVerification;
this.writeRelays = new NewestEventCache(10003, this, void 0, true);
this.metadataCache = new NewestEventCache(0, this);
this.contactListCache = new NewestEventCache(3, this);
if (options.useEventCache) {
this.eventCache = new EventCache();
}
if (options.subscriptionCache) {
this.subscriptionCache = /* @__PURE__ */ new Map();
}
if (relays) {
for (const relay of unique2(relays)) {
this.addOrGetRelay(relay);
}
}
this.logErrorsAndNotices = (_a = options.logErrorsAndNotices) != null ? _a : true;
this.onnotice((url, msg) => {
this.errorsAndNotices.push({
type: "notice",
url,
msg,
time: Date.now() - this.startTime
});
});
this.onerror((url, msg) => {
this.errorsAndNotices.push({
type: "error",
url,
msg,
time: Date.now() - this.startTime
});
});
this.errorsAndNoticesInterval = setInterval(
() => __privateMethod(this, _maybeLogErrorsAndNotices, maybeLogErrorsAndNotices_fn).call(this),
1e3 * 10
);
}
addOrGetRelay(relay) {
const origRelayInstance = this.relayByUrl.get(relay);
if (origRelayInstance) {
return origRelayInstance;
}
const relayInstance = relayInit(
relay,
this.externalGetEventById ? this.externalGetEventById : this.eventCache ? (id) => {
var _a;
return (_a = this.eventCache) == null ? void 0 : _a.getEventById(id);
} : void 0,
this.autoReconnect
);
this.relayByUrl.set(relay, relayInstance);
relayInstance.connect().then(
(onfulfilled) => {
relayInstance == null ? void 0 : relayInstance.on("notice", (msg) => {
this.noticecbs.forEach((cb) => cb(relay, msg));
});
relayInstance == null ? void 0 : relayInstance.on("auth", (msg) => {
this.authcbs.forEach((cb) => cb(relayInstance, msg));
});
},
(onrejected) => {
this.errorcbs.forEach((cb) => cb(relay, onrejected));
}
);
return relayInstance;
}
async close() {
const promises = [];
for (const relayInstance of this.relayByUrl.values()) {
promises.push(relayInstance.close());
}
this.relayByUrl.clear();
clearInterval(this.errorsAndNoticesInterval);
return Promise.all(promises);
}
removeRelay(url) {
const relay = this.relayByUrl.get(url);
if (relay) {
relay.close();
this.relayByUrl.delete(url);
}
}
sendSubscriptions(onEose, filtersToSubscribe) {
clearTimeout(this.timer);
this.timer = void 0;
let minMaxDelayms = this.minMaxDelayms;
this.minMaxDelayms = Infinity;
const [onEvent, filtersByRelay, unsub] = batchFiltersByRelay(
filtersToSubscribe || this.filtersToSubscribe,
this.subscriptionCache
);
let allUnsub = __privateMethod(this, _subscribeRelays, subscribeRelays_fn).call(this, filtersByRelay, onEvent, onEose, unsub, minMaxDelayms);
return allUnsub;
}
subscribeEventObject(filters, relays, onEventObject, maxDelayms, onEose, options = {}) {
return this.subscribe(
filters,
relays,
(event, afterEose, url) => onEventObject(new EventObject(event, this, relays), afterEose, url)
);
}
subscribe(filters, relays, onEvent, maxDelayms, onEose, options = {}) {
var _a;
if (maxDelayms !== void 0 && onEose) {
throw new Error("maxDelayms and onEose cannot be used together");
}
if (relays === void 0) {
const promise = __privateMethod(this, _getRelaysAndSubscribe, getRelaysAndSubscribe_fn).call(this, filters, onEvent, maxDelayms, onEose, options);
return () => {
promise.then((x) => {
x();
});
};
}
let subscriptionCacheKey;
if (options.unsubscribeOnEose && !onEose) {
subscriptionCacheKey = JSON.stringify([filters, relays]);
const cachedSubscription = (_a = this.subscriptionCache) == null ? void 0 : _a.get(subscriptionCacheKey);
if (cachedSubscription) {
return cachedSubscription.sub(onEvent);
}
}
const [dedupedOnEvent, filtersByRelay] = groupFiltersByRelayAndEmitCacheHits(
filters,
relays,
onEvent,
options,
this.eventCache
);
let unsub = { unsubcb: () => {
} };
if (maxDelayms === void 0 && onEose && this.filtersToSubscribe.length > 0 && !options.dontSendOtherFilters) {
this.sendSubscriptions();
}
const newFilters = [
dedupedOnEvent,
filtersByRelay,
unsub,
options.unsubscribeOnEose,
subscriptionCacheKey,
maxDelayms
];
if (options.dontSendOtherFilters) {
return this.sendSubscriptions(onEose, [newFilters]);
}
this.filtersToSubscribe.push(newFilters);
if (maxDelayms === void 0) {
return this.sendSubscriptions(onEose);
} else {
__privateMethod(this, _resetTimer, resetTimer_fn).call(this, maxDelayms);
return () => {
var _a2;
(_a2 = unsub.unsubcb) == null ? void 0 : _a2.call(unsub);
delete unsub.unsubcb;
};
}
}
async getEventObjectById(id, relays, maxDelayms) {
return this.getEventById(id, relays, maxDelayms).then(
(event) => new EventObject(event, this, relays)
);
}
async getEventById(id, relays, maxDelayms) {
return new Promise((resolve, reject) => {
this.subscribe(
[{ ids: [id] }],
relays,
(event) => {
resolve(event);
},
maxDelayms,
void 0
// {unsubscribeOnEose: true}
);
});
}
publish(event, relays) {
for (const relay of unique2(relays)) {
const instance = this.addOrGetRelay(relay);
instance.publish(event);
}
}
onnotice(cb) {
this.noticecbs.push(cb);
}
onerror(cb) {
this.relayByUrl.forEach(
(relay, url) => relay.on("error", (msg) => cb(url, msg))
);
this.errorcbs.push(cb);
}
ondisconnect(cb) {
this.relayByUrl.forEach(
(relay, url) => relay.on("disconnect", (msg) => cb(url, msg))
);
}
onauth(cb) {
this.authcbs.push(cb);
}
getRelayStatuses() {
return Array.from(this.relayByUrl.entries()).map(
([url, relay]) => [url, relay.status]
).sort();
}
setWriteRelaysForPubKey(pubkey, writeRelays, created_at) {
const event = {
created_at,
pubkey: "",
id: "",
sig: "",
content: JSON.stringify(writeRelays),
// @ts-ignore
kind: 10003,
tags: [["p", pubkey]]
};
this.writeRelays.data.set(pubkey, event);
}
setCachedMetadata(pubkey, metadata) {
this.metadataCache.data.set(pubkey, metadata);
}
setCachedContactList(pubkey, contactList) {
this.contactListCache.data.set(pubkey, contactList);
}
subscribeReferencedEvents(event, onEvent, maxDelayms, onEose, options = {}) {
let ids = [];
let authors = [];
for (const tag of event.tags) {
if (tag[0] === "p") {
const pubkey = tag[1];
if (pubkey.length !== 64) {
console.log("bad pubkey", pubkey, tag);
continue;
}
authors.push(pubkey);
}
if (tag[0] === "e") {
const id = tag[1];
ids.push(id);
}
}
if (ids.length === 0) {
return () => {
};
}
if (authors.length === 0) {
if (options.defaultRelays) {
return this.subscribe(
[{ ids }],
options.defaultRelays,
onEvent,
maxDelayms,
onEose,
options
);
} else {
console.error("No authors for ids in event", event);
return () => {
};
}
}
if (this.logSubscriptions) {
}
return this.subscribe(
[{ ids, authors }],
void 0,
onEvent,
maxDelayms,
onEose,
options
);
}
fetchAndCacheMetadata(pubkey) {
return this.metadataCache.get(pubkey).catch((e) => {
this.errorsAndNotices.push({
type: "error",
msg: `Error fetching metadata for ${pubkey}: ${e}`,
time: Date.now() - this.startTime,
url: ""
});
throw new Error(`Error fetching metadata for ${pubkey}: ${e}`);
});
}
fetchAndCacheContactList(pubkey) {
return this.contactListCache.get(pubkey).catch((e) => {
this.errorsAndNotices.push({
type: "error",
msg: `Error fetching contact list for ${pubkey}: ${e}`,
time: Date.now() - this.startTime,
url: ""
});
throw new Error(`Error fetching contact list for ${pubkey}: ${e}`);
});
}
subscribeReferencedEventsAndPrefetchMetadata(event, onEvent, maxDelayms, onEose, options = {}) {
for (const tag of event.tags) {
if (tag[0] === "p") {
const pubkey = tag[1];
if (pubkey.length !== 64) {
console.log("bad pubkey", pubkey, tag);
continue;
}
this.fetchAndCacheMetadata(pubkey).catch((e) => {
this.errorsAndNotices.push({
type: "error",
url: "",
msg: `Error fetching metadata for ${pubkey}: ${e}`,
time: Date.now() - this.startTime
});
});
}
}
return this.subscribeReferencedEvents(
event,
onEvent,
maxDelayms,
onEose,
options
);
}
reconnect() {
this.relayByUrl.forEach((relay) => {
relay.connect().catch((e) => {
this.errorsAndNotices.push({
type: "error",
msg: `Error reconnecting to ${relay.url}: ${e}`,
time: Date.now() - this.startTime,
url: relay.url
});
});
});
}
};
_maybeLogErrorsAndNotices = new WeakSet();
maybeLogErrorsAndNotices_fn = function() {
if (!this.errorsAndNotices.length) {
return;
}
if (!this.logErrorsAndNotices) {
this.errorsAndNotices = [];
return;
}
if (this.errorsAndNotices.length > 5) {
console.groupCollapsed(
"RelayPool errors and notices with " + this.errorsAndNotices.length + " entries"
);
} else {
console.group("RelayPool errors and notices");
}
console.table(this.errorsAndNotices.map((e) => ({ ...e, msg: e.msg })));
console.groupEnd();
this.errorsAndNotices = [];
};
_subscribeRelay = new WeakSet();
subscribeRelay_fn = function(relay, filters, onEvent, onEose, eventIds) {
const mergedAndRemovedEmptyFilters = mergeSimilarAndRemoveEmptyFilters(filters);
if (mergedAndRemovedEmptyFilters.length === 0) {
return;
}
const instance = this.addOrGetRelay(relay);
const sub = instance.sub(mergedAndRemovedEmptyFilters, {
skipVerification: this.skipVerification,
eventIds
});
let afterEose = false;
let minCreatedAt = Infinity;
sub.on("event", (nostrEvent) => {
var _a;
if (nostrEvent.created_at < minCreatedAt) {
minCreatedAt = nostrEvent.created_at;
}
let event = nostrEvent;
if (!this.deleteSignatures) {
event.sig = nostrEvent.sig;
}
(_a = this.eventCache) == null ? void 0 : _a.addEvent(event);
onEvent(event, afterEose, relay);
});
sub.on("eose", () => {
onEose == null ? void 0 : onEose(relay, minCreatedAt);
afterEose = true;
});
return sub;
};
_mergeAndRemoveEmptyFiltersByRelay = new WeakSet();
mergeAndRemoveEmptyFiltersByRelay_fn = function(filtersByRelay) {
const mergedAndRemovedEmptyFiltersByRelay = /* @__PURE__ */ new Map();
for (const [relay, filters] of filtersByRelay) {
const mergedAndRemovedEmptyFilters = mergeSimilarAndRemoveEmptyFilters(
mergeSimilarAndRemoveEmptyFilters(filters)
);
if (mergedAndRemovedEmptyFilters.length > 0) {
mergedAndRemovedEmptyFiltersByRelay.set(
relay,
mergedAndRemovedEmptyFilters
);
}
}
return mergedAndRemovedEmptyFiltersByRelay;
};
_subscribeRelays = new WeakSet();
subscribeRelays_fn = function(filtersByRelay, onEvent, onEose, unsub = {}, minMaxDelayms) {
var _a, _b;
if (filtersByRelay.size === 0) {
return () => {
};
}
filtersByRelay = __privateMethod(this, _mergeAndRemoveEmptyFiltersByRelay, mergeAndRemoveEmptyFiltersByRelay_fn).call(this, filtersByRelay);
if (this.logSubscriptions) {
console.group("RelayPool subscribeRelays");
console.log(
"at time",
(/* @__PURE__ */ new Date()).getTime() - this.startTime,
"ms, minMaxDelayms=",
minMaxDelayms
);
const flattenedFilters = {};
for (const [relay, filters] of filtersByRelay) {
let i = 0;
for (const filter of filters) {
const filter2 = { ...filter };
if (filter2.authors) {
filter2.authors = filter2.authors.join();
filter2["authors.length"] = (_a = filter == null ? void 0 : filter.authors) == null ? void 0 : _a.length;
}
if (filter2.kinds) {
filter2.kinds = filter2.kinds.join();
}
if (filter2.ids) {
filter2.ids = filter2.ids.join();
filter2["ids.length"] = (_b = filter == null ? void 0 : filter.ids) == null ? void 0 : _b.length;
}
if (filter2["#e"]) {
filter2["#e"] = filter2["#e"].join();
filter2["#e.length"] = filter["#e"].length;
}
if (filter2["#p"]) {
filter2["#p"] = filter2["#p"].join();
filter2["#p.length"] = filter["#p"].length;
}
flattenedFilters[relay + " " + i] = filter2;
i++;
}
}
if (Object.keys(flattenedFilters).length > 3) {
console.groupCollapsed(
Object.keys(flattenedFilters).length + " filters to " + filtersByRelay.size + " relays"
);
}
console.table(flattenedFilters);
if (Object.keys(flattenedFilters).length > 3) {
console.groupEnd();
}
console.groupEnd();
}
const subs = [];
let unsuboneosecbcalled = false;
let eoseSubs = [];
unsub.unsuboneosecb = () => {
unsuboneosecbcalled = true;
eoseSubs.forEach((sub) => sub.unsub());
};
for (const [relay, filters] of filtersByRelay) {
let subHolder = {};
const subOnEose = (url, minCreatedAt) => {
var _a2;
if (onEose) {
onEose(url, minCreatedAt);
}
if (unsuboneosecbcalled) {
(_a2 = subHolder.sub) == null ? void 0 : _a2.unsub();
} else {
if (subHolder.sub) {
eoseSubs.push(subHolder.sub);
}
}
};
const eventIds = /* @__PURE__ */ new Set();
const sub = __privateMethod(this, _subscribeRelay, subscribeRelay_fn).call(this, relay, filters, onEvent, subOnEose, eventIds);
if (sub) {
subHolder.sub = sub;
subs.push(sub);
}
}
const allUnsub = () => subs.forEach((sub) => sub.unsub());
unsub.unsubcb = () => {
allUnsub();
delete unsub.unsubcb;
};
return allUnsub;
};
_resetTimer = new WeakSet();
resetTimer_fn = function(maxDelayms) {
if (this.minMaxDelayms > maxDelayms) {
this.minMaxDelayms = maxDelayms;
}
clearTimeout(this.timer);
this.timer = void 0;
if (this.minMaxDelayms !== Infinity) {
this.timer = setTimeout(() => {
this.sendSubscriptions();
}, this.minMaxDelayms);
}
};
_getRelaysAndSubscribe = new WeakSet();
getRelaysAndSubscribe_fn = async function(filters, onEvent, maxDelayms, onEose, options = {}) {
var _a;
const allAuthors = /* @__PURE__ */ new Set();
for (const filter of filters) {
if (filter.authors) {
for (const author of filter.authors) {
allAuthors.add(author);
}
} else {
if (!options.defaultRelays) {
throw new Error(
"Authors must be specified if no relays are subscribed and no default relays are specified."
);
}
}
}
const promises = [];
const allAuthorsArray = [];
for (const author of allAuthors) {
promises.push(
(_a = this.writeRelays) == null ? void 0 : _a.get(author).then((event) => parseJSON(event == null ? void 0 : event.content)).catch(() => (options == null ? void 0 : options.defaultRelays) || [])
);
allAuthorsArray.push(author);
}
const allRelays = /* @__PURE__ */ new Set();
let i = 0;
for (const promise of promises) {
const author = allAuthorsArray[i];
i += 1;
let relays = await promise;
if (!Array.isArray(relays)) {
console.error("Couldn't load relays for author ", author);
continue;
}
for (let relay of relays) {
allRelays.add(relay);
}
}
let allRelaysArray = Array.from(allRelays);
if (allRelaysArray.length === 0) {
if (options.defaultRelays) {
allRelaysArray = options.defaultRelays;
}
}
return this.subscribe(
filters,
allRelaysArray,
onEvent,
maxDelayms,
onEose,
options
);
};
// relay-pool.worker.ts
var relayPool;
var subscriptions = /* @__PURE__ */ new Map();
self.onmessage = (event) => {
const { action, data } = event.data;
switch (action) {
case "create_relay_pool":
relayPool = new RelayPool(data.relays, data.options);
relayPool.onerror((err, relayUrl) => {
postMessage({ type: "error", err, relayUrl });
});
relayPool.onnotice((relayUrl, notice) => {
postMessage({ type: "notice", relayUrl, notice });
});
break;
case "subscribe":
const subscriptionId = data.subscriptionId;
const unsub = relayPool.subscribe(
data.filters,
data.relays,
(event2, isAfterEose, relayURL) => {
postMessage({
type: "event",
subscriptionId,
event: event2,
isAfterEose,
relayURL
});
},
data.maxDelayms,
data.onEose ? (relayURL, minCreatedAt) => {
postMessage({
type: "eose",
subscriptionId,
relayURL,
minCreatedAt
});
} : void 0,
data.options
);
subscriptions.set(subscriptionId, unsub);
postMessage({ type: "subscribed", subscriptionId });
break;
case "unsubscribe":
const { subscriptionId: idToUnsubscribe } = data;
const unsubscribe = subscriptions.get(idToUnsubscribe);
if (unsubscribe) {
unsubscribe();
subscriptions.delete(idToUnsubscribe);
}
break;
case "publish":
relayPool.publish(data.event, data.relays);
break;
case "set_write_relays_for_pub_key":
relayPool.setWriteRelaysForPubKey(
data.pubkey,
data.writeRelays,
data.created_at
);
break;
case "subscribe_referenced_events":
const subRefId = data.subscriptionId;
const unsubRef = relayPool.subscribeReferencedEvents(
data.event,
(event2, isAfterEose, relayURL) => {
postMessage({
type: "event",
subscriptionId: subRefId,
event: event2,
isAfterEose,
relayURL
});
},
data.maxDelayms,
data.onEose ? (relayURL, minCreatedAt) => {
postMessage({
type: "eose",
subscriptionId: subRefId,
relayURL,
minCreatedAt
});
} : void 0,
data.options
);
subscriptions.set(subRefId, unsubRef);
postMessage({ type: "subscribed", subscriptionId: subRefId });
break;
case "fetch_and_cache_metadata":
relayPool.fetchAndCacheMetadata(data.pubkey).then((metadata) => {
postMessage({ type: "metadata", pubkey: data.pubkey, metadata });
});
break;
case "fetch_and_cache_contact_list":
relayPool.fetchAndCacheContactList(data.pubkey).then((contactList) => {
postMessage({ type: "contactList", pubkey: data.pubkey, contactList });
});
break;
case "subscribe_referenced_events_and_prefetch_metadata":
const subPrefetchId = data.subscriptionId;
const unsubPrefetch = relayPool.subscribeReferencedEventsAndPrefetchMetadata(
data.event,
(event2, isAfterEose, relayURL) => {
postMessage({
type: "event",
subscriptionId: subPrefetchId,
event: event2,
isAfterEose,
relayURL
});
},
data.maxDelayms,
data.onEose ? (relayURL, minCreatedAt) => {
postMessage({
type: "eose",
subscriptionId: subPrefetchId,
relayURL,
minCreatedAt
});
} : void 0,
data.options
);
subscriptions.set(subPrefetchId, unsubPrefetch);
postMessage({ type: "subscribed", subscriptionId: subPrefetchId });
break;
case "set_cached_metadata":
relayPool.setCachedMetadata(data.pubkey, data.metadata);
break;
case "close":
subscriptions.clear();
relayPool.close();
break;
default:
console.error("Unknown action:", action);
}
};
/*! Bundled license information:
@noble/hashes/esm/utils.js:
(*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) *)
@noble/curves/esm/abstract/utils.js:
(*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) *)
@noble/curves/esm/abstract/modular.js:
(*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) *)
@noble/curves/esm/abstract/curve.js:
(*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) *)
@noble/curves/esm/abstract/weierstrass.js:
(*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) *)
@noble/curves/esm/_shortw_utils.js:
(*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) *)
@noble/curves/esm/secp256k1.js:
(*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) *)
@noble/hashes/esm/utils.js:
(*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) *)
@scure/base/lib/esm/index.js:
(*! scure-base - MIT License (c) 2022 Paul Miller (paulmillr.com) *)
@noble/hashes/esm/utils.js:
(*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) *)
@scure/base/lib/esm/index.js:
(*! scure-base - MIT License (c) 2022 Paul Miller (paulmillr.com) *)
@noble/hashes/esm/utils.js:
(*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) *)
@scure/base/lib/esm/index.js:
(*! scure-base - MIT License (c) 2022 Paul Miller (paulmillr.com) *)
@noble/ciphers/esm/utils.js:
(*! noble-ciphers - MIT License (c) 2023 Paul Miller (paulmillr.com) *)
*/