@typeberry/lib 0.1.2-ef67dce → 0.1.3-0eba10b

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (4) hide show
  1. package/index.cjs +1254 -1466
  2. package/index.d.ts +1984 -1432
  3. package/index.js +1235 -1448
  4. package/package.json +1 -1
package/index.d.ts CHANGED
@@ -35,7 +35,9 @@ declare function parseCurrentVersion(env?: string): GpVersion | undefined {
35
35
  }
36
36
 
37
37
  declare function parseCurrentSuite(env?: string): TestSuite | undefined {
38
- if (env === undefined) return undefined;
38
+ if (env === undefined) {
39
+ return undefined;
40
+ }
39
41
  switch (env) {
40
42
  case TestSuite.W3F_DAVXY:
41
43
  case TestSuite.JAMDUNA:
@@ -420,6 +422,20 @@ declare const Result$2 = {
420
422
  },
421
423
  };
422
424
 
425
+ // about 2GB, the maximum ArrayBuffer length on Chrome confirmed by several sources:
426
+ // - https://issues.chromium.org/issues/40055619
427
+ // - https://stackoverflow.com/a/72124984
428
+ // - https://onnxruntime.ai/docs/tutorials/web/large-models.html#maximum-size-of-arraybuffer
429
+ declare const MAX_LENGTH$1 = 2145386496;
430
+
431
+ declare function safeAllocUint8Array(length: number) {
432
+ if (length > MAX_LENGTH) {
433
+ // biome-ignore lint/suspicious/noConsole: can't have a dependency on logger here
434
+ console.warn(`Trying to allocate ${length} bytes, which is greater than the maximum of ${MAX_LENGTH}.`);
435
+ }
436
+ return new Uint8Array(Math.min(MAX_LENGTH, length));
437
+ }
438
+
423
439
  /**
424
440
  * Utilities for tests.
425
441
  */
@@ -573,8 +589,12 @@ declare function deepEqual<T>(
573
589
  const aKey = `${a.key}`;
574
590
  const bKey = `${b.key}`;
575
591
 
576
- if (aKey < bKey) return -1;
577
- if (bKey < aKey) return 1;
592
+ if (aKey < bKey) {
593
+ return -1;
594
+ }
595
+ if (bKey < aKey) {
596
+ return 1;
597
+ }
578
598
  return 0;
579
599
  });
580
600
  };
