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