@noble/curves 0.6.4 → 0.7.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +486 -298
- package/{lib/_shortw_utils.d.ts → _shortw_utils.d.ts} +1 -1
- package/_shortw_utils.d.ts.map +1 -0
- package/{lib/_shortw_utils.js → _shortw_utils.js} +2 -0
- package/_shortw_utils.js.map +1 -0
- package/{lib/abstract → abstract}/bls.d.ts +4 -9
- package/abstract/bls.d.ts.map +1 -0
- package/{lib/abstract → abstract}/bls.js +13 -26
- package/abstract/bls.js.map +1 -0
- package/{lib/abstract → abstract}/curve.d.ts +1 -0
- package/abstract/curve.d.ts.map +1 -0
- package/{lib/abstract → abstract}/curve.js +1 -0
- package/abstract/curve.js.map +1 -0
- package/{lib/abstract → abstract}/edwards.d.ts +1 -0
- package/abstract/edwards.d.ts.map +1 -0
- package/{lib/abstract → abstract}/edwards.js +9 -15
- package/abstract/edwards.js.map +1 -0
- package/{lib/abstract → abstract}/hash-to-curve.d.ts +5 -5
- package/abstract/hash-to-curve.d.ts.map +1 -0
- package/{lib/abstract → abstract}/hash-to-curve.js +41 -38
- package/abstract/hash-to-curve.js.map +1 -0
- package/{lib/abstract → abstract}/modular.d.ts +1 -0
- package/abstract/modular.d.ts.map +1 -0
- package/{lib/abstract → abstract}/modular.js +2 -1
- package/abstract/modular.js.map +1 -0
- package/{lib/abstract → abstract}/montgomery.d.ts +4 -3
- package/abstract/montgomery.d.ts.map +1 -0
- package/{lib/abstract → abstract}/montgomery.js +12 -9
- package/abstract/montgomery.js.map +1 -0
- package/{lib/abstract → abstract}/poseidon.d.ts +1 -0
- package/abstract/poseidon.d.ts.map +1 -0
- package/{lib/abstract → abstract}/poseidon.js +1 -0
- package/abstract/poseidon.js.map +1 -0
- package/{lib/abstract → abstract}/utils.d.ts +12 -1
- package/abstract/utils.d.ts.map +1 -0
- package/{lib/abstract → abstract}/utils.js +96 -10
- package/abstract/utils.js.map +1 -0
- package/{lib/abstract → abstract}/weierstrass.d.ts +6 -6
- package/abstract/weierstrass.d.ts.map +1 -0
- package/{lib/abstract → abstract}/weierstrass.js +74 -115
- package/abstract/weierstrass.js.map +1 -0
- package/{lib/bls12-381.d.ts → bls12-381.d.ts} +1 -0
- package/bls12-381.d.ts.map +1 -0
- package/{lib/bls12-381.js → bls12-381.js} +41 -7
- package/bls12-381.js.map +1 -0
- package/{lib/bn.d.ts → bn.d.ts} +1 -0
- package/bn.d.ts.map +1 -0
- package/{lib/bn.js → bn.js} +1 -0
- package/bn.js.map +1 -0
- package/{lib/ed25519.d.ts → ed25519.d.ts} +2 -1
- package/ed25519.d.ts.map +1 -0
- package/{lib/ed25519.js → ed25519.js} +6 -5
- package/ed25519.js.map +1 -0
- package/{lib/ed448.d.ts → ed448.d.ts} +2 -1
- package/ed448.d.ts.map +1 -0
- package/{lib/ed448.js → ed448.js} +4 -3
- package/ed448.js.map +1 -0
- package/{lib/esm → esm}/_shortw_utils.js +2 -0
- package/esm/_shortw_utils.js.map +1 -0
- package/{lib/esm → esm}/abstract/bls.js +14 -27
- package/esm/abstract/bls.js.map +1 -0
- package/{lib/esm → esm}/abstract/curve.js +1 -0
- package/esm/abstract/curve.js.map +1 -0
- package/{lib/esm → esm}/abstract/edwards.js +9 -15
- package/esm/abstract/edwards.js.map +1 -0
- package/{lib/esm → esm}/abstract/hash-to-curve.js +40 -36
- package/esm/abstract/hash-to-curve.js.map +1 -0
- package/{lib/esm → esm}/abstract/modular.js +2 -1
- package/esm/abstract/modular.js.map +1 -0
- package/{lib/esm → esm}/abstract/montgomery.js +12 -9
- package/esm/abstract/montgomery.js.map +1 -0
- package/{lib/esm → esm}/abstract/poseidon.js +1 -0
- package/esm/abstract/poseidon.js.map +1 -0
- package/{lib/esm → esm}/abstract/utils.js +93 -9
- package/esm/abstract/utils.js.map +1 -0
- package/{lib/esm → esm}/abstract/weierstrass.js +74 -115
- package/esm/abstract/weierstrass.js.map +1 -0
- package/{lib/esm → esm}/bls12-381.js +41 -7
- package/esm/bls12-381.js.map +1 -0
- package/{lib/esm → esm}/bn.js +1 -0
- package/esm/bn.js.map +1 -0
- package/{lib/esm → esm}/ed25519.js +7 -6
- package/esm/ed25519.js.map +1 -0
- package/{lib/esm → esm}/ed448.js +4 -3
- package/esm/ed448.js.map +1 -0
- package/{lib → esm}/index.js +1 -0
- package/esm/index.js.map +1 -0
- package/{lib/esm → esm}/jubjub.js +1 -0
- package/esm/jubjub.js.map +1 -0
- package/{lib/esm → esm}/p192.js +1 -0
- package/esm/p192.js.map +1 -0
- package/{lib/esm → esm}/p224.js +1 -0
- package/esm/p224.js.map +1 -0
- package/{lib/esm → esm}/p256.js +2 -1
- package/esm/p256.js.map +1 -0
- package/{lib/esm → esm}/p384.js +2 -1
- package/esm/p384.js.map +1 -0
- package/{lib/esm → esm}/p521.js +2 -1
- package/esm/p521.js.map +1 -0
- package/{lib/esm → esm}/package.json +0 -0
- package/{lib/esm → esm}/pasta.js +1 -0
- package/esm/pasta.js.map +1 -0
- package/{lib/esm → esm}/secp256k1.js +51 -50
- package/esm/secp256k1.js.map +1 -0
- package/{lib/esm → esm}/stark.js +5 -4
- package/esm/stark.js.map +1 -0
- package/index.d.ts +1 -0
- package/index.d.ts.map +1 -0
- package/index.js +3 -0
- package/index.js.map +1 -0
- package/{lib/jubjub.d.ts → jubjub.d.ts} +1 -0
- package/jubjub.d.ts.map +1 -0
- package/{lib/jubjub.js → jubjub.js} +1 -0
- package/jubjub.js.map +1 -0
- package/{lib/p192.d.ts → p192.d.ts} +1 -2
- package/p192.d.ts.map +1 -0
- package/{lib/p192.js → p192.js} +1 -0
- package/p192.js.map +1 -0
- package/{lib/p224.d.ts → p224.d.ts} +1 -2
- package/p224.d.ts.map +1 -0
- package/{lib/p224.js → p224.js} +1 -0
- package/p224.js.map +1 -0
- package/{lib/p256.d.ts → p256.d.ts} +2 -3
- package/p256.d.ts.map +1 -0
- package/{lib/p256.js → p256.js} +2 -1
- package/p256.js.map +1 -0
- package/{lib/p384.d.ts → p384.d.ts} +2 -3
- package/p384.d.ts.map +1 -0
- package/{lib/p384.js → p384.js} +2 -1
- package/p384.js.map +1 -0
- package/{lib/p521.d.ts → p521.d.ts} +2 -3
- package/p521.d.ts.map +1 -0
- package/{lib/p521.js → p521.js} +2 -1
- package/p521.js.map +1 -0
- package/package.json +84 -79
- package/{lib/pasta.d.ts → pasta.d.ts} +1 -0
- package/pasta.d.ts.map +1 -0
- package/{lib/pasta.js → pasta.js} +1 -0
- package/pasta.js.map +1 -0
- package/{lib/secp256k1.d.ts → secp256k1.d.ts} +20 -6
- package/secp256k1.d.ts.map +1 -0
- package/{lib/secp256k1.js → secp256k1.js} +48 -47
- package/secp256k1.js.map +1 -0
- package/src/_shortw_utils.ts +20 -0
- package/src/abstract/bls.ts +376 -0
- package/src/abstract/curve.ts +199 -0
- package/src/abstract/edwards.ts +479 -0
- package/src/abstract/hash-to-curve.ts +220 -0
- package/src/abstract/modular.ts +417 -0
- package/src/abstract/montgomery.ts +186 -0
- package/src/abstract/poseidon.ts +119 -0
- package/src/abstract/utils.ts +246 -0
- package/src/abstract/weierstrass.ts +1177 -0
- package/src/bls12-381.ts +1274 -0
- package/src/bn.ts +21 -0
- package/src/ed25519.ts +428 -0
- package/src/ed448.ts +241 -0
- package/{lib/esm/index.js → src/index.ts} +0 -1
- package/src/jubjub.ts +58 -0
- package/src/p192.ts +25 -0
- package/src/p224.ts +25 -0
- package/src/p256.ts +53 -0
- package/src/p384.ts +57 -0
- package/src/p521.ts +57 -0
- package/src/pasta.ts +31 -0
- package/src/secp256k1.ts +270 -0
- package/src/stark.ts +356 -0
- package/{lib/stark.d.ts → stark.d.ts} +1 -1
- package/stark.d.ts.map +1 -0
- package/{lib/stark.js → stark.js} +5 -4
- package/stark.js.map +1 -0
- package/lib/index.d.ts +0 -0
|
@@ -0,0 +1,119 @@
|
|
|
1
|
+
/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
|
|
2
|
+
// Poseidon Hash: https://eprint.iacr.org/2019/458.pdf, https://www.poseidon-hash.info
|
|
3
|
+
import { Field, FpPow, validateField } from './modular.js';
|
|
4
|
+
// We don't provide any constants, since different implementations use different constants.
|
|
5
|
+
// For reference constants see './test/poseidon.test.js'.
|
|
6
|
+
export type PoseidonOpts = {
|
|
7
|
+
Fp: Field<bigint>;
|
|
8
|
+
t: number;
|
|
9
|
+
roundsFull: number;
|
|
10
|
+
roundsPartial: number;
|
|
11
|
+
sboxPower?: number;
|
|
12
|
+
reversePartialPowIdx?: boolean; // Hack for stark
|
|
13
|
+
mds: bigint[][];
|
|
14
|
+
roundConstants: bigint[][];
|
|
15
|
+
};
|
|
16
|
+
|
|
17
|
+
export function validateOpts(opts: PoseidonOpts) {
|
|
18
|
+
const { Fp } = opts;
|
|
19
|
+
validateField(Fp);
|
|
20
|
+
for (const i of ['t', 'roundsFull', 'roundsPartial'] as const) {
|
|
21
|
+
if (typeof opts[i] !== 'number' || !Number.isSafeInteger(opts[i]))
|
|
22
|
+
throw new Error(`Poseidon: invalid param ${i}=${opts[i]} (${typeof opts[i]})`);
|
|
23
|
+
}
|
|
24
|
+
if (opts.reversePartialPowIdx !== undefined && typeof opts.reversePartialPowIdx !== 'boolean')
|
|
25
|
+
throw new Error(`Poseidon: invalid param reversePartialPowIdx=${opts.reversePartialPowIdx}`);
|
|
26
|
+
// Default is 5, but by some reasons stark uses 3
|
|
27
|
+
let sboxPower = opts.sboxPower;
|
|
28
|
+
if (sboxPower === undefined) sboxPower = 5;
|
|
29
|
+
if (typeof sboxPower !== 'number' || !Number.isSafeInteger(sboxPower))
|
|
30
|
+
throw new Error(`Poseidon wrong sboxPower=${sboxPower}`);
|
|
31
|
+
|
|
32
|
+
const _sboxPower = BigInt(sboxPower);
|
|
33
|
+
let sboxFn = (n: bigint) => FpPow(Fp, n, _sboxPower);
|
|
34
|
+
// Unwrapped sbox power for common cases (195->142μs)
|
|
35
|
+
if (sboxPower === 3) sboxFn = (n: bigint) => Fp.mul(Fp.sqrN(n), n);
|
|
36
|
+
else if (sboxPower === 5) sboxFn = (n: bigint) => Fp.mul(Fp.sqrN(Fp.sqrN(n)), n);
|
|
37
|
+
|
|
38
|
+
if (opts.roundsFull % 2 !== 0)
|
|
39
|
+
throw new Error(`Poseidon roundsFull is not even: ${opts.roundsFull}`);
|
|
40
|
+
const rounds = opts.roundsFull + opts.roundsPartial;
|
|
41
|
+
|
|
42
|
+
if (!Array.isArray(opts.roundConstants) || opts.roundConstants.length !== rounds)
|
|
43
|
+
throw new Error('Poseidon: wrong round constants');
|
|
44
|
+
const roundConstants = opts.roundConstants.map((rc) => {
|
|
45
|
+
if (!Array.isArray(rc) || rc.length !== opts.t)
|
|
46
|
+
throw new Error(`Poseidon wrong round constants: ${rc}`);
|
|
47
|
+
return rc.map((i) => {
|
|
48
|
+
if (typeof i !== 'bigint' || !Fp.isValid(i))
|
|
49
|
+
throw new Error(`Poseidon wrong round constant=${i}`);
|
|
50
|
+
return Fp.create(i);
|
|
51
|
+
});
|
|
52
|
+
});
|
|
53
|
+
// MDS is TxT matrix
|
|
54
|
+
if (!Array.isArray(opts.mds) || opts.mds.length !== opts.t)
|
|
55
|
+
throw new Error('Poseidon: wrong MDS matrix');
|
|
56
|
+
const mds = opts.mds.map((mdsRow) => {
|
|
57
|
+
if (!Array.isArray(mdsRow) || mdsRow.length !== opts.t)
|
|
58
|
+
throw new Error(`Poseidon MDS matrix row: ${mdsRow}`);
|
|
59
|
+
return mdsRow.map((i) => {
|
|
60
|
+
if (typeof i !== 'bigint') throw new Error(`Poseidon MDS matrix value=${i}`);
|
|
61
|
+
return Fp.create(i);
|
|
62
|
+
});
|
|
63
|
+
});
|
|
64
|
+
return Object.freeze({ ...opts, rounds, sboxFn, roundConstants, mds });
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
export function splitConstants(rc: bigint[], t: number) {
|
|
68
|
+
if (typeof t !== 'number') throw new Error('poseidonSplitConstants: wrong t');
|
|
69
|
+
if (!Array.isArray(rc) || rc.length % t) throw new Error('poseidonSplitConstants: wrong rc');
|
|
70
|
+
const res = [];
|
|
71
|
+
let tmp = [];
|
|
72
|
+
for (let i = 0; i < rc.length; i++) {
|
|
73
|
+
tmp.push(rc[i]);
|
|
74
|
+
if (tmp.length === t) {
|
|
75
|
+
res.push(tmp);
|
|
76
|
+
tmp = [];
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
return res;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
export function poseidon(opts: PoseidonOpts) {
|
|
83
|
+
const { t, Fp, rounds, sboxFn, reversePartialPowIdx } = validateOpts(opts);
|
|
84
|
+
const halfRoundsFull = Math.floor(opts.roundsFull / 2);
|
|
85
|
+
const partialIdx = reversePartialPowIdx ? t - 1 : 0;
|
|
86
|
+
const poseidonRound = (values: bigint[], isFull: boolean, idx: number) => {
|
|
87
|
+
values = values.map((i, j) => Fp.add(i, opts.roundConstants[idx][j]));
|
|
88
|
+
|
|
89
|
+
if (isFull) values = values.map((i) => sboxFn(i));
|
|
90
|
+
else values[partialIdx] = sboxFn(values[partialIdx]);
|
|
91
|
+
// Matrix multiplication
|
|
92
|
+
values = opts.mds.map((i) =>
|
|
93
|
+
i.reduce((acc, i, j) => Fp.add(acc, Fp.mulN(i, values[j])), Fp.ZERO)
|
|
94
|
+
);
|
|
95
|
+
return values;
|
|
96
|
+
};
|
|
97
|
+
const poseidonHash = function poseidonHash(values: bigint[]) {
|
|
98
|
+
if (!Array.isArray(values) || values.length !== t)
|
|
99
|
+
throw new Error(`Poseidon: wrong values (expected array of bigints with length ${t})`);
|
|
100
|
+
values = values.map((i) => {
|
|
101
|
+
if (typeof i !== 'bigint') throw new Error(`Poseidon: wrong value=${i} (${typeof i})`);
|
|
102
|
+
return Fp.create(i);
|
|
103
|
+
});
|
|
104
|
+
let round = 0;
|
|
105
|
+
// Apply r_f/2 full rounds.
|
|
106
|
+
for (let i = 0; i < halfRoundsFull; i++) values = poseidonRound(values, true, round++);
|
|
107
|
+
// Apply r_p partial rounds.
|
|
108
|
+
for (let i = 0; i < opts.roundsPartial; i++) values = poseidonRound(values, false, round++);
|
|
109
|
+
// Apply r_f/2 full rounds.
|
|
110
|
+
for (let i = 0; i < halfRoundsFull; i++) values = poseidonRound(values, true, round++);
|
|
111
|
+
|
|
112
|
+
if (round !== rounds)
|
|
113
|
+
throw new Error(`Poseidon: wrong number of rounds: last round=${round}, total=${rounds}`);
|
|
114
|
+
return values;
|
|
115
|
+
};
|
|
116
|
+
// For verification in tests
|
|
117
|
+
poseidonHash.roundConstants = opts.roundConstants;
|
|
118
|
+
return poseidonHash;
|
|
119
|
+
}
|
|
@@ -0,0 +1,246 @@
|
|
|
1
|
+
/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
|
|
2
|
+
const _0n = BigInt(0);
|
|
3
|
+
const _1n = BigInt(1);
|
|
4
|
+
const _2n = BigInt(2);
|
|
5
|
+
const u8a = (a: any): a is Uint8Array => a instanceof Uint8Array;
|
|
6
|
+
|
|
7
|
+
// We accept hex strings besides Uint8Array for simplicity
|
|
8
|
+
export type Hex = Uint8Array | string;
|
|
9
|
+
// Very few implementations accept numbers, we do it to ease learning curve
|
|
10
|
+
export type PrivKey = Hex | bigint;
|
|
11
|
+
export type CHash = {
|
|
12
|
+
(message: Uint8Array | string): Uint8Array;
|
|
13
|
+
blockLen: number;
|
|
14
|
+
outputLen: number;
|
|
15
|
+
create(opts?: { dkLen?: number }): any; // For shake
|
|
16
|
+
};
|
|
17
|
+
export type FHash = (message: Uint8Array | string) => Uint8Array;
|
|
18
|
+
|
|
19
|
+
const hexes = Array.from({ length: 256 }, (v, i) => i.toString(16).padStart(2, '0'));
|
|
20
|
+
export function bytesToHex(bytes: Uint8Array): string {
|
|
21
|
+
if (!u8a(bytes)) throw new Error('Uint8Array expected');
|
|
22
|
+
// pre-caching improves the speed 6x
|
|
23
|
+
let hex = '';
|
|
24
|
+
for (let i = 0; i < bytes.length; i++) {
|
|
25
|
+
hex += hexes[bytes[i]];
|
|
26
|
+
}
|
|
27
|
+
return hex;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
export function numberToHexUnpadded(num: number | bigint): string {
|
|
31
|
+
const hex = num.toString(16);
|
|
32
|
+
return hex.length & 1 ? `0${hex}` : hex;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export function hexToNumber(hex: string): bigint {
|
|
36
|
+
if (typeof hex !== 'string') throw new Error('hex string expected, got ' + typeof hex);
|
|
37
|
+
// Big Endian
|
|
38
|
+
return BigInt(hex === '' ? '0' : `0x${hex}`);
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
// Caching slows it down 2-3x
|
|
42
|
+
export function hexToBytes(hex: string): Uint8Array {
|
|
43
|
+
if (typeof hex !== 'string') throw new Error('hex string expected, got ' + typeof hex);
|
|
44
|
+
if (hex.length % 2) throw new Error('hex string is invalid: unpadded ' + hex.length);
|
|
45
|
+
const array = new Uint8Array(hex.length / 2);
|
|
46
|
+
for (let i = 0; i < array.length; i++) {
|
|
47
|
+
const j = i * 2;
|
|
48
|
+
const hexByte = hex.slice(j, j + 2);
|
|
49
|
+
const byte = Number.parseInt(hexByte, 16);
|
|
50
|
+
if (Number.isNaN(byte) || byte < 0) throw new Error('invalid byte sequence');
|
|
51
|
+
array[i] = byte;
|
|
52
|
+
}
|
|
53
|
+
return array;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
// Big Endian
|
|
57
|
+
export function bytesToNumberBE(bytes: Uint8Array): bigint {
|
|
58
|
+
return hexToNumber(bytesToHex(bytes));
|
|
59
|
+
}
|
|
60
|
+
export function bytesToNumberLE(bytes: Uint8Array): bigint {
|
|
61
|
+
if (!u8a(bytes)) throw new Error('Uint8Array expected');
|
|
62
|
+
return hexToNumber(bytesToHex(Uint8Array.from(bytes).reverse()));
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
export const numberToBytesBE = (n: bigint, len: number) =>
|
|
66
|
+
hexToBytes(n.toString(16).padStart(len * 2, '0'));
|
|
67
|
+
export const numberToBytesLE = (n: bigint, len: number) => numberToBytesBE(n, len).reverse();
|
|
68
|
+
// Returns variable number bytes (minimal bigint encoding?)
|
|
69
|
+
export const numberToVarBytesBE = (n: bigint) => hexToBytes(numberToHexUnpadded(n));
|
|
70
|
+
|
|
71
|
+
export function ensureBytes(title: string, hex: Hex, expectedLength?: number): Uint8Array {
|
|
72
|
+
let res: Uint8Array;
|
|
73
|
+
if (typeof hex === 'string') {
|
|
74
|
+
try {
|
|
75
|
+
res = hexToBytes(hex);
|
|
76
|
+
} catch (e) {
|
|
77
|
+
throw new Error(`${title} must be valid hex string, got "${hex}". Cause: ${e}`);
|
|
78
|
+
}
|
|
79
|
+
} else if (u8a(hex)) {
|
|
80
|
+
// Uint8Array.from() instead of hash.slice() because node.js Buffer
|
|
81
|
+
// is instance of Uint8Array, and its slice() creates **mutable** copy
|
|
82
|
+
res = Uint8Array.from(hex);
|
|
83
|
+
} else {
|
|
84
|
+
throw new Error(`${title} must be hex string or Uint8Array`);
|
|
85
|
+
}
|
|
86
|
+
const len = res.length;
|
|
87
|
+
if (typeof expectedLength === 'number' && len !== expectedLength)
|
|
88
|
+
throw new Error(`${title} expected ${expectedLength} bytes, got ${len}`);
|
|
89
|
+
return res;
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
// Copies several Uint8Arrays into one.
|
|
93
|
+
export function concatBytes(...arrs: Uint8Array[]): Uint8Array {
|
|
94
|
+
const r = new Uint8Array(arrs.reduce((sum, a) => sum + a.length, 0));
|
|
95
|
+
let pad = 0; // walk through each item, ensure they have proper type
|
|
96
|
+
arrs.forEach((a) => {
|
|
97
|
+
if (!u8a(a)) throw new Error('Uint8Array expected');
|
|
98
|
+
r.set(a, pad);
|
|
99
|
+
pad += a.length;
|
|
100
|
+
});
|
|
101
|
+
return r;
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
export function equalBytes(b1: Uint8Array, b2: Uint8Array) {
|
|
105
|
+
// We don't care about timing attacks here
|
|
106
|
+
if (b1.length !== b2.length) return false;
|
|
107
|
+
for (let i = 0; i < b1.length; i++) if (b1[i] !== b2[i]) return false;
|
|
108
|
+
return true;
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
// Global symbols in both browsers and Node.js since v11
|
|
112
|
+
// See https://github.com/microsoft/TypeScript/issues/31535
|
|
113
|
+
declare const TextEncoder: any;
|
|
114
|
+
export function utf8ToBytes(str: string): Uint8Array {
|
|
115
|
+
if (typeof str !== 'string') {
|
|
116
|
+
throw new Error(`utf8ToBytes expected string, got ${typeof str}`);
|
|
117
|
+
}
|
|
118
|
+
return new TextEncoder().encode(str);
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
// Bit operations
|
|
122
|
+
|
|
123
|
+
// Amount of bits inside bigint (Same as n.toString(2).length)
|
|
124
|
+
export function bitLen(n: bigint) {
|
|
125
|
+
let len;
|
|
126
|
+
for (len = 0; n > 0n; n >>= _1n, len += 1);
|
|
127
|
+
return len;
|
|
128
|
+
}
|
|
129
|
+
// Gets single bit at position. NOTE: first bit position is 0 (same as arrays)
|
|
130
|
+
// Same as !!+Array.from(n.toString(2)).reverse()[pos]
|
|
131
|
+
export const bitGet = (n: bigint, pos: number) => (n >> BigInt(pos)) & 1n;
|
|
132
|
+
// Sets single bit at position
|
|
133
|
+
export const bitSet = (n: bigint, pos: number, value: boolean) =>
|
|
134
|
+
n | ((value ? _1n : _0n) << BigInt(pos));
|
|
135
|
+
// Return mask for N bits (Same as BigInt(`0b${Array(i).fill('1').join('')}`))
|
|
136
|
+
// Not using ** operator with bigints for old engines.
|
|
137
|
+
export const bitMask = (n: number) => (_2n << BigInt(n - 1)) - _1n;
|
|
138
|
+
|
|
139
|
+
// DRBG
|
|
140
|
+
|
|
141
|
+
const u8n = (data?: any) => new Uint8Array(data); // creates Uint8Array
|
|
142
|
+
const u8fr = (arr: any) => Uint8Array.from(arr); // another shortcut
|
|
143
|
+
type Pred<T> = (v: Uint8Array) => T | undefined;
|
|
144
|
+
/**
|
|
145
|
+
* Minimal HMAC-DRBG from NIST 800-90 for RFC6979 sigs.
|
|
146
|
+
* @returns function that will call DRBG until 2nd arg returns something meaningful
|
|
147
|
+
* @example
|
|
148
|
+
* const drbg = createHmacDRBG<Key>(32, 32, hmac);
|
|
149
|
+
* drbg(seed, bytesToKey); // bytesToKey must return Key or undefined
|
|
150
|
+
*/
|
|
151
|
+
export function createHmacDrbg<T>(
|
|
152
|
+
hashLen: number,
|
|
153
|
+
qByteLen: number,
|
|
154
|
+
hmacFn: (key: Uint8Array, ...messages: Uint8Array[]) => Uint8Array
|
|
155
|
+
): (seed: Uint8Array, predicate: Pred<T>) => T {
|
|
156
|
+
if (typeof hashLen !== 'number' || hashLen < 2) throw new Error('hashLen must be a number');
|
|
157
|
+
if (typeof qByteLen !== 'number' || qByteLen < 2) throw new Error('qByteLen must be a number');
|
|
158
|
+
if (typeof hmacFn !== 'function') throw new Error('hmacFn must be a function');
|
|
159
|
+
// Step B, Step C: set hashLen to 8*ceil(hlen/8)
|
|
160
|
+
let v = u8n(hashLen); // Minimal non-full-spec HMAC-DRBG from NIST 800-90 for RFC6979 sigs.
|
|
161
|
+
let k = u8n(hashLen); // Steps B and C of RFC6979 3.2: set hashLen, in our case always same
|
|
162
|
+
let i = 0; // Iterations counter, will throw when over 1000
|
|
163
|
+
const reset = () => {
|
|
164
|
+
v.fill(1);
|
|
165
|
+
k.fill(0);
|
|
166
|
+
i = 0;
|
|
167
|
+
};
|
|
168
|
+
const h = (...b: Uint8Array[]) => hmacFn(k, v, ...b); // hmac(k)(v, ...values)
|
|
169
|
+
const reseed = (seed = u8n()) => {
|
|
170
|
+
// HMAC-DRBG reseed() function. Steps D-G
|
|
171
|
+
k = h(u8fr([0x00]), seed); // k = hmac(k || v || 0x00 || seed)
|
|
172
|
+
v = h(); // v = hmac(k || v)
|
|
173
|
+
if (seed.length === 0) return;
|
|
174
|
+
k = h(u8fr([0x01]), seed); // k = hmac(k || v || 0x01 || seed)
|
|
175
|
+
v = h(); // v = hmac(k || v)
|
|
176
|
+
};
|
|
177
|
+
const gen = () => {
|
|
178
|
+
// HMAC-DRBG generate() function
|
|
179
|
+
if (i++ >= 1000) throw new Error('drbg: tried 1000 values');
|
|
180
|
+
let len = 0;
|
|
181
|
+
const out: Uint8Array[] = [];
|
|
182
|
+
while (len < qByteLen) {
|
|
183
|
+
v = h();
|
|
184
|
+
const sl = v.slice();
|
|
185
|
+
out.push(sl);
|
|
186
|
+
len += v.length;
|
|
187
|
+
}
|
|
188
|
+
return concatBytes(...out);
|
|
189
|
+
};
|
|
190
|
+
const genUntil = (seed: Uint8Array, pred: Pred<T>): T => {
|
|
191
|
+
reset();
|
|
192
|
+
reseed(seed); // Steps D-G
|
|
193
|
+
let res: T | undefined = undefined; // Step H: grind until k is in [1..n-1]
|
|
194
|
+
while (!(res = pred(gen()))) reseed();
|
|
195
|
+
reset();
|
|
196
|
+
return res;
|
|
197
|
+
};
|
|
198
|
+
return genUntil;
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
// Validating curves and fields
|
|
202
|
+
|
|
203
|
+
const validatorFns = {
|
|
204
|
+
bigint: (val: any) => typeof val === 'bigint',
|
|
205
|
+
function: (val: any) => typeof val === 'function',
|
|
206
|
+
boolean: (val: any) => typeof val === 'boolean',
|
|
207
|
+
string: (val: any) => typeof val === 'string',
|
|
208
|
+
isSafeInteger: (val: any) => Number.isSafeInteger(val),
|
|
209
|
+
array: (val: any) => Array.isArray(val),
|
|
210
|
+
field: (val: any, object: any) => (object as any).Fp.isValid(val),
|
|
211
|
+
hash: (val: any) => typeof val === 'function' && Number.isSafeInteger(val.outputLen),
|
|
212
|
+
} as const;
|
|
213
|
+
type Validator = keyof typeof validatorFns;
|
|
214
|
+
type ValMap<T extends Record<string, any>> = { [K in keyof T]?: Validator };
|
|
215
|
+
// type Record<K extends string | number | symbol, T> = { [P in K]: T; }
|
|
216
|
+
|
|
217
|
+
export function validateObject<T extends Record<string, any>>(
|
|
218
|
+
object: T,
|
|
219
|
+
validators: ValMap<T>,
|
|
220
|
+
optValidators: ValMap<T> = {}
|
|
221
|
+
) {
|
|
222
|
+
const checkField = (fieldName: keyof T, type: Validator, isOptional: boolean) => {
|
|
223
|
+
const checkVal = validatorFns[type];
|
|
224
|
+
if (typeof checkVal !== 'function')
|
|
225
|
+
throw new Error(`Invalid validator "${type}", expected function`);
|
|
226
|
+
|
|
227
|
+
const val = object[fieldName as keyof typeof object];
|
|
228
|
+
if (isOptional && val === undefined) return;
|
|
229
|
+
if (!checkVal(val, object)) {
|
|
230
|
+
throw new Error(
|
|
231
|
+
`Invalid param ${String(fieldName)}=${val} (${typeof val}), expected ${type}`
|
|
232
|
+
);
|
|
233
|
+
}
|
|
234
|
+
};
|
|
235
|
+
for (const [fieldName, type] of Object.entries(validators)) checkField(fieldName, type!, false);
|
|
236
|
+
for (const [fieldName, type] of Object.entries(optValidators)) checkField(fieldName, type!, true);
|
|
237
|
+
return object;
|
|
238
|
+
}
|
|
239
|
+
// validate type tests
|
|
240
|
+
// const o: { a: number; b: number; c: number } = { a: 1, b: 5, c: 6 };
|
|
241
|
+
// const z0 = validateObject(o, { a: 'isSafeInteger' }, { c: 'bigint' }); // Ok!
|
|
242
|
+
// // Should fail type-check
|
|
243
|
+
// const z1 = validateObject(o, { a: 'tmp' }, { c: 'zz' });
|
|
244
|
+
// const z2 = validateObject(o, { a: 'isSafeInteger' }, { c: 'zz' });
|
|
245
|
+
// const z3 = validateObject(o, { test: 'boolean', z: 'bug' });
|
|
246
|
+
// const z4 = validateObject(o, { a: 'boolean', z: 'bug' });
|