@typeberry/lib 0.1.1 → 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.cjs CHANGED
@@ -10,6 +10,7 @@ var GpVersion;
10
10
  GpVersion["V0_6_7"] = "0.6.7";
11
11
  GpVersion["V0_7_0"] = "0.7.0";
12
12
  GpVersion["V0_7_1"] = "0.7.1-preview";
13
+ GpVersion["V0_7_2"] = "0.7.2-preview";
13
14
  })(GpVersion || (GpVersion = {}));
14
15
  var TestSuite;
15
16
  (function (TestSuite) {
@@ -17,29 +18,35 @@ var TestSuite;
17
18
  TestSuite["JAMDUNA"] = "jamduna";
18
19
  })(TestSuite || (TestSuite = {}));
19
20
  const DEFAULT_SUITE = TestSuite.W3F_DAVXY;
20
- const ALL_VERSIONS_IN_ORDER = [GpVersion.V0_6_7, GpVersion.V0_7_0, GpVersion.V0_7_1];
21
- const env = typeof process === "undefined" ? {} : process.env;
21
+ const ALL_VERSIONS_IN_ORDER = [GpVersion.V0_6_7, GpVersion.V0_7_0, GpVersion.V0_7_1, GpVersion.V0_7_2];
22
+ const env$1 = typeof process === "undefined" ? {} : process.env;
22
23
  const DEFAULT_VERSION = GpVersion.V0_7_0;
