@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.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,29 +15,35 @@ 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 env = typeof process === "undefined" ? {} : process.env;
18
+ const ALL_VERSIONS_IN_ORDER = [GpVersion.V0_6_7, GpVersion.V0_7_0, GpVersion.V0_7_1, GpVersion.V0_7_2];
19
+ const env$1 = typeof process === "undefined" ? {} : process.env;
19
20
  const DEFAULT_VERSION = GpVersion.V0_7_0;
20
- let CURRENT_VERSION = parseCurrentVersion(env.GP_VERSION) ?? DEFAULT_VERSION;
21
- let CURRENT_SUITE = parseCurrentSuite(env.TEST_SUITE) ?? DEFAULT_SUITE;
21
+ let CURRENT_VERSION = parseCurrentVersion(env$1.GP_VERSION) ?? DEFAULT_VERSION;
22
+ let CURRENT_SUITE = parseCurrentSuite(env$1.TEST_SUITE) ?? DEFAULT_SUITE;
22
23
  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) {
@@ -197,6 +204,33 @@ class WithDebug {
197
204
  }
198
205
  }
199
206
 
207
+ const env = typeof process === "undefined" ? {} : process.env;
208
+ /**
209
+ * The function will produce relative path resolver that is adjusted
210
+ * for package location within the workspace.
211
+ *
212
+ * Example:
213
+ * $ npm start -w @typeberry/jam
214
+ *
215
+ * The above command will run `./bin/jam/index.js`, however we would
216
+ * still want relative paths to be resolved according to top-level workspace
217
+ * directory.
218
+ *
219
+ * So the caller, passes the absolute workspace path as argument and get's
220
+ * a function that can properly resolve relative paths.
221
+ *
222
+ * NOTE: the translation happens only for development build! When
223
+ * we build a single library from our project, we no longer mangle the paths.
224
+ */
225
+ const workspacePathFix = env.NODE_ENV === "development"
226
+ ? (workspacePath) => (p) => {
227
+ if (p.startsWith("/")) {
228
+ return p;
229
+ }
230
+ return `${workspacePath}/${p}`;
231
+ }
232
+ : () => (p) => p;
233
+
200
234
  /**
201
235
  * @fileoverview `Opaque<Type, Token>` constructs a unique type which is a subset of Type with a
202
236
  * specified unique token Token. It means that base type cannot be assigned to unique type by accident.
@@ -526,7 +560,7 @@ function isResult(x) {
526
560
  * as an afterthought.
527
561
  */
528
562
 
