@typeberry/lib 0.1.2-ef67dce → 0.1.3-135961b

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.
Files changed (4) hide show
  1. package/index.cjs +524 -52
  2. package/index.d.ts +1252 -661
  3. package/index.js +505 -34
  4. package/package.json +1 -1
package/index.cjs CHANGED
@@ -563,7 +563,7 @@ function isResult(x) {
563
563
  * as an afterthought.
564
564
  */
565
565
 
566
- var index$s = /*#__PURE__*/Object.freeze({
566
+ var index$u = /*#__PURE__*/Object.freeze({
567
567
  __proto__: null,
568
568
  get CURRENT_SUITE () { return CURRENT_SUITE; },
569
569
  get CURRENT_VERSION () { return CURRENT_VERSION; },
@@ -717,7 +717,7 @@ class Ordering {
717
717
  }
718
718
  }
719
719
 
720
- var index$r = /*#__PURE__*/Object.freeze({
720
+ var index$t = /*#__PURE__*/Object.freeze({
721
721
  __proto__: null,
722
722
  Ordering: Ordering
723
723
  });
@@ -968,7 +968,7 @@ function u8ArraySameLengthEqual(self, other) {
968
968
  }
969
969
  const bytesBlobComparator = (a, b) => a.compare(b);
970
970
 
971
- var index$q = /*#__PURE__*/Object.freeze({
971
+ var index$s = /*#__PURE__*/Object.freeze({
972
972
  __proto__: null,
973
973
  BitVec: BitVec,
974
974
  Bytes: Bytes,
@@ -1070,7 +1070,7 @@ const minU64 = (a, ...values) => values.reduce((min, value) => (value > min ? mi
1070
1070
  /** Get the biggest value between U64 a and values given as input parameters. */
1071
1071
  const maxU64 = (a, ...values) => values.reduce((max, value) => (value < max ? max : value), a);
1072
1072
 
1073
- var index$p = /*#__PURE__*/Object.freeze({
1073
+ var index$r = /*#__PURE__*/Object.freeze({
1074
1074
  __proto__: null,
1075
1075
  isU16: isU16,
1076
1076
  isU32: isU32,
@@ -1947,13 +1947,15 @@ function validateLength(range, length, context) {
1947
1947
 
1948
1948
  /** A caching wrapper for either object or sequence item. */
1949
1949
  class ViewField {
1950
+ name;
1950
1951
  getView;
1951
1952
  getValue;
1952
1953
  getEncoded;
1953
1954
  cachedValue;
1954
1955
  cachedView;
1955
1956
  cachedBlob;
1956
- constructor(getView, getValue, getEncoded) {
1957
+ constructor(name, getView, getValue, getEncoded) {
1958
+ this.name = name;
1957
1959
  this.getView = getView;
1958
1960
  this.getValue = getValue;
1959
1961
  this.getEncoded = getEncoded;
@@ -1979,6 +1981,9 @@ class ViewField {
1979
1981
  }
1980
1982
  return this.cachedBlob;
1981
1983
  }
1984
+ toString() {
1985
+ return `ViewField<${this.name}>`;
1986
+ }
1982
1987
  }
1983
1988
  /**
1984
1989
  * A base class for all the lazy views.
@@ -2053,7 +2058,7 @@ class ObjectView {
2053
2058
  const fieldDecoder = skipper.decoder.clone();
2054
2059
  const field = this.descriptorsKeys[i];
2055
2060
  const type = this.descriptors[field];
2056
- lastItem = new ViewField(() => type.View.decode(fieldDecoder.clone()), () => type.decode(fieldDecoder.clone()), () => type.skipEncoded(fieldDecoder.clone()));
2061
+ lastItem = new ViewField(`${this.toString()}.${String(field)}`, () => type.View.decode(fieldDecoder.clone()), () => type.decode(fieldDecoder.clone()), () => type.skipEncoded(fieldDecoder.clone()));
2057
2062
  // skip the field
2058
2063
  type.skip(skipper);
2059
2064
  // cache data
@@ -2065,6 +2070,9 @@ class ObjectView {
2065
2070
  }
2066
2071
  return lastItem;
2067
2072
  }
2073
+ toString() {
2074
+ return `View<${this.materializedConstructor.name}>(cache: ${this.cache.size})`;
2075
+ }
2068
2076
  }
2069
2077
  /**
2070
2078
  * A lazy-evaluated decoder of a sequence.
@@ -2153,7 +2161,7 @@ class SequenceView {
2153
2161
  // create new cached prop
2154
2162
  const fieldDecoder = skipper.decoder.clone();
2155
2163
  const type = this.descriptor;
2156
- lastItem = new ViewField(() => type.View.decode(fieldDecoder.clone()), () => type.decode(fieldDecoder.clone()), () => type.skipEncoded(fieldDecoder.clone()));
2164
+ lastItem = new ViewField(`${this.toString()}[${index}]`, () => type.View.decode(fieldDecoder.clone()), () => type.decode(fieldDecoder.clone()), () => type.skipEncoded(fieldDecoder.clone()));
2157
2165
  // skip the field
2158
2166
  type.skip(skipper);
2159
2167
  // cache data
@@ -2165,6 +2173,9 @@ class SequenceView {
2165
2173
  }
2166
2174
  return lastItem;
2167
2175
  }
2176
+ toString() {
2177
+ return `SequenceView<${this.descriptor.name}>(cache: ${this.cache.size})`;
2178
+ }
2168
2179
  }
2169
2180
 
2170
2181
  /**
@@ -2480,7 +2491,7 @@ function sequenceViewFixLen(type, { fixedLength }) {
2480
2491
  }, skipper);
2481
2492
  }
2482
2493
 
2483
- var index$o = /*#__PURE__*/Object.freeze({
2494
+ var index$q = /*#__PURE__*/Object.freeze({
2484
2495
  __proto__: null,
2485
2496
  Decoder: Decoder,
2486
2497
  Descriptor: Descriptor,
@@ -4919,7 +4930,7 @@ var keccak = /*#__PURE__*/Object.freeze({
4919
4930
  hashBlobs: hashBlobs
4920
4931
  });
4921
4932
 
4922
- var index$n = /*#__PURE__*/Object.freeze({
4933
+ var index$p = /*#__PURE__*/Object.freeze({
4923
4934
  __proto__: null,
4924
4935
  HASH_SIZE: HASH_SIZE,
4925
4936
  PageAllocator: PageAllocator,
@@ -4985,7 +4996,7 @@ var keyDerivation = /*#__PURE__*/Object.freeze({
4985
4996
  trivialSeed: trivialSeed
4986
4997
  });
4987
4998
 
4988
- var index$m = /*#__PURE__*/Object.freeze({
4999
+ var index$o = /*#__PURE__*/Object.freeze({
4989
5000
  __proto__: null,
4990
5001
  BANDERSNATCH_KEY_BYTES: BANDERSNATCH_KEY_BYTES,
4991
5002
  BANDERSNATCH_PROOF_BYTES: BANDERSNATCH_PROOF_BYTES,
@@ -5589,7 +5600,7 @@ class TruncatedHashDictionary {
5589
5600
  }
5590
5601
  }
5591
5602
 
5592
- var index$l = /*#__PURE__*/Object.freeze({
5603
+ var index$n = /*#__PURE__*/Object.freeze({
5593
5604
  __proto__: null,
5594
5605
  FixedSizeArray: FixedSizeArray,
5595
5606
  HashDictionary: HashDictionary,
@@ -5784,7 +5795,7 @@ class Bootnode {
5784
5795
  }
5785
5796
  }
5786
5797
 
5787
- var index$k = /*#__PURE__*/Object.freeze({
5798
+ var index$m = /*#__PURE__*/Object.freeze({
5788
5799
  __proto__: null,
5789
5800
  Bootnode: Bootnode,
5790
5801
  ChainSpec: ChainSpec,
@@ -7279,7 +7290,7 @@ function emptyBlock(slot = tryAsTimeSlot(0)) {
7279
7290
  });
7280
7291
  }
7281
7292
 
7282
- var index$j = /*#__PURE__*/Object.freeze({
7293
+ var index$l = /*#__PURE__*/Object.freeze({
7283
7294
  __proto__: null,
7284
7295
  Block: Block,
7285
7296
  EpochMarker: EpochMarker,
@@ -7535,7 +7546,7 @@ var json;
7535
7546
  json.object = object;
7536
7547
  })(json || (json = {}));
7537
7548
 
7538
- var index$i = /*#__PURE__*/Object.freeze({
7549
+ var index$k = /*#__PURE__*/Object.freeze({
7539
7550
  __proto__: null,
7540
7551
  get json () { return json; },
7541
7552
  parseFromJson: parseFromJson
@@ -7805,7 +7816,7 @@ const blockFromJson = (spec) => json.object({
7805
7816
  extrinsic: getExtrinsicFromJson(spec),
7806
7817
  }, ({ header, extrinsic }) => Block.create({ header, extrinsic }));
7807
7818
 
7808
- var index$h = /*#__PURE__*/Object.freeze({
7819
+ var index$j = /*#__PURE__*/Object.freeze({
7809
7820
  __proto__: null,
7810
7821
  blockFromJson: blockFromJson,
7811
7822
  disputesExtrinsicFromJson: disputesExtrinsicFromJson,
@@ -8303,7 +8314,7 @@ class Logger {
8303
8314
  }
8304
8315
  }
8305
8316
 
8306
- var index$g = /*#__PURE__*/Object.freeze({
8317
+ var index$i = /*#__PURE__*/Object.freeze({
8307
8318
  __proto__: null,
8308
8319
  get Level () { return Level; },
8309
8320
  Logger: Logger,
@@ -8326,7 +8337,7 @@ class AuthorshipOptions {
8326
8337
  }
8327
8338
  }
8328
8339
 
8329
- const logger$4 = Logger.new(undefined, "config");
8340
+ const logger$5 = Logger.new(undefined, "config");
8330
8341
  /** Development config. Will accept unsealed blocks for now. */
8331
8342
  const DEV_CONFIG = "dev";
8332
8343
  /** Default config file. */
@@ -8385,15 +8396,15 @@ class NodeConfiguration {
8385
8396
  }
8386
8397
  function loadConfig(configPath) {
8387
8398
  if (configPath === DEFAULT_CONFIG) {
8388
- logger$4.log `🔧 Loading DEFAULT config`;
8399
+ logger$5.log `🔧 Loading DEFAULT config`;
8389
8400
  return parseFromJson(configs.default, NodeConfiguration.fromJson);
8390
8401
  }
8391
8402
  if (configPath === DEV_CONFIG) {
8392
- logger$4.log `🔧 Loading DEV config`;
8403
+ logger$5.log `🔧 Loading DEV config`;
8393
8404
  return parseFromJson(configs.dev, NodeConfiguration.fromJson);
8394
8405
  }
8395
8406
  try {
8396
- logger$4.log `🔧 Loading config from ${configPath}`;
8407
+ logger$5.log `🔧 Loading config from ${configPath}`;
8397
8408
  const configFile = fs.readFileSync(configPath, "utf8");
8398
8409
  const parsed = JSON.parse(configFile);
8399
8410
  return parseFromJson(parsed, NodeConfiguration.fromJson);
@@ -8403,7 +8414,7 @@ function loadConfig(configPath) {
8403
8414
  }
8404
8415
  }
8405
8416
 
8406
- var index$f = /*#__PURE__*/Object.freeze({
8417
+ var index$h = /*#__PURE__*/Object.freeze({
8407
8418
  __proto__: null,
8408
8419
  DEFAULT_CONFIG: DEFAULT_CONFIG,
8409
8420
  DEV_CONFIG: DEV_CONFIG,
@@ -8720,6 +8731,10 @@ class DisputesRecords {
8720
8731
  static create({ goodSet, badSet, wonkySet, punishSet }) {
8721
8732
  return new DisputesRecords(goodSet, badSet, wonkySet, punishSet);
8722
8733
  }
8734
+ goodSetDict;
8735
+ badSetDict;
8736
+ wonkySetDict;
8737
+ punishSetDict;
8723
8738
  constructor(
8724
8739
  /** `goodSet`: all work-reports hashes which were judged to be correct */
8725
8740
  goodSet,
@@ -8733,6 +8748,18 @@ class DisputesRecords {
8733
8748
  this.badSet = badSet;
8734
8749
  this.wonkySet = wonkySet;
8735
8750
  this.punishSet = punishSet;
8751
+ this.goodSetDict = HashSet.from(goodSet.array);
8752
+ this.badSetDict = HashSet.from(badSet.array);
8753
+ this.wonkySetDict = HashSet.from(wonkySet.array);
8754
+ this.punishSetDict = HashSet.from(punishSet.array);
8755
+ }
8756
+ asDictionaries() {
8757
+ return {
8758
+ goodSet: this.goodSetDict,
8759
+ badSet: this.badSetDict,
8760
+ wonkySet: this.wonkySetDict,
8761
+ punishSet: this.punishSetDict,
8762
+ };
8736
8763
  }
8737
8764
  static fromSortedArrays({ goodSet, badSet, wonkySet, punishSet, }) {
8738
8765
  return new DisputesRecords(SortedSet.fromSortedArray(hashComparator, goodSet), SortedSet.fromSortedArray(hashComparator, badSet), SortedSet.fromSortedArray(hashComparator, wonkySet), SortedSet.fromSortedArray(hashComparator, punishSet));
@@ -10069,7 +10096,7 @@ const serviceDataCodec = codec$1.dictionary(codec$1.u32.asOpaque(), serviceEntri
10069
10096
  sortKeys: (a, b) => a - b,
10070
10097
  });
10071
10098
 
10072
- var index$e = /*#__PURE__*/Object.freeze({
10099
+ var index$g = /*#__PURE__*/Object.freeze({
10073
10100
  __proto__: null,
10074
10101
  AccumulationOutput: AccumulationOutput,
10075
10102
  AutoAccumulate: AutoAccumulate,
@@ -11079,7 +11106,7 @@ const bitLookup = [
11079
11106
  [0b00000000, 8],
11080
11107
  ];
11081
11108
 
11082
- var index$d = /*#__PURE__*/Object.freeze({
11109
+ var index$f = /*#__PURE__*/Object.freeze({
11083
11110
  __proto__: null,
11084
11111
  BranchNode: BranchNode,
11085
11112
  InMemoryTrie: InMemoryTrie,
@@ -11425,7 +11452,7 @@ function loadState(spec, entries) {
11425
11452
  * hashmap of `key -> value` entries.
11426
11453
  */
11427
11454
 
11428
- var index$c = /*#__PURE__*/Object.freeze({
11455
+ var index$e = /*#__PURE__*/Object.freeze({
11429
11456
  __proto__: null,
11430
11457
  SerializedService: SerializedService,
11431
11458
  SerializedState: SerializedState,
@@ -11711,7 +11738,7 @@ class InMemoryStates {
11711
11738
  }
11712
11739
  }
11713
11740
 
11714
- var index$b = /*#__PURE__*/Object.freeze({
11741
+ var index$d = /*#__PURE__*/Object.freeze({
11715
11742
  __proto__: null,
11716
11743
  InMemoryBlocks: InMemoryBlocks,
11717
11744
  InMemoryStates: InMemoryStates,
@@ -12073,7 +12100,7 @@ const initEc = async () => {
12073
12100
  await init.reedSolomon();
12074
12101
  };
12075
12102
 
12076
- var index$a = /*#__PURE__*/Object.freeze({
12103
+ var index$c = /*#__PURE__*/Object.freeze({
12077
12104
  __proto__: null,
12078
12105
  N_CHUNKS_REDUNDANCY: N_CHUNKS_REDUNDANCY,
12079
12106
  N_CHUNKS_REQUIRED: N_CHUNKS_REQUIRED,
@@ -12097,6 +12124,439 @@ var index$a = /*#__PURE__*/Object.freeze({
12097
12124
  unzip: unzip
12098
12125
  });
12099
12126
 
12127
+ /**
12128
+ * Version ::= SEQUENCE {
12129
+ * major INTEGER (0..255),
12130
+ * minor INTEGER (0..255),
12131
+ * patch INTEGER (0..255)
12132
+ * }
12133
+ */
12134
+ class Version extends WithDebug {
12135
+ major;
12136
+ minor;
12137
+ patch;
12138
+ static Codec = codec$1.Class(Version, {
12139
+ major: codec$1.u8,
12140
+ minor: codec$1.u8,
12141
+ patch: codec$1.u8,
12142
+ });
12143
+ static tryFromString(str) {
12144
+ const parse = (v) => tryAsU8(Number(v));
12145
+ try {
12146
+ const [major, minor, patch] = str.trim().split(".").map(parse);
12147
+ return Version.create({
12148
+ major,
12149
+ minor,
12150
+ patch,
12151
+ });
12152
+ }
12153
+ catch (e) {
12154
+ throw new Error(`Unable to parse ${str} as Version: ${e}`);
12155
+ }
12156
+ }
12157
+ static create({ major, minor, patch }) {
12158
+ return new Version(major, minor, patch);
12159
+ }
12160
+ constructor(major, minor, patch) {
12161
+ super();
12162
+ this.major = major;
12163
+ this.minor = minor;
12164
+ this.patch = patch;
12165
+ }
12166
+ }
12167
+ /**
12168
+ * Fuzzer Protocol V1
12169
+ * Reference: https://github.com/davxy/jam-conformance/blob/main/fuzz-proto/fuzz.asn
12170
+ */
12171
+ // Feature bit constants
12172
+ var Features;
12173
+ (function (Features) {
12174
+ Features[Features["Ancestry"] = 1] = "Ancestry";
12175
+ Features[Features["Fork"] = 2] = "Fork";
12176
+ Features[Features["Reserved"] = 2147483648] = "Reserved";
12177
+ })(Features || (Features = {}));
12178
+ /**
12179
+ * PeerInfo ::= SEQUENCE {
12180
+ * fuzz-version U8,
12181
+ * features Features,
12182
+ * jam-version Version,
12183
+ * app-version Version,
12184
+ * name UTF8String
12185
+ * }
12186
+ */
12187
+ class PeerInfo extends WithDebug {
12188
+ fuzzVersion;
12189
+ features;
12190
+ jamVersion;
12191
+ appVersion;
12192
+ name;
12193
+ static Codec = codec$1.Class(PeerInfo, {
12194
+ fuzzVersion: codec$1.u8,
12195
+ features: codec$1.u32,
12196
+ jamVersion: Version.Codec,
12197
+ appVersion: Version.Codec,
12198
+ name: codec$1.string,
12199
+ });
12200
+ static create({ fuzzVersion, features, appVersion, jamVersion, name }) {
12201
+ return new PeerInfo(fuzzVersion, features, jamVersion, appVersion, name);
12202
+ }
12203
+ constructor(fuzzVersion, features, jamVersion, appVersion, name) {
12204
+ super();
12205
+ this.fuzzVersion = fuzzVersion;
12206
+ this.features = features;
12207
+ this.jamVersion = jamVersion;
12208
+ this.appVersion = appVersion;
12209
+ this.name = name;
12210
+ }
12211
+ }
12212
+ /**
12213
+ * AncestryItem ::= SEQUENCE {
12214
+ * slot TimeSlot,
12215
+ * header-hash HeaderHash
12216
+ * }
12217
+ */
12218
+ class AncestryItem extends WithDebug {
12219
+ slot;
12220
+ headerHash;
12221
+ static Codec = codec$1.Class(AncestryItem, {
12222
+ slot: codec$1.u32.asOpaque(),
12223
+ headerHash: codec$1.bytes(HASH_SIZE).asOpaque(),
12224
+ });
12225
+ static create({ slot, headerHash }) {
12226
+ return new AncestryItem(slot, headerHash);
12227
+ }
12228
+ constructor(slot, headerHash) {
12229
+ super();
12230
+ this.slot = slot;
12231
+ this.headerHash = headerHash;
12232
+ }
12233
+ }
12234
+ /**
12235
+ * KeyValue ::= SEQUENCE {
12236
+ * key TrieKey,
12237
+ * value OCTET STRING
12238
+ * }
12239
+ */
12240
+ class KeyValue extends WithDebug {
12241
+ key;
12242
+ value;
12243
+ static Codec = codec$1.Class(KeyValue, {
12244
+ key: codec$1.bytes(TRUNCATED_HASH_SIZE),
12245
+ value: codec$1.blob,
12246
+ });
12247
+ static create({ key, value }) {
12248
+ return new KeyValue(key, value);
12249
+ }
12250
+ constructor(key, value) {
12251
+ super();
12252
+ this.key = key;
12253
+ this.value = value;
12254
+ }
12255
+ }
12256
+ /** State ::= SEQUENCE OF KeyValue */
12257
+ const stateCodec = codec$1.sequenceVarLen(KeyValue.Codec);
12258
+ /**
12259
+ * Ancestry ::= SEQUENCE (SIZE(0..24)) OF AncestryItem
12260
+ * Empty when `feature-ancestry` is not supported by both parties
12261
+ */
12262
+ const ancestryCodec = codec$1.sequenceVarLen(AncestryItem.Codec, {
12263
+ minLength: 0,
12264
+ maxLength: 24,
12265
+ });
12266
+ /**
12267
+ * Initialize ::= SEQUENCE {
12268
+ * header Header,
12269
+ * keyvals State,
12270
+ * ancestry Ancestry
12271
+ * }
12272
+ */
12273
+ class Initialize extends WithDebug {
12274
+ header;
12275
+ keyvals;
12276
+ ancestry;
12277
+ static Codec = codec$1.Class(Initialize, {
12278
+ header: Header.Codec,
12279
+ keyvals: stateCodec,
12280
+ ancestry: ancestryCodec,
12281
+ });
12282
+ static create({ header, keyvals, ancestry }) {
12283
+ return new Initialize(header, keyvals, ancestry);
12284
+ }
12285
+ constructor(header, keyvals, ancestry) {
12286
+ super();
12287
+ this.header = header;
12288
+ this.keyvals = keyvals;
12289
+ this.ancestry = ancestry;
12290
+ }
12291
+ }
12292
+ /** GetState ::= HeaderHash */
12293
+ const getStateCodec = codec$1.bytes(HASH_SIZE).asOpaque();
12294
+ /** StateRoot ::= StateRootHash */
12295
+ const stateRootCodec = codec$1.bytes(HASH_SIZE).asOpaque();
12296
+ /** Error ::= UTF8String */
12297
+ class ErrorMessage extends WithDebug {
12298
+ message;
12299
+ static Codec = codec$1.Class(ErrorMessage, {
12300
+ message: codec$1.string,
12301
+ });
12302
+ static create({ message }) {
12303
+ return new ErrorMessage(message);
12304
+ }
12305
+ constructor(message) {
12306
+ super();
12307
+ this.message = message;
12308
+ }
12309
+ }
12310
+ /** Message choice type tags */
12311
+ var MessageType;
12312
+ (function (MessageType) {
12313
+ MessageType[MessageType["PeerInfo"] = 0] = "PeerInfo";
12314
+ MessageType[MessageType["Initialize"] = 1] = "Initialize";
12315
+ MessageType[MessageType["StateRoot"] = 2] = "StateRoot";
12316
+ MessageType[MessageType["ImportBlock"] = 3] = "ImportBlock";
12317
+ MessageType[MessageType["GetState"] = 4] = "GetState";
12318
+ MessageType[MessageType["State"] = 5] = "State";
12319
+ MessageType[MessageType["Error"] = 255] = "Error";
12320
+ })(MessageType || (MessageType = {}));
12321
+ /**
12322
+ * Message ::= CHOICE {
12323
+ * peer-info [0] PeerInfo,
12324
+ * initialize [1] Initialize,
12325
+ * state-root [2] StateRoot,
12326
+ * import-block [3] ImportBlock,
12327
+ * get-state [4] GetState,
12328
+ * state [5] State,
12329
+ * error [255] Error
12330
+ * }
12331
+ */
12332
+ const messageCodec = codec$1.custom({
12333
+ name: "Message",
12334
+ sizeHint: { bytes: 1, isExact: false },
12335
+ }, (e, msg) => {
12336
+ e.i8(msg.type);
12337
+ switch (msg.type) {
12338
+ case MessageType.PeerInfo:
12339
+ PeerInfo.Codec.encode(e, msg.value);
12340
+ break;
12341
+ case MessageType.Initialize:
12342
+ Initialize.Codec.encode(e, msg.value);
12343
+ break;
12344
+ case MessageType.StateRoot:
12345
+ stateRootCodec.encode(e, msg.value);
12346
+ break;
12347
+ case MessageType.ImportBlock:
12348
+ Block.Codec.View.encode(e, msg.value);
12349
+ break;
12350
+ case MessageType.GetState:
12351
+ getStateCodec.encode(e, msg.value);
12352
+ break;
12353
+ case MessageType.State:
12354
+ stateCodec.encode(e, msg.value);
12355
+ break;
12356
+ case MessageType.Error:
12357
+ ErrorMessage.Codec.encode(e, msg.value);
12358
+ break;
12359
+ default:
12360
+ throw new Error(`Unknown message type: ${msg}`);
12361
+ }
12362
+ }, (d) => {
12363
+ const type = d.u8();
12364
+ switch (type) {
12365
+ case MessageType.PeerInfo:
12366
+ return { type: MessageType.PeerInfo, value: PeerInfo.Codec.decode(d) };
12367
+ case MessageType.Initialize:
12368
+ return { type: MessageType.Initialize, value: Initialize.Codec.decode(d) };
12369
+ case MessageType.StateRoot:
12370
+ return { type: MessageType.StateRoot, value: stateRootCodec.decode(d) };
12371
+ case MessageType.ImportBlock:
12372
+ return { type: MessageType.ImportBlock, value: Block.Codec.View.decode(d) };
12373
+ case MessageType.GetState:
12374
+ return { type: MessageType.GetState, value: getStateCodec.decode(d) };
12375
+ case MessageType.State:
12376
+ return { type: MessageType.State, value: stateCodec.decode(d) };
12377
+ case MessageType.Error:
12378
+ return { type: MessageType.Error, value: ErrorMessage.Codec.decode(d) };
12379
+ default:
12380
+ throw new Error(`Unknown message type: ${type}`);
12381
+ }
12382
+ }, (s) => {
12383
+ const type = s.decoder.u8();
12384
+ switch (type) {
12385
+ case MessageType.PeerInfo:
12386
+ PeerInfo.Codec.View.skip(s);
12387
+ break;
12388
+ case MessageType.Initialize:
12389
+ Initialize.Codec.View.skip(s);
12390
+ break;
12391
+ case MessageType.StateRoot:
12392
+ stateRootCodec.View.skip(s);
12393
+ break;
12394
+ case MessageType.ImportBlock:
12395
+ Block.Codec.View.skip(s);
12396
+ break;
12397
+ case MessageType.GetState:
12398
+ getStateCodec.View.skip(s);
12399
+ break;
12400
+ case MessageType.State:
12401
+ stateCodec.View.skip(s);
12402
+ break;
12403
+ case MessageType.Error:
12404
+ ErrorMessage.Codec.View.skip(s);
12405
+ break;
12406
+ default:
12407
+ throw new Error(`Unknown message type: ${type}`);
12408
+ }
12409
+ });
12410
+
12411
+ const logger$4 = Logger.new(undefined, "ext-ipc-fuzz-v1");
12412
+ class FuzzTarget {
12413
+ msgHandler;
12414
+ sender;
12415
+ spec;
12416
+ sessionFeatures = 0;
12417
+ constructor(msgHandler, sender, spec) {
12418
+ this.msgHandler = msgHandler;
12419
+ this.sender = sender;
12420
+ this.spec = spec;
12421
+ }
12422
+ async onSocketMessage(msg) {
12423
+ // attempt to decode the messsage
12424
+ try {
12425
+ const message = Decoder.decodeObject(messageCodec, msg, this.spec);
12426
+ logger$4.log `[${message.type}] incoming message`;
12427
+ await this.processAndRespond(message);
12428
+ }
12429
+ catch (e) {
12430
+ logger$4.error `Error while processing fuzz v1 message: ${e}`;
12431
+ logger$4.error `${e}`;
12432
+ if (e instanceof Error) {
12433
+ logger$4.error `${e.stack ?? ""}`;
12434
+ }
12435
+ this.sender.close();
12436
+ }
12437
+ }
12438
+ async processAndRespond(message) {
12439
+ let response = null;
12440
+ switch (message.type) {
12441
+ case MessageType.PeerInfo: {
12442
+ // only support V1
12443
+ if (message.value.fuzzVersion !== 1) {
12444
+ logger$4.warn `Unsupported fuzzer protocol version: ${message.value.fuzzVersion}. Closing`;
12445
+ this.sender.close();
12446
+ return;
12447
+ }
12448
+ // Handle handshake
12449
+ const ourPeerInfo = await this.msgHandler.getPeerInfo(message.value);
12450
+ // Calculate session features (intersection of both peer features)
12451
+ this.sessionFeatures = message.value.features & ourPeerInfo.features;
12452
+ logger$4.info `Handshake completed. Shared features: 0b${this.sessionFeatures.toString(2)}`;
12453
+ logger$4.log `Feature ancestry: ${(this.sessionFeatures & Features.Ancestry) !== 0}`;
12454
+ logger$4.log `Feature fork: ${(this.sessionFeatures & Features.Fork) !== 0}`;
12455
+ response = {
12456
+ type: MessageType.PeerInfo,
12457
+ value: ourPeerInfo,
12458
+ };
12459
+ break;
12460
+ }
12461
+ case MessageType.Initialize: {
12462
+ const stateRoot = await this.msgHandler.initialize(message.value);
12463
+ response = {
12464
+ type: MessageType.StateRoot,
12465
+ value: stateRoot,
12466
+ };
12467
+ break;
12468
+ }
12469
+ case MessageType.ImportBlock: {
12470
+ const result = await this.msgHandler.importBlock(message.value);
12471
+ if (result.isOk) {
12472
+ response = {
12473
+ type: MessageType.StateRoot,
12474
+ value: result.ok,
12475
+ };
12476
+ }
12477
+ else {
12478
+ response = {
12479
+ type: MessageType.Error,
12480
+ value: result.error,
12481
+ };
12482
+ }
12483
+ break;
12484
+ }
12485
+ case MessageType.GetState: {
12486
+ const state = await this.msgHandler.getSerializedState(message.value);
12487
+ response = {
12488
+ type: MessageType.State,
12489
+ value: state,
12490
+ };
12491
+ break;
12492
+ }
12493
+ case MessageType.StateRoot: {
12494
+ logger$4.log `--> Received unexpected 'StateRoot' message from the fuzzer. Closing.`;
12495
+ this.sender.close();
12496
+ return;
12497
+ }
12498
+ case MessageType.State: {
12499
+ logger$4.log `--> Received unexpected 'State' message from the fuzzer. Closing.`;
12500
+ this.sender.close();
12501
+ return;
12502
+ }
12503
+ case MessageType.Error: {
12504
+ logger$4.log `--> Received unexpected 'Error' message from the fuzzer. Closing.`;
12505
+ this.sender.close();
12506
+ return;
12507
+ }
12508
+ default: {
12509
+ logger$4.log `--> Received unexpected message type ${JSON.stringify(message)} from the fuzzer. Closing.`;
12510
+ this.sender.close();
12511
+ try {
12512
+ assertNever(message);
12513
+ }
12514
+ catch {
12515
+ return;
12516
+ }
12517
+ }
12518
+ }
12519
+ if (response !== null) {
12520
+ logger$4.trace `<-- responding with: ${response.type}`;
12521
+ const encoded = Encoder.encodeObject(messageCodec, response, this.spec);
12522
+ this.sender.send(encoded);
12523
+ }
12524
+ else {
12525
+ logger$4.warn `<-- no response generated for: ${message.type}`;
12526
+ }
12527
+ }
12528
+ onClose({ error }) {
12529
+ logger$4.log `Closing the v1 handler. Reason: ${error !== undefined ? error.message : "close"}.`;
12530
+ }
12531
+ /** Check if a specific feature is enabled in the session */
12532
+ hasFeature(feature) {
12533
+ return (this.sessionFeatures & feature) !== 0;
12534
+ }
12535
+ }
12536
+
12537
+ var index$b = /*#__PURE__*/Object.freeze({
12538
+ __proto__: null,
12539
+ AncestryItem: AncestryItem,
12540
+ ErrorMessage: ErrorMessage,
12541
+ get Features () { return Features; },
12542
+ FuzzTarget: FuzzTarget,
12543
+ Initialize: Initialize,
12544
+ KeyValue: KeyValue,
12545
+ get MessageType () { return MessageType; },
12546
+ PeerInfo: PeerInfo,
12547
+ Version: Version,
12548
+ ancestryCodec: ancestryCodec,
12549
+ getStateCodec: getStateCodec,
12550
+ messageCodec: messageCodec,
12551
+ stateCodec: stateCodec,
12552
+ stateRootCodec: stateRootCodec
12553
+ });
12554
+
12555
+ var index$a = /*#__PURE__*/Object.freeze({
12556
+ __proto__: null,
12557
+ v1: index$b
12558
+ });
12559
+
12100
12560
  /** Size of the transfer memo. */
12101
12561
  const TRANSFER_MEMO_BYTES = W_T;
12102
12562
  /**
@@ -12883,10 +13343,16 @@ function signExtend32To64(value) {
12883
13343
 
12884
13344
  /** Attempt to convert a number into `HostCallIndex`. */
12885
13345
  const tryAsHostCallIndex = (v) => asOpaqueType(tryAsU32(v));
13346
+ /**
13347
+ * Host-call exit reason.
13348
+ *
13349
+ * https://graypaper.fluffylabs.dev/#/ab2cdbd/24a30124a501?v=0.7.2
13350
+ */
12886
13351
  var PvmExecution;
12887
13352
  (function (PvmExecution) {
12888
13353
  PvmExecution[PvmExecution["Halt"] = 0] = "Halt";
12889
13354
  PvmExecution[PvmExecution["Panic"] = 1] = "Panic";
13355
+ PvmExecution[PvmExecution["OOG"] = 2] = "OOG";
12890
13356
  })(PvmExecution || (PvmExecution = {}));
12891
13357
  /** A utility function to easily trace a bunch of registers. */
12892
13358
  function traceRegisters(...regs) {
@@ -16521,8 +16987,9 @@ class HostCalls {
16521
16987
  const index = tryAsHostCallIndex(hostCallIndex);
16522
16988
  const hostCall = this.hostCalls.get(index);
16523
16989
  const gasBefore = gas.get();
16524
- const gasCost = typeof hostCall.gasCost === "number" ? hostCall.gasCost : hostCall.gasCost(regs);
16525
- const underflow = gas.sub(gasCost);
16990
+ // NOTE: `basicGasCost(regs)` function is for compatibility reasons: pre GP 0.7.2
16991
+ const basicGasCost = typeof hostCall.basicGasCost === "number" ? hostCall.basicGasCost : hostCall.basicGasCost(regs);
16992
+ const underflow = gas.sub(basicGasCost);
16526
16993
  const pcLog = `[PC: ${pvmInstance.getPC()}]`;
16527
16994
  if (underflow) {
16528
16995
  this.hostCalls.traceHostCall(`${pcLog} OOG`, index, hostCall, regs, gas.get());
@@ -16539,6 +17006,10 @@ class HostCalls {
16539
17006
  status = Status.PANIC;
16540
17007
  return this.getReturnValue(status, pvmInstance);
16541
17008
  }
17009
+ if (result === PvmExecution.OOG) {
17010
+ status = Status.OOG;
17011
+ return this.getReturnValue(status, pvmInstance);
17012
+ }
16542
17013
  if (result === undefined) {
16543
17014
  pvmInstance.runProgram();
16544
17015
  status = pvmInstance.getStatus();
@@ -16939,8 +17410,8 @@ var index$3 = /*#__PURE__*/Object.freeze({
16939
17410
  asOpaqueType: asOpaqueType,
16940
17411
  assertEmpty: assertEmpty,
16941
17412
  assertNever: assertNever,
16942
- block: index$j,
16943
- bytes: index$q,
17413
+ block: index$l,
17414
+ bytes: index$s,
16944
17415
  check: check,
16945
17416
  clampU64ToU32: clampU64ToU32,
16946
17417
  createResults: createResults,
@@ -16948,13 +17419,13 @@ var index$3 = /*#__PURE__*/Object.freeze({
16948
17419
  extractCodeAndMetadata: extractCodeAndMetadata,
16949
17420
  getServiceId: getServiceId,
16950
17421
  getServiceIdOrCurrent: getServiceIdOrCurrent,
16951
- hash: index$n,
17422
+ hash: index$p,
16952
17423
  inspect: inspect,
16953
17424
  instructionArgumentTypeMap: instructionArgumentTypeMap,
16954
17425
  interpreter: index$7,
16955
17426
  isBrowser: isBrowser,
16956
17427
  measure: measure,
16957
- numbers: index$p,
17428
+ numbers: index$r,
16958
17429
  resultToString: resultToString,
16959
17430
  seeThrough: seeThrough,
16960
17431
  slotsToPreimageStatus: slotsToPreimageStatus,
@@ -17528,7 +17999,7 @@ class Preimages {
17528
17999
 
17529
18000
  class Missing {
17530
18001
  index = tryAsHostCallIndex(2 ** 32 - 1);
17531
- gasCost = tryAsSmallGas(10);
18002
+ basicGasCost = tryAsSmallGas(10);
17532
18003
  currentServiceId = CURRENT_SERVICE_ID;
17533
18004
  tracedRegisters = traceRegisters(7);
17534
18005
  execute(_gas, regs, _memory) {
@@ -17668,32 +18139,33 @@ var index = /*#__PURE__*/Object.freeze({
17668
18139
  WorkPackageExecutor: WorkPackageExecutor
17669
18140
  });
17670
18141
 
17671
- exports.block = index$j;
17672
- exports.block_json = index$h;
17673
- exports.bytes = index$q;
17674
- exports.codec = index$o;
17675
- exports.collections = index$l;
17676
- exports.config = index$k;
17677
- exports.config_node = index$f;
17678
- exports.crypto = index$m;
17679
- exports.database = index$b;
17680
- exports.erasure_coding = index$a;
17681
- exports.hash = index$n;
18142
+ exports.block = index$l;
18143
+ exports.block_json = index$j;
18144
+ exports.bytes = index$s;
18145
+ exports.codec = index$q;
18146
+ exports.collections = index$n;
18147
+ exports.config = index$m;
18148
+ exports.config_node = index$h;
18149
+ exports.crypto = index$o;
18150
+ exports.database = index$d;
18151
+ exports.erasure_coding = index$c;
18152
+ exports.fuzz_proto = index$a;
18153
+ exports.hash = index$p;
17682
18154
  exports.jam_host_calls = index$9;
17683
- exports.json_parser = index$i;
17684
- exports.logger = index$g;
18155
+ exports.json_parser = index$k;
18156
+ exports.logger = index$i;
17685
18157
  exports.mmr = index$8;
17686
- exports.numbers = index$p;
17687
- exports.ordering = index$r;
18158
+ exports.numbers = index$r;
18159
+ exports.ordering = index$t;
17688
18160
  exports.pvm = index$3;
17689
18161
  exports.pvm_host_calls = index$6;
17690
18162
  exports.pvm_interpreter = index$7;
17691
18163
  exports.pvm_program = index$4;
17692
18164
  exports.pvm_spi_decoder = index$5;
17693
18165
  exports.shuffling = index$2;
17694
- exports.state = index$e;
18166
+ exports.state = index$g;
17695
18167
  exports.state_json = index$1;
17696
- exports.state_merkleization = index$c;
18168
+ exports.state_merkleization = index$e;
17697
18169
  exports.transition = index;
17698
- exports.trie = index$d;
17699
- exports.utils = index$s;
18170
+ exports.trie = index$f;
18171
+ exports.utils = index$u;