23
- let CURRENT_VERSION = parseCurrentVersion(env.GP_VERSION) ?? DEFAULT_VERSION;
24
- let CURRENT_SUITE = parseCurrentSuite(env.TEST_SUITE) ?? DEFAULT_SUITE;
24
+ let CURRENT_VERSION = parseCurrentVersion(env$1.GP_VERSION) ?? DEFAULT_VERSION;
25
+ let CURRENT_SUITE = parseCurrentSuite(env$1.TEST_SUITE) ?? DEFAULT_SUITE;
25
26
  function parseCurrentVersion(env) {
26
27
  if (env === undefined) {
27
28
  return undefined;
28
29
  }
29
- const version = env;
30
- if (!Object.values(GpVersion).includes(version)) {
31
- throw new Error(`Configured environment variable GP_VERSION is unknown: '${env}'. Use one of: ${ALL_VERSIONS_IN_ORDER}`);
30
+ switch (env) {
31
+ case GpVersion.V0_6_7:
32
+ case GpVersion.V0_7_0:
33
+ case GpVersion.V0_7_1:
34
+ case GpVersion.V0_7_2:
35
+ return env;
36
+ default:
37
+ throw new Error(`Configured environment variable GP_VERSION is unknown: '${env}'. Use one of: ${ALL_VERSIONS_IN_ORDER}`);
32
38
  }
33
- return version;
34
39
  }
35
40
  function parseCurrentSuite(env) {
36
41
  if (env === undefined)
37
42
  return undefined;
38
- const val = env;
39
- if (!Object.values(TestSuite).includes(val)) {
40
- throw new Error(`Configured environment variable TEST_SUITE is unknown: '${env}'. Use one of: ${Object.values(TestSuite)}`);
43
+ switch (env) {
44
+ case TestSuite.W3F_DAVXY:
45
+ case TestSuite.JAMDUNA:
46
+ return env;
47
+ default:
48
+ throw new Error(`Configured environment variable TEST_SUITE is unknown: '${env}'. Use one of: ${Object.values(TestSuite)}`);
41
49
  }
42
- return val;
43
50
  }
44
51
  class Compatibility {
45
52
  static override(version) {
@@ -200,6 +207,33 @@ class WithDebug {
200
207
  }
201
208
  }
202
209
 
210
+ const env = typeof process === "undefined" ? {} : process.env;
211
+ /**
212
+ * The function will produce relative path resolver that is adjusted
213
+ * for package location within the workspace.
214
+ *
215
+ * Example:
216
+ * $ npm start -w @typeberry/jam
217
+ *
218
+ * The above command will run `./bin/jam/index.js`, however we would
219
+ * still want relative paths to be resolved according to top-level workspace
220
+ * directory.
221
+ *
222
+ * So the caller, passes the absolute workspace path as argument and get's
223
+ * a function that can properly resolve relative paths.
224
+ *
225
+ * NOTE: the translation happens only for development build! When
226
+ * we build a single library from our project, we no longer mangle the paths.
227
+ */
228
+ const workspacePathFix = env.NODE_ENV === "development"
229
+ ? (workspacePath) => (p) => {
230
+ if (p.startsWith("/")) {
231
+ return p;
232
+ }
233
+ return `${workspacePath}/${p}`;
234
+ }
235
+ : () => (p) => p;
236
+
203
237
  /**
204
238
  * @fileoverview `Opaque<Type, Token>` constructs a unique type which is a subset of Type with a
205
239
  * specified unique token Token. It means that base type cannot be assigned to unique type by accident.
@@ -529,7 +563,7 @@ function isResult(x) {
529
563
  * as an afterthought.
530
564
  */
531
565
 
532
- var index$s = /*#__PURE__*/Object.freeze({
566
+ var index$u = /*#__PURE__*/Object.freeze({
533
567
  __proto__: null,
534
568
  get CURRENT_SUITE () { return CURRENT_SUITE; },
535
569
  get CURRENT_VERSION () { return CURRENT_VERSION; },
@@ -552,7 +586,8 @@ var index$s = /*#__PURE__*/Object.freeze({
552
586
  isBrowser: isBrowser,
553
587
  measure: measure,
554
588
  resultToString: resultToString,
555
- seeThrough: seeThrough
589
+ seeThrough: seeThrough,
590
+ workspacePathFix: workspacePathFix
556
591
  });
557
592
 
558
593
  /**
@@ -682,7 +717,7 @@ class Ordering {
682
717
  }
683
718
  }
684
719
 
685
- var index$r = /*#__PURE__*/Object.freeze({
720
+ var index$t = /*#__PURE__*/Object.freeze({
686
721
  __proto__: null,
687
722
  Ordering: Ordering
688
723
  });
@@ -933,7 +968,7 @@ function u8ArraySameLengthEqual(self, other) {
933
968
  }
934
969
  const bytesBlobComparator = (a, b) => a.compare(b);
935
970
 
936
- var index$q = /*#__PURE__*/Object.freeze({
971
+ var index$s = /*#__PURE__*/Object.freeze({
937
972
  __proto__: null,
938
973
  BitVec: BitVec,
939
974
  Bytes: Bytes,
@@ -1035,7 +1070,7 @@ const minU64 = (a, ...values) => values.reduce((min, value) => (value > min ? mi
1035
1070
  /** Get the biggest value between U64 a and values given as input parameters. */
1036
1071
  const maxU64 = (a, ...values) => values.reduce((max, value) => (value < max ? max : value), a);
1037
1072
 
1038
- var index$p = /*#__PURE__*/Object.freeze({
1073
+ var index$r = /*#__PURE__*/Object.freeze({
1039
1074
  __proto__: null,
1040
1075
  isU16: isU16,
1041
1076
  isU32: isU32,
@@ -2445,7 +2480,7 @@ function sequenceViewFixLen(type, { fixedLength }) {
2445
2480
  }, skipper);
2446
2481
  }
2447
2482
 
2448
- var index$o = /*#__PURE__*/Object.freeze({
2483
+ var index$q = /*#__PURE__*/Object.freeze({
2449
2484
  __proto__: null,
2450
2485
  Decoder: Decoder,
2451
2486
  Descriptor: Descriptor,
@@ -4884,7 +4919,7 @@ var keccak = /*#__PURE__*/Object.freeze({
4884
4919
  hashBlobs: hashBlobs
4885
4920
  });
4886
4921
 
4887
- var index$n = /*#__PURE__*/Object.freeze({
4922
+ var index$p = /*#__PURE__*/Object.freeze({
4888
4923
  __proto__: null,
4889
4924
  HASH_SIZE: HASH_SIZE,
4890
4925
  PageAllocator: PageAllocator,
@@ -4950,7 +4985,7 @@ var keyDerivation = /*#__PURE__*/Object.freeze({
4950
4985
  trivialSeed: trivialSeed
4951
4986
  });
4952
4987
 
4953
- var index$m = /*#__PURE__*/Object.freeze({
4988
+ var index$o = /*#__PURE__*/Object.freeze({
4954
4989
  __proto__: null,
4955
4990
  BANDERSNATCH_KEY_BYTES: BANDERSNATCH_KEY_BYTES,
4956
4991
  BANDERSNATCH_PROOF_BYTES: BANDERSNATCH_PROOF_BYTES,
@@ -5554,7 +5589,7 @@ class TruncatedHashDictionary {
5554
5589
  }
5555
5590
  }
5556
5591
 
5557
- var index$l = /*#__PURE__*/Object.freeze({
5592
+ var index$n = /*#__PURE__*/Object.freeze({
5558
5593
  __proto__: null,
5559
5594
  FixedSizeArray: FixedSizeArray,
5560
5595
  HashDictionary: HashDictionary,
@@ -5749,7 +5784,7 @@ class Bootnode {
5749
5784
  }
5750
5785
  }
5751
5786
 
5752
- var index$k = /*#__PURE__*/Object.freeze({
5787
+ var index$m = /*#__PURE__*/Object.freeze({
5753
5788
  __proto__: null,
5754
5789
  Bootnode: Bootnode,
5755
5790
  ChainSpec: ChainSpec,
@@ -5922,6 +5957,40 @@ var assurances = /*#__PURE__*/Object.freeze({
5922
5957
  assurancesExtrinsicCodec: assurancesExtrinsicCodec
5923
5958
  });
5924
5959
 
5960
+ /** Attempt to convert a number into `TimeSlot`. */
5961
+ const tryAsTimeSlot = (v) => asOpaqueType(tryAsU32(v));
5962
+ /** Attempt to convert a number into `ValidatorIndex`. */
5963
+ const tryAsValidatorIndex = (v) => asOpaqueType(tryAsU16(v));
5964
+ /** Attempt to convert a number into `ServiceId`. */
5965
+ const tryAsServiceId = (v) => asOpaqueType(tryAsU32(v));
5966
+ const tryAsServiceGas = (v) => asOpaqueType(tryAsU64(v));
5967
+ /** Attempt to convert a number into `CoreIndex`. */
5968
+ const tryAsCoreIndex = (v) => asOpaqueType(tryAsU16(v));
5969
+ /** Attempt to convert a number into `Epoch`. */
5970
+ const tryAsEpoch = (v) => asOpaqueType(tryAsU32(v));
5971
+ function tryAsPerValidator(array, spec) {
5972
+ check `
5973
+ ${array.length === spec.validatorsCount}
5974
+ Invalid per-validator array length. Expected ${spec.validatorsCount}, got: ${array.length}
5975
+ `;
5976
+ return asKnownSize(array);
5977
+ }
5978
+ const codecPerValidator = (val) => codecWithContext((context) => {
5979
+ return codecKnownSizeArray(val, {
5980
+ fixedLength: context.validatorsCount,
5981
+ });
5982
+ });
5983
+ function tryAsPerEpochBlock(array, spec) {
5984
+ check `
5985
+ ${array.length === spec.epochLength}
5986
+ Invalid per-epoch-block array length. Expected ${spec.epochLength}, got: ${array.length}
5987
+ `;
5988
+ return asKnownSize(array);
5989
+ }
5990
+ const codecPerEpochBlock = (val) => codecWithContext((context) => {
5991
+ return codecKnownSizeArray(val, { fixedLength: context.epochLength });
5992
+ });
5993
+
5925
5994
  /**
5926
5995
  * Proof of signing a contradictory [`Judgement`] of a work report.
5927
5996
  */
@@ -6113,40 +6182,6 @@ var disputes = /*#__PURE__*/Object.freeze({
6113
6182
  Verdict: Verdict
6114
6183
  });
6115
6184
 
6116
- /** Attempt to convert a number into `TimeSlot`. */
6117
- const tryAsTimeSlot = (v) => asOpaqueType(tryAsU32(v));
6118
- /** Attempt to convert a number into `ValidatorIndex`. */
6119
- const tryAsValidatorIndex = (v) => asOpaqueType(tryAsU16(v));
6120
- /** Attempt to convert a number into `ServiceId`. */
6121
- const tryAsServiceId = (v) => asOpaqueType(tryAsU32(v));
6122
- const tryAsServiceGas = (v) => asOpaqueType(tryAsU64(v));
6123
- /** Attempt to convert a number into `CoreIndex`. */
6124
- const tryAsCoreIndex = (v) => asOpaqueType(tryAsU16(v));
6125
- /** Attempt to convert a number into `Epoch`. */
6126
- const tryAsEpoch = (v) => asOpaqueType(tryAsU32(v));
6127
- function tryAsPerValidator(array, spec) {
6128
- check `
6129
- ${array.length === spec.validatorsCount}
6130
- Invalid per-validator array length. Expected ${spec.validatorsCount}, got: ${array.length}
6131
- `;
6132
- return asKnownSize(array);
6133
- }
6134
- const codecPerValidator = (val) => codecWithContext((context) => {
6135
- return codecKnownSizeArray(val, {
6136
- fixedLength: context.validatorsCount,
6137
- });
6138
- });
6139
- function tryAsPerEpochBlock(array, spec) {
6140
- check `
6141
- ${array.length === spec.epochLength}
6142
- Invalid per-epoch-block array length. Expected ${spec.epochLength}, got: ${array.length}
6143
- `;
6144
- return asKnownSize(array);
6145
- }
6146
- const codecPerEpochBlock = (val) => codecWithContext((context) => {
6147
- return codecKnownSizeArray(val, { fixedLength: context.epochLength });
6148
- });
6149
-
6150
6185
  /**
6151
6186
  * Mapping between work package hash and root hash of it's exports.
6152
6187
  *
@@ -7225,8 +7260,26 @@ class Block extends WithDebug {
7225
7260
  this.extrinsic = extrinsic;
7226
7261
  }
7227
7262
  }
7263
+ function emptyBlock(slot = tryAsTimeSlot(0)) {
7264
+ const header = Header.empty();
7265
+ header.timeSlotIndex = slot;
7266
+ return Block.create({
7267
+ header,
7268
+ extrinsic: Extrinsic.create({
7269
+ tickets: asKnownSize([]),
7270
+ preimages: [],
7271
+ assurances: asKnownSize([]),
7272
+ guarantees: asKnownSize([]),
7273
+ disputes: {
7274
+ verdicts: [],
7275
+ culprits: [],
7276
+ faults: [],
7277
+ },
7278
+ }),
7279
+ });
7280
+ }
7228
7281
 
7229
- var index$j = /*#__PURE__*/Object.freeze({
7282
+ var index$l = /*#__PURE__*/Object.freeze({
7230
7283
  __proto__: null,
7231
7284
  Block: Block,
7232
7285
  EpochMarker: EpochMarker,
@@ -7241,6 +7294,7 @@ var index$j = /*#__PURE__*/Object.freeze({
7241
7294
  codecPerValidator: codecPerValidator,
7242
7295
  codecUtils: codec,
7243
7296
  disputes: disputes,
7297
+ emptyBlock: emptyBlock,
7244
7298
  encodeUnsealedHeader: encodeUnsealedHeader,
7245
7299
  guarantees: guarantees,
7246
7300
  headerViewWithHashCodec: headerViewWithHashCodec,
@@ -7481,7 +7535,7 @@ var json;
7481
7535
  json.object = object;
7482
7536
  })(json || (json = {}));
7483
7537
 
7484
- var index$i = /*#__PURE__*/Object.freeze({
7538
+ var index$k = /*#__PURE__*/Object.freeze({
7485
7539
  __proto__: null,
7486
7540
  get json () { return json; },
7487
7541
  parseFromJson: parseFromJson
@@ -7751,7 +7805,7 @@ const blockFromJson = (spec) => json.object({
7751
7805
  extrinsic: getExtrinsicFromJson(spec),
7752
7806
  }, ({ header, extrinsic }) => Block.create({ header, extrinsic }));
7753
7807
 
7754
- var index$h = /*#__PURE__*/Object.freeze({
7808
+ var index$j = /*#__PURE__*/Object.freeze({
7755
7809
  __proto__: null,
7756
7810
  blockFromJson: blockFromJson,
7757
7811
  disputesExtrinsicFromJson: disputesExtrinsicFromJson,
@@ -8012,6 +8066,23 @@ function parseLevel(lvl) {
8012
8066
  }
8013
8067
 
8014
8068
  // biome-ignore-all lint/suspicious/noConsole: logger
8069
+ function print(level, levelAndName, strings, data) {
8070
+ if (level < levelAndName[0]) {
8071
+ return;
8072
+ }
8073
+ const lvlText = Level[level].padEnd(5);
8074
+ const val = strings.map((v, idx) => `${v}${idx < data.length ? data[idx] : ""}`);
8075
+ const msg = `${lvlText} [${levelAndName[1]}] ${val.join("")}`;
8076
+ if (level === Level.WARN) {
8077
+ console.warn(msg);
8078
+ }
8079
+ else if (level === Level.ERROR) {
8080
+ console.error(msg);
8081
+ }
8082
+ else {
8083
+ console.info(msg);
8084
+ }
8085
+ }
8015
8086
  /** An optimized logger that ignores `TRACE`, `DEBUG` and `LOG` messages.
8016
8087
  *
8017
8088
  * Use the `create` method to instantiate the right instance of a more specialized logger.
@@ -8042,109 +8113,91 @@ class ConsoleTransport {
8042
8113
  constructor(options) {
8043
8114
  this.options = options;
8044
8115
  }
8045
- insane(_moduleName, _val) {
8116
+ insane(_levelAndName, _strings, _data) {
8046
8117
  /* no-op */
8047
8118
  }
8048
- trace(_moduleName, _val) {
8119
+ trace(_levelAndName, _strings, _data) {
8049
8120
  /* no-op */
8050
8121
  }
8051
- log(_moduleName, _val) {
8122
+ log(_levelAndName, _strings, _data) {
8052
8123
  /* no-op */
8053
8124
  }
8054
- info(_moduleName, _val) {
8125
+ info(_levelAndName, _strings, _data) {
8055
8126
  /* no-op */
8056
8127
  }
8057
- warn(moduleName, val) {
8058
- this.push(Level.WARN, moduleName, val);
8128
+ warn(levelAndName, strings, data) {
8129
+ print(Level.WARN, levelAndName, strings, data);
8059
8130
  }
8060
- error(moduleName, val) {
8061
- this.push(Level.ERROR, moduleName, val);
8062
- }
8063
- push(level, moduleName, val) {
8064
- const shortModule = moduleName.replace(this.options.workingDir, "");
8065
- const configuredLevel = findLevel(this.options, moduleName);
8066
- const lvlText = Level[level].padEnd(5);
8067
- if (level < configuredLevel) {
8068
- return;
8069
- }
8070
- const msg = `${lvlText} [${shortModule}] ${val}`;
8071
- if (level === Level.WARN) {
8072
- console.warn(msg);
8073
- }
8074
- else if (level === Level.ERROR) {
8075
- console.error(msg);
8076
- }
8077
- else {
8078
- console.info(msg);
8079
- }
8131
+ error(levelAndName, strings, data) {
8132
+ print(Level.ERROR, levelAndName, strings, data);
8080
8133
  }
8081
8134
  }
8082
8135
  /**
8083
8136
  * Insane version of console logger - supports insane level.
8084
8137
  */
8085
8138
  class InsaneConsoleLogger extends ConsoleTransport {
8086
- insane(moduleName, val) {
8087
- this.push(Level.INSANE, moduleName, val);
8139
+ insane(levelAndName, strings, data) {
8140
+ print(Level.INSANE, levelAndName, strings, data);
8088
8141
  }
8089
- trace(moduleName, val) {
8090
- this.push(Level.TRACE, moduleName, val);
8142
+ trace(levelAndName, strings, data) {
8143
+ print(Level.TRACE, levelAndName, strings, data);
8091
8144
  }
8092
- log(moduleName, val) {
8093
- this.push(Level.LOG, moduleName, val);
8145
+ log(levelAndName, strings, data) {
8146
+ print(Level.LOG, levelAndName, strings, data);
8094
8147
  }
8095
- info(moduleName, val) {
8096
- this.push(Level.INFO, moduleName, val);
8148
+ info(levelAndName, strings, data) {
8149
+ print(Level.INFO, levelAndName, strings, data);
8097
8150
  }
8098
8151
  }
8099
8152
  /**
8100
8153
  * A basic version of console logger - printing everything.
8101
8154
  */
8102
8155
  class TraceConsoleTransport extends ConsoleTransport {
8103
- insane(_moduleName, _val) {
8156
+ insane(_levelAndName, _strings, _data) {
8104
8157
  /* no-op */
8105
8158
  }
8106
- trace(moduleName, val) {
8107
- this.push(Level.TRACE, moduleName, val);
8159
+ trace(levelAndName, strings, data) {
8160
+ print(Level.TRACE, levelAndName, strings, data);
8108
8161
  }
8109
- log(moduleName, val) {
8110
- this.push(Level.LOG, moduleName, val);
8162
+ log(levelAndName, strings, data) {
8163
+ print(Level.LOG, levelAndName, strings, data);
8111
8164
  }
8112
- info(moduleName, val) {
8113
- this.push(Level.INFO, moduleName, val);
8165
+ info(levelAndName, strings, data) {
8166
+ print(Level.INFO, levelAndName, strings, data);
8114
8167
  }
8115
8168
  }
8116
8169
  /**
8117
8170
  * An optimized version of the logger - completely ignores `TRACE` level calls.
8118
8171
  */
8119
8172
  class LogConsoleTransport extends ConsoleTransport {
8120
- insane(_moduleName, _val) {
8173
+ insane(_levelAndName, _strings, _data) {
8121
8174
  /* no-op */
8122
8175
  }
8123
- trace(_moduleName, _val) {
8176
+ trace(_levelAndName, _strings, _data) {
8124
8177
  /* no-op */
8125
8178
  }
8126
- log(moduleName, val) {
8127
- this.push(Level.LOG, moduleName, val);
8179
+ log(levelAndName, strings, data) {
8180
+ print(Level.LOG, levelAndName, strings, data);
8128
8181
  }
8129
- info(moduleName, val) {
8130
- this.push(Level.INFO, moduleName, val);
8182
+ info(levelAndName, strings, data) {
8183
+ print(Level.INFO, levelAndName, strings, data);
8131
8184
  }
8132
8185
  }
8133
8186
  /**
8134
8187
  * An optimized version of the logger - completely ignores `TRACE` & `DEBUG` level calls.
8135
8188
  */
8136
8189
  class InfoConsoleTransport extends ConsoleTransport {
8137
- insane(_moduleName, _val) {
8190
+ insane(_levelAndName, _strings, _data) {
8138
8191
  /* no-op */
8139
8192
  }
8140
- trace(_moduleName, _val) {
8193
+ trace(_levelAndName, _strings, _data) {
8141
8194
  /* no-op */
8142
8195
  }
8143
- log(_moduleName, _val) {
8196
+ log(_levelAndName, _strings, _data) {
8144
8197
  /* no-op */
8145
8198
  }
8146
- info(moduleName, val) {
8147
- this.push(Level.INFO, moduleName, val);
8199
+ info(levelAndName, strings, data) {
8200
+ print(Level.INFO, levelAndName, strings, data);
8148
8201
  }
8149
8202
  }
8150
8203
 
@@ -8177,11 +8230,6 @@ class Logger {
8177
8230
  const module = moduleName ?? fName;
8178
8231
  return new Logger(module.padStart(8, " "), GLOBAL_CONFIG);
8179
8232
  }
8180
- /**
8181
- * Return currently configured level for given module. */
8182
- static getLevel(moduleName) {
8183
- return findLevel(GLOBAL_CONFIG.options, moduleName);
8184
- }
8185
8233
  /**
8186
8234
  * Global configuration of all loggers.
8187
8235
  *
@@ -8212,37 +8260,50 @@ class Logger {
8212
8260
  const options = parseLoggerOptions(input, defaultLevel, workingDir);
8213
8261
  Logger.configureAllFromOptions(options);
8214
8262
  }
8263
+ cachedLevelAndName;
8215
8264
  constructor(moduleName, config) {
8216
8265
  this.moduleName = moduleName;
8217
8266
  this.config = config;
8218
8267
  }
8268
+ /** Return currently configured level for given module. */
8269
+ getLevel() {
8270
+ return this.getLevelAndName()[0];
8271
+ }
8272
+ getLevelAndName() {
8273
+ if (this.cachedLevelAndName === undefined) {
8274
+ const level = findLevel(this.config.options, this.moduleName);
8275
+ const shortName = this.moduleName.replace(this.config.options.workingDir, "");
8276
+ this.cachedLevelAndName = [level, shortName];
8277
+ }
8278
+ return this.cachedLevelAndName;
8279
+ }
8219
8280
  /** Log a message with `INSANE` level. */
8220
- insane(val) {
8221
- this.config.transport.insane(this.moduleName, val);
8281
+ insane(strings, ...data) {
8282
+ this.config.transport.insane(this.getLevelAndName(), strings, data);
8222
8283
  }
8223
8284
  /** Log a message with `TRACE` level. */
8224
- trace(val) {
8225
- this.config.transport.trace(this.moduleName, val);
8285
+ trace(strings, ...data) {
8286
+ this.config.transport.trace(this.getLevelAndName(), strings, data);
8226
8287
  }
8227
8288
  /** Log a message with `DEBUG`/`LOG` level. */
8228
- log(val) {
8229
- this.config.transport.log(this.moduleName, val);
8289
+ log(strings, ...data) {
8290
+ this.config.transport.log(this.getLevelAndName(), strings, data);
8230
8291
  }
8231
8292
  /** Log a message with `INFO` level. */
8232
- info(val) {
8233
- this.config.transport.info(this.moduleName, val);
8293
+ info(strings, ...data) {
8294
+ this.config.transport.info(this.getLevelAndName(), strings, data);
8234
8295
  }
8235
8296
  /** Log a message with `WARN` level. */
8236
- warn(val) {
8237
- this.config.transport.warn(this.moduleName, val);
8297
+ warn(strings, ...data) {
8298
+ this.config.transport.warn(this.getLevelAndName(), strings, data);
8238
8299
  }
8239
8300
  /** Log a message with `ERROR` level. */
8240
- error(val) {
8241
- this.config.transport.error(this.moduleName, val);
8301
+ error(strings, ...data) {
8302
+ this.config.transport.error(this.getLevelAndName(), strings, data);
8242
8303
  }
8243
8304
  }
8244
8305
 
8245
- var index$g = /*#__PURE__*/Object.freeze({
8306
+ var index$i = /*#__PURE__*/Object.freeze({
8246
8307
  __proto__: null,
8247
8308
  get Level () { return Level; },
8248
8309
  Logger: Logger,
@@ -8265,7 +8326,7 @@ class AuthorshipOptions {
8265
8326
  }
8266
8327
  }
8267
8328
 
8268
- const logger$3 = Logger.new(undefined, "config");
8329
+ const logger$5 = Logger.new(undefined, "config");
8269
8330
  /** Development config. Will accept unsealed blocks for now. */
8270
8331
  const DEV_CONFIG = "dev";
8271
8332
  /** Default config file. */
@@ -8324,15 +8385,15 @@ class NodeConfiguration {
8324
8385
  }
8325
8386
  function loadConfig(configPath) {
8326
8387
  if (configPath === DEFAULT_CONFIG) {
8327
- logger$3.log("🔧 Loading DEFAULT config");
8388
+ logger$5.log `🔧 Loading DEFAULT config`;
8328
8389
  return parseFromJson(configs.default, NodeConfiguration.fromJson);
8329
8390
  }
8330
8391
  if (configPath === DEV_CONFIG) {
8331
- logger$3.log("🔧 Loading DEV config");
8392
+ logger$5.log `🔧 Loading DEV config`;
8332
8393
  return parseFromJson(configs.dev, NodeConfiguration.fromJson);
8333
8394
  }
8334
8395
  try {
8335
- logger$3.log(`🔧 Loading config from ${configPath}`);
8396
+ logger$5.log `🔧 Loading config from ${configPath}`;
8336
8397
  const configFile = fs.readFileSync(configPath, "utf8");
8337
8398
  const parsed = JSON.parse(configFile);
8338
8399
  return parseFromJson(parsed, NodeConfiguration.fromJson);
@@ -8342,7 +8403,7 @@ function loadConfig(configPath) {
8342
8403
  }
8343
8404
  }
8344
8405
 
8345
- var index$f = /*#__PURE__*/Object.freeze({
8406
+ var index$h = /*#__PURE__*/Object.freeze({
8346
8407
  __proto__: null,
8347
8408
  DEFAULT_CONFIG: DEFAULT_CONFIG,
8348
8409
  DEV_CONFIG: DEV_CONFIG,
@@ -10008,7 +10069,7 @@ const serviceDataCodec = codec$1.dictionary(codec$1.u32.asOpaque(), serviceEntri
10008
10069
  sortKeys: (a, b) => a - b,
10009
10070
  });
10010
10071
 
10011
- var index$e = /*#__PURE__*/Object.freeze({
10072
+ var index$g = /*#__PURE__*/Object.freeze({
10012
10073
  __proto__: null,
10013
10074
  AccumulationOutput: AccumulationOutput,
10014
10075
  AutoAccumulate: AutoAccumulate,
@@ -11018,7 +11079,7 @@ const bitLookup = [
11018
11079
  [0b00000000, 8],
11019
11080
  ];
11020
11081
 
11021
- var index$d = /*#__PURE__*/Object.freeze({
11082
+ var index$f = /*#__PURE__*/Object.freeze({
11022
11083
  __proto__: null,
11023
11084
  BranchNode: BranchNode,
11024
11085
  InMemoryTrie: InMemoryTrie,
@@ -11364,7 +11425,7 @@ function loadState(spec, entries) {
11364
11425
  * hashmap of `key -> value` entries.
11365
11426
  */
11366
11427
 
11367
- var index$c = /*#__PURE__*/Object.freeze({
11428
+ var index$e = /*#__PURE__*/Object.freeze({
11368
11429
  __proto__: null,
11369
11430
  SerializedService: SerializedService,
11370
11431
  SerializedState: SerializedState,
@@ -11650,7 +11711,7 @@ class InMemoryStates {
11650
11711
  }
11651
11712
  }
11652
11713
 
11653
- var index$b = /*#__PURE__*/Object.freeze({
11714
+ var index$d = /*#__PURE__*/Object.freeze({
11654
11715
  __proto__: null,
11655
11716
  InMemoryBlocks: InMemoryBlocks,
11656
11717
  InMemoryStates: InMemoryStates,
@@ -12012,7 +12073,7 @@ const initEc = async () => {
12012
12073
  await init.reedSolomon();
12013
12074
  };
12014
12075
 
12015
- var index$a = /*#__PURE__*/Object.freeze({
12076
+ var index$c = /*#__PURE__*/Object.freeze({
12016
12077
  __proto__: null,
12017
12078
  N_CHUNKS_REDUNDANCY: N_CHUNKS_REDUNDANCY,
12018
12079
  N_CHUNKS_REQUIRED: N_CHUNKS_REQUIRED,
@@ -12036,6 +12097,439 @@ var index$a = /*#__PURE__*/Object.freeze({
12036
12097
  unzip: unzip
12037
12098
  });
12038
12099
 
12100
+ /**
12101
+ * Version ::= SEQUENCE {
12102
+ * major INTEGER (0..255),
12103
+ * minor INTEGER (0..255),
12104
+ * patch INTEGER (0..255)
12105
+ * }
12106
+ */
12107
+ class Version extends WithDebug {
12108
+ major;
12109
+ minor;
12110
+ patch;
12111
+ static Codec = codec$1.Class(Version, {
12112
+ major: codec$1.u8,
12113
+ minor: codec$1.u8,
12114
+ patch: codec$1.u8,
12115
+ });
12116
+ static tryFromString(str) {
12117
+ const parse = (v) => tryAsU8(Number(v));
12118
+ try {
12119
+ const [major, minor, patch] = str.trim().split(".").map(parse);
12120
+ return Version.create({
12121
+ major,
12122
+ minor,
12123
+ patch,
12124
+ });
12125
+ }
12126
+ catch (e) {
12127
+ throw new Error(`Unable to parse ${str} as Version: ${e}`);
12128
+ }
12129
+ }
12130
+ static create({ major, minor, patch }) {
12131
+ return new Version(major, minor, patch);
12132
+ }
12133
+ constructor(major, minor, patch) {
12134
+ super();
12135
+ this.major = major;
12136
+ this.minor = minor;
12137
+ this.patch = patch;
12138
+ }
12139
+ }
12140
+ /**
12141
+ * Fuzzer Protocol V1
12142
+ * Reference: https://github.com/davxy/jam-conformance/blob/main/fuzz-proto/fuzz.asn
12143
+ */
12144
+ // Feature bit constants
12145
+ var Features;
12146
+ (function (Features) {
12147
+ Features[Features["Ancestry"] = 1] = "Ancestry";
12148
+ Features[Features["Fork"] = 2] = "Fork";
12149
+ Features[Features["Reserved"] = 2147483648] = "Reserved";
12150
+ })(Features || (Features = {}));
12151
+ /**
12152
+ * PeerInfo ::= SEQUENCE {
12153
+ * fuzz-version U8,
12154
+ * features Features,
12155
+ * jam-version Version,
12156
+ * app-version Version,
12157
+ * name UTF8String
12158
+ * }
12159
+ */
12160
+ class PeerInfo extends WithDebug {
12161
+ fuzzVersion;
12162
+ features;
12163
+ jamVersion;
12164
+ appVersion;
12165
+ name;
12166
+ static Codec = codec$1.Class(PeerInfo, {
12167
+ fuzzVersion: codec$1.u8,
12168
+ features: codec$1.u32,
12169
+ jamVersion: Version.Codec,
12170
+ appVersion: Version.Codec,
12171
+ name: codec$1.string,
12172
+ });
12173
+ static create({ fuzzVersion, features, appVersion, jamVersion, name }) {
12174
+ return new PeerInfo(fuzzVersion, features, jamVersion, appVersion, name);
12175
+ }
12176
+ constructor(fuzzVersion, features, jamVersion, appVersion, name) {
12177
+ super();
12178
+ this.fuzzVersion = fuzzVersion;
12179
+ this.features = features;
12180
+ this.jamVersion = jamVersion;
12181
+ this.appVersion = appVersion;
12182
+ this.name = name;
12183
+ }
12184
+ }
12185
+ /**
12186
+ * AncestryItem ::= SEQUENCE {
12187
+ * slot TimeSlot,
12188
+ * header-hash HeaderHash
12189
+ * }
12190
+ */
12191
+ class AncestryItem extends WithDebug {
12192
+ slot;
12193
+ headerHash;
12194
+ static Codec = codec$1.Class(AncestryItem, {
12195
+ slot: codec$1.u32.asOpaque(),
12196
+ headerHash: codec$1.bytes(HASH_SIZE).asOpaque(),
12197
+ });
12198
+ static create({ slot, headerHash }) {
12199
+ return new AncestryItem(slot, headerHash);
12200
+ }
12201
+ constructor(slot, headerHash) {
12202
+ super();
12203
+ this.slot = slot;
12204
+ this.headerHash = headerHash;
12205
+ }
12206
+ }
12207
+ /**
12208
+ * KeyValue ::= SEQUENCE {
12209
+ * key TrieKey,
12210
+ * value OCTET STRING
12211
+ * }
12212
+ */
12213
+ class KeyValue extends WithDebug {
12214
+ key;
12215
+ value;
12216
+ static Codec = codec$1.Class(KeyValue, {
12217
+ key: codec$1.bytes(TRUNCATED_HASH_SIZE),
12218
+ value: codec$1.blob,
12219
+ });
12220
+ static create({ key, value }) {
12221
+ return new KeyValue(key, value);
12222
+ }
12223
+ constructor(key, value) {
12224
+ super();
12225
+ this.key = key;
12226
+ this.value = value;
12227
+ }
12228
+ }
12229
+ /** State ::= SEQUENCE OF KeyValue */
12230
+ const stateCodec = codec$1.sequenceVarLen(KeyValue.Codec);
12231
+ /**
12232
+ * Ancestry ::= SEQUENCE (SIZE(0..24)) OF AncestryItem
12233
+ * Empty when `feature-ancestry` is not supported by both parties
12234
+ */
12235
+ const ancestryCodec = codec$1.sequenceVarLen(AncestryItem.Codec, {
12236
+ minLength: 0,
12237
+ maxLength: 24,
12238
+ });
12239
+ /**
12240
+ * Initialize ::= SEQUENCE {
12241
+ * header Header,
12242
+ * keyvals State,
12243
+ * ancestry Ancestry
12244
+ * }
12245
+ */
12246
+ class Initialize extends WithDebug {
12247
+ header;
12248
+ keyvals;
12249
+ ancestry;
12250
+ static Codec = codec$1.Class(Initialize, {
12251
+ header: Header.Codec,
12252
+ keyvals: stateCodec,
12253
+ ancestry: ancestryCodec,
12254
+ });
12255
+ static create({ header, keyvals, ancestry }) {
12256
+ return new Initialize(header, keyvals, ancestry);
12257
+ }
12258
+ constructor(header, keyvals, ancestry) {
12259
+ super();
12260
+ this.header = header;
12261
+ this.keyvals = keyvals;
12262
+ this.ancestry = ancestry;
12263
+ }
12264
+ }
12265
+ /** GetState ::= HeaderHash */
12266
+ const getStateCodec = codec$1.bytes(HASH_SIZE).asOpaque();
12267
+ /** StateRoot ::= StateRootHash */
12268
+ const stateRootCodec = codec$1.bytes(HASH_SIZE).asOpaque();
12269
+ /** Error ::= UTF8String */
12270
+ class ErrorMessage extends WithDebug {
12271
+ message;
12272
+ static Codec = codec$1.Class(ErrorMessage, {
12273
+ message: codec$1.string,
12274
+ });
12275
+ static create({ message }) {
12276
+ return new ErrorMessage(message);
12277
+ }
12278
+ constructor(message) {
12279
+ super();
12280
+ this.message = message;
12281
+ }
12282
+ }
12283
+ /** Message choice type tags */
12284
+ var MessageType;
12285
+ (function (MessageType) {
12286
+ MessageType[MessageType["PeerInfo"] = 0] = "PeerInfo";
12287
+ MessageType[MessageType["Initialize"] = 1] = "Initialize";
12288
+ MessageType[MessageType["StateRoot"] = 2] = "StateRoot";
12289
+ MessageType[MessageType["ImportBlock"] = 3] = "ImportBlock";
12290
+ MessageType[MessageType["GetState"] = 4] = "GetState";
12291
+ MessageType[MessageType["State"] = 5] = "State";
12292
+ MessageType[MessageType["Error"] = 255] = "Error";
12293
+ })(MessageType || (MessageType = {}));
12294
+ /**
12295
+ * Message ::= CHOICE {
12296
+ * peer-info [0] PeerInfo,
12297
+ * initialize [1] Initialize,
12298
+ * state-root [2] StateRoot,
12299
+ * import-block [3] ImportBlock,
12300
+ * get-state [4] GetState,
12301
+ * state [5] State,
12302
+ * error [255] Error
12303
+ * }
12304
+ */
12305
+ const messageCodec = codec$1.custom({
12306
+ name: "Message",
12307
+ sizeHint: { bytes: 1, isExact: false },
12308
+ }, (e, msg) => {
12309
+ e.i8(msg.type);
12310
+ switch (msg.type) {
12311
+ case MessageType.PeerInfo:
12312
+ PeerInfo.Codec.encode(e, msg.value);
12313
+ break;
12314
+ case MessageType.Initialize:
12315
+ Initialize.Codec.encode(e, msg.value);
12316
+ break;
12317
+ case MessageType.StateRoot:
12318
+ stateRootCodec.encode(e, msg.value);
12319
+ break;
12320
+ case MessageType.ImportBlock:
12321
+ Block.Codec.View.encode(e, msg.value);
12322
+ break;
12323
+ case MessageType.GetState:
12324
+ getStateCodec.encode(e, msg.value);
12325
+ break;
12326
+ case MessageType.State:
12327
+ stateCodec.encode(e, msg.value);
12328
+ break;
12329
+ case MessageType.Error:
12330
+ ErrorMessage.Codec.encode(e, msg.value);
12331
+ break;
12332
+ default:
12333
+ throw new Error(`Unknown message type: ${msg}`);
12334
+ }
12335
+ }, (d) => {
12336
+ const type = d.u8();
12337
+ switch (type) {
12338
+ case MessageType.PeerInfo:
12339
+ return { type: MessageType.PeerInfo, value: PeerInfo.Codec.decode(d) };
12340
+ case MessageType.Initialize:
12341
+ return { type: MessageType.Initialize, value: Initialize.Codec.decode(d) };
12342
+ case MessageType.StateRoot:
12343
+ return { type: MessageType.StateRoot, value: stateRootCodec.decode(d) };
12344
+ case MessageType.ImportBlock:
12345
+ return { type: MessageType.ImportBlock, value: Block.Codec.View.decode(d) };
12346
+ case MessageType.GetState:
12347
+ return { type: MessageType.GetState, value: getStateCodec.decode(d) };
12348
+ case MessageType.State:
12349
+ return { type: MessageType.State, value: stateCodec.decode(d) };
12350
+ case MessageType.Error:
12351
+ return { type: MessageType.Error, value: ErrorMessage.Codec.decode(d) };
12352
+ default:
12353
+ throw new Error(`Unknown message type: ${type}`);
12354
+ }
12355
+ }, (s) => {
12356
+ const type = s.decoder.u8();
12357
+ switch (type) {
12358
+ case MessageType.PeerInfo:
12359
+ PeerInfo.Codec.View.skip(s);
12360
+ break;
12361
+ case MessageType.Initialize:
12362
+ Initialize.Codec.View.skip(s);
12363
+ break;
12364
+ case MessageType.StateRoot:
12365
+ stateRootCodec.View.skip(s);
12366
+ break;
12367
+ case MessageType.ImportBlock:
12368
+ Block.Codec.View.skip(s);
12369
+ break;
12370
+ case MessageType.GetState:
12371
+ getStateCodec.View.skip(s);
12372
+ break;
12373
+ case MessageType.State:
12374
+ stateCodec.View.skip(s);
12375
+ break;
12376
+ case MessageType.Error:
12377
+ ErrorMessage.Codec.View.skip(s);
12378
+ break;
12379
+ default:
12380
+ throw new Error(`Unknown message type: ${type}`);
12381
+ }
12382
+ });
12383
+
12384
+ const logger$4 = Logger.new(undefined, "ext-ipc-fuzz-v1");
12385
+ class FuzzTarget {
12386
+ msgHandler;
12387
+ sender;
12388
+ spec;
12389
+ sessionFeatures = 0;
12390
+ constructor(msgHandler, sender, spec) {
12391
+ this.msgHandler = msgHandler;
12392
+ this.sender = sender;
12393
+ this.spec = spec;
12394
+ }
12395
+ async onSocketMessage(msg) {
12396
+ // attempt to decode the messsage
12397
+ try {
12398
+ const message = Decoder.decodeObject(messageCodec, msg, this.spec);
12399
+ logger$4.log `[${message.type}] incoming message`;
12400
+ await this.processAndRespond(message);
12401
+ }
12402
+ catch (e) {
12403
+ logger$4.error `Error while processing fuzz v1 message: ${e}`;
12404
+ logger$4.error `${e}`;
12405
+ if (e instanceof Error) {
12406
+ logger$4.error `${e.stack ?? ""}`;
12407
+ }
12408
+ this.sender.close();
12409
+ }
12410
+ }
12411
+ async processAndRespond(message) {
12412
+ let response = null;
12413
+ switch (message.type) {
12414
+ case MessageType.PeerInfo: {
12415
+ // only support V1
12416
+ if (message.value.fuzzVersion !== 1) {
12417
+ logger$4.warn `Unsupported fuzzer protocol version: ${message.value.fuzzVersion}. Closing`;
12418
+ this.sender.close();
12419
+ return;
12420
+ }
12421
+ // Handle handshake
12422
+ const ourPeerInfo = await this.msgHandler.getPeerInfo(message.value);
12423
+ // Calculate session features (intersection of both peer features)
12424
+ this.sessionFeatures = message.value.features & ourPeerInfo.features;
12425
+ logger$4.info `Handshake completed. Shared features: 0b${this.sessionFeatures.toString(2)}`;
12426
+ logger$4.log `Feature ancestry: ${(this.sessionFeatures & Features.Ancestry) !== 0}`;
12427
+ logger$4.log `Feature fork: ${(this.sessionFeatures & Features.Fork) !== 0}`;
12428
+ response = {
12429
+ type: MessageType.PeerInfo,
12430
+ value: ourPeerInfo,
12431
+ };
12432
+ break;
12433
+ }
12434
+ case MessageType.Initialize: {
12435
+ const stateRoot = await this.msgHandler.initialize(message.value);
12436
+ response = {
12437
+ type: MessageType.StateRoot,
12438
+ value: stateRoot,
12439
+ };
12440
+ break;
12441
+ }
12442
+ case MessageType.ImportBlock: {
12443
+ const result = await this.msgHandler.importBlock(message.value);
12444
+ if (result.isOk) {
12445
+ response = {
12446
+ type: MessageType.StateRoot,
12447
+ value: result.ok,
12448
+ };
12449
+ }
12450
+ else {
12451
+ response = {
12452
+ type: MessageType.Error,
12453
+ value: result.error,
12454
+ };
12455
+ }
12456
+ break;
12457
+ }
12458
+ case MessageType.GetState: {
12459
+ const state = await this.msgHandler.getSerializedState(message.value);
12460
+ response = {
12461
+ type: MessageType.State,
12462
+ value: state,
12463
+ };
12464
+ break;
12465
+ }
12466
+ case MessageType.StateRoot: {
12467
+ logger$4.log `--> Received unexpected 'StateRoot' message from the fuzzer. Closing.`;
12468
+ this.sender.close();
12469
+ return;
12470
+ }
12471
+ case MessageType.State: {
12472
+ logger$4.log `--> Received unexpected 'State' message from the fuzzer. Closing.`;
12473
+ this.sender.close();
12474
+ return;
12475
+ }
12476
+ case MessageType.Error: {
12477
+ logger$4.log `--> Received unexpected 'Error' message from the fuzzer. Closing.`;
12478
+ this.sender.close();
12479
+ return;
12480
+ }
12481
+ default: {
12482
+ logger$4.log `--> Received unexpected message type ${JSON.stringify(message)} from the fuzzer. Closing.`;
12483
+ this.sender.close();
12484
+ try {
12485
+ assertNever(message);
12486
+ }
12487
+ catch {
12488
+ return;
12489
+ }
12490
+ }
12491
+ }
12492
+ if (response !== null) {
12493
+ logger$4.trace `<-- responding with: ${response.type}`;
12494
+ const encoded = Encoder.encodeObject(messageCodec, response, this.spec);
12495
+ this.sender.send(encoded);
12496
+ }
12497
+ else {
12498
+ logger$4.warn `<-- no response generated for: ${message.type}`;
12499
+ }
12500
+ }
12501
+ onClose({ error }) {
12502
+ logger$4.log `Closing the v1 handler. Reason: ${error !== undefined ? error.message : "close"}.`;
12503
+ }
12504
+ /** Check if a specific feature is enabled in the session */
12505
+ hasFeature(feature) {
12506
+ return (this.sessionFeatures & feature) !== 0;
12507
+ }
12508
+ }
12509
+
12510
+ var index$b = /*#__PURE__*/Object.freeze({
12511
+ __proto__: null,
12512
+ AncestryItem: AncestryItem,
12513
+ ErrorMessage: ErrorMessage,
12514
+ get Features () { return Features; },
12515
+ FuzzTarget: FuzzTarget,
12516
+ Initialize: Initialize,
12517
+ KeyValue: KeyValue,
12518
+ get MessageType () { return MessageType; },
12519
+ PeerInfo: PeerInfo,
12520
+ Version: Version,
12521
+ ancestryCodec: ancestryCodec,
12522
+ getStateCodec: getStateCodec,
12523
+ messageCodec: messageCodec,
12524
+ stateCodec: stateCodec,
12525
+ stateRootCodec: stateRootCodec
12526
+ });
12527
+
12528
+ var index$a = /*#__PURE__*/Object.freeze({
12529
+ __proto__: null,
12530
+ v1: index$b
12531
+ });
12532
+
12039
12533
  /** Size of the transfer memo. */
12040
12534
  const TRANSFER_MEMO_BYTES = W_T;
12041
12535
  /**
@@ -12362,16 +12856,12 @@ class PartiallyUpdatedState {
12362
12856
  *
12363
12857
  * NOTE the info may be updated compared to what is in the state.
12364
12858
  *
12365
- * Takes into account newly created services as well.
12859
+ * Takes into account ejected and newly created services as well.
12366
12860
  */
12367
12861
  getServiceInfo(destination) {
12368
12862
  if (destination === null) {
12369
12863
  return null;
12370
12864
  }
12371
- const isEjected = this.stateUpdate.services.servicesRemoved.some((x) => x === destination);
12372
- if (isEjected) {
12373
- return null;
12374
- }
12375
12865
  const maybeNewService = this.stateUpdate.services.servicesUpdates.find((update) => update.serviceId === destination);
12376
12866
  if (maybeNewService !== undefined) {
12377
12867
  return maybeNewService.action.account;
@@ -14087,6 +14577,17 @@ class PageRange {
14087
14577
  }
14088
14578
  return new PageRange(start, length);
14089
14579
  }
14580
+ /** Returns true if the page range is wrapped (`start` >= `end`) and is not empty */
14581
+ isWrapped() {
14582
+ return this.start >= this.end && !this.isEmpty();
14583
+ }
14584
+ /** Checks if given page number is within the range */
14585
+ isInRange(page) {
14586
+ if (this.isWrapped()) {
14587
+ return page >= this.start || page < this.end;
14588
+ }
14589
+ return page >= this.start && page < this.end;
14590
+ }
14090
14591
  /** Checks if a range is empty (`length === 0`) */
14091
14592
  isEmpty() {
14092
14593
  return this.length === 0;
@@ -14194,7 +14695,7 @@ var AccessType;
14194
14695
  AccessType[AccessType["READ"] = 0] = "READ";
14195
14696
  AccessType[AccessType["WRITE"] = 1] = "WRITE";
14196
14697
  })(AccessType || (AccessType = {}));
14197
- // const logger = Logger.new(import.meta.filename, "pvm:mem");
14698
+ const logger$3 = Logger.new(undefined, "pvm:mem");
14198
14699
  class Memory {
14199
14700
  sbrkIndex;
14200
14701
  virtualSbrkIndex;
@@ -14225,7 +14726,7 @@ class Memory {
14225
14726
  if (bytes.length === 0) {
14226
14727
  return Result$1.ok(OK);
14227
14728
  }
14228
- // logger.insane(`MEM[${address}] <- ${BytesBlob.blobFrom(bytes)}`);
14729
+ logger$3.insane `MEM[${address}] <- ${BytesBlob.blobFrom(bytes)}`;
14229
14730
  const pagesResult = this.getPages(address, bytes.length, AccessType.WRITE);
14230
14731
  if (pagesResult.isError) {
14231
14732
  return Result$1.error(pagesResult.error);
@@ -14292,7 +14793,7 @@ class Memory {
14292
14793
  currentPosition += bytesToRead;
14293
14794
  bytesLeft -= bytesToRead;
14294
14795
  }
14295
- // logger.insane(`MEM[${startAddress}] => ${BytesBlob.blobFrom(result)}`);
14796
+ logger$3.insane `MEM[${startAddress}] => ${BytesBlob.blobFrom(result)}`;
14296
14797
  return Result$1.ok(OK);
14297
14798
  }
14298
14799
  sbrk(length) {
@@ -14427,10 +14928,11 @@ class MemoryBuilder {
14427
14928
  startHeapIndex (${startHeapIndex}) has to be less than or equal to endHeapIndex (${endHeapIndex})
14428
14929
  `;
14429
14930
  this.ensureNotFinalized();
14430
- const range = MemoryRange.fromStartAndLength(startHeapIndex, endHeapIndex - startHeapIndex);
14431
- const pages = PageRange.fromMemoryRange(range);
14432
- for (const pageNumber of pages) {
14433
- if (this.initialMemory.has(pageNumber)) {
14931
+ const heapRange = MemoryRange.fromStartAndLength(startHeapIndex, endHeapIndex - startHeapIndex);
14932
+ const heapPagesRange = PageRange.fromMemoryRange(heapRange);
14933
+ const initializedPageNumbers = Array.from(this.initialMemory.keys());
14934
+ for (const pageNumber of initializedPageNumbers) {
14935
+ if (heapPagesRange.isInRange(pageNumber)) {
14434
14936
  throw new IncorrectSbrkIndex();
14435
14937
  }
14436
14938
  }
@@ -16086,7 +16588,7 @@ class ProgramDecoder {
16086
16588
  return Result$1.ok(new ProgramDecoder(program));
16087
16589
  }
16088
16590
  catch (e) {
16089
- logger$2.error(`Invalid program: ${e}`);
16591
+ logger$2.error `Invalid program: ${e}`;
16090
16592
  return Result$1.error(ProgramDecoderError.InvalidProgramError);
16091
16593
  }
16092
16594
  }
@@ -16211,7 +16713,7 @@ class Interpreter {
16211
16713
  const argsType = instructionArgumentTypeMap[currentInstruction] ?? ArgumentType.NO_ARGUMENTS;
16212
16714
  const argsResult = this.argsDecodingResults[argsType];
16213
16715
  this.argsDecoder.fillArgs(this.pc, argsResult);
16214
- logger$1.insane(`[PC: ${this.pc}] ${Instruction[currentInstruction]}`);
16716
+ logger$1.insane `[PC: ${this.pc}] ${Instruction[currentInstruction]}`;
16215
16717
  if (!isValidInstruction) {
16216
16718
  this.instructionResult.status = Result.PANIC;
16217
16719
  }
@@ -16283,7 +16785,7 @@ class Interpreter {
16283
16785
  this.status = Status.HOST;
16284
16786
  break;
16285
16787
  }
16286
- logger$1.insane(`[PC: ${this.pc}] Status: ${Result[this.instructionResult.status]}`);
16788
+ logger$1.insane `[PC: ${this.pc}] Status: ${Result[this.instructionResult.status]}`;
16287
16789
  return this.status;
16288
16790
  }
16289
16791
  this.pc = this.instructionResult.nextPc;
@@ -16517,7 +17019,7 @@ class HostCallsManager {
16517
17019
  return `r${idx}=${value} (0x${value.toString(16)})`;
16518
17020
  })
16519
17021
  .join(", ");
16520
- logger.insane(`[${currentServiceId}] ${context} ${name}${requested}. Gas: ${gas}. Regs: ${registerValues}.`);
17022
+ logger.insane `[${currentServiceId}] ${context} ${name}${requested}. Gas: ${gas}. Regs: ${registerValues}.`;
16521
17023
  }
16522
17024
  }
16523
17025
 
@@ -16870,8 +17372,8 @@ var index$3 = /*#__PURE__*/Object.freeze({
16870
17372
  asOpaqueType: asOpaqueType,
16871
17373
  assertEmpty: assertEmpty,
16872
17374
  assertNever: assertNever,
16873
- block: index$j,
16874
- bytes: index$q,
17375
+ block: index$l,
17376
+ bytes: index$s,
16875
17377
  check: check,
16876
17378
  clampU64ToU32: clampU64ToU32,
16877
17379
  createResults: createResults,
@@ -16879,13 +17381,13 @@ var index$3 = /*#__PURE__*/Object.freeze({
16879
17381
  extractCodeAndMetadata: extractCodeAndMetadata,
16880
17382
  getServiceId: getServiceId,
16881
17383
  getServiceIdOrCurrent: getServiceIdOrCurrent,
16882
- hash: index$n,
17384
+ hash: index$p,
16883
17385
  inspect: inspect,
16884
17386
  instructionArgumentTypeMap: instructionArgumentTypeMap,
16885
17387
  interpreter: index$7,
16886
17388
  isBrowser: isBrowser,
16887
17389
  measure: measure,
16888
- numbers: index$p,
17390
+ numbers: index$r,
16889
17391
  resultToString: resultToString,
16890
17392
  seeThrough: seeThrough,
16891
17393
  slotsToPreimageStatus: slotsToPreimageStatus,
@@ -17599,32 +18101,33 @@ var index = /*#__PURE__*/Object.freeze({
17599
18101
  WorkPackageExecutor: WorkPackageExecutor
17600
18102
  });
17601
18103
 
17602
- exports.block = index$j;
17603
- exports.block_json = index$h;
17604
- exports.bytes = index$q;
17605
- exports.codec = index$o;
17606
- exports.collections = index$l;
17607
- exports.config = index$k;
17608
- exports.config_node = index$f;
17609
- exports.crypto = index$m;
17610
- exports.database = index$b;
17611
- exports.erasure_coding = index$a;
17612
- exports.hash = index$n;
18104
+ exports.block = index$l;
18105
+ exports.block_json = index$j;
18106
+ exports.bytes = index$s;
18107
+ exports.codec = index$q;
18108
+ exports.collections = index$n;
18109
+ exports.config = index$m;
18110
+ exports.config_node = index$h;
18111
+ exports.crypto = index$o;
18112
+ exports.database = index$d;
18113
+ exports.erasure_coding = index$c;
18114
+ exports.fuzz_proto = index$a;
18115
+ exports.hash = index$p;
17613
18116
  exports.jam_host_calls = index$9;
17614
- exports.json_parser = index$i;
17615
- exports.logger = index$g;
18117
+ exports.json_parser = index$k;
18118
+ exports.logger = index$i;
17616
18119
  exports.mmr = index$8;
17617
- exports.numbers = index$p;
17618
- exports.ordering = index$r;
18120
+ exports.numbers = index$r;
18121
+ exports.ordering = index$t;
17619
18122
  exports.pvm = index$3;
17620
18123
  exports.pvm_host_calls = index$6;
17621
18124
  exports.pvm_interpreter = index$7;
17622
18125
  exports.pvm_program = index$4;
17623
18126
  exports.pvm_spi_decoder = index$5;
17624
18127
  exports.shuffling = index$2;
17625
- exports.state = index$e;
18128
+ exports.state = index$g;
17626
18129
  exports.state_json = index$1;
17627
- exports.state_merkleization = index$c;
18130
+ exports.state_merkleization = index$e;
17628
18131
  exports.transition = index;
17629
- exports.trie = index$d;
17630
- exports.utils = index$s;
18132
+ exports.trie = index$f;
18133
+ exports.utils = index$u;