@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.
package/index.js CHANGED
@@ -26373,6 +26373,9 @@ class ObjectView {
26373
26373
  toString() {
26374
26374
  return `View<${this.materializedConstructor.name}>(cache: ${this.cache.size})`;
26375
26375
  }
26376
+ [TEST_COMPARE_USING]() {
26377
+ return this.materialize();
26378
+ }
26376
26379
  }
26377
26380
  /**
26378
26381
  * A lazy-evaluated decoder of a sequence.
@@ -26505,7 +26508,7 @@ const TYPICAL_DICTIONARY_LENGTH = 32;
26505
26508
  * It's not true in a general case, but should be good enough for us.
26506
26509
  *
26507
26510
  */
26508
- function readonlyArray(desc) {
26511
+ function descriptors_readonlyArray(desc) {
26509
26512
  return desc.convert((x) => {
26510
26513
  debug_check `
26511
26514
  ${Array.isArray(x)}
@@ -26667,7 +26670,15 @@ var descriptors_codec;
26667
26670
  /** Custom encoding / decoding logic. */
26668
26671
  codec.custom = ({ name, sizeHint = { bytes: 0, isExact: false }, }, encode, decode, skip) => Descriptor.new(name, sizeHint, encode, decode, skip);
26669
26672
  /** Choose a descriptor depending on the encoding/decoding context. */
26670
- 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);
26673
+ codec.select = ({ name, sizeHint, }, chooser) => {
26674
+ const Self = chooser(null);
26675
+ 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)
26676
+ ? codec.select({
26677
+ name: Self.View.name,
26678
+ sizeHint: Self.View.sizeHint,
26679
+ }, (ctx) => chooser(ctx).View)
26680
+ : Self.View);
26681
+ };
26671
26682
  /**
26672
26683
  * A descriptor for a more complex POJO.
26673
26684
  *
@@ -27489,7 +27500,7 @@ const BANDERSNATCH_KEY_BYTES = 32;
27489
27500
  /** Bandersnatch VRF signature size */
27490
27501
  const BANDERSNATCH_VRF_SIGNATURE_BYTES = 96;
27491
27502
  /** Bandersnatch ring commitment size */
27492
- const BANDERSNATCH_RING_ROOT_BYTES = 144;
27503
+ const bandersnatch_BANDERSNATCH_RING_ROOT_BYTES = 144;
27493
27504
  /** Bandersnatch proof size */
27494
27505
  const BANDERSNATCH_PROOF_BYTES = 784;
27495
27506
  /** BLS public key size. */
@@ -29070,9 +29081,9 @@ function codecWithContext(chooser) {
29070
29081
  /** Codec for a known-size array with length validation. */
29071
29082
  const codecKnownSizeArray = (val, options, _id) => {
29072
29083
  if ("fixedLength" in options) {
29073
- return readonlyArray(descriptors_codec.sequenceFixLen(val, options.fixedLength)).convert(seeThrough, sized_array_asKnownSize);
29084
+ return descriptors_readonlyArray(descriptors_codec.sequenceFixLen(val, options.fixedLength)).convert(seeThrough, sized_array_asKnownSize);
29074
29085
  }
29075
- return readonlyArray(descriptors_codec.sequenceVarLen(val, options)).convert(seeThrough, sized_array_asKnownSize);
29086
+ return descriptors_readonlyArray(descriptors_codec.sequenceVarLen(val, options)).convert(seeThrough, sized_array_asKnownSize);
29076
29087
  };
29077
29088
  /** Codec for a fixed-size array with length validation. */
29078
29089
  const codecFixedSizeArray = (val, len) => {
@@ -29446,16 +29457,16 @@ class SignedTicket extends WithDebug {
29446
29457
  }
29447
29458
  }
29448
29459
  /** Anonymous? entry into the ticket contest. */
29449
- class Ticket extends WithDebug {
29460
+ class tickets_Ticket extends WithDebug {
29450
29461
  id;
29451
29462
  attempt;
29452
- static Codec = descriptors_codec.Class(Ticket, {
29463
+ static Codec = descriptors_codec.Class(tickets_Ticket, {
29453
29464
  id: descriptors_codec.bytes(hash_HASH_SIZE),
29454
29465
  // TODO [ToDr] we should verify that attempt is either 0|1|2.
29455
29466
  attempt: descriptors_codec.u8.asOpaque(),
29456
29467
  });
29457
29468
  static create({ id, attempt }) {
29458
- return new Ticket(id, attempt);
29469
+ return new tickets_Ticket(id, attempt);
29459
29470
  }
29460
29471
  constructor(
29461
29472
  /**
@@ -29567,7 +29578,7 @@ function tryAsPerValidator(array, spec) {
29567
29578
  `;
29568
29579
  return sized_array_asKnownSize(array);
29569
29580
  }
29570
- const codecPerValidator = (val) => codecWithContext((context) => {
29581
+ const common_codecPerValidator = (val) => codecWithContext((context) => {
29571
29582
  return codecKnownSizeArray(val, {
29572
29583
  fixedLength: context.validatorsCount,
29573
29584
  });
@@ -29694,7 +29705,7 @@ class Verdict extends WithDebug {
29694
29705
  workReportHash: descriptors_codec.bytes(hash_HASH_SIZE).asOpaque(),
29695
29706
  votesEpoch: descriptors_codec.u32.asOpaque(),
29696
29707
  votes: codecWithContext((context) => {
29697
- return readonlyArray(descriptors_codec.sequenceFixLen(Judgement.Codec, context.validatorsSuperMajority)).convert(seeThrough, sized_array_asKnownSize);
29708
+ return descriptors_readonlyArray(descriptors_codec.sequenceFixLen(Judgement.Codec, context.validatorsSuperMajority)).convert(seeThrough, sized_array_asKnownSize);
29698
29709
  }),
29699
29710
  });
29700
29711
  static create({ workReportHash, votesEpoch, votes }) {
@@ -30386,7 +30397,7 @@ const WorkReportCodec = descriptors_codec.Class(WorkReportNoCodec, {
30386
30397
  authorizerHash: descriptors_codec.bytes(hash_HASH_SIZE).asOpaque(),
30387
30398
  authorizationGasUsed: descriptors_codec.varU64.asOpaque(),
30388
30399
  authorizationOutput: descriptors_codec.blob,
30389
- segmentRootLookup: readonlyArray(descriptors_codec.sequenceVarLen(WorkPackageInfo.Codec)),
30400
+ segmentRootLookup: descriptors_readonlyArray(descriptors_codec.sequenceVarLen(WorkPackageInfo.Codec)),
30390
30401
  results: descriptors_codec.sequenceVarLen(WorkResult.Codec).convert((x) => x, (items) => FixedSizeArray.new(items, tryAsWorkItemsCount(items.length))),
30391
30402
  });
30392
30403
  const WorkReportCodecPre070 = descriptors_codec.Class(WorkReportNoCodec, {
@@ -30400,7 +30411,7 @@ const WorkReportCodecPre070 = descriptors_codec.Class(WorkReportNoCodec, {
30400
30411
  }),
30401
30412
  authorizerHash: descriptors_codec.bytes(hash_HASH_SIZE).asOpaque(),
30402
30413
  authorizationOutput: descriptors_codec.blob,
30403
- segmentRootLookup: readonlyArray(descriptors_codec.sequenceVarLen(WorkPackageInfo.Codec)),
30414
+ segmentRootLookup: descriptors_readonlyArray(descriptors_codec.sequenceVarLen(WorkPackageInfo.Codec)),
30404
30415
  results: descriptors_codec.sequenceVarLen(WorkResult.Codec).convert((x) => x, (items) => FixedSizeArray.new(items, tryAsWorkItemsCount(items.length))),
30405
30416
  authorizationGasUsed: descriptors_codec.varU64.asOpaque(),
30406
30417
  });
@@ -30521,7 +30532,7 @@ class ValidatorKeys extends WithDebug {
30521
30532
  class TicketsMarker extends WithDebug {
30522
30533
  tickets;
30523
30534
  static Codec = descriptors_codec.Class(TicketsMarker, {
30524
- tickets: codecPerEpochBlock(Ticket.Codec),
30535
+ tickets: codecPerEpochBlock(tickets_Ticket.Codec),
30525
30536
  });
30526
30537
  static create({ tickets }) {
30527
30538
  return new TicketsMarker(tickets);
@@ -30545,7 +30556,7 @@ class EpochMarker extends WithDebug {
30545
30556
  static Codec = descriptors_codec.Class(EpochMarker, {
30546
30557
  entropy: descriptors_codec.bytes(hash_HASH_SIZE).asOpaque(),
30547
30558
  ticketsEntropy: descriptors_codec.bytes(hash_HASH_SIZE).asOpaque(),
30548
- validators: codecPerValidator(ValidatorKeys.Codec),
30559
+ validators: common_codecPerValidator(ValidatorKeys.Codec),
30549
30560
  });
30550
30561
  static create({ entropy, ticketsEntropy, validators }) {
30551
30562
  return new EpochMarker(entropy, ticketsEntropy, validators);
@@ -30817,6 +30828,19 @@ function emptyBlock(slot = tryAsTimeSlot(0)) {
30817
30828
  });
30818
30829
  }
30819
30830
 
30831
+ ;// CONCATENATED MODULE: ./packages/jam/block/utils.ts
30832
+
30833
+ /**
30834
+ * Take an input data and re-encode that data as view.
30835
+ *
30836
+ * NOTE: this function should NEVER be used in any production code,
30837
+ * it's only a test helper.
30838
+ */
30839
+ function reencodeAsView(codec, object, chainSpec) {
30840
+ const encoded = encoder_Encoder.encodeObject(codec, object, chainSpec);
30841
+ return decoder_Decoder.decodeObject(codec.View, encoded, chainSpec);
30842
+ }
30843
+
30820
30844
  ;// CONCATENATED MODULE: ./packages/jam/block/index.ts
30821
30845
 
30822
30846
 
@@ -30835,6 +30859,7 @@ function emptyBlock(slot = tryAsTimeSlot(0)) {
30835
30859
 
30836
30860
 
30837
30861
 
30862
+
30838
30863
  ;// CONCATENATED MODULE: ./packages/jam/block-json/disputes-extrinsic.ts
30839
30864
 
30840
30865
 
@@ -31074,7 +31099,7 @@ const epochMark = json.object({
31074
31099
  const ticket = json.object({
31075
31100
  id: fromJson.bytes32(),
31076
31101
  attempt: fromJson.ticketAttempt,
31077
- }, (x) => Ticket.create({ id: x.id, attempt: x.attempt }));
31102
+ }, (x) => tickets_Ticket.create({ id: x.id, attempt: x.attempt }));
31078
31103
  const headerFromJson = json.object({
31079
31104
  parent: fromJson.bytes32(),
31080
31105
  parent_state_root: fromJson.bytes32(),
@@ -31999,10 +32024,129 @@ function accumulationOutputComparator(a, b) {
31999
32024
  return Ordering.Equal;
32000
32025
  }
32001
32026
 
32027
+ ;// CONCATENATED MODULE: ./packages/jam/block/gp-constants.ts
32028
+
32029
+
32030
+ /**
32031
+ * This file lists all of the constants defined in the GrayPaper appendix.
32032
+ *
32033
+ * NOTE: Avoid using the constants directly, prefer "named" constants defined
32034
+ * in a semantical proximity to where they are used.
32035
+ *
32036
+ * NOTE: This file will most likely be removed in the future. The constants
32037
+ * here are only temporarily for convenience. When we figure out better names
32038
+ * and places for these this file will be eradicated.
32039
+ *
32040
+ * https://graypaper.fluffylabs.dev/#/ab2cdbd/442300442300?v=0.7.2
32041
+ */
32042
+ /** `G_I`: The gas allocated to invoke a work-package’s Is-Authorized logic. */
32043
+ const G_I = 50_000_000;
32044
+ /** `I`: Maximum number of work items in a package. */
32045
+ const gp_constants_I = (/* unused pure expression or super */ null && (MAX_NUMBER_OF_WORK_ITEMS));
32046
+ /** `O`: Maximum number of items in the authorizations pool. */
32047
+ const O = 8;
32048
+ /** `Q`: The number of items in the authorizations queue. */
32049
+ const Q = 80;
32050
+ /** `S`: The maximum number of entries in the accumulation queue. */
32051
+ const S = 1024;
32052
+ /** `T`: The maximum number of extrinsics in a work-package. */
32053
+ const T = 128;
32054
+ /** `W_A`: The maximum size of is-authorized code in octets. */
32055
+ const W_A = 64_000;
32056
+ /** `W_B`: The maximum size of the concatenated variable-size blobs, extrinsics and imported segments of a work-package, in octets */
32057
+ const W_B = Compatibility.isGreaterOrEqual(GpVersion.V0_7_2) ? 13_791_360 : 13_794_305;
32058
+ /** `W_C`: The maximum size of service code in octets. */
32059
+ const W_C = 4_000_000;
32060
+ /** `W_M`: The maximum number of imports in a work-package. */
32061
+ const W_M = 3_072;
32062
+ /** `W_R`: The maximum total size of all output blobs in a work-report, in octets. */
32063
+ const W_R = 49_152;
32064
+ /** `W_T`: The size of a transfer memo in octets. */
32065
+ const W_T = 128;
32066
+ /** `W_M`: The maximum number of exports in a work-package. */
32067
+ const W_X = 3_072;
32068
+ // TODO [ToDr] Not sure where these should live yet :(
32069
+ /**
32070
+ * `S`: The minimum public service index.
32071
+ * Services of indices below these may only be created by the Registrar.
32072
+ *
32073
+ * https://graypaper.fluffylabs.dev/#/ab2cdbd/447a00447a00?v=0.7.2
32074
+ */
32075
+ const MIN_PUBLIC_SERVICE_INDEX = 2 ** 16;
32076
+ /**
32077
+ * `J`: The maximum sum of dependency items in a work-report.
32078
+ *
32079
+ * https://graypaper.fluffylabs.dev/#/5f542d7/416a00416a00?v=0.6.2
32080
+ */
32081
+ const MAX_REPORT_DEPENDENCIES = 8;
32082
+
32083
+ ;// CONCATENATED MODULE: ./packages/jam/state/accumulation-queue.ts
32084
+
32085
+
32086
+
32087
+
32088
+
32089
+
32090
+
32091
+ /**
32092
+ * Ready (i.e. available and/or audited) but not-yet-accumulated work-reports.
32093
+ *
32094
+ * https://graypaper.fluffylabs.dev/#/5f542d7/165300165400
32095
+ */
32096
+ class NotYetAccumulatedReport extends WithDebug {
32097
+ report;
32098
+ dependencies;
32099
+ static Codec = descriptors_codec.Class(NotYetAccumulatedReport, {
32100
+ report: WorkReport.Codec,
32101
+ dependencies: codecKnownSizeArray(descriptors_codec.bytes(hash_HASH_SIZE).asOpaque(), {
32102
+ typicalLength: MAX_REPORT_DEPENDENCIES / 2,
32103
+ maxLength: MAX_REPORT_DEPENDENCIES,
32104
+ minLength: 0,
32105
+ }),
32106
+ });
32107
+ static create({ report, dependencies }) {
32108
+ return new NotYetAccumulatedReport(report, dependencies);
32109
+ }
32110
+ constructor(
32111
+ /**
32112
+ * Each of these were made available at most one epoch ago
32113
+ * but have or had unfulfilled dependencies.
32114
+ */
32115
+ report,
32116
+ /**
32117
+ * Alongside the work-report itself, we retain its un-accumulated
32118
+ * dependencies, a set of work-package hashes.
32119
+ *
32120
+ * https://graypaper.fluffylabs.dev/#/5f542d7/165800165800
32121
+ */
32122
+ dependencies) {
32123
+ super();
32124
+ this.report = report;
32125
+ this.dependencies = dependencies;
32126
+ }
32127
+ }
32128
+ const accumulationQueueCodec = codecPerEpochBlock(descriptors_readonlyArray(descriptors_codec.sequenceVarLen(NotYetAccumulatedReport.Codec)));
32129
+
32130
+ ;// CONCATENATED MODULE: ./packages/jam/state/common.ts
32131
+
32132
+
32133
+ /** Check if given array has correct length before casting to the opaque type. */
32134
+ function tryAsPerCore(array, spec) {
32135
+ debug_check `
32136
+ ${array.length === spec.coresCount}
32137
+ Invalid per-core array length. Expected ${spec.coresCount}, got: ${array.length}
32138
+ `;
32139
+ return opaque_asOpaqueType(array);
32140
+ }
32141
+ const codecPerCore = (val) => codecWithContext((context) => {
32142
+ return codecKnownSizeArray(val, { fixedLength: context.coresCount });
32143
+ });
32144
+
32002
32145
  ;// CONCATENATED MODULE: ./packages/jam/state/assurances.ts
32003
32146
 
32004
32147
 
32005
32148
 
32149
+
32006
32150
  /**
32007
32151
  * Assignment of particular work report to a core.
32008
32152
  *
@@ -32031,27 +32175,30 @@ class AvailabilityAssignment extends WithDebug {
32031
32175
  this.timeout = timeout;
32032
32176
  }
32033
32177
  }
32178
+ const availabilityAssignmentsCodec = codecPerCore(descriptors_codec.optional(AvailabilityAssignment.Codec));
32034
32179
 
32035
- ;// CONCATENATED MODULE: ./packages/jam/state/common.ts
32180
+ ;// CONCATENATED MODULE: ./packages/jam/state/auth.ts
32036
32181
 
32037
32182
 
32038
- /** Check if given array has correct length before casting to the opaque type. */
32039
- function tryAsPerCore(array, spec) {
32040
- debug_check `
32041
- ${array.length === spec.coresCount}
32042
- Invalid per-core array length. Expected ${spec.coresCount}, got: ${array.length}
32043
- `;
32044
- return opaque_asOpaqueType(array);
32045
- }
32046
- const codecPerCore = (val) => codecWithContext((context) => {
32047
- return codecKnownSizeArray(val, { fixedLength: context.coresCount });
32048
- });
32183
+
32184
+
32185
+
32186
+ /** `O`: Maximal authorization pool size. */
32187
+ const MAX_AUTH_POOL_SIZE = O;
32188
+ /** `Q`: Size of the authorization queue. */
32189
+ const AUTHORIZATION_QUEUE_SIZE = Q;
32190
+ const authPoolsCodec = codecPerCore(codecKnownSizeArray(descriptors_codec.bytes(hash_HASH_SIZE).asOpaque(), {
32191
+ minLength: 0,
32192
+ maxLength: MAX_AUTH_POOL_SIZE,
32193
+ typicalLength: MAX_AUTH_POOL_SIZE,
32194
+ }));
32195
+ const authQueuesCodec = codecPerCore(codecFixedSizeArray(descriptors_codec.bytes(hash_HASH_SIZE).asOpaque(), AUTHORIZATION_QUEUE_SIZE));
32049
32196
 
32050
32197
  ;// CONCATENATED MODULE: ./packages/jam/state/disputes.ts
32051
32198
 
32052
32199
 
32053
32200
 
32054
- const sortedSetCodec = () => readonlyArray(descriptors_codec.sequenceVarLen(descriptors_codec.bytes(hash_HASH_SIZE))).convert((input) => input.array, (output) => {
32201
+ const sortedSetCodec = () => descriptors_readonlyArray(descriptors_codec.sequenceVarLen(descriptors_codec.bytes(hash_HASH_SIZE))).convert((input) => input.array, (output) => {
32055
32202
  const typed = output.map((x) => x.asOpaque());
32056
32203
  return SortedSet.fromSortedArray(hashComparator, typed);
32057
32204
  });
@@ -32113,65 +32260,6 @@ function hashComparator(a, b) {
32113
32260
  return a.compare(b);
32114
32261
  }
32115
32262
 
32116
- ;// CONCATENATED MODULE: ./packages/jam/block/gp-constants.ts
32117
-
32118
- /**
32119
- * This file lists all of the constants defined in the GrayPaper appendix.
32120
- *
32121
- * NOTE: Avoid using the constants directly, prefer "named" constants defined
32122
- * in a semantical proximity to where they are used.
32123
- *
32124
- * NOTE: This file will most likely be removed in the future. The constants
32125
- * here are only temporarily for convenience. When we figure out better names
32126
- * and places for these this file will be eradicated.
32127
- *
32128
- * https://graypaper.fluffylabs.dev/#/579bd12/413000413000
32129
- */
32130
- /** `G_I`: The gas allocated to invoke a work-package’s Is-Authorized logic. */
32131
- const G_I = 50_000_000;
32132
- /** `I`: Maximum number of work items in a package. */
32133
- const gp_constants_I = (/* unused pure expression or super */ null && (MAX_NUMBER_OF_WORK_ITEMS));
32134
- /** `O`: Maximum number of items in the authorizations pool. */
32135
- const O = 8;
32136
- /** `Q`: The number of items in the authorizations queue. */
32137
- const Q = 80;
32138
- /** `S`: The maximum number of entries in the accumulation queue. */
32139
- const S = 1024;
32140
- /** `T`: The maximum number of extrinsics in a work-package. */
32141
- const T = 128;
32142
- /** `W_A`: The maximum size of is-authorized code in octets. */
32143
- const W_A = 64_000;
32144
- /** `W_B`: The maximum size of an encoded work-package with extrinsic data and imports. */
32145
- const W_B = 13_794_305;
32146
- /** `W_C`: The maximum size of service code in octets. */
32147
- const W_C = 4_000_000;
32148
- /** `W_M`: The maximum number of imports in a work-package. */
32149
- const W_M = 3_072;
32150
- /** `W_R`: The maximum total size of all output blobs in a work-report, in octets. */
32151
- const W_R = 49_152;
32152
- /** `W_T`: The size of a transfer memo in octets. */
32153
- const W_T = 128;
32154
- /** `W_M`: The maximum number of exports in a work-package. */
32155
- const W_X = 3_072;
32156
- // TODO [ToDr] Not sure where these should live yet :(
32157
- /**
32158
- * `S`: The minimum public service index.
32159
- * Services of indices below these may only be created by the Registrar.
32160
- *
32161
- * https://graypaper.fluffylabs.dev/#/ab2cdbd/447a00447a00?v=0.7.2
32162
- */
32163
- const MIN_PUBLIC_SERVICE_INDEX = 2 ** 16;
32164
- /**
32165
- * `J`: The maximum sum of dependency items in a work-report.
32166
- *
32167
- * https://graypaper.fluffylabs.dev/#/5f542d7/416a00416a00?v=0.6.2
32168
- */
32169
- const MAX_REPORT_DEPENDENCIES = 8;
32170
- /** `Q`: Size of the authorization queue. */
32171
- const AUTHORIZATION_QUEUE_SIZE = Q;
32172
- /** `O`: Maximal authorization pool size. */
32173
- const MAX_AUTH_POOL_SIZE = O;
32174
-
32175
32263
  ;// CONCATENATED MODULE: ./packages/core/pvm-interpreter/ops/math-consts.ts
32176
32264
  const MAX_VALUE = 4294967295;
32177
32265
  const math_consts_MAX_VALUE_U64 = (/* unused pure expression or super */ null && (2n ** 63n));
@@ -32179,7 +32267,7 @@ const MIN_VALUE = -(2 ** 31);
32179
32267
  const MAX_SHIFT_U32 = 32;
32180
32268
  const MAX_SHIFT_U64 = 64n;
32181
32269
 
32182
- ;// CONCATENATED MODULE: ./packages/jam/state/service.ts
32270
+ ;// CONCATENATED MODULE: ./packages/jam/state/recent-blocks.ts
32183
32271
 
32184
32272
 
32185
32273
 
@@ -32187,28 +32275,272 @@ const MAX_SHIFT_U64 = 64n;
32187
32275
 
32188
32276
 
32189
32277
  /**
32190
- * `B_S`: The basic minimum balance which all services require.
32191
- *
32192
- * https://graypaper.fluffylabs.dev/#/7e6ff6a/445800445800?v=0.6.7
32193
- */
32194
- const BASE_SERVICE_BALANCE = 100n;
32195
- /**
32196
- * `B_I`: The additional minimum balance required per item of elective service state.
32278
+ * `H = 8`: The size of recent history, in blocks.
32197
32279
  *
32198
- * https://graypaper.fluffylabs.dev/#/7e6ff6a/445000445000?v=0.6.7
32280
+ * https://graypaper.fluffylabs.dev/#/579bd12/416300416500
32199
32281
  */
32200
- const ELECTIVE_ITEM_BALANCE = 10n;
32282
+ const MAX_RECENT_HISTORY = 8;
32283
+ /** Recent history of a single block. */
32284
+ class BlockState extends WithDebug {
32285
+ headerHash;
32286
+ accumulationResult;
32287
+ postStateRoot;
32288
+ reported;
32289
+ static Codec = descriptors_codec.Class(BlockState, {
32290
+ headerHash: descriptors_codec.bytes(hash_HASH_SIZE).asOpaque(),
32291
+ accumulationResult: descriptors_codec.bytes(hash_HASH_SIZE),
32292
+ postStateRoot: descriptors_codec.bytes(hash_HASH_SIZE).asOpaque(),
32293
+ reported: codecHashDictionary(WorkPackageInfo.Codec, (x) => x.workPackageHash),
32294
+ });
32295
+ static create({ headerHash, accumulationResult, postStateRoot, reported }) {
32296
+ return new BlockState(headerHash, accumulationResult, postStateRoot, reported);
32297
+ }
32298
+ constructor(
32299
+ /** Header hash. */
32300
+ headerHash,
32301
+ /** Merkle mountain belt of accumulation result. */
32302
+ accumulationResult,
32303
+ /** Posterior state root filled in with a 1-block delay. */
32304
+ postStateRoot,
32305
+ /** Reported work packages (no more than number of cores). */
32306
+ reported) {
32307
+ super();
32308
+ this.headerHash = headerHash;
32309
+ this.accumulationResult = accumulationResult;
32310
+ this.postStateRoot = postStateRoot;
32311
+ this.reported = reported;
32312
+ }
32313
+ }
32201
32314
  /**
32202
- * `B_L`: The additional minimum balance required per octet of elective service state.
32315
+ * Recent history of blocks.
32203
32316
  *
32204
- * https://graypaper.fluffylabs.dev/#/7e6ff6a/445400445400?v=0.6.7
32317
+ * https://graypaper.fluffylabs.dev/#/7e6ff6a/0fc9010fc901?v=0.6.7
32205
32318
  */
32206
- const ELECTIVE_BYTE_BALANCE = 1n;
32207
- const zeroSizeHint = {
32208
- bytes: 0,
32209
- isExact: true,
32210
- };
32211
- /** 0-byte read, return given default value */
32319
+ class RecentBlocks extends WithDebug {
32320
+ blocks;
32321
+ accumulationLog;
32322
+ static Codec = descriptors_codec.Class(RecentBlocks, {
32323
+ blocks: codecKnownSizeArray(BlockState.Codec, {
32324
+ minLength: 0,
32325
+ maxLength: MAX_RECENT_HISTORY,
32326
+ typicalLength: MAX_RECENT_HISTORY,
32327
+ }),
32328
+ accumulationLog: descriptors_codec.object({
32329
+ peaks: descriptors_readonlyArray(descriptors_codec.sequenceVarLen(descriptors_codec.optional(descriptors_codec.bytes(hash_HASH_SIZE)))),
32330
+ }),
32331
+ });
32332
+ static empty() {
32333
+ return new RecentBlocks(sized_array_asKnownSize([]), {
32334
+ peaks: [],
32335
+ });
32336
+ }
32337
+ static create(a) {
32338
+ return new RecentBlocks(a.blocks, a.accumulationLog);
32339
+ }
32340
+ constructor(
32341
+ /**
32342
+ * Most recent blocks.
32343
+ * https://graypaper.fluffylabs.dev/#/7e6ff6a/0fea010fea01?v=0.6.7
32344
+ */
32345
+ blocks,
32346
+ /**
32347
+ * Accumulation output log.
32348
+ * https://graypaper.fluffylabs.dev/#/7e6ff6a/0f02020f0202?v=0.6.7
32349
+ */
32350
+ accumulationLog) {
32351
+ super();
32352
+ this.blocks = blocks;
32353
+ this.accumulationLog = accumulationLog;
32354
+ }
32355
+ }
32356
+
32357
+ ;// CONCATENATED MODULE: ./packages/jam/state/recently-accumulated.ts
32358
+
32359
+
32360
+
32361
+
32362
+ const recentlyAccumulatedCodec = codecPerEpochBlock(descriptors_codec.sequenceVarLen(descriptors_codec.bytes(hash_HASH_SIZE).asOpaque()).convert((x) => Array.from(x), (x) => HashSet.from(x)));
32363
+
32364
+ ;// CONCATENATED MODULE: ./packages/jam/state/validator-data.ts
32365
+
32366
+
32367
+
32368
+
32369
+ /**
32370
+ * Fixed size of validator metadata.
32371
+ *
32372
+ * https://graypaper.fluffylabs.dev/#/5f542d7/0d55010d5501
32373
+ */
32374
+ const VALIDATOR_META_BYTES = 128;
32375
+ /**
32376
+ * Details about validators' identity.
32377
+ *
32378
+ * https://graypaper.fluffylabs.dev/#/5f542d7/0d4b010d4c01
32379
+ */
32380
+ class validator_data_ValidatorData extends WithDebug {
32381
+ bandersnatch;
32382
+ ed25519;
32383
+ bls;
32384
+ metadata;
32385
+ static Codec = descriptors_codec.Class(validator_data_ValidatorData, {
32386
+ bandersnatch: descriptors_codec.bytes(BANDERSNATCH_KEY_BYTES).asOpaque(),
32387
+ ed25519: descriptors_codec.bytes(ED25519_KEY_BYTES).asOpaque(),
32388
+ bls: descriptors_codec.bytes(BLS_KEY_BYTES).asOpaque(),
32389
+ metadata: descriptors_codec.bytes(VALIDATOR_META_BYTES),
32390
+ });
32391
+ static create({ ed25519, bandersnatch, bls, metadata }) {
32392
+ return new validator_data_ValidatorData(bandersnatch, ed25519, bls, metadata);
32393
+ }
32394
+ constructor(
32395
+ /** Bandersnatch public key. */
32396
+ bandersnatch,
32397
+ /** ED25519 key data. */
32398
+ ed25519,
32399
+ /** BLS public key. */
32400
+ bls,
32401
+ /** Validator-defined additional metdata. */
32402
+ metadata) {
32403
+ super();
32404
+ this.bandersnatch = bandersnatch;
32405
+ this.ed25519 = ed25519;
32406
+ this.bls = bls;
32407
+ this.metadata = metadata;
32408
+ }
32409
+ }
32410
+ const validatorsDataCodec = common_codecPerValidator(validator_data_ValidatorData.Codec);
32411
+
32412
+ ;// CONCATENATED MODULE: ./packages/jam/state/safrole-data.ts
32413
+
32414
+
32415
+
32416
+
32417
+
32418
+
32419
+
32420
+
32421
+
32422
+
32423
+
32424
+ var SafroleSealingKeysKind;
32425
+ (function (SafroleSealingKeysKind) {
32426
+ SafroleSealingKeysKind[SafroleSealingKeysKind["Tickets"] = 0] = "Tickets";
32427
+ SafroleSealingKeysKind[SafroleSealingKeysKind["Keys"] = 1] = "Keys";
32428
+ })(SafroleSealingKeysKind || (SafroleSealingKeysKind = {}));
32429
+ const codecBandersnatchKey = descriptors_codec.bytes(BANDERSNATCH_KEY_BYTES).asOpaque();
32430
+ class safrole_data_SafroleSealingKeysData extends WithDebug {
32431
+ kind;
32432
+ keys;
32433
+ tickets;
32434
+ static Codec = codecWithContext((context) => {
32435
+ return descriptors_codec.custom({
32436
+ name: "SafroleSealingKeys",
32437
+ sizeHint: { bytes: 1 + hash_HASH_SIZE * context.epochLength, isExact: false },
32438
+ }, (e, x) => {
32439
+ e.varU32(numbers_tryAsU32(x.kind));
32440
+ if (x.kind === SafroleSealingKeysKind.Keys) {
32441
+ e.sequenceFixLen(codecBandersnatchKey, x.keys);
32442
+ }
32443
+ else {
32444
+ e.sequenceFixLen(tickets_Ticket.Codec, x.tickets);
32445
+ }
32446
+ }, (d) => {
32447
+ const epochLength = context.epochLength;
32448
+ const kind = d.varU32();
32449
+ if (kind === SafroleSealingKeysKind.Keys) {
32450
+ const keys = d.sequenceFixLen(codecBandersnatchKey, epochLength);
32451
+ return safrole_data_SafroleSealingKeysData.keys(tryAsPerEpochBlock(keys, context));
32452
+ }
32453
+ if (kind === SafroleSealingKeysKind.Tickets) {
32454
+ const tickets = d.sequenceFixLen(tickets_Ticket.Codec, epochLength);
32455
+ return safrole_data_SafroleSealingKeysData.tickets(tryAsPerEpochBlock(tickets, context));
32456
+ }
32457
+ throw new Error(`Unexpected safrole sealing keys kind: ${kind}`);
32458
+ }, (s) => {
32459
+ const kind = s.decoder.varU32();
32460
+ if (kind === SafroleSealingKeysKind.Keys) {
32461
+ s.sequenceFixLen(codecBandersnatchKey, context.epochLength);
32462
+ return;
32463
+ }
32464
+ if (kind === SafroleSealingKeysKind.Tickets) {
32465
+ s.sequenceFixLen(tickets_Ticket.Codec, context.epochLength);
32466
+ return;
32467
+ }
32468
+ throw new Error(`Unexpected safrole sealing keys kind: ${kind}`);
32469
+ });
32470
+ });
32471
+ static keys(keys) {
32472
+ return new safrole_data_SafroleSealingKeysData(SafroleSealingKeysKind.Keys, keys, undefined);
32473
+ }
32474
+ static tickets(tickets) {
32475
+ return new safrole_data_SafroleSealingKeysData(SafroleSealingKeysKind.Tickets, undefined, tickets);
32476
+ }
32477
+ constructor(kind, keys, tickets) {
32478
+ super();
32479
+ this.kind = kind;
32480
+ this.keys = keys;
32481
+ this.tickets = tickets;
32482
+ }
32483
+ }
32484
+ class SafroleData {
32485
+ nextValidatorData;
32486
+ epochRoot;
32487
+ sealingKeySeries;
32488
+ ticketsAccumulator;
32489
+ static Codec = descriptors_codec.Class(SafroleData, {
32490
+ nextValidatorData: common_codecPerValidator(validator_data_ValidatorData.Codec),
32491
+ epochRoot: descriptors_codec.bytes(bandersnatch_BANDERSNATCH_RING_ROOT_BYTES).asOpaque(),
32492
+ sealingKeySeries: safrole_data_SafroleSealingKeysData.Codec,
32493
+ ticketsAccumulator: descriptors_readonlyArray(descriptors_codec.sequenceVarLen(tickets_Ticket.Codec)).convert(seeThrough, sized_array_asKnownSize),
32494
+ });
32495
+ static create({ nextValidatorData, epochRoot, sealingKeySeries, ticketsAccumulator }) {
32496
+ return new SafroleData(nextValidatorData, epochRoot, sealingKeySeries, ticketsAccumulator);
32497
+ }
32498
+ constructor(
32499
+ /** gamma_k */
32500
+ nextValidatorData,
32501
+ /** gamma_z */
32502
+ epochRoot,
32503
+ /** gamma_s */
32504
+ sealingKeySeries,
32505
+ /** gamma_a */
32506
+ ticketsAccumulator) {
32507
+ this.nextValidatorData = nextValidatorData;
32508
+ this.epochRoot = epochRoot;
32509
+ this.sealingKeySeries = sealingKeySeries;
32510
+ this.ticketsAccumulator = ticketsAccumulator;
32511
+ }
32512
+ }
32513
+
32514
+ ;// CONCATENATED MODULE: ./packages/jam/state/service.ts
32515
+
32516
+
32517
+
32518
+
32519
+
32520
+
32521
+ /**
32522
+ * `B_S`: The basic minimum balance which all services require.
32523
+ *
32524
+ * https://graypaper.fluffylabs.dev/#/7e6ff6a/445800445800?v=0.6.7
32525
+ */
32526
+ const BASE_SERVICE_BALANCE = 100n;
32527
+ /**
32528
+ * `B_I`: The additional minimum balance required per item of elective service state.
32529
+ *
32530
+ * https://graypaper.fluffylabs.dev/#/7e6ff6a/445000445000?v=0.6.7
32531
+ */
32532
+ const ELECTIVE_ITEM_BALANCE = 10n;
32533
+ /**
32534
+ * `B_L`: The additional minimum balance required per octet of elective service state.
32535
+ *
32536
+ * https://graypaper.fluffylabs.dev/#/7e6ff6a/445400445400?v=0.6.7
32537
+ */
32538
+ const ELECTIVE_BYTE_BALANCE = 1n;
32539
+ const zeroSizeHint = {
32540
+ bytes: 0,
32541
+ isExact: true,
32542
+ };
32543
+ /** 0-byte read, return given default value */
32212
32544
  const ignoreValueWithDefault = (defaultValue) => Descriptor.new("ignoreValue", zeroSizeHint, (_e, _v) => { }, (_d) => defaultValue, (_s) => { });
32213
32545
  /** Encode and decode object with leading version number. */
32214
32546
  const codecWithVersion = (val) => Descriptor.new("withVersion", {
@@ -32369,358 +32701,418 @@ class LookupHistoryItem {
32369
32701
  }
32370
32702
  }
32371
32703
 
32372
- ;// CONCATENATED MODULE: ./packages/jam/state/privileged-services.ts
32704
+ ;// CONCATENATED MODULE: ./packages/jam/state/statistics.ts
32373
32705
 
32374
32706
 
32375
32707
 
32376
32708
 
32377
32709
 
32378
- /** Dictionary entry of services that auto-accumulate every block. */
32379
- class AutoAccumulate {
32380
- service;
32381
- gasLimit;
32382
- static Codec = descriptors_codec.Class(AutoAccumulate, {
32383
- service: descriptors_codec.u32.asOpaque(),
32384
- gasLimit: descriptors_codec.u64.asOpaque(),
32710
+
32711
+ const codecServiceId = Compatibility.isSuite(TestSuite.W3F_DAVXY) || Compatibility.isSuite(TestSuite.JAMDUNA, GpVersion.V0_6_7)
32712
+ ? descriptors_codec.u32.asOpaque()
32713
+ : descriptors_codec.varU32.convert((s) => numbers_tryAsU32(s), (i) => tryAsServiceId(i));
32714
+ /**
32715
+ * Activity Record of a single validator.
32716
+ *
32717
+ * https://graypaper.fluffylabs.dev/#/579bd12/183701183701
32718
+ */
32719
+ class ValidatorStatistics {
32720
+ blocks;
32721
+ tickets;
32722
+ preImages;
32723
+ preImagesSize;
32724
+ guarantees;
32725
+ assurances;
32726
+ static Codec = descriptors_codec.Class(ValidatorStatistics, {
32727
+ blocks: descriptors_codec.u32,
32728
+ tickets: descriptors_codec.u32,
32729
+ preImages: descriptors_codec.u32,
32730
+ preImagesSize: descriptors_codec.u32,
32731
+ guarantees: descriptors_codec.u32,
32732
+ assurances: descriptors_codec.u32,
32385
32733
  });
32386
- static create({ service, gasLimit }) {
32387
- return new AutoAccumulate(service, gasLimit);
32734
+ static create({ blocks, tickets, preImages, preImagesSize, guarantees, assurances, }) {
32735
+ return new ValidatorStatistics(blocks, tickets, preImages, preImagesSize, guarantees, assurances);
32388
32736
  }
32389
32737
  constructor(
32390
- /** Service id that auto-accumulates. */
32391
- service,
32392
- /** Gas limit for auto-accumulation. */
32393
- gasLimit) {
32394
- this.service = service;
32395
- this.gasLimit = gasLimit;
32396
- }
32397
- }
32398
- /**
32399
- * https://graypaper.fluffylabs.dev/#/ab2cdbd/114402114402?v=0.7.2
32400
- */
32401
- class PrivilegedServices {
32402
- manager;
32403
- delegator;
32404
- registrar;
32405
- assigners;
32406
- autoAccumulateServices;
32407
- /** https://graypaper.fluffylabs.dev/#/ab2cdbd/3bbd023bcb02?v=0.7.2 */
32408
- static Codec = descriptors_codec.Class(PrivilegedServices, {
32409
- manager: descriptors_codec.u32.asOpaque(),
32410
- assigners: codecPerCore(descriptors_codec.u32.asOpaque()),
32411
- delegator: descriptors_codec.u32.asOpaque(),
32412
- registrar: Compatibility.isGreaterOrEqual(GpVersion.V0_7_1)
32413
- ? descriptors_codec.u32.asOpaque()
32414
- : ignoreValueWithDefault(tryAsServiceId(2 ** 32 - 1)),
32415
- autoAccumulateServices: readonlyArray(descriptors_codec.sequenceVarLen(AutoAccumulate.Codec)),
32416
- });
32417
- static create(a) {
32418
- return new PrivilegedServices(a.manager, a.delegator, a.registrar, a.assigners, a.autoAccumulateServices);
32738
+ /** The number of blocks produced by the validator. */
32739
+ blocks,
32740
+ /** The number of tickets introduced by the validator. */
32741
+ tickets,
32742
+ /** The number of preimages introduced by the validator. */
32743
+ preImages,
32744
+ /** The total number of octets across all preimages introduced by the validator. */
32745
+ preImagesSize,
32746
+ /** The number of reports guaranteed by the validator. */
32747
+ guarantees,
32748
+ /** The number of availability assurances made by the validator. */
32749
+ assurances) {
32750
+ this.blocks = blocks;
32751
+ this.tickets = tickets;
32752
+ this.preImages = preImages;
32753
+ this.preImagesSize = preImagesSize;
32754
+ this.guarantees = guarantees;
32755
+ this.assurances = assurances;
32419
32756
  }
32420
- constructor(
32421
- /**
32422
- * `χ_M`: Manages alteration of χ from block to block,
32423
- * as well as bestow services with storage deposit credits.
32424
- * https://graypaper.fluffylabs.dev/#/ab2cdbd/111502111902?v=0.7.2
32425
- */
32426
- manager,
32427
- /** `χ_V`: Managers validator keys. */
32428
- delegator,
32429
- /**
32430
- * `χ_R`: Manages the creation of services in protected range.
32431
- *
32432
- * https://graypaper.fluffylabs.dev/#/ab2cdbd/111b02111d02?v=0.7.2
32433
- */
32434
- registrar,
32435
- /** `χ_A`: Manages authorization queue one for each core. */
32436
- assigners,
32437
- /** `χ_Z`: Dictionary of services that auto-accumulate every block with their gas limit. */
32438
- autoAccumulateServices) {
32439
- this.manager = manager;
32440
- this.delegator = delegator;
32441
- this.registrar = registrar;
32442
- this.assigners = assigners;
32443
- this.autoAccumulateServices = autoAccumulateServices;
32757
+ static empty() {
32758
+ const zero = numbers_tryAsU32(0);
32759
+ return new ValidatorStatistics(zero, zero, zero, zero, zero, zero);
32444
32760
  }
32445
32761
  }
32446
-
32447
- ;// CONCATENATED MODULE: ./packages/jam/state/recent-blocks.ts
32448
-
32449
-
32450
-
32451
-
32452
-
32453
-
32762
+ const codecVarU16 = descriptors_codec.varU32.convert((i) => numbers_tryAsU32(i), (o) => numbers_tryAsU16(o));
32763
+ /** Encode/decode unsigned gas. */
32764
+ const codecVarGas = descriptors_codec.varU64.convert((g) => numbers_tryAsU64(g), (i) => tryAsServiceGas(i));
32454
32765
  /**
32455
- * `H = 8`: The size of recent history, in blocks.
32766
+ * Single core statistics.
32767
+ * Updated per block, based on incoming work reports (`w`).
32456
32768
  *
32457
- * https://graypaper.fluffylabs.dev/#/579bd12/416300416500
32769
+ * https://graypaper.fluffylabs.dev/#/68eaa1f/18f10318f103?v=0.6.4
32770
+ * https://github.com/gavofyork/graypaper/blob/9bffb08f3ea7b67832019176754df4fb36b9557d/text/statistics.tex#L65
32458
32771
  */
32459
- const MAX_RECENT_HISTORY = 8;
32460
- /** Recent history of a single block. */
32461
- class BlockState extends WithDebug {
32462
- headerHash;
32463
- accumulationResult;
32464
- postStateRoot;
32465
- reported;
32466
- static Codec = descriptors_codec.Class(BlockState, {
32467
- headerHash: descriptors_codec.bytes(hash_HASH_SIZE).asOpaque(),
32468
- accumulationResult: descriptors_codec.bytes(hash_HASH_SIZE),
32469
- postStateRoot: descriptors_codec.bytes(hash_HASH_SIZE).asOpaque(),
32470
- reported: codecHashDictionary(WorkPackageInfo.Codec, (x) => x.workPackageHash),
32471
- });
32472
- static create({ headerHash, accumulationResult, postStateRoot, reported }) {
32473
- return new BlockState(headerHash, accumulationResult, postStateRoot, reported);
32772
+ class CoreStatistics {
32773
+ dataAvailabilityLoad;
32774
+ popularity;
32775
+ imports;
32776
+ exports;
32777
+ extrinsicSize;
32778
+ extrinsicCount;
32779
+ bundleSize;
32780
+ gasUsed;
32781
+ static Codec = Compatibility.isGreaterOrEqual(GpVersion.V0_7_0)
32782
+ ? descriptors_codec.Class(CoreStatistics, {
32783
+ dataAvailabilityLoad: descriptors_codec.varU32,
32784
+ popularity: codecVarU16,
32785
+ imports: codecVarU16,
32786
+ extrinsicCount: codecVarU16,
32787
+ extrinsicSize: descriptors_codec.varU32,
32788
+ exports: codecVarU16,
32789
+ bundleSize: descriptors_codec.varU32,
32790
+ gasUsed: codecVarGas,
32791
+ })
32792
+ : descriptors_codec.Class(CoreStatistics, {
32793
+ dataAvailabilityLoad: descriptors_codec.varU32,
32794
+ popularity: codecVarU16,
32795
+ imports: codecVarU16,
32796
+ exports: codecVarU16,
32797
+ extrinsicSize: descriptors_codec.varU32,
32798
+ extrinsicCount: codecVarU16,
32799
+ bundleSize: descriptors_codec.varU32,
32800
+ gasUsed: codecVarGas,
32801
+ });
32802
+ static create(v) {
32803
+ return new CoreStatistics(v.dataAvailabilityLoad, v.popularity, v.imports, v.exports, v.extrinsicSize, v.extrinsicCount, v.bundleSize, v.gasUsed);
32474
32804
  }
32475
32805
  constructor(
32476
- /** Header hash. */
32477
- headerHash,
32478
- /** Merkle mountain belt of accumulation result. */
32479
- accumulationResult,
32480
- /** Posterior state root filled in with a 1-block delay. */
32481
- postStateRoot,
32482
- /** Reported work packages (no more than number of cores). */
32483
- reported) {
32484
- super();
32485
- this.headerHash = headerHash;
32486
- this.accumulationResult = accumulationResult;
32487
- this.postStateRoot = postStateRoot;
32488
- this.reported = reported;
32489
- }
32490
- }
32491
- class RecentBlocks extends WithDebug {
32492
- blocks;
32493
- accumulationLog;
32494
- static Codec = descriptors_codec.Class(RecentBlocks, {
32495
- blocks: codecKnownSizeArray(BlockState.Codec, {
32496
- minLength: 0,
32497
- maxLength: MAX_RECENT_HISTORY,
32498
- typicalLength: MAX_RECENT_HISTORY,
32499
- }),
32500
- accumulationLog: descriptors_codec.object({
32501
- peaks: readonlyArray(descriptors_codec.sequenceVarLen(descriptors_codec.optional(descriptors_codec.bytes(hash_HASH_SIZE)))),
32502
- }),
32503
- });
32504
- static create(a) {
32505
- return new RecentBlocks(a.blocks, a.accumulationLog);
32806
+ /** `d` */
32807
+ dataAvailabilityLoad,
32808
+ /** `p` */
32809
+ popularity,
32810
+ /** `i` */
32811
+ imports,
32812
+ /** `e` */
32813
+ exports,
32814
+ /** `z` */
32815
+ extrinsicSize,
32816
+ /** `x` */
32817
+ extrinsicCount,
32818
+ /** `b` */
32819
+ bundleSize,
32820
+ /** `u` */
32821
+ gasUsed) {
32822
+ this.dataAvailabilityLoad = dataAvailabilityLoad;
32823
+ this.popularity = popularity;
32824
+ this.imports = imports;
32825
+ this.exports = exports;
32826
+ this.extrinsicSize = extrinsicSize;
32827
+ this.extrinsicCount = extrinsicCount;
32828
+ this.bundleSize = bundleSize;
32829
+ this.gasUsed = gasUsed;
32506
32830
  }
32507
- constructor(
32508
- /**
32509
- * Most recent blocks.
32510
- * https://graypaper.fluffylabs.dev/#/7e6ff6a/0fea010fea01?v=0.6.7
32511
- */
32512
- blocks,
32513
- /**
32514
- * Accumulation output log.
32515
- * https://graypaper.fluffylabs.dev/#/7e6ff6a/0f02020f0202?v=0.6.7
32516
- */
32517
- accumulationLog) {
32518
- super();
32519
- this.blocks = blocks;
32520
- this.accumulationLog = accumulationLog;
32831
+ static empty() {
32832
+ const zero = numbers_tryAsU32(0);
32833
+ const zero16 = numbers_tryAsU16(0);
32834
+ const zeroGas = tryAsServiceGas(0);
32835
+ return new CoreStatistics(zero, zero16, zero16, zero16, zero, zero16, zero, zeroGas);
32521
32836
  }
32522
32837
  }
32523
32838
  /**
32524
- * Recent history of blocks.
32839
+ * Service statistics.
32840
+ * Updated per block, based on available work reports (`W`).
32525
32841
  *
32526
- * https://graypaper.fluffylabs.dev/#/7e6ff6a/0fc9010fc901?v=0.6.7
32842
+ * https://graypaper.fluffylabs.dev/#/1c979cb/199802199802?v=0.7.1
32527
32843
  */
32528
- class RecentBlocksHistory extends WithDebug {
32529
- current;
32530
- static Codec = Descriptor.new("RecentBlocksHistory", RecentBlocks.Codec.sizeHint, (encoder, value) => RecentBlocks.Codec.encode(encoder, value.asCurrent()), (decoder) => {
32531
- const recentBlocks = RecentBlocks.Codec.decode(decoder);
32532
- return RecentBlocksHistory.create(recentBlocks);
32533
- }, (skip) => {
32534
- return RecentBlocks.Codec.skip(skip);
32844
+ class ServiceStatistics {
32845
+ providedCount;
32846
+ providedSize;
32847
+ refinementCount;
32848
+ refinementGasUsed;
32849
+ imports;
32850
+ exports;
32851
+ extrinsicSize;
32852
+ extrinsicCount;
32853
+ accumulateCount;
32854
+ accumulateGasUsed;
32855
+ onTransfersCount;
32856
+ onTransfersGasUsed;
32857
+ static Codec = Compatibility.selectIfGreaterOrEqual({
32858
+ fallback: descriptors_codec.Class(ServiceStatistics, {
32859
+ providedCount: codecVarU16,
32860
+ providedSize: descriptors_codec.varU32,
32861
+ refinementCount: descriptors_codec.varU32,
32862
+ refinementGasUsed: codecVarGas,
32863
+ imports: codecVarU16,
32864
+ exports: codecVarU16,
32865
+ extrinsicSize: descriptors_codec.varU32,
32866
+ extrinsicCount: codecVarU16,
32867
+ accumulateCount: descriptors_codec.varU32,
32868
+ accumulateGasUsed: codecVarGas,
32869
+ onTransfersCount: descriptors_codec.varU32,
32870
+ onTransfersGasUsed: codecVarGas,
32871
+ }),
32872
+ versions: {
32873
+ [GpVersion.V0_7_0]: descriptors_codec.Class(ServiceStatistics, {
32874
+ providedCount: codecVarU16,
32875
+ providedSize: descriptors_codec.varU32,
32876
+ refinementCount: descriptors_codec.varU32,
32877
+ refinementGasUsed: codecVarGas,
32878
+ imports: codecVarU16,
32879
+ extrinsicCount: codecVarU16,
32880
+ extrinsicSize: descriptors_codec.varU32,
32881
+ exports: codecVarU16,
32882
+ accumulateCount: descriptors_codec.varU32,
32883
+ accumulateGasUsed: codecVarGas,
32884
+ onTransfersCount: descriptors_codec.varU32,
32885
+ onTransfersGasUsed: codecVarGas,
32886
+ }),
32887
+ [GpVersion.V0_7_1]: descriptors_codec.Class(ServiceStatistics, {
32888
+ providedCount: codecVarU16,
32889
+ providedSize: descriptors_codec.varU32,
32890
+ refinementCount: descriptors_codec.varU32,
32891
+ refinementGasUsed: codecVarGas,
32892
+ imports: codecVarU16,
32893
+ extrinsicCount: codecVarU16,
32894
+ extrinsicSize: descriptors_codec.varU32,
32895
+ exports: codecVarU16,
32896
+ accumulateCount: descriptors_codec.varU32,
32897
+ accumulateGasUsed: codecVarGas,
32898
+ onTransfersCount: ignoreValueWithDefault(numbers_tryAsU32(0)),
32899
+ onTransfersGasUsed: ignoreValueWithDefault(tryAsServiceGas(0)),
32900
+ }),
32901
+ },
32535
32902
  });
32536
- static create(recentBlocks) {
32537
- return new RecentBlocksHistory(recentBlocks);
32903
+ static create(v) {
32904
+ 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);
32905
+ }
32906
+ constructor(
32907
+ /** `p.0` */
32908
+ providedCount,
32909
+ /** `p.1` */
32910
+ providedSize,
32911
+ /** `r.0` */
32912
+ refinementCount,
32913
+ /** `r.1` */
32914
+ refinementGasUsed,
32915
+ /** `i` */
32916
+ imports,
32917
+ /** `e` */
32918
+ exports,
32919
+ /** `z` */
32920
+ extrinsicSize,
32921
+ /** `x` */
32922
+ extrinsicCount,
32923
+ /** `a.0` */
32924
+ accumulateCount,
32925
+ /** `a.1` */
32926
+ accumulateGasUsed,
32927
+ /** `t.0` @deprecated since 0.7.1 */
32928
+ onTransfersCount,
32929
+ /** `t.1` @deprecated since 0.7.1 */
32930
+ onTransfersGasUsed) {
32931
+ this.providedCount = providedCount;
32932
+ this.providedSize = providedSize;
32933
+ this.refinementCount = refinementCount;
32934
+ this.refinementGasUsed = refinementGasUsed;
32935
+ this.imports = imports;
32936
+ this.exports = exports;
32937
+ this.extrinsicSize = extrinsicSize;
32938
+ this.extrinsicCount = extrinsicCount;
32939
+ this.accumulateCount = accumulateCount;
32940
+ this.accumulateGasUsed = accumulateGasUsed;
32941
+ this.onTransfersCount = onTransfersCount;
32942
+ this.onTransfersGasUsed = onTransfersGasUsed;
32538
32943
  }
32539
32944
  static empty() {
32540
- return RecentBlocksHistory.create(RecentBlocks.create({
32541
- blocks: sized_array_asKnownSize([]),
32542
- accumulationLog: { peaks: [] },
32543
- }));
32945
+ const zero = numbers_tryAsU32(0);
32946
+ const zero16 = numbers_tryAsU16(0);
32947
+ const zeroGas = tryAsServiceGas(0);
32948
+ return new ServiceStatistics(zero16, zero, zero, zeroGas, zero16, zero16, zero, zero16, zero, zeroGas, zero, zeroGas);
32544
32949
  }
32545
- /**
32546
- * Returns the block's BEEFY super peak.
32547
- */
32548
- static accumulationResult(block) {
32549
- return block.accumulationResult;
32950
+ }
32951
+ /** `pi`: Statistics of each validator, cores statistics and services statistics. */
32952
+ class StatisticsData {
32953
+ current;
32954
+ previous;
32955
+ cores;
32956
+ services;
32957
+ static Codec = descriptors_codec.Class(StatisticsData, {
32958
+ current: common_codecPerValidator(ValidatorStatistics.Codec),
32959
+ previous: common_codecPerValidator(ValidatorStatistics.Codec),
32960
+ cores: codecPerCore(CoreStatistics.Codec),
32961
+ services: descriptors_codec.dictionary(codecServiceId, ServiceStatistics.Codec, {
32962
+ sortKeys: (a, b) => a - b,
32963
+ }),
32964
+ });
32965
+ static create(v) {
32966
+ return new StatisticsData(v.current, v.previous, v.cores, v.services);
32550
32967
  }
32551
- constructor(current) {
32552
- super();
32968
+ constructor(current, previous, cores, services) {
32553
32969
  this.current = current;
32554
- }
32555
- /** History of recent blocks with maximum size of `MAX_RECENT_HISTORY` */
32556
- get blocks() {
32557
- if (this.current !== null) {
32558
- return this.current.blocks;
32559
- }
32560
- throw new Error("RecentBlocksHistory is in invalid state");
32561
- }
32562
- asCurrent() {
32563
- if (this.current === null) {
32564
- throw new Error("Cannot access current RecentBlocks format");
32565
- }
32566
- return this.current;
32567
- }
32568
- updateBlocks(blocks) {
32569
- if (this.current !== null) {
32570
- return RecentBlocksHistory.create(RecentBlocks.create({
32571
- ...this.current,
32572
- blocks: opaque_asOpaqueType(blocks),
32573
- }));
32574
- }
32575
- throw new Error("RecentBlocksHistory is in invalid state. Cannot be updated!");
32970
+ this.previous = previous;
32971
+ this.cores = cores;
32972
+ this.services = services;
32576
32973
  }
32577
32974
  }
32578
32975
 
32579
- ;// CONCATENATED MODULE: ./packages/jam/state/validator-data.ts
32976
+ ;// CONCATENATED MODULE: ./packages/jam/state/in-memory-state-view.ts
32580
32977
 
32581
32978
 
32582
32979
 
32583
- /**
32584
- * Fixed size of validator metadata.
32585
- *
32586
- * https://graypaper.fluffylabs.dev/#/5f542d7/0d55010d5501
32587
- */
32588
- const VALIDATOR_META_BYTES = 128;
32589
- /**
32590
- * Details about validators' identity.
32591
- *
32592
- * https://graypaper.fluffylabs.dev/#/5f542d7/0d4b010d4c01
32593
- */
32594
- class ValidatorData extends WithDebug {
32595
- bandersnatch;
32596
- ed25519;
32597
- bls;
32598
- metadata;
32599
- static Codec = descriptors_codec.Class(ValidatorData, {
32600
- bandersnatch: descriptors_codec.bytes(BANDERSNATCH_KEY_BYTES).asOpaque(),
32601
- ed25519: descriptors_codec.bytes(ED25519_KEY_BYTES).asOpaque(),
32602
- bls: descriptors_codec.bytes(BLS_KEY_BYTES).asOpaque(),
32603
- metadata: descriptors_codec.bytes(VALIDATOR_META_BYTES),
32604
- });
32605
- static create({ ed25519, bandersnatch, bls, metadata }) {
32606
- return new ValidatorData(bandersnatch, ed25519, bls, metadata);
32607
- }
32608
- constructor(
32609
- /** Bandersnatch public key. */
32610
- bandersnatch,
32611
- /** ED25519 key data. */
32612
- ed25519,
32613
- /** BLS public key. */
32614
- bls,
32615
- /** Validator-defined additional metdata. */
32616
- metadata) {
32617
- super();
32618
- this.bandersnatch = bandersnatch;
32619
- this.ed25519 = ed25519;
32620
- this.bls = bls;
32621
- this.metadata = metadata;
32622
- }
32623
- }
32624
32980
 
32625
- ;// CONCATENATED MODULE: ./packages/jam/state/safrole-data.ts
32626
32981
 
32627
32982
 
32628
32983
 
32629
32984
 
32630
32985
 
32631
32986
 
32987
+ class InMemoryStateView {
32988
+ chainSpec;
32989
+ state;
32990
+ constructor(chainSpec, state) {
32991
+ this.chainSpec = chainSpec;
32992
+ this.state = state;
32993
+ }
32994
+ availabilityAssignmentView() {
32995
+ return reencodeAsView(availabilityAssignmentsCodec, this.state.availabilityAssignment, this.chainSpec);
32996
+ }
32997
+ designatedValidatorDataView() {
32998
+ return reencodeAsView(validatorsDataCodec, this.state.designatedValidatorData, this.chainSpec);
32999
+ }
33000
+ currentValidatorDataView() {
33001
+ return reencodeAsView(validatorsDataCodec, this.state.currentValidatorData, this.chainSpec);
33002
+ }
33003
+ previousValidatorDataView() {
33004
+ return reencodeAsView(validatorsDataCodec, this.state.previousValidatorData, this.chainSpec);
33005
+ }
33006
+ authPoolsView() {
33007
+ return reencodeAsView(authPoolsCodec, this.state.authPools, this.chainSpec);
33008
+ }
33009
+ authQueuesView() {
33010
+ return reencodeAsView(authQueuesCodec, this.state.authQueues, this.chainSpec);
33011
+ }
33012
+ recentBlocksView() {
33013
+ return reencodeAsView(RecentBlocks.Codec, this.state.recentBlocks, this.chainSpec);
33014
+ }
33015
+ statisticsView() {
33016
+ return reencodeAsView(StatisticsData.Codec, this.state.statistics, this.chainSpec);
33017
+ }
33018
+ accumulationQueueView() {
33019
+ return reencodeAsView(accumulationQueueCodec, this.state.accumulationQueue, this.chainSpec);
33020
+ }
33021
+ recentlyAccumulatedView() {
33022
+ return reencodeAsView(recentlyAccumulatedCodec, this.state.recentlyAccumulated, this.chainSpec);
33023
+ }
33024
+ safroleDataView() {
33025
+ // TODO [ToDr] Consider exposting `safrole` from state
33026
+ // instead of individual fields
33027
+ const safrole = SafroleData.create({
33028
+ nextValidatorData: this.state.nextValidatorData,
33029
+ epochRoot: this.state.epochRoot,
33030
+ sealingKeySeries: this.state.sealingKeySeries,
33031
+ ticketsAccumulator: this.state.ticketsAccumulator,
33032
+ });
33033
+ return reencodeAsView(SafroleData.Codec, safrole, this.chainSpec);
33034
+ }
33035
+ getServiceInfoView(id) {
33036
+ const service = this.state.getService(id);
33037
+ if (service === null) {
33038
+ return null;
33039
+ }
33040
+ return reencodeAsView(ServiceAccountInfo.Codec, service.getInfo(), this.chainSpec);
33041
+ }
33042
+ }
32632
33043
 
33044
+ ;// CONCATENATED MODULE: ./packages/jam/state/privileged-services.ts
32633
33045
 
32634
33046
 
32635
33047
 
32636
33048
 
32637
- var SafroleSealingKeysKind;
32638
- (function (SafroleSealingKeysKind) {
32639
- SafroleSealingKeysKind[SafroleSealingKeysKind["Tickets"] = 0] = "Tickets";
32640
- SafroleSealingKeysKind[SafroleSealingKeysKind["Keys"] = 1] = "Keys";
32641
- })(SafroleSealingKeysKind || (SafroleSealingKeysKind = {}));
32642
- const codecBandersnatchKey = descriptors_codec.bytes(BANDERSNATCH_KEY_BYTES).asOpaque();
32643
- class SafroleSealingKeysData extends WithDebug {
32644
- kind;
32645
- keys;
32646
- tickets;
32647
- static Codec = codecWithContext((context) => {
32648
- return descriptors_codec.custom({
32649
- name: "SafroleSealingKeys",
32650
- sizeHint: { bytes: 1 + hash_HASH_SIZE * context.epochLength, isExact: false },
32651
- }, (e, x) => {
32652
- e.varU32(numbers_tryAsU32(x.kind));
32653
- if (x.kind === SafroleSealingKeysKind.Keys) {
32654
- e.sequenceFixLen(codecBandersnatchKey, x.keys);
32655
- }
32656
- else {
32657
- e.sequenceFixLen(Ticket.Codec, x.tickets);
32658
- }
32659
- }, (d) => {
32660
- const epochLength = context.epochLength;
32661
- const kind = d.varU32();
32662
- if (kind === SafroleSealingKeysKind.Keys) {
32663
- const keys = d.sequenceFixLen(codecBandersnatchKey, epochLength);
32664
- return SafroleSealingKeysData.keys(tryAsPerEpochBlock(keys, context));
32665
- }
32666
- if (kind === SafroleSealingKeysKind.Tickets) {
32667
- const tickets = d.sequenceFixLen(Ticket.Codec, epochLength);
32668
- return SafroleSealingKeysData.tickets(tryAsPerEpochBlock(tickets, context));
32669
- }
32670
- throw new Error(`Unexpected safrole sealing keys kind: ${kind}`);
32671
- }, (s) => {
32672
- const kind = s.decoder.varU32();
32673
- if (kind === SafroleSealingKeysKind.Keys) {
32674
- s.sequenceFixLen(codecBandersnatchKey, context.epochLength);
32675
- return;
32676
- }
32677
- if (kind === SafroleSealingKeysKind.Tickets) {
32678
- s.sequenceFixLen(Ticket.Codec, context.epochLength);
32679
- return;
32680
- }
32681
- throw new Error(`Unexpected safrole sealing keys kind: ${kind}`);
32682
- });
33049
+
33050
+ /** Dictionary entry of services that auto-accumulate every block. */
33051
+ class AutoAccumulate {
33052
+ service;
33053
+ gasLimit;
33054
+ static Codec = descriptors_codec.Class(AutoAccumulate, {
33055
+ service: descriptors_codec.u32.asOpaque(),
33056
+ gasLimit: descriptors_codec.u64.asOpaque(),
32683
33057
  });
32684
- static keys(keys) {
32685
- return new SafroleSealingKeysData(SafroleSealingKeysKind.Keys, keys, undefined);
32686
- }
32687
- static tickets(tickets) {
32688
- return new SafroleSealingKeysData(SafroleSealingKeysKind.Tickets, undefined, tickets);
33058
+ static create({ service, gasLimit }) {
33059
+ return new AutoAccumulate(service, gasLimit);
32689
33060
  }
32690
- constructor(kind, keys, tickets) {
32691
- super();
32692
- this.kind = kind;
32693
- this.keys = keys;
32694
- this.tickets = tickets;
33061
+ constructor(
33062
+ /** Service id that auto-accumulates. */
33063
+ service,
33064
+ /** Gas limit for auto-accumulation. */
33065
+ gasLimit) {
33066
+ this.service = service;
33067
+ this.gasLimit = gasLimit;
32695
33068
  }
32696
33069
  }
32697
- class SafroleData {
32698
- nextValidatorData;
32699
- epochRoot;
32700
- sealingKeySeries;
32701
- ticketsAccumulator;
32702
- static Codec = descriptors_codec.Class(SafroleData, {
32703
- nextValidatorData: codecPerValidator(ValidatorData.Codec),
32704
- epochRoot: descriptors_codec.bytes(BANDERSNATCH_RING_ROOT_BYTES).asOpaque(),
32705
- sealingKeySeries: SafroleSealingKeysData.Codec,
32706
- ticketsAccumulator: readonlyArray(descriptors_codec.sequenceVarLen(Ticket.Codec)).convert(seeThrough, sized_array_asKnownSize),
33070
+ /**
33071
+ * https://graypaper.fluffylabs.dev/#/ab2cdbd/114402114402?v=0.7.2
33072
+ */
33073
+ class PrivilegedServices {
33074
+ manager;
33075
+ delegator;
33076
+ registrar;
33077
+ assigners;
33078
+ autoAccumulateServices;
33079
+ /** https://graypaper.fluffylabs.dev/#/ab2cdbd/3bbd023bcb02?v=0.7.2 */
33080
+ static Codec = descriptors_codec.Class(PrivilegedServices, {
33081
+ manager: descriptors_codec.u32.asOpaque(),
33082
+ assigners: codecPerCore(descriptors_codec.u32.asOpaque()),
33083
+ delegator: descriptors_codec.u32.asOpaque(),
33084
+ registrar: Compatibility.isGreaterOrEqual(GpVersion.V0_7_1)
33085
+ ? descriptors_codec.u32.asOpaque()
33086
+ : ignoreValueWithDefault(tryAsServiceId(2 ** 32 - 1)),
33087
+ autoAccumulateServices: descriptors_readonlyArray(descriptors_codec.sequenceVarLen(AutoAccumulate.Codec)),
32707
33088
  });
32708
- static create({ nextValidatorData, epochRoot, sealingKeySeries, ticketsAccumulator }) {
32709
- return new SafroleData(nextValidatorData, epochRoot, sealingKeySeries, ticketsAccumulator);
33089
+ static create(a) {
33090
+ return new PrivilegedServices(a.manager, a.delegator, a.registrar, a.assigners, a.autoAccumulateServices);
32710
33091
  }
32711
33092
  constructor(
32712
- /** gamma_k */
32713
- nextValidatorData,
32714
- /** gamma_z */
32715
- epochRoot,
32716
- /** gamma_s */
32717
- sealingKeySeries,
32718
- /** gamma_a */
32719
- ticketsAccumulator) {
32720
- this.nextValidatorData = nextValidatorData;
32721
- this.epochRoot = epochRoot;
32722
- this.sealingKeySeries = sealingKeySeries;
32723
- this.ticketsAccumulator = ticketsAccumulator;
33093
+ /**
33094
+ * `χ_M`: Manages alteration of χ from block to block,
33095
+ * as well as bestow services with storage deposit credits.
33096
+ * https://graypaper.fluffylabs.dev/#/ab2cdbd/111502111902?v=0.7.2
33097
+ */
33098
+ manager,
33099
+ /** `χ_V`: Managers validator keys. */
33100
+ delegator,
33101
+ /**
33102
+ * `χ_R`: Manages the creation of services in protected range.
33103
+ *
33104
+ * https://graypaper.fluffylabs.dev/#/ab2cdbd/111b02111d02?v=0.7.2
33105
+ */
33106
+ registrar,
33107
+ /** `χ_A`: Manages authorization queue one for each core. */
33108
+ assigners,
33109
+ /** `χ_Z`: Dictionary of services that auto-accumulate every block with their gas limit. */
33110
+ autoAccumulateServices) {
33111
+ this.manager = manager;
33112
+ this.delegator = delegator;
33113
+ this.registrar = registrar;
33114
+ this.assigners = assigners;
33115
+ this.autoAccumulateServices = autoAccumulateServices;
32724
33116
  }
32725
33117
  }
32726
33118
 
@@ -32849,311 +33241,39 @@ class UpdateService {
32849
33241
  var UpdateStorageKind;
32850
33242
  (function (UpdateStorageKind) {
32851
33243
  /** Set a storage value. */
32852
- UpdateStorageKind[UpdateStorageKind["Set"] = 0] = "Set";
32853
- /** Remove a storage value. */
32854
- UpdateStorageKind[UpdateStorageKind["Remove"] = 1] = "Remove";
32855
- })(UpdateStorageKind || (UpdateStorageKind = {}));
32856
- /**
32857
- * Update service storage item.
32858
- *
32859
- * Can either create/modify an entry or remove it.
32860
- */
32861
- class UpdateStorage {
32862
- serviceId;
32863
- action;
32864
- constructor(serviceId, action) {
32865
- this.serviceId = serviceId;
32866
- this.action = action;
32867
- }
32868
- static set({ serviceId, storage }) {
32869
- return new UpdateStorage(serviceId, { kind: UpdateStorageKind.Set, storage });
32870
- }
32871
- static remove({ serviceId, key }) {
32872
- return new UpdateStorage(serviceId, { kind: UpdateStorageKind.Remove, key });
32873
- }
32874
- get key() {
32875
- if (this.action.kind === UpdateStorageKind.Remove) {
32876
- return this.action.key;
32877
- }
32878
- return this.action.storage.key;
32879
- }
32880
- get value() {
32881
- if (this.action.kind === UpdateStorageKind.Remove) {
32882
- return null;
32883
- }
32884
- return this.action.storage.value;
32885
- }
32886
- }
32887
-
32888
- ;// CONCATENATED MODULE: ./packages/jam/state/statistics.ts
32889
-
32890
-
32891
-
32892
-
32893
-
32894
-
32895
- const codecServiceId = Compatibility.isSuite(TestSuite.W3F_DAVXY) || Compatibility.isSuite(TestSuite.JAMDUNA, GpVersion.V0_6_7)
32896
- ? descriptors_codec.u32.asOpaque()
32897
- : descriptors_codec.varU32.convert((s) => numbers_tryAsU32(s), (i) => tryAsServiceId(i));
32898
- /**
32899
- * Activity Record of a single validator.
32900
- *
32901
- * https://graypaper.fluffylabs.dev/#/579bd12/183701183701
32902
- */
32903
- class ValidatorStatistics {
32904
- blocks;
32905
- tickets;
32906
- preImages;
32907
- preImagesSize;
32908
- guarantees;
32909
- assurances;
32910
- static Codec = descriptors_codec.Class(ValidatorStatistics, {
32911
- blocks: descriptors_codec.u32,
32912
- tickets: descriptors_codec.u32,
32913
- preImages: descriptors_codec.u32,
32914
- preImagesSize: descriptors_codec.u32,
32915
- guarantees: descriptors_codec.u32,
32916
- assurances: descriptors_codec.u32,
32917
- });
32918
- static create({ blocks, tickets, preImages, preImagesSize, guarantees, assurances, }) {
32919
- return new ValidatorStatistics(blocks, tickets, preImages, preImagesSize, guarantees, assurances);
32920
- }
32921
- constructor(
32922
- /** The number of blocks produced by the validator. */
32923
- blocks,
32924
- /** The number of tickets introduced by the validator. */
32925
- tickets,
32926
- /** The number of preimages introduced by the validator. */
32927
- preImages,
32928
- /** The total number of octets across all preimages introduced by the validator. */
32929
- preImagesSize,
32930
- /** The number of reports guaranteed by the validator. */
32931
- guarantees,
32932
- /** The number of availability assurances made by the validator. */
32933
- assurances) {
32934
- this.blocks = blocks;
32935
- this.tickets = tickets;
32936
- this.preImages = preImages;
32937
- this.preImagesSize = preImagesSize;
32938
- this.guarantees = guarantees;
32939
- this.assurances = assurances;
32940
- }
32941
- static empty() {
32942
- const zero = numbers_tryAsU32(0);
32943
- return new ValidatorStatistics(zero, zero, zero, zero, zero, zero);
32944
- }
32945
- }
32946
- const codecVarU16 = descriptors_codec.varU32.convert((i) => numbers_tryAsU32(i), (o) => numbers_tryAsU16(o));
32947
- /** Encode/decode unsigned gas. */
32948
- const codecVarGas = descriptors_codec.varU64.convert((g) => numbers_tryAsU64(g), (i) => tryAsServiceGas(i));
32949
- /**
32950
- * Single core statistics.
32951
- * Updated per block, based on incoming work reports (`w`).
32952
- *
32953
- * https://graypaper.fluffylabs.dev/#/68eaa1f/18f10318f103?v=0.6.4
32954
- * https://github.com/gavofyork/graypaper/blob/9bffb08f3ea7b67832019176754df4fb36b9557d/text/statistics.tex#L65
32955
- */
32956
- class CoreStatistics {
32957
- dataAvailabilityLoad;
32958
- popularity;
32959
- imports;
32960
- exports;
32961
- extrinsicSize;
32962
- extrinsicCount;
32963
- bundleSize;
32964
- gasUsed;
32965
- static Codec = Compatibility.isGreaterOrEqual(GpVersion.V0_7_0)
32966
- ? descriptors_codec.Class(CoreStatistics, {
32967
- dataAvailabilityLoad: descriptors_codec.varU32,
32968
- popularity: codecVarU16,
32969
- imports: codecVarU16,
32970
- extrinsicCount: codecVarU16,
32971
- extrinsicSize: descriptors_codec.varU32,
32972
- exports: codecVarU16,
32973
- bundleSize: descriptors_codec.varU32,
32974
- gasUsed: codecVarGas,
32975
- })
32976
- : descriptors_codec.Class(CoreStatistics, {
32977
- dataAvailabilityLoad: descriptors_codec.varU32,
32978
- popularity: codecVarU16,
32979
- imports: codecVarU16,
32980
- exports: codecVarU16,
32981
- extrinsicSize: descriptors_codec.varU32,
32982
- extrinsicCount: codecVarU16,
32983
- bundleSize: descriptors_codec.varU32,
32984
- gasUsed: codecVarGas,
32985
- });
32986
- static create(v) {
32987
- return new CoreStatistics(v.dataAvailabilityLoad, v.popularity, v.imports, v.exports, v.extrinsicSize, v.extrinsicCount, v.bundleSize, v.gasUsed);
32988
- }
32989
- constructor(
32990
- /** `d` */
32991
- dataAvailabilityLoad,
32992
- /** `p` */
32993
- popularity,
32994
- /** `i` */
32995
- imports,
32996
- /** `e` */
32997
- exports,
32998
- /** `z` */
32999
- extrinsicSize,
33000
- /** `x` */
33001
- extrinsicCount,
33002
- /** `b` */
33003
- bundleSize,
33004
- /** `u` */
33005
- gasUsed) {
33006
- this.dataAvailabilityLoad = dataAvailabilityLoad;
33007
- this.popularity = popularity;
33008
- this.imports = imports;
33009
- this.exports = exports;
33010
- this.extrinsicSize = extrinsicSize;
33011
- this.extrinsicCount = extrinsicCount;
33012
- this.bundleSize = bundleSize;
33013
- this.gasUsed = gasUsed;
33014
- }
33015
- static empty() {
33016
- const zero = numbers_tryAsU32(0);
33017
- const zero16 = numbers_tryAsU16(0);
33018
- const zeroGas = tryAsServiceGas(0);
33019
- return new CoreStatistics(zero, zero16, zero16, zero16, zero, zero16, zero, zeroGas);
33020
- }
33021
- }
33244
+ UpdateStorageKind[UpdateStorageKind["Set"] = 0] = "Set";
33245
+ /** Remove a storage value. */
33246
+ UpdateStorageKind[UpdateStorageKind["Remove"] = 1] = "Remove";
33247
+ })(UpdateStorageKind || (UpdateStorageKind = {}));
33022
33248
  /**
33023
- * Service statistics.
33024
- * Updated per block, based on available work reports (`W`).
33249
+ * Update service storage item.
33025
33250
  *
33026
- * https://graypaper.fluffylabs.dev/#/1c979cb/199802199802?v=0.7.1
33251
+ * Can either create/modify an entry or remove it.
33027
33252
  */
33028
- class ServiceStatistics {
33029
- providedCount;
33030
- providedSize;
33031
- refinementCount;
33032
- refinementGasUsed;
33033
- imports;
33034
- exports;
33035
- extrinsicSize;
33036
- extrinsicCount;
33037
- accumulateCount;
33038
- accumulateGasUsed;
33039
- onTransfersCount;
33040
- onTransfersGasUsed;
33041
- static Codec = Compatibility.selectIfGreaterOrEqual({
33042
- fallback: descriptors_codec.Class(ServiceStatistics, {
33043
- providedCount: codecVarU16,
33044
- providedSize: descriptors_codec.varU32,
33045
- refinementCount: descriptors_codec.varU32,
33046
- refinementGasUsed: codecVarGas,
33047
- imports: codecVarU16,
33048
- exports: codecVarU16,
33049
- extrinsicSize: descriptors_codec.varU32,
33050
- extrinsicCount: codecVarU16,
33051
- accumulateCount: descriptors_codec.varU32,
33052
- accumulateGasUsed: codecVarGas,
33053
- onTransfersCount: descriptors_codec.varU32,
33054
- onTransfersGasUsed: codecVarGas,
33055
- }),
33056
- versions: {
33057
- [GpVersion.V0_7_0]: descriptors_codec.Class(ServiceStatistics, {
33058
- providedCount: codecVarU16,
33059
- providedSize: descriptors_codec.varU32,
33060
- refinementCount: descriptors_codec.varU32,
33061
- refinementGasUsed: codecVarGas,
33062
- imports: codecVarU16,
33063
- extrinsicCount: codecVarU16,
33064
- extrinsicSize: descriptors_codec.varU32,
33065
- exports: codecVarU16,
33066
- accumulateCount: descriptors_codec.varU32,
33067
- accumulateGasUsed: codecVarGas,
33068
- onTransfersCount: descriptors_codec.varU32,
33069
- onTransfersGasUsed: codecVarGas,
33070
- }),
33071
- [GpVersion.V0_7_1]: descriptors_codec.Class(ServiceStatistics, {
33072
- providedCount: codecVarU16,
33073
- providedSize: descriptors_codec.varU32,
33074
- refinementCount: descriptors_codec.varU32,
33075
- refinementGasUsed: codecVarGas,
33076
- imports: codecVarU16,
33077
- extrinsicCount: codecVarU16,
33078
- extrinsicSize: descriptors_codec.varU32,
33079
- exports: codecVarU16,
33080
- accumulateCount: descriptors_codec.varU32,
33081
- accumulateGasUsed: codecVarGas,
33082
- onTransfersCount: ignoreValueWithDefault(numbers_tryAsU32(0)),
33083
- onTransfersGasUsed: ignoreValueWithDefault(tryAsServiceGas(0)),
33084
- }),
33085
- },
33086
- });
33087
- static create(v) {
33088
- 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);
33253
+ class UpdateStorage {
33254
+ serviceId;
33255
+ action;
33256
+ constructor(serviceId, action) {
33257
+ this.serviceId = serviceId;
33258
+ this.action = action;
33089
33259
  }
33090
- constructor(
33091
- /** `p.0` */
33092
- providedCount,
33093
- /** `p.1` */
33094
- providedSize,
33095
- /** `r.0` */
33096
- refinementCount,
33097
- /** `r.1` */
33098
- refinementGasUsed,
33099
- /** `i` */
33100
- imports,
33101
- /** `e` */
33102
- exports,
33103
- /** `z` */
33104
- extrinsicSize,
33105
- /** `x` */
33106
- extrinsicCount,
33107
- /** `a.0` */
33108
- accumulateCount,
33109
- /** `a.1` */
33110
- accumulateGasUsed,
33111
- /** `t.0` @deprecated since 0.7.1 */
33112
- onTransfersCount,
33113
- /** `t.1` @deprecated since 0.7.1 */
33114
- onTransfersGasUsed) {
33115
- this.providedCount = providedCount;
33116
- this.providedSize = providedSize;
33117
- this.refinementCount = refinementCount;
33118
- this.refinementGasUsed = refinementGasUsed;
33119
- this.imports = imports;
33120
- this.exports = exports;
33121
- this.extrinsicSize = extrinsicSize;
33122
- this.extrinsicCount = extrinsicCount;
33123
- this.accumulateCount = accumulateCount;
33124
- this.accumulateGasUsed = accumulateGasUsed;
33125
- this.onTransfersCount = onTransfersCount;
33126
- this.onTransfersGasUsed = onTransfersGasUsed;
33260
+ static set({ serviceId, storage }) {
33261
+ return new UpdateStorage(serviceId, { kind: UpdateStorageKind.Set, storage });
33127
33262
  }
33128
- static empty() {
33129
- const zero = numbers_tryAsU32(0);
33130
- const zero16 = numbers_tryAsU16(0);
33131
- const zeroGas = tryAsServiceGas(0);
33132
- return new ServiceStatistics(zero16, zero, zero, zeroGas, zero16, zero16, zero, zero16, zero, zeroGas, zero, zeroGas);
33263
+ static remove({ serviceId, key }) {
33264
+ return new UpdateStorage(serviceId, { kind: UpdateStorageKind.Remove, key });
33133
33265
  }
33134
- }
33135
- /** `pi`: Statistics of each validator, cores statistics and services statistics. */
33136
- class StatisticsData {
33137
- current;
33138
- previous;
33139
- cores;
33140
- services;
33141
- static Codec = descriptors_codec.Class(StatisticsData, {
33142
- current: codecPerValidator(ValidatorStatistics.Codec),
33143
- previous: codecPerValidator(ValidatorStatistics.Codec),
33144
- cores: codecPerCore(CoreStatistics.Codec),
33145
- services: descriptors_codec.dictionary(codecServiceId, ServiceStatistics.Codec, {
33146
- sortKeys: (a, b) => a - b,
33147
- }),
33148
- });
33149
- static create(v) {
33150
- return new StatisticsData(v.current, v.previous, v.cores, v.services);
33266
+ get key() {
33267
+ if (this.action.kind === UpdateStorageKind.Remove) {
33268
+ return this.action.key;
33269
+ }
33270
+ return this.action.storage.key;
33151
33271
  }
33152
- constructor(current, previous, cores, services) {
33153
- this.current = current;
33154
- this.previous = previous;
33155
- this.cores = cores;
33156
- this.services = services;
33272
+ get value() {
33273
+ if (this.action.kind === UpdateStorageKind.Remove) {
33274
+ return null;
33275
+ }
33276
+ return this.action.storage.value;
33157
33277
  }
33158
33278
  }
33159
33279
 
@@ -33178,6 +33298,7 @@ class StatisticsData {
33178
33298
 
33179
33299
 
33180
33300
 
33301
+
33181
33302
 
33182
33303
 
33183
33304
  var in_memory_state_UpdateError;
@@ -33278,10 +33399,11 @@ class InMemoryService extends WithDebug {
33278
33399
  /**
33279
33400
  * A special version of state, stored fully in-memory.
33280
33401
  */
33281
- class InMemoryState extends WithDebug {
33402
+ class in_memory_state_InMemoryState extends WithDebug {
33403
+ chainSpec;
33282
33404
  /** Create a new `InMemoryState` by providing all required fields. */
33283
- static create(state) {
33284
- return new InMemoryState(state);
33405
+ static new(chainSpec, state) {
33406
+ return new in_memory_state_InMemoryState(chainSpec, state);
33285
33407
  }
33286
33408
  /**
33287
33409
  * Create a new `InMemoryState` with a partial state override.
@@ -33290,14 +33412,14 @@ class InMemoryState extends WithDebug {
33290
33412
  * not-necessarily coherent values.
33291
33413
  */
33292
33414
  static partial(spec, partial) {
33293
- const state = InMemoryState.empty(spec);
33415
+ const state = in_memory_state_InMemoryState.empty(spec);
33294
33416
  Object.assign(state, partial);
33295
33417
  return state;
33296
33418
  }
33297
33419
  /**
33298
33420
  * Create a new `InMemoryState` from some other state object.
33299
33421
  */
33300
- static copyFrom(other, servicesData) {
33422
+ static copyFrom(chainSpec, other, servicesData) {
33301
33423
  const services = new Map();
33302
33424
  for (const [id, entries] of servicesData.entries()) {
33303
33425
  const service = other.getService(id);
@@ -33307,7 +33429,7 @@ class InMemoryState extends WithDebug {
33307
33429
  const inMemService = InMemoryService.copyFrom(service, entries);
33308
33430
  services.set(id, inMemService);
33309
33431
  }
33310
- return InMemoryState.create({
33432
+ return in_memory_state_InMemoryState.new(chainSpec, {
33311
33433
  availabilityAssignment: other.availabilityAssignment,
33312
33434
  accumulationQueue: other.accumulationQueue,
33313
33435
  designatedValidatorData: other.designatedValidatorData,
@@ -33504,8 +33626,9 @@ class InMemoryState extends WithDebug {
33504
33626
  getService(id) {
33505
33627
  return this.services.get(id) ?? null;
33506
33628
  }
33507
- constructor(s) {
33629
+ constructor(chainSpec, s) {
33508
33630
  super();
33631
+ this.chainSpec = chainSpec;
33509
33632
  this.availabilityAssignment = s.availabilityAssignment;
33510
33633
  this.designatedValidatorData = s.designatedValidatorData;
33511
33634
  this.nextValidatorData = s.nextValidatorData;
@@ -33527,31 +33650,34 @@ class InMemoryState extends WithDebug {
33527
33650
  this.accumulationOutputLog = s.accumulationOutputLog;
33528
33651
  this.services = s.services;
33529
33652
  }
33653
+ view() {
33654
+ return new InMemoryStateView(this.chainSpec, this);
33655
+ }
33530
33656
  /**
33531
33657
  * Create an empty and possibly incoherent `InMemoryState`.
33532
33658
  */
33533
33659
  static empty(spec) {
33534
- return new InMemoryState({
33660
+ return new in_memory_state_InMemoryState(spec, {
33535
33661
  availabilityAssignment: tryAsPerCore(Array.from({ length: spec.coresCount }, () => null), spec),
33536
- designatedValidatorData: tryAsPerValidator(Array.from({ length: spec.validatorsCount }, () => ValidatorData.create({
33662
+ designatedValidatorData: tryAsPerValidator(Array.from({ length: spec.validatorsCount }, () => validator_data_ValidatorData.create({
33537
33663
  bandersnatch: bytes_Bytes.zero(BANDERSNATCH_KEY_BYTES).asOpaque(),
33538
33664
  bls: bytes_Bytes.zero(BLS_KEY_BYTES).asOpaque(),
33539
33665
  ed25519: bytes_Bytes.zero(ED25519_KEY_BYTES).asOpaque(),
33540
33666
  metadata: bytes_Bytes.zero(VALIDATOR_META_BYTES).asOpaque(),
33541
33667
  })), spec),
33542
- nextValidatorData: tryAsPerValidator(Array.from({ length: spec.validatorsCount }, () => ValidatorData.create({
33668
+ nextValidatorData: tryAsPerValidator(Array.from({ length: spec.validatorsCount }, () => validator_data_ValidatorData.create({
33543
33669
  bandersnatch: bytes_Bytes.zero(BANDERSNATCH_KEY_BYTES).asOpaque(),
33544
33670
  bls: bytes_Bytes.zero(BLS_KEY_BYTES).asOpaque(),
33545
33671
  ed25519: bytes_Bytes.zero(ED25519_KEY_BYTES).asOpaque(),
33546
33672
  metadata: bytes_Bytes.zero(VALIDATOR_META_BYTES).asOpaque(),
33547
33673
  })), spec),
33548
- currentValidatorData: tryAsPerValidator(Array.from({ length: spec.validatorsCount }, () => ValidatorData.create({
33674
+ currentValidatorData: tryAsPerValidator(Array.from({ length: spec.validatorsCount }, () => validator_data_ValidatorData.create({
33549
33675
  bandersnatch: bytes_Bytes.zero(BANDERSNATCH_KEY_BYTES).asOpaque(),
33550
33676
  bls: bytes_Bytes.zero(BLS_KEY_BYTES).asOpaque(),
33551
33677
  ed25519: bytes_Bytes.zero(ED25519_KEY_BYTES).asOpaque(),
33552
33678
  metadata: bytes_Bytes.zero(VALIDATOR_META_BYTES).asOpaque(),
33553
33679
  })), spec),
33554
- previousValidatorData: tryAsPerValidator(Array.from({ length: spec.validatorsCount }, () => ValidatorData.create({
33680
+ previousValidatorData: tryAsPerValidator(Array.from({ length: spec.validatorsCount }, () => validator_data_ValidatorData.create({
33555
33681
  bandersnatch: bytes_Bytes.zero(BANDERSNATCH_KEY_BYTES).asOpaque(),
33556
33682
  bls: bytes_Bytes.zero(BLS_KEY_BYTES).asOpaque(),
33557
33683
  ed25519: bytes_Bytes.zero(ED25519_KEY_BYTES).asOpaque(),
@@ -33567,7 +33693,7 @@ class InMemoryState extends WithDebug {
33567
33693
  entropy: FixedSizeArray.fill(() => bytes_Bytes.zero(hash_HASH_SIZE).asOpaque(), ENTROPY_ENTRIES),
33568
33694
  authPools: tryAsPerCore(Array.from({ length: spec.coresCount }, () => sized_array_asKnownSize([])), spec),
33569
33695
  authQueues: tryAsPerCore(Array.from({ length: spec.coresCount }, () => FixedSizeArray.fill(() => bytes_Bytes.zero(hash_HASH_SIZE).asOpaque(), AUTHORIZATION_QUEUE_SIZE)), spec),
33570
- recentBlocks: RecentBlocksHistory.empty(),
33696
+ recentBlocks: RecentBlocks.empty(),
33571
33697
  statistics: StatisticsData.create({
33572
33698
  current: tryAsPerValidator(Array.from({ length: spec.validatorsCount }, () => ValidatorStatistics.empty()), spec),
33573
33699
  previous: tryAsPerValidator(Array.from({ length: spec.validatorsCount }, () => ValidatorStatistics.empty()), spec),
@@ -33577,8 +33703,8 @@ class InMemoryState extends WithDebug {
33577
33703
  accumulationQueue: tryAsPerEpochBlock(Array.from({ length: spec.epochLength }, () => []), spec),
33578
33704
  recentlyAccumulated: tryAsPerEpochBlock(Array.from({ length: spec.epochLength }, () => HashSet.new()), spec),
33579
33705
  ticketsAccumulator: sized_array_asKnownSize([]),
33580
- sealingKeySeries: SafroleSealingKeysData.keys(tryAsPerEpochBlock(Array.from({ length: spec.epochLength }, () => bytes_Bytes.zero(BANDERSNATCH_KEY_BYTES).asOpaque()), spec)),
33581
- epochRoot: bytes_Bytes.zero(BANDERSNATCH_RING_ROOT_BYTES).asOpaque(),
33706
+ sealingKeySeries: safrole_data_SafroleSealingKeysData.keys(tryAsPerEpochBlock(Array.from({ length: spec.epochLength }, () => bytes_Bytes.zero(BANDERSNATCH_KEY_BYTES).asOpaque()), spec)),
33707
+ epochRoot: bytes_Bytes.zero(bandersnatch_BANDERSNATCH_RING_ROOT_BYTES).asOpaque(),
33582
33708
  privilegedServices: PrivilegedServices.create({
33583
33709
  manager: tryAsServiceId(0),
33584
33710
  assigners: tryAsPerCore(new Array(spec.coresCount).fill(tryAsServiceId(0)), spec),
@@ -33618,50 +33744,9 @@ const serviceDataCodec = descriptors_codec.dictionary(descriptors_codec.u32.asOp
33618
33744
 
33619
33745
 
33620
33746
 
33621
- ;// CONCATENATED MODULE: ./packages/jam/state/not-yet-accumulated.ts
33622
-
33623
-
33624
-
33625
33747
 
33626
33748
 
33627
33749
 
33628
- /**
33629
- * Ready (i.e. available and/or audited) but not-yet-accumulated work-reports.
33630
- *
33631
- * https://graypaper.fluffylabs.dev/#/5f542d7/165300165400
33632
- */
33633
- class NotYetAccumulatedReport extends WithDebug {
33634
- report;
33635
- dependencies;
33636
- static Codec = descriptors_codec.Class(NotYetAccumulatedReport, {
33637
- report: WorkReport.Codec,
33638
- dependencies: codecKnownSizeArray(descriptors_codec.bytes(hash_HASH_SIZE).asOpaque(), {
33639
- typicalLength: MAX_REPORT_DEPENDENCIES / 2,
33640
- maxLength: MAX_REPORT_DEPENDENCIES,
33641
- minLength: 0,
33642
- }),
33643
- });
33644
- static create({ report, dependencies }) {
33645
- return new NotYetAccumulatedReport(report, dependencies);
33646
- }
33647
- constructor(
33648
- /**
33649
- * Each of these were made available at most one epoch ago
33650
- * but have or had unfulfilled dependencies.
33651
- */
33652
- report,
33653
- /**
33654
- * Alongside the work-report itself, we retain its un-accumulated
33655
- * dependencies, a set of work-package hashes.
33656
- *
33657
- * https://graypaper.fluffylabs.dev/#/5f542d7/165800165800
33658
- */
33659
- dependencies) {
33660
- super();
33661
- this.report = report;
33662
- this.dependencies = dependencies;
33663
- }
33664
- }
33665
33750
 
33666
33751
  ;// CONCATENATED MODULE: ./packages/jam/state-merkleization/serialize.ts
33667
33752
 
@@ -33675,26 +33760,19 @@ class NotYetAccumulatedReport extends WithDebug {
33675
33760
 
33676
33761
 
33677
33762
 
33678
-
33679
-
33680
-
33681
33763
  /** Serialization for particular state entries. */
33682
- var serialize;
33764
+ var serialize_serialize;
33683
33765
  (function (serialize) {
33684
33766
  /** C(1): https://graypaper.fluffylabs.dev/#/7e6ff6a/3b15013b1501?v=0.6.7 */
33685
33767
  serialize.authPools = {
33686
33768
  key: stateKeys.index(StateKeyIdx.Alpha),
33687
- Codec: codecPerCore(codecKnownSizeArray(descriptors_codec.bytes(hash_HASH_SIZE).asOpaque(), {
33688
- minLength: 0,
33689
- maxLength: MAX_AUTH_POOL_SIZE,
33690
- typicalLength: MAX_AUTH_POOL_SIZE,
33691
- })),
33769
+ Codec: authPoolsCodec,
33692
33770
  extract: (s) => s.authPools,
33693
33771
  };
33694
33772
  /** C(2): https://graypaper.fluffylabs.dev/#/7e6ff6a/3b31013b3101?v=0.6.7 */
33695
33773
  serialize.authQueues = {
33696
33774
  key: stateKeys.index(StateKeyIdx.Phi),
33697
- Codec: codecPerCore(codecFixedSizeArray(descriptors_codec.bytes(hash_HASH_SIZE).asOpaque(), AUTHORIZATION_QUEUE_SIZE)),
33775
+ Codec: authQueuesCodec,
33698
33776
  extract: (s) => s.authQueues,
33699
33777
  };
33700
33778
  /**
@@ -33703,7 +33781,7 @@ var serialize;
33703
33781
  */
33704
33782
  serialize.recentBlocks = {
33705
33783
  key: stateKeys.index(StateKeyIdx.Beta),
33706
- Codec: RecentBlocksHistory.Codec,
33784
+ Codec: RecentBlocks.Codec,
33707
33785
  extract: (s) => s.recentBlocks,
33708
33786
  };
33709
33787
  /** C(4): https://graypaper.fluffylabs.dev/#/7e6ff6a/3b63013b6301?v=0.6.7 */
@@ -33732,25 +33810,25 @@ var serialize;
33732
33810
  /** C(7): https://graypaper.fluffylabs.dev/#/7e6ff6a/3b00023b0002?v=0.6.7 */
33733
33811
  serialize.designatedValidators = {
33734
33812
  key: stateKeys.index(StateKeyIdx.Iota),
33735
- Codec: codecPerValidator(ValidatorData.Codec),
33813
+ Codec: validatorsDataCodec,
33736
33814
  extract: (s) => s.designatedValidatorData,
33737
33815
  };
33738
33816
  /** C(8): https://graypaper.fluffylabs.dev/#/7e6ff6a/3b0d023b0d02?v=0.6.7 */
33739
33817
  serialize.currentValidators = {
33740
33818
  key: stateKeys.index(StateKeyIdx.Kappa),
33741
- Codec: codecPerValidator(ValidatorData.Codec),
33819
+ Codec: validatorsDataCodec,
33742
33820
  extract: (s) => s.currentValidatorData,
33743
33821
  };
33744
33822
  /** C(9): https://graypaper.fluffylabs.dev/#/7e6ff6a/3b1a023b1a02?v=0.6.7 */
33745
33823
  serialize.previousValidators = {
33746
33824
  key: stateKeys.index(StateKeyIdx.Lambda),
33747
- Codec: codecPerValidator(ValidatorData.Codec),
33825
+ Codec: validatorsDataCodec,
33748
33826
  extract: (s) => s.previousValidatorData,
33749
33827
  };
33750
33828
  /** C(10): https://graypaper.fluffylabs.dev/#/7e6ff6a/3b27023b2702?v=0.6.7 */
33751
33829
  serialize.availabilityAssignment = {
33752
33830
  key: stateKeys.index(StateKeyIdx.Rho),
33753
- Codec: codecPerCore(descriptors_codec.optional(AvailabilityAssignment.Codec)),
33831
+ Codec: availabilityAssignmentsCodec,
33754
33832
  extract: (s) => s.availabilityAssignment,
33755
33833
  };
33756
33834
  /** C(11): https://graypaper.fluffylabs.dev/#/7e6ff6a/3b3e023b3e02?v=0.6.7 */
@@ -33774,13 +33852,13 @@ var serialize;
33774
33852
  /** C(14): https://graypaper.fluffylabs.dev/#/1c979cb/3bf0023bf002?v=0.7.1 */
33775
33853
  serialize.accumulationQueue = {
33776
33854
  key: stateKeys.index(StateKeyIdx.Omega),
33777
- Codec: codecPerEpochBlock(readonlyArray(descriptors_codec.sequenceVarLen(NotYetAccumulatedReport.Codec))),
33855
+ Codec: accumulationQueueCodec,
33778
33856
  extract: (s) => s.accumulationQueue,
33779
33857
  };
33780
33858
  /** C(15): https://graypaper.fluffylabs.dev/#/7e6ff6a/3b96023b9602?v=0.6.7 */
33781
33859
  serialize.recentlyAccumulated = {
33782
33860
  key: stateKeys.index(StateKeyIdx.Xi),
33783
- Codec: codecPerEpochBlock(descriptors_codec.sequenceVarLen(descriptors_codec.bytes(hash_HASH_SIZE).asOpaque()).convert((x) => Array.from(x), (x) => HashSet.from(x))),
33861
+ Codec: recentlyAccumulatedCodec,
33784
33862
  extract: (s) => s.recentlyAccumulated,
33785
33863
  };
33786
33864
  /** C(16): https://graypaper.fluffylabs.dev/#/38c4e62/3b46033b4603?v=0.7.0 */
@@ -33809,9 +33887,9 @@ var serialize;
33809
33887
  /** https://graypaper.fluffylabs.dev/#/85129da/387603387603?v=0.6.3 */
33810
33888
  serialize.serviceLookupHistory = (blake2b, serviceId, hash, len) => ({
33811
33889
  key: stateKeys.serviceLookupHistory(blake2b, serviceId, hash, len),
33812
- Codec: readonlyArray(descriptors_codec.sequenceVarLen(descriptors_codec.u32)),
33890
+ Codec: descriptors_readonlyArray(descriptors_codec.sequenceVarLen(descriptors_codec.u32)),
33813
33891
  });
33814
- })(serialize || (serialize = {}));
33892
+ })(serialize_serialize || (serialize_serialize = {}));
33815
33893
  /**
33816
33894
  * Just dump the entire terminal blob as-is.
33817
33895
  *
@@ -33821,6 +33899,87 @@ var serialize;
33821
33899
  */
33822
33900
  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()));
33823
33901
 
33902
+ ;// CONCATENATED MODULE: ./packages/jam/state-merkleization/serialized-state-view.ts
33903
+
33904
+
33905
+ class SerializedStateView {
33906
+ spec;
33907
+ backend;
33908
+ recentlyUsedServices;
33909
+ viewCache;
33910
+ constructor(spec, backend,
33911
+ /** Best-effort list of recently active services. */
33912
+ recentlyUsedServices, viewCache) {
33913
+ this.spec = spec;
33914
+ this.backend = backend;
33915
+ this.recentlyUsedServices = recentlyUsedServices;
33916
+ this.viewCache = viewCache;
33917
+ }
33918
+ retrieveView({ key, Codec }, description) {
33919
+ const cached = this.viewCache.get(key);
33920
+ if (cached !== undefined) {
33921
+ return cached;
33922
+ }
33923
+ const bytes = this.backend.get(key);
33924
+ if (bytes === null) {
33925
+ throw new Error(`Required state entry for ${description} is missing!. Accessing view of key: ${key}`);
33926
+ }
33927
+ // NOTE [ToDr] we are not using `Decoder.decodeObject` here because
33928
+ // it needs to get to the end of the data (skip), yet that's expensive.
33929
+ // we assume that the state data is correct and coherent anyway, so
33930
+ // for performance reasons we simply create the view here.
33931
+ const d = decoder_Decoder.fromBytesBlob(bytes);
33932
+ d.attachContext(this.spec);
33933
+ const view = Codec.View.decode(d);
33934
+ this.viewCache.set(key, view);
33935
+ return view;
33936
+ }
33937
+ availabilityAssignmentView() {
33938
+ return this.retrieveView(serialize_serialize.availabilityAssignment, "availabilityAssignmentView");
33939
+ }
33940
+ designatedValidatorDataView() {
33941
+ return this.retrieveView(serialize_serialize.designatedValidators, "designatedValidatorsView");
33942
+ }
33943
+ currentValidatorDataView() {
33944
+ return this.retrieveView(serialize_serialize.currentValidators, "currentValidatorsView");
33945
+ }
33946
+ previousValidatorDataView() {
33947
+ return this.retrieveView(serialize_serialize.previousValidators, "previousValidatorsView");
33948
+ }
33949
+ authPoolsView() {
33950
+ return this.retrieveView(serialize_serialize.authPools, "authPoolsView");
33951
+ }
33952
+ authQueuesView() {
33953
+ return this.retrieveView(serialize_serialize.authQueues, "authQueuesView");
33954
+ }
33955
+ recentBlocksView() {
33956
+ return this.retrieveView(serialize_serialize.recentBlocks, "recentBlocksView");
33957
+ }
33958
+ statisticsView() {
33959
+ return this.retrieveView(serialize_serialize.statistics, "statisticsView");
33960
+ }
33961
+ accumulationQueueView() {
33962
+ return this.retrieveView(serialize_serialize.accumulationQueue, "accumulationQueueView");
33963
+ }
33964
+ recentlyAccumulatedView() {
33965
+ return this.retrieveView(serialize_serialize.recentlyAccumulated, "recentlyAccumulatedView");
33966
+ }
33967
+ safroleDataView() {
33968
+ return this.retrieveView(serialize_serialize.safrole, "safroleDataView");
33969
+ }
33970
+ getServiceInfoView(id) {
33971
+ const serviceData = serialize_serialize.serviceData(id);
33972
+ const bytes = this.backend.get(serviceData.key);
33973
+ if (bytes === null) {
33974
+ return null;
33975
+ }
33976
+ if (!this.recentlyUsedServices.includes(id)) {
33977
+ this.recentlyUsedServices.push(id);
33978
+ }
33979
+ return decoder_Decoder.decodeObject(serviceData.Codec.View, bytes, this.spec);
33980
+ }
33981
+ }
33982
+
33824
33983
  ;// CONCATENATED MODULE: ./packages/jam/state-merkleization/serialized-state.ts
33825
33984
 
33826
33985
 
@@ -33829,6 +33988,8 @@ const dumpCodec = Descriptor.new("Dump", { bytes: 64, isExact: false }, (e, v) =
33829
33988
 
33830
33989
 
33831
33990
 
33991
+
33992
+
33832
33993
  /**
33833
33994
  * State object which reads it's entries from some backend.
33834
33995
  *
@@ -33841,7 +34002,7 @@ class serialized_state_SerializedState {
33841
34002
  spec;
33842
34003
  blake2b;
33843
34004
  backend;
33844
- _recentServiceIds;
34005
+ recentlyUsedServices;
33845
34006
  /** Create a state-like object from collection of serialized entries. */
33846
34007
  static fromStateEntries(spec, blake2b, state, recentServices = []) {
33847
34008
  return new serialized_state_SerializedState(spec, blake2b, state, recentServices);
@@ -33850,106 +34011,120 @@ class serialized_state_SerializedState {
33850
34011
  static new(spec, blake2b, db, recentServices = []) {
33851
34012
  return new serialized_state_SerializedState(spec, blake2b, db, recentServices);
33852
34013
  }
34014
+ dataCache = hash_dictionary_HashDictionary.new();
34015
+ viewCache = hash_dictionary_HashDictionary.new();
33853
34016
  constructor(spec, blake2b, backend,
33854
34017
  /** Best-effort list of recently active services. */
33855
- _recentServiceIds) {
34018
+ recentlyUsedServices) {
33856
34019
  this.spec = spec;
33857
34020
  this.blake2b = blake2b;
33858
34021
  this.backend = backend;
33859
- this._recentServiceIds = _recentServiceIds;
34022
+ this.recentlyUsedServices = recentlyUsedServices;
33860
34023
  }
33861
34024
  /** Comparing the serialized states, just means comparing their backends. */
33862
34025
  [TEST_COMPARE_USING]() {
33863
34026
  return this.backend;
33864
34027
  }
34028
+ /** Return a non-decoding version of the state. */
34029
+ view() {
34030
+ return new SerializedStateView(this.spec, this.backend, this.recentlyUsedServices, this.viewCache);
34031
+ }
33865
34032
  // TODO [ToDr] Temporary method to update the state,
33866
34033
  // without changing references.
33867
34034
  updateBackend(newBackend) {
33868
34035
  this.backend = newBackend;
34036
+ this.dataCache = hash_dictionary_HashDictionary.new();
34037
+ this.viewCache = hash_dictionary_HashDictionary.new();
33869
34038
  }
33870
34039
  recentServiceIds() {
33871
- return this._recentServiceIds;
34040
+ return this.recentlyUsedServices;
33872
34041
  }
33873
34042
  getService(id) {
33874
- const serviceData = this.retrieveOptional(serialize.serviceData(id));
34043
+ const serviceData = this.retrieveOptional(serialize_serialize.serviceData(id));
33875
34044
  if (serviceData === undefined) {
33876
34045
  return null;
33877
34046
  }
33878
- if (!this._recentServiceIds.includes(id)) {
33879
- this._recentServiceIds.push(id);
34047
+ if (!this.recentlyUsedServices.includes(id)) {
34048
+ this.recentlyUsedServices.push(id);
33880
34049
  }
33881
34050
  return new SerializedService(this.blake2b, id, serviceData, (key) => this.retrieveOptional(key));
33882
34051
  }
33883
- retrieve({ key, Codec }, description) {
33884
- const bytes = this.backend.get(key);
33885
- if (bytes === null) {
33886
- throw new Error(`Required state entry for ${description} is missing!. Accessing key: ${key}`);
34052
+ retrieve(k, description) {
34053
+ const data = this.retrieveOptional(k);
34054
+ if (data === undefined) {
34055
+ throw new Error(`Required state entry for ${description} is missing!. Accessing key: ${k.key}`);
33887
34056
  }
33888
- return decoder_Decoder.decodeObject(Codec, bytes, this.spec);
34057
+ return data;
33889
34058
  }
33890
34059
  retrieveOptional({ key, Codec }) {
34060
+ const cached = this.dataCache.get(key);
34061
+ if (cached !== undefined) {
34062
+ return cached;
34063
+ }
33891
34064
  const bytes = this.backend.get(key);
33892
34065
  if (bytes === null) {
33893
34066
  return undefined;
33894
34067
  }
33895
- return decoder_Decoder.decodeObject(Codec, bytes, this.spec);
34068
+ const data = decoder_Decoder.decodeObject(Codec, bytes, this.spec);
34069
+ this.dataCache.set(key, data);
34070
+ return data;
33896
34071
  }
33897
34072
  get availabilityAssignment() {
33898
- return this.retrieve(serialize.availabilityAssignment, "availabilityAssignment");
34073
+ return this.retrieve(serialize_serialize.availabilityAssignment, "availabilityAssignment");
33899
34074
  }
33900
34075
  get designatedValidatorData() {
33901
- return this.retrieve(serialize.designatedValidators, "designatedValidatorData");
34076
+ return this.retrieve(serialize_serialize.designatedValidators, "designatedValidatorData");
33902
34077
  }
33903
34078
  get nextValidatorData() {
33904
- return this.retrieve(serialize.safrole, "safroleData.nextValidatorData").nextValidatorData;
34079
+ return this.retrieve(serialize_serialize.safrole, "safroleData.nextValidatorData").nextValidatorData;
33905
34080
  }
33906
34081
  get currentValidatorData() {
33907
- return this.retrieve(serialize.currentValidators, "currentValidators");
34082
+ return this.retrieve(serialize_serialize.currentValidators, "currentValidators");
33908
34083
  }
33909
34084
  get previousValidatorData() {
33910
- return this.retrieve(serialize.previousValidators, "previousValidators");
34085
+ return this.retrieve(serialize_serialize.previousValidators, "previousValidators");
33911
34086
  }
33912
34087
  get disputesRecords() {
33913
- return this.retrieve(serialize.disputesRecords, "disputesRecords");
34088
+ return this.retrieve(serialize_serialize.disputesRecords, "disputesRecords");
33914
34089
  }
33915
34090
  get timeslot() {
33916
- return this.retrieve(serialize.timeslot, "timeslot");
34091
+ return this.retrieve(serialize_serialize.timeslot, "timeslot");
33917
34092
  }
33918
34093
  get entropy() {
33919
- return this.retrieve(serialize.entropy, "entropy");
34094
+ return this.retrieve(serialize_serialize.entropy, "entropy");
33920
34095
  }
33921
34096
  get authPools() {
33922
- return this.retrieve(serialize.authPools, "authPools");
34097
+ return this.retrieve(serialize_serialize.authPools, "authPools");
33923
34098
  }
33924
34099
  get authQueues() {
33925
- return this.retrieve(serialize.authQueues, "authQueues");
34100
+ return this.retrieve(serialize_serialize.authQueues, "authQueues");
33926
34101
  }
33927
34102
  get recentBlocks() {
33928
- return this.retrieve(serialize.recentBlocks, "recentBlocks");
34103
+ return this.retrieve(serialize_serialize.recentBlocks, "recentBlocks");
33929
34104
  }
33930
34105
  get statistics() {
33931
- return this.retrieve(serialize.statistics, "statistics");
34106
+ return this.retrieve(serialize_serialize.statistics, "statistics");
33932
34107
  }
33933
34108
  get accumulationQueue() {
33934
- return this.retrieve(serialize.accumulationQueue, "accumulationQueue");
34109
+ return this.retrieve(serialize_serialize.accumulationQueue, "accumulationQueue");
33935
34110
  }
33936
34111
  get recentlyAccumulated() {
33937
- return this.retrieve(serialize.recentlyAccumulated, "recentlyAccumulated");
34112
+ return this.retrieve(serialize_serialize.recentlyAccumulated, "recentlyAccumulated");
33938
34113
  }
33939
34114
  get ticketsAccumulator() {
33940
- return this.retrieve(serialize.safrole, "safroleData.ticketsAccumulator").ticketsAccumulator;
34115
+ return this.retrieve(serialize_serialize.safrole, "safroleData.ticketsAccumulator").ticketsAccumulator;
33941
34116
  }
33942
34117
  get sealingKeySeries() {
33943
- return this.retrieve(serialize.safrole, "safrole.sealingKeySeries").sealingKeySeries;
34118
+ return this.retrieve(serialize_serialize.safrole, "safrole.sealingKeySeries").sealingKeySeries;
33944
34119
  }
33945
34120
  get epochRoot() {
33946
- return this.retrieve(serialize.safrole, "safrole.epochRoot").epochRoot;
34121
+ return this.retrieve(serialize_serialize.safrole, "safrole.epochRoot").epochRoot;
33947
34122
  }
33948
34123
  get privilegedServices() {
33949
- return this.retrieve(serialize.privilegedServices, "privilegedServices");
34124
+ return this.retrieve(serialize_serialize.privilegedServices, "privilegedServices");
33950
34125
  }
33951
34126
  get accumulationOutputLog() {
33952
- return this.retrieve(serialize.accumulationOutputLog, "accumulationOutputLog");
34127
+ return this.retrieve(serialize_serialize.accumulationOutputLog, "accumulationOutputLog");
33953
34128
  }
33954
34129
  }
33955
34130
  /** Service data representation on a serialized state. */
@@ -33978,9 +34153,9 @@ class SerializedService {
33978
34153
  serviceIdAndKey.set(numbers_u32AsLeBytes(this.serviceId));
33979
34154
  serviceIdAndKey.set(rawKey.raw, SERVICE_ID_BYTES);
33980
34155
  const key = opaque_asOpaqueType(bytes_BytesBlob.blobFrom(this.blake2b.hashBytes(serviceIdAndKey).raw));
33981
- return this.retrieveOptional(serialize.serviceStorage(this.blake2b, this.serviceId, key)) ?? null;
34156
+ return this.retrieveOptional(serialize_serialize.serviceStorage(this.blake2b, this.serviceId, key)) ?? null;
33982
34157
  }
33983
- return this.retrieveOptional(serialize.serviceStorage(this.blake2b, this.serviceId, rawKey)) ?? null;
34158
+ return this.retrieveOptional(serialize_serialize.serviceStorage(this.blake2b, this.serviceId, rawKey)) ?? null;
33984
34159
  }
33985
34160
  /**
33986
34161
  * Check if preimage is present in the DB.
@@ -33989,15 +34164,15 @@ class SerializedService {
33989
34164
  */
33990
34165
  hasPreimage(hash) {
33991
34166
  // TODO [ToDr] consider optimizing to avoid fetching the whole data.
33992
- return this.retrieveOptional(serialize.servicePreimages(this.blake2b, this.serviceId, hash)) !== undefined;
34167
+ return this.retrieveOptional(serialize_serialize.servicePreimages(this.blake2b, this.serviceId, hash)) !== undefined;
33993
34168
  }
33994
34169
  /** Retrieve preimage from the DB. */
33995
34170
  getPreimage(hash) {
33996
- return this.retrieveOptional(serialize.servicePreimages(this.blake2b, this.serviceId, hash)) ?? null;
34171
+ return this.retrieveOptional(serialize_serialize.servicePreimages(this.blake2b, this.serviceId, hash)) ?? null;
33997
34172
  }
33998
34173
  /** Retrieve preimage lookup history. */
33999
34174
  getLookupHistory(hash, len) {
34000
- const rawSlots = this.retrieveOptional(serialize.serviceLookupHistory(this.blake2b, this.serviceId, hash, len));
34175
+ const rawSlots = this.retrieveOptional(serialize_serialize.serviceLookupHistory(this.blake2b, this.serviceId, hash, len));
34001
34176
  if (rawSlots === undefined) {
34002
34177
  return null;
34003
34178
  }
@@ -34686,7 +34861,7 @@ function* serializeStateUpdate(spec, blake2b, update) {
34686
34861
  function* serializeRemovedServices(servicesRemoved) {
34687
34862
  for (const serviceId of servicesRemoved ?? []) {
34688
34863
  // TODO [ToDr] what about all data associated with a service?
34689
- const codec = serialize.serviceData(serviceId);
34864
+ const codec = serialize_serialize.serviceData(serviceId);
34690
34865
  yield [StateEntryUpdateAction.Remove, codec.key, EMPTY_BLOB];
34691
34866
  }
34692
34867
  }
@@ -34695,13 +34870,13 @@ function* serializeStorage(storage, blake2b) {
34695
34870
  switch (action.kind) {
34696
34871
  case UpdateStorageKind.Set: {
34697
34872
  const key = action.storage.key;
34698
- const codec = serialize.serviceStorage(blake2b, serviceId, key);
34873
+ const codec = serialize_serialize.serviceStorage(blake2b, serviceId, key);
34699
34874
  yield [StateEntryUpdateAction.Insert, codec.key, action.storage.value];
34700
34875
  break;
34701
34876
  }
34702
34877
  case UpdateStorageKind.Remove: {
34703
34878
  const key = action.key;
34704
- const codec = serialize.serviceStorage(blake2b, serviceId, key);
34879
+ const codec = serialize_serialize.serviceStorage(blake2b, serviceId, key);
34705
34880
  yield [StateEntryUpdateAction.Remove, codec.key, EMPTY_BLOB];
34706
34881
  break;
34707
34882
  }
@@ -34715,10 +34890,10 @@ function* serializePreimages(preimages, encode, blake2b) {
34715
34890
  switch (action.kind) {
34716
34891
  case UpdatePreimageKind.Provide: {
34717
34892
  const { hash, blob } = action.preimage;
34718
- const codec = serialize.servicePreimages(blake2b, serviceId, hash);
34893
+ const codec = serialize_serialize.servicePreimages(blake2b, serviceId, hash);
34719
34894
  yield [StateEntryUpdateAction.Insert, codec.key, blob];
34720
34895
  if (action.slot !== null) {
34721
- const codec2 = serialize.serviceLookupHistory(blake2b, serviceId, hash, numbers_tryAsU32(blob.length));
34896
+ const codec2 = serialize_serialize.serviceLookupHistory(blake2b, serviceId, hash, numbers_tryAsU32(blob.length));
34722
34897
  yield [
34723
34898
  StateEntryUpdateAction.Insert,
34724
34899
  codec2.key,
@@ -34729,15 +34904,15 @@ function* serializePreimages(preimages, encode, blake2b) {
34729
34904
  }
34730
34905
  case UpdatePreimageKind.UpdateOrAdd: {
34731
34906
  const { hash, length, slots } = action.item;
34732
- const codec = serialize.serviceLookupHistory(blake2b, serviceId, hash, length);
34907
+ const codec = serialize_serialize.serviceLookupHistory(blake2b, serviceId, hash, length);
34733
34908
  yield [StateEntryUpdateAction.Insert, codec.key, encode(codec.Codec, slots)];
34734
34909
  break;
34735
34910
  }
34736
34911
  case UpdatePreimageKind.Remove: {
34737
34912
  const { hash, length } = action;
34738
- const codec = serialize.servicePreimages(blake2b, serviceId, hash);
34913
+ const codec = serialize_serialize.servicePreimages(blake2b, serviceId, hash);
34739
34914
  yield [StateEntryUpdateAction.Remove, codec.key, EMPTY_BLOB];
34740
- const codec2 = serialize.serviceLookupHistory(blake2b, serviceId, hash, length);
34915
+ const codec2 = serialize_serialize.serviceLookupHistory(blake2b, serviceId, hash, length);
34741
34916
  yield [StateEntryUpdateAction.Remove, codec2.key, EMPTY_BLOB];
34742
34917
  break;
34743
34918
  }
@@ -34749,12 +34924,12 @@ function* serializePreimages(preimages, encode, blake2b) {
34749
34924
  function* serializeServiceUpdates(servicesUpdates, encode, blake2b) {
34750
34925
  for (const { action, serviceId } of servicesUpdates ?? []) {
34751
34926
  // new service being created or updated
34752
- const codec = serialize.serviceData(serviceId);
34927
+ const codec = serialize_serialize.serviceData(serviceId);
34753
34928
  yield [StateEntryUpdateAction.Insert, codec.key, encode(codec.Codec, action.account)];
34754
34929
  // additional lookup history update
34755
34930
  if (action.kind === UpdateServiceKind.Create && action.lookupHistory !== null) {
34756
34931
  const { lookupHistory } = action;
34757
- const codec2 = serialize.serviceLookupHistory(blake2b, serviceId, lookupHistory.hash, lookupHistory.length);
34932
+ const codec2 = serialize_serialize.serviceLookupHistory(blake2b, serviceId, lookupHistory.hash, lookupHistory.length);
34758
34933
  yield [StateEntryUpdateAction.Insert, codec2.key, encode(codec2.Codec, lookupHistory.slots)];
34759
34934
  }
34760
34935
  }
@@ -34764,53 +34939,53 @@ function* serializeBasicKeys(spec, update) {
34764
34939
  return [StateEntryUpdateAction.Insert, codec.key, encoder_Encoder.encodeObject(codec.Codec, val, spec)];
34765
34940
  }
34766
34941
  if (update.authPools !== undefined) {
34767
- yield doSerialize(update.authPools, serialize.authPools); // C(1)
34942
+ yield doSerialize(update.authPools, serialize_serialize.authPools); // C(1)
34768
34943
  }
34769
34944
  if (update.authQueues !== undefined) {
34770
- yield doSerialize(update.authQueues, serialize.authQueues); // C(2)
34945
+ yield doSerialize(update.authQueues, serialize_serialize.authQueues); // C(2)
34771
34946
  }
34772
34947
  if (update.recentBlocks !== undefined) {
34773
- yield doSerialize(update.recentBlocks, serialize.recentBlocks); // C(3)
34948
+ yield doSerialize(update.recentBlocks, serialize_serialize.recentBlocks); // C(3)
34774
34949
  }
34775
34950
  const safroleData = getSafroleData(update.nextValidatorData, update.epochRoot, update.sealingKeySeries, update.ticketsAccumulator);
34776
34951
  if (safroleData !== undefined) {
34777
- yield doSerialize(safroleData, serialize.safrole); // C(4)
34952
+ yield doSerialize(safroleData, serialize_serialize.safrole); // C(4)
34778
34953
  }
34779
34954
  if (update.disputesRecords !== undefined) {
34780
- yield doSerialize(update.disputesRecords, serialize.disputesRecords); // C(5)
34955
+ yield doSerialize(update.disputesRecords, serialize_serialize.disputesRecords); // C(5)
34781
34956
  }
34782
34957
  if (update.entropy !== undefined) {
34783
- yield doSerialize(update.entropy, serialize.entropy); // C(6)
34958
+ yield doSerialize(update.entropy, serialize_serialize.entropy); // C(6)
34784
34959
  }
34785
34960
  if (update.designatedValidatorData !== undefined) {
34786
- yield doSerialize(update.designatedValidatorData, serialize.designatedValidators); // C(7)
34961
+ yield doSerialize(update.designatedValidatorData, serialize_serialize.designatedValidators); // C(7)
34787
34962
  }
34788
34963
  if (update.currentValidatorData !== undefined) {
34789
- yield doSerialize(update.currentValidatorData, serialize.currentValidators); // C(8)
34964
+ yield doSerialize(update.currentValidatorData, serialize_serialize.currentValidators); // C(8)
34790
34965
  }
34791
34966
  if (update.previousValidatorData !== undefined) {
34792
- yield doSerialize(update.previousValidatorData, serialize.previousValidators); // C(9)
34967
+ yield doSerialize(update.previousValidatorData, serialize_serialize.previousValidators); // C(9)
34793
34968
  }
34794
34969
  if (update.availabilityAssignment !== undefined) {
34795
- yield doSerialize(update.availabilityAssignment, serialize.availabilityAssignment); // C(10)
34970
+ yield doSerialize(update.availabilityAssignment, serialize_serialize.availabilityAssignment); // C(10)
34796
34971
  }
34797
34972
  if (update.timeslot !== undefined) {
34798
- yield doSerialize(update.timeslot, serialize.timeslot); // C(11)
34973
+ yield doSerialize(update.timeslot, serialize_serialize.timeslot); // C(11)
34799
34974
  }
34800
34975
  if (update.privilegedServices !== undefined) {
34801
- yield doSerialize(update.privilegedServices, serialize.privilegedServices); // C(12)
34976
+ yield doSerialize(update.privilegedServices, serialize_serialize.privilegedServices); // C(12)
34802
34977
  }
34803
34978
  if (update.statistics !== undefined) {
34804
- yield doSerialize(update.statistics, serialize.statistics); // C(13)
34979
+ yield doSerialize(update.statistics, serialize_serialize.statistics); // C(13)
34805
34980
  }
34806
34981
  if (update.accumulationQueue !== undefined) {
34807
- yield doSerialize(update.accumulationQueue, serialize.accumulationQueue); // C(14)
34982
+ yield doSerialize(update.accumulationQueue, serialize_serialize.accumulationQueue); // C(14)
34808
34983
  }
34809
34984
  if (update.recentlyAccumulated !== undefined) {
34810
- yield doSerialize(update.recentlyAccumulated, serialize.recentlyAccumulated); // C(15)
34985
+ yield doSerialize(update.recentlyAccumulated, serialize_serialize.recentlyAccumulated); // C(15)
34811
34986
  }
34812
34987
  if (update.accumulationOutputLog !== undefined) {
34813
- yield doSerialize(update.accumulationOutputLog, serialize.accumulationOutputLog); // C(16)
34988
+ yield doSerialize(update.accumulationOutputLog, serialize_serialize.accumulationOutputLog); // C(16)
34814
34989
  }
34815
34990
  }
34816
34991
  function getSafroleData(nextValidatorData, epochRoot, sealingKeySeries, ticketsAccumulator) {
@@ -34923,41 +35098,41 @@ function convertInMemoryStateToDictionary(spec, blake2b, state) {
34923
35098
  function doSerialize(codec) {
34924
35099
  serialized.set(codec.key, encoder_Encoder.encodeObject(codec.Codec, codec.extract(state), spec));
34925
35100
  }
34926
- doSerialize(serialize.authPools); // C(1)
34927
- doSerialize(serialize.authQueues); // C(2)
34928
- doSerialize(serialize.recentBlocks); // C(3)
34929
- doSerialize(serialize.safrole); // C(4)
34930
- doSerialize(serialize.disputesRecords); // C(5)
34931
- doSerialize(serialize.entropy); // C(6)
34932
- doSerialize(serialize.designatedValidators); // C(7)
34933
- doSerialize(serialize.currentValidators); // C(8)
34934
- doSerialize(serialize.previousValidators); // C(9)
34935
- doSerialize(serialize.availabilityAssignment); // C(10)
34936
- doSerialize(serialize.timeslot); // C(11)
34937
- doSerialize(serialize.privilegedServices); // C(12)
34938
- doSerialize(serialize.statistics); // C(13)
34939
- doSerialize(serialize.accumulationQueue); // C(14)
34940
- doSerialize(serialize.recentlyAccumulated); // C(15)
34941
- doSerialize(serialize.accumulationOutputLog); // C(16)
35101
+ doSerialize(serialize_serialize.authPools); // C(1)
35102
+ doSerialize(serialize_serialize.authQueues); // C(2)
35103
+ doSerialize(serialize_serialize.recentBlocks); // C(3)
35104
+ doSerialize(serialize_serialize.safrole); // C(4)
35105
+ doSerialize(serialize_serialize.disputesRecords); // C(5)
35106
+ doSerialize(serialize_serialize.entropy); // C(6)
35107
+ doSerialize(serialize_serialize.designatedValidators); // C(7)
35108
+ doSerialize(serialize_serialize.currentValidators); // C(8)
35109
+ doSerialize(serialize_serialize.previousValidators); // C(9)
35110
+ doSerialize(serialize_serialize.availabilityAssignment); // C(10)
35111
+ doSerialize(serialize_serialize.timeslot); // C(11)
35112
+ doSerialize(serialize_serialize.privilegedServices); // C(12)
35113
+ doSerialize(serialize_serialize.statistics); // C(13)
35114
+ doSerialize(serialize_serialize.accumulationQueue); // C(14)
35115
+ doSerialize(serialize_serialize.recentlyAccumulated); // C(15)
35116
+ doSerialize(serialize_serialize.accumulationOutputLog); // C(16)
34942
35117
  // services
34943
35118
  for (const [serviceId, service] of state.services.entries()) {
34944
35119
  // data
34945
- const { key, Codec } = serialize.serviceData(serviceId);
35120
+ const { key, Codec } = serialize_serialize.serviceData(serviceId);
34946
35121
  serialized.set(key, encoder_Encoder.encodeObject(Codec, service.getInfo()));
34947
35122
  // preimages
34948
35123
  for (const preimage of service.data.preimages.values()) {
34949
- const { key, Codec } = serialize.servicePreimages(blake2b, serviceId, preimage.hash);
35124
+ const { key, Codec } = serialize_serialize.servicePreimages(blake2b, serviceId, preimage.hash);
34950
35125
  serialized.set(key, encoder_Encoder.encodeObject(Codec, preimage.blob));
34951
35126
  }
34952
35127
  // storage
34953
35128
  for (const storage of service.data.storage.values()) {
34954
- const { key, Codec } = serialize.serviceStorage(blake2b, serviceId, storage.key);
35129
+ const { key, Codec } = serialize_serialize.serviceStorage(blake2b, serviceId, storage.key);
34955
35130
  serialized.set(key, encoder_Encoder.encodeObject(Codec, storage.value));
34956
35131
  }
34957
35132
  // lookup history
34958
35133
  for (const lookupHistoryList of service.data.lookupHistory.values()) {
34959
35134
  for (const lookupHistory of lookupHistoryList) {
34960
- const { key, Codec } = serialize.serviceLookupHistory(blake2b, serviceId, lookupHistory.hash, lookupHistory.length);
35135
+ const { key, Codec } = serialize_serialize.serviceLookupHistory(blake2b, serviceId, lookupHistory.hash, lookupHistory.length);
34961
35136
  serialized.set(key, encoder_Encoder.encodeObject(Codec, lookupHistory.slots.slice()));
34962
35137
  }
34963
35138
  }
@@ -35007,6 +35182,7 @@ function loadState(spec, blake2b, entries) {
35007
35182
 
35008
35183
 
35009
35184
 
35185
+
35010
35186
  ;// CONCATENATED MODULE: ./packages/jam/database/leaf-db.ts
35011
35187
 
35012
35188
 
@@ -35165,7 +35341,7 @@ const codecMap = (value, extractKey, { typicalLength = TYPICAL_DICTIONARY_LENGTH
35165
35341
  const lookupHistoryItemCodec = descriptors_codec.object({
35166
35342
  hash: descriptors_codec.bytes(hash_HASH_SIZE).asOpaque(),
35167
35343
  length: descriptors_codec.u32,
35168
- slots: readonlyArray(descriptors_codec.sequenceVarLen(descriptors_codec.u32.asOpaque())).convert(seeThrough, tryAsLookupHistorySlots),
35344
+ slots: descriptors_readonlyArray(descriptors_codec.sequenceVarLen(descriptors_codec.u32.asOpaque())).convert(seeThrough, tryAsLookupHistorySlots),
35169
35345
  }, "LookupHistoryItem", ({ hash, length, slots }) => new LookupHistoryItem(hash, length, slots));
35170
35346
  const lookupHistoryEntryCodec = descriptors_codec.object({
35171
35347
  key: descriptors_codec.bytes(hash_HASH_SIZE).asOpaque(),
@@ -35208,7 +35384,11 @@ class ServiceWithCodec extends InMemoryService {
35208
35384
  return new ServiceWithCodec(serviceId, data);
35209
35385
  }
35210
35386
  }
35211
- const in_memory_state_codec_inMemoryStateCodec = descriptors_codec.Class(InMemoryState, {
35387
+ const in_memory_state_codec_inMemoryStateCodec = (spec) => codec.Class(class State extends InMemoryState {
35388
+ static create(data) {
35389
+ return InMemoryState.new(spec, data);
35390
+ }
35391
+ }, {
35212
35392
  // alpha
35213
35393
  authPools: serialize.authPools.Codec,
35214
35394
  // phi
@@ -35218,11 +35398,11 @@ const in_memory_state_codec_inMemoryStateCodec = descriptors_codec.Class(InMemor
35218
35398
  // gamma_k
35219
35399
  nextValidatorData: codecPerValidator(ValidatorData.Codec),
35220
35400
  // gamma_z
35221
- epochRoot: descriptors_codec.bytes(BANDERSNATCH_RING_ROOT_BYTES).asOpaque(),
35401
+ epochRoot: codec.bytes(BANDERSNATCH_RING_ROOT_BYTES).asOpaque(),
35222
35402
  // gamma_s
35223
35403
  sealingKeySeries: SafroleSealingKeysData.Codec,
35224
35404
  // gamma_a
35225
- ticketsAccumulator: readonlyArray(descriptors_codec.sequenceVarLen(Ticket.Codec)).convert((x) => x, sized_array_asKnownSize),
35405
+ ticketsAccumulator: readonlyArray(codec.sequenceVarLen(Ticket.Codec)).convert((x) => x, asKnownSize),
35226
35406
  // psi
35227
35407
  disputesRecords: serialize.disputesRecords.Codec,
35228
35408
  // eta
@@ -35248,7 +35428,7 @@ const in_memory_state_codec_inMemoryStateCodec = descriptors_codec.Class(InMemor
35248
35428
  // theta
35249
35429
  accumulationOutputLog: serialize.accumulationOutputLog.Codec,
35250
35430
  // delta
35251
- services: descriptors_codec.dictionary(descriptors_codec.u32.asOpaque(), ServiceWithCodec.Codec, {
35431
+ services: codec.dictionary(codec.u32.asOpaque(), ServiceWithCodec.Codec, {
35252
35432
  sortKeys: (a, b) => a - b,
35253
35433
  }),
35254
35434
  });
@@ -35295,7 +35475,7 @@ class InMemoryStates {
35295
35475
  }
35296
35476
  /** Insert a full state into the database. */
35297
35477
  async insertState(headerHash, state) {
35298
- const encoded = Encoder.encodeObject(inMemoryStateCodec, state, this.spec);
35478
+ const encoded = Encoder.encodeObject(inMemoryStateCodec(this.spec), state, this.spec);
35299
35479
  this.db.set(headerHash, encoded);
35300
35480
  return Result.ok(OK);
35301
35481
  }
@@ -35304,7 +35484,7 @@ class InMemoryStates {
35304
35484
  if (encodedState === undefined) {
35305
35485
  return null;
35306
35486
  }
35307
- return Decoder.decodeObject(inMemoryStateCodec, encodedState, this.spec);
35487
+ return Decoder.decodeObject(inMemoryStateCodec(this.spec), encodedState, this.spec);
35308
35488
  }
35309
35489
  }
35310
35490
 
@@ -35530,14 +35710,14 @@ async function initializeDatabase(spec, blake2b, genesisHeaderHash, rootDb, conf
35530
35710
  const genesisHeader = decoder_Decoder.decodeObject(Header.Codec, config.genesisHeader, spec);
35531
35711
  const genesisExtrinsic = emptyBlock().extrinsic;
35532
35712
  const genesisBlock = Block.create({ header: genesisHeader, extrinsic: genesisExtrinsic });
35533
- const blockView = blockAsView(genesisBlock, spec);
35713
+ const blockView = reencodeAsView(Block.Codec, genesisBlock, spec);
35534
35714
  common_logger.log `🧬 Writing genesis block #${genesisHeader.timeSlotIndex}: ${genesisHeaderHash}`;
35535
35715
  const { genesisStateSerialized, genesisStateRootHash } = loadGenesisState(spec, blake2b, config.genesisState);
35536
35716
  // write to db
35537
35717
  await blocks.insertBlock(new WithHash(genesisHeaderHash, blockView));
35538
35718
  // insert fake blocks for ancestry data
35539
35719
  for (const [hash, slot] of ancestry) {
35540
- await blocks.insertBlock(new WithHash(hash, blockAsView(emptyBlock(slot), spec)));
35720
+ await blocks.insertBlock(new WithHash(hash, reencodeAsView(Block.Codec, emptyBlock(slot), spec)));
35541
35721
  }
35542
35722
  await states.insertState(genesisHeaderHash, genesisStateSerialized);
35543
35723
  await blocks.setPostStateRoot(genesisHeaderHash, genesisStateRootHash);
@@ -35556,9 +35736,6 @@ function loadGenesisState(spec, blake2b, data) {
35556
35736
  genesisStateRootHash,
35557
35737
  };
35558
35738
  }
35559
- function blockAsView(block, spec) {
35560
- return decoder_Decoder.decodeObject(Block.Codec.View, encoder_Encoder.encodeObject(Block.Codec, block, spec), spec);
35561
- }
35562
35739
 
35563
35740
  ;// CONCATENATED MODULE: external "node:path"
35564
35741
  const external_node_path_namespaceObject = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("node:path");
@@ -36748,21 +36925,21 @@ class TransitionHasher {
36748
36925
  */
36749
36926
  extrinsic(extrinsicView) {
36750
36927
  // https://graypaper.fluffylabs.dev/#/cc517d7/0cfb000cfb00?v=0.6.5
36751
- const guarantees = extrinsicView.guarantees
36928
+ const guaranteesCount = numbers_tryAsU32(extrinsicView.guarantees.view().length);
36929
+ const countEncoded = encoder_Encoder.encodeObject(descriptors_codec.varU32, guaranteesCount);
36930
+ const guaranteesBlobs = extrinsicView.guarantees
36752
36931
  .view()
36753
36932
  .map((g) => g.view())
36754
- .map((guarantee) => {
36933
+ .reduce((aggregated, guarantee) => {
36755
36934
  const reportHash = this.blake2b.hashBytes(guarantee.report.encoded()).asOpaque();
36756
- return bytes_BytesBlob.blobFromParts([
36757
- reportHash.raw,
36758
- guarantee.slot.encoded().raw,
36759
- guarantee.credentials.encoded().raw,
36760
- ]);
36761
- });
36762
- const guaranteeBlob = encoder_Encoder.encodeObject(descriptors_codec.sequenceVarLen(dumpCodec), guarantees, this.context);
36935
+ aggregated.push(reportHash.raw);
36936
+ aggregated.push(guarantee.slot.encoded().raw);
36937
+ aggregated.push(guarantee.credentials.encoded().raw);
36938
+ return aggregated;
36939
+ }, [countEncoded.raw]);
36763
36940
  const et = this.blake2b.hashBytes(extrinsicView.tickets.encoded()).asOpaque();
36764
36941
  const ep = this.blake2b.hashBytes(extrinsicView.preimages.encoded()).asOpaque();
36765
- const eg = this.blake2b.hashBytes(guaranteeBlob).asOpaque();
36942
+ const eg = this.blake2b.hashBlobs(guaranteesBlobs).asOpaque();
36766
36943
  const ea = this.blake2b.hashBytes(extrinsicView.assurances.encoded()).asOpaque();
36767
36944
  const ed = this.blake2b.hashBytes(extrinsicView.disputes.encoded()).asOpaque();
36768
36945
  const encoded = bytes_BytesBlob.blobFromParts([et.raw, ep.raw, eg.raw, ea.raw, ed.raw]);
@@ -41378,7 +41555,7 @@ async function getRingCommitmentNoCache(bandersnatch, keys) {
41378
41555
  if (commitmentResult[RESULT_INDEX] === ResultValues.Error) {
41379
41556
  return result_Result.error(null);
41380
41557
  }
41381
- return result_Result.ok(bytes_Bytes.fromBlob(commitmentResult.subarray(1), BANDERSNATCH_RING_ROOT_BYTES).asOpaque());
41558
+ return result_Result.ok(bytes_Bytes.fromBlob(commitmentResult.subarray(1), bandersnatch_BANDERSNATCH_RING_ROOT_BYTES).asOpaque());
41382
41559
  }
41383
41560
  // One byte for result discriminator (`ResultValues`) and the rest is entropy hash.
41384
41561
  const TICKET_RESULT_LENGTH = 1 + hash_HASH_SIZE;
@@ -41532,7 +41709,7 @@ class Safrole {
41532
41709
  * https://graypaper.fluffylabs.dev/#/5f542d7/0ea2000ea200
41533
41710
  */
41534
41711
  if (isOffender) {
41535
- return ValidatorData.create({
41712
+ return validator_data_ValidatorData.create({
41536
41713
  bandersnatch: bytes_Bytes.zero(BANDERSNATCH_KEY_BYTES).asOpaque(),
41537
41714
  ed25519: bytes_Bytes.zero(ED25519_KEY_BYTES).asOpaque(),
41538
41715
  bls: bytes_Bytes.zero(BLS_KEY_BYTES).asOpaque(),
@@ -41610,13 +41787,13 @@ class Safrole {
41610
41787
  if (this.isNextEpoch(timeslot) &&
41611
41788
  m >= this.chainSpec.contestLength &&
41612
41789
  this.state.ticketsAccumulator.length === this.chainSpec.epochLength) {
41613
- return SafroleSealingKeysData.tickets(this.outsideInSequencer(this.state.ticketsAccumulator).tickets);
41790
+ return safrole_data_SafroleSealingKeysData.tickets(this.outsideInSequencer(this.state.ticketsAccumulator).tickets);
41614
41791
  }
41615
41792
  if (this.isSameEpoch(timeslot)) {
41616
41793
  return this.state.sealingKeySeries;
41617
41794
  }
41618
41795
  // TODO [MaSi]: the result of fallback sequencer should be cached
41619
- return SafroleSealingKeysData.keys(this.fallbackKeySequencer(newEntropy, newValidators));
41796
+ return safrole_data_SafroleSealingKeysData.keys(this.fallbackKeySequencer(newEntropy, newValidators));
41620
41797
  }
41621
41798
  /**
41622
41799
  * Returns epoch markers if the epoch is changed and null otherwise
@@ -41866,47 +42043,46 @@ class SafroleSeal {
41866
42043
  }
41867
42044
  async verifySeal(headerView, state) {
41868
42045
  // we use transitioned keys already
41869
- const validators = state.currentValidatorData;
41870
42046
  const validatorIndex = headerView.bandersnatchBlockAuthorIndex.materialize();
41871
- const authorKey = validators[validatorIndex];
41872
- if (authorKey === undefined) {
42047
+ const authorKeys = state.currentValidatorData.at(validatorIndex);
42048
+ if (authorKeys === undefined) {
41873
42049
  return result_Result.error(SafroleSealError.InvalidValidatorIndex);
41874
42050
  }
41875
42051
  const timeSlot = headerView.timeSlotIndex.materialize();
41876
42052
  const sealingKeys = state.sealingKeySeries;
41877
42053
  const entropy = state.currentEntropy;
41878
42054
  if (sealingKeys.kind === SafroleSealingKeysKind.Tickets) {
41879
- return await this.verifySealWithTicket(sealingKeys.tickets, timeSlot, entropy, validators, validatorIndex, headerView);
42055
+ return await this.verifySealWithTicket(sealingKeys.tickets, timeSlot, entropy, authorKeys, headerView);
41880
42056
  }
41881
- return await this.verifySealWithKeys(sealingKeys.keys, authorKey, timeSlot, entropy, validators, validatorIndex, headerView);
42057
+ return await this.verifySealWithKeys(sealingKeys.keys, timeSlot, entropy, authorKeys, headerView);
41882
42058
  }
41883
42059
  /** Regular (non-fallback) mode of Safrole. */
41884
- async verifySealWithTicket(tickets, timeSlot, entropy, validators, validatorIndex, headerView) {
42060
+ async verifySealWithTicket(tickets, timeSlot, entropy, validatorData, headerView) {
41885
42061
  const index = timeSlot % tickets.length;
41886
- const { id, attempt } = tickets[index];
41887
- const payload = bytes_BytesBlob.blobFromParts(JAM_TICKET_SEAL, entropy.raw, new Uint8Array([attempt]));
42062
+ const ticket = tickets.at(index);
42063
+ const payload = bytes_BytesBlob.blobFromParts(JAM_TICKET_SEAL, entropy.raw, new Uint8Array([ticket?.attempt ?? 0]));
41888
42064
  // verify seal correctness
41889
- const authorKey = validators.at(validatorIndex)?.bandersnatch;
42065
+ const authorKey = validatorData.bandersnatch;
41890
42066
  const result = await bandersnatch_vrf.verifySeal(await this.bandersnatch, authorKey ?? BANDERSNATCH_ZERO_KEY, headerView.seal.materialize(), payload, encodeUnsealedHeader(headerView));
41891
42067
  if (result.isError) {
41892
42068
  return result_Result.error(SafroleSealError.IncorrectSeal);
41893
42069
  }
41894
- if (!id.isEqualTo(result.ok)) {
42070
+ if (ticket === undefined || !ticket.id.isEqualTo(result.ok)) {
41895
42071
  return result_Result.error(SafroleSealError.InvalidTicket);
41896
42072
  }
41897
42073
  return result_Result.ok(result.ok);
41898
42074
  }
41899
42075
  /** Fallback mode of Safrole. */
41900
- async verifySealWithKeys(keys, authorKey, timeSlot, entropy, validators, validatorIndex, headerView) {
42076
+ async verifySealWithKeys(keys, timeSlot, entropy, authorKey, headerView) {
41901
42077
  const index = timeSlot % keys.length;
41902
- const sealingKey = keys[index];
41903
- if (!sealingKey.isEqualTo(authorKey.bandersnatch)) {
42078
+ const sealingKey = keys.at(index);
42079
+ const authorBandersnatchKey = authorKey.bandersnatch;
42080
+ if (sealingKey === undefined || !sealingKey.isEqualTo(authorBandersnatchKey)) {
41904
42081
  return result_Result.error(SafroleSealError.InvalidValidator, `Invalid Validator. Expected: ${sealingKey}, got: ${authorKey.bandersnatch}`);
41905
42082
  }
41906
42083
  // verify seal correctness
41907
42084
  const payload = bytes_BytesBlob.blobFromParts(JAM_FALLBACK_SEAL, entropy.raw);
41908
- const blockAuthorKey = validators.at(validatorIndex)?.bandersnatch;
41909
- const result = await bandersnatch_vrf.verifySeal(await this.bandersnatch, blockAuthorKey ?? BANDERSNATCH_ZERO_KEY, headerView.seal.materialize(), payload, encodeUnsealedHeader(headerView));
42085
+ const result = await bandersnatch_vrf.verifySeal(await this.bandersnatch, authorBandersnatchKey, headerView.seal.materialize(), payload, encodeUnsealedHeader(headerView));
41910
42086
  if (result.isError) {
41911
42087
  return result_Result.error(SafroleSealError.IncorrectSeal);
41912
42088
  }
@@ -47822,9 +47998,6 @@ class HostCallMemory {
47822
47998
  }
47823
47999
  return this.memory.loadInto(result, tryAsMemoryIndex(Number(startAddress)));
47824
48000
  }
47825
- getMemory() {
47826
- return this.memory;
47827
- }
47828
48001
  }
47829
48002
 
47830
48003
  ;// CONCATENATED MODULE: ./packages/core/pvm-host-calls/host-call-registers.ts
@@ -48103,7 +48276,7 @@ class Assign {
48103
48276
  // NOTE: Here we know the core index is valid
48104
48277
  const coreIndex = tryAsCoreIndex(Number(maybeCoreIndex));
48105
48278
  const decoder = decoder_Decoder.fromBlob(res);
48106
- const authQueue = decoder.sequenceFixLen(descriptors_codec.bytes(hash_HASH_SIZE), AUTHORIZATION_QUEUE_SIZE);
48279
+ const authQueue = decoder.sequenceFixLen(descriptors_codec.bytes(hash_HASH_SIZE).asOpaque(), AUTHORIZATION_QUEUE_SIZE);
48107
48280
  const fixedSizeAuthQueue = FixedSizeArray.new(authQueue, AUTHORIZATION_QUEUE_SIZE);
48108
48281
  const result = this.partialState.updateAuthorizationQueue(coreIndex, fixedSizeAuthQueue, assigners);
48109
48282
  if (result.isOk) {
@@ -48299,7 +48472,7 @@ class Checkpoint {
48299
48472
 
48300
48473
 
48301
48474
  const designate_IN_OUT_REG = 7;
48302
- const VALIDATOR_DATA_BYTES = tryAsExactBytes(ValidatorData.Codec.sizeHint);
48475
+ const VALIDATOR_DATA_BYTES = tryAsExactBytes(validator_data_ValidatorData.Codec.sizeHint);
48303
48476
  /**
48304
48477
  * Designate a new set of validator keys.
48305
48478
  *
@@ -48328,7 +48501,7 @@ class Designate {
48328
48501
  return PvmExecution.Panic;
48329
48502
  }
48330
48503
  const decoder = decoder_Decoder.fromBlob(res);
48331
- const validatorsData = decoder.sequenceFixLen(ValidatorData.Codec, this.chainSpec.validatorsCount);
48504
+ const validatorsData = decoder.sequenceFixLen(validator_data_ValidatorData.Codec, this.chainSpec.validatorsCount);
48332
48505
  const result = this.partialState.updateValidatorsData(tryAsPerValidator(validatorsData, this.chainSpec));
48333
48506
  if (result.isError) {
48334
48507
  logger_logger.trace `DESIGNATE([${validatorsData[0]}, ${validatorsData[1]}, ...]) <- HUH`;
@@ -49849,7 +50022,7 @@ class Accumulate {
49849
50022
  }
49850
50023
  const result = await this.pvmAccumulateInvocation(slot, serviceId, transfers, operands, gasCost, entropy, updatedState);
49851
50024
  if (result.isError) {
49852
- // https://graypaper.fluffylabs.dev/#/7e6ff6a/2fb6012fb601?v=0.6.7
50025
+ // https://graypaper.fluffylabs.dev/#/ab2cdbd/2fc9032fc903?v=0.7.2
49853
50026
  accumulate_logger.log `Accumulation failed for ${serviceId}.`;
49854
50027
  // even though accumulation failed, we still need to make sure that
49855
50028
  // incoming transfers updated the balance, hence we pass state update here
@@ -49943,10 +50116,12 @@ class Accumulate {
49943
50116
  const { consumedGas, stateUpdate } = await this.accumulateSingleService(serviceId, accumulateData.getTransfers(serviceId), operands, accumulateData.getGasCost(serviceId), slot, entropy, currentState);
49944
50117
  gasCost = tryAsServiceGas(gasCost + consumedGas);
49945
50118
  // https://graypaper.fluffylabs.dev/#/ab2cdbd/193b05193b05?v=0.7.2
49946
- // do not update statistics, if the service only had incoming transfers
49947
- if (operands.length > 0) {
49948
- const serviceStatistics = statistics.get(serviceId) ?? { count: numbers_tryAsU32(0), gasUsed: tryAsServiceGas(0) };
49949
- serviceStatistics.count = numbers_tryAsU32(serviceStatistics.count + accumulateData.getReportsLength(serviceId));
50119
+ const serviceStatistics = statistics.get(serviceId) ?? { count: numbers_tryAsU32(0), gasUsed: tryAsServiceGas(0) };
50120
+ const count = accumulateData.getReportsLength(serviceId);
50121
+ // [0.7.1]: do not update statistics, if the service only had incoming transfers
50122
+ if ((Compatibility.isLessThan(GpVersion.V0_7_2) && count > 0) ||
50123
+ (Compatibility.isGreaterOrEqual(GpVersion.V0_7_2) && (count > 0 || consumedGas > 0n))) {
50124
+ serviceStatistics.count = numbers_tryAsU32(serviceStatistics.count + count);
49950
50125
  serviceStatistics.gasUsed = tryAsServiceGas(serviceStatistics.gasUsed + consumedGas);
49951
50126
  statistics.set(serviceId, serviceStatistics);
49952
50127
  }
@@ -49984,9 +50159,10 @@ class Accumulate {
49984
50159
  const recentlyAccumulated = tryAsPerEpochBlock(newRecentlyAccumulated, this.chainSpec);
49985
50160
  const accumulationQueue = this.state.accumulationQueue.slice();
49986
50161
  accumulationQueue[phaseIndex] = pruneQueue(toAccumulateLater, accumulatedSet);
50162
+ const timeslot = this.state.timeslot;
49987
50163
  for (let i = 1; i < epochLength; i++) {
49988
50164
  const queueIndex = (phaseIndex + epochLength - i) % epochLength;
49989
- if (i < slot - this.state.timeslot) {
50165
+ if (i < slot - timeslot) {
49990
50166
  accumulationQueue[queueIndex] = [];
49991
50167
  }
49992
50168
  else {
@@ -50198,7 +50374,6 @@ class DeferredTransfers {
50198
50374
 
50199
50375
 
50200
50376
 
50201
-
50202
50377
  /**
50203
50378
  * Maintain a list of available authorizations per core.
50204
50379
  *
@@ -50227,11 +50402,12 @@ class Authorization {
50227
50402
  */
50228
50403
  transition(input) {
50229
50404
  const authPoolsUpdate = this.state.authPools.slice();
50405
+ const authQueues = this.state.authQueues;
50230
50406
  // we transition authorizations for each core.
50231
50407
  for (let coreIndex = tryAsCoreIndex(0); coreIndex < this.chainSpec.coresCount; coreIndex++) {
50232
50408
  let pool = authPoolsUpdate[coreIndex].slice();
50233
50409
  // the queue is only read (we should most likely use `ArrayView` here).
50234
- const queue = this.state.authQueues[coreIndex];
50410
+ const queue = authQueues[coreIndex];
50235
50411
  // if there were any used hashes - remove them
50236
50412
  const usedHashes = input.used.get(coreIndex);
50237
50413
  if (usedHashes !== undefined) {
@@ -50405,14 +50581,18 @@ class RecentHistory {
50405
50581
  * https://graypaper.fluffylabs.dev/#/1c979cb/0f55020f5502?v=0.7.1
50406
50582
  */
50407
50583
  partialTransition(input) {
50408
- const recentBlocks = this.state.recentBlocks.blocks.slice();
50584
+ const stateBlocks = this.state.recentBlocks;
50585
+ const recentBlocks = stateBlocks.blocks.slice();
50409
50586
  const lastState = recentBlocks.length > 0 ? recentBlocks[recentBlocks.length - 1] : null;
50410
50587
  // update the posterior root of previous state.
50411
50588
  if (lastState !== null) {
50412
50589
  lastState.postStateRoot = input.priorStateRoot;
50413
50590
  }
50414
50591
  return {
50415
- recentBlocks: this.state.recentBlocks.updateBlocks(recentBlocks), // β_H†
50592
+ recentBlocks: RecentBlocks.create({
50593
+ blocks: sized_array_asKnownSize(recentBlocks),
50594
+ accumulationLog: stateBlocks.accumulationLog,
50595
+ }), // β_H†
50416
50596
  };
50417
50597
  }
50418
50598
  /**
@@ -50424,8 +50604,8 @@ class RecentHistory {
50424
50604
  transition(input) {
50425
50605
  const recentBlocks = input.partial.recentBlocks.blocks.slice();
50426
50606
  // `β′_B`
50427
- const mmr = this.state.recentBlocks.asCurrent().accumulationLog !== null
50428
- ? MerkleMountainRange.fromPeaks(this.hasher, this.state.recentBlocks.asCurrent().accumulationLog)
50607
+ const mmr = this.state.recentBlocks.accumulationLog !== null
50608
+ ? MerkleMountainRange.fromPeaks(this.hasher, this.state.recentBlocks.accumulationLog)
50429
50609
  : MerkleMountainRange.empty(this.hasher);
50430
50610
  // append the accumulation root
50431
50611
  mmr.append(input.accumulateRoot);
@@ -50443,7 +50623,7 @@ class RecentHistory {
50443
50623
  }
50444
50624
  // write back to the state.
50445
50625
  return {
50446
- recentBlocks: RecentBlocksHistory.create(RecentBlocks.create({
50626
+ recentBlocks: RecentBlocks.create(RecentBlocks.create({
50447
50627
  blocks: sized_array_asKnownSize(recentBlocks),
50448
50628
  accumulationLog: peaks,
50449
50629
  })),
@@ -50655,7 +50835,6 @@ function verifyReportsBasic(input) {
50655
50835
 
50656
50836
 
50657
50837
 
50658
-
50659
50838
  const verify_contextual_logger = Logger.new(import.meta.filename, "stf:reports");
50660
50839
  /** https://graypaper.fluffylabs.dev/#/7e6ff6a/15eb0115eb01?v=0.6.7 */
50661
50840
  function verifyContextualValidity(input, state, headerChain, maxLookupAnchorAge) {
@@ -50768,7 +50947,7 @@ function verifyRefineContexts(minLookupSlot, contexts, recentBlocksPartialUpdate
50768
50947
  return result_Result.error(ReportsError.BadStateRoot, `Anchor state root mismatch. Got: ${context.stateRoot}, expected: ${recentBlock.postStateRoot}.`);
50769
50948
  }
50770
50949
  // check beefy root
50771
- const beefyRoot = RecentBlocksHistory.accumulationResult(recentBlock);
50950
+ const beefyRoot = recentBlock.accumulationResult;
50772
50951
  if (!beefyRoot.isEqualTo(context.beefyRoot)) {
50773
50952
  return result_Result.error(ReportsError.BadBeefyMmrRoot, `Invalid BEEFY super peak hash. Got: ${context.beefyRoot}, expected: ${beefyRoot}. Anchor: ${recentBlock.headerHash}`);
50774
50953
  }
@@ -51010,8 +51189,9 @@ function verifyPostSignatureChecks(input, availabilityAssignment, authPools, ser
51010
51189
  * https://graypaper.fluffylabs.dev/#/5f542d7/15eb0015ed00
51011
51190
  */
51012
51191
  const authorizerHash = report.authorizerHash;
51013
- const authorizerPool = authPools[coreIndex];
51014
- if (authorizerPool.find((hash) => hash.isEqualTo(authorizerHash)) === undefined) {
51192
+ const authorizerPool = authPools.get(coreIndex);
51193
+ const pool = authorizerPool?.materialize() ?? [];
51194
+ if (pool.find((hash) => hash.isEqualTo(authorizerHash)) === undefined) {
51015
51195
  return result_Result.error(ReportsError.CoreUnauthorized, `Authorizer hash not found in the pool of core ${coreIndex}: ${authorizerHash}`);
51016
51196
  }
51017
51197
  /**
@@ -51141,7 +51321,8 @@ class Reports {
51141
51321
  return verifyCredentials(input.guarantees, workReportHashes, input.slot, (headerTimeSlot, guaranteeTimeSlot) => this.getGuarantorAssignment(headerTimeSlot, guaranteeTimeSlot, input.newEntropy));
51142
51322
  }
51143
51323
  verifyPostSignatureChecks(input, assurancesAvailAssignment) {
51144
- return verifyPostSignatureChecks(input, assurancesAvailAssignment, this.state.authPools, (id) => this.state.getService(id));
51324
+ const authPoolsView = this.state.view().authPoolsView();
51325
+ return verifyPostSignatureChecks(input, assurancesAvailAssignment, authPoolsView, (id) => this.state.getService(id));
51145
51326
  }
51146
51327
  verifyContextualValidity(input) {
51147
51328
  return verifyContextualValidity(input, this.state, this.headerChain, this.chainSpec.maxLookupAnchorAge);