eth-crypto-ts 0.0.2 → 0.0.5
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 +10 -0
- package/dist/index.cjs.js +3896 -151
- package/dist/index.cjs.js.map +1 -1
- package/dist/index.d.ts +1 -5
- package/dist/index.esm.js +3891 -143
- package/dist/index.esm.js.map +1 -1
- package/dist/index.js +3891 -143
- package/dist/index.js.map +1 -1
- package/dist/lib/create-identity.d.ts +10 -9
- package/dist/lib/decrypt-with-private-key.d.ts +2 -2
- package/dist/lib/encrypt-with-public-key.d.ts +2 -0
- package/dist/lib/encryption-utils.d.ts +18 -0
- package/dist/lib/hash.d.ts +1 -0
- package/dist/lib/index.d.ts +27 -0
- package/dist/lib/public-key-by-private-key.d.ts +1 -2
- package/dist/lib/{recover-public-key.d.ts → recoverPublicKey.d.ts} +1 -1
- package/dist/lib/sign.d.ts +2 -2
- package/dist/{types → lib/types}/index.d.ts +2 -3
- package/dist/lib/utils.d.ts +37 -4
- package/package.json +23 -9
- package/dist/lib/cipher/index.d.ts +0 -11
- package/dist/lib/compress-public-key.d.ts +0 -1
- package/dist/lib/decompress-public-key.d.ts +0 -1
- package/dist/lib/encrypt-with-private-key.d.ts +0 -2
- package/dist/lib/hash/index.d.ts +0 -4
package/dist/index.cjs.js
CHANGED
|
@@ -2,211 +2,3956 @@
|
|
|
2
2
|
|
|
3
3
|
Object.defineProperty(exports, '__esModule', { value: true });
|
|
4
4
|
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
5
|
+
const SIGN_PREFIX = '\x19Ethereum Signed Message:\n32';
|
|
6
|
+
const MIN_ENTROPY_SIZE = 128;
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* Hex, bytes and number utilities.
|
|
10
|
+
* @module
|
|
11
|
+
*/
|
|
12
|
+
/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
|
|
13
|
+
// 100 lines of code in the file are duplicated from noble-hashes (utils).
|
|
14
|
+
// This is OK: `abstract` directory does not use noble-hashes.
|
|
15
|
+
// User may opt-in into using different hashing library. This way, noble-hashes
|
|
16
|
+
// won't be included into their bundle.
|
|
17
|
+
const _0n$4 = /* @__PURE__ */ BigInt(0);
|
|
18
|
+
const _1n$5 = /* @__PURE__ */ BigInt(1);
|
|
19
|
+
function isBytes$2(a) {
|
|
20
|
+
return a instanceof Uint8Array || (ArrayBuffer.isView(a) && a.constructor.name === 'Uint8Array');
|
|
21
|
+
}
|
|
22
|
+
function abytes$3(item) {
|
|
23
|
+
if (!isBytes$2(item))
|
|
24
|
+
throw new Error('Uint8Array expected');
|
|
25
|
+
}
|
|
26
|
+
function abool(title, value) {
|
|
27
|
+
if (typeof value !== 'boolean')
|
|
28
|
+
throw new Error(title + ' boolean expected, got ' + value);
|
|
29
|
+
}
|
|
30
|
+
// Used in weierstrass, der
|
|
31
|
+
function numberToHexUnpadded(num) {
|
|
32
|
+
const hex = num.toString(16);
|
|
33
|
+
return hex.length & 1 ? '0' + hex : hex;
|
|
34
|
+
}
|
|
35
|
+
function hexToNumber(hex) {
|
|
36
|
+
if (typeof hex !== 'string')
|
|
37
|
+
throw new Error('hex string expected, got ' + typeof hex);
|
|
38
|
+
return hex === '' ? _0n$4 : BigInt('0x' + hex); // Big Endian
|
|
39
|
+
}
|
|
40
|
+
// Built-in hex conversion https://caniuse.com/mdn-javascript_builtins_uint8array_fromhex
|
|
41
|
+
const hasHexBuiltin$1 =
|
|
42
|
+
// @ts-ignore
|
|
43
|
+
typeof Uint8Array.from([]).toHex === 'function' && typeof Uint8Array.fromHex === 'function';
|
|
44
|
+
// Array where index 0xf0 (240) is mapped to string 'f0'
|
|
45
|
+
const hexes$1 = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, '0'));
|
|
46
|
+
/**
|
|
47
|
+
* Convert byte array to hex string. Uses built-in function, when available.
|
|
48
|
+
* @example bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])) // 'cafe0123'
|
|
49
|
+
*/
|
|
50
|
+
function bytesToHex$1(bytes) {
|
|
51
|
+
abytes$3(bytes);
|
|
52
|
+
// @ts-ignore
|
|
53
|
+
if (hasHexBuiltin$1)
|
|
54
|
+
return bytes.toHex();
|
|
55
|
+
// pre-caching improves the speed 6x
|
|
56
|
+
let hex = '';
|
|
57
|
+
for (let i = 0; i < bytes.length; i++) {
|
|
58
|
+
hex += hexes$1[bytes[i]];
|
|
59
|
+
}
|
|
60
|
+
return hex;
|
|
61
|
+
}
|
|
62
|
+
// We use optimized technique to convert hex string to byte array
|
|
63
|
+
const asciis$1 = { _0: 48, _9: 57, A: 65, F: 70, a: 97, f: 102 };
|
|
64
|
+
function asciiToBase16$1(ch) {
|
|
65
|
+
if (ch >= asciis$1._0 && ch <= asciis$1._9)
|
|
66
|
+
return ch - asciis$1._0; // '2' => 50-48
|
|
67
|
+
if (ch >= asciis$1.A && ch <= asciis$1.F)
|
|
68
|
+
return ch - (asciis$1.A - 10); // 'B' => 66-(65-10)
|
|
69
|
+
if (ch >= asciis$1.a && ch <= asciis$1.f)
|
|
70
|
+
return ch - (asciis$1.a - 10); // 'b' => 98-(97-10)
|
|
71
|
+
return;
|
|
72
|
+
}
|
|
73
|
+
/**
|
|
74
|
+
* Convert hex string to byte array. Uses built-in function, when available.
|
|
75
|
+
* @example hexToBytes('cafe0123') // Uint8Array.from([0xca, 0xfe, 0x01, 0x23])
|
|
76
|
+
*/
|
|
77
|
+
function hexToBytes$2(hex) {
|
|
78
|
+
if (typeof hex !== 'string')
|
|
79
|
+
throw new Error('hex string expected, got ' + typeof hex);
|
|
80
|
+
// @ts-ignore
|
|
81
|
+
if (hasHexBuiltin$1)
|
|
82
|
+
return Uint8Array.fromHex(hex);
|
|
83
|
+
const hl = hex.length;
|
|
84
|
+
const al = hl / 2;
|
|
85
|
+
if (hl % 2)
|
|
86
|
+
throw new Error('hex string expected, got unpadded hex of length ' + hl);
|
|
87
|
+
const array = new Uint8Array(al);
|
|
88
|
+
for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) {
|
|
89
|
+
const n1 = asciiToBase16$1(hex.charCodeAt(hi));
|
|
90
|
+
const n2 = asciiToBase16$1(hex.charCodeAt(hi + 1));
|
|
91
|
+
if (n1 === undefined || n2 === undefined) {
|
|
92
|
+
const char = hex[hi] + hex[hi + 1];
|
|
93
|
+
throw new Error('hex string expected, got non-hex character "' + char + '" at index ' + hi);
|
|
94
|
+
}
|
|
95
|
+
array[ai] = n1 * 16 + n2; // multiply first octet, e.g. 'a3' => 10*16+3 => 160 + 3 => 163
|
|
96
|
+
}
|
|
97
|
+
return array;
|
|
98
|
+
}
|
|
99
|
+
// BE: Big Endian, LE: Little Endian
|
|
100
|
+
function bytesToNumberBE(bytes) {
|
|
101
|
+
return hexToNumber(bytesToHex$1(bytes));
|
|
102
|
+
}
|
|
103
|
+
function bytesToNumberLE(bytes) {
|
|
104
|
+
abytes$3(bytes);
|
|
105
|
+
return hexToNumber(bytesToHex$1(Uint8Array.from(bytes).reverse()));
|
|
106
|
+
}
|
|
107
|
+
function numberToBytesBE(n, len) {
|
|
108
|
+
return hexToBytes$2(n.toString(16).padStart(len * 2, '0'));
|
|
109
|
+
}
|
|
110
|
+
function numberToBytesLE(n, len) {
|
|
111
|
+
return numberToBytesBE(n, len).reverse();
|
|
112
|
+
}
|
|
113
|
+
/**
|
|
114
|
+
* Takes hex string or Uint8Array, converts to Uint8Array.
|
|
115
|
+
* Validates output length.
|
|
116
|
+
* Will throw error for other types.
|
|
117
|
+
* @param title descriptive title for an error e.g. 'private key'
|
|
118
|
+
* @param hex hex string or Uint8Array
|
|
119
|
+
* @param expectedLength optional, will compare to result array's length
|
|
120
|
+
* @returns
|
|
121
|
+
*/
|
|
122
|
+
function ensureBytes(title, hex, expectedLength) {
|
|
123
|
+
let res;
|
|
124
|
+
if (typeof hex === 'string') {
|
|
125
|
+
try {
|
|
126
|
+
res = hexToBytes$2(hex);
|
|
127
|
+
}
|
|
128
|
+
catch (e) {
|
|
129
|
+
throw new Error(title + ' must be hex string or Uint8Array, cause: ' + e);
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
else if (isBytes$2(hex)) {
|
|
133
|
+
// Uint8Array.from() instead of hash.slice() because node.js Buffer
|
|
134
|
+
// is instance of Uint8Array, and its slice() creates **mutable** copy
|
|
135
|
+
res = Uint8Array.from(hex);
|
|
136
|
+
}
|
|
137
|
+
else {
|
|
138
|
+
throw new Error(title + ' must be hex string or Uint8Array');
|
|
139
|
+
}
|
|
140
|
+
const len = res.length;
|
|
141
|
+
if (typeof expectedLength === 'number' && len !== expectedLength)
|
|
142
|
+
throw new Error(title + ' of length ' + expectedLength + ' expected, got ' + len);
|
|
143
|
+
return res;
|
|
144
|
+
}
|
|
145
|
+
/**
|
|
146
|
+
* Copies several Uint8Arrays into one.
|
|
147
|
+
*/
|
|
148
|
+
function concatBytes$1(...arrays) {
|
|
149
|
+
let sum = 0;
|
|
150
|
+
for (let i = 0; i < arrays.length; i++) {
|
|
151
|
+
const a = arrays[i];
|
|
152
|
+
abytes$3(a);
|
|
153
|
+
sum += a.length;
|
|
154
|
+
}
|
|
155
|
+
const res = new Uint8Array(sum);
|
|
156
|
+
for (let i = 0, pad = 0; i < arrays.length; i++) {
|
|
157
|
+
const a = arrays[i];
|
|
158
|
+
res.set(a, pad);
|
|
159
|
+
pad += a.length;
|
|
160
|
+
}
|
|
161
|
+
return res;
|
|
162
|
+
}
|
|
163
|
+
// Is positive bigint
|
|
164
|
+
const isPosBig = (n) => typeof n === 'bigint' && _0n$4 <= n;
|
|
165
|
+
function inRange(n, min, max) {
|
|
166
|
+
return isPosBig(n) && isPosBig(min) && isPosBig(max) && min <= n && n < max;
|
|
167
|
+
}
|
|
168
|
+
/**
|
|
169
|
+
* Asserts min <= n < max. NOTE: It's < max and not <= max.
|
|
170
|
+
* @example
|
|
171
|
+
* aInRange('x', x, 1n, 256n); // would assume x is in (1n..255n)
|
|
172
|
+
*/
|
|
173
|
+
function aInRange(title, n, min, max) {
|
|
174
|
+
// Why min <= n < max and not a (min < n < max) OR b (min <= n <= max)?
|
|
175
|
+
// consider P=256n, min=0n, max=P
|
|
176
|
+
// - a for min=0 would require -1: `inRange('x', x, -1n, P)`
|
|
177
|
+
// - b would commonly require subtraction: `inRange('x', x, 0n, P - 1n)`
|
|
178
|
+
// - our way is the cleanest: `inRange('x', x, 0n, P)
|
|
179
|
+
if (!inRange(n, min, max))
|
|
180
|
+
throw new Error('expected valid ' + title + ': ' + min + ' <= n < ' + max + ', got ' + n);
|
|
181
|
+
}
|
|
182
|
+
// Bit operations
|
|
183
|
+
/**
|
|
184
|
+
* Calculates amount of bits in a bigint.
|
|
185
|
+
* Same as `n.toString(2).length`
|
|
186
|
+
* TODO: merge with nLength in modular
|
|
187
|
+
*/
|
|
188
|
+
function bitLen(n) {
|
|
189
|
+
let len;
|
|
190
|
+
for (len = 0; n > _0n$4; n >>= _1n$5, len += 1)
|
|
191
|
+
;
|
|
192
|
+
return len;
|
|
193
|
+
}
|
|
194
|
+
/**
|
|
195
|
+
* Calculate mask for N bits. Not using ** operator with bigints because of old engines.
|
|
196
|
+
* Same as BigInt(`0b${Array(i).fill('1').join('')}`)
|
|
197
|
+
*/
|
|
198
|
+
const bitMask = (n) => (_1n$5 << BigInt(n)) - _1n$5;
|
|
199
|
+
// DRBG
|
|
200
|
+
const u8n = (len) => new Uint8Array(len); // creates Uint8Array
|
|
201
|
+
const u8fr = (arr) => Uint8Array.from(arr); // another shortcut
|
|
202
|
+
/**
|
|
203
|
+
* Minimal HMAC-DRBG from NIST 800-90 for RFC6979 sigs.
|
|
204
|
+
* @returns function that will call DRBG until 2nd arg returns something meaningful
|
|
205
|
+
* @example
|
|
206
|
+
* const drbg = createHmacDRBG<Key>(32, 32, hmac);
|
|
207
|
+
* drbg(seed, bytesToKey); // bytesToKey must return Key or undefined
|
|
208
|
+
*/
|
|
209
|
+
function createHmacDrbg(hashLen, qByteLen, hmacFn) {
|
|
210
|
+
if (typeof hashLen !== 'number' || hashLen < 2)
|
|
211
|
+
throw new Error('hashLen must be a number');
|
|
212
|
+
if (typeof qByteLen !== 'number' || qByteLen < 2)
|
|
213
|
+
throw new Error('qByteLen must be a number');
|
|
214
|
+
if (typeof hmacFn !== 'function')
|
|
215
|
+
throw new Error('hmacFn must be a function');
|
|
216
|
+
// Step B, Step C: set hashLen to 8*ceil(hlen/8)
|
|
217
|
+
let v = u8n(hashLen); // Minimal non-full-spec HMAC-DRBG from NIST 800-90 for RFC6979 sigs.
|
|
218
|
+
let k = u8n(hashLen); // Steps B and C of RFC6979 3.2: set hashLen, in our case always same
|
|
219
|
+
let i = 0; // Iterations counter, will throw when over 1000
|
|
220
|
+
const reset = () => {
|
|
221
|
+
v.fill(1);
|
|
222
|
+
k.fill(0);
|
|
223
|
+
i = 0;
|
|
224
|
+
};
|
|
225
|
+
const h = (...b) => hmacFn(k, v, ...b); // hmac(k)(v, ...values)
|
|
226
|
+
const reseed = (seed = u8n(0)) => {
|
|
227
|
+
// HMAC-DRBG reseed() function. Steps D-G
|
|
228
|
+
k = h(u8fr([0x00]), seed); // k = hmac(k || v || 0x00 || seed)
|
|
229
|
+
v = h(); // v = hmac(k || v)
|
|
230
|
+
if (seed.length === 0)
|
|
231
|
+
return;
|
|
232
|
+
k = h(u8fr([0x01]), seed); // k = hmac(k || v || 0x01 || seed)
|
|
233
|
+
v = h(); // v = hmac(k || v)
|
|
234
|
+
};
|
|
235
|
+
const gen = () => {
|
|
236
|
+
// HMAC-DRBG generate() function
|
|
237
|
+
if (i++ >= 1000)
|
|
238
|
+
throw new Error('drbg: tried 1000 values');
|
|
239
|
+
let len = 0;
|
|
240
|
+
const out = [];
|
|
241
|
+
while (len < qByteLen) {
|
|
242
|
+
v = h();
|
|
243
|
+
const sl = v.slice();
|
|
244
|
+
out.push(sl);
|
|
245
|
+
len += v.length;
|
|
246
|
+
}
|
|
247
|
+
return concatBytes$1(...out);
|
|
248
|
+
};
|
|
249
|
+
const genUntil = (seed, pred) => {
|
|
250
|
+
reset();
|
|
251
|
+
reseed(seed); // Steps D-G
|
|
252
|
+
let res = undefined; // Step H: grind until k is in [1..n-1]
|
|
253
|
+
while (!(res = pred(gen())))
|
|
254
|
+
reseed();
|
|
255
|
+
reset();
|
|
256
|
+
return res;
|
|
257
|
+
};
|
|
258
|
+
return genUntil;
|
|
259
|
+
}
|
|
260
|
+
// Validating curves and fields
|
|
261
|
+
const validatorFns = {
|
|
262
|
+
bigint: (val) => typeof val === 'bigint',
|
|
263
|
+
function: (val) => typeof val === 'function',
|
|
264
|
+
boolean: (val) => typeof val === 'boolean',
|
|
265
|
+
string: (val) => typeof val === 'string',
|
|
266
|
+
stringOrUint8Array: (val) => typeof val === 'string' || isBytes$2(val),
|
|
267
|
+
isSafeInteger: (val) => Number.isSafeInteger(val),
|
|
268
|
+
array: (val) => Array.isArray(val),
|
|
269
|
+
field: (val, object) => object.Fp.isValid(val),
|
|
270
|
+
hash: (val) => typeof val === 'function' && Number.isSafeInteger(val.outputLen),
|
|
271
|
+
};
|
|
272
|
+
// type Record<K extends string | number | symbol, T> = { [P in K]: T; }
|
|
273
|
+
function validateObject(object, validators, optValidators = {}) {
|
|
274
|
+
const checkField = (fieldName, type, isOptional) => {
|
|
275
|
+
const checkVal = validatorFns[type];
|
|
276
|
+
if (typeof checkVal !== 'function')
|
|
277
|
+
throw new Error('invalid validator function');
|
|
278
|
+
const val = object[fieldName];
|
|
279
|
+
if (isOptional && val === undefined)
|
|
280
|
+
return;
|
|
281
|
+
if (!checkVal(val, object)) {
|
|
282
|
+
throw new Error('param ' + String(fieldName) + ' is invalid. Expected ' + type + ', got ' + val);
|
|
283
|
+
}
|
|
284
|
+
};
|
|
285
|
+
for (const [fieldName, type] of Object.entries(validators))
|
|
286
|
+
checkField(fieldName, type, false);
|
|
287
|
+
for (const [fieldName, type] of Object.entries(optValidators))
|
|
288
|
+
checkField(fieldName, type, true);
|
|
289
|
+
return object;
|
|
290
|
+
}
|
|
291
|
+
/**
|
|
292
|
+
* Memoizes (caches) computation result.
|
|
293
|
+
* Uses WeakMap: the value is going auto-cleaned by GC after last reference is removed.
|
|
294
|
+
*/
|
|
295
|
+
function memoized(fn) {
|
|
296
|
+
const map = new WeakMap();
|
|
297
|
+
return (arg, ...args) => {
|
|
298
|
+
const val = map.get(arg);
|
|
299
|
+
if (val !== undefined)
|
|
300
|
+
return val;
|
|
301
|
+
const computed = fn(arg, ...args);
|
|
302
|
+
map.set(arg, computed);
|
|
303
|
+
return computed;
|
|
304
|
+
};
|
|
305
|
+
}
|
|
306
|
+
|
|
307
|
+
const crypto = typeof globalThis === 'object' && 'crypto' in globalThis ? globalThis.crypto : undefined;
|
|
308
|
+
|
|
309
|
+
/**
|
|
310
|
+
* Utilities for hex, bytes, CSPRNG.
|
|
311
|
+
* @module
|
|
312
|
+
*/
|
|
313
|
+
/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */
|
|
314
|
+
// We use WebCrypto aka globalThis.crypto, which exists in browsers and node.js 16+.
|
|
315
|
+
// node.js versions earlier than v19 don't declare it in global scope.
|
|
316
|
+
// For node.js, package.json#exports field mapping rewrites import
|
|
317
|
+
// from `crypto` to `cryptoNode`, which imports native module.
|
|
318
|
+
// Makes the utils un-importable in browsers without a bundler.
|
|
319
|
+
// Once node.js 18 is deprecated (2025-04-30), we can just drop the import.
|
|
320
|
+
/** Checks if something is Uint8Array. Be careful: nodejs Buffer will return true. */
|
|
321
|
+
function isBytes$1(a) {
|
|
322
|
+
return a instanceof Uint8Array || (ArrayBuffer.isView(a) && a.constructor.name === 'Uint8Array');
|
|
323
|
+
}
|
|
324
|
+
/** Asserts something is positive integer. */
|
|
325
|
+
function anumber(n) {
|
|
326
|
+
if (!Number.isSafeInteger(n) || n < 0)
|
|
327
|
+
throw new Error('positive integer expected, got ' + n);
|
|
328
|
+
}
|
|
329
|
+
/** Asserts something is Uint8Array. */
|
|
330
|
+
function abytes$2(b, ...lengths) {
|
|
331
|
+
if (!isBytes$1(b))
|
|
332
|
+
throw new Error('Uint8Array expected');
|
|
333
|
+
if (lengths.length > 0 && !lengths.includes(b.length))
|
|
334
|
+
throw new Error('Uint8Array expected of length ' + lengths + ', got length=' + b.length);
|
|
335
|
+
}
|
|
336
|
+
/** Asserts something is hash */
|
|
337
|
+
function ahash(h) {
|
|
338
|
+
if (typeof h !== 'function' || typeof h.create !== 'function')
|
|
339
|
+
throw new Error('Hash should be wrapped by utils.createHasher');
|
|
340
|
+
anumber(h.outputLen);
|
|
341
|
+
anumber(h.blockLen);
|
|
342
|
+
}
|
|
343
|
+
/** Asserts a hash instance has not been destroyed / finished */
|
|
344
|
+
function aexists(instance, checkFinished = true) {
|
|
345
|
+
if (instance.destroyed)
|
|
346
|
+
throw new Error('Hash instance has been destroyed');
|
|
347
|
+
if (checkFinished && instance.finished)
|
|
348
|
+
throw new Error('Hash#digest() has already been called');
|
|
349
|
+
}
|
|
350
|
+
/** Asserts output is properly-sized byte array */
|
|
351
|
+
function aoutput(out, instance) {
|
|
352
|
+
abytes$2(out);
|
|
353
|
+
const min = instance.outputLen;
|
|
354
|
+
if (out.length < min) {
|
|
355
|
+
throw new Error('digestInto() expects output buffer of length at least ' + min);
|
|
356
|
+
}
|
|
357
|
+
}
|
|
358
|
+
/** Cast u8 / u16 / u32 to u32. */
|
|
359
|
+
function u32$1(arr) {
|
|
360
|
+
return new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4));
|
|
361
|
+
}
|
|
362
|
+
/** Zeroize a byte array. Warning: JS provides no guarantees. */
|
|
363
|
+
function clean$1(...arrays) {
|
|
364
|
+
for (let i = 0; i < arrays.length; i++) {
|
|
365
|
+
arrays[i].fill(0);
|
|
366
|
+
}
|
|
367
|
+
}
|
|
368
|
+
/** Create DataView of an array for easy byte-level manipulation. */
|
|
369
|
+
function createView(arr) {
|
|
370
|
+
return new DataView(arr.buffer, arr.byteOffset, arr.byteLength);
|
|
371
|
+
}
|
|
372
|
+
/** The rotate right (circular right shift) operation for uint32 */
|
|
373
|
+
function rotr(word, shift) {
|
|
374
|
+
return (word << (32 - shift)) | (word >>> shift);
|
|
375
|
+
}
|
|
376
|
+
/** Is current platform little-endian? Most are. Big-Endian platform: IBM */
|
|
377
|
+
const isLE$1 = /* @__PURE__ */ (() => new Uint8Array(new Uint32Array([0x11223344]).buffer)[0] === 0x44)();
|
|
378
|
+
/** The byte swap operation for uint32 */
|
|
379
|
+
function byteSwap(word) {
|
|
380
|
+
return (((word << 24) & 0xff000000) |
|
|
381
|
+
((word << 8) & 0xff0000) |
|
|
382
|
+
((word >>> 8) & 0xff00) |
|
|
383
|
+
((word >>> 24) & 0xff));
|
|
384
|
+
}
|
|
385
|
+
/** In place byte swap for Uint32Array */
|
|
386
|
+
function byteSwap32(arr) {
|
|
387
|
+
for (let i = 0; i < arr.length; i++) {
|
|
388
|
+
arr[i] = byteSwap(arr[i]);
|
|
389
|
+
}
|
|
390
|
+
return arr;
|
|
391
|
+
}
|
|
392
|
+
const swap32IfBE = isLE$1
|
|
393
|
+
? (u) => u
|
|
394
|
+
: byteSwap32;
|
|
395
|
+
// Built-in hex conversion https://caniuse.com/mdn-javascript_builtins_uint8array_fromhex
|
|
396
|
+
const hasHexBuiltin = /* @__PURE__ */ (() =>
|
|
397
|
+
// @ts-ignore
|
|
398
|
+
typeof Uint8Array.from([]).toHex === 'function' && typeof Uint8Array.fromHex === 'function')();
|
|
399
|
+
// Array where index 0xf0 (240) is mapped to string 'f0'
|
|
400
|
+
const hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, '0'));
|
|
401
|
+
/**
|
|
402
|
+
* Convert byte array to hex string. Uses built-in function, when available.
|
|
403
|
+
* @example bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])) // 'cafe0123'
|
|
404
|
+
*/
|
|
405
|
+
function bytesToHex(bytes) {
|
|
406
|
+
abytes$2(bytes);
|
|
407
|
+
// @ts-ignore
|
|
408
|
+
if (hasHexBuiltin)
|
|
409
|
+
return bytes.toHex();
|
|
410
|
+
// pre-caching improves the speed 6x
|
|
411
|
+
let hex = '';
|
|
412
|
+
for (let i = 0; i < bytes.length; i++) {
|
|
413
|
+
hex += hexes[bytes[i]];
|
|
414
|
+
}
|
|
415
|
+
return hex;
|
|
416
|
+
}
|
|
417
|
+
// We use optimized technique to convert hex string to byte array
|
|
418
|
+
const asciis = { _0: 48, _9: 57, A: 65, F: 70, a: 97, f: 102 };
|
|
419
|
+
function asciiToBase16(ch) {
|
|
420
|
+
if (ch >= asciis._0 && ch <= asciis._9)
|
|
421
|
+
return ch - asciis._0; // '2' => 50-48
|
|
422
|
+
if (ch >= asciis.A && ch <= asciis.F)
|
|
423
|
+
return ch - (asciis.A - 10); // 'B' => 66-(65-10)
|
|
424
|
+
if (ch >= asciis.a && ch <= asciis.f)
|
|
425
|
+
return ch - (asciis.a - 10); // 'b' => 98-(97-10)
|
|
426
|
+
return;
|
|
427
|
+
}
|
|
428
|
+
/**
|
|
429
|
+
* Convert hex string to byte array. Uses built-in function, when available.
|
|
430
|
+
* @example hexToBytes('cafe0123') // Uint8Array.from([0xca, 0xfe, 0x01, 0x23])
|
|
431
|
+
*/
|
|
432
|
+
function hexToBytes$1(hex) {
|
|
433
|
+
if (typeof hex !== 'string')
|
|
434
|
+
throw new Error('hex string expected, got ' + typeof hex);
|
|
435
|
+
// @ts-ignore
|
|
436
|
+
if (hasHexBuiltin)
|
|
437
|
+
return Uint8Array.fromHex(hex);
|
|
438
|
+
const hl = hex.length;
|
|
439
|
+
const al = hl / 2;
|
|
440
|
+
if (hl % 2)
|
|
441
|
+
throw new Error('hex string expected, got unpadded hex of length ' + hl);
|
|
442
|
+
const array = new Uint8Array(al);
|
|
443
|
+
for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) {
|
|
444
|
+
const n1 = asciiToBase16(hex.charCodeAt(hi));
|
|
445
|
+
const n2 = asciiToBase16(hex.charCodeAt(hi + 1));
|
|
446
|
+
if (n1 === undefined || n2 === undefined) {
|
|
447
|
+
const char = hex[hi] + hex[hi + 1];
|
|
448
|
+
throw new Error('hex string expected, got non-hex character "' + char + '" at index ' + hi);
|
|
449
|
+
}
|
|
450
|
+
array[ai] = n1 * 16 + n2; // multiply first octet, e.g. 'a3' => 10*16+3 => 160 + 3 => 163
|
|
451
|
+
}
|
|
452
|
+
return array;
|
|
453
|
+
}
|
|
454
|
+
/**
|
|
455
|
+
* Converts string to bytes using UTF8 encoding.
|
|
456
|
+
* @example utf8ToBytes('abc') // Uint8Array.from([97, 98, 99])
|
|
457
|
+
*/
|
|
458
|
+
function utf8ToBytes$1(str) {
|
|
459
|
+
if (typeof str !== 'string')
|
|
460
|
+
throw new Error('string expected');
|
|
461
|
+
return new Uint8Array(new TextEncoder().encode(str)); // https://bugzil.la/1681809
|
|
462
|
+
}
|
|
463
|
+
/**
|
|
464
|
+
* Normalizes (non-hex) string or Uint8Array to Uint8Array.
|
|
465
|
+
* Warning: when Uint8Array is passed, it would NOT get copied.
|
|
466
|
+
* Keep in mind for future mutable operations.
|
|
467
|
+
*/
|
|
468
|
+
function toBytes(data) {
|
|
469
|
+
if (typeof data === 'string')
|
|
470
|
+
data = utf8ToBytes$1(data);
|
|
471
|
+
abytes$2(data);
|
|
472
|
+
return data;
|
|
473
|
+
}
|
|
474
|
+
/** Copies several Uint8Arrays into one. */
|
|
475
|
+
function concatBytes(...arrays) {
|
|
476
|
+
let sum = 0;
|
|
477
|
+
for (let i = 0; i < arrays.length; i++) {
|
|
478
|
+
const a = arrays[i];
|
|
479
|
+
abytes$2(a);
|
|
480
|
+
sum += a.length;
|
|
481
|
+
}
|
|
482
|
+
const res = new Uint8Array(sum);
|
|
483
|
+
for (let i = 0, pad = 0; i < arrays.length; i++) {
|
|
484
|
+
const a = arrays[i];
|
|
485
|
+
res.set(a, pad);
|
|
486
|
+
pad += a.length;
|
|
487
|
+
}
|
|
488
|
+
return res;
|
|
489
|
+
}
|
|
490
|
+
/** For runtime check if class implements interface */
|
|
491
|
+
class Hash {
|
|
492
|
+
}
|
|
493
|
+
/** Wraps hash function, creating an interface on top of it */
|
|
494
|
+
function createHasher(hashCons) {
|
|
495
|
+
const hashC = (msg) => hashCons().update(toBytes(msg)).digest();
|
|
496
|
+
const tmp = hashCons();
|
|
497
|
+
hashC.outputLen = tmp.outputLen;
|
|
498
|
+
hashC.blockLen = tmp.blockLen;
|
|
499
|
+
hashC.create = () => hashCons();
|
|
500
|
+
return hashC;
|
|
501
|
+
}
|
|
502
|
+
/** Cryptographically secure PRNG. Uses internal OS-level `crypto.getRandomValues`. */
|
|
503
|
+
function randomBytes(bytesLength = 32) {
|
|
504
|
+
if (crypto && typeof crypto.getRandomValues === 'function') {
|
|
505
|
+
return crypto.getRandomValues(new Uint8Array(bytesLength));
|
|
506
|
+
}
|
|
507
|
+
// Legacy Node.js compatibility
|
|
508
|
+
if (crypto && typeof crypto.randomBytes === 'function') {
|
|
509
|
+
return Uint8Array.from(crypto.randomBytes(bytesLength));
|
|
510
|
+
}
|
|
511
|
+
throw new Error('crypto.getRandomValues must be defined');
|
|
512
|
+
}
|
|
513
|
+
|
|
514
|
+
/**
|
|
515
|
+
* Internal assertion helpers.
|
|
516
|
+
* @module
|
|
517
|
+
* @deprecated
|
|
518
|
+
*/
|
|
519
|
+
/** @deprecated Use import from `noble/hashes/utils` module */
|
|
520
|
+
const abytes$1 = abytes$2;
|
|
521
|
+
|
|
522
|
+
// buf.toString('utf8') -> bytesToUtf8(buf)
|
|
523
|
+
function bytesToUtf8(data) {
|
|
524
|
+
if (!(data instanceof Uint8Array)) {
|
|
525
|
+
throw new TypeError(`bytesToUtf8 expected Uint8Array, got ${typeof data}`);
|
|
526
|
+
}
|
|
527
|
+
return new TextDecoder().decode(data);
|
|
528
|
+
}
|
|
529
|
+
function hexToBytes(data) {
|
|
530
|
+
const sliced = data.startsWith("0x") ? data.substring(2) : data;
|
|
531
|
+
return hexToBytes$1(sliced);
|
|
532
|
+
}
|
|
533
|
+
// Internal utils
|
|
534
|
+
function wrapHash(hash) {
|
|
535
|
+
return (msg) => {
|
|
536
|
+
abytes$1(msg);
|
|
537
|
+
return hash(msg);
|
|
538
|
+
};
|
|
539
|
+
}
|
|
540
|
+
|
|
541
|
+
/**
|
|
542
|
+
* Internal helpers for u64. BigUint64Array is too slow as per 2025, so we implement it using Uint32Array.
|
|
543
|
+
* @todo re-check https://issues.chromium.org/issues/42212588
|
|
544
|
+
* @module
|
|
545
|
+
*/
|
|
546
|
+
const U32_MASK64 = /* @__PURE__ */ BigInt(2 ** 32 - 1);
|
|
547
|
+
const _32n = /* @__PURE__ */ BigInt(32);
|
|
548
|
+
function fromBig(n, le = false) {
|
|
549
|
+
if (le)
|
|
550
|
+
return { h: Number(n & U32_MASK64), l: Number((n >> _32n) & U32_MASK64) };
|
|
551
|
+
return { h: Number((n >> _32n) & U32_MASK64) | 0, l: Number(n & U32_MASK64) | 0 };
|
|
552
|
+
}
|
|
553
|
+
function split(lst, le = false) {
|
|
554
|
+
const len = lst.length;
|
|
555
|
+
let Ah = new Uint32Array(len);
|
|
556
|
+
let Al = new Uint32Array(len);
|
|
557
|
+
for (let i = 0; i < len; i++) {
|
|
558
|
+
const { h, l } = fromBig(lst[i], le);
|
|
559
|
+
[Ah[i], Al[i]] = [h, l];
|
|
560
|
+
}
|
|
561
|
+
return [Ah, Al];
|
|
562
|
+
}
|
|
563
|
+
// for Shift in [0, 32)
|
|
564
|
+
const shrSH = (h, _l, s) => h >>> s;
|
|
565
|
+
const shrSL = (h, l, s) => (h << (32 - s)) | (l >>> s);
|
|
566
|
+
// Right rotate for Shift in [1, 32)
|
|
567
|
+
const rotrSH = (h, l, s) => (h >>> s) | (l << (32 - s));
|
|
568
|
+
const rotrSL = (h, l, s) => (h << (32 - s)) | (l >>> s);
|
|
569
|
+
// Right rotate for Shift in (32, 64), NOTE: 32 is special case.
|
|
570
|
+
const rotrBH = (h, l, s) => (h << (64 - s)) | (l >>> (s - 32));
|
|
571
|
+
const rotrBL = (h, l, s) => (h >>> (s - 32)) | (l << (64 - s));
|
|
572
|
+
// Left rotate for Shift in [1, 32)
|
|
573
|
+
const rotlSH = (h, l, s) => (h << s) | (l >>> (32 - s));
|
|
574
|
+
const rotlSL = (h, l, s) => (l << s) | (h >>> (32 - s));
|
|
575
|
+
// Left rotate for Shift in (32, 64), NOTE: 32 is special case.
|
|
576
|
+
const rotlBH = (h, l, s) => (l << (s - 32)) | (h >>> (64 - s));
|
|
577
|
+
const rotlBL = (h, l, s) => (h << (s - 32)) | (l >>> (64 - s));
|
|
578
|
+
// JS uses 32-bit signed integers for bitwise operations which means we cannot
|
|
579
|
+
// simple take carry out of low bit sum by shift, we need to use division.
|
|
580
|
+
function add(Ah, Al, Bh, Bl) {
|
|
581
|
+
const l = (Al >>> 0) + (Bl >>> 0);
|
|
582
|
+
return { h: (Ah + Bh + ((l / 2 ** 32) | 0)) | 0, l: l | 0 };
|
|
583
|
+
}
|
|
584
|
+
// Addition with more than 2 elements
|
|
585
|
+
const add3L = (Al, Bl, Cl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0);
|
|
586
|
+
const add3H = (low, Ah, Bh, Ch) => (Ah + Bh + Ch + ((low / 2 ** 32) | 0)) | 0;
|
|
587
|
+
const add4L = (Al, Bl, Cl, Dl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0);
|
|
588
|
+
const add4H = (low, Ah, Bh, Ch, Dh) => (Ah + Bh + Ch + Dh + ((low / 2 ** 32) | 0)) | 0;
|
|
589
|
+
const add5L = (Al, Bl, Cl, Dl, El) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0) + (El >>> 0);
|
|
590
|
+
const add5H = (low, Ah, Bh, Ch, Dh, Eh) => (Ah + Bh + Ch + Dh + Eh + ((low / 2 ** 32) | 0)) | 0;
|
|
591
|
+
|
|
592
|
+
/**
|
|
593
|
+
* SHA3 (keccak) hash function, based on a new "Sponge function" design.
|
|
594
|
+
* Different from older hashes, the internal state is bigger than output size.
|
|
595
|
+
*
|
|
596
|
+
* Check out [FIPS-202](https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.202.pdf),
|
|
597
|
+
* [Website](https://keccak.team/keccak.html),
|
|
598
|
+
* [the differences between SHA-3 and Keccak](https://crypto.stackexchange.com/questions/15727/what-are-the-key-differences-between-the-draft-sha-3-standard-and-the-keccak-sub).
|
|
599
|
+
*
|
|
600
|
+
* Check out `sha3-addons` module for cSHAKE, k12, and others.
|
|
601
|
+
* @module
|
|
602
|
+
*/
|
|
603
|
+
// No __PURE__ annotations in sha3 header:
|
|
604
|
+
// EVERYTHING is in fact used on every export.
|
|
605
|
+
// Various per round constants calculations
|
|
606
|
+
const _0n$3 = BigInt(0);
|
|
607
|
+
const _1n$4 = BigInt(1);
|
|
608
|
+
const _2n$2 = BigInt(2);
|
|
609
|
+
const _7n = BigInt(7);
|
|
610
|
+
const _256n = BigInt(256);
|
|
611
|
+
const _0x71n = BigInt(0x71);
|
|
612
|
+
const SHA3_PI = [];
|
|
613
|
+
const SHA3_ROTL = [];
|
|
614
|
+
const _SHA3_IOTA = [];
|
|
615
|
+
for (let round = 0, R = _1n$4, x = 1, y = 0; round < 24; round++) {
|
|
616
|
+
// Pi
|
|
617
|
+
[x, y] = [y, (2 * x + 3 * y) % 5];
|
|
618
|
+
SHA3_PI.push(2 * (5 * y + x));
|
|
619
|
+
// Rotational
|
|
620
|
+
SHA3_ROTL.push((((round + 1) * (round + 2)) / 2) % 64);
|
|
621
|
+
// Iota
|
|
622
|
+
let t = _0n$3;
|
|
623
|
+
for (let j = 0; j < 7; j++) {
|
|
624
|
+
R = ((R << _1n$4) ^ ((R >> _7n) * _0x71n)) % _256n;
|
|
625
|
+
if (R & _2n$2)
|
|
626
|
+
t ^= _1n$4 << ((_1n$4 << /* @__PURE__ */ BigInt(j)) - _1n$4);
|
|
627
|
+
}
|
|
628
|
+
_SHA3_IOTA.push(t);
|
|
629
|
+
}
|
|
630
|
+
const IOTAS = split(_SHA3_IOTA, true);
|
|
631
|
+
const SHA3_IOTA_H = IOTAS[0];
|
|
632
|
+
const SHA3_IOTA_L = IOTAS[1];
|
|
633
|
+
// Left rotation (without 0, 32, 64)
|
|
634
|
+
const rotlH = (h, l, s) => (s > 32 ? rotlBH(h, l, s) : rotlSH(h, l, s));
|
|
635
|
+
const rotlL = (h, l, s) => (s > 32 ? rotlBL(h, l, s) : rotlSL(h, l, s));
|
|
636
|
+
/** `keccakf1600` internal function, additionally allows to adjust round count. */
|
|
637
|
+
function keccakP(s, rounds = 24) {
|
|
638
|
+
const B = new Uint32Array(5 * 2);
|
|
639
|
+
// NOTE: all indices are x2 since we store state as u32 instead of u64 (bigints to slow in js)
|
|
640
|
+
for (let round = 24 - rounds; round < 24; round++) {
|
|
641
|
+
// Theta θ
|
|
642
|
+
for (let x = 0; x < 10; x++)
|
|
643
|
+
B[x] = s[x] ^ s[x + 10] ^ s[x + 20] ^ s[x + 30] ^ s[x + 40];
|
|
644
|
+
for (let x = 0; x < 10; x += 2) {
|
|
645
|
+
const idx1 = (x + 8) % 10;
|
|
646
|
+
const idx0 = (x + 2) % 10;
|
|
647
|
+
const B0 = B[idx0];
|
|
648
|
+
const B1 = B[idx0 + 1];
|
|
649
|
+
const Th = rotlH(B0, B1, 1) ^ B[idx1];
|
|
650
|
+
const Tl = rotlL(B0, B1, 1) ^ B[idx1 + 1];
|
|
651
|
+
for (let y = 0; y < 50; y += 10) {
|
|
652
|
+
s[x + y] ^= Th;
|
|
653
|
+
s[x + y + 1] ^= Tl;
|
|
654
|
+
}
|
|
655
|
+
}
|
|
656
|
+
// Rho (ρ) and Pi (π)
|
|
657
|
+
let curH = s[2];
|
|
658
|
+
let curL = s[3];
|
|
659
|
+
for (let t = 0; t < 24; t++) {
|
|
660
|
+
const shift = SHA3_ROTL[t];
|
|
661
|
+
const Th = rotlH(curH, curL, shift);
|
|
662
|
+
const Tl = rotlL(curH, curL, shift);
|
|
663
|
+
const PI = SHA3_PI[t];
|
|
664
|
+
curH = s[PI];
|
|
665
|
+
curL = s[PI + 1];
|
|
666
|
+
s[PI] = Th;
|
|
667
|
+
s[PI + 1] = Tl;
|
|
668
|
+
}
|
|
669
|
+
// Chi (χ)
|
|
670
|
+
for (let y = 0; y < 50; y += 10) {
|
|
671
|
+
for (let x = 0; x < 10; x++)
|
|
672
|
+
B[x] = s[y + x];
|
|
673
|
+
for (let x = 0; x < 10; x++)
|
|
674
|
+
s[y + x] ^= ~B[(x + 2) % 10] & B[(x + 4) % 10];
|
|
675
|
+
}
|
|
676
|
+
// Iota (ι)
|
|
677
|
+
s[0] ^= SHA3_IOTA_H[round];
|
|
678
|
+
s[1] ^= SHA3_IOTA_L[round];
|
|
679
|
+
}
|
|
680
|
+
clean$1(B);
|
|
15
681
|
}
|
|
16
|
-
function
|
|
682
|
+
/** Keccak sponge function. */
|
|
683
|
+
class Keccak extends Hash {
|
|
684
|
+
// NOTE: we accept arguments in bytes instead of bits here.
|
|
685
|
+
constructor(blockLen, suffix, outputLen, enableXOF = false, rounds = 24) {
|
|
686
|
+
super();
|
|
687
|
+
this.pos = 0;
|
|
688
|
+
this.posOut = 0;
|
|
689
|
+
this.finished = false;
|
|
690
|
+
this.destroyed = false;
|
|
691
|
+
this.enableXOF = false;
|
|
692
|
+
this.blockLen = blockLen;
|
|
693
|
+
this.suffix = suffix;
|
|
694
|
+
this.outputLen = outputLen;
|
|
695
|
+
this.enableXOF = enableXOF;
|
|
696
|
+
this.rounds = rounds;
|
|
697
|
+
// Can be passed from user as dkLen
|
|
698
|
+
anumber(outputLen);
|
|
699
|
+
// 1600 = 5x5 matrix of 64bit. 1600 bits === 200 bytes
|
|
700
|
+
// 0 < blockLen < 200
|
|
701
|
+
if (!(0 < blockLen && blockLen < 200))
|
|
702
|
+
throw new Error('only keccak-f1600 function is supported');
|
|
703
|
+
this.state = new Uint8Array(200);
|
|
704
|
+
this.state32 = u32$1(this.state);
|
|
705
|
+
}
|
|
706
|
+
clone() {
|
|
707
|
+
return this._cloneInto();
|
|
708
|
+
}
|
|
709
|
+
keccak() {
|
|
710
|
+
swap32IfBE(this.state32);
|
|
711
|
+
keccakP(this.state32, this.rounds);
|
|
712
|
+
swap32IfBE(this.state32);
|
|
713
|
+
this.posOut = 0;
|
|
714
|
+
this.pos = 0;
|
|
715
|
+
}
|
|
716
|
+
update(data) {
|
|
717
|
+
aexists(this);
|
|
718
|
+
data = toBytes(data);
|
|
719
|
+
abytes$2(data);
|
|
720
|
+
const { blockLen, state } = this;
|
|
721
|
+
const len = data.length;
|
|
722
|
+
for (let pos = 0; pos < len;) {
|
|
723
|
+
const take = Math.min(blockLen - this.pos, len - pos);
|
|
724
|
+
for (let i = 0; i < take; i++)
|
|
725
|
+
state[this.pos++] ^= data[pos++];
|
|
726
|
+
if (this.pos === blockLen)
|
|
727
|
+
this.keccak();
|
|
728
|
+
}
|
|
729
|
+
return this;
|
|
730
|
+
}
|
|
731
|
+
finish() {
|
|
732
|
+
if (this.finished)
|
|
733
|
+
return;
|
|
734
|
+
this.finished = true;
|
|
735
|
+
const { state, suffix, pos, blockLen } = this;
|
|
736
|
+
// Do the padding
|
|
737
|
+
state[pos] ^= suffix;
|
|
738
|
+
if ((suffix & 0x80) !== 0 && pos === blockLen - 1)
|
|
739
|
+
this.keccak();
|
|
740
|
+
state[blockLen - 1] ^= 0x80;
|
|
741
|
+
this.keccak();
|
|
742
|
+
}
|
|
743
|
+
writeInto(out) {
|
|
744
|
+
aexists(this, false);
|
|
745
|
+
abytes$2(out);
|
|
746
|
+
this.finish();
|
|
747
|
+
const bufferOut = this.state;
|
|
748
|
+
const { blockLen } = this;
|
|
749
|
+
for (let pos = 0, len = out.length; pos < len;) {
|
|
750
|
+
if (this.posOut >= blockLen)
|
|
751
|
+
this.keccak();
|
|
752
|
+
const take = Math.min(blockLen - this.posOut, len - pos);
|
|
753
|
+
out.set(bufferOut.subarray(this.posOut, this.posOut + take), pos);
|
|
754
|
+
this.posOut += take;
|
|
755
|
+
pos += take;
|
|
756
|
+
}
|
|
757
|
+
return out;
|
|
758
|
+
}
|
|
759
|
+
xofInto(out) {
|
|
760
|
+
// Sha3/Keccak usage with XOF is probably mistake, only SHAKE instances can do XOF
|
|
761
|
+
if (!this.enableXOF)
|
|
762
|
+
throw new Error('XOF is not possible for this instance');
|
|
763
|
+
return this.writeInto(out);
|
|
764
|
+
}
|
|
765
|
+
xof(bytes) {
|
|
766
|
+
anumber(bytes);
|
|
767
|
+
return this.xofInto(new Uint8Array(bytes));
|
|
768
|
+
}
|
|
769
|
+
digestInto(out) {
|
|
770
|
+
aoutput(out, this);
|
|
771
|
+
if (this.finished)
|
|
772
|
+
throw new Error('digest() was already called');
|
|
773
|
+
this.writeInto(out);
|
|
774
|
+
this.destroy();
|
|
775
|
+
return out;
|
|
776
|
+
}
|
|
777
|
+
digest() {
|
|
778
|
+
return this.digestInto(new Uint8Array(this.outputLen));
|
|
779
|
+
}
|
|
780
|
+
destroy() {
|
|
781
|
+
this.destroyed = true;
|
|
782
|
+
clean$1(this.state);
|
|
783
|
+
}
|
|
784
|
+
_cloneInto(to) {
|
|
785
|
+
const { blockLen, suffix, outputLen, rounds, enableXOF } = this;
|
|
786
|
+
to || (to = new Keccak(blockLen, suffix, outputLen, enableXOF, rounds));
|
|
787
|
+
to.state32.set(this.state32);
|
|
788
|
+
to.pos = this.pos;
|
|
789
|
+
to.posOut = this.posOut;
|
|
790
|
+
to.finished = this.finished;
|
|
791
|
+
to.rounds = rounds;
|
|
792
|
+
// Suffix can change in cSHAKE
|
|
793
|
+
to.suffix = suffix;
|
|
794
|
+
to.outputLen = outputLen;
|
|
795
|
+
to.enableXOF = enableXOF;
|
|
796
|
+
to.destroyed = this.destroyed;
|
|
797
|
+
return to;
|
|
798
|
+
}
|
|
799
|
+
}
|
|
800
|
+
const gen = (suffix, blockLen, outputLen) => createHasher(() => new Keccak(blockLen, suffix, outputLen));
|
|
801
|
+
/** keccak-256 hash function. Different from SHA3-256. */
|
|
802
|
+
const keccak_256 = /* @__PURE__ */ (() => gen(0x01, 136, 256 / 8))();
|
|
803
|
+
|
|
804
|
+
const keccak256$1 = (() => {
|
|
805
|
+
const k = wrapHash(keccak_256);
|
|
806
|
+
k.create = keccak_256.create;
|
|
807
|
+
return k;
|
|
808
|
+
})();
|
|
809
|
+
|
|
810
|
+
/**
|
|
811
|
+
* Returns a `Boolean` on whether or not the a `String` starts with '0x'
|
|
812
|
+
* @param str the string input value
|
|
813
|
+
* @return a boolean if it is or is not hex prefixed
|
|
814
|
+
* @throws if the str input is not a string
|
|
815
|
+
*/
|
|
816
|
+
const isHexPrefixed = (str) => {
|
|
817
|
+
if (typeof str !== 'string') {
|
|
818
|
+
throw new Error(`[isHexPrefixed] input must be type 'string', received type ${typeof str}`);
|
|
819
|
+
}
|
|
820
|
+
return str[0] === '0' && str[1] === 'x';
|
|
821
|
+
};
|
|
822
|
+
/**
|
|
823
|
+
* Removes '0x' from a given `String` if present
|
|
824
|
+
* @param str the string value
|
|
825
|
+
* @returns the string without 0x prefix
|
|
826
|
+
*/
|
|
827
|
+
const stripHexPrefix = (str) => {
|
|
828
|
+
if (typeof str !== 'string')
|
|
829
|
+
throw new Error(`[stripHexPrefix] input must be type 'string', received ${typeof str}`);
|
|
830
|
+
return isHexPrefixed(str) ? str.slice(2) : str;
|
|
831
|
+
};
|
|
832
|
+
/**
|
|
833
|
+
* Is the string a hex string.
|
|
834
|
+
*
|
|
835
|
+
* @param value
|
|
836
|
+
* @param length
|
|
837
|
+
* @returns output the string is a hex string
|
|
838
|
+
*/
|
|
839
|
+
const isHexString = (value, length) => {
|
|
840
|
+
if (typeof value !== 'string' || !value.match(/^0x[0-9A-Fa-f]+$/))
|
|
841
|
+
return false;
|
|
842
|
+
return true;
|
|
843
|
+
};
|
|
844
|
+
/**
|
|
845
|
+
* Adds '0x' to a given `String` if not present
|
|
846
|
+
* @param str the string input value
|
|
847
|
+
* @return the string with a 0x prefix
|
|
848
|
+
*/
|
|
849
|
+
const addLeading0x = (str) => {
|
|
17
850
|
if (!str.startsWith('0x'))
|
|
18
851
|
return '0x' + str;
|
|
19
852
|
else
|
|
20
853
|
return str;
|
|
854
|
+
};
|
|
855
|
+
const decompress = (startsWith02Or03) => {
|
|
856
|
+
const testByteArray = hexToBytes(startsWith02Or03);
|
|
857
|
+
let startsWith04 = startsWith02Or03;
|
|
858
|
+
if (testByteArray.length === 64) {
|
|
859
|
+
startsWith04 = '04' + startsWith02Or03;
|
|
860
|
+
}
|
|
861
|
+
return startsWith04.substring(2);
|
|
862
|
+
};
|
|
863
|
+
/** Helper function to concat UInt8Arrays mimicking the behaviour of the
|
|
864
|
+
* Buffer.concat function in Node.js
|
|
865
|
+
*/
|
|
866
|
+
const concatUint8Arrays = (uint8arrays) => {
|
|
867
|
+
const totalLength = uint8arrays.reduce((total, uint8array) => total + uint8array.byteLength, 0);
|
|
868
|
+
const result = new Uint8Array(totalLength);
|
|
869
|
+
let offset = 0;
|
|
870
|
+
uint8arrays.forEach((uint8array) => {
|
|
871
|
+
result.set(uint8array, offset);
|
|
872
|
+
offset += uint8array.byteLength;
|
|
873
|
+
});
|
|
874
|
+
return result;
|
|
875
|
+
};
|
|
876
|
+
/**
|
|
877
|
+
* Converts a UTF-8 string to a Uint8Array without using TextEncoder, which is not available in mobile
|
|
878
|
+
* @example utf8ToBytes('abc') // new Uint8Array([97, 98, 99])
|
|
879
|
+
*/
|
|
880
|
+
const utf8ToBytes = (str) => {
|
|
881
|
+
if (typeof str !== 'string')
|
|
882
|
+
throw new Error(`utf8ToBytes expected string, got ${typeof str}`);
|
|
883
|
+
const bytes = [];
|
|
884
|
+
for (let i = 0; i < str.length; i++) {
|
|
885
|
+
const codePoint = str.codePointAt(i);
|
|
886
|
+
if (!codePoint) {
|
|
887
|
+
throw new Error('Invalid code point');
|
|
888
|
+
}
|
|
889
|
+
if (codePoint < 0x80) {
|
|
890
|
+
bytes.push(codePoint);
|
|
891
|
+
}
|
|
892
|
+
else if (codePoint < 0x800) {
|
|
893
|
+
bytes.push(0xc0 | (codePoint >> 6), 0x80 | (codePoint & 0x3f));
|
|
894
|
+
}
|
|
895
|
+
else if (codePoint < 0x10000) {
|
|
896
|
+
bytes.push(0xe0 | (codePoint >> 12), 0x80 | ((codePoint >> 6) & 0x3f), 0x80 | (codePoint & 0x3f));
|
|
897
|
+
}
|
|
898
|
+
else {
|
|
899
|
+
i++; // skip one iteration since we have a surrogate pair
|
|
900
|
+
bytes.push(0xf0 | (codePoint >> 18), 0x80 | ((codePoint >> 12) & 0x3f), 0x80 | ((codePoint >> 6) & 0x3f), 0x80 | (codePoint & 0x3f));
|
|
901
|
+
}
|
|
902
|
+
}
|
|
903
|
+
return new Uint8Array(bytes);
|
|
904
|
+
};
|
|
905
|
+
|
|
906
|
+
const solidityPackedKeccak256 = (value) => {
|
|
907
|
+
const bytes = utf8ToBytes(value);
|
|
908
|
+
const hex = addLeading0x(bytesToHex(bytes));
|
|
909
|
+
const hash = keccak256$1(hexToBytes(hex));
|
|
910
|
+
return addLeading0x(bytesToHex(hash));
|
|
911
|
+
};
|
|
912
|
+
const keccak256 = (params) => {
|
|
913
|
+
return solidityPackedKeccak256(params);
|
|
914
|
+
};
|
|
915
|
+
|
|
916
|
+
/**
|
|
917
|
+
* Internal Merkle-Damgard hash utils.
|
|
918
|
+
* @module
|
|
919
|
+
*/
|
|
920
|
+
/** Polyfill for Safari 14. https://caniuse.com/mdn-javascript_builtins_dataview_setbiguint64 */
|
|
921
|
+
function setBigUint64(view, byteOffset, value, isLE) {
|
|
922
|
+
if (typeof view.setBigUint64 === 'function')
|
|
923
|
+
return view.setBigUint64(byteOffset, value, isLE);
|
|
924
|
+
const _32n = BigInt(32);
|
|
925
|
+
const _u32_max = BigInt(0xffffffff);
|
|
926
|
+
const wh = Number((value >> _32n) & _u32_max);
|
|
927
|
+
const wl = Number(value & _u32_max);
|
|
928
|
+
const h = isLE ? 4 : 0;
|
|
929
|
+
const l = isLE ? 0 : 4;
|
|
930
|
+
view.setUint32(byteOffset + h, wh, isLE);
|
|
931
|
+
view.setUint32(byteOffset + l, wl, isLE);
|
|
932
|
+
}
|
|
933
|
+
/** Choice: a ? b : c */
|
|
934
|
+
function Chi(a, b, c) {
|
|
935
|
+
return (a & b) ^ (~a & c);
|
|
936
|
+
}
|
|
937
|
+
/** Majority function, true if any two inputs is true. */
|
|
938
|
+
function Maj(a, b, c) {
|
|
939
|
+
return (a & b) ^ (a & c) ^ (b & c);
|
|
940
|
+
}
|
|
941
|
+
/**
|
|
942
|
+
* Merkle-Damgard hash construction base class.
|
|
943
|
+
* Could be used to create MD5, RIPEMD, SHA1, SHA2.
|
|
944
|
+
*/
|
|
945
|
+
class HashMD extends Hash {
|
|
946
|
+
constructor(blockLen, outputLen, padOffset, isLE) {
|
|
947
|
+
super();
|
|
948
|
+
this.finished = false;
|
|
949
|
+
this.length = 0;
|
|
950
|
+
this.pos = 0;
|
|
951
|
+
this.destroyed = false;
|
|
952
|
+
this.blockLen = blockLen;
|
|
953
|
+
this.outputLen = outputLen;
|
|
954
|
+
this.padOffset = padOffset;
|
|
955
|
+
this.isLE = isLE;
|
|
956
|
+
this.buffer = new Uint8Array(blockLen);
|
|
957
|
+
this.view = createView(this.buffer);
|
|
958
|
+
}
|
|
959
|
+
update(data) {
|
|
960
|
+
aexists(this);
|
|
961
|
+
data = toBytes(data);
|
|
962
|
+
abytes$2(data);
|
|
963
|
+
const { view, buffer, blockLen } = this;
|
|
964
|
+
const len = data.length;
|
|
965
|
+
for (let pos = 0; pos < len;) {
|
|
966
|
+
const take = Math.min(blockLen - this.pos, len - pos);
|
|
967
|
+
// Fast path: we have at least one block in input, cast it to view and process
|
|
968
|
+
if (take === blockLen) {
|
|
969
|
+
const dataView = createView(data);
|
|
970
|
+
for (; blockLen <= len - pos; pos += blockLen)
|
|
971
|
+
this.process(dataView, pos);
|
|
972
|
+
continue;
|
|
973
|
+
}
|
|
974
|
+
buffer.set(data.subarray(pos, pos + take), this.pos);
|
|
975
|
+
this.pos += take;
|
|
976
|
+
pos += take;
|
|
977
|
+
if (this.pos === blockLen) {
|
|
978
|
+
this.process(view, 0);
|
|
979
|
+
this.pos = 0;
|
|
980
|
+
}
|
|
981
|
+
}
|
|
982
|
+
this.length += data.length;
|
|
983
|
+
this.roundClean();
|
|
984
|
+
return this;
|
|
985
|
+
}
|
|
986
|
+
digestInto(out) {
|
|
987
|
+
aexists(this);
|
|
988
|
+
aoutput(out, this);
|
|
989
|
+
this.finished = true;
|
|
990
|
+
// Padding
|
|
991
|
+
// We can avoid allocation of buffer for padding completely if it
|
|
992
|
+
// was previously not allocated here. But it won't change performance.
|
|
993
|
+
const { buffer, view, blockLen, isLE } = this;
|
|
994
|
+
let { pos } = this;
|
|
995
|
+
// append the bit '1' to the message
|
|
996
|
+
buffer[pos++] = 0b10000000;
|
|
997
|
+
clean$1(this.buffer.subarray(pos));
|
|
998
|
+
// we have less than padOffset left in buffer, so we cannot put length in
|
|
999
|
+
// current block, need process it and pad again
|
|
1000
|
+
if (this.padOffset > blockLen - pos) {
|
|
1001
|
+
this.process(view, 0);
|
|
1002
|
+
pos = 0;
|
|
1003
|
+
}
|
|
1004
|
+
// Pad until full block byte with zeros
|
|
1005
|
+
for (let i = pos; i < blockLen; i++)
|
|
1006
|
+
buffer[i] = 0;
|
|
1007
|
+
// Note: sha512 requires length to be 128bit integer, but length in JS will overflow before that
|
|
1008
|
+
// You need to write around 2 exabytes (u64_max / 8 / (1024**6)) for this to happen.
|
|
1009
|
+
// So we just write lowest 64 bits of that value.
|
|
1010
|
+
setBigUint64(view, blockLen - 8, BigInt(this.length * 8), isLE);
|
|
1011
|
+
this.process(view, 0);
|
|
1012
|
+
const oview = createView(out);
|
|
1013
|
+
const len = this.outputLen;
|
|
1014
|
+
// NOTE: we do division by 4 later, which should be fused in single op with modulo by JIT
|
|
1015
|
+
if (len % 4)
|
|
1016
|
+
throw new Error('_sha2: outputLen should be aligned to 32bit');
|
|
1017
|
+
const outLen = len / 4;
|
|
1018
|
+
const state = this.get();
|
|
1019
|
+
if (outLen > state.length)
|
|
1020
|
+
throw new Error('_sha2: outputLen bigger than state');
|
|
1021
|
+
for (let i = 0; i < outLen; i++)
|
|
1022
|
+
oview.setUint32(4 * i, state[i], isLE);
|
|
1023
|
+
}
|
|
1024
|
+
digest() {
|
|
1025
|
+
const { buffer, outputLen } = this;
|
|
1026
|
+
this.digestInto(buffer);
|
|
1027
|
+
const res = buffer.slice(0, outputLen);
|
|
1028
|
+
this.destroy();
|
|
1029
|
+
return res;
|
|
1030
|
+
}
|
|
1031
|
+
_cloneInto(to) {
|
|
1032
|
+
to || (to = new this.constructor());
|
|
1033
|
+
to.set(...this.get());
|
|
1034
|
+
const { blockLen, buffer, length, finished, destroyed, pos } = this;
|
|
1035
|
+
to.destroyed = destroyed;
|
|
1036
|
+
to.finished = finished;
|
|
1037
|
+
to.length = length;
|
|
1038
|
+
to.pos = pos;
|
|
1039
|
+
if (length % blockLen)
|
|
1040
|
+
to.buffer.set(buffer);
|
|
1041
|
+
return to;
|
|
1042
|
+
}
|
|
1043
|
+
clone() {
|
|
1044
|
+
return this._cloneInto();
|
|
1045
|
+
}
|
|
1046
|
+
}
|
|
1047
|
+
/**
|
|
1048
|
+
* Initial SHA-2 state: fractional parts of square roots of first 16 primes 2..53.
|
|
1049
|
+
* Check out `test/misc/sha2-gen-iv.js` for recomputation guide.
|
|
1050
|
+
*/
|
|
1051
|
+
/** Initial SHA256 state. Bits 0..32 of frac part of sqrt of primes 2..19 */
|
|
1052
|
+
const SHA256_IV = /* @__PURE__ */ Uint32Array.from([
|
|
1053
|
+
0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19,
|
|
1054
|
+
]);
|
|
1055
|
+
/** Initial SHA512 state. Bits 0..64 of frac part of sqrt of primes 2..19 */
|
|
1056
|
+
const SHA512_IV = /* @__PURE__ */ Uint32Array.from([
|
|
1057
|
+
0x6a09e667, 0xf3bcc908, 0xbb67ae85, 0x84caa73b, 0x3c6ef372, 0xfe94f82b, 0xa54ff53a, 0x5f1d36f1,
|
|
1058
|
+
0x510e527f, 0xade682d1, 0x9b05688c, 0x2b3e6c1f, 0x1f83d9ab, 0xfb41bd6b, 0x5be0cd19, 0x137e2179,
|
|
1059
|
+
]);
|
|
1060
|
+
|
|
1061
|
+
/**
|
|
1062
|
+
* SHA2 hash function. A.k.a. sha256, sha384, sha512, sha512_224, sha512_256.
|
|
1063
|
+
* SHA256 is the fastest hash implementable in JS, even faster than Blake3.
|
|
1064
|
+
* Check out [RFC 4634](https://datatracker.ietf.org/doc/html/rfc4634) and
|
|
1065
|
+
* [FIPS 180-4](https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.180-4.pdf).
|
|
1066
|
+
* @module
|
|
1067
|
+
*/
|
|
1068
|
+
/**
|
|
1069
|
+
* Round constants:
|
|
1070
|
+
* First 32 bits of fractional parts of the cube roots of the first 64 primes 2..311)
|
|
1071
|
+
*/
|
|
1072
|
+
// prettier-ignore
|
|
1073
|
+
const SHA256_K = /* @__PURE__ */ Uint32Array.from([
|
|
1074
|
+
0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,
|
|
1075
|
+
0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,
|
|
1076
|
+
0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
|
|
1077
|
+
0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,
|
|
1078
|
+
0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,
|
|
1079
|
+
0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
|
|
1080
|
+
0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
|
|
1081
|
+
0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2
|
|
1082
|
+
]);
|
|
1083
|
+
/** Reusable temporary buffer. "W" comes straight from spec. */
|
|
1084
|
+
const SHA256_W = /* @__PURE__ */ new Uint32Array(64);
|
|
1085
|
+
class SHA256 extends HashMD {
|
|
1086
|
+
constructor(outputLen = 32) {
|
|
1087
|
+
super(64, outputLen, 8, false);
|
|
1088
|
+
// We cannot use array here since array allows indexing by variable
|
|
1089
|
+
// which means optimizer/compiler cannot use registers.
|
|
1090
|
+
this.A = SHA256_IV[0] | 0;
|
|
1091
|
+
this.B = SHA256_IV[1] | 0;
|
|
1092
|
+
this.C = SHA256_IV[2] | 0;
|
|
1093
|
+
this.D = SHA256_IV[3] | 0;
|
|
1094
|
+
this.E = SHA256_IV[4] | 0;
|
|
1095
|
+
this.F = SHA256_IV[5] | 0;
|
|
1096
|
+
this.G = SHA256_IV[6] | 0;
|
|
1097
|
+
this.H = SHA256_IV[7] | 0;
|
|
1098
|
+
}
|
|
1099
|
+
get() {
|
|
1100
|
+
const { A, B, C, D, E, F, G, H } = this;
|
|
1101
|
+
return [A, B, C, D, E, F, G, H];
|
|
1102
|
+
}
|
|
1103
|
+
// prettier-ignore
|
|
1104
|
+
set(A, B, C, D, E, F, G, H) {
|
|
1105
|
+
this.A = A | 0;
|
|
1106
|
+
this.B = B | 0;
|
|
1107
|
+
this.C = C | 0;
|
|
1108
|
+
this.D = D | 0;
|
|
1109
|
+
this.E = E | 0;
|
|
1110
|
+
this.F = F | 0;
|
|
1111
|
+
this.G = G | 0;
|
|
1112
|
+
this.H = H | 0;
|
|
1113
|
+
}
|
|
1114
|
+
process(view, offset) {
|
|
1115
|
+
// Extend the first 16 words into the remaining 48 words w[16..63] of the message schedule array
|
|
1116
|
+
for (let i = 0; i < 16; i++, offset += 4)
|
|
1117
|
+
SHA256_W[i] = view.getUint32(offset, false);
|
|
1118
|
+
for (let i = 16; i < 64; i++) {
|
|
1119
|
+
const W15 = SHA256_W[i - 15];
|
|
1120
|
+
const W2 = SHA256_W[i - 2];
|
|
1121
|
+
const s0 = rotr(W15, 7) ^ rotr(W15, 18) ^ (W15 >>> 3);
|
|
1122
|
+
const s1 = rotr(W2, 17) ^ rotr(W2, 19) ^ (W2 >>> 10);
|
|
1123
|
+
SHA256_W[i] = (s1 + SHA256_W[i - 7] + s0 + SHA256_W[i - 16]) | 0;
|
|
1124
|
+
}
|
|
1125
|
+
// Compression function main loop, 64 rounds
|
|
1126
|
+
let { A, B, C, D, E, F, G, H } = this;
|
|
1127
|
+
for (let i = 0; i < 64; i++) {
|
|
1128
|
+
const sigma1 = rotr(E, 6) ^ rotr(E, 11) ^ rotr(E, 25);
|
|
1129
|
+
const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0;
|
|
1130
|
+
const sigma0 = rotr(A, 2) ^ rotr(A, 13) ^ rotr(A, 22);
|
|
1131
|
+
const T2 = (sigma0 + Maj(A, B, C)) | 0;
|
|
1132
|
+
H = G;
|
|
1133
|
+
G = F;
|
|
1134
|
+
F = E;
|
|
1135
|
+
E = (D + T1) | 0;
|
|
1136
|
+
D = C;
|
|
1137
|
+
C = B;
|
|
1138
|
+
B = A;
|
|
1139
|
+
A = (T1 + T2) | 0;
|
|
1140
|
+
}
|
|
1141
|
+
// Add the compressed chunk to the current hash value
|
|
1142
|
+
A = (A + this.A) | 0;
|
|
1143
|
+
B = (B + this.B) | 0;
|
|
1144
|
+
C = (C + this.C) | 0;
|
|
1145
|
+
D = (D + this.D) | 0;
|
|
1146
|
+
E = (E + this.E) | 0;
|
|
1147
|
+
F = (F + this.F) | 0;
|
|
1148
|
+
G = (G + this.G) | 0;
|
|
1149
|
+
H = (H + this.H) | 0;
|
|
1150
|
+
this.set(A, B, C, D, E, F, G, H);
|
|
1151
|
+
}
|
|
1152
|
+
roundClean() {
|
|
1153
|
+
clean$1(SHA256_W);
|
|
1154
|
+
}
|
|
1155
|
+
destroy() {
|
|
1156
|
+
this.set(0, 0, 0, 0, 0, 0, 0, 0);
|
|
1157
|
+
clean$1(this.buffer);
|
|
1158
|
+
}
|
|
1159
|
+
}
|
|
1160
|
+
// SHA2-512 is slower than sha256 in js because u64 operations are slow.
|
|
1161
|
+
// Round contants
|
|
1162
|
+
// First 32 bits of the fractional parts of the cube roots of the first 80 primes 2..409
|
|
1163
|
+
// prettier-ignore
|
|
1164
|
+
const K512 = /* @__PURE__ */ (() => split([
|
|
1165
|
+
'0x428a2f98d728ae22', '0x7137449123ef65cd', '0xb5c0fbcfec4d3b2f', '0xe9b5dba58189dbbc',
|
|
1166
|
+
'0x3956c25bf348b538', '0x59f111f1b605d019', '0x923f82a4af194f9b', '0xab1c5ed5da6d8118',
|
|
1167
|
+
'0xd807aa98a3030242', '0x12835b0145706fbe', '0x243185be4ee4b28c', '0x550c7dc3d5ffb4e2',
|
|
1168
|
+
'0x72be5d74f27b896f', '0x80deb1fe3b1696b1', '0x9bdc06a725c71235', '0xc19bf174cf692694',
|
|
1169
|
+
'0xe49b69c19ef14ad2', '0xefbe4786384f25e3', '0x0fc19dc68b8cd5b5', '0x240ca1cc77ac9c65',
|
|
1170
|
+
'0x2de92c6f592b0275', '0x4a7484aa6ea6e483', '0x5cb0a9dcbd41fbd4', '0x76f988da831153b5',
|
|
1171
|
+
'0x983e5152ee66dfab', '0xa831c66d2db43210', '0xb00327c898fb213f', '0xbf597fc7beef0ee4',
|
|
1172
|
+
'0xc6e00bf33da88fc2', '0xd5a79147930aa725', '0x06ca6351e003826f', '0x142929670a0e6e70',
|
|
1173
|
+
'0x27b70a8546d22ffc', '0x2e1b21385c26c926', '0x4d2c6dfc5ac42aed', '0x53380d139d95b3df',
|
|
1174
|
+
'0x650a73548baf63de', '0x766a0abb3c77b2a8', '0x81c2c92e47edaee6', '0x92722c851482353b',
|
|
1175
|
+
'0xa2bfe8a14cf10364', '0xa81a664bbc423001', '0xc24b8b70d0f89791', '0xc76c51a30654be30',
|
|
1176
|
+
'0xd192e819d6ef5218', '0xd69906245565a910', '0xf40e35855771202a', '0x106aa07032bbd1b8',
|
|
1177
|
+
'0x19a4c116b8d2d0c8', '0x1e376c085141ab53', '0x2748774cdf8eeb99', '0x34b0bcb5e19b48a8',
|
|
1178
|
+
'0x391c0cb3c5c95a63', '0x4ed8aa4ae3418acb', '0x5b9cca4f7763e373', '0x682e6ff3d6b2b8a3',
|
|
1179
|
+
'0x748f82ee5defb2fc', '0x78a5636f43172f60', '0x84c87814a1f0ab72', '0x8cc702081a6439ec',
|
|
1180
|
+
'0x90befffa23631e28', '0xa4506cebde82bde9', '0xbef9a3f7b2c67915', '0xc67178f2e372532b',
|
|
1181
|
+
'0xca273eceea26619c', '0xd186b8c721c0c207', '0xeada7dd6cde0eb1e', '0xf57d4f7fee6ed178',
|
|
1182
|
+
'0x06f067aa72176fba', '0x0a637dc5a2c898a6', '0x113f9804bef90dae', '0x1b710b35131c471b',
|
|
1183
|
+
'0x28db77f523047d84', '0x32caab7b40c72493', '0x3c9ebe0a15c9bebc', '0x431d67c49c100d4c',
|
|
1184
|
+
'0x4cc5d4becb3e42b6', '0x597f299cfc657e2a', '0x5fcb6fab3ad6faec', '0x6c44198c4a475817'
|
|
1185
|
+
].map(n => BigInt(n))))();
|
|
1186
|
+
const SHA512_Kh = /* @__PURE__ */ (() => K512[0])();
|
|
1187
|
+
const SHA512_Kl = /* @__PURE__ */ (() => K512[1])();
|
|
1188
|
+
// Reusable temporary buffers
|
|
1189
|
+
const SHA512_W_H = /* @__PURE__ */ new Uint32Array(80);
|
|
1190
|
+
const SHA512_W_L = /* @__PURE__ */ new Uint32Array(80);
|
|
1191
|
+
class SHA512 extends HashMD {
|
|
1192
|
+
constructor(outputLen = 64) {
|
|
1193
|
+
super(128, outputLen, 16, false);
|
|
1194
|
+
// We cannot use array here since array allows indexing by variable
|
|
1195
|
+
// which means optimizer/compiler cannot use registers.
|
|
1196
|
+
// h -- high 32 bits, l -- low 32 bits
|
|
1197
|
+
this.Ah = SHA512_IV[0] | 0;
|
|
1198
|
+
this.Al = SHA512_IV[1] | 0;
|
|
1199
|
+
this.Bh = SHA512_IV[2] | 0;
|
|
1200
|
+
this.Bl = SHA512_IV[3] | 0;
|
|
1201
|
+
this.Ch = SHA512_IV[4] | 0;
|
|
1202
|
+
this.Cl = SHA512_IV[5] | 0;
|
|
1203
|
+
this.Dh = SHA512_IV[6] | 0;
|
|
1204
|
+
this.Dl = SHA512_IV[7] | 0;
|
|
1205
|
+
this.Eh = SHA512_IV[8] | 0;
|
|
1206
|
+
this.El = SHA512_IV[9] | 0;
|
|
1207
|
+
this.Fh = SHA512_IV[10] | 0;
|
|
1208
|
+
this.Fl = SHA512_IV[11] | 0;
|
|
1209
|
+
this.Gh = SHA512_IV[12] | 0;
|
|
1210
|
+
this.Gl = SHA512_IV[13] | 0;
|
|
1211
|
+
this.Hh = SHA512_IV[14] | 0;
|
|
1212
|
+
this.Hl = SHA512_IV[15] | 0;
|
|
1213
|
+
}
|
|
1214
|
+
// prettier-ignore
|
|
1215
|
+
get() {
|
|
1216
|
+
const { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;
|
|
1217
|
+
return [Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl];
|
|
1218
|
+
}
|
|
1219
|
+
// prettier-ignore
|
|
1220
|
+
set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl) {
|
|
1221
|
+
this.Ah = Ah | 0;
|
|
1222
|
+
this.Al = Al | 0;
|
|
1223
|
+
this.Bh = Bh | 0;
|
|
1224
|
+
this.Bl = Bl | 0;
|
|
1225
|
+
this.Ch = Ch | 0;
|
|
1226
|
+
this.Cl = Cl | 0;
|
|
1227
|
+
this.Dh = Dh | 0;
|
|
1228
|
+
this.Dl = Dl | 0;
|
|
1229
|
+
this.Eh = Eh | 0;
|
|
1230
|
+
this.El = El | 0;
|
|
1231
|
+
this.Fh = Fh | 0;
|
|
1232
|
+
this.Fl = Fl | 0;
|
|
1233
|
+
this.Gh = Gh | 0;
|
|
1234
|
+
this.Gl = Gl | 0;
|
|
1235
|
+
this.Hh = Hh | 0;
|
|
1236
|
+
this.Hl = Hl | 0;
|
|
1237
|
+
}
|
|
1238
|
+
process(view, offset) {
|
|
1239
|
+
// Extend the first 16 words into the remaining 64 words w[16..79] of the message schedule array
|
|
1240
|
+
for (let i = 0; i < 16; i++, offset += 4) {
|
|
1241
|
+
SHA512_W_H[i] = view.getUint32(offset);
|
|
1242
|
+
SHA512_W_L[i] = view.getUint32((offset += 4));
|
|
1243
|
+
}
|
|
1244
|
+
for (let i = 16; i < 80; i++) {
|
|
1245
|
+
// s0 := (w[i-15] rightrotate 1) xor (w[i-15] rightrotate 8) xor (w[i-15] rightshift 7)
|
|
1246
|
+
const W15h = SHA512_W_H[i - 15] | 0;
|
|
1247
|
+
const W15l = SHA512_W_L[i - 15] | 0;
|
|
1248
|
+
const s0h = rotrSH(W15h, W15l, 1) ^ rotrSH(W15h, W15l, 8) ^ shrSH(W15h, W15l, 7);
|
|
1249
|
+
const s0l = rotrSL(W15h, W15l, 1) ^ rotrSL(W15h, W15l, 8) ^ shrSL(W15h, W15l, 7);
|
|
1250
|
+
// s1 := (w[i-2] rightrotate 19) xor (w[i-2] rightrotate 61) xor (w[i-2] rightshift 6)
|
|
1251
|
+
const W2h = SHA512_W_H[i - 2] | 0;
|
|
1252
|
+
const W2l = SHA512_W_L[i - 2] | 0;
|
|
1253
|
+
const s1h = rotrSH(W2h, W2l, 19) ^ rotrBH(W2h, W2l, 61) ^ shrSH(W2h, W2l, 6);
|
|
1254
|
+
const s1l = rotrSL(W2h, W2l, 19) ^ rotrBL(W2h, W2l, 61) ^ shrSL(W2h, W2l, 6);
|
|
1255
|
+
// SHA256_W[i] = s0 + s1 + SHA256_W[i - 7] + SHA256_W[i - 16];
|
|
1256
|
+
const SUMl = add4L(s0l, s1l, SHA512_W_L[i - 7], SHA512_W_L[i - 16]);
|
|
1257
|
+
const SUMh = add4H(SUMl, s0h, s1h, SHA512_W_H[i - 7], SHA512_W_H[i - 16]);
|
|
1258
|
+
SHA512_W_H[i] = SUMh | 0;
|
|
1259
|
+
SHA512_W_L[i] = SUMl | 0;
|
|
1260
|
+
}
|
|
1261
|
+
let { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;
|
|
1262
|
+
// Compression function main loop, 80 rounds
|
|
1263
|
+
for (let i = 0; i < 80; i++) {
|
|
1264
|
+
// S1 := (e rightrotate 14) xor (e rightrotate 18) xor (e rightrotate 41)
|
|
1265
|
+
const sigma1h = rotrSH(Eh, El, 14) ^ rotrSH(Eh, El, 18) ^ rotrBH(Eh, El, 41);
|
|
1266
|
+
const sigma1l = rotrSL(Eh, El, 14) ^ rotrSL(Eh, El, 18) ^ rotrBL(Eh, El, 41);
|
|
1267
|
+
//const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0;
|
|
1268
|
+
const CHIh = (Eh & Fh) ^ (~Eh & Gh);
|
|
1269
|
+
const CHIl = (El & Fl) ^ (~El & Gl);
|
|
1270
|
+
// T1 = H + sigma1 + Chi(E, F, G) + SHA512_K[i] + SHA512_W[i]
|
|
1271
|
+
// prettier-ignore
|
|
1272
|
+
const T1ll = add5L(Hl, sigma1l, CHIl, SHA512_Kl[i], SHA512_W_L[i]);
|
|
1273
|
+
const T1h = add5H(T1ll, Hh, sigma1h, CHIh, SHA512_Kh[i], SHA512_W_H[i]);
|
|
1274
|
+
const T1l = T1ll | 0;
|
|
1275
|
+
// S0 := (a rightrotate 28) xor (a rightrotate 34) xor (a rightrotate 39)
|
|
1276
|
+
const sigma0h = rotrSH(Ah, Al, 28) ^ rotrBH(Ah, Al, 34) ^ rotrBH(Ah, Al, 39);
|
|
1277
|
+
const sigma0l = rotrSL(Ah, Al, 28) ^ rotrBL(Ah, Al, 34) ^ rotrBL(Ah, Al, 39);
|
|
1278
|
+
const MAJh = (Ah & Bh) ^ (Ah & Ch) ^ (Bh & Ch);
|
|
1279
|
+
const MAJl = (Al & Bl) ^ (Al & Cl) ^ (Bl & Cl);
|
|
1280
|
+
Hh = Gh | 0;
|
|
1281
|
+
Hl = Gl | 0;
|
|
1282
|
+
Gh = Fh | 0;
|
|
1283
|
+
Gl = Fl | 0;
|
|
1284
|
+
Fh = Eh | 0;
|
|
1285
|
+
Fl = El | 0;
|
|
1286
|
+
({ h: Eh, l: El } = add(Dh | 0, Dl | 0, T1h | 0, T1l | 0));
|
|
1287
|
+
Dh = Ch | 0;
|
|
1288
|
+
Dl = Cl | 0;
|
|
1289
|
+
Ch = Bh | 0;
|
|
1290
|
+
Cl = Bl | 0;
|
|
1291
|
+
Bh = Ah | 0;
|
|
1292
|
+
Bl = Al | 0;
|
|
1293
|
+
const All = add3L(T1l, sigma0l, MAJl);
|
|
1294
|
+
Ah = add3H(All, T1h, sigma0h, MAJh);
|
|
1295
|
+
Al = All | 0;
|
|
1296
|
+
}
|
|
1297
|
+
// Add the compressed chunk to the current hash value
|
|
1298
|
+
({ h: Ah, l: Al } = add(this.Ah | 0, this.Al | 0, Ah | 0, Al | 0));
|
|
1299
|
+
({ h: Bh, l: Bl } = add(this.Bh | 0, this.Bl | 0, Bh | 0, Bl | 0));
|
|
1300
|
+
({ h: Ch, l: Cl } = add(this.Ch | 0, this.Cl | 0, Ch | 0, Cl | 0));
|
|
1301
|
+
({ h: Dh, l: Dl } = add(this.Dh | 0, this.Dl | 0, Dh | 0, Dl | 0));
|
|
1302
|
+
({ h: Eh, l: El } = add(this.Eh | 0, this.El | 0, Eh | 0, El | 0));
|
|
1303
|
+
({ h: Fh, l: Fl } = add(this.Fh | 0, this.Fl | 0, Fh | 0, Fl | 0));
|
|
1304
|
+
({ h: Gh, l: Gl } = add(this.Gh | 0, this.Gl | 0, Gh | 0, Gl | 0));
|
|
1305
|
+
({ h: Hh, l: Hl } = add(this.Hh | 0, this.Hl | 0, Hh | 0, Hl | 0));
|
|
1306
|
+
this.set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl);
|
|
1307
|
+
}
|
|
1308
|
+
roundClean() {
|
|
1309
|
+
clean$1(SHA512_W_H, SHA512_W_L);
|
|
1310
|
+
}
|
|
1311
|
+
destroy() {
|
|
1312
|
+
clean$1(this.buffer);
|
|
1313
|
+
this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
|
|
1314
|
+
}
|
|
1315
|
+
}
|
|
1316
|
+
/**
|
|
1317
|
+
* SHA2-256 hash function from RFC 4634.
|
|
1318
|
+
*
|
|
1319
|
+
* It is the fastest JS hash, even faster than Blake3.
|
|
1320
|
+
* To break sha256 using birthday attack, attackers need to try 2^128 hashes.
|
|
1321
|
+
* BTC network is doing 2^70 hashes/sec (2^95 hashes/year) as per 2025.
|
|
1322
|
+
*/
|
|
1323
|
+
const sha256 = /* @__PURE__ */ createHasher(() => new SHA256());
|
|
1324
|
+
/** SHA2-512 hash function from RFC 4634. */
|
|
1325
|
+
const sha512$1 = /* @__PURE__ */ createHasher(() => new SHA512());
|
|
1326
|
+
|
|
1327
|
+
/**
|
|
1328
|
+
* HMAC: RFC2104 message authentication code.
|
|
1329
|
+
* @module
|
|
1330
|
+
*/
|
|
1331
|
+
class HMAC extends Hash {
|
|
1332
|
+
constructor(hash, _key) {
|
|
1333
|
+
super();
|
|
1334
|
+
this.finished = false;
|
|
1335
|
+
this.destroyed = false;
|
|
1336
|
+
ahash(hash);
|
|
1337
|
+
const key = toBytes(_key);
|
|
1338
|
+
this.iHash = hash.create();
|
|
1339
|
+
if (typeof this.iHash.update !== 'function')
|
|
1340
|
+
throw new Error('Expected instance of class which extends utils.Hash');
|
|
1341
|
+
this.blockLen = this.iHash.blockLen;
|
|
1342
|
+
this.outputLen = this.iHash.outputLen;
|
|
1343
|
+
const blockLen = this.blockLen;
|
|
1344
|
+
const pad = new Uint8Array(blockLen);
|
|
1345
|
+
// blockLen can be bigger than outputLen
|
|
1346
|
+
pad.set(key.length > blockLen ? hash.create().update(key).digest() : key);
|
|
1347
|
+
for (let i = 0; i < pad.length; i++)
|
|
1348
|
+
pad[i] ^= 0x36;
|
|
1349
|
+
this.iHash.update(pad);
|
|
1350
|
+
// By doing update (processing of first block) of outer hash here we can re-use it between multiple calls via clone
|
|
1351
|
+
this.oHash = hash.create();
|
|
1352
|
+
// Undo internal XOR && apply outer XOR
|
|
1353
|
+
for (let i = 0; i < pad.length; i++)
|
|
1354
|
+
pad[i] ^= 0x36 ^ 0x5c;
|
|
1355
|
+
this.oHash.update(pad);
|
|
1356
|
+
clean$1(pad);
|
|
1357
|
+
}
|
|
1358
|
+
update(buf) {
|
|
1359
|
+
aexists(this);
|
|
1360
|
+
this.iHash.update(buf);
|
|
1361
|
+
return this;
|
|
1362
|
+
}
|
|
1363
|
+
digestInto(out) {
|
|
1364
|
+
aexists(this);
|
|
1365
|
+
abytes$2(out, this.outputLen);
|
|
1366
|
+
this.finished = true;
|
|
1367
|
+
this.iHash.digestInto(out);
|
|
1368
|
+
this.oHash.update(out);
|
|
1369
|
+
this.oHash.digestInto(out);
|
|
1370
|
+
this.destroy();
|
|
1371
|
+
}
|
|
1372
|
+
digest() {
|
|
1373
|
+
const out = new Uint8Array(this.oHash.outputLen);
|
|
1374
|
+
this.digestInto(out);
|
|
1375
|
+
return out;
|
|
1376
|
+
}
|
|
1377
|
+
_cloneInto(to) {
|
|
1378
|
+
// Create new instance without calling constructor since key already in state and we don't know it.
|
|
1379
|
+
to || (to = Object.create(Object.getPrototypeOf(this), {}));
|
|
1380
|
+
const { oHash, iHash, finished, destroyed, blockLen, outputLen } = this;
|
|
1381
|
+
to = to;
|
|
1382
|
+
to.finished = finished;
|
|
1383
|
+
to.destroyed = destroyed;
|
|
1384
|
+
to.blockLen = blockLen;
|
|
1385
|
+
to.outputLen = outputLen;
|
|
1386
|
+
to.oHash = oHash._cloneInto(to.oHash);
|
|
1387
|
+
to.iHash = iHash._cloneInto(to.iHash);
|
|
1388
|
+
return to;
|
|
1389
|
+
}
|
|
1390
|
+
clone() {
|
|
1391
|
+
return this._cloneInto();
|
|
1392
|
+
}
|
|
1393
|
+
destroy() {
|
|
1394
|
+
this.destroyed = true;
|
|
1395
|
+
this.oHash.destroy();
|
|
1396
|
+
this.iHash.destroy();
|
|
1397
|
+
}
|
|
1398
|
+
}
|
|
1399
|
+
/**
|
|
1400
|
+
* HMAC: RFC2104 message authentication code.
|
|
1401
|
+
* @param hash - function that would be used e.g. sha256
|
|
1402
|
+
* @param key - message key
|
|
1403
|
+
* @param message - message data
|
|
1404
|
+
* @example
|
|
1405
|
+
* import { hmac } from '@noble/hashes/hmac';
|
|
1406
|
+
* import { sha256 } from '@noble/hashes/sha2';
|
|
1407
|
+
* const mac1 = hmac(sha256, 'key', 'message');
|
|
1408
|
+
*/
|
|
1409
|
+
const hmac = (hash, key, message) => new HMAC(hash, key).update(message).digest();
|
|
1410
|
+
hmac.create = (hash, key) => new HMAC(hash, key);
|
|
1411
|
+
|
|
1412
|
+
/**
|
|
1413
|
+
* Utils for modular division and finite fields.
|
|
1414
|
+
* A finite field over 11 is integer number operations `mod 11`.
|
|
1415
|
+
* There is no division: it is replaced by modular multiplicative inverse.
|
|
1416
|
+
* @module
|
|
1417
|
+
*/
|
|
1418
|
+
/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
|
|
1419
|
+
// prettier-ignore
|
|
1420
|
+
const _0n$2 = BigInt(0), _1n$3 = BigInt(1), _2n$1 = /* @__PURE__ */ BigInt(2), _3n$1 = /* @__PURE__ */ BigInt(3);
|
|
1421
|
+
// prettier-ignore
|
|
1422
|
+
const _4n = /* @__PURE__ */ BigInt(4), _5n = /* @__PURE__ */ BigInt(5), _8n = /* @__PURE__ */ BigInt(8);
|
|
1423
|
+
// Calculates a modulo b
|
|
1424
|
+
function mod(a, b) {
|
|
1425
|
+
const result = a % b;
|
|
1426
|
+
return result >= _0n$2 ? result : b + result;
|
|
21
1427
|
}
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
let
|
|
43
|
-
//
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
1428
|
+
/** Does `x^(2^power)` mod p. `pow2(30, 4)` == `30^(2^4)` */
|
|
1429
|
+
function pow2(x, power, modulo) {
|
|
1430
|
+
let res = x;
|
|
1431
|
+
while (power-- > _0n$2) {
|
|
1432
|
+
res *= res;
|
|
1433
|
+
res %= modulo;
|
|
1434
|
+
}
|
|
1435
|
+
return res;
|
|
1436
|
+
}
|
|
1437
|
+
/**
|
|
1438
|
+
* Inverses number over modulo.
|
|
1439
|
+
* Implemented using [Euclidean GCD](https://brilliant.org/wiki/extended-euclidean-algorithm/).
|
|
1440
|
+
*/
|
|
1441
|
+
function invert(number, modulo) {
|
|
1442
|
+
if (number === _0n$2)
|
|
1443
|
+
throw new Error('invert: expected non-zero number');
|
|
1444
|
+
if (modulo <= _0n$2)
|
|
1445
|
+
throw new Error('invert: expected positive modulus, got ' + modulo);
|
|
1446
|
+
// Fermat's little theorem "CT-like" version inv(n) = n^(m-2) mod m is 30x slower.
|
|
1447
|
+
let a = mod(number, modulo);
|
|
1448
|
+
let b = modulo;
|
|
1449
|
+
// prettier-ignore
|
|
1450
|
+
let x = _0n$2, u = _1n$3;
|
|
1451
|
+
while (a !== _0n$2) {
|
|
1452
|
+
// JIT applies optimization if those two lines follow each other
|
|
1453
|
+
const q = b / a;
|
|
1454
|
+
const r = b % a;
|
|
1455
|
+
const m = x - u * q;
|
|
1456
|
+
// prettier-ignore
|
|
1457
|
+
b = a, a = r, x = u, u = m;
|
|
1458
|
+
}
|
|
1459
|
+
const gcd = b;
|
|
1460
|
+
if (gcd !== _1n$3)
|
|
1461
|
+
throw new Error('invert: does not exist');
|
|
1462
|
+
return mod(x, modulo);
|
|
1463
|
+
}
|
|
1464
|
+
/**
|
|
1465
|
+
* Tonelli-Shanks square root search algorithm.
|
|
1466
|
+
* 1. https://eprint.iacr.org/2012/685.pdf (page 12)
|
|
1467
|
+
* 2. Square Roots from 1; 24, 51, 10 to Dan Shanks
|
|
1468
|
+
* @param P field order
|
|
1469
|
+
* @returns function that takes field Fp (created from P) and number n
|
|
1470
|
+
*/
|
|
1471
|
+
function tonelliShanks(P) {
|
|
1472
|
+
// Do expensive precomputation step
|
|
1473
|
+
// Step 1: By factoring out powers of 2 from p - 1,
|
|
1474
|
+
// find q and s such that p-1 == q*(2^s) with q odd
|
|
1475
|
+
let Q = P - _1n$3;
|
|
1476
|
+
let S = 0;
|
|
1477
|
+
while (Q % _2n$1 === _0n$2) {
|
|
1478
|
+
Q /= _2n$1;
|
|
1479
|
+
S++;
|
|
1480
|
+
}
|
|
1481
|
+
// Step 2: Select a non-square z such that (z | p) ≡ -1 and set c ≡ zq
|
|
1482
|
+
let Z = _2n$1;
|
|
1483
|
+
const _Fp = Field(P);
|
|
1484
|
+
while (Z < P && FpIsSquare(_Fp, Z)) {
|
|
1485
|
+
if (Z++ > 1000)
|
|
1486
|
+
throw new Error('Cannot find square root: probably non-prime P');
|
|
1487
|
+
}
|
|
1488
|
+
// Fast-path
|
|
1489
|
+
if (S === 1) {
|
|
1490
|
+
const p1div4 = (P + _1n$3) / _4n;
|
|
1491
|
+
return function tonelliFast(Fp, n) {
|
|
1492
|
+
const root = Fp.pow(n, p1div4);
|
|
1493
|
+
if (!Fp.eql(Fp.sqr(root), n))
|
|
1494
|
+
throw new Error('Cannot find square root');
|
|
1495
|
+
return root;
|
|
72
1496
|
};
|
|
73
|
-
// decompress publicKey
|
|
74
|
-
ret.ephemPublicKey = '04' + decompress(ret.ephemPublicKey);
|
|
75
|
-
return ret;
|
|
76
1497
|
}
|
|
1498
|
+
// Slow-path
|
|
1499
|
+
const Q1div2 = (Q + _1n$3) / _2n$1;
|
|
1500
|
+
return function tonelliSlow(Fp, n) {
|
|
1501
|
+
// Step 0: Check that n is indeed a square: (n | p) should not be ≡ -1
|
|
1502
|
+
if (!FpIsSquare(Fp, n))
|
|
1503
|
+
throw new Error('Cannot find square root');
|
|
1504
|
+
let r = S;
|
|
1505
|
+
// TODO: test on Fp2 and others
|
|
1506
|
+
let g = Fp.pow(Fp.mul(Fp.ONE, Z), Q); // will update both x and b
|
|
1507
|
+
let x = Fp.pow(n, Q1div2); // first guess at the square root
|
|
1508
|
+
let b = Fp.pow(n, Q); // first guess at the fudge factor
|
|
1509
|
+
while (!Fp.eql(b, Fp.ONE)) {
|
|
1510
|
+
// (4. If t = 0, return r = 0)
|
|
1511
|
+
// https://en.wikipedia.org/wiki/Tonelli%E2%80%93Shanks_algorithm
|
|
1512
|
+
if (Fp.eql(b, Fp.ZERO))
|
|
1513
|
+
return Fp.ZERO;
|
|
1514
|
+
// Find m such b^(2^m)==1
|
|
1515
|
+
let m = 1;
|
|
1516
|
+
for (let t2 = Fp.sqr(b); m < r; m++) {
|
|
1517
|
+
if (Fp.eql(t2, Fp.ONE))
|
|
1518
|
+
break;
|
|
1519
|
+
t2 = Fp.sqr(t2); // t2 *= t2
|
|
1520
|
+
}
|
|
1521
|
+
// NOTE: r-m-1 can be bigger than 32, need to convert to bigint before shift,
|
|
1522
|
+
// otherwise there will be overflow.
|
|
1523
|
+
const ge = Fp.pow(g, _1n$3 << BigInt(r - m - 1)); // ge = 2^(r-m-1)
|
|
1524
|
+
g = Fp.sqr(ge); // g = ge * ge
|
|
1525
|
+
x = Fp.mul(x, ge); // x *= ge
|
|
1526
|
+
b = Fp.mul(b, g); // b *= g
|
|
1527
|
+
r = m;
|
|
1528
|
+
}
|
|
1529
|
+
return x;
|
|
1530
|
+
};
|
|
1531
|
+
}
|
|
1532
|
+
/**
|
|
1533
|
+
* Square root for a finite field. It will try to check if optimizations are applicable and fall back to 4:
|
|
1534
|
+
*
|
|
1535
|
+
* 1. P ≡ 3 (mod 4)
|
|
1536
|
+
* 2. P ≡ 5 (mod 8)
|
|
1537
|
+
* 3. P ≡ 9 (mod 16)
|
|
1538
|
+
* 4. Tonelli-Shanks algorithm
|
|
1539
|
+
*
|
|
1540
|
+
* Different algorithms can give different roots, it is up to user to decide which one they want.
|
|
1541
|
+
* For example there is FpSqrtOdd/FpSqrtEven to choice root based on oddness (used for hash-to-curve).
|
|
1542
|
+
*/
|
|
1543
|
+
function FpSqrt(P) {
|
|
1544
|
+
// P ≡ 3 (mod 4)
|
|
1545
|
+
// √n = n^((P+1)/4)
|
|
1546
|
+
if (P % _4n === _3n$1) {
|
|
1547
|
+
// Not all roots possible!
|
|
1548
|
+
// const ORDER =
|
|
1549
|
+
// 0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaaabn;
|
|
1550
|
+
// const NUM = 72057594037927816n;
|
|
1551
|
+
return function sqrt3mod4(Fp, n) {
|
|
1552
|
+
const p1div4 = (P + _1n$3) / _4n;
|
|
1553
|
+
const root = Fp.pow(n, p1div4);
|
|
1554
|
+
// Throw if root**2 != n
|
|
1555
|
+
if (!Fp.eql(Fp.sqr(root), n))
|
|
1556
|
+
throw new Error('Cannot find square root');
|
|
1557
|
+
return root;
|
|
1558
|
+
};
|
|
1559
|
+
}
|
|
1560
|
+
// Atkin algorithm for q ≡ 5 (mod 8), https://eprint.iacr.org/2012/685.pdf (page 10)
|
|
1561
|
+
if (P % _8n === _5n) {
|
|
1562
|
+
return function sqrt5mod8(Fp, n) {
|
|
1563
|
+
const n2 = Fp.mul(n, _2n$1);
|
|
1564
|
+
const c1 = (P - _5n) / _8n;
|
|
1565
|
+
const v = Fp.pow(n2, c1);
|
|
1566
|
+
const nv = Fp.mul(n, v);
|
|
1567
|
+
const i = Fp.mul(Fp.mul(nv, _2n$1), v);
|
|
1568
|
+
const root = Fp.mul(nv, Fp.sub(i, Fp.ONE));
|
|
1569
|
+
if (!Fp.eql(Fp.sqr(root), n))
|
|
1570
|
+
throw new Error('Cannot find square root');
|
|
1571
|
+
return root;
|
|
1572
|
+
};
|
|
1573
|
+
}
|
|
1574
|
+
// Other cases: Tonelli-Shanks algorithm
|
|
1575
|
+
return tonelliShanks(P);
|
|
1576
|
+
}
|
|
1577
|
+
// prettier-ignore
|
|
1578
|
+
const FIELD_FIELDS = [
|
|
1579
|
+
'create', 'isValid', 'is0', 'neg', 'inv', 'sqrt', 'sqr',
|
|
1580
|
+
'eql', 'add', 'sub', 'mul', 'pow', 'div',
|
|
1581
|
+
'addN', 'subN', 'mulN', 'sqrN'
|
|
1582
|
+
];
|
|
1583
|
+
function validateField(field) {
|
|
1584
|
+
const initial = {
|
|
1585
|
+
ORDER: 'bigint',
|
|
1586
|
+
MASK: 'bigint',
|
|
1587
|
+
BYTES: 'isSafeInteger',
|
|
1588
|
+
BITS: 'isSafeInteger',
|
|
1589
|
+
};
|
|
1590
|
+
const opts = FIELD_FIELDS.reduce((map, val) => {
|
|
1591
|
+
map[val] = 'function';
|
|
1592
|
+
return map;
|
|
1593
|
+
}, initial);
|
|
1594
|
+
return validateObject(field, opts);
|
|
1595
|
+
}
|
|
1596
|
+
// Generic field functions
|
|
1597
|
+
/**
|
|
1598
|
+
* Same as `pow` but for Fp: non-constant-time.
|
|
1599
|
+
* Unsafe in some contexts: uses ladder, so can expose bigint bits.
|
|
1600
|
+
*/
|
|
1601
|
+
function FpPow(Fp, num, power) {
|
|
1602
|
+
if (power < _0n$2)
|
|
1603
|
+
throw new Error('invalid exponent, negatives unsupported');
|
|
1604
|
+
if (power === _0n$2)
|
|
1605
|
+
return Fp.ONE;
|
|
1606
|
+
if (power === _1n$3)
|
|
1607
|
+
return num;
|
|
1608
|
+
// @ts-ignore
|
|
1609
|
+
let p = Fp.ONE;
|
|
1610
|
+
let d = num;
|
|
1611
|
+
while (power > _0n$2) {
|
|
1612
|
+
if (power & _1n$3)
|
|
1613
|
+
p = Fp.mul(p, d);
|
|
1614
|
+
d = Fp.sqr(d);
|
|
1615
|
+
power >>= _1n$3;
|
|
1616
|
+
}
|
|
1617
|
+
return p;
|
|
1618
|
+
}
|
|
1619
|
+
/**
|
|
1620
|
+
* Efficiently invert an array of Field elements.
|
|
1621
|
+
* Exception-free. Will return `undefined` for 0 elements.
|
|
1622
|
+
* @param passZero map 0 to 0 (instead of undefined)
|
|
1623
|
+
*/
|
|
1624
|
+
function FpInvertBatch(Fp, nums, passZero = false) {
|
|
1625
|
+
const inverted = new Array(nums.length).fill(passZero ? Fp.ZERO : undefined);
|
|
1626
|
+
// Walk from first to last, multiply them by each other MOD p
|
|
1627
|
+
const multipliedAcc = nums.reduce((acc, num, i) => {
|
|
1628
|
+
if (Fp.is0(num))
|
|
1629
|
+
return acc;
|
|
1630
|
+
inverted[i] = acc;
|
|
1631
|
+
return Fp.mul(acc, num);
|
|
1632
|
+
}, Fp.ONE);
|
|
1633
|
+
// Invert last element
|
|
1634
|
+
const invertedAcc = Fp.inv(multipliedAcc);
|
|
1635
|
+
// Walk from last to first, multiply them by inverted each other MOD p
|
|
1636
|
+
nums.reduceRight((acc, num, i) => {
|
|
1637
|
+
if (Fp.is0(num))
|
|
1638
|
+
return acc;
|
|
1639
|
+
inverted[i] = Fp.mul(acc, inverted[i]);
|
|
1640
|
+
return Fp.mul(acc, num);
|
|
1641
|
+
}, invertedAcc);
|
|
1642
|
+
return inverted;
|
|
1643
|
+
}
|
|
1644
|
+
/**
|
|
1645
|
+
* Legendre symbol.
|
|
1646
|
+
* Legendre constant is used to calculate Legendre symbol (a | p)
|
|
1647
|
+
* which denotes the value of a^((p-1)/2) (mod p)..
|
|
1648
|
+
*
|
|
1649
|
+
* * (a | p) ≡ 1 if a is a square (mod p), quadratic residue
|
|
1650
|
+
* * (a | p) ≡ -1 if a is not a square (mod p), quadratic non residue
|
|
1651
|
+
* * (a | p) ≡ 0 if a ≡ 0 (mod p)
|
|
1652
|
+
*/
|
|
1653
|
+
function FpLegendre(Fp, n) {
|
|
1654
|
+
const legc = (Fp.ORDER - _1n$3) / _2n$1;
|
|
1655
|
+
const powered = Fp.pow(n, legc);
|
|
1656
|
+
const yes = Fp.eql(powered, Fp.ONE);
|
|
1657
|
+
const zero = Fp.eql(powered, Fp.ZERO);
|
|
1658
|
+
const no = Fp.eql(powered, Fp.neg(Fp.ONE));
|
|
1659
|
+
if (!yes && !zero && !no)
|
|
1660
|
+
throw new Error('Cannot find square root: probably non-prime P');
|
|
1661
|
+
return yes ? 1 : zero ? 0 : -1;
|
|
1662
|
+
}
|
|
1663
|
+
// This function returns True whenever the value x is a square in the field F.
|
|
1664
|
+
function FpIsSquare(Fp, n) {
|
|
1665
|
+
const l = FpLegendre(Fp, n);
|
|
1666
|
+
return l === 0 || l === 1;
|
|
1667
|
+
}
|
|
1668
|
+
// CURVE.n lengths
|
|
1669
|
+
function nLength(n, nBitLength) {
|
|
1670
|
+
// Bit size, byte size of CURVE.n
|
|
1671
|
+
if (nBitLength !== undefined)
|
|
1672
|
+
anumber(nBitLength);
|
|
1673
|
+
const _nBitLength = nBitLength !== undefined ? nBitLength : n.toString(2).length;
|
|
1674
|
+
const nByteLength = Math.ceil(_nBitLength / 8);
|
|
1675
|
+
return { nBitLength: _nBitLength, nByteLength };
|
|
1676
|
+
}
|
|
1677
|
+
/**
|
|
1678
|
+
* Initializes a finite field over prime.
|
|
1679
|
+
* Major performance optimizations:
|
|
1680
|
+
* * a) denormalized operations like mulN instead of mul
|
|
1681
|
+
* * b) same object shape: never add or remove keys
|
|
1682
|
+
* * c) Object.freeze
|
|
1683
|
+
* Fragile: always run a benchmark on a change.
|
|
1684
|
+
* Security note: operations don't check 'isValid' for all elements for performance reasons,
|
|
1685
|
+
* it is caller responsibility to check this.
|
|
1686
|
+
* This is low-level code, please make sure you know what you're doing.
|
|
1687
|
+
* @param ORDER prime positive bigint
|
|
1688
|
+
* @param bitLen how many bits the field consumes
|
|
1689
|
+
* @param isLE (def: false) if encoding / decoding should be in little-endian
|
|
1690
|
+
* @param redef optional faster redefinitions of sqrt and other methods
|
|
1691
|
+
*/
|
|
1692
|
+
function Field(ORDER, bitLen, isLE = false, redef = {}) {
|
|
1693
|
+
if (ORDER <= _0n$2)
|
|
1694
|
+
throw new Error('invalid field: expected ORDER > 0, got ' + ORDER);
|
|
1695
|
+
const { nBitLength: BITS, nByteLength: BYTES } = nLength(ORDER, bitLen);
|
|
1696
|
+
if (BYTES > 2048)
|
|
1697
|
+
throw new Error('invalid field: expected ORDER of <= 2048 bytes');
|
|
1698
|
+
let sqrtP; // cached sqrtP
|
|
1699
|
+
const f = Object.freeze({
|
|
1700
|
+
ORDER,
|
|
1701
|
+
isLE,
|
|
1702
|
+
BITS,
|
|
1703
|
+
BYTES,
|
|
1704
|
+
MASK: bitMask(BITS),
|
|
1705
|
+
ZERO: _0n$2,
|
|
1706
|
+
ONE: _1n$3,
|
|
1707
|
+
create: (num) => mod(num, ORDER),
|
|
1708
|
+
isValid: (num) => {
|
|
1709
|
+
if (typeof num !== 'bigint')
|
|
1710
|
+
throw new Error('invalid field element: expected bigint, got ' + typeof num);
|
|
1711
|
+
return _0n$2 <= num && num < ORDER; // 0 is valid element, but it's not invertible
|
|
1712
|
+
},
|
|
1713
|
+
is0: (num) => num === _0n$2,
|
|
1714
|
+
isOdd: (num) => (num & _1n$3) === _1n$3,
|
|
1715
|
+
neg: (num) => mod(-num, ORDER),
|
|
1716
|
+
eql: (lhs, rhs) => lhs === rhs,
|
|
1717
|
+
sqr: (num) => mod(num * num, ORDER),
|
|
1718
|
+
add: (lhs, rhs) => mod(lhs + rhs, ORDER),
|
|
1719
|
+
sub: (lhs, rhs) => mod(lhs - rhs, ORDER),
|
|
1720
|
+
mul: (lhs, rhs) => mod(lhs * rhs, ORDER),
|
|
1721
|
+
pow: (num, power) => FpPow(f, num, power),
|
|
1722
|
+
div: (lhs, rhs) => mod(lhs * invert(rhs, ORDER), ORDER),
|
|
1723
|
+
// Same as above, but doesn't normalize
|
|
1724
|
+
sqrN: (num) => num * num,
|
|
1725
|
+
addN: (lhs, rhs) => lhs + rhs,
|
|
1726
|
+
subN: (lhs, rhs) => lhs - rhs,
|
|
1727
|
+
mulN: (lhs, rhs) => lhs * rhs,
|
|
1728
|
+
inv: (num) => invert(num, ORDER),
|
|
1729
|
+
sqrt: redef.sqrt ||
|
|
1730
|
+
((n) => {
|
|
1731
|
+
if (!sqrtP)
|
|
1732
|
+
sqrtP = FpSqrt(ORDER);
|
|
1733
|
+
return sqrtP(f, n);
|
|
1734
|
+
}),
|
|
1735
|
+
toBytes: (num) => (isLE ? numberToBytesLE(num, BYTES) : numberToBytesBE(num, BYTES)),
|
|
1736
|
+
fromBytes: (bytes) => {
|
|
1737
|
+
if (bytes.length !== BYTES)
|
|
1738
|
+
throw new Error('Field.fromBytes: expected ' + BYTES + ' bytes, got ' + bytes.length);
|
|
1739
|
+
return isLE ? bytesToNumberLE(bytes) : bytesToNumberBE(bytes);
|
|
1740
|
+
},
|
|
1741
|
+
// TODO: we don't need it here, move out to separate fn
|
|
1742
|
+
invertBatch: (lst) => FpInvertBatch(f, lst),
|
|
1743
|
+
// We can't move this out because Fp6, Fp12 implement it
|
|
1744
|
+
// and it's unclear what to return in there.
|
|
1745
|
+
cmov: (a, b, c) => (c ? b : a),
|
|
1746
|
+
});
|
|
1747
|
+
return Object.freeze(f);
|
|
1748
|
+
}
|
|
1749
|
+
/**
|
|
1750
|
+
* Returns total number of bytes consumed by the field element.
|
|
1751
|
+
* For example, 32 bytes for usual 256-bit weierstrass curve.
|
|
1752
|
+
* @param fieldOrder number of field elements, usually CURVE.n
|
|
1753
|
+
* @returns byte length of field
|
|
1754
|
+
*/
|
|
1755
|
+
function getFieldBytesLength(fieldOrder) {
|
|
1756
|
+
if (typeof fieldOrder !== 'bigint')
|
|
1757
|
+
throw new Error('field order must be bigint');
|
|
1758
|
+
const bitLength = fieldOrder.toString(2).length;
|
|
1759
|
+
return Math.ceil(bitLength / 8);
|
|
1760
|
+
}
|
|
1761
|
+
/**
|
|
1762
|
+
* Returns minimal amount of bytes that can be safely reduced
|
|
1763
|
+
* by field order.
|
|
1764
|
+
* Should be 2^-128 for 128-bit curve such as P256.
|
|
1765
|
+
* @param fieldOrder number of field elements, usually CURVE.n
|
|
1766
|
+
* @returns byte length of target hash
|
|
1767
|
+
*/
|
|
1768
|
+
function getMinHashLength(fieldOrder) {
|
|
1769
|
+
const length = getFieldBytesLength(fieldOrder);
|
|
1770
|
+
return length + Math.ceil(length / 2);
|
|
1771
|
+
}
|
|
1772
|
+
/**
|
|
1773
|
+
* "Constant-time" private key generation utility.
|
|
1774
|
+
* Can take (n + n/2) or more bytes of uniform input e.g. from CSPRNG or KDF
|
|
1775
|
+
* and convert them into private scalar, with the modulo bias being negligible.
|
|
1776
|
+
* Needs at least 48 bytes of input for 32-byte private key.
|
|
1777
|
+
* https://research.kudelskisecurity.com/2020/07/28/the-definitive-guide-to-modulo-bias-and-how-to-avoid-it/
|
|
1778
|
+
* FIPS 186-5, A.2 https://csrc.nist.gov/publications/detail/fips/186/5/final
|
|
1779
|
+
* RFC 9380, https://www.rfc-editor.org/rfc/rfc9380#section-5
|
|
1780
|
+
* @param hash hash output from SHA3 or a similar function
|
|
1781
|
+
* @param groupOrder size of subgroup - (e.g. secp256k1.CURVE.n)
|
|
1782
|
+
* @param isLE interpret hash bytes as LE num
|
|
1783
|
+
* @returns valid private scalar
|
|
1784
|
+
*/
|
|
1785
|
+
function mapHashToField(key, fieldOrder, isLE = false) {
|
|
1786
|
+
const len = key.length;
|
|
1787
|
+
const fieldLen = getFieldBytesLength(fieldOrder);
|
|
1788
|
+
const minLen = getMinHashLength(fieldOrder);
|
|
1789
|
+
// No small numbers: need to understand bias story. No huge numbers: easier to detect JS timings.
|
|
1790
|
+
if (len < 16 || len < minLen || len > 1024)
|
|
1791
|
+
throw new Error('expected ' + minLen + '-1024 bytes of input, got ' + len);
|
|
1792
|
+
const num = isLE ? bytesToNumberLE(key) : bytesToNumberBE(key);
|
|
1793
|
+
// `mod(x, 11)` can sometimes produce 0. `mod(x, 10) + 1` is the same, but no 0
|
|
1794
|
+
const reduced = mod(num, fieldOrder - _1n$3) + _1n$3;
|
|
1795
|
+
return isLE ? numberToBytesLE(reduced, fieldLen) : numberToBytesBE(reduced, fieldLen);
|
|
77
1796
|
}
|
|
78
1797
|
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
1798
|
+
/**
|
|
1799
|
+
* Methods for elliptic curve multiplication by scalars.
|
|
1800
|
+
* Contains wNAF, pippenger
|
|
1801
|
+
* @module
|
|
1802
|
+
*/
|
|
1803
|
+
/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
|
|
1804
|
+
const _0n$1 = BigInt(0);
|
|
1805
|
+
const _1n$2 = BigInt(1);
|
|
1806
|
+
function constTimeNegate(condition, item) {
|
|
1807
|
+
const neg = item.negate();
|
|
1808
|
+
return condition ? neg : item;
|
|
1809
|
+
}
|
|
1810
|
+
function validateW(W, bits) {
|
|
1811
|
+
if (!Number.isSafeInteger(W) || W <= 0 || W > bits)
|
|
1812
|
+
throw new Error('invalid window size, expected [1..' + bits + '], got W=' + W);
|
|
1813
|
+
}
|
|
1814
|
+
function calcWOpts(W, scalarBits) {
|
|
1815
|
+
validateW(W, scalarBits);
|
|
1816
|
+
const windows = Math.ceil(scalarBits / W) + 1; // W=8 33. Not 32, because we skip zero
|
|
1817
|
+
const windowSize = 2 ** (W - 1); // W=8 128. Not 256, because we skip zero
|
|
1818
|
+
const maxNumber = 2 ** W; // W=8 256
|
|
1819
|
+
const mask = bitMask(W); // W=8 255 == mask 0b11111111
|
|
1820
|
+
const shiftBy = BigInt(W); // W=8 8
|
|
1821
|
+
return { windows, windowSize, mask, maxNumber, shiftBy };
|
|
1822
|
+
}
|
|
1823
|
+
function calcOffsets(n, window, wOpts) {
|
|
1824
|
+
const { windowSize, mask, maxNumber, shiftBy } = wOpts;
|
|
1825
|
+
let wbits = Number(n & mask); // extract W bits.
|
|
1826
|
+
let nextN = n >> shiftBy; // shift number by W bits.
|
|
1827
|
+
// What actually happens here:
|
|
1828
|
+
// const highestBit = Number(mask ^ (mask >> 1n));
|
|
1829
|
+
// let wbits2 = wbits - 1; // skip zero
|
|
1830
|
+
// if (wbits2 & highestBit) { wbits2 ^= Number(mask); // (~);
|
|
1831
|
+
// split if bits > max: +224 => 256-32
|
|
1832
|
+
if (wbits > windowSize) {
|
|
1833
|
+
// we skip zero, which means instead of `>= size-1`, we do `> size`
|
|
1834
|
+
wbits -= maxNumber; // -32, can be maxNumber - wbits, but then we need to set isNeg here.
|
|
1835
|
+
nextN += _1n$2; // +256 (carry)
|
|
1836
|
+
}
|
|
1837
|
+
const offsetStart = window * windowSize;
|
|
1838
|
+
const offset = offsetStart + Math.abs(wbits) - 1; // -1 because we skip zero
|
|
1839
|
+
const isZero = wbits === 0; // is current window slice a 0?
|
|
1840
|
+
const isNeg = wbits < 0; // is current window slice negative?
|
|
1841
|
+
const isNegF = window % 2 !== 0; // fake random statement for noise
|
|
1842
|
+
const offsetF = offsetStart; // fake offset for noise
|
|
1843
|
+
return { nextN, offset, isZero, isNeg, isNegF, offsetF };
|
|
1844
|
+
}
|
|
1845
|
+
function validateMSMPoints(points, c) {
|
|
1846
|
+
if (!Array.isArray(points))
|
|
1847
|
+
throw new Error('array expected');
|
|
1848
|
+
points.forEach((p, i) => {
|
|
1849
|
+
if (!(p instanceof c))
|
|
1850
|
+
throw new Error('invalid point at index ' + i);
|
|
1851
|
+
});
|
|
1852
|
+
}
|
|
1853
|
+
function validateMSMScalars(scalars, field) {
|
|
1854
|
+
if (!Array.isArray(scalars))
|
|
1855
|
+
throw new Error('array of scalars expected');
|
|
1856
|
+
scalars.forEach((s, i) => {
|
|
1857
|
+
if (!field.isValid(s))
|
|
1858
|
+
throw new Error('invalid scalar at index ' + i);
|
|
1859
|
+
});
|
|
1860
|
+
}
|
|
1861
|
+
// Since points in different groups cannot be equal (different object constructor),
|
|
1862
|
+
// we can have single place to store precomputes.
|
|
1863
|
+
// Allows to make points frozen / immutable.
|
|
1864
|
+
const pointPrecomputes = new WeakMap();
|
|
1865
|
+
const pointWindowSizes = new WeakMap();
|
|
1866
|
+
function getW(P) {
|
|
1867
|
+
return pointWindowSizes.get(P) || 1;
|
|
1868
|
+
}
|
|
1869
|
+
/**
|
|
1870
|
+
* Elliptic curve multiplication of Point by scalar. Fragile.
|
|
1871
|
+
* Scalars should always be less than curve order: this should be checked inside of a curve itself.
|
|
1872
|
+
* Creates precomputation tables for fast multiplication:
|
|
1873
|
+
* - private scalar is split by fixed size windows of W bits
|
|
1874
|
+
* - every window point is collected from window's table & added to accumulator
|
|
1875
|
+
* - since windows are different, same point inside tables won't be accessed more than once per calc
|
|
1876
|
+
* - each multiplication is 'Math.ceil(CURVE_ORDER / 𝑊) + 1' point additions (fixed for any scalar)
|
|
1877
|
+
* - +1 window is neccessary for wNAF
|
|
1878
|
+
* - wNAF reduces table size: 2x less memory + 2x faster generation, but 10% slower multiplication
|
|
1879
|
+
*
|
|
1880
|
+
* @todo Research returning 2d JS array of windows, instead of a single window.
|
|
1881
|
+
* This would allow windows to be in different memory locations
|
|
1882
|
+
*/
|
|
1883
|
+
function wNAF(c, bits) {
|
|
1884
|
+
return {
|
|
1885
|
+
constTimeNegate,
|
|
1886
|
+
hasPrecomputes(elm) {
|
|
1887
|
+
return getW(elm) !== 1;
|
|
1888
|
+
},
|
|
1889
|
+
// non-const time multiplication ladder
|
|
1890
|
+
unsafeLadder(elm, n, p = c.ZERO) {
|
|
1891
|
+
let d = elm;
|
|
1892
|
+
while (n > _0n$1) {
|
|
1893
|
+
if (n & _1n$2)
|
|
1894
|
+
p = p.add(d);
|
|
1895
|
+
d = d.double();
|
|
1896
|
+
n >>= _1n$2;
|
|
1897
|
+
}
|
|
1898
|
+
return p;
|
|
1899
|
+
},
|
|
1900
|
+
/**
|
|
1901
|
+
* Creates a wNAF precomputation window. Used for caching.
|
|
1902
|
+
* Default window size is set by `utils.precompute()` and is equal to 8.
|
|
1903
|
+
* Number of precomputed points depends on the curve size:
|
|
1904
|
+
* 2^(𝑊−1) * (Math.ceil(𝑛 / 𝑊) + 1), where:
|
|
1905
|
+
* - 𝑊 is the window size
|
|
1906
|
+
* - 𝑛 is the bitlength of the curve order.
|
|
1907
|
+
* For a 256-bit curve and window size 8, the number of precomputed points is 128 * 33 = 4224.
|
|
1908
|
+
* @param elm Point instance
|
|
1909
|
+
* @param W window size
|
|
1910
|
+
* @returns precomputed point tables flattened to a single array
|
|
1911
|
+
*/
|
|
1912
|
+
precomputeWindow(elm, W) {
|
|
1913
|
+
const { windows, windowSize } = calcWOpts(W, bits);
|
|
1914
|
+
const points = [];
|
|
1915
|
+
let p = elm;
|
|
1916
|
+
let base = p;
|
|
1917
|
+
for (let window = 0; window < windows; window++) {
|
|
1918
|
+
base = p;
|
|
1919
|
+
points.push(base);
|
|
1920
|
+
// i=1, bc we skip 0
|
|
1921
|
+
for (let i = 1; i < windowSize; i++) {
|
|
1922
|
+
base = base.add(p);
|
|
1923
|
+
points.push(base);
|
|
1924
|
+
}
|
|
1925
|
+
p = base.double();
|
|
1926
|
+
}
|
|
1927
|
+
return points;
|
|
1928
|
+
},
|
|
1929
|
+
/**
|
|
1930
|
+
* Implements ec multiplication using precomputed tables and w-ary non-adjacent form.
|
|
1931
|
+
* @param W window size
|
|
1932
|
+
* @param precomputes precomputed tables
|
|
1933
|
+
* @param n scalar (we don't check here, but should be less than curve order)
|
|
1934
|
+
* @returns real and fake (for const-time) points
|
|
1935
|
+
*/
|
|
1936
|
+
wNAF(W, precomputes, n) {
|
|
1937
|
+
// Smaller version:
|
|
1938
|
+
// https://github.com/paulmillr/noble-secp256k1/blob/47cb1669b6e506ad66b35fe7d76132ae97465da2/index.ts#L502-L541
|
|
1939
|
+
// TODO: check the scalar is less than group order?
|
|
1940
|
+
// wNAF behavior is undefined otherwise. But have to carefully remove
|
|
1941
|
+
// other checks before wNAF. ORDER == bits here.
|
|
1942
|
+
// Accumulators
|
|
1943
|
+
let p = c.ZERO;
|
|
1944
|
+
let f = c.BASE;
|
|
1945
|
+
// This code was first written with assumption that 'f' and 'p' will never be infinity point:
|
|
1946
|
+
// since each addition is multiplied by 2 ** W, it cannot cancel each other. However,
|
|
1947
|
+
// there is negate now: it is possible that negated element from low value
|
|
1948
|
+
// would be the same as high element, which will create carry into next window.
|
|
1949
|
+
// It's not obvious how this can fail, but still worth investigating later.
|
|
1950
|
+
const wo = calcWOpts(W, bits);
|
|
1951
|
+
for (let window = 0; window < wo.windows; window++) {
|
|
1952
|
+
// (n === _0n) is handled and not early-exited. isEven and offsetF are used for noise
|
|
1953
|
+
const { nextN, offset, isZero, isNeg, isNegF, offsetF } = calcOffsets(n, window, wo);
|
|
1954
|
+
n = nextN;
|
|
1955
|
+
if (isZero) {
|
|
1956
|
+
// bits are 0: add garbage to fake point
|
|
1957
|
+
// Important part for const-time getPublicKey: add random "noise" point to f.
|
|
1958
|
+
f = f.add(constTimeNegate(isNegF, precomputes[offsetF]));
|
|
1959
|
+
}
|
|
1960
|
+
else {
|
|
1961
|
+
// bits are 1: add to result point
|
|
1962
|
+
p = p.add(constTimeNegate(isNeg, precomputes[offset]));
|
|
1963
|
+
}
|
|
1964
|
+
}
|
|
1965
|
+
// Return both real and fake points: JIT won't eliminate f.
|
|
1966
|
+
// At this point there is a way to F be infinity-point even if p is not,
|
|
1967
|
+
// which makes it less const-time: around 1 bigint multiply.
|
|
1968
|
+
return { p, f };
|
|
1969
|
+
},
|
|
1970
|
+
/**
|
|
1971
|
+
* Implements ec unsafe (non const-time) multiplication using precomputed tables and w-ary non-adjacent form.
|
|
1972
|
+
* @param W window size
|
|
1973
|
+
* @param precomputes precomputed tables
|
|
1974
|
+
* @param n scalar (we don't check here, but should be less than curve order)
|
|
1975
|
+
* @param acc accumulator point to add result of multiplication
|
|
1976
|
+
* @returns point
|
|
1977
|
+
*/
|
|
1978
|
+
wNAFUnsafe(W, precomputes, n, acc = c.ZERO) {
|
|
1979
|
+
const wo = calcWOpts(W, bits);
|
|
1980
|
+
for (let window = 0; window < wo.windows; window++) {
|
|
1981
|
+
if (n === _0n$1)
|
|
1982
|
+
break; // Early-exit, skip 0 value
|
|
1983
|
+
const { nextN, offset, isZero, isNeg } = calcOffsets(n, window, wo);
|
|
1984
|
+
n = nextN;
|
|
1985
|
+
if (isZero) {
|
|
1986
|
+
// Window bits are 0: skip processing.
|
|
1987
|
+
// Move to next window.
|
|
1988
|
+
continue;
|
|
1989
|
+
}
|
|
1990
|
+
else {
|
|
1991
|
+
const item = precomputes[offset];
|
|
1992
|
+
acc = acc.add(isNeg ? item.negate() : item); // Re-using acc allows to save adds in MSM
|
|
1993
|
+
}
|
|
1994
|
+
}
|
|
1995
|
+
return acc;
|
|
1996
|
+
},
|
|
1997
|
+
getPrecomputes(W, P, transform) {
|
|
1998
|
+
// Calculate precomputes on a first run, reuse them after
|
|
1999
|
+
let comp = pointPrecomputes.get(P);
|
|
2000
|
+
if (!comp) {
|
|
2001
|
+
comp = this.precomputeWindow(P, W);
|
|
2002
|
+
if (W !== 1)
|
|
2003
|
+
pointPrecomputes.set(P, transform(comp));
|
|
2004
|
+
}
|
|
2005
|
+
return comp;
|
|
2006
|
+
},
|
|
2007
|
+
wNAFCached(P, n, transform) {
|
|
2008
|
+
const W = getW(P);
|
|
2009
|
+
return this.wNAF(W, this.getPrecomputes(W, P, transform), n);
|
|
2010
|
+
},
|
|
2011
|
+
wNAFCachedUnsafe(P, n, transform, prev) {
|
|
2012
|
+
const W = getW(P);
|
|
2013
|
+
if (W === 1)
|
|
2014
|
+
return this.unsafeLadder(P, n, prev); // For W=1 ladder is ~x2 faster
|
|
2015
|
+
return this.wNAFUnsafe(W, this.getPrecomputes(W, P, transform), n, prev);
|
|
2016
|
+
},
|
|
2017
|
+
// We calculate precomputes for elliptic curve point multiplication
|
|
2018
|
+
// using windowed method. This specifies window size and
|
|
2019
|
+
// stores precomputed values. Usually only base point would be precomputed.
|
|
2020
|
+
setWindowSize(P, W) {
|
|
2021
|
+
validateW(W, bits);
|
|
2022
|
+
pointWindowSizes.set(P, W);
|
|
2023
|
+
pointPrecomputes.delete(P);
|
|
2024
|
+
},
|
|
2025
|
+
};
|
|
2026
|
+
}
|
|
2027
|
+
/**
|
|
2028
|
+
* Pippenger algorithm for multi-scalar multiplication (MSM, Pa + Qb + Rc + ...).
|
|
2029
|
+
* 30x faster vs naive addition on L=4096, 10x faster than precomputes.
|
|
2030
|
+
* For N=254bit, L=1, it does: 1024 ADD + 254 DBL. For L=5: 1536 ADD + 254 DBL.
|
|
2031
|
+
* Algorithmically constant-time (for same L), even when 1 point + scalar, or when scalar = 0.
|
|
2032
|
+
* @param c Curve Point constructor
|
|
2033
|
+
* @param fieldN field over CURVE.N - important that it's not over CURVE.P
|
|
2034
|
+
* @param points array of L curve points
|
|
2035
|
+
* @param scalars array of L scalars (aka private keys / bigints)
|
|
2036
|
+
*/
|
|
2037
|
+
function pippenger(c, fieldN, points, scalars) {
|
|
2038
|
+
// If we split scalars by some window (let's say 8 bits), every chunk will only
|
|
2039
|
+
// take 256 buckets even if there are 4096 scalars, also re-uses double.
|
|
2040
|
+
// TODO:
|
|
2041
|
+
// - https://eprint.iacr.org/2024/750.pdf
|
|
2042
|
+
// - https://tches.iacr.org/index.php/TCHES/article/view/10287
|
|
2043
|
+
// 0 is accepted in scalars
|
|
2044
|
+
validateMSMPoints(points, c);
|
|
2045
|
+
validateMSMScalars(scalars, fieldN);
|
|
2046
|
+
if (points.length !== scalars.length)
|
|
2047
|
+
throw new Error('arrays of points and scalars must have equal length');
|
|
2048
|
+
const zero = c.ZERO;
|
|
2049
|
+
const wbits = bitLen(BigInt(points.length));
|
|
2050
|
+
const windowSize = wbits > 12 ? wbits - 3 : wbits > 4 ? wbits - 2 : wbits ? 2 : 1; // in bits
|
|
2051
|
+
const MASK = bitMask(windowSize);
|
|
2052
|
+
const buckets = new Array(Number(MASK) + 1).fill(zero); // +1 for zero array
|
|
2053
|
+
const lastBits = Math.floor((fieldN.BITS - 1) / windowSize) * windowSize;
|
|
2054
|
+
let sum = zero;
|
|
2055
|
+
for (let i = lastBits; i >= 0; i -= windowSize) {
|
|
2056
|
+
buckets.fill(zero);
|
|
2057
|
+
for (let j = 0; j < scalars.length; j++) {
|
|
2058
|
+
const scalar = scalars[j];
|
|
2059
|
+
const wbits = Number((scalar >> BigInt(i)) & MASK);
|
|
2060
|
+
buckets[wbits] = buckets[wbits].add(points[j]);
|
|
87
2061
|
}
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
2062
|
+
let resI = zero; // not using this will do small speed-up, but will lose ct
|
|
2063
|
+
// Skip first bucket, because it is zero
|
|
2064
|
+
for (let j = buckets.length - 1, sumI = zero; j > 0; j--) {
|
|
2065
|
+
sumI = sumI.add(buckets[j]);
|
|
2066
|
+
resI = resI.add(sumI);
|
|
93
2067
|
}
|
|
94
|
-
|
|
2068
|
+
sum = sum.add(resI);
|
|
2069
|
+
if (i !== 0)
|
|
2070
|
+
for (let j = 0; j < windowSize; j++)
|
|
2071
|
+
sum = sum.double();
|
|
95
2072
|
}
|
|
2073
|
+
return sum;
|
|
2074
|
+
}
|
|
2075
|
+
function validateBasic(curve) {
|
|
2076
|
+
validateField(curve.Fp);
|
|
2077
|
+
validateObject(curve, {
|
|
2078
|
+
n: 'bigint',
|
|
2079
|
+
h: 'bigint',
|
|
2080
|
+
Gx: 'field',
|
|
2081
|
+
Gy: 'field',
|
|
2082
|
+
}, {
|
|
2083
|
+
nBitLength: 'isSafeInteger',
|
|
2084
|
+
nByteLength: 'isSafeInteger',
|
|
2085
|
+
});
|
|
2086
|
+
// Set defaults
|
|
2087
|
+
return Object.freeze({
|
|
2088
|
+
...nLength(curve.n, curve.nBitLength),
|
|
2089
|
+
...curve,
|
|
2090
|
+
...{ p: curve.Fp.ORDER },
|
|
2091
|
+
});
|
|
96
2092
|
}
|
|
97
2093
|
|
|
2094
|
+
/**
|
|
2095
|
+
* Short Weierstrass curve methods. The formula is: y² = x³ + ax + b.
|
|
2096
|
+
*
|
|
2097
|
+
* ### Parameters
|
|
2098
|
+
*
|
|
2099
|
+
* To initialize a weierstrass curve, one needs to pass following params:
|
|
2100
|
+
*
|
|
2101
|
+
* * a: formula param
|
|
2102
|
+
* * b: formula param
|
|
2103
|
+
* * Fp: finite Field over which we'll do calculations. Can be complex (Fp2, Fp12)
|
|
2104
|
+
* * n: Curve prime subgroup order, total count of valid points in the field
|
|
2105
|
+
* * Gx: Base point (x, y) aka generator point x coordinate
|
|
2106
|
+
* * Gy: ...y coordinate
|
|
2107
|
+
* * h: cofactor, usually 1. h*n = curve group order (n is only subgroup order)
|
|
2108
|
+
* * lowS: whether to enable (default) or disable "low-s" non-malleable signatures
|
|
2109
|
+
*
|
|
2110
|
+
* ### Design rationale for types
|
|
2111
|
+
*
|
|
2112
|
+
* * Interaction between classes from different curves should fail:
|
|
2113
|
+
* `k256.Point.BASE.add(p256.Point.BASE)`
|
|
2114
|
+
* * For this purpose we want to use `instanceof` operator, which is fast and works during runtime
|
|
2115
|
+
* * Different calls of `curve()` would return different classes -
|
|
2116
|
+
* `curve(params) !== curve(params)`: if somebody decided to monkey-patch their curve,
|
|
2117
|
+
* it won't affect others
|
|
2118
|
+
*
|
|
2119
|
+
* TypeScript can't infer types for classes created inside a function. Classes is one instance
|
|
2120
|
+
* of nominative types in TypeScript and interfaces only check for shape, so it's hard to create
|
|
2121
|
+
* unique type for every function call.
|
|
2122
|
+
*
|
|
2123
|
+
* We can use generic types via some param, like curve opts, but that would:
|
|
2124
|
+
* 1. Enable interaction between `curve(params)` and `curve(params)` (curves of same params)
|
|
2125
|
+
* which is hard to debug.
|
|
2126
|
+
* 2. Params can be generic and we can't enforce them to be constant value:
|
|
2127
|
+
* if somebody creates curve from non-constant params,
|
|
2128
|
+
* it would be allowed to interact with other curves with non-constant params
|
|
2129
|
+
*
|
|
2130
|
+
* @todo https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-7.html#unique-symbol
|
|
2131
|
+
* @module
|
|
2132
|
+
*/
|
|
2133
|
+
/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
|
|
2134
|
+
// prettier-ignore
|
|
2135
|
+
function validateSigVerOpts(opts) {
|
|
2136
|
+
if (opts.lowS !== undefined)
|
|
2137
|
+
abool('lowS', opts.lowS);
|
|
2138
|
+
if (opts.prehash !== undefined)
|
|
2139
|
+
abool('prehash', opts.prehash);
|
|
2140
|
+
}
|
|
2141
|
+
function validatePointOpts(curve) {
|
|
2142
|
+
const opts = validateBasic(curve);
|
|
2143
|
+
validateObject(opts, {
|
|
2144
|
+
a: 'field',
|
|
2145
|
+
b: 'field',
|
|
2146
|
+
}, {
|
|
2147
|
+
allowedPrivateKeyLengths: 'array',
|
|
2148
|
+
wrapPrivateKey: 'boolean',
|
|
2149
|
+
isTorsionFree: 'function',
|
|
2150
|
+
clearCofactor: 'function',
|
|
2151
|
+
allowInfinityPoint: 'boolean',
|
|
2152
|
+
fromBytes: 'function',
|
|
2153
|
+
toBytes: 'function',
|
|
2154
|
+
});
|
|
2155
|
+
const { endo, Fp, a } = opts;
|
|
2156
|
+
if (endo) {
|
|
2157
|
+
if (!Fp.eql(a, Fp.ZERO)) {
|
|
2158
|
+
throw new Error('invalid endomorphism, can only be defined for Koblitz curves that have a=0');
|
|
2159
|
+
}
|
|
2160
|
+
if (typeof endo !== 'object' ||
|
|
2161
|
+
typeof endo.beta !== 'bigint' ||
|
|
2162
|
+
typeof endo.splitScalar !== 'function') {
|
|
2163
|
+
throw new Error('invalid endomorphism, expected beta: bigint and splitScalar: function');
|
|
2164
|
+
}
|
|
2165
|
+
}
|
|
2166
|
+
return Object.freeze({ ...opts });
|
|
2167
|
+
}
|
|
2168
|
+
class DERErr extends Error {
|
|
2169
|
+
constructor(m = '') {
|
|
2170
|
+
super(m);
|
|
2171
|
+
}
|
|
2172
|
+
}
|
|
2173
|
+
/**
|
|
2174
|
+
* ASN.1 DER encoding utilities. ASN is very complex & fragile. Format:
|
|
2175
|
+
*
|
|
2176
|
+
* [0x30 (SEQUENCE), bytelength, 0x02 (INTEGER), intLength, R, 0x02 (INTEGER), intLength, S]
|
|
2177
|
+
*
|
|
2178
|
+
* Docs: https://letsencrypt.org/docs/a-warm-welcome-to-asn1-and-der/, https://luca.ntop.org/Teaching/Appunti/asn1.html
|
|
2179
|
+
*/
|
|
2180
|
+
const DER = {
|
|
2181
|
+
// asn.1 DER encoding utils
|
|
2182
|
+
Err: DERErr,
|
|
2183
|
+
// Basic building block is TLV (Tag-Length-Value)
|
|
2184
|
+
_tlv: {
|
|
2185
|
+
encode: (tag, data) => {
|
|
2186
|
+
const { Err: E } = DER;
|
|
2187
|
+
if (tag < 0 || tag > 256)
|
|
2188
|
+
throw new E('tlv.encode: wrong tag');
|
|
2189
|
+
if (data.length & 1)
|
|
2190
|
+
throw new E('tlv.encode: unpadded data');
|
|
2191
|
+
const dataLen = data.length / 2;
|
|
2192
|
+
const len = numberToHexUnpadded(dataLen);
|
|
2193
|
+
if ((len.length / 2) & 128)
|
|
2194
|
+
throw new E('tlv.encode: long form length too big');
|
|
2195
|
+
// length of length with long form flag
|
|
2196
|
+
const lenLen = dataLen > 127 ? numberToHexUnpadded((len.length / 2) | 128) : '';
|
|
2197
|
+
const t = numberToHexUnpadded(tag);
|
|
2198
|
+
return t + lenLen + len + data;
|
|
2199
|
+
},
|
|
2200
|
+
// v - value, l - left bytes (unparsed)
|
|
2201
|
+
decode(tag, data) {
|
|
2202
|
+
const { Err: E } = DER;
|
|
2203
|
+
let pos = 0;
|
|
2204
|
+
if (tag < 0 || tag > 256)
|
|
2205
|
+
throw new E('tlv.encode: wrong tag');
|
|
2206
|
+
if (data.length < 2 || data[pos++] !== tag)
|
|
2207
|
+
throw new E('tlv.decode: wrong tlv');
|
|
2208
|
+
const first = data[pos++];
|
|
2209
|
+
const isLong = !!(first & 128); // First bit of first length byte is flag for short/long form
|
|
2210
|
+
let length = 0;
|
|
2211
|
+
if (!isLong)
|
|
2212
|
+
length = first;
|
|
2213
|
+
else {
|
|
2214
|
+
// Long form: [longFlag(1bit), lengthLength(7bit), length (BE)]
|
|
2215
|
+
const lenLen = first & 127;
|
|
2216
|
+
if (!lenLen)
|
|
2217
|
+
throw new E('tlv.decode(long): indefinite length not supported');
|
|
2218
|
+
if (lenLen > 4)
|
|
2219
|
+
throw new E('tlv.decode(long): byte length is too big'); // this will overflow u32 in js
|
|
2220
|
+
const lengthBytes = data.subarray(pos, pos + lenLen);
|
|
2221
|
+
if (lengthBytes.length !== lenLen)
|
|
2222
|
+
throw new E('tlv.decode: length bytes not complete');
|
|
2223
|
+
if (lengthBytes[0] === 0)
|
|
2224
|
+
throw new E('tlv.decode(long): zero leftmost byte');
|
|
2225
|
+
for (const b of lengthBytes)
|
|
2226
|
+
length = (length << 8) | b;
|
|
2227
|
+
pos += lenLen;
|
|
2228
|
+
if (length < 128)
|
|
2229
|
+
throw new E('tlv.decode(long): not minimal encoding');
|
|
2230
|
+
}
|
|
2231
|
+
const v = data.subarray(pos, pos + length);
|
|
2232
|
+
if (v.length !== length)
|
|
2233
|
+
throw new E('tlv.decode: wrong value length');
|
|
2234
|
+
return { v, l: data.subarray(pos + length) };
|
|
2235
|
+
},
|
|
2236
|
+
},
|
|
2237
|
+
// https://crypto.stackexchange.com/a/57734 Leftmost bit of first byte is 'negative' flag,
|
|
2238
|
+
// since we always use positive integers here. It must always be empty:
|
|
2239
|
+
// - add zero byte if exists
|
|
2240
|
+
// - if next byte doesn't have a flag, leading zero is not allowed (minimal encoding)
|
|
2241
|
+
_int: {
|
|
2242
|
+
encode(num) {
|
|
2243
|
+
const { Err: E } = DER;
|
|
2244
|
+
if (num < _0n)
|
|
2245
|
+
throw new E('integer: negative integers are not allowed');
|
|
2246
|
+
let hex = numberToHexUnpadded(num);
|
|
2247
|
+
// Pad with zero byte if negative flag is present
|
|
2248
|
+
if (Number.parseInt(hex[0], 16) & 0b1000)
|
|
2249
|
+
hex = '00' + hex;
|
|
2250
|
+
if (hex.length & 1)
|
|
2251
|
+
throw new E('unexpected DER parsing assertion: unpadded hex');
|
|
2252
|
+
return hex;
|
|
2253
|
+
},
|
|
2254
|
+
decode(data) {
|
|
2255
|
+
const { Err: E } = DER;
|
|
2256
|
+
if (data[0] & 128)
|
|
2257
|
+
throw new E('invalid signature integer: negative');
|
|
2258
|
+
if (data[0] === 0x00 && !(data[1] & 128))
|
|
2259
|
+
throw new E('invalid signature integer: unnecessary leading zero');
|
|
2260
|
+
return bytesToNumberBE(data);
|
|
2261
|
+
},
|
|
2262
|
+
},
|
|
2263
|
+
toSig(hex) {
|
|
2264
|
+
// parse DER signature
|
|
2265
|
+
const { Err: E, _int: int, _tlv: tlv } = DER;
|
|
2266
|
+
const data = ensureBytes('signature', hex);
|
|
2267
|
+
const { v: seqBytes, l: seqLeftBytes } = tlv.decode(0x30, data);
|
|
2268
|
+
if (seqLeftBytes.length)
|
|
2269
|
+
throw new E('invalid signature: left bytes after parsing');
|
|
2270
|
+
const { v: rBytes, l: rLeftBytes } = tlv.decode(0x02, seqBytes);
|
|
2271
|
+
const { v: sBytes, l: sLeftBytes } = tlv.decode(0x02, rLeftBytes);
|
|
2272
|
+
if (sLeftBytes.length)
|
|
2273
|
+
throw new E('invalid signature: left bytes after parsing');
|
|
2274
|
+
return { r: int.decode(rBytes), s: int.decode(sBytes) };
|
|
2275
|
+
},
|
|
2276
|
+
hexFromSig(sig) {
|
|
2277
|
+
const { _tlv: tlv, _int: int } = DER;
|
|
2278
|
+
const rs = tlv.encode(0x02, int.encode(sig.r));
|
|
2279
|
+
const ss = tlv.encode(0x02, int.encode(sig.s));
|
|
2280
|
+
const seq = rs + ss;
|
|
2281
|
+
return tlv.encode(0x30, seq);
|
|
2282
|
+
},
|
|
2283
|
+
};
|
|
2284
|
+
// Be friendly to bad ECMAScript parsers by not using bigint literals
|
|
2285
|
+
// prettier-ignore
|
|
2286
|
+
const _0n = BigInt(0), _1n$1 = BigInt(1); BigInt(2); const _3n = BigInt(3); BigInt(4);
|
|
2287
|
+
function weierstrassPoints(opts) {
|
|
2288
|
+
const CURVE = validatePointOpts(opts);
|
|
2289
|
+
const { Fp } = CURVE; // All curves has same field / group length as for now, but they can differ
|
|
2290
|
+
const Fn = Field(CURVE.n, CURVE.nBitLength);
|
|
2291
|
+
const toBytes = CURVE.toBytes ||
|
|
2292
|
+
((_c, point, _isCompressed) => {
|
|
2293
|
+
const a = point.toAffine();
|
|
2294
|
+
return concatBytes$1(Uint8Array.from([0x04]), Fp.toBytes(a.x), Fp.toBytes(a.y));
|
|
2295
|
+
});
|
|
2296
|
+
const fromBytes = CURVE.fromBytes ||
|
|
2297
|
+
((bytes) => {
|
|
2298
|
+
// const head = bytes[0];
|
|
2299
|
+
const tail = bytes.subarray(1);
|
|
2300
|
+
// if (head !== 0x04) throw new Error('Only non-compressed encoding is supported');
|
|
2301
|
+
const x = Fp.fromBytes(tail.subarray(0, Fp.BYTES));
|
|
2302
|
+
const y = Fp.fromBytes(tail.subarray(Fp.BYTES, 2 * Fp.BYTES));
|
|
2303
|
+
return { x, y };
|
|
2304
|
+
});
|
|
2305
|
+
/**
|
|
2306
|
+
* y² = x³ + ax + b: Short weierstrass curve formula. Takes x, returns y².
|
|
2307
|
+
* @returns y²
|
|
2308
|
+
*/
|
|
2309
|
+
function weierstrassEquation(x) {
|
|
2310
|
+
const { a, b } = CURVE;
|
|
2311
|
+
const x2 = Fp.sqr(x); // x * x
|
|
2312
|
+
const x3 = Fp.mul(x2, x); // x2 * x
|
|
2313
|
+
return Fp.add(Fp.add(x3, Fp.mul(x, a)), b); // x3 + a * x + b
|
|
2314
|
+
}
|
|
2315
|
+
// Validate whether the passed curve params are valid.
|
|
2316
|
+
// We check if curve equation works for generator point.
|
|
2317
|
+
// `assertValidity()` won't work: `isTorsionFree()` is not available at this point in bls12-381.
|
|
2318
|
+
// ProjectivePoint class has not been initialized yet.
|
|
2319
|
+
if (!Fp.eql(Fp.sqr(CURVE.Gy), weierstrassEquation(CURVE.Gx)))
|
|
2320
|
+
throw new Error('bad generator point: equation left != right');
|
|
2321
|
+
// Valid group elements reside in range 1..n-1
|
|
2322
|
+
function isWithinCurveOrder(num) {
|
|
2323
|
+
return inRange(num, _1n$1, CURVE.n);
|
|
2324
|
+
}
|
|
2325
|
+
// Validates if priv key is valid and converts it to bigint.
|
|
2326
|
+
// Supports options allowedPrivateKeyLengths and wrapPrivateKey.
|
|
2327
|
+
function normPrivateKeyToScalar(key) {
|
|
2328
|
+
const { allowedPrivateKeyLengths: lengths, nByteLength, wrapPrivateKey, n: N } = CURVE;
|
|
2329
|
+
if (lengths && typeof key !== 'bigint') {
|
|
2330
|
+
if (isBytes$2(key))
|
|
2331
|
+
key = bytesToHex$1(key);
|
|
2332
|
+
// Normalize to hex string, pad. E.g. P521 would norm 130-132 char hex to 132-char bytes
|
|
2333
|
+
if (typeof key !== 'string' || !lengths.includes(key.length))
|
|
2334
|
+
throw new Error('invalid private key');
|
|
2335
|
+
key = key.padStart(nByteLength * 2, '0');
|
|
2336
|
+
}
|
|
2337
|
+
let num;
|
|
2338
|
+
try {
|
|
2339
|
+
num =
|
|
2340
|
+
typeof key === 'bigint'
|
|
2341
|
+
? key
|
|
2342
|
+
: bytesToNumberBE(ensureBytes('private key', key, nByteLength));
|
|
2343
|
+
}
|
|
2344
|
+
catch (error) {
|
|
2345
|
+
throw new Error('invalid private key, expected hex or ' + nByteLength + ' bytes, got ' + typeof key);
|
|
2346
|
+
}
|
|
2347
|
+
if (wrapPrivateKey)
|
|
2348
|
+
num = mod(num, N); // disabled by default, enabled for BLS
|
|
2349
|
+
aInRange('private key', num, _1n$1, N); // num in range [1..N-1]
|
|
2350
|
+
return num;
|
|
2351
|
+
}
|
|
2352
|
+
function aprjpoint(other) {
|
|
2353
|
+
if (!(other instanceof Point))
|
|
2354
|
+
throw new Error('ProjectivePoint expected');
|
|
2355
|
+
}
|
|
2356
|
+
// Memoized toAffine / validity check. They are heavy. Points are immutable.
|
|
2357
|
+
// Converts Projective point to affine (x, y) coordinates.
|
|
2358
|
+
// Can accept precomputed Z^-1 - for example, from invertBatch.
|
|
2359
|
+
// (x, y, z) ∋ (x=x/z, y=y/z)
|
|
2360
|
+
const toAffineMemo = memoized((p, iz) => {
|
|
2361
|
+
const { px: x, py: y, pz: z } = p;
|
|
2362
|
+
// Fast-path for normalized points
|
|
2363
|
+
if (Fp.eql(z, Fp.ONE))
|
|
2364
|
+
return { x, y };
|
|
2365
|
+
const is0 = p.is0();
|
|
2366
|
+
// If invZ was 0, we return zero point. However we still want to execute
|
|
2367
|
+
// all operations, so we replace invZ with a random number, 1.
|
|
2368
|
+
if (iz == null)
|
|
2369
|
+
iz = is0 ? Fp.ONE : Fp.inv(z);
|
|
2370
|
+
const ax = Fp.mul(x, iz);
|
|
2371
|
+
const ay = Fp.mul(y, iz);
|
|
2372
|
+
const zz = Fp.mul(z, iz);
|
|
2373
|
+
if (is0)
|
|
2374
|
+
return { x: Fp.ZERO, y: Fp.ZERO };
|
|
2375
|
+
if (!Fp.eql(zz, Fp.ONE))
|
|
2376
|
+
throw new Error('invZ was invalid');
|
|
2377
|
+
return { x: ax, y: ay };
|
|
2378
|
+
});
|
|
2379
|
+
// NOTE: on exception this will crash 'cached' and no value will be set.
|
|
2380
|
+
// Otherwise true will be return
|
|
2381
|
+
const assertValidMemo = memoized((p) => {
|
|
2382
|
+
if (p.is0()) {
|
|
2383
|
+
// (0, 1, 0) aka ZERO is invalid in most contexts.
|
|
2384
|
+
// In BLS, ZERO can be serialized, so we allow it.
|
|
2385
|
+
// (0, 0, 0) is invalid representation of ZERO.
|
|
2386
|
+
if (CURVE.allowInfinityPoint && !Fp.is0(p.py))
|
|
2387
|
+
return;
|
|
2388
|
+
throw new Error('bad point: ZERO');
|
|
2389
|
+
}
|
|
2390
|
+
// Some 3rd-party test vectors require different wording between here & `fromCompressedHex`
|
|
2391
|
+
const { x, y } = p.toAffine();
|
|
2392
|
+
// Check if x, y are valid field elements
|
|
2393
|
+
if (!Fp.isValid(x) || !Fp.isValid(y))
|
|
2394
|
+
throw new Error('bad point: x or y not FE');
|
|
2395
|
+
const left = Fp.sqr(y); // y²
|
|
2396
|
+
const right = weierstrassEquation(x); // x³ + ax + b
|
|
2397
|
+
if (!Fp.eql(left, right))
|
|
2398
|
+
throw new Error('bad point: equation left != right');
|
|
2399
|
+
if (!p.isTorsionFree())
|
|
2400
|
+
throw new Error('bad point: not in prime-order subgroup');
|
|
2401
|
+
return true;
|
|
2402
|
+
});
|
|
2403
|
+
/**
|
|
2404
|
+
* Projective Point works in 3d / projective (homogeneous) coordinates: (x, y, z) ∋ (x=x/z, y=y/z)
|
|
2405
|
+
* Default Point works in 2d / affine coordinates: (x, y)
|
|
2406
|
+
* We're doing calculations in projective, because its operations don't require costly inversion.
|
|
2407
|
+
*/
|
|
2408
|
+
class Point {
|
|
2409
|
+
constructor(px, py, pz) {
|
|
2410
|
+
if (px == null || !Fp.isValid(px))
|
|
2411
|
+
throw new Error('x required');
|
|
2412
|
+
if (py == null || !Fp.isValid(py) || Fp.is0(py))
|
|
2413
|
+
throw new Error('y required');
|
|
2414
|
+
if (pz == null || !Fp.isValid(pz))
|
|
2415
|
+
throw new Error('z required');
|
|
2416
|
+
this.px = px;
|
|
2417
|
+
this.py = py;
|
|
2418
|
+
this.pz = pz;
|
|
2419
|
+
Object.freeze(this);
|
|
2420
|
+
}
|
|
2421
|
+
// Does not validate if the point is on-curve.
|
|
2422
|
+
// Use fromHex instead, or call assertValidity() later.
|
|
2423
|
+
static fromAffine(p) {
|
|
2424
|
+
const { x, y } = p || {};
|
|
2425
|
+
if (!p || !Fp.isValid(x) || !Fp.isValid(y))
|
|
2426
|
+
throw new Error('invalid affine point');
|
|
2427
|
+
if (p instanceof Point)
|
|
2428
|
+
throw new Error('projective point not allowed');
|
|
2429
|
+
const is0 = (i) => Fp.eql(i, Fp.ZERO);
|
|
2430
|
+
// fromAffine(x:0, y:0) would produce (x:0, y:0, z:1), but we need (x:0, y:1, z:0)
|
|
2431
|
+
if (is0(x) && is0(y))
|
|
2432
|
+
return Point.ZERO;
|
|
2433
|
+
return new Point(x, y, Fp.ONE);
|
|
2434
|
+
}
|
|
2435
|
+
get x() {
|
|
2436
|
+
return this.toAffine().x;
|
|
2437
|
+
}
|
|
2438
|
+
get y() {
|
|
2439
|
+
return this.toAffine().y;
|
|
2440
|
+
}
|
|
2441
|
+
/**
|
|
2442
|
+
* Takes a bunch of Projective Points but executes only one
|
|
2443
|
+
* inversion on all of them. Inversion is very slow operation,
|
|
2444
|
+
* so this improves performance massively.
|
|
2445
|
+
* Optimization: converts a list of projective points to a list of identical points with Z=1.
|
|
2446
|
+
*/
|
|
2447
|
+
static normalizeZ(points) {
|
|
2448
|
+
const toInv = FpInvertBatch(Fp, points.map((p) => p.pz));
|
|
2449
|
+
return points.map((p, i) => p.toAffine(toInv[i])).map(Point.fromAffine);
|
|
2450
|
+
}
|
|
2451
|
+
/**
|
|
2452
|
+
* Converts hash string or Uint8Array to Point.
|
|
2453
|
+
* @param hex short/long ECDSA hex
|
|
2454
|
+
*/
|
|
2455
|
+
static fromHex(hex) {
|
|
2456
|
+
const P = Point.fromAffine(fromBytes(ensureBytes('pointHex', hex)));
|
|
2457
|
+
P.assertValidity();
|
|
2458
|
+
return P;
|
|
2459
|
+
}
|
|
2460
|
+
// Multiplies generator point by privateKey.
|
|
2461
|
+
static fromPrivateKey(privateKey) {
|
|
2462
|
+
return Point.BASE.multiply(normPrivateKeyToScalar(privateKey));
|
|
2463
|
+
}
|
|
2464
|
+
// Multiscalar Multiplication
|
|
2465
|
+
static msm(points, scalars) {
|
|
2466
|
+
return pippenger(Point, Fn, points, scalars);
|
|
2467
|
+
}
|
|
2468
|
+
// "Private method", don't use it directly
|
|
2469
|
+
_setWindowSize(windowSize) {
|
|
2470
|
+
wnaf.setWindowSize(this, windowSize);
|
|
2471
|
+
}
|
|
2472
|
+
// A point on curve is valid if it conforms to equation.
|
|
2473
|
+
assertValidity() {
|
|
2474
|
+
assertValidMemo(this);
|
|
2475
|
+
}
|
|
2476
|
+
hasEvenY() {
|
|
2477
|
+
const { y } = this.toAffine();
|
|
2478
|
+
if (Fp.isOdd)
|
|
2479
|
+
return !Fp.isOdd(y);
|
|
2480
|
+
throw new Error("Field doesn't support isOdd");
|
|
2481
|
+
}
|
|
2482
|
+
/**
|
|
2483
|
+
* Compare one point to another.
|
|
2484
|
+
*/
|
|
2485
|
+
equals(other) {
|
|
2486
|
+
aprjpoint(other);
|
|
2487
|
+
const { px: X1, py: Y1, pz: Z1 } = this;
|
|
2488
|
+
const { px: X2, py: Y2, pz: Z2 } = other;
|
|
2489
|
+
const U1 = Fp.eql(Fp.mul(X1, Z2), Fp.mul(X2, Z1));
|
|
2490
|
+
const U2 = Fp.eql(Fp.mul(Y1, Z2), Fp.mul(Y2, Z1));
|
|
2491
|
+
return U1 && U2;
|
|
2492
|
+
}
|
|
2493
|
+
/**
|
|
2494
|
+
* Flips point to one corresponding to (x, -y) in Affine coordinates.
|
|
2495
|
+
*/
|
|
2496
|
+
negate() {
|
|
2497
|
+
return new Point(this.px, Fp.neg(this.py), this.pz);
|
|
2498
|
+
}
|
|
2499
|
+
// Renes-Costello-Batina exception-free doubling formula.
|
|
2500
|
+
// There is 30% faster Jacobian formula, but it is not complete.
|
|
2501
|
+
// https://eprint.iacr.org/2015/1060, algorithm 3
|
|
2502
|
+
// Cost: 8M + 3S + 3*a + 2*b3 + 15add.
|
|
2503
|
+
double() {
|
|
2504
|
+
const { a, b } = CURVE;
|
|
2505
|
+
const b3 = Fp.mul(b, _3n);
|
|
2506
|
+
const { px: X1, py: Y1, pz: Z1 } = this;
|
|
2507
|
+
let X3 = Fp.ZERO, Y3 = Fp.ZERO, Z3 = Fp.ZERO; // prettier-ignore
|
|
2508
|
+
let t0 = Fp.mul(X1, X1); // step 1
|
|
2509
|
+
let t1 = Fp.mul(Y1, Y1);
|
|
2510
|
+
let t2 = Fp.mul(Z1, Z1);
|
|
2511
|
+
let t3 = Fp.mul(X1, Y1);
|
|
2512
|
+
t3 = Fp.add(t3, t3); // step 5
|
|
2513
|
+
Z3 = Fp.mul(X1, Z1);
|
|
2514
|
+
Z3 = Fp.add(Z3, Z3);
|
|
2515
|
+
X3 = Fp.mul(a, Z3);
|
|
2516
|
+
Y3 = Fp.mul(b3, t2);
|
|
2517
|
+
Y3 = Fp.add(X3, Y3); // step 10
|
|
2518
|
+
X3 = Fp.sub(t1, Y3);
|
|
2519
|
+
Y3 = Fp.add(t1, Y3);
|
|
2520
|
+
Y3 = Fp.mul(X3, Y3);
|
|
2521
|
+
X3 = Fp.mul(t3, X3);
|
|
2522
|
+
Z3 = Fp.mul(b3, Z3); // step 15
|
|
2523
|
+
t2 = Fp.mul(a, t2);
|
|
2524
|
+
t3 = Fp.sub(t0, t2);
|
|
2525
|
+
t3 = Fp.mul(a, t3);
|
|
2526
|
+
t3 = Fp.add(t3, Z3);
|
|
2527
|
+
Z3 = Fp.add(t0, t0); // step 20
|
|
2528
|
+
t0 = Fp.add(Z3, t0);
|
|
2529
|
+
t0 = Fp.add(t0, t2);
|
|
2530
|
+
t0 = Fp.mul(t0, t3);
|
|
2531
|
+
Y3 = Fp.add(Y3, t0);
|
|
2532
|
+
t2 = Fp.mul(Y1, Z1); // step 25
|
|
2533
|
+
t2 = Fp.add(t2, t2);
|
|
2534
|
+
t0 = Fp.mul(t2, t3);
|
|
2535
|
+
X3 = Fp.sub(X3, t0);
|
|
2536
|
+
Z3 = Fp.mul(t2, t1);
|
|
2537
|
+
Z3 = Fp.add(Z3, Z3); // step 30
|
|
2538
|
+
Z3 = Fp.add(Z3, Z3);
|
|
2539
|
+
return new Point(X3, Y3, Z3);
|
|
2540
|
+
}
|
|
2541
|
+
// Renes-Costello-Batina exception-free addition formula.
|
|
2542
|
+
// There is 30% faster Jacobian formula, but it is not complete.
|
|
2543
|
+
// https://eprint.iacr.org/2015/1060, algorithm 1
|
|
2544
|
+
// Cost: 12M + 0S + 3*a + 3*b3 + 23add.
|
|
2545
|
+
add(other) {
|
|
2546
|
+
aprjpoint(other);
|
|
2547
|
+
const { px: X1, py: Y1, pz: Z1 } = this;
|
|
2548
|
+
const { px: X2, py: Y2, pz: Z2 } = other;
|
|
2549
|
+
let X3 = Fp.ZERO, Y3 = Fp.ZERO, Z3 = Fp.ZERO; // prettier-ignore
|
|
2550
|
+
const a = CURVE.a;
|
|
2551
|
+
const b3 = Fp.mul(CURVE.b, _3n);
|
|
2552
|
+
let t0 = Fp.mul(X1, X2); // step 1
|
|
2553
|
+
let t1 = Fp.mul(Y1, Y2);
|
|
2554
|
+
let t2 = Fp.mul(Z1, Z2);
|
|
2555
|
+
let t3 = Fp.add(X1, Y1);
|
|
2556
|
+
let t4 = Fp.add(X2, Y2); // step 5
|
|
2557
|
+
t3 = Fp.mul(t3, t4);
|
|
2558
|
+
t4 = Fp.add(t0, t1);
|
|
2559
|
+
t3 = Fp.sub(t3, t4);
|
|
2560
|
+
t4 = Fp.add(X1, Z1);
|
|
2561
|
+
let t5 = Fp.add(X2, Z2); // step 10
|
|
2562
|
+
t4 = Fp.mul(t4, t5);
|
|
2563
|
+
t5 = Fp.add(t0, t2);
|
|
2564
|
+
t4 = Fp.sub(t4, t5);
|
|
2565
|
+
t5 = Fp.add(Y1, Z1);
|
|
2566
|
+
X3 = Fp.add(Y2, Z2); // step 15
|
|
2567
|
+
t5 = Fp.mul(t5, X3);
|
|
2568
|
+
X3 = Fp.add(t1, t2);
|
|
2569
|
+
t5 = Fp.sub(t5, X3);
|
|
2570
|
+
Z3 = Fp.mul(a, t4);
|
|
2571
|
+
X3 = Fp.mul(b3, t2); // step 20
|
|
2572
|
+
Z3 = Fp.add(X3, Z3);
|
|
2573
|
+
X3 = Fp.sub(t1, Z3);
|
|
2574
|
+
Z3 = Fp.add(t1, Z3);
|
|
2575
|
+
Y3 = Fp.mul(X3, Z3);
|
|
2576
|
+
t1 = Fp.add(t0, t0); // step 25
|
|
2577
|
+
t1 = Fp.add(t1, t0);
|
|
2578
|
+
t2 = Fp.mul(a, t2);
|
|
2579
|
+
t4 = Fp.mul(b3, t4);
|
|
2580
|
+
t1 = Fp.add(t1, t2);
|
|
2581
|
+
t2 = Fp.sub(t0, t2); // step 30
|
|
2582
|
+
t2 = Fp.mul(a, t2);
|
|
2583
|
+
t4 = Fp.add(t4, t2);
|
|
2584
|
+
t0 = Fp.mul(t1, t4);
|
|
2585
|
+
Y3 = Fp.add(Y3, t0);
|
|
2586
|
+
t0 = Fp.mul(t5, t4); // step 35
|
|
2587
|
+
X3 = Fp.mul(t3, X3);
|
|
2588
|
+
X3 = Fp.sub(X3, t0);
|
|
2589
|
+
t0 = Fp.mul(t3, t1);
|
|
2590
|
+
Z3 = Fp.mul(t5, Z3);
|
|
2591
|
+
Z3 = Fp.add(Z3, t0); // step 40
|
|
2592
|
+
return new Point(X3, Y3, Z3);
|
|
2593
|
+
}
|
|
2594
|
+
subtract(other) {
|
|
2595
|
+
return this.add(other.negate());
|
|
2596
|
+
}
|
|
2597
|
+
is0() {
|
|
2598
|
+
return this.equals(Point.ZERO);
|
|
2599
|
+
}
|
|
2600
|
+
wNAF(n) {
|
|
2601
|
+
return wnaf.wNAFCached(this, n, Point.normalizeZ);
|
|
2602
|
+
}
|
|
2603
|
+
/**
|
|
2604
|
+
* Non-constant-time multiplication. Uses double-and-add algorithm.
|
|
2605
|
+
* It's faster, but should only be used when you don't care about
|
|
2606
|
+
* an exposed private key e.g. sig verification, which works over *public* keys.
|
|
2607
|
+
*/
|
|
2608
|
+
multiplyUnsafe(sc) {
|
|
2609
|
+
const { endo, n: N } = CURVE;
|
|
2610
|
+
aInRange('scalar', sc, _0n, N);
|
|
2611
|
+
const I = Point.ZERO;
|
|
2612
|
+
if (sc === _0n)
|
|
2613
|
+
return I;
|
|
2614
|
+
if (this.is0() || sc === _1n$1)
|
|
2615
|
+
return this;
|
|
2616
|
+
// Case a: no endomorphism. Case b: has precomputes.
|
|
2617
|
+
if (!endo || wnaf.hasPrecomputes(this))
|
|
2618
|
+
return wnaf.wNAFCachedUnsafe(this, sc, Point.normalizeZ);
|
|
2619
|
+
// Case c: endomorphism
|
|
2620
|
+
let { k1neg, k1, k2neg, k2 } = endo.splitScalar(sc);
|
|
2621
|
+
let k1p = I;
|
|
2622
|
+
let k2p = I;
|
|
2623
|
+
let d = this;
|
|
2624
|
+
while (k1 > _0n || k2 > _0n) {
|
|
2625
|
+
if (k1 & _1n$1)
|
|
2626
|
+
k1p = k1p.add(d);
|
|
2627
|
+
if (k2 & _1n$1)
|
|
2628
|
+
k2p = k2p.add(d);
|
|
2629
|
+
d = d.double();
|
|
2630
|
+
k1 >>= _1n$1;
|
|
2631
|
+
k2 >>= _1n$1;
|
|
2632
|
+
}
|
|
2633
|
+
if (k1neg)
|
|
2634
|
+
k1p = k1p.negate();
|
|
2635
|
+
if (k2neg)
|
|
2636
|
+
k2p = k2p.negate();
|
|
2637
|
+
k2p = new Point(Fp.mul(k2p.px, endo.beta), k2p.py, k2p.pz);
|
|
2638
|
+
return k1p.add(k2p);
|
|
2639
|
+
}
|
|
2640
|
+
/**
|
|
2641
|
+
* Constant time multiplication.
|
|
2642
|
+
* Uses wNAF method. Windowed method may be 10% faster,
|
|
2643
|
+
* but takes 2x longer to generate and consumes 2x memory.
|
|
2644
|
+
* Uses precomputes when available.
|
|
2645
|
+
* Uses endomorphism for Koblitz curves.
|
|
2646
|
+
* @param scalar by which the point would be multiplied
|
|
2647
|
+
* @returns New point
|
|
2648
|
+
*/
|
|
2649
|
+
multiply(scalar) {
|
|
2650
|
+
const { endo, n: N } = CURVE;
|
|
2651
|
+
aInRange('scalar', scalar, _1n$1, N);
|
|
2652
|
+
let point, fake; // Fake point is used to const-time mult
|
|
2653
|
+
if (endo) {
|
|
2654
|
+
const { k1neg, k1, k2neg, k2 } = endo.splitScalar(scalar);
|
|
2655
|
+
let { p: k1p, f: f1p } = this.wNAF(k1);
|
|
2656
|
+
let { p: k2p, f: f2p } = this.wNAF(k2);
|
|
2657
|
+
k1p = wnaf.constTimeNegate(k1neg, k1p);
|
|
2658
|
+
k2p = wnaf.constTimeNegate(k2neg, k2p);
|
|
2659
|
+
k2p = new Point(Fp.mul(k2p.px, endo.beta), k2p.py, k2p.pz);
|
|
2660
|
+
point = k1p.add(k2p);
|
|
2661
|
+
fake = f1p.add(f2p);
|
|
2662
|
+
}
|
|
2663
|
+
else {
|
|
2664
|
+
const { p, f } = this.wNAF(scalar);
|
|
2665
|
+
point = p;
|
|
2666
|
+
fake = f;
|
|
2667
|
+
}
|
|
2668
|
+
// Normalize `z` for both points, but return only real one
|
|
2669
|
+
return Point.normalizeZ([point, fake])[0];
|
|
2670
|
+
}
|
|
2671
|
+
/**
|
|
2672
|
+
* Efficiently calculate `aP + bQ`. Unsafe, can expose private key, if used incorrectly.
|
|
2673
|
+
* Not using Strauss-Shamir trick: precomputation tables are faster.
|
|
2674
|
+
* The trick could be useful if both P and Q are not G (not in our case).
|
|
2675
|
+
* @returns non-zero affine point
|
|
2676
|
+
*/
|
|
2677
|
+
multiplyAndAddUnsafe(Q, a, b) {
|
|
2678
|
+
const G = Point.BASE; // No Strauss-Shamir trick: we have 10% faster G precomputes
|
|
2679
|
+
const mul = (P, a // Select faster multiply() method
|
|
2680
|
+
) => (a === _0n || a === _1n$1 || !P.equals(G) ? P.multiplyUnsafe(a) : P.multiply(a));
|
|
2681
|
+
const sum = mul(this, a).add(mul(Q, b));
|
|
2682
|
+
return sum.is0() ? undefined : sum;
|
|
2683
|
+
}
|
|
2684
|
+
// Converts Projective point to affine (x, y) coordinates.
|
|
2685
|
+
// Can accept precomputed Z^-1 - for example, from invertBatch.
|
|
2686
|
+
// (x, y, z) ∋ (x=x/z, y=y/z)
|
|
2687
|
+
toAffine(iz) {
|
|
2688
|
+
return toAffineMemo(this, iz);
|
|
2689
|
+
}
|
|
2690
|
+
isTorsionFree() {
|
|
2691
|
+
const { h: cofactor, isTorsionFree } = CURVE;
|
|
2692
|
+
if (cofactor === _1n$1)
|
|
2693
|
+
return true; // No subgroups, always torsion-free
|
|
2694
|
+
if (isTorsionFree)
|
|
2695
|
+
return isTorsionFree(Point, this);
|
|
2696
|
+
throw new Error('isTorsionFree() has not been declared for the elliptic curve');
|
|
2697
|
+
}
|
|
2698
|
+
clearCofactor() {
|
|
2699
|
+
const { h: cofactor, clearCofactor } = CURVE;
|
|
2700
|
+
if (cofactor === _1n$1)
|
|
2701
|
+
return this; // Fast-path
|
|
2702
|
+
if (clearCofactor)
|
|
2703
|
+
return clearCofactor(Point, this);
|
|
2704
|
+
return this.multiplyUnsafe(CURVE.h);
|
|
2705
|
+
}
|
|
2706
|
+
toRawBytes(isCompressed = true) {
|
|
2707
|
+
abool('isCompressed', isCompressed);
|
|
2708
|
+
this.assertValidity();
|
|
2709
|
+
return toBytes(Point, this, isCompressed);
|
|
2710
|
+
}
|
|
2711
|
+
toHex(isCompressed = true) {
|
|
2712
|
+
abool('isCompressed', isCompressed);
|
|
2713
|
+
return bytesToHex$1(this.toRawBytes(isCompressed));
|
|
2714
|
+
}
|
|
2715
|
+
}
|
|
2716
|
+
Point.BASE = new Point(CURVE.Gx, CURVE.Gy, Fp.ONE);
|
|
2717
|
+
Point.ZERO = new Point(Fp.ZERO, Fp.ONE, Fp.ZERO); // 0, 1, 0
|
|
2718
|
+
const _bits = CURVE.nBitLength;
|
|
2719
|
+
const wnaf = wNAF(Point, CURVE.endo ? Math.ceil(_bits / 2) : _bits);
|
|
2720
|
+
return {
|
|
2721
|
+
CURVE,
|
|
2722
|
+
ProjectivePoint: Point,
|
|
2723
|
+
normPrivateKeyToScalar,
|
|
2724
|
+
weierstrassEquation,
|
|
2725
|
+
isWithinCurveOrder,
|
|
2726
|
+
};
|
|
2727
|
+
}
|
|
2728
|
+
function validateOpts(curve) {
|
|
2729
|
+
const opts = validateBasic(curve);
|
|
2730
|
+
validateObject(opts, {
|
|
2731
|
+
hash: 'hash',
|
|
2732
|
+
hmac: 'function',
|
|
2733
|
+
randomBytes: 'function',
|
|
2734
|
+
}, {
|
|
2735
|
+
bits2int: 'function',
|
|
2736
|
+
bits2int_modN: 'function',
|
|
2737
|
+
lowS: 'boolean',
|
|
2738
|
+
});
|
|
2739
|
+
return Object.freeze({ lowS: true, ...opts });
|
|
2740
|
+
}
|
|
2741
|
+
/**
|
|
2742
|
+
* Creates short weierstrass curve and ECDSA signature methods for it.
|
|
2743
|
+
* @example
|
|
2744
|
+
* import { Field } from '@noble/curves/abstract/modular';
|
|
2745
|
+
* // Before that, define BigInt-s: a, b, p, n, Gx, Gy
|
|
2746
|
+
* const curve = weierstrass({ a, b, Fp: Field(p), n, Gx, Gy, h: 1n })
|
|
2747
|
+
*/
|
|
2748
|
+
function weierstrass(curveDef) {
|
|
2749
|
+
const CURVE = validateOpts(curveDef);
|
|
2750
|
+
const { Fp, n: CURVE_ORDER } = CURVE;
|
|
2751
|
+
const compressedLen = Fp.BYTES + 1; // e.g. 33 for 32
|
|
2752
|
+
const uncompressedLen = 2 * Fp.BYTES + 1; // e.g. 65 for 32
|
|
2753
|
+
function modN(a) {
|
|
2754
|
+
return mod(a, CURVE_ORDER);
|
|
2755
|
+
}
|
|
2756
|
+
function invN(a) {
|
|
2757
|
+
return invert(a, CURVE_ORDER);
|
|
2758
|
+
}
|
|
2759
|
+
const { ProjectivePoint: Point, normPrivateKeyToScalar, weierstrassEquation, isWithinCurveOrder, } = weierstrassPoints({
|
|
2760
|
+
...CURVE,
|
|
2761
|
+
toBytes(_c, point, isCompressed) {
|
|
2762
|
+
const a = point.toAffine();
|
|
2763
|
+
const x = Fp.toBytes(a.x);
|
|
2764
|
+
const cat = concatBytes$1;
|
|
2765
|
+
abool('isCompressed', isCompressed);
|
|
2766
|
+
if (isCompressed) {
|
|
2767
|
+
return cat(Uint8Array.from([point.hasEvenY() ? 0x02 : 0x03]), x);
|
|
2768
|
+
}
|
|
2769
|
+
else {
|
|
2770
|
+
return cat(Uint8Array.from([0x04]), x, Fp.toBytes(a.y));
|
|
2771
|
+
}
|
|
2772
|
+
},
|
|
2773
|
+
fromBytes(bytes) {
|
|
2774
|
+
const len = bytes.length;
|
|
2775
|
+
const head = bytes[0];
|
|
2776
|
+
const tail = bytes.subarray(1);
|
|
2777
|
+
// this.assertValidity() is done inside of fromHex
|
|
2778
|
+
if (len === compressedLen && (head === 0x02 || head === 0x03)) {
|
|
2779
|
+
const x = bytesToNumberBE(tail);
|
|
2780
|
+
if (!inRange(x, _1n$1, Fp.ORDER))
|
|
2781
|
+
throw new Error('Point is not on curve');
|
|
2782
|
+
const y2 = weierstrassEquation(x); // y² = x³ + ax + b
|
|
2783
|
+
let y;
|
|
2784
|
+
try {
|
|
2785
|
+
y = Fp.sqrt(y2); // y = y² ^ (p+1)/4
|
|
2786
|
+
}
|
|
2787
|
+
catch (sqrtError) {
|
|
2788
|
+
const suffix = sqrtError instanceof Error ? ': ' + sqrtError.message : '';
|
|
2789
|
+
throw new Error('Point is not on curve' + suffix);
|
|
2790
|
+
}
|
|
2791
|
+
const isYOdd = (y & _1n$1) === _1n$1;
|
|
2792
|
+
// ECDSA
|
|
2793
|
+
const isHeadOdd = (head & 1) === 1;
|
|
2794
|
+
if (isHeadOdd !== isYOdd)
|
|
2795
|
+
y = Fp.neg(y);
|
|
2796
|
+
return { x, y };
|
|
2797
|
+
}
|
|
2798
|
+
else if (len === uncompressedLen && head === 0x04) {
|
|
2799
|
+
const x = Fp.fromBytes(tail.subarray(0, Fp.BYTES));
|
|
2800
|
+
const y = Fp.fromBytes(tail.subarray(Fp.BYTES, 2 * Fp.BYTES));
|
|
2801
|
+
return { x, y };
|
|
2802
|
+
}
|
|
2803
|
+
else {
|
|
2804
|
+
const cl = compressedLen;
|
|
2805
|
+
const ul = uncompressedLen;
|
|
2806
|
+
throw new Error('invalid Point, expected length of ' + cl + ', or uncompressed ' + ul + ', got ' + len);
|
|
2807
|
+
}
|
|
2808
|
+
},
|
|
2809
|
+
});
|
|
2810
|
+
const numToNByteHex = (num) => bytesToHex$1(numberToBytesBE(num, CURVE.nByteLength));
|
|
2811
|
+
function isBiggerThanHalfOrder(number) {
|
|
2812
|
+
const HALF = CURVE_ORDER >> _1n$1;
|
|
2813
|
+
return number > HALF;
|
|
2814
|
+
}
|
|
2815
|
+
function normalizeS(s) {
|
|
2816
|
+
return isBiggerThanHalfOrder(s) ? modN(-s) : s;
|
|
2817
|
+
}
|
|
2818
|
+
// slice bytes num
|
|
2819
|
+
const slcNum = (b, from, to) => bytesToNumberBE(b.slice(from, to));
|
|
2820
|
+
/**
|
|
2821
|
+
* ECDSA signature with its (r, s) properties. Supports DER & compact representations.
|
|
2822
|
+
*/
|
|
2823
|
+
class Signature {
|
|
2824
|
+
constructor(r, s, recovery) {
|
|
2825
|
+
aInRange('r', r, _1n$1, CURVE_ORDER); // r in [1..N]
|
|
2826
|
+
aInRange('s', s, _1n$1, CURVE_ORDER); // s in [1..N]
|
|
2827
|
+
this.r = r;
|
|
2828
|
+
this.s = s;
|
|
2829
|
+
if (recovery != null)
|
|
2830
|
+
this.recovery = recovery;
|
|
2831
|
+
Object.freeze(this);
|
|
2832
|
+
}
|
|
2833
|
+
// pair (bytes of r, bytes of s)
|
|
2834
|
+
static fromCompact(hex) {
|
|
2835
|
+
const l = CURVE.nByteLength;
|
|
2836
|
+
hex = ensureBytes('compactSignature', hex, l * 2);
|
|
2837
|
+
return new Signature(slcNum(hex, 0, l), slcNum(hex, l, 2 * l));
|
|
2838
|
+
}
|
|
2839
|
+
// DER encoded ECDSA signature
|
|
2840
|
+
// https://bitcoin.stackexchange.com/questions/57644/what-are-the-parts-of-a-bitcoin-transaction-input-script
|
|
2841
|
+
static fromDER(hex) {
|
|
2842
|
+
const { r, s } = DER.toSig(ensureBytes('DER', hex));
|
|
2843
|
+
return new Signature(r, s);
|
|
2844
|
+
}
|
|
2845
|
+
/**
|
|
2846
|
+
* @todo remove
|
|
2847
|
+
* @deprecated
|
|
2848
|
+
*/
|
|
2849
|
+
assertValidity() { }
|
|
2850
|
+
addRecoveryBit(recovery) {
|
|
2851
|
+
return new Signature(this.r, this.s, recovery);
|
|
2852
|
+
}
|
|
2853
|
+
recoverPublicKey(msgHash) {
|
|
2854
|
+
const { r, s, recovery: rec } = this;
|
|
2855
|
+
const h = bits2int_modN(ensureBytes('msgHash', msgHash)); // Truncate hash
|
|
2856
|
+
if (rec == null || ![0, 1, 2, 3].includes(rec))
|
|
2857
|
+
throw new Error('recovery id invalid');
|
|
2858
|
+
const radj = rec === 2 || rec === 3 ? r + CURVE.n : r;
|
|
2859
|
+
if (radj >= Fp.ORDER)
|
|
2860
|
+
throw new Error('recovery id 2 or 3 invalid');
|
|
2861
|
+
const prefix = (rec & 1) === 0 ? '02' : '03';
|
|
2862
|
+
const R = Point.fromHex(prefix + numToNByteHex(radj));
|
|
2863
|
+
const ir = invN(radj); // r^-1
|
|
2864
|
+
const u1 = modN(-h * ir); // -hr^-1
|
|
2865
|
+
const u2 = modN(s * ir); // sr^-1
|
|
2866
|
+
const Q = Point.BASE.multiplyAndAddUnsafe(R, u1, u2); // (sr^-1)R-(hr^-1)G = -(hr^-1)G + (sr^-1)
|
|
2867
|
+
if (!Q)
|
|
2868
|
+
throw new Error('point at infinify'); // unsafe is fine: no priv data leaked
|
|
2869
|
+
Q.assertValidity();
|
|
2870
|
+
return Q;
|
|
2871
|
+
}
|
|
2872
|
+
// Signatures should be low-s, to prevent malleability.
|
|
2873
|
+
hasHighS() {
|
|
2874
|
+
return isBiggerThanHalfOrder(this.s);
|
|
2875
|
+
}
|
|
2876
|
+
normalizeS() {
|
|
2877
|
+
return this.hasHighS() ? new Signature(this.r, modN(-this.s), this.recovery) : this;
|
|
2878
|
+
}
|
|
2879
|
+
// DER-encoded
|
|
2880
|
+
toDERRawBytes() {
|
|
2881
|
+
return hexToBytes$2(this.toDERHex());
|
|
2882
|
+
}
|
|
2883
|
+
toDERHex() {
|
|
2884
|
+
return DER.hexFromSig(this);
|
|
2885
|
+
}
|
|
2886
|
+
// padded bytes of r, then padded bytes of s
|
|
2887
|
+
toCompactRawBytes() {
|
|
2888
|
+
return hexToBytes$2(this.toCompactHex());
|
|
2889
|
+
}
|
|
2890
|
+
toCompactHex() {
|
|
2891
|
+
return numToNByteHex(this.r) + numToNByteHex(this.s);
|
|
2892
|
+
}
|
|
2893
|
+
}
|
|
2894
|
+
const utils = {
|
|
2895
|
+
isValidPrivateKey(privateKey) {
|
|
2896
|
+
try {
|
|
2897
|
+
normPrivateKeyToScalar(privateKey);
|
|
2898
|
+
return true;
|
|
2899
|
+
}
|
|
2900
|
+
catch (error) {
|
|
2901
|
+
return false;
|
|
2902
|
+
}
|
|
2903
|
+
},
|
|
2904
|
+
normPrivateKeyToScalar: normPrivateKeyToScalar,
|
|
2905
|
+
/**
|
|
2906
|
+
* Produces cryptographically secure private key from random of size
|
|
2907
|
+
* (groupLen + ceil(groupLen / 2)) with modulo bias being negligible.
|
|
2908
|
+
*/
|
|
2909
|
+
randomPrivateKey: () => {
|
|
2910
|
+
const length = getMinHashLength(CURVE.n);
|
|
2911
|
+
return mapHashToField(CURVE.randomBytes(length), CURVE.n);
|
|
2912
|
+
},
|
|
2913
|
+
/**
|
|
2914
|
+
* Creates precompute table for an arbitrary EC point. Makes point "cached".
|
|
2915
|
+
* Allows to massively speed-up `point.multiply(scalar)`.
|
|
2916
|
+
* @returns cached point
|
|
2917
|
+
* @example
|
|
2918
|
+
* const fast = utils.precompute(8, ProjectivePoint.fromHex(someonesPubKey));
|
|
2919
|
+
* fast.multiply(privKey); // much faster ECDH now
|
|
2920
|
+
*/
|
|
2921
|
+
precompute(windowSize = 8, point = Point.BASE) {
|
|
2922
|
+
point._setWindowSize(windowSize);
|
|
2923
|
+
point.multiply(BigInt(3)); // 3 is arbitrary, just need any number here
|
|
2924
|
+
return point;
|
|
2925
|
+
},
|
|
2926
|
+
};
|
|
2927
|
+
/**
|
|
2928
|
+
* Computes public key for a private key. Checks for validity of the private key.
|
|
2929
|
+
* @param privateKey private key
|
|
2930
|
+
* @param isCompressed whether to return compact (default), or full key
|
|
2931
|
+
* @returns Public key, full when isCompressed=false; short when isCompressed=true
|
|
2932
|
+
*/
|
|
2933
|
+
function getPublicKey(privateKey, isCompressed = true) {
|
|
2934
|
+
return Point.fromPrivateKey(privateKey).toRawBytes(isCompressed);
|
|
2935
|
+
}
|
|
2936
|
+
/**
|
|
2937
|
+
* Quick and dirty check for item being public key. Does not validate hex, or being on-curve.
|
|
2938
|
+
*/
|
|
2939
|
+
function isProbPub(item) {
|
|
2940
|
+
const arr = isBytes$2(item);
|
|
2941
|
+
const str = typeof item === 'string';
|
|
2942
|
+
const len = (arr || str) && item.length;
|
|
2943
|
+
if (arr)
|
|
2944
|
+
return len === compressedLen || len === uncompressedLen;
|
|
2945
|
+
if (str)
|
|
2946
|
+
return len === 2 * compressedLen || len === 2 * uncompressedLen;
|
|
2947
|
+
if (item instanceof Point)
|
|
2948
|
+
return true;
|
|
2949
|
+
return false;
|
|
2950
|
+
}
|
|
2951
|
+
/**
|
|
2952
|
+
* ECDH (Elliptic Curve Diffie Hellman).
|
|
2953
|
+
* Computes shared public key from private key and public key.
|
|
2954
|
+
* Checks: 1) private key validity 2) shared key is on-curve.
|
|
2955
|
+
* Does NOT hash the result.
|
|
2956
|
+
* @param privateA private key
|
|
2957
|
+
* @param publicB different public key
|
|
2958
|
+
* @param isCompressed whether to return compact (default), or full key
|
|
2959
|
+
* @returns shared public key
|
|
2960
|
+
*/
|
|
2961
|
+
function getSharedSecret(privateA, publicB, isCompressed = true) {
|
|
2962
|
+
if (isProbPub(privateA))
|
|
2963
|
+
throw new Error('first arg must be private key');
|
|
2964
|
+
if (!isProbPub(publicB))
|
|
2965
|
+
throw new Error('second arg must be public key');
|
|
2966
|
+
const b = Point.fromHex(publicB); // check for being on-curve
|
|
2967
|
+
return b.multiply(normPrivateKeyToScalar(privateA)).toRawBytes(isCompressed);
|
|
2968
|
+
}
|
|
2969
|
+
// RFC6979: ensure ECDSA msg is X bytes and < N. RFC suggests optional truncating via bits2octets.
|
|
2970
|
+
// FIPS 186-4 4.6 suggests the leftmost min(nBitLen, outLen) bits, which matches bits2int.
|
|
2971
|
+
// bits2int can produce res>N, we can do mod(res, N) since the bitLen is the same.
|
|
2972
|
+
// int2octets can't be used; pads small msgs with 0: unacceptatble for trunc as per RFC vectors
|
|
2973
|
+
const bits2int = CURVE.bits2int ||
|
|
2974
|
+
function (bytes) {
|
|
2975
|
+
// Our custom check "just in case"
|
|
2976
|
+
if (bytes.length > 8192)
|
|
2977
|
+
throw new Error('input is too large');
|
|
2978
|
+
// For curves with nBitLength % 8 !== 0: bits2octets(bits2octets(m)) !== bits2octets(m)
|
|
2979
|
+
// for some cases, since bytes.length * 8 is not actual bitLength.
|
|
2980
|
+
const num = bytesToNumberBE(bytes); // check for == u8 done here
|
|
2981
|
+
const delta = bytes.length * 8 - CURVE.nBitLength; // truncate to nBitLength leftmost bits
|
|
2982
|
+
return delta > 0 ? num >> BigInt(delta) : num;
|
|
2983
|
+
};
|
|
2984
|
+
const bits2int_modN = CURVE.bits2int_modN ||
|
|
2985
|
+
function (bytes) {
|
|
2986
|
+
return modN(bits2int(bytes)); // can't use bytesToNumberBE here
|
|
2987
|
+
};
|
|
2988
|
+
// NOTE: pads output with zero as per spec
|
|
2989
|
+
const ORDER_MASK = bitMask(CURVE.nBitLength);
|
|
2990
|
+
/**
|
|
2991
|
+
* Converts to bytes. Checks if num in `[0..ORDER_MASK-1]` e.g.: `[0..2^256-1]`.
|
|
2992
|
+
*/
|
|
2993
|
+
function int2octets(num) {
|
|
2994
|
+
aInRange('num < 2^' + CURVE.nBitLength, num, _0n, ORDER_MASK);
|
|
2995
|
+
// works with order, can have different size than numToField!
|
|
2996
|
+
return numberToBytesBE(num, CURVE.nByteLength);
|
|
2997
|
+
}
|
|
2998
|
+
// Steps A, D of RFC6979 3.2
|
|
2999
|
+
// Creates RFC6979 seed; converts msg/privKey to numbers.
|
|
3000
|
+
// Used only in sign, not in verify.
|
|
3001
|
+
// NOTE: we cannot assume here that msgHash has same amount of bytes as curve order,
|
|
3002
|
+
// this will be invalid at least for P521. Also it can be bigger for P224 + SHA256
|
|
3003
|
+
function prepSig(msgHash, privateKey, opts = defaultSigOpts) {
|
|
3004
|
+
if (['recovered', 'canonical'].some((k) => k in opts))
|
|
3005
|
+
throw new Error('sign() legacy options not supported');
|
|
3006
|
+
const { hash, randomBytes } = CURVE;
|
|
3007
|
+
let { lowS, prehash, extraEntropy: ent } = opts; // generates low-s sigs by default
|
|
3008
|
+
if (lowS == null)
|
|
3009
|
+
lowS = true; // RFC6979 3.2: we skip step A, because we already provide hash
|
|
3010
|
+
msgHash = ensureBytes('msgHash', msgHash);
|
|
3011
|
+
validateSigVerOpts(opts);
|
|
3012
|
+
if (prehash)
|
|
3013
|
+
msgHash = ensureBytes('prehashed msgHash', hash(msgHash));
|
|
3014
|
+
// We can't later call bits2octets, since nested bits2int is broken for curves
|
|
3015
|
+
// with nBitLength % 8 !== 0. Because of that, we unwrap it here as int2octets call.
|
|
3016
|
+
// const bits2octets = (bits) => int2octets(bits2int_modN(bits))
|
|
3017
|
+
const h1int = bits2int_modN(msgHash);
|
|
3018
|
+
const d = normPrivateKeyToScalar(privateKey); // validate private key, convert to bigint
|
|
3019
|
+
const seedArgs = [int2octets(d), int2octets(h1int)];
|
|
3020
|
+
// extraEntropy. RFC6979 3.6: additional k' (optional).
|
|
3021
|
+
if (ent != null && ent !== false) {
|
|
3022
|
+
// K = HMAC_K(V || 0x00 || int2octets(x) || bits2octets(h1) || k')
|
|
3023
|
+
const e = ent === true ? randomBytes(Fp.BYTES) : ent; // generate random bytes OR pass as-is
|
|
3024
|
+
seedArgs.push(ensureBytes('extraEntropy', e)); // check for being bytes
|
|
3025
|
+
}
|
|
3026
|
+
const seed = concatBytes$1(...seedArgs); // Step D of RFC6979 3.2
|
|
3027
|
+
const m = h1int; // NOTE: no need to call bits2int second time here, it is inside truncateHash!
|
|
3028
|
+
// Converts signature params into point w r/s, checks result for validity.
|
|
3029
|
+
function k2sig(kBytes) {
|
|
3030
|
+
// RFC 6979 Section 3.2, step 3: k = bits2int(T)
|
|
3031
|
+
const k = bits2int(kBytes); // Cannot use fields methods, since it is group element
|
|
3032
|
+
if (!isWithinCurveOrder(k))
|
|
3033
|
+
return; // Important: all mod() calls here must be done over N
|
|
3034
|
+
const ik = invN(k); // k^-1 mod n
|
|
3035
|
+
const q = Point.BASE.multiply(k).toAffine(); // q = Gk
|
|
3036
|
+
const r = modN(q.x); // r = q.x mod n
|
|
3037
|
+
if (r === _0n)
|
|
3038
|
+
return;
|
|
3039
|
+
// Can use scalar blinding b^-1(bm + bdr) where b ∈ [1,q−1] according to
|
|
3040
|
+
// https://tches.iacr.org/index.php/TCHES/article/view/7337/6509. We've decided against it:
|
|
3041
|
+
// a) dependency on CSPRNG b) 15% slowdown c) doesn't really help since bigints are not CT
|
|
3042
|
+
const s = modN(ik * modN(m + r * d)); // Not using blinding here
|
|
3043
|
+
if (s === _0n)
|
|
3044
|
+
return;
|
|
3045
|
+
let recovery = (q.x === r ? 0 : 2) | Number(q.y & _1n$1); // recovery bit (2 or 3, when q.x > n)
|
|
3046
|
+
let normS = s;
|
|
3047
|
+
if (lowS && isBiggerThanHalfOrder(s)) {
|
|
3048
|
+
normS = normalizeS(s); // if lowS was passed, ensure s is always
|
|
3049
|
+
recovery ^= 1; // // in the bottom half of N
|
|
3050
|
+
}
|
|
3051
|
+
return new Signature(r, normS, recovery); // use normS, not s
|
|
3052
|
+
}
|
|
3053
|
+
return { seed, k2sig };
|
|
3054
|
+
}
|
|
3055
|
+
const defaultSigOpts = { lowS: CURVE.lowS, prehash: false };
|
|
3056
|
+
const defaultVerOpts = { lowS: CURVE.lowS, prehash: false };
|
|
3057
|
+
/**
|
|
3058
|
+
* Signs message hash with a private key.
|
|
3059
|
+
* ```
|
|
3060
|
+
* sign(m, d, k) where
|
|
3061
|
+
* (x, y) = G × k
|
|
3062
|
+
* r = x mod n
|
|
3063
|
+
* s = (m + dr)/k mod n
|
|
3064
|
+
* ```
|
|
3065
|
+
* @param msgHash NOT message. msg needs to be hashed to `msgHash`, or use `prehash`.
|
|
3066
|
+
* @param privKey private key
|
|
3067
|
+
* @param opts lowS for non-malleable sigs. extraEntropy for mixing randomness into k. prehash will hash first arg.
|
|
3068
|
+
* @returns signature with recovery param
|
|
3069
|
+
*/
|
|
3070
|
+
function sign(msgHash, privKey, opts = defaultSigOpts) {
|
|
3071
|
+
const { seed, k2sig } = prepSig(msgHash, privKey, opts); // Steps A, D of RFC6979 3.2.
|
|
3072
|
+
const C = CURVE;
|
|
3073
|
+
const drbg = createHmacDrbg(C.hash.outputLen, C.nByteLength, C.hmac);
|
|
3074
|
+
return drbg(seed, k2sig); // Steps B, C, D, E, F, G
|
|
3075
|
+
}
|
|
3076
|
+
// Enable precomputes. Slows down first publicKey computation by 20ms.
|
|
3077
|
+
Point.BASE._setWindowSize(8);
|
|
3078
|
+
// utils.precompute(8, ProjectivePoint.BASE)
|
|
3079
|
+
/**
|
|
3080
|
+
* Verifies a signature against message hash and public key.
|
|
3081
|
+
* Rejects lowS signatures by default: to override,
|
|
3082
|
+
* specify option `{lowS: false}`. Implements section 4.1.4 from https://www.secg.org/sec1-v2.pdf:
|
|
3083
|
+
*
|
|
3084
|
+
* ```
|
|
3085
|
+
* verify(r, s, h, P) where
|
|
3086
|
+
* U1 = hs^-1 mod n
|
|
3087
|
+
* U2 = rs^-1 mod n
|
|
3088
|
+
* R = U1⋅G - U2⋅P
|
|
3089
|
+
* mod(R.x, n) == r
|
|
3090
|
+
* ```
|
|
3091
|
+
*/
|
|
3092
|
+
function verify(signature, msgHash, publicKey, opts = defaultVerOpts) {
|
|
3093
|
+
const sg = signature;
|
|
3094
|
+
msgHash = ensureBytes('msgHash', msgHash);
|
|
3095
|
+
publicKey = ensureBytes('publicKey', publicKey);
|
|
3096
|
+
const { lowS, prehash, format } = opts;
|
|
3097
|
+
// Verify opts, deduce signature format
|
|
3098
|
+
validateSigVerOpts(opts);
|
|
3099
|
+
if ('strict' in opts)
|
|
3100
|
+
throw new Error('options.strict was renamed to lowS');
|
|
3101
|
+
if (format !== undefined && format !== 'compact' && format !== 'der')
|
|
3102
|
+
throw new Error('format must be compact or der');
|
|
3103
|
+
const isHex = typeof sg === 'string' || isBytes$2(sg);
|
|
3104
|
+
const isObj = !isHex &&
|
|
3105
|
+
!format &&
|
|
3106
|
+
typeof sg === 'object' &&
|
|
3107
|
+
sg !== null &&
|
|
3108
|
+
typeof sg.r === 'bigint' &&
|
|
3109
|
+
typeof sg.s === 'bigint';
|
|
3110
|
+
if (!isHex && !isObj)
|
|
3111
|
+
throw new Error('invalid signature, expected Uint8Array, hex string or Signature instance');
|
|
3112
|
+
let _sig = undefined;
|
|
3113
|
+
let P;
|
|
3114
|
+
try {
|
|
3115
|
+
if (isObj)
|
|
3116
|
+
_sig = new Signature(sg.r, sg.s);
|
|
3117
|
+
if (isHex) {
|
|
3118
|
+
// Signature can be represented in 2 ways: compact (2*nByteLength) & DER (variable-length).
|
|
3119
|
+
// Since DER can also be 2*nByteLength bytes, we check for it first.
|
|
3120
|
+
try {
|
|
3121
|
+
if (format !== 'compact')
|
|
3122
|
+
_sig = Signature.fromDER(sg);
|
|
3123
|
+
}
|
|
3124
|
+
catch (derError) {
|
|
3125
|
+
if (!(derError instanceof DER.Err))
|
|
3126
|
+
throw derError;
|
|
3127
|
+
}
|
|
3128
|
+
if (!_sig && format !== 'der')
|
|
3129
|
+
_sig = Signature.fromCompact(sg);
|
|
3130
|
+
}
|
|
3131
|
+
P = Point.fromHex(publicKey);
|
|
3132
|
+
}
|
|
3133
|
+
catch (error) {
|
|
3134
|
+
return false;
|
|
3135
|
+
}
|
|
3136
|
+
if (!_sig)
|
|
3137
|
+
return false;
|
|
3138
|
+
if (lowS && _sig.hasHighS())
|
|
3139
|
+
return false;
|
|
3140
|
+
if (prehash)
|
|
3141
|
+
msgHash = CURVE.hash(msgHash);
|
|
3142
|
+
const { r, s } = _sig;
|
|
3143
|
+
const h = bits2int_modN(msgHash); // Cannot use fields methods, since it is group element
|
|
3144
|
+
const is = invN(s); // s^-1
|
|
3145
|
+
const u1 = modN(h * is); // u1 = hs^-1 mod n
|
|
3146
|
+
const u2 = modN(r * is); // u2 = rs^-1 mod n
|
|
3147
|
+
const R = Point.BASE.multiplyAndAddUnsafe(P, u1, u2)?.toAffine(); // R = u1⋅G + u2⋅P
|
|
3148
|
+
if (!R)
|
|
3149
|
+
return false;
|
|
3150
|
+
const v = modN(R.x);
|
|
3151
|
+
return v === r;
|
|
3152
|
+
}
|
|
3153
|
+
return {
|
|
3154
|
+
CURVE,
|
|
3155
|
+
getPublicKey,
|
|
3156
|
+
getSharedSecret,
|
|
3157
|
+
sign,
|
|
3158
|
+
verify,
|
|
3159
|
+
ProjectivePoint: Point,
|
|
3160
|
+
Signature,
|
|
3161
|
+
utils,
|
|
3162
|
+
};
|
|
3163
|
+
}
|
|
3164
|
+
|
|
3165
|
+
/**
|
|
3166
|
+
* Utilities for short weierstrass curves, combined with noble-hashes.
|
|
3167
|
+
* @module
|
|
3168
|
+
*/
|
|
3169
|
+
/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
|
|
3170
|
+
/** connects noble-curves to noble-hashes */
|
|
3171
|
+
function getHash(hash) {
|
|
3172
|
+
return {
|
|
3173
|
+
hash,
|
|
3174
|
+
hmac: (key, ...msgs) => hmac(hash, key, concatBytes(...msgs)),
|
|
3175
|
+
randomBytes,
|
|
3176
|
+
};
|
|
3177
|
+
}
|
|
3178
|
+
function createCurve(curveDef, defHash) {
|
|
3179
|
+
const create = (hash) => weierstrass({ ...curveDef, ...getHash(hash) });
|
|
3180
|
+
return { ...create(defHash), create };
|
|
3181
|
+
}
|
|
3182
|
+
|
|
3183
|
+
/**
|
|
3184
|
+
* NIST secp256k1. See [pdf](https://www.secg.org/sec2-v2.pdf).
|
|
3185
|
+
*
|
|
3186
|
+
* Seems to be rigid (not backdoored)
|
|
3187
|
+
* [as per discussion](https://bitcointalk.org/index.php?topic=289795.msg3183975#msg3183975).
|
|
3188
|
+
*
|
|
3189
|
+
* secp256k1 belongs to Koblitz curves: it has efficiently computable endomorphism.
|
|
3190
|
+
* Endomorphism uses 2x less RAM, speeds up precomputation by 2x and ECDH / key recovery by 20%.
|
|
3191
|
+
* For precomputed wNAF it trades off 1/2 init time & 1/3 ram for 20% perf hit.
|
|
3192
|
+
* [See explanation](https://gist.github.com/paulmillr/eb670806793e84df628a7c434a873066).
|
|
3193
|
+
* @module
|
|
3194
|
+
*/
|
|
3195
|
+
/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
|
|
3196
|
+
const secp256k1P = BigInt('0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f');
|
|
3197
|
+
const secp256k1N = BigInt('0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141');
|
|
3198
|
+
const _1n = BigInt(1);
|
|
3199
|
+
const _2n = BigInt(2);
|
|
3200
|
+
const divNearest = (a, b) => (a + b / _2n) / b;
|
|
3201
|
+
/**
|
|
3202
|
+
* √n = n^((p+1)/4) for fields p = 3 mod 4. We unwrap the loop and multiply bit-by-bit.
|
|
3203
|
+
* (P+1n/4n).toString(2) would produce bits [223x 1, 0, 22x 1, 4x 0, 11, 00]
|
|
3204
|
+
*/
|
|
3205
|
+
function sqrtMod(y) {
|
|
3206
|
+
const P = secp256k1P;
|
|
3207
|
+
// prettier-ignore
|
|
3208
|
+
const _3n = BigInt(3), _6n = BigInt(6), _11n = BigInt(11), _22n = BigInt(22);
|
|
3209
|
+
// prettier-ignore
|
|
3210
|
+
const _23n = BigInt(23), _44n = BigInt(44), _88n = BigInt(88);
|
|
3211
|
+
const b2 = (y * y * y) % P; // x^3, 11
|
|
3212
|
+
const b3 = (b2 * b2 * y) % P; // x^7
|
|
3213
|
+
const b6 = (pow2(b3, _3n, P) * b3) % P;
|
|
3214
|
+
const b9 = (pow2(b6, _3n, P) * b3) % P;
|
|
3215
|
+
const b11 = (pow2(b9, _2n, P) * b2) % P;
|
|
3216
|
+
const b22 = (pow2(b11, _11n, P) * b11) % P;
|
|
3217
|
+
const b44 = (pow2(b22, _22n, P) * b22) % P;
|
|
3218
|
+
const b88 = (pow2(b44, _44n, P) * b44) % P;
|
|
3219
|
+
const b176 = (pow2(b88, _88n, P) * b88) % P;
|
|
3220
|
+
const b220 = (pow2(b176, _44n, P) * b44) % P;
|
|
3221
|
+
const b223 = (pow2(b220, _3n, P) * b3) % P;
|
|
3222
|
+
const t1 = (pow2(b223, _23n, P) * b22) % P;
|
|
3223
|
+
const t2 = (pow2(t1, _6n, P) * b2) % P;
|
|
3224
|
+
const root = pow2(t2, _2n, P);
|
|
3225
|
+
if (!Fpk1.eql(Fpk1.sqr(root), y))
|
|
3226
|
+
throw new Error('Cannot find square root');
|
|
3227
|
+
return root;
|
|
3228
|
+
}
|
|
3229
|
+
const Fpk1 = Field(secp256k1P, undefined, undefined, { sqrt: sqrtMod });
|
|
3230
|
+
/**
|
|
3231
|
+
* secp256k1 curve, ECDSA and ECDH methods.
|
|
3232
|
+
*
|
|
3233
|
+
* Field: `2n**256n - 2n**32n - 2n**9n - 2n**8n - 2n**7n - 2n**6n - 2n**4n - 1n`
|
|
3234
|
+
*
|
|
3235
|
+
* @example
|
|
3236
|
+
* ```js
|
|
3237
|
+
* import { secp256k1 } from '@noble/curves/secp256k1';
|
|
3238
|
+
* const priv = secp256k1.utils.randomPrivateKey();
|
|
3239
|
+
* const pub = secp256k1.getPublicKey(priv);
|
|
3240
|
+
* const msg = new Uint8Array(32).fill(1); // message hash (not message) in ecdsa
|
|
3241
|
+
* const sig = secp256k1.sign(msg, priv); // `{prehash: true}` option is available
|
|
3242
|
+
* const isValid = secp256k1.verify(sig, msg, pub) === true;
|
|
3243
|
+
* ```
|
|
3244
|
+
*/
|
|
3245
|
+
const secp256k1 = createCurve({
|
|
3246
|
+
a: BigInt(0),
|
|
3247
|
+
b: BigInt(7),
|
|
3248
|
+
Fp: Fpk1,
|
|
3249
|
+
n: secp256k1N,
|
|
3250
|
+
Gx: BigInt('55066263022277343669578718895168534326250603453777594175500187360389116729240'),
|
|
3251
|
+
Gy: BigInt('32670510020758816978083085130507043184471273380659243275938904335757337482424'),
|
|
3252
|
+
h: BigInt(1),
|
|
3253
|
+
lowS: true, // Allow only low-S signatures by default in sign() and verify()
|
|
3254
|
+
endo: {
|
|
3255
|
+
// Endomorphism, see above
|
|
3256
|
+
beta: BigInt('0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee'),
|
|
3257
|
+
splitScalar: (k) => {
|
|
3258
|
+
const n = secp256k1N;
|
|
3259
|
+
const a1 = BigInt('0x3086d221a7d46bcde86c90e49284eb15');
|
|
3260
|
+
const b1 = -_1n * BigInt('0xe4437ed6010e88286f547fa90abfe4c3');
|
|
3261
|
+
const a2 = BigInt('0x114ca50f7a8e2f3f657c1108d9d44cfd8');
|
|
3262
|
+
const b2 = a1;
|
|
3263
|
+
const POW_2_128 = BigInt('0x100000000000000000000000000000000'); // (2n**128n).toString(16)
|
|
3264
|
+
const c1 = divNearest(b2 * k, n);
|
|
3265
|
+
const c2 = divNearest(-b1 * k, n);
|
|
3266
|
+
let k1 = mod(k - c1 * a1 - c2 * a2, n);
|
|
3267
|
+
let k2 = mod(-c1 * b1 - c2 * b2, n);
|
|
3268
|
+
const k1neg = k1 > POW_2_128;
|
|
3269
|
+
const k2neg = k2 > POW_2_128;
|
|
3270
|
+
if (k1neg)
|
|
3271
|
+
k1 = n - k1;
|
|
3272
|
+
if (k2neg)
|
|
3273
|
+
k2 = n - k2;
|
|
3274
|
+
if (k1 > POW_2_128 || k2 > POW_2_128) {
|
|
3275
|
+
throw new Error('splitScalar: Endomorphism failed, k=' + k);
|
|
3276
|
+
}
|
|
3277
|
+
return { k1neg, k1, k2neg, k2 };
|
|
3278
|
+
},
|
|
3279
|
+
},
|
|
3280
|
+
}, sha256);
|
|
3281
|
+
// Schnorr signatures are superior to ECDSA from above. Below is Schnorr-specific BIP0340 code.
|
|
3282
|
+
// https://github.com/bitcoin/bips/blob/master/bip-0340.mediawiki
|
|
3283
|
+
BigInt(0);
|
|
3284
|
+
secp256k1.ProjectivePoint;
|
|
3285
|
+
|
|
98
3286
|
/**
|
|
99
3287
|
* signs the given message
|
|
100
|
-
* we do not use sign from eth-lib because the pure secp256k1-version is 90% faster
|
|
101
3288
|
* @param {string} privateKey
|
|
102
3289
|
* @param {string} hash
|
|
103
3290
|
* @return {string} hexString
|
|
104
3291
|
*/
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
if (
|
|
108
|
-
throw new Error('
|
|
109
|
-
const sigObj = secp256k1.
|
|
110
|
-
const recoveryId = sigObj.
|
|
111
|
-
const newSignature = '0x' +
|
|
3292
|
+
const sign = (privateKey, hash) => {
|
|
3293
|
+
const hashWith0x = addLeading0x(hash);
|
|
3294
|
+
if (hashWith0x.length !== 66 || !isHexString(hashWith0x))
|
|
3295
|
+
throw new Error('Can only sign hashes, given: ' + hash);
|
|
3296
|
+
const sigObj = secp256k1.sign(hexToBytes(stripHexPrefix(hash)), hexToBytes(stripHexPrefix(privateKey)));
|
|
3297
|
+
const recoveryId = sigObj.recovery === 1 ? '1c' : '1b';
|
|
3298
|
+
const newSignature = '0x' + sigObj.toCompactHex() + recoveryId;
|
|
112
3299
|
return newSignature;
|
|
3300
|
+
};
|
|
3301
|
+
const hmacSha256Sign = (key, msg) => {
|
|
3302
|
+
const result = hmac(sha256, key, msg);
|
|
3303
|
+
return result;
|
|
3304
|
+
};
|
|
3305
|
+
|
|
3306
|
+
const sha512 = wrapHash(sha512$1);
|
|
3307
|
+
|
|
3308
|
+
function getRandomBytesSync(bytes) {
|
|
3309
|
+
return randomBytes(bytes);
|
|
113
3310
|
}
|
|
114
3311
|
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
3312
|
+
/**
|
|
3313
|
+
* Utilities for hex, bytes, CSPRNG.
|
|
3314
|
+
* @module
|
|
3315
|
+
*/
|
|
3316
|
+
/*! noble-ciphers - MIT License (c) 2023 Paul Miller (paulmillr.com) */
|
|
3317
|
+
/** Checks if something is Uint8Array. Be careful: nodejs Buffer will return true. */
|
|
3318
|
+
function isBytes(a) {
|
|
3319
|
+
return a instanceof Uint8Array || (ArrayBuffer.isView(a) && a.constructor.name === 'Uint8Array');
|
|
3320
|
+
}
|
|
3321
|
+
/** Asserts something is Uint8Array. */
|
|
3322
|
+
function abytes(b, ...lengths) {
|
|
3323
|
+
if (!isBytes(b))
|
|
3324
|
+
throw new Error('Uint8Array expected');
|
|
3325
|
+
if (lengths.length > 0 && !lengths.includes(b.length))
|
|
3326
|
+
throw new Error('Uint8Array expected of length ' + lengths + ', got length=' + b.length);
|
|
3327
|
+
}
|
|
3328
|
+
/** Cast u8 / u16 / u32 to u8. */
|
|
3329
|
+
function u8(arr) {
|
|
3330
|
+
return new Uint8Array(arr.buffer, arr.byteOffset, arr.byteLength);
|
|
3331
|
+
}
|
|
3332
|
+
/** Cast u8 / u16 / u32 to u32. */
|
|
3333
|
+
function u32(arr) {
|
|
3334
|
+
return new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4));
|
|
3335
|
+
}
|
|
3336
|
+
/** Zeroize a byte array. Warning: JS provides no guarantees. */
|
|
3337
|
+
function clean(...arrays) {
|
|
3338
|
+
for (let i = 0; i < arrays.length; i++) {
|
|
3339
|
+
arrays[i].fill(0);
|
|
3340
|
+
}
|
|
3341
|
+
}
|
|
3342
|
+
/** Is current platform little-endian? Most are. Big-Endian platform: IBM */
|
|
3343
|
+
const isLE = /* @__PURE__ */ (() => new Uint8Array(new Uint32Array([0x11223344]).buffer)[0] === 0x44)();
|
|
3344
|
+
/**
|
|
3345
|
+
* Checks if two U8A use same underlying buffer and overlaps.
|
|
3346
|
+
* This is invalid and can corrupt data.
|
|
3347
|
+
*/
|
|
3348
|
+
function overlapBytes(a, b) {
|
|
3349
|
+
return (a.buffer === b.buffer && // best we can do, may fail with an obscure Proxy
|
|
3350
|
+
a.byteOffset < b.byteOffset + b.byteLength && // a starts before b end
|
|
3351
|
+
b.byteOffset < a.byteOffset + a.byteLength // b starts before a end
|
|
3352
|
+
);
|
|
3353
|
+
}
|
|
3354
|
+
/**
|
|
3355
|
+
* If input and output overlap and input starts before output, we will overwrite end of input before
|
|
3356
|
+
* we start processing it, so this is not supported for most ciphers (except chacha/salse, which designed with this)
|
|
3357
|
+
*/
|
|
3358
|
+
function complexOverlapBytes(input, output) {
|
|
3359
|
+
// This is very cursed. It works somehow, but I'm completely unsure,
|
|
3360
|
+
// reasoning about overlapping aligned windows is very hard.
|
|
3361
|
+
if (overlapBytes(input, output) && input.byteOffset < output.byteOffset)
|
|
3362
|
+
throw new Error('complex overlap of input and output is not supported');
|
|
3363
|
+
}
|
|
3364
|
+
/**
|
|
3365
|
+
* Wraps a cipher: validates args, ensures encrypt() can only be called once.
|
|
3366
|
+
* @__NO_SIDE_EFFECTS__
|
|
3367
|
+
*/
|
|
3368
|
+
const wrapCipher = (params, constructor) => {
|
|
3369
|
+
function wrappedCipher(key, ...args) {
|
|
3370
|
+
// Validate key
|
|
3371
|
+
abytes(key);
|
|
3372
|
+
// Big-Endian hardware is rare. Just in case someone still decides to run ciphers:
|
|
3373
|
+
if (!isLE)
|
|
3374
|
+
throw new Error('Non little-endian hardware is not yet supported');
|
|
3375
|
+
// Validate nonce if nonceLength is present
|
|
3376
|
+
if (params.nonceLength !== undefined) {
|
|
3377
|
+
const nonce = args[0];
|
|
3378
|
+
if (!nonce)
|
|
3379
|
+
throw new Error('nonce / iv required');
|
|
3380
|
+
if (params.varSizeNonce)
|
|
3381
|
+
abytes(nonce);
|
|
3382
|
+
else
|
|
3383
|
+
abytes(nonce, params.nonceLength);
|
|
3384
|
+
}
|
|
3385
|
+
// Validate AAD if tagLength present
|
|
3386
|
+
const tagl = params.tagLength;
|
|
3387
|
+
if (tagl && args[1] !== undefined) {
|
|
3388
|
+
abytes(args[1]);
|
|
3389
|
+
}
|
|
3390
|
+
const cipher = constructor(key, ...args);
|
|
3391
|
+
const checkOutput = (fnLength, output) => {
|
|
3392
|
+
if (output !== undefined) {
|
|
3393
|
+
if (fnLength !== 2)
|
|
3394
|
+
throw new Error('cipher output not supported');
|
|
3395
|
+
abytes(output);
|
|
3396
|
+
}
|
|
126
3397
|
};
|
|
127
|
-
|
|
128
|
-
|
|
3398
|
+
// Create wrapped cipher with validation and single-use encryption
|
|
3399
|
+
let called = false;
|
|
3400
|
+
const wrCipher = {
|
|
3401
|
+
encrypt(data, output) {
|
|
3402
|
+
if (called)
|
|
3403
|
+
throw new Error('cannot encrypt() twice with same key + nonce');
|
|
3404
|
+
called = true;
|
|
3405
|
+
abytes(data);
|
|
3406
|
+
checkOutput(cipher.encrypt.length, output);
|
|
3407
|
+
return cipher.encrypt(data, output);
|
|
3408
|
+
},
|
|
3409
|
+
decrypt(data, output) {
|
|
3410
|
+
abytes(data);
|
|
3411
|
+
if (tagl && data.length < tagl)
|
|
3412
|
+
throw new Error('invalid ciphertext length: smaller than tagLength=' + tagl);
|
|
3413
|
+
checkOutput(cipher.decrypt.length, output);
|
|
3414
|
+
return cipher.decrypt(data, output);
|
|
3415
|
+
},
|
|
3416
|
+
};
|
|
3417
|
+
return wrCipher;
|
|
3418
|
+
}
|
|
3419
|
+
Object.assign(wrappedCipher, params);
|
|
3420
|
+
return wrappedCipher;
|
|
3421
|
+
};
|
|
3422
|
+
/**
|
|
3423
|
+
* By default, returns u8a of length.
|
|
3424
|
+
* When out is available, it checks it for validity and uses it.
|
|
3425
|
+
*/
|
|
3426
|
+
function getOutput(expectedLength, out, onlyAligned = true) {
|
|
3427
|
+
if (out === undefined)
|
|
3428
|
+
return new Uint8Array(expectedLength);
|
|
3429
|
+
if (out.length !== expectedLength)
|
|
3430
|
+
throw new Error('invalid output length, expected ' + expectedLength + ', got: ' + out.length);
|
|
3431
|
+
if (onlyAligned && !isAligned32(out))
|
|
3432
|
+
throw new Error('invalid output, must be aligned');
|
|
3433
|
+
return out;
|
|
3434
|
+
}
|
|
3435
|
+
// Is byte array aligned to 4 byte offset (u32)?
|
|
3436
|
+
function isAligned32(bytes) {
|
|
3437
|
+
return bytes.byteOffset % 4 === 0;
|
|
3438
|
+
}
|
|
3439
|
+
// copy bytes to new u8a (aligned). Because Buffer.slice is broken.
|
|
3440
|
+
function copyBytes(bytes) {
|
|
3441
|
+
return Uint8Array.from(bytes);
|
|
129
3442
|
}
|
|
130
3443
|
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
3444
|
+
/**
|
|
3445
|
+
* [AES](https://en.wikipedia.org/wiki/Advanced_Encryption_Standard)
|
|
3446
|
+
* a.k.a. Advanced Encryption Standard
|
|
3447
|
+
* is a variant of Rijndael block cipher, standardized by NIST in 2001.
|
|
3448
|
+
* We provide the fastest available pure JS implementation.
|
|
3449
|
+
*
|
|
3450
|
+
* Data is split into 128-bit blocks. Encrypted in 10/12/14 rounds (128/192/256 bits). In every round:
|
|
3451
|
+
* 1. **S-box**, table substitution
|
|
3452
|
+
* 2. **Shift rows**, cyclic shift left of all rows of data array
|
|
3453
|
+
* 3. **Mix columns**, multiplying every column by fixed polynomial
|
|
3454
|
+
* 4. **Add round key**, round_key xor i-th column of array
|
|
3455
|
+
*
|
|
3456
|
+
* Check out [FIPS-197](https://csrc.nist.gov/files/pubs/fips/197/final/docs/fips-197.pdf)
|
|
3457
|
+
* and [original proposal](https://csrc.nist.gov/csrc/media/projects/cryptographic-standards-and-guidelines/documents/aes-development/rijndael-ammended.pdf)
|
|
3458
|
+
* @module
|
|
3459
|
+
*/
|
|
3460
|
+
const BLOCK_SIZE = 16;
|
|
3461
|
+
const BLOCK_SIZE32 = 4;
|
|
3462
|
+
const POLY = 0x11b; // 1 + x + x**3 + x**4 + x**8
|
|
3463
|
+
// TODO: remove multiplication, binary ops only
|
|
3464
|
+
function mul2(n) {
|
|
3465
|
+
return (n << 1) ^ (POLY & -(n >> 7));
|
|
3466
|
+
}
|
|
3467
|
+
function mul(a, b) {
|
|
3468
|
+
let res = 0;
|
|
3469
|
+
for (; b > 0; b >>= 1) {
|
|
3470
|
+
// Montgomery ladder
|
|
3471
|
+
res ^= a & -(b & 1); // if (b&1) res ^=a (but const-time).
|
|
3472
|
+
a = mul2(a); // a = 2*a
|
|
3473
|
+
}
|
|
3474
|
+
return res;
|
|
3475
|
+
}
|
|
3476
|
+
// AES S-box is generated using finite field inversion,
|
|
3477
|
+
// an affine transform, and xor of a constant 0x63.
|
|
3478
|
+
const sbox = /* @__PURE__ */ (() => {
|
|
3479
|
+
const t = new Uint8Array(256);
|
|
3480
|
+
for (let i = 0, x = 1; i < 256; i++, x ^= mul2(x))
|
|
3481
|
+
t[i] = x;
|
|
3482
|
+
const box = new Uint8Array(256);
|
|
3483
|
+
box[0] = 0x63; // first elm
|
|
3484
|
+
for (let i = 0; i < 255; i++) {
|
|
3485
|
+
let x = t[255 - i];
|
|
3486
|
+
x |= x << 8;
|
|
3487
|
+
box[t[i]] = (x ^ (x >> 4) ^ (x >> 5) ^ (x >> 6) ^ (x >> 7) ^ 0x63) & 0xff;
|
|
3488
|
+
}
|
|
3489
|
+
clean(t);
|
|
3490
|
+
return box;
|
|
3491
|
+
})();
|
|
3492
|
+
// Inverted S-box
|
|
3493
|
+
const invSbox = /* @__PURE__ */ sbox.map((_, j) => sbox.indexOf(j));
|
|
3494
|
+
// Rotate u32 by 8
|
|
3495
|
+
const rotr32_8 = (n) => (n << 24) | (n >>> 8);
|
|
3496
|
+
const rotl32_8 = (n) => (n << 8) | (n >>> 24);
|
|
3497
|
+
// T-table is optimization suggested in 5.2 of original proposal (missed from FIPS-197). Changes:
|
|
3498
|
+
// - LE instead of BE
|
|
3499
|
+
// - bigger tables: T0 and T1 are merged into T01 table and T2 & T3 into T23;
|
|
3500
|
+
// so index is u16, instead of u8. This speeds up things, unexpectedly
|
|
3501
|
+
function genTtable(sbox, fn) {
|
|
3502
|
+
if (sbox.length !== 256)
|
|
3503
|
+
throw new Error('Wrong sbox length');
|
|
3504
|
+
const T0 = new Uint32Array(256).map((_, j) => fn(sbox[j]));
|
|
3505
|
+
const T1 = T0.map(rotl32_8);
|
|
3506
|
+
const T2 = T1.map(rotl32_8);
|
|
3507
|
+
const T3 = T2.map(rotl32_8);
|
|
3508
|
+
const T01 = new Uint32Array(256 * 256);
|
|
3509
|
+
const T23 = new Uint32Array(256 * 256);
|
|
3510
|
+
const sbox2 = new Uint16Array(256 * 256);
|
|
3511
|
+
for (let i = 0; i < 256; i++) {
|
|
3512
|
+
for (let j = 0; j < 256; j++) {
|
|
3513
|
+
const idx = i * 256 + j;
|
|
3514
|
+
T01[idx] = T0[i] ^ T1[j];
|
|
3515
|
+
T23[idx] = T2[i] ^ T3[j];
|
|
3516
|
+
sbox2[idx] = (sbox[i] << 8) | sbox[j];
|
|
3517
|
+
}
|
|
3518
|
+
}
|
|
3519
|
+
return { sbox, sbox2, T0, T1, T2, T3, T01, T23 };
|
|
3520
|
+
}
|
|
3521
|
+
const tableEncoding = /* @__PURE__ */ genTtable(sbox, (s) => (mul(s, 3) << 24) | (s << 16) | (s << 8) | mul(s, 2));
|
|
3522
|
+
const tableDecoding = /* @__PURE__ */ genTtable(invSbox, (s) => (mul(s, 11) << 24) | (mul(s, 13) << 16) | (mul(s, 9) << 8) | mul(s, 14));
|
|
3523
|
+
const xPowers = /* @__PURE__ */ (() => {
|
|
3524
|
+
const p = new Uint8Array(16);
|
|
3525
|
+
for (let i = 0, x = 1; i < 16; i++, x = mul2(x))
|
|
3526
|
+
p[i] = x;
|
|
3527
|
+
return p;
|
|
3528
|
+
})();
|
|
3529
|
+
/** Key expansion used in CTR. */
|
|
3530
|
+
function expandKeyLE(key) {
|
|
3531
|
+
abytes(key);
|
|
3532
|
+
const len = key.length;
|
|
3533
|
+
if (![16, 24, 32].includes(len))
|
|
3534
|
+
throw new Error('aes: invalid key size, should be 16, 24 or 32, got ' + len);
|
|
3535
|
+
const { sbox2 } = tableEncoding;
|
|
3536
|
+
const toClean = [];
|
|
3537
|
+
if (!isAligned32(key))
|
|
3538
|
+
toClean.push((key = copyBytes(key)));
|
|
3539
|
+
const k32 = u32(key);
|
|
3540
|
+
const Nk = k32.length;
|
|
3541
|
+
const subByte = (n) => applySbox(sbox2, n, n, n, n);
|
|
3542
|
+
const xk = new Uint32Array(len + 28); // expanded key
|
|
3543
|
+
xk.set(k32);
|
|
3544
|
+
// 4.3.1 Key expansion
|
|
3545
|
+
for (let i = Nk; i < xk.length; i++) {
|
|
3546
|
+
let t = xk[i - 1];
|
|
3547
|
+
if (i % Nk === 0)
|
|
3548
|
+
t = subByte(rotr32_8(t)) ^ xPowers[i / Nk - 1];
|
|
3549
|
+
else if (Nk > 6 && i % Nk === 4)
|
|
3550
|
+
t = subByte(t);
|
|
3551
|
+
xk[i] = xk[i - Nk] ^ t;
|
|
3552
|
+
}
|
|
3553
|
+
clean(...toClean);
|
|
3554
|
+
return xk;
|
|
3555
|
+
}
|
|
3556
|
+
function expandKeyDecLE(key) {
|
|
3557
|
+
const encKey = expandKeyLE(key);
|
|
3558
|
+
const xk = encKey.slice();
|
|
3559
|
+
const Nk = encKey.length;
|
|
3560
|
+
const { sbox2 } = tableEncoding;
|
|
3561
|
+
const { T0, T1, T2, T3 } = tableDecoding;
|
|
3562
|
+
// Inverse key by chunks of 4 (rounds)
|
|
3563
|
+
for (let i = 0; i < Nk; i += 4) {
|
|
3564
|
+
for (let j = 0; j < 4; j++)
|
|
3565
|
+
xk[i + j] = encKey[Nk - i - 4 + j];
|
|
3566
|
+
}
|
|
3567
|
+
clean(encKey);
|
|
3568
|
+
// apply InvMixColumn except first & last round
|
|
3569
|
+
for (let i = 4; i < Nk - 4; i++) {
|
|
3570
|
+
const x = xk[i];
|
|
3571
|
+
const w = applySbox(sbox2, x, x, x, x);
|
|
3572
|
+
xk[i] = T0[w & 0xff] ^ T1[(w >>> 8) & 0xff] ^ T2[(w >>> 16) & 0xff] ^ T3[w >>> 24];
|
|
3573
|
+
}
|
|
3574
|
+
return xk;
|
|
3575
|
+
}
|
|
3576
|
+
// Apply tables
|
|
3577
|
+
function apply0123(T01, T23, s0, s1, s2, s3) {
|
|
3578
|
+
return (T01[((s0 << 8) & 0xff00) | ((s1 >>> 8) & 0xff)] ^
|
|
3579
|
+
T23[((s2 >>> 8) & 0xff00) | ((s3 >>> 24) & 0xff)]);
|
|
3580
|
+
}
|
|
3581
|
+
function applySbox(sbox2, s0, s1, s2, s3) {
|
|
3582
|
+
return (sbox2[(s0 & 0xff) | (s1 & 0xff00)] |
|
|
3583
|
+
(sbox2[((s2 >>> 16) & 0xff) | ((s3 >>> 16) & 0xff00)] << 16));
|
|
3584
|
+
}
|
|
3585
|
+
function encrypt(xk, s0, s1, s2, s3) {
|
|
3586
|
+
const { sbox2, T01, T23 } = tableEncoding;
|
|
3587
|
+
let k = 0;
|
|
3588
|
+
(s0 ^= xk[k++]), (s1 ^= xk[k++]), (s2 ^= xk[k++]), (s3 ^= xk[k++]);
|
|
3589
|
+
const rounds = xk.length / 4 - 2;
|
|
3590
|
+
for (let i = 0; i < rounds; i++) {
|
|
3591
|
+
const t0 = xk[k++] ^ apply0123(T01, T23, s0, s1, s2, s3);
|
|
3592
|
+
const t1 = xk[k++] ^ apply0123(T01, T23, s1, s2, s3, s0);
|
|
3593
|
+
const t2 = xk[k++] ^ apply0123(T01, T23, s2, s3, s0, s1);
|
|
3594
|
+
const t3 = xk[k++] ^ apply0123(T01, T23, s3, s0, s1, s2);
|
|
3595
|
+
(s0 = t0), (s1 = t1), (s2 = t2), (s3 = t3);
|
|
3596
|
+
}
|
|
3597
|
+
// last round (without mixcolumns, so using SBOX2 table)
|
|
3598
|
+
const t0 = xk[k++] ^ applySbox(sbox2, s0, s1, s2, s3);
|
|
3599
|
+
const t1 = xk[k++] ^ applySbox(sbox2, s1, s2, s3, s0);
|
|
3600
|
+
const t2 = xk[k++] ^ applySbox(sbox2, s2, s3, s0, s1);
|
|
3601
|
+
const t3 = xk[k++] ^ applySbox(sbox2, s3, s0, s1, s2);
|
|
3602
|
+
return { s0: t0, s1: t1, s2: t2, s3: t3 };
|
|
3603
|
+
}
|
|
3604
|
+
// Can't be merged with encrypt: arg positions for apply0123 / applySbox are different
|
|
3605
|
+
function decrypt$2(xk, s0, s1, s2, s3) {
|
|
3606
|
+
const { sbox2, T01, T23 } = tableDecoding;
|
|
3607
|
+
let k = 0;
|
|
3608
|
+
(s0 ^= xk[k++]), (s1 ^= xk[k++]), (s2 ^= xk[k++]), (s3 ^= xk[k++]);
|
|
3609
|
+
const rounds = xk.length / 4 - 2;
|
|
3610
|
+
for (let i = 0; i < rounds; i++) {
|
|
3611
|
+
const t0 = xk[k++] ^ apply0123(T01, T23, s0, s3, s2, s1);
|
|
3612
|
+
const t1 = xk[k++] ^ apply0123(T01, T23, s1, s0, s3, s2);
|
|
3613
|
+
const t2 = xk[k++] ^ apply0123(T01, T23, s2, s1, s0, s3);
|
|
3614
|
+
const t3 = xk[k++] ^ apply0123(T01, T23, s3, s2, s1, s0);
|
|
3615
|
+
(s0 = t0), (s1 = t1), (s2 = t2), (s3 = t3);
|
|
3616
|
+
}
|
|
3617
|
+
// Last round
|
|
3618
|
+
const t0 = xk[k++] ^ applySbox(sbox2, s0, s3, s2, s1);
|
|
3619
|
+
const t1 = xk[k++] ^ applySbox(sbox2, s1, s0, s3, s2);
|
|
3620
|
+
const t2 = xk[k++] ^ applySbox(sbox2, s2, s1, s0, s3);
|
|
3621
|
+
const t3 = xk[k++] ^ applySbox(sbox2, s3, s2, s1, s0);
|
|
3622
|
+
return { s0: t0, s1: t1, s2: t2, s3: t3 };
|
|
3623
|
+
}
|
|
3624
|
+
// TODO: investigate merging with ctr32
|
|
3625
|
+
function ctrCounter(xk, nonce, src, dst) {
|
|
3626
|
+
abytes(nonce, BLOCK_SIZE);
|
|
3627
|
+
abytes(src);
|
|
3628
|
+
const srcLen = src.length;
|
|
3629
|
+
dst = getOutput(srcLen, dst);
|
|
3630
|
+
complexOverlapBytes(src, dst);
|
|
3631
|
+
const ctr = nonce;
|
|
3632
|
+
const c32 = u32(ctr);
|
|
3633
|
+
// Fill block (empty, ctr=0)
|
|
3634
|
+
let { s0, s1, s2, s3 } = encrypt(xk, c32[0], c32[1], c32[2], c32[3]);
|
|
3635
|
+
const src32 = u32(src);
|
|
3636
|
+
const dst32 = u32(dst);
|
|
3637
|
+
// process blocks
|
|
3638
|
+
for (let i = 0; i + 4 <= src32.length; i += 4) {
|
|
3639
|
+
dst32[i + 0] = src32[i + 0] ^ s0;
|
|
3640
|
+
dst32[i + 1] = src32[i + 1] ^ s1;
|
|
3641
|
+
dst32[i + 2] = src32[i + 2] ^ s2;
|
|
3642
|
+
dst32[i + 3] = src32[i + 3] ^ s3;
|
|
3643
|
+
// Full 128 bit counter with wrap around
|
|
3644
|
+
let carry = 1;
|
|
3645
|
+
for (let i = ctr.length - 1; i >= 0; i--) {
|
|
3646
|
+
carry = (carry + (ctr[i] & 0xff)) | 0;
|
|
3647
|
+
ctr[i] = carry & 0xff;
|
|
3648
|
+
carry >>>= 8;
|
|
3649
|
+
}
|
|
3650
|
+
({ s0, s1, s2, s3 } = encrypt(xk, c32[0], c32[1], c32[2], c32[3]));
|
|
3651
|
+
}
|
|
3652
|
+
// leftovers (less than block)
|
|
3653
|
+
// It's possible to handle > u32 fast, but is it worth it?
|
|
3654
|
+
const start = BLOCK_SIZE * Math.floor(src32.length / BLOCK_SIZE32);
|
|
3655
|
+
if (start < srcLen) {
|
|
3656
|
+
const b32 = new Uint32Array([s0, s1, s2, s3]);
|
|
3657
|
+
const buf = u8(b32);
|
|
3658
|
+
for (let i = start, pos = 0; i < srcLen; i++, pos++)
|
|
3659
|
+
dst[i] = src[i] ^ buf[pos];
|
|
3660
|
+
clean(b32);
|
|
3661
|
+
}
|
|
3662
|
+
return dst;
|
|
3663
|
+
}
|
|
3664
|
+
/**
|
|
3665
|
+
* CTR: counter mode. Creates stream cipher.
|
|
3666
|
+
* Requires good IV. Parallelizable. OK, but no MAC.
|
|
3667
|
+
*/
|
|
3668
|
+
const ctr = /* @__PURE__ */ wrapCipher({ blockSize: 16, nonceLength: 16 }, function aesctr(key, nonce) {
|
|
3669
|
+
function processCtr(buf, dst) {
|
|
3670
|
+
abytes(buf);
|
|
3671
|
+
if (dst !== undefined) {
|
|
3672
|
+
abytes(dst);
|
|
3673
|
+
if (!isAligned32(dst))
|
|
3674
|
+
throw new Error('unaligned destination');
|
|
3675
|
+
}
|
|
3676
|
+
const xk = expandKeyLE(key);
|
|
3677
|
+
const n = copyBytes(nonce); // align + avoid changing
|
|
3678
|
+
const toClean = [xk, n];
|
|
3679
|
+
if (!isAligned32(buf))
|
|
3680
|
+
toClean.push((buf = copyBytes(buf)));
|
|
3681
|
+
const out = ctrCounter(xk, n, buf, dst);
|
|
3682
|
+
clean(...toClean);
|
|
3683
|
+
return out;
|
|
3684
|
+
}
|
|
3685
|
+
return {
|
|
3686
|
+
encrypt: (plaintext, dst) => processCtr(plaintext, dst),
|
|
3687
|
+
decrypt: (ciphertext, dst) => processCtr(ciphertext, dst),
|
|
142
3688
|
};
|
|
143
|
-
|
|
3689
|
+
});
|
|
3690
|
+
function validateBlockDecrypt(data) {
|
|
3691
|
+
abytes(data);
|
|
3692
|
+
if (data.length % BLOCK_SIZE !== 0) {
|
|
3693
|
+
throw new Error('aes-(cbc/ecb).decrypt ciphertext should consist of blocks with size ' + BLOCK_SIZE);
|
|
3694
|
+
}
|
|
3695
|
+
}
|
|
3696
|
+
function validateBlockEncrypt(plaintext, pcks5, dst) {
|
|
3697
|
+
abytes(plaintext);
|
|
3698
|
+
let outLen = plaintext.length;
|
|
3699
|
+
const remaining = outLen % BLOCK_SIZE;
|
|
3700
|
+
if (!pcks5 && remaining !== 0)
|
|
3701
|
+
throw new Error('aec/(cbc-ecb): unpadded plaintext with disabled padding');
|
|
3702
|
+
if (!isAligned32(plaintext))
|
|
3703
|
+
plaintext = copyBytes(plaintext);
|
|
3704
|
+
const b = u32(plaintext);
|
|
3705
|
+
if (pcks5) {
|
|
3706
|
+
let left = BLOCK_SIZE - remaining;
|
|
3707
|
+
if (!left)
|
|
3708
|
+
left = BLOCK_SIZE; // if no bytes left, create empty padding block
|
|
3709
|
+
outLen = outLen + left;
|
|
3710
|
+
}
|
|
3711
|
+
dst = getOutput(outLen, dst);
|
|
3712
|
+
complexOverlapBytes(plaintext, dst);
|
|
3713
|
+
const o = u32(dst);
|
|
3714
|
+
return { b, o, out: dst };
|
|
144
3715
|
}
|
|
3716
|
+
function validatePCKS(data, pcks5) {
|
|
3717
|
+
if (!pcks5)
|
|
3718
|
+
return data;
|
|
3719
|
+
const len = data.length;
|
|
3720
|
+
if (!len)
|
|
3721
|
+
throw new Error('aes/pcks5: empty ciphertext not allowed');
|
|
3722
|
+
const lastByte = data[len - 1];
|
|
3723
|
+
if (lastByte <= 0 || lastByte > 16)
|
|
3724
|
+
throw new Error('aes/pcks5: wrong padding');
|
|
3725
|
+
const out = data.subarray(0, -lastByte);
|
|
3726
|
+
for (let i = 0; i < lastByte; i++)
|
|
3727
|
+
if (data[len - i - 1] !== lastByte)
|
|
3728
|
+
throw new Error('aes/pcks5: wrong padding');
|
|
3729
|
+
return out;
|
|
3730
|
+
}
|
|
3731
|
+
function padPCKS(left) {
|
|
3732
|
+
const tmp = new Uint8Array(16);
|
|
3733
|
+
const tmp32 = u32(tmp);
|
|
3734
|
+
tmp.set(left);
|
|
3735
|
+
const paddingByte = BLOCK_SIZE - left.length;
|
|
3736
|
+
for (let i = BLOCK_SIZE - paddingByte; i < BLOCK_SIZE; i++)
|
|
3737
|
+
tmp[i] = paddingByte;
|
|
3738
|
+
return tmp32;
|
|
3739
|
+
}
|
|
3740
|
+
/**
|
|
3741
|
+
* CBC: Cipher-Block-Chaining. Key is previous round’s block.
|
|
3742
|
+
* Fragile: needs proper padding. Unauthenticated: needs MAC.
|
|
3743
|
+
*/
|
|
3744
|
+
const cbc = /* @__PURE__ */ wrapCipher({ blockSize: 16, nonceLength: 16 }, function aescbc(key, iv, opts = {}) {
|
|
3745
|
+
const pcks5 = !opts.disablePadding;
|
|
3746
|
+
return {
|
|
3747
|
+
encrypt(plaintext, dst) {
|
|
3748
|
+
const xk = expandKeyLE(key);
|
|
3749
|
+
const { b, o, out: _out } = validateBlockEncrypt(plaintext, pcks5, dst);
|
|
3750
|
+
let _iv = iv;
|
|
3751
|
+
const toClean = [xk];
|
|
3752
|
+
if (!isAligned32(_iv))
|
|
3753
|
+
toClean.push((_iv = copyBytes(_iv)));
|
|
3754
|
+
const n32 = u32(_iv);
|
|
3755
|
+
// prettier-ignore
|
|
3756
|
+
let s0 = n32[0], s1 = n32[1], s2 = n32[2], s3 = n32[3];
|
|
3757
|
+
let i = 0;
|
|
3758
|
+
for (; i + 4 <= b.length;) {
|
|
3759
|
+
(s0 ^= b[i + 0]), (s1 ^= b[i + 1]), (s2 ^= b[i + 2]), (s3 ^= b[i + 3]);
|
|
3760
|
+
({ s0, s1, s2, s3 } = encrypt(xk, s0, s1, s2, s3));
|
|
3761
|
+
(o[i++] = s0), (o[i++] = s1), (o[i++] = s2), (o[i++] = s3);
|
|
3762
|
+
}
|
|
3763
|
+
if (pcks5) {
|
|
3764
|
+
const tmp32 = padPCKS(plaintext.subarray(i * 4));
|
|
3765
|
+
(s0 ^= tmp32[0]), (s1 ^= tmp32[1]), (s2 ^= tmp32[2]), (s3 ^= tmp32[3]);
|
|
3766
|
+
({ s0, s1, s2, s3 } = encrypt(xk, s0, s1, s2, s3));
|
|
3767
|
+
(o[i++] = s0), (o[i++] = s1), (o[i++] = s2), (o[i++] = s3);
|
|
3768
|
+
}
|
|
3769
|
+
clean(...toClean);
|
|
3770
|
+
return _out;
|
|
3771
|
+
},
|
|
3772
|
+
decrypt(ciphertext, dst) {
|
|
3773
|
+
validateBlockDecrypt(ciphertext);
|
|
3774
|
+
const xk = expandKeyDecLE(key);
|
|
3775
|
+
let _iv = iv;
|
|
3776
|
+
const toClean = [xk];
|
|
3777
|
+
if (!isAligned32(_iv))
|
|
3778
|
+
toClean.push((_iv = copyBytes(_iv)));
|
|
3779
|
+
const n32 = u32(_iv);
|
|
3780
|
+
dst = getOutput(ciphertext.length, dst);
|
|
3781
|
+
if (!isAligned32(ciphertext))
|
|
3782
|
+
toClean.push((ciphertext = copyBytes(ciphertext)));
|
|
3783
|
+
complexOverlapBytes(ciphertext, dst);
|
|
3784
|
+
const b = u32(ciphertext);
|
|
3785
|
+
const o = u32(dst);
|
|
3786
|
+
// prettier-ignore
|
|
3787
|
+
let s0 = n32[0], s1 = n32[1], s2 = n32[2], s3 = n32[3];
|
|
3788
|
+
for (let i = 0; i + 4 <= b.length;) {
|
|
3789
|
+
// prettier-ignore
|
|
3790
|
+
const ps0 = s0, ps1 = s1, ps2 = s2, ps3 = s3;
|
|
3791
|
+
(s0 = b[i + 0]), (s1 = b[i + 1]), (s2 = b[i + 2]), (s3 = b[i + 3]);
|
|
3792
|
+
const { s0: o0, s1: o1, s2: o2, s3: o3 } = decrypt$2(xk, s0, s1, s2, s3);
|
|
3793
|
+
(o[i++] = o0 ^ ps0), (o[i++] = o1 ^ ps1), (o[i++] = o2 ^ ps2), (o[i++] = o3 ^ ps3);
|
|
3794
|
+
}
|
|
3795
|
+
clean(...toClean);
|
|
3796
|
+
return validatePCKS(dst, pcks5);
|
|
3797
|
+
},
|
|
3798
|
+
};
|
|
3799
|
+
});
|
|
3800
|
+
|
|
3801
|
+
function getCipher(key, iv, mode, pkcs7PaddingEnabled = true) {
|
|
3802
|
+
if (!mode.startsWith("aes-")) {
|
|
3803
|
+
throw new Error("AES: unsupported mode");
|
|
3804
|
+
}
|
|
3805
|
+
const len = key.length;
|
|
3806
|
+
if ((mode.startsWith("aes-128") && len !== 16) ||
|
|
3807
|
+
(mode.startsWith("aes-256") && len !== 32)) {
|
|
3808
|
+
throw new Error("AES: wrong key length");
|
|
3809
|
+
}
|
|
3810
|
+
if (iv.length !== 16) {
|
|
3811
|
+
throw new Error("AES: wrong IV length");
|
|
3812
|
+
}
|
|
3813
|
+
if (["aes-128-cbc", "aes-256-cbc"].includes(mode)) {
|
|
3814
|
+
return cbc(key, iv, { disablePadding: !pkcs7PaddingEnabled });
|
|
3815
|
+
}
|
|
3816
|
+
if (["aes-128-ctr", "aes-256-ctr"].includes(mode)) {
|
|
3817
|
+
return ctr(key, iv);
|
|
3818
|
+
}
|
|
3819
|
+
throw new Error("AES: unsupported mode");
|
|
3820
|
+
}
|
|
3821
|
+
function decrypt$1(ciphertext, key, iv, mode = "aes-128-ctr", pkcs7PaddingEnabled = true) {
|
|
3822
|
+
return getCipher(key, iv, mode, pkcs7PaddingEnabled).decrypt(ciphertext);
|
|
3823
|
+
}
|
|
3824
|
+
|
|
3825
|
+
/**
|
|
3826
|
+
* Decrypts an encrypted message using the recipient's private key.
|
|
3827
|
+
* @param {string} privateKey - The recipient's private key.
|
|
3828
|
+
* @param {Encrypted} opts - The encrypted message.
|
|
3829
|
+
* @returns {string} The decrypted message.
|
|
3830
|
+
*/
|
|
3831
|
+
const decrypt = (privateKey, opts) => {
|
|
3832
|
+
let sharedSecret;
|
|
3833
|
+
try {
|
|
3834
|
+
sharedSecret = secp256k1.getSharedSecret(hexToBytes(privateKey), opts.ephemPublicKey, true).slice(1);
|
|
3835
|
+
}
|
|
3836
|
+
catch (e) {
|
|
3837
|
+
throw new Error(`Invalid MAC: data integrity check failed: ${e}`);
|
|
3838
|
+
}
|
|
3839
|
+
const hash = sha512(sharedSecret);
|
|
3840
|
+
const encryptionKey = hash.subarray(0, 32);
|
|
3841
|
+
const macKey = hash.subarray(32);
|
|
3842
|
+
const ciphertext = hexToBytes(opts.ciphertext);
|
|
3843
|
+
const iv = hexToBytes(opts.iv);
|
|
3844
|
+
const ephemPublicKey = hexToBytes(opts.ephemPublicKey);
|
|
3845
|
+
const receivedMac = hexToBytes(opts.mac);
|
|
3846
|
+
// Recompute MAC
|
|
3847
|
+
const dataToMac = concatUint8Arrays([iv, ephemPublicKey, ciphertext]);
|
|
3848
|
+
const expectedMac = hmacSha256Sign(macKey, dataToMac);
|
|
3849
|
+
if (!constantTimeEqual(expectedMac, receivedMac)) {
|
|
3850
|
+
throw new Error('Invalid MAC: data integrity check failed');
|
|
3851
|
+
}
|
|
3852
|
+
const decrypted = decrypt$1(ciphertext, encryptionKey, iv, 'aes-256-cbc');
|
|
3853
|
+
return bytesToUtf8(decrypted);
|
|
3854
|
+
};
|
|
3855
|
+
/**
|
|
3856
|
+
* Compares two Uint8Arrays in constant time to prevent timing attacks.
|
|
3857
|
+
* @param {Uint8Array} a - The first array.
|
|
3858
|
+
* @param {Uint8Array} b - The second array.
|
|
3859
|
+
* @returns {boolean} True if the arrays are equal, false otherwise.
|
|
3860
|
+
*/
|
|
3861
|
+
function constantTimeEqual(a, b) {
|
|
3862
|
+
if (a.length !== b.length)
|
|
3863
|
+
return false;
|
|
3864
|
+
let result = 0;
|
|
3865
|
+
for (let i = 0; i < a.length; i++) {
|
|
3866
|
+
result |= a[i] ^ b[i];
|
|
3867
|
+
}
|
|
3868
|
+
return result === 0;
|
|
3869
|
+
}
|
|
3870
|
+
|
|
3871
|
+
const decryptWithPrivateKey = (privateKey, encrypted) => {
|
|
3872
|
+
// remove '0x' from privateKey
|
|
3873
|
+
const twoStripped = stripHexPrefix(privateKey);
|
|
3874
|
+
return decrypt(twoStripped, encrypted);
|
|
3875
|
+
};
|
|
145
3876
|
|
|
146
3877
|
/**
|
|
147
3878
|
* Generate publicKey from the privateKey.
|
|
148
3879
|
* This creates the uncompressed publicKey,
|
|
149
3880
|
* where 04 has stripped from left
|
|
150
|
-
* @param {string} privateKey
|
|
151
3881
|
* @returns {string}
|
|
152
3882
|
*/
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
const
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
const MIN_ENTROPY_SIZE = 128;
|
|
3883
|
+
const publicKeyByPrivateKey = (privateKey) => {
|
|
3884
|
+
const key = stripHexPrefix(privateKey);
|
|
3885
|
+
const compressedPub = secp256k1.getPublicKey(key); // defaults to compressed format
|
|
3886
|
+
const point = secp256k1.ProjectivePoint.fromHex(compressedPub); // decompress the pub into an EC point
|
|
3887
|
+
return decompress(bytesToHex(point.toRawBytes(false))); // Get uncompressed SEC1 format pub
|
|
3888
|
+
};
|
|
160
3889
|
|
|
3890
|
+
const DEFAULT_ENTROPY_BYTES = 32;
|
|
3891
|
+
const MINIMUM_SHANNON_ENTROPY = 4;
|
|
161
3892
|
/**
|
|
162
|
-
*
|
|
163
|
-
* @param
|
|
164
|
-
* @
|
|
3893
|
+
* creates a new private key
|
|
3894
|
+
* @param { Uint8Array } entropy - optional entropy to create the private key
|
|
3895
|
+
* @returns a new private key
|
|
165
3896
|
*/
|
|
166
|
-
|
|
3897
|
+
const createPrivateKey = (entropy) => {
|
|
167
3898
|
if (entropy) {
|
|
168
|
-
if (!
|
|
169
|
-
throw new Error(
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
const
|
|
173
|
-
|
|
3899
|
+
if (!(entropy instanceof Uint8Array) || entropy.length < DEFAULT_ENTROPY_BYTES) {
|
|
3900
|
+
throw new Error(`entropy must be a Uint8Array of at least ${DEFAULT_ENTROPY_BYTES} bytes`);
|
|
3901
|
+
}
|
|
3902
|
+
// Check byte diversity
|
|
3903
|
+
const uniqueBytes = new Set(entropy);
|
|
3904
|
+
if (uniqueBytes.size < Math.min(8, entropy.length / 4)) {
|
|
3905
|
+
throw new Error(`entropy is too repetitive (only ${uniqueBytes.size} unique byte values)`);
|
|
3906
|
+
}
|
|
3907
|
+
// Estimate Shannon entropy
|
|
3908
|
+
const byteCounts = new Uint32Array(256);
|
|
3909
|
+
entropy.forEach((b) => byteCounts[b]++);
|
|
3910
|
+
const total = entropy.length;
|
|
3911
|
+
let shannonEntropy = 0;
|
|
3912
|
+
for (let i = 0; i < 256; i++) {
|
|
3913
|
+
if (byteCounts[i] > 0) {
|
|
3914
|
+
const p = byteCounts[i] / total;
|
|
3915
|
+
shannonEntropy -= p * Math.log2(p);
|
|
3916
|
+
}
|
|
3917
|
+
}
|
|
3918
|
+
if (shannonEntropy < MINIMUM_SHANNON_ENTROPY) {
|
|
3919
|
+
throw new Error(`entropy has low Shannon entropy (${shannonEntropy.toFixed(2)} bits/byte)`);
|
|
3920
|
+
}
|
|
3921
|
+
const outerHex = keccak256$1(entropy);
|
|
3922
|
+
return addLeading0x(bytesToHex(outerHex));
|
|
174
3923
|
}
|
|
175
3924
|
else {
|
|
176
|
-
const innerHex =
|
|
177
|
-
const middleHex =
|
|
178
|
-
const outerHex =
|
|
179
|
-
return outerHex;
|
|
3925
|
+
const innerHex = keccak256$1(concatUint8Arrays([getRandomBytesSync(32), getRandomBytesSync(32)]));
|
|
3926
|
+
const middleHex = concatUint8Arrays([concatUint8Arrays([getRandomBytesSync(32), innerHex]), getRandomBytesSync(32)]);
|
|
3927
|
+
const outerHex = keccak256$1(middleHex);
|
|
3928
|
+
return addLeading0x(bytesToHex(outerHex));
|
|
180
3929
|
}
|
|
181
|
-
}
|
|
3930
|
+
};
|
|
182
3931
|
/**
|
|
183
|
-
* creates a new
|
|
184
|
-
*
|
|
185
|
-
* @
|
|
3932
|
+
* creates a new identity
|
|
3933
|
+
* @param { Uint8Array } entropy - optional entropy to create the private key
|
|
3934
|
+
* @returns a new pair of private and public key
|
|
186
3935
|
*/
|
|
187
|
-
|
|
3936
|
+
const createIdentity = (entropy) => {
|
|
188
3937
|
const privateKey = createPrivateKey(entropy);
|
|
189
|
-
const
|
|
3938
|
+
const walletPublicKey = publicKeyByPrivateKey(privateKey);
|
|
190
3939
|
const identity = {
|
|
191
3940
|
privateKey: privateKey,
|
|
192
|
-
publicKey:
|
|
193
|
-
address: wallet.address,
|
|
3941
|
+
publicKey: stripHexPrefix(walletPublicKey),
|
|
194
3942
|
};
|
|
195
3943
|
return identity;
|
|
196
|
-
}
|
|
3944
|
+
};
|
|
197
3945
|
|
|
198
|
-
exports.
|
|
199
|
-
exports.
|
|
200
|
-
exports.
|
|
201
|
-
exports.
|
|
3946
|
+
exports.DEFAULT_ENTROPY_BYTES = DEFAULT_ENTROPY_BYTES;
|
|
3947
|
+
exports.MINIMUM_SHANNON_ENTROPY = MINIMUM_SHANNON_ENTROPY;
|
|
3948
|
+
exports.MIN_ENTROPY_SIZE = MIN_ENTROPY_SIZE;
|
|
3949
|
+
exports.SIGN_PREFIX = SIGN_PREFIX;
|
|
202
3950
|
exports.createIdentity = createIdentity;
|
|
203
3951
|
exports.createPrivateKey = createPrivateKey;
|
|
204
|
-
exports.decompress = decompress;
|
|
205
3952
|
exports.decryptWithPrivateKey = decryptWithPrivateKey;
|
|
206
|
-
exports.
|
|
207
|
-
exports.
|
|
3953
|
+
exports.hmacSha256Sign = hmacSha256Sign;
|
|
3954
|
+
exports.keccak256 = keccak256;
|
|
208
3955
|
exports.publicKeyByPrivateKey = publicKeyByPrivateKey;
|
|
209
|
-
exports.removeLeading0x = removeLeading0x;
|
|
210
3956
|
exports.sign = sign;
|
|
211
|
-
exports.uint8ArrayToHex = uint8ArrayToHex;
|
|
212
3957
|
//# sourceMappingURL=index.cjs.js.map
|