@typeberry/lib 0.1.2 → 0.1.3-0eba10b

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/index.js CHANGED
@@ -35,8 +35,9 @@ function parseCurrentVersion(env) {
35
35
  }
36
36
  }
37
37
  function parseCurrentSuite(env) {
38
- if (env === undefined)
38
+ if (env === undefined) {
39
39
  return undefined;
40
+ }
40
41
  switch (env) {
41
42
  case TestSuite.W3F_DAVXY:
42
43
  case TestSuite.JAMDUNA:
@@ -329,6 +330,19 @@ const Result$1 = {
329
330
  },
330
331
  };
331
332
 
333
+ // about 2GB, the maximum ArrayBuffer length on Chrome confirmed by several sources:
334
+ // - https://issues.chromium.org/issues/40055619
335
+ // - https://stackoverflow.com/a/72124984
336
+ // - https://onnxruntime.ai/docs/tutorials/web/large-models.html#maximum-size-of-arraybuffer
337
+ const MAX_LENGTH$2 = 2145386496;
338
+ function safeAllocUint8Array(length) {
339
+ if (length > MAX_LENGTH$2) {
340
+ // biome-ignore lint/suspicious/noConsole: can't have a dependency on logger here
341
+ console.warn(`Trying to allocate ${length} bytes, which is greater than the maximum of ${MAX_LENGTH$2}.`);
342
+ }
343
+ return new Uint8Array(Math.min(MAX_LENGTH$2, length));
344
+ }
345
+
332
346
  /**
333
347
  * Utilities for tests.
334
348
  */
@@ -443,10 +457,12 @@ function deepEqual(actual, expected, { context = [], errorsCollector, ignore = [
443
457
  .sort((a, b) => {
444
458
  const aKey = `${a.key}`;
445
459
  const bKey = `${b.key}`;
446
- if (aKey < bKey)
460
+ if (aKey < bKey) {
447
461
  return -1;
448
- if (bKey < aKey)
462
+ }
463
+ if (bKey < aKey) {
449
464
  return 1;
465
+ }
450
466
  return 0;
451
467
  });
452
468
  };
@@ -560,7 +576,7 @@ function isResult(x) {
560
576
  * as an afterthought.
561
577
  */
562
578
 
563
- var index$s = /*#__PURE__*/Object.freeze({
579
+ var index$u = /*#__PURE__*/Object.freeze({
564
580
  __proto__: null,
565
581
  get CURRENT_SUITE () { return CURRENT_SUITE; },
566
582
  get CURRENT_VERSION () { return CURRENT_VERSION; },
@@ -569,6 +585,7 @@ var index$s = /*#__PURE__*/Object.freeze({
569
585
  DEFAULT_VERSION: DEFAULT_VERSION,
570
586
  ErrorsCollector: ErrorsCollector,
571
587
  get GpVersion () { return GpVersion; },
588
+ MAX_LENGTH: MAX_LENGTH$2,
572
589
  OK: OK,
573
590
  Result: Result$1,
574
591
  TEST_COMPARE_USING: TEST_COMPARE_USING,
@@ -583,6 +600,7 @@ var index$s = /*#__PURE__*/Object.freeze({
583
600
  isBrowser: isBrowser,
584
601
  measure: measure,
585
602
  resultToString: resultToString,
603
+ safeAllocUint8Array: safeAllocUint8Array,
586
604
  seeThrough: seeThrough,
587
605
  workspacePathFix: workspacePathFix
588
606
  });
@@ -606,7 +624,7 @@ class BitVec {
606
624
  * Create new [`BitVec`] with all values set to `false`.
607
625
  */
608
626
  static empty(bitLength) {
609
- const data = new Uint8Array(Math.ceil(bitLength / 8));
627
+ const data = safeAllocUint8Array(Math.ceil(bitLength / 8));
610
628
  return new BitVec(data, bitLength);
611
629
  }
612
630
  byteLength;
@@ -714,7 +732,7 @@ class Ordering {
714
732
  }
715
733
  }
716
734
 
717
- var index$r = /*#__PURE__*/Object.freeze({
735
+ var index$t = /*#__PURE__*/Object.freeze({
718
736
  __proto__: null,
719
737
  Ordering: Ordering
720
738
  });
@@ -807,7 +825,7 @@ class BytesBlob {
807
825
  static blobFromParts(v, ...rest) {
808
826
  const vArr = v instanceof Uint8Array ? [v] : v;
809
827
  const totalLength = vArr.reduce((a, v) => a + v.length, 0) + rest.reduce((a, v) => a + v.length, 0);
810
- const buffer = new Uint8Array(totalLength);
828
+ const buffer = safeAllocUint8Array(totalLength);
811
829
  let offset = 0;
812
830
  for (const r of vArr) {
813
831
  buffer.set(r, offset);
@@ -880,7 +898,7 @@ class Bytes extends BytesBlob {
880
898
  }
881
899
  /** Create an empty [`Bytes<X>`] of given length. */
882
900
  static zero(len) {
883
- return new Bytes(new Uint8Array(len), len);
901
+ return new Bytes(safeAllocUint8Array(len), len);
884
902
  }
885
903
  // TODO [ToDr] `fill` should have the argments swapped to align with the rest.
886
904
  /** Create a [`Bytes<X>`] with all bytes filled with given input number. */
@@ -965,7 +983,7 @@ function u8ArraySameLengthEqual(self, other) {
965
983
  }
966
984
  const bytesBlobComparator = (a, b) => a.compare(b);
967
985
 
968
- var index$q = /*#__PURE__*/Object.freeze({
986
+ var index$s = /*#__PURE__*/Object.freeze({
969
987
  __proto__: null,
970
988
  BitVec: BitVec,
971
989
  Bytes: Bytes,
@@ -1067,7 +1085,7 @@ const minU64 = (a, ...values) => values.reduce((min, value) => (value > min ? mi
1067
1085
  /** Get the biggest value between U64 a and values given as input parameters. */
1068
1086
  const maxU64 = (a, ...values) => values.reduce((max, value) => (value < max ? max : value), a);
1069
1087
 
1070
- var index$p = /*#__PURE__*/Object.freeze({
1088
+ var index$r = /*#__PURE__*/Object.freeze({
1071
1089
  __proto__: null,
1072
1090
  isU16: isU16,
1073
1091
  isU32: isU32,
@@ -1944,13 +1962,15 @@ function validateLength(range, length, context) {
1944
1962
 
1945
1963
  /** A caching wrapper for either object or sequence item. */
1946
1964
  class ViewField {
1965
+ name;
1947
1966
  getView;
1948
1967
  getValue;
1949
1968
  getEncoded;
1950
1969
  cachedValue;
1951
1970
  cachedView;
1952
1971
  cachedBlob;
1953
- constructor(getView, getValue, getEncoded) {
1972
+ constructor(name, getView, getValue, getEncoded) {
1973
+ this.name = name;
1954
1974
  this.getView = getView;
1955
1975
  this.getValue = getValue;
1956
1976
  this.getEncoded = getEncoded;
@@ -1976,6 +1996,9 @@ class ViewField {
1976
1996
  }
1977
1997
  return this.cachedBlob;
1978
1998
  }
1999
+ toString() {
2000
+ return `ViewField<${this.name}>`;
2001
+ }
1979
2002
  }
1980
2003
  /**
1981
2004
  * A base class for all the lazy views.
@@ -2050,7 +2073,7 @@ class ObjectView {
2050
2073
  const fieldDecoder = skipper.decoder.clone();
2051
2074
  const field = this.descriptorsKeys[i];
2052
2075
  const type = this.descriptors[field];
2053
- lastItem = new ViewField(() => type.View.decode(fieldDecoder.clone()), () => type.decode(fieldDecoder.clone()), () => type.skipEncoded(fieldDecoder.clone()));
2076
+ lastItem = new ViewField(`${this.toString()}.${String(field)}`, () => type.View.decode(fieldDecoder.clone()), () => type.decode(fieldDecoder.clone()), () => type.skipEncoded(fieldDecoder.clone()));
2054
2077
  // skip the field
2055
2078
  type.skip(skipper);
2056
2079
  // cache data
@@ -2062,6 +2085,9 @@ class ObjectView {
2062
2085
  }
2063
2086
  return lastItem;
2064
2087
  }
2088
+ toString() {
2089
+ return `View<${this.materializedConstructor.name}>(cache: ${this.cache.size})`;
2090
+ }
2065
2091
  }
2066
2092
  /**
2067
2093
  * A lazy-evaluated decoder of a sequence.
@@ -2150,7 +2176,7 @@ class SequenceView {
2150
2176
  // create new cached prop
2151
2177
  const fieldDecoder = skipper.decoder.clone();
2152
2178
  const type = this.descriptor;
2153
- lastItem = new ViewField(() => type.View.decode(fieldDecoder.clone()), () => type.decode(fieldDecoder.clone()), () => type.skipEncoded(fieldDecoder.clone()));
2179
+ lastItem = new ViewField(`${this.toString()}[${index}]`, () => type.View.decode(fieldDecoder.clone()), () => type.decode(fieldDecoder.clone()), () => type.skipEncoded(fieldDecoder.clone()));
2154
2180
  // skip the field
2155
2181
  type.skip(skipper);
2156
2182
  // cache data
@@ -2162,6 +2188,9 @@ class SequenceView {
2162
2188
  }
2163
2189
  return lastItem;
2164
2190
  }
2191
+ toString() {
2192
+ return `SequenceView<${this.descriptor.name}>(cache: ${this.cache.size})`;
2193
+ }
2165
2194
  }
2166
2195
 
2167
2196
  /**
@@ -2477,7 +2506,7 @@ function sequenceViewFixLen(type, { fixedLength }) {
2477
2506
  }, skipper);
2478
2507
  }
2479
2508
 
2480
- var index$o = /*#__PURE__*/Object.freeze({
2509
+ var index$q = /*#__PURE__*/Object.freeze({
2481
2510
  __proto__: null,
2482
2511
  Decoder: Decoder,
2483
2512
  Descriptor: Descriptor,
@@ -3578,7 +3607,7 @@ async function verify(input) {
3578
3607
  return Promise.resolve([]);
3579
3608
  }
3580
3609
  const dataLength = input.reduce((acc, { message, key, signature }) => acc + key.length + signature.length + message.length + 1, 0);
3581
- const data = new Uint8Array(dataLength);
3610
+ const data = safeAllocUint8Array(dataLength);
3582
3611
  let offset = 0;
3583
3612
  for (const { key, message, signature } of input) {
3584
3613
  data.set(key.raw, offset);
@@ -3625,823 +3654,75 @@ var ed25519 = /*#__PURE__*/Object.freeze({
3625
3654
  verifyBatch: verifyBatch
3626
3655
  });
3627
3656
 
3657
+ const SEED_SIZE = 32;
3658
+ const ED25519_SECRET_KEY = Bytes.blobFromString("jam_val_key_ed25519");
3659
+ const BANDERSNATCH_SECRET_KEY = Bytes.blobFromString("jam_val_key_bandersnatch");
3628
3660
  /**
3629
- * Size of the output of the hash functions.
3630
- *
3631
- * https://graypaper.fluffylabs.dev/#/579bd12/073101073c01
3661
+ * JIP-5: Secret key derivation
3632
3662
  *
3633
- */
3634
- const HASH_SIZE = 32;
3635
- /** A hash without last byte (useful for trie representation). */
3636
- const TRUNCATED_HASH_SIZE = 31;
3637
- const ZERO_HASH = Bytes.zero(HASH_SIZE);
3663
+ * https://github.com/polkadot-fellows/JIPs/blob/7048f79edf4f4eb8bfe6fb42e6bbf61900f44c65/JIP-5.md */
3638
3664
  /**
3639
- * Container for some object with a hash that is related to this object.
3640
- *
3641
- * After calculating the hash these two should be passed together to avoid
3642
- * unnecessary re-hashing of the data.
3665
+ * Deriving a 32-byte seed from a 32-bit unsigned integer
3666
+ * https://github.com/polkadot-fellows/JIPs/blob/7048f79edf4f4eb8bfe6fb42e6bbf61900f44c65/JIP-5.md#trivial-seeds
3643
3667
  */
3644
- class WithHash extends WithDebug {
3645
- hash;
3646
- data;
3647
- constructor(hash, data) {
3648
- super();
3649
- this.hash = hash;
3650
- this.data = data;
3651
- }
3668
+ function trivialSeed(s) {
3669
+ const s_le = u32AsLeBytes(s);
3670
+ return Bytes.fromBlob(BytesBlob.blobFromParts([s_le, s_le, s_le, s_le, s_le, s_le, s_le, s_le]).raw, SEED_SIZE).asOpaque();
3652
3671
  }
3653
3672
  /**
3654
- * Extension of [`WithHash`] additionally containing an encoded version of the object.
3673
+ * Derives a Ed25519 secret key from a seed.
3674
+ * https://github.com/polkadot-fellows/JIPs/blob/7048f79edf4f4eb8bfe6fb42e6bbf61900f44c65/JIP-5.md#derivation-method
3655
3675
  */
3656
- class WithHashAndBytes extends WithHash {
3657
- encoded;
3658
- constructor(hash, data, encoded) {
3659
- super(hash, data);
3660
- this.encoded = encoded;
3661
- }
3662
- }
3663
-
3664
- /** The simplest allocator returning just a fresh copy of bytes each time. */
3665
- class SimpleAllocator {
3666
- emptyHash() {
3667
- return Bytes.zero(HASH_SIZE);
3668
- }
3669
- }
3670
- /** An allocator that works by allocating larger (continuous) pages of memory. */
3671
- class PageAllocator {
3672
- hashesPerPage;
3673
- page = new Uint8Array(0);
3674
- currentHash = 0;
3675
- // TODO [ToDr] Benchmark the performance!
3676
- constructor(hashesPerPage) {
3677
- this.hashesPerPage = hashesPerPage;
3678
- check `${hashesPerPage > 0 && hashesPerPage >>> 0 === hashesPerPage} Expected a non-zero integer.`;
3679
- this.resetPage();
3680
- }
3681
- resetPage() {
3682
- const pageSizeBytes = this.hashesPerPage * HASH_SIZE;
3683
- this.currentHash = 0;
3684
- this.page = new Uint8Array(pageSizeBytes);
3685
- }
3686
- emptyHash() {
3687
- const startIdx = this.currentHash * HASH_SIZE;
3688
- const endIdx = startIdx + HASH_SIZE;
3689
- this.currentHash += 1;
3690
- if (this.currentHash >= this.hashesPerPage) {
3691
- this.resetPage();
3692
- }
3693
- return Bytes.fromBlob(this.page.subarray(startIdx, endIdx), HASH_SIZE);
3694
- }
3695
- }
3696
- const defaultAllocator = new SimpleAllocator();
3697
-
3698
- function getDefaultExportFromCjs (x) {
3699
- return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
3700
- }
3701
-
3702
- var blake2b$3 = {exports: {}};
3703
-
3704
- var nanoassert;
3705
- var hasRequiredNanoassert;
3706
-
3707
- function requireNanoassert () {
3708
- if (hasRequiredNanoassert) return nanoassert;
3709
- hasRequiredNanoassert = 1;
3710
- nanoassert = assert;
3711
-
3712
- class AssertionError extends Error {}
3713
- AssertionError.prototype.name = 'AssertionError';
3714
-
3715
- /**
3716
- * Minimal assert function
3717
- * @param {any} t Value to check if falsy
3718
- * @param {string=} m Optional assertion error message
3719
- * @throws {AssertionError}
3720
- */
3721
- function assert (t, m) {
3722
- if (!t) {
3723
- var err = new AssertionError(m);
3724
- if (Error.captureStackTrace) Error.captureStackTrace(err, assert);
3725
- throw err
3726
- }
3727
- }
3728
- return nanoassert;
3729
- }
3730
-
3731
- var blake2bWasm = {exports: {}};
3732
-
3733
- var b4a;
3734
- var hasRequiredB4a;
3735
-
3736
- function requireB4a () {
3737
- if (hasRequiredB4a) return b4a;
3738
- hasRequiredB4a = 1;
3739
- function isBuffer (value) {
3740
- return Buffer.isBuffer(value) || value instanceof Uint8Array
3741
- }
3742
-
3743
- function isEncoding (encoding) {
3744
- return Buffer.isEncoding(encoding)
3745
- }
3746
-
3747
- function alloc (size, fill, encoding) {
3748
- return Buffer.alloc(size, fill, encoding)
3749
- }
3750
-
3751
- function allocUnsafe (size) {
3752
- return Buffer.allocUnsafe(size)
3753
- }
3754
-
3755
- function allocUnsafeSlow (size) {
3756
- return Buffer.allocUnsafeSlow(size)
3757
- }
3758
-
3759
- function byteLength (string, encoding) {
3760
- return Buffer.byteLength(string, encoding)
3761
- }
3762
-
3763
- function compare (a, b) {
3764
- return Buffer.compare(a, b)
3765
- }
3766
-
3767
- function concat (buffers, totalLength) {
3768
- return Buffer.concat(buffers, totalLength)
3769
- }
3770
-
3771
- function copy (source, target, targetStart, start, end) {
3772
- return toBuffer(source).copy(target, targetStart, start, end)
3773
- }
3774
-
3775
- function equals (a, b) {
3776
- return toBuffer(a).equals(b)
3777
- }
3778
-
3779
- function fill (buffer, value, offset, end, encoding) {
3780
- return toBuffer(buffer).fill(value, offset, end, encoding)
3781
- }
3782
-
3783
- function from (value, encodingOrOffset, length) {
3784
- return Buffer.from(value, encodingOrOffset, length)
3785
- }
3786
-
3787
- function includes (buffer, value, byteOffset, encoding) {
3788
- return toBuffer(buffer).includes(value, byteOffset, encoding)
3789
- }
3790
-
3791
- function indexOf (buffer, value, byfeOffset, encoding) {
3792
- return toBuffer(buffer).indexOf(value, byfeOffset, encoding)
3793
- }
3794
-
3795
- function lastIndexOf (buffer, value, byteOffset, encoding) {
3796
- return toBuffer(buffer).lastIndexOf(value, byteOffset, encoding)
3797
- }
3798
-
3799
- function swap16 (buffer) {
3800
- return toBuffer(buffer).swap16()
3801
- }
3802
-
3803
- function swap32 (buffer) {
3804
- return toBuffer(buffer).swap32()
3805
- }
3806
-
3807
- function swap64 (buffer) {
3808
- return toBuffer(buffer).swap64()
3809
- }
3810
-
3811
- function toBuffer (buffer) {
3812
- if (Buffer.isBuffer(buffer)) return buffer
3813
- return Buffer.from(buffer.buffer, buffer.byteOffset, buffer.byteLength)
3814
- }
3815
-
3816
- function toString (buffer, encoding, start, end) {
3817
- return toBuffer(buffer).toString(encoding, start, end)
3818
- }
3819
-
3820
- function write (buffer, string, offset, length, encoding) {
3821
- return toBuffer(buffer).write(string, offset, length, encoding)
3822
- }
3823
-
3824
- function writeDoubleLE (buffer, value, offset) {
3825
- return toBuffer(buffer).writeDoubleLE(value, offset)
3826
- }
3827
-
3828
- function writeFloatLE (buffer, value, offset) {
3829
- return toBuffer(buffer).writeFloatLE(value, offset)
3830
- }
3831
-
3832
- function writeUInt32LE (buffer, value, offset) {
3833
- return toBuffer(buffer).writeUInt32LE(value, offset)
3834
- }
3835
-
3836
- function writeInt32LE (buffer, value, offset) {
3837
- return toBuffer(buffer).writeInt32LE(value, offset)
3838
- }
3839
-
3840
- function readDoubleLE (buffer, offset) {
3841
- return toBuffer(buffer).readDoubleLE(offset)
3842
- }
3843
-
3844
- function readFloatLE (buffer, offset) {
3845
- return toBuffer(buffer).readFloatLE(offset)
3846
- }
3847
-
3848
- function readUInt32LE (buffer, offset) {
3849
- return toBuffer(buffer).readUInt32LE(offset)
3850
- }
3851
-
3852
- function readInt32LE (buffer, offset) {
3853
- return toBuffer(buffer).readInt32LE(offset)
3854
- }
3855
-
3856
- b4a = {
3857
- isBuffer,
3858
- isEncoding,
3859
- alloc,
3860
- allocUnsafe,
3861
- allocUnsafeSlow,
3862
- byteLength,
3863
- compare,
3864
- concat,
3865
- copy,
3866
- equals,
3867
- fill,
3868
- from,
3869
- includes,
3870
- indexOf,
3871
- lastIndexOf,
3872
- swap16,
3873
- swap32,
3874
- swap64,
3875
- toBuffer,
3876
- toString,
3877
- write,
3878
- writeDoubleLE,
3879
- writeFloatLE,
3880
- writeUInt32LE,
3881
- writeInt32LE,
3882
- readDoubleLE,
3883
- readFloatLE,
3884
- readUInt32LE,
3885
- readInt32LE
3886
- };
3887
- return b4a;
3888
- }
3889
-
3890
- var blake2b$2;
3891
- var hasRequiredBlake2b$1;
3892
-
3893
- function requireBlake2b$1 () {
3894
- if (hasRequiredBlake2b$1) return blake2b$2;
3895
- hasRequiredBlake2b$1 = 1;
3896
- var __commonJS = (cb, mod) => function __require() {
3897
- return mod || (0, cb[Object.keys(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
3898
- };
3899
- var __toBinary = /* @__PURE__ */ (() => {
3900
- var table = new Uint8Array(128);
3901
- for (var i = 0; i < 64; i++)
3902
- table[i < 26 ? i + 65 : i < 52 ? i + 71 : i < 62 ? i - 4 : i * 4 - 205] = i;
3903
- return (base64) => {
3904
- var n = base64.length, bytes2 = new Uint8Array((n - (base64[n - 1] == "=") - (base64[n - 2] == "=")) * 3 / 4 | 0);
3905
- for (var i2 = 0, j = 0; i2 < n; ) {
3906
- var c0 = table[base64.charCodeAt(i2++)], c1 = table[base64.charCodeAt(i2++)];
3907
- var c2 = table[base64.charCodeAt(i2++)], c3 = table[base64.charCodeAt(i2++)];
3908
- bytes2[j++] = c0 << 2 | c1 >> 4;
3909
- bytes2[j++] = c1 << 4 | c2 >> 2;
3910
- bytes2[j++] = c2 << 6 | c3;
3911
- }
3912
- return bytes2;
3913
- };
3914
- })();
3915
-
3916
- // wasm-binary:./blake2b.wat
3917
- var require_blake2b = __commonJS({
3918
- "wasm-binary:./blake2b.wat"(exports2, module2) {
3919
- module2.exports = __toBinary("AGFzbQEAAAABEANgAn9/AGADf39/AGABfwADBQQAAQICBQUBAQroBwdNBQZtZW1vcnkCAAxibGFrZTJiX2luaXQAAA5ibGFrZTJiX3VwZGF0ZQABDWJsYWtlMmJfZmluYWwAAhBibGFrZTJiX2NvbXByZXNzAAMKvz8EwAIAIABCADcDACAAQgA3AwggAEIANwMQIABCADcDGCAAQgA3AyAgAEIANwMoIABCADcDMCAAQgA3AzggAEIANwNAIABCADcDSCAAQgA3A1AgAEIANwNYIABCADcDYCAAQgA3A2ggAEIANwNwIABCADcDeCAAQoiS853/zPmE6gBBACkDAIU3A4ABIABCu86qptjQ67O7f0EIKQMAhTcDiAEgAEKr8NP0r+68tzxBECkDAIU3A5ABIABC8e30+KWn/aelf0EYKQMAhTcDmAEgAELRhZrv+s+Uh9EAQSApAwCFNwOgASAAQp/Y+dnCkdqCm39BKCkDAIU3A6gBIABC6/qG2r+19sEfQTApAwCFNwOwASAAQvnC+JuRo7Pw2wBBOCkDAIU3A7gBIABCADcDwAEgAEIANwPIASAAQgA3A9ABC20BA38gAEHAAWohAyAAQcgBaiEEIAQpAwCnIQUCQANAIAEgAkYNASAFQYABRgRAIAMgAykDACAFrXw3AwBBACEFIAAQAwsgACAFaiABLQAAOgAAIAVBAWohBSABQQFqIQEMAAsLIAQgBa03AwALYQEDfyAAQcABaiEBIABByAFqIQIgASABKQMAIAIpAwB8NwMAIABCfzcD0AEgAikDAKchAwJAA0AgA0GAAUYNASAAIANqQQA6AAAgA0EBaiEDDAALCyACIAOtNw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FQhiKIQggAyAIIBh8fCEDIA4gA4VCEIohDiAJIA58IQkgCCAJhUI/iiEIIAQgBSAWfHwhBCAPIASFQiCKIQ8gCiAPfCEKIAUgCoVCGIohBSAEIAUgFHx8IQQgDyAEhUIQiiEPIAogD3whCiAFIAqFQj+KIQUgISAhKQMAIAEgCYWFNwMAICIgIikDACACIAqFhTcDACAjICMpAwAgAyALhYU3AwAgJCAkKQMAIAQgDIWFNwMAICUgJSkDACAFIA2FhTcDACAmICYpAwAgBiAOhYU3AwAgJyAnKQMAIAcgD4WFNwMAICggKCkDACAIIBCFhTcDAAs=");
3920
- }
3921
- });
3922
-
3923
- // wasm-module:./blake2b.wat
3924
- var bytes = require_blake2b();
3925
- var compiled = WebAssembly.compile(bytes);
3926
- blake2b$2 = async (imports) => {
3927
- const instance = await WebAssembly.instantiate(await compiled, imports);
3928
- return instance.exports;
3929
- };
3930
- return blake2b$2;
3931
- }
3932
-
3933
- var hasRequiredBlake2bWasm;
3934
-
3935
- function requireBlake2bWasm () {
3936
- if (hasRequiredBlake2bWasm) return blake2bWasm.exports;
3937
- hasRequiredBlake2bWasm = 1;
3938
- var assert = /*@__PURE__*/ requireNanoassert();
3939
- var b4a = /*@__PURE__*/ requireB4a();
3940
-
3941
- var wasm = null;
3942
- var wasmPromise = typeof WebAssembly !== "undefined" && /*@__PURE__*/ requireBlake2b$1()().then(mod => {
3943
- wasm = mod;
3944
- });
3945
-
3946
- var head = 64;
3947
- var freeList = [];
3948
-
3949
- blake2bWasm.exports = Blake2b;
3950
- var BYTES_MIN = blake2bWasm.exports.BYTES_MIN = 16;
3951
- var BYTES_MAX = blake2bWasm.exports.BYTES_MAX = 64;
3952
- blake2bWasm.exports.BYTES = 32;
3953
- var KEYBYTES_MIN = blake2bWasm.exports.KEYBYTES_MIN = 16;
3954
- var KEYBYTES_MAX = blake2bWasm.exports.KEYBYTES_MAX = 64;
3955
- blake2bWasm.exports.KEYBYTES = 32;
3956
- var SALTBYTES = blake2bWasm.exports.SALTBYTES = 16;
3957
- var PERSONALBYTES = blake2bWasm.exports.PERSONALBYTES = 16;
3958
-
3959
- function Blake2b (digestLength, key, salt, personal, noAssert) {
3960
- if (!(this instanceof Blake2b)) return new Blake2b(digestLength, key, salt, personal, noAssert)
3961
- if (!wasm) throw new Error('WASM not loaded. Wait for Blake2b.ready(cb)')
3962
- if (!digestLength) digestLength = 32;
3963
-
3964
- if (noAssert !== true) {
3965
- assert(digestLength >= BYTES_MIN, 'digestLength must be at least ' + BYTES_MIN + ', was given ' + digestLength);
3966
- assert(digestLength <= BYTES_MAX, 'digestLength must be at most ' + BYTES_MAX + ', was given ' + digestLength);
3967
- if (key != null) {
3968
- assert(key instanceof Uint8Array, 'key must be Uint8Array or Buffer');
3969
- assert(key.length >= KEYBYTES_MIN, 'key must be at least ' + KEYBYTES_MIN + ', was given ' + key.length);
3970
- assert(key.length <= KEYBYTES_MAX, 'key must be at least ' + KEYBYTES_MAX + ', was given ' + key.length);
3971
- }
3972
- if (salt != null) {
3973
- assert(salt instanceof Uint8Array, 'salt must be Uint8Array or Buffer');
3974
- assert(salt.length === SALTBYTES, 'salt must be exactly ' + SALTBYTES + ', was given ' + salt.length);
3975
- }
3976
- if (personal != null) {
3977
- assert(personal instanceof Uint8Array, 'personal must be Uint8Array or Buffer');
3978
- assert(personal.length === PERSONALBYTES, 'personal must be exactly ' + PERSONALBYTES + ', was given ' + personal.length);
3979
- }
3980
- }
3981
-
3982
- if (!freeList.length) {
3983
- freeList.push(head);
3984
- head += 216;
3985
- }
3986
-
3987
- this.digestLength = digestLength;
3988
- this.finalized = false;
3989
- this.pointer = freeList.pop();
3990
- this._memory = new Uint8Array(wasm.memory.buffer);
3991
-
3992
- this._memory.fill(0, 0, 64);
3993
- this._memory[0] = this.digestLength;
3994
- this._memory[1] = key ? key.length : 0;
3995
- this._memory[2] = 1; // fanout
3996
- this._memory[3] = 1; // depth
3997
-
3998
- if (salt) this._memory.set(salt, 32);
3999
- if (personal) this._memory.set(personal, 48);
4000
-
4001
- if (this.pointer + 216 > this._memory.length) this._realloc(this.pointer + 216); // we need 216 bytes for the state
4002
- wasm.blake2b_init(this.pointer, this.digestLength);
4003
-
4004
- if (key) {
4005
- this.update(key);
4006
- this._memory.fill(0, head, head + key.length); // whiteout key
4007
- this._memory[this.pointer + 200] = 128;
4008
- }
4009
- }
4010
-
4011
- Blake2b.prototype._realloc = function (size) {
4012
- wasm.memory.grow(Math.max(0, Math.ceil(Math.abs(size - this._memory.length) / 65536)));
4013
- this._memory = new Uint8Array(wasm.memory.buffer);
4014
- };
4015
-
4016
- Blake2b.prototype.update = function (input) {
4017
- assert(this.finalized === false, 'Hash instance finalized');
4018
- assert(input instanceof Uint8Array, 'input must be Uint8Array or Buffer');
4019
-
4020
- if (head + input.length > this._memory.length) this._realloc(head + input.length);
4021
- this._memory.set(input, head);
4022
- wasm.blake2b_update(this.pointer, head, head + input.length);
4023
- return this
4024
- };
4025
-
4026
- Blake2b.prototype.digest = function (enc) {
4027
- assert(this.finalized === false, 'Hash instance finalized');
4028
- this.finalized = true;
4029
-
4030
- freeList.push(this.pointer);
4031
- wasm.blake2b_final(this.pointer);
4032
-
4033
- if (!enc || enc === 'binary') {
4034
- return this._memory.slice(this.pointer + 128, this.pointer + 128 + this.digestLength)
4035
- }
4036
-
4037
- if (typeof enc === 'string') {
4038
- return b4a.toString(this._memory, enc, this.pointer + 128, this.pointer + 128 + this.digestLength)
4039
- }
4040
-
4041
- assert(enc instanceof Uint8Array && enc.length >= this.digestLength, 'input must be Uint8Array or Buffer');
4042
- for (var i = 0; i < this.digestLength; i++) {
4043
- enc[i] = this._memory[this.pointer + 128 + i];
4044
- }
4045
-
4046
- return enc
4047
- };
4048
-
4049
- // libsodium compat
4050
- Blake2b.prototype.final = Blake2b.prototype.digest;
4051
-
4052
- Blake2b.WASM = wasm;
4053
- Blake2b.SUPPORTED = typeof WebAssembly !== 'undefined';
4054
-
4055
- Blake2b.ready = function (cb) {
4056
- if (!cb) cb = noop;
4057
- if (!wasmPromise) return cb(new Error('WebAssembly not supported'))
4058
- return wasmPromise.then(() => cb(), cb)
4059
- };
4060
-
4061
- Blake2b.prototype.ready = Blake2b.ready;
4062
-
4063
- Blake2b.prototype.getPartialHash = function () {
4064
- return this._memory.slice(this.pointer, this.pointer + 216);
4065
- };
4066
-
4067
- Blake2b.prototype.setPartialHash = function (ph) {
4068
- this._memory.set(ph, this.pointer);
4069
- };
4070
-
4071
- function noop () {}
4072
- return blake2bWasm.exports;
4073
- }
4074
-
4075
- var hasRequiredBlake2b;
4076
-
4077
- function requireBlake2b () {
4078
- if (hasRequiredBlake2b) return blake2b$3.exports;
4079
- hasRequiredBlake2b = 1;
4080
- var assert = /*@__PURE__*/ requireNanoassert();
4081
- var b2wasm = /*@__PURE__*/ requireBlake2bWasm();
4082
-
4083
- // 64-bit unsigned addition
4084
- // Sets v[a,a+1] += v[b,b+1]
4085
- // v should be a Uint32Array
4086
- function ADD64AA (v, a, b) {
4087
- var o0 = v[a] + v[b];
4088
- var o1 = v[a + 1] + v[b + 1];
4089
- if (o0 >= 0x100000000) {
4090
- o1++;
4091
- }
4092
- v[a] = o0;
4093
- v[a + 1] = o1;
4094
- }
4095
-
4096
- // 64-bit unsigned addition
4097
- // Sets v[a,a+1] += b
4098
- // b0 is the low 32 bits of b, b1 represents the high 32 bits
4099
- function ADD64AC (v, a, b0, b1) {
4100
- var o0 = v[a] + b0;
4101
- if (b0 < 0) {
4102
- o0 += 0x100000000;
4103
- }
4104
- var o1 = v[a + 1] + b1;
4105
- if (o0 >= 0x100000000) {
4106
- o1++;
4107
- }
4108
- v[a] = o0;
4109
- v[a + 1] = o1;
4110
- }
4111
-
4112
- // Little-endian byte access
4113
- function B2B_GET32 (arr, i) {
4114
- return (arr[i] ^
4115
- (arr[i + 1] << 8) ^
4116
- (arr[i + 2] << 16) ^
4117
- (arr[i + 3] << 24))
4118
- }
4119
-
4120
- // G Mixing function
4121
- // The ROTRs are inlined for speed
4122
- function B2B_G (a, b, c, d, ix, iy) {
4123
- var x0 = m[ix];
4124
- var x1 = m[ix + 1];
4125
- var y0 = m[iy];
4126
- var y1 = m[iy + 1];
4127
-
4128
- ADD64AA(v, a, b); // v[a,a+1] += v[b,b+1] ... in JS we must store a uint64 as two uint32s
4129
- ADD64AC(v, a, x0, x1); // v[a, a+1] += x ... x0 is the low 32 bits of x, x1 is the high 32 bits
4130
-
4131
- // v[d,d+1] = (v[d,d+1] xor v[a,a+1]) rotated to the right by 32 bits
4132
- var xor0 = v[d] ^ v[a];
4133
- var xor1 = v[d + 1] ^ v[a + 1];
4134
- v[d] = xor1;
4135
- v[d + 1] = xor0;
4136
-
4137
- ADD64AA(v, c, d);
4138
-
4139
- // v[b,b+1] = (v[b,b+1] xor v[c,c+1]) rotated right by 24 bits
4140
- xor0 = v[b] ^ v[c];
4141
- xor1 = v[b + 1] ^ v[c + 1];
4142
- v[b] = (xor0 >>> 24) ^ (xor1 << 8);
4143
- v[b + 1] = (xor1 >>> 24) ^ (xor0 << 8);
4144
-
4145
- ADD64AA(v, a, b);
4146
- ADD64AC(v, a, y0, y1);
4147
-
4148
- // v[d,d+1] = (v[d,d+1] xor v[a,a+1]) rotated right by 16 bits
4149
- xor0 = v[d] ^ v[a];
4150
- xor1 = v[d + 1] ^ v[a + 1];
4151
- v[d] = (xor0 >>> 16) ^ (xor1 << 16);
4152
- v[d + 1] = (xor1 >>> 16) ^ (xor0 << 16);
4153
-
4154
- ADD64AA(v, c, d);
4155
-
4156
- // v[b,b+1] = (v[b,b+1] xor v[c,c+1]) rotated right by 63 bits
4157
- xor0 = v[b] ^ v[c];
4158
- xor1 = v[b + 1] ^ v[c + 1];
4159
- v[b] = (xor1 >>> 31) ^ (xor0 << 1);
4160
- v[b + 1] = (xor0 >>> 31) ^ (xor1 << 1);
4161
- }
4162
-
4163
- // Initialization Vector
4164
- var BLAKE2B_IV32 = new Uint32Array([
4165
- 0xF3BCC908, 0x6A09E667, 0x84CAA73B, 0xBB67AE85,
4166
- 0xFE94F82B, 0x3C6EF372, 0x5F1D36F1, 0xA54FF53A,
4167
- 0xADE682D1, 0x510E527F, 0x2B3E6C1F, 0x9B05688C,
4168
- 0xFB41BD6B, 0x1F83D9AB, 0x137E2179, 0x5BE0CD19
4169
- ]);
4170
-
4171
- var SIGMA8 = [
4172
- 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,
4173
- 14, 10, 4, 8, 9, 15, 13, 6, 1, 12, 0, 2, 11, 7, 5, 3,
4174
- 11, 8, 12, 0, 5, 2, 15, 13, 10, 14, 3, 6, 7, 1, 9, 4,
4175
- 7, 9, 3, 1, 13, 12, 11, 14, 2, 6, 5, 10, 4, 0, 15, 8,
4176
- 9, 0, 5, 7, 2, 4, 10, 15, 14, 1, 11, 12, 6, 8, 3, 13,
4177
- 2, 12, 6, 10, 0, 11, 8, 3, 4, 13, 7, 5, 15, 14, 1, 9,
4178
- 12, 5, 1, 15, 14, 13, 4, 10, 0, 7, 6, 3, 9, 2, 8, 11,
4179
- 13, 11, 7, 14, 12, 1, 3, 9, 5, 0, 15, 4, 8, 6, 2, 10,
4180
- 6, 15, 14, 9, 11, 3, 0, 8, 12, 2, 13, 7, 1, 4, 10, 5,
4181
- 10, 2, 8, 4, 7, 6, 1, 5, 15, 11, 9, 14, 3, 12, 13, 0,
4182
- 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,
4183
- 14, 10, 4, 8, 9, 15, 13, 6, 1, 12, 0, 2, 11, 7, 5, 3
4184
- ];
4185
-
4186
- // These are offsets into a uint64 buffer.
4187
- // Multiply them all by 2 to make them offsets into a uint32 buffer,
4188
- // because this is Javascript and we don't have uint64s
4189
- var SIGMA82 = new Uint8Array(SIGMA8.map(function (x) { return x * 2 }));
4190
-
4191
- // Compression function. 'last' flag indicates last block.
4192
- // Note we're representing 16 uint64s as 32 uint32s
4193
- var v = new Uint32Array(32);
4194
- var m = new Uint32Array(32);
4195
- function blake2bCompress (ctx, last) {
4196
- var i = 0;
4197
-
4198
- // init work variables
4199
- for (i = 0; i < 16; i++) {
4200
- v[i] = ctx.h[i];
4201
- v[i + 16] = BLAKE2B_IV32[i];
4202
- }
4203
-
4204
- // low 64 bits of offset
4205
- v[24] = v[24] ^ ctx.t;
4206
- v[25] = v[25] ^ (ctx.t / 0x100000000);
4207
- // high 64 bits not supported, offset may not be higher than 2**53-1
4208
-
4209
- // last block flag set ?
4210
- if (last) {
4211
- v[28] = ~v[28];
4212
- v[29] = ~v[29];
4213
- }
4214
-
4215
- // get little-endian words
4216
- for (i = 0; i < 32; i++) {
4217
- m[i] = B2B_GET32(ctx.b, 4 * i);
4218
- }
4219
-
4220
- // twelve rounds of mixing
4221
- for (i = 0; i < 12; i++) {
4222
- B2B_G(0, 8, 16, 24, SIGMA82[i * 16 + 0], SIGMA82[i * 16 + 1]);
4223
- B2B_G(2, 10, 18, 26, SIGMA82[i * 16 + 2], SIGMA82[i * 16 + 3]);
4224
- B2B_G(4, 12, 20, 28, SIGMA82[i * 16 + 4], SIGMA82[i * 16 + 5]);
4225
- B2B_G(6, 14, 22, 30, SIGMA82[i * 16 + 6], SIGMA82[i * 16 + 7]);
4226
- B2B_G(0, 10, 20, 30, SIGMA82[i * 16 + 8], SIGMA82[i * 16 + 9]);
4227
- B2B_G(2, 12, 22, 24, SIGMA82[i * 16 + 10], SIGMA82[i * 16 + 11]);
4228
- B2B_G(4, 14, 16, 26, SIGMA82[i * 16 + 12], SIGMA82[i * 16 + 13]);
4229
- B2B_G(6, 8, 18, 28, SIGMA82[i * 16 + 14], SIGMA82[i * 16 + 15]);
4230
- }
4231
-
4232
- for (i = 0; i < 16; i++) {
4233
- ctx.h[i] = ctx.h[i] ^ v[i] ^ v[i + 16];
4234
- }
4235
- }
4236
-
4237
- // reusable parameter_block
4238
- var parameter_block = new Uint8Array([
4239
- 0, 0, 0, 0, // 0: outlen, keylen, fanout, depth
4240
- 0, 0, 0, 0, // 4: leaf length, sequential mode
4241
- 0, 0, 0, 0, // 8: node offset
4242
- 0, 0, 0, 0, // 12: node offset
4243
- 0, 0, 0, 0, // 16: node depth, inner length, rfu
4244
- 0, 0, 0, 0, // 20: rfu
4245
- 0, 0, 0, 0, // 24: rfu
4246
- 0, 0, 0, 0, // 28: rfu
4247
- 0, 0, 0, 0, // 32: salt
4248
- 0, 0, 0, 0, // 36: salt
4249
- 0, 0, 0, 0, // 40: salt
4250
- 0, 0, 0, 0, // 44: salt
4251
- 0, 0, 0, 0, // 48: personal
4252
- 0, 0, 0, 0, // 52: personal
4253
- 0, 0, 0, 0, // 56: personal
4254
- 0, 0, 0, 0 // 60: personal
4255
- ]);
4256
-
4257
- // Creates a BLAKE2b hashing context
4258
- // Requires an output length between 1 and 64 bytes
4259
- // Takes an optional Uint8Array key
4260
- function Blake2b (outlen, key, salt, personal) {
4261
- // zero out parameter_block before usage
4262
- parameter_block.fill(0);
4263
- // state, 'param block'
4264
-
4265
- this.b = new Uint8Array(128);
4266
- this.h = new Uint32Array(16);
4267
- this.t = 0; // input count
4268
- this.c = 0; // pointer within buffer
4269
- this.outlen = outlen; // output length in bytes
4270
-
4271
- parameter_block[0] = outlen;
4272
- if (key) parameter_block[1] = key.length;
4273
- parameter_block[2] = 1; // fanout
4274
- parameter_block[3] = 1; // depth
4275
-
4276
- if (salt) parameter_block.set(salt, 32);
4277
- if (personal) parameter_block.set(personal, 48);
4278
-
4279
- // initialize hash state
4280
- for (var i = 0; i < 16; i++) {
4281
- this.h[i] = BLAKE2B_IV32[i] ^ B2B_GET32(parameter_block, i * 4);
4282
- }
4283
-
4284
- // key the hash, if applicable
4285
- if (key) {
4286
- blake2bUpdate(this, key);
4287
- // at the end
4288
- this.c = 128;
4289
- }
4290
- }
4291
-
4292
- Blake2b.prototype.update = function (input) {
4293
- assert(input instanceof Uint8Array, 'input must be Uint8Array or Buffer');
4294
- blake2bUpdate(this, input);
4295
- return this
4296
- };
4297
-
4298
- Blake2b.prototype.digest = function (out) {
4299
- var buf = (!out || out === 'binary' || out === 'hex') ? new Uint8Array(this.outlen) : out;
4300
- assert(buf instanceof Uint8Array, 'out must be "binary", "hex", Uint8Array, or Buffer');
4301
- assert(buf.length >= this.outlen, 'out must have at least outlen bytes of space');
4302
- blake2bFinal(this, buf);
4303
- if (out === 'hex') return hexSlice(buf)
4304
- return buf
4305
- };
4306
-
4307
- Blake2b.prototype.final = Blake2b.prototype.digest;
4308
-
4309
- Blake2b.ready = function (cb) {
4310
- b2wasm.ready(function () {
4311
- cb(); // ignore the error
4312
- });
4313
- };
4314
-
4315
- // Updates a BLAKE2b streaming hash
4316
- // Requires hash context and Uint8Array (byte array)
4317
- function blake2bUpdate (ctx, input) {
4318
- for (var i = 0; i < input.length; i++) {
4319
- if (ctx.c === 128) { // buffer full ?
4320
- ctx.t += ctx.c; // add counters
4321
- blake2bCompress(ctx, false); // compress (not last)
4322
- ctx.c = 0; // counter to zero
4323
- }
4324
- ctx.b[ctx.c++] = input[i];
4325
- }
4326
- }
4327
-
4328
- // Completes a BLAKE2b streaming hash
4329
- // Returns a Uint8Array containing the message digest
4330
- function blake2bFinal (ctx, out) {
4331
- ctx.t += ctx.c; // mark last block offset
4332
-
4333
- while (ctx.c < 128) { // fill up with zeros
4334
- ctx.b[ctx.c++] = 0;
4335
- }
4336
- blake2bCompress(ctx, true); // final block flag = 1
4337
-
4338
- for (var i = 0; i < ctx.outlen; i++) {
4339
- out[i] = ctx.h[i >> 2] >> (8 * (i & 3));
4340
- }
4341
- return out
4342
- }
4343
-
4344
- function hexSlice (buf) {
4345
- var str = '';
4346
- for (var i = 0; i < buf.length; i++) str += toHex(buf[i]);
4347
- return str
4348
- }
4349
-
4350
- function toHex (n) {
4351
- if (n < 16) return '0' + n.toString(16)
4352
- return n.toString(16)
4353
- }
4354
-
4355
- var Proto = Blake2b;
4356
-
4357
- blake2b$3.exports = function createHash (outlen, key, salt, personal, noAssert) {
4358
- if (noAssert !== true) {
4359
- assert(outlen >= BYTES_MIN, 'outlen must be at least ' + BYTES_MIN + ', was given ' + outlen);
4360
- assert(outlen <= BYTES_MAX, 'outlen must be at most ' + BYTES_MAX + ', was given ' + outlen);
4361
- if (key != null) {
4362
- assert(key instanceof Uint8Array, 'key must be Uint8Array or Buffer');
4363
- assert(key.length >= KEYBYTES_MIN, 'key must be at least ' + KEYBYTES_MIN + ', was given ' + key.length);
4364
- assert(key.length <= KEYBYTES_MAX, 'key must be at most ' + KEYBYTES_MAX + ', was given ' + key.length);
4365
- }
4366
- if (salt != null) {
4367
- assert(salt instanceof Uint8Array, 'salt must be Uint8Array or Buffer');
4368
- assert(salt.length === SALTBYTES, 'salt must be exactly ' + SALTBYTES + ', was given ' + salt.length);
4369
- }
4370
- if (personal != null) {
4371
- assert(personal instanceof Uint8Array, 'personal must be Uint8Array or Buffer');
4372
- assert(personal.length === PERSONALBYTES, 'personal must be exactly ' + PERSONALBYTES + ', was given ' + personal.length);
4373
- }
4374
- }
4375
-
4376
- return new Proto(outlen, key, salt, personal)
4377
- };
4378
-
4379
- blake2b$3.exports.ready = function (cb) {
4380
- b2wasm.ready(function () { // ignore errors
4381
- cb();
4382
- });
4383
- };
4384
-
4385
- blake2b$3.exports.WASM_SUPPORTED = b2wasm.SUPPORTED;
4386
- blake2b$3.exports.WASM_LOADED = false;
4387
-
4388
- var BYTES_MIN = blake2b$3.exports.BYTES_MIN = 16;
4389
- var BYTES_MAX = blake2b$3.exports.BYTES_MAX = 64;
4390
- blake2b$3.exports.BYTES = 32;
4391
- var KEYBYTES_MIN = blake2b$3.exports.KEYBYTES_MIN = 16;
4392
- var KEYBYTES_MAX = blake2b$3.exports.KEYBYTES_MAX = 64;
4393
- blake2b$3.exports.KEYBYTES = 32;
4394
- var SALTBYTES = blake2b$3.exports.SALTBYTES = 16;
4395
- var PERSONALBYTES = blake2b$3.exports.PERSONALBYTES = 16;
4396
-
4397
- b2wasm.ready(function (err) {
4398
- if (!err) {
4399
- blake2b$3.exports.WASM_LOADED = true;
4400
- blake2b$3.exports = b2wasm;
4401
- }
4402
- });
4403
- return blake2b$3.exports;
3676
+ function deriveEd25519SecretKey(seed, blake2b) {
3677
+ return blake2b.hashBytes(BytesBlob.blobFromParts([ED25519_SECRET_KEY.raw, seed.raw])).asOpaque();
4404
3678
  }
4405
-
4406
- var blake2bExports = /*@__PURE__*/ requireBlake2b();
4407
- var blake2b$1 = /*@__PURE__*/getDefaultExportFromCjs(blake2bExports);
4408
-
4409
3679
  /**
4410
- * Hash given collection of blobs.
4411
- *
4412
- * If empty array is given a zero-hash is returned.
3680
+ * Derives a Bandersnatch secret key from a seed.
3681
+ * https://github.com/polkadot-fellows/JIPs/blob/7048f79edf4f4eb8bfe6fb42e6bbf61900f44c65/JIP-5.md#derivation-method
4413
3682
  */
4414
- function hashBlobs$1(r, allocator = defaultAllocator) {
4415
- const out = allocator.emptyHash();
4416
- if (r.length === 0) {
4417
- return out.asOpaque();
4418
- }
4419
- const hasher = blake2b$1(HASH_SIZE);
4420
- for (const v of r) {
4421
- hasher?.update(v instanceof BytesBlob ? v.raw : v);
4422
- }
4423
- hasher?.digest(out.raw);
4424
- return out.asOpaque();
3683
+ function deriveBandersnatchSecretKey(seed, blake2b) {
3684
+ return blake2b.hashBytes(BytesBlob.blobFromParts([BANDERSNATCH_SECRET_KEY.raw, seed.raw])).asOpaque();
4425
3685
  }
4426
- /** Hash given blob of bytes. */
4427
- function hashBytes(blob, allocator = defaultAllocator) {
4428
- const hasher = blake2b$1(HASH_SIZE);
4429
- const bytes = blob instanceof BytesBlob ? blob.raw : blob;
4430
- hasher?.update(bytes);
4431
- const out = allocator.emptyHash();
4432
- hasher?.digest(out.raw);
4433
- return out;
3686
+ /**
3687
+ * Derive Ed25519 public key from secret seed
3688
+ */
3689
+ async function deriveEd25519PublicKey(seed) {
3690
+ return (await privateKey(seed)).pubKey;
4434
3691
  }
4435
- /** Convert given string into bytes and hash it. */
4436
- function hashString(str, allocator = defaultAllocator) {
4437
- return hashBytes(BytesBlob.blobFromString(str), allocator);
3692
+ /**
3693
+ * Derive Bandersnatch public key from secret seed
3694
+ */
3695
+ function deriveBandersnatchPublicKey(seed) {
3696
+ return publicKey(seed.raw);
4438
3697
  }
4439
3698
 
4440
- var blake2b = /*#__PURE__*/Object.freeze({
3699
+ var keyDerivation = /*#__PURE__*/Object.freeze({
3700
+ __proto__: null,
3701
+ SEED_SIZE: SEED_SIZE,
3702
+ deriveBandersnatchPublicKey: deriveBandersnatchPublicKey,
3703
+ deriveBandersnatchSecretKey: deriveBandersnatchSecretKey,
3704
+ deriveEd25519PublicKey: deriveEd25519PublicKey,
3705
+ deriveEd25519SecretKey: deriveEd25519SecretKey,
3706
+ trivialSeed: trivialSeed
3707
+ });
3708
+
3709
+ var index$p = /*#__PURE__*/Object.freeze({
4441
3710
  __proto__: null,
4442
- hashBlobs: hashBlobs$1,
4443
- hashBytes: hashBytes,
4444
- hashString: hashString
3711
+ BANDERSNATCH_KEY_BYTES: BANDERSNATCH_KEY_BYTES,
3712
+ BANDERSNATCH_PROOF_BYTES: BANDERSNATCH_PROOF_BYTES,
3713
+ BANDERSNATCH_RING_ROOT_BYTES: BANDERSNATCH_RING_ROOT_BYTES,
3714
+ BANDERSNATCH_VRF_SIGNATURE_BYTES: BANDERSNATCH_VRF_SIGNATURE_BYTES,
3715
+ BLS_KEY_BYTES: BLS_KEY_BYTES,
3716
+ ED25519_KEY_BYTES: ED25519_KEY_BYTES,
3717
+ ED25519_PRIV_KEY_BYTES: ED25519_PRIV_KEY_BYTES,
3718
+ ED25519_SIGNATURE_BYTES: ED25519_SIGNATURE_BYTES,
3719
+ Ed25519Pair: Ed25519Pair,
3720
+ SEED_SIZE: SEED_SIZE,
3721
+ bandersnatch: bandersnatch,
3722
+ bandersnatchWasm: bandersnatch_exports,
3723
+ ed25519: ed25519,
3724
+ initWasm: initAll,
3725
+ keyDerivation: keyDerivation
4445
3726
  });
4446
3727
 
4447
3728
  /*!
@@ -4802,7 +4083,78 @@ function WASMInterface(binary, hashLength) {
4802
4083
 
4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FNwOoiQFBAEEAKQOgiwFC6/qG2r+19sEfhTcDsIkBQQBBACkDqIsBQvnC+JuRo7Pw2wCFNwO4iQFBACADp0H/AXE2AuSKAQJAIAFBAUgNACACQgA3A3ggAkIANwNwIAJCADcDaCACQgA3A2AgAkIANwNYIAJCADcDUCACQgA3A0ggAkIANwNAIAJCADcDOCACQgA3AzAgAkIANwMoIAJCADcDICACQgA3AxggAkIANwMQIAJCADcDCCACQgA3AwBBACEEA0AgAiAAaiAAQYAJai0AADoAACAAQQFqIQAgBEEBaiIEQf8BcSABSA0ACyACQYABEAELIAJBgAFqJAALEgAgAEEDdkH/P3EgAEEQdhAECwkAQYAJIAAQAQsGAEGAiQELGwAgAUEDdkH/P3EgAUEQdhAEQYAJIAAQARADCwsLAQBBgAgLBPAAAAA=";
4088
+ var hash$j = "c6f286e6";
4089
+ var wasmJson$j = {
4090
+ name: name$j,
4091
+ data: data$j,
4092
+ hash: hash$j
4093
+ };
4094
+
4805
4095
  new Mutex();
4096
+ function validateBits$4(bits) {
4097
+ if (!Number.isInteger(bits) || bits < 8 || bits > 512 || bits % 8 !== 0) {
4098
+ return new Error("Invalid variant! Valid values: 8, 16, ..., 512");
4099
+ }
4100
+ return null;
4101
+ }
4102
+ function getInitParam$1(outputBits, keyBits) {
4103
+ return outputBits | (keyBits << 16);
4104
+ }
4105
+ /**
4106
+ * Creates a new BLAKE2b hash instance
4107
+ * @param bits Number of output bits, which has to be a number
4108
+ * divisible by 8, between 8 and 512. Defaults to 512.
4109
+ * @param key Optional key (string, Buffer or TypedArray). Maximum length is 64 bytes.
4110
+ */
4111
+ function createBLAKE2b(bits = 512, key = null) {
4112
+ if (validateBits$4(bits)) {
4113
+ return Promise.reject(validateBits$4(bits));
4114
+ }
4115
+ let keyBuffer = null;
4116
+ let initParam = bits;
4117
+ if (key !== null) {
4118
+ keyBuffer = getUInt8Buffer(key);
4119
+ if (keyBuffer.length > 64) {
4120
+ return Promise.reject(new Error("Max key length is 64 bytes"));
4121
+ }
4122
+ initParam = getInitParam$1(bits, keyBuffer.length);
4123
+ }
4124
+ const outputSize = bits / 8;
4125
+ return WASMInterface(wasmJson$j, outputSize).then((wasm) => {
4126
+ if (initParam > 512) {
4127
+ wasm.writeMemory(keyBuffer);
4128
+ }
4129
+ wasm.init(initParam);
4130
+ const obj = {
4131
+ init: initParam > 512
4132
+ ? () => {
4133
+ wasm.writeMemory(keyBuffer);
4134
+ wasm.init(initParam);
4135
+ return obj;
4136
+ }
4137
+ : () => {
4138
+ wasm.init(initParam);
4139
+ return obj;
4140
+ },
4141
+ update: (data) => {
4142
+ wasm.update(data);
4143
+ return obj;
4144
+ },
4145
+ // biome-ignore lint/suspicious/noExplicitAny: Conflict with IHasher type
4146
+ digest: (outputType) => wasm.digest(outputType),
4147
+ save: () => wasm.save(),
4148
+ load: (data) => {
4149
+ wasm.load(data);
4150
+ return obj;
4151
+ },
4152
+ blockSize: 128,
4153
+ digestSize: outputSize,
4154
+ };
4155
+ return obj;
4156
+ });
4157
+ }
4806
4158
 
4807
4159
  new Mutex();
4808
4160
 
@@ -4892,6 +4244,79 @@ new Mutex();
4892
4244
 
4893
4245
  new Mutex();
4894
4246
 
4247
+ /**
4248
+ * Size of the output of the hash functions.
4249
+ *
4250
+ * https://graypaper.fluffylabs.dev/#/579bd12/073101073c01
4251
+ *
4252
+ */
4253
+ const HASH_SIZE = 32;
4254
+ /** A hash without last byte (useful for trie representation). */
4255
+ const TRUNCATED_HASH_SIZE = 31;
4256
+ const ZERO_HASH = Bytes.zero(HASH_SIZE);
4257
+ /**
4258
+ * Container for some object with a hash that is related to this object.
4259
+ *
4260
+ * After calculating the hash these two should be passed together to avoid
4261
+ * unnecessary re-hashing of the data.
4262
+ */
4263
+ class WithHash extends WithDebug {
4264
+ hash;
4265
+ data;
4266
+ constructor(hash, data) {
4267
+ super();
4268
+ this.hash = hash;
4269
+ this.data = data;
4270
+ }
4271
+ }
4272
+ /**
4273
+ * Extension of [`WithHash`] additionally containing an encoded version of the object.
4274
+ */
4275
+ class WithHashAndBytes extends WithHash {
4276
+ encoded;
4277
+ constructor(hash, data, encoded) {
4278
+ super(hash, data);
4279
+ this.encoded = encoded;
4280
+ }
4281
+ }
4282
+
4283
+ const zero$1 = Bytes.zero(HASH_SIZE);
4284
+ class Blake2b {
4285
+ hasher;
4286
+ static async createHasher() {
4287
+ return new Blake2b(await createBLAKE2b(HASH_SIZE * 8));
4288
+ }
4289
+ constructor(hasher) {
4290
+ this.hasher = hasher;
4291
+ }
4292
+ /**
4293
+ * Hash given collection of blobs.
4294
+ *
4295
+ * If empty array is given a zero-hash is returned.
4296
+ */
4297
+ hashBlobs(r) {
4298
+ if (r.length === 0) {
4299
+ return zero$1.asOpaque();
4300
+ }
4301
+ const hasher = this.hasher.init();
4302
+ for (const v of r) {
4303
+ hasher.update(v instanceof BytesBlob ? v.raw : v);
4304
+ }
4305
+ return Bytes.fromBlob(hasher.digest("binary"), HASH_SIZE).asOpaque();
4306
+ }
4307
+ /** Hash given blob of bytes. */
4308
+ hashBytes(blob) {
4309
+ const hasher = this.hasher.init();
4310
+ const bytes = blob instanceof BytesBlob ? blob.raw : blob;
4311
+ hasher.update(bytes);
4312
+ return Bytes.fromBlob(hasher.digest("binary"), HASH_SIZE).asOpaque();
4313
+ }
4314
+ /** Convert given string into bytes and hash it. */
4315
+ hashString(str) {
4316
+ return this.hashBytes(BytesBlob.blobFromString(str));
4317
+ }
4318
+ }
4319
+
4895
4320
  class KeccakHasher {
4896
4321
  hasher;
4897
4322
  static async create() {
@@ -4916,91 +4341,61 @@ var keccak = /*#__PURE__*/Object.freeze({
4916
4341
  hashBlobs: hashBlobs
4917
4342
  });
4918
4343
 
4919
- var index$n = /*#__PURE__*/Object.freeze({
4344
+ // TODO [ToDr] (#213) this should most likely be moved to a separate
4345
+ // package to avoid pulling in unnecessary deps.
4346
+
4347
+ var index$o = /*#__PURE__*/Object.freeze({
4920
4348
  __proto__: null,
4349
+ Blake2b: Blake2b,
4921
4350
  HASH_SIZE: HASH_SIZE,
4922
- PageAllocator: PageAllocator,
4923
- SimpleAllocator: SimpleAllocator,
4924
4351
  TRUNCATED_HASH_SIZE: TRUNCATED_HASH_SIZE,
4925
4352
  WithHash: WithHash,
4926
4353
  WithHashAndBytes: WithHashAndBytes,
4927
4354
  ZERO_HASH: ZERO_HASH,
4928
- blake2b: blake2b,
4929
- defaultAllocator: defaultAllocator,
4930
4355
  keccak: keccak
4931
4356
  });
4932
4357
 
4933
- const SEED_SIZE = 32;
4934
- const ED25519_SECRET_KEY = Bytes.blobFromString("jam_val_key_ed25519");
4935
- const BANDERSNATCH_SECRET_KEY = Bytes.blobFromString("jam_val_key_bandersnatch");
4936
- /**
4937
- * JIP-5: Secret key derivation
4938
- *
4939
- * https://github.com/polkadot-fellows/JIPs/blob/7048f79edf4f4eb8bfe6fb42e6bbf61900f44c65/JIP-5.md */
4940
- /**
4941
- * Deriving a 32-byte seed from a 32-bit unsigned integer
4942
- * https://github.com/polkadot-fellows/JIPs/blob/7048f79edf4f4eb8bfe6fb42e6bbf61900f44c65/JIP-5.md#trivial-seeds
4943
- */
4944
- function trivialSeed(s) {
4945
- const s_le = u32AsLeBytes(s);
4946
- return Bytes.fromBlob(BytesBlob.blobFromParts([s_le, s_le, s_le, s_le, s_le, s_le, s_le, s_le]).raw, SEED_SIZE).asOpaque();
4947
- }
4948
- /**
4949
- * Derives a Ed25519 secret key from a seed.
4950
- * https://github.com/polkadot-fellows/JIPs/blob/7048f79edf4f4eb8bfe6fb42e6bbf61900f44c65/JIP-5.md#derivation-method
4951
- */
4952
- function deriveEd25519SecretKey(seed, allocator = new SimpleAllocator()) {
4953
- return hashBytes(BytesBlob.blobFromParts([ED25519_SECRET_KEY.raw, seed.raw]), allocator).asOpaque();
4954
- }
4955
- /**
4956
- * Derives a Bandersnatch secret key from a seed.
4957
- * https://github.com/polkadot-fellows/JIPs/blob/7048f79edf4f4eb8bfe6fb42e6bbf61900f44c65/JIP-5.md#derivation-method
4958
- */
4959
- function deriveBandersnatchSecretKey(seed, allocator = new SimpleAllocator()) {
4960
- return hashBytes(BytesBlob.blobFromParts([BANDERSNATCH_SECRET_KEY.raw, seed.raw]), allocator).asOpaque();
4961
- }
4962
- /**
4963
- * Derive Ed25519 public key from secret seed
4964
- */
4965
- async function deriveEd25519PublicKey(seed) {
4966
- return (await privateKey(seed)).pubKey;
4967
- }
4968
4358
  /**
4969
- * Derive Bandersnatch public key from secret seed
4359
+ * A utility class providing a readonly view over a portion of an array without copying it.
4970
4360
  */
4971
- function deriveBandersnatchPublicKey(seed) {
4972
- return publicKey(seed.raw);
4361
+ class ArrayView {
4362
+ start;
4363
+ end;
4364
+ source;
4365
+ length;
4366
+ constructor(source, start, end) {
4367
+ this.start = start;
4368
+ this.end = end;
4369
+ this.source = source;
4370
+ this.length = end - start;
4371
+ }
4372
+ static from(source, start = 0, end = source.length) {
4373
+ check `
4374
+ ${start >= 0 && end <= source.length && start <= end}
4375
+ Invalid start (${start})/end (${end}) for ArrayView
4376
+ `;
4377
+ return new ArrayView(source, start, end);
4378
+ }
4379
+ get(i) {
4380
+ check `
4381
+ ${i >= 0 && i < this.length}
4382
+ Index out of bounds: ${i} < ${this.length}
4383
+ `;
4384
+ return this.source[this.start + i];
4385
+ }
4386
+ subview(from, to = this.length) {
4387
+ return ArrayView.from(this.source, this.start + from, this.start + to);
4388
+ }
4389
+ toArray() {
4390
+ return this.source.slice(this.start, this.end);
4391
+ }
4392
+ *[Symbol.iterator]() {
4393
+ for (let i = this.start; i < this.end; i++) {
4394
+ yield this.source[i];
4395
+ }
4396
+ }
4973
4397
  }
4974
4398
 
4975
- var keyDerivation = /*#__PURE__*/Object.freeze({
4976
- __proto__: null,
4977
- SEED_SIZE: SEED_SIZE,
4978
- deriveBandersnatchPublicKey: deriveBandersnatchPublicKey,
4979
- deriveBandersnatchSecretKey: deriveBandersnatchSecretKey,
4980
- deriveEd25519PublicKey: deriveEd25519PublicKey,
4981
- deriveEd25519SecretKey: deriveEd25519SecretKey,
4982
- trivialSeed: trivialSeed
4983
- });
4984
-
4985
- var index$m = /*#__PURE__*/Object.freeze({
4986
- __proto__: null,
4987
- BANDERSNATCH_KEY_BYTES: BANDERSNATCH_KEY_BYTES,
4988
- BANDERSNATCH_PROOF_BYTES: BANDERSNATCH_PROOF_BYTES,
4989
- BANDERSNATCH_RING_ROOT_BYTES: BANDERSNATCH_RING_ROOT_BYTES,
4990
- BANDERSNATCH_VRF_SIGNATURE_BYTES: BANDERSNATCH_VRF_SIGNATURE_BYTES,
4991
- BLS_KEY_BYTES: BLS_KEY_BYTES,
4992
- ED25519_KEY_BYTES: ED25519_KEY_BYTES,
4993
- ED25519_PRIV_KEY_BYTES: ED25519_PRIV_KEY_BYTES,
4994
- ED25519_SIGNATURE_BYTES: ED25519_SIGNATURE_BYTES,
4995
- Ed25519Pair: Ed25519Pair,
4996
- SEED_SIZE: SEED_SIZE,
4997
- bandersnatch: bandersnatch,
4998
- bandersnatchWasm: bandersnatch_exports,
4999
- ed25519: ed25519,
5000
- initWasm: initAll,
5001
- keyDerivation: keyDerivation
5002
- });
5003
-
5004
4399
  /** A map which uses hashes as keys. */
5005
4400
  class HashDictionary {
5006
4401
  // TODO [ToDr] [crit] We can't use `TrieHash` directly in the map,
@@ -5586,8 +4981,9 @@ class TruncatedHashDictionary {
5586
4981
  }
5587
4982
  }
5588
4983
 
5589
- var index$l = /*#__PURE__*/Object.freeze({
4984
+ var index$n = /*#__PURE__*/Object.freeze({
5590
4985
  __proto__: null,
4986
+ ArrayView: ArrayView,
5591
4987
  FixedSizeArray: FixedSizeArray,
5592
4988
  HashDictionary: HashDictionary,
5593
4989
  HashSet: HashSet,
@@ -5781,7 +5177,7 @@ class Bootnode {
5781
5177
  }
5782
5178
  }
5783
5179
 
5784
- var index$k = /*#__PURE__*/Object.freeze({
5180
+ var index$m = /*#__PURE__*/Object.freeze({
5785
5181
  __proto__: null,
5786
5182
  Bootnode: Bootnode,
5787
5183
  ChainSpec: ChainSpec,
@@ -5954,6 +5350,40 @@ var assurances = /*#__PURE__*/Object.freeze({
5954
5350
  assurancesExtrinsicCodec: assurancesExtrinsicCodec
5955
5351
  });
5956
5352
 
5353
+ /** Attempt to convert a number into `TimeSlot`. */
5354
+ const tryAsTimeSlot = (v) => asOpaqueType(tryAsU32(v));
5355
+ /** Attempt to convert a number into `ValidatorIndex`. */
5356
+ const tryAsValidatorIndex = (v) => asOpaqueType(tryAsU16(v));
5357
+ /** Attempt to convert a number into `ServiceId`. */
5358
+ const tryAsServiceId = (v) => asOpaqueType(tryAsU32(v));
5359
+ const tryAsServiceGas = (v) => asOpaqueType(tryAsU64(v));
5360
+ /** Attempt to convert a number into `CoreIndex`. */
5361
+ const tryAsCoreIndex = (v) => asOpaqueType(tryAsU16(v));
5362
+ /** Attempt to convert a number into `Epoch`. */
5363
+ const tryAsEpoch = (v) => asOpaqueType(tryAsU32(v));
5364
+ function tryAsPerValidator(array, spec) {
5365
+ check `
5366
+ ${array.length === spec.validatorsCount}
5367
+ Invalid per-validator array length. Expected ${spec.validatorsCount}, got: ${array.length}
5368
+ `;
5369
+ return asKnownSize(array);
5370
+ }
5371
+ const codecPerValidator = (val) => codecWithContext((context) => {
5372
+ return codecKnownSizeArray(val, {
5373
+ fixedLength: context.validatorsCount,
5374
+ });
5375
+ });
5376
+ function tryAsPerEpochBlock(array, spec) {
5377
+ check `
5378
+ ${array.length === spec.epochLength}
5379
+ Invalid per-epoch-block array length. Expected ${spec.epochLength}, got: ${array.length}
5380
+ `;
5381
+ return asKnownSize(array);
5382
+ }
5383
+ const codecPerEpochBlock = (val) => codecWithContext((context) => {
5384
+ return codecKnownSizeArray(val, { fixedLength: context.epochLength });
5385
+ });
5386
+
5957
5387
  /**
5958
5388
  * Proof of signing a contradictory [`Judgement`] of a work report.
5959
5389
  */
@@ -6145,40 +5575,6 @@ var disputes = /*#__PURE__*/Object.freeze({
6145
5575
  Verdict: Verdict
6146
5576
  });
6147
5577
 
6148
- /** Attempt to convert a number into `TimeSlot`. */
6149
- const tryAsTimeSlot = (v) => asOpaqueType(tryAsU32(v));
6150
- /** Attempt to convert a number into `ValidatorIndex`. */
6151
- const tryAsValidatorIndex = (v) => asOpaqueType(tryAsU16(v));
6152
- /** Attempt to convert a number into `ServiceId`. */
6153
- const tryAsServiceId = (v) => asOpaqueType(tryAsU32(v));
6154
- const tryAsServiceGas = (v) => asOpaqueType(tryAsU64(v));
6155
- /** Attempt to convert a number into `CoreIndex`. */
6156
- const tryAsCoreIndex = (v) => asOpaqueType(tryAsU16(v));
6157
- /** Attempt to convert a number into `Epoch`. */
6158
- const tryAsEpoch = (v) => asOpaqueType(tryAsU32(v));
6159
- function tryAsPerValidator(array, spec) {
6160
- check `
6161
- ${array.length === spec.validatorsCount}
6162
- Invalid per-validator array length. Expected ${spec.validatorsCount}, got: ${array.length}
6163
- `;
6164
- return asKnownSize(array);
6165
- }
6166
- const codecPerValidator = (val) => codecWithContext((context) => {
6167
- return codecKnownSizeArray(val, {
6168
- fixedLength: context.validatorsCount,
6169
- });
6170
- });
6171
- function tryAsPerEpochBlock(array, spec) {
6172
- check `
6173
- ${array.length === spec.epochLength}
6174
- Invalid per-epoch-block array length. Expected ${spec.epochLength}, got: ${array.length}
6175
- `;
6176
- return asKnownSize(array);
6177
- }
6178
- const codecPerEpochBlock = (val) => codecWithContext((context) => {
6179
- return codecKnownSizeArray(val, { fixedLength: context.epochLength });
6180
- });
6181
-
6182
5578
  /**
6183
5579
  * Mapping between work package hash and root hash of it's exports.
6184
5580
  *
@@ -7257,8 +6653,26 @@ class Block extends WithDebug {
7257
6653
  this.extrinsic = extrinsic;
7258
6654
  }
7259
6655
  }
6656
+ function emptyBlock(slot = tryAsTimeSlot(0)) {
6657
+ const header = Header.empty();
6658
+ header.timeSlotIndex = slot;
6659
+ return Block.create({
6660
+ header,
6661
+ extrinsic: Extrinsic.create({
6662
+ tickets: asKnownSize([]),
6663
+ preimages: [],
6664
+ assurances: asKnownSize([]),
6665
+ guarantees: asKnownSize([]),
6666
+ disputes: {
6667
+ verdicts: [],
6668
+ culprits: [],
6669
+ faults: [],
6670
+ },
6671
+ }),
6672
+ });
6673
+ }
7260
6674
 
7261
- var index$j = /*#__PURE__*/Object.freeze({
6675
+ var index$l = /*#__PURE__*/Object.freeze({
7262
6676
  __proto__: null,
7263
6677
  Block: Block,
7264
6678
  EpochMarker: EpochMarker,
@@ -7273,6 +6687,7 @@ var index$j = /*#__PURE__*/Object.freeze({
7273
6687
  codecPerValidator: codecPerValidator,
7274
6688
  codecUtils: codec,
7275
6689
  disputes: disputes,
6690
+ emptyBlock: emptyBlock,
7276
6691
  encodeUnsealedHeader: encodeUnsealedHeader,
7277
6692
  guarantees: guarantees,
7278
6693
  headerViewWithHashCodec: headerViewWithHashCodec,
@@ -7513,7 +6928,7 @@ var json;
7513
6928
  json.object = object;
7514
6929
  })(json || (json = {}));
7515
6930
 
7516
- var index$i = /*#__PURE__*/Object.freeze({
6931
+ var index$k = /*#__PURE__*/Object.freeze({
7517
6932
  __proto__: null,
7518
6933
  get json () { return json; },
7519
6934
  parseFromJson: parseFromJson
@@ -7783,7 +7198,7 @@ const blockFromJson = (spec) => json.object({
7783
7198
  extrinsic: getExtrinsicFromJson(spec),
7784
7199
  }, ({ header, extrinsic }) => Block.create({ header, extrinsic }));
7785
7200
 
7786
- var index$h = /*#__PURE__*/Object.freeze({
7201
+ var index$j = /*#__PURE__*/Object.freeze({
7787
7202
  __proto__: null,
7788
7203
  blockFromJson: blockFromJson,
7789
7204
  disputesExtrinsicFromJson: disputesExtrinsicFromJson,
@@ -8049,8 +7464,8 @@ function print(level, levelAndName, strings, data) {
8049
7464
  return;
8050
7465
  }
8051
7466
  const lvlText = Level[level].padEnd(5);
8052
- const val = strings.map((v, idx) => `${v}${data[idx]}`);
8053
- const msg = `${lvlText} [${levelAndName[1]}] ${val}`;
7467
+ const val = strings.map((v, idx) => `${v}${idx < data.length ? data[idx] : ""}`);
7468
+ const msg = `${lvlText} [${levelAndName[1]}] ${val.join("")}`;
8054
7469
  if (level === Level.WARN) {
8055
7470
  console.warn(msg);
8056
7471
  }
@@ -8281,7 +7696,7 @@ class Logger {
8281
7696
  }
8282
7697
  }
8283
7698
 
8284
- var index$g = /*#__PURE__*/Object.freeze({
7699
+ var index$i = /*#__PURE__*/Object.freeze({
8285
7700
  __proto__: null,
8286
7701
  get Level () { return Level; },
8287
7702
  Logger: Logger,
@@ -8304,7 +7719,7 @@ class AuthorshipOptions {
8304
7719
  }
8305
7720
  }
8306
7721
 
8307
- const logger$4 = Logger.new(import.meta.filename, "config");
7722
+ const logger$5 = Logger.new(import.meta.filename, "config");
8308
7723
  /** Development config. Will accept unsealed blocks for now. */
8309
7724
  const DEV_CONFIG = "dev";
8310
7725
  /** Default config file. */
@@ -8363,15 +7778,15 @@ class NodeConfiguration {
8363
7778
  }
8364
7779
  function loadConfig(configPath) {
8365
7780
  if (configPath === DEFAULT_CONFIG) {
8366
- logger$4.log `🔧 Loading DEFAULT config`;
7781
+ logger$5.log `🔧 Loading DEFAULT config`;
8367
7782
  return parseFromJson(configs.default, NodeConfiguration.fromJson);
8368
7783
  }
8369
7784
  if (configPath === DEV_CONFIG) {
8370
- logger$4.log `🔧 Loading DEV config`;
7785
+ logger$5.log `🔧 Loading DEV config`;
8371
7786
  return parseFromJson(configs.dev, NodeConfiguration.fromJson);
8372
7787
  }
8373
7788
  try {
8374
- logger$4.log `🔧 Loading config from ${configPath}`;
7789
+ logger$5.log `🔧 Loading config from ${configPath}`;
8375
7790
  const configFile = fs.readFileSync(configPath, "utf8");
8376
7791
  const parsed = JSON.parse(configFile);
8377
7792
  return parseFromJson(parsed, NodeConfiguration.fromJson);
@@ -8381,7 +7796,7 @@ function loadConfig(configPath) {
8381
7796
  }
8382
7797
  }
8383
7798
 
8384
- var index$f = /*#__PURE__*/Object.freeze({
7799
+ var index$h = /*#__PURE__*/Object.freeze({
8385
7800
  __proto__: null,
8386
7801
  DEFAULT_CONFIG: DEFAULT_CONFIG,
8387
7802
  DEV_CONFIG: DEV_CONFIG,
@@ -8530,43 +7945,43 @@ var stateKeys;
8530
7945
  }
8531
7946
  stateKeys.serviceInfo = serviceInfo;
8532
7947
  /** https://graypaper.fluffylabs.dev/#/1c979cb/3bba033bba03?v=0.7.1 */
8533
- function serviceStorage(serviceId, key) {
7948
+ function serviceStorage(blake2b, serviceId, key) {
8534
7949
  if (Compatibility.isLessThan(GpVersion.V0_6_7)) {
8535
7950
  const out = Bytes.zero(HASH_SIZE);
8536
7951
  out.raw.set(u32AsLeBytes(tryAsU32(2 ** 32 - 1)), 0);
8537
7952
  out.raw.set(key.raw.subarray(0, HASH_SIZE - U32_BYTES), U32_BYTES);
8538
7953
  return legacyServiceNested(serviceId, out);
8539
7954
  }
8540
- return serviceNested(serviceId, tryAsU32(2 ** 32 - 1), key);
7955
+ return serviceNested(blake2b, serviceId, tryAsU32(2 ** 32 - 1), key);
8541
7956
  }
8542
7957
  stateKeys.serviceStorage = serviceStorage;
8543
7958
  /** https://graypaper.fluffylabs.dev/#/1c979cb/3bd7033bd703?v=0.7.1 */
8544
- function servicePreimage(serviceId, hash) {
7959
+ function servicePreimage(blake2b, serviceId, hash) {
8545
7960
  if (Compatibility.isLessThan(GpVersion.V0_6_7)) {
8546
7961
  const out = Bytes.zero(HASH_SIZE);
8547
7962
  out.raw.set(u32AsLeBytes(tryAsU32(2 ** 32 - 2)), 0);
8548
7963
  out.raw.set(hash.raw.subarray(1, HASH_SIZE - U32_BYTES + 1), U32_BYTES);
8549
7964
  return legacyServiceNested(serviceId, out);
8550
7965
  }
8551
- return serviceNested(serviceId, tryAsU32(2 ** 32 - 2), hash);
7966
+ return serviceNested(blake2b, serviceId, tryAsU32(2 ** 32 - 2), hash);
8552
7967
  }
8553
7968
  stateKeys.servicePreimage = servicePreimage;
8554
7969
  /** https://graypaper.fluffylabs.dev/#/1c979cb/3b0a043b0a04?v=0.7.1 */
8555
- function serviceLookupHistory(serviceId, hash, preimageLength) {
7970
+ function serviceLookupHistory(blake2b, serviceId, hash, preimageLength) {
8556
7971
  if (Compatibility.isLessThan(GpVersion.V0_6_7)) {
8557
- const doubleHash = hashBytes(hash);
7972
+ const doubleHash = blake2b.hashBytes(hash);
8558
7973
  const out = Bytes.zero(HASH_SIZE);
8559
7974
  out.raw.set(u32AsLeBytes(preimageLength), 0);
8560
7975
  out.raw.set(doubleHash.raw.subarray(2, HASH_SIZE - U32_BYTES + 2), U32_BYTES);
8561
7976
  return legacyServiceNested(serviceId, out);
8562
7977
  }
8563
- return serviceNested(serviceId, preimageLength, hash);
7978
+ return serviceNested(blake2b, serviceId, preimageLength, hash);
8564
7979
  }
8565
7980
  stateKeys.serviceLookupHistory = serviceLookupHistory;
8566
7981
  /** https://graypaper.fluffylabs.dev/#/1c979cb/3b88003b8800?v=0.7.1 */
8567
- function serviceNested(serviceId, numberPrefix, hash) {
7982
+ function serviceNested(blake2b, serviceId, numberPrefix, hash) {
8568
7983
  const inputToHash = BytesBlob.blobFromParts(u32AsLeBytes(numberPrefix), hash.raw);
8569
- const newHash = hashBytes(inputToHash).raw.subarray(0, 28);
7984
+ const newHash = blake2b.hashBytes(inputToHash).raw.subarray(0, 28);
8570
7985
  const key = Bytes.zero(HASH_SIZE);
8571
7986
  let i = 0;
8572
7987
  for (const byte of u32AsLeBytes(serviceId)) {
@@ -8627,12 +8042,6 @@ function accumulationOutputComparator(a, b) {
8627
8042
  return Ordering.Equal;
8628
8043
  }
8629
8044
 
8630
- const codecWithHash = (val) => Descriptor.withView(val.name, val.sizeHint, (e, elem) => val.encode(e, elem.data), (d) => {
8631
- const decoder2 = d.clone();
8632
- const encoded = val.skipEncoded(decoder2);
8633
- const hash = hashBytes(encoded);
8634
- return new WithHash(hash.asOpaque(), val.decode(d));
8635
- }, val.skip, val.View);
8636
8045
  /**
8637
8046
  * Assignment of particular work report to a core.
8638
8047
  *
@@ -8645,7 +8054,7 @@ class AvailabilityAssignment extends WithDebug {
8645
8054
  workReport;
8646
8055
  timeout;
8647
8056
  static Codec = codec$1.Class(AvailabilityAssignment, {
8648
- workReport: codecWithHash(WorkReport.Codec),
8057
+ workReport: WorkReport.Codec,
8649
8058
  timeout: codec$1.u32.asOpaque(),
8650
8059
  });
8651
8060
  static create({ workReport, timeout }) {
@@ -8698,6 +8107,10 @@ class DisputesRecords {
8698
8107
  static create({ goodSet, badSet, wonkySet, punishSet }) {
8699
8108
  return new DisputesRecords(goodSet, badSet, wonkySet, punishSet);
8700
8109
  }
8110
+ goodSetDict;
8111
+ badSetDict;
8112
+ wonkySetDict;
8113
+ punishSetDict;
8701
8114
  constructor(
8702
8115
  /** `goodSet`: all work-reports hashes which were judged to be correct */
8703
8116
  goodSet,
@@ -8711,6 +8124,18 @@ class DisputesRecords {
8711
8124
  this.badSet = badSet;
8712
8125
  this.wonkySet = wonkySet;
8713
8126
  this.punishSet = punishSet;
8127
+ this.goodSetDict = HashSet.from(goodSet.array);
8128
+ this.badSetDict = HashSet.from(badSet.array);
8129
+ this.wonkySetDict = HashSet.from(wonkySet.array);
8130
+ this.punishSetDict = HashSet.from(punishSet.array);
8131
+ }
8132
+ asDictionaries() {
8133
+ return {
8134
+ goodSet: this.goodSetDict,
8135
+ badSet: this.badSetDict,
8136
+ wonkySet: this.wonkySetDict,
8137
+ punishSet: this.punishSetDict,
8138
+ };
8714
8139
  }
8715
8140
  static fromSortedArrays({ goodSet, badSet, wonkySet, punishSet, }) {
8716
8141
  return new DisputesRecords(SortedSet.fromSortedArray(hashComparator, goodSet), SortedSet.fromSortedArray(hashComparator, badSet), SortedSet.fromSortedArray(hashComparator, wonkySet), SortedSet.fromSortedArray(hashComparator, punishSet));
@@ -8726,7 +8151,6 @@ const O = 8;
8726
8151
  const Q = 80;
8727
8152
  /** `W_T`: The size of a transfer memo in octets. */
8728
8153
  const W_T = 128;
8729
- // TODO [ToDr] Not sure where these should live yet :(
8730
8154
  /**
8731
8155
  * `J`: The maximum sum of dependency items in a work-report.
8732
8156
  *
@@ -8738,6 +8162,194 @@ const AUTHORIZATION_QUEUE_SIZE = Q;
8738
8162
  /** `O`: Maximal authorization pool size. */
8739
8163
  const MAX_AUTH_POOL_SIZE = O;
8740
8164
 
8165
+ const MAX_VALUE = 4294967295;
8166
+ const MIN_VALUE = -2147483648;
8167
+ const MAX_SHIFT_U32 = 32;
8168
+ const MAX_SHIFT_U64 = 64n;
8169
+
8170
+ /**
8171
+ * `B_S`: The basic minimum balance which all services require.
8172
+ *
8173
+ * https://graypaper.fluffylabs.dev/#/7e6ff6a/445800445800?v=0.6.7
8174
+ */
8175
+ const BASE_SERVICE_BALANCE = 100n;
8176
+ /**
8177
+ * `B_I`: The additional minimum balance required per item of elective service state.
8178
+ *
8179
+ * https://graypaper.fluffylabs.dev/#/7e6ff6a/445000445000?v=0.6.7
8180
+ */
8181
+ const ELECTIVE_ITEM_BALANCE = 10n;
8182
+ /**
8183
+ * `B_L`: The additional minimum balance required per octet of elective service state.
8184
+ *
8185
+ * https://graypaper.fluffylabs.dev/#/7e6ff6a/445400445400?v=0.6.7
8186
+ */
8187
+ const ELECTIVE_BYTE_BALANCE = 1n;
8188
+ const zeroSizeHint = {
8189
+ bytes: 0,
8190
+ isExact: true,
8191
+ };
8192
+ /** 0-byte read, return given default value */
8193
+ const ignoreValueWithDefault = (defaultValue) => Descriptor.new("ignoreValue", zeroSizeHint, (_e, _v) => { }, (_d) => defaultValue, (_s) => { });
8194
+ /** Encode and decode object with leading version number. */
8195
+ const codecWithVersion = (val) => Descriptor.new("withVersion", {
8196
+ bytes: val.sizeHint.bytes + 8,
8197
+ isExact: false,
8198
+ }, (e, v) => {
8199
+ e.varU64(0n);
8200
+ val.encode(e, v);
8201
+ }, (d) => {
8202
+ const version = d.varU64();
8203
+ if (version !== 0n) {
8204
+ throw new Error("Non-zero version is not supported!");
8205
+ }
8206
+ return val.decode(d);
8207
+ }, (s) => {
8208
+ s.varU64();
8209
+ val.skip(s);
8210
+ });
8211
+ /**
8212
+ * Service account details.
8213
+ *
8214
+ * https://graypaper.fluffylabs.dev/#/7e6ff6a/108301108301?v=0.6.7
8215
+ */
8216
+ class ServiceAccountInfo extends WithDebug {
8217
+ codeHash;
8218
+ balance;
8219
+ accumulateMinGas;
8220
+ onTransferMinGas;
8221
+ storageUtilisationBytes;
8222
+ gratisStorage;
8223
+ storageUtilisationCount;
8224
+ created;
8225
+ lastAccumulation;
8226
+ parentService;
8227
+ static Codec = codec$1.Class(ServiceAccountInfo, {
8228
+ codeHash: codec$1.bytes(HASH_SIZE).asOpaque(),
8229
+ balance: codec$1.u64,
8230
+ accumulateMinGas: codec$1.u64.convert((x) => x, tryAsServiceGas),
8231
+ onTransferMinGas: codec$1.u64.convert((x) => x, tryAsServiceGas),
8232
+ storageUtilisationBytes: codec$1.u64,
8233
+ gratisStorage: codec$1.u64,
8234
+ storageUtilisationCount: codec$1.u32,
8235
+ created: codec$1.u32.convert((x) => x, tryAsTimeSlot),
8236
+ lastAccumulation: codec$1.u32.convert((x) => x, tryAsTimeSlot),
8237
+ parentService: codec$1.u32.convert((x) => x, tryAsServiceId),
8238
+ });
8239
+ static create(a) {
8240
+ return new ServiceAccountInfo(a.codeHash, a.balance, a.accumulateMinGas, a.onTransferMinGas, a.storageUtilisationBytes, a.gratisStorage, a.storageUtilisationCount, a.created, a.lastAccumulation, a.parentService);
8241
+ }
8242
+ /**
8243
+ * `a_t = max(0, BS + BI * a_i + BL * a_o - a_f)`
8244
+ * https://graypaper.fluffylabs.dev/#/7e6ff6a/119e01119e01?v=0.6.7
8245
+ */
8246
+ static calculateThresholdBalance(items, bytes, gratisStorage) {
8247
+ const storageCost = BASE_SERVICE_BALANCE + ELECTIVE_ITEM_BALANCE * BigInt(items) + ELECTIVE_BYTE_BALANCE * bytes - gratisStorage;
8248
+ if (storageCost < 0n) {
8249
+ return tryAsU64(0);
8250
+ }
8251
+ if (storageCost >= 2n ** 64n) {
8252
+ return tryAsU64(2n ** 64n - 1n);
8253
+ }
8254
+ return tryAsU64(storageCost);
8255
+ }
8256
+ constructor(
8257
+ /** `a_c`: Hash of the service code. */
8258
+ codeHash,
8259
+ /** `a_b`: Current account balance. */
8260
+ balance,
8261
+ /** `a_g`: Minimal gas required to execute Accumulate entrypoint. */
8262
+ accumulateMinGas,
8263
+ /** `a_m`: Minimal gas required to execute On Transfer entrypoint. */
8264
+ onTransferMinGas,
8265
+ /** `a_o`: Total number of octets in storage. */
8266
+ storageUtilisationBytes,
8267
+ /** `a_f`: Cost-free storage. Decreases both storage item count and total byte size. */
8268
+ gratisStorage,
8269
+ /** `a_i`: Number of items in storage. */
8270
+ storageUtilisationCount,
8271
+ /** `a_r`: Creation account time slot. */
8272
+ created,
8273
+ /** `a_a`: Most recent accumulation time slot. */
8274
+ lastAccumulation,
8275
+ /** `a_p`: Parent service ID. */
8276
+ parentService) {
8277
+ super();
8278
+ this.codeHash = codeHash;
8279
+ this.balance = balance;
8280
+ this.accumulateMinGas = accumulateMinGas;
8281
+ this.onTransferMinGas = onTransferMinGas;
8282
+ this.storageUtilisationBytes = storageUtilisationBytes;
8283
+ this.gratisStorage = gratisStorage;
8284
+ this.storageUtilisationCount = storageUtilisationCount;
8285
+ this.created = created;
8286
+ this.lastAccumulation = lastAccumulation;
8287
+ this.parentService = parentService;
8288
+ }
8289
+ }
8290
+ class PreimageItem extends WithDebug {
8291
+ hash;
8292
+ blob;
8293
+ static Codec = codec$1.Class(PreimageItem, {
8294
+ hash: codec$1.bytes(HASH_SIZE).asOpaque(),
8295
+ blob: codec$1.blob,
8296
+ });
8297
+ static create({ hash, blob }) {
8298
+ return new PreimageItem(hash, blob);
8299
+ }
8300
+ constructor(hash, blob) {
8301
+ super();
8302
+ this.hash = hash;
8303
+ this.blob = blob;
8304
+ }
8305
+ }
8306
+ class StorageItem extends WithDebug {
8307
+ key;
8308
+ value;
8309
+ static Codec = codec$1.Class(StorageItem, {
8310
+ key: codec$1.blob.convert((i) => i, (o) => asOpaqueType(o)),
8311
+ value: codec$1.blob,
8312
+ });
8313
+ static create({ key, value }) {
8314
+ return new StorageItem(key, value);
8315
+ }
8316
+ constructor(key, value) {
8317
+ super();
8318
+ this.key = key;
8319
+ this.value = value;
8320
+ }
8321
+ }
8322
+ const MAX_LOOKUP_HISTORY_SLOTS = 3;
8323
+ function tryAsLookupHistorySlots(items) {
8324
+ const knownSize = asKnownSize(items);
8325
+ if (knownSize.length > MAX_LOOKUP_HISTORY_SLOTS) {
8326
+ throw new Error(`Lookup history items must contain 0-${MAX_LOOKUP_HISTORY_SLOTS} timeslots.`);
8327
+ }
8328
+ return knownSize;
8329
+ }
8330
+ /** https://graypaper.fluffylabs.dev/#/5f542d7/115400115800 */
8331
+ class LookupHistoryItem {
8332
+ hash;
8333
+ length;
8334
+ slots;
8335
+ constructor(hash, length,
8336
+ /**
8337
+ * Preimage availability history as a sequence of time slots.
8338
+ * See PreimageStatus and the following GP fragment for more details.
8339
+ * https://graypaper.fluffylabs.dev/#/5f542d7/11780011a500 */
8340
+ slots) {
8341
+ this.hash = hash;
8342
+ this.length = length;
8343
+ this.slots = slots;
8344
+ }
8345
+ static isRequested(item) {
8346
+ if ("slots" in item) {
8347
+ return item.slots.length === 0;
8348
+ }
8349
+ return item.length === 0;
8350
+ }
8351
+ }
8352
+
8741
8353
  /** Dictionary entry of services that auto-accumulate every block. */
8742
8354
  class AutoAccumulate {
8743
8355
  service;
@@ -8759,39 +8371,50 @@ class AutoAccumulate {
8759
8371
  }
8760
8372
  }
8761
8373
  /**
8762
- * https://graypaper.fluffylabs.dev/#/7e6ff6a/11da0111da01?v=0.6.7
8374
+ * https://graypaper.fluffylabs.dev/#/ab2cdbd/114402114402?v=0.7.2
8763
8375
  */
8764
8376
  class PrivilegedServices {
8765
8377
  manager;
8766
- authManager;
8767
- validatorsManager;
8378
+ delegator;
8379
+ registrar;
8380
+ assigners;
8768
8381
  autoAccumulateServices;
8382
+ /** https://graypaper.fluffylabs.dev/#/ab2cdbd/3bbd023bcb02?v=0.7.2 */
8769
8383
  static Codec = codec$1.Class(PrivilegedServices, {
8770
8384
  manager: codec$1.u32.asOpaque(),
8771
- authManager: codecPerCore(codec$1.u32.asOpaque()),
8772
- validatorsManager: codec$1.u32.asOpaque(),
8385
+ assigners: codecPerCore(codec$1.u32.asOpaque()),
8386
+ delegator: codec$1.u32.asOpaque(),
8387
+ registrar: Compatibility.isGreaterOrEqual(GpVersion.V0_7_1)
8388
+ ? codec$1.u32.asOpaque()
8389
+ : ignoreValueWithDefault(tryAsServiceId(2 ** 32 - 1)),
8773
8390
  autoAccumulateServices: readonlyArray(codec$1.sequenceVarLen(AutoAccumulate.Codec)),
8774
8391
  });
8775
- static create({ manager, authManager, validatorsManager, autoAccumulateServices }) {
8776
- return new PrivilegedServices(manager, authManager, validatorsManager, autoAccumulateServices);
8392
+ static create(a) {
8393
+ return new PrivilegedServices(a.manager, a.delegator, a.registrar, a.assigners, a.autoAccumulateServices);
8777
8394
  }
8778
8395
  constructor(
8779
8396
  /**
8780
- * `chi_m`: The first, χm, is the index of the manager service which is
8781
- * the service able to effect an alteration of χ from block to block,
8397
+ * `χ_M`: Manages alteration of χ from block to block,
8782
8398
  * as well as bestow services with storage deposit credits.
8783
- * https://graypaper.fluffylabs.dev/#/7e6ff6a/11a40111a801?v=0.6.7
8399
+ * https://graypaper.fluffylabs.dev/#/ab2cdbd/111502111902?v=0.7.2
8784
8400
  */
8785
8401
  manager,
8786
- /** `chi_a`: Manages authorization queue one for each core. */
8787
- authManager,
8788
- /** `chi_v`: Managers validator keys. */
8789
- validatorsManager,
8790
- /** `chi_g`: Dictionary of services that auto-accumulate every block with their gas limit. */
8402
+ /** `χ_V`: Managers validator keys. */
8403
+ delegator,
8404
+ /**
8405
+ * `χ_R`: Manages the creation of services in protected range.
8406
+ *
8407
+ * https://graypaper.fluffylabs.dev/#/ab2cdbd/111b02111d02?v=0.7.2
8408
+ */
8409
+ registrar,
8410
+ /** `χ_A`: Manages authorization queue one for each core. */
8411
+ assigners,
8412
+ /** `χ_Z`: Dictionary of services that auto-accumulate every block with their gas limit. */
8791
8413
  autoAccumulateServices) {
8792
8414
  this.manager = manager;
8793
- this.authManager = authManager;
8794
- this.validatorsManager = validatorsManager;
8415
+ this.delegator = delegator;
8416
+ this.registrar = registrar;
8417
+ this.assigners = assigners;
8795
8418
  this.autoAccumulateServices = autoAccumulateServices;
8796
8419
  }
8797
8420
  }
@@ -9010,212 +8633,46 @@ class SafroleSealingKeysData extends WithDebug {
9010
8633
  throw new Error(`Unexpected safrole sealing keys kind: ${kind}`);
9011
8634
  });
9012
8635
  });
9013
- static keys(keys) {
9014
- return new SafroleSealingKeysData(SafroleSealingKeysKind.Keys, keys, undefined);
9015
- }
9016
- static tickets(tickets) {
9017
- return new SafroleSealingKeysData(SafroleSealingKeysKind.Tickets, undefined, tickets);
9018
- }
9019
- constructor(kind, keys, tickets) {
9020
- super();
9021
- this.kind = kind;
9022
- this.keys = keys;
9023
- this.tickets = tickets;
9024
- }
9025
- }
9026
- class SafroleData {
9027
- nextValidatorData;
9028
- epochRoot;
9029
- sealingKeySeries;
9030
- ticketsAccumulator;
9031
- static Codec = codec$1.Class(SafroleData, {
9032
- nextValidatorData: codecPerValidator(ValidatorData.Codec),
9033
- epochRoot: codec$1.bytes(BANDERSNATCH_RING_ROOT_BYTES).asOpaque(),
9034
- sealingKeySeries: SafroleSealingKeysData.Codec,
9035
- ticketsAccumulator: readonlyArray(codec$1.sequenceVarLen(Ticket.Codec)).convert(seeThrough, asKnownSize),
9036
- });
9037
- static create({ nextValidatorData, epochRoot, sealingKeySeries, ticketsAccumulator }) {
9038
- return new SafroleData(nextValidatorData, epochRoot, sealingKeySeries, ticketsAccumulator);
9039
- }
9040
- constructor(
9041
- /** gamma_k */
9042
- nextValidatorData,
9043
- /** gamma_z */
9044
- epochRoot,
9045
- /** gamma_s */
9046
- sealingKeySeries,
9047
- /** gamma_a */
9048
- ticketsAccumulator) {
9049
- this.nextValidatorData = nextValidatorData;
9050
- this.epochRoot = epochRoot;
9051
- this.sealingKeySeries = sealingKeySeries;
9052
- this.ticketsAccumulator = ticketsAccumulator;
9053
- }
9054
- }
9055
-
9056
- /**
9057
- * `B_S`: The basic minimum balance which all services require.
9058
- *
9059
- * https://graypaper.fluffylabs.dev/#/7e6ff6a/445800445800?v=0.6.7
9060
- */
9061
- const BASE_SERVICE_BALANCE = 100n;
9062
- /**
9063
- * `B_I`: The additional minimum balance required per item of elective service state.
9064
- *
9065
- * https://graypaper.fluffylabs.dev/#/7e6ff6a/445000445000?v=0.6.7
9066
- */
9067
- const ELECTIVE_ITEM_BALANCE = 10n;
9068
- /**
9069
- * `B_L`: The additional minimum balance required per octet of elective service state.
9070
- *
9071
- * https://graypaper.fluffylabs.dev/#/7e6ff6a/445400445400?v=0.6.7
9072
- */
9073
- const ELECTIVE_BYTE_BALANCE = 1n;
9074
- const zeroSizeHint = {
9075
- bytes: 0,
9076
- isExact: true,
9077
- };
9078
- /** 0-byte read, return given default value */
9079
- const ignoreValueWithDefault = (defaultValue) => Descriptor.new("ignoreValue", zeroSizeHint, (_e, _v) => { }, (_d) => defaultValue, (_s) => { });
9080
- /**
9081
- * Service account details.
9082
- *
9083
- * https://graypaper.fluffylabs.dev/#/7e6ff6a/108301108301?v=0.6.7
9084
- */
9085
- class ServiceAccountInfo extends WithDebug {
9086
- codeHash;
9087
- balance;
9088
- accumulateMinGas;
9089
- onTransferMinGas;
9090
- storageUtilisationBytes;
9091
- gratisStorage;
9092
- storageUtilisationCount;
9093
- created;
9094
- lastAccumulation;
9095
- parentService;
9096
- static Codec = codec$1.Class(ServiceAccountInfo, {
9097
- codeHash: codec$1.bytes(HASH_SIZE).asOpaque(),
9098
- balance: codec$1.u64,
9099
- accumulateMinGas: codec$1.u64.convert((x) => x, tryAsServiceGas),
9100
- onTransferMinGas: codec$1.u64.convert((x) => x, tryAsServiceGas),
9101
- storageUtilisationBytes: codec$1.u64,
9102
- gratisStorage: codec$1.u64,
9103
- storageUtilisationCount: codec$1.u32,
9104
- created: codec$1.u32.convert((x) => x, tryAsTimeSlot),
9105
- lastAccumulation: codec$1.u32.convert((x) => x, tryAsTimeSlot),
9106
- parentService: codec$1.u32.convert((x) => x, tryAsServiceId),
9107
- });
9108
- static create(a) {
9109
- return new ServiceAccountInfo(a.codeHash, a.balance, a.accumulateMinGas, a.onTransferMinGas, a.storageUtilisationBytes, a.gratisStorage, a.storageUtilisationCount, a.created, a.lastAccumulation, a.parentService);
9110
- }
9111
- /**
9112
- * `a_t = max(0, BS + BI * a_i + BL * a_o - a_f)`
9113
- * https://graypaper.fluffylabs.dev/#/7e6ff6a/119e01119e01?v=0.6.7
9114
- */
9115
- static calculateThresholdBalance(items, bytes, gratisStorage) {
9116
- const storageCost = BASE_SERVICE_BALANCE + ELECTIVE_ITEM_BALANCE * BigInt(items) + ELECTIVE_BYTE_BALANCE * bytes - gratisStorage;
9117
- if (storageCost < 0n) {
9118
- return tryAsU64(0);
9119
- }
9120
- if (storageCost >= 2n ** 64n) {
9121
- return tryAsU64(2n ** 64n - 1n);
9122
- }
9123
- return tryAsU64(storageCost);
9124
- }
9125
- constructor(
9126
- /** `a_c`: Hash of the service code. */
9127
- codeHash,
9128
- /** `a_b`: Current account balance. */
9129
- balance,
9130
- /** `a_g`: Minimal gas required to execute Accumulate entrypoint. */
9131
- accumulateMinGas,
9132
- /** `a_m`: Minimal gas required to execute On Transfer entrypoint. */
9133
- onTransferMinGas,
9134
- /** `a_o`: Total number of octets in storage. */
9135
- storageUtilisationBytes,
9136
- /** `a_f`: Cost-free storage. Decreases both storage item count and total byte size. */
9137
- gratisStorage,
9138
- /** `a_i`: Number of items in storage. */
9139
- storageUtilisationCount,
9140
- /** `a_r`: Creation account time slot. */
9141
- created,
9142
- /** `a_a`: Most recent accumulation time slot. */
9143
- lastAccumulation,
9144
- /** `a_p`: Parent service ID. */
9145
- parentService) {
9146
- super();
9147
- this.codeHash = codeHash;
9148
- this.balance = balance;
9149
- this.accumulateMinGas = accumulateMinGas;
9150
- this.onTransferMinGas = onTransferMinGas;
9151
- this.storageUtilisationBytes = storageUtilisationBytes;
9152
- this.gratisStorage = gratisStorage;
9153
- this.storageUtilisationCount = storageUtilisationCount;
9154
- this.created = created;
9155
- this.lastAccumulation = lastAccumulation;
9156
- this.parentService = parentService;
9157
- }
9158
- }
9159
- class PreimageItem extends WithDebug {
9160
- hash;
9161
- blob;
9162
- static Codec = codec$1.Class(PreimageItem, {
9163
- hash: codec$1.bytes(HASH_SIZE).asOpaque(),
9164
- blob: codec$1.blob,
9165
- });
9166
- static create({ hash, blob }) {
9167
- return new PreimageItem(hash, blob);
9168
- }
9169
- constructor(hash, blob) {
9170
- super();
9171
- this.hash = hash;
9172
- this.blob = blob;
9173
- }
9174
- }
9175
- class StorageItem extends WithDebug {
9176
- key;
9177
- value;
9178
- static Codec = codec$1.Class(StorageItem, {
9179
- key: codec$1.blob.convert((i) => i, (o) => asOpaqueType(o)),
9180
- value: codec$1.blob,
9181
- });
9182
- static create({ key, value }) {
9183
- return new StorageItem(key, value);
9184
- }
9185
- constructor(key, value) {
9186
- super();
9187
- this.key = key;
9188
- this.value = value;
9189
- }
9190
- }
9191
- const MAX_LOOKUP_HISTORY_SLOTS = 3;
9192
- function tryAsLookupHistorySlots(items) {
9193
- const knownSize = asKnownSize(items);
9194
- if (knownSize.length > MAX_LOOKUP_HISTORY_SLOTS) {
9195
- throw new Error(`Lookup history items must contain 0-${MAX_LOOKUP_HISTORY_SLOTS} timeslots.`);
9196
- }
9197
- return knownSize;
9198
- }
9199
- /** https://graypaper.fluffylabs.dev/#/5f542d7/115400115800 */
9200
- class LookupHistoryItem {
9201
- hash;
9202
- length;
9203
- slots;
9204
- constructor(hash, length,
9205
- /**
9206
- * Preimage availability history as a sequence of time slots.
9207
- * See PreimageStatus and the following GP fragment for more details.
9208
- * https://graypaper.fluffylabs.dev/#/5f542d7/11780011a500 */
9209
- slots) {
9210
- this.hash = hash;
9211
- this.length = length;
9212
- this.slots = slots;
8636
+ static keys(keys) {
8637
+ return new SafroleSealingKeysData(SafroleSealingKeysKind.Keys, keys, undefined);
9213
8638
  }
9214
- static isRequested(item) {
9215
- if ("slots" in item) {
9216
- return item.slots.length === 0;
9217
- }
9218
- return item.length === 0;
8639
+ static tickets(tickets) {
8640
+ return new SafroleSealingKeysData(SafroleSealingKeysKind.Tickets, undefined, tickets);
8641
+ }
8642
+ constructor(kind, keys, tickets) {
8643
+ super();
8644
+ this.kind = kind;
8645
+ this.keys = keys;
8646
+ this.tickets = tickets;
8647
+ }
8648
+ }
8649
+ class SafroleData {
8650
+ nextValidatorData;
8651
+ epochRoot;
8652
+ sealingKeySeries;
8653
+ ticketsAccumulator;
8654
+ static Codec = codec$1.Class(SafroleData, {
8655
+ nextValidatorData: codecPerValidator(ValidatorData.Codec),
8656
+ epochRoot: codec$1.bytes(BANDERSNATCH_RING_ROOT_BYTES).asOpaque(),
8657
+ sealingKeySeries: SafroleSealingKeysData.Codec,
8658
+ ticketsAccumulator: readonlyArray(codec$1.sequenceVarLen(Ticket.Codec)).convert(seeThrough, asKnownSize),
8659
+ });
8660
+ static create({ nextValidatorData, epochRoot, sealingKeySeries, ticketsAccumulator }) {
8661
+ return new SafroleData(nextValidatorData, epochRoot, sealingKeySeries, ticketsAccumulator);
8662
+ }
8663
+ constructor(
8664
+ /** gamma_k */
8665
+ nextValidatorData,
8666
+ /** gamma_z */
8667
+ epochRoot,
8668
+ /** gamma_s */
8669
+ sealingKeySeries,
8670
+ /** gamma_a */
8671
+ ticketsAccumulator) {
8672
+ this.nextValidatorData = nextValidatorData;
8673
+ this.epochRoot = epochRoot;
8674
+ this.sealingKeySeries = sealingKeySeries;
8675
+ this.ticketsAccumulator = ticketsAccumulator;
9219
8676
  }
9220
8677
  }
9221
8678
 
@@ -10026,8 +9483,9 @@ class InMemoryState extends WithDebug {
10026
9483
  epochRoot: Bytes.zero(BANDERSNATCH_RING_ROOT_BYTES).asOpaque(),
10027
9484
  privilegedServices: PrivilegedServices.create({
10028
9485
  manager: tryAsServiceId(0),
10029
- authManager: tryAsPerCore(new Array(spec.coresCount).fill(tryAsServiceId(0)), spec),
10030
- validatorsManager: tryAsServiceId(0),
9486
+ assigners: tryAsPerCore(new Array(spec.coresCount).fill(tryAsServiceId(0)), spec),
9487
+ delegator: tryAsServiceId(0),
9488
+ registrar: tryAsServiceId(MAX_VALUE),
10031
9489
  autoAccumulateServices: [],
10032
9490
  }),
10033
9491
  accumulationOutputLog: SortedArray.fromArray(accumulationOutputComparator, []),
@@ -10047,7 +9505,7 @@ const serviceDataCodec = codec$1.dictionary(codec$1.u32.asOpaque(), serviceEntri
10047
9505
  sortKeys: (a, b) => a - b,
10048
9506
  });
10049
9507
 
10050
- var index$e = /*#__PURE__*/Object.freeze({
9508
+ var index$g = /*#__PURE__*/Object.freeze({
10051
9509
  __proto__: null,
10052
9510
  AccumulationOutput: AccumulationOutput,
10053
9511
  AutoAccumulate: AutoAccumulate,
@@ -10086,6 +9544,7 @@ var index$e = /*#__PURE__*/Object.freeze({
10086
9544
  ValidatorStatistics: ValidatorStatistics,
10087
9545
  accumulationOutputComparator: accumulationOutputComparator,
10088
9546
  codecPerCore: codecPerCore,
9547
+ codecWithVersion: codecWithVersion,
10089
9548
  hashComparator: hashComparator,
10090
9549
  ignoreValueWithDefault: ignoreValueWithDefault,
10091
9550
  serviceDataCodec: serviceDataCodec,
@@ -10246,21 +9705,23 @@ var serialize;
10246
9705
  /** C(255, s): https://graypaper.fluffylabs.dev/#/85129da/383103383103?v=0.6.3 */
10247
9706
  serialize.serviceData = (serviceId) => ({
10248
9707
  key: stateKeys.serviceInfo(serviceId),
10249
- Codec: ServiceAccountInfo.Codec,
9708
+ Codec: Compatibility.isGreaterOrEqual(GpVersion.V0_7_1)
9709
+ ? codecWithVersion(ServiceAccountInfo.Codec)
9710
+ : ServiceAccountInfo.Codec,
10250
9711
  });
10251
9712
  /** https://graypaper.fluffylabs.dev/#/85129da/384803384803?v=0.6.3 */
10252
- serialize.serviceStorage = (serviceId, key) => ({
10253
- key: stateKeys.serviceStorage(serviceId, key),
9713
+ serialize.serviceStorage = (blake2b, serviceId, key) => ({
9714
+ key: stateKeys.serviceStorage(blake2b, serviceId, key),
10254
9715
  Codec: dumpCodec,
10255
9716
  });
10256
9717
  /** https://graypaper.fluffylabs.dev/#/85129da/385b03385b03?v=0.6.3 */
10257
- serialize.servicePreimages = (serviceId, hash) => ({
10258
- key: stateKeys.servicePreimage(serviceId, hash),
9718
+ serialize.servicePreimages = (blake2b, serviceId, hash) => ({
9719
+ key: stateKeys.servicePreimage(blake2b, serviceId, hash),
10259
9720
  Codec: dumpCodec,
10260
9721
  });
10261
9722
  /** https://graypaper.fluffylabs.dev/#/85129da/387603387603?v=0.6.3 */
10262
- serialize.serviceLookupHistory = (serviceId, hash, len) => ({
10263
- key: stateKeys.serviceLookupHistory(serviceId, hash, len),
9723
+ serialize.serviceLookupHistory = (blake2b, serviceId, hash, len) => ({
9724
+ key: stateKeys.serviceLookupHistory(blake2b, serviceId, hash, len),
10264
9725
  Codec: readonlyArray(codec$1.sequenceVarLen(codec$1.u32)),
10265
9726
  });
10266
9727
  })(serialize || (serialize = {}));
@@ -10283,20 +9744,22 @@ const dumpCodec = Descriptor.new("Dump", { bytes: 64, isExact: false }, (e, v) =
10283
9744
  */
10284
9745
  class SerializedState {
10285
9746
  spec;
9747
+ blake2b;
10286
9748
  backend;
10287
9749
  _recentServiceIds;
10288
9750
  /** Create a state-like object from collection of serialized entries. */
10289
- static fromStateEntries(spec, state, recentServices = []) {
10290
- return new SerializedState(spec, state, recentServices);
9751
+ static fromStateEntries(spec, blake2b, state, recentServices = []) {
9752
+ return new SerializedState(spec, blake2b, state, recentServices);
10291
9753
  }
10292
9754
  /** Create a state-like object backed by some DB. */
10293
- static new(spec, db, recentServices = []) {
10294
- return new SerializedState(spec, db, recentServices);
9755
+ static new(spec, blake2b, db, recentServices = []) {
9756
+ return new SerializedState(spec, blake2b, db, recentServices);
10295
9757
  }
10296
- constructor(spec, backend,
9758
+ constructor(spec, blake2b, backend,
10297
9759
  /** Best-effort list of recently active services. */
10298
9760
  _recentServiceIds) {
10299
9761
  this.spec = spec;
9762
+ this.blake2b = blake2b;
10300
9763
  this.backend = backend;
10301
9764
  this._recentServiceIds = _recentServiceIds;
10302
9765
  }
@@ -10320,7 +9783,7 @@ class SerializedState {
10320
9783
  if (!this._recentServiceIds.includes(id)) {
10321
9784
  this._recentServiceIds.push(id);
10322
9785
  }
10323
- return new SerializedService(id, serviceData, (key) => this.retrieveOptional(key));
9786
+ return new SerializedService(this.blake2b, id, serviceData, (key) => this.retrieveOptional(key));
10324
9787
  }
10325
9788
  retrieve({ key, Codec }, description) {
10326
9789
  const bytes = this.backend.get(key);
@@ -10396,12 +9859,14 @@ class SerializedState {
10396
9859
  }
10397
9860
  /** Service data representation on a serialized state. */
10398
9861
  class SerializedService {
9862
+ blake2b;
10399
9863
  serviceId;
10400
9864
  accountInfo;
10401
9865
  retrieveOptional;
10402
- constructor(
9866
+ constructor(blake2b,
10403
9867
  /** Service id */
10404
9868
  serviceId, accountInfo, retrieveOptional) {
9869
+ this.blake2b = blake2b;
10405
9870
  this.serviceId = serviceId;
10406
9871
  this.accountInfo = accountInfo;
10407
9872
  this.retrieveOptional = retrieveOptional;
@@ -10414,13 +9879,13 @@ class SerializedService {
10414
9879
  getStorage(rawKey) {
10415
9880
  if (Compatibility.isLessThan(GpVersion.V0_6_7)) {
10416
9881
  const SERVICE_ID_BYTES = 4;
10417
- const serviceIdAndKey = new Uint8Array(SERVICE_ID_BYTES + rawKey.length);
9882
+ const serviceIdAndKey = safeAllocUint8Array(SERVICE_ID_BYTES + rawKey.length);
10418
9883
  serviceIdAndKey.set(u32AsLeBytes(this.serviceId));
10419
9884
  serviceIdAndKey.set(rawKey.raw, SERVICE_ID_BYTES);
10420
- const key = asOpaqueType(BytesBlob.blobFrom(hashBytes(serviceIdAndKey).raw));
10421
- return this.retrieveOptional(serialize.serviceStorage(this.serviceId, key)) ?? null;
9885
+ const key = asOpaqueType(BytesBlob.blobFrom(this.blake2b.hashBytes(serviceIdAndKey).raw));
9886
+ return this.retrieveOptional(serialize.serviceStorage(this.blake2b, this.serviceId, key)) ?? null;
10422
9887
  }
10423
- return this.retrieveOptional(serialize.serviceStorage(this.serviceId, rawKey)) ?? null;
9888
+ return this.retrieveOptional(serialize.serviceStorage(this.blake2b, this.serviceId, rawKey)) ?? null;
10424
9889
  }
10425
9890
  /**
10426
9891
  * Check if preimage is present in the DB.
@@ -10429,15 +9894,15 @@ class SerializedService {
10429
9894
  */
10430
9895
  hasPreimage(hash) {
10431
9896
  // TODO [ToDr] consider optimizing to avoid fetching the whole data.
10432
- return this.retrieveOptional(serialize.servicePreimages(this.serviceId, hash)) !== undefined;
9897
+ return this.retrieveOptional(serialize.servicePreimages(this.blake2b, this.serviceId, hash)) !== undefined;
10433
9898
  }
10434
9899
  /** Retrieve preimage from the DB. */
10435
9900
  getPreimage(hash) {
10436
- return this.retrieveOptional(serialize.servicePreimages(this.serviceId, hash)) ?? null;
9901
+ return this.retrieveOptional(serialize.servicePreimages(this.blake2b, this.serviceId, hash)) ?? null;
10437
9902
  }
10438
9903
  /** Retrieve preimage lookup history. */
10439
9904
  getLookupHistory(hash, len) {
10440
- const rawSlots = this.retrieveOptional(serialize.serviceLookupHistory(this.serviceId, hash, len));
9905
+ const rawSlots = this.retrieveOptional(serialize.serviceLookupHistory(this.blake2b, this.serviceId, hash, len));
10441
9906
  if (rawSlots === undefined) {
10442
9907
  return null;
10443
9908
  }
@@ -10499,7 +9964,7 @@ class TrieNode {
10499
9964
  raw;
10500
9965
  constructor(
10501
9966
  /** Exactly 512 bits / 64 bytes */
10502
- raw = new Uint8Array(TRIE_NODE_BYTES)) {
9967
+ raw = safeAllocUint8Array(TRIE_NODE_BYTES)) {
10503
9968
  this.raw = raw;
10504
9969
  }
10505
9970
  /** Returns the type of the node */
@@ -11057,7 +10522,7 @@ const bitLookup = [
11057
10522
  [0b00000000, 8],
11058
10523
  ];
11059
10524
 
11060
- var index$d = /*#__PURE__*/Object.freeze({
10525
+ var index$f = /*#__PURE__*/Object.freeze({
11061
10526
  __proto__: null,
11062
10527
  BranchNode: BranchNode,
11063
10528
  InMemoryTrie: InMemoryTrie,
@@ -11074,11 +10539,13 @@ var index$d = /*#__PURE__*/Object.freeze({
11074
10539
  parseInputKey: parseInputKey
11075
10540
  });
11076
10541
 
11077
- const blake2bTrieHasher = {
11078
- hashConcat(n, rest = []) {
11079
- return hashBlobs$1([n, ...rest]);
11080
- },
11081
- };
10542
+ function getBlake2bTrieHasher(hasher) {
10543
+ return {
10544
+ hashConcat(n, rest = []) {
10545
+ return hasher.hashBlobs([n, ...rest]);
10546
+ },
10547
+ };
10548
+ }
11082
10549
 
11083
10550
  /** What should be done with that key? */
11084
10551
  var StateEntryUpdateAction;
@@ -11090,14 +10557,14 @@ var StateEntryUpdateAction;
11090
10557
  })(StateEntryUpdateAction || (StateEntryUpdateAction = {}));
11091
10558
  const EMPTY_BLOB = BytesBlob.empty();
11092
10559
  /** Serialize given state update into a series of key-value pairs. */
11093
- function* serializeStateUpdate(spec, update) {
10560
+ function* serializeStateUpdate(spec, blake2b, update) {
11094
10561
  // first let's serialize all of the simple entries (if present!)
11095
10562
  yield* serializeBasicKeys(spec, update);
11096
10563
  const encode = (codec, val) => Encoder.encodeObject(codec, val, spec);
11097
10564
  // then let's proceed with service updates
11098
- yield* serializeServiceUpdates(update.servicesUpdates, encode);
11099
- yield* serializePreimages(update.preimages, encode);
11100
- yield* serializeStorage(update.storage);
10565
+ yield* serializeServiceUpdates(update.servicesUpdates, encode, blake2b);
10566
+ yield* serializePreimages(update.preimages, encode, blake2b);
10567
+ yield* serializeStorage(update.storage, blake2b);
11101
10568
  yield* serializeRemovedServices(update.servicesRemoved);
11102
10569
  }
11103
10570
  function* serializeRemovedServices(servicesRemoved) {
@@ -11107,18 +10574,18 @@ function* serializeRemovedServices(servicesRemoved) {
11107
10574
  yield [StateEntryUpdateAction.Remove, codec.key, EMPTY_BLOB];
11108
10575
  }
11109
10576
  }
11110
- function* serializeStorage(storage) {
10577
+ function* serializeStorage(storage, blake2b) {
11111
10578
  for (const { action, serviceId } of storage ?? []) {
11112
10579
  switch (action.kind) {
11113
10580
  case UpdateStorageKind.Set: {
11114
10581
  const key = action.storage.key;
11115
- const codec = serialize.serviceStorage(serviceId, key);
10582
+ const codec = serialize.serviceStorage(blake2b, serviceId, key);
11116
10583
  yield [StateEntryUpdateAction.Insert, codec.key, action.storage.value];
11117
10584
  break;
11118
10585
  }
11119
10586
  case UpdateStorageKind.Remove: {
11120
10587
  const key = action.key;
11121
- const codec = serialize.serviceStorage(serviceId, key);
10588
+ const codec = serialize.serviceStorage(blake2b, serviceId, key);
11122
10589
  yield [StateEntryUpdateAction.Remove, codec.key, EMPTY_BLOB];
11123
10590
  break;
11124
10591
  }
@@ -11127,15 +10594,15 @@ function* serializeStorage(storage) {
11127
10594
  }
11128
10595
  }
11129
10596
  }
11130
- function* serializePreimages(preimages, encode) {
10597
+ function* serializePreimages(preimages, encode, blake2b) {
11131
10598
  for (const { action, serviceId } of preimages ?? []) {
11132
10599
  switch (action.kind) {
11133
10600
  case UpdatePreimageKind.Provide: {
11134
10601
  const { hash, blob } = action.preimage;
11135
- const codec = serialize.servicePreimages(serviceId, hash);
10602
+ const codec = serialize.servicePreimages(blake2b, serviceId, hash);
11136
10603
  yield [StateEntryUpdateAction.Insert, codec.key, blob];
11137
10604
  if (action.slot !== null) {
11138
- const codec2 = serialize.serviceLookupHistory(serviceId, hash, tryAsU32(blob.length));
10605
+ const codec2 = serialize.serviceLookupHistory(blake2b, serviceId, hash, tryAsU32(blob.length));
11139
10606
  yield [
11140
10607
  StateEntryUpdateAction.Insert,
11141
10608
  codec2.key,
@@ -11146,15 +10613,15 @@ function* serializePreimages(preimages, encode) {
11146
10613
  }
11147
10614
  case UpdatePreimageKind.UpdateOrAdd: {
11148
10615
  const { hash, length, slots } = action.item;
11149
- const codec = serialize.serviceLookupHistory(serviceId, hash, length);
10616
+ const codec = serialize.serviceLookupHistory(blake2b, serviceId, hash, length);
11150
10617
  yield [StateEntryUpdateAction.Insert, codec.key, encode(codec.Codec, slots)];
11151
10618
  break;
11152
10619
  }
11153
10620
  case UpdatePreimageKind.Remove: {
11154
10621
  const { hash, length } = action;
11155
- const codec = serialize.servicePreimages(serviceId, hash);
10622
+ const codec = serialize.servicePreimages(blake2b, serviceId, hash);
11156
10623
  yield [StateEntryUpdateAction.Remove, codec.key, EMPTY_BLOB];
11157
- const codec2 = serialize.serviceLookupHistory(serviceId, hash, length);
10624
+ const codec2 = serialize.serviceLookupHistory(blake2b, serviceId, hash, length);
11158
10625
  yield [StateEntryUpdateAction.Remove, codec2.key, EMPTY_BLOB];
11159
10626
  break;
11160
10627
  }
@@ -11163,7 +10630,7 @@ function* serializePreimages(preimages, encode) {
11163
10630
  }
11164
10631
  }
11165
10632
  }
11166
- function* serializeServiceUpdates(servicesUpdates, encode) {
10633
+ function* serializeServiceUpdates(servicesUpdates, encode, blake2b) {
11167
10634
  for (const { action, serviceId } of servicesUpdates ?? []) {
11168
10635
  // new service being created or updated
11169
10636
  const codec = serialize.serviceData(serviceId);
@@ -11171,7 +10638,7 @@ function* serializeServiceUpdates(servicesUpdates, encode) {
11171
10638
  // additional lookup history update
11172
10639
  if (action.kind === UpdateServiceKind.Create && action.lookupHistory !== null) {
11173
10640
  const { lookupHistory } = action;
11174
- const codec2 = serialize.serviceLookupHistory(serviceId, lookupHistory.hash, lookupHistory.length);
10641
+ const codec2 = serialize.serviceLookupHistory(blake2b, serviceId, lookupHistory.hash, lookupHistory.length);
11175
10642
  yield [StateEntryUpdateAction.Insert, codec2.key, encode(codec2.Codec, lookupHistory.slots)];
11176
10643
  }
11177
10644
  }
@@ -11266,8 +10733,8 @@ class StateEntries {
11266
10733
  },
11267
10734
  }, (e, v) => stateEntriesSequenceCodec.encode(e, Array.from(v.entries)), (d) => StateEntries.fromEntriesUnsafe(stateEntriesSequenceCodec.decode(d)), (s) => stateEntriesSequenceCodec.skip(s));
11268
10735
  /** Turn in-memory state into it's serialized form. */
11269
- static serializeInMemory(spec, state) {
11270
- return new StateEntries(convertInMemoryStateToDictionary(spec, state));
10736
+ static serializeInMemory(spec, blake2b, state) {
10737
+ return new StateEntries(convertInMemoryStateToDictionary(spec, blake2b, state));
11271
10738
  }
11272
10739
  /**
11273
10740
  * Wrap a collection of truncated state entries and treat it as state.
@@ -11316,7 +10783,8 @@ class StateEntries {
11316
10783
  }
11317
10784
  }
11318
10785
  /** https://graypaper.fluffylabs.dev/#/68eaa1f/391600391600?v=0.6.4 */
11319
- getRootHash() {
10786
+ getRootHash(blake2b) {
10787
+ const blake2bTrieHasher = getBlake2bTrieHasher(blake2b);
11320
10788
  const leaves = SortedSet.fromArray(leafComparator);
11321
10789
  for (const [key, value] of this) {
11322
10790
  leaves.insert(InMemoryTrie.constructLeaf(blake2bTrieHasher, key.asOpaque(), value));
@@ -11325,7 +10793,7 @@ class StateEntries {
11325
10793
  }
11326
10794
  }
11327
10795
  /** https://graypaper.fluffylabs.dev/#/68eaa1f/38a50038a500?v=0.6.4 */
11328
- function convertInMemoryStateToDictionary(spec, state) {
10796
+ function convertInMemoryStateToDictionary(spec, blake2b, state) {
11329
10797
  const serialized = TruncatedHashDictionary.fromEntries([]);
11330
10798
  function doSerialize(codec) {
11331
10799
  serialized.set(codec.key, Encoder.encodeObject(codec.Codec, codec.extract(state), spec));
@@ -11353,18 +10821,18 @@ function convertInMemoryStateToDictionary(spec, state) {
11353
10821
  serialized.set(key, Encoder.encodeObject(Codec, service.getInfo()));
11354
10822
  // preimages
11355
10823
  for (const preimage of service.data.preimages.values()) {
11356
- const { key, Codec } = serialize.servicePreimages(serviceId, preimage.hash);
10824
+ const { key, Codec } = serialize.servicePreimages(blake2b, serviceId, preimage.hash);
11357
10825
  serialized.set(key, Encoder.encodeObject(Codec, preimage.blob));
11358
10826
  }
11359
10827
  // storage
11360
10828
  for (const storage of service.data.storage.values()) {
11361
- const { key, Codec } = serialize.serviceStorage(serviceId, storage.key);
10829
+ const { key, Codec } = serialize.serviceStorage(blake2b, serviceId, storage.key);
11362
10830
  serialized.set(key, Encoder.encodeObject(Codec, storage.value));
11363
10831
  }
11364
10832
  // lookup history
11365
10833
  for (const lookupHistoryList of service.data.lookupHistory.values()) {
11366
10834
  for (const lookupHistory of lookupHistoryList) {
11367
- const { key, Codec } = serialize.serviceLookupHistory(serviceId, lookupHistory.hash, lookupHistory.length);
10835
+ const { key, Codec } = serialize.serviceLookupHistory(blake2b, serviceId, lookupHistory.hash, lookupHistory.length);
11368
10836
  serialized.set(key, Encoder.encodeObject(Codec, lookupHistory.slots.slice()));
11369
10837
  }
11370
10838
  }
@@ -11372,9 +10840,9 @@ function convertInMemoryStateToDictionary(spec, state) {
11372
10840
  return serialized;
11373
10841
  }
11374
10842
 
11375
- function loadState(spec, entries) {
10843
+ function loadState(spec, blake2b, entries) {
11376
10844
  const stateEntries = StateEntries.fromEntriesUnsafe(entries);
11377
- return SerializedState.fromStateEntries(spec, stateEntries);
10845
+ return SerializedState.fromStateEntries(spec, blake2b, stateEntries);
11378
10846
  }
11379
10847
 
11380
10848
  /**
@@ -11403,7 +10871,7 @@ function loadState(spec, entries) {
11403
10871
  * hashmap of `key -> value` entries.
11404
10872
  */
11405
10873
 
11406
- var index$c = /*#__PURE__*/Object.freeze({
10874
+ var index$e = /*#__PURE__*/Object.freeze({
11407
10875
  __proto__: null,
11408
10876
  SerializedService: SerializedService,
11409
10877
  SerializedState: SerializedState,
@@ -11482,7 +10950,8 @@ class LeafDb {
11482
10950
  }
11483
10951
  assertNever(val);
11484
10952
  }
11485
- getStateRoot() {
10953
+ getStateRoot(blake2b) {
10954
+ const blake2bTrieHasher = getBlake2bTrieHasher(blake2b);
11486
10955
  return InMemoryTrie.computeStateRoot(blake2bTrieHasher, this.leaves).asOpaque();
11487
10956
  }
11488
10957
  intoStateEntries() {
@@ -11672,7 +11141,8 @@ class InMemoryStates {
11672
11141
  }
11673
11142
  }
11674
11143
  async getStateRoot(state) {
11675
- return StateEntries.serializeInMemory(this.spec, state).getRootHash();
11144
+ const blake2b = await Blake2b.createHasher();
11145
+ return StateEntries.serializeInMemory(this.spec, blake2b, state).getRootHash(blake2b);
11676
11146
  }
11677
11147
  /** Insert a full state into the database. */
11678
11148
  async insertState(headerHash, state) {
@@ -11689,7 +11159,7 @@ class InMemoryStates {
11689
11159
  }
11690
11160
  }
11691
11161
 
11692
- var index$b = /*#__PURE__*/Object.freeze({
11162
+ var index$d = /*#__PURE__*/Object.freeze({
11693
11163
  __proto__: null,
11694
11164
  InMemoryBlocks: InMemoryBlocks,
11695
11165
  InMemoryStates: InMemoryStates,
@@ -11750,7 +11220,7 @@ function padAndEncodeData(input) {
11750
11220
  const paddedLength = Math.ceil(input.length / PIECE_SIZE) * PIECE_SIZE;
11751
11221
  let padded = input;
11752
11222
  if (input.length !== paddedLength) {
11753
- padded = BytesBlob.blobFrom(new Uint8Array(paddedLength));
11223
+ padded = BytesBlob.blobFrom(safeAllocUint8Array(paddedLength));
11754
11224
  padded.raw.set(input.raw, 0);
11755
11225
  }
11756
11226
  return chunkingFunction(padded);
@@ -11796,7 +11266,7 @@ function decodeData(input) {
11796
11266
  */
11797
11267
  function encodePoints(input) {
11798
11268
  const result = [];
11799
- const data = new Uint8Array(POINT_ALIGNMENT * N_CHUNKS_REQUIRED);
11269
+ const data = safeAllocUint8Array(POINT_ALIGNMENT * N_CHUNKS_REQUIRED);
11800
11270
  // add original shards to the result
11801
11271
  for (let i = 0; i < N_CHUNKS_REQUIRED; i++) {
11802
11272
  const pointStart = POINT_LENGTH * i;
@@ -11812,7 +11282,7 @@ function encodePoints(input) {
11812
11282
  const encodedData = encodedResult.take_data();
11813
11283
  for (let i = 0; i < N_CHUNKS_REDUNDANCY; i++) {
11814
11284
  const pointIndex = i * POINT_ALIGNMENT;
11815
- const redundancyPoint = new Uint8Array(POINT_LENGTH);
11285
+ const redundancyPoint = safeAllocUint8Array(POINT_LENGTH);
11816
11286
  for (let j = 0; j < POINT_LENGTH; j++) {
11817
11287
  redundancyPoint[j] = encodedData[pointIndex + j * HALF_POINT_SIZE];
11818
11288
  }
@@ -11827,7 +11297,7 @@ function encodePoints(input) {
11827
11297
  */
11828
11298
  function decodePiece(input) {
11829
11299
  const result = Bytes.zero(PIECE_SIZE);
11830
- const data = new Uint8Array(N_CHUNKS_REQUIRED * POINT_ALIGNMENT);
11300
+ const data = safeAllocUint8Array(N_CHUNKS_REQUIRED * POINT_ALIGNMENT);
11831
11301
  const indices = new Uint16Array(input.length);
11832
11302
  for (let i = 0; i < N_CHUNKS_REQUIRED; i++) {
11833
11303
  const [index, points] = input[i];
@@ -11943,7 +11413,7 @@ function lace(input) {
11943
11413
  return BytesBlob.empty();
11944
11414
  }
11945
11415
  const n = input[0].length;
11946
- const result = BytesBlob.blobFrom(new Uint8Array(k * n));
11416
+ const result = BytesBlob.blobFrom(safeAllocUint8Array(k * n));
11947
11417
  for (let i = 0; i < k; i++) {
11948
11418
  const entry = input[i].raw;
11949
11419
  for (let j = 0; j < n; j++) {
@@ -12051,7 +11521,7 @@ const initEc = async () => {
12051
11521
  await init.reedSolomon();
12052
11522
  };
12053
11523
 
12054
- var index$a = /*#__PURE__*/Object.freeze({
11524
+ var index$c = /*#__PURE__*/Object.freeze({
12055
11525
  __proto__: null,
12056
11526
  N_CHUNKS_REDUNDANCY: N_CHUNKS_REDUNDANCY,
12057
11527
  N_CHUNKS_REQUIRED: N_CHUNKS_REQUIRED,
@@ -12075,6 +11545,439 @@ var index$a = /*#__PURE__*/Object.freeze({
12075
11545
  unzip: unzip
12076
11546
  });
12077
11547
 
11548
+ /**
11549
+ * Version ::= SEQUENCE {
11550
+ * major INTEGER (0..255),
11551
+ * minor INTEGER (0..255),
11552
+ * patch INTEGER (0..255)
11553
+ * }
11554
+ */
11555
+ class Version extends WithDebug {
11556
+ major;
11557
+ minor;
11558
+ patch;
11559
+ static Codec = codec$1.Class(Version, {
11560
+ major: codec$1.u8,
11561
+ minor: codec$1.u8,
11562
+ patch: codec$1.u8,
11563
+ });
11564
+ static tryFromString(str) {
11565
+ const parse = (v) => tryAsU8(Number(v));
11566
+ try {
11567
+ const [major, minor, patch] = str.trim().split(".").map(parse);
11568
+ return Version.create({
11569
+ major,
11570
+ minor,
11571
+ patch,
11572
+ });
11573
+ }
11574
+ catch (e) {
11575
+ throw new Error(`Unable to parse ${str} as Version: ${e}`);
11576
+ }
11577
+ }
11578
+ static create({ major, minor, patch }) {
11579
+ return new Version(major, minor, patch);
11580
+ }
11581
+ constructor(major, minor, patch) {
11582
+ super();
11583
+ this.major = major;
11584
+ this.minor = minor;
11585
+ this.patch = patch;
11586
+ }
11587
+ }
11588
+ /**
11589
+ * Fuzzer Protocol V1
11590
+ * Reference: https://github.com/davxy/jam-conformance/blob/main/fuzz-proto/fuzz.asn
11591
+ */
11592
+ // Feature bit constants
11593
+ var Features;
11594
+ (function (Features) {
11595
+ Features[Features["Ancestry"] = 1] = "Ancestry";
11596
+ Features[Features["Fork"] = 2] = "Fork";
11597
+ Features[Features["Reserved"] = 2147483648] = "Reserved";
11598
+ })(Features || (Features = {}));
11599
+ /**
11600
+ * PeerInfo ::= SEQUENCE {
11601
+ * fuzz-version U8,
11602
+ * features Features,
11603
+ * jam-version Version,
11604
+ * app-version Version,
11605
+ * name UTF8String
11606
+ * }
11607
+ */
11608
+ class PeerInfo extends WithDebug {
11609
+ fuzzVersion;
11610
+ features;
11611
+ jamVersion;
11612
+ appVersion;
11613
+ name;
11614
+ static Codec = codec$1.Class(PeerInfo, {
11615
+ fuzzVersion: codec$1.u8,
11616
+ features: codec$1.u32,
11617
+ jamVersion: Version.Codec,
11618
+ appVersion: Version.Codec,
11619
+ name: codec$1.string,
11620
+ });
11621
+ static create({ fuzzVersion, features, appVersion, jamVersion, name }) {
11622
+ return new PeerInfo(fuzzVersion, features, jamVersion, appVersion, name);
11623
+ }
11624
+ constructor(fuzzVersion, features, jamVersion, appVersion, name) {
11625
+ super();
11626
+ this.fuzzVersion = fuzzVersion;
11627
+ this.features = features;
11628
+ this.jamVersion = jamVersion;
11629
+ this.appVersion = appVersion;
11630
+ this.name = name;
11631
+ }
11632
+ }
11633
+ /**
11634
+ * AncestryItem ::= SEQUENCE {
11635
+ * slot TimeSlot,
11636
+ * header-hash HeaderHash
11637
+ * }
11638
+ */
11639
+ class AncestryItem extends WithDebug {
11640
+ slot;
11641
+ headerHash;
11642
+ static Codec = codec$1.Class(AncestryItem, {
11643
+ slot: codec$1.u32.asOpaque(),
11644
+ headerHash: codec$1.bytes(HASH_SIZE).asOpaque(),
11645
+ });
11646
+ static create({ slot, headerHash }) {
11647
+ return new AncestryItem(slot, headerHash);
11648
+ }
11649
+ constructor(slot, headerHash) {
11650
+ super();
11651
+ this.slot = slot;
11652
+ this.headerHash = headerHash;
11653
+ }
11654
+ }
11655
+ /**
11656
+ * KeyValue ::= SEQUENCE {
11657
+ * key TrieKey,
11658
+ * value OCTET STRING
11659
+ * }
11660
+ */
11661
+ class KeyValue extends WithDebug {
11662
+ key;
11663
+ value;
11664
+ static Codec = codec$1.Class(KeyValue, {
11665
+ key: codec$1.bytes(TRUNCATED_HASH_SIZE),
11666
+ value: codec$1.blob,
11667
+ });
11668
+ static create({ key, value }) {
11669
+ return new KeyValue(key, value);
11670
+ }
11671
+ constructor(key, value) {
11672
+ super();
11673
+ this.key = key;
11674
+ this.value = value;
11675
+ }
11676
+ }
11677
+ /** State ::= SEQUENCE OF KeyValue */
11678
+ const stateCodec = codec$1.sequenceVarLen(KeyValue.Codec);
11679
+ /**
11680
+ * Ancestry ::= SEQUENCE (SIZE(0..24)) OF AncestryItem
11681
+ * Empty when `feature-ancestry` is not supported by both parties
11682
+ */
11683
+ const ancestryCodec = codec$1.sequenceVarLen(AncestryItem.Codec, {
11684
+ minLength: 0,
11685
+ maxLength: 24,
11686
+ });
11687
+ /**
11688
+ * Initialize ::= SEQUENCE {
11689
+ * header Header,
11690
+ * keyvals State,
11691
+ * ancestry Ancestry
11692
+ * }
11693
+ */
11694
+ class Initialize extends WithDebug {
11695
+ header;
11696
+ keyvals;
11697
+ ancestry;
11698
+ static Codec = codec$1.Class(Initialize, {
11699
+ header: Header.Codec,
11700
+ keyvals: stateCodec,
11701
+ ancestry: ancestryCodec,
11702
+ });
11703
+ static create({ header, keyvals, ancestry }) {
11704
+ return new Initialize(header, keyvals, ancestry);
11705
+ }
11706
+ constructor(header, keyvals, ancestry) {
11707
+ super();
11708
+ this.header = header;
11709
+ this.keyvals = keyvals;
11710
+ this.ancestry = ancestry;
11711
+ }
11712
+ }
11713
+ /** GetState ::= HeaderHash */
11714
+ const getStateCodec = codec$1.bytes(HASH_SIZE).asOpaque();
11715
+ /** StateRoot ::= StateRootHash */
11716
+ const stateRootCodec = codec$1.bytes(HASH_SIZE).asOpaque();
11717
+ /** Error ::= UTF8String */
11718
+ class ErrorMessage extends WithDebug {
11719
+ message;
11720
+ static Codec = codec$1.Class(ErrorMessage, {
11721
+ message: codec$1.string,
11722
+ });
11723
+ static create({ message }) {
11724
+ return new ErrorMessage(message);
11725
+ }
11726
+ constructor(message) {
11727
+ super();
11728
+ this.message = message;
11729
+ }
11730
+ }
11731
+ /** Message choice type tags */
11732
+ var MessageType;
11733
+ (function (MessageType) {
11734
+ MessageType[MessageType["PeerInfo"] = 0] = "PeerInfo";
11735
+ MessageType[MessageType["Initialize"] = 1] = "Initialize";
11736
+ MessageType[MessageType["StateRoot"] = 2] = "StateRoot";
11737
+ MessageType[MessageType["ImportBlock"] = 3] = "ImportBlock";
11738
+ MessageType[MessageType["GetState"] = 4] = "GetState";
11739
+ MessageType[MessageType["State"] = 5] = "State";
11740
+ MessageType[MessageType["Error"] = 255] = "Error";
11741
+ })(MessageType || (MessageType = {}));
11742
+ /**
11743
+ * Message ::= CHOICE {
11744
+ * peer-info [0] PeerInfo,
11745
+ * initialize [1] Initialize,
11746
+ * state-root [2] StateRoot,
11747
+ * import-block [3] ImportBlock,
11748
+ * get-state [4] GetState,
11749
+ * state [5] State,
11750
+ * error [255] Error
11751
+ * }
11752
+ */
11753
+ const messageCodec = codec$1.custom({
11754
+ name: "Message",
11755
+ sizeHint: { bytes: 1, isExact: false },
11756
+ }, (e, msg) => {
11757
+ e.i8(msg.type);
11758
+ switch (msg.type) {
11759
+ case MessageType.PeerInfo:
11760
+ PeerInfo.Codec.encode(e, msg.value);
11761
+ break;
11762
+ case MessageType.Initialize:
11763
+ Initialize.Codec.encode(e, msg.value);
11764
+ break;
11765
+ case MessageType.StateRoot:
11766
+ stateRootCodec.encode(e, msg.value);
11767
+ break;
11768
+ case MessageType.ImportBlock:
11769
+ Block.Codec.View.encode(e, msg.value);
11770
+ break;
11771
+ case MessageType.GetState:
11772
+ getStateCodec.encode(e, msg.value);
11773
+ break;
11774
+ case MessageType.State:
11775
+ stateCodec.encode(e, msg.value);
11776
+ break;
11777
+ case MessageType.Error:
11778
+ ErrorMessage.Codec.encode(e, msg.value);
11779
+ break;
11780
+ default:
11781
+ throw new Error(`Unknown message type: ${msg}`);
11782
+ }
11783
+ }, (d) => {
11784
+ const type = d.u8();
11785
+ switch (type) {
11786
+ case MessageType.PeerInfo:
11787
+ return { type: MessageType.PeerInfo, value: PeerInfo.Codec.decode(d) };
11788
+ case MessageType.Initialize:
11789
+ return { type: MessageType.Initialize, value: Initialize.Codec.decode(d) };
11790
+ case MessageType.StateRoot:
11791
+ return { type: MessageType.StateRoot, value: stateRootCodec.decode(d) };
11792
+ case MessageType.ImportBlock:
11793
+ return { type: MessageType.ImportBlock, value: Block.Codec.View.decode(d) };
11794
+ case MessageType.GetState:
11795
+ return { type: MessageType.GetState, value: getStateCodec.decode(d) };
11796
+ case MessageType.State:
11797
+ return { type: MessageType.State, value: stateCodec.decode(d) };
11798
+ case MessageType.Error:
11799
+ return { type: MessageType.Error, value: ErrorMessage.Codec.decode(d) };
11800
+ default:
11801
+ throw new Error(`Unknown message type: ${type}`);
11802
+ }
11803
+ }, (s) => {
11804
+ const type = s.decoder.u8();
11805
+ switch (type) {
11806
+ case MessageType.PeerInfo:
11807
+ PeerInfo.Codec.View.skip(s);
11808
+ break;
11809
+ case MessageType.Initialize:
11810
+ Initialize.Codec.View.skip(s);
11811
+ break;
11812
+ case MessageType.StateRoot:
11813
+ stateRootCodec.View.skip(s);
11814
+ break;
11815
+ case MessageType.ImportBlock:
11816
+ Block.Codec.View.skip(s);
11817
+ break;
11818
+ case MessageType.GetState:
11819
+ getStateCodec.View.skip(s);
11820
+ break;
11821
+ case MessageType.State:
11822
+ stateCodec.View.skip(s);
11823
+ break;
11824
+ case MessageType.Error:
11825
+ ErrorMessage.Codec.View.skip(s);
11826
+ break;
11827
+ default:
11828
+ throw new Error(`Unknown message type: ${type}`);
11829
+ }
11830
+ });
11831
+
11832
+ const logger$4 = Logger.new(import.meta.filename, "ext-ipc-fuzz-v1");
11833
+ class FuzzTarget {
11834
+ msgHandler;
11835
+ sender;
11836
+ spec;
11837
+ sessionFeatures = 0;
11838
+ constructor(msgHandler, sender, spec) {
11839
+ this.msgHandler = msgHandler;
11840
+ this.sender = sender;
11841
+ this.spec = spec;
11842
+ }
11843
+ async onSocketMessage(msg) {
11844
+ // attempt to decode the messsage
11845
+ try {
11846
+ const message = Decoder.decodeObject(messageCodec, msg, this.spec);
11847
+ logger$4.log `[${message.type}] incoming message`;
11848
+ await this.processAndRespond(message);
11849
+ }
11850
+ catch (e) {
11851
+ logger$4.error `Error while processing fuzz v1 message: ${e}`;
11852
+ logger$4.error `${e}`;
11853
+ if (e instanceof Error) {
11854
+ logger$4.error `${e.stack ?? ""}`;
11855
+ }
11856
+ this.sender.close();
11857
+ }
11858
+ }
11859
+ async processAndRespond(message) {
11860
+ let response = null;
11861
+ switch (message.type) {
11862
+ case MessageType.PeerInfo: {
11863
+ // only support V1
11864
+ if (message.value.fuzzVersion !== 1) {
11865
+ logger$4.warn `Unsupported fuzzer protocol version: ${message.value.fuzzVersion}. Closing`;
11866
+ this.sender.close();
11867
+ return;
11868
+ }
11869
+ // Handle handshake
11870
+ const ourPeerInfo = await this.msgHandler.getPeerInfo(message.value);
11871
+ // Calculate session features (intersection of both peer features)
11872
+ this.sessionFeatures = message.value.features & ourPeerInfo.features;
11873
+ logger$4.info `Handshake completed. Shared features: 0b${this.sessionFeatures.toString(2)}`;
11874
+ logger$4.log `Feature ancestry: ${(this.sessionFeatures & Features.Ancestry) !== 0}`;
11875
+ logger$4.log `Feature fork: ${(this.sessionFeatures & Features.Fork) !== 0}`;
11876
+ response = {
11877
+ type: MessageType.PeerInfo,
11878
+ value: ourPeerInfo,
11879
+ };
11880
+ break;
11881
+ }
11882
+ case MessageType.Initialize: {
11883
+ const stateRoot = await this.msgHandler.initialize(message.value);
11884
+ response = {
11885
+ type: MessageType.StateRoot,
11886
+ value: stateRoot,
11887
+ };
11888
+ break;
11889
+ }
11890
+ case MessageType.ImportBlock: {
11891
+ const result = await this.msgHandler.importBlock(message.value);
11892
+ if (result.isOk) {
11893
+ response = {
11894
+ type: MessageType.StateRoot,
11895
+ value: result.ok,
11896
+ };
11897
+ }
11898
+ else {
11899
+ response = {
11900
+ type: MessageType.Error,
11901
+ value: result.error,
11902
+ };
11903
+ }
11904
+ break;
11905
+ }
11906
+ case MessageType.GetState: {
11907
+ const state = await this.msgHandler.getSerializedState(message.value);
11908
+ response = {
11909
+ type: MessageType.State,
11910
+ value: state,
11911
+ };
11912
+ break;
11913
+ }
11914
+ case MessageType.StateRoot: {
11915
+ logger$4.log `--> Received unexpected 'StateRoot' message from the fuzzer. Closing.`;
11916
+ this.sender.close();
11917
+ return;
11918
+ }
11919
+ case MessageType.State: {
11920
+ logger$4.log `--> Received unexpected 'State' message from the fuzzer. Closing.`;
11921
+ this.sender.close();
11922
+ return;
11923
+ }
11924
+ case MessageType.Error: {
11925
+ logger$4.log `--> Received unexpected 'Error' message from the fuzzer. Closing.`;
11926
+ this.sender.close();
11927
+ return;
11928
+ }
11929
+ default: {
11930
+ logger$4.log `--> Received unexpected message type ${JSON.stringify(message)} from the fuzzer. Closing.`;
11931
+ this.sender.close();
11932
+ try {
11933
+ assertNever(message);
11934
+ }
11935
+ catch {
11936
+ return;
11937
+ }
11938
+ }
11939
+ }
11940
+ if (response !== null) {
11941
+ logger$4.trace `<-- responding with: ${response.type}`;
11942
+ const encoded = Encoder.encodeObject(messageCodec, response, this.spec);
11943
+ this.sender.send(encoded);
11944
+ }
11945
+ else {
11946
+ logger$4.warn `<-- no response generated for: ${message.type}`;
11947
+ }
11948
+ }
11949
+ onClose({ error }) {
11950
+ logger$4.log `Closing the v1 handler. Reason: ${error !== undefined ? error.message : "close"}.`;
11951
+ }
11952
+ /** Check if a specific feature is enabled in the session */
11953
+ hasFeature(feature) {
11954
+ return (this.sessionFeatures & feature) !== 0;
11955
+ }
11956
+ }
11957
+
11958
+ var index$b = /*#__PURE__*/Object.freeze({
11959
+ __proto__: null,
11960
+ AncestryItem: AncestryItem,
11961
+ ErrorMessage: ErrorMessage,
11962
+ get Features () { return Features; },
11963
+ FuzzTarget: FuzzTarget,
11964
+ Initialize: Initialize,
11965
+ KeyValue: KeyValue,
11966
+ get MessageType () { return MessageType; },
11967
+ PeerInfo: PeerInfo,
11968
+ Version: Version,
11969
+ ancestryCodec: ancestryCodec,
11970
+ getStateCodec: getStateCodec,
11971
+ messageCodec: messageCodec,
11972
+ stateCodec: stateCodec,
11973
+ stateRootCodec: stateRootCodec
11974
+ });
11975
+
11976
+ var index$a = /*#__PURE__*/Object.freeze({
11977
+ __proto__: null,
11978
+ v1: index$b
11979
+ });
11980
+
12078
11981
  /** Size of the transfer memo. */
12079
11982
  const TRANSFER_MEMO_BYTES = W_T;
12080
11983
  /**
@@ -12189,6 +12092,8 @@ var NewServiceError;
12189
12092
  NewServiceError[NewServiceError["InsufficientFunds"] = 0] = "InsufficientFunds";
12190
12093
  /** Service is not privileged to set gratis storage. */
12191
12094
  NewServiceError[NewServiceError["UnprivilegedService"] = 1] = "UnprivilegedService";
12095
+ /** Registrar attempting to create a service with already existing id. */
12096
+ NewServiceError[NewServiceError["RegistrarServiceIdAlreadyTaken"] = 2] = "RegistrarServiceIdAlreadyTaken";
12192
12097
  })(NewServiceError || (NewServiceError = {}));
12193
12098
  var UpdatePrivilegesError;
12194
12099
  (function (UpdatePrivilegesError) {
@@ -12379,11 +12284,17 @@ class AccumulationStateUpdate {
12379
12284
  if (from.privilegedServices !== null) {
12380
12285
  update.privilegedServices = PrivilegedServices.create({
12381
12286
  ...from.privilegedServices,
12382
- authManager: asKnownSize([...from.privilegedServices.authManager]),
12287
+ assigners: asKnownSize([...from.privilegedServices.assigners]),
12383
12288
  });
12384
12289
  }
12385
12290
  return update;
12386
12291
  }
12292
+ /** Retrieve and clear pending transfers. */
12293
+ takeTransfers() {
12294
+ const transfers = this.transfers;
12295
+ this.transfers = [];
12296
+ return transfers;
12297
+ }
12387
12298
  }
12388
12299
  class PartiallyUpdatedState {
12389
12300
  state;
@@ -12580,7 +12491,7 @@ const HostCallResult = {
12580
12491
  OOB: tryAsU64(0xfffffffffffffffdn), // 2**64 - 3
12581
12492
  /** Index unknown. */
12582
12493
  WHO: tryAsU64(0xfffffffffffffffcn), // 2**64 - 4
12583
- /** Storage full. */
12494
+ /** Storage full or resource already allocated. */
12584
12495
  FULL: tryAsU64(0xfffffffffffffffbn), // 2**64 - 5
12585
12496
  /** Core index unknown. */
12586
12497
  CORE: tryAsU64(0xfffffffffffffffan), // 2**64 - 6
@@ -12588,7 +12499,7 @@ const HostCallResult = {
12588
12499
  CASH: tryAsU64(0xfffffffffffffff9n), // 2**64 - 7
12589
12500
  /** Gas limit too low. */
12590
12501
  LOW: tryAsU64(0xfffffffffffffff8n), // 2**64 - 8
12591
- /** The item is already solicited or cannot be forgotten. */
12502
+ /** The item is already solicited, cannot be forgotten or the operation is invalid due to privilege level. */
12592
12503
  HUH: tryAsU64(0xfffffffffffffff7n), // 2**64 - 9
12593
12504
  /** The return value indicating general success. */
12594
12505
  OK: tryAsU64(0n),
@@ -12789,7 +12700,7 @@ class Registers {
12789
12700
  bytes;
12790
12701
  asSigned;
12791
12702
  asUnsigned;
12792
- constructor(bytes = new Uint8Array(NO_OF_REGISTERS$1 << REGISTER_SIZE_SHIFT)) {
12703
+ constructor(bytes = safeAllocUint8Array(NO_OF_REGISTERS$1 << REGISTER_SIZE_SHIFT)) {
12793
12704
  this.bytes = bytes;
12794
12705
  check `${bytes.length === NO_OF_REGISTERS$1 << REGISTER_SIZE_SHIFT} Invalid size of registers array.`;
12795
12706
  this.asSigned = new BigInt64Array(bytes.buffer, bytes.byteOffset);
@@ -12861,10 +12772,16 @@ function signExtend32To64(value) {
12861
12772
 
12862
12773
  /** Attempt to convert a number into `HostCallIndex`. */
12863
12774
  const tryAsHostCallIndex = (v) => asOpaqueType(tryAsU32(v));
12775
+ /**
12776
+ * Host-call exit reason.
12777
+ *
12778
+ * https://graypaper.fluffylabs.dev/#/ab2cdbd/24a30124a501?v=0.7.2
12779
+ */
12864
12780
  var PvmExecution;
12865
12781
  (function (PvmExecution) {
12866
12782
  PvmExecution[PvmExecution["Halt"] = 0] = "Halt";
12867
12783
  PvmExecution[PvmExecution["Panic"] = 1] = "Panic";
12784
+ PvmExecution[PvmExecution["OOG"] = 2] = "OOG";
12868
12785
  })(PvmExecution || (PvmExecution = {}));
12869
12786
  /** A utility function to easily trace a bunch of registers. */
12870
12787
  function traceRegisters(...regs) {
@@ -12936,7 +12853,7 @@ class Mask {
12936
12853
  return Math.min(this.lookupTableForward[index] ?? 0, MAX_INSTRUCTION_DISTANCE);
12937
12854
  }
12938
12855
  buildLookupTableForward(mask) {
12939
- const table = new Uint8Array(mask.bitLength);
12856
+ const table = safeAllocUint8Array(mask.bitLength);
12940
12857
  let lastInstructionOffset = 0;
12941
12858
  for (let i = mask.bitLength - 1; i >= 0; i--) {
12942
12859
  if (mask.isSet(i)) {
@@ -14122,6 +14039,17 @@ class PageRange {
14122
14039
  }
14123
14040
  return new PageRange(start, length);
14124
14041
  }
14042
+ /** Returns true if the page range is wrapped (`start` >= `end`) and is not empty */
14043
+ isWrapped() {
14044
+ return this.start >= this.end && !this.isEmpty();
14045
+ }
14046
+ /** Checks if given page number is within the range */
14047
+ isInRange(page) {
14048
+ if (this.isWrapped()) {
14049
+ return page >= this.start || page < this.end;
14050
+ }
14051
+ return page >= this.start && page < this.end;
14052
+ }
14125
14053
  /** Checks if a range is empty (`length === 0`) */
14126
14054
  isEmpty() {
14127
14055
  return this.length === 0;
@@ -14462,10 +14390,11 @@ class MemoryBuilder {
14462
14390
  startHeapIndex (${startHeapIndex}) has to be less than or equal to endHeapIndex (${endHeapIndex})
14463
14391
  `;
14464
14392
  this.ensureNotFinalized();
14465
- const range = MemoryRange.fromStartAndLength(startHeapIndex, endHeapIndex - startHeapIndex);
14466
- const pages = PageRange.fromMemoryRange(range);
14467
- for (const pageNumber of pages) {
14468
- if (this.initialMemory.has(pageNumber)) {
14393
+ const heapRange = MemoryRange.fromStartAndLength(startHeapIndex, endHeapIndex - startHeapIndex);
14394
+ const heapPagesRange = PageRange.fromMemoryRange(heapRange);
14395
+ const initializedPageNumbers = Array.from(this.initialMemory.keys());
14396
+ for (const pageNumber of initializedPageNumbers) {
14397
+ if (heapPagesRange.isInRange(pageNumber)) {
14469
14398
  throw new IncorrectSbrkIndex();
14470
14399
  }
14471
14400
  }
@@ -14605,11 +14534,6 @@ class BitOps {
14605
14534
  }
14606
14535
  }
14607
14536
 
14608
- const MAX_VALUE = 4294967295;
14609
- const MIN_VALUE = -2147483648;
14610
- const MAX_SHIFT_U32 = 32;
14611
- const MAX_SHIFT_U64 = 64n;
14612
-
14613
14537
  /**
14614
14538
  * Overflowing addition for two-complement representation of 32-bit signed numbers.
14615
14539
  */
@@ -16459,7 +16383,7 @@ class HostCalls {
16459
16383
  const regs = pvmInstance.getRegisters();
16460
16384
  const maybeAddress = regs.getLowerU32(7);
16461
16385
  const maybeLength = regs.getLowerU32(8);
16462
- const result = new Uint8Array(maybeLength);
16386
+ const result = safeAllocUint8Array(maybeLength);
16463
16387
  const startAddress = tryAsMemoryIndex(maybeAddress);
16464
16388
  const loadResult = memory.loadInto(result, startAddress);
16465
16389
  if (loadResult.isError) {
@@ -16487,8 +16411,9 @@ class HostCalls {
16487
16411
  const index = tryAsHostCallIndex(hostCallIndex);
16488
16412
  const hostCall = this.hostCalls.get(index);
16489
16413
  const gasBefore = gas.get();
16490
- const gasCost = typeof hostCall.gasCost === "number" ? hostCall.gasCost : hostCall.gasCost(regs);
16491
- const underflow = gas.sub(gasCost);
16414
+ // NOTE: `basicGasCost(regs)` function is for compatibility reasons: pre GP 0.7.2
16415
+ const basicGasCost = typeof hostCall.basicGasCost === "number" ? hostCall.basicGasCost : hostCall.basicGasCost(regs);
16416
+ const underflow = gas.sub(basicGasCost);
16492
16417
  const pcLog = `[PC: ${pvmInstance.getPC()}]`;
16493
16418
  if (underflow) {
16494
16419
  this.hostCalls.traceHostCall(`${pcLog} OOG`, index, hostCall, regs, gas.get());
@@ -16505,6 +16430,10 @@ class HostCalls {
16505
16430
  status = Status.PANIC;
16506
16431
  return this.getReturnValue(status, pvmInstance);
16507
16432
  }
16433
+ if (result === PvmExecution.OOG) {
16434
+ status = Status.OOG;
16435
+ return this.getReturnValue(status, pvmInstance);
16436
+ }
16508
16437
  if (result === undefined) {
16509
16438
  pvmInstance.runProgram();
16510
16439
  status = pvmInstance.getStatus();
@@ -16803,14 +16732,14 @@ class DebuggerAdapter {
16803
16732
  const page = this.pvm.getMemoryPage(pageNumber);
16804
16733
  if (page === null) {
16805
16734
  // page wasn't allocated so we return an empty page
16806
- return new Uint8Array(PAGE_SIZE$1);
16735
+ return safeAllocUint8Array(PAGE_SIZE$1);
16807
16736
  }
16808
16737
  if (page.length === PAGE_SIZE$1) {
16809
16738
  // page was allocated and has a proper size so we can simply return it
16810
16739
  return page;
16811
16740
  }
16812
16741
  // page was allocated but it is shorter than PAGE_SIZE so we have to extend it
16813
- const fullPage = new Uint8Array(PAGE_SIZE$1);
16742
+ const fullPage = safeAllocUint8Array(PAGE_SIZE$1);
16814
16743
  fullPage.set(page);
16815
16744
  return fullPage;
16816
16745
  }
@@ -16905,8 +16834,8 @@ var index$3 = /*#__PURE__*/Object.freeze({
16905
16834
  asOpaqueType: asOpaqueType,
16906
16835
  assertEmpty: assertEmpty,
16907
16836
  assertNever: assertNever,
16908
- block: index$j,
16909
- bytes: index$q,
16837
+ block: index$l,
16838
+ bytes: index$s,
16910
16839
  check: check,
16911
16840
  clampU64ToU32: clampU64ToU32,
16912
16841
  createResults: createResults,
@@ -16914,13 +16843,13 @@ var index$3 = /*#__PURE__*/Object.freeze({
16914
16843
  extractCodeAndMetadata: extractCodeAndMetadata,
16915
16844
  getServiceId: getServiceId,
16916
16845
  getServiceIdOrCurrent: getServiceIdOrCurrent,
16917
- hash: index$n,
16846
+ hash: index$o,
16918
16847
  inspect: inspect,
16919
16848
  instructionArgumentTypeMap: instructionArgumentTypeMap,
16920
16849
  interpreter: index$7,
16921
16850
  isBrowser: isBrowser,
16922
16851
  measure: measure,
16923
- numbers: index$p,
16852
+ numbers: index$r,
16924
16853
  resultToString: resultToString,
16925
16854
  seeThrough: seeThrough,
16926
16855
  slotsToPreimageStatus: slotsToPreimageStatus,
@@ -16936,10 +16865,10 @@ const ENTROPY_BYTES = 32;
16936
16865
  *
16937
16866
  * https://graypaper.fluffylabs.dev/#/579bd12/3b9a013b9a01
16938
16867
  */
16939
- function fisherYatesShuffle(arr, entropy) {
16868
+ function fisherYatesShuffle(blake2b, arr, entropy) {
16940
16869
  check `${entropy.length === ENTROPY_BYTES} Expected entropy of length ${ENTROPY_BYTES}, got ${entropy.length}`;
16941
16870
  const n = arr.length;
16942
- const randomNumbers = hashToNumberSequence(entropy, arr.length);
16871
+ const randomNumbers = hashToNumberSequence(blake2b, entropy, arr.length);
16943
16872
  const result = new Array(n);
16944
16873
  let itemsLeft = n;
16945
16874
  for (let i = 0; i < n; i++) {
@@ -16952,13 +16881,13 @@ function fisherYatesShuffle(arr, entropy) {
16952
16881
  }
16953
16882
  return result;
16954
16883
  }
16955
- function hashToNumberSequence(entropy, length) {
16884
+ function hashToNumberSequence(blake2b, entropy, length) {
16956
16885
  const result = new Array(length);
16957
- const randomBytes = new Uint8Array(ENTROPY_BYTES + 4);
16886
+ const randomBytes = safeAllocUint8Array(ENTROPY_BYTES + 4);
16958
16887
  randomBytes.set(entropy.raw);
16959
16888
  for (let i = 0; i < length; i++) {
16960
16889
  randomBytes.set(u32AsLeBytes(tryAsU32(Math.floor(i / 8))), ENTROPY_BYTES);
16961
- const newHash = hashBytes(randomBytes);
16890
+ const newHash = blake2b.hashBytes(randomBytes);
16962
16891
  const numberStartIndex = (4 * i) % 32;
16963
16892
  const numberEndIndex = numberStartIndex + 4;
16964
16893
  const number = leBytesAsU32(newHash.raw.subarray(numberStartIndex, numberEndIndex)) >>> 0;
@@ -16974,6 +16903,7 @@ var index$2 = /*#__PURE__*/Object.freeze({
16974
16903
 
16975
16904
  class JsonServiceInfo {
16976
16905
  static fromJson = json.object({
16906
+ ...(Compatibility.isGreaterOrEqual(GpVersion.V0_7_1) ? { version: "number" } : {}),
16977
16907
  code_hash: fromJson.bytes32(),
16978
16908
  balance: json.fromNumber((x) => tryAsU64(x)),
16979
16909
  min_item_gas: json.fromNumber((x) => tryAsServiceGas(x)),
@@ -16998,6 +16928,7 @@ class JsonServiceInfo {
16998
16928
  parentService: parent_service,
16999
16929
  });
17000
16930
  });
16931
+ version;
17001
16932
  code_hash;
17002
16933
  balance;
17003
16934
  min_item_gas;
@@ -17032,23 +16963,35 @@ const lookupMetaFromJson = json.object({
17032
16963
  },
17033
16964
  value: json.array("number"),
17034
16965
  }, ({ key, value }) => new LookupHistoryItem(key.hash, key.length, value));
16966
+ const preimageStatusFromJson = json.object({
16967
+ hash: fromJson.bytes32(),
16968
+ status: json.array("number"),
16969
+ }, ({ hash, status }) => new LookupHistoryItem(hash, tryAsU32(0), status));
17035
16970
  class JsonService {
17036
16971
  static fromJson = json.object({
17037
16972
  id: "number",
17038
- data: {
17039
- service: JsonServiceInfo.fromJson,
17040
- preimages: json.optional(json.array(JsonPreimageItem.fromJson)),
17041
- storage: json.optional(json.array(JsonStorageItem.fromJson)),
17042
- lookup_meta: json.optional(json.array(lookupMetaFromJson)),
17043
- },
16973
+ data: Compatibility.isLessThan(GpVersion.V0_7_1)
16974
+ ? {
16975
+ service: JsonServiceInfo.fromJson,
16976
+ preimages: json.optional(json.array(JsonPreimageItem.fromJson)),
16977
+ storage: json.optional(json.array(JsonStorageItem.fromJson)),
16978
+ lookup_meta: json.optional(json.array(lookupMetaFromJson)),
16979
+ }
16980
+ : {
16981
+ service: JsonServiceInfo.fromJson,
16982
+ storage: json.optional(json.array(JsonStorageItem.fromJson)),
16983
+ preimages_blob: json.optional(json.array(JsonPreimageItem.fromJson)),
16984
+ preimages_status: json.optional(json.array(preimageStatusFromJson)),
16985
+ },
17044
16986
  }, ({ id, data }) => {
16987
+ const preimages = HashDictionary.fromEntries((data.preimages ?? data.preimages_blob ?? []).map((x) => [x.hash, x]));
17045
16988
  const lookupHistory = HashDictionary.new();
17046
- for (const item of data.lookup_meta ?? []) {
16989
+ for (const item of data.lookup_meta ?? data.preimages_status ?? []) {
17047
16990
  const data = lookupHistory.get(item.hash) ?? [];
17048
- data.push(item);
16991
+ const length = tryAsU32(preimages.get(item.hash)?.blob.length ?? item.length);
16992
+ data.push(new LookupHistoryItem(item.hash, length, item.slots));
17049
16993
  lookupHistory.set(item.hash, data);
17050
16994
  }
17051
- const preimages = HashDictionary.fromEntries((data.preimages ?? []).map((x) => [x.hash, x]));
17052
16995
  const storage = new Map();
17053
16996
  const entries = (data.storage ?? []).map(({ key, value }) => {
17054
16997
  const opaqueKey = asOpaqueType(key);
@@ -17072,8 +17015,7 @@ const availabilityAssignmentFromJson = json.object({
17072
17015
  report: workReportFromJson,
17073
17016
  timeout: "number",
17074
17017
  }, ({ report, timeout }) => {
17075
- const workReportHash = hashBytes(Encoder.encodeObject(WorkReport.Codec, report)).asOpaque();
17076
- return AvailabilityAssignment.create({ workReport: new WithHash(workReportHash, report), timeout });
17018
+ return AvailabilityAssignment.create({ workReport: report, timeout });
17077
17019
  });
17078
17020
 
17079
17021
  const disputesRecordsFromJson = json.object({
@@ -17221,8 +17163,12 @@ class JsonServiceStatistics {
17221
17163
  extrinsic_count: "number",
17222
17164
  accumulate_count: "number",
17223
17165
  accumulate_gas_used: json.fromNumber(tryAsServiceGas),
17224
- on_transfers_count: "number",
17225
- on_transfers_gas_used: json.fromNumber(tryAsServiceGas),
17166
+ ...(Compatibility.isLessThan(GpVersion.V0_7_1)
17167
+ ? {
17168
+ on_transfers_count: "number",
17169
+ on_transfers_gas_used: json.fromNumber(tryAsServiceGas),
17170
+ }
17171
+ : {}),
17226
17172
  }, ({ provided_count, provided_size, refinement_count, refinement_gas_used, imports, exports, extrinsic_size, extrinsic_count, accumulate_count, accumulate_gas_used, on_transfers_count, on_transfers_gas_used, }) => {
17227
17173
  return ServiceStatistics.create({
17228
17174
  providedCount: provided_count,
@@ -17235,8 +17181,8 @@ class JsonServiceStatistics {
17235
17181
  extrinsicCount: extrinsic_count,
17236
17182
  accumulateCount: accumulate_count,
17237
17183
  accumulateGasUsed: accumulate_gas_used,
17238
- onTransfersCount: on_transfers_count,
17239
- onTransfersGasUsed: on_transfers_gas_used,
17184
+ onTransfersCount: on_transfers_count ?? tryAsU32(0),
17185
+ onTransfersGasUsed: on_transfers_gas_used ?? tryAsServiceGas(0),
17240
17186
  });
17241
17187
  });
17242
17188
  provided_count;
@@ -17307,6 +17253,7 @@ const fullStateDumpFromJson = (spec) => json.object({
17307
17253
  chi_m: "number",
17308
17254
  chi_a: json.array("number"),
17309
17255
  chi_v: "number",
17256
+ chi_r: json.optional("number"),
17310
17257
  chi_g: json.nullable(json.array({
17311
17258
  service: "number",
17312
17259
  gasLimit: json.fromNumber((v) => tryAsServiceGas(v)),
@@ -17318,6 +17265,9 @@ const fullStateDumpFromJson = (spec) => json.object({
17318
17265
  theta: json.nullable(json.array(accumulationOutput)),
17319
17266
  accounts: json.array(JsonService.fromJson),
17320
17267
  }, ({ alpha, varphi, beta, gamma, psi, eta, iota, kappa, lambda, rho, tau, chi, pi, omega, xi, theta, accounts, }) => {
17268
+ if (Compatibility.isGreaterOrEqual(GpVersion.V0_7_1) && chi.chi_r === undefined) {
17269
+ throw new Error("Registrar is required in Privileges GP ^0.7.1");
17270
+ }
17321
17271
  return InMemoryState.create({
17322
17272
  authPools: tryAsPerCore(alpha.map((perCore) => {
17323
17273
  if (perCore.length > MAX_AUTH_POOL_SIZE) {
@@ -17345,8 +17295,9 @@ const fullStateDumpFromJson = (spec) => json.object({
17345
17295
  timeslot: tau,
17346
17296
  privilegedServices: PrivilegedServices.create({
17347
17297
  manager: chi.chi_m,
17348
- authManager: chi.chi_a,
17349
- validatorsManager: chi.chi_v,
17298
+ assigners: chi.chi_a,
17299
+ delegator: chi.chi_v,
17300
+ registrar: chi.chi_r ?? tryAsServiceId(2 ** 32 - 1),
17350
17301
  autoAccumulateServices: chi.chi_g ?? [],
17351
17302
  }),
17352
17303
  statistics: JsonStatisticsData.toStatisticsData(spec, pi),
@@ -17379,11 +17330,11 @@ var index$1 = /*#__PURE__*/Object.freeze({
17379
17330
  class TransitionHasher {
17380
17331
  context;
17381
17332
  keccakHasher;
17382
- allocator;
17383
- constructor(context, keccakHasher, allocator) {
17333
+ blake2b;
17334
+ constructor(context, keccakHasher, blake2b) {
17384
17335
  this.context = context;
17385
17336
  this.keccakHasher = keccakHasher;
17386
- this.allocator = allocator;
17337
+ this.blake2b = blake2b;
17387
17338
  }
17388
17339
  /** Concatenates two hashes and hash this concatenation */
17389
17340
  hashConcat(a, b) {
@@ -17394,7 +17345,7 @@ class TransitionHasher {
17394
17345
  }
17395
17346
  /** Creates hash from the block header view */
17396
17347
  header(header) {
17397
- return new WithHash(hashBytes(header.encoded(), this.allocator).asOpaque(), header);
17348
+ return new WithHash(this.blake2b.hashBytes(header.encoded()).asOpaque(), header);
17398
17349
  }
17399
17350
  /**
17400
17351
  * Merkle commitment of the extrinsic data
@@ -17407,7 +17358,7 @@ class TransitionHasher {
17407
17358
  .view()
17408
17359
  .map((g) => g.view())
17409
17360
  .map((guarantee) => {
17410
- const reportHash = hashBytes(guarantee.report.encoded(), this.allocator).asOpaque();
17361
+ const reportHash = this.blake2b.hashBytes(guarantee.report.encoded()).asOpaque();
17411
17362
  return BytesBlob.blobFromParts([
17412
17363
  reportHash.raw,
17413
17364
  guarantee.slot.encoded().raw,
@@ -17415,13 +17366,13 @@ class TransitionHasher {
17415
17366
  ]);
17416
17367
  });
17417
17368
  const guaranteeBlob = Encoder.encodeObject(codec$1.sequenceVarLen(dumpCodec), guarantees, this.context);
17418
- const et = hashBytes(extrinsicView.tickets.encoded(), this.allocator).asOpaque();
17419
- const ep = hashBytes(extrinsicView.preimages.encoded(), this.allocator).asOpaque();
17420
- const eg = hashBytes(guaranteeBlob, this.allocator).asOpaque();
17421
- const ea = hashBytes(extrinsicView.assurances.encoded(), this.allocator).asOpaque();
17422
- const ed = hashBytes(extrinsicView.disputes.encoded(), this.allocator).asOpaque();
17369
+ const et = this.blake2b.hashBytes(extrinsicView.tickets.encoded()).asOpaque();
17370
+ const ep = this.blake2b.hashBytes(extrinsicView.preimages.encoded()).asOpaque();
17371
+ const eg = this.blake2b.hashBytes(guaranteeBlob).asOpaque();
17372
+ const ea = this.blake2b.hashBytes(extrinsicView.assurances.encoded()).asOpaque();
17373
+ const ed = this.blake2b.hashBytes(extrinsicView.disputes.encoded()).asOpaque();
17423
17374
  const encoded = BytesBlob.blobFromParts([et.raw, ep.raw, eg.raw, ea.raw, ed.raw]);
17424
- return new WithHashAndBytes(hashBytes(encoded, this.allocator).asOpaque(), extrinsicView, encoded);
17375
+ return new WithHashAndBytes(this.blake2b.hashBytes(encoded).asOpaque(), extrinsicView, encoded);
17425
17376
  }
17426
17377
  /** Creates hash for given WorkPackage */
17427
17378
  workPackage(workPackage) {
@@ -17430,7 +17381,7 @@ class TransitionHasher {
17430
17381
  encode(codec, data) {
17431
17382
  // TODO [ToDr] Use already allocated encoding destination and hash bytes from some arena.
17432
17383
  const encoded = Encoder.encodeObject(codec, data, this.context);
17433
- return new WithHashAndBytes(hashBytes(encoded, this.allocator).asOpaque(), data, encoded);
17384
+ return new WithHashAndBytes(this.blake2b.hashBytes(encoded).asOpaque(), data, encoded);
17434
17385
  }
17435
17386
  }
17436
17387
 
@@ -17443,8 +17394,10 @@ var PreimagesErrorCode;
17443
17394
  // TODO [SeKo] consider whether this module is the right place to remove expired preimages
17444
17395
  class Preimages {
17445
17396
  state;
17446
- constructor(state) {
17397
+ blake2b;
17398
+ constructor(state, blake2b) {
17447
17399
  this.state = state;
17400
+ this.blake2b = blake2b;
17448
17401
  }
17449
17402
  integrate(input) {
17450
17403
  // make sure lookup extrinsics are sorted and unique
@@ -17467,7 +17420,7 @@ class Preimages {
17467
17420
  // select preimages for integration
17468
17421
  for (const preimage of preimages) {
17469
17422
  const { requester, blob } = preimage;
17470
- const hash = hashBytes(blob).asOpaque();
17423
+ const hash = this.blake2b.hashBytes(blob).asOpaque();
17471
17424
  const service = this.state.getService(requester);
17472
17425
  if (service === null) {
17473
17426
  return Result$1.error(PreimagesErrorCode.AccountNotFound);
@@ -17492,146 +17445,11 @@ class Preimages {
17492
17445
  }
17493
17446
  }
17494
17447
 
17495
- class Missing {
17496
- index = tryAsHostCallIndex(2 ** 32 - 1);
17497
- gasCost = tryAsSmallGas(10);
17498
- currentServiceId = CURRENT_SERVICE_ID;
17499
- tracedRegisters = traceRegisters(7);
17500
- execute(_gas, regs, _memory) {
17501
- regs.set(7, HostCallResult.WHAT);
17502
- return Promise.resolve(undefined);
17503
- }
17504
- }
17505
-
17506
- var ServiceExecutorError;
17507
- (function (ServiceExecutorError) {
17508
- ServiceExecutorError[ServiceExecutorError["NoLookup"] = 0] = "NoLookup";
17509
- ServiceExecutorError[ServiceExecutorError["NoState"] = 1] = "NoState";
17510
- ServiceExecutorError[ServiceExecutorError["NoServiceCode"] = 2] = "NoServiceCode";
17511
- ServiceExecutorError[ServiceExecutorError["ServiceCodeMismatch"] = 3] = "ServiceCodeMismatch";
17512
- })(ServiceExecutorError || (ServiceExecutorError = {}));
17513
- class WorkPackageExecutor {
17514
- blocks;
17515
- state;
17516
- hasher;
17517
- constructor(blocks, state, hasher) {
17518
- this.blocks = blocks;
17519
- this.state = state;
17520
- this.hasher = hasher;
17521
- }
17522
- // TODO [ToDr] this while thing should be triple-checked with the GP.
17523
- // I'm currently implementing some dirty version for the demo.
17524
- async executeWorkPackage(pack) {
17525
- const headerHash = pack.context.lookupAnchor;
17526
- // execute authorisation first or is it already executed and we just need to check it?
17527
- const authExec = this.getServiceExecutor(
17528
- // TODO [ToDr] should this be anchor or lookupAnchor?
17529
- headerHash, pack.authCodeHost, pack.authCodeHash);
17530
- if (authExec.isError) {
17531
- // TODO [ToDr] most likely shouldn't be throw.
17532
- throw new Error(`Could not get authorization executor: ${authExec.error}`);
17533
- }
17534
- const pvm = authExec.ok;
17535
- const authGas = tryAsGas(15000n);
17536
- const result = await pvm.run(pack.parametrization, authGas);
17537
- if (!result.isEqualTo(pack.authorization)) {
17538
- throw new Error("Authorization is invalid.");
17539
- }
17540
- const results = [];
17541
- for (const item of pack.items) {
17542
- const exec = this.getServiceExecutor(headerHash, item.service, item.codeHash);
17543
- if (exec.isError) {
17544
- throw new Error(`Could not get item executor: ${exec.error}`);
17545
- }
17546
- const pvm = exec.ok;
17547
- const gasRatio = tryAsServiceGas(3000n);
17548
- const ret = await pvm.run(item.payload, tryAsGas(item.refineGasLimit)); // or accumulateGasLimit?
17549
- results.push(WorkResult.create({
17550
- serviceId: item.service,
17551
- codeHash: item.codeHash,
17552
- payloadHash: hashBytes(item.payload),
17553
- gas: gasRatio,
17554
- result: new WorkExecResult(WorkExecResultKind.ok, ret),
17555
- load: WorkRefineLoad.create({
17556
- gasUsed: tryAsServiceGas(5),
17557
- importedSegments: tryAsU32(0),
17558
- exportedSegments: tryAsU32(0),
17559
- extrinsicSize: tryAsU32(0),
17560
- extrinsicCount: tryAsU32(0),
17561
- }),
17562
- }));
17563
- }
17564
- const workPackage = this.hasher.workPackage(pack);
17565
- const workPackageSpec = WorkPackageSpec.create({
17566
- hash: workPackage.hash,
17567
- length: tryAsU32(workPackage.encoded.length),
17568
- erasureRoot: Bytes.zero(HASH_SIZE),
17569
- exportsRoot: Bytes.zero(HASH_SIZE).asOpaque(),
17570
- exportsCount: tryAsU16(0),
17571
- });
17572
- const coreIndex = tryAsCoreIndex(0);
17573
- const authorizerHash = Bytes.fill(HASH_SIZE, 5).asOpaque();
17574
- const workResults = FixedSizeArray.new(results, tryAsWorkItemsCount(results.length));
17575
- return Promise.resolve(WorkReport.create({
17576
- workPackageSpec,
17577
- context: pack.context,
17578
- coreIndex,
17579
- authorizerHash,
17580
- authorizationOutput: pack.authorization,
17581
- segmentRootLookup: [],
17582
- results: workResults,
17583
- authorizationGasUsed: tryAsServiceGas(0),
17584
- }));
17585
- }
17586
- getServiceExecutor(lookupAnchor, serviceId, expectedCodeHash) {
17587
- const header = this.blocks.getHeader(lookupAnchor);
17588
- if (header === null) {
17589
- return Result$1.error(ServiceExecutorError.NoLookup);
17590
- }
17591
- const state = this.state.getState(lookupAnchor);
17592
- if (state === null) {
17593
- return Result$1.error(ServiceExecutorError.NoState);
17594
- }
17595
- const service = state.getService(serviceId);
17596
- const serviceCodeHash = service?.getInfo().codeHash ?? null;
17597
- if (serviceCodeHash === null) {
17598
- return Result$1.error(ServiceExecutorError.NoServiceCode);
17599
- }
17600
- if (!serviceCodeHash.isEqualTo(expectedCodeHash)) {
17601
- return Result$1.error(ServiceExecutorError.ServiceCodeMismatch);
17602
- }
17603
- const serviceCode = service?.getPreimage(serviceCodeHash.asOpaque()) ?? null;
17604
- if (serviceCode === null) {
17605
- return Result$1.error(ServiceExecutorError.NoServiceCode);
17606
- }
17607
- return Result$1.ok(new PvmExecutor(serviceCode));
17608
- }
17609
- }
17610
- class PvmExecutor {
17611
- serviceCode;
17612
- pvm;
17613
- hostCalls = new HostCallsManager({ missing: new Missing() });
17614
- pvmInstanceManager = new InterpreterInstanceManager(4);
17615
- constructor(serviceCode) {
17616
- this.serviceCode = serviceCode;
17617
- this.pvm = new HostCalls(this.pvmInstanceManager, this.hostCalls);
17618
- }
17619
- async run(args, gas) {
17620
- const program = Program.fromSpi(this.serviceCode.raw, args.raw, true);
17621
- const result = await this.pvm.runProgram(program.code, 5, gas, program.registers, program.memory);
17622
- if (result.hasMemorySlice()) {
17623
- return BytesBlob.blobFrom(result.memorySlice);
17624
- }
17625
- return BytesBlob.empty();
17626
- }
17627
- }
17628
-
17629
17448
  var index = /*#__PURE__*/Object.freeze({
17630
17449
  __proto__: null,
17631
17450
  Preimages: Preimages,
17632
17451
  get PreimagesErrorCode () { return PreimagesErrorCode; },
17633
- TransitionHasher: TransitionHasher,
17634
- WorkPackageExecutor: WorkPackageExecutor
17452
+ TransitionHasher: TransitionHasher
17635
17453
  });
17636
17454
 
17637
- export { index$j as block, index$h as block_json, index$q as bytes, index$o as codec, index$l as collections, index$k as config, index$f as config_node, index$m as crypto, index$b as database, index$a as erasure_coding, index$n as hash, index$9 as jam_host_calls, index$i as json_parser, index$g as logger, index$8 as mmr, index$p as numbers, index$r as ordering, index$3 as pvm, index$6 as pvm_host_calls, index$7 as pvm_interpreter, index$4 as pvm_program, index$5 as pvm_spi_decoder, index$2 as shuffling, index$e as state, index$1 as state_json, index$c as state_merkleization, index as transition, index$d as trie, index$s as utils };
17455
+ export { index$l as block, index$j as block_json, index$s as bytes, index$q as codec, index$n as collections, index$m as config, index$h as config_node, index$p as crypto, index$d as database, index$c as erasure_coding, index$a as fuzz_proto, index$o as hash, index$9 as jam_host_calls, index$k as json_parser, index$i as logger, index$8 as mmr, index$r as numbers, index$t as ordering, index$3 as pvm, index$6 as pvm_host_calls, index$7 as pvm_interpreter, index$4 as pvm_program, index$5 as pvm_spi_decoder, index$2 as shuffling, index$g as state, index$1 as state_json, index$e as state_merkleization, index as transition, index$f as trie, index$u as utils };