529
- var index$s = /*#__PURE__*/Object.freeze({
563
+ var index$u = /*#__PURE__*/Object.freeze({
530
564
  __proto__: null,
531
565
  get CURRENT_SUITE () { return CURRENT_SUITE; },
532
566
  get CURRENT_VERSION () { return CURRENT_VERSION; },
@@ -549,7 +583,8 @@ var index$s = /*#__PURE__*/Object.freeze({
549
583
  isBrowser: isBrowser,
550
584
  measure: measure,
551
585
  resultToString: resultToString,
552
- seeThrough: seeThrough
586
+ seeThrough: seeThrough,
587
+ workspacePathFix: workspacePathFix
553
588
  });
554
589
 
555
590
  /**
@@ -679,7 +714,7 @@ class Ordering {
679
714
  }
680
715
  }
681
716
 
682
- var index$r = /*#__PURE__*/Object.freeze({
717
+ var index$t = /*#__PURE__*/Object.freeze({
683
718
  __proto__: null,
684
719
  Ordering: Ordering
685
720
  });
@@ -930,7 +965,7 @@ function u8ArraySameLengthEqual(self, other) {
930
965
  }
931
966
  const bytesBlobComparator = (a, b) => a.compare(b);
932
967
 
933
- var index$q = /*#__PURE__*/Object.freeze({
968
+ var index$s = /*#__PURE__*/Object.freeze({
934
969
  __proto__: null,
935
970
  BitVec: BitVec,
936
971
  Bytes: Bytes,
@@ -1032,7 +1067,7 @@ const minU64 = (a, ...values) => values.reduce((min, value) => (value > min ? mi
1032
1067
  /** Get the biggest value between U64 a and values given as input parameters. */
1033
1068
  const maxU64 = (a, ...values) => values.reduce((max, value) => (value < max ? max : value), a);
1034
1069
 
1035
- var index$p = /*#__PURE__*/Object.freeze({
1070
+ var index$r = /*#__PURE__*/Object.freeze({
1036
1071
  __proto__: null,
1037
1072
  isU16: isU16,
1038
1073
  isU32: isU32,
@@ -2442,7 +2477,7 @@ function sequenceViewFixLen(type, { fixedLength }) {
2442
2477
  }, skipper);
2443
2478
  }
2444
2479
 
2445
- var index$o = /*#__PURE__*/Object.freeze({
2480
+ var index$q = /*#__PURE__*/Object.freeze({
2446
2481
  __proto__: null,
2447
2482
  Decoder: Decoder,
2448
2483
  Descriptor: Descriptor,
@@ -4881,7 +4916,7 @@ var keccak = /*#__PURE__*/Object.freeze({
4881
4916
  hashBlobs: hashBlobs
4882
4917
  });
4883
4918
 
4884
- var index$n = /*#__PURE__*/Object.freeze({
4919
+ var index$p = /*#__PURE__*/Object.freeze({
4885
4920
  __proto__: null,
4886
4921
  HASH_SIZE: HASH_SIZE,
4887
4922
  PageAllocator: PageAllocator,
@@ -4947,7 +4982,7 @@ var keyDerivation = /*#__PURE__*/Object.freeze({
4947
4982
  trivialSeed: trivialSeed
4948
4983
  });
4949
4984
 
4950
- var index$m = /*#__PURE__*/Object.freeze({
4985
+ var index$o = /*#__PURE__*/Object.freeze({
4951
4986
  __proto__: null,
4952
4987
  BANDERSNATCH_KEY_BYTES: BANDERSNATCH_KEY_BYTES,
4953
4988
  BANDERSNATCH_PROOF_BYTES: BANDERSNATCH_PROOF_BYTES,
@@ -5551,7 +5586,7 @@ class TruncatedHashDictionary {
5551
5586
  }
5552
5587
  }
5553
5588
 
5554
- var index$l = /*#__PURE__*/Object.freeze({
5589
+ var index$n = /*#__PURE__*/Object.freeze({
5555
5590
  __proto__: null,
5556
5591
  FixedSizeArray: FixedSizeArray,
5557
5592
  HashDictionary: HashDictionary,
@@ -5746,7 +5781,7 @@ class Bootnode {
5746
5781
  }
5747
5782
  }
5748
5783
 
5749
- var index$k = /*#__PURE__*/Object.freeze({
5784
+ var index$m = /*#__PURE__*/Object.freeze({
5750
5785
  __proto__: null,
5751
5786
  Bootnode: Bootnode,
5752
5787
  ChainSpec: ChainSpec,
@@ -5919,6 +5954,40 @@ var assurances = /*#__PURE__*/Object.freeze({
5919
5954
  assurancesExtrinsicCodec: assurancesExtrinsicCodec
5920
5955
  });
5921
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
+
5922
5991
  /**
5923
5992
  * Proof of signing a contradictory [`Judgement`] of a work report.
5924
5993
  */
@@ -6110,40 +6179,6 @@ var disputes = /*#__PURE__*/Object.freeze({
6110
6179
  Verdict: Verdict
6111
6180
  });
6112
6181
 
6113
- /** Attempt to convert a number into `TimeSlot`. */
6114
- const tryAsTimeSlot = (v) => asOpaqueType(tryAsU32(v));
6115
- /** Attempt to convert a number into `ValidatorIndex`. */
6116
- const tryAsValidatorIndex = (v) => asOpaqueType(tryAsU16(v));
6117
- /** Attempt to convert a number into `ServiceId`. */
6118
- const tryAsServiceId = (v) => asOpaqueType(tryAsU32(v));
6119
- const tryAsServiceGas = (v) => asOpaqueType(tryAsU64(v));
6120
- /** Attempt to convert a number into `CoreIndex`. */
6121
- const tryAsCoreIndex = (v) => asOpaqueType(tryAsU16(v));
6122
- /** Attempt to convert a number into `Epoch`. */
6123
- const tryAsEpoch = (v) => asOpaqueType(tryAsU32(v));
6124
- function tryAsPerValidator(array, spec) {
6125
- check `
6126
- ${array.length === spec.validatorsCount}
6127
- Invalid per-validator array length. Expected ${spec.validatorsCount}, got: ${array.length}
6128
- `;
6129
- return asKnownSize(array);
6130
- }
6131
- const codecPerValidator = (val) => codecWithContext((context) => {
6132
- return codecKnownSizeArray(val, {
6133
- fixedLength: context.validatorsCount,
6134
- });
6135
- });
6136
- function tryAsPerEpochBlock(array, spec) {
6137
- check `
6138
- ${array.length === spec.epochLength}
6139
- Invalid per-epoch-block array length. Expected ${spec.epochLength}, got: ${array.length}
6140
- `;
6141
- return asKnownSize(array);
6142
- }
6143
- const codecPerEpochBlock = (val) => codecWithContext((context) => {
6144
- return codecKnownSizeArray(val, { fixedLength: context.epochLength });
6145
- });
6146
-
6147
6182
  /**
6148
6183
  * Mapping between work package hash and root hash of it's exports.
6149
6184
  *
@@ -7222,8 +7257,26 @@ class Block extends WithDebug {
7222
7257
  this.extrinsic = extrinsic;
7223
7258
  }
7224
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
+ }
7225
7278
 
7226
- var index$j = /*#__PURE__*/Object.freeze({
7279
+ var index$l = /*#__PURE__*/Object.freeze({
7227
7280
  __proto__: null,
7228
7281
  Block: Block,
7229
7282
  EpochMarker: EpochMarker,
@@ -7238,6 +7291,7 @@ var index$j = /*#__PURE__*/Object.freeze({
7238
7291
  codecPerValidator: codecPerValidator,
7239
7292
  codecUtils: codec,
7240
7293
  disputes: disputes,
7294
+ emptyBlock: emptyBlock,
7241
7295
  encodeUnsealedHeader: encodeUnsealedHeader,
7242
7296
  guarantees: guarantees,
7243
7297
  headerViewWithHashCodec: headerViewWithHashCodec,
@@ -7478,7 +7532,7 @@ var json;
7478
7532
  json.object = object;
7479
7533
  })(json || (json = {}));
7480
7534
 
7481
- var index$i = /*#__PURE__*/Object.freeze({
7535
+ var index$k = /*#__PURE__*/Object.freeze({
7482
7536
  __proto__: null,
7483
7537
  get json () { return json; },
7484
7538
  parseFromJson: parseFromJson
@@ -7748,7 +7802,7 @@ const blockFromJson = (spec) => json.object({
7748
7802
  extrinsic: getExtrinsicFromJson(spec),
7749
7803
  }, ({ header, extrinsic }) => Block.create({ header, extrinsic }));
7750
7804
 
7751
- var index$h = /*#__PURE__*/Object.freeze({
7805
+ var index$j = /*#__PURE__*/Object.freeze({
7752
7806
  __proto__: null,
7753
7807
  blockFromJson: blockFromJson,
7754
7808
  disputesExtrinsicFromJson: disputesExtrinsicFromJson,
@@ -8009,6 +8063,23 @@ function parseLevel(lvl) {
8009
8063
  }
8010
8064
 
8011
8065
  // biome-ignore-all lint/suspicious/noConsole: logger
8066
+ function print(level, levelAndName, strings, data) {
8067
+ if (level < levelAndName[0]) {
8068
+ return;
8069
+ }
8070
+ const lvlText = Level[level].padEnd(5);
8071
+ const val = strings.map((v, idx) => `${v}${idx < data.length ? data[idx] : ""}`);
8072
+ const msg = `${lvlText} [${levelAndName[1]}] ${val.join("")}`;
8073
+ if (level === Level.WARN) {
8074
+ console.warn(msg);
8075
+ }
8076
+ else if (level === Level.ERROR) {
8077
+ console.error(msg);
8078
+ }
8079
+ else {
8080
+ console.info(msg);
8081
+ }
8082
+ }
8012
8083
  /** An optimized logger that ignores `TRACE`, `DEBUG` and `LOG` messages.
8013
8084
  *
8014
8085
  * Use the `create` method to instantiate the right instance of a more specialized logger.
@@ -8039,109 +8110,91 @@ class ConsoleTransport {
8039
8110
  constructor(options) {
8040
8111
  this.options = options;
8041
8112
  }
8042
- insane(_moduleName, _val) {
8113
+ insane(_levelAndName, _strings, _data) {
8043
8114
  /* no-op */
8044
8115
  }
8045
- trace(_moduleName, _val) {
8116
+ trace(_levelAndName, _strings, _data) {
8046
8117
  /* no-op */
8047
8118
  }
8048
- log(_moduleName, _val) {
8119
+ log(_levelAndName, _strings, _data) {
8049
8120
  /* no-op */
8050
8121
  }
8051
- info(_moduleName, _val) {
8122
+ info(_levelAndName, _strings, _data) {
8052
8123
  /* no-op */
8053
8124
  }
8054
- warn(moduleName, val) {
8055
- this.push(Level.WARN, moduleName, val);
8125
+ warn(levelAndName, strings, data) {
8126
+ print(Level.WARN, levelAndName, strings, data);
8056
8127
  }
8057
- error(moduleName, val) {
8058
- this.push(Level.ERROR, moduleName, val);
8059
- }
8060
- push(level, moduleName, val) {
8061
- const shortModule = moduleName.replace(this.options.workingDir, "");
8062
- const configuredLevel = findLevel(this.options, moduleName);
8063
- const lvlText = Level[level].padEnd(5);
8064
- if (level < configuredLevel) {
8065
- return;
8066
- }
8067
- const msg = `${lvlText} [${shortModule}] ${val}`;
8068
- if (level === Level.WARN) {
8069
- console.warn(msg);
8070
- }
8071
- else if (level === Level.ERROR) {
8072
- console.error(msg);
8073
- }
8074
- else {
8075
- console.info(msg);
8076
- }
8128
+ error(levelAndName, strings, data) {
8129
+ print(Level.ERROR, levelAndName, strings, data);
8077
8130
  }
8078
8131
  }
8079
8132
  /**
8080
8133
  * Insane version of console logger - supports insane level.
8081
8134
  */
8082
8135
  class InsaneConsoleLogger extends ConsoleTransport {
8083
- insane(moduleName, val) {
8084
- this.push(Level.INSANE, moduleName, val);
8136
+ insane(levelAndName, strings, data) {
8137
+ print(Level.INSANE, levelAndName, strings, data);
8085
8138
  }
8086
- trace(moduleName, val) {
8087
- this.push(Level.TRACE, moduleName, val);
8139
+ trace(levelAndName, strings, data) {
8140
+ print(Level.TRACE, levelAndName, strings, data);
8088
8141
  }
8089
- log(moduleName, val) {
8090
- this.push(Level.LOG, moduleName, val);
8142
+ log(levelAndName, strings, data) {
8143
+ print(Level.LOG, levelAndName, strings, data);
8091
8144
  }
8092
- info(moduleName, val) {
8093
- this.push(Level.INFO, moduleName, val);
8145
+ info(levelAndName, strings, data) {
8146
+ print(Level.INFO, levelAndName, strings, data);
8094
8147
  }
8095
8148
  }
8096
8149
  /**
8097
8150
  * A basic version of console logger - printing everything.
8098
8151
  */
8099
8152
  class TraceConsoleTransport extends ConsoleTransport {
8100
- insane(_moduleName, _val) {
8153
+ insane(_levelAndName, _strings, _data) {
8101
8154
  /* no-op */
8102
8155
  }
8103
- trace(moduleName, val) {
8104
- this.push(Level.TRACE, moduleName, val);
8156
+ trace(levelAndName, strings, data) {
8157
+ print(Level.TRACE, levelAndName, strings, data);
8105
8158
  }
8106
- log(moduleName, val) {
8107
- this.push(Level.LOG, moduleName, val);
8159
+ log(levelAndName, strings, data) {
8160
+ print(Level.LOG, levelAndName, strings, data);
8108
8161
  }
8109
- info(moduleName, val) {
8110
- this.push(Level.INFO, moduleName, val);
8162
+ info(levelAndName, strings, data) {
8163
+ print(Level.INFO, levelAndName, strings, data);
8111
8164
  }
8112
8165
  }
8113
8166
  /**
8114
8167
  * An optimized version of the logger - completely ignores `TRACE` level calls.
8115
8168
  */
8116
8169
  class LogConsoleTransport extends ConsoleTransport {
8117
- insane(_moduleName, _val) {
8170
+ insane(_levelAndName, _strings, _data) {
8118
8171
  /* no-op */
8119
8172
  }
8120
- trace(_moduleName, _val) {
8173
+ trace(_levelAndName, _strings, _data) {
8121
8174
  /* no-op */
8122
8175
  }
8123
- log(moduleName, val) {
8124
- this.push(Level.LOG, moduleName, val);
8176
+ log(levelAndName, strings, data) {
8177
+ print(Level.LOG, levelAndName, strings, data);
8125
8178
  }
8126
- info(moduleName, val) {
8127
- this.push(Level.INFO, moduleName, val);
8179
+ info(levelAndName, strings, data) {
8180
+ print(Level.INFO, levelAndName, strings, data);
8128
8181
  }
8129
8182
  }
8130
8183
  /**
8131
8184
  * An optimized version of the logger - completely ignores `TRACE` & `DEBUG` level calls.
8132
8185
  */
8133
8186
  class InfoConsoleTransport extends ConsoleTransport {
8134
- insane(_moduleName, _val) {
8187
+ insane(_levelAndName, _strings, _data) {
8135
8188
  /* no-op */
8136
8189
  }
8137
- trace(_moduleName, _val) {
8190
+ trace(_levelAndName, _strings, _data) {
8138
8191
  /* no-op */
8139
8192
  }
8140
- log(_moduleName, _val) {
8193
+ log(_levelAndName, _strings, _data) {
8141
8194
  /* no-op */
8142
8195
  }
8143
- info(moduleName, val) {
8144
- this.push(Level.INFO, moduleName, val);
8196
+ info(levelAndName, strings, data) {
8197
+ print(Level.INFO, levelAndName, strings, data);
8145
8198
  }
8146
8199
  }
8147
8200
 
@@ -8174,11 +8227,6 @@ class Logger {
8174
8227
  const module = moduleName ?? fName;
8175
8228
  return new Logger(module.padStart(8, " "), GLOBAL_CONFIG);
8176
8229
  }
8177
- /**
8178
- * Return currently configured level for given module. */
8179
- static getLevel(moduleName) {
8180
- return findLevel(GLOBAL_CONFIG.options, moduleName);
8181
- }
8182
8230
  /**
8183
8231
  * Global configuration of all loggers.
8184
8232
  *
@@ -8209,37 +8257,50 @@ class Logger {
8209
8257
  const options = parseLoggerOptions(input, defaultLevel, workingDir);
8210
8258
  Logger.configureAllFromOptions(options);
8211
8259
  }
8260
+ cachedLevelAndName;
8212
8261
  constructor(moduleName, config) {
8213
8262
  this.moduleName = moduleName;
8214
8263
  this.config = config;
8215
8264
  }
8265
+ /** Return currently configured level for given module. */
8266
+ getLevel() {
8267
+ return this.getLevelAndName()[0];
8268
+ }
8269
+ getLevelAndName() {
8270
+ if (this.cachedLevelAndName === undefined) {
8271
+ const level = findLevel(this.config.options, this.moduleName);
8272
+ const shortName = this.moduleName.replace(this.config.options.workingDir, "");
8273
+ this.cachedLevelAndName = [level, shortName];
8274
+ }
8275
+ return this.cachedLevelAndName;
8276
+ }
8216
8277
  /** Log a message with `INSANE` level. */
8217
- insane(val) {
8218
- this.config.transport.insane(this.moduleName, val);
8278
+ insane(strings, ...data) {
8279
+ this.config.transport.insane(this.getLevelAndName(), strings, data);
8219
8280
  }
8220
8281
  /** Log a message with `TRACE` level. */
8221
- trace(val) {
8222
- this.config.transport.trace(this.moduleName, val);
8282
+ trace(strings, ...data) {
8283
+ this.config.transport.trace(this.getLevelAndName(), strings, data);
8223
8284
  }
8224
8285
  /** Log a message with `DEBUG`/`LOG` level. */
8225
- log(val) {
8226
- this.config.transport.log(this.moduleName, val);
8286
+ log(strings, ...data) {
8287
+ this.config.transport.log(this.getLevelAndName(), strings, data);
8227
8288
  }
8228
8289
  /** Log a message with `INFO` level. */
8229
- info(val) {
8230
- this.config.transport.info(this.moduleName, val);
8290
+ info(strings, ...data) {
8291
+ this.config.transport.info(this.getLevelAndName(), strings, data);
8231
8292
  }
8232
8293
  /** Log a message with `WARN` level. */
8233
- warn(val) {
8234
- this.config.transport.warn(this.moduleName, val);
8294
+ warn(strings, ...data) {
8295
+ this.config.transport.warn(this.getLevelAndName(), strings, data);
8235
8296
  }
8236
8297
  /** Log a message with `ERROR` level. */
8237
- error(val) {
8238
- this.config.transport.error(this.moduleName, val);
8298
+ error(strings, ...data) {
8299
+ this.config.transport.error(this.getLevelAndName(), strings, data);
8239
8300
  }
8240
8301
  }
8241
8302
 
8242
- var index$g = /*#__PURE__*/Object.freeze({
8303
+ var index$i = /*#__PURE__*/Object.freeze({
8243
8304
  __proto__: null,
8244
8305
  get Level () { return Level; },
8245
8306
  Logger: Logger,
@@ -8262,7 +8323,7 @@ class AuthorshipOptions {
8262
8323
  }
8263
8324
  }
8264
8325
 
8265
- const logger$3 = Logger.new(import.meta.filename, "config");
8326
+ const logger$5 = Logger.new(import.meta.filename, "config");
8266
8327
  /** Development config. Will accept unsealed blocks for now. */
8267
8328
  const DEV_CONFIG = "dev";
8268
8329
  /** Default config file. */
@@ -8321,15 +8382,15 @@ class NodeConfiguration {
8321
8382
  }
8322
8383
  function loadConfig(configPath) {
8323
8384
  if (configPath === DEFAULT_CONFIG) {
8324
- logger$3.log("🔧 Loading DEFAULT config");
8385
+ logger$5.log `🔧 Loading DEFAULT config`;
8325
8386
  return parseFromJson(configs.default, NodeConfiguration.fromJson);
8326
8387
  }
8327
8388
  if (configPath === DEV_CONFIG) {
8328
- logger$3.log("🔧 Loading DEV config");
8389
+ logger$5.log `🔧 Loading DEV config`;
8329
8390
  return parseFromJson(configs.dev, NodeConfiguration.fromJson);
8330
8391
  }
8331
8392
  try {
8332
- logger$3.log(`🔧 Loading config from ${configPath}`);
8393
+ logger$5.log `🔧 Loading config from ${configPath}`;
8333
8394
  const configFile = fs.readFileSync(configPath, "utf8");
8334
8395
  const parsed = JSON.parse(configFile);
8335
8396
  return parseFromJson(parsed, NodeConfiguration.fromJson);
@@ -8339,7 +8400,7 @@ function loadConfig(configPath) {
8339
8400
  }
8340
8401
  }
8341
8402
 
8342
- var index$f = /*#__PURE__*/Object.freeze({
8403
+ var index$h = /*#__PURE__*/Object.freeze({
8343
8404
  __proto__: null,
8344
8405
  DEFAULT_CONFIG: DEFAULT_CONFIG,
8345
8406
  DEV_CONFIG: DEV_CONFIG,
@@ -10005,7 +10066,7 @@ const serviceDataCodec = codec$1.dictionary(codec$1.u32.asOpaque(), serviceEntri
10005
10066
  sortKeys: (a, b) => a - b,
10006
10067
  });
10007
10068
 
10008
- var index$e = /*#__PURE__*/Object.freeze({
10069
+ var index$g = /*#__PURE__*/Object.freeze({
10009
10070
  __proto__: null,
10010
10071
  AccumulationOutput: AccumulationOutput,
10011
10072
  AutoAccumulate: AutoAccumulate,
@@ -11015,7 +11076,7 @@ const bitLookup = [
11015
11076
  [0b00000000, 8],
11016
11077
  ];
11017
11078
 
11018
- var index$d = /*#__PURE__*/Object.freeze({
11079
+ var index$f = /*#__PURE__*/Object.freeze({
11019
11080
  __proto__: null,
11020
11081
  BranchNode: BranchNode,
11021
11082
  InMemoryTrie: InMemoryTrie,
@@ -11361,7 +11422,7 @@ function loadState(spec, entries) {
11361
11422
  * hashmap of `key -> value` entries.
11362
11423
  */
11363
11424
 
11364
- var index$c = /*#__PURE__*/Object.freeze({
11425
+ var index$e = /*#__PURE__*/Object.freeze({
11365
11426
  __proto__: null,
11366
11427
  SerializedService: SerializedService,
11367
11428
  SerializedState: SerializedState,
@@ -11647,7 +11708,7 @@ class InMemoryStates {
11647
11708
  }
11648
11709
  }
11649
11710
 
11650
- var index$b = /*#__PURE__*/Object.freeze({
11711
+ var index$d = /*#__PURE__*/Object.freeze({
11651
11712
  __proto__: null,
11652
11713
  InMemoryBlocks: InMemoryBlocks,
11653
11714
  InMemoryStates: InMemoryStates,
@@ -12009,7 +12070,7 @@ const initEc = async () => {
12009
12070
  await init.reedSolomon();
12010
12071
  };
12011
12072
 
12012
- var index$a = /*#__PURE__*/Object.freeze({
12073
+ var index$c = /*#__PURE__*/Object.freeze({
12013
12074
  __proto__: null,
12014
12075
  N_CHUNKS_REDUNDANCY: N_CHUNKS_REDUNDANCY,
12015
12076
  N_CHUNKS_REQUIRED: N_CHUNKS_REQUIRED,
@@ -12033,6 +12094,439 @@ var index$a = /*#__PURE__*/Object.freeze({
12033
12094
  unzip: unzip
12034
12095
  });
12035
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
+
12036
12530
  /** Size of the transfer memo. */
12037
12531
  const TRANSFER_MEMO_BYTES = W_T;
12038
12532
  /**
@@ -12359,16 +12853,12 @@ class PartiallyUpdatedState {
12359
12853
  *
12360
12854
  * NOTE the info may be updated compared to what is in the state.
12361
12855
  *
12362
- * Takes into account newly created services as well.
12856
+ * Takes into account ejected and newly created services as well.
12363
12857
  */
12364
12858
  getServiceInfo(destination) {
12365
12859
  if (destination === null) {
12366
12860
  return null;
12367
12861
  }
12368
- const isEjected = this.stateUpdate.services.servicesRemoved.some((x) => x === destination);
12369
- if (isEjected) {
12370
- return null;
12371
- }
12372
12862
  const maybeNewService = this.stateUpdate.services.servicesUpdates.find((update) => update.serviceId === destination);
12373
12863
  if (maybeNewService !== undefined) {
12374
12864
  return maybeNewService.action.account;
@@ -14084,6 +14574,17 @@ class PageRange {
14084
14574
  }
14085
14575
  return new PageRange(start, length);
14086
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
+ }
14087
14588
  /** Checks if a range is empty (`length === 0`) */
14088
14589
  isEmpty() {
14089
14590
  return this.length === 0;
@@ -14191,7 +14692,7 @@ var AccessType;
14191
14692
  AccessType[AccessType["READ"] = 0] = "READ";
14192
14693
  AccessType[AccessType["WRITE"] = 1] = "WRITE";
14193
14694
  })(AccessType || (AccessType = {}));
14194
- // const logger = Logger.new(import.meta.filename, "pvm:mem");
14695
+ const logger$3 = Logger.new(import.meta.filename, "pvm:mem");
14195
14696
  class Memory {
14196
14697
  sbrkIndex;
14197
14698
  virtualSbrkIndex;
@@ -14222,7 +14723,7 @@ class Memory {
14222
14723
  if (bytes.length === 0) {
14223
14724
  return Result$1.ok(OK);
14224
14725
  }
14225
- // logger.insane(`MEM[${address}] <- ${BytesBlob.blobFrom(bytes)}`);
14726
+ logger$3.insane `MEM[${address}] <- ${BytesBlob.blobFrom(bytes)}`;
14226
14727
  const pagesResult = this.getPages(address, bytes.length, AccessType.WRITE);
14227
14728
  if (pagesResult.isError) {
14228
14729
  return Result$1.error(pagesResult.error);
@@ -14289,7 +14790,7 @@ class Memory {
14289
14790
  currentPosition += bytesToRead;
14290
14791
  bytesLeft -= bytesToRead;
14291
14792
  }
14292
- // logger.insane(`MEM[${startAddress}] => ${BytesBlob.blobFrom(result)}`);
14793
+ logger$3.insane `MEM[${startAddress}] => ${BytesBlob.blobFrom(result)}`;
14293
14794
  return Result$1.ok(OK);
14294
14795
  }
14295
14796
  sbrk(length) {
@@ -14424,10 +14925,11 @@ class MemoryBuilder {
14424
14925
  startHeapIndex (${startHeapIndex}) has to be less than or equal to endHeapIndex (${endHeapIndex})
14425
14926
  `;
14426
14927
  this.ensureNotFinalized();
14427
- const range = MemoryRange.fromStartAndLength(startHeapIndex, endHeapIndex - startHeapIndex);
14428
- const pages = PageRange.fromMemoryRange(range);
14429
- for (const pageNumber of pages) {
14430
- 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)) {
14431
14933
  throw new IncorrectSbrkIndex();
14432
14934
  }
14433
14935
  }
@@ -16083,7 +16585,7 @@ class ProgramDecoder {
16083
16585
  return Result$1.ok(new ProgramDecoder(program));
16084
16586
  }
16085
16587
  catch (e) {
16086
- logger$2.error(`Invalid program: ${e}`);
16588
+ logger$2.error `Invalid program: ${e}`;
16087
16589
  return Result$1.error(ProgramDecoderError.InvalidProgramError);
16088
16590
  }
16089
16591
  }
@@ -16208,7 +16710,7 @@ class Interpreter {
16208
16710
  const argsType = instructionArgumentTypeMap[currentInstruction] ?? ArgumentType.NO_ARGUMENTS;
16209
16711
  const argsResult = this.argsDecodingResults[argsType];
16210
16712
  this.argsDecoder.fillArgs(this.pc, argsResult);
16211
- logger$1.insane(`[PC: ${this.pc}] ${Instruction[currentInstruction]}`);
16713
+ logger$1.insane `[PC: ${this.pc}] ${Instruction[currentInstruction]}`;
16212
16714
  if (!isValidInstruction) {
16213
16715
  this.instructionResult.status = Result.PANIC;
16214
16716
  }
@@ -16280,7 +16782,7 @@ class Interpreter {
16280
16782
  this.status = Status.HOST;
16281
16783
  break;
16282
16784
  }
16283
- logger$1.insane(`[PC: ${this.pc}] Status: ${Result[this.instructionResult.status]}`);
16785
+ logger$1.insane `[PC: ${this.pc}] Status: ${Result[this.instructionResult.status]}`;
16284
16786
  return this.status;
16285
16787
  }
16286
16788
  this.pc = this.instructionResult.nextPc;
@@ -16514,7 +17016,7 @@ class HostCallsManager {
16514
17016
  return `r${idx}=${value} (0x${value.toString(16)})`;
16515
17017
  })
16516
17018
  .join(", ");
16517
- logger.insane(`[${currentServiceId}] ${context} ${name}${requested}. Gas: ${gas}. Regs: ${registerValues}.`);
17019
+ logger.insane `[${currentServiceId}] ${context} ${name}${requested}. Gas: ${gas}. Regs: ${registerValues}.`;
16518
17020
  }
16519
17021
  }
16520
17022
 
@@ -16867,8 +17369,8 @@ var index$3 = /*#__PURE__*/Object.freeze({
16867
17369
  asOpaqueType: asOpaqueType,
16868
17370
  assertEmpty: assertEmpty,
16869
17371
  assertNever: assertNever,
16870
- block: index$j,
16871
- bytes: index$q,
17372
+ block: index$l,
17373
+ bytes: index$s,
16872
17374
  check: check,
16873
17375
  clampU64ToU32: clampU64ToU32,
16874
17376
  createResults: createResults,
@@ -16876,13 +17378,13 @@ var index$3 = /*#__PURE__*/Object.freeze({
16876
17378
  extractCodeAndMetadata: extractCodeAndMetadata,
16877
17379
  getServiceId: getServiceId,
16878
17380
  getServiceIdOrCurrent: getServiceIdOrCurrent,
16879
- hash: index$n,
17381
+ hash: index$p,
16880
17382
  inspect: inspect,
16881
17383
  instructionArgumentTypeMap: instructionArgumentTypeMap,
16882
17384
  interpreter: index$7,
16883
17385
  isBrowser: isBrowser,
16884
17386
  measure: measure,
16885
- numbers: index$p,
17387
+ numbers: index$r,
16886
17388
  resultToString: resultToString,
16887
17389
  seeThrough: seeThrough,
16888
17390
  slotsToPreimageStatus: slotsToPreimageStatus,
@@ -17596,4 +18098,4 @@ var index = /*#__PURE__*/Object.freeze({
17596
18098
  WorkPackageExecutor: WorkPackageExecutor
17597
18099
  });
17598
18100
 
17599
- 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 };