@typeberry/lib 0.1.3 → 0.2.0-41490e3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (4) hide show
  1. package/index.cjs +1332 -1765
  2. package/index.d.ts +2155 -1776
  3. package/index.js +1331 -1764
  4. package/package.json +1 -1
package/index.cjs CHANGED
@@ -9,7 +9,7 @@ var GpVersion;
9
9
  (function (GpVersion) {
10
10
  GpVersion["V0_6_7"] = "0.6.7";
11
11
  GpVersion["V0_7_0"] = "0.7.0";
12
- GpVersion["V0_7_1"] = "0.7.1-preview";
12
+ GpVersion["V0_7_1"] = "0.7.1";
13
13
  GpVersion["V0_7_2"] = "0.7.2-preview";
14
14
  })(GpVersion || (GpVersion = {}));
15
15
  var TestSuite;
@@ -18,11 +18,11 @@ var TestSuite;
18
18
  TestSuite["JAMDUNA"] = "jamduna";
19
19
  })(TestSuite || (TestSuite = {}));
20
20
  const DEFAULT_SUITE = TestSuite.W3F_DAVXY;
21
- const ALL_VERSIONS_IN_ORDER = [GpVersion.V0_6_7, GpVersion.V0_7_0, GpVersion.V0_7_1, GpVersion.V0_7_2];
21
+ const DEFAULT_VERSION = GpVersion.V0_7_1;
22
22
  const env$1 = typeof process === "undefined" ? {} : process.env;
23
- const DEFAULT_VERSION = GpVersion.V0_7_0;
24
23
  let CURRENT_VERSION = parseCurrentVersion(env$1.GP_VERSION) ?? DEFAULT_VERSION;
25
24
  let CURRENT_SUITE = parseCurrentSuite(env$1.TEST_SUITE) ?? DEFAULT_SUITE;
