Every node now serves a search and listing-detail UI at GET /. It is vanilla TypeScript, bundled unminified into web/dist (committed) and embedded with go:embed, so `go build` is enough to run a node. The browser verifies each listing itself (certificate, binding, validity, signature, proof-of-work) with pure-JS ed25519, so a gateway can withhold listings but not forge them. Unverifiable results are hidden and their content is never shown. Listing text is only inserted via textContent and the UI is served with a strict CSP. Canonical JSON is reimplemented in TypeScript and tested against a golden fixture signed by the Go code. /api/v1/status now reports difficulty. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2847 lines
94 KiB
JavaScript
2847 lines
94 KiB
JavaScript
// src/api.ts
|
||
async function getJSON(url) {
|
||
const res = await fetch(url, { headers: { Accept: "application/json" } });
|
||
if (res.status === 404) return null;
|
||
if (!res.ok) throw new Error(`${res.status} ${res.statusText}`);
|
||
return res.json();
|
||
}
|
||
async function getStatus() {
|
||
return await getJSON("/api/v1/status");
|
||
}
|
||
async function search(params) {
|
||
const data = await getJSON(`/api/v1/listings?${params}`);
|
||
if (!Array.isArray(data)) throw new Error("unexpected response");
|
||
return data;
|
||
}
|
||
async function getListing(author, id) {
|
||
return getJSON(`/api/v1/listings/${encodeURIComponent(author)}/${encodeURIComponent(id)}`);
|
||
}
|
||
|
||
// src/dom.ts
|
||
function h(tag, props = null, ...children) {
|
||
const el = document.createElement(tag);
|
||
for (const [key, value] of Object.entries(props ?? {})) {
|
||
if (value === void 0 || value === false) continue;
|
||
if (typeof value === "function") {
|
||
el.addEventListener(key.replace(/^on/, "").toLowerCase(), value);
|
||
} else if (value === true) {
|
||
el.setAttribute(key, "");
|
||
} else {
|
||
el.setAttribute(key, String(value));
|
||
}
|
||
}
|
||
append(el, children);
|
||
return el;
|
||
}
|
||
function append(parent, children) {
|
||
for (const c of children) {
|
||
if (c === null || c === void 0 || c === false) continue;
|
||
parent.appendChild(typeof c === "object" ? c : document.createTextNode(String(c)));
|
||
}
|
||
}
|
||
function clear(el) {
|
||
while (el.firstChild) el.removeChild(el.firstChild);
|
||
}
|
||
|
||
// src/i18n.ts
|
||
var de = {
|
||
"app.tagline": "Wohnungen und H\xE4user, getragen von allen. Kostenlos, ohne Konzern.",
|
||
"status.line": "{listings} Anzeigen \xB7 {peers} verbundene Knoten \xB7 Regionen: {regions}",
|
||
"status.unreachable": "Dieser Knoten ist nicht erreichbar.",
|
||
"filter.kind": "Angebot",
|
||
"filter.category": "Art",
|
||
"filter.region": "Gebiet (Geohash)",
|
||
"filter.regionHint": "z. B. u1x f\xFCr den Raum Hamburg, genauer: u1xj",
|
||
"filter.maxPrice": "Preis bis (\u20AC)",
|
||
"filter.minArea": "Fl\xE4che ab (m\xB2)",
|
||
"filter.minRooms": "Zimmer ab",
|
||
"filter.any": "Alle",
|
||
"filter.search": "Suchen",
|
||
"filter.reset": "Zur\xFCcksetzen",
|
||
"kind.rent": "Miete",
|
||
"kind.sale": "Kauf",
|
||
"cat.apartment": "Wohnung",
|
||
"cat.house": "Haus",
|
||
"cat.room": "Zimmer",
|
||
"cat.commercial": "Gewerbe",
|
||
"results.none": "Keine Anzeigen gefunden.",
|
||
"results.loading": "L\xE4dt \u2026",
|
||
"results.more": "Mehr laden",
|
||
"results.hidden": "{n} Ergebnis(se) ausgeblendet, weil die Signatur nicht gepr\xFCft werden konnte.",
|
||
"results.error": "Die Suche ist fehlgeschlagen.",
|
||
"card.perMonth": "/ Monat",
|
||
"card.rooms": "{n} Zimmer",
|
||
"card.area": "{n} m\xB2",
|
||
"badge.ok": "Signatur gepr\xFCft",
|
||
"badge.bad": "Nicht verifiziert",
|
||
"detail.back": "\u2190 Zur\xFCck zur Suche",
|
||
"detail.notFound": "Diese Anzeige gibt es nicht (mehr).",
|
||
"detail.unverified": "Diese Anzeige konnte nicht verifiziert werden und wird deshalb nicht angezeigt. Sie k\xF6nnte gef\xE4lscht oder ver\xE4ndert sein.",
|
||
"detail.features": "Ausstattung",
|
||
"detail.facts": "Eckdaten",
|
||
"detail.kind": "Angebot",
|
||
"detail.category": "Art",
|
||
"detail.area": "Fl\xE4che",
|
||
"detail.rooms": "Zimmer",
|
||
"detail.published": "Ver\xF6ffentlicht",
|
||
"detail.expires": "L\xE4uft ab",
|
||
"detail.version": "Version",
|
||
"detail.location": "Lage (ungef\xE4hr, ca. 1 km)",
|
||
"detail.map": "Auf OpenStreetMap ansehen (externe Seite)",
|
||
"detail.contact": "Kontakt",
|
||
"detail.contactSoon": "Der Kontakt zum Anbieter l\xE4uft \xFCber dessen eigenen Knoten und ist noch nicht verf\xFCgbar. Die genaue Adresse wird nie \xF6ffentlich verteilt.",
|
||
"verify.title": "Pr\xFCfung in deinem Browser",
|
||
"verify.intro": "Diese Pr\xFCfung l\xE4uft lokal, nicht auf dem Server. Ein Knoten kann Anzeigen also nicht unbemerkt f\xE4lschen.",
|
||
"verify.limit": "Nicht pr\xFCfbar: ob der Anbieter sein Ger\xE4t inzwischen gesperrt hat. Das wei\xDF nur das Netzwerk; dein Knoten kennt den aktuellen Stand.",
|
||
"verify.format": "Aufbau der Anzeige",
|
||
"verify.certificate": "Ger\xE4tezertifikat des Anbieters ist g\xFCltig",
|
||
"verify.binding": "Zertifikat geh\xF6rt zu diesem Anbieter und Ger\xE4t",
|
||
"verify.validity": "Zeitr\xE4ume (Zertifikat, Anzeige) stimmen",
|
||
"verify.signature": "Signatur passt zum Inhalt",
|
||
"verify.pow": "Rechenaufwand gegen Spam (Proof-of-Work)",
|
||
"verify.owner": "Anbieter (Identit\xE4t)",
|
||
"verify.device": "Ger\xE4t",
|
||
"verify.raw": "Rohdaten (so signiert)",
|
||
"footer.text": "Allmende ist freie Software (AGPL-3.0). Es gibt keinen Betreiber und keine Geb\xFChren."
|
||
};
|
||
var en = {
|
||
"app.tagline": "Homes to rent and buy, run by everyone. Free, with no company behind it.",
|
||
"status.line": "{listings} listings \xB7 {peers} connected nodes \xB7 regions: {regions}",
|
||
"status.unreachable": "This node is not reachable.",
|
||
"filter.kind": "Offer",
|
||
"filter.category": "Type",
|
||
"filter.region": "Area (geohash)",
|
||
"filter.regionHint": "e.g. u1x for the Hamburg area, more precise: u1xj",
|
||
"filter.maxPrice": "Price up to (\u20AC)",
|
||
"filter.minArea": "Area from (m\xB2)",
|
||
"filter.minRooms": "Rooms from",
|
||
"filter.any": "Any",
|
||
"filter.search": "Search",
|
||
"filter.reset": "Reset",
|
||
"kind.rent": "Rent",
|
||
"kind.sale": "Buy",
|
||
"cat.apartment": "Apartment",
|
||
"cat.house": "House",
|
||
"cat.room": "Room",
|
||
"cat.commercial": "Commercial",
|
||
"results.none": "No listings found.",
|
||
"results.loading": "Loading \u2026",
|
||
"results.more": "Load more",
|
||
"results.hidden": "{n} result(s) hidden because their signature could not be verified.",
|
||
"results.error": "The search failed.",
|
||
"card.perMonth": "/ month",
|
||
"card.rooms": "{n} rooms",
|
||
"card.area": "{n} m\xB2",
|
||
"badge.ok": "Signature verified",
|
||
"badge.bad": "Not verified",
|
||
"detail.back": "\u2190 Back to search",
|
||
"detail.notFound": "This listing does not exist (any more).",
|
||
"detail.unverified": "This listing could not be verified and is therefore not shown. It may be forged or altered.",
|
||
"detail.features": "Features",
|
||
"detail.facts": "Key facts",
|
||
"detail.kind": "Offer",
|
||
"detail.category": "Type",
|
||
"detail.area": "Area",
|
||
"detail.rooms": "Rooms",
|
||
"detail.published": "Published",
|
||
"detail.expires": "Expires",
|
||
"detail.version": "Version",
|
||
"detail.location": "Location (approximate, about 1 km)",
|
||
"detail.map": "View on OpenStreetMap (external site)",
|
||
"detail.contact": "Contact",
|
||
"detail.contactSoon": "Contact goes through the owner's own node and is not available yet. The exact address is never distributed publicly.",
|
||
"verify.title": "Checked in your browser",
|
||
"verify.intro": "This check runs locally, not on the server, so a node cannot forge listings unnoticed.",
|
||
"verify.limit": "Cannot be checked: whether the owner has since revoked their device. Only the network knows that; your node has the current state.",
|
||
"verify.format": "Structure of the listing",
|
||
"verify.certificate": "Owner's device certificate is valid",
|
||
"verify.binding": "Certificate belongs to this owner and device",
|
||
"verify.validity": "Time windows (certificate, listing) are right",
|
||
"verify.signature": "Signature matches the content",
|
||
"verify.pow": "Anti-spam work (proof-of-work)",
|
||
"verify.owner": "Owner (identity)",
|
||
"verify.device": "Device",
|
||
"verify.raw": "Raw data (as signed)",
|
||
"footer.text": "Allmende is free software (AGPL-3.0). There is no operator and there are no fees."
|
||
};
|
||
function detect() {
|
||
const q = new URLSearchParams(location.search).get("lang");
|
||
if (q === "de" || q === "en") return q;
|
||
return navigator.language?.toLowerCase().startsWith("de") ? "de" : "en";
|
||
}
|
||
var lang = detect();
|
||
var dict = lang === "de" ? de : en;
|
||
function t(key, vars = {}) {
|
||
return dict[key].replace(/\{(\w+)\}/g, (_, name) => String(vars[name] ?? ""));
|
||
}
|
||
|
||
// src/format.ts
|
||
function money(cents) {
|
||
return new Intl.NumberFormat(lang, { style: "currency", currency: "EUR" }).format(cents / 100);
|
||
}
|
||
function rooms(x2) {
|
||
return t("card.rooms", { n: (x2 / 2).toLocaleString(lang, { maximumFractionDigits: 1 }) });
|
||
}
|
||
function date(unix) {
|
||
return new Date(unix * 1e3).toLocaleDateString(lang, { dateStyle: "medium" });
|
||
}
|
||
function price(l) {
|
||
if (!l.price) return "";
|
||
const base = money(l.price.amount_cents);
|
||
return l.price.period === "month" ? `${base} ${t("card.perMonth")}` : base;
|
||
}
|
||
function shortKey(hex) {
|
||
return hex.length > 16 ? `${hex.slice(0, 8)}\u2026${hex.slice(-4)}` : hex;
|
||
}
|
||
|
||
// src/geohash.ts
|
||
var ALPHABET = "0123456789bcdefghjkmnpqrstuvwxyz";
|
||
function decodeGeohash(hash) {
|
||
let lat = [-90, 90];
|
||
let lon = [-180, 180];
|
||
let evenBit = true;
|
||
for (const ch of hash) {
|
||
const idx = ALPHABET.indexOf(ch);
|
||
if (idx < 0) return null;
|
||
for (let bit = 4; bit >= 0; bit--) {
|
||
const on = idx >> bit & 1;
|
||
const range = evenBit ? lon : lat;
|
||
const mid = (range[0] + range[1]) / 2;
|
||
if (on) range[0] = mid;
|
||
else range[1] = mid;
|
||
evenBit = !evenBit;
|
||
}
|
||
}
|
||
return {
|
||
lat: (lat[0] + lat[1]) / 2,
|
||
lon: (lon[0] + lon[1]) / 2,
|
||
latErr: (lat[1] - lat[0]) / 2,
|
||
lonErr: (lon[1] - lon[0]) / 2
|
||
};
|
||
}
|
||
|
||
// node_modules/@noble/hashes/_u64.js
|
||
var U32_MASK64 = /* @__PURE__ */ (() => BigInt(2 ** 32 - 1))();
|
||
var _32n = /* @__PURE__ */ BigInt(32);
|
||
function fromBig(n, le = false) {
|
||
if (le)
|
||
return { h: Number(n & U32_MASK64), l: Number(n >> _32n & U32_MASK64) };
|
||
return { h: Number(n >> _32n & U32_MASK64) | 0, l: Number(n & U32_MASK64) | 0 };
|
||
}
|
||
function split(lst, le = false) {
|
||
const len = lst.length;
|
||
let Ah = new Uint32Array(len);
|
||
let Al = new Uint32Array(len);
|
||
for (let i = 0; i < len; i++) {
|
||
const { h: h2, l } = fromBig(lst[i], le);
|
||
[Ah[i], Al[i]] = [h2, l];
|
||
}
|
||
return [Ah, Al];
|
||
}
|
||
var fromNumH = (n) => n / 2 ** 32 | 0;
|
||
var fromNumL = (n) => n >>> 0;
|
||
function setU64FromNum(view, byteOffset, n, isLE) {
|
||
const h2 = fromNumH(n);
|
||
const l = fromNumL(n);
|
||
view.setUint32(byteOffset, isLE ? l : h2, isLE);
|
||
view.setUint32(byteOffset + 4, isLE ? h2 : l, isLE);
|
||
}
|
||
var shrSH = (h2, _l, s) => h2 >>> s;
|
||
var shrSL = (h2, l, s) => h2 << 32 - s | l >>> s;
|
||
var rotrSH = (h2, l, s) => h2 >>> s | l << 32 - s;
|
||
var rotrSL = (h2, l, s) => h2 << 32 - s | l >>> s;
|
||
var rotrBH = (h2, l, s) => h2 << 64 - s | l >>> s - 32;
|
||
var rotrBL = (h2, l, s) => h2 >>> 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;
|
||
|
||
// node_modules/@noble/hashes/utils.js
|
||
function isBytes(a) {
|
||
return a instanceof Uint8Array || ArrayBuffer.isView(a) && a.constructor.name === "Uint8Array" && "BYTES_PER_ELEMENT" in a && a.BYTES_PER_ELEMENT === 1;
|
||
}
|
||
var atitle = (title) => title ? `"${title}" ` : "";
|
||
function anumber(n, title = "") {
|
||
if (typeof n !== "number")
|
||
throw new TypeError(atitle(title) + "expected number, got " + typeof n);
|
||
if (!Number.isSafeInteger(n) || n < 0)
|
||
throw new RangeError(atitle(title) + "expected integer >= 0, got " + n);
|
||
return n;
|
||
}
|
||
function abytes(value, length, title = "") {
|
||
if (isBytes(value) && (length === void 0 || value.length === length))
|
||
return value;
|
||
if (length !== void 0)
|
||
anumber(length, "length");
|
||
const bytes = isBytes(value);
|
||
const ofLen = length !== void 0 ? ` of length ${length}` : "";
|
||
const got = bytes ? `length=${value.length}` : `type=${typeof value}`;
|
||
const message = atitle(title) + "expected Uint8Array" + ofLen + ", got " + got;
|
||
if (!bytes)
|
||
throw new TypeError(message);
|
||
throw new RangeError(message);
|
||
}
|
||
var aobject = (value, label2) => {
|
||
if (value === null || typeof value !== "object" || Array.isArray(value))
|
||
throw new TypeError((label2 === "object" ? "" : `"${label2}" `) + "expected object, got type=" + typeof value);
|
||
};
|
||
var aopts = (value, label2) => {
|
||
aobject(value, label2);
|
||
const proto = Object.getPrototypeOf(value);
|
||
if (proto !== Object.prototype && proto !== null)
|
||
throw new TypeError(`"${label2}" expected plain object`);
|
||
if (Object.hasOwn(value, "__proto__"))
|
||
throw new TypeError(`"${label2}.__proto__" is not allowed`);
|
||
};
|
||
function aexists(instance, checkFinished = true) {
|
||
if (instance.destroyed)
|
||
throw new Error("hash was destroyed");
|
||
if (checkFinished && instance.finished)
|
||
throw new Error("digest() was already called");
|
||
}
|
||
function aoutput(out, instance) {
|
||
abytes(out, void 0, "output");
|
||
const min = instance.outputLen;
|
||
if (!(out.length >= min)) {
|
||
throw new RangeError('"output" expected length >= ' + min);
|
||
}
|
||
}
|
||
function clean(...arrays) {
|
||
for (let i = 0; i < arrays.length; i++) {
|
||
arrays[i].fill(0);
|
||
}
|
||
}
|
||
function createView(arr) {
|
||
return new DataView(arr.buffer, arr.byteOffset, arr.byteLength);
|
||
}
|
||
function rotr(word, shift) {
|
||
return word << 32 - shift | word >>> shift;
|
||
}
|
||
var hasHexBuiltin = /* @__PURE__ */ (() => (
|
||
// @ts-ignore
|
||
typeof Uint8Array.from([]).toHex === "function" && typeof Uint8Array.fromHex === "function"
|
||
))();
|
||
var hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, "0"));
|
||
function bytesToHex(bytes) {
|
||
abytes(bytes);
|
||
if (hasHexBuiltin)
|
||
return bytes.toHex();
|
||
let hex = "";
|
||
for (let i = 0; i < bytes.length; i++) {
|
||
hex += hexes[bytes[i]];
|
||
}
|
||
return hex;
|
||
}
|
||
function asciiToBase16(ch) {
|
||
return ch >= 48 && ch <= 57 ? ch - 48 : ch >= 65 && ch <= 70 ? ch - (65 - 10) : ch >= 97 && ch <= 102 ? ch - (97 - 10) : void 0;
|
||
}
|
||
function hexToBytes(hex) {
|
||
if (typeof hex !== "string")
|
||
throw new TypeError("hex string expected, got " + typeof hex);
|
||
if (hasHexBuiltin) {
|
||
try {
|
||
return Uint8Array.fromHex(hex);
|
||
} catch (error) {
|
||
if (error instanceof SyntaxError)
|
||
throw new RangeError(error.message);
|
||
throw error;
|
||
}
|
||
}
|
||
const hl = hex.length;
|
||
const al = hl / 2;
|
||
if (hl % 2)
|
||
throw new RangeError("hex string expected, got unpadded hex of length " + hl);
|
||
const array = new Uint8Array(al);
|
||
for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) {
|
||
const n1 = asciiToBase16(hex.charCodeAt(hi));
|
||
const n2 = asciiToBase16(hex.charCodeAt(hi + 1));
|
||
if (n1 === void 0 || n2 === void 0) {
|
||
const char = hex[hi] + hex[hi + 1];
|
||
throw new RangeError('hex string expected, got non-hex character "' + char + '" at index ' + hi);
|
||
}
|
||
array[ai] = n1 * 16 + n2;
|
||
}
|
||
return array;
|
||
}
|
||
function concatBytes(...arrays) {
|
||
let sum = 0;
|
||
for (let i = 0; i < arrays.length; i++) {
|
||
const a = arrays[i];
|
||
abytes(a);
|
||
sum += a.length;
|
||
}
|
||
const res = new Uint8Array(sum);
|
||
for (let i = 0, pad = 0; i < arrays.length; i++) {
|
||
const a = arrays[i];
|
||
res.set(a, pad);
|
||
pad += a.length;
|
||
}
|
||
return res;
|
||
}
|
||
function checkOpts(defaults, opts, title = "opts") {
|
||
aopts(defaults, "defaults");
|
||
if (opts !== void 0)
|
||
aopts(opts, title);
|
||
const merged = Object.assign(/* @__PURE__ */ Object.create(null), defaults, opts);
|
||
return merged;
|
||
}
|
||
function createHasher(hashCons, info = {}) {
|
||
if (typeof hashCons !== "function")
|
||
throw new TypeError('"hashCons" expected function, got type=' + typeof hashCons);
|
||
info = checkOpts({}, info, "info");
|
||
const hashC = (msg, opts) => hashCons(opts).update(msg).digest();
|
||
const tmp = hashCons(void 0);
|
||
hashC.outputLen = tmp.outputLen;
|
||
hashC.blockLen = tmp.blockLen;
|
||
hashC.canXOF = tmp.canXOF;
|
||
hashC.create = (opts) => hashCons(opts);
|
||
Object.assign(hashC, info);
|
||
return Object.freeze(hashC);
|
||
}
|
||
function randomBytes(bytesLength = 32) {
|
||
anumber(bytesLength, "bytesLength");
|
||
const cr = typeof globalThis === "object" ? globalThis.crypto : null;
|
||
if (typeof cr?.getRandomValues !== "function")
|
||
throw new Error("crypto.getRandomValues must be defined");
|
||
if (bytesLength > 65536)
|
||
throw new RangeError(`"bytesLength" expected <= 65536, got ${bytesLength}`);
|
||
return cr.getRandomValues(new Uint8Array(bytesLength));
|
||
}
|
||
var oidNist = (suffix) => ({
|
||
// Current NIST hashAlgs suffixes used here fit in one DER subidentifier octet.
|
||
// Larger suffix values would need base-128 OID encoding and a different length byte.
|
||
oid: Uint8Array.from([6, 9, 96, 134, 72, 1, 101, 3, 4, 2, suffix])
|
||
});
|
||
|
||
// node_modules/@noble/hashes/_md.js
|
||
function Chi(a, b, c) {
|
||
return a & b ^ ~a & c;
|
||
}
|
||
function Maj(a, b, c) {
|
||
return a & b ^ a & c ^ b & c;
|
||
}
|
||
var HashMD = class {
|
||
blockLen;
|
||
outputLen;
|
||
canXOF = false;
|
||
padOffset;
|
||
isLE;
|
||
// For partial updates less than block size
|
||
buffer;
|
||
view;
|
||
finished = false;
|
||
length = 0;
|
||
pos = 0;
|
||
destroyed = false;
|
||
constructor(blockLen, outputLen, padOffset, isLE) {
|
||
this.blockLen = blockLen;
|
||
this.outputLen = outputLen;
|
||
this.padOffset = padOffset;
|
||
this.isLE = isLE;
|
||
this.buffer = new Uint8Array(blockLen);
|
||
this.view = createView(this.buffer);
|
||
}
|
||
update(data) {
|
||
aexists(this);
|
||
abytes(data);
|
||
const { view, buffer, blockLen } = this;
|
||
const len = data.length;
|
||
let processed = false;
|
||
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);
|
||
processed = true;
|
||
continue;
|
||
}
|
||
buffer.set(pos === 0 && take === len ? data : data.subarray(pos, pos + take), this.pos);
|
||
this.pos += take;
|
||
pos += take;
|
||
if (this.pos === blockLen) {
|
||
this.process(view, 0);
|
||
this.pos = 0;
|
||
processed = true;
|
||
}
|
||
}
|
||
this.length += data.length;
|
||
if (processed)
|
||
this.roundClean();
|
||
return this;
|
||
}
|
||
digestInto(out) {
|
||
aexists(this);
|
||
aoutput(out, this);
|
||
this.finished = true;
|
||
const { buffer, view, blockLen, isLE } = this;
|
||
let { pos } = this;
|
||
buffer[pos++] = 128;
|
||
buffer.fill(0, pos);
|
||
if (this.padOffset > blockLen - pos) {
|
||
this.process(view, 0);
|
||
buffer.fill(0);
|
||
}
|
||
setU64FromNum(view, blockLen - 8, this.length * 8, isLE);
|
||
this.process(view, 0);
|
||
this.roundClean();
|
||
const oview = out === buffer ? view : createView(out);
|
||
const len = this.outputLen;
|
||
const outLen = len / 4;
|
||
const state = this.get();
|
||
if (len % 4 || outLen > state.length)
|
||
throw new Error("invalid outputLen");
|
||
for (let i = 0; i < outLen; i++)
|
||
oview.setUint32(4 * i, state[i], isLE);
|
||
}
|
||
digest() {
|
||
const { buffer, outputLen } = this;
|
||
this.digestInto(buffer);
|
||
const res = buffer.slice(0, outputLen);
|
||
this.destroy();
|
||
return res;
|
||
}
|
||
_cloneIntoMeta(to) {
|
||
const { buffer, length, finished, destroyed, pos } = this;
|
||
to.destroyed = destroyed;
|
||
to.finished = finished;
|
||
to.length = length;
|
||
to.pos = pos;
|
||
if (pos)
|
||
to.buffer.set(buffer);
|
||
return to;
|
||
}
|
||
clone() {
|
||
return this._cloneInto();
|
||
}
|
||
};
|
||
var SHA256_IV = /* @__PURE__ */ Uint32Array.from([
|
||
1779033703,
|
||
3144134277,
|
||
1013904242,
|
||
2773480762,
|
||
1359893119,
|
||
2600822924,
|
||
528734635,
|
||
1541459225
|
||
]);
|
||
var SHA512_IV = /* @__PURE__ */ Uint32Array.from([
|
||
1779033703,
|
||
4089235720,
|
||
3144134277,
|
||
2227873595,
|
||
1013904242,
|
||
4271175723,
|
||
2773480762,
|
||
1595750129,
|
||
1359893119,
|
||
2917565137,
|
||
2600822924,
|
||
725511199,
|
||
528734635,
|
||
4215389547,
|
||
1541459225,
|
||
327033209
|
||
]);
|
||
|
||
// node_modules/@noble/hashes/sha2.js
|
||
var SHA256_K = /* @__PURE__ */ Uint32Array.from([
|
||
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 SHA256_W = /* @__PURE__ */ new Uint32Array(64);
|
||
var SHA2_32B = class extends HashMD {
|
||
// We cannot use array here since array allows indexing by variable
|
||
// which means optimizer/compiler cannot use registers.
|
||
// Numeric initializers matter: starting the fields as `undefined` changes
|
||
// V8's field representation and makes sha256 3x slower (measured).
|
||
A = 0;
|
||
B = 0;
|
||
C = 0;
|
||
D = 0;
|
||
E = 0;
|
||
F = 0;
|
||
G = 0;
|
||
H = 0;
|
||
constructor(outputLen, IV) {
|
||
super(64, outputLen, 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;
|
||
}
|
||
_cloneInto(to) {
|
||
(to ||= new this.constructor()).set(...this.get());
|
||
return this._cloneIntoMeta(to);
|
||
}
|
||
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() {
|
||
clean(SHA256_W);
|
||
}
|
||
destroy() {
|
||
this.destroyed = true;
|
||
this.set(0, 0, 0, 0, 0, 0, 0, 0);
|
||
clean(this.buffer);
|
||
}
|
||
};
|
||
var _SHA256 = class extends SHA2_32B {
|
||
constructor() {
|
||
super(32, SHA256_IV);
|
||
}
|
||
};
|
||
var K512 = /* @__PURE__ */ (() => 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_Kh = /* @__PURE__ */ (() => K512[0])();
|
||
var SHA512_Kl = /* @__PURE__ */ (() => K512[1])();
|
||
var SHA512_W_H = /* @__PURE__ */ new Uint32Array(80);
|
||
var SHA512_W_L = /* @__PURE__ */ new Uint32Array(80);
|
||
var SHA2_64B = class extends HashMD {
|
||
// We cannot use array here since array allows indexing by variable
|
||
// which means optimizer/compiler cannot use registers.
|
||
// h -- high 32 bits, l -- low 32 bits
|
||
// Numeric initializers matter: starting the fields as `undefined` changes
|
||
// V8's field representation and slows hashing down (measured on sha256).
|
||
Ah = 0;
|
||
Al = 0;
|
||
Bh = 0;
|
||
Bl = 0;
|
||
Ch = 0;
|
||
Cl = 0;
|
||
Dh = 0;
|
||
Dl = 0;
|
||
Eh = 0;
|
||
El = 0;
|
||
Fh = 0;
|
||
Fl = 0;
|
||
Gh = 0;
|
||
Gl = 0;
|
||
Hh = 0;
|
||
Hl = 0;
|
||
constructor(outputLen, IV) {
|
||
super(128, outputLen, 16, false);
|
||
this.Ah = IV[0] | 0;
|
||
this.Al = IV[1] | 0;
|
||
this.Bh = IV[2] | 0;
|
||
this.Bl = IV[3] | 0;
|
||
this.Ch = IV[4] | 0;
|
||
this.Cl = IV[5] | 0;
|
||
this.Dh = IV[6] | 0;
|
||
this.Dl = IV[7] | 0;
|
||
this.Eh = IV[8] | 0;
|
||
this.El = IV[9] | 0;
|
||
this.Fh = IV[10] | 0;
|
||
this.Fl = IV[11] | 0;
|
||
this.Gh = IV[12] | 0;
|
||
this.Gl = IV[13] | 0;
|
||
this.Hh = IV[14] | 0;
|
||
this.Hl = IV[15] | 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;
|
||
}
|
||
_cloneInto(to) {
|
||
(to ||= new this.constructor()).set(...this.get());
|
||
return this._cloneIntoMeta(to);
|
||
}
|
||
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 = rotrSH(W15h, W15l, 1) ^ rotrSH(W15h, W15l, 8) ^ shrSH(W15h, W15l, 7);
|
||
const s0l = rotrSL(W15h, W15l, 1) ^ rotrSL(W15h, W15l, 8) ^ shrSL(W15h, W15l, 7);
|
||
const W2h = SHA512_W_H[i - 2] | 0;
|
||
const W2l = SHA512_W_L[i - 2] | 0;
|
||
const s1h = rotrSH(W2h, W2l, 19) ^ rotrBH(W2h, W2l, 61) ^ shrSH(W2h, W2l, 6);
|
||
const s1l = rotrSL(W2h, W2l, 19) ^ rotrBL(W2h, W2l, 61) ^ shrSL(W2h, W2l, 6);
|
||
const SUMl = add4L(s0l, s1l, SHA512_W_L[i - 7], SHA512_W_L[i - 16]);
|
||
const SUMh = 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 = rotrSH(Eh, El, 14) ^ rotrSH(Eh, El, 18) ^ rotrBH(Eh, El, 41);
|
||
const sigma1l = rotrSL(Eh, El, 14) ^ rotrSL(Eh, El, 18) ^ rotrBL(Eh, El, 41);
|
||
const CHIh = Eh & Fh ^ ~Eh & Gh;
|
||
const CHIl = El & Fl ^ ~El & Gl;
|
||
const T1ll = add5L(Hl, sigma1l, CHIl, SHA512_Kl[i], SHA512_W_L[i]);
|
||
const T1h = add5H(T1ll, Hh, sigma1h, CHIh, SHA512_Kh[i], SHA512_W_H[i]);
|
||
const T1l = T1ll | 0;
|
||
const sigma0h = rotrSH(Ah, Al, 28) ^ rotrBH(Ah, Al, 34) ^ rotrBH(Ah, Al, 39);
|
||
const sigma0l = rotrSL(Ah, Al, 28) ^ rotrBL(Ah, Al, 34) ^ 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 } = 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 = add3L(T1l, sigma0l, MAJl);
|
||
Ah = add3H(All, T1h, sigma0h, MAJh);
|
||
Al = All | 0;
|
||
}
|
||
({ h: Ah, l: Al } = add(this.Ah | 0, this.Al | 0, Ah | 0, Al | 0));
|
||
({ h: Bh, l: Bl } = add(this.Bh | 0, this.Bl | 0, Bh | 0, Bl | 0));
|
||
({ h: Ch, l: Cl } = add(this.Ch | 0, this.Cl | 0, Ch | 0, Cl | 0));
|
||
({ h: Dh, l: Dl } = add(this.Dh | 0, this.Dl | 0, Dh | 0, Dl | 0));
|
||
({ h: Eh, l: El } = add(this.Eh | 0, this.El | 0, Eh | 0, El | 0));
|
||
({ h: Fh, l: Fl } = add(this.Fh | 0, this.Fl | 0, Fh | 0, Fl | 0));
|
||
({ h: Gh, l: Gl } = add(this.Gh | 0, this.Gl | 0, Gh | 0, Gl | 0));
|
||
({ h: Hh, l: Hl } = 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() {
|
||
clean(SHA512_W_H, SHA512_W_L);
|
||
}
|
||
destroy() {
|
||
this.destroyed = true;
|
||
clean(this.buffer);
|
||
this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
|
||
}
|
||
};
|
||
var _SHA512 = class extends SHA2_64B {
|
||
constructor() {
|
||
super(64, SHA512_IV);
|
||
}
|
||
};
|
||
var sha256 = /* @__PURE__ */ createHasher(
|
||
() => new _SHA256(),
|
||
/* @__PURE__ */ oidNist(1)
|
||
);
|
||
var sha512 = /* @__PURE__ */ createHasher(
|
||
() => new _SHA512(),
|
||
/* @__PURE__ */ oidNist(3)
|
||
);
|
||
|
||
// node_modules/@noble/curves/utils.js
|
||
/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
|
||
function aarray(item, title, inner = () => {
|
||
}) {
|
||
if (!Array.isArray(item))
|
||
throw new TypeError(`"${title}" expected array, got type=${typeof item}`);
|
||
for (let i = 0; i < item.length; i++)
|
||
inner(item[i], `${title}[${i}]`);
|
||
return item;
|
||
}
|
||
var abytes2 = (value, length, title) => abytes(value, length, title);
|
||
var anumber2 = anumber;
|
||
function aobject2(value, title = "object") {
|
||
if (value === null || typeof value !== "object" || Array.isArray(value))
|
||
throw new TypeError(title === "object" ? "expected valid options object" : `"${title}" expected object, got type=${typeof value}`);
|
||
return value;
|
||
}
|
||
function afunction(value, title) {
|
||
if (typeof value !== "function")
|
||
throw new TypeError(`"${title}" is invalid: expected function, got ${typeof value}`);
|
||
return value;
|
||
}
|
||
var bytesToHex2 = bytesToHex;
|
||
var concatBytes2 = (...arrays) => concatBytes(...arrays);
|
||
var hexToBytes2 = (hex) => hexToBytes(hex);
|
||
var isBytes2 = isBytes;
|
||
var randomBytes2 = (bytesLength) => randomBytes(bytesLength);
|
||
var _0n = /* @__PURE__ */ BigInt(0);
|
||
var _1n = /* @__PURE__ */ BigInt(1);
|
||
var atitle2 = (title) => title ? `"${title}" ` : "";
|
||
function abool(value, title = "") {
|
||
if (typeof value !== "boolean")
|
||
throw new TypeError(atitle2(title) + "expected boolean, got type=" + typeof value);
|
||
return value;
|
||
}
|
||
function abignumber(n) {
|
||
if (typeof n === "bigint") {
|
||
if (!isPosBig(n))
|
||
throw new RangeError("positive bigint expected, got " + n);
|
||
} else
|
||
anumber2(n);
|
||
return n;
|
||
}
|
||
function asafenumber(value, title = "") {
|
||
if (typeof value !== "number") {
|
||
const prefix = title && `"${title}" `;
|
||
throw new TypeError(prefix + "expected number, got type=" + typeof value);
|
||
}
|
||
if (!Number.isSafeInteger(value)) {
|
||
const prefix = title && `"${title}" `;
|
||
throw new RangeError(prefix + "expected safe integer, got " + value);
|
||
}
|
||
}
|
||
function hexToNumber(hex) {
|
||
if (typeof hex !== "string")
|
||
throw new TypeError("hex string expected, got " + typeof hex);
|
||
return hex === "" ? _0n : BigInt("0x" + hex);
|
||
}
|
||
function bytesToNumberBE(bytes) {
|
||
return hexToNumber(bytesToHex(bytes));
|
||
}
|
||
function bytesToNumberLE(bytes) {
|
||
return hexToNumber(bytesToHex(copyBytes(abytes(bytes)).reverse()));
|
||
}
|
||
function numberToBytesBE(n, len) {
|
||
anumber(len);
|
||
if (len === 0)
|
||
throw new Error("zero output length is invalid");
|
||
n = abignumber(n);
|
||
const expectedLen = len * 2;
|
||
const hex = n.toString(16);
|
||
if (hex.length > expectedLen)
|
||
throw new RangeError("number is too large");
|
||
return hexToBytes(hex.padStart(expectedLen, "0"));
|
||
}
|
||
function numberToBytesLE(n, len) {
|
||
return numberToBytesBE(n, len).reverse();
|
||
}
|
||
function copyBytes(bytes) {
|
||
return Uint8Array.from(abytes2(bytes));
|
||
}
|
||
function isPosBig(n) {
|
||
return typeof n === "bigint" && _0n <= n;
|
||
}
|
||
function inRange(n, min, max) {
|
||
return isPosBig(n) && isPosBig(min) && isPosBig(max) && min <= n && n < max;
|
||
}
|
||
function aInRange(title, n, min, max) {
|
||
if (!inRange(n, min, max))
|
||
throw new RangeError("expected valid " + title + ": " + min + " <= n < " + max + ", got " + n);
|
||
}
|
||
function bitLen(n) {
|
||
if (n < _0n)
|
||
throw new Error("expected non-negative bigint, got " + n);
|
||
return n === _0n ? 0 : n.toString(2).length;
|
||
}
|
||
var bitMask = (n) => {
|
||
asafenumber(n, "n");
|
||
return (_1n << BigInt(n)) - _1n;
|
||
};
|
||
function validateObject(object, fields = {}, optFields = {}, title = "object") {
|
||
aobject2(object, title);
|
||
aobject2(fields, "fields");
|
||
aobject2(optFields, "optFields");
|
||
function checkField(fieldName, expectedType, isOpt) {
|
||
const label2 = title === "object" ? `param "${String(fieldName)}"` : `"${title}.${String(fieldName)}"`;
|
||
const val = object[fieldName];
|
||
if (!Object.hasOwn(object, fieldName) && (isOpt ? val !== void 0 : expectedType !== "function")) {
|
||
throw new TypeError(`${label2} is invalid: expected own property`);
|
||
}
|
||
if (isOpt && val === void 0)
|
||
return;
|
||
const current = typeof val;
|
||
if (current !== expectedType || val === null)
|
||
throw new TypeError(`${label2} is invalid: expected ${expectedType}, got ${current}`);
|
||
}
|
||
const iter = (f, isOpt) => Object.entries(f).forEach(([k, v]) => checkField(k, v, isOpt));
|
||
iter(fields, false);
|
||
iter(optFields, true);
|
||
}
|
||
|
||
// node_modules/@noble/curves/abstract/modular.js
|
||
/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
|
||
var _0n2 = /* @__PURE__ */ BigInt(0);
|
||
var _1n2 = /* @__PURE__ */ BigInt(1);
|
||
var _2n = /* @__PURE__ */ BigInt(2);
|
||
var _3n = /* @__PURE__ */ BigInt(3);
|
||
var _4n = /* @__PURE__ */ BigInt(4);
|
||
var _5n = /* @__PURE__ */ BigInt(5);
|
||
var _7n = /* @__PURE__ */ BigInt(7);
|
||
var _8n = /* @__PURE__ */ BigInt(8);
|
||
var _9n = /* @__PURE__ */ BigInt(9);
|
||
var _15n = /* @__PURE__ */ BigInt(15);
|
||
var _16n = /* @__PURE__ */ BigInt(16);
|
||
var POW_WINDOWED_MIN = /* @__PURE__ */ BigInt("0x10000000000000000");
|
||
function mod(a, b) {
|
||
if (b <= _0n2)
|
||
throw new Error("mod: expected positive modulus, got " + b);
|
||
const result = a % b;
|
||
return result >= _0n2 ? result : b + result;
|
||
}
|
||
function pow(num2, power, modulo) {
|
||
if (modulo <= _1n2)
|
||
throw new Error("pow: expected modulus > 1, got " + modulo);
|
||
if (typeof power !== "bigint")
|
||
throw new TypeError("invalid exponent: expected bigint, got " + typeof power);
|
||
if (power < _0n2)
|
||
throw new Error("invalid exponent, negatives unsupported");
|
||
if (power === _0n2)
|
||
return _1n2;
|
||
if (power === _1n2)
|
||
return num2;
|
||
let d = num2 % modulo;
|
||
if (d < _0n2)
|
||
d += modulo;
|
||
if (power < POW_WINDOWED_MIN) {
|
||
let p2 = _1n2;
|
||
while (power > _0n2) {
|
||
if (power & _1n2)
|
||
p2 = p2 * d % modulo;
|
||
d = d * d % modulo;
|
||
power >>= _1n2;
|
||
}
|
||
return p2;
|
||
}
|
||
const digits = [];
|
||
while (power > _0n2) {
|
||
digits.push(Number(power & _15n));
|
||
power >>= _4n;
|
||
}
|
||
const table = new Array(16);
|
||
table[0] = _1n2;
|
||
table[1] = d;
|
||
for (let i = 2; i < 16; i++)
|
||
table[i] = table[i - 1] * d % modulo;
|
||
let p = table[digits[digits.length - 1]];
|
||
for (let w = digits.length - 2; w >= 0; w--) {
|
||
p = p * p % modulo;
|
||
p = p * p % modulo;
|
||
p = p * p % modulo;
|
||
p = p * p % modulo;
|
||
const digit = digits[w];
|
||
if (digit !== 0)
|
||
p = p * table[digit] % modulo;
|
||
}
|
||
return p;
|
||
}
|
||
function pow2(x, power, modulo) {
|
||
if (modulo <= _1n2)
|
||
throw new Error("pow2: expected modulus > 1, got " + modulo);
|
||
if (power < _0n2)
|
||
throw new Error("pow2: expected non-negative exponent, got " + power);
|
||
let res = x;
|
||
while (power-- > _0n2) {
|
||
res *= res;
|
||
res %= modulo;
|
||
}
|
||
return res;
|
||
}
|
||
function invert(number, modulo) {
|
||
if (number === _0n2)
|
||
throw new Error("invert: expected non-zero number");
|
||
if (modulo <= _1n2)
|
||
throw new Error("invert: expected modulus > 1, got " + modulo);
|
||
let a = mod(number, modulo);
|
||
let b = modulo;
|
||
let x = _0n2, u = _1n2;
|
||
while (a !== _0n2) {
|
||
const q = b / a;
|
||
const r = b - a * q;
|
||
const m = x - u * q;
|
||
b = a, a = r, x = u, u = m;
|
||
}
|
||
const gcd = b;
|
||
if (gcd !== _1n2)
|
||
throw new Error("invert: does not exist");
|
||
return mod(x, modulo);
|
||
}
|
||
function assertIsSquare(Fp2, root, n) {
|
||
const F = Fp2;
|
||
if (!F.eql(F.sqr(root), n))
|
||
throw new Error("Cannot find square root");
|
||
}
|
||
function aoddModulus(order, fnName) {
|
||
if ((order & _1n2) === _0n2)
|
||
throw new Error(fnName + ": expected odd modulus, got " + order);
|
||
}
|
||
function sqrt3mod4(Fp2, n) {
|
||
const F = Fp2;
|
||
const p1div4 = (F.ORDER + _1n2) / _4n;
|
||
const root = F.pow(n, p1div4);
|
||
assertIsSquare(F, root, n);
|
||
return root;
|
||
}
|
||
function sqrt5mod8(Fp2, n) {
|
||
const F = Fp2;
|
||
const p5div8 = (F.ORDER - _5n) / _8n;
|
||
const n2 = F.mul(n, _2n);
|
||
const v = F.pow(n2, p5div8);
|
||
const nv = F.mul(n, v);
|
||
const i = F.mul(F.mul(nv, _2n), v);
|
||
const root = F.mul(nv, F.sub(i, F.ONE));
|
||
assertIsSquare(F, root, n);
|
||
return root;
|
||
}
|
||
function sqrt9mod16(P) {
|
||
const Fp_ = Field(P);
|
||
const tn = tonelliShanks(P);
|
||
const c1 = tn(Fp_, Fp_.neg(Fp_.ONE));
|
||
const c2 = tn(Fp_, c1);
|
||
const c3 = tn(Fp_, Fp_.neg(c1));
|
||
const c4 = (P + _7n) / _16n;
|
||
return ((Fp2, n) => {
|
||
const F = Fp2;
|
||
let tv1 = F.pow(n, c4);
|
||
let tv2 = F.mul(tv1, c1);
|
||
const tv3 = F.mul(tv1, c2);
|
||
const tv4 = F.mul(tv1, c3);
|
||
const e1 = F.eql(F.sqr(tv2), n);
|
||
const e2 = F.eql(F.sqr(tv3), n);
|
||
tv1 = F.cmov(tv1, tv2, e1);
|
||
tv2 = F.cmov(tv4, tv3, e2);
|
||
const e3 = F.eql(F.sqr(tv2), n);
|
||
const root = F.cmov(tv1, tv2, e3);
|
||
assertIsSquare(F, root, n);
|
||
return root;
|
||
});
|
||
}
|
||
function tonelliShanks(P) {
|
||
if (P < _3n)
|
||
throw new Error("sqrt is not defined for small field");
|
||
aoddModulus(P, "tonelliShanks");
|
||
let Q = P - _1n2;
|
||
let S = 0;
|
||
while (Q % _2n === _0n2) {
|
||
Q /= _2n;
|
||
S++;
|
||
}
|
||
let Z = _2n;
|
||
const _Fp = Field(P);
|
||
while (FpLegendre(_Fp, Z) === 1) {
|
||
if (Z++ > 1e3)
|
||
throw new Error("Cannot find square root: probably non-prime P");
|
||
}
|
||
if (S === 1)
|
||
return sqrt3mod4;
|
||
let cc = _Fp.pow(Z, Q);
|
||
const Q1div2 = (Q + _1n2) / _2n;
|
||
return function tonelliSlow(Fp2, n) {
|
||
const F = Fp2;
|
||
if (F.is0(n))
|
||
return n;
|
||
if (FpLegendre(F, n) !== 1)
|
||
throw new Error("Cannot find square root");
|
||
let M = S;
|
||
let c = F.mul(F.ONE, cc);
|
||
let t2 = F.pow(n, Q);
|
||
let R = F.pow(n, Q1div2);
|
||
while (!F.eql(t2, F.ONE)) {
|
||
if (F.is0(t2))
|
||
throw new Error("Cannot find square root: probably non-prime P");
|
||
let i = 1;
|
||
let t_tmp = F.sqr(t2);
|
||
while (!F.eql(t_tmp, F.ONE)) {
|
||
i++;
|
||
t_tmp = F.sqr(t_tmp);
|
||
if (i === M)
|
||
throw new Error("Cannot find square root");
|
||
}
|
||
const exponent = _1n2 << BigInt(M - i - 1);
|
||
const b = F.pow(c, exponent);
|
||
M = i;
|
||
c = F.sqr(b);
|
||
t2 = F.mul(t2, c);
|
||
R = F.mul(R, b);
|
||
}
|
||
return R;
|
||
};
|
||
}
|
||
function FpSqrt(P) {
|
||
aoddModulus(P, "Fp.sqrt");
|
||
if (P % _4n === _3n)
|
||
return sqrt3mod4;
|
||
if (P % _8n === _5n)
|
||
return sqrt5mod8;
|
||
if (P % _16n === _9n)
|
||
return sqrt9mod16(P);
|
||
return tonelliShanks(P);
|
||
}
|
||
var isNegativeLE = (num2, modulo) => (mod(num2, modulo) & _1n2) === _1n2;
|
||
var FIELD_FIELDS = [
|
||
"create",
|
||
"isValid",
|
||
"is0",
|
||
"neg",
|
||
"inv",
|
||
"sqrt",
|
||
"sqr",
|
||
"eql",
|
||
"add",
|
||
"sub",
|
||
"mul",
|
||
"pow",
|
||
"div",
|
||
"addN",
|
||
"subN",
|
||
"mulN",
|
||
"sqrN"
|
||
];
|
||
function validateField(field2) {
|
||
aobject2(field2, "field");
|
||
if (typeof field2.ORDER !== "bigint")
|
||
throw new TypeError('param "ORDER" is invalid: expected bigint, got ' + typeof field2.ORDER);
|
||
asafenumber(field2.BYTES, "BYTES");
|
||
asafenumber(field2.BITS, "BITS");
|
||
for (const name of FIELD_FIELDS)
|
||
afunction(field2[name], "field." + name);
|
||
if (field2.BYTES < 1 || field2.BITS < 1)
|
||
throw new Error("invalid field: expected BYTES/BITS > 0");
|
||
if (field2.ORDER <= _1n2)
|
||
throw new Error("invalid field: expected ORDER > 1, got " + field2.ORDER);
|
||
return field2;
|
||
}
|
||
function FpInvertBatch(Fp2, nums, passZero = false) {
|
||
validateField(Fp2);
|
||
aarray(nums, "nums");
|
||
abool(passZero, "passZero");
|
||
const F = Fp2;
|
||
const inverted = new Array(nums.length).fill(passZero ? F.ZERO : void 0);
|
||
const multipliedAcc = nums.reduce((acc, num2, i) => {
|
||
if (F.is0(num2))
|
||
return acc;
|
||
inverted[i] = acc;
|
||
return F.mul(acc, num2);
|
||
}, F.ONE);
|
||
const invertedAcc = F.inv(multipliedAcc);
|
||
nums.reduceRight((acc, num2, i) => {
|
||
if (F.is0(num2))
|
||
return acc;
|
||
inverted[i] = F.mul(acc, inverted[i]);
|
||
return F.mul(acc, num2);
|
||
}, invertedAcc);
|
||
return inverted;
|
||
}
|
||
function FpLegendre(Fp2, n) {
|
||
validateField(Fp2);
|
||
const F = Fp2;
|
||
aoddModulus(F.ORDER, "FpLegendre");
|
||
const p1mod2 = (F.ORDER - _1n2) / _2n;
|
||
const powered = F.pow(n, p1mod2);
|
||
const yes = F.eql(powered, F.ONE);
|
||
const zero = F.eql(powered, F.ZERO);
|
||
const no = F.eql(powered, F.neg(F.ONE));
|
||
if (!yes && !zero && !no)
|
||
throw new Error("invalid Legendre symbol result");
|
||
return yes ? 1 : zero ? 0 : -1;
|
||
}
|
||
function nLength(n, nBitLength) {
|
||
if (nBitLength !== void 0)
|
||
anumber2(nBitLength);
|
||
if (n <= _0n2)
|
||
throw new Error("invalid n length: expected positive n, got " + n);
|
||
if (nBitLength !== void 0 && nBitLength < 1)
|
||
throw new Error("invalid n length: expected positive bit length, got " + nBitLength);
|
||
const bits = bitLen(n);
|
||
if (nBitLength !== void 0 && nBitLength < bits)
|
||
throw new Error(`invalid n length: expected nBitLength (${nBitLength}) >= bitLen(n) (${bits})`);
|
||
const _nBitLength = nBitLength !== void 0 ? nBitLength : bits;
|
||
const nByteLength = Math.ceil(_nBitLength / 8);
|
||
return { nBitLength: _nBitLength, nByteLength };
|
||
}
|
||
var FIELD_SQRT = /* @__PURE__ */ new WeakMap();
|
||
var _Field = class {
|
||
ORDER;
|
||
BITS;
|
||
BYTES;
|
||
isLE;
|
||
ZERO = _0n2;
|
||
ONE = _1n2;
|
||
_lengths;
|
||
_mod;
|
||
constructor(ORDER, opts = {}) {
|
||
if (ORDER <= _1n2)
|
||
throw new Error("invalid field: expected ORDER > 1, got " + ORDER);
|
||
let _nbitLength = void 0;
|
||
this.isLE = false;
|
||
if (opts != null && typeof opts === "object") {
|
||
if (typeof opts.BITS === "number")
|
||
_nbitLength = opts.BITS;
|
||
if (typeof opts.sqrt === "function")
|
||
Object.defineProperty(this, "sqrt", { value: opts.sqrt, enumerable: true });
|
||
if (typeof opts.isLE === "boolean")
|
||
this.isLE = opts.isLE;
|
||
if (opts.allowedLengths)
|
||
this._lengths = Object.freeze(opts.allowedLengths.slice());
|
||
if (typeof opts.modFromBytes === "boolean")
|
||
this._mod = opts.modFromBytes;
|
||
}
|
||
const { nBitLength, nByteLength } = nLength(ORDER, _nbitLength);
|
||
if (nByteLength > 2048)
|
||
throw new Error("invalid field: expected ORDER of <= 2048 bytes");
|
||
this.ORDER = ORDER;
|
||
this.BITS = nBitLength;
|
||
this.BYTES = nByteLength;
|
||
Object.freeze(this);
|
||
}
|
||
create(num2) {
|
||
return mod(num2, this.ORDER);
|
||
}
|
||
isValid(num2) {
|
||
if (typeof num2 !== "bigint")
|
||
throw new TypeError("invalid field element: expected bigint, got " + typeof num2);
|
||
return _0n2 <= num2 && num2 < this.ORDER;
|
||
}
|
||
is0(num2) {
|
||
return num2 === _0n2;
|
||
}
|
||
// is valid and invertible
|
||
isValidNot0(num2) {
|
||
return !this.is0(num2) && this.isValid(num2);
|
||
}
|
||
isOdd(num2) {
|
||
return (num2 & _1n2) === _1n2;
|
||
}
|
||
neg(num2) {
|
||
return mod(-num2, this.ORDER);
|
||
}
|
||
eql(lhs, rhs) {
|
||
return lhs === rhs;
|
||
}
|
||
sqr(num2) {
|
||
return mod(num2 * num2, this.ORDER);
|
||
}
|
||
add(lhs, rhs) {
|
||
return mod(lhs + rhs, this.ORDER);
|
||
}
|
||
sub(lhs, rhs) {
|
||
return mod(lhs - rhs, this.ORDER);
|
||
}
|
||
mul(lhs, rhs) {
|
||
return mod(lhs * rhs, this.ORDER);
|
||
}
|
||
pow(num2, power) {
|
||
return pow(num2, power, this.ORDER);
|
||
}
|
||
div(lhs, rhs) {
|
||
return mod(lhs * invert(rhs, this.ORDER), this.ORDER);
|
||
}
|
||
// Same as above, but doesn't normalize
|
||
sqrN(num2) {
|
||
return num2 * num2;
|
||
}
|
||
addN(lhs, rhs) {
|
||
return lhs + rhs;
|
||
}
|
||
subN(lhs, rhs) {
|
||
return lhs - rhs;
|
||
}
|
||
mulN(lhs, rhs) {
|
||
return lhs * rhs;
|
||
}
|
||
inv(num2) {
|
||
return invert(num2, this.ORDER);
|
||
}
|
||
sqrt(num2) {
|
||
let sqrt = FIELD_SQRT.get(this);
|
||
if (!sqrt)
|
||
FIELD_SQRT.set(this, sqrt = FpSqrt(this.ORDER));
|
||
return sqrt(this, num2);
|
||
}
|
||
toBytes(num2) {
|
||
return this.isLE ? numberToBytesLE(num2, this.BYTES) : numberToBytesBE(num2, this.BYTES);
|
||
}
|
||
fromBytes(bytes, skipValidation = false) {
|
||
abytes2(bytes);
|
||
const { _lengths: allowedLengths, BYTES, isLE, ORDER, _mod: modFromBytes } = this;
|
||
if (allowedLengths) {
|
||
if (bytes.length < 1 || !allowedLengths.includes(bytes.length) || bytes.length > BYTES) {
|
||
throw new Error("Field.fromBytes: expected " + allowedLengths + " bytes, got " + bytes.length);
|
||
}
|
||
const padded = new Uint8Array(BYTES);
|
||
padded.set(bytes, isLE ? 0 : padded.length - bytes.length);
|
||
bytes = padded;
|
||
}
|
||
if (bytes.length !== BYTES)
|
||
throw new Error("Field.fromBytes: expected " + BYTES + " bytes, got " + bytes.length);
|
||
let scalar = isLE ? bytesToNumberLE(bytes) : bytesToNumberBE(bytes);
|
||
if (modFromBytes)
|
||
scalar = mod(scalar, ORDER);
|
||
if (!skipValidation) {
|
||
if (!this.isValid(scalar))
|
||
throw new Error("invalid field element: outside of range 0..ORDER");
|
||
}
|
||
return scalar;
|
||
}
|
||
// TODO: we don't need it here, move out to separate fn
|
||
invertBatch(lst) {
|
||
return FpInvertBatch(this, lst, true);
|
||
}
|
||
// We can't move this out because Fp6, Fp12 implement it
|
||
// and it's unclear what to return in there.
|
||
cmov(a, b, condition) {
|
||
abool(condition, "condition");
|
||
return condition ? b : a;
|
||
}
|
||
};
|
||
function Field(ORDER, opts = {}) {
|
||
Object.freeze(_Field.prototype);
|
||
return new _Field(ORDER, opts);
|
||
}
|
||
|
||
// node_modules/@noble/curves/abstract/curve.js
|
||
/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
|
||
var _0n3 = /* @__PURE__ */ BigInt(0);
|
||
var _1n3 = /* @__PURE__ */ BigInt(1);
|
||
var _4n2 = /* @__PURE__ */ BigInt(4);
|
||
var BLIND_BYTES = 16;
|
||
var BLIND_BITS = 128;
|
||
var FW_WINDOW = 5;
|
||
var TABLE_BYTES_MAX = /* @__PURE__ */ (() => 2 ** 31)();
|
||
function validatePointCons(Point) {
|
||
const pc = Point;
|
||
if (typeof pc !== "function")
|
||
throw new TypeError('"Point" expected constructor, got type=' + typeof Point);
|
||
afunction(pc.fromAffine, "Point.fromAffine");
|
||
afunction(pc.fromBytes, "Point.fromBytes");
|
||
afunction(pc.fromHex, "Point.fromHex");
|
||
aobject2(pc.BASE, "Point.BASE");
|
||
aobject2(pc.ZERO, "Point.ZERO");
|
||
validateField(pc.Fp);
|
||
validateField(pc.Fn);
|
||
}
|
||
function normalizeZ(c, points) {
|
||
validatePointCons(c);
|
||
validateMSMPoints(points, c);
|
||
const invertedZs = FpInvertBatch(c.Fp, points.map((p) => p.Z));
|
||
return points.map((p, i) => c.fromAffine(p.toAffine(invertedZs[i])));
|
||
}
|
||
function validateW(W, bits, min = 1) {
|
||
if (!Number.isSafeInteger(W) || W < min || W > bits)
|
||
throw new Error("invalid window size, expected [" + min + ".." + bits + "], got W=" + W);
|
||
}
|
||
function validateTableBytes(numPoints, fpBytes) {
|
||
const bytes = numPoints * (4 * fpBytes + 128);
|
||
if (bytes > TABLE_BYTES_MAX)
|
||
throw new Error("invalid window size: table would need ~" + Math.ceil(bytes / 2 ** 20) + " MiB, max " + TABLE_BYTES_MAX / 2 ** 20 + " MiB");
|
||
}
|
||
function probeRandomBytes(randomBytes3, length) {
|
||
if (randomBytes3 === void 0)
|
||
return void 0;
|
||
afunction(randomBytes3, "randomBytes");
|
||
try {
|
||
const probe = randomBytes3(length);
|
||
if (!isBytes2(probe) || probe.length !== length)
|
||
return void 0;
|
||
} catch {
|
||
return void 0;
|
||
}
|
||
return randomBytes3;
|
||
}
|
||
function validateMSMPoints(points, c) {
|
||
aarray(points, "points");
|
||
points.forEach((p, i) => {
|
||
if (!(p instanceof c))
|
||
throw new Error("invalid point at index " + i);
|
||
});
|
||
}
|
||
function validateMSMScalars(scalars, field2, maxScalar) {
|
||
if (!Array.isArray(scalars))
|
||
throw new Error("array of scalars expected");
|
||
scalars.forEach((s, i) => {
|
||
const ok = maxScalar === void 0 ? field2.isValid(s) : isPosBig(s) && s < maxScalar;
|
||
if (!ok)
|
||
throw new Error("invalid scalar at index " + i);
|
||
});
|
||
}
|
||
var pointWindowSizes = /* @__PURE__ */ new WeakMap();
|
||
function getWindowSize(P) {
|
||
return pointWindowSizes.get(P) || 1;
|
||
}
|
||
function oddMultiples(p, size) {
|
||
const dbl = p.double();
|
||
const t2 = [p];
|
||
for (let j = 1; j < size; j++)
|
||
t2.push(t2[j - 1].add(dbl));
|
||
return t2;
|
||
}
|
||
function wnafDigits(n, W) {
|
||
const size = 2 ** W;
|
||
const half = size / 2;
|
||
const mask = BigInt(size - 1);
|
||
const d = [];
|
||
while (n > _0n3) {
|
||
let w = 0;
|
||
if (n & _1n3) {
|
||
w = Number(n & mask);
|
||
if (w >= half)
|
||
w -= size;
|
||
n -= BigInt(w);
|
||
}
|
||
d.push(w);
|
||
n >>= _1n3;
|
||
}
|
||
return d;
|
||
}
|
||
function signedWindowDigits(n, W, windows) {
|
||
const size = 2 ** W;
|
||
const half = size / 2;
|
||
const mask = BigInt(size - 1);
|
||
const shiftBy = BigInt(W);
|
||
const d = [];
|
||
for (let w = 0; w < windows; w++) {
|
||
let v = Number(n & mask);
|
||
n >>= shiftBy;
|
||
if (v > half) {
|
||
v -= size;
|
||
n += _1n3;
|
||
}
|
||
d.push(v);
|
||
}
|
||
if (n !== _0n3)
|
||
throw new Error("invalid wnaf");
|
||
return d;
|
||
}
|
||
function wnafWalk(zero, tables, digits) {
|
||
let max = 0;
|
||
for (const d of digits)
|
||
max = Math.max(max, d.length);
|
||
let acc = zero;
|
||
for (let bit = max - 1; bit >= 0; bit--) {
|
||
if (bit !== max - 1)
|
||
acc = acc.double();
|
||
for (let i = 0; i < digits.length; i++) {
|
||
const w = digits[i][bit];
|
||
if (w) {
|
||
const item = tables[i][Math.abs(w) - 1 >> 1];
|
||
acc = acc.add(w < 0 ? item.negate() : item);
|
||
}
|
||
}
|
||
}
|
||
return acc;
|
||
}
|
||
var ScalarMultiplier = class {
|
||
Point;
|
||
BASE;
|
||
ZERO;
|
||
randomBytes;
|
||
wnafPrecomputes = /* @__PURE__ */ new WeakMap();
|
||
baseCanBeBlinded;
|
||
bits;
|
||
// Parametrized with a given Point class (not individual point)
|
||
constructor(Point, randomBytes3) {
|
||
validatePointCons(Point);
|
||
this.randomBytes = probeRandomBytes(randomBytes3, BLIND_BYTES);
|
||
this.Point = Point;
|
||
this.BASE = Point.BASE;
|
||
this.ZERO = Point.ZERO;
|
||
this.bits = Point.Fn.BITS;
|
||
}
|
||
/**
|
||
* Creates a signed fixed-window wNAF precomputation table: for every window w, the
|
||
* multiples `[1..2^(W−1)]⋅2^(w⋅W)⋅P`, flattened. All doublings are baked into the table,
|
||
* so cached multiplication is additions-only. `windows = ceil(bits/W) + 1`: the extra
|
||
* window absorbs the final carry of signed-digit recoding.
|
||
* For a 256-bit curve and W=6, the table is 44⋅32 = 1408 points.
|
||
* @param point - Point instance
|
||
* @param W - window size
|
||
* @param bits - scalar bitlength the table must cover
|
||
*/
|
||
buildWnafTable(point, W, bits) {
|
||
const windows = Math.ceil(bits / W) + 1;
|
||
const half = 2 ** (W - 1);
|
||
const comp = [];
|
||
let base = point;
|
||
for (let w = 0; w < windows; w++) {
|
||
let acc = base;
|
||
for (let i = 0; i < half; i++) {
|
||
comp.push(acc);
|
||
acc = acc.add(base);
|
||
}
|
||
base = comp[comp.length - 1].double();
|
||
}
|
||
return { W, bits, windows, comp };
|
||
}
|
||
/**
|
||
* Implements ec multiplication using precomputed signed fixed-window wNAF tables.
|
||
* Constant-time: fixed window count with one table addition per window — zero digits feed
|
||
* the fake accumulator — and no doublings; the lookup scans the whole window slice.
|
||
* Scalar bounds are validated by the public entry points ({@link ScalarMultiplier.mulCT},
|
||
* {@link ScalarMultiplier.mulCTBlinded}, {@link ScalarMultiplier.mulUnsafe});
|
||
* signedWindowDigits throws if `n` exceeds the table.
|
||
* @returns real and fake (for const-time) points
|
||
*/
|
||
wnafCachedCT(precomputes, n) {
|
||
const { W, windows, comp } = precomputes;
|
||
const half = 2 ** (W - 1);
|
||
const digits = signedWindowDigits(n, W, windows);
|
||
let p = this.ZERO;
|
||
let f = this.BASE;
|
||
for (let w = 0; w < windows; w++) {
|
||
const digit = digits[w];
|
||
const start = w * half;
|
||
const idx = Math.abs(digit) - 1;
|
||
let sel = comp[start];
|
||
for (let i = 1; i < half; i++)
|
||
sel = i === idx ? comp[start + i] : sel;
|
||
const neg = sel.negate();
|
||
if (digit === 0)
|
||
f = f.add(comp[start]);
|
||
else
|
||
p = p.add(digit < 0 ? neg : sel);
|
||
}
|
||
return { p, f };
|
||
}
|
||
// Cache key is point identity plus (W, bits); at most two entries exist per point (public-width
|
||
// `Fn.BITS` and blinded `Fn.BITS + BLIND_BITS`). Callers must not reuse the same point with
|
||
// incompatible `transform(...)` layouts and expect a separate cache entry.
|
||
getWnafPrecomputes(W, point, bits, transform) {
|
||
let entries = this.wnafPrecomputes.get(point);
|
||
let comp = entries?.find((entry) => entry.W === W && entry.bits === bits);
|
||
if (!comp) {
|
||
comp = this.buildWnafTable(point, W, bits);
|
||
if (typeof transform === "function")
|
||
comp = { ...comp, comp: transform(comp.comp) };
|
||
if (!entries) {
|
||
entries = [];
|
||
this.wnafPrecomputes.set(point, entries);
|
||
}
|
||
entries.push(comp);
|
||
}
|
||
return comp;
|
||
}
|
||
assertPoint(point) {
|
||
if (!(point instanceof this.Point))
|
||
throw new TypeError('"point" expected Point instance, got type=' + typeof point);
|
||
}
|
||
// Shared prologue of the constant-time entry points. Rejects scalar 0: in key/signature-style
|
||
// callers a zero scalar means broken upstream plumbing, and concrete Points already reject it.
|
||
// Uses inRange instead of Fn.isValidNot0: validateField() only certifies the arithmetic subset.
|
||
validateMulInput(point, scalar) {
|
||
this.assertPoint(point);
|
||
if (!inRange(scalar, _1n3, this.Point.Fn.ORDER))
|
||
throw new Error("invalid scalar");
|
||
}
|
||
// Constant-time dispatch shared by mulCT / mulCTBlinded. Un-precomputed points (W===1, e.g.
|
||
// ECDH peer keys) skip building a throwaway cached table in favor of a small fixed-window
|
||
// multiply. `n` must be < 2^bits.
|
||
runCT(point, n, bits, transform) {
|
||
const W = getWindowSize(point);
|
||
if (W === 1)
|
||
return this.fixedWindowCT(point, n, bits);
|
||
return this.wnafCachedCT(this.getWnafPrecomputes(W, point, bits, transform), n);
|
||
}
|
||
mulCT(point, scalar, transform) {
|
||
this.validateMulInput(point, scalar);
|
||
return this.runCT(point, scalar, this.bits, transform);
|
||
}
|
||
mulCTBlinded(point, scalar, transform) {
|
||
this.validateMulInput(point, scalar);
|
||
if (this.randomBytes === void 0)
|
||
throw new Error("randomBytes is required for scalar blinding");
|
||
const bits = this.Point.Fn.BITS + BLIND_BITS;
|
||
const blind = this.randomBytes(BLIND_BYTES);
|
||
if (!isBytes2(blind) || blind.length !== BLIND_BYTES)
|
||
throw new Error("randomBytes returned invalid byte array");
|
||
blind[0] = blind[0] & 63 | 128;
|
||
const n = scalar + bytesToNumberBE(blind) * this.Point.Fn.ORDER;
|
||
return this.runCT(point, n, bits, transform);
|
||
}
|
||
/**
|
||
* Constant-time multiplication `n*point` for an un-precomputed point, via a small fixed window.
|
||
* A cached wNAF table only pays off when reused; a flat 2^FW_WINDOW table (`size-1` adds) is
|
||
* far cheaper to build for a single use. The point-operation sequence is independent of `n`:
|
||
* build the table, then per window exactly FW_WINDOW doublings, a data-oblivious scan over
|
||
* every table entry, and one addition (adds the identity when the window digit is 0 — never
|
||
* skipped).
|
||
*
|
||
* `n` must be `< 2^bits`. Assumes complete addition (adding the identity costs the same as any
|
||
* add), which holds for the Weierstrass/Edwards point types used here. The table is left in
|
||
* projective form (no normalizeZ): normalizing this small a table costs more than the
|
||
* mixed-add savings it would buy for a single multiply.
|
||
* @returns real point `p`; `f` duplicates it only to match {@link wnafCachedCT}'s return shape
|
||
* (this path needs no fake accumulator — its op-count is already scalar-independent).
|
||
*/
|
||
fixedWindowCT(point, n, bits) {
|
||
const W = FW_WINDOW;
|
||
const size = 1 << W;
|
||
const mask = bitMask(W);
|
||
const table = new Array(size);
|
||
table[0] = this.ZERO;
|
||
for (let i = 1; i < size; i++)
|
||
table[i] = table[i - 1].add(point);
|
||
const windows = Math.ceil(bits / W);
|
||
let acc = this.ZERO;
|
||
for (let window2 = windows - 1; window2 >= 0; window2--) {
|
||
if (window2 !== windows - 1)
|
||
for (let d = 0; d < W; d++)
|
||
acc = acc.double();
|
||
const digit = Number(n >> BigInt(window2 * W) & mask);
|
||
let sel = table[0];
|
||
for (let i = 1; i < size; i++)
|
||
sel = i === digit ? table[i] : sel;
|
||
acc = acc.add(sel);
|
||
}
|
||
return { p: acc, f: acc };
|
||
}
|
||
shouldBlind(point, cofactor) {
|
||
if (this.randomBytes === void 0)
|
||
return false;
|
||
if (cofactor === _1n3)
|
||
return true;
|
||
if (point !== this.BASE)
|
||
return false;
|
||
if (this.baseCanBeBlinded === void 0)
|
||
this.baseCanBeBlinded = this.mulUnsafe(this.BASE, this.Point.Fn.ORDER).is0();
|
||
return this.baseCanBeBlinded;
|
||
}
|
||
mulSecret(point, scalar, cofactor, transform) {
|
||
return this.shouldBlind(point, cofactor) ? this.mulCTBlinded(point, scalar, transform) : this.mulCT(point, scalar, transform);
|
||
}
|
||
mulUnsafe(point, scalar, transform) {
|
||
this.assertPoint(point);
|
||
if (!isPosBig(scalar))
|
||
throw new Error("invalid scalar");
|
||
const W = getWindowSize(point);
|
||
if (W === 1 || scalar >= this.Point.Fn.ORDER)
|
||
return mulAddUnsafe(this.Point, [point], [scalar], true);
|
||
const precomputes = this.getWnafPrecomputes(W, point, this.bits, transform);
|
||
return this.wnafCachedCT(precomputes, scalar).p;
|
||
}
|
||
// Remembers the window size used for precomputed wNAF multiplication of the given point
|
||
// and drops any previously built tables. Usually only the base point is precomputed.
|
||
// W=1 resets the point to the un-precomputed (table-less) paths.
|
||
// W is additionally capped so tables stay under ~2 GiB ({@link TABLE_BYTES_MAX}).
|
||
setWindowSize(point, W) {
|
||
this.assertPoint(point);
|
||
validateW(W, this.bits);
|
||
const windows = Math.ceil((this.bits + BLIND_BITS) / W) + 1;
|
||
validateTableBytes(windows * 2 ** (W - 1), this.Point.Fp.BYTES);
|
||
pointWindowSizes.set(point, W);
|
||
this.wnafPrecomputes.delete(point);
|
||
}
|
||
// True when a window size is set: tables themselves are built lazily on first multiply.
|
||
hasWindowSize(point) {
|
||
return getWindowSize(point) !== 1;
|
||
}
|
||
};
|
||
function mulAddUnsafe(c, points, scalars, allowOversized = false) {
|
||
validatePointCons(c);
|
||
validateMSMPoints(points, c);
|
||
abool(allowOversized, "allowOversized");
|
||
validateMSMScalars(scalars, c.Fn, allowOversized ? c.Fn.ORDER ** _4n2 : void 0);
|
||
if (points.length !== scalars.length)
|
||
throw new Error("arrays of points and scalars must have equal length");
|
||
const tables = points.map((p) => oddMultiples(p, 4));
|
||
const digits = scalars.map((n) => wnafDigits(n, 4));
|
||
return wnafWalk(c.ZERO, tables, digits);
|
||
}
|
||
function createField(order, field2, isLE) {
|
||
if (field2) {
|
||
if (field2.ORDER !== order)
|
||
throw new Error("Field.ORDER must match order: Fp == p, Fn == n");
|
||
validateField(field2);
|
||
return field2;
|
||
} else {
|
||
return Field(order, { isLE });
|
||
}
|
||
}
|
||
function createCurveFields(type, CURVE, curveOpts = {}, FpFnLE) {
|
||
if (type !== "weierstrass" && type !== "edwards")
|
||
throw new Error('expected curve type "weierstrass" or "edwards"');
|
||
if (FpFnLE === void 0)
|
||
FpFnLE = type === "edwards";
|
||
if (!CURVE || typeof CURVE !== "object")
|
||
throw new Error(`expected valid ${type} CURVE object`);
|
||
validateObject(curveOpts);
|
||
for (const p of ["p", "n", "h"]) {
|
||
const val = CURVE[p];
|
||
if (!(isPosBig(val) && val !== _0n3))
|
||
throw new Error(`CURVE.${p} must be positive bigint`);
|
||
}
|
||
const Fp2 = createField(CURVE.p, curveOpts.Fp, FpFnLE);
|
||
const Fn = createField(CURVE.n, curveOpts.Fn, FpFnLE);
|
||
const _b = type === "weierstrass" ? "b" : "d";
|
||
const params = ["Gx", "Gy", "a", _b];
|
||
for (const p of params) {
|
||
if (!Fp2.isValid(CURVE[p]))
|
||
throw new Error(`CURVE.${p} must be valid field element of CURVE.Fp`);
|
||
}
|
||
CURVE = Object.freeze(Object.assign({}, CURVE));
|
||
return { CURVE, Fp: Fp2, Fn };
|
||
}
|
||
function createKeygen(randomSecretKey, getPublicKey) {
|
||
return function keygen(seed) {
|
||
const secretKey = randomSecretKey(seed);
|
||
return { secretKey, publicKey: getPublicKey(secretKey) };
|
||
};
|
||
}
|
||
|
||
// node_modules/@noble/curves/abstract/edwards.js
|
||
/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
|
||
var _0n4 = /* @__PURE__ */ BigInt(0);
|
||
var _1n4 = /* @__PURE__ */ BigInt(1);
|
||
var _2n2 = /* @__PURE__ */ BigInt(2);
|
||
var _4n3 = /* @__PURE__ */ BigInt(4);
|
||
var _8n2 = /* @__PURE__ */ BigInt(8);
|
||
function isEdValidXY(Fp2, CURVE, x, y) {
|
||
const x2 = Fp2.sqr(x);
|
||
const y2 = Fp2.sqr(y);
|
||
const left = Fp2.add(Fp2.mul(CURVE.a, x2), y2);
|
||
const right = Fp2.add(Fp2.ONE, Fp2.mul(CURVE.d, Fp2.mul(x2, y2)));
|
||
return Fp2.eql(left, right);
|
||
}
|
||
function edwards(params, extraOpts = {}) {
|
||
validateObject(extraOpts, {}, {}, "extraOpts");
|
||
const opts = extraOpts;
|
||
const validated = createCurveFields("edwards", params, opts, opts.FpFnLE);
|
||
const { Fp: Fp2, Fn } = validated;
|
||
let CURVE = validated.CURVE;
|
||
const { h: cofactor } = CURVE;
|
||
if (FpLegendre(Fp2, CURVE.a) !== 1)
|
||
throw new Error("edwards: CURVE.a must be a square in Fp for complete addition formulas");
|
||
if (FpLegendre(Fp2, CURVE.d) !== -1)
|
||
throw new Error("edwards: CURVE.d must be a non-square in Fp for complete addition formulas");
|
||
validateObject(opts, {}, { uvRatio: "function", randomBytes: "function" });
|
||
const randomBytes3 = opts.randomBytes === void 0 ? randomBytes2 : opts.randomBytes;
|
||
const MASK = _2n2 << BigInt(Fp2.BYTES * 8) - _1n4;
|
||
function isOdd(n) {
|
||
if (!Fp2.isOdd)
|
||
throw new Error("Field does not have .isOdd()");
|
||
return Fp2.isOdd(n);
|
||
}
|
||
const uvRatio2 = opts.uvRatio === void 0 ? (u, v) => {
|
||
try {
|
||
return { isValid: true, value: Fp2.sqrt(Fp2.div(u, v)) };
|
||
} catch (e) {
|
||
return { isValid: false, value: _0n4 };
|
||
}
|
||
} : opts.uvRatio;
|
||
if (!isEdValidXY(Fp2, CURVE, CURVE.Gx, CURVE.Gy))
|
||
throw new Error("bad curve params: generator point");
|
||
const mulA = Fp2.eql(CURVE.a, Fp2.neg(Fp2.ONE)) ? (x) => Fp2.neg(x) : Fp2.eql(CURVE.a, Fp2.ONE) ? (x) => x : (x) => Fp2.mul(CURVE.a, x);
|
||
function acoord(title, n, banZero = false) {
|
||
const min = banZero ? _1n4 : _0n4;
|
||
aInRange("coordinate " + title, n, min, MASK);
|
||
return n;
|
||
}
|
||
function aedpoint(other) {
|
||
if (!(other instanceof Point))
|
||
throw new Error("EdwardsPoint expected");
|
||
}
|
||
class Point {
|
||
static BASE = new Point(CURVE.Gx, CURVE.Gy, Fp2.ONE, Fp2.mul(CURVE.Gx, CURVE.Gy));
|
||
static ZERO = new Point(Fp2.ZERO, Fp2.ONE, Fp2.ONE, Fp2.ZERO);
|
||
static Fp = Fp2;
|
||
static Fn = Fn;
|
||
X;
|
||
Y;
|
||
Z;
|
||
T;
|
||
constructor(X, Y, Z, T) {
|
||
this.X = acoord("x", X);
|
||
this.Y = acoord("y", Y);
|
||
this.Z = acoord("z", Z, true);
|
||
this.T = acoord("t", T);
|
||
Object.freeze(this);
|
||
}
|
||
static CURVE() {
|
||
return CURVE;
|
||
}
|
||
/**
|
||
* Create one extended Edwards point from affine coordinates.
|
||
* Does NOT validate that the point is on-curve or torsion-free.
|
||
* Use `.assertValidity()` on adversarial inputs.
|
||
*/
|
||
static fromAffine(p) {
|
||
if (p instanceof Point)
|
||
throw new Error("extended point not allowed");
|
||
const { x, y } = p || {};
|
||
acoord("x", x);
|
||
acoord("y", y);
|
||
return new Point(x, y, Fp2.ONE, Fp2.mul(x, y));
|
||
}
|
||
// Uses algo from RFC8032 5.1.3.
|
||
static fromBytes(bytes, zip215 = false) {
|
||
const len = Fp2.BYTES;
|
||
const { a, d } = CURVE;
|
||
bytes = copyBytes(abytes2(bytes, len, "point"));
|
||
abool(zip215, "zip215");
|
||
const normed = copyBytes(bytes);
|
||
const lastByte = bytes[len - 1];
|
||
normed[len - 1] = lastByte & ~128;
|
||
const y = bytesToNumberLE(normed);
|
||
const max = zip215 ? MASK : Fp2.ORDER;
|
||
aInRange("point.y", y, _0n4, max);
|
||
const y2 = Fp2.sqr(y);
|
||
const u = Fp2.sub(y2, Fp2.ONE);
|
||
const v = Fp2.sub(Fp2.mulN(d, y2), a);
|
||
let { isValid, value: x } = uvRatio2(u, v);
|
||
if (!isValid)
|
||
throw new Error("bad point: invalid y coordinate");
|
||
const isXOdd = isOdd(x);
|
||
const isLastByteOdd = (lastByte & 128) !== 0;
|
||
if (!zip215 && Fp2.is0(x) && isLastByteOdd)
|
||
throw new Error("bad point: x=0 and x_0=1");
|
||
if (isLastByteOdd !== isXOdd)
|
||
x = Fp2.neg(x);
|
||
return Point.fromAffine({ x, y });
|
||
}
|
||
static fromHex(hex, zip215 = false) {
|
||
return Point.fromBytes(hexToBytes2(hex), zip215);
|
||
}
|
||
get x() {
|
||
return this.toAffine().x;
|
||
}
|
||
get y() {
|
||
return this.toAffine().y;
|
||
}
|
||
precompute(windowSize = 6, isLazy = true) {
|
||
wnaf.setWindowSize(this, windowSize);
|
||
if (!isLazy)
|
||
this.multiply(_2n2);
|
||
return this;
|
||
}
|
||
// Useful in fromAffine() - not for fromBytes(), which always created valid points.
|
||
assertValidity() {
|
||
const p = this;
|
||
const { a, d } = CURVE;
|
||
if (p.is0())
|
||
throw new Error("bad point: ZERO");
|
||
const { X, Y, Z, T } = p;
|
||
const X2 = Fp2.sqr(X);
|
||
const Y2 = Fp2.sqr(Y);
|
||
const Z2 = Fp2.sqr(Z);
|
||
const Z4 = Fp2.sqr(Z2);
|
||
const aX2 = Fp2.mul(X2, a);
|
||
const left = Fp2.mul(Fp2.add(aX2, Y2), Z2);
|
||
const right = Fp2.add(Z4, Fp2.mul(d, Fp2.mul(X2, Y2)));
|
||
if (!Fp2.eql(left, right))
|
||
throw new Error("bad point: equation left != right (1)");
|
||
const XY = Fp2.mul(X, Y);
|
||
const ZT = Fp2.mul(Z, T);
|
||
if (!Fp2.eql(XY, ZT))
|
||
throw new Error("bad point: equation left != right (2)");
|
||
}
|
||
// Compare one point to another.
|
||
equals(other) {
|
||
aedpoint(other);
|
||
const { X: X1, Y: Y1, Z: Z1 } = this;
|
||
const { X: X2, Y: Y2, Z: Z2 } = other;
|
||
const X1Z2 = Fp2.mul(X1, Z2);
|
||
const X2Z1 = Fp2.mul(X2, Z1);
|
||
const Y1Z2 = Fp2.mul(Y1, Z2);
|
||
const Y2Z1 = Fp2.mul(Y2, Z1);
|
||
return Fp2.eql(X1Z2, X2Z1) && Fp2.eql(Y1Z2, Y2Z1);
|
||
}
|
||
is0() {
|
||
return this.equals(Point.ZERO);
|
||
}
|
||
negate() {
|
||
return new Point(Fp2.neg(this.X), this.Y, this.Z, Fp2.neg(this.T));
|
||
}
|
||
// Fast algo for doubling Extended Point.
|
||
// https://hyperelliptic.org/EFD/g1p/auto-twisted-extended.html#doubling-dbl-2008-hwcd
|
||
// Cost: 4M + 4S + 1*a + 6add + 1*2.
|
||
double() {
|
||
const { X: X1, Y: Y1, Z: Z1 } = this;
|
||
const A = Fp2.sqr(X1);
|
||
const B = Fp2.sqr(Y1);
|
||
const C = Fp2.mul(Fp2.sqr(Z1), _2n2);
|
||
const D = mulA(A);
|
||
const x1y1 = Fp2.addN(X1, Y1);
|
||
const E = Fp2.sub(Fp2.subN(Fp2.sqr(x1y1), A), B);
|
||
const G = Fp2.addN(D, B);
|
||
const F = Fp2.subN(G, C);
|
||
const H = Fp2.subN(D, B);
|
||
const X3 = Fp2.mul(E, F);
|
||
const Y3 = Fp2.mul(G, H);
|
||
const T3 = Fp2.mul(E, H);
|
||
const Z3 = Fp2.mul(F, G);
|
||
return new Point(X3, Y3, Z3, T3);
|
||
}
|
||
// Fast algo for adding 2 Extended Points.
|
||
// https://hyperelliptic.org/EFD/g1p/auto-twisted-extended.html#addition-add-2008-hwcd
|
||
// Cost: 9M + 1*a + 1*d + 7add.
|
||
add(other) {
|
||
aedpoint(other);
|
||
const { d } = CURVE;
|
||
const { X: X1, Y: Y1, Z: Z1, T: T1 } = this;
|
||
const { X: X2, Y: Y2, Z: Z2, T: T2 } = other;
|
||
const A = Fp2.mul(X1, X2);
|
||
const B = Fp2.mul(Y1, Y2);
|
||
const C = Fp2.mul(Fp2.mulN(T1, d), T2);
|
||
const D = Fp2.mul(Z1, Z2);
|
||
const E = Fp2.sub(Fp2.subN(Fp2.mulN(Fp2.addN(X1, Y1), Fp2.addN(X2, Y2)), A), B);
|
||
const F = Fp2.subN(D, C);
|
||
const G = Fp2.addN(D, C);
|
||
const H = Fp2.sub(B, mulA(A));
|
||
const X3 = Fp2.mul(E, F);
|
||
const Y3 = Fp2.mul(G, H);
|
||
const T3 = Fp2.mul(E, H);
|
||
const Z3 = Fp2.mul(F, G);
|
||
return new Point(X3, Y3, Z3, T3);
|
||
}
|
||
subtract(other) {
|
||
aedpoint(other);
|
||
return this.add(other.negate());
|
||
}
|
||
// Constant-time multiplication.
|
||
multiply(scalar) {
|
||
if (!Fn.isValidNot0(scalar))
|
||
throw new RangeError("invalid scalar: expected 1 <= sc < curve.n");
|
||
const { p, f } = wnaf.mulSecret(this, scalar, cofactor, normalize);
|
||
return normalize([p, f])[0];
|
||
}
|
||
// 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.
|
||
// Keeps the same subgroup-scalar contract: 0 is allowed for public-scalar callers, but
|
||
// n and larger values are rejected instead of being reduced mod n to the identity point.
|
||
multiplyUnsafe(scalar) {
|
||
if (!Fn.isValid(scalar))
|
||
throw new RangeError("invalid scalar: expected 0 <= sc < curve.n");
|
||
if (scalar === _0n4)
|
||
return Point.ZERO;
|
||
if (this.is0() || scalar === _1n4)
|
||
return this;
|
||
return wnaf.mulUnsafe(this, scalar, normalize);
|
||
}
|
||
// Checks if point is of small order.
|
||
// If you add something to small order point, you will have "dirty"
|
||
// point with torsion component.
|
||
// Clears cofactor and checks if the result is 0.
|
||
isSmallOrder() {
|
||
return this.clearCofactor().is0();
|
||
}
|
||
// Multiplies point by curve order and checks if the result is 0.
|
||
// Returns `false` is the point is dirty.
|
||
isTorsionFree() {
|
||
return wnaf.mulUnsafe(this, CURVE.n).is0();
|
||
}
|
||
// Converts Extended point to default (x, y) coordinates.
|
||
// Can accept precomputed Z^-1 - for example, from invertBatch.
|
||
toAffine(invertedZ) {
|
||
const p = this;
|
||
let iz = invertedZ;
|
||
if (iz != null && typeof iz !== "bigint")
|
||
throw new TypeError('"invertedZ" expected bigint, got type=' + typeof iz);
|
||
const { X, Y, Z } = p;
|
||
const is0 = p.is0();
|
||
if (iz == null)
|
||
iz = is0 ? Fp2.create(_8n2) : Fp2.inv(Z);
|
||
const x = Fp2.mul(X, iz);
|
||
const y = Fp2.mul(Y, iz);
|
||
const zz = Fp2.mul(Z, iz);
|
||
if (is0)
|
||
return { x: Fp2.ZERO, y: Fp2.ONE };
|
||
if (!Fp2.eql(zz, Fp2.ONE))
|
||
throw new Error("invZ was invalid");
|
||
return { x, y };
|
||
}
|
||
clearCofactor() {
|
||
if (cofactor === _1n4)
|
||
return this;
|
||
if (cofactor === _2n2)
|
||
return this.double();
|
||
if (cofactor === _4n3)
|
||
return this.double().double();
|
||
if (cofactor === _8n2)
|
||
return this.double().double().double();
|
||
return this.multiplyUnsafe(cofactor);
|
||
}
|
||
toBytes() {
|
||
const { x, y } = this.toAffine();
|
||
const bytes = Fp2.toBytes(y);
|
||
bytes[bytes.length - 1] |= isOdd(x) ? 128 : 0;
|
||
return bytes;
|
||
}
|
||
toHex() {
|
||
return bytesToHex2(this.toBytes());
|
||
}
|
||
toString() {
|
||
return `<Point ${this.is0() ? "ZERO" : this.toHex()}>`;
|
||
}
|
||
}
|
||
const normalize = (points) => normalizeZ(Point, points);
|
||
const wnaf = new ScalarMultiplier(Point, randomBytes3);
|
||
if (wnaf.bits >= 6)
|
||
Point.BASE.precompute(6);
|
||
Object.freeze(Point.prototype);
|
||
Object.freeze(Point);
|
||
return Point;
|
||
}
|
||
function eddsa(Point, cHash, eddsaOpts = {}) {
|
||
validatePointCons(Point);
|
||
if (typeof cHash !== "function")
|
||
throw new Error('"hash" function param is required');
|
||
const hash = cHash;
|
||
const opts = eddsaOpts;
|
||
validateObject(opts, {}, {
|
||
adjustScalarBytes: "function",
|
||
randomBytes: "function",
|
||
domain: "function",
|
||
prehash: "function",
|
||
zip215: "boolean",
|
||
mapToCurve: "function",
|
||
toMontgomery: "function",
|
||
toMontgomerySecret: "function"
|
||
});
|
||
const { prehash } = opts;
|
||
const { BASE, Fp: Fp2, Fn } = Point;
|
||
const outputLen = hash.outputLen;
|
||
const expectedLen = 2 * Fp2.BYTES;
|
||
if (outputLen !== void 0) {
|
||
asafenumber(outputLen, "hash.outputLen");
|
||
if (outputLen !== expectedLen)
|
||
throw new Error(`hash.outputLen must be ${expectedLen}, got ${outputLen}`);
|
||
}
|
||
const randomBytes3 = opts.randomBytes === void 0 ? randomBytes2 : opts.randomBytes;
|
||
const toMontgomery2 = opts.toMontgomery;
|
||
const toMontgomerySecret2 = opts.toMontgomerySecret;
|
||
const adjustScalarBytes2 = opts.adjustScalarBytes === void 0 ? (bytes) => bytes : opts.adjustScalarBytes;
|
||
const domain = opts.domain === void 0 ? (data, ctx, phflag) => {
|
||
abool(phflag, "phflag");
|
||
if (ctx.length || phflag)
|
||
throw new Error("Contexts/pre-hash are not supported");
|
||
return data;
|
||
} : opts.domain;
|
||
function modN_LE(hash2) {
|
||
return Fn.create(bytesToNumberLE(hash2));
|
||
}
|
||
function getPrivateScalar(key) {
|
||
const len = lengths.secretKey;
|
||
abytes2(key, lengths.secretKey, "secretKey");
|
||
const hashed = abytes2(hash(key), 2 * len, "hashedSecretKey");
|
||
const head = adjustScalarBytes2(hashed.slice(0, len));
|
||
const prefix = hashed.slice(len, 2 * len);
|
||
const scalar = modN_LE(head);
|
||
return { head, prefix, scalar };
|
||
}
|
||
function getExtendedPublicKey(secretKey) {
|
||
const { head, prefix, scalar } = getPrivateScalar(secretKey);
|
||
const point = BASE.multiply(scalar);
|
||
const pointBytes = point.toBytes();
|
||
return { head, prefix, scalar, point, pointBytes };
|
||
}
|
||
function getPublicKey(secretKey) {
|
||
return getExtendedPublicKey(secretKey).pointBytes;
|
||
}
|
||
function hashDomainToScalar(context = Uint8Array.of(), ...msgs) {
|
||
const msg = concatBytes2(...msgs);
|
||
return modN_LE(hash(domain(msg, abytes2(context, void 0, "context"), !!prehash)));
|
||
}
|
||
function sign(msg, secretKey, options = {}) {
|
||
validateObject(options, {}, {}, "options");
|
||
msg = copyBytes(abytes2(msg, void 0, "message"));
|
||
if (prehash)
|
||
msg = prehash(msg);
|
||
const { prefix, scalar, pointBytes } = getExtendedPublicKey(secretKey);
|
||
const r = hashDomainToScalar(options.context, prefix, msg);
|
||
const R = BASE.multiply(r).toBytes();
|
||
const k = hashDomainToScalar(options.context, R, pointBytes, msg);
|
||
const s = Fn.create(r + k * scalar);
|
||
if (!Fn.isValid(s))
|
||
throw new Error("sign failed: invalid s");
|
||
const rs = concatBytes2(R, Fn.toBytes(s));
|
||
return abytes2(rs, lengths.signature, "result");
|
||
}
|
||
const verifyOpts2 = {
|
||
zip215: opts.zip215
|
||
};
|
||
function verify(sig, msg, publicKey, options = verifyOpts2) {
|
||
validateObject(options);
|
||
const { context } = options;
|
||
const zip215 = options.zip215 === void 0 ? !!verifyOpts2.zip215 : options.zip215;
|
||
const len = lengths.signature;
|
||
sig = abytes2(sig, len, "signature");
|
||
msg = abytes2(msg, void 0, "message");
|
||
publicKey = abytes2(publicKey, lengths.publicKey, "publicKey");
|
||
if (zip215 !== void 0)
|
||
abool(zip215, "zip215");
|
||
if (prehash)
|
||
msg = prehash(msg);
|
||
const mid = len / 2;
|
||
const r = sig.subarray(0, mid);
|
||
const s = bytesToNumberLE(sig.subarray(mid, len));
|
||
let A, R, SB;
|
||
try {
|
||
A = Point.fromBytes(publicKey, zip215);
|
||
R = Point.fromBytes(r, zip215);
|
||
SB = BASE.multiplyUnsafe(s);
|
||
} catch (error) {
|
||
return false;
|
||
}
|
||
if (!zip215 && A.isSmallOrder())
|
||
return false;
|
||
const k = hashDomainToScalar(context, r, publicKey, msg);
|
||
const RkA = R.add(A.multiplyUnsafe(k));
|
||
return RkA.subtract(SB).clearCofactor().is0();
|
||
}
|
||
const _size = Fp2.BYTES;
|
||
const lengths = {
|
||
secretKey: _size,
|
||
publicKey: _size,
|
||
signature: 2 * _size,
|
||
seed: _size
|
||
};
|
||
function randomSecretKey(seed) {
|
||
seed = seed === void 0 ? randomBytes3(lengths.seed) : seed;
|
||
return abytes2(seed, lengths.seed, "seed");
|
||
}
|
||
function isValidSecretKey(key) {
|
||
return isBytes2(key) && key.length === lengths.secretKey;
|
||
}
|
||
function isValidPublicKey(key, zip215) {
|
||
try {
|
||
return !!Point.fromBytes(key, zip215 === void 0 ? verifyOpts2.zip215 : zip215);
|
||
} catch (error) {
|
||
return false;
|
||
}
|
||
}
|
||
const utils = {
|
||
getExtendedPublicKey,
|
||
randomSecretKey,
|
||
isValidSecretKey,
|
||
isValidPublicKey,
|
||
/** Converts an Edwards public key to a companion Montgomery public key. */
|
||
toMontgomery(publicKey) {
|
||
if (toMontgomery2 === void 0)
|
||
throw new Error("Montgomery conversion is not supported for this curve");
|
||
return toMontgomery2(Point.fromBytes(publicKey));
|
||
},
|
||
toMontgomerySecret(secretKey) {
|
||
if (toMontgomerySecret2 === void 0)
|
||
throw new Error("Montgomery conversion is not supported for this curve");
|
||
return toMontgomerySecret2(secretKey);
|
||
}
|
||
};
|
||
Object.freeze(lengths);
|
||
Object.freeze(utils);
|
||
return Object.freeze({
|
||
keygen: createKeygen(randomSecretKey, getPublicKey),
|
||
getPublicKey,
|
||
sign,
|
||
verify,
|
||
utils,
|
||
Point,
|
||
lengths
|
||
});
|
||
}
|
||
|
||
// node_modules/@noble/curves/ed25519.js
|
||
/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
|
||
var _1n5 = /* @__PURE__ */ BigInt(1);
|
||
var _2n3 = /* @__PURE__ */ BigInt(2);
|
||
var _5n2 = /* @__PURE__ */ BigInt(5);
|
||
var _8n3 = /* @__PURE__ */ BigInt(8);
|
||
var ed25519_CURVE_p = /* @__PURE__ */ BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed");
|
||
var ed25519_CURVE = /* @__PURE__ */ (() => ({
|
||
p: ed25519_CURVE_p,
|
||
n: BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),
|
||
h: _8n3,
|
||
a: BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),
|
||
d: BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),
|
||
Gx: BigInt("0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"),
|
||
Gy: BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")
|
||
}))();
|
||
function ed25519_pow_2_252_3(x) {
|
||
const _10n = BigInt(10), _20n = BigInt(20), _40n = BigInt(40), _80n = BigInt(80);
|
||
const P = ed25519_CURVE_p;
|
||
const x2 = x * x % P;
|
||
const b2 = x2 * x % P;
|
||
const b4 = pow2(b2, _2n3, P) * b2 % P;
|
||
const b5 = pow2(b4, _1n5, P) * x % P;
|
||
const b10 = pow2(b5, _5n2, P) * b5 % P;
|
||
const b20 = pow2(b10, _10n, P) * b10 % P;
|
||
const b40 = pow2(b20, _20n, P) * b20 % P;
|
||
const b80 = pow2(b40, _40n, P) * b40 % P;
|
||
const b160 = pow2(b80, _80n, P) * b80 % P;
|
||
const b240 = pow2(b160, _80n, P) * b80 % P;
|
||
const b250 = pow2(b240, _10n, P) * b10 % P;
|
||
const pow_p_5_8 = pow2(b250, _2n3, P) * x % P;
|
||
return { pow_p_5_8, b2 };
|
||
}
|
||
function adjustScalarBytes(bytes) {
|
||
bytes[0] &= 248;
|
||
bytes[31] &= 127;
|
||
bytes[31] |= 64;
|
||
return bytes;
|
||
}
|
||
var ED25519_SQRT_M1 = /* @__PURE__ */ BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");
|
||
function uvRatio(u, v) {
|
||
const P = ed25519_CURVE_p;
|
||
const v3 = mod(v * v * v, P);
|
||
const v7 = mod(v3 * v3 * v, P);
|
||
const pow3 = ed25519_pow_2_252_3(u * v7).pow_p_5_8;
|
||
let x = mod(u * v3 * pow3, P);
|
||
const vx2 = mod(v * x * x, P);
|
||
const root1 = x;
|
||
const root2 = mod(x * ED25519_SQRT_M1, P);
|
||
const useRoot1 = vx2 === u;
|
||
const useRoot2 = vx2 === mod(-u, P);
|
||
const noRoot = vx2 === mod(-u * ED25519_SQRT_M1, P);
|
||
if (useRoot1)
|
||
x = root1;
|
||
if (useRoot2 || noRoot)
|
||
x = root2;
|
||
if (isNegativeLE(x, P))
|
||
x = mod(-x, P);
|
||
return { isValid: useRoot1 || useRoot2, value: x };
|
||
}
|
||
var ed25519_Point = /* @__PURE__ */ edwards(ed25519_CURVE, { uvRatio });
|
||
var Fp = /* @__PURE__ */ (() => ed25519_Point.Fp)();
|
||
function toMontgomery(point) {
|
||
const { y } = point;
|
||
return Fp.toBytes(Fp.div(_1n5 + y, _1n5 - y));
|
||
}
|
||
function toMontgomerySecret(secretKey) {
|
||
const size = ed25519_Point.Fp.BYTES;
|
||
abytes(secretKey, size);
|
||
return adjustScalarBytes(sha512(secretKey.subarray(0, size))).subarray(0, size);
|
||
}
|
||
function ed(opts) {
|
||
return eddsa(ed25519_Point, sha512, Object.assign({ adjustScalarBytes, toMontgomery, toMontgomerySecret, zip215: true }, opts));
|
||
}
|
||
var ed25519 = /* @__PURE__ */ ed({});
|
||
|
||
// src/jcs.ts
|
||
function canonicalize(value) {
|
||
if (value === null) return "null";
|
||
switch (typeof value) {
|
||
case "boolean":
|
||
return value ? "true" : "false";
|
||
case "number":
|
||
if (!Number.isSafeInteger(value)) {
|
||
throw new Error("jcs: only safe integers are supported");
|
||
}
|
||
return String(value);
|
||
case "string":
|
||
return JSON.stringify(value);
|
||
case "object": {
|
||
if (Array.isArray(value)) {
|
||
return "[" + value.map(canonicalize).join(",") + "]";
|
||
}
|
||
const obj = value;
|
||
const keys = Object.keys(obj).sort();
|
||
return "{" + keys.map((k) => JSON.stringify(k) + ":" + canonicalize(obj[k])).join(",") + "}";
|
||
}
|
||
default:
|
||
throw new Error("jcs: unsupported value");
|
||
}
|
||
}
|
||
|
||
// src/verify.ts
|
||
var LISTING_CONTEXT = "allmende-listing-v1\n";
|
||
var CERT_CONTEXT = "allmende-cert-v1\n";
|
||
var DAY = 86400;
|
||
var MAX_CERT_LIFETIME = 366 * DAY;
|
||
var MAX_LISTING_LIFETIME = 30 * DAY;
|
||
var MAX_CLOCK_SKEW = 10 * 60;
|
||
var enc = new TextEncoder();
|
||
function hexBytes(s, bytes) {
|
||
if (typeof s !== "string" || s.length !== bytes * 2 || !/^[0-9a-f]+$/.test(s)) {
|
||
return null;
|
||
}
|
||
const out = new Uint8Array(bytes);
|
||
for (let i = 0; i < bytes; i++) out[i] = parseInt(s.slice(i * 2, i * 2 + 2), 16);
|
||
return out;
|
||
}
|
||
function leadingZeroBits(bytes) {
|
||
let n = 0;
|
||
for (const b of bytes) {
|
||
if (b === 0) {
|
||
n += 8;
|
||
continue;
|
||
}
|
||
return n + Math.clz32(b) - 24;
|
||
}
|
||
return n;
|
||
}
|
||
function without(o, key) {
|
||
const copy = { ...o };
|
||
delete copy[key];
|
||
return copy;
|
||
}
|
||
function isObject(v) {
|
||
return typeof v === "object" && v !== null && !Array.isArray(v);
|
||
}
|
||
function safeInt(v) {
|
||
return typeof v === "number" && Number.isSafeInteger(v);
|
||
}
|
||
function signedBy(context, signed, sigHex, pubHex) {
|
||
const sig = hexBytes(sigHex, 64);
|
||
const pub = hexBytes(pubHex, 32);
|
||
if (!sig || !pub) return false;
|
||
try {
|
||
const msg = enc.encode(context + canonicalize(signed));
|
||
return ed25519.verify(sig, msg, pub);
|
||
} catch {
|
||
return false;
|
||
}
|
||
}
|
||
function verifyListing(input, opts) {
|
||
const checks = [];
|
||
const add2 = (id, ok, info = "") => checks.push({ id, ok, info });
|
||
let powBits = 0;
|
||
const finish = () => ({ ok: checks.every((c2) => c2.ok), checks, powBits });
|
||
if (!isObject(input) || !isObject(input.cert)) {
|
||
add2("format", false, "not a listing object");
|
||
return finish();
|
||
}
|
||
const l = input;
|
||
const c = l.cert;
|
||
const shapeOk = l.v === 1 && hexBytes(l.id, 16) !== null && hexBytes(l.author, 32) !== null && hexBytes(l.device, 32) !== null && hexBytes(l.sig, 64) !== null && safeInt(l.seq) && safeInt(l.created_at) && safeInt(l.expires_at) && safeInt(l.pow) && typeof l.geohash === "string";
|
||
add2("format", shapeOk, shapeOk ? "" : "malformed fields");
|
||
if (!shapeOk) return finish();
|
||
const certShape = c.v === 1 && hexBytes(c.author, 32) !== null && hexBytes(c.device, 32) !== null && safeInt(c.issued_at) && safeInt(c.expires_at) && c.expires_at > c.issued_at && c.expires_at - c.issued_at <= MAX_CERT_LIFETIME;
|
||
const certSig = certShape && signedBy(CERT_CONTEXT, without(c, "sig"), c.sig, c.author);
|
||
add2(
|
||
"certificate",
|
||
certSig,
|
||
!certShape ? "malformed certificate" : certSig ? "" : "bad certificate signature"
|
||
);
|
||
if (!certSig) return finish();
|
||
const bound = c.author === l.author && c.device === l.device;
|
||
add2("binding", bound, bound ? "" : "certificate is for a different identity or device");
|
||
const reasons = [];
|
||
if (!(c.issued_at <= l.created_at && l.created_at < c.expires_at)) {
|
||
reasons.push("created outside certificate validity");
|
||
}
|
||
if (opts.now >= c.expires_at) reasons.push("certificate expired");
|
||
if (l.expires_at <= l.created_at) reasons.push("expires before it was created");
|
||
if (l.expires_at - l.created_at > MAX_LISTING_LIFETIME) reasons.push("lifetime over 30 days");
|
||
if (l.created_at > opts.now + MAX_CLOCK_SKEW) reasons.push("created in the future");
|
||
if (l.expires_at <= opts.now) reasons.push("expired");
|
||
add2("validity", reasons.length === 0, reasons.join("; "));
|
||
const unsigned = without(l, "sig");
|
||
const sigOk = signedBy(LISTING_CONTEXT, unsigned, l.sig, l.device);
|
||
add2("signature", sigOk, sigOk ? "" : "signature does not match the content");
|
||
try {
|
||
powBits = leadingZeroBits(sha256(enc.encode(canonicalize(unsigned))));
|
||
} catch {
|
||
powBits = 0;
|
||
}
|
||
const powOk = powBits >= opts.minPowBits;
|
||
add2("pow", powOk, `${powBits} bits (network requires ${opts.minPowBits})`);
|
||
return finish();
|
||
}
|
||
|
||
// src/main.ts
|
||
var PAGE = 20;
|
||
var GEOHASH_PREFIX = /^[0-9bcdefghjkmnpqrstuvwxyz]{1,6}$/;
|
||
var app = document.getElementById("app");
|
||
var statusEl = document.getElementById("status");
|
||
var nodeInfo = null;
|
||
var generation = 0;
|
||
function verifyOpts() {
|
||
return { now: Math.floor(Date.now() / 1e3), minPowBits: nodeInfo?.difficulty ?? 0 };
|
||
}
|
||
function label(prefix, value) {
|
||
if (!value) return "";
|
||
const key = `${prefix}.${value}`;
|
||
const known = ["kind.rent", "kind.sale", "cat.apartment", "cat.house", "cat.room", "cat.commercial"];
|
||
return known.includes(key) ? t(key) : value;
|
||
}
|
||
function where(geohash) {
|
||
const a = decodeGeohash(geohash);
|
||
if (!a) return geohash;
|
||
const ns = a.lat >= 0 ? "N" : "S";
|
||
const ew = a.lon >= 0 ? lang === "de" ? "O" : "E" : lang === "de" ? "W" : "W";
|
||
return `${Math.abs(a.lat).toFixed(2)}\xB0 ${ns}, ${Math.abs(a.lon).toFixed(2)}\xB0 ${ew}`;
|
||
}
|
||
function badge(ok) {
|
||
return h("span", { class: ok ? "badge ok" : "badge bad" }, (ok ? "\u2713 " : "\u2717 ") + t(ok ? "badge.ok" : "badge.bad"));
|
||
}
|
||
function num(v) {
|
||
const n = Number((v ?? "").replace(",", "."));
|
||
return Number.isFinite(n) && n > 0 ? n : 0;
|
||
}
|
||
function toApi(p) {
|
||
const q = new URLSearchParams();
|
||
for (const k of ["kind", "category", "geohash"]) {
|
||
const v = p.get(k)?.trim().toLowerCase();
|
||
if (v) q.set(k, v);
|
||
}
|
||
const eur = num(p.get("max_price"));
|
||
if (eur) q.set("max_price", String(Math.round(eur * 100)));
|
||
const area = num(p.get("min_area"));
|
||
if (area) q.set("min_area", String(Math.ceil(area)));
|
||
const r = num(p.get("min_rooms"));
|
||
if (r) q.set("min_rooms", String(Math.ceil(r * 2)));
|
||
return q;
|
||
}
|
||
function field(text, input, hint) {
|
||
return h("label", { class: "field" }, h("span", { class: "field-label" }, text), input, hint && h("span", { class: "hint" }, hint));
|
||
}
|
||
function select(name, current, options) {
|
||
const el = h("select", { name });
|
||
for (const [value, text] of options) {
|
||
el.append(h("option", { value, selected: value === current }, text));
|
||
}
|
||
return el;
|
||
}
|
||
function searchForm(params) {
|
||
const get = (k) => params.get(k) ?? "";
|
||
const regions = h("datalist", { id: "regions" }, ...(nodeInfo?.regions ?? []).map((r) => h("option", { value: r })));
|
||
const form = h(
|
||
"form",
|
||
{ class: "filters" },
|
||
field(t("filter.kind"), select("kind", get("kind"), [["", t("filter.any")], ["rent", t("kind.rent")], ["sale", t("kind.sale")]])),
|
||
field(
|
||
t("filter.category"),
|
||
select("category", get("category"), [
|
||
["", t("filter.any")],
|
||
["apartment", t("cat.apartment")],
|
||
["house", t("cat.house")],
|
||
["room", t("cat.room")],
|
||
["commercial", t("cat.commercial")]
|
||
])
|
||
),
|
||
field(
|
||
t("filter.region"),
|
||
h("input", { name: "geohash", value: get("geohash"), list: "regions", autocomplete: "off", spellcheck: "false", maxlength: 6, placeholder: nodeInfo?.regions[0] ?? "u1x" }),
|
||
t("filter.regionHint")
|
||
),
|
||
field(t("filter.maxPrice"), h("input", { name: "max_price", type: "number", min: 0, step: 50, inputmode: "decimal", value: get("max_price") })),
|
||
field(t("filter.minArea"), h("input", { name: "min_area", type: "number", min: 0, step: 5, value: get("min_area") })),
|
||
field(t("filter.minRooms"), h("input", { name: "min_rooms", type: "number", min: 0, step: 0.5, value: get("min_rooms") })),
|
||
h(
|
||
"div",
|
||
{ class: "actions" },
|
||
h("button", { type: "submit", class: "btn primary" }, t("filter.search")),
|
||
h("button", { type: "button", class: "btn", onclick: () => navigate("#/") }, t("filter.reset"))
|
||
),
|
||
regions
|
||
);
|
||
form.addEventListener("submit", (e) => {
|
||
e.preventDefault();
|
||
const q = new URLSearchParams();
|
||
for (const [k, v] of new FormData(form)) {
|
||
if (typeof v === "string" && v.trim() !== "") q.set(k, v.trim());
|
||
}
|
||
const s = q.toString();
|
||
navigate(s ? `#/?${s}` : "#/");
|
||
});
|
||
return form;
|
||
}
|
||
function navigate(hash) {
|
||
if (location.hash === hash || hash === "#/" && location.hash === "") route();
|
||
else location.hash = hash;
|
||
}
|
||
function card(l) {
|
||
const facts = [
|
||
label("cat", l.category),
|
||
l.area_m2 ? t("card.area", { n: l.area_m2 }) : "",
|
||
l.rooms_x2 ? rooms(l.rooms_x2) : ""
|
||
].filter(Boolean);
|
||
return h(
|
||
"a",
|
||
{ class: "card", href: `#/l/${l.author}/${l.id}` },
|
||
// author and id were verified to be hex
|
||
h("div", { class: "card-top" }, h("h3", null, l.title ?? ""), badge(true)),
|
||
h("p", { class: "price" }, price(l)),
|
||
h("p", { class: "facts" }, facts.join(" \xB7 ")),
|
||
h("p", { class: "muted" }, where(l.geohash))
|
||
);
|
||
}
|
||
async function loadResults(gen, q, root) {
|
||
const cards = h("div", { class: "cards" });
|
||
const foot = h("div", { class: "results-foot" });
|
||
append(root, [cards, foot]);
|
||
let offset = 0;
|
||
let shown = 0;
|
||
let hidden = 0;
|
||
const more = async () => {
|
||
clear(foot);
|
||
foot.append(h("p", { class: "muted" }, t("results.loading")));
|
||
let items;
|
||
try {
|
||
const paged = new URLSearchParams(q);
|
||
paged.set("limit", String(PAGE));
|
||
paged.set("offset", String(offset));
|
||
items = await search(paged);
|
||
} catch {
|
||
if (gen !== generation) return;
|
||
clear(foot);
|
||
foot.append(h("p", { class: "error" }, t("results.error")));
|
||
return;
|
||
}
|
||
if (gen !== generation) return;
|
||
const opts = verifyOpts();
|
||
for (const raw of items) {
|
||
const verdict = verifyListing(raw, opts);
|
||
if (verdict.ok) {
|
||
cards.append(card(raw));
|
||
shown++;
|
||
} else {
|
||
hidden++;
|
||
}
|
||
}
|
||
offset += items.length;
|
||
clear(foot);
|
||
if (hidden > 0) foot.append(h("p", { class: "warn" }, t("results.hidden", { n: hidden })));
|
||
if (shown === 0 && items.length < PAGE) foot.append(h("p", { class: "muted" }, t("results.none")));
|
||
if (items.length === PAGE) {
|
||
foot.append(h("button", { type: "button", class: "btn", onclick: () => void more() }, t("results.more")));
|
||
}
|
||
};
|
||
await more();
|
||
}
|
||
function showSearch(params) {
|
||
const gen = generation;
|
||
clear(app);
|
||
const results = h("div", { class: "results", "aria-live": "polite" });
|
||
app.append(h("p", { class: "tagline" }, t("app.tagline")), searchForm(params), results);
|
||
const prefix = params.get("geohash")?.trim().toLowerCase();
|
||
if (prefix && !GEOHASH_PREFIX.test(prefix)) {
|
||
results.append(h("p", { class: "error" }, t("filter.regionHint")));
|
||
return;
|
||
}
|
||
void loadResults(gen, toApi(params), results);
|
||
}
|
||
function checkList(v) {
|
||
return h(
|
||
"ul",
|
||
{ class: "checks" },
|
||
...v.checks.map(
|
||
(c) => h(
|
||
"li",
|
||
{ class: c.ok ? "ok" : "bad" },
|
||
h("span", { class: "mark", "aria-hidden": "true" }, c.ok ? "\u2713" : "\u2717"),
|
||
h("span", null, t(`verify.${c.id}`)),
|
||
c.info && h("span", { class: "muted info" }, c.info)
|
||
)
|
||
)
|
||
);
|
||
}
|
||
function verification(raw, l, v) {
|
||
return h(
|
||
"section",
|
||
{ class: "panel" },
|
||
h("h2", null, t("verify.title")),
|
||
h("p", { class: "muted" }, t("verify.intro")),
|
||
checkList(v),
|
||
v.ok && h(
|
||
"dl",
|
||
{ class: "kv" },
|
||
h("dt", null, t("verify.owner")),
|
||
h("dd", { class: "mono" }, shortKey(l.author)),
|
||
h("dt", null, t("verify.device")),
|
||
h("dd", { class: "mono" }, shortKey(l.device))
|
||
),
|
||
h("p", { class: "muted" }, t("verify.limit")),
|
||
// Never echo the content of a listing that failed verification, not even as raw data.
|
||
v.ok && h("details", null, h("summary", null, t("verify.raw")), h("pre", null, JSON.stringify(raw, null, 2)))
|
||
);
|
||
}
|
||
function listingBody(l) {
|
||
const area = decodeGeohash(l.geohash);
|
||
const fact = (k, v) => v ? [h("dt", null, t(k)), h("dd", null, v)] : [false];
|
||
const map = area && h(
|
||
"a",
|
||
{
|
||
href: `https://www.openstreetmap.org/?mlat=${area.lat.toFixed(5)}&mlon=${area.lon.toFixed(5)}#map=14/${area.lat.toFixed(5)}/${area.lon.toFixed(5)}`,
|
||
target: "_blank",
|
||
rel: "noopener noreferrer"
|
||
},
|
||
t("detail.map")
|
||
);
|
||
return [
|
||
h("div", { class: "detail-head" }, h("h1", null, l.title ?? ""), badge(true)),
|
||
h("p", { class: "price big" }, price(l)),
|
||
h(
|
||
"section",
|
||
{ class: "panel" },
|
||
h("h2", null, t("detail.facts")),
|
||
h(
|
||
"dl",
|
||
{ class: "kv" },
|
||
...[
|
||
...fact("detail.kind", label("kind", l.kind)),
|
||
...fact("detail.category", label("cat", l.category)),
|
||
...fact("detail.area", l.area_m2 ? t("card.area", { n: l.area_m2 }) : ""),
|
||
...fact("detail.rooms", l.rooms_x2 ? rooms(l.rooms_x2) : ""),
|
||
...fact("detail.published", date(l.created_at)),
|
||
...fact("detail.expires", date(l.expires_at)),
|
||
...fact("detail.version", String(l.seq)),
|
||
...fact("detail.location", where(l.geohash))
|
||
].filter(Boolean)
|
||
),
|
||
map && h("p", null, map)
|
||
),
|
||
l.description ? h("section", { class: "panel" }, h("p", { class: "desc" }, l.description)) : h("span"),
|
||
l.features?.length ? h("section", { class: "panel" }, h("h2", null, t("detail.features")), h("ul", { class: "chips" }, ...l.features.map((f) => h("li", null, f)))) : h("span"),
|
||
h("section", { class: "panel contact" }, h("h2", null, t("detail.contact")), h("p", null, t("detail.contactSoon")))
|
||
];
|
||
}
|
||
async function showDetail(author, id) {
|
||
const gen = generation;
|
||
clear(app);
|
||
const body = h("div", null, h("p", { class: "muted" }, t("results.loading")));
|
||
app.append(h("a", { class: "back", href: "#/" }, t("detail.back")), body);
|
||
let raw;
|
||
try {
|
||
raw = await getListing(author, id);
|
||
} catch {
|
||
if (gen !== generation) return;
|
||
clear(body);
|
||
body.append(h("p", { class: "error" }, t("results.error")));
|
||
return;
|
||
}
|
||
if (gen !== generation) return;
|
||
clear(body);
|
||
if (raw === null) {
|
||
body.append(h("p", { class: "muted" }, t("detail.notFound")));
|
||
return;
|
||
}
|
||
const l = raw;
|
||
let v = verifyListing(raw, verifyOpts());
|
||
if (v.ok && (l.author !== author || l.id !== id)) {
|
||
v = { ...v, ok: false, checks: [...v.checks, { id: "binding", ok: false, info: "not the listing that was requested" }] };
|
||
}
|
||
if (!v.ok) {
|
||
body.append(h("p", { class: "error" }, t("detail.unverified")), verification(raw, l, v));
|
||
return;
|
||
}
|
||
append(body, [...listingBody(l), verification(raw, l, v)]);
|
||
}
|
||
function route() {
|
||
generation++;
|
||
const hash = location.hash.replace(/^#/, "") || "/";
|
||
const q = hash.indexOf("?");
|
||
const path = q < 0 ? hash : hash.slice(0, q);
|
||
const params = new URLSearchParams(q < 0 ? "" : hash.slice(q + 1));
|
||
const m = /^\/l\/([0-9a-f]{64})\/([0-9a-f]{32})$/.exec(path);
|
||
if (m) void showDetail(m[1], m[2]);
|
||
else showSearch(params);
|
||
window.scrollTo(0, 0);
|
||
}
|
||
async function boot() {
|
||
document.documentElement.lang = lang;
|
||
document.getElementById("foot").textContent = t("footer.text");
|
||
try {
|
||
nodeInfo = await getStatus();
|
||
statusEl.textContent = t("status.line", {
|
||
listings: nodeInfo.listings,
|
||
peers: nodeInfo.peers,
|
||
regions: nodeInfo.regions.join(", ")
|
||
});
|
||
} catch {
|
||
statusEl.textContent = t("status.unreachable");
|
||
}
|
||
window.addEventListener("hashchange", route);
|
||
route();
|
||
}
|
||
void boot();
|