@leofcoin/chain 1.4.36 → 1.4.38

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (30) hide show
  1. package/exports/browser/chain.js +135 -4326
  2. package/exports/browser/client-de444350-a666f9b6.js +41075 -0
  3. package/exports/browser/contract-32687834.js +6071 -0
  4. package/exports/browser/{index-1ce30988-44319c80.js → index-712688fc-ad40bdec.js} +2 -2
  5. package/exports/browser/{messages-e025829d-a0354268.js → messages-3f370680-fb7e5b5b.js} +2 -2
  6. package/exports/browser/{node-browser-13cbe71a.js → node-browser-bd6a5de3.js} +4290 -187
  7. package/exports/browser/node-browser.js +2 -2
  8. package/exports/browser/workers/block-worker.js +6069 -0
  9. package/exports/browser/workers/machine-worker.js +6279 -0
  10. package/exports/chain.js +117 -96
  11. package/exports/node.js +2 -1
  12. package/exports/typings/chain.d.ts +5 -2
  13. package/exports/typings/contract.d.ts +1 -0
  14. package/exports/typings/node.d.ts +1 -0
  15. package/exports/typings/transaction.d.ts +1 -1
  16. package/package.json +4 -2
  17. package/exports/browser/browser-10ffabe1-10ffabe1.js +0 -56
  18. package/exports/browser/browser-e1cd4e67-e1cd4e67.js +0 -198
  19. package/exports/browser/client-111c93a3-b0dcdc19.js +0 -612
  20. package/exports/browser/client-1d0234a7-df40059a.js +0 -624
  21. package/exports/browser/client-21cee984-77440b6b.js +0 -624
  22. package/exports/browser/contract-163f031f.js +0 -1859
  23. package/exports/browser/index-3d3f56ca-064d16ce.js +0 -37
  24. package/exports/browser/index-543bc6a3-be806e11.js +0 -37
  25. package/exports/browser/messages-48deb2c3-73e8ace1.js +0 -205
  26. package/exports/browser/messages-af41e873-479a93a8.js +0 -205
  27. package/exports/browser/node-browser-63c7cb33.js +0 -16877
  28. package/exports/browser/node-browser-64b82fc8.js +0 -16877
  29. package/exports/browser/pako.esm-aa674ebf-aa674ebf.js +0 -6876
  30. package/exports/browser/simple-peer-743c19fe-03a0830e.js +0 -7856
