@typeberry/jam 0.2.0-b6e3410 → 0.2.0-c3df163

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.
@@ -2753,7 +2753,7 @@ module.exports = __nccwpck_require__.p + "e2fdc1b646378dd96eda.js?ed25519_wasm_b
2753
2753
 
2754
2754
  /***/ }),
2755
2755
 
2756
- /***/ 185:
2756
+ /***/ 566:
2757
2757
  /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
2758
2758
 
2759
2759
  module.exports = __nccwpck_require__.p + "ccf8ada94096a8f232f5.js?reed_solomon_wasm_bg.wasm";
@@ -3452,7 +3452,7 @@ async function __wbg_init(module_or_path) {
3452
3452
  if (wasm !== void 0) return wasm;
3453
3453
  if (typeof module_or_path !== "undefined") if (Object.getPrototypeOf(module_or_path) === Object.prototype) ({module_or_path} = module_or_path);
3454
3454
  else console.warn("using deprecated parameters for the initialization function; pass a single object instead");
3455
- if (typeof module_or_path === "undefined") module_or_path = new URL(/* asset import */ __nccwpck_require__(185), __nccwpck_require__.b);
3455
+ if (typeof module_or_path === "undefined") module_or_path = new URL(/* asset import */ __nccwpck_require__(566), __nccwpck_require__.b);
3456
3456
  const imports = __wbg_get_imports();
3457
3457
  if (typeof module_or_path === "string" || typeof Request === "function" && module_or_path instanceof Request || typeof URL === "function" && module_or_path instanceof URL) module_or_path = fetch(module_or_path);
3458
3458
  __wbg_init_memory(imports);
@@ -4521,7 +4521,7 @@ const BANDERSNATCH_KEY_BYTES = 32;
4521
4521
  /** Bandersnatch VRF signature size */
4522
4522
  const BANDERSNATCH_VRF_SIGNATURE_BYTES = 96;
4523
4523
  /** Bandersnatch ring commitment size */
4524
- const BANDERSNATCH_RING_ROOT_BYTES = 144;
4524
+ const bandersnatch_BANDERSNATCH_RING_ROOT_BYTES = 144;
4525
4525
  /** Bandersnatch proof size */
4526
4526
  const BANDERSNATCH_PROOF_BYTES = 784;
4527
4527
  /** BLS public key size. */
@@ -6198,6 +6198,9 @@ class ObjectView {
6198
6198
  toString() {
6199
6199
  return `View<${this.materializedConstructor.name}>(cache: ${this.cache.size})`;
6200
6200
  }
6201
+ [TEST_COMPARE_USING]() {
6202
+ return this.materialize();
6203
+ }
6201
6204
  }
6202
6205
  /**
6203
6206
  * A lazy-evaluated decoder of a sequence.
@@ -6330,7 +6333,7 @@ const TYPICAL_DICTIONARY_LENGTH = 32;
6330
6333
  * It's not true in a general case, but should be good enough for us.
6331
6334
  *
6332
6335
  */
6333
- function readonlyArray(desc) {
6336
+ function descriptors_readonlyArray(desc) {
6334
6337
  return desc.convert((x) => {
6335
6338
  debug_check `
6336
6339
  ${Array.isArray(x)}
@@ -6492,7 +6495,15 @@ var descriptors_codec;
6492
6495
  /** Custom encoding / decoding logic. */
6493
6496
  codec.custom = ({ name, sizeHint = { bytes: 0, isExact: false }, }, encode, decode, skip) => Descriptor.new(name, sizeHint, encode, decode, skip);
6494
6497
  /** Choose a descriptor depending on the encoding/decoding context. */
6495
- codec.select = ({ name, sizeHint, }, chooser) => Descriptor.withView(name, sizeHint, (e, x) => chooser(e.getContext()).encode(e, x), (d) => chooser(d.getContext()).decode(d), (s) => chooser(s.decoder.getContext()).skip(s), chooser(null).View);
6498
+ codec.select = ({ name, sizeHint, }, chooser) => {
6499
+ const Self = chooser(null);
6500
+ return Descriptor.withView(name, sizeHint, (e, x) => chooser(e.getContext()).encode(e, x), (d) => chooser(d.getContext()).decode(d), (s) => chooser(s.decoder.getContext()).skip(s), hasUniqueView(Self)
6501
+ ? codec.select({
6502
+ name: Self.View.name,
6503
+ sizeHint: Self.View.sizeHint,
6504
+ }, (ctx) => chooser(ctx).View)
6505
+ : Self.View);
6506
+ };
6496
6507
  /**
6497
6508
  * A descriptor for a more complex POJO.
6498
6509
  *
@@ -7610,9 +7621,9 @@ function codecWithContext(chooser) {
7610
7621
  /** Codec for a known-size array with length validation. */
7611
7622
  const codecKnownSizeArray = (val, options, _id) => {
7612
7623
  if ("fixedLength" in options) {
7613
- return readonlyArray(descriptors_codec.sequenceFixLen(val, options.fixedLength)).convert(seeThrough, sized_array_asKnownSize);
7624
+ return descriptors_readonlyArray(descriptors_codec.sequenceFixLen(val, options.fixedLength)).convert(seeThrough, sized_array_asKnownSize);
7614
7625
  }
7615
- return readonlyArray(descriptors_codec.sequenceVarLen(val, options)).convert(seeThrough, sized_array_asKnownSize);
7626
+ return descriptors_readonlyArray(descriptors_codec.sequenceVarLen(val, options)).convert(seeThrough, sized_array_asKnownSize);
7616
7627
  };
7617
7628
  /** Codec for a fixed-size array with length validation. */
7618
7629
  const codecFixedSizeArray = (val, len) => {
@@ -7749,7 +7760,7 @@ function tryAsPerValidator(array, spec) {
7749
7760
  `;
7750
7761
  return sized_array_asKnownSize(array);
7751
7762
  }
7752
- const codecPerValidator = (val) => codecWithContext((context) => {
7763
+ const common_codecPerValidator = (val) => codecWithContext((context) => {
7753
7764
  return codecKnownSizeArray(val, {
7754
7765
  fixedLength: context.validatorsCount,
7755
7766
  });
@@ -7876,7 +7887,7 @@ class Verdict extends WithDebug {
7876
7887
  workReportHash: descriptors_codec.bytes(hash_HASH_SIZE).asOpaque(),
7877
7888
  votesEpoch: descriptors_codec.u32.asOpaque(),
7878
7889
  votes: codecWithContext((context) => {
7879
- return readonlyArray(descriptors_codec.sequenceFixLen(Judgement.Codec, context.validatorsSuperMajority)).convert(seeThrough, sized_array_asKnownSize);
7890
+ return descriptors_readonlyArray(descriptors_codec.sequenceFixLen(Judgement.Codec, context.validatorsSuperMajority)).convert(seeThrough, sized_array_asKnownSize);
7880
7891
  }),
7881
7892
  });
7882
7893
  static create({ workReportHash, votesEpoch, votes }) {
@@ -8568,7 +8579,7 @@ const WorkReportCodec = descriptors_codec.Class(WorkReportNoCodec, {
8568
8579
  authorizerHash: descriptors_codec.bytes(hash_HASH_SIZE).asOpaque(),
8569
8580
  authorizationGasUsed: descriptors_codec.varU64.asOpaque(),
8570
8581
  authorizationOutput: descriptors_codec.blob,
8571
- segmentRootLookup: readonlyArray(descriptors_codec.sequenceVarLen(WorkPackageInfo.Codec)),
8582
+ segmentRootLookup: descriptors_readonlyArray(descriptors_codec.sequenceVarLen(WorkPackageInfo.Codec)),
8572
8583
  results: descriptors_codec.sequenceVarLen(WorkResult.Codec).convert((x) => x, (items) => FixedSizeArray.new(items, tryAsWorkItemsCount(items.length))),
8573
8584
  });
8574
8585
  const WorkReportCodecPre070 = descriptors_codec.Class(WorkReportNoCodec, {
@@ -8582,7 +8593,7 @@ const WorkReportCodecPre070 = descriptors_codec.Class(WorkReportNoCodec, {
8582
8593
  }),
8583
8594
  authorizerHash: descriptors_codec.bytes(hash_HASH_SIZE).asOpaque(),
8584
8595
  authorizationOutput: descriptors_codec.blob,
8585
- segmentRootLookup: readonlyArray(descriptors_codec.sequenceVarLen(WorkPackageInfo.Codec)),
8596
+ segmentRootLookup: descriptors_readonlyArray(descriptors_codec.sequenceVarLen(WorkPackageInfo.Codec)),
8586
8597
  results: descriptors_codec.sequenceVarLen(WorkResult.Codec).convert((x) => x, (items) => FixedSizeArray.new(items, tryAsWorkItemsCount(items.length))),
8587
8598
  authorizationGasUsed: descriptors_codec.varU64.asOpaque(),
8588
8599
  });
@@ -8700,16 +8711,16 @@ class SignedTicket extends WithDebug {
8700
8711
  }
8701
8712
  }
8702
8713
  /** Anonymous? entry into the ticket contest. */
8703
- class Ticket extends WithDebug {
8714
+ class tickets_Ticket extends WithDebug {
8704
8715
  id;
8705
8716
  attempt;
8706
- static Codec = descriptors_codec.Class(Ticket, {
8717
+ static Codec = descriptors_codec.Class(tickets_Ticket, {
8707
8718
  id: descriptors_codec.bytes(hash_HASH_SIZE),
8708
8719
  // TODO [ToDr] we should verify that attempt is either 0|1|2.
8709
8720
  attempt: descriptors_codec.u8.asOpaque(),
8710
8721
  });
8711
8722
  static create({ id, attempt }) {
8712
- return new Ticket(id, attempt);
8723
+ return new tickets_Ticket(id, attempt);
8713
8724
  }
8714
8725
  constructor(
8715
8726
  /**
@@ -8778,7 +8789,7 @@ class ValidatorKeys extends WithDebug {
8778
8789
  class TicketsMarker extends WithDebug {
8779
8790
  tickets;
8780
8791
  static Codec = descriptors_codec.Class(TicketsMarker, {
8781
- tickets: codecPerEpochBlock(Ticket.Codec),
8792
+ tickets: codecPerEpochBlock(tickets_Ticket.Codec),
8782
8793
  });
8783
8794
  static create({ tickets }) {
8784
8795
  return new TicketsMarker(tickets);
@@ -8802,7 +8813,7 @@ class EpochMarker extends WithDebug {
8802
8813
  static Codec = descriptors_codec.Class(EpochMarker, {
8803
8814
  entropy: descriptors_codec.bytes(hash_HASH_SIZE).asOpaque(),
8804
8815
  ticketsEntropy: descriptors_codec.bytes(hash_HASH_SIZE).asOpaque(),
8805
- validators: codecPerValidator(ValidatorKeys.Codec),
8816
+ validators: common_codecPerValidator(ValidatorKeys.Codec),
8806
8817
  });
8807
8818
  static create({ entropy, ticketsEntropy, validators }) {
8808
8819
  return new EpochMarker(entropy, ticketsEntropy, validators);
@@ -9074,6 +9085,19 @@ function emptyBlock(slot = tryAsTimeSlot(0)) {
9074
9085
  });
9075
9086
  }
9076
9087
 
9088
+ ;// CONCATENATED MODULE: ./packages/jam/block/utils.ts
9089
+
9090
+ /**
9091
+ * Take an input data and re-encode that data as view.
9092
+ *
9093
+ * NOTE: this function should NEVER be used in any production code,
9094
+ * it's only a test helper.
9095
+ */
9096
+ function reencodeAsView(codec, object, chainSpec) {
9097
+ const encoded = encoder_Encoder.encodeObject(codec, object, chainSpec);
9098
+ return decoder_Decoder.decodeObject(codec.View, encoded, chainSpec);
9099
+ }
9100
+
9077
9101
  ;// CONCATENATED MODULE: ./packages/jam/block/index.ts
9078
9102
 
9079
9103
 
@@ -9092,6 +9116,7 @@ function emptyBlock(slot = tryAsTimeSlot(0)) {
9092
9116
 
9093
9117
 
9094
9118
 
9119
+
9095
9120
  ;// CONCATENATED MODULE: ./packages/jam/database-lmdb/blocks.ts
9096
9121
 
9097
9122
 
@@ -9443,10 +9468,129 @@ function accumulationOutputComparator(a, b) {
9443
9468
  return Ordering.Equal;
9444
9469
  }
9445
9470
 
9471
+ ;// CONCATENATED MODULE: ./packages/jam/block/gp-constants.ts
9472
+
9473
+
9474
+ /**
9475
+ * This file lists all of the constants defined in the GrayPaper appendix.
9476
+ *
9477
+ * NOTE: Avoid using the constants directly, prefer "named" constants defined
9478
+ * in a semantical proximity to where they are used.
9479
+ *
9480
+ * NOTE: This file will most likely be removed in the future. The constants
9481
+ * here are only temporarily for convenience. When we figure out better names
9482
+ * and places for these this file will be eradicated.
9483
+ *
9484
+ * https://graypaper.fluffylabs.dev/#/ab2cdbd/442300442300?v=0.7.2
9485
+ */
9486
+ /** `G_I`: The gas allocated to invoke a work-package’s Is-Authorized logic. */
9487
+ const G_I = 50_000_000;
9488
+ /** `I`: Maximum number of work items in a package. */
9489
+ const gp_constants_I = (/* unused pure expression or super */ null && (MAX_NUMBER_OF_WORK_ITEMS));
9490
+ /** `O`: Maximum number of items in the authorizations pool. */
9491
+ const O = 8;
9492
+ /** `Q`: The number of items in the authorizations queue. */
9493
+ const Q = 80;
9494
+ /** `S`: The maximum number of entries in the accumulation queue. */
9495
+ const S = 1024;
9496
+ /** `T`: The maximum number of extrinsics in a work-package. */
9497
+ const T = 128;
9498
+ /** `W_A`: The maximum size of is-authorized code in octets. */
9499
+ const W_A = 64_000;
9500
+ /** `W_B`: The maximum size of the concatenated variable-size blobs, extrinsics and imported segments of a work-package, in octets */
9501
+ const W_B = Compatibility.isGreaterOrEqual(GpVersion.V0_7_2) ? 13_791_360 : 13_794_305;
9502
+ /** `W_C`: The maximum size of service code in octets. */
9503
+ const W_C = 4_000_000;
9504
+ /** `W_M`: The maximum number of imports in a work-package. */
9505
+ const W_M = 3_072;
9506
+ /** `W_R`: The maximum total size of all output blobs in a work-report, in octets. */
9507
+ const W_R = 49_152;
9508
+ /** `W_T`: The size of a transfer memo in octets. */
9509
+ const W_T = 128;
9510
+ /** `W_M`: The maximum number of exports in a work-package. */
9511
+ const W_X = 3_072;
9512
+ // TODO [ToDr] Not sure where these should live yet :(
9513
+ /**
9514
+ * `S`: The minimum public service index.
9515
+ * Services of indices below these may only be created by the Registrar.
9516
+ *
9517
+ * https://graypaper.fluffylabs.dev/#/ab2cdbd/447a00447a00?v=0.7.2
9518
+ */
9519
+ const MIN_PUBLIC_SERVICE_INDEX = 2 ** 16;
9520
+ /**
9521
+ * `J`: The maximum sum of dependency items in a work-report.
9522
+ *
9523
+ * https://graypaper.fluffylabs.dev/#/5f542d7/416a00416a00?v=0.6.2
9524
+ */
9525
+ const MAX_REPORT_DEPENDENCIES = 8;
9526
+
9527
+ ;// CONCATENATED MODULE: ./packages/jam/state/accumulation-queue.ts
9528
+
9529
+
9530
+
9531
+
9532
+
9533
+
9534
+
9535
+ /**
9536
+ * Ready (i.e. available and/or audited) but not-yet-accumulated work-reports.
9537
+ *
9538
+ * https://graypaper.fluffylabs.dev/#/5f542d7/165300165400
9539
+ */
9540
+ class NotYetAccumulatedReport extends WithDebug {
9541
+ report;
9542
+ dependencies;
9543
+ static Codec = descriptors_codec.Class(NotYetAccumulatedReport, {
9544
+ report: WorkReport.Codec,
9545
+ dependencies: codecKnownSizeArray(descriptors_codec.bytes(hash_HASH_SIZE).asOpaque(), {
9546
+ typicalLength: MAX_REPORT_DEPENDENCIES / 2,
9547
+ maxLength: MAX_REPORT_DEPENDENCIES,
9548
+ minLength: 0,
9549
+ }),
9550
+ });
9551
+ static create({ report, dependencies }) {
9552
+ return new NotYetAccumulatedReport(report, dependencies);
9553
+ }
9554
+ constructor(
9555
+ /**
9556
+ * Each of these were made available at most one epoch ago
9557
+ * but have or had unfulfilled dependencies.
9558
+ */
9559
+ report,
9560
+ /**
9561
+ * Alongside the work-report itself, we retain its un-accumulated
9562
+ * dependencies, a set of work-package hashes.
9563
+ *
9564
+ * https://graypaper.fluffylabs.dev/#/5f542d7/165800165800
9565
+ */
9566
+ dependencies) {
9567
+ super();
9568
+ this.report = report;
9569
+ this.dependencies = dependencies;
9570
+ }
9571
+ }
9572
+ const accumulationQueueCodec = codecPerEpochBlock(descriptors_readonlyArray(descriptors_codec.sequenceVarLen(NotYetAccumulatedReport.Codec)));
9573
+
9574
+ ;// CONCATENATED MODULE: ./packages/jam/state/common.ts
9575
+
9576
+
9577
+ /** Check if given array has correct length before casting to the opaque type. */
9578
+ function tryAsPerCore(array, spec) {
9579
+ debug_check `
9580
+ ${array.length === spec.coresCount}
9581
+ Invalid per-core array length. Expected ${spec.coresCount}, got: ${array.length}
9582
+ `;
9583
+ return opaque_asOpaqueType(array);
9584
+ }
9585
+ const codecPerCore = (val) => codecWithContext((context) => {
9586
+ return codecKnownSizeArray(val, { fixedLength: context.coresCount });
9587
+ });
9588
+
9446
9589
  ;// CONCATENATED MODULE: ./packages/jam/state/assurances.ts
9447
9590
 
9448
9591
 
9449
9592
 
9593
+
9450
9594
  /**
9451
9595
  * Assignment of particular work report to a core.
9452
9596
  *
@@ -9475,27 +9619,30 @@ class AvailabilityAssignment extends WithDebug {
9475
9619
  this.timeout = timeout;
9476
9620
  }
9477
9621
  }
9622
+ const availabilityAssignmentsCodec = codecPerCore(descriptors_codec.optional(AvailabilityAssignment.Codec));
9478
9623
 
9479
- ;// CONCATENATED MODULE: ./packages/jam/state/common.ts
9624
+ ;// CONCATENATED MODULE: ./packages/jam/state/auth.ts
9480
9625
 
9481
9626
 
9482
- /** Check if given array has correct length before casting to the opaque type. */
9483
- function tryAsPerCore(array, spec) {
9484
- debug_check `
9485
- ${array.length === spec.coresCount}
9486
- Invalid per-core array length. Expected ${spec.coresCount}, got: ${array.length}
9487
- `;
9488
- return opaque_asOpaqueType(array);
9489
- }
9490
- const codecPerCore = (val) => codecWithContext((context) => {
9491
- return codecKnownSizeArray(val, { fixedLength: context.coresCount });
9492
- });
9627
+
9628
+
9629
+
9630
+ /** `O`: Maximal authorization pool size. */
9631
+ const MAX_AUTH_POOL_SIZE = O;
9632
+ /** `Q`: Size of the authorization queue. */
9633
+ const AUTHORIZATION_QUEUE_SIZE = Q;
9634
+ const authPoolsCodec = codecPerCore(codecKnownSizeArray(descriptors_codec.bytes(hash_HASH_SIZE).asOpaque(), {
9635
+ minLength: 0,
9636
+ maxLength: MAX_AUTH_POOL_SIZE,
9637
+ typicalLength: MAX_AUTH_POOL_SIZE,
9638
+ }));
9639
+ const authQueuesCodec = codecPerCore(codecFixedSizeArray(descriptors_codec.bytes(hash_HASH_SIZE).asOpaque(), AUTHORIZATION_QUEUE_SIZE));
9493
9640
 
9494
9641
  ;// CONCATENATED MODULE: ./packages/jam/state/disputes.ts
9495
9642
 
9496
9643
 
9497
9644
 
9498
- const sortedSetCodec = () => readonlyArray(descriptors_codec.sequenceVarLen(descriptors_codec.bytes(hash_HASH_SIZE))).convert((input) => input.array, (output) => {
9645
+ const sortedSetCodec = () => descriptors_readonlyArray(descriptors_codec.sequenceVarLen(descriptors_codec.bytes(hash_HASH_SIZE))).convert((input) => input.array, (output) => {
9499
9646
  const typed = output.map((x) => x.asOpaque());
9500
9647
  return SortedSet.fromSortedArray(hashComparator, typed);
9501
9648
  });
@@ -9557,65 +9704,6 @@ function hashComparator(a, b) {
9557
9704
  return a.compare(b);
9558
9705
  }
9559
9706
 
9560
- ;// CONCATENATED MODULE: ./packages/jam/block/gp-constants.ts
9561
-
9562
- /**
9563
- * This file lists all of the constants defined in the GrayPaper appendix.
9564
- *
9565
- * NOTE: Avoid using the constants directly, prefer "named" constants defined
9566
- * in a semantical proximity to where they are used.
9567
- *
9568
- * NOTE: This file will most likely be removed in the future. The constants
9569
- * here are only temporarily for convenience. When we figure out better names
9570
- * and places for these this file will be eradicated.
9571
- *
9572
- * https://graypaper.fluffylabs.dev/#/579bd12/413000413000
9573
- */
9574
- /** `G_I`: The gas allocated to invoke a work-package’s Is-Authorized logic. */
9575
- const G_I = 50_000_000;
9576
- /** `I`: Maximum number of work items in a package. */
9577
- const gp_constants_I = (/* unused pure expression or super */ null && (MAX_NUMBER_OF_WORK_ITEMS));
9578
- /** `O`: Maximum number of items in the authorizations pool. */
9579
- const O = 8;
9580
- /** `Q`: The number of items in the authorizations queue. */
9581
- const Q = 80;
9582
- /** `S`: The maximum number of entries in the accumulation queue. */
9583
- const S = 1024;
9584
- /** `T`: The maximum number of extrinsics in a work-package. */
9585
- const T = 128;
9586
- /** `W_A`: The maximum size of is-authorized code in octets. */
9587
- const W_A = 64_000;
9588
- /** `W_B`: The maximum size of an encoded work-package with extrinsic data and imports. */
9589
- const W_B = 13_794_305;
9590
- /** `W_C`: The maximum size of service code in octets. */
9591
- const W_C = 4_000_000;
9592
- /** `W_M`: The maximum number of imports in a work-package. */
9593
- const W_M = 3_072;
9594
- /** `W_R`: The maximum total size of all output blobs in a work-report, in octets. */
9595
- const W_R = 49_152;
9596
- /** `W_T`: The size of a transfer memo in octets. */
9597
- const W_T = 128;
9598
- /** `W_M`: The maximum number of exports in a work-package. */
9599
- const W_X = 3_072;
9600
- // TODO [ToDr] Not sure where these should live yet :(
9601
- /**
9602
- * `S`: The minimum public service index.
9603
- * Services of indices below these may only be created by the Registrar.
9604
- *
9605
- * https://graypaper.fluffylabs.dev/#/ab2cdbd/447a00447a00?v=0.7.2
9606
- */
9607
- const MIN_PUBLIC_SERVICE_INDEX = 2 ** 16;
9608
- /**
9609
- * `J`: The maximum sum of dependency items in a work-report.
9610
- *
9611
- * https://graypaper.fluffylabs.dev/#/5f542d7/416a00416a00?v=0.6.2
9612
- */
9613
- const MAX_REPORT_DEPENDENCIES = 8;
9614
- /** `Q`: Size of the authorization queue. */
9615
- const AUTHORIZATION_QUEUE_SIZE = Q;
9616
- /** `O`: Maximal authorization pool size. */
9617
- const MAX_AUTH_POOL_SIZE = O;
9618
-
9619
9707
  ;// CONCATENATED MODULE: ./packages/core/pvm-interpreter/ops/math-consts.ts
9620
9708
  const MAX_VALUE = 4294967295;
9621
9709
  const math_consts_MAX_VALUE_U64 = (/* unused pure expression or super */ null && (2n ** 63n));
@@ -9623,7 +9711,7 @@ const MIN_VALUE = -(2 ** 31);
9623
9711
  const MAX_SHIFT_U32 = 32;
9624
9712
  const MAX_SHIFT_U64 = 64n;
9625
9713
 
9626
- ;// CONCATENATED MODULE: ./packages/jam/state/service.ts
9714
+ ;// CONCATENATED MODULE: ./packages/jam/state/recent-blocks.ts
9627
9715
 
9628
9716
 
9629
9717
 
@@ -9631,28 +9719,272 @@ const MAX_SHIFT_U64 = 64n;
9631
9719
 
9632
9720
 
9633
9721
  /**
9634
- * `B_S`: The basic minimum balance which all services require.
9635
- *
9636
- * https://graypaper.fluffylabs.dev/#/7e6ff6a/445800445800?v=0.6.7
9637
- */
9638
- const BASE_SERVICE_BALANCE = 100n;
9639
- /**
9640
- * `B_I`: The additional minimum balance required per item of elective service state.
9722
+ * `H = 8`: The size of recent history, in blocks.
9641
9723
  *
9642
- * https://graypaper.fluffylabs.dev/#/7e6ff6a/445000445000?v=0.6.7
9724
+ * https://graypaper.fluffylabs.dev/#/579bd12/416300416500
9643
9725
  */
9644
- const ELECTIVE_ITEM_BALANCE = 10n;
9726
+ const MAX_RECENT_HISTORY = 8;
9727
+ /** Recent history of a single block. */
9728
+ class BlockState extends WithDebug {
9729
+ headerHash;
9730
+ accumulationResult;
9731
+ postStateRoot;
9732
+ reported;
9733
+ static Codec = descriptors_codec.Class(BlockState, {
9734
+ headerHash: descriptors_codec.bytes(hash_HASH_SIZE).asOpaque(),
9735
+ accumulationResult: descriptors_codec.bytes(hash_HASH_SIZE),
9736
+ postStateRoot: descriptors_codec.bytes(hash_HASH_SIZE).asOpaque(),
9737
+ reported: codecHashDictionary(WorkPackageInfo.Codec, (x) => x.workPackageHash),
9738
+ });
9739
+ static create({ headerHash, accumulationResult, postStateRoot, reported }) {
9740
+ return new BlockState(headerHash, accumulationResult, postStateRoot, reported);
9741
+ }
9742
+ constructor(
9743
+ /** Header hash. */
9744
+ headerHash,
9745
+ /** Merkle mountain belt of accumulation result. */
9746
+ accumulationResult,
9747
+ /** Posterior state root filled in with a 1-block delay. */
9748
+ postStateRoot,
9749
+ /** Reported work packages (no more than number of cores). */
9750
+ reported) {
9751
+ super();
9752
+ this.headerHash = headerHash;
9753
+ this.accumulationResult = accumulationResult;
9754
+ this.postStateRoot = postStateRoot;
9755
+ this.reported = reported;
9756
+ }
9757
+ }
9645
9758
  /**
9646
- * `B_L`: The additional minimum balance required per octet of elective service state.
9759
+ * Recent history of blocks.
9647
9760
  *
9648
- * https://graypaper.fluffylabs.dev/#/7e6ff6a/445400445400?v=0.6.7
9761
+ * https://graypaper.fluffylabs.dev/#/7e6ff6a/0fc9010fc901?v=0.6.7
9649
9762
  */
9650
- const ELECTIVE_BYTE_BALANCE = 1n;
9651
- const zeroSizeHint = {
9652
- bytes: 0,
9653
- isExact: true,
9654
- };
9655
- /** 0-byte read, return given default value */
9763
+ class RecentBlocks extends WithDebug {
9764
+ blocks;
9765
+ accumulationLog;
9766
+ static Codec = descriptors_codec.Class(RecentBlocks, {
9767
+ blocks: codecKnownSizeArray(BlockState.Codec, {
9768
+ minLength: 0,
9769
+ maxLength: MAX_RECENT_HISTORY,
9770
+ typicalLength: MAX_RECENT_HISTORY,
9771
+ }),
9772
+ accumulationLog: descriptors_codec.object({
9773
+ peaks: descriptors_readonlyArray(descriptors_codec.sequenceVarLen(descriptors_codec.optional(descriptors_codec.bytes(hash_HASH_SIZE)))),
9774
+ }),
9775
+ });
9776
+ static empty() {
9777
+ return new RecentBlocks(sized_array_asKnownSize([]), {
9778
+ peaks: [],
9779
+ });
9780
+ }
9781
+ static create(a) {
9782
+ return new RecentBlocks(a.blocks, a.accumulationLog);
9783
+ }
9784
+ constructor(
9785
+ /**
9786
+ * Most recent blocks.
9787
+ * https://graypaper.fluffylabs.dev/#/7e6ff6a/0fea010fea01?v=0.6.7
9788
+ */
9789
+ blocks,
9790
+ /**
9791
+ * Accumulation output log.
9792
+ * https://graypaper.fluffylabs.dev/#/7e6ff6a/0f02020f0202?v=0.6.7
9793
+ */
9794
+ accumulationLog) {
9795
+ super();
9796
+ this.blocks = blocks;
9797
+ this.accumulationLog = accumulationLog;
9798
+ }
9799
+ }
9800
+
9801
+ ;// CONCATENATED MODULE: ./packages/jam/state/recently-accumulated.ts
9802
+
9803
+
9804
+
9805
+
9806
+ const recentlyAccumulatedCodec = codecPerEpochBlock(descriptors_codec.sequenceVarLen(descriptors_codec.bytes(hash_HASH_SIZE).asOpaque()).convert((x) => Array.from(x), (x) => HashSet.from(x)));
9807
+
9808
+ ;// CONCATENATED MODULE: ./packages/jam/state/validator-data.ts
9809
+
9810
+
9811
+
9812
+
9813
+ /**
9814
+ * Fixed size of validator metadata.
9815
+ *
9816
+ * https://graypaper.fluffylabs.dev/#/5f542d7/0d55010d5501
9817
+ */
9818
+ const VALIDATOR_META_BYTES = 128;
9819
+ /**
9820
+ * Details about validators' identity.
9821
+ *
9822
+ * https://graypaper.fluffylabs.dev/#/5f542d7/0d4b010d4c01
9823
+ */
9824
+ class validator_data_ValidatorData extends WithDebug {
9825
+ bandersnatch;
9826
+ ed25519;
9827
+ bls;
9828
+ metadata;
9829
+ static Codec = descriptors_codec.Class(validator_data_ValidatorData, {
9830
+ bandersnatch: descriptors_codec.bytes(BANDERSNATCH_KEY_BYTES).asOpaque(),
9831
+ ed25519: descriptors_codec.bytes(ED25519_KEY_BYTES).asOpaque(),
9832
+ bls: descriptors_codec.bytes(BLS_KEY_BYTES).asOpaque(),
9833
+ metadata: descriptors_codec.bytes(VALIDATOR_META_BYTES),
9834
+ });
9835
+ static create({ ed25519, bandersnatch, bls, metadata }) {
9836
+ return new validator_data_ValidatorData(bandersnatch, ed25519, bls, metadata);
9837
+ }
9838
+ constructor(
9839
+ /** Bandersnatch public key. */
9840
+ bandersnatch,
9841
+ /** ED25519 key data. */
9842
+ ed25519,
9843
+ /** BLS public key. */
9844
+ bls,
9845
+ /** Validator-defined additional metdata. */
9846
+ metadata) {
9847
+ super();
9848
+ this.bandersnatch = bandersnatch;
9849
+ this.ed25519 = ed25519;
9850
+ this.bls = bls;
9851
+ this.metadata = metadata;
9852
+ }
9853
+ }
9854
+ const validatorsDataCodec = common_codecPerValidator(validator_data_ValidatorData.Codec);
9855
+
9856
+ ;// CONCATENATED MODULE: ./packages/jam/state/safrole-data.ts
9857
+
9858
+
9859
+
9860
+
9861
+
9862
+
9863
+
9864
+
9865
+
9866
+
9867
+
9868
+ var SafroleSealingKeysKind;
9869
+ (function (SafroleSealingKeysKind) {
9870
+ SafroleSealingKeysKind[SafroleSealingKeysKind["Tickets"] = 0] = "Tickets";
9871
+ SafroleSealingKeysKind[SafroleSealingKeysKind["Keys"] = 1] = "Keys";
9872
+ })(SafroleSealingKeysKind || (SafroleSealingKeysKind = {}));
9873
+ const codecBandersnatchKey = descriptors_codec.bytes(BANDERSNATCH_KEY_BYTES).asOpaque();
9874
+ class safrole_data_SafroleSealingKeysData extends WithDebug {
9875
+ kind;
9876
+ keys;
9877
+ tickets;
9878
+ static Codec = codecWithContext((context) => {
9879
+ return descriptors_codec.custom({
9880
+ name: "SafroleSealingKeys",
9881
+ sizeHint: { bytes: 1 + hash_HASH_SIZE * context.epochLength, isExact: false },
9882
+ }, (e, x) => {
9883
+ e.varU32(numbers_tryAsU32(x.kind));
9884
+ if (x.kind === SafroleSealingKeysKind.Keys) {
9885
+ e.sequenceFixLen(codecBandersnatchKey, x.keys);
9886
+ }
9887
+ else {
9888
+ e.sequenceFixLen(tickets_Ticket.Codec, x.tickets);
9889
+ }
9890
+ }, (d) => {
9891
+ const epochLength = context.epochLength;
9892
+ const kind = d.varU32();
9893
+ if (kind === SafroleSealingKeysKind.Keys) {
9894
+ const keys = d.sequenceFixLen(codecBandersnatchKey, epochLength);
9895
+ return safrole_data_SafroleSealingKeysData.keys(tryAsPerEpochBlock(keys, context));
9896
+ }
9897
+ if (kind === SafroleSealingKeysKind.Tickets) {
9898
+ const tickets = d.sequenceFixLen(tickets_Ticket.Codec, epochLength);
9899
+ return safrole_data_SafroleSealingKeysData.tickets(tryAsPerEpochBlock(tickets, context));
9900
+ }
9901
+ throw new Error(`Unexpected safrole sealing keys kind: ${kind}`);
9902
+ }, (s) => {
9903
+ const kind = s.decoder.varU32();
9904
+ if (kind === SafroleSealingKeysKind.Keys) {
9905
+ s.sequenceFixLen(codecBandersnatchKey, context.epochLength);
9906
+ return;
9907
+ }
9908
+ if (kind === SafroleSealingKeysKind.Tickets) {
9909
+ s.sequenceFixLen(tickets_Ticket.Codec, context.epochLength);
9910
+ return;
9911
+ }
9912
+ throw new Error(`Unexpected safrole sealing keys kind: ${kind}`);
9913
+ });
9914
+ });
9915
+ static keys(keys) {
9916
+ return new safrole_data_SafroleSealingKeysData(SafroleSealingKeysKind.Keys, keys, undefined);
9917
+ }
9918
+ static tickets(tickets) {
9919
+ return new safrole_data_SafroleSealingKeysData(SafroleSealingKeysKind.Tickets, undefined, tickets);
9920
+ }
9921
+ constructor(kind, keys, tickets) {
9922
+ super();
9923
+ this.kind = kind;
9924
+ this.keys = keys;
9925
+ this.tickets = tickets;
9926
+ }
9927
+ }
9928
+ class SafroleData {
9929
+ nextValidatorData;
9930
+ epochRoot;
9931
+ sealingKeySeries;
9932
+ ticketsAccumulator;
9933
+ static Codec = descriptors_codec.Class(SafroleData, {
9934
+ nextValidatorData: common_codecPerValidator(validator_data_ValidatorData.Codec),
9935
+ epochRoot: descriptors_codec.bytes(bandersnatch_BANDERSNATCH_RING_ROOT_BYTES).asOpaque(),
9936
+ sealingKeySeries: safrole_data_SafroleSealingKeysData.Codec,
9937
+ ticketsAccumulator: descriptors_readonlyArray(descriptors_codec.sequenceVarLen(tickets_Ticket.Codec)).convert(seeThrough, sized_array_asKnownSize),
9938
+ });
9939
+ static create({ nextValidatorData, epochRoot, sealingKeySeries, ticketsAccumulator }) {
9940
+ return new SafroleData(nextValidatorData, epochRoot, sealingKeySeries, ticketsAccumulator);
9941
+ }
9942
+ constructor(
9943
+ /** gamma_k */
9944
+ nextValidatorData,
9945
+ /** gamma_z */
9946
+ epochRoot,
9947
+ /** gamma_s */
9948
+ sealingKeySeries,
9949
+ /** gamma_a */
9950
+ ticketsAccumulator) {
9951
+ this.nextValidatorData = nextValidatorData;
9952
+ this.epochRoot = epochRoot;
9953
+ this.sealingKeySeries = sealingKeySeries;
9954
+ this.ticketsAccumulator = ticketsAccumulator;
9955
+ }
9956
+ }
9957
+
9958
+ ;// CONCATENATED MODULE: ./packages/jam/state/service.ts
9959
+
9960
+
9961
+
9962
+
9963
+
9964
+
9965
+ /**
9966
+ * `B_S`: The basic minimum balance which all services require.
9967
+ *
9968
+ * https://graypaper.fluffylabs.dev/#/7e6ff6a/445800445800?v=0.6.7
9969
+ */
9970
+ const BASE_SERVICE_BALANCE = 100n;
9971
+ /**
9972
+ * `B_I`: The additional minimum balance required per item of elective service state.
9973
+ *
9974
+ * https://graypaper.fluffylabs.dev/#/7e6ff6a/445000445000?v=0.6.7
9975
+ */
9976
+ const ELECTIVE_ITEM_BALANCE = 10n;
9977
+ /**
9978
+ * `B_L`: The additional minimum balance required per octet of elective service state.
9979
+ *
9980
+ * https://graypaper.fluffylabs.dev/#/7e6ff6a/445400445400?v=0.6.7
9981
+ */
9982
+ const ELECTIVE_BYTE_BALANCE = 1n;
9983
+ const zeroSizeHint = {
9984
+ bytes: 0,
9985
+ isExact: true,
9986
+ };
9987
+ /** 0-byte read, return given default value */
9656
9988
  const ignoreValueWithDefault = (defaultValue) => Descriptor.new("ignoreValue", zeroSizeHint, (_e, _v) => { }, (_d) => defaultValue, (_s) => { });
9657
9989
  /** Encode and decode object with leading version number. */
9658
9990
  const codecWithVersion = (val) => Descriptor.new("withVersion", {
@@ -9813,358 +10145,418 @@ class LookupHistoryItem {
9813
10145
  }
9814
10146
  }
9815
10147
 
9816
- ;// CONCATENATED MODULE: ./packages/jam/state/privileged-services.ts
10148
+ ;// CONCATENATED MODULE: ./packages/jam/state/statistics.ts
9817
10149
 
9818
10150
 
9819
10151
 
9820
10152
 
9821
10153
 
9822
- /** Dictionary entry of services that auto-accumulate every block. */
9823
- class AutoAccumulate {
9824
- service;
9825
- gasLimit;
9826
- static Codec = descriptors_codec.Class(AutoAccumulate, {
9827
- service: descriptors_codec.u32.asOpaque(),
9828
- gasLimit: descriptors_codec.u64.asOpaque(),
10154
+
10155
+ const codecServiceId = Compatibility.isSuite(TestSuite.W3F_DAVXY) || Compatibility.isSuite(TestSuite.JAMDUNA, GpVersion.V0_6_7)
10156
+ ? descriptors_codec.u32.asOpaque()
10157
+ : descriptors_codec.varU32.convert((s) => numbers_tryAsU32(s), (i) => tryAsServiceId(i));
10158
+ /**
10159
+ * Activity Record of a single validator.
10160
+ *
10161
+ * https://graypaper.fluffylabs.dev/#/579bd12/183701183701
10162
+ */
10163
+ class ValidatorStatistics {
10164
+ blocks;
10165
+ tickets;
10166
+ preImages;
10167
+ preImagesSize;
10168
+ guarantees;
10169
+ assurances;
10170
+ static Codec = descriptors_codec.Class(ValidatorStatistics, {
10171
+ blocks: descriptors_codec.u32,
10172
+ tickets: descriptors_codec.u32,
10173
+ preImages: descriptors_codec.u32,
10174
+ preImagesSize: descriptors_codec.u32,
10175
+ guarantees: descriptors_codec.u32,
10176
+ assurances: descriptors_codec.u32,
9829
10177
  });
9830
- static create({ service, gasLimit }) {
9831
- return new AutoAccumulate(service, gasLimit);
10178
+ static create({ blocks, tickets, preImages, preImagesSize, guarantees, assurances, }) {
10179
+ return new ValidatorStatistics(blocks, tickets, preImages, preImagesSize, guarantees, assurances);
9832
10180
  }
9833
10181
  constructor(
9834
- /** Service id that auto-accumulates. */
9835
- service,
9836
- /** Gas limit for auto-accumulation. */
9837
- gasLimit) {
9838
- this.service = service;
9839
- this.gasLimit = gasLimit;
9840
- }
9841
- }
9842
- /**
9843
- * https://graypaper.fluffylabs.dev/#/ab2cdbd/114402114402?v=0.7.2
9844
- */
9845
- class PrivilegedServices {
9846
- manager;
9847
- delegator;
9848
- registrar;
9849
- assigners;
9850
- autoAccumulateServices;
9851
- /** https://graypaper.fluffylabs.dev/#/ab2cdbd/3bbd023bcb02?v=0.7.2 */
9852
- static Codec = descriptors_codec.Class(PrivilegedServices, {
9853
- manager: descriptors_codec.u32.asOpaque(),
9854
- assigners: codecPerCore(descriptors_codec.u32.asOpaque()),
9855
- delegator: descriptors_codec.u32.asOpaque(),
9856
- registrar: Compatibility.isGreaterOrEqual(GpVersion.V0_7_1)
9857
- ? descriptors_codec.u32.asOpaque()
9858
- : ignoreValueWithDefault(tryAsServiceId(2 ** 32 - 1)),
9859
- autoAccumulateServices: readonlyArray(descriptors_codec.sequenceVarLen(AutoAccumulate.Codec)),
9860
- });
9861
- static create(a) {
9862
- return new PrivilegedServices(a.manager, a.delegator, a.registrar, a.assigners, a.autoAccumulateServices);
10182
+ /** The number of blocks produced by the validator. */
10183
+ blocks,
10184
+ /** The number of tickets introduced by the validator. */
10185
+ tickets,
10186
+ /** The number of preimages introduced by the validator. */
10187
+ preImages,
10188
+ /** The total number of octets across all preimages introduced by the validator. */
10189
+ preImagesSize,
10190
+ /** The number of reports guaranteed by the validator. */
10191
+ guarantees,
10192
+ /** The number of availability assurances made by the validator. */
10193
+ assurances) {
10194
+ this.blocks = blocks;
10195
+ this.tickets = tickets;
10196
+ this.preImages = preImages;
10197
+ this.preImagesSize = preImagesSize;
10198
+ this.guarantees = guarantees;
10199
+ this.assurances = assurances;
9863
10200
  }
9864
- constructor(
9865
- /**
9866
- * `χ_M`: Manages alteration of χ from block to block,
9867
- * as well as bestow services with storage deposit credits.
9868
- * https://graypaper.fluffylabs.dev/#/ab2cdbd/111502111902?v=0.7.2
9869
- */
9870
- manager,
9871
- /** `χ_V`: Managers validator keys. */
9872
- delegator,
9873
- /**
9874
- * `χ_R`: Manages the creation of services in protected range.
9875
- *
9876
- * https://graypaper.fluffylabs.dev/#/ab2cdbd/111b02111d02?v=0.7.2
9877
- */
9878
- registrar,
9879
- /** `χ_A`: Manages authorization queue one for each core. */
9880
- assigners,
9881
- /** `χ_Z`: Dictionary of services that auto-accumulate every block with their gas limit. */
9882
- autoAccumulateServices) {
9883
- this.manager = manager;
9884
- this.delegator = delegator;
9885
- this.registrar = registrar;
9886
- this.assigners = assigners;
9887
- this.autoAccumulateServices = autoAccumulateServices;
10201
+ static empty() {
10202
+ const zero = numbers_tryAsU32(0);
10203
+ return new ValidatorStatistics(zero, zero, zero, zero, zero, zero);
9888
10204
  }
9889
10205
  }
9890
-
9891
- ;// CONCATENATED MODULE: ./packages/jam/state/recent-blocks.ts
9892
-
9893
-
9894
-
9895
-
9896
-
9897
-
10206
+ const codecVarU16 = descriptors_codec.varU32.convert((i) => numbers_tryAsU32(i), (o) => numbers_tryAsU16(o));
10207
+ /** Encode/decode unsigned gas. */
10208
+ const codecVarGas = descriptors_codec.varU64.convert((g) => numbers_tryAsU64(g), (i) => tryAsServiceGas(i));
9898
10209
  /**
9899
- * `H = 8`: The size of recent history, in blocks.
10210
+ * Single core statistics.
10211
+ * Updated per block, based on incoming work reports (`w`).
9900
10212
  *
9901
- * https://graypaper.fluffylabs.dev/#/579bd12/416300416500
10213
+ * https://graypaper.fluffylabs.dev/#/68eaa1f/18f10318f103?v=0.6.4
10214
+ * https://github.com/gavofyork/graypaper/blob/9bffb08f3ea7b67832019176754df4fb36b9557d/text/statistics.tex#L65
9902
10215
  */
9903
- const MAX_RECENT_HISTORY = 8;
9904
- /** Recent history of a single block. */
9905
- class BlockState extends WithDebug {
9906
- headerHash;
9907
- accumulationResult;
9908
- postStateRoot;
9909
- reported;
9910
- static Codec = descriptors_codec.Class(BlockState, {
9911
- headerHash: descriptors_codec.bytes(hash_HASH_SIZE).asOpaque(),
9912
- accumulationResult: descriptors_codec.bytes(hash_HASH_SIZE),
9913
- postStateRoot: descriptors_codec.bytes(hash_HASH_SIZE).asOpaque(),
9914
- reported: codecHashDictionary(WorkPackageInfo.Codec, (x) => x.workPackageHash),
9915
- });
9916
- static create({ headerHash, accumulationResult, postStateRoot, reported }) {
9917
- return new BlockState(headerHash, accumulationResult, postStateRoot, reported);
10216
+ class CoreStatistics {
10217
+ dataAvailabilityLoad;
10218
+ popularity;
10219
+ imports;
10220
+ exports;
10221
+ extrinsicSize;
10222
+ extrinsicCount;
10223
+ bundleSize;
10224
+ gasUsed;
10225
+ static Codec = Compatibility.isGreaterOrEqual(GpVersion.V0_7_0)
10226
+ ? descriptors_codec.Class(CoreStatistics, {
10227
+ dataAvailabilityLoad: descriptors_codec.varU32,
10228
+ popularity: codecVarU16,
10229
+ imports: codecVarU16,
10230
+ extrinsicCount: codecVarU16,
10231
+ extrinsicSize: descriptors_codec.varU32,
10232
+ exports: codecVarU16,
10233
+ bundleSize: descriptors_codec.varU32,
10234
+ gasUsed: codecVarGas,
10235
+ })
10236
+ : descriptors_codec.Class(CoreStatistics, {
10237
+ dataAvailabilityLoad: descriptors_codec.varU32,
10238
+ popularity: codecVarU16,
10239
+ imports: codecVarU16,
10240
+ exports: codecVarU16,
10241
+ extrinsicSize: descriptors_codec.varU32,
10242
+ extrinsicCount: codecVarU16,
10243
+ bundleSize: descriptors_codec.varU32,
10244
+ gasUsed: codecVarGas,
10245
+ });
10246
+ static create(v) {
10247
+ return new CoreStatistics(v.dataAvailabilityLoad, v.popularity, v.imports, v.exports, v.extrinsicSize, v.extrinsicCount, v.bundleSize, v.gasUsed);
9918
10248
  }
9919
10249
  constructor(
9920
- /** Header hash. */
9921
- headerHash,
9922
- /** Merkle mountain belt of accumulation result. */
9923
- accumulationResult,
9924
- /** Posterior state root filled in with a 1-block delay. */
9925
- postStateRoot,
9926
- /** Reported work packages (no more than number of cores). */
9927
- reported) {
9928
- super();
9929
- this.headerHash = headerHash;
9930
- this.accumulationResult = accumulationResult;
9931
- this.postStateRoot = postStateRoot;
9932
- this.reported = reported;
9933
- }
9934
- }
9935
- class RecentBlocks extends WithDebug {
9936
- blocks;
9937
- accumulationLog;
9938
- static Codec = descriptors_codec.Class(RecentBlocks, {
9939
- blocks: codecKnownSizeArray(BlockState.Codec, {
9940
- minLength: 0,
9941
- maxLength: MAX_RECENT_HISTORY,
9942
- typicalLength: MAX_RECENT_HISTORY,
9943
- }),
9944
- accumulationLog: descriptors_codec.object({
9945
- peaks: readonlyArray(descriptors_codec.sequenceVarLen(descriptors_codec.optional(descriptors_codec.bytes(hash_HASH_SIZE)))),
9946
- }),
9947
- });
9948
- static create(a) {
9949
- return new RecentBlocks(a.blocks, a.accumulationLog);
10250
+ /** `d` */
10251
+ dataAvailabilityLoad,
10252
+ /** `p` */
10253
+ popularity,
10254
+ /** `i` */
10255
+ imports,
10256
+ /** `e` */
10257
+ exports,
10258
+ /** `z` */
10259
+ extrinsicSize,
10260
+ /** `x` */
10261
+ extrinsicCount,
10262
+ /** `b` */
10263
+ bundleSize,
10264
+ /** `u` */
10265
+ gasUsed) {
10266
+ this.dataAvailabilityLoad = dataAvailabilityLoad;
10267
+ this.popularity = popularity;
10268
+ this.imports = imports;
10269
+ this.exports = exports;
10270
+ this.extrinsicSize = extrinsicSize;
10271
+ this.extrinsicCount = extrinsicCount;
10272
+ this.bundleSize = bundleSize;
10273
+ this.gasUsed = gasUsed;
9950
10274
  }
9951
- constructor(
9952
- /**
9953
- * Most recent blocks.
9954
- * https://graypaper.fluffylabs.dev/#/7e6ff6a/0fea010fea01?v=0.6.7
9955
- */
9956
- blocks,
9957
- /**
9958
- * Accumulation output log.
9959
- * https://graypaper.fluffylabs.dev/#/7e6ff6a/0f02020f0202?v=0.6.7
9960
- */
9961
- accumulationLog) {
9962
- super();
9963
- this.blocks = blocks;
9964
- this.accumulationLog = accumulationLog;
10275
+ static empty() {
10276
+ const zero = numbers_tryAsU32(0);
10277
+ const zero16 = numbers_tryAsU16(0);
10278
+ const zeroGas = tryAsServiceGas(0);
10279
+ return new CoreStatistics(zero, zero16, zero16, zero16, zero, zero16, zero, zeroGas);
9965
10280
  }
9966
10281
  }
9967
10282
  /**
9968
- * Recent history of blocks.
10283
+ * Service statistics.
10284
+ * Updated per block, based on available work reports (`W`).
9969
10285
  *
9970
- * https://graypaper.fluffylabs.dev/#/7e6ff6a/0fc9010fc901?v=0.6.7
10286
+ * https://graypaper.fluffylabs.dev/#/1c979cb/199802199802?v=0.7.1
9971
10287
  */
9972
- class RecentBlocksHistory extends WithDebug {
9973
- current;
9974
- static Codec = Descriptor.new("RecentBlocksHistory", RecentBlocks.Codec.sizeHint, (encoder, value) => RecentBlocks.Codec.encode(encoder, value.asCurrent()), (decoder) => {
9975
- const recentBlocks = RecentBlocks.Codec.decode(decoder);
9976
- return RecentBlocksHistory.create(recentBlocks);
9977
- }, (skip) => {
9978
- return RecentBlocks.Codec.skip(skip);
10288
+ class ServiceStatistics {
10289
+ providedCount;
10290
+ providedSize;
10291
+ refinementCount;
10292
+ refinementGasUsed;
10293
+ imports;
10294
+ exports;
10295
+ extrinsicSize;
10296
+ extrinsicCount;
10297
+ accumulateCount;
10298
+ accumulateGasUsed;
10299
+ onTransfersCount;
10300
+ onTransfersGasUsed;
10301
+ static Codec = Compatibility.selectIfGreaterOrEqual({
10302
+ fallback: descriptors_codec.Class(ServiceStatistics, {
10303
+ providedCount: codecVarU16,
10304
+ providedSize: descriptors_codec.varU32,
10305
+ refinementCount: descriptors_codec.varU32,
10306
+ refinementGasUsed: codecVarGas,
10307
+ imports: codecVarU16,
10308
+ exports: codecVarU16,
10309
+ extrinsicSize: descriptors_codec.varU32,
10310
+ extrinsicCount: codecVarU16,
10311
+ accumulateCount: descriptors_codec.varU32,
10312
+ accumulateGasUsed: codecVarGas,
10313
+ onTransfersCount: descriptors_codec.varU32,
10314
+ onTransfersGasUsed: codecVarGas,
10315
+ }),
10316
+ versions: {
10317
+ [GpVersion.V0_7_0]: descriptors_codec.Class(ServiceStatistics, {
10318
+ providedCount: codecVarU16,
10319
+ providedSize: descriptors_codec.varU32,
10320
+ refinementCount: descriptors_codec.varU32,
10321
+ refinementGasUsed: codecVarGas,
10322
+ imports: codecVarU16,
10323
+ extrinsicCount: codecVarU16,
10324
+ extrinsicSize: descriptors_codec.varU32,
10325
+ exports: codecVarU16,
10326
+ accumulateCount: descriptors_codec.varU32,
10327
+ accumulateGasUsed: codecVarGas,
10328
+ onTransfersCount: descriptors_codec.varU32,
10329
+ onTransfersGasUsed: codecVarGas,
10330
+ }),
10331
+ [GpVersion.V0_7_1]: descriptors_codec.Class(ServiceStatistics, {
10332
+ providedCount: codecVarU16,
10333
+ providedSize: descriptors_codec.varU32,
10334
+ refinementCount: descriptors_codec.varU32,
10335
+ refinementGasUsed: codecVarGas,
10336
+ imports: codecVarU16,
10337
+ extrinsicCount: codecVarU16,
10338
+ extrinsicSize: descriptors_codec.varU32,
10339
+ exports: codecVarU16,
10340
+ accumulateCount: descriptors_codec.varU32,
10341
+ accumulateGasUsed: codecVarGas,
10342
+ onTransfersCount: ignoreValueWithDefault(numbers_tryAsU32(0)),
10343
+ onTransfersGasUsed: ignoreValueWithDefault(tryAsServiceGas(0)),
10344
+ }),
10345
+ },
9979
10346
  });
9980
- static create(recentBlocks) {
9981
- return new RecentBlocksHistory(recentBlocks);
10347
+ static create(v) {
10348
+ return new ServiceStatistics(v.providedCount, v.providedSize, v.refinementCount, v.refinementGasUsed, v.imports, v.exports, v.extrinsicSize, v.extrinsicCount, v.accumulateCount, v.accumulateGasUsed, v.onTransfersCount, v.onTransfersGasUsed);
10349
+ }
10350
+ constructor(
10351
+ /** `p.0` */
10352
+ providedCount,
10353
+ /** `p.1` */
10354
+ providedSize,
10355
+ /** `r.0` */
10356
+ refinementCount,
10357
+ /** `r.1` */
10358
+ refinementGasUsed,
10359
+ /** `i` */
10360
+ imports,
10361
+ /** `e` */
10362
+ exports,
10363
+ /** `z` */
10364
+ extrinsicSize,
10365
+ /** `x` */
10366
+ extrinsicCount,
10367
+ /** `a.0` */
10368
+ accumulateCount,
10369
+ /** `a.1` */
10370
+ accumulateGasUsed,
10371
+ /** `t.0` @deprecated since 0.7.1 */
10372
+ onTransfersCount,
10373
+ /** `t.1` @deprecated since 0.7.1 */
10374
+ onTransfersGasUsed) {
10375
+ this.providedCount = providedCount;
10376
+ this.providedSize = providedSize;
10377
+ this.refinementCount = refinementCount;
10378
+ this.refinementGasUsed = refinementGasUsed;
10379
+ this.imports = imports;
10380
+ this.exports = exports;
10381
+ this.extrinsicSize = extrinsicSize;
10382
+ this.extrinsicCount = extrinsicCount;
10383
+ this.accumulateCount = accumulateCount;
10384
+ this.accumulateGasUsed = accumulateGasUsed;
10385
+ this.onTransfersCount = onTransfersCount;
10386
+ this.onTransfersGasUsed = onTransfersGasUsed;
9982
10387
  }
9983
10388
  static empty() {
9984
- return RecentBlocksHistory.create(RecentBlocks.create({
9985
- blocks: sized_array_asKnownSize([]),
9986
- accumulationLog: { peaks: [] },
9987
- }));
10389
+ const zero = numbers_tryAsU32(0);
10390
+ const zero16 = numbers_tryAsU16(0);
10391
+ const zeroGas = tryAsServiceGas(0);
10392
+ return new ServiceStatistics(zero16, zero, zero, zeroGas, zero16, zero16, zero, zero16, zero, zeroGas, zero, zeroGas);
9988
10393
  }
9989
- /**
9990
- * Returns the block's BEEFY super peak.
9991
- */
9992
- static accumulationResult(block) {
9993
- return block.accumulationResult;
10394
+ }
10395
+ /** `pi`: Statistics of each validator, cores statistics and services statistics. */
10396
+ class StatisticsData {
10397
+ current;
10398
+ previous;
10399
+ cores;
10400
+ services;
10401
+ static Codec = descriptors_codec.Class(StatisticsData, {
10402
+ current: common_codecPerValidator(ValidatorStatistics.Codec),
10403
+ previous: common_codecPerValidator(ValidatorStatistics.Codec),
10404
+ cores: codecPerCore(CoreStatistics.Codec),
10405
+ services: descriptors_codec.dictionary(codecServiceId, ServiceStatistics.Codec, {
10406
+ sortKeys: (a, b) => a - b,
10407
+ }),
10408
+ });
10409
+ static create(v) {
10410
+ return new StatisticsData(v.current, v.previous, v.cores, v.services);
9994
10411
  }
9995
- constructor(current) {
9996
- super();
10412
+ constructor(current, previous, cores, services) {
9997
10413
  this.current = current;
9998
- }
9999
- /** History of recent blocks with maximum size of `MAX_RECENT_HISTORY` */
10000
- get blocks() {
10001
- if (this.current !== null) {
10002
- return this.current.blocks;
10003
- }
10004
- throw new Error("RecentBlocksHistory is in invalid state");
10005
- }
10006
- asCurrent() {
10007
- if (this.current === null) {
10008
- throw new Error("Cannot access current RecentBlocks format");
10009
- }
10010
- return this.current;
10011
- }
10012
- updateBlocks(blocks) {
10013
- if (this.current !== null) {
10014
- return RecentBlocksHistory.create(RecentBlocks.create({
10015
- ...this.current,
10016
- blocks: opaque_asOpaqueType(blocks),
10017
- }));
10018
- }
10019
- throw new Error("RecentBlocksHistory is in invalid state. Cannot be updated!");
10414
+ this.previous = previous;
10415
+ this.cores = cores;
10416
+ this.services = services;
10020
10417
  }
10021
10418
  }
10022
10419
 
10023
- ;// CONCATENATED MODULE: ./packages/jam/state/validator-data.ts
10420
+ ;// CONCATENATED MODULE: ./packages/jam/state/in-memory-state-view.ts
10024
10421
 
10025
10422
 
10026
10423
 
10027
- /**
10028
- * Fixed size of validator metadata.
10029
- *
10030
- * https://graypaper.fluffylabs.dev/#/5f542d7/0d55010d5501
10031
- */
10032
- const VALIDATOR_META_BYTES = 128;
10033
- /**
10034
- * Details about validators' identity.
10035
- *
10036
- * https://graypaper.fluffylabs.dev/#/5f542d7/0d4b010d4c01
10037
- */
10038
- class ValidatorData extends WithDebug {
10039
- bandersnatch;
10040
- ed25519;
10041
- bls;
10042
- metadata;
10043
- static Codec = descriptors_codec.Class(ValidatorData, {
10044
- bandersnatch: descriptors_codec.bytes(BANDERSNATCH_KEY_BYTES).asOpaque(),
10045
- ed25519: descriptors_codec.bytes(ED25519_KEY_BYTES).asOpaque(),
10046
- bls: descriptors_codec.bytes(BLS_KEY_BYTES).asOpaque(),
10047
- metadata: descriptors_codec.bytes(VALIDATOR_META_BYTES),
10048
- });
10049
- static create({ ed25519, bandersnatch, bls, metadata }) {
10050
- return new ValidatorData(bandersnatch, ed25519, bls, metadata);
10051
- }
10052
- constructor(
10053
- /** Bandersnatch public key. */
10054
- bandersnatch,
10055
- /** ED25519 key data. */
10056
- ed25519,
10057
- /** BLS public key. */
10058
- bls,
10059
- /** Validator-defined additional metdata. */
10060
- metadata) {
10061
- super();
10062
- this.bandersnatch = bandersnatch;
10063
- this.ed25519 = ed25519;
10064
- this.bls = bls;
10065
- this.metadata = metadata;
10066
- }
10067
- }
10068
10424
 
10069
- ;// CONCATENATED MODULE: ./packages/jam/state/safrole-data.ts
10070
10425
 
10071
10426
 
10072
10427
 
10073
10428
 
10074
10429
 
10075
10430
 
10431
+ class InMemoryStateView {
10432
+ chainSpec;
10433
+ state;
10434
+ constructor(chainSpec, state) {
10435
+ this.chainSpec = chainSpec;
10436
+ this.state = state;
10437
+ }
10438
+ availabilityAssignmentView() {
10439
+ return reencodeAsView(availabilityAssignmentsCodec, this.state.availabilityAssignment, this.chainSpec);
10440
+ }
10441
+ designatedValidatorDataView() {
10442
+ return reencodeAsView(validatorsDataCodec, this.state.designatedValidatorData, this.chainSpec);
10443
+ }
10444
+ currentValidatorDataView() {
10445
+ return reencodeAsView(validatorsDataCodec, this.state.currentValidatorData, this.chainSpec);
10446
+ }
10447
+ previousValidatorDataView() {
10448
+ return reencodeAsView(validatorsDataCodec, this.state.previousValidatorData, this.chainSpec);
10449
+ }
10450
+ authPoolsView() {
10451
+ return reencodeAsView(authPoolsCodec, this.state.authPools, this.chainSpec);
10452
+ }
10453
+ authQueuesView() {
10454
+ return reencodeAsView(authQueuesCodec, this.state.authQueues, this.chainSpec);
10455
+ }
10456
+ recentBlocksView() {
10457
+ return reencodeAsView(RecentBlocks.Codec, this.state.recentBlocks, this.chainSpec);
10458
+ }
10459
+ statisticsView() {
10460
+ return reencodeAsView(StatisticsData.Codec, this.state.statistics, this.chainSpec);
10461
+ }
10462
+ accumulationQueueView() {
10463
+ return reencodeAsView(accumulationQueueCodec, this.state.accumulationQueue, this.chainSpec);
10464
+ }
10465
+ recentlyAccumulatedView() {
10466
+ return reencodeAsView(recentlyAccumulatedCodec, this.state.recentlyAccumulated, this.chainSpec);
10467
+ }
10468
+ safroleDataView() {
10469
+ // TODO [ToDr] Consider exposting `safrole` from state
10470
+ // instead of individual fields
10471
+ const safrole = SafroleData.create({
10472
+ nextValidatorData: this.state.nextValidatorData,
10473
+ epochRoot: this.state.epochRoot,
10474
+ sealingKeySeries: this.state.sealingKeySeries,
10475
+ ticketsAccumulator: this.state.ticketsAccumulator,
10476
+ });
10477
+ return reencodeAsView(SafroleData.Codec, safrole, this.chainSpec);
10478
+ }
10479
+ getServiceInfoView(id) {
10480
+ const service = this.state.getService(id);
10481
+ if (service === null) {
10482
+ return null;
10483
+ }
10484
+ return reencodeAsView(ServiceAccountInfo.Codec, service.getInfo(), this.chainSpec);
10485
+ }
10486
+ }
10076
10487
 
10488
+ ;// CONCATENATED MODULE: ./packages/jam/state/privileged-services.ts
10077
10489
 
10078
10490
 
10079
10491
 
10080
10492
 
10081
- var SafroleSealingKeysKind;
10082
- (function (SafroleSealingKeysKind) {
10083
- SafroleSealingKeysKind[SafroleSealingKeysKind["Tickets"] = 0] = "Tickets";
10084
- SafroleSealingKeysKind[SafroleSealingKeysKind["Keys"] = 1] = "Keys";
10085
- })(SafroleSealingKeysKind || (SafroleSealingKeysKind = {}));
10086
- const codecBandersnatchKey = descriptors_codec.bytes(BANDERSNATCH_KEY_BYTES).asOpaque();
10087
- class SafroleSealingKeysData extends WithDebug {
10088
- kind;
10089
- keys;
10090
- tickets;
10091
- static Codec = codecWithContext((context) => {
10092
- return descriptors_codec.custom({
10093
- name: "SafroleSealingKeys",
10094
- sizeHint: { bytes: 1 + hash_HASH_SIZE * context.epochLength, isExact: false },
10095
- }, (e, x) => {
10096
- e.varU32(numbers_tryAsU32(x.kind));
10097
- if (x.kind === SafroleSealingKeysKind.Keys) {
10098
- e.sequenceFixLen(codecBandersnatchKey, x.keys);
10099
- }
10100
- else {
10101
- e.sequenceFixLen(Ticket.Codec, x.tickets);
10102
- }
10103
- }, (d) => {
10104
- const epochLength = context.epochLength;
10105
- const kind = d.varU32();
10106
- if (kind === SafroleSealingKeysKind.Keys) {
10107
- const keys = d.sequenceFixLen(codecBandersnatchKey, epochLength);
10108
- return SafroleSealingKeysData.keys(tryAsPerEpochBlock(keys, context));
10109
- }
10110
- if (kind === SafroleSealingKeysKind.Tickets) {
10111
- const tickets = d.sequenceFixLen(Ticket.Codec, epochLength);
10112
- return SafroleSealingKeysData.tickets(tryAsPerEpochBlock(tickets, context));
10113
- }
10114
- throw new Error(`Unexpected safrole sealing keys kind: ${kind}`);
10115
- }, (s) => {
10116
- const kind = s.decoder.varU32();
10117
- if (kind === SafroleSealingKeysKind.Keys) {
10118
- s.sequenceFixLen(codecBandersnatchKey, context.epochLength);
10119
- return;
10120
- }
10121
- if (kind === SafroleSealingKeysKind.Tickets) {
10122
- s.sequenceFixLen(Ticket.Codec, context.epochLength);
10123
- return;
10124
- }
10125
- throw new Error(`Unexpected safrole sealing keys kind: ${kind}`);
10126
- });
10493
+
10494
+ /** Dictionary entry of services that auto-accumulate every block. */
10495
+ class AutoAccumulate {
10496
+ service;
10497
+ gasLimit;
10498
+ static Codec = descriptors_codec.Class(AutoAccumulate, {
10499
+ service: descriptors_codec.u32.asOpaque(),
10500
+ gasLimit: descriptors_codec.u64.asOpaque(),
10127
10501
  });
10128
- static keys(keys) {
10129
- return new SafroleSealingKeysData(SafroleSealingKeysKind.Keys, keys, undefined);
10130
- }
10131
- static tickets(tickets) {
10132
- return new SafroleSealingKeysData(SafroleSealingKeysKind.Tickets, undefined, tickets);
10502
+ static create({ service, gasLimit }) {
10503
+ return new AutoAccumulate(service, gasLimit);
10133
10504
  }
10134
- constructor(kind, keys, tickets) {
10135
- super();
10136
- this.kind = kind;
10137
- this.keys = keys;
10138
- this.tickets = tickets;
10505
+ constructor(
10506
+ /** Service id that auto-accumulates. */
10507
+ service,
10508
+ /** Gas limit for auto-accumulation. */
10509
+ gasLimit) {
10510
+ this.service = service;
10511
+ this.gasLimit = gasLimit;
10139
10512
  }
10140
10513
  }
10141
- class SafroleData {
10142
- nextValidatorData;
10143
- epochRoot;
10144
- sealingKeySeries;
10145
- ticketsAccumulator;
10146
- static Codec = descriptors_codec.Class(SafroleData, {
10147
- nextValidatorData: codecPerValidator(ValidatorData.Codec),
10148
- epochRoot: descriptors_codec.bytes(BANDERSNATCH_RING_ROOT_BYTES).asOpaque(),
10149
- sealingKeySeries: SafroleSealingKeysData.Codec,
10150
- ticketsAccumulator: readonlyArray(descriptors_codec.sequenceVarLen(Ticket.Codec)).convert(seeThrough, sized_array_asKnownSize),
10514
+ /**
10515
+ * https://graypaper.fluffylabs.dev/#/ab2cdbd/114402114402?v=0.7.2
10516
+ */
10517
+ class PrivilegedServices {
10518
+ manager;
10519
+ delegator;
10520
+ registrar;
10521
+ assigners;
10522
+ autoAccumulateServices;
10523
+ /** https://graypaper.fluffylabs.dev/#/ab2cdbd/3bbd023bcb02?v=0.7.2 */
10524
+ static Codec = descriptors_codec.Class(PrivilegedServices, {
10525
+ manager: descriptors_codec.u32.asOpaque(),
10526
+ assigners: codecPerCore(descriptors_codec.u32.asOpaque()),
10527
+ delegator: descriptors_codec.u32.asOpaque(),
10528
+ registrar: Compatibility.isGreaterOrEqual(GpVersion.V0_7_1)
10529
+ ? descriptors_codec.u32.asOpaque()
10530
+ : ignoreValueWithDefault(tryAsServiceId(2 ** 32 - 1)),
10531
+ autoAccumulateServices: descriptors_readonlyArray(descriptors_codec.sequenceVarLen(AutoAccumulate.Codec)),
10151
10532
  });
10152
- static create({ nextValidatorData, epochRoot, sealingKeySeries, ticketsAccumulator }) {
10153
- return new SafroleData(nextValidatorData, epochRoot, sealingKeySeries, ticketsAccumulator);
10533
+ static create(a) {
10534
+ return new PrivilegedServices(a.manager, a.delegator, a.registrar, a.assigners, a.autoAccumulateServices);
10154
10535
  }
10155
10536
  constructor(
10156
- /** gamma_k */
10157
- nextValidatorData,
10158
- /** gamma_z */
10159
- epochRoot,
10160
- /** gamma_s */
10161
- sealingKeySeries,
10162
- /** gamma_a */
10163
- ticketsAccumulator) {
10164
- this.nextValidatorData = nextValidatorData;
10165
- this.epochRoot = epochRoot;
10166
- this.sealingKeySeries = sealingKeySeries;
10167
- this.ticketsAccumulator = ticketsAccumulator;
10537
+ /**
10538
+ * `χ_M`: Manages alteration of χ from block to block,
10539
+ * as well as bestow services with storage deposit credits.
10540
+ * https://graypaper.fluffylabs.dev/#/ab2cdbd/111502111902?v=0.7.2
10541
+ */
10542
+ manager,
10543
+ /** `χ_V`: Managers validator keys. */
10544
+ delegator,
10545
+ /**
10546
+ * `χ_R`: Manages the creation of services in protected range.
10547
+ *
10548
+ * https://graypaper.fluffylabs.dev/#/ab2cdbd/111b02111d02?v=0.7.2
10549
+ */
10550
+ registrar,
10551
+ /** `χ_A`: Manages authorization queue one for each core. */
10552
+ assigners,
10553
+ /** `χ_Z`: Dictionary of services that auto-accumulate every block with their gas limit. */
10554
+ autoAccumulateServices) {
10555
+ this.manager = manager;
10556
+ this.delegator = delegator;
10557
+ this.registrar = registrar;
10558
+ this.assigners = assigners;
10559
+ this.autoAccumulateServices = autoAccumulateServices;
10168
10560
  }
10169
10561
  }
10170
10562
 
@@ -10291,313 +10683,41 @@ class UpdateService {
10291
10683
  }
10292
10684
  /** Update service storage kind. */
10293
10685
  var UpdateStorageKind;
10294
- (function (UpdateStorageKind) {
10295
- /** Set a storage value. */
10296
- UpdateStorageKind[UpdateStorageKind["Set"] = 0] = "Set";
10297
- /** Remove a storage value. */
10298
- UpdateStorageKind[UpdateStorageKind["Remove"] = 1] = "Remove";
10299
- })(UpdateStorageKind || (UpdateStorageKind = {}));
10300
- /**
10301
- * Update service storage item.
10302
- *
10303
- * Can either create/modify an entry or remove it.
10304
- */
10305
- class UpdateStorage {
10306
- serviceId;
10307
- action;
10308
- constructor(serviceId, action) {
10309
- this.serviceId = serviceId;
10310
- this.action = action;
10311
- }
10312
- static set({ serviceId, storage }) {
10313
- return new UpdateStorage(serviceId, { kind: UpdateStorageKind.Set, storage });
10314
- }
10315
- static remove({ serviceId, key }) {
10316
- return new UpdateStorage(serviceId, { kind: UpdateStorageKind.Remove, key });
10317
- }
10318
- get key() {
10319
- if (this.action.kind === UpdateStorageKind.Remove) {
10320
- return this.action.key;
10321
- }
10322
- return this.action.storage.key;
10323
- }
10324
- get value() {
10325
- if (this.action.kind === UpdateStorageKind.Remove) {
10326
- return null;
10327
- }
10328
- return this.action.storage.value;
10329
- }
10330
- }
10331
-
10332
- ;// CONCATENATED MODULE: ./packages/jam/state/statistics.ts
10333
-
10334
-
10335
-
10336
-
10337
-
10338
-
10339
- const codecServiceId = Compatibility.isSuite(TestSuite.W3F_DAVXY) || Compatibility.isSuite(TestSuite.JAMDUNA, GpVersion.V0_6_7)
10340
- ? descriptors_codec.u32.asOpaque()
10341
- : descriptors_codec.varU32.convert((s) => numbers_tryAsU32(s), (i) => tryAsServiceId(i));
10342
- /**
10343
- * Activity Record of a single validator.
10344
- *
10345
- * https://graypaper.fluffylabs.dev/#/579bd12/183701183701
10346
- */
10347
- class ValidatorStatistics {
10348
- blocks;
10349
- tickets;
10350
- preImages;
10351
- preImagesSize;
10352
- guarantees;
10353
- assurances;
10354
- static Codec = descriptors_codec.Class(ValidatorStatistics, {
10355
- blocks: descriptors_codec.u32,
10356
- tickets: descriptors_codec.u32,
10357
- preImages: descriptors_codec.u32,
10358
- preImagesSize: descriptors_codec.u32,
10359
- guarantees: descriptors_codec.u32,
10360
- assurances: descriptors_codec.u32,
10361
- });
10362
- static create({ blocks, tickets, preImages, preImagesSize, guarantees, assurances, }) {
10363
- return new ValidatorStatistics(blocks, tickets, preImages, preImagesSize, guarantees, assurances);
10364
- }
10365
- constructor(
10366
- /** The number of blocks produced by the validator. */
10367
- blocks,
10368
- /** The number of tickets introduced by the validator. */
10369
- tickets,
10370
- /** The number of preimages introduced by the validator. */
10371
- preImages,
10372
- /** The total number of octets across all preimages introduced by the validator. */
10373
- preImagesSize,
10374
- /** The number of reports guaranteed by the validator. */
10375
- guarantees,
10376
- /** The number of availability assurances made by the validator. */
10377
- assurances) {
10378
- this.blocks = blocks;
10379
- this.tickets = tickets;
10380
- this.preImages = preImages;
10381
- this.preImagesSize = preImagesSize;
10382
- this.guarantees = guarantees;
10383
- this.assurances = assurances;
10384
- }
10385
- static empty() {
10386
- const zero = numbers_tryAsU32(0);
10387
- return new ValidatorStatistics(zero, zero, zero, zero, zero, zero);
10388
- }
10389
- }
10390
- const codecVarU16 = descriptors_codec.varU32.convert((i) => numbers_tryAsU32(i), (o) => numbers_tryAsU16(o));
10391
- /** Encode/decode unsigned gas. */
10392
- const codecVarGas = descriptors_codec.varU64.convert((g) => numbers_tryAsU64(g), (i) => tryAsServiceGas(i));
10393
- /**
10394
- * Single core statistics.
10395
- * Updated per block, based on incoming work reports (`w`).
10396
- *
10397
- * https://graypaper.fluffylabs.dev/#/68eaa1f/18f10318f103?v=0.6.4
10398
- * https://github.com/gavofyork/graypaper/blob/9bffb08f3ea7b67832019176754df4fb36b9557d/text/statistics.tex#L65
10399
- */
10400
- class CoreStatistics {
10401
- dataAvailabilityLoad;
10402
- popularity;
10403
- imports;
10404
- exports;
10405
- extrinsicSize;
10406
- extrinsicCount;
10407
- bundleSize;
10408
- gasUsed;
10409
- static Codec = Compatibility.isGreaterOrEqual(GpVersion.V0_7_0)
10410
- ? descriptors_codec.Class(CoreStatistics, {
10411
- dataAvailabilityLoad: descriptors_codec.varU32,
10412
- popularity: codecVarU16,
10413
- imports: codecVarU16,
10414
- extrinsicCount: codecVarU16,
10415
- extrinsicSize: descriptors_codec.varU32,
10416
- exports: codecVarU16,
10417
- bundleSize: descriptors_codec.varU32,
10418
- gasUsed: codecVarGas,
10419
- })
10420
- : descriptors_codec.Class(CoreStatistics, {
10421
- dataAvailabilityLoad: descriptors_codec.varU32,
10422
- popularity: codecVarU16,
10423
- imports: codecVarU16,
10424
- exports: codecVarU16,
10425
- extrinsicSize: descriptors_codec.varU32,
10426
- extrinsicCount: codecVarU16,
10427
- bundleSize: descriptors_codec.varU32,
10428
- gasUsed: codecVarGas,
10429
- });
10430
- static create(v) {
10431
- return new CoreStatistics(v.dataAvailabilityLoad, v.popularity, v.imports, v.exports, v.extrinsicSize, v.extrinsicCount, v.bundleSize, v.gasUsed);
10432
- }
10433
- constructor(
10434
- /** `d` */
10435
- dataAvailabilityLoad,
10436
- /** `p` */
10437
- popularity,
10438
- /** `i` */
10439
- imports,
10440
- /** `e` */
10441
- exports,
10442
- /** `z` */
10443
- extrinsicSize,
10444
- /** `x` */
10445
- extrinsicCount,
10446
- /** `b` */
10447
- bundleSize,
10448
- /** `u` */
10449
- gasUsed) {
10450
- this.dataAvailabilityLoad = dataAvailabilityLoad;
10451
- this.popularity = popularity;
10452
- this.imports = imports;
10453
- this.exports = exports;
10454
- this.extrinsicSize = extrinsicSize;
10455
- this.extrinsicCount = extrinsicCount;
10456
- this.bundleSize = bundleSize;
10457
- this.gasUsed = gasUsed;
10458
- }
10459
- static empty() {
10460
- const zero = numbers_tryAsU32(0);
10461
- const zero16 = numbers_tryAsU16(0);
10462
- const zeroGas = tryAsServiceGas(0);
10463
- return new CoreStatistics(zero, zero16, zero16, zero16, zero, zero16, zero, zeroGas);
10464
- }
10465
- }
10686
+ (function (UpdateStorageKind) {
10687
+ /** Set a storage value. */
10688
+ UpdateStorageKind[UpdateStorageKind["Set"] = 0] = "Set";
10689
+ /** Remove a storage value. */
10690
+ UpdateStorageKind[UpdateStorageKind["Remove"] = 1] = "Remove";
10691
+ })(UpdateStorageKind || (UpdateStorageKind = {}));
10466
10692
  /**
10467
- * Service statistics.
10468
- * Updated per block, based on available work reports (`W`).
10693
+ * Update service storage item.
10469
10694
  *
10470
- * https://graypaper.fluffylabs.dev/#/1c979cb/199802199802?v=0.7.1
10695
+ * Can either create/modify an entry or remove it.
10471
10696
  */
10472
- class ServiceStatistics {
10473
- providedCount;
10474
- providedSize;
10475
- refinementCount;
10476
- refinementGasUsed;
10477
- imports;
10478
- exports;
10479
- extrinsicSize;
10480
- extrinsicCount;
10481
- accumulateCount;
10482
- accumulateGasUsed;
10483
- onTransfersCount;
10484
- onTransfersGasUsed;
10485
- static Codec = Compatibility.selectIfGreaterOrEqual({
10486
- fallback: descriptors_codec.Class(ServiceStatistics, {
10487
- providedCount: codecVarU16,
10488
- providedSize: descriptors_codec.varU32,
10489
- refinementCount: descriptors_codec.varU32,
10490
- refinementGasUsed: codecVarGas,
10491
- imports: codecVarU16,
10492
- exports: codecVarU16,
10493
- extrinsicSize: descriptors_codec.varU32,
10494
- extrinsicCount: codecVarU16,
10495
- accumulateCount: descriptors_codec.varU32,
10496
- accumulateGasUsed: codecVarGas,
10497
- onTransfersCount: descriptors_codec.varU32,
10498
- onTransfersGasUsed: codecVarGas,
10499
- }),
10500
- versions: {
10501
- [GpVersion.V0_7_0]: descriptors_codec.Class(ServiceStatistics, {
10502
- providedCount: codecVarU16,
10503
- providedSize: descriptors_codec.varU32,
10504
- refinementCount: descriptors_codec.varU32,
10505
- refinementGasUsed: codecVarGas,
10506
- imports: codecVarU16,
10507
- extrinsicCount: codecVarU16,
10508
- extrinsicSize: descriptors_codec.varU32,
10509
- exports: codecVarU16,
10510
- accumulateCount: descriptors_codec.varU32,
10511
- accumulateGasUsed: codecVarGas,
10512
- onTransfersCount: descriptors_codec.varU32,
10513
- onTransfersGasUsed: codecVarGas,
10514
- }),
10515
- [GpVersion.V0_7_1]: descriptors_codec.Class(ServiceStatistics, {
10516
- providedCount: codecVarU16,
10517
- providedSize: descriptors_codec.varU32,
10518
- refinementCount: descriptors_codec.varU32,
10519
- refinementGasUsed: codecVarGas,
10520
- imports: codecVarU16,
10521
- extrinsicCount: codecVarU16,
10522
- extrinsicSize: descriptors_codec.varU32,
10523
- exports: codecVarU16,
10524
- accumulateCount: descriptors_codec.varU32,
10525
- accumulateGasUsed: codecVarGas,
10526
- onTransfersCount: ignoreValueWithDefault(numbers_tryAsU32(0)),
10527
- onTransfersGasUsed: ignoreValueWithDefault(tryAsServiceGas(0)),
10528
- }),
10529
- },
10530
- });
10531
- static create(v) {
10532
- return new ServiceStatistics(v.providedCount, v.providedSize, v.refinementCount, v.refinementGasUsed, v.imports, v.exports, v.extrinsicSize, v.extrinsicCount, v.accumulateCount, v.accumulateGasUsed, v.onTransfersCount, v.onTransfersGasUsed);
10697
+ class UpdateStorage {
10698
+ serviceId;
10699
+ action;
10700
+ constructor(serviceId, action) {
10701
+ this.serviceId = serviceId;
10702
+ this.action = action;
10533
10703
  }
10534
- constructor(
10535
- /** `p.0` */
10536
- providedCount,
10537
- /** `p.1` */
10538
- providedSize,
10539
- /** `r.0` */
10540
- refinementCount,
10541
- /** `r.1` */
10542
- refinementGasUsed,
10543
- /** `i` */
10544
- imports,
10545
- /** `e` */
10546
- exports,
10547
- /** `z` */
10548
- extrinsicSize,
10549
- /** `x` */
10550
- extrinsicCount,
10551
- /** `a.0` */
10552
- accumulateCount,
10553
- /** `a.1` */
10554
- accumulateGasUsed,
10555
- /** `t.0` @deprecated since 0.7.1 */
10556
- onTransfersCount,
10557
- /** `t.1` @deprecated since 0.7.1 */
10558
- onTransfersGasUsed) {
10559
- this.providedCount = providedCount;
10560
- this.providedSize = providedSize;
10561
- this.refinementCount = refinementCount;
10562
- this.refinementGasUsed = refinementGasUsed;
10563
- this.imports = imports;
10564
- this.exports = exports;
10565
- this.extrinsicSize = extrinsicSize;
10566
- this.extrinsicCount = extrinsicCount;
10567
- this.accumulateCount = accumulateCount;
10568
- this.accumulateGasUsed = accumulateGasUsed;
10569
- this.onTransfersCount = onTransfersCount;
10570
- this.onTransfersGasUsed = onTransfersGasUsed;
10704
+ static set({ serviceId, storage }) {
10705
+ return new UpdateStorage(serviceId, { kind: UpdateStorageKind.Set, storage });
10571
10706
  }
10572
- static empty() {
10573
- const zero = numbers_tryAsU32(0);
10574
- const zero16 = numbers_tryAsU16(0);
10575
- const zeroGas = tryAsServiceGas(0);
10576
- return new ServiceStatistics(zero16, zero, zero, zeroGas, zero16, zero16, zero, zero16, zero, zeroGas, zero, zeroGas);
10707
+ static remove({ serviceId, key }) {
10708
+ return new UpdateStorage(serviceId, { kind: UpdateStorageKind.Remove, key });
10577
10709
  }
10578
- }
10579
- /** `pi`: Statistics of each validator, cores statistics and services statistics. */
10580
- class StatisticsData {
10581
- current;
10582
- previous;
10583
- cores;
10584
- services;
10585
- static Codec = descriptors_codec.Class(StatisticsData, {
10586
- current: codecPerValidator(ValidatorStatistics.Codec),
10587
- previous: codecPerValidator(ValidatorStatistics.Codec),
10588
- cores: codecPerCore(CoreStatistics.Codec),
10589
- services: descriptors_codec.dictionary(codecServiceId, ServiceStatistics.Codec, {
10590
- sortKeys: (a, b) => a - b,
10591
- }),
10592
- });
10593
- static create(v) {
10594
- return new StatisticsData(v.current, v.previous, v.cores, v.services);
10710
+ get key() {
10711
+ if (this.action.kind === UpdateStorageKind.Remove) {
10712
+ return this.action.key;
10713
+ }
10714
+ return this.action.storage.key;
10595
10715
  }
10596
- constructor(current, previous, cores, services) {
10597
- this.current = current;
10598
- this.previous = previous;
10599
- this.cores = cores;
10600
- this.services = services;
10716
+ get value() {
10717
+ if (this.action.kind === UpdateStorageKind.Remove) {
10718
+ return null;
10719
+ }
10720
+ return this.action.storage.value;
10601
10721
  }
10602
10722
  }
10603
10723
 
@@ -10622,6 +10742,7 @@ class StatisticsData {
10622
10742
 
10623
10743
 
10624
10744
 
10745
+
10625
10746
 
10626
10747
 
10627
10748
  var in_memory_state_UpdateError;
@@ -10722,10 +10843,11 @@ class InMemoryService extends WithDebug {
10722
10843
  /**
10723
10844
  * A special version of state, stored fully in-memory.
10724
10845
  */
10725
- class InMemoryState extends WithDebug {
10846
+ class in_memory_state_InMemoryState extends WithDebug {
10847
+ chainSpec;
10726
10848
  /** Create a new `InMemoryState` by providing all required fields. */
10727
- static create(state) {
10728
- return new InMemoryState(state);
10849
+ static new(chainSpec, state) {
10850
+ return new in_memory_state_InMemoryState(chainSpec, state);
10729
10851
  }
10730
10852
  /**
10731
10853
  * Create a new `InMemoryState` with a partial state override.
@@ -10734,14 +10856,14 @@ class InMemoryState extends WithDebug {
10734
10856
  * not-necessarily coherent values.
10735
10857
  */
10736
10858
  static partial(spec, partial) {
10737
- const state = InMemoryState.empty(spec);
10859
+ const state = in_memory_state_InMemoryState.empty(spec);
10738
10860
  Object.assign(state, partial);
10739
10861
  return state;
10740
10862
  }
10741
10863
  /**
10742
10864
  * Create a new `InMemoryState` from some other state object.
10743
10865
  */
10744
- static copyFrom(other, servicesData) {
10866
+ static copyFrom(chainSpec, other, servicesData) {
10745
10867
  const services = new Map();
10746
10868
  for (const [id, entries] of servicesData.entries()) {
10747
10869
  const service = other.getService(id);
@@ -10751,7 +10873,7 @@ class InMemoryState extends WithDebug {
10751
10873
  const inMemService = InMemoryService.copyFrom(service, entries);
10752
10874
  services.set(id, inMemService);
10753
10875
  }
10754
- return InMemoryState.create({
10876
+ return in_memory_state_InMemoryState.new(chainSpec, {
10755
10877
  availabilityAssignment: other.availabilityAssignment,
10756
10878
  accumulationQueue: other.accumulationQueue,
10757
10879
  designatedValidatorData: other.designatedValidatorData,
@@ -10948,8 +11070,9 @@ class InMemoryState extends WithDebug {
10948
11070
  getService(id) {
10949
11071
  return this.services.get(id) ?? null;
10950
11072
  }
10951
- constructor(s) {
11073
+ constructor(chainSpec, s) {
10952
11074
  super();
11075
+ this.chainSpec = chainSpec;
10953
11076
  this.availabilityAssignment = s.availabilityAssignment;
10954
11077
  this.designatedValidatorData = s.designatedValidatorData;
10955
11078
  this.nextValidatorData = s.nextValidatorData;
@@ -10971,31 +11094,34 @@ class InMemoryState extends WithDebug {
10971
11094
  this.accumulationOutputLog = s.accumulationOutputLog;
10972
11095
  this.services = s.services;
10973
11096
  }
11097
+ view() {
11098
+ return new InMemoryStateView(this.chainSpec, this);
11099
+ }
10974
11100
  /**
10975
11101
  * Create an empty and possibly incoherent `InMemoryState`.
10976
11102
  */
10977
11103
  static empty(spec) {
10978
- return new InMemoryState({
11104
+ return new in_memory_state_InMemoryState(spec, {
10979
11105
  availabilityAssignment: tryAsPerCore(Array.from({ length: spec.coresCount }, () => null), spec),
10980
- designatedValidatorData: tryAsPerValidator(Array.from({ length: spec.validatorsCount }, () => ValidatorData.create({
11106
+ designatedValidatorData: tryAsPerValidator(Array.from({ length: spec.validatorsCount }, () => validator_data_ValidatorData.create({
10981
11107
  bandersnatch: bytes_Bytes.zero(BANDERSNATCH_KEY_BYTES).asOpaque(),
10982
11108
  bls: bytes_Bytes.zero(BLS_KEY_BYTES).asOpaque(),
10983
11109
  ed25519: bytes_Bytes.zero(ED25519_KEY_BYTES).asOpaque(),
10984
11110
  metadata: bytes_Bytes.zero(VALIDATOR_META_BYTES).asOpaque(),
10985
11111
  })), spec),
10986
- nextValidatorData: tryAsPerValidator(Array.from({ length: spec.validatorsCount }, () => ValidatorData.create({
11112
+ nextValidatorData: tryAsPerValidator(Array.from({ length: spec.validatorsCount }, () => validator_data_ValidatorData.create({
10987
11113
  bandersnatch: bytes_Bytes.zero(BANDERSNATCH_KEY_BYTES).asOpaque(),
10988
11114
  bls: bytes_Bytes.zero(BLS_KEY_BYTES).asOpaque(),
10989
11115
  ed25519: bytes_Bytes.zero(ED25519_KEY_BYTES).asOpaque(),
10990
11116
  metadata: bytes_Bytes.zero(VALIDATOR_META_BYTES).asOpaque(),
10991
11117
  })), spec),
10992
- currentValidatorData: tryAsPerValidator(Array.from({ length: spec.validatorsCount }, () => ValidatorData.create({
11118
+ currentValidatorData: tryAsPerValidator(Array.from({ length: spec.validatorsCount }, () => validator_data_ValidatorData.create({
10993
11119
  bandersnatch: bytes_Bytes.zero(BANDERSNATCH_KEY_BYTES).asOpaque(),
10994
11120
  bls: bytes_Bytes.zero(BLS_KEY_BYTES).asOpaque(),
10995
11121
  ed25519: bytes_Bytes.zero(ED25519_KEY_BYTES).asOpaque(),
10996
11122
  metadata: bytes_Bytes.zero(VALIDATOR_META_BYTES).asOpaque(),
10997
11123
  })), spec),
10998
- previousValidatorData: tryAsPerValidator(Array.from({ length: spec.validatorsCount }, () => ValidatorData.create({
11124
+ previousValidatorData: tryAsPerValidator(Array.from({ length: spec.validatorsCount }, () => validator_data_ValidatorData.create({
10999
11125
  bandersnatch: bytes_Bytes.zero(BANDERSNATCH_KEY_BYTES).asOpaque(),
11000
11126
  bls: bytes_Bytes.zero(BLS_KEY_BYTES).asOpaque(),
11001
11127
  ed25519: bytes_Bytes.zero(ED25519_KEY_BYTES).asOpaque(),
@@ -11011,7 +11137,7 @@ class InMemoryState extends WithDebug {
11011
11137
  entropy: FixedSizeArray.fill(() => bytes_Bytes.zero(hash_HASH_SIZE).asOpaque(), ENTROPY_ENTRIES),
11012
11138
  authPools: tryAsPerCore(Array.from({ length: spec.coresCount }, () => sized_array_asKnownSize([])), spec),
11013
11139
  authQueues: tryAsPerCore(Array.from({ length: spec.coresCount }, () => FixedSizeArray.fill(() => bytes_Bytes.zero(hash_HASH_SIZE).asOpaque(), AUTHORIZATION_QUEUE_SIZE)), spec),
11014
- recentBlocks: RecentBlocksHistory.empty(),
11140
+ recentBlocks: RecentBlocks.empty(),
11015
11141
  statistics: StatisticsData.create({
11016
11142
  current: tryAsPerValidator(Array.from({ length: spec.validatorsCount }, () => ValidatorStatistics.empty()), spec),
11017
11143
  previous: tryAsPerValidator(Array.from({ length: spec.validatorsCount }, () => ValidatorStatistics.empty()), spec),
@@ -11021,8 +11147,8 @@ class InMemoryState extends WithDebug {
11021
11147
  accumulationQueue: tryAsPerEpochBlock(Array.from({ length: spec.epochLength }, () => []), spec),
11022
11148
  recentlyAccumulated: tryAsPerEpochBlock(Array.from({ length: spec.epochLength }, () => HashSet.new()), spec),
11023
11149
  ticketsAccumulator: sized_array_asKnownSize([]),
11024
- sealingKeySeries: SafroleSealingKeysData.keys(tryAsPerEpochBlock(Array.from({ length: spec.epochLength }, () => bytes_Bytes.zero(BANDERSNATCH_KEY_BYTES).asOpaque()), spec)),
11025
- epochRoot: bytes_Bytes.zero(BANDERSNATCH_RING_ROOT_BYTES).asOpaque(),
11150
+ sealingKeySeries: safrole_data_SafroleSealingKeysData.keys(tryAsPerEpochBlock(Array.from({ length: spec.epochLength }, () => bytes_Bytes.zero(BANDERSNATCH_KEY_BYTES).asOpaque()), spec)),
11151
+ epochRoot: bytes_Bytes.zero(bandersnatch_BANDERSNATCH_RING_ROOT_BYTES).asOpaque(),
11026
11152
  privilegedServices: PrivilegedServices.create({
11027
11153
  manager: tryAsServiceId(0),
11028
11154
  assigners: tryAsPerCore(new Array(spec.coresCount).fill(tryAsServiceId(0)), spec),
@@ -11062,51 +11188,10 @@ const serviceDataCodec = descriptors_codec.dictionary(descriptors_codec.u32.asOp
11062
11188
 
11063
11189
 
11064
11190
 
11065
- ;// CONCATENATED MODULE: ./packages/jam/state/not-yet-accumulated.ts
11066
-
11067
11191
 
11068
11192
 
11069
11193
 
11070
11194
 
11071
-
11072
- /**
11073
- * Ready (i.e. available and/or audited) but not-yet-accumulated work-reports.
11074
- *
11075
- * https://graypaper.fluffylabs.dev/#/5f542d7/165300165400
11076
- */
11077
- class NotYetAccumulatedReport extends WithDebug {
11078
- report;
11079
- dependencies;
11080
- static Codec = descriptors_codec.Class(NotYetAccumulatedReport, {
11081
- report: WorkReport.Codec,
11082
- dependencies: codecKnownSizeArray(descriptors_codec.bytes(hash_HASH_SIZE).asOpaque(), {
11083
- typicalLength: MAX_REPORT_DEPENDENCIES / 2,
11084
- maxLength: MAX_REPORT_DEPENDENCIES,
11085
- minLength: 0,
11086
- }),
11087
- });
11088
- static create({ report, dependencies }) {
11089
- return new NotYetAccumulatedReport(report, dependencies);
11090
- }
11091
- constructor(
11092
- /**
11093
- * Each of these were made available at most one epoch ago
11094
- * but have or had unfulfilled dependencies.
11095
- */
11096
- report,
11097
- /**
11098
- * Alongside the work-report itself, we retain its un-accumulated
11099
- * dependencies, a set of work-package hashes.
11100
- *
11101
- * https://graypaper.fluffylabs.dev/#/5f542d7/165800165800
11102
- */
11103
- dependencies) {
11104
- super();
11105
- this.report = report;
11106
- this.dependencies = dependencies;
11107
- }
11108
- }
11109
-
11110
11195
  ;// CONCATENATED MODULE: ./packages/jam/state-merkleization/serialize.ts
11111
11196
 
11112
11197
 
@@ -11119,26 +11204,19 @@ class NotYetAccumulatedReport extends WithDebug {
11119
11204
 
11120
11205
 
11121
11206
 
11122
-
11123
-
11124
-
11125
11207
  /** Serialization for particular state entries. */
11126
- var serialize;
11208
+ var serialize_serialize;
11127
11209
  (function (serialize) {
11128
11210
  /** C(1): https://graypaper.fluffylabs.dev/#/7e6ff6a/3b15013b1501?v=0.6.7 */
11129
11211
  serialize.authPools = {
11130
11212
  key: stateKeys.index(StateKeyIdx.Alpha),
11131
- Codec: codecPerCore(codecKnownSizeArray(descriptors_codec.bytes(hash_HASH_SIZE).asOpaque(), {
11132
- minLength: 0,
11133
- maxLength: MAX_AUTH_POOL_SIZE,
11134
- typicalLength: MAX_AUTH_POOL_SIZE,
11135
- })),
11213
+ Codec: authPoolsCodec,
11136
11214
  extract: (s) => s.authPools,
11137
11215
  };
11138
11216
  /** C(2): https://graypaper.fluffylabs.dev/#/7e6ff6a/3b31013b3101?v=0.6.7 */
11139
11217
  serialize.authQueues = {
11140
11218
  key: stateKeys.index(StateKeyIdx.Phi),
11141
- Codec: codecPerCore(codecFixedSizeArray(descriptors_codec.bytes(hash_HASH_SIZE).asOpaque(), AUTHORIZATION_QUEUE_SIZE)),
11219
+ Codec: authQueuesCodec,
11142
11220
  extract: (s) => s.authQueues,
11143
11221
  };
11144
11222
  /**
@@ -11147,7 +11225,7 @@ var serialize;
11147
11225
  */
11148
11226
  serialize.recentBlocks = {
11149
11227
  key: stateKeys.index(StateKeyIdx.Beta),
11150
- Codec: RecentBlocksHistory.Codec,
11228
+ Codec: RecentBlocks.Codec,
11151
11229
  extract: (s) => s.recentBlocks,
11152
11230
  };
11153
11231
  /** C(4): https://graypaper.fluffylabs.dev/#/7e6ff6a/3b63013b6301?v=0.6.7 */
@@ -11176,25 +11254,25 @@ var serialize;
11176
11254
  /** C(7): https://graypaper.fluffylabs.dev/#/7e6ff6a/3b00023b0002?v=0.6.7 */
11177
11255
  serialize.designatedValidators = {
11178
11256
  key: stateKeys.index(StateKeyIdx.Iota),
11179
- Codec: codecPerValidator(ValidatorData.Codec),
11257
+ Codec: validatorsDataCodec,
11180
11258
  extract: (s) => s.designatedValidatorData,
11181
11259
  };
11182
11260
  /** C(8): https://graypaper.fluffylabs.dev/#/7e6ff6a/3b0d023b0d02?v=0.6.7 */
11183
11261
  serialize.currentValidators = {
11184
11262
  key: stateKeys.index(StateKeyIdx.Kappa),
11185
- Codec: codecPerValidator(ValidatorData.Codec),
11263
+ Codec: validatorsDataCodec,
11186
11264
  extract: (s) => s.currentValidatorData,
11187
11265
  };
11188
11266
  /** C(9): https://graypaper.fluffylabs.dev/#/7e6ff6a/3b1a023b1a02?v=0.6.7 */
11189
11267
  serialize.previousValidators = {
11190
11268
  key: stateKeys.index(StateKeyIdx.Lambda),
11191
- Codec: codecPerValidator(ValidatorData.Codec),
11269
+ Codec: validatorsDataCodec,
11192
11270
  extract: (s) => s.previousValidatorData,
11193
11271
  };
11194
11272
  /** C(10): https://graypaper.fluffylabs.dev/#/7e6ff6a/3b27023b2702?v=0.6.7 */
11195
11273
  serialize.availabilityAssignment = {
11196
11274
  key: stateKeys.index(StateKeyIdx.Rho),
11197
- Codec: codecPerCore(descriptors_codec.optional(AvailabilityAssignment.Codec)),
11275
+ Codec: availabilityAssignmentsCodec,
11198
11276
  extract: (s) => s.availabilityAssignment,
11199
11277
  };
11200
11278
  /** C(11): https://graypaper.fluffylabs.dev/#/7e6ff6a/3b3e023b3e02?v=0.6.7 */
@@ -11218,13 +11296,13 @@ var serialize;
11218
11296
  /** C(14): https://graypaper.fluffylabs.dev/#/1c979cb/3bf0023bf002?v=0.7.1 */
11219
11297
  serialize.accumulationQueue = {
11220
11298
  key: stateKeys.index(StateKeyIdx.Omega),
11221
- Codec: codecPerEpochBlock(readonlyArray(descriptors_codec.sequenceVarLen(NotYetAccumulatedReport.Codec))),
11299
+ Codec: accumulationQueueCodec,
11222
11300
  extract: (s) => s.accumulationQueue,
11223
11301
  };
11224
11302
  /** C(15): https://graypaper.fluffylabs.dev/#/7e6ff6a/3b96023b9602?v=0.6.7 */
11225
11303
  serialize.recentlyAccumulated = {
11226
11304
  key: stateKeys.index(StateKeyIdx.Xi),
11227
- Codec: codecPerEpochBlock(descriptors_codec.sequenceVarLen(descriptors_codec.bytes(hash_HASH_SIZE).asOpaque()).convert((x) => Array.from(x), (x) => HashSet.from(x))),
11305
+ Codec: recentlyAccumulatedCodec,
11228
11306
  extract: (s) => s.recentlyAccumulated,
11229
11307
  };
11230
11308
  /** C(16): https://graypaper.fluffylabs.dev/#/38c4e62/3b46033b4603?v=0.7.0 */
@@ -11253,9 +11331,9 @@ var serialize;
11253
11331
  /** https://graypaper.fluffylabs.dev/#/85129da/387603387603?v=0.6.3 */
11254
11332
  serialize.serviceLookupHistory = (blake2b, serviceId, hash, len) => ({
11255
11333
  key: stateKeys.serviceLookupHistory(blake2b, serviceId, hash, len),
11256
- Codec: readonlyArray(descriptors_codec.sequenceVarLen(descriptors_codec.u32)),
11334
+ Codec: descriptors_readonlyArray(descriptors_codec.sequenceVarLen(descriptors_codec.u32)),
11257
11335
  });
11258
- })(serialize || (serialize = {}));
11336
+ })(serialize_serialize || (serialize_serialize = {}));
11259
11337
  /**
11260
11338
  * Just dump the entire terminal blob as-is.
11261
11339
  *
@@ -11265,6 +11343,87 @@ var serialize;
11265
11343
  */
11266
11344
  const dumpCodec = Descriptor.new("Dump", { bytes: 64, isExact: false }, (e, v) => e.bytes(bytes_Bytes.fromBlob(v.raw, v.raw.length)), (d) => bytes_BytesBlob.blobFrom(d.bytes(d.source.length - d.bytesRead()).raw), (s) => s.bytes(s.decoder.source.length - s.decoder.bytesRead()));
11267
11345
 
11346
+ ;// CONCATENATED MODULE: ./packages/jam/state-merkleization/serialized-state-view.ts
11347
+
11348
+
11349
+ class SerializedStateView {
11350
+ spec;
11351
+ backend;
11352
+ recentlyUsedServices;
11353
+ viewCache;
11354
+ constructor(spec, backend,
11355
+ /** Best-effort list of recently active services. */
11356
+ recentlyUsedServices, viewCache) {
11357
+ this.spec = spec;
11358
+ this.backend = backend;
11359
+ this.recentlyUsedServices = recentlyUsedServices;
11360
+ this.viewCache = viewCache;
11361
+ }
11362
+ retrieveView({ key, Codec }, description) {
11363
+ const cached = this.viewCache.get(key);
11364
+ if (cached !== undefined) {
11365
+ return cached;
11366
+ }
11367
+ const bytes = this.backend.get(key);
11368
+ if (bytes === null) {
11369
+ throw new Error(`Required state entry for ${description} is missing!. Accessing view of key: ${key}`);
11370
+ }
11371
+ // NOTE [ToDr] we are not using `Decoder.decodeObject` here because
11372
+ // it needs to get to the end of the data (skip), yet that's expensive.
11373
+ // we assume that the state data is correct and coherent anyway, so
11374
+ // for performance reasons we simply create the view here.
11375
+ const d = decoder_Decoder.fromBytesBlob(bytes);
11376
+ d.attachContext(this.spec);
11377
+ const view = Codec.View.decode(d);
11378
+ this.viewCache.set(key, view);
11379
+ return view;
11380
+ }
11381
+ availabilityAssignmentView() {
11382
+ return this.retrieveView(serialize_serialize.availabilityAssignment, "availabilityAssignmentView");
11383
+ }
11384
+ designatedValidatorDataView() {
11385
+ return this.retrieveView(serialize_serialize.designatedValidators, "designatedValidatorsView");
11386
+ }
11387
+ currentValidatorDataView() {
11388
+ return this.retrieveView(serialize_serialize.currentValidators, "currentValidatorsView");
11389
+ }
11390
+ previousValidatorDataView() {
11391
+ return this.retrieveView(serialize_serialize.previousValidators, "previousValidatorsView");
11392
+ }
11393
+ authPoolsView() {
11394
+ return this.retrieveView(serialize_serialize.authPools, "authPoolsView");
11395
+ }
11396
+ authQueuesView() {
11397
+ return this.retrieveView(serialize_serialize.authQueues, "authQueuesView");
11398
+ }
11399
+ recentBlocksView() {
11400
+ return this.retrieveView(serialize_serialize.recentBlocks, "recentBlocksView");
11401
+ }
11402
+ statisticsView() {
11403
+ return this.retrieveView(serialize_serialize.statistics, "statisticsView");
11404
+ }
11405
+ accumulationQueueView() {
11406
+ return this.retrieveView(serialize_serialize.accumulationQueue, "accumulationQueueView");
11407
+ }
11408
+ recentlyAccumulatedView() {
11409
+ return this.retrieveView(serialize_serialize.recentlyAccumulated, "recentlyAccumulatedView");
11410
+ }
11411
+ safroleDataView() {
11412
+ return this.retrieveView(serialize_serialize.safrole, "safroleDataView");
11413
+ }
11414
+ getServiceInfoView(id) {
11415
+ const serviceData = serialize_serialize.serviceData(id);
11416
+ const bytes = this.backend.get(serviceData.key);
11417
+ if (bytes === null) {
11418
+ return null;
11419
+ }
11420
+ if (!this.recentlyUsedServices.includes(id)) {
11421
+ this.recentlyUsedServices.push(id);
11422
+ }
11423
+ return decoder_Decoder.decodeObject(serviceData.Codec.View, bytes, this.spec);
11424
+ }
11425
+ }
11426
+
11268
11427
  ;// CONCATENATED MODULE: ./packages/jam/state-merkleization/serialized-state.ts
11269
11428
 
11270
11429
 
@@ -11273,6 +11432,8 @@ const dumpCodec = Descriptor.new("Dump", { bytes: 64, isExact: false }, (e, v) =
11273
11432
 
11274
11433
 
11275
11434
 
11435
+
11436
+
11276
11437
  /**
11277
11438
  * State object which reads it's entries from some backend.
11278
11439
  *
@@ -11285,7 +11446,7 @@ class serialized_state_SerializedState {
11285
11446
  spec;
11286
11447
  blake2b;
11287
11448
  backend;
11288
- _recentServiceIds;
11449
+ recentlyUsedServices;
11289
11450
  /** Create a state-like object from collection of serialized entries. */
11290
11451
  static fromStateEntries(spec, blake2b, state, recentServices = []) {
11291
11452
  return new serialized_state_SerializedState(spec, blake2b, state, recentServices);
@@ -11294,106 +11455,120 @@ class serialized_state_SerializedState {
11294
11455
  static new(spec, blake2b, db, recentServices = []) {
11295
11456
  return new serialized_state_SerializedState(spec, blake2b, db, recentServices);
11296
11457
  }
11458
+ dataCache = hash_dictionary_HashDictionary.new();
11459
+ viewCache = hash_dictionary_HashDictionary.new();
11297
11460
  constructor(spec, blake2b, backend,
11298
11461
  /** Best-effort list of recently active services. */
11299
- _recentServiceIds) {
11462
+ recentlyUsedServices) {
11300
11463
  this.spec = spec;
11301
11464
  this.blake2b = blake2b;
11302
11465
  this.backend = backend;
11303
- this._recentServiceIds = _recentServiceIds;
11466
+ this.recentlyUsedServices = recentlyUsedServices;
11304
11467
  }
11305
11468
  /** Comparing the serialized states, just means comparing their backends. */
11306
11469
  [TEST_COMPARE_USING]() {
11307
11470
  return this.backend;
11308
11471
  }
11472
+ /** Return a non-decoding version of the state. */
11473
+ view() {
11474
+ return new SerializedStateView(this.spec, this.backend, this.recentlyUsedServices, this.viewCache);
11475
+ }
11309
11476
  // TODO [ToDr] Temporary method to update the state,
11310
11477
  // without changing references.
11311
11478
  updateBackend(newBackend) {
11312
11479
  this.backend = newBackend;
11480
+ this.dataCache = hash_dictionary_HashDictionary.new();
11481
+ this.viewCache = hash_dictionary_HashDictionary.new();
11313
11482
  }
11314
11483
  recentServiceIds() {
11315
- return this._recentServiceIds;
11484
+ return this.recentlyUsedServices;
11316
11485
  }
11317
11486
  getService(id) {
11318
- const serviceData = this.retrieveOptional(serialize.serviceData(id));
11487
+ const serviceData = this.retrieveOptional(serialize_serialize.serviceData(id));
11319
11488
  if (serviceData === undefined) {
11320
11489
  return null;
11321
11490
  }
11322
- if (!this._recentServiceIds.includes(id)) {
11323
- this._recentServiceIds.push(id);
11491
+ if (!this.recentlyUsedServices.includes(id)) {
11492
+ this.recentlyUsedServices.push(id);
11324
11493
  }
11325
11494
  return new SerializedService(this.blake2b, id, serviceData, (key) => this.retrieveOptional(key));
11326
11495
  }
11327
- retrieve({ key, Codec }, description) {
11328
- const bytes = this.backend.get(key);
11329
- if (bytes === null) {
11330
- throw new Error(`Required state entry for ${description} is missing!. Accessing key: ${key}`);
11496
+ retrieve(k, description) {
11497
+ const data = this.retrieveOptional(k);
11498
+ if (data === undefined) {
11499
+ throw new Error(`Required state entry for ${description} is missing!. Accessing key: ${k.key}`);
11331
11500
  }
11332
- return decoder_Decoder.decodeObject(Codec, bytes, this.spec);
11501
+ return data;
11333
11502
  }
11334
11503
  retrieveOptional({ key, Codec }) {
11504
+ const cached = this.dataCache.get(key);
11505
+ if (cached !== undefined) {
11506
+ return cached;
11507
+ }
11335
11508
  const bytes = this.backend.get(key);
11336
11509
  if (bytes === null) {
11337
11510
  return undefined;
11338
11511
  }
11339
- return decoder_Decoder.decodeObject(Codec, bytes, this.spec);
11512
+ const data = decoder_Decoder.decodeObject(Codec, bytes, this.spec);
11513
+ this.dataCache.set(key, data);
11514
+ return data;
11340
11515
  }
11341
11516
  get availabilityAssignment() {
11342
- return this.retrieve(serialize.availabilityAssignment, "availabilityAssignment");
11517
+ return this.retrieve(serialize_serialize.availabilityAssignment, "availabilityAssignment");
11343
11518
  }
11344
11519
  get designatedValidatorData() {
11345
- return this.retrieve(serialize.designatedValidators, "designatedValidatorData");
11520
+ return this.retrieve(serialize_serialize.designatedValidators, "designatedValidatorData");
11346
11521
  }
11347
11522
  get nextValidatorData() {
11348
- return this.retrieve(serialize.safrole, "safroleData.nextValidatorData").nextValidatorData;
11523
+ return this.retrieve(serialize_serialize.safrole, "safroleData.nextValidatorData").nextValidatorData;
11349
11524
  }
11350
11525
  get currentValidatorData() {
11351
- return this.retrieve(serialize.currentValidators, "currentValidators");
11526
+ return this.retrieve(serialize_serialize.currentValidators, "currentValidators");
11352
11527
  }
11353
11528
  get previousValidatorData() {
11354
- return this.retrieve(serialize.previousValidators, "previousValidators");
11529
+ return this.retrieve(serialize_serialize.previousValidators, "previousValidators");
11355
11530
  }
11356
11531
  get disputesRecords() {
11357
- return this.retrieve(serialize.disputesRecords, "disputesRecords");
11532
+ return this.retrieve(serialize_serialize.disputesRecords, "disputesRecords");
11358
11533
  }
11359
11534
  get timeslot() {
11360
- return this.retrieve(serialize.timeslot, "timeslot");
11535
+ return this.retrieve(serialize_serialize.timeslot, "timeslot");
11361
11536
  }
11362
11537
  get entropy() {
11363
- return this.retrieve(serialize.entropy, "entropy");
11538
+ return this.retrieve(serialize_serialize.entropy, "entropy");
11364
11539
  }
11365
11540
  get authPools() {
11366
- return this.retrieve(serialize.authPools, "authPools");
11541
+ return this.retrieve(serialize_serialize.authPools, "authPools");
11367
11542
  }
11368
11543
  get authQueues() {
11369
- return this.retrieve(serialize.authQueues, "authQueues");
11544
+ return this.retrieve(serialize_serialize.authQueues, "authQueues");
11370
11545
  }
11371
11546
  get recentBlocks() {
11372
- return this.retrieve(serialize.recentBlocks, "recentBlocks");
11547
+ return this.retrieve(serialize_serialize.recentBlocks, "recentBlocks");
11373
11548
  }
11374
11549
  get statistics() {
11375
- return this.retrieve(serialize.statistics, "statistics");
11550
+ return this.retrieve(serialize_serialize.statistics, "statistics");
11376
11551
  }
11377
11552
  get accumulationQueue() {
11378
- return this.retrieve(serialize.accumulationQueue, "accumulationQueue");
11553
+ return this.retrieve(serialize_serialize.accumulationQueue, "accumulationQueue");
11379
11554
  }
11380
11555
  get recentlyAccumulated() {
11381
- return this.retrieve(serialize.recentlyAccumulated, "recentlyAccumulated");
11556
+ return this.retrieve(serialize_serialize.recentlyAccumulated, "recentlyAccumulated");
11382
11557
  }
11383
11558
  get ticketsAccumulator() {
11384
- return this.retrieve(serialize.safrole, "safroleData.ticketsAccumulator").ticketsAccumulator;
11559
+ return this.retrieve(serialize_serialize.safrole, "safroleData.ticketsAccumulator").ticketsAccumulator;
11385
11560
  }
11386
11561
  get sealingKeySeries() {
11387
- return this.retrieve(serialize.safrole, "safrole.sealingKeySeries").sealingKeySeries;
11562
+ return this.retrieve(serialize_serialize.safrole, "safrole.sealingKeySeries").sealingKeySeries;
11388
11563
  }
11389
11564
  get epochRoot() {
11390
- return this.retrieve(serialize.safrole, "safrole.epochRoot").epochRoot;
11565
+ return this.retrieve(serialize_serialize.safrole, "safrole.epochRoot").epochRoot;
11391
11566
  }
11392
11567
  get privilegedServices() {
11393
- return this.retrieve(serialize.privilegedServices, "privilegedServices");
11568
+ return this.retrieve(serialize_serialize.privilegedServices, "privilegedServices");
11394
11569
  }
11395
11570
  get accumulationOutputLog() {
11396
- return this.retrieve(serialize.accumulationOutputLog, "accumulationOutputLog");
11571
+ return this.retrieve(serialize_serialize.accumulationOutputLog, "accumulationOutputLog");
11397
11572
  }
11398
11573
  }
11399
11574
  /** Service data representation on a serialized state. */
@@ -11422,9 +11597,9 @@ class SerializedService {
11422
11597
  serviceIdAndKey.set(numbers_u32AsLeBytes(this.serviceId));
11423
11598
  serviceIdAndKey.set(rawKey.raw, SERVICE_ID_BYTES);
11424
11599
  const key = opaque_asOpaqueType(bytes_BytesBlob.blobFrom(this.blake2b.hashBytes(serviceIdAndKey).raw));
11425
- return this.retrieveOptional(serialize.serviceStorage(this.blake2b, this.serviceId, key)) ?? null;
11600
+ return this.retrieveOptional(serialize_serialize.serviceStorage(this.blake2b, this.serviceId, key)) ?? null;
11426
11601
  }
11427
- return this.retrieveOptional(serialize.serviceStorage(this.blake2b, this.serviceId, rawKey)) ?? null;
11602
+ return this.retrieveOptional(serialize_serialize.serviceStorage(this.blake2b, this.serviceId, rawKey)) ?? null;
11428
11603
  }
11429
11604
  /**
11430
11605
  * Check if preimage is present in the DB.
@@ -11433,15 +11608,15 @@ class SerializedService {
11433
11608
  */
11434
11609
  hasPreimage(hash) {
11435
11610
  // TODO [ToDr] consider optimizing to avoid fetching the whole data.
11436
- return this.retrieveOptional(serialize.servicePreimages(this.blake2b, this.serviceId, hash)) !== undefined;
11611
+ return this.retrieveOptional(serialize_serialize.servicePreimages(this.blake2b, this.serviceId, hash)) !== undefined;
11437
11612
  }
11438
11613
  /** Retrieve preimage from the DB. */
11439
11614
  getPreimage(hash) {
11440
- return this.retrieveOptional(serialize.servicePreimages(this.blake2b, this.serviceId, hash)) ?? null;
11615
+ return this.retrieveOptional(serialize_serialize.servicePreimages(this.blake2b, this.serviceId, hash)) ?? null;
11441
11616
  }
11442
11617
  /** Retrieve preimage lookup history. */
11443
11618
  getLookupHistory(hash, len) {
11444
- const rawSlots = this.retrieveOptional(serialize.serviceLookupHistory(this.blake2b, this.serviceId, hash, len));
11619
+ const rawSlots = this.retrieveOptional(serialize_serialize.serviceLookupHistory(this.blake2b, this.serviceId, hash, len));
11445
11620
  if (rawSlots === undefined) {
11446
11621
  return null;
11447
11622
  }
@@ -12130,7 +12305,7 @@ function* serializeStateUpdate(spec, blake2b, update) {
12130
12305
  function* serializeRemovedServices(servicesRemoved) {
12131
12306
  for (const serviceId of servicesRemoved ?? []) {
12132
12307
  // TODO [ToDr] what about all data associated with a service?
12133
- const codec = serialize.serviceData(serviceId);
12308
+ const codec = serialize_serialize.serviceData(serviceId);
12134
12309
  yield [StateEntryUpdateAction.Remove, codec.key, EMPTY_BLOB];
12135
12310
  }
12136
12311
  }
@@ -12139,13 +12314,13 @@ function* serializeStorage(storage, blake2b) {
12139
12314
  switch (action.kind) {
12140
12315
  case UpdateStorageKind.Set: {
12141
12316
  const key = action.storage.key;
12142
- const codec = serialize.serviceStorage(blake2b, serviceId, key);
12317
+ const codec = serialize_serialize.serviceStorage(blake2b, serviceId, key);
12143
12318
  yield [StateEntryUpdateAction.Insert, codec.key, action.storage.value];
12144
12319
  break;
12145
12320
  }
12146
12321
  case UpdateStorageKind.Remove: {
12147
12322
  const key = action.key;
12148
- const codec = serialize.serviceStorage(blake2b, serviceId, key);
12323
+ const codec = serialize_serialize.serviceStorage(blake2b, serviceId, key);
12149
12324
  yield [StateEntryUpdateAction.Remove, codec.key, EMPTY_BLOB];
12150
12325
  break;
12151
12326
  }
@@ -12159,10 +12334,10 @@ function* serializePreimages(preimages, encode, blake2b) {
12159
12334
  switch (action.kind) {
12160
12335
  case UpdatePreimageKind.Provide: {
12161
12336
  const { hash, blob } = action.preimage;
12162
- const codec = serialize.servicePreimages(blake2b, serviceId, hash);
12337
+ const codec = serialize_serialize.servicePreimages(blake2b, serviceId, hash);
12163
12338
  yield [StateEntryUpdateAction.Insert, codec.key, blob];
12164
12339
  if (action.slot !== null) {
12165
- const codec2 = serialize.serviceLookupHistory(blake2b, serviceId, hash, numbers_tryAsU32(blob.length));
12340
+ const codec2 = serialize_serialize.serviceLookupHistory(blake2b, serviceId, hash, numbers_tryAsU32(blob.length));
12166
12341
  yield [
12167
12342
  StateEntryUpdateAction.Insert,
12168
12343
  codec2.key,
@@ -12173,15 +12348,15 @@ function* serializePreimages(preimages, encode, blake2b) {
12173
12348
  }
12174
12349
  case UpdatePreimageKind.UpdateOrAdd: {
12175
12350
  const { hash, length, slots } = action.item;
12176
- const codec = serialize.serviceLookupHistory(blake2b, serviceId, hash, length);
12351
+ const codec = serialize_serialize.serviceLookupHistory(blake2b, serviceId, hash, length);
12177
12352
  yield [StateEntryUpdateAction.Insert, codec.key, encode(codec.Codec, slots)];
12178
12353
  break;
12179
12354
  }
12180
12355
  case UpdatePreimageKind.Remove: {
12181
12356
  const { hash, length } = action;
12182
- const codec = serialize.servicePreimages(blake2b, serviceId, hash);
12357
+ const codec = serialize_serialize.servicePreimages(blake2b, serviceId, hash);
12183
12358
  yield [StateEntryUpdateAction.Remove, codec.key, EMPTY_BLOB];
12184
- const codec2 = serialize.serviceLookupHistory(blake2b, serviceId, hash, length);
12359
+ const codec2 = serialize_serialize.serviceLookupHistory(blake2b, serviceId, hash, length);
12185
12360
  yield [StateEntryUpdateAction.Remove, codec2.key, EMPTY_BLOB];
12186
12361
  break;
12187
12362
  }
@@ -12193,12 +12368,12 @@ function* serializePreimages(preimages, encode, blake2b) {
12193
12368
  function* serializeServiceUpdates(servicesUpdates, encode, blake2b) {
12194
12369
  for (const { action, serviceId } of servicesUpdates ?? []) {
12195
12370
  // new service being created or updated
12196
- const codec = serialize.serviceData(serviceId);
12371
+ const codec = serialize_serialize.serviceData(serviceId);
12197
12372
  yield [StateEntryUpdateAction.Insert, codec.key, encode(codec.Codec, action.account)];
12198
12373
  // additional lookup history update
12199
12374
  if (action.kind === UpdateServiceKind.Create && action.lookupHistory !== null) {
12200
12375
  const { lookupHistory } = action;
12201
- const codec2 = serialize.serviceLookupHistory(blake2b, serviceId, lookupHistory.hash, lookupHistory.length);
12376
+ const codec2 = serialize_serialize.serviceLookupHistory(blake2b, serviceId, lookupHistory.hash, lookupHistory.length);
12202
12377
  yield [StateEntryUpdateAction.Insert, codec2.key, encode(codec2.Codec, lookupHistory.slots)];
12203
12378
  }
12204
12379
  }
@@ -12208,53 +12383,53 @@ function* serializeBasicKeys(spec, update) {
12208
12383
  return [StateEntryUpdateAction.Insert, codec.key, encoder_Encoder.encodeObject(codec.Codec, val, spec)];
12209
12384
  }
12210
12385
  if (update.authPools !== undefined) {
12211
- yield doSerialize(update.authPools, serialize.authPools); // C(1)
12386
+ yield doSerialize(update.authPools, serialize_serialize.authPools); // C(1)
12212
12387
  }
12213
12388
  if (update.authQueues !== undefined) {
12214
- yield doSerialize(update.authQueues, serialize.authQueues); // C(2)
12389
+ yield doSerialize(update.authQueues, serialize_serialize.authQueues); // C(2)
12215
12390
  }
12216
12391
  if (update.recentBlocks !== undefined) {
12217
- yield doSerialize(update.recentBlocks, serialize.recentBlocks); // C(3)
12392
+ yield doSerialize(update.recentBlocks, serialize_serialize.recentBlocks); // C(3)
12218
12393
  }
12219
12394
  const safroleData = getSafroleData(update.nextValidatorData, update.epochRoot, update.sealingKeySeries, update.ticketsAccumulator);
12220
12395
  if (safroleData !== undefined) {
12221
- yield doSerialize(safroleData, serialize.safrole); // C(4)
12396
+ yield doSerialize(safroleData, serialize_serialize.safrole); // C(4)
12222
12397
  }
12223
12398
  if (update.disputesRecords !== undefined) {
12224
- yield doSerialize(update.disputesRecords, serialize.disputesRecords); // C(5)
12399
+ yield doSerialize(update.disputesRecords, serialize_serialize.disputesRecords); // C(5)
12225
12400
  }
12226
12401
  if (update.entropy !== undefined) {
12227
- yield doSerialize(update.entropy, serialize.entropy); // C(6)
12402
+ yield doSerialize(update.entropy, serialize_serialize.entropy); // C(6)
12228
12403
  }
12229
12404
  if (update.designatedValidatorData !== undefined) {
12230
- yield doSerialize(update.designatedValidatorData, serialize.designatedValidators); // C(7)
12405
+ yield doSerialize(update.designatedValidatorData, serialize_serialize.designatedValidators); // C(7)
12231
12406
  }
12232
12407
  if (update.currentValidatorData !== undefined) {
12233
- yield doSerialize(update.currentValidatorData, serialize.currentValidators); // C(8)
12408
+ yield doSerialize(update.currentValidatorData, serialize_serialize.currentValidators); // C(8)
12234
12409
  }
12235
12410
  if (update.previousValidatorData !== undefined) {
12236
- yield doSerialize(update.previousValidatorData, serialize.previousValidators); // C(9)
12411
+ yield doSerialize(update.previousValidatorData, serialize_serialize.previousValidators); // C(9)
12237
12412
  }
12238
12413
  if (update.availabilityAssignment !== undefined) {
12239
- yield doSerialize(update.availabilityAssignment, serialize.availabilityAssignment); // C(10)
12414
+ yield doSerialize(update.availabilityAssignment, serialize_serialize.availabilityAssignment); // C(10)
12240
12415
  }
12241
12416
  if (update.timeslot !== undefined) {
12242
- yield doSerialize(update.timeslot, serialize.timeslot); // C(11)
12417
+ yield doSerialize(update.timeslot, serialize_serialize.timeslot); // C(11)
12243
12418
  }
12244
12419
  if (update.privilegedServices !== undefined) {
12245
- yield doSerialize(update.privilegedServices, serialize.privilegedServices); // C(12)
12420
+ yield doSerialize(update.privilegedServices, serialize_serialize.privilegedServices); // C(12)
12246
12421
  }
12247
12422
  if (update.statistics !== undefined) {
12248
- yield doSerialize(update.statistics, serialize.statistics); // C(13)
12423
+ yield doSerialize(update.statistics, serialize_serialize.statistics); // C(13)
12249
12424
  }
12250
12425
  if (update.accumulationQueue !== undefined) {
12251
- yield doSerialize(update.accumulationQueue, serialize.accumulationQueue); // C(14)
12426
+ yield doSerialize(update.accumulationQueue, serialize_serialize.accumulationQueue); // C(14)
12252
12427
  }
12253
12428
  if (update.recentlyAccumulated !== undefined) {
12254
- yield doSerialize(update.recentlyAccumulated, serialize.recentlyAccumulated); // C(15)
12429
+ yield doSerialize(update.recentlyAccumulated, serialize_serialize.recentlyAccumulated); // C(15)
12255
12430
  }
12256
12431
  if (update.accumulationOutputLog !== undefined) {
12257
- yield doSerialize(update.accumulationOutputLog, serialize.accumulationOutputLog); // C(16)
12432
+ yield doSerialize(update.accumulationOutputLog, serialize_serialize.accumulationOutputLog); // C(16)
12258
12433
  }
12259
12434
  }
12260
12435
  function getSafroleData(nextValidatorData, epochRoot, sealingKeySeries, ticketsAccumulator) {
@@ -12367,41 +12542,41 @@ function convertInMemoryStateToDictionary(spec, blake2b, state) {
12367
12542
  function doSerialize(codec) {
12368
12543
  serialized.set(codec.key, encoder_Encoder.encodeObject(codec.Codec, codec.extract(state), spec));
12369
12544
  }
12370
- doSerialize(serialize.authPools); // C(1)
12371
- doSerialize(serialize.authQueues); // C(2)
12372
- doSerialize(serialize.recentBlocks); // C(3)
12373
- doSerialize(serialize.safrole); // C(4)
12374
- doSerialize(serialize.disputesRecords); // C(5)
12375
- doSerialize(serialize.entropy); // C(6)
12376
- doSerialize(serialize.designatedValidators); // C(7)
12377
- doSerialize(serialize.currentValidators); // C(8)
12378
- doSerialize(serialize.previousValidators); // C(9)
12379
- doSerialize(serialize.availabilityAssignment); // C(10)
12380
- doSerialize(serialize.timeslot); // C(11)
12381
- doSerialize(serialize.privilegedServices); // C(12)
12382
- doSerialize(serialize.statistics); // C(13)
12383
- doSerialize(serialize.accumulationQueue); // C(14)
12384
- doSerialize(serialize.recentlyAccumulated); // C(15)
12385
- doSerialize(serialize.accumulationOutputLog); // C(16)
12545
+ doSerialize(serialize_serialize.authPools); // C(1)
12546
+ doSerialize(serialize_serialize.authQueues); // C(2)
12547
+ doSerialize(serialize_serialize.recentBlocks); // C(3)
12548
+ doSerialize(serialize_serialize.safrole); // C(4)
12549
+ doSerialize(serialize_serialize.disputesRecords); // C(5)
12550
+ doSerialize(serialize_serialize.entropy); // C(6)
12551
+ doSerialize(serialize_serialize.designatedValidators); // C(7)
12552
+ doSerialize(serialize_serialize.currentValidators); // C(8)
12553
+ doSerialize(serialize_serialize.previousValidators); // C(9)
12554
+ doSerialize(serialize_serialize.availabilityAssignment); // C(10)
12555
+ doSerialize(serialize_serialize.timeslot); // C(11)
12556
+ doSerialize(serialize_serialize.privilegedServices); // C(12)
12557
+ doSerialize(serialize_serialize.statistics); // C(13)
12558
+ doSerialize(serialize_serialize.accumulationQueue); // C(14)
12559
+ doSerialize(serialize_serialize.recentlyAccumulated); // C(15)
12560
+ doSerialize(serialize_serialize.accumulationOutputLog); // C(16)
12386
12561
  // services
12387
12562
  for (const [serviceId, service] of state.services.entries()) {
12388
12563
  // data
12389
- const { key, Codec } = serialize.serviceData(serviceId);
12564
+ const { key, Codec } = serialize_serialize.serviceData(serviceId);
12390
12565
  serialized.set(key, encoder_Encoder.encodeObject(Codec, service.getInfo()));
12391
12566
  // preimages
12392
12567
  for (const preimage of service.data.preimages.values()) {
12393
- const { key, Codec } = serialize.servicePreimages(blake2b, serviceId, preimage.hash);
12568
+ const { key, Codec } = serialize_serialize.servicePreimages(blake2b, serviceId, preimage.hash);
12394
12569
  serialized.set(key, encoder_Encoder.encodeObject(Codec, preimage.blob));
12395
12570
  }
12396
12571
  // storage
12397
12572
  for (const storage of service.data.storage.values()) {
12398
- const { key, Codec } = serialize.serviceStorage(blake2b, serviceId, storage.key);
12573
+ const { key, Codec } = serialize_serialize.serviceStorage(blake2b, serviceId, storage.key);
12399
12574
  serialized.set(key, encoder_Encoder.encodeObject(Codec, storage.value));
12400
12575
  }
12401
12576
  // lookup history
12402
12577
  for (const lookupHistoryList of service.data.lookupHistory.values()) {
12403
12578
  for (const lookupHistory of lookupHistoryList) {
12404
- const { key, Codec } = serialize.serviceLookupHistory(blake2b, serviceId, lookupHistory.hash, lookupHistory.length);
12579
+ const { key, Codec } = serialize_serialize.serviceLookupHistory(blake2b, serviceId, lookupHistory.hash, lookupHistory.length);
12405
12580
  serialized.set(key, encoder_Encoder.encodeObject(Codec, lookupHistory.slots.slice()));
12406
12581
  }
12407
12582
  }
@@ -12451,6 +12626,7 @@ function loadState(spec, blake2b, entries) {
12451
12626
 
12452
12627
 
12453
12628
 
12629
+
12454
12630
  ;// CONCATENATED MODULE: ./packages/jam/database/leaf-db.ts
12455
12631
 
12456
12632
 
@@ -12609,7 +12785,7 @@ const codecMap = (value, extractKey, { typicalLength = TYPICAL_DICTIONARY_LENGTH
12609
12785
  const lookupHistoryItemCodec = descriptors_codec.object({
12610
12786
  hash: descriptors_codec.bytes(hash_HASH_SIZE).asOpaque(),
12611
12787
  length: descriptors_codec.u32,
12612
- slots: readonlyArray(descriptors_codec.sequenceVarLen(descriptors_codec.u32.asOpaque())).convert(seeThrough, tryAsLookupHistorySlots),
12788
+ slots: descriptors_readonlyArray(descriptors_codec.sequenceVarLen(descriptors_codec.u32.asOpaque())).convert(seeThrough, tryAsLookupHistorySlots),
12613
12789
  }, "LookupHistoryItem", ({ hash, length, slots }) => new LookupHistoryItem(hash, length, slots));
12614
12790
  const lookupHistoryEntryCodec = descriptors_codec.object({
12615
12791
  key: descriptors_codec.bytes(hash_HASH_SIZE).asOpaque(),
@@ -12652,7 +12828,11 @@ class ServiceWithCodec extends InMemoryService {
12652
12828
  return new ServiceWithCodec(serviceId, data);
12653
12829
  }
12654
12830
  }
12655
- const in_memory_state_codec_inMemoryStateCodec = descriptors_codec.Class(InMemoryState, {
12831
+ const in_memory_state_codec_inMemoryStateCodec = (spec) => codec.Class(class State extends InMemoryState {
12832
+ static create(data) {
12833
+ return InMemoryState.new(spec, data);
12834
+ }
12835
+ }, {
12656
12836
  // alpha
12657
12837
  authPools: serialize.authPools.Codec,
12658
12838
  // phi
@@ -12662,11 +12842,11 @@ const in_memory_state_codec_inMemoryStateCodec = descriptors_codec.Class(InMemor
12662
12842
  // gamma_k
12663
12843
  nextValidatorData: codecPerValidator(ValidatorData.Codec),
12664
12844
  // gamma_z
12665
- epochRoot: descriptors_codec.bytes(BANDERSNATCH_RING_ROOT_BYTES).asOpaque(),
12845
+ epochRoot: codec.bytes(BANDERSNATCH_RING_ROOT_BYTES).asOpaque(),
12666
12846
  // gamma_s
12667
12847
  sealingKeySeries: SafroleSealingKeysData.Codec,
12668
12848
  // gamma_a
12669
- ticketsAccumulator: readonlyArray(descriptors_codec.sequenceVarLen(Ticket.Codec)).convert((x) => x, sized_array_asKnownSize),
12849
+ ticketsAccumulator: readonlyArray(codec.sequenceVarLen(Ticket.Codec)).convert((x) => x, asKnownSize),
12670
12850
  // psi
12671
12851
  disputesRecords: serialize.disputesRecords.Codec,
12672
12852
  // eta
@@ -12692,7 +12872,7 @@ const in_memory_state_codec_inMemoryStateCodec = descriptors_codec.Class(InMemor
12692
12872
  // theta
12693
12873
  accumulationOutputLog: serialize.accumulationOutputLog.Codec,
12694
12874
  // delta
12695
- services: descriptors_codec.dictionary(descriptors_codec.u32.asOpaque(), ServiceWithCodec.Codec, {
12875
+ services: codec.dictionary(codec.u32.asOpaque(), ServiceWithCodec.Codec, {
12696
12876
  sortKeys: (a, b) => a - b,
12697
12877
  }),
12698
12878
  });
@@ -12739,7 +12919,7 @@ class InMemoryStates {
12739
12919
  }
12740
12920
  /** Insert a full state into the database. */
12741
12921
  async insertState(headerHash, state) {
12742
- const encoded = Encoder.encodeObject(inMemoryStateCodec, state, this.spec);
12922
+ const encoded = Encoder.encodeObject(inMemoryStateCodec(this.spec), state, this.spec);
12743
12923
  this.db.set(headerHash, encoded);
12744
12924
  return Result.ok(OK);
12745
12925
  }
@@ -12748,7 +12928,7 @@ class InMemoryStates {
12748
12928
  if (encodedState === undefined) {
12749
12929
  return null;
12750
12930
  }
12751
- return Decoder.decodeObject(inMemoryStateCodec, encodedState, this.spec);
12931
+ return Decoder.decodeObject(inMemoryStateCodec(this.spec), encodedState, this.spec);
12752
12932
  }
12753
12933
  }
12754
12934
 
@@ -13856,21 +14036,21 @@ class TransitionHasher {
13856
14036
  */
13857
14037
  extrinsic(extrinsicView) {
13858
14038
  // https://graypaper.fluffylabs.dev/#/cc517d7/0cfb000cfb00?v=0.6.5
13859
- const guarantees = extrinsicView.guarantees
14039
+ const guaranteesCount = numbers_tryAsU32(extrinsicView.guarantees.view().length);
14040
+ const countEncoded = encoder_Encoder.encodeObject(descriptors_codec.varU32, guaranteesCount);
14041
+ const guaranteesBlobs = extrinsicView.guarantees
13860
14042
  .view()
13861
14043
  .map((g) => g.view())
13862
- .map((guarantee) => {
14044
+ .reduce((aggregated, guarantee) => {
13863
14045
  const reportHash = this.blake2b.hashBytes(guarantee.report.encoded()).asOpaque();
13864
- return bytes_BytesBlob.blobFromParts([
13865
- reportHash.raw,
13866
- guarantee.slot.encoded().raw,
13867
- guarantee.credentials.encoded().raw,
13868
- ]);
13869
- });
13870
- const guaranteeBlob = encoder_Encoder.encodeObject(descriptors_codec.sequenceVarLen(dumpCodec), guarantees, this.context);
14046
+ aggregated.push(reportHash.raw);
14047
+ aggregated.push(guarantee.slot.encoded().raw);
14048
+ aggregated.push(guarantee.credentials.encoded().raw);
14049
+ return aggregated;
14050
+ }, [countEncoded.raw]);
13871
14051
  const et = this.blake2b.hashBytes(extrinsicView.tickets.encoded()).asOpaque();
13872
14052
  const ep = this.blake2b.hashBytes(extrinsicView.preimages.encoded()).asOpaque();
13873
- const eg = this.blake2b.hashBytes(guaranteeBlob).asOpaque();
14053
+ const eg = this.blake2b.hashBlobs(guaranteesBlobs).asOpaque();
13874
14054
  const ea = this.blake2b.hashBytes(extrinsicView.assurances.encoded()).asOpaque();
13875
14055
  const ed = this.blake2b.hashBytes(extrinsicView.disputes.encoded()).asOpaque();
13876
14056
  const encoded = bytes_BytesBlob.blobFromParts([et.raw, ep.raw, eg.raw, ea.raw, ed.raw]);
@@ -14529,7 +14709,7 @@ async function getRingCommitmentNoCache(bandersnatch, keys) {
14529
14709
  if (commitmentResult[RESULT_INDEX] === ResultValues.Error) {
14530
14710
  return result_Result.error(null);
14531
14711
  }
14532
- return result_Result.ok(bytes_Bytes.fromBlob(commitmentResult.subarray(1), BANDERSNATCH_RING_ROOT_BYTES).asOpaque());
14712
+ return result_Result.ok(bytes_Bytes.fromBlob(commitmentResult.subarray(1), bandersnatch_BANDERSNATCH_RING_ROOT_BYTES).asOpaque());
14533
14713
  }
14534
14714
  // One byte for result discriminator (`ResultValues`) and the rest is entropy hash.
14535
14715
  const TICKET_RESULT_LENGTH = 1 + hash_HASH_SIZE;
@@ -14683,7 +14863,7 @@ class Safrole {
14683
14863
  * https://graypaper.fluffylabs.dev/#/5f542d7/0ea2000ea200
14684
14864
  */
14685
14865
  if (isOffender) {
14686
- return ValidatorData.create({
14866
+ return validator_data_ValidatorData.create({
14687
14867
  bandersnatch: bytes_Bytes.zero(BANDERSNATCH_KEY_BYTES).asOpaque(),
14688
14868
  ed25519: bytes_Bytes.zero(ED25519_KEY_BYTES).asOpaque(),
14689
14869
  bls: bytes_Bytes.zero(BLS_KEY_BYTES).asOpaque(),
@@ -14761,13 +14941,13 @@ class Safrole {
14761
14941
  if (this.isNextEpoch(timeslot) &&
14762
14942
  m >= this.chainSpec.contestLength &&
14763
14943
  this.state.ticketsAccumulator.length === this.chainSpec.epochLength) {
14764
- return SafroleSealingKeysData.tickets(this.outsideInSequencer(this.state.ticketsAccumulator).tickets);
14944
+ return safrole_data_SafroleSealingKeysData.tickets(this.outsideInSequencer(this.state.ticketsAccumulator).tickets);
14765
14945
  }
14766
14946
  if (this.isSameEpoch(timeslot)) {
14767
14947
  return this.state.sealingKeySeries;
14768
14948
  }
14769
14949
  // TODO [MaSi]: the result of fallback sequencer should be cached
14770
- return SafroleSealingKeysData.keys(this.fallbackKeySequencer(newEntropy, newValidators));
14950
+ return safrole_data_SafroleSealingKeysData.keys(this.fallbackKeySequencer(newEntropy, newValidators));
14771
14951
  }
14772
14952
  /**
14773
14953
  * Returns epoch markers if the epoch is changed and null otherwise
@@ -15017,47 +15197,46 @@ class SafroleSeal {
15017
15197
  }
15018
15198
  async verifySeal(headerView, state) {
15019
15199
  // we use transitioned keys already
15020
- const validators = state.currentValidatorData;
15021
15200
  const validatorIndex = headerView.bandersnatchBlockAuthorIndex.materialize();
15022
- const authorKey = validators[validatorIndex];
15023
- if (authorKey === undefined) {
15201
+ const authorKeys = state.currentValidatorData.at(validatorIndex);
15202
+ if (authorKeys === undefined) {
15024
15203
  return result_Result.error(SafroleSealError.InvalidValidatorIndex);
15025
15204
  }
15026
15205
  const timeSlot = headerView.timeSlotIndex.materialize();
15027
15206
  const sealingKeys = state.sealingKeySeries;
15028
15207
  const entropy = state.currentEntropy;
15029
15208
  if (sealingKeys.kind === SafroleSealingKeysKind.Tickets) {
15030
- return await this.verifySealWithTicket(sealingKeys.tickets, timeSlot, entropy, validators, validatorIndex, headerView);
15209
+ return await this.verifySealWithTicket(sealingKeys.tickets, timeSlot, entropy, authorKeys, headerView);
15031
15210
  }
15032
- return await this.verifySealWithKeys(sealingKeys.keys, authorKey, timeSlot, entropy, validators, validatorIndex, headerView);
15211
+ return await this.verifySealWithKeys(sealingKeys.keys, timeSlot, entropy, authorKeys, headerView);
15033
15212
  }
15034
15213
  /** Regular (non-fallback) mode of Safrole. */
15035
- async verifySealWithTicket(tickets, timeSlot, entropy, validators, validatorIndex, headerView) {
15214
+ async verifySealWithTicket(tickets, timeSlot, entropy, validatorData, headerView) {
15036
15215
  const index = timeSlot % tickets.length;
15037
- const { id, attempt } = tickets[index];
15038
- const payload = bytes_BytesBlob.blobFromParts(JAM_TICKET_SEAL, entropy.raw, new Uint8Array([attempt]));
15216
+ const ticket = tickets.at(index);
15217
+ const payload = bytes_BytesBlob.blobFromParts(JAM_TICKET_SEAL, entropy.raw, new Uint8Array([ticket?.attempt ?? 0]));
15039
15218
  // verify seal correctness
15040
- const authorKey = validators.at(validatorIndex)?.bandersnatch;
15219
+ const authorKey = validatorData.bandersnatch;
15041
15220
  const result = await bandersnatch_vrf.verifySeal(await this.bandersnatch, authorKey ?? BANDERSNATCH_ZERO_KEY, headerView.seal.materialize(), payload, encodeUnsealedHeader(headerView));
15042
15221
  if (result.isError) {
15043
15222
  return result_Result.error(SafroleSealError.IncorrectSeal);
15044
15223
  }
15045
- if (!id.isEqualTo(result.ok)) {
15224
+ if (ticket === undefined || !ticket.id.isEqualTo(result.ok)) {
15046
15225
  return result_Result.error(SafroleSealError.InvalidTicket);
15047
15226
  }
15048
15227
  return result_Result.ok(result.ok);
15049
15228
  }
15050
15229
  /** Fallback mode of Safrole. */
15051
- async verifySealWithKeys(keys, authorKey, timeSlot, entropy, validators, validatorIndex, headerView) {
15230
+ async verifySealWithKeys(keys, timeSlot, entropy, authorKey, headerView) {
15052
15231
  const index = timeSlot % keys.length;
15053
- const sealingKey = keys[index];
15054
- if (!sealingKey.isEqualTo(authorKey.bandersnatch)) {
15232
+ const sealingKey = keys.at(index);
15233
+ const authorBandersnatchKey = authorKey.bandersnatch;
15234
+ if (sealingKey === undefined || !sealingKey.isEqualTo(authorBandersnatchKey)) {
15055
15235
  return result_Result.error(SafroleSealError.InvalidValidator, `Invalid Validator. Expected: ${sealingKey}, got: ${authorKey.bandersnatch}`);
15056
15236
  }
15057
15237
  // verify seal correctness
15058
15238
  const payload = bytes_BytesBlob.blobFromParts(JAM_FALLBACK_SEAL, entropy.raw);
15059
- const blockAuthorKey = validators.at(validatorIndex)?.bandersnatch;
15060
- const result = await bandersnatch_vrf.verifySeal(await this.bandersnatch, blockAuthorKey ?? BANDERSNATCH_ZERO_KEY, headerView.seal.materialize(), payload, encodeUnsealedHeader(headerView));
15239
+ const result = await bandersnatch_vrf.verifySeal(await this.bandersnatch, authorBandersnatchKey, headerView.seal.materialize(), payload, encodeUnsealedHeader(headerView));
15061
15240
  if (result.isError) {
15062
15241
  return result_Result.error(SafroleSealError.IncorrectSeal);
15063
15242
  }
@@ -20973,9 +21152,6 @@ class HostCallMemory {
20973
21152
  }
20974
21153
  return this.memory.loadInto(result, tryAsMemoryIndex(Number(startAddress)));
20975
21154
  }
20976
- getMemory() {
20977
- return this.memory;
20978
- }
20979
21155
  }
20980
21156
 
20981
21157
  ;// CONCATENATED MODULE: ./packages/core/pvm-host-calls/host-call-registers.ts
@@ -21254,7 +21430,7 @@ class Assign {
21254
21430
  // NOTE: Here we know the core index is valid
21255
21431
  const coreIndex = tryAsCoreIndex(Number(maybeCoreIndex));
21256
21432
  const decoder = decoder_Decoder.fromBlob(res);
21257
- const authQueue = decoder.sequenceFixLen(descriptors_codec.bytes(hash_HASH_SIZE), AUTHORIZATION_QUEUE_SIZE);
21433
+ const authQueue = decoder.sequenceFixLen(descriptors_codec.bytes(hash_HASH_SIZE).asOpaque(), AUTHORIZATION_QUEUE_SIZE);
21258
21434
  const fixedSizeAuthQueue = FixedSizeArray.new(authQueue, AUTHORIZATION_QUEUE_SIZE);
21259
21435
  const result = this.partialState.updateAuthorizationQueue(coreIndex, fixedSizeAuthQueue, assigners);
21260
21436
  if (result.isOk) {
@@ -21450,7 +21626,7 @@ class Checkpoint {
21450
21626
 
21451
21627
 
21452
21628
  const designate_IN_OUT_REG = 7;
21453
- const VALIDATOR_DATA_BYTES = tryAsExactBytes(ValidatorData.Codec.sizeHint);
21629
+ const VALIDATOR_DATA_BYTES = tryAsExactBytes(validator_data_ValidatorData.Codec.sizeHint);
21454
21630
  /**
21455
21631
  * Designate a new set of validator keys.
21456
21632
  *
@@ -21479,7 +21655,7 @@ class Designate {
21479
21655
  return PvmExecution.Panic;
21480
21656
  }
21481
21657
  const decoder = decoder_Decoder.fromBlob(res);
21482
- const validatorsData = decoder.sequenceFixLen(ValidatorData.Codec, this.chainSpec.validatorsCount);
21658
+ const validatorsData = decoder.sequenceFixLen(validator_data_ValidatorData.Codec, this.chainSpec.validatorsCount);
21483
21659
  const result = this.partialState.updateValidatorsData(tryAsPerValidator(validatorsData, this.chainSpec));
21484
21660
  if (result.isError) {
21485
21661
  logger_logger.trace `DESIGNATE([${validatorsData[0]}, ${validatorsData[1]}, ...]) <- HUH`;
@@ -23000,7 +23176,7 @@ class Accumulate {
23000
23176
  }
23001
23177
  const result = await this.pvmAccumulateInvocation(slot, serviceId, transfers, operands, gasCost, entropy, updatedState);
23002
23178
  if (result.isError) {
23003
- // https://graypaper.fluffylabs.dev/#/7e6ff6a/2fb6012fb601?v=0.6.7
23179
+ // https://graypaper.fluffylabs.dev/#/ab2cdbd/2fc9032fc903?v=0.7.2
23004
23180
  accumulate_logger.log `Accumulation failed for ${serviceId}.`;
23005
23181
  // even though accumulation failed, we still need to make sure that
23006
23182
  // incoming transfers updated the balance, hence we pass state update here
@@ -23094,10 +23270,12 @@ class Accumulate {
23094
23270
  const { consumedGas, stateUpdate } = await this.accumulateSingleService(serviceId, accumulateData.getTransfers(serviceId), operands, accumulateData.getGasCost(serviceId), slot, entropy, currentState);
23095
23271
  gasCost = tryAsServiceGas(gasCost + consumedGas);
23096
23272
  // https://graypaper.fluffylabs.dev/#/ab2cdbd/193b05193b05?v=0.7.2
23097
- // do not update statistics, if the service only had incoming transfers
23098
- if (operands.length > 0) {
23099
- const serviceStatistics = statistics.get(serviceId) ?? { count: numbers_tryAsU32(0), gasUsed: tryAsServiceGas(0) };
23100
- serviceStatistics.count = numbers_tryAsU32(serviceStatistics.count + accumulateData.getReportsLength(serviceId));
23273
+ const serviceStatistics = statistics.get(serviceId) ?? { count: numbers_tryAsU32(0), gasUsed: tryAsServiceGas(0) };
23274
+ const count = accumulateData.getReportsLength(serviceId);
23275
+ // [0.7.1]: do not update statistics, if the service only had incoming transfers
23276
+ if ((Compatibility.isLessThan(GpVersion.V0_7_2) && count > 0) ||
23277
+ (Compatibility.isGreaterOrEqual(GpVersion.V0_7_2) && (count > 0 || consumedGas > 0n))) {
23278
+ serviceStatistics.count = numbers_tryAsU32(serviceStatistics.count + count);
23101
23279
  serviceStatistics.gasUsed = tryAsServiceGas(serviceStatistics.gasUsed + consumedGas);
23102
23280
  statistics.set(serviceId, serviceStatistics);
23103
23281
  }
@@ -23135,9 +23313,10 @@ class Accumulate {
23135
23313
  const recentlyAccumulated = tryAsPerEpochBlock(newRecentlyAccumulated, this.chainSpec);
23136
23314
  const accumulationQueue = this.state.accumulationQueue.slice();
23137
23315
  accumulationQueue[phaseIndex] = pruneQueue(toAccumulateLater, accumulatedSet);
23316
+ const timeslot = this.state.timeslot;
23138
23317
  for (let i = 1; i < epochLength; i++) {
23139
23318
  const queueIndex = (phaseIndex + epochLength - i) % epochLength;
23140
- if (i < slot - this.state.timeslot) {
23319
+ if (i < slot - timeslot) {
23141
23320
  accumulationQueue[queueIndex] = [];
23142
23321
  }
23143
23322
  else {
@@ -23349,7 +23528,6 @@ class DeferredTransfers {
23349
23528
 
23350
23529
 
23351
23530
 
23352
-
23353
23531
  /**
23354
23532
  * Maintain a list of available authorizations per core.
23355
23533
  *
@@ -23378,11 +23556,12 @@ class Authorization {
23378
23556
  */
23379
23557
  transition(input) {
23380
23558
  const authPoolsUpdate = this.state.authPools.slice();
23559
+ const authQueues = this.state.authQueues;
23381
23560
  // we transition authorizations for each core.
23382
23561
  for (let coreIndex = tryAsCoreIndex(0); coreIndex < this.chainSpec.coresCount; coreIndex++) {
23383
23562
  let pool = authPoolsUpdate[coreIndex].slice();
23384
23563
  // the queue is only read (we should most likely use `ArrayView` here).
23385
- const queue = this.state.authQueues[coreIndex];
23564
+ const queue = authQueues[coreIndex];
23386
23565
  // if there were any used hashes - remove them
23387
23566
  const usedHashes = input.used.get(coreIndex);
23388
23567
  if (usedHashes !== undefined) {
@@ -23556,14 +23735,18 @@ class RecentHistory {
23556
23735
  * https://graypaper.fluffylabs.dev/#/1c979cb/0f55020f5502?v=0.7.1
23557
23736
  */
23558
23737
  partialTransition(input) {
23559
- const recentBlocks = this.state.recentBlocks.blocks.slice();
23738
+ const stateBlocks = this.state.recentBlocks;
23739
+ const recentBlocks = stateBlocks.blocks.slice();
23560
23740
  const lastState = recentBlocks.length > 0 ? recentBlocks[recentBlocks.length - 1] : null;
23561
23741
  // update the posterior root of previous state.
23562
23742
  if (lastState !== null) {
23563
23743
  lastState.postStateRoot = input.priorStateRoot;
23564
23744
  }
23565
23745
  return {
23566
- recentBlocks: this.state.recentBlocks.updateBlocks(recentBlocks), // β_H†
23746
+ recentBlocks: RecentBlocks.create({
23747
+ blocks: sized_array_asKnownSize(recentBlocks),
23748
+ accumulationLog: stateBlocks.accumulationLog,
23749
+ }), // β_H†
23567
23750
  };
23568
23751
  }
23569
23752
  /**
@@ -23575,8 +23758,8 @@ class RecentHistory {
23575
23758
  transition(input) {
23576
23759
  const recentBlocks = input.partial.recentBlocks.blocks.slice();
23577
23760
  // `β′_B`
23578
- const mmr = this.state.recentBlocks.asCurrent().accumulationLog !== null
23579
- ? MerkleMountainRange.fromPeaks(this.hasher, this.state.recentBlocks.asCurrent().accumulationLog)
23761
+ const mmr = this.state.recentBlocks.accumulationLog !== null
23762
+ ? MerkleMountainRange.fromPeaks(this.hasher, this.state.recentBlocks.accumulationLog)
23580
23763
  : MerkleMountainRange.empty(this.hasher);
23581
23764
  // append the accumulation root
23582
23765
  mmr.append(input.accumulateRoot);
@@ -23594,7 +23777,7 @@ class RecentHistory {
23594
23777
  }
23595
23778
  // write back to the state.
23596
23779
  return {
23597
- recentBlocks: RecentBlocksHistory.create(RecentBlocks.create({
23780
+ recentBlocks: RecentBlocks.create(RecentBlocks.create({
23598
23781
  blocks: sized_array_asKnownSize(recentBlocks),
23599
23782
  accumulationLog: peaks,
23600
23783
  })),
@@ -23806,7 +23989,6 @@ function verifyReportsBasic(input) {
23806
23989
 
23807
23990
 
23808
23991
 
23809
-
23810
23992
  const verify_contextual_logger = Logger.new(import.meta.filename, "stf:reports");
23811
23993
  /** https://graypaper.fluffylabs.dev/#/7e6ff6a/15eb0115eb01?v=0.6.7 */
23812
23994
  function verifyContextualValidity(input, state, headerChain, maxLookupAnchorAge) {
@@ -23919,7 +24101,7 @@ function verifyRefineContexts(minLookupSlot, contexts, recentBlocksPartialUpdate
23919
24101
  return result_Result.error(ReportsError.BadStateRoot, `Anchor state root mismatch. Got: ${context.stateRoot}, expected: ${recentBlock.postStateRoot}.`);
23920
24102
  }
23921
24103
  // check beefy root
23922
- const beefyRoot = RecentBlocksHistory.accumulationResult(recentBlock);
24104
+ const beefyRoot = recentBlock.accumulationResult;
23923
24105
  if (!beefyRoot.isEqualTo(context.beefyRoot)) {
23924
24106
  return result_Result.error(ReportsError.BadBeefyMmrRoot, `Invalid BEEFY super peak hash. Got: ${context.beefyRoot}, expected: ${beefyRoot}. Anchor: ${recentBlock.headerHash}`);
23925
24107
  }
@@ -24161,8 +24343,9 @@ function verifyPostSignatureChecks(input, availabilityAssignment, authPools, ser
24161
24343
  * https://graypaper.fluffylabs.dev/#/5f542d7/15eb0015ed00
24162
24344
  */
24163
24345
  const authorizerHash = report.authorizerHash;
24164
- const authorizerPool = authPools[coreIndex];
24165
- if (authorizerPool.find((hash) => hash.isEqualTo(authorizerHash)) === undefined) {
24346
+ const authorizerPool = authPools.get(coreIndex);
24347
+ const pool = authorizerPool?.materialize() ?? [];
24348
+ if (pool.find((hash) => hash.isEqualTo(authorizerHash)) === undefined) {
24166
24349
  return result_Result.error(ReportsError.CoreUnauthorized, `Authorizer hash not found in the pool of core ${coreIndex}: ${authorizerHash}`);
24167
24350
  }
24168
24351
  /**
@@ -24292,7 +24475,8 @@ class Reports {
24292
24475
  return verifyCredentials(input.guarantees, workReportHashes, input.slot, (headerTimeSlot, guaranteeTimeSlot) => this.getGuarantorAssignment(headerTimeSlot, guaranteeTimeSlot, input.newEntropy));
24293
24476
  }
24294
24477
  verifyPostSignatureChecks(input, assurancesAvailAssignment) {
24295
- return verifyPostSignatureChecks(input, assurancesAvailAssignment, this.state.authPools, (id) => this.state.getService(id));
24478
+ const authPoolsView = this.state.view().authPoolsView();
24479
+ return verifyPostSignatureChecks(input, assurancesAvailAssignment, authPoolsView, (id) => this.state.getService(id));
24296
24480
  }
24297
24481
  verifyContextualValidity(input) {
24298
24482
  return verifyContextualValidity(input, this.state, this.headerChain, this.chainSpec.maxLookupAnchorAge);