@qntx/wallet-chains 0.0.0-stage → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1 @@
1
+ {"version":3,"file":"ed25519-DUtI5nWr.mjs","names":["_1n","_2n","_8n","randomBytes","wcRandomBytes"],"sources":["../../../node_modules/.bun/@noble+curves@2.4.0/node_modules/@noble/curves/abstract/edwards.js","../../../node_modules/.bun/@noble+curves@2.4.0/node_modules/@noble/curves/ed25519.js"],"sourcesContent":["/**\n * Twisted Edwards curve. The formula is: ax² + y² = 1 + dx²y².\n * For design rationale of types / exports, see weierstrass module documentation.\n * Untwisted Edwards curves exist, but they aren't used in real-world protocols.\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport { abool, abytes, aInRange, asafenumber, bytesToHex, bytesToNumberLE, concatBytes, copyBytes, hexToBytes, isBytes, notImplemented, validateObject, randomBytes as wcRandomBytes, } from \"../utils.js\";\nimport { createCurveFields, createKeygen, normalizeZ, ScalarMultiplier, validatePointCons, } from \"./curve.js\";\nimport { FpLegendre } from \"./modular.js\";\n// Be friendly to bad ECMAScript parsers by not using bigint literals\n// prettier-ignore\nconst _0n = /* @__PURE__ */ BigInt(0), _1n = /* @__PURE__ */ BigInt(1), _2n = /* @__PURE__ */ BigInt(2), _4n = /* @__PURE__ */ BigInt(4), _8n = /* @__PURE__ */ BigInt(8);\n// Affine Edwards-equation check only; this does not prove subgroup membership, canonical\n// encoding, prime-order base-point requirements, or identity exclusion.\nfunction isEdValidXY(Fp, CURVE, x, y) {\n const x2 = Fp.sqr(x);\n const y2 = Fp.sqr(y);\n const left = Fp.add(Fp.mul(CURVE.a, x2), y2);\n const right = Fp.add(Fp.ONE, Fp.mul(CURVE.d, Fp.mul(x2, y2)));\n return Fp.eql(left, right);\n}\n/**\n * @param params - Curve parameters. See {@link EdwardsOpts}.\n * @param extraOpts - Optional helpers and overrides. See {@link EdwardsExtraOpts}.\n * @returns Edwards point constructor. Generator validation here only checks\n * that `(Gx, Gy)` satisfies the affine Edwards equation.\n * RFC 8032 base-point constraints like `B != (0,1)` and `[L]B = 0`\n * are left to the caller's chosen parameters, since eager subgroup\n * validation here adds about 10-15ms to heavyweight imports like ed448.\n * The returned constructor also eagerly marks `Point.BASE` for W=6\n * precompute caching. Some code paths still assume\n * `Fp.BYTES === Fn.BYTES`, so mismatched byte lengths are not fully audited here.\n * @throws If the curve parameters or Edwards overrides are invalid. {@link Error}\n * @example\n * ```ts\n * import { edwards } from '@noble/curves/abstract/edwards.js';\n * import { jubjub } from '@noble/curves/misc.js';\n * // Build a point constructor from explicit curve parameters, then use its base point.\n * const Point = edwards(jubjub.Point.CURVE());\n * Point.BASE.toHex();\n * ```\n */\nexport function edwards(params, extraOpts = {}) {\n validateObject(extraOpts, {}, {}, 'extraOpts');\n const opts = extraOpts;\n const validated = createCurveFields('edwards', params, opts, opts.FpFnLE);\n const { Fp, Fn } = validated;\n let CURVE = validated.CURVE;\n const { h: cofactor } = CURVE;\n // The unified add-2008-hwcd formulas (see EdwardsPoint.add/double) are complete —\n // exception-free for every input pair — only when a is a square and d a non-square in Fp\n // (Bernstein–Birkner–Joye–Lange–Peters, \"Twisted Edwards curves\", thm 3.3). The constant-time\n // kernels in curve.ts assume completeness, so an incomplete curve could silently produce\n // wrong results on exceptional inputs. Fail construction instead.\n if (FpLegendre(Fp, CURVE.a) !== 1)\n throw new Error('edwards: CURVE.a must be a square in Fp for complete addition formulas');\n if (FpLegendre(Fp, CURVE.d) !== -1)\n throw new Error('edwards: CURVE.d must be a non-square in Fp for complete addition formulas');\n validateObject(opts, {}, { uvRatio: 'function', randomBytes: 'function' });\n const randomBytes = opts.randomBytes === undefined ? wcRandomBytes : opts.randomBytes;\n // Coordinate and ZIP-215 bounds follow the base-field byte container, not scalar bytes.\n const MASK = _2n << (BigInt(Fp.BYTES * 8) - _1n);\n function isOdd(n) {\n if (!Fp.isOdd)\n throw new Error('Field does not have .isOdd()');\n return Fp.isOdd(n);\n }\n // sqrt(u/v)\n const uvRatio = opts.uvRatio === undefined\n ? (u, v) => {\n try {\n return { isValid: true, value: Fp.sqrt(Fp.div(u, v)) };\n }\n catch (e) {\n return { isValid: false, value: _0n };\n }\n }\n : opts.uvRatio;\n // Validate whether the passed curve params are valid.\n // equation ax² + y² = 1 + dx²y² should work for generator point.\n if (!isEdValidXY(Fp, CURVE, CURVE.Gx, CURVE.Gy))\n throw new Error('bad curve params: generator point');\n // Multiplication by param `a` sits on the double() / add() hot paths. For the common twists\n // a=-1 (ed25519, jubjub) and a=1 (ed448) the full field multiplication is replaced with\n // negation / identity. Selection depends only on public curve constants.\n const mulA = Fp.eql(CURVE.a, Fp.neg(Fp.ONE)) ? (x) => Fp.neg(x)\n : Fp.eql(CURVE.a, Fp.ONE) ? (x) => x\n : (x) => Fp.mul(CURVE.a, x); // prettier-ignore\n /**\n * Asserts coordinate is valid: 0 <= n < MASK.\n * Coordinates >= Fp.ORDER are allowed for zip215.\n */\n function acoord(title, n, banZero = false) {\n const min = banZero ? _1n : _0n;\n aInRange('coordinate ' + title, n, min, MASK);\n return n;\n }\n function aedpoint(other) {\n if (!(other instanceof Point))\n throw new Error('EdwardsPoint expected');\n }\n // Extended Point works in extended coordinates: (X, Y, Z, T) ∋ (x=X/Z, y=Y/Z, T=xy).\n // https://en.wikipedia.org/wiki/Twisted_Edwards_curve#Extended_coordinates\n class Point {\n static BASE = new Point(CURVE.Gx, CURVE.Gy, Fp.ONE, Fp.mul(CURVE.Gx, CURVE.Gy));\n static ZERO = new Point(Fp.ZERO, Fp.ONE, Fp.ONE, Fp.ZERO);\n static Fp = Fp;\n static Fn = Fn;\n X;\n Y;\n Z;\n T;\n constructor(X, Y, Z, T) {\n this.X = acoord('x', X);\n this.Y = acoord('y', Y);\n this.Z = acoord('z', Z, true);\n this.T = acoord('t', T);\n Object.freeze(this);\n }\n static CURVE() {\n return CURVE;\n }\n /**\n * Create one extended Edwards point from affine coordinates.\n * Does NOT validate that the point is on-curve or torsion-free.\n * Use `.assertValidity()` on adversarial inputs.\n */\n static fromAffine(p) {\n if (p instanceof Point)\n throw new Error('extended point not allowed');\n const { x, y } = p || {};\n acoord('x', x);\n acoord('y', y);\n return new Point(x, y, Fp.ONE, Fp.mul(x, y));\n }\n // Uses algo from RFC8032 5.1.3.\n static fromBytes(bytes, zip215 = false) {\n const len = Fp.BYTES;\n const { a, d } = CURVE;\n bytes = copyBytes(abytes(bytes, len, 'point'));\n abool(zip215, 'zip215');\n const normed = copyBytes(bytes); // copy again, we'll manipulate it\n const lastByte = bytes[len - 1]; // select last byte\n normed[len - 1] = lastByte & ~0x80; // clear last bit\n const y = bytesToNumberLE(normed);\n // zip215=true is good for consensus-critical apps. =false follows RFC8032 / NIST186-5.\n // RFC8032 prohibits >= p, but ZIP215 doesn't\n // zip215=true: 0 <= y < MASK (2^256 for ed25519)\n // zip215=false: 0 <= y < P (2^255-19 for ed25519)\n const max = zip215 ? MASK : Fp.ORDER;\n aInRange('point.y', y, _0n, max);\n // Ed25519: x² = (y²-1)/(dy²+1) mod p. Ed448: x² = (y²-1)/(dy²-1) mod p. Generic case:\n // ax²+y²=1+dx²y² => y²-1=dx²y²-ax² => y²-1=x²(dy²-a) => x²=(y²-1)/(dy²-a)\n const y2 = Fp.sqr(y); // denominator is always non-0 mod p.\n const u = Fp.sub(y2, Fp.ONE); // u = y² - 1\n const v = Fp.sub(Fp.mulN(d, y2), a); // v = d y² - a.\n let { isValid, value: x } = uvRatio(u, v); // √(u/v)\n if (!isValid)\n throw new Error('bad point: invalid y coordinate');\n const isXOdd = isOdd(x); // There are 2 square roots. Use x_0 bit to select proper\n const isLastByteOdd = (lastByte & 0x80) !== 0; // x_0, last bit\n if (!zip215 && Fp.is0(x) && isLastByteOdd)\n // if x=0 and x_0 = 1, fail\n throw new Error('bad point: x=0 and x_0=1');\n if (isLastByteOdd !== isXOdd)\n x = Fp.neg(x); // if x_0 != x mod 2, set x = p-x\n return Point.fromAffine({ x, y });\n }\n static fromHex(hex, zip215 = false) {\n return Point.fromBytes(hexToBytes(hex), zip215);\n }\n get x() {\n return this.toAffine().x;\n }\n get y() {\n return this.toAffine().y;\n }\n precompute(windowSize = 6, isLazy = true) {\n wnaf.setWindowSize(this, windowSize);\n if (!isLazy)\n this.multiply(_2n); // random number\n return this;\n }\n // Useful in fromAffine() - not for fromBytes(), which always created valid points.\n assertValidity() {\n const p = this;\n const { a, d } = CURVE;\n // Keep generic Edwards validation fail-closed on the neutral point.\n // Even though ZERO is algebraically valid and can roundtrip through encodings, higher-level\n // callers often reach it only through broken hash/scalar plumbing; rejecting it here avoids\n // silently treating that degenerate state as an ordinary public point.\n if (p.is0())\n throw new Error('bad point: ZERO'); // TODO: optimize, with vars below?\n // Equation in affine coordinates: ax² + y² = 1 + dx²y²\n // Equation in projective coordinates (X/Z, Y/Z, Z): (aX² + Y²)Z² = Z⁴ + dX²Y²\n const { X, Y, Z, T } = p;\n const X2 = Fp.sqr(X); // X²\n const Y2 = Fp.sqr(Y); // Y²\n const Z2 = Fp.sqr(Z); // Z²\n const Z4 = Fp.sqr(Z2); // Z⁴\n const aX2 = Fp.mul(X2, a); // aX²\n const left = Fp.mul(Fp.add(aX2, Y2), Z2); // (aX² + Y²)Z²\n const right = Fp.add(Z4, Fp.mul(d, Fp.mul(X2, Y2))); // Z⁴ + dX²Y²\n if (!Fp.eql(left, right))\n throw new Error('bad point: equation left != right (1)');\n // In Extended coordinates we also have T, which is x*y=T/Z: check X*Y == Z*T\n const XY = Fp.mul(X, Y);\n const ZT = Fp.mul(Z, T);\n if (!Fp.eql(XY, ZT))\n throw new Error('bad point: equation left != right (2)');\n }\n // Compare one point to another.\n equals(other) {\n aedpoint(other);\n const { X: X1, Y: Y1, Z: Z1 } = this;\n const { X: X2, Y: Y2, Z: Z2 } = other;\n const X1Z2 = Fp.mul(X1, Z2);\n const X2Z1 = Fp.mul(X2, Z1);\n const Y1Z2 = Fp.mul(Y1, Z2);\n const Y2Z1 = Fp.mul(Y2, Z1);\n return Fp.eql(X1Z2, X2Z1) && Fp.eql(Y1Z2, Y2Z1);\n }\n is0() {\n return this.equals(Point.ZERO);\n }\n negate() {\n // Flips point sign to a negative one (-x, y in affine coords)\n return new Point(Fp.neg(this.X), this.Y, this.Z, Fp.neg(this.T));\n }\n // Fast algo for doubling Extended Point.\n // https://hyperelliptic.org/EFD/g1p/auto-twisted-extended.html#doubling-dbl-2008-hwcd\n // Cost: 4M + 4S + 1*a + 6add + 1*2.\n double() {\n const { X: X1, Y: Y1, Z: Z1 } = this;\n const A = Fp.sqr(X1); // A = X12\n const B = Fp.sqr(Y1); // B = Y12\n const C = Fp.mul(Fp.sqr(Z1), _2n); // C = 2*Z12\n const D = mulA(A); // D = a*A\n const x1y1 = Fp.addN(X1, Y1);\n const E = Fp.sub(Fp.subN(Fp.sqr(x1y1), A), B); // E = (X1+Y1)2-A-B\n const G = Fp.addN(D, B); // G = D+B\n const F = Fp.subN(G, C); // F = G-C\n const H = Fp.subN(D, B); // H = D-B\n const X3 = Fp.mul(E, F); // X3 = E*F\n const Y3 = Fp.mul(G, H); // Y3 = G*H\n const T3 = Fp.mul(E, H); // T3 = E*H\n const Z3 = Fp.mul(F, G); // Z3 = F*G\n return new Point(X3, Y3, Z3, T3);\n }\n // Fast algo for adding 2 Extended Points.\n // https://hyperelliptic.org/EFD/g1p/auto-twisted-extended.html#addition-add-2008-hwcd\n // Cost: 9M + 1*a + 1*d + 7add.\n add(other) {\n aedpoint(other);\n const { d } = CURVE;\n const { X: X1, Y: Y1, Z: Z1, T: T1 } = this;\n const { X: X2, Y: Y2, Z: Z2, T: T2 } = other;\n const A = Fp.mul(X1, X2); // A = X1*X2\n const B = Fp.mul(Y1, Y2); // B = Y1*Y2\n const C = Fp.mul(Fp.mulN(T1, d), T2); // C = T1*d*T2\n const D = Fp.mul(Z1, Z2); // D = Z1*Z2\n // E = (X1+Y1)*(X2+Y2)-A-B\n const E = Fp.sub(Fp.subN(Fp.mulN(Fp.addN(X1, Y1), Fp.addN(X2, Y2)), A), B);\n const F = Fp.subN(D, C); // F = D-C\n const G = Fp.addN(D, C); // G = D+C\n const H = Fp.sub(B, mulA(A)); // H = B-a*A\n const X3 = Fp.mul(E, F); // X3 = E*F\n const Y3 = Fp.mul(G, H); // Y3 = G*H\n const T3 = Fp.mul(E, H); // T3 = E*H\n const Z3 = Fp.mul(F, G); // Z3 = F*G\n return new Point(X3, Y3, Z3, T3);\n }\n subtract(other) {\n // Validate before calling `negate()` so wrong inputs fail with the point guard\n // instead of leaking a foreign `negate()` error.\n aedpoint(other);\n return this.add(other.negate());\n }\n // Constant-time multiplication.\n multiply(scalar) {\n // 1 <= scalar < L\n // Keep the subgroup-scalar contract strict instead of reducing 0 / n to ZERO.\n // In keygen/signing-style callers, those values usually mean broken hash/scalar plumbing,\n // and failing closed is safer than silently producing the identity point.\n if (!Fn.isValidNot0(scalar))\n throw new RangeError('invalid scalar: expected 1 <= sc < curve.n');\n const { p, f } = wnaf.mulSecret(this, scalar, cofactor, normalize);\n return normalize([p, f])[0];\n }\n // Non-constant-time multiplication. Uses double-and-add algorithm.\n // It's faster, but should only be used when you don't care about\n // an exposed private key e.g. sig verification.\n // Keeps the same subgroup-scalar contract: 0 is allowed for public-scalar callers, but\n // n and larger values are rejected instead of being reduced mod n to the identity point.\n multiplyUnsafe(scalar) {\n // 0 <= scalar < L\n if (!Fn.isValid(scalar))\n throw new RangeError('invalid scalar: expected 0 <= sc < curve.n');\n if (scalar === _0n)\n return Point.ZERO;\n if (this.is0() || scalar === _1n)\n return this;\n return wnaf.mulUnsafe(this, scalar, normalize);\n }\n // Checks if point is of small order.\n // If you add something to small order point, you will have \"dirty\"\n // point with torsion component.\n // Clears cofactor and checks if the result is 0.\n isSmallOrder() {\n return this.clearCofactor().is0();\n }\n // Multiplies point by curve order and checks if the result is 0.\n // Returns `false` is the point is dirty.\n isTorsionFree() {\n return wnaf.mulUnsafe(this, CURVE.n).is0();\n }\n // Converts Extended point to default (x, y) coordinates.\n // Can accept precomputed Z^-1 - for example, from invertBatch.\n toAffine(invertedZ) {\n const p = this;\n let iz = invertedZ;\n if (iz != null && typeof iz !== 'bigint')\n throw new TypeError('\"invertedZ\" expected bigint, got type=' + typeof iz);\n const { X, Y, Z } = p;\n const is0 = p.is0();\n if (iz == null)\n iz = is0 ? Fp.create(_8n) : Fp.inv(Z);\n const x = Fp.mul(X, iz);\n const y = Fp.mul(Y, iz);\n const zz = Fp.mul(Z, iz);\n if (is0)\n return { x: Fp.ZERO, y: Fp.ONE };\n if (!Fp.eql(zz, Fp.ONE))\n throw new Error('invZ was invalid');\n return { x, y };\n }\n clearCofactor() {\n if (cofactor === _1n)\n return this;\n // 2.8-3.8x speed-up vs naive\n if (cofactor === _2n)\n return this.double();\n if (cofactor === _4n)\n return this.double().double();\n if (cofactor === _8n)\n return this.double().double().double();\n return this.multiplyUnsafe(cofactor);\n }\n toBytes() {\n const { x, y } = this.toAffine();\n // Fp.toBytes() allows non-canonical encoding of y (>= p).\n const bytes = Fp.toBytes(y);\n // Each y has 2 valid points: (x, y), (x,-y).\n // When compressing, it's enough to store y and use the last byte to encode sign of x\n bytes[bytes.length - 1] |= isOdd(x) ? 0x80 : 0;\n return bytes;\n }\n toHex() {\n return bytesToHex(this.toBytes());\n }\n toString() {\n return `<Point ${this.is0() ? 'ZERO' : this.toHex()}>`;\n }\n }\n // Keep constructor work cheap: subgroup/generator validation belongs to the caller's curve\n // parameters, and doing the extra checks here adds about 10-15ms to heavy module imports.\n // Callers that construct custom curves are responsible for supplying the correct base point.\n // try {\n // Point.BASE.assertValidity();\n // if (!Point.BASE.isTorsionFree()) throw new Error('bad point: not in prime-order subgroup');\n // } catch {\n // throw new Error('bad curve params: generator point');\n // }\n const normalize = (points) => normalizeZ(Point, points);\n const wnaf = new ScalarMultiplier(Point, randomBytes);\n // Enable W=6 wNAF precomputes. Slows down first publicKey computation.\n // Disable for tiny toy curves, with scalar fields < 6 bits.\n if (wnaf.bits >= 6)\n Point.BASE.precompute(6);\n Object.freeze(Point.prototype);\n Object.freeze(Point);\n return Point;\n}\n/**\n * Base class for prime-order points like Ristretto255 and Decaf448.\n * These points eliminate cofactor issues by representing equivalence classes\n * of Edwards curve points. Multiple Edwards representatives can describe the\n * same abstract wrapper element, so wrapper validity is not the same thing as\n * the hidden representative being torsion-free.\n * @param ep - Backing Edwards point.\n * @example\n * Base class for prime-order points like Ristretto255 and Decaf448.\n *\n * ```ts\n * import { ristretto255 } from '@noble/curves/ed25519.js';\n * const point = ristretto255.Point.BASE.multiply(2n);\n * ```\n */\nexport class PrimeEdwardsPoint {\n static BASE;\n static ZERO;\n static Fp;\n static Fn;\n ep;\n /**\n * Wrap one internal Edwards representative directly.\n * This is not a canonical encoding boundary: alternate Edwards\n * representatives may still describe the same abstract wrapper element.\n */\n constructor(ep) {\n this.ep = ep;\n }\n // Static methods that must be implemented by subclasses\n static fromBytes(_bytes) {\n notImplemented();\n }\n static fromHex(_hex) {\n notImplemented();\n }\n get x() {\n return this.toAffine().x;\n }\n get y() {\n return this.toAffine().y;\n }\n // Common implementations\n clearCofactor() {\n // no-op for the abstract prime-order wrapper group; this is about the\n // wrapper element, not the hidden Edwards representative.\n return this;\n }\n assertValidity() {\n // Keep wrapper validity at the abstract-group boundary. Canonical decode\n // may choose Edwards representatives that differ by small torsion, so\n // checking `this.ep.isTorsionFree()` here would reject valid wrapper points.\n this.ep.assertValidity();\n }\n /**\n * Return affine coordinates of the current internal Edwards representative.\n * This is a convenience helper, not a canonical Ristretto/Decaf encoding.\n * Equal abstract elements may expose different `x` / `y`; use\n * `toBytes()` / `fromBytes()` for canonical roundtrips.\n */\n toAffine(invertedZ) {\n return this.ep.toAffine(invertedZ);\n }\n toHex() {\n return bytesToHex(this.toBytes());\n }\n toString() {\n return this.toHex();\n }\n isTorsionFree() {\n // Abstract Ristretto/Decaf elements are already prime-order even when the\n // hidden Edwards representative is not torsion-free.\n return true;\n }\n isSmallOrder() {\n return false;\n }\n add(other) {\n this.assertSame(other);\n return this.init(this.ep.add(other.ep));\n }\n subtract(other) {\n this.assertSame(other);\n return this.init(this.ep.subtract(other.ep));\n }\n multiply(scalar) {\n return this.init(this.ep.multiply(scalar));\n }\n multiplyUnsafe(scalar) {\n return this.init(this.ep.multiplyUnsafe(scalar));\n }\n double() {\n return this.init(this.ep.double());\n }\n negate() {\n return this.init(this.ep.negate());\n }\n precompute(windowSize, isLazy) {\n this.ep.precompute(windowSize, isLazy);\n // Keep the wrapper identity stable like the backing Edwards API instead of\n // allocating a fresh wrapper around the same cached point.\n return this;\n }\n}\n/**\n * Initializes EdDSA signatures over given Edwards curve.\n * @param Point - Edwards point constructor.\n * @param cHash - Hash function.\n * @param eddsaOpts - Optional signature helpers. See {@link EdDSAOpts}.\n * @returns EdDSA helper namespace.\n * @throws If the hash function, options, or derived point operations are invalid. {@link Error}\n * @example\n * Initializes EdDSA signatures over given Edwards curve.\n *\n * ```ts\n * import { eddsa } from '@noble/curves/abstract/edwards.js';\n * import { jubjub } from '@noble/curves/misc.js';\n * import { sha512 } from '@noble/hashes/sha2.js';\n * const sigs = eddsa(jubjub.Point, sha512);\n * const { secretKey, publicKey } = sigs.keygen();\n * const msg = new TextEncoder().encode('hello noble');\n * const sig = sigs.sign(msg, secretKey);\n * const isValid = sigs.verify(sig, msg, publicKey);\n * ```\n */\nexport function eddsa(Point, cHash, eddsaOpts = {}) {\n validatePointCons(Point);\n if (typeof cHash !== 'function')\n throw new Error('\"hash\" function param is required');\n const hash = cHash;\n const opts = eddsaOpts;\n validateObject(opts, {}, {\n adjustScalarBytes: 'function',\n randomBytes: 'function',\n domain: 'function',\n prehash: 'function',\n zip215: 'boolean',\n mapToCurve: 'function',\n toMontgomery: 'function',\n toMontgomerySecret: 'function',\n });\n const { prehash } = opts;\n const { BASE, Fp, Fn } = Point;\n const outputLen = hash.outputLen;\n const expectedLen = 2 * Fp.BYTES;\n // When hash metadata is available, reject incompatible EdDSA wrappers at construction time\n // instead of deferring the mismatch until the first keygen/sign call.\n if (outputLen !== undefined) {\n asafenumber(outputLen, 'hash.outputLen');\n if (outputLen !== expectedLen)\n throw new Error(`hash.outputLen must be ${expectedLen}, got ${outputLen}`);\n }\n const randomBytes = opts.randomBytes === undefined ? wcRandomBytes : opts.randomBytes;\n const toMontgomery = opts.toMontgomery;\n const toMontgomerySecret = opts.toMontgomerySecret;\n const adjustScalarBytes = opts.adjustScalarBytes === undefined\n ? (bytes) => bytes\n : opts.adjustScalarBytes;\n const domain = opts.domain === undefined\n ? (data, ctx, phflag) => {\n abool(phflag, 'phflag');\n if (ctx.length || phflag)\n throw new Error('Contexts/pre-hash are not supported');\n return data;\n }\n : opts.domain; // NOOP\n // Parse an EdDSA digest as a little-endian integer and reduce it modulo the scalar field order.\n function modN_LE(hash) {\n return Fn.create(bytesToNumberLE(hash)); // Not Fn.fromBytes: it has length limit\n }\n // Get the hashed private scalar per RFC8032 5.1.5\n function getPrivateScalar(key) {\n const len = lengths.secretKey;\n abytes(key, lengths.secretKey, 'secretKey');\n // Hash private key with curve's hash function to produce uniformingly random input\n // Check byte lengths: ensure(64, h(ensure(32, key)))\n const hashed = abytes(hash(key), 2 * len, 'hashedSecretKey');\n // Slice before clamping so in-place adjustors don't corrupt the prefix half.\n const head = adjustScalarBytes(hashed.slice(0, len)); // clear first half bits, produce FE\n const prefix = hashed.slice(len, 2 * len); // second half is called key prefix (5.1.6)\n const scalar = modN_LE(head); // The actual private scalar\n return { head, prefix, scalar };\n }\n /** Convenience method that creates public key from scalar. RFC8032 5.1.5\n * Also exposes the derived scalar/prefix tuple and point form reused by sign().\n */\n function getExtendedPublicKey(secretKey) {\n const { head, prefix, scalar } = getPrivateScalar(secretKey);\n const point = BASE.multiply(scalar); // Point on Edwards curve aka public key\n const pointBytes = point.toBytes();\n return { head, prefix, scalar, point, pointBytes };\n }\n /** Calculates EdDSA pub key. RFC8032 5.1.5. */\n function getPublicKey(secretKey) {\n return getExtendedPublicKey(secretKey).pointBytes;\n }\n // Hash domain-separated chunks into a little-endian scalar modulo the group order.\n function hashDomainToScalar(context = Uint8Array.of(), ...msgs) {\n const msg = concatBytes(...msgs);\n return modN_LE(hash(domain(msg, abytes(context, undefined, 'context'), !!prehash)));\n }\n /** Signs message with secret key. RFC8032 5.1.6 */\n function sign(msg, secretKey, options = {}) {\n validateObject(options, {}, {}, 'options');\n // Snapshot once: nonce and challenge must use the same invocation-time message bytes.\n msg = copyBytes(abytes(msg, undefined, 'message'));\n if (prehash)\n msg = prehash(msg); // for ed25519ph etc.\n const { prefix, scalar, pointBytes } = getExtendedPublicKey(secretKey);\n const r = hashDomainToScalar(options.context, prefix, msg); // r = dom2(F, C) || prefix || PH(M)\n // RFC 8032 5.1.6 allows r mod L = 0, and SUPERCOP ref10 accepts the resulting identity-point\n // signature.\n // We intentionally keep the safe multiply() rejection here so a miswired all-zero hash provider\n // fails loudly instead of silently producing a degenerate signature.\n const R = BASE.multiply(r).toBytes(); // R = rG\n const k = hashDomainToScalar(options.context, R, pointBytes, msg); // R || A || PH(M)\n const s = Fn.create(r + k * scalar); // S = (r + k * s) mod L\n if (!Fn.isValid(s))\n throw new Error('sign failed: invalid s'); // 0 <= s < L\n const rs = concatBytes(R, Fn.toBytes(s));\n return abytes(rs, lengths.signature, 'result');\n }\n // Keep the shared helper strict by default: RFC 8032 / NIST-style wrappers should reject\n // non-canonical encodings unless they explicitly opt into ZIP-215's more permissive decode rules.\n const verifyOpts = {\n zip215: opts.zip215,\n };\n /**\n * Verifies EdDSA signature against message and public key. RFC 8032 §§5.1.7 and 5.2.7.\n * A cofactored verification equation is checked.\n */\n function verify(sig, msg, publicKey, options = verifyOpts) {\n // Validate before destructuring so explicit null follows the standard options error.\n validateObject(options);\n // Preserve the wrapper-selected default for `{}` / `{ zip215: undefined }`, not just omitted opts.\n const { context } = options;\n const zip215 = options.zip215 === undefined ? !!verifyOpts.zip215 : options.zip215;\n const len = lengths.signature;\n sig = abytes(sig, len, 'signature');\n msg = abytes(msg, undefined, 'message');\n publicKey = abytes(publicKey, lengths.publicKey, 'publicKey');\n if (zip215 !== undefined)\n abool(zip215, 'zip215');\n if (prehash)\n msg = prehash(msg); // for ed25519ph, etc\n const mid = len / 2;\n const r = sig.subarray(0, mid);\n const s = bytesToNumberLE(sig.subarray(mid, len));\n let A, R, SB;\n try {\n // ZIP-215 is more permissive than RFC 8032 / NIST186-5. Use it only for wrappers that\n // explicitly want consensus-style unreduced encoding acceptance.\n // zip215=true: 0 <= y < MASK (2^256 for ed25519)\n // zip215=false: 0 <= y < P (2^255-19 for ed25519)\n A = Point.fromBytes(publicKey, zip215);\n R = Point.fromBytes(r, zip215);\n SB = BASE.multiplyUnsafe(s); // 0 <= s < l is done inside\n }\n catch (error) {\n return false;\n }\n // RFC 8032 §§5.1.7/5.2.7 and FIPS 186-5 §§7.7.2/7.8.2 only decode A' and check the cofactored\n // verification equation; they do not add a separate low-order-public-key rejection here.\n // Strict mode still rejects small-order A' intentionally for SBS-style non-repudiation and to\n // avoid ambiguous verification outcomes where unusual low-order keys can make distinct\n // key/signature/message combinations verify.\n if (!zip215 && A.isSmallOrder())\n return false;\n // ZIP-215 accepts noncanonical / unreduced point encodings, so the challenge hash must use the\n // exact signature/public-key bytes rather than canonicalized re-encodings of the decoded points.\n const k = hashDomainToScalar(context, r, publicKey, msg);\n const RkA = R.add(A.multiplyUnsafe(k));\n // Check the cofactored verification equation via the curve cofactor h.\n // [h][S]B = [h]R + [h][k]A'\n return RkA.subtract(SB).clearCofactor().is0();\n }\n const _size = Fp.BYTES; // 32 for ed25519, 57 for ed448\n const lengths = {\n secretKey: _size,\n publicKey: _size,\n signature: 2 * _size,\n seed: _size,\n };\n function randomSecretKey(seed) {\n seed = seed === undefined ? randomBytes(lengths.seed) : seed;\n return abytes(seed, lengths.seed, 'seed');\n }\n function isValidSecretKey(key) {\n return isBytes(key) && key.length === lengths.secretKey;\n }\n function isValidPublicKey(key, zip215) {\n try {\n // Preserve the wrapper-selected default for omitted / `undefined` ZIP-215 flags here too.\n return !!Point.fromBytes(key, zip215 === undefined ? verifyOpts.zip215 : zip215);\n }\n catch (error) {\n return false;\n }\n }\n const utils = {\n getExtendedPublicKey,\n randomSecretKey,\n isValidSecretKey,\n isValidPublicKey,\n /** Converts an Edwards public key to a companion Montgomery public key. */\n toMontgomery(publicKey) {\n if (toMontgomery === undefined)\n throw new Error('Montgomery conversion is not supported for this curve');\n return toMontgomery(Point.fromBytes(publicKey));\n },\n toMontgomerySecret(secretKey) {\n if (toMontgomerySecret === undefined)\n throw new Error('Montgomery conversion is not supported for this curve');\n return toMontgomerySecret(secretKey);\n },\n };\n Object.freeze(lengths);\n Object.freeze(utils);\n return Object.freeze({\n keygen: createKeygen(randomSecretKey, getPublicKey),\n getPublicKey,\n sign,\n verify,\n utils,\n Point,\n lengths,\n });\n}\n","/**\n * ed25519 Twisted Edwards curve with following addons:\n * - X25519 ECDH\n * - Ristretto cofactor elimination\n * - Elligator hash-to-group / point indistinguishability\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport { sha512 } from '@noble/hashes/sha2.js';\nimport { abytes, concatBytes, hexToBytes } from '@noble/hashes/utils.js';\nimport {} from \"./abstract/curve.js\";\nimport { eddsa, edwards, PrimeEdwardsPoint, } from \"./abstract/edwards.js\";\nimport { createFROST } from \"./abstract/frost.js\";\nimport { _DST_scalar, createHasher, expand_message_xmd, } from \"./abstract/hash-to-curve.js\";\nimport { FpInvertBatch, FpSqrtEven, isNegativeLE, mod, pow2, } from \"./abstract/modular.js\";\nimport { montgomery } from \"./abstract/montgomery.js\";\nimport { createOPRF } from \"./abstract/oprf.js\";\nimport { asciiToBytes, bytesToNumberLE, equalBytes } from \"./utils.js\";\n// prettier-ignore\nconst _0n = /* @__PURE__ */ BigInt(0), _1n = /* @__PURE__ */ BigInt(1), _2n = /* @__PURE__ */ BigInt(2), _3n = /* @__PURE__ */ BigInt(3);\n// prettier-ignore\nconst _5n = /* @__PURE__ */ BigInt(5), _8n = /* @__PURE__ */ BigInt(8);\n// P = 2n**255n - 19n\nconst ed25519_CURVE_p = /* @__PURE__ */ BigInt('0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed');\n// N = 2n**252n + 27742317777372353535851937790883648493n\n// a = Fp.create(BigInt(-1))\n// d = -121665/121666 a.k.a. Fp.neg(121665 * Fp.inv(121666))\nconst ed25519_CURVE = /* @__PURE__ */ (() => ({\n p: ed25519_CURVE_p,\n n: BigInt('0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed'),\n h: _8n,\n a: BigInt('0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec'),\n d: BigInt('0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3'),\n Gx: BigInt('0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a'),\n Gy: BigInt('0x6666666666666666666666666666666666666666666666666666666666666658'),\n}))();\nfunction ed25519_pow_2_252_3(x) {\n // prettier-ignore\n const _10n = BigInt(10), _20n = BigInt(20), _40n = BigInt(40), _80n = BigInt(80);\n const P = ed25519_CURVE_p;\n const x2 = (x * x) % P;\n const b2 = (x2 * x) % P; // x^3, 11\n const b4 = (pow2(b2, _2n, P) * b2) % P; // x^15, 1111\n const b5 = (pow2(b4, _1n, P) * x) % P; // x^31\n const b10 = (pow2(b5, _5n, P) * b5) % P;\n const b20 = (pow2(b10, _10n, P) * b10) % P;\n const b40 = (pow2(b20, _20n, P) * b20) % P;\n const b80 = (pow2(b40, _40n, P) * b40) % P;\n const b160 = (pow2(b80, _80n, P) * b80) % P;\n const b240 = (pow2(b160, _80n, P) * b80) % P;\n const b250 = (pow2(b240, _10n, P) * b10) % P;\n const pow_p_5_8 = (pow2(b250, _2n, P) * x) % P;\n // ^ This is x^((p-5)/8); multiply by x once more to get x^((p+3)/8).\n return { pow_p_5_8, b2 };\n}\n// Mutates and returns the provided 32-byte buffer in place.\nfunction adjustScalarBytes(bytes) {\n // Section 5: For X25519, in order to decode 32 random bytes as an integer scalar,\n // set the three least significant bits of the first byte\n bytes[0] &= 248; // 0b1111_1000\n // and the most significant bit of the last to zero,\n bytes[31] &= 127; // 0b0111_1111\n // set the second most significant bit of the last byte to 1\n bytes[31] |= 64; // 0b0100_0000\n return bytes;\n}\n// √(-1) aka √(a) aka 2^((p-1)/4)\n// Fp.sqrt(Fp.neg(1))\nconst ED25519_SQRT_M1 = /* @__PURE__ */ BigInt('19681161376707505956807079304988542015446066515923890162744021073123829784752');\n// sqrt(u/v). Returns `{ isValid, value }`; on non-squares `value` is still a\n// dummy root-shaped field element so callers can stay constant-time.\nfunction uvRatio(u, v) {\n const P = ed25519_CURVE_p;\n const v3 = mod(v * v * v, P); // v³\n const v7 = mod(v3 * v3 * v, P); // v⁷\n // (p+3)/8 and (p-5)/8\n const pow = ed25519_pow_2_252_3(u * v7).pow_p_5_8;\n let x = mod(u * v3 * pow, P); // (uv³)(uv⁷)^(p-5)/8\n const vx2 = mod(v * x * x, P); // vx²\n const root1 = x; // First root candidate\n const root2 = mod(x * ED25519_SQRT_M1, P); // Second root candidate\n const useRoot1 = vx2 === u; // If vx² = u (mod p), x is a square root\n const useRoot2 = vx2 === mod(-u, P); // If vx² = -u, set x <-- x * 2^((p-1)/4)\n const noRoot = vx2 === mod(-u * ED25519_SQRT_M1, P); // There is no valid root, vx² = -u√(-1)\n if (useRoot1)\n x = root1;\n if (useRoot2 || noRoot)\n x = root2; // We return root2 anyway, for const-time\n if (isNegativeLE(x, P))\n x = mod(-x, P);\n return { isValid: useRoot1 || useRoot2, value: x };\n}\nconst ed25519_Point = /* @__PURE__ */ edwards(ed25519_CURVE, { uvRatio });\n// Public field alias stays stricter than the RFC 8032 Appendix A sample code:\n// `Fp.inv(0)` throws instead of returning `0`.\nconst Fp = /* @__PURE__ */ (() => ed25519_Point.Fp)();\nfunction toMontgomery(point) {\n // Birational map from Ed25519 to Curve25519 / X25519:\n // (u, v) = ((1 + y) / (1 - y), sqrt(-486664) * u / x)\n // (x, y) = (sqrt(-486664) * u / v, (u - 1) / (u + 1))\n const { y } = point;\n return Fp.toBytes(Fp.div(_1n + y, _1n - y));\n}\nfunction toMontgomerySecret(secretKey) {\n const size = ed25519_Point.Fp.BYTES;\n abytes(secretKey, size);\n return adjustScalarBytes(sha512(secretKey.subarray(0, size))).subarray(0, size);\n}\nconst Fn = /* @__PURE__ */ (() => ed25519_Point.Fn)();\n// RFC 8032 `dom2` helper for ctx/ph variants only. Plain Ed25519 keeps the\n// empty-domain path in `ed()` and would be wrong if routed through this helper.\nfunction ed25519_domain(data, ctx, phflag) {\n if (ctx.length > 255)\n throw new Error('Context is too big');\n return concatBytes(asciiToBytes('SigEd25519 no Ed25519 collisions'), new Uint8Array([phflag ? 1 : 0, ctx.length]), ctx, data);\n}\nfunction ed(opts) {\n // Ed25519 keeps ZIP-215 default verification semantics for consensus compatibility.\n return eddsa(ed25519_Point, sha512, Object.assign({ adjustScalarBytes, toMontgomery, toMontgomerySecret, zip215: true }, opts));\n}\n/**\n * ed25519 curve with EdDSA signatures.\n * Seeded `keygen(seed)` / `utils.randomSecretKey(seed)` reuse the provided\n * 32-byte seed buffer instead of copying it.\n * @example\n * Generate one Ed25519 keypair, sign a message, and verify it.\n *\n * ```js\n * import { ed25519 } from '@noble/curves/ed25519.js';\n * const { secretKey, publicKey } = ed25519.keygen();\n * // const publicKey = ed25519.getPublicKey(secretKey);\n * const msg = new TextEncoder().encode('hello noble');\n * const sig = ed25519.sign(msg, secretKey);\n * const isValid = ed25519.verify(sig, msg, publicKey); // ZIP215\n * // RFC8032 / FIPS 186-5\n * const isValid2 = ed25519.verify(sig, msg, publicKey, { zip215: false });\n * ```\n */\nexport const ed25519 = /* @__PURE__ */ ed({});\n/**\n * Context version of ed25519 (ctx for domain separation). See {@link ed25519}\n * Seeded `keygen(seed)` / `utils.randomSecretKey(seed)` reuse the provided\n * 32-byte seed buffer instead of copying it.\n * @example\n * Sign and verify with Ed25519ctx under one explicit context.\n *\n * ```ts\n * const context = new TextEncoder().encode('docs');\n * const { secretKey, publicKey } = ed25519ctx.keygen();\n * const msg = new TextEncoder().encode('hello noble');\n * const sig = ed25519ctx.sign(msg, secretKey, { context });\n * const isValid = ed25519ctx.verify(sig, msg, publicKey, { context });\n * ```\n */\nexport const ed25519ctx = /* @__PURE__ */ ed({ domain: ed25519_domain });\n/**\n * Prehashed version of ed25519. See {@link ed25519}\n * Seeded `keygen(seed)` / `utils.randomSecretKey(seed)` reuse the provided\n * 32-byte seed buffer instead of copying it.\n * @example\n * Use the prehashed Ed25519 variant for one message.\n *\n * ```ts\n * const { secretKey, publicKey } = ed25519ph.keygen();\n * const msg = new TextEncoder().encode('hello noble');\n * const sig = ed25519ph.sign(msg, secretKey);\n * const isValid = ed25519ph.verify(sig, msg, publicKey);\n * ```\n */\nexport const ed25519ph = /* @__PURE__ */ ed({ domain: ed25519_domain, prehash: sha512 });\n/**\n * FROST threshold signatures over ed25519. RFC 9591.\n * @example\n * Create one trusted-dealer package for 2-of-3 ed25519 signing.\n *\n * ```ts\n * const alice = ed25519_FROST.Identifier.derive('alice@example.com');\n * const bob = ed25519_FROST.Identifier.derive('bob@example.com');\n * const carol = ed25519_FROST.Identifier.derive('carol@example.com');\n * const deal = ed25519_FROST.trustedDealer({ min: 2, max: 3 }, [alice, bob, carol]);\n * ```\n */\nexport const ed25519_FROST = /* @__PURE__ */ (() => createFROST({\n name: 'FROST-ED25519-SHA512-v1',\n Point: ed25519_Point,\n validatePoint: (p) => {\n p.assertValidity();\n if (!p.isTorsionFree())\n throw new Error('bad point: not torsion-free');\n },\n hash: sha512,\n // RFC 9591 keeps H2 undecorated here for RFC 8032 compatibility. In createFROST(),\n // `H2: ''` becomes an empty DST prefix; the built-in hashToScalar fallback treats\n // that the same as omitted DST, even though custom hooks can still observe the empty bag.\n H2: '',\n}))();\n/**\n * ECDH using curve25519 aka x25519.\n * `getSharedSecret()` rejects low-order peer inputs by default, and seeded\n * `keygen(seed)` reuses the provided 32-byte seed buffer instead of copying it.\n * @example\n * Derive one shared secret between two X25519 peers.\n *\n * ```js\n * import { x25519 } from '@noble/curves/ed25519.js';\n * const alice = x25519.keygen();\n * const bob = x25519.keygen();\n * const alicePublic = x25519.getPublicKey(alice.secretKey);\n * const shared = x25519.getSharedSecret(alice.secretKey, bob.publicKey);\n * ```\n */\nexport const x25519 = /* @__PURE__ */ (() => {\n const P = ed25519_CURVE_p;\n const powPminus2 = (x) => {\n // x^(p-2) aka x^(2^255-21)\n const { pow_p_5_8, b2 } = ed25519_pow_2_252_3(x);\n return mod(pow2(pow_p_5_8, _3n, P) * b2, P);\n };\n return montgomery({\n P,\n type: 'x25519',\n powPminus2,\n adjustScalarBytes,\n // ~3x faster fixed-base: [k]B on the birationally-equivalent Edwards curve using cached\n // base tables, mapped back via u = (1+y)/(1-y) = (Z+Y)/(Z-Y) with one Fermat inversion.\n // Same construction as libsodium's crypto_scalarmult_curve25519_base.\n scalarMultBase: (k) => {\n // Clamped k (≈2^254) exceeds n, but B has prime order n, so [k]B == [k mod n]B.\n const kn = mod(k, ed25519_Point.Fn.ORDER);\n // k ≡ 0 (mod n): [k]B is the point at infinity, whose u is 0 in the x-only ladder;\n // returning 0 makes montgomery() reject it exactly like the ladder path.\n if (kn === _0n)\n return _0n;\n const p = ed25519_Point.BASE.multiply(kn);\n // Z-Y == 0 only at the identity, which kn != 0 excludes.\n return mod((p.Z + p.Y) * powPminus2(mod(p.Z - p.Y, P)), P);\n },\n });\n})();\n// Hash To Curve Elligator2 Map (NOTE: different from ristretto255 elligator)\n// RFC 9380 Appendix G.2.2 / Err4730 requires `sgn0(c1) = 0` for the Edwards\n// map constant below, so use the even root explicitly.\n// 1. c1 = (q + 3) / 8 # Integer arithmetic\nconst ELL2_C1 = /* @__PURE__ */ (() => (ed25519_CURVE_p + _3n) / _8n)();\nconst ELL2_C2 = /* @__PURE__ */ (() => Fp.pow(_2n, ELL2_C1))(); // 2. c2 = 2^c1\nconst ELL2_C3 = /* @__PURE__ */ (() => Fp.sqrt(Fp.neg(Fp.ONE)))(); // 3. c3 = sqrt(-1)\nconst ELL2_J = /* @__PURE__ */ BigInt(486662);\n/**\n * RFC 9380 method `map_to_curve_elligator2_curve25519`. Experimental name: may be renamed later.\n * @private\n */\n// prettier-ignore\nexport function _map_to_curve_elligator2_curve25519(u) {\n // 4. c4 = (q - 5) / 8: tv2^c4 below reuses the ed25519_pow_2_252_3 addition chain,\n // whose pow_p_5_8 output is exactly x^((p-5)/8).\n let tv1 = Fp.sqr(u); // 1. tv1 = u^2\n tv1 = Fp.mul(tv1, _2n); // 2. tv1 = 2 * tv1\n // 3. xd = tv1 + 1 # Nonzero: -1 is square (mod p), tv1 is not\n let xd = Fp.add(tv1, Fp.ONE);\n let x1n = Fp.neg(ELL2_J); // 4. x1n = -J # x1 = x1n / xd = -J / (1 + 2 * u^2)\n let tv2 = Fp.sqr(xd); // 5. tv2 = xd^2\n let gxd = Fp.mul(tv2, xd); // 6. gxd = tv2 * xd # gxd = xd^3\n let gx1 = Fp.mul(tv1, ELL2_J); // 7. gx1 = J * tv1 # x1n + J * xd\n gx1 = Fp.mul(gx1, x1n); // 8. gx1 = gx1 * x1n # x1n^2 + J * x1n * xd\n gx1 = Fp.add(gx1, tv2); // 9. gx1 = gx1 + tv2 # x1n^2 + J * x1n * xd + xd^2\n gx1 = Fp.mul(gx1, x1n); // 10. gx1 = gx1 * x1n # x1n^3 + J * x1n^2 * xd + x1n * xd^2\n let tv3 = Fp.sqr(gxd); // 11. tv3 = gxd^2\n tv2 = Fp.sqr(tv3); // 12. tv2 = tv3^2 # gxd^4\n tv3 = Fp.mul(tv3, gxd); // 13. tv3 = tv3 * gxd # gxd^3\n tv3 = Fp.mul(tv3, gx1); // 14. tv3 = tv3 * gx1 # gx1 * gxd^3\n tv2 = Fp.mul(tv2, tv3); // 15. tv2 = tv2 * tv3 # gx1 * gxd^7\n let y11 = ed25519_pow_2_252_3(tv2).pow_p_5_8; // 16. y11 = tv2^c4 # (gx1 * gxd^7)^((p - 5) / 8)\n y11 = Fp.mul(y11, tv3); // 17. y11 = y11 * tv3 # gx1*gxd^3*(gx1*gxd^7)^((p-5)/8)\n let y12 = Fp.mul(y11, ELL2_C3); // 18. y12 = y11 * c3\n tv2 = Fp.sqr(y11); // 19. tv2 = y11^2\n tv2 = Fp.mul(tv2, gxd); // 20. tv2 = tv2 * gxd\n let e1 = Fp.eql(tv2, gx1); // 21. e1 = tv2 == gx1\n // 22. y1 = CMOV(y12, y11, e1) # If g(x1) is square, this is its sqrt\n let y1 = Fp.cmov(y12, y11, e1);\n let x2n = Fp.mul(x1n, tv1); // 23. x2n = x1n * tv1 # x2 = x2n / xd = 2 * u^2 * x1n / xd\n let y21 = Fp.mul(y11, u); // 24. y21 = y11 * u\n y21 = Fp.mul(y21, ELL2_C2); // 25. y21 = y21 * c2\n let y22 = Fp.mul(y21, ELL2_C3); // 26. y22 = y21 * c3\n let gx2 = Fp.mul(gx1, tv1); // 27. gx2 = gx1 * tv1 # g(x2) = gx2 / gxd = 2 * u^2 * g(x1)\n tv2 = Fp.sqr(y21); // 28. tv2 = y21^2\n tv2 = Fp.mul(tv2, gxd); // 29. tv2 = tv2 * gxd\n let e2 = Fp.eql(tv2, gx2); // 30. e2 = tv2 == gx2\n // 31. y2 = CMOV(y22, y21, e2) # If g(x2) is square, this is its sqrt\n let y2 = Fp.cmov(y22, y21, e2);\n tv2 = Fp.sqr(y1); // 32. tv2 = y1^2\n tv2 = Fp.mul(tv2, gxd); // 33. tv2 = tv2 * gxd\n let e3 = Fp.eql(tv2, gx1); // 34. e3 = tv2 == gx1\n let xn = Fp.cmov(x2n, x1n, e3); // 35. xn = CMOV(x2n, x1n, e3) # If e3, x = x1, else x = x2\n let y = Fp.cmov(y2, y1, e3); // 36. y = CMOV(y2, y1, e3) # If e3, y = y1, else y = y2\n let e4 = Fp.isOdd(y); // 37. e4 = sgn0(y) == 1 # Fix sign of y\n y = Fp.cmov(y, Fp.neg(y), e3 !== e4); // 38. y = CMOV(y, -y, e3 XOR e4)\n return { xMn: xn, xMd: xd, yMn: y, yMd: _1n }; // 39. return (xn, xd, y, 1)\n}\n// sgn0(c1) MUST equal 0\nconst ELL2_C1_EDWARDS = /* @__PURE__ */ (() => FpSqrtEven(Fp, Fp.neg(BigInt(486664))))();\nfunction map_to_curve_elligator2_edwards25519(u) {\n // 1. (xMn, xMd, yMn, yMd) = map_to_curve_elligator2_curve25519(u)\n const { xMn, xMd, yMn, yMd } = _map_to_curve_elligator2_curve25519(u);\n // map_to_curve_elligator2_curve25519(u)\n let xn = Fp.mul(xMn, yMd); // 2. xn = xMn * yMd\n xn = Fp.mul(xn, ELL2_C1_EDWARDS); // 3. xn = xn * c1\n let xd = Fp.mul(xMd, yMn); // 4. xd = xMd * yMn # xn / xd = c1 * xM / yM\n let yn = Fp.sub(xMn, xMd); // 5. yn = xMn - xMd\n // 6. yd = xMn + xMd # (n / d - 1) / (n / d + 1) = (n - d) / (n + d)\n let yd = Fp.add(xMn, xMd);\n let tv1 = Fp.mul(xd, yd); // 7. tv1 = xd * yd\n let e = Fp.eql(tv1, Fp.ZERO); // 8. e = tv1 == 0\n xn = Fp.cmov(xn, Fp.ZERO, e); // 9. xn = CMOV(xn, 0, e)\n xd = Fp.cmov(xd, Fp.ONE, e); // 10. xd = CMOV(xd, 1, e)\n yn = Fp.cmov(yn, Fp.ONE, e); // 11. yn = CMOV(yn, 1, e)\n yd = Fp.cmov(yd, Fp.ONE, e); // 12. yd = CMOV(yd, 1, e)\n const [xd_inv, yd_inv] = FpInvertBatch(Fp, [xd, yd], true); // batch division\n // Noble normalizes the RFC rational representation to affine `{ x, y }`\n // before returning from the internal helper.\n return { x: Fp.mul(xn, xd_inv), y: Fp.mul(yn, yd_inv) }; // 13. return (xn, xd, yn, yd)\n}\n/**\n * Hashing to ed25519 points / field. RFC 9380 methods.\n * Public `mapToCurve()` returns the cofactor-cleared subgroup point; the\n * internal map callback below consumes one field element bigint, not `[bigint]`.\n * @example\n * Hash one message onto the ed25519 curve.\n *\n * ```ts\n * const point = ed25519_hasher.hashToCurve(new TextEncoder().encode('hello noble'));\n * ```\n */\nexport const ed25519_hasher = /* @__PURE__ */ (() => createHasher(ed25519_Point, (scalars) => map_to_curve_elligator2_edwards25519(scalars[0]), {\n DST: 'edwards25519_XMD:SHA-512_ELL2_RO_',\n encodeDST: 'edwards25519_XMD:SHA-512_ELL2_NU_',\n p: ed25519_CURVE_p,\n m: 1,\n k: 128,\n expand: 'xmd',\n hash: sha512,\n}))();\n// √(-1) aka √(a) aka 2^((p-1)/4)\nconst SQRT_M1 = ED25519_SQRT_M1;\n// √(ad - 1)\nconst SQRT_AD_MINUS_ONE = /* @__PURE__ */ BigInt('25063068953384623474111414158702152701244531502492656460079210482610430750235');\n// 1 / √(a-d)\nconst INVSQRT_A_MINUS_D = /* @__PURE__ */ BigInt('54469307008909316920995813868745141605393597292927456921205312896311721017578');\n// 1-d²\nconst ONE_MINUS_D_SQ = /* @__PURE__ */ BigInt('1159843021668779879193775521855586647937357759715417654439879720876111806838');\n// (d-1)²\nconst D_MINUS_ONE_SQ = /* @__PURE__ */ BigInt('40440834346308536858101042469323190826248399146238708352240133220865137265952');\n// `SQRT_RATIO_M1(1, number)` specialization. Returns `{ isValid, value }`,\n// where non-squares get the nonnegative `sqrt(SQRT_M1 / number)` branch.\nconst invertSqrt = (number) => uvRatio(_1n, number);\nconst MAX_255B = /* @__PURE__ */ BigInt('0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff');\n// RFC 9496 §4.3.4 MAP parser: masks bit 255 and reduces modulo p for element\n// derivation. The decode path has the opposite contract and rejects that bit.\nconst bytes255ToNumberLE = (bytes) => Fp.create(bytesToNumberLE(bytes) & MAX_255B);\n/**\n * Computes Elligator map for Ristretto255.\n * Primary formula source is RFC 9496 §4.3.4 MAP; RFC 9380 Appendix B builds\n * `hash_to_ristretto255` on top of this helper.\n * Returns an internal Edwards representative, not a public `_RistrettoPoint`.\n */\nfunction calcElligatorRistrettoMap(r0) {\n const { d } = ed25519_CURVE;\n const r = Fp.mul(Fp.mulN(SQRT_M1, r0), r0); // 1\n const Ns = Fp.mul(Fp.addN(r, _1n), ONE_MINUS_D_SQ); // 2\n let c = BigInt(-1); // 3\n const D = Fp.mul(Fp.subN(c, Fp.mulN(d, r)), Fp.add(r, d)); // 4\n let { isValid: Ns_D_is_sq, value: s } = uvRatio(Ns, D); // 5\n let s_ = Fp.mul(s, r0); // 6\n if (!Fp.isOdd(s_))\n s_ = Fp.neg(s_);\n if (!Ns_D_is_sq)\n s = s_; // 7\n if (!Ns_D_is_sq)\n c = r; // 8\n const Nt = Fp.sub(Fp.mulN(Fp.mulN(c, Fp.subN(r, _1n)), D_MINUS_ONE_SQ), D); // 9\n const s2 = Fp.sqrN(s);\n const W0 = Fp.mul(Fp.addN(s, s), D); // 10\n const W1 = Fp.mul(Nt, SQRT_AD_MINUS_ONE); // 11\n const W2 = Fp.sub(_1n, s2); // 12\n const W3 = Fp.add(_1n, s2); // 13\n return new ed25519_Point(Fp.mul(W0, W3), Fp.mul(W2, W1), Fp.mul(W1, W3), Fp.mul(W0, W2));\n}\n/**\n * Wrapper over Edwards Point for ristretto255.\n *\n * Each ed25519/EdwardsPoint has 8 different equivalent points. This can be\n * a source of bugs for protocols like ring signatures. Ristretto was created to solve this.\n * Ristretto point operates in X:Y:Z:T extended coordinates like EdwardsPoint,\n * but it should work in its own namespace: do not combine those two.\n * See [RFC9496](https://www.rfc-editor.org/rfc/rfc9496).\n */\nclass _RistrettoPoint extends PrimeEdwardsPoint {\n // Do NOT change syntax: the following gymnastics is done,\n // because typescript strips comments, which makes bundlers disable tree-shaking.\n // prettier-ignore\n static BASE = \n /* @__PURE__ */ (() => new _RistrettoPoint(ed25519_Point.BASE))();\n // prettier-ignore\n static ZERO = \n /* @__PURE__ */ (() => new _RistrettoPoint(ed25519_Point.ZERO))();\n // prettier-ignore\n static Fp = \n /* @__PURE__ */ (() => Fp)();\n // prettier-ignore\n static Fn = \n /* @__PURE__ */ (() => Fn)();\n constructor(ep) {\n super(ep);\n }\n /**\n * Create one Ristretto255 point from affine Edwards coordinates.\n * This wraps the internal Edwards representative directly and is not a\n * canonical ristretto255 decoding path.\n * Use `toBytes()` / `fromBytes()` if canonical ristretto255 bytes matter.\n */\n static fromAffine(ap) {\n return new _RistrettoPoint(ed25519_Point.fromAffine(ap));\n }\n assertSame(other) {\n if (!(other instanceof _RistrettoPoint))\n throw new Error('RistrettoPoint expected');\n }\n init(ep) {\n return new _RistrettoPoint(ep);\n }\n static fromBytes(bytes) {\n abytes(bytes, 32);\n const { a, d } = ed25519_CURVE;\n const s = bytes255ToNumberLE(bytes);\n // 1. Check that s_bytes is the canonical encoding of a field element, or else abort.\n // 3. Check that s is non-negative, or else abort\n if (!equalBytes(Fp.toBytes(s), bytes) || Fp.isOdd(s))\n throw new Error('invalid ristretto255 encoding 1');\n const s2 = Fp.sqr(s);\n const u1 = Fp.add(_1n, Fp.mulN(a, s2)); // 4 (a is -1)\n const u2 = Fp.sub(_1n, Fp.mulN(a, s2)); // 5\n const u1_2 = Fp.sqr(u1);\n const u2_2 = Fp.sqr(u2);\n const v = Fp.sub(Fp.mulN(Fp.mulN(a, d), u1_2), u2_2); // 6\n const { isValid, value: I } = invertSqrt(Fp.mul(v, u2_2)); // 7\n const Dx = Fp.mul(I, u2); // 8\n const Dy = Fp.mul(Fp.mulN(I, Dx), v); // 9\n let x = Fp.mul(Fp.addN(s, s), Dx); // 10\n if (Fp.isOdd(x))\n x = Fp.neg(x); // 10\n const y = Fp.mul(u1, Dy); // 11\n const t = Fp.mul(x, y); // 12\n if (!isValid || Fp.isOdd(t) || Fp.is0(y))\n throw new Error('invalid ristretto255 encoding 2');\n return new _RistrettoPoint(new ed25519_Point(x, y, Fp.ONE, t));\n }\n /**\n * Converts ristretto-encoded string to ristretto point.\n * Described in [RFC9496](https://www.rfc-editor.org/rfc/rfc9496#name-decode).\n * @param hex - Ristretto-encoded 32 bytes. Not every 32-byte string is valid ristretto encoding\n */\n static fromHex(hex) {\n return _RistrettoPoint.fromBytes(hexToBytes(hex));\n }\n /**\n * Encodes ristretto point to Uint8Array.\n * Described in [RFC9496](https://www.rfc-editor.org/rfc/rfc9496#name-encode).\n */\n toBytes() {\n let { X, Y, Z, T } = this.ep;\n const u1 = Fp.mul(Fp.add(Z, Y), Fp.sub(Z, Y)); // 1\n const u2 = Fp.mul(X, Y); // 2\n // Square root always exists\n const u2sq = Fp.sqr(u2);\n const { value: invsqrt } = invertSqrt(Fp.mul(u1, u2sq)); // 3\n const D1 = Fp.mul(invsqrt, u1); // 4\n const D2 = Fp.mul(invsqrt, u2); // 5\n const zInv = Fp.mul(Fp.mulN(D1, D2), T); // 6\n let D; // 7\n if (Fp.isOdd(Fp.mul(T, zInv))) {\n let _x = Fp.mul(Y, SQRT_M1);\n let _y = Fp.mul(X, SQRT_M1);\n X = _x;\n Y = _y;\n D = Fp.mul(D1, INVSQRT_A_MINUS_D);\n }\n else {\n D = D2; // 8\n }\n if (Fp.isOdd(Fp.mul(X, zInv)))\n Y = Fp.neg(Y); // 9\n let s = Fp.mul(Fp.subN(Z, Y), D); // 10 (check footer's note, no sqrt(-a))\n if (Fp.isOdd(s))\n s = Fp.neg(s);\n return Fp.toBytes(s); // 11\n }\n /**\n * Compares two Ristretto points.\n * Described in [RFC9496](https://www.rfc-editor.org/rfc/rfc9496#name-equals).\n */\n equals(other) {\n this.assertSame(other);\n const { X: X1, Y: Y1 } = this.ep;\n const { X: X2, Y: Y2 } = other.ep;\n // (x1 * y2 == y1 * x2) | (y1 * y2 == x1 * x2)\n const one = Fp.eql(Fp.mul(X1, Y2), Fp.mul(Y1, X2));\n const two = Fp.eql(Fp.mul(Y1, Y2), Fp.mul(X1, X2));\n return one || two;\n }\n is0() {\n return this.equals(_RistrettoPoint.ZERO);\n }\n}\n/** Prime-order Ristretto255 group bundle. */\nexport const ristretto255 = /* @__PURE__ */ (() => {\n Object.freeze(_RistrettoPoint.BASE);\n Object.freeze(_RistrettoPoint.ZERO);\n Object.freeze(_RistrettoPoint.prototype);\n Object.freeze(_RistrettoPoint);\n return Object.freeze({ Point: _RistrettoPoint });\n})();\n/**\n * Hashing to ristretto255 points / field. RFC 9380 methods.\n * `hashToCurve()` is RFC 9380 Appendix B, `deriveToCurve()` is the RFC 9496\n * §4.3.4 element-derivation building block, and `hashToScalar()` is a\n * library-specific helper for OPRF-style use.\n * @example\n * Hash one message onto ristretto255.\n *\n * ```ts\n * const point = ristretto255_hasher.hashToCurve(new TextEncoder().encode('hello noble'));\n * ```\n */\nexport const ristretto255_hasher = \n/* @__PURE__ */ Object.freeze({\n Point: _RistrettoPoint,\n /**\n * Spec: https://www.rfc-editor.org/rfc/rfc9380.html#name-hashing-to-ristretto255. Caveats:\n * * There are no test vectors\n * * encodeToCurve / mapToCurve is undefined\n * * mapToCurve would be `calcElligatorRistrettoMap(scalars[0])`, not ristretto255_map!\n * * hashToScalar is undefined too, so we just use OPRF implementation\n * * We cannot re-use 'createHasher', because ristretto255_map is different algorithm/RFC\n (os2ip -> bytes255ToNumberLE)\n * * mapToCurve == calcElligatorRistrettoMap, hashToCurve == ristretto255_map\n * * hashToScalar is undefined in RFC9380 for ristretto, so we use the OPRF\n version here. Using `bytes255ToNumblerLE` will create a different result\n if we use `bytes255ToNumberLE` as os2ip\n * * current version is closest to spec.\n */\n hashToCurve(msg, options) {\n // == 'hash_to_ristretto255'\n // Preserve explicit empty/invalid DST overrides so expand_message_xmd() can reject them.\n const DST = options?.DST === undefined ? 'ristretto255_XMD:SHA-512_R255MAP_RO_' : options.DST;\n const xmd = expand_message_xmd(msg, DST, 64, sha512);\n // NOTE: RFC 9380 incorrectly calls this function `ristretto255_map`.\n // In RFC 9496, `map` was the per-point function inside the construction.\n // That also led to confusion that `ristretto255_map` is `mapToCurve`.\n // It is not: it is the older hash-to-curve construction.\n return ristretto255_hasher.deriveToCurve(xmd);\n },\n hashToScalar(msg, options) {\n const DST = options?.DST === undefined ? _DST_scalar : options.DST;\n const xmd = expand_message_xmd(msg, DST, 64, sha512);\n return Fn.create(bytesToNumberLE(xmd));\n },\n /**\n * HashToCurve-like construction based on RFC 9496 (Element Derivation).\n * Converts 64 uniform random bytes into a curve point.\n *\n * WARNING: This represents an older hash-to-curve construction from before\n * RFC 9380 was finalized.\n * It was later reused as a component in the newer\n * `hash_to_ristretto255` function defined in RFC 9380.\n */\n deriveToCurve(bytes) {\n // https://www.rfc-editor.org/rfc/rfc9496.html#name-element-derivation\n abytes(bytes, 64);\n const r1 = bytes255ToNumberLE(bytes.subarray(0, 32));\n const R1 = calcElligatorRistrettoMap(r1);\n const r2 = bytes255ToNumberLE(bytes.subarray(32, 64));\n const R2 = calcElligatorRistrettoMap(r2);\n return new _RistrettoPoint(R1.add(R2));\n },\n});\n/**\n * ristretto255 OPRF/VOPRF/POPRF bundle, defined in RFC 9497.\n * @example\n * Run one blind/evaluate/finalize OPRF round over ristretto255.\n *\n * ```ts\n * const input = new TextEncoder().encode('hello noble');\n * const keys = ristretto255_oprf.oprf.generateKeyPair();\n * const blind = ristretto255_oprf.oprf.blind(input);\n * const evaluated = ristretto255_oprf.oprf.blindEvaluate(keys.secretKey, blind.blinded);\n * const output = ristretto255_oprf.oprf.finalize(input, blind.blind, evaluated);\n * ```\n */\nexport const ristretto255_oprf = /* @__PURE__ */ (() => createOPRF({\n name: 'ristretto255-SHA512',\n Point: _RistrettoPoint,\n hash: sha512,\n hashToGroup: ristretto255_hasher.hashToCurve,\n hashToScalar: ristretto255_hasher.hashToScalar,\n}))();\n/**\n * FROST threshold signatures over ristretto255. RFC 9591.\n * @example\n * Create one trusted-dealer package for 2-of-3 ristretto255 signing.\n *\n * ```ts\n * const alice = ristretto255_FROST.Identifier.derive('alice@example.com');\n * const bob = ristretto255_FROST.Identifier.derive('bob@example.com');\n * const carol = ristretto255_FROST.Identifier.derive('carol@example.com');\n * const deal = ristretto255_FROST.trustedDealer({ min: 2, max: 3 }, [alice, bob, carol]);\n * ```\n */\nexport const ristretto255_FROST = /* @__PURE__ */ (() => createFROST({\n name: 'FROST-RISTRETTO255-SHA512-v1',\n Point: _RistrettoPoint,\n validatePoint: (p) => {\n // Prime-order wrappers are torsion-free at the abstract-group level.\n p.assertValidity();\n },\n hash: sha512,\n}))();\n/**\n * Weird / bogus points, useful for debugging.\n * All 8 ed25519 points of 8-torsion subgroup can be generated from the point\n * T = `26e8958fc2b227b045c3f489f2ef98f0d5dfac05d3c63339b13802886d53fc05`.\n * The subgroup generated by `T` is `{ O, T, 2T, 3T, 4T, 5T, 6T, 7T }`; the\n * array below is that set, not the powers in that exact index order.\n * @example\n * Decode one known torsion point for debugging.\n *\n * ```ts\n * import { ED25519_TORSION_SUBGROUP, ed25519 } from '@noble/curves/ed25519.js';\n * const point = ed25519.Point.fromHex(ED25519_TORSION_SUBGROUP[1]);\n * ```\n */\nexport const ED25519_TORSION_SUBGROUP = /* @__PURE__ */ Object.freeze([\n '0100000000000000000000000000000000000000000000000000000000000000',\n 'c7176a703d4dd84fba3c0b760d10670f2a2053fa2c39ccc64ec7fd7792ac037a',\n '0000000000000000000000000000000000000000000000000000000000000080',\n '26e8958fc2b227b045c3f489f2ef98f0d5dfac05d3c63339b13802886d53fc05',\n 'ecffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff7f',\n '26e8958fc2b227b045c3f489f2ef98f0d5dfac05d3c63339b13802886d53fc85',\n '0000000000000000000000000000000000000000000000000000000000000000',\n 'c7176a703d4dd84fba3c0b760d10670f2a2053fa2c39ccc64ec7fd7792ac03fa',\n]);\n"],"ignoreList":[0,1],"mappings":";;;;;;;;;AAYA,MAAM,MAAsB,uBAAO,CAAC;AAAGA,MAAAA,QAAsB,uBAAO,CAAC;AAAGC,MAAAA,QAAsB,uBAAO,CAAC;AAAG,MAAA,MAAsB,uBAAO,CAAC;AAAGC,MAAAA,QAAsB,uBAAO,CAAC;AAGxK,SAAS,YAAY,IAAI,OAAO,GAAG,GAAG;CAClC,MAAM,KAAK,GAAG,I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CAAC,GACjB,IAAI,IAAI,CAAC,GAAG,CAAC;CACjB,OAAO;EAAE,SAAS,YAAY;EAAU,OAAO;CAAE;AACrD;AACA,MAAM,gBAAgC,wBAAQ,eAAe,EAAE,QAAQ,CAAC;AAGxE,MAAM,KAAqB,uBAAO,cAAc,GAAA,CAAI;AACpD,SAAS,aAAa,OAAO;CAIzB,MAAM,EAAE,MAAM;CACd,OAAO,GAAG,QAAQ,GAAG,IAAI,MAAM,GAAG,MAAM,CAAC,CAAC;AAC9C;AACA,SAAS,mBAAmB,WAAW;CACnC,MAAM,OAAO,cAAc,GAAG;CAC9B,SAAO,WAAW,IAAI;CACtB,OAAO,kBAAkB,OAAO,UAAU,SAAS,GAAG,IAAI,CAAC,CAAC,CAAC,CAAC,SAAS,GAAG,IAAI;AAClF;AASA,SAAS,GAAG,MAAM;CAEd,OAAO,MAAM,eAAe,QAAQ,OAAO,OAAO;EAAE;EAAmB;EAAc;EAAoB,QAAQ;CAAK,GAAG,IAAI,CAAC;AAClI;;;;;;;;;;;;;;;;;;;AAmBA,MAAa,UAA0B,mBAAG,CAAC,CAAC"}
@@ -0,0 +1,10 @@
1
+ import { EvmTransaction } from "./index.mjs";
2
+ //#region src/evm/sign.d.ts
3
+ /** Signs a normalized transaction; returns the serialized signed envelope. */
4
+ export declare const signEvmTransaction: (tx: EvmTransaction, privateKey: Uint8Array) => Uint8Array;
5
+ /** EIP-191 personal_sign; returns the 65-byte signature r‖s‖v with v∈{27,28}. */
6
+ export declare const signEvmPersonalMessage: (message: Uint8Array, privateKey: Uint8Array) => Uint8Array;
7
+ /** EIP-712 typed data; returns the 65-byte signature r‖s‖v with v∈{27,28}. */
8
+ export declare const signEvmTypedData: (typedData: string, privateKey: Uint8Array) => Uint8Array;
9
+ //#endregion
10
+ //# sourceMappingURL=evm-sign.d.mts.map
@@ -0,0 +1,94 @@
1
+ import { ChainError } from "./index.mjs";
2
+ import { t as parseTypedData } from "./typed-data-D28VBOIm.mjs";
3
+ import * as TypedData from "ox/TypedData";
4
+ import * as Hex from "ox/Hex";
5
+ import * as PersonalMessage from "ox/PersonalMessage";
6
+ import * as Secp256k1 from "ox/Secp256k1";
7
+ import * as Signature from "ox/Signature";
8
+ import * as TxEnvelopeEip1559 from "ox/TxEnvelopeEip1559";
9
+ import * as TxEnvelopeEip2930 from "ox/TxEnvelopeEip2930";
10
+ import * as TxEnvelopeLegacy from "ox/TxEnvelopeLegacy";
11
+ //#region src/evm/sign.ts
12
+ /**
13
+ * /evm/sign — deterministic (RFC 6979) ECDSA signing over the chain's canonical payloads. Inputs
14
+ * must already be normalized: the kernel calls `normalizeEvm` first and rejects on a ChainError. No
15
+ * key caching; the caller wipes key bytes.
16
+ */
17
+ /** Validates a string is `0x`-hex and narrows it for ox's branded type. */
18
+ function assertHex(value, field) {
19
+ if (!/^0x(?:[0-9a-fA-F]{2})*$/.test(value)) throw new ChainError("invalid-quantity", `${field} must be 0x-prefixed bytes`);
20
+ }
21
+ const hex = (value, field) => {
22
+ assertHex(value, field);
23
+ return value;
24
+ };
25
+ const key = (privateKey) => {
26
+ if (privateKey.length !== 32) throw new ChainError("invalid-request", "private key must be 32 bytes");
27
+ return Hex.fromBytes(privateKey);
28
+ };
29
+ const accessEntry = (entry) => ({
30
+ address: hex(entry.address, "accessList.address"),
31
+ storageKeys: entry.storageKeys.map((k) => hex(k, "accessList.storageKeys"))
32
+ });
33
+ const sign = (payload, privateKey) => Secp256k1.sign({
34
+ payload,
35
+ privateKey,
36
+ as: "Object"
37
+ });
38
+ /** Signs a normalized transaction; returns the serialized signed envelope. */
39
+ const signEvmTransaction = (tx, privateKey) => {
40
+ const privateKeyHex = key(privateKey);
41
+ const base = {
42
+ chainId: tx.chainId,
43
+ to: tx.to === void 0 ? void 0 : hex(tx.to, "to"),
44
+ data: hex(tx.data, "data"),
45
+ value: BigInt(tx.value),
46
+ nonce: BigInt(tx.nonce),
47
+ gas: BigInt(tx.gas)
48
+ };
49
+ if (tx.type === "legacy") {
50
+ const envelope = {
51
+ ...base,
52
+ type: "legacy",
53
+ gasPrice: BigInt(tx.gasPrice)
54
+ };
55
+ const signature = sign(TxEnvelopeLegacy.getSignPayload(envelope), privateKeyHex);
56
+ return Hex.toBytes(TxEnvelopeLegacy.serialize(envelope, { signature }));
57
+ }
58
+ if (tx.type === "eip2930") {
59
+ const envelope = {
60
+ ...base,
61
+ type: "eip2930",
62
+ gasPrice: BigInt(tx.gasPrice),
63
+ accessList: tx.accessList.map(accessEntry)
64
+ };
65
+ const signature = sign(TxEnvelopeEip2930.getSignPayload(envelope), privateKeyHex);
66
+ return Hex.toBytes(TxEnvelopeEip2930.serialize(envelope, { signature }));
67
+ }
68
+ const envelope = {
69
+ ...base,
70
+ type: "eip1559",
71
+ accessList: tx.accessList.map(accessEntry),
72
+ maxFeePerGas: BigInt(tx.maxFeePerGas),
73
+ maxPriorityFeePerGas: BigInt(tx.maxPriorityFeePerGas)
74
+ };
75
+ const signature = sign(TxEnvelopeEip1559.getSignPayload(envelope), privateKeyHex);
76
+ return Hex.toBytes(TxEnvelopeEip1559.serialize(envelope, { signature }));
77
+ };
78
+ /** 65-byte r‖s‖v; `Signature.toBytes` emits v = 27 + yParity already. */
79
+ const rs_v = (signature) => Signature.toBytes(signature);
80
+ /** EIP-191 personal_sign; returns the 65-byte signature r‖s‖v with v∈{27,28}. */
81
+ const signEvmPersonalMessage = (message, privateKey) => {
82
+ const payload = PersonalMessage.getSignPayload(Hex.fromBytes(message));
83
+ return rs_v(Signature.from(sign(payload, key(privateKey))));
84
+ };
85
+ /** EIP-712 typed data; returns the 65-byte signature r‖s‖v with v∈{27,28}. */
86
+ const signEvmTypedData = (typedData, privateKey) => {
87
+ const { json } = parseTypedData(typedData, "eip155:1");
88
+ const payload = TypedData.getSignPayload(json);
89
+ return rs_v(Signature.from(sign(payload, key(privateKey))));
90
+ };
91
+ //#endregion
92
+ export { signEvmPersonalMessage, signEvmTransaction, signEvmTypedData };
93
+
94
+ //# sourceMappingURL=evm-sign.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"evm-sign.mjs","names":[],"sources":["../src/evm/sign.ts"],"sourcesContent":["/**\n * /evm/sign — deterministic (RFC 6979) ECDSA signing over the chain's canonical payloads. Inputs\n * must already be normalized: the kernel calls `normalizeEvm` first and rejects on a ChainError. No\n * key caching; the caller wipes key bytes.\n */\nimport * as Hex from \"ox/Hex\";\nimport * as PersonalMessage from \"ox/PersonalMessage\";\nimport * as Secp256k1 from \"ox/Secp256k1\";\nimport * as Signature from \"ox/Signature\";\nimport * as TxEnvelopeEip1559 from \"ox/TxEnvelopeEip1559\";\nimport * as TxEnvelopeEip2930 from \"ox/TxEnvelopeEip2930\";\nimport * as TxEnvelopeLegacy from \"ox/TxEnvelopeLegacy\";\nimport * as TypedData from \"ox/TypedData\";\n\nimport { ChainError } from \"../index.ts\";\nimport type { EvmAccessListEntry, EvmTransaction } from \"../index.ts\";\nimport { parseTypedData } from \"./typed-data.ts\";\n\n/** Validates a string is `0x`-hex and narrows it for ox's branded type. */\nfunction assertHex(value: string, field: string): asserts value is `0x${string}` {\n if (!/^0x(?:[0-9a-fA-F]{2})*$/.test(value)) {\n throw new ChainError(\"invalid-quantity\", `${field} must be 0x-prefixed bytes`);\n }\n}\n\nconst hex = (value: string, field: string): `0x${string}` => {\n assertHex(value, field);\n return value;\n};\n\nconst key = (privateKey: Uint8Array): `0x${string}` => {\n if (privateKey.length !== 32) {\n throw new ChainError(\"invalid-request\", \"private key must be 32 bytes\");\n }\n return Hex.fromBytes(privateKey);\n};\n\nconst accessEntry = (entry: EvmAccessListEntry) => ({\n address: hex(entry.address, \"accessList.address\"),\n storageKeys: entry.storageKeys.map((k) => hex(k, \"accessList.storageKeys\")),\n});\n\nconst sign = (payload: `0x${string}`, privateKey: `0x${string}`) =>\n Secp256k1.sign({ payload, privateKey, as: \"Object\" as const });\n\n/** Signs a normalized transaction; returns the serialized signed envelope. */\nexport const signEvmTransaction = (tx: EvmTransaction, privateKey: Uint8Array): Uint8Array => {\n const privateKeyHex = key(privateKey);\n const base = {\n chainId: tx.chainId,\n to: tx.to === undefined ? undefined : hex(tx.to, \"to\"),\n data: hex(tx.data, \"data\"),\n value: BigInt(tx.value),\n nonce: BigInt(tx.nonce),\n gas: BigInt(tx.gas),\n };\n if (tx.type === \"legacy\") {\n const envelope = { ...base, type: \"legacy\" as const, gasPrice: BigInt(tx.gasPrice) };\n const signature = sign(TxEnvelopeLegacy.getSignPayload(envelope), privateKeyHex);\n return Hex.toBytes(TxEnvelopeLegacy.serialize(envelope, { signature }));\n }\n if (tx.type === \"eip2930\") {\n const envelope = {\n ...base,\n type: \"eip2930\" as const,\n gasPrice: BigInt(tx.gasPrice),\n accessList: tx.accessList.map(accessEntry),\n };\n const signature = sign(TxEnvelopeEip2930.getSignPayload(envelope), privateKeyHex);\n return Hex.toBytes(TxEnvelopeEip2930.serialize(envelope, { signature }));\n }\n const envelope = {\n ...base,\n type: \"eip1559\" as const,\n accessList: tx.accessList.map(accessEntry),\n maxFeePerGas: BigInt(tx.maxFeePerGas),\n maxPriorityFeePerGas: BigInt(tx.maxPriorityFeePerGas),\n };\n const signature = sign(TxEnvelopeEip1559.getSignPayload(envelope), privateKeyHex);\n return Hex.toBytes(TxEnvelopeEip1559.serialize(envelope, { signature }));\n};\n\n/** 65-byte r‖s‖v; `Signature.toBytes` emits v = 27 + yParity already. */\nconst rs_v = (signature: Signature.Signature): Uint8Array => Signature.toBytes(signature);\n\n/** EIP-191 personal_sign; returns the 65-byte signature r‖s‖v with v∈{27,28}. */\nexport const signEvmPersonalMessage = (message: Uint8Array, privateKey: Uint8Array): Uint8Array => {\n const payload = PersonalMessage.getSignPayload(Hex.fromBytes(message));\n return rs_v(Signature.from(sign(payload, key(privateKey))));\n};\n\n/** EIP-712 typed data; returns the 65-byte signature r‖s‖v with v∈{27,28}. */\nexport const signEvmTypedData = (typedData: string, privateKey: Uint8Array): Uint8Array => {\n const { json } = parseTypedData(typedData, \"eip155:1\");\n const payload = TypedData.getS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AAG;GACH,MAAM;GACN,UAAU,OAAO,GAAG,QAAQ;GAC5B,YAAY,GAAG,WAAW,IAAI,WAAW;EAC3C;EACA,MAAM,YAAY,KAAK,kBAAkB,eAAe,QAAQ,GAAG,aAAa;EAChF,OAAO,IAAI,QAAQ,kBAAkB,UAAU,UAAU,EAAE,UAAU,CAAC,CAAC;CACzE;CACA,MAAM,WAAW;EACf,GAAG;EACH,MAAM;EACN,YAAY,GAAG,WAAW,IAAI,WAAW;EACzC,cAAc,OAAO,GAAG,YAAY;EACpC,sBAAsB,OAAO,GAAG,oBAAoB;CACtD;CACA,MAAM,YAAY,KAAK,kBAAkB,eAAe,QAAQ,GAAG,aAAa;CAChF,OAAO,IAAI,QAAQ,kBAAkB,UAAU,UAAU,EAAE,UAAU,CAAC,CAAC;AACzE;;AAGA,MAAM,QAAQ,cAA+C,UAAU,QAAQ,SAAS;;AAGxF,MAAa,0BAA0B,SAAqB,eAAuC;CACjG,MAAM,UAAU,gBAAgB,eAAe,IAAI,UAAU,OAAO,CAAC;CACrE,OAAO,KAAK,UAAU,KAAK,KAAK,SAAS,IAAI,UAAU,CAAC,CAAC,CAAC;AAC5D;;AAGA,MAAa,oBAAoB,WAAmB,eAAuC;CACzF,MAAM,EAAE,SAAS,eAAe,WAAW,UAAU;CACrD,MAAM,UAAU,UAAU,eAAe,IAAI;CAC7C,OAAO,KAAK,UAAU,KAAK,KAAK,SAAS,IAAI,UAAU,CAAC,CAAC,CAAC;AAC5D"}
package/dist/evm.d.mts ADDED
@@ -0,0 +1,88 @@
1
+ import { DisplayIntent, EvmTransaction, SignRequest, Verifiability } from "./index.mjs";
2
+ //#region src/evm/address.d.ts
3
+ /** EIP-55 checksummed address, e.g. `0x52908400098527886E0F7030069857D2E4169EE7`. */
4
+ export declare const isEvmAddress: (value: string) => boolean;
5
+ export declare function checksumEvmAddress(address: string): string;
6
+ /** `keccak256(pubkey)[12:]` — accepts a 33-byte compressed or 65-byte uncompressed secp256k1 key. */
7
+ export declare function evmAddressFromPublicKey(pubkey: Uint8Array): string;
8
+ //#endregion
9
+ //#region src/evm/transaction.d.ts
10
+ export declare const isCanonicalHex: (value: string) => boolean;
11
+ export declare const canonicalHex: (value: bigint) => string;
12
+ /** The EIP-155 part of a CAIP-2 `network` string, e.g. `eip155:1` → 1. */
13
+ export declare const networkChainId: (network: string) => number;
14
+ /**
15
+ * Canonicalizes an EVM transaction: exact key sets per type, all required fields present, `0x`
16
+ * canonical quantities, EIP-55 addresses. Idempotent.
17
+ */
18
+ export declare const normalizeEvmTransaction: (tx: unknown) => EvmTransaction;
19
+ //#endregion
20
+ //#region src/evm/tokens.d.ts
21
+ /**
22
+ * Built-in ERC-20 token table, keyed by `chainId` then checksummed address. Intentionally EMPTY in
23
+ * this layer — real entries need official-source review (C6). Tests exercise the `full` ERC-20 path
24
+ * through `evmTokenTable`, which is exported for the kernel/test callers only via the `/evm` entry
25
+ * point.
26
+ */
27
+ type EvmToken = {
28
+ readonly symbol: string;
29
+ readonly decimals: number;
30
+ readonly name?: string;
31
+ };
32
+ type EvmTokenTable = Readonly<Record<string, Readonly<Record<string, EvmToken>>>>;
33
+ /** The built-in table — empty until official-source review lands the entries. */
34
+ export declare const evmTokenTable: EvmTokenTable;
35
+ export declare const lookupEvmToken: (table: EvmTokenTable, chainId: number, address: string) => EvmToken | undefined;
36
+ //#endregion
37
+ //#region src/evm/decode.d.ts
38
+ /** What the signer can guarantee about this request (WD-065). */
39
+ export declare const verifiabilityEvm: (request: SignRequest) => Verifiability;
40
+ /**
41
+ * Decodes a normalized request into a DisplayIntent. The token table parameter is for tests;
42
+ * production callers use the built-in table.
43
+ */
44
+ export declare const decodeEvm: (request: SignRequest, table?: EvmTokenTable) => DisplayIntent;
45
+ //#endregion
46
+ //#region src/evm/recover.d.ts
47
+ /**
48
+ * The EIP-55 address that produced `result` for `request` — a `chain.sign` round-trip check
49
+ * (`{kind:"evm.transaction",signedTransaction}` | `{kind,signature}`).
50
+ */
51
+ export declare const recoverEvmSigner: (request: Extract<SignRequest, {
52
+ network: string;
53
+ }>, result: {
54
+ readonly signedTransaction?: Uint8Array;
55
+ readonly signature?: Uint8Array;
56
+ }) => string;
57
+ //#endregion
58
+ //#region src/evm/typed-data.d.ts
59
+ type TypedDataField = {
60
+ readonly name: string;
61
+ readonly type: string;
62
+ };
63
+ /**
64
+ * The subset of the EIP-712 document the wallet needs to see before handing it to ox's validator —
65
+ * object with `types`, `primaryType`, `domain` and `message` of the right shapes.
66
+ */
67
+ type TypedDataInput = {
68
+ readonly types: Record<string, ReadonlyArray<TypedDataField>>;
69
+ readonly primaryType: string;
70
+ readonly domain: Record<string, unknown>;
71
+ readonly message: Record<string, unknown>;
72
+ };
73
+ type ParsedTypedData = {
74
+ readonly json: TypedDataInput;
75
+ /**
76
+ * True when `domain.chainId` disagrees with the request's network — the intent is still signable
77
+ * but renders `opaque` with a warning.
78
+ */
79
+ readonly chainIdMismatch: boolean;
80
+ };
81
+ /** Parses the EIP-712 JSON source and validates its shape with ox. */
82
+ export declare const parseTypedData: (typedData: string, network: string) => ParsedTypedData;
83
+ //#endregion
84
+ //#region src/evm/index.d.ts
85
+ export declare const normalizeEvm: (request: unknown) => SignRequest;
86
+ //#endregion
87
+ export type { EvmToken, EvmTokenTable };
88
+ //# sourceMappingURL=evm.d.mts.map