25
+ const ALL_VERSIONS_IN_ORDER = [GpVersion.V0_6_7, GpVersion.V0_7_0, GpVersion.V0_7_1, GpVersion.V0_7_2];
26
26
  function parseCurrentVersion(env) {
27
27
  if (env === undefined) {
28
28
  return undefined;
@@ -38,8 +38,9 @@ function parseCurrentVersion(env) {
38
38
  }
39
39
  }
40
40
  function parseCurrentSuite(env) {
41
- if (env === undefined)
41
+ if (env === undefined) {
42
42
  return undefined;
43
+ }
43
44
  switch (env) {
44
45
  case TestSuite.W3F_DAVXY:
45
46
  case TestSuite.JAMDUNA:
@@ -303,7 +304,7 @@ function resultToString(res) {
303
304
  if (res.isOk) {
304
305
  return `OK: ${typeof res.ok === "symbol" ? res.ok.toString() : res.ok}`;
305
306
  }
306
- return `${res.details}\nError: ${maybeTaggedErrorToString(res.error)}`;
307
+ return `${res.details()}\nError: ${maybeTaggedErrorToString(res.error)}`;
307
308
  }
308
309
  /** An indication of two possible outcomes returned from a function. */
309
310
  const Result$1 = {
@@ -317,7 +318,7 @@ const Result$1 = {
317
318
  };
318
319
  },
319
320
  /** Create new [`Result`] with `Error` status. */
320
- error: (error, details = "") => {
321
+ error: (error, details) => {
321
322
  check `${error !== undefined} 'Error' type cannot be undefined.`;
322
323
  return {
323
324
  isOk: false,
@@ -332,6 +333,19 @@ const Result$1 = {
332
333
  },
333
334
  };
334
335
 
336
+ // about 2GB, the maximum ArrayBuffer length on Chrome confirmed by several sources:
337
+ // - https://issues.chromium.org/issues/40055619
338
+ // - https://stackoverflow.com/a/72124984
339
+ // - https://onnxruntime.ai/docs/tutorials/web/large-models.html#maximum-size-of-arraybuffer
340
+ const MAX_LENGTH$2 = 2145386496;
341
+ function safeAllocUint8Array(length) {
342
+ if (length > MAX_LENGTH$2) {
343
+ // biome-ignore lint/suspicious/noConsole: can't have a dependency on logger here
344
+ console.warn(`Trying to allocate ${length} bytes, which is greater than the maximum of ${MAX_LENGTH$2}.`);
345
+ }
346
+ return new Uint8Array(Math.min(MAX_LENGTH$2, length));
347
+ }
348
+
335
349
  /**
336
350
  * Utilities for tests.
337
351
  */
@@ -417,7 +431,7 @@ function deepEqual(actual, expected, { context = [], errorsCollector, ignore = [
417
431
  }
418
432
  if (actual.isError && expected.isError) {
419
433
  deepEqual(actual.error, expected.error, { context: ctx.concat(["error"]), errorsCollector: errors, ignore });
420
- deepEqual(actual.details, expected.details, {
434
+ deepEqual(actual.details(), expected.details(), {
421
435
  context: ctx.concat(["details"]),
422
436
  errorsCollector: errors,
423
437
  // display details when error does not match
@@ -446,10 +460,12 @@ function deepEqual(actual, expected, { context = [], errorsCollector, ignore = [
446
460
  .sort((a, b) => {
447
461
  const aKey = `${a.key}`;
448
462
  const bKey = `${b.key}`;
449
- if (aKey < bKey)
463
+ if (aKey < bKey) {
450
464
  return -1;
451
- if (bKey < aKey)
465
+ }
466
+ if (bKey < aKey) {
452
467
  return 1;
468
+ }
453
469
  return 0;
454
470
  });
455
471
  };
@@ -572,6 +588,7 @@ var index$u = /*#__PURE__*/Object.freeze({
572
588
  DEFAULT_VERSION: DEFAULT_VERSION,
573
589
  ErrorsCollector: ErrorsCollector,
574
590
  get GpVersion () { return GpVersion; },
591
+ MAX_LENGTH: MAX_LENGTH$2,
575
592
  OK: OK,
576
593
  Result: Result$1,
577
594
  TEST_COMPARE_USING: TEST_COMPARE_USING,
@@ -586,6 +603,7 @@ var index$u = /*#__PURE__*/Object.freeze({
586
603
  isBrowser: isBrowser,
587
604
  measure: measure,
588
605
  resultToString: resultToString,
606
+ safeAllocUint8Array: safeAllocUint8Array,
589
607
  seeThrough: seeThrough,
590
608
  workspacePathFix: workspacePathFix
591
609
  });
@@ -609,7 +627,7 @@ class BitVec {
609
627
  * Create new [`BitVec`] with all values set to `false`.
610
628
  */
611
629
  static empty(bitLength) {
612
- const data = new Uint8Array(Math.ceil(bitLength / 8));
630
+ const data = safeAllocUint8Array(Math.ceil(bitLength / 8));
613
631
  return new BitVec(data, bitLength);
614
632
  }
615
633
  byteLength;
@@ -810,7 +828,7 @@ class BytesBlob {
810
828
  static blobFromParts(v, ...rest) {
811
829
  const vArr = v instanceof Uint8Array ? [v] : v;
812
830
  const totalLength = vArr.reduce((a, v) => a + v.length, 0) + rest.reduce((a, v) => a + v.length, 0);
813
- const buffer = new Uint8Array(totalLength);
831
+ const buffer = safeAllocUint8Array(totalLength);
814
832
  let offset = 0;
815
833
  for (const r of vArr) {
816
834
  buffer.set(r, offset);
@@ -883,7 +901,7 @@ class Bytes extends BytesBlob {
883
901
  }
884
902
  /** Create an empty [`Bytes<X>`] of given length. */
885
903
  static zero(len) {
886
- return new Bytes(new Uint8Array(len), len);
904
+ return new Bytes(safeAllocUint8Array(len), len);
887
905
  }
888
906
  // TODO [ToDr] `fill` should have the argments swapped to align with the rest.
889
907
  /** Create a [`Bytes<X>`] with all bytes filled with given input number. */
@@ -2073,6 +2091,9 @@ class ObjectView {
2073
2091
  toString() {
2074
2092
  return `View<${this.materializedConstructor.name}>(cache: ${this.cache.size})`;
2075
2093
  }
2094
+ [TEST_COMPARE_USING]() {
2095
+ return this.materialize();
2096
+ }
2076
2097
  }
2077
2098
  /**
2078
2099
  * A lazy-evaluated decoder of a sequence.
@@ -2358,7 +2379,15 @@ var codec$1;
2358
2379
  /** Custom encoding / decoding logic. */
2359
2380
  codec.custom = ({ name, sizeHint = { bytes: 0, isExact: false }, }, encode, decode, skip) => Descriptor.new(name, sizeHint, encode, decode, skip);
2360
2381
  /** Choose a descriptor depending on the encoding/decoding context. */
2361
- codec.select = ({ name, sizeHint, }, chooser) => Descriptor.withView(name, sizeHint, (e, x) => chooser(e.getContext()).encode(e, x), (d) => chooser(d.getContext()).decode(d), (s) => chooser(s.decoder.getContext()).skip(s), chooser(null).View);
2382
+ codec.select = ({ name, sizeHint, }, chooser) => {
2383
+ const Self = chooser(null);
2384
+ return Descriptor.withView(name, sizeHint, (e, x) => chooser(e.getContext()).encode(e, x), (d) => chooser(d.getContext()).decode(d), (s) => chooser(s.decoder.getContext()).skip(s), hasUniqueView(Self)
2385
+ ? codec.select({
2386
+ name: Self.View.name,
2387
+ sizeHint: Self.View.sizeHint,
2388
+ }, (ctx) => chooser(ctx).View)
2389
+ : Self.View);
2390
+ };
2362
2391
  /**
2363
2392
  * A descriptor for a more complex POJO.
2364
2393
  *
@@ -3592,7 +3621,7 @@ async function verify(input) {
3592
3621
  return Promise.resolve([]);
3593
3622
  }
3594
3623
  const dataLength = input.reduce((acc, { message, key, signature }) => acc + key.length + signature.length + message.length + 1, 0);
3595
- const data = new Uint8Array(dataLength);
3624
+ const data = safeAllocUint8Array(dataLength);
3596
3625
  let offset = 0;
3597
3626
  for (const { key, message, signature } of input) {
3598
3627
  data.set(key.raw, offset);
@@ -3639,823 +3668,75 @@ var ed25519 = /*#__PURE__*/Object.freeze({
3639
3668
  verifyBatch: verifyBatch
3640
3669
  });
3641
3670
 
3671
+ const SEED_SIZE = 32;
3672
+ const ED25519_SECRET_KEY = Bytes.blobFromString("jam_val_key_ed25519");
3673
+ const BANDERSNATCH_SECRET_KEY = Bytes.blobFromString("jam_val_key_bandersnatch");
3642
3674
  /**
3643
- * Size of the output of the hash functions.
3644
- *
3645
- * https://graypaper.fluffylabs.dev/#/579bd12/073101073c01
3675
+ * JIP-5: Secret key derivation
3646
3676
  *
3647
- */
3648
- const HASH_SIZE = 32;
3649
- /** A hash without last byte (useful for trie representation). */
3650
- const TRUNCATED_HASH_SIZE = 31;
3651
- const ZERO_HASH = Bytes.zero(HASH_SIZE);
3677
+ * https://github.com/polkadot-fellows/JIPs/blob/7048f79edf4f4eb8bfe6fb42e6bbf61900f44c65/JIP-5.md */
3652
3678
  /**
3653
- * Container for some object with a hash that is related to this object.
3654
- *
3655
- * After calculating the hash these two should be passed together to avoid
3656
- * unnecessary re-hashing of the data.
3679
+ * Deriving a 32-byte seed from a 32-bit unsigned integer
3680
+ * https://github.com/polkadot-fellows/JIPs/blob/7048f79edf4f4eb8bfe6fb42e6bbf61900f44c65/JIP-5.md#trivial-seeds
3657
3681
  */
3658
- class WithHash extends WithDebug {
3659
- hash;
3660
- data;
3661
- constructor(hash, data) {
3662
- super();
3663
- this.hash = hash;
3664
- this.data = data;
3665
- }
3682
+ function trivialSeed(s) {
3683
+ const s_le = u32AsLeBytes(s);
3684
+ 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();
3666
3685
  }
3667
3686
  /**
3668
- * Extension of [`WithHash`] additionally containing an encoded version of the object.
3687
+ * Derives a Ed25519 secret key from a seed.
3688
+ * https://github.com/polkadot-fellows/JIPs/blob/7048f79edf4f4eb8bfe6fb42e6bbf61900f44c65/JIP-5.md#derivation-method
3669
3689
  */
3670
- class WithHashAndBytes extends WithHash {
3671
- encoded;
3672
- constructor(hash, data, encoded) {
3673
- super(hash, data);
3674
- this.encoded = encoded;
3675
- }
3676
- }
3677
-
3678
- /** The simplest allocator returning just a fresh copy of bytes each time. */
3679
- class SimpleAllocator {
3680
- emptyHash() {
3681
- return Bytes.zero(HASH_SIZE);
3682
- }
3683
- }
3684
- /** An allocator that works by allocating larger (continuous) pages of memory. */
3685
- class PageAllocator {
3686
- hashesPerPage;
3687
- page = new Uint8Array(0);
3688
- currentHash = 0;
3689
- // TODO [ToDr] Benchmark the performance!
3690
- constructor(hashesPerPage) {
3691
- this.hashesPerPage = hashesPerPage;
3692
- check `${hashesPerPage > 0 && hashesPerPage >>> 0 === hashesPerPage} Expected a non-zero integer.`;
3693
- this.resetPage();
3694
- }
3695
- resetPage() {
3696
- const pageSizeBytes = this.hashesPerPage * HASH_SIZE;
3697
- this.currentHash = 0;
3698
- this.page = new Uint8Array(pageSizeBytes);
3699
- }
3700
- emptyHash() {
3701
- const startIdx = this.currentHash * HASH_SIZE;
3702
- const endIdx = startIdx + HASH_SIZE;
3703
- this.currentHash += 1;
3704
- if (this.currentHash >= this.hashesPerPage) {
3705
- this.resetPage();
3706
- }
3707
- return Bytes.fromBlob(this.page.subarray(startIdx, endIdx), HASH_SIZE);
3708
- }
3709
- }
3710
- const defaultAllocator = new SimpleAllocator();
3711
-
3712
- function getDefaultExportFromCjs (x) {
3713
- return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
3714
- }
3715
-
3716
- var blake2b$3 = {exports: {}};
3717
-
3718
- var nanoassert;
3719
- var hasRequiredNanoassert;
3720
-
3721
- function requireNanoassert () {
3722
- if (hasRequiredNanoassert) return nanoassert;
3723
- hasRequiredNanoassert = 1;
3724
- nanoassert = assert;
3725
-
3726
- class AssertionError extends Error {}
3727
- AssertionError.prototype.name = 'AssertionError';
3728
-
3729
- /**
3730
- * Minimal assert function
3731
- * @param {any} t Value to check if falsy
3732
- * @param {string=} m Optional assertion error message
3733
- * @throws {AssertionError}
3734
- */
3735
- function assert (t, m) {
3736
- if (!t) {
3737
- var err = new AssertionError(m);
3738
- if (Error.captureStackTrace) Error.captureStackTrace(err, assert);
3739
- throw err
3740
- }
3741
- }
3742
- return nanoassert;
3743
- }
3744
-
3745
- var blake2bWasm = {exports: {}};
3746
-
3747
- var b4a;
3748
- var hasRequiredB4a;
3749
-
3750
- function requireB4a () {
3751
- if (hasRequiredB4a) return b4a;
3752
- hasRequiredB4a = 1;
3753
- function isBuffer (value) {
3754
- return Buffer.isBuffer(value) || value instanceof Uint8Array
3755
- }
3756
-
3757
- function isEncoding (encoding) {
3758
- return Buffer.isEncoding(encoding)
3759
- }
3760
-
3761
- function alloc (size, fill, encoding) {
3762
- return Buffer.alloc(size, fill, encoding)
3763
- }
3764
-
3765
- function allocUnsafe (size) {
3766
- return Buffer.allocUnsafe(size)
3767
- }
3768
-
3769
- function allocUnsafeSlow (size) {
3770
- return Buffer.allocUnsafeSlow(size)
3771
- }
3772
-
3773
- function byteLength (string, encoding) {
3774
- return Buffer.byteLength(string, encoding)
3775
- }
3776
-
3777
- function compare (a, b) {
3778
- return Buffer.compare(a, b)
3779
- }
3780
-
3781
- function concat (buffers, totalLength) {
3782
- return Buffer.concat(buffers, totalLength)
3783
- }
3784
-
3785
- function copy (source, target, targetStart, start, end) {
3786
- return toBuffer(source).copy(target, targetStart, start, end)
3787
- }
3788
-
3789
- function equals (a, b) {
3790
- return toBuffer(a).equals(b)
3791
- }
3792
-
3793
- function fill (buffer, value, offset, end, encoding) {
3794
- return toBuffer(buffer).fill(value, offset, end, encoding)
3795
- }
3796
-
3797
- function from (value, encodingOrOffset, length) {
3798
- return Buffer.from(value, encodingOrOffset, length)
3799
- }
3800
-
3801
- function includes (buffer, value, byteOffset, encoding) {
3802
- return toBuffer(buffer).includes(value, byteOffset, encoding)
3803
- }
3804
-
3805
- function indexOf (buffer, value, byfeOffset, encoding) {
3806
- return toBuffer(buffer).indexOf(value, byfeOffset, encoding)
3807
- }
3808
-
3809
- function lastIndexOf (buffer, value, byteOffset, encoding) {
3810
- return toBuffer(buffer).lastIndexOf(value, byteOffset, encoding)
3811
- }
3812
-
3813
- function swap16 (buffer) {
3814
- return toBuffer(buffer).swap16()
3815
- }
3816
-
3817
- function swap32 (buffer) {
3818
- return toBuffer(buffer).swap32()
3819
- }
3820
-
3821
- function swap64 (buffer) {
3822
- return toBuffer(buffer).swap64()
3823
- }
3824
-
3825
- function toBuffer (buffer) {
3826
- if (Buffer.isBuffer(buffer)) return buffer
3827
- return Buffer.from(buffer.buffer, buffer.byteOffset, buffer.byteLength)
3828
- }
3829
-
3830
- function toString (buffer, encoding, start, end) {
3831
- return toBuffer(buffer).toString(encoding, start, end)
3832
- }
3833
-
3834
- function write (buffer, string, offset, length, encoding) {
3835
- return toBuffer(buffer).write(string, offset, length, encoding)
3836
- }
3837
-
3838
- function writeDoubleLE (buffer, value, offset) {
3839
- return toBuffer(buffer).writeDoubleLE(value, offset)
3840
- }
3841
-
3842
- function writeFloatLE (buffer, value, offset) {
3843
- return toBuffer(buffer).writeFloatLE(value, offset)
3844
- }
3845
-
3846
- function writeUInt32LE (buffer, value, offset) {
3847
- return toBuffer(buffer).writeUInt32LE(value, offset)
3848
- }
3849
-
3850
- function writeInt32LE (buffer, value, offset) {
3851
- return toBuffer(buffer).writeInt32LE(value, offset)
3852
- }
3853
-
3854
- function readDoubleLE (buffer, offset) {
3855
- return toBuffer(buffer).readDoubleLE(offset)
3856
- }
3857
-
3858
- function readFloatLE (buffer, offset) {
3859
- return toBuffer(buffer).readFloatLE(offset)
3860
- }
3861
-
3862
- function readUInt32LE (buffer, offset) {
3863
- return toBuffer(buffer).readUInt32LE(offset)
3864
- }
3865
-
3866
- function readInt32LE (buffer, offset) {
3867
- return toBuffer(buffer).readInt32LE(offset)
3868
- }
3869
-
3870
- b4a = {
3871
- isBuffer,
3872
- isEncoding,
3873
- alloc,
3874
- allocUnsafe,
3875
- allocUnsafeSlow,
3876
- byteLength,
3877
- compare,
3878
- concat,
3879
- copy,
3880
- equals,
3881
- fill,
3882
- from,
3883
- includes,
3884
- indexOf,
3885
- lastIndexOf,
3886
- swap16,
3887
- swap32,
3888
- swap64,
3889
- toBuffer,
3890
- toString,
3891
- write,
3892
- writeDoubleLE,
3893
- writeFloatLE,
3894
- writeUInt32LE,
3895
- writeInt32LE,
3896
- readDoubleLE,
3897
- readFloatLE,
3898
- readUInt32LE,
3899
- readInt32LE
3900
- };
3901
- return b4a;
3902
- }
3903
-
3904
- var blake2b$2;
3905
- var hasRequiredBlake2b$1;
3906
-
3907
- function requireBlake2b$1 () {
3908
- if (hasRequiredBlake2b$1) return blake2b$2;
3909
- hasRequiredBlake2b$1 = 1;
3910
- var __commonJS = (cb, mod) => function __require() {
3911
- return mod || (0, cb[Object.keys(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
3912
- };
3913
- var __toBinary = /* @__PURE__ */ (() => {
3914
- var table = new Uint8Array(128);
3915
- for (var i = 0; i < 64; i++)
3916
- table[i < 26 ? i + 65 : i < 52 ? i + 71 : i < 62 ? i - 4 : i * 4 - 205] = i;
3917
- return (base64) => {
3918
- var n = base64.length, bytes2 = new Uint8Array((n - (base64[n - 1] == "=") - (base64[n - 2] == "=")) * 3 / 4 | 0);
3919
- for (var i2 = 0, j = 0; i2 < n; ) {
3920
- var c0 = table[base64.charCodeAt(i2++)], c1 = table[base64.charCodeAt(i2++)];
3921
- var c2 = table[base64.charCodeAt(i2++)], c3 = table[base64.charCodeAt(i2++)];
3922
- bytes2[j++] = c0 << 2 | c1 >> 4;
3923
- bytes2[j++] = c1 << 4 | c2 >> 2;
3924
- bytes2[j++] = c2 << 6 | c3;
3925
- }
3926
- return bytes2;
3927
- };
3928
- })();
3929
-
3930
- // wasm-binary:./blake2b.wat
3931
- var require_blake2b = __commonJS({
3932
- "wasm-binary:./blake2b.wat"(exports2, module2) {
3933
- module2.exports = __toBinary("AGFzbQEAAAABEANgAn9/AGADf39/AGABfwADBQQAAQICBQUBAQroBwdNBQZtZW1vcnkCAAxibGFrZTJiX2luaXQAAA5ibGFrZTJiX3VwZGF0ZQABDWJsYWtlMmJfZmluYWwAAhBibGFrZTJiX2NvbXByZXNzAAMKvz8EwAIAIABCADcDACAAQgA3AwggAEIANwMQIABCADcDGCAAQgA3AyAgAEIANwMoIABCADcDMCAAQgA3AzggAEIANwNAIABCADcDSCAAQgA3A1AgAEIANwNYIABCADcDYCAAQgA3A2ggAEIANwNwIABCADcDeCAAQoiS853/zPmE6gBBACkDAIU3A4ABIABCu86qptjQ67O7f0EIKQMAhTcDiAEgAEKr8NP0r+68tzxBECkDAIU3A5ABIABC8e30+KWn/aelf0EYKQMAhTcDmAEgAELRhZrv+s+Uh9EAQSApAwCFNwOgASAAQp/Y+dnCkdqCm39BKCkDAIU3A6gBIABC6/qG2r+19sEfQTApAwCFNwOwASAAQvnC+JuRo7Pw2wBBOCkDAIU3A7gBIABCADcDwAEgAEIANwPIASAAQgA3A9ABC20BA38gAEHAAWohAyAAQcgBaiEEIAQpAwCnIQUCQANAIAEgAkYNASAFQYABRgRAIAMgAykDACAFrXw3AwBBACEFIAAQAwsgACAFaiABLQAAOgAAIAVBAWohBSABQQFqIQEMAAsLIAQgBa03AwALYQEDfyAAQcABaiEBIABByAFqIQIgASABKQMAIAIpAwB8NwMAIABCfzcD0AEgAikDAKchAwJAA0AgA0GAAUYNASAAIANqQQA6AAAgA0EBaiEDDAALCyACIAOtNwMAIAAQAwuqOwIgfgl/IABBgAFqISEgAEGIAWohIiAAQZABaiEjIABBmAFqISQgAEGgAWohJSAAQagBaiEmIABBsAFqIScgAEG4AWohKCAhKQMAIQEgIikDACECICMpAwAhAyAkKQ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hUIQiiEPIAogD3whCiAFIAqFQj+KIQUgISAhKQMAIAEgCYWFNwMAICIgIikDACACIAqFhTcDACAjICMpAwAgAyALhYU3AwAgJCAkKQMAIAQgDIWFNwMAICUgJSkDACAFIA2FhTcDACAmICYpAwAgBiAOhYU3AwAgJyAnKQMAIAcgD4WFNwMAICggKCkDACAIIBCFhTcDAAs=");
3934
- }
3935
- });
3936
-
3937
- // wasm-module:./blake2b.wat
3938
- var bytes = require_blake2b();
3939
- var compiled = WebAssembly.compile(bytes);
3940
- blake2b$2 = async (imports) => {
3941
- const instance = await WebAssembly.instantiate(await compiled, imports);
3942
- return instance.exports;
3943
- };
3944
- return blake2b$2;
3945
- }
3946
-
3947
- var hasRequiredBlake2bWasm;
3948
-
3949
- function requireBlake2bWasm () {
3950
- if (hasRequiredBlake2bWasm) return blake2bWasm.exports;
3951
- hasRequiredBlake2bWasm = 1;
3952
- var assert = /*@__PURE__*/ requireNanoassert();
3953
- var b4a = /*@__PURE__*/ requireB4a();
3954
-
3955
- var wasm = null;
3956
- var wasmPromise = typeof WebAssembly !== "undefined" && /*@__PURE__*/ requireBlake2b$1()().then(mod => {
3957
- wasm = mod;
3958
- });
3959
-
3960
- var head = 64;
3961
- var freeList = [];
3962
-
3963
- blake2bWasm.exports = Blake2b;
3964
- var BYTES_MIN = blake2bWasm.exports.BYTES_MIN = 16;
3965
- var BYTES_MAX = blake2bWasm.exports.BYTES_MAX = 64;
3966
- blake2bWasm.exports.BYTES = 32;
3967
- var KEYBYTES_MIN = blake2bWasm.exports.KEYBYTES_MIN = 16;
3968
- var KEYBYTES_MAX = blake2bWasm.exports.KEYBYTES_MAX = 64;
3969
- blake2bWasm.exports.KEYBYTES = 32;
3970
- var SALTBYTES = blake2bWasm.exports.SALTBYTES = 16;
3971
- var PERSONALBYTES = blake2bWasm.exports.PERSONALBYTES = 16;
3972
-
3973
- function Blake2b (digestLength, key, salt, personal, noAssert) {
3974
- if (!(this instanceof Blake2b)) return new Blake2b(digestLength, key, salt, personal, noAssert)
3975
- if (!wasm) throw new Error('WASM not loaded. Wait for Blake2b.ready(cb)')
3976
- if (!digestLength) digestLength = 32;
3977
-
3978
- if (noAssert !== true) {
3979
- assert(digestLength >= BYTES_MIN, 'digestLength must be at least ' + BYTES_MIN + ', was given ' + digestLength);
3980
- assert(digestLength <= BYTES_MAX, 'digestLength must be at most ' + BYTES_MAX + ', was given ' + digestLength);
3981
- if (key != null) {
3982
- assert(key instanceof Uint8Array, 'key must be Uint8Array or Buffer');
3983
- assert(key.length >= KEYBYTES_MIN, 'key must be at least ' + KEYBYTES_MIN + ', was given ' + key.length);
3984
- assert(key.length <= KEYBYTES_MAX, 'key must be at least ' + KEYBYTES_MAX + ', was given ' + key.length);
3985
- }
3986
- if (salt != null) {
3987
- assert(salt instanceof Uint8Array, 'salt must be Uint8Array or Buffer');
3988
- assert(salt.length === SALTBYTES, 'salt must be exactly ' + SALTBYTES + ', was given ' + salt.length);
3989
- }
3990
- if (personal != null) {
3991
- assert(personal instanceof Uint8Array, 'personal must be Uint8Array or Buffer');
3992
- assert(personal.length === PERSONALBYTES, 'personal must be exactly ' + PERSONALBYTES + ', was given ' + personal.length);
3993
- }
3994
- }
3995
-
3996
- if (!freeList.length) {
3997
- freeList.push(head);
3998
- head += 216;
3999
- }
4000
-
4001
- this.digestLength = digestLength;
4002
- this.finalized = false;
4003
- this.pointer = freeList.pop();
4004
- this._memory = new Uint8Array(wasm.memory.buffer);
4005
-
4006
- this._memory.fill(0, 0, 64);
4007
- this._memory[0] = this.digestLength;
4008
- this._memory[1] = key ? key.length : 0;
4009
- this._memory[2] = 1; // fanout
4010
- this._memory[3] = 1; // depth
4011
-
4012
- if (salt) this._memory.set(salt, 32);
4013
- if (personal) this._memory.set(personal, 48);
4014
-
4015
- if (this.pointer + 216 > this._memory.length) this._realloc(this.pointer + 216); // we need 216 bytes for the state
4016
- wasm.blake2b_init(this.pointer, this.digestLength);
4017
-
4018
- if (key) {
4019
- this.update(key);
4020
- this._memory.fill(0, head, head + key.length); // whiteout key
4021
- this._memory[this.pointer + 200] = 128;
4022
- }
4023
- }
4024
-
4025
- Blake2b.prototype._realloc = function (size) {
4026
- wasm.memory.grow(Math.max(0, Math.ceil(Math.abs(size - this._memory.length) / 65536)));
4027
- this._memory = new Uint8Array(wasm.memory.buffer);
4028
- };
4029
-
4030
- Blake2b.prototype.update = function (input) {
4031
- assert(this.finalized === false, 'Hash instance finalized');
4032
- assert(input instanceof Uint8Array, 'input must be Uint8Array or Buffer');
4033
-
4034
- if (head + input.length > this._memory.length) this._realloc(head + input.length);
4035
- this._memory.set(input, head);
4036
- wasm.blake2b_update(this.pointer, head, head + input.length);
4037
- return this
4038
- };
4039
-
4040
- Blake2b.prototype.digest = function (enc) {
4041
- assert(this.finalized === false, 'Hash instance finalized');
4042
- this.finalized = true;
4043
-
4044
- freeList.push(this.pointer);
4045
- wasm.blake2b_final(this.pointer);
4046
-
4047
- if (!enc || enc === 'binary') {
4048
- return this._memory.slice(this.pointer + 128, this.pointer + 128 + this.digestLength)
4049
- }
4050
-
4051
- if (typeof enc === 'string') {
4052
- return b4a.toString(this._memory, enc, this.pointer + 128, this.pointer + 128 + this.digestLength)
4053
- }
4054
-
4055
- assert(enc instanceof Uint8Array && enc.length >= this.digestLength, 'input must be Uint8Array or Buffer');
4056
- for (var i = 0; i < this.digestLength; i++) {
4057
- enc[i] = this._memory[this.pointer + 128 + i];
4058
- }
4059
-
4060
- return enc
4061
- };
4062
-
4063
- // libsodium compat
4064
- Blake2b.prototype.final = Blake2b.prototype.digest;
4065
-
4066
- Blake2b.WASM = wasm;
4067
- Blake2b.SUPPORTED = typeof WebAssembly !== 'undefined';
4068
-
4069
- Blake2b.ready = function (cb) {
4070
- if (!cb) cb = noop;
4071
- if (!wasmPromise) return cb(new Error('WebAssembly not supported'))
4072
- return wasmPromise.then(() => cb(), cb)
4073
- };
4074
-
4075
- Blake2b.prototype.ready = Blake2b.ready;
4076
-
4077
- Blake2b.prototype.getPartialHash = function () {
4078
- return this._memory.slice(this.pointer, this.pointer + 216);
4079
- };
4080
-
4081
- Blake2b.prototype.setPartialHash = function (ph) {
4082
- this._memory.set(ph, this.pointer);
4083
- };
4084
-
4085
- function noop () {}
4086
- return blake2bWasm.exports;
4087
- }
4088
-
4089
- var hasRequiredBlake2b;
4090
-
4091
- function requireBlake2b () {
4092
- if (hasRequiredBlake2b) return blake2b$3.exports;
4093
- hasRequiredBlake2b = 1;
4094
- var assert = /*@__PURE__*/ requireNanoassert();
4095
- var b2wasm = /*@__PURE__*/ requireBlake2bWasm();
4096
-
4097
- // 64-bit unsigned addition
4098
- // Sets v[a,a+1] += v[b,b+1]
4099
- // v should be a Uint32Array
4100
- function ADD64AA (v, a, b) {
4101
- var o0 = v[a] + v[b];
4102
- var o1 = v[a + 1] + v[b + 1];
4103
- if (o0 >= 0x100000000) {
4104
- o1++;
4105
- }
4106
- v[a] = o0;
4107
- v[a + 1] = o1;
4108
- }
4109
-
4110
- // 64-bit unsigned addition
4111
- // Sets v[a,a+1] += b
4112
- // b0 is the low 32 bits of b, b1 represents the high 32 bits
4113
- function ADD64AC (v, a, b0, b1) {
4114
- var o0 = v[a] + b0;
4115
- if (b0 < 0) {
4116
- o0 += 0x100000000;
4117
- }
4118
- var o1 = v[a + 1] + b1;
4119
- if (o0 >= 0x100000000) {
4120
- o1++;
4121
- }
4122
- v[a] = o0;
4123
- v[a + 1] = o1;
4124
- }
4125
-
4126
- // Little-endian byte access
4127
- function B2B_GET32 (arr, i) {
4128
- return (arr[i] ^
4129
- (arr[i + 1] << 8) ^
4130
- (arr[i + 2] << 16) ^
4131
- (arr[i + 3] << 24))
4132
- }
4133
-
4134
- // G Mixing function
4135
- // The ROTRs are inlined for speed
4136
- function B2B_G (a, b, c, d, ix, iy) {
4137
- var x0 = m[ix];
4138
- var x1 = m[ix + 1];
4139
- var y0 = m[iy];
4140
- var y1 = m[iy + 1];
4141
-
4142
- ADD64AA(v, a, b); // v[a,a+1] += v[b,b+1] ... in JS we must store a uint64 as two uint32s
4143
- ADD64AC(v, a, x0, x1); // v[a, a+1] += x ... x0 is the low 32 bits of x, x1 is the high 32 bits
4144
-
4145
- // v[d,d+1] = (v[d,d+1] xor v[a,a+1]) rotated to the right by 32 bits
4146
- var xor0 = v[d] ^ v[a];
4147
- var xor1 = v[d + 1] ^ v[a + 1];
4148
- v[d] = xor1;
4149
- v[d + 1] = xor0;
4150
-
4151
- ADD64AA(v, c, d);
4152
-
4153
- // v[b,b+1] = (v[b,b+1] xor v[c,c+1]) rotated right by 24 bits
4154
- xor0 = v[b] ^ v[c];
4155
- xor1 = v[b + 1] ^ v[c + 1];
4156
- v[b] = (xor0 >>> 24) ^ (xor1 << 8);
4157
- v[b + 1] = (xor1 >>> 24) ^ (xor0 << 8);
4158
-
4159
- ADD64AA(v, a, b);
4160
- ADD64AC(v, a, y0, y1);
4161
-
4162
- // v[d,d+1] = (v[d,d+1] xor v[a,a+1]) rotated right by 16 bits
4163
- xor0 = v[d] ^ v[a];
4164
- xor1 = v[d + 1] ^ v[a + 1];
4165
- v[d] = (xor0 >>> 16) ^ (xor1 << 16);
4166
- v[d + 1] = (xor1 >>> 16) ^ (xor0 << 16);
4167
-
4168
- ADD64AA(v, c, d);
4169
-
4170
- // v[b,b+1] = (v[b,b+1] xor v[c,c+1]) rotated right by 63 bits
4171
- xor0 = v[b] ^ v[c];
4172
- xor1 = v[b + 1] ^ v[c + 1];
4173
- v[b] = (xor1 >>> 31) ^ (xor0 << 1);
4174
- v[b + 1] = (xor0 >>> 31) ^ (xor1 << 1);
4175
- }
4176
-
4177
- // Initialization Vector
4178
- var BLAKE2B_IV32 = new Uint32Array([
4179
- 0xF3BCC908, 0x6A09E667, 0x84CAA73B, 0xBB67AE85,
4180
- 0xFE94F82B, 0x3C6EF372, 0x5F1D36F1, 0xA54FF53A,
4181
- 0xADE682D1, 0x510E527F, 0x2B3E6C1F, 0x9B05688C,
4182
- 0xFB41BD6B, 0x1F83D9AB, 0x137E2179, 0x5BE0CD19
4183
- ]);
4184
-
4185
- var SIGMA8 = [
4186
- 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,
4187
- 14, 10, 4, 8, 9, 15, 13, 6, 1, 12, 0, 2, 11, 7, 5, 3,
4188
- 11, 8, 12, 0, 5, 2, 15, 13, 10, 14, 3, 6, 7, 1, 9, 4,
4189
- 7, 9, 3, 1, 13, 12, 11, 14, 2, 6, 5, 10, 4, 0, 15, 8,
4190
- 9, 0, 5, 7, 2, 4, 10, 15, 14, 1, 11, 12, 6, 8, 3, 13,
4191
- 2, 12, 6, 10, 0, 11, 8, 3, 4, 13, 7, 5, 15, 14, 1, 9,
4192
- 12, 5, 1, 15, 14, 13, 4, 10, 0, 7, 6, 3, 9, 2, 8, 11,
4193
- 13, 11, 7, 14, 12, 1, 3, 9, 5, 0, 15, 4, 8, 6, 2, 10,
4194
- 6, 15, 14, 9, 11, 3, 0, 8, 12, 2, 13, 7, 1, 4, 10, 5,
4195
- 10, 2, 8, 4, 7, 6, 1, 5, 15, 11, 9, 14, 3, 12, 13, 0,
4196
- 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,
4197
- 14, 10, 4, 8, 9, 15, 13, 6, 1, 12, 0, 2, 11, 7, 5, 3
4198
- ];
4199
-
4200
- // These are offsets into a uint64 buffer.
4201
- // Multiply them all by 2 to make them offsets into a uint32 buffer,
4202
- // because this is Javascript and we don't have uint64s
4203
- var SIGMA82 = new Uint8Array(SIGMA8.map(function (x) { return x * 2 }));
4204
-
4205
- // Compression function. 'last' flag indicates last block.
4206
- // Note we're representing 16 uint64s as 32 uint32s
4207
- var v = new Uint32Array(32);
4208
- var m = new Uint32Array(32);
4209
- function blake2bCompress (ctx, last) {
4210
- var i = 0;
4211
-
4212
- // init work variables
4213
- for (i = 0; i < 16; i++) {
4214
- v[i] = ctx.h[i];
4215
- v[i + 16] = BLAKE2B_IV32[i];
4216
- }
4217
-
4218
- // low 64 bits of offset
4219
- v[24] = v[24] ^ ctx.t;
4220
- v[25] = v[25] ^ (ctx.t / 0x100000000);
4221
- // high 64 bits not supported, offset may not be higher than 2**53-1
4222
-
4223
- // last block flag set ?
4224
- if (last) {
4225
- v[28] = ~v[28];
4226
- v[29] = ~v[29];
4227
- }
4228
-
4229
- // get little-endian words
4230
- for (i = 0; i < 32; i++) {
4231
- m[i] = B2B_GET32(ctx.b, 4 * i);
4232
- }
4233
-
4234
- // twelve rounds of mixing
4235
- for (i = 0; i < 12; i++) {
4236
- B2B_G(0, 8, 16, 24, SIGMA82[i * 16 + 0], SIGMA82[i * 16 + 1]);
4237
- B2B_G(2, 10, 18, 26, SIGMA82[i * 16 + 2], SIGMA82[i * 16 + 3]);
4238
- B2B_G(4, 12, 20, 28, SIGMA82[i * 16 + 4], SIGMA82[i * 16 + 5]);
4239
- B2B_G(6, 14, 22, 30, SIGMA82[i * 16 + 6], SIGMA82[i * 16 + 7]);
4240
- B2B_G(0, 10, 20, 30, SIGMA82[i * 16 + 8], SIGMA82[i * 16 + 9]);
4241
- B2B_G(2, 12, 22, 24, SIGMA82[i * 16 + 10], SIGMA82[i * 16 + 11]);
4242
- B2B_G(4, 14, 16, 26, SIGMA82[i * 16 + 12], SIGMA82[i * 16 + 13]);
4243
- B2B_G(6, 8, 18, 28, SIGMA82[i * 16 + 14], SIGMA82[i * 16 + 15]);
4244
- }
4245
-
4246
- for (i = 0; i < 16; i++) {
4247
- ctx.h[i] = ctx.h[i] ^ v[i] ^ v[i + 16];
4248
- }
4249
- }
4250
-
4251
- // reusable parameter_block
4252
- var parameter_block = new Uint8Array([
4253
- 0, 0, 0, 0, // 0: outlen, keylen, fanout, depth
4254
- 0, 0, 0, 0, // 4: leaf length, sequential mode
4255
- 0, 0, 0, 0, // 8: node offset
4256
- 0, 0, 0, 0, // 12: node offset
4257
- 0, 0, 0, 0, // 16: node depth, inner length, rfu
4258
- 0, 0, 0, 0, // 20: rfu
4259
- 0, 0, 0, 0, // 24: rfu
4260
- 0, 0, 0, 0, // 28: rfu
4261
- 0, 0, 0, 0, // 32: salt
4262
- 0, 0, 0, 0, // 36: salt
4263
- 0, 0, 0, 0, // 40: salt
4264
- 0, 0, 0, 0, // 44: salt
4265
- 0, 0, 0, 0, // 48: personal
4266
- 0, 0, 0, 0, // 52: personal
4267
- 0, 0, 0, 0, // 56: personal
4268
- 0, 0, 0, 0 // 60: personal
4269
- ]);
4270
-
4271
- // Creates a BLAKE2b hashing context
4272
- // Requires an output length between 1 and 64 bytes
4273
- // Takes an optional Uint8Array key
4274
- function Blake2b (outlen, key, salt, personal) {
4275
- // zero out parameter_block before usage
4276
- parameter_block.fill(0);
4277
- // state, 'param block'
4278
-
4279
- this.b = new Uint8Array(128);
4280
- this.h = new Uint32Array(16);
4281
- this.t = 0; // input count
4282
- this.c = 0; // pointer within buffer
4283
- this.outlen = outlen; // output length in bytes
4284
-
4285
- parameter_block[0] = outlen;
4286
- if (key) parameter_block[1] = key.length;
4287
- parameter_block[2] = 1; // fanout
4288
- parameter_block[3] = 1; // depth
4289
-
4290
- if (salt) parameter_block.set(salt, 32);
4291
- if (personal) parameter_block.set(personal, 48);
4292
-
4293
- // initialize hash state
4294
- for (var i = 0; i < 16; i++) {
4295
- this.h[i] = BLAKE2B_IV32[i] ^ B2B_GET32(parameter_block, i * 4);
4296
- }
4297
-
4298
- // key the hash, if applicable
4299
- if (key) {
4300
- blake2bUpdate(this, key);
4301
- // at the end
4302
- this.c = 128;
4303
- }
4304
- }
4305
-
4306
- Blake2b.prototype.update = function (input) {
4307
- assert(input instanceof Uint8Array, 'input must be Uint8Array or Buffer');
4308
- blake2bUpdate(this, input);
4309
- return this
4310
- };
4311
-
4312
- Blake2b.prototype.digest = function (out) {
4313
- var buf = (!out || out === 'binary' || out === 'hex') ? new Uint8Array(this.outlen) : out;
4314
- assert(buf instanceof Uint8Array, 'out must be "binary", "hex", Uint8Array, or Buffer');
4315
- assert(buf.length >= this.outlen, 'out must have at least outlen bytes of space');
4316
- blake2bFinal(this, buf);
4317
- if (out === 'hex') return hexSlice(buf)
4318
- return buf
4319
- };
4320
-
4321
- Blake2b.prototype.final = Blake2b.prototype.digest;
4322
-
4323
- Blake2b.ready = function (cb) {
4324
- b2wasm.ready(function () {
4325
- cb(); // ignore the error
4326
- });
4327
- };
4328
-
4329
- // Updates a BLAKE2b streaming hash
4330
- // Requires hash context and Uint8Array (byte array)
4331
- function blake2bUpdate (ctx, input) {
4332
- for (var i = 0; i < input.length; i++) {
4333
- if (ctx.c === 128) { // buffer full ?
4334
- ctx.t += ctx.c; // add counters
4335
- blake2bCompress(ctx, false); // compress (not last)
4336
- ctx.c = 0; // counter to zero
4337
- }
4338
- ctx.b[ctx.c++] = input[i];
4339
- }
4340
- }
4341
-
4342
- // Completes a BLAKE2b streaming hash
4343
- // Returns a Uint8Array containing the message digest
4344
- function blake2bFinal (ctx, out) {
4345
- ctx.t += ctx.c; // mark last block offset
4346
-
4347
- while (ctx.c < 128) { // fill up with zeros
4348
- ctx.b[ctx.c++] = 0;
4349
- }
4350
- blake2bCompress(ctx, true); // final block flag = 1
4351
-
4352
- for (var i = 0; i < ctx.outlen; i++) {
4353
- out[i] = ctx.h[i >> 2] >> (8 * (i & 3));
4354
- }
4355
- return out
4356
- }
4357
-
4358
- function hexSlice (buf) {
4359
- var str = '';
4360
- for (var i = 0; i < buf.length; i++) str += toHex(buf[i]);
4361
- return str
4362
- }
4363
-
4364
- function toHex (n) {
4365
- if (n < 16) return '0' + n.toString(16)
4366
- return n.toString(16)
4367
- }
4368
-
4369
- var Proto = Blake2b;
4370
-
4371
- blake2b$3.exports = function createHash (outlen, key, salt, personal, noAssert) {
4372
- if (noAssert !== true) {
4373
- assert(outlen >= BYTES_MIN, 'outlen must be at least ' + BYTES_MIN + ', was given ' + outlen);
4374
- assert(outlen <= BYTES_MAX, 'outlen must be at most ' + BYTES_MAX + ', was given ' + outlen);
4375
- if (key != null) {
4376
- assert(key instanceof Uint8Array, 'key must be Uint8Array or Buffer');
4377
- assert(key.length >= KEYBYTES_MIN, 'key must be at least ' + KEYBYTES_MIN + ', was given ' + key.length);
4378
- assert(key.length <= KEYBYTES_MAX, 'key must be at most ' + KEYBYTES_MAX + ', was given ' + key.length);
4379
- }
4380
- if (salt != null) {
4381
- assert(salt instanceof Uint8Array, 'salt must be Uint8Array or Buffer');
4382
- assert(salt.length === SALTBYTES, 'salt must be exactly ' + SALTBYTES + ', was given ' + salt.length);
4383
- }
4384
- if (personal != null) {
4385
- assert(personal instanceof Uint8Array, 'personal must be Uint8Array or Buffer');
4386
- assert(personal.length === PERSONALBYTES, 'personal must be exactly ' + PERSONALBYTES + ', was given ' + personal.length);
4387
- }
4388
- }
4389
-
4390
- return new Proto(outlen, key, salt, personal)
4391
- };
4392
-
4393
- blake2b$3.exports.ready = function (cb) {
4394
- b2wasm.ready(function () { // ignore errors
4395
- cb();
4396
- });
4397
- };
4398
-
4399
- blake2b$3.exports.WASM_SUPPORTED = b2wasm.SUPPORTED;
4400
- blake2b$3.exports.WASM_LOADED = false;
4401
-
4402
- var BYTES_MIN = blake2b$3.exports.BYTES_MIN = 16;
4403
- var BYTES_MAX = blake2b$3.exports.BYTES_MAX = 64;
4404
- blake2b$3.exports.BYTES = 32;
4405
- var KEYBYTES_MIN = blake2b$3.exports.KEYBYTES_MIN = 16;
4406
- var KEYBYTES_MAX = blake2b$3.exports.KEYBYTES_MAX = 64;
4407
- blake2b$3.exports.KEYBYTES = 32;
4408
- var SALTBYTES = blake2b$3.exports.SALTBYTES = 16;
4409
- var PERSONALBYTES = blake2b$3.exports.PERSONALBYTES = 16;
4410
-
4411
- b2wasm.ready(function (err) {
4412
- if (!err) {
4413
- blake2b$3.exports.WASM_LOADED = true;
4414
- blake2b$3.exports = b2wasm;
4415
- }
4416
- });
4417
- return blake2b$3.exports;
3690
+ function deriveEd25519SecretKey(seed, blake2b) {
3691
+ return blake2b.hashBytes(BytesBlob.blobFromParts([ED25519_SECRET_KEY.raw, seed.raw])).asOpaque();
4418
3692
  }
4419
-
4420
- var blake2bExports = /*@__PURE__*/ requireBlake2b();
4421
- var blake2b$1 = /*@__PURE__*/getDefaultExportFromCjs(blake2bExports);
4422
-
4423
3693
  /**
4424
- * Hash given collection of blobs.
4425
- *
4426
- * If empty array is given a zero-hash is returned.
3694
+ * Derives a Bandersnatch secret key from a seed.
3695
+ * https://github.com/polkadot-fellows/JIPs/blob/7048f79edf4f4eb8bfe6fb42e6bbf61900f44c65/JIP-5.md#derivation-method
4427
3696
  */
4428
- function hashBlobs$1(r, allocator = defaultAllocator) {
4429
- const out = allocator.emptyHash();
4430
- if (r.length === 0) {
4431
- return out.asOpaque();
4432
- }
4433
- const hasher = blake2b$1(HASH_SIZE);
4434
- for (const v of r) {
4435
- hasher?.update(v instanceof BytesBlob ? v.raw : v);
4436
- }
4437
- hasher?.digest(out.raw);
4438
- return out.asOpaque();
3697
+ function deriveBandersnatchSecretKey(seed, blake2b) {
3698
+ return blake2b.hashBytes(BytesBlob.blobFromParts([BANDERSNATCH_SECRET_KEY.raw, seed.raw])).asOpaque();
4439
3699
  }
4440
- /** Hash given blob of bytes. */
4441
- function hashBytes(blob, allocator = defaultAllocator) {
4442
- const hasher = blake2b$1(HASH_SIZE);
4443
- const bytes = blob instanceof BytesBlob ? blob.raw : blob;
4444
- hasher?.update(bytes);
4445
- const out = allocator.emptyHash();
4446
- hasher?.digest(out.raw);
4447
- return out;
3700
+ /**
3701
+ * Derive Ed25519 public key from secret seed
3702
+ */
3703
+ async function deriveEd25519PublicKey(seed) {
3704
+ return (await privateKey(seed)).pubKey;
4448
3705
  }
4449
- /** Convert given string into bytes and hash it. */
4450
- function hashString(str, allocator = defaultAllocator) {
4451
- return hashBytes(BytesBlob.blobFromString(str), allocator);
3706
+ /**
3707
+ * Derive Bandersnatch public key from secret seed
3708
+ */
3709
+ function deriveBandersnatchPublicKey(seed) {
3710
+ return publicKey(seed.raw);
4452
3711
  }
4453
3712
 
4454
- var blake2b = /*#__PURE__*/Object.freeze({
3713
+ var keyDerivation = /*#__PURE__*/Object.freeze({
3714
+ __proto__: null,
3715
+ SEED_SIZE: SEED_SIZE,
3716
+ deriveBandersnatchPublicKey: deriveBandersnatchPublicKey,
3717
+ deriveBandersnatchSecretKey: deriveBandersnatchSecretKey,
3718
+ deriveEd25519PublicKey: deriveEd25519PublicKey,
3719
+ deriveEd25519SecretKey: deriveEd25519SecretKey,
3720
+ trivialSeed: trivialSeed
3721
+ });
3722
+
3723
+ var index$p = /*#__PURE__*/Object.freeze({
4455
3724
  __proto__: null,
4456
- hashBlobs: hashBlobs$1,
4457
- hashBytes: hashBytes,
4458
- hashString: hashString
3725
+ BANDERSNATCH_KEY_BYTES: BANDERSNATCH_KEY_BYTES,
3726
+ BANDERSNATCH_PROOF_BYTES: BANDERSNATCH_PROOF_BYTES,
3727
+ BANDERSNATCH_RING_ROOT_BYTES: BANDERSNATCH_RING_ROOT_BYTES,
3728
+ BANDERSNATCH_VRF_SIGNATURE_BYTES: BANDERSNATCH_VRF_SIGNATURE_BYTES,
3729
+ BLS_KEY_BYTES: BLS_KEY_BYTES,
3730
+ ED25519_KEY_BYTES: ED25519_KEY_BYTES,
3731
+ ED25519_PRIV_KEY_BYTES: ED25519_PRIV_KEY_BYTES,
3732
+ ED25519_SIGNATURE_BYTES: ED25519_SIGNATURE_BYTES,
3733
+ Ed25519Pair: Ed25519Pair,
3734
+ SEED_SIZE: SEED_SIZE,
3735
+ bandersnatch: bandersnatch,
3736
+ bandersnatchWasm: bandersnatch_exports,
3737
+ ed25519: ed25519,
3738
+ initWasm: initAll,
3739
+ keyDerivation: keyDerivation
4459
3740
  });
4460
3741
 
4461
3742
  /*!
@@ -4816,18 +4097,89 @@ function WASMInterface(binary, hashLength) {
4816
4097
 
4817
4098
  new Mutex();
4818
4099
 
4819
- new Mutex();
4820
-
4821
- new Mutex();
4822
-
4823
- new Mutex();
4824
-
4825
- new Mutex();
4826
-
4827
- new Mutex();
4100
+ var name$j = "blake2b";
4101
+ var data$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DqIsBQvnC+JuRo7Pw2wCFNwO4iQFBACADp0H/AXE2AuSKAQJAIAFBAUgNACACQgA3A3ggAkIANwNwIAJCADcDaCACQgA3A2AgAkIANwNYIAJCADcDUCACQgA3A0ggAkIANwNAIAJCADcDOCACQgA3AzAgAkIANwMoIAJCADcDICACQgA3AxggAkIANwMQIAJCADcDCCACQgA3AwBBACEEA0AgAiAAaiAAQYAJai0AADoAACAAQQFqIQAgBEEBaiIEQf8BcSABSA0ACyACQYABEAELIAJBgAFqJAALEgAgAEEDdkH/P3EgAEEQdhAECwkAQYAJIAAQAQsGAEGAiQELGwAgAUEDdkH/P3EgAUEQdhAEQYAJIAAQARADCwsLAQBBgAgLBPAAAAA=";
4102
+ var hash$j = "c6f286e6";
4103
+ var wasmJson$j = {
4104
+ name: name$j,
4105
+ data: data$j,
4106
+ hash: hash$j
4107
+ };
4828
4108
 
4829
4109
  new Mutex();
4830
-
4110
+ function validateBits$4(bits) {
4111
+ if (!Number.isInteger(bits) || bits < 8 || bits > 512 || bits % 8 !== 0) {
4112
+ return new Error("Invalid variant! Valid values: 8, 16, ..., 512");
4113
+ }
4114
+ return null;
4115
+ }
4116
+ function getInitParam$1(outputBits, keyBits) {
4117
+ return outputBits | (keyBits << 16);
4118
+ }
4119
+ /**
4120
+ * Creates a new BLAKE2b hash instance
4121
+ * @param bits Number of output bits, which has to be a number
4122
+ * divisible by 8, between 8 and 512. Defaults to 512.
4123
+ * @param key Optional key (string, Buffer or TypedArray). Maximum length is 64 bytes.
4124
+ */
4125
+ function createBLAKE2b(bits = 512, key = null) {
4126
+ if (validateBits$4(bits)) {
4127
+ return Promise.reject(validateBits$4(bits));
4128
+ }
4129
+ let keyBuffer = null;
4130
+ let initParam = bits;
4131
+ if (key !== null) {
4132
+ keyBuffer = getUInt8Buffer(key);
4133
+ if (keyBuffer.length > 64) {
4134
+ return Promise.reject(new Error("Max key length is 64 bytes"));
4135
+ }
4136
+ initParam = getInitParam$1(bits, keyBuffer.length);
4137
+ }
4138
+ const outputSize = bits / 8;
4139
+ return WASMInterface(wasmJson$j, outputSize).then((wasm) => {
4140
+ if (initParam > 512) {
4141
+ wasm.writeMemory(keyBuffer);
4142
+ }
4143
+ wasm.init(initParam);
4144
+ const obj = {
4145
+ init: initParam > 512
4146
+ ? () => {
4147
+ wasm.writeMemory(keyBuffer);
4148
+ wasm.init(initParam);
4149
+ return obj;
4150
+ }
4151
+ : () => {
4152
+ wasm.init(initParam);
4153
+ return obj;
4154
+ },
4155
+ update: (data) => {
4156
+ wasm.update(data);
4157
+ return obj;
4158
+ },
4159
+ // biome-ignore lint/suspicious/noExplicitAny: Conflict with IHasher type
4160
+ digest: (outputType) => wasm.digest(outputType),
4161
+ save: () => wasm.save(),
4162
+ load: (data) => {
4163
+ wasm.load(data);
4164
+ return obj;
4165
+ },
4166
+ blockSize: 128,
4167
+ digestSize: outputSize,
4168
+ };
4169
+ return obj;
4170
+ });
4171
+ }
4172
+
4173
+ new Mutex();
4174
+
4175
+ new Mutex();
4176
+
4177
+ new Mutex();
4178
+
4179
+ new Mutex();
4180
+
4181
+ new Mutex();
4182
+
4831
4183
  new Mutex();
4832
4184
 
4833
4185
  new Mutex();
@@ -4906,6 +4258,79 @@ new Mutex();
4906
4258
 
4907
4259
  new Mutex();
4908
4260
 
4261
+ /**
4262
+ * Size of the output of the hash functions.
4263
+ *
4264
+ * https://graypaper.fluffylabs.dev/#/579bd12/073101073c01
4265
+ *
4266
+ */
4267
+ const HASH_SIZE = 32;
4268
+ /** A hash without last byte (useful for trie representation). */
4269
+ const TRUNCATED_HASH_SIZE = 31;
4270
+ const ZERO_HASH = Bytes.zero(HASH_SIZE);
4271
+ /**
4272
+ * Container for some object with a hash that is related to this object.
4273
+ *
4274
+ * After calculating the hash these two should be passed together to avoid
4275
+ * unnecessary re-hashing of the data.
4276
+ */
4277
+ class WithHash extends WithDebug {
4278
+ hash;
4279
+ data;
4280
+ constructor(hash, data) {
4281
+ super();
4282
+ this.hash = hash;
4283
+ this.data = data;
4284
+ }
4285
+ }
4286
+ /**
4287
+ * Extension of [`WithHash`] additionally containing an encoded version of the object.
4288
+ */
4289
+ class WithHashAndBytes extends WithHash {
4290
+ encoded;
4291
+ constructor(hash, data, encoded) {
4292
+ super(hash, data);
4293
+ this.encoded = encoded;
4294
+ }
4295
+ }
4296
+
4297
+ const zero$1 = Bytes.zero(HASH_SIZE);
4298
+ class Blake2b {
4299
+ hasher;
4300
+ static async createHasher() {
4301
+ return new Blake2b(await createBLAKE2b(HASH_SIZE * 8));
4302
+ }
4303
+ constructor(hasher) {
4304
+ this.hasher = hasher;
4305
+ }
4306
+ /**
4307
+ * Hash given collection of blobs.
4308
+ *
4309
+ * If empty array is given a zero-hash is returned.
4310
+ */
4311
+ hashBlobs(r) {
4312
+ if (r.length === 0) {
4313
+ return zero$1.asOpaque();
4314
+ }
4315
+ const hasher = this.hasher.init();
4316
+ for (const v of r) {
4317
+ hasher.update(v instanceof BytesBlob ? v.raw : v);
4318
+ }
4319
+ return Bytes.fromBlob(hasher.digest("binary"), HASH_SIZE).asOpaque();
4320
+ }
4321
+ /** Hash given blob of bytes. */
4322
+ hashBytes(blob) {
4323
+ const hasher = this.hasher.init();
4324
+ const bytes = blob instanceof BytesBlob ? blob.raw : blob;
4325
+ hasher.update(bytes);
4326
+ return Bytes.fromBlob(hasher.digest("binary"), HASH_SIZE).asOpaque();
4327
+ }
4328
+ /** Convert given string into bytes and hash it. */
4329
+ hashString(str) {
4330
+ return this.hashBytes(BytesBlob.blobFromString(str));
4331
+ }
4332
+ }
4333
+
4909
4334
  class KeccakHasher {
4910
4335
  hasher;
4911
4336
  static async create() {
@@ -4930,91 +4355,61 @@ var keccak = /*#__PURE__*/Object.freeze({
4930
4355
  hashBlobs: hashBlobs
4931
4356
  });
4932
4357
 
4933
- var index$p = /*#__PURE__*/Object.freeze({
4358
+ // TODO [ToDr] (#213) this should most likely be moved to a separate
4359
+ // package to avoid pulling in unnecessary deps.
4360
+
4361
+ var index$o = /*#__PURE__*/Object.freeze({
4934
4362
  __proto__: null,
4363
+ Blake2b: Blake2b,
4935
4364
  HASH_SIZE: HASH_SIZE,
4936
- PageAllocator: PageAllocator,
4937
- SimpleAllocator: SimpleAllocator,
4938
4365
  TRUNCATED_HASH_SIZE: TRUNCATED_HASH_SIZE,
4939
4366
  WithHash: WithHash,
4940
4367
  WithHashAndBytes: WithHashAndBytes,
4941
4368
  ZERO_HASH: ZERO_HASH,
4942
- blake2b: blake2b,
4943
- defaultAllocator: defaultAllocator,
4944
4369
  keccak: keccak
4945
4370
  });
4946
4371
 
4947
- const SEED_SIZE = 32;
4948
- const ED25519_SECRET_KEY = Bytes.blobFromString("jam_val_key_ed25519");
4949
- const BANDERSNATCH_SECRET_KEY = Bytes.blobFromString("jam_val_key_bandersnatch");
4950
- /**
4951
- * JIP-5: Secret key derivation
4952
- *
4953
- * https://github.com/polkadot-fellows/JIPs/blob/7048f79edf4f4eb8bfe6fb42e6bbf61900f44c65/JIP-5.md */
4954
- /**
4955
- * Deriving a 32-byte seed from a 32-bit unsigned integer
4956
- * https://github.com/polkadot-fellows/JIPs/blob/7048f79edf4f4eb8bfe6fb42e6bbf61900f44c65/JIP-5.md#trivial-seeds
4957
- */
4958
- function trivialSeed(s) {
4959
- const s_le = u32AsLeBytes(s);
4960
- 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();
4961
- }
4962
- /**
4963
- * Derives a Ed25519 secret key from a seed.
4964
- * https://github.com/polkadot-fellows/JIPs/blob/7048f79edf4f4eb8bfe6fb42e6bbf61900f44c65/JIP-5.md#derivation-method
4965
- */
4966
- function deriveEd25519SecretKey(seed, allocator = new SimpleAllocator()) {
4967
- return hashBytes(BytesBlob.blobFromParts([ED25519_SECRET_KEY.raw, seed.raw]), allocator).asOpaque();
4968
- }
4969
- /**
4970
- * Derives a Bandersnatch secret key from a seed.
4971
- * https://github.com/polkadot-fellows/JIPs/blob/7048f79edf4f4eb8bfe6fb42e6bbf61900f44c65/JIP-5.md#derivation-method
4972
- */
4973
- function deriveBandersnatchSecretKey(seed, allocator = new SimpleAllocator()) {
4974
- return hashBytes(BytesBlob.blobFromParts([BANDERSNATCH_SECRET_KEY.raw, seed.raw]), allocator).asOpaque();
4975
- }
4976
- /**
4977
- * Derive Ed25519 public key from secret seed
4978
- */
4979
- async function deriveEd25519PublicKey(seed) {
4980
- return (await privateKey(seed)).pubKey;
4981
- }
4982
4372
  /**
4983
- * Derive Bandersnatch public key from secret seed
4373
+ * A utility class providing a readonly view over a portion of an array without copying it.
4984
4374
  */
4985
- function deriveBandersnatchPublicKey(seed) {
4986
- return publicKey(seed.raw);
4375
+ class ArrayView {
4376
+ start;
4377
+ end;
4378
+ source;
4379
+ length;
4380
+ constructor(source, start, end) {
4381
+ this.start = start;
4382
+ this.end = end;
4383
+ this.source = source;
4384
+ this.length = end - start;
4385
+ }
4386
+ static from(source, start = 0, end = source.length) {
4387
+ check `
4388
+ ${start >= 0 && end <= source.length && start <= end}
4389
+ Invalid start (${start})/end (${end}) for ArrayView
4390
+ `;
4391
+ return new ArrayView(source, start, end);
4392
+ }
4393
+ get(i) {
4394
+ check `
4395
+ ${i >= 0 && i < this.length}
4396
+ Index out of bounds: ${i} < ${this.length}
4397
+ `;
4398
+ return this.source[this.start + i];
4399
+ }
4400
+ subview(from, to = this.length) {
4401
+ return ArrayView.from(this.source, this.start + from, this.start + to);
4402
+ }
4403
+ toArray() {
4404
+ return this.source.slice(this.start, this.end);
4405
+ }
4406
+ *[Symbol.iterator]() {
4407
+ for (let i = this.start; i < this.end; i++) {
4408
+ yield this.source[i];
4409
+ }
4410
+ }
4987
4411
  }
4988
4412
 
4989
- var keyDerivation = /*#__PURE__*/Object.freeze({
4990
- __proto__: null,
4991
- SEED_SIZE: SEED_SIZE,
4992
- deriveBandersnatchPublicKey: deriveBandersnatchPublicKey,
4993
- deriveBandersnatchSecretKey: deriveBandersnatchSecretKey,
4994
- deriveEd25519PublicKey: deriveEd25519PublicKey,
4995
- deriveEd25519SecretKey: deriveEd25519SecretKey,
4996
- trivialSeed: trivialSeed
4997
- });
4998
-
4999
- var index$o = /*#__PURE__*/Object.freeze({
5000
- __proto__: null,
5001
- BANDERSNATCH_KEY_BYTES: BANDERSNATCH_KEY_BYTES,
5002
- BANDERSNATCH_PROOF_BYTES: BANDERSNATCH_PROOF_BYTES,
5003
- BANDERSNATCH_RING_ROOT_BYTES: BANDERSNATCH_RING_ROOT_BYTES,
5004
- BANDERSNATCH_VRF_SIGNATURE_BYTES: BANDERSNATCH_VRF_SIGNATURE_BYTES,
5005
- BLS_KEY_BYTES: BLS_KEY_BYTES,
5006
- ED25519_KEY_BYTES: ED25519_KEY_BYTES,
5007
- ED25519_PRIV_KEY_BYTES: ED25519_PRIV_KEY_BYTES,
5008
- ED25519_SIGNATURE_BYTES: ED25519_SIGNATURE_BYTES,
5009
- Ed25519Pair: Ed25519Pair,
5010
- SEED_SIZE: SEED_SIZE,
5011
- bandersnatch: bandersnatch,
5012
- bandersnatchWasm: bandersnatch_exports,
5013
- ed25519: ed25519,
5014
- initWasm: initAll,
5015
- keyDerivation: keyDerivation
5016
- });
5017
-
5018
4413
  /** A map which uses hashes as keys. */
5019
4414
  class HashDictionary {
5020
4415
  // TODO [ToDr] [crit] We can't use `TrieHash` directly in the map,
@@ -5602,6 +4997,7 @@ class TruncatedHashDictionary {
5602
4997
 
5603
4998
  var index$n = /*#__PURE__*/Object.freeze({
5604
4999
  __proto__: null,
5000
+ ArrayView: ArrayView,
5605
5001
  FixedSizeArray: FixedSizeArray,
5606
5002
  HashDictionary: HashDictionary,
5607
5003
  HashSet: HashSet,
@@ -7290,6 +6686,17 @@ function emptyBlock(slot = tryAsTimeSlot(0)) {
7290
6686
  });
7291
6687
  }
7292
6688
 
6689
+ /**
6690
+ * Take an input data and re-encode that data as view.
6691
+ *
6692
+ * NOTE: this function should NEVER be used in any production code,
6693
+ * it's only a test helper.
6694
+ */
6695
+ function reencodeAsView(codec, object, chainSpec) {
6696
+ const encoded = Encoder.encodeObject(codec, object, chainSpec);
6697
+ return Decoder.decodeObject(codec.View, encoded, chainSpec);
6698
+ }
6699
+
7293
6700
  var index$l = /*#__PURE__*/Object.freeze({
7294
6701
  __proto__: null,
7295
6702
  Block: Block,
@@ -7310,6 +6717,7 @@ var index$l = /*#__PURE__*/Object.freeze({
7310
6717
  guarantees: guarantees,
7311
6718
  headerViewWithHashCodec: headerViewWithHashCodec,
7312
6719
  preimage: preimage,
6720
+ reencodeAsView: reencodeAsView,
7313
6721
  refineContext: refineContext,
7314
6722
  tickets: tickets,
7315
6723
  tryAsCoreIndex: tryAsCoreIndex,
@@ -7903,9 +7311,7 @@ var chain_spec$1 = {
7903
7311
  id: "typeberry-default",
7904
7312
  bootnodes: [
7905
7313
  "e3r2oc62zwfj3crnuifuvsxvbtlzetk4o5qyhetkhagsc2fgl2oka@127.0.0.1:40000",
7906
- "eecgwpgwq3noky4ijm4jmvjtmuzv44qvigciusxakq5epnrfj2utb@127.0.0.1:12345",
7907
- "en5ejs5b2tybkfh4ym5vpfh7nynby73xhtfzmazumtvcijpcsz6ma@127.0.0.1:12346",
7908
- "ekwmt37xecoq6a7otkm4ux5gfmm4uwbat4bg5m223shckhaaxdpqa@127.0.0.1:12347"
7314
+ "eyonydqt7gj7bjdek62lwdeuxdzr5q7nmxa2p5zwwtoijgamdnkka@127.0.0.1:12345"
7909
7315
  ],
7910
7316
  genesis_header: "0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001ee155ace9c40292074cb6aff8c9ccdd273c81648ff1149ef36bcea6ebb8a3e25bb30a42c1e62f0afda5f0a4e8a562f7a13a24cea00ee81917b86b89e801314aaff71c6c03ff88adb5ed52c9681de1629a54e702fc14729f6b50d2f0a76f185b34418fb8c85bb3985394a8c2756d3643457ce614546202a2f50b093d762499acedee6d555b82024f1ccf8a1e37e60fa60fd40b1958c4bb3006af78647950e1b91ad93247bd01307550ec7acd757ce6fb805fcf73db364063265b30a949e90d9339326edb21e5541717fde24ec085000b28709847b8aab1ac51f84e94b37ca1b66cab2b9ff25c2410fbe9b8a717abb298c716a03983c98ceb4def2087500b8e3410746846d17469fb2f95ef365efcab9f4e22fa1feb53111c995376be8019981ccf30aa5444688b3cab47697b37d5cac5707bb3289e986b19b17db437206931a8d151e5c8fe2b9d8a606966a79edd2f9e5db47e83947ce368ccba53bf6ba20a40b8b8c5d436f92ecf605421e873a99ec528761eb52a88a2f9a057b3b3003e6f32a2105650944fcd101621fd5bb3124c9fd191d114b7ad936c1d79d734f9f21392eab0084d01534b31c1dd87c81645fd762482a90027754041ca1b56133d0466c0600ffff00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000",
7911
7317
  genesis_state: {
@@ -7922,7 +7328,7 @@ var chain_spec$1 = {
7922
7328
  "0d000000000000000000000000000000000000000000000000000000000000": "0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000",
7923
7329
  "01000000000000000000000000000000000000000000000000000000000000": "080868db7f54e8b81d3a86438a8865eaf6b108b7992ae41dbc78f401b9acb5f9780868db7f54e8b81d3a86438a8865eaf6b108b7992ae41dbc78f401b9acb5f9780868db7f54e8b81d3a86438a8865eaf6b108b7992ae41dbc78f401b9acb5f9780868db7f54e8b81d3a86438a8865eaf6b108b7992ae41dbc78f401b9acb5f9780868db7f54e8b81d3a86438a8865eaf6b108b7992ae41dbc78f401b9acb5f9780868db7f54e8b81d3a86438a8865eaf6b108b7992ae41dbc78f401b9acb5f9780868db7f54e8b81d3a86438a8865eaf6b108b7992ae41dbc78f401b9acb5f9780868db7f54e8b81d3a86438a8865eaf6b108b7992ae41dbc78f401b9acb5f978080868db7f54e8b81d3a86438a8865eaf6b108b7992ae41dbc78f401b9acb5f9780868db7f54e8b81d3a86438a8865eaf6b108b7992ae41dbc78f401b9acb5f9780868db7f54e8b81d3a86438a8865eaf6b108b7992ae41dbc78f401b9acb5f9780868db7f54e8b81d3a86438a8865eaf6b108b7992ae41dbc78f401b9acb5f9780868db7f54e8b81d3a86438a8865eaf6b108b7992ae41dbc78f401b9acb5f9780868db7f54e8b81d3a86438a8865eaf6b108b7992ae41dbc78f401b9acb5f9780868db7f54e8b81d3a86438a8865eaf6b108b7992ae41dbc78f401b9acb5f9780868db7f54e8b81d3a86438a8865eaf6b108b7992ae41dbc78f401b9acb5f978",
7924
7330
  "10000000000000000000000000000000000000000000000000000000000000": "00",
7925
- "0c000000000000000000000000000000000000000000000000000000000000": "0000000000000000000000000000000000",
7331
+ "0c000000000000000000000000000000000000000000000000000000000000": "000000000000000000000000000000000000000000",
7926
7332
  "06000000000000000000000000000000000000000000000000000000000000": "03170a2e7597b7b7e3d84c05391d139a62b157e78786d8c082f29dcf4c111314ee155ace9c40292074cb6aff8c9ccdd273c81648ff1149ef36bcea6ebb8a3e25bb30a42c1e62f0afda5f0a4e8a562f7a13a24cea00ee81917b86b89e801314aae88bd757ad5b9bedf372d8d3f0cf6c962a469db61a265f6418e1ffed86da29ec",
7927
7333
  "0a000000000000000000000000000000000000000000000000000000000000": "0000",
7928
7334
  "03000000000000000000000000000000000000000000000000000000000000": "012bf11dc5e1c7b9bbaafc2c8533017abc12daeb0baf22c92509ad50f7875e5716000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000",
@@ -7951,9 +7357,7 @@ var authorship = {
7951
7357
  var chain_spec = {
7952
7358
  id: "typeberry-dev",
7953
7359
  bootnodes: [
7954
- "eecgwpgwq3noky4ijm4jmvjtmuzv44qvigciusxakq5epnrfj2utb@127.0.0.1:12345",
7955
- "en5ejs5b2tybkfh4ym5vpfh7nynby73xhtfzmazumtvcijpcsz6ma@127.0.0.1:12346",
7956
- "ekwmt37xecoq6a7otkm4ux5gfmm4uwbat4bg5m223shckhaaxdpqa@127.0.0.1:12347"
7360
+ "eyonydqt7gj7bjdek62lwdeuxdzr5q7nmxa2p5zwwtoijgamdnkka@127.0.0.1:12345"
7957
7361
  ],
7958
7362
  genesis_header: "0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001ee155ace9c40292074cb6aff8c9ccdd273c81648ff1149ef36bcea6ebb8a3e25bb30a42c1e62f0afda5f0a4e8a562f7a13a24cea00ee81917b86b89e801314aaff71c6c03ff88adb5ed52c9681de1629a54e702fc14729f6b50d2f0a76f185b34418fb8c85bb3985394a8c2756d3643457ce614546202a2f50b093d762499acedee6d555b82024f1ccf8a1e37e60fa60fd40b1958c4bb3006af78647950e1b91ad93247bd01307550ec7acd757ce6fb805fcf73db364063265b30a949e90d9339326edb21e5541717fde24ec085000b28709847b8aab1ac51f84e94b37ca1b66cab2b9ff25c2410fbe9b8a717abb298c716a03983c98ceb4def2087500b8e3410746846d17469fb2f95ef365efcab9f4e22fa1feb53111c995376be8019981ccf30aa5444688b3cab47697b37d5cac5707bb3289e986b19b17db437206931a8d151e5c8fe2b9d8a606966a79edd2f9e5db47e83947ce368ccba53bf6ba20a40b8b8c5d436f92ecf605421e873a99ec528761eb52a88a2f9a057b3b3003e6f32a2105650944fcd101621fd5bb3124c9fd191d114b7ad936c1d79d734f9f21392eab0084d01534b31c1dd87c81645fd762482a90027754041ca1b56133d0466c0600ffff00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000",
7959
7363
  genesis_state: {
@@ -7970,7 +7374,7 @@ var chain_spec = {
7970
7374
  "0d000000000000000000000000000000000000000000000000000000000000": "0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000",
7971
7375
  "01000000000000000000000000000000000000000000000000000000000000": "080868db7f54e8b81d3a86438a8865eaf6b108b7992ae41dbc78f401b9acb5f9780868db7f54e8b81d3a86438a8865eaf6b108b7992ae41dbc78f401b9acb5f9780868db7f54e8b81d3a86438a8865eaf6b108b7992ae41dbc78f401b9acb5f9780868db7f54e8b81d3a86438a8865eaf6b108b7992ae41dbc78f401b9acb5f9780868db7f54e8b81d3a86438a8865eaf6b108b7992ae41dbc78f401b9acb5f9780868db7f54e8b81d3a86438a8865eaf6b108b7992ae41dbc78f401b9acb5f9780868db7f54e8b81d3a86438a8865eaf6b108b7992ae41dbc78f401b9acb5f9780868db7f54e8b81d3a86438a8865eaf6b108b7992ae41dbc78f401b9acb5f978080868db7f54e8b81d3a86438a8865eaf6b108b7992ae41dbc78f401b9acb5f9780868db7f54e8b81d3a86438a8865eaf6b108b7992ae41dbc78f401b9acb5f9780868db7f54e8b81d3a86438a8865eaf6b108b7992ae41dbc78f401b9acb5f9780868db7f54e8b81d3a86438a8865eaf6b108b7992ae41dbc78f401b9acb5f9780868db7f54e8b81d3a86438a8865eaf6b108b7992ae41dbc78f401b9acb5f9780868db7f54e8b81d3a86438a8865eaf6b108b7992ae41dbc78f401b9acb5f9780868db7f54e8b81d3a86438a8865eaf6b108b7992ae41dbc78f401b9acb5f9780868db7f54e8b81d3a86438a8865eaf6b108b7992ae41dbc78f401b9acb5f978",
7972
7376
  "10000000000000000000000000000000000000000000000000000000000000": "00",
7973
- "0c000000000000000000000000000000000000000000000000000000000000": "0000000000000000000000000000000000",
7377
+ "0c000000000000000000000000000000000000000000000000000000000000": "000000000000000000000000000000000000000000",
7974
7378
  "06000000000000000000000000000000000000000000000000000000000000": "03170a2e7597b7b7e3d84c05391d139a62b157e78786d8c082f29dcf4c111314ee155ace9c40292074cb6aff8c9ccdd273c81648ff1149ef36bcea6ebb8a3e25bb30a42c1e62f0afda5f0a4e8a562f7a13a24cea00ee81917b86b89e801314aae88bd757ad5b9bedf372d8d3f0cf6c962a469db61a265f6418e1ffed86da29ec",
7975
7379
  "0a000000000000000000000000000000000000000000000000000000000000": "0000",
7976
7380
  "03000000000000000000000000000000000000000000000000000000000000": "012bf11dc5e1c7b9bbaafc2c8533017abc12daeb0baf22c92509ad50f7875e5716000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000",
@@ -8563,43 +7967,43 @@ var stateKeys;
8563
7967
  }
8564
7968
  stateKeys.serviceInfo = serviceInfo;
8565
7969
  /** https://graypaper.fluffylabs.dev/#/1c979cb/3bba033bba03?v=0.7.1 */
8566
- function serviceStorage(serviceId, key) {
7970
+ function serviceStorage(blake2b, serviceId, key) {
8567
7971
  if (Compatibility.isLessThan(GpVersion.V0_6_7)) {
8568
7972
  const out = Bytes.zero(HASH_SIZE);
8569
7973
  out.raw.set(u32AsLeBytes(tryAsU32(2 ** 32 - 1)), 0);
8570
7974
  out.raw.set(key.raw.subarray(0, HASH_SIZE - U32_BYTES), U32_BYTES);
8571
7975
  return legacyServiceNested(serviceId, out);
8572
7976
  }
8573
- return serviceNested(serviceId, tryAsU32(2 ** 32 - 1), key);
7977
+ return serviceNested(blake2b, serviceId, tryAsU32(2 ** 32 - 1), key);
8574
7978
  }
8575
7979
  stateKeys.serviceStorage = serviceStorage;
8576
7980
  /** https://graypaper.fluffylabs.dev/#/1c979cb/3bd7033bd703?v=0.7.1 */
8577
- function servicePreimage(serviceId, hash) {
7981
+ function servicePreimage(blake2b, serviceId, hash) {
8578
7982
  if (Compatibility.isLessThan(GpVersion.V0_6_7)) {
8579
7983
  const out = Bytes.zero(HASH_SIZE);
8580
7984
  out.raw.set(u32AsLeBytes(tryAsU32(2 ** 32 - 2)), 0);
8581
7985
  out.raw.set(hash.raw.subarray(1, HASH_SIZE - U32_BYTES + 1), U32_BYTES);
8582
7986
  return legacyServiceNested(serviceId, out);
8583
7987
  }
8584
- return serviceNested(serviceId, tryAsU32(2 ** 32 - 2), hash);
7988
+ return serviceNested(blake2b, serviceId, tryAsU32(2 ** 32 - 2), hash);
8585
7989
  }
8586
7990
  stateKeys.servicePreimage = servicePreimage;
8587
7991
  /** https://graypaper.fluffylabs.dev/#/1c979cb/3b0a043b0a04?v=0.7.1 */
8588
- function serviceLookupHistory(serviceId, hash, preimageLength) {
7992
+ function serviceLookupHistory(blake2b, serviceId, hash, preimageLength) {
8589
7993
  if (Compatibility.isLessThan(GpVersion.V0_6_7)) {
8590
- const doubleHash = hashBytes(hash);
7994
+ const doubleHash = blake2b.hashBytes(hash);
8591
7995
  const out = Bytes.zero(HASH_SIZE);
8592
7996
  out.raw.set(u32AsLeBytes(preimageLength), 0);
8593
7997
  out.raw.set(doubleHash.raw.subarray(2, HASH_SIZE - U32_BYTES + 2), U32_BYTES);
8594
7998
  return legacyServiceNested(serviceId, out);
8595
7999
  }
8596
- return serviceNested(serviceId, preimageLength, hash);
8000
+ return serviceNested(blake2b, serviceId, preimageLength, hash);
8597
8001
  }
8598
8002
  stateKeys.serviceLookupHistory = serviceLookupHistory;
8599
8003
  /** https://graypaper.fluffylabs.dev/#/1c979cb/3b88003b8800?v=0.7.1 */
8600
- function serviceNested(serviceId, numberPrefix, hash) {
8004
+ function serviceNested(blake2b, serviceId, numberPrefix, hash) {
8601
8005
  const inputToHash = BytesBlob.blobFromParts(u32AsLeBytes(numberPrefix), hash.raw);
8602
- const newHash = hashBytes(inputToHash).raw.subarray(0, 28);
8006
+ const newHash = blake2b.hashBytes(inputToHash).raw.subarray(0, 28);
8603
8007
  const key = Bytes.zero(HASH_SIZE);
8604
8008
  let i = 0;
8605
8009
  for (const byte of u32AsLeBytes(serviceId)) {
@@ -8660,12 +8064,72 @@ function accumulationOutputComparator(a, b) {
8660
8064
  return Ordering.Equal;
8661
8065
  }
8662
8066
 
8663
- const codecWithHash = (val) => Descriptor.withView(val.name, val.sizeHint, (e, elem) => val.encode(e, elem.data), (d) => {
8664
- const decoder2 = d.clone();
8665
- const encoded = val.skipEncoded(decoder2);
8666
- const hash = hashBytes(encoded);
8667
- return new WithHash(hash.asOpaque(), val.decode(d));
8668
- }, val.skip, val.View);
8067
+ /** `O`: Maximum number of items in the authorizations pool. */
8068
+ const O = 8;
8069
+ /** `Q`: The number of items in the authorizations queue. */
8070
+ const Q = 80;
8071
+ /** `W_B`: The maximum size of the concatenated variable-size blobs, extrinsics and imported segments of a work-package, in octets */
8072
+ Compatibility.isGreaterOrEqual(GpVersion.V0_7_2) ? 13_791_360 : 13_794_305;
8073
+ /** `W_T`: The size of a transfer memo in octets. */
8074
+ const W_T = 128;
8075
+ /**
8076
+ * `J`: The maximum sum of dependency items in a work-report.
8077
+ *
8078
+ * https://graypaper.fluffylabs.dev/#/5f542d7/416a00416a00?v=0.6.2
8079
+ */
8080
+ const MAX_REPORT_DEPENDENCIES = 8;
8081
+
8082
+ /**
8083
+ * Ready (i.e. available and/or audited) but not-yet-accumulated work-reports.
8084
+ *
8085
+ * https://graypaper.fluffylabs.dev/#/5f542d7/165300165400
8086
+ */
8087
+ class NotYetAccumulatedReport extends WithDebug {
8088
+ report;
8089
+ dependencies;
8090
+ static Codec = codec$1.Class(NotYetAccumulatedReport, {
8091
+ report: WorkReport.Codec,
8092
+ dependencies: codecKnownSizeArray(codec$1.bytes(HASH_SIZE).asOpaque(), {
8093
+ typicalLength: MAX_REPORT_DEPENDENCIES / 2,
8094
+ maxLength: MAX_REPORT_DEPENDENCIES,
8095
+ minLength: 0,
8096
+ }),
8097
+ });
8098
+ static create({ report, dependencies }) {
8099
+ return new NotYetAccumulatedReport(report, dependencies);
8100
+ }
8101
+ constructor(
8102
+ /**
8103
+ * Each of these were made available at most one epoch ago
8104
+ * but have or had unfulfilled dependencies.
8105
+ */
8106
+ report,
8107
+ /**
8108
+ * Alongside the work-report itself, we retain its un-accumulated
8109
+ * dependencies, a set of work-package hashes.
8110
+ *
8111
+ * https://graypaper.fluffylabs.dev/#/5f542d7/165800165800
8112
+ */
8113
+ dependencies) {
8114
+ super();
8115
+ this.report = report;
8116
+ this.dependencies = dependencies;
8117
+ }
8118
+ }
8119
+ const accumulationQueueCodec = codecPerEpochBlock(readonlyArray(codec$1.sequenceVarLen(NotYetAccumulatedReport.Codec)));
8120
+
8121
+ /** Check if given array has correct length before casting to the opaque type. */
8122
+ function tryAsPerCore(array, spec) {
8123
+ check `
8124
+ ${array.length === spec.coresCount}
8125
+ Invalid per-core array length. Expected ${spec.coresCount}, got: ${array.length}
8126
+ `;
8127
+ return asOpaqueType(array);
8128
+ }
8129
+ const codecPerCore = (val) => codecWithContext((context) => {
8130
+ return codecKnownSizeArray(val, { fixedLength: context.coresCount });
8131
+ });
8132
+
8669
8133
  /**
8670
8134
  * Assignment of particular work report to a core.
8671
8135
  *
@@ -8678,7 +8142,7 @@ class AvailabilityAssignment extends WithDebug {
8678
8142
  workReport;
8679
8143
  timeout;
8680
8144
  static Codec = codec$1.Class(AvailabilityAssignment, {
8681
- workReport: codecWithHash(WorkReport.Codec),
8145
+ workReport: WorkReport.Codec,
8682
8146
  timeout: codec$1.u32.asOpaque(),
8683
8147
  });
8684
8148
  static create({ workReport, timeout }) {
@@ -8694,19 +8158,19 @@ class AvailabilityAssignment extends WithDebug {
8694
8158
  this.timeout = timeout;
8695
8159
  }
8696
8160
  }
8161
+ const availabilityAssignmentsCodec = codecPerCore(codec$1.optional(AvailabilityAssignment.Codec));
8162
+
8163
+ /** `O`: Maximal authorization pool size. */
8164
+ const MAX_AUTH_POOL_SIZE = O;
8165
+ /** `Q`: Size of the authorization queue. */
8166
+ const AUTHORIZATION_QUEUE_SIZE = Q;
8167
+ const authPoolsCodec = codecPerCore(codecKnownSizeArray(codec$1.bytes(HASH_SIZE).asOpaque(), {
8168
+ minLength: 0,
8169
+ maxLength: MAX_AUTH_POOL_SIZE,
8170
+ typicalLength: MAX_AUTH_POOL_SIZE,
8171
+ }));
8172
+ const authQueuesCodec = codecPerCore(codecFixedSizeArray(codec$1.bytes(HASH_SIZE).asOpaque(), AUTHORIZATION_QUEUE_SIZE));
8697
8173
 
8698
- /** Check if given array has correct length before casting to the opaque type. */
8699
- function tryAsPerCore(array, spec) {
8700
- check `
8701
- ${array.length === spec.coresCount}
8702
- Invalid per-core array length. Expected ${spec.coresCount}, got: ${array.length}
8703
- `;
8704
- return asOpaqueType(array);
8705
- }
8706
- const codecPerCore = (val) => codecWithContext((context) => {
8707
- return codecKnownSizeArray(val, { fixedLength: context.coresCount });
8708
- });
8709
-
8710
8174
  const sortedSetCodec = () => readonlyArray(codec$1.sequenceVarLen(codec$1.bytes(HASH_SIZE))).convert((input) => input.array, (output) => {
8711
8175
  const typed = output.map((x) => x.asOpaque());
8712
8176
  return SortedSet.fromSortedArray(hashComparator, typed);
@@ -8731,6 +8195,10 @@ class DisputesRecords {
8731
8195
  static create({ goodSet, badSet, wonkySet, punishSet }) {
8732
8196
  return new DisputesRecords(goodSet, badSet, wonkySet, punishSet);
8733
8197
  }
8198
+ goodSetDict;
8199
+ badSetDict;
8200
+ wonkySetDict;
8201
+ punishSetDict;
8734
8202
  constructor(
8735
8203
  /** `goodSet`: all work-reports hashes which were judged to be correct */
8736
8204
  goodSet,
@@ -8744,6 +8212,18 @@ class DisputesRecords {
8744
8212
  this.badSet = badSet;
8745
8213
  this.wonkySet = wonkySet;
8746
8214
  this.punishSet = punishSet;
8215
+ this.goodSetDict = HashSet.from(goodSet.array);
8216
+ this.badSetDict = HashSet.from(badSet.array);
8217
+ this.wonkySetDict = HashSet.from(wonkySet.array);
8218
+ this.punishSetDict = HashSet.from(punishSet.array);
8219
+ }
8220
+ asDictionaries() {
8221
+ return {
8222
+ goodSet: this.goodSetDict,
8223
+ badSet: this.badSetDict,
8224
+ wonkySet: this.wonkySetDict,
8225
+ punishSet: this.punishSetDict,
8226
+ };
8747
8227
  }
8748
8228
  static fromSortedArrays({ goodSet, badSet, wonkySet, punishSet, }) {
8749
8229
  return new DisputesRecords(SortedSet.fromSortedArray(hashComparator, goodSet), SortedSet.fromSortedArray(hashComparator, badSet), SortedSet.fromSortedArray(hashComparator, wonkySet), SortedSet.fromSortedArray(hashComparator, punishSet));
@@ -8753,81 +8233,10 @@ function hashComparator(a, b) {
8753
8233
  return a.compare(b);
8754
8234
  }
8755
8235
 
8756
- /** `O`: Maximum number of items in the authorizations pool. */
8757
- const O = 8;
8758
- /** `Q`: The number of items in the authorizations queue. */
8759
- const Q = 80;
8760
- /** `W_T`: The size of a transfer memo in octets. */
8761
- const W_T = 128;
8762
- // TODO [ToDr] Not sure where these should live yet :(
8763
- /**
8764
- * `J`: The maximum sum of dependency items in a work-report.
8765
- *
8766
- * https://graypaper.fluffylabs.dev/#/5f542d7/416a00416a00?v=0.6.2
8767
- */
8768
- const MAX_REPORT_DEPENDENCIES = 8;
8769
- /** `Q`: Size of the authorization queue. */
8770
- const AUTHORIZATION_QUEUE_SIZE = Q;
8771
- /** `O`: Maximal authorization pool size. */
8772
- const MAX_AUTH_POOL_SIZE = O;
8773
-
8774
- /** Dictionary entry of services that auto-accumulate every block. */
8775
- class AutoAccumulate {
8776
- service;
8777
- gasLimit;
8778
- static Codec = codec$1.Class(AutoAccumulate, {
8779
- service: codec$1.u32.asOpaque(),
8780
- gasLimit: codec$1.u64.asOpaque(),
8781
- });
8782
- static create({ service, gasLimit }) {
8783
- return new AutoAccumulate(service, gasLimit);
8784
- }
8785
- constructor(
8786
- /** Service id that auto-accumulates. */
8787
- service,
8788
- /** Gas limit for auto-accumulation. */
8789
- gasLimit) {
8790
- this.service = service;
8791
- this.gasLimit = gasLimit;
8792
- }
8793
- }
8794
- /**
8795
- * https://graypaper.fluffylabs.dev/#/7e6ff6a/11da0111da01?v=0.6.7
8796
- */
8797
- class PrivilegedServices {
8798
- manager;
8799
- authManager;
8800
- validatorsManager;
8801
- autoAccumulateServices;
8802
- static Codec = codec$1.Class(PrivilegedServices, {
8803
- manager: codec$1.u32.asOpaque(),
8804
- authManager: codecPerCore(codec$1.u32.asOpaque()),
8805
- validatorsManager: codec$1.u32.asOpaque(),
8806
- autoAccumulateServices: readonlyArray(codec$1.sequenceVarLen(AutoAccumulate.Codec)),
8807
- });
8808
- static create({ manager, authManager, validatorsManager, autoAccumulateServices }) {
8809
- return new PrivilegedServices(manager, authManager, validatorsManager, autoAccumulateServices);
8810
- }
8811
- constructor(
8812
- /**
8813
- * `chi_m`: The first, χm, is the index of the manager service which is
8814
- * the service able to effect an alteration of χ from block to block,
8815
- * as well as bestow services with storage deposit credits.
8816
- * https://graypaper.fluffylabs.dev/#/7e6ff6a/11a40111a801?v=0.6.7
8817
- */
8818
- manager,
8819
- /** `chi_a`: Manages authorization queue one for each core. */
8820
- authManager,
8821
- /** `chi_v`: Managers validator keys. */
8822
- validatorsManager,
8823
- /** `chi_g`: Dictionary of services that auto-accumulate every block with their gas limit. */
8824
- autoAccumulateServices) {
8825
- this.manager = manager;
8826
- this.authManager = authManager;
8827
- this.validatorsManager = validatorsManager;
8828
- this.autoAccumulateServices = autoAccumulateServices;
8829
- }
8830
- }
8236
+ const MAX_VALUE = 4294967295;
8237
+ const MIN_VALUE = -2147483648;
8238
+ const MAX_SHIFT_U32 = 32;
8239
+ const MAX_SHIFT_U64 = 64n;
8831
8240
 
8832
8241
  /**
8833
8242
  * `H = 8`: The size of recent history, in blocks.
@@ -8866,6 +8275,11 @@ class BlockState extends WithDebug {
8866
8275
  this.reported = reported;
8867
8276
  }
8868
8277
  }
8278
+ /**
8279
+ * Recent history of blocks.
8280
+ *
8281
+ * https://graypaper.fluffylabs.dev/#/7e6ff6a/0fc9010fc901?v=0.6.7
8282
+ */
8869
8283
  class RecentBlocks extends WithDebug {
8870
8284
  blocks;
8871
8285
  accumulationLog;
@@ -8879,6 +8293,11 @@ class RecentBlocks extends WithDebug {
8879
8293
  peaks: readonlyArray(codec$1.sequenceVarLen(codec$1.optional(codec$1.bytes(HASH_SIZE)))),
8880
8294
  }),
8881
8295
  });
8296
+ static empty() {
8297
+ return new RecentBlocks(asKnownSize([]), {
8298
+ peaks: [],
8299
+ });
8300
+ }
8882
8301
  static create(a) {
8883
8302
  return new RecentBlocks(a.blocks, a.accumulationLog);
8884
8303
  }
@@ -8898,61 +8317,8 @@ class RecentBlocks extends WithDebug {
8898
8317
  this.accumulationLog = accumulationLog;
8899
8318
  }
8900
8319
  }
8901
- /**
8902
- * Recent history of blocks.
8903
- *
8904
- * https://graypaper.fluffylabs.dev/#/7e6ff6a/0fc9010fc901?v=0.6.7
8905
- */
8906
- class RecentBlocksHistory extends WithDebug {
8907
- current;
8908
- static Codec = Descriptor.new("RecentBlocksHistory", RecentBlocks.Codec.sizeHint, (encoder, value) => RecentBlocks.Codec.encode(encoder, value.asCurrent()), (decoder) => {
8909
- const recentBlocks = RecentBlocks.Codec.decode(decoder);
8910
- return RecentBlocksHistory.create(recentBlocks);
8911
- }, (skip) => {
8912
- return RecentBlocks.Codec.skip(skip);
8913
- });
8914
- static create(recentBlocks) {
8915
- return new RecentBlocksHistory(recentBlocks);
8916
- }
8917
- static empty() {
8918
- return RecentBlocksHistory.create(RecentBlocks.create({
8919
- blocks: asKnownSize([]),
8920
- accumulationLog: { peaks: [] },
8921
- }));
8922
- }
8923
- /**
8924
- * Returns the block's BEEFY super peak.
8925
- */
8926
- static accumulationResult(block) {
8927
- return block.accumulationResult;
8928
- }
8929
- constructor(current) {
8930
- super();
8931
- this.current = current;
8932
- }
8933
- /** History of recent blocks with maximum size of `MAX_RECENT_HISTORY` */
8934
- get blocks() {
8935
- if (this.current !== null) {
8936
- return this.current.blocks;
8937
- }
8938
- throw new Error("RecentBlocksHistory is in invalid state");
8939
- }
8940
- asCurrent() {
8941
- if (this.current === null) {
8942
- throw new Error("Cannot access current RecentBlocks format");
8943
- }
8944
- return this.current;
8945
- }
8946
- updateBlocks(blocks) {
8947
- if (this.current !== null) {
8948
- return RecentBlocksHistory.create(RecentBlocks.create({
8949
- ...this.current,
8950
- blocks: asOpaqueType(blocks),
8951
- }));
8952
- }
8953
- throw new Error("RecentBlocksHistory is in invalid state. Cannot be updated!");
8954
- }
8955
- }
8320
+
8321
+ const recentlyAccumulatedCodec = codecPerEpochBlock(codec$1.sequenceVarLen(codec$1.bytes(HASH_SIZE).asOpaque()).convert((x) => Array.from(x), (x) => HashSet.from(x)));
8956
8322
 
8957
8323
  /**
8958
8324
  * Fixed size of validator metadata.
@@ -8995,6 +8361,7 @@ class ValidatorData extends WithDebug {
8995
8361
  this.metadata = metadata;
8996
8362
  }
8997
8363
  }
8364
+ const validatorsDataCodec = codecPerValidator(ValidatorData.Codec);
8998
8365
 
8999
8366
  var SafroleSealingKeysKind;
9000
8367
  (function (SafroleSealingKeysKind) {
@@ -9110,6 +8477,23 @@ const zeroSizeHint = {
9110
8477
  };
9111
8478
  /** 0-byte read, return given default value */
9112
8479
  const ignoreValueWithDefault = (defaultValue) => Descriptor.new("ignoreValue", zeroSizeHint, (_e, _v) => { }, (_d) => defaultValue, (_s) => { });
8480
+ /** Encode and decode object with leading version number. */
8481
+ const codecWithVersion = (val) => Descriptor.new("withVersion", {
8482
+ bytes: val.sizeHint.bytes + 8,
8483
+ isExact: false,
8484
+ }, (e, v) => {
8485
+ e.varU64(0n);
8486
+ val.encode(e, v);
8487
+ }, (d) => {
8488
+ const version = d.varU64();
8489
+ if (version !== 0n) {
8490
+ throw new Error("Non-zero version is not supported!");
8491
+ }
8492
+ return val.decode(d);
8493
+ }, (s) => {
8494
+ s.varU64();
8495
+ val.skip(s);
8496
+ });
9113
8497
  /**
9114
8498
  * Service account details.
9115
8499
  *
@@ -9252,163 +8636,6 @@ class LookupHistoryItem {
9252
8636
  }
9253
8637
  }
9254
8638
 
9255
- /**
9256
- * In addition to the entropy accumulator η_0, we retain
9257
- * three additional historical values of the accumulator at
9258
- * the point of each of the three most recently ended epochs,
9259
- * η_1, η_2 and η_3. The second-oldest of these η2 is utilized to
9260
- * help ensure future entropy is unbiased (see equation 6.29)
9261
- * and seed the fallback seal-key generation function with
9262
- * randomness (see equation 6.24). The oldest is used to re-
9263
- * generate this randomness when verifying the seal above
9264
- * (see equations 6.16 and 6.15).
9265
- *
9266
- * https://graypaper.fluffylabs.dev/#/579bd12/0ef5010ef501
9267
- */
9268
- const ENTROPY_ENTRIES = 4;
9269
-
9270
- var UpdatePreimageKind;
9271
- (function (UpdatePreimageKind) {
9272
- /** Insert new preimage and optionally update it's lookup history. */
9273
- UpdatePreimageKind[UpdatePreimageKind["Provide"] = 0] = "Provide";
9274
- /** Remove a preimage and it's lookup history. */
9275
- UpdatePreimageKind[UpdatePreimageKind["Remove"] = 1] = "Remove";
9276
- /** update or add lookup history for preimage hash/len to given value. */
9277
- UpdatePreimageKind[UpdatePreimageKind["UpdateOrAdd"] = 2] = "UpdateOrAdd";
9278
- })(UpdatePreimageKind || (UpdatePreimageKind = {}));
9279
- /**
9280
- * A preimage update.
9281
- *
9282
- * Can be one of the following cases:
9283
- * 1. Provide a new preimage blob and set the lookup history to available at `slot`.
9284
- * 2. Remove (expunge) a preimage and it's lookup history.
9285
- * 3. Update `LookupHistory` with given value.
9286
- */
9287
- class UpdatePreimage {
9288
- serviceId;
9289
- action;
9290
- constructor(serviceId, action) {
9291
- this.serviceId = serviceId;
9292
- this.action = action;
9293
- }
9294
- /** A preimage is provided. We should update the lookuphistory and add the preimage to db. */
9295
- static provide({ serviceId, preimage, slot, }) {
9296
- return new UpdatePreimage(serviceId, {
9297
- kind: UpdatePreimageKind.Provide,
9298
- preimage,
9299
- slot,
9300
- });
9301
- }
9302
- /** The preimage should be removed completely from the database. */
9303
- static remove({ serviceId, hash, length }) {
9304
- return new UpdatePreimage(serviceId, {
9305
- kind: UpdatePreimageKind.Remove,
9306
- hash,
9307
- length,
9308
- });
9309
- }
9310
- /** Update the lookup history of some preimage or add a new one (request). */
9311
- static updateOrAdd({ serviceId, lookupHistory }) {
9312
- return new UpdatePreimage(serviceId, {
9313
- kind: UpdatePreimageKind.UpdateOrAdd,
9314
- item: lookupHistory,
9315
- });
9316
- }
9317
- get hash() {
9318
- switch (this.action.kind) {
9319
- case UpdatePreimageKind.Provide:
9320
- return this.action.preimage.hash;
9321
- case UpdatePreimageKind.Remove:
9322
- return this.action.hash;
9323
- case UpdatePreimageKind.UpdateOrAdd:
9324
- return this.action.item.hash;
9325
- }
9326
- throw assertNever(this.action);
9327
- }
9328
- get length() {
9329
- switch (this.action.kind) {
9330
- case UpdatePreimageKind.Provide:
9331
- return tryAsU32(this.action.preimage.blob.length);
9332
- case UpdatePreimageKind.Remove:
9333
- return this.action.length;
9334
- case UpdatePreimageKind.UpdateOrAdd:
9335
- return this.action.item.length;
9336
- }
9337
- throw assertNever(this.action);
9338
- }
9339
- }
9340
- /** The type of service update. */
9341
- var UpdateServiceKind;
9342
- (function (UpdateServiceKind) {
9343
- /** Just update the `ServiceAccountInfo`. */
9344
- UpdateServiceKind[UpdateServiceKind["Update"] = 0] = "Update";
9345
- /** Create a new `Service` instance. */
9346
- UpdateServiceKind[UpdateServiceKind["Create"] = 1] = "Create";
9347
- })(UpdateServiceKind || (UpdateServiceKind = {}));
9348
- /**
9349
- * Update service info of a particular `ServiceId` or create a new one.
9350
- */
9351
- class UpdateService {
9352
- serviceId;
9353
- action;
9354
- constructor(serviceId, action) {
9355
- this.serviceId = serviceId;
9356
- this.action = action;
9357
- }
9358
- static update({ serviceId, serviceInfo }) {
9359
- return new UpdateService(serviceId, {
9360
- kind: UpdateServiceKind.Update,
9361
- account: serviceInfo,
9362
- });
9363
- }
9364
- static create({ serviceId, serviceInfo, lookupHistory, }) {
9365
- return new UpdateService(serviceId, {
9366
- kind: UpdateServiceKind.Create,
9367
- account: serviceInfo,
9368
- lookupHistory,
9369
- });
9370
- }
9371
- }
9372
- /** Update service storage kind. */
9373
- var UpdateStorageKind;
9374
- (function (UpdateStorageKind) {
9375
- /** Set a storage value. */
9376
- UpdateStorageKind[UpdateStorageKind["Set"] = 0] = "Set";
9377
- /** Remove a storage value. */
9378
- UpdateStorageKind[UpdateStorageKind["Remove"] = 1] = "Remove";
9379
- })(UpdateStorageKind || (UpdateStorageKind = {}));
9380
- /**
9381
- * Update service storage item.
9382
- *
9383
- * Can either create/modify an entry or remove it.
9384
- */
9385
- class UpdateStorage {
9386
- serviceId;
9387
- action;
9388
- constructor(serviceId, action) {
9389
- this.serviceId = serviceId;
9390
- this.action = action;
9391
- }
9392
- static set({ serviceId, storage }) {
9393
- return new UpdateStorage(serviceId, { kind: UpdateStorageKind.Set, storage });
9394
- }
9395
- static remove({ serviceId, key }) {
9396
- return new UpdateStorage(serviceId, { kind: UpdateStorageKind.Remove, key });
9397
- }
9398
- get key() {
9399
- if (this.action.kind === UpdateStorageKind.Remove) {
9400
- return this.action.key;
9401
- }
9402
- return this.action.storage.key;
9403
- }
9404
- get value() {
9405
- if (this.action.kind === UpdateStorageKind.Remove) {
9406
- return null;
9407
- }
9408
- return this.action.storage.value;
9409
- }
9410
- }
9411
-
9412
8639
  const codecServiceId = Compatibility.isSuite(TestSuite.W3F_DAVXY) || Compatibility.isSuite(TestSuite.JAMDUNA, GpVersion.V0_6_7)
9413
8640
  ? codec$1.u32.asOpaque()
9414
8641
  : codec$1.varU32.convert((s) => tryAsU32(s), (i) => tryAsServiceId(i));
@@ -9540,8 +8767,7 @@ class CoreStatistics {
9540
8767
  * Service statistics.
9541
8768
  * Updated per block, based on available work reports (`W`).
9542
8769
  *
9543
- * https://graypaper.fluffylabs.dev/#/68eaa1f/185104185104?v=0.6.4
9544
- * https://github.com/gavofyork/graypaper/blob/9bffb08f3ea7b67832019176754df4fb36b9557d/text/statistics.tex#L77
8770
+ * https://graypaper.fluffylabs.dev/#/1c979cb/199802199802?v=0.7.1
9545
8771
  */
9546
8772
  class ServiceStatistics {
9547
8773
  providedCount;
@@ -9556,22 +8782,8 @@ class ServiceStatistics {
9556
8782
  accumulateGasUsed;
9557
8783
  onTransfersCount;
9558
8784
  onTransfersGasUsed;
9559
- static Codec = Compatibility.isGreaterOrEqual(GpVersion.V0_7_0)
9560
- ? codec$1.Class(ServiceStatistics, {
9561
- providedCount: codecVarU16,
9562
- providedSize: codec$1.varU32,
9563
- refinementCount: codec$1.varU32,
9564
- refinementGasUsed: codecVarGas,
9565
- imports: codecVarU16,
9566
- extrinsicCount: codecVarU16,
9567
- extrinsicSize: codec$1.varU32,
9568
- exports: codecVarU16,
9569
- accumulateCount: codec$1.varU32,
9570
- accumulateGasUsed: codecVarGas,
9571
- onTransfersCount: codec$1.varU32,
9572
- onTransfersGasUsed: codecVarGas,
9573
- })
9574
- : codec$1.Class(ServiceStatistics, {
8785
+ static Codec = Compatibility.selectIfGreaterOrEqual({
8786
+ fallback: codec$1.Class(ServiceStatistics, {
9575
8787
  providedCount: codecVarU16,
9576
8788
  providedSize: codec$1.varU32,
9577
8789
  refinementCount: codec$1.varU32,
@@ -9584,7 +8796,38 @@ class ServiceStatistics {
9584
8796
  accumulateGasUsed: codecVarGas,
9585
8797
  onTransfersCount: codec$1.varU32,
9586
8798
  onTransfersGasUsed: codecVarGas,
9587
- });
8799
+ }),
8800
+ versions: {
8801
+ [GpVersion.V0_7_0]: codec$1.Class(ServiceStatistics, {
8802
+ providedCount: codecVarU16,
8803
+ providedSize: codec$1.varU32,
8804
+ refinementCount: codec$1.varU32,
8805
+ refinementGasUsed: codecVarGas,
8806
+ imports: codecVarU16,
8807
+ extrinsicCount: codecVarU16,
8808
+ extrinsicSize: codec$1.varU32,
8809
+ exports: codecVarU16,
8810
+ accumulateCount: codec$1.varU32,
8811
+ accumulateGasUsed: codecVarGas,
8812
+ onTransfersCount: codec$1.varU32,
8813
+ onTransfersGasUsed: codecVarGas,
8814
+ }),
8815
+ [GpVersion.V0_7_1]: codec$1.Class(ServiceStatistics, {
8816
+ providedCount: codecVarU16,
8817
+ providedSize: codec$1.varU32,
8818
+ refinementCount: codec$1.varU32,
8819
+ refinementGasUsed: codecVarGas,
8820
+ imports: codecVarU16,
8821
+ extrinsicCount: codecVarU16,
8822
+ extrinsicSize: codec$1.varU32,
8823
+ exports: codecVarU16,
8824
+ accumulateCount: codec$1.varU32,
8825
+ accumulateGasUsed: codecVarGas,
8826
+ onTransfersCount: ignoreValueWithDefault(tryAsU32(0)),
8827
+ onTransfersGasUsed: ignoreValueWithDefault(tryAsServiceGas(0)),
8828
+ }),
8829
+ },
8830
+ });
9588
8831
  static create(v) {
9589
8832
  return new ServiceStatistics(v.providedCount, v.providedSize, v.refinementCount, v.refinementGasUsed, v.imports, v.exports, v.extrinsicSize, v.extrinsicCount, v.accumulateCount, v.accumulateGasUsed, v.onTransfersCount, v.onTransfersGasUsed);
9590
8833
  }
@@ -9609,9 +8852,9 @@ class ServiceStatistics {
9609
8852
  accumulateCount,
9610
8853
  /** `a.1` */
9611
8854
  accumulateGasUsed,
9612
- /** `t.0` */
8855
+ /** `t.0` @deprecated since 0.7.1 */
9613
8856
  onTransfersCount,
9614
- /** `t.1` */
8857
+ /** `t.1` @deprecated since 0.7.1 */
9615
8858
  onTransfersGasUsed) {
9616
8859
  this.providedCount = providedCount;
9617
8860
  this.providedSize = providedSize;
@@ -9632,29 +8875,306 @@ class ServiceStatistics {
9632
8875
  const zeroGas = tryAsServiceGas(0);
9633
8876
  return new ServiceStatistics(zero16, zero, zero, zeroGas, zero16, zero16, zero, zero16, zero, zeroGas, zero, zeroGas);
9634
8877
  }
9635
- }
9636
- /** `pi`: Statistics of each validator, cores statistics and services statistics. */
9637
- class StatisticsData {
9638
- current;
9639
- previous;
9640
- cores;
9641
- services;
9642
- static Codec = codec$1.Class(StatisticsData, {
9643
- current: codecPerValidator(ValidatorStatistics.Codec),
9644
- previous: codecPerValidator(ValidatorStatistics.Codec),
9645
- cores: codecPerCore(CoreStatistics.Codec),
9646
- services: codec$1.dictionary(codecServiceId, ServiceStatistics.Codec, {
9647
- sortKeys: (a, b) => a - b,
9648
- }),
9649
- });
9650
- static create(v) {
9651
- return new StatisticsData(v.current, v.previous, v.cores, v.services);
8878
+ }
8879
+ /** `pi`: Statistics of each validator, cores statistics and services statistics. */
8880
+ class StatisticsData {
8881
+ current;
8882
+ previous;
8883
+ cores;
8884
+ services;
8885
+ static Codec = codec$1.Class(StatisticsData, {
8886
+ current: codecPerValidator(ValidatorStatistics.Codec),
8887
+ previous: codecPerValidator(ValidatorStatistics.Codec),
8888
+ cores: codecPerCore(CoreStatistics.Codec),
8889
+ services: codec$1.dictionary(codecServiceId, ServiceStatistics.Codec, {
8890
+ sortKeys: (a, b) => a - b,
8891
+ }),
8892
+ });
8893
+ static create(v) {
8894
+ return new StatisticsData(v.current, v.previous, v.cores, v.services);
8895
+ }
8896
+ constructor(current, previous, cores, services) {
8897
+ this.current = current;
8898
+ this.previous = previous;
8899
+ this.cores = cores;
8900
+ this.services = services;
8901
+ }
8902
+ }
8903
+
8904
+ class InMemoryStateView {
8905
+ chainSpec;
8906
+ state;
8907
+ constructor(chainSpec, state) {
8908
+ this.chainSpec = chainSpec;
8909
+ this.state = state;
8910
+ }
8911
+ availabilityAssignmentView() {
8912
+ return reencodeAsView(availabilityAssignmentsCodec, this.state.availabilityAssignment, this.chainSpec);
8913
+ }
8914
+ designatedValidatorDataView() {
8915
+ return reencodeAsView(validatorsDataCodec, this.state.designatedValidatorData, this.chainSpec);
8916
+ }
8917
+ currentValidatorDataView() {
8918
+ return reencodeAsView(validatorsDataCodec, this.state.currentValidatorData, this.chainSpec);
8919
+ }
8920
+ previousValidatorDataView() {
8921
+ return reencodeAsView(validatorsDataCodec, this.state.previousValidatorData, this.chainSpec);
8922
+ }
8923
+ authPoolsView() {
8924
+ return reencodeAsView(authPoolsCodec, this.state.authPools, this.chainSpec);
8925
+ }
8926
+ authQueuesView() {
8927
+ return reencodeAsView(authQueuesCodec, this.state.authQueues, this.chainSpec);
8928
+ }
8929
+ recentBlocksView() {
8930
+ return reencodeAsView(RecentBlocks.Codec, this.state.recentBlocks, this.chainSpec);
8931
+ }
8932
+ statisticsView() {
8933
+ return reencodeAsView(StatisticsData.Codec, this.state.statistics, this.chainSpec);
8934
+ }
8935
+ accumulationQueueView() {
8936
+ return reencodeAsView(accumulationQueueCodec, this.state.accumulationQueue, this.chainSpec);
8937
+ }
8938
+ recentlyAccumulatedView() {
8939
+ return reencodeAsView(recentlyAccumulatedCodec, this.state.recentlyAccumulated, this.chainSpec);
8940
+ }
8941
+ safroleDataView() {
8942
+ // TODO [ToDr] Consider exposting `safrole` from state
8943
+ // instead of individual fields
8944
+ const safrole = SafroleData.create({
8945
+ nextValidatorData: this.state.nextValidatorData,
8946
+ epochRoot: this.state.epochRoot,
8947
+ sealingKeySeries: this.state.sealingKeySeries,
8948
+ ticketsAccumulator: this.state.ticketsAccumulator,
8949
+ });
8950
+ return reencodeAsView(SafroleData.Codec, safrole, this.chainSpec);
8951
+ }
8952
+ getServiceInfoView(id) {
8953
+ const service = this.state.getService(id);
8954
+ if (service === null) {
8955
+ return null;
8956
+ }
8957
+ return reencodeAsView(ServiceAccountInfo.Codec, service.getInfo(), this.chainSpec);
8958
+ }
8959
+ }
8960
+
8961
+ /** Dictionary entry of services that auto-accumulate every block. */
8962
+ class AutoAccumulate {
8963
+ service;
8964
+ gasLimit;
8965
+ static Codec = codec$1.Class(AutoAccumulate, {
8966
+ service: codec$1.u32.asOpaque(),
8967
+ gasLimit: codec$1.u64.asOpaque(),
8968
+ });
8969
+ static create({ service, gasLimit }) {
8970
+ return new AutoAccumulate(service, gasLimit);
8971
+ }
8972
+ constructor(
8973
+ /** Service id that auto-accumulates. */
8974
+ service,
8975
+ /** Gas limit for auto-accumulation. */
8976
+ gasLimit) {
8977
+ this.service = service;
8978
+ this.gasLimit = gasLimit;
8979
+ }
8980
+ }
8981
+ /**
8982
+ * https://graypaper.fluffylabs.dev/#/ab2cdbd/114402114402?v=0.7.2
8983
+ */
8984
+ class PrivilegedServices {
8985
+ manager;
8986
+ delegator;
8987
+ registrar;
8988
+ assigners;
8989
+ autoAccumulateServices;
8990
+ /** https://graypaper.fluffylabs.dev/#/ab2cdbd/3bbd023bcb02?v=0.7.2 */
8991
+ static Codec = codec$1.Class(PrivilegedServices, {
8992
+ manager: codec$1.u32.asOpaque(),
8993
+ assigners: codecPerCore(codec$1.u32.asOpaque()),
8994
+ delegator: codec$1.u32.asOpaque(),
8995
+ registrar: Compatibility.isGreaterOrEqual(GpVersion.V0_7_1)
8996
+ ? codec$1.u32.asOpaque()
8997
+ : ignoreValueWithDefault(tryAsServiceId(2 ** 32 - 1)),
8998
+ autoAccumulateServices: readonlyArray(codec$1.sequenceVarLen(AutoAccumulate.Codec)),
8999
+ });
9000
+ static create(a) {
9001
+ return new PrivilegedServices(a.manager, a.delegator, a.registrar, a.assigners, a.autoAccumulateServices);
9002
+ }
9003
+ constructor(
9004
+ /**
9005
+ * `χ_M`: Manages alteration of χ from block to block,
9006
+ * as well as bestow services with storage deposit credits.
9007
+ * https://graypaper.fluffylabs.dev/#/ab2cdbd/111502111902?v=0.7.2
9008
+ */
9009
+ manager,
9010
+ /** `χ_V`: Managers validator keys. */
9011
+ delegator,
9012
+ /**
9013
+ * `χ_R`: Manages the creation of services in protected range.
9014
+ *
9015
+ * https://graypaper.fluffylabs.dev/#/ab2cdbd/111b02111d02?v=0.7.2
9016
+ */
9017
+ registrar,
9018
+ /** `χ_A`: Manages authorization queue one for each core. */
9019
+ assigners,
9020
+ /** `χ_Z`: Dictionary of services that auto-accumulate every block with their gas limit. */
9021
+ autoAccumulateServices) {
9022
+ this.manager = manager;
9023
+ this.delegator = delegator;
9024
+ this.registrar = registrar;
9025
+ this.assigners = assigners;
9026
+ this.autoAccumulateServices = autoAccumulateServices;
9027
+ }
9028
+ }
9029
+
9030
+ /**
9031
+ * In addition to the entropy accumulator η_0, we retain
9032
+ * three additional historical values of the accumulator at
9033
+ * the point of each of the three most recently ended epochs,
9034
+ * η_1, η_2 and η_3. The second-oldest of these η2 is utilized to
9035
+ * help ensure future entropy is unbiased (see equation 6.29)
9036
+ * and seed the fallback seal-key generation function with
9037
+ * randomness (see equation 6.24). The oldest is used to re-
9038
+ * generate this randomness when verifying the seal above
9039
+ * (see equations 6.16 and 6.15).
9040
+ *
9041
+ * https://graypaper.fluffylabs.dev/#/579bd12/0ef5010ef501
9042
+ */
9043
+ const ENTROPY_ENTRIES = 4;
9044
+
9045
+ var UpdatePreimageKind;
9046
+ (function (UpdatePreimageKind) {
9047
+ /** Insert new preimage and optionally update it's lookup history. */
9048
+ UpdatePreimageKind[UpdatePreimageKind["Provide"] = 0] = "Provide";
9049
+ /** Remove a preimage and it's lookup history. */
9050
+ UpdatePreimageKind[UpdatePreimageKind["Remove"] = 1] = "Remove";
9051
+ /** update or add lookup history for preimage hash/len to given value. */
9052
+ UpdatePreimageKind[UpdatePreimageKind["UpdateOrAdd"] = 2] = "UpdateOrAdd";
9053
+ })(UpdatePreimageKind || (UpdatePreimageKind = {}));
9054
+ /**
9055
+ * A preimage update.
9056
+ *
9057
+ * Can be one of the following cases:
9058
+ * 1. Provide a new preimage blob and set the lookup history to available at `slot`.
9059
+ * 2. Remove (expunge) a preimage and it's lookup history.
9060
+ * 3. Update `LookupHistory` with given value.
9061
+ */
9062
+ class UpdatePreimage {
9063
+ action;
9064
+ constructor(action) {
9065
+ this.action = action;
9066
+ }
9067
+ /** A preimage is provided. We should update the lookuphistory and add the preimage to db. */
9068
+ static provide({ preimage, slot }) {
9069
+ return new UpdatePreimage({
9070
+ kind: UpdatePreimageKind.Provide,
9071
+ preimage,
9072
+ slot,
9073
+ });
9074
+ }
9075
+ /** The preimage should be removed completely from the database. */
9076
+ static remove({ hash, length }) {
9077
+ return new UpdatePreimage({
9078
+ kind: UpdatePreimageKind.Remove,
9079
+ hash,
9080
+ length,
9081
+ });
9082
+ }
9083
+ /** Update the lookup history of some preimage or add a new one (request). */
9084
+ static updateOrAdd({ lookupHistory }) {
9085
+ return new UpdatePreimage({
9086
+ kind: UpdatePreimageKind.UpdateOrAdd,
9087
+ item: lookupHistory,
9088
+ });
9089
+ }
9090
+ get hash() {
9091
+ switch (this.action.kind) {
9092
+ case UpdatePreimageKind.Provide:
9093
+ return this.action.preimage.hash;
9094
+ case UpdatePreimageKind.Remove:
9095
+ return this.action.hash;
9096
+ case UpdatePreimageKind.UpdateOrAdd:
9097
+ return this.action.item.hash;
9098
+ }
9099
+ throw assertNever(this.action);
9100
+ }
9101
+ get length() {
9102
+ switch (this.action.kind) {
9103
+ case UpdatePreimageKind.Provide:
9104
+ return tryAsU32(this.action.preimage.blob.length);
9105
+ case UpdatePreimageKind.Remove:
9106
+ return this.action.length;
9107
+ case UpdatePreimageKind.UpdateOrAdd:
9108
+ return this.action.item.length;
9109
+ }
9110
+ throw assertNever(this.action);
9111
+ }
9112
+ }
9113
+ /** The type of service update. */
9114
+ var UpdateServiceKind;
9115
+ (function (UpdateServiceKind) {
9116
+ /** Just update the `ServiceAccountInfo`. */
9117
+ UpdateServiceKind[UpdateServiceKind["Update"] = 0] = "Update";
9118
+ /** Create a new `Service` instance. */
9119
+ UpdateServiceKind[UpdateServiceKind["Create"] = 1] = "Create";
9120
+ })(UpdateServiceKind || (UpdateServiceKind = {}));
9121
+ /**
9122
+ * Update service info or create a new one.
9123
+ */
9124
+ class UpdateService {
9125
+ action;
9126
+ constructor(action) {
9127
+ this.action = action;
9128
+ }
9129
+ static update({ serviceInfo }) {
9130
+ return new UpdateService({
9131
+ kind: UpdateServiceKind.Update,
9132
+ account: serviceInfo,
9133
+ });
9134
+ }
9135
+ static create({ serviceInfo, lookupHistory, }) {
9136
+ return new UpdateService({
9137
+ kind: UpdateServiceKind.Create,
9138
+ account: serviceInfo,
9139
+ lookupHistory,
9140
+ });
9141
+ }
9142
+ }
9143
+ /** Update service storage kind. */
9144
+ var UpdateStorageKind;
9145
+ (function (UpdateStorageKind) {
9146
+ /** Set a storage value. */
9147
+ UpdateStorageKind[UpdateStorageKind["Set"] = 0] = "Set";
9148
+ /** Remove a storage value. */
9149
+ UpdateStorageKind[UpdateStorageKind["Remove"] = 1] = "Remove";
9150
+ })(UpdateStorageKind || (UpdateStorageKind = {}));
9151
+ /**
9152
+ * Update service storage item.
9153
+ *
9154
+ * Can either create/modify an entry or remove it.
9155
+ */
9156
+ class UpdateStorage {
9157
+ action;
9158
+ constructor(action) {
9159
+ this.action = action;
9160
+ }
9161
+ static set({ storage }) {
9162
+ return new UpdateStorage({ kind: UpdateStorageKind.Set, storage });
9652
9163
  }
9653
- constructor(current, previous, cores, services) {
9654
- this.current = current;
9655
- this.previous = previous;
9656
- this.cores = cores;
9657
- this.services = services;
9164
+ static remove({ key }) {
9165
+ return new UpdateStorage({ kind: UpdateStorageKind.Remove, key });
9166
+ }
9167
+ get key() {
9168
+ if (this.action.kind === UpdateStorageKind.Remove) {
9169
+ return this.action.key;
9170
+ }
9171
+ return this.action.storage.key;
9172
+ }
9173
+ get value() {
9174
+ if (this.action.kind === UpdateStorageKind.Remove) {
9175
+ return null;
9176
+ }
9177
+ return this.action.storage.value;
9658
9178
  }
9659
9179
  }
9660
9180
 
@@ -9757,9 +9277,10 @@ class InMemoryService extends WithDebug {
9757
9277
  * A special version of state, stored fully in-memory.
9758
9278
  */
9759
9279
  class InMemoryState extends WithDebug {
9280
+ chainSpec;
9760
9281
  /** Create a new `InMemoryState` by providing all required fields. */
9761
- static create(state) {
9762
- return new InMemoryState(state);
9282
+ static new(chainSpec, state) {
9283
+ return new InMemoryState(chainSpec, state);
9763
9284
  }
9764
9285
  /**
9765
9286
  * Create a new `InMemoryState` with a partial state override.
@@ -9775,7 +9296,7 @@ class InMemoryState extends WithDebug {
9775
9296
  /**
9776
9297
  * Create a new `InMemoryState` from some other state object.
9777
9298
  */
9778
- static copyFrom(other, servicesData) {
9299
+ static copyFrom(chainSpec, other, servicesData) {
9779
9300
  const services = new Map();
9780
9301
  for (const [id, entries] of servicesData.entries()) {
9781
9302
  const service = other.getService(id);
@@ -9785,7 +9306,7 @@ class InMemoryState extends WithDebug {
9785
9306
  const inMemService = InMemoryService.copyFrom(service, entries);
9786
9307
  services.set(id, inMemService);
9787
9308
  }
9788
- return InMemoryState.create({
9309
+ return InMemoryState.new(chainSpec, {
9789
9310
  availabilityAssignment: other.availabilityAssignment,
9790
9311
  accumulationQueue: other.accumulationQueue,
9791
9312
  designatedValidatorData: other.designatedValidatorData,
@@ -9826,12 +9347,12 @@ class InMemoryState extends WithDebug {
9826
9347
  * Modify the state and apply a single state update.
9827
9348
  */
9828
9349
  applyUpdate(update) {
9829
- const { servicesRemoved, servicesUpdates, preimages, storage, ...rest } = update;
9350
+ const { removed, created: _, updated, preimages, storage, ...rest } = update;
9830
9351
  // just assign all other variables
9831
9352
  Object.assign(this, rest);
9832
9353
  // and update the services state
9833
9354
  let result;
9834
- result = this.updateServices(servicesUpdates);
9355
+ result = this.updateServices(updated);
9835
9356
  if (result.isError) {
9836
9357
  return result;
9837
9358
  }
@@ -9843,7 +9364,7 @@ class InMemoryState extends WithDebug {
9843
9364
  if (result.isError) {
9844
9365
  return result;
9845
9366
  }
9846
- this.removeServices(servicesRemoved);
9367
+ this.removeServices(removed);
9847
9368
  return Result$1.ok(OK);
9848
9369
  }
9849
9370
  removeServices(servicesRemoved) {
@@ -9852,89 +9373,102 @@ class InMemoryState extends WithDebug {
9852
9373
  this.services.delete(serviceId);
9853
9374
  }
9854
9375
  }
9855
- updateStorage(storage) {
9856
- for (const { serviceId, action } of storage ?? []) {
9857
- const { kind } = action;
9858
- const service = this.services.get(serviceId);
9859
- if (service === undefined) {
9860
- return Result$1.error(UpdateError.NoService, `Attempting to update storage of non-existing service: ${serviceId}`);
9861
- }
9862
- if (kind === UpdateStorageKind.Set) {
9863
- const { key, value } = action.storage;
9864
- service.data.storage.set(key.toString(), StorageItem.create({ key, value }));
9865
- }
9866
- else if (kind === UpdateStorageKind.Remove) {
9867
- const { key } = action;
9868
- check `
9376
+ updateStorage(storageUpdates) {
9377
+ if (storageUpdates === undefined) {
9378
+ return Result$1.ok(OK);
9379
+ }
9380
+ for (const [serviceId, updates] of storageUpdates.entries()) {
9381
+ for (const update of updates) {
9382
+ const { kind } = update.action;
9383
+ const service = this.services.get(serviceId);
9384
+ if (service === undefined) {
9385
+ return Result$1.error(UpdateError.NoService, () => `Attempting to update storage of non-existing service: ${serviceId}`);
9386
+ }
9387
+ if (kind === UpdateStorageKind.Set) {
9388
+ const { key, value } = update.action.storage;
9389
+ service.data.storage.set(key.toString(), StorageItem.create({ key, value }));
9390
+ }
9391
+ else if (kind === UpdateStorageKind.Remove) {
9392
+ const { key } = update.action;
9393
+ check `
9869
9394
  ${service.data.storage.has(key.toString())}
9870
- Attempting to remove non-existing storage item at ${serviceId}: ${action.key}
9395
+ Attempting to remove non-existing storage item at ${serviceId}: ${update.action.key}
9871
9396
  `;
9872
- service.data.storage.delete(key.toString());
9873
- }
9874
- else {
9875
- assertNever(kind);
9397
+ service.data.storage.delete(key.toString());
9398
+ }
9399
+ else {
9400
+ assertNever(kind);
9401
+ }
9876
9402
  }
9877
9403
  }
9878
9404
  return Result$1.ok(OK);
9879
9405
  }
9880
- updatePreimages(preimages) {
9881
- for (const { serviceId, action } of preimages ?? []) {
9406
+ updatePreimages(preimagesUpdates) {
9407
+ if (preimagesUpdates === undefined) {
9408
+ return Result$1.ok(OK);
9409
+ }
9410
+ for (const [serviceId, updates] of preimagesUpdates.entries()) {
9882
9411
  const service = this.services.get(serviceId);
9883
9412
  if (service === undefined) {
9884
- return Result$1.error(UpdateError.NoService, `Attempting to update preimage of non-existing service: ${serviceId}`);
9413
+ return Result$1.error(UpdateError.NoService, () => `Attempting to update preimage of non-existing service: ${serviceId}`);
9885
9414
  }
9886
- const { kind } = action;
9887
- if (kind === UpdatePreimageKind.Provide) {
9888
- const { preimage, slot } = action;
9889
- if (service.data.preimages.has(preimage.hash)) {
9890
- return Result$1.error(UpdateError.PreimageExists, `Overwriting existing preimage at ${serviceId}: ${preimage}`);
9891
- }
9892
- service.data.preimages.set(preimage.hash, preimage);
9893
- if (slot !== null) {
9894
- const lookupHistory = service.data.lookupHistory.get(preimage.hash);
9895
- const length = tryAsU32(preimage.blob.length);
9896
- const lookup = new LookupHistoryItem(preimage.hash, length, tryAsLookupHistorySlots([slot]));
9897
- if (lookupHistory === undefined) {
9898
- // no lookup history for that preimage at all (edge case, should be requested)
9899
- service.data.lookupHistory.set(preimage.hash, [lookup]);
9415
+ for (const update of updates) {
9416
+ const { kind } = update.action;
9417
+ if (kind === UpdatePreimageKind.Provide) {
9418
+ const { preimage, slot } = update.action;
9419
+ if (service.data.preimages.has(preimage.hash)) {
9420
+ return Result$1.error(UpdateError.PreimageExists, () => `Overwriting existing preimage at ${serviceId}: ${preimage}`);
9421
+ }
9422
+ service.data.preimages.set(preimage.hash, preimage);
9423
+ if (slot !== null) {
9424
+ const lookupHistory = service.data.lookupHistory.get(preimage.hash);
9425
+ const length = tryAsU32(preimage.blob.length);
9426
+ const lookup = new LookupHistoryItem(preimage.hash, length, tryAsLookupHistorySlots([slot]));
9427
+ if (lookupHistory === undefined) {
9428
+ // no lookup history for that preimage at all (edge case, should be requested)
9429
+ service.data.lookupHistory.set(preimage.hash, [lookup]);
9430
+ }
9431
+ else {
9432
+ // insert or replace exiting entry
9433
+ const index = lookupHistory.map((x) => x.length).indexOf(length);
9434
+ lookupHistory.splice(index, index === -1 ? 0 : 1, lookup);
9435
+ }
9900
9436
  }
9901
- else {
9902
- // insert or replace exiting entry
9903
- const index = lookupHistory.map((x) => x.length).indexOf(length);
9904
- lookupHistory.splice(index, index === -1 ? 0 : 1, lookup);
9437
+ }
9438
+ else if (kind === UpdatePreimageKind.Remove) {
9439
+ const { hash, length } = update.action;
9440
+ service.data.preimages.delete(hash);
9441
+ const history = service.data.lookupHistory.get(hash) ?? [];
9442
+ const idx = history.map((x) => x.length).indexOf(length);
9443
+ if (idx !== -1) {
9444
+ history.splice(idx, 1);
9905
9445
  }
9906
9446
  }
9907
- }
9908
- else if (kind === UpdatePreimageKind.Remove) {
9909
- const { hash, length } = action;
9910
- service.data.preimages.delete(hash);
9911
- const history = service.data.lookupHistory.get(hash) ?? [];
9912
- const idx = history.map((x) => x.length).indexOf(length);
9913
- if (idx !== -1) {
9914
- history.splice(idx, 1);
9447
+ else if (kind === UpdatePreimageKind.UpdateOrAdd) {
9448
+ const { item } = update.action;
9449
+ const history = service.data.lookupHistory.get(item.hash) ?? [];
9450
+ const existingIdx = history.map((x) => x.length).indexOf(item.length);
9451
+ const removeCount = existingIdx === -1 ? 0 : 1;
9452
+ history.splice(existingIdx, removeCount, item);
9453
+ service.data.lookupHistory.set(item.hash, history);
9454
+ }
9455
+ else {
9456
+ assertNever(kind);
9915
9457
  }
9916
- }
9917
- else if (kind === UpdatePreimageKind.UpdateOrAdd) {
9918
- const { item } = action;
9919
- const history = service.data.lookupHistory.get(item.hash) ?? [];
9920
- const existingIdx = history.map((x) => x.length).indexOf(item.length);
9921
- const removeCount = existingIdx === -1 ? 0 : 1;
9922
- history.splice(existingIdx, removeCount, item);
9923
- service.data.lookupHistory.set(item.hash, history);
9924
- }
9925
- else {
9926
- assertNever(kind);
9927
9458
  }
9928
9459
  }
9929
9460
  return Result$1.ok(OK);
9930
9461
  }
9931
9462
  updateServices(servicesUpdates) {
9932
- for (const { serviceId, action } of servicesUpdates ?? []) {
9933
- const { kind, account } = action;
9463
+ if (servicesUpdates === undefined) {
9464
+ return Result$1.ok(OK);
9465
+ }
9466
+ for (const [serviceId, update] of servicesUpdates.entries()) {
9467
+ const { kind, account } = update.action;
9934
9468
  if (kind === UpdateServiceKind.Create) {
9935
- const { lookupHistory } = action;
9469
+ const { lookupHistory } = update.action;
9936
9470
  if (this.services.has(serviceId)) {
9937
- return Result$1.error(UpdateError.DuplicateService, `${serviceId} already exists!`);
9471
+ return Result$1.error(UpdateError.DuplicateService, () => `${serviceId} already exists!`);
9938
9472
  }
9939
9473
  this.services.set(serviceId, new InMemoryService(serviceId, {
9940
9474
  info: account,
@@ -9946,7 +9480,7 @@ class InMemoryState extends WithDebug {
9946
9480
  else if (kind === UpdateServiceKind.Update) {
9947
9481
  const existingService = this.services.get(serviceId);
9948
9482
  if (existingService === undefined) {
9949
- return Result$1.error(UpdateError.NoService, `Cannot update ${serviceId} because it does not exist.`);
9483
+ return Result$1.error(UpdateError.NoService, () => `Cannot update ${serviceId} because it does not exist.`);
9950
9484
  }
9951
9485
  existingService.data.info = account;
9952
9486
  }
@@ -9982,8 +9516,9 @@ class InMemoryState extends WithDebug {
9982
9516
  getService(id) {
9983
9517
  return this.services.get(id) ?? null;
9984
9518
  }
9985
- constructor(s) {
9519
+ constructor(chainSpec, s) {
9986
9520
  super();
9521
+ this.chainSpec = chainSpec;
9987
9522
  this.availabilityAssignment = s.availabilityAssignment;
9988
9523
  this.designatedValidatorData = s.designatedValidatorData;
9989
9524
  this.nextValidatorData = s.nextValidatorData;
@@ -10005,11 +9540,14 @@ class InMemoryState extends WithDebug {
10005
9540
  this.accumulationOutputLog = s.accumulationOutputLog;
10006
9541
  this.services = s.services;
10007
9542
  }
9543
+ view() {
9544
+ return new InMemoryStateView(this.chainSpec, this);
9545
+ }
10008
9546
  /**
10009
9547
  * Create an empty and possibly incoherent `InMemoryState`.
10010
9548
  */
10011
9549
  static empty(spec) {
10012
- return new InMemoryState({
9550
+ return new InMemoryState(spec, {
10013
9551
  availabilityAssignment: tryAsPerCore(Array.from({ length: spec.coresCount }, () => null), spec),
10014
9552
  designatedValidatorData: tryAsPerValidator(Array.from({ length: spec.validatorsCount }, () => ValidatorData.create({
10015
9553
  bandersnatch: Bytes.zero(BANDERSNATCH_KEY_BYTES).asOpaque(),
@@ -10045,7 +9583,7 @@ class InMemoryState extends WithDebug {
10045
9583
  entropy: FixedSizeArray.fill(() => Bytes.zero(HASH_SIZE).asOpaque(), ENTROPY_ENTRIES),
10046
9584
  authPools: tryAsPerCore(Array.from({ length: spec.coresCount }, () => asKnownSize([])), spec),
10047
9585
  authQueues: tryAsPerCore(Array.from({ length: spec.coresCount }, () => FixedSizeArray.fill(() => Bytes.zero(HASH_SIZE).asOpaque(), AUTHORIZATION_QUEUE_SIZE)), spec),
10048
- recentBlocks: RecentBlocksHistory.empty(),
9586
+ recentBlocks: RecentBlocks.empty(),
10049
9587
  statistics: StatisticsData.create({
10050
9588
  current: tryAsPerValidator(Array.from({ length: spec.validatorsCount }, () => ValidatorStatistics.empty()), spec),
10051
9589
  previous: tryAsPerValidator(Array.from({ length: spec.validatorsCount }, () => ValidatorStatistics.empty()), spec),
@@ -10059,8 +9597,9 @@ class InMemoryState extends WithDebug {
10059
9597
  epochRoot: Bytes.zero(BANDERSNATCH_RING_ROOT_BYTES).asOpaque(),
10060
9598
  privilegedServices: PrivilegedServices.create({
10061
9599
  manager: tryAsServiceId(0),
10062
- authManager: tryAsPerCore(new Array(spec.coresCount).fill(tryAsServiceId(0)), spec),
10063
- validatorsManager: tryAsServiceId(0),
9600
+ assigners: tryAsPerCore(new Array(spec.coresCount).fill(tryAsServiceId(0)), spec),
9601
+ delegator: tryAsServiceId(0),
9602
+ registrar: tryAsServiceId(MAX_VALUE),
10064
9603
  autoAccumulateServices: [],
10065
9604
  }),
10066
9605
  accumulationOutputLog: SortedArray.fromArray(accumulationOutputComparator, []),
@@ -10082,6 +9621,7 @@ const serviceDataCodec = codec$1.dictionary(codec$1.u32.asOpaque(), serviceEntri
10082
9621
 
10083
9622
  var index$g = /*#__PURE__*/Object.freeze({
10084
9623
  __proto__: null,
9624
+ AUTHORIZATION_QUEUE_SIZE: AUTHORIZATION_QUEUE_SIZE,
10085
9625
  AccumulationOutput: AccumulationOutput,
10086
9626
  AutoAccumulate: AutoAccumulate,
10087
9627
  AvailabilityAssignment: AvailabilityAssignment,
@@ -10095,11 +9635,12 @@ var index$g = /*#__PURE__*/Object.freeze({
10095
9635
  InMemoryService: InMemoryService,
10096
9636
  InMemoryState: InMemoryState,
10097
9637
  LookupHistoryItem: LookupHistoryItem,
9638
+ MAX_AUTH_POOL_SIZE: MAX_AUTH_POOL_SIZE,
10098
9639
  MAX_RECENT_HISTORY: MAX_RECENT_HISTORY,
9640
+ NotYetAccumulatedReport: NotYetAccumulatedReport,
10099
9641
  PreimageItem: PreimageItem,
10100
9642
  PrivilegedServices: PrivilegedServices,
10101
9643
  RecentBlocks: RecentBlocks,
10102
- RecentBlocksHistory: RecentBlocksHistory,
10103
9644
  SafroleData: SafroleData,
10104
9645
  SafroleSealingKeysData: SafroleSealingKeysData,
10105
9646
  get SafroleSealingKeysKind () { return SafroleSealingKeysKind; },
@@ -10118,70 +9659,35 @@ var index$g = /*#__PURE__*/Object.freeze({
10118
9659
  ValidatorData: ValidatorData,
10119
9660
  ValidatorStatistics: ValidatorStatistics,
10120
9661
  accumulationOutputComparator: accumulationOutputComparator,
9662
+ accumulationQueueCodec: accumulationQueueCodec,
9663
+ authPoolsCodec: authPoolsCodec,
9664
+ authQueuesCodec: authQueuesCodec,
9665
+ availabilityAssignmentsCodec: availabilityAssignmentsCodec,
10121
9666
  codecPerCore: codecPerCore,
9667
+ codecWithVersion: codecWithVersion,
10122
9668
  hashComparator: hashComparator,
10123
9669
  ignoreValueWithDefault: ignoreValueWithDefault,
9670
+ recentlyAccumulatedCodec: recentlyAccumulatedCodec,
10124
9671
  serviceDataCodec: serviceDataCodec,
10125
9672
  serviceEntriesCodec: serviceEntriesCodec,
10126
9673
  tryAsLookupHistorySlots: tryAsLookupHistorySlots,
10127
- tryAsPerCore: tryAsPerCore
9674
+ tryAsPerCore: tryAsPerCore,
9675
+ validatorsDataCodec: validatorsDataCodec
10128
9676
  });
10129
9677
 
10130
- /**
10131
- * Ready (i.e. available and/or audited) but not-yet-accumulated work-reports.
10132
- *
10133
- * https://graypaper.fluffylabs.dev/#/5f542d7/165300165400
10134
- */
10135
- class NotYetAccumulatedReport extends WithDebug {
10136
- report;
10137
- dependencies;
10138
- static Codec = codec$1.Class(NotYetAccumulatedReport, {
10139
- report: WorkReport.Codec,
10140
- dependencies: codecKnownSizeArray(codec$1.bytes(HASH_SIZE).asOpaque(), {
10141
- typicalLength: MAX_REPORT_DEPENDENCIES / 2,
10142
- maxLength: MAX_REPORT_DEPENDENCIES,
10143
- minLength: 0,
10144
- }),
10145
- });
10146
- static create({ report, dependencies }) {
10147
- return new NotYetAccumulatedReport(report, dependencies);
10148
- }
10149
- constructor(
10150
- /**
10151
- * Each of these were made available at most one epoch ago
10152
- * but have or had unfulfilled dependencies.
10153
- */
10154
- report,
10155
- /**
10156
- * Alongside the work-report itself, we retain its un-accumulated
10157
- * dependencies, a set of work-package hashes.
10158
- *
10159
- * https://graypaper.fluffylabs.dev/#/5f542d7/165800165800
10160
- */
10161
- dependencies) {
10162
- super();
10163
- this.report = report;
10164
- this.dependencies = dependencies;
10165
- }
10166
- }
10167
-
10168
9678
  /** Serialization for particular state entries. */
10169
9679
  var serialize;
10170
9680
  (function (serialize) {
10171
9681
  /** C(1): https://graypaper.fluffylabs.dev/#/7e6ff6a/3b15013b1501?v=0.6.7 */
10172
9682
  serialize.authPools = {
10173
9683
  key: stateKeys.index(StateKeyIdx.Alpha),
10174
- Codec: codecPerCore(codecKnownSizeArray(codec$1.bytes(HASH_SIZE).asOpaque(), {
10175
- minLength: 0,
10176
- maxLength: MAX_AUTH_POOL_SIZE,
10177
- typicalLength: MAX_AUTH_POOL_SIZE,
10178
- })),
9684
+ Codec: authPoolsCodec,
10179
9685
  extract: (s) => s.authPools,
10180
9686
  };
10181
9687
  /** C(2): https://graypaper.fluffylabs.dev/#/7e6ff6a/3b31013b3101?v=0.6.7 */
10182
9688
  serialize.authQueues = {
10183
9689
  key: stateKeys.index(StateKeyIdx.Phi),
10184
- Codec: codecPerCore(codecFixedSizeArray(codec$1.bytes(HASH_SIZE).asOpaque(), AUTHORIZATION_QUEUE_SIZE)),
9690
+ Codec: authQueuesCodec,
10185
9691
  extract: (s) => s.authQueues,
10186
9692
  };
10187
9693
  /**
@@ -10190,7 +9696,7 @@ var serialize;
10190
9696
  */
10191
9697
  serialize.recentBlocks = {
10192
9698
  key: stateKeys.index(StateKeyIdx.Beta),
10193
- Codec: RecentBlocksHistory.Codec,
9699
+ Codec: RecentBlocks.Codec,
10194
9700
  extract: (s) => s.recentBlocks,
10195
9701
  };
10196
9702
  /** C(4): https://graypaper.fluffylabs.dev/#/7e6ff6a/3b63013b6301?v=0.6.7 */
@@ -10219,25 +9725,25 @@ var serialize;
10219
9725
  /** C(7): https://graypaper.fluffylabs.dev/#/7e6ff6a/3b00023b0002?v=0.6.7 */
10220
9726
  serialize.designatedValidators = {
10221
9727
  key: stateKeys.index(StateKeyIdx.Iota),
10222
- Codec: codecPerValidator(ValidatorData.Codec),
9728
+ Codec: validatorsDataCodec,
10223
9729
  extract: (s) => s.designatedValidatorData,
10224
9730
  };
10225
9731
  /** C(8): https://graypaper.fluffylabs.dev/#/7e6ff6a/3b0d023b0d02?v=0.6.7 */
10226
9732
  serialize.currentValidators = {
10227
9733
  key: stateKeys.index(StateKeyIdx.Kappa),
10228
- Codec: codecPerValidator(ValidatorData.Codec),
9734
+ Codec: validatorsDataCodec,
10229
9735
  extract: (s) => s.currentValidatorData,
10230
9736
  };
10231
9737
  /** C(9): https://graypaper.fluffylabs.dev/#/7e6ff6a/3b1a023b1a02?v=0.6.7 */
10232
9738
  serialize.previousValidators = {
10233
9739
  key: stateKeys.index(StateKeyIdx.Lambda),
10234
- Codec: codecPerValidator(ValidatorData.Codec),
9740
+ Codec: validatorsDataCodec,
10235
9741
  extract: (s) => s.previousValidatorData,
10236
9742
  };
10237
9743
  /** C(10): https://graypaper.fluffylabs.dev/#/7e6ff6a/3b27023b2702?v=0.6.7 */
10238
9744
  serialize.availabilityAssignment = {
10239
9745
  key: stateKeys.index(StateKeyIdx.Rho),
10240
- Codec: codecPerCore(codec$1.optional(AvailabilityAssignment.Codec)),
9746
+ Codec: availabilityAssignmentsCodec,
10241
9747
  extract: (s) => s.availabilityAssignment,
10242
9748
  };
10243
9749
  /** C(11): https://graypaper.fluffylabs.dev/#/7e6ff6a/3b3e023b3e02?v=0.6.7 */
@@ -10261,13 +9767,13 @@ var serialize;
10261
9767
  /** C(14): https://graypaper.fluffylabs.dev/#/1c979cb/3bf0023bf002?v=0.7.1 */
10262
9768
  serialize.accumulationQueue = {
10263
9769
  key: stateKeys.index(StateKeyIdx.Omega),
10264
- Codec: codecPerEpochBlock(readonlyArray(codec$1.sequenceVarLen(NotYetAccumulatedReport.Codec))),
9770
+ Codec: accumulationQueueCodec,
10265
9771
  extract: (s) => s.accumulationQueue,
10266
9772
  };
10267
9773
  /** C(15): https://graypaper.fluffylabs.dev/#/7e6ff6a/3b96023b9602?v=0.6.7 */
10268
9774
  serialize.recentlyAccumulated = {
10269
9775
  key: stateKeys.index(StateKeyIdx.Xi),
10270
- Codec: codecPerEpochBlock(codec$1.sequenceVarLen(codec$1.bytes(HASH_SIZE).asOpaque()).convert((x) => Array.from(x), (x) => HashSet.from(x))),
9776
+ Codec: recentlyAccumulatedCodec,
10271
9777
  extract: (s) => s.recentlyAccumulated,
10272
9778
  };
10273
9779
  /** C(16): https://graypaper.fluffylabs.dev/#/38c4e62/3b46033b4603?v=0.7.0 */
@@ -10279,21 +9785,23 @@ var serialize;
10279
9785
  /** C(255, s): https://graypaper.fluffylabs.dev/#/85129da/383103383103?v=0.6.3 */
10280
9786
  serialize.serviceData = (serviceId) => ({
10281
9787
  key: stateKeys.serviceInfo(serviceId),
10282
- Codec: ServiceAccountInfo.Codec,
9788
+ Codec: Compatibility.isGreaterOrEqual(GpVersion.V0_7_1)
9789
+ ? codecWithVersion(ServiceAccountInfo.Codec)
9790
+ : ServiceAccountInfo.Codec,
10283
9791
  });
10284
9792
  /** https://graypaper.fluffylabs.dev/#/85129da/384803384803?v=0.6.3 */
10285
- serialize.serviceStorage = (serviceId, key) => ({
10286
- key: stateKeys.serviceStorage(serviceId, key),
9793
+ serialize.serviceStorage = (blake2b, serviceId, key) => ({
9794
+ key: stateKeys.serviceStorage(blake2b, serviceId, key),
10287
9795
  Codec: dumpCodec,
10288
9796
  });
10289
9797
  /** https://graypaper.fluffylabs.dev/#/85129da/385b03385b03?v=0.6.3 */
10290
- serialize.servicePreimages = (serviceId, hash) => ({
10291
- key: stateKeys.servicePreimage(serviceId, hash),
9798
+ serialize.servicePreimages = (blake2b, serviceId, hash) => ({
9799
+ key: stateKeys.servicePreimage(blake2b, serviceId, hash),
10292
9800
  Codec: dumpCodec,
10293
9801
  });
10294
9802
  /** https://graypaper.fluffylabs.dev/#/85129da/387603387603?v=0.6.3 */
10295
- serialize.serviceLookupHistory = (serviceId, hash, len) => ({
10296
- key: stateKeys.serviceLookupHistory(serviceId, hash, len),
9803
+ serialize.serviceLookupHistory = (blake2b, serviceId, hash, len) => ({
9804
+ key: stateKeys.serviceLookupHistory(blake2b, serviceId, hash, len),
10297
9805
  Codec: readonlyArray(codec$1.sequenceVarLen(codec$1.u32)),
10298
9806
  });
10299
9807
  })(serialize || (serialize = {}));
@@ -10306,6 +9814,84 @@ var serialize;
10306
9814
  */
10307
9815
  const dumpCodec = Descriptor.new("Dump", { bytes: 64, isExact: false }, (e, v) => e.bytes(Bytes.fromBlob(v.raw, v.raw.length)), (d) => BytesBlob.blobFrom(d.bytes(d.source.length - d.bytesRead()).raw), (s) => s.bytes(s.decoder.source.length - s.decoder.bytesRead()));
10308
9816
 
9817
+ class SerializedStateView {
9818
+ spec;
9819
+ backend;
9820
+ recentlyUsedServices;
9821
+ viewCache;
9822
+ constructor(spec, backend,
9823
+ /** Best-effort list of recently active services. */
9824
+ recentlyUsedServices, viewCache) {
9825
+ this.spec = spec;
9826
+ this.backend = backend;
9827
+ this.recentlyUsedServices = recentlyUsedServices;
9828
+ this.viewCache = viewCache;
9829
+ }
9830
+ retrieveView({ key, Codec }, description) {
9831
+ const cached = this.viewCache.get(key);
9832
+ if (cached !== undefined) {
9833
+ return cached;
9834
+ }
9835
+ const bytes = this.backend.get(key);
9836
+ if (bytes === null) {
9837
+ throw new Error(`Required state entry for ${description} is missing!. Accessing view of key: ${key}`);
9838
+ }
9839
+ // NOTE [ToDr] we are not using `Decoder.decodeObject` here because
9840
+ // it needs to get to the end of the data (skip), yet that's expensive.
9841
+ // we assume that the state data is correct and coherent anyway, so
9842
+ // for performance reasons we simply create the view here.
9843
+ const d = Decoder.fromBytesBlob(bytes);
9844
+ d.attachContext(this.spec);
9845
+ const view = Codec.View.decode(d);
9846
+ this.viewCache.set(key, view);
9847
+ return view;
9848
+ }
9849
+ availabilityAssignmentView() {
9850
+ return this.retrieveView(serialize.availabilityAssignment, "availabilityAssignmentView");
9851
+ }
9852
+ designatedValidatorDataView() {
9853
+ return this.retrieveView(serialize.designatedValidators, "designatedValidatorsView");
9854
+ }
9855
+ currentValidatorDataView() {
9856
+ return this.retrieveView(serialize.currentValidators, "currentValidatorsView");
9857
+ }
9858
+ previousValidatorDataView() {
9859
+ return this.retrieveView(serialize.previousValidators, "previousValidatorsView");
9860
+ }
9861
+ authPoolsView() {
9862
+ return this.retrieveView(serialize.authPools, "authPoolsView");
9863
+ }
9864
+ authQueuesView() {
9865
+ return this.retrieveView(serialize.authQueues, "authQueuesView");
9866
+ }
9867
+ recentBlocksView() {
9868
+ return this.retrieveView(serialize.recentBlocks, "recentBlocksView");
9869
+ }
9870
+ statisticsView() {
9871
+ return this.retrieveView(serialize.statistics, "statisticsView");
9872
+ }
9873
+ accumulationQueueView() {
9874
+ return this.retrieveView(serialize.accumulationQueue, "accumulationQueueView");
9875
+ }
9876
+ recentlyAccumulatedView() {
9877
+ return this.retrieveView(serialize.recentlyAccumulated, "recentlyAccumulatedView");
9878
+ }
9879
+ safroleDataView() {
9880
+ return this.retrieveView(serialize.safrole, "safroleDataView");
9881
+ }
9882
+ getServiceInfoView(id) {
9883
+ const serviceData = serialize.serviceData(id);
9884
+ const bytes = this.backend.get(serviceData.key);
9885
+ if (bytes === null) {
9886
+ return null;
9887
+ }
9888
+ if (!this.recentlyUsedServices.includes(id)) {
9889
+ this.recentlyUsedServices.push(id);
9890
+ }
9891
+ return Decoder.decodeObject(serviceData.Codec.View, bytes, this.spec);
9892
+ }
9893
+ }
9894
+
10309
9895
  /**
10310
9896
  * State object which reads it's entries from some backend.
10311
9897
  *
@@ -10316,58 +9902,74 @@ const dumpCodec = Descriptor.new("Dump", { bytes: 64, isExact: false }, (e, v) =
10316
9902
  */
10317
9903
  class SerializedState {
10318
9904
  spec;
9905
+ blake2b;
10319
9906
  backend;
10320
- _recentServiceIds;
9907
+ recentlyUsedServices;
10321
9908
  /** Create a state-like object from collection of serialized entries. */
10322
- static fromStateEntries(spec, state, recentServices = []) {
10323
- return new SerializedState(spec, state, recentServices);
9909
+ static fromStateEntries(spec, blake2b, state, recentServices = []) {
9910
+ return new SerializedState(spec, blake2b, state, recentServices);
10324
9911
  }
10325
9912
  /** Create a state-like object backed by some DB. */
10326
- static new(spec, db, recentServices = []) {
10327
- return new SerializedState(spec, db, recentServices);
9913
+ static new(spec, blake2b, db, recentServices = []) {
9914
+ return new SerializedState(spec, blake2b, db, recentServices);
10328
9915
  }
10329
- constructor(spec, backend,
9916
+ dataCache = HashDictionary.new();
9917
+ viewCache = HashDictionary.new();
9918
+ constructor(spec, blake2b, backend,
10330
9919
  /** Best-effort list of recently active services. */
10331
- _recentServiceIds) {
9920
+ recentlyUsedServices) {
10332
9921
  this.spec = spec;
9922
+ this.blake2b = blake2b;
10333
9923
  this.backend = backend;
10334
- this._recentServiceIds = _recentServiceIds;
9924
+ this.recentlyUsedServices = recentlyUsedServices;
10335
9925
  }
10336
9926
  /** Comparing the serialized states, just means comparing their backends. */
10337
9927
  [TEST_COMPARE_USING]() {
10338
9928
  return this.backend;
10339
9929
  }
9930
+ /** Return a non-decoding version of the state. */
9931
+ view() {
9932
+ return new SerializedStateView(this.spec, this.backend, this.recentlyUsedServices, this.viewCache);
9933
+ }
10340
9934
  // TODO [ToDr] Temporary method to update the state,
10341
9935
  // without changing references.
10342
9936
  updateBackend(newBackend) {
10343
9937
  this.backend = newBackend;
9938
+ this.dataCache = HashDictionary.new();
9939
+ this.viewCache = HashDictionary.new();
10344
9940
  }
10345
9941
  recentServiceIds() {
10346
- return this._recentServiceIds;
9942
+ return this.recentlyUsedServices;
10347
9943
  }
10348
9944
  getService(id) {
10349
9945
  const serviceData = this.retrieveOptional(serialize.serviceData(id));
10350
9946
  if (serviceData === undefined) {
10351
9947
  return null;
10352
9948
  }
10353
- if (!this._recentServiceIds.includes(id)) {
10354
- this._recentServiceIds.push(id);
9949
+ if (!this.recentlyUsedServices.includes(id)) {
9950
+ this.recentlyUsedServices.push(id);
10355
9951
  }
10356
- return new SerializedService(id, serviceData, (key) => this.retrieveOptional(key));
9952
+ return new SerializedService(this.blake2b, id, serviceData, (key) => this.retrieveOptional(key));
10357
9953
  }
10358
- retrieve({ key, Codec }, description) {
10359
- const bytes = this.backend.get(key);
10360
- if (bytes === null) {
10361
- throw new Error(`Required state entry for ${description} is missing!. Accessing key: ${key}`);
9954
+ retrieve(k, description) {
9955
+ const data = this.retrieveOptional(k);
9956
+ if (data === undefined) {
9957
+ throw new Error(`Required state entry for ${description} is missing!. Accessing key: ${k.key}`);
10362
9958
  }
10363
- return Decoder.decodeObject(Codec, bytes, this.spec);
9959
+ return data;
10364
9960
  }
10365
9961
  retrieveOptional({ key, Codec }) {
9962
+ const cached = this.dataCache.get(key);
9963
+ if (cached !== undefined) {
9964
+ return cached;
9965
+ }
10366
9966
  const bytes = this.backend.get(key);
10367
9967
  if (bytes === null) {
10368
9968
  return undefined;
10369
9969
  }
10370
- return Decoder.decodeObject(Codec, bytes, this.spec);
9970
+ const data = Decoder.decodeObject(Codec, bytes, this.spec);
9971
+ this.dataCache.set(key, data);
9972
+ return data;
10371
9973
  }
10372
9974
  get availabilityAssignment() {
10373
9975
  return this.retrieve(serialize.availabilityAssignment, "availabilityAssignment");
@@ -10429,12 +10031,14 @@ class SerializedState {
10429
10031
  }
10430
10032
  /** Service data representation on a serialized state. */
10431
10033
  class SerializedService {
10034
+ blake2b;
10432
10035
  serviceId;
10433
10036
  accountInfo;
10434
10037
  retrieveOptional;
10435
- constructor(
10038
+ constructor(blake2b,
10436
10039
  /** Service id */
10437
10040
  serviceId, accountInfo, retrieveOptional) {
10041
+ this.blake2b = blake2b;
10438
10042
  this.serviceId = serviceId;
10439
10043
  this.accountInfo = accountInfo;
10440
10044
  this.retrieveOptional = retrieveOptional;
@@ -10447,13 +10051,13 @@ class SerializedService {
10447
10051
  getStorage(rawKey) {
10448
10052
  if (Compatibility.isLessThan(GpVersion.V0_6_7)) {
10449
10053
  const SERVICE_ID_BYTES = 4;
10450
- const serviceIdAndKey = new Uint8Array(SERVICE_ID_BYTES + rawKey.length);
10054
+ const serviceIdAndKey = safeAllocUint8Array(SERVICE_ID_BYTES + rawKey.length);
10451
10055
  serviceIdAndKey.set(u32AsLeBytes(this.serviceId));
10452
10056
  serviceIdAndKey.set(rawKey.raw, SERVICE_ID_BYTES);
10453
- const key = asOpaqueType(BytesBlob.blobFrom(hashBytes(serviceIdAndKey).raw));
10454
- return this.retrieveOptional(serialize.serviceStorage(this.serviceId, key)) ?? null;
10057
+ const key = asOpaqueType(BytesBlob.blobFrom(this.blake2b.hashBytes(serviceIdAndKey).raw));
10058
+ return this.retrieveOptional(serialize.serviceStorage(this.blake2b, this.serviceId, key)) ?? null;
10455
10059
  }
10456
- return this.retrieveOptional(serialize.serviceStorage(this.serviceId, rawKey)) ?? null;
10060
+ return this.retrieveOptional(serialize.serviceStorage(this.blake2b, this.serviceId, rawKey)) ?? null;
10457
10061
  }
10458
10062
  /**
10459
10063
  * Check if preimage is present in the DB.
@@ -10462,15 +10066,15 @@ class SerializedService {
10462
10066
  */
10463
10067
  hasPreimage(hash) {
10464
10068
  // TODO [ToDr] consider optimizing to avoid fetching the whole data.
10465
- return this.retrieveOptional(serialize.servicePreimages(this.serviceId, hash)) !== undefined;
10069
+ return this.retrieveOptional(serialize.servicePreimages(this.blake2b, this.serviceId, hash)) !== undefined;
10466
10070
  }
10467
10071
  /** Retrieve preimage from the DB. */
10468
10072
  getPreimage(hash) {
10469
- return this.retrieveOptional(serialize.servicePreimages(this.serviceId, hash)) ?? null;
10073
+ return this.retrieveOptional(serialize.servicePreimages(this.blake2b, this.serviceId, hash)) ?? null;
10470
10074
  }
10471
10075
  /** Retrieve preimage lookup history. */
10472
10076
  getLookupHistory(hash, len) {
10473
- const rawSlots = this.retrieveOptional(serialize.serviceLookupHistory(this.serviceId, hash, len));
10077
+ const rawSlots = this.retrieveOptional(serialize.serviceLookupHistory(this.blake2b, this.serviceId, hash, len));
10474
10078
  if (rawSlots === undefined) {
10475
10079
  return null;
10476
10080
  }
@@ -10532,7 +10136,7 @@ class TrieNode {
10532
10136
  raw;
10533
10137
  constructor(
10534
10138
  /** Exactly 512 bits / 64 bytes */
10535
- raw = new Uint8Array(TRIE_NODE_BYTES)) {
10139
+ raw = safeAllocUint8Array(TRIE_NODE_BYTES)) {
10536
10140
  this.raw = raw;
10537
10141
  }
10538
10142
  /** Returns the type of the node */
@@ -11107,11 +10711,13 @@ var index$f = /*#__PURE__*/Object.freeze({
11107
10711
  parseInputKey: parseInputKey
11108
10712
  });
11109
10713
 
11110
- const blake2bTrieHasher = {
11111
- hashConcat(n, rest = []) {
11112
- return hashBlobs$1([n, ...rest]);
11113
- },
11114
- };
10714
+ function getBlake2bTrieHasher(hasher) {
10715
+ return {
10716
+ hashConcat(n, rest = []) {
10717
+ return hasher.hashBlobs([n, ...rest]);
10718
+ },
10719
+ };
10720
+ }
11115
10721
 
11116
10722
  /** What should be done with that key? */
11117
10723
  var StateEntryUpdateAction;
@@ -11123,88 +10729,100 @@ var StateEntryUpdateAction;
11123
10729
  })(StateEntryUpdateAction || (StateEntryUpdateAction = {}));
11124
10730
  const EMPTY_BLOB = BytesBlob.empty();
11125
10731
  /** Serialize given state update into a series of key-value pairs. */
11126
- function* serializeStateUpdate(spec, update) {
10732
+ function* serializeStateUpdate(spec, blake2b, update) {
11127
10733
  // first let's serialize all of the simple entries (if present!)
11128
10734
  yield* serializeBasicKeys(spec, update);
11129
10735
  const encode = (codec, val) => Encoder.encodeObject(codec, val, spec);
11130
10736
  // then let's proceed with service updates
11131
- yield* serializeServiceUpdates(update.servicesUpdates, encode);
11132
- yield* serializePreimages(update.preimages, encode);
11133
- yield* serializeStorage(update.storage);
11134
- yield* serializeRemovedServices(update.servicesRemoved);
10737
+ yield* serializeServiceUpdates(update.updated, encode, blake2b);
10738
+ yield* serializePreimages(update.preimages, encode, blake2b);
10739
+ yield* serializeStorage(update.storage, blake2b);
10740
+ yield* serializeRemovedServices(update.removed);
11135
10741
  }
11136
10742
  function* serializeRemovedServices(servicesRemoved) {
11137
- for (const serviceId of servicesRemoved ?? []) {
10743
+ if (servicesRemoved === undefined) {
10744
+ return;
10745
+ }
10746
+ for (const serviceId of servicesRemoved) {
11138
10747
  // TODO [ToDr] what about all data associated with a service?
11139
10748
  const codec = serialize.serviceData(serviceId);
11140
10749
  yield [StateEntryUpdateAction.Remove, codec.key, EMPTY_BLOB];
11141
10750
  }
11142
10751
  }
11143
- function* serializeStorage(storage) {
11144
- for (const { action, serviceId } of storage ?? []) {
11145
- switch (action.kind) {
11146
- case UpdateStorageKind.Set: {
11147
- const key = action.storage.key;
11148
- const codec = serialize.serviceStorage(serviceId, key);
11149
- yield [StateEntryUpdateAction.Insert, codec.key, action.storage.value];
11150
- break;
11151
- }
11152
- case UpdateStorageKind.Remove: {
11153
- const key = action.key;
11154
- const codec = serialize.serviceStorage(serviceId, key);
11155
- yield [StateEntryUpdateAction.Remove, codec.key, EMPTY_BLOB];
11156
- break;
10752
+ function* serializeStorage(storageUpdates, blake2b) {
10753
+ if (storageUpdates === undefined) {
10754
+ return;
10755
+ }
10756
+ for (const [serviceId, updates] of storageUpdates.entries()) {
10757
+ for (const { action } of updates) {
10758
+ switch (action.kind) {
10759
+ case UpdateStorageKind.Set: {
10760
+ const key = action.storage.key;
10761
+ const codec = serialize.serviceStorage(blake2b, serviceId, key);
10762
+ yield [StateEntryUpdateAction.Insert, codec.key, action.storage.value];
10763
+ break;
10764
+ }
10765
+ case UpdateStorageKind.Remove: {
10766
+ const key = action.key;
10767
+ const codec = serialize.serviceStorage(blake2b, serviceId, key);
10768
+ yield [StateEntryUpdateAction.Remove, codec.key, EMPTY_BLOB];
10769
+ break;
10770
+ }
11157
10771
  }
11158
- default:
11159
- assertNever(action);
11160
10772
  }
11161
10773
  }
11162
10774
  }
11163
- function* serializePreimages(preimages, encode) {
11164
- for (const { action, serviceId } of preimages ?? []) {
11165
- switch (action.kind) {
11166
- case UpdatePreimageKind.Provide: {
11167
- const { hash, blob } = action.preimage;
11168
- const codec = serialize.servicePreimages(serviceId, hash);
11169
- yield [StateEntryUpdateAction.Insert, codec.key, blob];
11170
- if (action.slot !== null) {
11171
- const codec2 = serialize.serviceLookupHistory(serviceId, hash, tryAsU32(blob.length));
11172
- yield [
11173
- StateEntryUpdateAction.Insert,
11174
- codec2.key,
11175
- encode(codec2.Codec, tryAsLookupHistorySlots([action.slot])),
11176
- ];
10775
+ function* serializePreimages(preimagesUpdates, encode, blake2b) {
10776
+ if (preimagesUpdates === undefined) {
10777
+ return;
10778
+ }
10779
+ for (const [serviceId, updates] of preimagesUpdates.entries()) {
10780
+ for (const { action } of updates) {
10781
+ switch (action.kind) {
10782
+ case UpdatePreimageKind.Provide: {
10783
+ const { hash, blob } = action.preimage;
10784
+ const codec = serialize.servicePreimages(blake2b, serviceId, hash);
10785
+ yield [StateEntryUpdateAction.Insert, codec.key, blob];
10786
+ if (action.slot !== null) {
10787
+ const codec2 = serialize.serviceLookupHistory(blake2b, serviceId, hash, tryAsU32(blob.length));
10788
+ yield [
10789
+ StateEntryUpdateAction.Insert,
10790
+ codec2.key,
10791
+ encode(codec2.Codec, tryAsLookupHistorySlots([action.slot])),
10792
+ ];
10793
+ }
10794
+ break;
10795
+ }
10796
+ case UpdatePreimageKind.UpdateOrAdd: {
10797
+ const { hash, length, slots } = action.item;
10798
+ const codec = serialize.serviceLookupHistory(blake2b, serviceId, hash, length);
10799
+ yield [StateEntryUpdateAction.Insert, codec.key, encode(codec.Codec, slots)];
10800
+ break;
10801
+ }
10802
+ case UpdatePreimageKind.Remove: {
10803
+ const { hash, length } = action;
10804
+ const codec = serialize.servicePreimages(blake2b, serviceId, hash);
10805
+ yield [StateEntryUpdateAction.Remove, codec.key, EMPTY_BLOB];
10806
+ const codec2 = serialize.serviceLookupHistory(blake2b, serviceId, hash, length);
10807
+ yield [StateEntryUpdateAction.Remove, codec2.key, EMPTY_BLOB];
10808
+ break;
11177
10809
  }
11178
- break;
11179
- }
11180
- case UpdatePreimageKind.UpdateOrAdd: {
11181
- const { hash, length, slots } = action.item;
11182
- const codec = serialize.serviceLookupHistory(serviceId, hash, length);
11183
- yield [StateEntryUpdateAction.Insert, codec.key, encode(codec.Codec, slots)];
11184
- break;
11185
- }
11186
- case UpdatePreimageKind.Remove: {
11187
- const { hash, length } = action;
11188
- const codec = serialize.servicePreimages(serviceId, hash);
11189
- yield [StateEntryUpdateAction.Remove, codec.key, EMPTY_BLOB];
11190
- const codec2 = serialize.serviceLookupHistory(serviceId, hash, length);
11191
- yield [StateEntryUpdateAction.Remove, codec2.key, EMPTY_BLOB];
11192
- break;
11193
10810
  }
11194
- default:
11195
- assertNever(action);
11196
10811
  }
11197
10812
  }
11198
10813
  }
11199
- function* serializeServiceUpdates(servicesUpdates, encode) {
11200
- for (const { action, serviceId } of servicesUpdates ?? []) {
10814
+ function* serializeServiceUpdates(servicesUpdates, encode, blake2b) {
10815
+ if (servicesUpdates === undefined) {
10816
+ return;
10817
+ }
10818
+ for (const [serviceId, { action }] of servicesUpdates.entries()) {
11201
10819
  // new service being created or updated
11202
10820
  const codec = serialize.serviceData(serviceId);
11203
10821
  yield [StateEntryUpdateAction.Insert, codec.key, encode(codec.Codec, action.account)];
11204
10822
  // additional lookup history update
11205
10823
  if (action.kind === UpdateServiceKind.Create && action.lookupHistory !== null) {
11206
10824
  const { lookupHistory } = action;
11207
- const codec2 = serialize.serviceLookupHistory(serviceId, lookupHistory.hash, lookupHistory.length);
10825
+ const codec2 = serialize.serviceLookupHistory(blake2b, serviceId, lookupHistory.hash, lookupHistory.length);
11208
10826
  yield [StateEntryUpdateAction.Insert, codec2.key, encode(codec2.Codec, lookupHistory.slots)];
11209
10827
  }
11210
10828
  }
@@ -11299,8 +10917,8 @@ class StateEntries {
11299
10917
  },
11300
10918
  }, (e, v) => stateEntriesSequenceCodec.encode(e, Array.from(v.entries)), (d) => StateEntries.fromEntriesUnsafe(stateEntriesSequenceCodec.decode(d)), (s) => stateEntriesSequenceCodec.skip(s));
11301
10919
  /** Turn in-memory state into it's serialized form. */
11302
- static serializeInMemory(spec, state) {
11303
- return new StateEntries(convertInMemoryStateToDictionary(spec, state));
10920
+ static serializeInMemory(spec, blake2b, state) {
10921
+ return new StateEntries(convertInMemoryStateToDictionary(spec, blake2b, state));
11304
10922
  }
11305
10923
  /**
11306
10924
  * Wrap a collection of truncated state entries and treat it as state.
@@ -11349,7 +10967,8 @@ class StateEntries {
11349
10967
  }
11350
10968
  }
11351
10969
  /** https://graypaper.fluffylabs.dev/#/68eaa1f/391600391600?v=0.6.4 */
11352
- getRootHash() {
10970
+ getRootHash(blake2b) {
10971
+ const blake2bTrieHasher = getBlake2bTrieHasher(blake2b);
11353
10972
  const leaves = SortedSet.fromArray(leafComparator);
11354
10973
  for (const [key, value] of this) {
11355
10974
  leaves.insert(InMemoryTrie.constructLeaf(blake2bTrieHasher, key.asOpaque(), value));
@@ -11358,7 +10977,7 @@ class StateEntries {
11358
10977
  }
11359
10978
  }
11360
10979
  /** https://graypaper.fluffylabs.dev/#/68eaa1f/38a50038a500?v=0.6.4 */
11361
- function convertInMemoryStateToDictionary(spec, state) {
10980
+ function convertInMemoryStateToDictionary(spec, blake2b, state) {
11362
10981
  const serialized = TruncatedHashDictionary.fromEntries([]);
11363
10982
  function doSerialize(codec) {
11364
10983
  serialized.set(codec.key, Encoder.encodeObject(codec.Codec, codec.extract(state), spec));
@@ -11386,18 +11005,18 @@ function convertInMemoryStateToDictionary(spec, state) {
11386
11005
  serialized.set(key, Encoder.encodeObject(Codec, service.getInfo()));
11387
11006
  // preimages
11388
11007
  for (const preimage of service.data.preimages.values()) {
11389
- const { key, Codec } = serialize.servicePreimages(serviceId, preimage.hash);
11008
+ const { key, Codec } = serialize.servicePreimages(blake2b, serviceId, preimage.hash);
11390
11009
  serialized.set(key, Encoder.encodeObject(Codec, preimage.blob));
11391
11010
  }
11392
11011
  // storage
11393
11012
  for (const storage of service.data.storage.values()) {
11394
- const { key, Codec } = serialize.serviceStorage(serviceId, storage.key);
11013
+ const { key, Codec } = serialize.serviceStorage(blake2b, serviceId, storage.key);
11395
11014
  serialized.set(key, Encoder.encodeObject(Codec, storage.value));
11396
11015
  }
11397
11016
  // lookup history
11398
11017
  for (const lookupHistoryList of service.data.lookupHistory.values()) {
11399
11018
  for (const lookupHistory of lookupHistoryList) {
11400
- const { key, Codec } = serialize.serviceLookupHistory(serviceId, lookupHistory.hash, lookupHistory.length);
11019
+ const { key, Codec } = serialize.serviceLookupHistory(blake2b, serviceId, lookupHistory.hash, lookupHistory.length);
11401
11020
  serialized.set(key, Encoder.encodeObject(Codec, lookupHistory.slots.slice()));
11402
11021
  }
11403
11022
  }
@@ -11405,9 +11024,9 @@ function convertInMemoryStateToDictionary(spec, state) {
11405
11024
  return serialized;
11406
11025
  }
11407
11026
 
11408
- function loadState(spec, entries) {
11027
+ function loadState(spec, blake2b, entries) {
11409
11028
  const stateEntries = StateEntries.fromEntriesUnsafe(entries);
11410
- return SerializedState.fromStateEntries(spec, stateEntries);
11029
+ return SerializedState.fromStateEntries(spec, blake2b, stateEntries);
11411
11030
  }
11412
11031
 
11413
11032
  /**
@@ -11440,6 +11059,7 @@ var index$e = /*#__PURE__*/Object.freeze({
11440
11059
  __proto__: null,
11441
11060
  SerializedService: SerializedService,
11442
11061
  SerializedState: SerializedState,
11062
+ SerializedStateView: SerializedStateView,
11443
11063
  StateEntries: StateEntries,
11444
11064
  get StateEntryUpdateAction () { return StateEntryUpdateAction; },
11445
11065
  get StateKeyIdx () { return StateKeyIdx; },
@@ -11471,13 +11091,13 @@ class LeafDb {
11471
11091
  */
11472
11092
  static fromLeavesBlob(blob, db) {
11473
11093
  if (blob.length % TRIE_NODE_BYTES !== 0) {
11474
- return Result$1.error(LeafDbError.InvalidLeafData, `${blob.length} is not a multiply of ${TRIE_NODE_BYTES}: ${blob}`);
11094
+ return Result$1.error(LeafDbError.InvalidLeafData, () => `${blob.length} is not a multiply of ${TRIE_NODE_BYTES}: ${blob}`);
11475
11095
  }
11476
11096
  const leaves = SortedSet.fromArray(leafComparator, []);
11477
11097
  for (const nodeData of blob.chunks(TRIE_NODE_BYTES)) {
11478
11098
  const node = new TrieNode(nodeData.raw);
11479
11099
  if (node.getNodeType() === NodeType.Branch) {
11480
- return Result$1.error(LeafDbError.InvalidLeafData, `Branch node detected: ${nodeData}`);
11100
+ return Result$1.error(LeafDbError.InvalidLeafData, () => `Branch node detected: ${nodeData}`);
11481
11101
  }
11482
11102
  leaves.insert(node.asLeafNode());
11483
11103
  }
@@ -11515,7 +11135,8 @@ class LeafDb {
11515
11135
  }
11516
11136
  assertNever(val);
11517
11137
  }
11518
- getStateRoot() {
11138
+ getStateRoot(blake2b) {
11139
+ const blake2bTrieHasher = getBlake2bTrieHasher(blake2b);
11519
11140
  return InMemoryTrie.computeStateRoot(blake2bTrieHasher, this.leaves).asOpaque();
11520
11141
  }
11521
11142
  intoStateEntries() {
@@ -11631,7 +11252,11 @@ class ServiceWithCodec extends InMemoryService {
11631
11252
  return new ServiceWithCodec(serviceId, data);
11632
11253
  }
11633
11254
  }
11634
- const inMemoryStateCodec = codec$1.Class(InMemoryState, {
11255
+ const inMemoryStateCodec = (spec) => codec$1.Class(class State extends InMemoryState {
11256
+ static create(data) {
11257
+ return InMemoryState.new(spec, data);
11258
+ }
11259
+ }, {
11635
11260
  // alpha
11636
11261
  authPools: serialize.authPools.Codec,
11637
11262
  // phi
@@ -11705,11 +11330,12 @@ class InMemoryStates {
11705
11330
  }
11706
11331
  }
11707
11332
  async getStateRoot(state) {
11708
- return StateEntries.serializeInMemory(this.spec, state).getRootHash();
11333
+ const blake2b = await Blake2b.createHasher();
11334
+ return StateEntries.serializeInMemory(this.spec, blake2b, state).getRootHash(blake2b);
11709
11335
  }
11710
11336
  /** Insert a full state into the database. */
11711
11337
  async insertState(headerHash, state) {
11712
- const encoded = Encoder.encodeObject(inMemoryStateCodec, state, this.spec);
11338
+ const encoded = Encoder.encodeObject(inMemoryStateCodec(this.spec), state, this.spec);
11713
11339
  this.db.set(headerHash, encoded);
11714
11340
  return Result$1.ok(OK);
11715
11341
  }
@@ -11718,7 +11344,7 @@ class InMemoryStates {
11718
11344
  if (encodedState === undefined) {
11719
11345
  return null;
11720
11346
  }
11721
- return Decoder.decodeObject(inMemoryStateCodec, encodedState, this.spec);
11347
+ return Decoder.decodeObject(inMemoryStateCodec(this.spec), encodedState, this.spec);
11722
11348
  }
11723
11349
  }
11724
11350
 
@@ -11783,7 +11409,7 @@ function padAndEncodeData(input) {
11783
11409
  const paddedLength = Math.ceil(input.length / PIECE_SIZE) * PIECE_SIZE;
11784
11410
  let padded = input;
11785
11411
  if (input.length !== paddedLength) {
11786
- padded = BytesBlob.blobFrom(new Uint8Array(paddedLength));
11412
+ padded = BytesBlob.blobFrom(safeAllocUint8Array(paddedLength));
11787
11413
  padded.raw.set(input.raw, 0);
11788
11414
  }
11789
11415
  return chunkingFunction(padded);
@@ -11829,7 +11455,7 @@ function decodeData(input) {
11829
11455
  */
11830
11456
  function encodePoints(input) {
11831
11457
  const result = [];
11832
- const data = new Uint8Array(POINT_ALIGNMENT * N_CHUNKS_REQUIRED);
11458
+ const data = safeAllocUint8Array(POINT_ALIGNMENT * N_CHUNKS_REQUIRED);
11833
11459
  // add original shards to the result
11834
11460
  for (let i = 0; i < N_CHUNKS_REQUIRED; i++) {
11835
11461
  const pointStart = POINT_LENGTH * i;
@@ -11845,7 +11471,7 @@ function encodePoints(input) {
11845
11471
  const encodedData = encodedResult.take_data();
11846
11472
  for (let i = 0; i < N_CHUNKS_REDUNDANCY; i++) {
11847
11473
  const pointIndex = i * POINT_ALIGNMENT;
11848
- const redundancyPoint = new Uint8Array(POINT_LENGTH);
11474
+ const redundancyPoint = safeAllocUint8Array(POINT_LENGTH);
11849
11475
  for (let j = 0; j < POINT_LENGTH; j++) {
11850
11476
  redundancyPoint[j] = encodedData[pointIndex + j * HALF_POINT_SIZE];
11851
11477
  }
@@ -11860,7 +11486,7 @@ function encodePoints(input) {
11860
11486
  */
11861
11487
  function decodePiece(input) {
11862
11488
  const result = Bytes.zero(PIECE_SIZE);
11863
- const data = new Uint8Array(N_CHUNKS_REQUIRED * POINT_ALIGNMENT);
11489
+ const data = safeAllocUint8Array(N_CHUNKS_REQUIRED * POINT_ALIGNMENT);
11864
11490
  const indices = new Uint16Array(input.length);
11865
11491
  for (let i = 0; i < N_CHUNKS_REQUIRED; i++) {
11866
11492
  const [index, points] = input[i];
@@ -11976,7 +11602,7 @@ function lace(input) {
11976
11602
  return BytesBlob.empty();
11977
11603
  }
11978
11604
  const n = input[0].length;
11979
- const result = BytesBlob.blobFrom(new Uint8Array(k * n));
11605
+ const result = BytesBlob.blobFrom(safeAllocUint8Array(k * n));
11980
11606
  for (let i = 0; i < k; i++) {
11981
11607
  const entry = input[i].raw;
11982
11608
  for (let j = 0; j < n; j++) {
@@ -12655,6 +12281,8 @@ var NewServiceError;
12655
12281
  NewServiceError[NewServiceError["InsufficientFunds"] = 0] = "InsufficientFunds";
12656
12282
  /** Service is not privileged to set gratis storage. */
12657
12283
  NewServiceError[NewServiceError["UnprivilegedService"] = 1] = "UnprivilegedService";
12284
+ /** Registrar attempting to create a service with already existing id. */
12285
+ NewServiceError[NewServiceError["RegistrarServiceIdAlreadyTaken"] = 2] = "RegistrarServiceIdAlreadyTaken";
12658
12286
  })(NewServiceError || (NewServiceError = {}));
12659
12287
  var UpdatePrivilegesError;
12660
12288
  (function (UpdatePrivilegesError) {
@@ -12784,6 +12412,14 @@ const NoMachineError = Symbol("Machine index not found.");
12784
12412
  const SegmentExportError = Symbol("Too many segments already exported.");
12785
12413
 
12786
12414
  const InsufficientFundsError = "insufficient funds";
12415
+ /** Deep clone of a map with array. */
12416
+ function deepCloneMapWithArray(map) {
12417
+ const cloned = [];
12418
+ for (const [k, v] of map.entries()) {
12419
+ cloned.push([k, v.slice()]);
12420
+ }
12421
+ return new Map(cloned);
12422
+ }
12787
12423
  /**
12788
12424
  * State updates that currently accumulating service produced.
12789
12425
  *
@@ -12813,10 +12449,11 @@ class AccumulationStateUpdate {
12813
12449
  /** Create new empty state update. */
12814
12450
  static empty() {
12815
12451
  return new AccumulationStateUpdate({
12816
- servicesUpdates: [],
12817
- servicesRemoved: [],
12818
- preimages: [],
12819
- storage: [],
12452
+ created: [],
12453
+ updated: new Map(),
12454
+ removed: [],
12455
+ preimages: new Map(),
12456
+ storage: new Map(),
12820
12457
  }, []);
12821
12458
  }
12822
12459
  /** Create a state update with some existing, yet uncommited services updates. */
@@ -12828,10 +12465,13 @@ class AccumulationStateUpdate {
12828
12465
  /** Create a copy of another `StateUpdate`. Used by checkpoints. */
12829
12466
  static copyFrom(from) {
12830
12467
  const serviceUpdates = {
12831
- servicesUpdates: [...from.services.servicesUpdates],
12832
- servicesRemoved: [...from.services.servicesRemoved],
12833
- preimages: [...from.services.preimages],
12834
- storage: [...from.services.storage],
12468
+ // shallow copy
12469
+ created: [...from.services.created],
12470
+ updated: new Map(from.services.updated),
12471
+ removed: [...from.services.removed],
12472
+ // deep copy
12473
+ preimages: deepCloneMapWithArray(from.services.preimages),
12474
+ storage: deepCloneMapWithArray(from.services.storage),
12835
12475
  };
12836
12476
  const transfers = [...from.transfers];
12837
12477
  const update = new AccumulationStateUpdate(serviceUpdates, transfers, new Map(from.yieldedRoots));
@@ -12845,11 +12485,17 @@ class AccumulationStateUpdate {
12845
12485
  if (from.privilegedServices !== null) {
12846
12486
  update.privilegedServices = PrivilegedServices.create({
12847
12487
  ...from.privilegedServices,
12848
- authManager: asKnownSize([...from.privilegedServices.authManager]),
12488
+ assigners: asKnownSize([...from.privilegedServices.assigners]),
12849
12489
  });
12850
12490
  }
12851
12491
  return update;
12852
12492
  }
12493
+ /** Retrieve and clear pending transfers. */
12494
+ takeTransfers() {
12495
+ const transfers = this.transfers;
12496
+ this.transfers = [];
12497
+ return transfers;
12498
+ }
12853
12499
  }
12854
12500
  class PartiallyUpdatedState {
12855
12501
  state;
@@ -12873,9 +12519,9 @@ class PartiallyUpdatedState {
12873
12519
  if (destination === null) {
12874
12520
  return null;
12875
12521
  }
12876
- const maybeNewService = this.stateUpdate.services.servicesUpdates.find((update) => update.serviceId === destination);
12877
- if (maybeNewService !== undefined) {
12878
- return maybeNewService.action.account;
12522
+ const maybeUpdatedServiceInfo = this.stateUpdate.services.updated.get(destination);
12523
+ if (maybeUpdatedServiceInfo !== undefined) {
12524
+ return maybeUpdatedServiceInfo.action.account;
12879
12525
  }
12880
12526
  const maybeService = this.state.getService(destination);
12881
12527
  if (maybeService === null) {
@@ -12884,7 +12530,8 @@ class PartiallyUpdatedState {
12884
12530
  return maybeService.getInfo();
12885
12531
  }
12886
12532
  getStorage(serviceId, rawKey) {
12887
- const item = this.stateUpdate.services.storage.find((x) => x.serviceId === serviceId && x.key.isEqualTo(rawKey));
12533
+ const storages = this.stateUpdate.services.storage.get(serviceId) ?? [];
12534
+ const item = storages.find((x) => x.key.isEqualTo(rawKey));
12888
12535
  if (item !== undefined) {
12889
12536
  return item.value;
12890
12537
  }
@@ -12899,10 +12546,11 @@ class PartiallyUpdatedState {
12899
12546
  * the existence in `preimages` map.
12900
12547
  */
12901
12548
  hasPreimage(serviceId, hash) {
12902
- const providedPreimage = this.stateUpdate.services.preimages.find(
12549
+ const preimages = this.stateUpdate.services.preimages.get(serviceId) ?? [];
12550
+ const providedPreimage = preimages.find(
12903
12551
  // we ignore the action here, since if there is <any> update on that
12904
12552
  // hash it means it has to exist, right?
12905
- (p) => p.serviceId === serviceId && p.hash.isEqualTo(hash));
12553
+ (p) => p.hash.isEqualTo(hash));
12906
12554
  if (providedPreimage !== undefined) {
12907
12555
  return true;
12908
12556
  }
@@ -12915,7 +12563,8 @@ class PartiallyUpdatedState {
12915
12563
  }
12916
12564
  getPreimage(serviceId, hash) {
12917
12565
  // TODO [ToDr] Should we verify availability here?
12918
- const freshlyProvided = this.stateUpdate.services.preimages.find((x) => x.serviceId === serviceId && x.hash.isEqualTo(hash));
12566
+ const preimages = this.stateUpdate.services.preimages.get(serviceId) ?? [];
12567
+ const freshlyProvided = preimages.find((x) => x.hash.isEqualTo(hash));
12919
12568
  if (freshlyProvided !== undefined && freshlyProvided.action.kind === UpdatePreimageKind.Provide) {
12920
12569
  return freshlyProvided.action.preimage.blob;
12921
12570
  }
@@ -12924,10 +12573,11 @@ class PartiallyUpdatedState {
12924
12573
  }
12925
12574
  /** Get status of a preimage of current service taking into account any updates. */
12926
12575
  getLookupHistory(currentTimeslot, serviceId, hash, length) {
12576
+ const preimages = this.stateUpdate.services.preimages.get(serviceId) ?? [];
12927
12577
  // TODO [ToDr] This is most likely wrong. We may have `provide` and `remove` within
12928
12578
  // the same state update. We should however switch to proper "updated state"
12929
12579
  // representation soon.
12930
- const updatedPreimage = this.stateUpdate.services.preimages.findLast((update) => update.serviceId === serviceId && update.hash.isEqualTo(hash) && BigInt(update.length) === length);
12580
+ const updatedPreimage = preimages.findLast((update) => update.hash.isEqualTo(hash) && BigInt(update.length) === length);
12931
12581
  const stateFallback = () => {
12932
12582
  // fallback to state lookup
12933
12583
  const service = this.state.getService(serviceId);
@@ -12964,14 +12614,15 @@ class PartiallyUpdatedState {
12964
12614
  /* State update functions. */
12965
12615
  updateStorage(serviceId, key, value) {
12966
12616
  const update = value === null
12967
- ? UpdateStorage.remove({ serviceId, key })
12617
+ ? UpdateStorage.remove({ key })
12968
12618
  : UpdateStorage.set({
12969
- serviceId,
12970
12619
  storage: StorageItem.create({ key, value }),
12971
12620
  });
12972
- const index = this.stateUpdate.services.storage.findIndex((x) => x.serviceId === update.serviceId && x.key.isEqualTo(key));
12621
+ const storages = this.stateUpdate.services.storage.get(serviceId) ?? [];
12622
+ const index = storages.findIndex((x) => x.key.isEqualTo(key));
12973
12623
  const count = index === -1 ? 0 : 1;
12974
- this.stateUpdate.services.storage.splice(index, count, update);
12624
+ storages.splice(index, count, update);
12625
+ this.stateUpdate.services.storage.set(serviceId, storages);
12975
12626
  }
12976
12627
  /**
12977
12628
  * Update a preimage.
@@ -12979,8 +12630,10 @@ class PartiallyUpdatedState {
12979
12630
  * Note we store all previous entries as well, since there might be a sequence of:
12980
12631
  * `provide` -> `remove` and both should update the end state somehow.
12981
12632
  */
12982
- updatePreimage(newUpdate) {
12983
- this.stateUpdate.services.preimages.push(newUpdate);
12633
+ updatePreimage(serviceId, newUpdate) {
12634
+ const updatePreimages = this.stateUpdate.services.preimages.get(serviceId) ?? [];
12635
+ updatePreimages.push(newUpdate);
12636
+ this.stateUpdate.services.preimages.set(serviceId, updatePreimages);
12984
12637
  }
12985
12638
  updateServiceStorageUtilisation(serviceId, items, bytes, serviceInfo) {
12986
12639
  check `${items >= 0} storageUtilisationCount has to be a positive number, got: ${items}`;
@@ -12989,11 +12642,11 @@ class PartiallyUpdatedState {
12989
12642
  const overflowBytes = !isU64(bytes);
12990
12643
  // TODO [ToDr] this is not specified in GP, but it seems sensible.
12991
12644
  if (overflowItems || overflowBytes) {
12992
- return Result$1.error(InsufficientFundsError);
12645
+ return Result$1.error(InsufficientFundsError, () => `Storage utilisation overflow: items=${overflowItems}, bytes=${overflowBytes}`);
12993
12646
  }
12994
12647
  const thresholdBalance = ServiceAccountInfo.calculateThresholdBalance(items, bytes, serviceInfo.gratisStorage);
12995
12648
  if (serviceInfo.balance < thresholdBalance) {
12996
- return Result$1.error(InsufficientFundsError);
12649
+ return Result$1.error(InsufficientFundsError, () => `Service balance (${serviceInfo.balance}) below threshold (${thresholdBalance})`);
12997
12650
  }
12998
12651
  // Update service info with new details.
12999
12652
  this.updateServiceInfo(serviceId, ServiceAccountInfo.create({
@@ -13004,20 +12657,23 @@ class PartiallyUpdatedState {
13004
12657
  return Result$1.ok(OK);
13005
12658
  }
13006
12659
  updateServiceInfo(serviceId, newInfo) {
13007
- const idx = this.stateUpdate.services.servicesUpdates.findIndex((x) => x.serviceId === serviceId);
13008
- const toRemove = idx === -1 ? 0 : 1;
13009
- const existingItem = this.stateUpdate.services.servicesUpdates[idx];
13010
- if (existingItem?.action.kind === UpdateServiceKind.Create) {
13011
- this.stateUpdate.services.servicesUpdates.splice(idx, toRemove, UpdateService.create({
13012
- serviceId,
12660
+ const existingUpdate = this.stateUpdate.services.updated.get(serviceId);
12661
+ if (existingUpdate?.action.kind === UpdateServiceKind.Create) {
12662
+ this.stateUpdate.services.updated.set(serviceId, UpdateService.create({
13013
12663
  serviceInfo: newInfo,
13014
- lookupHistory: existingItem.action.lookupHistory,
12664
+ lookupHistory: existingUpdate.action.lookupHistory,
13015
12665
  }));
13016
12666
  return;
13017
12667
  }
13018
- this.stateUpdate.services.servicesUpdates.splice(idx, toRemove, UpdateService.update({
13019
- serviceId,
12668
+ this.stateUpdate.services.updated.set(serviceId, UpdateService.update({
12669
+ serviceInfo: newInfo,
12670
+ }));
12671
+ }
12672
+ createService(serviceId, newInfo, newLookupHistory) {
12673
+ this.stateUpdate.services.created.push(serviceId);
12674
+ this.stateUpdate.services.updated.set(serviceId, UpdateService.create({
13020
12675
  serviceInfo: newInfo,
12676
+ lookupHistory: newLookupHistory,
13021
12677
  }));
13022
12678
  }
13023
12679
  getPrivilegedServices() {
@@ -13046,7 +12702,7 @@ const HostCallResult = {
13046
12702
  OOB: tryAsU64(0xfffffffffffffffdn), // 2**64 - 3
13047
12703
  /** Index unknown. */
13048
12704
  WHO: tryAsU64(0xfffffffffffffffcn), // 2**64 - 4
13049
- /** Storage full. */
12705
+ /** Storage full or resource already allocated. */
13050
12706
  FULL: tryAsU64(0xfffffffffffffffbn), // 2**64 - 5
13051
12707
  /** Core index unknown. */
13052
12708
  CORE: tryAsU64(0xfffffffffffffffan), // 2**64 - 6
@@ -13054,7 +12710,7 @@ const HostCallResult = {
13054
12710
  CASH: tryAsU64(0xfffffffffffffff9n), // 2**64 - 7
13055
12711
  /** Gas limit too low. */
13056
12712
  LOW: tryAsU64(0xfffffffffffffff8n), // 2**64 - 8
13057
- /** The item is already solicited or cannot be forgotten. */
12713
+ /** The item is already solicited, cannot be forgotten or the operation is invalid due to privilege level. */
13058
12714
  HUH: tryAsU64(0xfffffffffffffff7n), // 2**64 - 9
13059
12715
  /** The return value indicating general success. */
13060
12716
  OK: tryAsU64(0n),
@@ -13255,7 +12911,7 @@ class Registers {
13255
12911
  bytes;
13256
12912
  asSigned;
13257
12913
  asUnsigned;
13258
- constructor(bytes = new Uint8Array(NO_OF_REGISTERS$1 << REGISTER_SIZE_SHIFT)) {
12914
+ constructor(bytes = safeAllocUint8Array(NO_OF_REGISTERS$1 << REGISTER_SIZE_SHIFT)) {
13259
12915
  this.bytes = bytes;
13260
12916
  check `${bytes.length === NO_OF_REGISTERS$1 << REGISTER_SIZE_SHIFT} Invalid size of registers array.`;
13261
12917
  this.asSigned = new BigInt64Array(bytes.buffer, bytes.byteOffset);
@@ -13327,10 +12983,16 @@ function signExtend32To64(value) {
13327
12983
 
13328
12984
  /** Attempt to convert a number into `HostCallIndex`. */
13329
12985
  const tryAsHostCallIndex = (v) => asOpaqueType(tryAsU32(v));
12986
+ /**
12987
+ * Host-call exit reason.
12988
+ *
12989
+ * https://graypaper.fluffylabs.dev/#/ab2cdbd/24a30124a501?v=0.7.2
12990
+ */
13330
12991
  var PvmExecution;
13331
12992
  (function (PvmExecution) {
13332
12993
  PvmExecution[PvmExecution["Halt"] = 0] = "Halt";
13333
12994
  PvmExecution[PvmExecution["Panic"] = 1] = "Panic";
12995
+ PvmExecution[PvmExecution["OOG"] = 2] = "OOG";
13334
12996
  })(PvmExecution || (PvmExecution = {}));
13335
12997
  /** A utility function to easily trace a bunch of registers. */
13336
12998
  function traceRegisters(...regs) {
@@ -13402,7 +13064,7 @@ class Mask {
13402
13064
  return Math.min(this.lookupTableForward[index] ?? 0, MAX_INSTRUCTION_DISTANCE);
13403
13065
  }
13404
13066
  buildLookupTableForward(mask) {
13405
- const table = new Uint8Array(mask.bitLength);
13067
+ const table = safeAllocUint8Array(mask.bitLength);
13406
13068
  let lastInstructionOffset = 0;
13407
13069
  for (let i = mask.bitLength - 1; i >= 0; i--) {
13408
13070
  if (mask.isSet(i)) {
@@ -14632,7 +14294,7 @@ class ReadablePage extends MemoryPage {
14632
14294
  loadInto(result, startIndex, length) {
14633
14295
  const endIndex = startIndex + length;
14634
14296
  if (endIndex > PAGE_SIZE$1) {
14635
- return Result$1.error(PageFault.fromMemoryIndex(this.start + PAGE_SIZE$1));
14297
+ return Result$1.error(PageFault.fromMemoryIndex(this.start + PAGE_SIZE$1), () => `Page fault: read beyond page boundary at ${this.start + PAGE_SIZE$1}`);
14636
14298
  }
14637
14299
  const bytes = this.data.subarray(startIndex, endIndex);
14638
14300
  // we zero the bytes, since data might not yet be initialized at `endIndex`.
@@ -14641,7 +14303,7 @@ class ReadablePage extends MemoryPage {
14641
14303
  return Result$1.ok(OK);
14642
14304
  }
14643
14305
  storeFrom(_address, _data) {
14644
- return Result$1.error(PageFault.fromMemoryIndex(this.start, true));
14306
+ return Result$1.error(PageFault.fromMemoryIndex(this.start, true), () => `Page fault: attempted to write to read-only page at ${this.start}`);
14645
14307
  }
14646
14308
  setData(pageIndex, data) {
14647
14309
  this.data.set(data, pageIndex);
@@ -14670,7 +14332,7 @@ class WriteablePage extends MemoryPage {
14670
14332
  loadInto(result, startIndex, length) {
14671
14333
  const endIndex = startIndex + length;
14672
14334
  if (endIndex > PAGE_SIZE$1) {
14673
- return Result$1.error(PageFault.fromMemoryIndex(this.start + PAGE_SIZE$1));
14335
+ return Result$1.error(PageFault.fromMemoryIndex(this.start + PAGE_SIZE$1), () => `Page fault: read beyond page boundary at ${this.start + PAGE_SIZE$1}`);
14674
14336
  }
14675
14337
  const bytes = this.view.subarray(startIndex, endIndex);
14676
14338
  // we zero the bytes, since the view might not yet be initialized at `endIndex`.
@@ -14740,7 +14402,7 @@ class Memory {
14740
14402
  logger$3.insane `MEM[${address}] <- ${BytesBlob.blobFrom(bytes)}`;
14741
14403
  const pagesResult = this.getPages(address, bytes.length, AccessType.WRITE);
14742
14404
  if (pagesResult.isError) {
14743
- return Result$1.error(pagesResult.error);
14405
+ return Result$1.error(pagesResult.error, pagesResult.details);
14744
14406
  }
14745
14407
  const pages = pagesResult.ok;
14746
14408
  let currentPosition = address;
@@ -14765,14 +14427,14 @@ class Memory {
14765
14427
  const pages = [];
14766
14428
  for (const pageNumber of pageRange) {
14767
14429
  if (pageNumber < RESERVED_NUMBER_OF_PAGES) {
14768
- return Result$1.error(PageFault.fromPageNumber(pageNumber, true));
14430
+ return Result$1.error(PageFault.fromPageNumber(pageNumber, true), () => `Page fault: attempted to access reserved page ${pageNumber}`);
14769
14431
  }
14770
14432
  const page = this.memory.get(pageNumber);
14771
14433
  if (page === undefined) {
14772
- return Result$1.error(PageFault.fromPageNumber(pageNumber));
14434
+ return Result$1.error(PageFault.fromPageNumber(pageNumber), () => `Page fault: page ${pageNumber} not allocated`);
14773
14435
  }
14774
14436
  if (accessType === AccessType.WRITE && !page.isWriteable()) {
14775
- return Result$1.error(PageFault.fromPageNumber(pageNumber, true));
14437
+ return Result$1.error(PageFault.fromPageNumber(pageNumber, true), () => `Page fault: attempted to write to read-only page ${pageNumber}`);
14776
14438
  }
14777
14439
  pages.push(page);
14778
14440
  }
@@ -14790,7 +14452,7 @@ class Memory {
14790
14452
  }
14791
14453
  const pagesResult = this.getPages(startAddress, result.length, AccessType.READ);
14792
14454
  if (pagesResult.isError) {
14793
- return Result$1.error(pagesResult.error);
14455
+ return Result$1.error(pagesResult.error, pagesResult.details);
14794
14456
  }
14795
14457
  const pages = pagesResult.ok;
14796
14458
  let currentPosition = startAddress;
@@ -15083,11 +14745,6 @@ class BitOps {
15083
14745
  }
15084
14746
  }
15085
14747
 
15086
- const MAX_VALUE = 4294967295;
15087
- const MIN_VALUE = -2147483648;
15088
- const MAX_SHIFT_U32 = 32;
15089
- const MAX_SHIFT_U64 = 64n;
15090
-
15091
14748
  /**
15092
14749
  * Overflowing addition for two-complement representation of 32-bit signed numbers.
15093
14750
  */
@@ -16600,7 +16257,7 @@ class ProgramDecoder {
16600
16257
  }
16601
16258
  catch (e) {
16602
16259
  logger$2.error `Invalid program: ${e}`;
16603
- return Result$1.error(ProgramDecoderError.InvalidProgramError);
16260
+ return Result$1.error(ProgramDecoderError.InvalidProgramError, () => `Program decoder error: ${e}`);
16604
16261
  }
16605
16262
  }
16606
16263
  }
@@ -16837,6 +16494,24 @@ class Interpreter {
16837
16494
  getMemoryPage(pageNumber) {
16838
16495
  return this.memory.getPageDump(tryAsPageNumber(pageNumber));
16839
16496
  }
16497
+ calculateBlockGasCost() {
16498
+ const codeLength = this.code.length;
16499
+ const blocks = new Map();
16500
+ let currentBlock = "0";
16501
+ let gasCost = 0;
16502
+ const getNextIstructionIndex = (index) => index + 1 + this.mask.getNoOfBytesToNextInstruction(index + 1);
16503
+ for (let index = 0; index < codeLength; index = getNextIstructionIndex(index)) {
16504
+ const instruction = this.code[index];
16505
+ if (this.basicBlocks.isBeginningOfBasicBlock(index)) {
16506
+ blocks.set(currentBlock, gasCost);
16507
+ currentBlock = index.toString();
16508
+ gasCost = 0;
16509
+ }
16510
+ gasCost += instructionGasMap[instruction];
16511
+ }
16512
+ blocks.set(currentBlock, gasCost);
16513
+ return blocks;
16514
+ }
16840
16515
  }
16841
16516
 
16842
16517
  var index$7 = /*#__PURE__*/Object.freeze({
@@ -16863,7 +16538,7 @@ class HostCallMemory {
16863
16538
  return Result$1.ok(OK);
16864
16539
  }
16865
16540
  if (address + tryAsU64(bytes.length) > MEMORY_SIZE) {
16866
- return Result$1.error(new OutOfBounds());
16541
+ return Result$1.error(new OutOfBounds(), () => `Memory access out of bounds: address ${address} + length ${bytes.length} exceeds memory size`);
16867
16542
  }
16868
16543
  return this.memory.storeFrom(tryAsMemoryIndex(Number(address)), bytes);
16869
16544
  }
@@ -16872,13 +16547,10 @@ class HostCallMemory {
16872
16547
  return Result$1.ok(OK);
16873
16548
  }
16874
16549
  if (startAddress + tryAsU64(result.length) > MEMORY_SIZE) {
16875
- return Result$1.error(new OutOfBounds());
16550
+ return Result$1.error(new OutOfBounds(), () => `Memory access out of bounds: address ${startAddress} + length ${result.length} exceeds memory size`);
16876
16551
  }
16877
16552
  return this.memory.loadInto(result, tryAsMemoryIndex(Number(startAddress)));
16878
16553
  }
16879
- getMemory() {
16880
- return this.memory;
16881
- }
16882
16554
  }
16883
16555
 
16884
16556
  class HostCallRegisters {
@@ -16937,7 +16609,7 @@ class HostCalls {
16937
16609
  const regs = pvmInstance.getRegisters();
16938
16610
  const maybeAddress = regs.getLowerU32(7);
16939
16611
  const maybeLength = regs.getLowerU32(8);
16940
- const result = new Uint8Array(maybeLength);
16612
+ const result = safeAllocUint8Array(maybeLength);
16941
16613
  const startAddress = tryAsMemoryIndex(maybeAddress);
16942
16614
  const loadResult = memory.loadInto(result, startAddress);
16943
16615
  if (loadResult.isError) {
@@ -16965,8 +16637,9 @@ class HostCalls {
16965
16637
  const index = tryAsHostCallIndex(hostCallIndex);
16966
16638
  const hostCall = this.hostCalls.get(index);
16967
16639
  const gasBefore = gas.get();
16968
- const gasCost = typeof hostCall.gasCost === "number" ? hostCall.gasCost : hostCall.gasCost(regs);
16969
- const underflow = gas.sub(gasCost);
16640
+ // NOTE: `basicGasCost(regs)` function is for compatibility reasons: pre GP 0.7.2
16641
+ const basicGasCost = typeof hostCall.basicGasCost === "number" ? hostCall.basicGasCost : hostCall.basicGasCost(regs);
16642
+ const underflow = gas.sub(basicGasCost);
16970
16643
  const pcLog = `[PC: ${pvmInstance.getPC()}]`;
16971
16644
  if (underflow) {
16972
16645
  this.hostCalls.traceHostCall(`${pcLog} OOG`, index, hostCall, regs, gas.get());
@@ -16983,6 +16656,10 @@ class HostCalls {
16983
16656
  status = Status.PANIC;
16984
16657
  return this.getReturnValue(status, pvmInstance);
16985
16658
  }
16659
+ if (result === PvmExecution.OOG) {
16660
+ status = Status.OOG;
16661
+ return this.getReturnValue(status, pvmInstance);
16662
+ }
16986
16663
  if (result === undefined) {
16987
16664
  pvmInstance.runProgram();
16988
16665
  status = pvmInstance.getStatus();
@@ -17281,14 +16958,14 @@ class DebuggerAdapter {
17281
16958
  const page = this.pvm.getMemoryPage(pageNumber);
17282
16959
  if (page === null) {
17283
16960
  // page wasn't allocated so we return an empty page
17284
- return new Uint8Array(PAGE_SIZE$1);
16961
+ return safeAllocUint8Array(PAGE_SIZE$1);
17285
16962
  }
17286
16963
  if (page.length === PAGE_SIZE$1) {
17287
16964
  // page was allocated and has a proper size so we can simply return it
17288
16965
  return page;
17289
16966
  }
17290
16967
  // page was allocated but it is shorter than PAGE_SIZE so we have to extend it
17291
- const fullPage = new Uint8Array(PAGE_SIZE$1);
16968
+ const fullPage = safeAllocUint8Array(PAGE_SIZE$1);
17292
16969
  fullPage.set(page);
17293
16970
  return fullPage;
17294
16971
  }
@@ -17392,7 +17069,7 @@ var index$3 = /*#__PURE__*/Object.freeze({
17392
17069
  extractCodeAndMetadata: extractCodeAndMetadata,
17393
17070
  getServiceId: getServiceId,
17394
17071
  getServiceIdOrCurrent: getServiceIdOrCurrent,
17395
- hash: index$p,
17072
+ hash: index$o,
17396
17073
  inspect: inspect,
17397
17074
  instructionArgumentTypeMap: instructionArgumentTypeMap,
17398
17075
  interpreter: index$7,
@@ -17414,10 +17091,10 @@ const ENTROPY_BYTES = 32;
17414
17091
  *
17415
17092
  * https://graypaper.fluffylabs.dev/#/579bd12/3b9a013b9a01
17416
17093
  */
17417
- function fisherYatesShuffle(arr, entropy) {
17094
+ function fisherYatesShuffle(blake2b, arr, entropy) {
17418
17095
  check `${entropy.length === ENTROPY_BYTES} Expected entropy of length ${ENTROPY_BYTES}, got ${entropy.length}`;
17419
17096
  const n = arr.length;
17420
- const randomNumbers = hashToNumberSequence(entropy, arr.length);
17097
+ const randomNumbers = hashToNumberSequence(blake2b, entropy, arr.length);
17421
17098
  const result = new Array(n);
17422
17099
  let itemsLeft = n;
17423
17100
  for (let i = 0; i < n; i++) {
@@ -17430,13 +17107,13 @@ function fisherYatesShuffle(arr, entropy) {
17430
17107
  }
17431
17108
  return result;
17432
17109
  }
17433
- function hashToNumberSequence(entropy, length) {
17110
+ function hashToNumberSequence(blake2b, entropy, length) {
17434
17111
  const result = new Array(length);
17435
- const randomBytes = new Uint8Array(ENTROPY_BYTES + 4);
17112
+ const randomBytes = safeAllocUint8Array(ENTROPY_BYTES + 4);
17436
17113
  randomBytes.set(entropy.raw);
17437
17114
  for (let i = 0; i < length; i++) {
17438
17115
  randomBytes.set(u32AsLeBytes(tryAsU32(Math.floor(i / 8))), ENTROPY_BYTES);
17439
- const newHash = hashBytes(randomBytes);
17116
+ const newHash = blake2b.hashBytes(randomBytes);
17440
17117
  const numberStartIndex = (4 * i) % 32;
17441
17118
  const numberEndIndex = numberStartIndex + 4;
17442
17119
  const number = leBytesAsU32(newHash.raw.subarray(numberStartIndex, numberEndIndex)) >>> 0;
@@ -17452,6 +17129,7 @@ var index$2 = /*#__PURE__*/Object.freeze({
17452
17129
 
17453
17130
  class JsonServiceInfo {
17454
17131
  static fromJson = json.object({
17132
+ ...(Compatibility.isGreaterOrEqual(GpVersion.V0_7_1) ? { version: "number" } : {}),
17455
17133
  code_hash: fromJson.bytes32(),
17456
17134
  balance: json.fromNumber((x) => tryAsU64(x)),
17457
17135
  min_item_gas: json.fromNumber((x) => tryAsServiceGas(x)),
@@ -17476,6 +17154,7 @@ class JsonServiceInfo {
17476
17154
  parentService: parent_service,
17477
17155
  });
17478
17156
  });
17157
+ version;
17479
17158
  code_hash;
17480
17159
  balance;
17481
17160
  min_item_gas;
@@ -17510,23 +17189,35 @@ const lookupMetaFromJson = json.object({
17510
17189
  },
17511
17190
  value: json.array("number"),
17512
17191
  }, ({ key, value }) => new LookupHistoryItem(key.hash, key.length, value));
17192
+ const preimageStatusFromJson = json.object({
17193
+ hash: fromJson.bytes32(),
17194
+ status: json.array("number"),
17195
+ }, ({ hash, status }) => new LookupHistoryItem(hash, tryAsU32(0), status));
17513
17196
  class JsonService {
17514
17197
  static fromJson = json.object({
17515
17198
  id: "number",
17516
- data: {
17517
- service: JsonServiceInfo.fromJson,
17518
- preimages: json.optional(json.array(JsonPreimageItem.fromJson)),
17519
- storage: json.optional(json.array(JsonStorageItem.fromJson)),
17520
- lookup_meta: json.optional(json.array(lookupMetaFromJson)),
17521
- },
17199
+ data: Compatibility.isLessThan(GpVersion.V0_7_1)
17200
+ ? {
17201
+ service: JsonServiceInfo.fromJson,
17202
+ preimages: json.optional(json.array(JsonPreimageItem.fromJson)),
17203
+ storage: json.optional(json.array(JsonStorageItem.fromJson)),
17204
+ lookup_meta: json.optional(json.array(lookupMetaFromJson)),
17205
+ }
17206
+ : {
17207
+ service: JsonServiceInfo.fromJson,
17208
+ storage: json.optional(json.array(JsonStorageItem.fromJson)),
17209
+ preimages_blob: json.optional(json.array(JsonPreimageItem.fromJson)),
17210
+ preimages_status: json.optional(json.array(preimageStatusFromJson)),
17211
+ },
17522
17212
  }, ({ id, data }) => {
17213
+ const preimages = HashDictionary.fromEntries((data.preimages ?? data.preimages_blob ?? []).map((x) => [x.hash, x]));
17523
17214
  const lookupHistory = HashDictionary.new();
17524
- for (const item of data.lookup_meta ?? []) {
17215
+ for (const item of data.lookup_meta ?? data.preimages_status ?? []) {
17525
17216
  const data = lookupHistory.get(item.hash) ?? [];
17526
- data.push(item);
17217
+ const length = tryAsU32(preimages.get(item.hash)?.blob.length ?? item.length);
17218
+ data.push(new LookupHistoryItem(item.hash, length, item.slots));
17527
17219
  lookupHistory.set(item.hash, data);
17528
17220
  }
17529
- const preimages = HashDictionary.fromEntries((data.preimages ?? []).map((x) => [x.hash, x]));
17530
17221
  const storage = new Map();
17531
17222
  const entries = (data.storage ?? []).map(({ key, value }) => {
17532
17223
  const opaqueKey = asOpaqueType(key);
@@ -17550,8 +17241,7 @@ const availabilityAssignmentFromJson = json.object({
17550
17241
  report: workReportFromJson,
17551
17242
  timeout: "number",
17552
17243
  }, ({ report, timeout }) => {
17553
- const workReportHash = hashBytes(Encoder.encodeObject(WorkReport.Codec, report)).asOpaque();
17554
- return AvailabilityAssignment.create({ workReport: new WithHash(workReportHash, report), timeout });
17244
+ return AvailabilityAssignment.create({ workReport: report, timeout });
17555
17245
  });
17556
17246
 
17557
17247
  const disputesRecordsFromJson = json.object({
@@ -17603,10 +17293,10 @@ const recentBlocksHistoryFromJson = json.object({
17603
17293
  peaks: json.array(json.nullable(fromJson.bytes32())),
17604
17294
  },
17605
17295
  }, ({ history, mmr }) => {
17606
- return RecentBlocksHistory.create(RecentBlocks.create({
17296
+ return RecentBlocks.create({
17607
17297
  blocks: history,
17608
17298
  accumulationLog: mmr,
17609
- }));
17299
+ });
17610
17300
  });
17611
17301
 
17612
17302
  const ticketFromJson = json.object({
@@ -17699,8 +17389,12 @@ class JsonServiceStatistics {
17699
17389
  extrinsic_count: "number",
17700
17390
  accumulate_count: "number",
17701
17391
  accumulate_gas_used: json.fromNumber(tryAsServiceGas),
17702
- on_transfers_count: "number",
17703
- on_transfers_gas_used: json.fromNumber(tryAsServiceGas),
17392
+ ...(Compatibility.isLessThan(GpVersion.V0_7_1)
17393
+ ? {
17394
+ on_transfers_count: "number",
17395
+ on_transfers_gas_used: json.fromNumber(tryAsServiceGas),
17396
+ }
17397
+ : {}),
17704
17398
  }, ({ 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, }) => {
17705
17399
  return ServiceStatistics.create({
17706
17400
  providedCount: provided_count,
@@ -17713,8 +17407,8 @@ class JsonServiceStatistics {
17713
17407
  extrinsicCount: extrinsic_count,
17714
17408
  accumulateCount: accumulate_count,
17715
17409
  accumulateGasUsed: accumulate_gas_used,
17716
- onTransfersCount: on_transfers_count,
17717
- onTransfersGasUsed: on_transfers_gas_used,
17410
+ onTransfersCount: on_transfers_count ?? tryAsU32(0),
17411
+ onTransfersGasUsed: on_transfers_gas_used ?? tryAsServiceGas(0),
17718
17412
  });
17719
17413
  });
17720
17414
  provided_count;
@@ -17785,6 +17479,7 @@ const fullStateDumpFromJson = (spec) => json.object({
17785
17479
  chi_m: "number",
17786
17480
  chi_a: json.array("number"),
17787
17481
  chi_v: "number",
17482
+ chi_r: json.optional("number"),
17788
17483
  chi_g: json.nullable(json.array({
17789
17484
  service: "number",
17790
17485
  gasLimit: json.fromNumber((v) => tryAsServiceGas(v)),
@@ -17796,7 +17491,10 @@ const fullStateDumpFromJson = (spec) => json.object({
17796
17491
  theta: json.nullable(json.array(accumulationOutput)),
17797
17492
  accounts: json.array(JsonService.fromJson),
17798
17493
  }, ({ alpha, varphi, beta, gamma, psi, eta, iota, kappa, lambda, rho, tau, chi, pi, omega, xi, theta, accounts, }) => {
17799
- return InMemoryState.create({
17494
+ if (Compatibility.isGreaterOrEqual(GpVersion.V0_7_1) && chi.chi_r === undefined) {
17495
+ throw new Error("Registrar is required in Privileges GP ^0.7.1");
17496
+ }
17497
+ return InMemoryState.new(spec, {
17800
17498
  authPools: tryAsPerCore(alpha.map((perCore) => {
17801
17499
  if (perCore.length > MAX_AUTH_POOL_SIZE) {
17802
17500
  throw new Error(`AuthPools: expected less than ${MAX_AUTH_POOL_SIZE}, got ${perCore.length}`);
@@ -17809,7 +17507,7 @@ const fullStateDumpFromJson = (spec) => json.object({
17809
17507
  }
17810
17508
  return asKnownSize(perCore);
17811
17509
  }), spec),
17812
- recentBlocks: beta ?? RecentBlocksHistory.empty(),
17510
+ recentBlocks: beta ?? RecentBlocks.empty(),
17813
17511
  nextValidatorData: gamma.gamma_k,
17814
17512
  epochRoot: gamma.gamma_z,
17815
17513
  sealingKeySeries: TicketsOrKeys.toSafroleSealingKeys(gamma.gamma_s, spec),
@@ -17823,8 +17521,9 @@ const fullStateDumpFromJson = (spec) => json.object({
17823
17521
  timeslot: tau,
17824
17522
  privilegedServices: PrivilegedServices.create({
17825
17523
  manager: chi.chi_m,
17826
- authManager: chi.chi_a,
17827
- validatorsManager: chi.chi_v,
17524
+ assigners: chi.chi_a,
17525
+ delegator: chi.chi_v,
17526
+ registrar: chi.chi_r ?? tryAsServiceId(2 ** 32 - 1),
17828
17527
  autoAccumulateServices: chi.chi_g ?? [],
17829
17528
  }),
17830
17529
  statistics: JsonStatisticsData.toStatisticsData(spec, pi),
@@ -17857,11 +17556,11 @@ var index$1 = /*#__PURE__*/Object.freeze({
17857
17556
  class TransitionHasher {
17858
17557
  context;
17859
17558
  keccakHasher;
17860
- allocator;
17861
- constructor(context, keccakHasher, allocator) {
17559
+ blake2b;
17560
+ constructor(context, keccakHasher, blake2b) {
17862
17561
  this.context = context;
17863
17562
  this.keccakHasher = keccakHasher;
17864
- this.allocator = allocator;
17563
+ this.blake2b = blake2b;
17865
17564
  }
17866
17565
  /** Concatenates two hashes and hash this concatenation */
17867
17566
  hashConcat(a, b) {
@@ -17872,7 +17571,7 @@ class TransitionHasher {
17872
17571
  }
17873
17572
  /** Creates hash from the block header view */
17874
17573
  header(header) {
17875
- return new WithHash(hashBytes(header.encoded(), this.allocator).asOpaque(), header);
17574
+ return new WithHash(this.blake2b.hashBytes(header.encoded()).asOpaque(), header);
17876
17575
  }
17877
17576
  /**
17878
17577
  * Merkle commitment of the extrinsic data
@@ -17881,25 +17580,25 @@ class TransitionHasher {
17881
17580
  */
17882
17581
  extrinsic(extrinsicView) {
17883
17582
  // https://graypaper.fluffylabs.dev/#/cc517d7/0cfb000cfb00?v=0.6.5
17884
- const guarantees = extrinsicView.guarantees
17583
+ const guaranteesCount = tryAsU32(extrinsicView.guarantees.view().length);
17584
+ const countEncoded = Encoder.encodeObject(codec$1.varU32, guaranteesCount);
17585
+ const guaranteesBlobs = extrinsicView.guarantees
17885
17586
  .view()
17886
17587
  .map((g) => g.view())
17887
- .map((guarantee) => {
17888
- const reportHash = hashBytes(guarantee.report.encoded(), this.allocator).asOpaque();
17889
- return BytesBlob.blobFromParts([
17890
- reportHash.raw,
17891
- guarantee.slot.encoded().raw,
17892
- guarantee.credentials.encoded().raw,
17893
- ]);
17894
- });
17895
- const guaranteeBlob = Encoder.encodeObject(codec$1.sequenceVarLen(dumpCodec), guarantees, this.context);
17896
- const et = hashBytes(extrinsicView.tickets.encoded(), this.allocator).asOpaque();
17897
- const ep = hashBytes(extrinsicView.preimages.encoded(), this.allocator).asOpaque();
17898
- const eg = hashBytes(guaranteeBlob, this.allocator).asOpaque();
17899
- const ea = hashBytes(extrinsicView.assurances.encoded(), this.allocator).asOpaque();
17900
- const ed = hashBytes(extrinsicView.disputes.encoded(), this.allocator).asOpaque();
17588
+ .reduce((aggregated, guarantee) => {
17589
+ const reportHash = this.blake2b.hashBytes(guarantee.report.encoded()).asOpaque();
17590
+ aggregated.push(reportHash.raw);
17591
+ aggregated.push(guarantee.slot.encoded().raw);
17592
+ aggregated.push(guarantee.credentials.encoded().raw);
17593
+ return aggregated;
17594
+ }, [countEncoded.raw]);
17595
+ const et = this.blake2b.hashBytes(extrinsicView.tickets.encoded()).asOpaque();
17596
+ const ep = this.blake2b.hashBytes(extrinsicView.preimages.encoded()).asOpaque();
17597
+ const eg = this.blake2b.hashBlobs(guaranteesBlobs).asOpaque();
17598
+ const ea = this.blake2b.hashBytes(extrinsicView.assurances.encoded()).asOpaque();
17599
+ const ed = this.blake2b.hashBytes(extrinsicView.disputes.encoded()).asOpaque();
17901
17600
  const encoded = BytesBlob.blobFromParts([et.raw, ep.raw, eg.raw, ea.raw, ed.raw]);
17902
- return new WithHashAndBytes(hashBytes(encoded, this.allocator).asOpaque(), extrinsicView, encoded);
17601
+ return new WithHashAndBytes(this.blake2b.hashBytes(encoded).asOpaque(), extrinsicView, encoded);
17903
17602
  }
17904
17603
  /** Creates hash for given WorkPackage */
17905
17604
  workPackage(workPackage) {
@@ -17908,7 +17607,7 @@ class TransitionHasher {
17908
17607
  encode(codec, data) {
17909
17608
  // TODO [ToDr] Use already allocated encoding destination and hash bytes from some arena.
17910
17609
  const encoded = Encoder.encodeObject(codec, data, this.context);
17911
- return new WithHashAndBytes(hashBytes(encoded, this.allocator).asOpaque(), data, encoded);
17610
+ return new WithHashAndBytes(this.blake2b.hashBytes(encoded).asOpaque(), data, encoded);
17912
17611
  }
17913
17612
  }
17914
17613
 
@@ -17921,8 +17620,10 @@ var PreimagesErrorCode;
17921
17620
  // TODO [SeKo] consider whether this module is the right place to remove expired preimages
17922
17621
  class Preimages {
17923
17622
  state;
17924
- constructor(state) {
17623
+ blake2b;
17624
+ constructor(state, blake2b) {
17925
17625
  this.state = state;
17626
+ this.blake2b = blake2b;
17926
17627
  }
17927
17628
  integrate(input) {
17928
17629
  // make sure lookup extrinsics are sorted and unique
@@ -17937,32 +17638,33 @@ class Preimages {
17937
17638
  }
17938
17639
  if (prevPreimage.requester > currPreimage.requester ||
17939
17640
  currPreimage.blob.compare(prevPreimage.blob).isLessOrEqual()) {
17940
- return Result$1.error(PreimagesErrorCode.PreimagesNotSortedUnique);
17641
+ return Result$1.error(PreimagesErrorCode.PreimagesNotSortedUnique, () => `Preimages not sorted/unique at index ${i}`);
17941
17642
  }
17942
17643
  }
17943
17644
  const { preimages, slot } = input;
17944
- const pendingChanges = [];
17645
+ const pendingChanges = new Map();
17945
17646
  // select preimages for integration
17946
17647
  for (const preimage of preimages) {
17947
17648
  const { requester, blob } = preimage;
17948
- const hash = hashBytes(blob).asOpaque();
17649
+ const hash = this.blake2b.hashBytes(blob).asOpaque();
17949
17650
  const service = this.state.getService(requester);
17950
17651
  if (service === null) {
17951
- return Result$1.error(PreimagesErrorCode.AccountNotFound);
17652
+ return Result$1.error(PreimagesErrorCode.AccountNotFound, () => `Service not found: ${requester}`);
17952
17653
  }
17953
17654
  const hasPreimage = service.hasPreimage(hash);
17954
17655
  const slots = service.getLookupHistory(hash, tryAsU32(blob.length));
17955
17656
  // https://graypaper.fluffylabs.dev/#/5f542d7/181800181900
17956
17657
  // https://graypaper.fluffylabs.dev/#/5f542d7/116f0011a500
17957
17658
  if (hasPreimage || slots === null || !LookupHistoryItem.isRequested(slots)) {
17958
- return Result$1.error(PreimagesErrorCode.PreimageUnneeded);
17659
+ return Result$1.error(PreimagesErrorCode.PreimageUnneeded, () => `Preimage unneeded: requester=${requester}, hash=${hash}, hasPreimage=${hasPreimage}, isRequested=${slots !== null && LookupHistoryItem.isRequested(slots)}`);
17959
17660
  }
17960
17661
  // https://graypaper.fluffylabs.dev/#/5f542d7/18c00018f300
17961
- pendingChanges.push(UpdatePreimage.provide({
17962
- serviceId: requester,
17662
+ const updates = pendingChanges.get(requester) ?? [];
17663
+ updates.push(UpdatePreimage.provide({
17963
17664
  preimage: PreimageItem.create({ hash, blob }),
17964
17665
  slot,
17965
17666
  }));
17667
+ pendingChanges.set(requester, updates);
17966
17668
  }
17967
17669
  return Result$1.ok({
17968
17670
  preimages: pendingChanges,
@@ -17970,146 +17672,11 @@ class Preimages {
17970
17672
  }
17971
17673
  }
17972
17674
 
17973
- class Missing {
17974
- index = tryAsHostCallIndex(2 ** 32 - 1);
17975
- gasCost = tryAsSmallGas(10);
17976
- currentServiceId = CURRENT_SERVICE_ID;
17977
- tracedRegisters = traceRegisters(7);
17978
- execute(_gas, regs, _memory) {
17979
- regs.set(7, HostCallResult.WHAT);
17980
- return Promise.resolve(undefined);
17981
- }
17982
- }
17983
-
17984
- var ServiceExecutorError;
17985
- (function (ServiceExecutorError) {
17986
- ServiceExecutorError[ServiceExecutorError["NoLookup"] = 0] = "NoLookup";
17987
- ServiceExecutorError[ServiceExecutorError["NoState"] = 1] = "NoState";
17988
- ServiceExecutorError[ServiceExecutorError["NoServiceCode"] = 2] = "NoServiceCode";
17989
- ServiceExecutorError[ServiceExecutorError["ServiceCodeMismatch"] = 3] = "ServiceCodeMismatch";
17990
- })(ServiceExecutorError || (ServiceExecutorError = {}));
17991
- class WorkPackageExecutor {
17992
- blocks;
17993
- state;
17994
- hasher;
17995
- constructor(blocks, state, hasher) {
17996
- this.blocks = blocks;
17997
- this.state = state;
17998
- this.hasher = hasher;
17999
- }
18000
- // TODO [ToDr] this while thing should be triple-checked with the GP.
18001
- // I'm currently implementing some dirty version for the demo.
18002
- async executeWorkPackage(pack) {
18003
- const headerHash = pack.context.lookupAnchor;
18004
- // execute authorisation first or is it already executed and we just need to check it?
18005
- const authExec = this.getServiceExecutor(
18006
- // TODO [ToDr] should this be anchor or lookupAnchor?
18007
- headerHash, pack.authCodeHost, pack.authCodeHash);
18008
- if (authExec.isError) {
18009
- // TODO [ToDr] most likely shouldn't be throw.
18010
- throw new Error(`Could not get authorization executor: ${authExec.error}`);
18011
- }
18012
- const pvm = authExec.ok;
18013
- const authGas = tryAsGas(15000n);
18014
- const result = await pvm.run(pack.parametrization, authGas);
18015
- if (!result.isEqualTo(pack.authorization)) {
18016
- throw new Error("Authorization is invalid.");
18017
- }
18018
- const results = [];
18019
- for (const item of pack.items) {
18020
- const exec = this.getServiceExecutor(headerHash, item.service, item.codeHash);
18021
- if (exec.isError) {
18022
- throw new Error(`Could not get item executor: ${exec.error}`);
18023
- }
18024
- const pvm = exec.ok;
18025
- const gasRatio = tryAsServiceGas(3000n);
18026
- const ret = await pvm.run(item.payload, tryAsGas(item.refineGasLimit)); // or accumulateGasLimit?
18027
- results.push(WorkResult.create({
18028
- serviceId: item.service,
18029
- codeHash: item.codeHash,
18030
- payloadHash: hashBytes(item.payload),
18031
- gas: gasRatio,
18032
- result: new WorkExecResult(WorkExecResultKind.ok, ret),
18033
- load: WorkRefineLoad.create({
18034
- gasUsed: tryAsServiceGas(5),
18035
- importedSegments: tryAsU32(0),
18036
- exportedSegments: tryAsU32(0),
18037
- extrinsicSize: tryAsU32(0),
18038
- extrinsicCount: tryAsU32(0),
18039
- }),
18040
- }));
18041
- }
18042
- const workPackage = this.hasher.workPackage(pack);
18043
- const workPackageSpec = WorkPackageSpec.create({
18044
- hash: workPackage.hash,
18045
- length: tryAsU32(workPackage.encoded.length),
18046
- erasureRoot: Bytes.zero(HASH_SIZE),
18047
- exportsRoot: Bytes.zero(HASH_SIZE).asOpaque(),
18048
- exportsCount: tryAsU16(0),
18049
- });
18050
- const coreIndex = tryAsCoreIndex(0);
18051
- const authorizerHash = Bytes.fill(HASH_SIZE, 5).asOpaque();
18052
- const workResults = FixedSizeArray.new(results, tryAsWorkItemsCount(results.length));
18053
- return Promise.resolve(WorkReport.create({
18054
- workPackageSpec,
18055
- context: pack.context,
18056
- coreIndex,
18057
- authorizerHash,
18058
- authorizationOutput: pack.authorization,
18059
- segmentRootLookup: [],
18060
- results: workResults,
18061
- authorizationGasUsed: tryAsServiceGas(0),
18062
- }));
18063
- }
18064
- getServiceExecutor(lookupAnchor, serviceId, expectedCodeHash) {
18065
- const header = this.blocks.getHeader(lookupAnchor);
18066
- if (header === null) {
18067
- return Result$1.error(ServiceExecutorError.NoLookup);
18068
- }
18069
- const state = this.state.getState(lookupAnchor);
18070
- if (state === null) {
18071
- return Result$1.error(ServiceExecutorError.NoState);
18072
- }
18073
- const service = state.getService(serviceId);
18074
- const serviceCodeHash = service?.getInfo().codeHash ?? null;
18075
- if (serviceCodeHash === null) {
18076
- return Result$1.error(ServiceExecutorError.NoServiceCode);
18077
- }
18078
- if (!serviceCodeHash.isEqualTo(expectedCodeHash)) {
18079
- return Result$1.error(ServiceExecutorError.ServiceCodeMismatch);
18080
- }
18081
- const serviceCode = service?.getPreimage(serviceCodeHash.asOpaque()) ?? null;
18082
- if (serviceCode === null) {
18083
- return Result$1.error(ServiceExecutorError.NoServiceCode);
18084
- }
18085
- return Result$1.ok(new PvmExecutor(serviceCode));
18086
- }
18087
- }
18088
- class PvmExecutor {
18089
- serviceCode;
18090
- pvm;
18091
- hostCalls = new HostCallsManager({ missing: new Missing() });
18092
- pvmInstanceManager = new InterpreterInstanceManager(4);
18093
- constructor(serviceCode) {
18094
- this.serviceCode = serviceCode;
18095
- this.pvm = new HostCalls(this.pvmInstanceManager, this.hostCalls);
18096
- }
18097
- async run(args, gas) {
18098
- const program = Program.fromSpi(this.serviceCode.raw, args.raw, true);
18099
- const result = await this.pvm.runProgram(program.code, 5, gas, program.registers, program.memory);
18100
- if (result.hasMemorySlice()) {
18101
- return BytesBlob.blobFrom(result.memorySlice);
18102
- }
18103
- return BytesBlob.empty();
18104
- }
18105
- }
18106
-
18107
17675
  var index = /*#__PURE__*/Object.freeze({
18108
17676
  __proto__: null,
18109
17677
  Preimages: Preimages,
18110
17678
  get PreimagesErrorCode () { return PreimagesErrorCode; },
18111
- TransitionHasher: TransitionHasher,
18112
- WorkPackageExecutor: WorkPackageExecutor
17679
+ TransitionHasher: TransitionHasher
18113
17680
  });
18114
17681
 
18115
17682
  exports.block = index$l;
@@ -18119,11 +17686,11 @@ exports.codec = index$q;
18119
17686
  exports.collections = index$n;
18120
17687
  exports.config = index$m;
18121
17688
  exports.config_node = index$h;
18122
- exports.crypto = index$o;
17689
+ exports.crypto = index$p;
18123
17690
  exports.database = index$d;
18124
17691
  exports.erasure_coding = index$c;
18125
17692
  exports.fuzz_proto = index$a;
18126
- exports.hash = index$p;
17693
+ exports.hash = index$o;
18127
17694
  exports.jam_host_calls = index$9;
18128
17695
  exports.json_parser = index$k;
18129
17696
  exports.logger = index$i;