@typeberry/convert 0.1.2-ced735c9 → 0.1.3-707962d

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 (3) hide show
  1. package/index.js +364 -234
  2. package/index.js.map +1 -1
  3. package/package.json +1 -1
package/index.js CHANGED
@@ -4695,8 +4695,8 @@ function print(level, levelAndName, strings, data) {
4695
4695
  return;
4696
4696
  }
4697
4697
  const lvlText = Level[level].padEnd(5);
4698
- const val = strings.map((v, idx) => `${v}${data[idx]}`);
4699
- const msg = `${lvlText} [${levelAndName[1]}] ${val}`;
4698
+ const val = strings.map((v, idx) => `${v}${idx < data.length ? data[idx] : ""}`);
4699
+ const msg = `${lvlText} [${levelAndName[1]}] ${val.join("")}`;
4700
4700
  if (level === Level.WARN) {
4701
4701
  console.warn(msg);
4702
4702
  }
@@ -5511,7 +5511,7 @@ function isResult(x) {
5511
5511
  var minimist = __nccwpck_require__(595);
5512
5512
  var minimist_default = /*#__PURE__*/__nccwpck_require__.n(minimist);
5513
5513
  ;// CONCATENATED MODULE: ./bin/convert/package.json
5514
- const package_namespaceObject = {"rE":"0.1.2"};
5514
+ const package_namespaceObject = {"rE":"0.1.3"};
5515
5515
  ;// CONCATENATED MODULE: ./packages/core/bytes/bitvec.ts
5516
5516
 
5517
5517
  /**
@@ -6867,13 +6867,15 @@ function validateLength(range, length, context) {
6867
6867
 
6868
6868
  /** A caching wrapper for either object or sequence item. */
6869
6869
  class ViewField {
6870
+ name;
6870
6871
  getView;
6871
6872
  getValue;
6872
6873
  getEncoded;
6873
6874
  cachedValue;
6874
6875
  cachedView;
6875
6876
  cachedBlob;
6876
- constructor(getView, getValue, getEncoded) {
6877
+ constructor(name, getView, getValue, getEncoded) {
6878
+ this.name = name;
6877
6879
  this.getView = getView;
6878
6880
  this.getValue = getValue;
6879
6881
  this.getEncoded = getEncoded;
@@ -6899,6 +6901,9 @@ class ViewField {
6899
6901
  }
6900
6902
  return this.cachedBlob;
6901
6903
  }
6904
+ toString() {
6905
+ return `ViewField<${this.name}>`;
6906
+ }
6902
6907
  }
6903
6908
  /**
6904
6909
  * A base class for all the lazy views.
@@ -6973,7 +6978,7 @@ class ObjectView {
6973
6978
  const fieldDecoder = skipper.decoder.clone();
6974
6979
  const field = this.descriptorsKeys[i];
6975
6980
  const type = this.descriptors[field];
6976
- lastItem = new ViewField(() => type.View.decode(fieldDecoder.clone()), () => type.decode(fieldDecoder.clone()), () => type.skipEncoded(fieldDecoder.clone()));
6981
+ lastItem = new ViewField(`${this.toString()}.${String(field)}`, () => type.View.decode(fieldDecoder.clone()), () => type.decode(fieldDecoder.clone()), () => type.skipEncoded(fieldDecoder.clone()));
6977
6982
  // skip the field
6978
6983
  type.skip(skipper);
6979
6984
  // cache data
@@ -6985,6 +6990,9 @@ class ObjectView {
6985
6990
  }
6986
6991
  return lastItem;
6987
6992
  }
6993
+ toString() {
6994
+ return `View<${this.materializedConstructor.name}>(cache: ${this.cache.size})`;
6995
+ }
6988
6996
  }
6989
6997
  /**
6990
6998
  * A lazy-evaluated decoder of a sequence.
@@ -7073,7 +7081,7 @@ class SequenceView {
7073
7081
  // create new cached prop
7074
7082
  const fieldDecoder = skipper.decoder.clone();
7075
7083
  const type = this.descriptor;
7076
- lastItem = new ViewField(() => type.View.decode(fieldDecoder.clone()), () => type.decode(fieldDecoder.clone()), () => type.skipEncoded(fieldDecoder.clone()));
7084
+ lastItem = new ViewField(`${this.toString()}[${index}]`, () => type.View.decode(fieldDecoder.clone()), () => type.decode(fieldDecoder.clone()), () => type.skipEncoded(fieldDecoder.clone()));
7077
7085
  // skip the field
7078
7086
  type.skip(skipper);
7079
7087
  // cache data
@@ -7085,6 +7093,9 @@ class SequenceView {
7085
7093
  }
7086
7094
  return lastItem;
7087
7095
  }
7096
+ toString() {
7097
+ return `SequenceView<${this.descriptor.name}>(cache: ${this.cache.size})`;
7098
+ }
7088
7099
  }
7089
7100
 
7090
7101
  ;// CONCATENATED MODULE: ./packages/core/codec/descriptors.ts
@@ -11498,15 +11509,12 @@ function loadConfig(configPath) {
11498
11509
 
11499
11510
 
11500
11511
 
11501
- ;// CONCATENATED MODULE: ./packages/extensions/ipc/fuzz/v0/types.ts
11512
+ ;// CONCATENATED MODULE: ./packages/jam/fuzz-proto/v1/types.ts
11502
11513
 
11503
11514
 
11504
11515
 
11505
11516
 
11506
11517
 
11507
- /**
11508
- * Reference: https://github.com/davxy/jam-conformance/blob/7c6a371a966c6446564f91676e7a2afdec5fa3da/fuzz-proto/fuzz.asn
11509
- */
11510
11518
  /**
11511
11519
  * Version ::= SEQUENCE {
11512
11520
  * major INTEGER (0..255),
@@ -11547,190 +11555,17 @@ class Version extends WithDebug {
11547
11555
  this.patch = patch;
11548
11556
  }
11549
11557
  }
11550
- /**
11551
- * PeerInfo ::= SEQUENCE {
11552
- * name UTF8String,
11553
- * app-version Version,
11554
- * jam-version Version
11555
- * }
11556
- */
11557
- class PeerInfo extends WithDebug {
11558
- name;
11559
- appVersion;
11560
- jamVersion;
11561
- static Codec = descriptors_codec.Class(PeerInfo, {
11562
- name: descriptors_codec.string,
11563
- appVersion: Version.Codec,
11564
- jamVersion: Version.Codec,
11565
- });
11566
- static create({ name, appVersion, jamVersion }) {
11567
- return new PeerInfo(name, appVersion, jamVersion);
11568
- }
11569
- constructor(name, appVersion, jamVersion) {
11570
- super();
11571
- this.name = name;
11572
- this.appVersion = appVersion;
11573
- this.jamVersion = jamVersion;
11574
- }
11575
- }
11576
- /**
11577
- * KeyValue ::= SEQUENCE {
11578
- * key TrieKey,
11579
- * value OCTET STRING
11580
- * }
11581
- */
11582
- class KeyValue extends WithDebug {
11583
- key;
11584
- value;
11585
- static Codec = descriptors_codec.Class(KeyValue, {
11586
- key: descriptors_codec.bytes(TRUNCATED_HASH_SIZE),
11587
- value: descriptors_codec.blob,
11588
- });
11589
- static create({ key, value }) {
11590
- return new KeyValue(key, value);
11591
- }
11592
- constructor(key, value) {
11593
- super();
11594
- this.key = key;
11595
- this.value = value;
11596
- }
11597
- }
11598
- /** State ::= SEQUENCE OF KeyValue */
11599
- const stateCodec = descriptors_codec.sequenceVarLen(KeyValue.Codec);
11600
- /**
11601
- * SetState ::= SEQUENCE {
11602
- * header Header,
11603
- * state State
11604
- * }
11605
- */
11606
- class SetState extends WithDebug {
11607
- header;
11608
- state;
11609
- static Codec = descriptors_codec.Class(SetState, {
11610
- header: header_Header.Codec,
11611
- state: descriptors_codec.sequenceVarLen(KeyValue.Codec),
11612
- });
11613
- static create({ header, state }) {
11614
- return new SetState(header, state);
11615
- }
11616
- constructor(header, state) {
11617
- super();
11618
- this.header = header;
11619
- this.state = state;
11620
- }
11621
- }
11622
- /** GetState ::= HeaderHash */
11623
- const getStateCodec = descriptors_codec.bytes(hash_HASH_SIZE).asOpaque();
11624
- /** StateRoot ::= StateRootHash */
11625
- const stateRootCodec = descriptors_codec.bytes(hash_HASH_SIZE).asOpaque();
11626
- /** Message choice type tags */
11627
- var MessageType;
11628
- (function (MessageType) {
11629
- MessageType[MessageType["PeerInfo"] = 0] = "PeerInfo";
11630
- MessageType[MessageType["ImportBlock"] = 1] = "ImportBlock";
11631
- MessageType[MessageType["SetState"] = 2] = "SetState";
11632
- MessageType[MessageType["GetState"] = 3] = "GetState";
11633
- MessageType[MessageType["State"] = 4] = "State";
11634
- MessageType[MessageType["StateRoot"] = 5] = "StateRoot";
11635
- })(MessageType || (MessageType = {}));
11636
- /**
11637
- * Message ::= CHOICE {
11638
- * peer-info [0] PeerInfo,
11639
- * import-block [1] ImportBlock,
11640
- * set-state [2] SetState,
11641
- * get-state [3] GetState,
11642
- * state [4] State,
11643
- * state-root [5] StateRoot
11644
- * }
11645
- */
11646
- const messageCodec = descriptors_codec.custom({
11647
- name: "Message",
11648
- sizeHint: { bytes: 1, isExact: false },
11649
- }, (e, msg) => {
11650
- e.i8(msg.type);
11651
- switch (msg.type) {
11652
- case MessageType.PeerInfo:
11653
- PeerInfo.Codec.encode(e, msg.value);
11654
- break;
11655
- case MessageType.ImportBlock:
11656
- block_Block.Codec.View.encode(e, msg.value);
11657
- break;
11658
- case MessageType.SetState:
11659
- SetState.Codec.encode(e, msg.value);
11660
- break;
11661
- case MessageType.GetState:
11662
- getStateCodec.encode(e, msg.value);
11663
- break;
11664
- case MessageType.State:
11665
- stateCodec.encode(e, msg.value);
11666
- break;
11667
- case MessageType.StateRoot:
11668
- stateRootCodec.encode(e, msg.value);
11669
- break;
11670
- default:
11671
- throw new Error(`Unknown message type: ${msg}`);
11672
- }
11673
- }, (d) => {
11674
- const type = d.u8();
11675
- switch (type) {
11676
- case MessageType.PeerInfo:
11677
- return { type: MessageType.PeerInfo, value: PeerInfo.Codec.decode(d) };
11678
- case MessageType.ImportBlock:
11679
- return { type: MessageType.ImportBlock, value: block_Block.Codec.View.decode(d) };
11680
- case MessageType.SetState:
11681
- return { type: MessageType.SetState, value: SetState.Codec.decode(d) };
11682
- case MessageType.GetState:
11683
- return { type: MessageType.GetState, value: getStateCodec.decode(d) };
11684
- case MessageType.State:
11685
- return { type: MessageType.State, value: stateCodec.decode(d) };
11686
- case MessageType.StateRoot:
11687
- return { type: MessageType.StateRoot, value: stateRootCodec.decode(d) };
11688
- default:
11689
- throw new Error(`Unknown message type: ${type}`);
11690
- }
11691
- }, (s) => {
11692
- const type = s.decoder.u8();
11693
- switch (type) {
11694
- case MessageType.PeerInfo:
11695
- PeerInfo.Codec.View.skip(s);
11696
- break;
11697
- case MessageType.ImportBlock:
11698
- block_Block.Codec.View.skip(s);
11699
- break;
11700
- case MessageType.SetState:
11701
- SetState.Codec.View.skip(s);
11702
- break;
11703
- case MessageType.GetState:
11704
- getStateCodec.View.skip(s);
11705
- break;
11706
- case MessageType.State:
11707
- stateCodec.View.skip(s);
11708
- break;
11709
- case MessageType.StateRoot:
11710
- stateRootCodec.View.skip(s);
11711
- break;
11712
- default:
11713
- throw new Error(`Unknown message type: ${type}`);
11714
- }
11715
- });
11716
-
11717
- ;// CONCATENATED MODULE: ./packages/extensions/ipc/fuzz/v1/types.ts
11718
-
11719
-
11720
-
11721
-
11722
-
11723
11558
  /**
11724
11559
  * Fuzzer Protocol V1
11725
11560
  * Reference: https://github.com/davxy/jam-conformance/blob/main/fuzz-proto/fuzz.asn
11726
11561
  */
11727
11562
  // Feature bit constants
11728
- var Features;
11563
+ var types_Features;
11729
11564
  (function (Features) {
11730
11565
  Features[Features["Ancestry"] = 1] = "Ancestry";
11731
11566
  Features[Features["Fork"] = 2] = "Fork";
11732
11567
  Features[Features["Reserved"] = 2147483648] = "Reserved";
11733
- })(Features || (Features = {}));
11568
+ })(types_Features || (types_Features = {}));
11734
11569
  /**
11735
11570
  * PeerInfo ::= SEQUENCE {
11736
11571
  * fuzz-version U8,
@@ -11740,13 +11575,13 @@ var Features;
11740
11575
  * name UTF8String
11741
11576
  * }
11742
11577
  */