@@ -708,59 +728,60 @@ declare function isResult(x: unknown): x is Result$2<unknown, unknown> {
708
728
  * as an afterthought.
709
729
  */
710
730
 
711
- declare const index$s_ALL_VERSIONS_IN_ORDER: typeof ALL_VERSIONS_IN_ORDER;
712
- declare const index$s_CURRENT_SUITE: typeof CURRENT_SUITE;
713
- declare const index$s_CURRENT_VERSION: typeof CURRENT_VERSION;
714
- type index$s_Compatibility = Compatibility;
715
- declare const index$s_Compatibility: typeof Compatibility;
716
- declare const index$s_DEFAULT_SUITE: typeof DEFAULT_SUITE;
717
- declare const index$s_DEFAULT_VERSION: typeof DEFAULT_VERSION;
718
- type index$s_DeepEqualOptions = DeepEqualOptions;
719
- type index$s_EnumMapping = EnumMapping;
720
- type index$s_ErrorResult<Error> = ErrorResult<Error>;
721
- type index$s_ErrorsCollector = ErrorsCollector;
722
- declare const index$s_ErrorsCollector: typeof ErrorsCollector;
723
- type index$s_GpVersion = GpVersion;
724
- declare const index$s_GpVersion: typeof GpVersion;
725
- type index$s_OK = OK;
726
- type index$s_OkResult<Ok> = OkResult<Ok>;
727
- type index$s_Opaque<Type, Token extends string> = Opaque<Type, Token>;
728
- type index$s_RichTaggedError<Kind extends string | number, Nested> = RichTaggedError<Kind, Nested>;
729
- declare const index$s_RichTaggedError: typeof RichTaggedError;
730
- type index$s_StringLiteral<Type> = StringLiteral<Type>;
731
- declare const index$s_TEST_COMPARE_USING: typeof TEST_COMPARE_USING;
732
- type index$s_TaggedError<Kind, Nested> = TaggedError<Kind, Nested>;
733
- type index$s_TestSuite = TestSuite;
734
- declare const index$s_TestSuite: typeof TestSuite;
735
- type index$s_TokenOf<OpaqueType, Type> = TokenOf<OpaqueType, Type>;
736
- type index$s_Uninstantiable = Uninstantiable;
737
- type index$s_WithDebug = WithDebug;
738
- declare const index$s_WithDebug: typeof WithDebug;
739
- type index$s_WithOpaque<Token extends string> = WithOpaque<Token>;
740
- declare const index$s___OPAQUE_TYPE__: typeof __OPAQUE_TYPE__;
741
- declare const index$s_asOpaqueType: typeof asOpaqueType;
742
- declare const index$s_assertEmpty: typeof assertEmpty;
743
- declare const index$s_assertNever: typeof assertNever;
744
- declare const index$s_callCompareFunction: typeof callCompareFunction;
745
- declare const index$s_check: typeof check;
746
- declare const index$s_deepEqual: typeof deepEqual;
747
- declare const index$s_getAllKeysSorted: typeof getAllKeysSorted;
748
- declare const index$s_inspect: typeof inspect;
749
- declare const index$s_isBrowser: typeof isBrowser;
750
- declare const index$s_isResult: typeof isResult;
751
- declare const index$s_isTaggedError: typeof isTaggedError;
752
- declare const index$s_maybeTaggedErrorToString: typeof maybeTaggedErrorToString;
753
- declare const index$s_measure: typeof measure;
754
- declare const index$s_oomWarningPrinted: typeof oomWarningPrinted;
755
- declare const index$s_parseCurrentSuite: typeof parseCurrentSuite;
756
- declare const index$s_parseCurrentVersion: typeof parseCurrentVersion;
757
- declare const index$s_resultToString: typeof resultToString;
758
- declare const index$s_seeThrough: typeof seeThrough;
759
- declare const index$s_trimStack: typeof trimStack;
760
- declare const index$s_workspacePathFix: typeof workspacePathFix;
761
- declare namespace index$s {
762
- export { index$s_ALL_VERSIONS_IN_ORDER as ALL_VERSIONS_IN_ORDER, index$s_CURRENT_SUITE as CURRENT_SUITE, index$s_CURRENT_VERSION as CURRENT_VERSION, index$s_Compatibility as Compatibility, index$s_DEFAULT_SUITE as DEFAULT_SUITE, index$s_DEFAULT_VERSION as DEFAULT_VERSION, index$s_ErrorsCollector as ErrorsCollector, index$s_GpVersion as GpVersion, Result$2 as Result, index$s_RichTaggedError as RichTaggedError, index$s_TEST_COMPARE_USING as TEST_COMPARE_USING, index$s_TestSuite as TestSuite, index$s_WithDebug as WithDebug, index$s___OPAQUE_TYPE__ as __OPAQUE_TYPE__, index$s_asOpaqueType as asOpaqueType, index$s_assertEmpty as assertEmpty, index$s_assertNever as assertNever, index$s_callCompareFunction as callCompareFunction, index$s_check as check, index$s_deepEqual as deepEqual, index$s_getAllKeysSorted as getAllKeysSorted, index$s_inspect as inspect, index$s_isBrowser as isBrowser, index$s_isResult as isResult, index$s_isTaggedError as isTaggedError, index$s_maybeTaggedErrorToString as maybeTaggedErrorToString, index$s_measure as measure, index$s_oomWarningPrinted as oomWarningPrinted, index$s_parseCurrentSuite as parseCurrentSuite, index$s_parseCurrentVersion as parseCurrentVersion, index$s_resultToString as resultToString, index$s_seeThrough as seeThrough, index$s_trimStack as trimStack, index$s_workspacePathFix as workspacePathFix };
763
- export type { index$s_DeepEqualOptions as DeepEqualOptions, index$s_EnumMapping as EnumMapping, index$s_ErrorResult as ErrorResult, index$s_OK as OK, index$s_OkResult as OkResult, index$s_Opaque as Opaque, index$s_StringLiteral as StringLiteral, index$s_TaggedError as TaggedError, index$s_TokenOf as TokenOf, index$s_Uninstantiable as Uninstantiable, index$s_WithOpaque as WithOpaque };
731
+ declare const index$u_ALL_VERSIONS_IN_ORDER: typeof ALL_VERSIONS_IN_ORDER;
732
+ declare const index$u_CURRENT_SUITE: typeof CURRENT_SUITE;
733
+ declare const index$u_CURRENT_VERSION: typeof CURRENT_VERSION;
734
+ type index$u_Compatibility = Compatibility;
735
+ declare const index$u_Compatibility: typeof Compatibility;
736
+ declare const index$u_DEFAULT_SUITE: typeof DEFAULT_SUITE;
737
+ declare const index$u_DEFAULT_VERSION: typeof DEFAULT_VERSION;
738
+ type index$u_DeepEqualOptions = DeepEqualOptions;
739
+ type index$u_EnumMapping = EnumMapping;
740
+ type index$u_ErrorResult<Error> = ErrorResult<Error>;
741
+ type index$u_ErrorsCollector = ErrorsCollector;
742
+ declare const index$u_ErrorsCollector: typeof ErrorsCollector;
743
+ type index$u_GpVersion = GpVersion;
744
+ declare const index$u_GpVersion: typeof GpVersion;
745
+ type index$u_OK = OK;
746
+ type index$u_OkResult<Ok> = OkResult<Ok>;
747
+ type index$u_Opaque<Type, Token extends string> = Opaque<Type, Token>;
748
+ type index$u_RichTaggedError<Kind extends string | number, Nested> = RichTaggedError<Kind, Nested>;
749
+ declare const index$u_RichTaggedError: typeof RichTaggedError;
750
+ type index$u_StringLiteral<Type> = StringLiteral<Type>;
751
+ declare const index$u_TEST_COMPARE_USING: typeof TEST_COMPARE_USING;
752
+ type index$u_TaggedError<Kind, Nested> = TaggedError<Kind, Nested>;
753
+ type index$u_TestSuite = TestSuite;
754
+ declare const index$u_TestSuite: typeof TestSuite;
755
+ type index$u_TokenOf<OpaqueType, Type> = TokenOf<OpaqueType, Type>;
756
+ type index$u_Uninstantiable = Uninstantiable;
757
+ type index$u_WithDebug = WithDebug;
758
+ declare const index$u_WithDebug: typeof WithDebug;
759
+ type index$u_WithOpaque<Token extends string> = WithOpaque<Token>;
760
+ declare const index$u___OPAQUE_TYPE__: typeof __OPAQUE_TYPE__;
761
+ declare const index$u_asOpaqueType: typeof asOpaqueType;
762
+ declare const index$u_assertEmpty: typeof assertEmpty;
763
+ declare const index$u_assertNever: typeof assertNever;
764
+ declare const index$u_callCompareFunction: typeof callCompareFunction;
765
+ declare const index$u_check: typeof check;
766
+ declare const index$u_deepEqual: typeof deepEqual;
767
+ declare const index$u_getAllKeysSorted: typeof getAllKeysSorted;
768
+ declare const index$u_inspect: typeof inspect;
769
+ declare const index$u_isBrowser: typeof isBrowser;
770
+ declare const index$u_isResult: typeof isResult;
771
+ declare const index$u_isTaggedError: typeof isTaggedError;
772
+ declare const index$u_maybeTaggedErrorToString: typeof maybeTaggedErrorToString;
773
+ declare const index$u_measure: typeof measure;
774
+ declare const index$u_oomWarningPrinted: typeof oomWarningPrinted;
775
+ declare const index$u_parseCurrentSuite: typeof parseCurrentSuite;
776
+ declare const index$u_parseCurrentVersion: typeof parseCurrentVersion;
777
+ declare const index$u_resultToString: typeof resultToString;
778
+ declare const index$u_safeAllocUint8Array: typeof safeAllocUint8Array;
779
+ declare const index$u_seeThrough: typeof seeThrough;
780
+ declare const index$u_trimStack: typeof trimStack;
781
+ declare const index$u_workspacePathFix: typeof workspacePathFix;
782
+ declare namespace index$u {
783
+ export { index$u_ALL_VERSIONS_IN_ORDER as ALL_VERSIONS_IN_ORDER, index$u_CURRENT_SUITE as CURRENT_SUITE, index$u_CURRENT_VERSION as CURRENT_VERSION, index$u_Compatibility as Compatibility, index$u_DEFAULT_SUITE as DEFAULT_SUITE, index$u_DEFAULT_VERSION as DEFAULT_VERSION, index$u_ErrorsCollector as ErrorsCollector, index$u_GpVersion as GpVersion, MAX_LENGTH$1 as MAX_LENGTH, Result$2 as Result, index$u_RichTaggedError as RichTaggedError, index$u_TEST_COMPARE_USING as TEST_COMPARE_USING, index$u_TestSuite as TestSuite, index$u_WithDebug as WithDebug, index$u___OPAQUE_TYPE__ as __OPAQUE_TYPE__, index$u_asOpaqueType as asOpaqueType, index$u_assertEmpty as assertEmpty, index$u_assertNever as assertNever, index$u_callCompareFunction as callCompareFunction, index$u_check as check, index$u_deepEqual as deepEqual, index$u_getAllKeysSorted as getAllKeysSorted, index$u_inspect as inspect, index$u_isBrowser as isBrowser, index$u_isResult as isResult, index$u_isTaggedError as isTaggedError, index$u_maybeTaggedErrorToString as maybeTaggedErrorToString, index$u_measure as measure, index$u_oomWarningPrinted as oomWarningPrinted, index$u_parseCurrentSuite as parseCurrentSuite, index$u_parseCurrentVersion as parseCurrentVersion, index$u_resultToString as resultToString, index$u_safeAllocUint8Array as safeAllocUint8Array, index$u_seeThrough as seeThrough, index$u_trimStack as trimStack, index$u_workspacePathFix as workspacePathFix };
784
+ export type { index$u_DeepEqualOptions as DeepEqualOptions, index$u_EnumMapping as EnumMapping, index$u_ErrorResult as ErrorResult, index$u_OK as OK, index$u_OkResult as OkResult, index$u_Opaque as Opaque, index$u_StringLiteral as StringLiteral, index$u_TaggedError as TaggedError, index$u_TokenOf as TokenOf, index$u_Uninstantiable as Uninstantiable, index$u_WithOpaque as WithOpaque };
764
785
  }
765
786
 
766
787
  /** A return value of some comparator. */
@@ -813,14 +834,14 @@ declare class Ordering {
813
834
  */
814
835
  type Comparator<V> = (self: V, other: V) => Ordering;
815
836
 
816
- type index$r_Comparator<V> = Comparator<V>;
817
- type index$r_Ordering = Ordering;
818
- declare const index$r_Ordering: typeof Ordering;
819
- type index$r_OrderingValue = OrderingValue;
820
- declare const index$r_OrderingValue: typeof OrderingValue;
821
- declare namespace index$r {
822
- export { index$r_Ordering as Ordering, index$r_OrderingValue as OrderingValue };
823
- export type { index$r_Comparator as Comparator };
837
+ type index$t_Comparator<V> = Comparator<V>;
838
+ type index$t_Ordering = Ordering;
839
+ declare const index$t_Ordering: typeof Ordering;
840
+ type index$t_OrderingValue = OrderingValue;
841
+ declare const index$t_OrderingValue: typeof OrderingValue;
842
+ declare namespace index$t {
843
+ export { index$t_Ordering as Ordering, index$t_OrderingValue as OrderingValue };
844
+ export type { index$t_Comparator as Comparator };
824
845
  }
825
846
 
826
847
  // TODO: [MaSo] Update BytesBlob and Bytes, so they return Result (not throw error)
@@ -929,7 +950,7 @@ declare class BytesBlob {
929
950
  static blobFromParts(v: Uint8Array | Uint8Array[], ...rest: Uint8Array[]) {
930
951
  const vArr = v instanceof Uint8Array ? [v] : v;
931
952
  const totalLength = vArr.reduce((a, v) => a + v.length, 0) + rest.reduce((a, v) => a + v.length, 0);
932
- const buffer = new Uint8Array(totalLength);
953
+ const buffer = safeAllocUint8Array(totalLength);
933
954
  let offset = 0;
934
955
  for (const r of vArr) {
935
956
  buffer.set(r, offset);
@@ -1012,7 +1033,7 @@ declare class Bytes<T extends number> extends BytesBlob {
1012
1033
 
1013
1034
  /** Create an empty [`Bytes<X>`] of given length. */
1014
1035
  static zero<X extends number>(len: X): Bytes<X> {
1015
- return new Bytes(new Uint8Array(len), len);
1036
+ return new Bytes(safeAllocUint8Array(len), len);
1016
1037
  }
1017
1038
 
1018
1039
  // TODO [ToDr] `fill` should have the argments swapped to align with the rest.
@@ -1133,7 +1154,7 @@ declare class BitVec {
1133
1154
  * Create new [`BitVec`] with all values set to `false`.
1134
1155
  */
1135
1156
  static empty(bitLength: number) {
1136
- const data = new Uint8Array(Math.ceil(bitLength / 8));
1157
+ const data = safeAllocUint8Array(Math.ceil(bitLength / 8));
1137
1158
  return new BitVec(data, bitLength);
1138
1159
  }
1139
1160
 
@@ -1213,41 +1234,41 @@ declare class BitVec {
1213
1234
  }
1214
1235
  }
1215
1236
 
1216
- type index$q_BitVec = BitVec;
1217
- declare const index$q_BitVec: typeof BitVec;
1218
- type index$q_Bytes<T extends number> = Bytes<T>;
1219
- declare const index$q_Bytes: typeof Bytes;
1220
- type index$q_BytesBlob = BytesBlob;
1221
- declare const index$q_BytesBlob: typeof BytesBlob;
1222
- declare const index$q_CODE_OF_0: typeof CODE_OF_0;
1223
- declare const index$q_CODE_OF_9: typeof CODE_OF_9;
1224
- declare const index$q_CODE_OF_A: typeof CODE_OF_A;
1225
- declare const index$q_CODE_OF_F: typeof CODE_OF_F;
1226
- declare const index$q_CODE_OF_a: typeof CODE_OF_a;
1227
- declare const index$q_CODE_OF_f: typeof CODE_OF_f;
1228
- declare const index$q_VALUE_OF_A: typeof VALUE_OF_A;
1229
- declare const index$q_byteFromString: typeof byteFromString;
1230
- declare const index$q_bytesBlobComparator: typeof bytesBlobComparator;
1231
- declare const index$q_bytesToHexString: typeof bytesToHexString;
1232
- declare const index$q_numberFromCharCode: typeof numberFromCharCode;
1233
- declare const index$q_u8ArraySameLengthEqual: typeof u8ArraySameLengthEqual;
1234
- declare namespace index$q {
1237
+ type index$s_BitVec = BitVec;
1238
+ declare const index$s_BitVec: typeof BitVec;
1239
+ type index$s_Bytes<T extends number> = Bytes<T>;
1240
+ declare const index$s_Bytes: typeof Bytes;
1241
+ type index$s_BytesBlob = BytesBlob;
1242
+ declare const index$s_BytesBlob: typeof BytesBlob;
1243
+ declare const index$s_CODE_OF_0: typeof CODE_OF_0;
1244
+ declare const index$s_CODE_OF_9: typeof CODE_OF_9;
1245
+ declare const index$s_CODE_OF_A: typeof CODE_OF_A;
1246
+ declare const index$s_CODE_OF_F: typeof CODE_OF_F;
1247
+ declare const index$s_CODE_OF_a: typeof CODE_OF_a;
1248
+ declare const index$s_CODE_OF_f: typeof CODE_OF_f;
1249
+ declare const index$s_VALUE_OF_A: typeof VALUE_OF_A;
1250
+ declare const index$s_byteFromString: typeof byteFromString;
1251
+ declare const index$s_bytesBlobComparator: typeof bytesBlobComparator;
1252
+ declare const index$s_bytesToHexString: typeof bytesToHexString;
1253
+ declare const index$s_numberFromCharCode: typeof numberFromCharCode;
1254
+ declare const index$s_u8ArraySameLengthEqual: typeof u8ArraySameLengthEqual;
1255
+ declare namespace index$s {
1235
1256
  export {
1236
- index$q_BitVec as BitVec,
1237
- index$q_Bytes as Bytes,
1238
- index$q_BytesBlob as BytesBlob,
1239
- index$q_CODE_OF_0 as CODE_OF_0,
1240
- index$q_CODE_OF_9 as CODE_OF_9,
1241
- index$q_CODE_OF_A as CODE_OF_A,
1242
- index$q_CODE_OF_F as CODE_OF_F,
1243
- index$q_CODE_OF_a as CODE_OF_a,
1244
- index$q_CODE_OF_f as CODE_OF_f,
1245
- index$q_VALUE_OF_A as VALUE_OF_A,
1246
- index$q_byteFromString as byteFromString,
1247
- index$q_bytesBlobComparator as bytesBlobComparator,
1248
- index$q_bytesToHexString as bytesToHexString,
1249
- index$q_numberFromCharCode as numberFromCharCode,
1250
- index$q_u8ArraySameLengthEqual as u8ArraySameLengthEqual,
1257
+ index$s_BitVec as BitVec,
1258
+ index$s_Bytes as Bytes,
1259
+ index$s_BytesBlob as BytesBlob,
1260
+ index$s_CODE_OF_0 as CODE_OF_0,
1261
+ index$s_CODE_OF_9 as CODE_OF_9,
1262
+ index$s_CODE_OF_A as CODE_OF_A,
1263
+ index$s_CODE_OF_F as CODE_OF_F,
1264
+ index$s_CODE_OF_a as CODE_OF_a,
1265
+ index$s_CODE_OF_f as CODE_OF_f,
1266
+ index$s_VALUE_OF_A as VALUE_OF_A,
1267
+ index$s_byteFromString as byteFromString,
1268
+ index$s_bytesBlobComparator as bytesBlobComparator,
1269
+ index$s_bytesToHexString as bytesToHexString,
1270
+ index$s_numberFromCharCode as numberFromCharCode,
1271
+ index$s_u8ArraySameLengthEqual as u8ArraySameLengthEqual,
1251
1272
  };
1252
1273
  }
1253
1274
 
@@ -1395,37 +1416,37 @@ declare const minU64 = (a: U64, ...values: U64[]): U64 => values.reduce((min, va
1395
1416
  /** Get the biggest value between U64 a and values given as input parameters. */
1396
1417
  declare const maxU64 = (a: U64, ...values: U64[]): U64 => values.reduce((max, value) => (value < max ? max : value), a);
1397
1418
 
1398
- type index$p_FixedSizeNumber<Bytes extends number> = FixedSizeNumber<Bytes>;
1399
- declare const index$p_MAX_VALUE_U16: typeof MAX_VALUE_U16;
1400
- declare const index$p_MAX_VALUE_U32: typeof MAX_VALUE_U32;
1401
- declare const index$p_MAX_VALUE_U64: typeof MAX_VALUE_U64;
1402
- declare const index$p_MAX_VALUE_U8: typeof MAX_VALUE_U8;
1403
- type index$p_U16 = U16;
1404
- type index$p_U32 = U32;
1405
- type index$p_U64 = U64;
1406
- type index$p_U8 = U8;
1407
- type index$p_WithBytesRepresentation<Bytes extends number> = WithBytesRepresentation<Bytes>;
1408
- declare const index$p___REPRESENTATION_BYTES__: typeof __REPRESENTATION_BYTES__;
1409
- declare const index$p_asTypedNumber: typeof asTypedNumber;
1410
- declare const index$p_isU16: typeof isU16;
1411
- declare const index$p_isU32: typeof isU32;
1412
- declare const index$p_isU64: typeof isU64;
1413
- declare const index$p_isU8: typeof isU8;
1414
- declare const index$p_leBytesAsU32: typeof leBytesAsU32;
1415
- declare const index$p_maxU64: typeof maxU64;
1416
- declare const index$p_minU64: typeof minU64;
1417
- declare const index$p_sumU32: typeof sumU32;
1418
- declare const index$p_sumU64: typeof sumU64;
1419
- declare const index$p_tryAsU16: typeof tryAsU16;
1420
- declare const index$p_tryAsU32: typeof tryAsU32;
1421
- declare const index$p_tryAsU64: typeof tryAsU64;
1422
- declare const index$p_tryAsU8: typeof tryAsU8;
1423
- declare const index$p_u32AsLeBytes: typeof u32AsLeBytes;
1424
- declare const index$p_u64FromParts: typeof u64FromParts;
1425
- declare const index$p_u64IntoParts: typeof u64IntoParts;
1426
- declare namespace index$p {
1427
- export { index$p_MAX_VALUE_U16 as MAX_VALUE_U16, index$p_MAX_VALUE_U32 as MAX_VALUE_U32, index$p_MAX_VALUE_U64 as MAX_VALUE_U64, index$p_MAX_VALUE_U8 as MAX_VALUE_U8, index$p___REPRESENTATION_BYTES__ as __REPRESENTATION_BYTES__, index$p_asTypedNumber as asTypedNumber, index$p_isU16 as isU16, index$p_isU32 as isU32, index$p_isU64 as isU64, index$p_isU8 as isU8, index$p_leBytesAsU32 as leBytesAsU32, index$p_maxU64 as maxU64, index$p_minU64 as minU64, index$p_sumU32 as sumU32, index$p_sumU64 as sumU64, index$p_tryAsU16 as tryAsU16, index$p_tryAsU32 as tryAsU32, index$p_tryAsU64 as tryAsU64, index$p_tryAsU8 as tryAsU8, index$p_u32AsLeBytes as u32AsLeBytes, index$p_u64FromParts as u64FromParts, index$p_u64IntoParts as u64IntoParts };
1428
- export type { index$p_FixedSizeNumber as FixedSizeNumber, Result$1 as Result, index$p_U16 as U16, index$p_U32 as U32, index$p_U64 as U64, index$p_U8 as U8, index$p_WithBytesRepresentation as WithBytesRepresentation };
1419
+ type index$r_FixedSizeNumber<Bytes extends number> = FixedSizeNumber<Bytes>;
1420
+ declare const index$r_MAX_VALUE_U16: typeof MAX_VALUE_U16;
1421
+ declare const index$r_MAX_VALUE_U32: typeof MAX_VALUE_U32;
1422
+ declare const index$r_MAX_VALUE_U64: typeof MAX_VALUE_U64;
1423
+ declare const index$r_MAX_VALUE_U8: typeof MAX_VALUE_U8;
1424
+ type index$r_U16 = U16;
1425
+ type index$r_U32 = U32;
1426
+ type index$r_U64 = U64;
1427
+ type index$r_U8 = U8;
1428
+ type index$r_WithBytesRepresentation<Bytes extends number> = WithBytesRepresentation<Bytes>;
1429
+ declare const index$r___REPRESENTATION_BYTES__: typeof __REPRESENTATION_BYTES__;
1430
+ declare const index$r_asTypedNumber: typeof asTypedNumber;
1431
+ declare const index$r_isU16: typeof isU16;
1432
+ declare const index$r_isU32: typeof isU32;
1433
+ declare const index$r_isU64: typeof isU64;
1434
+ declare const index$r_isU8: typeof isU8;
1435
+ declare const index$r_leBytesAsU32: typeof leBytesAsU32;
1436
+ declare const index$r_maxU64: typeof maxU64;
1437
+ declare const index$r_minU64: typeof minU64;
1438
+ declare const index$r_sumU32: typeof sumU32;
1439
+ declare const index$r_sumU64: typeof sumU64;
1440
+ declare const index$r_tryAsU16: typeof tryAsU16;
1441
+ declare const index$r_tryAsU32: typeof tryAsU32;
1442
+ declare const index$r_tryAsU64: typeof tryAsU64;
1443
+ declare const index$r_tryAsU8: typeof tryAsU8;
1444
+ declare const index$r_u32AsLeBytes: typeof u32AsLeBytes;
1445
+ declare const index$r_u64FromParts: typeof u64FromParts;
1446
+ declare const index$r_u64IntoParts: typeof u64IntoParts;
1447
+ declare namespace index$r {
1448
+ export { index$r_MAX_VALUE_U16 as MAX_VALUE_U16, index$r_MAX_VALUE_U32 as MAX_VALUE_U32, index$r_MAX_VALUE_U64 as MAX_VALUE_U64, index$r_MAX_VALUE_U8 as MAX_VALUE_U8, index$r___REPRESENTATION_BYTES__ as __REPRESENTATION_BYTES__, index$r_asTypedNumber as asTypedNumber, index$r_isU16 as isU16, index$r_isU32 as isU32, index$r_isU64 as isU64, index$r_isU8 as isU8, index$r_leBytesAsU32 as leBytesAsU32, index$r_maxU64 as maxU64, index$r_minU64 as minU64, index$r_sumU32 as sumU32, index$r_sumU64 as sumU64, index$r_tryAsU16 as tryAsU16, index$r_tryAsU32 as tryAsU32, index$r_tryAsU64 as tryAsU64, index$r_tryAsU8 as tryAsU8, index$r_u32AsLeBytes as u32AsLeBytes, index$r_u64FromParts as u64FromParts, index$r_u64IntoParts as u64IntoParts };
1449
+ export type { index$r_FixedSizeNumber as FixedSizeNumber, Result$1 as Result, index$r_U16 as U16, index$r_U32 as U32, index$r_U64 as U64, index$r_U8 as U8, index$r_WithBytesRepresentation as WithBytesRepresentation };
1429
1450
  }
1430
1451
 
1431
1452
  /** A decoder for some specific type `T` */
@@ -2527,6 +2548,7 @@ declare class ViewField<T, V> implements ViewField<T, V> {
2527
2548
  private cachedBlob: BytesBlob | undefined;
2528
2549
 
2529
2550
  constructor(
2551
+ private readonly name: string,
2530
2552
  private readonly getView: () => V,
2531
2553
  private readonly getValue: () => T,
2532
2554
  private readonly getEncoded: () => BytesBlob,
@@ -2555,6 +2577,10 @@ declare class ViewField<T, V> implements ViewField<T, V> {
2555
2577
  }
2556
2578
  return this.cachedBlob;
2557
2579
  }
2580
+
2581
+ toString() {
2582
+ return `ViewField<${this.name}>`;
2583
+ }
2558
2584
  }
2559
2585
 
2560
2586
  /**
@@ -2638,6 +2664,7 @@ declare abstract class ObjectView<T> {
2638
2664
  const field = this.descriptorsKeys[i];
2639
2665
  const type = this.descriptors[field as keyof DescriptorRecord<T>];
2640
2666
  lastItem = new ViewField(
2667
+ `${this.toString()}.${String(field)}`,
2641
2668
  () => type.View.decode(fieldDecoder.clone()),
2642
2669
  () => type.decode(fieldDecoder.clone()),
2643
2670
  () => type.skipEncoded(fieldDecoder.clone()),
@@ -2655,6 +2682,10 @@ declare abstract class ObjectView<T> {
2655
2682
 
2656
2683
  return lastItem as ViewField<T[K], unknown>;
2657
2684
  }
2685
+
2686
+ toString() {
2687
+ return `View<${this.materializedConstructor.name}>(cache: ${this.cache.size})`;
2688
+ }
2658
2689
  }
2659
2690
 
2660
2691
  /**
@@ -2755,6 +2786,7 @@ declare class SequenceView<T, V = T> {
2755
2786
  const fieldDecoder = skipper.decoder.clone();
2756
2787
  const type = this.descriptor;
2757
2788
  lastItem = new ViewField(
2789
+ `${this.toString()}[${index}]`,
2758
2790
  () => type.View.decode(fieldDecoder.clone()),
2759
2791
  () => type.decode(fieldDecoder.clone()),
2760
2792
  () => type.skipEncoded(fieldDecoder.clone()),
@@ -2771,6 +2803,10 @@ declare class SequenceView<T, V = T> {
2771
2803
  }
2772
2804
  return lastItem;
2773
2805
  }
2806
+
2807
+ toString() {
2808
+ return `SequenceView<${this.descriptor.name}>(cache: ${this.cache.size})`;
2809
+ }
2774
2810
  }
2775
2811
 
2776
2812
  /**
@@ -3400,52 +3436,145 @@ declare function sequenceViewFixLen<T, V>(
3400
3436
  );
3401
3437
  }
3402
3438
 
3403
- type index$o_ClassConstructor<T> = ClassConstructor<T>;
3404
- type index$o_Codec<T> = Codec<T>;
3405
- type index$o_CodecRecord<T> = CodecRecord<T>;
3406
- declare const index$o_DEFAULT_START_LENGTH: typeof DEFAULT_START_LENGTH;
3407
- type index$o_Decode<T> = Decode<T>;
3408
- type index$o_Decoder = Decoder;
3409
- declare const index$o_Decoder: typeof Decoder;
3410
- type index$o_DescribedBy<T> = DescribedBy<T>;
3411
- type index$o_Descriptor<T, V = T> = Descriptor<T, V>;
3412
- declare const index$o_Descriptor: typeof Descriptor;
3413
- type index$o_DescriptorRecord<T> = DescriptorRecord<T>;
3414
- type index$o_Encode<T> = Encode<T>;
3415
- type index$o_Encoder = Encoder;
3416
- declare const index$o_Encoder: typeof Encoder;
3417
- type index$o_LengthRange = LengthRange;
3418
- declare const index$o_MASKS: typeof MASKS;
3419
- declare const index$o_MAX_LENGTH: typeof MAX_LENGTH;
3420
- type index$o_ObjectView<T> = ObjectView<T>;
3421
- declare const index$o_ObjectView: typeof ObjectView;
3422
- type index$o_OptionalRecord<T> = OptionalRecord<T>;
3423
- type index$o_PropertyKeys<T> = PropertyKeys<T>;
3424
- type index$o_SequenceView<T, V = T> = SequenceView<T, V>;
3425
- declare const index$o_SequenceView: typeof SequenceView;
3426
- type index$o_SimpleDescriptorRecord<T> = SimpleDescriptorRecord<T>;
3427
- type index$o_SizeHint = SizeHint;
3428
- declare const index$o_TYPICAL_DICTIONARY_LENGTH: typeof TYPICAL_DICTIONARY_LENGTH;
3429
- declare const index$o_TYPICAL_SEQUENCE_LENGTH: typeof TYPICAL_SEQUENCE_LENGTH;
3430
- type index$o_ViewField<T, V> = ViewField<T, V>;
3431
- declare const index$o_ViewField: typeof ViewField;
3432
- type index$o_ViewOf<T, D extends DescriptorRecord<T>> = ViewOf<T, D>;
3433
- declare const index$o_addSizeHints: typeof addSizeHints;
3434
- declare const index$o_decodeVariableLengthExtraBytes: typeof decodeVariableLengthExtraBytes;
3435
- declare const index$o_exactHint: typeof exactHint;
3436
- declare const index$o_forEachDescriptor: typeof forEachDescriptor;
3437
- declare const index$o_hasUniqueView: typeof hasUniqueView;
3438
- declare const index$o_objectView: typeof objectView;
3439
- declare const index$o_readonlyArray: typeof readonlyArray;
3440
- declare const index$o_sequenceViewFixLen: typeof sequenceViewFixLen;
3441
- declare const index$o_sequenceViewVarLen: typeof sequenceViewVarLen;
3442
- declare const index$o_tryAsExactBytes: typeof tryAsExactBytes;
3443
- declare const index$o_validateLength: typeof validateLength;
3444
- declare namespace index$o {
3445
- export { index$o_DEFAULT_START_LENGTH as DEFAULT_START_LENGTH, index$o_Decoder as Decoder, index$o_Descriptor as Descriptor, index$o_Encoder as Encoder, index$o_MASKS as MASKS, index$o_MAX_LENGTH as MAX_LENGTH, index$o_ObjectView as ObjectView, index$o_SequenceView as SequenceView, index$o_TYPICAL_DICTIONARY_LENGTH as TYPICAL_DICTIONARY_LENGTH, index$o_TYPICAL_SEQUENCE_LENGTH as TYPICAL_SEQUENCE_LENGTH, index$o_ViewField as ViewField, index$o_addSizeHints as addSizeHints, codec$1 as codec, index$o_decodeVariableLengthExtraBytes as decodeVariableLengthExtraBytes, index$o_exactHint as exactHint, index$o_forEachDescriptor as forEachDescriptor, index$o_hasUniqueView as hasUniqueView, index$o_objectView as objectView, index$o_readonlyArray as readonlyArray, index$o_sequenceViewFixLen as sequenceViewFixLen, index$o_sequenceViewVarLen as sequenceViewVarLen, index$o_tryAsExactBytes as tryAsExactBytes, index$o_validateLength as validateLength };
3446
- export type { index$o_ClassConstructor as ClassConstructor, index$o_Codec as Codec, index$o_CodecRecord as CodecRecord, index$o_Decode as Decode, index$o_DescribedBy as DescribedBy, index$o_DescriptorRecord as DescriptorRecord, index$o_Encode as Encode, index$o_LengthRange as LengthRange, index$o_OptionalRecord as OptionalRecord, Options$1 as Options, index$o_PropertyKeys as PropertyKeys, index$o_SimpleDescriptorRecord as SimpleDescriptorRecord, index$o_SizeHint as SizeHint, index$o_ViewOf as ViewOf };
3439
+ type index$q_ClassConstructor<T> = ClassConstructor<T>;
3440
+ type index$q_Codec<T> = Codec<T>;
3441
+ type index$q_CodecRecord<T> = CodecRecord<T>;
3442
+ declare const index$q_DEFAULT_START_LENGTH: typeof DEFAULT_START_LENGTH;
3443
+ type index$q_Decode<T> = Decode<T>;
3444
+ type index$q_Decoder = Decoder;
3445
+ declare const index$q_Decoder: typeof Decoder;
3446
+ type index$q_DescribedBy<T> = DescribedBy<T>;
3447
+ type index$q_Descriptor<T, V = T> = Descriptor<T, V>;
3448
+ declare const index$q_Descriptor: typeof Descriptor;
3449
+ type index$q_DescriptorRecord<T> = DescriptorRecord<T>;
3450
+ type index$q_Encode<T> = Encode<T>;
3451
+ type index$q_Encoder = Encoder;
3452
+ declare const index$q_Encoder: typeof Encoder;
3453
+ type index$q_LengthRange = LengthRange;
3454
+ declare const index$q_MASKS: typeof MASKS;
3455
+ declare const index$q_MAX_LENGTH: typeof MAX_LENGTH;
3456
+ type index$q_ObjectView<T> = ObjectView<T>;
3457
+ declare const index$q_ObjectView: typeof ObjectView;
3458
+ type index$q_OptionalRecord<T> = OptionalRecord<T>;
3459
+ type index$q_PropertyKeys<T> = PropertyKeys<T>;
3460
+ type index$q_SequenceView<T, V = T> = SequenceView<T, V>;
3461
+ declare const index$q_SequenceView: typeof SequenceView;
3462
+ type index$q_SimpleDescriptorRecord<T> = SimpleDescriptorRecord<T>;
3463
+ type index$q_SizeHint = SizeHint;
3464
+ declare const index$q_TYPICAL_DICTIONARY_LENGTH: typeof TYPICAL_DICTIONARY_LENGTH;
3465
+ declare const index$q_TYPICAL_SEQUENCE_LENGTH: typeof TYPICAL_SEQUENCE_LENGTH;
3466
+ type index$q_ViewField<T, V> = ViewField<T, V>;
3467
+ declare const index$q_ViewField: typeof ViewField;
3468
+ type index$q_ViewOf<T, D extends DescriptorRecord<T>> = ViewOf<T, D>;
3469
+ declare const index$q_addSizeHints: typeof addSizeHints;
3470
+ declare const index$q_decodeVariableLengthExtraBytes: typeof decodeVariableLengthExtraBytes;
3471
+ declare const index$q_exactHint: typeof exactHint;
3472
+ declare const index$q_forEachDescriptor: typeof forEachDescriptor;
3473
+ declare const index$q_hasUniqueView: typeof hasUniqueView;
3474
+ declare const index$q_objectView: typeof objectView;
3475
+ declare const index$q_readonlyArray: typeof readonlyArray;
3476
+ declare const index$q_sequenceViewFixLen: typeof sequenceViewFixLen;
3477
+ declare const index$q_sequenceViewVarLen: typeof sequenceViewVarLen;
3478
+ declare const index$q_tryAsExactBytes: typeof tryAsExactBytes;
3479
+ declare const index$q_validateLength: typeof validateLength;
3480
+ declare namespace index$q {
3481
+ export { index$q_DEFAULT_START_LENGTH as DEFAULT_START_LENGTH, index$q_Decoder as Decoder, index$q_Descriptor as Descriptor, index$q_Encoder as Encoder, index$q_MASKS as MASKS, index$q_MAX_LENGTH as MAX_LENGTH, index$q_ObjectView as ObjectView, index$q_SequenceView as SequenceView, index$q_TYPICAL_DICTIONARY_LENGTH as TYPICAL_DICTIONARY_LENGTH, index$q_TYPICAL_SEQUENCE_LENGTH as TYPICAL_SEQUENCE_LENGTH, index$q_ViewField as ViewField, index$q_addSizeHints as addSizeHints, codec$1 as codec, index$q_decodeVariableLengthExtraBytes as decodeVariableLengthExtraBytes, index$q_exactHint as exactHint, index$q_forEachDescriptor as forEachDescriptor, index$q_hasUniqueView as hasUniqueView, index$q_objectView as objectView, index$q_readonlyArray as readonlyArray, index$q_sequenceViewFixLen as sequenceViewFixLen, index$q_sequenceViewVarLen as sequenceViewVarLen, index$q_tryAsExactBytes as tryAsExactBytes, index$q_validateLength as validateLength };
3482
+ export type { index$q_ClassConstructor as ClassConstructor, index$q_Codec as Codec, index$q_CodecRecord as CodecRecord, index$q_Decode as Decode, index$q_DescribedBy as DescribedBy, index$q_DescriptorRecord as DescriptorRecord, index$q_Encode as Encode, index$q_LengthRange as LengthRange, index$q_OptionalRecord as OptionalRecord, Options$1 as Options, index$q_PropertyKeys as PropertyKeys, index$q_SimpleDescriptorRecord as SimpleDescriptorRecord, index$q_SizeHint as SizeHint, index$q_ViewOf as ViewOf };
3483
+ }
3484
+
3485
+ /**
3486
+ * A utility class providing a readonly view over a portion of an array without copying it.
3487
+ */
3488
+ declare class ArrayView<T> implements Iterable<T> {
3489
+ private readonly source: T[];
3490
+ public readonly length: number;
3491
+
3492
+ private constructor(
3493
+ source: T[],
3494
+ private readonly start: number,
3495
+ private readonly end: number,
3496
+ ) {
3497
+ this.source = source;
3498
+ this.length = end - start;
3499
+ }
3500
+
3501
+ static from<T>(source: T[], start = 0, end = source.length): ArrayView<T> {
3502
+ check`
3503
+ ${start >= 0 && end <= source.length && start <= end}
3504
+ Invalid start (${start})/end (${end}) for ArrayView
3505
+ `;
3506
+ return new ArrayView(source, start, end);
3507
+ }
3508
+
3509
+ get(i: number): T {
3510
+ check`
3511
+ ${i >= 0 && i < this.length}
3512
+ Index out of bounds: ${i} < ${this.length}
3513
+ `;
3514
+ return this.source[this.start + i];
3515
+ }
3516
+
3517
+ subview(from: number, to: number = this.length): ArrayView<T> {
3518
+ return ArrayView.from(this.source, this.start + from, this.start + to);
3519
+ }
3520
+
3521
+ toArray(): T[] {
3522
+ return this.source.slice(this.start, this.end);
3523
+ }
3524
+
3525
+ *[Symbol.iterator](): Iterator<T> {
3526
+ for (let i = this.start; i < this.end; i++) {
3527
+ yield this.source[i];
3528
+ }
3529
+ }
3447
3530
  }
3448
3531
 
3532
+ type ITypedArray = Uint8Array | Uint16Array | Uint32Array;
3533
+ type IDataType = string | Buffer | ITypedArray;
3534
+
3535
+ type IHasher = {
3536
+ /**
3537
+ * Initializes hash state to default value
3538
+ */
3539
+ init: () => IHasher;
3540
+ /**
3541
+ * Updates the hash content with the given data
3542
+ */
3543
+ update: (data: IDataType) => IHasher;
3544
+ /**
3545
+ * Calculates the hash of all of the data passed to be hashed with hash.update().
3546
+ * Defaults to hexadecimal string
3547
+ * @param outputType If outputType is "binary", it returns Uint8Array. Otherwise it
3548
+ * returns hexadecimal string
3549
+ */
3550
+ digest: {
3551
+ (outputType: "binary"): Uint8Array;
3552
+ (outputType?: "hex"): string;
3553
+ };
3554
+ /**
3555
+ * Save the current internal state of the hasher for later resumption with load().
3556
+ * Cannot be called before .init() or after .digest()
3557
+ *
3558
+ * Note that this state can include arbitrary information about the value being hashed (e.g.
3559
+ * could include N plaintext bytes from the value), so needs to be treated as being as
3560
+ * sensitive as the input value itself.
3561
+ */
3562
+ save: () => Uint8Array;
3563
+ /**
3564
+ * Resume a state that was created by save(). If this state was not created by a
3565
+ * compatible build of hash-wasm, an exception will be thrown.
3566
+ */
3567
+ load: (state: Uint8Array) => IHasher;
3568
+ /**
3569
+ * Block size in bytes
3570
+ */
3571
+ blockSize: number;
3572
+ /**
3573
+ * Digest size in bytes
3574
+ */
3575
+ digestSize: number;
3576
+ };
3577
+
3449
3578
  /**
3450
3579
  * Size of the output of the hash functions.
3451
3580
  *
@@ -3501,144 +3630,46 @@ declare class WithHashAndBytes<THash extends OpaqueHash, TData> extends WithHash
3501
3630
  }
3502
3631
  }
3503
3632
 
3504
- /** Allocator interface - returns an empty bytes vector that can be filled with the hash. */
3505
- interface HashAllocator {
3506
- /** Return a new hash destination. */
3507
- emptyHash(): OpaqueHash;
3508
- }
3509
-
3510
- /** The simplest allocator returning just a fresh copy of bytes each time. */
3511
- declare class SimpleAllocator implements HashAllocator {
3512
- emptyHash(): OpaqueHash {
3513
- return Bytes.zero(HASH_SIZE);
3514
- }
3515
- }
3633
+ declare const zero$1 = Bytes.zero(HASH_SIZE);
3516
3634
 
3517
- /** An allocator that works by allocating larger (continuous) pages of memory. */
3518
- declare class PageAllocator implements HashAllocator {
3519
- private page: Uint8Array = new Uint8Array(0);
3520
- private currentHash = 0;
3521
-
3522
- // TODO [ToDr] Benchmark the performance!
3523
- constructor(private readonly hashesPerPage: number) {
3524
- check`${hashesPerPage > 0 && hashesPerPage >>> 0 === hashesPerPage} Expected a non-zero integer.`;
3525
- this.resetPage();
3526
- }
3527
-
3528
- private resetPage() {
3529
- const pageSizeBytes = this.hashesPerPage * HASH_SIZE;
3530
- this.currentHash = 0;
3531
- this.page = new Uint8Array(pageSizeBytes);
3635
+ declare class Blake2b {
3636
+ static async createHasher() {
3637
+ return new Blake2b(await createBLAKE2b(HASH_SIZE * 8));
3532
3638
  }
3533
3639
 
3534
- emptyHash(): OpaqueHash {
3535
- const startIdx = this.currentHash * HASH_SIZE;
3536
- const endIdx = startIdx + HASH_SIZE;
3640
+ private constructor(private readonly hasher: IHasher) {}
3537
3641
 
3538
- this.currentHash += 1;
3539
- if (this.currentHash >= this.hashesPerPage) {
3540
- this.resetPage();
3642
+ /**
3643
+ * Hash given collection of blobs.
3644
+ *
3645
+ * If empty array is given a zero-hash is returned.
3646
+ */
3647
+ hashBlobs<H extends Blake2bHash>(r: (BytesBlob | Uint8Array)[]): H {
3648
+ if (r.length === 0) {
3649
+ return zero.asOpaque();
3541
3650
  }
3542
3651
 
3543
- return Bytes.fromBlob(this.page.subarray(startIdx, endIdx), HASH_SIZE);
3652
+ const hasher = this.hasher.init();
3653
+ for (const v of r) {
3654
+ hasher.update(v instanceof BytesBlob ? v.raw : v);
3655
+ }
3656
+ return Bytes.fromBlob(hasher.digest("binary"), HASH_SIZE).asOpaque();
3544
3657
  }
3545
- }
3546
3658
 
3547
- declare const defaultAllocator = new SimpleAllocator();
3548
-
3549
- /**
3550
- * Hash given collection of blobs.
3551
- *
3552
- * If empty array is given a zero-hash is returned.
3553
- */
3554
- declare function hashBlobs$1<H extends Blake2bHash>(
3555
- r: (BytesBlob | Uint8Array)[],
3556
- allocator: HashAllocator = defaultAllocator,
3557
- ): H {
3558
- const out = allocator.emptyHash();
3559
- if (r.length === 0) {
3560
- return out.asOpaque();
3659
+ /** Hash given blob of bytes. */
3660
+ hashBytes(blob: BytesBlob | Uint8Array): Blake2bHash {
3661
+ const hasher = this.hasher.init();
3662
+ const bytes = blob instanceof BytesBlob ? blob.raw : blob;
3663
+ hasher.update(bytes);
3664
+ return Bytes.fromBlob(hasher.digest("binary"), HASH_SIZE).asOpaque();
3561
3665
  }
3562
3666
 
3563
- const hasher = blake2b(HASH_SIZE);
3564
- for (const v of r) {
3565
- hasher?.update(v instanceof BytesBlob ? v.raw : v);
3667
+ /** Convert given string into bytes and hash it. */
3668
+ hashString(str: string) {
3669
+ return this.hashBytes(BytesBlob.blobFromString(str));
3566
3670
  }
3567
- hasher?.digest(out.raw);
3568
- return out.asOpaque();
3569
3671
  }
3570
3672
 
3571
- /** Hash given blob of bytes. */
3572
- declare function hashBytes(blob: BytesBlob | Uint8Array, allocator: HashAllocator = defaultAllocator): Blake2bHash {
3573
- const hasher = blake2b(HASH_SIZE);
3574
- const bytes = blob instanceof BytesBlob ? blob.raw : blob;
3575
- hasher?.update(bytes);
3576
- const out = allocator.emptyHash();
3577
- hasher?.digest(out.raw);
3578
- return out;
3579
- }
3580
-
3581
- /** Convert given string into bytes and hash it. */
3582
- declare function hashString(str: string, allocator: HashAllocator = defaultAllocator) {
3583
- return hashBytes(BytesBlob.blobFromString(str), allocator);
3584
- }
3585
-
3586
- declare const blake2b_hashBytes: typeof hashBytes;
3587
- declare const blake2b_hashString: typeof hashString;
3588
- declare namespace blake2b {
3589
- export {
3590
- hashBlobs$1 as hashBlobs,
3591
- blake2b_hashBytes as hashBytes,
3592
- blake2b_hashString as hashString,
3593
- };
3594
- }
3595
-
3596
- type ITypedArray = Uint8Array | Uint16Array | Uint32Array;
3597
- type IDataType = string | Buffer | ITypedArray;
3598
-
3599
- type IHasher = {
3600
- /**
3601
- * Initializes hash state to default value
3602
- */
3603
- init: () => IHasher;
3604
- /**
3605
- * Updates the hash content with the given data
3606
- */
3607
- update: (data: IDataType) => IHasher;
3608
- /**
3609
- * Calculates the hash of all of the data passed to be hashed with hash.update().
3610
- * Defaults to hexadecimal string
3611
- * @param outputType If outputType is "binary", it returns Uint8Array. Otherwise it
3612
- * returns hexadecimal string
3613
- */
3614
- digest: {
3615
- (outputType: "binary"): Uint8Array;
3616
- (outputType?: "hex"): string;
3617
- };
3618
- /**
3619
- * Save the current internal state of the hasher for later resumption with load().
3620
- * Cannot be called before .init() or after .digest()
3621
- *
3622
- * Note that this state can include arbitrary information about the value being hashed (e.g.
3623
- * could include N plaintext bytes from the value), so needs to be treated as being as
3624
- * sensitive as the input value itself.
3625
- */
3626
- save: () => Uint8Array;
3627
- /**
3628
- * Resume a state that was created by save(). If this state was not created by a
3629
- * compatible build of hash-wasm, an exception will be thrown.
3630
- */
3631
- load: (state: Uint8Array) => IHasher;
3632
- /**
3633
- * Block size in bytes
3634
- */
3635
- blockSize: number;
3636
- /**
3637
- * Digest size in bytes
3638
- */
3639
- digestSize: number;
3640
- };
3641
-
3642
3673
  declare class KeccakHasher {
3643
3674
  static async create(): Promise<KeccakHasher> {
3644
3675
  return new KeccakHasher(await createKeccak(256));
@@ -3666,28 +3697,26 @@ declare namespace keccak {
3666
3697
  };
3667
3698
  }
3668
3699
 
3669
- type index$n_Blake2bHash = Blake2bHash;
3670
- type index$n_HASH_SIZE = HASH_SIZE;
3671
- type index$n_HashAllocator = HashAllocator;
3672
- type index$n_KeccakHash = KeccakHash;
3673
- type index$n_OpaqueHash = OpaqueHash;
3674
- type index$n_PageAllocator = PageAllocator;
3675
- declare const index$n_PageAllocator: typeof PageAllocator;
3676
- type index$n_SimpleAllocator = SimpleAllocator;
3677
- declare const index$n_SimpleAllocator: typeof SimpleAllocator;
3678
- type index$n_TRUNCATED_HASH_SIZE = TRUNCATED_HASH_SIZE;
3679
- type index$n_TruncatedHash = TruncatedHash;
3680
- type index$n_WithHash<THash extends OpaqueHash, TData> = WithHash<THash, TData>;
3681
- declare const index$n_WithHash: typeof WithHash;
3682
- type index$n_WithHashAndBytes<THash extends OpaqueHash, TData> = WithHashAndBytes<THash, TData>;
3683
- declare const index$n_WithHashAndBytes: typeof WithHashAndBytes;
3684
- declare const index$n_ZERO_HASH: typeof ZERO_HASH;
3685
- declare const index$n_blake2b: typeof blake2b;
3686
- declare const index$n_defaultAllocator: typeof defaultAllocator;
3687
- declare const index$n_keccak: typeof keccak;
3688
- declare namespace index$n {
3689
- export { index$n_PageAllocator as PageAllocator, index$n_SimpleAllocator as SimpleAllocator, index$n_WithHash as WithHash, index$n_WithHashAndBytes as WithHashAndBytes, index$n_ZERO_HASH as ZERO_HASH, index$n_blake2b as blake2b, index$n_defaultAllocator as defaultAllocator, index$n_keccak as keccak };
3690
- export type { index$n_Blake2bHash as Blake2bHash, index$n_HASH_SIZE as HASH_SIZE, index$n_HashAllocator as HashAllocator, index$n_KeccakHash as KeccakHash, index$n_OpaqueHash as OpaqueHash, index$n_TRUNCATED_HASH_SIZE as TRUNCATED_HASH_SIZE, index$n_TruncatedHash as TruncatedHash };
3700
+ // TODO [ToDr] (#213) this should most likely be moved to a separate
3701
+ // package to avoid pulling in unnecessary deps.
3702
+
3703
+ type index$p_Blake2b = Blake2b;
3704
+ declare const index$p_Blake2b: typeof Blake2b;
3705
+ type index$p_Blake2bHash = Blake2bHash;
3706
+ type index$p_HASH_SIZE = HASH_SIZE;
3707
+ type index$p_KeccakHash = KeccakHash;
3708
+ type index$p_OpaqueHash = OpaqueHash;
3709
+ type index$p_TRUNCATED_HASH_SIZE = TRUNCATED_HASH_SIZE;
3710
+ type index$p_TruncatedHash = TruncatedHash;
3711
+ type index$p_WithHash<THash extends OpaqueHash, TData> = WithHash<THash, TData>;
3712
+ declare const index$p_WithHash: typeof WithHash;
3713
+ type index$p_WithHashAndBytes<THash extends OpaqueHash, TData> = WithHashAndBytes<THash, TData>;
3714
+ declare const index$p_WithHashAndBytes: typeof WithHashAndBytes;
3715
+ declare const index$p_ZERO_HASH: typeof ZERO_HASH;
3716
+ declare const index$p_keccak: typeof keccak;
3717
+ declare namespace index$p {
3718
+ export { index$p_Blake2b as Blake2b, index$p_WithHash as WithHash, index$p_WithHashAndBytes as WithHashAndBytes, index$p_ZERO_HASH as ZERO_HASH, index$p_keccak as keccak, zero$1 as zero };
3719
+ export type { index$p_Blake2bHash as Blake2bHash, index$p_HASH_SIZE as HASH_SIZE, index$p_KeccakHash as KeccakHash, index$p_OpaqueHash as OpaqueHash, index$p_TRUNCATED_HASH_SIZE as TRUNCATED_HASH_SIZE, index$p_TruncatedHash as TruncatedHash };
3691
3720
  }
3692
3721
 
3693
3722
  /** Immutable view of the `HashDictionary`. */
@@ -4464,35 +4493,37 @@ declare class TruncatedHashDictionary<T extends OpaqueHash, V> {
4464
4493
  }
4465
4494
  }
4466
4495
 
4467
- type index$m_FixedSizeArray<T, N extends number> = FixedSizeArray<T, N>;
4468
- declare const index$m_FixedSizeArray: typeof FixedSizeArray;
4469
- type index$m_HashDictionary<K extends OpaqueHash, V> = HashDictionary<K, V>;
4470
- declare const index$m_HashDictionary: typeof HashDictionary;
4471
- type index$m_HashSet<V extends OpaqueHash> = HashSet<V>;
4472
- declare const index$m_HashSet: typeof HashSet;
4473
- type index$m_HashWithZeroedBit<T extends OpaqueHash> = HashWithZeroedBit<T>;
4474
- type index$m_ImmutableHashDictionary<K extends OpaqueHash, V> = ImmutableHashDictionary<K, V>;
4475
- type index$m_ImmutableHashSet<V extends OpaqueHash> = ImmutableHashSet<V>;
4476
- type index$m_ImmutableSortedArray<V> = ImmutableSortedArray<V>;
4477
- type index$m_ImmutableSortedSet<V> = ImmutableSortedSet<V>;
4478
- type index$m_KeyMapper<K> = KeyMapper<K>;
4479
- type index$m_KeyMappers<TKeys extends readonly unknown[]> = KeyMappers<TKeys>;
4480
- type index$m_KnownSize<T, F extends string> = KnownSize<T, F>;
4481
- type index$m_KnownSizeArray<T, F extends string> = KnownSizeArray<T, F>;
4482
- type index$m_KnownSizeId<X> = KnownSizeId<X>;
4483
- type index$m_MultiMap<TKeys extends readonly unknown[], TValue> = MultiMap<TKeys, TValue>;
4484
- declare const index$m_MultiMap: typeof MultiMap;
4485
- type index$m_NestedMaps<TKeys extends readonly unknown[], TValue> = NestedMaps<TKeys, TValue>;
4486
- type index$m_SortedArray<V> = SortedArray<V>;
4487
- declare const index$m_SortedArray: typeof SortedArray;
4488
- type index$m_SortedSet<V> = SortedSet<V>;
4489
- declare const index$m_SortedSet: typeof SortedSet;
4490
- type index$m_TruncatedHashDictionary<T extends OpaqueHash, V> = TruncatedHashDictionary<T, V>;
4491
- declare const index$m_TruncatedHashDictionary: typeof TruncatedHashDictionary;
4492
- declare const index$m_asKnownSize: typeof asKnownSize;
4493
- declare namespace index$m {
4494
- export { index$m_FixedSizeArray as FixedSizeArray, index$m_HashDictionary as HashDictionary, index$m_HashSet as HashSet, index$m_MultiMap as MultiMap, index$m_SortedArray as SortedArray, index$m_SortedSet as SortedSet, index$m_TruncatedHashDictionary as TruncatedHashDictionary, index$m_asKnownSize as asKnownSize };
4495
- export type { index$m_HashWithZeroedBit as HashWithZeroedBit, index$m_ImmutableHashDictionary as ImmutableHashDictionary, index$m_ImmutableHashSet as ImmutableHashSet, index$m_ImmutableSortedArray as ImmutableSortedArray, index$m_ImmutableSortedSet as ImmutableSortedSet, index$m_KeyMapper as KeyMapper, index$m_KeyMappers as KeyMappers, index$m_KnownSize as KnownSize, index$m_KnownSizeArray as KnownSizeArray, index$m_KnownSizeId as KnownSizeId, index$m_NestedMaps as NestedMaps };
4496
+ type index$o_ArrayView<T> = ArrayView<T>;
4497
+ declare const index$o_ArrayView: typeof ArrayView;
4498
+ type index$o_FixedSizeArray<T, N extends number> = FixedSizeArray<T, N>;
4499
+ declare const index$o_FixedSizeArray: typeof FixedSizeArray;
4500
+ type index$o_HashDictionary<K extends OpaqueHash, V> = HashDictionary<K, V>;
4501
+ declare const index$o_HashDictionary: typeof HashDictionary;
4502
+ type index$o_HashSet<V extends OpaqueHash> = HashSet<V>;
4503
+ declare const index$o_HashSet: typeof HashSet;
4504
+ type index$o_HashWithZeroedBit<T extends OpaqueHash> = HashWithZeroedBit<T>;
4505
+ type index$o_ImmutableHashDictionary<K extends OpaqueHash, V> = ImmutableHashDictionary<K, V>;
4506
+ type index$o_ImmutableHashSet<V extends OpaqueHash> = ImmutableHashSet<V>;
4507
+ type index$o_ImmutableSortedArray<V> = ImmutableSortedArray<V>;
4508
+ type index$o_ImmutableSortedSet<V> = ImmutableSortedSet<V>;
4509
+ type index$o_KeyMapper<K> = KeyMapper<K>;
4510
+ type index$o_KeyMappers<TKeys extends readonly unknown[]> = KeyMappers<TKeys>;
4511
+ type index$o_KnownSize<T, F extends string> = KnownSize<T, F>;
4512
+ type index$o_KnownSizeArray<T, F extends string> = KnownSizeArray<T, F>;
4513
+ type index$o_KnownSizeId<X> = KnownSizeId<X>;
4514
+ type index$o_MultiMap<TKeys extends readonly unknown[], TValue> = MultiMap<TKeys, TValue>;
4515
+ declare const index$o_MultiMap: typeof MultiMap;
4516
+ type index$o_NestedMaps<TKeys extends readonly unknown[], TValue> = NestedMaps<TKeys, TValue>;
4517
+ type index$o_SortedArray<V> = SortedArray<V>;
4518
+ declare const index$o_SortedArray: typeof SortedArray;
4519
+ type index$o_SortedSet<V> = SortedSet<V>;
4520
+ declare const index$o_SortedSet: typeof SortedSet;
4521
+ type index$o_TruncatedHashDictionary<T extends OpaqueHash, V> = TruncatedHashDictionary<T, V>;
4522
+ declare const index$o_TruncatedHashDictionary: typeof TruncatedHashDictionary;
4523
+ declare const index$o_asKnownSize: typeof asKnownSize;
4524
+ declare namespace index$o {
4525
+ export { index$o_ArrayView as ArrayView, index$o_FixedSizeArray as FixedSizeArray, index$o_HashDictionary as HashDictionary, index$o_HashSet as HashSet, index$o_MultiMap as MultiMap, index$o_SortedArray as SortedArray, index$o_SortedSet as SortedSet, index$o_TruncatedHashDictionary as TruncatedHashDictionary, index$o_asKnownSize as asKnownSize };
4526
+ export type { index$o_HashWithZeroedBit as HashWithZeroedBit, index$o_ImmutableHashDictionary as ImmutableHashDictionary, index$o_ImmutableHashSet as ImmutableHashSet, index$o_ImmutableSortedArray as ImmutableSortedArray, index$o_ImmutableSortedSet as ImmutableSortedSet, index$o_KeyMapper as KeyMapper, index$o_KeyMappers as KeyMappers, index$o_KnownSize as KnownSize, index$o_KnownSizeArray as KnownSizeArray, index$o_KnownSizeId as KnownSizeId, index$o_NestedMaps as NestedMaps };
4496
4527
  }
4497
4528
 
4498
4529
  declare namespace bandersnatch_d_exports {
@@ -4720,7 +4751,7 @@ declare async function verify<T extends BytesBlob>(input: Input<T>[]): Promise<b
4720
4751
  (acc, { message, key, signature }) => acc + key.length + signature.length + message.length + 1,
4721
4752
  0,
4722
4753
  );
4723
- const data = new Uint8Array(dataLength);
4754
+ const data = safeAllocUint8Array(dataLength);
4724
4755
 
4725
4756
  let offset = 0;
4726
4757
 
@@ -4810,22 +4841,16 @@ declare function trivialSeed(s: U32): KeySeed {
4810
4841
  * Derives a Ed25519 secret key from a seed.
4811
4842
  * https://github.com/polkadot-fellows/JIPs/blob/7048f79edf4f4eb8bfe6fb42e6bbf61900f44c65/JIP-5.md#derivation-method
4812
4843
  */
4813
- declare function deriveEd25519SecretKey(
4814
- seed: KeySeed,
4815
- allocator: SimpleAllocator = new SimpleAllocator(),
4816
- ): Ed25519SecretSeed {
4817
- return blake2b.hashBytes(BytesBlob.blobFromParts([ED25519_SECRET_KEY.raw, seed.raw]), allocator).asOpaque();
4844
+ declare function deriveEd25519SecretKey(seed: KeySeed, blake2b: Blake2b): Ed25519SecretSeed {
4845
+ return blake2b.hashBytes(BytesBlob.blobFromParts([ED25519_SECRET_KEY.raw, seed.raw])).asOpaque();
4818
4846
  }
4819
4847
 
4820
4848
  /**
4821
4849
  * Derives a Bandersnatch secret key from a seed.
4822
4850
  * https://github.com/polkadot-fellows/JIPs/blob/7048f79edf4f4eb8bfe6fb42e6bbf61900f44c65/JIP-5.md#derivation-method
4823
4851
  */
4824
- declare function deriveBandersnatchSecretKey(
4825
- seed: KeySeed,
4826
- allocator: SimpleAllocator = new SimpleAllocator(),
4827
- ): BandersnatchSecretSeed {
4828
- return blake2b.hashBytes(BytesBlob.blobFromParts([BANDERSNATCH_SECRET_KEY.raw, seed.raw]), allocator).asOpaque();
4852
+ declare function deriveBandersnatchSecretKey(seed: KeySeed, blake2b: Blake2b): BandersnatchSecretSeed {
4853
+ return blake2b.hashBytes(BytesBlob.blobFromParts([BANDERSNATCH_SECRET_KEY.raw, seed.raw])).asOpaque();
4829
4854
  }
4830
4855
 
4831
4856
  /**
@@ -4858,32 +4883,32 @@ declare namespace keyDerivation {
4858
4883
  export type { keyDerivation_BandersnatchSecretSeed as BandersnatchSecretSeed, keyDerivation_Ed25519SecretSeed as Ed25519SecretSeed, keyDerivation_KeySeed as KeySeed, keyDerivation_SEED_SIZE as SEED_SIZE };
4859
4884
  }
4860
4885
 
4861
- type index$l_BANDERSNATCH_KEY_BYTES = BANDERSNATCH_KEY_BYTES;
4862
- type index$l_BANDERSNATCH_PROOF_BYTES = BANDERSNATCH_PROOF_BYTES;
4863
- type index$l_BANDERSNATCH_RING_ROOT_BYTES = BANDERSNATCH_RING_ROOT_BYTES;
4864
- type index$l_BANDERSNATCH_VRF_SIGNATURE_BYTES = BANDERSNATCH_VRF_SIGNATURE_BYTES;
4865
- type index$l_BLS_KEY_BYTES = BLS_KEY_BYTES;
4866
- type index$l_BandersnatchKey = BandersnatchKey;
4867
- type index$l_BandersnatchProof = BandersnatchProof;
4868
- type index$l_BandersnatchRingRoot = BandersnatchRingRoot;
4869
- type index$l_BandersnatchSecretSeed = BandersnatchSecretSeed;
4870
- type index$l_BandersnatchVrfSignature = BandersnatchVrfSignature;
4871
- type index$l_BlsKey = BlsKey;
4872
- type index$l_ED25519_KEY_BYTES = ED25519_KEY_BYTES;
4873
- type index$l_ED25519_PRIV_KEY_BYTES = ED25519_PRIV_KEY_BYTES;
4874
- type index$l_ED25519_SIGNATURE_BYTES = ED25519_SIGNATURE_BYTES;
4875
- type index$l_Ed25519Key = Ed25519Key;
4876
- type index$l_Ed25519Pair = Ed25519Pair;
4877
- declare const index$l_Ed25519Pair: typeof Ed25519Pair;
4878
- type index$l_Ed25519SecretSeed = Ed25519SecretSeed;
4879
- type index$l_Ed25519Signature = Ed25519Signature;
4880
- type index$l_SEED_SIZE = SEED_SIZE;
4881
- declare const index$l_bandersnatch: typeof bandersnatch;
4882
- declare const index$l_ed25519: typeof ed25519;
4883
- declare const index$l_keyDerivation: typeof keyDerivation;
4884
- declare namespace index$l {
4885
- export { index$l_Ed25519Pair as Ed25519Pair, index$l_bandersnatch as bandersnatch, bandersnatch_d_exports as bandersnatchWasm, index$l_ed25519 as ed25519, initAll as initWasm, index$l_keyDerivation as keyDerivation };
4886
- export type { index$l_BANDERSNATCH_KEY_BYTES as BANDERSNATCH_KEY_BYTES, index$l_BANDERSNATCH_PROOF_BYTES as BANDERSNATCH_PROOF_BYTES, index$l_BANDERSNATCH_RING_ROOT_BYTES as BANDERSNATCH_RING_ROOT_BYTES, index$l_BANDERSNATCH_VRF_SIGNATURE_BYTES as BANDERSNATCH_VRF_SIGNATURE_BYTES, index$l_BLS_KEY_BYTES as BLS_KEY_BYTES, index$l_BandersnatchKey as BandersnatchKey, index$l_BandersnatchProof as BandersnatchProof, index$l_BandersnatchRingRoot as BandersnatchRingRoot, index$l_BandersnatchSecretSeed as BandersnatchSecretSeed, index$l_BandersnatchVrfSignature as BandersnatchVrfSignature, index$l_BlsKey as BlsKey, index$l_ED25519_KEY_BYTES as ED25519_KEY_BYTES, index$l_ED25519_PRIV_KEY_BYTES as ED25519_PRIV_KEY_BYTES, index$l_ED25519_SIGNATURE_BYTES as ED25519_SIGNATURE_BYTES, index$l_Ed25519Key as Ed25519Key, index$l_Ed25519SecretSeed as Ed25519SecretSeed, index$l_Ed25519Signature as Ed25519Signature, KeySeed as PublicKeySeed, index$l_SEED_SIZE as SEED_SIZE };
4886
+ type index$n_BANDERSNATCH_KEY_BYTES = BANDERSNATCH_KEY_BYTES;
4887
+ type index$n_BANDERSNATCH_PROOF_BYTES = BANDERSNATCH_PROOF_BYTES;
4888
+ type index$n_BANDERSNATCH_RING_ROOT_BYTES = BANDERSNATCH_RING_ROOT_BYTES;
4889
+ type index$n_BANDERSNATCH_VRF_SIGNATURE_BYTES = BANDERSNATCH_VRF_SIGNATURE_BYTES;
4890
+ type index$n_BLS_KEY_BYTES = BLS_KEY_BYTES;
4891
+ type index$n_BandersnatchKey = BandersnatchKey;
4892
+ type index$n_BandersnatchProof = BandersnatchProof;
4893
+ type index$n_BandersnatchRingRoot = BandersnatchRingRoot;
4894
+ type index$n_BandersnatchSecretSeed = BandersnatchSecretSeed;
4895
+ type index$n_BandersnatchVrfSignature = BandersnatchVrfSignature;
4896
+ type index$n_BlsKey = BlsKey;
4897
+ type index$n_ED25519_KEY_BYTES = ED25519_KEY_BYTES;
4898
+ type index$n_ED25519_PRIV_KEY_BYTES = ED25519_PRIV_KEY_BYTES;
4899
+ type index$n_ED25519_SIGNATURE_BYTES = ED25519_SIGNATURE_BYTES;
4900
+ type index$n_Ed25519Key = Ed25519Key;
4901
+ type index$n_Ed25519Pair = Ed25519Pair;
4902
+ declare const index$n_Ed25519Pair: typeof Ed25519Pair;
4903
+ type index$n_Ed25519SecretSeed = Ed25519SecretSeed;
4904
+ type index$n_Ed25519Signature = Ed25519Signature;
4905
+ type index$n_SEED_SIZE = SEED_SIZE;
4906
+ declare const index$n_bandersnatch: typeof bandersnatch;
4907
+ declare const index$n_ed25519: typeof ed25519;
4908
+ declare const index$n_keyDerivation: typeof keyDerivation;
4909
+ declare namespace index$n {
4910
+ export { index$n_Ed25519Pair as Ed25519Pair, index$n_bandersnatch as bandersnatch, bandersnatch_d_exports as bandersnatchWasm, index$n_ed25519 as ed25519, initAll as initWasm, index$n_keyDerivation as keyDerivation };
4911
+ export type { index$n_BANDERSNATCH_KEY_BYTES as BANDERSNATCH_KEY_BYTES, index$n_BANDERSNATCH_PROOF_BYTES as BANDERSNATCH_PROOF_BYTES, index$n_BANDERSNATCH_RING_ROOT_BYTES as BANDERSNATCH_RING_ROOT_BYTES, index$n_BANDERSNATCH_VRF_SIGNATURE_BYTES as BANDERSNATCH_VRF_SIGNATURE_BYTES, index$n_BLS_KEY_BYTES as BLS_KEY_BYTES, index$n_BandersnatchKey as BandersnatchKey, index$n_BandersnatchProof as BandersnatchProof, index$n_BandersnatchRingRoot as BandersnatchRingRoot, index$n_BandersnatchSecretSeed as BandersnatchSecretSeed, index$n_BandersnatchVrfSignature as BandersnatchVrfSignature, index$n_BlsKey as BlsKey, index$n_ED25519_KEY_BYTES as ED25519_KEY_BYTES, index$n_ED25519_PRIV_KEY_BYTES as ED25519_PRIV_KEY_BYTES, index$n_ED25519_SIGNATURE_BYTES as ED25519_SIGNATURE_BYTES, index$n_Ed25519Key as Ed25519Key, index$n_Ed25519SecretSeed as Ed25519SecretSeed, index$n_Ed25519Signature as Ed25519Signature, KeySeed as PublicKeySeed, index$n_SEED_SIZE as SEED_SIZE };
4887
4912
  }
4888
4913
 
4889
4914
  /**
@@ -5080,24 +5105,24 @@ declare class Bootnode implements PeerAddress {
5080
5105
  }
5081
5106
  }
5082
5107
 
5083
- type index$k_Bootnode = Bootnode;
5084
- declare const index$k_Bootnode: typeof Bootnode;
5085
- type index$k_ChainSpec = ChainSpec;
5086
- declare const index$k_ChainSpec: typeof ChainSpec;
5087
- declare const index$k_EC_SEGMENT_SIZE: typeof EC_SEGMENT_SIZE;
5088
- declare const index$k_EST_CORES: typeof EST_CORES;
5089
- declare const index$k_EST_EPOCH_LENGTH: typeof EST_EPOCH_LENGTH;
5090
- declare const index$k_EST_VALIDATORS: typeof EST_VALIDATORS;
5091
- declare const index$k_EST_VALIDATORS_SUPER_MAJORITY: typeof EST_VALIDATORS_SUPER_MAJORITY;
5092
- type index$k_PeerAddress = PeerAddress;
5093
- type index$k_PeerId = PeerId;
5094
- type index$k_WorkerConfig = WorkerConfig;
5095
- declare const index$k_WorkerConfig: typeof WorkerConfig;
5096
- declare const index$k_fullChainSpec: typeof fullChainSpec;
5097
- declare const index$k_tinyChainSpec: typeof tinyChainSpec;
5098
- declare namespace index$k {
5099
- export { index$k_Bootnode as Bootnode, index$k_ChainSpec as ChainSpec, index$k_EC_SEGMENT_SIZE as EC_SEGMENT_SIZE, index$k_EST_CORES as EST_CORES, index$k_EST_EPOCH_LENGTH as EST_EPOCH_LENGTH, index$k_EST_VALIDATORS as EST_VALIDATORS, index$k_EST_VALIDATORS_SUPER_MAJORITY as EST_VALIDATORS_SUPER_MAJORITY, index$k_WorkerConfig as WorkerConfig, index$k_fullChainSpec as fullChainSpec, index$k_tinyChainSpec as tinyChainSpec };
5100
- export type { index$k_PeerAddress as PeerAddress, index$k_PeerId as PeerId };
5108
+ type index$m_Bootnode = Bootnode;
5109
+ declare const index$m_Bootnode: typeof Bootnode;
5110
+ type index$m_ChainSpec = ChainSpec;
5111
+ declare const index$m_ChainSpec: typeof ChainSpec;
5112
+ declare const index$m_EC_SEGMENT_SIZE: typeof EC_SEGMENT_SIZE;
5113
+ declare const index$m_EST_CORES: typeof EST_CORES;
5114
+ declare const index$m_EST_EPOCH_LENGTH: typeof EST_EPOCH_LENGTH;
5115
+ declare const index$m_EST_VALIDATORS: typeof EST_VALIDATORS;
5116
+ declare const index$m_EST_VALIDATORS_SUPER_MAJORITY: typeof EST_VALIDATORS_SUPER_MAJORITY;
5117
+ type index$m_PeerAddress = PeerAddress;
5118
+ type index$m_PeerId = PeerId;
5119
+ type index$m_WorkerConfig = WorkerConfig;
5120
+ declare const index$m_WorkerConfig: typeof WorkerConfig;
5121
+ declare const index$m_fullChainSpec: typeof fullChainSpec;
5122
+ declare const index$m_tinyChainSpec: typeof tinyChainSpec;
5123
+ declare namespace index$m {
5124
+ export { index$m_Bootnode as Bootnode, index$m_ChainSpec as ChainSpec, index$m_EC_SEGMENT_SIZE as EC_SEGMENT_SIZE, index$m_EST_CORES as EST_CORES, index$m_EST_EPOCH_LENGTH as EST_EPOCH_LENGTH, index$m_EST_VALIDATORS as EST_VALIDATORS, index$m_EST_VALIDATORS_SUPER_MAJORITY as EST_VALIDATORS_SUPER_MAJORITY, index$m_WorkerConfig as WorkerConfig, index$m_fullChainSpec as fullChainSpec, index$m_tinyChainSpec as tinyChainSpec };
5125
+ export type { index$m_PeerAddress as PeerAddress, index$m_PeerId as PeerId };
5101
5126
  }
5102
5127
 
5103
5128
  /**
@@ -6892,73 +6917,73 @@ declare function emptyBlock(slot: TimeSlot = tryAsTimeSlot(0)) {
6892
6917
  });
6893
6918
  }
6894
6919
 
6895
- type index$j_Block = Block;
6896
- declare const index$j_Block: typeof Block;
6897
- type index$j_BlockView = BlockView;
6898
- type index$j_CodeHash = CodeHash;
6899
- type index$j_CoreIndex = CoreIndex;
6900
- type index$j_EntropyHash = EntropyHash;
6901
- type index$j_Epoch = Epoch;
6902
- type index$j_EpochMarker = EpochMarker;
6903
- declare const index$j_EpochMarker: typeof EpochMarker;
6904
- type index$j_EpochMarkerView = EpochMarkerView;
6905
- type index$j_Extrinsic = Extrinsic;
6906
- declare const index$j_Extrinsic: typeof Extrinsic;
6907
- type index$j_ExtrinsicHash = ExtrinsicHash;
6908
- type index$j_ExtrinsicView = ExtrinsicView;
6909
- type index$j_Header = Header;
6910
- declare const index$j_Header: typeof Header;
6911
- type index$j_HeaderHash = HeaderHash;
6912
- type index$j_HeaderView = HeaderView;
6913
- type index$j_HeaderViewWithHash = HeaderViewWithHash;
6914
- declare const index$j_HeaderViewWithHash: typeof HeaderViewWithHash;
6915
- declare const index$j_MAX_NUMBER_OF_SEGMENTS: typeof MAX_NUMBER_OF_SEGMENTS;
6916
- type index$j_PerEpochBlock<T> = PerEpochBlock<T>;
6917
- type index$j_PerValidator<T> = PerValidator<T>;
6918
- type index$j_SEGMENT_BYTES = SEGMENT_BYTES;
6919
- type index$j_Segment = Segment;
6920
- type index$j_SegmentIndex = SegmentIndex;
6921
- type index$j_ServiceGas = ServiceGas;
6922
- type index$j_ServiceId = ServiceId;
6923
- type index$j_StateRootHash = StateRootHash;
6924
- type index$j_TicketsMarker = TicketsMarker;
6925
- declare const index$j_TicketsMarker: typeof TicketsMarker;
6926
- type index$j_TicketsMarkerView = TicketsMarkerView;
6927
- type index$j_TimeSlot = TimeSlot;
6928
- type index$j_ValidatorIndex = ValidatorIndex;
6929
- type index$j_ValidatorKeys = ValidatorKeys;
6930
- declare const index$j_ValidatorKeys: typeof ValidatorKeys;
6931
- declare const index$j_W_E: typeof W_E;
6932
- declare const index$j_W_S: typeof W_S;
6933
- type index$j_WorkReportHash = WorkReportHash;
6934
- declare const index$j_assurances: typeof assurances;
6935
- declare const index$j_codecPerEpochBlock: typeof codecPerEpochBlock;
6936
- declare const index$j_codecPerValidator: typeof codecPerValidator;
6937
- declare const index$j_disputes: typeof disputes;
6938
- declare const index$j_emptyBlock: typeof emptyBlock;
6939
- declare const index$j_encodeUnsealedHeader: typeof encodeUnsealedHeader;
6940
- declare const index$j_guarantees: typeof guarantees;
6941
- declare const index$j_headerViewWithHashCodec: typeof headerViewWithHashCodec;
6942
- declare const index$j_legacyDescriptor: typeof legacyDescriptor;
6943
- declare const index$j_preimage: typeof preimage;
6944
- declare const index$j_refineContext: typeof refineContext;
6945
- declare const index$j_tickets: typeof tickets;
6946
- declare const index$j_tryAsCoreIndex: typeof tryAsCoreIndex;
6947
- declare const index$j_tryAsEpoch: typeof tryAsEpoch;
6948
- declare const index$j_tryAsPerEpochBlock: typeof tryAsPerEpochBlock;
6949
- declare const index$j_tryAsPerValidator: typeof tryAsPerValidator;
6950
- declare const index$j_tryAsSegmentIndex: typeof tryAsSegmentIndex;
6951
- declare const index$j_tryAsServiceGas: typeof tryAsServiceGas;
6952
- declare const index$j_tryAsServiceId: typeof tryAsServiceId;
6953
- declare const index$j_tryAsTimeSlot: typeof tryAsTimeSlot;
6954
- declare const index$j_tryAsValidatorIndex: typeof tryAsValidatorIndex;
6955
- declare const index$j_workItem: typeof workItem;
6956
- declare const index$j_workPackage: typeof workPackage;
6957
- declare const index$j_workReport: typeof workReport;
6958
- declare const index$j_workResult: typeof workResult;
6959
- declare namespace index$j {
6960
- export { index$j_Block as Block, index$j_EpochMarker as EpochMarker, index$j_Extrinsic as Extrinsic, index$j_Header as Header, index$j_HeaderViewWithHash as HeaderViewWithHash, index$j_MAX_NUMBER_OF_SEGMENTS as MAX_NUMBER_OF_SEGMENTS, index$j_TicketsMarker as TicketsMarker, index$j_ValidatorKeys as ValidatorKeys, index$j_W_E as W_E, index$j_W_S as W_S, index$j_assurances as assurances, index$j_codecPerEpochBlock as codecPerEpochBlock, index$j_codecPerValidator as codecPerValidator, codec as codecUtils, index$j_disputes as disputes, index$j_emptyBlock as emptyBlock, index$j_encodeUnsealedHeader as encodeUnsealedHeader, index$j_guarantees as guarantees, index$j_headerViewWithHashCodec as headerViewWithHashCodec, index$j_legacyDescriptor as legacyDescriptor, index$j_preimage as preimage, index$j_refineContext as refineContext, index$j_tickets as tickets, index$j_tryAsCoreIndex as tryAsCoreIndex, index$j_tryAsEpoch as tryAsEpoch, index$j_tryAsPerEpochBlock as tryAsPerEpochBlock, index$j_tryAsPerValidator as tryAsPerValidator, index$j_tryAsSegmentIndex as tryAsSegmentIndex, index$j_tryAsServiceGas as tryAsServiceGas, index$j_tryAsServiceId as tryAsServiceId, index$j_tryAsTimeSlot as tryAsTimeSlot, index$j_tryAsValidatorIndex as tryAsValidatorIndex, index$j_workItem as workItem, index$j_workPackage as workPackage, index$j_workReport as workReport, index$j_workResult as workResult };
6961
- export type { index$j_BlockView as BlockView, index$j_CodeHash as CodeHash, index$j_CoreIndex as CoreIndex, index$j_EntropyHash as EntropyHash, index$j_Epoch as Epoch, index$j_EpochMarkerView as EpochMarkerView, index$j_ExtrinsicHash as ExtrinsicHash, index$j_ExtrinsicView as ExtrinsicView, index$j_HeaderHash as HeaderHash, index$j_HeaderView as HeaderView, index$j_PerEpochBlock as PerEpochBlock, index$j_PerValidator as PerValidator, index$j_SEGMENT_BYTES as SEGMENT_BYTES, index$j_Segment as Segment, index$j_SegmentIndex as SegmentIndex, index$j_ServiceGas as ServiceGas, index$j_ServiceId as ServiceId, index$j_StateRootHash as StateRootHash, index$j_TicketsMarkerView as TicketsMarkerView, index$j_TimeSlot as TimeSlot, index$j_ValidatorIndex as ValidatorIndex, index$j_WorkReportHash as WorkReportHash };
6920
+ type index$l_Block = Block;
6921
+ declare const index$l_Block: typeof Block;
6922
+ type index$l_BlockView = BlockView;
6923
+ type index$l_CodeHash = CodeHash;
6924
+ type index$l_CoreIndex = CoreIndex;
6925
+ type index$l_EntropyHash = EntropyHash;
6926
+ type index$l_Epoch = Epoch;
6927
+ type index$l_EpochMarker = EpochMarker;
6928
+ declare const index$l_EpochMarker: typeof EpochMarker;
6929
+ type index$l_EpochMarkerView = EpochMarkerView;
6930
+ type index$l_Extrinsic = Extrinsic;
6931
+ declare const index$l_Extrinsic: typeof Extrinsic;
6932
+ type index$l_ExtrinsicHash = ExtrinsicHash;
6933
+ type index$l_ExtrinsicView = ExtrinsicView;
6934
+ type index$l_Header = Header;
6935
+ declare const index$l_Header: typeof Header;
6936
+ type index$l_HeaderHash = HeaderHash;
6937
+ type index$l_HeaderView = HeaderView;
6938
+ type index$l_HeaderViewWithHash = HeaderViewWithHash;
6939
+ declare const index$l_HeaderViewWithHash: typeof HeaderViewWithHash;
6940
+ declare const index$l_MAX_NUMBER_OF_SEGMENTS: typeof MAX_NUMBER_OF_SEGMENTS;
6941
+ type index$l_PerEpochBlock<T> = PerEpochBlock<T>;
6942
+ type index$l_PerValidator<T> = PerValidator<T>;
6943
+ type index$l_SEGMENT_BYTES = SEGMENT_BYTES;
6944
+ type index$l_Segment = Segment;
6945
+ type index$l_SegmentIndex = SegmentIndex;
6946
+ type index$l_ServiceGas = ServiceGas;
6947
+ type index$l_ServiceId = ServiceId;
6948
+ type index$l_StateRootHash = StateRootHash;
6949
+ type index$l_TicketsMarker = TicketsMarker;
6950
+ declare const index$l_TicketsMarker: typeof TicketsMarker;
6951
+ type index$l_TicketsMarkerView = TicketsMarkerView;
6952
+ type index$l_TimeSlot = TimeSlot;
6953
+ type index$l_ValidatorIndex = ValidatorIndex;
6954
+ type index$l_ValidatorKeys = ValidatorKeys;
6955
+ declare const index$l_ValidatorKeys: typeof ValidatorKeys;
6956
+ declare const index$l_W_E: typeof W_E;
6957
+ declare const index$l_W_S: typeof W_S;
6958
+ type index$l_WorkReportHash = WorkReportHash;
6959
+ declare const index$l_assurances: typeof assurances;
6960
+ declare const index$l_codecPerEpochBlock: typeof codecPerEpochBlock;
6961
+ declare const index$l_codecPerValidator: typeof codecPerValidator;
6962
+ declare const index$l_disputes: typeof disputes;
6963
+ declare const index$l_emptyBlock: typeof emptyBlock;
6964
+ declare const index$l_encodeUnsealedHeader: typeof encodeUnsealedHeader;
6965
+ declare const index$l_guarantees: typeof guarantees;
6966
+ declare const index$l_headerViewWithHashCodec: typeof headerViewWithHashCodec;
6967
+ declare const index$l_legacyDescriptor: typeof legacyDescriptor;
6968
+ declare const index$l_preimage: typeof preimage;
6969
+ declare const index$l_refineContext: typeof refineContext;
6970
+ declare const index$l_tickets: typeof tickets;
6971
+ declare const index$l_tryAsCoreIndex: typeof tryAsCoreIndex;
6972
+ declare const index$l_tryAsEpoch: typeof tryAsEpoch;
6973
+ declare const index$l_tryAsPerEpochBlock: typeof tryAsPerEpochBlock;
6974
+ declare const index$l_tryAsPerValidator: typeof tryAsPerValidator;
6975
+ declare const index$l_tryAsSegmentIndex: typeof tryAsSegmentIndex;
6976
+ declare const index$l_tryAsServiceGas: typeof tryAsServiceGas;
6977
+ declare const index$l_tryAsServiceId: typeof tryAsServiceId;
6978
+ declare const index$l_tryAsTimeSlot: typeof tryAsTimeSlot;
6979
+ declare const index$l_tryAsValidatorIndex: typeof tryAsValidatorIndex;
6980
+ declare const index$l_workItem: typeof workItem;
6981
+ declare const index$l_workPackage: typeof workPackage;
6982
+ declare const index$l_workReport: typeof workReport;
6983
+ declare const index$l_workResult: typeof workResult;
6984
+ declare namespace index$l {
6985
+ export { index$l_Block as Block, index$l_EpochMarker as EpochMarker, index$l_Extrinsic as Extrinsic, index$l_Header as Header, index$l_HeaderViewWithHash as HeaderViewWithHash, index$l_MAX_NUMBER_OF_SEGMENTS as MAX_NUMBER_OF_SEGMENTS, index$l_TicketsMarker as TicketsMarker, index$l_ValidatorKeys as ValidatorKeys, index$l_W_E as W_E, index$l_W_S as W_S, index$l_assurances as assurances, index$l_codecPerEpochBlock as codecPerEpochBlock, index$l_codecPerValidator as codecPerValidator, codec as codecUtils, index$l_disputes as disputes, index$l_emptyBlock as emptyBlock, index$l_encodeUnsealedHeader as encodeUnsealedHeader, index$l_guarantees as guarantees, index$l_headerViewWithHashCodec as headerViewWithHashCodec, index$l_legacyDescriptor as legacyDescriptor, index$l_preimage as preimage, index$l_refineContext as refineContext, index$l_tickets as tickets, index$l_tryAsCoreIndex as tryAsCoreIndex, index$l_tryAsEpoch as tryAsEpoch, index$l_tryAsPerEpochBlock as tryAsPerEpochBlock, index$l_tryAsPerValidator as tryAsPerValidator, index$l_tryAsSegmentIndex as tryAsSegmentIndex, index$l_tryAsServiceGas as tryAsServiceGas, index$l_tryAsServiceId as tryAsServiceId, index$l_tryAsTimeSlot as tryAsTimeSlot, index$l_tryAsValidatorIndex as tryAsValidatorIndex, index$l_workItem as workItem, index$l_workPackage as workPackage, index$l_workReport as workReport, index$l_workResult as workResult };
6986
+ export type { index$l_BlockView as BlockView, index$l_CodeHash as CodeHash, index$l_CoreIndex as CoreIndex, index$l_EntropyHash as EntropyHash, index$l_Epoch as Epoch, index$l_EpochMarkerView as EpochMarkerView, index$l_ExtrinsicHash as ExtrinsicHash, index$l_ExtrinsicView as ExtrinsicView, index$l_HeaderHash as HeaderHash, index$l_HeaderView as HeaderView, index$l_PerEpochBlock as PerEpochBlock, index$l_PerValidator as PerValidator, index$l_SEGMENT_BYTES as SEGMENT_BYTES, index$l_Segment as Segment, index$l_SegmentIndex as SegmentIndex, index$l_ServiceGas as ServiceGas, index$l_ServiceId as ServiceId, index$l_StateRootHash as StateRootHash, index$l_TicketsMarkerView as TicketsMarkerView, index$l_TimeSlot as TimeSlot, index$l_ValidatorIndex as ValidatorIndex, index$l_WorkReportHash as WorkReportHash };
6962
6987
  }
6963
6988
 
6964
6989
  /** A type that can be read from a JSON-parsed object. */
@@ -7256,21 +7281,21 @@ declare namespace json {
7256
7281
  }
7257
7282
  }
7258
7283
 
7259
- type index$i_Builder<TFrom, TInto> = Builder<TFrom, TInto>;
7260
- type index$i_FromJson<T> = FromJson<T>;
7261
- type index$i_FromJsonOptional<TInto> = FromJsonOptional<TInto>;
7262
- type index$i_FromJsonPrimitive<T> = FromJsonPrimitive<T>;
7263
- type index$i_FromJsonWithParser<TFrom, TInto> = FromJsonWithParser<TFrom, TInto>;
7264
- declare const index$i_NO_KEY: typeof NO_KEY;
7265
- type index$i_ObjectFromJson<T> = ObjectFromJson<T>;
7266
- type index$i_Parser<TFrom, TInto> = Parser<TFrom, TInto>;
7267
- declare const index$i_diffKeys: typeof diffKeys;
7268
- import index$i_json = json;
7269
- declare const index$i_parseFromJson: typeof parseFromJson;
7270
- declare const index$i_parseOrThrow: typeof parseOrThrow;
7271
- declare namespace index$i {
7272
- export { index$i_NO_KEY as NO_KEY, index$i_diffKeys as diffKeys, index$i_json as json, index$i_parseFromJson as parseFromJson, index$i_parseOrThrow as parseOrThrow };
7273
- export type { index$i_Builder as Builder, index$i_FromJson as FromJson, index$i_FromJsonOptional as FromJsonOptional, index$i_FromJsonPrimitive as FromJsonPrimitive, index$i_FromJsonWithParser as FromJsonWithParser, index$i_ObjectFromJson as ObjectFromJson, index$i_Parser as Parser };
7284
+ type index$k_Builder<TFrom, TInto> = Builder<TFrom, TInto>;
7285
+ type index$k_FromJson<T> = FromJson<T>;
7286
+ type index$k_FromJsonOptional<TInto> = FromJsonOptional<TInto>;
7287
+ type index$k_FromJsonPrimitive<T> = FromJsonPrimitive<T>;
7288
+ type index$k_FromJsonWithParser<TFrom, TInto> = FromJsonWithParser<TFrom, TInto>;
7289
+ declare const index$k_NO_KEY: typeof NO_KEY;
7290
+ type index$k_ObjectFromJson<T> = ObjectFromJson<T>;
7291
+ type index$k_Parser<TFrom, TInto> = Parser<TFrom, TInto>;
7292
+ declare const index$k_diffKeys: typeof diffKeys;
7293
+ import index$k_json = json;
7294
+ declare const index$k_parseFromJson: typeof parseFromJson;
7295
+ declare const index$k_parseOrThrow: typeof parseOrThrow;
7296
+ declare namespace index$k {
7297
+ export { index$k_NO_KEY as NO_KEY, index$k_diffKeys as diffKeys, index$k_json as json, index$k_parseFromJson as parseFromJson, index$k_parseOrThrow as parseOrThrow };
7298
+ export type { index$k_Builder as Builder, index$k_FromJson as FromJson, index$k_FromJsonOptional as FromJsonOptional, index$k_FromJsonPrimitive as FromJsonPrimitive, index$k_FromJsonWithParser as FromJsonWithParser, index$k_ObjectFromJson as ObjectFromJson, index$k_Parser as Parser };
7274
7299
  }
7275
7300
 
7276
7301
  declare namespace fromJson {
@@ -7773,52 +7798,52 @@ declare const blockFromJson = (spec: ChainSpec) =>
7773
7798
  ({ header, extrinsic }) => Block.create({ header, extrinsic }),
7774
7799
  );
7775
7800
 
7776
- type index$h_CamelToSnake<S extends string> = CamelToSnake<S>;
7777
- type index$h_JsonCulprit = JsonCulprit;
7778
- type index$h_JsonEpochMarker = JsonEpochMarker;
7779
- type index$h_JsonFault = JsonFault;
7780
- type index$h_JsonHeader = JsonHeader;
7781
- type index$h_JsonJudgement = JsonJudgement;
7782
- type index$h_JsonObject<T> = JsonObject<T>;
7783
- type index$h_JsonRefineContext = JsonRefineContext;
7784
- type index$h_JsonReportGuarantee = JsonReportGuarantee;
7785
- type index$h_JsonVerdict = JsonVerdict;
7786
- type index$h_JsonWorkExecResult = JsonWorkExecResult;
7787
- type index$h_JsonWorkRefineLoad = JsonWorkRefineLoad;
7788
- type index$h_JsonWorkReport = JsonWorkReport;
7789
- type index$h_JsonWorkResult = JsonWorkResult;
7790
- declare const index$h_bandersnatchVrfSignature: typeof bandersnatchVrfSignature;
7791
- declare const index$h_blockFromJson: typeof blockFromJson;
7792
- declare const index$h_culpritFromJson: typeof culpritFromJson;
7793
- declare const index$h_disputesExtrinsicFromJson: typeof disputesExtrinsicFromJson;
7794
- declare const index$h_epochMark: typeof epochMark;
7795
- declare const index$h_faultFromJson: typeof faultFromJson;
7796
- import index$h_fromJson = fromJson;
7797
- declare const index$h_getAssurancesExtrinsicFromJson: typeof getAssurancesExtrinsicFromJson;
7798
- declare const index$h_getAvailabilityAssuranceFromJson: typeof getAvailabilityAssuranceFromJson;
7799
- declare const index$h_getExtrinsicFromJson: typeof getExtrinsicFromJson;
7800
- declare const index$h_guaranteesExtrinsicFromJson: typeof guaranteesExtrinsicFromJson;
7801
- declare const index$h_headerFromJson: typeof headerFromJson;
7802
- declare const index$h_judgementFromJson: typeof judgementFromJson;
7803
- declare const index$h_preimageFromJson: typeof preimageFromJson;
7804
- declare const index$h_preimagesExtrinsicFromJson: typeof preimagesExtrinsicFromJson;
7805
- declare const index$h_refineContextFromJson: typeof refineContextFromJson;
7806
- declare const index$h_reportGuaranteeFromJson: typeof reportGuaranteeFromJson;
7807
- declare const index$h_segmentRootLookupItemFromJson: typeof segmentRootLookupItemFromJson;
7808
- declare const index$h_ticket: typeof ticket;
7809
- declare const index$h_ticketEnvelopeFromJson: typeof ticketEnvelopeFromJson;
7810
- declare const index$h_ticketsExtrinsicFromJson: typeof ticketsExtrinsicFromJson;
7811
- declare const index$h_validatorKeysFromJson: typeof validatorKeysFromJson;
7812
- declare const index$h_validatorSignatureFromJson: typeof validatorSignatureFromJson;
7813
- declare const index$h_verdictFromJson: typeof verdictFromJson;
7814
- declare const index$h_workExecResultFromJson: typeof workExecResultFromJson;
7815
- declare const index$h_workPackageSpecFromJson: typeof workPackageSpecFromJson;
7816
- declare const index$h_workRefineLoadFromJson: typeof workRefineLoadFromJson;
7817
- declare const index$h_workReportFromJson: typeof workReportFromJson;
7818
- declare const index$h_workResultFromJson: typeof workResultFromJson;
7819
- declare namespace index$h {
7820
- export { index$h_bandersnatchVrfSignature as bandersnatchVrfSignature, index$h_blockFromJson as blockFromJson, index$h_culpritFromJson as culpritFromJson, index$h_disputesExtrinsicFromJson as disputesExtrinsicFromJson, index$h_epochMark as epochMark, index$h_faultFromJson as faultFromJson, index$h_fromJson as fromJson, index$h_getAssurancesExtrinsicFromJson as getAssurancesExtrinsicFromJson, index$h_getAvailabilityAssuranceFromJson as getAvailabilityAssuranceFromJson, index$h_getExtrinsicFromJson as getExtrinsicFromJson, index$h_guaranteesExtrinsicFromJson as guaranteesExtrinsicFromJson, index$h_headerFromJson as headerFromJson, index$h_judgementFromJson as judgementFromJson, index$h_preimageFromJson as preimageFromJson, index$h_preimagesExtrinsicFromJson as preimagesExtrinsicFromJson, index$h_refineContextFromJson as refineContextFromJson, index$h_reportGuaranteeFromJson as reportGuaranteeFromJson, index$h_segmentRootLookupItemFromJson as segmentRootLookupItemFromJson, index$h_ticket as ticket, index$h_ticketEnvelopeFromJson as ticketEnvelopeFromJson, index$h_ticketsExtrinsicFromJson as ticketsExtrinsicFromJson, index$h_validatorKeysFromJson as validatorKeysFromJson, index$h_validatorSignatureFromJson as validatorSignatureFromJson, index$h_verdictFromJson as verdictFromJson, index$h_workExecResultFromJson as workExecResultFromJson, index$h_workPackageSpecFromJson as workPackageSpecFromJson, index$h_workRefineLoadFromJson as workRefineLoadFromJson, index$h_workReportFromJson as workReportFromJson, index$h_workResultFromJson as workResultFromJson };
7821
- export type { index$h_CamelToSnake as CamelToSnake, index$h_JsonCulprit as JsonCulprit, index$h_JsonEpochMarker as JsonEpochMarker, index$h_JsonFault as JsonFault, index$h_JsonHeader as JsonHeader, index$h_JsonJudgement as JsonJudgement, index$h_JsonObject as JsonObject, index$h_JsonRefineContext as JsonRefineContext, index$h_JsonReportGuarantee as JsonReportGuarantee, index$h_JsonVerdict as JsonVerdict, index$h_JsonWorkExecResult as JsonWorkExecResult, index$h_JsonWorkRefineLoad as JsonWorkRefineLoad, index$h_JsonWorkReport as JsonWorkReport, index$h_JsonWorkResult as JsonWorkResult };
7801
+ type index$j_CamelToSnake<S extends string> = CamelToSnake<S>;
7802
+ type index$j_JsonCulprit = JsonCulprit;
7803
+ type index$j_JsonEpochMarker = JsonEpochMarker;
7804
+ type index$j_JsonFault = JsonFault;
7805
+ type index$j_JsonHeader = JsonHeader;
7806
+ type index$j_JsonJudgement = JsonJudgement;
7807
+ type index$j_JsonObject<T> = JsonObject<T>;
7808
+ type index$j_JsonRefineContext = JsonRefineContext;
7809
+ type index$j_JsonReportGuarantee = JsonReportGuarantee;
7810
+ type index$j_JsonVerdict = JsonVerdict;
7811
+ type index$j_JsonWorkExecResult = JsonWorkExecResult;
7812
+ type index$j_JsonWorkRefineLoad = JsonWorkRefineLoad;
7813
+ type index$j_JsonWorkReport = JsonWorkReport;
7814
+ type index$j_JsonWorkResult = JsonWorkResult;
7815
+ declare const index$j_bandersnatchVrfSignature: typeof bandersnatchVrfSignature;
7816
+ declare const index$j_blockFromJson: typeof blockFromJson;
7817
+ declare const index$j_culpritFromJson: typeof culpritFromJson;
7818
+ declare const index$j_disputesExtrinsicFromJson: typeof disputesExtrinsicFromJson;
7819
+ declare const index$j_epochMark: typeof epochMark;
7820
+ declare const index$j_faultFromJson: typeof faultFromJson;
7821
+ import index$j_fromJson = fromJson;
7822
+ declare const index$j_getAssurancesExtrinsicFromJson: typeof getAssurancesExtrinsicFromJson;
7823
+ declare const index$j_getAvailabilityAssuranceFromJson: typeof getAvailabilityAssuranceFromJson;
7824
+ declare const index$j_getExtrinsicFromJson: typeof getExtrinsicFromJson;
7825
+ declare const index$j_guaranteesExtrinsicFromJson: typeof guaranteesExtrinsicFromJson;
7826
+ declare const index$j_headerFromJson: typeof headerFromJson;
7827
+ declare const index$j_judgementFromJson: typeof judgementFromJson;
7828
+ declare const index$j_preimageFromJson: typeof preimageFromJson;
7829
+ declare const index$j_preimagesExtrinsicFromJson: typeof preimagesExtrinsicFromJson;
7830
+ declare const index$j_refineContextFromJson: typeof refineContextFromJson;
7831
+ declare const index$j_reportGuaranteeFromJson: typeof reportGuaranteeFromJson;
7832
+ declare const index$j_segmentRootLookupItemFromJson: typeof segmentRootLookupItemFromJson;
7833
+ declare const index$j_ticket: typeof ticket;
7834
+ declare const index$j_ticketEnvelopeFromJson: typeof ticketEnvelopeFromJson;
7835
+ declare const index$j_ticketsExtrinsicFromJson: typeof ticketsExtrinsicFromJson;
7836
+ declare const index$j_validatorKeysFromJson: typeof validatorKeysFromJson;
7837
+ declare const index$j_validatorSignatureFromJson: typeof validatorSignatureFromJson;
7838
+ declare const index$j_verdictFromJson: typeof verdictFromJson;
7839
+ declare const index$j_workExecResultFromJson: typeof workExecResultFromJson;
7840
+ declare const index$j_workPackageSpecFromJson: typeof workPackageSpecFromJson;
7841
+ declare const index$j_workRefineLoadFromJson: typeof workRefineLoadFromJson;
7842
+ declare const index$j_workReportFromJson: typeof workReportFromJson;
7843
+ declare const index$j_workResultFromJson: typeof workResultFromJson;
7844
+ declare namespace index$j {
7845
+ export { index$j_bandersnatchVrfSignature as bandersnatchVrfSignature, index$j_blockFromJson as blockFromJson, index$j_culpritFromJson as culpritFromJson, index$j_disputesExtrinsicFromJson as disputesExtrinsicFromJson, index$j_epochMark as epochMark, index$j_faultFromJson as faultFromJson, index$j_fromJson as fromJson, index$j_getAssurancesExtrinsicFromJson as getAssurancesExtrinsicFromJson, index$j_getAvailabilityAssuranceFromJson as getAvailabilityAssuranceFromJson, index$j_getExtrinsicFromJson as getExtrinsicFromJson, index$j_guaranteesExtrinsicFromJson as guaranteesExtrinsicFromJson, index$j_headerFromJson as headerFromJson, index$j_judgementFromJson as judgementFromJson, index$j_preimageFromJson as preimageFromJson, index$j_preimagesExtrinsicFromJson as preimagesExtrinsicFromJson, index$j_refineContextFromJson as refineContextFromJson, index$j_reportGuaranteeFromJson as reportGuaranteeFromJson, index$j_segmentRootLookupItemFromJson as segmentRootLookupItemFromJson, index$j_ticket as ticket, index$j_ticketEnvelopeFromJson as ticketEnvelopeFromJson, index$j_ticketsExtrinsicFromJson as ticketsExtrinsicFromJson, index$j_validatorKeysFromJson as validatorKeysFromJson, index$j_validatorSignatureFromJson as validatorSignatureFromJson, index$j_verdictFromJson as verdictFromJson, index$j_workExecResultFromJson as workExecResultFromJson, index$j_workPackageSpecFromJson as workPackageSpecFromJson, index$j_workRefineLoadFromJson as workRefineLoadFromJson, index$j_workReportFromJson as workReportFromJson, index$j_workResultFromJson as workResultFromJson };
7846
+ export type { index$j_CamelToSnake as CamelToSnake, index$j_JsonCulprit as JsonCulprit, index$j_JsonEpochMarker as JsonEpochMarker, index$j_JsonFault as JsonFault, index$j_JsonHeader as JsonHeader, index$j_JsonJudgement as JsonJudgement, index$j_JsonObject as JsonObject, index$j_JsonRefineContext as JsonRefineContext, index$j_JsonReportGuarantee as JsonReportGuarantee, index$j_JsonVerdict as JsonVerdict, index$j_JsonWorkExecResult as JsonWorkExecResult, index$j_JsonWorkRefineLoad as JsonWorkRefineLoad, index$j_JsonWorkReport as JsonWorkReport, index$j_JsonWorkResult as JsonWorkResult };
7822
7847
  }
7823
7848
 
7824
7849
  declare function parseBootnode(v: string): Bootnode {
@@ -8066,16 +8091,16 @@ declare class Logger {
8066
8091
  }
8067
8092
  }
8068
8093
 
8069
- type index$g_Level = Level;
8070
- declare const index$g_Level: typeof Level;
8071
- type index$g_Logger = Logger;
8072
- declare const index$g_Logger: typeof Logger;
8073
- declare const index$g_parseLoggerOptions: typeof parseLoggerOptions;
8074
- declare namespace index$g {
8094
+ type index$i_Level = Level;
8095
+ declare const index$i_Level: typeof Level;
8096
+ type index$i_Logger = Logger;
8097
+ declare const index$i_Logger: typeof Logger;
8098
+ declare const index$i_parseLoggerOptions: typeof parseLoggerOptions;
8099
+ declare namespace index$i {
8075
8100
  export {
8076
- index$g_Level as Level,
8077
- index$g_Logger as Logger,
8078
- index$g_parseLoggerOptions as parseLoggerOptions,
8101
+ index$i_Level as Level,
8102
+ index$i_Logger as Logger,
8103
+ index$i_parseLoggerOptions as parseLoggerOptions,
8079
8104
  };
8080
8105
  }
8081
8106
 
@@ -8098,7 +8123,7 @@ declare class AuthorshipOptions {
8098
8123
  ) {}
8099
8124
  }
8100
8125
 
8101
- declare const logger$1 = Logger.new(import.meta.filename, "config");
8126
+ declare const logger$2 = Logger.new(import.meta.filename, "config");
8102
8127
 
8103
8128
  /** Development config. Will accept unsealed blocks for now. */
8104
8129
  declare const DEV_CONFIG = "dev";
@@ -8180,30 +8205,30 @@ declare function loadConfig(configPath: string): NodeConfiguration {
8180
8205
  }
8181
8206
  }
8182
8207
 
8183
- declare const index$f_DEFAULT_CONFIG: typeof DEFAULT_CONFIG;
8184
- declare const index$f_DEV_CONFIG: typeof DEV_CONFIG;
8185
- type index$f_JipChainSpec = JipChainSpec;
8186
- declare const index$f_JipChainSpec: typeof JipChainSpec;
8187
- type index$f_KnownChainSpec = KnownChainSpec;
8188
- declare const index$f_KnownChainSpec: typeof KnownChainSpec;
8189
- declare const index$f_NODE_DEFAULTS: typeof NODE_DEFAULTS;
8190
- type index$f_NodeConfiguration = NodeConfiguration;
8191
- declare const index$f_NodeConfiguration: typeof NodeConfiguration;
8192
- declare const index$f_knownChainSpecFromJson: typeof knownChainSpecFromJson;
8193
- declare const index$f_loadConfig: typeof loadConfig;
8194
- declare const index$f_parseBootnode: typeof parseBootnode;
8195
- declare namespace index$f {
8208
+ declare const index$h_DEFAULT_CONFIG: typeof DEFAULT_CONFIG;
8209
+ declare const index$h_DEV_CONFIG: typeof DEV_CONFIG;
8210
+ type index$h_JipChainSpec = JipChainSpec;
8211
+ declare const index$h_JipChainSpec: typeof JipChainSpec;
8212
+ type index$h_KnownChainSpec = KnownChainSpec;
8213
+ declare const index$h_KnownChainSpec: typeof KnownChainSpec;
8214
+ declare const index$h_NODE_DEFAULTS: typeof NODE_DEFAULTS;
8215
+ type index$h_NodeConfiguration = NodeConfiguration;
8216
+ declare const index$h_NodeConfiguration: typeof NodeConfiguration;
8217
+ declare const index$h_knownChainSpecFromJson: typeof knownChainSpecFromJson;
8218
+ declare const index$h_loadConfig: typeof loadConfig;
8219
+ declare const index$h_parseBootnode: typeof parseBootnode;
8220
+ declare namespace index$h {
8196
8221
  export {
8197
- index$f_DEFAULT_CONFIG as DEFAULT_CONFIG,
8198
- index$f_DEV_CONFIG as DEV_CONFIG,
8199
- index$f_JipChainSpec as JipChainSpec,
8200
- index$f_KnownChainSpec as KnownChainSpec,
8201
- index$f_NODE_DEFAULTS as NODE_DEFAULTS,
8202
- index$f_NodeConfiguration as NodeConfiguration,
8203
- index$f_knownChainSpecFromJson as knownChainSpecFromJson,
8204
- index$f_loadConfig as loadConfig,
8205
- logger$1 as logger,
8206
- index$f_parseBootnode as parseBootnode,
8222
+ index$h_DEFAULT_CONFIG as DEFAULT_CONFIG,
8223
+ index$h_DEV_CONFIG as DEV_CONFIG,
8224
+ index$h_JipChainSpec as JipChainSpec,
8225
+ index$h_KnownChainSpec as KnownChainSpec,
8226
+ index$h_NODE_DEFAULTS as NODE_DEFAULTS,
8227
+ index$h_NodeConfiguration as NodeConfiguration,
8228
+ index$h_knownChainSpecFromJson as knownChainSpecFromJson,
8229
+ index$h_loadConfig as loadConfig,
8230
+ logger$2 as logger,
8231
+ index$h_parseBootnode as parseBootnode,
8207
8232
  };
8208
8233
  }
8209
8234
 
@@ -8358,7 +8383,7 @@ declare enum NodeType {
8358
8383
  declare class TrieNode {
8359
8384
  constructor(
8360
8385
  /** Exactly 512 bits / 64 bytes */
8361
- public readonly raw: Uint8Array = new Uint8Array(TRIE_NODE_BYTES),
8386
+ public readonly raw: Uint8Array = safeAllocUint8Array(TRIE_NODE_BYTES),
8362
8387
  ) {}
8363
8388
 
8364
8389
  /** Returns the type of the node */
@@ -8990,43 +9015,43 @@ declare const bitLookup = [
8990
9015
  [0b00000000, 8],
8991
9016
  ];
8992
9017
 
8993
- type index$e_BranchNode = BranchNode;
8994
- declare const index$e_BranchNode: typeof BranchNode;
8995
- type index$e_InMemoryTrie = InMemoryTrie;
8996
- declare const index$e_InMemoryTrie: typeof InMemoryTrie;
8997
- type index$e_InputKey = InputKey;
8998
- type index$e_LeafNode = LeafNode;
8999
- declare const index$e_LeafNode: typeof LeafNode;
9000
- type index$e_NodeType = NodeType;
9001
- declare const index$e_NodeType: typeof NodeType;
9002
- type index$e_NodesDb = NodesDb;
9003
- declare const index$e_NodesDb: typeof NodesDb;
9004
- declare const index$e_TRIE_NODE_BYTES: typeof TRIE_NODE_BYTES;
9005
- declare const index$e_TRUNCATED_KEY_BITS: typeof TRUNCATED_KEY_BITS;
9006
- type index$e_TRUNCATED_KEY_BYTES = TRUNCATED_KEY_BYTES;
9007
- type index$e_TraversedPath = TraversedPath;
9008
- declare const index$e_TraversedPath: typeof TraversedPath;
9009
- type index$e_TrieHasher = TrieHasher;
9010
- type index$e_TrieNode = TrieNode;
9011
- declare const index$e_TrieNode: typeof TrieNode;
9012
- type index$e_TrieNodeHash = TrieNodeHash;
9013
- type index$e_TruncatedStateKey = TruncatedStateKey;
9014
- type index$e_ValueHash = ValueHash;
9015
- type index$e_WriteableNodesDb = WriteableNodesDb;
9016
- declare const index$e_WriteableNodesDb: typeof WriteableNodesDb;
9017
- declare const index$e_bitLookup: typeof bitLookup;
9018
- declare const index$e_createSubtreeForBothLeaves: typeof createSubtreeForBothLeaves;
9019
- declare const index$e_findNodeToReplace: typeof findNodeToReplace;
9020
- declare const index$e_findSharedPrefix: typeof findSharedPrefix;
9021
- declare const index$e_getBit: typeof getBit;
9022
- declare const index$e_leafComparator: typeof leafComparator;
9023
- declare const index$e_parseInputKey: typeof parseInputKey;
9024
- declare const index$e_trieInsert: typeof trieInsert;
9025
- declare const index$e_trieStringify: typeof trieStringify;
9026
- declare const index$e_zero: typeof zero;
9027
- declare namespace index$e {
9028
- export { index$e_BranchNode as BranchNode, index$e_InMemoryTrie as InMemoryTrie, index$e_LeafNode as LeafNode, index$e_NodeType as NodeType, index$e_NodesDb as NodesDb, index$e_TRIE_NODE_BYTES as TRIE_NODE_BYTES, index$e_TRUNCATED_KEY_BITS as TRUNCATED_KEY_BITS, index$e_TraversedPath as TraversedPath, index$e_TrieNode as TrieNode, index$e_WriteableNodesDb as WriteableNodesDb, index$e_bitLookup as bitLookup, index$e_createSubtreeForBothLeaves as createSubtreeForBothLeaves, index$e_findNodeToReplace as findNodeToReplace, index$e_findSharedPrefix as findSharedPrefix, index$e_getBit as getBit, index$e_leafComparator as leafComparator, index$e_parseInputKey as parseInputKey, index$e_trieInsert as trieInsert, index$e_trieStringify as trieStringify, index$e_zero as zero };
9029
- export type { index$e_InputKey as InputKey, StateKey$1 as StateKey, index$e_TRUNCATED_KEY_BYTES as TRUNCATED_KEY_BYTES, index$e_TrieHasher as TrieHasher, index$e_TrieNodeHash as TrieNodeHash, index$e_TruncatedStateKey as TruncatedStateKey, index$e_ValueHash as ValueHash };
9018
+ type index$g_BranchNode = BranchNode;
9019
+ declare const index$g_BranchNode: typeof BranchNode;
9020
+ type index$g_InMemoryTrie = InMemoryTrie;
9021
+ declare const index$g_InMemoryTrie: typeof InMemoryTrie;
9022
+ type index$g_InputKey = InputKey;
9023
+ type index$g_LeafNode = LeafNode;
9024
+ declare const index$g_LeafNode: typeof LeafNode;
9025
+ type index$g_NodeType = NodeType;
9026
+ declare const index$g_NodeType: typeof NodeType;
9027
+ type index$g_NodesDb = NodesDb;
9028
+ declare const index$g_NodesDb: typeof NodesDb;
9029
+ declare const index$g_TRIE_NODE_BYTES: typeof TRIE_NODE_BYTES;
9030
+ declare const index$g_TRUNCATED_KEY_BITS: typeof TRUNCATED_KEY_BITS;
9031
+ type index$g_TRUNCATED_KEY_BYTES = TRUNCATED_KEY_BYTES;
9032
+ type index$g_TraversedPath = TraversedPath;
9033
+ declare const index$g_TraversedPath: typeof TraversedPath;
9034
+ type index$g_TrieHasher = TrieHasher;
9035
+ type index$g_TrieNode = TrieNode;
9036
+ declare const index$g_TrieNode: typeof TrieNode;
9037
+ type index$g_TrieNodeHash = TrieNodeHash;
9038
+ type index$g_TruncatedStateKey = TruncatedStateKey;
9039
+ type index$g_ValueHash = ValueHash;
9040
+ type index$g_WriteableNodesDb = WriteableNodesDb;
9041
+ declare const index$g_WriteableNodesDb: typeof WriteableNodesDb;
9042
+ declare const index$g_bitLookup: typeof bitLookup;
9043
+ declare const index$g_createSubtreeForBothLeaves: typeof createSubtreeForBothLeaves;
9044
+ declare const index$g_findNodeToReplace: typeof findNodeToReplace;
9045
+ declare const index$g_findSharedPrefix: typeof findSharedPrefix;
9046
+ declare const index$g_getBit: typeof getBit;
9047
+ declare const index$g_leafComparator: typeof leafComparator;
9048
+ declare const index$g_parseInputKey: typeof parseInputKey;
9049
+ declare const index$g_trieInsert: typeof trieInsert;
9050
+ declare const index$g_trieStringify: typeof trieStringify;
9051
+ declare const index$g_zero: typeof zero;
9052
+ declare namespace index$g {
9053
+ export { index$g_BranchNode as BranchNode, index$g_InMemoryTrie as InMemoryTrie, index$g_LeafNode as LeafNode, index$g_NodeType as NodeType, index$g_NodesDb as NodesDb, index$g_TRIE_NODE_BYTES as TRIE_NODE_BYTES, index$g_TRUNCATED_KEY_BITS as TRUNCATED_KEY_BITS, index$g_TraversedPath as TraversedPath, index$g_TrieNode as TrieNode, index$g_WriteableNodesDb as WriteableNodesDb, index$g_bitLookup as bitLookup, index$g_createSubtreeForBothLeaves as createSubtreeForBothLeaves, index$g_findNodeToReplace as findNodeToReplace, index$g_findSharedPrefix as findSharedPrefix, index$g_getBit as getBit, index$g_leafComparator as leafComparator, index$g_parseInputKey as parseInputKey, index$g_trieInsert as trieInsert, index$g_trieStringify as trieStringify, index$g_zero as zero };
9054
+ export type { index$g_InputKey as InputKey, StateKey$1 as StateKey, index$g_TRUNCATED_KEY_BYTES as TRUNCATED_KEY_BYTES, index$g_TrieHasher as TrieHasher, index$g_TrieNodeHash as TrieNodeHash, index$g_TruncatedStateKey as TruncatedStateKey, index$g_ValueHash as ValueHash };
9030
9055
  }
9031
9056
 
9032
9057
  /**
@@ -9096,21 +9121,6 @@ declare function accumulationOutputComparator(a: AccumulationOutput, b: Accumula
9096
9121
  return Ordering.Equal;
9097
9122
  }
9098
9123
 
9099
- declare const codecWithHash = <T, V, H extends OpaqueHash>(val: Descriptor<T, V>): Descriptor<WithHash<H, T>, V> =>
9100
- Descriptor.withView(
9101
- val.name,
9102
- val.sizeHint,
9103
- (e, elem) => val.encode(e, elem.data),
9104
- (d): WithHash<H, T> => {
9105
- const decoder2 = d.clone();
9106
- const encoded = val.skipEncoded(decoder2);
9107
- const hash = blake2b.hashBytes(encoded);
9108
- return new WithHash(hash.asOpaque(), val.decode(d));
9109
- },
9110
- val.skip,
9111
- val.View,
9112
- );
9113
-
9114
9124
  /**
9115
9125
  * Assignment of particular work report to a core.
9116
9126
  *
@@ -9121,7 +9131,7 @@ declare const codecWithHash = <T, V, H extends OpaqueHash>(val: Descriptor<T, V>
9121
9131
  */
9122
9132
  declare class AvailabilityAssignment extends WithDebug {
9123
9133
  static Codec = codec.Class(AvailabilityAssignment, {
9124
- workReport: codecWithHash(WorkReport.Codec),
9134
+ workReport: WorkReport.Codec,
9125
9135
  timeout: codec.u32.asOpaque<TimeSlot>(),
9126
9136
  });
9127
9137
 
@@ -9131,7 +9141,7 @@ declare class AvailabilityAssignment extends WithDebug {
9131
9141
 
9132
9142
  private constructor(
9133
9143
  /** Work report assigned to a core. */
9134
- public readonly workReport: WithHash<WorkReportHash, WorkReport>,
9144
+ public readonly workReport: WorkReport,
9135
9145
  /** Time slot at which the report becomes obsolete. */
9136
9146
  public readonly timeout: TimeSlot,
9137
9147
  ) {
@@ -9181,6 +9191,11 @@ declare class DisputesRecords {
9181
9191
  return new DisputesRecords(goodSet, badSet, wonkySet, punishSet);
9182
9192
  }
9183
9193
 
9194
+ private readonly goodSetDict: ImmutableHashSet<WorkReportHash>;
9195
+ private readonly badSetDict: ImmutableHashSet<WorkReportHash>;
9196
+ private readonly wonkySetDict: ImmutableHashSet<WorkReportHash>;
9197
+ private readonly punishSetDict: ImmutableHashSet<Ed25519Key>;
9198
+
9184
9199
  private constructor(
9185
9200
  /** `goodSet`: all work-reports hashes which were judged to be correct */
9186
9201
  public readonly goodSet: ImmutableSortedSet<WorkReportHash>,
@@ -9190,7 +9205,21 @@ declare class DisputesRecords {
9190
9205
  public readonly wonkySet: ImmutableSortedSet<WorkReportHash>,
9191
9206
  /** `punishSet`: set of Ed25519 keys representing validators which were found to have misjudged a work-report */
9192
9207
  public readonly punishSet: ImmutableSortedSet<Ed25519Key>,
9193
- ) {}
9208
+ ) {
9209
+ this.goodSetDict = HashSet.from(goodSet.array);
9210
+ this.badSetDict = HashSet.from(badSet.array);
9211
+ this.wonkySetDict = HashSet.from(wonkySet.array);
9212
+ this.punishSetDict = HashSet.from(punishSet.array);
9213
+ }
9214
+
9215
+ public asDictionaries() {
9216
+ return {
9217
+ goodSet: this.goodSetDict,
9218
+ badSet: this.badSetDict,
9219
+ wonkySet: this.wonkySetDict,
9220
+ punishSet: this.punishSetDict,
9221
+ };
9222
+ }
9194
9223
 
9195
9224
  static fromSortedArrays({
9196
9225
  goodSet,
@@ -9216,8 +9245,6 @@ declare function hashComparator<V extends OpaqueHash>(a: V, b: V) {
9216
9245
  return a.compare(b);
9217
9246
  }
9218
9247
 
9219
- // TODO [ToDr] Not sure where these should live yet :(
9220
-
9221
9248
  /**
9222
9249
  * `J`: The maximum sum of dependency items in a work-report.
9223
9250
  *
@@ -9271,61 +9298,279 @@ declare class NotYetAccumulatedReport extends WithDebug {
9271
9298
  }
9272
9299
  }
9273
9300
 
9274
- /** Dictionary entry of services that auto-accumulate every block. */
9275
- declare class AutoAccumulate {
9276
- static Codec = codec.Class(AutoAccumulate, {
9277
- service: codec.u32.asOpaque<ServiceId>(),
9278
- gasLimit: codec.u64.asOpaque<ServiceGas>(),
9279
- });
9280
-
9281
- static create({ service, gasLimit }: CodecRecord<AutoAccumulate>) {
9282
- return new AutoAccumulate(service, gasLimit);
9283
- }
9284
-
9285
- private constructor(
9286
- /** Service id that auto-accumulates. */
9287
- readonly service: ServiceId,
9288
- /** Gas limit for auto-accumulation. */
9289
- readonly gasLimit: ServiceGas,
9290
- ) {}
9291
- }
9292
-
9293
9301
  /**
9294
- * https://graypaper.fluffylabs.dev/#/7e6ff6a/11da0111da01?v=0.6.7
9302
+ * `B_S`: The basic minimum balance which all services require.
9303
+ *
9304
+ * https://graypaper.fluffylabs.dev/#/7e6ff6a/445800445800?v=0.6.7
9295
9305
  */
9296
- declare class PrivilegedServices {
9297
- static Codec = codec.Class(PrivilegedServices, {
9298
- manager: codec.u32.asOpaque<ServiceId>(),
9299
- authManager: codecPerCore(codec.u32.asOpaque<ServiceId>()),
9300
- validatorsManager: codec.u32.asOpaque<ServiceId>(),
9301
- autoAccumulateServices: readonlyArray(codec.sequenceVarLen(AutoAccumulate.Codec)),
9302
- });
9303
-
9304
- static create({ manager, authManager, validatorsManager, autoAccumulateServices }: CodecRecord<PrivilegedServices>) {
9305
- return new PrivilegedServices(manager, authManager, validatorsManager, autoAccumulateServices);
9306
- }
9307
-
9308
- private constructor(
9309
- /**
9310
- * `chi_m`: The first, χm, is the index of the manager service which is
9311
- * the service able to effect an alteration of χ from block to block,
9312
- * as well as bestow services with storage deposit credits.
9313
- * https://graypaper.fluffylabs.dev/#/7e6ff6a/11a40111a801?v=0.6.7
9314
- */
9315
- readonly manager: ServiceId,
9316
- /** `chi_a`: Manages authorization queue one for each core. */
9317
- readonly authManager: PerCore<ServiceId>,
9318
- /** `chi_v`: Managers validator keys. */
9319
- readonly validatorsManager: ServiceId,
9320
- /** `chi_g`: Dictionary of services that auto-accumulate every block with their gas limit. */
9321
- readonly autoAccumulateServices: readonly AutoAccumulate[],
9322
- ) {}
9323
- }
9306
+ declare const BASE_SERVICE_BALANCE = 100n;
9307
+ /**
9308
+ * `B_I`: The additional minimum balance required per item of elective service state.
9309
+ *
9310
+ * https://graypaper.fluffylabs.dev/#/7e6ff6a/445000445000?v=0.6.7
9311
+ */
9312
+ declare const ELECTIVE_ITEM_BALANCE = 10n;
9313
+ /**
9314
+ * `B_L`: The additional minimum balance required per octet of elective service state.
9315
+ *
9316
+ * https://graypaper.fluffylabs.dev/#/7e6ff6a/445400445400?v=0.6.7
9317
+ */
9318
+ declare const ELECTIVE_BYTE_BALANCE = 1n;
9324
9319
 
9325
- declare const SUPER_PEAK_STRING = BytesBlob.blobFromString("peak");
9320
+ declare const zeroSizeHint: SizeHint = {
9321
+ bytes: 0,
9322
+ isExact: true,
9323
+ };
9324
+
9325
+ /** 0-byte read, return given default value */
9326
+ declare const ignoreValueWithDefault = <T>(defaultValue: T) =>
9327
+ Descriptor.new<T>(
9328
+ "ignoreValue",
9329
+ zeroSizeHint,
9330
+ (_e, _v) => {},
9331
+ (_d) => defaultValue,
9332
+ (_s) => {},
9333
+ );
9334
+
9335
+ /** Encode and decode object with leading version number. */
9336
+ declare const codecWithVersion = <T>(val: Descriptor<T>): Descriptor<T> =>
9337
+ Descriptor.new<T>(
9338
+ "withVersion",
9339
+ {
9340
+ bytes: val.sizeHint.bytes + 8,
9341
+ isExact: false,
9342
+ },
9343
+ (e, v) => {
9344
+ e.varU64(0n);
9345
+ val.encode(e, v);
9346
+ },
9347
+ (d) => {
9348
+ const version = d.varU64();
9349
+ if (version !== 0n) {
9350
+ throw new Error("Non-zero version is not supported!");
9351
+ }
9352
+ return val.decode(d);
9353
+ },
9354
+ (s) => {
9355
+ s.varU64();
9356
+ val.skip(s);
9357
+ },
9358
+ );
9359
+
9360
+ /**
9361
+ * Service account details.
9362
+ *
9363
+ * https://graypaper.fluffylabs.dev/#/7e6ff6a/108301108301?v=0.6.7
9364
+ */
9365
+ declare class ServiceAccountInfo extends WithDebug {
9366
+ static Codec = codec.Class(ServiceAccountInfo, {
9367
+ codeHash: codec.bytes(HASH_SIZE).asOpaque<CodeHash>(),
9368
+ balance: codec.u64,
9369
+ accumulateMinGas: codec.u64.convert((x) => x, tryAsServiceGas),
9370
+ onTransferMinGas: codec.u64.convert((x) => x, tryAsServiceGas),
9371
+ storageUtilisationBytes: codec.u64,
9372
+ gratisStorage: codec.u64,
9373
+ storageUtilisationCount: codec.u32,
9374
+ created: codec.u32.convert((x) => x, tryAsTimeSlot),
9375
+ lastAccumulation: codec.u32.convert((x) => x, tryAsTimeSlot),
9376
+ parentService: codec.u32.convert((x) => x, tryAsServiceId),
9377
+ });
9378
+
9379
+ static create(a: CodecRecord<ServiceAccountInfo>) {
9380
+ return new ServiceAccountInfo(
9381
+ a.codeHash,
9382
+ a.balance,
9383
+ a.accumulateMinGas,
9384
+ a.onTransferMinGas,
9385
+ a.storageUtilisationBytes,
9386
+ a.gratisStorage,
9387
+ a.storageUtilisationCount,
9388
+ a.created,
9389
+ a.lastAccumulation,
9390
+ a.parentService,
9391
+ );
9392
+ }
9326
9393
 
9327
- /** Merkle Mountain Range peaks. */
9328
- interface MmrPeaks<H extends OpaqueHash> {
9394
+ /**
9395
+ * `a_t = max(0, BS + BI * a_i + BL * a_o - a_f)`
9396
+ * https://graypaper.fluffylabs.dev/#/7e6ff6a/119e01119e01?v=0.6.7
9397
+ */
9398
+ static calculateThresholdBalance(items: U32, bytes: U64, gratisStorage: U64): U64 {
9399
+ const storageCost =
9400
+ BASE_SERVICE_BALANCE + ELECTIVE_ITEM_BALANCE * BigInt(items) + ELECTIVE_BYTE_BALANCE * bytes - gratisStorage;
9401
+
9402
+ if (storageCost < 0n) {
9403
+ return tryAsU64(0);
9404
+ }
9405
+
9406
+ if (storageCost >= 2n ** 64n) {
9407
+ return tryAsU64(2n ** 64n - 1n);
9408
+ }
9409
+
9410
+ return tryAsU64(storageCost);
9411
+ }
9412
+
9413
+ private constructor(
9414
+ /** `a_c`: Hash of the service code. */
9415
+ public readonly codeHash: CodeHash,
9416
+ /** `a_b`: Current account balance. */
9417
+ public readonly balance: U64,
9418
+ /** `a_g`: Minimal gas required to execute Accumulate entrypoint. */
9419
+ public readonly accumulateMinGas: ServiceGas,
9420
+ /** `a_m`: Minimal gas required to execute On Transfer entrypoint. */
9421
+ public readonly onTransferMinGas: ServiceGas,
9422
+ /** `a_o`: Total number of octets in storage. */
9423
+ public readonly storageUtilisationBytes: U64,
9424
+ /** `a_f`: Cost-free storage. Decreases both storage item count and total byte size. */
9425
+ public readonly gratisStorage: U64,
9426
+ /** `a_i`: Number of items in storage. */
9427
+ public readonly storageUtilisationCount: U32,
9428
+ /** `a_r`: Creation account time slot. */
9429
+ public readonly created: TimeSlot,
9430
+ /** `a_a`: Most recent accumulation time slot. */
9431
+ public readonly lastAccumulation: TimeSlot,
9432
+ /** `a_p`: Parent service ID. */
9433
+ public readonly parentService: ServiceId,
9434
+ ) {
9435
+ super();
9436
+ }
9437
+ }
9438
+
9439
+ declare class PreimageItem extends WithDebug {
9440
+ static Codec = codec.Class(PreimageItem, {
9441
+ hash: codec.bytes(HASH_SIZE).asOpaque<PreimageHash>(),
9442
+ blob: codec.blob,
9443
+ });
9444
+
9445
+ static create({ hash, blob }: CodecRecord<PreimageItem>) {
9446
+ return new PreimageItem(hash, blob);
9447
+ }
9448
+
9449
+ private constructor(
9450
+ readonly hash: PreimageHash,
9451
+ readonly blob: BytesBlob,
9452
+ ) {
9453
+ super();
9454
+ }
9455
+ }
9456
+
9457
+ type StorageKey = Opaque<BytesBlob, "storage key">;
9458
+
9459
+ declare class StorageItem extends WithDebug {
9460
+ static Codec = codec.Class(StorageItem, {
9461
+ key: codec.blob.convert(
9462
+ (i) => i,
9463
+ (o) => asOpaqueType(o),
9464
+ ),
9465
+ value: codec.blob,
9466
+ });
9467
+
9468
+ static create({ key, value }: CodecRecord<StorageItem>) {
9469
+ return new StorageItem(key, value);
9470
+ }
9471
+
9472
+ private constructor(
9473
+ readonly key: StorageKey,
9474
+ readonly value: BytesBlob,
9475
+ ) {
9476
+ super();
9477
+ }
9478
+ }
9479
+
9480
+ declare const MAX_LOOKUP_HISTORY_SLOTS = 3;
9481
+ type LookupHistorySlots = KnownSizeArray<TimeSlot, `0-${typeof MAX_LOOKUP_HISTORY_SLOTS} timeslots`>;
9482
+ declare function tryAsLookupHistorySlots(items: readonly TimeSlot[]): LookupHistorySlots {
9483
+ const knownSize = asKnownSize(items) as LookupHistorySlots;
9484
+ if (knownSize.length > MAX_LOOKUP_HISTORY_SLOTS) {
9485
+ throw new Error(`Lookup history items must contain 0-${MAX_LOOKUP_HISTORY_SLOTS} timeslots.`);
9486
+ }
9487
+ return knownSize;
9488
+ }
9489
+
9490
+ /** https://graypaper.fluffylabs.dev/#/5f542d7/115400115800 */
9491
+ declare class LookupHistoryItem {
9492
+ constructor(
9493
+ public readonly hash: PreimageHash,
9494
+ public readonly length: U32,
9495
+ /**
9496
+ * Preimage availability history as a sequence of time slots.
9497
+ * See PreimageStatus and the following GP fragment for more details.
9498
+ * https://graypaper.fluffylabs.dev/#/5f542d7/11780011a500 */
9499
+ public readonly slots: LookupHistorySlots,
9500
+ ) {}
9501
+
9502
+ static isRequested(item: LookupHistoryItem | LookupHistorySlots): boolean {
9503
+ if ("slots" in item) {
9504
+ return item.slots.length === 0;
9505
+ }
9506
+ return item.length === 0;
9507
+ }
9508
+ }
9509
+
9510
+ /** Dictionary entry of services that auto-accumulate every block. */
9511
+ declare class AutoAccumulate {
9512
+ static Codec = codec.Class(AutoAccumulate, {
9513
+ service: codec.u32.asOpaque<ServiceId>(),
9514
+ gasLimit: codec.u64.asOpaque<ServiceGas>(),
9515
+ });
9516
+
9517
+ static create({ service, gasLimit }: CodecRecord<AutoAccumulate>) {
9518
+ return new AutoAccumulate(service, gasLimit);
9519
+ }
9520
+
9521
+ private constructor(
9522
+ /** Service id that auto-accumulates. */
9523
+ readonly service: ServiceId,
9524
+ /** Gas limit for auto-accumulation. */
9525
+ readonly gasLimit: ServiceGas,
9526
+ ) {}
9527
+ }
9528
+
9529
+ /**
9530
+ * https://graypaper.fluffylabs.dev/#/ab2cdbd/114402114402?v=0.7.2
9531
+ */
9532
+ declare class PrivilegedServices {
9533
+ /** https://graypaper.fluffylabs.dev/#/ab2cdbd/3bbd023bcb02?v=0.7.2 */
9534
+ static Codec = codec.Class(PrivilegedServices, {
9535
+ manager: codec.u32.asOpaque<ServiceId>(),
9536
+ assigners: codecPerCore(codec.u32.asOpaque<ServiceId>()),
9537
+ delegator: codec.u32.asOpaque<ServiceId>(),
9538
+ registrar: Compatibility.isGreaterOrEqual(GpVersion.V0_7_1)
9539
+ ? codec.u32.asOpaque<ServiceId>()
9540
+ : ignoreValueWithDefault(tryAsServiceId(2 ** 32 - 1)),
9541
+ autoAccumulateServices: readonlyArray(codec.sequenceVarLen(AutoAccumulate.Codec)),
9542
+ });
9543
+
9544
+ static create(a: CodecRecord<PrivilegedServices>) {
9545
+ return new PrivilegedServices(a.manager, a.delegator, a.registrar, a.assigners, a.autoAccumulateServices);
9546
+ }
9547
+
9548
+ private constructor(
9549
+ /**
9550
+ * `χ_M`: Manages alteration of χ from block to block,
9551
+ * as well as bestow services with storage deposit credits.
9552
+ * https://graypaper.fluffylabs.dev/#/ab2cdbd/111502111902?v=0.7.2
9553
+ */
9554
+ readonly manager: ServiceId,
9555
+ /** `χ_V`: Managers validator keys. */
9556
+ readonly delegator: ServiceId,
9557
+ /**
9558
+ * `χ_R`: Manages the creation of services in protected range.
9559
+ *
9560
+ * https://graypaper.fluffylabs.dev/#/ab2cdbd/111b02111d02?v=0.7.2
9561
+ */
9562
+ readonly registrar: ServiceId,
9563
+ /** `χ_A`: Manages authorization queue one for each core. */
9564
+ readonly assigners: PerCore<ServiceId>,
9565
+ /** `χ_Z`: Dictionary of services that auto-accumulate every block with their gas limit. */
9566
+ readonly autoAccumulateServices: readonly AutoAccumulate[],
9567
+ ) {}
9568
+ }
9569
+
9570
+ declare const SUPER_PEAK_STRING = BytesBlob.blobFromString("peak");
9571
+
9572
+ /** Merkle Mountain Range peaks. */
9573
+ interface MmrPeaks<H extends OpaqueHash> {
9329
9574
  /**
9330
9575
  * Peaks at particular positions.
9331
9576
  *
@@ -9468,16 +9713,16 @@ declare class Mountain<H extends OpaqueHash> {
9468
9713
  }
9469
9714
  }
9470
9715
 
9471
- type index$d_MerkleMountainRange<H extends OpaqueHash> = MerkleMountainRange<H>;
9472
- declare const index$d_MerkleMountainRange: typeof MerkleMountainRange;
9473
- type index$d_MmrHasher<H extends OpaqueHash> = MmrHasher<H>;
9474
- type index$d_MmrPeaks<H extends OpaqueHash> = MmrPeaks<H>;
9475
- type index$d_Mountain<H extends OpaqueHash> = Mountain<H>;
9476
- declare const index$d_Mountain: typeof Mountain;
9477
- declare const index$d_SUPER_PEAK_STRING: typeof SUPER_PEAK_STRING;
9478
- declare namespace index$d {
9479
- export { index$d_MerkleMountainRange as MerkleMountainRange, index$d_Mountain as Mountain, index$d_SUPER_PEAK_STRING as SUPER_PEAK_STRING };
9480
- export type { index$d_MmrHasher as MmrHasher, index$d_MmrPeaks as MmrPeaks };
9716
+ type index$f_MerkleMountainRange<H extends OpaqueHash> = MerkleMountainRange<H>;
9717
+ declare const index$f_MerkleMountainRange: typeof MerkleMountainRange;
9718
+ type index$f_MmrHasher<H extends OpaqueHash> = MmrHasher<H>;
9719
+ type index$f_MmrPeaks<H extends OpaqueHash> = MmrPeaks<H>;
9720
+ type index$f_Mountain<H extends OpaqueHash> = Mountain<H>;
9721
+ declare const index$f_Mountain: typeof Mountain;
9722
+ declare const index$f_SUPER_PEAK_STRING: typeof SUPER_PEAK_STRING;
9723
+ declare namespace index$f {
9724
+ export { index$f_MerkleMountainRange as MerkleMountainRange, index$f_Mountain as Mountain, index$f_SUPER_PEAK_STRING as SUPER_PEAK_STRING };
9725
+ export type { index$f_MmrHasher as MmrHasher, index$f_MmrPeaks as MmrPeaks };
9481
9726
  }
9482
9727
 
9483
9728
  /**
@@ -9748,206 +9993,22 @@ declare class SafroleData {
9748
9993
  epochRoot: codec.bytes(BANDERSNATCH_RING_ROOT_BYTES).asOpaque<BandersnatchRingRoot>(),
9749
9994
  sealingKeySeries: SafroleSealingKeysData.Codec,
9750
9995
  ticketsAccumulator: readonlyArray(codec.sequenceVarLen(Ticket.Codec)).convert(seeThrough, asKnownSize),
9751
- });
9752
-
9753
- static create({ nextValidatorData, epochRoot, sealingKeySeries, ticketsAccumulator }: CodecRecord<SafroleData>) {
9754
- return new SafroleData(nextValidatorData, epochRoot, sealingKeySeries, ticketsAccumulator);
9755
- }
9756
-
9757
- private constructor(
9758
- /** gamma_k */
9759
- public readonly nextValidatorData: PerValidator<ValidatorData>,
9760
- /** gamma_z */
9761
- public readonly epochRoot: BandersnatchRingRoot,
9762
- /** gamma_s */
9763
- public readonly sealingKeySeries: SafroleSealingKeys,
9764
- /** gamma_a */
9765
- public readonly ticketsAccumulator: KnownSizeArray<Ticket, "0...EpochLength">,
9766
- ) {}
9767
- }
9768
-
9769
- /**
9770
- * `B_S`: The basic minimum balance which all services require.
9771
- *
9772
- * https://graypaper.fluffylabs.dev/#/7e6ff6a/445800445800?v=0.6.7
9773
- */
9774
- declare const BASE_SERVICE_BALANCE = 100n;
9775
- /**
9776
- * `B_I`: The additional minimum balance required per item of elective service state.
9777
- *
9778
- * https://graypaper.fluffylabs.dev/#/7e6ff6a/445000445000?v=0.6.7
9779
- */
9780
- declare const ELECTIVE_ITEM_BALANCE = 10n;
9781
- /**
9782
- * `B_L`: The additional minimum balance required per octet of elective service state.
9783
- *
9784
- * https://graypaper.fluffylabs.dev/#/7e6ff6a/445400445400?v=0.6.7
9785
- */
9786
- declare const ELECTIVE_BYTE_BALANCE = 1n;
9787
-
9788
- declare const zeroSizeHint: SizeHint = {
9789
- bytes: 0,
9790
- isExact: true,
9791
- };
9792
-
9793
- /** 0-byte read, return given default value */
9794
- declare const ignoreValueWithDefault = <T>(defaultValue: T) =>
9795
- Descriptor.new<T>(
9796
- "ignoreValue",
9797
- zeroSizeHint,
9798
- (_e, _v) => {},
9799
- (_d) => defaultValue,
9800
- (_s) => {},
9801
- );
9802
-
9803
- /**
9804
- * Service account details.
9805
- *
9806
- * https://graypaper.fluffylabs.dev/#/7e6ff6a/108301108301?v=0.6.7
9807
- */
9808
- declare class ServiceAccountInfo extends WithDebug {
9809
- static Codec = codec.Class(ServiceAccountInfo, {
9810
- codeHash: codec.bytes(HASH_SIZE).asOpaque<CodeHash>(),
9811
- balance: codec.u64,
9812
- accumulateMinGas: codec.u64.convert((x) => x, tryAsServiceGas),
9813
- onTransferMinGas: codec.u64.convert((x) => x, tryAsServiceGas),
9814
- storageUtilisationBytes: codec.u64,
9815
- gratisStorage: codec.u64,
9816
- storageUtilisationCount: codec.u32,
9817
- created: codec.u32.convert((x) => x, tryAsTimeSlot),
9818
- lastAccumulation: codec.u32.convert((x) => x, tryAsTimeSlot),
9819
- parentService: codec.u32.convert((x) => x, tryAsServiceId),
9820
- });
9821
-
9822
- static create(a: CodecRecord<ServiceAccountInfo>) {
9823
- return new ServiceAccountInfo(
9824
- a.codeHash,
9825
- a.balance,
9826
- a.accumulateMinGas,
9827
- a.onTransferMinGas,
9828
- a.storageUtilisationBytes,
9829
- a.gratisStorage,
9830
- a.storageUtilisationCount,
9831
- a.created,
9832
- a.lastAccumulation,
9833
- a.parentService,
9834
- );
9835
- }
9836
-
9837
- /**
9838
- * `a_t = max(0, BS + BI * a_i + BL * a_o - a_f)`
9839
- * https://graypaper.fluffylabs.dev/#/7e6ff6a/119e01119e01?v=0.6.7
9840
- */
9841
- static calculateThresholdBalance(items: U32, bytes: U64, gratisStorage: U64): U64 {
9842
- const storageCost =
9843
- BASE_SERVICE_BALANCE + ELECTIVE_ITEM_BALANCE * BigInt(items) + ELECTIVE_BYTE_BALANCE * bytes - gratisStorage;
9844
-
9845
- if (storageCost < 0n) {
9846
- return tryAsU64(0);
9847
- }
9848
-
9849
- if (storageCost >= 2n ** 64n) {
9850
- return tryAsU64(2n ** 64n - 1n);
9851
- }
9852
-
9853
- return tryAsU64(storageCost);
9854
- }
9855
-
9856
- private constructor(
9857
- /** `a_c`: Hash of the service code. */
9858
- public readonly codeHash: CodeHash,
9859
- /** `a_b`: Current account balance. */
9860
- public readonly balance: U64,
9861
- /** `a_g`: Minimal gas required to execute Accumulate entrypoint. */
9862
- public readonly accumulateMinGas: ServiceGas,
9863
- /** `a_m`: Minimal gas required to execute On Transfer entrypoint. */
9864
- public readonly onTransferMinGas: ServiceGas,
9865
- /** `a_o`: Total number of octets in storage. */
9866
- public readonly storageUtilisationBytes: U64,
9867
- /** `a_f`: Cost-free storage. Decreases both storage item count and total byte size. */
9868
- public readonly gratisStorage: U64,
9869
- /** `a_i`: Number of items in storage. */
9870
- public readonly storageUtilisationCount: U32,
9871
- /** `a_r`: Creation account time slot. */
9872
- public readonly created: TimeSlot,
9873
- /** `a_a`: Most recent accumulation time slot. */
9874
- public readonly lastAccumulation: TimeSlot,
9875
- /** `a_p`: Parent service ID. */
9876
- public readonly parentService: ServiceId,
9877
- ) {
9878
- super();
9879
- }
9880
- }
9881
-
9882
- declare class PreimageItem extends WithDebug {
9883
- static Codec = codec.Class(PreimageItem, {
9884
- hash: codec.bytes(HASH_SIZE).asOpaque<PreimageHash>(),
9885
- blob: codec.blob,
9886
- });
9887
-
9888
- static create({ hash, blob }: CodecRecord<PreimageItem>) {
9889
- return new PreimageItem(hash, blob);
9890
- }
9891
-
9892
- private constructor(
9893
- readonly hash: PreimageHash,
9894
- readonly blob: BytesBlob,
9895
- ) {
9896
- super();
9897
- }
9898
- }
9899
-
9900
- type StorageKey = Opaque<BytesBlob, "storage key">;
9901
-
9902
- declare class StorageItem extends WithDebug {
9903
- static Codec = codec.Class(StorageItem, {
9904
- key: codec.blob.convert(
9905
- (i) => i,
9906
- (o) => asOpaqueType(o),
9907
- ),
9908
- value: codec.blob,
9909
- });
9910
-
9911
- static create({ key, value }: CodecRecord<StorageItem>) {
9912
- return new StorageItem(key, value);
9913
- }
9914
-
9915
- private constructor(
9916
- readonly key: StorageKey,
9917
- readonly value: BytesBlob,
9918
- ) {
9919
- super();
9920
- }
9921
- }
9922
-
9923
- declare const MAX_LOOKUP_HISTORY_SLOTS = 3;
9924
- type LookupHistorySlots = KnownSizeArray<TimeSlot, `0-${typeof MAX_LOOKUP_HISTORY_SLOTS} timeslots`>;
9925
- declare function tryAsLookupHistorySlots(items: readonly TimeSlot[]): LookupHistorySlots {
9926
- const knownSize = asKnownSize(items) as LookupHistorySlots;
9927
- if (knownSize.length > MAX_LOOKUP_HISTORY_SLOTS) {
9928
- throw new Error(`Lookup history items must contain 0-${MAX_LOOKUP_HISTORY_SLOTS} timeslots.`);
9929
- }
9930
- return knownSize;
9931
- }
9932
-
9933
- /** https://graypaper.fluffylabs.dev/#/5f542d7/115400115800 */
9934
- declare class LookupHistoryItem {
9935
- constructor(
9936
- public readonly hash: PreimageHash,
9937
- public readonly length: U32,
9938
- /**
9939
- * Preimage availability history as a sequence of time slots.
9940
- * See PreimageStatus and the following GP fragment for more details.
9941
- * https://graypaper.fluffylabs.dev/#/5f542d7/11780011a500 */
9942
- public readonly slots: LookupHistorySlots,
9943
- ) {}
9996
+ });
9944
9997
 
9945
- static isRequested(item: LookupHistoryItem | LookupHistorySlots): boolean {
9946
- if ("slots" in item) {
9947
- return item.slots.length === 0;
9948
- }
9949
- return item.length === 0;
9998
+ static create({ nextValidatorData, epochRoot, sealingKeySeries, ticketsAccumulator }: CodecRecord<SafroleData>) {
9999
+ return new SafroleData(nextValidatorData, epochRoot, sealingKeySeries, ticketsAccumulator);
9950
10000
  }
10001
+
10002
+ private constructor(
10003
+ /** gamma_k */
10004
+ public readonly nextValidatorData: PerValidator<ValidatorData>,
10005
+ /** gamma_z */
10006
+ public readonly epochRoot: BandersnatchRingRoot,
10007
+ /** gamma_s */
10008
+ public readonly sealingKeySeries: SafroleSealingKeys,
10009
+ /** gamma_a */
10010
+ public readonly ticketsAccumulator: KnownSizeArray<Ticket, "0...EpochLength">,
10011
+ ) {}
9951
10012
  }
9952
10013
 
9953
10014
  declare const codecServiceId: Descriptor<ServiceId> =
@@ -11124,8 +11185,9 @@ declare class InMemoryState extends WithDebug implements State, EnumerableState
11124
11185
  epochRoot: Bytes.zero(BANDERSNATCH_RING_ROOT_BYTES).asOpaque(),
11125
11186
  privilegedServices: PrivilegedServices.create({
11126
11187
  manager: tryAsServiceId(0),
11127
- authManager: tryAsPerCore(new Array(spec.coresCount).fill(tryAsServiceId(0)), spec),
11128
- validatorsManager: tryAsServiceId(0),
11188
+ assigners: tryAsPerCore(new Array(spec.coresCount).fill(tryAsServiceId(0)), spec),
11189
+ delegator: tryAsServiceId(0),
11190
+ registrar: tryAsServiceId(MAX_VALUE),
11129
11191
  autoAccumulateServices: [],
11130
11192
  }),
11131
11193
  accumulationOutputLog: SortedArray.fromArray(accumulationOutputComparator, []),
@@ -11175,103 +11237,103 @@ type FieldNames<T> = {
11175
11237
  [K in keyof T]: T[K] extends Function ? never : K;
11176
11238
  }[keyof T];
11177
11239
 
11178
- type index$c_AccumulationOutput = AccumulationOutput;
11179
- declare const index$c_AccumulationOutput: typeof AccumulationOutput;
11180
- type index$c_AutoAccumulate = AutoAccumulate;
11181
- declare const index$c_AutoAccumulate: typeof AutoAccumulate;
11182
- type index$c_AvailabilityAssignment = AvailabilityAssignment;
11183
- declare const index$c_AvailabilityAssignment: typeof AvailabilityAssignment;
11184
- declare const index$c_BASE_SERVICE_BALANCE: typeof BASE_SERVICE_BALANCE;
11185
- type index$c_BlockState = BlockState;
11186
- declare const index$c_BlockState: typeof BlockState;
11187
- type index$c_BlocksState = BlocksState;
11188
- type index$c_CoreStatistics = CoreStatistics;
11189
- declare const index$c_CoreStatistics: typeof CoreStatistics;
11190
- type index$c_DisputesRecords = DisputesRecords;
11191
- declare const index$c_DisputesRecords: typeof DisputesRecords;
11192
- declare const index$c_ELECTIVE_BYTE_BALANCE: typeof ELECTIVE_BYTE_BALANCE;
11193
- declare const index$c_ELECTIVE_ITEM_BALANCE: typeof ELECTIVE_ITEM_BALANCE;
11194
- type index$c_ENTROPY_ENTRIES = ENTROPY_ENTRIES;
11195
- type index$c_EnumerableState = EnumerableState;
11196
- type index$c_FieldNames<T> = FieldNames<T>;
11197
- type index$c_InMemoryService = InMemoryService;
11198
- declare const index$c_InMemoryService: typeof InMemoryService;
11199
- type index$c_InMemoryState = InMemoryState;
11200
- declare const index$c_InMemoryState: typeof InMemoryState;
11201
- type index$c_InMemoryStateFields = InMemoryStateFields;
11202
- type index$c_LookupHistoryItem = LookupHistoryItem;
11203
- declare const index$c_LookupHistoryItem: typeof LookupHistoryItem;
11204
- type index$c_LookupHistorySlots = LookupHistorySlots;
11205
- declare const index$c_MAX_LOOKUP_HISTORY_SLOTS: typeof MAX_LOOKUP_HISTORY_SLOTS;
11206
- type index$c_MAX_RECENT_HISTORY = MAX_RECENT_HISTORY;
11207
- type index$c_PerCore<T> = PerCore<T>;
11208
- type index$c_PreimageItem = PreimageItem;
11209
- declare const index$c_PreimageItem: typeof PreimageItem;
11210
- type index$c_PrivilegedServices = PrivilegedServices;
11211
- declare const index$c_PrivilegedServices: typeof PrivilegedServices;
11212
- type index$c_RecentBlocks = RecentBlocks;
11213
- declare const index$c_RecentBlocks: typeof RecentBlocks;
11214
- type index$c_RecentBlocksHistory = RecentBlocksHistory;
11215
- declare const index$c_RecentBlocksHistory: typeof RecentBlocksHistory;
11216
- type index$c_SafroleData = SafroleData;
11217
- declare const index$c_SafroleData: typeof SafroleData;
11218
- type index$c_SafroleSealingKeys = SafroleSealingKeys;
11219
- type index$c_SafroleSealingKeysData = SafroleSealingKeysData;
11220
- declare const index$c_SafroleSealingKeysData: typeof SafroleSealingKeysData;
11221
- type index$c_SafroleSealingKeysKind = SafroleSealingKeysKind;
11222
- declare const index$c_SafroleSealingKeysKind: typeof SafroleSealingKeysKind;
11223
- type index$c_Service = Service;
11224
- type index$c_ServiceAccountInfo = ServiceAccountInfo;
11225
- declare const index$c_ServiceAccountInfo: typeof ServiceAccountInfo;
11226
- type index$c_ServiceData = ServiceData;
11227
- type index$c_ServiceEntries = ServiceEntries;
11228
- type index$c_ServiceStatistics = ServiceStatistics;
11229
- declare const index$c_ServiceStatistics: typeof ServiceStatistics;
11230
- type index$c_ServicesUpdate = ServicesUpdate;
11231
- type index$c_State = State;
11232
- type index$c_StatisticsData = StatisticsData;
11233
- declare const index$c_StatisticsData: typeof StatisticsData;
11234
- type index$c_StorageItem = StorageItem;
11235
- declare const index$c_StorageItem: typeof StorageItem;
11236
- type index$c_StorageKey = StorageKey;
11237
- type index$c_UpdateError = UpdateError;
11238
- declare const index$c_UpdateError: typeof UpdateError;
11239
- type index$c_UpdatePreimage = UpdatePreimage;
11240
- declare const index$c_UpdatePreimage: typeof UpdatePreimage;
11241
- type index$c_UpdatePreimageKind = UpdatePreimageKind;
11242
- declare const index$c_UpdatePreimageKind: typeof UpdatePreimageKind;
11243
- type index$c_UpdateService = UpdateService;
11244
- declare const index$c_UpdateService: typeof UpdateService;
11245
- type index$c_UpdateServiceKind = UpdateServiceKind;
11246
- declare const index$c_UpdateServiceKind: typeof UpdateServiceKind;
11247
- type index$c_UpdateStorage = UpdateStorage;
11248
- declare const index$c_UpdateStorage: typeof UpdateStorage;
11249
- type index$c_UpdateStorageKind = UpdateStorageKind;
11250
- declare const index$c_UpdateStorageKind: typeof UpdateStorageKind;
11251
- type index$c_VALIDATOR_META_BYTES = VALIDATOR_META_BYTES;
11252
- type index$c_ValidatorData = ValidatorData;
11253
- declare const index$c_ValidatorData: typeof ValidatorData;
11254
- type index$c_ValidatorStatistics = ValidatorStatistics;
11255
- declare const index$c_ValidatorStatistics: typeof ValidatorStatistics;
11256
- declare const index$c_accumulationOutputComparator: typeof accumulationOutputComparator;
11257
- declare const index$c_codecBandersnatchKey: typeof codecBandersnatchKey;
11258
- declare const index$c_codecPerCore: typeof codecPerCore;
11259
- declare const index$c_codecServiceId: typeof codecServiceId;
11260
- declare const index$c_codecVarGas: typeof codecVarGas;
11261
- declare const index$c_codecVarU16: typeof codecVarU16;
11262
- declare const index$c_codecWithHash: typeof codecWithHash;
11263
- declare const index$c_hashComparator: typeof hashComparator;
11264
- declare const index$c_ignoreValueWithDefault: typeof ignoreValueWithDefault;
11265
- declare const index$c_serviceDataCodec: typeof serviceDataCodec;
11266
- declare const index$c_serviceEntriesCodec: typeof serviceEntriesCodec;
11267
- declare const index$c_sortedSetCodec: typeof sortedSetCodec;
11268
- declare const index$c_tryAsLookupHistorySlots: typeof tryAsLookupHistorySlots;
11269
- declare const index$c_tryAsPerCore: typeof tryAsPerCore;
11270
- declare const index$c_workReportsSortedSetCodec: typeof workReportsSortedSetCodec;
11271
- declare const index$c_zeroSizeHint: typeof zeroSizeHint;
11272
- declare namespace index$c {
11273
- export { index$c_AccumulationOutput as AccumulationOutput, index$c_AutoAccumulate as AutoAccumulate, index$c_AvailabilityAssignment as AvailabilityAssignment, index$c_BASE_SERVICE_BALANCE as BASE_SERVICE_BALANCE, index$c_BlockState as BlockState, index$c_CoreStatistics as CoreStatistics, index$c_DisputesRecords as DisputesRecords, index$c_ELECTIVE_BYTE_BALANCE as ELECTIVE_BYTE_BALANCE, index$c_ELECTIVE_ITEM_BALANCE as ELECTIVE_ITEM_BALANCE, index$c_InMemoryService as InMemoryService, index$c_InMemoryState as InMemoryState, index$c_LookupHistoryItem as LookupHistoryItem, index$c_MAX_LOOKUP_HISTORY_SLOTS as MAX_LOOKUP_HISTORY_SLOTS, index$c_PreimageItem as PreimageItem, index$c_PrivilegedServices as PrivilegedServices, index$c_RecentBlocks as RecentBlocks, index$c_RecentBlocksHistory as RecentBlocksHistory, index$c_SafroleData as SafroleData, index$c_SafroleSealingKeysData as SafroleSealingKeysData, index$c_SafroleSealingKeysKind as SafroleSealingKeysKind, index$c_ServiceAccountInfo as ServiceAccountInfo, index$c_ServiceStatistics as ServiceStatistics, index$c_StatisticsData as StatisticsData, index$c_StorageItem as StorageItem, index$c_UpdateError as UpdateError, index$c_UpdatePreimage as UpdatePreimage, index$c_UpdatePreimageKind as UpdatePreimageKind, index$c_UpdateService as UpdateService, index$c_UpdateServiceKind as UpdateServiceKind, index$c_UpdateStorage as UpdateStorage, index$c_UpdateStorageKind as UpdateStorageKind, index$c_ValidatorData as ValidatorData, index$c_ValidatorStatistics as ValidatorStatistics, index$c_accumulationOutputComparator as accumulationOutputComparator, index$c_codecBandersnatchKey as codecBandersnatchKey, index$c_codecPerCore as codecPerCore, index$c_codecServiceId as codecServiceId, index$c_codecVarGas as codecVarGas, index$c_codecVarU16 as codecVarU16, index$c_codecWithHash as codecWithHash, index$c_hashComparator as hashComparator, index$c_ignoreValueWithDefault as ignoreValueWithDefault, index$c_serviceDataCodec as serviceDataCodec, index$c_serviceEntriesCodec as serviceEntriesCodec, index$c_sortedSetCodec as sortedSetCodec, index$c_tryAsLookupHistorySlots as tryAsLookupHistorySlots, index$c_tryAsPerCore as tryAsPerCore, index$c_workReportsSortedSetCodec as workReportsSortedSetCodec, index$c_zeroSizeHint as zeroSizeHint };
11274
- export type { index$c_BlocksState as BlocksState, index$c_ENTROPY_ENTRIES as ENTROPY_ENTRIES, index$c_EnumerableState as EnumerableState, index$c_FieldNames as FieldNames, index$c_InMemoryStateFields as InMemoryStateFields, index$c_LookupHistorySlots as LookupHistorySlots, index$c_MAX_RECENT_HISTORY as MAX_RECENT_HISTORY, index$c_PerCore as PerCore, index$c_SafroleSealingKeys as SafroleSealingKeys, index$c_Service as Service, index$c_ServiceData as ServiceData, index$c_ServiceEntries as ServiceEntries, index$c_ServicesUpdate as ServicesUpdate, index$c_State as State, index$c_StorageKey as StorageKey, index$c_VALIDATOR_META_BYTES as VALIDATOR_META_BYTES };
11240
+ type index$e_AccumulationOutput = AccumulationOutput;
11241
+ declare const index$e_AccumulationOutput: typeof AccumulationOutput;
11242
+ type index$e_AutoAccumulate = AutoAccumulate;
11243
+ declare const index$e_AutoAccumulate: typeof AutoAccumulate;
11244
+ type index$e_AvailabilityAssignment = AvailabilityAssignment;
11245
+ declare const index$e_AvailabilityAssignment: typeof AvailabilityAssignment;
11246
+ declare const index$e_BASE_SERVICE_BALANCE: typeof BASE_SERVICE_BALANCE;
11247
+ type index$e_BlockState = BlockState;
11248
+ declare const index$e_BlockState: typeof BlockState;
11249
+ type index$e_BlocksState = BlocksState;
11250
+ type index$e_CoreStatistics = CoreStatistics;
11251
+ declare const index$e_CoreStatistics: typeof CoreStatistics;
11252
+ type index$e_DisputesRecords = DisputesRecords;
11253
+ declare const index$e_DisputesRecords: typeof DisputesRecords;
11254
+ declare const index$e_ELECTIVE_BYTE_BALANCE: typeof ELECTIVE_BYTE_BALANCE;
11255
+ declare const index$e_ELECTIVE_ITEM_BALANCE: typeof ELECTIVE_ITEM_BALANCE;
11256
+ type index$e_ENTROPY_ENTRIES = ENTROPY_ENTRIES;
11257
+ type index$e_EnumerableState = EnumerableState;
11258
+ type index$e_FieldNames<T> = FieldNames<T>;
11259
+ type index$e_InMemoryService = InMemoryService;
11260
+ declare const index$e_InMemoryService: typeof InMemoryService;
11261
+ type index$e_InMemoryState = InMemoryState;
11262
+ declare const index$e_InMemoryState: typeof InMemoryState;
11263
+ type index$e_InMemoryStateFields = InMemoryStateFields;
11264
+ type index$e_LookupHistoryItem = LookupHistoryItem;
11265
+ declare const index$e_LookupHistoryItem: typeof LookupHistoryItem;
11266
+ type index$e_LookupHistorySlots = LookupHistorySlots;
11267
+ declare const index$e_MAX_LOOKUP_HISTORY_SLOTS: typeof MAX_LOOKUP_HISTORY_SLOTS;
11268
+ type index$e_MAX_RECENT_HISTORY = MAX_RECENT_HISTORY;
11269
+ type index$e_PerCore<T> = PerCore<T>;
11270
+ type index$e_PreimageItem = PreimageItem;
11271
+ declare const index$e_PreimageItem: typeof PreimageItem;
11272
+ type index$e_PrivilegedServices = PrivilegedServices;
11273
+ declare const index$e_PrivilegedServices: typeof PrivilegedServices;
11274
+ type index$e_RecentBlocks = RecentBlocks;
11275
+ declare const index$e_RecentBlocks: typeof RecentBlocks;
11276
+ type index$e_RecentBlocksHistory = RecentBlocksHistory;
11277
+ declare const index$e_RecentBlocksHistory: typeof RecentBlocksHistory;
11278
+ type index$e_SafroleData = SafroleData;
11279
+ declare const index$e_SafroleData: typeof SafroleData;
11280
+ type index$e_SafroleSealingKeys = SafroleSealingKeys;
11281
+ type index$e_SafroleSealingKeysData = SafroleSealingKeysData;
11282
+ declare const index$e_SafroleSealingKeysData: typeof SafroleSealingKeysData;
11283
+ type index$e_SafroleSealingKeysKind = SafroleSealingKeysKind;
11284
+ declare const index$e_SafroleSealingKeysKind: typeof SafroleSealingKeysKind;
11285
+ type index$e_Service = Service;
11286
+ type index$e_ServiceAccountInfo = ServiceAccountInfo;
11287
+ declare const index$e_ServiceAccountInfo: typeof ServiceAccountInfo;
11288
+ type index$e_ServiceData = ServiceData;
11289
+ type index$e_ServiceEntries = ServiceEntries;
11290
+ type index$e_ServiceStatistics = ServiceStatistics;
11291
+ declare const index$e_ServiceStatistics: typeof ServiceStatistics;
11292
+ type index$e_ServicesUpdate = ServicesUpdate;
11293
+ type index$e_State = State;
11294
+ type index$e_StatisticsData = StatisticsData;
11295
+ declare const index$e_StatisticsData: typeof StatisticsData;
11296
+ type index$e_StorageItem = StorageItem;
11297
+ declare const index$e_StorageItem: typeof StorageItem;
11298
+ type index$e_StorageKey = StorageKey;
11299
+ type index$e_UpdateError = UpdateError;
11300
+ declare const index$e_UpdateError: typeof UpdateError;
11301
+ type index$e_UpdatePreimage = UpdatePreimage;
11302
+ declare const index$e_UpdatePreimage: typeof UpdatePreimage;
11303
+ type index$e_UpdatePreimageKind = UpdatePreimageKind;
11304
+ declare const index$e_UpdatePreimageKind: typeof UpdatePreimageKind;
11305
+ type index$e_UpdateService = UpdateService;
11306
+ declare const index$e_UpdateService: typeof UpdateService;
11307
+ type index$e_UpdateServiceKind = UpdateServiceKind;
11308
+ declare const index$e_UpdateServiceKind: typeof UpdateServiceKind;
11309
+ type index$e_UpdateStorage = UpdateStorage;
11310
+ declare const index$e_UpdateStorage: typeof UpdateStorage;
11311
+ type index$e_UpdateStorageKind = UpdateStorageKind;
11312
+ declare const index$e_UpdateStorageKind: typeof UpdateStorageKind;
11313
+ type index$e_VALIDATOR_META_BYTES = VALIDATOR_META_BYTES;
11314
+ type index$e_ValidatorData = ValidatorData;
11315
+ declare const index$e_ValidatorData: typeof ValidatorData;
11316
+ type index$e_ValidatorStatistics = ValidatorStatistics;
11317
+ declare const index$e_ValidatorStatistics: typeof ValidatorStatistics;
11318
+ declare const index$e_accumulationOutputComparator: typeof accumulationOutputComparator;
11319
+ declare const index$e_codecBandersnatchKey: typeof codecBandersnatchKey;
11320
+ declare const index$e_codecPerCore: typeof codecPerCore;
11321
+ declare const index$e_codecServiceId: typeof codecServiceId;
11322
+ declare const index$e_codecVarGas: typeof codecVarGas;
11323
+ declare const index$e_codecVarU16: typeof codecVarU16;
11324
+ declare const index$e_codecWithVersion: typeof codecWithVersion;
11325
+ declare const index$e_hashComparator: typeof hashComparator;
11326
+ declare const index$e_ignoreValueWithDefault: typeof ignoreValueWithDefault;
11327
+ declare const index$e_serviceDataCodec: typeof serviceDataCodec;
11328
+ declare const index$e_serviceEntriesCodec: typeof serviceEntriesCodec;
11329
+ declare const index$e_sortedSetCodec: typeof sortedSetCodec;
11330
+ declare const index$e_tryAsLookupHistorySlots: typeof tryAsLookupHistorySlots;
11331
+ declare const index$e_tryAsPerCore: typeof tryAsPerCore;
11332
+ declare const index$e_workReportsSortedSetCodec: typeof workReportsSortedSetCodec;
11333
+ declare const index$e_zeroSizeHint: typeof zeroSizeHint;
11334
+ declare namespace index$e {
11335
+ export { index$e_AccumulationOutput as AccumulationOutput, index$e_AutoAccumulate as AutoAccumulate, index$e_AvailabilityAssignment as AvailabilityAssignment, index$e_BASE_SERVICE_BALANCE as BASE_SERVICE_BALANCE, index$e_BlockState as BlockState, index$e_CoreStatistics as CoreStatistics, index$e_DisputesRecords as DisputesRecords, index$e_ELECTIVE_BYTE_BALANCE as ELECTIVE_BYTE_BALANCE, index$e_ELECTIVE_ITEM_BALANCE as ELECTIVE_ITEM_BALANCE, index$e_InMemoryService as InMemoryService, index$e_InMemoryState as InMemoryState, index$e_LookupHistoryItem as LookupHistoryItem, index$e_MAX_LOOKUP_HISTORY_SLOTS as MAX_LOOKUP_HISTORY_SLOTS, index$e_PreimageItem as PreimageItem, index$e_PrivilegedServices as PrivilegedServices, index$e_RecentBlocks as RecentBlocks, index$e_RecentBlocksHistory as RecentBlocksHistory, index$e_SafroleData as SafroleData, index$e_SafroleSealingKeysData as SafroleSealingKeysData, index$e_SafroleSealingKeysKind as SafroleSealingKeysKind, index$e_ServiceAccountInfo as ServiceAccountInfo, index$e_ServiceStatistics as ServiceStatistics, index$e_StatisticsData as StatisticsData, index$e_StorageItem as StorageItem, index$e_UpdateError as UpdateError, index$e_UpdatePreimage as UpdatePreimage, index$e_UpdatePreimageKind as UpdatePreimageKind, index$e_UpdateService as UpdateService, index$e_UpdateServiceKind as UpdateServiceKind, index$e_UpdateStorage as UpdateStorage, index$e_UpdateStorageKind as UpdateStorageKind, index$e_ValidatorData as ValidatorData, index$e_ValidatorStatistics as ValidatorStatistics, index$e_accumulationOutputComparator as accumulationOutputComparator, index$e_codecBandersnatchKey as codecBandersnatchKey, index$e_codecPerCore as codecPerCore, index$e_codecServiceId as codecServiceId, index$e_codecVarGas as codecVarGas, index$e_codecVarU16 as codecVarU16, index$e_codecWithVersion as codecWithVersion, index$e_hashComparator as hashComparator, index$e_ignoreValueWithDefault as ignoreValueWithDefault, index$e_serviceDataCodec as serviceDataCodec, index$e_serviceEntriesCodec as serviceEntriesCodec, index$e_sortedSetCodec as sortedSetCodec, index$e_tryAsLookupHistorySlots as tryAsLookupHistorySlots, index$e_tryAsPerCore as tryAsPerCore, index$e_workReportsSortedSetCodec as workReportsSortedSetCodec, index$e_zeroSizeHint as zeroSizeHint };
11336
+ export type { index$e_BlocksState as BlocksState, index$e_ENTROPY_ENTRIES as ENTROPY_ENTRIES, index$e_EnumerableState as EnumerableState, index$e_FieldNames as FieldNames, index$e_InMemoryStateFields as InMemoryStateFields, index$e_LookupHistorySlots as LookupHistorySlots, index$e_MAX_RECENT_HISTORY as MAX_RECENT_HISTORY, index$e_PerCore as PerCore, index$e_SafroleSealingKeys as SafroleSealingKeys, index$e_Service as Service, index$e_ServiceData as ServiceData, index$e_ServiceEntries as ServiceEntries, index$e_ServicesUpdate as ServicesUpdate, index$e_State as State, index$e_StorageKey as StorageKey, index$e_VALIDATOR_META_BYTES as VALIDATOR_META_BYTES };
11275
11337
  }
11276
11338
 
11277
11339
  type StateKey = Opaque<OpaqueHash, "stateKey">;
@@ -11338,7 +11400,7 @@ declare namespace stateKeys {
11338
11400
  }
11339
11401
 
11340
11402
  /** https://graypaper.fluffylabs.dev/#/1c979cb/3bba033bba03?v=0.7.1 */
11341
- export function serviceStorage(serviceId: ServiceId, key: StorageKey): StateKey {
11403
+ export function serviceStorage(blake2b: Blake2b, serviceId: ServiceId, key: StorageKey): StateKey {
11342
11404
  if (Compatibility.isLessThan(GpVersion.V0_6_7)) {
11343
11405
  const out = Bytes.zero(HASH_SIZE);
11344
11406
  out.raw.set(u32AsLeBytes(tryAsU32(2 ** 32 - 1)), 0);
@@ -11346,11 +11408,11 @@ declare namespace stateKeys {
11346
11408
  return legacyServiceNested(serviceId, out);
11347
11409
  }
11348
11410
 
11349
- return serviceNested(serviceId, tryAsU32(2 ** 32 - 1), key);
11411
+ return serviceNested(blake2b, serviceId, tryAsU32(2 ** 32 - 1), key);
11350
11412
  }
11351
11413
 
11352
11414
  /** https://graypaper.fluffylabs.dev/#/1c979cb/3bd7033bd703?v=0.7.1 */
11353
- export function servicePreimage(serviceId: ServiceId, hash: PreimageHash): StateKey {
11415
+ export function servicePreimage(blake2b: Blake2b, serviceId: ServiceId, hash: PreimageHash): StateKey {
11354
11416
  if (Compatibility.isLessThan(GpVersion.V0_6_7)) {
11355
11417
  const out = Bytes.zero(HASH_SIZE);
11356
11418
  out.raw.set(u32AsLeBytes(tryAsU32(2 ** 32 - 2)), 0);
@@ -11358,11 +11420,16 @@ declare namespace stateKeys {
11358
11420
  return legacyServiceNested(serviceId, out);
11359
11421
  }
11360
11422
 
11361
- return serviceNested(serviceId, tryAsU32(2 ** 32 - 2), hash);
11423
+ return serviceNested(blake2b, serviceId, tryAsU32(2 ** 32 - 2), hash);
11362
11424
  }
11363
11425
 
11364
11426
  /** https://graypaper.fluffylabs.dev/#/1c979cb/3b0a043b0a04?v=0.7.1 */
11365
- export function serviceLookupHistory(serviceId: ServiceId, hash: PreimageHash, preimageLength: U32): StateKey {
11427
+ export function serviceLookupHistory(
11428
+ blake2b: Blake2b,
11429
+ serviceId: ServiceId,
11430
+ hash: PreimageHash,
11431
+ preimageLength: U32,
11432
+ ): StateKey {
11366
11433
  if (Compatibility.isLessThan(GpVersion.V0_6_7)) {
11367
11434
  const doubleHash = blake2b.hashBytes(hash);
11368
11435
  const out = Bytes.zero(HASH_SIZE);
@@ -11371,11 +11438,11 @@ declare namespace stateKeys {
11371
11438
  return legacyServiceNested(serviceId, out);
11372
11439
  }
11373
11440
 
11374
- return serviceNested(serviceId, preimageLength, hash);
11441
+ return serviceNested(blake2b, serviceId, preimageLength, hash);
11375
11442
  }
11376
11443
 
11377
11444
  /** https://graypaper.fluffylabs.dev/#/1c979cb/3b88003b8800?v=0.7.1 */
11378
- export function serviceNested(serviceId: ServiceId, numberPrefix: U32, hash: BytesBlob): StateKey {
11445
+ export function serviceNested(blake2b: Blake2b, serviceId: ServiceId, numberPrefix: U32, hash: BytesBlob): StateKey {
11379
11446
  const inputToHash = BytesBlob.blobFromParts(u32AsLeBytes(numberPrefix), hash.raw);
11380
11447
  const newHash = blake2b.hashBytes(inputToHash).raw.subarray(0, 28);
11381
11448
  const key = Bytes.zero(HASH_SIZE);
@@ -11555,24 +11622,26 @@ declare namespace serialize {
11555
11622
  /** C(255, s): https://graypaper.fluffylabs.dev/#/85129da/383103383103?v=0.6.3 */
11556
11623
  export const serviceData = (serviceId: ServiceId) => ({
11557
11624
  key: stateKeys.serviceInfo(serviceId),
11558
- Codec: ServiceAccountInfo.Codec,
11625
+ Codec: Compatibility.isGreaterOrEqual(GpVersion.V0_7_1)
11626
+ ? codecWithVersion(ServiceAccountInfo.Codec)
11627
+ : ServiceAccountInfo.Codec,
11559
11628
  });
11560
11629
 
11561
11630
  /** https://graypaper.fluffylabs.dev/#/85129da/384803384803?v=0.6.3 */
11562
- export const serviceStorage = (serviceId: ServiceId, key: StorageKey) => ({
11563
- key: stateKeys.serviceStorage(serviceId, key),
11631
+ export const serviceStorage = (blake2b: Blake2b, serviceId: ServiceId, key: StorageKey) => ({
11632
+ key: stateKeys.serviceStorage(blake2b, serviceId, key),
11564
11633
  Codec: dumpCodec,
11565
11634
  });
11566
11635
 
11567
11636
  /** https://graypaper.fluffylabs.dev/#/85129da/385b03385b03?v=0.6.3 */
11568
- export const servicePreimages = (serviceId: ServiceId, hash: PreimageHash) => ({
11569
- key: stateKeys.servicePreimage(serviceId, hash),
11637
+ export const servicePreimages = (blake2b: Blake2b, serviceId: ServiceId, hash: PreimageHash) => ({
11638
+ key: stateKeys.servicePreimage(blake2b, serviceId, hash),
11570
11639
  Codec: dumpCodec,
11571
11640
  });
11572
11641
 
11573
11642
  /** https://graypaper.fluffylabs.dev/#/85129da/387603387603?v=0.6.3 */
11574
- export const serviceLookupHistory = (serviceId: ServiceId, hash: PreimageHash, len: U32) => ({
11575
- key: stateKeys.serviceLookupHistory(serviceId, hash, len),
11643
+ export const serviceLookupHistory = (blake2b: Blake2b, serviceId: ServiceId, hash: PreimageHash, len: U32) => ({
11644
+ key: stateKeys.serviceLookupHistory(blake2b, serviceId, hash, len),
11576
11645
  Codec: readonlyArray(codec.sequenceVarLen(codec.u32)),
11577
11646
  });
11578
11647
  }
@@ -11607,6 +11676,7 @@ declare const EMPTY_BLOB = BytesBlob.empty();
11607
11676
  /** Serialize given state update into a series of key-value pairs. */
11608
11677
  declare function* serializeStateUpdate(
11609
11678
  spec: ChainSpec,
11679
+ blake2b: Blake2b,
11610
11680
  update: Partial<State & ServicesUpdate>,
11611
11681
  ): Generator<StateEntryUpdate> {
11612
11682
  // first let's serialize all of the simple entries (if present!)
@@ -11615,9 +11685,9 @@ declare function* serializeStateUpdate(
11615
11685
  const encode = <T>(codec: Encode<T>, val: T) => Encoder.encodeObject(codec, val, spec);
11616
11686
 
11617
11687
  // then let's proceed with service updates
11618
- yield* serializeServiceUpdates(update.servicesUpdates, encode);
11619
- yield* serializePreimages(update.preimages, encode);
11620
- yield* serializeStorage(update.storage);
11688
+ yield* serializeServiceUpdates(update.servicesUpdates, encode, blake2b);
11689
+ yield* serializePreimages(update.preimages, encode, blake2b);
11690
+ yield* serializeStorage(update.storage, blake2b);
11621
11691
  yield* serializeRemovedServices(update.servicesRemoved);
11622
11692
  }
11623
11693
 
@@ -11629,18 +11699,18 @@ declare function* serializeRemovedServices(servicesRemoved: ServiceId[] | undefi
11629
11699
  }
11630
11700
  }
11631
11701
 
11632
- declare function* serializeStorage(storage: UpdateStorage[] | undefined): Generator<StateEntryUpdate> {
11702
+ declare function* serializeStorage(storage: UpdateStorage[] | undefined, blake2b: Blake2b): Generator<StateEntryUpdate> {
11633
11703
  for (const { action, serviceId } of storage ?? []) {
11634
11704
  switch (action.kind) {
11635
11705
  case UpdateStorageKind.Set: {
11636
11706
  const key = action.storage.key;
11637
- const codec = serialize.serviceStorage(serviceId, key);
11707
+ const codec = serialize.serviceStorage(blake2b, serviceId, key);
11638
11708
  yield [StateEntryUpdateAction.Insert, codec.key, action.storage.value];
11639
11709
  break;
11640
11710
  }
11641
11711
  case UpdateStorageKind.Remove: {
11642
11712
  const key = action.key;
11643
- const codec = serialize.serviceStorage(serviceId, key);
11713
+ const codec = serialize.serviceStorage(blake2b, serviceId, key);
11644
11714
  yield [StateEntryUpdateAction.Remove, codec.key, EMPTY_BLOB];
11645
11715
  break;
11646
11716
  }
@@ -11650,16 +11720,20 @@ declare function* serializeStorage(storage: UpdateStorage[] | undefined): Genera
11650
11720
  }
11651
11721
  }
11652
11722
 
11653
- declare function* serializePreimages(preimages: UpdatePreimage[] | undefined, encode: EncodeFun): Generator<StateEntryUpdate> {
11723
+ declare function* serializePreimages(
11724
+ preimages: UpdatePreimage[] | undefined,
11725
+ encode: EncodeFun,
11726
+ blake2b: Blake2b,
11727
+ ): Generator<StateEntryUpdate> {
11654
11728
  for (const { action, serviceId } of preimages ?? []) {
11655
11729
  switch (action.kind) {
11656
11730
  case UpdatePreimageKind.Provide: {
11657
11731
  const { hash, blob } = action.preimage;
11658
- const codec = serialize.servicePreimages(serviceId, hash);
11732
+ const codec = serialize.servicePreimages(blake2b, serviceId, hash);
11659
11733
  yield [StateEntryUpdateAction.Insert, codec.key, blob];
11660
11734
 
11661
11735
  if (action.slot !== null) {
11662
- const codec2 = serialize.serviceLookupHistory(serviceId, hash, tryAsU32(blob.length));
11736
+ const codec2 = serialize.serviceLookupHistory(blake2b, serviceId, hash, tryAsU32(blob.length));
11663
11737
  yield [
11664
11738
  StateEntryUpdateAction.Insert,
11665
11739
  codec2.key,
@@ -11670,16 +11744,16 @@ declare function* serializePreimages(preimages: UpdatePreimage[] | undefined, en
11670
11744
  }
11671
11745
  case UpdatePreimageKind.UpdateOrAdd: {
11672
11746
  const { hash, length, slots } = action.item;
11673
- const codec = serialize.serviceLookupHistory(serviceId, hash, length);
11747
+ const codec = serialize.serviceLookupHistory(blake2b, serviceId, hash, length);
11674
11748
  yield [StateEntryUpdateAction.Insert, codec.key, encode(codec.Codec, slots)];
11675
11749
  break;
11676
11750
  }
11677
11751
  case UpdatePreimageKind.Remove: {
11678
11752
  const { hash, length } = action;
11679
- const codec = serialize.servicePreimages(serviceId, hash);
11753
+ const codec = serialize.servicePreimages(blake2b, serviceId, hash);
11680
11754
  yield [StateEntryUpdateAction.Remove, codec.key, EMPTY_BLOB];
11681
11755
 
11682
- const codec2 = serialize.serviceLookupHistory(serviceId, hash, length);
11756
+ const codec2 = serialize.serviceLookupHistory(blake2b, serviceId, hash, length);
11683
11757
  yield [StateEntryUpdateAction.Remove, codec2.key, EMPTY_BLOB];
11684
11758
  break;
11685
11759
  }
@@ -11691,6 +11765,7 @@ declare function* serializePreimages(preimages: UpdatePreimage[] | undefined, en
11691
11765
  declare function* serializeServiceUpdates(
11692
11766
  servicesUpdates: UpdateService[] | undefined,
11693
11767
  encode: EncodeFun,
11768
+ blake2b: Blake2b,
11694
11769
  ): Generator<StateEntryUpdate> {
11695
11770
  for (const { action, serviceId } of servicesUpdates ?? []) {
11696
11771
  // new service being created or updated
@@ -11700,7 +11775,7 @@ declare function* serializeServiceUpdates(
11700
11775
  // additional lookup history update
11701
11776
  if (action.kind === UpdateServiceKind.Create && action.lookupHistory !== null) {
11702
11777
  const { lookupHistory } = action;
11703
- const codec2 = serialize.serviceLookupHistory(serviceId, lookupHistory.hash, lookupHistory.length);
11778
+ const codec2 = serialize.serviceLookupHistory(blake2b, serviceId, lookupHistory.hash, lookupHistory.length);
11704
11779
  yield [StateEntryUpdateAction.Insert, codec2.key, encode(codec2.Codec, lookupHistory.slots)];
11705
11780
  }
11706
11781
  }
@@ -11834,8 +11909,8 @@ declare class StateEntries {
11834
11909
  );
11835
11910
 
11836
11911
  /** Turn in-memory state into it's serialized form. */
11837
- static serializeInMemory(spec: ChainSpec, state: InMemoryState) {
11838
- return new StateEntries(convertInMemoryStateToDictionary(spec, state));
11912
+ static serializeInMemory(spec: ChainSpec, blake2b: Blake2b, state: InMemoryState) {
11913
+ return new StateEntries(convertInMemoryStateToDictionary(spec, blake2b, state));
11839
11914
  }
11840
11915
 
11841
11916
  /**
@@ -11890,7 +11965,8 @@ declare class StateEntries {
11890
11965
  }
11891
11966
 
11892
11967
  /** https://graypaper.fluffylabs.dev/#/68eaa1f/391600391600?v=0.6.4 */
11893
- getRootHash(): StateRootHash {
11968
+ getRootHash(blake2b: Blake2b): StateRootHash {
11969
+ const blake2bTrieHasher = getBlake2bTrieHasher(blake2b);
11894
11970
  const leaves: SortedSet<LeafNode> = SortedSet.fromArray(leafComparator);
11895
11971
  for (const [key, value] of this) {
11896
11972
  leaves.insert(InMemoryTrie.constructLeaf(blake2bTrieHasher, key.asOpaque(), value));
@@ -11903,6 +11979,7 @@ declare class StateEntries {
11903
11979
  /** https://graypaper.fluffylabs.dev/#/68eaa1f/38a50038a500?v=0.6.4 */
11904
11980
  declare function convertInMemoryStateToDictionary(
11905
11981
  spec: ChainSpec,
11982
+ blake2b: Blake2b,
11906
11983
  state: InMemoryState,
11907
11984
  ): TruncatedHashDictionary<StateKey, BytesBlob> {
11908
11985
  const serialized = TruncatedHashDictionary.fromEntries<StateKey, BytesBlob>([]);
@@ -11935,20 +12012,25 @@ declare function convertInMemoryStateToDictionary(
11935
12012
 
11936
12013
  // preimages
11937
12014
  for (const preimage of service.data.preimages.values()) {
11938
- const { key, Codec } = serialize.servicePreimages(serviceId, preimage.hash);
12015
+ const { key, Codec } = serialize.servicePreimages(blake2b, serviceId, preimage.hash);
11939
12016
  serialized.set(key, Encoder.encodeObject(Codec, preimage.blob));
11940
12017
  }
11941
12018
 
11942
12019
  // storage
11943
12020
  for (const storage of service.data.storage.values()) {
11944
- const { key, Codec } = serialize.serviceStorage(serviceId, storage.key);
12021
+ const { key, Codec } = serialize.serviceStorage(blake2b, serviceId, storage.key);
11945
12022
  serialized.set(key, Encoder.encodeObject(Codec, storage.value));
11946
12023
  }
11947
12024
 
11948
12025
  // lookup history
11949
12026
  for (const lookupHistoryList of service.data.lookupHistory.values()) {
11950
12027
  for (const lookupHistory of lookupHistoryList) {
11951
- const { key, Codec } = serialize.serviceLookupHistory(serviceId, lookupHistory.hash, lookupHistory.length);
12028
+ const { key, Codec } = serialize.serviceLookupHistory(
12029
+ blake2b,
12030
+ serviceId,
12031
+ lookupHistory.hash,
12032
+ lookupHistory.length,
12033
+ );
11952
12034
  serialized.set(key, Encoder.encodeObject(Codec, lookupHistory.slots.slice()));
11953
12035
  }
11954
12036
  }
@@ -11979,21 +12061,23 @@ declare class SerializedState<T extends SerializedStateBackend = SerializedState
11979
12061
  implements State, EnumerableState
11980
12062
  {
11981
12063
  /** Create a state-like object from collection of serialized entries. */
11982
- static fromStateEntries(spec: ChainSpec, state: StateEntries, recentServices: ServiceId[] = []) {
11983
- return new SerializedState(spec, state, recentServices);
12064
+ static fromStateEntries(spec: ChainSpec, blake2b: Blake2b, state: StateEntries, recentServices: ServiceId[] = []) {
12065
+ return new SerializedState(spec, blake2b, state, recentServices);
11984
12066
  }
11985
12067
 
11986
12068
  /** Create a state-like object backed by some DB. */
11987
12069
  static new<T extends SerializedStateBackend>(
11988
12070
  spec: ChainSpec,
12071
+ blake2b: Blake2b,
11989
12072
  db: T,
11990
12073
  recentServices: ServiceId[] = [],
11991
12074
  ): SerializedState<T> {
11992
- return new SerializedState(spec, db, recentServices);
12075
+ return new SerializedState(spec, blake2b, db, recentServices);
11993
12076
  }
11994
12077
 
11995
12078
  private constructor(
11996
12079
  private readonly spec: ChainSpec,
12080
+ private readonly blake2b: Blake2b,
11997
12081
  public backend: T,
11998
12082
  /** Best-effort list of recently active services. */
11999
12083
  private readonly _recentServiceIds: ServiceId[],
@@ -12024,7 +12108,7 @@ declare class SerializedState<T extends SerializedStateBackend = SerializedState
12024
12108
  this._recentServiceIds.push(id);
12025
12109
  }
12026
12110
 
12027
- return new SerializedService(id, serviceData, (key) => this.retrieveOptional(key));
12111
+ return new SerializedService(this.blake2b, id, serviceData, (key) => this.retrieveOptional(key));
12028
12112
  }
12029
12113
 
12030
12114
  private retrieve<T>({ key, Codec }: KeyAndCodec<T>, description: string): T {
@@ -12123,6 +12207,7 @@ declare class SerializedState<T extends SerializedStateBackend = SerializedState
12123
12207
  /** Service data representation on a serialized state. */
12124
12208
  declare class SerializedService implements Service {
12125
12209
  constructor(
12210
+ public readonly blake2b: Blake2b,
12126
12211
  /** Service id */
12127
12212
  public readonly serviceId: ServiceId,
12128
12213
  private readonly accountInfo: ServiceAccountInfo,
@@ -12138,14 +12223,14 @@ declare class SerializedService implements Service {
12138
12223
  getStorage(rawKey: StorageKey): BytesBlob | null {
12139
12224
  if (Compatibility.isLessThan(GpVersion.V0_6_7)) {
12140
12225
  const SERVICE_ID_BYTES = 4;
12141
- const serviceIdAndKey = new Uint8Array(SERVICE_ID_BYTES + rawKey.length);
12226
+ const serviceIdAndKey = safeAllocUint8Array(SERVICE_ID_BYTES + rawKey.length);
12142
12227
  serviceIdAndKey.set(u32AsLeBytes(this.serviceId));
12143
12228
  serviceIdAndKey.set(rawKey.raw, SERVICE_ID_BYTES);
12144
- const key: StorageKey = asOpaqueType(BytesBlob.blobFrom(blake2b.hashBytes(serviceIdAndKey).raw));
12145
- return this.retrieveOptional(serialize.serviceStorage(this.serviceId, key)) ?? null;
12229
+ const key: StorageKey = asOpaqueType(BytesBlob.blobFrom(this.blake2b.hashBytes(serviceIdAndKey).raw));
12230
+ return this.retrieveOptional(serialize.serviceStorage(this.blake2b, this.serviceId, key)) ?? null;
12146
12231
  }
12147
12232
 
12148
- return this.retrieveOptional(serialize.serviceStorage(this.serviceId, rawKey)) ?? null;
12233
+ return this.retrieveOptional(serialize.serviceStorage(this.blake2b, this.serviceId, rawKey)) ?? null;
12149
12234
  }
12150
12235
 
12151
12236
  /**
@@ -12155,17 +12240,17 @@ declare class SerializedService implements Service {
12155
12240
  */
12156
12241
  hasPreimage(hash: PreimageHash): boolean {
12157
12242
  // TODO [ToDr] consider optimizing to avoid fetching the whole data.
12158
- return this.retrieveOptional(serialize.servicePreimages(this.serviceId, hash)) !== undefined;
12243
+ return this.retrieveOptional(serialize.servicePreimages(this.blake2b, this.serviceId, hash)) !== undefined;
12159
12244
  }
12160
12245
 
12161
12246
  /** Retrieve preimage from the DB. */
12162
12247
  getPreimage(hash: PreimageHash): BytesBlob | null {
12163
- return this.retrieveOptional(serialize.servicePreimages(this.serviceId, hash)) ?? null;
12248
+ return this.retrieveOptional(serialize.servicePreimages(this.blake2b, this.serviceId, hash)) ?? null;
12164
12249
  }
12165
12250
 
12166
12251
  /** Retrieve preimage lookup history. */
12167
12252
  getLookupHistory(hash: PreimageHash, len: U32): LookupHistorySlots | null {
12168
- const rawSlots = this.retrieveOptional(serialize.serviceLookupHistory(this.serviceId, hash, len));
12253
+ const rawSlots = this.retrieveOptional(serialize.serviceLookupHistory(this.blake2b, this.serviceId, hash, len));
12169
12254
  if (rawSlots === undefined) {
12170
12255
  return null;
12171
12256
  }
@@ -12178,9 +12263,9 @@ type KeyAndCodec<T> = {
12178
12263
  Codec: Decode<T>;
12179
12264
  };
12180
12265
 
12181
- declare function loadState(spec: ChainSpec, entries: Iterable<[StateKey | TruncatedHash, BytesBlob]>) {
12266
+ declare function loadState(spec: ChainSpec, blake2b: Blake2b, entries: Iterable<[StateKey | TruncatedHash, BytesBlob]>) {
12182
12267
  const stateEntries = StateEntries.fromEntriesUnsafe(entries);
12183
- return SerializedState.fromStateEntries(spec, stateEntries);
12268
+ return SerializedState.fromStateEntries(spec, blake2b, stateEntries);
12184
12269
  }
12185
12270
 
12186
12271
  /**
@@ -12209,44 +12294,44 @@ declare function loadState(spec: ChainSpec, entries: Iterable<[StateKey | Trunca
12209
12294
  * hashmap of `key -> value` entries.
12210
12295
  */
12211
12296
 
12212
- declare const index$b_EMPTY_BLOB: typeof EMPTY_BLOB;
12213
- type index$b_EncodeFun = EncodeFun;
12214
- type index$b_KeyAndCodec<T> = KeyAndCodec<T>;
12215
- type index$b_SerializedService = SerializedService;
12216
- declare const index$b_SerializedService: typeof SerializedService;
12217
- type index$b_SerializedState<T extends SerializedStateBackend = SerializedStateBackend> = SerializedState<T>;
12218
- declare const index$b_SerializedState: typeof SerializedState;
12219
- type index$b_SerializedStateBackend = SerializedStateBackend;
12220
- type index$b_StateCodec<T> = StateCodec<T>;
12221
- type index$b_StateEntries = StateEntries;
12222
- declare const index$b_StateEntries: typeof StateEntries;
12223
- type index$b_StateEntryUpdate = StateEntryUpdate;
12224
- type index$b_StateEntryUpdateAction = StateEntryUpdateAction;
12225
- declare const index$b_StateEntryUpdateAction: typeof StateEntryUpdateAction;
12226
- type index$b_StateKey = StateKey;
12227
- type index$b_StateKeyIdx = StateKeyIdx;
12228
- declare const index$b_StateKeyIdx: typeof StateKeyIdx;
12229
- declare const index$b_TYPICAL_STATE_ITEMS: typeof TYPICAL_STATE_ITEMS;
12230
- declare const index$b_TYPICAL_STATE_ITEM_LEN: typeof TYPICAL_STATE_ITEM_LEN;
12231
- declare const index$b_U32_BYTES: typeof U32_BYTES;
12232
- declare const index$b_binaryMerkleization: typeof binaryMerkleization;
12233
- declare const index$b_convertInMemoryStateToDictionary: typeof convertInMemoryStateToDictionary;
12234
- declare const index$b_dumpCodec: typeof dumpCodec;
12235
- declare const index$b_getSafroleData: typeof getSafroleData;
12236
- declare const index$b_legacyServiceNested: typeof legacyServiceNested;
12237
- declare const index$b_loadState: typeof loadState;
12238
- import index$b_serialize = serialize;
12239
- declare const index$b_serializeBasicKeys: typeof serializeBasicKeys;
12240
- declare const index$b_serializePreimages: typeof serializePreimages;
12241
- declare const index$b_serializeRemovedServices: typeof serializeRemovedServices;
12242
- declare const index$b_serializeServiceUpdates: typeof serializeServiceUpdates;
12243
- declare const index$b_serializeStateUpdate: typeof serializeStateUpdate;
12244
- declare const index$b_serializeStorage: typeof serializeStorage;
12245
- declare const index$b_stateEntriesSequenceCodec: typeof stateEntriesSequenceCodec;
12246
- import index$b_stateKeys = stateKeys;
12247
- declare namespace index$b {
12248
- export { index$b_EMPTY_BLOB as EMPTY_BLOB, index$b_SerializedService as SerializedService, index$b_SerializedState as SerializedState, index$b_StateEntries as StateEntries, index$b_StateEntryUpdateAction as StateEntryUpdateAction, index$b_StateKeyIdx as StateKeyIdx, index$b_TYPICAL_STATE_ITEMS as TYPICAL_STATE_ITEMS, index$b_TYPICAL_STATE_ITEM_LEN as TYPICAL_STATE_ITEM_LEN, index$b_U32_BYTES as U32_BYTES, index$b_binaryMerkleization as binaryMerkleization, index$b_convertInMemoryStateToDictionary as convertInMemoryStateToDictionary, index$b_dumpCodec as dumpCodec, index$b_getSafroleData as getSafroleData, index$b_legacyServiceNested as legacyServiceNested, index$b_loadState as loadState, index$b_serialize as serialize, index$b_serializeBasicKeys as serializeBasicKeys, index$b_serializePreimages as serializePreimages, index$b_serializeRemovedServices as serializeRemovedServices, index$b_serializeServiceUpdates as serializeServiceUpdates, index$b_serializeStateUpdate as serializeStateUpdate, index$b_serializeStorage as serializeStorage, index$b_stateEntriesSequenceCodec as stateEntriesSequenceCodec, index$b_stateKeys as stateKeys };
12249
- export type { index$b_EncodeFun as EncodeFun, index$b_KeyAndCodec as KeyAndCodec, index$b_SerializedStateBackend as SerializedStateBackend, index$b_StateCodec as StateCodec, index$b_StateEntryUpdate as StateEntryUpdate, index$b_StateKey as StateKey };
12297
+ declare const index$d_EMPTY_BLOB: typeof EMPTY_BLOB;
12298
+ type index$d_EncodeFun = EncodeFun;
12299
+ type index$d_KeyAndCodec<T> = KeyAndCodec<T>;
12300
+ type index$d_SerializedService = SerializedService;
12301
+ declare const index$d_SerializedService: typeof SerializedService;
12302
+ type index$d_SerializedState<T extends SerializedStateBackend = SerializedStateBackend> = SerializedState<T>;
12303
+ declare const index$d_SerializedState: typeof SerializedState;
12304
+ type index$d_SerializedStateBackend = SerializedStateBackend;
12305
+ type index$d_StateCodec<T> = StateCodec<T>;
12306
+ type index$d_StateEntries = StateEntries;
12307
+ declare const index$d_StateEntries: typeof StateEntries;
12308
+ type index$d_StateEntryUpdate = StateEntryUpdate;
12309
+ type index$d_StateEntryUpdateAction = StateEntryUpdateAction;
12310
+ declare const index$d_StateEntryUpdateAction: typeof StateEntryUpdateAction;
12311
+ type index$d_StateKey = StateKey;
12312
+ type index$d_StateKeyIdx = StateKeyIdx;
12313
+ declare const index$d_StateKeyIdx: typeof StateKeyIdx;
12314
+ declare const index$d_TYPICAL_STATE_ITEMS: typeof TYPICAL_STATE_ITEMS;
12315
+ declare const index$d_TYPICAL_STATE_ITEM_LEN: typeof TYPICAL_STATE_ITEM_LEN;
12316
+ declare const index$d_U32_BYTES: typeof U32_BYTES;
12317
+ declare const index$d_binaryMerkleization: typeof binaryMerkleization;
12318
+ declare const index$d_convertInMemoryStateToDictionary: typeof convertInMemoryStateToDictionary;
12319
+ declare const index$d_dumpCodec: typeof dumpCodec;
12320
+ declare const index$d_getSafroleData: typeof getSafroleData;
12321
+ declare const index$d_legacyServiceNested: typeof legacyServiceNested;
12322
+ declare const index$d_loadState: typeof loadState;
12323
+ import index$d_serialize = serialize;
12324
+ declare const index$d_serializeBasicKeys: typeof serializeBasicKeys;
12325
+ declare const index$d_serializePreimages: typeof serializePreimages;
12326
+ declare const index$d_serializeRemovedServices: typeof serializeRemovedServices;
12327
+ declare const index$d_serializeServiceUpdates: typeof serializeServiceUpdates;
12328
+ declare const index$d_serializeStateUpdate: typeof serializeStateUpdate;
12329
+ declare const index$d_serializeStorage: typeof serializeStorage;
12330
+ declare const index$d_stateEntriesSequenceCodec: typeof stateEntriesSequenceCodec;
12331
+ import index$d_stateKeys = stateKeys;
12332
+ declare namespace index$d {
12333
+ export { index$d_EMPTY_BLOB as EMPTY_BLOB, index$d_SerializedService as SerializedService, index$d_SerializedState as SerializedState, index$d_StateEntries as StateEntries, index$d_StateEntryUpdateAction as StateEntryUpdateAction, index$d_StateKeyIdx as StateKeyIdx, index$d_TYPICAL_STATE_ITEMS as TYPICAL_STATE_ITEMS, index$d_TYPICAL_STATE_ITEM_LEN as TYPICAL_STATE_ITEM_LEN, index$d_U32_BYTES as U32_BYTES, index$d_binaryMerkleization as binaryMerkleization, index$d_convertInMemoryStateToDictionary as convertInMemoryStateToDictionary, index$d_dumpCodec as dumpCodec, index$d_getSafroleData as getSafroleData, index$d_legacyServiceNested as legacyServiceNested, index$d_loadState as loadState, index$d_serialize as serialize, index$d_serializeBasicKeys as serializeBasicKeys, index$d_serializePreimages as serializePreimages, index$d_serializeRemovedServices as serializeRemovedServices, index$d_serializeServiceUpdates as serializeServiceUpdates, index$d_serializeStateUpdate as serializeStateUpdate, index$d_serializeStorage as serializeStorage, index$d_stateEntriesSequenceCodec as stateEntriesSequenceCodec, index$d_stateKeys as stateKeys };
12334
+ export type { index$d_EncodeFun as EncodeFun, index$d_KeyAndCodec as KeyAndCodec, index$d_SerializedStateBackend as SerializedStateBackend, index$d_StateCodec as StateCodec, index$d_StateEntryUpdate as StateEntryUpdate, index$d_StateKey as StateKey };
12250
12335
  }
12251
12336
 
12252
12337
  /** Error during `LeafDb` creation. */
@@ -12336,7 +12421,8 @@ declare class LeafDb implements SerializedStateBackend {
12336
12421
  assertNever(val);
12337
12422
  }
12338
12423
 
12339
- getStateRoot(): StateRootHash {
12424
+ getStateRoot(blake2b: Blake2b): StateRootHash {
12425
+ const blake2bTrieHasher = getBlake2bTrieHasher(blake2b);
12340
12426
  return InMemoryTrie.computeStateRoot(blake2bTrieHasher, this.leaves).asOpaque();
12341
12427
  }
12342
12428
 
@@ -12434,7 +12520,8 @@ declare class InMemoryStates implements StatesDb<InMemoryState> {
12434
12520
  }
12435
12521
 
12436
12522
  async getStateRoot(state: InMemoryState): Promise<StateRootHash> {
12437
- return StateEntries.serializeInMemory(this.spec, state).getRootHash();
12523
+ const blake2b = await Blake2b.createHasher();
12524
+ return StateEntries.serializeInMemory(this.spec, blake2b, state).getRootHash(blake2b);
12438
12525
  }
12439
12526
 
12440
12527
  /** Insert a full state into the database. */
@@ -12454,25 +12541,25 @@ declare class InMemoryStates implements StatesDb<InMemoryState> {
12454
12541
  }
12455
12542
  }
12456
12543
 
12457
- type index$a_BlocksDb = BlocksDb;
12458
- type index$a_InMemoryBlocks = InMemoryBlocks;
12459
- declare const index$a_InMemoryBlocks: typeof InMemoryBlocks;
12460
- type index$a_InMemoryStates = InMemoryStates;
12461
- declare const index$a_InMemoryStates: typeof InMemoryStates;
12462
- type index$a_LeafDb = LeafDb;
12463
- declare const index$a_LeafDb: typeof LeafDb;
12464
- type index$a_LeafDbError = LeafDbError;
12465
- declare const index$a_LeafDbError: typeof LeafDbError;
12466
- type index$a_Lookup = Lookup;
12467
- type index$a_LookupKind = LookupKind;
12468
- declare const index$a_LookupKind: typeof LookupKind;
12469
- type index$a_StateUpdateError = StateUpdateError;
12470
- declare const index$a_StateUpdateError: typeof StateUpdateError;
12471
- type index$a_StatesDb<T extends State = State> = StatesDb<T>;
12472
- type index$a_ValuesDb = ValuesDb;
12473
- declare namespace index$a {
12474
- export { index$a_InMemoryBlocks as InMemoryBlocks, index$a_InMemoryStates as InMemoryStates, index$a_LeafDb as LeafDb, index$a_LeafDbError as LeafDbError, index$a_LookupKind as LookupKind, index$a_StateUpdateError as StateUpdateError };
12475
- export type { index$a_BlocksDb as BlocksDb, index$a_Lookup as Lookup, index$a_StatesDb as StatesDb, index$a_ValuesDb as ValuesDb };
12544
+ type index$c_BlocksDb = BlocksDb;
12545
+ type index$c_InMemoryBlocks = InMemoryBlocks;
12546
+ declare const index$c_InMemoryBlocks: typeof InMemoryBlocks;
12547
+ type index$c_InMemoryStates = InMemoryStates;
12548
+ declare const index$c_InMemoryStates: typeof InMemoryStates;
12549
+ type index$c_LeafDb = LeafDb;
12550
+ declare const index$c_LeafDb: typeof LeafDb;
12551
+ type index$c_LeafDbError = LeafDbError;
12552
+ declare const index$c_LeafDbError: typeof LeafDbError;
12553
+ type index$c_Lookup = Lookup;
12554
+ type index$c_LookupKind = LookupKind;
12555
+ declare const index$c_LookupKind: typeof LookupKind;
12556
+ type index$c_StateUpdateError = StateUpdateError;
12557
+ declare const index$c_StateUpdateError: typeof StateUpdateError;
12558
+ type index$c_StatesDb<T extends State = State> = StatesDb<T>;
12559
+ type index$c_ValuesDb = ValuesDb;
12560
+ declare namespace index$c {
12561
+ export { index$c_InMemoryBlocks as InMemoryBlocks, index$c_InMemoryStates as InMemoryStates, index$c_LeafDb as LeafDb, index$c_LeafDbError as LeafDbError, index$c_LookupKind as LookupKind, index$c_StateUpdateError as StateUpdateError };
12562
+ export type { index$c_BlocksDb as BlocksDb, index$c_Lookup as Lookup, index$c_StatesDb as StatesDb, index$c_ValuesDb as ValuesDb };
12476
12563
  }
12477
12564
 
12478
12565
  /**
@@ -12539,7 +12626,7 @@ declare function padAndEncodeData(input: BytesBlob) {
12539
12626
  const paddedLength = Math.ceil(input.length / PIECE_SIZE) * PIECE_SIZE;
12540
12627
  let padded = input;
12541
12628
  if (input.length !== paddedLength) {
12542
- padded = BytesBlob.blobFrom(new Uint8Array(paddedLength));
12629
+ padded = BytesBlob.blobFrom(safeAllocUint8Array(paddedLength));
12543
12630
  padded.raw.set(input.raw, 0);
12544
12631
  }
12545
12632
  return chunkingFunction(padded);
@@ -12595,7 +12682,7 @@ declare function decodeData(input: FixedSizeArray<[number, BytesBlob], N_CHUNKS_
12595
12682
  */
12596
12683
  declare function encodePoints(input: Bytes<PIECE_SIZE>): FixedSizeArray<Bytes<POINT_LENGTH>, N_CHUNKS_TOTAL> {
12597
12684
  const result: Bytes<POINT_LENGTH>[] = [];
12598
- const data = new Uint8Array(POINT_ALIGNMENT * N_CHUNKS_REQUIRED);
12685
+ const data = safeAllocUint8Array(POINT_ALIGNMENT * N_CHUNKS_REQUIRED);
12599
12686
 
12600
12687
  // add original shards to the result
12601
12688
  for (let i = 0; i < N_CHUNKS_REQUIRED; i++) {
@@ -12615,7 +12702,7 @@ declare function encodePoints(input: Bytes<PIECE_SIZE>): FixedSizeArray<Bytes<PO
12615
12702
  for (let i = 0; i < N_CHUNKS_REDUNDANCY; i++) {
12616
12703
  const pointIndex = i * POINT_ALIGNMENT;
12617
12704
 
12618
- const redundancyPoint = new Uint8Array(POINT_LENGTH);
12705
+ const redundancyPoint = safeAllocUint8Array(POINT_LENGTH);
12619
12706
  for (let j = 0; j < POINT_LENGTH; j++) {
12620
12707
  redundancyPoint[j] = encodedData[pointIndex + j * HALF_POINT_SIZE];
12621
12708
  }
@@ -12635,7 +12722,7 @@ declare function decodePiece(
12635
12722
  ): Bytes<PIECE_SIZE> {
12636
12723
  const result = Bytes.zero(PIECE_SIZE);
12637
12724
 
12638
- const data = new Uint8Array(N_CHUNKS_REQUIRED * POINT_ALIGNMENT);
12725
+ const data = safeAllocUint8Array(N_CHUNKS_REQUIRED * POINT_ALIGNMENT);
12639
12726
  const indices = new Uint16Array(input.length);
12640
12727
 
12641
12728
  for (let i = 0; i < N_CHUNKS_REQUIRED; i++) {
@@ -12762,163 +12849,704 @@ declare function lace<N extends number, K extends number>(input: FixedSizeArray<
12762
12849
  return BytesBlob.empty();
12763
12850
  }
12764
12851
  const n = input[0].length;
12765
- const result = BytesBlob.blobFrom(new Uint8Array(k * n));
12852
+ const result = BytesBlob.blobFrom(safeAllocUint8Array(k * n));
12766
12853
  for (let i = 0; i < k; i++) {
12767
12854
  const entry = input[i].raw;
12768
12855
  for (let j = 0; j < n; j++) {
12769
12856
  result.raw[j * k + i] = entry[j];
12770
12857
  }
12771
12858
  }
12772
- return result;
12859
+ return result;
12860
+ }
12861
+
12862
+ /**
12863
+ * `T`: Transposing function which accepts an array of `K` pieces of data
12864
+ * which each have same lenght of `N` octets and returns an array of `N`
12865
+ * pieces of data which each have length of `K` octets.
12866
+ *
12867
+ * T[[x0,0, x0,1, x0,2, . . . ], [x1,0, x1,1, . . . ], . . . ] ≡
12868
+ * [[x0,0, x1,0, x2,0, . . . ], [x0,1, x1,1, . . . ], . . . ]
12869
+ *
12870
+ * https://graypaper.fluffylabs.dev/#/9a08063/3e2e023e2e02?v=0.6.6
12871
+ */
12872
+ declare function transpose<T, N extends number, K extends number>(
12873
+ input: FixedSizeArray<FixedSizeArray<T, K>, N>,
12874
+ k: K,
12875
+ ): FixedSizeArray<FixedSizeArray<T, N>, K> {
12876
+ const n = input.fixedLength;
12877
+ const columns: FixedSizeArray<T, N>[] = [];
12878
+
12879
+ for (let c = 0; c < k; c++) {
12880
+ const newColumn: T[] = [];
12881
+ for (let r = 0; r < n; r++) {
12882
+ const cell = input[r][c];
12883
+ newColumn.push(cell);
12884
+ }
12885
+ columns.push(FixedSizeArray.new(newColumn, n));
12886
+ }
12887
+ return FixedSizeArray.new(columns, k);
12888
+ }
12889
+
12890
+ /**
12891
+ * `C`: Erasure-code chunking function which accepts an arbitrary sized data blob whose
12892
+ * length divides wholly into `PIECE_SIZE` octets and results in `N_CHUNKS_TOTAL`
12893
+ * sequences of sequences, each of `POINT_LENGTH * K` octets blobs.
12894
+ * Where `K` is the number that divides input length by `PIECE_SIZE`.
12895
+ *
12896
+ * Each element of resulting array is the same length.
12897
+ *
12898
+ * https://graypaper.fluffylabs.dev/#/9a08063/3f15003f1500?v=0.6.6
12899
+ */
12900
+ declare function chunkingFunction(input: BytesBlob): FixedSizeArray<BytesBlob, N_CHUNKS_TOTAL> {
12901
+ const k = Math.floor(input.length / PIECE_SIZE);
12902
+ check`${k * PIECE_SIZE === input.length} Input length ${input.length} is not divisible by ${PIECE_SIZE}`;
12903
+
12904
+ // we get a `k` pieces.
12905
+ const pieces = unzip<PIECE_SIZE, typeof k>(input, PIECE_SIZE, k);
12906
+ // and each piece get's ec-codec
12907
+ const points = pieces.map((p) => encodePoints(p));
12908
+ // hence we end up with a matrix of `points * k`
12909
+ type POINTS = FixedSizeArray<Bytes<POINT_LENGTH>, N_CHUNKS_TOTAL>;
12910
+ const pointsTyped: FixedSizeArray<POINTS, typeof k> = FixedSizeArray.new(points, k);
12911
+ // next we transpose the array, getting back an array of `N_CHUNKS_TOTAL` elements,
12912
+ // where each element is a `k` points (`Bytes<POINT_LENGTH>`).
12913
+ const transposed = transpose(pointsTyped, N_CHUNKS_TOTAL);
12914
+ // lastly we join each element of that resulting array
12915
+ // we get an array of `N_SHARDS_TOTAL` elements, each of length `POINT_LENGTH * k`.
12916
+ const chunks = transposed.map((c) => join(c));
12917
+ return FixedSizeArray.new(chunks, N_CHUNKS_TOTAL);
12918
+ }
12919
+
12920
+ /** Split each validator's shard into numbered chunks it originally should have got. */
12921
+ declare function shardsToChunks(spec: ChainSpec, shards: PerValidator<BytesBlob>): PerValidator<[number, BytesBlob][]> {
12922
+ const result: [number, BytesBlob][][] = [];
12923
+
12924
+ const shardSize = shards[0].length;
12925
+ check`
12926
+ ${shards.every((s) => s.length === shardSize)}
12927
+ Each shard must be the same length!
12928
+ `;
12929
+
12930
+ const totalData = shards.map((s) => s.length).reduce((sum, sLength) => sum + sLength, 0);
12931
+ const chunkSize = Math.floor(totalData / N_CHUNKS_TOTAL);
12932
+ const piecesPerChunk = Math.floor(shardSize / chunkSize);
12933
+
12934
+ let currentChunk = 0;
12935
+ for (const s of shards) {
12936
+ const validatorChunks: [number, BytesBlob][] = [];
12937
+ for (let i = 0; i < piecesPerChunk; i++) {
12938
+ const start = i * chunkSize;
12939
+ const end = start + chunkSize;
12940
+ const chunk = BytesBlob.blobFrom(s.raw.subarray(start, end));
12941
+ // TODO [ToDr] we may possibly have not enough data for some of the chunk here
12942
+ if (chunk.length === chunkSize) {
12943
+ validatorChunks.push([currentChunk, chunk]);
12944
+ }
12945
+
12946
+ currentChunk = (currentChunk + 1) % N_CHUNKS_TOTAL;
12947
+ }
12948
+ result.push(validatorChunks);
12949
+ }
12950
+
12951
+ return tryAsPerValidator(result, spec);
12952
+ }
12953
+
12954
+ /** Divide chunks between validators. */
12955
+ declare function chunksToShards(
12956
+ spec: ChainSpec,
12957
+ chunks: FixedSizeArray<BytesBlob, N_CHUNKS_TOTAL>,
12958
+ ): PerValidator<BytesBlob> {
12959
+ const result: BytesBlob[] = [];
12960
+
12961
+ const allChunks = BytesBlob.blobFromParts(chunks.map((c) => c.raw));
12962
+ const shardSize = allChunks.length / N_CHUNKS_TOTAL;
12963
+
12964
+ // wrap around the data to have enough
12965
+ const bytesToDrawFrom = BytesBlob.blobFromParts(allChunks.raw, allChunks.raw);
12966
+ const bytesPerValidator = Math.ceil(allChunks.length / spec.validatorsCount);
12967
+ // align number of bytes to the shard length.
12968
+ const alignedBytesPerValidator = Math.ceil(bytesPerValidator / shardSize) * shardSize;
12969
+
12970
+ for (let i = 0; i < spec.validatorsCount; i++) {
12971
+ const start = i * alignedBytesPerValidator;
12972
+ const end = start + alignedBytesPerValidator;
12973
+
12974
+ result.push(BytesBlob.blobFrom(bytesToDrawFrom.raw.subarray(start, end)));
12975
+ }
12976
+
12977
+ return tryAsPerValidator(result, spec);
12978
+ }
12979
+
12980
+ declare const initEc = async () => {
12981
+ await init.reedSolomon();
12982
+ };
12983
+
12984
+ declare const index$b_HALF_POINT_SIZE: typeof HALF_POINT_SIZE;
12985
+ declare const index$b_N_CHUNKS_REDUNDANCY: typeof N_CHUNKS_REDUNDANCY;
12986
+ type index$b_N_CHUNKS_REQUIRED = N_CHUNKS_REQUIRED;
12987
+ type index$b_N_CHUNKS_TOTAL = N_CHUNKS_TOTAL;
12988
+ type index$b_PIECE_SIZE = PIECE_SIZE;
12989
+ declare const index$b_POINT_ALIGNMENT: typeof POINT_ALIGNMENT;
12990
+ type index$b_POINT_LENGTH = POINT_LENGTH;
12991
+ declare const index$b_checkConsistency: typeof checkConsistency;
12992
+ declare const index$b_chunkingFunction: typeof chunkingFunction;
12993
+ declare const index$b_chunksToShards: typeof chunksToShards;
12994
+ declare const index$b_decodeData: typeof decodeData;
12995
+ declare const index$b_decodeDataAndTrim: typeof decodeDataAndTrim;
12996
+ declare const index$b_decodePiece: typeof decodePiece;
12997
+ declare const index$b_encodePoints: typeof encodePoints;
12998
+ declare const index$b_initEc: typeof initEc;
12999
+ declare const index$b_join: typeof join;
13000
+ declare const index$b_lace: typeof lace;
13001
+ declare const index$b_padAndEncodeData: typeof padAndEncodeData;
13002
+ declare const index$b_shardsToChunks: typeof shardsToChunks;
13003
+ declare const index$b_split: typeof split;
13004
+ declare const index$b_transpose: typeof transpose;
13005
+ declare const index$b_unzip: typeof unzip;
13006
+ declare namespace index$b {
13007
+ export { index$b_HALF_POINT_SIZE as HALF_POINT_SIZE, index$b_N_CHUNKS_REDUNDANCY as N_CHUNKS_REDUNDANCY, index$b_POINT_ALIGNMENT as POINT_ALIGNMENT, index$b_checkConsistency as checkConsistency, index$b_chunkingFunction as chunkingFunction, index$b_chunksToShards as chunksToShards, index$b_decodeData as decodeData, index$b_decodeDataAndTrim as decodeDataAndTrim, index$b_decodePiece as decodePiece, index$b_encodePoints as encodePoints, index$b_initEc as initEc, index$b_join as join, index$b_lace as lace, index$b_padAndEncodeData as padAndEncodeData, index$b_shardsToChunks as shardsToChunks, index$b_split as split, index$b_transpose as transpose, index$b_unzip as unzip };
13008
+ export type { index$b_N_CHUNKS_REQUIRED as N_CHUNKS_REQUIRED, index$b_N_CHUNKS_TOTAL as N_CHUNKS_TOTAL, index$b_PIECE_SIZE as PIECE_SIZE, index$b_POINT_LENGTH as POINT_LENGTH };
13009
+ }
13010
+
13011
+ /** A per-client handler of incoming socket messages. */
13012
+ interface IpcHandler {
13013
+ /** New data on the socket received. */
13014
+ onSocketMessage(msg: Uint8Array): Promise<void>;
13015
+
13016
+ /** Socket closed or errored. */
13017
+ onClose(reason: { error?: Error }): void;
13018
+ }
13019
+
13020
+ /** Sending data abstraction on a socket. */
13021
+ interface IpcSender {
13022
+ /** Write given data to the outgoing socket. */
13023
+ send(data: BytesBlob): void;
13024
+
13025
+ /** Close the socket. */
13026
+ close(): void;
13027
+ }
13028
+
13029
+ /**
13030
+ * Version ::= SEQUENCE {
13031
+ * major INTEGER (0..255),
13032
+ * minor INTEGER (0..255),
13033
+ * patch INTEGER (0..255)
13034
+ * }
13035
+ */
13036
+ declare class Version extends WithDebug {
13037
+ static Codec = codec.Class(Version, {
13038
+ major: codec.u8,
13039
+ minor: codec.u8,
13040
+ patch: codec.u8,
13041
+ });
13042
+
13043
+ static tryFromString(str: string): Version {
13044
+ const parse = (v: string) => tryAsU8(Number(v));
13045
+ try {
13046
+ const [major, minor, patch] = str.trim().split(".").map(parse);
13047
+
13048
+ return Version.create({
13049
+ major,
13050
+ minor,
13051
+ patch,
13052
+ });
13053
+ } catch (e) {
13054
+ throw new Error(`Unable to parse ${str} as Version: ${e}`);
13055
+ }
13056
+ }
13057
+
13058
+ static create({ major, minor, patch }: CodecRecord<Version>) {
13059
+ return new Version(major, minor, patch);
13060
+ }
13061
+
13062
+ private constructor(
13063
+ public readonly major: U8,
13064
+ public readonly minor: U8,
13065
+ public readonly patch: U8,
13066
+ ) {
13067
+ super();
13068
+ }
13069
+ }
13070
+
13071
+ /**
13072
+ * Fuzzer Protocol V1
13073
+ * Reference: https://github.com/davxy/jam-conformance/blob/main/fuzz-proto/fuzz.asn
13074
+ */
13075
+ // Feature bit constants
13076
+ declare enum Features {
13077
+ Ancestry = 1, // 2^0
13078
+ Fork = 2, // 2^1
13079
+ Reserved = 2147483648, // 2^31
13080
+ }
13081
+
13082
+ /**
13083
+ * PeerInfo ::= SEQUENCE {
13084
+ * fuzz-version U8,
13085
+ * features Features,
13086
+ * jam-version Version,
13087
+ * app-version Version,
13088
+ * name UTF8String
13089
+ * }
13090
+ */
13091
+ declare class PeerInfo extends WithDebug {
13092
+ static Codec = codec.Class(PeerInfo, {
13093
+ fuzzVersion: codec.u8,
13094
+ features: codec.u32,
13095
+ jamVersion: Version.Codec,
13096
+ appVersion: Version.Codec,
13097
+ name: codec.string,
13098
+ });
13099
+
13100
+ static create({ fuzzVersion, features, appVersion, jamVersion, name }: CodecRecord<PeerInfo>) {
13101
+ return new PeerInfo(fuzzVersion, features, jamVersion, appVersion, name);
13102
+ }
13103
+
13104
+ private constructor(
13105
+ public readonly fuzzVersion: U8,
13106
+ public readonly features: U32,
13107
+ public readonly jamVersion: Version,
13108
+ public readonly appVersion: Version,
13109
+ public readonly name: string,
13110
+ ) {
13111
+ super();
13112
+ }
13113
+ }
13114
+
13115
+ /**
13116
+ * AncestryItem ::= SEQUENCE {
13117
+ * slot TimeSlot,
13118
+ * header-hash HeaderHash
13119
+ * }
13120
+ */
13121
+ declare class AncestryItem extends WithDebug {
13122
+ static Codec = codec.Class(AncestryItem, {
13123
+ slot: codec.u32.asOpaque<TimeSlot>(),
13124
+ headerHash: codec.bytes(HASH_SIZE).asOpaque<HeaderHash>(),
13125
+ });
13126
+
13127
+ static create({ slot, headerHash }: CodecRecord<AncestryItem>) {
13128
+ return new AncestryItem(slot, headerHash);
13129
+ }
13130
+
13131
+ private constructor(
13132
+ public readonly slot: TimeSlot,
13133
+ public readonly headerHash: HeaderHash,
13134
+ ) {
13135
+ super();
13136
+ }
13137
+ }
13138
+
13139
+ /**
13140
+ * KeyValue ::= SEQUENCE {
13141
+ * key TrieKey,
13142
+ * value OCTET STRING
13143
+ * }
13144
+ */
13145
+ declare class KeyValue extends WithDebug {
13146
+ static Codec = codec.Class(KeyValue, {
13147
+ key: codec.bytes(TRUNCATED_HASH_SIZE),
13148
+ value: codec.blob,
13149
+ });
13150
+
13151
+ static create({ key, value }: CodecRecord<KeyValue>) {
13152
+ return new KeyValue(key, value);
13153
+ }
13154
+
13155
+ private constructor(
13156
+ public readonly key: TruncatedHash,
13157
+ public readonly value: BytesBlob,
13158
+ ) {
13159
+ super();
13160
+ }
13161
+ }
13162
+
13163
+ /** State ::= SEQUENCE OF KeyValue */
13164
+ declare const stateCodec = codec.sequenceVarLen(KeyValue.Codec);
13165
+
13166
+ /**
13167
+ * Ancestry ::= SEQUENCE (SIZE(0..24)) OF AncestryItem
13168
+ * Empty when `feature-ancestry` is not supported by both parties
13169
+ */
13170
+ declare const ancestryCodec = codec.sequenceVarLen(AncestryItem.Codec, {
13171
+ minLength: 0,
13172
+ maxLength: 24,
13173
+ });
13174
+ type Ancestry = AncestryItem[];
13175
+
13176
+ /**
13177
+ * Initialize ::= SEQUENCE {
13178
+ * header Header,
13179
+ * keyvals State,
13180
+ * ancestry Ancestry
13181
+ * }
13182
+ */
13183
+ declare class Initialize extends WithDebug {
13184
+ static Codec = codec.Class(Initialize, {
13185
+ header: Header.Codec,
13186
+ keyvals: stateCodec,
13187
+ ancestry: ancestryCodec,
13188
+ });
13189
+
13190
+ static create({ header, keyvals, ancestry }: CodecRecord<Initialize>) {
13191
+ return new Initialize(header, keyvals, ancestry);
13192
+ }
13193
+
13194
+ private constructor(
13195
+ public readonly header: Header,
13196
+ public readonly keyvals: KeyValue[],
13197
+ public readonly ancestry: Ancestry,
13198
+ ) {
13199
+ super();
13200
+ }
13201
+ }
13202
+
13203
+ /** GetState ::= HeaderHash */
13204
+ declare const getStateCodec = codec.bytes(HASH_SIZE).asOpaque<HeaderHash>();
13205
+ type GetState = HeaderHash;
13206
+
13207
+ /** StateRoot ::= StateRootHash */
13208
+ declare const stateRootCodec = codec.bytes(HASH_SIZE).asOpaque<StateRootHash>();
13209
+ type StateRoot = StateRootHash;
13210
+
13211
+ /** Error ::= UTF8String */
13212
+ declare class ErrorMessage extends WithDebug {
13213
+ static Codec = codec.Class(ErrorMessage, {
13214
+ message: codec.string,
13215
+ });
13216
+
13217
+ static create({ message }: CodecRecord<ErrorMessage>): ErrorMessage {
13218
+ return new ErrorMessage(message);
13219
+ }
13220
+
13221
+ private constructor(public readonly message: string) {
13222
+ super();
13223
+ }
13224
+ }
13225
+
13226
+ /** Message choice type tags */
13227
+ declare enum MessageType {
13228
+ PeerInfo = 0,
13229
+ Initialize = 1,
13230
+ StateRoot = 2,
13231
+ ImportBlock = 3,
13232
+ GetState = 4,
13233
+ State = 5,
13234
+ Error = 255,
12773
13235
  }
12774
13236
 
13237
+ /** Message data union */
13238
+ type MessageData =
13239
+ | { type: MessageType.PeerInfo; value: PeerInfo }
13240
+ | { type: MessageType.Initialize; value: Initialize }
13241
+ | { type: MessageType.StateRoot; value: StateRoot }
13242
+ | { type: MessageType.ImportBlock; value: BlockView }
13243
+ | { type: MessageType.GetState; value: GetState }
13244
+ | { type: MessageType.State; value: KeyValue[] }
13245
+ | { type: MessageType.Error; value: ErrorMessage };
13246
+
12775
13247
  /**
12776
- * `T`: Transposing function which accepts an array of `K` pieces of data
12777
- * which each have same lenght of `N` octets and returns an array of `N`
12778
- * pieces of data which each have length of `K` octets.
12779
- *
12780
- * T[[x0,0, x0,1, x0,2, . . . ], [x1,0, x1,1, . . . ], . . . ] ≡
12781
- * [[x0,0, x1,0, x2,0, . . . ], [x0,1, x1,1, . . . ], . . . ]
12782
- *
12783
- * https://graypaper.fluffylabs.dev/#/9a08063/3e2e023e2e02?v=0.6.6
13248
+ * Message ::= CHOICE {
13249
+ * peer-info [0] PeerInfo,
13250
+ * initialize [1] Initialize,
13251
+ * state-root [2] StateRoot,
13252
+ * import-block [3] ImportBlock,
13253
+ * get-state [4] GetState,
13254
+ * state [5] State,
13255
+ * error [255] Error
13256
+ * }
12784
13257
  */
12785
- declare function transpose<T, N extends number, K extends number>(
12786
- input: FixedSizeArray<FixedSizeArray<T, K>, N>,
12787
- k: K,
12788
- ): FixedSizeArray<FixedSizeArray<T, N>, K> {
12789
- const n = input.fixedLength;
12790
- const columns: FixedSizeArray<T, N>[] = [];
12791
-
12792
- for (let c = 0; c < k; c++) {
12793
- const newColumn: T[] = [];
12794
- for (let r = 0; r < n; r++) {
12795
- const cell = input[r][c];
12796
- newColumn.push(cell);
13258
+ declare const messageCodec = codec.custom<MessageData>(
13259
+ {
13260
+ name: "Message",
13261
+ sizeHint: { bytes: 1, isExact: false },
13262
+ },
13263
+ (e, msg) => {
13264
+ e.i8(msg.type);
13265
+ switch (msg.type) {
13266
+ case MessageType.PeerInfo:
13267
+ PeerInfo.Codec.encode(e, msg.value);
13268
+ break;
13269
+ case MessageType.Initialize:
13270
+ Initialize.Codec.encode(e, msg.value);
13271
+ break;
13272
+ case MessageType.StateRoot:
13273
+ stateRootCodec.encode(e, msg.value);
13274
+ break;
13275
+ case MessageType.ImportBlock:
13276
+ Block.Codec.View.encode(e, msg.value);
13277
+ break;
13278
+ case MessageType.GetState:
13279
+ getStateCodec.encode(e, msg.value);
13280
+ break;
13281
+ case MessageType.State:
13282
+ stateCodec.encode(e, msg.value);
13283
+ break;
13284
+ case MessageType.Error:
13285
+ ErrorMessage.Codec.encode(e, msg.value);
13286
+ break;
13287
+ default:
13288
+ throw new Error(`Unknown message type: ${msg}`);
12797
13289
  }
12798
- columns.push(FixedSizeArray.new(newColumn, n));
12799
- }
12800
- return FixedSizeArray.new(columns, k);
12801
- }
13290
+ },
13291
+ (d): MessageData => {
13292
+ const type = d.u8();
13293
+ switch (type) {
13294
+ case MessageType.PeerInfo:
13295
+ return { type: MessageType.PeerInfo, value: PeerInfo.Codec.decode(d) };
13296
+ case MessageType.Initialize:
13297
+ return { type: MessageType.Initialize, value: Initialize.Codec.decode(d) };
13298
+ case MessageType.StateRoot:
13299
+ return { type: MessageType.StateRoot, value: stateRootCodec.decode(d) };
13300
+ case MessageType.ImportBlock:
13301
+ return { type: MessageType.ImportBlock, value: Block.Codec.View.decode(d) };
13302
+ case MessageType.GetState:
13303
+ return { type: MessageType.GetState, value: getStateCodec.decode(d) };
13304
+ case MessageType.State:
13305
+ return { type: MessageType.State, value: stateCodec.decode(d) };
13306
+ case MessageType.Error:
13307
+ return { type: MessageType.Error, value: ErrorMessage.Codec.decode(d) };
13308
+ default:
13309
+ throw new Error(`Unknown message type: ${type}`);
13310
+ }
13311
+ },
13312
+ (s) => {
13313
+ const type = s.decoder.u8();
13314
+ switch (type) {
13315
+ case MessageType.PeerInfo:
13316
+ PeerInfo.Codec.View.skip(s);
13317
+ break;
13318
+ case MessageType.Initialize:
13319
+ Initialize.Codec.View.skip(s);
13320
+ break;
13321
+ case MessageType.StateRoot:
13322
+ stateRootCodec.View.skip(s);
13323
+ break;
13324
+ case MessageType.ImportBlock:
13325
+ Block.Codec.View.skip(s);
13326
+ break;
13327
+ case MessageType.GetState:
13328
+ getStateCodec.View.skip(s);
13329
+ break;
13330
+ case MessageType.State:
13331
+ stateCodec.View.skip(s);
13332
+ break;
13333
+ case MessageType.Error:
13334
+ ErrorMessage.Codec.View.skip(s);
13335
+ break;
13336
+ default:
13337
+ throw new Error(`Unknown message type: ${type}`);
13338
+ }
13339
+ },
13340
+ );
13341
+
13342
+ type Message = MessageData;
13343
+
13344
+ declare const logger$1 = Logger.new(import.meta.filename, "ext-ipc-fuzz-v1");
12802
13345
 
12803
13346
  /**
12804
- * `C`: Erasure-code chunking function which accepts an arbitrary sized data blob whose
12805
- * length divides wholly into `PIECE_SIZE` octets and results in `N_CHUNKS_TOTAL`
12806
- * sequences of sequences, each of `POINT_LENGTH * K` octets blobs.
12807
- * Where `K` is the number that divides input length by `PIECE_SIZE`.
12808
- *
12809
- * Each element of resulting array is the same length.
12810
- *
12811
- * https://graypaper.fluffylabs.dev/#/9a08063/3f15003f1500?v=0.6.6
13347
+ * Handler interface for v1 fuzzer protocol messages.
13348
+ * https://github.com/davxy/jam-conformance/blob/main/fuzz-proto/fuzz-v1.asn
12812
13349
  */
12813
- declare function chunkingFunction(input: BytesBlob): FixedSizeArray<BytesBlob, N_CHUNKS_TOTAL> {
12814
- const k = Math.floor(input.length / PIECE_SIZE);
12815
- check`${k * PIECE_SIZE === input.length} Input length ${input.length} is not divisible by ${PIECE_SIZE}`;
13350
+ interface FuzzMessageHandler {
13351
+ /**
13352
+ * Handshake and versioning exchange.
13353
+ * Target waits to receive the fuzzer's PeerInfo message before sending its own.
13354
+ */
13355
+ getPeerInfo(value: PeerInfo): Promise<PeerInfo>;
12816
13356
 
12817
- // we get a `k` pieces.
12818
- const pieces = unzip<PIECE_SIZE, typeof k>(input, PIECE_SIZE, k);
12819
- // and each piece get's ec-codec
12820
- const points = pieces.map((p) => encodePoints(p));
12821
- // hence we end up with a matrix of `points * k`
12822
- type POINTS = FixedSizeArray<Bytes<POINT_LENGTH>, N_CHUNKS_TOTAL>;
12823
- const pointsTyped: FixedSizeArray<POINTS, typeof k> = FixedSizeArray.new(points, k);
12824
- // next we transpose the array, getting back an array of `N_CHUNKS_TOTAL` elements,
12825
- // where each element is a `k` points (`Bytes<POINT_LENGTH>`).
12826
- const transposed = transpose(pointsTyped, N_CHUNKS_TOTAL);
12827
- // lastly we join each element of that resulting array
12828
- // we get an array of `N_SHARDS_TOTAL` elements, each of length `POINT_LENGTH * k`.
12829
- const chunks = transposed.map((c) => join(c));
12830
- return FixedSizeArray.new(chunks, N_CHUNKS_TOTAL);
13357
+ /**
13358
+ * Initialize or reset target state.
13359
+ * Returns the state root of the initialized state.
13360
+ */
13361
+ initialize(header: Initialize): Promise<StateRootHash>;
13362
+
13363
+ /**
13364
+ * Process block and return resulting state root.
13365
+ * May return an Error if the block import fails.
13366
+ */
13367
+ importBlock(value: BlockView): Promise<Result$2<StateRootHash, ErrorMessage>>;
13368
+
13369
+ /** Retrieve posterior state associated to given header hash. */
13370
+ getSerializedState(value: HeaderHash): Promise<KeyValue[]>;
12831
13371
  }
12832
13372
 
12833
- /** Split each validator's shard into numbered chunks it originally should have got. */
12834
- declare function shardsToChunks(spec: ChainSpec, shards: PerValidator<BytesBlob>): PerValidator<[number, BytesBlob][]> {
12835
- const result: [number, BytesBlob][][] = [];
13373
+ declare class FuzzTarget implements IpcHandler {
13374
+ private sessionFeatures = 0;
12836
13375
 
12837
- const shardSize = shards[0].length;
12838
- check`
12839
- ${shards.every((s) => s.length === shardSize)}
12840
- Each shard must be the same length!
12841
- `;
13376
+ constructor(
13377
+ public readonly msgHandler: FuzzMessageHandler,
13378
+ public readonly sender: IpcSender,
13379
+ public readonly spec: ChainSpec,
13380
+ ) {}
12842
13381
 
12843
- const totalData = shards.map((s) => s.length).reduce((sum, sLength) => sum + sLength, 0);
12844
- const chunkSize = Math.floor(totalData / N_CHUNKS_TOTAL);
12845
- const piecesPerChunk = Math.floor(shardSize / chunkSize);
13382
+ async onSocketMessage(msg: Uint8Array): Promise<void> {
13383
+ // attempt to decode the messsage
13384
+ try {
13385
+ const message = Decoder.decodeObject(messageCodec, msg, this.spec);
13386
+ logger.log`[${message.type}] incoming message`;
12846
13387
 
12847
- let currentChunk = 0;
12848
- for (const s of shards) {
12849
- const validatorChunks: [number, BytesBlob][] = [];
12850
- for (let i = 0; i < piecesPerChunk; i++) {
12851
- const start = i * chunkSize;
12852
- const end = start + chunkSize;
12853
- const chunk = BytesBlob.blobFrom(s.raw.subarray(start, end));
12854
- // TODO [ToDr] we may possibly have not enough data for some of the chunk here
12855
- if (chunk.length === chunkSize) {
12856
- validatorChunks.push([currentChunk, chunk]);
13388
+ await this.processAndRespond(message);
13389
+ } catch (e) {
13390
+ logger.error`Error while processing fuzz v1 message: ${e}`;
13391
+ logger.error`${e}`;
13392
+ if (e instanceof Error) {
13393
+ logger.error`${e.stack ?? ""}`;
12857
13394
  }
12858
-
12859
- currentChunk = (currentChunk + 1) % N_CHUNKS_TOTAL;
13395
+ this.sender.close();
12860
13396
  }
12861
- result.push(validatorChunks);
12862
13397
  }
12863
13398
 
12864
- return tryAsPerValidator(result, spec);
12865
- }
13399
+ private async processAndRespond(message: MessageData): Promise<void> {
13400
+ let response: Message | null = null;
12866
13401
 
12867
- /** Divide chunks between validators. */
12868
- declare function chunksToShards(
12869
- spec: ChainSpec,
12870
- chunks: FixedSizeArray<BytesBlob, N_CHUNKS_TOTAL>,
12871
- ): PerValidator<BytesBlob> {
12872
- const result: BytesBlob[] = [];
13402
+ switch (message.type) {
13403
+ case MessageType.PeerInfo: {
13404
+ // only support V1
13405
+ if (message.value.fuzzVersion !== 1) {
13406
+ logger.warn`Unsupported fuzzer protocol version: ${message.value.fuzzVersion}. Closing`;
13407
+ this.sender.close();
13408
+ return;
13409
+ }
12873
13410
 
12874
- const allChunks = BytesBlob.blobFromParts(chunks.map((c) => c.raw));
12875
- const shardSize = allChunks.length / N_CHUNKS_TOTAL;
13411
+ // Handle handshake
13412
+ const ourPeerInfo = await this.msgHandler.getPeerInfo(message.value);
12876
13413
 
12877
- // wrap around the data to have enough
12878
- const bytesToDrawFrom = BytesBlob.blobFromParts(allChunks.raw, allChunks.raw);
12879
- const bytesPerValidator = Math.ceil(allChunks.length / spec.validatorsCount);
12880
- // align number of bytes to the shard length.
12881
- const alignedBytesPerValidator = Math.ceil(bytesPerValidator / shardSize) * shardSize;
13414
+ // Calculate session features (intersection of both peer features)
13415
+ this.sessionFeatures = message.value.features & ourPeerInfo.features;
12882
13416
 
12883
- for (let i = 0; i < spec.validatorsCount; i++) {
12884
- const start = i * alignedBytesPerValidator;
12885
- const end = start + alignedBytesPerValidator;
13417
+ logger.info`Handshake completed. Shared features: 0b${this.sessionFeatures.toString(2)}`;
13418
+ logger.log`Feature ancestry: ${(this.sessionFeatures & Features.Ancestry) !== 0}`;
13419
+ logger.log`Feature fork: ${(this.sessionFeatures & Features.Fork) !== 0}`;
12886
13420
 
12887
- result.push(BytesBlob.blobFrom(bytesToDrawFrom.raw.subarray(start, end)));
12888
- }
13421
+ response = {
13422
+ type: MessageType.PeerInfo,
13423
+ value: ourPeerInfo,
13424
+ };
13425
+ break;
13426
+ }
12889
13427
 
12890
- return tryAsPerValidator(result, spec);
12891
- }
13428
+ case MessageType.Initialize: {
13429
+ const stateRoot = await this.msgHandler.initialize(message.value);
13430
+ response = {
13431
+ type: MessageType.StateRoot,
13432
+ value: stateRoot,
13433
+ };
13434
+ break;
13435
+ }
12892
13436
 
12893
- declare const initEc = async () => {
12894
- await init.reedSolomon();
12895
- };
13437
+ case MessageType.ImportBlock: {
13438
+ const result = await this.msgHandler.importBlock(message.value);
13439
+
13440
+ if (result.isOk) {
13441
+ response = {
13442
+ type: MessageType.StateRoot,
13443
+ value: result.ok,
13444
+ };
13445
+ } else {
13446
+ response = {
13447
+ type: MessageType.Error,
13448
+ value: result.error,
13449
+ };
13450
+ }
13451
+ break;
13452
+ }
13453
+
13454
+ case MessageType.GetState: {
13455
+ const state = await this.msgHandler.getSerializedState(message.value);
13456
+ response = {
13457
+ type: MessageType.State,
13458
+ value: state,
13459
+ };
13460
+ break;
13461
+ }
12896
13462
 
12897
- declare const index$9_HALF_POINT_SIZE: typeof HALF_POINT_SIZE;
12898
- declare const index$9_N_CHUNKS_REDUNDANCY: typeof N_CHUNKS_REDUNDANCY;
12899
- type index$9_N_CHUNKS_REQUIRED = N_CHUNKS_REQUIRED;
12900
- type index$9_N_CHUNKS_TOTAL = N_CHUNKS_TOTAL;
12901
- type index$9_PIECE_SIZE = PIECE_SIZE;
12902
- declare const index$9_POINT_ALIGNMENT: typeof POINT_ALIGNMENT;
12903
- type index$9_POINT_LENGTH = POINT_LENGTH;
12904
- declare const index$9_checkConsistency: typeof checkConsistency;
12905
- declare const index$9_chunkingFunction: typeof chunkingFunction;
12906
- declare const index$9_chunksToShards: typeof chunksToShards;
12907
- declare const index$9_decodeData: typeof decodeData;
12908
- declare const index$9_decodeDataAndTrim: typeof decodeDataAndTrim;
12909
- declare const index$9_decodePiece: typeof decodePiece;
12910
- declare const index$9_encodePoints: typeof encodePoints;
12911
- declare const index$9_initEc: typeof initEc;
12912
- declare const index$9_join: typeof join;
12913
- declare const index$9_lace: typeof lace;
12914
- declare const index$9_padAndEncodeData: typeof padAndEncodeData;
12915
- declare const index$9_shardsToChunks: typeof shardsToChunks;
12916
- declare const index$9_split: typeof split;
12917
- declare const index$9_transpose: typeof transpose;
12918
- declare const index$9_unzip: typeof unzip;
13463
+ case MessageType.StateRoot: {
13464
+ logger.log`--> Received unexpected 'StateRoot' message from the fuzzer. Closing.`;
13465
+ this.sender.close();
13466
+ return;
13467
+ }
13468
+
13469
+ case MessageType.State: {
13470
+ logger.log`--> Received unexpected 'State' message from the fuzzer. Closing.`;
13471
+ this.sender.close();
13472
+ return;
13473
+ }
13474
+
13475
+ case MessageType.Error: {
13476
+ logger.log`--> Received unexpected 'Error' message from the fuzzer. Closing.`;
13477
+ this.sender.close();
13478
+ return;
13479
+ }
13480
+
13481
+ default: {
13482
+ logger.log`--> Received unexpected message type ${JSON.stringify(message)} from the fuzzer. Closing.`;
13483
+ this.sender.close();
13484
+ try {
13485
+ assertNever(message);
13486
+ } catch {
13487
+ return;
13488
+ }
13489
+ }
13490
+ }
13491
+
13492
+ if (response !== null) {
13493
+ logger.trace`<-- responding with: ${response.type}`;
13494
+ const encoded = Encoder.encodeObject(messageCodec, response, this.spec);
13495
+ this.sender.send(encoded);
13496
+ } else {
13497
+ logger.warn`<-- no response generated for: ${message.type}`;
13498
+ }
13499
+ }
13500
+
13501
+ onClose({ error }: { error?: Error }): void {
13502
+ logger.log`Closing the v1 handler. Reason: ${error !== undefined ? error.message : "close"}.`;
13503
+ }
13504
+
13505
+ /** Check if a specific feature is enabled in the session */
13506
+ hasFeature(feature: number): boolean {
13507
+ return (this.sessionFeatures & feature) !== 0;
13508
+ }
13509
+ }
13510
+
13511
+ type index$a_Ancestry = Ancestry;
13512
+ type index$a_AncestryItem = AncestryItem;
13513
+ declare const index$a_AncestryItem: typeof AncestryItem;
13514
+ type index$a_ErrorMessage = ErrorMessage;
13515
+ declare const index$a_ErrorMessage: typeof ErrorMessage;
13516
+ type index$a_Features = Features;
13517
+ declare const index$a_Features: typeof Features;
13518
+ type index$a_FuzzMessageHandler = FuzzMessageHandler;
13519
+ type index$a_FuzzTarget = FuzzTarget;
13520
+ declare const index$a_FuzzTarget: typeof FuzzTarget;
13521
+ type index$a_GetState = GetState;
13522
+ type index$a_Initialize = Initialize;
13523
+ declare const index$a_Initialize: typeof Initialize;
13524
+ type index$a_KeyValue = KeyValue;
13525
+ declare const index$a_KeyValue: typeof KeyValue;
13526
+ type index$a_Message = Message;
13527
+ type index$a_MessageData = MessageData;
13528
+ type index$a_MessageType = MessageType;
13529
+ declare const index$a_MessageType: typeof MessageType;
13530
+ type index$a_PeerInfo = PeerInfo;
13531
+ declare const index$a_PeerInfo: typeof PeerInfo;
13532
+ type index$a_StateRoot = StateRoot;
13533
+ type index$a_Version = Version;
13534
+ declare const index$a_Version: typeof Version;
13535
+ declare const index$a_ancestryCodec: typeof ancestryCodec;
13536
+ declare const index$a_getStateCodec: typeof getStateCodec;
13537
+ declare const index$a_messageCodec: typeof messageCodec;
13538
+ declare const index$a_stateCodec: typeof stateCodec;
13539
+ declare const index$a_stateRootCodec: typeof stateRootCodec;
13540
+ declare namespace index$a {
13541
+ export { index$a_AncestryItem as AncestryItem, index$a_ErrorMessage as ErrorMessage, index$a_Features as Features, index$a_FuzzTarget as FuzzTarget, index$a_Initialize as Initialize, index$a_KeyValue as KeyValue, index$a_MessageType as MessageType, index$a_PeerInfo as PeerInfo, index$a_Version as Version, index$a_ancestryCodec as ancestryCodec, index$a_getStateCodec as getStateCodec, logger$1 as logger, index$a_messageCodec as messageCodec, index$a_stateCodec as stateCodec, index$a_stateRootCodec as stateRootCodec };
13542
+ export type { index$a_Ancestry as Ancestry, index$a_FuzzMessageHandler as FuzzMessageHandler, index$a_GetState as GetState, index$a_Message as Message, index$a_MessageData as MessageData, index$a_StateRoot as StateRoot };
13543
+ }
13544
+
13545
+ type index$9_IpcHandler = IpcHandler;
13546
+ type index$9_IpcSender = IpcSender;
12919
13547
  declare namespace index$9 {
12920
- export { index$9_HALF_POINT_SIZE as HALF_POINT_SIZE, index$9_N_CHUNKS_REDUNDANCY as N_CHUNKS_REDUNDANCY, index$9_POINT_ALIGNMENT as POINT_ALIGNMENT, index$9_checkConsistency as checkConsistency, index$9_chunkingFunction as chunkingFunction, index$9_chunksToShards as chunksToShards, index$9_decodeData as decodeData, index$9_decodeDataAndTrim as decodeDataAndTrim, index$9_decodePiece as decodePiece, index$9_encodePoints as encodePoints, index$9_initEc as initEc, index$9_join as join, index$9_lace as lace, index$9_padAndEncodeData as padAndEncodeData, index$9_shardsToChunks as shardsToChunks, index$9_split as split, index$9_transpose as transpose, index$9_unzip as unzip };
12921
- export type { index$9_N_CHUNKS_REQUIRED as N_CHUNKS_REQUIRED, index$9_N_CHUNKS_TOTAL as N_CHUNKS_TOTAL, index$9_PIECE_SIZE as PIECE_SIZE, index$9_POINT_LENGTH as POINT_LENGTH };
13548
+ export { index$a as v1 };
13549
+ export type { index$9_IpcHandler as IpcHandler, index$9_IpcSender as IpcSender };
12922
13550
  }
12923
13551
 
12924
13552
  /** Size of the transfer memo. */
@@ -13064,6 +13692,8 @@ declare enum NewServiceError {
13064
13692
  InsufficientFunds = 0,
13065
13693
  /** Service is not privileged to set gratis storage. */
13066
13694
  UnprivilegedService = 1,
13695
+ /** Registrar attempting to create a service with already existing id. */
13696
+ RegistrarServiceIdAlreadyTaken = 2,
13067
13697
  }
13068
13698
 
13069
13699
  declare enum UpdatePrivilegesError {
@@ -13119,25 +13749,28 @@ interface PartialState {
13119
13749
 
13120
13750
  /**
13121
13751
  * Transfer given `amount` of funds to the `destination`,
13122
- * passing `suppliedGas` to invoke `OnTransfer` entry point
13123
- * and given `memo`.
13752
+ * passing `gas` fee for transfer and given `memo`.
13124
13753
  */
13125
13754
  transfer(
13126
13755
  destination: ServiceId | null,
13127
13756
  amount: U64,
13128
- suppliedGas: ServiceGas,
13757
+ gas: ServiceGas,
13129
13758
  memo: Bytes<TRANSFER_MEMO_BYTES>,
13130
13759
  ): Result$2<OK, TransferError>;
13131
13760
 
13132
13761
  /**
13133
- * Create a new service with given codeHash, length, gas, allowance and gratisStorage.
13762
+ * Create a new service with given codeHash, length, gas, allowance, gratisStorage and wantedServiceId.
13763
+ *
13764
+ * Returns a newly assigned id
13765
+ * or `wantedServiceId` if it's lower than `S`
13766
+ * and parent of that service is `Registrar`.
13134
13767
  *
13135
- * Returns a newly assigned id of that service.
13136
- * https://graypaper.fluffylabs.dev/#/7e6ff6a/2f4c022f4c02?v=0.6.7
13768
+ * https://graypaper.fluffylabs.dev/#/ab2cdbd/2fa9042fc304?v=0.7.2
13137
13769
  *
13138
13770
  * An error can be returned in case the account does not
13139
13771
  * have the required balance
13140
- * or tries to set gratis storage without being privileged.
13772
+ * or tries to set gratis storage without being `Manager`
13773
+ * or `Registrar` tries to set service id thats already taken.
13141
13774
  */
13142
13775
  newService(
13143
13776
  codeHash: CodeHash,
@@ -13145,6 +13778,7 @@ interface PartialState {
13145
13778
  gas: ServiceGas,
13146
13779
  allowance: ServiceGas,
13147
13780
  gratisStorage: U64,
13781
+ wantedServiceId: U64,
13148
13782
  ): Result$2<ServiceId, NewServiceError>;
13149
13783
 
13150
13784
  /** Upgrade code of currently running service. */
@@ -13166,7 +13800,7 @@ interface PartialState {
13166
13800
  updateAuthorizationQueue(
13167
13801
  coreIndex: CoreIndex,
13168
13802
  authQueue: FixedSizeArray<Blake2bHash, AUTHORIZATION_QUEUE_SIZE>,
13169
- authManager: ServiceId | null,
13803
+ assigners: ServiceId | null,
13170
13804
  ): Result$2<OK, UpdatePrivilegesError>;
13171
13805
 
13172
13806
  /**
@@ -13175,14 +13809,16 @@ interface PartialState {
13175
13809
  * `m`: manager service (can change privileged services)
13176
13810
  * `a`: manages authorization queue
13177
13811
  * `v`: manages validator keys
13178
- * `g`: collection of serviceId -> gas that auto-accumulate every block
13812
+ * `r`: manages create new services in protected id range.
13813
+ * `z`: collection of serviceId -> gas that auto-accumulate every block
13179
13814
  *
13180
13815
  */
13181
13816
  updatePrivilegedServices(
13182
13817
  m: ServiceId | null,
13183
13818
  a: PerCore<ServiceId>,
13184
13819
  v: ServiceId | null,
13185
- g: [ServiceId, ServiceGas][],
13820
+ r: ServiceId | null,
13821
+ z: [ServiceId, ServiceGas][],
13186
13822
  ): Result$2<OK, UpdatePrivilegesError>;
13187
13823
 
13188
13824
  /** Yield accumulation trie result hash. */
@@ -13294,7 +13930,7 @@ declare class Mask {
13294
13930
  }
13295
13931
 
13296
13932
  private buildLookupTableForward(mask: BitVec) {
13297
- const table = new Uint8Array(mask.bitLength);
13933
+ const table = safeAllocUint8Array(mask.bitLength);
13298
13934
  let lastInstructionOffset = 0;
13299
13935
  for (let i = mask.bitLength - 1; i >= 0; i--) {
13300
13936
  if (mask.isSet(i)) {
@@ -13438,7 +14074,7 @@ declare class Registers {
13438
14074
  private asSigned: BigInt64Array;
13439
14075
  private asUnsigned: BigUint64Array;
13440
14076
 
13441
- constructor(private readonly bytes = new Uint8Array(NO_OF_REGISTERS << REGISTER_SIZE_SHIFT)) {
14077
+ constructor(private readonly bytes = safeAllocUint8Array(NO_OF_REGISTERS << REGISTER_SIZE_SHIFT)) {
13442
14078
  check`${bytes.length === NO_OF_REGISTERS << REGISTER_SIZE_SHIFT} Invalid size of registers array.`;
13443
14079
  this.asSigned = new BigInt64Array(bytes.buffer, bytes.byteOffset);
13444
14080
  this.asUnsigned = new BigUint64Array(bytes.buffer, bytes.byteOffset);
@@ -17100,7 +17736,7 @@ declare class AccumulationStateUpdate {
17100
17736
  /** Services state updates. */
17101
17737
  public readonly services: ServicesUpdate,
17102
17738
  /** Pending transfers. */
17103
- public readonly transfers: PendingTransfer[],
17739
+ public transfers: PendingTransfer[],
17104
17740
  /** Yielded accumulation root. */
17105
17741
  public readonly yieldedRoots: Map<ServiceId, OpaqueHash> = new Map(),
17106
17742
  ) {}
@@ -17151,11 +17787,18 @@ declare class AccumulationStateUpdate {
17151
17787
  if (from.privilegedServices !== null) {
17152
17788
  update.privilegedServices = PrivilegedServices.create({
17153
17789
  ...from.privilegedServices,
17154
- authManager: asKnownSize([...from.privilegedServices.authManager]),
17790
+ assigners: asKnownSize([...from.privilegedServices.assigners]),
17155
17791
  });
17156
17792
  }
17157
17793
  return update;
17158
17794
  }
17795
+
17796
+ /** Retrieve and clear pending transfers. */
17797
+ takeTransfers() {
17798
+ const transfers = this.transfers;
17799
+ this.transfers = [];
17800
+ return transfers;
17801
+ }
17159
17802
  }
17160
17803
 
17161
17804
  type StateSlice = Pick<State, "getService" | "privilegedServices">;
@@ -17422,7 +18065,7 @@ declare const HostCallResult = {
17422
18065
  OOB: tryAsU64(0xffff_ffff_ffff_fffdn), // 2**64 - 3
17423
18066
  /** Index unknown. */
17424
18067
  WHO: tryAsU64(0xffff_ffff_ffff_fffcn), // 2**64 - 4
17425
- /** Storage full. */
18068
+ /** Storage full or resource already allocated. */
17426
18069
  FULL: tryAsU64(0xffff_ffff_ffff_fffbn), // 2**64 - 5
17427
18070
  /** Core index unknown. */
17428
18071
  CORE: tryAsU64(0xffff_ffff_ffff_fffan), // 2**64 - 6
@@ -17430,7 +18073,7 @@ declare const HostCallResult = {
17430
18073
  CASH: tryAsU64(0xffff_ffff_ffff_fff9n), // 2**64 - 7
17431
18074
  /** Gas limit too low. */
17432
18075
  LOW: tryAsU64(0xffff_ffff_ffff_fff8n), // 2**64 - 8
17433
- /** The item is already solicited or cannot be forgotten. */
18076
+ /** The item is already solicited, cannot be forgotten or the operation is invalid due to privilege level. */
17434
18077
  HUH: tryAsU64(0xffff_ffff_ffff_fff7n), // 2**64 - 9
17435
18078
  /** The return value indicating general success. */
17436
18079
  OK: tryAsU64(0n),
@@ -17496,9 +18139,15 @@ type HostCallIndex = Opaque<U32, "HostCallIndex[U32]">;
17496
18139
  /** Attempt to convert a number into `HostCallIndex`. */
17497
18140
  declare const tryAsHostCallIndex = (v: number): HostCallIndex => asOpaqueType(tryAsU32(v));
17498
18141
 
18142
+ /**
18143
+ * Host-call exit reason.
18144
+ *
18145
+ * https://graypaper.fluffylabs.dev/#/ab2cdbd/24a30124a501?v=0.7.2
18146
+ */
17499
18147
  declare enum PvmExecution {
17500
18148
  Halt = 0,
17501
18149
  Panic = 1,
18150
+ OOG = 2, // out-of-gas
17502
18151
  }
17503
18152
 
17504
18153
  /** A utility function to easily trace a bunch of registers. */
@@ -17511,8 +18160,12 @@ interface HostCallHandler {
17511
18160
  /** Index of that host call (i.e. what PVM invokes via `ecalli`) */
17512
18161
  readonly index: HostCallIndex;
17513
18162
 
17514
- /** The gas cost of invocation of that host call. */
17515
- readonly gasCost: SmallGas | ((reg: IHostCallRegisters) => Gas);
18163
+ /**
18164
+ * The gas cost of invocation of that host call.
18165
+ *
18166
+ * NOTE: `((reg: IHostCallRegisters) => Gas)` function is for compatibility reasons: pre GP 0.7.2
18167
+ */
18168
+ readonly basicGasCost: SmallGas | ((reg: IHostCallRegisters) => Gas);
17516
18169
 
17517
18170
  /** Currently executing service id. */
17518
18171
  readonly currentServiceId: U32;
@@ -17655,7 +18308,7 @@ declare class HostCalls {
17655
18308
  const maybeAddress = regs.getLowerU32(7);
17656
18309
  const maybeLength = regs.getLowerU32(8);
17657
18310
 
17658
- const result = new Uint8Array(maybeLength);
18311
+ const result = safeAllocUint8Array(maybeLength);
17659
18312
  const startAddress = tryAsMemoryIndex(maybeAddress);
17660
18313
  const loadResult = memory.loadInto(result, startAddress);
17661
18314
 
@@ -17688,8 +18341,10 @@ declare class HostCalls {
17688
18341
 
17689
18342
  const hostCall = this.hostCalls.get(index);
17690
18343
  const gasBefore = gas.get();
17691
- const gasCost = typeof hostCall.gasCost === "number" ? hostCall.gasCost : hostCall.gasCost(regs);
17692
- const underflow = gas.sub(gasCost);
18344
+ // NOTE: `basicGasCost(regs)` function is for compatibility reasons: pre GP 0.7.2
18345
+ const basicGasCost =
18346
+ typeof hostCall.basicGasCost === "number" ? hostCall.basicGasCost : hostCall.basicGasCost(regs);
18347
+ const underflow = gas.sub(basicGasCost);
17693
18348
 
17694
18349
  const pcLog = `[PC: ${pvmInstance.getPC()}]`;
17695
18350
  if (underflow) {
@@ -17716,6 +18371,11 @@ declare class HostCalls {
17716
18371
  return this.getReturnValue(status, pvmInstance);
17717
18372
  }
17718
18373
 
18374
+ if (result === PvmExecution.OOG) {
18375
+ status = Status.OOG;
18376
+ return this.getReturnValue(status, pvmInstance);
18377
+ }
18378
+
17719
18379
  if (result === undefined) {
17720
18380
  pvmInstance.runProgram();
17721
18381
  status = pvmInstance.getStatus();
@@ -18087,7 +18747,7 @@ declare class DebuggerAdapter {
18087
18747
 
18088
18748
  if (page === null) {
18089
18749
  // page wasn't allocated so we return an empty page
18090
- return new Uint8Array(PAGE_SIZE);
18750
+ return safeAllocUint8Array(PAGE_SIZE);
18091
18751
  }
18092
18752
 
18093
18753
  if (page.length === PAGE_SIZE) {
@@ -18096,7 +18756,7 @@ declare class DebuggerAdapter {
18096
18756
  }
18097
18757
 
18098
18758
  // page was allocated but it is shorter than PAGE_SIZE so we have to extend it
18099
- const fullPage = new Uint8Array(PAGE_SIZE);
18759
+ const fullPage = safeAllocUint8Array(PAGE_SIZE);
18100
18760
  fullPage.set(page);
18101
18761
  return fullPage;
18102
18762
  }
@@ -18277,7 +18937,7 @@ declare const index$3_tryAsMachineId: typeof tryAsMachineId;
18277
18937
  declare const index$3_tryAsProgramCounter: typeof tryAsProgramCounter;
18278
18938
  declare const index$3_writeServiceIdAsLeBytes: typeof writeServiceIdAsLeBytes;
18279
18939
  declare namespace index$3 {
18280
- export { index$3_AccumulationStateUpdate as AccumulationStateUpdate, index$3_ArgsDecoder as ArgsDecoder, index$3_ArgumentType as ArgumentType, index$3_BasicBlocks as BasicBlocks, index$3_CURRENT_SERVICE_ID as CURRENT_SERVICE_ID, index$3_EjectError as EjectError, index$3_ExtendedWitdthImmediateDecoder as ExtendedWitdthImmediateDecoder, index$3_ForgetPreimageError as ForgetPreimageError, index$3_HostCallMemory as HostCallMemory, index$3_HostCallRegisters as HostCallRegisters, index$3_HostCallResult as HostCallResult, index$3_ImmediateDecoder as ImmediateDecoder, index$3_MAX_U32 as MAX_U32, index$3_MAX_U32_BIG_INT as MAX_U32_BIG_INT, index$3_MachineInstance as MachineInstance, index$3_Mask as Mask, index$3_MemoryOperation as MemoryOperation, index$3_MemorySegment as MemorySegment, NO_OF_REGISTERS$1 as NO_OF_REGISTERS, index$3_NewServiceError as NewServiceError, index$3_NibblesDecoder as NibblesDecoder, index$3_PagesError as PagesError, index$3_PartiallyUpdatedState as PartiallyUpdatedState, index$3_PeekPokeError as PeekPokeError, index$3_PendingTransfer as PendingTransfer, index$3_PreimageStatusKind as PreimageStatusKind, index$3_Program as Program, index$3_ProgramDecoder as ProgramDecoder, index$3_ProvidePreimageError as ProvidePreimageError, DebuggerAdapter as Pvm, index$3_Registers as Registers, index$3_RequestPreimageError as RequestPreimageError, Result$2 as Result, index$3_RichTaggedError as RichTaggedError, index$3_SERVICE_ID_BYTES as SERVICE_ID_BYTES, index$3_SpiMemory as SpiMemory, index$3_SpiProgram as SpiProgram, index$3_TransferError as TransferError, index$3_UpdatePrivilegesError as UpdatePrivilegesError, index$3_WithDebug as WithDebug, index$3_ZeroVoidError as ZeroVoidError, index$3___OPAQUE_TYPE__ as __OPAQUE_TYPE__, index$3_asOpaqueType as asOpaqueType, index$3_assertEmpty as assertEmpty, index$3_assertNever as assertNever, index$j as block, index$q as bytes, index$3_check as check, index$3_clampU64ToU32 as clampU64ToU32, index$3_createResults as createResults, index$3_decodeStandardProgram as decodeStandardProgram, index$3_extractCodeAndMetadata as extractCodeAndMetadata, index$3_getServiceId as getServiceId, index$3_getServiceIdOrCurrent as getServiceIdOrCurrent, index$n as hash, index$3_inspect as inspect, index$3_instructionArgumentTypeMap as instructionArgumentTypeMap, index$8 as interpreter, index$3_isBrowser as isBrowser, index$3_isTaggedError as isTaggedError, index$3_maybeTaggedErrorToString as maybeTaggedErrorToString, index$3_measure as measure, index$p as numbers, index$3_preimageLenAsU32 as preimageLenAsU32, index$3_resultToString as resultToString, index$3_seeThrough as seeThrough, index$3_slotsToPreimageStatus as slotsToPreimageStatus, index$3_toMemoryOperation as toMemoryOperation, index$3_tryAsMachineId as tryAsMachineId, index$3_tryAsProgramCounter as tryAsProgramCounter, index$3_writeServiceIdAsLeBytes as writeServiceIdAsLeBytes };
18940
+ export { index$3_AccumulationStateUpdate as AccumulationStateUpdate, index$3_ArgsDecoder as ArgsDecoder, index$3_ArgumentType as ArgumentType, index$3_BasicBlocks as BasicBlocks, index$3_CURRENT_SERVICE_ID as CURRENT_SERVICE_ID, index$3_EjectError as EjectError, index$3_ExtendedWitdthImmediateDecoder as ExtendedWitdthImmediateDecoder, index$3_ForgetPreimageError as ForgetPreimageError, index$3_HostCallMemory as HostCallMemory, index$3_HostCallRegisters as HostCallRegisters, index$3_HostCallResult as HostCallResult, index$3_ImmediateDecoder as ImmediateDecoder, index$3_MAX_U32 as MAX_U32, index$3_MAX_U32_BIG_INT as MAX_U32_BIG_INT, index$3_MachineInstance as MachineInstance, index$3_Mask as Mask, index$3_MemoryOperation as MemoryOperation, index$3_MemorySegment as MemorySegment, NO_OF_REGISTERS$1 as NO_OF_REGISTERS, index$3_NewServiceError as NewServiceError, index$3_NibblesDecoder as NibblesDecoder, index$3_PagesError as PagesError, index$3_PartiallyUpdatedState as PartiallyUpdatedState, index$3_PeekPokeError as PeekPokeError, index$3_PendingTransfer as PendingTransfer, index$3_PreimageStatusKind as PreimageStatusKind, index$3_Program as Program, index$3_ProgramDecoder as ProgramDecoder, index$3_ProvidePreimageError as ProvidePreimageError, DebuggerAdapter as Pvm, index$3_Registers as Registers, index$3_RequestPreimageError as RequestPreimageError, Result$2 as Result, index$3_RichTaggedError as RichTaggedError, index$3_SERVICE_ID_BYTES as SERVICE_ID_BYTES, index$3_SpiMemory as SpiMemory, index$3_SpiProgram as SpiProgram, index$3_TransferError as TransferError, index$3_UpdatePrivilegesError as UpdatePrivilegesError, index$3_WithDebug as WithDebug, index$3_ZeroVoidError as ZeroVoidError, index$3___OPAQUE_TYPE__ as __OPAQUE_TYPE__, index$3_asOpaqueType as asOpaqueType, index$3_assertEmpty as assertEmpty, index$3_assertNever as assertNever, index$l as block, index$s as bytes, index$3_check as check, index$3_clampU64ToU32 as clampU64ToU32, index$3_createResults as createResults, index$3_decodeStandardProgram as decodeStandardProgram, index$3_extractCodeAndMetadata as extractCodeAndMetadata, index$3_getServiceId as getServiceId, index$3_getServiceIdOrCurrent as getServiceIdOrCurrent, index$p as hash, index$3_inspect as inspect, index$3_instructionArgumentTypeMap as instructionArgumentTypeMap, index$8 as interpreter, index$3_isBrowser as isBrowser, index$3_isTaggedError as isTaggedError, index$3_maybeTaggedErrorToString as maybeTaggedErrorToString, index$3_measure as measure, index$r as numbers, index$3_preimageLenAsU32 as preimageLenAsU32, index$3_resultToString as resultToString, index$3_seeThrough as seeThrough, index$3_slotsToPreimageStatus as slotsToPreimageStatus, index$3_toMemoryOperation as toMemoryOperation, index$3_tryAsMachineId as tryAsMachineId, index$3_tryAsProgramCounter as tryAsProgramCounter, index$3_writeServiceIdAsLeBytes as writeServiceIdAsLeBytes };
18281
18941
  export type { index$3_Args as Args, index$3_EnumMapping as EnumMapping, index$3_ErrorResult as ErrorResult, index$3_IHostCallMemory as IHostCallMemory, index$3_IHostCallRegisters as IHostCallRegisters, index$3_InsufficientFundsError as InsufficientFundsError, index$3_MachineId as MachineId, index$3_MachineResult as MachineResult, index$3_MachineStatus as MachineStatus, index$3_NoMachineError as NoMachineError, index$3_OK as OK, index$3_OkResult as OkResult, index$3_Opaque as Opaque, index$3_PartialState as PartialState, index$3_PreimageStatus as PreimageStatus, index$3_ProgramCounter as ProgramCounter, index$3_RefineExternalities as RefineExternalities, index$3_SegmentExportError as SegmentExportError, index$3_ServiceStateUpdate as ServiceStateUpdate, index$3_StateSlice as StateSlice, index$3_StringLiteral as StringLiteral, index$3_TRANSFER_MEMO_BYTES as TRANSFER_MEMO_BYTES, index$3_TaggedError as TaggedError, index$3_TokenOf as TokenOf, index$3_Uninstantiable as Uninstantiable, index$3_UnprivilegedError as UnprivilegedError, index$3_WithOpaque as WithOpaque };
18282
18942
  }
18283
18943
 
@@ -18289,10 +18949,10 @@ type ENTROPY_BYTES = typeof ENTROPY_BYTES;
18289
18949
  *
18290
18950
  * https://graypaper.fluffylabs.dev/#/579bd12/3b9a013b9a01
18291
18951
  */
18292
- declare function fisherYatesShuffle<T>(arr: T[], entropy: Bytes<ENTROPY_BYTES>): T[] {
18952
+ declare function fisherYatesShuffle<T>(blake2b: Blake2b, arr: T[], entropy: Bytes<ENTROPY_BYTES>): T[] {
18293
18953
  check`${entropy.length === ENTROPY_BYTES} Expected entropy of length ${ENTROPY_BYTES}, got ${entropy.length}`;
18294
18954
  const n = arr.length;
18295
- const randomNumbers = hashToNumberSequence(entropy, arr.length);
18955
+ const randomNumbers = hashToNumberSequence(blake2b, entropy, arr.length);
18296
18956
  const result: T[] = new Array<T>(n);
18297
18957
 
18298
18958
  let itemsLeft = n;
@@ -18318,6 +18978,7 @@ declare namespace index$2 {
18318
18978
  declare class JsonServiceInfo {
18319
18979
  static fromJson = json.object<JsonServiceInfo, ServiceAccountInfo>(
18320
18980
  {
18981
+ ...(Compatibility.isGreaterOrEqual(GpVersion.V0_7_1) ? { version: "number" } : {}),
18321
18982
  code_hash: fromJson.bytes32(),
18322
18983
  balance: json.fromNumber((x) => tryAsU64(x)),
18323
18984
  min_item_gas: json.fromNumber((x) => tryAsServiceGas(x)),
@@ -18356,6 +19017,7 @@ declare class JsonServiceInfo {
18356
19017
  },
18357
19018
  );
18358
19019
 
19020
+ version?: number;
18359
19021
  code_hash!: CodeHash;
18360
19022
  balance!: U64;
18361
19023
  min_item_gas!: ServiceGas;
@@ -18402,6 +19064,19 @@ declare const lookupMetaFromJson = json.object<JsonLookupMeta, LookupHistoryItem
18402
19064
  ({ key, value }) => new LookupHistoryItem(key.hash, key.length, value),
18403
19065
  );
18404
19066
 
19067
+ declare const preimageStatusFromJson = json.object<JsonPreimageStatus, LookupHistoryItem>(
19068
+ {
19069
+ hash: fromJson.bytes32(),
19070
+ status: json.array("number"),
19071
+ },
19072
+ ({ hash, status }) => new LookupHistoryItem(hash, tryAsU32(0), status),
19073
+ );
19074
+
19075
+ type JsonPreimageStatus = {
19076
+ hash: PreimageHash;
19077
+ status: LookupHistorySlots;
19078
+ };
19079
+
18405
19080
  type JsonLookupMeta = {
18406
19081
  key: {
18407
19082
  hash: PreimageHash;
@@ -18414,21 +19089,34 @@ declare class JsonService {
18414
19089
  static fromJson = json.object<JsonService, InMemoryService>(
18415
19090
  {
18416
19091
  id: "number",
18417
- data: {
18418
- service: JsonServiceInfo.fromJson,
18419
- preimages: json.optional(json.array(JsonPreimageItem.fromJson)),
18420
- storage: json.optional(json.array(JsonStorageItem.fromJson)),
18421
- lookup_meta: json.optional(json.array(lookupMetaFromJson)),
18422
- },
19092
+ data: Compatibility.isLessThan(GpVersion.V0_7_1)
19093
+ ? {
19094
+ service: JsonServiceInfo.fromJson,
19095
+ preimages: json.optional(json.array(JsonPreimageItem.fromJson)),
19096
+ storage: json.optional(json.array(JsonStorageItem.fromJson)),
19097
+ lookup_meta: json.optional(json.array(lookupMetaFromJson)),
19098
+ }
19099
+ : {
19100
+ service: JsonServiceInfo.fromJson,
19101
+ storage: json.optional(json.array(JsonStorageItem.fromJson)),
19102
+ preimages_blob: json.optional(json.array(JsonPreimageItem.fromJson)),
19103
+ preimages_status: json.optional(json.array(preimageStatusFromJson)),
19104
+ },
18423
19105
  },
18424
19106
  ({ id, data }) => {
19107
+ const preimages = HashDictionary.fromEntries(
19108
+ (data.preimages ?? data.preimages_blob ?? []).map((x) => [x.hash, x]),
19109
+ );
19110
+
18425
19111
  const lookupHistory = HashDictionary.new<PreimageHash, LookupHistoryItem[]>();
18426
- for (const item of data.lookup_meta ?? []) {
19112
+
19113
+ for (const item of data.lookup_meta ?? data.preimages_status ?? []) {
18427
19114
  const data = lookupHistory.get(item.hash) ?? [];
18428
- data.push(item);
19115
+ const length = tryAsU32(preimages.get(item.hash)?.blob.length ?? item.length);
19116
+ data.push(new LookupHistoryItem(item.hash, length, item.slots));
18429
19117
  lookupHistory.set(item.hash, data);
18430
19118
  }
18431
- const preimages = HashDictionary.fromEntries((data.preimages ?? []).map((x) => [x.hash, x]));
19119
+
18432
19120
  const storage = new Map<string, StorageItem>();
18433
19121
 
18434
19122
  const entries = (data.storage ?? []).map(({ key, value }) => {
@@ -18455,6 +19143,8 @@ declare class JsonService {
18455
19143
  preimages?: JsonPreimageItem[];
18456
19144
  storage?: JsonStorageItem[];
18457
19145
  lookup_meta?: LookupHistoryItem[];
19146
+ preimages_blob?: JsonPreimageItem[];
19147
+ preimages_status?: LookupHistoryItem[];
18458
19148
  };
18459
19149
  }
18460
19150
 
@@ -18464,8 +19154,7 @@ declare const availabilityAssignmentFromJson = json.object<JsonAvailabilityAssig
18464
19154
  timeout: "number",
18465
19155
  },
18466
19156
  ({ report, timeout }) => {
18467
- const workReportHash = blake2b.hashBytes(Encoder.encodeObject(WorkReport.Codec, report)).asOpaque();
18468
- return AvailabilityAssignment.create({ workReport: new WithHash(workReportHash, report), timeout });
19157
+ return AvailabilityAssignment.create({ workReport: report, timeout });
18469
19158
  },
18470
19159
  );
18471
19160
 
@@ -18686,8 +19375,12 @@ declare class JsonServiceStatistics {
18686
19375
  extrinsic_count: "number",
18687
19376
  accumulate_count: "number",
18688
19377
  accumulate_gas_used: json.fromNumber(tryAsServiceGas),
18689
- on_transfers_count: "number",
18690
- on_transfers_gas_used: json.fromNumber(tryAsServiceGas),
19378
+ ...(Compatibility.isLessThan(GpVersion.V0_7_1)
19379
+ ? {
19380
+ on_transfers_count: "number",
19381
+ on_transfers_gas_used: json.fromNumber(tryAsServiceGas),
19382
+ }
19383
+ : {}),
18691
19384
  },
18692
19385
  ({
18693
19386
  provided_count,
@@ -18714,8 +19407,8 @@ declare class JsonServiceStatistics {
18714
19407
  extrinsicCount: extrinsic_count,
18715
19408
  accumulateCount: accumulate_count,
18716
19409
  accumulateGasUsed: accumulate_gas_used,
18717
- onTransfersCount: on_transfers_count,
18718
- onTransfersGasUsed: on_transfers_gas_used,
19410
+ onTransfersCount: on_transfers_count ?? tryAsU32(0),
19411
+ onTransfersGasUsed: on_transfers_gas_used ?? tryAsServiceGas(0),
18719
19412
  });
18720
19413
  },
18721
19414
  );
@@ -18730,8 +19423,8 @@ declare class JsonServiceStatistics {
18730
19423
  extrinsic_count!: U16;
18731
19424
  accumulate_count!: U32;
18732
19425
  accumulate_gas_used!: ServiceGas;
18733
- on_transfers_count!: U32;
18734
- on_transfers_gas_used!: ServiceGas;
19426
+ on_transfers_count?: U32;
19427
+ on_transfers_gas_used?: ServiceGas;
18735
19428
  }
18736
19429
 
18737
19430
  type ServiceStatisticsEntry = {
@@ -18803,8 +19496,9 @@ type JsonStateDump = {
18803
19496
  tau: State["timeslot"];
18804
19497
  chi: {
18805
19498
  chi_m: PrivilegedServices["manager"];
18806
- chi_a: PrivilegedServices["authManager"];
18807
- chi_v: PrivilegedServices["validatorsManager"];
19499
+ chi_a: PrivilegedServices["assigners"];
19500
+ chi_v: PrivilegedServices["delegator"];
19501
+ chi_r?: PrivilegedServices["registrar"];
18808
19502
  chi_g: PrivilegedServices["autoAccumulateServices"] | null;
18809
19503
  };
18810
19504
  pi: JsonStatisticsData;
@@ -18837,6 +19531,7 @@ declare const fullStateDumpFromJson = (spec: ChainSpec) =>
18837
19531
  chi_m: "number",
18838
19532
  chi_a: json.array("number"),
18839
19533
  chi_v: "number",
19534
+ chi_r: json.optional("number"),
18840
19535
  chi_g: json.nullable(
18841
19536
  json.array({
18842
19537
  service: "number",
@@ -18869,6 +19564,9 @@ declare const fullStateDumpFromJson = (spec: ChainSpec) =>
18869
19564
  theta,
18870
19565
  accounts,
18871
19566
  }): InMemoryState => {
19567
+ if (Compatibility.isGreaterOrEqual(GpVersion.V0_7_1) && chi.chi_r === undefined) {
19568
+ throw new Error("Registrar is required in Privileges GP ^0.7.1");
19569
+ }
18872
19570
  return InMemoryState.create({
18873
19571
  authPools: tryAsPerCore(
18874
19572
  alpha.map((perCore) => {
@@ -18902,8 +19600,9 @@ declare const fullStateDumpFromJson = (spec: ChainSpec) =>
18902
19600
  timeslot: tau,
18903
19601
  privilegedServices: PrivilegedServices.create({
18904
19602
  manager: chi.chi_m,
18905
- authManager: chi.chi_a,
18906
- validatorsManager: chi.chi_v,
19603
+ assigners: chi.chi_a,
19604
+ delegator: chi.chi_v,
19605
+ registrar: chi.chi_r ?? tryAsServiceId(2 ** 32 - 1),
18907
19606
  autoAccumulateServices: chi.chi_g ?? [],
18908
19607
  }),
18909
19608
  statistics: JsonStatisticsData.toStatisticsData(spec, pi),
@@ -18926,6 +19625,7 @@ declare const index$1_JsonDisputesRecords: typeof JsonDisputesRecords;
18926
19625
  type index$1_JsonLookupMeta = JsonLookupMeta;
18927
19626
  type index$1_JsonPreimageItem = JsonPreimageItem;
18928
19627
  declare const index$1_JsonPreimageItem: typeof JsonPreimageItem;
19628
+ type index$1_JsonPreimageStatus = JsonPreimageStatus;
18929
19629
  type index$1_JsonRecentBlockState = JsonRecentBlockState;
18930
19630
  type index$1_JsonRecentBlocks = JsonRecentBlocks;
18931
19631
  type index$1_JsonReportedWorkPackageInfo = JsonReportedWorkPackageInfo;
@@ -18950,6 +19650,7 @@ declare const index$1_disputesRecordsFromJson: typeof disputesRecordsFromJson;
18950
19650
  declare const index$1_fullStateDumpFromJson: typeof fullStateDumpFromJson;
18951
19651
  declare const index$1_lookupMetaFromJson: typeof lookupMetaFromJson;
18952
19652
  declare const index$1_notYetAccumulatedFromJson: typeof notYetAccumulatedFromJson;
19653
+ declare const index$1_preimageStatusFromJson: typeof preimageStatusFromJson;
18953
19654
  declare const index$1_recentBlockStateFromJson: typeof recentBlockStateFromJson;
18954
19655
  declare const index$1_recentBlocksHistoryFromJson: typeof recentBlocksHistoryFromJson;
18955
19656
  declare const index$1_reportedWorkPackageFromJson: typeof reportedWorkPackageFromJson;
@@ -18957,8 +19658,8 @@ declare const index$1_serviceStatisticsEntryFromJson: typeof serviceStatisticsEn
18957
19658
  declare const index$1_ticketFromJson: typeof ticketFromJson;
18958
19659
  declare const index$1_validatorDataFromJson: typeof validatorDataFromJson;
18959
19660
  declare namespace index$1 {
18960
- export { index$1_JsonCoreStatistics as JsonCoreStatistics, index$1_JsonDisputesRecords as JsonDisputesRecords, index$1_JsonPreimageItem as JsonPreimageItem, index$1_JsonService as JsonService, index$1_JsonServiceInfo as JsonServiceInfo, index$1_JsonServiceStatistics as JsonServiceStatistics, index$1_JsonStatisticsData as JsonStatisticsData, index$1_JsonStorageItem as JsonStorageItem, index$1_JsonValidatorStatistics as JsonValidatorStatistics, index$1_TicketsOrKeys as TicketsOrKeys, index$1_availabilityAssignmentFromJson as availabilityAssignmentFromJson, index$1_disputesRecordsFromJson as disputesRecordsFromJson, index$1_fullStateDumpFromJson as fullStateDumpFromJson, index$1_lookupMetaFromJson as lookupMetaFromJson, index$1_notYetAccumulatedFromJson as notYetAccumulatedFromJson, index$1_recentBlockStateFromJson as recentBlockStateFromJson, index$1_recentBlocksHistoryFromJson as recentBlocksHistoryFromJson, index$1_reportedWorkPackageFromJson as reportedWorkPackageFromJson, index$1_serviceStatisticsEntryFromJson as serviceStatisticsEntryFromJson, index$1_ticketFromJson as ticketFromJson, index$1_validatorDataFromJson as validatorDataFromJson };
18961
- export type { index$1_JsonAvailabilityAssignment as JsonAvailabilityAssignment, index$1_JsonLookupMeta as JsonLookupMeta, index$1_JsonRecentBlockState as JsonRecentBlockState, index$1_JsonRecentBlocks as JsonRecentBlocks, index$1_JsonReportedWorkPackageInfo as JsonReportedWorkPackageInfo, index$1_JsonStateDump as JsonStateDump, index$1_ServiceStatisticsEntry as ServiceStatisticsEntry };
19661
+ export { index$1_JsonCoreStatistics as JsonCoreStatistics, index$1_JsonDisputesRecords as JsonDisputesRecords, index$1_JsonPreimageItem as JsonPreimageItem, index$1_JsonService as JsonService, index$1_JsonServiceInfo as JsonServiceInfo, index$1_JsonServiceStatistics as JsonServiceStatistics, index$1_JsonStatisticsData as JsonStatisticsData, index$1_JsonStorageItem as JsonStorageItem, index$1_JsonValidatorStatistics as JsonValidatorStatistics, index$1_TicketsOrKeys as TicketsOrKeys, index$1_availabilityAssignmentFromJson as availabilityAssignmentFromJson, index$1_disputesRecordsFromJson as disputesRecordsFromJson, index$1_fullStateDumpFromJson as fullStateDumpFromJson, index$1_lookupMetaFromJson as lookupMetaFromJson, index$1_notYetAccumulatedFromJson as notYetAccumulatedFromJson, index$1_preimageStatusFromJson as preimageStatusFromJson, index$1_recentBlockStateFromJson as recentBlockStateFromJson, index$1_recentBlocksHistoryFromJson as recentBlocksHistoryFromJson, index$1_reportedWorkPackageFromJson as reportedWorkPackageFromJson, index$1_serviceStatisticsEntryFromJson as serviceStatisticsEntryFromJson, index$1_ticketFromJson as ticketFromJson, index$1_validatorDataFromJson as validatorDataFromJson };
19662
+ export type { index$1_JsonAvailabilityAssignment as JsonAvailabilityAssignment, index$1_JsonLookupMeta as JsonLookupMeta, index$1_JsonPreimageStatus as JsonPreimageStatus, index$1_JsonRecentBlockState as JsonRecentBlockState, index$1_JsonRecentBlocks as JsonRecentBlocks, index$1_JsonReportedWorkPackageInfo as JsonReportedWorkPackageInfo, index$1_JsonStateDump as JsonStateDump, index$1_ServiceStatisticsEntry as ServiceStatisticsEntry };
18962
19663
  }
18963
19664
 
18964
19665
  /** Helper function to create most used hashes in the block */
@@ -18966,7 +19667,7 @@ declare class TransitionHasher implements MmrHasher<KeccakHash> {
18966
19667
  constructor(
18967
19668
  private readonly context: ChainSpec,
18968
19669
  private readonly keccakHasher: KeccakHasher,
18969
- private readonly allocator: HashAllocator,
19670
+ public readonly blake2b: Blake2b,
18970
19671
  ) {}
18971
19672
 
18972
19673
  /** Concatenates two hashes and hash this concatenation */
@@ -18980,7 +19681,7 @@ declare class TransitionHasher implements MmrHasher<KeccakHash> {
18980
19681
 
18981
19682
  /** Creates hash from the block header view */
18982
19683
  header(header: HeaderView): WithHash<HeaderHash, HeaderView> {
18983
- return new WithHash(blake2b.hashBytes(header.encoded(), this.allocator).asOpaque(), header);
19684
+ return new WithHash(this.blake2b.hashBytes(header.encoded()).asOpaque(), header);
18984
19685
  }
18985
19686
 
18986
19687
  /**
@@ -18994,7 +19695,7 @@ declare class TransitionHasher implements MmrHasher<KeccakHash> {
18994
19695
  .view()
18995
19696
  .map((g) => g.view())
18996
19697
  .map((guarantee) => {
18997
- const reportHash = blake2b.hashBytes(guarantee.report.encoded(), this.allocator).asOpaque<WorkReportHash>();
19698
+ const reportHash = this.blake2b.hashBytes(guarantee.report.encoded()).asOpaque<WorkReportHash>();
18998
19699
  return BytesBlob.blobFromParts([
18999
19700
  reportHash.raw,
19000
19701
  guarantee.slot.encoded().raw,
@@ -19004,15 +19705,15 @@ declare class TransitionHasher implements MmrHasher<KeccakHash> {
19004
19705
 
19005
19706
  const guaranteeBlob = Encoder.encodeObject(codec.sequenceVarLen(dumpCodec), guarantees, this.context);
19006
19707
 
19007
- const et = blake2b.hashBytes(extrinsicView.tickets.encoded(), this.allocator).asOpaque<ExtrinsicHash>();
19008
- const ep = blake2b.hashBytes(extrinsicView.preimages.encoded(), this.allocator).asOpaque<ExtrinsicHash>();
19009
- const eg = blake2b.hashBytes(guaranteeBlob, this.allocator).asOpaque<ExtrinsicHash>();
19010
- const ea = blake2b.hashBytes(extrinsicView.assurances.encoded(), this.allocator).asOpaque<ExtrinsicHash>();
19011
- const ed = blake2b.hashBytes(extrinsicView.disputes.encoded(), this.allocator).asOpaque<ExtrinsicHash>();
19708
+ const et = this.blake2b.hashBytes(extrinsicView.tickets.encoded()).asOpaque<ExtrinsicHash>();
19709
+ const ep = this.blake2b.hashBytes(extrinsicView.preimages.encoded()).asOpaque<ExtrinsicHash>();
19710
+ const eg = this.blake2b.hashBytes(guaranteeBlob).asOpaque<ExtrinsicHash>();
19711
+ const ea = this.blake2b.hashBytes(extrinsicView.assurances.encoded()).asOpaque<ExtrinsicHash>();
19712
+ const ed = this.blake2b.hashBytes(extrinsicView.disputes.encoded()).asOpaque<ExtrinsicHash>();
19012
19713
 
19013
19714
  const encoded = BytesBlob.blobFromParts([et.raw, ep.raw, eg.raw, ea.raw, ed.raw]);
19014
19715
 
19015
- return new WithHashAndBytes(blake2b.hashBytes(encoded, this.allocator).asOpaque(), extrinsicView, encoded);
19716
+ return new WithHashAndBytes(this.blake2b.hashBytes(encoded).asOpaque(), extrinsicView, encoded);
19016
19717
  }
19017
19718
 
19018
19719
  /** Creates hash for given WorkPackage */
@@ -19023,7 +19724,7 @@ declare class TransitionHasher implements MmrHasher<KeccakHash> {
19023
19724
  private encode<T, THash extends OpaqueHash>(codec: Codec<T>, data: T): WithHashAndBytes<THash, T> {
19024
19725
  // TODO [ToDr] Use already allocated encoding destination and hash bytes from some arena.
19025
19726
  const encoded = Encoder.encodeObject(codec, data, this.context);
19026
- return new WithHashAndBytes(blake2b.hashBytes(encoded, this.allocator).asOpaque(), data, encoded);
19727
+ return new WithHashAndBytes(this.blake2b.hashBytes(encoded).asOpaque(), data, encoded);
19027
19728
  }
19028
19729
  }
19029
19730
 
@@ -19044,7 +19745,10 @@ declare enum PreimagesErrorCode {
19044
19745
 
19045
19746
  // TODO [SeKo] consider whether this module is the right place to remove expired preimages
19046
19747
  declare class Preimages {
19047
- constructor(public readonly state: PreimagesState) {}
19748
+ constructor(
19749
+ public readonly state: PreimagesState,
19750
+ public readonly blake2b: Blake2b,
19751
+ ) {}
19048
19752
 
19049
19753
  integrate(input: PreimagesInput): Result$2<PreimagesStateUpdate, PreimagesErrorCode> {
19050
19754
  // make sure lookup extrinsics are sorted and unique
@@ -19073,7 +19777,7 @@ declare class Preimages {
19073
19777
  // select preimages for integration
19074
19778
  for (const preimage of preimages) {
19075
19779
  const { requester, blob } = preimage;
19076
- const hash: PreimageHash = blake2b.hashBytes(blob).asOpaque();
19780
+ const hash: PreimageHash = this.blake2b.hashBytes(blob).asOpaque();
19077
19781
 
19078
19782
  const service = this.state.getService(requester);
19079
19783
  if (service === null) {
@@ -19104,156 +19808,6 @@ declare class Preimages {
19104
19808
  }
19105
19809
  }
19106
19810
 
19107
- declare enum ServiceExecutorError {
19108
- NoLookup = 0,
19109
- NoState = 1,
19110
- NoServiceCode = 2,
19111
- ServiceCodeMismatch = 3,
19112
- }
19113
-
19114
- declare class WorkPackageExecutor {
19115
- constructor(
19116
- private readonly blocks: BlocksDb,
19117
- private readonly state: StatesDb,
19118
- private readonly hasher: TransitionHasher,
19119
- ) {}
19120
-
19121
- // TODO [ToDr] this while thing should be triple-checked with the GP.
19122
- // I'm currently implementing some dirty version for the demo.
19123
- async executeWorkPackage(pack: WorkPackage): Promise<WorkReport> {
19124
- const headerHash = pack.context.lookupAnchor;
19125
- // execute authorisation first or is it already executed and we just need to check it?
19126
- const authExec = this.getServiceExecutor(
19127
- // TODO [ToDr] should this be anchor or lookupAnchor?
19128
- headerHash,
19129
- pack.authCodeHost,
19130
- pack.authCodeHash,
19131
- );
19132
-
19133
- if (authExec.isError) {
19134
- // TODO [ToDr] most likely shouldn't be throw.
19135
- throw new Error(`Could not get authorization executor: ${authExec.error}`);
19136
- }
19137
-
19138
- const pvm = authExec.ok;
19139
- const authGas = tryAsGas(15_000n);
19140
- const result = await pvm.run(pack.parametrization, authGas);
19141
-
19142
- if (!result.isEqualTo(pack.authorization)) {
19143
- throw new Error("Authorization is invalid.");
19144
- }
19145
-
19146
- const results: WorkResult[] = [];
19147
- for (const item of pack.items) {
19148
- const exec = this.getServiceExecutor(headerHash, item.service, item.codeHash);
19149
- if (exec.isError) {
19150
- throw new Error(`Could not get item executor: ${exec.error}`);
19151
- }
19152
- const pvm = exec.ok;
19153
-
19154
- const gasRatio = tryAsServiceGas(3_000n);
19155
- const ret = await pvm.run(item.payload, tryAsGas(item.refineGasLimit)); // or accumulateGasLimit?
19156
- results.push(
19157
- WorkResult.create({
19158
- serviceId: item.service,
19159
- codeHash: item.codeHash,
19160
- payloadHash: blake2b.hashBytes(item.payload),
19161
- gas: gasRatio,
19162
- result: new WorkExecResult(WorkExecResultKind.ok, ret),
19163
- load: WorkRefineLoad.create({
19164
- gasUsed: tryAsServiceGas(5),
19165
- importedSegments: tryAsU32(0),
19166
- exportedSegments: tryAsU32(0),
19167
- extrinsicSize: tryAsU32(0),
19168
- extrinsicCount: tryAsU32(0),
19169
- }),
19170
- }),
19171
- );
19172
- }
19173
-
19174
- const workPackage = this.hasher.workPackage(pack);
19175
- const workPackageSpec = WorkPackageSpec.create({
19176
- hash: workPackage.hash,
19177
- length: tryAsU32(workPackage.encoded.length),
19178
- erasureRoot: Bytes.zero(HASH_SIZE),
19179
- exportsRoot: Bytes.zero(HASH_SIZE).asOpaque(),
19180
- exportsCount: tryAsU16(0),
19181
- });
19182
- const coreIndex = tryAsCoreIndex(0);
19183
- const authorizerHash = Bytes.fill(HASH_SIZE, 5).asOpaque();
19184
-
19185
- const workResults = FixedSizeArray.new(results, tryAsWorkItemsCount(results.length));
19186
-
19187
- return Promise.resolve(
19188
- WorkReport.create({
19189
- workPackageSpec,
19190
- context: pack.context,
19191
- coreIndex,
19192
- authorizerHash,
19193
- authorizationOutput: pack.authorization,
19194
- segmentRootLookup: [],
19195
- results: workResults,
19196
- authorizationGasUsed: tryAsServiceGas(0),
19197
- }),
19198
- );
19199
- }
19200
-
19201
- getServiceExecutor(
19202
- lookupAnchor: HeaderHash,
19203
- serviceId: ServiceId,
19204
- expectedCodeHash: CodeHash,
19205
- ): Result$2<PvmExecutor, ServiceExecutorError> {
19206
- const header = this.blocks.getHeader(lookupAnchor);
19207
- if (header === null) {
19208
- return Result.error(ServiceExecutorError.NoLookup);
19209
- }
19210
-
19211
- const state = this.state.getState(lookupAnchor);
19212
- if (state === null) {
19213
- return Result.error(ServiceExecutorError.NoState);
19214
- }
19215
-
19216
- const service = state.getService(serviceId);
19217
- const serviceCodeHash = service?.getInfo().codeHash ?? null;
19218
- if (serviceCodeHash === null) {
19219
- return Result.error(ServiceExecutorError.NoServiceCode);
19220
- }
19221
-
19222
- if (!serviceCodeHash.isEqualTo(expectedCodeHash)) {
19223
- return Result.error(ServiceExecutorError.ServiceCodeMismatch);
19224
- }
19225
-
19226
- const serviceCode = service?.getPreimage(serviceCodeHash.asOpaque()) ?? null;
19227
- if (serviceCode === null) {
19228
- return Result.error(ServiceExecutorError.NoServiceCode);
19229
- }
19230
-
19231
- return Result.ok(new PvmExecutor(serviceCode));
19232
- }
19233
- }
19234
-
19235
- declare class PvmExecutor {
19236
- private readonly pvm: HostCalls;
19237
- private hostCalls = new HostCallsManager({ missing: new Missing() });
19238
- private pvmInstanceManager = new PvmInstanceManager(4);
19239
-
19240
- constructor(private serviceCode: BytesBlob) {
19241
- this.pvm = new PvmHostCallExtension(this.pvmInstanceManager, this.hostCalls);
19242
- }
19243
-
19244
- async run(args: BytesBlob, gas: Gas): Promise<BytesBlob> {
19245
- const program = Program.fromSpi(this.serviceCode.raw, args.raw, true);
19246
-
19247
- const result = await this.pvm.runProgram(program.code, 5, gas, program.registers, program.memory);
19248
-
19249
- if (result.hasMemorySlice()) {
19250
- return BytesBlob.blobFrom(result.memorySlice);
19251
- }
19252
-
19253
- return BytesBlob.empty();
19254
- }
19255
- }
19256
-
19257
19811
  type index_Preimages = Preimages;
19258
19812
  declare const index_Preimages: typeof Preimages;
19259
19813
  type index_PreimagesErrorCode = PreimagesErrorCode;
@@ -19263,11 +19817,9 @@ type index_PreimagesState = PreimagesState;
19263
19817
  type index_PreimagesStateUpdate = PreimagesStateUpdate;
19264
19818
  type index_TransitionHasher = TransitionHasher;
19265
19819
  declare const index_TransitionHasher: typeof TransitionHasher;
19266
- type index_WorkPackageExecutor = WorkPackageExecutor;
19267
- declare const index_WorkPackageExecutor: typeof WorkPackageExecutor;
19268
19820
  declare namespace index {
19269
- export { index_Preimages as Preimages, index_PreimagesErrorCode as PreimagesErrorCode, index_TransitionHasher as TransitionHasher, index_WorkPackageExecutor as WorkPackageExecutor };
19821
+ export { index_Preimages as Preimages, index_PreimagesErrorCode as PreimagesErrorCode, index_TransitionHasher as TransitionHasher };
19270
19822
  export type { index_PreimagesInput as PreimagesInput, index_PreimagesState as PreimagesState, index_PreimagesStateUpdate as PreimagesStateUpdate };
19271
19823
  }
19272
19824
 
19273
- export { index$j as block, index$h as block_json, index$q as bytes, index$o as codec, index$m as collections, index$k as config, index$f as config_node, index$l as crypto, index$a as database, index$9 as erasure_coding, index$n as hash, index$6 as jam_host_calls, index$i as json_parser, index$g as logger, index$d as mmr, index$p as numbers, index$r as ordering, index$3 as pvm, index$7 as pvm_host_calls, index$8 as pvm_interpreter, index$4 as pvm_program, index$5 as pvm_spi_decoder, index$2 as shuffling, index$c as state, index$1 as state_json, index$b as state_merkleization, index as transition, index$e as trie, index$s as utils };
19825
+ export { index$l as block, index$j as block_json, index$s as bytes, index$q as codec, index$o as collections, index$m as config, index$h as config_node, index$n as crypto, index$c as database, index$b as erasure_coding, index$9 as fuzz_proto, index$p as hash, index$6 as jam_host_calls, index$k as json_parser, index$i as logger, index$f as mmr, index$r as numbers, index$t as ordering, index$3 as pvm, index$7 as pvm_host_calls, index$8 as pvm_interpreter, index$4 as pvm_program, index$5 as pvm_spi_decoder, index$2 as shuffling, index$e as state, index$1 as state_json, index$d as state_merkleization, index as transition, index$g as trie, index$u as utils };