Socket
Socket
Sign inDemoInstall

@noble/curves

Package Overview
Dependencies
Maintainers
1
Versions
34
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@noble/curves - npm Package Compare versions

Comparing version 0.7.3 to 0.8.0

21

_shortw_utils.js

@@ -1,22 +0,17 @@

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.createCurve = exports.getHash = void 0;
/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
const hmac_1 = require("@noble/hashes/hmac");
const utils_1 = require("@noble/hashes/utils");
const weierstrass_js_1 = require("./abstract/weierstrass.js");
import { hmac } from '@noble/hashes/hmac';
import { concatBytes, randomBytes } from '@noble/hashes/utils';
import { weierstrass } from './abstract/weierstrass.js';
// connects noble-curves to noble-hashes
function getHash(hash) {
export function getHash(hash) {
return {
hash,
hmac: (key, ...msgs) => (0, hmac_1.hmac)(hash, key, (0, utils_1.concatBytes)(...msgs)),
randomBytes: utils_1.randomBytes,
hmac: (key, ...msgs) => hmac(hash, key, concatBytes(...msgs)),
randomBytes,
};
}
exports.getHash = getHash;
function createCurve(curveDef, defHash) {
const create = (hash) => (0, weierstrass_js_1.weierstrass)({ ...curveDef, ...getHash(hash) });
export function createCurve(curveDef, defHash) {
const create = (hash) => weierstrass({ ...curveDef, ...getHash(hash) });
return Object.freeze({ ...create(defHash), create });
}
exports.createCurve = createCurve;
//# sourceMappingURL=_shortw_utils.js.map

@@ -1,12 +0,9 @@

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.bls = void 0;
const modular_js_1 = require("./modular.js");
const utils_js_1 = require("./utils.js");
const htf = require("./hash-to-curve.js");
const weierstrass_js_1 = require("./weierstrass.js");
function bls(CURVE) {
import { hashToPrivateScalar } from './modular.js';
import { bitLen, bitGet, ensureBytes } from './utils.js';
import * as htf from './hash-to-curve.js';
import { weierstrassPoints, } from './weierstrass.js';
export function bls(CURVE) {
// Fields looks pretty specific for curve, so for now we need to pass them with opts
const { Fp, Fr, Fp2, Fp6, Fp12 } = CURVE;
const BLS_X_LEN = (0, utils_js_1.bitLen)(CURVE.x);
const BLS_X_LEN = bitLen(CURVE.x);
const groupLen = 32; // TODO: calculate; hardcoded for now

@@ -37,3 +34,3 @@ // Pre-compute coefficients for sparse multiplication

Rz = Fp2.mul(t0, t4); // T0 * T4
if ((0, utils_js_1.bitGet)(CURVE.x, i)) {
if (bitGet(CURVE.x, i)) {
// Addition

@@ -66,3 +63,3 @@ let t0 = Fp2.sub(Ry, Fp2.mul(Qy, Rz)); // Ry - Qy * Rz

f12 = Fp12.multiplyBy014(f12, E[0], Fp2.mul(E[1], Px), Fp2.mul(E[2], Py));
if ((0, utils_js_1.bitGet)(x, i)) {
if (bitGet(x, i)) {
j += 1;

@@ -79,7 +76,7 @@ const F = ell[j];

randomPrivateKey: () => {
return Fr.toBytes((0, modular_js_1.hashToPrivateScalar)(CURVE.randomBytes(groupLen + 8), CURVE.r));
return Fr.toBytes(hashToPrivateScalar(CURVE.randomBytes(groupLen + 8), CURVE.r));
},
};
// Point on G1 curve: (x, y)
const G1_ = (0, weierstrass_js_1.weierstrassPoints)({ n: Fr.ORDER, ...CURVE.G1 });
const G1_ = weierstrassPoints({ n: Fr.ORDER, ...CURVE.G1 });
const G1 = Object.assign(G1_, htf.createHasher(G1_.ProjectivePoint, CURVE.G1.mapToCurve, {

@@ -102,3 +99,3 @@ ...CURVE.htfDefaults,

// Point on G2 curve (complex numbers): (x₁, x₂+i), (y₁, y₂+i)
const G2_ = (0, weierstrass_js_1.weierstrassPoints)({ n: Fr.ORDER, ...CURVE.G2 });
const G2_ = weierstrassPoints({ n: Fr.ORDER, ...CURVE.G2 });
const G2 = Object.assign(G2_, htf.createHasher(G2_.ProjectivePoint, CURVE.G2.mapToCurve, {

@@ -129,3 +126,3 @@ ...CURVE.htfDefaults,

? point
: G2.hashToCurve((0, utils_js_1.ensureBytes)('point', point), htfOpts);
: G2.hashToCurve(ensureBytes('point', point), htfOpts);
}

@@ -234,3 +231,2 @@ // Multiplies generator by private key.

}
exports.bls = bls;
//# sourceMappingURL=bls.js.map

@@ -1,8 +0,5 @@

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.validateBasic = exports.wNAF = void 0;
/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
// Abelian group utilities
const modular_js_1 = require("./modular.js");
const utils_js_1 = require("./utils.js");
import { validateField, nLength } from './modular.js';
import { validateObject } from './utils.js';
const _0n = BigInt(0);

@@ -21,3 +18,3 @@ const _1n = BigInt(1);

// windows to be in different memory locations
function wNAF(c, bits) {
export function wNAF(c, bits) {
const constTimeNegate = (condition, item) => {

@@ -142,6 +139,5 @@ const neg = item.negate();

}
exports.wNAF = wNAF;
function validateBasic(curve) {
(0, modular_js_1.validateField)(curve.Fp);
(0, utils_js_1.validateObject)(curve, {
export function validateBasic(curve) {
validateField(curve.Fp);
validateObject(curve, {
n: 'bigint',

@@ -156,5 +152,4 @@ h: 'bigint',

// Set defaults
return Object.freeze({ ...(0, modular_js_1.nLength)(curve.n, curve.nBitLength), ...curve });
return Object.freeze({ ...nLength(curve.n, curve.nBitLength), ...curve });
}
exports.validateBasic = validateBasic;
//# sourceMappingURL=curve.js.map

@@ -1,10 +0,7 @@

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.twistedEdwards = void 0;
/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
// Twisted Edwards curve. The formula is: ax² + y² = 1 + dx²y²
const modular_js_1 = require("./modular.js");
const ut = require("./utils.js");
const utils_js_1 = require("./utils.js");
const curve_js_1 = require("./curve.js");
import { mod } from './modular.js';
import * as ut from './utils.js';
import { ensureBytes } from './utils.js';
import { wNAF, validateBasic } from './curve.js';
// Be friendly to bad ECMAScript parsers by not using bigint literals like 123n

@@ -16,3 +13,3 @@ const _0n = BigInt(0);

function validateOpts(curve) {
const opts = (0, curve_js_1.validateBasic)(curve);
const opts = validateBasic(curve);
ut.validateObject(curve, {

@@ -33,3 +30,3 @@ hash: 'function',

// It is not generic twisted curve for now, but ed25519/ed448 generic implementation
function twistedEdwards(curveDef) {
export function twistedEdwards(curveDef) {
const CURVE = validateOpts(curveDef);

@@ -283,3 +280,3 @@ const { Fp, n: CURVE_ORDER, preHash, hash: cHash, randomBytes, nByteLength, h: cofactor } = CURVE;

const len = Fp.BYTES;
hex = (0, utils_js_1.ensureBytes)('pointHex', hex, len); // copy hex to a new array
hex = ensureBytes('pointHex', hex, len); // copy hex to a new array
const normed = hex.slice(); // copy again, we'll manipulate it

@@ -329,5 +326,5 @@ const lastByte = hex[len - 1]; // select last byte

const { BASE: G, ZERO: I } = Point;
const wnaf = (0, curve_js_1.wNAF)(Point, nByteLength * 8);
const wnaf = wNAF(Point, nByteLength * 8);
function modN(a) {
return (0, modular_js_1.mod)(a, CURVE_ORDER);
return mod(a, CURVE_ORDER);
}

@@ -341,6 +338,6 @@ // Little-endian SHA512 with modulo n

const len = nByteLength;
key = (0, utils_js_1.ensureBytes)('private key', key, len);
key = ensureBytes('private key', key, len);
// Hash private key with curve's hash function to produce uniformingly random input
// Check byte lengths: ensure(64, h(ensure(32, key)))
const hashed = (0, utils_js_1.ensureBytes)('hashed private key', cHash(key), 2 * len);
const hashed = ensureBytes('hashed private key', cHash(key), 2 * len);
const head = adjustScalarBytes(hashed.slice(0, len)); // clear first half bits, produce FE

@@ -360,7 +357,7 @@ const prefix = hashed.slice(len, 2 * len); // second half is called key prefix (5.1.6)

const msg = ut.concatBytes(...msgs);
return modN_LE(cHash(domain(msg, (0, utils_js_1.ensureBytes)('context', context), !!preHash)));
return modN_LE(cHash(domain(msg, ensureBytes('context', context), !!preHash)));
}
/** Signs message with privateKey. RFC8032 5.1.6 */
function sign(msg, privKey, context) {
msg = (0, utils_js_1.ensureBytes)('message', msg);
msg = ensureBytes('message', msg);
if (preHash)

@@ -375,8 +372,8 @@ msg = preHash(msg); // for ed25519ph etc.

const res = ut.concatBytes(R, ut.numberToBytesLE(s, Fp.BYTES));
return (0, utils_js_1.ensureBytes)('result', res, nByteLength * 2); // 64-byte signature
return ensureBytes('result', res, nByteLength * 2); // 64-byte signature
}
function verify(sig, msg, publicKey, context) {
const len = Fp.BYTES; // Verifies EdDSA signature against message and public key. RFC8032 5.1.7.
sig = (0, utils_js_1.ensureBytes)('signature', sig, 2 * len); // An extended group equation is checked.
msg = (0, utils_js_1.ensureBytes)('message', msg); // ZIP215 compliant, which means not fully RFC8032 compliant.
sig = ensureBytes('signature', sig, 2 * len); // An extended group equation is checked.
msg = ensureBytes('message', msg); // ZIP215 compliant, which means not fully RFC8032 compliant.
if (preHash)

@@ -419,3 +416,2 @@ msg = preHash(msg); // for ed25519ph, etc

}
exports.twistedEdwards = twistedEdwards;
//# sourceMappingURL=edwards.js.map

@@ -13,4 +13,5 @@ /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */

*/
declare type UnicodeOrBytes = string | Uint8Array;
export declare type Opts = {
DST: string | Uint8Array;
DST: UnicodeOrBytes;
p: bigint;

@@ -48,6 +49,6 @@ m: number;

export declare type htfBasicOpts = {
DST: string;
DST: UnicodeOrBytes;
};
export declare function createHasher<T>(Point: H2CPointConstructor<T>, mapToCurve: MapToCurve<T>, def: Opts & {
encodeDST?: string;
encodeDST?: UnicodeOrBytes;
}): {

@@ -57,2 +58,3 @@ hashToCurve(msg: Uint8Array, options?: htfBasicOpts): H2CPoint<T>;

};
export {};
//# sourceMappingURL=hash-to-curve.d.ts.map

@@ -1,6 +0,3 @@

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.createHasher = exports.isogenyMap = exports.hash_to_field = exports.expand_message_xof = exports.expand_message_xmd = void 0;
const modular_js_1 = require("./modular.js");
const utils_js_1 = require("./utils.js");
import { mod } from './modular.js';
import { bytesToNumberBE, concatBytes, utf8ToBytes, validateObject } from './utils.js';
function validateDST(dst) {

@@ -10,7 +7,7 @@ if (dst instanceof Uint8Array)

if (typeof dst === 'string')
return (0, utils_js_1.utf8ToBytes)(dst);
return utf8ToBytes(dst);
throw new Error('DST must be Uint8Array or string');
}
// Octet Stream to Integer. "spec" implementation of os2ip is 2.5x slower vs bytesToNumberBE.
const os2ip = utils_js_1.bytesToNumberBE;
const os2ip = bytesToNumberBE;
// Integer to Octet Stream (numberToBytesBE)

@@ -45,3 +42,3 @@ function i2osp(value, length) {

// https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-hash-to-curve-11#section-5.4.1
function expand_message_xmd(msg, DST, lenInBytes, H) {
export function expand_message_xmd(msg, DST, lenInBytes, H) {
isBytes(msg);

@@ -52,3 +49,3 @@ isBytes(DST);

if (DST.length > 255)
DST = H((0, utils_js_1.concatBytes)((0, utils_js_1.utf8ToBytes)('H2C-OVERSIZE-DST-'), DST));
DST = H(concatBytes(utf8ToBytes('H2C-OVERSIZE-DST-'), DST));
const { outputLen: b_in_bytes, blockLen: r_in_bytes } = H;

@@ -58,17 +55,16 @@ const ell = Math.ceil(lenInBytes / b_in_bytes);

throw new Error('Invalid xmd length');
const DST_prime = (0, utils_js_1.concatBytes)(DST, i2osp(DST.length, 1));
const DST_prime = concatBytes(DST, i2osp(DST.length, 1));
const Z_pad = i2osp(0, r_in_bytes);
const l_i_b_str = i2osp(lenInBytes, 2); // len_in_bytes_str
const b = new Array(ell);
const b_0 = H((0, utils_js_1.concatBytes)(Z_pad, msg, l_i_b_str, i2osp(0, 1), DST_prime));
b[0] = H((0, utils_js_1.concatBytes)(b_0, i2osp(1, 1), DST_prime));
const b_0 = H(concatBytes(Z_pad, msg, l_i_b_str, i2osp(0, 1), DST_prime));
b[0] = H(concatBytes(b_0, i2osp(1, 1), DST_prime));
for (let i = 1; i <= ell; i++) {
const args = [strxor(b_0, b[i - 1]), i2osp(i + 1, 1), DST_prime];
b[i] = H((0, utils_js_1.concatBytes)(...args));
b[i] = H(concatBytes(...args));
}
const pseudo_random_bytes = (0, utils_js_1.concatBytes)(...b);
const pseudo_random_bytes = concatBytes(...b);
return pseudo_random_bytes.slice(0, lenInBytes);
}
exports.expand_message_xmd = expand_message_xmd;
function expand_message_xof(msg, DST, lenInBytes, k, H) {
export function expand_message_xof(msg, DST, lenInBytes, k, H) {
isBytes(msg);

@@ -81,3 +77,3 @@ isBytes(DST);

const dkLen = Math.ceil((2 * k) / 8);
DST = H.create({ dkLen }).update((0, utils_js_1.utf8ToBytes)('H2C-OVERSIZE-DST-')).update(DST).digest();
DST = H.create({ dkLen }).update(utf8ToBytes('H2C-OVERSIZE-DST-')).update(DST).digest();
}

@@ -94,3 +90,2 @@ if (lenInBytes > 65535 || DST.length > 255)

}
exports.expand_message_xof = expand_message_xof;
/**

@@ -104,3 +99,10 @@ * Hashes arbitrary-length byte strings to a list of one or more elements of a finite field F

*/
function hash_to_field(msg, count, options) {
export function hash_to_field(msg, count, options) {
validateObject(options, {
DST: 'string',
p: 'bigint',
m: 'isSafeInteger',
k: 'isSafeInteger',
hash: 'hash',
});
const { p, k, m, hash, expand, DST: _DST } = options;

@@ -132,3 +134,3 @@ isBytes(msg);

const tv = prb.subarray(elm_offset, elm_offset + L);
e[j] = (0, modular_js_1.mod)(os2ip(tv), p);
e[j] = mod(os2ip(tv), p);
}

@@ -139,4 +141,3 @@ u[i] = e;

}
exports.hash_to_field = hash_to_field;
function isogenyMap(field, map) {
export function isogenyMap(field, map) {
// Make same order as in spec

@@ -151,11 +152,3 @@ const COEFF = map.map((i) => Array.from(i).reverse());

}
exports.isogenyMap = isogenyMap;
function createHasher(Point, mapToCurve, def) {
(0, utils_js_1.validateObject)(def, {
DST: 'string',
p: 'bigint',
m: 'isSafeInteger',
k: 'isSafeInteger',
hash: 'hash',
});
export function createHasher(Point, mapToCurve, def) {
if (typeof mapToCurve !== 'function')

@@ -165,3 +158,3 @@ throw new Error('mapToCurve() must be defined');

// Encodes byte string to elliptic curve
// https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-hash-to-curve-11#section-3
// https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-hash-to-curve-16#section-3
hashToCurve(msg, options) {

@@ -184,3 +177,2 @@ const u = hash_to_field(msg, 2, { ...def, DST: def.DST, ...options });

}
exports.createHasher = createHasher;
//# sourceMappingURL=hash-to-curve.js.map

@@ -1,7 +0,4 @@

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.hashToPrivateScalar = exports.FpSqrtEven = exports.FpSqrtOdd = exports.Fp = exports.nLength = exports.FpIsSquare = exports.FpDiv = exports.FpInvertBatch = exports.FpPow = exports.validateField = exports.isNegativeLE = exports.FpSqrt = exports.tonelliShanks = exports.invert = exports.pow2 = exports.pow = exports.mod = void 0;
/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
// Utilities for modular arithmetics and finite fields
const utils_js_1 = require("./utils.js");
import { bitMask, numberToBytesBE, numberToBytesLE, bytesToNumberBE, bytesToNumberLE, ensureBytes, validateObject, } from './utils.js';
// prettier-ignore

@@ -14,7 +11,6 @@ const _0n = BigInt(0), _1n = BigInt(1), _2n = BigInt(2), _3n = BigInt(3);

// Calculates a modulo b
function mod(a, b) {
export function mod(a, b) {
const result = a % b;
return result >= _0n ? result : b + result;
}
exports.mod = mod;
/**

@@ -27,3 +23,3 @@ * Efficiently exponentiate num to power and do modular division.

// TODO: use field version && remove
function pow(num, power, modulo) {
export function pow(num, power, modulo) {
if (modulo <= _0n || power < _0n)

@@ -42,5 +38,4 @@ throw new Error('Expected power/modulo > 0');

}
exports.pow = pow;
// Does x ^ (2 ^ power) mod p. pow2(30, 4) == 30 ^ (2 ^ 4)
function pow2(x, power, modulo) {
export function pow2(x, power, modulo) {
let res = x;

@@ -53,5 +48,4 @@ while (power-- > _0n) {

}
exports.pow2 = pow2;
// Inverses number over modulo
function invert(number, modulo) {
export function invert(number, modulo) {
if (number === _0n || modulo <= _0n) {

@@ -61,2 +55,3 @@ throw new Error(`invert: expected positive integers, got n=${number} mod=${modulo}`);

// Eucledian GCD https://brilliant.org/wiki/extended-euclidean-algorithm/
// Fermat's little theorem "CT-like" version inv(n) = n^(m-2) mod m is 30x slower.
let a = mod(number, modulo);

@@ -80,7 +75,6 @@ let b = modulo;

}
exports.invert = invert;
// Tonelli-Shanks algorithm
// Paper 1: https://eprint.iacr.org/2012/685.pdf (page 12)
// Paper 2: Square Roots from 1; 24, 51, 10 to Dan Shanks
function tonelliShanks(P) {
export function tonelliShanks(P) {
// Legendre constant: used to calculate Legendre symbol (a | p),

@@ -141,4 +135,3 @@ // which denotes the value of a^((p-1)/2) (mod p).

}
exports.tonelliShanks = tonelliShanks;
function FpSqrt(P) {
export function FpSqrt(P) {
// NOTE: different algorithms can give different roots, it is up to user to decide which one they want.

@@ -201,6 +194,4 @@ // For example there is FpSqrtOdd/FpSqrtEven to choice root based on oddness (used for hash-to-curve).

}
exports.FpSqrt = FpSqrt;
// Little-endian check for first LE bit (last BE bit);
const isNegativeLE = (num, modulo) => (mod(num, modulo) & _1n) === _1n;
exports.isNegativeLE = isNegativeLE;
export const isNegativeLE = (num, modulo) => (mod(num, modulo) & _1n) === _1n;
// prettier-ignore

@@ -212,3 +203,3 @@ const FIELD_FIELDS = [

];
function validateField(field) {
export function validateField(field) {
const initial = {

@@ -224,7 +215,6 @@ ORDER: 'bigint',

}, initial);
return (0, utils_js_1.validateObject)(field, opts);
return validateObject(field, opts);
}
exports.validateField = validateField;
// Generic field functions
function FpPow(f, num, power) {
export function FpPow(f, num, power) {
// Should have same speed as pow for bigints

@@ -248,4 +238,3 @@ // TODO: benchmark!

}
exports.FpPow = FpPow;
function FpInvertBatch(f, nums) {
export function FpInvertBatch(f, nums) {
const tmp = new Array(nums.length);

@@ -270,9 +259,7 @@ // Walk from first to last, multiply them by each other MOD p

}
exports.FpInvertBatch = FpInvertBatch;
function FpDiv(f, lhs, rhs) {
export function FpDiv(f, lhs, rhs) {
return f.mul(lhs, typeof rhs === 'bigint' ? invert(rhs, f.ORDER) : f.inv(rhs));
}
exports.FpDiv = FpDiv;
// This function returns True whenever the value x is a square in the field F.
function FpIsSquare(f) {
export function FpIsSquare(f) {
const legendreConst = (f.ORDER - _1n) / _2n; // Integer arithmetic

@@ -284,5 +271,4 @@ return (x) => {

}
exports.FpIsSquare = FpIsSquare;
// CURVE.n lengths
function nLength(n, nBitLength) {
export function nLength(n, nBitLength) {
// Bit size, byte size of CURVE.n

@@ -293,4 +279,3 @@ const _nBitLength = nBitLength !== undefined ? nBitLength : n.toString(2).length;

}
exports.nLength = nLength;
function Fp(ORDER, bitLen, isLE = false, redef = {}) {
export function Fp(ORDER, bitLen, isLE = false, redef = {}) {
if (ORDER <= _0n)

@@ -306,3 +291,3 @@ throw new Error(`Expected Fp ORDER > 0, got ${ORDER}`);

BYTES,
MASK: (0, utils_js_1.bitMask)(BITS),
MASK: bitMask(BITS),
ZERO: _0n,

@@ -337,7 +322,7 @@ ONE: _1n,

cmov: (a, b, c) => (c ? b : a),
toBytes: (num) => (isLE ? (0, utils_js_1.numberToBytesLE)(num, BYTES) : (0, utils_js_1.numberToBytesBE)(num, BYTES)),
toBytes: (num) => (isLE ? numberToBytesLE(num, BYTES) : numberToBytesBE(num, BYTES)),
fromBytes: (bytes) => {
if (bytes.length !== BYTES)
throw new Error(`Fp.fromBytes: expected ${BYTES}, got ${bytes.length}`);
return isLE ? (0, utils_js_1.bytesToNumberLE)(bytes) : (0, utils_js_1.bytesToNumberBE)(bytes);
return isLE ? bytesToNumberLE(bytes) : bytesToNumberBE(bytes);
},

@@ -347,4 +332,3 @@ });

}
exports.Fp = Fp;
function FpSqrtOdd(Fp, elm) {
export function FpSqrtOdd(Fp, elm) {
if (!Fp.isOdd)

@@ -355,4 +339,3 @@ throw new Error(`Field doesn't have isOdd`);

}
exports.FpSqrtOdd = FpSqrtOdd;
function FpSqrtEven(Fp, elm) {
export function FpSqrtEven(Fp, elm) {
if (!Fp.isOdd)

@@ -363,3 +346,2 @@ throw new Error(`Field doesn't have isOdd`);

}
exports.FpSqrtEven = FpSqrtEven;
/**

@@ -374,4 +356,4 @@ * FIPS 186 B.4.1-compliant "constant-time" private key generation utility.

*/
function hashToPrivateScalar(hash, groupOrder, isLE = false) {
hash = (0, utils_js_1.ensureBytes)('privateHash', hash);
export function hashToPrivateScalar(hash, groupOrder, isLE = false) {
hash = ensureBytes('privateHash', hash);
const hashLen = hash.length;

@@ -381,6 +363,5 @@ const minLen = nLength(groupOrder).nByteLength + 8;

throw new Error(`hashToPrivateScalar: expected ${minLen}-1024 bytes of input, got ${hashLen}`);
const num = isLE ? (0, utils_js_1.bytesToNumberLE)(hash) : (0, utils_js_1.bytesToNumberBE)(hash);
const num = isLE ? bytesToNumberLE(hash) : bytesToNumberBE(hash);
return mod(num, groupOrder - _1n) + _1n;
}
exports.hashToPrivateScalar = hashToPrivateScalar;
//# sourceMappingURL=modular.js.map

@@ -1,11 +0,8 @@

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.montgomery = void 0;
/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
const modular_js_1 = require("./modular.js");
const utils_js_1 = require("./utils.js");
import { mod, pow } from './modular.js';
import { bytesToNumberLE, ensureBytes, numberToBytesLE, validateObject } from './utils.js';
const _0n = BigInt(0);
const _1n = BigInt(1);
function validateOpts(curve) {
(0, utils_js_1.validateObject)(curve, {
validateObject(curve, {
a: 'bigint',

@@ -25,6 +22,6 @@ }, {

// Uses only one coordinate instead of two
function montgomery(curveDef) {
export function montgomery(curveDef) {
const CURVE = validateOpts(curveDef);
const { P } = CURVE;
const modP = (n) => (0, modular_js_1.mod)(n, P);
const modP = (n) => mod(n, P);
const montgomeryBits = CURVE.montgomeryBits;

@@ -34,3 +31,3 @@ const montgomeryBytes = Math.ceil(montgomeryBits / 8);

const adjustScalarBytes = CURVE.adjustScalarBytes || ((bytes) => bytes);
const powPminus2 = CURVE.powPminus2 || ((x) => (0, modular_js_1.pow)(x, P - BigInt(2), P));
const powPminus2 = CURVE.powPminus2 || ((x) => pow(x, P - BigInt(2), P));
// cswap from RFC7748. But it is not from RFC7748!

@@ -119,3 +116,3 @@ /*

function encodeUCoordinate(u) {
return (0, utils_js_1.numberToBytesLE)(modP(u), montgomeryBytes);
return numberToBytesLE(modP(u), montgomeryBytes);
}

@@ -127,13 +124,13 @@ function decodeUCoordinate(uEnc) {

// fieldLen - scalaryBytes = 1 for X448 and = 0 for X25519
const u = (0, utils_js_1.ensureBytes)('u coordinate', uEnc, montgomeryBytes);
const u = ensureBytes('u coordinate', uEnc, montgomeryBytes);
// u[fieldLen-1] crashes QuickJS (TypeError: out-of-bound numeric index)
if (fieldLen === montgomeryBytes)
u[fieldLen - 1] &= 127; // 0b0111_1111
return (0, utils_js_1.bytesToNumberLE)(u);
return bytesToNumberLE(u);
}
function decodeScalar(n) {
const bytes = (0, utils_js_1.ensureBytes)('scalar', n);
const bytes = ensureBytes('scalar', n);
if (bytes.length !== montgomeryBytes && bytes.length !== fieldLen)
throw new Error(`Expected ${montgomeryBytes} or ${fieldLen} bytes, got ${bytes.length}`);
return (0, utils_js_1.bytesToNumberLE)(adjustScalarBytes(bytes));
return bytesToNumberLE(adjustScalarBytes(bytes));
}

@@ -164,3 +161,2 @@ function scalarMult(scalar, u) {

}
exports.montgomery = montgomery;
//# sourceMappingURL=montgomery.js.map

@@ -1,10 +0,7 @@

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.poseidon = exports.splitConstants = exports.validateOpts = void 0;
/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
// Poseidon Hash: https://eprint.iacr.org/2019/458.pdf, https://www.poseidon-hash.info
const modular_js_1 = require("./modular.js");
function validateOpts(opts) {
import { FpPow, validateField } from './modular.js';
export function validateOpts(opts) {
const { Fp } = opts;
(0, modular_js_1.validateField)(Fp);
validateField(Fp);
for (const i of ['t', 'roundsFull', 'roundsPartial']) {

@@ -23,3 +20,3 @@ if (typeof opts[i] !== 'number' || !Number.isSafeInteger(opts[i]))

const _sboxPower = BigInt(sboxPower);
let sboxFn = (n) => (0, modular_js_1.FpPow)(Fp, n, _sboxPower);
let sboxFn = (n) => FpPow(Fp, n, _sboxPower);
// Unwrapped sbox power for common cases (195->142μs)

@@ -58,4 +55,3 @@ if (sboxPower === 3)

}
exports.validateOpts = validateOpts;
function splitConstants(rc, t) {
export function splitConstants(rc, t) {
if (typeof t !== 'number')

@@ -76,4 +72,3 @@ throw new Error('poseidonSplitConstants: wrong t');

}
exports.splitConstants = splitConstants;
function poseidon(opts) {
export function poseidon(opts) {
const { t, Fp, rounds, sboxFn, reversePartialPowIdx } = validateOpts(opts);

@@ -118,3 +113,2 @@ const halfRoundsFull = Math.floor(opts.roundsFull / 2);

}
exports.poseidon = poseidon;
//# sourceMappingURL=poseidon.js.map

@@ -1,4 +0,1 @@

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.validateObject = exports.createHmacDrbg = exports.bitMask = exports.bitSet = exports.bitGet = exports.bitLen = exports.utf8ToBytes = exports.equalBytes = exports.concatBytes = exports.ensureBytes = exports.numberToVarBytesBE = exports.numberToBytesLE = exports.numberToBytesBE = exports.bytesToNumberLE = exports.bytesToNumberBE = exports.hexToBytes = exports.hexToNumber = exports.numberToHexUnpadded = exports.bytesToHex = void 0;
/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */

@@ -10,3 +7,3 @@ const _0n = BigInt(0);

const hexes = Array.from({ length: 256 }, (v, i) => i.toString(16).padStart(2, '0'));
function bytesToHex(bytes) {
export function bytesToHex(bytes) {
if (!u8a(bytes))

@@ -21,9 +18,7 @@ throw new Error('Uint8Array expected');

}
exports.bytesToHex = bytesToHex;
function numberToHexUnpadded(num) {
export function numberToHexUnpadded(num) {
const hex = num.toString(16);
return hex.length & 1 ? `0${hex}` : hex;
}
exports.numberToHexUnpadded = numberToHexUnpadded;
function hexToNumber(hex) {
export function hexToNumber(hex) {
if (typeof hex !== 'string')

@@ -34,5 +29,4 @@ throw new Error('hex string expected, got ' + typeof hex);

}
exports.hexToNumber = hexToNumber;
// Caching slows it down 2-3x
function hexToBytes(hex) {
export function hexToBytes(hex) {
if (typeof hex !== 'string')

@@ -53,9 +47,7 @@ throw new Error('hex string expected, got ' + typeof hex);

}
exports.hexToBytes = hexToBytes;
// Big Endian
function bytesToNumberBE(bytes) {
export function bytesToNumberBE(bytes) {
return hexToNumber(bytesToHex(bytes));
}
exports.bytesToNumberBE = bytesToNumberBE;
function bytesToNumberLE(bytes) {
export function bytesToNumberLE(bytes) {
if (!u8a(bytes))

@@ -65,11 +57,7 @@ throw new Error('Uint8Array expected');

}
exports.bytesToNumberLE = bytesToNumberLE;
const numberToBytesBE = (n, len) => hexToBytes(n.toString(16).padStart(len * 2, '0'));
exports.numberToBytesBE = numberToBytesBE;
const numberToBytesLE = (n, len) => (0, exports.numberToBytesBE)(n, len).reverse();
exports.numberToBytesLE = numberToBytesLE;
export const numberToBytesBE = (n, len) => hexToBytes(n.toString(16).padStart(len * 2, '0'));
export const numberToBytesLE = (n, len) => numberToBytesBE(n, len).reverse();
// Returns variable number bytes (minimal bigint encoding?)
const numberToVarBytesBE = (n) => hexToBytes(numberToHexUnpadded(n));
exports.numberToVarBytesBE = numberToVarBytesBE;
function ensureBytes(title, hex, expectedLength) {
export const numberToVarBytesBE = (n) => hexToBytes(numberToHexUnpadded(n));
export function ensureBytes(title, hex, expectedLength) {
let res;

@@ -97,5 +85,4 @@ if (typeof hex === 'string') {

}
exports.ensureBytes = ensureBytes;
// Copies several Uint8Arrays into one.
function concatBytes(...arrs) {
export function concatBytes(...arrs) {
const r = new Uint8Array(arrs.reduce((sum, a) => sum + a.length, 0));

@@ -111,4 +98,3 @@ let pad = 0; // walk through each item, ensure they have proper type

}
exports.concatBytes = concatBytes;
function equalBytes(b1, b2) {
export function equalBytes(b1, b2) {
// We don't care about timing attacks here

@@ -122,4 +108,3 @@ if (b1.length !== b2.length)

}
exports.equalBytes = equalBytes;
function utf8ToBytes(str) {
export function utf8ToBytes(str) {
if (typeof str !== 'string') {

@@ -130,6 +115,5 @@ throw new Error(`utf8ToBytes expected string, got ${typeof str}`);

}
exports.utf8ToBytes = utf8ToBytes;
// Bit operations
// Amount of bits inside bigint (Same as n.toString(2).length)
function bitLen(n) {
export function bitLen(n) {
let len;

@@ -140,14 +124,10 @@ for (len = 0; n > 0n; n >>= _1n, len += 1)

}
exports.bitLen = bitLen;
// Gets single bit at position. NOTE: first bit position is 0 (same as arrays)
// Same as !!+Array.from(n.toString(2)).reverse()[pos]
const bitGet = (n, pos) => (n >> BigInt(pos)) & 1n;
exports.bitGet = bitGet;
export const bitGet = (n, pos) => (n >> BigInt(pos)) & 1n;
// Sets single bit at position
const bitSet = (n, pos, value) => n | ((value ? _1n : _0n) << BigInt(pos));
exports.bitSet = bitSet;
export const bitSet = (n, pos, value) => n | ((value ? _1n : _0n) << BigInt(pos));
// Return mask for N bits (Same as BigInt(`0b${Array(i).fill('1').join('')}`))
// Not using ** operator with bigints for old engines.
const bitMask = (n) => (_2n << BigInt(n - 1)) - _1n;
exports.bitMask = bitMask;
export const bitMask = (n) => (_2n << BigInt(n - 1)) - _1n;
// DRBG

@@ -163,3 +143,3 @@ const u8n = (data) => new Uint8Array(data); // creates Uint8Array

*/
function createHmacDrbg(hashLen, qByteLen, hmacFn) {
export function createHmacDrbg(hashLen, qByteLen, hmacFn) {
if (typeof hashLen !== 'number' || hashLen < 2)

@@ -215,3 +195,2 @@ throw new Error('hashLen must be a number');

}
exports.createHmacDrbg = createHmacDrbg;
// Validating curves and fields

@@ -229,3 +208,3 @@ const validatorFns = {

// type Record<K extends string | number | symbol, T> = { [P in K]: T; }
function validateObject(object, validators, optValidators = {}) {
export function validateObject(object, validators, optValidators = {}) {
const checkField = (fieldName, type, isOptional) => {

@@ -248,3 +227,2 @@ const checkVal = validatorFns[type];

}
exports.validateObject = validateObject;
// validate type tests

@@ -251,0 +229,0 @@ // const o: { a: number; b: number; c: number } = { a: 1, b: 5, c: 6 };

@@ -1,12 +0,9 @@

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.mapToCurveSimpleSWU = exports.SWUFpSqrtRatio = exports.weierstrass = exports.weierstrassPoints = void 0;
/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
// Short Weierstrass curve. The formula is: y² = x³ + ax + b
const mod = require("./modular.js");
const ut = require("./utils.js");
const utils_js_1 = require("./utils.js");
const curve_js_1 = require("./curve.js");
import * as mod from './modular.js';
import * as ut from './utils.js';
import { ensureBytes } from './utils.js';
import { wNAF, validateBasic } from './curve.js';
function validatePointOpts(curve) {
const opts = (0, curve_js_1.validateBasic)(curve);
const opts = validateBasic(curve);
ut.validateObject(opts, {

@@ -94,3 +91,3 @@ a: 'field',

const _1n = BigInt(1);
function weierstrassPoints(opts) {
export function weierstrassPoints(opts) {
const CURVE = validatePointOpts(opts);

@@ -133,3 +130,3 @@ const { Fp } = CURVE; // All curves has same field / group length as for now, but they can differ

? key
: ut.bytesToNumberBE((0, utils_js_1.ensureBytes)('private key', key, nByteLength));
: ut.bytesToNumberBE(ensureBytes('private key', key, nByteLength));
}

@@ -201,3 +198,3 @@ catch (error) {

static fromHex(hex) {
const P = Point.fromAffine(CURVE.fromBytes((0, utils_js_1.ensureBytes)('pointHex', hex)));
const P = Point.fromAffine(CURVE.fromBytes(ensureBytes('pointHex', hex)));
P.assertValidity();

@@ -492,3 +489,3 @@ return P;

const _bits = CURVE.nBitLength;
const wnaf = (0, curve_js_1.wNAF)(Point, CURVE.endo ? Math.ceil(_bits / 2) : _bits);
const wnaf = wNAF(Point, CURVE.endo ? Math.ceil(_bits / 2) : _bits);
return {

@@ -501,5 +498,4 @@ ProjectivePoint: Point,

}
exports.weierstrassPoints = weierstrassPoints;
function validateOpts(curve) {
const opts = (0, curve_js_1.validateBasic)(curve);
const opts = validateBasic(curve);
ut.validateObject(opts, {

@@ -516,3 +512,3 @@ hash: 'hash',

}
function weierstrass(curveDef) {
export function weierstrass(curveDef) {
const CURVE = validateOpts(curveDef);

@@ -596,3 +592,3 @@ const CURVE_ORDER = CURVE.n;

const l = CURVE.nByteLength;
hex = (0, utils_js_1.ensureBytes)('compactSignature', hex, l * 2);
hex = ensureBytes('compactSignature', hex, l * 2);
return new Signature(slcNum(hex, 0, l), slcNum(hex, l, 2 * l));

@@ -603,3 +599,3 @@ }

static fromDER(hex) {
const { r, s } = DER.toSig((0, utils_js_1.ensureBytes)('DER', hex));
const { r, s } = DER.toSig(ensureBytes('DER', hex));
return new Signature(r, s);

@@ -619,3 +615,3 @@ }

const { r, s, recovery: rec } = this;
const h = bits2int_modN((0, utils_js_1.ensureBytes)('msgHash', msgHash)); // Truncate hash
const h = bits2int_modN(ensureBytes('msgHash', msgHash)); // Truncate hash
if (rec == null || ![0, 1, 2, 3].includes(rec))

@@ -776,5 +772,5 @@ throw new Error('recovery id invalid');

lowS = true; // RFC6979 3.2: we skip step A, because we already provide hash
msgHash = (0, utils_js_1.ensureBytes)('msgHash', msgHash);
msgHash = ensureBytes('msgHash', msgHash);
if (prehash)
msgHash = (0, utils_js_1.ensureBytes)('prehashed msgHash', hash(msgHash));
msgHash = ensureBytes('prehashed msgHash', hash(msgHash));
// We can't later call bits2octets, since nested bits2int is broken for curves

@@ -790,3 +786,3 @@ // with nBitLength % 8 !== 0. Because of that, we unwrap it here as int2octets call.

const e = ent === true ? randomBytes(Fp.BYTES) : ent; // generate random bytes OR pass as-is
seedArgs.push((0, utils_js_1.ensureBytes)('extraEntropy', e, Fp.BYTES)); // check for being of size BYTES
seedArgs.push(ensureBytes('extraEntropy', e, Fp.BYTES)); // check for being of size BYTES
}

@@ -806,11 +802,6 @@ const seed = ut.concatBytes(...seedArgs); // Step D of RFC6979 3.2

return;
// X blinding according to https://tches.iacr.org/index.php/TCHES/article/view/7337/6509
// b * m + b * r * d ∈ [0,q−1] exposed via side-channel, but d (private scalar) is not.
// NOTE: there is still probable some leak in multiplication, since it is not constant-time
const b = ut.bytesToNumberBE(utils.randomPrivateKey()); // random scalar, b ∈ [1,q−1]
const bi = invN(b); // b^-1
const bdr = modN(b * d * r); // b * d * r
const bm = modN(b * m); // b * m
const mrx = modN(bi * modN(bdr + bm)); // b^-1(bm + bdr) -> m + rd
const s = modN(ik * mrx); // s = k^-1(m + rd) mod n
// Can use scalar blinding b^-1(bm + bdr) where b ∈ [1,q−1] according to
// https://tches.iacr.org/index.php/TCHES/article/view/7337/6509. We've decided against it:
// a) dependency on CSPRNG b) 15% slowdown c) doesn't really help since bigints are not CT
const s = modN(ik * modN(m + r * d)); // Not using blinding here
if (s === _0n)

@@ -863,4 +854,4 @@ return;

const sg = signature;
msgHash = (0, utils_js_1.ensureBytes)('msgHash', msgHash);
publicKey = (0, utils_js_1.ensureBytes)('publicKey', publicKey);
msgHash = ensureBytes('msgHash', msgHash);
publicKey = ensureBytes('publicKey', publicKey);
if ('strict' in opts)

@@ -924,3 +915,2 @@ throw new Error('options.strict was renamed to lowS');

}
exports.weierstrass = weierstrass;
// Implementation of the Shallue and van de Woestijne method for any Weierstrass curve

@@ -930,3 +920,3 @@ // TODO: check if there is a way to merge this with uvRatio in Edwards && move to modular?

// b = False and y = sqrt(Z * (u / v)) otherwise.
function SWUFpSqrtRatio(Fp, Z) {
export function SWUFpSqrtRatio(Fp, Z) {
// Generic implementation

@@ -995,5 +985,4 @@ const q = Fp.ORDER;

}
exports.SWUFpSqrtRatio = SWUFpSqrtRatio;
// From draft-irtf-cfrg-hash-to-curve-16
function mapToCurveSimpleSWU(Fp, opts) {
export function mapToCurveSimpleSWU(Fp, opts) {
mod.validateField(Fp);

@@ -1038,3 +1027,2 @@ if (!Fp.isValid(opts.A) || !Fp.isValid(opts.B) || !Fp.isValid(opts.Z))

}
exports.mapToCurveSimpleSWU = mapToCurveSimpleSWU;
//# sourceMappingURL=weierstrass.js.map

@@ -1,5 +0,2 @@

"use strict";
/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
Object.defineProperty(exports, "__esModule", { value: true });
exports.bls12_381 = void 0;
// bls12-381 pairing-friendly Barreto-Lynn-Scott elliptic curve construction allows to:

@@ -49,10 +46,10 @@ // - Construct zk-SNARKs at the 128-bit security

// - Points now have only two coordinates
const sha256_1 = require("@noble/hashes/sha256");
const utils_1 = require("@noble/hashes/utils");
const bls_js_1 = require("./abstract/bls.js");
const mod = require("./abstract/modular.js");
const utils_js_1 = require("./abstract/utils.js");
import { sha256 } from '@noble/hashes/sha256';
import { randomBytes } from '@noble/hashes/utils';
import { bls } from './abstract/bls.js';
import * as mod from './abstract/modular.js';
import { concatBytes as concatB, ensureBytes, numberToBytesBE, bytesToNumberBE, bitLen, bitSet, bitGet, bitMask, } from './abstract/utils.js';
// Types
const weierstrass_js_1 = require("./abstract/weierstrass.js");
const hash_to_curve_js_1 = require("./abstract/hash-to-curve.js");
import { mapToCurveSimpleSWU, } from './abstract/weierstrass.js';
import { isogenyMap } from './abstract/hash-to-curve.js';
// CURVE FIELDS

@@ -99,5 +96,5 @@ // Finite field over p.

ORDER: FP2_ORDER,
BITS: (0, utils_js_1.bitLen)(FP2_ORDER),
BYTES: Math.ceil((0, utils_js_1.bitLen)(FP2_ORDER) / 8),
MASK: (0, utils_js_1.bitMask)((0, utils_js_1.bitLen)(FP2_ORDER)),
BITS: bitLen(FP2_ORDER),
BYTES: Math.ceil(bitLen(FP2_ORDER) / 8),
MASK: bitMask(bitLen(FP2_ORDER)),
ZERO: { c0: Fp.ZERO, c1: Fp.ZERO },

@@ -182,3 +179,3 @@ ONE: { c0: Fp.ONE, c1: Fp.ZERO },

},
toBytes: ({ c0, c1 }) => (0, utils_js_1.concatBytes)(Fp.toBytes(c0), Fp.toBytes(c1)),
toBytes: ({ c0, c1 }) => concatB(Fp.toBytes(c0), Fp.toBytes(c1)),
cmov: ({ c0, c1 }, { c0: r0, c1: r1 }, c) => ({

@@ -288,3 +285,3 @@ c0: Fp.cmov(c0, r0, c),

BYTES: 3 * Fp2.BYTES,
MASK: (0, utils_js_1.bitMask)(3 * Fp2.BITS),
MASK: bitMask(3 * Fp2.BITS),
ZERO: { c0: Fp2.ZERO, c1: Fp2.ZERO, c2: Fp2.ZERO },

@@ -332,3 +329,3 @@ ONE: { c0: Fp2.ONE, c1: Fp2.ZERO, c2: Fp2.ZERO },

},
toBytes: ({ c0, c1, c2 }) => (0, utils_js_1.concatBytes)(Fp2.toBytes(c0), Fp2.toBytes(c1), Fp2.toBytes(c2)),
toBytes: ({ c0, c1, c2 }) => concatB(Fp2.toBytes(c0), Fp2.toBytes(c1), Fp2.toBytes(c2)),
cmov: ({ c0, c1, c2 }, { c0: r0, c1: r1, c2: r2 }, c) => ({

@@ -431,3 +428,3 @@ c0: Fp2.cmov(c0, r0, c),

const BLS_X = 0xd201000000010000n;
const BLS_X_LEN = (0, utils_js_1.bitLen)(BLS_X);
const BLS_X_LEN = bitLen(BLS_X);
const Fp12Add = ({ c0, c1 }, { c0: r0, c1: r1 }) => ({

@@ -473,3 +470,3 @@ c0: Fp6.add(c0, r0),

BYTES: 2 * Fp2.BYTES,
MASK: (0, utils_js_1.bitMask)(2 * Fp2.BITS),
MASK: bitMask(2 * Fp2.BITS),
ZERO: { c0: Fp6.ZERO, c1: Fp6.ZERO },

@@ -511,3 +508,3 @@ ONE: { c0: Fp6.ONE, c1: Fp6.ZERO },

},
toBytes: ({ c0, c1 }) => (0, utils_js_1.concatBytes)(Fp6.toBytes(c0), Fp6.toBytes(c1)),
toBytes: ({ c0, c1 }) => concatB(Fp6.toBytes(c0), Fp6.toBytes(c1)),
cmov: ({ c0, c1 }, { c0: r0, c1: r1 }, c) => ({

@@ -585,3 +582,3 @@ c0: Fp6.cmov(c0, r0, c),

z = Fp12._cyclotomicSquare(z);
if ((0, utils_js_1.bitGet)(n, i))
if (bitGet(n, i))
z = Fp12.mul(z, num);

@@ -664,3 +661,3 @@ }

// https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-hash-to-curve-11#appendix-E.3
const isogenyMapG2 = (0, hash_to_curve_js_1.isogenyMap)(Fp2, [
const isogenyMapG2 = isogenyMap(Fp2, [
// xNum

@@ -734,3 +731,3 @@ [

// 11-isogeny map from E' to E
const isogenyMapG1 = (0, hash_to_curve_js_1.isogenyMap)(Fp, [
const isogenyMapG1 = isogenyMap(Fp, [
// xNum

@@ -805,3 +802,3 @@ [

// SWU Map - Fp2 to G2': y² = x³ + 240i * x + 1012 + 1012i
const G2_SWU = (0, weierstrass_js_1.mapToCurveSimpleSWU)(Fp2, {
const G2_SWU = mapToCurveSimpleSWU(Fp2, {
A: Fp2.create({ c0: Fp.create(0n), c1: Fp.create(240n) }),

@@ -812,3 +809,3 @@ B: Fp2.create({ c0: Fp.create(1012n), c1: Fp.create(1012n) }),

// Optimized SWU Map - Fp to G1
const G1_SWU = (0, weierstrass_js_1.mapToCurveSimpleSWU)(Fp, {
const G1_SWU = mapToCurveSimpleSWU(Fp, {
A: Fp.create(0x144698a3b8e9433d693a02c96d4982b0ea985383ee66a8d8e8981aefd881ac98936f8da0e0f97f5cf428082d584c1dn),

@@ -878,3 +875,3 @@ B: Fp.create(0x12e2908d11688030018b12e8753eee3b2016c1f0f24f4070a0b9c14fcef35ef55a23215a316ceaa5d1cc48e98e172be0n),

// BBS+ uses blake2: https://github.com/hyperledger/aries-framework-go/issues/2247
hash: sha256_1.sha256,
hash: sha256,
});

@@ -887,3 +884,3 @@ // Encoding utils

// Compressed point of infinity
const COMPRESSED_ZERO = Fp.toBytes((0, utils_js_1.bitSet)((0, utils_js_1.bitSet)(0n, I_BIT_POS, true), S_BIT_POS, true)); // set compressed & point-at-infinity bits
const COMPRESSED_ZERO = Fp.toBytes(bitSet(bitSet(0n, I_BIT_POS, true), S_BIT_POS, true)); // set compressed & point-at-infinity bits
// To verify curve parameters, see pairing-friendly-curves spec:

@@ -899,3 +896,3 @@ // https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-pairing-friendly-curves-09

// Here goes constants && point encoding format
exports.bls12_381 = (0, bls_js_1.bls)({
export const bls12_381 = bls({
// Fields

@@ -934,4 +931,4 @@ Fr,

// todo: unroll
const xP = point.multiplyUnsafe(exports.bls12_381.CURVE.x).negate(); // [x]P
const u2P = xP.multiplyUnsafe(exports.bls12_381.CURVE.x); // [u2]P
const xP = point.multiplyUnsafe(bls12_381.CURVE.x).negate(); // [x]P
const u2P = xP.multiplyUnsafe(bls12_381.CURVE.x); // [u2]P
return u2P.equals(phi);

@@ -954,3 +951,3 @@ // https://eprint.iacr.org/2019/814.pdf

// return this.multiplyUnsafe(CURVE.h);
return point.multiplyUnsafe(exports.bls12_381.CURVE.x).add(point); // x*P + P
return point.multiplyUnsafe(bls12_381.CURVE.x).add(point); // x*P + P
},

@@ -964,4 +961,4 @@ mapToCurve: (scalars) => {

const P = Fp.ORDER;
const compressedValue = (0, utils_js_1.bytesToNumberBE)(bytes);
const bflag = (0, utils_js_1.bitGet)(compressedValue, I_BIT_POS);
const compressedValue = bytesToNumberBE(bytes);
const bflag = bitGet(compressedValue, I_BIT_POS);
// Zero

@@ -971,7 +968,7 @@ if (bflag === 1n)

const x = Fp.create(compressedValue & Fp.MASK);
const right = Fp.add(Fp.pow(x, 3n), Fp.create(exports.bls12_381.CURVE.G1.b)); // y² = x³ + b
const right = Fp.add(Fp.pow(x, 3n), Fp.create(bls12_381.CURVE.G1.b)); // y² = x³ + b
let y = Fp.sqrt(right);
if (!y)
throw new Error('Invalid compressed G1 point');
const aflag = (0, utils_js_1.bitGet)(compressedValue, C_BIT_POS);
const aflag = bitGet(compressedValue, C_BIT_POS);
if ((y * 2n) / P !== aflag)

@@ -984,5 +981,5 @@ y = Fp.neg(y);

if ((bytes[0] & (1 << 6)) !== 0)
return exports.bls12_381.G1.ProjectivePoint.ZERO.toAffine();
const x = (0, utils_js_1.bytesToNumberBE)(bytes.slice(0, Fp.BYTES));
const y = (0, utils_js_1.bytesToNumberBE)(bytes.slice(Fp.BYTES));
return bls12_381.G1.ProjectivePoint.ZERO.toAffine();
const x = bytesToNumberBE(bytes.slice(0, Fp.BYTES));
const y = bytesToNumberBE(bytes.slice(Fp.BYTES));
return { x: Fp.create(x), y: Fp.create(y) };

@@ -1002,5 +999,5 @@ }

let num;
num = (0, utils_js_1.bitSet)(x, C_BIT_POS, Boolean((y * 2n) / P)); // set aflag
num = (0, utils_js_1.bitSet)(num, S_BIT_POS, true);
return (0, utils_js_1.numberToBytesBE)(num, Fp.BYTES);
num = bitSet(x, C_BIT_POS, Boolean((y * 2n) / P)); // set aflag
num = bitSet(num, S_BIT_POS, true);
return numberToBytesBE(num, Fp.BYTES);
}

@@ -1010,7 +1007,7 @@ else {

// 2x PUBLIC_KEY_LENGTH
const x = (0, utils_js_1.concatBytes)(new Uint8Array([0x40]), new Uint8Array(2 * Fp.BYTES - 1));
const x = concatB(new Uint8Array([0x40]), new Uint8Array(2 * Fp.BYTES - 1));
return x;
}
else {
return (0, utils_js_1.concatBytes)((0, utils_js_1.numberToBytesBE)(x, Fp.BYTES), (0, utils_js_1.numberToBytesBE)(y, Fp.BYTES));
return concatB(numberToBytesBE(x, Fp.BYTES), numberToBytesBE(y, Fp.BYTES));
}

@@ -1054,3 +1051,3 @@ }

isTorsionFree: (c, P) => {
return P.multiplyUnsafe(exports.bls12_381.CURVE.x).negate().equals(G2psi(c, P)); // ψ(P) == [u](P)
return P.multiplyUnsafe(bls12_381.CURVE.x).negate().equals(G2psi(c, P)); // ψ(P) == [u](P)
// Older version: https://eprint.iacr.org/2019/814.pdf

@@ -1065,3 +1062,3 @@ // Ψ²(P) => Ψ³(P) => [z]Ψ³(P) where z = -x => [z]Ψ³(P) - Ψ²(P) + P == O

clearCofactor: (c, P) => {
const { x } = exports.bls12_381.CURVE;
const { x } = bls12_381.CURVE;
let t1 = P.multiplyUnsafe(x).negate(); // [-x]P

@@ -1088,5 +1085,5 @@ let t2 = G2psi(c, P); // Ψ(P)

const L = Fp.BYTES;
const slc = (b, from, to) => (0, utils_js_1.bytesToNumberBE)(b.slice(from, to));
const slc = (b, from, to) => bytesToNumberBE(b.slice(from, to));
if (bytes.length === 96 && bitC) {
const { b } = exports.bls12_381.CURVE.G2;
const { b } = bls12_381.CURVE.G2;
const P = Fp.ORDER;

@@ -1131,15 +1128,15 @@ bytes[0] = bytes[0] & 0x1f; // clear flags

if (isZero)
return (0, utils_js_1.concatBytes)(COMPRESSED_ZERO, (0, utils_js_1.numberToBytesBE)(0n, Fp.BYTES));
return concatB(COMPRESSED_ZERO, numberToBytesBE(0n, Fp.BYTES));
const flag = Boolean(y.c1 === 0n ? (y.c0 * 2n) / P : (y.c1 * 2n) / P);
// set compressed & sign bits (looks like different offsets than for G1/Fp?)
let x_1 = (0, utils_js_1.bitSet)(x.c1, C_BIT_POS, flag);
x_1 = (0, utils_js_1.bitSet)(x_1, S_BIT_POS, true);
return (0, utils_js_1.concatBytes)((0, utils_js_1.numberToBytesBE)(x_1, Fp.BYTES), (0, utils_js_1.numberToBytesBE)(x.c0, Fp.BYTES));
let x_1 = bitSet(x.c1, C_BIT_POS, flag);
x_1 = bitSet(x_1, S_BIT_POS, true);
return concatB(numberToBytesBE(x_1, Fp.BYTES), numberToBytesBE(x.c0, Fp.BYTES));
}
else {
if (isZero)
return (0, utils_js_1.concatBytes)(new Uint8Array([0x40]), new Uint8Array(4 * Fp.BYTES - 1)); // bytes[0] |= 1 << 6;
return concatB(new Uint8Array([0x40]), new Uint8Array(4 * Fp.BYTES - 1)); // bytes[0] |= 1 << 6;
const { re: x0, im: x1 } = Fp2.reim(x);
const { re: y0, im: y1 } = Fp2.reim(y);
return (0, utils_js_1.concatBytes)((0, utils_js_1.numberToBytesBE)(x1, Fp.BYTES), (0, utils_js_1.numberToBytesBE)(x0, Fp.BYTES), (0, utils_js_1.numberToBytesBE)(y1, Fp.BYTES), (0, utils_js_1.numberToBytesBE)(y0, Fp.BYTES));
return concatB(numberToBytesBE(x1, Fp.BYTES), numberToBytesBE(x0, Fp.BYTES), numberToBytesBE(y1, Fp.BYTES), numberToBytesBE(y0, Fp.BYTES));
}

@@ -1150,3 +1147,3 @@ },

decode(hex) {
hex = (0, utils_js_1.ensureBytes)('signatureHex', hex);
hex = ensureBytes('signatureHex', hex);
const P = Fp.ORDER;

@@ -1156,12 +1153,12 @@ const half = hex.length / 2;

throw new Error('Invalid compressed signature length, must be 96 or 192');
const z1 = (0, utils_js_1.bytesToNumberBE)(hex.slice(0, half));
const z2 = (0, utils_js_1.bytesToNumberBE)(hex.slice(half));
const z1 = bytesToNumberBE(hex.slice(0, half));
const z2 = bytesToNumberBE(hex.slice(half));
// Indicates the infinity point
const bflag1 = (0, utils_js_1.bitGet)(z1, I_BIT_POS);
const bflag1 = bitGet(z1, I_BIT_POS);
if (bflag1 === 1n)
return exports.bls12_381.G2.ProjectivePoint.ZERO;
return bls12_381.G2.ProjectivePoint.ZERO;
const x1 = Fp.create(z1 & Fp.MASK);
const x2 = Fp.create(z2);
const x = Fp2.create({ c0: x2, c1: x1 });
const y2 = Fp2.add(Fp2.pow(x, 3n), exports.bls12_381.CURVE.G2.b); // y² = x³ + 4
const y2 = Fp2.add(Fp2.pow(x, 3n), bls12_381.CURVE.G2.b); // y² = x³ + 4
// The slow part

@@ -1174,3 +1171,3 @@ let y = Fp2.sqrt(y2);

const { re: y0, im: y1 } = Fp2.reim(y);
const aflag1 = (0, utils_js_1.bitGet)(z1, 381);
const aflag1 = bitGet(z1, 381);
const isGreater = y1 > 0n && (y1 * 2n) / P !== aflag1;

@@ -1180,3 +1177,3 @@ const isZero = y1 === 0n && (y0 * 2n) / P !== aflag1;

y = Fp2.neg(y);
const point = exports.bls12_381.G2.ProjectivePoint.fromAffine({ x, y });
const point = bls12_381.G2.ProjectivePoint.fromAffine({ x, y });
point.assertValidity();

@@ -1188,4 +1185,4 @@ return point;

point.assertValidity();
if (point.equals(exports.bls12_381.G2.ProjectivePoint.ZERO))
return (0, utils_js_1.concatBytes)(COMPRESSED_ZERO, (0, utils_js_1.numberToBytesBE)(0n, Fp.BYTES));
if (point.equals(bls12_381.G2.ProjectivePoint.ZERO))
return concatB(COMPRESSED_ZERO, numberToBytesBE(0n, Fp.BYTES));
const a = point.toAffine();

@@ -1196,5 +1193,5 @@ const { re: x0, im: x1 } = Fp2.reim(a.x);

const aflag1 = Boolean((tmp / Fp.ORDER) & 1n);
const z1 = (0, utils_js_1.bitSet)((0, utils_js_1.bitSet)(x1, 381, aflag1), S_BIT_POS, true);
const z1 = bitSet(bitSet(x1, 381, aflag1), S_BIT_POS, true);
const z2 = x0;
return (0, utils_js_1.concatBytes)((0, utils_js_1.numberToBytesBE)(z1, Fp.BYTES), (0, utils_js_1.numberToBytesBE)(z2, Fp.BYTES));
return concatB(numberToBytesBE(z1, Fp.BYTES), numberToBytesBE(z2, Fp.BYTES));
},

@@ -1206,5 +1203,5 @@ },

htfDefaults,
hash: sha256_1.sha256,
randomBytes: utils_1.randomBytes,
hash: sha256,
randomBytes,
});
//# sourceMappingURL=bls12-381.js.map

@@ -1,9 +0,6 @@

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.bn254 = void 0;
/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
const sha256_1 = require("@noble/hashes/sha256");
const weierstrass_js_1 = require("./abstract/weierstrass.js");
const _shortw_utils_js_1 = require("./_shortw_utils.js");
const modular_js_1 = require("./abstract/modular.js");
import { sha256 } from '@noble/hashes/sha256';
import { weierstrass } from './abstract/weierstrass.js';
import { getHash } from './_shortw_utils.js';
import { Fp } from './abstract/modular.js';
/**

@@ -15,6 +12,6 @@ * bn254 pairing-friendly curve.

*/
exports.bn254 = (0, weierstrass_js_1.weierstrass)({
export const bn254 = weierstrass({
a: BigInt(0),
b: BigInt(3),
Fp: (0, modular_js_1.Fp)(BigInt('0x30644e72e131a029b85045b68181585d97816a916871ca8d3c208c16d87cfd47')),
Fp: Fp(BigInt('0x30644e72e131a029b85045b68181585d97816a916871ca8d3c208c16d87cfd47')),
n: BigInt('0x30644e72e131a029b85045b68181585d2833e84879b9709143e1f593f0000001'),

@@ -24,4 +21,4 @@ Gx: BigInt(1),

h: BigInt(1),
...(0, _shortw_utils_js_1.getHash)(sha256_1.sha256),
...getHash(sha256),
});
//# sourceMappingURL=bn.js.map
import { ExtPointType } from './abstract/edwards.js';
import { Hex } from './abstract/utils.js';
import * as htf from './abstract/hash-to-curve.js';
import { AffinePoint } from './abstract/curve.js';
export declare const ED25519_TORSION_SUBGROUP: string[];

@@ -24,2 +25,3 @@ export declare const ed25519: import("./abstract/edwards.js").CurveFn;

constructor(ep: ExtendedPoint);
static fromAffine(ap: AffinePoint<bigint>): RistrettoPoint;
/**

@@ -52,2 +54,3 @@ * Takes uniform output of 64-bit hash function like sha512 and converts it to `RistrettoPoint`.

}
export declare const hash_to_ristretto255: (msg: Uint8Array, options: htf.htfBasicOpts) => RistrettoPoint;
//# sourceMappingURL=ed25519.d.ts.map

@@ -1,12 +0,9 @@

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.RistrettoPoint = exports.encodeToCurve = exports.hashToCurve = exports.x25519 = exports.ed25519ph = exports.ed25519ctx = exports.ed25519 = exports.ED25519_TORSION_SUBGROUP = void 0;
/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
const sha512_1 = require("@noble/hashes/sha512");
const utils_1 = require("@noble/hashes/utils");
const edwards_js_1 = require("./abstract/edwards.js");
const montgomery_js_1 = require("./abstract/montgomery.js");
const modular_js_1 = require("./abstract/modular.js");
const utils_js_1 = require("./abstract/utils.js");
const htf = require("./abstract/hash-to-curve.js");
import { sha512 } from '@noble/hashes/sha512';
import { concatBytes, randomBytes, utf8ToBytes } from '@noble/hashes/utils';
import { twistedEdwards } from './abstract/edwards.js';
import { montgomery } from './abstract/montgomery.js';
import { mod, pow2, isNegativeLE, Fp as Field, FpSqrtEven } from './abstract/modular.js';
import { equalBytes, bytesToHex, bytesToNumberLE, numberToBytesLE, ensureBytes, } from './abstract/utils.js';
import * as htf from './abstract/hash-to-curve.js';
/**

@@ -29,12 +26,12 @@ * ed25519 Twisted Edwards curve with following addons:

const b2 = (x2 * x) % P; // x^3, 11
const b4 = ((0, modular_js_1.pow2)(b2, _2n, P) * b2) % P; // x^15, 1111
const b5 = ((0, modular_js_1.pow2)(b4, _1n, P) * x) % P; // x^31
const b10 = ((0, modular_js_1.pow2)(b5, _5n, P) * b5) % P;
const b20 = ((0, modular_js_1.pow2)(b10, _10n, P) * b10) % P;
const b40 = ((0, modular_js_1.pow2)(b20, _20n, P) * b20) % P;
const b80 = ((0, modular_js_1.pow2)(b40, _40n, P) * b40) % P;
const b160 = ((0, modular_js_1.pow2)(b80, _80n, P) * b80) % P;
const b240 = ((0, modular_js_1.pow2)(b160, _80n, P) * b80) % P;
const b250 = ((0, modular_js_1.pow2)(b240, _10n, P) * b10) % P;
const pow_p_5_8 = ((0, modular_js_1.pow2)(b250, _2n, P) * x) % P;
const b4 = (pow2(b2, _2n, P) * b2) % P; // x^15, 1111
const b5 = (pow2(b4, _1n, P) * x) % P; // x^31
const b10 = (pow2(b5, _5n, P) * b5) % P;
const b20 = (pow2(b10, _10n, P) * b10) % P;
const b40 = (pow2(b20, _20n, P) * b20) % P;
const b80 = (pow2(b40, _40n, P) * b40) % P;
const b160 = (pow2(b80, _80n, P) * b80) % P;
const b240 = (pow2(b160, _80n, P) * b80) % P;
const b250 = (pow2(b240, _10n, P) * b10) % P;
const pow_p_5_8 = (pow2(b250, _2n, P) * x) % P;
// ^ To pow to (p+3)/8, multiply it by x.

@@ -56,13 +53,13 @@ return { pow_p_5_8, b2 };

const P = ED25519_P;
const v3 = (0, modular_js_1.mod)(v * v * v, P); // v³
const v7 = (0, modular_js_1.mod)(v3 * v3 * v, P); // v⁷
const v3 = mod(v * v * v, P); // v³
const v7 = mod(v3 * v3 * v, P); // v⁷
// (p+3)/8 and (p-5)/8
const pow = ed25519_pow_2_252_3(u * v7).pow_p_5_8;
let x = (0, modular_js_1.mod)(u * v3 * pow, P); // (uv³)(uv⁷)^(p-5)/8
const vx2 = (0, modular_js_1.mod)(v * x * x, P); // vx²
let x = mod(u * v3 * pow, P); // (uv³)(uv⁷)^(p-5)/8
const vx2 = mod(v * x * x, P); // vx²
const root1 = x; // First root candidate
const root2 = (0, modular_js_1.mod)(x * ED25519_SQRT_M1, P); // Second root candidate
const root2 = mod(x * ED25519_SQRT_M1, P); // Second root candidate
const useRoot1 = vx2 === u; // If vx² = u (mod p), x is a square root
const useRoot2 = vx2 === (0, modular_js_1.mod)(-u, P); // If vx² = -u, set x <-- x * 2^((p-1)/4)
const noRoot = vx2 === (0, modular_js_1.mod)(-u * ED25519_SQRT_M1, P); // There is no valid root, vx² = -u√(-1)
const useRoot2 = vx2 === mod(-u, P); // If vx² = -u, set x <-- x * 2^((p-1)/4)
const noRoot = vx2 === mod(-u * ED25519_SQRT_M1, P); // There is no valid root, vx² = -u√(-1)
if (useRoot1)

@@ -72,8 +69,8 @@ x = root1;

x = root2; // We return root2 anyway, for const-time
if ((0, modular_js_1.isNegativeLE)(x, P))
x = (0, modular_js_1.mod)(-x, P);
if (isNegativeLE(x, P))
x = mod(-x, P);
return { isValid: useRoot1 || useRoot2, value: x };
}
// Just in case
exports.ED25519_TORSION_SUBGROUP = [
export const ED25519_TORSION_SUBGROUP = [
'0100000000000000000000000000000000000000000000000000000000000000',

@@ -88,3 +85,3 @@ 'c7176a703d4dd84fba3c0b760d10670f2a2053fa2c39ccc64ec7fd7792ac037a',

];
const Fp = (0, modular_js_1.Fp)(ED25519_P, undefined, true);
const Fp = Field(ED25519_P, undefined, true);
const ED25519_DEF = {

@@ -106,4 +103,4 @@ // Param: a

Gy: BigInt('46316835694926478169428394003475163141307993866256225615783033603165251855960'),
hash: sha512_1.sha512,
randomBytes: utils_1.randomBytes,
hash: sha512,
randomBytes,
adjustScalarBytes,

@@ -115,15 +112,15 @@ // dom2

};
exports.ed25519 = (0, edwards_js_1.twistedEdwards)(ED25519_DEF);
export const ed25519 = twistedEdwards(ED25519_DEF);
function ed25519_domain(data, ctx, phflag) {
if (ctx.length > 255)
throw new Error('Context is too big');
return (0, utils_1.concatBytes)((0, utils_1.utf8ToBytes)('SigEd25519 no Ed25519 collisions'), new Uint8Array([phflag ? 1 : 0, ctx.length]), ctx, data);
return concatBytes(utf8ToBytes('SigEd25519 no Ed25519 collisions'), new Uint8Array([phflag ? 1 : 0, ctx.length]), ctx, data);
}
exports.ed25519ctx = (0, edwards_js_1.twistedEdwards)({ ...ED25519_DEF, domain: ed25519_domain });
exports.ed25519ph = (0, edwards_js_1.twistedEdwards)({
export const ed25519ctx = twistedEdwards({ ...ED25519_DEF, domain: ed25519_domain });
export const ed25519ph = twistedEdwards({
...ED25519_DEF,
domain: ed25519_domain,
preHash: sha512_1.sha512,
preHash: sha512,
});
exports.x25519 = (0, montgomery_js_1.montgomery)({
export const x25519 = montgomery({
P: ED25519_P,

@@ -138,6 +135,6 @@ a: BigInt(486662),

const { pow_p_5_8, b2 } = ed25519_pow_2_252_3(x);
return (0, modular_js_1.mod)((0, modular_js_1.pow2)(pow_p_5_8, BigInt(3), P) * b2, P);
return mod(pow2(pow_p_5_8, BigInt(3), P) * b2, P);
},
adjustScalarBytes,
randomBytes: utils_1.randomBytes,
randomBytes,
});

@@ -194,3 +191,3 @@ // Hash To Curve Elligator2 Map (NOTE: different from ristretto255 elligator)

}
const ELL2_C1_EDWARDS = (0, modular_js_1.FpSqrtEven)(Fp, Fp.neg(BigInt(486664))); // sgn0(c1) MUST equal 0
const ELL2_C1_EDWARDS = FpSqrtEven(Fp, Fp.neg(BigInt(486664))); // sgn0(c1) MUST equal 0
function map_to_curve_elligator2_edwards25519(u) {

@@ -212,3 +209,3 @@ const { xMn, xMd, yMn, yMd } = map_to_curve_elligator2_curve25519(u); // 1. (xMn, xMd, yMn, yMd) = map_to_curve_elligator2_curve25519(u)

}
const { hashToCurve, encodeToCurve } = htf.createHasher(exports.ed25519.ExtendedPoint, (scalars) => map_to_curve_elligator2_edwards25519(scalars[0]), {
const { hashToCurve, encodeToCurve } = htf.createHasher(ed25519.ExtendedPoint, (scalars) => map_to_curve_elligator2_edwards25519(scalars[0]), {
DST: 'edwards25519_XMD:SHA-512_ELL2_RO_',

@@ -220,6 +217,5 @@ encodeDST: 'edwards25519_XMD:SHA-512_ELL2_NU_',

expand: 'xmd',
hash: sha512_1.sha512,
hash: sha512,
});
exports.hashToCurve = hashToCurve;
exports.encodeToCurve = encodeToCurve;
export { hashToCurve, encodeToCurve };
function assertRstPoint(other) {

@@ -242,9 +238,9 @@ if (!(other instanceof RistrettoPoint))

const MAX_255B = BigInt('0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff');
const bytes255ToNumberLE = (bytes) => exports.ed25519.CURVE.Fp.create((0, utils_js_1.bytesToNumberLE)(bytes) & MAX_255B);
const bytes255ToNumberLE = (bytes) => ed25519.CURVE.Fp.create(bytesToNumberLE(bytes) & MAX_255B);
// Computes Elligator map for Ristretto
// https://ristretto.group/formulas/elligator.html
function calcElligatorRistrettoMap(r0) {
const { d } = exports.ed25519.CURVE;
const P = exports.ed25519.CURVE.Fp.ORDER;
const mod = exports.ed25519.CURVE.Fp.create;
const { d } = ed25519.CURVE;
const P = ed25519.CURVE.Fp.ORDER;
const mod = ed25519.CURVE.Fp.create;
const r = mod(SQRT_M1 * r0 * r0); // 1

@@ -256,3 +252,3 @@ const Ns = mod((r + _1n) * ONE_MINUS_D_SQ); // 2

let s_ = mod(s * r0); // 6
if (!(0, modular_js_1.isNegativeLE)(s_, P))
if (!isNegativeLE(s_, P))
s_ = mod(-s_);

@@ -269,3 +265,3 @@ if (!Ns_D_is_sq)

const W3 = mod(_1n + s2); // 13
return new exports.ed25519.ExtendedPoint(mod(W0 * W3), mod(W2 * W1), mod(W1 * W3), mod(W0 * W2));
return new ed25519.ExtendedPoint(mod(W0 * W3), mod(W2 * W1), mod(W1 * W3), mod(W0 * W2));
}

@@ -279,3 +275,3 @@ /**

*/
class RistrettoPoint {
export class RistrettoPoint {
// Private property to discourage combining ExtendedPoint + RistrettoPoint

@@ -286,2 +282,5 @@ // Always use Ristretto encoding/decoding instead.

}
static fromAffine(ap) {
return new RistrettoPoint(ed25519.ExtendedPoint.fromAffine(ap));
}
/**

@@ -295,3 +294,3 @@ * Takes uniform output of 64-bit hash function like sha512 and converts it to `RistrettoPoint`.

static hashToCurve(hex) {
hex = (0, utils_js_1.ensureBytes)('ristrettoHash', hex, 64);
hex = ensureBytes('ristrettoHash', hex, 64);
const r1 = bytes255ToNumberLE(hex.slice(0, 32));

@@ -309,6 +308,6 @@ const R1 = calcElligatorRistrettoMap(r1);

static fromHex(hex) {
hex = (0, utils_js_1.ensureBytes)('ristrettoHex', hex, 32);
const { a, d } = exports.ed25519.CURVE;
const P = exports.ed25519.CURVE.Fp.ORDER;
const mod = exports.ed25519.CURVE.Fp.create;
hex = ensureBytes('ristrettoHex', hex, 32);
const { a, d } = ed25519.CURVE;
const P = ed25519.CURVE.Fp.ORDER;
const mod = ed25519.CURVE.Fp.create;
const emsg = 'RistrettoPoint.fromHex: the hex is not valid encoding of RistrettoPoint';

@@ -318,3 +317,3 @@ const s = bytes255ToNumberLE(hex);

// 3. Check that s is non-negative, or else abort
if (!(0, utils_js_1.equalBytes)((0, utils_js_1.numberToBytesLE)(s, 32), hex) || (0, modular_js_1.isNegativeLE)(s, P))
if (!equalBytes(numberToBytesLE(s, 32), hex) || isNegativeLE(s, P))
throw new Error(emsg);

@@ -331,9 +330,9 @@ const s2 = mod(s * s);

let x = mod((s + s) * Dx); // 10
if ((0, modular_js_1.isNegativeLE)(x, P))
if (isNegativeLE(x, P))
x = mod(-x); // 10
const y = mod(u1 * Dy); // 11
const t = mod(x * y); // 12
if (!isValid || (0, modular_js_1.isNegativeLE)(t, P) || y === _0n)
if (!isValid || isNegativeLE(t, P) || y === _0n)
throw new Error(emsg);
return new RistrettoPoint(new exports.ed25519.ExtendedPoint(x, y, _1n, t));
return new RistrettoPoint(new ed25519.ExtendedPoint(x, y, _1n, t));
}

@@ -346,4 +345,4 @@ /**

let { ex: x, ey: y, ez: z, et: t } = this.ep;
const P = exports.ed25519.CURVE.Fp.ORDER;
const mod = exports.ed25519.CURVE.Fp.create;
const P = ed25519.CURVE.Fp.ORDER;
const mod = ed25519.CURVE.Fp.create;
const u1 = mod(mod(z + y) * mod(z - y)); // 1

@@ -358,3 +357,3 @@ const u2 = mod(x * y); // 2

let D; // 7
if ((0, modular_js_1.isNegativeLE)(t * zInv, P)) {
if (isNegativeLE(t * zInv, P)) {
let _x = mod(y * SQRT_M1);

@@ -369,11 +368,11 @@ let _y = mod(x * SQRT_M1);

}
if ((0, modular_js_1.isNegativeLE)(x * zInv, P))
if (isNegativeLE(x * zInv, P))
y = mod(-y); // 9
let s = mod((z - y) * D); // 10 (check footer's note, no sqrt(-a))
if ((0, modular_js_1.isNegativeLE)(s, P))
if (isNegativeLE(s, P))
s = mod(-s);
return (0, utils_js_1.numberToBytesLE)(s, 32); // 11
return numberToBytesLE(s, 32); // 11
}
toHex() {
return (0, utils_js_1.bytesToHex)(this.toRawBytes());
return bytesToHex(this.toRawBytes());
}

@@ -387,4 +386,4 @@ toString() {

const { ex: X1, ey: Y1 } = this.ep;
const { ex: X2, ey: Y2 } = this.ep;
const mod = exports.ed25519.CURVE.Fp.create;
const { ex: X2, ey: Y2 } = other.ep;
const mod = ed25519.CURVE.Fp.create;
// (x1 * y2 == y1 * x2) | (y1 * y2 == x1 * x2)

@@ -410,5 +409,13 @@ const one = mod(X1 * Y2) === mod(Y1 * X2);

}
exports.RistrettoPoint = RistrettoPoint;
RistrettoPoint.BASE = new RistrettoPoint(exports.ed25519.ExtendedPoint.BASE);
RistrettoPoint.ZERO = new RistrettoPoint(exports.ed25519.ExtendedPoint.ZERO);
RistrettoPoint.BASE = new RistrettoPoint(ed25519.ExtendedPoint.BASE);
RistrettoPoint.ZERO = new RistrettoPoint(ed25519.ExtendedPoint.ZERO);
// https://datatracker.ietf.org/doc/draft-irtf-cfrg-hash-to-curve/14/
// Appendix B. Hashing to ristretto255
export const hash_to_ristretto255 = (msg, options) => {
const d = options.DST;
const DST = typeof d === 'string' ? utf8ToBytes(d) : d;
const uniform_bytes = htf.expand_message_xmd(msg, DST, 64, sha512);
const P = RistrettoPoint.hashToCurve(uniform_bytes);
return P;
};
//# sourceMappingURL=ed25519.js.map

@@ -1,11 +0,8 @@

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.encodeToCurve = exports.hashToCurve = exports.x448 = exports.ed448ph = exports.ed448 = void 0;
/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
const sha3_1 = require("@noble/hashes/sha3");
const utils_1 = require("@noble/hashes/utils");
const edwards_js_1 = require("./abstract/edwards.js");
const modular_js_1 = require("./abstract/modular.js");
const montgomery_js_1 = require("./abstract/montgomery.js");
const htf = require("./abstract/hash-to-curve.js");
import { shake256 } from '@noble/hashes/sha3';
import { concatBytes, randomBytes, utf8ToBytes, wrapConstructor } from '@noble/hashes/utils';
import { twistedEdwards } from './abstract/edwards.js';
import { mod, pow2, Fp as Field } from './abstract/modular.js';
import { montgomery } from './abstract/montgomery.js';
import * as htf from './abstract/hash-to-curve.js';
/**

@@ -16,4 +13,4 @@ * Edwards448 (not Ed448-Goldilocks) curve with following addons:

*/
const shake256_114 = (0, utils_1.wrapConstructor)(() => sha3_1.shake256.create({ dkLen: 114 }));
const shake256_64 = (0, utils_1.wrapConstructor)(() => sha3_1.shake256.create({ dkLen: 64 }));
const shake256_114 = wrapConstructor(() => shake256.create({ dkLen: 114 }));
const shake256_64 = wrapConstructor(() => shake256.create({ dkLen: 64 }));
const ed448P = BigInt('726838724295606890549323807888004534353641360687318060281490199180612328166730772686396383698676545930088884461843637361053498018365439');

@@ -31,13 +28,13 @@ // powPminus3div4 calculates z = x^k mod p, where k = (p-3)/4.

const b3 = (b2 * b2 * x) % P;
const b6 = ((0, modular_js_1.pow2)(b3, _3n, P) * b3) % P;
const b9 = ((0, modular_js_1.pow2)(b6, _3n, P) * b3) % P;
const b11 = ((0, modular_js_1.pow2)(b9, _2n, P) * b2) % P;
const b22 = ((0, modular_js_1.pow2)(b11, _11n, P) * b11) % P;
const b44 = ((0, modular_js_1.pow2)(b22, _22n, P) * b22) % P;
const b88 = ((0, modular_js_1.pow2)(b44, _44n, P) * b44) % P;
const b176 = ((0, modular_js_1.pow2)(b88, _88n, P) * b88) % P;
const b220 = ((0, modular_js_1.pow2)(b176, _44n, P) * b44) % P;
const b222 = ((0, modular_js_1.pow2)(b220, _2n, P) * b2) % P;
const b223 = ((0, modular_js_1.pow2)(b222, _1n, P) * x) % P;
return ((0, modular_js_1.pow2)(b223, _223n, P) * b222) % P;
const b6 = (pow2(b3, _3n, P) * b3) % P;
const b9 = (pow2(b6, _3n, P) * b3) % P;
const b11 = (pow2(b9, _2n, 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 b222 = (pow2(b220, _2n, P) * b2) % P;
const b223 = (pow2(b222, _1n, P) * x) % P;
return (pow2(b223, _223n, P) * b222) % P;
}

@@ -54,3 +51,3 @@ function adjustScalarBytes(bytes) {

}
const Fp = (0, modular_js_1.Fp)(ed448P, 456, true);
const Fp = Field(ed448P, 456, true);
const ED448_DEF = {

@@ -74,3 +71,3 @@ // Param: a

hash: shake256_114,
randomBytes: utils_1.randomBytes,
randomBytes,
adjustScalarBytes,

@@ -81,3 +78,3 @@ // dom4

throw new Error(`Context is too big: ${ctx.length}`);
return (0, utils_1.concatBytes)((0, utils_1.utf8ToBytes)('SigEd448'), new Uint8Array([phflag ? 1 : 0, ctx.length]), ctx, data);
return concatBytes(utf8ToBytes('SigEd448'), new Uint8Array([phflag ? 1 : 0, ctx.length]), ctx, data);
},

@@ -94,18 +91,18 @@ // Constant-time ratio of u to v. Allows to combine inversion and square root u/√v.

// x = (u/v)^((p+1)/4) = u³v(u⁵v³)^((p-3)/4) (mod p)
const u2v = (0, modular_js_1.mod)(u * u * v, P); // u²v
const u3v = (0, modular_js_1.mod)(u2v * u, P); // u³v
const u5v3 = (0, modular_js_1.mod)(u3v * u2v * v, P); // u⁵v³
const u2v = mod(u * u * v, P); // u²v
const u3v = mod(u2v * u, P); // u³v
const u5v3 = mod(u3v * u2v * v, P); // u⁵v³
const root = ed448_pow_Pminus3div4(u5v3);
const x = (0, modular_js_1.mod)(u3v * root, P);
const x = mod(u3v * root, P);
// Verify that root is exists
const x2 = (0, modular_js_1.mod)(x * x, P); // x²
const x2 = mod(x * x, P); // x²
// If vx² = u, the recovered x-coordinate is x. Otherwise, no
// square root exists, and the decoding fails.
return { isValid: (0, modular_js_1.mod)(x2 * v, P) === u, value: x };
return { isValid: mod(x2 * v, P) === u, value: x };
},
};
exports.ed448 = (0, edwards_js_1.twistedEdwards)(ED448_DEF);
export const ed448 = twistedEdwards(ED448_DEF);
// NOTE: there is no ed448ctx, since ed448 supports ctx by default
exports.ed448ph = (0, edwards_js_1.twistedEdwards)({ ...ED448_DEF, preHash: shake256_64 });
exports.x448 = (0, montgomery_js_1.montgomery)({
export const ed448ph = twistedEdwards({ ...ED448_DEF, preHash: shake256_64 });
export const x448 = montgomery({
a: BigInt(156326),

@@ -119,7 +116,7 @@ montgomeryBits: 448,

const Pminus3div4 = ed448_pow_Pminus3div4(x);
const Pminus3 = (0, modular_js_1.pow2)(Pminus3div4, BigInt(2), P);
return (0, modular_js_1.mod)(Pminus3 * x, P); // Pminus3 * x = Pminus2
const Pminus3 = pow2(Pminus3div4, BigInt(2), P);
return mod(Pminus3 * x, P); // Pminus3 * x = Pminus2
},
adjustScalarBytes,
randomBytes: utils_1.randomBytes,
randomBytes,
// The 4-isogeny maps between the Montgomery curve and this Edwards

@@ -213,3 +210,3 @@ // curve are:

}
const { hashToCurve, encodeToCurve } = htf.createHasher(exports.ed448.ExtendedPoint, (scalars) => map_to_curve_elligator2_edwards448(scalars[0]), {
const { hashToCurve, encodeToCurve } = htf.createHasher(ed448.ExtendedPoint, (scalars) => map_to_curve_elligator2_edwards448(scalars[0]), {
DST: 'edwards448_XOF:SHAKE256_ELL2_RO_',

@@ -221,6 +218,5 @@ encodeDST: 'edwards448_XOF:SHAKE256_ELL2_NU_',

expand: 'xof',
hash: sha3_1.shake256,
hash: shake256,
});
exports.hashToCurve = hashToCurve;
exports.encodeToCurve = encodeToCurve;
export { hashToCurve, encodeToCurve };
//# sourceMappingURL=ed448.js.map

@@ -1,10 +0,7 @@

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.findGroupHash = exports.groupHash = exports.jubjub = void 0;
/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
const sha512_1 = require("@noble/hashes/sha512");
const utils_1 = require("@noble/hashes/utils");
const edwards_js_1 = require("./abstract/edwards.js");
const blake2s_1 = require("@noble/hashes/blake2s");
const modular_js_1 = require("./abstract/modular.js");
import { sha512 } from '@noble/hashes/sha512';
import { concatBytes, randomBytes, utf8ToBytes } from '@noble/hashes/utils';
import { twistedEdwards } from './abstract/edwards.js';
import { blake2s } from '@noble/hashes/blake2s';
import { Fp } from './abstract/modular.js';
/**

@@ -15,3 +12,3 @@ * jubjub Twisted Edwards curve.

*/
exports.jubjub = (0, edwards_js_1.twistedEdwards)({
export const jubjub = twistedEdwards({
// Params: a, d

@@ -22,3 +19,3 @@ a: BigInt('0x73eda753299d7d483339d80809a1d80553bda402fffe5bfeffffffff00000000'),

// Same value as bls12-381 Fr (not Fp)
Fp: (0, modular_js_1.Fp)(BigInt('0x73eda753299d7d483339d80809a1d80553bda402fffe5bfeffffffff00000001')),
Fp: Fp(BigInt('0x73eda753299d7d483339d80809a1d80553bda402fffe5bfeffffffff00000001')),
// Subgroup order: how many points curve has

@@ -31,22 +28,21 @@ n: BigInt('0xe7db4ea6533afa906673b0101343b00a6682093ccc81082d0970e5ed6f72cb7'),

Gy: BigInt('0x1d523cf1ddab1a1793132e78c866c0c33e26ba5cc220fed7cc3f870e59d292aa'),
hash: sha512_1.sha512,
randomBytes: utils_1.randomBytes,
hash: sha512,
randomBytes,
});
const GH_FIRST_BLOCK = (0, utils_1.utf8ToBytes)('096b36a5804bfacef1691e173c366a47ff5ba84a44f26ddd7e8d9f79d5b42df0');
const GH_FIRST_BLOCK = utf8ToBytes('096b36a5804bfacef1691e173c366a47ff5ba84a44f26ddd7e8d9f79d5b42df0');
// Returns point at JubJub curve which is prime order and not zero
function groupHash(tag, personalization) {
const h = blake2s_1.blake2s.create({ personalization, dkLen: 32 });
export function groupHash(tag, personalization) {
const h = blake2s.create({ personalization, dkLen: 32 });
h.update(GH_FIRST_BLOCK);
h.update(tag);
// NOTE: returns ExtendedPoint, in case it will be multiplied later
let p = exports.jubjub.ExtendedPoint.fromHex(h.digest());
let p = jubjub.ExtendedPoint.fromHex(h.digest());
// NOTE: cannot replace with isSmallOrder, returns Point*8
p = p.multiply(exports.jubjub.CURVE.h);
if (p.equals(exports.jubjub.ExtendedPoint.ZERO))
p = p.multiply(jubjub.CURVE.h);
if (p.equals(jubjub.ExtendedPoint.ZERO))
throw new Error('Point has small order');
return p;
}
exports.groupHash = groupHash;
function findGroupHash(m, personalization) {
const tag = (0, utils_1.concatBytes)(m, new Uint8Array([0]));
export function findGroupHash(m, personalization) {
const tag = concatBytes(m, new Uint8Array([0]));
for (let i = 0; i < 256; i++) {

@@ -61,3 +57,2 @@ tag[tag.length - 1] = i;

}
exports.findGroupHash = findGroupHash;
//# sourceMappingURL=jubjub.js.map

@@ -1,17 +0,14 @@

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.encodeToCurve = exports.hashToCurve = exports.secp256r1 = exports.P256 = void 0;
/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
const _shortw_utils_js_1 = require("./_shortw_utils.js");
const sha256_1 = require("@noble/hashes/sha256");
const modular_js_1 = require("./abstract/modular.js");
const weierstrass_js_1 = require("./abstract/weierstrass.js");
const htf = require("./abstract/hash-to-curve.js");
import { createCurve } from './_shortw_utils.js';
import { sha256 } from '@noble/hashes/sha256';
import { Fp as Field } from './abstract/modular.js';
import { mapToCurveSimpleSWU } from './abstract/weierstrass.js';
import * as htf from './abstract/hash-to-curve.js';
// NIST secp256r1 aka P256
// https://www.secg.org/sec2-v2.pdf, https://neuromancer.sk/std/nist/P-256
// Field over which we'll do calculations; 2n**224n * (2n**32n-1n) + 2n**192n + 2n**96n-1n
const Fp = (0, modular_js_1.Fp)(BigInt('0xffffffff00000001000000000000000000000000ffffffffffffffffffffffff'));
const Fp = Field(BigInt('0xffffffff00000001000000000000000000000000ffffffffffffffffffffffff'));
const CURVE_A = Fp.create(BigInt('-3'));
const CURVE_B = BigInt('0x5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b');
const mapSWU = (0, weierstrass_js_1.mapToCurveSimpleSWU)(Fp, {
const mapSWU = mapToCurveSimpleSWU(Fp, {
A: CURVE_A,

@@ -21,3 +18,3 @@ B: CURVE_B,

});
exports.P256 = (0, _shortw_utils_js_1.createCurve)({
export const P256 = createCurve({
// Params: a, b

@@ -34,5 +31,5 @@ a: CURVE_A,

lowS: false,
}, sha256_1.sha256);
exports.secp256r1 = exports.P256;
const { hashToCurve, encodeToCurve } = htf.createHasher(exports.secp256r1.ProjectivePoint, (scalars) => mapSWU(scalars[0]), {
}, sha256);
export const secp256r1 = P256;
const { hashToCurve, encodeToCurve } = htf.createHasher(secp256r1.ProjectivePoint, (scalars) => mapSWU(scalars[0]), {
DST: 'P256_XMD:SHA-256_SSWU_RO_',

@@ -44,6 +41,5 @@ encodeDST: 'P256_XMD:SHA-256_SSWU_NU_',

expand: 'xmd',
hash: sha256_1.sha256,
hash: sha256,
});
exports.hashToCurve = hashToCurve;
exports.encodeToCurve = encodeToCurve;
export { hashToCurve, encodeToCurve };
//# sourceMappingURL=p256.js.map

@@ -1,10 +0,7 @@

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.encodeToCurve = exports.hashToCurve = exports.secp384r1 = exports.P384 = void 0;
/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
const _shortw_utils_js_1 = require("./_shortw_utils.js");
const sha512_1 = require("@noble/hashes/sha512");
const modular_js_1 = require("./abstract/modular.js");
const weierstrass_js_1 = require("./abstract/weierstrass.js");
const htf = require("./abstract/hash-to-curve.js");
import { createCurve } from './_shortw_utils.js';
import { sha384 } from '@noble/hashes/sha512';
import { Fp as Field } from './abstract/modular.js';
import { mapToCurveSimpleSWU } from './abstract/weierstrass.js';
import * as htf from './abstract/hash-to-curve.js';
// NIST secp384r1 aka P384

@@ -15,7 +12,7 @@ // https://www.secg.org/sec2-v2.pdf, https://neuromancer.sk/std/nist/P-384

const P = BigInt('0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffeffffffff0000000000000000ffffffff');
const Fp = (0, modular_js_1.Fp)(P);
const Fp = Field(P);
const CURVE_A = Fp.create(BigInt('-3'));
// prettier-ignore
const CURVE_B = BigInt('0xb3312fa7e23ee7e4988e056be3f82d19181d9c6efe8141120314088f5013875ac656398d8a2ed19d2a85c8edd3ec2aef');
const mapSWU = (0, weierstrass_js_1.mapToCurveSimpleSWU)(Fp, {
const mapSWU = mapToCurveSimpleSWU(Fp, {
A: CURVE_A,

@@ -26,3 +23,3 @@ B: CURVE_B,

// prettier-ignore
exports.P384 = (0, _shortw_utils_js_1.createCurve)({
export const P384 = createCurve({
// Params: a, b

@@ -40,5 +37,5 @@ a: CURVE_A,

lowS: false,
}, sha512_1.sha384);
exports.secp384r1 = exports.P384;
const { hashToCurve, encodeToCurve } = htf.createHasher(exports.secp384r1.ProjectivePoint, (scalars) => mapSWU(scalars[0]), {
}, sha384);
export const secp384r1 = P384;
const { hashToCurve, encodeToCurve } = htf.createHasher(secp384r1.ProjectivePoint, (scalars) => mapSWU(scalars[0]), {
DST: 'P384_XMD:SHA-384_SSWU_RO_',

@@ -50,6 +47,5 @@ encodeDST: 'P384_XMD:SHA-384_SSWU_NU_',

expand: 'xmd',
hash: sha512_1.sha384,
hash: sha384,
});
exports.hashToCurve = hashToCurve;
exports.encodeToCurve = encodeToCurve;
export { hashToCurve, encodeToCurve };
//# sourceMappingURL=p384.js.map

@@ -1,10 +0,7 @@

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.encodeToCurve = exports.hashToCurve = exports.secp521r1 = exports.P521 = void 0;
/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
const _shortw_utils_js_1 = require("./_shortw_utils.js");
const sha512_1 = require("@noble/hashes/sha512");
const modular_js_1 = require("./abstract/modular.js");
const weierstrass_js_1 = require("./abstract/weierstrass.js");
const htf = require("./abstract/hash-to-curve.js");
import { createCurve } from './_shortw_utils.js';
import { sha512 } from '@noble/hashes/sha512';
import { Fp as Field } from './abstract/modular.js';
import { mapToCurveSimpleSWU } from './abstract/weierstrass.js';
import * as htf from './abstract/hash-to-curve.js';
// NIST secp521r1 aka P521

@@ -16,7 +13,7 @@ // Note that it's 521, which differs from 512 of its hash function.

const P = BigInt('0x1ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff');
const Fp = (0, modular_js_1.Fp)(P);
const Fp = Field(P);
const CURVE_A = Fp.create(BigInt('-3'));
// prettier-ignore
const CURVE_B = BigInt('0x0051953eb9618e1c9a1f929a21a0b68540eea2da725b99b315f3b8b489918ef109e156193951ec7e937b1652c0bd3bb1bf073573df883d2c34f1ef451fd46b503f00');
const mapSWU = (0, weierstrass_js_1.mapToCurveSimpleSWU)(Fp, {
const mapSWU = mapToCurveSimpleSWU(Fp, {
A: CURVE_A,

@@ -27,3 +24,3 @@ B: CURVE_B,

// prettier-ignore
exports.P521 = (0, _shortw_utils_js_1.createCurve)({
export const P521 = createCurve({
// Params: a, b

@@ -41,5 +38,5 @@ a: CURVE_A,

allowedPrivateKeyLengths: [130, 131, 132] // P521 keys are variable-length. Normalize to 132b
}, sha512_1.sha512);
exports.secp521r1 = exports.P521;
const { hashToCurve, encodeToCurve } = htf.createHasher(exports.secp521r1.ProjectivePoint, (scalars) => mapSWU(scalars[0]), {
}, sha512);
export const secp521r1 = P521;
const { hashToCurve, encodeToCurve } = htf.createHasher(secp521r1.ProjectivePoint, (scalars) => mapSWU(scalars[0]), {
DST: 'P521_XMD:SHA-512_SSWU_RO_',

@@ -51,6 +48,5 @@ encodeDST: 'P521_XMD:SHA-512_SSWU_NU_',

expand: 'xmd',
hash: sha512_1.sha512,
hash: sha512,
});
exports.hashToCurve = hashToCurve;
exports.encodeToCurve = encodeToCurve;
export { hashToCurve, encodeToCurve };
//# sourceMappingURL=p521.js.map
{
"name": "@noble/curves",
"version": "0.7.3",
"version": "0.8.0",
"description": "Minimal, auditable JS implementation of elliptic curve cryptography",
"files": [
"abstract",
"esm",
"src",

@@ -16,3 +15,4 @@ "*.js",

"bench": "cd benchmark; node secp256k1.js; node curves.js; node ecdh.js; node stark.js; node bls.js",
"build": "tsc && tsc -p tsconfig.esm.json",
"build": "tsc",
"build:clean": "rm *.{js,d.ts,js.map} esm/*.{js,js.map} 2> /dev/null",
"build:release": "rollup -c rollup.config.js",

@@ -44,6 +44,6 @@ "lint": "prettier --check 'src/**/*.{js,ts}' 'test/*.js'",

"main": "index.js",
"type": "module",
"exports": {
".": {
"types": "./index.d.ts",
"import": "./esm/index.js",
"default": "./index.js"

@@ -53,3 +53,2 @@ },

"types": "./abstract/edwards.d.ts",
"import": "./esm/abstract/edwards.js",
"default": "./abstract/edwards.js"

@@ -59,3 +58,2 @@ },

"types": "./abstract/modular.d.ts",
"import": "./esm/abstract/modular.js",
"default": "./abstract/modular.js"

@@ -65,3 +63,2 @@ },

"types": "./abstract/montgomery.d.ts",
"import": "./esm/abstract/montgomery.js",
"default": "./abstract/montgomery.js"

@@ -71,3 +68,2 @@ },

"types": "./abstract/weierstrass.d.ts",
"import": "./esm/abstract/weierstrass.js",
"default": "./abstract/weierstrass.js"

@@ -77,3 +73,2 @@ },

"types": "./abstract/bls.d.ts",
"import": "./esm/abstract/bls.js",
"default": "./abstract/bls.js"

@@ -83,3 +78,2 @@ },

"types": "./abstract/hash-to-curve.d.ts",
"import": "./esm/abstract/hash-to-curve.js",
"default": "./abstract/hash-to-curve.js"

@@ -89,3 +83,2 @@ },

"types": "./abstract/curve.d.ts",
"import": "./esm/abstract/curve.js",
"default": "./abstract/curve.js"

@@ -95,3 +88,2 @@ },

"types": "./abstract/utils.d.ts",
"import": "./esm/abstract/utils.js",
"default": "./abstract/utils.js"

@@ -101,3 +93,2 @@ },

"types": "./abstract/poseidon.d.ts",
"import": "./esm/abstract/poseidon.js",
"default": "./abstract/poseidon.js"

@@ -107,3 +98,2 @@ },

"types": "./_shortw_utils.d.ts",
"import": "./esm/_shortw_utils.js",
"default": "./_shortw_utils.js"

@@ -113,3 +103,2 @@ },

"types": "./bls12-381.d.ts",
"import": "./esm/bls12-381.js",
"default": "./bls12-381.js"

@@ -119,3 +108,2 @@ },

"types": "./bn.d.ts",
"import": "./esm/bn.js",
"default": "./bn.js"

@@ -125,3 +113,2 @@ },

"types": "./ed25519.d.ts",
"import": "./esm/ed25519.js",
"default": "./ed25519.js"

@@ -131,3 +118,2 @@ },

"types": "./ed448.d.ts",
"import": "./esm/ed448.js",
"default": "./ed448.js"

@@ -137,3 +123,2 @@ },

"types": "./index.d.ts",
"import": "./esm/index.js",
"default": "./index.js"

@@ -143,3 +128,2 @@ },

"types": "./jubjub.d.ts",
"import": "./esm/jubjub.js",
"default": "./jubjub.js"

@@ -149,3 +133,2 @@ },

"types": "./p256.d.ts",
"import": "./esm/p256.js",
"default": "./p256.js"

@@ -155,3 +138,2 @@ },

"types": "./p384.d.ts",
"import": "./esm/p384.js",
"default": "./p384.js"

@@ -161,3 +143,2 @@ },

"types": "./p521.d.ts",
"import": "./esm/p521.js",
"default": "./p521.js"

@@ -167,3 +148,2 @@ },

"types": "./pasta.d.ts",
"import": "./esm/pasta.js",
"default": "./pasta.js"

@@ -173,3 +153,2 @@ },

"types": "./secp256k1.d.ts",
"import": "./esm/secp256k1.js",
"default": "./secp256k1.js"

@@ -179,3 +158,2 @@ },

"types": "./stark.d.ts",
"import": "./esm/stark.js",
"default": "./stark.js"

@@ -182,0 +160,0 @@ }

@@ -1,33 +0,30 @@

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.vesta = exports.pallas = exports.q = exports.p = void 0;
/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
const sha256_1 = require("@noble/hashes/sha256");
const weierstrass_js_1 = require("./abstract/weierstrass.js");
const _shortw_utils_js_1 = require("./_shortw_utils.js");
const mod = require("./abstract/modular.js");
exports.p = BigInt('0x40000000000000000000000000000000224698fc094cf91b992d30ed00000001');
exports.q = BigInt('0x40000000000000000000000000000000224698fc0994a8dd8c46eb2100000001');
import { sha256 } from '@noble/hashes/sha256';
import { weierstrass } from './abstract/weierstrass.js';
import { getHash } from './_shortw_utils.js';
import * as mod from './abstract/modular.js';
export const p = BigInt('0x40000000000000000000000000000000224698fc094cf91b992d30ed00000001');
export const q = BigInt('0x40000000000000000000000000000000224698fc0994a8dd8c46eb2100000001');
// https://neuromancer.sk/std/other/Pallas
exports.pallas = (0, weierstrass_js_1.weierstrass)({
export const pallas = weierstrass({
a: BigInt(0),
b: BigInt(5),
Fp: mod.Fp(exports.p),
n: exports.q,
Gx: mod.mod(BigInt(-1), exports.p),
Fp: mod.Fp(p),
n: q,
Gx: mod.mod(BigInt(-1), p),
Gy: BigInt(2),
h: BigInt(1),
...(0, _shortw_utils_js_1.getHash)(sha256_1.sha256),
...getHash(sha256),
});
// https://neuromancer.sk/std/other/Vesta
exports.vesta = (0, weierstrass_js_1.weierstrass)({
export const vesta = weierstrass({
a: BigInt(0),
b: BigInt(5),
Fp: mod.Fp(exports.q),
n: exports.p,
Gx: mod.mod(BigInt(-1), exports.q),
Fp: mod.Fp(q),
n: p,
Gx: mod.mod(BigInt(-1), q),
Gy: BigInt(2),
h: BigInt(1),
...(0, _shortw_utils_js_1.getHash)(sha256_1.sha256),
...getHash(sha256),
});
//# sourceMappingURL=pasta.js.map

@@ -59,3 +59,3 @@ # noble-curves

```ts
import { secp256k1 } from '@noble/curves/secp256k1'; // ECMAScript Modules (ESM) and Common.js
import { secp256k1 } from '@noble/curves/secp256k1'; // ECMAScript Modules (ESM)
// import { secp256k1 } from 'npm:@noble/curves@1.2.0/secp256k1'; // Deno

@@ -476,3 +476,3 @@ const priv = secp256k1.utils.randomPrivateKey();

Every curve has exported `hashToCurve` and `encodeToCurve` methods:
Every curve has exported `hashToCurve` and `encodeToCurve` methods. You should always prefer `hashToCurve` for security:

@@ -716,6 +716,10 @@ ```ts

Article about some of library's features: [Learning fast elliptic-curve cryptography](https://paulmillr.com/posts/noble-secp256k1-fast-ecc/). Elliptic curve calculator: [paulmillr.com/ecc](https://paulmillr.com/ecc)
Article about some of library's features: [Learning fast elliptic-curve cryptography](https://paulmillr.com/posts/noble-secp256k1-fast-ecc/)
Demo: Elliptic curve calculator [paulmillr.com/ecc](https://paulmillr.com/ecc).
Projects using the library:
- secp256k1
- [btc-signer](https://github.com/paulmillr/micro-btc-signer), [eth-signer](https://github.com/paulmillr/micro-eth-signer)
- [btc-signer](https://github.com/paulmillr/scure-btc-signer), [eth-signer](https://github.com/paulmillr/micro-eth-signer)
- ed25519

@@ -722,0 +726,0 @@ - [sol-signer](https://github.com/paulmillr/micro-sol-signer)

@@ -57,7 +57,2 @@ import { mod } from './abstract/modular.js';

declare function taggedHash(tag: string, ...messages: Uint8Array[]): Uint8Array;
declare function schnorrGetExtPubKey(priv: PrivKey): {
point: PointType<bigint>;
scalar: bigint;
bytes: Uint8Array;
};
/**

@@ -88,3 +83,2 @@ * lift_x from BIP340. Convert 32-byte x coordinate to elliptic curve point.

randomPrivateKey: () => Uint8Array;
getExtendedPublicKey: typeof schnorrGetExtPubKey;
lift_x: typeof lift_x;

@@ -91,0 +85,0 @@ pointToBytes: (point: PointType<bigint>) => Uint8Array;

@@ -1,13 +0,9 @@

"use strict";
var _a;
Object.defineProperty(exports, "__esModule", { value: true });
exports.encodeToCurve = exports.hashToCurve = exports.schnorr = exports.secp256k1 = void 0;
/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
const sha256_1 = require("@noble/hashes/sha256");
const utils_1 = require("@noble/hashes/utils");
const modular_js_1 = require("./abstract/modular.js");
const weierstrass_js_1 = require("./abstract/weierstrass.js");
const utils_js_1 = require("./abstract/utils.js");
const htf = require("./abstract/hash-to-curve.js");
const _shortw_utils_js_1 = require("./_shortw_utils.js");
import { sha256 } from '@noble/hashes/sha256';
import { randomBytes } from '@noble/hashes/utils';
import { Fp as Field, mod, pow2 } from './abstract/modular.js';
import { mapToCurveSimpleSWU } from './abstract/weierstrass.js';
import { bytesToNumberBE, concatBytes, ensureBytes, numberToBytesBE } from './abstract/utils.js';
import * as htf from './abstract/hash-to-curve.js';
import { createCurve } from './_shortw_utils.js';
const secp256k1P = BigInt('0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f');

@@ -30,14 +26,14 @@ const secp256k1N = BigInt('0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141');

const b3 = (b2 * b2 * y) % P; // x^7
const b6 = ((0, modular_js_1.pow2)(b3, _3n, P) * b3) % P;
const b9 = ((0, modular_js_1.pow2)(b6, _3n, P) * b3) % P;
const b11 = ((0, modular_js_1.pow2)(b9, _2n, P) * b2) % P;
const b22 = ((0, modular_js_1.pow2)(b11, _11n, P) * b11) % P;
const b44 = ((0, modular_js_1.pow2)(b22, _22n, P) * b22) % P;
const b88 = ((0, modular_js_1.pow2)(b44, _44n, P) * b44) % P;
const b176 = ((0, modular_js_1.pow2)(b88, _88n, P) * b88) % P;
const b220 = ((0, modular_js_1.pow2)(b176, _44n, P) * b44) % P;
const b223 = ((0, modular_js_1.pow2)(b220, _3n, P) * b3) % P;
const t1 = ((0, modular_js_1.pow2)(b223, _23n, P) * b22) % P;
const t2 = ((0, modular_js_1.pow2)(t1, _6n, P) * b2) % P;
const root = (0, modular_js_1.pow2)(t2, _2n, P);
const b6 = (pow2(b3, _3n, P) * b3) % P;
const b9 = (pow2(b6, _3n, P) * b3) % P;
const b11 = (pow2(b9, _2n, 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, _3n, P) * b3) % P;
const t1 = (pow2(b223, _23n, P) * b22) % P;
const t2 = (pow2(t1, _6n, P) * b2) % P;
const root = pow2(t2, _2n, P);
if (!Fp.eql(Fp.sqr(root), y))

@@ -47,4 +43,4 @@ throw new Error('Cannot find square root');

}
const Fp = (0, modular_js_1.Fp)(secp256k1P, undefined, undefined, { sqrt: sqrtMod });
exports.secp256k1 = (0, _shortw_utils_js_1.createCurve)({
const Fp = Field(secp256k1P, undefined, undefined, { sqrt: sqrtMod });
export const secp256k1 = createCurve({
a: BigInt(0),

@@ -76,4 +72,4 @@ b: BigInt(7),

const c2 = divNearest(-b1 * k, n);
let k1 = (0, modular_js_1.mod)(k - c1 * a1 - c2 * a2, n);
let k2 = (0, modular_js_1.mod)(-c1 * b1 - c2 * b2, n);
let k1 = mod(k - c1 * a1 - c2 * a2, n);
let k2 = mod(-c1 * b1 - c2 * b2, n);
const k1neg = k1 > POW_2_128;

@@ -91,3 +87,3 @@ const k2neg = k2 > POW_2_128;

},
}, sha256_1.sha256);
}, sha256);
// Schnorr signatures are superior to ECDSA from above. Below is Schnorr-specific BIP0340 code.

@@ -103,21 +99,21 @@ // https://github.com/bitcoin/bips/blob/master/bip-0340.mediawiki

if (tagP === undefined) {
const tagH = (0, sha256_1.sha256)(Uint8Array.from(tag, (c) => c.charCodeAt(0)));
tagP = (0, utils_js_1.concatBytes)(tagH, tagH);
const tagH = sha256(Uint8Array.from(tag, (c) => c.charCodeAt(0)));
tagP = concatBytes(tagH, tagH);
TAGGED_HASH_PREFIXES[tag] = tagP;
}
return (0, sha256_1.sha256)((0, utils_js_1.concatBytes)(tagP, ...messages));
return sha256(concatBytes(tagP, ...messages));
}
// ECDSA compact points are 33-byte. Schnorr is 32: we strip first byte 0x02 or 0x03
const pointToBytes = (point) => point.toRawBytes(true).slice(1);
const numTo32b = (n) => (0, utils_js_1.numberToBytesBE)(n, 32);
const modP = (x) => (0, modular_js_1.mod)(x, secp256k1P);
const modN = (x) => (0, modular_js_1.mod)(x, secp256k1N);
const Point = exports.secp256k1.ProjectivePoint;
const numTo32b = (n) => numberToBytesBE(n, 32);
const modP = (x) => mod(x, secp256k1P);
const modN = (x) => mod(x, secp256k1N);
const Point = secp256k1.ProjectivePoint;
const GmulAdd = (Q, a, b) => Point.BASE.multiplyAndAddUnsafe(Q, a, b);
// Calculate point, scalar and bytes
function schnorrGetExtPubKey(priv) {
const d = exports.secp256k1.utils.normPrivateKeyToScalar(priv); // same method executed in fromPrivateKey
const point = Point.fromPrivateKey(d); // P = d'⋅G; 0 < d' < n check is done inside
const scalar = point.hasEvenY() ? d : modN(-d); // d = d' if has_even_y(P), otherwise d = n-d'
return { point, scalar, bytes: pointToBytes(point) };
let d_ = secp256k1.utils.normPrivateKeyToScalar(priv); // same method executed in fromPrivateKey
let p = Point.fromPrivateKey(d_); // P = d'⋅G; 0 < d' < n check is done inside
const scalar = p.hasEvenY() ? d_ : modN(-d_);
return { scalar: scalar, bytes: pointToBytes(p) };
}

@@ -144,3 +140,3 @@ /**

function challenge(...args) {
return modN((0, utils_js_1.bytesToNumberBE)(taggedHash('BIP0340/challenge', ...args)));
return modN(bytesToNumberBE(taggedHash('BIP0340/challenge', ...args)));
}

@@ -157,15 +153,15 @@ /**

*/
function schnorrSign(message, privateKey, auxRand = (0, utils_1.randomBytes)(32)) {
const m = (0, utils_js_1.ensureBytes)('message', message);
function schnorrSign(message, privateKey, auxRand = randomBytes(32)) {
const m = ensureBytes('message', message);
const { bytes: px, scalar: d } = schnorrGetExtPubKey(privateKey); // checks for isWithinCurveOrder
const a = (0, utils_js_1.ensureBytes)('auxRand', auxRand, 32); // Auxiliary random data a: a 32-byte array
const t = numTo32b(d ^ (0, utils_js_1.bytesToNumberBE)(taggedHash('BIP0340/aux', a))); // Let t be the byte-wise xor of bytes(d) and hash/aux(a)
const a = ensureBytes('auxRand', auxRand, 32); // Auxiliary random data a: a 32-byte array
const t = numTo32b(d ^ bytesToNumberBE(taggedHash('BIP0340/aux', a))); // Let t be the byte-wise xor of bytes(d) and hash/aux(a)
const rand = taggedHash('BIP0340/nonce', t, px, m); // Let rand = hash/nonce(t || bytes(P) || m)
const k_ = modN((0, utils_js_1.bytesToNumberBE)(rand)); // Let k' = int(rand) mod n
const k_ = modN(bytesToNumberBE(rand)); // Let k' = int(rand) mod n
if (k_ === _0n)
throw new Error('sign failed: k is zero'); // Fail if k' = 0.
const { point: R, bytes: rx, scalar: k } = schnorrGetExtPubKey(k_); // Let R = k'⋅G.
const { bytes: rx, scalar: k } = schnorrGetExtPubKey(k_); // Let R = k'⋅G.
const e = challenge(rx, px, m); // Let e = int(hash/challenge(bytes(R) || bytes(P) || m)) mod n.
const sig = new Uint8Array(64); // Let sig = bytes(R) || bytes((k + ed) mod n).
sig.set(numTo32b(R.px), 0);
sig.set(rx, 0);
sig.set(numTo32b(modN(k + e * d)), 32);

@@ -182,11 +178,11 @@ // If Verify(bytes(P), m, sig) (see below) returns failure, abort

function schnorrVerify(signature, message, publicKey) {
const sig = (0, utils_js_1.ensureBytes)('signature', signature, 64);
const m = (0, utils_js_1.ensureBytes)('message', message);
const pub = (0, utils_js_1.ensureBytes)('publicKey', publicKey, 32);
const sig = ensureBytes('signature', signature, 64);
const m = ensureBytes('message', message);
const pub = ensureBytes('publicKey', publicKey, 32);
try {
const P = lift_x((0, utils_js_1.bytesToNumberBE)(pub)); // P = lift_x(int(pk)); fail if that fails
const r = (0, utils_js_1.bytesToNumberBE)(sig.subarray(0, 32)); // Let r = int(sig[0:32]); fail if r ≥ p.
const P = lift_x(bytesToNumberBE(pub)); // P = lift_x(int(pk)); fail if that fails
const r = bytesToNumberBE(sig.subarray(0, 32)); // Let r = int(sig[0:32]); fail if r ≥ p.
if (!fe(r))
return false;
const s = (0, utils_js_1.bytesToNumberBE)(sig.subarray(32, 64)); // Let s = int(sig[32:64]); fail if s ≥ n.
const s = bytesToNumberBE(sig.subarray(32, 64)); // Let s = int(sig[32:64]); fail if s ≥ n.
if (!ge(s))

@@ -204,3 +200,3 @@ return false;

}
exports.schnorr = {
export const schnorr = {
getPublicKey: schnorrGetPublicKey,

@@ -210,10 +206,9 @@ sign: schnorrSign,

utils: {
randomPrivateKey: exports.secp256k1.utils.randomPrivateKey,
getExtendedPublicKey: schnorrGetExtPubKey,
randomPrivateKey: secp256k1.utils.randomPrivateKey,
lift_x,
pointToBytes,
numberToBytesBE: utils_js_1.numberToBytesBE,
bytesToNumberBE: utils_js_1.bytesToNumberBE,
numberToBytesBE,
bytesToNumberBE,
taggedHash,
mod: modular_js_1.mod,
mod,
},

@@ -250,3 +245,3 @@ };

].map((i) => i.map((j) => BigInt(j))));
const mapSWU = (0, weierstrass_js_1.mapToCurveSimpleSWU)(Fp, {
const mapSWU = mapToCurveSimpleSWU(Fp, {
A: BigInt('0x3f8731abdd661adca08a5558f0f5d272e953d363cb6f0e5d405447c01a444533'),

@@ -256,3 +251,3 @@ B: BigInt('1771'),

});
_a = htf.createHasher(exports.secp256k1.ProjectivePoint, (scalars) => {
export const { hashToCurve, encodeToCurve } = htf.createHasher(secp256k1.ProjectivePoint, (scalars) => {
const { x, y } = mapSWU(Fp.create(scalars[0]));

@@ -267,4 +262,4 @@ return isoMap(x, y);

expand: 'xmd',
hash: sha256_1.sha256,
}), exports.hashToCurve = _a.hashToCurve, exports.encodeToCurve = _a.encodeToCurve;
hash: sha256,
});
//# sourceMappingURL=secp256k1.js.map

@@ -14,4 +14,5 @@ /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */

*/
type UnicodeOrBytes = string | Uint8Array;
export type Opts = {
DST: string | Uint8Array;
DST: UnicodeOrBytes;
p: bigint;

@@ -24,3 +25,3 @@ m: number;

function validateDST(dst: string | Uint8Array): Uint8Array {
function validateDST(dst: UnicodeOrBytes): Uint8Array {
if (dst instanceof Uint8Array) return dst;

@@ -130,2 +131,9 @@ if (typeof dst === 'string') return utf8ToBytes(dst);

export function hash_to_field(msg: Uint8Array, count: number, options: Opts): bigint[][] {
validateObject(options, {
DST: 'string',
p: 'bigint',
m: 'isSafeInteger',
k: 'isSafeInteger',
hash: 'hash',
});
const { p, k, m, hash, expand, DST: _DST } = options;

@@ -189,3 +197,3 @@ isBytes(msg);

// (changing DST is ok!)
export type htfBasicOpts = { DST: string };
export type htfBasicOpts = { DST: UnicodeOrBytes };

@@ -195,15 +203,8 @@ export function createHasher<T>(

mapToCurve: MapToCurve<T>,
def: Opts & { encodeDST?: string }
def: Opts & { encodeDST?: UnicodeOrBytes }
) {
validateObject(def, {
DST: 'string',
p: 'bigint',
m: 'isSafeInteger',
k: 'isSafeInteger',
hash: 'hash',
});
if (typeof mapToCurve !== 'function') throw new Error('mapToCurve() must be defined');
return {
// Encodes byte string to elliptic curve
// https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-hash-to-curve-11#section-3
// https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-hash-to-curve-16#section-3
hashToCurve(msg: Uint8Array, options?: htfBasicOpts) {

@@ -210,0 +211,0 @@ const u = hash_to_field(msg, 2, { ...def, DST: def.DST, ...options } as Opts);

@@ -59,2 +59,3 @@ /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */

// Eucledian GCD https://brilliant.org/wiki/extended-euclidean-algorithm/
// Fermat's little theorem "CT-like" version inv(n) = n^(m-2) mod m is 30x slower.
let a = mod(number, modulo);

@@ -61,0 +62,0 @@ let b = modulo;

@@ -946,12 +946,6 @@ /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */

if (r === _0n) return;
// X blinding according to https://tches.iacr.org/index.php/TCHES/article/view/7337/6509
// b * m + b * r * d ∈ [0,q−1] exposed via side-channel, but d (private scalar) is not.
// NOTE: there is still probable some leak in multiplication, since it is not constant-time
const b = ut.bytesToNumberBE(utils.randomPrivateKey()); // random scalar, b ∈ [1,q−1]
const bi = invN(b); // b^-1
const bdr = modN(b * d * r); // b * d * r
const bm = modN(b * m); // b * m
const mrx = modN(bi * modN(bdr + bm)); // b^-1(bm + bdr) -> m + rd
const s = modN(ik * mrx); // s = k^-1(m + rd) mod n
// Can use scalar blinding b^-1(bm + bdr) where b ∈ [1,q−1] according to
// https://tches.iacr.org/index.php/TCHES/article/view/7337/6509. We've decided against it:
// a) dependency on CSPRNG b) 15% slowdown c) doesn't really help since bigints are not CT
const s = modN(ik * modN(m + r * d)); // Not using blinding here
if (s === _0n) return;

@@ -958,0 +952,0 @@ let recovery = (q.x === r ? 0 : 2) | Number(q.y & _1n); // recovery bit (2 or 3, when q.x > n)

@@ -16,2 +16,3 @@ /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */

import * as htf from './abstract/hash-to-curve.js';
import { AffinePoint } from './abstract/curve.js';

@@ -313,2 +314,7 @@ /**

constructor(private readonly ep: ExtendedPoint) {}
static fromAffine(ap: AffinePoint<bigint>) {
return new RistrettoPoint(ed25519.ExtendedPoint.fromAffine(ap));
}
/**

@@ -406,3 +412,3 @@ * Takes uniform output of 64-bit hash function like sha512 and converts it to `RistrettoPoint`.

const { ex: X1, ey: Y1 } = this.ep;
const { ex: X2, ey: Y2 } = this.ep;
const { ex: X2, ey: Y2 } = other.ep;
const mod = ed25519.CURVE.Fp.create;

@@ -433,1 +439,11 @@ // (x1 * y2 == y1 * x2) | (y1 * y2 == x1 * x2)

}
// https://datatracker.ietf.org/doc/draft-irtf-cfrg-hash-to-curve/14/
// Appendix B. Hashing to ristretto255
export const hash_to_ristretto255 = (msg: Uint8Array, options: htf.htfBasicOpts) => {
const d = options.DST;
const DST = typeof d === 'string' ? utf8ToBytes(d) : d;
const uniform_bytes = htf.expand_message_xmd(msg, DST, 64, sha512);
const P = RistrettoPoint.hashToCurve(uniform_bytes);
return P;
};

@@ -118,8 +118,9 @@ /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */

Point.BASE.multiplyAndAddUnsafe(Q, a, b);
// Calculate point, scalar and bytes
function schnorrGetExtPubKey(priv: PrivKey) {
const d = secp256k1.utils.normPrivateKeyToScalar(priv); // same method executed in fromPrivateKey
const point = Point.fromPrivateKey(d); // P = d'⋅G; 0 < d' < n check is done inside
const scalar = point.hasEvenY() ? d : modN(-d); // d = d' if has_even_y(P), otherwise d = n-d'
return { point, scalar, bytes: pointToBytes(point) };
let d_ = secp256k1.utils.normPrivateKeyToScalar(priv); // same method executed in fromPrivateKey
let p = Point.fromPrivateKey(d_); // P = d'⋅G; 0 < d' < n check is done inside
const scalar = p.hasEvenY() ? d_ : modN(-d_);
return { scalar: scalar, bytes: pointToBytes(p) };
}

@@ -170,6 +171,6 @@ /**

if (k_ === _0n) throw new Error('sign failed: k is zero'); // Fail if k' = 0.
const { point: R, bytes: rx, scalar: k } = schnorrGetExtPubKey(k_); // Let R = k'⋅G.
const { bytes: rx, scalar: k } = schnorrGetExtPubKey(k_); // Let R = k'⋅G.
const e = challenge(rx, px, m); // Let e = int(hash/challenge(bytes(R) || bytes(P) || m)) mod n.
const sig = new Uint8Array(64); // Let sig = bytes(R) || bytes((k + ed) mod n).
sig.set(numTo32b(R.px), 0);
sig.set(rx, 0);
sig.set(numTo32b(modN(k + e * d)), 32);

@@ -210,3 +211,2 @@ // If Verify(bytes(P), m, sig) (see below) returns failure, abort

randomPrivateKey: secp256k1.utils.randomPrivateKey,
getExtendedPublicKey: schnorrGetExtPubKey,
lift_x,

@@ -213,0 +213,0 @@ pointToBytes,

@@ -8,13 +8,4 @@ /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */

import { weierstrass, ProjPointType, SignatureType } from './abstract/weierstrass.js';
import {
Hex,
bitMask,
bytesToHex,
bytesToNumberBE,
concatBytes,
ensureBytes as ensureBytesOrig,
hexToBytes,
hexToNumber,
numberToVarBytesBE,
} from './abstract/utils.js';
import * as u from './abstract/utils.js';
import type { Hex } from './abstract/utils.js';
import { getHash } from './_shortw_utils.js';

@@ -34,3 +25,3 @@

const delta = bytes.length * 8 - nBitLength;
const num = bytesToNumberBE(bytes);
const num = u.bytesToNumberBE(bytes);
return delta > 0 ? num >> BigInt(delta) : num;

@@ -43,3 +34,3 @@ }

}
return hexToBytes(hex);
return u.hexToBytes(hex);
}

@@ -65,3 +56,3 @@ const curve = weierstrass({

// 2102820b232636d200cb21f1d330f20d096cae09d1bf3edb1cc333ddee113180
const hex = bytesToNumberBE(bytes).toString(16); // toHex unpadded
const hex = u.bytesToNumberBE(bytes).toString(16); // toHex unpadded
if (hex.length === 63) bytes = hex0xToBytes(hex + '0'); // append trailing 0

@@ -74,7 +65,7 @@ return mod(bits2int(bytes), CURVE_ORDER);

function ensureBytes(hex: Hex): Uint8Array {
return ensureBytesOrig('', typeof hex === 'string' ? hex0xToBytes(hex) : hex);
return u.ensureBytes('', typeof hex === 'string' ? hex0xToBytes(hex) : hex);
}
function normPrivKey(privKey: Hex): string {
return bytesToHex(ensureBytes(privKey)).padStart(64, '0');
return u.bytesToHex(ensureBytes(privKey)).padStart(64, '0');
}

@@ -99,3 +90,3 @@ export function getPublicKey(privKey: Hex, isCompressed = false): Uint8Array {

function extractX(bytes: Uint8Array): string {
const hex = bytesToHex(bytes.subarray(1));
const hex = u.bytesToHex(bytes.subarray(1));
const stripped = hex.replace(/^0+/gm, ''); // strip leading 0s

@@ -118,3 +109,3 @@ return `0x${stripped}`;

for (let i = 0; ; i++) {
const key = sha256Num(concatBytes(_seed, numberToVarBytesBE(BigInt(i))));
const key = sha256Num(u.concatBytes(_seed, u.numberToVarBytesBE(BigInt(i))));
if (key < limit) return mod(key, CURVE_ORDER).toString(16); // key should be in [0, limit)

@@ -145,3 +136,3 @@ if (i === 100000) throw new Error('grindKey is broken: tried 100k vals'); // prevent dos

const applicationNum = int31(sha256Num(application));
const eth = hexToNumber(strip0x(ethereumAddress));
const eth = u.hexToNumber(strip0x(ethereumAddress));
return `m/2645'/${layerNum}'/${applicationNum}'/${int31(eth)}'/${int31(eth >> 31n)}'/${index}`;

@@ -207,3 +198,3 @@ }

} else {
value = bytesToNumberBE(ensureBytes(arg));
value = u.bytesToNumberBE(ensureBytes(arg));
}

@@ -219,3 +210,3 @@ if (!(0n <= value && value < curve.CURVE.Fp.ORDER))

const pt = constants[j];
if (pt.px === point.px) throw new Error('Same point');
if (pt.equals(point)) throw new Error('Same point');
if ((x & 1n) !== 0n) point = point.add(pt);

@@ -247,5 +238,5 @@ x >>= 1n;

const MASK_250 = bitMask(250);
export const keccak = (data: Uint8Array): bigint => bytesToNumberBE(keccak_256(data)) & MASK_250;
const sha256Num = (data: Uint8Array | string): bigint => bytesToNumberBE(sha256(data));
const MASK_250 = u.bitMask(250);
export const keccak = (data: Uint8Array): bigint => u.bytesToNumberBE(keccak_256(data)) & MASK_250;
const sha256Num = (data: Uint8Array | string): bigint => u.bytesToNumberBE(sha256(data));

@@ -294,3 +285,9 @@ // Poseidon hash

export function poseidonBasic(opts: PoseidonOpts, mds: bigint[][]) {
export type PoseidonFn = ReturnType<typeof poseidon> & {
m: number;
rate: number;
capacity: number;
};
export function poseidonBasic(opts: PoseidonOpts, mds: bigint[][]): PoseidonFn {
validateField(opts.Fp);

@@ -307,3 +304,3 @@ if (!Number.isSafeInteger(opts.rate) || !Number.isSafeInteger(opts.capacity))

}
return poseidon({
const res: Partial<PoseidonFn> = poseidon({
...opts,

@@ -316,2 +313,6 @@ t: m,

});
res.m = m;
res.rate = opts.rate;
res.capacity = opts.capacity;
return res as PoseidonFn;
}

@@ -330,4 +331,26 @@

export function poseidonHash(x: bigint, y: bigint, fn = poseidonSmall) {
export function poseidonHash(x: bigint, y: bigint, fn = poseidonSmall): bigint {
return fn([x, y, 2n])[0];
}
export function poseidonHashFunc(x: Uint8Array, y: Uint8Array, fn = poseidonSmall): Uint8Array {
return u.numberToVarBytesBE(poseidonHash(u.bytesToNumberBE(x), u.bytesToNumberBE(y), fn));
}
export function poseidonHashSingle(x: bigint, fn = poseidonSmall): bigint {
return fn([x, 0n, 1n])[0];
}
export function poseidonHashMany(values: bigint[], fn = poseidonSmall): bigint {
const { m, rate } = fn;
if (!Array.isArray(values)) throw new Error('bigint array expected in values');
const padded = Array.from(values); // copy
padded.push(1n);
while (padded.length % rate !== 0) padded.push(0n);
let state: bigint[] = new Array(m).fill(0n);
for (let i = 0; i < padded.length; i += rate) {
for (let j = 0; j < rate; j++) state[j] += padded[i + j];
state = fn(state);
}
return state[0];
}
import { Field } from './abstract/modular.js';
import { poseidon } from './abstract/poseidon.js';
import { ProjPointType, SignatureType } from './abstract/weierstrass.js';
import { Hex } from './abstract/utils.js';
import * as u from './abstract/utils.js';
import type { Hex } from './abstract/utils.js';
declare type ProjectivePoint = ProjPointType<bigint>;

@@ -35,3 +37,3 @@ export declare const _starkCurve: import("./abstract/weierstrass.js").CurveFn;

readonly clearCofactor?: ((c: import("./abstract/weierstrass.js").ProjConstructor<bigint>, point: ProjPointType<bigint>) => ProjPointType<bigint>) | undefined;
readonly hash: import("./abstract/utils.js").CHash;
readonly hash: u.CHash;
readonly hmac: (key: Uint8Array, ...messages: Uint8Array[]) => Uint8Array;

@@ -43,4 +45,4 @@ readonly randomBytes: (bytesLength?: number | undefined) => Uint8Array;

}>, ProjectivePoint: import("./abstract/weierstrass.js").ProjConstructor<bigint>, Signature: import("./abstract/weierstrass.js").SignatureConstructor, utils: {
normPrivateKeyToScalar: (key: import("./abstract/utils.js").PrivKey) => bigint;
isValidPrivateKey(privateKey: import("./abstract/utils.js").PrivKey): boolean;
normPrivateKeyToScalar: (key: u.PrivKey) => bigint;
isValidPrivateKey(privateKey: u.PrivKey): boolean;
randomPrivateKey: () => Uint8Array;

@@ -69,18 +71,14 @@ precompute: (windowSize?: number | undefined, point?: ProjPointType<bigint> | undefined) => ProjPointType<bigint>;

};
export declare function poseidonBasic(opts: PoseidonOpts, mds: bigint[][]): {
(values: bigint[]): bigint[];
roundConstants: bigint[][];
export declare type PoseidonFn = ReturnType<typeof poseidon> & {
m: number;
rate: number;
capacity: number;
};
export declare function poseidonCreate(opts: PoseidonOpts, mdsAttempt?: number): {
(values: bigint[]): bigint[];
roundConstants: bigint[][];
};
export declare const poseidonSmall: {
(values: bigint[]): bigint[];
roundConstants: bigint[][];
};
export declare function poseidonHash(x: bigint, y: bigint, fn?: {
(values: bigint[]): bigint[];
roundConstants: bigint[][];
}): bigint;
export declare function poseidonBasic(opts: PoseidonOpts, mds: bigint[][]): PoseidonFn;
export declare function poseidonCreate(opts: PoseidonOpts, mdsAttempt?: number): PoseidonFn;
export declare const poseidonSmall: PoseidonFn;
export declare function poseidonHash(x: bigint, y: bigint, fn?: PoseidonFn): bigint;
export declare function poseidonHashFunc(x: Uint8Array, y: Uint8Array, fn?: PoseidonFn): Uint8Array;
export declare function poseidonHashSingle(x: bigint, fn?: PoseidonFn): bigint;
export declare function poseidonHashMany(values: bigint[], fn?: PoseidonFn): bigint;
//# sourceMappingURL=stark.d.ts.map

@@ -1,13 +0,10 @@

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.poseidonHash = exports.poseidonSmall = exports.poseidonCreate = exports.poseidonBasic = exports._poseidonMDS = exports.Fp251 = exports.Fp253 = exports.keccak = exports.computeHashOnElements = exports.hashChain = exports.pedersen = exports.getAccountPath = exports.ethSigToPrivate = exports.getStarkKey = exports.grindKey = exports.utils = exports.Signature = exports.ProjectivePoint = exports.CURVE = exports.verify = exports.sign = exports.getSharedSecret = exports.getPublicKey = exports._starkCurve = void 0;
/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
const sha3_1 = require("@noble/hashes/sha3");
const sha256_1 = require("@noble/hashes/sha256");
const utils_1 = require("@noble/hashes/utils");
const modular_js_1 = require("./abstract/modular.js");
const poseidon_js_1 = require("./abstract/poseidon.js");
const weierstrass_js_1 = require("./abstract/weierstrass.js");
const utils_js_1 = require("./abstract/utils.js");
const _shortw_utils_js_1 = require("./_shortw_utils.js");
import { keccak_256 } from '@noble/hashes/sha3';
import { sha256 } from '@noble/hashes/sha256';
import { utf8ToBytes } from '@noble/hashes/utils';
import { Fp, mod, validateField } from './abstract/modular.js';
import { poseidon } from './abstract/poseidon.js';
import { weierstrass } from './abstract/weierstrass.js';
import * as u from './abstract/utils.js';
import { getHash } from './_shortw_utils.js';
const CURVE_ORDER = BigInt('3618502788666131213697322783095070105526743751716087489154079457884512865583');

@@ -20,3 +17,3 @@ const nBitLength = 252;

const delta = bytes.length * 8 - nBitLength;
const num = (0, utils_js_1.bytesToNumberBE)(bytes);
const num = u.bytesToNumberBE(bytes);
return delta > 0 ? num >> BigInt(delta) : num;

@@ -30,5 +27,5 @@ }

}
return (0, utils_js_1.hexToBytes)(hex);
return u.hexToBytes(hex);
}
const curve = (0, weierstrass_js_1.weierstrass)({
const curve = weierstrass({
a: BigInt(1),

@@ -38,3 +35,3 @@ b: BigInt('3141592653589793238462643383279502884197169399375105820974944592307816406665'),

// There is no efficient sqrt for field (P%4==1)
Fp: (0, modular_js_1.Fp)(BigInt('0x800000000000011000000000000000000000000000000000000000000000001')),
Fp: Fp(BigInt('0x800000000000011000000000000000000000000000000000000000000000001')),
n: CURVE_ORDER,

@@ -47,3 +44,3 @@ nBitLength,

lowS: false,
...(0, _shortw_utils_js_1.getHash)(sha256_1.sha256),
...getHash(sha256),
// Custom truncation routines for stark curve

@@ -54,39 +51,32 @@ bits2int,

// 2102820b232636d200cb21f1d330f20d096cae09d1bf3edb1cc333ddee113180
const hex = (0, utils_js_1.bytesToNumberBE)(bytes).toString(16); // toHex unpadded
const hex = u.bytesToNumberBE(bytes).toString(16); // toHex unpadded
if (hex.length === 63)
bytes = hex0xToBytes(hex + '0'); // append trailing 0
return (0, modular_js_1.mod)(bits2int(bytes), CURVE_ORDER);
return mod(bits2int(bytes), CURVE_ORDER);
},
});
exports._starkCurve = curve;
export const _starkCurve = curve;
function ensureBytes(hex) {
return (0, utils_js_1.ensureBytes)('', typeof hex === 'string' ? hex0xToBytes(hex) : hex);
return u.ensureBytes('', typeof hex === 'string' ? hex0xToBytes(hex) : hex);
}
function normPrivKey(privKey) {
return (0, utils_js_1.bytesToHex)(ensureBytes(privKey)).padStart(64, '0');
return u.bytesToHex(ensureBytes(privKey)).padStart(64, '0');
}
function getPublicKey(privKey, isCompressed = false) {
export function getPublicKey(privKey, isCompressed = false) {
return curve.getPublicKey(normPrivKey(privKey), isCompressed);
}
exports.getPublicKey = getPublicKey;
function getSharedSecret(privKeyA, pubKeyB) {
export function getSharedSecret(privKeyA, pubKeyB) {
return curve.getSharedSecret(normPrivKey(privKeyA), pubKeyB);
}
exports.getSharedSecret = getSharedSecret;
function sign(msgHash, privKey, opts) {
export function sign(msgHash, privKey, opts) {
return curve.sign(ensureBytes(msgHash), normPrivKey(privKey), opts);
}
exports.sign = sign;
function verify(signature, msgHash, pubKey) {
export function verify(signature, msgHash, pubKey) {
const sig = signature instanceof Signature ? signature : ensureBytes(signature);
return curve.verify(sig, ensureBytes(msgHash), ensureBytes(pubKey));
}
exports.verify = verify;
const { CURVE, ProjectivePoint, Signature, utils } = curve;
exports.CURVE = CURVE;
exports.ProjectivePoint = ProjectivePoint;
exports.Signature = Signature;
exports.utils = utils;
export { CURVE, ProjectivePoint, Signature, utils };
function extractX(bytes) {
const hex = (0, utils_js_1.bytesToHex)(bytes.subarray(1));
const hex = u.bytesToHex(bytes.subarray(1));
const stripped = hex.replace(/^0+/gm, ''); // strip leading 0s

@@ -103,10 +93,10 @@ return `0x${stripped}`;

// seed generation
function grindKey(seed) {
export function grindKey(seed) {
const _seed = ensureBytes(seed);
const sha256mask = 2n ** 256n;
const limit = sha256mask - (0, modular_js_1.mod)(sha256mask, CURVE_ORDER);
const limit = sha256mask - mod(sha256mask, CURVE_ORDER);
for (let i = 0;; i++) {
const key = sha256Num((0, utils_js_1.concatBytes)(_seed, (0, utils_js_1.numberToVarBytesBE)(BigInt(i))));
const key = sha256Num(u.concatBytes(_seed, u.numberToVarBytesBE(BigInt(i))));
if (key < limit)
return (0, modular_js_1.mod)(key, CURVE_ORDER).toString(16); // key should be in [0, limit)
return mod(key, CURVE_ORDER).toString(16); // key should be in [0, limit)
if (i === 100000)

@@ -116,8 +106,6 @@ throw new Error('grindKey is broken: tried 100k vals'); // prevent dos

}
exports.grindKey = grindKey;
function getStarkKey(privateKey) {
export function getStarkKey(privateKey) {
return extractX(getPublicKey(privateKey, true));
}
exports.getStarkKey = getStarkKey;
function ethSigToPrivate(signature) {
export function ethSigToPrivate(signature) {
signature = strip0x(signature);

@@ -128,12 +116,10 @@ if (signature.length !== 130)

}
exports.ethSigToPrivate = ethSigToPrivate;
const MASK_31 = 2n ** 31n - 1n;
const int31 = (n) => Number(n & MASK_31);
function getAccountPath(layer, application, ethereumAddress, index) {
export function getAccountPath(layer, application, ethereumAddress, index) {
const layerNum = int31(sha256Num(layer));
const applicationNum = int31(sha256Num(application));
const eth = (0, utils_js_1.hexToNumber)(strip0x(ethereumAddress));
const eth = u.hexToNumber(strip0x(ethereumAddress));
return `m/2645'/${layerNum}'/${applicationNum}'/${int31(eth)}'/${int31(eth >> 31n)}'/${index}`;
}
exports.getAccountPath = getAccountPath;
// https://docs.starkware.co/starkex/pedersen-hash-function.html

@@ -176,3 +162,3 @@ const PEDERSEN_POINTS = [

else {
value = (0, utils_js_1.bytesToNumberBE)(ensureBytes(arg));
value = u.bytesToNumberBE(ensureBytes(arg));
}

@@ -187,3 +173,3 @@ if (!(0n <= value && value < curve.CURVE.Fp.ORDER))

const pt = constants[j];
if (pt.px === point.px)
if (pt.equals(point))
throw new Error('Same point');

@@ -197,3 +183,3 @@ if ((x & 1n) !== 0n)

// shift_point + x_low * P_0 + x_high * P1 + y_low * P2 + y_high * P3
function pedersen(x, y) {
export function pedersen(x, y) {
let point = PEDERSEN_POINTS[0];

@@ -204,4 +190,3 @@ point = pedersenSingle(point, x, PEDERSEN_POINTS1);

}
exports.pedersen = pedersen;
function hashChain(data, fn = pedersen) {
export function hashChain(data, fn = pedersen) {
if (!Array.isArray(data) || data.length < 1)

@@ -215,15 +200,12 @@ throw new Error('data should be array of at least 1 element');

}
exports.hashChain = hashChain;
// Same as hashChain, but computes hash even for single element and order is not revesed
const computeHashOnElements = (data, fn = pedersen) => [0, ...data, data.length].reduce((x, y) => fn(x, y));
exports.computeHashOnElements = computeHashOnElements;
const MASK_250 = (0, utils_js_1.bitMask)(250);
const keccak = (data) => (0, utils_js_1.bytesToNumberBE)((0, sha3_1.keccak_256)(data)) & MASK_250;
exports.keccak = keccak;
const sha256Num = (data) => (0, utils_js_1.bytesToNumberBE)((0, sha256_1.sha256)(data));
export const computeHashOnElements = (data, fn = pedersen) => [0, ...data, data.length].reduce((x, y) => fn(x, y));
const MASK_250 = u.bitMask(250);
export const keccak = (data) => u.bytesToNumberBE(keccak_256(data)) & MASK_250;
const sha256Num = (data) => u.bytesToNumberBE(sha256(data));
// Poseidon hash
exports.Fp253 = (0, modular_js_1.Fp)(BigInt('14474011154664525231415395255581126252639794253786371766033694892385558855681')); // 2^253 + 2^199 + 1
exports.Fp251 = (0, modular_js_1.Fp)(BigInt('3618502788666131213697322783095070105623107215331596699973092056135872020481')); // 2^251 + 17 * 2^192 + 1
export const Fp253 = Fp(BigInt('14474011154664525231415395255581126252639794253786371766033694892385558855681')); // 2^253 + 2^199 + 1
export const Fp251 = Fp(BigInt('3618502788666131213697322783095070105623107215331596699973092056135872020481')); // 2^251 + 17 * 2^192 + 1
function poseidonRoundConstant(Fp, name, idx) {
const val = Fp.fromBytes((0, sha256_1.sha256)((0, utils_1.utf8ToBytes)(`${name}${idx}`)));
const val = Fp.fromBytes(sha256(utf8ToBytes(`${name}${idx}`)));
return Fp.create(val);

@@ -234,3 +216,3 @@ }

// https://eprint.iacr.org/2019/458.pdf Section 2.3 (Avoiding Insecure Matrices)
function _poseidonMDS(Fp, name, m, attempt = 0) {
export function _poseidonMDS(Fp, name, m, attempt = 0) {
const x_values = [];

@@ -246,3 +228,2 @@ const y_values = [];

}
exports._poseidonMDS = _poseidonMDS;
const MDS_SMALL = [

@@ -253,4 +234,4 @@ [3, 1, 1],

].map((i) => i.map(BigInt));
function poseidonBasic(opts, mds) {
(0, modular_js_1.validateField)(opts.Fp);
export function poseidonBasic(opts, mds) {
validateField(opts.Fp);
if (!Number.isSafeInteger(opts.rate) || !Number.isSafeInteger(opts.capacity))

@@ -267,3 +248,3 @@ throw new Error(`Wrong poseidon opts: ${opts}`);

}
return (0, poseidon_js_1.poseidon)({
const res = poseidon({
...opts,

@@ -276,5 +257,8 @@ t: m,

});
res.m = m;
res.rate = opts.rate;
res.capacity = opts.capacity;
return res;
}
exports.poseidonBasic = poseidonBasic;
function poseidonCreate(opts, mdsAttempt = 0) {
export function poseidonCreate(opts, mdsAttempt = 0) {
const m = opts.rate + opts.capacity;

@@ -285,8 +269,28 @@ if (!Number.isSafeInteger(mdsAttempt))

}
exports.poseidonCreate = poseidonCreate;
exports.poseidonSmall = poseidonBasic({ Fp: exports.Fp251, rate: 2, capacity: 1, roundsFull: 8, roundsPartial: 83 }, MDS_SMALL);
function poseidonHash(x, y, fn = exports.poseidonSmall) {
export const poseidonSmall = poseidonBasic({ Fp: Fp251, rate: 2, capacity: 1, roundsFull: 8, roundsPartial: 83 }, MDS_SMALL);
export function poseidonHash(x, y, fn = poseidonSmall) {
return fn([x, y, 2n])[0];
}
exports.poseidonHash = poseidonHash;
export function poseidonHashFunc(x, y, fn = poseidonSmall) {
return u.numberToVarBytesBE(poseidonHash(u.bytesToNumberBE(x), u.bytesToNumberBE(y), fn));
}
export function poseidonHashSingle(x, fn = poseidonSmall) {
return fn([x, 0n, 1n])[0];
}
export function poseidonHashMany(values, fn = poseidonSmall) {
const { m, rate } = fn;
if (!Array.isArray(values))
throw new Error('bigint array expected in values');
const padded = Array.from(values); // copy
padded.push(1n);
while (padded.length % rate !== 0)
padded.push(0n);
let state = new Array(m).fill(0n);
for (let i = 0; i < padded.length; i += rate) {
for (let j = 0; j < rate; j++)
state[j] += padded[i + j];
state = fn(state);
}
return state[0];
}
//# sourceMappingURL=stark.js.map

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc