@noble/curves 0.7.3 → 0.8.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.
Files changed (73) hide show
  1. package/README.md +16 -17
  2. package/_shortw_utils.js +8 -13
  3. package/_shortw_utils.js.map +1 -1
  4. package/abstract/bls.js +12 -16
  5. package/abstract/bls.js.map +1 -1
  6. package/abstract/curve.js +7 -12
  7. package/abstract/curve.js.map +1 -1
  8. package/abstract/edwards.js +16 -20
  9. package/abstract/edwards.js.map +1 -1
  10. package/abstract/hash-to-curve.d.ts +5 -3
  11. package/abstract/hash-to-curve.d.ts.map +1 -1
  12. package/abstract/hash-to-curve.js +25 -33
  13. package/abstract/hash-to-curve.js.map +1 -1
  14. package/abstract/modular.d.ts.map +1 -1
  15. package/abstract/modular.js +25 -44
  16. package/abstract/modular.js.map +1 -1
  17. package/abstract/montgomery.js +11 -15
  18. package/abstract/montgomery.js.map +1 -1
  19. package/abstract/poseidon.js +6 -12
  20. package/abstract/poseidon.js.map +1 -1
  21. package/abstract/utils.js +19 -41
  22. package/abstract/utils.js.map +1 -1
  23. package/abstract/weierstrass.d.ts.map +1 -1
  24. package/abstract/weierstrass.js +25 -37
  25. package/abstract/weierstrass.js.map +1 -1
  26. package/bls12-381.js +63 -66
  27. package/bls12-381.js.map +1 -1
  28. package/bn.js +7 -10
  29. package/bn.js.map +1 -1
  30. package/ed25519.d.ts +3 -0
  31. package/ed25519.d.ts.map +1 -1
  32. package/ed25519.js +81 -74
  33. package/ed25519.js.map +1 -1
  34. package/ed448.js +37 -41
  35. package/ed448.js.map +1 -1
  36. package/esm/abstract/hash-to-curve.js +8 -8
  37. package/esm/abstract/hash-to-curve.js.map +1 -1
  38. package/esm/abstract/modular.js +1 -0
  39. package/esm/abstract/modular.js.map +1 -1
  40. package/esm/abstract/weierstrass.js +4 -9
  41. package/esm/abstract/weierstrass.js.map +1 -1
  42. package/esm/ed25519.js +13 -1
  43. package/esm/ed25519.js.map +1 -1
  44. package/esm/package.json +1 -1
  45. package/esm/secp256k1.js +6 -7
  46. package/esm/secp256k1.js.map +1 -1
  47. package/jubjub.js +17 -22
  48. package/jubjub.js.map +1 -1
  49. package/p256.js +13 -17
  50. package/p256.js.map +1 -1
  51. package/p384.js +13 -17
  52. package/p384.js.map +1 -1
  53. package/p521.js +13 -17
  54. package/p521.js.map +1 -1
  55. package/package.json +3 -7
  56. package/pasta.js +16 -19
  57. package/pasta.js.map +1 -1
  58. package/secp256k1.d.ts +0 -6
  59. package/secp256k1.d.ts.map +1 -1
  60. package/secp256k1.js +58 -63
  61. package/secp256k1.js.map +1 -1
  62. package/src/abstract/hash-to-curve.ts +13 -12
  63. package/src/abstract/modular.ts +1 -0
  64. package/src/abstract/weierstrass.ts +4 -10
  65. package/src/ed25519.ts +17 -1
  66. package/src/secp256k1.ts +7 -7
  67. package/esm/stark.js +0 -251
  68. package/esm/stark.js.map +0 -1
  69. package/src/stark.ts +0 -318
  70. package/stark.d.ts +0 -83
  71. package/stark.d.ts.map +0 -1
  72. package/stark.js +0 -273
  73. package/stark.js.map +0 -1
package/esm/stark.js DELETED
@@ -1,251 +0,0 @@
1
- /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
2
- import { keccak_256 } from '@noble/hashes/sha3';
3
- import { sha256 } from '@noble/hashes/sha256';
4
- import { utf8ToBytes } from '@noble/hashes/utils';
5
- import { Fp, mod, validateField } from './abstract/modular.js';
6
- import { poseidon } from './abstract/poseidon.js';
7
- import { weierstrass } from './abstract/weierstrass.js';
8
- import { bitMask, bytesToHex, bytesToNumberBE, concatBytes, ensureBytes as ensureBytesOrig, hexToBytes, hexToNumber, numberToVarBytesBE, } from './abstract/utils.js';
9
- import { getHash } from './_shortw_utils.js';
10
- const CURVE_ORDER = BigInt('3618502788666131213697322783095070105526743751716087489154079457884512865583');
11
- const nBitLength = 252;
12
- function bits2int(bytes) {
13
- while (bytes[0] === 0)
14
- bytes = bytes.subarray(1); // strip leading 0s
15
- // Copy-pasted from weierstrass.ts
16
- const delta = bytes.length * 8 - nBitLength;
17
- const num = bytesToNumberBE(bytes);
18
- return delta > 0 ? num >> BigInt(delta) : num;
19
- }
20
- function hex0xToBytes(hex) {
21
- if (typeof hex === 'string') {
22
- hex = strip0x(hex); // allow 0x prefix
23
- if (hex.length & 1)
24
- hex = '0' + hex; // allow unpadded hex
25
- }
26
- return hexToBytes(hex);
27
- }
28
- const curve = weierstrass({
29
- a: BigInt(1),
30
- b: BigInt('3141592653589793238462643383279502884197169399375105820974944592307816406665'),
31
- // Field over which we'll do calculations; 2n**251n + 17n * 2n**192n + 1n
32
- // There is no efficient sqrt for field (P%4==1)
33
- Fp: Fp(BigInt('0x800000000000011000000000000000000000000000000000000000000000001')),
34
- n: CURVE_ORDER,
35
- nBitLength,
36
- // Base point (x, y) aka generator point
37
- Gx: BigInt('874739451078007766457464989774322083649278607533249481151382481072868806602'),
38
- Gy: BigInt('152666792071518830868575557812948353041420400780739481342941381225525861407'),
39
- h: BigInt(1),
40
- lowS: false,
41
- ...getHash(sha256),
42
- // Custom truncation routines for stark curve
43
- bits2int,
44
- bits2int_modN: (bytes) => {
45
- // 2102820b232636d200cb21f1d330f20d096cae09d1bf3edb1cc333ddee11318 =>
46
- // 2102820b232636d200cb21f1d330f20d096cae09d1bf3edb1cc333ddee113180
47
- const hex = bytesToNumberBE(bytes).toString(16); // toHex unpadded
48
- if (hex.length === 63)
49
- bytes = hex0xToBytes(hex + '0'); // append trailing 0
50
- return mod(bits2int(bytes), CURVE_ORDER);
51
- },
52
- });
53
- export const _starkCurve = curve;
54
- function ensureBytes(hex) {
55
- return ensureBytesOrig('', typeof hex === 'string' ? hex0xToBytes(hex) : hex);
56
- }
57
- function normPrivKey(privKey) {
58
- return bytesToHex(ensureBytes(privKey)).padStart(64, '0');
59
- }
60
- export function getPublicKey(privKey, isCompressed = false) {
61
- return curve.getPublicKey(normPrivKey(privKey), isCompressed);
62
- }
63
- export function getSharedSecret(privKeyA, pubKeyB) {
64
- return curve.getSharedSecret(normPrivKey(privKeyA), pubKeyB);
65
- }
66
- export function sign(msgHash, privKey, opts) {
67
- return curve.sign(ensureBytes(msgHash), normPrivKey(privKey), opts);
68
- }
69
- export function verify(signature, msgHash, pubKey) {
70
- const sig = signature instanceof Signature ? signature : ensureBytes(signature);
71
- return curve.verify(sig, ensureBytes(msgHash), ensureBytes(pubKey));
72
- }
73
- const { CURVE, ProjectivePoint, Signature, utils } = curve;
74
- export { CURVE, ProjectivePoint, Signature, utils };
75
- function extractX(bytes) {
76
- const hex = bytesToHex(bytes.subarray(1));
77
- const stripped = hex.replace(/^0+/gm, ''); // strip leading 0s
78
- return `0x${stripped}`;
79
- }
80
- function strip0x(hex) {
81
- return hex.replace(/^0x/i, '');
82
- }
83
- function numberTo0x16(num) {
84
- // can't use utils.numberToHexUnpadded: adds leading 0 for even byte length
85
- return `0x${num.toString(16)}`;
86
- }
87
- // seed generation
88
- export function grindKey(seed) {
89
- const _seed = ensureBytes(seed);
90
- const sha256mask = 2n ** 256n;
91
- const limit = sha256mask - mod(sha256mask, CURVE_ORDER);
92
- for (let i = 0;; i++) {
93
- const key = sha256Num(concatBytes(_seed, numberToVarBytesBE(BigInt(i))));
94
- if (key < limit)
95
- return mod(key, CURVE_ORDER).toString(16); // key should be in [0, limit)
96
- if (i === 100000)
97
- throw new Error('grindKey is broken: tried 100k vals'); // prevent dos
98
- }
99
- }
100
- export function getStarkKey(privateKey) {
101
- return extractX(getPublicKey(privateKey, true));
102
- }
103
- export function ethSigToPrivate(signature) {
104
- signature = strip0x(signature);
105
- if (signature.length !== 130)
106
- throw new Error('Wrong ethereum signature');
107
- return grindKey(signature.substring(0, 64));
108
- }
109
- const MASK_31 = 2n ** 31n - 1n;
110
- const int31 = (n) => Number(n & MASK_31);
111
- export function getAccountPath(layer, application, ethereumAddress, index) {
112
- const layerNum = int31(sha256Num(layer));
113
- const applicationNum = int31(sha256Num(application));
114
- const eth = hexToNumber(strip0x(ethereumAddress));
115
- return `m/2645'/${layerNum}'/${applicationNum}'/${int31(eth)}'/${int31(eth >> 31n)}'/${index}`;
116
- }
117
- // https://docs.starkware.co/starkex/pedersen-hash-function.html
118
- const PEDERSEN_POINTS = [
119
- new ProjectivePoint(2089986280348253421170679821480865132823066470938446095505822317253594081284n, 1713931329540660377023406109199410414810705867260802078187082345529207694986n, 1n),
120
- new ProjectivePoint(996781205833008774514500082376783249102396023663454813447423147977397232763n, 1668503676786377725805489344771023921079126552019160156920634619255970485781n, 1n),
121
- new ProjectivePoint(2251563274489750535117886426533222435294046428347329203627021249169616184184n, 1798716007562728905295480679789526322175868328062420237419143593021674992973n, 1n),
122
- new ProjectivePoint(2138414695194151160943305727036575959195309218611738193261179310511854807447n, 113410276730064486255102093846540133784865286929052426931474106396135072156n, 1n),
123
- new ProjectivePoint(2379962749567351885752724891227938183011949129833673362440656643086021394946n, 776496453633298175483985398648758586525933812536653089401905292063708816422n, 1n),
124
- ];
125
- function pedersenPrecompute(p1, p2) {
126
- const out = [];
127
- let p = p1;
128
- for (let i = 0; i < 248; i++) {
129
- out.push(p);
130
- p = p.double();
131
- }
132
- // NOTE: we cannot use wNAF here, because last 4 bits will require full 248 bits multiplication
133
- // We can add support for this to wNAF, but it will complicate wNAF.
134
- p = p2;
135
- for (let i = 0; i < 4; i++) {
136
- out.push(p);
137
- p = p.double();
138
- }
139
- return out;
140
- }
141
- const PEDERSEN_POINTS1 = pedersenPrecompute(PEDERSEN_POINTS[1], PEDERSEN_POINTS[2]);
142
- const PEDERSEN_POINTS2 = pedersenPrecompute(PEDERSEN_POINTS[3], PEDERSEN_POINTS[4]);
143
- function pedersenArg(arg) {
144
- let value;
145
- if (typeof arg === 'bigint') {
146
- value = arg;
147
- }
148
- else if (typeof arg === 'number') {
149
- if (!Number.isSafeInteger(arg))
150
- throw new Error(`Invalid pedersenArg: ${arg}`);
151
- value = BigInt(arg);
152
- }
153
- else {
154
- value = bytesToNumberBE(ensureBytes(arg));
155
- }
156
- if (!(0n <= value && value < curve.CURVE.Fp.ORDER))
157
- throw new Error(`PedersenArg should be 0 <= value < CURVE.P: ${value}`); // [0..Fp)
158
- return value;
159
- }
160
- function pedersenSingle(point, value, constants) {
161
- let x = pedersenArg(value);
162
- for (let j = 0; j < 252; j++) {
163
- const pt = constants[j];
164
- if (pt.px === point.px)
165
- throw new Error('Same point');
166
- if ((x & 1n) !== 0n)
167
- point = point.add(pt);
168
- x >>= 1n;
169
- }
170
- return point;
171
- }
172
- // shift_point + x_low * P_0 + x_high * P1 + y_low * P2 + y_high * P3
173
- export function pedersen(x, y) {
174
- let point = PEDERSEN_POINTS[0];
175
- point = pedersenSingle(point, x, PEDERSEN_POINTS1);
176
- point = pedersenSingle(point, y, PEDERSEN_POINTS2);
177
- return extractX(point.toRawBytes(true));
178
- }
179
- export function hashChain(data, fn = pedersen) {
180
- if (!Array.isArray(data) || data.length < 1)
181
- throw new Error('data should be array of at least 1 element');
182
- if (data.length === 1)
183
- return numberTo0x16(pedersenArg(data[0]));
184
- return Array.from(data)
185
- .reverse()
186
- .reduce((acc, i) => fn(i, acc));
187
- }
188
- // Same as hashChain, but computes hash even for single element and order is not revesed
189
- export const computeHashOnElements = (data, fn = pedersen) => [0, ...data, data.length].reduce((x, y) => fn(x, y));
190
- const MASK_250 = bitMask(250);
191
- export const keccak = (data) => bytesToNumberBE(keccak_256(data)) & MASK_250;
192
- const sha256Num = (data) => bytesToNumberBE(sha256(data));
193
- // Poseidon hash
194
- export const Fp253 = Fp(BigInt('14474011154664525231415395255581126252639794253786371766033694892385558855681')); // 2^253 + 2^199 + 1
195
- export const Fp251 = Fp(BigInt('3618502788666131213697322783095070105623107215331596699973092056135872020481')); // 2^251 + 17 * 2^192 + 1
196
- function poseidonRoundConstant(Fp, name, idx) {
197
- const val = Fp.fromBytes(sha256(utf8ToBytes(`${name}${idx}`)));
198
- return Fp.create(val);
199
- }
200
- // NOTE: doesn't check eiginvalues and possible can create unsafe matrix. But any filtration here will break compatibility with starknet
201
- // Please use only if you really know what you doing.
202
- // https://eprint.iacr.org/2019/458.pdf Section 2.3 (Avoiding Insecure Matrices)
203
- export function _poseidonMDS(Fp, name, m, attempt = 0) {
204
- const x_values = [];
205
- const y_values = [];
206
- for (let i = 0; i < m; i++) {
207
- x_values.push(poseidonRoundConstant(Fp, `${name}x`, attempt * m + i));
208
- y_values.push(poseidonRoundConstant(Fp, `${name}y`, attempt * m + i));
209
- }
210
- if (new Set([...x_values, ...y_values]).size !== 2 * m)
211
- throw new Error('X and Y values are not distinct');
212
- return x_values.map((x) => y_values.map((y) => Fp.inv(Fp.sub(x, y))));
213
- }
214
- const MDS_SMALL = [
215
- [3, 1, 1],
216
- [1, -1, 1],
217
- [1, 1, -2],
218
- ].map((i) => i.map(BigInt));
219
- export function poseidonBasic(opts, mds) {
220
- validateField(opts.Fp);
221
- if (!Number.isSafeInteger(opts.rate) || !Number.isSafeInteger(opts.capacity))
222
- throw new Error(`Wrong poseidon opts: ${opts}`);
223
- const m = opts.rate + opts.capacity;
224
- const rounds = opts.roundsFull + opts.roundsPartial;
225
- const roundConstants = [];
226
- for (let i = 0; i < rounds; i++) {
227
- const row = [];
228
- for (let j = 0; j < m; j++)
229
- row.push(poseidonRoundConstant(opts.Fp, 'Hades', m * i + j));
230
- roundConstants.push(row);
231
- }
232
- return poseidon({
233
- ...opts,
234
- t: m,
235
- sboxPower: 3,
236
- reversePartialPowIdx: true,
237
- mds,
238
- roundConstants,
239
- });
240
- }
241
- export function poseidonCreate(opts, mdsAttempt = 0) {
242
- const m = opts.rate + opts.capacity;
243
- if (!Number.isSafeInteger(mdsAttempt))
244
- throw new Error(`Wrong mdsAttempt=${mdsAttempt}`);
245
- return poseidonBasic(opts, _poseidonMDS(opts.Fp, 'HadesMDS', m, mdsAttempt));
246
- }
247
- export const poseidonSmall = poseidonBasic({ Fp: Fp251, rate: 2, capacity: 1, roundsFull: 8, roundsPartial: 83 }, MDS_SMALL);
248
- export function poseidonHash(x, y, fn = poseidonSmall) {
249
- return fn([x, y, 2n])[0];
250
- }
251
- //# sourceMappingURL=stark.js.map
package/esm/stark.js.map DELETED
@@ -1 +0,0 @@
1
- {"version":3,"file":"stark.js","sourceRoot":"","sources":["../src/stark.ts"],"names":[],"mappings":"AAAA,sEAAsE;AACtE,OAAO,EAAE,UAAU,EAAE,MAAM,oBAAoB,CAAC;AAChD,OAAO,EAAE,MAAM,EAAE,MAAM,sBAAsB,CAAC;AAC9C,OAAO,EAAE,WAAW,EAAE,MAAM,qBAAqB,CAAC;AAClD,OAAO,EAAE,EAAE,EAAE,GAAG,EAAS,aAAa,EAAE,MAAM,uBAAuB,CAAC;AACtE,OAAO,EAAE,QAAQ,EAAE,MAAM,wBAAwB,CAAC;AAClD,OAAO,EAAE,WAAW,EAAgC,MAAM,2BAA2B,CAAC;AACtF,OAAO,EAEL,OAAO,EACP,UAAU,EACV,eAAe,EACf,WAAW,EACX,WAAW,IAAI,eAAe,EAC9B,UAAU,EACV,WAAW,EACX,kBAAkB,GACnB,MAAM,qBAAqB,CAAC;AAC7B,OAAO,EAAE,OAAO,EAAE,MAAM,oBAAoB,CAAC;AAM7C,MAAM,WAAW,GAAG,MAAM,CACxB,8EAA8E,CAC/E,CAAC;AACF,MAAM,UAAU,GAAG,GAAG,CAAC;AACvB,SAAS,QAAQ,CAAC,KAAiB;IACjC,OAAO,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC;QAAE,KAAK,GAAG,KAAK,CAAC,QAAQ,CAAC,CAAC,CAAC,CAAC,CAAC,mBAAmB;IACrE,kCAAkC;IAClC,MAAM,KAAK,GAAG,KAAK,CAAC,MAAM,GAAG,CAAC,GAAG,UAAU,CAAC;IAC5C,MAAM,GAAG,GAAG,eAAe,CAAC,KAAK,CAAC,CAAC;IACnC,OAAO,KAAK,GAAG,CAAC,CAAC,CAAC,CAAC,GAAG,IAAI,MAAM,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC;AAChD,CAAC;AACD,SAAS,YAAY,CAAC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GAAG;QACH,cAAc;KACf,CAAC,CAAC;AACL,CAAC;AAED,MAAM,UAAU,cAAc,CAAC,IAAkB,EAAE,UAAU,GAAG,CAAC;IAC/D,MAAM,CAAC,GAAG,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC,QAAQ,CAAC;IACpC,IAAI,CAAC,MAAM,CAAC,aAAa,CAAC,UAAU,CAAC;QAAE,MAAM,IAAI,KAAK,CAAC,oBAAoB,UAAU,EAAE,CAAC,CAAC;IACzF,OAAO,aAAa,CAAC,IAAI,EAAE,YAAY,CAAC,IAAI,CAAC,EAAE,EAAE,UAAU,EAAE,CAAC,EAAE,UAAU,CAAC,CAAC,CAAC;AAC/E,CAAC;AAED,MAAM,CAAC,MAAM,aAAa,GAAG,aAAa,CACxC,EAAE,EAAE,EAAE,KAAK,EAAE,IAAI,EAAE,CAAC,EAAE,QAAQ,EAAE,CAAC,EAAE,UAAU,EAAE,CAAC,EAAE,aAAa,EAAE,EAAE,EAAE,EACrE,SAAS,CACV,CAAC;AAEF,MAAM,UAAU,YAAY,CAAC,CAAS,EAAE,CAAS,EAAE,EAAE,GAAG,aAAa;IACnE,OAAO,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;AAC3B,CAAC"}
package/src/stark.ts DELETED
@@ -1,318 +0,0 @@
1
- /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
2
- import { keccak_256 } from '@noble/hashes/sha3';
3
- import { sha256 } from '@noble/hashes/sha256';
4
- import { utf8ToBytes } from '@noble/hashes/utils';
5
- import { Fp, mod, Field, validateField } from './abstract/modular.js';
6
- import { poseidon } from './abstract/poseidon.js';
7
- import { weierstrass, ProjPointType, SignatureType } from './abstract/weierstrass.js';
8
- import {
9
- Hex,
10
- bitMask,
11
- bytesToHex,
12
- bytesToNumberBE,
13
- concatBytes,
14
- ensureBytes as ensureBytesOrig,
15
- hexToBytes,
16
- hexToNumber,
17
- numberToVarBytesBE,
18
- } from './abstract/utils.js';
19
- import { getHash } from './_shortw_utils.js';
20
-
21
- // Stark-friendly elliptic curve
22
- // https://docs.starkware.co/starkex/stark-curve.html
23
-
24
- type ProjectivePoint = ProjPointType<bigint>;
25
- const CURVE_ORDER = BigInt(
26
- '3618502788666131213697322783095070105526743751716087489154079457884512865583'
27
- );
28
- const nBitLength = 252;
29
- function bits2int(bytes: Uint8Array): bigint {
30
- while (bytes[0] === 0) bytes = bytes.subarray(1); // strip leading 0s
31
- // Copy-pasted from weierstrass.ts
32
- const delta = bytes.length * 8 - nBitLength;
33
- const num = bytesToNumberBE(bytes);
34
- return delta > 0 ? num >> BigInt(delta) : num;
35
- }
36
- function hex0xToBytes(hex: string): Uint8Array {
37
- if (typeof hex === 'string') {
38
- hex = strip0x(hex); // allow 0x prefix
39
- if (hex.length & 1) hex = '0' + hex; // allow unpadded hex
40
- }
41
- return hexToBytes(hex);
42
- }
43
- const curve = weierstrass({
44
- a: BigInt(1), // Params: a, b
45
- b: BigInt('3141592653589793238462643383279502884197169399375105820974944592307816406665'),
46
- // Field over which we'll do calculations; 2n**251n + 17n * 2n**192n + 1n
47
- // There is no efficient sqrt for field (P%4==1)
48
- Fp: Fp(BigInt('0x800000000000011000000000000000000000000000000000000000000000001')),
49
- n: CURVE_ORDER, // Curve order, total count of valid points in the field.
50
- nBitLength, // len(bin(N).replace('0b',''))
51
- // Base point (x, y) aka generator point
52
- Gx: BigInt('874739451078007766457464989774322083649278607533249481151382481072868806602'),
53
- Gy: BigInt('152666792071518830868575557812948353041420400780739481342941381225525861407'),
54
- h: BigInt(1), // cofactor
55
- lowS: false, // Allow high-s signatures
56
- ...getHash(sha256),
57
- // Custom truncation routines for stark curve
58
- bits2int,
59
- bits2int_modN: (bytes: Uint8Array): bigint => {
60
- // 2102820b232636d200cb21f1d330f20d096cae09d1bf3edb1cc333ddee11318 =>
61
- // 2102820b232636d200cb21f1d330f20d096cae09d1bf3edb1cc333ddee113180
62
- const hex = bytesToNumberBE(bytes).toString(16); // toHex unpadded
63
- if (hex.length === 63) bytes = hex0xToBytes(hex + '0'); // append trailing 0
64
- return mod(bits2int(bytes), CURVE_ORDER);
65
- },
66
- });
67
- export const _starkCurve = curve;
68
-
69
- function ensureBytes(hex: Hex): Uint8Array {
70
- return ensureBytesOrig('', typeof hex === 'string' ? hex0xToBytes(hex) : hex);
71
- }
72
-
73
- function normPrivKey(privKey: Hex): string {
74
- return bytesToHex(ensureBytes(privKey)).padStart(64, '0');
75
- }
76
- export function getPublicKey(privKey: Hex, isCompressed = false): Uint8Array {
77
- return curve.getPublicKey(normPrivKey(privKey), isCompressed);
78
- }
79
- export function getSharedSecret(privKeyA: Hex, pubKeyB: Hex): Uint8Array {
80
- return curve.getSharedSecret(normPrivKey(privKeyA), pubKeyB);
81
- }
82
- export function sign(msgHash: Hex, privKey: Hex, opts?: any): SignatureType {
83
- return curve.sign(ensureBytes(msgHash), normPrivKey(privKey), opts);
84
- }
85
- export function verify(signature: SignatureType | Hex, msgHash: Hex, pubKey: Hex) {
86
- const sig = signature instanceof Signature ? signature : ensureBytes(signature);
87
- return curve.verify(sig, ensureBytes(msgHash), ensureBytes(pubKey));
88
- }
89
-
90
- const { CURVE, ProjectivePoint, Signature, utils } = curve;
91
- export { CURVE, ProjectivePoint, Signature, utils };
92
-
93
- function extractX(bytes: Uint8Array): string {
94
- const hex = bytesToHex(bytes.subarray(1));
95
- const stripped = hex.replace(/^0+/gm, ''); // strip leading 0s
96
- return `0x${stripped}`;
97
- }
98
- function strip0x(hex: string) {
99
- return hex.replace(/^0x/i, '');
100
- }
101
- function numberTo0x16(num: bigint) {
102
- // can't use utils.numberToHexUnpadded: adds leading 0 for even byte length
103
- return `0x${num.toString(16)}`;
104
- }
105
-
106
- // seed generation
107
- export function grindKey(seed: Hex) {
108
- const _seed = ensureBytes(seed);
109
- const sha256mask = 2n ** 256n;
110
- const limit = sha256mask - mod(sha256mask, CURVE_ORDER);
111
- for (let i = 0; ; i++) {
112
- const key = sha256Num(concatBytes(_seed, numberToVarBytesBE(BigInt(i))));
113
- if (key < limit) return mod(key, CURVE_ORDER).toString(16); // key should be in [0, limit)
114
- if (i === 100000) throw new Error('grindKey is broken: tried 100k vals'); // prevent dos
115
- }
116
- }
117
-
118
- export function getStarkKey(privateKey: Hex): string {
119
- return extractX(getPublicKey(privateKey, true));
120
- }
121
-
122
- export function ethSigToPrivate(signature: string): string {
123
- signature = strip0x(signature);
124
- if (signature.length !== 130) throw new Error('Wrong ethereum signature');
125
- return grindKey(signature.substring(0, 64));
126
- }
127
-
128
- const MASK_31 = 2n ** 31n - 1n;
129
- const int31 = (n: bigint) => Number(n & MASK_31);
130
- export function getAccountPath(
131
- layer: string,
132
- application: string,
133
- ethereumAddress: string,
134
- index: number
135
- ): string {
136
- const layerNum = int31(sha256Num(layer));
137
- const applicationNum = int31(sha256Num(application));
138
- const eth = hexToNumber(strip0x(ethereumAddress));
139
- return `m/2645'/${layerNum}'/${applicationNum}'/${int31(eth)}'/${int31(eth >> 31n)}'/${index}`;
140
- }
141
-
142
- // https://docs.starkware.co/starkex/pedersen-hash-function.html
143
- const PEDERSEN_POINTS = [
144
- new ProjectivePoint(
145
- 2089986280348253421170679821480865132823066470938446095505822317253594081284n,
146
- 1713931329540660377023406109199410414810705867260802078187082345529207694986n,
147
- 1n
148
- ),
149
- new ProjectivePoint(
150
- 996781205833008774514500082376783249102396023663454813447423147977397232763n,
151
- 1668503676786377725805489344771023921079126552019160156920634619255970485781n,
152
- 1n
153
- ),
154
- new ProjectivePoint(
155
- 2251563274489750535117886426533222435294046428347329203627021249169616184184n,
156
- 1798716007562728905295480679789526322175868328062420237419143593021674992973n,
157
- 1n
158
- ),
159
- new ProjectivePoint(
160
- 2138414695194151160943305727036575959195309218611738193261179310511854807447n,
161
- 113410276730064486255102093846540133784865286929052426931474106396135072156n,
162
- 1n
163
- ),
164
- new ProjectivePoint(
165
- 2379962749567351885752724891227938183011949129833673362440656643086021394946n,
166
- 776496453633298175483985398648758586525933812536653089401905292063708816422n,
167
- 1n
168
- ),
169
- ];
170
-
171
- function pedersenPrecompute(p1: ProjectivePoint, p2: ProjectivePoint): ProjectivePoint[] {
172
- const out: ProjectivePoint[] = [];
173
- let p = p1;
174
- for (let i = 0; i < 248; i++) {
175
- out.push(p);
176
- p = p.double();
177
- }
178
- // NOTE: we cannot use wNAF here, because last 4 bits will require full 248 bits multiplication
179
- // We can add support for this to wNAF, but it will complicate wNAF.
180
- p = p2;
181
- for (let i = 0; i < 4; i++) {
182
- out.push(p);
183
- p = p.double();
184
- }
185
- return out;
186
- }
187
- const PEDERSEN_POINTS1 = pedersenPrecompute(PEDERSEN_POINTS[1], PEDERSEN_POINTS[2]);
188
- const PEDERSEN_POINTS2 = pedersenPrecompute(PEDERSEN_POINTS[3], PEDERSEN_POINTS[4]);
189
-
190
- type PedersenArg = Hex | bigint | number;
191
- function pedersenArg(arg: PedersenArg): bigint {
192
- let value: bigint;
193
- if (typeof arg === 'bigint') {
194
- value = arg;
195
- } else if (typeof arg === 'number') {
196
- if (!Number.isSafeInteger(arg)) throw new Error(`Invalid pedersenArg: ${arg}`);
197
- value = BigInt(arg);
198
- } else {
199
- value = bytesToNumberBE(ensureBytes(arg));
200
- }
201
- if (!(0n <= value && value < curve.CURVE.Fp.ORDER))
202
- throw new Error(`PedersenArg should be 0 <= value < CURVE.P: ${value}`); // [0..Fp)
203
- return value;
204
- }
205
-
206
- function pedersenSingle(point: ProjectivePoint, value: PedersenArg, constants: ProjectivePoint[]) {
207
- let x = pedersenArg(value);
208
- for (let j = 0; j < 252; j++) {
209
- const pt = constants[j];
210
- if (pt.px === point.px) throw new Error('Same point');
211
- if ((x & 1n) !== 0n) point = point.add(pt);
212
- x >>= 1n;
213
- }
214
- return point;
215
- }
216
-
217
- // shift_point + x_low * P_0 + x_high * P1 + y_low * P2 + y_high * P3
218
- export function pedersen(x: PedersenArg, y: PedersenArg): string {
219
- let point: ProjectivePoint = PEDERSEN_POINTS[0];
220
- point = pedersenSingle(point, x, PEDERSEN_POINTS1);
221
- point = pedersenSingle(point, y, PEDERSEN_POINTS2);
222
- return extractX(point.toRawBytes(true));
223
- }
224
-
225
- export function hashChain(data: PedersenArg[], fn = pedersen) {
226
- if (!Array.isArray(data) || data.length < 1)
227
- throw new Error('data should be array of at least 1 element');
228
- if (data.length === 1) return numberTo0x16(pedersenArg(data[0]));
229
- return Array.from(data)
230
- .reverse()
231
- .reduce((acc, i) => fn(i, acc));
232
- }
233
- // Same as hashChain, but computes hash even for single element and order is not revesed
234
- export const computeHashOnElements = (data: PedersenArg[], fn = pedersen) =>
235
- [0, ...data, data.length].reduce((x, y) => fn(x, y));
236
-
237
- const MASK_250 = bitMask(250);
238
- export const keccak = (data: Uint8Array): bigint => bytesToNumberBE(keccak_256(data)) & MASK_250;
239
- const sha256Num = (data: Uint8Array | string): bigint => bytesToNumberBE(sha256(data));
240
-
241
- // Poseidon hash
242
- export const Fp253 = Fp(
243
- BigInt('14474011154664525231415395255581126252639794253786371766033694892385558855681')
244
- ); // 2^253 + 2^199 + 1
245
- export const Fp251 = Fp(
246
- BigInt('3618502788666131213697322783095070105623107215331596699973092056135872020481')
247
- ); // 2^251 + 17 * 2^192 + 1
248
-
249
- function poseidonRoundConstant(Fp: Field<bigint>, name: string, idx: number) {
250
- const val = Fp.fromBytes(sha256(utf8ToBytes(`${name}${idx}`)));
251
- return Fp.create(val);
252
- }
253
-
254
- // NOTE: doesn't check eiginvalues and possible can create unsafe matrix. But any filtration here will break compatibility with starknet
255
- // Please use only if you really know what you doing.
256
- // https://eprint.iacr.org/2019/458.pdf Section 2.3 (Avoiding Insecure Matrices)
257
- export function _poseidonMDS(Fp: Field<bigint>, name: string, m: number, attempt = 0) {
258
- const x_values: bigint[] = [];
259
- const y_values: bigint[] = [];
260
- for (let i = 0; i < m; i++) {
261
- x_values.push(poseidonRoundConstant(Fp, `${name}x`, attempt * m + i));
262
- y_values.push(poseidonRoundConstant(Fp, `${name}y`, attempt * m + i));
263
- }
264
- if (new Set([...x_values, ...y_values]).size !== 2 * m)
265
- throw new Error('X and Y values are not distinct');
266
- return x_values.map((x) => y_values.map((y) => Fp.inv(Fp.sub(x, y))));
267
- }
268
-
269
- const MDS_SMALL = [
270
- [3, 1, 1],
271
- [1, -1, 1],
272
- [1, 1, -2],
273
- ].map((i) => i.map(BigInt));
274
-
275
- export type PoseidonOpts = {
276
- Fp: Field<bigint>;
277
- rate: number;
278
- capacity: number;
279
- roundsFull: number;
280
- roundsPartial: number;
281
- };
282
-
283
- export function poseidonBasic(opts: PoseidonOpts, mds: bigint[][]) {
284
- validateField(opts.Fp);
285
- if (!Number.isSafeInteger(opts.rate) || !Number.isSafeInteger(opts.capacity))
286
- throw new Error(`Wrong poseidon opts: ${opts}`);
287
- const m = opts.rate + opts.capacity;
288
- const rounds = opts.roundsFull + opts.roundsPartial;
289
- const roundConstants = [];
290
- for (let i = 0; i < rounds; i++) {
291
- const row = [];
292
- for (let j = 0; j < m; j++) row.push(poseidonRoundConstant(opts.Fp, 'Hades', m * i + j));
293
- roundConstants.push(row);
294
- }
295
- return poseidon({
296
- ...opts,
297
- t: m,
298
- sboxPower: 3,
299
- reversePartialPowIdx: true, // Why?!
300
- mds,
301
- roundConstants,
302
- });
303
- }
304
-
305
- export function poseidonCreate(opts: PoseidonOpts, mdsAttempt = 0) {
306
- const m = opts.rate + opts.capacity;
307
- if (!Number.isSafeInteger(mdsAttempt)) throw new Error(`Wrong mdsAttempt=${mdsAttempt}`);
308
- return poseidonBasic(opts, _poseidonMDS(opts.Fp, 'HadesMDS', m, mdsAttempt));
309
- }
310
-
311
- export const poseidonSmall = poseidonBasic(
312
- { Fp: Fp251, rate: 2, capacity: 1, roundsFull: 8, roundsPartial: 83 },
313
- MDS_SMALL
314
- );
315
-
316
- export function poseidonHash(x: bigint, y: bigint, fn = poseidonSmall) {
317
- return fn([x, y, 2n])[0];
318
- }
package/stark.d.ts DELETED
@@ -1,83 +0,0 @@
1
- import { Field } from './abstract/modular.js';
2
- import { ProjPointType, SignatureType } from './abstract/weierstrass.js';
3
- import { Hex } from './abstract/utils.js';
4
- declare type ProjectivePoint = ProjPointType<bigint>;
5
- export declare const _starkCurve: import("./abstract/weierstrass.js").CurveFn;
6
- export declare function getPublicKey(privKey: Hex, isCompressed?: boolean): Uint8Array;
7
- export declare function getSharedSecret(privKeyA: Hex, pubKeyB: Hex): Uint8Array;
8
- export declare function sign(msgHash: Hex, privKey: Hex, opts?: any): SignatureType;
9
- export declare function verify(signature: SignatureType | Hex, msgHash: Hex, pubKey: Hex): boolean;
10
- declare const CURVE: Readonly<{
11
- readonly nBitLength: number;
12
- readonly nByteLength: number;
13
- readonly Fp: Field<bigint>;
14
- readonly n: bigint;
15
- readonly h: bigint;
16
- readonly hEff?: bigint | undefined;
17
- readonly Gx: bigint;
18
- readonly Gy: bigint;
19
- readonly allowInfinityPoint?: boolean | undefined;
20
- readonly a: bigint;
21
- readonly b: bigint;
22
- readonly allowedPrivateKeyLengths?: readonly number[] | undefined;
23
- readonly wrapPrivateKey?: boolean | undefined;
24
- readonly endo?: {
25
- beta: bigint;
26
- splitScalar: (k: bigint) => {
27
- k1neg: boolean;
28
- k1: bigint;
29
- k2neg: boolean;
30
- k2: bigint;
31
- };
32
- } | undefined;
33
- readonly isTorsionFree?: ((c: import("./abstract/weierstrass.js").ProjConstructor<bigint>, point: ProjPointType<bigint>) => boolean) | undefined;
34
- readonly clearCofactor?: ((c: import("./abstract/weierstrass.js").ProjConstructor<bigint>, point: ProjPointType<bigint>) => ProjPointType<bigint>) | undefined;
35
- readonly hash: import("./abstract/utils.js").CHash;
36
- readonly hmac: (key: Uint8Array, ...messages: Uint8Array[]) => Uint8Array;
37
- readonly randomBytes: (bytesLength?: number | undefined) => Uint8Array;
38
- lowS: boolean;
39
- readonly bits2int?: ((bytes: Uint8Array) => bigint) | undefined;
40
- readonly bits2int_modN?: ((bytes: Uint8Array) => bigint) | undefined;
41
- }>, ProjectivePoint: import("./abstract/weierstrass.js").ProjConstructor<bigint>, Signature: import("./abstract/weierstrass.js").SignatureConstructor, utils: {
42
- normPrivateKeyToScalar: (key: import("./abstract/utils.js").PrivKey) => bigint;
43
- isValidPrivateKey(privateKey: import("./abstract/utils.js").PrivKey): boolean;
44
- randomPrivateKey: () => Uint8Array;
45
- precompute: (windowSize?: number | undefined, point?: ProjPointType<bigint> | undefined) => ProjPointType<bigint>;
46
- };
47
- export { CURVE, ProjectivePoint, Signature, utils };
48
- export declare function grindKey(seed: Hex): string;
49
- export declare function getStarkKey(privateKey: Hex): string;
50
- export declare function ethSigToPrivate(signature: string): string;
51
- export declare function getAccountPath(layer: string, application: string, ethereumAddress: string, index: number): string;
52
- declare type PedersenArg = Hex | bigint | number;
53
- export declare function pedersen(x: PedersenArg, y: PedersenArg): string;
54
- export declare function hashChain(data: PedersenArg[], fn?: typeof pedersen): PedersenArg;
55
- export declare const computeHashOnElements: (data: PedersenArg[], fn?: typeof pedersen) => PedersenArg;
56
- export declare const keccak: (data: Uint8Array) => bigint;
57
- export declare const Fp253: Readonly<Field<bigint> & Required<Pick<Field<bigint>, "isOdd">>>;
58
- export declare const Fp251: Readonly<Field<bigint> & Required<Pick<Field<bigint>, "isOdd">>>;
59
- export declare function _poseidonMDS(Fp: Field<bigint>, name: string, m: number, attempt?: number): bigint[][];
60
- export declare type PoseidonOpts = {
61
- Fp: Field<bigint>;
62
- rate: number;
63
- capacity: number;
64
- roundsFull: number;
65
- roundsPartial: number;
66
- };
67
- export declare function poseidonBasic(opts: PoseidonOpts, mds: bigint[][]): {
68
- (values: bigint[]): bigint[];
69
- roundConstants: bigint[][];
70
- };
71
- export declare function poseidonCreate(opts: PoseidonOpts, mdsAttempt?: number): {
72
- (values: bigint[]): bigint[];
73
- roundConstants: bigint[][];
74
- };
75
- export declare const poseidonSmall: {
76
- (values: bigint[]): bigint[];
77
- roundConstants: bigint[][];
78
- };
79
- export declare function poseidonHash(x: bigint, y: bigint, fn?: {
80
- (values: bigint[]): bigint[];
81
- roundConstants: bigint[][];
82
- }): bigint;
83
- //# sourceMappingURL=stark.d.ts.map