@typeberry/lib 0.1.1-e48de40 → 0.1.2-0416cb6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/index.js CHANGED
@@ -7,6 +7,7 @@ var GpVersion;
7
7
  GpVersion["V0_6_7"] = "0.6.7";
8
8
  GpVersion["V0_7_0"] = "0.7.0";
9
9
  GpVersion["V0_7_1"] = "0.7.1-preview";
10
+ GpVersion["V0_7_2"] = "0.7.2-preview";
10
11
  })(GpVersion || (GpVersion = {}));
11
12
  var TestSuite;
12
13
  (function (TestSuite) {
@@ -14,7 +15,7 @@ var TestSuite;
14
15
  TestSuite["JAMDUNA"] = "jamduna";
15
16
  })(TestSuite || (TestSuite = {}));
16
17
  const DEFAULT_SUITE = TestSuite.W3F_DAVXY;
17
- const ALL_VERSIONS_IN_ORDER = [GpVersion.V0_6_7, GpVersion.V0_7_0, GpVersion.V0_7_1];
18
+ const ALL_VERSIONS_IN_ORDER = [GpVersion.V0_6_7, GpVersion.V0_7_0, GpVersion.V0_7_1, GpVersion.V0_7_2];
18
19
  const env$1 = typeof process === "undefined" ? {} : process.env;
19
20
  const DEFAULT_VERSION = GpVersion.V0_7_0;
20
21
  let CURRENT_VERSION = parseCurrentVersion(env$1.GP_VERSION) ?? DEFAULT_VERSION;