11743
- class types_PeerInfo extends WithDebug {
11578
+ class PeerInfo extends WithDebug {
11744
11579
  fuzzVersion;
11745
11580
  features;
11746
11581
  jamVersion;
11747
11582
  appVersion;
11748
11583
  name;
11749
- static Codec = descriptors_codec.Class(types_PeerInfo, {
11584
+ static Codec = descriptors_codec.Class(PeerInfo, {
11750
11585
  fuzzVersion: descriptors_codec.u8,
11751
11586
  features: descriptors_codec.u32,
11752
11587
  jamVersion: Version.Codec,
@@ -11754,7 +11589,7 @@ class types_PeerInfo extends WithDebug {
11754
11589
  name: descriptors_codec.string,
11755
11590
  });
11756
11591
  static create({ fuzzVersion, features, appVersion, jamVersion, name }) {
11757
- return new types_PeerInfo(fuzzVersion, features, jamVersion, appVersion, name);
11592
+ return new PeerInfo(fuzzVersion, features, jamVersion, appVersion, name);
11758
11593
  }
11759
11594
  constructor(fuzzVersion, features, jamVersion, appVersion, name) {
11760
11595
  super();
@@ -11787,6 +11622,30 @@ class AncestryItem extends WithDebug {
11787
11622
  this.headerHash = headerHash;
11788
11623
  }
11789
11624
  }
11625
+ /**
11626
+ * KeyValue ::= SEQUENCE {
11627
+ * key TrieKey,
11628
+ * value OCTET STRING
11629
+ * }
11630
+ */
11631
+ class KeyValue extends WithDebug {
11632
+ key;
11633
+ value;
11634
+ static Codec = descriptors_codec.Class(KeyValue, {
11635
+ key: descriptors_codec.bytes(TRUNCATED_HASH_SIZE),
11636
+ value: descriptors_codec.blob,
11637
+ });
11638
+ static create({ key, value }) {
11639
+ return new KeyValue(key, value);
11640
+ }
11641
+ constructor(key, value) {
11642
+ super();
11643
+ this.key = key;
11644
+ this.value = value;
11645
+ }
11646
+ }
11647
+ /** State ::= SEQUENCE OF KeyValue */
11648
+ const stateCodec = descriptors_codec.sequenceVarLen(KeyValue.Codec);
11790
11649
  /**
11791
11650
  * Ancestry ::= SEQUENCE (SIZE(0..24)) OF AncestryItem
11792
11651
  * Empty when `feature-ancestry` is not supported by both parties
@@ -11822,9 +11681,9 @@ class Initialize extends WithDebug {
11822
11681
  }
11823
11682
  }
11824
11683
  /** GetState ::= HeaderHash */
11825
- const types_getStateCodec = descriptors_codec.bytes(hash_HASH_SIZE).asOpaque();
11684
+ const getStateCodec = descriptors_codec.bytes(hash_HASH_SIZE).asOpaque();
11826
11685
  /** StateRoot ::= StateRootHash */
11827
- const types_stateRootCodec = descriptors_codec.bytes(hash_HASH_SIZE).asOpaque();
11686
+ const stateRootCodec = descriptors_codec.bytes(hash_HASH_SIZE).asOpaque();
11828
11687
  /** Error ::= UTF8String */
11829
11688
  class ErrorMessage extends WithDebug {
11830
11689
  message;
@@ -11868,19 +11727,19 @@ const types_messageCodec = descriptors_codec.custom({
11868
11727
  e.i8(msg.type);
11869
11728
  switch (msg.type) {
11870
11729
  case types_MessageType.PeerInfo:
11871
- types_PeerInfo.Codec.encode(e, msg.value);
11730
+ PeerInfo.Codec.encode(e, msg.value);
11872
11731
  break;
11873
11732
  case types_MessageType.Initialize:
11874
11733
  Initialize.Codec.encode(e, msg.value);
11875
11734
  break;
11876
11735
  case types_MessageType.StateRoot:
11877
- types_stateRootCodec.encode(e, msg.value);
11736
+ stateRootCodec.encode(e, msg.value);
11878
11737
  break;
11879
11738
  case types_MessageType.ImportBlock:
11880
11739
  block_Block.Codec.View.encode(e, msg.value);
11881
11740
  break;
11882
11741
  case types_MessageType.GetState:
11883
- types_getStateCodec.encode(e, msg.value);
11742
+ getStateCodec.encode(e, msg.value);
11884
11743
  break;
11885
11744
  case types_MessageType.State:
11886
11745
  stateCodec.encode(e, msg.value);
@@ -11895,15 +11754,15 @@ const types_messageCodec = descriptors_codec.custom({
11895
11754
  const type = d.u8();
11896
11755
  switch (type) {
11897
11756
  case types_MessageType.PeerInfo:
11898
- return { type: types_MessageType.PeerInfo, value: types_PeerInfo.Codec.decode(d) };
11757
+ return { type: types_MessageType.PeerInfo, value: PeerInfo.Codec.decode(d) };
11899
11758
  case types_MessageType.Initialize:
11900
11759
  return { type: types_MessageType.Initialize, value: Initialize.Codec.decode(d) };
11901
11760
  case types_MessageType.StateRoot:
11902
- return { type: types_MessageType.StateRoot, value: types_stateRootCodec.decode(d) };
11761
+ return { type: types_MessageType.StateRoot, value: stateRootCodec.decode(d) };
11903
11762
  case types_MessageType.ImportBlock:
11904
11763
  return { type: types_MessageType.ImportBlock, value: block_Block.Codec.View.decode(d) };
11905
11764
  case types_MessageType.GetState:
11906
- return { type: types_MessageType.GetState, value: types_getStateCodec.decode(d) };
11765
+ return { type: types_MessageType.GetState, value: getStateCodec.decode(d) };
11907
11766
  case types_MessageType.State:
11908
11767
  return { type: types_MessageType.State, value: stateCodec.decode(d) };
11909
11768
  case types_MessageType.Error:
@@ -11915,19 +11774,19 @@ const types_messageCodec = descriptors_codec.custom({
11915
11774
  const type = s.decoder.u8();
11916
11775
  switch (type) {
11917
11776
  case types_MessageType.PeerInfo:
11918
- types_PeerInfo.Codec.View.skip(s);
11777
+ PeerInfo.Codec.View.skip(s);
11919
11778
  break;
11920
11779
  case types_MessageType.Initialize:
11921
11780
  Initialize.Codec.View.skip(s);
11922
11781
  break;
11923
11782
  case types_MessageType.StateRoot:
11924
- types_stateRootCodec.View.skip(s);
11783
+ stateRootCodec.View.skip(s);
11925
11784
  break;
11926
11785
  case types_MessageType.ImportBlock:
11927
11786
  block_Block.Codec.View.skip(s);
11928
11787
  break;
11929
11788
  case types_MessageType.GetState:
11930
- types_getStateCodec.View.skip(s);
11789
+ getStateCodec.View.skip(s);
11931
11790
  break;
11932
11791
  case types_MessageType.State:
11933
11792
  stateCodec.View.skip(s);
@@ -11940,6 +11799,145 @@ const types_messageCodec = descriptors_codec.custom({
11940
11799
  }
11941
11800
  });
11942
11801
 
11802
+ ;// CONCATENATED MODULE: ./packages/jam/fuzz-proto/v1/handler.ts
11803
+
11804
+
11805
+
11806
+
11807
+ const handler_logger = Logger.new(import.meta.filename, "ext-ipc-fuzz-v1");
11808
+ class FuzzTarget {
11809
+ msgHandler;
11810
+ sender;
11811
+ spec;
11812
+ sessionFeatures = 0;
11813
+ constructor(msgHandler, sender, spec) {
11814
+ this.msgHandler = msgHandler;
11815
+ this.sender = sender;
11816
+ this.spec = spec;
11817
+ }
11818
+ async onSocketMessage(msg) {
11819
+ // attempt to decode the messsage
11820
+ try {
11821
+ const message = Decoder.decodeObject(messageCodec, msg, this.spec);
11822
+ handler_logger.log `[${message.type}] incoming message`;
11823
+ await this.processAndRespond(message);
11824
+ }
11825
+ catch (e) {
11826
+ handler_logger.error `Error while processing fuzz v1 message: ${e}`;
11827
+ handler_logger.error `${e}`;
11828
+ if (e instanceof Error) {
11829
+ handler_logger.error `${e.stack ?? ""}`;
11830
+ }
11831
+ this.sender.close();
11832
+ }
11833
+ }
11834
+ async processAndRespond(message) {
11835
+ let response = null;
11836
+ switch (message.type) {
11837
+ case MessageType.PeerInfo: {
11838
+ // only support V1
11839
+ if (message.value.fuzzVersion !== 1) {
11840
+ handler_logger.warn `Unsupported fuzzer protocol version: ${message.value.fuzzVersion}. Closing`;
11841
+ this.sender.close();
11842
+ return;
11843
+ }
11844
+ // Handle handshake
11845
+ const ourPeerInfo = await this.msgHandler.getPeerInfo(message.value);
11846
+ // Calculate session features (intersection of both peer features)
11847
+ this.sessionFeatures = message.value.features & ourPeerInfo.features;
11848
+ handler_logger.info `Handshake completed. Shared features: 0b${this.sessionFeatures.toString(2)}`;
11849
+ handler_logger.log `Feature ancestry: ${(this.sessionFeatures & Features.Ancestry) !== 0}`;
11850
+ handler_logger.log `Feature fork: ${(this.sessionFeatures & Features.Fork) !== 0}`;
11851
+ response = {
11852
+ type: MessageType.PeerInfo,
11853
+ value: ourPeerInfo,
11854
+ };
11855
+ break;
11856
+ }
11857
+ case MessageType.Initialize: {
11858
+ const stateRoot = await this.msgHandler.initialize(message.value);
11859
+ response = {
11860
+ type: MessageType.StateRoot,
11861
+ value: stateRoot,
11862
+ };
11863
+ break;
11864
+ }
11865
+ case MessageType.ImportBlock: {
11866
+ const result = await this.msgHandler.importBlock(message.value);
11867
+ if (result.isOk) {
11868
+ response = {
11869
+ type: MessageType.StateRoot,
11870
+ value: result.ok,
11871
+ };
11872
+ }
11873
+ else {
11874
+ response = {
11875
+ type: MessageType.Error,
11876
+ value: result.error,
11877
+ };
11878
+ }
11879
+ break;
11880
+ }
11881
+ case MessageType.GetState: {
11882
+ const state = await this.msgHandler.getSerializedState(message.value);
11883
+ response = {
11884
+ type: MessageType.State,
11885
+ value: state,
11886
+ };
11887
+ break;
11888
+ }
11889
+ case MessageType.StateRoot: {
11890
+ handler_logger.log `--> Received unexpected 'StateRoot' message from the fuzzer. Closing.`;
11891
+ this.sender.close();
11892
+ return;
11893
+ }
11894
+ case MessageType.State: {
11895
+ handler_logger.log `--> Received unexpected 'State' message from the fuzzer. Closing.`;
11896
+ this.sender.close();
11897
+ return;
11898
+ }
11899
+ case MessageType.Error: {
11900
+ handler_logger.log `--> Received unexpected 'Error' message from the fuzzer. Closing.`;
11901
+ this.sender.close();
11902
+ return;
11903
+ }
11904
+ default: {
11905
+ handler_logger.log `--> Received unexpected message type ${JSON.stringify(message)} from the fuzzer. Closing.`;
11906
+ this.sender.close();
11907
+ try {
11908
+ assertNever(message);
11909
+ }
11910
+ catch {
11911
+ return;
11912
+ }
11913
+ }
11914
+ }
11915
+ if (response !== null) {
11916
+ handler_logger.trace `<-- responding with: ${response.type}`;
11917
+ const encoded = Encoder.encodeObject(messageCodec, response, this.spec);
11918
+ this.sender.send(encoded);
11919
+ }
11920
+ else {
11921
+ handler_logger.warn `<-- no response generated for: ${message.type}`;
11922
+ }
11923
+ }
11924
+ onClose({ error }) {
11925
+ handler_logger.log `Closing the v1 handler. Reason: ${error !== undefined ? error.message : "close"}.`;
11926
+ }
11927
+ /** Check if a specific feature is enabled in the session */
11928
+ hasFeature(feature) {
11929
+ return (this.sessionFeatures & feature) !== 0;
11930
+ }
11931
+ }
11932
+
11933
+ ;// CONCATENATED MODULE: ./packages/jam/fuzz-proto/v1/index.ts
11934
+
11935
+
11936
+
11937
+ ;// CONCATENATED MODULE: ./packages/jam/fuzz-proto/index.ts
11938
+
11939
+
11940
+
11943
11941
  ;// CONCATENATED MODULE: ./packages/core/pvm-spi-decoder/memory-conts.ts
11944
11942
  // GP reference: https://graypaper.fluffylabs.dev/#/7e6ff6a/2d32002d3200?v=0.6.7
11945
11943
  const memory_conts_PAGE_SIZE = 2 ** 12; // Z_P from GP
@@ -17473,6 +17471,17 @@ class page_range_PageRange {
17473
17471
  }
17474
17472
  return new page_range_PageRange(start, length);
17475
17473
  }
17474
+ /** Returns true if the page range is wrapped (`start` >= `end`) and is not empty */
17475
+ isWrapped() {
17476
+ return this.start >= this.end && !this.isEmpty();
17477
+ }
17478
+ /** Checks if given page number is within the range */
17479
+ isInRange(page) {
17480
+ if (this.isWrapped()) {
17481
+ return page >= this.start || page < this.end;
17482
+ }
17483
+ return page >= this.start && page < this.end;
17484
+ }
17476
17485
  /** Checks if a range is empty (`length === 0`) */
17477
17486
  isEmpty() {
17478
17487
  return this.length === 0;
@@ -17852,10 +17861,11 @@ class memory_builder_MemoryBuilder {
17852
17861
  startHeapIndex (${startHeapIndex}) has to be less than or equal to endHeapIndex (${endHeapIndex})
17853
17862
  `;
17854
17863
  this.ensureNotFinalized();
17855
- const range = MemoryRange.fromStartAndLength(startHeapIndex, endHeapIndex - startHeapIndex);
17856
- const pages = PageRange.fromMemoryRange(range);
17857
- for (const pageNumber of pages) {
17858
- if (this.initialMemory.has(pageNumber)) {
17864
+ const heapRange = MemoryRange.fromStartAndLength(startHeapIndex, endHeapIndex - startHeapIndex);
17865
+ const heapPagesRange = PageRange.fromMemoryRange(heapRange);
17866
+ const initializedPageNumbers = Array.from(this.initialMemory.keys());
17867
+ for (const pageNumber of initializedPageNumbers) {
17868
+ if (heapPagesRange.isInRange(pageNumber)) {
17859
17869
  throw new IncorrectSbrkIndex();
17860
17870
  }
17861
17871
  }
@@ -26809,6 +26819,12 @@ async function runPvmTest(testContent) {
26809
26819
 
26810
26820
 
26811
26821
 
26822
+ function looseType(output) {
26823
+ return {
26824
+ value: output.value,
26825
+ encode: output.encode,
26826
+ };
26827
+ }
26812
26828
  const SUPPORTED_TYPES = [
26813
26829
  {
26814
26830
  name: "block",
@@ -26826,8 +26842,12 @@ const SUPPORTED_TYPES = [
26826
26842
  run(spec, data, option) {
26827
26843
  const header = data;
26828
26844
  if (option === "as-hash") {
26829
- return hashBytes(encoder_Encoder.encodeObject(header_Header.Codec, header, spec));
26845
+ return looseType({
26846
+ value: hashBytes(encoder_Encoder.encodeObject(header_Header.Codec, header, spec)),
26847
+ encode: descriptors_codec.bytes(hash_HASH_SIZE),
26848
+ });
26830
26849
  }
26850
+ throw new Error(`Invalid processing option: ${option}`);
26831
26851
  },
26832
26852
  },
26833
26853
  },
@@ -26871,11 +26891,17 @@ const SUPPORTED_TYPES = [
26871
26891
  run(spec, data, option) {
26872
26892
  const state = data;
26873
26893
  if (option === "as-entries") {
26874
- return Object.fromEntries(state_entries_StateEntries.serializeInMemory(spec, state));
26894
+ return looseType({
26895
+ value: Object.fromEntries(state_entries_StateEntries.serializeInMemory(spec, state)),
26896
+ });
26875
26897
  }
26876
26898
  if (option === "as-root-hash") {
26877
- return state_entries_StateEntries.serializeInMemory(spec, state).getRootHash();
26899
+ return looseType({
26900
+ value: state_entries_StateEntries.serializeInMemory(spec, state).getRootHash(),
26901
+ encode: descriptors_codec.bytes(hash_HASH_SIZE),
26902
+ });
26878
26903
  }
26904
+ throw new Error(`Invalid processing option: ${option}`);
26879
26905
  },
26880
26906
  },
26881
26907
  },
@@ -26885,19 +26911,39 @@ const SUPPORTED_TYPES = [
26885
26911
  decode: StateTransitionGenesis.Codec,
26886
26912
  json: () => StateTransitionGenesis.fromJson,
26887
26913
  process: {
26888
- options: ["as-state", "as-jip4"],
26914
+ options: ["as-state", "as-jip4", "as-fuzz-message"],
26889
26915
  run(spec, data, option) {
26890
26916
  const test = data;
26891
26917
  if (option === "as-state") {
26892
- return stateFromKeyvals(spec, test.state);
26918
+ return looseType({
26919
+ value: stateFromKeyvals(spec, test.state),
26920
+ });
26893
26921
  }
26894
26922
  if (option === "as-jip4") {
26895
26923
  const genesisState = new Map(test.state.keyvals.map((x) => [x.key, x.value]));
26896
- return JipChainSpec.create({
26897
- genesisHeader: encoder_Encoder.encodeObject(header_Header.Codec, test.header, spec),
26898
- genesisState,
26924
+ return looseType({
26925
+ value: JipChainSpec.create({
26926
+ genesisHeader: encoder_Encoder.encodeObject(header_Header.Codec, test.header, spec),
26927
+ genesisState,
26928
+ }),
26899
26929
  });
26900
26930
  }
26931
+ if (option === "as-fuzz-message") {
26932
+ const init = Initialize.create({
26933
+ header: test.header,
26934
+ keyvals: test.state.keyvals,
26935
+ ancestry: [],
26936
+ });
26937
+ const msg = {
26938
+ type: types_MessageType.Initialize,
26939
+ value: init,
26940
+ };
26941
+ return looseType({
26942
+ value: msg,
26943
+ encode: types_messageCodec,
26944
+ });
26945
+ }
26946
+ throw new Error(`Invalid processing option: ${option}`);
26901
26947
  },
26902
26948
  },
26903
26949
  },
@@ -26907,15 +26953,32 @@ const SUPPORTED_TYPES = [
26907
26953
  decode: StateTransition.Codec,
26908
26954
  json: () => StateTransition.fromJson,
26909
26955
  process: {
26910
- options: ["as-pre-state", "as-post-state"],
26956
+ options: ["as-pre-state", "as-post-state", "as-fuzz-message"],
26911
26957
  run(spec, data, option) {
26912
26958
  const test = data;
26913
26959
  if (option === "as-pre-state") {
26914
- return stateFromKeyvals(spec, test.pre_state);
26960
+ return looseType({
26961
+ value: stateFromKeyvals(spec, test.pre_state),
26962
+ });
26915
26963
  }
26916
26964
  if (option === "as-post-state") {
26917
- return stateFromKeyvals(spec, test.post_state);
26965
+ return looseType({
26966
+ value: stateFromKeyvals(spec, test.post_state),
26967
+ });
26968
+ }
26969
+ if (option === "as-fuzz-message") {
26970
+ const encoded = encoder_Encoder.encodeObject(block_Block.Codec, test.block, spec);
26971
+ const blockView = decoder_Decoder.decodeObject(block_Block.Codec.View, encoded, spec);
26972
+ const msg = {
26973
+ type: types_MessageType.ImportBlock,
26974
+ value: blockView,
26975
+ };
26976
+ return looseType({
26977
+ value: msg,
26978
+ encode: types_messageCodec,
26979
+ });
26918
26980
  }
26981
+ throw new Error(`Invalid processing option: ${option}`);
26919
26982
  },
26920
26983
  },
26921
26984
  },
@@ -26938,7 +27001,7 @@ const HELP = `
26938
27001
  @typeberry/convert ${package_namespaceObject.rE} by Fluffy Labs.
26939
27002
 
26940
27003
  Usage:
26941
- @typeberry/convert [options] <bin-hex-or-json-input-file> <type> [process] [output-format]
27004
+ @typeberry/convert [options] <bin-hex-or-json-input-file> <type> [process] [output-format] [output-file]
26942
27005
 
26943
27006
  Attempts to read provided input file as 'type' and output in requested 'output-format'.
26944
27007
  For some 'type's it's additionally possible to process the data before outputting it.
@@ -26947,6 +27010,7 @@ The input type is detected from file extension ('.bin', '.hex' or '.json').
26947
27010
  Example usage:
26948
27011
  @typeberry/convert ./genesis-header.json header to-hex
26949
27012
  @typeberry/convert ./state-snapshot.json state-dump as-entries to-json
27013
+ @typeberry/convert ./state-snapshot.json stf-vector as-fuzz-message to-bin msg0.bin
26950
27014
 
26951
27015
  Options:
26952
27016
  --flavor - chain spec flavor, either 'full' or 'tiny'.
@@ -26956,6 +27020,7 @@ Output formats:
26956
27020
  to-print - Print the object to the console
26957
27021
  to-json - JSON format (when supported)
26958
27022
  to-hex - JAM-codec hex-encoded string (when supported)
27023
+ to-bin - JAM-codec binary data (when supported)
26959
27024
  to-repl - Start a JavaScript REPL with the data loaded into a variable
26960
27025
 
26961
27026
  Input types:
@@ -26978,6 +27043,7 @@ var OutputFormat;
26978
27043
  OutputFormat["Print"] = "to-print";
26979
27044
  OutputFormat["Json"] = "to-json";
26980
27045
  OutputFormat["Hex"] = "to-hex";
27046
+ OutputFormat["Bin"] = "to-bin";
26981
27047
  OutputFormat["Repl"] = "to-repl";
26982
27048
  })(OutputFormat || (OutputFormat = {}));
26983
27049
  function parseArgs(cliInput, withRelPath) {
@@ -26999,14 +27065,16 @@ function parseArgs(cliInput, withRelPath) {
26999
27065
  const type = parseType(args._.shift());
27000
27066
  const maybeProcess = args._.shift();
27001
27067
  const maybeOutputFormat = args._.shift();
27068
+ const maybeDestination = args._.shift();
27002
27069
  assertNoMoreArgs(args);
27003
- const { process, format } = getProcessAndOutput(type, maybeProcess, maybeOutputFormat);
27070
+ const { process, format, destination } = getProcessFormatAndDestination(type, maybeProcess, maybeOutputFormat, maybeDestination);
27004
27071
  return {
27005
27072
  flavor: chainSpec.flavor,
27006
27073
  type,
27007
27074
  process,
27008
27075
  inputPath: withRelPath(input),
27009
27076
  outputFormat: format,
27077
+ destination,
27010
27078
  };
27011
27079
  }
27012
27080
  function parseType(type) {
@@ -27032,10 +27100,21 @@ function parseOutputFormat(output) {
27032
27100
  return OutputFormat.Json;
27033
27101
  case OutputFormat.Repl:
27034
27102
  return OutputFormat.Repl;
27103
+ case OutputFormat.Bin:
27104
+ return OutputFormat.Bin;
27035
27105
  default:
27036
27106
  throw new Error(`Invalid output format: '${output}'.`);
27037
27107
  }
27038
27108
  }
27109
+ function parseProcess(processOptions, maybeProcess) {
27110
+ if (maybeProcess === undefined) {
27111
+ return null;
27112
+ }
27113
+ if (!processOptions.includes(maybeProcess)) {
27114
+ throw new Error(`Incorrect processing option: ${maybeProcess}. Expected one of: ${processOptions}.`);
27115
+ }
27116
+ return maybeProcess;
27117
+ }
27039
27118
  // TODO [ToDr] Consider sharing that?
27040
27119
  function parseOption(args, option, parser, defaultValue) {
27041
27120
  if (args[option] === undefined) {
@@ -27071,33 +27150,64 @@ function assertNoMoreArgs(args) {
27071
27150
  throw new Error(`Unrecognized options: '${keysLeft}'`);
27072
27151
  }
27073
27152
  }
27074
- function getProcessAndOutput(type, maybeProcess, maybeOutputFormat) {
27153
+ function getProcessFormatAndDestination(type, maybeProcess, maybeOutputFormat, maybeDestination) {
27154
+ const defaultProcess = "";
27075
27155
  const defaultFormat = parseOutputFormat(undefined);
27076
- const options = type.process?.options ?? [];
27077
- // we have both options, so we expect them in the right order.
27078
- if (maybeProcess !== undefined && maybeOutputFormat !== undefined) {
27156
+ const processOptions = type.process?.options ?? [];
27157
+ // we have all three so it must be in order
27158
+ if (maybeProcess !== undefined && maybeOutputFormat !== undefined && maybeDestination !== undefined) {
27079
27159
  const format = parseOutputFormat(maybeOutputFormat);
27080
- if (!options.includes(maybeProcess)) {
27081
- throw new Error(`Incorrect processing option: ${maybeProcess}. Expected one of: ${options}.`);
27082
- }
27083
- return { process: maybeProcess, format };
27160
+ const process = parseProcess(processOptions, maybeProcess) ?? defaultProcess;
27161
+ const destination = maybeDestination;
27162
+ throwIfDumpNotSupported(format, destination);
27163
+ return { process, format, destination };
27164
+ }
27165
+ // we have either:
27166
+ // 1. process + format
27167
+ // 2. format + destination
27168
+ if (maybeProcess !== undefined && maybeOutputFormat !== undefined) {
27169
+ // we've got processing first, so easy-peasy
27170
+ if (processOptions.includes(maybeProcess)) {
27171
+ const format = parseOutputFormat(maybeOutputFormat);
27172
+ throwIfDumpNotSupported(format, null);
27173
+ return { process: maybeProcess, format, destination: null };
27174
+ }
27175
+ // first one has to be format then.
27176
+ const format = parseOutputFormat(maybeProcess);
27177
+ const destination = maybeOutputFormat;
27178
+ throwIfDumpNotSupported(format, destination);
27179
+ return { process: defaultProcess, format, destination };
27084
27180
  }
27085
27181
  // only one parameter, but it can be either output or processing.
27182
+ const destination = null;
27086
27183
  if (maybeProcess !== undefined) {
27087
- if (options.includes(maybeProcess)) {
27088
- return { process: maybeProcess, format: defaultFormat };
27184
+ if (processOptions.includes(maybeProcess)) {
27185
+ return { process: maybeProcess, format: defaultFormat, destination };
27089
27186
  }
27090
27187
  // now it should be output format, but we want to give a better error message,
27091
27188
  // if user mispelled processing.
27092
27189
  try {
27093
27190
  const format = parseOutputFormat(maybeProcess);
27094
- return { process: "", format };
27191
+ throwIfDumpNotSupported(format, destination);
27192
+ return { process: defaultProcess, format, destination };
27095
27193
  }
27096
27194
  catch {
27097
27195
  throw new Error(`'${maybeProcess}' is neither output format nor processing parameter.`);
27098
27196
  }
27099
27197
  }
27100
- return { process: "", format: defaultFormat };
27198
+ return { process: defaultProcess, format: defaultFormat, destination };
27199
+ }
27200
+ function throwIfDumpNotSupported(format, destination) {
27201
+ if (destination !== null) {
27202
+ if (format === OutputFormat.Print || format === OutputFormat.Repl) {
27203
+ throw new Error(`Dumping to file is not supported for ${format}`);
27204
+ }
27205
+ }
27206
+ else {
27207
+ if (format === OutputFormat.Bin) {
27208
+ throw new Error(`${format} requires destination file`);
27209
+ }
27210
+ }
27101
27211
  }
27102
27212
 
27103
27213
  // EXTERNAL MODULE: ./node_modules/json-bigint-patch/dist/index.js
@@ -27157,9 +27267,13 @@ function loadInputFile(file, withRelPath) {
27157
27267
  throw new Error("Input file format unsupported.");
27158
27268
  }
27159
27269
  function dumpOutput(spec, data, type, outputFormat, args, withRelPath) {
27270
+ const { destination } = args;
27271
+ const dump = destination !== null
27272
+ ? (v) => external_node_fs_default().writeFileSync(withRelPath(destination), v)
27273
+ : (v) => console.info(v);
27160
27274
  switch (outputFormat) {
27161
27275
  case OutputFormat.Print: {
27162
- console.info(`${debug_inspect(data)}`);
27276
+ dump(`${debug_inspect(data)}`);
27163
27277
  return;
27164
27278
  }
27165
27279
  case OutputFormat.Hex: {
@@ -27167,13 +27281,24 @@ function dumpOutput(spec, data, type, outputFormat, args, withRelPath) {
27167
27281
  throw new Error(`${type.name} does not support encoding to JAM codec.`);
27168
27282
  }
27169
27283
  const encoded = encoder_Encoder.encodeObject(type.encode, data, spec);
27170
- console.info(`${encoded}`);
27284
+ dump(`${encoded}`);
27285
+ return;
27286
+ }
27287
+ case OutputFormat.Bin: {
27288
+ if (type.encode === undefined) {
27289
+ throw new Error(`${type.name} does not support encoding to JAM codec.`);
27290
+ }
27291
+ if (destination === null) {
27292
+ throw new Error(`${OutputFormat.Bin} requires destination file.`);
27293
+ }
27294
+ const encoded = encoder_Encoder.encodeObject(type.encode, data, spec);
27295
+ dump(encoded.raw);
27171
27296
  return;
27172
27297
  }
27173
27298
  case OutputFormat.Json: {
27174
27299
  // TODO [ToDr] this will probably not work for all cases,
27175
27300
  // but for now may be good enough.
27176
- console.info(toJson(data));
27301
+ dump(toJson(data));
27177
27302
  return;
27178
27303
  }
27179
27304
  case OutputFormat.Repl: {
@@ -27240,6 +27365,9 @@ function toJson(data) {
27240
27365
  if (value instanceof Map) {
27241
27366
  return Object.fromEntries(value.entries());
27242
27367
  }
27368
+ if (value instanceof ObjectView) {
27369
+ return value.materialize();
27370
+ }
27243
27371
  return value;
27244
27372
  }, 2);
27245
27373
  }
@@ -27250,12 +27378,14 @@ function processOutput(spec, data, type, process) {
27250
27378
  if (type.process === undefined || !type.process.options.includes(process)) {
27251
27379
  throw new Error(`Unsupported processing: '${process}' for '${type.name}'`);
27252
27380
  }
27381
+ const processed = type.process.run(spec, data, process);
27253
27382
  return {
27254
- processed: type.process.run(spec, data, process),
27383
+ processed: processed.value,
27255
27384
  type: {
27256
27385
  ...type,
27257
- // disable encoding, since it won't match
27258
- encode: undefined,
27386
+ name: `${type.name}(${process})`,
27387
+ // use encoding from processed type
27388
+ encode: processed.encode,
27259
27389
  },
27260
27390
  };
27261
27391
  }