@typeberry/lib 0.1.3 → 0.2.0-b6e3410

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 +747 -1370
  2. package/index.d.ts +833 -798
  3. package/index.js +746 -1369
  4. package/package.json +1 -1
package/index.cjs CHANGED
@@ -9,7 +9,7 @@ var GpVersion;
9
9
  (function (GpVersion) {
10
10
  GpVersion["V0_6_7"] = "0.6.7";
11
11
  GpVersion["V0_7_0"] = "0.7.0";
12
- GpVersion["V0_7_1"] = "0.7.1-preview";
12
+ GpVersion["V0_7_1"] = "0.7.1";
13
13
  GpVersion["V0_7_2"] = "0.7.2-preview";
14
14
  })(GpVersion || (GpVersion = {}));
15
15
  var TestSuite;
@@ -18,11 +18,11 @@ var TestSuite;
18
18
  TestSuite["JAMDUNA"] = "jamduna";
19
19
  })(TestSuite || (TestSuite = {}));
20
20
  const DEFAULT_SUITE = TestSuite.W3F_DAVXY;
21
- const ALL_VERSIONS_IN_ORDER = [GpVersion.V0_6_7, GpVersion.V0_7_0, GpVersion.V0_7_1, GpVersion.V0_7_2];
21
+ const DEFAULT_VERSION = GpVersion.V0_7_1;
22
22
  const env$1 = typeof process === "undefined" ? {} : process.env;
23
- const DEFAULT_VERSION = GpVersion.V0_7_0;
24
23
  let CURRENT_VERSION = parseCurrentVersion(env$1.GP_VERSION) ?? DEFAULT_VERSION;
25
24
  let CURRENT_SUITE = parseCurrentSuite(env$1.TEST_SUITE) ?? DEFAULT_SUITE;
25
+ const ALL_VERSIONS_IN_ORDER = [GpVersion.V0_6_7, GpVersion.V0_7_0, GpVersion.V0_7_1, GpVersion.V0_7_2];
26
26
  function parseCurrentVersion(env) {
27
27
  if (env === undefined) {
28
28
  return undefined;
@@ -38,8 +38,9 @@ function parseCurrentVersion(env) {
38
38
  }
39
39
  }
40
40
  function parseCurrentSuite(env) {
41
- if (env === undefined)
41
+ if (env === undefined) {
42
42
  return undefined;
43
+ }
43
44
  switch (env) {
44
45
  case TestSuite.W3F_DAVXY:
45
46
  case TestSuite.JAMDUNA:
@@ -332,6 +333,19 @@ const Result$1 = {
332
333
  },
333
334
  };
334
335
 
336
+ // about 2GB, the maximum ArrayBuffer length on Chrome confirmed by several sources:
337
+ // - https://issues.chromium.org/issues/40055619
338
+ // - https://stackoverflow.com/a/72124984
339
+ // - https://onnxruntime.ai/docs/tutorials/web/large-models.html#maximum-size-of-arraybuffer
340
+ const MAX_LENGTH$2 = 2145386496;
341
+ function safeAllocUint8Array(length) {
342
+ if (length > MAX_LENGTH$2) {
343
+ // biome-ignore lint/suspicious/noConsole: can't have a dependency on logger here
344
+ console.warn(`Trying to allocate ${length} bytes, which is greater than the maximum of ${MAX_LENGTH$2}.`);
345
+ }
346
+ return new Uint8Array(Math.min(MAX_LENGTH$2, length));
347
+ }
348
+
335
349
  /**
336
350
  * Utilities for tests.
337
351
  */
@@ -446,10 +460,12 @@ function deepEqual(actual, expected, { context = [], errorsCollector, ignore = [
446
460
  .sort((a, b) => {
447
461
  const aKey = `${a.key}`;
448
462
  const bKey = `${b.key}`;
449
- if (aKey < bKey)
463
+ if (aKey < bKey) {
450
464
  return -1;
451
- if (bKey < aKey)
465
+ }
466
+ if (bKey < aKey) {
452
467
  return 1;
468
+ }
453
469
  return 0;
454
470
  });
455
471
  };
@@ -572,6 +588,7 @@ var index$u = /*#__PURE__*/Object.freeze({
572
588
  DEFAULT_VERSION: DEFAULT_VERSION,
573
589
  ErrorsCollector: ErrorsCollector,
574
590
  get GpVersion () { return GpVersion; },
591
+ MAX_LENGTH: MAX_LENGTH$2,
575
592
  OK: OK,
576
593
  Result: Result$1,
577
594
  TEST_COMPARE_USING: TEST_COMPARE_USING,
@@ -586,6 +603,7 @@ var index$u = /*#__PURE__*/Object.freeze({
586
603
  isBrowser: isBrowser,
587
604
  measure: measure,
588
605
  resultToString: resultToString,
606
+ safeAllocUint8Array: safeAllocUint8Array,
589
607
  seeThrough: seeThrough,
590
608
  workspacePathFix: workspacePathFix
591
609
  });
@@ -609,7 +627,7 @@ class BitVec {
609
627
  * Create new [`BitVec`] with all values set to `false`.
610
628
  */
611
629
  static empty(bitLength) {
612
- const data = new Uint8Array(Math.ceil(bitLength / 8));
630
+ const data = safeAllocUint8Array(Math.ceil(bitLength / 8));
613
631
  return new BitVec(data, bitLength);
614
632
  }
615
633
  byteLength;
@@ -810,7 +828,7 @@ class BytesBlob {
810
828
  static blobFromParts(v, ...rest) {
811
829
  const vArr = v instanceof Uint8Array ? [v] : v;
812
830
  const totalLength = vArr.reduce((a, v) => a + v.length, 0) + rest.reduce((a, v) => a + v.length, 0);
813
- const buffer = new Uint8Array(totalLength);
831
+ const buffer = safeAllocUint8Array(totalLength);
814
832
  let offset = 0;
815
833
  for (const r of vArr) {
816
834
  buffer.set(r, offset);
@@ -883,7 +901,7 @@ class Bytes extends BytesBlob {
883
901
  }
884
902
  /** Create an empty [`Bytes<X>`] of given length. */
885
903
  static zero(len) {
886
- return new Bytes(new Uint8Array(len), len);
904
+ return new Bytes(safeAllocUint8Array(len), len);
887
905
  }
888
906
  // TODO [ToDr] `fill` should have the argments swapped to align with the rest.
889
907
  /** Create a [`Bytes<X>`] with all bytes filled with given input number. */
@@ -3592,7 +3610,7 @@ async function verify(input) {
3592
3610
  return Promise.resolve([]);
3593
3611
  }
3594
3612
  const dataLength = input.reduce((acc, { message, key, signature }) => acc + key.length + signature.length + message.length + 1, 0);
3595
- const data = new Uint8Array(dataLength);
3613
+ const data = safeAllocUint8Array(dataLength);
3596
3614
  let offset = 0;
3597
3615
  for (const { key, message, signature } of input) {
3598
3616
  data.set(key.raw, offset);
@@ -3639,823 +3657,75 @@ var ed25519 = /*#__PURE__*/Object.freeze({
3639
3657
  verifyBatch: verifyBatch
3640
3658
  });
3641
3659
 
3660
+ const SEED_SIZE = 32;
3661
+ const ED25519_SECRET_KEY = Bytes.blobFromString("jam_val_key_ed25519");
3662
+ const BANDERSNATCH_SECRET_KEY = Bytes.blobFromString("jam_val_key_bandersnatch");
3642
3663
  /**
3643
- * Size of the output of the hash functions.
3644
- *
3645
- * https://graypaper.fluffylabs.dev/#/579bd12/073101073c01
3664
+ * JIP-5: Secret key derivation
3646
3665
  *
3647
- */
3648
- const HASH_SIZE = 32;
3649
- /** A hash without last byte (useful for trie representation). */
3650
- const TRUNCATED_HASH_SIZE = 31;
3651
- const ZERO_HASH = Bytes.zero(HASH_SIZE);
3666
+ * https://github.com/polkadot-fellows/JIPs/blob/7048f79edf4f4eb8bfe6fb42e6bbf61900f44c65/JIP-5.md */
3652
3667
  /**
3653
- * Container for some object with a hash that is related to this object.
3654
- *
3655
- * After calculating the hash these two should be passed together to avoid
3656
- * unnecessary re-hashing of the data.
3668
+ * Deriving a 32-byte seed from a 32-bit unsigned integer
3669
+ * https://github.com/polkadot-fellows/JIPs/blob/7048f79edf4f4eb8bfe6fb42e6bbf61900f44c65/JIP-5.md#trivial-seeds
3657
3670
  */
3658
- class WithHash extends WithDebug {
3659
- hash;
3660
- data;
3661
- constructor(hash, data) {
3662
- super();
3663
- this.hash = hash;
3664
- this.data = data;
3665
- }
3671
+ function trivialSeed(s) {
3672
+ const s_le = u32AsLeBytes(s);
3673
+ return Bytes.fromBlob(BytesBlob.blobFromParts([s_le, s_le, s_le, s_le, s_le, s_le, s_le, s_le]).raw, SEED_SIZE).asOpaque();
3666
3674
  }
3667
3675
  /**
3668
- * Extension of [`WithHash`] additionally containing an encoded version of the object.
3676
+ * Derives a Ed25519 secret key from a seed.
3677
+ * https://github.com/polkadot-fellows/JIPs/blob/7048f79edf4f4eb8bfe6fb42e6bbf61900f44c65/JIP-5.md#derivation-method
3669
3678
  */
3670
- class WithHashAndBytes extends WithHash {
3671
- encoded;
3672
- constructor(hash, data, encoded) {
3673
- super(hash, data);
3674
- this.encoded = encoded;
3675
- }
3676
- }
3677
-
3678
- /** The simplest allocator returning just a fresh copy of bytes each time. */
3679
- class SimpleAllocator {
3680
- emptyHash() {
3681
- return Bytes.zero(HASH_SIZE);
3682
- }
3683
- }
3684
- /** An allocator that works by allocating larger (continuous) pages of memory. */
3685
- class PageAllocator {
3686
- hashesPerPage;
3687
- page = new Uint8Array(0);
3688
- currentHash = 0;
3689
- // TODO [ToDr] Benchmark the performance!
3690
- constructor(hashesPerPage) {
3691
- this.hashesPerPage = hashesPerPage;
3692
- check `${hashesPerPage > 0 && hashesPerPage >>> 0 === hashesPerPage} Expected a non-zero integer.`;
3693
- this.resetPage();
3694
- }
3695
- resetPage() {
3696
- const pageSizeBytes = this.hashesPerPage * HASH_SIZE;
3697
- this.currentHash = 0;
3698
- this.page = new Uint8Array(pageSizeBytes);
3699
- }
3700
- emptyHash() {
3701
- const startIdx = this.currentHash * HASH_SIZE;
3702
- const endIdx = startIdx + HASH_SIZE;
3703
- this.currentHash += 1;
3704
- if (this.currentHash >= this.hashesPerPage) {
3705
- this.resetPage();
3706
- }
3707
- return Bytes.fromBlob(this.page.subarray(startIdx, endIdx), HASH_SIZE);
3708
- }
3709
- }
3710
- const defaultAllocator = new SimpleAllocator();
3711
-
3712
- function getDefaultExportFromCjs (x) {
3713
- return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
3714
- }
3715
-
3716
- var blake2b$3 = {exports: {}};
3717
-
3718
- var nanoassert;
3719
- var hasRequiredNanoassert;
3720
-
3721
- function requireNanoassert () {
3722
- if (hasRequiredNanoassert) return nanoassert;
3723
- hasRequiredNanoassert = 1;
3724
- nanoassert = assert;
3725
-
3726
- class AssertionError extends Error {}
3727
- AssertionError.prototype.name = 'AssertionError';
3728
-
3729
- /**
3730
- * Minimal assert function
3731
- * @param {any} t Value to check if falsy
3732
- * @param {string=} m Optional assertion error message
3733
- * @throws {AssertionError}
3734
- */
3735
- function assert (t, m) {
3736
- if (!t) {
3737
- var err = new AssertionError(m);
3738
- if (Error.captureStackTrace) Error.captureStackTrace(err, assert);
3739
- throw err
3740
- }
3741
- }
3742
- return nanoassert;
3743
- }
3744
-
3745
- var blake2bWasm = {exports: {}};
3746
-
3747
- var b4a;
3748
- var hasRequiredB4a;
3749
-
3750
- function requireB4a () {
3751
- if (hasRequiredB4a) return b4a;
3752
- hasRequiredB4a = 1;
3753
- function isBuffer (value) {
3754
- return Buffer.isBuffer(value) || value instanceof Uint8Array
3755
- }
3756
-
3757
- function isEncoding (encoding) {
3758
- return Buffer.isEncoding(encoding)
3759
- }
3760
-
3761
- function alloc (size, fill, encoding) {
3762
- return Buffer.alloc(size, fill, encoding)
3763
- }
3764
-
3765
- function allocUnsafe (size) {
3766
- return Buffer.allocUnsafe(size)
3767
- }
3768
-
3769
- function allocUnsafeSlow (size) {
3770
- return Buffer.allocUnsafeSlow(size)
3771
- }
3772
-
3773
- function byteLength (string, encoding) {
3774
- return Buffer.byteLength(string, encoding)
3775
- }
3776
-
3777
- function compare (a, b) {
3778
- return Buffer.compare(a, b)
3779
- }
3780
-
3781
- function concat (buffers, totalLength) {
3782
- return Buffer.concat(buffers, totalLength)
3783
- }
3784
-
3785
- function copy (source, target, targetStart, start, end) {
3786
- return toBuffer(source).copy(target, targetStart, start, end)
3787
- }
3788
-
3789
- function equals (a, b) {
3790
- return toBuffer(a).equals(b)
3791
- }
3792
-
3793
- function fill (buffer, value, offset, end, encoding) {
3794
- return toBuffer(buffer).fill(value, offset, end, encoding)
3795
- }
3796
-
3797
- function from (value, encodingOrOffset, length) {
3798
- return Buffer.from(value, encodingOrOffset, length)
3799
- }
3800
-
3801
- function includes (buffer, value, byteOffset, encoding) {
3802
- return toBuffer(buffer).includes(value, byteOffset, encoding)
3803
- }
3804
-
3805
- function indexOf (buffer, value, byfeOffset, encoding) {
3806
- return toBuffer(buffer).indexOf(value, byfeOffset, encoding)
3807
- }
3808
-
3809
- function lastIndexOf (buffer, value, byteOffset, encoding) {
3810
- return toBuffer(buffer).lastIndexOf(value, byteOffset, encoding)
3811
- }
3812
-
3813
- function swap16 (buffer) {
3814
- return toBuffer(buffer).swap16()
3815
- }
3816
-
3817
- function swap32 (buffer) {
3818
- return toBuffer(buffer).swap32()
3819
- }
3820
-
3821
- function swap64 (buffer) {
3822
- return toBuffer(buffer).swap64()
3823
- }
3824
-
3825
- function toBuffer (buffer) {
3826
- if (Buffer.isBuffer(buffer)) return buffer
3827
- return Buffer.from(buffer.buffer, buffer.byteOffset, buffer.byteLength)
3828
- }
3829
-
3830
- function toString (buffer, encoding, start, end) {
3831
- return toBuffer(buffer).toString(encoding, start, end)
3832
- }
3833
-
3834
- function write (buffer, string, offset, length, encoding) {
3835
- return toBuffer(buffer).write(string, offset, length, encoding)
3836
- }
3837
-
3838
- function writeDoubleLE (buffer, value, offset) {
3839
- return toBuffer(buffer).writeDoubleLE(value, offset)
3840
- }
3841
-
3842
- function writeFloatLE (buffer, value, offset) {
3843
- return toBuffer(buffer).writeFloatLE(value, offset)
3844
- }
3845
-
3846
- function writeUInt32LE (buffer, value, offset) {
3847
- return toBuffer(buffer).writeUInt32LE(value, offset)
3848
- }
3849
-
3850
- function writeInt32LE (buffer, value, offset) {
3851
- return toBuffer(buffer).writeInt32LE(value, offset)
3852
- }
3853
-
3854
- function readDoubleLE (buffer, offset) {
3855
- return toBuffer(buffer).readDoubleLE(offset)
3856
- }
3857
-
3858
- function readFloatLE (buffer, offset) {
3859
- return toBuffer(buffer).readFloatLE(offset)
3860
- }
3861
-
3862
- function readUInt32LE (buffer, offset) {
3863
- return toBuffer(buffer).readUInt32LE(offset)
3864
- }
3865
-
3866
- function readInt32LE (buffer, offset) {
3867
- return toBuffer(buffer).readInt32LE(offset)
3868
- }
3869
-
3870
- b4a = {
3871
- isBuffer,
3872
- isEncoding,
3873
- alloc,
3874
- allocUnsafe,
3875
- allocUnsafeSlow,
3876
- byteLength,
3877
- compare,
3878
- concat,
3879
- copy,
3880
- equals,
3881
- fill,
3882
- from,
3883
- includes,
3884
- indexOf,
3885
- lastIndexOf,
3886
- swap16,
3887
- swap32,
3888
- swap64,
3889
- toBuffer,
3890
- toString,
3891
- write,
3892
- writeDoubleLE,
3893
- writeFloatLE,
3894
- writeUInt32LE,
3895
- writeInt32LE,
3896
- readDoubleLE,
3897
- readFloatLE,
3898
- readUInt32LE,
3899
- readInt32LE
3900
- };
3901
- return b4a;
3902
- }
3903
-
3904
- var blake2b$2;
3905
- var hasRequiredBlake2b$1;
3906
-
3907
- function requireBlake2b$1 () {
3908
- if (hasRequiredBlake2b$1) return blake2b$2;
3909
- hasRequiredBlake2b$1 = 1;
3910
- var __commonJS = (cb, mod) => function __require() {
3911
- return mod || (0, cb[Object.keys(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
3912
- };
3913
- var __toBinary = /* @__PURE__ */ (() => {
3914
- var table = new Uint8Array(128);
3915
- for (var i = 0; i < 64; i++)
3916
- table[i < 26 ? i + 65 : i < 52 ? i + 71 : i < 62 ? i - 4 : i * 4 - 205] = i;
3917
- return (base64) => {
3918
- var n = base64.length, bytes2 = new Uint8Array((n - (base64[n - 1] == "=") - (base64[n - 2] == "=")) * 3 / 4 | 0);
3919
- for (var i2 = 0, j = 0; i2 < n; ) {
3920
- var c0 = table[base64.charCodeAt(i2++)], c1 = table[base64.charCodeAt(i2++)];
3921
- var c2 = table[base64.charCodeAt(i2++)], c3 = table[base64.charCodeAt(i2++)];
3922
- bytes2[j++] = c0 << 2 | c1 >> 4;
3923
- bytes2[j++] = c1 << 4 | c2 >> 2;
3924
- bytes2[j++] = c2 << 6 | c3;
3925
- }
3926
- return bytes2;
3927
- };
3928
- })();
3929
-
3930
- // wasm-binary:./blake2b.wat
3931
- var require_blake2b = __commonJS({
3932
- "wasm-binary:./blake2b.wat"(exports2, module2) {
3933
- module2.exports = __toBinary("AGFzbQEAAAABEANgAn9/AGADf39/AGABfwADBQQAAQICBQUBAQroBwdNBQZtZW1vcnkCAAxibGFrZTJiX2luaXQAAA5ibGFrZTJiX3VwZGF0ZQABDWJsYWtlMmJfZmluYWwAAhBibGFrZTJiX2NvbXByZXNzAAMKvz8EwAIAIABCADcDACAAQgA3AwggAEIANwMQI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oVCP4ohBSABIAUgH3x8IQEgDSABhUIgiiENIAkgDXwhCSAFIAmFQhiKIQUgASAFIBt8fCEBIA0gAYVCEIohDSAJIA18IQkgBSAJhUI/iiEFIAIgBiAVfHwhAiAOIAKFQiCKIQ4gCiAOfCEKIAYgCoVCGIohBiACIAYgGXx8IQIgDiAChUIQiiEOIAogDnwhCiAGIAqFQj+KIQYgAyAHIBp8fCEDIA8gA4VCIIohDyALIA98IQsgByALhUIYiiEHIAMgByAgfHwhAyAPIAOFQhCKIQ8gCyAPfCELIAcgC4VCP4ohByAEIAggHnx8IQQgECAEhUIgiiEQIAwgEHwhDCAIIAyFQhiKIQggBCAIIBd8fCEEIBAgBIVCEIohECAMIBB8IQwgCCAMhUI/iiEIIAEgBiASfHwhASAQIAGFQiCKIRAgCyAQfCELIAYgC4VCGIohBiABIAYgHXx8IQEgECABhUIQiiEQIAsgEHwhCyAGIAuFQj+KIQYgAiAHIBF8fCECIA0gAoVCIIohDSAMIA18IQwgByAMhUIYiiEHIAIgByATfHwhAiANIAKFQhCKIQ0gDCANfCEMIAcgDIVCP4ohByADIAggHHx8IQMgDiADhUIgiiEOIAkgDnwhCSAIIAmFQhiKIQggAyAIIBh8fCEDIA4gA4VCEIohDiAJIA58IQkgCCAJhUI/iiEIIAQgBSAWfHwhBCAPIASFQiCKIQ8gCiAPfCEKIAUgCoVCGIohBSAEIAUgFHx8IQQgDyAEhUIQiiEPIAogD3whCiAFIAqFQj+KIQUgISAhKQMAIAEgCYWFNwMAICIgIikDACACIAqFhTcDACAjICMpAwAgAyALhYU3AwAgJCAkKQMAIAQgDIWFNwMAICUgJSkDACAFIA2FhTcDACAmICYpAwAgBiAOhYU3AwAgJyAnKQMAIAcgD4WFNwMAICggKCkDACAIIBCFhTcDAAs=");
3934
- }
3935
- });
3936
-
3937
- // wasm-module:./blake2b.wat
3938
- var bytes = require_blake2b();
3939
- var compiled = WebAssembly.compile(bytes);
3940
- blake2b$2 = async (imports) => {
3941
- const instance = await WebAssembly.instantiate(await compiled, imports);
3942
- return instance.exports;
3943
- };
3944
- return blake2b$2;
3945
- }
3946
-
3947
- var hasRequiredBlake2bWasm;
3948
-
3949
- function requireBlake2bWasm () {
3950
- if (hasRequiredBlake2bWasm) return blake2bWasm.exports;
3951
- hasRequiredBlake2bWasm = 1;
3952
- var assert = /*@__PURE__*/ requireNanoassert();
3953
- var b4a = /*@__PURE__*/ requireB4a();
3954
-
3955
- var wasm = null;
3956
- var wasmPromise = typeof WebAssembly !== "undefined" && /*@__PURE__*/ requireBlake2b$1()().then(mod => {
3957
- wasm = mod;
3958
- });
3959
-
3960
- var head = 64;
3961
- var freeList = [];
3962
-
3963
- blake2bWasm.exports = Blake2b;
3964
- var BYTES_MIN = blake2bWasm.exports.BYTES_MIN = 16;
3965
- var BYTES_MAX = blake2bWasm.exports.BYTES_MAX = 64;
3966
- blake2bWasm.exports.BYTES = 32;
3967
- var KEYBYTES_MIN = blake2bWasm.exports.KEYBYTES_MIN = 16;
3968
- var KEYBYTES_MAX = blake2bWasm.exports.KEYBYTES_MAX = 64;
3969
- blake2bWasm.exports.KEYBYTES = 32;
3970
- var SALTBYTES = blake2bWasm.exports.SALTBYTES = 16;
3971
- var PERSONALBYTES = blake2bWasm.exports.PERSONALBYTES = 16;
3972
-
3973
- function Blake2b (digestLength, key, salt, personal, noAssert) {
3974
- if (!(this instanceof Blake2b)) return new Blake2b(digestLength, key, salt, personal, noAssert)
3975
- if (!wasm) throw new Error('WASM not loaded. Wait for Blake2b.ready(cb)')
3976
- if (!digestLength) digestLength = 32;
3977
-
3978
- if (noAssert !== true) {
3979
- assert(digestLength >= BYTES_MIN, 'digestLength must be at least ' + BYTES_MIN + ', was given ' + digestLength);
3980
- assert(digestLength <= BYTES_MAX, 'digestLength must be at most ' + BYTES_MAX + ', was given ' + digestLength);
3981
- if (key != null) {
3982
- assert(key instanceof Uint8Array, 'key must be Uint8Array or Buffer');
3983
- assert(key.length >= KEYBYTES_MIN, 'key must be at least ' + KEYBYTES_MIN + ', was given ' + key.length);
3984
- assert(key.length <= KEYBYTES_MAX, 'key must be at least ' + KEYBYTES_MAX + ', was given ' + key.length);
3985
- }
3986
- if (salt != null) {
3987
- assert(salt instanceof Uint8Array, 'salt must be Uint8Array or Buffer');
3988
- assert(salt.length === SALTBYTES, 'salt must be exactly ' + SALTBYTES + ', was given ' + salt.length);
3989
- }
3990
- if (personal != null) {
3991
- assert(personal instanceof Uint8Array, 'personal must be Uint8Array or Buffer');
3992
- assert(personal.length === PERSONALBYTES, 'personal must be exactly ' + PERSONALBYTES + ', was given ' + personal.length);
3993
- }
3994
- }
3995
-
3996
- if (!freeList.length) {
3997
- freeList.push(head);
3998
- head += 216;
3999
- }
4000
-
4001
- this.digestLength = digestLength;
4002
- this.finalized = false;
4003
- this.pointer = freeList.pop();
4004
- this._memory = new Uint8Array(wasm.memory.buffer);
4005
-
4006
- this._memory.fill(0, 0, 64);
4007
- this._memory[0] = this.digestLength;
4008
- this._memory[1] = key ? key.length : 0;
4009
- this._memory[2] = 1; // fanout
4010
- this._memory[3] = 1; // depth
4011
-
4012
- if (salt) this._memory.set(salt, 32);
4013
- if (personal) this._memory.set(personal, 48);
4014
-
4015
- if (this.pointer + 216 > this._memory.length) this._realloc(this.pointer + 216); // we need 216 bytes for the state
4016
- wasm.blake2b_init(this.pointer, this.digestLength);
4017
-
4018
- if (key) {
4019
- this.update(key);
4020
- this._memory.fill(0, head, head + key.length); // whiteout key
4021
- this._memory[this.pointer + 200] = 128;
4022
- }
4023
- }
4024
-
4025
- Blake2b.prototype._realloc = function (size) {
4026
- wasm.memory.grow(Math.max(0, Math.ceil(Math.abs(size - this._memory.length) / 65536)));
4027
- this._memory = new Uint8Array(wasm.memory.buffer);
4028
- };
4029
-
4030
- Blake2b.prototype.update = function (input) {
4031
- assert(this.finalized === false, 'Hash instance finalized');
4032
- assert(input instanceof Uint8Array, 'input must be Uint8Array or Buffer');
4033
-
4034
- if (head + input.length > this._memory.length) this._realloc(head + input.length);
4035
- this._memory.set(input, head);
4036
- wasm.blake2b_update(this.pointer, head, head + input.length);
4037
- return this
4038
- };
4039
-
4040
- Blake2b.prototype.digest = function (enc) {
4041
- assert(this.finalized === false, 'Hash instance finalized');
4042
- this.finalized = true;
4043
-
4044
- freeList.push(this.pointer);
4045
- wasm.blake2b_final(this.pointer);
4046
-
4047
- if (!enc || enc === 'binary') {
4048
- return this._memory.slice(this.pointer + 128, this.pointer + 128 + this.digestLength)
4049
- }
4050
-
4051
- if (typeof enc === 'string') {
4052
- return b4a.toString(this._memory, enc, this.pointer + 128, this.pointer + 128 + this.digestLength)
4053
- }
4054
-
4055
- assert(enc instanceof Uint8Array && enc.length >= this.digestLength, 'input must be Uint8Array or Buffer');
4056
- for (var i = 0; i < this.digestLength; i++) {
4057
- enc[i] = this._memory[this.pointer + 128 + i];
4058
- }
4059
-
4060
- return enc
4061
- };
4062
-
4063
- // libsodium compat
4064
- Blake2b.prototype.final = Blake2b.prototype.digest;
4065
-
4066
- Blake2b.WASM = wasm;
4067
- Blake2b.SUPPORTED = typeof WebAssembly !== 'undefined';
4068
-
4069
- Blake2b.ready = function (cb) {
4070
- if (!cb) cb = noop;
4071
- if (!wasmPromise) return cb(new Error('WebAssembly not supported'))
4072
- return wasmPromise.then(() => cb(), cb)
4073
- };
4074
-
4075
- Blake2b.prototype.ready = Blake2b.ready;
4076
-
4077
- Blake2b.prototype.getPartialHash = function () {
4078
- return this._memory.slice(this.pointer, this.pointer + 216);
4079
- };
4080
-
4081
- Blake2b.prototype.setPartialHash = function (ph) {
4082
- this._memory.set(ph, this.pointer);
4083
- };
4084
-
4085
- function noop () {}
4086
- return blake2bWasm.exports;
4087
- }
4088
-
4089
- var hasRequiredBlake2b;
4090
-
4091
- function requireBlake2b () {
4092
- if (hasRequiredBlake2b) return blake2b$3.exports;
4093
- hasRequiredBlake2b = 1;
4094
- var assert = /*@__PURE__*/ requireNanoassert();
4095
- var b2wasm = /*@__PURE__*/ requireBlake2bWasm();
4096
-
4097
- // 64-bit unsigned addition
4098
- // Sets v[a,a+1] += v[b,b+1]
4099
- // v should be a Uint32Array
4100
- function ADD64AA (v, a, b) {
4101
- var o0 = v[a] + v[b];
4102
- var o1 = v[a + 1] + v[b + 1];
4103
- if (o0 >= 0x100000000) {
4104
- o1++;
4105
- }
4106
- v[a] = o0;
4107
- v[a + 1] = o1;
4108
- }
4109
-
4110
- // 64-bit unsigned addition
4111
- // Sets v[a,a+1] += b
4112
- // b0 is the low 32 bits of b, b1 represents the high 32 bits
4113
- function ADD64AC (v, a, b0, b1) {
4114
- var o0 = v[a] + b0;
4115
- if (b0 < 0) {
4116
- o0 += 0x100000000;
4117
- }
4118
- var o1 = v[a + 1] + b1;
4119
- if (o0 >= 0x100000000) {
4120
- o1++;
4121
- }
4122
- v[a] = o0;
4123
- v[a + 1] = o1;
4124
- }
4125
-
4126
- // Little-endian byte access
4127
- function B2B_GET32 (arr, i) {
4128
- return (arr[i] ^
4129
- (arr[i + 1] << 8) ^
4130
- (arr[i + 2] << 16) ^
4131
- (arr[i + 3] << 24))
4132
- }
4133
-
4134
- // G Mixing function
4135
- // The ROTRs are inlined for speed
4136
- function B2B_G (a, b, c, d, ix, iy) {
4137
- var x0 = m[ix];
4138
- var x1 = m[ix + 1];
4139
- var y0 = m[iy];
4140
- var y1 = m[iy + 1];
4141
-
4142
- ADD64AA(v, a, b); // v[a,a+1] += v[b,b+1] ... in JS we must store a uint64 as two uint32s
4143
- ADD64AC(v, a, x0, x1); // v[a, a+1] += x ... x0 is the low 32 bits of x, x1 is the high 32 bits
4144
-
4145
- // v[d,d+1] = (v[d,d+1] xor v[a,a+1]) rotated to the right by 32 bits
4146
- var xor0 = v[d] ^ v[a];
4147
- var xor1 = v[d + 1] ^ v[a + 1];
4148
- v[d] = xor1;
4149
- v[d + 1] = xor0;
4150
-
4151
- ADD64AA(v, c, d);
4152
-
4153
- // v[b,b+1] = (v[b,b+1] xor v[c,c+1]) rotated right by 24 bits
4154
- xor0 = v[b] ^ v[c];
4155
- xor1 = v[b + 1] ^ v[c + 1];
4156
- v[b] = (xor0 >>> 24) ^ (xor1 << 8);
4157
- v[b + 1] = (xor1 >>> 24) ^ (xor0 << 8);
4158
-
4159
- ADD64AA(v, a, b);
4160
- ADD64AC(v, a, y0, y1);
4161
-
4162
- // v[d,d+1] = (v[d,d+1] xor v[a,a+1]) rotated right by 16 bits
4163
- xor0 = v[d] ^ v[a];
4164
- xor1 = v[d + 1] ^ v[a + 1];
4165
- v[d] = (xor0 >>> 16) ^ (xor1 << 16);
4166
- v[d + 1] = (xor1 >>> 16) ^ (xor0 << 16);
4167
-
4168
- ADD64AA(v, c, d);
4169
-
4170
- // v[b,b+1] = (v[b,b+1] xor v[c,c+1]) rotated right by 63 bits
4171
- xor0 = v[b] ^ v[c];
4172
- xor1 = v[b + 1] ^ v[c + 1];
4173
- v[b] = (xor1 >>> 31) ^ (xor0 << 1);
4174
- v[b + 1] = (xor0 >>> 31) ^ (xor1 << 1);
4175
- }
4176
-
4177
- // Initialization Vector
4178
- var BLAKE2B_IV32 = new Uint32Array([
4179
- 0xF3BCC908, 0x6A09E667, 0x84CAA73B, 0xBB67AE85,
4180
- 0xFE94F82B, 0x3C6EF372, 0x5F1D36F1, 0xA54FF53A,
4181
- 0xADE682D1, 0x510E527F, 0x2B3E6C1F, 0x9B05688C,
4182
- 0xFB41BD6B, 0x1F83D9AB, 0x137E2179, 0x5BE0CD19
4183
- ]);
4184
-
4185
- var SIGMA8 = [
4186
- 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,
4187
- 14, 10, 4, 8, 9, 15, 13, 6, 1, 12, 0, 2, 11, 7, 5, 3,
4188
- 11, 8, 12, 0, 5, 2, 15, 13, 10, 14, 3, 6, 7, 1, 9, 4,
4189
- 7, 9, 3, 1, 13, 12, 11, 14, 2, 6, 5, 10, 4, 0, 15, 8,
4190
- 9, 0, 5, 7, 2, 4, 10, 15, 14, 1, 11, 12, 6, 8, 3, 13,
4191
- 2, 12, 6, 10, 0, 11, 8, 3, 4, 13, 7, 5, 15, 14, 1, 9,
4192
- 12, 5, 1, 15, 14, 13, 4, 10, 0, 7, 6, 3, 9, 2, 8, 11,
4193
- 13, 11, 7, 14, 12, 1, 3, 9, 5, 0, 15, 4, 8, 6, 2, 10,
4194
- 6, 15, 14, 9, 11, 3, 0, 8, 12, 2, 13, 7, 1, 4, 10, 5,
4195
- 10, 2, 8, 4, 7, 6, 1, 5, 15, 11, 9, 14, 3, 12, 13, 0,
4196
- 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,
4197
- 14, 10, 4, 8, 9, 15, 13, 6, 1, 12, 0, 2, 11, 7, 5, 3
4198
- ];
4199
-
4200
- // These are offsets into a uint64 buffer.
4201
- // Multiply them all by 2 to make them offsets into a uint32 buffer,
4202
- // because this is Javascript and we don't have uint64s
4203
- var SIGMA82 = new Uint8Array(SIGMA8.map(function (x) { return x * 2 }));
4204
-
4205
- // Compression function. 'last' flag indicates last block.
4206
- // Note we're representing 16 uint64s as 32 uint32s
4207
- var v = new Uint32Array(32);
4208
- var m = new Uint32Array(32);
4209
- function blake2bCompress (ctx, last) {
4210
- var i = 0;
4211
-
4212
- // init work variables
4213
- for (i = 0; i < 16; i++) {
4214
- v[i] = ctx.h[i];
4215
- v[i + 16] = BLAKE2B_IV32[i];
4216
- }
4217
-
4218
- // low 64 bits of offset
4219
- v[24] = v[24] ^ ctx.t;
4220
- v[25] = v[25] ^ (ctx.t / 0x100000000);
4221
- // high 64 bits not supported, offset may not be higher than 2**53-1
4222
-
4223
- // last block flag set ?
4224
- if (last) {
4225
- v[28] = ~v[28];
4226
- v[29] = ~v[29];
4227
- }
4228
-
4229
- // get little-endian words
4230
- for (i = 0; i < 32; i++) {
4231
- m[i] = B2B_GET32(ctx.b, 4 * i);
4232
- }
4233
-
4234
- // twelve rounds of mixing
4235
- for (i = 0; i < 12; i++) {
4236
- B2B_G(0, 8, 16, 24, SIGMA82[i * 16 + 0], SIGMA82[i * 16 + 1]);
4237
- B2B_G(2, 10, 18, 26, SIGMA82[i * 16 + 2], SIGMA82[i * 16 + 3]);
4238
- B2B_G(4, 12, 20, 28, SIGMA82[i * 16 + 4], SIGMA82[i * 16 + 5]);
4239
- B2B_G(6, 14, 22, 30, SIGMA82[i * 16 + 6], SIGMA82[i * 16 + 7]);
4240
- B2B_G(0, 10, 20, 30, SIGMA82[i * 16 + 8], SIGMA82[i * 16 + 9]);
4241
- B2B_G(2, 12, 22, 24, SIGMA82[i * 16 + 10], SIGMA82[i * 16 + 11]);
4242
- B2B_G(4, 14, 16, 26, SIGMA82[i * 16 + 12], SIGMA82[i * 16 + 13]);
4243
- B2B_G(6, 8, 18, 28, SIGMA82[i * 16 + 14], SIGMA82[i * 16 + 15]);
4244
- }
4245
-
4246
- for (i = 0; i < 16; i++) {
4247
- ctx.h[i] = ctx.h[i] ^ v[i] ^ v[i + 16];
4248
- }
4249
- }
4250
-
4251
- // reusable parameter_block
4252
- var parameter_block = new Uint8Array([
4253
- 0, 0, 0, 0, // 0: outlen, keylen, fanout, depth
4254
- 0, 0, 0, 0, // 4: leaf length, sequential mode
4255
- 0, 0, 0, 0, // 8: node offset
4256
- 0, 0, 0, 0, // 12: node offset
4257
- 0, 0, 0, 0, // 16: node depth, inner length, rfu
4258
- 0, 0, 0, 0, // 20: rfu
4259
- 0, 0, 0, 0, // 24: rfu
4260
- 0, 0, 0, 0, // 28: rfu
4261
- 0, 0, 0, 0, // 32: salt
4262
- 0, 0, 0, 0, // 36: salt
4263
- 0, 0, 0, 0, // 40: salt
4264
- 0, 0, 0, 0, // 44: salt
4265
- 0, 0, 0, 0, // 48: personal
4266
- 0, 0, 0, 0, // 52: personal
4267
- 0, 0, 0, 0, // 56: personal
4268
- 0, 0, 0, 0 // 60: personal
4269
- ]);
4270
-
4271
- // Creates a BLAKE2b hashing context
4272
- // Requires an output length between 1 and 64 bytes
4273
- // Takes an optional Uint8Array key
4274
- function Blake2b (outlen, key, salt, personal) {
4275
- // zero out parameter_block before usage
4276
- parameter_block.fill(0);
4277
- // state, 'param block'
4278
-
4279
- this.b = new Uint8Array(128);
4280
- this.h = new Uint32Array(16);
4281
- this.t = 0; // input count
4282
- this.c = 0; // pointer within buffer
4283
- this.outlen = outlen; // output length in bytes
4284
-
4285
- parameter_block[0] = outlen;
4286
- if (key) parameter_block[1] = key.length;
4287
- parameter_block[2] = 1; // fanout
4288
- parameter_block[3] = 1; // depth
4289
-
4290
- if (salt) parameter_block.set(salt, 32);
4291
- if (personal) parameter_block.set(personal, 48);
4292
-
4293
- // initialize hash state
4294
- for (var i = 0; i < 16; i++) {
4295
- this.h[i] = BLAKE2B_IV32[i] ^ B2B_GET32(parameter_block, i * 4);
4296
- }
4297
-
4298
- // key the hash, if applicable
4299
- if (key) {
4300
- blake2bUpdate(this, key);
4301
- // at the end
4302
- this.c = 128;
4303
- }
4304
- }
4305
-
4306
- Blake2b.prototype.update = function (input) {
4307
- assert(input instanceof Uint8Array, 'input must be Uint8Array or Buffer');
4308
- blake2bUpdate(this, input);
4309
- return this
4310
- };
4311
-
4312
- Blake2b.prototype.digest = function (out) {
4313
- var buf = (!out || out === 'binary' || out === 'hex') ? new Uint8Array(this.outlen) : out;
4314
- assert(buf instanceof Uint8Array, 'out must be "binary", "hex", Uint8Array, or Buffer');
4315
- assert(buf.length >= this.outlen, 'out must have at least outlen bytes of space');
4316
- blake2bFinal(this, buf);
4317
- if (out === 'hex') return hexSlice(buf)
4318
- return buf
4319
- };
4320
-
4321
- Blake2b.prototype.final = Blake2b.prototype.digest;
4322
-
4323
- Blake2b.ready = function (cb) {
4324
- b2wasm.ready(function () {
4325
- cb(); // ignore the error
4326
- });
4327
- };
4328
-
4329
- // Updates a BLAKE2b streaming hash
4330
- // Requires hash context and Uint8Array (byte array)
4331
- function blake2bUpdate (ctx, input) {
4332
- for (var i = 0; i < input.length; i++) {
4333
- if (ctx.c === 128) { // buffer full ?
4334
- ctx.t += ctx.c; // add counters
4335
- blake2bCompress(ctx, false); // compress (not last)
4336
- ctx.c = 0; // counter to zero
4337
- }
4338
- ctx.b[ctx.c++] = input[i];
4339
- }
4340
- }
4341
-
4342
- // Completes a BLAKE2b streaming hash
4343
- // Returns a Uint8Array containing the message digest
4344
- function blake2bFinal (ctx, out) {
4345
- ctx.t += ctx.c; // mark last block offset
4346
-
4347
- while (ctx.c < 128) { // fill up with zeros
4348
- ctx.b[ctx.c++] = 0;
4349
- }
4350
- blake2bCompress(ctx, true); // final block flag = 1
4351
-
4352
- for (var i = 0; i < ctx.outlen; i++) {
4353
- out[i] = ctx.h[i >> 2] >> (8 * (i & 3));
4354
- }
4355
- return out
4356
- }
4357
-
4358
- function hexSlice (buf) {
4359
- var str = '';
4360
- for (var i = 0; i < buf.length; i++) str += toHex(buf[i]);
4361
- return str
4362
- }
4363
-
4364
- function toHex (n) {
4365
- if (n < 16) return '0' + n.toString(16)
4366
- return n.toString(16)
4367
- }
4368
-
4369
- var Proto = Blake2b;
4370
-
4371
- blake2b$3.exports = function createHash (outlen, key, salt, personal, noAssert) {
4372
- if (noAssert !== true) {
4373
- assert(outlen >= BYTES_MIN, 'outlen must be at least ' + BYTES_MIN + ', was given ' + outlen);
4374
- assert(outlen <= BYTES_MAX, 'outlen must be at most ' + BYTES_MAX + ', was given ' + outlen);
4375
- if (key != null) {
4376
- assert(key instanceof Uint8Array, 'key must be Uint8Array or Buffer');
4377
- assert(key.length >= KEYBYTES_MIN, 'key must be at least ' + KEYBYTES_MIN + ', was given ' + key.length);
4378
- assert(key.length <= KEYBYTES_MAX, 'key must be at most ' + KEYBYTES_MAX + ', was given ' + key.length);
4379
- }
4380
- if (salt != null) {
4381
- assert(salt instanceof Uint8Array, 'salt must be Uint8Array or Buffer');
4382
- assert(salt.length === SALTBYTES, 'salt must be exactly ' + SALTBYTES + ', was given ' + salt.length);
4383
- }
4384
- if (personal != null) {
4385
- assert(personal instanceof Uint8Array, 'personal must be Uint8Array or Buffer');
4386
- assert(personal.length === PERSONALBYTES, 'personal must be exactly ' + PERSONALBYTES + ', was given ' + personal.length);
4387
- }
4388
- }
4389
-
4390
- return new Proto(outlen, key, salt, personal)
4391
- };
4392
-
4393
- blake2b$3.exports.ready = function (cb) {
4394
- b2wasm.ready(function () { // ignore errors
4395
- cb();
4396
- });
4397
- };
4398
-
4399
- blake2b$3.exports.WASM_SUPPORTED = b2wasm.SUPPORTED;
4400
- blake2b$3.exports.WASM_LOADED = false;
4401
-
4402
- var BYTES_MIN = blake2b$3.exports.BYTES_MIN = 16;
4403
- var BYTES_MAX = blake2b$3.exports.BYTES_MAX = 64;
4404
- blake2b$3.exports.BYTES = 32;
4405
- var KEYBYTES_MIN = blake2b$3.exports.KEYBYTES_MIN = 16;
4406
- var KEYBYTES_MAX = blake2b$3.exports.KEYBYTES_MAX = 64;
4407
- blake2b$3.exports.KEYBYTES = 32;
4408
- var SALTBYTES = blake2b$3.exports.SALTBYTES = 16;
4409
- var PERSONALBYTES = blake2b$3.exports.PERSONALBYTES = 16;
4410
-
4411
- b2wasm.ready(function (err) {
4412
- if (!err) {
4413
- blake2b$3.exports.WASM_LOADED = true;
4414
- blake2b$3.exports = b2wasm;
4415
- }
4416
- });
4417
- return blake2b$3.exports;
3679
+ function deriveEd25519SecretKey(seed, blake2b) {
3680
+ return blake2b.hashBytes(BytesBlob.blobFromParts([ED25519_SECRET_KEY.raw, seed.raw])).asOpaque();
4418
3681
  }
4419
-
4420
- var blake2bExports = /*@__PURE__*/ requireBlake2b();
4421
- var blake2b$1 = /*@__PURE__*/getDefaultExportFromCjs(blake2bExports);
4422
-
4423
3682
  /**
4424
- * Hash given collection of blobs.
4425
- *
4426
- * If empty array is given a zero-hash is returned.
3683
+ * Derives a Bandersnatch secret key from a seed.
3684
+ * https://github.com/polkadot-fellows/JIPs/blob/7048f79edf4f4eb8bfe6fb42e6bbf61900f44c65/JIP-5.md#derivation-method
4427
3685
  */
4428
- function hashBlobs$1(r, allocator = defaultAllocator) {
4429
- const out = allocator.emptyHash();
4430
- if (r.length === 0) {
4431
- return out.asOpaque();
4432
- }
4433
- const hasher = blake2b$1(HASH_SIZE);
4434
- for (const v of r) {
4435
- hasher?.update(v instanceof BytesBlob ? v.raw : v);
4436
- }
4437
- hasher?.digest(out.raw);
4438
- return out.asOpaque();
3686
+ function deriveBandersnatchSecretKey(seed, blake2b) {
3687
+ return blake2b.hashBytes(BytesBlob.blobFromParts([BANDERSNATCH_SECRET_KEY.raw, seed.raw])).asOpaque();
4439
3688
  }
4440
- /** Hash given blob of bytes. */
4441
- function hashBytes(blob, allocator = defaultAllocator) {
4442
- const hasher = blake2b$1(HASH_SIZE);
4443
- const bytes = blob instanceof BytesBlob ? blob.raw : blob;
4444
- hasher?.update(bytes);
4445
- const out = allocator.emptyHash();
4446
- hasher?.digest(out.raw);
4447
- return out;
3689
+ /**
3690
+ * Derive Ed25519 public key from secret seed
3691
+ */
3692
+ async function deriveEd25519PublicKey(seed) {
3693
+ return (await privateKey(seed)).pubKey;
4448
3694
  }
4449
- /** Convert given string into bytes and hash it. */
4450
- function hashString(str, allocator = defaultAllocator) {
4451
- return hashBytes(BytesBlob.blobFromString(str), allocator);
3695
+ /**
3696
+ * Derive Bandersnatch public key from secret seed
3697
+ */
3698
+ function deriveBandersnatchPublicKey(seed) {
3699
+ return publicKey(seed.raw);
4452
3700
  }
4453
3701
 
4454
- var blake2b = /*#__PURE__*/Object.freeze({
3702
+ var keyDerivation = /*#__PURE__*/Object.freeze({
3703
+ __proto__: null,
3704
+ SEED_SIZE: SEED_SIZE,
3705
+ deriveBandersnatchPublicKey: deriveBandersnatchPublicKey,
3706
+ deriveBandersnatchSecretKey: deriveBandersnatchSecretKey,
3707
+ deriveEd25519PublicKey: deriveEd25519PublicKey,
3708
+ deriveEd25519SecretKey: deriveEd25519SecretKey,
3709
+ trivialSeed: trivialSeed
3710
+ });
3711
+
3712
+ var index$p = /*#__PURE__*/Object.freeze({
4455
3713
  __proto__: null,
4456
- hashBlobs: hashBlobs$1,
4457
- hashBytes: hashBytes,
4458
- hashString: hashString
3714
+ BANDERSNATCH_KEY_BYTES: BANDERSNATCH_KEY_BYTES,
3715
+ BANDERSNATCH_PROOF_BYTES: BANDERSNATCH_PROOF_BYTES,
3716
+ BANDERSNATCH_RING_ROOT_BYTES: BANDERSNATCH_RING_ROOT_BYTES,
3717
+ BANDERSNATCH_VRF_SIGNATURE_BYTES: BANDERSNATCH_VRF_SIGNATURE_BYTES,
3718
+ BLS_KEY_BYTES: BLS_KEY_BYTES,
3719
+ ED25519_KEY_BYTES: ED25519_KEY_BYTES,
3720
+ ED25519_PRIV_KEY_BYTES: ED25519_PRIV_KEY_BYTES,
3721
+ ED25519_SIGNATURE_BYTES: ED25519_SIGNATURE_BYTES,
3722
+ Ed25519Pair: Ed25519Pair,
3723
+ SEED_SIZE: SEED_SIZE,
3724
+ bandersnatch: bandersnatch,
3725
+ bandersnatchWasm: bandersnatch_exports,
3726
+ ed25519: ed25519,
3727
+ initWasm: initAll,
3728
+ keyDerivation: keyDerivation
4459
3729
  });
4460
3730
 
4461
3731
  /*!
@@ -4816,19 +4086,90 @@ function WASMInterface(binary, hashLength) {
4816
4086
 
4817
4087
  new Mutex();
4818
4088
 
4819
- new Mutex();
4820
-
4821
- new Mutex();
4822
-
4823
- new Mutex();
4824
-
4825
- new Mutex();
4826
-
4827
- new Mutex();
4828
-
4829
- new Mutex();
4830
-
4831
- new Mutex();
4089
+ var name$j = "blake2b";
4090
+ var data$j = "AGFzbQEAAAABEQRgAAF/YAJ/fwBgAX8AYAAAAwoJAAECAwECAgABBQQBAQICBg4CfwFBsIsFC38AQYAICwdwCAZtZW1vcnkCAA5IYXNoX0dldEJ1ZmZlcgAACkhhc2hfRmluYWwAAwlIYXNoX0luaXQABQtIYXNoX1VwZGF0ZQAGDUhhc2hfR2V0U3RhdGUABw5IYXNoX0NhbGN1bGF0ZQAIClNUQVRFX1NJWkUDAQrTOAkFAEGACQvrAgIFfwF+AkAgAUEBSA0AAkACQAJA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AEEDdkH/P3EgAEEQdhAECwkAQYAJIAAQAQsGAEGAiQELGwAgAUEDdkH/P3EgAUEQdhAEQYAJIAAQARADCwsLAQBBgAgLBPAAAAA=";
4091
+ var hash$j = "c6f286e6";
4092
+ var wasmJson$j = {
4093
+ name: name$j,
4094
+ data: data$j,
4095
+ hash: hash$j
4096
+ };
4097
+
4098
+ new Mutex();
4099
+ function validateBits$4(bits) {
4100
+ if (!Number.isInteger(bits) || bits < 8 || bits > 512 || bits % 8 !== 0) {
4101
+ return new Error("Invalid variant! Valid values: 8, 16, ..., 512");
4102
+ }
4103
+ return null;
4104
+ }
4105
+ function getInitParam$1(outputBits, keyBits) {
4106
+ return outputBits | (keyBits << 16);
4107
+ }
4108
+ /**
4109
+ * Creates a new BLAKE2b hash instance
4110
+ * @param bits Number of output bits, which has to be a number
4111
+ * divisible by 8, between 8 and 512. Defaults to 512.
4112
+ * @param key Optional key (string, Buffer or TypedArray). Maximum length is 64 bytes.
4113
+ */
4114
+ function createBLAKE2b(bits = 512, key = null) {
4115
+ if (validateBits$4(bits)) {
4116
+ return Promise.reject(validateBits$4(bits));
4117
+ }
4118
+ let keyBuffer = null;
4119
+ let initParam = bits;
4120
+ if (key !== null) {
4121
+ keyBuffer = getUInt8Buffer(key);
4122
+ if (keyBuffer.length > 64) {
4123
+ return Promise.reject(new Error("Max key length is 64 bytes"));
4124
+ }
4125
+ initParam = getInitParam$1(bits, keyBuffer.length);
4126
+ }
4127
+ const outputSize = bits / 8;
4128
+ return WASMInterface(wasmJson$j, outputSize).then((wasm) => {
4129
+ if (initParam > 512) {
4130
+ wasm.writeMemory(keyBuffer);
4131
+ }
4132
+ wasm.init(initParam);
4133
+ const obj = {
4134
+ init: initParam > 512
4135
+ ? () => {
4136
+ wasm.writeMemory(keyBuffer);
4137
+ wasm.init(initParam);
4138
+ return obj;
4139
+ }
4140
+ : () => {
4141
+ wasm.init(initParam);
4142
+ return obj;
4143
+ },
4144
+ update: (data) => {
4145
+ wasm.update(data);
4146
+ return obj;
4147
+ },
4148
+ // biome-ignore lint/suspicious/noExplicitAny: Conflict with IHasher type
4149
+ digest: (outputType) => wasm.digest(outputType),
4150
+ save: () => wasm.save(),
4151
+ load: (data) => {
4152
+ wasm.load(data);
4153
+ return obj;
4154
+ },
4155
+ blockSize: 128,
4156
+ digestSize: outputSize,
4157
+ };
4158
+ return obj;
4159
+ });
4160
+ }
4161
+
4162
+ new Mutex();
4163
+
4164
+ new Mutex();
4165
+
4166
+ new Mutex();
4167
+
4168
+ new Mutex();
4169
+
4170
+ new Mutex();
4171
+
4172
+ new Mutex();
4832
4173
 
4833
4174
  new Mutex();
4834
4175
 
@@ -4906,6 +4247,79 @@ new Mutex();
4906
4247
 
4907
4248
  new Mutex();
4908
4249
 
4250
+ /**
4251
+ * Size of the output of the hash functions.
4252
+ *
4253
+ * https://graypaper.fluffylabs.dev/#/579bd12/073101073c01
4254
+ *
4255
+ */
4256
+ const HASH_SIZE = 32;
4257
+ /** A hash without last byte (useful for trie representation). */
4258
+ const TRUNCATED_HASH_SIZE = 31;
4259
+ const ZERO_HASH = Bytes.zero(HASH_SIZE);
4260
+ /**
4261
+ * Container for some object with a hash that is related to this object.
4262
+ *
4263
+ * After calculating the hash these two should be passed together to avoid
4264
+ * unnecessary re-hashing of the data.
4265
+ */
4266
+ class WithHash extends WithDebug {
4267
+ hash;
4268
+ data;
4269
+ constructor(hash, data) {
4270
+ super();
4271
+ this.hash = hash;
4272
+ this.data = data;
4273
+ }
4274
+ }
4275
+ /**
4276
+ * Extension of [`WithHash`] additionally containing an encoded version of the object.
4277
+ */
4278
+ class WithHashAndBytes extends WithHash {
4279
+ encoded;
4280
+ constructor(hash, data, encoded) {
4281
+ super(hash, data);
4282
+ this.encoded = encoded;
4283
+ }
4284
+ }
4285
+
4286
+ const zero$1 = Bytes.zero(HASH_SIZE);
4287
+ class Blake2b {
4288
+ hasher;
4289
+ static async createHasher() {
4290
+ return new Blake2b(await createBLAKE2b(HASH_SIZE * 8));
4291
+ }
4292
+ constructor(hasher) {
4293
+ this.hasher = hasher;
4294
+ }
4295
+ /**
4296
+ * Hash given collection of blobs.
4297
+ *
4298
+ * If empty array is given a zero-hash is returned.
4299
+ */
4300
+ hashBlobs(r) {
4301
+ if (r.length === 0) {
4302
+ return zero$1.asOpaque();
4303
+ }
4304
+ const hasher = this.hasher.init();
4305
+ for (const v of r) {
4306
+ hasher.update(v instanceof BytesBlob ? v.raw : v);
4307
+ }
4308
+ return Bytes.fromBlob(hasher.digest("binary"), HASH_SIZE).asOpaque();
4309
+ }
4310
+ /** Hash given blob of bytes. */
4311
+ hashBytes(blob) {
4312
+ const hasher = this.hasher.init();
4313
+ const bytes = blob instanceof BytesBlob ? blob.raw : blob;
4314
+ hasher.update(bytes);
4315
+ return Bytes.fromBlob(hasher.digest("binary"), HASH_SIZE).asOpaque();
4316
+ }
4317
+ /** Convert given string into bytes and hash it. */
4318
+ hashString(str) {
4319
+ return this.hashBytes(BytesBlob.blobFromString(str));
4320
+ }
4321
+ }
4322
+
4909
4323
  class KeccakHasher {
4910
4324
  hasher;
4911
4325
  static async create() {
@@ -4930,91 +4344,61 @@ var keccak = /*#__PURE__*/Object.freeze({
4930
4344
  hashBlobs: hashBlobs
4931
4345
  });
4932
4346
 
4933
- var index$p = /*#__PURE__*/Object.freeze({
4347
+ // TODO [ToDr] (#213) this should most likely be moved to a separate
4348
+ // package to avoid pulling in unnecessary deps.
4349
+
4350
+ var index$o = /*#__PURE__*/Object.freeze({
4934
4351
  __proto__: null,
4352
+ Blake2b: Blake2b,
4935
4353
  HASH_SIZE: HASH_SIZE,
4936
- PageAllocator: PageAllocator,
4937
- SimpleAllocator: SimpleAllocator,
4938
4354
  TRUNCATED_HASH_SIZE: TRUNCATED_HASH_SIZE,
4939
4355
  WithHash: WithHash,
4940
4356
  WithHashAndBytes: WithHashAndBytes,
4941
4357
  ZERO_HASH: ZERO_HASH,
4942
- blake2b: blake2b,
4943
- defaultAllocator: defaultAllocator,
4944
4358
  keccak: keccak
4945
4359
  });
4946
4360
 
4947
- const SEED_SIZE = 32;
4948
- const ED25519_SECRET_KEY = Bytes.blobFromString("jam_val_key_ed25519");
4949
- const BANDERSNATCH_SECRET_KEY = Bytes.blobFromString("jam_val_key_bandersnatch");
4950
- /**
4951
- * JIP-5: Secret key derivation
4952
- *
4953
- * https://github.com/polkadot-fellows/JIPs/blob/7048f79edf4f4eb8bfe6fb42e6bbf61900f44c65/JIP-5.md */
4954
- /**
4955
- * Deriving a 32-byte seed from a 32-bit unsigned integer
4956
- * https://github.com/polkadot-fellows/JIPs/blob/7048f79edf4f4eb8bfe6fb42e6bbf61900f44c65/JIP-5.md#trivial-seeds
4957
- */
4958
- function trivialSeed(s) {
4959
- const s_le = u32AsLeBytes(s);
4960
- return Bytes.fromBlob(BytesBlob.blobFromParts([s_le, s_le, s_le, s_le, s_le, s_le, s_le, s_le]).raw, SEED_SIZE).asOpaque();
4961
- }
4962
- /**
4963
- * Derives a Ed25519 secret key from a seed.
4964
- * https://github.com/polkadot-fellows/JIPs/blob/7048f79edf4f4eb8bfe6fb42e6bbf61900f44c65/JIP-5.md#derivation-method
4965
- */
4966
- function deriveEd25519SecretKey(seed, allocator = new SimpleAllocator()) {
4967
- return hashBytes(BytesBlob.blobFromParts([ED25519_SECRET_KEY.raw, seed.raw]), allocator).asOpaque();
4968
- }
4969
- /**
4970
- * Derives a Bandersnatch secret key from a seed.
4971
- * https://github.com/polkadot-fellows/JIPs/blob/7048f79edf4f4eb8bfe6fb42e6bbf61900f44c65/JIP-5.md#derivation-method
4972
- */
4973
- function deriveBandersnatchSecretKey(seed, allocator = new SimpleAllocator()) {
4974
- return hashBytes(BytesBlob.blobFromParts([BANDERSNATCH_SECRET_KEY.raw, seed.raw]), allocator).asOpaque();
4975
- }
4976
4361
  /**
4977
- * Derive Ed25519 public key from secret seed
4362
+ * A utility class providing a readonly view over a portion of an array without copying it.
4978
4363
  */
4979
- async function deriveEd25519PublicKey(seed) {
4980
- return (await privateKey(seed)).pubKey;
4981
- }
4982
- /**
4983
- * Derive Bandersnatch public key from secret seed
4984
- */
4985
- function deriveBandersnatchPublicKey(seed) {
4986
- return publicKey(seed.raw);
4364
+ class ArrayView {
4365
+ start;
4366
+ end;
4367
+ source;
4368
+ length;
4369
+ constructor(source, start, end) {
4370
+ this.start = start;
4371
+ this.end = end;
4372
+ this.source = source;
4373
+ this.length = end - start;
4374
+ }
4375
+ static from(source, start = 0, end = source.length) {
4376
+ check `
4377
+ ${start >= 0 && end <= source.length && start <= end}
4378
+ Invalid start (${start})/end (${end}) for ArrayView
4379
+ `;
4380
+ return new ArrayView(source, start, end);
4381
+ }
4382
+ get(i) {
4383
+ check `
4384
+ ${i >= 0 && i < this.length}
4385
+ Index out of bounds: ${i} < ${this.length}
4386
+ `;
4387
+ return this.source[this.start + i];
4388
+ }
4389
+ subview(from, to = this.length) {
4390
+ return ArrayView.from(this.source, this.start + from, this.start + to);
4391
+ }
4392
+ toArray() {
4393
+ return this.source.slice(this.start, this.end);
4394
+ }
4395
+ *[Symbol.iterator]() {
4396
+ for (let i = this.start; i < this.end; i++) {
4397
+ yield this.source[i];
4398
+ }
4399
+ }
4987
4400
  }
4988
4401
 
4989
- var keyDerivation = /*#__PURE__*/Object.freeze({
4990
- __proto__: null,
4991
- SEED_SIZE: SEED_SIZE,
4992
- deriveBandersnatchPublicKey: deriveBandersnatchPublicKey,
4993
- deriveBandersnatchSecretKey: deriveBandersnatchSecretKey,
4994
- deriveEd25519PublicKey: deriveEd25519PublicKey,
4995
- deriveEd25519SecretKey: deriveEd25519SecretKey,
4996
- trivialSeed: trivialSeed
4997
- });
4998
-
4999
- var index$o = /*#__PURE__*/Object.freeze({
5000
- __proto__: null,
5001
- BANDERSNATCH_KEY_BYTES: BANDERSNATCH_KEY_BYTES,
5002
- BANDERSNATCH_PROOF_BYTES: BANDERSNATCH_PROOF_BYTES,
5003
- BANDERSNATCH_RING_ROOT_BYTES: BANDERSNATCH_RING_ROOT_BYTES,
5004
- BANDERSNATCH_VRF_SIGNATURE_BYTES: BANDERSNATCH_VRF_SIGNATURE_BYTES,
5005
- BLS_KEY_BYTES: BLS_KEY_BYTES,
5006
- ED25519_KEY_BYTES: ED25519_KEY_BYTES,
5007
- ED25519_PRIV_KEY_BYTES: ED25519_PRIV_KEY_BYTES,
5008
- ED25519_SIGNATURE_BYTES: ED25519_SIGNATURE_BYTES,
5009
- Ed25519Pair: Ed25519Pair,
5010
- SEED_SIZE: SEED_SIZE,
5011
- bandersnatch: bandersnatch,
5012
- bandersnatchWasm: bandersnatch_exports,
5013
- ed25519: ed25519,
5014
- initWasm: initAll,
5015
- keyDerivation: keyDerivation
5016
- });
5017
-
5018
4402
  /** A map which uses hashes as keys. */
5019
4403
  class HashDictionary {
5020
4404
  // TODO [ToDr] [crit] We can't use `TrieHash` directly in the map,
@@ -5602,6 +4986,7 @@ class TruncatedHashDictionary {
5602
4986
 
5603
4987
  var index$n = /*#__PURE__*/Object.freeze({
5604
4988
  __proto__: null,
4989
+ ArrayView: ArrayView,
5605
4990
  FixedSizeArray: FixedSizeArray,
5606
4991
  HashDictionary: HashDictionary,
5607
4992
  HashSet: HashSet,
@@ -7922,7 +7307,7 @@ var chain_spec$1 = {
7922
7307
  "0d000000000000000000000000000000000000000000000000000000000000": "0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000",
7923
7308
  "01000000000000000000000000000000000000000000000000000000000000": "080868db7f54e8b81d3a86438a8865eaf6b108b7992ae41dbc78f401b9acb5f9780868db7f54e8b81d3a86438a8865eaf6b108b7992ae41dbc78f401b9acb5f9780868db7f54e8b81d3a86438a8865eaf6b108b7992ae41dbc78f401b9acb5f9780868db7f54e8b81d3a86438a8865eaf6b108b7992ae41dbc78f401b9acb5f9780868db7f54e8b81d3a86438a8865eaf6b108b7992ae41dbc78f401b9acb5f9780868db7f54e8b81d3a86438a8865eaf6b108b7992ae41dbc78f401b9acb5f9780868db7f54e8b81d3a86438a8865eaf6b108b7992ae41dbc78f401b9acb5f9780868db7f54e8b81d3a86438a8865eaf6b108b7992ae41dbc78f401b9acb5f978080868db7f54e8b81d3a86438a8865eaf6b108b7992ae41dbc78f401b9acb5f9780868db7f54e8b81d3a86438a8865eaf6b108b7992ae41dbc78f401b9acb5f9780868db7f54e8b81d3a86438a8865eaf6b108b7992ae41dbc78f401b9acb5f9780868db7f54e8b81d3a86438a8865eaf6b108b7992ae41dbc78f401b9acb5f9780868db7f54e8b81d3a86438a8865eaf6b108b7992ae41dbc78f401b9acb5f9780868db7f54e8b81d3a86438a8865eaf6b108b7992ae41dbc78f401b9acb5f9780868db7f54e8b81d3a86438a8865eaf6b108b7992ae41dbc78f401b9acb5f9780868db7f54e8b81d3a86438a8865eaf6b108b7992ae41dbc78f401b9acb5f978",
7924
7309
  "10000000000000000000000000000000000000000000000000000000000000": "00",
7925
- "0c000000000000000000000000000000000000000000000000000000000000": "0000000000000000000000000000000000",
7310
+ "0c000000000000000000000000000000000000000000000000000000000000": "000000000000000000000000000000000000000000",
7926
7311
  "06000000000000000000000000000000000000000000000000000000000000": "03170a2e7597b7b7e3d84c05391d139a62b157e78786d8c082f29dcf4c111314ee155ace9c40292074cb6aff8c9ccdd273c81648ff1149ef36bcea6ebb8a3e25bb30a42c1e62f0afda5f0a4e8a562f7a13a24cea00ee81917b86b89e801314aae88bd757ad5b9bedf372d8d3f0cf6c962a469db61a265f6418e1ffed86da29ec",
7927
7312
  "0a000000000000000000000000000000000000000000000000000000000000": "0000",
7928
7313
  "03000000000000000000000000000000000000000000000000000000000000": "012bf11dc5e1c7b9bbaafc2c8533017abc12daeb0baf22c92509ad50f7875e5716000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000",
@@ -7970,7 +7355,7 @@ var chain_spec = {
7970
7355
  "0d000000000000000000000000000000000000000000000000000000000000": "0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000",
7971
7356
  "01000000000000000000000000000000000000000000000000000000000000": "080868db7f54e8b81d3a86438a8865eaf6b108b7992ae41dbc78f401b9acb5f9780868db7f54e8b81d3a86438a8865eaf6b108b7992ae41dbc78f401b9acb5f9780868db7f54e8b81d3a86438a8865eaf6b108b7992ae41dbc78f401b9acb5f9780868db7f54e8b81d3a86438a8865eaf6b108b7992ae41dbc78f401b9acb5f9780868db7f54e8b81d3a86438a8865eaf6b108b7992ae41dbc78f401b9acb5f9780868db7f54e8b81d3a86438a8865eaf6b108b7992ae41dbc78f401b9acb5f9780868db7f54e8b81d3a86438a8865eaf6b108b7992ae41dbc78f401b9acb5f9780868db7f54e8b81d3a86438a8865eaf6b108b7992ae41dbc78f401b9acb5f978080868db7f54e8b81d3a86438a8865eaf6b108b7992ae41dbc78f401b9acb5f9780868db7f54e8b81d3a86438a8865eaf6b108b7992ae41dbc78f401b9acb5f9780868db7f54e8b81d3a86438a8865eaf6b108b7992ae41dbc78f401b9acb5f9780868db7f54e8b81d3a86438a8865eaf6b108b7992ae41dbc78f401b9acb5f9780868db7f54e8b81d3a86438a8865eaf6b108b7992ae41dbc78f401b9acb5f9780868db7f54e8b81d3a86438a8865eaf6b108b7992ae41dbc78f401b9acb5f9780868db7f54e8b81d3a86438a8865eaf6b108b7992ae41dbc78f401b9acb5f9780868db7f54e8b81d3a86438a8865eaf6b108b7992ae41dbc78f401b9acb5f978",
7972
7357
  "10000000000000000000000000000000000000000000000000000000000000": "00",
7973
- "0c000000000000000000000000000000000000000000000000000000000000": "0000000000000000000000000000000000",
7358
+ "0c000000000000000000000000000000000000000000000000000000000000": "000000000000000000000000000000000000000000",
7974
7359
  "06000000000000000000000000000000000000000000000000000000000000": "03170a2e7597b7b7e3d84c05391d139a62b157e78786d8c082f29dcf4c111314ee155ace9c40292074cb6aff8c9ccdd273c81648ff1149ef36bcea6ebb8a3e25bb30a42c1e62f0afda5f0a4e8a562f7a13a24cea00ee81917b86b89e801314aae88bd757ad5b9bedf372d8d3f0cf6c962a469db61a265f6418e1ffed86da29ec",
7975
7360
  "0a000000000000000000000000000000000000000000000000000000000000": "0000",
7976
7361
  "03000000000000000000000000000000000000000000000000000000000000": "012bf11dc5e1c7b9bbaafc2c8533017abc12daeb0baf22c92509ad50f7875e5716000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000",
@@ -8563,43 +7948,43 @@ var stateKeys;
8563
7948
  }
8564
7949
  stateKeys.serviceInfo = serviceInfo;
8565
7950
  /** https://graypaper.fluffylabs.dev/#/1c979cb/3bba033bba03?v=0.7.1 */
8566
- function serviceStorage(serviceId, key) {
7951
+ function serviceStorage(blake2b, serviceId, key) {
8567
7952
  if (Compatibility.isLessThan(GpVersion.V0_6_7)) {
8568
7953
  const out = Bytes.zero(HASH_SIZE);
8569
7954
  out.raw.set(u32AsLeBytes(tryAsU32(2 ** 32 - 1)), 0);
8570
7955
  out.raw.set(key.raw.subarray(0, HASH_SIZE - U32_BYTES), U32_BYTES);
8571
7956
  return legacyServiceNested(serviceId, out);
8572
7957
  }
8573
- return serviceNested(serviceId, tryAsU32(2 ** 32 - 1), key);
7958
+ return serviceNested(blake2b, serviceId, tryAsU32(2 ** 32 - 1), key);
8574
7959
  }
8575
7960
  stateKeys.serviceStorage = serviceStorage;
8576
7961
  /** https://graypaper.fluffylabs.dev/#/1c979cb/3bd7033bd703?v=0.7.1 */
8577
- function servicePreimage(serviceId, hash) {
7962
+ function servicePreimage(blake2b, serviceId, hash) {
8578
7963
  if (Compatibility.isLessThan(GpVersion.V0_6_7)) {
8579
7964
  const out = Bytes.zero(HASH_SIZE);
8580
7965
  out.raw.set(u32AsLeBytes(tryAsU32(2 ** 32 - 2)), 0);
8581
7966
  out.raw.set(hash.raw.subarray(1, HASH_SIZE - U32_BYTES + 1), U32_BYTES);
8582
7967
  return legacyServiceNested(serviceId, out);
8583
7968
  }
8584
- return serviceNested(serviceId, tryAsU32(2 ** 32 - 2), hash);
7969
+ return serviceNested(blake2b, serviceId, tryAsU32(2 ** 32 - 2), hash);
8585
7970
  }
8586
7971
  stateKeys.servicePreimage = servicePreimage;
8587
7972
  /** https://graypaper.fluffylabs.dev/#/1c979cb/3b0a043b0a04?v=0.7.1 */
8588
- function serviceLookupHistory(serviceId, hash, preimageLength) {
7973
+ function serviceLookupHistory(blake2b, serviceId, hash, preimageLength) {
8589
7974
  if (Compatibility.isLessThan(GpVersion.V0_6_7)) {
8590
- const doubleHash = hashBytes(hash);
7975
+ const doubleHash = blake2b.hashBytes(hash);
8591
7976
  const out = Bytes.zero(HASH_SIZE);
8592
7977
  out.raw.set(u32AsLeBytes(preimageLength), 0);
8593
7978
  out.raw.set(doubleHash.raw.subarray(2, HASH_SIZE - U32_BYTES + 2), U32_BYTES);
8594
7979
  return legacyServiceNested(serviceId, out);
8595
7980
  }
8596
- return serviceNested(serviceId, preimageLength, hash);
7981
+ return serviceNested(blake2b, serviceId, preimageLength, hash);
8597
7982
  }
8598
7983
  stateKeys.serviceLookupHistory = serviceLookupHistory;
8599
7984
  /** https://graypaper.fluffylabs.dev/#/1c979cb/3b88003b8800?v=0.7.1 */
8600
- function serviceNested(serviceId, numberPrefix, hash) {
7985
+ function serviceNested(blake2b, serviceId, numberPrefix, hash) {
8601
7986
  const inputToHash = BytesBlob.blobFromParts(u32AsLeBytes(numberPrefix), hash.raw);
8602
- const newHash = hashBytes(inputToHash).raw.subarray(0, 28);
7987
+ const newHash = blake2b.hashBytes(inputToHash).raw.subarray(0, 28);
8603
7988
  const key = Bytes.zero(HASH_SIZE);
8604
7989
  let i = 0;
8605
7990
  for (const byte of u32AsLeBytes(serviceId)) {
@@ -8660,12 +8045,6 @@ function accumulationOutputComparator(a, b) {
8660
8045
  return Ordering.Equal;
8661
8046
  }
8662
8047
 
8663
- const codecWithHash = (val) => Descriptor.withView(val.name, val.sizeHint, (e, elem) => val.encode(e, elem.data), (d) => {
8664
- const decoder2 = d.clone();
8665
- const encoded = val.skipEncoded(decoder2);
8666
- const hash = hashBytes(encoded);
8667
- return new WithHash(hash.asOpaque(), val.decode(d));
8668
- }, val.skip, val.View);
8669
8048
  /**
8670
8049
  * Assignment of particular work report to a core.
8671
8050
  *
@@ -8678,7 +8057,7 @@ class AvailabilityAssignment extends WithDebug {
8678
8057
  workReport;
8679
8058
  timeout;
8680
8059
  static Codec = codec$1.Class(AvailabilityAssignment, {
8681
- workReport: codecWithHash(WorkReport.Codec),
8060
+ workReport: WorkReport.Codec,
8682
8061
  timeout: codec$1.u32.asOpaque(),
8683
8062
  });
8684
8063
  static create({ workReport, timeout }) {
@@ -8731,6 +8110,10 @@ class DisputesRecords {
8731
8110
  static create({ goodSet, badSet, wonkySet, punishSet }) {
8732
8111
  return new DisputesRecords(goodSet, badSet, wonkySet, punishSet);
8733
8112
  }
8113
+ goodSetDict;
8114
+ badSetDict;
8115
+ wonkySetDict;
8116
+ punishSetDict;
8734
8117
  constructor(
8735
8118
  /** `goodSet`: all work-reports hashes which were judged to be correct */
8736
8119
  goodSet,
@@ -8744,6 +8127,18 @@ class DisputesRecords {
8744
8127
  this.badSet = badSet;
8745
8128
  this.wonkySet = wonkySet;
8746
8129
  this.punishSet = punishSet;
8130
+ this.goodSetDict = HashSet.from(goodSet.array);
8131
+ this.badSetDict = HashSet.from(badSet.array);
8132
+ this.wonkySetDict = HashSet.from(wonkySet.array);
8133
+ this.punishSetDict = HashSet.from(punishSet.array);
8134
+ }
8135
+ asDictionaries() {
8136
+ return {
8137
+ goodSet: this.goodSetDict,
8138
+ badSet: this.badSetDict,
8139
+ wonkySet: this.wonkySetDict,
8140
+ punishSet: this.punishSetDict,
8141
+ };
8747
8142
  }
8748
8143
  static fromSortedArrays({ goodSet, badSet, wonkySet, punishSet, }) {
8749
8144
  return new DisputesRecords(SortedSet.fromSortedArray(hashComparator, goodSet), SortedSet.fromSortedArray(hashComparator, badSet), SortedSet.fromSortedArray(hashComparator, wonkySet), SortedSet.fromSortedArray(hashComparator, punishSet));
@@ -8759,7 +8154,6 @@ const O = 8;
8759
8154
  const Q = 80;
8760
8155
  /** `W_T`: The size of a transfer memo in octets. */
8761
8156
  const W_T = 128;
8762
- // TODO [ToDr] Not sure where these should live yet :(
8763
8157
  /**
8764
8158
  * `J`: The maximum sum of dependency items in a work-report.
8765
8159
  *
@@ -8771,6 +8165,194 @@ const AUTHORIZATION_QUEUE_SIZE = Q;
8771
8165
  /** `O`: Maximal authorization pool size. */
8772
8166
  const MAX_AUTH_POOL_SIZE = O;
8773
8167
 
8168
+ const MAX_VALUE = 4294967295;
8169
+ const MIN_VALUE = -2147483648;
8170
+ const MAX_SHIFT_U32 = 32;
8171
+ const MAX_SHIFT_U64 = 64n;
8172
+
8173
+ /**
8174
+ * `B_S`: The basic minimum balance which all services require.
8175
+ *
8176
+ * https://graypaper.fluffylabs.dev/#/7e6ff6a/445800445800?v=0.6.7
8177
+ */
8178
+ const BASE_SERVICE_BALANCE = 100n;
8179
+ /**
8180
+ * `B_I`: The additional minimum balance required per item of elective service state.
8181
+ *
8182
+ * https://graypaper.fluffylabs.dev/#/7e6ff6a/445000445000?v=0.6.7
8183
+ */
8184
+ const ELECTIVE_ITEM_BALANCE = 10n;
8185
+ /**
8186
+ * `B_L`: The additional minimum balance required per octet of elective service state.
8187
+ *
8188
+ * https://graypaper.fluffylabs.dev/#/7e6ff6a/445400445400?v=0.6.7
8189
+ */
8190
+ const ELECTIVE_BYTE_BALANCE = 1n;
8191
+ const zeroSizeHint = {
8192
+ bytes: 0,
8193
+ isExact: true,
8194
+ };
8195
+ /** 0-byte read, return given default value */
8196
+ const ignoreValueWithDefault = (defaultValue) => Descriptor.new("ignoreValue", zeroSizeHint, (_e, _v) => { }, (_d) => defaultValue, (_s) => { });
8197
+ /** Encode and decode object with leading version number. */
8198
+ const codecWithVersion = (val) => Descriptor.new("withVersion", {
8199
+ bytes: val.sizeHint.bytes + 8,
8200
+ isExact: false,
8201
+ }, (e, v) => {
8202
+ e.varU64(0n);
8203
+ val.encode(e, v);
8204
+ }, (d) => {
8205
+ const version = d.varU64();
8206
+ if (version !== 0n) {
8207
+ throw new Error("Non-zero version is not supported!");
8208
+ }
8209
+ return val.decode(d);
8210
+ }, (s) => {
8211
+ s.varU64();
8212
+ val.skip(s);
8213
+ });
8214
+ /**
8215
+ * Service account details.
8216
+ *
8217
+ * https://graypaper.fluffylabs.dev/#/7e6ff6a/108301108301?v=0.6.7
8218
+ */
8219
+ class ServiceAccountInfo extends WithDebug {
8220
+ codeHash;
8221
+ balance;
8222
+ accumulateMinGas;
8223
+ onTransferMinGas;
8224
+ storageUtilisationBytes;
8225
+ gratisStorage;
8226
+ storageUtilisationCount;
8227
+ created;
8228
+ lastAccumulation;
8229
+ parentService;
8230
+ static Codec = codec$1.Class(ServiceAccountInfo, {
8231
+ codeHash: codec$1.bytes(HASH_SIZE).asOpaque(),
8232
+ balance: codec$1.u64,
8233
+ accumulateMinGas: codec$1.u64.convert((x) => x, tryAsServiceGas),
8234
+ onTransferMinGas: codec$1.u64.convert((x) => x, tryAsServiceGas),
8235
+ storageUtilisationBytes: codec$1.u64,
8236
+ gratisStorage: codec$1.u64,
8237
+ storageUtilisationCount: codec$1.u32,
8238
+ created: codec$1.u32.convert((x) => x, tryAsTimeSlot),
8239
+ lastAccumulation: codec$1.u32.convert((x) => x, tryAsTimeSlot),
8240
+ parentService: codec$1.u32.convert((x) => x, tryAsServiceId),
8241
+ });
8242
+ static create(a) {
8243
+ return new ServiceAccountInfo(a.codeHash, a.balance, a.accumulateMinGas, a.onTransferMinGas, a.storageUtilisationBytes, a.gratisStorage, a.storageUtilisationCount, a.created, a.lastAccumulation, a.parentService);
8244
+ }
8245
+ /**
8246
+ * `a_t = max(0, BS + BI * a_i + BL * a_o - a_f)`
8247
+ * https://graypaper.fluffylabs.dev/#/7e6ff6a/119e01119e01?v=0.6.7
8248
+ */
8249
+ static calculateThresholdBalance(items, bytes, gratisStorage) {
8250
+ const storageCost = BASE_SERVICE_BALANCE + ELECTIVE_ITEM_BALANCE * BigInt(items) + ELECTIVE_BYTE_BALANCE * bytes - gratisStorage;
8251
+ if (storageCost < 0n) {
8252
+ return tryAsU64(0);
8253
+ }
8254
+ if (storageCost >= 2n ** 64n) {
8255
+ return tryAsU64(2n ** 64n - 1n);
8256
+ }
8257
+ return tryAsU64(storageCost);
8258
+ }
8259
+ constructor(
8260
+ /** `a_c`: Hash of the service code. */
8261
+ codeHash,
8262
+ /** `a_b`: Current account balance. */
8263
+ balance,
8264
+ /** `a_g`: Minimal gas required to execute Accumulate entrypoint. */
8265
+ accumulateMinGas,
8266
+ /** `a_m`: Minimal gas required to execute On Transfer entrypoint. */
8267
+ onTransferMinGas,
8268
+ /** `a_o`: Total number of octets in storage. */
8269
+ storageUtilisationBytes,
8270
+ /** `a_f`: Cost-free storage. Decreases both storage item count and total byte size. */
8271
+ gratisStorage,
8272
+ /** `a_i`: Number of items in storage. */
8273
+ storageUtilisationCount,
8274
+ /** `a_r`: Creation account time slot. */
8275
+ created,
8276
+ /** `a_a`: Most recent accumulation time slot. */
8277
+ lastAccumulation,
8278
+ /** `a_p`: Parent service ID. */
8279
+ parentService) {
8280
+ super();
8281
+ this.codeHash = codeHash;
8282
+ this.balance = balance;
8283
+ this.accumulateMinGas = accumulateMinGas;
8284
+ this.onTransferMinGas = onTransferMinGas;
8285
+ this.storageUtilisationBytes = storageUtilisationBytes;
8286
+ this.gratisStorage = gratisStorage;
8287
+ this.storageUtilisationCount = storageUtilisationCount;
8288
+ this.created = created;
8289
+ this.lastAccumulation = lastAccumulation;
8290
+ this.parentService = parentService;
8291
+ }
8292
+ }
8293
+ class PreimageItem extends WithDebug {
8294
+ hash;
8295
+ blob;
8296
+ static Codec = codec$1.Class(PreimageItem, {
8297
+ hash: codec$1.bytes(HASH_SIZE).asOpaque(),
8298
+ blob: codec$1.blob,
8299
+ });
8300
+ static create({ hash, blob }) {
8301
+ return new PreimageItem(hash, blob);
8302
+ }
8303
+ constructor(hash, blob) {
8304
+ super();
8305
+ this.hash = hash;
8306
+ this.blob = blob;
8307
+ }
8308
+ }
8309
+ class StorageItem extends WithDebug {
8310
+ key;
8311
+ value;
8312
+ static Codec = codec$1.Class(StorageItem, {
8313
+ key: codec$1.blob.convert((i) => i, (o) => asOpaqueType(o)),
8314
+ value: codec$1.blob,
8315
+ });
8316
+ static create({ key, value }) {
8317
+ return new StorageItem(key, value);
8318
+ }
8319
+ constructor(key, value) {
8320
+ super();
8321
+ this.key = key;
8322
+ this.value = value;
8323
+ }
8324
+ }
8325
+ const MAX_LOOKUP_HISTORY_SLOTS = 3;
8326
+ function tryAsLookupHistorySlots(items) {
8327
+ const knownSize = asKnownSize(items);
8328
+ if (knownSize.length > MAX_LOOKUP_HISTORY_SLOTS) {
8329
+ throw new Error(`Lookup history items must contain 0-${MAX_LOOKUP_HISTORY_SLOTS} timeslots.`);
8330
+ }
8331
+ return knownSize;
8332
+ }
8333
+ /** https://graypaper.fluffylabs.dev/#/5f542d7/115400115800 */
8334
+ class LookupHistoryItem {
8335
+ hash;
8336
+ length;
8337
+ slots;
8338
+ constructor(hash, length,
8339
+ /**
8340
+ * Preimage availability history as a sequence of time slots.
8341
+ * See PreimageStatus and the following GP fragment for more details.
8342
+ * https://graypaper.fluffylabs.dev/#/5f542d7/11780011a500 */
8343
+ slots) {
8344
+ this.hash = hash;
8345
+ this.length = length;
8346
+ this.slots = slots;
8347
+ }
8348
+ static isRequested(item) {
8349
+ if ("slots" in item) {
8350
+ return item.slots.length === 0;
8351
+ }
8352
+ return item.length === 0;
8353
+ }
8354
+ }
8355
+
8774
8356
  /** Dictionary entry of services that auto-accumulate every block. */
8775
8357
  class AutoAccumulate {
8776
8358
  service;
@@ -8792,39 +8374,50 @@ class AutoAccumulate {
8792
8374
  }
8793
8375
  }
8794
8376
  /**
8795
- * https://graypaper.fluffylabs.dev/#/7e6ff6a/11da0111da01?v=0.6.7
8377
+ * https://graypaper.fluffylabs.dev/#/ab2cdbd/114402114402?v=0.7.2
8796
8378
  */
8797
8379
  class PrivilegedServices {
8798
8380
  manager;
8799
- authManager;
8800
- validatorsManager;
8381
+ delegator;
8382
+ registrar;
8383
+ assigners;
8801
8384
  autoAccumulateServices;
8385
+ /** https://graypaper.fluffylabs.dev/#/ab2cdbd/3bbd023bcb02?v=0.7.2 */
8802
8386
  static Codec = codec$1.Class(PrivilegedServices, {
8803
8387
  manager: codec$1.u32.asOpaque(),
8804
- authManager: codecPerCore(codec$1.u32.asOpaque()),
8805
- validatorsManager: codec$1.u32.asOpaque(),
8388
+ assigners: codecPerCore(codec$1.u32.asOpaque()),
8389
+ delegator: codec$1.u32.asOpaque(),
8390
+ registrar: Compatibility.isGreaterOrEqual(GpVersion.V0_7_1)
8391
+ ? codec$1.u32.asOpaque()
8392
+ : ignoreValueWithDefault(tryAsServiceId(2 ** 32 - 1)),
8806
8393
  autoAccumulateServices: readonlyArray(codec$1.sequenceVarLen(AutoAccumulate.Codec)),
8807
8394
  });
8808
- static create({ manager, authManager, validatorsManager, autoAccumulateServices }) {
8809
- return new PrivilegedServices(manager, authManager, validatorsManager, autoAccumulateServices);
8395
+ static create(a) {
8396
+ return new PrivilegedServices(a.manager, a.delegator, a.registrar, a.assigners, a.autoAccumulateServices);
8810
8397
  }
8811
8398
  constructor(
8812
8399
  /**
8813
- * `chi_m`: The first, χm, is the index of the manager service which is
8814
- * the service able to effect an alteration of χ from block to block,
8400
+ * `χ_M`: Manages alteration of χ from block to block,
8815
8401
  * as well as bestow services with storage deposit credits.
8816
- * https://graypaper.fluffylabs.dev/#/7e6ff6a/11a40111a801?v=0.6.7
8402
+ * https://graypaper.fluffylabs.dev/#/ab2cdbd/111502111902?v=0.7.2
8817
8403
  */
8818
8404
  manager,
8819
- /** `chi_a`: Manages authorization queue one for each core. */
8820
- authManager,
8821
- /** `chi_v`: Managers validator keys. */
8822
- validatorsManager,
8823
- /** `chi_g`: Dictionary of services that auto-accumulate every block with their gas limit. */
8405
+ /** `χ_V`: Managers validator keys. */
8406
+ delegator,
8407
+ /**
8408
+ * `χ_R`: Manages the creation of services in protected range.
8409
+ *
8410
+ * https://graypaper.fluffylabs.dev/#/ab2cdbd/111b02111d02?v=0.7.2
8411
+ */
8412
+ registrar,
8413
+ /** `χ_A`: Manages authorization queue one for each core. */
8414
+ assigners,
8415
+ /** `χ_Z`: Dictionary of services that auto-accumulate every block with their gas limit. */
8824
8416
  autoAccumulateServices) {
8825
8417
  this.manager = manager;
8826
- this.authManager = authManager;
8827
- this.validatorsManager = validatorsManager;
8418
+ this.delegator = delegator;
8419
+ this.registrar = registrar;
8420
+ this.assigners = assigners;
8828
8421
  this.autoAccumulateServices = autoAccumulateServices;
8829
8422
  }
8830
8423
  }
@@ -9086,172 +8679,6 @@ class SafroleData {
9086
8679
  }
9087
8680
  }
9088
8681
 
9089
- /**
9090
- * `B_S`: The basic minimum balance which all services require.
9091
- *
9092
- * https://graypaper.fluffylabs.dev/#/7e6ff6a/445800445800?v=0.6.7
9093
- */
9094
- const BASE_SERVICE_BALANCE = 100n;
9095
- /**
9096
- * `B_I`: The additional minimum balance required per item of elective service state.
9097
- *
9098
- * https://graypaper.fluffylabs.dev/#/7e6ff6a/445000445000?v=0.6.7
9099
- */
9100
- const ELECTIVE_ITEM_BALANCE = 10n;
9101
- /**
9102
- * `B_L`: The additional minimum balance required per octet of elective service state.
9103
- *
9104
- * https://graypaper.fluffylabs.dev/#/7e6ff6a/445400445400?v=0.6.7
9105
- */
9106
- const ELECTIVE_BYTE_BALANCE = 1n;
9107
- const zeroSizeHint = {
9108
- bytes: 0,
9109
- isExact: true,
9110
- };
9111
- /** 0-byte read, return given default value */
9112
- const ignoreValueWithDefault = (defaultValue) => Descriptor.new("ignoreValue", zeroSizeHint, (_e, _v) => { }, (_d) => defaultValue, (_s) => { });
9113
- /**
9114
- * Service account details.
9115
- *
9116
- * https://graypaper.fluffylabs.dev/#/7e6ff6a/108301108301?v=0.6.7
9117
- */
9118
- class ServiceAccountInfo extends WithDebug {
9119
- codeHash;
9120
- balance;
9121
- accumulateMinGas;
9122
- onTransferMinGas;
9123
- storageUtilisationBytes;
9124
- gratisStorage;
9125
- storageUtilisationCount;
9126
- created;
9127
- lastAccumulation;
9128
- parentService;
9129
- static Codec = codec$1.Class(ServiceAccountInfo, {
9130
- codeHash: codec$1.bytes(HASH_SIZE).asOpaque(),
9131
- balance: codec$1.u64,
9132
- accumulateMinGas: codec$1.u64.convert((x) => x, tryAsServiceGas),
9133
- onTransferMinGas: codec$1.u64.convert((x) => x, tryAsServiceGas),
9134
- storageUtilisationBytes: codec$1.u64,
9135
- gratisStorage: codec$1.u64,
9136
- storageUtilisationCount: codec$1.u32,
9137
- created: codec$1.u32.convert((x) => x, tryAsTimeSlot),
9138
- lastAccumulation: codec$1.u32.convert((x) => x, tryAsTimeSlot),
9139
- parentService: codec$1.u32.convert((x) => x, tryAsServiceId),
9140
- });
9141
- static create(a) {
9142
- return new ServiceAccountInfo(a.codeHash, a.balance, a.accumulateMinGas, a.onTransferMinGas, a.storageUtilisationBytes, a.gratisStorage, a.storageUtilisationCount, a.created, a.lastAccumulation, a.parentService);
9143
- }
9144
- /**
9145
- * `a_t = max(0, BS + BI * a_i + BL * a_o - a_f)`
9146
- * https://graypaper.fluffylabs.dev/#/7e6ff6a/119e01119e01?v=0.6.7
9147
- */
9148
- static calculateThresholdBalance(items, bytes, gratisStorage) {
9149
- const storageCost = BASE_SERVICE_BALANCE + ELECTIVE_ITEM_BALANCE * BigInt(items) + ELECTIVE_BYTE_BALANCE * bytes - gratisStorage;
9150
- if (storageCost < 0n) {
9151
- return tryAsU64(0);
9152
- }
9153
- if (storageCost >= 2n ** 64n) {
9154
- return tryAsU64(2n ** 64n - 1n);
9155
- }
9156
- return tryAsU64(storageCost);
9157
- }
9158
- constructor(
9159
- /** `a_c`: Hash of the service code. */
9160
- codeHash,
9161
- /** `a_b`: Current account balance. */
9162
- balance,
9163
- /** `a_g`: Minimal gas required to execute Accumulate entrypoint. */
9164
- accumulateMinGas,
9165
- /** `a_m`: Minimal gas required to execute On Transfer entrypoint. */
9166
- onTransferMinGas,
9167
- /** `a_o`: Total number of octets in storage. */
9168
- storageUtilisationBytes,
9169
- /** `a_f`: Cost-free storage. Decreases both storage item count and total byte size. */
9170
- gratisStorage,
9171
- /** `a_i`: Number of items in storage. */
9172
- storageUtilisationCount,
9173
- /** `a_r`: Creation account time slot. */
9174
- created,
9175
- /** `a_a`: Most recent accumulation time slot. */
9176
- lastAccumulation,
9177
- /** `a_p`: Parent service ID. */
9178
- parentService) {
9179
- super();
9180
- this.codeHash = codeHash;
9181
- this.balance = balance;
9182
- this.accumulateMinGas = accumulateMinGas;
9183
- this.onTransferMinGas = onTransferMinGas;
9184
- this.storageUtilisationBytes = storageUtilisationBytes;
9185
- this.gratisStorage = gratisStorage;
9186
- this.storageUtilisationCount = storageUtilisationCount;
9187
- this.created = created;
9188
- this.lastAccumulation = lastAccumulation;
9189
- this.parentService = parentService;
9190
- }
9191
- }
9192
- class PreimageItem extends WithDebug {
9193
- hash;
9194
- blob;
9195
- static Codec = codec$1.Class(PreimageItem, {
9196
- hash: codec$1.bytes(HASH_SIZE).asOpaque(),
9197
- blob: codec$1.blob,
9198
- });
9199
- static create({ hash, blob }) {
9200
- return new PreimageItem(hash, blob);
9201
- }
9202
- constructor(hash, blob) {
9203
- super();
9204
- this.hash = hash;
9205
- this.blob = blob;
9206
- }
9207
- }
9208
- class StorageItem extends WithDebug {
9209
- key;
9210
- value;
9211
- static Codec = codec$1.Class(StorageItem, {
9212
- key: codec$1.blob.convert((i) => i, (o) => asOpaqueType(o)),
9213
- value: codec$1.blob,
9214
- });
9215
- static create({ key, value }) {
9216
- return new StorageItem(key, value);
9217
- }
9218
- constructor(key, value) {
9219
- super();
9220
- this.key = key;
9221
- this.value = value;
9222
- }
9223
- }
9224
- const MAX_LOOKUP_HISTORY_SLOTS = 3;
9225
- function tryAsLookupHistorySlots(items) {
9226
- const knownSize = asKnownSize(items);
9227
- if (knownSize.length > MAX_LOOKUP_HISTORY_SLOTS) {
9228
- throw new Error(`Lookup history items must contain 0-${MAX_LOOKUP_HISTORY_SLOTS} timeslots.`);
9229
- }
9230
- return knownSize;
9231
- }
9232
- /** https://graypaper.fluffylabs.dev/#/5f542d7/115400115800 */
9233
- class LookupHistoryItem {
9234
- hash;
9235
- length;
9236
- slots;
9237
- constructor(hash, length,
9238
- /**
9239
- * Preimage availability history as a sequence of time slots.
9240
- * See PreimageStatus and the following GP fragment for more details.
9241
- * https://graypaper.fluffylabs.dev/#/5f542d7/11780011a500 */
9242
- slots) {
9243
- this.hash = hash;
9244
- this.length = length;
9245
- this.slots = slots;
9246
- }
9247
- static isRequested(item) {
9248
- if ("slots" in item) {
9249
- return item.slots.length === 0;
9250
- }
9251
- return item.length === 0;
9252
- }
9253
- }
9254
-
9255
8682
  /**
9256
8683
  * In addition to the entropy accumulator η_0, we retain
9257
8684
  * three additional historical values of the accumulator at
@@ -9540,8 +8967,7 @@ class CoreStatistics {
9540
8967
  * Service statistics.
9541
8968
  * Updated per block, based on available work reports (`W`).
9542
8969
  *
9543
- * https://graypaper.fluffylabs.dev/#/68eaa1f/185104185104?v=0.6.4
9544
- * https://github.com/gavofyork/graypaper/blob/9bffb08f3ea7b67832019176754df4fb36b9557d/text/statistics.tex#L77
8970
+ * https://graypaper.fluffylabs.dev/#/1c979cb/199802199802?v=0.7.1
9545
8971
  */
9546
8972
  class ServiceStatistics {
9547
8973
  providedCount;
@@ -9556,22 +8982,8 @@ class ServiceStatistics {
9556
8982
  accumulateGasUsed;
9557
8983
  onTransfersCount;
9558
8984
  onTransfersGasUsed;
9559
- static Codec = Compatibility.isGreaterOrEqual(GpVersion.V0_7_0)
9560
- ? codec$1.Class(ServiceStatistics, {
9561
- providedCount: codecVarU16,
9562
- providedSize: codec$1.varU32,
9563
- refinementCount: codec$1.varU32,
9564
- refinementGasUsed: codecVarGas,
9565
- imports: codecVarU16,
9566
- extrinsicCount: codecVarU16,
9567
- extrinsicSize: codec$1.varU32,
9568
- exports: codecVarU16,
9569
- accumulateCount: codec$1.varU32,
9570
- accumulateGasUsed: codecVarGas,
9571
- onTransfersCount: codec$1.varU32,
9572
- onTransfersGasUsed: codecVarGas,
9573
- })
9574
- : codec$1.Class(ServiceStatistics, {
8985
+ static Codec = Compatibility.selectIfGreaterOrEqual({
8986
+ fallback: codec$1.Class(ServiceStatistics, {
9575
8987
  providedCount: codecVarU16,
9576
8988
  providedSize: codec$1.varU32,
9577
8989
  refinementCount: codec$1.varU32,
@@ -9584,7 +8996,38 @@ class ServiceStatistics {
9584
8996
  accumulateGasUsed: codecVarGas,
9585
8997
  onTransfersCount: codec$1.varU32,
9586
8998
  onTransfersGasUsed: codecVarGas,
9587
- });
8999
+ }),
9000
+ versions: {
9001
+ [GpVersion.V0_7_0]: codec$1.Class(ServiceStatistics, {
9002
+ providedCount: codecVarU16,
9003
+ providedSize: codec$1.varU32,
9004
+ refinementCount: codec$1.varU32,
9005
+ refinementGasUsed: codecVarGas,
9006
+ imports: codecVarU16,
9007
+ extrinsicCount: codecVarU16,
9008
+ extrinsicSize: codec$1.varU32,
9009
+ exports: codecVarU16,
9010
+ accumulateCount: codec$1.varU32,
9011
+ accumulateGasUsed: codecVarGas,
9012
+ onTransfersCount: codec$1.varU32,
9013
+ onTransfersGasUsed: codecVarGas,
9014
+ }),
9015
+ [GpVersion.V0_7_1]: codec$1.Class(ServiceStatistics, {
9016
+ providedCount: codecVarU16,
9017
+ providedSize: codec$1.varU32,
9018
+ refinementCount: codec$1.varU32,
9019
+ refinementGasUsed: codecVarGas,
9020
+ imports: codecVarU16,
9021
+ extrinsicCount: codecVarU16,
9022
+ extrinsicSize: codec$1.varU32,
9023
+ exports: codecVarU16,
9024
+ accumulateCount: codec$1.varU32,
9025
+ accumulateGasUsed: codecVarGas,
9026
+ onTransfersCount: ignoreValueWithDefault(tryAsU32(0)),
9027
+ onTransfersGasUsed: ignoreValueWithDefault(tryAsServiceGas(0)),
9028
+ }),
9029
+ },
9030
+ });
9588
9031
  static create(v) {
9589
9032
  return new ServiceStatistics(v.providedCount, v.providedSize, v.refinementCount, v.refinementGasUsed, v.imports, v.exports, v.extrinsicSize, v.extrinsicCount, v.accumulateCount, v.accumulateGasUsed, v.onTransfersCount, v.onTransfersGasUsed);
9590
9033
  }
@@ -9609,9 +9052,9 @@ class ServiceStatistics {
9609
9052
  accumulateCount,
9610
9053
  /** `a.1` */
9611
9054
  accumulateGasUsed,
9612
- /** `t.0` */
9055
+ /** `t.0` @deprecated since 0.7.1 */
9613
9056
  onTransfersCount,
9614
- /** `t.1` */
9057
+ /** `t.1` @deprecated since 0.7.1 */
9615
9058
  onTransfersGasUsed) {
9616
9059
  this.providedCount = providedCount;
9617
9060
  this.providedSize = providedSize;
@@ -10059,8 +9502,9 @@ class InMemoryState extends WithDebug {
10059
9502
  epochRoot: Bytes.zero(BANDERSNATCH_RING_ROOT_BYTES).asOpaque(),
10060
9503
  privilegedServices: PrivilegedServices.create({
10061
9504
  manager: tryAsServiceId(0),
10062
- authManager: tryAsPerCore(new Array(spec.coresCount).fill(tryAsServiceId(0)), spec),
10063
- validatorsManager: tryAsServiceId(0),
9505
+ assigners: tryAsPerCore(new Array(spec.coresCount).fill(tryAsServiceId(0)), spec),
9506
+ delegator: tryAsServiceId(0),
9507
+ registrar: tryAsServiceId(MAX_VALUE),
10064
9508
  autoAccumulateServices: [],
10065
9509
  }),
10066
9510
  accumulationOutputLog: SortedArray.fromArray(accumulationOutputComparator, []),
@@ -10119,6 +9563,7 @@ var index$g = /*#__PURE__*/Object.freeze({
10119
9563
  ValidatorStatistics: ValidatorStatistics,
10120
9564
  accumulationOutputComparator: accumulationOutputComparator,
10121
9565
  codecPerCore: codecPerCore,
9566
+ codecWithVersion: codecWithVersion,
10122
9567
  hashComparator: hashComparator,
10123
9568
  ignoreValueWithDefault: ignoreValueWithDefault,
10124
9569
  serviceDataCodec: serviceDataCodec,
@@ -10279,21 +9724,23 @@ var serialize;
10279
9724
  /** C(255, s): https://graypaper.fluffylabs.dev/#/85129da/383103383103?v=0.6.3 */
10280
9725
  serialize.serviceData = (serviceId) => ({
10281
9726
  key: stateKeys.serviceInfo(serviceId),
10282
- Codec: ServiceAccountInfo.Codec,
9727
+ Codec: Compatibility.isGreaterOrEqual(GpVersion.V0_7_1)
9728
+ ? codecWithVersion(ServiceAccountInfo.Codec)
9729
+ : ServiceAccountInfo.Codec,
10283
9730
  });
10284
9731
  /** https://graypaper.fluffylabs.dev/#/85129da/384803384803?v=0.6.3 */
10285
- serialize.serviceStorage = (serviceId, key) => ({
10286
- key: stateKeys.serviceStorage(serviceId, key),
9732
+ serialize.serviceStorage = (blake2b, serviceId, key) => ({
9733
+ key: stateKeys.serviceStorage(blake2b, serviceId, key),
10287
9734
  Codec: dumpCodec,
10288
9735
  });
10289
9736
  /** https://graypaper.fluffylabs.dev/#/85129da/385b03385b03?v=0.6.3 */
10290
- serialize.servicePreimages = (serviceId, hash) => ({
10291
- key: stateKeys.servicePreimage(serviceId, hash),
9737
+ serialize.servicePreimages = (blake2b, serviceId, hash) => ({
9738
+ key: stateKeys.servicePreimage(blake2b, serviceId, hash),
10292
9739
  Codec: dumpCodec,
10293
9740
  });
10294
9741
  /** https://graypaper.fluffylabs.dev/#/85129da/387603387603?v=0.6.3 */
10295
- serialize.serviceLookupHistory = (serviceId, hash, len) => ({
10296
- key: stateKeys.serviceLookupHistory(serviceId, hash, len),
9742
+ serialize.serviceLookupHistory = (blake2b, serviceId, hash, len) => ({
9743
+ key: stateKeys.serviceLookupHistory(blake2b, serviceId, hash, len),
10297
9744
  Codec: readonlyArray(codec$1.sequenceVarLen(codec$1.u32)),
10298
9745
  });
10299
9746
  })(serialize || (serialize = {}));
@@ -10316,20 +9763,22 @@ const dumpCodec = Descriptor.new("Dump", { bytes: 64, isExact: false }, (e, v) =
10316
9763
  */
10317
9764
  class SerializedState {
10318
9765
  spec;
9766
+ blake2b;
10319
9767
  backend;
10320
9768
  _recentServiceIds;
10321
9769
  /** Create a state-like object from collection of serialized entries. */
10322
- static fromStateEntries(spec, state, recentServices = []) {
10323
- return new SerializedState(spec, state, recentServices);
9770
+ static fromStateEntries(spec, blake2b, state, recentServices = []) {
9771
+ return new SerializedState(spec, blake2b, state, recentServices);
10324
9772
  }
10325
9773
  /** Create a state-like object backed by some DB. */
10326
- static new(spec, db, recentServices = []) {
10327
- return new SerializedState(spec, db, recentServices);
9774
+ static new(spec, blake2b, db, recentServices = []) {
9775
+ return new SerializedState(spec, blake2b, db, recentServices);
10328
9776
  }
10329
- constructor(spec, backend,
9777
+ constructor(spec, blake2b, backend,
10330
9778
  /** Best-effort list of recently active services. */
10331
9779
  _recentServiceIds) {
10332
9780
  this.spec = spec;
9781
+ this.blake2b = blake2b;
10333
9782
  this.backend = backend;
10334
9783
  this._recentServiceIds = _recentServiceIds;
10335
9784
  }
@@ -10353,7 +9802,7 @@ class SerializedState {
10353
9802
  if (!this._recentServiceIds.includes(id)) {
10354
9803
  this._recentServiceIds.push(id);
10355
9804
  }
10356
- return new SerializedService(id, serviceData, (key) => this.retrieveOptional(key));
9805
+ return new SerializedService(this.blake2b, id, serviceData, (key) => this.retrieveOptional(key));
10357
9806
  }
10358
9807
  retrieve({ key, Codec }, description) {
10359
9808
  const bytes = this.backend.get(key);
@@ -10429,12 +9878,14 @@ class SerializedState {
10429
9878
  }
10430
9879
  /** Service data representation on a serialized state. */
10431
9880
  class SerializedService {
9881
+ blake2b;
10432
9882
  serviceId;
10433
9883
  accountInfo;
10434
9884
  retrieveOptional;
10435
- constructor(
9885
+ constructor(blake2b,
10436
9886
  /** Service id */
10437
9887
  serviceId, accountInfo, retrieveOptional) {
9888
+ this.blake2b = blake2b;
10438
9889
  this.serviceId = serviceId;
10439
9890
  this.accountInfo = accountInfo;
10440
9891
  this.retrieveOptional = retrieveOptional;
@@ -10447,13 +9898,13 @@ class SerializedService {
10447
9898
  getStorage(rawKey) {
10448
9899
  if (Compatibility.isLessThan(GpVersion.V0_6_7)) {
10449
9900
  const SERVICE_ID_BYTES = 4;
10450
- const serviceIdAndKey = new Uint8Array(SERVICE_ID_BYTES + rawKey.length);
9901
+ const serviceIdAndKey = safeAllocUint8Array(SERVICE_ID_BYTES + rawKey.length);
10451
9902
  serviceIdAndKey.set(u32AsLeBytes(this.serviceId));
10452
9903
  serviceIdAndKey.set(rawKey.raw, SERVICE_ID_BYTES);
10453
- const key = asOpaqueType(BytesBlob.blobFrom(hashBytes(serviceIdAndKey).raw));
10454
- return this.retrieveOptional(serialize.serviceStorage(this.serviceId, key)) ?? null;
9904
+ const key = asOpaqueType(BytesBlob.blobFrom(this.blake2b.hashBytes(serviceIdAndKey).raw));
9905
+ return this.retrieveOptional(serialize.serviceStorage(this.blake2b, this.serviceId, key)) ?? null;
10455
9906
  }
10456
- return this.retrieveOptional(serialize.serviceStorage(this.serviceId, rawKey)) ?? null;
9907
+ return this.retrieveOptional(serialize.serviceStorage(this.blake2b, this.serviceId, rawKey)) ?? null;
10457
9908
  }
10458
9909
  /**
10459
9910
  * Check if preimage is present in the DB.
@@ -10462,15 +9913,15 @@ class SerializedService {
10462
9913
  */
10463
9914
  hasPreimage(hash) {
10464
9915
  // TODO [ToDr] consider optimizing to avoid fetching the whole data.
10465
- return this.retrieveOptional(serialize.servicePreimages(this.serviceId, hash)) !== undefined;
9916
+ return this.retrieveOptional(serialize.servicePreimages(this.blake2b, this.serviceId, hash)) !== undefined;
10466
9917
  }
10467
9918
  /** Retrieve preimage from the DB. */
10468
9919
  getPreimage(hash) {
10469
- return this.retrieveOptional(serialize.servicePreimages(this.serviceId, hash)) ?? null;
9920
+ return this.retrieveOptional(serialize.servicePreimages(this.blake2b, this.serviceId, hash)) ?? null;
10470
9921
  }
10471
9922
  /** Retrieve preimage lookup history. */
10472
9923
  getLookupHistory(hash, len) {
10473
- const rawSlots = this.retrieveOptional(serialize.serviceLookupHistory(this.serviceId, hash, len));
9924
+ const rawSlots = this.retrieveOptional(serialize.serviceLookupHistory(this.blake2b, this.serviceId, hash, len));
10474
9925
  if (rawSlots === undefined) {
10475
9926
  return null;
10476
9927
  }
@@ -10532,7 +9983,7 @@ class TrieNode {
10532
9983
  raw;
10533
9984
  constructor(
10534
9985
  /** Exactly 512 bits / 64 bytes */
10535
- raw = new Uint8Array(TRIE_NODE_BYTES)) {
9986
+ raw = safeAllocUint8Array(TRIE_NODE_BYTES)) {
10536
9987
  this.raw = raw;
10537
9988
  }
10538
9989
  /** Returns the type of the node */
@@ -11107,11 +10558,13 @@ var index$f = /*#__PURE__*/Object.freeze({
11107
10558
  parseInputKey: parseInputKey
11108
10559
  });
11109
10560
 
11110
- const blake2bTrieHasher = {
11111
- hashConcat(n, rest = []) {
11112
- return hashBlobs$1([n, ...rest]);
11113
- },
11114
- };
10561
+ function getBlake2bTrieHasher(hasher) {
10562
+ return {
10563
+ hashConcat(n, rest = []) {
10564
+ return hasher.hashBlobs([n, ...rest]);
10565
+ },
10566
+ };
10567
+ }
11115
10568
 
11116
10569
  /** What should be done with that key? */
11117
10570
  var StateEntryUpdateAction;
@@ -11123,14 +10576,14 @@ var StateEntryUpdateAction;
11123
10576
  })(StateEntryUpdateAction || (StateEntryUpdateAction = {}));
11124
10577
  const EMPTY_BLOB = BytesBlob.empty();
11125
10578
  /** Serialize given state update into a series of key-value pairs. */
11126
- function* serializeStateUpdate(spec, update) {
10579
+ function* serializeStateUpdate(spec, blake2b, update) {
11127
10580
  // first let's serialize all of the simple entries (if present!)
11128
10581
  yield* serializeBasicKeys(spec, update);
11129
10582
  const encode = (codec, val) => Encoder.encodeObject(codec, val, spec);
11130
10583
  // then let's proceed with service updates
11131
- yield* serializeServiceUpdates(update.servicesUpdates, encode);
11132
- yield* serializePreimages(update.preimages, encode);
11133
- yield* serializeStorage(update.storage);
10584
+ yield* serializeServiceUpdates(update.servicesUpdates, encode, blake2b);
10585
+ yield* serializePreimages(update.preimages, encode, blake2b);
10586
+ yield* serializeStorage(update.storage, blake2b);
11134
10587
  yield* serializeRemovedServices(update.servicesRemoved);
11135
10588
  }
11136
10589
  function* serializeRemovedServices(servicesRemoved) {
@@ -11140,18 +10593,18 @@ function* serializeRemovedServices(servicesRemoved) {
11140
10593
  yield [StateEntryUpdateAction.Remove, codec.key, EMPTY_BLOB];
11141
10594
  }
11142
10595
  }
11143
- function* serializeStorage(storage) {
10596
+ function* serializeStorage(storage, blake2b) {
11144
10597
  for (const { action, serviceId } of storage ?? []) {
11145
10598
  switch (action.kind) {
11146
10599
  case UpdateStorageKind.Set: {
11147
10600
  const key = action.storage.key;
11148
- const codec = serialize.serviceStorage(serviceId, key);
10601
+ const codec = serialize.serviceStorage(blake2b, serviceId, key);
11149
10602
  yield [StateEntryUpdateAction.Insert, codec.key, action.storage.value];
11150
10603
  break;
11151
10604
  }
11152
10605
  case UpdateStorageKind.Remove: {
11153
10606
  const key = action.key;
11154
- const codec = serialize.serviceStorage(serviceId, key);
10607
+ const codec = serialize.serviceStorage(blake2b, serviceId, key);
11155
10608
  yield [StateEntryUpdateAction.Remove, codec.key, EMPTY_BLOB];
11156
10609
  break;
11157
10610
  }
@@ -11160,15 +10613,15 @@ function* serializeStorage(storage) {
11160
10613
  }
11161
10614
  }
11162
10615
  }
11163
- function* serializePreimages(preimages, encode) {
10616
+ function* serializePreimages(preimages, encode, blake2b) {
11164
10617
  for (const { action, serviceId } of preimages ?? []) {
11165
10618
  switch (action.kind) {
11166
10619
  case UpdatePreimageKind.Provide: {
11167
10620
  const { hash, blob } = action.preimage;
11168
- const codec = serialize.servicePreimages(serviceId, hash);
10621
+ const codec = serialize.servicePreimages(blake2b, serviceId, hash);
11169
10622
  yield [StateEntryUpdateAction.Insert, codec.key, blob];
11170
10623
  if (action.slot !== null) {
11171
- const codec2 = serialize.serviceLookupHistory(serviceId, hash, tryAsU32(blob.length));
10624
+ const codec2 = serialize.serviceLookupHistory(blake2b, serviceId, hash, tryAsU32(blob.length));
11172
10625
  yield [
11173
10626
  StateEntryUpdateAction.Insert,
11174
10627
  codec2.key,
@@ -11179,15 +10632,15 @@ function* serializePreimages(preimages, encode) {
11179
10632
  }
11180
10633
  case UpdatePreimageKind.UpdateOrAdd: {
11181
10634
  const { hash, length, slots } = action.item;
11182
- const codec = serialize.serviceLookupHistory(serviceId, hash, length);
10635
+ const codec = serialize.serviceLookupHistory(blake2b, serviceId, hash, length);
11183
10636
  yield [StateEntryUpdateAction.Insert, codec.key, encode(codec.Codec, slots)];
11184
10637
  break;
11185
10638
  }
11186
10639
  case UpdatePreimageKind.Remove: {
11187
10640
  const { hash, length } = action;
11188
- const codec = serialize.servicePreimages(serviceId, hash);
10641
+ const codec = serialize.servicePreimages(blake2b, serviceId, hash);
11189
10642
  yield [StateEntryUpdateAction.Remove, codec.key, EMPTY_BLOB];
11190
- const codec2 = serialize.serviceLookupHistory(serviceId, hash, length);
10643
+ const codec2 = serialize.serviceLookupHistory(blake2b, serviceId, hash, length);
11191
10644
  yield [StateEntryUpdateAction.Remove, codec2.key, EMPTY_BLOB];
11192
10645
  break;
11193
10646
  }
@@ -11196,7 +10649,7 @@ function* serializePreimages(preimages, encode) {
11196
10649
  }
11197
10650
  }
11198
10651
  }
11199
- function* serializeServiceUpdates(servicesUpdates, encode) {
10652
+ function* serializeServiceUpdates(servicesUpdates, encode, blake2b) {
11200
10653
  for (const { action, serviceId } of servicesUpdates ?? []) {
11201
10654
  // new service being created or updated
11202
10655
  const codec = serialize.serviceData(serviceId);
@@ -11204,7 +10657,7 @@ function* serializeServiceUpdates(servicesUpdates, encode) {
11204
10657
  // additional lookup history update
11205
10658
  if (action.kind === UpdateServiceKind.Create && action.lookupHistory !== null) {
11206
10659
  const { lookupHistory } = action;
11207
- const codec2 = serialize.serviceLookupHistory(serviceId, lookupHistory.hash, lookupHistory.length);
10660
+ const codec2 = serialize.serviceLookupHistory(blake2b, serviceId, lookupHistory.hash, lookupHistory.length);
11208
10661
  yield [StateEntryUpdateAction.Insert, codec2.key, encode(codec2.Codec, lookupHistory.slots)];
11209
10662
  }
11210
10663
  }
@@ -11299,8 +10752,8 @@ class StateEntries {
11299
10752
  },
11300
10753
  }, (e, v) => stateEntriesSequenceCodec.encode(e, Array.from(v.entries)), (d) => StateEntries.fromEntriesUnsafe(stateEntriesSequenceCodec.decode(d)), (s) => stateEntriesSequenceCodec.skip(s));
11301
10754
  /** Turn in-memory state into it's serialized form. */
11302
- static serializeInMemory(spec, state) {
11303
- return new StateEntries(convertInMemoryStateToDictionary(spec, state));
10755
+ static serializeInMemory(spec, blake2b, state) {
10756
+ return new StateEntries(convertInMemoryStateToDictionary(spec, blake2b, state));
11304
10757
  }
11305
10758
  /**
11306
10759
  * Wrap a collection of truncated state entries and treat it as state.
@@ -11349,7 +10802,8 @@ class StateEntries {
11349
10802
  }
11350
10803
  }
11351
10804
  /** https://graypaper.fluffylabs.dev/#/68eaa1f/391600391600?v=0.6.4 */
11352
- getRootHash() {
10805
+ getRootHash(blake2b) {
10806
+ const blake2bTrieHasher = getBlake2bTrieHasher(blake2b);
11353
10807
  const leaves = SortedSet.fromArray(leafComparator);
11354
10808
  for (const [key, value] of this) {
11355
10809
  leaves.insert(InMemoryTrie.constructLeaf(blake2bTrieHasher, key.asOpaque(), value));
@@ -11358,7 +10812,7 @@ class StateEntries {
11358
10812
  }
11359
10813
  }
11360
10814
  /** https://graypaper.fluffylabs.dev/#/68eaa1f/38a50038a500?v=0.6.4 */
11361
- function convertInMemoryStateToDictionary(spec, state) {
10815
+ function convertInMemoryStateToDictionary(spec, blake2b, state) {
11362
10816
  const serialized = TruncatedHashDictionary.fromEntries([]);
11363
10817
  function doSerialize(codec) {
11364
10818
  serialized.set(codec.key, Encoder.encodeObject(codec.Codec, codec.extract(state), spec));
@@ -11386,18 +10840,18 @@ function convertInMemoryStateToDictionary(spec, state) {
11386
10840
  serialized.set(key, Encoder.encodeObject(Codec, service.getInfo()));
11387
10841
  // preimages
11388
10842
  for (const preimage of service.data.preimages.values()) {
11389
- const { key, Codec } = serialize.servicePreimages(serviceId, preimage.hash);
10843
+ const { key, Codec } = serialize.servicePreimages(blake2b, serviceId, preimage.hash);
11390
10844
  serialized.set(key, Encoder.encodeObject(Codec, preimage.blob));
11391
10845
  }
11392
10846
  // storage
11393
10847
  for (const storage of service.data.storage.values()) {
11394
- const { key, Codec } = serialize.serviceStorage(serviceId, storage.key);
10848
+ const { key, Codec } = serialize.serviceStorage(blake2b, serviceId, storage.key);
11395
10849
  serialized.set(key, Encoder.encodeObject(Codec, storage.value));
11396
10850
  }
11397
10851
  // lookup history
11398
10852
  for (const lookupHistoryList of service.data.lookupHistory.values()) {
11399
10853
  for (const lookupHistory of lookupHistoryList) {
11400
- const { key, Codec } = serialize.serviceLookupHistory(serviceId, lookupHistory.hash, lookupHistory.length);
10854
+ const { key, Codec } = serialize.serviceLookupHistory(blake2b, serviceId, lookupHistory.hash, lookupHistory.length);
11401
10855
  serialized.set(key, Encoder.encodeObject(Codec, lookupHistory.slots.slice()));
11402
10856
  }
11403
10857
  }
@@ -11405,9 +10859,9 @@ function convertInMemoryStateToDictionary(spec, state) {
11405
10859
  return serialized;
11406
10860
  }
11407
10861
 
11408
- function loadState(spec, entries) {
10862
+ function loadState(spec, blake2b, entries) {
11409
10863
  const stateEntries = StateEntries.fromEntriesUnsafe(entries);
11410
- return SerializedState.fromStateEntries(spec, stateEntries);
10864
+ return SerializedState.fromStateEntries(spec, blake2b, stateEntries);
11411
10865
  }
11412
10866
 
11413
10867
  /**
@@ -11515,7 +10969,8 @@ class LeafDb {
11515
10969
  }
11516
10970
  assertNever(val);
11517
10971
  }
11518
- getStateRoot() {
10972
+ getStateRoot(blake2b) {
10973
+ const blake2bTrieHasher = getBlake2bTrieHasher(blake2b);
11519
10974
  return InMemoryTrie.computeStateRoot(blake2bTrieHasher, this.leaves).asOpaque();
11520
10975
  }
11521
10976
  intoStateEntries() {
@@ -11705,7 +11160,8 @@ class InMemoryStates {
11705
11160
  }
11706
11161
  }
11707
11162
  async getStateRoot(state) {
11708
- return StateEntries.serializeInMemory(this.spec, state).getRootHash();
11163
+ const blake2b = await Blake2b.createHasher();
11164
+ return StateEntries.serializeInMemory(this.spec, blake2b, state).getRootHash(blake2b);
11709
11165
  }
11710
11166
  /** Insert a full state into the database. */
11711
11167
  async insertState(headerHash, state) {
@@ -11783,7 +11239,7 @@ function padAndEncodeData(input) {
11783
11239
  const paddedLength = Math.ceil(input.length / PIECE_SIZE) * PIECE_SIZE;
11784
11240
  let padded = input;
11785
11241
  if (input.length !== paddedLength) {
11786
- padded = BytesBlob.blobFrom(new Uint8Array(paddedLength));
11242
+ padded = BytesBlob.blobFrom(safeAllocUint8Array(paddedLength));
11787
11243
  padded.raw.set(input.raw, 0);
11788
11244
  }
11789
11245
  return chunkingFunction(padded);
@@ -11829,7 +11285,7 @@ function decodeData(input) {
11829
11285
  */
11830
11286
  function encodePoints(input) {
11831
11287
  const result = [];
11832
- const data = new Uint8Array(POINT_ALIGNMENT * N_CHUNKS_REQUIRED);
11288
+ const data = safeAllocUint8Array(POINT_ALIGNMENT * N_CHUNKS_REQUIRED);
11833
11289
  // add original shards to the result
11834
11290
  for (let i = 0; i < N_CHUNKS_REQUIRED; i++) {
11835
11291
  const pointStart = POINT_LENGTH * i;
@@ -11845,7 +11301,7 @@ function encodePoints(input) {
11845
11301
  const encodedData = encodedResult.take_data();
11846
11302
  for (let i = 0; i < N_CHUNKS_REDUNDANCY; i++) {
11847
11303
  const pointIndex = i * POINT_ALIGNMENT;
11848
- const redundancyPoint = new Uint8Array(POINT_LENGTH);
11304
+ const redundancyPoint = safeAllocUint8Array(POINT_LENGTH);
11849
11305
  for (let j = 0; j < POINT_LENGTH; j++) {
11850
11306
  redundancyPoint[j] = encodedData[pointIndex + j * HALF_POINT_SIZE];
11851
11307
  }
@@ -11860,7 +11316,7 @@ function encodePoints(input) {
11860
11316
  */
11861
11317
  function decodePiece(input) {
11862
11318
  const result = Bytes.zero(PIECE_SIZE);
11863
- const data = new Uint8Array(N_CHUNKS_REQUIRED * POINT_ALIGNMENT);
11319
+ const data = safeAllocUint8Array(N_CHUNKS_REQUIRED * POINT_ALIGNMENT);
11864
11320
  const indices = new Uint16Array(input.length);
11865
11321
  for (let i = 0; i < N_CHUNKS_REQUIRED; i++) {
11866
11322
  const [index, points] = input[i];
@@ -11976,7 +11432,7 @@ function lace(input) {
11976
11432
  return BytesBlob.empty();
11977
11433
  }
11978
11434
  const n = input[0].length;
11979
- const result = BytesBlob.blobFrom(new Uint8Array(k * n));
11435
+ const result = BytesBlob.blobFrom(safeAllocUint8Array(k * n));
11980
11436
  for (let i = 0; i < k; i++) {
11981
11437
  const entry = input[i].raw;
11982
11438
  for (let j = 0; j < n; j++) {
@@ -12655,6 +12111,8 @@ var NewServiceError;
12655
12111
  NewServiceError[NewServiceError["InsufficientFunds"] = 0] = "InsufficientFunds";
12656
12112
  /** Service is not privileged to set gratis storage. */
12657
12113
  NewServiceError[NewServiceError["UnprivilegedService"] = 1] = "UnprivilegedService";
12114
+ /** Registrar attempting to create a service with already existing id. */
12115
+ NewServiceError[NewServiceError["RegistrarServiceIdAlreadyTaken"] = 2] = "RegistrarServiceIdAlreadyTaken";
12658
12116
  })(NewServiceError || (NewServiceError = {}));
12659
12117
  var UpdatePrivilegesError;
12660
12118
  (function (UpdatePrivilegesError) {
@@ -12845,11 +12303,17 @@ class AccumulationStateUpdate {
12845
12303
  if (from.privilegedServices !== null) {
12846
12304
  update.privilegedServices = PrivilegedServices.create({
12847
12305
  ...from.privilegedServices,
12848
- authManager: asKnownSize([...from.privilegedServices.authManager]),
12306
+ assigners: asKnownSize([...from.privilegedServices.assigners]),
12849
12307
  });
12850
12308
  }
12851
12309
  return update;
12852
12310
  }
12311
+ /** Retrieve and clear pending transfers. */
12312
+ takeTransfers() {
12313
+ const transfers = this.transfers;
12314
+ this.transfers = [];
12315
+ return transfers;
12316
+ }
12853
12317
  }
12854
12318
  class PartiallyUpdatedState {
12855
12319
  state;
@@ -13046,7 +12510,7 @@ const HostCallResult = {
13046
12510
  OOB: tryAsU64(0xfffffffffffffffdn), // 2**64 - 3
13047
12511
  /** Index unknown. */
13048
12512
  WHO: tryAsU64(0xfffffffffffffffcn), // 2**64 - 4
13049
- /** Storage full. */
12513
+ /** Storage full or resource already allocated. */
13050
12514
  FULL: tryAsU64(0xfffffffffffffffbn), // 2**64 - 5
13051
12515
  /** Core index unknown. */
13052
12516
  CORE: tryAsU64(0xfffffffffffffffan), // 2**64 - 6
@@ -13054,7 +12518,7 @@ const HostCallResult = {
13054
12518
  CASH: tryAsU64(0xfffffffffffffff9n), // 2**64 - 7
13055
12519
  /** Gas limit too low. */
13056
12520
  LOW: tryAsU64(0xfffffffffffffff8n), // 2**64 - 8
13057
- /** The item is already solicited or cannot be forgotten. */
12521
+ /** The item is already solicited, cannot be forgotten or the operation is invalid due to privilege level. */
13058
12522
  HUH: tryAsU64(0xfffffffffffffff7n), // 2**64 - 9
13059
12523
  /** The return value indicating general success. */
13060
12524
  OK: tryAsU64(0n),
@@ -13255,7 +12719,7 @@ class Registers {
13255
12719
  bytes;
13256
12720
  asSigned;
13257
12721
  asUnsigned;
13258
- constructor(bytes = new Uint8Array(NO_OF_REGISTERS$1 << REGISTER_SIZE_SHIFT)) {
12722
+ constructor(bytes = safeAllocUint8Array(NO_OF_REGISTERS$1 << REGISTER_SIZE_SHIFT)) {
13259
12723
  this.bytes = bytes;
13260
12724
  check `${bytes.length === NO_OF_REGISTERS$1 << REGISTER_SIZE_SHIFT} Invalid size of registers array.`;
13261
12725
  this.asSigned = new BigInt64Array(bytes.buffer, bytes.byteOffset);
@@ -13327,10 +12791,16 @@ function signExtend32To64(value) {
13327
12791
 
13328
12792
  /** Attempt to convert a number into `HostCallIndex`. */
13329
12793
  const tryAsHostCallIndex = (v) => asOpaqueType(tryAsU32(v));
12794
+ /**
12795
+ * Host-call exit reason.
12796
+ *
12797
+ * https://graypaper.fluffylabs.dev/#/ab2cdbd/24a30124a501?v=0.7.2
12798
+ */
13330
12799
  var PvmExecution;
13331
12800
  (function (PvmExecution) {
13332
12801
  PvmExecution[PvmExecution["Halt"] = 0] = "Halt";
13333
12802
  PvmExecution[PvmExecution["Panic"] = 1] = "Panic";
12803
+ PvmExecution[PvmExecution["OOG"] = 2] = "OOG";
13334
12804
  })(PvmExecution || (PvmExecution = {}));
13335
12805
  /** A utility function to easily trace a bunch of registers. */
13336
12806
  function traceRegisters(...regs) {
@@ -13402,7 +12872,7 @@ class Mask {
13402
12872
  return Math.min(this.lookupTableForward[index] ?? 0, MAX_INSTRUCTION_DISTANCE);
13403
12873
  }
13404
12874
  buildLookupTableForward(mask) {
13405
- const table = new Uint8Array(mask.bitLength);
12875
+ const table = safeAllocUint8Array(mask.bitLength);
13406
12876
  let lastInstructionOffset = 0;
13407
12877
  for (let i = mask.bitLength - 1; i >= 0; i--) {
13408
12878
  if (mask.isSet(i)) {
@@ -15083,11 +14553,6 @@ class BitOps {
15083
14553
  }
15084
14554
  }
15085
14555
 
15086
- const MAX_VALUE = 4294967295;
15087
- const MIN_VALUE = -2147483648;
15088
- const MAX_SHIFT_U32 = 32;
15089
- const MAX_SHIFT_U64 = 64n;
15090
-
15091
14556
  /**
15092
14557
  * Overflowing addition for two-complement representation of 32-bit signed numbers.
15093
14558
  */
@@ -16837,6 +16302,24 @@ class Interpreter {
16837
16302
  getMemoryPage(pageNumber) {
16838
16303
  return this.memory.getPageDump(tryAsPageNumber(pageNumber));
16839
16304
  }
16305
+ calculateBlockGasCost() {
16306
+ const codeLength = this.code.length;
16307
+ const blocks = new Map();
16308
+ let currentBlock = "0";
16309
+ let gasCost = 0;
16310
+ const getNextIstructionIndex = (index) => index + 1 + this.mask.getNoOfBytesToNextInstruction(index + 1);
16311
+ for (let index = 0; index < codeLength; index = getNextIstructionIndex(index)) {
16312
+ const instruction = this.code[index];
16313
+ if (this.basicBlocks.isBeginningOfBasicBlock(index)) {
16314
+ blocks.set(currentBlock, gasCost);
16315
+ currentBlock = index.toString();
16316
+ gasCost = 0;
16317
+ }
16318
+ gasCost += instructionGasMap[instruction];
16319
+ }
16320
+ blocks.set(currentBlock, gasCost);
16321
+ return blocks;
16322
+ }
16840
16323
  }
16841
16324
 
16842
16325
  var index$7 = /*#__PURE__*/Object.freeze({
@@ -16937,7 +16420,7 @@ class HostCalls {
16937
16420
  const regs = pvmInstance.getRegisters();
16938
16421
  const maybeAddress = regs.getLowerU32(7);
16939
16422
  const maybeLength = regs.getLowerU32(8);
16940
- const result = new Uint8Array(maybeLength);
16423
+ const result = safeAllocUint8Array(maybeLength);
16941
16424
  const startAddress = tryAsMemoryIndex(maybeAddress);
16942
16425
  const loadResult = memory.loadInto(result, startAddress);
16943
16426
  if (loadResult.isError) {
@@ -16965,8 +16448,9 @@ class HostCalls {
16965
16448
  const index = tryAsHostCallIndex(hostCallIndex);
16966
16449
  const hostCall = this.hostCalls.get(index);
16967
16450
  const gasBefore = gas.get();
16968
- const gasCost = typeof hostCall.gasCost === "number" ? hostCall.gasCost : hostCall.gasCost(regs);
16969
- const underflow = gas.sub(gasCost);
16451
+ // NOTE: `basicGasCost(regs)` function is for compatibility reasons: pre GP 0.7.2
16452
+ const basicGasCost = typeof hostCall.basicGasCost === "number" ? hostCall.basicGasCost : hostCall.basicGasCost(regs);
16453
+ const underflow = gas.sub(basicGasCost);
16970
16454
  const pcLog = `[PC: ${pvmInstance.getPC()}]`;
16971
16455
  if (underflow) {
16972
16456
  this.hostCalls.traceHostCall(`${pcLog} OOG`, index, hostCall, regs, gas.get());
@@ -16983,6 +16467,10 @@ class HostCalls {
16983
16467
  status = Status.PANIC;
16984
16468
  return this.getReturnValue(status, pvmInstance);
16985
16469
  }
16470
+ if (result === PvmExecution.OOG) {
16471
+ status = Status.OOG;
16472
+ return this.getReturnValue(status, pvmInstance);
16473
+ }
16986
16474
  if (result === undefined) {
16987
16475
  pvmInstance.runProgram();
16988
16476
  status = pvmInstance.getStatus();
@@ -17281,14 +16769,14 @@ class DebuggerAdapter {
17281
16769
  const page = this.pvm.getMemoryPage(pageNumber);
17282
16770
  if (page === null) {
17283
16771
  // page wasn't allocated so we return an empty page
17284
- return new Uint8Array(PAGE_SIZE$1);
16772
+ return safeAllocUint8Array(PAGE_SIZE$1);
17285
16773
  }
17286
16774
  if (page.length === PAGE_SIZE$1) {
17287
16775
  // page was allocated and has a proper size so we can simply return it
17288
16776
  return page;
17289
16777
  }
17290
16778
  // page was allocated but it is shorter than PAGE_SIZE so we have to extend it
17291
- const fullPage = new Uint8Array(PAGE_SIZE$1);
16779
+ const fullPage = safeAllocUint8Array(PAGE_SIZE$1);
17292
16780
  fullPage.set(page);
17293
16781
  return fullPage;
17294
16782
  }
@@ -17392,7 +16880,7 @@ var index$3 = /*#__PURE__*/Object.freeze({
17392
16880
  extractCodeAndMetadata: extractCodeAndMetadata,
17393
16881
  getServiceId: getServiceId,
17394
16882
  getServiceIdOrCurrent: getServiceIdOrCurrent,
17395
- hash: index$p,
16883
+ hash: index$o,
17396
16884
  inspect: inspect,
17397
16885
  instructionArgumentTypeMap: instructionArgumentTypeMap,
17398
16886
  interpreter: index$7,
@@ -17414,10 +16902,10 @@ const ENTROPY_BYTES = 32;
17414
16902
  *
17415
16903
  * https://graypaper.fluffylabs.dev/#/579bd12/3b9a013b9a01
17416
16904
  */
17417
- function fisherYatesShuffle(arr, entropy) {
16905
+ function fisherYatesShuffle(blake2b, arr, entropy) {
17418
16906
  check `${entropy.length === ENTROPY_BYTES} Expected entropy of length ${ENTROPY_BYTES}, got ${entropy.length}`;
17419
16907
  const n = arr.length;
17420
- const randomNumbers = hashToNumberSequence(entropy, arr.length);
16908
+ const randomNumbers = hashToNumberSequence(blake2b, entropy, arr.length);
17421
16909
  const result = new Array(n);
17422
16910
  let itemsLeft = n;
17423
16911
  for (let i = 0; i < n; i++) {
@@ -17430,13 +16918,13 @@ function fisherYatesShuffle(arr, entropy) {
17430
16918
  }
17431
16919
  return result;
17432
16920
  }
17433
- function hashToNumberSequence(entropy, length) {
16921
+ function hashToNumberSequence(blake2b, entropy, length) {
17434
16922
  const result = new Array(length);
17435
- const randomBytes = new Uint8Array(ENTROPY_BYTES + 4);
16923
+ const randomBytes = safeAllocUint8Array(ENTROPY_BYTES + 4);
17436
16924
  randomBytes.set(entropy.raw);
17437
16925
  for (let i = 0; i < length; i++) {
17438
16926
  randomBytes.set(u32AsLeBytes(tryAsU32(Math.floor(i / 8))), ENTROPY_BYTES);
17439
- const newHash = hashBytes(randomBytes);
16927
+ const newHash = blake2b.hashBytes(randomBytes);
17440
16928
  const numberStartIndex = (4 * i) % 32;
17441
16929
  const numberEndIndex = numberStartIndex + 4;
17442
16930
  const number = leBytesAsU32(newHash.raw.subarray(numberStartIndex, numberEndIndex)) >>> 0;
@@ -17452,6 +16940,7 @@ var index$2 = /*#__PURE__*/Object.freeze({
17452
16940
 
17453
16941
  class JsonServiceInfo {
17454
16942
  static fromJson = json.object({
16943
+ ...(Compatibility.isGreaterOrEqual(GpVersion.V0_7_1) ? { version: "number" } : {}),
17455
16944
  code_hash: fromJson.bytes32(),
17456
16945
  balance: json.fromNumber((x) => tryAsU64(x)),
17457
16946
  min_item_gas: json.fromNumber((x) => tryAsServiceGas(x)),
@@ -17476,6 +16965,7 @@ class JsonServiceInfo {
17476
16965
  parentService: parent_service,
17477
16966
  });
17478
16967
  });
16968
+ version;
17479
16969
  code_hash;
17480
16970
  balance;
17481
16971
  min_item_gas;
@@ -17510,23 +17000,35 @@ const lookupMetaFromJson = json.object({
17510
17000
  },
17511
17001
  value: json.array("number"),
17512
17002
  }, ({ key, value }) => new LookupHistoryItem(key.hash, key.length, value));
17003
+ const preimageStatusFromJson = json.object({
17004
+ hash: fromJson.bytes32(),
17005
+ status: json.array("number"),
17006
+ }, ({ hash, status }) => new LookupHistoryItem(hash, tryAsU32(0), status));
17513
17007
  class JsonService {
17514
17008
  static fromJson = json.object({
17515
17009
  id: "number",
17516
- data: {
17517
- service: JsonServiceInfo.fromJson,
17518
- preimages: json.optional(json.array(JsonPreimageItem.fromJson)),
17519
- storage: json.optional(json.array(JsonStorageItem.fromJson)),
17520
- lookup_meta: json.optional(json.array(lookupMetaFromJson)),
17521
- },
17010
+ data: Compatibility.isLessThan(GpVersion.V0_7_1)
17011
+ ? {
17012
+ service: JsonServiceInfo.fromJson,
17013
+ preimages: json.optional(json.array(JsonPreimageItem.fromJson)),
17014
+ storage: json.optional(json.array(JsonStorageItem.fromJson)),
17015
+ lookup_meta: json.optional(json.array(lookupMetaFromJson)),
17016
+ }
17017
+ : {
17018
+ service: JsonServiceInfo.fromJson,
17019
+ storage: json.optional(json.array(JsonStorageItem.fromJson)),
17020
+ preimages_blob: json.optional(json.array(JsonPreimageItem.fromJson)),
17021
+ preimages_status: json.optional(json.array(preimageStatusFromJson)),
17022
+ },
17522
17023
  }, ({ id, data }) => {
17024
+ const preimages = HashDictionary.fromEntries((data.preimages ?? data.preimages_blob ?? []).map((x) => [x.hash, x]));
17523
17025
  const lookupHistory = HashDictionary.new();
17524
- for (const item of data.lookup_meta ?? []) {
17026
+ for (const item of data.lookup_meta ?? data.preimages_status ?? []) {
17525
17027
  const data = lookupHistory.get(item.hash) ?? [];
17526
- data.push(item);
17028
+ const length = tryAsU32(preimages.get(item.hash)?.blob.length ?? item.length);
17029
+ data.push(new LookupHistoryItem(item.hash, length, item.slots));
17527
17030
  lookupHistory.set(item.hash, data);
17528
17031
  }
17529
- const preimages = HashDictionary.fromEntries((data.preimages ?? []).map((x) => [x.hash, x]));
17530
17032
  const storage = new Map();
17531
17033
  const entries = (data.storage ?? []).map(({ key, value }) => {
17532
17034
  const opaqueKey = asOpaqueType(key);
@@ -17550,8 +17052,7 @@ const availabilityAssignmentFromJson = json.object({
17550
17052
  report: workReportFromJson,
17551
17053
  timeout: "number",
17552
17054
  }, ({ report, timeout }) => {
17553
- const workReportHash = hashBytes(Encoder.encodeObject(WorkReport.Codec, report)).asOpaque();
17554
- return AvailabilityAssignment.create({ workReport: new WithHash(workReportHash, report), timeout });
17055
+ return AvailabilityAssignment.create({ workReport: report, timeout });
17555
17056
  });
17556
17057
 
17557
17058
  const disputesRecordsFromJson = json.object({
@@ -17699,8 +17200,12 @@ class JsonServiceStatistics {
17699
17200
  extrinsic_count: "number",
17700
17201
  accumulate_count: "number",
17701
17202
  accumulate_gas_used: json.fromNumber(tryAsServiceGas),
17702
- on_transfers_count: "number",
17703
- on_transfers_gas_used: json.fromNumber(tryAsServiceGas),
17203
+ ...(Compatibility.isLessThan(GpVersion.V0_7_1)
17204
+ ? {
17205
+ on_transfers_count: "number",
17206
+ on_transfers_gas_used: json.fromNumber(tryAsServiceGas),
17207
+ }
17208
+ : {}),
17704
17209
  }, ({ provided_count, provided_size, refinement_count, refinement_gas_used, imports, exports, extrinsic_size, extrinsic_count, accumulate_count, accumulate_gas_used, on_transfers_count, on_transfers_gas_used, }) => {
17705
17210
  return ServiceStatistics.create({
17706
17211
  providedCount: provided_count,
@@ -17713,8 +17218,8 @@ class JsonServiceStatistics {
17713
17218
  extrinsicCount: extrinsic_count,
17714
17219
  accumulateCount: accumulate_count,
17715
17220
  accumulateGasUsed: accumulate_gas_used,
17716
- onTransfersCount: on_transfers_count,
17717
- onTransfersGasUsed: on_transfers_gas_used,
17221
+ onTransfersCount: on_transfers_count ?? tryAsU32(0),
17222
+ onTransfersGasUsed: on_transfers_gas_used ?? tryAsServiceGas(0),
17718
17223
  });
17719
17224
  });
17720
17225
  provided_count;
@@ -17785,6 +17290,7 @@ const fullStateDumpFromJson = (spec) => json.object({
17785
17290
  chi_m: "number",
17786
17291
  chi_a: json.array("number"),
17787
17292
  chi_v: "number",
17293
+ chi_r: json.optional("number"),
17788
17294
  chi_g: json.nullable(json.array({
17789
17295
  service: "number",
17790
17296
  gasLimit: json.fromNumber((v) => tryAsServiceGas(v)),
@@ -17796,6 +17302,9 @@ const fullStateDumpFromJson = (spec) => json.object({
17796
17302
  theta: json.nullable(json.array(accumulationOutput)),
17797
17303
  accounts: json.array(JsonService.fromJson),
17798
17304
  }, ({ alpha, varphi, beta, gamma, psi, eta, iota, kappa, lambda, rho, tau, chi, pi, omega, xi, theta, accounts, }) => {
17305
+ if (Compatibility.isGreaterOrEqual(GpVersion.V0_7_1) && chi.chi_r === undefined) {
17306
+ throw new Error("Registrar is required in Privileges GP ^0.7.1");
17307
+ }
17799
17308
  return InMemoryState.create({
17800
17309
  authPools: tryAsPerCore(alpha.map((perCore) => {
17801
17310
  if (perCore.length > MAX_AUTH_POOL_SIZE) {
@@ -17823,8 +17332,9 @@ const fullStateDumpFromJson = (spec) => json.object({
17823
17332
  timeslot: tau,
17824
17333
  privilegedServices: PrivilegedServices.create({
17825
17334
  manager: chi.chi_m,
17826
- authManager: chi.chi_a,
17827
- validatorsManager: chi.chi_v,
17335
+ assigners: chi.chi_a,
17336
+ delegator: chi.chi_v,
17337
+ registrar: chi.chi_r ?? tryAsServiceId(2 ** 32 - 1),
17828
17338
  autoAccumulateServices: chi.chi_g ?? [],
17829
17339
  }),
17830
17340
  statistics: JsonStatisticsData.toStatisticsData(spec, pi),
@@ -17857,11 +17367,11 @@ var index$1 = /*#__PURE__*/Object.freeze({
17857
17367
  class TransitionHasher {
17858
17368
  context;
17859
17369
  keccakHasher;
17860
- allocator;
17861
- constructor(context, keccakHasher, allocator) {
17370
+ blake2b;
17371
+ constructor(context, keccakHasher, blake2b) {
17862
17372
  this.context = context;
17863
17373
  this.keccakHasher = keccakHasher;
17864
- this.allocator = allocator;
17374
+ this.blake2b = blake2b;
17865
17375
  }
17866
17376
  /** Concatenates two hashes and hash this concatenation */
17867
17377
  hashConcat(a, b) {
@@ -17872,7 +17382,7 @@ class TransitionHasher {
17872
17382
  }
17873
17383
  /** Creates hash from the block header view */
17874
17384
  header(header) {
17875
- return new WithHash(hashBytes(header.encoded(), this.allocator).asOpaque(), header);
17385
+ return new WithHash(this.blake2b.hashBytes(header.encoded()).asOpaque(), header);
17876
17386
  }
17877
17387
  /**
17878
17388
  * Merkle commitment of the extrinsic data
@@ -17885,7 +17395,7 @@ class TransitionHasher {
17885
17395
  .view()
17886
17396
  .map((g) => g.view())
17887
17397
  .map((guarantee) => {
17888
- const reportHash = hashBytes(guarantee.report.encoded(), this.allocator).asOpaque();
17398
+ const reportHash = this.blake2b.hashBytes(guarantee.report.encoded()).asOpaque();
17889
17399
  return BytesBlob.blobFromParts([
17890
17400
  reportHash.raw,
17891
17401
  guarantee.slot.encoded().raw,
@@ -17893,13 +17403,13 @@ class TransitionHasher {
17893
17403
  ]);
17894
17404
  });
17895
17405
  const guaranteeBlob = Encoder.encodeObject(codec$1.sequenceVarLen(dumpCodec), guarantees, this.context);
17896
- const et = hashBytes(extrinsicView.tickets.encoded(), this.allocator).asOpaque();
17897
- const ep = hashBytes(extrinsicView.preimages.encoded(), this.allocator).asOpaque();
17898
- const eg = hashBytes(guaranteeBlob, this.allocator).asOpaque();
17899
- const ea = hashBytes(extrinsicView.assurances.encoded(), this.allocator).asOpaque();
17900
- const ed = hashBytes(extrinsicView.disputes.encoded(), this.allocator).asOpaque();
17406
+ const et = this.blake2b.hashBytes(extrinsicView.tickets.encoded()).asOpaque();
17407
+ const ep = this.blake2b.hashBytes(extrinsicView.preimages.encoded()).asOpaque();
17408
+ const eg = this.blake2b.hashBytes(guaranteeBlob).asOpaque();
17409
+ const ea = this.blake2b.hashBytes(extrinsicView.assurances.encoded()).asOpaque();
17410
+ const ed = this.blake2b.hashBytes(extrinsicView.disputes.encoded()).asOpaque();
17901
17411
  const encoded = BytesBlob.blobFromParts([et.raw, ep.raw, eg.raw, ea.raw, ed.raw]);
17902
- return new WithHashAndBytes(hashBytes(encoded, this.allocator).asOpaque(), extrinsicView, encoded);
17412
+ return new WithHashAndBytes(this.blake2b.hashBytes(encoded).asOpaque(), extrinsicView, encoded);
17903
17413
  }
17904
17414
  /** Creates hash for given WorkPackage */
17905
17415
  workPackage(workPackage) {
@@ -17908,7 +17418,7 @@ class TransitionHasher {
17908
17418
  encode(codec, data) {
17909
17419
  // TODO [ToDr] Use already allocated encoding destination and hash bytes from some arena.
17910
17420
  const encoded = Encoder.encodeObject(codec, data, this.context);
17911
- return new WithHashAndBytes(hashBytes(encoded, this.allocator).asOpaque(), data, encoded);
17421
+ return new WithHashAndBytes(this.blake2b.hashBytes(encoded).asOpaque(), data, encoded);
17912
17422
  }
17913
17423
  }
17914
17424
 
@@ -17921,8 +17431,10 @@ var PreimagesErrorCode;
17921
17431
  // TODO [SeKo] consider whether this module is the right place to remove expired preimages
17922
17432
  class Preimages {
17923
17433
  state;
17924
- constructor(state) {
17434
+ blake2b;
17435
+ constructor(state, blake2b) {
17925
17436
  this.state = state;
17437
+ this.blake2b = blake2b;
17926
17438
  }
17927
17439
  integrate(input) {
17928
17440
  // make sure lookup extrinsics are sorted and unique
@@ -17945,7 +17457,7 @@ class Preimages {
17945
17457
  // select preimages for integration
17946
17458
  for (const preimage of preimages) {
17947
17459
  const { requester, blob } = preimage;
17948
- const hash = hashBytes(blob).asOpaque();
17460
+ const hash = this.blake2b.hashBytes(blob).asOpaque();
17949
17461
  const service = this.state.getService(requester);
17950
17462
  if (service === null) {
17951
17463
  return Result$1.error(PreimagesErrorCode.AccountNotFound);
@@ -17970,146 +17482,11 @@ class Preimages {
17970
17482
  }
17971
17483
  }
17972
17484
 
17973
- class Missing {
17974
- index = tryAsHostCallIndex(2 ** 32 - 1);
17975
- gasCost = tryAsSmallGas(10);
17976
- currentServiceId = CURRENT_SERVICE_ID;
17977
- tracedRegisters = traceRegisters(7);
17978
- execute(_gas, regs, _memory) {
17979
- regs.set(7, HostCallResult.WHAT);
17980
- return Promise.resolve(undefined);
17981
- }
17982
- }
17983
-
17984
- var ServiceExecutorError;
17985
- (function (ServiceExecutorError) {
17986
- ServiceExecutorError[ServiceExecutorError["NoLookup"] = 0] = "NoLookup";
17987
- ServiceExecutorError[ServiceExecutorError["NoState"] = 1] = "NoState";
17988
- ServiceExecutorError[ServiceExecutorError["NoServiceCode"] = 2] = "NoServiceCode";
17989
- ServiceExecutorError[ServiceExecutorError["ServiceCodeMismatch"] = 3] = "ServiceCodeMismatch";
17990
- })(ServiceExecutorError || (ServiceExecutorError = {}));
17991
- class WorkPackageExecutor {
17992
- blocks;
17993
- state;
17994
- hasher;
17995
- constructor(blocks, state, hasher) {
17996
- this.blocks = blocks;
17997
- this.state = state;
17998
- this.hasher = hasher;
17999
- }
18000
- // TODO [ToDr] this while thing should be triple-checked with the GP.
18001
- // I'm currently implementing some dirty version for the demo.
18002
- async executeWorkPackage(pack) {
18003
- const headerHash = pack.context.lookupAnchor;
18004
- // execute authorisation first or is it already executed and we just need to check it?
18005
- const authExec = this.getServiceExecutor(
18006
- // TODO [ToDr] should this be anchor or lookupAnchor?
18007
- headerHash, pack.authCodeHost, pack.authCodeHash);
18008
- if (authExec.isError) {
18009
- // TODO [ToDr] most likely shouldn't be throw.
18010
- throw new Error(`Could not get authorization executor: ${authExec.error}`);
18011
- }
18012
- const pvm = authExec.ok;
18013
- const authGas = tryAsGas(15000n);
18014
- const result = await pvm.run(pack.parametrization, authGas);
18015
- if (!result.isEqualTo(pack.authorization)) {
18016
- throw new Error("Authorization is invalid.");
18017
- }
18018
- const results = [];
18019
- for (const item of pack.items) {
18020
- const exec = this.getServiceExecutor(headerHash, item.service, item.codeHash);
18021
- if (exec.isError) {
18022
- throw new Error(`Could not get item executor: ${exec.error}`);
18023
- }
18024
- const pvm = exec.ok;
18025
- const gasRatio = tryAsServiceGas(3000n);
18026
- const ret = await pvm.run(item.payload, tryAsGas(item.refineGasLimit)); // or accumulateGasLimit?
18027
- results.push(WorkResult.create({
18028
- serviceId: item.service,
18029
- codeHash: item.codeHash,
18030
- payloadHash: hashBytes(item.payload),
18031
- gas: gasRatio,
18032
- result: new WorkExecResult(WorkExecResultKind.ok, ret),
18033
- load: WorkRefineLoad.create({
18034
- gasUsed: tryAsServiceGas(5),
18035
- importedSegments: tryAsU32(0),
18036
- exportedSegments: tryAsU32(0),
18037
- extrinsicSize: tryAsU32(0),
18038
- extrinsicCount: tryAsU32(0),
18039
- }),
18040
- }));
18041
- }
18042
- const workPackage = this.hasher.workPackage(pack);
18043
- const workPackageSpec = WorkPackageSpec.create({
18044
- hash: workPackage.hash,
18045
- length: tryAsU32(workPackage.encoded.length),
18046
- erasureRoot: Bytes.zero(HASH_SIZE),
18047
- exportsRoot: Bytes.zero(HASH_SIZE).asOpaque(),
18048
- exportsCount: tryAsU16(0),
18049
- });
18050
- const coreIndex = tryAsCoreIndex(0);
18051
- const authorizerHash = Bytes.fill(HASH_SIZE, 5).asOpaque();
18052
- const workResults = FixedSizeArray.new(results, tryAsWorkItemsCount(results.length));
18053
- return Promise.resolve(WorkReport.create({
18054
- workPackageSpec,
18055
- context: pack.context,
18056
- coreIndex,
18057
- authorizerHash,
18058
- authorizationOutput: pack.authorization,
18059
- segmentRootLookup: [],
18060
- results: workResults,
18061
- authorizationGasUsed: tryAsServiceGas(0),
18062
- }));
18063
- }
18064
- getServiceExecutor(lookupAnchor, serviceId, expectedCodeHash) {
18065
- const header = this.blocks.getHeader(lookupAnchor);
18066
- if (header === null) {
18067
- return Result$1.error(ServiceExecutorError.NoLookup);
18068
- }
18069
- const state = this.state.getState(lookupAnchor);
18070
- if (state === null) {
18071
- return Result$1.error(ServiceExecutorError.NoState);
18072
- }
18073
- const service = state.getService(serviceId);
18074
- const serviceCodeHash = service?.getInfo().codeHash ?? null;
18075
- if (serviceCodeHash === null) {
18076
- return Result$1.error(ServiceExecutorError.NoServiceCode);
18077
- }
18078
- if (!serviceCodeHash.isEqualTo(expectedCodeHash)) {
18079
- return Result$1.error(ServiceExecutorError.ServiceCodeMismatch);
18080
- }
18081
- const serviceCode = service?.getPreimage(serviceCodeHash.asOpaque()) ?? null;
18082
- if (serviceCode === null) {
18083
- return Result$1.error(ServiceExecutorError.NoServiceCode);
18084
- }
18085
- return Result$1.ok(new PvmExecutor(serviceCode));
18086
- }
18087
- }
18088
- class PvmExecutor {
18089
- serviceCode;
18090
- pvm;
18091
- hostCalls = new HostCallsManager({ missing: new Missing() });
18092
- pvmInstanceManager = new InterpreterInstanceManager(4);
18093
- constructor(serviceCode) {
18094
- this.serviceCode = serviceCode;
18095
- this.pvm = new HostCalls(this.pvmInstanceManager, this.hostCalls);
18096
- }
18097
- async run(args, gas) {
18098
- const program = Program.fromSpi(this.serviceCode.raw, args.raw, true);
18099
- const result = await this.pvm.runProgram(program.code, 5, gas, program.registers, program.memory);
18100
- if (result.hasMemorySlice()) {
18101
- return BytesBlob.blobFrom(result.memorySlice);
18102
- }
18103
- return BytesBlob.empty();
18104
- }
18105
- }
18106
-
18107
17485
  var index = /*#__PURE__*/Object.freeze({
18108
17486
  __proto__: null,
18109
17487
  Preimages: Preimages,
18110
17488
  get PreimagesErrorCode () { return PreimagesErrorCode; },
18111
- TransitionHasher: TransitionHasher,
18112
- WorkPackageExecutor: WorkPackageExecutor
17489
+ TransitionHasher: TransitionHasher
18113
17490
  });
18114
17491
 
18115
17492
  exports.block = index$l;
@@ -18119,11 +17496,11 @@ exports.codec = index$q;
18119
17496
  exports.collections = index$n;
18120
17497
  exports.config = index$m;
18121
17498
  exports.config_node = index$h;
18122
- exports.crypto = index$o;
17499
+ exports.crypto = index$p;
18123
17500
  exports.database = index$d;
18124
17501
  exports.erasure_coding = index$c;
18125
17502
  exports.fuzz_proto = index$a;
18126
- exports.hash = index$p;
17503
+ exports.hash = index$o;
18127
17504
  exports.jam_host_calls = index$9;
18128
17505
  exports.json_parser = index$k;
18129
17506
  exports.logger = index$i;