@typeberry/lib 0.5.0-d7595f1 → 0.5.1-1dda9d6

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.
@@ -1581,7 +1581,7 @@ function addSizeHints(a, b) {
1581
1581
  };
1582
1582
  }
1583
1583
  const DEFAULT_START_LENGTH = 512; // 512B
1584
- const MAX_LENGTH$1 = 10 * 1024 * 1024; // 10MB
1584
+ const MAX_LENGTH$1 = 20 * 1024 * 1024; // 20MB
1585
1585
  /**
1586
1586
  * JAM encoder.
1587
1587
  */
@@ -1934,7 +1934,7 @@ class Encoder {
1934
1934
  if (options.silent) {
1935
1935
  return;
1936
1936
  }
1937
- throw new Error(`The encoded size would reach the maximum of ${MAX_LENGTH$1}.`);
1937
+ throw new Error(`The encoded size (${newLength}) would reach the maximum of ${MAX_LENGTH$1}.`);
1938
1938
  }
1939
1939
  if (newLength > this.destination.length) {
1940
1940
  // we can try to resize the underlying buffer
@@ -2379,6 +2379,48 @@ const pair = (a, b) => {
2379
2379
  };
2380
2380
  /** Custom encoding / decoding logic. */
2381
2381
  const custom = ({ name, sizeHint = { bytes: 0, isExact: false }, }, encode, decode, skip) => Descriptor.new(name, sizeHint, encode, decode, skip);
2382
+ /** Tagged union type encoding. */
2383
+ const union = (name, variants) => {
2384
+ const keys = Object.keys(variants).map(Number);
2385
+ const variantMap = Object.fromEntries(keys.map((key, idx) => [key, idx]));
2386
+ const indexToKey = Object.fromEntries(keys.map((key, idx) => [idx, key]));
2387
+ // Calculate size hint as the minimum variant size + index size
2388
+ const minVariantSize = Math.max(...keys.map((key) => variants[key].sizeHint.bytes));
2389
+ const sizeHint = {
2390
+ bytes: 1 + minVariantSize, // varU32 index + smallest variant
2391
+ isExact: false,
2392
+ };
2393
+ const encode = (e, x) => {
2394
+ const idx = variantMap[x.kind];
2395
+ if (idx === undefined) {
2396
+ throw new Error(`Unknown variant type: ${x.kind} for ${name}`);
2397
+ }
2398
+ e.varU32(tryAsU32(idx));
2399
+ const codec = variants[x.kind];
2400
+ // I'm sorry but I can't figure out a better typing here :)
2401
+ codec.encode(e, x);
2402
+ };
2403
+ const decode = (d) => {
2404
+ const idx = d.varU32();
2405
+ const kind = indexToKey[idx];
2406
+ if (kind === undefined) {
2407
+ throw new Error(`Unknown variant index: ${idx} for ${name}`);
2408
+ }
2409
+ const codec = variants[kind];
2410
+ const value = codec.decode(d);
2411
+ return { kind, ...value };
2412
+ };
2413
+ const skip = (s) => {
2414
+ const idx = s.decoder.varU32();
2415
+ const kind = indexToKey[idx];
2416
+ if (kind === undefined) {
2417
+ throw new Error(`Unknown variant index: ${idx} for ${name}`);
2418
+ }
2419
+ const codec = variants[kind];
2420
+ codec.skip(s);
2421
+ };
2422
+ return Descriptor.new(name, sizeHint, encode, decode, skip);
2423
+ };
2382
2424
  /** Choose a descriptor depending on the encoding/decoding context. */
2383
2425
  const select = ({ name, sizeHint, }, chooser) => {
2384
2426
  const Self = chooser(null);
@@ -2554,24 +2596,59 @@ var descriptors = /*#__PURE__*/Object.freeze({
2554
2596
  u32: u32,
2555
2597
  u64: u64,
2556
2598
  u8: u8,
2599
+ union: union,
2557
2600
  varU32: varU32,
2558
2601
  varU64: varU64
2559
2602
  });
2560
2603
 
2604
+ const codec = descriptors;
2605
+
2561
2606
  var index$x = /*#__PURE__*/Object.freeze({
2562
2607
  __proto__: null,
2608
+ Class: Class,
2563
2609
  Decoder: Decoder,
2564
2610
  Descriptor: Descriptor,
2565
2611
  Encoder: Encoder,
2566
2612
  EndOfDataError: EndOfDataError,
2567
2613
  ObjectView: ObjectView,
2568
2614
  SequenceView: SequenceView,
2615
+ TYPICAL_DICTIONARY_LENGTH: TYPICAL_DICTIONARY_LENGTH,
2569
2616
  ViewField: ViewField,
2570
2617
  addSizeHints: addSizeHints,
2571
- codec: descriptors,
2618
+ bitVecFixLen: bitVecFixLen,
2619
+ bitVecVarLen: bitVecVarLen,
2620
+ blob: blob,
2621
+ bool: bool,
2622
+ bytes: bytes,
2623
+ codec: codec,
2624
+ custom: custom,
2572
2625
  decodeVariableLengthExtraBytes: decodeVariableLengthExtraBytes,
2626
+ dictionary: dictionary,
2627
+ forEachDescriptor: forEachDescriptor,
2628
+ i16: i16,
2629
+ i24: i24,
2630
+ i32: i32,
2631
+ i64: i64,
2632
+ i8: i8,
2633
+ nothing: nothing,
2634
+ object: object,
2635
+ optional: optional,
2636
+ pair: pair,
2637
+ readonlyArray: readonlyArray,
2638
+ select: select,
2639
+ sequenceFixLen: sequenceFixLen,
2640
+ sequenceVarLen: sequenceVarLen,
2641
+ string: string,
2573
2642
  tryAsExactBytes: tryAsExactBytes,
2574
- validateLength: validateLength
2643
+ u16: u16,
2644
+ u24: u24,
2645
+ u32: u32,
2646
+ u64: u64,
2647
+ u8: u8,
2648
+ union: union,
2649
+ validateLength: validateLength,
2650
+ varU32: varU32,
2651
+ varU64: varU64
2575
2652
  });
2576
2653
 
2577
2654
  //#region rolldown:runtime
@@ -5782,7 +5859,7 @@ function codecWithContext(chooser) {
5782
5859
  const defaultContext = fullChainSpec;
5783
5860
  const { name, sizeHint } = chooser(defaultContext);
5784
5861
  const cache = new Map();
5785
- return select({
5862
+ return codec.select({
5786
5863
  name,
5787
5864
  sizeHint: { bytes: sizeHint.bytes, isExact: false },
5788
5865
  }, (context) => {
@@ -5809,9 +5886,9 @@ function codecWithContext(chooser) {
5809
5886
  /** Codec for a known-size array with length validation. */
5810
5887
  const codecKnownSizeArray = (val, options, _id) => {
5811
5888
  if ("fixedLength" in options) {
5812
- return readonlyArray(sequenceFixLen(val, options.fixedLength)).convert(seeThrough, asKnownSize);
5889
+ return codec.readonlyArray(codec.sequenceFixLen(val, options.fixedLength)).convert(seeThrough, asKnownSize);
5813
5890
  }
5814
- return readonlyArray(sequenceVarLen(val, options)).convert(seeThrough, asKnownSize);
5891
+ return codec.readonlyArray(codec.sequenceVarLen(val, options)).convert(seeThrough, asKnownSize);
5815
5892
  };
5816
5893
  /** Codec for a fixed-size array with length validation. */
5817
5894
  const codecFixedSizeArray = (val, len) => {
@@ -5820,7 +5897,7 @@ const codecFixedSizeArray = (val, len) => {
5820
5897
  throw new Error(`[${val.name}] Invalid size of fixed-size array. Got ${actual}, expected: ${len}`);
5821
5898
  }
5822
5899
  };
5823
- return sequenceFixLen(val, len).convert((i) => {
5900
+ return codec.sequenceFixLen(val, len).convert((i) => {
5824
5901
  checkLength(i.length);
5825
5902
  return i;
5826
5903
  }, (o) => {
@@ -5829,7 +5906,7 @@ const codecFixedSizeArray = (val, len) => {
5829
5906
  });
5830
5907
  };
5831
5908
  /** Codec for a hash-dictionary. */
5832
- const codecHashDictionary = (value, extractKey, { typicalLength = TYPICAL_DICTIONARY_LENGTH, compare = (a, b) => extractKey(a).compare(extractKey(b)), } = {}) => {
5909
+ const codecHashDictionary = (value, extractKey, { typicalLength = codec.TYPICAL_DICTIONARY_LENGTH, compare = (a, b) => extractKey(a).compare(extractKey(b)), } = {}) => {
5833
5910
  return Descriptor.new(`HashDictionary<${value.name}>[?]`, {
5834
5911
  bytes: typicalLength * value.sizeHint.bytes,
5835
5912
  isExact: false,
@@ -5883,13 +5960,13 @@ class AvailabilityAssurance extends WithDebug {
5883
5960
  bitfield;
5884
5961
  validatorIndex;
5885
5962
  signature;
5886
- static Codec = Class(AvailabilityAssurance, {
5887
- anchor: bytes(HASH_SIZE).asOpaque(),
5963
+ static Codec = codec.Class(AvailabilityAssurance, {
5964
+ anchor: codec.bytes(HASH_SIZE).asOpaque(),
5888
5965
  bitfield: codecWithContext((context) => {
5889
- return bitVecFixLen(context.coresCount);
5966
+ return codec.bitVecFixLen(context.coresCount);
5890
5967
  }),
5891
- validatorIndex: u16.asOpaque(),
5892
- signature: bytes(ED25519_SIGNATURE_BYTES).asOpaque(),
5968
+ validatorIndex: codec.u16.asOpaque(),
5969
+ signature: codec.bytes(ED25519_SIGNATURE_BYTES).asOpaque(),
5893
5970
  });
5894
5971
  static create({ anchor, bitfield, validatorIndex, signature }) {
5895
5972
  return new AvailabilityAssurance(anchor, bitfield, validatorIndex, signature);
@@ -5974,11 +6051,11 @@ class Fault extends WithDebug {
5974
6051
  wasConsideredValid;
5975
6052
  key;
5976
6053
  signature;
5977
- static Codec = Class(Fault, {
5978
- workReportHash: bytes(HASH_SIZE).asOpaque(),
5979
- wasConsideredValid: bool,
5980
- key: bytes(ED25519_KEY_BYTES).asOpaque(),
5981
- signature: bytes(ED25519_SIGNATURE_BYTES).asOpaque(),
6054
+ static Codec = codec.Class(Fault, {
6055
+ workReportHash: codec.bytes(HASH_SIZE).asOpaque(),
6056
+ wasConsideredValid: codec.bool,
6057
+ key: codec.bytes(ED25519_KEY_BYTES).asOpaque(),
6058
+ signature: codec.bytes(ED25519_SIGNATURE_BYTES).asOpaque(),
5982
6059
  });
5983
6060
  static create({ workReportHash, wasConsideredValid, key, signature }) {
5984
6061
  return new Fault(workReportHash, wasConsideredValid, key, signature);
@@ -6006,10 +6083,10 @@ class Culprit extends WithDebug {
6006
6083
  workReportHash;
6007
6084
  key;
6008
6085
  signature;
6009
- static Codec = Class(Culprit, {
6010
- workReportHash: bytes(HASH_SIZE).asOpaque(),
6011
- key: bytes(ED25519_KEY_BYTES).asOpaque(),
6012
- signature: bytes(ED25519_SIGNATURE_BYTES).asOpaque(),
6086
+ static Codec = codec.Class(Culprit, {
6087
+ workReportHash: codec.bytes(HASH_SIZE).asOpaque(),
6088
+ key: codec.bytes(ED25519_KEY_BYTES).asOpaque(),
6089
+ signature: codec.bytes(ED25519_SIGNATURE_BYTES).asOpaque(),
6013
6090
  });
6014
6091
  static create({ workReportHash, key, signature }) {
6015
6092
  return new Culprit(workReportHash, key, signature);
@@ -6034,10 +6111,10 @@ class Judgement extends WithDebug {
6034
6111
  isWorkReportValid;
6035
6112
  index;
6036
6113
  signature;
6037
- static Codec = Class(Judgement, {
6038
- isWorkReportValid: bool,
6039
- index: u16.asOpaque(),
6040
- signature: bytes(ED25519_SIGNATURE_BYTES).asOpaque(),
6114
+ static Codec = codec.Class(Judgement, {
6115
+ isWorkReportValid: codec.bool,
6116
+ index: codec.u16.asOpaque(),
6117
+ signature: codec.bytes(ED25519_SIGNATURE_BYTES).asOpaque(),
6041
6118
  });
6042
6119
  static create({ isWorkReportValid, index, signature }) {
6043
6120
  return new Judgement(isWorkReportValid, index, signature);
@@ -6066,11 +6143,12 @@ class Verdict extends WithDebug {
6066
6143
  workReportHash;
6067
6144
  votesEpoch;
6068
6145
  votes;
6069
- static Codec = Class(Verdict, {
6070
- workReportHash: bytes(HASH_SIZE).asOpaque(),
6071
- votesEpoch: u32.asOpaque(),
6146
+ static Codec = codec.Class(Verdict, {
6147
+ workReportHash: codec.bytes(HASH_SIZE).asOpaque(),
6148
+ votesEpoch: codec.u32.asOpaque(),
6072
6149
  votes: codecWithContext((context) => {
6073
- return readonlyArray(sequenceFixLen(Judgement.Codec, context.validatorsSuperMajority))
6150
+ return codec
6151
+ .readonlyArray(codec.sequenceFixLen(Judgement.Codec, context.validatorsSuperMajority))
6074
6152
  .convert(seeThrough, asKnownSize);
6075
6153
  }),
6076
6154
  });
@@ -6112,10 +6190,10 @@ class DisputesExtrinsic extends WithDebug {
6112
6190
  verdicts;
6113
6191
  culprits;
6114
6192
  faults;
6115
- static Codec = Class(DisputesExtrinsic, {
6116
- verdicts: sequenceVarLen(Verdict.Codec),
6117
- culprits: sequenceVarLen(Culprit.Codec),
6118
- faults: sequenceVarLen(Fault.Codec),
6193
+ static Codec = codec.Class(DisputesExtrinsic, {
6194
+ verdicts: codec.sequenceVarLen(Verdict.Codec),
6195
+ culprits: codec.sequenceVarLen(Culprit.Codec),
6196
+ faults: codec.sequenceVarLen(Fault.Codec),
6119
6197
  });
6120
6198
  static create({ verdicts, culprits, faults }) {
6121
6199
  return new DisputesExtrinsic(verdicts, culprits, faults);
@@ -6166,9 +6244,9 @@ var disputes = /*#__PURE__*/Object.freeze({
6166
6244
  class WorkPackageInfo extends WithDebug {
6167
6245
  workPackageHash;
6168
6246
  segmentTreeRoot;
6169
- static Codec = Class(WorkPackageInfo, {
6170
- workPackageHash: bytes(HASH_SIZE).asOpaque(),
6171
- segmentTreeRoot: bytes(HASH_SIZE).asOpaque(),
6247
+ static Codec = codec.Class(WorkPackageInfo, {
6248
+ workPackageHash: codec.bytes(HASH_SIZE).asOpaque(),
6249
+ segmentTreeRoot: codec.bytes(HASH_SIZE).asOpaque(),
6172
6250
  });
6173
6251
  constructor(
6174
6252
  /** Hash of the described work package. */
@@ -6196,13 +6274,13 @@ class RefineContext extends WithDebug {
6196
6274
  lookupAnchor;
6197
6275
  lookupAnchorSlot;
6198
6276
  prerequisites;
6199
- static Codec = Class(RefineContext, {
6200
- anchor: bytes(HASH_SIZE).asOpaque(),
6201
- stateRoot: bytes(HASH_SIZE).asOpaque(),
6202
- beefyRoot: bytes(HASH_SIZE).asOpaque(),
6203
- lookupAnchor: bytes(HASH_SIZE).asOpaque(),
6204
- lookupAnchorSlot: u32.asOpaque(),
6205
- prerequisites: sequenceVarLen(bytes(HASH_SIZE).asOpaque()),
6277
+ static Codec = codec.Class(RefineContext, {
6278
+ anchor: codec.bytes(HASH_SIZE).asOpaque(),
6279
+ stateRoot: codec.bytes(HASH_SIZE).asOpaque(),
6280
+ beefyRoot: codec.bytes(HASH_SIZE).asOpaque(),
6281
+ lookupAnchor: codec.bytes(HASH_SIZE).asOpaque(),
6282
+ lookupAnchorSlot: codec.u32.asOpaque(),
6283
+ prerequisites: codec.sequenceVarLen(codec.bytes(HASH_SIZE).asOpaque()),
6206
6284
  });
6207
6285
  static create({ anchor, stateRoot, beefyRoot, lookupAnchor, lookupAnchorSlot, prerequisites, }) {
6208
6286
  return new RefineContext(anchor, stateRoot, beefyRoot, lookupAnchor, lookupAnchorSlot, prerequisites);
@@ -6254,9 +6332,9 @@ const tryAsSegmentIndex = (v) => asOpaqueType(tryAsU16(v));
6254
6332
  class ImportSpec extends WithDebug {
6255
6333
  treeRoot;
6256
6334
  index;
6257
- static Codec = Class(ImportSpec, {
6258
- treeRoot: bytes(HASH_SIZE),
6259
- index: u16.asOpaque(),
6335
+ static Codec = codec.Class(ImportSpec, {
6336
+ treeRoot: codec.bytes(HASH_SIZE),
6337
+ index: codec.u16.asOpaque(),
6260
6338
  });
6261
6339
  static create({ treeRoot, index }) {
6262
6340
  return new ImportSpec(treeRoot, index);
@@ -6278,9 +6356,9 @@ class ImportSpec extends WithDebug {
6278
6356
  class WorkItemExtrinsicSpec extends WithDebug {
6279
6357
  hash;
6280
6358
  len;
6281
- static Codec = Class(WorkItemExtrinsicSpec, {
6282
- hash: bytes(HASH_SIZE).asOpaque(),
6283
- len: u32,
6359
+ static Codec = codec.Class(WorkItemExtrinsicSpec, {
6360
+ hash: codec.bytes(HASH_SIZE).asOpaque(),
6361
+ len: codec.u32,
6284
6362
  });
6285
6363
  static create({ hash, len }) {
6286
6364
  return new WorkItemExtrinsicSpec(hash, len);
@@ -6310,7 +6388,7 @@ function workItemExtrinsicsCodec(workItems) {
6310
6388
  if (sum.overflow) {
6311
6389
  throw new Error("Unable to create a decoder, because the length of extrinsics overflows!");
6312
6390
  }
6313
- return custom({
6391
+ return codec.custom({
6314
6392
  name: "WorkItemExtrinsics",
6315
6393
  sizeHint: { bytes: sum.value, isExact: true },
6316
6394
  }, (e, val) => {
@@ -6340,19 +6418,19 @@ class WorkItem extends WithDebug {
6340
6418
  importSegments;
6341
6419
  extrinsic;
6342
6420
  exportCount;
6343
- static Codec = Class(WorkItem, {
6344
- service: u32.asOpaque(),
6345
- codeHash: bytes(HASH_SIZE).asOpaque(),
6346
- refineGasLimit: u64.asOpaque(),
6347
- accumulateGasLimit: u64.asOpaque(),
6348
- exportCount: u16,
6349
- payload: blob,
6421
+ static Codec = codec.Class(WorkItem, {
6422
+ service: codec.u32.asOpaque(),
6423
+ codeHash: codec.bytes(HASH_SIZE).asOpaque(),
6424
+ refineGasLimit: codec.u64.asOpaque(),
6425
+ accumulateGasLimit: codec.u64.asOpaque(),
6426
+ exportCount: codec.u16,
6427
+ payload: codec.blob,
6350
6428
  importSegments: codecKnownSizeArray(ImportSpec.Codec, {
6351
6429
  minLength: 0,
6352
6430
  maxLength: MAX_NUMBER_OF_SEGMENTS,
6353
6431
  typicalLength: MAX_NUMBER_OF_SEGMENTS,
6354
6432
  }),
6355
- extrinsic: sequenceVarLen(WorkItemExtrinsicSpec.Codec),
6433
+ extrinsic: codec.sequenceVarLen(WorkItemExtrinsicSpec.Codec),
6356
6434
  });
6357
6435
  static create({ service, codeHash, payload, refineGasLimit, accumulateGasLimit, importSegments, extrinsic, exportCount, }) {
6358
6436
  return new WorkItem(service, codeHash, payload, refineGasLimit, accumulateGasLimit, importSegments, extrinsic, exportCount);
@@ -6425,13 +6503,13 @@ class WorkPackage extends WithDebug {
6425
6503
  parametrization;
6426
6504
  context;
6427
6505
  items;
6428
- static Codec = Class(WorkPackage, {
6429
- authCodeHost: u32.asOpaque(),
6430
- authCodeHash: bytes(HASH_SIZE).asOpaque(),
6506
+ static Codec = codec.Class(WorkPackage, {
6507
+ authCodeHost: codec.u32.asOpaque(),
6508
+ authCodeHash: codec.bytes(HASH_SIZE).asOpaque(),
6431
6509
  context: RefineContext.Codec,
6432
- authorization: blob,
6433
- parametrization: blob,
6434
- items: sequenceVarLen(WorkItem.Codec).convert((x) => x, (items) => FixedSizeArray.new(items, tryAsWorkItemsCount(items.length))),
6510
+ authorization: codec.blob,
6511
+ parametrization: codec.blob,
6512
+ items: codec.sequenceVarLen(WorkItem.Codec).convert((x) => x, (items) => FixedSizeArray.new(items, tryAsWorkItemsCount(items.length))),
6435
6513
  });
6436
6514
  static create({ authorization, authCodeHost, authCodeHash, parametrization, context, items, }) {
6437
6515
  return new WorkPackage(authorization, authCodeHost, authCodeHash, parametrization, context, items);
@@ -6494,30 +6572,22 @@ var WorkExecResultKind;
6494
6572
  class WorkExecResult extends WithDebug {
6495
6573
  kind;
6496
6574
  okBlob;
6497
- static Codec = custom({
6498
- name: "WorkExecResult",
6499
- sizeHint: { bytes: 1, isExact: false },
6500
- }, (e, x) => {
6501
- e.varU32(tryAsU32(x.kind));
6502
- if (x.kind === WorkExecResultKind.ok && x.okBlob !== null) {
6503
- e.bytesBlob(x.okBlob);
6504
- }
6505
- }, (d) => {
6506
- const kind = d.varU32();
6507
- if (kind === WorkExecResultKind.ok) {
6508
- const blob = d.bytesBlob();
6509
- return new WorkExecResult(kind, blob);
6510
- }
6511
- if (kind > WorkExecResultKind.codeOversize) {
6512
- throw new Error(`Invalid WorkExecResultKind: ${kind}`);
6513
- }
6514
- return new WorkExecResult(kind);
6515
- }, (s) => {
6516
- const kind = s.decoder.varU32();
6517
- if (kind === WorkExecResultKind.ok) {
6518
- s.bytesBlob();
6519
- }
6520
- });
6575
+ static Codec = codec
6576
+ .union("WorkExecResult", {
6577
+ [WorkExecResultKind.ok]: codec.object({ okBlob: codec.blob }),
6578
+ [WorkExecResultKind.outOfGas]: codec.object({}),
6579
+ [WorkExecResultKind.panic]: codec.object({}),
6580
+ [WorkExecResultKind.incorrectNumberOfExports]: codec.object({}),
6581
+ [WorkExecResultKind.digestTooBig]: codec.object({}),
6582
+ [WorkExecResultKind.badCode]: codec.object({}),
6583
+ [WorkExecResultKind.codeOversize]: codec.object({}),
6584
+ })
6585
+ .convert((x) => {
6586
+ if (x.kind === WorkExecResultKind.ok) {
6587
+ return { kind: WorkExecResultKind.ok, okBlob: x.okBlob ?? BytesBlob.empty() };
6588
+ }
6589
+ return { kind: x.kind };
6590
+ }, (x) => new WorkExecResult(x.kind, x.kind === WorkExecResultKind.ok ? x.okBlob : null));
6521
6591
  constructor(
6522
6592
  /** The execution result tag. */
6523
6593
  kind,
@@ -6541,12 +6611,12 @@ class WorkRefineLoad extends WithDebug {
6541
6611
  extrinsicCount;
6542
6612
  extrinsicSize;
6543
6613
  exportedSegments;
6544
- static Codec = Class(WorkRefineLoad, {
6545
- gasUsed: varU64.asOpaque(),
6546
- importedSegments: varU32,
6547
- extrinsicCount: varU32,
6548
- extrinsicSize: varU32,
6549
- exportedSegments: varU32,
6614
+ static Codec = codec.Class(WorkRefineLoad, {
6615
+ gasUsed: codec.varU64.asOpaque(),
6616
+ importedSegments: codec.varU32,
6617
+ extrinsicCount: codec.varU32,
6618
+ extrinsicSize: codec.varU32,
6619
+ exportedSegments: codec.varU32,
6550
6620
  });
6551
6621
  static create({ gasUsed, importedSegments, extrinsicCount, extrinsicSize, exportedSegments, }) {
6552
6622
  return new WorkRefineLoad(gasUsed, importedSegments, extrinsicCount, extrinsicSize, exportedSegments);
@@ -6582,11 +6652,11 @@ class WorkResult {
6582
6652
  gas;
6583
6653
  result;
6584
6654
  load;
6585
- static Codec = Class(WorkResult, {
6586
- serviceId: u32.asOpaque(),
6587
- codeHash: bytes(HASH_SIZE).asOpaque(),
6588
- payloadHash: bytes(HASH_SIZE),
6589
- gas: u64.asOpaque(),
6655
+ static Codec = codec.Class(WorkResult, {
6656
+ serviceId: codec.u32.asOpaque(),
6657
+ codeHash: codec.bytes(HASH_SIZE).asOpaque(),
6658
+ payloadHash: codec.bytes(HASH_SIZE),
6659
+ gas: codec.u64.asOpaque(),
6590
6660
  result: WorkExecResult.Codec,
6591
6661
  load: WorkRefineLoad.Codec,
6592
6662
  });
@@ -6651,12 +6721,12 @@ class WorkPackageSpec extends WithDebug {
6651
6721
  erasureRoot;
6652
6722
  exportsRoot;
6653
6723
  exportsCount;
6654
- static Codec = Class(WorkPackageSpec, {
6655
- hash: bytes(HASH_SIZE).asOpaque(),
6656
- length: u32,
6657
- erasureRoot: bytes(HASH_SIZE),
6658
- exportsRoot: bytes(HASH_SIZE).asOpaque(),
6659
- exportsCount: u16,
6724
+ static Codec = codec.Class(WorkPackageSpec, {
6725
+ hash: codec.bytes(HASH_SIZE).asOpaque(),
6726
+ length: codec.u32,
6727
+ erasureRoot: codec.bytes(HASH_SIZE),
6728
+ exportsRoot: codec.bytes(HASH_SIZE).asOpaque(),
6729
+ exportsCount: codec.u16,
6660
6730
  });
6661
6731
  static create({ hash, length, erasureRoot, exportsRoot, exportsCount }) {
6662
6732
  return new WorkPackageSpec(hash, length, erasureRoot, exportsRoot, exportsCount);
@@ -6694,20 +6764,20 @@ class WorkReport extends WithDebug {
6694
6764
  segmentRootLookup;
6695
6765
  results;
6696
6766
  authorizationGasUsed;
6697
- static Codec = Class(WorkReport, {
6767
+ static Codec = codec.Class(WorkReport, {
6698
6768
  workPackageSpec: WorkPackageSpec.Codec,
6699
6769
  context: RefineContext.Codec,
6700
- coreIndex: varU32.convert((o) => tryAsU32(o), (i) => {
6770
+ coreIndex: codec.varU32.convert((o) => tryAsU32(o), (i) => {
6701
6771
  if (!isU16(i)) {
6702
6772
  throw new Error(`Core index exceeds U16: ${i}`);
6703
6773
  }
6704
6774
  return tryAsCoreIndex(i);
6705
6775
  }),
6706
- authorizerHash: bytes(HASH_SIZE).asOpaque(),
6707
- authorizationGasUsed: varU64.asOpaque(),
6708
- authorizationOutput: blob,
6709
- segmentRootLookup: readonlyArray(sequenceVarLen(WorkPackageInfo.Codec)),
6710
- results: sequenceVarLen(WorkResult.Codec).convert((x) => x, (items) => FixedSizeArray.new(items, tryAsWorkItemsCount(items.length))),
6776
+ authorizerHash: codec.bytes(HASH_SIZE).asOpaque(),
6777
+ authorizationGasUsed: codec.varU64.asOpaque(),
6778
+ authorizationOutput: codec.blob,
6779
+ segmentRootLookup: codec.readonlyArray(codec.sequenceVarLen(WorkPackageInfo.Codec)),
6780
+ results: codec.sequenceVarLen(WorkResult.Codec).convert((x) => x, (items) => FixedSizeArray.new(items, tryAsWorkItemsCount(items.length))),
6711
6781
  });
6712
6782
  static create({ workPackageSpec, context, coreIndex, authorizerHash, authorizationOutput, segmentRootLookup, results, authorizationGasUsed, }) {
6713
6783
  return new WorkReport(workPackageSpec, context, coreIndex, authorizerHash, authorizationOutput, segmentRootLookup, results, authorizationGasUsed);
@@ -6755,9 +6825,9 @@ const REQUIRED_CREDENTIALS_RANGE = [2, 3];
6755
6825
  class Credential extends WithDebug {
6756
6826
  validatorIndex;
6757
6827
  signature;
6758
- static Codec = Class(Credential, {
6759
- validatorIndex: u16.asOpaque(),
6760
- signature: bytes(ED25519_SIGNATURE_BYTES).asOpaque(),
6828
+ static Codec = codec.Class(Credential, {
6829
+ validatorIndex: codec.u16.asOpaque(),
6830
+ signature: codec.bytes(ED25519_SIGNATURE_BYTES).asOpaque(),
6761
6831
  });
6762
6832
  static create({ validatorIndex, signature }) {
6763
6833
  return new Credential(validatorIndex, signature);
@@ -6775,15 +6845,15 @@ class Credential extends WithDebug {
6775
6845
  /**
6776
6846
  * Tuple of work-report, a credential and it's corresponding timeslot.
6777
6847
  *
6778
- * https://graypaper.fluffylabs.dev/#/579bd12/147102149102
6848
+ * https://graypaper.fluffylabs.dev/#/ab2cdbd/15df00150301?v=0.7.2
6779
6849
  */
6780
6850
  class ReportGuarantee extends WithDebug {
6781
6851
  report;
6782
6852
  slot;
6783
6853
  credentials;
6784
- static Codec = Class(ReportGuarantee, {
6854
+ static Codec = codec.Class(ReportGuarantee, {
6785
6855
  report: WorkReport.Codec,
6786
- slot: u32.asOpaque(),
6856
+ slot: codec.u32.asOpaque(),
6787
6857
  credentials: codecKnownSizeArray(Credential.Codec, {
6788
6858
  minLength: REQUIRED_CREDENTIALS_RANGE[0],
6789
6859
  maxLength: REQUIRED_CREDENTIALS_RANGE[1],
@@ -6803,7 +6873,7 @@ class ReportGuarantee extends WithDebug {
6803
6873
  * validator index and a signature.
6804
6874
  * Credentials must be ordered by their validator index.
6805
6875
  *
6806
- * https://graypaper.fluffylabs.dev/#/579bd12/14b90214bb02
6876
+ * https://graypaper.fluffylabs.dev/#/ab2cdbd/152b01152d01?v=0.7.2
6807
6877
  */
6808
6878
  credentials) {
6809
6879
  super();
@@ -6835,10 +6905,10 @@ function tryAsTicketAttempt(x) {
6835
6905
  class SignedTicket extends WithDebug {
6836
6906
  attempt;
6837
6907
  signature;
6838
- static Codec = Class(SignedTicket, {
6908
+ static Codec = codec.Class(SignedTicket, {
6839
6909
  // TODO [ToDr] we should verify that attempt is either 0|1|2.
6840
- attempt: u8.asOpaque(),
6841
- signature: bytes(BANDERSNATCH_PROOF_BYTES).asOpaque(),
6910
+ attempt: codec.u8.asOpaque(),
6911
+ signature: codec.bytes(BANDERSNATCH_PROOF_BYTES).asOpaque(),
6842
6912
  });
6843
6913
  static create({ attempt, signature }) {
6844
6914
  return new SignedTicket(attempt, signature);
@@ -6857,10 +6927,10 @@ class SignedTicket extends WithDebug {
6857
6927
  class Ticket extends WithDebug {
6858
6928
  id;
6859
6929
  attempt;
6860
- static Codec = Class(Ticket, {
6861
- id: bytes(HASH_SIZE),
6930
+ static Codec = codec.Class(Ticket, {
6931
+ id: codec.bytes(HASH_SIZE),
6862
6932
  // TODO [ToDr] we should verify that attempt is either 0|1|2.
6863
- attempt: u8.asOpaque(),
6933
+ attempt: codec.u8.asOpaque(),
6864
6934
  });
6865
6935
  static create({ id, attempt }) {
6866
6936
  return new Ticket(id, attempt);
@@ -6902,9 +6972,9 @@ var tickets = /*#__PURE__*/Object.freeze({
6902
6972
  class ValidatorKeys extends WithDebug {
6903
6973
  bandersnatch;
6904
6974
  ed25519;
6905
- static Codec = Class(ValidatorKeys, {
6906
- bandersnatch: bytes(BANDERSNATCH_KEY_BYTES).asOpaque(),
6907
- ed25519: bytes(ED25519_KEY_BYTES).asOpaque(),
6975
+ static Codec = codec.Class(ValidatorKeys, {
6976
+ bandersnatch: codec.bytes(BANDERSNATCH_KEY_BYTES).asOpaque(),
6977
+ ed25519: codec.bytes(ED25519_KEY_BYTES).asOpaque(),
6908
6978
  });
6909
6979
  static create({ bandersnatch, ed25519 }) {
6910
6980
  return new ValidatorKeys(bandersnatch, ed25519);
@@ -6921,7 +6991,7 @@ class ValidatorKeys extends WithDebug {
6921
6991
  }
6922
6992
  class TicketsMarker extends WithDebug {
6923
6993
  tickets;
6924
- static Codec = Class(TicketsMarker, {
6994
+ static Codec = codec.Class(TicketsMarker, {
6925
6995
  tickets: codecPerEpochBlock(Ticket.Codec),
6926
6996
  });
6927
6997
  static create({ tickets }) {
@@ -6943,9 +7013,9 @@ class EpochMarker extends WithDebug {
6943
7013
  entropy;
6944
7014
  ticketsEntropy;
6945
7015
  validators;
6946
- static Codec = Class(EpochMarker, {
6947
- entropy: bytes(HASH_SIZE).asOpaque(),
6948
- ticketsEntropy: bytes(HASH_SIZE).asOpaque(),
7016
+ static Codec = codec.Class(EpochMarker, {
7017
+ entropy: codec.bytes(HASH_SIZE).asOpaque(),
7018
+ ticketsEntropy: codec.bytes(HASH_SIZE).asOpaque(),
6949
7019
  validators: codecPerValidator(ValidatorKeys.Codec),
6950
7020
  });
6951
7021
  static create({ entropy, ticketsEntropy, validators }) {
@@ -6982,17 +7052,17 @@ const encodeUnsealedHeader = (view) => {
6982
7052
  * https://graypaper.fluffylabs.dev/#/ab2cdbd/0c66000c7200?v=0.7.2
6983
7053
  */
6984
7054
  class Header extends WithDebug {
6985
- static Codec = Class(Header, {
6986
- parentHeaderHash: bytes(HASH_SIZE).asOpaque(),
6987
- priorStateRoot: bytes(HASH_SIZE).asOpaque(),
6988
- extrinsicHash: bytes(HASH_SIZE).asOpaque(),
6989
- timeSlotIndex: u32.asOpaque(),
6990
- epochMarker: optional(EpochMarker.Codec),
6991
- ticketsMarker: optional(TicketsMarker.Codec),
6992
- bandersnatchBlockAuthorIndex: u16.asOpaque(),
6993
- entropySource: bytes(BANDERSNATCH_VRF_SIGNATURE_BYTES).asOpaque(),
6994
- offendersMarker: sequenceVarLen(bytes(ED25519_KEY_BYTES).asOpaque()),
6995
- seal: bytes(BANDERSNATCH_VRF_SIGNATURE_BYTES).asOpaque(),
7055
+ static Codec = codec.Class(Header, {
7056
+ parentHeaderHash: codec.bytes(HASH_SIZE).asOpaque(),
7057
+ priorStateRoot: codec.bytes(HASH_SIZE).asOpaque(),
7058
+ extrinsicHash: codec.bytes(HASH_SIZE).asOpaque(),
7059
+ timeSlotIndex: codec.u32.asOpaque(),
7060
+ epochMarker: codec.optional(EpochMarker.Codec),
7061
+ ticketsMarker: codec.optional(TicketsMarker.Codec),
7062
+ bandersnatchBlockAuthorIndex: codec.u16.asOpaque(),
7063
+ entropySource: codec.bytes(BANDERSNATCH_VRF_SIGNATURE_BYTES).asOpaque(),
7064
+ offendersMarker: codec.sequenceVarLen(codec.bytes(ED25519_KEY_BYTES).asOpaque()),
7065
+ seal: codec.bytes(BANDERSNATCH_VRF_SIGNATURE_BYTES).asOpaque(),
6996
7066
  });
6997
7067
  static create(h) {
6998
7068
  return Object.assign(Header.empty(), h);
@@ -7047,8 +7117,8 @@ class Header extends WithDebug {
7047
7117
  * `DescriptorRecord` or `CodecRecord` for some reason.
7048
7118
  */
7049
7119
  class HeaderViewWithHash extends WithHash {
7050
- static Codec = Class(HeaderViewWithHash, {
7051
- hash: bytes(HASH_SIZE).asOpaque(),
7120
+ static Codec = codec.Class(HeaderViewWithHash, {
7121
+ hash: codec.bytes(HASH_SIZE).asOpaque(),
7052
7122
  data: Header.Codec.View,
7053
7123
  });
7054
7124
  static create({ hash, data }) {
@@ -7066,9 +7136,9 @@ const headerViewWithHashCodec = HeaderViewWithHash.Codec;
7066
7136
  class Preimage extends WithDebug {
7067
7137
  requester;
7068
7138
  blob;
7069
- static Codec = Class(Preimage, {
7070
- requester: u32.asOpaque(),
7071
- blob: blob,
7139
+ static Codec = codec.Class(Preimage, {
7140
+ requester: codec.u32.asOpaque(),
7141
+ blob: codec.blob,
7072
7142
  });
7073
7143
  static create({ requester, blob }) {
7074
7144
  return new Preimage(requester, blob);
@@ -7083,7 +7153,7 @@ class Preimage extends WithDebug {
7083
7153
  this.blob = blob;
7084
7154
  }
7085
7155
  }
7086
- const preimagesExtrinsicCodec = sequenceVarLen(Preimage.Codec);
7156
+ const preimagesExtrinsicCodec = codec.sequenceVarLen(Preimage.Codec);
7087
7157
 
7088
7158
  var preimage = /*#__PURE__*/Object.freeze({
7089
7159
  __proto__: null,
@@ -7104,7 +7174,7 @@ class Extrinsic extends WithDebug {
7104
7174
  guarantees;
7105
7175
  assurances;
7106
7176
  disputes;
7107
- static Codec = Class(Extrinsic, {
7177
+ static Codec = codec.Class(Extrinsic, {
7108
7178
  tickets: ticketsExtrinsicCodec,
7109
7179
  preimages: preimagesExtrinsicCodec,
7110
7180
  guarantees: guaranteesExtrinsicCodec,
@@ -7157,7 +7227,7 @@ class Extrinsic extends WithDebug {
7157
7227
  class Block extends WithDebug {
7158
7228
  header;
7159
7229
  extrinsic;
7160
- static Codec = Class(Block, {
7230
+ static Codec = codec.Class(Block, {
7161
7231
  header: Header.Codec,
7162
7232
  extrinsic: Extrinsic.Codec,
7163
7233
  });
@@ -7578,8 +7648,9 @@ const workExecResultFromJson = json.object({
7578
7648
  panic: json.optional(json.fromAny(() => null)),
7579
7649
  bad_code: json.optional(json.fromAny(() => null)),
7580
7650
  code_oversize: json.optional(json.fromAny(() => null)),
7651
+ output_oversize: json.optional(json.fromAny(() => null)),
7581
7652
  }, (val) => {
7582
- const { ok, out_of_gas, panic, bad_code, code_oversize } = val;
7653
+ const { ok, out_of_gas, panic, bad_code, code_oversize, output_oversize } = val;
7583
7654
  if (ok !== undefined) {
7584
7655
  return new WorkExecResult(tryAsU32(WorkExecResultKind.ok), ok);
7585
7656
  }
@@ -7595,6 +7666,9 @@ const workExecResultFromJson = json.object({
7595
7666
  if (code_oversize === null) {
7596
7667
  return new WorkExecResult(tryAsU32(WorkExecResultKind.codeOversize));
7597
7668
  }
7669
+ if (output_oversize === null) {
7670
+ return new WorkExecResult(tryAsU32(WorkExecResultKind.digestTooBig));
7671
+ }
7598
7672
  throw new Error("Invalid WorkExecResult");
7599
7673
  });
7600
7674
  const workRefineLoadFromJson = json.object({
@@ -7859,14 +7933,14 @@ var chain_spec$1 = {
7859
7933
  ff000000000000000000000000000000000000000000000000000000000000: "00d1b097b4410b3a63446d7c57d093972a9744fcd2d74f4a5e2ec163610e6d6327ffffffffffffffff0a000000000000000a000000000000003418020000000000ffffffffffffffff04000000000000000000000000000000"
7860
7934
  }
7861
7935
  };
7862
- var database_base_path$1 = "./database";
7936
+ var database_base_path = "./database";
7863
7937
  var defaultConfig = {
7864
7938
  $schema: $schema$1,
7865
7939
  version: version$2,
7866
7940
  flavor: flavor$1,
7867
7941
  authorship: authorship$1,
7868
7942
  chain_spec: chain_spec$1,
7869
- database_base_path: database_base_path$1
7943
+ database_base_path: database_base_path
7870
7944
  };
7871
7945
 
7872
7946
  var $schema = "https://fluffylabs.dev/typeberry/schemas/config-v1.schema.json";
@@ -7904,14 +7978,12 @@ var chain_spec = {
7904
7978
  ff000000000000000000000000000000000000000000000000000000000000: "00d1b097b4410b3a63446d7c57d093972a9744fcd2d74f4a5e2ec163610e6d6327ffffffffffffffff0a000000000000000a000000000000003418020000000000ffffffffffffffff04000000000000000000000000000000"
7905
7979
  }
7906
7980
  };
7907
- var database_base_path = "./database";
7908
7981
  var devConfig = {
7909
7982
  $schema: $schema,
7910
7983
  version: version$1,
7911
7984
  flavor: flavor,
7912
7985
  authorship: authorship,
7913
- chain_spec: chain_spec,
7914
- database_base_path: database_base_path
7986
+ chain_spec: chain_spec
7915
7987
  };
7916
7988
 
7917
7989
  const configs = {
@@ -8653,9 +8725,9 @@ function legacyServiceNested(serviceId, hash) {
8653
8725
  class AccumulationOutput {
8654
8726
  serviceId;
8655
8727
  output;
8656
- static Codec = Class(AccumulationOutput, {
8657
- serviceId: u32.asOpaque(),
8658
- output: bytes(HASH_SIZE),
8728
+ static Codec = codec.Class(AccumulationOutput, {
8729
+ serviceId: codec.u32.asOpaque(),
8730
+ output: codec.bytes(HASH_SIZE),
8659
8731
  });
8660
8732
  static create(a) {
8661
8733
  return new AccumulationOutput(a.serviceId, a.output);
@@ -8704,8 +8776,6 @@ const W_B = Compatibility.isGreaterOrEqual(GpVersion.V0_7_2) ? 13_791_360 : 13_7
8704
8776
  const W_C = 4_000_000;
8705
8777
  /** `W_M`: The maximum number of imports in a work-package. */
8706
8778
  const W_M = 3_072;
8707
- /** `W_R`: The maximum total size of all output blobs in a work-report, in octets. */
8708
- const W_R = 49_152;
8709
8779
  /** `W_T`: The size of a transfer memo in octets. */
8710
8780
  const W_T = 128;
8711
8781
  /** `W_M`: The maximum number of exports in a work-package. */
@@ -8733,9 +8803,9 @@ const MAX_REPORT_DEPENDENCIES = 8;
8733
8803
  class NotYetAccumulatedReport extends WithDebug {
8734
8804
  report;
8735
8805
  dependencies;
8736
- static Codec = Class(NotYetAccumulatedReport, {
8806
+ static Codec = codec.Class(NotYetAccumulatedReport, {
8737
8807
  report: WorkReport.Codec,
8738
- dependencies: codecKnownSizeArray(bytes(HASH_SIZE).asOpaque(), {
8808
+ dependencies: codecKnownSizeArray(codec.bytes(HASH_SIZE).asOpaque(), {
8739
8809
  typicalLength: MAX_REPORT_DEPENDENCIES / 2,
8740
8810
  maxLength: MAX_REPORT_DEPENDENCIES,
8741
8811
  minLength: 0,
@@ -8762,7 +8832,7 @@ class NotYetAccumulatedReport extends WithDebug {
8762
8832
  this.dependencies = dependencies;
8763
8833
  }
8764
8834
  }
8765
- const accumulationQueueCodec = codecPerEpochBlock(readonlyArray(sequenceVarLen(NotYetAccumulatedReport.Codec)));
8835
+ const accumulationQueueCodec = codecPerEpochBlock(codec.readonlyArray(codec.sequenceVarLen(NotYetAccumulatedReport.Codec)));
8766
8836
 
8767
8837
  /** Check if given array has correct length before casting to the opaque type. */
8768
8838
  function tryAsPerCore(array, spec) {
@@ -8787,9 +8857,9 @@ const codecPerCore = (val) => codecWithContext((context) => {
8787
8857
  class AvailabilityAssignment extends WithDebug {
8788
8858
  workReport;
8789
8859
  timeout;
8790
- static Codec = Class(AvailabilityAssignment, {
8860
+ static Codec = codec.Class(AvailabilityAssignment, {
8791
8861
  workReport: WorkReport.Codec,
8792
- timeout: u32.asOpaque(),
8862
+ timeout: codec.u32.asOpaque(),
8793
8863
  });
8794
8864
  static create({ workReport, timeout }) {
8795
8865
  return new AvailabilityAssignment(workReport, timeout);
@@ -8804,20 +8874,20 @@ class AvailabilityAssignment extends WithDebug {
8804
8874
  this.timeout = timeout;
8805
8875
  }
8806
8876
  }
8807
- const availabilityAssignmentsCodec = codecPerCore(optional(AvailabilityAssignment.Codec));
8877
+ const availabilityAssignmentsCodec = codecPerCore(codec.optional(AvailabilityAssignment.Codec));
8808
8878
 
8809
8879
  /** `O`: Maximal authorization pool size. */
8810
8880
  const MAX_AUTH_POOL_SIZE = O;
8811
8881
  /** `Q`: Size of the authorization queue. */
8812
8882
  const AUTHORIZATION_QUEUE_SIZE = Q;
8813
- const authPoolsCodec = codecPerCore(codecKnownSizeArray(bytes(HASH_SIZE).asOpaque(), {
8883
+ const authPoolsCodec = codecPerCore(codecKnownSizeArray(codec.bytes(HASH_SIZE).asOpaque(), {
8814
8884
  minLength: 0,
8815
8885
  maxLength: MAX_AUTH_POOL_SIZE,
8816
8886
  typicalLength: MAX_AUTH_POOL_SIZE,
8817
8887
  }));
8818
- const authQueuesCodec = codecPerCore(codecFixedSizeArray(bytes(HASH_SIZE).asOpaque(), AUTHORIZATION_QUEUE_SIZE));
8888
+ const authQueuesCodec = codecPerCore(codecFixedSizeArray(codec.bytes(HASH_SIZE).asOpaque(), AUTHORIZATION_QUEUE_SIZE));
8819
8889
 
8820
- const sortedSetCodec = () => readonlyArray(sequenceVarLen(bytes(HASH_SIZE))).convert((input) => input.array, (output) => {
8890
+ const sortedSetCodec = () => codec.readonlyArray(codec.sequenceVarLen(codec.bytes(HASH_SIZE))).convert((input) => input.array, (output) => {
8821
8891
  const typed = output.map((x) => x.asOpaque());
8822
8892
  return SortedSet.fromSortedArray(hashComparator, typed);
8823
8893
  });
@@ -8832,7 +8902,7 @@ class DisputesRecords {
8832
8902
  badSet;
8833
8903
  wonkySet;
8834
8904
  punishSet;
8835
- static Codec = Class(DisputesRecords, {
8905
+ static Codec = codec.Class(DisputesRecords, {
8836
8906
  goodSet: workReportsSortedSetCodec,
8837
8907
  badSet: workReportsSortedSetCodec,
8838
8908
  wonkySet: workReportsSortedSetCodec,
@@ -8897,10 +8967,10 @@ class BlockState extends WithDebug {
8897
8967
  accumulationResult;
8898
8968
  postStateRoot;
8899
8969
  reported;
8900
- static Codec = Class(BlockState, {
8901
- headerHash: bytes(HASH_SIZE).asOpaque(),
8902
- accumulationResult: bytes(HASH_SIZE),
8903
- postStateRoot: bytes(HASH_SIZE).asOpaque(),
8970
+ static Codec = codec.Class(BlockState, {
8971
+ headerHash: codec.bytes(HASH_SIZE).asOpaque(),
8972
+ accumulationResult: codec.bytes(HASH_SIZE),
8973
+ postStateRoot: codec.bytes(HASH_SIZE).asOpaque(),
8904
8974
  reported: codecHashDictionary(WorkPackageInfo.Codec, (x) => x.workPackageHash),
8905
8975
  });
8906
8976
  static create({ headerHash, accumulationResult, postStateRoot, reported }) {
@@ -8930,14 +9000,14 @@ class BlockState extends WithDebug {
8930
9000
  class RecentBlocks extends WithDebug {
8931
9001
  blocks;
8932
9002
  accumulationLog;
8933
- static Codec = Class(RecentBlocks, {
9003
+ static Codec = codec.Class(RecentBlocks, {
8934
9004
  blocks: codecKnownSizeArray(BlockState.Codec, {
8935
9005
  minLength: 0,
8936
9006
  maxLength: MAX_RECENT_HISTORY,
8937
9007
  typicalLength: MAX_RECENT_HISTORY,
8938
9008
  }),
8939
- accumulationLog: object({
8940
- peaks: readonlyArray(sequenceVarLen(optional(bytes(HASH_SIZE)))),
9009
+ accumulationLog: codec.object({
9010
+ peaks: codec.readonlyArray(codec.sequenceVarLen(codec.optional(codec.bytes(HASH_SIZE)))),
8941
9011
  }),
8942
9012
  });
8943
9013
  static empty() {
@@ -8965,7 +9035,7 @@ class RecentBlocks extends WithDebug {
8965
9035
  }
8966
9036
  }
8967
9037
 
8968
- const recentlyAccumulatedCodec = codecPerEpochBlock(sequenceVarLen(bytes(HASH_SIZE).asOpaque()).convert((x) => Array.from(x), (x) => HashSet.from(x)));
9038
+ const recentlyAccumulatedCodec = codecPerEpochBlock(codec.sequenceVarLen(codec.bytes(HASH_SIZE).asOpaque()).convert((x) => Array.from(x), (x) => HashSet.from(x)));
8969
9039
 
8970
9040
  /**
8971
9041
  * Fixed size of validator metadata.
@@ -8983,11 +9053,11 @@ class ValidatorData extends WithDebug {
8983
9053
  ed25519;
8984
9054
  bls;
8985
9055
  metadata;
8986
- static Codec = Class(ValidatorData, {
8987
- bandersnatch: bytes(BANDERSNATCH_KEY_BYTES).asOpaque(),
8988
- ed25519: bytes(ED25519_KEY_BYTES).asOpaque(),
8989
- bls: bytes(BLS_KEY_BYTES).asOpaque(),
8990
- metadata: bytes(VALIDATOR_META_BYTES),
9056
+ static Codec = codec.Class(ValidatorData, {
9057
+ bandersnatch: codec.bytes(BANDERSNATCH_KEY_BYTES).asOpaque(),
9058
+ ed25519: codec.bytes(ED25519_KEY_BYTES).asOpaque(),
9059
+ bls: codec.bytes(BLS_KEY_BYTES).asOpaque(),
9060
+ metadata: codec.bytes(VALIDATOR_META_BYTES),
8991
9061
  });
8992
9062
  static create({ ed25519, bandersnatch, bls, metadata }) {
8993
9063
  return new ValidatorData(bandersnatch, ed25519, bls, metadata);
@@ -9015,46 +9085,26 @@ var SafroleSealingKeysKind;
9015
9085
  SafroleSealingKeysKind[SafroleSealingKeysKind["Tickets"] = 0] = "Tickets";
9016
9086
  SafroleSealingKeysKind[SafroleSealingKeysKind["Keys"] = 1] = "Keys";
9017
9087
  })(SafroleSealingKeysKind || (SafroleSealingKeysKind = {}));
9018
- const codecBandersnatchKey = bytes(BANDERSNATCH_KEY_BYTES).asOpaque();
9088
+ const codecBandersnatchKey = codec.bytes(BANDERSNATCH_KEY_BYTES).asOpaque();
9019
9089
  class SafroleSealingKeysData extends WithDebug {
9020
9090
  kind;
9021
9091
  keys;
9022
9092
  tickets;
9023
9093
  static Codec = codecWithContext((context) => {
9024
- return custom({
9025
- name: "SafroleSealingKeys",
9026
- sizeHint: { bytes: 1 + HASH_SIZE * context.epochLength, isExact: false },
9027
- }, (e, x) => {
9028
- e.varU32(tryAsU32(x.kind));
9094
+ const keysCodec = codec
9095
+ .sequenceFixLen(codecBandersnatchKey, context.epochLength)
9096
+ .convert((keys) => Array.from(keys), (keys) => tryAsPerEpochBlock(keys, context));
9097
+ const ticketsCodec = codec.sequenceFixLen(Ticket.Codec, context.epochLength).convert((tickets) => Array.from(tickets), (tickets) => tryAsPerEpochBlock(tickets, context));
9098
+ return codec
9099
+ .union("SafroleSealingKeys", {
9100
+ [SafroleSealingKeysKind.Keys]: codec.object({ keys: keysCodec }),
9101
+ [SafroleSealingKeysKind.Tickets]: codec.object({ tickets: ticketsCodec }),
9102
+ })
9103
+ .convert((x) => x, (x) => {
9029
9104
  if (x.kind === SafroleSealingKeysKind.Keys) {
9030
- e.sequenceFixLen(codecBandersnatchKey, x.keys);
9105
+ return SafroleSealingKeysData.keys(x.keys);
9031
9106
  }
9032
- else {
9033
- e.sequenceFixLen(Ticket.Codec, x.tickets);
9034
- }
9035
- }, (d) => {
9036
- const epochLength = context.epochLength;
9037
- const kind = d.varU32();
9038
- if (kind === SafroleSealingKeysKind.Keys) {
9039
- const keys = d.sequenceFixLen(codecBandersnatchKey, epochLength);
9040
- return SafroleSealingKeysData.keys(tryAsPerEpochBlock(keys, context));
9041
- }
9042
- if (kind === SafroleSealingKeysKind.Tickets) {
9043
- const tickets = d.sequenceFixLen(Ticket.Codec, epochLength);
9044
- return SafroleSealingKeysData.tickets(tryAsPerEpochBlock(tickets, context));
9045
- }
9046
- throw new Error(`Unexpected safrole sealing keys kind: ${kind}`);
9047
- }, (s) => {
9048
- const kind = s.decoder.varU32();
9049
- if (kind === SafroleSealingKeysKind.Keys) {
9050
- s.sequenceFixLen(codecBandersnatchKey, context.epochLength);
9051
- return;
9052
- }
9053
- if (kind === SafroleSealingKeysKind.Tickets) {
9054
- s.sequenceFixLen(Ticket.Codec, context.epochLength);
9055
- return;
9056
- }
9057
- throw new Error(`Unexpected safrole sealing keys kind: ${kind}`);
9107
+ return SafroleSealingKeysData.tickets(x.tickets);
9058
9108
  });
9059
9109
  });
9060
9110
  static keys(keys) {
@@ -9075,11 +9125,11 @@ class SafroleData {
9075
9125
  epochRoot;
9076
9126
  sealingKeySeries;
9077
9127
  ticketsAccumulator;
9078
- static Codec = Class(SafroleData, {
9128
+ static Codec = codec.Class(SafroleData, {
9079
9129
  nextValidatorData: codecPerValidator(ValidatorData.Codec),
9080
- epochRoot: bytes(BANDERSNATCH_RING_ROOT_BYTES).asOpaque(),
9130
+ epochRoot: codec.bytes(BANDERSNATCH_RING_ROOT_BYTES).asOpaque(),
9081
9131
  sealingKeySeries: SafroleSealingKeysData.Codec,
9082
- ticketsAccumulator: readonlyArray(sequenceVarLen(Ticket.Codec)).convert(seeThrough, asKnownSize),
9132
+ ticketsAccumulator: codec.readonlyArray(codec.sequenceVarLen(Ticket.Codec)).convert(seeThrough, asKnownSize),
9083
9133
  });
9084
9134
  static create({ nextValidatorData, epochRoot, sealingKeySeries, ticketsAccumulator }) {
9085
9135
  return new SafroleData(nextValidatorData, epochRoot, sealingKeySeries, ticketsAccumulator);
@@ -9157,17 +9207,17 @@ class ServiceAccountInfo extends WithDebug {
9157
9207
  created;
9158
9208
  lastAccumulation;
9159
9209
  parentService;
9160
- static Codec = Class(ServiceAccountInfo, {
9161
- codeHash: bytes(HASH_SIZE).asOpaque(),
9162
- balance: u64,
9163
- accumulateMinGas: u64.convert((x) => x, tryAsServiceGas),
9164
- onTransferMinGas: u64.convert((x) => x, tryAsServiceGas),
9165
- storageUtilisationBytes: u64,
9166
- gratisStorage: u64,
9167
- storageUtilisationCount: u32,
9168
- created: u32.convert((x) => x, tryAsTimeSlot),
9169
- lastAccumulation: u32.convert((x) => x, tryAsTimeSlot),
9170
- parentService: u32.convert((x) => x, tryAsServiceId),
9210
+ static Codec = codec.Class(ServiceAccountInfo, {
9211
+ codeHash: codec.bytes(HASH_SIZE).asOpaque(),
9212
+ balance: codec.u64,
9213
+ accumulateMinGas: codec.u64.convert((x) => x, tryAsServiceGas),
9214
+ onTransferMinGas: codec.u64.convert((x) => x, tryAsServiceGas),
9215
+ storageUtilisationBytes: codec.u64,
9216
+ gratisStorage: codec.u64,
9217
+ storageUtilisationCount: codec.u32,
9218
+ created: codec.u32.convert((x) => x, tryAsTimeSlot),
9219
+ lastAccumulation: codec.u32.convert((x) => x, tryAsTimeSlot),
9220
+ parentService: codec.u32.convert((x) => x, tryAsServiceId),
9171
9221
  });
9172
9222
  static create(a) {
9173
9223
  return new ServiceAccountInfo(a.codeHash, a.balance, a.accumulateMinGas, a.onTransferMinGas, a.storageUtilisationBytes, a.gratisStorage, a.storageUtilisationCount, a.created, a.lastAccumulation, a.parentService);
@@ -9223,9 +9273,9 @@ class ServiceAccountInfo extends WithDebug {
9223
9273
  class PreimageItem extends WithDebug {
9224
9274
  hash;
9225
9275
  blob;
9226
- static Codec = Class(PreimageItem, {
9227
- hash: bytes(HASH_SIZE).asOpaque(),
9228
- blob: blob,
9276
+ static Codec = codec.Class(PreimageItem, {
9277
+ hash: codec.bytes(HASH_SIZE).asOpaque(),
9278
+ blob: codec.blob,
9229
9279
  });
9230
9280
  static create({ hash, blob }) {
9231
9281
  return new PreimageItem(hash, blob);
@@ -9239,9 +9289,9 @@ class PreimageItem extends WithDebug {
9239
9289
  class StorageItem extends WithDebug {
9240
9290
  key;
9241
9291
  value;
9242
- static Codec = Class(StorageItem, {
9243
- key: blob.convert((i) => i, (o) => asOpaqueType(o)),
9244
- value: blob,
9292
+ static Codec = codec.Class(StorageItem, {
9293
+ key: codec.blob.convert((i) => i, (o) => asOpaqueType(o)),
9294
+ value: codec.blob,
9245
9295
  });
9246
9296
  static create({ key, value }) {
9247
9297
  return new StorageItem(key, value);
@@ -9295,13 +9345,13 @@ class ValidatorStatistics {
9295
9345
  preImagesSize;
9296
9346
  guarantees;
9297
9347
  assurances;
9298
- static Codec = Class(ValidatorStatistics, {
9299
- blocks: u32,
9300
- tickets: u32,
9301
- preImages: u32,
9302
- preImagesSize: u32,
9303
- guarantees: u32,
9304
- assurances: u32,
9348
+ static Codec = codec.Class(ValidatorStatistics, {
9349
+ blocks: codec.u32,
9350
+ tickets: codec.u32,
9351
+ preImages: codec.u32,
9352
+ preImagesSize: codec.u32,
9353
+ guarantees: codec.u32,
9354
+ assurances: codec.u32,
9305
9355
  });
9306
9356
  static create({ blocks, tickets, preImages, preImagesSize, guarantees, assurances, }) {
9307
9357
  return new ValidatorStatistics(blocks, tickets, preImages, preImagesSize, guarantees, assurances);
@@ -9331,9 +9381,9 @@ class ValidatorStatistics {
9331
9381
  return new ValidatorStatistics(zero, zero, zero, zero, zero, zero);
9332
9382
  }
9333
9383
  }
9334
- const codecVarU16 = varU32.convert((i) => tryAsU32(i), (o) => tryAsU16(o));
9384
+ const codecVarU16 = codec.varU32.convert((i) => tryAsU32(i), (o) => tryAsU16(o));
9335
9385
  /** Encode/decode unsigned gas. */
9336
- const codecVarGas = varU64.convert((g) => tryAsU64(g), (i) => tryAsServiceGas(i));
9386
+ const codecVarGas = codec.varU64.convert((g) => tryAsU64(g), (i) => tryAsServiceGas(i));
9337
9387
  /**
9338
9388
  * Single core statistics.
9339
9389
  * Updated per block, based on incoming work reports (`w`).
@@ -9350,14 +9400,14 @@ class CoreStatistics {
9350
9400
  extrinsicCount;
9351
9401
  bundleSize;
9352
9402
  gasUsed;
9353
- static Codec = Class(CoreStatistics, {
9354
- dataAvailabilityLoad: varU32,
9403
+ static Codec = codec.Class(CoreStatistics, {
9404
+ dataAvailabilityLoad: codec.varU32,
9355
9405
  popularity: codecVarU16,
9356
9406
  imports: codecVarU16,
9357
9407
  extrinsicCount: codecVarU16,
9358
- extrinsicSize: varU32,
9408
+ extrinsicSize: codec.varU32,
9359
9409
  exports: codecVarU16,
9360
- bundleSize: varU32,
9410
+ bundleSize: codec.varU32,
9361
9411
  gasUsed: codecVarGas,
9362
9412
  });
9363
9413
  static create(v) {
@@ -9416,31 +9466,31 @@ class ServiceStatistics {
9416
9466
  onTransfersCount;
9417
9467
  onTransfersGasUsed;
9418
9468
  static Codec = Compatibility.selectIfGreaterOrEqual({
9419
- fallback: Class(ServiceStatistics, {
9469
+ fallback: codec.Class(ServiceStatistics, {
9420
9470
  providedCount: codecVarU16,
9421
- providedSize: varU32,
9422
- refinementCount: varU32,
9471
+ providedSize: codec.varU32,
9472
+ refinementCount: codec.varU32,
9423
9473
  refinementGasUsed: codecVarGas,
9424
9474
  imports: codecVarU16,
9425
9475
  extrinsicCount: codecVarU16,
9426
- extrinsicSize: varU32,
9476
+ extrinsicSize: codec.varU32,
9427
9477
  exports: codecVarU16,
9428
- accumulateCount: varU32,
9478
+ accumulateCount: codec.varU32,
9429
9479
  accumulateGasUsed: codecVarGas,
9430
- onTransfersCount: varU32,
9480
+ onTransfersCount: codec.varU32,
9431
9481
  onTransfersGasUsed: codecVarGas,
9432
9482
  }),
9433
9483
  versions: {
9434
- [GpVersion.V0_7_1]: Class(ServiceStatistics, {
9484
+ [GpVersion.V0_7_1]: codec.Class(ServiceStatistics, {
9435
9485
  providedCount: codecVarU16,
9436
- providedSize: varU32,
9437
- refinementCount: varU32,
9486
+ providedSize: codec.varU32,
9487
+ refinementCount: codec.varU32,
9438
9488
  refinementGasUsed: codecVarGas,
9439
9489
  imports: codecVarU16,
9440
9490
  extrinsicCount: codecVarU16,
9441
- extrinsicSize: varU32,
9491
+ extrinsicSize: codec.varU32,
9442
9492
  exports: codecVarU16,
9443
- accumulateCount: varU32,
9493
+ accumulateCount: codec.varU32,
9444
9494
  accumulateGasUsed: codecVarGas,
9445
9495
  onTransfersCount: ignoreValueWithDefault(tryAsU32(0)),
9446
9496
  onTransfersGasUsed: ignoreValueWithDefault(tryAsServiceGas(0)),
@@ -9501,11 +9551,11 @@ class StatisticsData {
9501
9551
  previous;
9502
9552
  cores;
9503
9553
  services;
9504
- static Codec = Class(StatisticsData, {
9554
+ static Codec = codec.Class(StatisticsData, {
9505
9555
  current: codecPerValidator(ValidatorStatistics.Codec),
9506
9556
  previous: codecPerValidator(ValidatorStatistics.Codec),
9507
9557
  cores: codecPerCore(CoreStatistics.Codec),
9508
- services: dictionary(u32.asOpaque(), ServiceStatistics.Codec, {
9558
+ services: codec.dictionary(codec.u32.asOpaque(), ServiceStatistics.Codec, {
9509
9559
  sortKeys: (a, b) => a - b,
9510
9560
  }),
9511
9561
  });
@@ -9587,14 +9637,14 @@ class PrivilegedServices {
9587
9637
  assigners;
9588
9638
  autoAccumulateServices;
9589
9639
  /** https://graypaper.fluffylabs.dev/#/ab2cdbd/3bbd023bcb02?v=0.7.2 */
9590
- static Codec = Class(PrivilegedServices, {
9591
- manager: u32.asOpaque(),
9592
- assigners: codecPerCore(u32.asOpaque()),
9593
- delegator: u32.asOpaque(),
9640
+ static Codec = codec.Class(PrivilegedServices, {
9641
+ manager: codec.u32.asOpaque(),
9642
+ assigners: codecPerCore(codec.u32.asOpaque()),
9643
+ delegator: codec.u32.asOpaque(),
9594
9644
  registrar: Compatibility.isGreaterOrEqual(GpVersion.V0_7_1)
9595
- ? u32.asOpaque()
9645
+ ? codec.u32.asOpaque()
9596
9646
  : ignoreValueWithDefault(tryAsServiceId(2 ** 32 - 1)),
9597
- autoAccumulateServices: dictionary(u32.asOpaque(), u64.asOpaque(), {
9647
+ autoAccumulateServices: codec.dictionary(codec.u32.asOpaque(), codec.u64.asOpaque(), {
9598
9648
  sortKeys: (a, b) => a - b,
9599
9649
  }),
9600
9650
  });
@@ -10239,15 +10289,15 @@ class InMemoryState extends WithDebug {
10239
10289
  });
10240
10290
  }
10241
10291
  }
10242
- const serviceEntriesCodec = object({
10243
- storageKeys: sequenceVarLen(blob.convert((i) => i, (o) => asOpaqueType(o))),
10244
- preimages: sequenceVarLen(bytes(HASH_SIZE).asOpaque()),
10245
- lookupHistory: sequenceVarLen(object({
10246
- hash: bytes(HASH_SIZE).asOpaque(),
10247
- length: u32,
10292
+ const serviceEntriesCodec = codec.object({
10293
+ storageKeys: codec.sequenceVarLen(codec.blob.convert((i) => i, (o) => asOpaqueType(o))),
10294
+ preimages: codec.sequenceVarLen(codec.bytes(HASH_SIZE).asOpaque()),
10295
+ lookupHistory: codec.sequenceVarLen(codec.object({
10296
+ hash: codec.bytes(HASH_SIZE).asOpaque(),
10297
+ length: codec.u32,
10248
10298
  })),
10249
10299
  });
10250
- const serviceDataCodec = dictionary(u32.asOpaque(), serviceEntriesCodec, {
10300
+ const serviceDataCodec = codec.dictionary(codec.u32.asOpaque(), serviceEntriesCodec, {
10251
10301
  sortKeys: (a, b) => a - b,
10252
10302
  });
10253
10303
 
@@ -10350,7 +10400,7 @@ var serialize;
10350
10400
  /** C(6): https://graypaper.fluffylabs.dev/#/7e6ff6a/3bf3013bf301?v=0.6.7 */
10351
10401
  serialize.entropy = {
10352
10402
  key: stateKeys.index(StateKeyIdx.Eta),
10353
- Codec: codecFixedSizeArray(bytes(HASH_SIZE).asOpaque(), ENTROPY_ENTRIES),
10403
+ Codec: codecFixedSizeArray(codec.bytes(HASH_SIZE).asOpaque(), ENTROPY_ENTRIES),
10354
10404
  extract: (s) => s.entropy,
10355
10405
  };
10356
10406
  /** C(7): https://graypaper.fluffylabs.dev/#/7e6ff6a/3b00023b0002?v=0.6.7 */
@@ -10380,7 +10430,7 @@ var serialize;
10380
10430
  /** C(11): https://graypaper.fluffylabs.dev/#/7e6ff6a/3b3e023b3e02?v=0.6.7 */
10381
10431
  serialize.timeslot = {
10382
10432
  key: stateKeys.index(StateKeyIdx.Tau),
10383
- Codec: u32.asOpaque(),
10433
+ Codec: codec.u32.asOpaque(),
10384
10434
  extract: (s) => s.timeslot,
10385
10435
  };
10386
10436
  /** C(12): https://graypaper.fluffylabs.dev/#/7e6ff6a/3b4c023b4c02?v=0.6.7 */
@@ -10410,7 +10460,7 @@ var serialize;
10410
10460
  /** C(16): https://graypaper.fluffylabs.dev/#/38c4e62/3b46033b4603?v=0.7.0 */
10411
10461
  serialize.accumulationOutputLog = {
10412
10462
  key: stateKeys.index(StateKeyIdx.Theta),
10413
- Codec: sequenceVarLen(AccumulationOutput.Codec).convert((i) => i.array, (o) => SortedArray.fromSortedArray(accumulationOutputComparator, o)),
10463
+ Codec: codec.sequenceVarLen(AccumulationOutput.Codec).convert((i) => i.array, (o) => SortedArray.fromSortedArray(accumulationOutputComparator, o)),
10414
10464
  extract: (s) => s.accumulationOutputLog,
10415
10465
  };
10416
10466
  /** C(255, s): https://graypaper.fluffylabs.dev/#/85129da/383103383103?v=0.6.3 */
@@ -10433,7 +10483,7 @@ var serialize;
10433
10483
  /** https://graypaper.fluffylabs.dev/#/85129da/387603387603?v=0.6.3 */
10434
10484
  serialize.serviceLookupHistory = (blake2b, serviceId, hash, len) => ({
10435
10485
  key: stateKeys.serviceLookupHistory(blake2b, serviceId, hash, len),
10436
- Codec: readonlyArray(sequenceVarLen(u32)),
10486
+ Codec: codec.readonlyArray(codec.sequenceVarLen(codec.u32)),
10437
10487
  });
10438
10488
  })(serialize || (serialize = {}));
10439
10489
  /**
@@ -11527,7 +11577,7 @@ function getSafroleData(nextValidatorData, epochRoot, sealingKeySeries, ticketsA
11527
11577
 
11528
11578
  const TYPICAL_STATE_ITEMS = 50;
11529
11579
  const TYPICAL_STATE_ITEM_LEN = 50;
11530
- const stateEntriesSequenceCodec = sequenceVarLen(pair(bytes(TRUNCATED_HASH_SIZE), blob));
11580
+ const stateEntriesSequenceCodec = codec.sequenceVarLen(codec.pair(codec.bytes(TRUNCATED_HASH_SIZE), codec.blob));
11531
11581
  /**
11532
11582
  * Full, in-memory state represented as serialized entries dictionary.
11533
11583
  *
@@ -11535,7 +11585,7 @@ const stateEntriesSequenceCodec = sequenceVarLen(pair(bytes(TRUNCATED_HASH_SIZE)
11535
11585
  */
11536
11586
  class StateEntries {
11537
11587
  dictionary;
11538
- static Codec = custom({
11588
+ static Codec = codec.custom({
11539
11589
  name: "StateEntries",
11540
11590
  sizeHint: {
11541
11591
  isExact: false,
@@ -12355,10 +12405,10 @@ class Version extends WithDebug {
12355
12405
  major;
12356
12406
  minor;
12357
12407
  patch;
12358
- static Codec = Class(Version, {
12359
- major: u8,
12360
- minor: u8,
12361
- patch: u8,
12408
+ static Codec = codec.Class(Version, {
12409
+ major: codec.u8,
12410
+ minor: codec.u8,
12411
+ patch: codec.u8,
12362
12412
  });
12363
12413
  static tryFromString(str) {
12364
12414
  const parse = (v) => tryAsU8(Number(v));
@@ -12410,12 +12460,12 @@ class PeerInfo extends WithDebug {
12410
12460
  jamVersion;
12411
12461
  appVersion;
12412
12462
  name;
12413
- static Codec = Class(PeerInfo, {
12414
- fuzzVersion: u8,
12415
- features: u32,
12463
+ static Codec = codec.Class(PeerInfo, {
12464
+ fuzzVersion: codec.u8,
12465
+ features: codec.u32,
12416
12466
  jamVersion: Version.Codec,
12417
12467
  appVersion: Version.Codec,
12418
- name: string,
12468
+ name: codec.string,
12419
12469
  });
12420
12470
  static create({ fuzzVersion, features, appVersion, jamVersion, name }) {
12421
12471
  return new PeerInfo(fuzzVersion, features, jamVersion, appVersion, name);
@@ -12438,9 +12488,9 @@ class PeerInfo extends WithDebug {
12438
12488
  class AncestryItem extends WithDebug {
12439
12489
  slot;
12440
12490
  headerHash;
12441
- static Codec = Class(AncestryItem, {
12442
- slot: u32.asOpaque(),
12443
- headerHash: bytes(HASH_SIZE).asOpaque(),
12491
+ static Codec = codec.Class(AncestryItem, {
12492
+ slot: codec.u32.asOpaque(),
12493
+ headerHash: codec.bytes(HASH_SIZE).asOpaque(),
12444
12494
  });
12445
12495
  static create({ slot, headerHash }) {
12446
12496
  return new AncestryItem(slot, headerHash);
@@ -12460,9 +12510,9 @@ class AncestryItem extends WithDebug {
12460
12510
  class KeyValue extends WithDebug {
12461
12511
  key;
12462
12512
  value;
12463
- static Codec = Class(KeyValue, {
12464
- key: bytes(TRUNCATED_HASH_SIZE),
12465
- value: blob,
12513
+ static Codec = codec.Class(KeyValue, {
12514
+ key: codec.bytes(TRUNCATED_HASH_SIZE),
12515
+ value: codec.blob,
12466
12516
  });
12467
12517
  static create({ key, value }) {
12468
12518
  return new KeyValue(key, value);
@@ -12474,12 +12524,12 @@ class KeyValue extends WithDebug {
12474
12524
  }
12475
12525
  }
12476
12526
  /** State ::= SEQUENCE OF KeyValue */
12477
- const stateCodec = sequenceVarLen(KeyValue.Codec);
12527
+ const stateCodec = codec.sequenceVarLen(KeyValue.Codec);
12478
12528
  /**
12479
12529
  * Ancestry ::= SEQUENCE (SIZE(0..24)) OF AncestryItem
12480
12530
  * Empty when `feature-ancestry` is not supported by both parties
12481
12531
  */
12482
- const ancestryCodec = sequenceVarLen(AncestryItem.Codec, {
12532
+ const ancestryCodec = codec.sequenceVarLen(AncestryItem.Codec, {
12483
12533
  minLength: 0,
12484
12534
  maxLength: 24,
12485
12535
  });
@@ -12494,7 +12544,7 @@ class Initialize extends WithDebug {
12494
12544
  header;
12495
12545
  keyvals;
12496
12546
  ancestry;
12497
- static Codec = Class(Initialize, {
12547
+ static Codec = codec.Class(Initialize, {
12498
12548
  header: Header.Codec,
12499
12549
  keyvals: stateCodec,
12500
12550
  ancestry: ancestryCodec,
@@ -12510,14 +12560,14 @@ class Initialize extends WithDebug {
12510
12560
  }
12511
12561
  }
12512
12562
  /** GetState ::= HeaderHash */
12513
- const getStateCodec = bytes(HASH_SIZE).asOpaque();
12563
+ const getStateCodec = codec.bytes(HASH_SIZE).asOpaque();
12514
12564
  /** StateRoot ::= StateRootHash */
12515
- const stateRootCodec = bytes(HASH_SIZE).asOpaque();
12565
+ const stateRootCodec = codec.bytes(HASH_SIZE).asOpaque();
12516
12566
  /** Error ::= UTF8String */
12517
12567
  class ErrorMessage extends WithDebug {
12518
12568
  message;
12519
- static Codec = Class(ErrorMessage, {
12520
- message: string,
12569
+ static Codec = codec.Class(ErrorMessage, {
12570
+ message: codec.string,
12521
12571
  });
12522
12572
  static create({ message }) {
12523
12573
  return new ErrorMessage(message);
@@ -12549,7 +12599,7 @@ var MessageType;
12549
12599
  * error [255] Error
12550
12600
  * }
12551
12601
  */
12552
- const messageCodec = custom({
12602
+ const messageCodec = codec.custom({
12553
12603
  name: "Message",
12554
12604
  sizeHint: { bytes: 1, isExact: false },
12555
12605
  }, (e, msg) => {
@@ -18034,7 +18084,7 @@ class Assign {
18034
18084
  // NOTE: Here we know the core index is valid
18035
18085
  const coreIndex = tryAsCoreIndex(Number(maybeCoreIndex));
18036
18086
  const decoder = Decoder.fromBlob(res);
18037
- const authQueue = decoder.sequenceFixLen(bytes(HASH_SIZE).asOpaque(), AUTHORIZATION_QUEUE_SIZE);
18087
+ const authQueue = decoder.sequenceFixLen(codec.bytes(HASH_SIZE).asOpaque(), AUTHORIZATION_QUEUE_SIZE);
18038
18088
  const fixedSizeAuthQueue = FixedSizeArray.new(authQueue, AUTHORIZATION_QUEUE_SIZE);
18039
18089
  const result = this.partialState.updateAuthorizationQueue(coreIndex, fixedSizeAuthQueue, assigners);
18040
18090
  if (result.isOk) {
@@ -18058,9 +18108,9 @@ class Assign {
18058
18108
  }
18059
18109
 
18060
18110
  const IN_OUT_REG$m = 7;
18061
- const serviceIdAndGasCodec = object({
18062
- serviceId: u32.convert((i) => i, (o) => asOpaqueType(o)),
18063
- gas: u64.convert((i) => tryAsU64(i), (o) => tryAsServiceGas(o)),
18111
+ const serviceIdAndGasCodec = codec.object({
18112
+ serviceId: codec.u32.convert((i) => i, (o) => asOpaqueType(o)),
18113
+ gas: codec.u64.convert((i) => tryAsU64(i), (o) => tryAsServiceGas(o)),
18064
18114
  });
18065
18115
  /**
18066
18116
  * Modify privileged services and services that auto-accumulate every block.
@@ -18118,7 +18168,7 @@ class Bless {
18118
18168
  memIndex = tryAsU64(memIndex + tryAsU64(decoder.bytesRead()));
18119
18169
  }
18120
18170
  // https://graypaper.fluffylabs.dev/#/7e6ff6a/367200367200?v=0.6.7
18121
- const res = safeAllocUint8Array(tryAsExactBytes(u32.sizeHint) * this.chainSpec.coresCount);
18171
+ const res = safeAllocUint8Array(tryAsExactBytes(codec.u32.sizeHint) * this.chainSpec.coresCount);
18122
18172
  const authorizersDecoder = Decoder.fromBlob(res);
18123
18173
  const memoryReadResult = memory.loadInto(res, authorization);
18124
18174
  if (memoryReadResult.isError) {
@@ -18126,7 +18176,7 @@ class Bless {
18126
18176
  return PvmExecution.Panic;
18127
18177
  }
18128
18178
  // `a`
18129
- const authorizers = tryAsPerCore(authorizersDecoder.sequenceFixLen(u32.asOpaque(), this.chainSpec.coresCount), this.chainSpec);
18179
+ const authorizers = tryAsPerCore(authorizersDecoder.sequenceFixLen(codec.u32.asOpaque(), this.chainSpec.coresCount), this.chainSpec);
18130
18180
  const updateResult = this.partialState.updatePrivilegedServices(manager, authorizers, delegator, registrar, autoAccumulate);
18131
18181
  if (updateResult.isOk) {
18132
18182
  logger$7.trace `[${this.currentServiceId}] BLESS(m: ${manager}, a: [${authorizers}], v: ${delegator}, r: ${registrar}, ${lazyInspect(autoAccumulate)}) <- OK`;
@@ -18736,12 +18786,12 @@ class PendingTransfer {
18736
18786
  amount;
18737
18787
  memo;
18738
18788
  gas;
18739
- static Codec = Class(PendingTransfer, {
18740
- source: u32.asOpaque(),
18741
- destination: u32.asOpaque(),
18742
- amount: u64,
18743
- memo: bytes(TRANSFER_MEMO_BYTES),
18744
- gas: u64.asOpaque(),
18789
+ static Codec = codec.Class(PendingTransfer, {
18790
+ source: codec.u32.asOpaque(),
18791
+ destination: codec.u32.asOpaque(),
18792
+ amount: codec.u64,
18793
+ memo: codec.bytes(TRANSFER_MEMO_BYTES),
18794
+ gas: codec.u64.asOpaque(),
18745
18795
  });
18746
18796
  constructor(
18747
18797
  /** `s`: sending service */
@@ -19039,18 +19089,18 @@ class Info {
19039
19089
  *
19040
19090
  * https://graypaper.fluffylabs.dev/#/ab2cdbd/33920033b500?v=0.7.2
19041
19091
  */
19042
- const codecServiceAccountInfoWithThresholdBalance = object({
19043
- codeHash: bytes(HASH_SIZE),
19044
- balance: u64,
19045
- thresholdBalance: u64,
19046
- accumulateMinGas: u64.convert((i) => i, tryAsServiceGas),
19047
- onTransferMinGas: u64.convert((i) => i, tryAsServiceGas),
19048
- storageUtilisationBytes: u64,
19049
- storageUtilisationCount: u32,
19050
- gratisStorage: u64,
19051
- created: u32.convert((x) => x, tryAsTimeSlot),
19052
- lastAccumulation: u32.convert((x) => x, tryAsTimeSlot),
19053
- parentService: u32.convert((x) => x, tryAsServiceId),
19092
+ const codecServiceAccountInfoWithThresholdBalance = codec.object({
19093
+ codeHash: codec.bytes(HASH_SIZE),
19094
+ balance: codec.u64,
19095
+ thresholdBalance: codec.u64,
19096
+ accumulateMinGas: codec.u64.convert((i) => i, tryAsServiceGas),
19097
+ onTransferMinGas: codec.u64.convert((i) => i, tryAsServiceGas),
19098
+ storageUtilisationBytes: codec.u64,
19099
+ storageUtilisationCount: codec.u32,
19100
+ gratisStorage: codec.u64,
19101
+ created: codec.u32.convert((x) => x, tryAsTimeSlot),
19102
+ lastAccumulation: codec.u32.convert((x) => x, tryAsTimeSlot),
19103
+ parentService: codec.u32.convert((x) => x, tryAsServiceId),
19054
19104
  }, "ServiceAccountInfoWithThresholdBalance");
19055
19105
 
19056
19106
  const decoder = new TextDecoder("utf8");
@@ -19426,9 +19476,9 @@ class HistoricalLookup {
19426
19476
 
19427
19477
  const IN_OUT_REG_1 = 7;
19428
19478
  const IN_OUT_REG_2 = 8;
19429
- const gasAndRegistersCodec = object({
19430
- gas: i64,
19431
- registers: bytes(NO_OF_REGISTERS$1 * REGISTER_BYTE_SIZE),
19479
+ const gasAndRegistersCodec = codec.object({
19480
+ gas: codec.i64,
19481
+ registers: codec.bytes(NO_OF_REGISTERS$1 * REGISTER_BYTE_SIZE),
19432
19482
  });
19433
19483
  const GAS_REGISTERS_SIZE = tryAsExactBytes(gasAndRegistersCodec.sizeHint);
19434
19484
  /**
@@ -20274,21 +20324,21 @@ const GAS_TO_INVOKE_WORK_REPORT = 10000000n;
20274
20324
  * https://graypaper.fluffylabs.dev/#/ab2cdbd/176b00176b00?v=0.7.2
20275
20325
  */
20276
20326
  class Operand extends WithDebug {
20277
- static Codec = Class(Operand, {
20327
+ static Codec = codec.Class(Operand, {
20278
20328
  // h
20279
- hash: bytes(HASH_SIZE).asOpaque(),
20329
+ hash: codec.bytes(HASH_SIZE).asOpaque(),
20280
20330
  // e
20281
- exportsRoot: bytes(HASH_SIZE).asOpaque(),
20331
+ exportsRoot: codec.bytes(HASH_SIZE).asOpaque(),
20282
20332
  // a
20283
- authorizerHash: bytes(HASH_SIZE).asOpaque(),
20333
+ authorizerHash: codec.bytes(HASH_SIZE).asOpaque(),
20284
20334
  // y
20285
- payloadHash: bytes(HASH_SIZE),
20335
+ payloadHash: codec.bytes(HASH_SIZE),
20286
20336
  // g
20287
- gas: varU64.asOpaque(),
20337
+ gas: codec.varU64.asOpaque(),
20288
20338
  // d
20289
20339
  result: WorkExecResult.Codec,
20290
20340
  // o
20291
- authorizationOutput: blob,
20341
+ authorizationOutput: codec.blob,
20292
20342
  });
20293
20343
  /**
20294
20344
  * https://graypaper.fluffylabs.dev/#/ab2cdbd/18680118eb01?v=0.7.2
@@ -20471,80 +20521,153 @@ function signingPayload$1(blake2b, anchor, blob) {
20471
20521
  return BytesBlob.blobFromParts(JAM_AVAILABLE, blake2b.hashBytes(BytesBlob.blobFromParts(anchor.raw, blob.raw)).raw);
20472
20522
  }
20473
20523
 
20524
+ /** Error that may happen during reports processing. */
20525
+ var ReportsError;
20526
+ (function (ReportsError) {
20527
+ /** Core index is greater than the number of available cores. */
20528
+ ReportsError[ReportsError["BadCoreIndex"] = 0] = "BadCoreIndex";
20529
+ /** The report slot is greater than the current block slot. */
20530
+ ReportsError[ReportsError["FutureReportSlot"] = 1] = "FutureReportSlot";
20531
+ /** Report is too old to be considered. */
20532
+ ReportsError[ReportsError["ReportEpochBeforeLast"] = 2] = "ReportEpochBeforeLast";
20533
+ /** Not enough credentials for the guarantee. */
20534
+ ReportsError[ReportsError["InsufficientGuarantees"] = 3] = "InsufficientGuarantees";
20535
+ /** Guarantees are not ordered by the core index. */
20536
+ ReportsError[ReportsError["OutOfOrderGuarantee"] = 4] = "OutOfOrderGuarantee";
20537
+ /** Credentials of guarantors are not sorted or unique. */
20538
+ ReportsError[ReportsError["NotSortedOrUniqueGuarantors"] = 5] = "NotSortedOrUniqueGuarantors";
20539
+ /** Validator in credentials is assigned to a different core. */
20540
+ ReportsError[ReportsError["WrongAssignment"] = 6] = "WrongAssignment";
20541
+ /** There is a report pending availability on that core already. */
20542
+ ReportsError[ReportsError["CoreEngaged"] = 7] = "CoreEngaged";
20543
+ /** Anchor block is not found in recent blocks. */
20544
+ ReportsError[ReportsError["AnchorNotRecent"] = 8] = "AnchorNotRecent";
20545
+ /** Service not foubd. */
20546
+ ReportsError[ReportsError["BadServiceId"] = 9] = "BadServiceId";
20547
+ /** Service code hash does not match the current one. */
20548
+ ReportsError[ReportsError["BadCodeHash"] = 10] = "BadCodeHash";
20549
+ /** Pre-requisite work package is missing in either recent blocks or lookup extrinsic. */
20550
+ ReportsError[ReportsError["DependencyMissing"] = 11] = "DependencyMissing";
20551
+ /** Results for the same package are in more than one report. */
20552
+ ReportsError[ReportsError["DuplicatePackage"] = 12] = "DuplicatePackage";
20553
+ /** Anchor block declared state root does not match the one we have in recent blocks. */
20554
+ ReportsError[ReportsError["BadStateRoot"] = 13] = "BadStateRoot";
20555
+ /** BEEFY super hash mmr mismatch. */
20556
+ ReportsError[ReportsError["BadBeefyMmrRoot"] = 14] = "BadBeefyMmrRoot";
20557
+ /** The authorization hash is not found in the authorization pool. */
20558
+ ReportsError[ReportsError["CoreUnauthorized"] = 15] = "CoreUnauthorized";
20559
+ /** Validator index is greater than the number of validators. */
20560
+ ReportsError[ReportsError["BadValidatorIndex"] = 16] = "BadValidatorIndex";
20561
+ /** Total gas of work report is too high. */
20562
+ ReportsError[ReportsError["WorkReportGasTooHigh"] = 17] = "WorkReportGasTooHigh";
20563
+ /** Work item has is smaller than required minimal accumulation gas of a service. */
20564
+ ReportsError[ReportsError["ServiceItemGasTooLow"] = 18] = "ServiceItemGasTooLow";
20565
+ /** The report has too many dependencies (prerequisites and/or segment-root lookups). */
20566
+ ReportsError[ReportsError["TooManyDependencies"] = 19] = "TooManyDependencies";
20567
+ /** Segment root lookup block has invalid time slot or is not found in the header chain. */
20568
+ ReportsError[ReportsError["SegmentRootLookupInvalid"] = 20] = "SegmentRootLookupInvalid";
20569
+ /** Signature in credentials is invalid. */
20570
+ ReportsError[ReportsError["BadSignature"] = 21] = "BadSignature";
20571
+ /** Size of authorizer output and all work-item successful output blobs is too big. */
20572
+ ReportsError[ReportsError["WorkReportTooBig"] = 22] = "WorkReportTooBig";
20573
+ /** Contains guarantee from validator that is proven to be an offender. */
20574
+ ReportsError[ReportsError["BannedValidator"] = 23] = "BannedValidator";
20575
+ })(ReportsError || (ReportsError = {}));
20576
+
20577
+ /**
20578
+ * `W_R = 48 * 2**10`: The maximum total size of all output blobs in a work-report, in octets.
20579
+ *
20580
+ * https://graypaper.fluffylabs.dev/#/5f542d7/41a60041aa00?v=0.6.2
20581
+ */
20582
+ const MAX_WORK_REPORT_SIZE_BYTES = 48 * 2 ** 10;
20583
+ function verifyReportsBasic(input) {
20584
+ for (const guarantee of input) {
20585
+ const reportView = guarantee.view().report.view();
20586
+ /**
20587
+ * We limit the sum of the number of items in the
20588
+ * segment-root lookup dictionary and the number of
20589
+ * prerequisites to J = 8:
20590
+ *
20591
+ * https://graypaper.fluffylabs.dev/#/ab2cdbd/13fd0113ff01?v=0.7.2
20592
+ */
20593
+ const noOfPrerequisites = reportView.context.view().prerequisites.view().length;
20594
+ const noOfSegmentRootLookups = reportView.segmentRootLookup.view().length;
20595
+ if (noOfPrerequisites + noOfSegmentRootLookups > MAX_REPORT_DEPENDENCIES) {
20596
+ return Result$1.error(ReportsError.TooManyDependencies, () => `Report at ${reportView.coreIndex.materialize()} has too many dependencies. Got ${noOfPrerequisites} + ${noOfSegmentRootLookups}, max: ${MAX_REPORT_DEPENDENCIES}`);
20597
+ }
20598
+ /**
20599
+ * In order to ensure fair use of a block’s extrinsic space,
20600
+ * work-reports are limited in the maximum total size of the
20601
+ * successful output blobs together with the authorizer output
20602
+ * blob, effectively limiting their overall size:
20603
+ *
20604
+ * https://graypaper.fluffylabs.dev/#/ab2cdbd/14a80014ab00?v=0.7.2
20605
+ */
20606
+ // adding is safe here, since the total-encoded size of the report
20607
+ // is limited as well. Even though we just have a view, the size
20608
+ // should have been verified earlier.
20609
+ const authOutputSize = reportView.authorizationOutput.view().length;
20610
+ let totalOutputsSize = 0;
20611
+ for (const item of reportView.results.view()) {
20612
+ const workItemView = item.view();
20613
+ const result = workItemView.result.materialize();
20614
+ if (result.kind === WorkExecResultKind.ok) {
20615
+ totalOutputsSize += result.okBlob?.raw.length ?? 0;
20616
+ }
20617
+ }
20618
+ if (authOutputSize + totalOutputsSize > MAX_WORK_REPORT_SIZE_BYTES) {
20619
+ return Result$1.error(ReportsError.WorkReportTooBig, () => `Work report at ${reportView.coreIndex.materialize()} too big. Got ${authOutputSize} + ${totalOutputsSize}, max: ${MAX_WORK_REPORT_SIZE_BYTES}`);
20620
+ }
20621
+ }
20622
+ return Result$1.ok(OK);
20623
+ }
20624
+
20474
20625
  var TransferOperandKind;
20475
20626
  (function (TransferOperandKind) {
20476
20627
  TransferOperandKind[TransferOperandKind["OPERAND"] = 0] = "OPERAND";
20477
20628
  TransferOperandKind[TransferOperandKind["TRANSFER"] = 1] = "TRANSFER";
20478
20629
  })(TransferOperandKind || (TransferOperandKind = {}));
20479
- const TRANSFER_OR_OPERAND = custom({
20480
- name: "TransferOrOperand",
20481
- sizeHint: { bytes: 1, isExact: false },
20482
- }, (e, x) => {
20483
- e.varU32(tryAsU32(x.kind));
20484
- if (x.kind === TransferOperandKind.OPERAND) {
20485
- e.object(Operand.Codec, x.value);
20486
- }
20487
- if (x.kind === TransferOperandKind.TRANSFER) {
20488
- e.object(PendingTransfer.Codec, x.value);
20489
- }
20490
- }, (d) => {
20491
- const kind = d.varU32();
20492
- if (kind === TransferOperandKind.OPERAND) {
20493
- return {
20494
- kind: TransferOperandKind.OPERAND,
20495
- value: d.object(Operand.Codec),
20496
- };
20497
- }
20498
- if (kind === TransferOperandKind.TRANSFER) {
20499
- return { kind: TransferOperandKind.TRANSFER, value: d.object(PendingTransfer.Codec) };
20500
- }
20501
- throw new Error(`Unable to decode TransferOrOperand. Invalid kind: ${kind}.`);
20502
- }, (s) => {
20503
- const kind = s.decoder.varU32();
20504
- if (kind === TransferOperandKind.OPERAND) {
20505
- s.object(Operand.Codec);
20506
- }
20507
- if (kind === TransferOperandKind.TRANSFER) {
20508
- s.object(PendingTransfer.Codec);
20509
- }
20630
+ const TRANSFER_OR_OPERAND = codec.union("TransferOrOperand", {
20631
+ [TransferOperandKind.OPERAND]: codec.object({ value: Operand.Codec }),
20632
+ [TransferOperandKind.TRANSFER]: codec.object({ value: PendingTransfer.Codec }),
20510
20633
  });
20511
- const TRANSFERS_AND_OPERANDS = sequenceVarLen(TRANSFER_OR_OPERAND);
20634
+ const TRANSFERS_AND_OPERANDS = codec.sequenceVarLen(TRANSFER_OR_OPERAND);
20512
20635
  // https://github.com/gavofyork/graypaper/pull/414
20513
20636
  // 0.7.0 encoding is used for prior versions as well.
20514
- const CONSTANTS_CODEC = object({
20515
- B_I: u64,
20516
- B_L: u64,
20517
- B_S: u64,
20518
- C: u16,
20519
- D: u32,
20520
- E: u32,
20521
- G_A: u64,
20522
- G_I: u64,
20523
- G_R: u64,
20524
- G_T: u64,
20525
- H: u16,
20526
- I: u16,
20527
- J: u16,
20528
- K: u16,
20529
- L: u32,
20530
- N: u16,
20531
- O: u16,
20532
- P: u16,
20533
- Q: u16,
20534
- R: u16,
20535
- T: u16,
20536
- U: u16,
20537
- V: u16,
20538
- W_A: u32,
20539
- W_B: u32,
20540
- W_C: u32,
20541
- W_E: u32,
20542
- W_M: u32,
20543
- W_P: u32,
20544
- W_R: u32,
20545
- W_T: u32,
20546
- W_X: u32,
20547
- Y: u32,
20637
+ const CONSTANTS_CODEC = codec.object({
20638
+ B_I: codec.u64,
20639
+ B_L: codec.u64,
20640
+ B_S: codec.u64,
20641
+ C: codec.u16,
20642
+ D: codec.u32,
20643
+ E: codec.u32,
20644
+ G_A: codec.u64,
20645
+ G_I: codec.u64,
20646
+ G_R: codec.u64,
20647
+ G_T: codec.u64,
20648
+ H: codec.u16,
20649
+ I: codec.u16,
20650
+ J: codec.u16,
20651
+ K: codec.u16,
20652
+ L: codec.u32,
20653
+ N: codec.u16,
20654
+ O: codec.u16,
20655
+ P: codec.u16,
20656
+ Q: codec.u16,
20657
+ R: codec.u16,
20658
+ T: codec.u16,
20659
+ U: codec.u16,
20660
+ V: codec.u16,
20661
+ W_A: codec.u32,
20662
+ W_B: codec.u32,
20663
+ W_C: codec.u32,
20664
+ W_E: codec.u32,
20665
+ W_M: codec.u32,
20666
+ W_P: codec.u32,
20667
+ W_R: codec.u32,
20668
+ W_T: codec.u32,
20669
+ W_X: codec.u32,
20670
+ Y: codec.u32,
20548
20671
  });
20549
20672
  const encodedConstantsCache = new Map();
20550
20673
  function getEncodedConstants(chainSpec) {
@@ -20582,7 +20705,7 @@ function getEncodedConstants(chainSpec) {
20582
20705
  W_E: tryAsU32(chainSpec.erasureCodedPieceSize),
20583
20706
  W_M: tryAsU32(W_M),
20584
20707
  W_P: tryAsU32(chainSpec.numberECPiecesPerSegment),
20585
- W_R: tryAsU32(W_R),
20708
+ W_R: tryAsU32(MAX_WORK_REPORT_SIZE_BYTES),
20586
20709
  W_T: tryAsU32(W_T),
20587
20710
  W_X: tryAsU32(W_X),
20588
20711
  Y: tryAsU32(chainSpec.contestLength),
@@ -20657,7 +20780,7 @@ class FetchExternalities {
20657
20780
  allOperands() {
20658
20781
  if (this.fetchData.context === FetchContext.LegacyAccumulate) {
20659
20782
  const operands = this.fetchData.operands;
20660
- return Encoder.encodeObject(sequenceVarLen(Operand.Codec), operands, this.chainSpec);
20783
+ return Encoder.encodeObject(codec.sequenceVarLen(Operand.Codec), operands, this.chainSpec);
20661
20784
  }
20662
20785
  return null;
20663
20786
  }
@@ -20678,7 +20801,7 @@ class FetchExternalities {
20678
20801
  allTransfers() {
20679
20802
  if (this.fetchData.context === FetchContext.LegacyOnTransfer) {
20680
20803
  const { transfers } = this.fetchData;
20681
- return Encoder.encodeObject(sequenceVarLen(PendingTransfer.Codec), transfers, this.chainSpec);
20804
+ return Encoder.encodeObject(codec.sequenceVarLen(PendingTransfer.Codec), transfers, this.chainSpec);
20682
20805
  }
20683
20806
  return null;
20684
20807
  }
@@ -20909,10 +21032,10 @@ function getWorkPackageHashes(reports) {
20909
21032
  const workPackageHashes = reports.map((report) => report.workPackageSpec.hash);
20910
21033
  return HashSet.from(workPackageHashes);
20911
21034
  }
20912
- const NEXT_ID_CODEC = object({
20913
- serviceId: varU32.asOpaque(),
20914
- entropy: bytes(HASH_SIZE).asOpaque(),
20915
- timeslot: varU32.asOpaque(),
21035
+ const NEXT_ID_CODEC = codec.object({
21036
+ serviceId: codec.varU32.asOpaque(),
21037
+ entropy: codec.bytes(HASH_SIZE).asOpaque(),
21038
+ timeslot: codec.varU32.asOpaque(),
20916
21039
  });
20917
21040
  /**
20918
21041
  * Generate a next service id.
@@ -21310,21 +21433,24 @@ var PvmInvocationError;
21310
21433
  PvmInvocationError[PvmInvocationError["PreimageTooLong"] = 2] = "PreimageTooLong";
21311
21434
  })(PvmInvocationError || (PvmInvocationError = {}));
21312
21435
  const logger$5 = Logger.new(import.meta.filename, "accumulate");
21313
- const ARGS_CODEC$1 = object({
21314
- slot: varU32.asOpaque(),
21315
- serviceId: varU32.asOpaque(),
21316
- argsLength: varU32,
21436
+ const ARGS_CODEC$1 = codec.object({
21437
+ slot: codec.varU32.asOpaque(),
21438
+ serviceId: codec.varU32.asOpaque(),
21439
+ argsLength: codec.varU32,
21317
21440
  });
21318
21441
  class Accumulate {
21319
21442
  chainSpec;
21320
21443
  blake2b;
21321
21444
  state;
21322
- pvm;
21323
- constructor(chainSpec, blake2b, state, pvm) {
21445
+ options;
21446
+ constructor(chainSpec, blake2b, state, options) {
21324
21447
  this.chainSpec = chainSpec;
21325
21448
  this.blake2b = blake2b;
21326
21449
  this.state = state;
21327
- this.pvm = pvm;
21450
+ this.options = options;
21451
+ if (options.accumulateSequentially === true) {
21452
+ logger$5.warn `⚠️ Parallel accumulation is disabled. Running in sequential mode.`;
21453
+ }
21328
21454
  }
21329
21455
  /**
21330
21456
  * Returns an index that determines how many WorkReports can be processed before exceeding a given gasLimit.
@@ -21376,7 +21502,7 @@ class Accumulate {
21376
21502
  serviceExternalities: partialState,
21377
21503
  fetchExternalities,
21378
21504
  };
21379
- const executor = await PvmExecutor.createAccumulateExecutor(serviceId, code, externalities, this.chainSpec, this.pvm);
21505
+ const executor = await PvmExecutor.createAccumulateExecutor(serviceId, code, externalities, this.chainSpec, this.options.pvm);
21380
21506
  const invocationArgs = Encoder.encodeObject(ARGS_CODEC$1, {
21381
21507
  slot,
21382
21508
  serviceId,
@@ -21593,6 +21719,9 @@ class Accumulate {
21593
21719
  ];
21594
21720
  return resultEntry;
21595
21721
  });
21722
+ if (this.options.accumulateSequentially === true) {
21723
+ await promise;
21724
+ }
21596
21725
  resultPromises[serviceIndex] = promise;
21597
21726
  }
21598
21727
  return Promise.all(resultPromises).then((results) => new Map(results));
@@ -21717,10 +21846,10 @@ class Accumulate {
21717
21846
  }
21718
21847
  }
21719
21848
 
21720
- const ARGS_CODEC = object({
21721
- timeslot: varU32.asOpaque(),
21722
- serviceId: varU32.asOpaque(),
21723
- transfersLength: varU32,
21849
+ const ARGS_CODEC = codec.object({
21850
+ timeslot: codec.varU32.asOpaque(),
21851
+ serviceId: codec.varU32.asOpaque(),
21852
+ transfersLength: codec.varU32,
21724
21853
  });
21725
21854
  var DeferredTransfersErrorCode;
21726
21855
  (function (DeferredTransfersErrorCode) {
@@ -21901,7 +22030,7 @@ class BlockVerifier {
21901
22030
  }
21902
22031
  }
21903
22032
  // Check if extrinsic is valid.
21904
- // https://graypaper.fluffylabs.dev/#/cc517d7/0cba000cba00?v=0.6.5
22033
+ // https://graypaper.fluffylabs.dev/#/ab2cdbd/0cba000cba00?v=0.7.2
21905
22034
  const extrinsicHash = headerView.extrinsicHash.materialize();
21906
22035
  const extrinsicMerkleCommitment = this.hasher.extrinsic(block.extrinsic.view());
21907
22036
  if (!extrinsicHash.isEqualTo(extrinsicMerkleCommitment.hash)) {
@@ -23227,59 +23356,6 @@ class RecentHistory {
23227
23356
  }
23228
23357
  }
23229
23358
 
23230
- /** Error that may happen during reports processing. */
23231
- var ReportsError;
23232
- (function (ReportsError) {
23233
- /** Core index is greater than the number of available cores. */
23234
- ReportsError[ReportsError["BadCoreIndex"] = 0] = "BadCoreIndex";
23235
- /** The report slot is greater than the current block slot. */
23236
- ReportsError[ReportsError["FutureReportSlot"] = 1] = "FutureReportSlot";
23237
- /** Report is too old to be considered. */
23238
- ReportsError[ReportsError["ReportEpochBeforeLast"] = 2] = "ReportEpochBeforeLast";
23239
- /** Not enough credentials for the guarantee. */
23240
- ReportsError[ReportsError["InsufficientGuarantees"] = 3] = "InsufficientGuarantees";
23241
- /** Guarantees are not ordered by the core index. */
23242
- ReportsError[ReportsError["OutOfOrderGuarantee"] = 4] = "OutOfOrderGuarantee";
23243
- /** Credentials of guarantors are not sorted or unique. */
23244
- ReportsError[ReportsError["NotSortedOrUniqueGuarantors"] = 5] = "NotSortedOrUniqueGuarantors";
23245
- /** Validator in credentials is assigned to a different core. */
23246
- ReportsError[ReportsError["WrongAssignment"] = 6] = "WrongAssignment";
23247
- /** There is a report pending availability on that core already. */
23248
- ReportsError[ReportsError["CoreEngaged"] = 7] = "CoreEngaged";
23249
- /** Anchor block is not found in recent blocks. */
23250
- ReportsError[ReportsError["AnchorNotRecent"] = 8] = "AnchorNotRecent";
23251
- /** Service not foubd. */
23252
- ReportsError[ReportsError["BadServiceId"] = 9] = "BadServiceId";
23253
- /** Service code hash does not match the current one. */
23254
- ReportsError[ReportsError["BadCodeHash"] = 10] = "BadCodeHash";
23255
- /** Pre-requisite work package is missing in either recent blocks or lookup extrinsic. */
23256
- ReportsError[ReportsError["DependencyMissing"] = 11] = "DependencyMissing";
23257
- /** Results for the same package are in more than one report. */
23258
- ReportsError[ReportsError["DuplicatePackage"] = 12] = "DuplicatePackage";
23259
- /** Anchor block declared state root does not match the one we have in recent blocks. */
23260
- ReportsError[ReportsError["BadStateRoot"] = 13] = "BadStateRoot";
23261
- /** BEEFY super hash mmr mismatch. */
23262
- ReportsError[ReportsError["BadBeefyMmrRoot"] = 14] = "BadBeefyMmrRoot";
23263
- /** The authorization hash is not found in the authorization pool. */
23264
- ReportsError[ReportsError["CoreUnauthorized"] = 15] = "CoreUnauthorized";
23265
- /** Validator index is greater than the number of validators. */
23266
- ReportsError[ReportsError["BadValidatorIndex"] = 16] = "BadValidatorIndex";
23267
- /** Total gas of work report is too high. */
23268
- ReportsError[ReportsError["WorkReportGasTooHigh"] = 17] = "WorkReportGasTooHigh";
23269
- /** Work item has is smaller than required minimal accumulation gas of a service. */
23270
- ReportsError[ReportsError["ServiceItemGasTooLow"] = 18] = "ServiceItemGasTooLow";
23271
- /** The report has too many dependencies (prerequisites and/or segment-root lookups). */
23272
- ReportsError[ReportsError["TooManyDependencies"] = 19] = "TooManyDependencies";
23273
- /** Segment root lookup block has invalid time slot or is not found in the header chain. */
23274
- ReportsError[ReportsError["SegmentRootLookupInvalid"] = 20] = "SegmentRootLookupInvalid";
23275
- /** Signature in credentials is invalid. */
23276
- ReportsError[ReportsError["BadSignature"] = 21] = "BadSignature";
23277
- /** Size of authorizer output and all work-item successful output blobs is too big. */
23278
- ReportsError[ReportsError["WorkReportTooBig"] = 22] = "WorkReportTooBig";
23279
- /** Contains guarantee from validator that is proven to be an offender. */
23280
- ReportsError[ReportsError["BannedValidator"] = 23] = "BannedValidator";
23281
- })(ReportsError || (ReportsError = {}));
23282
-
23283
23359
  const ENTROPY_BYTES = 32;
23284
23360
  /**
23285
23361
  * Deterministic variant of the Fisher–Yates shuffle function
@@ -23328,17 +23404,17 @@ var index$5 = /*#__PURE__*/Object.freeze({
23328
23404
  * reports for it. This is borne out with V= 1023 validators
23329
23405
  * and C = 341 cores, since V/C = 3. The core index assigned to
23330
23406
  * each of the validators, as well as the validators’ Ed25519
23331
- * keys are denoted by G.
23407
+ * keys are denoted by M.
23332
23408
  *
23333
- * https://graypaper.fluffylabs.dev/#/5f542d7/147601147e01
23409
+ * https://graypaper.fluffylabs.dev/#/ab2cdbd/144c02145402?v=0.7.2
23334
23410
  */
23335
23411
  /**
23336
23412
  * Returns core assignments for each validator index.
23337
23413
  *
23338
- * https://graypaper.fluffylabs.dev/#/5f542d7/14fd0114fd01
23414
+ * https://graypaper.fluffylabs.dev/#/ab2cdbd/155300155d00?v=0.7.2
23339
23415
  */
23340
23416
  function generateCoreAssignment(spec, blake2b,
23341
- /** https://graypaper.fluffylabs.dev/#/5f542d7/149601149601 */
23417
+ /** https://graypaper.fluffylabs.dev/#/ab2cdbd/147102147102?v=0.7.2 */
23342
23418
  eta2entropy,
23343
23419
  /** timeslot */
23344
23420
  slot) {
@@ -23348,7 +23424,7 @@ slot) {
23348
23424
  function rotationIndex(slot, rotationPeriod) {
23349
23425
  return asOpaqueType(Math.floor(slot / rotationPeriod));
23350
23426
  }
23351
- /** https://graypaper.fluffylabs.dev/#/5f542d7/14c00114c001 */
23427
+ /** https://graypaper.fluffylabs.dev/#/ab2cdbd/151900151900?v=0.7.2 */
23352
23428
  function permute(blake2b, entropy, slot, spec) {
23353
23429
  const shift = rotationIndex(tryAsTimeSlot(slot % spec.epochLength), spec.rotationPeriod);
23354
23430
  const initialAssignment = Array(spec.validatorsCount)
@@ -23363,58 +23439,14 @@ function permute(blake2b, entropy, slot, spec) {
23363
23439
  // we are sure this is PerValidator, since that's the array we create earlier.
23364
23440
  return asKnownSize(coreAssignment);
23365
23441
  }
23366
- /** https://graypaper.fluffylabs.dev/#/5f542d7/14a50114a501 */
23442
+ /** https://graypaper.fluffylabs.dev/#/ab2cdbd/148002148002?v=0.7.2 */
23367
23443
  function rotate(cores, n, noOfCores) {
23368
23444
  // modulo `noOfCores` guarantees that we're within `CoreIndex` range.
23369
23445
  return cores.map((x) => asOpaqueType((x + n) % noOfCores));
23370
23446
  }
23371
23447
 
23372
- /**
23373
- * `W_R = 48 * 2**10`: The maximum total size of all output blobs in a work-report, in octets.
23374
- *
23375
- * https://graypaper.fluffylabs.dev/#/5f542d7/41a60041aa00?v=0.6.2
23376
- */
23377
- const MAX_WORK_REPORT_SIZE_BYTES = 48 * 2 ** 10;
23378
- function verifyReportsBasic(input) {
23379
- for (const guarantee of input) {
23380
- const reportView = guarantee.view().report.view();
23381
- /**
23382
- * We limit the sum of the number of items in the
23383
- * segment-root lookup dictionary and the number of
23384
- * prerequisites to J = 8:
23385
- *
23386
- * https://graypaper.fluffylabs.dev/#/5f542d7/13ab0013ad00?v=0.6.2
23387
- */
23388
- const noOfPrerequisites = reportView.context.view().prerequisites.view().length;
23389
- const noOfSegmentRootLookups = reportView.segmentRootLookup.view().length;
23390
- if (noOfPrerequisites + noOfSegmentRootLookups > MAX_REPORT_DEPENDENCIES) {
23391
- return Result$1.error(ReportsError.TooManyDependencies, () => `Report at ${reportView.coreIndex.materialize()} has too many dependencies. Got ${noOfPrerequisites} + ${noOfSegmentRootLookups}, max: ${MAX_REPORT_DEPENDENCIES}`);
23392
- }
23393
- /**
23394
- * In order to ensure fair use of a block’s extrinsic space,
23395
- * work-reports are limited in the maximum total size of the
23396
- * successful output blobs together with the authorizer output
23397
- * blob, effectively limiting their overall size:
23398
- *
23399
- * https://graypaper.fluffylabs.dev/#/5f542d7/141d00142000?v=0.6.2
23400
- */
23401
- // adding is safe here, since the total-encoded size of the report
23402
- // is limited as well. Even though we just have a view, the size
23403
- // should have been verified earlier.
23404
- const authOutputSize = reportView.authorizationOutput.view().length;
23405
- let totalOutputsSize = 0;
23406
- for (const item of reportView.results.view()) {
23407
- totalOutputsSize += item.view().result.view().okBlob?.raw.length ?? 0;
23408
- }
23409
- if (authOutputSize + totalOutputsSize > MAX_WORK_REPORT_SIZE_BYTES) {
23410
- return Result$1.error(ReportsError.WorkReportTooBig, () => `Work report at ${reportView.coreIndex.materialize()} too big. Got ${authOutputSize} + ${totalOutputsSize}, max: ${MAX_WORK_REPORT_SIZE_BYTES}`);
23411
- }
23412
- }
23413
- return Result$1.ok(OK);
23414
- }
23415
-
23416
23448
  const logger$3 = Logger.new(import.meta.filename, "stf:reports");
23417
- /** https://graypaper.fluffylabs.dev/#/7e6ff6a/15eb0115eb01?v=0.6.7 */
23449
+ /** https://graypaper.fluffylabs.dev/#/ab2cdbd/158202158202?v=0.7.2 */
23418
23450
  function verifyContextualValidity(input, state, headerChain, maxLookupAnchorAge) {
23419
23451
  const contexts = [];
23420
23452
  // hashes of work packages reported in this extrinsic
@@ -23436,8 +23468,11 @@ function verifyContextualValidity(input, state, headerChain, maxLookupAnchorAge)
23436
23468
  if (service === null) {
23437
23469
  return Result$1.error(ReportsError.BadServiceId, () => `No service with id: ${result.serviceId}`);
23438
23470
  }
23439
- // check service code hash
23440
- // https://graypaper.fluffylabs.dev/#/5f542d7/154b02154b02
23471
+ /**
23472
+ * Check service code hash
23473
+ *
23474
+ * https://graypaper.fluffylabs.dev/#/ab2cdbd/150804150804?v=0.7.2
23475
+ */
23441
23476
  if (!result.codeHash.isEqualTo(service.getInfo().codeHash)) {
23442
23477
  return Result$1.error(ReportsError.BadCodeHash, () => `Service (${result.serviceId}) code hash mismatch. Got: ${result.codeHash}, expected: ${service.getInfo().codeHash}`);
23443
23478
  }
@@ -23447,7 +23482,7 @@ function verifyContextualValidity(input, state, headerChain, maxLookupAnchorAge)
23447
23482
  * There must be no duplicate work-package hashes (i.e.
23448
23483
  * two work-reports of the same package).
23449
23484
  *
23450
- * https://graypaper.fluffylabs.dev/#/5f542d7/151f01152101
23485
+ * https://graypaper.fluffylabs.dev/#/ab2cdbd/159c02159e02?v=0.7.2
23451
23486
  */
23452
23487
  if (currentWorkPackages.size !== input.guarantees.length) {
23453
23488
  return Result$1.error(ReportsError.DuplicatePackage, () => "Duplicate work package detected.");
@@ -23501,7 +23536,7 @@ function verifyContextualValidity(input, state, headerChain, maxLookupAnchorAge)
23501
23536
  }
23502
23537
  return Result$1.ok(currentWorkPackages);
23503
23538
  }
23504
- /** https://graypaper.fluffylabs.dev/#/7e6ff6a/152502152502?v=0.6.7 */
23539
+ /** https://graypaper.fluffylabs.dev/#/ab2cdbd/15cd0215cd02?v=0.7.2 */
23505
23540
  function verifyRefineContexts(minLookupSlot, contexts, recentBlocksPartialUpdate, headerChain) {
23506
23541
  // TODO [ToDr] [opti] This could be cached and updated efficiently between runs.
23507
23542
  const recentBlocks = HashDictionary.new();
@@ -23512,9 +23547,9 @@ function verifyRefineContexts(minLookupSlot, contexts, recentBlocksPartialUpdate
23512
23547
  /**
23513
23548
  * We require that the anchor block be within the last H
23514
23549
  * blocks and that its details be correct by ensuring that it
23515
- * appears within our most recent blocks β †:
23550
+ * appears within our most recent blocks β†:
23516
23551
  *
23517
- * https://graypaper.fluffylabs.dev/#/5f542d7/152801152b01
23552
+ * https://graypaper.fluffylabs.dev/#/ab2cdbd/15ad0215af02?v=0.7.2
23518
23553
  */
23519
23554
  const recentBlock = recentBlocks.get(context.anchor);
23520
23555
  if (recentBlock === undefined) {
@@ -23533,7 +23568,7 @@ function verifyRefineContexts(minLookupSlot, contexts, recentBlocksPartialUpdate
23533
23568
  * We require that each lookup-anchor block be within the
23534
23569
  * last L timeslots.
23535
23570
  *
23536
- * https://graypaper.fluffylabs.dev/#/5f542d7/154601154701
23571
+ * https://graypaper.fluffylabs.dev/#/ab2cdbd/15ce0215cf02?v=0.7.2
23537
23572
  */
23538
23573
  if (context.lookupAnchorSlot < minLookupSlot) {
23539
23574
  return Result$1.error(ReportsError.SegmentRootLookupInvalid, () => `Lookup anchor slot's too old. Got: ${context.lookupAnchorSlot}, minimal: ${minLookupSlot}`);
@@ -23544,7 +23579,7 @@ function verifyRefineContexts(minLookupSlot, contexts, recentBlocksPartialUpdate
23544
23579
  * on-chain state and must be checked by virtue of retaini
23545
23580
  * ing the series of the last L headers as the ancestor set A.
23546
23581
  *
23547
- * https://graypaper.fluffylabs.dev/#/5f542d7/155c01155f01
23582
+ * https://graypaper.fluffylabs.dev/#/ab2cdbd/15e40215e702?v=0.7.2
23548
23583
  */
23549
23584
  const isInChain = recentBlocks.has(context.lookupAnchor) ||
23550
23585
  headerChain.isAncestor(context.lookupAnchorSlot, context.lookupAnchor, context.anchor);
@@ -23567,7 +23602,7 @@ function verifyDependencies({ currentWorkPackages, recentlyReported, prerequisit
23567
23602
  * segment-root lookup, be either in the extrinsic or in our
23568
23603
  * recent history.
23569
23604
  *
23570
- * https://graypaper.fluffylabs.dev/#/5f542d7/15ca0115cd01
23605
+ * https://graypaper.fluffylabs.dev/#/ab2cdbd/156b03156e03?v=0.7.2
23571
23606
  */
23572
23607
  for (const preReqHash of dependencies) {
23573
23608
  if (currentWorkPackages.has(preReqHash)) {
@@ -23596,7 +23631,7 @@ function verifyWorkPackagesUniqueness(workPackageHashes, state) {
23596
23631
  /**
23597
23632
  * Make sure that the package does not appear anywhere in the pipeline.
23598
23633
  *
23599
- * https://graypaper.fluffylabs.dev/#/5f542d7/159101159101
23634
+ * https://graypaper.fluffylabs.dev/#/ab2cdbd/152803152803?v=0.7.2
23600
23635
  */
23601
23636
  // TODO [ToDr] [opti] this most likely should be cached and either
23602
23637
  // re-computed on invalidity or we could maintain additional
@@ -23637,9 +23672,9 @@ function verifyCredentials(guarantees,
23637
23672
  workReportHashes, slot, getGuarantorAssignment) {
23638
23673
  /**
23639
23674
  * Collect signatures payload for later verification
23640
- * and construct the `reporters set R` from that data.
23675
+ * and construct the `reporters set G` from that data.
23641
23676
  *
23642
- * https://graypaper.fluffylabs.dev/#/5f542d7/15cf0015cf00
23677
+ * https://graypaper.fluffylabs.dev/#/ab2cdbd/153002153002?v=0.7.2
23643
23678
  */
23644
23679
  const signaturesToVerify = [];
23645
23680
  const headerTimeSlot = slot;
@@ -23653,7 +23688,7 @@ workReportHashes, slot, getGuarantorAssignment) {
23653
23688
  * The credential is a sequence of two or three tuples of a
23654
23689
  * unique validator index and a signature.
23655
23690
  *
23656
- * https://graypaper.fluffylabs.dev/#/5f542d7/14b90214bb02
23691
+ * https://graypaper.fluffylabs.dev/#/ab2cdbd/152b01152d01?v=0.7.2
23657
23692
  */
23658
23693
  const credentialsView = guaranteeView.credentials.view();
23659
23694
  if (credentialsView.length < REQUIRED_CREDENTIALS_RANGE[0] ||
@@ -23683,7 +23718,8 @@ workReportHashes, slot, getGuarantorAssignment) {
23683
23718
  }
23684
23719
  /**
23685
23720
  * Verify core assignment.
23686
- * https://graypaper.fluffylabs.dev/#/5f542d7/14e40214e602
23721
+ *
23722
+ * https://graypaper.fluffylabs.dev/#/ab2cdbd/155201155401?v=0.7.2
23687
23723
  */
23688
23724
  if (guarantorData.core !== coreIndex) {
23689
23725
  return Result$1.error(ReportsError.WrongAssignment, () => `Invalid core assignment for validator ${validatorIndex}. Expected: ${guarantorData.core}, got: ${coreIndex}`);
@@ -23702,7 +23738,7 @@ const JAM_GUARANTEE = BytesBlob.blobFromString("jam_guarantee").raw;
23702
23738
  * The signature [...] whose message is the serialization of the hash
23703
23739
  * of the work-report.
23704
23740
  *
23705
- * https://graypaper.fluffylabs.dev/#/5f542d7/155200155200
23741
+ * https://graypaper.fluffylabs.dev/#/ab2cdbd/15a20115a201?v=0.7.2
23706
23742
  */
23707
23743
  function signingPayload(hash) {
23708
23744
  return BytesBlob.blobFromParts(JAM_GUARANTEE, hash.raw);
@@ -23713,7 +23749,7 @@ function verifyReportsOrder(input, chainSpec) {
23713
23749
  * The core index of each guarantee must be unique and
23714
23750
  * guarantees must be in ascending order of this.
23715
23751
  *
23716
- * https://graypaper.fluffylabs.dev/#/5f542d7/146902146a02
23752
+ * https://graypaper.fluffylabs.dev/#/ab2cdbd/15d60015d700?v=0.7.2
23717
23753
  */
23718
23754
  const noOfCores = chainSpec.coresCount;
23719
23755
  let lastCoreIndex = -1;
@@ -23742,7 +23778,7 @@ function verifyPostSignatureChecks(input, availabilityAssignment, authPools, ser
23742
23778
  * No reports may be placed on cores with a report pending
23743
23779
  * availability on it.
23744
23780
  *
23745
- * https://graypaper.fluffylabs.dev/#/5f542d7/15ea0015ea00
23781
+ * https://graypaper.fluffylabs.dev/#/ab2cdbd/155002155002?v=0.7.2
23746
23782
  */
23747
23783
  if (availabilityAssignment[coreIndex] !== null) {
23748
23784
  return Result$1.error(ReportsError.CoreEngaged, () => `Report pending availability at core: ${coreIndex}`);
@@ -23752,7 +23788,7 @@ function verifyPostSignatureChecks(input, availabilityAssignment, authPools, ser
23752
23788
  * in the authorizer pool of the core on which the work is
23753
23789
  * reported.
23754
23790
  *
23755
- * https://graypaper.fluffylabs.dev/#/5f542d7/15eb0015ed00
23791
+ * https://graypaper.fluffylabs.dev/#/ab2cdbd/155102155302?v=0.7.2
23756
23792
  */
23757
23793
  const authorizerHash = report.authorizerHash;
23758
23794
  const authorizerPool = authPools.get(coreIndex);
@@ -23762,10 +23798,10 @@ function verifyPostSignatureChecks(input, availabilityAssignment, authPools, ser
23762
23798
  }
23763
23799
  /**
23764
23800
  * We require that the gas allotted for accumulation of each
23765
- * work item in each work-report respects its service’s
23801
+ * work-digest in each work-report respects its service’s
23766
23802
  * minimum gas requirements.
23767
23803
  *
23768
- * https://graypaper.fluffylabs.dev/#/5f542d7/15f80015fa00
23804
+ * https://graypaper.fluffylabs.dev/#/ab2cdbd/156602156802?v=0.7.2
23769
23805
  */
23770
23806
  for (const result of report.results) {
23771
23807
  const service = services(result.serviceId);
@@ -23837,10 +23873,11 @@ class Reports {
23837
23873
  /**
23838
23874
  * ρ′ - equivalent to ρ‡, except where the extrinsic replaced
23839
23875
  * an entry. In the case an entry is replaced, the new value
23840
- * includes the present time τ allowing for the value to be
23876
+ * includes the present time τ' allowing for the value to be
23841
23877
  * replaced without respect to its availability once sufficient
23842
23878
  * time has elapsed.
23843
- * https://graypaper.fluffylabs.dev/#/1c979cb/161e00165900?v=0.7.1
23879
+ *
23880
+ * https://graypaper.fluffylabs.dev/#/ab2cdbd/161e00165900?v=0.7.2
23844
23881
  */
23845
23882
  const availabilityAssignment = input.assurancesAvailAssignment.slice();
23846
23883
  for (const guarantee of input.guarantees) {
@@ -23870,7 +23907,7 @@ class Reports {
23870
23907
  return asKnownSize(workReportHashes);
23871
23908
  }
23872
23909
  verifyCredentials(input, workReportHashes) {
23873
- return verifyCredentials(input.guarantees, workReportHashes, input.slot, (headerTimeSlot, guaranteeTimeSlot) => this.getGuarantorAssignment(headerTimeSlot, guaranteeTimeSlot, input.newEntropy));
23910
+ return verifyCredentials(input.guarantees, workReportHashes, input.slot, (headerTimeSlot, guaranteeTimeSlot) => this.getGuarantorAssignment(headerTimeSlot, guaranteeTimeSlot, input.newEntropy, input.currentValidatorData, input.previousValidatorData));
23874
23911
  }
23875
23912
  verifyPostSignatureChecks(input, assurancesAvailAssignment) {
23876
23913
  const authPoolsView = this.state.view().authPoolsView();
@@ -23898,15 +23935,15 @@ class Reports {
23898
23935
  * Get the guarantor assignment (both core and validator data)
23899
23936
  * depending on the rotation.
23900
23937
  *
23901
- * https://graypaper.fluffylabs.dev/#/5f542d7/158200158200
23938
+ * https://graypaper.fluffylabs.dev/#/ab2cdbd/15df0115df01?v=0.7.2
23902
23939
  */
23903
- getGuarantorAssignment(headerTimeSlot, guaranteeTimeSlot, newEntropy) {
23940
+ getGuarantorAssignment(headerTimeSlot, guaranteeTimeSlot, newEntropy, currentValidatorData, previousValidatorData) {
23904
23941
  const epochLength = this.chainSpec.epochLength;
23905
23942
  const rotationPeriod = this.chainSpec.rotationPeriod;
23906
23943
  const headerRotation = rotationIndex(headerTimeSlot, rotationPeriod);
23907
23944
  const guaranteeRotation = rotationIndex(guaranteeTimeSlot, rotationPeriod);
23908
23945
  const minTimeSlot = Math.max(0, headerRotation - 1) * rotationPeriod;
23909
- // https://graypaper.fluffylabs.dev/#/5f542d7/155e00156900
23946
+ // https://graypaper.fluffylabs.dev/#/ab2cdbd/15980115be01?v=0.7.2
23910
23947
  if (guaranteeTimeSlot > headerTimeSlot) {
23911
23948
  return Result$1.error(ReportsError.FutureReportSlot, () => `Report slot is in future. Block ${headerTimeSlot}, Report: ${guaranteeTimeSlot}`);
23912
23949
  }
@@ -23914,10 +23951,10 @@ class Reports {
23914
23951
  return Result$1.error(ReportsError.ReportEpochBeforeLast, () => `Report slot is too old. Block ${headerTimeSlot}, Report: ${guaranteeTimeSlot}`);
23915
23952
  }
23916
23953
  // TODO [ToDr] [opti] below code needs cache.
23917
- // The `G` and `G*` sets should only be computed once per rotation.
23954
+ // The `M` and `M*` sets should only be computed once per rotation.
23918
23955
  // Default data for the current rotation
23919
23956
  let entropy = newEntropy[2];
23920
- let validatorData = this.state.currentValidatorData;
23957
+ let validatorData = currentValidatorData;
23921
23958
  let timeSlot = headerTimeSlot;
23922
23959
  // we might need a different set of data
23923
23960
  if (headerRotation > guaranteeRotation) {
@@ -23927,11 +23964,11 @@ class Reports {
23927
23964
  // if the epoch changed, we need to take previous entropy and previous validator data.
23928
23965
  if (isPreviousRotationPreviousEpoch(timeSlot, headerTimeSlot, epochLength)) {
23929
23966
  entropy = newEntropy[3];
23930
- validatorData = this.state.previousValidatorData;
23967
+ validatorData = previousValidatorData;
23931
23968
  }
23932
23969
  }
23933
23970
  // we know which entropy, timeSlot and validatorData should be used,
23934
- // so we can compute `G` or `G*` here.
23971
+ // so we can compute `M` or `M*` here.
23935
23972
  const coreAssignment = generateCoreAssignment(this.chainSpec, this.blake2b, entropy, timeSlot);
23936
23973
  return Result$1.ok(zip(coreAssignment, validatorData, (core, validator) => ({
23937
23974
  core,
@@ -24099,22 +24136,23 @@ class Statistics {
24099
24136
  const newPreImagesSize = current[authorIndex].preImagesSize + preImagesSize;
24100
24137
  current[authorIndex].preImagesSize = tryAsU32(newPreImagesSize);
24101
24138
  /**
24102
- * * NOTE [MaSi] Please note I don't use Kappa' here. If I understand correctly we don't need it.
24103
- * Kappa' is not needed because we can use validator indexes directly from guarantees extrinsic.
24104
- * I asked a question to ensure it is true but I didn't get any response yet:
24105
- * https://github.com/w3f/jamtestvectors/pull/28#discussion_r190723700
24139
+ * Update guarantees
24106
24140
  *
24107
- * https://graypaper.fluffylabs.dev/#/1c979cb/19a00119a801?v=0.7.1
24141
+ * https://graypaper.fluffylabs.dev/#/ab2cdbd/19ea0119f201?v=0.7.2
24108
24142
  */
24109
- const incrementedGuarantors = new Set();
24110
- for (const guarantee of extrinsic.guarantees) {
24111
- for (const { validatorIndex } of guarantee.credentials) {
24112
- if (!incrementedGuarantors.has(validatorIndex)) {
24113
- const newGuaranteesCount = current[validatorIndex].guarantees + 1;
24114
- current[validatorIndex].guarantees = tryAsU32(newGuaranteesCount);
24115
- incrementedGuarantors.add(validatorIndex);
24116
- }
24143
+ const validatorKeys = input.currentValidatorData.map((v) => v.ed25519);
24144
+ for (const reporter of input.reporters) {
24145
+ const index = validatorKeys.findIndex((x) => x.isEqualTo(reporter));
24146
+ if (index === -1) {
24147
+ /**
24148
+ * it should never happen because:
24149
+ * 1. the extrinsic is verified in reports transition
24150
+ * 2. we use current validators set from safrole
24151
+ */
24152
+ continue;
24117
24153
  }
24154
+ const newGuaranteesCount = current[index].guarantees + 1;
24155
+ current[index].guarantees = tryAsU32(newGuaranteesCount);
24118
24156
  }
24119
24157
  for (const { validatorIndex } of extrinsic.assurances) {
24120
24158
  const newAssurancesCount = current[validatorIndex].assurances + 1;
@@ -24269,7 +24307,7 @@ class OnChain {
24269
24307
  // chapter 13: https://graypaper.fluffylabs.dev/#/68eaa1f/18b60118b601?v=0.6.4
24270
24308
  statistics;
24271
24309
  isReadyForNextEpoch = Promise.resolve(false);
24272
- constructor(chainSpec, state, hasher, pvm, headerChain) {
24310
+ constructor(chainSpec, state, hasher, options, headerChain) {
24273
24311
  this.chainSpec = chainSpec;
24274
24312
  this.state = state;
24275
24313
  this.hasher = hasher;
@@ -24281,9 +24319,9 @@ class OnChain {
24281
24319
  this.disputes = new Disputes(chainSpec, hasher.blake2b, state);
24282
24320
  this.reports = new Reports(chainSpec, hasher.blake2b, state, headerChain);
24283
24321
  this.assurances = new Assurances(chainSpec, state, hasher.blake2b);
24284
- this.accumulate = new Accumulate(chainSpec, hasher.blake2b, state, pvm);
24322
+ this.accumulate = new Accumulate(chainSpec, hasher.blake2b, state, options);
24285
24323
  this.accumulateOutput = new AccumulateOutput();
24286
- this.deferredTransfers = new DeferredTransfers(chainSpec, hasher.blake2b, state, pvm);
24324
+ this.deferredTransfers = new DeferredTransfers(chainSpec, hasher.blake2b, state, options.pvm);
24287
24325
  this.preimages = new Preimages(state, hasher.blake2b);
24288
24326
  this.authorization = new Authorization(chainSpec, state);
24289
24327
  }
@@ -24367,12 +24405,13 @@ class OnChain {
24367
24405
  recentBlocksPartialUpdate,
24368
24406
  assurancesAvailAssignment,
24369
24407
  offenders: offendersMark,
24408
+ currentValidatorData,
24409
+ previousValidatorData,
24370
24410
  });
24371
24411
  if (reportsResult.isError) {
24372
24412
  return stfError(StfErrorKind.Reports, reportsResult);
24373
24413
  }
24374
- // NOTE `reporters` are unused
24375
- const { reported: workPackages, reporters: _, stateUpdate: reportsUpdate, ...reportsRest } = reportsResult.ok;
24414
+ const { reported: workPackages, reporters, stateUpdate: reportsUpdate, ...reportsRest } = reportsResult.ok;
24376
24415
  assertEmpty(reportsRest);
24377
24416
  const { availabilityAssignment: reportsAvailAssignment, ...reportsUpdateRest } = reportsUpdate;
24378
24417
  assertEmpty(reportsUpdateRest);
@@ -24386,7 +24425,7 @@ class OnChain {
24386
24425
  }
24387
24426
  const { preimages, ...preimagesRest } = preimagesResult.ok;
24388
24427
  assertEmpty(preimagesRest);
24389
- const timerAccumulate = measure(`import:accumulate (${PvmBackend[this.accumulate.pvm]})`);
24428
+ const timerAccumulate = measure(`import:accumulate (${PvmBackend[this.accumulate.options.pvm]})`);
24390
24429
  // accumulate
24391
24430
  const accumulateResult = await this.accumulate.transition({
24392
24431
  slot: timeSlot,
@@ -24446,6 +24485,8 @@ class OnChain {
24446
24485
  availableReports,
24447
24486
  accumulationStatistics,
24448
24487
  transferStatistics,
24488
+ reporters: reporters,
24489
+ currentValidatorData,
24449
24490
  });
24450
24491
  const { statistics, ...statisticsRest } = statisticsUpdate;
24451
24492
  assertEmpty(statisticsRest);
@@ -24537,7 +24578,7 @@ class TransitionHasher {
24537
24578
  extrinsic(extrinsicView) {
24538
24579
  // https://graypaper.fluffylabs.dev/#/cc517d7/0cfb000cfb00?v=0.6.5
24539
24580
  const guaranteesCount = tryAsU32(extrinsicView.guarantees.view().length);
24540
- const countEncoded = Encoder.encodeObject(varU32, guaranteesCount);
24581
+ const countEncoded = Encoder.encodeObject(codec.varU32, guaranteesCount);
24541
24582
  const guaranteesBlobs = extrinsicView.guarantees
24542
24583
  .view()
24543
24584
  .map((g) => g.view())
@@ -25378,7 +25419,7 @@ var MetricsAPI = /** @class */ (function () {
25378
25419
  var metrics = MetricsAPI.getInstance();
25379
25420
 
25380
25421
  var name = "@typeberry/importer";
25381
- var version = "0.5.0";
25422
+ var version = "0.5.1";
25382
25423
  var packageJson = {
25383
25424
  name: name,
25384
25425
  version: version};
@@ -25488,7 +25529,7 @@ class Importer {
25488
25529
  throw new Error(`Unable to load best state from header hash: ${currentBestHeaderHash}.`);
25489
25530
  }
25490
25531
  this.verifier = new BlockVerifier(hasher, blocks);
25491
- this.stf = new OnChain(spec, state, hasher, pvm, DbHeaderChain.new(blocks));
25532
+ this.stf = new OnChain(spec, state, hasher, { pvm, accumulateSequentially: false }, DbHeaderChain.new(blocks));
25492
25533
  this.state = state;
25493
25534
  this.currentHash = currentBestHeaderHash;
25494
25535
  this.prepareForNextEpoch();
@@ -25634,11 +25675,11 @@ const blake2b = Blake2b.createHasher();
25634
25675
  async function createImporter(config) {
25635
25676
  const chainSpec = config.chainSpec;
25636
25677
  const db = config.openDatabase({ readonly: false });
25637
- const interpreter = config.workerParams.pvm;
25678
+ const pvm = config.workerParams.pvm;
25638
25679
  const blocks = db.getBlocksDb();
25639
25680
  const states = db.getStatesDb();
25640
25681
  const hasher = new TransitionHasher(await keccakHasher, await blake2b);
25641
- const importer = new Importer(chainSpec, interpreter, hasher, logger$1, blocks, states);
25682
+ const importer = new Importer(chainSpec, pvm, hasher, logger$1, blocks, states);
25642
25683
  return {
25643
25684
  importer,
25644
25685
  db,
@@ -25807,7 +25848,7 @@ class DirectWorkerConfig {
25807
25848
  workerParams;
25808
25849
  blocksDb;
25809
25850
  statesDb;
25810
- static new({ nodeName, chainSpec, blocksDb, statesDb, params, }) {
25851
+ static new({ nodeName, chainSpec, blocksDb, statesDb, workerParams: params, }) {
25811
25852
  return new DirectWorkerConfig(nodeName, chainSpec, params, blocksDb, statesDb);
25812
25853
  }
25813
25854
  constructor(nodeName, chainSpec, workerParams, blocksDb, statesDb) {
@@ -26251,7 +26292,7 @@ var index$3 = /*#__PURE__*/Object.freeze({
26251
26292
  startSameThread: startSameThread
26252
26293
  });
26253
26294
 
26254
- const importBlockResultCodec = (hashName) => custom({
26295
+ const importBlockResultCodec = (hashName) => codec.custom({
26255
26296
  name: `Result<${hashName}, string>`,
26256
26297
  sizeHint: { bytes: 1, isExact: false },
26257
26298
  }, (e, x) => {
@@ -26289,33 +26330,33 @@ const importBlockResultCodec = (hashName) => custom({
26289
26330
  const protocol = createProtocol("importer", {
26290
26331
  toWorker: {
26291
26332
  getStateEntries: {
26292
- request: bytes(HASH_SIZE).asOpaque(),
26293
- response: optional(StateEntries.Codec),
26333
+ request: codec.bytes(HASH_SIZE).asOpaque(),
26334
+ response: codec.optional(StateEntries.Codec),
26294
26335
  },
26295
26336
  getBestStateRootHash: {
26296
- request: nothing,
26297
- response: bytes(HASH_SIZE).asOpaque(),
26337
+ request: codec.nothing,
26338
+ response: codec.bytes(HASH_SIZE).asOpaque(),
26298
26339
  },
26299
26340
  importBlock: {
26300
26341
  request: Block.Codec.View,
26301
26342
  response: importBlockResultCodec("HeaderHash"),
26302
26343
  },
26303
26344
  finish: {
26304
- request: nothing,
26305
- response: nothing,
26345
+ request: codec.nothing,
26346
+ response: codec.nothing,
26306
26347
  },
26307
26348
  },
26308
26349
  fromWorker: {
26309
26350
  bestHeaderAnnouncement: {
26310
26351
  request: headerViewWithHashCodec,
26311
- response: nothing,
26352
+ response: codec.nothing,
26312
26353
  },
26313
26354
  },
26314
26355
  });
26315
26356
  class ImporterConfig {
26316
26357
  pvm;
26317
- static Codec = Class(ImporterConfig, {
26318
- pvm: u8.convert((i) => tryAsU8(i), (o) => {
26358
+ static Codec = codec.Class(ImporterConfig, {
26359
+ pvm: codec.u8.convert((i) => tryAsU8(i), (o) => {
26319
26360
  if (o === PvmBackend.BuiltIn) {
26320
26361
  return PvmBackend.BuiltIn;
26321
26362
  }
@@ -26333,7 +26374,7 @@ class ImporterConfig {
26333
26374
  }
26334
26375
  }
26335
26376
 
26336
- const WORKER = new URL(import.meta.resolve("./bootstrap-importer.mjs"));
26377
+ const WORKER = new URL("./bootstrap-importer.mjs", import.meta.url);
26337
26378
 
26338
26379
  var index$2 = /*#__PURE__*/Object.freeze({
26339
26380
  __proto__: null,
@@ -26780,11 +26821,11 @@ class TestState {
26780
26821
  state_root: fromJson.bytes32(),
26781
26822
  keyvals: json.array(StateKeyVal.fromJson),
26782
26823
  };
26783
- static Codec = object({
26784
- state_root: bytes(HASH_SIZE).asOpaque(),
26785
- keyvals: sequenceVarLen(object({
26786
- key: bytes(TRUNCATED_HASH_SIZE),
26787
- value: blob,
26824
+ static Codec = codec.object({
26825
+ state_root: codec.bytes(HASH_SIZE).asOpaque(),
26826
+ keyvals: codec.sequenceVarLen(codec.object({
26827
+ key: codec.bytes(TRUNCATED_HASH_SIZE),
26828
+ value: codec.blob,
26788
26829
  })),
26789
26830
  });
26790
26831
  state_root;
@@ -26795,7 +26836,7 @@ class StateTransitionGenesis {
26795
26836
  header: headerFromJson,
26796
26837
  state: TestState.fromJson,
26797
26838
  };
26798
- static Codec = object({
26839
+ static Codec = codec.object({
26799
26840
  header: Header.Codec,
26800
26841
  state: TestState.Codec,
26801
26842
  });
@@ -26808,7 +26849,7 @@ class StateTransition {
26808
26849
  post_state: TestState.fromJson,
26809
26850
  block: blockFromJson(tinyChainSpec),
26810
26851
  };
26811
- static Codec = object({
26852
+ static Codec = codec.object({
26812
26853
  pre_state: TestState.Codec,
26813
26854
  block: Block.Codec,
26814
26855
  post_state: TestState.Codec,