@@ -23,20 +24,26 @@ function parseCurrentVersion(env) {
23
24
  if (env === undefined) {
24
25
  return undefined;
25
26
  }
26
- const version = env;
27
- if (!Object.values(GpVersion).includes(version)) {
28
- throw new Error(`Configured environment variable GP_VERSION is unknown: '${env}'. Use one of: ${ALL_VERSIONS_IN_ORDER}`);
27
+ switch (env) {
28
+ case GpVersion.V0_6_7:
29
+ case GpVersion.V0_7_0:
30
+ case GpVersion.V0_7_1:
31
+ case GpVersion.V0_7_2:
32
+ return env;
33
+ default:
34
+ throw new Error(`Configured environment variable GP_VERSION is unknown: '${env}'. Use one of: ${ALL_VERSIONS_IN_ORDER}`);
29
35
  }
30
- return version;
31
36
  }
32
37
  function parseCurrentSuite(env) {
33
38
  if (env === undefined)
34
39
  return undefined;
35
- const val = env;
36
- if (!Object.values(TestSuite).includes(val)) {
37
- throw new Error(`Configured environment variable TEST_SUITE is unknown: '${env}'. Use one of: ${Object.values(TestSuite)}`);
40
+ switch (env) {
41
+ case TestSuite.W3F_DAVXY:
42
+ case TestSuite.JAMDUNA:
43
+ return env;
44
+ default:
45
+ throw new Error(`Configured environment variable TEST_SUITE is unknown: '${env}'. Use one of: ${Object.values(TestSuite)}`);
38
46
  }
39
- return val;
40
47
  }
41
48
  class Compatibility {
42
49
  static override(version) {
@@ -553,7 +560,7 @@ function isResult(x) {
553
560
  * as an afterthought.
554
561
  */
555
562
 
556
- var index$s = /*#__PURE__*/Object.freeze({
563
+ var index$u = /*#__PURE__*/Object.freeze({
557
564
  __proto__: null,
558
565
  get CURRENT_SUITE () { return CURRENT_SUITE; },
559
566
  get CURRENT_VERSION () { return CURRENT_VERSION; },
@@ -707,7 +714,7 @@ class Ordering {
707
714
  }
708
715
  }
709
716
 
710
- var index$r = /*#__PURE__*/Object.freeze({
717
+ var index$t = /*#__PURE__*/Object.freeze({
711
718
  __proto__: null,
712
719
  Ordering: Ordering
713
720
  });
@@ -958,7 +965,7 @@ function u8ArraySameLengthEqual(self, other) {
958
965
  }
959
966
  const bytesBlobComparator = (a, b) => a.compare(b);
960
967
 
961
- var index$q = /*#__PURE__*/Object.freeze({
968
+ var index$s = /*#__PURE__*/Object.freeze({
962
969
  __proto__: null,
963
970
  BitVec: BitVec,
964
971
  Bytes: Bytes,
@@ -1060,7 +1067,7 @@ const minU64 = (a, ...values) => values.reduce((min, value) => (value > min ? mi
1060
1067
  /** Get the biggest value between U64 a and values given as input parameters. */
1061
1068
  const maxU64 = (a, ...values) => values.reduce((max, value) => (value < max ? max : value), a);
1062
1069
 
1063
- var index$p = /*#__PURE__*/Object.freeze({
1070
+ var index$r = /*#__PURE__*/Object.freeze({
1064
1071
  __proto__: null,
1065
1072
  isU16: isU16,
1066
1073
  isU32: isU32,
@@ -2470,7 +2477,7 @@ function sequenceViewFixLen(type, { fixedLength }) {
2470
2477
  }, skipper);
2471
2478
  }
2472
2479
 
2473
- var index$o = /*#__PURE__*/Object.freeze({
2480
+ var index$q = /*#__PURE__*/Object.freeze({
2474
2481
  __proto__: null,
2475
2482
  Decoder: Decoder,
2476
2483
  Descriptor: Descriptor,
@@ -4909,7 +4916,7 @@ var keccak = /*#__PURE__*/Object.freeze({
4909
4916
  hashBlobs: hashBlobs
4910
4917
  });
4911
4918
 
4912
- var index$n = /*#__PURE__*/Object.freeze({
4919
+ var index$p = /*#__PURE__*/Object.freeze({
4913
4920
  __proto__: null,
4914
4921
  HASH_SIZE: HASH_SIZE,
4915
4922
  PageAllocator: PageAllocator,
@@ -4975,7 +4982,7 @@ var keyDerivation = /*#__PURE__*/Object.freeze({
4975
4982
  trivialSeed: trivialSeed
4976
4983
  });
4977
4984
 
4978
- var index$m = /*#__PURE__*/Object.freeze({
4985
+ var index$o = /*#__PURE__*/Object.freeze({
4979
4986
  __proto__: null,
4980
4987
  BANDERSNATCH_KEY_BYTES: BANDERSNATCH_KEY_BYTES,
4981
4988
  BANDERSNATCH_PROOF_BYTES: BANDERSNATCH_PROOF_BYTES,
@@ -5579,7 +5586,7 @@ class TruncatedHashDictionary {
5579
5586
  }
5580
5587
  }
5581
5588
 
5582
- var index$l = /*#__PURE__*/Object.freeze({
5589
+ var index$n = /*#__PURE__*/Object.freeze({
5583
5590
  __proto__: null,
5584
5591
  FixedSizeArray: FixedSizeArray,
5585
5592
  HashDictionary: HashDictionary,
@@ -5774,7 +5781,7 @@ class Bootnode {
5774
5781
  }
5775
5782
  }
5776
5783
 
5777
- var index$k = /*#__PURE__*/Object.freeze({
5784
+ var index$m = /*#__PURE__*/Object.freeze({
5778
5785
  __proto__: null,
5779
5786
  Bootnode: Bootnode,
5780
5787
  ChainSpec: ChainSpec,
@@ -5947,6 +5954,40 @@ var assurances = /*#__PURE__*/Object.freeze({
5947
5954
  assurancesExtrinsicCodec: assurancesExtrinsicCodec
5948
5955
  });
5949
5956
 
5957
+ /** Attempt to convert a number into `TimeSlot`. */
5958
+ const tryAsTimeSlot = (v) => asOpaqueType(tryAsU32(v));
5959
+ /** Attempt to convert a number into `ValidatorIndex`. */
5960
+ const tryAsValidatorIndex = (v) => asOpaqueType(tryAsU16(v));
5961
+ /** Attempt to convert a number into `ServiceId`. */
5962
+ const tryAsServiceId = (v) => asOpaqueType(tryAsU32(v));
5963
+ const tryAsServiceGas = (v) => asOpaqueType(tryAsU64(v));
5964
+ /** Attempt to convert a number into `CoreIndex`. */
5965
+ const tryAsCoreIndex = (v) => asOpaqueType(tryAsU16(v));
5966
+ /** Attempt to convert a number into `Epoch`. */
5967
+ const tryAsEpoch = (v) => asOpaqueType(tryAsU32(v));
5968
+ function tryAsPerValidator(array, spec) {
5969
+ check `
5970
+ ${array.length === spec.validatorsCount}
5971
+ Invalid per-validator array length. Expected ${spec.validatorsCount}, got: ${array.length}
5972
+ `;
5973
+ return asKnownSize(array);
5974
+ }
5975
+ const codecPerValidator = (val) => codecWithContext((context) => {
5976
+ return codecKnownSizeArray(val, {
5977
+ fixedLength: context.validatorsCount,
5978
+ });
5979
+ });
5980
+ function tryAsPerEpochBlock(array, spec) {
5981
+ check `
5982
+ ${array.length === spec.epochLength}
5983
+ Invalid per-epoch-block array length. Expected ${spec.epochLength}, got: ${array.length}
5984
+ `;
5985
+ return asKnownSize(array);
5986
+ }
5987
+ const codecPerEpochBlock = (val) => codecWithContext((context) => {
5988
+ return codecKnownSizeArray(val, { fixedLength: context.epochLength });
5989
+ });
5990
+
5950
5991
  /**
5951
5992
  * Proof of signing a contradictory [`Judgement`] of a work report.
5952
5993
  */
@@ -6138,40 +6179,6 @@ var disputes = /*#__PURE__*/Object.freeze({
6138
6179
  Verdict: Verdict
6139
6180
  });
6140
6181
 
6141
- /** Attempt to convert a number into `TimeSlot`. */
6142
- const tryAsTimeSlot = (v) => asOpaqueType(tryAsU32(v));
6143
- /** Attempt to convert a number into `ValidatorIndex`. */
6144
- const tryAsValidatorIndex = (v) => asOpaqueType(tryAsU16(v));
6145
- /** Attempt to convert a number into `ServiceId`. */
6146
- const tryAsServiceId = (v) => asOpaqueType(tryAsU32(v));
6147
- const tryAsServiceGas = (v) => asOpaqueType(tryAsU64(v));
6148
- /** Attempt to convert a number into `CoreIndex`. */
6149
- const tryAsCoreIndex = (v) => asOpaqueType(tryAsU16(v));
6150
- /** Attempt to convert a number into `Epoch`. */
6151
- const tryAsEpoch = (v) => asOpaqueType(tryAsU32(v));
6152
- function tryAsPerValidator(array, spec) {
6153
- check `
6154
- ${array.length === spec.validatorsCount}
6155
- Invalid per-validator array length. Expected ${spec.validatorsCount}, got: ${array.length}
6156
- `;
6157
- return asKnownSize(array);
6158
- }
6159
- const codecPerValidator = (val) => codecWithContext((context) => {
6160
- return codecKnownSizeArray(val, {
6161
- fixedLength: context.validatorsCount,
6162
- });
6163
- });
6164
- function tryAsPerEpochBlock(array, spec) {
6165
- check `
6166
- ${array.length === spec.epochLength}
6167
- Invalid per-epoch-block array length. Expected ${spec.epochLength}, got: ${array.length}
6168
- `;
6169
- return asKnownSize(array);
6170
- }
6171
- const codecPerEpochBlock = (val) => codecWithContext((context) => {
6172
- return codecKnownSizeArray(val, { fixedLength: context.epochLength });
6173
- });
6174
-
6175
6182
  /**
6176
6183
  * Mapping between work package hash and root hash of it's exports.
6177
6184
  *
@@ -7250,8 +7257,26 @@ class Block extends WithDebug {
7250
7257
  this.extrinsic = extrinsic;
7251
7258
  }
7252
7259
  }
7260
+ function emptyBlock(slot = tryAsTimeSlot(0)) {
7261
+ const header = Header.empty();
7262
+ header.timeSlotIndex = slot;
7263
+ return Block.create({
7264
+ header,
7265
+ extrinsic: Extrinsic.create({
7266
+ tickets: asKnownSize([]),
7267
+ preimages: [],
7268
+ assurances: asKnownSize([]),
7269
+ guarantees: asKnownSize([]),
7270
+ disputes: {
7271
+ verdicts: [],
7272
+ culprits: [],
7273
+ faults: [],
7274
+ },
7275
+ }),
7276
+ });
7277
+ }
7253
7278
 
7254
- var index$j = /*#__PURE__*/Object.freeze({
7279
+ var index$l = /*#__PURE__*/Object.freeze({
7255
7280
  __proto__: null,
7256
7281
  Block: Block,
7257
7282
  EpochMarker: EpochMarker,
@@ -7266,6 +7291,7 @@ var index$j = /*#__PURE__*/Object.freeze({
7266
7291
  codecPerValidator: codecPerValidator,
7267
7292
  codecUtils: codec,
7268
7293
  disputes: disputes,
7294
+ emptyBlock: emptyBlock,
7269
7295
  encodeUnsealedHeader: encodeUnsealedHeader,
7270
7296
  guarantees: guarantees,
7271
7297
  headerViewWithHashCodec: headerViewWithHashCodec,
@@ -7506,7 +7532,7 @@ var json;
7506
7532
  json.object = object;
7507
7533
  })(json || (json = {}));
7508
7534
 
7509
- var index$i = /*#__PURE__*/Object.freeze({
7535
+ var index$k = /*#__PURE__*/Object.freeze({
7510
7536
  __proto__: null,
7511
7537
  get json () { return json; },
7512
7538
  parseFromJson: parseFromJson
@@ -7776,7 +7802,7 @@ const blockFromJson = (spec) => json.object({
7776
7802
  extrinsic: getExtrinsicFromJson(spec),
7777
7803
  }, ({ header, extrinsic }) => Block.create({ header, extrinsic }));
7778
7804
 
7779
- var index$h = /*#__PURE__*/Object.freeze({
7805
+ var index$j = /*#__PURE__*/Object.freeze({
7780
7806
  __proto__: null,
7781
7807
  blockFromJson: blockFromJson,
7782
7808
  disputesExtrinsicFromJson: disputesExtrinsicFromJson,
@@ -8042,8 +8068,8 @@ function print(level, levelAndName, strings, data) {
8042
8068
  return;
8043
8069
  }
8044
8070
  const lvlText = Level[level].padEnd(5);
8045
- const val = strings.map((v, idx) => `${v}${data[idx]}`);
8046
- const msg = `${lvlText} [${levelAndName[1]}] ${val}`;
8071
+ const val = strings.map((v, idx) => `${v}${idx < data.length ? data[idx] : ""}`);
8072
+ const msg = `${lvlText} [${levelAndName[1]}] ${val.join("")}`;
8047
8073
  if (level === Level.WARN) {
8048
8074
  console.warn(msg);
8049
8075
  }
@@ -8274,7 +8300,7 @@ class Logger {
8274
8300
  }
8275
8301
  }
8276
8302
 
8277
- var index$g = /*#__PURE__*/Object.freeze({
8303
+ var index$i = /*#__PURE__*/Object.freeze({
8278
8304
  __proto__: null,
8279
8305
  get Level () { return Level; },
8280
8306
  Logger: Logger,
@@ -8297,7 +8323,7 @@ class AuthorshipOptions {
8297
8323
  }
8298
8324
  }
8299
8325
 
8300
- const logger$4 = Logger.new(import.meta.filename, "config");
8326
+ const logger$5 = Logger.new(import.meta.filename, "config");
8301
8327
  /** Development config. Will accept unsealed blocks for now. */
8302
8328
  const DEV_CONFIG = "dev";
8303
8329
  /** Default config file. */
@@ -8356,15 +8382,15 @@ class NodeConfiguration {
8356
8382
  }
8357
8383
  function loadConfig(configPath) {
8358
8384
  if (configPath === DEFAULT_CONFIG) {
8359
- logger$4.log `🔧 Loading DEFAULT config`;
8385
+ logger$5.log `🔧 Loading DEFAULT config`;
8360
8386
  return parseFromJson(configs.default, NodeConfiguration.fromJson);
8361
8387
  }
8362
8388
  if (configPath === DEV_CONFIG) {
8363
- logger$4.log `🔧 Loading DEV config`;
8389
+ logger$5.log `🔧 Loading DEV config`;
8364
8390
  return parseFromJson(configs.dev, NodeConfiguration.fromJson);
8365
8391
  }
8366
8392
  try {
8367
- logger$4.log `🔧 Loading config from ${configPath}`;
8393
+ logger$5.log `🔧 Loading config from ${configPath}`;
8368
8394
  const configFile = fs.readFileSync(configPath, "utf8");
8369
8395
  const parsed = JSON.parse(configFile);
8370
8396
  return parseFromJson(parsed, NodeConfiguration.fromJson);
@@ -8374,7 +8400,7 @@ function loadConfig(configPath) {
8374
8400
  }
8375
8401
  }
8376
8402
 
8377
- var index$f = /*#__PURE__*/Object.freeze({
8403
+ var index$h = /*#__PURE__*/Object.freeze({
8378
8404
  __proto__: null,
8379
8405
  DEFAULT_CONFIG: DEFAULT_CONFIG,
8380
8406
  DEV_CONFIG: DEV_CONFIG,
@@ -10040,7 +10066,7 @@ const serviceDataCodec = codec$1.dictionary(codec$1.u32.asOpaque(), serviceEntri
10040
10066
  sortKeys: (a, b) => a - b,
10041
10067
  });
10042
10068
 
10043
- var index$e = /*#__PURE__*/Object.freeze({
10069
+ var index$g = /*#__PURE__*/Object.freeze({
10044
10070
  __proto__: null,
10045
10071
  AccumulationOutput: AccumulationOutput,
10046
10072
  AutoAccumulate: AutoAccumulate,
@@ -11050,7 +11076,7 @@ const bitLookup = [
11050
11076
  [0b00000000, 8],
11051
11077
  ];
11052
11078
 
11053
- var index$d = /*#__PURE__*/Object.freeze({
11079
+ var index$f = /*#__PURE__*/Object.freeze({
11054
11080
  __proto__: null,
11055
11081
  BranchNode: BranchNode,
11056
11082
  InMemoryTrie: InMemoryTrie,
@@ -11396,7 +11422,7 @@ function loadState(spec, entries) {
11396
11422
  * hashmap of `key -> value` entries.
11397
11423
  */
11398
11424
 
11399
- var index$c = /*#__PURE__*/Object.freeze({
11425
+ var index$e = /*#__PURE__*/Object.freeze({
11400
11426
  __proto__: null,
11401
11427
  SerializedService: SerializedService,
11402
11428
  SerializedState: SerializedState,
@@ -11682,7 +11708,7 @@ class InMemoryStates {
11682
11708
  }
11683
11709
  }
11684
11710
 
11685
- var index$b = /*#__PURE__*/Object.freeze({
11711
+ var index$d = /*#__PURE__*/Object.freeze({
11686
11712
  __proto__: null,
11687
11713
  InMemoryBlocks: InMemoryBlocks,
11688
11714
  InMemoryStates: InMemoryStates,
@@ -12044,7 +12070,7 @@ const initEc = async () => {
12044
12070
  await init.reedSolomon();
12045
12071
  };
12046
12072
 
12047
- var index$a = /*#__PURE__*/Object.freeze({
12073
+ var index$c = /*#__PURE__*/Object.freeze({
12048
12074
  __proto__: null,
12049
12075
  N_CHUNKS_REDUNDANCY: N_CHUNKS_REDUNDANCY,
12050
12076
  N_CHUNKS_REQUIRED: N_CHUNKS_REQUIRED,
@@ -12068,6 +12094,439 @@ var index$a = /*#__PURE__*/Object.freeze({
12068
12094
  unzip: unzip
12069
12095
  });
12070
12096
 
12097
+ /**
12098
+ * Version ::= SEQUENCE {
12099
+ * major INTEGER (0..255),
12100
+ * minor INTEGER (0..255),
12101
+ * patch INTEGER (0..255)
12102
+ * }
12103
+ */
12104
+ class Version extends WithDebug {
12105
+ major;
12106
+ minor;
12107
+ patch;
12108
+ static Codec = codec$1.Class(Version, {
12109
+ major: codec$1.u8,
12110
+ minor: codec$1.u8,
12111
+ patch: codec$1.u8,
12112
+ });
12113
+ static tryFromString(str) {
12114
+ const parse = (v) => tryAsU8(Number(v));
12115
+ try {
12116
+ const [major, minor, patch] = str.trim().split(".").map(parse);
12117
+ return Version.create({
12118
+ major,
12119
+ minor,
12120
+ patch,
12121
+ });
12122
+ }
12123
+ catch (e) {
12124
+ throw new Error(`Unable to parse ${str} as Version: ${e}`);
12125
+ }
12126
+ }
12127
+ static create({ major, minor, patch }) {
12128
+ return new Version(major, minor, patch);
12129
+ }
12130
+ constructor(major, minor, patch) {
12131
+ super();
12132
+ this.major = major;
12133
+ this.minor = minor;
12134
+ this.patch = patch;
12135
+ }
12136
+ }
12137
+ /**
12138
+ * Fuzzer Protocol V1
12139
+ * Reference: https://github.com/davxy/jam-conformance/blob/main/fuzz-proto/fuzz.asn
12140
+ */
12141
+ // Feature bit constants
12142
+ var Features;
12143
+ (function (Features) {
12144
+ Features[Features["Ancestry"] = 1] = "Ancestry";
12145
+ Features[Features["Fork"] = 2] = "Fork";
12146
+ Features[Features["Reserved"] = 2147483648] = "Reserved";
12147
+ })(Features || (Features = {}));
12148
+ /**
12149
+ * PeerInfo ::= SEQUENCE {
12150
+ * fuzz-version U8,
12151
+ * features Features,
12152
+ * jam-version Version,
12153
+ * app-version Version,
12154
+ * name UTF8String
12155
+ * }
12156
+ */
12157
+ class PeerInfo extends WithDebug {
12158
+ fuzzVersion;
12159
+ features;
12160
+ jamVersion;
12161
+ appVersion;
12162
+ name;
12163
+ static Codec = codec$1.Class(PeerInfo, {
12164
+ fuzzVersion: codec$1.u8,
12165
+ features: codec$1.u32,
12166
+ jamVersion: Version.Codec,
12167
+ appVersion: Version.Codec,
12168
+ name: codec$1.string,
12169
+ });
12170
+ static create({ fuzzVersion, features, appVersion, jamVersion, name }) {
12171
+ return new PeerInfo(fuzzVersion, features, jamVersion, appVersion, name);
12172
+ }
12173
+ constructor(fuzzVersion, features, jamVersion, appVersion, name) {
12174
+ super();
12175
+ this.fuzzVersion = fuzzVersion;
12176
+ this.features = features;
12177
+ this.jamVersion = jamVersion;
12178
+ this.appVersion = appVersion;
12179
+ this.name = name;
12180
+ }
12181
+ }
12182
+ /**
12183
+ * AncestryItem ::= SEQUENCE {
12184
+ * slot TimeSlot,
12185
+ * header-hash HeaderHash
12186
+ * }
12187
+ */
12188
+ class AncestryItem extends WithDebug {
12189
+ slot;
12190
+ headerHash;
12191
+ static Codec = codec$1.Class(AncestryItem, {
12192
+ slot: codec$1.u32.asOpaque(),
12193
+ headerHash: codec$1.bytes(HASH_SIZE).asOpaque(),
12194
+ });
12195
+ static create({ slot, headerHash }) {
12196
+ return new AncestryItem(slot, headerHash);
12197
+ }
12198
+ constructor(slot, headerHash) {
12199
+ super();
12200
+ this.slot = slot;
12201
+ this.headerHash = headerHash;
12202
+ }
12203
+ }
12204
+ /**
12205
+ * KeyValue ::= SEQUENCE {
12206
+ * key TrieKey,
12207
+ * value OCTET STRING
12208
+ * }
12209
+ */
12210
+ class KeyValue extends WithDebug {
12211
+ key;
12212
+ value;
12213
+ static Codec = codec$1.Class(KeyValue, {
12214
+ key: codec$1.bytes(TRUNCATED_HASH_SIZE),
12215
+ value: codec$1.blob,
12216
+ });
12217
+ static create({ key, value }) {
12218
+ return new KeyValue(key, value);
12219
+ }
12220
+ constructor(key, value) {
12221
+ super();
12222
+ this.key = key;
12223
+ this.value = value;
12224
+ }
12225
+ }
12226
+ /** State ::= SEQUENCE OF KeyValue */
12227
+ const stateCodec = codec$1.sequenceVarLen(KeyValue.Codec);
12228
+ /**
12229
+ * Ancestry ::= SEQUENCE (SIZE(0..24)) OF AncestryItem
12230
+ * Empty when `feature-ancestry` is not supported by both parties
12231
+ */
12232
+ const ancestryCodec = codec$1.sequenceVarLen(AncestryItem.Codec, {
12233
+ minLength: 0,
12234
+ maxLength: 24,
12235
+ });
12236
+ /**
12237
+ * Initialize ::= SEQUENCE {
12238
+ * header Header,
12239
+ * keyvals State,
12240
+ * ancestry Ancestry
12241
+ * }
12242
+ */
12243
+ class Initialize extends WithDebug {
12244
+ header;
12245
+ keyvals;
12246
+ ancestry;
12247
+ static Codec = codec$1.Class(Initialize, {
12248
+ header: Header.Codec,
12249
+ keyvals: stateCodec,
12250
+ ancestry: ancestryCodec,
12251
+ });
12252
+ static create({ header, keyvals, ancestry }) {
12253
+ return new Initialize(header, keyvals, ancestry);
12254
+ }
12255
+ constructor(header, keyvals, ancestry) {
12256
+ super();
12257
+ this.header = header;
12258
+ this.keyvals = keyvals;
12259
+ this.ancestry = ancestry;
12260
+ }
12261
+ }
12262
+ /** GetState ::= HeaderHash */
12263
+ const getStateCodec = codec$1.bytes(HASH_SIZE).asOpaque();
12264
+ /** StateRoot ::= StateRootHash */
12265
+ const stateRootCodec = codec$1.bytes(HASH_SIZE).asOpaque();
12266
+ /** Error ::= UTF8String */
12267
+ class ErrorMessage extends WithDebug {
12268
+ message;
12269
+ static Codec = codec$1.Class(ErrorMessage, {
12270
+ message: codec$1.string,
12271
+ });
12272
+ static create({ message }) {
12273
+ return new ErrorMessage(message);
12274
+ }
12275
+ constructor(message) {
12276
+ super();
12277
+ this.message = message;
12278
+ }
12279
+ }
12280
+ /** Message choice type tags */
12281
+ var MessageType;
12282
+ (function (MessageType) {
12283
+ MessageType[MessageType["PeerInfo"] = 0] = "PeerInfo";
12284
+ MessageType[MessageType["Initialize"] = 1] = "Initialize";
12285
+ MessageType[MessageType["StateRoot"] = 2] = "StateRoot";
12286
+ MessageType[MessageType["ImportBlock"] = 3] = "ImportBlock";
12287
+ MessageType[MessageType["GetState"] = 4] = "GetState";
12288
+ MessageType[MessageType["State"] = 5] = "State";
12289
+ MessageType[MessageType["Error"] = 255] = "Error";
12290
+ })(MessageType || (MessageType = {}));
12291
+ /**
12292
+ * Message ::= CHOICE {
12293
+ * peer-info [0] PeerInfo,
12294
+ * initialize [1] Initialize,
12295
+ * state-root [2] StateRoot,
12296
+ * import-block [3] ImportBlock,
12297
+ * get-state [4] GetState,
12298
+ * state [5] State,
12299
+ * error [255] Error
12300
+ * }
12301
+ */
12302
+ const messageCodec = codec$1.custom({
12303
+ name: "Message",
12304
+ sizeHint: { bytes: 1, isExact: false },
12305
+ }, (e, msg) => {
12306
+ e.i8(msg.type);
12307
+ switch (msg.type) {
12308
+ case MessageType.PeerInfo:
12309
+ PeerInfo.Codec.encode(e, msg.value);
12310
+ break;
12311
+ case MessageType.Initialize:
12312
+ Initialize.Codec.encode(e, msg.value);
12313
+ break;
12314
+ case MessageType.StateRoot:
12315
+ stateRootCodec.encode(e, msg.value);
12316
+ break;
12317
+ case MessageType.ImportBlock:
12318
+ Block.Codec.View.encode(e, msg.value);
12319
+ break;
12320
+ case MessageType.GetState:
12321
+ getStateCodec.encode(e, msg.value);
12322
+ break;
12323
+ case MessageType.State:
12324
+ stateCodec.encode(e, msg.value);
12325
+ break;
12326
+ case MessageType.Error:
12327
+ ErrorMessage.Codec.encode(e, msg.value);
12328
+ break;
12329
+ default:
12330
+ throw new Error(`Unknown message type: ${msg}`);
12331
+ }
12332
+ }, (d) => {
12333
+ const type = d.u8();
12334
+ switch (type) {
12335
+ case MessageType.PeerInfo:
12336
+ return { type: MessageType.PeerInfo, value: PeerInfo.Codec.decode(d) };
12337
+ case MessageType.Initialize:
12338
+ return { type: MessageType.Initialize, value: Initialize.Codec.decode(d) };
12339
+ case MessageType.StateRoot:
12340
+ return { type: MessageType.StateRoot, value: stateRootCodec.decode(d) };
12341
+ case MessageType.ImportBlock:
12342
+ return { type: MessageType.ImportBlock, value: Block.Codec.View.decode(d) };
12343
+ case MessageType.GetState:
12344
+ return { type: MessageType.GetState, value: getStateCodec.decode(d) };
12345
+ case MessageType.State:
12346
+ return { type: MessageType.State, value: stateCodec.decode(d) };
12347
+ case MessageType.Error:
12348
+ return { type: MessageType.Error, value: ErrorMessage.Codec.decode(d) };
12349
+ default:
12350
+ throw new Error(`Unknown message type: ${type}`);
12351
+ }
12352
+ }, (s) => {
12353
+ const type = s.decoder.u8();
12354
+ switch (type) {
12355
+ case MessageType.PeerInfo:
12356
+ PeerInfo.Codec.View.skip(s);
12357
+ break;
12358
+ case MessageType.Initialize:
12359
+ Initialize.Codec.View.skip(s);
12360
+ break;
12361
+ case MessageType.StateRoot:
12362
+ stateRootCodec.View.skip(s);
12363
+ break;
12364
+ case MessageType.ImportBlock:
12365
+ Block.Codec.View.skip(s);
12366
+ break;
12367
+ case MessageType.GetState:
12368
+ getStateCodec.View.skip(s);
12369
+ break;
12370
+ case MessageType.State:
12371
+ stateCodec.View.skip(s);
12372
+ break;
12373
+ case MessageType.Error:
12374
+ ErrorMessage.Codec.View.skip(s);
12375
+ break;
12376
+ default:
12377
+ throw new Error(`Unknown message type: ${type}`);
12378
+ }
12379
+ });
12380
+
12381
+ const logger$4 = Logger.new(import.meta.filename, "ext-ipc-fuzz-v1");
12382
+ class FuzzTarget {
12383
+ msgHandler;
12384
+ sender;
12385
+ spec;
12386
+ sessionFeatures = 0;
12387
+ constructor(msgHandler, sender, spec) {
12388
+ this.msgHandler = msgHandler;
12389
+ this.sender = sender;
12390
+ this.spec = spec;
12391
+ }
12392
+ async onSocketMessage(msg) {
12393
+ // attempt to decode the messsage
12394
+ try {
12395
+ const message = Decoder.decodeObject(messageCodec, msg, this.spec);
12396
+ logger$4.log `[${message.type}] incoming message`;
12397
+ await this.processAndRespond(message);
12398
+ }
12399
+ catch (e) {
12400
+ logger$4.error `Error while processing fuzz v1 message: ${e}`;
12401
+ logger$4.error `${e}`;
12402
+ if (e instanceof Error) {
12403
+ logger$4.error `${e.stack ?? ""}`;
12404
+ }
12405
+ this.sender.close();
12406
+ }
12407
+ }
12408
+ async processAndRespond(message) {
12409
+ let response = null;
12410
+ switch (message.type) {
12411
+ case MessageType.PeerInfo: {
12412
+ // only support V1
12413
+ if (message.value.fuzzVersion !== 1) {
12414
+ logger$4.warn `Unsupported fuzzer protocol version: ${message.value.fuzzVersion}. Closing`;
12415
+ this.sender.close();
12416
+ return;
12417
+ }
12418
+ // Handle handshake
12419
+ const ourPeerInfo = await this.msgHandler.getPeerInfo(message.value);
12420
+ // Calculate session features (intersection of both peer features)
12421
+ this.sessionFeatures = message.value.features & ourPeerInfo.features;
12422
+ logger$4.info `Handshake completed. Shared features: 0b${this.sessionFeatures.toString(2)}`;
12423
+ logger$4.log `Feature ancestry: ${(this.sessionFeatures & Features.Ancestry) !== 0}`;
12424
+ logger$4.log `Feature fork: ${(this.sessionFeatures & Features.Fork) !== 0}`;
12425
+ response = {
12426
+ type: MessageType.PeerInfo,
12427
+ value: ourPeerInfo,
12428
+ };
12429
+ break;
12430
+ }
12431
+ case MessageType.Initialize: {
12432
+ const stateRoot = await this.msgHandler.initialize(message.value);
12433
+ response = {
12434
+ type: MessageType.StateRoot,
12435
+ value: stateRoot,
12436
+ };
12437
+ break;
12438
+ }
12439
+ case MessageType.ImportBlock: {
12440
+ const result = await this.msgHandler.importBlock(message.value);
12441
+ if (result.isOk) {
12442
+ response = {
12443
+ type: MessageType.StateRoot,
12444
+ value: result.ok,
12445
+ };
12446
+ }
12447
+ else {
12448
+ response = {
12449
+ type: MessageType.Error,
12450
+ value: result.error,
12451
+ };
12452
+ }
12453
+ break;
12454
+ }
12455
+ case MessageType.GetState: {
12456
+ const state = await this.msgHandler.getSerializedState(message.value);
12457
+ response = {
12458
+ type: MessageType.State,
12459
+ value: state,
12460
+ };
12461
+ break;
12462
+ }
12463
+ case MessageType.StateRoot: {
12464
+ logger$4.log `--> Received unexpected 'StateRoot' message from the fuzzer. Closing.`;
12465
+ this.sender.close();
12466
+ return;
12467
+ }
12468
+ case MessageType.State: {
12469
+ logger$4.log `--> Received unexpected 'State' message from the fuzzer. Closing.`;
12470
+ this.sender.close();
12471
+ return;
12472
+ }
12473
+ case MessageType.Error: {
12474
+ logger$4.log `--> Received unexpected 'Error' message from the fuzzer. Closing.`;
12475
+ this.sender.close();
12476
+ return;
12477
+ }
12478
+ default: {
12479
+ logger$4.log `--> Received unexpected message type ${JSON.stringify(message)} from the fuzzer. Closing.`;
12480
+ this.sender.close();
12481
+ try {
12482
+ assertNever(message);
12483
+ }
12484
+ catch {
12485
+ return;
12486
+ }
12487
+ }
12488
+ }
12489
+ if (response !== null) {
12490
+ logger$4.trace `<-- responding with: ${response.type}`;
12491
+ const encoded = Encoder.encodeObject(messageCodec, response, this.spec);
12492
+ this.sender.send(encoded);
12493
+ }
12494
+ else {
12495
+ logger$4.warn `<-- no response generated for: ${message.type}`;
12496
+ }
12497
+ }
12498
+ onClose({ error }) {
12499
+ logger$4.log `Closing the v1 handler. Reason: ${error !== undefined ? error.message : "close"}.`;
12500
+ }
12501
+ /** Check if a specific feature is enabled in the session */
12502
+ hasFeature(feature) {
12503
+ return (this.sessionFeatures & feature) !== 0;
12504
+ }
12505
+ }
12506
+
12507
+ var index$b = /*#__PURE__*/Object.freeze({
12508
+ __proto__: null,
12509
+ AncestryItem: AncestryItem,
12510
+ ErrorMessage: ErrorMessage,
12511
+ get Features () { return Features; },
12512
+ FuzzTarget: FuzzTarget,
12513
+ Initialize: Initialize,
12514
+ KeyValue: KeyValue,
12515
+ get MessageType () { return MessageType; },
12516
+ PeerInfo: PeerInfo,
12517
+ Version: Version,
12518
+ ancestryCodec: ancestryCodec,
12519
+ getStateCodec: getStateCodec,
12520
+ messageCodec: messageCodec,
12521
+ stateCodec: stateCodec,
12522
+ stateRootCodec: stateRootCodec
12523
+ });
12524
+
12525
+ var index$a = /*#__PURE__*/Object.freeze({
12526
+ __proto__: null,
12527
+ v1: index$b
12528
+ });
12529
+
12071
12530
  /** Size of the transfer memo. */
12072
12531
  const TRANSFER_MEMO_BYTES = W_T;
12073
12532
  /**
@@ -12394,16 +12853,12 @@ class PartiallyUpdatedState {
12394
12853
  *
12395
12854
  * NOTE the info may be updated compared to what is in the state.
12396
12855
  *
12397
- * Takes into account newly created services as well.
12856
+ * Takes into account ejected and newly created services as well.
12398
12857
  */
12399
12858
  getServiceInfo(destination) {
12400
12859
  if (destination === null) {
12401
12860
  return null;
12402
12861
  }
12403
- const isEjected = this.stateUpdate.services.servicesRemoved.some((x) => x === destination);
12404
- if (isEjected) {
12405
- return null;
12406
- }
12407
12862
  const maybeNewService = this.stateUpdate.services.servicesUpdates.find((update) => update.serviceId === destination);
12408
12863
  if (maybeNewService !== undefined) {
12409
12864
  return maybeNewService.action.account;
@@ -14119,6 +14574,17 @@ class PageRange {
14119
14574
  }
14120
14575
  return new PageRange(start, length);
14121
14576
  }
14577
+ /** Returns true if the page range is wrapped (`start` >= `end`) and is not empty */
14578
+ isWrapped() {
14579
+ return this.start >= this.end && !this.isEmpty();
14580
+ }
14581
+ /** Checks if given page number is within the range */
14582
+ isInRange(page) {
14583
+ if (this.isWrapped()) {
14584
+ return page >= this.start || page < this.end;
14585
+ }
14586
+ return page >= this.start && page < this.end;
14587
+ }
14122
14588
  /** Checks if a range is empty (`length === 0`) */
14123
14589
  isEmpty() {
14124
14590
  return this.length === 0;
@@ -14459,10 +14925,11 @@ class MemoryBuilder {
14459
14925
  startHeapIndex (${startHeapIndex}) has to be less than or equal to endHeapIndex (${endHeapIndex})
14460
14926
  `;
14461
14927
  this.ensureNotFinalized();
14462
- const range = MemoryRange.fromStartAndLength(startHeapIndex, endHeapIndex - startHeapIndex);
14463
- const pages = PageRange.fromMemoryRange(range);
14464
- for (const pageNumber of pages) {
14465
- if (this.initialMemory.has(pageNumber)) {
14928
+ const heapRange = MemoryRange.fromStartAndLength(startHeapIndex, endHeapIndex - startHeapIndex);
14929
+ const heapPagesRange = PageRange.fromMemoryRange(heapRange);
14930
+ const initializedPageNumbers = Array.from(this.initialMemory.keys());
14931
+ for (const pageNumber of initializedPageNumbers) {
14932
+ if (heapPagesRange.isInRange(pageNumber)) {
14466
14933
  throw new IncorrectSbrkIndex();
14467
14934
  }
14468
14935
  }
@@ -16902,8 +17369,8 @@ var index$3 = /*#__PURE__*/Object.freeze({
16902
17369
  asOpaqueType: asOpaqueType,
16903
17370
  assertEmpty: assertEmpty,
16904
17371
  assertNever: assertNever,
16905
- block: index$j,
16906
- bytes: index$q,
17372
+ block: index$l,
17373
+ bytes: index$s,
16907
17374
  check: check,
16908
17375
  clampU64ToU32: clampU64ToU32,
16909
17376
  createResults: createResults,
@@ -16911,13 +17378,13 @@ var index$3 = /*#__PURE__*/Object.freeze({
16911
17378
  extractCodeAndMetadata: extractCodeAndMetadata,
16912
17379
  getServiceId: getServiceId,
16913
17380
  getServiceIdOrCurrent: getServiceIdOrCurrent,
16914
- hash: index$n,
17381
+ hash: index$p,
16915
17382
  inspect: inspect,
16916
17383
  instructionArgumentTypeMap: instructionArgumentTypeMap,
16917
17384
  interpreter: index$7,
16918
17385
  isBrowser: isBrowser,
16919
17386
  measure: measure,
16920
- numbers: index$p,
17387
+ numbers: index$r,
16921
17388
  resultToString: resultToString,
16922
17389
  seeThrough: seeThrough,
16923
17390
  slotsToPreimageStatus: slotsToPreimageStatus,
@@ -17631,4 +18098,4 @@ var index = /*#__PURE__*/Object.freeze({
17631
18098
  WorkPackageExecutor: WorkPackageExecutor
17632
18099
  });
17633
18100
 
17634
- export { index$j as block, index$h as block_json, index$q as bytes, index$o as codec, index$l as collections, index$k as config, index$f as config_node, index$m as crypto, index$b as database, index$a as erasure_coding, index$n as hash, index$9 as jam_host_calls, index$i as json_parser, index$g as logger, index$8 as mmr, index$p as numbers, index$r as ordering, index$3 as pvm, index$6 as pvm_host_calls, index$7 as pvm_interpreter, index$4 as pvm_program, index$5 as pvm_spi_decoder, index$2 as shuffling, index$e as state, index$1 as state_json, index$c as state_merkleization, index as transition, index$d as trie, index$s as utils };
18101
+ export { index$l as block, index$j as block_json, index$s as bytes, index$q as codec, index$n as collections, index$m as config, index$h as config_node, index$o as crypto, index$d as database, index$c as erasure_coding, index$a as fuzz_proto, index$p as hash, index$9 as jam_host_calls, index$k as json_parser, index$i as logger, index$8 as mmr, index$r as numbers, index$t as ordering, index$3 as pvm, index$6 as pvm_host_calls, index$7 as pvm_interpreter, index$4 as pvm_program, index$5 as pvm_spi_decoder, index$2 as shuffling, index$g as state, index$1 as state_json, index$e as state_merkleization, index as transition, index$f as trie, index$u as utils };