@@ -1,4209 +1,4 @@
1
- import { C as ContractMessage, T as TransactionMessage, a as CodecHash, B as BlockMessage, b as BWMessage, c as BWRequestMessage } from './contract-163f031f.js';
2
-
3
- var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
4
-
5
- function getAugmentedNamespace(n) {
6
- if (n.__esModule) return n;
7
- var f = n.default;
8
- if (typeof f == "function") {
9
- var a = function a () {
10
- if (this instanceof a) {
11
- var args = [null];
12
- args.push.apply(args, arguments);
13
- var Ctor = Function.bind.apply(f, args);
14
- return new Ctor();
15
- }
16
- return f.apply(this, arguments);
17
- };
18
- a.prototype = f.prototype;
19
- } else a = {};
20
- Object.defineProperty(a, '__esModule', {value: true});
21
- Object.keys(n).forEach(function (k) {
22
- var d = Object.getOwnPropertyDescriptor(n, k);
23
- Object.defineProperty(a, k, d.get ? d : {
24
- enumerable: true,
25
- get: function () {
26
- return n[k];
27
- }
28
- });
29
- });
30
- return a;
31
- }
32
-
33
- var bnExports = {};
34
- var bn = {
35
- get exports(){ return bnExports; },
36
- set exports(v){ bnExports = v; },
37
- };
38
-
39
- var _nodeResolve_empty = {};
40
-
41
- var _nodeResolve_empty$1 = /*#__PURE__*/Object.freeze({
42
- __proto__: null,
43
- default: _nodeResolve_empty
44
- });
45
-
46
- var require$$0 = /*@__PURE__*/getAugmentedNamespace(_nodeResolve_empty$1);
47
-
48
- (function (module) {
49
- (function (module, exports) {
50
-
51
- // Utils
52
- function assert (val, msg) {
53
- if (!val) throw new Error(msg || 'Assertion failed');
54
- }
55
-
56
- // Could use `inherits` module, but don't want to move from single file
57
- // architecture yet.
58
- function inherits (ctor, superCtor) {
59
- ctor.super_ = superCtor;
60
- var TempCtor = function () {};
61
- TempCtor.prototype = superCtor.prototype;
62
- ctor.prototype = new TempCtor();
63
- ctor.prototype.constructor = ctor;
64
- }
65
-
66
- // BN
67
-
68
- function BN (number, base, endian) {
69
- if (BN.isBN(number)) {
70
- return number;
71
- }
72
-
73
- this.negative = 0;
74
- this.words = null;
75
- this.length = 0;
76
-
77
- // Reduction context
78
- this.red = null;
79
-
80
- if (number !== null) {
81
- if (base === 'le' || base === 'be') {
82
- endian = base;
83
- base = 10;
84
- }
85
-
86
- this._init(number || 0, base || 10, endian || 'be');
87
- }
88
- }
89
- if (typeof module === 'object') {
90
- module.exports = BN;
91
- } else {
92
- exports.BN = BN;
93
- }
94
-
95
- BN.BN = BN;
96
- BN.wordSize = 26;
97
-
98
- var Buffer;
99
- try {
100
- if (typeof window !== 'undefined' && typeof window.Buffer !== 'undefined') {
101
- Buffer = window.Buffer;
102
- } else {
103
- Buffer = require$$0.Buffer;
104
- }
105
- } catch (e) {
106
- }
107
-
108
- BN.isBN = function isBN (num) {
109
- if (num instanceof BN) {
110
- return true;
111
- }
112
-
113
- return num !== null && typeof num === 'object' &&
114
- num.constructor.wordSize === BN.wordSize && Array.isArray(num.words);
115
- };
116
-
117
- BN.max = function max (left, right) {
118
- if (left.cmp(right) > 0) return left;
119
- return right;
120
- };
121
-
122
- BN.min = function min (left, right) {
123
- if (left.cmp(right) < 0) return left;
124
- return right;
125
- };
126
-
127
- BN.prototype._init = function init (number, base, endian) {
128
- if (typeof number === 'number') {
129
- return this._initNumber(number, base, endian);
130
- }
131
-
132
- if (typeof number === 'object') {
133
- return this._initArray(number, base, endian);
134
- }
135
-
136
- if (base === 'hex') {
137
- base = 16;
138
- }
139
- assert(base === (base | 0) && base >= 2 && base <= 36);
140
-
141
- number = number.toString().replace(/\s+/g, '');
142
- var start = 0;
143
- if (number[0] === '-') {
144
- start++;
145
- this.negative = 1;
146
- }
147
-
148
- if (start < number.length) {
149
- if (base === 16) {
150
- this._parseHex(number, start, endian);
151
- } else {
152
- this._parseBase(number, base, start);
153
- if (endian === 'le') {
154
- this._initArray(this.toArray(), base, endian);
155
- }
156
- }
157
- }
158
- };
159
-
160
- BN.prototype._initNumber = function _initNumber (number, base, endian) {
161
- if (number < 0) {
162
- this.negative = 1;
163
- number = -number;
164
- }
165
- if (number < 0x4000000) {
166
- this.words = [number & 0x3ffffff];
167
- this.length = 1;
168
- } else if (number < 0x10000000000000) {
169
- this.words = [
170
- number & 0x3ffffff,
171
- (number / 0x4000000) & 0x3ffffff
172
- ];
173
- this.length = 2;
174
- } else {
175
- assert(number < 0x20000000000000); // 2 ^ 53 (unsafe)
176
- this.words = [
177
- number & 0x3ffffff,
178
- (number / 0x4000000) & 0x3ffffff,
179
- 1
180
- ];
181
- this.length = 3;
182
- }
183
-
184
- if (endian !== 'le') return;
185
-
186
- // Reverse the bytes
187
- this._initArray(this.toArray(), base, endian);
188
- };
189
-
190
- BN.prototype._initArray = function _initArray (number, base, endian) {
191
- // Perhaps a Uint8Array
192
- assert(typeof number.length === 'number');
193
- if (number.length <= 0) {
194
- this.words = [0];
195
- this.length = 1;
196
- return this;
197
- }
198
-
199
- this.length = Math.ceil(number.length / 3);
200
- this.words = new Array(this.length);
201
- for (var i = 0; i < this.length; i++) {
202
- this.words[i] = 0;
203
- }
204
-
205
- var j, w;
206
- var off = 0;
207
- if (endian === 'be') {
208
- for (i = number.length - 1, j = 0; i >= 0; i -= 3) {
209
- w = number[i] | (number[i - 1] << 8) | (number[i - 2] << 16);
210
- this.words[j] |= (w << off) & 0x3ffffff;
211
- this.words[j + 1] = (w >>> (26 - off)) & 0x3ffffff;
212
- off += 24;
213
- if (off >= 26) {
214
- off -= 26;
215
- j++;
216
- }
217
- }
218
- } else if (endian === 'le') {
219
- for (i = 0, j = 0; i < number.length; i += 3) {
220
- w = number[i] | (number[i + 1] << 8) | (number[i + 2] << 16);
221
- this.words[j] |= (w << off) & 0x3ffffff;
222
- this.words[j + 1] = (w >>> (26 - off)) & 0x3ffffff;
223
- off += 24;
224
- if (off >= 26) {
225
- off -= 26;
226
- j++;
227
- }
228
- }
229
- }
230
- return this._strip();
231
- };
232
-
233
- function parseHex4Bits (string, index) {
234
- var c = string.charCodeAt(index);
235
- // '0' - '9'
236
- if (c >= 48 && c <= 57) {
237
- return c - 48;
238
- // 'A' - 'F'
239
- } else if (c >= 65 && c <= 70) {
240
- return c - 55;
241
- // 'a' - 'f'
242
- } else if (c >= 97 && c <= 102) {
243
- return c - 87;
244
- } else {
245
- assert(false, 'Invalid character in ' + string);
246
- }
247
- }
248
-
249
- function parseHexByte (string, lowerBound, index) {
250
- var r = parseHex4Bits(string, index);
251
- if (index - 1 >= lowerBound) {
252
- r |= parseHex4Bits(string, index - 1) << 4;
253
- }
254
- return r;
255
- }
256
-
257
- BN.prototype._parseHex = function _parseHex (number, start, endian) {
258
- // Create possibly bigger array to ensure that it fits the number
259
- this.length = Math.ceil((number.length - start) / 6);
260
- this.words = new Array(this.length);
261
- for (var i = 0; i < this.length; i++) {
262
- this.words[i] = 0;
263
- }
264
-
265
- // 24-bits chunks
266
- var off = 0;
267
- var j = 0;
268
-
269
- var w;
270
- if (endian === 'be') {
271
- for (i = number.length - 1; i >= start; i -= 2) {
272
- w = parseHexByte(number, start, i) << off;
273
- this.words[j] |= w & 0x3ffffff;
274
- if (off >= 18) {
275
- off -= 18;
276
- j += 1;
277
- this.words[j] |= w >>> 26;
278
- } else {
279
- off += 8;
280
- }
281
- }
282
- } else {
283
- var parseLength = number.length - start;
284
- for (i = parseLength % 2 === 0 ? start + 1 : start; i < number.length; i += 2) {
285
- w = parseHexByte(number, start, i) << off;
286
- this.words[j] |= w & 0x3ffffff;
287
- if (off >= 18) {
288
- off -= 18;
289
- j += 1;
290
- this.words[j] |= w >>> 26;
291
- } else {
292
- off += 8;
293
- }
294
- }
295
- }
296
-
297
- this._strip();
298
- };
299
-
300
- function parseBase (str, start, end, mul) {
301
- var r = 0;
302
- var b = 0;
303
- var len = Math.min(str.length, end);
304
- for (var i = start; i < len; i++) {
305
- var c = str.charCodeAt(i) - 48;
306
-
307
- r *= mul;
308
-
309
- // 'a'
310
- if (c >= 49) {
311
- b = c - 49 + 0xa;
312
-
313
- // 'A'
314
- } else if (c >= 17) {
315
- b = c - 17 + 0xa;
316
-
317
- // '0' - '9'
318
- } else {
319
- b = c;
320
- }
321
- assert(c >= 0 && b < mul, 'Invalid character');
322
- r += b;
323
- }
324
- return r;
325
- }
326
-
327
- BN.prototype._parseBase = function _parseBase (number, base, start) {
328
- // Initialize as zero
329
- this.words = [0];
330
- this.length = 1;
331
-
332
- // Find length of limb in base
333
- for (var limbLen = 0, limbPow = 1; limbPow <= 0x3ffffff; limbPow *= base) {
334
- limbLen++;
335
- }
336
- limbLen--;
337
- limbPow = (limbPow / base) | 0;
338
-
339
- var total = number.length - start;
340
- var mod = total % limbLen;
341
- var end = Math.min(total, total - mod) + start;
342
-
343
- var word = 0;
344
- for (var i = start; i < end; i += limbLen) {
345
- word = parseBase(number, i, i + limbLen, base);
346
-
347
- this.imuln(limbPow);
348
- if (this.words[0] + word < 0x4000000) {
349
- this.words[0] += word;
350
- } else {
351
- this._iaddn(word);
352
- }
353
- }
354
-
355
- if (mod !== 0) {
356
- var pow = 1;
357
- word = parseBase(number, i, number.length, base);
358
-
359
- for (i = 0; i < mod; i++) {
360
- pow *= base;
361
- }
362
-
363
- this.imuln(pow);
364
- if (this.words[0] + word < 0x4000000) {
365
- this.words[0] += word;
366
- } else {
367
- this._iaddn(word);
368
- }
369
- }
370
-
371
- this._strip();
372
- };
373
-
374
- BN.prototype.copy = function copy (dest) {
375
- dest.words = new Array(this.length);
376
- for (var i = 0; i < this.length; i++) {
377
- dest.words[i] = this.words[i];
378
- }
379
- dest.length = this.length;
380
- dest.negative = this.negative;
381
- dest.red = this.red;
382
- };
383
-
384
- function move (dest, src) {
385
- dest.words = src.words;
386
- dest.length = src.length;
387
- dest.negative = src.negative;
388
- dest.red = src.red;
389
- }
390
-
391
- BN.prototype._move = function _move (dest) {
392
- move(dest, this);
393
- };
394
-
395
- BN.prototype.clone = function clone () {
396
- var r = new BN(null);
397
- this.copy(r);
398
- return r;
399
- };
400
-
401
- BN.prototype._expand = function _expand (size) {
402
- while (this.length < size) {
403
- this.words[this.length++] = 0;
404
- }
405
- return this;
406
- };
407
-
408
- // Remove leading `0` from `this`
409
- BN.prototype._strip = function strip () {
410
- while (this.length > 1 && this.words[this.length - 1] === 0) {
411
- this.length--;
412
- }
413
- return this._normSign();
414
- };
415
-
416
- BN.prototype._normSign = function _normSign () {
417
- // -0 = 0
418
- if (this.length === 1 && this.words[0] === 0) {
419
- this.negative = 0;
420
- }
421
- return this;
422
- };
423
-
424
- // Check Symbol.for because not everywhere where Symbol defined
425
- // See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol#Browser_compatibility
426
- if (typeof Symbol !== 'undefined' && typeof Symbol.for === 'function') {
427
- try {
428
- BN.prototype[Symbol.for('nodejs.util.inspect.custom')] = inspect;
429
- } catch (e) {
430
- BN.prototype.inspect = inspect;
431
- }
432
- } else {
433
- BN.prototype.inspect = inspect;
434
- }
435
-
436
- function inspect () {
437
- return (this.red ? '<BN-R: ' : '<BN: ') + this.toString(16) + '>';
438
- }
439
-
440
- /*
441
-
442
- var zeros = [];
443
- var groupSizes = [];
444
- var groupBases = [];
445
-
446
- var s = '';
447
- var i = -1;
448
- while (++i < BN.wordSize) {
449
- zeros[i] = s;
450
- s += '0';
451
- }
452
- groupSizes[0] = 0;
453
- groupSizes[1] = 0;
454
- groupBases[0] = 0;
455
- groupBases[1] = 0;
456
- var base = 2 - 1;
457
- while (++base < 36 + 1) {
458
- var groupSize = 0;
459
- var groupBase = 1;
460
- while (groupBase < (1 << BN.wordSize) / base) {
461
- groupBase *= base;
462
- groupSize += 1;
463
- }
464
- groupSizes[base] = groupSize;
465
- groupBases[base] = groupBase;
466
- }
467
-
468
- */
469
-
470
- var zeros = [
471
- '',
472
- '0',
473
- '00',
474
- '000',
475
- '0000',
476
- '00000',
477
- '000000',
478
- '0000000',
479
- '00000000',
480
- '000000000',
481
- '0000000000',
482
- '00000000000',
483
- '000000000000',
484
- '0000000000000',
485
- '00000000000000',
486
- '000000000000000',
487
- '0000000000000000',
488
- '00000000000000000',
489
- '000000000000000000',
490
- '0000000000000000000',
491
- '00000000000000000000',
492
- '000000000000000000000',
493
- '0000000000000000000000',
494
- '00000000000000000000000',
495
- '000000000000000000000000',
496
- '0000000000000000000000000'
497
- ];
498
-
499
- var groupSizes = [
500
- 0, 0,
501
- 25, 16, 12, 11, 10, 9, 8,
502
- 8, 7, 7, 7, 7, 6, 6,
503
- 6, 6, 6, 6, 6, 5, 5,
504
- 5, 5, 5, 5, 5, 5, 5,
505
- 5, 5, 5, 5, 5, 5, 5
506
- ];
507
-
508
- var groupBases = [
509
- 0, 0,
510
- 33554432, 43046721, 16777216, 48828125, 60466176, 40353607, 16777216,
511
- 43046721, 10000000, 19487171, 35831808, 62748517, 7529536, 11390625,
512
- 16777216, 24137569, 34012224, 47045881, 64000000, 4084101, 5153632,
513
- 6436343, 7962624, 9765625, 11881376, 14348907, 17210368, 20511149,
514
- 24300000, 28629151, 33554432, 39135393, 45435424, 52521875, 60466176
515
- ];
516
-
517
- BN.prototype.toString = function toString (base, padding) {
518
- base = base || 10;
519
- padding = padding | 0 || 1;
520
-
521
- var out;
522
- if (base === 16 || base === 'hex') {
523
- out = '';
524
- var off = 0;
525
- var carry = 0;
526
- for (var i = 0; i < this.length; i++) {
527
- var w = this.words[i];
528
- var word = (((w << off) | carry) & 0xffffff).toString(16);
529
- carry = (w >>> (24 - off)) & 0xffffff;
530
- off += 2;
531
- if (off >= 26) {
532
- off -= 26;
533
- i--;
534
- }
535
- if (carry !== 0 || i !== this.length - 1) {
536
- out = zeros[6 - word.length] + word + out;
537
- } else {
538
- out = word + out;
539
- }
540
- }
541
- if (carry !== 0) {
542
- out = carry.toString(16) + out;
543
- }
544
- while (out.length % padding !== 0) {
545
- out = '0' + out;
546
- }
547
- if (this.negative !== 0) {
548
- out = '-' + out;
549
- }
550
- return out;
551
- }
552
-
553
- if (base === (base | 0) && base >= 2 && base <= 36) {
554
- // var groupSize = Math.floor(BN.wordSize * Math.LN2 / Math.log(base));
555
- var groupSize = groupSizes[base];
556
- // var groupBase = Math.pow(base, groupSize);
557
- var groupBase = groupBases[base];
558
- out = '';
559
- var c = this.clone();
560
- c.negative = 0;
561
- while (!c.isZero()) {
562
- var r = c.modrn(groupBase).toString(base);
563
- c = c.idivn(groupBase);
564
-
565
- if (!c.isZero()) {
566
- out = zeros[groupSize - r.length] + r + out;
567
- } else {
568
- out = r + out;
569
- }
570
- }
571
- if (this.isZero()) {
572
- out = '0' + out;
573
- }
574
- while (out.length % padding !== 0) {
575
- out = '0' + out;
576
- }
577
- if (this.negative !== 0) {
578
- out = '-' + out;
579
- }
580
- return out;
581
- }
582
-
583
- assert(false, 'Base should be between 2 and 36');
584
- };
585
-
586
- BN.prototype.toNumber = function toNumber () {
587
- var ret = this.words[0];
588
- if (this.length === 2) {
589
- ret += this.words[1] * 0x4000000;
590
- } else if (this.length === 3 && this.words[2] === 0x01) {
591
- // NOTE: at this stage it is known that the top bit is set
592
- ret += 0x10000000000000 + (this.words[1] * 0x4000000);
593
- } else if (this.length > 2) {
594
- assert(false, 'Number can only safely store up to 53 bits');
595
- }
596
- return (this.negative !== 0) ? -ret : ret;
597
- };
598
-
599
- BN.prototype.toJSON = function toJSON () {
600
- return this.toString(16, 2);
601
- };
602
-
603
- if (Buffer) {
604
- BN.prototype.toBuffer = function toBuffer (endian, length) {
605
- return this.toArrayLike(Buffer, endian, length);
606
- };
607
- }
608
-
609
- BN.prototype.toArray = function toArray (endian, length) {
610
- return this.toArrayLike(Array, endian, length);
611
- };
612
-
613
- var allocate = function allocate (ArrayType, size) {
614
- if (ArrayType.allocUnsafe) {
615
- return ArrayType.allocUnsafe(size);
616
- }
617
- return new ArrayType(size);
618
- };
619
-
620
- BN.prototype.toArrayLike = function toArrayLike (ArrayType, endian, length) {
621
- this._strip();
622
-
623
- var byteLength = this.byteLength();
624
- var reqLength = length || Math.max(1, byteLength);
625
- assert(byteLength <= reqLength, 'byte array longer than desired length');
626
- assert(reqLength > 0, 'Requested array length <= 0');
627
-
628
- var res = allocate(ArrayType, reqLength);
629
- var postfix = endian === 'le' ? 'LE' : 'BE';
630
- this['_toArrayLike' + postfix](res, byteLength);
631
- return res;
632
- };
633
-
634
- BN.prototype._toArrayLikeLE = function _toArrayLikeLE (res, byteLength) {
635
- var position = 0;
636
- var carry = 0;
637
-
638
- for (var i = 0, shift = 0; i < this.length; i++) {
639
- var word = (this.words[i] << shift) | carry;
640
-
641
- res[position++] = word & 0xff;
642
- if (position < res.length) {
643
- res[position++] = (word >> 8) & 0xff;
644
- }
645
- if (position < res.length) {
646
- res[position++] = (word >> 16) & 0xff;
647
- }
648
-
649
- if (shift === 6) {
650
- if (position < res.length) {
651
- res[position++] = (word >> 24) & 0xff;
652
- }
653
- carry = 0;
654
- shift = 0;
655
- } else {
656
- carry = word >>> 24;
657
- shift += 2;
658
- }
659
- }
660
-
661
- if (position < res.length) {
662
- res[position++] = carry;
663
-
664
- while (position < res.length) {
665
- res[position++] = 0;
666
- }
667
- }
668
- };
669
-
670
- BN.prototype._toArrayLikeBE = function _toArrayLikeBE (res, byteLength) {
671
- var position = res.length - 1;
672
- var carry = 0;
673
-
674
- for (var i = 0, shift = 0; i < this.length; i++) {
675
- var word = (this.words[i] << shift) | carry;
676
-
677
- res[position--] = word & 0xff;
678
- if (position >= 0) {
679
- res[position--] = (word >> 8) & 0xff;
680
- }
681
- if (position >= 0) {
682
- res[position--] = (word >> 16) & 0xff;
683
- }
684
-
685
- if (shift === 6) {
686
- if (position >= 0) {
687
- res[position--] = (word >> 24) & 0xff;
688
- }
689
- carry = 0;
690
- shift = 0;
691
- } else {
692
- carry = word >>> 24;
693
- shift += 2;
694
- }
695
- }
696
-
697
- if (position >= 0) {
698
- res[position--] = carry;
699
-
700
- while (position >= 0) {
701
- res[position--] = 0;
702
- }
703
- }
704
- };
705
-
706
- if (Math.clz32) {
707
- BN.prototype._countBits = function _countBits (w) {
708
- return 32 - Math.clz32(w);
709
- };
710
- } else {
711
- BN.prototype._countBits = function _countBits (w) {
712
- var t = w;
713
- var r = 0;
714
- if (t >= 0x1000) {
715
- r += 13;
716
- t >>>= 13;
717
- }
718
- if (t >= 0x40) {
719
- r += 7;
720
- t >>>= 7;
721
- }
722
- if (t >= 0x8) {
723
- r += 4;
724
- t >>>= 4;
725
- }
726
- if (t >= 0x02) {
727
- r += 2;
728
- t >>>= 2;
729
- }
730
- return r + t;
731
- };
732
- }
733
-
734
- BN.prototype._zeroBits = function _zeroBits (w) {
735
- // Short-cut
736
- if (w === 0) return 26;
737
-
738
- var t = w;
739
- var r = 0;
740
- if ((t & 0x1fff) === 0) {
741
- r += 13;
742
- t >>>= 13;
743
- }
744
- if ((t & 0x7f) === 0) {
745
- r += 7;
746
- t >>>= 7;
747
- }
748
- if ((t & 0xf) === 0) {
749
- r += 4;
750
- t >>>= 4;
751
- }
752
- if ((t & 0x3) === 0) {
753
- r += 2;
754
- t >>>= 2;
755
- }
756
- if ((t & 0x1) === 0) {
757
- r++;
758
- }
759
- return r;
760
- };
761
-
762
- // Return number of used bits in a BN
763
- BN.prototype.bitLength = function bitLength () {
764
- var w = this.words[this.length - 1];
765
- var hi = this._countBits(w);
766
- return (this.length - 1) * 26 + hi;
767
- };
768
-
769
- function toBitArray (num) {
770
- var w = new Array(num.bitLength());
771
-
772
- for (var bit = 0; bit < w.length; bit++) {
773
- var off = (bit / 26) | 0;
774
- var wbit = bit % 26;
775
-
776
- w[bit] = (num.words[off] >>> wbit) & 0x01;
777
- }
778
-
779
- return w;
780
- }
781
-
782
- // Number of trailing zero bits
783
- BN.prototype.zeroBits = function zeroBits () {
784
- if (this.isZero()) return 0;
785
-
786
- var r = 0;
787
- for (var i = 0; i < this.length; i++) {
788
- var b = this._zeroBits(this.words[i]);
789
- r += b;
790
- if (b !== 26) break;
791
- }
792
- return r;
793
- };
794
-
795
- BN.prototype.byteLength = function byteLength () {
796
- return Math.ceil(this.bitLength() / 8);
797
- };
798
-
799
- BN.prototype.toTwos = function toTwos (width) {
800
- if (this.negative !== 0) {
801
- return this.abs().inotn(width).iaddn(1);
802
- }
803
- return this.clone();
804
- };
805
-
806
- BN.prototype.fromTwos = function fromTwos (width) {
807
- if (this.testn(width - 1)) {
808
- return this.notn(width).iaddn(1).ineg();
809
- }
810
- return this.clone();
811
- };
812
-
813
- BN.prototype.isNeg = function isNeg () {
814
- return this.negative !== 0;
815
- };
816
-
817
- // Return negative clone of `this`
818
- BN.prototype.neg = function neg () {
819
- return this.clone().ineg();
820
- };
821
-
822
- BN.prototype.ineg = function ineg () {
823
- if (!this.isZero()) {
824
- this.negative ^= 1;
825
- }
826
-
827
- return this;
828
- };
829
-
830
- // Or `num` with `this` in-place
831
- BN.prototype.iuor = function iuor (num) {
832
- while (this.length < num.length) {
833
- this.words[this.length++] = 0;
834
- }
835
-
836
- for (var i = 0; i < num.length; i++) {
837
- this.words[i] = this.words[i] | num.words[i];
838
- }
839
-
840
- return this._strip();
841
- };
842
-
843
- BN.prototype.ior = function ior (num) {
844
- assert((this.negative | num.negative) === 0);
845
- return this.iuor(num);
846
- };
847
-
848
- // Or `num` with `this`
849
- BN.prototype.or = function or (num) {
850
- if (this.length > num.length) return this.clone().ior(num);
851
- return num.clone().ior(this);
852
- };
853
-
854
- BN.prototype.uor = function uor (num) {
855
- if (this.length > num.length) return this.clone().iuor(num);
856
- return num.clone().iuor(this);
857
- };
858
-
859
- // And `num` with `this` in-place
860
- BN.prototype.iuand = function iuand (num) {
861
- // b = min-length(num, this)
862
- var b;
863
- if (this.length > num.length) {
864
- b = num;
865
- } else {
866
- b = this;
867
- }
868
-
869
- for (var i = 0; i < b.length; i++) {
870
- this.words[i] = this.words[i] & num.words[i];
871
- }
872
-
873
- this.length = b.length;
874
-
875
- return this._strip();
876
- };
877
-
878
- BN.prototype.iand = function iand (num) {
879
- assert((this.negative | num.negative) === 0);
880
- return this.iuand(num);
881
- };
882
-
883
- // And `num` with `this`
884
- BN.prototype.and = function and (num) {
885
- if (this.length > num.length) return this.clone().iand(num);
886
- return num.clone().iand(this);
887
- };
888
-
889
- BN.prototype.uand = function uand (num) {
890
- if (this.length > num.length) return this.clone().iuand(num);
891
- return num.clone().iuand(this);
892
- };
893
-
894
- // Xor `num` with `this` in-place
895
- BN.prototype.iuxor = function iuxor (num) {
896
- // a.length > b.length
897
- var a;
898
- var b;
899
- if (this.length > num.length) {
900
- a = this;
901
- b = num;
902
- } else {
903
- a = num;
904
- b = this;
905
- }
906
-
907
- for (var i = 0; i < b.length; i++) {
908
- this.words[i] = a.words[i] ^ b.words[i];
909
- }
910
-
911
- if (this !== a) {
912
- for (; i < a.length; i++) {
913
- this.words[i] = a.words[i];
914
- }
915
- }
916
-
917
- this.length = a.length;
918
-
919
- return this._strip();
920
- };
921
-
922
- BN.prototype.ixor = function ixor (num) {
923
- assert((this.negative | num.negative) === 0);
924
- return this.iuxor(num);
925
- };
926
-
927
- // Xor `num` with `this`
928
- BN.prototype.xor = function xor (num) {
929
- if (this.length > num.length) return this.clone().ixor(num);
930
- return num.clone().ixor(this);
931
- };
932
-
933
- BN.prototype.uxor = function uxor (num) {
934
- if (this.length > num.length) return this.clone().iuxor(num);
935
- return num.clone().iuxor(this);
936
- };
937
-
938
- // Not ``this`` with ``width`` bitwidth
939
- BN.prototype.inotn = function inotn (width) {
940
- assert(typeof width === 'number' && width >= 0);
941
-
942
- var bytesNeeded = Math.ceil(width / 26) | 0;
943
- var bitsLeft = width % 26;
944
-
945
- // Extend the buffer with leading zeroes
946
- this._expand(bytesNeeded);
947
-
948
- if (bitsLeft > 0) {
949
- bytesNeeded--;
950
- }
951
-
952
- // Handle complete words
953
- for (var i = 0; i < bytesNeeded; i++) {
954
- this.words[i] = ~this.words[i] & 0x3ffffff;
955
- }
956
-
957
- // Handle the residue
958
- if (bitsLeft > 0) {
959
- this.words[i] = ~this.words[i] & (0x3ffffff >> (26 - bitsLeft));
960
- }
961
-
962
- // And remove leading zeroes
963
- return this._strip();
964
- };
965
-
966
- BN.prototype.notn = function notn (width) {
967
- return this.clone().inotn(width);
968
- };
969
-
970
- // Set `bit` of `this`
971
- BN.prototype.setn = function setn (bit, val) {
972
- assert(typeof bit === 'number' && bit >= 0);
973
-
974
- var off = (bit / 26) | 0;
975
- var wbit = bit % 26;
976
-
977
- this._expand(off + 1);
978
-
979
- if (val) {
980
- this.words[off] = this.words[off] | (1 << wbit);
981
- } else {
982
- this.words[off] = this.words[off] & ~(1 << wbit);
983
- }
984
-
985
- return this._strip();
986
- };
987
-
988
- // Add `num` to `this` in-place
989
- BN.prototype.iadd = function iadd (num) {
990
- var r;
991
-
992
- // negative + positive
993
- if (this.negative !== 0 && num.negative === 0) {
994
- this.negative = 0;
995
- r = this.isub(num);
996
- this.negative ^= 1;
997
- return this._normSign();
998
-
999
- // positive + negative
1000
- } else if (this.negative === 0 && num.negative !== 0) {
1001
- num.negative = 0;
1002
- r = this.isub(num);
1003
- num.negative = 1;
1004
- return r._normSign();
1005
- }
1006
-
1007
- // a.length > b.length
1008
- var a, b;
1009
- if (this.length > num.length) {
1010
- a = this;
1011
- b = num;
1012
- } else {
1013
- a = num;
1014
- b = this;
1015
- }
1016
-
1017
- var carry = 0;
1018
- for (var i = 0; i < b.length; i++) {
1019
- r = (a.words[i] | 0) + (b.words[i] | 0) + carry;
1020
- this.words[i] = r & 0x3ffffff;
1021
- carry = r >>> 26;
1022
- }
1023
- for (; carry !== 0 && i < a.length; i++) {
1024
- r = (a.words[i] | 0) + carry;
1025
- this.words[i] = r & 0x3ffffff;
1026
- carry = r >>> 26;
1027
- }
1028
-
1029
- this.length = a.length;
1030
- if (carry !== 0) {
1031
- this.words[this.length] = carry;
1032
- this.length++;
1033
- // Copy the rest of the words
1034
- } else if (a !== this) {
1035
- for (; i < a.length; i++) {
1036
- this.words[i] = a.words[i];
1037
- }
1038
- }
1039
-
1040
- return this;
1041
- };
1042
-
1043
- // Add `num` to `this`
1044
- BN.prototype.add = function add (num) {
1045
- var res;
1046
- if (num.negative !== 0 && this.negative === 0) {
1047
- num.negative = 0;
1048
- res = this.sub(num);
1049
- num.negative ^= 1;
1050
- return res;
1051
- } else if (num.negative === 0 && this.negative !== 0) {
1052
- this.negative = 0;
1053
- res = num.sub(this);
1054
- this.negative = 1;
1055
- return res;
1056
- }
1057
-
1058
- if (this.length > num.length) return this.clone().iadd(num);
1059
-
1060
- return num.clone().iadd(this);
1061
- };
1062
-
1063
- // Subtract `num` from `this` in-place
1064
- BN.prototype.isub = function isub (num) {
1065
- // this - (-num) = this + num
1066
- if (num.negative !== 0) {
1067
- num.negative = 0;
1068
- var r = this.iadd(num);
1069
- num.negative = 1;
1070
- return r._normSign();
1071
-
1072
- // -this - num = -(this + num)
1073
- } else if (this.negative !== 0) {
1074
- this.negative = 0;
1075
- this.iadd(num);
1076
- this.negative = 1;
1077
- return this._normSign();
1078
- }
1079
-
1080
- // At this point both numbers are positive
1081
- var cmp = this.cmp(num);
1082
-
1083
- // Optimization - zeroify
1084
- if (cmp === 0) {
1085
- this.negative = 0;
1086
- this.length = 1;
1087
- this.words[0] = 0;
1088
- return this;
1089
- }
1090
-
1091
- // a > b
1092
- var a, b;
1093
- if (cmp > 0) {
1094
- a = this;
1095
- b = num;
1096
- } else {
1097
- a = num;
1098
- b = this;
1099
- }
1100
-
1101
- var carry = 0;
1102
- for (var i = 0; i < b.length; i++) {
1103
- r = (a.words[i] | 0) - (b.words[i] | 0) + carry;
1104
- carry = r >> 26;
1105
- this.words[i] = r & 0x3ffffff;
1106
- }
1107
- for (; carry !== 0 && i < a.length; i++) {
1108
- r = (a.words[i] | 0) + carry;
1109
- carry = r >> 26;
1110
- this.words[i] = r & 0x3ffffff;
1111
- }
1112
-
1113
- // Copy rest of the words
1114
- if (carry === 0 && i < a.length && a !== this) {
1115
- for (; i < a.length; i++) {
1116
- this.words[i] = a.words[i];
1117
- }
1118
- }
1119
-
1120
- this.length = Math.max(this.length, i);
1121
-
1122
- if (a !== this) {
1123
- this.negative = 1;
1124
- }
1125
-
1126
- return this._strip();
1127
- };
1128
-
1129
- // Subtract `num` from `this`
1130
- BN.prototype.sub = function sub (num) {
1131
- return this.clone().isub(num);
1132
- };
1133
-
1134
- function smallMulTo (self, num, out) {
1135
- out.negative = num.negative ^ self.negative;
1136
- var len = (self.length + num.length) | 0;
1137
- out.length = len;
1138
- len = (len - 1) | 0;
1139
-
1140
- // Peel one iteration (compiler can't do it, because of code complexity)
1141
- var a = self.words[0] | 0;
1142
- var b = num.words[0] | 0;
1143
- var r = a * b;
1144
-
1145
- var lo = r & 0x3ffffff;
1146
- var carry = (r / 0x4000000) | 0;
1147
- out.words[0] = lo;
1148
-
1149
- for (var k = 1; k < len; k++) {
1150
- // Sum all words with the same `i + j = k` and accumulate `ncarry`,
1151
- // note that ncarry could be >= 0x3ffffff
1152
- var ncarry = carry >>> 26;
1153
- var rword = carry & 0x3ffffff;
1154
- var maxJ = Math.min(k, num.length - 1);
1155
- for (var j = Math.max(0, k - self.length + 1); j <= maxJ; j++) {
1156
- var i = (k - j) | 0;
1157
- a = self.words[i] | 0;
1158
- b = num.words[j] | 0;
1159
- r = a * b + rword;
1160
- ncarry += (r / 0x4000000) | 0;
1161
- rword = r & 0x3ffffff;
1162
- }
1163
- out.words[k] = rword | 0;
1164
- carry = ncarry | 0;
1165
- }
1166
- if (carry !== 0) {
1167
- out.words[k] = carry | 0;
1168
- } else {
1169
- out.length--;
1170
- }
1171
-
1172
- return out._strip();
1173
- }
1174
-
1175
- // TODO(indutny): it may be reasonable to omit it for users who don't need
1176
- // to work with 256-bit numbers, otherwise it gives 20% improvement for 256-bit
1177
- // multiplication (like elliptic secp256k1).
1178
- var comb10MulTo = function comb10MulTo (self, num, out) {
1179
- var a = self.words;
1180
- var b = num.words;
1181
- var o = out.words;
1182
- var c = 0;
1183
- var lo;
1184
- var mid;
1185
- var hi;
1186
- var a0 = a[0] | 0;
1187
- var al0 = a0 & 0x1fff;
1188
- var ah0 = a0 >>> 13;
1189
- var a1 = a[1] | 0;
1190
- var al1 = a1 & 0x1fff;
1191
- var ah1 = a1 >>> 13;
1192
- var a2 = a[2] | 0;
1193
- var al2 = a2 & 0x1fff;
1194
- var ah2 = a2 >>> 13;
1195
- var a3 = a[3] | 0;
1196
- var al3 = a3 & 0x1fff;
1197
- var ah3 = a3 >>> 13;
1198
- var a4 = a[4] | 0;
1199
- var al4 = a4 & 0x1fff;
1200
- var ah4 = a4 >>> 13;
1201
- var a5 = a[5] | 0;
1202
- var al5 = a5 & 0x1fff;
1203
- var ah5 = a5 >>> 13;
1204
- var a6 = a[6] | 0;
1205
- var al6 = a6 & 0x1fff;
1206
- var ah6 = a6 >>> 13;
1207
- var a7 = a[7] | 0;
1208
- var al7 = a7 & 0x1fff;
1209
- var ah7 = a7 >>> 13;
1210
- var a8 = a[8] | 0;
1211
- var al8 = a8 & 0x1fff;
1212
- var ah8 = a8 >>> 13;
1213
- var a9 = a[9] | 0;
1214
- var al9 = a9 & 0x1fff;
1215
- var ah9 = a9 >>> 13;
1216
- var b0 = b[0] | 0;
1217
- var bl0 = b0 & 0x1fff;
1218
- var bh0 = b0 >>> 13;
1219
- var b1 = b[1] | 0;
1220
- var bl1 = b1 & 0x1fff;
1221
- var bh1 = b1 >>> 13;
1222
- var b2 = b[2] | 0;
1223
- var bl2 = b2 & 0x1fff;
1224
- var bh2 = b2 >>> 13;
1225
- var b3 = b[3] | 0;
1226
- var bl3 = b3 & 0x1fff;
1227
- var bh3 = b3 >>> 13;
1228
- var b4 = b[4] | 0;
1229
- var bl4 = b4 & 0x1fff;
1230
- var bh4 = b4 >>> 13;
1231
- var b5 = b[5] | 0;
1232
- var bl5 = b5 & 0x1fff;
1233
- var bh5 = b5 >>> 13;
1234
- var b6 = b[6] | 0;
1235
- var bl6 = b6 & 0x1fff;
1236
- var bh6 = b6 >>> 13;
1237
- var b7 = b[7] | 0;
1238
- var bl7 = b7 & 0x1fff;
1239
- var bh7 = b7 >>> 13;
1240
- var b8 = b[8] | 0;
1241
- var bl8 = b8 & 0x1fff;
1242
- var bh8 = b8 >>> 13;
1243
- var b9 = b[9] | 0;
1244
- var bl9 = b9 & 0x1fff;
1245
- var bh9 = b9 >>> 13;
1246
-
1247
- out.negative = self.negative ^ num.negative;
1248
- out.length = 19;
1249
- /* k = 0 */
1250
- lo = Math.imul(al0, bl0);
1251
- mid = Math.imul(al0, bh0);
1252
- mid = (mid + Math.imul(ah0, bl0)) | 0;
1253
- hi = Math.imul(ah0, bh0);
1254
- var w0 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
1255
- c = (((hi + (mid >>> 13)) | 0) + (w0 >>> 26)) | 0;
1256
- w0 &= 0x3ffffff;
1257
- /* k = 1 */
1258
- lo = Math.imul(al1, bl0);
1259
- mid = Math.imul(al1, bh0);
1260
- mid = (mid + Math.imul(ah1, bl0)) | 0;
1261
- hi = Math.imul(ah1, bh0);
1262
- lo = (lo + Math.imul(al0, bl1)) | 0;
1263
- mid = (mid + Math.imul(al0, bh1)) | 0;
1264
- mid = (mid + Math.imul(ah0, bl1)) | 0;
1265
- hi = (hi + Math.imul(ah0, bh1)) | 0;
1266
- var w1 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
1267
- c = (((hi + (mid >>> 13)) | 0) + (w1 >>> 26)) | 0;
1268
- w1 &= 0x3ffffff;
1269
- /* k = 2 */
1270
- lo = Math.imul(al2, bl0);
1271
- mid = Math.imul(al2, bh0);
1272
- mid = (mid + Math.imul(ah2, bl0)) | 0;
1273
- hi = Math.imul(ah2, bh0);
1274
- lo = (lo + Math.imul(al1, bl1)) | 0;
1275
- mid = (mid + Math.imul(al1, bh1)) | 0;
1276
- mid = (mid + Math.imul(ah1, bl1)) | 0;
1277
- hi = (hi + Math.imul(ah1, bh1)) | 0;
1278
- lo = (lo + Math.imul(al0, bl2)) | 0;
1279
- mid = (mid + Math.imul(al0, bh2)) | 0;
1280
- mid = (mid + Math.imul(ah0, bl2)) | 0;
1281
- hi = (hi + Math.imul(ah0, bh2)) | 0;
1282
- var w2 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
1283
- c = (((hi + (mid >>> 13)) | 0) + (w2 >>> 26)) | 0;
1284
- w2 &= 0x3ffffff;
1285
- /* k = 3 */
1286
- lo = Math.imul(al3, bl0);
1287
- mid = Math.imul(al3, bh0);
1288
- mid = (mid + Math.imul(ah3, bl0)) | 0;
1289
- hi = Math.imul(ah3, bh0);
1290
- lo = (lo + Math.imul(al2, bl1)) | 0;
1291
- mid = (mid + Math.imul(al2, bh1)) | 0;
1292
- mid = (mid + Math.imul(ah2, bl1)) | 0;
1293
- hi = (hi + Math.imul(ah2, bh1)) | 0;
1294
- lo = (lo + Math.imul(al1, bl2)) | 0;
1295
- mid = (mid + Math.imul(al1, bh2)) | 0;
1296
- mid = (mid + Math.imul(ah1, bl2)) | 0;
1297
- hi = (hi + Math.imul(ah1, bh2)) | 0;
1298
- lo = (lo + Math.imul(al0, bl3)) | 0;
1299
- mid = (mid + Math.imul(al0, bh3)) | 0;
1300
- mid = (mid + Math.imul(ah0, bl3)) | 0;
1301
- hi = (hi + Math.imul(ah0, bh3)) | 0;
1302
- var w3 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
1303
- c = (((hi + (mid >>> 13)) | 0) + (w3 >>> 26)) | 0;
1304
- w3 &= 0x3ffffff;
1305
- /* k = 4 */
1306
- lo = Math.imul(al4, bl0);
1307
- mid = Math.imul(al4, bh0);
1308
- mid = (mid + Math.imul(ah4, bl0)) | 0;
1309
- hi = Math.imul(ah4, bh0);
1310
- lo = (lo + Math.imul(al3, bl1)) | 0;
1311
- mid = (mid + Math.imul(al3, bh1)) | 0;
1312
- mid = (mid + Math.imul(ah3, bl1)) | 0;
1313
- hi = (hi + Math.imul(ah3, bh1)) | 0;
1314
- lo = (lo + Math.imul(al2, bl2)) | 0;
1315
- mid = (mid + Math.imul(al2, bh2)) | 0;
1316
- mid = (mid + Math.imul(ah2, bl2)) | 0;
1317
- hi = (hi + Math.imul(ah2, bh2)) | 0;
1318
- lo = (lo + Math.imul(al1, bl3)) | 0;
1319
- mid = (mid + Math.imul(al1, bh3)) | 0;
1320
- mid = (mid + Math.imul(ah1, bl3)) | 0;
1321
- hi = (hi + Math.imul(ah1, bh3)) | 0;
1322
- lo = (lo + Math.imul(al0, bl4)) | 0;
1323
- mid = (mid + Math.imul(al0, bh4)) | 0;
1324
- mid = (mid + Math.imul(ah0, bl4)) | 0;
1325
- hi = (hi + Math.imul(ah0, bh4)) | 0;
1326
- var w4 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
1327
- c = (((hi + (mid >>> 13)) | 0) + (w4 >>> 26)) | 0;
1328
- w4 &= 0x3ffffff;
1329
- /* k = 5 */
1330
- lo = Math.imul(al5, bl0);
1331
- mid = Math.imul(al5, bh0);
1332
- mid = (mid + Math.imul(ah5, bl0)) | 0;
1333
- hi = Math.imul(ah5, bh0);
1334
- lo = (lo + Math.imul(al4, bl1)) | 0;
1335
- mid = (mid + Math.imul(al4, bh1)) | 0;
1336
- mid = (mid + Math.imul(ah4, bl1)) | 0;
1337
- hi = (hi + Math.imul(ah4, bh1)) | 0;
1338
- lo = (lo + Math.imul(al3, bl2)) | 0;
1339
- mid = (mid + Math.imul(al3, bh2)) | 0;
1340
- mid = (mid + Math.imul(ah3, bl2)) | 0;
1341
- hi = (hi + Math.imul(ah3, bh2)) | 0;
1342
- lo = (lo + Math.imul(al2, bl3)) | 0;
1343
- mid = (mid + Math.imul(al2, bh3)) | 0;
1344
- mid = (mid + Math.imul(ah2, bl3)) | 0;
1345
- hi = (hi + Math.imul(ah2, bh3)) | 0;
1346
- lo = (lo + Math.imul(al1, bl4)) | 0;
1347
- mid = (mid + Math.imul(al1, bh4)) | 0;
1348
- mid = (mid + Math.imul(ah1, bl4)) | 0;
1349
- hi = (hi + Math.imul(ah1, bh4)) | 0;
1350
- lo = (lo + Math.imul(al0, bl5)) | 0;
1351
- mid = (mid + Math.imul(al0, bh5)) | 0;
1352
- mid = (mid + Math.imul(ah0, bl5)) | 0;
1353
- hi = (hi + Math.imul(ah0, bh5)) | 0;
1354
- var w5 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
1355
- c = (((hi + (mid >>> 13)) | 0) + (w5 >>> 26)) | 0;
1356
- w5 &= 0x3ffffff;
1357
- /* k = 6 */
1358
- lo = Math.imul(al6, bl0);
1359
- mid = Math.imul(al6, bh0);
1360
- mid = (mid + Math.imul(ah6, bl0)) | 0;
1361
- hi = Math.imul(ah6, bh0);
1362
- lo = (lo + Math.imul(al5, bl1)) | 0;
1363
- mid = (mid + Math.imul(al5, bh1)) | 0;
1364
- mid = (mid + Math.imul(ah5, bl1)) | 0;
1365
- hi = (hi + Math.imul(ah5, bh1)) | 0;
1366
- lo = (lo + Math.imul(al4, bl2)) | 0;
1367
- mid = (mid + Math.imul(al4, bh2)) | 0;
1368
- mid = (mid + Math.imul(ah4, bl2)) | 0;
1369
- hi = (hi + Math.imul(ah4, bh2)) | 0;
1370
- lo = (lo + Math.imul(al3, bl3)) | 0;
1371
- mid = (mid + Math.imul(al3, bh3)) | 0;
1372
- mid = (mid + Math.imul(ah3, bl3)) | 0;
1373
- hi = (hi + Math.imul(ah3, bh3)) | 0;
1374
- lo = (lo + Math.imul(al2, bl4)) | 0;
1375
- mid = (mid + Math.imul(al2, bh4)) | 0;
1376
- mid = (mid + Math.imul(ah2, bl4)) | 0;
1377
- hi = (hi + Math.imul(ah2, bh4)) | 0;
1378
- lo = (lo + Math.imul(al1, bl5)) | 0;
1379
- mid = (mid + Math.imul(al1, bh5)) | 0;
1380
- mid = (mid + Math.imul(ah1, bl5)) | 0;
1381
- hi = (hi + Math.imul(ah1, bh5)) | 0;
1382
- lo = (lo + Math.imul(al0, bl6)) | 0;
1383
- mid = (mid + Math.imul(al0, bh6)) | 0;
1384
- mid = (mid + Math.imul(ah0, bl6)) | 0;
1385
- hi = (hi + Math.imul(ah0, bh6)) | 0;
1386
- var w6 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
1387
- c = (((hi + (mid >>> 13)) | 0) + (w6 >>> 26)) | 0;
1388
- w6 &= 0x3ffffff;
1389
- /* k = 7 */
1390
- lo = Math.imul(al7, bl0);
1391
- mid = Math.imul(al7, bh0);
1392
- mid = (mid + Math.imul(ah7, bl0)) | 0;
1393
- hi = Math.imul(ah7, bh0);
1394
- lo = (lo + Math.imul(al6, bl1)) | 0;
1395
- mid = (mid + Math.imul(al6, bh1)) | 0;
1396
- mid = (mid + Math.imul(ah6, bl1)) | 0;
1397
- hi = (hi + Math.imul(ah6, bh1)) | 0;
1398
- lo = (lo + Math.imul(al5, bl2)) | 0;
1399
- mid = (mid + Math.imul(al5, bh2)) | 0;
1400
- mid = (mid + Math.imul(ah5, bl2)) | 0;
1401
- hi = (hi + Math.imul(ah5, bh2)) | 0;
1402
- lo = (lo + Math.imul(al4, bl3)) | 0;
1403
- mid = (mid + Math.imul(al4, bh3)) | 0;
1404
- mid = (mid + Math.imul(ah4, bl3)) | 0;
1405
- hi = (hi + Math.imul(ah4, bh3)) | 0;
1406
- lo = (lo + Math.imul(al3, bl4)) | 0;
1407
- mid = (mid + Math.imul(al3, bh4)) | 0;
1408
- mid = (mid + Math.imul(ah3, bl4)) | 0;
1409
- hi = (hi + Math.imul(ah3, bh4)) | 0;
1410
- lo = (lo + Math.imul(al2, bl5)) | 0;
1411
- mid = (mid + Math.imul(al2, bh5)) | 0;
1412
- mid = (mid + Math.imul(ah2, bl5)) | 0;
1413
- hi = (hi + Math.imul(ah2, bh5)) | 0;
1414
- lo = (lo + Math.imul(al1, bl6)) | 0;
1415
- mid = (mid + Math.imul(al1, bh6)) | 0;
1416
- mid = (mid + Math.imul(ah1, bl6)) | 0;
1417
- hi = (hi + Math.imul(ah1, bh6)) | 0;
1418
- lo = (lo + Math.imul(al0, bl7)) | 0;
1419
- mid = (mid + Math.imul(al0, bh7)) | 0;
1420
- mid = (mid + Math.imul(ah0, bl7)) | 0;
1421
- hi = (hi + Math.imul(ah0, bh7)) | 0;
1422
- var w7 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
1423
- c = (((hi + (mid >>> 13)) | 0) + (w7 >>> 26)) | 0;
1424
- w7 &= 0x3ffffff;
1425
- /* k = 8 */
1426
- lo = Math.imul(al8, bl0);
1427
- mid = Math.imul(al8, bh0);
1428
- mid = (mid + Math.imul(ah8, bl0)) | 0;
1429
- hi = Math.imul(ah8, bh0);
1430
- lo = (lo + Math.imul(al7, bl1)) | 0;
1431
- mid = (mid + Math.imul(al7, bh1)) | 0;
1432
- mid = (mid + Math.imul(ah7, bl1)) | 0;
1433
- hi = (hi + Math.imul(ah7, bh1)) | 0;
1434
- lo = (lo + Math.imul(al6, bl2)) | 0;
1435
- mid = (mid + Math.imul(al6, bh2)) | 0;
1436
- mid = (mid + Math.imul(ah6, bl2)) | 0;
1437
- hi = (hi + Math.imul(ah6, bh2)) | 0;
1438
- lo = (lo + Math.imul(al5, bl3)) | 0;
1439
- mid = (mid + Math.imul(al5, bh3)) | 0;
1440
- mid = (mid + Math.imul(ah5, bl3)) | 0;
1441
- hi = (hi + Math.imul(ah5, bh3)) | 0;
1442
- lo = (lo + Math.imul(al4, bl4)) | 0;
1443
- mid = (mid + Math.imul(al4, bh4)) | 0;
1444
- mid = (mid + Math.imul(ah4, bl4)) | 0;
1445
- hi = (hi + Math.imul(ah4, bh4)) | 0;
1446
- lo = (lo + Math.imul(al3, bl5)) | 0;
1447
- mid = (mid + Math.imul(al3, bh5)) | 0;
1448
- mid = (mid + Math.imul(ah3, bl5)) | 0;
1449
- hi = (hi + Math.imul(ah3, bh5)) | 0;
1450
- lo = (lo + Math.imul(al2, bl6)) | 0;
1451
- mid = (mid + Math.imul(al2, bh6)) | 0;
1452
- mid = (mid + Math.imul(ah2, bl6)) | 0;
1453
- hi = (hi + Math.imul(ah2, bh6)) | 0;
1454
- lo = (lo + Math.imul(al1, bl7)) | 0;
1455
- mid = (mid + Math.imul(al1, bh7)) | 0;
1456
- mid = (mid + Math.imul(ah1, bl7)) | 0;
1457
- hi = (hi + Math.imul(ah1, bh7)) | 0;
1458
- lo = (lo + Math.imul(al0, bl8)) | 0;
1459
- mid = (mid + Math.imul(al0, bh8)) | 0;
1460
- mid = (mid + Math.imul(ah0, bl8)) | 0;
1461
- hi = (hi + Math.imul(ah0, bh8)) | 0;
1462
- var w8 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
1463
- c = (((hi + (mid >>> 13)) | 0) + (w8 >>> 26)) | 0;
1464
- w8 &= 0x3ffffff;
1465
- /* k = 9 */
1466
- lo = Math.imul(al9, bl0);
1467
- mid = Math.imul(al9, bh0);
1468
- mid = (mid + Math.imul(ah9, bl0)) | 0;
1469
- hi = Math.imul(ah9, bh0);
1470
- lo = (lo + Math.imul(al8, bl1)) | 0;
1471
- mid = (mid + Math.imul(al8, bh1)) | 0;
1472
- mid = (mid + Math.imul(ah8, bl1)) | 0;
1473
- hi = (hi + Math.imul(ah8, bh1)) | 0;
1474
- lo = (lo + Math.imul(al7, bl2)) | 0;
1475
- mid = (mid + Math.imul(al7, bh2)) | 0;
1476
- mid = (mid + Math.imul(ah7, bl2)) | 0;
1477
- hi = (hi + Math.imul(ah7, bh2)) | 0;
1478
- lo = (lo + Math.imul(al6, bl3)) | 0;
1479
- mid = (mid + Math.imul(al6, bh3)) | 0;
1480
- mid = (mid + Math.imul(ah6, bl3)) | 0;
1481
- hi = (hi + Math.imul(ah6, bh3)) | 0;
1482
- lo = (lo + Math.imul(al5, bl4)) | 0;
1483
- mid = (mid + Math.imul(al5, bh4)) | 0;
1484
- mid = (mid + Math.imul(ah5, bl4)) | 0;
1485
- hi = (hi + Math.imul(ah5, bh4)) | 0;
1486
- lo = (lo + Math.imul(al4, bl5)) | 0;
1487
- mid = (mid + Math.imul(al4, bh5)) | 0;
1488
- mid = (mid + Math.imul(ah4, bl5)) | 0;
1489
- hi = (hi + Math.imul(ah4, bh5)) | 0;
1490
- lo = (lo + Math.imul(al3, bl6)) | 0;
1491
- mid = (mid + Math.imul(al3, bh6)) | 0;
1492
- mid = (mid + Math.imul(ah3, bl6)) | 0;
1493
- hi = (hi + Math.imul(ah3, bh6)) | 0;
1494
- lo = (lo + Math.imul(al2, bl7)) | 0;
1495
- mid = (mid + Math.imul(al2, bh7)) | 0;
1496
- mid = (mid + Math.imul(ah2, bl7)) | 0;
1497
- hi = (hi + Math.imul(ah2, bh7)) | 0;
1498
- lo = (lo + Math.imul(al1, bl8)) | 0;
1499
- mid = (mid + Math.imul(al1, bh8)) | 0;
1500
- mid = (mid + Math.imul(ah1, bl8)) | 0;
1501
- hi = (hi + Math.imul(ah1, bh8)) | 0;
1502
- lo = (lo + Math.imul(al0, bl9)) | 0;
1503
- mid = (mid + Math.imul(al0, bh9)) | 0;
1504
- mid = (mid + Math.imul(ah0, bl9)) | 0;
1505
- hi = (hi + Math.imul(ah0, bh9)) | 0;
1506
- var w9 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
1507
- c = (((hi + (mid >>> 13)) | 0) + (w9 >>> 26)) | 0;
1508
- w9 &= 0x3ffffff;
1509
- /* k = 10 */
1510
- lo = Math.imul(al9, bl1);
1511
- mid = Math.imul(al9, bh1);
1512
- mid = (mid + Math.imul(ah9, bl1)) | 0;
1513
- hi = Math.imul(ah9, bh1);
1514
- lo = (lo + Math.imul(al8, bl2)) | 0;
1515
- mid = (mid + Math.imul(al8, bh2)) | 0;
1516
- mid = (mid + Math.imul(ah8, bl2)) | 0;
1517
- hi = (hi + Math.imul(ah8, bh2)) | 0;
1518
- lo = (lo + Math.imul(al7, bl3)) | 0;
1519
- mid = (mid + Math.imul(al7, bh3)) | 0;
1520
- mid = (mid + Math.imul(ah7, bl3)) | 0;
1521
- hi = (hi + Math.imul(ah7, bh3)) | 0;
1522
- lo = (lo + Math.imul(al6, bl4)) | 0;
1523
- mid = (mid + Math.imul(al6, bh4)) | 0;
1524
- mid = (mid + Math.imul(ah6, bl4)) | 0;
1525
- hi = (hi + Math.imul(ah6, bh4)) | 0;
1526
- lo = (lo + Math.imul(al5, bl5)) | 0;
1527
- mid = (mid + Math.imul(al5, bh5)) | 0;
1528
- mid = (mid + Math.imul(ah5, bl5)) | 0;
1529
- hi = (hi + Math.imul(ah5, bh5)) | 0;
1530
- lo = (lo + Math.imul(al4, bl6)) | 0;
1531
- mid = (mid + Math.imul(al4, bh6)) | 0;
1532
- mid = (mid + Math.imul(ah4, bl6)) | 0;
1533
- hi = (hi + Math.imul(ah4, bh6)) | 0;
1534
- lo = (lo + Math.imul(al3, bl7)) | 0;
1535
- mid = (mid + Math.imul(al3, bh7)) | 0;
1536
- mid = (mid + Math.imul(ah3, bl7)) | 0;
1537
- hi = (hi + Math.imul(ah3, bh7)) | 0;
1538
- lo = (lo + Math.imul(al2, bl8)) | 0;
1539
- mid = (mid + Math.imul(al2, bh8)) | 0;
1540
- mid = (mid + Math.imul(ah2, bl8)) | 0;
1541
- hi = (hi + Math.imul(ah2, bh8)) | 0;
1542
- lo = (lo + Math.imul(al1, bl9)) | 0;
1543
- mid = (mid + Math.imul(al1, bh9)) | 0;
1544
- mid = (mid + Math.imul(ah1, bl9)) | 0;
1545
- hi = (hi + Math.imul(ah1, bh9)) | 0;
1546
- var w10 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
1547
- c = (((hi + (mid >>> 13)) | 0) + (w10 >>> 26)) | 0;
1548
- w10 &= 0x3ffffff;
1549
- /* k = 11 */
1550
- lo = Math.imul(al9, bl2);
1551
- mid = Math.imul(al9, bh2);
1552
- mid = (mid + Math.imul(ah9, bl2)) | 0;
1553
- hi = Math.imul(ah9, bh2);
1554
- lo = (lo + Math.imul(al8, bl3)) | 0;
1555
- mid = (mid + Math.imul(al8, bh3)) | 0;
1556
- mid = (mid + Math.imul(ah8, bl3)) | 0;
1557
- hi = (hi + Math.imul(ah8, bh3)) | 0;
1558
- lo = (lo + Math.imul(al7, bl4)) | 0;
1559
- mid = (mid + Math.imul(al7, bh4)) | 0;
1560
- mid = (mid + Math.imul(ah7, bl4)) | 0;
1561
- hi = (hi + Math.imul(ah7, bh4)) | 0;
1562
- lo = (lo + Math.imul(al6, bl5)) | 0;
1563
- mid = (mid + Math.imul(al6, bh5)) | 0;
1564
- mid = (mid + Math.imul(ah6, bl5)) | 0;
1565
- hi = (hi + Math.imul(ah6, bh5)) | 0;
1566
- lo = (lo + Math.imul(al5, bl6)) | 0;
1567
- mid = (mid + Math.imul(al5, bh6)) | 0;
1568
- mid = (mid + Math.imul(ah5, bl6)) | 0;
1569
- hi = (hi + Math.imul(ah5, bh6)) | 0;
1570
- lo = (lo + Math.imul(al4, bl7)) | 0;
1571
- mid = (mid + Math.imul(al4, bh7)) | 0;
1572
- mid = (mid + Math.imul(ah4, bl7)) | 0;
1573
- hi = (hi + Math.imul(ah4, bh7)) | 0;
1574
- lo = (lo + Math.imul(al3, bl8)) | 0;
1575
- mid = (mid + Math.imul(al3, bh8)) | 0;
1576
- mid = (mid + Math.imul(ah3, bl8)) | 0;
1577
- hi = (hi + Math.imul(ah3, bh8)) | 0;
1578
- lo = (lo + Math.imul(al2, bl9)) | 0;
1579
- mid = (mid + Math.imul(al2, bh9)) | 0;
1580
- mid = (mid + Math.imul(ah2, bl9)) | 0;
1581
- hi = (hi + Math.imul(ah2, bh9)) | 0;
1582
- var w11 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
1583
- c = (((hi + (mid >>> 13)) | 0) + (w11 >>> 26)) | 0;
1584
- w11 &= 0x3ffffff;
1585
- /* k = 12 */
1586
- lo = Math.imul(al9, bl3);
1587
- mid = Math.imul(al9, bh3);
1588
- mid = (mid + Math.imul(ah9, bl3)) | 0;
1589
- hi = Math.imul(ah9, bh3);
1590
- lo = (lo + Math.imul(al8, bl4)) | 0;
1591
- mid = (mid + Math.imul(al8, bh4)) | 0;
1592
- mid = (mid + Math.imul(ah8, bl4)) | 0;
1593
- hi = (hi + Math.imul(ah8, bh4)) | 0;
1594
- lo = (lo + Math.imul(al7, bl5)) | 0;
1595
- mid = (mid + Math.imul(al7, bh5)) | 0;
1596
- mid = (mid + Math.imul(ah7, bl5)) | 0;
1597
- hi = (hi + Math.imul(ah7, bh5)) | 0;
1598
- lo = (lo + Math.imul(al6, bl6)) | 0;
1599
- mid = (mid + Math.imul(al6, bh6)) | 0;
1600
- mid = (mid + Math.imul(ah6, bl6)) | 0;
1601
- hi = (hi + Math.imul(ah6, bh6)) | 0;
1602
- lo = (lo + Math.imul(al5, bl7)) | 0;
1603
- mid = (mid + Math.imul(al5, bh7)) | 0;
1604
- mid = (mid + Math.imul(ah5, bl7)) | 0;
1605
- hi = (hi + Math.imul(ah5, bh7)) | 0;
1606
- lo = (lo + Math.imul(al4, bl8)) | 0;
1607
- mid = (mid + Math.imul(al4, bh8)) | 0;
1608
- mid = (mid + Math.imul(ah4, bl8)) | 0;
1609
- hi = (hi + Math.imul(ah4, bh8)) | 0;
1610
- lo = (lo + Math.imul(al3, bl9)) | 0;
1611
- mid = (mid + Math.imul(al3, bh9)) | 0;
1612
- mid = (mid + Math.imul(ah3, bl9)) | 0;
1613
- hi = (hi + Math.imul(ah3, bh9)) | 0;
1614
- var w12 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
1615
- c = (((hi + (mid >>> 13)) | 0) + (w12 >>> 26)) | 0;
1616
- w12 &= 0x3ffffff;
1617
- /* k = 13 */
1618
- lo = Math.imul(al9, bl4);
1619
- mid = Math.imul(al9, bh4);
1620
- mid = (mid + Math.imul(ah9, bl4)) | 0;
1621
- hi = Math.imul(ah9, bh4);
1622
- lo = (lo + Math.imul(al8, bl5)) | 0;
1623
- mid = (mid + Math.imul(al8, bh5)) | 0;
1624
- mid = (mid + Math.imul(ah8, bl5)) | 0;
1625
- hi = (hi + Math.imul(ah8, bh5)) | 0;
1626
- lo = (lo + Math.imul(al7, bl6)) | 0;
1627
- mid = (mid + Math.imul(al7, bh6)) | 0;
1628
- mid = (mid + Math.imul(ah7, bl6)) | 0;
1629
- hi = (hi + Math.imul(ah7, bh6)) | 0;
1630
- lo = (lo + Math.imul(al6, bl7)) | 0;
1631
- mid = (mid + Math.imul(al6, bh7)) | 0;
1632
- mid = (mid + Math.imul(ah6, bl7)) | 0;
1633
- hi = (hi + Math.imul(ah6, bh7)) | 0;
1634
- lo = (lo + Math.imul(al5, bl8)) | 0;
1635
- mid = (mid + Math.imul(al5, bh8)) | 0;
1636
- mid = (mid + Math.imul(ah5, bl8)) | 0;
1637
- hi = (hi + Math.imul(ah5, bh8)) | 0;
1638
- lo = (lo + Math.imul(al4, bl9)) | 0;
1639
- mid = (mid + Math.imul(al4, bh9)) | 0;
1640
- mid = (mid + Math.imul(ah4, bl9)) | 0;
1641
- hi = (hi + Math.imul(ah4, bh9)) | 0;
1642
- var w13 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
1643
- c = (((hi + (mid >>> 13)) | 0) + (w13 >>> 26)) | 0;
1644
- w13 &= 0x3ffffff;
1645
- /* k = 14 */
1646
- lo = Math.imul(al9, bl5);
1647
- mid = Math.imul(al9, bh5);
1648
- mid = (mid + Math.imul(ah9, bl5)) | 0;
1649
- hi = Math.imul(ah9, bh5);
1650
- lo = (lo + Math.imul(al8, bl6)) | 0;
1651
- mid = (mid + Math.imul(al8, bh6)) | 0;
1652
- mid = (mid + Math.imul(ah8, bl6)) | 0;
1653
- hi = (hi + Math.imul(ah8, bh6)) | 0;
1654
- lo = (lo + Math.imul(al7, bl7)) | 0;
1655
- mid = (mid + Math.imul(al7, bh7)) | 0;
1656
- mid = (mid + Math.imul(ah7, bl7)) | 0;
1657
- hi = (hi + Math.imul(ah7, bh7)) | 0;
1658
- lo = (lo + Math.imul(al6, bl8)) | 0;
1659
- mid = (mid + Math.imul(al6, bh8)) | 0;
1660
- mid = (mid + Math.imul(ah6, bl8)) | 0;
1661
- hi = (hi + Math.imul(ah6, bh8)) | 0;
1662
- lo = (lo + Math.imul(al5, bl9)) | 0;
1663
- mid = (mid + Math.imul(al5, bh9)) | 0;
1664
- mid = (mid + Math.imul(ah5, bl9)) | 0;
1665
- hi = (hi + Math.imul(ah5, bh9)) | 0;
1666
- var w14 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
1667
- c = (((hi + (mid >>> 13)) | 0) + (w14 >>> 26)) | 0;
1668
- w14 &= 0x3ffffff;
1669
- /* k = 15 */
1670
- lo = Math.imul(al9, bl6);
1671
- mid = Math.imul(al9, bh6);
1672
- mid = (mid + Math.imul(ah9, bl6)) | 0;
1673
- hi = Math.imul(ah9, bh6);
1674
- lo = (lo + Math.imul(al8, bl7)) | 0;
1675
- mid = (mid + Math.imul(al8, bh7)) | 0;
1676
- mid = (mid + Math.imul(ah8, bl7)) | 0;
1677
- hi = (hi + Math.imul(ah8, bh7)) | 0;
1678
- lo = (lo + Math.imul(al7, bl8)) | 0;
1679
- mid = (mid + Math.imul(al7, bh8)) | 0;
1680
- mid = (mid + Math.imul(ah7, bl8)) | 0;
1681
- hi = (hi + Math.imul(ah7, bh8)) | 0;
1682
- lo = (lo + Math.imul(al6, bl9)) | 0;
1683
- mid = (mid + Math.imul(al6, bh9)) | 0;
1684
- mid = (mid + Math.imul(ah6, bl9)) | 0;
1685
- hi = (hi + Math.imul(ah6, bh9)) | 0;
1686
- var w15 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
1687
- c = (((hi + (mid >>> 13)) | 0) + (w15 >>> 26)) | 0;
1688
- w15 &= 0x3ffffff;
1689
- /* k = 16 */
1690
- lo = Math.imul(al9, bl7);
1691
- mid = Math.imul(al9, bh7);
1692
- mid = (mid + Math.imul(ah9, bl7)) | 0;
1693
- hi = Math.imul(ah9, bh7);
1694
- lo = (lo + Math.imul(al8, bl8)) | 0;
1695
- mid = (mid + Math.imul(al8, bh8)) | 0;
1696
- mid = (mid + Math.imul(ah8, bl8)) | 0;
1697
- hi = (hi + Math.imul(ah8, bh8)) | 0;
1698
- lo = (lo + Math.imul(al7, bl9)) | 0;
1699
- mid = (mid + Math.imul(al7, bh9)) | 0;
1700
- mid = (mid + Math.imul(ah7, bl9)) | 0;
1701
- hi = (hi + Math.imul(ah7, bh9)) | 0;
1702
- var w16 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
1703
- c = (((hi + (mid >>> 13)) | 0) + (w16 >>> 26)) | 0;
1704
- w16 &= 0x3ffffff;
1705
- /* k = 17 */
1706
- lo = Math.imul(al9, bl8);
1707
- mid = Math.imul(al9, bh8);
1708
- mid = (mid + Math.imul(ah9, bl8)) | 0;
1709
- hi = Math.imul(ah9, bh8);
1710
- lo = (lo + Math.imul(al8, bl9)) | 0;
1711
- mid = (mid + Math.imul(al8, bh9)) | 0;
1712
- mid = (mid + Math.imul(ah8, bl9)) | 0;
1713
- hi = (hi + Math.imul(ah8, bh9)) | 0;
1714
- var w17 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
1715
- c = (((hi + (mid >>> 13)) | 0) + (w17 >>> 26)) | 0;
1716
- w17 &= 0x3ffffff;
1717
- /* k = 18 */
1718
- lo = Math.imul(al9, bl9);
1719
- mid = Math.imul(al9, bh9);
1720
- mid = (mid + Math.imul(ah9, bl9)) | 0;
1721
- hi = Math.imul(ah9, bh9);
1722
- var w18 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
1723
- c = (((hi + (mid >>> 13)) | 0) + (w18 >>> 26)) | 0;
1724
- w18 &= 0x3ffffff;
1725
- o[0] = w0;
1726
- o[1] = w1;
1727
- o[2] = w2;
1728
- o[3] = w3;
1729
- o[4] = w4;
1730
- o[5] = w5;
1731
- o[6] = w6;
1732
- o[7] = w7;
1733
- o[8] = w8;
1734
- o[9] = w9;
1735
- o[10] = w10;
1736
- o[11] = w11;
1737
- o[12] = w12;
1738
- o[13] = w13;
1739
- o[14] = w14;
1740
- o[15] = w15;
1741
- o[16] = w16;
1742
- o[17] = w17;
1743
- o[18] = w18;
1744
- if (c !== 0) {
1745
- o[19] = c;
1746
- out.length++;
1747
- }
1748
- return out;
1749
- };
1750
-
1751
- // Polyfill comb
1752
- if (!Math.imul) {
1753
- comb10MulTo = smallMulTo;
1754
- }
1755
-
1756
- function bigMulTo (self, num, out) {
1757
- out.negative = num.negative ^ self.negative;
1758
- out.length = self.length + num.length;
1759
-
1760
- var carry = 0;
1761
- var hncarry = 0;
1762
- for (var k = 0; k < out.length - 1; k++) {
1763
- // Sum all words with the same `i + j = k` and accumulate `ncarry`,
1764
- // note that ncarry could be >= 0x3ffffff
1765
- var ncarry = hncarry;
1766
- hncarry = 0;
1767
- var rword = carry & 0x3ffffff;
1768
- var maxJ = Math.min(k, num.length - 1);
1769
- for (var j = Math.max(0, k - self.length + 1); j <= maxJ; j++) {
1770
- var i = k - j;
1771
- var a = self.words[i] | 0;
1772
- var b = num.words[j] | 0;
1773
- var r = a * b;
1774
-
1775
- var lo = r & 0x3ffffff;
1776
- ncarry = (ncarry + ((r / 0x4000000) | 0)) | 0;
1777
- lo = (lo + rword) | 0;
1778
- rword = lo & 0x3ffffff;
1779
- ncarry = (ncarry + (lo >>> 26)) | 0;
1780
-
1781
- hncarry += ncarry >>> 26;
1782
- ncarry &= 0x3ffffff;
1783
- }
1784
- out.words[k] = rword;
1785
- carry = ncarry;
1786
- ncarry = hncarry;
1787
- }
1788
- if (carry !== 0) {
1789
- out.words[k] = carry;
1790
- } else {
1791
- out.length--;
1792
- }
1793
-
1794
- return out._strip();
1795
- }
1796
-
1797
- function jumboMulTo (self, num, out) {
1798
- // Temporary disable, see https://github.com/indutny/bn.js/issues/211
1799
- // var fftm = new FFTM();
1800
- // return fftm.mulp(self, num, out);
1801
- return bigMulTo(self, num, out);
1802
- }
1803
-
1804
- BN.prototype.mulTo = function mulTo (num, out) {
1805
- var res;
1806
- var len = this.length + num.length;
1807
- if (this.length === 10 && num.length === 10) {
1808
- res = comb10MulTo(this, num, out);
1809
- } else if (len < 63) {
1810
- res = smallMulTo(this, num, out);
1811
- } else if (len < 1024) {
1812
- res = bigMulTo(this, num, out);
1813
- } else {
1814
- res = jumboMulTo(this, num, out);
1815
- }
1816
-
1817
- return res;
1818
- };
1819
-
1820
- // Multiply `this` by `num`
1821
- BN.prototype.mul = function mul (num) {
1822
- var out = new BN(null);
1823
- out.words = new Array(this.length + num.length);
1824
- return this.mulTo(num, out);
1825
- };
1826
-
1827
- // Multiply employing FFT
1828
- BN.prototype.mulf = function mulf (num) {
1829
- var out = new BN(null);
1830
- out.words = new Array(this.length + num.length);
1831
- return jumboMulTo(this, num, out);
1832
- };
1833
-
1834
- // In-place Multiplication
1835
- BN.prototype.imul = function imul (num) {
1836
- return this.clone().mulTo(num, this);
1837
- };
1838
-
1839
- BN.prototype.imuln = function imuln (num) {
1840
- var isNegNum = num < 0;
1841
- if (isNegNum) num = -num;
1842
-
1843
- assert(typeof num === 'number');
1844
- assert(num < 0x4000000);
1845
-
1846
- // Carry
1847
- var carry = 0;
1848
- for (var i = 0; i < this.length; i++) {
1849
- var w = (this.words[i] | 0) * num;
1850
- var lo = (w & 0x3ffffff) + (carry & 0x3ffffff);
1851
- carry >>= 26;
1852
- carry += (w / 0x4000000) | 0;
1853
- // NOTE: lo is 27bit maximum
1854
- carry += lo >>> 26;
1855
- this.words[i] = lo & 0x3ffffff;
1856
- }
1857
-
1858
- if (carry !== 0) {
1859
- this.words[i] = carry;
1860
- this.length++;
1861
- }
1862
-
1863
- return isNegNum ? this.ineg() : this;
1864
- };
1865
-
1866
- BN.prototype.muln = function muln (num) {
1867
- return this.clone().imuln(num);
1868
- };
1869
-
1870
- // `this` * `this`
1871
- BN.prototype.sqr = function sqr () {
1872
- return this.mul(this);
1873
- };
1874
-
1875
- // `this` * `this` in-place
1876
- BN.prototype.isqr = function isqr () {
1877
- return this.imul(this.clone());
1878
- };
1879
-
1880
- // Math.pow(`this`, `num`)
1881
- BN.prototype.pow = function pow (num) {
1882
- var w = toBitArray(num);
1883
- if (w.length === 0) return new BN(1);
1884
-
1885
- // Skip leading zeroes
1886
- var res = this;
1887
- for (var i = 0; i < w.length; i++, res = res.sqr()) {
1888
- if (w[i] !== 0) break;
1889
- }
1890
-
1891
- if (++i < w.length) {
1892
- for (var q = res.sqr(); i < w.length; i++, q = q.sqr()) {
1893
- if (w[i] === 0) continue;
1894
-
1895
- res = res.mul(q);
1896
- }
1897
- }
1898
-
1899
- return res;
1900
- };
1901
-
1902
- // Shift-left in-place
1903
- BN.prototype.iushln = function iushln (bits) {
1904
- assert(typeof bits === 'number' && bits >= 0);
1905
- var r = bits % 26;
1906
- var s = (bits - r) / 26;
1907
- var carryMask = (0x3ffffff >>> (26 - r)) << (26 - r);
1908
- var i;
1909
-
1910
- if (r !== 0) {
1911
- var carry = 0;
1912
-
1913
- for (i = 0; i < this.length; i++) {
1914
- var newCarry = this.words[i] & carryMask;
1915
- var c = ((this.words[i] | 0) - newCarry) << r;
1916
- this.words[i] = c | carry;
1917
- carry = newCarry >>> (26 - r);
1918
- }
1919
-
1920
- if (carry) {
1921
- this.words[i] = carry;
1922
- this.length++;
1923
- }
1924
- }
1925
-
1926
- if (s !== 0) {
1927
- for (i = this.length - 1; i >= 0; i--) {
1928
- this.words[i + s] = this.words[i];
1929
- }
1930
-
1931
- for (i = 0; i < s; i++) {
1932
- this.words[i] = 0;
1933
- }
1934
-
1935
- this.length += s;
1936
- }
1937
-
1938
- return this._strip();
1939
- };
1940
-
1941
- BN.prototype.ishln = function ishln (bits) {
1942
- // TODO(indutny): implement me
1943
- assert(this.negative === 0);
1944
- return this.iushln(bits);
1945
- };
1946
-
1947
- // Shift-right in-place
1948
- // NOTE: `hint` is a lowest bit before trailing zeroes
1949
- // NOTE: if `extended` is present - it will be filled with destroyed bits
1950
- BN.prototype.iushrn = function iushrn (bits, hint, extended) {
1951
- assert(typeof bits === 'number' && bits >= 0);
1952
- var h;
1953
- if (hint) {
1954
- h = (hint - (hint % 26)) / 26;
1955
- } else {
1956
- h = 0;
1957
- }
1958
-
1959
- var r = bits % 26;
1960
- var s = Math.min((bits - r) / 26, this.length);
1961
- var mask = 0x3ffffff ^ ((0x3ffffff >>> r) << r);
1962
- var maskedWords = extended;
1963
-
1964
- h -= s;
1965
- h = Math.max(0, h);
1966
-
1967
- // Extended mode, copy masked part
1968
- if (maskedWords) {
1969
- for (var i = 0; i < s; i++) {
1970
- maskedWords.words[i] = this.words[i];
1971
- }
1972
- maskedWords.length = s;
1973
- }
1974
-
1975
- if (s === 0) ; else if (this.length > s) {
1976
- this.length -= s;
1977
- for (i = 0; i < this.length; i++) {
1978
- this.words[i] = this.words[i + s];
1979
- }
1980
- } else {
1981
- this.words[0] = 0;
1982
- this.length = 1;
1983
- }
1984
-
1985
- var carry = 0;
1986
- for (i = this.length - 1; i >= 0 && (carry !== 0 || i >= h); i--) {
1987
- var word = this.words[i] | 0;
1988
- this.words[i] = (carry << (26 - r)) | (word >>> r);
1989
- carry = word & mask;
1990
- }
1991
-
1992
- // Push carried bits as a mask
1993
- if (maskedWords && carry !== 0) {
1994
- maskedWords.words[maskedWords.length++] = carry;
1995
- }
1996
-
1997
- if (this.length === 0) {
1998
- this.words[0] = 0;
1999
- this.length = 1;
2000
- }
2001
-
2002
- return this._strip();
2003
- };
2004
-
2005
- BN.prototype.ishrn = function ishrn (bits, hint, extended) {
2006
- // TODO(indutny): implement me
2007
- assert(this.negative === 0);
2008
- return this.iushrn(bits, hint, extended);
2009
- };
2010
-
2011
- // Shift-left
2012
- BN.prototype.shln = function shln (bits) {
2013
- return this.clone().ishln(bits);
2014
- };
2015
-
2016
- BN.prototype.ushln = function ushln (bits) {
2017
- return this.clone().iushln(bits);
2018
- };
2019
-
2020
- // Shift-right
2021
- BN.prototype.shrn = function shrn (bits) {
2022
- return this.clone().ishrn(bits);
2023
- };
2024
-
2025
- BN.prototype.ushrn = function ushrn (bits) {
2026
- return this.clone().iushrn(bits);
2027
- };
2028
-
2029
- // Test if n bit is set
2030
- BN.prototype.testn = function testn (bit) {
2031
- assert(typeof bit === 'number' && bit >= 0);
2032
- var r = bit % 26;
2033
- var s = (bit - r) / 26;
2034
- var q = 1 << r;
2035
-
2036
- // Fast case: bit is much higher than all existing words
2037
- if (this.length <= s) return false;
2038
-
2039
- // Check bit and return
2040
- var w = this.words[s];
2041
-
2042
- return !!(w & q);
2043
- };
2044
-
2045
- // Return only lowers bits of number (in-place)
2046
- BN.prototype.imaskn = function imaskn (bits) {
2047
- assert(typeof bits === 'number' && bits >= 0);
2048
- var r = bits % 26;
2049
- var s = (bits - r) / 26;
2050
-
2051
- assert(this.negative === 0, 'imaskn works only with positive numbers');
2052
-
2053
- if (this.length <= s) {
2054
- return this;
2055
- }
2056
-
2057
- if (r !== 0) {
2058
- s++;
2059
- }
2060
- this.length = Math.min(s, this.length);
2061
-
2062
- if (r !== 0) {
2063
- var mask = 0x3ffffff ^ ((0x3ffffff >>> r) << r);
2064
- this.words[this.length - 1] &= mask;
2065
- }
2066
-
2067
- return this._strip();
2068
- };
2069
-
2070
- // Return only lowers bits of number
2071
- BN.prototype.maskn = function maskn (bits) {
2072
- return this.clone().imaskn(bits);
2073
- };
2074
-
2075
- // Add plain number `num` to `this`
2076
- BN.prototype.iaddn = function iaddn (num) {
2077
- assert(typeof num === 'number');
2078
- assert(num < 0x4000000);
2079
- if (num < 0) return this.isubn(-num);
2080
-
2081
- // Possible sign change
2082
- if (this.negative !== 0) {
2083
- if (this.length === 1 && (this.words[0] | 0) <= num) {
2084
- this.words[0] = num - (this.words[0] | 0);
2085
- this.negative = 0;
2086
- return this;
2087
- }
2088
-
2089
- this.negative = 0;
2090
- this.isubn(num);
2091
- this.negative = 1;
2092
- return this;
2093
- }
2094
-
2095
- // Add without checks
2096
- return this._iaddn(num);
2097
- };
2098
-
2099
- BN.prototype._iaddn = function _iaddn (num) {
2100
- this.words[0] += num;
2101
-
2102
- // Carry
2103
- for (var i = 0; i < this.length && this.words[i] >= 0x4000000; i++) {
2104
- this.words[i] -= 0x4000000;
2105
- if (i === this.length - 1) {
2106
- this.words[i + 1] = 1;
2107
- } else {
2108
- this.words[i + 1]++;
2109
- }
2110
- }
2111
- this.length = Math.max(this.length, i + 1);
2112
-
2113
- return this;
2114
- };
2115
-
2116
- // Subtract plain number `num` from `this`
2117
- BN.prototype.isubn = function isubn (num) {
2118
- assert(typeof num === 'number');
2119
- assert(num < 0x4000000);
2120
- if (num < 0) return this.iaddn(-num);
2121
-
2122
- if (this.negative !== 0) {
2123
- this.negative = 0;
2124
- this.iaddn(num);
2125
- this.negative = 1;
2126
- return this;
2127
- }
2128
-
2129
- this.words[0] -= num;
2130
-
2131
- if (this.length === 1 && this.words[0] < 0) {
2132
- this.words[0] = -this.words[0];
2133
- this.negative = 1;
2134
- } else {
2135
- // Carry
2136
- for (var i = 0; i < this.length && this.words[i] < 0; i++) {
2137
- this.words[i] += 0x4000000;
2138
- this.words[i + 1] -= 1;
2139
- }
2140
- }
2141
-
2142
- return this._strip();
2143
- };
2144
-
2145
- BN.prototype.addn = function addn (num) {
2146
- return this.clone().iaddn(num);
2147
- };
2148
-
2149
- BN.prototype.subn = function subn (num) {
2150
- return this.clone().isubn(num);
2151
- };
2152
-
2153
- BN.prototype.iabs = function iabs () {
2154
- this.negative = 0;
2155
-
2156
- return this;
2157
- };
2158
-
2159
- BN.prototype.abs = function abs () {
2160
- return this.clone().iabs();
2161
- };
2162
-
2163
- BN.prototype._ishlnsubmul = function _ishlnsubmul (num, mul, shift) {
2164
- var len = num.length + shift;
2165
- var i;
2166
-
2167
- this._expand(len);
2168
-
2169
- var w;
2170
- var carry = 0;
2171
- for (i = 0; i < num.length; i++) {
2172
- w = (this.words[i + shift] | 0) + carry;
2173
- var right = (num.words[i] | 0) * mul;
2174
- w -= right & 0x3ffffff;
2175
- carry = (w >> 26) - ((right / 0x4000000) | 0);
2176
- this.words[i + shift] = w & 0x3ffffff;
2177
- }
2178
- for (; i < this.length - shift; i++) {
2179
- w = (this.words[i + shift] | 0) + carry;
2180
- carry = w >> 26;
2181
- this.words[i + shift] = w & 0x3ffffff;
2182
- }
2183
-
2184
- if (carry === 0) return this._strip();
2185
-
2186
- // Subtraction overflow
2187
- assert(carry === -1);
2188
- carry = 0;
2189
- for (i = 0; i < this.length; i++) {
2190
- w = -(this.words[i] | 0) + carry;
2191
- carry = w >> 26;
2192
- this.words[i] = w & 0x3ffffff;
2193
- }
2194
- this.negative = 1;
2195
-
2196
- return this._strip();
2197
- };
2198
-
2199
- BN.prototype._wordDiv = function _wordDiv (num, mode) {
2200
- var shift = this.length - num.length;
2201
-
2202
- var a = this.clone();
2203
- var b = num;
2204
-
2205
- // Normalize
2206
- var bhi = b.words[b.length - 1] | 0;
2207
- var bhiBits = this._countBits(bhi);
2208
- shift = 26 - bhiBits;
2209
- if (shift !== 0) {
2210
- b = b.ushln(shift);
2211
- a.iushln(shift);
2212
- bhi = b.words[b.length - 1] | 0;
2213
- }
2214
-
2215
- // Initialize quotient
2216
- var m = a.length - b.length;
2217
- var q;
2218
-
2219
- if (mode !== 'mod') {
2220
- q = new BN(null);
2221
- q.length = m + 1;
2222
- q.words = new Array(q.length);
2223
- for (var i = 0; i < q.length; i++) {
2224
- q.words[i] = 0;
2225
- }
2226
- }
2227
-
2228
- var diff = a.clone()._ishlnsubmul(b, 1, m);
2229
- if (diff.negative === 0) {
2230
- a = diff;
2231
- if (q) {
2232
- q.words[m] = 1;
2233
- }
2234
- }
2235
-
2236
- for (var j = m - 1; j >= 0; j--) {
2237
- var qj = (a.words[b.length + j] | 0) * 0x4000000 +
2238
- (a.words[b.length + j - 1] | 0);
2239
-
2240
- // NOTE: (qj / bhi) is (0x3ffffff * 0x4000000 + 0x3ffffff) / 0x2000000 max
2241
- // (0x7ffffff)
2242
- qj = Math.min((qj / bhi) | 0, 0x3ffffff);
2243
-
2244
- a._ishlnsubmul(b, qj, j);
2245
- while (a.negative !== 0) {
2246
- qj--;
2247
- a.negative = 0;
2248
- a._ishlnsubmul(b, 1, j);
2249
- if (!a.isZero()) {
2250
- a.negative ^= 1;
2251
- }
2252
- }
2253
- if (q) {
2254
- q.words[j] = qj;
2255
- }
2256
- }
2257
- if (q) {
2258
- q._strip();
2259
- }
2260
- a._strip();
2261
-
2262
- // Denormalize
2263
- if (mode !== 'div' && shift !== 0) {
2264
- a.iushrn(shift);
2265
- }
2266
-
2267
- return {
2268
- div: q || null,
2269
- mod: a
2270
- };
2271
- };
2272
-
2273
- // NOTE: 1) `mode` can be set to `mod` to request mod only,
2274
- // to `div` to request div only, or be absent to
2275
- // request both div & mod
2276
- // 2) `positive` is true if unsigned mod is requested
2277
- BN.prototype.divmod = function divmod (num, mode, positive) {
2278
- assert(!num.isZero());
2279
-
2280
- if (this.isZero()) {
2281
- return {
2282
- div: new BN(0),
2283
- mod: new BN(0)
2284
- };
2285
- }
2286
-
2287
- var div, mod, res;
2288
- if (this.negative !== 0 && num.negative === 0) {
2289
- res = this.neg().divmod(num, mode);
2290
-
2291
- if (mode !== 'mod') {
2292
- div = res.div.neg();
2293
- }
2294
-
2295
- if (mode !== 'div') {
2296
- mod = res.mod.neg();
2297
- if (positive && mod.negative !== 0) {
2298
- mod.iadd(num);
2299
- }
2300
- }
2301
-
2302
- return {
2303
- div: div,
2304
- mod: mod
2305
- };
2306
- }
2307
-
2308
- if (this.negative === 0 && num.negative !== 0) {
2309
- res = this.divmod(num.neg(), mode);
2310
-
2311
- if (mode !== 'mod') {
2312
- div = res.div.neg();
2313
- }
2314
-
2315
- return {
2316
- div: div,
2317
- mod: res.mod
2318
- };
2319
- }
2320
-
2321
- if ((this.negative & num.negative) !== 0) {
2322
- res = this.neg().divmod(num.neg(), mode);
2323
-
2324
- if (mode !== 'div') {
2325
- mod = res.mod.neg();
2326
- if (positive && mod.negative !== 0) {
2327
- mod.isub(num);
2328
- }
2329
- }
2330
-
2331
- return {
2332
- div: res.div,
2333
- mod: mod
2334
- };
2335
- }
2336
-
2337
- // Both numbers are positive at this point
2338
-
2339
- // Strip both numbers to approximate shift value
2340
- if (num.length > this.length || this.cmp(num) < 0) {
2341
- return {
2342
- div: new BN(0),
2343
- mod: this
2344
- };
2345
- }
2346
-
2347
- // Very short reduction
2348
- if (num.length === 1) {
2349
- if (mode === 'div') {
2350
- return {
2351
- div: this.divn(num.words[0]),
2352
- mod: null
2353
- };
2354
- }
2355
-
2356
- if (mode === 'mod') {
2357
- return {
2358
- div: null,
2359
- mod: new BN(this.modrn(num.words[0]))
2360
- };
2361
- }
2362
-
2363
- return {
2364
- div: this.divn(num.words[0]),
2365
- mod: new BN(this.modrn(num.words[0]))
2366
- };
2367
- }
2368
-
2369
- return this._wordDiv(num, mode);
2370
- };
2371
-
2372
- // Find `this` / `num`
2373
- BN.prototype.div = function div (num) {
2374
- return this.divmod(num, 'div', false).div;
2375
- };
2376
-
2377
- // Find `this` % `num`
2378
- BN.prototype.mod = function mod (num) {
2379
- return this.divmod(num, 'mod', false).mod;
2380
- };
2381
-
2382
- BN.prototype.umod = function umod (num) {
2383
- return this.divmod(num, 'mod', true).mod;
2384
- };
2385
-
2386
- // Find Round(`this` / `num`)
2387
- BN.prototype.divRound = function divRound (num) {
2388
- var dm = this.divmod(num);
2389
-
2390
- // Fast case - exact division
2391
- if (dm.mod.isZero()) return dm.div;
2392
-
2393
- var mod = dm.div.negative !== 0 ? dm.mod.isub(num) : dm.mod;
2394
-
2395
- var half = num.ushrn(1);
2396
- var r2 = num.andln(1);
2397
- var cmp = mod.cmp(half);
2398
-
2399
- // Round down
2400
- if (cmp < 0 || (r2 === 1 && cmp === 0)) return dm.div;
2401
-
2402
- // Round up
2403
- return dm.div.negative !== 0 ? dm.div.isubn(1) : dm.div.iaddn(1);
2404
- };
2405
-
2406
- BN.prototype.modrn = function modrn (num) {
2407
- var isNegNum = num < 0;
2408
- if (isNegNum) num = -num;
2409
-
2410
- assert(num <= 0x3ffffff);
2411
- var p = (1 << 26) % num;
2412
-
2413
- var acc = 0;
2414
- for (var i = this.length - 1; i >= 0; i--) {
2415
- acc = (p * acc + (this.words[i] | 0)) % num;
2416
- }
2417
-
2418
- return isNegNum ? -acc : acc;
2419
- };
2420
-
2421
- // WARNING: DEPRECATED
2422
- BN.prototype.modn = function modn (num) {
2423
- return this.modrn(num);
2424
- };
2425
-
2426
- // In-place division by number
2427
- BN.prototype.idivn = function idivn (num) {
2428
- var isNegNum = num < 0;
2429
- if (isNegNum) num = -num;
2430
-
2431
- assert(num <= 0x3ffffff);
2432
-
2433
- var carry = 0;
2434
- for (var i = this.length - 1; i >= 0; i--) {
2435
- var w = (this.words[i] | 0) + carry * 0x4000000;
2436
- this.words[i] = (w / num) | 0;
2437
- carry = w % num;
2438
- }
2439
-
2440
- this._strip();
2441
- return isNegNum ? this.ineg() : this;
2442
- };
2443
-
2444
- BN.prototype.divn = function divn (num) {
2445
- return this.clone().idivn(num);
2446
- };
2447
-
2448
- BN.prototype.egcd = function egcd (p) {
2449
- assert(p.negative === 0);
2450
- assert(!p.isZero());
2451
-
2452
- var x = this;
2453
- var y = p.clone();
2454
-
2455
- if (x.negative !== 0) {
2456
- x = x.umod(p);
2457
- } else {
2458
- x = x.clone();
2459
- }
2460
-
2461
- // A * x + B * y = x
2462
- var A = new BN(1);
2463
- var B = new BN(0);
2464
-
2465
- // C * x + D * y = y
2466
- var C = new BN(0);
2467
- var D = new BN(1);
2468
-
2469
- var g = 0;
2470
-
2471
- while (x.isEven() && y.isEven()) {
2472
- x.iushrn(1);
2473
- y.iushrn(1);
2474
- ++g;
2475
- }
2476
-
2477
- var yp = y.clone();
2478
- var xp = x.clone();
2479
-
2480
- while (!x.isZero()) {
2481
- for (var i = 0, im = 1; (x.words[0] & im) === 0 && i < 26; ++i, im <<= 1);
2482
- if (i > 0) {
2483
- x.iushrn(i);
2484
- while (i-- > 0) {
2485
- if (A.isOdd() || B.isOdd()) {
2486
- A.iadd(yp);
2487
- B.isub(xp);
2488
- }
2489
-
2490
- A.iushrn(1);
2491
- B.iushrn(1);
2492
- }
2493
- }
2494
-
2495
- for (var j = 0, jm = 1; (y.words[0] & jm) === 0 && j < 26; ++j, jm <<= 1);
2496
- if (j > 0) {
2497
- y.iushrn(j);
2498
- while (j-- > 0) {
2499
- if (C.isOdd() || D.isOdd()) {
2500
- C.iadd(yp);
2501
- D.isub(xp);
2502
- }
2503
-
2504
- C.iushrn(1);
2505
- D.iushrn(1);
2506
- }
2507
- }
2508
-
2509
- if (x.cmp(y) >= 0) {
2510
- x.isub(y);
2511
- A.isub(C);
2512
- B.isub(D);
2513
- } else {
2514
- y.isub(x);
2515
- C.isub(A);
2516
- D.isub(B);
2517
- }
2518
- }
2519
-
2520
- return {
2521
- a: C,
2522
- b: D,
2523
- gcd: y.iushln(g)
2524
- };
2525
- };
2526
-
2527
- // This is reduced incarnation of the binary EEA
2528
- // above, designated to invert members of the
2529
- // _prime_ fields F(p) at a maximal speed
2530
- BN.prototype._invmp = function _invmp (p) {
2531
- assert(p.negative === 0);
2532
- assert(!p.isZero());
2533
-
2534
- var a = this;
2535
- var b = p.clone();
2536
-
2537
- if (a.negative !== 0) {
2538
- a = a.umod(p);
2539
- } else {
2540
- a = a.clone();
2541
- }
2542
-
2543
- var x1 = new BN(1);
2544
- var x2 = new BN(0);
2545
-
2546
- var delta = b.clone();
2547
-
2548
- while (a.cmpn(1) > 0 && b.cmpn(1) > 0) {
2549
- for (var i = 0, im = 1; (a.words[0] & im) === 0 && i < 26; ++i, im <<= 1);
2550
- if (i > 0) {
2551
- a.iushrn(i);
2552
- while (i-- > 0) {
2553
- if (x1.isOdd()) {
2554
- x1.iadd(delta);
2555
- }
2556
-
2557
- x1.iushrn(1);
2558
- }
2559
- }
2560
-
2561
- for (var j = 0, jm = 1; (b.words[0] & jm) === 0 && j < 26; ++j, jm <<= 1);
2562
- if (j > 0) {
2563
- b.iushrn(j);
2564
- while (j-- > 0) {
2565
- if (x2.isOdd()) {
2566
- x2.iadd(delta);
2567
- }
2568
-
2569
- x2.iushrn(1);
2570
- }
2571
- }
2572
-
2573
- if (a.cmp(b) >= 0) {
2574
- a.isub(b);
2575
- x1.isub(x2);
2576
- } else {
2577
- b.isub(a);
2578
- x2.isub(x1);
2579
- }
2580
- }
2581
-
2582
- var res;
2583
- if (a.cmpn(1) === 0) {
2584
- res = x1;
2585
- } else {
2586
- res = x2;
2587
- }
2588
-
2589
- if (res.cmpn(0) < 0) {
2590
- res.iadd(p);
2591
- }
2592
-
2593
- return res;
2594
- };
2595
-
2596
- BN.prototype.gcd = function gcd (num) {
2597
- if (this.isZero()) return num.abs();
2598
- if (num.isZero()) return this.abs();
2599
-
2600
- var a = this.clone();
2601
- var b = num.clone();
2602
- a.negative = 0;
2603
- b.negative = 0;
2604
-
2605
- // Remove common factor of two
2606
- for (var shift = 0; a.isEven() && b.isEven(); shift++) {
2607
- a.iushrn(1);
2608
- b.iushrn(1);
2609
- }
2610
-
2611
- do {
2612
- while (a.isEven()) {
2613
- a.iushrn(1);
2614
- }
2615
- while (b.isEven()) {
2616
- b.iushrn(1);
2617
- }
2618
-
2619
- var r = a.cmp(b);
2620
- if (r < 0) {
2621
- // Swap `a` and `b` to make `a` always bigger than `b`
2622
- var t = a;
2623
- a = b;
2624
- b = t;
2625
- } else if (r === 0 || b.cmpn(1) === 0) {
2626
- break;
2627
- }
2628
-
2629
- a.isub(b);
2630
- } while (true);
2631
-
2632
- return b.iushln(shift);
2633
- };
2634
-
2635
- // Invert number in the field F(num)
2636
- BN.prototype.invm = function invm (num) {
2637
- return this.egcd(num).a.umod(num);
2638
- };
2639
-
2640
- BN.prototype.isEven = function isEven () {
2641
- return (this.words[0] & 1) === 0;
2642
- };
2643
-
2644
- BN.prototype.isOdd = function isOdd () {
2645
- return (this.words[0] & 1) === 1;
2646
- };
2647
-
2648
- // And first word and num
2649
- BN.prototype.andln = function andln (num) {
2650
- return this.words[0] & num;
2651
- };
2652
-
2653
- // Increment at the bit position in-line
2654
- BN.prototype.bincn = function bincn (bit) {
2655
- assert(typeof bit === 'number');
2656
- var r = bit % 26;
2657
- var s = (bit - r) / 26;
2658
- var q = 1 << r;
2659
-
2660
- // Fast case: bit is much higher than all existing words
2661
- if (this.length <= s) {
2662
- this._expand(s + 1);
2663
- this.words[s] |= q;
2664
- return this;
2665
- }
2666
-
2667
- // Add bit and propagate, if needed
2668
- var carry = q;
2669
- for (var i = s; carry !== 0 && i < this.length; i++) {
2670
- var w = this.words[i] | 0;
2671
- w += carry;
2672
- carry = w >>> 26;
2673
- w &= 0x3ffffff;
2674
- this.words[i] = w;
2675
- }
2676
- if (carry !== 0) {
2677
- this.words[i] = carry;
2678
- this.length++;
2679
- }
2680
- return this;
2681
- };
2682
-
2683
- BN.prototype.isZero = function isZero () {
2684
- return this.length === 1 && this.words[0] === 0;
2685
- };
2686
-
2687
- BN.prototype.cmpn = function cmpn (num) {
2688
- var negative = num < 0;
2689
-
2690
- if (this.negative !== 0 && !negative) return -1;
2691
- if (this.negative === 0 && negative) return 1;
2692
-
2693
- this._strip();
2694
-
2695
- var res;
2696
- if (this.length > 1) {
2697
- res = 1;
2698
- } else {
2699
- if (negative) {
2700
- num = -num;
2701
- }
2702
-
2703
- assert(num <= 0x3ffffff, 'Number is too big');
2704
-
2705
- var w = this.words[0] | 0;
2706
- res = w === num ? 0 : w < num ? -1 : 1;
2707
- }
2708
- if (this.negative !== 0) return -res | 0;
2709
- return res;
2710
- };
2711
-
2712
- // Compare two numbers and return:
2713
- // 1 - if `this` > `num`
2714
- // 0 - if `this` == `num`
2715
- // -1 - if `this` < `num`
2716
- BN.prototype.cmp = function cmp (num) {
2717
- if (this.negative !== 0 && num.negative === 0) return -1;
2718
- if (this.negative === 0 && num.negative !== 0) return 1;
2719
-
2720
- var res = this.ucmp(num);
2721
- if (this.negative !== 0) return -res | 0;
2722
- return res;
2723
- };
2724
-
2725
- // Unsigned comparison
2726
- BN.prototype.ucmp = function ucmp (num) {
2727
- // At this point both numbers have the same sign
2728
- if (this.length > num.length) return 1;
2729
- if (this.length < num.length) return -1;
2730
-
2731
- var res = 0;
2732
- for (var i = this.length - 1; i >= 0; i--) {
2733
- var a = this.words[i] | 0;
2734
- var b = num.words[i] | 0;
2735
-
2736
- if (a === b) continue;
2737
- if (a < b) {
2738
- res = -1;
2739
- } else if (a > b) {
2740
- res = 1;
2741
- }
2742
- break;
2743
- }
2744
- return res;
2745
- };
2746
-
2747
- BN.prototype.gtn = function gtn (num) {
2748
- return this.cmpn(num) === 1;
2749
- };
2750
-
2751
- BN.prototype.gt = function gt (num) {
2752
- return this.cmp(num) === 1;
2753
- };
2754
-
2755
- BN.prototype.gten = function gten (num) {
2756
- return this.cmpn(num) >= 0;
2757
- };
2758
-
2759
- BN.prototype.gte = function gte (num) {
2760
- return this.cmp(num) >= 0;
2761
- };
2762
-
2763
- BN.prototype.ltn = function ltn (num) {
2764
- return this.cmpn(num) === -1;
2765
- };
2766
-
2767
- BN.prototype.lt = function lt (num) {
2768
- return this.cmp(num) === -1;
2769
- };
2770
-
2771
- BN.prototype.lten = function lten (num) {
2772
- return this.cmpn(num) <= 0;
2773
- };
2774
-
2775
- BN.prototype.lte = function lte (num) {
2776
- return this.cmp(num) <= 0;
2777
- };
2778
-
2779
- BN.prototype.eqn = function eqn (num) {
2780
- return this.cmpn(num) === 0;
2781
- };
2782
-
2783
- BN.prototype.eq = function eq (num) {
2784
- return this.cmp(num) === 0;
2785
- };
2786
-
2787
- //
2788
- // A reduce context, could be using montgomery or something better, depending
2789
- // on the `m` itself.
2790
- //
2791
- BN.red = function red (num) {
2792
- return new Red(num);
2793
- };
2794
-
2795
- BN.prototype.toRed = function toRed (ctx) {
2796
- assert(!this.red, 'Already a number in reduction context');
2797
- assert(this.negative === 0, 'red works only with positives');
2798
- return ctx.convertTo(this)._forceRed(ctx);
2799
- };
2800
-
2801
- BN.prototype.fromRed = function fromRed () {
2802
- assert(this.red, 'fromRed works only with numbers in reduction context');
2803
- return this.red.convertFrom(this);
2804
- };
2805
-
2806
- BN.prototype._forceRed = function _forceRed (ctx) {
2807
- this.red = ctx;
2808
- return this;
2809
- };
2810
-
2811
- BN.prototype.forceRed = function forceRed (ctx) {
2812
- assert(!this.red, 'Already a number in reduction context');
2813
- return this._forceRed(ctx);
2814
- };
2815
-
2816
- BN.prototype.redAdd = function redAdd (num) {
2817
- assert(this.red, 'redAdd works only with red numbers');
2818
- return this.red.add(this, num);
2819
- };
2820
-
2821
- BN.prototype.redIAdd = function redIAdd (num) {
2822
- assert(this.red, 'redIAdd works only with red numbers');
2823
- return this.red.iadd(this, num);
2824
- };
2825
-
2826
- BN.prototype.redSub = function redSub (num) {
2827
- assert(this.red, 'redSub works only with red numbers');
2828
- return this.red.sub(this, num);
2829
- };
2830
-
2831
- BN.prototype.redISub = function redISub (num) {
2832
- assert(this.red, 'redISub works only with red numbers');
2833
- return this.red.isub(this, num);
2834
- };
2835
-
2836
- BN.prototype.redShl = function redShl (num) {
2837
- assert(this.red, 'redShl works only with red numbers');
2838
- return this.red.shl(this, num);
2839
- };
2840
-
2841
- BN.prototype.redMul = function redMul (num) {
2842
- assert(this.red, 'redMul works only with red numbers');
2843
- this.red._verify2(this, num);
2844
- return this.red.mul(this, num);
2845
- };
2846
-
2847
- BN.prototype.redIMul = function redIMul (num) {
2848
- assert(this.red, 'redMul works only with red numbers');
2849
- this.red._verify2(this, num);
2850
- return this.red.imul(this, num);
2851
- };
2852
-
2853
- BN.prototype.redSqr = function redSqr () {
2854
- assert(this.red, 'redSqr works only with red numbers');
2855
- this.red._verify1(this);
2856
- return this.red.sqr(this);
2857
- };
2858
-
2859
- BN.prototype.redISqr = function redISqr () {
2860
- assert(this.red, 'redISqr works only with red numbers');
2861
- this.red._verify1(this);
2862
- return this.red.isqr(this);
2863
- };
2864
-
2865
- // Square root over p
2866
- BN.prototype.redSqrt = function redSqrt () {
2867
- assert(this.red, 'redSqrt works only with red numbers');
2868
- this.red._verify1(this);
2869
- return this.red.sqrt(this);
2870
- };
2871
-
2872
- BN.prototype.redInvm = function redInvm () {
2873
- assert(this.red, 'redInvm works only with red numbers');
2874
- this.red._verify1(this);
2875
- return this.red.invm(this);
2876
- };
2877
-
2878
- // Return negative clone of `this` % `red modulo`
2879
- BN.prototype.redNeg = function redNeg () {
2880
- assert(this.red, 'redNeg works only with red numbers');
2881
- this.red._verify1(this);
2882
- return this.red.neg(this);
2883
- };
2884
-
2885
- BN.prototype.redPow = function redPow (num) {
2886
- assert(this.red && !num.red, 'redPow(normalNum)');
2887
- this.red._verify1(this);
2888
- return this.red.pow(this, num);
2889
- };
2890
-
2891
- // Prime numbers with efficient reduction
2892
- var primes = {
2893
- k256: null,
2894
- p224: null,
2895
- p192: null,
2896
- p25519: null
2897
- };
2898
-
2899
- // Pseudo-Mersenne prime
2900
- function MPrime (name, p) {
2901
- // P = 2 ^ N - K
2902
- this.name = name;
2903
- this.p = new BN(p, 16);
2904
- this.n = this.p.bitLength();
2905
- this.k = new BN(1).iushln(this.n).isub(this.p);
2906
-
2907
- this.tmp = this._tmp();
2908
- }
2909
-
2910
- MPrime.prototype._tmp = function _tmp () {
2911
- var tmp = new BN(null);
2912
- tmp.words = new Array(Math.ceil(this.n / 13));
2913
- return tmp;
2914
- };
2915
-
2916
- MPrime.prototype.ireduce = function ireduce (num) {
2917
- // Assumes that `num` is less than `P^2`
2918
- // num = HI * (2 ^ N - K) + HI * K + LO = HI * K + LO (mod P)
2919
- var r = num;
2920
- var rlen;
2921
-
2922
- do {
2923
- this.split(r, this.tmp);
2924
- r = this.imulK(r);
2925
- r = r.iadd(this.tmp);
2926
- rlen = r.bitLength();
2927
- } while (rlen > this.n);
2928
-
2929
- var cmp = rlen < this.n ? -1 : r.ucmp(this.p);
2930
- if (cmp === 0) {
2931
- r.words[0] = 0;
2932
- r.length = 1;
2933
- } else if (cmp > 0) {
2934
- r.isub(this.p);
2935
- } else {
2936
- if (r.strip !== undefined) {
2937
- // r is a BN v4 instance
2938
- r.strip();
2939
- } else {
2940
- // r is a BN v5 instance
2941
- r._strip();
2942
- }
2943
- }
2944
-
2945
- return r;
2946
- };
2947
-
2948
- MPrime.prototype.split = function split (input, out) {
2949
- input.iushrn(this.n, 0, out);
2950
- };
2951
-
2952
- MPrime.prototype.imulK = function imulK (num) {
2953
- return num.imul(this.k);
2954
- };
2955
-
2956
- function K256 () {
2957
- MPrime.call(
2958
- this,
2959
- 'k256',
2960
- 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f');
2961
- }
2962
- inherits(K256, MPrime);
2963
-
2964
- K256.prototype.split = function split (input, output) {
2965
- // 256 = 9 * 26 + 22
2966
- var mask = 0x3fffff;
2967
-
2968
- var outLen = Math.min(input.length, 9);
2969
- for (var i = 0; i < outLen; i++) {
2970
- output.words[i] = input.words[i];
2971
- }
2972
- output.length = outLen;
2973
-
2974
- if (input.length <= 9) {
2975
- input.words[0] = 0;
2976
- input.length = 1;
2977
- return;
2978
- }
2979
-
2980
- // Shift by 9 limbs
2981
- var prev = input.words[9];
2982
- output.words[output.length++] = prev & mask;
2983
-
2984
- for (i = 10; i < input.length; i++) {
2985
- var next = input.words[i] | 0;
2986
- input.words[i - 10] = ((next & mask) << 4) | (prev >>> 22);
2987
- prev = next;
2988
- }
2989
- prev >>>= 22;
2990
- input.words[i - 10] = prev;
2991
- if (prev === 0 && input.length > 10) {
2992
- input.length -= 10;
2993
- } else {
2994
- input.length -= 9;
2995
- }
2996
- };
2997
-
2998
- K256.prototype.imulK = function imulK (num) {
2999
- // K = 0x1000003d1 = [ 0x40, 0x3d1 ]
3000
- num.words[num.length] = 0;
3001
- num.words[num.length + 1] = 0;
3002
- num.length += 2;
3003
-
3004
- // bounded at: 0x40 * 0x3ffffff + 0x3d0 = 0x100000390
3005
- var lo = 0;
3006
- for (var i = 0; i < num.length; i++) {
3007
- var w = num.words[i] | 0;
3008
- lo += w * 0x3d1;
3009
- num.words[i] = lo & 0x3ffffff;
3010
- lo = w * 0x40 + ((lo / 0x4000000) | 0);
3011
- }
3012
-
3013
- // Fast length reduction
3014
- if (num.words[num.length - 1] === 0) {
3015
- num.length--;
3016
- if (num.words[num.length - 1] === 0) {
3017
- num.length--;
3018
- }
3019
- }
3020
- return num;
3021
- };
3022
-
3023
- function P224 () {
3024
- MPrime.call(
3025
- this,
3026
- 'p224',
3027
- 'ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001');
3028
- }
3029
- inherits(P224, MPrime);
3030
-
3031
- function P192 () {
3032
- MPrime.call(
3033
- this,
3034
- 'p192',
3035
- 'ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff');
3036
- }
3037
- inherits(P192, MPrime);
3038
-
3039
- function P25519 () {
3040
- // 2 ^ 255 - 19
3041
- MPrime.call(
3042
- this,
3043
- '25519',
3044
- '7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed');
3045
- }
3046
- inherits(P25519, MPrime);
3047
-
3048
- P25519.prototype.imulK = function imulK (num) {
3049
- // K = 0x13
3050
- var carry = 0;
3051
- for (var i = 0; i < num.length; i++) {
3052
- var hi = (num.words[i] | 0) * 0x13 + carry;
3053
- var lo = hi & 0x3ffffff;
3054
- hi >>>= 26;
3055
-
3056
- num.words[i] = lo;
3057
- carry = hi;
3058
- }
3059
- if (carry !== 0) {
3060
- num.words[num.length++] = carry;
3061
- }
3062
- return num;
3063
- };
3064
-
3065
- // Exported mostly for testing purposes, use plain name instead
3066
- BN._prime = function prime (name) {
3067
- // Cached version of prime
3068
- if (primes[name]) return primes[name];
3069
-
3070
- var prime;
3071
- if (name === 'k256') {
3072
- prime = new K256();
3073
- } else if (name === 'p224') {
3074
- prime = new P224();
3075
- } else if (name === 'p192') {
3076
- prime = new P192();
3077
- } else if (name === 'p25519') {
3078
- prime = new P25519();
3079
- } else {
3080
- throw new Error('Unknown prime ' + name);
3081
- }
3082
- primes[name] = prime;
3083
-
3084
- return prime;
3085
- };
3086
-
3087
- //
3088
- // Base reduction engine
3089
- //
3090
- function Red (m) {
3091
- if (typeof m === 'string') {
3092
- var prime = BN._prime(m);
3093
- this.m = prime.p;
3094
- this.prime = prime;
3095
- } else {
3096
- assert(m.gtn(1), 'modulus must be greater than 1');
3097
- this.m = m;
3098
- this.prime = null;
3099
- }
3100
- }
3101
-
3102
- Red.prototype._verify1 = function _verify1 (a) {
3103
- assert(a.negative === 0, 'red works only with positives');
3104
- assert(a.red, 'red works only with red numbers');
3105
- };
3106
-
3107
- Red.prototype._verify2 = function _verify2 (a, b) {
3108
- assert((a.negative | b.negative) === 0, 'red works only with positives');
3109
- assert(a.red && a.red === b.red,
3110
- 'red works only with red numbers');
3111
- };
3112
-
3113
- Red.prototype.imod = function imod (a) {
3114
- if (this.prime) return this.prime.ireduce(a)._forceRed(this);
3115
-
3116
- move(a, a.umod(this.m)._forceRed(this));
3117
- return a;
3118
- };
3119
-
3120
- Red.prototype.neg = function neg (a) {
3121
- if (a.isZero()) {
3122
- return a.clone();
3123
- }
3124
-
3125
- return this.m.sub(a)._forceRed(this);
3126
- };
3127
-
3128
- Red.prototype.add = function add (a, b) {
3129
- this._verify2(a, b);
3130
-
3131
- var res = a.add(b);
3132
- if (res.cmp(this.m) >= 0) {
3133
- res.isub(this.m);
3134
- }
3135
- return res._forceRed(this);
3136
- };
3137
-
3138
- Red.prototype.iadd = function iadd (a, b) {
3139
- this._verify2(a, b);
3140
-
3141
- var res = a.iadd(b);
3142
- if (res.cmp(this.m) >= 0) {
3143
- res.isub(this.m);
3144
- }
3145
- return res;
3146
- };
3147
-
3148
- Red.prototype.sub = function sub (a, b) {
3149
- this._verify2(a, b);
3150
-
3151
- var res = a.sub(b);
3152
- if (res.cmpn(0) < 0) {
3153
- res.iadd(this.m);
3154
- }
3155
- return res._forceRed(this);
3156
- };
3157
-
3158
- Red.prototype.isub = function isub (a, b) {
3159
- this._verify2(a, b);
3160
-
3161
- var res = a.isub(b);
3162
- if (res.cmpn(0) < 0) {
3163
- res.iadd(this.m);
3164
- }
3165
- return res;
3166
- };
3167
-
3168
- Red.prototype.shl = function shl (a, num) {
3169
- this._verify1(a);
3170
- return this.imod(a.ushln(num));
3171
- };
3172
-
3173
- Red.prototype.imul = function imul (a, b) {
3174
- this._verify2(a, b);
3175
- return this.imod(a.imul(b));
3176
- };
3177
-
3178
- Red.prototype.mul = function mul (a, b) {
3179
- this._verify2(a, b);
3180
- return this.imod(a.mul(b));
3181
- };
3182
-
3183
- Red.prototype.isqr = function isqr (a) {
3184
- return this.imul(a, a.clone());
3185
- };
3186
-
3187
- Red.prototype.sqr = function sqr (a) {
3188
- return this.mul(a, a);
3189
- };
3190
-
3191
- Red.prototype.sqrt = function sqrt (a) {
3192
- if (a.isZero()) return a.clone();
3193
-
3194
- var mod3 = this.m.andln(3);
3195
- assert(mod3 % 2 === 1);
3196
-
3197
- // Fast case
3198
- if (mod3 === 3) {
3199
- var pow = this.m.add(new BN(1)).iushrn(2);
3200
- return this.pow(a, pow);
3201
- }
3202
-
3203
- // Tonelli-Shanks algorithm (Totally unoptimized and slow)
3204
- //
3205
- // Find Q and S, that Q * 2 ^ S = (P - 1)
3206
- var q = this.m.subn(1);
3207
- var s = 0;
3208
- while (!q.isZero() && q.andln(1) === 0) {
3209
- s++;
3210
- q.iushrn(1);
3211
- }
3212
- assert(!q.isZero());
3213
-
3214
- var one = new BN(1).toRed(this);
3215
- var nOne = one.redNeg();
3216
-
3217
- // Find quadratic non-residue
3218
- // NOTE: Max is such because of generalized Riemann hypothesis.
3219
- var lpow = this.m.subn(1).iushrn(1);
3220
- var z = this.m.bitLength();
3221
- z = new BN(2 * z * z).toRed(this);
3222
-
3223
- while (this.pow(z, lpow).cmp(nOne) !== 0) {
3224
- z.redIAdd(nOne);
3225
- }
3226
-
3227
- var c = this.pow(z, q);
3228
- var r = this.pow(a, q.addn(1).iushrn(1));
3229
- var t = this.pow(a, q);
3230
- var m = s;
3231
- while (t.cmp(one) !== 0) {
3232
- var tmp = t;
3233
- for (var i = 0; tmp.cmp(one) !== 0; i++) {
3234
- tmp = tmp.redSqr();
3235
- }
3236
- assert(i < m);
3237
- var b = this.pow(c, new BN(1).iushln(m - i - 1));
3238
-
3239
- r = r.redMul(b);
3240
- c = b.redSqr();
3241
- t = t.redMul(c);
3242
- m = i;
3243
- }
3244
-
3245
- return r;
3246
- };
3247
-
3248
- Red.prototype.invm = function invm (a) {
3249
- var inv = a._invmp(this.m);
3250
- if (inv.negative !== 0) {
3251
- inv.negative = 0;
3252
- return this.imod(inv).redNeg();
3253
- } else {
3254
- return this.imod(inv);
3255
- }
3256
- };
3257
-
3258
- Red.prototype.pow = function pow (a, num) {
3259
- if (num.isZero()) return new BN(1).toRed(this);
3260
- if (num.cmpn(1) === 0) return a.clone();
3261
-
3262
- var windowSize = 4;
3263
- var wnd = new Array(1 << windowSize);
3264
- wnd[0] = new BN(1).toRed(this);
3265
- wnd[1] = a;
3266
- for (var i = 2; i < wnd.length; i++) {
3267
- wnd[i] = this.mul(wnd[i - 1], a);
3268
- }
3269
-
3270
- var res = wnd[0];
3271
- var current = 0;
3272
- var currentLen = 0;
3273
- var start = num.bitLength() % 26;
3274
- if (start === 0) {
3275
- start = 26;
3276
- }
3277
-
3278
- for (i = num.length - 1; i >= 0; i--) {
3279
- var word = num.words[i];
3280
- for (var j = start - 1; j >= 0; j--) {
3281
- var bit = (word >> j) & 1;
3282
- if (res !== wnd[0]) {
3283
- res = this.sqr(res);
3284
- }
3285
-
3286
- if (bit === 0 && current === 0) {
3287
- currentLen = 0;
3288
- continue;
3289
- }
3290
-
3291
- current <<= 1;
3292
- current |= bit;
3293
- currentLen++;
3294
- if (currentLen !== windowSize && (i !== 0 || j !== 0)) continue;
3295
-
3296
- res = this.mul(res, wnd[current]);
3297
- currentLen = 0;
3298
- current = 0;
3299
- }
3300
- start = 26;
3301
- }
3302
-
3303
- return res;
3304
- };
3305
-
3306
- Red.prototype.convertTo = function convertTo (num) {
3307
- var r = num.umod(this.m);
3308
-
3309
- return r === num ? r.clone() : r;
3310
- };
3311
-
3312
- Red.prototype.convertFrom = function convertFrom (num) {
3313
- var res = num.clone();
3314
- res.red = null;
3315
- return res;
3316
- };
3317
-
3318
- //
3319
- // Montgomery method engine
3320
- //
3321
-
3322
- BN.mont = function mont (num) {
3323
- return new Mont(num);
3324
- };
3325
-
3326
- function Mont (m) {
3327
- Red.call(this, m);
3328
-
3329
- this.shift = this.m.bitLength();
3330
- if (this.shift % 26 !== 0) {
3331
- this.shift += 26 - (this.shift % 26);
3332
- }
3333
-
3334
- this.r = new BN(1).iushln(this.shift);
3335
- this.r2 = this.imod(this.r.sqr());
3336
- this.rinv = this.r._invmp(this.m);
3337
-
3338
- this.minv = this.rinv.mul(this.r).isubn(1).div(this.m);
3339
- this.minv = this.minv.umod(this.r);
3340
- this.minv = this.r.sub(this.minv);
3341
- }
3342
- inherits(Mont, Red);
3343
-
3344
- Mont.prototype.convertTo = function convertTo (num) {
3345
- return this.imod(num.ushln(this.shift));
3346
- };
3347
-
3348
- Mont.prototype.convertFrom = function convertFrom (num) {
3349
- var r = this.imod(num.mul(this.rinv));
3350
- r.red = null;
3351
- return r;
3352
- };
3353
-
3354
- Mont.prototype.imul = function imul (a, b) {
3355
- if (a.isZero() || b.isZero()) {
3356
- a.words[0] = 0;
3357
- a.length = 1;
3358
- return a;
3359
- }
3360
-
3361
- var t = a.imul(b);
3362
- var c = t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m);
3363
- var u = t.isub(c).iushrn(this.shift);
3364
- var res = u;
3365
-
3366
- if (u.cmp(this.m) >= 0) {
3367
- res = u.isub(this.m);
3368
- } else if (u.cmpn(0) < 0) {
3369
- res = u.iadd(this.m);
3370
- }
3371
-
3372
- return res._forceRed(this);
3373
- };
3374
-
3375
- Mont.prototype.mul = function mul (a, b) {
3376
- if (a.isZero() || b.isZero()) return new BN(0)._forceRed(this);
3377
-
3378
- var t = a.mul(b);
3379
- var c = t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m);
3380
- var u = t.isub(c).iushrn(this.shift);
3381
- var res = u;
3382
- if (u.cmp(this.m) >= 0) {
3383
- res = u.isub(this.m);
3384
- } else if (u.cmpn(0) < 0) {
3385
- res = u.iadd(this.m);
3386
- }
3387
-
3388
- return res._forceRed(this);
3389
- };
3390
-
3391
- Mont.prototype.invm = function invm (a) {
3392
- // (AR)^-1 * R^2 = (A^-1 * R^-1) * R^2 = A^-1 * R
3393
- var res = this.imod(a._invmp(this.m).mul(this.r2));
3394
- return res._forceRed(this);
3395
- };
3396
- })(module, commonjsGlobal);
3397
- } (bn));
3398
-
3399
- var _BN = bnExports;
3400
-
3401
- const version$3 = "logger/5.7.0";
3402
-
3403
- let _permanentCensorErrors = false;
3404
- let _censorErrors = false;
3405
- const LogLevels = { debug: 1, "default": 2, info: 2, warning: 3, error: 4, off: 5 };
3406
- let _logLevel = LogLevels["default"];
3407
- let _globalLogger = null;
3408
- function _checkNormalize() {
3409
- try {
3410
- const missing = [];
3411
- // Make sure all forms of normalization are supported
3412
- ["NFD", "NFC", "NFKD", "NFKC"].forEach((form) => {
3413
- try {
3414
- if ("test".normalize(form) !== "test") {
3415
- throw new Error("bad normalize");
3416
- }
3417
- ;
3418
- }
3419
- catch (error) {
3420
- missing.push(form);
3421
- }
3422
- });
3423
- if (missing.length) {
3424
- throw new Error("missing " + missing.join(", "));
3425
- }
3426
- if (String.fromCharCode(0xe9).normalize("NFD") !== String.fromCharCode(0x65, 0x0301)) {
3427
- throw new Error("broken implementation");
3428
- }
3429
- }
3430
- catch (error) {
3431
- return error.message;
3432
- }
3433
- return null;
3434
- }
3435
- const _normalizeError = _checkNormalize();
3436
- var LogLevel;
3437
- (function (LogLevel) {
3438
- LogLevel["DEBUG"] = "DEBUG";
3439
- LogLevel["INFO"] = "INFO";
3440
- LogLevel["WARNING"] = "WARNING";
3441
- LogLevel["ERROR"] = "ERROR";
3442
- LogLevel["OFF"] = "OFF";
3443
- })(LogLevel || (LogLevel = {}));
3444
- var ErrorCode;
3445
- (function (ErrorCode) {
3446
- ///////////////////
3447
- // Generic Errors
3448
- // Unknown Error
3449
- ErrorCode["UNKNOWN_ERROR"] = "UNKNOWN_ERROR";
3450
- // Not Implemented
3451
- ErrorCode["NOT_IMPLEMENTED"] = "NOT_IMPLEMENTED";
3452
- // Unsupported Operation
3453
- // - operation
3454
- ErrorCode["UNSUPPORTED_OPERATION"] = "UNSUPPORTED_OPERATION";
3455
- // Network Error (i.e. Ethereum Network, such as an invalid chain ID)
3456
- // - event ("noNetwork" is not re-thrown in provider.ready; otherwise thrown)
3457
- ErrorCode["NETWORK_ERROR"] = "NETWORK_ERROR";
3458
- // Some sort of bad response from the server
3459
- ErrorCode["SERVER_ERROR"] = "SERVER_ERROR";
3460
- // Timeout
3461
- ErrorCode["TIMEOUT"] = "TIMEOUT";
3462
- ///////////////////
3463
- // Operational Errors
3464
- // Buffer Overrun
3465
- ErrorCode["BUFFER_OVERRUN"] = "BUFFER_OVERRUN";
3466
- // Numeric Fault
3467
- // - operation: the operation being executed
3468
- // - fault: the reason this faulted
3469
- ErrorCode["NUMERIC_FAULT"] = "NUMERIC_FAULT";
3470
- ///////////////////
3471
- // Argument Errors
3472
- // Missing new operator to an object
3473
- // - name: The name of the class
3474
- ErrorCode["MISSING_NEW"] = "MISSING_NEW";
3475
- // Invalid argument (e.g. value is incompatible with type) to a function:
3476
- // - argument: The argument name that was invalid
3477
- // - value: The value of the argument
3478
- ErrorCode["INVALID_ARGUMENT"] = "INVALID_ARGUMENT";
3479
- // Missing argument to a function:
3480
- // - count: The number of arguments received
3481
- // - expectedCount: The number of arguments expected
3482
- ErrorCode["MISSING_ARGUMENT"] = "MISSING_ARGUMENT";
3483
- // Too many arguments
3484
- // - count: The number of arguments received
3485
- // - expectedCount: The number of arguments expected
3486
- ErrorCode["UNEXPECTED_ARGUMENT"] = "UNEXPECTED_ARGUMENT";
3487
- ///////////////////
3488
- // Blockchain Errors
3489
- // Call exception
3490
- // - transaction: the transaction
3491
- // - address?: the contract address
3492
- // - args?: The arguments passed into the function
3493
- // - method?: The Solidity method signature
3494
- // - errorSignature?: The EIP848 error signature
3495
- // - errorArgs?: The EIP848 error parameters
3496
- // - reason: The reason (only for EIP848 "Error(string)")
3497
- ErrorCode["CALL_EXCEPTION"] = "CALL_EXCEPTION";
3498
- // Insufficient funds (< value + gasLimit * gasPrice)
3499
- // - transaction: the transaction attempted
3500
- ErrorCode["INSUFFICIENT_FUNDS"] = "INSUFFICIENT_FUNDS";
3501
- // Nonce has already been used
3502
- // - transaction: the transaction attempted
3503
- ErrorCode["NONCE_EXPIRED"] = "NONCE_EXPIRED";
3504
- // The replacement fee for the transaction is too low
3505
- // - transaction: the transaction attempted
3506
- ErrorCode["REPLACEMENT_UNDERPRICED"] = "REPLACEMENT_UNDERPRICED";
3507
- // The gas limit could not be estimated
3508
- // - transaction: the transaction passed to estimateGas
3509
- ErrorCode["UNPREDICTABLE_GAS_LIMIT"] = "UNPREDICTABLE_GAS_LIMIT";
3510
- // The transaction was replaced by one with a higher gas price
3511
- // - reason: "cancelled", "replaced" or "repriced"
3512
- // - cancelled: true if reason == "cancelled" or reason == "replaced")
3513
- // - hash: original transaction hash
3514
- // - replacement: the full TransactionsResponse for the replacement
3515
- // - receipt: the receipt of the replacement
3516
- ErrorCode["TRANSACTION_REPLACED"] = "TRANSACTION_REPLACED";
3517
- ///////////////////
3518
- // Interaction Errors
3519
- // The user rejected the action, such as signing a message or sending
3520
- // a transaction
3521
- ErrorCode["ACTION_REJECTED"] = "ACTION_REJECTED";
3522
- })(ErrorCode || (ErrorCode = {}));
3523
- const HEX = "0123456789abcdef";
3524
- class Logger {
3525
- constructor(version) {
3526
- Object.defineProperty(this, "version", {
3527
- enumerable: true,
3528
- value: version,
3529
- writable: false
3530
- });
3531
- }
3532
- _log(logLevel, args) {
3533
- const level = logLevel.toLowerCase();
3534
- if (LogLevels[level] == null) {
3535
- this.throwArgumentError("invalid log level name", "logLevel", logLevel);
3536
- }
3537
- if (_logLevel > LogLevels[level]) {
3538
- return;
3539
- }
3540
- console.log.apply(console, args);
3541
- }
3542
- debug(...args) {
3543
- this._log(Logger.levels.DEBUG, args);
3544
- }
3545
- info(...args) {
3546
- this._log(Logger.levels.INFO, args);
3547
- }
3548
- warn(...args) {
3549
- this._log(Logger.levels.WARNING, args);
3550
- }
3551
- makeError(message, code, params) {
3552
- // Errors are being censored
3553
- if (_censorErrors) {
3554
- return this.makeError("censored error", code, {});
3555
- }
3556
- if (!code) {
3557
- code = Logger.errors.UNKNOWN_ERROR;
3558
- }
3559
- if (!params) {
3560
- params = {};
3561
- }
3562
- const messageDetails = [];
3563
- Object.keys(params).forEach((key) => {
3564
- const value = params[key];
3565
- try {
3566
- if (value instanceof Uint8Array) {
3567
- let hex = "";
3568
- for (let i = 0; i < value.length; i++) {
3569
- hex += HEX[value[i] >> 4];
3570
- hex += HEX[value[i] & 0x0f];
3571
- }
3572
- messageDetails.push(key + "=Uint8Array(0x" + hex + ")");
3573
- }
3574
- else {
3575
- messageDetails.push(key + "=" + JSON.stringify(value));
3576
- }
3577
- }
3578
- catch (error) {
3579
- messageDetails.push(key + "=" + JSON.stringify(params[key].toString()));
3580
- }
3581
- });
3582
- messageDetails.push(`code=${code}`);
3583
- messageDetails.push(`version=${this.version}`);
3584
- const reason = message;
3585
- let url = "";
3586
- switch (code) {
3587
- case ErrorCode.NUMERIC_FAULT: {
3588
- url = "NUMERIC_FAULT";
3589
- const fault = message;
3590
- switch (fault) {
3591
- case "overflow":
3592
- case "underflow":
3593
- case "division-by-zero":
3594
- url += "-" + fault;
3595
- break;
3596
- case "negative-power":
3597
- case "negative-width":
3598
- url += "-unsupported";
3599
- break;
3600
- case "unbound-bitwise-result":
3601
- url += "-unbound-result";
3602
- break;
3603
- }
3604
- break;
3605
- }
3606
- case ErrorCode.CALL_EXCEPTION:
3607
- case ErrorCode.INSUFFICIENT_FUNDS:
3608
- case ErrorCode.MISSING_NEW:
3609
- case ErrorCode.NONCE_EXPIRED:
3610
- case ErrorCode.REPLACEMENT_UNDERPRICED:
3611
- case ErrorCode.TRANSACTION_REPLACED:
3612
- case ErrorCode.UNPREDICTABLE_GAS_LIMIT:
3613
- url = code;
3614
- break;
3615
- }
3616
- if (url) {
3617
- message += " [ See: https:/\/links.ethers.org/v5-errors-" + url + " ]";
3618
- }
3619
- if (messageDetails.length) {
3620
- message += " (" + messageDetails.join(", ") + ")";
3621
- }
3622
- // @TODO: Any??
3623
- const error = new Error(message);
3624
- error.reason = reason;
3625
- error.code = code;
3626
- Object.keys(params).forEach(function (key) {
3627
- error[key] = params[key];
3628
- });
3629
- return error;
3630
- }
3631
- throwError(message, code, params) {
3632
- throw this.makeError(message, code, params);
3633
- }
3634
- throwArgumentError(message, name, value) {
3635
- return this.throwError(message, Logger.errors.INVALID_ARGUMENT, {
3636
- argument: name,
3637
- value: value
3638
- });
3639
- }
3640
- assert(condition, message, code, params) {
3641
- if (!!condition) {
3642
- return;
3643
- }
3644
- this.throwError(message, code, params);
3645
- }
3646
- assertArgument(condition, message, name, value) {
3647
- if (!!condition) {
3648
- return;
3649
- }
3650
- this.throwArgumentError(message, name, value);
3651
- }
3652
- checkNormalize(message) {
3653
- if (_normalizeError) {
3654
- this.throwError("platform missing String.prototype.normalize", Logger.errors.UNSUPPORTED_OPERATION, {
3655
- operation: "String.prototype.normalize", form: _normalizeError
3656
- });
3657
- }
3658
- }
3659
- checkSafeUint53(value, message) {
3660
- if (typeof (value) !== "number") {
3661
- return;
3662
- }
3663
- if (message == null) {
3664
- message = "value not safe";
3665
- }
3666
- if (value < 0 || value >= 0x1fffffffffffff) {
3667
- this.throwError(message, Logger.errors.NUMERIC_FAULT, {
3668
- operation: "checkSafeInteger",
3669
- fault: "out-of-safe-range",
3670
- value: value
3671
- });
3672
- }
3673
- if (value % 1) {
3674
- this.throwError(message, Logger.errors.NUMERIC_FAULT, {
3675
- operation: "checkSafeInteger",
3676
- fault: "non-integer",
3677
- value: value
3678
- });
3679
- }
3680
- }
3681
- checkArgumentCount(count, expectedCount, message) {
3682
- if (message) {
3683
- message = ": " + message;
3684
- }
3685
- else {
3686
- message = "";
3687
- }
3688
- if (count < expectedCount) {
3689
- this.throwError("missing argument" + message, Logger.errors.MISSING_ARGUMENT, {
3690
- count: count,
3691
- expectedCount: expectedCount
3692
- });
3693
- }
3694
- if (count > expectedCount) {
3695
- this.throwError("too many arguments" + message, Logger.errors.UNEXPECTED_ARGUMENT, {
3696
- count: count,
3697
- expectedCount: expectedCount
3698
- });
3699
- }
3700
- }
3701
- checkNew(target, kind) {
3702
- if (target === Object || target == null) {
3703
- this.throwError("missing new", Logger.errors.MISSING_NEW, { name: kind.name });
3704
- }
3705
- }
3706
- checkAbstract(target, kind) {
3707
- if (target === kind) {
3708
- this.throwError("cannot instantiate abstract class " + JSON.stringify(kind.name) + " directly; use a sub-class", Logger.errors.UNSUPPORTED_OPERATION, { name: target.name, operation: "new" });
3709
- }
3710
- else if (target === Object || target == null) {
3711
- this.throwError("missing new", Logger.errors.MISSING_NEW, { name: kind.name });
3712
- }
3713
- }
3714
- static globalLogger() {
3715
- if (!_globalLogger) {
3716
- _globalLogger = new Logger(version$3);
3717
- }
3718
- return _globalLogger;
3719
- }
3720
- static setCensorship(censorship, permanent) {
3721
- if (!censorship && permanent) {
3722
- this.globalLogger().throwError("cannot permanently disable censorship", Logger.errors.UNSUPPORTED_OPERATION, {
3723
- operation: "setCensorship"
3724
- });
3725
- }
3726
- if (_permanentCensorErrors) {
3727
- if (!censorship) {
3728
- return;
3729
- }
3730
- this.globalLogger().throwError("error censorship permanent", Logger.errors.UNSUPPORTED_OPERATION, {
3731
- operation: "setCensorship"
3732
- });
3733
- }
3734
- _censorErrors = !!censorship;
3735
- _permanentCensorErrors = !!permanent;
3736
- }
3737
- static setLogLevel(logLevel) {
3738
- const level = LogLevels[logLevel.toLowerCase()];
3739
- if (level == null) {
3740
- Logger.globalLogger().warn("invalid log level - " + logLevel);
3741
- return;
3742
- }
3743
- _logLevel = level;
3744
- }
3745
- static from(version) {
3746
- return new Logger(version);
3747
- }
3748
- }
3749
- Logger.errors = ErrorCode;
3750
- Logger.levels = LogLevel;
3751
-
3752
- const version$2 = "bytes/5.7.0";
3753
-
3754
- const logger$3 = new Logger(version$2);
3755
- ///////////////////////////////
3756
- function isHexable(value) {
3757
- return !!(value.toHexString);
3758
- }
3759
- function addSlice(array) {
3760
- if (array.slice) {
3761
- return array;
3762
- }
3763
- array.slice = function () {
3764
- const args = Array.prototype.slice.call(arguments);
3765
- return addSlice(new Uint8Array(Array.prototype.slice.apply(array, args)));
3766
- };
3767
- return array;
3768
- }
3769
- function isInteger(value) {
3770
- return (typeof (value) === "number" && value == value && (value % 1) === 0);
3771
- }
3772
- function isBytes(value) {
3773
- if (value == null) {
3774
- return false;
3775
- }
3776
- if (value.constructor === Uint8Array) {
3777
- return true;
3778
- }
3779
- if (typeof (value) === "string") {
3780
- return false;
3781
- }
3782
- if (!isInteger(value.length) || value.length < 0) {
3783
- return false;
3784
- }
3785
- for (let i = 0; i < value.length; i++) {
3786
- const v = value[i];
3787
- if (!isInteger(v) || v < 0 || v >= 256) {
3788
- return false;
3789
- }
3790
- }
3791
- return true;
3792
- }
3793
- function arrayify(value, options) {
3794
- if (!options) {
3795
- options = {};
3796
- }
3797
- if (typeof (value) === "number") {
3798
- logger$3.checkSafeUint53(value, "invalid arrayify value");
3799
- const result = [];
3800
- while (value) {
3801
- result.unshift(value & 0xff);
3802
- value = parseInt(String(value / 256));
3803
- }
3804
- if (result.length === 0) {
3805
- result.push(0);
3806
- }
3807
- return addSlice(new Uint8Array(result));
3808
- }
3809
- if (options.allowMissingPrefix && typeof (value) === "string" && value.substring(0, 2) !== "0x") {
3810
- value = "0x" + value;
3811
- }
3812
- if (isHexable(value)) {
3813
- value = value.toHexString();
3814
- }
3815
- if (isHexString(value)) {
3816
- let hex = value.substring(2);
3817
- if (hex.length % 2) {
3818
- if (options.hexPad === "left") {
3819
- hex = "0" + hex;
3820
- }
3821
- else if (options.hexPad === "right") {
3822
- hex += "0";
3823
- }
3824
- else {
3825
- logger$3.throwArgumentError("hex data is odd-length", "value", value);
3826
- }
3827
- }
3828
- const result = [];
3829
- for (let i = 0; i < hex.length; i += 2) {
3830
- result.push(parseInt(hex.substring(i, i + 2), 16));
3831
- }
3832
- return addSlice(new Uint8Array(result));
3833
- }
3834
- if (isBytes(value)) {
3835
- return addSlice(new Uint8Array(value));
3836
- }
3837
- return logger$3.throwArgumentError("invalid arrayify value", "value", value);
3838
- }
3839
- function isHexString(value, length) {
3840
- if (typeof (value) !== "string" || !value.match(/^0x[0-9A-Fa-f]*$/)) {
3841
- return false;
3842
- }
3843
- if (length && value.length !== 2 + 2 * length) {
3844
- return false;
3845
- }
3846
- return true;
3847
- }
3848
- const HexCharacters = "0123456789abcdef";
3849
- function hexlify(value, options) {
3850
- if (!options) {
3851
- options = {};
3852
- }
3853
- if (typeof (value) === "number") {
3854
- logger$3.checkSafeUint53(value, "invalid hexlify value");
3855
- let hex = "";
3856
- while (value) {
3857
- hex = HexCharacters[value & 0xf] + hex;
3858
- value = Math.floor(value / 16);
3859
- }
3860
- if (hex.length) {
3861
- if (hex.length % 2) {
3862
- hex = "0" + hex;
3863
- }
3864
- return "0x" + hex;
3865
- }
3866
- return "0x00";
3867
- }
3868
- if (typeof (value) === "bigint") {
3869
- value = value.toString(16);
3870
- if (value.length % 2) {
3871
- return ("0x0" + value);
3872
- }
3873
- return "0x" + value;
3874
- }
3875
- if (options.allowMissingPrefix && typeof (value) === "string" && value.substring(0, 2) !== "0x") {
3876
- value = "0x" + value;
3877
- }
3878
- if (isHexable(value)) {
3879
- return value.toHexString();
3880
- }
3881
- if (isHexString(value)) {
3882
- if (value.length % 2) {
3883
- if (options.hexPad === "left") {
3884
- value = "0x0" + value.substring(2);
3885
- }
3886
- else if (options.hexPad === "right") {
3887
- value += "0";
3888
- }
3889
- else {
3890
- logger$3.throwArgumentError("hex data is odd-length", "value", value);
3891
- }
3892
- }
3893
- return value.toLowerCase();
3894
- }
3895
- if (isBytes(value)) {
3896
- let result = "0x";
3897
- for (let i = 0; i < value.length; i++) {
3898
- let v = value[i];
3899
- result += HexCharacters[(v & 0xf0) >> 4] + HexCharacters[v & 0x0f];
3900
- }
3901
- return result;
3902
- }
3903
- return logger$3.throwArgumentError("invalid hexlify value", "value", value);
3904
- }
3905
- function hexZeroPad(value, length) {
3906
- if (typeof (value) !== "string") {
3907
- value = hexlify(value);
3908
- }
3909
- else if (!isHexString(value)) {
3910
- logger$3.throwArgumentError("invalid hex string", "value", value);
3911
- }
3912
- if (value.length > 2 * length + 2) {
3913
- logger$3.throwArgumentError("value out of range", "value", arguments[1]);
3914
- }
3915
- while (value.length < 2 * length + 2) {
3916
- value = "0x0" + value.substring(2);
3917
- }
3918
- return value;
3919
- }
3920
-
3921
- const version$1 = "bignumber/5.7.0";
3922
-
3923
- var BN = _BN.BN;
3924
- const logger$2 = new Logger(version$1);
3925
- const _constructorGuard$1 = {};
3926
- const MAX_SAFE = 0x1fffffffffffff;
3927
- function isBigNumberish(value) {
3928
- return (value != null) && (BigNumber.isBigNumber(value) ||
3929
- (typeof (value) === "number" && (value % 1) === 0) ||
3930
- (typeof (value) === "string" && !!value.match(/^-?[0-9]+$/)) ||
3931
- isHexString(value) ||
3932
- (typeof (value) === "bigint") ||
3933
- isBytes(value));
3934
- }
3935
- // Only warn about passing 10 into radix once
3936
- let _warnedToStringRadix = false;
3937
- class BigNumber {
3938
- constructor(constructorGuard, hex) {
3939
- if (constructorGuard !== _constructorGuard$1) {
3940
- logger$2.throwError("cannot call constructor directly; use BigNumber.from", Logger.errors.UNSUPPORTED_OPERATION, {
3941
- operation: "new (BigNumber)"
3942
- });
3943
- }
3944
- this._hex = hex;
3945
- this._isBigNumber = true;
3946
- Object.freeze(this);
3947
- }
3948
- fromTwos(value) {
3949
- return toBigNumber(toBN(this).fromTwos(value));
3950
- }
3951
- toTwos(value) {
3952
- return toBigNumber(toBN(this).toTwos(value));
3953
- }
3954
- abs() {
3955
- if (this._hex[0] === "-") {
3956
- return BigNumber.from(this._hex.substring(1));
3957
- }
3958
- return this;
3959
- }
3960
- add(other) {
3961
- return toBigNumber(toBN(this).add(toBN(other)));
3962
- }
3963
- sub(other) {
3964
- return toBigNumber(toBN(this).sub(toBN(other)));
3965
- }
3966
- div(other) {
3967
- const o = BigNumber.from(other);
3968
- if (o.isZero()) {
3969
- throwFault$1("division-by-zero", "div");
3970
- }
3971
- return toBigNumber(toBN(this).div(toBN(other)));
3972
- }
3973
- mul(other) {
3974
- return toBigNumber(toBN(this).mul(toBN(other)));
3975
- }
3976
- mod(other) {
3977
- const value = toBN(other);
3978
- if (value.isNeg()) {
3979
- throwFault$1("division-by-zero", "mod");
3980
- }
3981
- return toBigNumber(toBN(this).umod(value));
3982
- }
3983
- pow(other) {
3984
- const value = toBN(other);
3985
- if (value.isNeg()) {
3986
- throwFault$1("negative-power", "pow");
3987
- }
3988
- return toBigNumber(toBN(this).pow(value));
3989
- }
3990
- and(other) {
3991
- const value = toBN(other);
3992
- if (this.isNegative() || value.isNeg()) {
3993
- throwFault$1("unbound-bitwise-result", "and");
3994
- }
3995
- return toBigNumber(toBN(this).and(value));
3996
- }
3997
- or(other) {
3998
- const value = toBN(other);
3999
- if (this.isNegative() || value.isNeg()) {
4000
- throwFault$1("unbound-bitwise-result", "or");
4001
- }
4002
- return toBigNumber(toBN(this).or(value));
4003
- }
4004
- xor(other) {
4005
- const value = toBN(other);
4006
- if (this.isNegative() || value.isNeg()) {
4007
- throwFault$1("unbound-bitwise-result", "xor");
4008
- }
4009
- return toBigNumber(toBN(this).xor(value));
4010
- }
4011
- mask(value) {
4012
- if (this.isNegative() || value < 0) {
4013
- throwFault$1("negative-width", "mask");
4014
- }
4015
- return toBigNumber(toBN(this).maskn(value));
4016
- }
4017
- shl(value) {
4018
- if (this.isNegative() || value < 0) {
4019
- throwFault$1("negative-width", "shl");
4020
- }
4021
- return toBigNumber(toBN(this).shln(value));
4022
- }
4023
- shr(value) {
4024
- if (this.isNegative() || value < 0) {
4025
- throwFault$1("negative-width", "shr");
4026
- }
4027
- return toBigNumber(toBN(this).shrn(value));
4028
- }
4029
- eq(other) {
4030
- return toBN(this).eq(toBN(other));
4031
- }
4032
- lt(other) {
4033
- return toBN(this).lt(toBN(other));
4034
- }
4035
- lte(other) {
4036
- return toBN(this).lte(toBN(other));
4037
- }
4038
- gt(other) {
4039
- return toBN(this).gt(toBN(other));
4040
- }
4041
- gte(other) {
4042
- return toBN(this).gte(toBN(other));
4043
- }
4044
- isNegative() {
4045
- return (this._hex[0] === "-");
4046
- }
4047
- isZero() {
4048
- return toBN(this).isZero();
4049
- }
4050
- toNumber() {
4051
- try {
4052
- return toBN(this).toNumber();
4053
- }
4054
- catch (error) {
4055
- throwFault$1("overflow", "toNumber", this.toString());
4056
- }
4057
- return null;
4058
- }
4059
- toBigInt() {
4060
- try {
4061
- return BigInt(this.toString());
4062
- }
4063
- catch (e) { }
4064
- return logger$2.throwError("this platform does not support BigInt", Logger.errors.UNSUPPORTED_OPERATION, {
4065
- value: this.toString()
4066
- });
4067
- }
4068
- toString() {
4069
- // Lots of people expect this, which we do not support, so check (See: #889)
4070
- if (arguments.length > 0) {
4071
- if (arguments[0] === 10) {
4072
- if (!_warnedToStringRadix) {
4073
- _warnedToStringRadix = true;
4074
- logger$2.warn("BigNumber.toString does not accept any parameters; base-10 is assumed");
4075
- }
4076
- }
4077
- else if (arguments[0] === 16) {
4078
- logger$2.throwError("BigNumber.toString does not accept any parameters; use bigNumber.toHexString()", Logger.errors.UNEXPECTED_ARGUMENT, {});
4079
- }
4080
- else {
4081
- logger$2.throwError("BigNumber.toString does not accept parameters", Logger.errors.UNEXPECTED_ARGUMENT, {});
4082
- }
4083
- }
4084
- return toBN(this).toString(10);
4085
- }
4086
- toHexString() {
4087
- return this._hex;
4088
- }
4089
- toJSON(key) {
4090
- return { type: "BigNumber", hex: this.toHexString() };
4091
- }
4092
- static from(value) {
4093
- if (value instanceof BigNumber) {
4094
- return value;
4095
- }
4096
- if (typeof (value) === "string") {
4097
- if (value.match(/^-?0x[0-9a-f]+$/i)) {
4098
- return new BigNumber(_constructorGuard$1, toHex(value));
4099
- }
4100
- if (value.match(/^-?[0-9]+$/)) {
4101
- return new BigNumber(_constructorGuard$1, toHex(new BN(value)));
4102
- }
4103
- return logger$2.throwArgumentError("invalid BigNumber string", "value", value);
4104
- }
4105
- if (typeof (value) === "number") {
4106
- if (value % 1) {
4107
- throwFault$1("underflow", "BigNumber.from", value);
4108
- }
4109
- if (value >= MAX_SAFE || value <= -MAX_SAFE) {
4110
- throwFault$1("overflow", "BigNumber.from", value);
4111
- }
4112
- return BigNumber.from(String(value));
4113
- }
4114
- const anyValue = value;
4115
- if (typeof (anyValue) === "bigint") {
4116
- return BigNumber.from(anyValue.toString());
4117
- }
4118
- if (isBytes(anyValue)) {
4119
- return BigNumber.from(hexlify(anyValue));
4120
- }
4121
- if (anyValue) {
4122
- // Hexable interface (takes priority)
4123
- if (anyValue.toHexString) {
4124
- const hex = anyValue.toHexString();
4125
- if (typeof (hex) === "string") {
4126
- return BigNumber.from(hex);
4127
- }
4128
- }
4129
- else {
4130
- // For now, handle legacy JSON-ified values (goes away in v6)
4131
- let hex = anyValue._hex;
4132
- // New-form JSON
4133
- if (hex == null && anyValue.type === "BigNumber") {
4134
- hex = anyValue.hex;
4135
- }
4136
- if (typeof (hex) === "string") {
4137
- if (isHexString(hex) || (hex[0] === "-" && isHexString(hex.substring(1)))) {
4138
- return BigNumber.from(hex);
4139
- }
4140
- }
4141
- }
4142
- }
4143
- return logger$2.throwArgumentError("invalid BigNumber value", "value", value);
4144
- }
4145
- static isBigNumber(value) {
4146
- return !!(value && value._isBigNumber);
4147
- }
4148
- }
4149
- // Normalize the hex string
4150
- function toHex(value) {
4151
- // For BN, call on the hex string
4152
- if (typeof (value) !== "string") {
4153
- return toHex(value.toString(16));
4154
- }
4155
- // If negative, prepend the negative sign to the normalized positive value
4156
- if (value[0] === "-") {
4157
- // Strip off the negative sign
4158
- value = value.substring(1);
4159
- // Cannot have multiple negative signs (e.g. "--0x04")
4160
- if (value[0] === "-") {
4161
- logger$2.throwArgumentError("invalid hex", "value", value);
4162
- }
4163
- // Call toHex on the positive component
4164
- value = toHex(value);
4165
- // Do not allow "-0x00"
4166
- if (value === "0x00") {
4167
- return value;
4168
- }
4169
- // Negate the value
4170
- return "-" + value;
4171
- }
4172
- // Add a "0x" prefix if missing
4173
- if (value.substring(0, 2) !== "0x") {
4174
- value = "0x" + value;
4175
- }
4176
- // Normalize zero
4177
- if (value === "0x") {
4178
- return "0x00";
4179
- }
4180
- // Make the string even length
4181
- if (value.length % 2) {
4182
- value = "0x0" + value.substring(2);
4183
- }
4184
- // Trim to smallest even-length string
4185
- while (value.length > 4 && value.substring(0, 4) === "0x00") {
4186
- value = "0x" + value.substring(4);
4187
- }
4188
- return value;
4189
- }
4190
- function toBigNumber(value) {
4191
- return BigNumber.from(toHex(value));
4192
- }
4193
- function toBN(value) {
4194
- const hex = BigNumber.from(value).toHexString();
4195
- if (hex[0] === "-") {
4196
- return (new BN("-" + hex.substring(3), 16));
4197
- }
4198
- return new BN(hex.substring(2), 16);
4199
- }
4200
- function throwFault$1(fault, operation, value) {
4201
- const params = { fault: fault, operation: operation };
4202
- if (value != null) {
4203
- params.value = value;
4204
- }
4205
- return logger$2.throwError(fault, Logger.errors.NUMERIC_FAULT, params);
4206
- }
1
+ import { B as BigNumber, L as Logger, v as version$1, h as hexZeroPad, i as isBigNumberish, a as arrayify, b as isBytes, C as ContractMessage, T as TransactionMessage, c as CodecHash, d as BlockMessage, e as BWMessage, f as BWRequestMessage } from './contract-32687834.js';
4207
2
 
