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