nostr-tools
2.20.02.21.0
lib/nostr.bundle.js~
lib/nostr.bundle.jsModified+2792−2318
Index: package/lib/nostr.bundle.js
===================================================================
--- package/lib/nostr.bundle.js
+++ package/lib/nostr.bundle.js
@@ -57,130 +57,194 @@
nip98: () => nip98_exports,
parseReferences: () => parseReferences,
serializeEvent: () => serializeEvent,
sortEvents: () => sortEvents,
- utils: () => utils_exports2,
+ utils: () => utils_exports,
validateEvent: () => validateEvent,
verifiedSymbol: () => verifiedSymbol,
verifyEvent: () => verifyEvent
});
- // node_modules/@noble/curves/node_modules/@noble/hashes/esm/_assert.js
- function number(n) {
- if (!Number.isSafeInteger(n) || n < 0)
- throw new Error(`Wrong positive integer: ${n}`);
+ // node_modules/@jsr/noble__hashes/src/utils.js
+ function isBytes(a) {
+ return a instanceof Uint8Array || ArrayBuffer.isView(a) && a.constructor.name === "Uint8Array";
}
- function bytes(b, ...lengths) {
- if (!(b instanceof Uint8Array))
- throw new Error("Expected Uint8Array");
- if (lengths.length > 0 && !lengths.includes(b.length))
- throw new Error(`Expected Uint8Array of length ${lengths}, not of length=${b.length}`);
+ function anumber(n, title = "") {
+ if (!Number.isSafeInteger(n) || n < 0) {
+ const prefix = title && `"${title}" `;
+ throw new Error(`${prefix}expected integer >= 0, got ${n}`);
+ }
}
- function hash(hash3) {
- if (typeof hash3 !== "function" || typeof hash3.create !== "function")
- throw new Error("Hash should be wrapped by utils.wrapConstructor");
- number(hash3.outputLen);
- number(hash3.blockLen);
+ function abytes(value, length, title = "") {
+ const bytes = isBytes(value);
+ const len = value?.length;
+ const needsLen = length !== void 0;
+ if (!bytes || needsLen && len !== length) {
+ const prefix = title && `"${title}" `;
+ const ofLen = needsLen ? ` of length ${length}` : "";
+ const got = bytes ? `length=${len}` : `type=${typeof value}`;
+ throw new Error(prefix + "expected Uint8Array" + ofLen + ", got " + got);
+ }
+ return value;
}
- function exists(instance, checkFinished = true) {
+ function ahash(h) {
+ if (typeof h !== "function" || typeof h.create !== "function")
+ throw new Error("Hash must wrapped by utils.createHasher");
+ anumber(h.outputLen);
+ anumber(h.blockLen);
+ }
+ function aexists(instance, checkFinished = true) {
if (instance.destroyed)
throw new Error("Hash instance has been destroyed");
if (checkFinished && instance.finished)
throw new Error("Hash#digest() has already been called");
}
- function output(out, instance) {
- bytes(out);
+ function aoutput(out, instance) {
+ abytes(out, void 0, "digestInto() output");
const min = instance.outputLen;
if (out.length < min) {
- throw new Error(`digestInto() expects output buffer of length at least ${min}`);
+ throw new Error('"digestInto() output" expected to be of length >=' + min);
}
}
-
- // node_modules/@noble/curves/node_modules/@noble/hashes/esm/crypto.js
- var crypto = typeof globalThis === "object" && "crypto" in globalThis ? globalThis.crypto : void 0;
-
- // node_modules/@noble/curves/node_modules/@noble/hashes/esm/utils.js
- var u8a = (a) => a instanceof Uint8Array;
- var createView = (arr) => new DataView(arr.buffer, arr.byteOffset, arr.byteLength);
- var rotr = (word, shift) => word << 32 - shift | word >>> shift;
- var isLE = new Uint8Array(new Uint32Array([287454020]).buffer)[0] === 68;
- if (!isLE)
- throw new Error("Non little-endian hardware is not supported");
- function utf8ToBytes(str) {
- if (typeof str !== "string")
- throw new Error(`utf8ToBytes expected string, got ${typeof str}`);
- return new Uint8Array(new TextEncoder().encode(str));
+ function clean(...arrays) {
+ for (let i2 = 0; i2 < arrays.length; i2++) {
+ arrays[i2].fill(0);
+ }
}
- function toBytes(data) {
- if (typeof data === "string")
- data = utf8ToBytes(data);
- if (!u8a(data))
- throw new Error(`expected Uint8Array, got ${typeof data}`);
- return data;
+ function createView(arr) {
+ return new DataView(arr.buffer, arr.byteOffset, arr.byteLength);
}
- function concatBytes(...arrays) {
- const r = new Uint8Array(arrays.reduce((sum, a) => sum + a.length, 0));
- let pad2 = 0;
- arrays.forEach((a) => {
- if (!u8a(a))
- throw new Error("Uint8Array expected");
- r.set(a, pad2);
- pad2 += a.length;
- });
- return r;
+ function rotr(word, shift) {
+ return word << 32 - shift | word >>> shift;
}
- var Hash = class {
- clone() {
- return this._cloneInto();
+ var hasHexBuiltin = /* @__PURE__ */ (() => typeof Uint8Array.from([]).toHex === "function" && typeof Uint8Array.fromHex === "function")();
+ var hexes = /* @__PURE__ */ Array.from({
+ length: 256
+ }, (_, i2) => i2.toString(16).padStart(2, "0"));
+ function bytesToHex(bytes) {
+ abytes(bytes);
+ if (hasHexBuiltin)
+ return bytes.toHex();
+ let hex2 = "";
+ for (let i2 = 0; i2 < bytes.length; i2++) {
+ hex2 += hexes[bytes[i2]];
}
+ return hex2;
+ }
+ var asciis = {
+ _0: 48,
+ _9: 57,
+ A: 65,
+ F: 70,
+ a: 97,
+ f: 102
};
- var toStr = {}.toString;
- function wrapConstructor(hashCons) {
- const hashC = (msg) => hashCons().update(toBytes(msg)).digest();
- const tmp = hashCons();
+ function asciiToBase16(ch) {
+ if (ch >= asciis._0 && ch <= asciis._9)
+ return ch - asciis._0;
+ if (ch >= asciis.A && ch <= asciis.F)
+ return ch - (asciis.A - 10);
+ if (ch >= asciis.a && ch <= asciis.f)
+ return ch - (asciis.a - 10);
+ return;
+ }
+ function hexToBytes(hex2) {
+ if (typeof hex2 !== "string")
+ throw new Error("hex string expected, got " + typeof hex2);
+ if (hasHexBuiltin)
+ return Uint8Array.fromHex(hex2);
+ const hl = hex2.length;
+ const al = hl / 2;
+ if (hl % 2)
+ throw new Error("hex string expected, got unpadded hex of length " + hl);
+ const array = new Uint8Array(al);
+ for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) {
+ const n1 = asciiToBase16(hex2.charCodeAt(hi));
+ const n2 = asciiToBase16(hex2.charCodeAt(hi + 1));
+ if (n1 === void 0 || n2 === void 0) {
+ const char = hex2[hi] + hex2[hi + 1];
+ throw new Error('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 i2 = 0; i2 < arrays.length; i2++) {
+ const a = arrays[i2];
+ abytes(a);
+ sum += a.length;
+ }
+ const res = new Uint8Array(sum);
+ for (let i2 = 0, pad2 = 0; i2 < arrays.length; i2++) {
+ const a = arrays[i2];
+ res.set(a, pad2);
+ pad2 += a.length;
+ }
+ return res;
+ }
+ function createHasher(hashCons, info = {}) {
+ const hashC = (msg, opts) => hashCons(opts).update(msg).digest();
+ const tmp = hashCons(void 0);
hashC.outputLen = tmp.outputLen;
hashC.blockLen = tmp.blockLen;
- hashC.create = () => hashCons();
- return hashC;
+ hashC.create = (opts) => hashCons(opts);
+ Object.assign(hashC, info);
+ return Object.freeze(hashC);
}
function randomBytes(bytesLength = 32) {
- if (crypto && typeof crypto.getRandomValues === "function") {
- return crypto.getRandomValues(new Uint8Array(bytesLength));
- }
- throw new Error("crypto.getRandomValues must be defined");
+ const cr = typeof globalThis === "object" ? globalThis.crypto : null;
+ if (typeof cr?.getRandomValues !== "function")
+ throw new Error("crypto.getRandomValues must be defined");
+ return cr.getRandomValues(new Uint8Array(bytesLength));
}
+ var oidNist = (suffix) => ({
+ oid: Uint8Array.from([
+ 6,
+ 9,
+ 96,
+ 134,
+ 72,
+ 1,
+ 101,
+ 3,
+ 4,
+ 2,
+ suffix
+ ])
+ });
- // node_modules/@noble/curves/node_modules/@noble/hashes/esm/_sha2.js
- function setBigUint64(view, byteOffset, value, isLE4) {
- if (typeof view.setBigUint64 === "function")
- return view.setBigUint64(byteOffset, value, isLE4);
- const _32n = BigInt(32);
- const _u32_max = BigInt(4294967295);
- const wh = Number(value >> _32n & _u32_max);
- const wl = Number(value & _u32_max);
- const h = isLE4 ? 4 : 0;
- const l = isLE4 ? 0 : 4;
- view.setUint32(byteOffset + h, wh, isLE4);
- view.setUint32(byteOffset + l, wl, isLE4);
+ // node_modules/@jsr/noble__hashes/src/_md.js
+ function Chi(a, b, c) {
+ return a & b ^ ~a & c;
}
- var SHA2 = class extends Hash {
- constructor(blockLen, outputLen, padOffset, isLE4) {
- super();
+ function Maj(a, b, c) {
+ return a & b ^ a & c ^ b & c;
+ }
+ var HashMD = class {
+ blockLen;
+ outputLen;
+ padOffset;
+ isLE;
+ buffer;
+ view;
+ finished = false;
+ length = 0;
+ pos = 0;
+ destroyed = false;
+ constructor(blockLen, outputLen, padOffset, isLE2) {
this.blockLen = blockLen;
this.outputLen = outputLen;
this.padOffset = padOffset;
- this.isLE = isLE4;
- this.finished = false;
- this.length = 0;
- this.pos = 0;
- this.destroyed = false;
+ this.isLE = isLE2;
this.buffer = new Uint8Array(blockLen);
this.view = createView(this.buffer);
}
update(data) {
- exists(this);
+ aexists(this);
+ abytes(data);
const { view, buffer, blockLen } = this;
- data = toBytes(data);
const len = data.length;
for (let pos = 0; pos < len; ) {
const take = Math.min(blockLen - this.pos, len - pos);
if (take === blockLen) {
@@ -201,33 +265,33 @@
this.roundClean();
return this;
}
digestInto(out) {
- exists(this);
- output(out, this);
+ aexists(this);
+ aoutput(out, this);
this.finished = true;
- const { buffer, view, blockLen, isLE: isLE4 } = this;
+ const { buffer, view, blockLen, isLE: isLE2 } = this;
let { pos } = this;
buffer[pos++] = 128;
- this.buffer.subarray(pos).fill(0);
+ clean(this.buffer.subarray(pos));
if (this.padOffset > blockLen - pos) {
this.process(view, 0);
pos = 0;
}
for (let i2 = pos; i2 < blockLen; i2++)
buffer[i2] = 0;
- setBigUint64(view, blockLen - 8, BigInt(this.length * 8), isLE4);
+ view.setBigUint64(blockLen - 8, BigInt(this.length * 8), isLE2);
this.process(view, 0);
const oview = createView(out);
const len = this.outputLen;
if (len % 4)
- throw new Error("_sha2: outputLen should be aligned to 32bit");
+ throw new Error("_sha2: outputLen must be aligned to 32bit");
const outLen = len / 4;
const state = this.get();
if (outLen > state.length)
throw new Error("_sha2: outputLen bigger than state");
for (let i2 = 0; i2 < outLen; i2++)
- oview.setUint32(4 * i2, state[i2], isLE4);
+ oview.setUint32(4 * i2, state[i2], isLE2);
}
digest() {
const { buffer, outputLen } = this;
this.digestInto(buffer);
@@ -235,25 +299,39 @@
this.destroy();
return res;
}
_cloneInto(to) {
- to || (to = new this.constructor());
+ to ||= new this.constructor();
to.set(...this.get());
const { blockLen, buffer, length, finished, destroyed, pos } = this;
+ to.destroyed = destroyed;
+ to.finished = finished;
to.length = length;
to.pos = pos;
- to.finished = finished;
- to.destroyed = destroyed;
if (length % blockLen)
to.buffer.set(buffer);
return to;
}
+ clone() {
+ return this._cloneInto();
+ }
};
+ var SHA256_IV = /* @__PURE__ */ Uint32Array.from([
+ 1779033703,
+ 3144134277,
+ 1013904242,
+ 2773480762,
+ 1359893119,
+ 2600822924,
+ 528734635,
+ 1541459225
+ ]);
- // node_modules/@noble/curves/node_modules/@noble/hashes/esm/sha256.js
- var Chi = (a, b, c) => a & b ^ ~a & c;
- var Maj = (a, b, c) => a & b ^ a & c ^ b & c;
- var SHA256_K = /* @__PURE__ */ new Uint32Array([
+ // node_modules/@jsr/noble__hashes/src/_u64.js
+ var U32_MASK64 = /* @__PURE__ */ BigInt(2 ** 32 - 1);
+
+ // node_modules/@jsr/noble__hashes/src/sha2.js
+ var SHA256_K = /* @__PURE__ */ Uint32Array.from([
1116352408,
1899447441,
3049323471,
3921009573,
@@ -317,34 +395,25 @@
2756734187,
3204031479,
3329325298
]);
- var IV = /* @__PURE__ */ new Uint32Array([
- 1779033703,
- 3144134277,
- 1013904242,
- 2773480762,
- 1359893119,
- 2600822924,
- 528734635,
- 1541459225
- ]);
var SHA256_W = /* @__PURE__ */ new Uint32Array(64);
- var SHA256 = class extends SHA2 {
- constructor() {
- super(64, 32, 8, false);
- this.A = IV[0] | 0;
- this.B = IV[1] | 0;
- this.C = IV[2] | 0;
- this.D = IV[3] | 0;
- this.E = IV[4] | 0;
- this.F = IV[5] | 0;
- this.G = IV[6] | 0;
- this.H = IV[7] | 0;
+ var SHA2_32B = class extends HashMD {
+ constructor(outputLen) {
+ super(64, outputLen, 8, false);
}
get() {
const { A, B, C, D, E, F, G, H } = this;
- return [A, B, C, D, E, F, G, H];
+ return [
+ A,
+ B,
+ C,
+ D,
+ E,
+ F,
+ G,
+ H
+ ];
}
set(A, B, C, D, E, F, G, H) {
this.A = A | 0;
this.B = B | 0;
@@ -390,190 +459,140 @@
H = H + this.H | 0;
this.set(A, B, C, D, E, F, G, H);
}
roundClean() {
- SHA256_W.fill(0);
+ clean(SHA256_W);
}
destroy() {
this.set(0, 0, 0, 0, 0, 0, 0, 0);
- this.buffer.fill(0);
+ clean(this.buffer);
}
};
- var sha256 = /* @__PURE__ */ wrapConstructor(() => new SHA256());
+ var _SHA256 = class extends SHA2_32B {
+ A = SHA256_IV[0] | 0;
+ B = SHA256_IV[1] | 0;
+ C = SHA256_IV[2] | 0;
+ D = SHA256_IV[3] | 0;
+ E = SHA256_IV[4] | 0;
+ F = SHA256_IV[5] | 0;
+ G = SHA256_IV[6] | 0;
+ H = SHA256_IV[7] | 0;
+ constructor() {
+ super(32);
+ }
+ };
+ var sha256 = /* @__PURE__ */ createHasher(() => new _SHA256(), /* @__PURE__ */ oidNist(1));
- // node_modules/@noble/curves/esm/abstract/utils.js
- var utils_exports = {};
- __export(utils_exports, {
- bitGet: () => bitGet,
- bitLen: () => bitLen,
- bitMask: () => bitMask,
- bitSet: () => bitSet,
- bytesToHex: () => bytesToHex,
- bytesToNumberBE: () => bytesToNumberBE,
- bytesToNumberLE: () => bytesToNumberLE,
- concatBytes: () => concatBytes2,
- createHmacDrbg: () => createHmacDrbg,
- ensureBytes: () => ensureBytes,
- equalBytes: () => equalBytes,
- hexToBytes: () => hexToBytes,
- hexToNumber: () => hexToNumber,
- numberToBytesBE: () => numberToBytesBE,
- numberToBytesLE: () => numberToBytesLE,
- numberToHexUnpadded: () => numberToHexUnpadded,
- numberToVarBytesBE: () => numberToVarBytesBE,
- utf8ToBytes: () => utf8ToBytes2,
- validateObject: () => validateObject
- });
- var _0n = BigInt(0);
- var _1n = BigInt(1);
- var _2n = BigInt(2);
- var u8a2 = (a) => a instanceof Uint8Array;
- var hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i2) => i2.toString(16).padStart(2, "0"));
- function bytesToHex(bytes4) {
- if (!u8a2(bytes4))
- throw new Error("Uint8Array expected");
- let hex2 = "";
- for (let i2 = 0; i2 < bytes4.length; i2++) {
- hex2 += hexes[bytes4[i2]];
+ // node_modules/@noble/curves/src/utils.js
+ var _0n = /* @__PURE__ */ BigInt(0);
+ var _1n = /* @__PURE__ */ BigInt(1);
+ function abool(value, title = "") {
+ if (typeof value !== "boolean") {
+ const prefix = title && `"${title}" `;
+ throw new Error(prefix + "expected boolean, got type=" + typeof value);
}
- return hex2;
+ return value;
}
- function numberToHexUnpadded(num) {
- const hex2 = num.toString(16);
- return hex2.length & 1 ? `0${hex2}` : hex2;
+ function abignumber(n) {
+ if (typeof n === "bigint") {
+ if (!isPosBig(n))
+ throw new Error("positive bigint expected, got " + n);
+ } else
+ anumber(n);
+ return n;
}
+ function numberToHexUnpadded(num2) {
+ const hex2 = abignumber(num2).toString(16);
+ return hex2.length & 1 ? "0" + hex2 : hex2;
+ }
function hexToNumber(hex2) {
if (typeof hex2 !== "string")
throw new Error("hex string expected, got " + typeof hex2);
- return BigInt(hex2 === "" ? "0" : `0x${hex2}`);
+ return hex2 === "" ? _0n : BigInt("0x" + hex2);
}
- function hexToBytes(hex2) {
- if (typeof hex2 !== "string")
- throw new Error("hex string expected, got " + typeof hex2);
- const len = hex2.length;
- if (len % 2)
- throw new Error("padded hex string expected, got unpadded hex of length " + len);
- const array = new Uint8Array(len / 2);
- for (let i2 = 0; i2 < array.length; i2++) {
- const j = i2 * 2;
- const hexByte = hex2.slice(j, j + 2);
- const byte = Number.parseInt(hexByte, 16);
- if (Number.isNaN(byte) || byte < 0)
- throw new Error("Invalid byte sequence");
- array[i2] = byte;
- }
- return array;
+ function bytesToNumberBE(bytes) {
+ return hexToNumber(bytesToHex(bytes));
}
- function bytesToNumberBE(bytes4) {
- return hexToNumber(bytesToHex(bytes4));
+ function bytesToNumberLE(bytes) {
+ return hexToNumber(bytesToHex(copyBytes(abytes(bytes)).reverse()));
}
- function bytesToNumberLE(bytes4) {
- if (!u8a2(bytes4))
- throw new Error("Uint8Array expected");
- return hexToNumber(bytesToHex(Uint8Array.from(bytes4).reverse()));
- }
function numberToBytesBE(n, len) {
- return hexToBytes(n.toString(16).padStart(len * 2, "0"));
+ anumber(len);
+ n = abignumber(n);
+ const res = hexToBytes(n.toString(16).padStart(len * 2, "0"));
+ if (res.length !== len)
+ throw new Error("number too large");
+ return res;
}
function numberToBytesLE(n, len) {
return numberToBytesBE(n, len).reverse();
}
- function numberToVarBytesBE(n) {
- return hexToBytes(numberToHexUnpadded(n));
+ function copyBytes(bytes) {
+ return Uint8Array.from(bytes);
}
- function ensureBytes(title, hex2, expectedLength) {
- let res;
- if (typeof hex2 === "string") {
- try {
- res = hexToBytes(hex2);
- } catch (e) {
- throw new Error(`${title} must be valid hex string, got "${hex2}". Cause: ${e}`);
+ function asciiToBytes(ascii) {
+ return Uint8Array.from(ascii, (c, i2) => {
+ const charCode = c.charCodeAt(0);
+ if (c.length !== 1 || charCode > 127) {
+ throw new Error(`string contains non-ASCII character "${ascii[i2]}" with code ${charCode} at position ${i2}`);
}
- } else if (u8a2(hex2)) {
- res = Uint8Array.from(hex2);
- } else {
- throw new Error(`${title} must be hex string or Uint8Array`);
- }
- const len = res.length;
- if (typeof expectedLength === "number" && len !== expectedLength)
- throw new Error(`${title} expected ${expectedLength} bytes, got ${len}`);
- return res;
- }
- function concatBytes2(...arrays) {
- const r = new Uint8Array(arrays.reduce((sum, a) => sum + a.length, 0));
- let pad2 = 0;
- arrays.forEach((a) => {
- if (!u8a2(a))
- throw new Error("Uint8Array expected");
- r.set(a, pad2);
- pad2 += a.length;
+ return charCode;
});
- return r;
}
- function equalBytes(b1, b2) {
- if (b1.length !== b2.length)
- return false;
- for (let i2 = 0; i2 < b1.length; i2++)
- if (b1[i2] !== b2[i2])
- return false;
- return true;
+ var isPosBig = (n) => typeof n === "bigint" && _0n <= n;
+ function inRange(n, min, max) {
+ return isPosBig(n) && isPosBig(min) && isPosBig(max) && min <= n && n < max;
}
- function utf8ToBytes2(str) {
- if (typeof str !== "string")
- throw new Error(`utf8ToBytes expected string, got ${typeof str}`);
- return new Uint8Array(new TextEncoder().encode(str));
+ function aInRange(title, n, min, max) {
+ if (!inRange(n, min, max))
+ throw new Error("expected valid " + title + ": " + min + " <= n < " + max + ", got " + n);
}
function bitLen(n) {
let len;
for (len = 0; n > _0n; n >>= _1n, len += 1)
;
return len;
}
- function bitGet(n, pos) {
- return n >> BigInt(pos) & _1n;
- }
- var bitSet = (n, pos, value) => {
- return n | (value ? _1n : _0n) << BigInt(pos);
- };
- var bitMask = (n) => (_2n << BigInt(n - 1)) - _1n;
- var u8n = (data) => new Uint8Array(data);
- var u8fr = (arr) => Uint8Array.from(arr);
+ var bitMask = (n) => (_1n << BigInt(n)) - _1n;
function createHmacDrbg(hashLen, qByteLen, hmacFn) {
- if (typeof hashLen !== "number" || hashLen < 2)
- throw new Error("hashLen must be a number");
- if (typeof qByteLen !== "number" || qByteLen < 2)
- throw new Error("qByteLen must be a number");
+ anumber(hashLen, "hashLen");
+ anumber(qByteLen, "qByteLen");
if (typeof hmacFn !== "function")
throw new Error("hmacFn must be a function");
+ const u8n = (len) => new Uint8Array(len);
+ const NULL = Uint8Array.of();
+ const byte0 = Uint8Array.of(0);
+ const byte1 = Uint8Array.of(1);
+ const _maxDrbgIters = 1e3;
let v = u8n(hashLen);
let k = u8n(hashLen);
let i2 = 0;
const reset = () => {
v.fill(1);
k.fill(0);
i2 = 0;
};
- const h = (...b) => hmacFn(k, v, ...b);
- const reseed = (seed = u8n()) => {
- k = h(u8fr([0]), seed);
+ const h = (...msgs) => hmacFn(k, concatBytes(v, ...msgs));
+ const reseed = (seed = NULL) => {
+ k = h(byte0, seed);
v = h();
if (seed.length === 0)
return;
- k = h(u8fr([1]), seed);
+ k = h(byte1, seed);
v = h();
};
const gen = () => {
- if (i2++ >= 1e3)
- throw new Error("drbg: tried 1000 values");
+ if (i2++ >= _maxDrbgIters)
+ throw new Error("drbg: tried max amount of iterations");
let len = 0;
const out = [];
while (len < qByteLen) {
v = h();
const sl = v.slice();
out.push(sl);
len += v.length;
}
- return concatBytes2(...out);
+ return concatBytes(...out);
};
const genUntil = (seed, pred) => {
reset();
reseed(seed);
@@ -584,79 +603,64 @@
return res;
};
return genUntil;
}
- var validatorFns = {
- bigint: (val) => typeof val === "bigint",
- function: (val) => typeof val === "function",
- boolean: (val) => typeof val === "boolean",
- string: (val) => typeof val === "string",
- stringOrUint8Array: (val) => typeof val === "string" || val instanceof Uint8Array,
- isSafeInteger: (val) => Number.isSafeInteger(val),
- array: (val) => Array.isArray(val),
- field: (val, object) => object.Fp.isValid(val),
- hash: (val) => typeof val === "function" && Number.isSafeInteger(val.outputLen)
- };
- function validateObject(object, validators, optValidators = {}) {
- const checkField = (fieldName, type, isOptional) => {
- const checkVal = validatorFns[type];
- if (typeof checkVal !== "function")
- throw new Error(`Invalid validator "${type}", expected function`);
+ function validateObject(object, fields = {}, optFields = {}) {
+ if (!object || typeof object !== "object")
+ throw new Error("expected valid options object");
+ function checkField(fieldName, expectedType, isOpt) {
const val = object[fieldName];
- if (isOptional && val === void 0)
+ if (isOpt && val === void 0)
return;
- if (!checkVal(val, object)) {
- throw new Error(`Invalid param ${String(fieldName)}=${val} (${typeof val}), expected ${type}`);
- }
+ const current = typeof val;
+ if (current !== expectedType || val === null)
+ throw new Error(`param "${fieldName}" 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);
+ }
+ function memoized(fn) {
+ const map = /* @__PURE__ */ new WeakMap();
+ return (arg, ...args) => {
+ const val = map.get(arg);
+ if (val !== void 0)
+ return val;
+ const computed = fn(arg, ...args);
+ map.set(arg, computed);
+ return computed;
};
- for (const [fieldName, type] of Object.entries(validators))
- checkField(fieldName, type, false);
- for (const [fieldName, type] of Object.entries(optValidators))
- checkField(fieldName, type, true);
- return object;
}
- // node_modules/@noble/curves/esm/abstract/modular.js
- var _0n2 = BigInt(0);
- var _1n2 = BigInt(1);
- var _2n2 = BigInt(2);
- var _3n = BigInt(3);
- var _4n = BigInt(4);
- var _5n = BigInt(5);
- var _8n = BigInt(8);
- var _9n = BigInt(9);
- var _16n = BigInt(16);
+ // node_modules/@noble/curves/src/abstract/modular.js
+ 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 _16n = /* @__PURE__ */ BigInt(16);
function mod(a, b) {
const result = a % b;
return result >= _0n2 ? result : b + result;
}
- function pow(num, power, modulo) {
- if (modulo <= _0n2 || power < _0n2)
- throw new Error("Expected power/modulo > 0");
- if (modulo === _1n2)
- return _0n2;
- let res = _1n2;
- while (power > _0n2) {
- if (power & _1n2)
- res = res * num % modulo;
- num = num * num % modulo;
- power >>= _1n2;
- }
- return res;
- }
function pow2(x, power, modulo) {
let res = x;
while (power-- > _0n2) {
res *= res;
res %= modulo;
}
return res;
}
- function invert(number4, modulo) {
- if (number4 === _0n2 || modulo <= _0n2) {
- throw new Error(`invert: expected positive integers, got n=${number4} mod=${modulo}`);
- }
- let a = mod(number4, modulo);
+ function invert(number, modulo) {
+ if (number === _0n2)
+ throw new Error("invert: expected non-zero number");
+ if (modulo <= _0n2)
+ throw new Error("invert: expected positive modulus, got " + modulo);
+ let a = mod(number, modulo);
let b = modulo;
let x = _0n2, y = _1n2, u = _1n2, v = _0n2;
while (a !== _0n2) {
const q = b / a;
@@ -669,75 +673,106 @@
if (gcd2 !== _1n2)
throw new Error("invert: does not exist");
return mod(x, modulo);
}
+ function assertIsSquare(Fp, root, n) {
+ if (!Fp.eql(Fp.sqr(root), n))
+ throw new Error("Cannot find square root");
+ }
+ function sqrt3mod4(Fp, n) {
+ const p1div4 = (Fp.ORDER + _1n2) / _4n;
+ const root = Fp.pow(n, p1div4);
+ assertIsSquare(Fp, root, n);
+ return root;
+ }
+ function sqrt5mod8(Fp, n) {
+ const p5div8 = (Fp.ORDER - _5n) / _8n;
+ const n2 = Fp.mul(n, _2n);
+ const v = Fp.pow(n2, p5div8);
+ const nv = Fp.mul(n, v);
+ const i2 = Fp.mul(Fp.mul(nv, _2n), v);
+ const root = Fp.mul(nv, Fp.sub(i2, Fp.ONE));
+ assertIsSquare(Fp, 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 (Fp, n) => {
+ let tv1 = Fp.pow(n, c4);
+ let tv2 = Fp.mul(tv1, c1);
+ const tv3 = Fp.mul(tv1, c2);
+ const tv4 = Fp.mul(tv1, c3);
+ const e1 = Fp.eql(Fp.sqr(tv2), n);
+ const e2 = Fp.eql(Fp.sqr(tv3), n);
+ tv1 = Fp.cmov(tv1, tv2, e1);
+ tv2 = Fp.cmov(tv4, tv3, e2);
+ const e3 = Fp.eql(Fp.sqr(tv2), n);
+ const root = Fp.cmov(tv1, tv2, e3);
+ assertIsSquare(Fp, root, n);
+ return root;
+ };
+ }
function tonelliShanks(P) {
- const legendreC = (P - _1n2) / _2n2;
- let Q, S, Z;
- for (Q = P - _1n2, S = 0; Q % _2n2 === _0n2; Q /= _2n2, S++)
- ;
- for (Z = _2n2; Z < P && pow(Z, legendreC, P) !== P - _1n2; Z++)
- ;
- if (S === 1) {
- const p1div4 = (P + _1n2) / _4n;
- return function tonelliFast(Fp2, n) {
- const root = Fp2.pow(n, p1div4);
- if (!Fp2.eql(Fp2.sqr(root), n))
- throw new Error("Cannot find square root");
- return root;
- };
+ if (P < _3n)
+ throw new Error("sqrt is not defined for small field");
+ let Q = P - _1n2;
+ let S = 0;
+ while (Q % _2n === _0n2) {
+ Q /= _2n;
+ S++;
}
- const Q1div2 = (Q + _1n2) / _2n2;
- return function tonelliSlow(Fp2, n) {
- if (Fp2.pow(n, legendreC) === Fp2.neg(Fp2.ONE))
+ 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(Fp, n) {
+ if (Fp.is0(n))
+ return n;
+ if (FpLegendre(Fp, n) !== 1)
throw new Error("Cannot find square root");
- let r = S;
- let g = Fp2.pow(Fp2.mul(Fp2.ONE, Z), Q);
- let x = Fp2.pow(n, Q1div2);
- let b = Fp2.pow(n, Q);
- while (!Fp2.eql(b, Fp2.ONE)) {
- if (Fp2.eql(b, Fp2.ZERO))
- return Fp2.ZERO;
- let m = 1;
- for (let t2 = Fp2.sqr(b); m < r; m++) {
- if (Fp2.eql(t2, Fp2.ONE))
- break;
- t2 = Fp2.sqr(t2);
+ let M = S;
+ let c = Fp.mul(Fp.ONE, cc);
+ let t = Fp.pow(n, Q);
+ let R = Fp.pow(n, Q1div2);
+ while (!Fp.eql(t, Fp.ONE)) {
+ if (Fp.is0(t))
+ return Fp.ZERO;
+ let i2 = 1;
+ let t_tmp = Fp.sqr(t);
+ while (!Fp.eql(t_tmp, Fp.ONE)) {
+ i2++;
+ t_tmp = Fp.sqr(t_tmp);
+ if (i2 === M)
+ throw new Error("Cannot find square root");
}
- const ge2 = Fp2.pow(g, _1n2 << BigInt(r - m - 1));
- g = Fp2.sqr(ge2);
- x = Fp2.mul(x, ge2);
- b = Fp2.mul(b, g);
- r = m;
+ const exponent = _1n2 << BigInt(M - i2 - 1);
+ const b = Fp.pow(c, exponent);
+ M = i2;
+ c = Fp.sqr(b);
+ t = Fp.mul(t, c);
+ R = Fp.mul(R, b);
}
- return x;
+ return R;
};
}
function FpSqrt(P) {
- if (P % _4n === _3n) {
- const p1div4 = (P + _1n2) / _4n;
- return function sqrt3mod4(Fp2, n) {
- const root = Fp2.pow(n, p1div4);
- if (!Fp2.eql(Fp2.sqr(root), n))
- throw new Error("Cannot find square root");
- return root;
- };
- }
- if (P % _8n === _5n) {
- const c1 = (P - _5n) / _8n;
- return function sqrt5mod8(Fp2, n) {
- const n2 = Fp2.mul(n, _2n2);
- const v = Fp2.pow(n2, c1);
- const nv = Fp2.mul(n, v);
- const i2 = Fp2.mul(Fp2.mul(nv, _2n2), v);
- const root = Fp2.mul(nv, Fp2.sub(i2, Fp2.ONE));
- if (!Fp2.eql(Fp2.sqr(root), n))
- throw new Error("Cannot find square root");
- return root;
- };
- }
- if (P % _16n === _9n) {
- }
+ if (P % _4n === _3n)
+ return sqrt3mod4;
+ if (P % _8n === _5n)
+ return sqrt5mod8;
+ if (P % _16n === _9n)
+ return sqrt9mod16(P);
return tonelliShanks(P);
}
var FIELD_FIELDS = [
"create",
@@ -760,103 +795,203 @@
];
function validateField(field) {
const initial = {
ORDER: "bigint",
- MASK: "bigint",
- BYTES: "isSafeInteger",
- BITS: "isSafeInteger"
+ BYTES: "number",
+ BITS: "number"
};
const opts = FIELD_FIELDS.reduce((map, val) => {
map[val] = "function";
return map;
}, initial);
- return validateObject(field, opts);
+ validateObject(field, opts);
+ return field;
}
- function FpPow(f, num, power) {
+ function FpPow(Fp, num2, power) {
if (power < _0n2)
- throw new Error("Expected power > 0");
+ throw new Error("invalid exponent, negatives unsupported");
if (power === _0n2)
- return f.ONE;
+ return Fp.ONE;
if (power === _1n2)
- return num;
- let p = f.ONE;
- let d = num;
+ return num2;
+ let p = Fp.ONE;
+ let d = num2;
while (power > _0n2) {
if (power & _1n2)
- p = f.mul(p, d);
- d = f.sqr(d);
+ p = Fp.mul(p, d);
+ d = Fp.sqr(d);
power >>= _1n2;
}
return p;
}
- function FpInvertBatch(f, nums) {
- const tmp = new Array(nums.length);
- const lastMultiplied = nums.reduce((acc, num, i2) => {
- if (f.is0(num))
+ function FpInvertBatch(Fp, nums, passZero = false) {
+ const inverted = new Array(nums.length).fill(passZero ? Fp.ZERO : void 0);
+ const multipliedAcc = nums.reduce((acc, num2, i2) => {
+ if (Fp.is0(num2))
return acc;
- tmp[i2] = acc;
- return f.mul(acc, num);
- }, f.ONE);
- const inverted = f.inv(lastMultiplied);
- nums.reduceRight((acc, num, i2) => {
- if (f.is0(num))
+ inverted[i2] = acc;
+ return Fp.mul(acc, num2);
+ }, Fp.ONE);
+ const invertedAcc = Fp.inv(multipliedAcc);
+ nums.reduceRight((acc, num2, i2) => {
+ if (Fp.is0(num2))
return acc;
- tmp[i2] = f.mul(acc, tmp[i2]);
- return f.mul(acc, num);
- }, inverted);
- return tmp;
+ inverted[i2] = Fp.mul(acc, inverted[i2]);
+ return Fp.mul(acc, num2);
+ }, invertedAcc);
+ return inverted;
}
+ function FpLegendre(Fp, n) {
+ const p1mod2 = (Fp.ORDER - _1n2) / _2n;
+ const powered = Fp.pow(n, p1mod2);
+ const yes = Fp.eql(powered, Fp.ONE);
+ const zero = Fp.eql(powered, Fp.ZERO);
+ const no = Fp.eql(powered, Fp.neg(Fp.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)
+ anumber(nBitLength);
const _nBitLength = nBitLength !== void 0 ? nBitLength : n.toString(2).length;
const nByteLength = Math.ceil(_nBitLength / 8);
- return { nBitLength: _nBitLength, nByteLength };
+ return {
+ nBitLength: _nBitLength,
+ nByteLength
+ };
}
- function Field(ORDER, bitLen2, isLE4 = false, redef = {}) {
- if (ORDER <= _0n2)
- throw new Error(`Expected Field ORDER > 0, got ${ORDER}`);
- const { nBitLength: BITS, nByteLength: BYTES } = nLength(ORDER, bitLen2);
- if (BYTES > 2048)
- throw new Error("Field lengths over 2048 bytes are not supported");
- const sqrtP = FpSqrt(ORDER);
- const f = Object.freeze({
- ORDER,
- BITS,
- BYTES,
- MASK: bitMask(BITS),
- ZERO: _0n2,
- ONE: _1n2,
- create: (num) => mod(num, ORDER),
- isValid: (num) => {
- if (typeof num !== "bigint")
- throw new Error(`Invalid field element: expected bigint, got ${typeof num}`);
- return _0n2 <= num && num < ORDER;
- },
- is0: (num) => num === _0n2,
- isOdd: (num) => (num & _1n2) === _1n2,
- neg: (num) => mod(-num, ORDER),
- eql: (lhs, rhs) => lhs === rhs,
- sqr: (num) => mod(num * num, ORDER),
- add: (lhs, rhs) => mod(lhs + rhs, ORDER),
- sub: (lhs, rhs) => mod(lhs - rhs, ORDER),
- mul: (lhs, rhs) => mod(lhs * rhs, ORDER),
- pow: (num, power) => FpPow(f, num, power),
- div: (lhs, rhs) => mod(lhs * invert(rhs, ORDER), ORDER),
- sqrN: (num) => num * num,
- addN: (lhs, rhs) => lhs + rhs,
- subN: (lhs, rhs) => lhs - rhs,
- mulN: (lhs, rhs) => lhs * rhs,
- inv: (num) => invert(num, ORDER),
- sqrt: redef.sqrt || ((n) => sqrtP(f, n)),
- invertBatch: (lst) => FpInvertBatch(f, lst),
- cmov: (a, b, c) => c ? b : a,
- toBytes: (num) => isLE4 ? numberToBytesLE(num, BYTES) : numberToBytesBE(num, BYTES),
- fromBytes: (bytes4) => {
- if (bytes4.length !== BYTES)
- throw new Error(`Fp.fromBytes: expected ${BYTES}, got ${bytes4.length}`);
- return isLE4 ? bytesToNumberLE(bytes4) : bytesToNumberBE(bytes4);
+ var _Field = class {
+ ORDER;
+ BITS;
+ BYTES;
+ isLE;
+ ZERO = _0n2;
+ ONE = _1n2;
+ _lengths;
+ _sqrt;
+ _mod;
+ constructor(ORDER, opts = {}) {
+ if (ORDER <= _0n2)
+ throw new Error("invalid field: expected ORDER > 0, 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")
+ this.sqrt = opts.sqrt;
+ if (typeof opts.isLE === "boolean")
+ this.isLE = opts.isLE;
+ if (opts.allowedLengths)
+ this._lengths = opts.allowedLengths?.slice();
+ if (typeof opts.modFromBytes === "boolean")
+ this._mod = opts.modFromBytes;
}
- });
- return Object.freeze(f);
+ 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;
+ this._sqrt = void 0;
+ Object.preventExtensions(this);
+ }
+ create(num2) {
+ return mod(num2, this.ORDER);
+ }
+ isValid(num2) {
+ if (typeof num2 !== "bigint")
+ throw new Error("invalid field element: expected bigint, got " + typeof num2);
+ return _0n2 <= num2 && num2 < this.ORDER;
+ }
+ is0(num2) {
+ return num2 === _0n2;
+ }
+ 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 FpPow(this, num2, power);
+ }
+ div(lhs, rhs) {
+ return mod(lhs * invert(rhs, this.ORDER), this.ORDER);
+ }
+ 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) {
+ if (!this._sqrt)
+ this._sqrt = FpSqrt(this.ORDER);
+ return this._sqrt(this, num2);
+ }
+ toBytes(num2) {
+ return this.isLE ? numberToBytesLE(num2, this.BYTES) : numberToBytesBE(num2, this.BYTES);
+ }
+ fromBytes(bytes, skipValidation = false) {
+ abytes(bytes);
+ const { _lengths: allowedLengths, BYTES, isLE: isLE2, ORDER, _mod: modFromBytes } = this;
+ if (allowedLengths) {
+ if (!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, isLE2 ? 0 : padded.length - bytes.length);
+ bytes = padded;
+ }
+ if (bytes.length !== BYTES)
+ throw new Error("Field.fromBytes: expected " + BYTES + " bytes, got " + bytes.length);
+ let scalar = isLE2 ? 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;
+ }
+ invertBatch(lst) {
+ return FpInvertBatch(this, lst);
+ }
+ cmov(a, b, condition) {
+ return condition ? b : a;
+ }
+ };
+ function Field(ORDER, opts = {}) {
+ return new _Field(ORDER, opts);
}
function getFieldBytesLength(fieldOrder) {
if (typeof fieldOrder !== "bigint")
throw new Error("field order must be bigint");
@@ -866,1158 +1001,1522 @@
function getMinHashLength(fieldOrder) {
const length = getFieldBytesLength(fieldOrder);
return length + Math.ceil(length / 2);
}
- function mapHashToField(key, fieldOrder, isLE4 = false) {
+ function mapHashToField(key, fieldOrder, isLE2 = false) {
+ abytes(key);
const len = key.length;
const fieldLen = getFieldBytesLength(fieldOrder);
const minLen = getMinHashLength(fieldOrder);
if (len < 16 || len < minLen || len > 1024)
- throw new Error(`expected ${minLen}-1024 bytes of input, got ${len}`);
- const num = isLE4 ? bytesToNumberBE(key) : bytesToNumberLE(key);
- const reduced = mod(num, fieldOrder - _1n2) + _1n2;
- return isLE4 ? numberToBytesLE(reduced, fieldLen) : numberToBytesBE(reduced, fieldLen);
+ throw new Error("expected " + minLen + "-1024 bytes of input, got " + len);
+ const num2 = isLE2 ? bytesToNumberLE(key) : bytesToNumberBE(key);
+ const reduced = mod(num2, fieldOrder - _1n2) + _1n2;
+ return isLE2 ? numberToBytesLE(reduced, fieldLen) : numberToBytesBE(reduced, fieldLen);
}
- // node_modules/@noble/curves/esm/abstract/curve.js
- var _0n3 = BigInt(0);
- var _1n3 = BigInt(1);
- function wNAF(c, bits) {
- const constTimeNegate = (condition, item) => {
- const neg = item.negate();
- return condition ? neg : item;
+ // node_modules/@noble/curves/src/abstract/curve.js
+ var _0n3 = /* @__PURE__ */ BigInt(0);
+ var _1n3 = /* @__PURE__ */ BigInt(1);
+ function negateCt(condition, item) {
+ const neg = item.negate();
+ return condition ? neg : item;
+ }
+ function normalizeZ(c, points) {
+ const invertedZs = FpInvertBatch(c.Fp, points.map((p) => p.Z));
+ return points.map((p, i2) => c.fromAffine(p.toAffine(invertedZs[i2])));
+ }
+ function validateW(W, bits) {
+ if (!Number.isSafeInteger(W) || W <= 0 || W > bits)
+ throw new Error("invalid window size, expected [1.." + bits + "], got W=" + W);
+ }
+ function calcWOpts(W, scalarBits) {
+ validateW(W, scalarBits);
+ const windows = Math.ceil(scalarBits / W) + 1;
+ const windowSize = 2 ** (W - 1);
+ const maxNumber = 2 ** W;
+ const mask = bitMask(W);
+ const shiftBy = BigInt(W);
+ return {
+ windows,
+ windowSize,
+ mask,
+ maxNumber,
+ shiftBy
};
- const opts = (W) => {
- const windows = Math.ceil(bits / W) + 1;
- const windowSize = 2 ** (W - 1);
- return { windows, windowSize };
- };
+ }
+ function calcOffsets(n, window, wOpts) {
+ const { windowSize, mask, maxNumber, shiftBy } = wOpts;
+ let wbits = Number(n & mask);
+ let nextN = n >> shiftBy;
+ if (wbits > windowSize) {
+ wbits -= maxNumber;
+ nextN += _1n3;
+ }
+ const offsetStart = window * windowSize;
+ const offset = offsetStart + Math.abs(wbits) - 1;
+ const isZero = wbits === 0;
+ const isNeg = wbits < 0;
+ const isNegF = window % 2 !== 0;
+ const offsetF = offsetStart;
return {
- constTimeNegate,
- unsafeLadder(elm, n) {
- let p = c.ZERO;
- let d = elm;
- while (n > _0n3) {
- if (n & _1n3)
- p = p.add(d);
- d = d.double();
- n >>= _1n3;
- }
- return p;
- },
- precomputeWindow(elm, W) {
- const { windows, windowSize } = opts(W);
- const points = [];
- let p = elm;
- let base = p;
- for (let window = 0; window < windows; window++) {
- base = p;
+ nextN,
+ offset,
+ isZero,
+ isNeg,
+ isNegF,
+ offsetF
+ };
+ }
+ var pointPrecomputes = /* @__PURE__ */ new WeakMap();
+ var pointWindowSizes = /* @__PURE__ */ new WeakMap();
+ function getW(P) {
+ return pointWindowSizes.get(P) || 1;
+ }
+ function assert0(n) {
+ if (n !== _0n3)
+ throw new Error("invalid wNAF");
+ }
+ var wNAF = class {
+ BASE;
+ ZERO;
+ Fn;
+ bits;
+ constructor(Point, bits) {
+ this.BASE = Point.BASE;
+ this.ZERO = Point.ZERO;
+ this.Fn = Point.Fn;
+ this.bits = bits;
+ }
+ _unsafeLadder(elm, n, p = this.ZERO) {
+ let d = elm;
+ while (n > _0n3) {
+ if (n & _1n3)
+ p = p.add(d);
+ d = d.double();
+ n >>= _1n3;
+ }
+ return p;
+ }
+ precomputeWindow(point, W) {
+ const { windows, windowSize } = calcWOpts(W, this.bits);
+ const points = [];
+ let p = point;
+ let base = p;
+ for (let window = 0; window < windows; window++) {
+ base = p;
+ points.push(base);
+ for (let i2 = 1; i2 < windowSize; i2++) {
+ base = base.add(p);
points.push(base);
- for (let i2 = 1; i2 < windowSize; i2++) {
- base = base.add(p);
- points.push(base);
- }
- p = base.double();
}
- return points;
- },
- wNAF(W, precomputes, n) {
- const { windows, windowSize } = opts(W);
- let p = c.ZERO;
- let f = c.BASE;
- const mask = BigInt(2 ** W - 1);
- const maxNumber = 2 ** W;
- const shiftBy = BigInt(W);
- for (let window = 0; window < windows; window++) {
- const offset = window * windowSize;
- let wbits = Number(n & mask);
- n >>= shiftBy;
- if (wbits > windowSize) {
- wbits -= maxNumber;
- n += _1n3;
- }
- const offset1 = offset;
- const offset2 = offset + Math.abs(wbits) - 1;
- const cond1 = window % 2 !== 0;
- const cond2 = wbits < 0;
- if (wbits === 0) {
- f = f.add(constTimeNegate(cond1, precomputes[offset1]));
- } else {
- p = p.add(constTimeNegate(cond2, precomputes[offset2]));
- }
+ p = base.double();
+ }
+ return points;
+ }
+ wNAF(W, precomputes, n) {
+ if (!this.Fn.isValid(n))
+ throw new Error("invalid scalar");
+ let p = this.ZERO;
+ let f = this.BASE;
+ const wo = calcWOpts(W, this.bits);
+ for (let window = 0; window < wo.windows; window++) {
+ const { nextN, offset, isZero, isNeg, isNegF, offsetF } = calcOffsets(n, window, wo);
+ n = nextN;
+ if (isZero) {
+ f = f.add(negateCt(isNegF, precomputes[offsetF]));
+ } else {
+ p = p.add(negateCt(isNeg, precomputes[offset]));
}
- return { p, f };
- },
- wNAFCached(P, precomputesMap, n, transform) {
- const W = P._WINDOW_SIZE || 1;
- let comp = precomputesMap.get(P);
- if (!comp) {
- comp = this.precomputeWindow(P, W);
- if (W !== 1) {
- precomputesMap.set(P, transform(comp));
- }
+ }
+ assert0(n);
+ return {
+ p,
+ f
+ };
+ }
+ wNAFUnsafe(W, precomputes, n, acc = this.ZERO) {
+ const wo = calcWOpts(W, this.bits);
+ for (let window = 0; window < wo.windows; window++) {
+ if (n === _0n3)
+ break;
+ const { nextN, offset, isZero, isNeg } = calcOffsets(n, window, wo);
+ n = nextN;
+ if (isZero) {
+ continue;
+ } else {
+ const item = precomputes[offset];
+ acc = acc.add(isNeg ? item.negate() : item);
}
- return this.wNAF(W, comp, n);
}
+ assert0(n);
+ return acc;
+ }
+ getPrecomputes(W, point, transform) {
+ let comp = pointPrecomputes.get(point);
+ if (!comp) {
+ comp = this.precomputeWindow(point, W);
+ if (W !== 1) {
+ if (typeof transform === "function")
+ comp = transform(comp);
+ pointPrecomputes.set(point, comp);
+ }
+ }
+ return comp;
+ }
+ cached(point, scalar, transform) {
+ const W = getW(point);
+ return this.wNAF(W, this.getPrecomputes(W, point, transform), scalar);
+ }
+ unsafe(point, scalar, transform, prev) {
+ const W = getW(point);
+ if (W === 1)
+ return this._unsafeLadder(point, scalar, prev);
+ return this.wNAFUnsafe(W, this.getPrecomputes(W, point, transform), scalar, prev);
+ }
+ createCache(P, W) {
+ validateW(W, this.bits);
+ pointWindowSizes.set(P, W);
+ pointPrecomputes.delete(P);
+ }
+ hasCache(elm) {
+ return getW(elm) !== 1;
+ }
+ };
+ function mulEndoUnsafe(Point, point, k1, k2) {
+ let acc = point;
+ let p1 = Point.ZERO;
+ let p2 = Point.ZERO;
+ while (k1 > _0n3 || k2 > _0n3) {
+ if (k1 & _1n3)
+ p1 = p1.add(acc);
+ if (k2 & _1n3)
+ p2 = p2.add(acc);
+ acc = acc.double();
+ k1 >>= _1n3;
+ k2 >>= _1n3;
+ }
+ return {
+ p1,
+ p2
};
}
- function validateBasic(curve) {
- validateField(curve.Fp);
- validateObject(curve, {
- n: "bigint",
- h: "bigint",
- Gx: "field",
- Gy: "field"
- }, {
- nBitLength: "isSafeInteger",
- nByteLength: "isSafeInteger"
- });
- return Object.freeze({
- ...nLength(curve.n, curve.nBitLength),
- ...curve,
- ...{ p: curve.Fp.ORDER }
- });
+ function createField(order, field, isLE2) {
+ if (field) {
+ if (field.ORDER !== order)
+ throw new Error("Field.ORDER must match order: Fp == p, Fn == n");
+ validateField(field);
+ return field;
+ } else {
+ return Field(order, {
+ isLE: isLE2
+ });
+ }
}
+ function createCurveFields(type, CURVE, curveOpts = {}, FpFnLE) {
+ if (FpFnLE === void 0)
+ FpFnLE = type === "edwards";
+ if (!CURVE || typeof CURVE !== "object")
+ throw new Error(`expected valid ${type} CURVE object`);
+ for (const p of [
+ "p",
+ "n",
+ "h"
+ ]) {
+ const val = CURVE[p];
+ if (!(typeof val === "bigint" && val > _0n3))
+ throw new Error(`CURVE.${p} must be positive bigint`);
+ }
+ const Fp = 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 (!Fp.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,
+ Fn
+ };
+ }
+ function createKeygen(randomSecretKey, getPublicKey2) {
+ return function keygen(seed) {
+ const secretKey = randomSecretKey(seed);
+ return {
+ secretKey,
+ publicKey: getPublicKey2(secretKey)
+ };
+ };
+ }
- // node_modules/@noble/curves/esm/abstract/weierstrass.js
- function validatePointOpts(curve) {
- const opts = validateBasic(curve);
- validateObject(opts, {
- a: "field",
- b: "field"
- }, {
- allowedPrivateKeyLengths: "array",
- wrapPrivateKey: "boolean",
- isTorsionFree: "function",
- clearCofactor: "function",
- allowInfinityPoint: "boolean",
- fromBytes: "function",
- toBytes: "function"
- });
- const { endo, Fp: Fp2, a } = opts;
- if (endo) {
- if (!Fp2.eql(a, Fp2.ZERO)) {
- throw new Error("Endomorphism can only be defined for Koblitz curves that have a=0");
- }
- if (typeof endo !== "object" || typeof endo.beta !== "bigint" || typeof endo.splitScalar !== "function") {
- throw new Error("Expected endomorphism with beta: bigint and splitScalar: function");
- }
+ // node_modules/@noble/curves/src/abstract/hash-to-curve.js
+ var _DST_scalar = asciiToBytes("HashToScalar-");
+
+ // node_modules/@jsr/noble__hashes/src/hmac.js
+ var _HMAC = class {
+ oHash;
+ iHash;
+ blockLen;
+ outputLen;
+ finished = false;
+ destroyed = false;
+ constructor(hash, key) {
+ ahash(hash);
+ abytes(key, void 0, "key");
+ this.iHash = hash.create();
+ if (typeof this.iHash.update !== "function")
+ throw new Error("Expected instance of class which extends utils.Hash");
+ this.blockLen = this.iHash.blockLen;
+ this.outputLen = this.iHash.outputLen;
+ const blockLen = this.blockLen;
+ const pad2 = new Uint8Array(blockLen);
+ pad2.set(key.length > blockLen ? hash.create().update(key).digest() : key);
+ for (let i2 = 0; i2 < pad2.length; i2++)
+ pad2[i2] ^= 54;
+ this.iHash.update(pad2);
+ this.oHash = hash.create();
+ for (let i2 = 0; i2 < pad2.length; i2++)
+ pad2[i2] ^= 54 ^ 92;
+ this.oHash.update(pad2);
+ clean(pad2);
}
- return Object.freeze({ ...opts });
+ update(buf) {
+ aexists(this);
+ this.iHash.update(buf);
+ return this;
+ }
+ digestInto(out) {
+ aexists(this);
+ abytes(out, this.outputLen, "output");
+ this.finished = true;
+ this.iHash.digestInto(out);
+ this.oHash.update(out);
+ this.oHash.digestInto(out);
+ this.destroy();
+ }
+ digest() {
+ const out = new Uint8Array(this.oHash.outputLen);
+ this.digestInto(out);
+ return out;
+ }
+ _cloneInto(to) {
+ to ||= Object.create(Object.getPrototypeOf(this), {});
+ const { oHash, iHash, finished, destroyed, blockLen, outputLen } = this;
+ to = to;
+ to.finished = finished;
+ to.destroyed = destroyed;
+ to.blockLen = blockLen;
+ to.outputLen = outputLen;
+ to.oHash = oHash._cloneInto(to.oHash);
+ to.iHash = iHash._cloneInto(to.iHash);
+ return to;
+ }
+ clone() {
+ return this._cloneInto();
+ }
+ destroy() {
+ this.destroyed = true;
+ this.oHash.destroy();
+ this.iHash.destroy();
+ }
+ };
+ var hmac = (hash, key, message) => new _HMAC(hash, key).update(message).digest();
+ hmac.create = (hash, key) => new _HMAC(hash, key);
+
+ // node_modules/@noble/curves/src/abstract/weierstrass.js
+ var divNearest = (num2, den) => (num2 + (num2 >= 0 ? den : -den) / _2n2) / den;
+ function _splitEndoScalar(k, basis, n) {
+ const [[a1, b1], [a2, b2]] = basis;
+ const c1 = divNearest(b2 * k, n);
+ const c2 = divNearest(-b1 * k, n);
+ let k1 = k - c1 * a1 - c2 * a2;
+ let k2 = -c1 * b1 - c2 * b2;
+ const k1neg = k1 < _0n4;
+ const k2neg = k2 < _0n4;
+ if (k1neg)
+ k1 = -k1;
+ if (k2neg)
+ k2 = -k2;
+ const MAX_NUM = bitMask(Math.ceil(bitLen(n) / 2)) + _1n4;
+ if (k1 < _0n4 || k1 >= MAX_NUM || k2 < _0n4 || k2 >= MAX_NUM) {
+ throw new Error("splitScalar (endomorphism): failed, k=" + k);
+ }
+ return {
+ k1neg,
+ k1,
+ k2neg,
+ k2
+ };
}
- var { bytesToNumberBE: b2n, hexToBytes: h2b } = utils_exports;
+ function validateSigFormat(format) {
+ if (![
+ "compact",
+ "recovered",
+ "der"
+ ].includes(format))
+ throw new Error('Signature format must be "compact", "recovered", or "der"');
+ return format;
+ }
+ function validateSigOpts(opts, def) {
+ const optsn = {};
+ for (let optName of Object.keys(def)) {
+ optsn[optName] = opts[optName] === void 0 ? def[optName] : opts[optName];
+ }
+ abool(optsn.lowS, "lowS");
+ abool(optsn.prehash, "prehash");
+ if (optsn.format !== void 0)
+ validateSigFormat(optsn.format);
+ return optsn;
+ }
+ var DERErr = class extends Error {
+ constructor(m = "") {
+ super(m);
+ }
+ };
var DER = {
- Err: class DERErr extends Error {
- constructor(m = "") {
- super(m);
+ Err: DERErr,
+ _tlv: {
+ encode: (tag, data) => {
+ const { Err: E } = DER;
+ if (tag < 0 || tag > 256)
+ throw new E("tlv.encode: wrong tag");
+ if (data.length & 1)
+ throw new E("tlv.encode: unpadded data");
+ const dataLen = data.length / 2;
+ const len = numberToHexUnpadded(dataLen);
+ if (len.length / 2 & 128)
+ throw new E("tlv.encode: long form length too big");
+ const lenLen = dataLen > 127 ? numberToHexUnpadded(len.length / 2 | 128) : "";
+ const t = numberToHexUnpadded(tag);
+ return t + lenLen + len + data;
+ },
+ decode(tag, data) {
+ const { Err: E } = DER;
+ let pos = 0;
+ if (tag < 0 || tag > 256)
+ throw new E("tlv.encode: wrong tag");
+ if (data.length < 2 || data[pos++] !== tag)
+ throw new E("tlv.decode: wrong tlv");
+ const first = data[pos++];
+ const isLong = !!(first & 128);
+ let length = 0;
+ if (!isLong)
+ length = first;
+ else {
+ const lenLen = first & 127;
+ if (!lenLen)
+ throw new E("tlv.decode(long): indefinite length not supported");
+ if (lenLen > 4)
+ throw new E("tlv.decode(long): byte length is too big");
+ const lengthBytes = data.subarray(pos, pos + lenLen);
+ if (lengthBytes.length !== lenLen)
+ throw new E("tlv.decode: length bytes not complete");
+ if (lengthBytes[0] === 0)
+ throw new E("tlv.decode(long): zero leftmost byte");
+ for (const b of lengthBytes)
+ length = length << 8 | b;
+ pos += lenLen;
+ if (length < 128)
+ throw new E("tlv.decode(long): not minimal encoding");
+ }
+ const v = data.subarray(pos, pos + length);
+ if (v.length !== length)
+ throw new E("tlv.decode: wrong value length");
+ return {
+ v,
+ l: data.subarray(pos + length)
+ };
}
},
- _parseInt(data) {
- const { Err: E } = DER;
- if (data.length < 2 || data[0] !== 2)
- throw new E("Invalid signature integer tag");
- const len = data[1];
- const res = data.subarray(2, len + 2);
- if (!len || res.length !== len)
- throw new E("Invalid signature integer: wrong length");
- if (res[0] & 128)
- throw new E("Invalid signature integer: negative");
- if (res[0] === 0 && !(res[1] & 128))
- throw new E("Invalid signature integer: unnecessary leading zero");
- return { d: b2n(res), l: data.subarray(len + 2) };
+ _int: {
+ encode(num2) {
+ const { Err: E } = DER;
+ if (num2 < _0n4)
+ throw new E("integer: negative integers are not allowed");
+ let hex2 = numberToHexUnpadded(num2);
+ if (Number.parseInt(hex2[0], 16) & 8)
+ hex2 = "00" + hex2;
+ if (hex2.length & 1)
+ throw new E("unexpected DER parsing assertion: unpadded hex");
+ return hex2;
+ },
+ decode(data) {
+ const { Err: E } = DER;
+ if (data[0] & 128)
+ throw new E("invalid signature integer: negative");
+ if (data[0] === 0 && !(data[1] & 128))
+ throw new E("invalid signature integer: unnecessary leading zero");
+ return bytesToNumberBE(data);
+ }
},
- toSig(hex2) {
- const { Err: E } = DER;
- const data = typeof hex2 === "string" ? h2b(hex2) : hex2;
- if (!(data instanceof Uint8Array))
- throw new Error("ui8a expected");
- let l = data.length;
- if (l < 2 || data[0] != 48)
- throw new E("Invalid signature tag");
- if (data[1] !== l - 2)
- throw new E("Invalid signature: incorrect length");
- const { d: r, l: sBytes } = DER._parseInt(data.subarray(2));
- const { d: s, l: rBytesLeft } = DER._parseInt(sBytes);
- if (rBytesLeft.length)
- throw new E("Invalid signature: left bytes after parsing");
- return { r, s };
+ toSig(bytes) {
+ const { Err: E, _int: int, _tlv: tlv } = DER;
+ const data = abytes(bytes, void 0, "signature");
+ const { v: seqBytes, l: seqLeftBytes } = tlv.decode(48, data);
+ if (seqLeftBytes.length)
+ throw new E("invalid signature: left bytes after parsing");
+ const { v: rBytes, l: rLeftBytes } = tlv.decode(2, seqBytes);
+ const { v: sBytes, l: sLeftBytes } = tlv.decode(2, rLeftBytes);
+ if (sLeftBytes.length)
+ throw new E("invalid signature: left bytes after parsing");
+ return {
+ r: int.decode(rBytes),
+ s: int.decode(sBytes)
+ };
},
hexFromSig(sig) {
- const slice = (s2) => Number.parseInt(s2[0], 16) & 8 ? "00" + s2 : s2;
- const h = (num) => {
- const hex2 = num.toString(16);
- return hex2.length & 1 ? `0${hex2}` : hex2;
- };
- const s = slice(h(sig.s));
- const r = slice(h(sig.r));
- const shl = s.length / 2;
- const rhl = r.length / 2;
- const sl = h(shl);
- const rl = h(rhl);
- return `30${h(rhl + shl + 4)}02${rl}${r}02${sl}${s}`;
+ const { _tlv: tlv, _int: int } = DER;
+ const rs = tlv.encode(2, int.encode(sig.r));
+ const ss = tlv.encode(2, int.encode(sig.s));
+ const seq = rs + ss;
+ return tlv.encode(48, seq);
}
};
var _0n4 = BigInt(0);
var _1n4 = BigInt(1);
- var _2n3 = BigInt(2);
+ var _2n2 = BigInt(2);
var _3n2 = BigInt(3);
var _4n2 = BigInt(4);
- function weierstrassPoints(opts) {
- const CURVE = validatePointOpts(opts);
- const { Fp: Fp2 } = CURVE;
- const toBytes4 = CURVE.toBytes || ((_c, point, _isCompressed) => {
- const a = point.toAffine();
- return concatBytes2(Uint8Array.from([4]), Fp2.toBytes(a.x), Fp2.toBytes(a.y));
+ function weierstrass(params, extraOpts = {}) {
+ const validated = createCurveFields("weierstrass", params, extraOpts);
+ const { Fp, Fn } = validated;
+ let CURVE = validated.CURVE;
+ const { h: cofactor, n: CURVE_ORDER } = CURVE;
+ validateObject(extraOpts, {}, {
+ allowInfinityPoint: "boolean",
+ clearCofactor: "function",
+ isTorsionFree: "function",
+ fromBytes: "function",
+ toBytes: "function",
+ endo: "object"
});
- const fromBytes = CURVE.fromBytes || ((bytes4) => {
- const tail = bytes4.subarray(1);
- const x = Fp2.fromBytes(tail.subarray(0, Fp2.BYTES));
- const y = Fp2.fromBytes(tail.subarray(Fp2.BYTES, 2 * Fp2.BYTES));
- return { x, y };
- });
- function weierstrassEquation(x) {
- const { a, b } = CURVE;
- const x2 = Fp2.sqr(x);
- const x3 = Fp2.mul(x2, x);
- return Fp2.add(Fp2.add(x3, Fp2.mul(x, a)), b);
+ const { endo } = extraOpts;
+ if (endo) {
+ if (!Fp.is0(CURVE.a) || typeof endo.beta !== "bigint" || !Array.isArray(endo.basises)) {
+ throw new Error('invalid endo: expected "beta": bigint and "basises": array');
+ }
}
- if (!Fp2.eql(Fp2.sqr(CURVE.Gy), weierstrassEquation(CURVE.Gx)))
- throw new Error("bad generator point: equation left != right");
- function isWithinCurveOrder(num) {
- return typeof num === "bigint" && _0n4 < num && num < CURVE.n;
+ const lengths = getWLengths(Fp, Fn);
+ function assertCompressionIsSupported() {
+ if (!Fp.isOdd)
+ throw new Error("compression is not supported: Field does not have .isOdd()");
}
- function assertGE(num) {
- if (!isWithinCurveOrder(num))
- throw new Error("Expected valid bigint: 0 < bigint < curve.n");
+ function pointToBytes2(_c, point, isCompressed) {
+ const { x, y } = point.toAffine();
+ const bx = Fp.toBytes(x);
+ abool(isCompressed, "isCompressed");
+ if (isCompressed) {
+ assertCompressionIsSupported();
+ const hasEvenY = !Fp.isOdd(y);
+ return concatBytes(pprefix(hasEvenY), bx);
+ } else {
+ return concatBytes(Uint8Array.of(4), bx, Fp.toBytes(y));
+ }
}
- function normPrivateKeyToScalar(key) {
- const { allowedPrivateKeyLengths: lengths, nByteLength, wrapPrivateKey, n } = CURVE;
- if (lengths && typeof key !== "bigint") {
- if (key instanceof Uint8Array)
- key = bytesToHex(key);
- if (typeof key !== "string" || !lengths.includes(key.length))
- throw new Error("Invalid key");
- key = key.padStart(nByteLength * 2, "0");
+ function pointFromBytes(bytes) {
+ abytes(bytes, void 0, "Point");
+ const { publicKey: comp, publicKeyUncompressed: uncomp } = lengths;
+ const length = bytes.length;
+ const head = bytes[0];
+ const tail = bytes.subarray(1);
+ if (length === comp && (head === 2 || head === 3)) {
+ const x = Fp.fromBytes(tail);
+ if (!Fp.isValid(x))
+ throw new Error("bad point: is not on curve, wrong x");
+ const y2 = weierstrassEquation(x);
+ let y;
+ try {
+ y = Fp.sqrt(y2);
+ } catch (sqrtError) {
+ const err = sqrtError instanceof Error ? ": " + sqrtError.message : "";
+ throw new Error("bad point: is not on curve, sqrt error" + err);
+ }
+ assertCompressionIsSupported();
+ const evenY = Fp.isOdd(y);
+ const evenH = (head & 1) === 1;
+ if (evenH !== evenY)
+ y = Fp.neg(y);
+ return {
+ x,
+ y
+ };
+ } else if (length === uncomp && head === 4) {
+ const L = Fp.BYTES;
+ const x = Fp.fromBytes(tail.subarray(0, L));
+ const y = Fp.fromBytes(tail.subarray(L, L * 2));
+ if (!isValidXY(x, y))
+ throw new Error("bad point: is not on curve");
+ return {
+ x,
+ y
+ };
+ } else {
+ throw new Error(`bad point: got length ${length}, expected compressed=${comp} or uncompressed=${uncomp}`);
}
- let num;
- try {
- num = typeof key === "bigint" ? key : bytesToNumberBE(ensureBytes("private key", key, nByteLength));
- } catch (error) {
- throw new Error(`private key must be ${nByteLength} bytes, hex or bigint, not ${typeof key}`);
- }
- if (wrapPrivateKey)
- num = mod(num, n);
- assertGE(num);
- return num;
}
- const pointPrecomputes = /* @__PURE__ */ new Map();
- function assertPrjPoint(other) {
- if (!(other instanceof Point2))
- throw new Error("ProjectivePoint expected");
+ const encodePoint = extraOpts.toBytes || pointToBytes2;
+ const decodePoint = extraOpts.fromBytes || pointFromBytes;
+ function weierstrassEquation(x) {
+ const x2 = Fp.sqr(x);
+ const x3 = Fp.mul(x2, x);
+ return Fp.add(Fp.add(x3, Fp.mul(x, CURVE.a)), CURVE.b);
}
- class Point2 {
- constructor(px, py, pz) {
- this.px = px;
- this.py = py;
- this.pz = pz;
- if (px == null || !Fp2.isValid(px))
- throw new Error("x required");
- if (py == null || !Fp2.isValid(py))
- throw new Error("y required");
- if (pz == null || !Fp2.isValid(pz))
- throw new Error("z required");
+ function isValidXY(x, y) {
+ const left = Fp.sqr(y);
+ const right = weierstrassEquation(x);
+ return Fp.eql(left, right);
+ }
+ if (!isValidXY(CURVE.Gx, CURVE.Gy))
+ throw new Error("bad curve params: generator point");
+ const _4a3 = Fp.mul(Fp.pow(CURVE.a, _3n2), _4n2);
+ const _27b2 = Fp.mul(Fp.sqr(CURVE.b), BigInt(27));
+ if (Fp.is0(Fp.add(_4a3, _27b2)))
+ throw new Error("bad curve params: a or b");
+ function acoord(title, n, banZero = false) {
+ if (!Fp.isValid(n) || banZero && Fp.is0(n))
+ throw new Error(`bad point coordinate ${title}`);
+ return n;
+ }
+ function aprjpoint(other) {
+ if (!(other instanceof Point))
+ throw new Error("Weierstrass Point expected");
+ }
+ function splitEndoScalarN(k) {
+ if (!endo || !endo.basises)
+ throw new Error("no endo");
+ return _splitEndoScalar(k, endo.basises, Fn.ORDER);
+ }
+ const toAffineMemo = memoized((p, iz) => {
+ const { X, Y, Z } = p;
+ if (Fp.eql(Z, Fp.ONE))
+ return {
+ x: X,
+ y: Y
+ };
+ const is0 = p.is0();
+ if (iz == null)
+ iz = is0 ? Fp.ONE : Fp.inv(Z);
+ const x = Fp.mul(X, iz);
+ const y = Fp.mul(Y, iz);
+ const zz = Fp.mul(Z, iz);
+ if (is0)
+ return {
+ x: Fp.ZERO,
+ y: Fp.ZERO
+ };
+ if (!Fp.eql(zz, Fp.ONE))
+ throw new Error("invZ was invalid");
+ return {
+ x,
+ y
+ };
+ });
+ const assertValidMemo = memoized((p) => {
+ if (p.is0()) {
+ if (extraOpts.allowInfinityPoint && !Fp.is0(p.Y))
+ return;
+ throw new Error("bad point: ZERO");
}
+ const { x, y } = p.toAffine();
+ if (!Fp.isValid(x) || !Fp.isValid(y))
+ throw new Error("bad point: x or y not field elements");
+ if (!isValidXY(x, y))
+ throw new Error("bad point: equation left != right");
+ if (!p.isTorsionFree())
+ throw new Error("bad point: not in prime-order subgroup");
+ return true;
+ });
+ function finishEndo(endoBeta, k1p, k2p, k1neg, k2neg) {
+ k2p = new Point(Fp.mul(k2p.X, endoBeta), k2p.Y, k2p.Z);
+ k1p = negateCt(k1neg, k1p);
+ k2p = negateCt(k2neg, k2p);
+ return k1p.add(k2p);
+ }
+ class Point {
+ static BASE = new Point(CURVE.Gx, CURVE.Gy, Fp.ONE);
+ static ZERO = new Point(Fp.ZERO, Fp.ONE, Fp.ZERO);
+ static Fp = Fp;
+ static Fn = Fn;
+ X;
+ Y;
+ Z;
+ constructor(X, Y, Z) {
+ this.X = acoord("x", X);
+ this.Y = acoord("y", Y, true);
+ this.Z = acoord("z", Z);
+ Object.freeze(this);
+ }
+ static CURVE() {
+ return CURVE;
+ }
static fromAffine(p) {
const { x, y } = p || {};
- if (!p || !Fp2.isValid(x) || !Fp2.isValid(y))
+ if (!p || !Fp.isValid(x) || !Fp.isValid(y))
throw new Error("invalid affine point");
- if (p instanceof Point2)
+ if (p instanceof Point)
throw new Error("projective point not allowed");
- const is0 = (i2) => Fp2.eql(i2, Fp2.ZERO);
- if (is0(x) && is0(y))
- return Point2.ZERO;
- return new Point2(x, y, Fp2.ONE);
+ if (Fp.is0(x) && Fp.is0(y))
+ return Point.ZERO;
+ return new Point(x, y, Fp.ONE);
}
+ static fromBytes(bytes) {
+ const P = Point.fromAffine(decodePoint(abytes(bytes, void 0, "point")));
+ P.assertValidity();
+ return P;
+ }
+ static fromHex(hex2) {
+ return Point.fromBytes(hexToBytes(hex2));
+ }
get x() {
return this.toAffine().x;
}
get y() {
return this.toAffine().y;
}
- static normalizeZ(points) {
- const toInv = Fp2.invertBatch(points.map((p) => p.pz));
- return points.map((p, i2) => p.toAffine(toInv[i2])).map(Point2.fromAffine);
+ precompute(windowSize = 8, isLazy = true) {
+ wnaf.createCache(this, windowSize);
+ if (!isLazy)
+ this.multiply(_3n2);
+ return this;
}
- static fromHex(hex2) {
- const P = Point2.fromAffine(fromBytes(ensureBytes("pointHex", hex2)));
- P.assertValidity();
- return P;
- }
- static fromPrivateKey(privateKey) {
- return Point2.BASE.multiply(normPrivateKeyToScalar(privateKey));
- }
- _setWindowSize(windowSize) {
- this._WINDOW_SIZE = windowSize;
- pointPrecomputes.delete(this);
- }
assertValidity() {
- if (this.is0()) {
- if (CURVE.allowInfinityPoint && !Fp2.is0(this.py))
- return;
- throw new Error("bad point: ZERO");
- }
- const { x, y } = this.toAffine();
- if (!Fp2.isValid(x) || !Fp2.isValid(y))
- throw new Error("bad point: x or y not FE");
- const left = Fp2.sqr(y);
- const right = weierstrassEquation(x);
- if (!Fp2.eql(left, right))
- throw new Error("bad point: equation left != right");
- if (!this.isTorsionFree())
- throw new Error("bad point: not in prime-order subgroup");
+ assertValidMemo(this);
}
hasEvenY() {
const { y } = this.toAffine();
- if (Fp2.isOdd)
- return !Fp2.isOdd(y);
- throw new Error("Field doesn't support isOdd");
+ if (!Fp.isOdd)
+ throw new Error("Field doesn't support isOdd");
+ return !Fp.isOdd(y);
}
equals(other) {
- assertPrjPoint(other);
- const { px: X1, py: Y1, pz: Z1 } = this;
- const { px: X2, py: Y2, pz: Z2 } = other;
- const U1 = Fp2.eql(Fp2.mul(X1, Z2), Fp2.mul(X2, Z1));
- const U2 = Fp2.eql(Fp2.mul(Y1, Z2), Fp2.mul(Y2, Z1));
+ aprjpoint(other);
+ const { X: X1, Y: Y1, Z: Z1 } = this;
+ const { X: X2, Y: Y2, Z: Z2 } = other;
+ const U1 = Fp.eql(Fp.mul(X1, Z2), Fp.mul(X2, Z1));
+ const U2 = Fp.eql(Fp.mul(Y1, Z2), Fp.mul(Y2, Z1));
return U1 && U2;
}
negate() {
- return new Point2(this.px, Fp2.neg(this.py), this.pz);
+ return new Point(this.X, Fp.neg(this.Y), this.Z);
}
double() {
const { a, b } = CURVE;
- const b3 = Fp2.mul(b, _3n2);
- const { px: X1, py: Y1, pz: Z1 } = this;
- let X3 = Fp2.ZERO, Y3 = Fp2.ZERO, Z3 = Fp2.ZERO;
- let t0 = Fp2.mul(X1, X1);
- let t1 = Fp2.mul(Y1, Y1);
- let t2 = Fp2.mul(Z1, Z1);
- let t3 = Fp2.mul(X1, Y1);
- t3 = Fp2.add(t3, t3);
- Z3 = Fp2.mul(X1, Z1);
- Z3 = Fp2.add(Z3, Z3);
- X3 = Fp2.mul(a, Z3);
- Y3 = Fp2.mul(b3, t2);
- Y3 = Fp2.add(X3, Y3);
- X3 = Fp2.sub(t1, Y3);
- Y3 = Fp2.add(t1, Y3);
- Y3 = Fp2.mul(X3, Y3);
- X3 = Fp2.mul(t3, X3);
- Z3 = Fp2.mul(b3, Z3);
- t2 = Fp2.mul(a, t2);
- t3 = Fp2.sub(t0, t2);
- t3 = Fp2.mul(a, t3);
- t3 = Fp2.add(t3, Z3);
- Z3 = Fp2.add(t0, t0);
- t0 = Fp2.add(Z3, t0);
- t0 = Fp2.add(t0, t2);
- t0 = Fp2.mul(t0, t3);
- Y3 = Fp2.add(Y3, t0);
- t2 = Fp2.mul(Y1, Z1);
- t2 = Fp2.add(t2, t2);
- t0 = Fp2.mul(t2, t3);
- X3 = Fp2.sub(X3, t0);
- Z3 = Fp2.mul(t2, t1);
- Z3 = Fp2.add(Z3, Z3);
- Z3 = Fp2.add(Z3, Z3);
- return new Point2(X3, Y3, Z3);
+ const b3 = Fp.mul(b, _3n2);
+ const { X: X1, Y: Y1, Z: Z1 } = this;
+ let X3 = Fp.ZERO, Y3 = Fp.ZERO, Z3 = Fp.ZERO;
+ let t0 = Fp.mul(X1, X1);
+ let t1 = Fp.mul(Y1, Y1);
+ let t2 = Fp.mul(Z1, Z1);
+ let t3 = Fp.mul(X1, Y1);
+ t3 = Fp.add(t3, t3);
+ Z3 = Fp.mul(X1, Z1);
+ Z3 = Fp.add(Z3, Z3);
+ X3 = Fp.mul(a, Z3);
+ Y3 = Fp.mul(b3, t2);
+ Y3 = Fp.add(X3, Y3);
+ X3 = Fp.sub(t1, Y3);
+ Y3 = Fp.add(t1, Y3);
+ Y3 = Fp.mul(X3, Y3);
+ X3 = Fp.mul(t3, X3);
+ Z3 = Fp.mul(b3, Z3);
+ t2 = Fp.mul(a, t2);
+ t3 = Fp.sub(t0, t2);
+ t3 = Fp.mul(a, t3);
+ t3 = Fp.add(t3, Z3);
+ Z3 = Fp.add(t0, t0);
+ t0 = Fp.add(Z3, t0);
+ t0 = Fp.add(t0, t2);
+ t0 = Fp.mul(t0, t3);
+ Y3 = Fp.add(Y3, t0);
+ t2 = Fp.mul(Y1, Z1);
+ t2 = Fp.add(t2, t2);
+ t0 = Fp.mul(t2, t3);
+ X3 = Fp.sub(X3, t0);
+ Z3 = Fp.mul(t2, t1);
+ Z3 = Fp.add(Z3, Z3);
+ Z3 = Fp.add(Z3, Z3);
+ return new Point(X3, Y3, Z3);
}
add(other) {
- assertPrjPoint(other);
- const { px: X1, py: Y1, pz: Z1 } = this;
- const { px: X2, py: Y2, pz: Z2 } = other;
- let X3 = Fp2.ZERO, Y3 = Fp2.ZERO, Z3 = Fp2.ZERO;
+ aprjpoint(other);
+ const { X: X1, Y: Y1, Z: Z1 } = this;
+ const { X: X2, Y: Y2, Z: Z2 } = other;
+ let X3 = Fp.ZERO, Y3 = Fp.ZERO, Z3 = Fp.ZERO;
const a = CURVE.a;
- const b3 = Fp2.mul(CURVE.b, _3n2);
- let t0 = Fp2.mul(X1, X2);
- let t1 = Fp2.mul(Y1, Y2);
- let t2 = Fp2.mul(Z1, Z2);
- let t3 = Fp2.add(X1, Y1);
- let t4 = Fp2.add(X2, Y2);
- t3 = Fp2.mul(t3, t4);
- t4 = Fp2.add(t0, t1);
- t3 = Fp2.sub(t3, t4);
- t4 = Fp2.add(X1, Z1);
- let t5 = Fp2.add(X2, Z2);
- t4 = Fp2.mul(t4, t5);
- t5 = Fp2.add(t0, t2);
- t4 = Fp2.sub(t4, t5);
- t5 = Fp2.add(Y1, Z1);
- X3 = Fp2.add(Y2, Z2);
- t5 = Fp2.mul(t5, X3);
- X3 = Fp2.add(t1, t2);
- t5 = Fp2.sub(t5, X3);
- Z3 = Fp2.mul(a, t4);
- X3 = Fp2.mul(b3, t2);
- Z3 = Fp2.add(X3, Z3);
- X3 = Fp2.sub(t1, Z3);
- Z3 = Fp2.add(t1, Z3);
- Y3 = Fp2.mul(X3, Z3);
- t1 = Fp2.add(t0, t0);
- t1 = Fp2.add(t1, t0);
- t2 = Fp2.mul(a, t2);
- t4 = Fp2.mul(b3, t4);
- t1 = Fp2.add(t1, t2);
- t2 = Fp2.sub(t0, t2);
- t2 = Fp2.mul(a, t2);
- t4 = Fp2.add(t4, t2);
- t0 = Fp2.mul(t1, t4);
- Y3 = Fp2.add(Y3, t0);
- t0 = Fp2.mul(t5, t4);
- X3 = Fp2.mul(t3, X3);
- X3 = Fp2.sub(X3, t0);
- t0 = Fp2.mul(t3, t1);
- Z3 = Fp2.mul(t5, Z3);
- Z3 = Fp2.add(Z3, t0);
- return new Point2(X3, Y3, Z3);
+ const b3 = Fp.mul(CURVE.b, _3n2);
+ let t0 = Fp.mul(X1, X2);
+ let t1 = Fp.mul(Y1, Y2);
+ let t2 = Fp.mul(Z1, Z2);
+ let t3 = Fp.add(X1, Y1);
+ let t4 = Fp.add(X2, Y2);
+ t3 = Fp.mul(t3, t4);
+ t4 = Fp.add(t0, t1);
+ t3 = Fp.sub(t3, t4);
+ t4 = Fp.add(X1, Z1);
+ let t5 = Fp.add(X2, Z2);
+ t4 = Fp.mul(t4, t5);
+ t5 = Fp.add(t0, t2);
+ t4 = Fp.sub(t4, t5);
+ t5 = Fp.add(Y1, Z1);
+ X3 = Fp.add(Y2, Z2);
+ t5 = Fp.mul(t5, X3);
+ X3 = Fp.add(t1, t2);
+ t5 = Fp.sub(t5, X3);
+ Z3 = Fp.mul(a, t4);
+ X3 = Fp.mul(b3, t2);
+ Z3 = Fp.add(X3, Z3);
+ X3 = Fp.sub(t1, Z3);
+ Z3 = Fp.add(t1, Z3);
+ Y3 = Fp.mul(X3, Z3);
+ t1 = Fp.add(t0, t0);
+ t1 = Fp.add(t1, t0);
+ t2 = Fp.mul(a, t2);
+ t4 = Fp.mul(b3, t4);
+ t1 = Fp.add(t1, t2);
+ t2 = Fp.sub(t0, t2);
+ t2 = Fp.mul(a, t2);
+ t4 = Fp.add(t4, t2);
+ t0 = Fp.mul(t1, t4);
+ Y3 = Fp.add(Y3, t0);
+ t0 = Fp.mul(t5, t4);
+ X3 = Fp.mul(t3, X3);
+ X3 = Fp.sub(X3, t0);
+ t0 = Fp.mul(t3, t1);
+ Z3 = Fp.mul(t5, Z3);
+ Z3 = Fp.add(Z3, t0);
+ return new Point(X3, Y3, Z3);
}
subtract(other) {
return this.add(other.negate());
}
is0() {
- return this.equals(Point2.ZERO);
+ return this.equals(Point.ZERO);
}
- wNAF(n) {
- return wnaf.wNAFCached(this, pointPrecomputes, n, (comp) => {
- const toInv = Fp2.invertBatch(comp.map((p) => p.pz));
- return comp.map((p, i2) => p.toAffine(toInv[i2])).map(Point2.fromAffine);
- });
- }
- multiplyUnsafe(n) {
- const I = Point2.ZERO;
- if (n === _0n4)
- return I;
- assertGE(n);
- if (n === _1n4)
- return this;
- const { endo } = CURVE;
- if (!endo)
- return wnaf.unsafeLadder(this, n);
- let { k1neg, k1, k2neg, k2 } = endo.splitScalar(n);
- let k1p = I;
- let k2p = I;
- let d = this;
- while (k1 > _0n4 || k2 > _0n4) {
- if (k1 & _1n4)
- k1p = k1p.add(d);
- if (k2 & _1n4)
- k2p = k2p.add(d);
- d = d.double();
- k1 >>= _1n4;
- k2 >>= _1n4;
- }
- if (k1neg)
- k1p = k1p.negate();
- if (k2neg)
- k2p = k2p.negate();
- k2p = new Point2(Fp2.mul(k2p.px, endo.beta), k2p.py, k2p.pz);
- return k1p.add(k2p);
- }
multiply(scalar) {
- assertGE(scalar);
- let n = scalar;
+ const { endo: endo2 } = extraOpts;
+ if (!Fn.isValidNot0(scalar))
+ throw new Error("invalid scalar: out of range");
let point, fake;
- const { endo } = CURVE;
- if (endo) {
- const { k1neg, k1, k2neg, k2 } = endo.splitScalar(n);
- let { p: k1p, f: f1p } = this.wNAF(k1);
- let { p: k2p, f: f2p } = this.wNAF(k2);
- k1p = wnaf.constTimeNegate(k1neg, k1p);
- k2p = wnaf.constTimeNegate(k2neg, k2p);
- k2p = new Point2(Fp2.mul(k2p.px, endo.beta), k2p.py, k2p.pz);
- point = k1p.add(k2p);
- fake = f1p.add(f2p);
+ const mul3 = (n) => wnaf.cached(this, n, (p) => normalizeZ(Point, p));
+ if (endo2) {
+ const { k1neg, k1, k2neg, k2 } = splitEndoScalarN(scalar);
+ const { p: k1p, f: k1f } = mul3(k1);
+ const { p: k2p, f: k2f } = mul3(k2);
+ fake = k1f.add(k2f);
+ point = finishEndo(endo2.beta, k1p, k2p, k1neg, k2neg);
} else {
- const { p, f } = this.wNAF(n);
+ const { p, f } = mul3(scalar);
point = p;
fake = f;
}
- return Point2.normalizeZ([point, fake])[0];
+ return normalizeZ(Point, [
+ point,
+ fake
+ ])[0];
}
- multiplyAndAddUnsafe(Q, a, b) {
- const G = Point2.BASE;
- const mul3 = (P, a2) => a2 === _0n4 || a2 === _1n4 || !P.equals(G) ? P.multiplyUnsafe(a2) : P.multiply(a2);
- const sum = mul3(this, a).add(mul3(Q, b));
- return sum.is0() ? void 0 : sum;
+ multiplyUnsafe(sc) {
+ const { endo: endo2 } = extraOpts;
+ const p = this;
+ if (!Fn.isValid(sc))
+ throw new Error("invalid scalar: out of range");
+ if (sc === _0n4 || p.is0())
+ return Point.ZERO;
+ if (sc === _1n4)
+ return p;
+ if (wnaf.hasCache(this))
+ return this.multiply(sc);
+ if (endo2) {
+ const { k1neg, k1, k2neg, k2 } = splitEndoScalarN(sc);
+ const { p1, p2 } = mulEndoUnsafe(Point, p, k1, k2);
+ return finishEndo(endo2.beta, p1, p2, k1neg, k2neg);
+ } else {
+ return wnaf.unsafe(p, sc);
+ }
}
- toAffine(iz) {
- const { px: x, py: y, pz: z } = this;
- const is0 = this.is0();
- if (iz == null)
- iz = is0 ? Fp2.ONE : Fp2.inv(z);
- const ax = Fp2.mul(x, iz);
- const ay = Fp2.mul(y, iz);
- const zz = Fp2.mul(z, iz);
- if (is0)
- return { x: Fp2.ZERO, y: Fp2.ZERO };
- if (!Fp2.eql(zz, Fp2.ONE))
- throw new Error("invZ was invalid");
- return { x: ax, y: ay };
+ toAffine(invertedZ) {
+ return toAffineMemo(this, invertedZ);
}
isTorsionFree() {
- const { h: cofactor, isTorsionFree } = CURVE;
+ const { isTorsionFree } = extraOpts;
if (cofactor === _1n4)
return true;
if (isTorsionFree)
- return isTorsionFree(Point2, this);
- throw new Error("isTorsionFree() has not been declared for the elliptic curve");
+ return isTorsionFree(Point, this);
+ return wnaf.unsafe(this, CURVE_ORDER).is0();
}
clearCofactor() {
- const { h: cofactor, clearCofactor } = CURVE;
+ const { clearCofactor } = extraOpts;
if (cofactor === _1n4)
return this;
if (clearCofactor)
- return clearCofactor(Point2, this);
- return this.multiplyUnsafe(CURVE.h);
+ return clearCofactor(Point, this);
+ return this.multiplyUnsafe(cofactor);
}
- toRawBytes(isCompressed = true) {
+ isSmallOrder() {
+ return this.multiplyUnsafe(cofactor).is0();
+ }
+ toBytes(isCompressed = true) {
+ abool(isCompressed, "isCompressed");
this.assertValidity();
- return toBytes4(Point2, this, isCompressed);
+ return encodePoint(Point, this, isCompressed);
}
toHex(isCompressed = true) {
- return bytesToHex(this.toRawBytes(isCompressed));
+ return bytesToHex(this.toBytes(isCompressed));
}
+ toString() {
+ return `<Point ${this.is0() ? "ZERO" : this.toHex()}>`;
+ }
}
- Point2.BASE = new Point2(CURVE.Gx, CURVE.Gy, Fp2.ONE);
- Point2.ZERO = new Point2(Fp2.ZERO, Fp2.ONE, Fp2.ZERO);
- const _bits = CURVE.nBitLength;
- const wnaf = wNAF(Point2, CURVE.endo ? Math.ceil(_bits / 2) : _bits);
+ const bits = Fn.BITS;
+ const wnaf = new wNAF(Point, extraOpts.endo ? Math.ceil(bits / 2) : bits);
+ Point.BASE.precompute(8);
+ return Point;
+ }
+ function pprefix(hasEvenY) {
+ return Uint8Array.of(hasEvenY ? 2 : 3);
+ }
+ function getWLengths(Fp, Fn) {
return {
- CURVE,
- ProjectivePoint: Point2,
- normPrivateKeyToScalar,
- weierstrassEquation,
- isWithinCurveOrder
+ secretKey: Fn.BYTES,
+ publicKey: 1 + Fp.BYTES,
+ publicKeyUncompressed: 1 + 2 * Fp.BYTES,
+ publicKeyHasPrefix: true,
+ signature: 2 * Fn.BYTES
};
}
- function validateOpts(curve) {
- const opts = validateBasic(curve);
- validateObject(opts, {
- hash: "hash",
- hmac: "function",
- randomBytes: "function"
- }, {
- bits2int: "function",
- bits2int_modN: "function",
- lowS: "boolean"
+ function ecdh(Point, ecdhOpts = {}) {
+ const { Fn } = Point;
+ const randomBytes_ = ecdhOpts.randomBytes || randomBytes;
+ const lengths = Object.assign(getWLengths(Point.Fp, Fn), {
+ seed: getMinHashLength(Fn.ORDER)
});
- return Object.freeze({ lowS: true, ...opts });
- }
- function weierstrass(curveDef) {
- const CURVE = validateOpts(curveDef);
- const { Fp: Fp2, n: CURVE_ORDER } = CURVE;
- const compressedLen = Fp2.BYTES + 1;
- const uncompressedLen = 2 * Fp2.BYTES + 1;
- function isValidFieldElement(num) {
- return _0n4 < num && num < Fp2.ORDER;
+ function isValidSecretKey(secretKey) {
+ try {
+ const num2 = Fn.fromBytes(secretKey);
+ return Fn.isValidNot0(num2);
+ } catch (error) {
+ return false;
+ }
}
- function modN2(a) {
- return mod(a, CURVE_ORDER);
+ function isValidPublicKey(publicKey, isCompressed) {
+ const { publicKey: comp, publicKeyUncompressed } = lengths;
+ try {
+ const l = publicKey.length;
+ if (isCompressed === true && l !== comp)
+ return false;
+ if (isCompressed === false && l !== publicKeyUncompressed)
+ return false;
+ return !!Point.fromBytes(publicKey);
+ } catch (error) {
+ return false;
+ }
}
- function invN(a) {
- return invert(a, CURVE_ORDER);
+ function randomSecretKey(seed = randomBytes_(lengths.seed)) {
+ return mapHashToField(abytes(seed, lengths.seed, "seed"), Fn.ORDER);
}
- const { ProjectivePoint: Point2, normPrivateKeyToScalar, weierstrassEquation, isWithinCurveOrder } = weierstrassPoints({
- ...CURVE,
- toBytes(_c, point, isCompressed) {
- const a = point.toAffine();
- const x = Fp2.toBytes(a.x);
- const cat = concatBytes2;
- if (isCompressed) {
- return cat(Uint8Array.from([point.hasEvenY() ? 2 : 3]), x);
- } else {
- return cat(Uint8Array.from([4]), x, Fp2.toBytes(a.y));
- }
- },
- fromBytes(bytes4) {
- const len = bytes4.length;
- const head = bytes4[0];
- const tail = bytes4.subarray(1);
- if (len === compressedLen && (head === 2 || head === 3)) {
- const x = bytesToNumberBE(tail);
- if (!isValidFieldElement(x))
- throw new Error("Point is not on curve");
- const y2 = weierstrassEquation(x);
- let y = Fp2.sqrt(y2);
- const isYOdd = (y & _1n4) === _1n4;
- const isHeadOdd = (head & 1) === 1;
- if (isHeadOdd !== isYOdd)
- y = Fp2.neg(y);
- return { x, y };
- } else if (len === uncompressedLen && head === 4) {
- const x = Fp2.fromBytes(tail.subarray(0, Fp2.BYTES));
- const y = Fp2.fromBytes(tail.subarray(Fp2.BYTES, 2 * Fp2.BYTES));
- return { x, y };
- } else {
- throw new Error(`Point of length ${len} was invalid. Expected ${compressedLen} compressed bytes or ${uncompressedLen} uncompressed bytes`);
- }
- }
+ function getPublicKey2(secretKey, isCompressed = true) {
+ return Point.BASE.multiply(Fn.fromBytes(secretKey)).toBytes(isCompressed);
+ }
+ function isProbPub(item) {
+ const { secretKey, publicKey, publicKeyUncompressed } = lengths;
+ if (!isBytes(item))
+ return void 0;
+ if ("_lengths" in Fn && Fn._lengths || secretKey === publicKey)
+ return void 0;
+ const l = abytes(item, void 0, "key").length;
+ return l === publicKey || l === publicKeyUncompressed;
+ }
+ function getSharedSecret(secretKeyA, publicKeyB, isCompressed = true) {
+ if (isProbPub(secretKeyA) === true)
+ throw new Error("first arg must be private key");
+ if (isProbPub(publicKeyB) === false)
+ throw new Error("second arg must be public key");
+ const s = Fn.fromBytes(secretKeyA);
+ const b = Point.fromBytes(publicKeyB);
+ return b.multiply(s).toBytes(isCompressed);
+ }
+ const utils = {
+ isValidSecretKey,
+ isValidPublicKey,
+ randomSecretKey
+ };
+ const keygen = createKeygen(randomSecretKey, getPublicKey2);
+ return Object.freeze({
+ getPublicKey: getPublicKey2,
+ getSharedSecret,
+ keygen,
+ Point,
+ utils,
+ lengths
});
- const numToNByteStr = (num) => bytesToHex(numberToBytesBE(num, CURVE.nByteLength));
- function isBiggerThanHalfOrder(number4) {
+ }
+ function ecdsa(Point, hash, ecdsaOpts = {}) {
+ ahash(hash);
+ validateObject(ecdsaOpts, {}, {
+ hmac: "function",
+ lowS: "boolean",
+ randomBytes: "function",
+ bits2int: "function",
+ bits2int_modN: "function"
+ });
+ ecdsaOpts = Object.assign({}, ecdsaOpts);
+ const randomBytes4 = ecdsaOpts.randomBytes || randomBytes;
+ const hmac3 = ecdsaOpts.hmac || ((key, msg) => hmac(hash, key, msg));
+ const { Fp, Fn } = Point;
+ const { ORDER: CURVE_ORDER, BITS: fnBits } = Fn;
+ const { keygen, getPublicKey: getPublicKey2, getSharedSecret, utils, lengths } = ecdh(Point, ecdsaOpts);
+ const defaultSigOpts = {
+ prehash: true,
+ lowS: typeof ecdsaOpts.lowS === "boolean" ? ecdsaOpts.lowS : true,
+ format: "compact",
+ extraEntropy: false
+ };
+ const hasLargeCofactor = CURVE_ORDER * _2n2 < Fp.ORDER;
+ function isBiggerThanHalfOrder(number) {
const HALF = CURVE_ORDER >> _1n4;
- return number4 > HALF;
+ return number > HALF;
}
- function normalizeS(s) {
- return isBiggerThanHalfOrder(s) ? modN2(-s) : s;
+ function validateRS(title, num2) {
+ if (!Fn.isValidNot0(num2))
+ throw new Error(`invalid signature ${title}: out of range 1..Point.Fn.ORDER`);
+ return num2;
}
- const slcNum = (b, from, to) => bytesToNumberBE(b.slice(from, to));
+ function assertSmallCofactor() {
+ if (hasLargeCofactor)
+ throw new Error('"recovered" sig type is not supported for cofactor >2 curves');
+ }
+ function validateSigLength(bytes, format) {
+ validateSigFormat(format);
+ const size = lengths.signature;
+ const sizer = format === "compact" ? size : format === "recovered" ? size + 1 : void 0;
+ return abytes(bytes, sizer);
+ }
class Signature {
+ r;
+ s;
+ recovery;
constructor(r, s, recovery) {
- this.r = r;
- this.s = s;
- this.recovery = recovery;
- this.assertValidity();
+ this.r = validateRS("r", r);
+ this.s = validateRS("s", s);
+ if (recovery != null) {
+ assertSmallCofactor();
+ if (![
+ 0,
+ 1,
+ 2,
+ 3
+ ].includes(recovery))
+ throw new Error("invalid recovery id");
+ this.recovery = recovery;
+ }
+ Object.freeze(this);
}
- static fromCompact(hex2) {
- const l = CURVE.nByteLength;
- hex2 = ensureBytes("compactSignature", hex2, l * 2);
- return new Signature(slcNum(hex2, 0, l), slcNum(hex2, l, 2 * l));
+ static fromBytes(bytes, format = defaultSigOpts.format) {
+ validateSigLength(bytes, format);
+ let recid;
+ if (format === "der") {
+ const { r: r2, s: s2 } = DER.toSig(abytes(bytes));
+ return new Signature(r2, s2);
+ }
+ if (format === "recovered") {
+ recid = bytes[0];
+ format = "compact";
+ bytes = bytes.subarray(1);
+ }
+ const L = lengths.signature / 2;
+ const r = bytes.subarray(0, L);
+ const s = bytes.subarray(L, L * 2);
+ return new Signature(Fn.fromBytes(r), Fn.fromBytes(s), recid);
}
- static fromDER(hex2) {
- const { r, s } = DER.toSig(ensureBytes("DER", hex2));
- return new Signature(r, s);
+ static fromHex(hex2, format) {
+ return this.fromBytes(hexToBytes(hex2), format);
}
- assertValidity() {
- if (!isWithinCurveOrder(this.r))
- throw new Error("r must be 0 < r < CURVE.n");
- if (!isWithinCurveOrder(this.s))
- throw new Error("s must be 0 < s < CURVE.n");
+ assertRecovery() {
+ const { recovery } = this;
+ if (recovery == null)
+ throw new Error("invalid recovery id: must be present");
+ return recovery;
}
addRecoveryBit(recovery) {
return new Signature(this.r, this.s, recovery);
}
- recoverPublicKey(msgHash) {
- const { r, s, recovery: rec } = this;
- const h = bits2int_modN(ensureBytes("msgHash", msgHash));
- if (rec == null || ![0, 1, 2, 3].includes(rec))
- throw new Error("recovery id invalid");
- const radj = rec === 2 || rec === 3 ? r + CURVE.n : r;
- if (radj >= Fp2.ORDER)
- throw new Error("recovery id 2 or 3 invalid");
- const prefix = (rec & 1) === 0 ? "02" : "03";
- const R = Point2.fromHex(prefix + numToNByteStr(radj));
- const ir = invN(radj);
- const u1 = modN2(-h * ir);
- const u2 = modN2(s * ir);
- const Q = Point2.BASE.multiplyAndAddUnsafe(R, u1, u2);
- if (!Q)
- throw new Error("point at infinify");
+ recoverPublicKey(messageHash) {
+ const { r, s } = this;
+ const recovery = this.assertRecovery();
+ const radj = recovery === 2 || recovery === 3 ? r + CURVE_ORDER : r;
+ if (!Fp.isValid(radj))
+ throw new Error("invalid recovery id: sig.r+curve.n != R.x");
+ const x = Fp.toBytes(radj);
+ const R = Point.fromBytes(concatBytes(pprefix((recovery & 1) === 0), x));
+ const ir = Fn.inv(radj);
+ const h = bits2int_modN(abytes(messageHash, void 0, "msgHash"));
+ const u1 = Fn.create(-h * ir);
+ const u2 = Fn.create(s * ir);
+ const Q = Point.BASE.multiplyUnsafe(u1).add(R.multiplyUnsafe(u2));
+ if (Q.is0())
+ throw new Error("invalid recovery: point at infinify");
Q.assertValidity();
return Q;
}
hasHighS() {
return isBiggerThanHalfOrder(this.s);
}
- normalizeS() {
- return this.hasHighS() ? new Signature(this.r, modN2(-this.s), this.recovery) : this;
+ toBytes(format = defaultSigOpts.format) {
+ validateSigFormat(format);
+ if (format === "der")
+ return hexToBytes(DER.hexFromSig(this));
+ const { r, s } = this;
+ const rb = Fn.toBytes(r);
+ const sb = Fn.toBytes(s);
+ if (format === "recovered") {
+ assertSmallCofactor();
+ return concatBytes(Uint8Array.of(this.assertRecovery()), rb, sb);
+ }
+ return concatBytes(rb, sb);
}
- toDERRawBytes() {
- return hexToBytes(this.toDERHex());
+ toHex(format) {
+ return bytesToHex(this.toBytes(format));
}
- toDERHex() {
- return DER.hexFromSig({ r: this.r, s: this.s });
- }
- toCompactRawBytes() {
- return hexToBytes(this.toCompactHex());
- }
- toCompactHex() {
- return numToNByteStr(this.r) + numToNByteStr(this.s);
- }
}
- const utils = {
- isValidPrivateKey(privateKey) {
- try {
- normPrivateKeyToScalar(privateKey);
- return true;
- } catch (error) {
- return false;
- }
- },
- normPrivateKeyToScalar,
- randomPrivateKey: () => {
- const length = getMinHashLength(CURVE.n);
- return mapHashToField(CURVE.randomBytes(length), CURVE.n);
- },
- precompute(windowSize = 8, point = Point2.BASE) {
- point._setWindowSize(windowSize);
- point.multiply(BigInt(3));
- return point;
- }
+ const bits2int = ecdsaOpts.bits2int || function bits2int_def(bytes) {
+ if (bytes.length > 8192)
+ throw new Error("input is too large");
+ const num2 = bytesToNumberBE(bytes);
+ const delta = bytes.length * 8 - fnBits;
+ return delta > 0 ? num2 >> BigInt(delta) : num2;
};
- function getPublicKey2(privateKey, isCompressed = true) {
- return Point2.fromPrivateKey(privateKey).toRawBytes(isCompressed);
- }
- function isProbPub(item) {
- const arr = item instanceof Uint8Array;
- const str = typeof item === "string";
- const len = (arr || str) && item.length;
- if (arr)
- return len === compressedLen || len === uncompressedLen;
- if (str)
- return len === 2 * compressedLen || len === 2 * uncompressedLen;
- if (item instanceof Point2)
- return true;
- return false;
- }
- function getSharedSecret(privateA, publicB, isCompressed = true) {
- if (isProbPub(privateA))
- throw new Error("first arg must be private key");
- if (!isProbPub(publicB))
- throw new Error("second arg must be public key");
- const b = Point2.fromHex(publicB);
- return b.multiply(normPrivateKeyToScalar(privateA)).toRawBytes(isCompressed);
- }
- const bits2int = CURVE.bits2int || function(bytes4) {
- const num = bytesToNumberBE(bytes4);
- const delta = bytes4.length * 8 - CURVE.nBitLength;
- return delta > 0 ? num >> BigInt(delta) : num;
+ const bits2int_modN = ecdsaOpts.bits2int_modN || function bits2int_modN_def(bytes) {
+ return Fn.create(bits2int(bytes));
};
- const bits2int_modN = CURVE.bits2int_modN || function(bytes4) {
- return modN2(bits2int(bytes4));
- };
- const ORDER_MASK = bitMask(CURVE.nBitLength);
- function int2octets(num) {
- if (typeof num !== "bigint")
- throw new Error("bigint expected");
- if (!(_0n4 <= num && num < ORDER_MASK))
- throw new Error(`bigint expected < 2^${CURVE.nBitLength}`);
- return numberToBytesBE(num, CURVE.nByteLength);
+ const ORDER_MASK = bitMask(fnBits);
+ function int2octets(num2) {
+ aInRange("num < 2^" + fnBits, num2, _0n4, ORDER_MASK);
+ return Fn.toBytes(num2);
}
- function prepSig(msgHash, privateKey, opts = defaultSigOpts) {
- if (["recovered", "canonical"].some((k) => k in opts))
- throw new Error("sign() legacy options not supported");
- const { hash: hash3, randomBytes: randomBytes3 } = CURVE;
- let { lowS, prehash, extraEntropy: ent } = opts;
- if (lowS == null)
- lowS = true;
- msgHash = ensureBytes("msgHash", msgHash);
- if (prehash)
- msgHash = ensureBytes("prehashed msgHash", hash3(msgHash));
- const h1int = bits2int_modN(msgHash);
- const d = normPrivateKeyToScalar(privateKey);
- const seedArgs = [int2octets(d), int2octets(h1int)];
- if (ent != null) {
- const e = ent === true ? randomBytes3(Fp2.BYTES) : ent;
- seedArgs.push(ensureBytes("extraEntropy", e));
+ function validateMsgAndHash(message, prehash) {
+ abytes(message, void 0, "message");
+ return prehash ? abytes(hash(message), void 0, "prehashed message") : message;
+ }
+ function prepSig(message, secretKey, opts) {
+ const { lowS, prehash, extraEntropy } = validateSigOpts(opts, defaultSigOpts);
+ message = validateMsgAndHash(message, prehash);
+ const h1int = bits2int_modN(message);
+ const d = Fn.fromBytes(secretKey);
+ if (!Fn.isValidNot0(d))
+ throw new Error("invalid private key");
+ const seedArgs = [
+ int2octets(d),
+ int2octets(h1int)
+ ];
+ if (extraEntropy != null && extraEntropy !== false) {
+ const e = extraEntropy === true ? randomBytes4(lengths.secretKey) : extraEntropy;
+ seedArgs.push(abytes(e, void 0, "extraEntropy"));
}
- const seed = concatBytes2(...seedArgs);
+ const seed = concatBytes(...seedArgs);
const m = h1int;
function k2sig(kBytes) {
const k = bits2int(kBytes);
- if (!isWithinCurveOrder(k))
+ if (!Fn.isValidNot0(k))
return;
- const ik = invN(k);
- const q = Point2.BASE.multiply(k).toAffine();
- const r = modN2(q.x);
+ const ik = Fn.inv(k);
+ const q = Point.BASE.multiply(k).toAffine();
+ const r = Fn.create(q.x);
if (r === _0n4)
return;
- const s = modN2(ik * modN2(m + r * d));
+ const s = Fn.create(ik * Fn.create(m + r * d));
if (s === _0n4)
return;
let recovery = (q.x === r ? 0 : 2) | Number(q.y & _1n4);
let normS = s;
if (lowS && isBiggerThanHalfOrder(s)) {
- normS = normalizeS(s);
+ normS = Fn.neg(s);
recovery ^= 1;
}
- return new Signature(r, normS, recovery);
+ return new Signature(r, normS, hasLargeCofactor ? void 0 : recovery);
}
- return { seed, k2sig };
+ return {
+ seed,
+ k2sig
+ };
}
- const defaultSigOpts = { lowS: CURVE.lowS, prehash: false };
- const defaultVerOpts = { lowS: CURVE.lowS, prehash: false };
- function sign(msgHash, privKey, opts = defaultSigOpts) {
- const { seed, k2sig } = prepSig(msgHash, privKey, opts);
- const C = CURVE;
- const drbg = createHmacDrbg(C.hash.outputLen, C.nByteLength, C.hmac);
- return drbg(seed, k2sig);
+ function sign(message, secretKey, opts = {}) {
+ const { seed, k2sig } = prepSig(message, secretKey, opts);
+ const drbg = createHmacDrbg(hash.outputLen, Fn.BYTES, hmac3);
+ const sig = drbg(seed, k2sig);
+ return sig.toBytes(opts.format);
}
- Point2.BASE._setWindowSize(8);
- function verify(signature, msgHash, publicKey, opts = defaultVerOpts) {
- const sg = signature;
- msgHash = ensureBytes("msgHash", msgHash);
- publicKey = ensureBytes("publicKey", publicKey);
- if ("strict" in opts)
- throw new Error("options.strict was renamed to lowS");
- const { lowS, prehash } = opts;
- let _sig = void 0;
- let P;
+ function verify(signature, message, publicKey, opts = {}) {
+ const { lowS, prehash, format } = validateSigOpts(opts, defaultSigOpts);
+ publicKey = abytes(publicKey, void 0, "publicKey");
+ message = validateMsgAndHash(message, prehash);
+ if (!isBytes(signature)) {
+ const end = signature instanceof Signature ? ", use sig.toBytes()" : "";
+ throw new Error("verify expects Uint8Array signature" + end);
+ }
+ validateSigLength(signature, format);
try {
- if (typeof sg === "string" || sg instanceof Uint8Array) {
- try {
- _sig = Signature.fromDER(sg);
- } catch (derError) {
- if (!(derError instanceof DER.Err))
- throw derError;
- _sig = Signature.fromCompact(sg);
- }
- } else if (typeof sg === "object" && typeof sg.r === "bigint" && typeof sg.s === "bigint") {
- const { r: r2, s: s2 } = sg;
- _sig = new Signature(r2, s2);
- } else {
- throw new Error("PARSE");
- }
- P = Point2.fromHex(publicKey);
- } catch (error) {
- if (error.message === "PARSE")
- throw new Error(`signature must be Signature instance, Uint8Array or hex string`);
+ const sig = Signature.fromBytes(signature, format);
+ const P = Point.fromBytes(publicKey);
+ if (lowS && sig.hasHighS())
+ return false;
+ const { r, s } = sig;
+ const h = bits2int_modN(message);
+ const is = Fn.inv(s);
+ const u1 = Fn.create(h * is);
+ const u2 = Fn.create(r * is);
+ const R = Point.BASE.multiplyUnsafe(u1).add(P.multiplyUnsafe(u2));
+ if (R.is0())
+ return false;
+ const v = Fn.create(R.x);
+ return v === r;
+ } catch (e) {
return false;
}
- if (lowS && _sig.hasHighS())
- return false;
- if (prehash)
- msgHash = CURVE.hash(msgHash);
- const { r, s } = _sig;
- const h = bits2int_modN(msgHash);
- const is = invN(s);
- const u1 = modN2(h * is);
- const u2 = modN2(r * is);
- const R = Point2.BASE.multiplyAndAddUnsafe(P, u1, u2)?.toAffine();
- if (!R)
- return false;
- const v = modN2(R.x);
- return v === r;
}
- return {
- CURVE,
+ function recoverPublicKey(signature, message, opts = {}) {
+ const { prehash } = validateSigOpts(opts, defaultSigOpts);
+ message = validateMsgAndHash(message, prehash);
+ return Signature.fromBytes(signature, "recovered").recoverPublicKey(message).toBytes();
+ }
+ return Object.freeze({
+ keygen,
getPublicKey: getPublicKey2,
getSharedSecret,
+ utils,
+ lengths,
+ Point,
sign,
verify,
- ProjectivePoint: Point2,
+ recoverPublicKey,
Signature,
- utils
- };
+ hash
+ });
}
- // node_modules/@noble/curves/node_modules/@noble/hashes/esm/hmac.js
- var HMAC = class extends Hash {
- constructor(hash3, _key) {
- super();
- this.finished = false;
- this.destroyed = false;
- hash(hash3);
- const key = toBytes(_key);
- this.iHash = hash3.create();
- if (typeof this.iHash.update !== "function")
- throw new Error("Expected instance of class which extends utils.Hash");
- this.blockLen = this.iHash.blockLen;
- this.outputLen = this.iHash.outputLen;
- const blockLen = this.blockLen;
- const pad2 = new Uint8Array(blockLen);
- pad2.set(key.length > blockLen ? hash3.create().update(key).digest() : key);
- for (let i2 = 0; i2 < pad2.length; i2++)
- pad2[i2] ^= 54;
- this.iHash.update(pad2);
- this.oHash = hash3.create();
- for (let i2 = 0; i2 < pad2.length; i2++)
- pad2[i2] ^= 54 ^ 92;
- this.oHash.update(pad2);
- pad2.fill(0);
- }
- update(buf) {
- exists(this);
- this.iHash.update(buf);
- return this;
- }
- digestInto(out) {
- exists(this);
- bytes(out, this.outputLen);
- this.finished = true;
- this.iHash.digestInto(out);
- this.oHash.update(out);
- this.oHash.digestInto(out);
- this.destroy();
- }
- digest() {
- const out = new Uint8Array(this.oHash.outputLen);
- this.digestInto(out);
- return out;
- }
- _cloneInto(to) {
- to || (to = Object.create(Object.getPrototypeOf(this), {}));
- const { oHash, iHash, finished, destroyed, blockLen, outputLen } = this;
- to = to;
- to.finished = finished;
- to.destroyed = destroyed;
- to.blockLen = blockLen;
- to.outputLen = outputLen;
- to.oHash = oHash._cloneInto(to.oHash);
- to.iHash = iHash._cloneInto(to.iHash);
- return to;
- }
- destroy() {
- this.destroyed = true;
- this.oHash.destroy();
- this.iHash.destroy();
- }
+ // node_modules/@noble/curves/src/secp256k1.js
+ var secp256k1_CURVE = {
+ p: BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),
+ n: BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),
+ h: BigInt(1),
+ a: BigInt(0),
+ b: BigInt(7),
+ Gx: BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),
+ Gy: BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")
};
- var hmac = (hash3, key, message) => new HMAC(hash3, key).update(message).digest();
- hmac.create = (hash3, key) => new HMAC(hash3, key);
-
- // node_modules/@noble/curves/esm/_shortw_utils.js
- function getHash(hash3) {
- return {
- hash: hash3,
- hmac: (key, ...msgs) => hmac(hash3, key, concatBytes(...msgs)),
- randomBytes
- };
- }
- function createCurve(curveDef, defHash) {
- const create = (hash3) => weierstrass({ ...curveDef, ...getHash(hash3) });
- return Object.freeze({ ...create(defHash), create });
- }
-
- // node_modules/@noble/curves/esm/secp256k1.js
- var secp256k1P = BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f");
- var secp256k1N = BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141");
- var _1n5 = BigInt(1);
- var _2n4 = BigInt(2);
- var divNearest = (a, b) => (a + b / _2n4) / b;
+ var secp256k1_ENDO = {
+ beta: BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),
+ basises: [
+ [
+ BigInt("0x3086d221a7d46bcde86c90e49284eb15"),
+ -BigInt("0xe4437ed6010e88286f547fa90abfe4c3")
+ ],
+ [
+ BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),
+ BigInt("0x3086d221a7d46bcde86c90e49284eb15")
+ ]
+ ]
+ };
+ var _0n5 = /* @__PURE__ */ BigInt(0);
+ var _2n3 = /* @__PURE__ */ BigInt(2);
function sqrtMod(y) {
- const P = secp256k1P;
+ const P = secp256k1_CURVE.p;
const _3n3 = BigInt(3), _6n = BigInt(6), _11n = BigInt(11), _22n = BigInt(22);
const _23n = BigInt(23), _44n = BigInt(44), _88n = BigInt(88);
const b2 = y * y * y % P;
const b3 = b2 * b2 * y % P;
const b6 = pow2(b3, _3n3, P) * b3 % P;
const b9 = pow2(b6, _3n3, P) * b3 % P;
- const b11 = pow2(b9, _2n4, P) * b2 % P;
+ const b11 = pow2(b9, _2n3, P) * b2 % P;
const b22 = pow2(b11, _11n, P) * b11 % P;
const b44 = pow2(b22, _22n, P) * b22 % P;
const b88 = pow2(b44, _44n, P) * b44 % P;
const b176 = pow2(b88, _88n, P) * b88 % P;
const b220 = pow2(b176, _44n, P) * b44 % P;
const b223 = pow2(b220, _3n3, P) * b3 % P;
const t1 = pow2(b223, _23n, P) * b22 % P;
const t2 = pow2(t1, _6n, P) * b2 % P;
- const root = pow2(t2, _2n4, P);
- if (!Fp.eql(Fp.sqr(root), y))
+ const root = pow2(t2, _2n3, P);
+ if (!Fpk1.eql(Fpk1.sqr(root), y))
throw new Error("Cannot find square root");
return root;
}
- var Fp = Field(secp256k1P, void 0, void 0, { sqrt: sqrtMod });
- var secp256k1 = createCurve({
- a: BigInt(0),
- b: BigInt(7),
- Fp,
- n: secp256k1N,
- Gx: BigInt("55066263022277343669578718895168534326250603453777594175500187360389116729240"),
- Gy: BigInt("32670510020758816978083085130507043184471273380659243275938904335757337482424"),
- h: BigInt(1),
- lowS: true,
- endo: {
- beta: BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),
- splitScalar: (k) => {
- const n = secp256k1N;
- const a1 = BigInt("0x3086d221a7d46bcde86c90e49284eb15");
- const b1 = -_1n5 * BigInt("0xe4437ed6010e88286f547fa90abfe4c3");
- const a2 = BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8");
- const b2 = a1;
- const POW_2_128 = BigInt("0x100000000000000000000000000000000");
- const c1 = divNearest(b2 * k, n);
- const c2 = divNearest(-b1 * k, n);
- let k1 = mod(k - c1 * a1 - c2 * a2, n);
- let k2 = mod(-c1 * b1 - c2 * b2, n);
- const k1neg = k1 > POW_2_128;
- const k2neg = k2 > POW_2_128;
- if (k1neg)
- k1 = n - k1;
- if (k2neg)
- k2 = n - k2;
- if (k1 > POW_2_128 || k2 > POW_2_128) {
- throw new Error("splitScalar: Endomorphism failed, k=" + k);
- }
- return { k1neg, k1, k2neg, k2 };
- }
- }
- }, sha256);
- var _0n5 = BigInt(0);
- var fe = (x) => typeof x === "bigint" && _0n5 < x && x < secp256k1P;
- var ge = (x) => typeof x === "bigint" && _0n5 < x && x < secp256k1N;
+ var Fpk1 = Field(secp256k1_CURVE.p, {
+ sqrt: sqrtMod
+ });
+ var Pointk1 = /* @__PURE__ */ weierstrass(secp256k1_CURVE, {
+ Fp: Fpk1,
+ endo: secp256k1_ENDO
+ });
+ var secp256k1 = /* @__PURE__ */ ecdsa(Pointk1, sha256);
var TAGGED_HASH_PREFIXES = {};
function taggedHash(tag, ...messages) {
let tagP = TAGGED_HASH_PREFIXES[tag];
if (tagP === void 0) {
- const tagH = sha256(Uint8Array.from(tag, (c) => c.charCodeAt(0)));
- tagP = concatBytes2(tagH, tagH);
+ const tagH = sha256(asciiToBytes(tag));
+ tagP = concatBytes(tagH, tagH);
TAGGED_HASH_PREFIXES[tag] = tagP;
}
- return sha256(concatBytes2(tagP, ...messages));
+ return sha256(concatBytes(tagP, ...messages));
}
- var pointToBytes = (point) => point.toRawBytes(true).slice(1);
- var numTo32b = (n) => numberToBytesBE(n, 32);
- var modP = (x) => mod(x, secp256k1P);
- var modN = (x) => mod(x, secp256k1N);
- var Point = secp256k1.ProjectivePoint;
- var GmulAdd = (Q, a, b) => Point.BASE.multiplyAndAddUnsafe(Q, a, b);
+ var pointToBytes = (point) => point.toBytes(true).slice(1);
+ var hasEven = (y) => y % _2n3 === _0n5;
function schnorrGetExtPubKey(priv) {
- let d_ = secp256k1.utils.normPrivateKeyToScalar(priv);
- let p = Point.fromPrivateKey(d_);
- const scalar = p.hasEvenY() ? d_ : modN(-d_);
- return { scalar, bytes: pointToBytes(p) };
+ const { Fn, BASE } = Pointk1;
+ const d_ = Fn.fromBytes(priv);
+ const p = BASE.multiply(d_);
+ const scalar = hasEven(p.y) ? d_ : Fn.neg(d_);
+ return {
+ scalar,
+ bytes: pointToBytes(p)
+ };
}
function lift_x(x) {
- if (!fe(x))
- throw new Error("bad x: need 0 < x < p");
- const xx = modP(x * x);
- const c = modP(xx * x + BigInt(7));
- let y = sqrtMod(c);
- if (y % _2n4 !== _0n5)
- y = modP(-y);
- const p = new Point(x, y, _1n5);
+ const Fp = Fpk1;
+ if (!Fp.isValidNot0(x))
+ throw new Error("invalid x: Fail if x \u2265 p");
+ const xx = Fp.create(x * x);
+ const c = Fp.create(xx * x + BigInt(7));
+ let y = Fp.sqrt(c);
+ if (!hasEven(y))
+ y = Fp.neg(y);
+ const p = Pointk1.fromAffine({
+ x,
+ y
+ });
p.assertValidity();
return p;
}
+ var num = bytesToNumberBE;
function challenge(...args) {
- return modN(bytesToNumberBE(taggedHash("BIP0340/challenge", ...args)));
+ return Pointk1.Fn.create(num(taggedHash("BIP0340/challenge", ...args)));
}
- function schnorrGetPublicKey(privateKey) {
- return schnorrGetExtPubKey(privateKey).bytes;
+ function schnorrGetPublicKey(secretKey) {
+ return schnorrGetExtPubKey(secretKey).bytes;
}
- function schnorrSign(message, privateKey, auxRand = randomBytes(32)) {
- const m = ensureBytes("message", message);
- const { bytes: px, scalar: d } = schnorrGetExtPubKey(privateKey);
- const a = ensureBytes("auxRand", auxRand, 32);
- const t = numTo32b(d ^ bytesToNumberBE(taggedHash("BIP0340/aux", a)));
+ function schnorrSign(message, secretKey, auxRand = randomBytes(32)) {
+ const { Fn } = Pointk1;
+ const m = abytes(message, void 0, "message");
+ const { bytes: px, scalar: d } = schnorrGetExtPubKey(secretKey);
+ const a = abytes(auxRand, 32, "auxRand");
+ const t = Fn.toBytes(d ^ num(taggedHash("BIP0340/aux", a)));
const rand = taggedHash("BIP0340/nonce", t, px, m);
- const k_ = modN(bytesToNumberBE(rand));
- if (k_ === _0n5)
- throw new Error("sign failed: k is zero");
- const { bytes: rx, scalar: k } = schnorrGetExtPubKey(k_);
+ const { bytes: rx, scalar: k } = schnorrGetExtPubKey(rand);
const e = challenge(rx, px, m);
const sig = new Uint8Array(64);
sig.set(rx, 0);
- sig.set(numTo32b(modN(k + e * d)), 32);
+ sig.set(Fn.toBytes(Fn.create(k + e * d)), 32);
if (!schnorrVerify(sig, m, px))
throw new Error("sign: Invalid signature produced");
return sig;
}
function schnorrVerify(signature, message, publicKey) {
- const sig = ensureBytes("signature", signature, 64);
- const m = ensureBytes("message", message);
- const pub = ensureBytes("publicKey", publicKey, 32);
+ const { Fp, Fn, BASE } = Pointk1;
+ const sig = abytes(signature, 64, "signature");
+ const m = abytes(message, void 0, "message");
+ const pub = abytes(publicKey, 32, "publicKey");
try {
- const P = lift_x(bytesToNumberBE(pub));
- const r = bytesToNumberBE(sig.subarray(0, 32));
- if (!fe(r))
+ const P = lift_x(num(pub));
+ const r = num(sig.subarray(0, 32));
+ if (!Fp.isValidNot0(r))
return false;
- const s = bytesToNumberBE(sig.subarray(32, 64));
- if (!ge(s))
+ const s = num(sig.subarray(32, 64));
+ if (!Fn.isValidNot0(s))
return false;
- const e = challenge(numTo32b(r), pointToBytes(P), m);
- const R = GmulAdd(P, s, modN(-e));
- if (!R || !R.hasEvenY() || R.toAffine().x !== r)
+ const e = challenge(Fn.toBytes(r), pointToBytes(P), m);
+ const R = BASE.multiplyUnsafe(s).add(P.multiplyUnsafe(Fn.neg(e)));
+ const { x, y } = R.toAffine();
+ if (R.is0() || !hasEven(y) || x !== r)
return false;
return true;
} catch (error) {
return false;
}
}
- var schnorr = /* @__PURE__ */ (() => ({
- getPublicKey: schnorrGetPublicKey,
- sign: schnorrSign,
- verify: schnorrVerify,
- utils: {
- randomPrivateKey: secp256k1.utils.randomPrivateKey,
- lift_x,
- pointToBytes,
- numberToBytesBE,
- bytesToNumberBE,
- taggedHash,
- mod
- }
- }))();
+ var schnorr = /* @__PURE__ */ (() => {
+ const size = 32;
+ const seedLength = 48;
+ const randomSecretKey = (seed = randomBytes(seedLength)) => {
+ return mapHashToField(seed, secp256k1_CURVE.n);
+ };
+ return {
+ keygen: createKeygen(randomSecretKey, schnorrGetPublicKey),
+ getPublicKey: schnorrGetPublicKey,
+ sign: schnorrSign,
+ verify: schnorrVerify,
+ Point: Pointk1,
+ utils: {
+ randomSecretKey,
+ taggedHash,
+ lift_x,
+ pointToBytes
+ },
+ lengths: {
+ secretKey: size,
+ publicKey: size,
+ publicKeyHasPrefix: false,
+ signature: size * 2,
+ seed: seedLength
+ }
+ };
+ })();
- // node_modules/@noble/hashes/esm/crypto.js
- var crypto2 = typeof globalThis === "object" && "crypto" in globalThis ? globalThis.crypto : void 0;
-
- // node_modules/@noble/hashes/esm/utils.js
- var u8a3 = (a) => a instanceof Uint8Array;
- var createView2 = (arr) => new DataView(arr.buffer, arr.byteOffset, arr.byteLength);
- var rotr2 = (word, shift) => word << 32 - shift | word >>> shift;
- var isLE2 = new Uint8Array(new Uint32Array([287454020]).buffer)[0] === 68;
- if (!isLE2)
- throw new Error("Non little-endian hardware is not supported");
- var hexes2 = Array.from({ length: 256 }, (v, i2) => i2.toString(16).padStart(2, "0"));
- function bytesToHex2(bytes4) {
- if (!u8a3(bytes4))
- throw new Error("Uint8Array expected");
+ // node_modules/@noble/hashes/src/utils.js
+ function isBytes2(a) {
+ return a instanceof Uint8Array || ArrayBuffer.isView(a) && a.constructor.name === "Uint8Array";
+ }
+ function anumber2(n, title = "") {
+ if (!Number.isSafeInteger(n) || n < 0) {
+ const prefix = title && `"${title}" `;
+ throw new Error(`${prefix}expected integer >= 0, got ${n}`);
+ }
+ }
+ function abytes2(value, length, title = "") {
+ const bytes = isBytes2(value);
+ const len = value?.length;
+ const needsLen = length !== void 0;
+ if (!bytes || needsLen && len !== length) {
+ const prefix = title && `"${title}" `;
+ const ofLen = needsLen ? ` of length ${length}` : "";
+ const got = bytes ? `length=${len}` : `type=${typeof value}`;
+ throw new Error(prefix + "expected Uint8Array" + ofLen + ", got " + got);
+ }
+ return value;
+ }
+ function ahash2(h) {
+ if (typeof h !== "function" || typeof h.create !== "function")
+ throw new Error("Hash must wrapped by utils.createHasher");
+ anumber2(h.outputLen);
+ anumber2(h.blockLen);
+ }
+ function aexists2(instance, checkFinished = true) {
+ if (instance.destroyed)
+ throw new Error("Hash instance has been destroyed");
+ if (checkFinished && instance.finished)
+ throw new Error("Hash#digest() has already been called");
+ }
+ function aoutput2(out, instance) {
+ abytes2(out, void 0, "digestInto() output");
+ const min = instance.outputLen;
+ if (out.length < min) {
+ throw new Error('"digestInto() output" expected to be of length >=' + min);
+ }
+ }
+ function clean2(...arrays) {
+ for (let i2 = 0; i2 < arrays.length; i2++) {
+ arrays[i2].fill(0);
+ }
+ }
+ function createView2(arr) {
+ return new DataView(arr.buffer, arr.byteOffset, arr.byteLength);
+ }
+ function rotr2(word, shift) {
+ return word << 32 - shift | word >>> shift;
+ }
+ var hasHexBuiltin2 = /* @__PURE__ */ (() => typeof Uint8Array.from([]).toHex === "function" && typeof Uint8Array.fromHex === "function")();
+ var hexes2 = /* @__PURE__ */ Array.from({
+ length: 256
+ }, (_, i2) => i2.toString(16).padStart(2, "0"));
+ function bytesToHex2(bytes) {
+ abytes2(bytes);
+ if (hasHexBuiltin2)
+ return bytes.toHex();
let hex2 = "";
- for (let i2 = 0; i2 < bytes4.length; i2++) {
- hex2 += hexes2[bytes4[i2]];
+ for (let i2 = 0; i2 < bytes.length; i2++) {
+ hex2 += hexes2[bytes[i2]];
}
return hex2;
}
+ var asciis2 = {
+ _0: 48,
+ _9: 57,
+ A: 65,
+ F: 70,
+ a: 97,
+ f: 102
+ };
+ function asciiToBase162(ch) {
+ if (ch >= asciis2._0 && ch <= asciis2._9)
+ return ch - asciis2._0;
+ if (ch >= asciis2.A && ch <= asciis2.F)
+ return ch - (asciis2.A - 10);
+ if (ch >= asciis2.a && ch <= asciis2.f)
+ return ch - (asciis2.a - 10);
+ return;
+ }
function hexToBytes2(hex2) {
if (typeof hex2 !== "string")
throw new Error("hex string expected, got " + typeof hex2);
- const len = hex2.length;
- if (len % 2)
- throw new Error("padded hex string expected, got unpadded hex of length " + len);
- const array = new Uint8Array(len / 2);
- for (let i2 = 0; i2 < array.length; i2++) {
- const j = i2 * 2;
- const hexByte = hex2.slice(j, j + 2);
- const byte = Number.parseInt(hexByte, 16);
- if (Number.isNaN(byte) || byte < 0)
- throw new Error("Invalid byte sequence");
- array[i2] = byte;
+ if (hasHexBuiltin2)
+ return Uint8Array.fromHex(hex2);
+ const hl = hex2.length;
+ const al = hl / 2;
+ if (hl % 2)
+ throw new Error("hex string expected, got unpadded hex of length " + hl);
+ const array = new Uint8Array(al);
+ for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) {
+ const n1 = asciiToBase162(hex2.charCodeAt(hi));
+ const n2 = asciiToBase162(hex2.charCodeAt(hi + 1));
+ if (n1 === void 0 || n2 === void 0) {
+ const char = hex2[hi] + hex2[hi + 1];
+ throw new Error('hex string expected, got non-hex character "' + char + '" at index ' + hi);
+ }
+ array[ai] = n1 * 16 + n2;
}
return array;
}
- function utf8ToBytes3(str) {
- if (typeof str !== "string")
- throw new Error(`utf8ToBytes expected string, got ${typeof str}`);
- return new Uint8Array(new TextEncoder().encode(str));
- }
- function toBytes2(data) {
- if (typeof data === "string")
- data = utf8ToBytes3(data);
- if (!u8a3(data))
- throw new Error(`expected Uint8Array, got ${typeof data}`);
- return data;
- }
- function concatBytes3(...arrays) {
- const r = new Uint8Array(arrays.reduce((sum, a) => sum + a.length, 0));
- let pad2 = 0;
- arrays.forEach((a) => {
- if (!u8a3(a))
- throw new Error("Uint8Array expected");
- r.set(a, pad2);
+ function concatBytes2(...arrays) {
+ let sum = 0;
+ for (let i2 = 0; i2 < arrays.length; i2++) {
+ const a = arrays[i2];
+ abytes2(a);
+ sum += a.length;
+ }
+ const res = new Uint8Array(sum);
+ for (let i2 = 0, pad2 = 0; i2 < arrays.length; i2++) {
+ const a = arrays[i2];
+ res.set(a, pad2);
pad2 += a.length;
- });
- return r;
- }
- var Hash2 = class {
- clone() {
- return this._cloneInto();
}
- };
- function wrapConstructor2(hashCons) {
- const hashC = (msg) => hashCons().update(toBytes2(msg)).digest();
- const tmp = hashCons();
+ return res;
+ }
+ function createHasher3(hashCons, info = {}) {
+ const hashC = (msg, opts) => hashCons(opts).update(msg).digest();
+ const tmp = hashCons(void 0);
hashC.outputLen = tmp.outputLen;
hashC.blockLen = tmp.blockLen;
- hashC.create = () => hashCons();
- return hashC;
+ hashC.create = (opts) => hashCons(opts);
+ Object.assign(hashC, info);
+ return Object.freeze(hashC);
}
function randomBytes2(bytesLength = 32) {
- if (crypto2 && typeof crypto2.getRandomValues === "function") {
- return crypto2.getRandomValues(new Uint8Array(bytesLength));
- }
- throw new Error("crypto.getRandomValues must be defined");
+ const cr = typeof globalThis === "object" ? globalThis.crypto : null;
+ if (typeof cr?.getRandomValues !== "function")
+ throw new Error("crypto.getRandomValues must be defined");
+ return cr.getRandomValues(new Uint8Array(bytesLength));
}
+ var oidNist2 = (suffix) => ({
+ oid: Uint8Array.from([
+ 6,
+ 9,
+ 96,
+ 134,
+ 72,
+ 1,
+ 101,
+ 3,
+ 4,
+ 2,
+ suffix
+ ])
+ });
// core.ts
var verifiedSymbol = Symbol("verified");
var isRecord = (obj) => obj instanceof Object;
@@ -2055,83 +2554,38 @@
return a.id.localeCompare(b.id);
});
}
- // node_modules/@noble/hashes/esm/_assert.js
- function number2(n) {
- if (!Number.isSafeInteger(n) || n < 0)
- throw new Error(`Wrong positive integer: ${n}`);
+ // node_modules/@noble/hashes/src/_md.js
+ function Chi2(a, b, c) {
+ return a & b ^ ~a & c;
}
- function bool(b) {
- if (typeof b !== "boolean")
- throw new Error(`Expected boolean, not ${b}`);
+ function Maj2(a, b, c) {
+ return a & b ^ a & c ^ b & c;
}
- function bytes2(b, ...lengths) {
- if (!(b instanceof Uint8Array))
- throw new Error("Expected Uint8Array");
- if (lengths.length > 0 && !lengths.includes(b.length))
- throw new Error(`Expected Uint8Array of length ${lengths}, not of length=${b.length}`);
- }
- function hash2(hash3) {
- if (typeof hash3 !== "function" || typeof hash3.create !== "function")
- throw new Error("Hash should be wrapped by utils.wrapConstructor");
- number2(hash3.outputLen);
- number2(hash3.blockLen);
- }
- function exists2(instance, checkFinished = true) {
- if (instance.destroyed)
- throw new Error("Hash instance has been destroyed");
- if (checkFinished && instance.finished)
- throw new Error("Hash#digest() has already been called");
- }
- function output2(out, instance) {
- bytes2(out);
- const min = instance.outputLen;
- if (out.length < min) {
- throw new Error(`digestInto() expects output buffer of length at least ${min}`);
- }
- }
- var assert = {
- number: number2,
- bool,
- bytes: bytes2,
- hash: hash2,
- exists: exists2,
- output: output2
- };
- var assert_default = assert;
-
- // node_modules/@noble/hashes/esm/_sha2.js
- function setBigUint642(view, byteOffset, value, isLE4) {
- if (typeof view.setBigUint64 === "function")
- return view.setBigUint64(byteOffset, value, isLE4);
- const _32n = BigInt(32);
- const _u32_max = BigInt(4294967295);
- const wh = Number(value >> _32n & _u32_max);
- const wl = Number(value & _u32_max);
- const h = isLE4 ? 4 : 0;
- const l = isLE4 ? 0 : 4;
- view.setUint32(byteOffset + h, wh, isLE4);
- view.setUint32(byteOffset + l, wl, isLE4);
- }
- var SHA22 = class extends Hash2 {
- constructor(blockLen, outputLen, padOffset, isLE4) {
- super();
+ var HashMD2 = class {
+ blockLen;
+ outputLen;
+ padOffset;
+ isLE;
+ buffer;
+ view;
+ finished = false;
+ length = 0;
+ pos = 0;
+ destroyed = false;
+ constructor(blockLen, outputLen, padOffset, isLE2) {
this.blockLen = blockLen;
this.outputLen = outputLen;
this.padOffset = padOffset;
- this.isLE = isLE4;
- this.finished = false;
- this.length = 0;
- this.pos = 0;
- this.destroyed = false;
+ this.isLE = isLE2;
this.buffer = new Uint8Array(blockLen);
this.view = createView2(this.buffer);
}
update(data) {
- assert_default.exists(this);
+ aexists2(this);
+ abytes2(data);
const { view, buffer, blockLen } = this;
- data = toBytes2(data);
const len = data.length;
for (let pos = 0; pos < len; ) {
const take = Math.min(blockLen - this.pos, len - pos);
if (take === blockLen) {
@@ -2152,33 +2606,33 @@
this.roundClean();
return this;
}
digestInto(out) {
- assert_default.exists(this);
- assert_default.output(out, this);
+ aexists2(this);
+ aoutput2(out, this);
this.finished = true;
- const { buffer, view, blockLen, isLE: isLE4 } = this;
+ const { buffer, view, blockLen, isLE: isLE2 } = this;
let { pos } = this;
buffer[pos++] = 128;
- this.buffer.subarray(pos).fill(0);
+ clean2(this.buffer.subarray(pos));
if (this.padOffset > blockLen - pos) {
this.process(view, 0);
pos = 0;
}
for (let i2 = pos; i2 < blockLen; i2++)
buffer[i2] = 0;
- setBigUint642(view, blockLen - 8, BigInt(this.length * 8), isLE4);
+ view.setBigUint64(blockLen - 8, BigInt(this.length * 8), isLE2);
this.process(view, 0);
const oview = createView2(out);
const len = this.outputLen;
if (len % 4)
- throw new Error("_sha2: outputLen should be aligned to 32bit");
+ throw new Error("_sha2: outputLen must be aligned to 32bit");
const outLen = len / 4;
const state = this.get();
if (outLen > state.length)
throw new Error("_sha2: outputLen bigger than state");
for (let i2 = 0; i2 < outLen; i2++)
- oview.setUint32(4 * i2, state[i2], isLE4);
+ oview.setUint32(4 * i2, state[i2], isLE2);
}
digest() {
const { buffer, outputLen } = this;
this.digestInto(buffer);
@@ -2186,25 +2640,39 @@
this.destroy();
return res;
}
_cloneInto(to) {
- to || (to = new this.constructor());
+ to ||= new this.constructor();
to.set(...this.get());
const { blockLen, buffer, length, finished, destroyed, pos } = this;
+ to.destroyed = destroyed;
+ to.finished = finished;
to.length = length;
to.pos = pos;
- to.finished = finished;
- to.destroyed = destroyed;
if (length % blockLen)
to.buffer.set(buffer);
return to;
}
+ clone() {
+ return this._cloneInto();
+ }
};
+ var SHA256_IV2 = /* @__PURE__ */ Uint32Array.from([
+ 1779033703,
+ 3144134277,
+ 1013904242,
+ 2773480762,
+ 1359893119,
+ 2600822924,
+ 528734635,
+ 1541459225
+ ]);
- // node_modules/@noble/hashes/esm/sha256.js
- var Chi2 = (a, b, c) => a & b ^ ~a & c;
- var Maj2 = (a, b, c) => a & b ^ a & c ^ b & c;
- var SHA256_K2 = new Uint32Array([
+ // node_modules/@noble/hashes/src/_u64.js
+ var U32_MASK642 = /* @__PURE__ */ BigInt(2 ** 32 - 1);
+
+ // node_modules/@noble/hashes/src/sha2.js
+ var SHA256_K2 = /* @__PURE__ */ Uint32Array.from([
1116352408,
1899447441,
3049323471,
3921009573,
@@ -2268,34 +2736,25 @@
2756734187,
3204031479,
3329325298
]);
- var IV2 = new Uint32Array([
- 1779033703,
- 3144134277,
- 1013904242,
- 2773480762,
- 1359893119,
- 2600822924,
- 528734635,
- 1541459225
- ]);
- var SHA256_W2 = new Uint32Array(64);
- var SHA2562 = class extends SHA22 {
- constructor() {
- super(64, 32, 8, false);
- this.A = IV2[0] | 0;
- this.B = IV2[1] | 0;
- this.C = IV2[2] | 0;
- this.D = IV2[3] | 0;
- this.E = IV2[4] | 0;
- this.F = IV2[5] | 0;
- this.G = IV2[6] | 0;
- this.H = IV2[7] | 0;
+ var SHA256_W2 = /* @__PURE__ */ new Uint32Array(64);
+ var SHA2_32B2 = class extends HashMD2 {
+ constructor(outputLen) {
+ super(64, outputLen, 8, false);
}
get() {
const { A, B, C, D, E, F, G, H } = this;
- return [A, B, C, D, E, F, G, H];
+ return [
+ A,
+ B,
+ C,
+ D,
+ E,
+ F,
+ G,
+ H
+ ];
}
set(A, B, C, D, E, F, G, H) {
this.A = A | 0;
this.B = B | 0;
@@ -2341,35 +2800,33 @@
H = H + this.H | 0;
this.set(A, B, C, D, E, F, G, H);
}
roundClean() {
- SHA256_W2.fill(0);
+ clean2(SHA256_W2);
}
destroy() {
this.set(0, 0, 0, 0, 0, 0, 0, 0);
- this.buffer.fill(0);
+ clean2(this.buffer);
}
};
- var SHA224 = class extends SHA2562 {
+ var _SHA2562 = class extends SHA2_32B2 {
+ A = SHA256_IV2[0] | 0;
+ B = SHA256_IV2[1] | 0;
+ C = SHA256_IV2[2] | 0;
+ D = SHA256_IV2[3] | 0;
+ E = SHA256_IV2[4] | 0;
+ F = SHA256_IV2[5] | 0;
+ G = SHA256_IV2[6] | 0;
+ H = SHA256_IV2[7] | 0;
constructor() {
- super();
- this.A = 3238371032 | 0;
- this.B = 914150663 | 0;
- this.C = 812702999 | 0;
- this.D = 4144912697 | 0;
- this.E = 4290775857 | 0;
- this.F = 1750603025 | 0;
- this.G = 1694076839 | 0;
- this.H = 3204075428 | 0;
- this.outputLen = 28;
+ super(32);
}
};
- var sha2562 = wrapConstructor2(() => new SHA2562());
- var sha224 = wrapConstructor2(() => new SHA224());
+ var sha2562 = /* @__PURE__ */ createHasher3(() => new _SHA2562(), /* @__PURE__ */ oidNist2(1));
// utils.ts
- var utils_exports2 = {};
- __export(utils_exports2, {
+ var utils_exports = {};
+ __export(utils_exports, {
Queue: () => Queue,
QueueNode: () => QueueNode,
binarySearch: () => binarySearch,
bytesToHex: () => bytesToHex2,
@@ -2497,31 +2954,31 @@
// pure.ts
var JS = class {
generateSecretKey() {
- return schnorr.utils.randomPrivateKey();
+ return schnorr.utils.randomSecretKey();
}
getPublicKey(secretKey) {
return bytesToHex2(schnorr.getPublicKey(secretKey));
}
finalizeEvent(t, secretKey) {
const event = t;
event.pubkey = bytesToHex2(schnorr.getPublicKey(secretKey));
event.id = getEventHash(event);
- event.sig = bytesToHex2(schnorr.sign(getEventHash(event), secretKey));
+ event.sig = bytesToHex2(schnorr.sign(hexToBytes2(getEventHash(event)), secretKey));
event[verifiedSymbol] = true;
return event;
}
verifyEvent(event) {
if (typeof event[verifiedSymbol] === "boolean")
return event[verifiedSymbol];
- const hash3 = getEventHash(event);
- if (hash3 !== event.id) {
+ const hash = getEventHash(event);
+ if (hash !== event.id) {
event[verifiedSymbol] = false;
return false;
}
try {
- const valid = schnorr.verify(event.sig, hash3, event.pubkey);
+ const valid = schnorr.verify(hexToBytes2(event.sig), hexToBytes2(hash), hexToBytes2(event.pubkey));
event[verifiedSymbol] = valid;
return valid;
} catch (err) {
event[verifiedSymbol] = false;
@@ -3691,134 +4148,173 @@
npubEncode: () => npubEncode,
nsecEncode: () => nsecEncode
});
- // node_modules/@scure/base/lib/esm/index.js
- function assertNumber(n) {
+ // node_modules/@scure/base/index.js
+ function isBytes3(a) {
+ return a instanceof Uint8Array || ArrayBuffer.isView(a) && a.constructor.name === "Uint8Array";
+ }
+ function abytes3(b) {
+ if (!isBytes3(b))
+ throw new Error("Uint8Array expected");
+ }
+ function isArrayOf(isString, arr) {
+ if (!Array.isArray(arr))
+ return false;
+ if (arr.length === 0)
+ return true;
+ if (isString) {
+ return arr.every((item) => typeof item === "string");
+ } else {
+ return arr.every((item) => Number.isSafeInteger(item));
+ }
+ }
+ function afn(input) {
+ if (typeof input !== "function")
+ throw new Error("function expected");
+ return true;
+ }
+ function astr(label, input) {
+ if (typeof input !== "string")
+ throw new Error(`${label}: string expected`);
+ return true;
+ }
+ function anumber3(n) {
if (!Number.isSafeInteger(n))
- throw new Error(`Wrong integer: ${n}`);
+ throw new Error(`invalid integer: ${n}`);
}
+ function aArr(input) {
+ if (!Array.isArray(input))
+ throw new Error("array expected");
+ }
+ function astrArr(label, input) {
+ if (!isArrayOf(true, input))
+ throw new Error(`${label}: array of strings expected`);
+ }
+ function anumArr(label, input) {
+ if (!isArrayOf(false, input))
+ throw new Error(`${label}: array of numbers expected`);
+ }
function chain(...args) {
+ const id = (a) => a;
const wrap = (a, b) => (c) => a(b(c));
- const encode = Array.from(args).reverse().reduce((acc, i2) => acc ? wrap(acc, i2.encode) : i2.encode, void 0);
- const decode2 = args.reduce((acc, i2) => acc ? wrap(acc, i2.decode) : i2.decode, void 0);
- return { encode, decode: decode2 };
+ const encode = args.map((x) => x.encode).reduceRight(wrap, id);
+ const decode2 = args.map((x) => x.decode).reduce(wrap, id);
+ return {
+ encode,
+ decode: decode2
+ };
}
- function alphabet(alphabet2) {
+ function alphabet(letters) {
+ const lettersA = typeof letters === "string" ? letters.split("") : letters;
+ const len = lettersA.length;
+ astrArr("alphabet", lettersA);
+ const indexes = new Map(lettersA.map((l, i2) => [
+ l,
+ i2
+ ]));
return {
encode: (digits) => {
- if (!Array.isArray(digits) || digits.length && typeof digits[0] !== "number")
- throw new Error("alphabet.encode input should be an array of numbers");
+ aArr(digits);
return digits.map((i2) => {
- assertNumber(i2);
- if (i2 < 0 || i2 >= alphabet2.length)
- throw new Error(`Digit index outside alphabet: ${i2} (alphabet: ${alphabet2.length})`);
- return alphabet2[i2];
+ if (!Number.isSafeInteger(i2) || i2 < 0 || i2 >= len)
+ throw new Error(`alphabet.encode: digit index outside alphabet "${i2}". Allowed: ${letters}`);
+ return lettersA[i2];
});
},
decode: (input) => {
- if (!Array.isArray(input) || input.length && typeof input[0] !== "string")
- throw new Error("alphabet.decode input should be array of strings");
+ aArr(input);
return input.map((letter) => {
- if (typeof letter !== "string")
- throw new Error(`alphabet.decode: not string element=${letter}`);
- const index = alphabet2.indexOf(letter);
- if (index === -1)
- throw new Error(`Unknown letter: "${letter}". Allowed: ${alphabet2}`);
- return index;
+ astr("alphabet.decode", letter);
+ const i2 = indexes.get(letter);
+ if (i2 === void 0)
+ throw new Error(`Unknown letter: "${letter}". Allowed: ${letters}`);
+ return i2;
});
}
};
}
function join(separator = "") {
- if (typeof separator !== "string")
- throw new Error("join separator should be string");
+ astr("join", separator);
return {
encode: (from) => {
- if (!Array.isArray(from) || from.length && typeof from[0] !== "string")
- throw new Error("join.encode input should be array of strings");
- for (let i2 of from)
- if (typeof i2 !== "string")
- throw new Error(`join.encode: non-string input=${i2}`);
+ astrArr("join.decode", from);
return from.join(separator);
},
decode: (to) => {
- if (typeof to !== "string")
- throw new Error("join.decode input should be string");
+ astr("join.decode", to);
return to.split(separator);
}
};
}
function padding(bits, chr = "=") {
- assertNumber(bits);
- if (typeof chr !== "string")
- throw new Error("padding chr should be string");
+ anumber3(bits);
+ astr("padding", chr);
return {
encode(data) {
- if (!Array.isArray(data) || data.length && typeof data[0] !== "string")
- throw new Error("padding.encode input should be array of strings");
- for (let i2 of data)
- if (typeof i2 !== "string")
- throw new Error(`padding.encode: non-string input=${i2}`);
+ astrArr("padding.encode", data);
while (data.length * bits % 8)
data.push(chr);
return data;
},
decode(input) {
- if (!Array.isArray(input) || input.length && typeof input[0] !== "string")
- throw new Error("padding.encode input should be array of strings");
- for (let i2 of input)
- if (typeof i2 !== "string")
- throw new Error(`padding.decode: non-string input=${i2}`);
+ astrArr("padding.decode", input);
let end = input.length;
if (end * bits % 8)
- throw new Error("Invalid padding: string should have whole number of bytes");
+ throw new Error("padding: invalid, string should have whole number of bytes");
for (; end > 0 && input[end - 1] === chr; end--) {
- if (!((end - 1) * bits % 8))
- throw new Error("Invalid padding: string has too much padding");
+ const last = end - 1;
+ const byte = last * bits;
+ if (byte % 8 === 0)
+ throw new Error("padding: invalid, string has too much padding");
}
return input.slice(0, end);
}
};
}
function normalize(fn) {
- if (typeof fn !== "function")
- throw new Error("normalize fn should be function");
- return { encode: (from) => from, decode: (to) => fn(to) };
+ afn(fn);
+ return {
+ encode: (from) => from,
+ decode: (to) => fn(to)
+ };
}
function convertRadix(data, from, to) {
if (from < 2)
- throw new Error(`convertRadix: wrong from=${from}, base cannot be less than 2`);
+ throw new Error(`convertRadix: invalid from=${from}, base cannot be less than 2`);
if (to < 2)
- throw new Error(`convertRadix: wrong to=${to}, base cannot be less than 2`);
- if (!Array.isArray(data))
- throw new Error("convertRadix: data should be array");
+ throw new Error(`convertRadix: invalid to=${to}, base cannot be less than 2`);
+ aArr(data);
if (!data.length)
return [];
let pos = 0;
const res = [];
- const digits = Array.from(data);
- digits.forEach((d) => {
- assertNumber(d);
+ const digits = Array.from(data, (d) => {
+ anumber3(d);
if (d < 0 || d >= from)
- throw new Error(`Wrong integer: ${d}`);
+ throw new Error(`invalid integer: ${d}`);
+ return d;
});
+ const dlen = digits.length;
while (true) {
let carry = 0;
let done = true;
- for (let i2 = pos; i2 < digits.length; i2++) {
+ for (let i2 = pos; i2 < dlen; i2++) {
const digit = digits[i2];
- const digitBase = from * carry + digit;
- if (!Number.isSafeInteger(digitBase) || from * carry / from !== carry || digitBase - digit !== from * carry) {
+ const fromCarry = from * carry;
+ const digitBase = fromCarry + digit;
+ if (!Number.isSafeInteger(digitBase) || fromCarry / from !== carry || digitBase - digit !== fromCarry) {
throw new Error("convertRadix: carry overflow");
}
+ const div = digitBase / to;
carry = digitBase % to;
- digits[i2] = Math.floor(digitBase / to);
- if (!Number.isSafeInteger(digits[i2]) || digits[i2] * to + carry !== digitBase)
+ const rounded = Math.floor(div);
+ digits[i2] = rounded;
+ if (!Number.isSafeInteger(rounded) || rounded * to + carry !== digitBase)
throw new Error("convertRadix: carry overflow");
if (!done)
continue;
- else if (!digits[i2])
+ else if (!rounded)
pos = i2;
else
done = false;
}
@@ -3829,13 +4325,18 @@
for (let i2 = 0; i2 < data.length - 1 && data[i2] === 0; i2++)
res.push(0);
return res.reverse();
}
- var gcd = (a, b) => !b ? a : gcd(b, a % b);
+ var gcd = (a, b) => b === 0 ? a : gcd(b, a % b);
var radix2carry = (from, to) => from + (to - gcd(from, to));
+ var powers = /* @__PURE__ */ (() => {
+ let res = [];
+ for (let i2 = 0; i2 < 40; i2++)
+ res.push(2 ** i2);
+ return res;
+ })();
function convertRadix2(data, from, to, padding2) {
- if (!Array.isArray(data))
- throw new Error("convertRadix2: data should be array");
+ aArr(data);
if (from <= 0 || from > 32)
throw new Error(`convertRadix2: wrong from=${from}`);
if (to <= 0 || to > 32)
throw new Error(`convertRadix2: wrong to=${to}`);
@@ -3843,68 +4344,70 @@
throw new Error(`convertRadix2: carry overflow from=${from} to=${to} carryBits=${radix2carry(from, to)}`);
}
let carry = 0;
let pos = 0;
- const mask = 2 ** to - 1;
+ const max = powers[from];
+ const mask = powers[to] - 1;
const res = [];
for (const n of data) {
- assertNumber(n);
- if (n >= 2 ** from)
+ anumber3(n);
+ if (n >= max)
throw new Error(`convertRadix2: invalid data word=${n} from=${from}`);
carry = carry << from | n;
if (pos + from > 32)
throw new Error(`convertRadix2: carry overflow pos=${pos} from=${from}`);
pos += from;
for (; pos >= to; pos -= to)
res.push((carry >> pos - to & mask) >>> 0);
- carry &= 2 ** pos - 1;
+ const pow = powers[pos];
+ if (pow === void 0)
+ throw new Error("invalid carry");
+ carry &= pow - 1;
}
carry = carry << to - pos & mask;
if (!padding2 && pos >= from)
throw new Error("Excess padding");
- if (!padding2 && carry)
+ if (!padding2 && carry > 0)
throw new Error(`Non-zero padding: ${carry}`);
if (padding2 && pos > 0)
res.push(carry >>> 0);
return res;
}
- function radix(num) {
- assertNumber(num);
+ function radix(num2) {
+ anumber3(num2);
+ const _256 = 2 ** 8;
return {
- encode: (bytes4) => {
- if (!(bytes4 instanceof Uint8Array))
+ encode: (bytes) => {
+ if (!isBytes3(bytes))
throw new Error("radix.encode input should be Uint8Array");
- return convertRadix(Array.from(bytes4), 2 ** 8, num);
+ return convertRadix(Array.from(bytes), _256, num2);
},
decode: (digits) => {
- if (!Array.isArray(digits) || digits.length && typeof digits[0] !== "number")
- throw new Error("radix.decode input should be array of strings");
- return Uint8Array.from(convertRadix(digits, num, 2 ** 8));
+ anumArr("radix.decode", digits);
+ return Uint8Array.from(convertRadix(digits, num2, _256));
}
};
}
function radix2(bits, revPadding = false) {
- assertNumber(bits);
+ anumber3(bits);
if (bits <= 0 || bits > 32)
throw new Error("radix2: bits should be in (0..32]");
if (radix2carry(8, bits) > 32 || radix2carry(bits, 8) > 32)
throw new Error("radix2: carry overflow");
return {
- encode: (bytes4) => {
- if (!(bytes4 instanceof Uint8Array))
+ encode: (bytes) => {
+ if (!isBytes3(bytes))
throw new Error("radix2.encode input should be Uint8Array");
- return convertRadix2(Array.from(bytes4), 8, bits, !revPadding);
+ return convertRadix2(Array.from(bytes), 8, bits, !revPadding);
},
decode: (digits) => {
- if (!Array.isArray(digits) || digits.length && typeof digits[0] !== "number")
- throw new Error("radix2.decode input should be array of strings");
+ anumArr("radix2.decode", digits);
return Uint8Array.from(convertRadix2(digits, bits, 8, revPadding));
}
};
}
function unsafeWrapper(fn) {
- if (typeof fn !== "function")
- throw new Error("unsafeWrapper fn should be function");
+ afn(fn);
return function(...args) {
try {
return fn.apply(null, args);
} catch (e) {
@@ -3912,43 +4415,58 @@
};
}
var base16 = chain(radix2(4), alphabet("0123456789ABCDEF"), join(""));
var base32 = chain(radix2(5), alphabet("ABCDEFGHIJKLMNOPQRSTUVWXYZ234567"), padding(5), join(""));
+ var base32nopad = chain(radix2(5), alphabet("ABCDEFGHIJKLMNOPQRSTUVWXYZ234567"), join(""));
var base32hex = chain(radix2(5), alphabet("0123456789ABCDEFGHIJKLMNOPQRSTUV"), padding(5), join(""));
+ var base32hexnopad = chain(radix2(5), alphabet("0123456789ABCDEFGHIJKLMNOPQRSTUV"), join(""));
var base32crockford = chain(radix2(5), alphabet("0123456789ABCDEFGHJKMNPQRSTVWXYZ"), join(""), normalize((s) => s.toUpperCase().replace(/O/g, "0").replace(/[IL]/g, "1")));
- var base64 = chain(radix2(6), alphabet("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"), padding(6), join(""));
- var base64url = chain(radix2(6), alphabet("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"), padding(6), join(""));
+ var hasBase64Builtin = /* @__PURE__ */ (() => typeof Uint8Array.from([]).toBase64 === "function" && typeof Uint8Array.fromBase64 === "function")();
+ var decodeBase64Builtin = (s, isUrl) => {
+ astr("base64", s);
+ const re = isUrl ? /^[A-Za-z0-9=_-]+$/ : /^[A-Za-z0-9=+/]+$/;
+ const alphabet2 = isUrl ? "base64url" : "base64";
+ if (s.length > 0 && !re.test(s))
+ throw new Error("invalid base64");
+ return Uint8Array.fromBase64(s, {
+ alphabet: alphabet2,
+ lastChunkHandling: "strict"
+ });
+ };
+ var base64 = hasBase64Builtin ? {
+ encode(b) {
+ abytes3(b);
+ return b.toBase64();
+ },
+ decode(s) {
+ return decodeBase64Builtin(s, false);
+ }
+ } : chain(radix2(6), alphabet("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"), padding(6), join(""));
+ var base64nopad = chain(radix2(6), alphabet("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"), join(""));
+ var base64url = hasBase64Builtin ? {
+ encode(b) {
+ abytes3(b);
+ return b.toBase64({
+ alphabet: "base64url"
+ });
+ },
+ decode(s) {
+ return decodeBase64Builtin(s, true);
+ }
+ } : chain(radix2(6), alphabet("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"), padding(6), join(""));
+ var base64urlnopad = chain(radix2(6), alphabet("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"), join(""));
var genBase58 = (abc) => chain(radix(58), alphabet(abc), join(""));
var base58 = genBase58("123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz");
var base58flickr = genBase58("123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ");
var base58xrp = genBase58("rpshnaf39wBUDNEGHJKLM4PQRST7VWXYZ2bcdeCg65jkm8oFqi1tuvAxyz");
- var XMR_BLOCK_LEN = [0, 2, 3, 5, 6, 7, 9, 10, 11];
- var base58xmr = {
- encode(data) {
- let res = "";
- for (let i2 = 0; i2 < data.length; i2 += 8) {
- const block = data.subarray(i2, i2 + 8);
- res += base58.encode(block).padStart(XMR_BLOCK_LEN[block.length], "1");
- }
- return res;
- },
- decode(str) {
- let res = [];
- for (let i2 = 0; i2 < str.length; i2 += 11) {
- const slice = str.slice(i2, i2 + 11);
- const blockLen = XMR_BLOCK_LEN.indexOf(slice.length);
- const block = base58.decode(slice);
- for (let j = 0; j < block.length - blockLen; j++) {
- if (block[j] !== 0)
- throw new Error("base58xmr: wrong padding");
- }
- res = res.concat(Array.from(block.slice(block.length - blockLen)));
- }
- return Uint8Array.from(res);
- }
- };
var BECH_ALPHABET = chain(alphabet("qpzry9x8gf2tvdw0s3jn54khce6mua7l"), join(""));
- var POLYMOD_GENERATORS = [996825010, 642813549, 513874426, 1027748829, 705979059];
+ var POLYMOD_GENERATORS = [
+ 996825010,
+ 642813549,
+ 513874426,
+ 1027748829,
+ 705979059
+ ];
function bech32Polymod(pre) {
const b = pre >> 25;
let chk = (pre & 33554431) << 5;
for (let i2 = 0; i2 < POLYMOD_GENERATORS.length; i2++) {
@@ -3973,78 +4491,98 @@
chk = bech32Polymod(chk) ^ v;
for (let i2 = 0; i2 < 6; i2++)
chk = bech32Polymod(chk);
chk ^= encodingConst;
- return BECH_ALPHABET.encode(convertRadix2([chk % 2 ** 30], 30, 5, false));
+ return BECH_ALPHABET.encode(convertRadix2([
+ chk % powers[30]
+ ], 30, 5, false));
}
function genBech32(encoding) {
const ENCODING_CONST = encoding === "bech32" ? 1 : 734539939;
const _words = radix2(5);
const fromWords = _words.decode;
const toWords = _words.encode;
const fromWordsUnsafe = unsafeWrapper(fromWords);
- function encode(prefix, words, limit2 = 90) {
- if (typeof prefix !== "string")
- throw new Error(`bech32.encode prefix should be string, not ${typeof prefix}`);
- if (!Array.isArray(words) || words.length && typeof words[0] !== "number")
- throw new Error(`bech32.encode words should be array of numbers, not ${typeof words}`);
- const actualLength = prefix.length + 7 + words.length;
- if (limit2 !== false && actualLength > limit2)
- throw new TypeError(`Length ${actualLength} exceeds limit ${limit2}`);
- prefix = prefix.toLowerCase();
- return `${prefix}1${BECH_ALPHABET.encode(words)}${bechChecksum(prefix, words, ENCODING_CONST)}`;
+ function encode(prefix, words, limit = 90) {
+ astr("bech32.encode prefix", prefix);
+ if (isBytes3(words))
+ words = Array.from(words);
+ anumArr("bech32.encode", words);
+ const plen = prefix.length;
+ if (plen === 0)
+ throw new TypeError(`Invalid prefix length ${plen}`);
+ const actualLength = plen + 7 + words.length;
+ if (limit !== false && actualLength > limit)
+ throw new TypeError(`Length ${actualLength} exceeds limit ${limit}`);
+ const lowered = prefix.toLowerCase();
+ const sum = bechChecksum(lowered, words, ENCODING_CONST);
+ return `${lowered}1${BECH_ALPHABET.encode(words)}${sum}`;
}
- function decode2(str, limit2 = 90) {
- if (typeof str !== "string")
- throw new Error(`bech32.decode input should be string, not ${typeof str}`);
- if (str.length < 8 || limit2 !== false && str.length > limit2)
- throw new TypeError(`Wrong string length: ${str.length} (${str}). Expected (8..${limit2})`);
+ function decode2(str, limit = 90) {
+ astr("bech32.decode input", str);
+ const slen = str.length;
+ if (slen < 8 || limit !== false && slen > limit)
+ throw new TypeError(`invalid string length: ${slen} (${str}). Expected (8..${limit})`);
const lowered = str.toLowerCase();
if (str !== lowered && str !== str.toUpperCase())
throw new Error(`String must be lowercase or uppercase`);
- str = lowered;
- const sepIndex = str.lastIndexOf("1");
+ const sepIndex = lowered.lastIndexOf("1");
if (sepIndex === 0 || sepIndex === -1)
throw new Error(`Letter "1" must be present between prefix and data only`);
- const prefix = str.slice(0, sepIndex);
- const _words2 = str.slice(sepIndex + 1);
- if (_words2.length < 6)
+ const prefix = lowered.slice(0, sepIndex);
+ const data = lowered.slice(sepIndex + 1);
+ if (data.length < 6)
throw new Error("Data must be at least 6 characters long");
- const words = BECH_ALPHABET.decode(_words2).slice(0, -6);
+ const words = BECH_ALPHABET.decode(data).slice(0, -6);
const sum = bechChecksum(prefix, words, ENCODING_CONST);
- if (!_words2.endsWith(sum))
+ if (!data.endsWith(sum))
throw new Error(`Invalid checksum in ${str}: expected "${sum}"`);
- return { prefix, words };
+ return {
+ prefix,
+ words
+ };
}
const decodeUnsafe = unsafeWrapper(decode2);
function decodeToBytes(str) {
const { prefix, words } = decode2(str, false);
- return { prefix, words, bytes: fromWords(words) };
+ return {
+ prefix,
+ words,
+ bytes: fromWords(words)
+ };
}
- return { encode, decode: decode2, decodeToBytes, decodeUnsafe, fromWords, fromWordsUnsafe, toWords };
+ function encodeFromBytes(prefix, bytes) {
+ return encode(prefix, toWords(bytes));
+ }
+ return {
+ encode,
+ decode: decode2,
+ encodeFromBytes,
+ decodeToBytes,
+ decodeUnsafe,
+ fromWords,
+ fromWordsUnsafe,
+ toWords
+ };
}
var bech32 = genBech32("bech32");
var bech32m = genBech32("bech32m");
- var utf8 = {
- encode: (data) => new TextDecoder().decode(data),
- decode: (str) => new TextEncoder().encode(str)
+ var hasHexBuiltin3 = /* @__PURE__ */ (() => typeof Uint8Array.from([]).toHex === "function" && typeof Uint8Array.fromHex === "function")();
+ var hexBuiltin = {
+ encode(data) {
+ abytes3(data);
+ return data.toHex();
+ },
+ decode(s) {
+ astr("hex", s);
+ return Uint8Array.fromHex(s);
+ }
};
- var hex = chain(radix2(4), alphabet("0123456789abcdef"), join(""), normalize((s) => {
- if (typeof s !== "string" || s.length % 2)
+ var hex = hasHexBuiltin3 ? hexBuiltin : chain(radix2(4), alphabet("0123456789abcdef"), join(""), normalize((s) => {
+ if (typeof s !== "string" || s.length % 2 !== 0)
throw new TypeError(`hex.decode: expected string, got ${typeof s} with length ${s.length}`);
return s.toLowerCase();
}));
- var CODERS = {
- utf8,
- hex,
- base16,
- base32,
- base64,
- base64url,
- base58,
- base58xmr
- };
- var coderTypeError = `Invalid encoding type. Available types: ${Object.keys(CODERS).join(", ")}`;
// nip19.ts
var NostrTypeGuard = {
isNProfile: (value) => /^nprofile1[a-z\d]+$/.test(value || ""),
@@ -4056,14 +4594,14 @@
isNcryptsec: (value) => /^ncryptsec1[a-z\d]+$/.test(value || "")
};
var Bech32MaxSize = 5e3;
var BECH32_REGEX = /[\x21-\x7E]{1,83}1[023456789acdefghjklmnpqrstuvwxyz]{6,}/;
- function integerToUint8Array(number4) {
+ function integerToUint8Array(number) {
const uint8Array = new Uint8Array(4);
- uint8Array[0] = number4 >> 24 & 255;
- uint8Array[1] = number4 >> 16 & 255;
- uint8Array[2] = number4 >> 8 & 255;
- uint8Array[3] = number4 & 255;
+ uint8Array[0] = number >> 24 & 255;
+ uint8Array[1] = number >> 16 & 255;
+ uint8Array[2] = number >> 8 & 255;
+ uint8Array[3] = number & 255;
return uint8Array;
}
function decodeNostrURI(nip19code) {
try {
@@ -4170,10 +4708,10 @@
function encodeBech32(prefix, data) {
let words = bech32.toWords(data);
return bech32.encode(prefix, words, Bech32MaxSize);
}
- function encodeBytes(prefix, bytes4) {
- return encodeBech32(prefix, bytes4);
+ function encodeBytes(prefix, bytes) {
+ return encodeBech32(prefix, bytes);
}
function nprofileEncode(profile) {
let data = encodeTLV({
0: [hexToBytes2(profile.pubkey)],
@@ -4215,9 +4753,9 @@
entry.set(v, 2);
entries.push(entry);
});
});
- return concatBytes3(...entries);
+ return concatBytes2(...entries);
}
// references.ts
var mentionRegex = /\bnostr:((note|npub|naddr|nevent|nprofile)1\w+)\b|#\[(\d+)\]/g;
@@ -4314,131 +4852,148 @@
decrypt: () => decrypt2,
encrypt: () => encrypt2
});
- // node_modules/@noble/ciphers/esm/_assert.js
- function number3(n) {
- if (!Number.isSafeInteger(n) || n < 0)
- throw new Error(`positive integer expected, not ${n}`);
+ // node_modules/@noble/ciphers/src/utils.js
+ function isBytes4(a) {
+ return a instanceof Uint8Array || ArrayBuffer.isView(a) && a.constructor.name === "Uint8Array";
}
- function bool2(b) {
+ function abool2(b) {
if (typeof b !== "boolean")
throw new Error(`boolean expected, not ${b}`);
}
- function isBytes(a) {
- return a instanceof Uint8Array || a != null && typeof a === "object" && a.constructor.name === "Uint8Array";
+ function anumber4(n) {
+ if (!Number.isSafeInteger(n) || n < 0)
+ throw new Error("positive integer expected, got " + n);
}
- function bytes3(b, ...lengths) {
- if (!isBytes(b))
- throw new Error("Uint8Array expected");
- if (lengths.length > 0 && !lengths.includes(b.length))
- throw new Error(`Uint8Array expected of length ${lengths}, not of length=${b.length}`);
+ function abytes4(value, length, title = "") {
+ const bytes = isBytes4(value);
+ const len = value?.length;
+ const needsLen = length !== void 0;
+ if (!bytes || needsLen && len !== length) {
+ const prefix = title && `"${title}" `;
+ const ofLen = needsLen ? ` of length ${length}` : "";
+ const got = bytes ? `length=${len}` : `type=${typeof value}`;
+ throw new Error(prefix + "expected Uint8Array" + ofLen + ", got " + got);
+ }
+ return value;
}
- function exists3(instance, checkFinished = true) {
+ function aexists3(instance, checkFinished = true) {
if (instance.destroyed)
throw new Error("Hash instance has been destroyed");
if (checkFinished && instance.finished)
throw new Error("Hash#digest() has already been called");
}
- function output3(out, instance) {
- bytes3(out);
+ function aoutput3(out, instance) {
+ abytes4(out, void 0, "output");
const min = instance.outputLen;
if (out.length < min) {
- throw new Error(`digestInto() expects output buffer of length at least ${min}`);
+ throw new Error("digestInto() expects output buffer of length at least " + min);
}
}
-
- // node_modules/@noble/ciphers/esm/utils.js
- var u8 = (arr) => new Uint8Array(arr.buffer, arr.byteOffset, arr.byteLength);
- var u32 = (arr) => new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4));
- var createView3 = (arr) => new DataView(arr.buffer, arr.byteOffset, arr.byteLength);
- var isLE3 = new Uint8Array(new Uint32Array([287454020]).buffer)[0] === 68;
- if (!isLE3)
- throw new Error("Non little-endian hardware is not supported");
- var hexes3 = /* @__PURE__ */ Array.from({ length: 256 }, (_, i2) => i2.toString(16).padStart(2, "0"));
- function bytesToHex3(bytes4) {
- bytes3(bytes4);
- let hex2 = "";
- for (let i2 = 0; i2 < bytes4.length; i2++) {
- hex2 += hexes3[bytes4[i2]];
- }
- return hex2;
+ function u32(arr) {
+ return new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4));
}
- var asciis = { _0: 48, _9: 57, _A: 65, _F: 70, _a: 97, _f: 102 };
- function asciiToBase16(char) {
- if (char >= asciis._0 && char <= asciis._9)
- return char - asciis._0;
- if (char >= asciis._A && char <= asciis._F)
- return char - (asciis._A - 10);
- if (char >= asciis._a && char <= asciis._f)
- return char - (asciis._a - 10);
- return;
- }
- function hexToBytes3(hex2) {
- if (typeof hex2 !== "string")
- throw new Error("hex string expected, got " + typeof hex2);
- const hl = hex2.length;
- const al = hl / 2;
- if (hl % 2)
- throw new Error("padded hex string expected, got unpadded hex of length " + hl);
- const array = new Uint8Array(al);
- for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) {
- const n1 = asciiToBase16(hex2.charCodeAt(hi));
- const n2 = asciiToBase16(hex2.charCodeAt(hi + 1));
- if (n1 === void 0 || n2 === void 0) {
- const char = hex2[hi] + hex2[hi + 1];
- throw new Error('hex string expected, got non-hex character "' + char + '" at index ' + hi);
- }
- array[ai] = n1 * 16 + n2;
+ function clean3(...arrays) {
+ for (let i2 = 0; i2 < arrays.length; i2++) {
+ arrays[i2].fill(0);
}
- return array;
}
- function utf8ToBytes4(str) {
- if (typeof str !== "string")
- throw new Error(`string expected, got ${typeof str}`);
- return new Uint8Array(new TextEncoder().encode(str));
+ function createView3(arr) {
+ return new DataView(arr.buffer, arr.byteOffset, arr.byteLength);
}
- function toBytes3(data) {
- if (typeof data === "string")
- data = utf8ToBytes4(data);
- else if (isBytes(data))
- data = data.slice();
- else
- throw new Error(`Uint8Array expected, got ${typeof data}`);
- return data;
+ var isLE = /* @__PURE__ */ (() => new Uint8Array(new Uint32Array([
+ 287454020
+ ]).buffer)[0] === 68)();
+ function overlapBytes(a, b) {
+ return a.buffer === b.buffer && a.byteOffset < b.byteOffset + b.byteLength && b.byteOffset < a.byteOffset + a.byteLength;
}
+ function complexOverlapBytes(input, output) {
+ if (overlapBytes(input, output) && input.byteOffset < output.byteOffset)
+ throw new Error("complex overlap of input and output is not supported");
+ }
function checkOpts(defaults, opts) {
if (opts == null || typeof opts !== "object")
throw new Error("options must be defined");
const merged = Object.assign(defaults, opts);
return merged;
}
- function equalBytes2(a, b) {
+ function equalBytes(a, b) {
if (a.length !== b.length)
return false;
let diff = 0;
for (let i2 = 0; i2 < a.length; i2++)
diff |= a[i2] ^ b[i2];
return diff === 0;
}
- var wrapCipher = (params, c) => {
- Object.assign(c, params);
- return c;
+ var wrapCipher = (params, constructor) => {
+ function wrappedCipher(key, ...args) {
+ abytes4(key, void 0, "key");
+ if (!isLE)
+ throw new Error("Non little-endian hardware is not yet supported");
+ if (params.nonceLength !== void 0) {
+ const nonce = args[0];
+ abytes4(nonce, params.varSizeNonce ? void 0 : params.nonceLength, "nonce");
+ }
+ const tagl = params.tagLength;
+ if (tagl && args[1] !== void 0)
+ abytes4(args[1], void 0, "AAD");
+ const cipher = constructor(key, ...args);
+ const checkOutput = (fnLength, output) => {
+ if (output !== void 0) {
+ if (fnLength !== 2)
+ throw new Error("cipher output not supported");
+ abytes4(output, void 0, "output");
+ }
+ };
+ let called = false;
+ const wrCipher = {
+ encrypt(data, output) {
+ if (called)
+ throw new Error("cannot encrypt() twice with same key + nonce");
+ called = true;
+ abytes4(data);
+ checkOutput(cipher.encrypt.length, output);
+ return cipher.encrypt(data, output);
+ },
+ decrypt(data, output) {
+ abytes4(data);
+ if (tagl && data.length < tagl)
+ throw new Error('"ciphertext" expected length bigger than tagLength=' + tagl);
+ checkOutput(cipher.decrypt.length, output);
+ return cipher.decrypt(data, output);
+ }
+ };
+ return wrCipher;
+ }
+ Object.assign(wrappedCipher, params);
+ return wrappedCipher;
};
- function setBigUint643(view, byteOffset, value, isLE4) {
- if (typeof view.setBigUint64 === "function")
- return view.setBigUint64(byteOffset, value, isLE4);
- const _32n = BigInt(32);
- const _u32_max = BigInt(4294967295);
- const wh = Number(value >> _32n & _u32_max);
- const wl = Number(value & _u32_max);
- const h = isLE4 ? 4 : 0;
- const l = isLE4 ? 0 : 4;
- view.setUint32(byteOffset + h, wh, isLE4);
- view.setUint32(byteOffset + l, wl, isLE4);
+ function getOutput(expectedLength, out, onlyAligned = true) {
+ if (out === void 0)
+ return new Uint8Array(expectedLength);
+ if (out.length !== expectedLength)
+ throw new Error('"output" expected Uint8Array of length ' + expectedLength + ", got: " + out.length);
+ if (onlyAligned && !isAligned32(out))
+ throw new Error("invalid output, must be aligned");
+ return out;
}
+ function u64Lengths(dataLength, aadLength, isLE2) {
+ abool2(isLE2);
+ const num2 = new Uint8Array(16);
+ const view = createView3(num2);
+ view.setBigUint64(0, BigInt(aadLength), isLE2);
+ view.setBigUint64(8, BigInt(dataLength), isLE2);
+ return num2;
+ }
+ function isAligned32(bytes) {
+ return bytes.byteOffset % 4 === 0;
+ }
+ function copyBytes2(bytes) {
+ return Uint8Array.from(bytes);
+ }
- // node_modules/@noble/ciphers/esm/_polyval.js
+ // node_modules/@noble/ciphers/src/_polyval.js
var BLOCK_SIZE = 16;
var ZEROS16 = /* @__PURE__ */ new Uint8Array(16);
var ZEROS32 = u32(ZEROS16);
var POLY = 225;
@@ -4463,39 +5018,52 @@
}
k[0] ^= -hiBit & 225;
return k;
}
- var estimateWindow = (bytes4) => {
- if (bytes4 > 64 * 1024)
+ var estimateWindow = (bytes) => {
+ if (bytes > 64 * 1024)
return 8;
- if (bytes4 > 1024)
+ if (bytes > 1024)
return 4;
return 2;
};
var GHASH = class {
+ blockLen = BLOCK_SIZE;
+ outputLen = BLOCK_SIZE;
+ s0 = 0;
+ s1 = 0;
+ s2 = 0;
+ s3 = 0;
+ finished = false;
+ t;
+ W;
+ windowSize;
constructor(key, expectedLength) {
- this.blockLen = BLOCK_SIZE;
- this.outputLen = BLOCK_SIZE;
- this.s0 = 0;
- this.s1 = 0;
- this.s2 = 0;
- this.s3 = 0;
- this.finished = false;
- key = toBytes3(key);
- bytes3(key, 16);
+ abytes4(key, 16, "key");
+ key = copyBytes2(key);
const kView = createView3(key);
let k0 = kView.getUint32(0, false);
let k1 = kView.getUint32(4, false);
let k2 = kView.getUint32(8, false);
let k3 = kView.getUint32(12, false);
const doubles = [];
for (let i2 = 0; i2 < 128; i2++) {
- doubles.push({ s0: swapLE(k0), s1: swapLE(k1), s2: swapLE(k2), s3: swapLE(k3) });
+ doubles.push({
+ s0: swapLE(k0),
+ s1: swapLE(k1),
+ s2: swapLE(k2),
+ s3: swapLE(k3)
+ });
({ s0: k0, s1: k1, s2: k2, s3: k3 } = mul2(k0, k1, k2, k3));
}
const W = estimateWindow(expectedLength || 1024);
- if (![1, 2, 4, 8].includes(W))
- throw new Error(`ghash: wrong window size=${W}, should be 2, 4 or 8`);
+ if (![
+ 1,
+ 2,
+ 4,
+ 8
+ ].includes(W))
+ throw new Error("ghash: invalid window size, expected 2, 4 or 8");
this.W = W;
const bits = 128;
const windows = bits / W;
const windowSize = this.windowSize = 2 ** W;
@@ -4509,9 +5077,14 @@
continue;
const { s0: d0, s1: d1, s2: d2, s3: d3 } = doubles[W * w + j];
s0 ^= d0, s1 ^= d1, s2 ^= d2, s3 ^= d3;
}
- items.push({ s0, s1, s2, s3 });
+ items.push({
+ s0,
+ s1,
+ s2,
+ s3
+ });
}
}
this.t = items;
}
@@ -4520,11 +5093,16 @@
const { W, t, windowSize } = this;
let o0 = 0, o1 = 0, o2 = 0, o3 = 0;
const mask = (1 << W) - 1;
let w = 0;
- for (const num of [s0, s1, s2, s3]) {
+ for (const num2 of [
+ s0,
+ s1,
+ s2,
+ s3
+ ]) {
for (let bytePos = 0; bytePos < 4; bytePos++) {
- const byte = num >>> 8 * bytePos & 255;
+ const byte = num2 >>> 8 * bytePos & 255;
for (let bitPos = 8 / W - 1; bitPos >= 0; bitPos--) {
const bit = byte >>> W * bitPos & mask;
const { s0: e0, s1: e1, s2: e2, s3: e3 } = t[w * windowSize + bit];
o0 ^= e0, o1 ^= e1, o2 ^= e2, o3 ^= e3;
@@ -4537,10 +5115,11 @@
this.s2 = o2;
this.s3 = o3;
}
update(data) {
- data = toBytes3(data);
- exists3(this);
+ aexists3(this);
+ abytes4(data);
+ data = copyBytes2(data);
const b32 = u32(data);
const blocks = Math.floor(data.length / BLOCK_SIZE);
const left = data.length % BLOCK_SIZE;
for (let i2 = 0; i2 < blocks; i2++) {
@@ -4548,9 +5127,9 @@
}
if (left) {
ZEROS16.set(data.subarray(blocks * BLOCK_SIZE));
this._updateBlock(ZEROS32[0], ZEROS32[1], ZEROS32[2], ZEROS32[3]);
- ZEROS32.fill(0);
+ clean3(ZEROS32);
}
return this;
}
destroy() {
@@ -4559,10 +5138,10 @@
elm.s0 = 0, elm.s1 = 0, elm.s2 = 0, elm.s3 = 0;
}
}
digestInto(out) {
- exists3(this);
- output3(out, this);
+ aexists3(this);
+ aoutput3(out, this);
this.finished = true;
const { s0, s1, s2, s3 } = this;
const o32 = u32(out);
o32[0] = s0;
@@ -4579,16 +5158,17 @@
}
};
var Polyval = class extends GHASH {
constructor(key, expectedLength) {
- key = toBytes3(key);
- const ghKey = _toGHASHKey(key.slice());
+ abytes4(key);
+ const ghKey = _toGHASHKey(copyBytes2(key));
super(ghKey, expectedLength);
- ghKey.fill(0);
+ clean3(ghKey);
}
update(data) {
- data = toBytes3(data);
- exists3(this);
+ aexists3(this);
+ abytes4(data);
+ data = copyBytes2(data);
const b32 = u32(data);
const left = data.length % BLOCK_SIZE;
const blocks = Math.floor(data.length / BLOCK_SIZE);
for (let i2 = 0; i2 < blocks; i2++) {
@@ -4596,15 +5176,15 @@
}
if (left) {
ZEROS16.set(data.subarray(blocks * BLOCK_SIZE));
this._updateBlock(swapLE(ZEROS32[3]), swapLE(ZEROS32[2]), swapLE(ZEROS32[1]), swapLE(ZEROS32[0]));
- ZEROS32.fill(0);
+ clean3(ZEROS32);
}
return this;
}
digestInto(out) {
- exists3(this);
- output3(out, this);
+ aexists3(this);
+ aoutput3(out, this);
this.finished = true;
const { s0, s1, s2, s3 } = this;
const o32 = u32(out);
o32[0] = s0;
@@ -4614,9 +5194,9 @@
return out.reverse();
}
};
function wrapConstructorWithKey(hashCons) {
- const hashC = (msg, key) => hashCons(key, msg.length).update(toBytes3(msg)).digest();
+ const hashC = (msg, key) => hashCons(key, msg.length).update(msg).digest();
const tmp = hashCons(new Uint8Array(16), 0);
hashC.outputLen = tmp.outputLen;
hashC.blockLen = tmp.blockLen;
hashC.create = (key, expectedLength) => hashCons(key, expectedLength);
@@ -4624,13 +5204,19 @@
}
var ghash = wrapConstructorWithKey((key, expectedLength) => new GHASH(key, expectedLength));
var polyval = wrapConstructorWithKey((key, expectedLength) => new Polyval(key, expectedLength));
- // node_modules/@noble/ciphers/esm/aes.js
+ // node_modules/@noble/ciphers/src/aes.js
var BLOCK_SIZE2 = 16;
- var BLOCK_SIZE32 = 4;
- var EMPTY_BLOCK = new Uint8Array(BLOCK_SIZE2);
var POLY2 = 283;
+ function validateKeyLength(key) {
+ if (![
+ 16,
+ 24,
+ 32
+ ].includes(key.length))
+ throw new Error('"aes key" expected Uint8Array of length 16/24/32, got length=' + key.length);
+ }
function mul22(n) {
return n << 1 ^ POLY2 & -(n >> 7);
}
function mul(a, b) {
@@ -4641,9 +5227,9 @@
}
return res;
}
var sbox = /* @__PURE__ */ (() => {
- let t = new Uint8Array(256);
+ const t = new Uint8Array(256);
for (let i2 = 0, x = 1; i2 < 256; i2++, x ^= mul22(x))
t[i2] = x;
const box = new Uint8Array(256);
box[0] = 99;
@@ -4651,8 +5237,9 @@
let x = t[255 - i2];
x |= x << 8;
box[t[i2]] = (x ^ x >> 4 ^ x >> 5 ^ x >> 6 ^ x >> 7 ^ 99) & 255;
}
+ clean3(t);
return box;
})();
var invSbox = /* @__PURE__ */ sbox.map((_, j) => sbox.indexOf(j));
var rotr32_8 = (n) => n << 24 | n >>> 8;
@@ -4674,9 +5261,18 @@
T23[idx] = T2[i2] ^ T3[j];
sbox22[idx] = sbox2[i2] << 8 | sbox2[j];
}
}
- return { sbox: sbox2, sbox2: sbox22, T0, T1, T2, T3, T01, T23 };
+ return {
+ sbox: sbox2,
+ sbox2: sbox22,
+ T0,
+ T1,
+ T2,
+ T3,
+ T01,
+ T23
+ };
}
var tableEncoding = /* @__PURE__ */ genTtable(sbox, (s) => mul(s, 3) << 24 | s << 16 | s << 8 | mul(s, 2));
var tableDecoding = /* @__PURE__ */ genTtable(invSbox, (s) => mul(s, 11) << 24 | mul(s, 13) << 16 | mul(s, 9) << 8 | mul(s, 14));
var xPowers = /* @__PURE__ */ (() => {
@@ -4685,13 +5281,15 @@
p[i2] = x;
return p;
})();
function expandKeyLE(key) {
- bytes3(key);
+ abytes4(key);
const len = key.length;
- if (![16, 24, 32].includes(len))
- throw new Error(`aes: wrong key size: should be 16, 24 or 32, got: ${len}`);
+ validateKeyLength(key);
const { sbox2 } = tableEncoding;
+ const toClean = [];
+ if (!isAligned32(key))
+ toClean.push(key = copyBytes2(key));
const k32 = u32(key);
const Nk = k32.length;
const subByte = (n) => applySbox(sbox2, n, n, n, n);
const xk = new Uint32Array(len + 28);
@@ -4703,8 +5301,9 @@
else if (Nk > 6 && i2 % Nk === 4)
t = subByte(t);
xk[i2] = xk[i2 - Nk] ^ t;
}
+ clean3(...toClean);
return xk;
}
function expandKeyDecLE(key) {
const encKey = expandKeyLE(key);
@@ -4715,9 +5314,9 @@
for (let i2 = 0; i2 < Nk; i2 += 4) {
for (let j = 0; j < 4; j++)
xk[i2 + j] = encKey[Nk - i2 - 4 + j];
}
- encKey.fill(0);
+ clean3(encKey);
for (let i2 = 4; i2 < Nk - 4; i2++) {
const x = xk[i2];
const w = applySbox(sbox2, x, x, x, x);
xk[i2] = T0[w & 255] ^ T1[w >>> 8 & 255] ^ T2[w >>> 16 & 255] ^ T3[w >>> 24];
@@ -4745,9 +5344,14 @@
const t0 = xk[k++] ^ applySbox(sbox2, s0, s1, s2, s3);
const t1 = xk[k++] ^ applySbox(sbox2, s1, s2, s3, s0);
const t2 = xk[k++] ^ applySbox(sbox2, s2, s3, s0, s1);
const t3 = xk[k++] ^ applySbox(sbox2, s3, s0, s1, s2);
- return { s0: t0, s1: t1, s2: t2, s3: t3 };
+ return {
+ s0: t0,
+ s1: t1,
+ s2: t2,
+ s3: t3
+ };
}
function decrypt(xk, s0, s1, s2, s3) {
const { sbox2, T01, T23 } = tableDecoding;
let k = 0;
@@ -4763,132 +5367,58 @@
const t0 = xk[k++] ^ applySbox(sbox2, s0, s3, s2, s1);
const t1 = xk[k++] ^ applySbox(sbox2, s1, s0, s3, s2);
const t2 = xk[k++] ^ applySbox(sbox2, s2, s1, s0, s3);
const t3 = xk[k++] ^ applySbox(sbox2, s3, s2, s1, s0);
- return { s0: t0, s1: t1, s2: t2, s3: t3 };
- }
- function getDst(len, dst) {
- if (!dst)
- return new Uint8Array(len);
- bytes3(dst);
- if (dst.length < len)
- throw new Error(`aes: wrong destination length, expected at least ${len}, got: ${dst.length}`);
- return dst;
- }
- function ctrCounter(xk, nonce, src, dst) {
- bytes3(nonce, BLOCK_SIZE2);
- bytes3(src);
- const srcLen = src.length;
- dst = getDst(srcLen, dst);
- const ctr3 = nonce;
- const c32 = u32(ctr3);
- let { s0, s1, s2, s3 } = encrypt(xk, c32[0], c32[1], c32[2], c32[3]);
- const src32 = u32(src);
- const dst32 = u32(dst);
- for (let i2 = 0; i2 + 4 <= src32.length; i2 += 4) {
- dst32[i2 + 0] = src32[i2 + 0] ^ s0;
- dst32[i2 + 1] = src32[i2 + 1] ^ s1;
- dst32[i2 + 2] = src32[i2 + 2] ^ s2;
- dst32[i2 + 3] = src32[i2 + 3] ^ s3;
- let carry = 1;
- for (let i3 = ctr3.length - 1; i3 >= 0; i3--) {
- carry = carry + (ctr3[i3] & 255) | 0;
- ctr3[i3] = carry & 255;
- carry >>>= 8;
- }
- ({ s0, s1, s2, s3 } = encrypt(xk, c32[0], c32[1], c32[2], c32[3]));
- }
- const start = BLOCK_SIZE2 * Math.floor(src32.length / BLOCK_SIZE32);
- if (start < srcLen) {
- const b32 = new Uint32Array([s0, s1, s2, s3]);
- const buf = u8(b32);
- for (let i2 = start, pos = 0; i2 < srcLen; i2++, pos++)
- dst[i2] = src[i2] ^ buf[pos];
- }
- return dst;
- }
- function ctr32(xk, isLE4, nonce, src, dst) {
- bytes3(nonce, BLOCK_SIZE2);
- bytes3(src);
- dst = getDst(src.length, dst);
- const ctr3 = nonce;
- const c32 = u32(ctr3);
- const view = createView3(ctr3);
- const src32 = u32(src);
- const dst32 = u32(dst);
- const ctrPos = isLE4 ? 0 : 12;
- const srcLen = src.length;
- let ctrNum = view.getUint32(ctrPos, isLE4);
- let { s0, s1, s2, s3 } = encrypt(xk, c32[0], c32[1], c32[2], c32[3]);
- for (let i2 = 0; i2 + 4 <= src32.length; i2 += 4) {
- dst32[i2 + 0] = src32[i2 + 0] ^ s0;
- dst32[i2 + 1] = src32[i2 + 1] ^ s1;
- dst32[i2 + 2] = src32[i2 + 2] ^ s2;
- dst32[i2 + 3] = src32[i2 + 3] ^ s3;
- ctrNum = ctrNum + 1 >>> 0;
- view.setUint32(ctrPos, ctrNum, isLE4);
- ({ s0, s1, s2, s3 } = encrypt(xk, c32[0], c32[1], c32[2], c32[3]));
- }
- const start = BLOCK_SIZE2 * Math.floor(src32.length / BLOCK_SIZE32);
- if (start < srcLen) {
- const b32 = new Uint32Array([s0, s1, s2, s3]);
- const buf = u8(b32);
- for (let i2 = start, pos = 0; i2 < srcLen; i2++, pos++)
- dst[i2] = src[i2] ^ buf[pos];
- }
- return dst;
- }
- var ctr = wrapCipher({ blockSize: 16, nonceLength: 16 }, function ctr2(key, nonce) {
- bytes3(key);
- bytes3(nonce, BLOCK_SIZE2);
- function processCtr(buf, dst) {
- const xk = expandKeyLE(key);
- const n = nonce.slice();
- const out = ctrCounter(xk, n, buf, dst);
- xk.fill(0);
- n.fill(0);
- return out;
- }
return {
- encrypt: (plaintext, dst) => processCtr(plaintext, dst),
- decrypt: (ciphertext, dst) => processCtr(ciphertext, dst)
+ s0: t0,
+ s1: t1,
+ s2: t2,
+ s3: t3
};
- });
+ }
function validateBlockDecrypt(data) {
- bytes3(data);
+ abytes4(data);
if (data.length % BLOCK_SIZE2 !== 0) {
- throw new Error(`aes/(cbc-ecb).decrypt ciphertext should consist of blocks with size ${BLOCK_SIZE2}`);
+ throw new Error("aes-(cbc/ecb).decrypt ciphertext should consist of blocks with size " + BLOCK_SIZE2);
}
}
function validateBlockEncrypt(plaintext, pcks5, dst) {
+ abytes4(plaintext);
let outLen = plaintext.length;
const remaining = outLen % BLOCK_SIZE2;
if (!pcks5 && remaining !== 0)
throw new Error("aec/(cbc-ecb): unpadded plaintext with disabled padding");
+ if (!isAligned32(plaintext))
+ plaintext = copyBytes2(plaintext);
const b = u32(plaintext);
if (pcks5) {
let left = BLOCK_SIZE2 - remaining;
if (!left)
left = BLOCK_SIZE2;
outLen = outLen + left;
}
- const out = getDst(outLen, dst);
- const o = u32(out);
- return { b, o, out };
+ dst = getOutput(outLen, dst);
+ complexOverlapBytes(plaintext, dst);
+ const o = u32(dst);
+ return {
+ b,
+ o,
+ out: dst
+ };
}
function validatePCKS(data, pcks5) {
if (!pcks5)
return data;
const len = data.length;
if (!len)
- throw new Error(`aes/pcks5: empty ciphertext not allowed`);
+ throw new Error("aes/pcks5: empty ciphertext not allowed");
const lastByte = data[len - 1];
if (lastByte <= 0 || lastByte > 16)
- throw new Error(`aes/pcks5: wrong padding byte: ${lastByte}`);
+ throw new Error("aes/pcks5: wrong padding");
const out = data.subarray(0, -lastByte);
for (let i2 = 0; i2 < lastByte; i2++)
if (data[len - i2 - 1] !== lastByte)
- throw new Error(`aes/pcks5: wrong padding`);
+ throw new Error("aes/pcks5: wrong padding");
return out;
}
function padPCKS(left) {
const tmp = new Uint8Array(16);
@@ -4898,53 +5428,24 @@
for (let i2 = BLOCK_SIZE2 - paddingByte; i2 < BLOCK_SIZE2; i2++)
tmp[i2] = paddingByte;
return tmp32;
}
- var ecb = wrapCipher({ blockSize: 16 }, function ecb2(key, opts = {}) {
- bytes3(key);
+ var cbc = /* @__PURE__ */ wrapCipher({
+ blockSize: 16,
+ nonceLength: 16
+ }, function aescbc(key, iv, opts = {}) {
const pcks5 = !opts.disablePadding;
return {
- encrypt: (plaintext, dst) => {
- bytes3(plaintext);
- const { b, o, out: _out } = validateBlockEncrypt(plaintext, pcks5, dst);
+ encrypt(plaintext, dst) {
const xk = expandKeyLE(key);
- let i2 = 0;
- for (; i2 + 4 <= b.length; ) {
- const { s0, s1, s2, s3 } = encrypt(xk, b[i2 + 0], b[i2 + 1], b[i2 + 2], b[i2 + 3]);
- o[i2++] = s0, o[i2++] = s1, o[i2++] = s2, o[i2++] = s3;
- }
- if (pcks5) {
- const tmp32 = padPCKS(plaintext.subarray(i2 * 4));
- const { s0, s1, s2, s3 } = encrypt(xk, tmp32[0], tmp32[1], tmp32[2], tmp32[3]);
- o[i2++] = s0, o[i2++] = s1, o[i2++] = s2, o[i2++] = s3;
- }
- xk.fill(0);
- return _out;
- },
- decrypt: (ciphertext, dst) => {
- validateBlockDecrypt(ciphertext);
- const xk = expandKeyDecLE(key);
- const out = getDst(ciphertext.length, dst);
- const b = u32(ciphertext);
- const o = u32(out);
- for (let i2 = 0; i2 + 4 <= b.length; ) {
- const { s0, s1, s2, s3 } = decrypt(xk, b[i2 + 0], b[i2 + 1], b[i2 + 2], b[i2 + 3]);
- o[i2++] = s0, o[i2++] = s1, o[i2++] = s2, o[i2++] = s3;
- }
- xk.fill(0);
- return validatePCKS(out, pcks5);
- }
- };
- });
- var cbc = wrapCipher({ blockSize: 16, nonceLength: 16 }, function cbc2(key, iv, opts = {}) {
- bytes3(key);
- bytes3(iv, 16);
- const pcks5 = !opts.disablePadding;
- return {
- encrypt: (plaintext, dst) => {
- const xk = expandKeyLE(key);
const { b, o, out: _out } = validateBlockEncrypt(plaintext, pcks5, dst);
- const n32 = u32(iv);
+ let _iv = iv;
+ const toClean = [
+ xk
+ ];
+ if (!isAligned32(_iv))
+ toClean.push(_iv = copyBytes2(_iv));
+ const n32 = u32(_iv);
let s0 = n32[0], s1 = n32[1], s2 = n32[2], s3 = n32[3];
let i2 = 0;
for (; i2 + 4 <= b.length; ) {
s0 ^= b[i2 + 0], s1 ^= b[i2 + 1], s2 ^= b[i2 + 2], s3 ^= b[i2 + 3];
@@ -4956,186 +5457,149 @@
s0 ^= tmp32[0], s1 ^= tmp32[1], s2 ^= tmp32[2], s3 ^= tmp32[3];
({ s0, s1, s2, s3 } = encrypt(xk, s0, s1, s2, s3));
o[i2++] = s0, o[i2++] = s1, o[i2++] = s2, o[i2++] = s3;
}
- xk.fill(0);
+ clean3(...toClean);
return _out;
},
- decrypt: (ciphertext, dst) => {
+ decrypt(ciphertext, dst) {
validateBlockDecrypt(ciphertext);
const xk = expandKeyDecLE(key);
- const n32 = u32(iv);
- const out = getDst(ciphertext.length, dst);
+ let _iv = iv;
+ const toClean = [
+ xk
+ ];
+ if (!isAligned32(_iv))
+ toClean.push(_iv = copyBytes2(_iv));
+ const n32 = u32(_iv);
+ dst = getOutput(ciphertext.length, dst);
+ if (!isAligned32(ciphertext))
+ toClean.push(ciphertext = copyBytes2(ciphertext));
+ complexOverlapBytes(ciphertext, dst);
const b = u32(ciphertext);
- const o = u32(out);
+ const o = u32(dst);
let s0 = n32[0], s1 = n32[1], s2 = n32[2], s3 = n32[3];
for (let i2 = 0; i2 + 4 <= b.length; ) {
const ps0 = s0, ps1 = s1, ps2 = s2, ps3 = s3;
s0 = b[i2 + 0], s1 = b[i2 + 1], s2 = b[i2 + 2], s3 = b[i2 + 3];
const { s0: o0, s1: o1, s2: o2, s3: o3 } = decrypt(xk, s0, s1, s2, s3);
o[i2++] = o0 ^ ps0, o[i2++] = o1 ^ ps1, o[i2++] = o2 ^ ps2, o[i2++] = o3 ^ ps3;
}
- xk.fill(0);
- return validatePCKS(out, pcks5);
+ clean3(...toClean);
+ return validatePCKS(dst, pcks5);
}
};
});
- function computeTag(fn, isLE4, key, data, AAD) {
- const h = fn.create(key, data.length + (AAD?.length || 0));
- if (AAD)
- h.update(AAD);
- h.update(data);
- const num = new Uint8Array(16);
- const view = createView3(num);
- if (AAD)
- setBigUint643(view, 0, BigInt(AAD.length * 8), isLE4);
- setBigUint643(view, 8, BigInt(data.length * 8), isLE4);
- h.update(num);
- return h.digest();
+ function isBytes32(a) {
+ return a instanceof Uint32Array || ArrayBuffer.isView(a) && a.constructor.name === "Uint32Array";
}
- var gcm = wrapCipher({ blockSize: 16, nonceLength: 12, tagLength: 16 }, function gcm2(key, nonce, AAD) {
- bytes3(nonce);
- if (nonce.length === 0)
- throw new Error("aes/gcm: empty nonce");
- const tagLength = 16;
- function _computeTag(authKey, tagMask, data) {
- const tag = computeTag(ghash, false, authKey, data, AAD);
- for (let i2 = 0; i2 < tagMask.length; i2++)
- tag[i2] ^= tagMask[i2];
- return tag;
+ function encryptBlock(xk, block) {
+ abytes4(block, 16, "block");
+ if (!isBytes32(xk))
+ throw new Error("_encryptBlock accepts result of expandKeyLE");
+ const b32 = u32(block);
+ let { s0, s1, s2, s3 } = encrypt(xk, b32[0], b32[1], b32[2], b32[3]);
+ b32[0] = s0, b32[1] = s1, b32[2] = s2, b32[3] = s3;
+ return block;
+ }
+ function dbl(block) {
+ let carry = 0;
+ for (let i2 = BLOCK_SIZE2 - 1; i2 >= 0; i2--) {
+ const newCarry = (block[i2] & 128) >>> 7;
+ block[i2] = block[i2] << 1 | carry;
+ carry = newCarry;
}
- function deriveKeys() {
- const xk = expandKeyLE(key);
- const authKey = EMPTY_BLOCK.slice();
- const counter = EMPTY_BLOCK.slice();
- ctr32(xk, false, counter, counter, authKey);
- if (nonce.length === 12) {
- counter.set(nonce);
+ if (carry) {
+ block[BLOCK_SIZE2 - 1] ^= 135;
+ }
+ return block;
+ }
+ function xorBlock(a, b) {
+ if (a.length !== b.length)
+ throw new Error("xorBlock: blocks must have same length");
+ for (let i2 = 0; i2 < a.length; i2++) {
+ a[i2] = a[i2] ^ b[i2];
+ }
+ return a;
+ }
+ var _CMAC = class {
+ buffer;
+ destroyed;
+ k1;
+ k2;
+ xk;
+ constructor(key) {
+ abytes4(key);
+ validateKeyLength(key);
+ this.xk = expandKeyLE(key);
+ this.buffer = new Uint8Array(0);
+ this.destroyed = false;
+ const L = new Uint8Array(BLOCK_SIZE2);
+ encryptBlock(this.xk, L);
+ this.k1 = dbl(L);
+ this.k2 = dbl(new Uint8Array(this.k1));
+ }
+ update(data) {
+ const { destroyed, buffer } = this;
+ if (destroyed)
+ throw new Error("CMAC instance was destroyed");
+ abytes4(data);
+ const newBuffer = new Uint8Array(buffer.length + data.length);
+ newBuffer.set(buffer);
+ newBuffer.set(data, buffer.length);
+ this.buffer = newBuffer;
+ return this;
+ }
+ digest() {
+ if (this.destroyed)
+ throw new Error("CMAC instance was destroyed");
+ const { buffer } = this;
+ const msgLen = buffer.length;
+ let n = Math.ceil(msgLen / BLOCK_SIZE2);
+ let flag;
+ if (n === 0) {
+ n = 1;
+ flag = false;
} else {
- const nonceLen = EMPTY_BLOCK.slice();
- const view = createView3(nonceLen);
- setBigUint643(view, 8, BigInt(nonce.length * 8), false);
- ghash.create(authKey).update(nonce).update(nonceLen).digestInto(counter);
+ flag = msgLen % BLOCK_SIZE2 === 0;
}
- const tagMask = ctr32(xk, false, counter, EMPTY_BLOCK);
- return { xk, authKey, counter, tagMask };
- }
- return {
- encrypt: (plaintext) => {
- bytes3(plaintext);
- const { xk, authKey, counter, tagMask } = deriveKeys();
- const out = new Uint8Array(plaintext.length + tagLength);
- ctr32(xk, false, counter, plaintext, out);
- const tag = _computeTag(authKey, tagMask, out.subarray(0, out.length - tagLength));
- out.set(tag, plaintext.length);
- xk.fill(0);
- return out;
- },
- decrypt: (ciphertext) => {
- bytes3(ciphertext);
- if (ciphertext.length < tagLength)
- throw new Error(`aes/gcm: ciphertext less than tagLen (${tagLength})`);
- const { xk, authKey, counter, tagMask } = deriveKeys();
- const data = ciphertext.subarray(0, -tagLength);
- const passedTag = ciphertext.subarray(-tagLength);
- const tag = _computeTag(authKey, tagMask, data);
- if (!equalBytes2(tag, passedTag))
- throw new Error("aes/gcm: invalid ghash tag");
- const out = ctr32(xk, false, counter, data);
- authKey.fill(0);
- tagMask.fill(0);
- xk.fill(0);
- return out;
+ const lastBlockStart = (n - 1) * BLOCK_SIZE2;
+ const lastBlockData = buffer.subarray(lastBlockStart);
+ let m_last;
+ if (flag) {
+ m_last = xorBlock(new Uint8Array(lastBlockData), this.k1);
+ } else {
+ const padded = new Uint8Array(BLOCK_SIZE2);
+ padded.set(lastBlockData);
+ padded[lastBlockData.length] = 128;
+ m_last = xorBlock(padded, this.k2);
}
- };
- });
- var limit = (name, min, max) => (value) => {
- if (!Number.isSafeInteger(value) || min > value || value > max)
- throw new Error(`${name}: invalid value=${value}, must be [${min}..${max}]`);
- };
- var siv = wrapCipher({ blockSize: 16, nonceLength: 12, tagLength: 16 }, function siv2(key, nonce, AAD) {
- const tagLength = 16;
- const AAD_LIMIT = limit("AAD", 0, 2 ** 36);
- const PLAIN_LIMIT = limit("plaintext", 0, 2 ** 36);
- const NONCE_LIMIT = limit("nonce", 12, 12);
- const CIPHER_LIMIT = limit("ciphertext", 16, 2 ** 36 + 16);
- bytes3(nonce);
- NONCE_LIMIT(nonce.length);
- if (AAD) {
- bytes3(AAD);
- AAD_LIMIT(AAD.length);
- }
- function deriveKeys() {
- const len = key.length;
- if (len !== 16 && len !== 24 && len !== 32)
- throw new Error(`key length must be 16, 24 or 32 bytes, got: ${len} bytes`);
- const xk = expandKeyLE(key);
- const encKey = new Uint8Array(len);
- const authKey = new Uint8Array(16);
- const n32 = u32(nonce);
- let s0 = 0, s1 = n32[0], s2 = n32[1], s3 = n32[2];
- let counter = 0;
- for (const derivedKey of [authKey, encKey].map(u32)) {
- const d32 = u32(derivedKey);
- for (let i2 = 0; i2 < d32.length; i2 += 2) {
- const { s0: o0, s1: o1 } = encrypt(xk, s0, s1, s2, s3);
- d32[i2 + 0] = o0;
- d32[i2 + 1] = o1;
- s0 = ++counter;
- }
+ let x = new Uint8Array(BLOCK_SIZE2);
+ for (let i2 = 0; i2 < n - 1; i2++) {
+ const m_i = buffer.subarray(i2 * BLOCK_SIZE2, (i2 + 1) * BLOCK_SIZE2);
+ xorBlock(x, m_i);
+ encryptBlock(this.xk, x);
}
- xk.fill(0);
- return { authKey, encKey: expandKeyLE(encKey) };
+ xorBlock(x, m_last);
+ encryptBlock(this.xk, x);
+ clean3(m_last);
+ return x;
}
- function _computeTag(encKey, authKey, data) {
- const tag = computeTag(polyval, true, authKey, data, AAD);
- for (let i2 = 0; i2 < 12; i2++)
- tag[i2] ^= nonce[i2];
- tag[15] &= 127;
- const t32 = u32(tag);
- let s0 = t32[0], s1 = t32[1], s2 = t32[2], s3 = t32[3];
- ({ s0, s1, s2, s3 } = encrypt(encKey, s0, s1, s2, s3));
- t32[0] = s0, t32[1] = s1, t32[2] = s2, t32[3] = s3;
- return tag;
+ destroy() {
+ const { buffer, destroyed, xk, k1, k2 } = this;
+ if (destroyed)
+ return;
+ this.destroyed = true;
+ clean3(buffer, xk, k1, k2);
}
- function processSiv(encKey, tag, input) {
- let block = tag.slice();
- block[15] |= 128;
- return ctr32(encKey, true, block, input);
- }
- return {
- encrypt: (plaintext) => {
- bytes3(plaintext);
- PLAIN_LIMIT(plaintext.length);
- const { encKey, authKey } = deriveKeys();
- const tag = _computeTag(encKey, authKey, plaintext);
- const out = new Uint8Array(plaintext.length + tagLength);
- out.set(tag, plaintext.length);
- out.set(processSiv(encKey, tag, plaintext));
- encKey.fill(0);
- authKey.fill(0);
- return out;
- },
- decrypt: (ciphertext) => {
- bytes3(ciphertext);
- CIPHER_LIMIT(ciphertext.length);
- const tag = ciphertext.subarray(-tagLength);
- const { encKey, authKey } = deriveKeys();
- const plaintext = processSiv(encKey, tag, ciphertext.subarray(0, -tagLength));
- const expectedTag = _computeTag(encKey, authKey, plaintext);
- encKey.fill(0);
- authKey.fill(0);
- if (!equalBytes2(tag, expectedTag))
- throw new Error("invalid polyval tag");
- return plaintext;
- }
- };
- });
+ };
+ var cmac = (key, message) => new _CMAC(key).update(message).digest();
+ cmac.create = (key) => new _CMAC(key);
// nip04.ts
function encrypt2(secretKey, pubkey, text) {
- const privkey = secretKey instanceof Uint8Array ? bytesToHex2(secretKey) : secretKey;
- const key = secp256k1.getSharedSecret(privkey, "02" + pubkey);
+ const privkey = secretKey instanceof Uint8Array ? secretKey : hexToBytes2(secretKey);
+ const key = secp256k1.getSharedSecret(privkey, hexToBytes2("02" + pubkey));
const normalizedKey = getNormalizedX(key);
let iv = Uint8Array.from(randomBytes2(16));
let plaintext = utf8Encoder.encode(text);
let ciphertext = cbc(normalizedKey, iv).encrypt(plaintext);
@@ -5143,11 +5607,11 @@
let ivb64 = base64.encode(new Uint8Array(iv.buffer));
return `${ctb64}?iv=${ivb64}`;
}
function decrypt2(secretKey, pubkey, data) {
- const privkey = secretKey instanceof Uint8Array ? bytesToHex2(secretKey) : secretKey;
+ const privkey = secretKey instanceof Uint8Array ? secretKey : hexToBytes2(secretKey);
let [ctb64, ivb64] = data.split("?iv=");
- let key = secp256k1.getSharedSecret(privkey, "02" + pubkey);
+ let key = secp256k1.getSharedSecret(privkey, hexToBytes2("02" + pubkey));
let normalizedKey = getNormalizedX(key);
let iv = base64.decode(ivb64);
let ciphertext = base64.decode(ctb64);
let plaintext = cbc(normalizedKey, iv).decrypt(ciphertext);
@@ -5413,22 +5877,137 @@
getConversationKey: () => getConversationKey,
v2: () => v2
});
- // node_modules/@noble/ciphers/esm/_poly1305.js
- var u8to16 = (a, i2) => a[i2++] & 255 | (a[i2++] & 255) << 8;
+ // node_modules/@noble/ciphers/src/_arx.js
+ var encodeStr = (str) => Uint8Array.from(str.split(""), (c) => c.charCodeAt(0));
+ var sigma16 = encodeStr("expand 16-byte k");
+ var sigma32 = encodeStr("expand 32-byte k");
+ var sigma16_32 = u32(sigma16);
+ var sigma32_32 = u32(sigma32);
+ function rotl(a, b) {
+ return a << b | a >>> 32 - b;
+ }
+ function isAligned322(b) {
+ return b.byteOffset % 4 === 0;
+ }
+ var BLOCK_LEN = 64;
+ var BLOCK_LEN32 = 16;
+ var MAX_COUNTER = 2 ** 32 - 1;
+ var U32_EMPTY = Uint32Array.of();
+ function runCipher(core, sigma, key, nonce, data, output, counter, rounds) {
+ const len = data.length;
+ const block = new Uint8Array(BLOCK_LEN);
+ const b32 = u32(block);
+ const isAligned = isAligned322(data) && isAligned322(output);
+ const d32 = isAligned ? u32(data) : U32_EMPTY;
+ const o32 = isAligned ? u32(output) : U32_EMPTY;
+ for (let pos = 0; pos < len; counter++) {
+ core(sigma, key, nonce, b32, counter, rounds);
+ if (counter >= MAX_COUNTER)
+ throw new Error("arx: counter overflow");
+ const take = Math.min(BLOCK_LEN, len - pos);
+ if (isAligned && take === BLOCK_LEN) {
+ const pos32 = pos / 4;
+ if (pos % 4 !== 0)
+ throw new Error("arx: invalid block position");
+ for (let j = 0, posj; j < BLOCK_LEN32; j++) {
+ posj = pos32 + j;
+ o32[posj] = d32[posj] ^ b32[j];
+ }
+ pos += BLOCK_LEN;
+ continue;
+ }
+ for (let j = 0, posj; j < take; j++) {
+ posj = pos + j;
+ output[posj] = data[posj] ^ block[j];
+ }
+ pos += take;
+ }
+ }
+ function createCipher(core, opts) {
+ const { allowShortKeys, extendNonceFn, counterLength, counterRight, rounds } = checkOpts({
+ allowShortKeys: false,
+ counterLength: 8,
+ counterRight: false,
+ rounds: 20
+ }, opts);
+ if (typeof core !== "function")
+ throw new Error("core must be a function");
+ anumber4(counterLength);
+ anumber4(rounds);
+ abool2(counterRight);
+ abool2(allowShortKeys);
+ return (key, nonce, data, output, counter = 0) => {
+ abytes4(key, void 0, "key");
+ abytes4(nonce, void 0, "nonce");
+ abytes4(data, void 0, "data");
+ const len = data.length;
+ if (output === void 0)
+ output = new Uint8Array(len);
+ abytes4(output, void 0, "output");
+ anumber4(counter);
+ if (counter < 0 || counter >= MAX_COUNTER)
+ throw new Error("arx: counter overflow");
+ if (output.length < len)
+ throw new Error(`arx: output (${output.length}) is shorter than data (${len})`);
+ const toClean = [];
+ let l = key.length;
+ let k;
+ let sigma;
+ if (l === 32) {
+ toClean.push(k = copyBytes2(key));
+ sigma = sigma32_32;
+ } else if (l === 16 && allowShortKeys) {
+ k = new Uint8Array(32);
+ k.set(key);
+ k.set(key, 16);
+ sigma = sigma16_32;
+ toClean.push(k);
+ } else {
+ abytes4(key, 32, "arx key");
+ throw new Error("invalid key size");
+ }
+ if (!isAligned322(nonce))
+ toClean.push(nonce = copyBytes2(nonce));
+ const k32 = u32(k);
+ if (extendNonceFn) {
+ if (nonce.length !== 24)
+ throw new Error(`arx: extended nonce must be 24 bytes`);
+ extendNonceFn(sigma, k32, u32(nonce.subarray(0, 16)), k32);
+ nonce = nonce.subarray(16);
+ }
+ const nonceNcLen = 16 - counterLength;
+ if (nonceNcLen !== nonce.length)
+ throw new Error(`arx: nonce must be ${nonceNcLen} or 16 bytes`);
+ if (nonceNcLen !== 12) {
+ const nc = new Uint8Array(12);
+ nc.set(nonce, counterRight ? 0 : 12 - nonce.length);
+ nonce = nc;
+ toClean.push(nonce);
+ }
+ const n32 = u32(nonce);
+ runCipher(core, sigma, k32, n32, data, output, counter, rounds);
+ clean3(...toClean);
+ return output;
+ };
+ }
+
+ // node_modules/@noble/ciphers/src/_poly1305.js
+ function u8to16(a, i2) {
+ return a[i2++] & 255 | (a[i2++] & 255) << 8;
+ }
var Poly1305 = class {
+ blockLen = 16;
+ outputLen = 16;
+ buffer = new Uint8Array(16);
+ r = new Uint16Array(10);
+ h = new Uint16Array(10);
+ pad = new Uint16Array(8);
+ pos = 0;
+ finished = false;
constructor(key) {
- this.blockLen = 16;
- this.outputLen = 16;
- this.buffer = new Uint8Array(16);
- this.r = new Uint16Array(10);
- this.h = new Uint16Array(10);
- this.pad = new Uint16Array(8);
- this.pos = 0;
- this.finished = false;
- key = toBytes3(key);
- bytes3(key, 32);
+ key = copyBytes2(abytes4(key, 32, "key"));
const t0 = u8to16(key, 0);
const t1 = u8to16(key, 2);
const t2 = u8to16(key, 4);
const t3 = u8to16(key, 6);
@@ -5602,13 +6181,15 @@
for (let i2 = 1; i2 < 8; i2++) {
f = (h[i2] + pad2[i2] | 0) + (f >>> 16) | 0;
h[i2] = f & 65535;
}
+ clean3(g);
}
update(data) {
- exists3(this);
+ aexists3(this);
+ abytes4(data);
+ data = copyBytes2(data);
const { buffer, blockLen } = this;
- data = toBytes3(data);
const len = data.length;
for (let pos = 0; pos < len; ) {
const take = Math.min(blockLen - this.pos, len - pos);
if (take === blockLen) {
@@ -5626,16 +6207,13 @@
}
return this;
}
destroy() {
- this.h.fill(0);
- this.r.fill(0);
- this.buffer.fill(0);
- this.pad.fill(0);
+ clean3(this.h, this.r, this.buffer, this.pad);
}
digestInto(out) {
- exists3(this);
- output3(out, this);
+ aexists3(this);
+ aoutput3(out, this);
this.finished = true;
const { buffer, h } = this;
let { pos } = this;
if (pos) {
@@ -5660,127 +6238,18 @@
return res;
}
};
function wrapConstructorWithKey2(hashCons) {
- const hashC = (msg, key) => hashCons(key).update(toBytes3(msg)).digest();
+ const hashC = (msg, key) => hashCons(key).update(msg).digest();
const tmp = hashCons(new Uint8Array(32));
hashC.outputLen = tmp.outputLen;
hashC.blockLen = tmp.blockLen;
hashC.create = (key) => hashCons(key);
return hashC;
}
- var poly1305 = wrapConstructorWithKey2((key) => new Poly1305(key));
+ var poly1305 = /* @__PURE__ */ (() => wrapConstructorWithKey2((key) => new Poly1305(key)))();
- // node_modules/@noble/ciphers/esm/_arx.js
- var sigma16 = utf8ToBytes4("expand 16-byte k");
- var sigma32 = utf8ToBytes4("expand 32-byte k");
- var sigma16_32 = u32(sigma16);
- var sigma32_32 = u32(sigma32);
- function rotl(a, b) {
- return a << b | a >>> 32 - b;
- }
- function isAligned32(b) {
- return b.byteOffset % 4 === 0;
- }
- var BLOCK_LEN = 64;
- var BLOCK_LEN32 = 16;
- var MAX_COUNTER = 2 ** 32 - 1;
- var U32_EMPTY = new Uint32Array();
- function runCipher(core, sigma, key, nonce, data, output4, counter, rounds) {
- const len = data.length;
- const block = new Uint8Array(BLOCK_LEN);
- const b32 = u32(block);
- const isAligned = isAligned32(data) && isAligned32(output4);
- const d32 = isAligned ? u32(data) : U32_EMPTY;
- const o32 = isAligned ? u32(output4) : U32_EMPTY;
- for (let pos = 0; pos < len; counter++) {
- core(sigma, key, nonce, b32, counter, rounds);
- if (counter >= MAX_COUNTER)
- throw new Error("arx: counter overflow");
- const take = Math.min(BLOCK_LEN, len - pos);
- if (isAligned && take === BLOCK_LEN) {
- const pos32 = pos / 4;
- if (pos % 4 !== 0)
- throw new Error("arx: invalid block position");
- for (let j = 0, posj; j < BLOCK_LEN32; j++) {
- posj = pos32 + j;
- o32[posj] = d32[posj] ^ b32[j];
- }
- pos += BLOCK_LEN;
- continue;
- }
- for (let j = 0, posj; j < take; j++) {
- posj = pos + j;
- output4[posj] = data[posj] ^ block[j];
- }
- pos += take;
- }
- }
- function createCipher(core, opts) {
- const { allowShortKeys, extendNonceFn, counterLength, counterRight, rounds } = checkOpts({ allowShortKeys: false, counterLength: 8, counterRight: false, rounds: 20 }, opts);
- if (typeof core !== "function")
- throw new Error("core must be a function");
- number3(counterLength);
- number3(rounds);
- bool2(counterRight);
- bool2(allowShortKeys);
- return (key, nonce, data, output4, counter = 0) => {
- bytes3(key);
- bytes3(nonce);
- bytes3(data);
- const len = data.length;
- if (!output4)
- output4 = new Uint8Array(len);
- bytes3(output4);
- number3(counter);
- if (counter < 0 || counter >= MAX_COUNTER)
- throw new Error("arx: counter overflow");
- if (output4.length < len)
- throw new Error(`arx: output (${output4.length}) is shorter than data (${len})`);
- const toClean = [];
- let l = key.length, k, sigma;
- if (l === 32) {
- k = key.slice();
- toClean.push(k);
- sigma = sigma32_32;
- } else if (l === 16 && allowShortKeys) {
- k = new Uint8Array(32);
- k.set(key);
- k.set(key, 16);
- sigma = sigma16_32;
- toClean.push(k);
- } else {
- throw new Error(`arx: invalid 32-byte key, got length=${l}`);
- }
- if (!isAligned32(nonce)) {
- nonce = nonce.slice();
- toClean.push(nonce);
- }
- const k32 = u32(k);
- if (extendNonceFn) {
- if (nonce.length !== 24)
- throw new Error(`arx: extended nonce must be 24 bytes`);
- extendNonceFn(sigma, k32, u32(nonce.subarray(0, 16)), k32);
- nonce = nonce.subarray(16);
- }
- const nonceNcLen = 16 - counterLength;
- if (nonceNcLen !== nonce.length)
- throw new Error(`arx: nonce must be ${nonceNcLen} or 16 bytes`);
- if (nonceNcLen !== 12) {
- const nc = new Uint8Array(12);
- nc.set(nonce, counterRight ? 0 : 12 - nonce.length);
- nonce = nc;
- toClean.push(nonce);
- }
- const n32 = u32(nonce);
- runCipher(core, sigma, k32, n32, data, output4, counter, rounds);
- while (toClean.length > 0)
- toClean.pop().fill(0);
- return output4;
- };
- }
-
- // node_modules/@noble/ciphers/esm/chacha.js
+ // node_modules/@noble/ciphers/src/chacha.js
function chachaCore(s, k, n, out, cnt, rounds = 20) {
let y00 = s[0], y01 = s[1], y02 = s[2], y03 = s[3], y04 = k[0], y05 = k[1], y06 = k[2], y07 = k[3], y08 = k[4], y09 = k[5], y10 = k[6], y11 = k[7], y12 = cnt, y13 = n[0], y14 = n[1], y15 = n[2];
let x00 = y00, x01 = y01, x02 = y02, x03 = y03, x04 = y04, x05 = y05, x06 = y06, x07 = y07, x08 = y08, x09 = y09, x10 = y10, x11 = y11, x12 = y12, x13 = y13, x14 = y14, x15 = y15;
for (let r = 0; r < rounds; r += 2) {
@@ -5866,9 +6335,9 @@
out[oi++] = y13 + x13 | 0;
out[oi++] = y14 + x14 | 0;
out[oi++] = y15 + x15 | 0;
}
- function hchacha(s, k, i2, o32) {
+ function hchacha(s, k, i2, out) {
let x00 = s[0], x01 = s[1], x02 = s[2], x03 = s[3], x04 = k[0], x05 = k[1], x06 = k[2], x07 = k[3], x08 = k[4], x09 = k[5], x10 = k[6], x11 = k[7], x12 = i2[0], x13 = i2[1], x14 = i2[2], x15 = i2[3];
for (let r = 0; r < 20; r += 2) {
x00 = x00 + x04 | 0;
x12 = rotl(x12 ^ x00, 16);
@@ -5935,16 +6404,16 @@
x09 = x09 + x14 | 0;
x04 = rotl(x04 ^ x09, 7);
}
let oi = 0;
- o32[oi++] = x00;
- o32[oi++] = x01;
- o32[oi++] = x02;
- o32[oi++] = x03;
- o32[oi++] = x12;
- o32[oi++] = x13;
- o32[oi++] = x14;
- o32[oi++] = x15;
+ out[oi++] = x00;
+ out[oi++] = x01;
+ out[oi++] = x02;
+ out[oi++] = x03;
+ out[oi++] = x12;
+ out[oi++] = x13;
+ out[oi++] = x14;
+ out[oi++] = x15;
}
var chacha20 = /* @__PURE__ */ createCipher(chachaCore, {
counterRight: false,
counterLength: 4,
@@ -5958,102 +6427,102 @@
});
var ZEROS162 = /* @__PURE__ */ new Uint8Array(16);
var updatePadded = (h, msg) => {
h.update(msg);
- const left = msg.length % 16;
- if (left)
- h.update(ZEROS162.subarray(left));
+ const leftover = msg.length % 16;
+ if (leftover)
+ h.update(ZEROS162.subarray(leftover));
};
var ZEROS322 = /* @__PURE__ */ new Uint8Array(32);
- function computeTag2(fn, key, nonce, data, AAD) {
+ function computeTag(fn, key, nonce, ciphertext, AAD) {
+ if (AAD !== void 0)
+ abytes4(AAD, void 0, "AAD");
const authKey = fn(key, nonce, ZEROS322);
+ const lengths = u64Lengths(ciphertext.length, AAD ? AAD.length : 0, true);
const h = poly1305.create(authKey);
if (AAD)
updatePadded(h, AAD);
- updatePadded(h, data);
- const num = new Uint8Array(16);
- const view = createView3(num);
- setBigUint643(view, 0, BigInt(AAD ? AAD.length : 0), true);
- setBigUint643(view, 8, BigInt(data.length), true);
- h.update(num);
+ updatePadded(h, ciphertext);
+ h.update(lengths);
const res = h.digest();
- authKey.fill(0);
+ clean3(authKey, lengths);
return res;
}
var _poly1305_aead = (xorStream) => (key, nonce, AAD) => {
const tagLength = 16;
- bytes3(key, 32);
- bytes3(nonce);
return {
- encrypt: (plaintext, output4) => {
+ encrypt(plaintext, output) {
const plength = plaintext.length;
- const clength = plength + tagLength;
- if (output4) {
- bytes3(output4, clength);
- } else {
- output4 = new Uint8Array(clength);
- }
- xorStream(key, nonce, plaintext, output4, 1);
- const tag = computeTag2(xorStream, key, nonce, output4.subarray(0, -tagLength), AAD);
- output4.set(tag, plength);
- return output4;
+ output = getOutput(plength + tagLength, output, false);
+ output.set(plaintext);
+ const oPlain = output.subarray(0, -tagLength);
+ xorStream(key, nonce, oPlain, oPlain, 1);
+ const tag = computeTag(xorStream, key, nonce, oPlain, AAD);
+ output.set(tag, plength);
+ clean3(tag);
+ return output;
},
- decrypt: (ciphertext, output4) => {
- const clength = ciphertext.length;
- const plength = clength - tagLength;
- if (clength < tagLength)
- throw new Error(`encrypted data must be at least ${tagLength} bytes`);
- if (output4) {
- bytes3(output4, plength);
- } else {
- output4 = new Uint8Array(plength);
- }
+ decrypt(ciphertext, output) {
+ output = getOutput(ciphertext.length - tagLength, output, false);
const data = ciphertext.subarray(0, -tagLength);
const passedTag = ciphertext.subarray(-tagLength);
- const tag = computeTag2(xorStream, key, nonce, data, AAD);
- if (!equalBytes2(passedTag, tag))
+ const tag = computeTag(xorStream, key, nonce, data, AAD);
+ if (!equalBytes(passedTag, tag))
throw new Error("invalid tag");
- xorStream(key, nonce, data, output4, 1);
- return output4;
+ output.set(ciphertext.subarray(0, -tagLength));
+ xorStream(key, nonce, output, output, 1);
+ clean3(tag);
+ return output;
}
};
};
- var chacha20poly1305 = /* @__PURE__ */ wrapCipher({ blockSize: 64, nonceLength: 12, tagLength: 16 }, _poly1305_aead(chacha20));
- var xchacha20poly1305 = /* @__PURE__ */ wrapCipher({ blockSize: 64, nonceLength: 24, tagLength: 16 }, _poly1305_aead(xchacha20));
+ var chacha20poly1305 = /* @__PURE__ */ wrapCipher({
+ blockSize: 64,
+ nonceLength: 12,
+ tagLength: 16
+ }, _poly1305_aead(chacha20));
+ var xchacha20poly1305 = /* @__PURE__ */ wrapCipher({
+ blockSize: 64,
+ nonceLength: 24,
+ tagLength: 16
+ }, _poly1305_aead(xchacha20));
- // node_modules/@noble/hashes/esm/hmac.js
- var HMAC2 = class extends Hash2 {
- constructor(hash3, _key) {
- super();
- this.finished = false;
- this.destroyed = false;
- assert_default.hash(hash3);
- const key = toBytes2(_key);
- this.iHash = hash3.create();
+ // node_modules/@noble/hashes/src/hmac.js
+ var _HMAC2 = class {
+ oHash;
+ iHash;
+ blockLen;
+ outputLen;
+ finished = false;
+ destroyed = false;
+ constructor(hash, key) {
+ ahash2(hash);
+ abytes2(key, void 0, "key");
+ this.iHash = hash.create();
if (typeof this.iHash.update !== "function")
throw new Error("Expected instance of class which extends utils.Hash");
this.blockLen = this.iHash.blockLen;
this.outputLen = this.iHash.outputLen;
const blockLen = this.blockLen;
const pad2 = new Uint8Array(blockLen);
- pad2.set(key.length > blockLen ? hash3.create().update(key).digest() : key);
+ pad2.set(key.length > blockLen ? hash.create().update(key).digest() : key);
for (let i2 = 0; i2 < pad2.length; i2++)
pad2[i2] ^= 54;
this.iHash.update(pad2);
- this.oHash = hash3.create();
+ this.oHash = hash.create();
for (let i2 = 0; i2 < pad2.length; i2++)
pad2[i2] ^= 54 ^ 92;
this.oHash.update(pad2);
- pad2.fill(0);
+ clean2(pad2);
}
update(buf) {
- assert_default.exists(this);
+ aexists2(this);
this.iHash.update(buf);
return this;
}
digestInto(out) {
- assert_default.exists(this);
- assert_default.bytes(out, this.outputLen);
+ aexists2(this);
+ abytes2(out, this.outputLen, "output");
this.finished = true;
this.iHash.digestInto(out);
this.oHash.update(out);
this.oHash.digestInto(out);
@@ -6064,9 +6533,9 @@
this.digestInto(out);
return out;
}
_cloneInto(to) {
- to || (to = Object.create(Object.getPrototypeOf(this), {}));
+ to ||= Object.create(Object.getPrototypeOf(this), {});
const { oHash, iHash, finished, destroyed, blockLen, outputLen } = this;
to = to;
to.finished = finished;
to.destroyed = destroyed;
@@ -6075,57 +6544,62 @@
to.oHash = oHash._cloneInto(to.oHash);
to.iHash = iHash._cloneInto(to.iHash);
return to;
}
+ clone() {
+ return this._cloneInto();
+ }
destroy() {
this.destroyed = true;
this.oHash.destroy();
this.iHash.destroy();
}
};
- var hmac2 = (hash3, key, message) => new HMAC2(hash3, key).update(message).digest();
- hmac2.create = (hash3, key) => new HMAC2(hash3, key);
+ var hmac2 = (hash, key, message) => new _HMAC2(hash, key).update(message).digest();
+ hmac2.create = (hash, key) => new _HMAC2(hash, key);
- // node_modules/@noble/hashes/esm/hkdf.js
- function extract(hash3, ikm, salt) {
- assert_default.hash(hash3);
+ // node_modules/@noble/hashes/src/hkdf.js
+ function extract(hash, ikm, salt) {
+ ahash2(hash);
if (salt === void 0)
- salt = new Uint8Array(hash3.outputLen);
- return hmac2(hash3, toBytes2(salt), toBytes2(ikm));
+ salt = new Uint8Array(hash.outputLen);
+ return hmac2(hash, salt, ikm);
}
- var HKDF_COUNTER = new Uint8Array([0]);
- var EMPTY_BUFFER = new Uint8Array();
- function expand(hash3, prk, info, length = 32) {
- assert_default.hash(hash3);
- assert_default.number(length);
- if (length > 255 * hash3.outputLen)
- throw new Error("Length should be <= 255*HashLen");
- const blocks = Math.ceil(length / hash3.outputLen);
+ var HKDF_COUNTER = /* @__PURE__ */ Uint8Array.of(0);
+ var EMPTY_BUFFER = /* @__PURE__ */ Uint8Array.of();
+ function expand(hash, prk, info, length = 32) {
+ ahash2(hash);
+ anumber2(length, "length");
+ const olen = hash.outputLen;
+ if (length > 255 * olen)
+ throw new Error("Length must be <= 255*HashLen");
+ const blocks = Math.ceil(length / olen);
if (info === void 0)
info = EMPTY_BUFFER;
- const okm = new Uint8Array(blocks * hash3.outputLen);
- const HMAC3 = hmac2.create(hash3, prk);
- const HMACTmp = HMAC3._cloneInto();
- const T = new Uint8Array(HMAC3.outputLen);
+ else
+ abytes2(info, void 0, "info");
+ const okm = new Uint8Array(blocks * olen);
+ const HMAC = hmac2.create(hash, prk);
+ const HMACTmp = HMAC._cloneInto();
+ const T = new Uint8Array(HMAC.outputLen);
for (let counter = 0; counter < blocks; counter++) {
HKDF_COUNTER[0] = counter + 1;
HMACTmp.update(counter === 0 ? EMPTY_BUFFER : T).update(info).update(HKDF_COUNTER).digestInto(T);
- okm.set(T, hash3.outputLen * counter);
- HMAC3._cloneInto(HMACTmp);
+ okm.set(T, olen * counter);
+ HMAC._cloneInto(HMACTmp);
}
- HMAC3.destroy();
+ HMAC.destroy();
HMACTmp.destroy();
- T.fill(0);
- HKDF_COUNTER.fill(0);
+ clean2(T, HKDF_COUNTER);
return okm.slice(0, length);
}
// nip44.ts
var minPlaintextSize = 1;
var maxPlaintextSize = 65535;
function getConversationKey(privkeyA, pubkeyB) {
- const sharedX = secp256k1.getSharedSecret(privkeyA, "02" + pubkeyB).subarray(1, 33);
- return extract(sha2562, sharedX, "nip44-v2");
+ const sharedX = secp256k1.getSharedSecret(privkeyA, hexToBytes2("02" + pubkeyB)).subarray(1, 33);
+ return extract(sha2562, sharedX, utf8Encoder.encode("nip44-v2"));
}
function getMessageKeys(conversationKey, nonce) {
const keys = expand(sha2562, conversationKey, nonce, 76);
return {
@@ -6142,21 +6616,21 @@
const nextPower = 1 << Math.floor(Math.log2(len - 1)) + 1;
const chunk = nextPower <= 256 ? 32 : nextPower / 8;
return chunk * (Math.floor((len - 1) / chunk) + 1);
}
- function writeU16BE(num) {
- if (!Number.isSafeInteger(num) || num < minPlaintextSize || num > maxPlaintextSize)
+ function writeU16BE(num2) {
+ if (!Number.isSafeInteger(num2) || num2 < minPlaintextSize || num2 > maxPlaintextSize)
throw new Error("invalid plaintext size: must be between 1 and 65535 bytes");
const arr = new Uint8Array(2);
- new DataView(arr.buffer).setUint16(0, num, false);
+ new DataView(arr.buffer).setUint16(0, num2, false);
return arr;
}
function pad(plaintext) {
const unpadded = utf8Encoder.encode(plaintext);
const unpaddedLen = unpadded.length;
const prefix = writeU16BE(unpaddedLen);
const suffix = new Uint8Array(calcPaddedLen(unpaddedLen) - unpaddedLen);
- return concatBytes3(prefix, unpadded, suffix);
+ return concatBytes2(prefix, unpadded, suffix);
}
function unpad(padded) {
const unpaddedLen = new DataView(padded.buffer).getUint16(0);
const unpadded = padded.subarray(2, 2 + unpaddedLen);
@@ -6166,9 +6640,9 @@
}
function hmacAad(key, message, aad) {
if (aad.length !== 32)
throw new Error("AAD associated data must be 32 bytes");
- const combined = concatBytes3(aad, message);
+ const combined = concatBytes2(aad, message);
return hmac2(sha2562, key, combined);
}
function decodePayload(payload) {
if (typeof payload !== "string")
@@ -6200,15 +6674,15 @@
const { chacha_key, chacha_nonce, hmac_key } = getMessageKeys(conversationKey, nonce);
const padded = pad(plaintext);
const ciphertext = chacha20(chacha_key, chacha_nonce, padded);
const mac = hmacAad(hmac_key, ciphertext, nonce);
- return base64.encode(concatBytes3(new Uint8Array([2]), nonce, ciphertext, mac));
+ return base64.encode(concatBytes2(new Uint8Array([2]), nonce, ciphertext, mac));
}
function decrypt3(payload, conversationKey) {
const { nonce, ciphertext, mac } = decodePayload(payload);
const { chacha_key, chacha_nonce, hmac_key } = getMessageKeys(conversationKey, nonce);
const calculatedMac = hmacAad(hmac_key, ciphertext, nonce);
- if (!equalBytes2(calculatedMac, mac))
+ if (!equalBytes(calculatedMac, mac))
throw new Error("invalid MAC");
const padded = chacha20(chacha_key, chacha_nonce, ciphertext);
return unpad(padded);
}
@@ -6960,20 +7434,20 @@
}
if (cutPoint < 1) {
return 0;
}
- const num = parseInt(amount.substring(0, cutPoint));
+ const num2 = parseInt(amount.substring(0, cutPoint));
switch (char) {
case "m":
- return num * 1e5;
+ return num2 * 1e5;
case "u":
- return num * 100;
+ return num2 * 100;
case "n":
- return num / 10;
+ return num2 / 10;
case "p":
- return num / 1e4;
+ return num2 / 1e4;
default:
- return num * 1e8;
+ return num2 * 1e8;
}
}
// nip77.ts
@@ -7112,10 +7586,10 @@
getFingerprint(n) {
let input = new WrappedBuffer();
input.extend(this.buf);
input.extend(encodeVarInt(n));
- let hash3 = sha2562(input.unwrap());
- return hash3.subarray(0, FINGERPRINT_SIZE);
+ let hash = sha2562(input.unwrap());
+ return hash.subarray(0, FINGERPRINT_SIZE);
}
};
var NegentropyStorageVector = class {
items;
@@ -7126,9 +7600,9 @@
}
insert(timestamp, id) {
if (this.sealed)
throw Error("already sealed");
- const idb = hexToBytes3(id);
+ const idb = hexToBytes2(id);
if (idb.byteLength !== ID_SIZE)
throw Error("bad id size for added item");
this.items.push({ timestamp, id: idb });
}
@@ -7217,15 +7691,15 @@
_bound(timestamp, id) {
return { timestamp, id: id || new Uint8Array(0) };
}
initiate() {
- let output4 = new WrappedBuffer();
- output4.extend(new Uint8Array([PROTOCOL_VERSION]));
- this.splitRange(0, this.storage.size(), this._bound(Number.MAX_VALUE), output4);
- return bytesToHex3(output4.unwrap());
+ let output = new WrappedBuffer();
+ output.extend(new Uint8Array([PROTOCOL_VERSION]));
+ this.splitRange(0, this.storage.size(), this._bound(Number.MAX_VALUE), output);
+ return bytesToHex2(output.unwrap());
}
reconcile(queryMsg, onhave, onneed) {
- const query = new WrappedBuffer(hexToBytes3(queryMsg));
+ const query = new WrappedBuffer(hexToBytes2(queryMsg));
this.lastTimestampIn = this.lastTimestampOut = 0;
let fullOutput = new WrappedBuffer();
fullOutput.extend(new Uint8Array([PROTOCOL_VERSION]));
let protocolVersion = getByte(query);
@@ -7266,24 +7740,24 @@
let numIds = decodeVarInt(query);
let theirElems = {};
for (let i2 = 0; i2 < numIds; i2++) {
let e = getBytes(query, ID_SIZE);
- theirElems[bytesToHex3(e)] = e;
+ theirElems[bytesToHex2(e)] = e;
}
skip = true;
this.storage.iterate(lower, upper, (item) => {
let k = item.id;
- const id = bytesToHex3(k);
+ const id = bytesToHex2(k);
if (!theirElems[id]) {
onhave?.(id);
} else {
- delete theirElems[bytesToHex3(k)];
+ delete theirElems[bytesToHex2(k)];
}
return true;
});
if (onneed) {
for (let v of Object.values(theirElems)) {
- onneed(bytesToHex3(v));
+ onneed(bytesToHex2(v));
}
}
} else {
throw Error("unexpected mode");
@@ -7299,9 +7773,9 @@
}
prevIndex = upper;
prevBound = currBound;
}
- return fullOutput.length === 1 ? null : bytesToHex3(fullOutput.unwrap());
+ return fullOutput.length === 1 ? null : bytesToHex2(fullOutput.unwrap());
}
splitRange(lower, upper, upperBound, o) {
let numElems = upper - lower;
let buckets = 16;
@@ -7374,13 +7848,13 @@
this.lastTimestampOut = temp;
return encodeVarInt(timestamp + 1);
}
encodeBound(key) {
- let output4 = new WrappedBuffer();
- output4.extend(this.encodeTimestampOut(key.timestamp));
- output4.extend(encodeVarInt(key.id.length));
- output4.extend(key.id);
- return output4;
+ let output = new WrappedBuffer();
+ output.extend(this.encodeTimestampOut(key.timestamp));
+ output.extend(encodeVarInt(key.id.length));
+ output.extend(key.id);
+ return output;
}
getMinimalBound(prev, curr) {
if (curr.timestamp !== prev.timestamp) {
return this._bound(curr.timestamp);
@@ -7550,10 +8024,10 @@
}
return methodTag.length > 0 && methodTag[1].toLowerCase() === method.toLowerCase();
}
function hashPayload(payload) {
- const hash3 = sha2562(utf8Encoder.encode(JSON.stringify(payload)));
- return bytesToHex2(hash3);
+ const hash = sha2562(utf8Encoder.encode(JSON.stringify(payload)));
+ return bytesToHex2(hash);
}
function validateEventPayloadTag(event, payload) {
const payloadTag = event.tags.find((t) => t[0] === "payload");
if (!payloadTag) {