4208
3
  const logger$1 = new Logger(version$1);
4209
4
  const _constructorGuard = {};
@@ -4593,16 +388,16 @@ function parseUnits(value, unitName) {
4593
388
  return parseFixed(value, (unitName != null) ? unitName : 18);
4594
389
  }
4595
390
 
4596
- const byteFormats = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
4597
-
4598
- const formatBytes = (bytes, decimals = 2) => {
4599
- if (bytes === 0) return '0 Bytes';
4600
- if (decimals < 0) decimals = 0;
4601
-
4602
- const k = 1024;
4603
- const i = Math.floor(Math.log(bytes) / Math.log(k));
4604
-
4605
- return `${parseFloat((bytes / Math.pow(k, i)).toFixed(decimals))} ${byteFormats[i]}`
391
+ const byteFormats = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
392
+
393
+ const formatBytes = (bytes, decimals = 2) => {
394
+ if (bytes === 0) return '0 Bytes';
395
+ if (decimals < 0) decimals = 0;
396
+
397
+ const k = 1024;
398
+ const i = Math.floor(Math.log(bytes) / Math.log(k));
399
+
400
+ return `${parseFloat((bytes / Math.pow(k, i)).toFixed(decimals))} ${byteFormats[i]}`
4606
401
  };
4607
402
 
4608
403
  var contractFactory$2 = "IHNY2GQHKD3V4U2EF6P4TIHJNRQNDJ3N3AVXV6YGD6F2T3CNLMXWFU2LAC5";
@@ -4755,7 +550,7 @@ class Machine {
4755
550
  resolve(this);
4756
551
  };
4757
552
  pubsub.subscribe('machine.ready', machineReady);
4758
- this.worker = await new EasyWorker('node_modules/@leofcoin/workers/src/machine-worker.js', { serialization: 'advanced', type: 'module' });
553
+ this.worker = await new EasyWorker('./exports/browser/workers/machine-worker.js', { serialization: 'advanced', type: 'module' });
4759
554
  this.worker.onmessage(this.#onmessage.bind(this));
4760
555
  // const blocks = await blockStore.values()
4761
556
  const contracts = await Promise.all([
@@ -4923,23 +718,16 @@ const createContractMessage = async (creator, contract, constructorParameters =
4923
718
  constructorParameters
4924
719
  });
4925
720
  };
4926
- const calculateFee = async (transaction) => {
721
+ const calculateFee = async (transaction, format = false) => {
4927
722
  // excluded from fees
4928
723
  if (transaction.to === validators$1)
4929
724
  return 0;
4930
- // fee per gb
4931
725
  transaction = await new TransactionMessage(transaction);
4932
- let fee = transaction.encoded.length;
4933
- fee = fee / 1024;
4934
- fee = fee / 1000000;
4935
- const parts = String(fee).split('.');
4936
- let decimals = 0;
4937
- if (parts[1]) {
4938
- const potentional = parts[1].split('e');
4939
- parts[1] = potentional[0];
4940
- decimals = Number(potentional[1].replace(/\-|\+/g, '')) + Number(potentional[0].length);
4941
- }
4942
- return Number.parseFloat(fee.toString()).toFixed(decimals);
726
+ let fee = parseUnits(String(transaction.encoded.length));
727
+ // fee per gb
728
+ fee = fee.div(1073741824);
729
+ // fee = fee.div(1000000)
730
+ return format ? formatUnits(fee.toString()) : fee;
4943
731
  };
4944
732
  const createTransactionHash = async (transaction) => (await new CodecHash(transaction, { name: 'transaction-message' })).digest;
4945
733
  const signTransaction = async (transaction, wallet) => {
@@ -12065,11 +7853,16 @@ class Contract extends Transaction {
12065
7853
  }
12066
7854
  return this.createTransactionFrom(peernet.selectedAccount, addresses.contractFactory, 'registerContract', [await message.hash()]);
12067
7855
  }
7856
+ async deployContractMessage(message) {
7857
+ }
12068
7858
  }
12069
7859
 
12070
7860
  globalThis.BigNumber = BigNumber;
12071
7861
  // check if browser or local
12072
7862
  class Chain extends Contract {
7863
+ #state;
7864
+ id;
7865
+ utils;
12073
7866
  /** {Address[]} */
12074
7867
  #validators = [];
12075
7868
  /** {Block[]} */
@@ -12151,7 +7944,7 @@ class Chain extends Contract {
12151
7944
  return [...this.#blocks];
12152
7945
  }
12153
7946
  async hasTransactionToHandle() {
12154
- const size = await transactionPoolStore.size();
7947
+ const size = await globalThis.transactionPoolStore.size();
12155
7948
  if (size > 0)
12156
7949
  return true;
12157
7950
  return false;
@@ -12161,7 +7954,7 @@ class Chain extends Contract {
12161
7954
  console.log('epoch');
12162
7955
  const validators = await this.staticCall(addresses.validators, 'validators');
12163
7956
  console.log({ validators });
12164
- if (!validators[globalThis.peernet.selectedAccount]?.active)
7957
+ if (!validators[globalThis.globalThis.peernet.selectedAccount]?.active)
12165
7958
  return;
12166
7959
  const start = Date.now();
12167
7960
  try {
@@ -12194,7 +7987,7 @@ class Chain extends Contract {
12194
7987
  await Promise.all(contracts.map(async ({ address, message }) => {
12195
7988
  // console.log({message});
12196
7989
  message = await new ContractMessage(Uint8Array.from(message.split(',').map(string => Number(string))));
12197
- await contractStore.put(address, message.encoded);
7990
+ await globalThis.contractStore.put(address, message.encoded);
12198
7991
  }));
12199
7992
  console.log('handle native contracts');
12200
7993
  // handle native contracts
@@ -12203,14 +7996,14 @@ class Chain extends Contract {
12203
7996
  return new Promise(async (resolve, reject) => {
12204
7997
  const timeout = setTimeout(() => {
12205
7998
  resolve([{ index: 0, hash: '0x0' }]);
12206
- debug('sync timed out');
7999
+ globalThis.debug('sync timed out');
12207
8000
  }, 10_000);
12208
8001
  promises = await Promise.allSettled(promises);
12209
8002
  promises = promises.filter(({ status }) => status === 'fulfilled');
12210
8003
  clearTimeout(timeout);
12211
8004
  if (promises.length > 0) {
12212
8005
  promises = promises.map(async ({ value }) => {
12213
- const node = await new peernet.protos['peernet-response'](value.result);
8006
+ const node = await new globalThis.peernet.protos['peernet-response'](value.result);
12214
8007
  return { value: node.decoded.response, peer: value.peer };
12215
8008
  });
12216
8009
  promises = await Promise.all(promises);
@@ -12226,10 +8019,10 @@ class Chain extends Contract {
12226
8019
  }
12227
8020
  async #getLatestBlock() {
12228
8021
  let promises = [];
12229
- let data = await new peernet.protos['peernet-request']({ request: 'lastBlock' });
12230
- let node = await peernet.prepareMessage(data);
12231
- for (const peer of peernet?.connections) {
12232
- if (peer.connected && peer.readyState === 'open' && peer.peerId !== this.id) {
8022
+ let data = await new globalThis.peernet.protos['peernet-request']({ request: 'lastBlock' });
8023
+ let node = await globalThis.peernet.prepareMessage(data);
8024
+ for (const peer of globalThis.peernet?.connections) {
8025
+ if (peer.connected) {
12233
8026
  promises.push(async () => {
12234
8027
  try {
12235
8028
  const result = await peer.request(node.encoded);
@@ -12240,7 +8033,11 @@ class Chain extends Contract {
12240
8033
  }
12241
8034
  });
12242
8035
  }
12243
- else if (!peer.connected || peer.readyState !== 'open') ;
8036
+ else if (!peer.connected) {
8037
+ globalThis.peernet.removePeer(peer);
8038
+ // todo: remove peer
8039
+ // reinitiate channel?
8040
+ }
12244
8041
  }
12245
8042
  promises = await this.promiseRequests(promises);
12246
8043
  let latest = { index: 0, hash: '0x0', previousHash: '0x0' };
@@ -12248,18 +8045,18 @@ class Chain extends Contract {
12248
8045
  if (promises.length > 0)
12249
8046
  latest = promises[0].value;
12250
8047
  if (latest.hash && latest.hash !== '0x0') {
12251
- let message = await peernet.get(latest.hash, 'block');
8048
+ let message = await globalThis.peernet.get(latest.hash, 'block');
12252
8049
  message = await new BlockMessage(message);
12253
8050
  const hash = await message.hash();
12254
8051
  if (hash !== latest.hash)
12255
8052
  throw new Error('invalid block @getLatestBlock');
12256
- let data = await new peernet.protos['peernet-request']({ request: 'knownBlocks' });
12257
- let node = await peernet.prepareMessage(data);
8053
+ let data = await new globalThis.peernet.protos['peernet-request']({ request: 'knownBlocks' });
8054
+ let node = await globalThis.peernet.prepareMessage(data);
12258
8055
  const peer = promises[0].peer;
12259
8056
  latest = { ...message.decoded, hash };
12260
8057
  if (peer.connected && peer.readyState === 'open' && peer.peerId !== this.id) {
12261
8058
  let message = await peer.request(node);
12262
- message = await new peernet.protos['peernet-response'](message);
8059
+ message = await new globalThis.peernet.protos['peernet-response'](message);
12263
8060
  this.#knownBlocks = message.decoded.response;
12264
8061
  }
12265
8062
  }
@@ -12269,33 +8066,37 @@ class Chain extends Contract {
12269
8066
  // this.node = await new Node()
12270
8067
  this.#participants = [];
12271
8068
  this.#participating = false;
12272
- const initialized = await contractStore.has(addresses.contractFactory);
8069
+ const initialized = await globalThis.contractStore.has(addresses.contractFactory);
12273
8070
  if (!initialized)
12274
8071
  await this.#setup();
12275
8072
  this.utils = { BigNumber, formatUnits, parseUnits };
12276
- this.state = new State();
12277
- await peernet.addRequestHandler('bw-request-message', () => {
12278
- return new BWMessage(peernet.client.bw) || { up: 0, down: 0 };
8073
+ this.#state = new State();
8074
+ await globalThis.peernet.addRequestHandler('bw-request-message', () => {
8075
+ return new BWMessage(globalThis.peernet.client.bw) || { up: 0, down: 0 };
12279
8076
  });
12280
- await peernet.addRequestHandler('lastBlock', this.#lastBlockHandler.bind(this));
12281
- await peernet.addRequestHandler('knownBlocks', this.#knownBlocksHandler.bind(this));
12282
- peernet.subscribe('add-block', this.#addBlock.bind(this));
12283
- peernet.subscribe('add-transaction', this.#addTransaction.bind(this));
12284
- peernet.subscribe('validator:timeout', this.#validatorTimeout.bind(this));
12285
- pubsub.subscribe('peer:connected', this.#peerConnected.bind(this));
8077
+ // await globalThis.peernet.addRequestHandler('peerId', () => {
8078
+ // let node =
8079
+ // globalThis.peernet.protos['peernet-response']({response: node.encoded})
8080
+ // })
8081
+ await globalThis.peernet.addRequestHandler('lastBlock', this.#lastBlockHandler.bind(this));
8082
+ await globalThis.peernet.addRequestHandler('knownBlocks', this.#knownBlocksHandler.bind(this));
8083
+ globalThis.peernet.subscribe('add-block', this.#addBlock.bind(this));
8084
+ globalThis.peernet.subscribe('add-transaction', this.#addTransaction.bind(this));
8085
+ globalThis.peernet.subscribe('validator:timeout', this.#validatorTimeout.bind(this));
8086
+ globalThis.pubsub.subscribe('peer:connected', this.#peerConnected.bind(this));
12286
8087
  // todo some functions rely on state
12287
8088
  try {
12288
8089
  let localBlock;
12289
8090
  try {
12290
- localBlock = await chainStore.get('lastBlock');
8091
+ localBlock = await globalThis.chainStore.get('lastBlock');
12291
8092
  }
12292
8093
  catch {
12293
- await chainStore.put('lastBlock', '0x0');
12294
- localBlock = await chainStore.get('lastBlock');
8094
+ await globalThis.chainStore.put('lastBlock', '0x0');
8095
+ localBlock = await globalThis.chainStore.get('lastBlock');
12295
8096
  }
12296
8097
  localBlock = new TextDecoder().decode(localBlock);
12297
8098
  if (localBlock && localBlock !== '0x0') {
12298
- localBlock = await peernet.get(localBlock, 'block');
8099
+ localBlock = await globalThis.peernet.get(localBlock, 'block');
12299
8100
  localBlock = await new BlockMessage(localBlock);
12300
8101
  this.#lastBlock = { ...localBlock.decoded, hash: await localBlock.hash() };
12301
8102
  }
@@ -12313,15 +8114,22 @@ class Chain extends Contract {
12313
8114
  await this.resolveBlocks();
12314
8115
  this.#machine = await new Machine(this.#blocks);
12315
8116
  await this.#loadBlocks(this.#blocks);
12316
- globalThis.pubsub.publish('chain:ready', true);
8117
+ globalThis.globalThis.pubsub.publish('chain:ready', true);
12317
8118
  return this;
12318
8119
  }
12319
8120
  async #validatorTimeout(validatorInfo) {
12320
8121
  setTimeout(() => {
12321
- this.#jail.splice(this.jail.indexOf(validatorInfo.address), 1);
8122
+ this.#jail.splice(this.#jail.indexOf(validatorInfo.address), 1);
12322
8123
  }, validatorInfo.timeout);
12323
8124
  this.#jail.push(validatorInfo.address);
12324
8125
  }
8126
+ async triggerSync() {
8127
+ if (this.#chainSyncing)
8128
+ return 'already syncing';
8129
+ const latest = await this.#getLatestBlock();
8130
+ await this.#syncChain(latest);
8131
+ return 'synced';
8132
+ }
12325
8133
  async #syncChain(lastBlock) {
12326
8134
  if (this.#chainSyncing || !lastBlock || !lastBlock.hash || !lastBlock.hash)
12327
8135
  return;
@@ -12329,7 +8137,7 @@ class Chain extends Contract {
12329
8137
  if (this.#knownBlocks?.length === Number(lastBlock.index) + 1) {
12330
8138
  let promises = [];
12331
8139
  promises = await Promise.allSettled(this.#knownBlocks.map(async (address) => {
12332
- const has = await peernet.has(address, 'block');
8140
+ const has = await globalThis.peernet.has(address, 'block');
12333
8141
  return { has, address };
12334
8142
  }));
12335
8143
  promises = promises.filter(({ status, value }) => status === 'fulfilled' && !value.has);
@@ -12341,53 +8149,58 @@ class Chain extends Contract {
12341
8149
  const index = lastBlock.index;
12342
8150
  await this.resolveBlock(lastBlock.hash);
12343
8151
  let blocksSynced = localIndex > 0 ? (localIndex > index ? localIndex - index : index - localIndex) : index;
12344
- debug(`synced ${blocksSynced} ${blocksSynced > 1 ? 'blocks' : 'block'}`);
8152
+ globalThis.debug(`synced ${blocksSynced} ${blocksSynced > 1 ? 'blocks' : 'block'}`);
12345
8153
  const start = (this.#blocks.length - blocksSynced) - 1;
12346
- await this.#loadBlocks(this.blocks.slice(start));
8154
+ if (this.#machine)
8155
+ await this.#loadBlocks(this.blocks.slice(start));
12347
8156
  await this.#updateState(new BlockMessage(this.#blocks[this.#blocks.length - 1]));
12348
8157
  }
12349
8158
  this.#chainSyncing = false;
12350
8159
  }
12351
8160
  async #peerConnected(peer) {
12352
- let node = await new peernet.protos['peernet-request']({ request: 'lastBlock' });
12353
- node = await peernet.prepareMessage(node);
8161
+ let node = await new globalThis.peernet.protos['peernet-request']({ request: 'lastBlock' });
8162
+ node = await globalThis.peernet.prepareMessage(node);
12354
8163
  let response = await peer.request(node.encoded);
12355
- response = await new globalThis.peernet.protos['peernet-response'](response);
8164
+ response = await new globalThis.globalThis.peernet.protos['peernet-response'](new Uint8Array(Object.values(response)));
12356
8165
  let lastBlock = response.decoded.response;
12357
8166
  // try catch known blocks
12358
- node = await new peernet.protos['peernet-request']({ request: 'knownBlocks' });
12359
- node = await peernet.prepareMessage(node);
8167
+ node = await new globalThis.peernet.protos['peernet-request']({ request: 'knownBlocks' });
8168
+ node = await globalThis.peernet.prepareMessage(node);
12360
8169
  response = await peer.request(node.encoded);
12361
- response = await new globalThis.peernet.protos['peernet-response'](response);
8170
+ response = await new globalThis.globalThis.peernet.protos['peernet-response'](new Uint8Array(Object.values(response)));
12362
8171
  this.#knownBlocks = response.decoded.response;
12363
8172
  this.#syncChain(lastBlock);
12364
8173
  }
12365
8174
  #epochTimeout;
12366
8175
  async #lastBlockHandler() {
12367
- return new peernet.protos['peernet-response']({ response: { hash: this.#lastBlock?.hash, index: this.#lastBlock?.index } });
8176
+ return new globalThis.peernet.protos['peernet-response']({ response: { hash: this.#lastBlock?.hash, index: this.#lastBlock?.index } });
12368
8177
  }
12369
8178
  async #knownBlocksHandler() {
12370
- return new peernet.protos['peernet-response']({ response: { blocks: this.#blocks.map((block) => block.hash) } });
8179
+ return new globalThis.peernet.protos['peernet-response']({ response: { blocks: this.#blocks.map((block) => block.hash) } });
12371
8180
  }
12372
8181
  async getAndPutBlock(hash) {
12373
- let block = await peernet.get(hash, 'block');
8182
+ let block = await globalThis.peernet.get(hash, 'block');
12374
8183
  block = await new BlockMessage(block);
12375
8184
  const { index } = block.decoded;
12376
8185
  if (this.#blocks[index] && this.#blocks[index].hash !== block.hash)
12377
8186
  throw `invalid block ${hash} @${index}`;
12378
- if (!await peernet.has(hash, 'block'))
12379
- await peernet.put(hash, block.encoded, 'block');
8187
+ if (!await globalThis.peernet.has(hash, 'block'))
8188
+ await globalThis.peernet.put(hash, block.encoded, 'block');
12380
8189
  return block;
12381
8190
  }
12382
8191
  async resolveBlock(hash) {
12383
8192
  if (!hash)
12384
8193
  throw new Error(`expected hash, got: ${hash}`);
8194
+ if (hash === '0x0')
8195
+ return;
12385
8196
  const index = this.#blockHashMap.get(hash);
12386
8197
  if (this.#blocks[index]) {
12387
8198
  if (this.#blocks[index].previousHash !== '0x0') {
12388
- return this.resolveBlock(this.#blocks[index]);
8199
+ return this.resolveBlock(this.#blocks[index].previousHash);
8200
+ }
8201
+ else {
8202
+ return;
12389
8203
  }
12390
- return;
12391
8204
  }
12392
8205
  try {
12393
8206
  const block = await this.getAndPutBlock(hash);
@@ -12407,14 +8220,14 @@ class Chain extends Contract {
12407
8220
  }
12408
8221
  async resolveBlocks() {
12409
8222
  try {
12410
- const localBlock = await chainStore.get('lastBlock');
8223
+ const localBlock = await globalThis.chainStore.get('lastBlock');
12411
8224
  const hash = new TextDecoder().decode(localBlock);
12412
8225
  if (hash && hash !== '0x0')
12413
8226
  await this.resolveBlock(hash);
12414
8227
  this.#lastBlock = this.#blocks[this.#blocks.length - 1];
12415
8228
  }
12416
8229
  catch {
12417
- await chainStore.put('lastBlock', new TextEncoder().encode('0x0'));
8230
+ await globalThis.chainStore.put('lastBlock', new TextEncoder().encode('0x0'));
12418
8231
  return this.resolveBlocks();
12419
8232
  // console.log(e);
12420
8233
  }
@@ -12445,7 +8258,7 @@ class Chain extends Contract {
12445
8258
  }
12446
8259
  }
12447
8260
  this.#blocks[block.index].loaded = true;
12448
- debug(`loaded block: ${block.hash} @${block.index}`);
8261
+ globalThis.debug(`loaded block: ${block.hash} @${block.index}`);
12449
8262
  }
12450
8263
  }
12451
8264
  }
@@ -12453,25 +8266,24 @@ class Chain extends Contract {
12453
8266
  try {
12454
8267
  let result = await this.#machine.execute(to, method, params, from, nonce);
12455
8268
  // if (!result) result = this.#machine.state
12456
- pubsub.publish(`transaction.completed.${hash}`, { status: 'fulfilled', hash });
8269
+ globalThis.pubsub.publish(`transaction.completed.${hash}`, { status: 'fulfilled', hash });
12457
8270
  return result || 'no state change';
12458
8271
  }
12459
8272
  catch (error) {
12460
8273
  console.log(error);
12461
- pubsub.publish(`transaction.completed.${hash}`, { status: 'fail', hash, error: error });
8274
+ globalThis.pubsub.publish(`transaction.completed.${hash}`, { status: 'fail', hash, error: error });
12462
8275
  throw error;
12463
8276
  }
12464
8277
  }
12465
8278
  async #addBlock(block) {
12466
- // console.log(block);
12467
8279
  const blockMessage = await new BlockMessage(block);
12468
8280
  await Promise.all(blockMessage.decoded.transactions
12469
- .map(async (transaction) => transactionPoolStore.delete(transaction.hash)));
8281
+ .map(async (transaction) => globalThis.transactionPoolStore.delete(transaction.hash)));
12470
8282
  const hash = await blockMessage.hash();
12471
- await blockStore.put(hash, blockMessage.encoded);
8283
+ await globalThis.blockStore.put(hash, blockMessage.encoded);
12472
8284
  if (this.lastBlock.index < blockMessage.decoded.index)
12473
8285
  await this.#updateState(blockMessage);
12474
- debug(`added block: ${hash}`);
8286
+ globalThis.debug(`added block: ${hash}`);
12475
8287
  let promises = [];
12476
8288
  let contracts = [];
12477
8289
  for (let transaction of blockMessage.decoded.transactions) {
@@ -12485,10 +8297,10 @@ class Chain extends Contract {
12485
8297
  try {
12486
8298
  promises = await Promise.allSettled(promises);
12487
8299
  for (let transaction of blockMessage.decoded.transactions) {
12488
- pubsub.publish('transaction-processed', transaction);
12489
- if (transaction.to === peernet.selectedAccount)
12490
- pubsub.publish('account-transaction-processed', transaction);
12491
- await accountsStore.put(transaction.from, String(transaction.nonce));
8300
+ globalThis.pubsub.publish('transaction-processed', transaction);
8301
+ if (transaction.to === globalThis.peernet.selectedAccount)
8302
+ globalThis.pubsub.publish('account-transaction-processed', transaction);
8303
+ await globalThis.accountsStore.put(transaction.from, String(transaction.nonce));
12492
8304
  }
12493
8305
  // todo finish state
12494
8306
  // for (const contract of contracts) {
@@ -12496,7 +8308,7 @@ class Chain extends Contract {
12496
8308
  // // await stateStore.put(contract, state)
12497
8309
  // console.log(state);
12498
8310
  // }
12499
- pubsub.publish('block-processed', blockMessage.decoded);
8311
+ globalThis.pubsub.publish('block-processed', blockMessage.decoded);
12500
8312
  }
12501
8313
  catch (error) {
12502
8314
  console.log({ e: error });
@@ -12506,7 +8318,7 @@ class Chain extends Contract {
12506
8318
  const hash = await message.hash();
12507
8319
  this.#lastBlock = { hash, ...message.decoded };
12508
8320
  // await this.state.updateState(message)
12509
- await chainStore.put('lastBlock', hash);
8321
+ await globalThis.chainStore.put('lastBlock', hash);
12510
8322
  }
12511
8323
  async participate(address) {
12512
8324
  // TODO: validate participant
@@ -12525,7 +8337,7 @@ class Chain extends Contract {
12525
8337
  nonce: (await this.getNonce(address)) + 1,
12526
8338
  timestamp: Date.now()
12527
8339
  };
12528
- const transaction = await signTransaction(rawTransaction, peernet.identity);
8340
+ const transaction = await signTransaction(rawTransaction, globalThis.peernet.identity);
12529
8341
  await this.sendTransaction(transaction);
12530
8342
  }
12531
8343
  if (await this.hasTransactionToHandle() && !this.#runningEpoch)
@@ -12534,15 +8346,19 @@ class Chain extends Contract {
12534
8346
  // todo filter tx that need to wait on prev nonce
12535
8347
  async #createBlock(limit = 1800) {
12536
8348
  // vote for transactions
12537
- if (await transactionPoolStore.size() === 0)
8349
+ if (await globalThis.transactionPoolStore.size() === 0)
12538
8350
  return;
12539
- let transactions = await transactionPoolStore.values(this.transactionLimit);
8351
+ let transactions = await globalThis.transactionPoolStore.values(this.transactionLimit);
12540
8352
  if (Object.keys(transactions)?.length === 0)
12541
8353
  return;
12542
8354
  let block = {
12543
8355
  transactions: [],
12544
8356
  validators: [],
12545
- fees: BigNumber.from(0)
8357
+ fees: BigNumber.from(0),
8358
+ timestamp: Date.now(),
8359
+ previousHash: '',
8360
+ reward: parseUnits('150'),
8361
+ index: 0
12546
8362
  };
12547
8363
  // exclude failing tx
12548
8364
  transactions = await this.promiseTransactions(transactions);
@@ -12552,11 +8368,11 @@ class Chain extends Contract {
12552
8368
  try {
12553
8369
  await this.#executeTransaction({ ...transaction.decoded, hash });
12554
8370
  block.transactions.push({ hash, ...transaction.decoded });
12555
- block.fees += Number(calculateFee(transaction.decoded));
12556
- await accountsStore.put(transaction.decoded.from, new TextEncoder().encode(String(transaction.decoded.nonce)));
8371
+ block.fees = block.fees.add(await calculateFee(transaction.decoded));
8372
+ await globalThis.accountsStore.put(transaction.decoded.from, new TextEncoder().encode(String(transaction.decoded.nonce)));
12557
8373
  }
12558
8374
  catch (e) {
12559
- await transactionPoolStore.delete(hash);
8375
+ await globalThis.transactionPoolStore.delete(hash);
12560
8376
  }
12561
8377
  }
12562
8378
  // don't add empty block
@@ -12572,7 +8388,7 @@ class Chain extends Contract {
12572
8388
  // }
12573
8389
  // }, [])
12574
8390
  const peers = {};
12575
- for (const entry of peernet.peerEntries) {
8391
+ for (const entry of globalThis.peernet.peerEntries) {
12576
8392
  peers[entry[0]] = entry[1];
12577
8393
  }
12578
8394
  for (const validator of Object.keys(validators)) {
@@ -12580,7 +8396,7 @@ class Chain extends Contract {
12580
8396
  const peer = peers[validator];
12581
8397
  if (peer && peer.connected) {
12582
8398
  let data = await new BWRequestMessage();
12583
- const node = await peernet.prepareMessage(validator, data.encoded);
8399
+ const node = await globalThis.peernet.prepareMessage(validator, data.encoded);
12584
8400
  try {
12585
8401
  const bw = await peer.request(node.encoded);
12586
8402
  console.log({ bw });
@@ -12591,21 +8407,24 @@ class Chain extends Contract {
12591
8407
  }
12592
8408
  catch { }
12593
8409
  }
12594
- else if (peernet.selectedAccount === validator) {
8410
+ else if (globalThis.peernet.selectedAccount === validator) {
12595
8411
  block.validators.push({
12596
- address: peernet.selectedAccount,
12597
- bw: peernet.bw.up + peernet.bw.down
8412
+ address: globalThis.peernet.selectedAccount,
8413
+ bw: globalThis.peernet.bw.up + globalThis.peernet.bw.down
12598
8414
  });
12599
8415
  }
12600
8416
  }
12601
8417
  }
12602
8418
  console.log({ validators: block.validators });
12603
- block.reward = 150;
12604
8419
  block.validators = block.validators.map(validator => {
12605
- validator.reward = String(Number(block.fees) + block.reward / block.validators.length);
8420
+ validator.reward = block.fees;
8421
+ validator.reward = validator.reward.add(block.reward);
8422
+ validator.reward = validator.reward.div(block.validators.length);
8423
+ validator.reward = validator.reward.toString();
12606
8424
  delete validator.bw;
12607
8425
  return validator;
12608
8426
  });
8427
+ console.log({ validators: block.validators });
12609
8428
  // block.validators = calculateValidatorReward(block.validators, block.fees)
12610
8429
  block.index = this.lastBlock?.index;
12611
8430
  if (block.index === undefined)
@@ -12614,29 +8433,19 @@ class Chain extends Contract {
12614
8433
  block.index += 1;
12615
8434
  block.previousHash = this.lastBlock?.hash || '0x0';
12616
8435
  block.timestamp = Date.now();
12617
- const parts = String(block.fees).split('.');
12618
- let decimals = 0;
12619
- if (parts[1]) {
12620
- const potentional = parts[1].split('e');
12621
- if (potentional[0] === parts[1]) {
12622
- decimals = parts[1].length;
12623
- }
12624
- else {
12625
- parts[1] = potentional[0];
12626
- decimals = Number(potentional[1]?.replace(/[+-]/g, '')) + Number(potentional[0].length);
12627
- }
12628
- }
12629
- block.fees = Number.parseFloat(String(block.fees)).toFixed(decimals);
8436
+ block.reward = block.reward.toString();
8437
+ block.fees = block.fees.toString();
12630
8438
  try {
12631
8439
  await Promise.all(block.transactions
12632
- .map(async (transaction) => transactionPoolStore.delete(transaction.hash)));
8440
+ .map(async (transaction) => globalThis.transactionPoolStore.delete(transaction.hash)));
12633
8441
  let blockMessage = await new BlockMessage(block);
8442
+ blockMessage = await new BlockMessage(blockMessage.encoded);
12634
8443
  const hash = await blockMessage.hash();
12635
- await peernet.put(hash, blockMessage.encoded, 'block');
8444
+ await globalThis.peernet.put(hash, blockMessage.encoded, 'block');
12636
8445
  await this.#updateState(blockMessage);
12637
- debug(`created block: ${hash}`);
12638
- peernet.publish('add-block', blockMessage.encoded);
12639
- pubsub.publish('add-block', blockMessage.decoded);
8446
+ globalThis.debug(`created block: ${hash}`);
8447
+ globalThis.peernet.publish('add-block', blockMessage.encoded);
8448
+ globalThis.pubsub.publish('add-block', blockMessage.decoded);
12640
8449
  }
12641
8450
  catch (error) {
12642
8451
  throw new Error(`invalid block ${block}`);
@@ -12648,9 +8457,9 @@ class Chain extends Contract {
12648
8457
  try {
12649
8458
  transaction = await new TransactionMessage(transaction);
12650
8459
  const hash = await transaction.hash();
12651
- const has = await transactionPoolStore.has(hash);
8460
+ const has = await globalThis.transactionPoolStore.has(hash);
12652
8461
  if (!has)
12653
- await transactionPoolStore.put(hash, transaction.encoded);
8462
+ await globalThis.transactionPoolStore.put(hash, transaction.encoded);
12654
8463
  if (this.#participating && !this.#runningEpoch)
12655
8464
  this.#runEpoch();
12656
8465
  }
@@ -12683,7 +8492,7 @@ class Chain extends Contract {
12683
8492
  * @param {Address} sender
12684
8493
  * @returns {globalMessage}
12685
8494
  */
12686
- #createMessage(sender = globalThis.peernet.selectedAccount) {
8495
+ #createMessage(sender = globalThis.globalThis.peernet.selectedAccount) {
12687
8496
  return {
12688
8497
  sender,
12689
8498
  call: this.call,