@typeberry/jam 0.4.1-9e565b9 → 0.4.1-f776cce

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.
@@ -27978,9 +27978,438 @@ class ArrayView {
27978
27978
  }
27979
27979
  }
27980
27980
 
27981
+ ;// CONCATENATED MODULE: ./packages/core/collections/blob-dictionary.ts
27982
+
27983
+
27984
+ /** A map which uses byte blobs as keys */
27985
+ class BlobDictionary extends WithDebug {
27986
+ mapNodeThreshold;
27987
+ /**
27988
+ * The root node of the dictionary.
27989
+ *
27990
+ * This is the main internal data structure that organizes entries
27991
+ * in a tree-like fashion (array-based nodes up to `mapNodeThreshold`,
27992
+ * map-based nodes beyond it). All insertions, updates, and deletions
27993
+ * operate through this structure.
27994
+ */
27995
+ root = Node.withList();
27996
+ /**
27997
+ * Auxiliary map that stores references to the original keys and their values.
27998
+ *
27999
+ * - Overriding a value in the main structure does not replace the original key reference.
28000
+ * - Used for efficient iteration over `keys()`, `values()`, `entries()`, and computing `size`.
28001
+ */
28002
+ keyvals = new Map();
28003
+ /**
28004
+ * Protected constructor used internally by `BlobDictionary.new`
28005
+ * and `BlobDictionary.fromEntries`.
28006
+ *
28007
+ * This enforces controlled instantiation — users should create instances
28008
+ * through the provided static factory methods instead of calling the
28009
+ * constructor directly.
28010
+ *
28011
+ * @param mapNodeThreshold - The threshold that determines when the dictionary
28012
+ * switches from using an array-based (`ListChildren`) node to a map-based (`MapChildren`) node for storing entries.
28013
+ */
28014
+ constructor(mapNodeThreshold) {
28015
+ super();
28016
+ this.mapNodeThreshold = mapNodeThreshold;
28017
+ }
28018
+ /**
28019
+ * Returns the number of entries in the dictionary.
28020
+ *
28021
+ * The count is derived from the auxiliary `keyvals` map, which stores
28022
+ * all original key references and their associated values. This ensures
28023
+ * that the `size` reflects the actual number of entries, independent of
28024
+ * internal overrides in the main `root` structure.
28025
+ *
28026
+ * @returns The total number of entries in the dictionary.
28027
+ */
28028
+ get size() {
28029
+ return this.keyvals.size;
28030
+ }
28031
+ [TEST_COMPARE_USING]() {
28032
+ const vals = Array.from(this);
28033
+ vals.sort((a, b) => a[0].compare(b[0]).value);
28034
+ return vals;
28035
+ }
28036
+ /**
28037
+ * Creates an empty `BlobDictionary`.
28038
+ *
28039
+ * @param mapNodeThreshold - The threshold that determines when the dictionary
28040
+ * switches from using an array-based (`ListChildren`) node to a map-based (`MapChildren`) node for storing entries.
28041
+ * Defaults to `0`.
28042
+ *
28043
+ * @returns A new, empty `BlobDictionary` instance.
28044
+ */
28045
+ static new(mapNodeThreshold = 0) {
28046
+ return new BlobDictionary(mapNodeThreshold);
28047
+ }
28048
+ /**
28049
+ * Creates a new `BlobDictionary` initialized with the given entries.
28050
+ *
28051
+ * @param entries - An array of `[key, value]` pairs used to populate the dictionary.
28052
+ * @param mapNodeThreshold - The threshold that determines when the dictionary
28053
+ * switches from using an array-based (`ListChildren`) node to a map-based (`MapChildren`) node for storing entries.
28054
+ * Defaults to `0`.
28055
+ *
28056
+ * @returns A new `BlobDictionary` containing the provided entries.
28057
+ */
28058
+ static fromEntries(entries, mapNodeThreshold) {
28059
+ const dict = BlobDictionary.new(mapNodeThreshold);
28060
+ for (const [key, value] of entries) {
28061
+ dict.set(key, value);
28062
+ }
28063
+ return dict;
28064
+ }
28065
+ /**
28066
+ * Internal helper that inserts, updates or deletes an entry in the dictionary.
28067
+ *
28068
+ * Behaviour details:
28069
+ * - Passing `undefined` as `value` indicates a deletion. (E.g. `delete` uses `internalSet(key, undefined)`.)
28070
+ * - When an add (new entry) or a delete actually changes the structure, the method returns the affected leaf node.
28071
+ * - When the call only overrides an existing value (no structural add/delete), the method returns `null`.
28072
+ *
28073
+ * This method is intended for internal use by the dictionary implementation and allows `undefined` as a
28074
+ * sentinel value to signal removals.
28075
+ *
28076
+ * @param key - The key to insert, update or remove.
28077
+ * @param value - The value to associate with the key, or `undefined` to remove the key.
28078
+ * @returns The leaf node created or removed on add/delete, or `null` if the operation only overwrote an existing value.
28079
+ */
28080
+ internalSet(key, value) {
28081
+ let node = this.root;
28082
+ const keyChunkGenerator = key.chunks(CHUNK_SIZE);
28083
+ let depth = 0;
28084
+ for (;;) {
28085
+ const maybeKeyChunk = keyChunkGenerator.next().value;
28086
+ if (maybeKeyChunk === undefined) {
28087
+ if (value === undefined) {
28088
+ return node.remove(key);
28089
+ }
28090
+ return node.set(key, value);
28091
+ }
28092
+ const keyChunk = opaque_asOpaqueType(maybeKeyChunk);
28093
+ if (node.children instanceof ListChildren) {
28094
+ const subkey = bytes_BytesBlob.blobFrom(key.raw.subarray(CHUNK_SIZE * depth));
28095
+ const leaf = value !== undefined ? node.children.insert(subkey, { key, value }) : node.children.remove(subkey);
28096
+ if (subkey.length > CHUNK_SIZE && node.children.children.length > this.mapNodeThreshold) {
28097
+ node.convertListChildrenToMap();
28098
+ }
28099
+ return leaf;
28100
+ }
28101
+ depth += 1;
28102
+ const children = node.children;
28103
+ if (children instanceof ListChildren) {
28104
+ throw new Error("We handle list node earlier. If we fall through, we know it's for the `Map` case.");
28105
+ }
28106
+ if (children instanceof MapChildren) {
28107
+ const maybeNode = children.getChild(keyChunk);
28108
+ if (maybeNode !== undefined) {
28109
+ // simply go one level deeper
28110
+ node = maybeNode;
28111
+ }
28112
+ else {
28113
+ // we are trying to remove an item, but it does not exist
28114
+ if (value === undefined) {
28115
+ return null;
28116
+ }
28117
+ // no more child nodes, we insert a new one.
28118
+ const newNode = Node.withList();
28119
+ children.setChild(keyChunk, newNode);
28120
+ node = newNode;
28121
+ }
28122
+ continue;
28123
+ }
28124
+ assertNever(children);
28125
+ }
28126
+ }
28127
+ /**
28128
+ * Adds a new entry to the dictionary or updates the value of an existing key.
28129
+ *
28130
+ * If an entry with the given key already exists, its value is replaced
28131
+ * with the new one.
28132
+ *
28133
+ * @param key - The key to add or update in the dictionary.
28134
+ * @param value - The value to associate with the specified key.
28135
+ * @returns Nothing (`void`).
28136
+ */
28137
+ set(key, value) {
28138
+ const leaf = this.internalSet(key, value);
28139
+ if (leaf !== null) {
28140
+ this.keyvals.set(leaf.key, leaf);
28141
+ }
28142
+ }
28143
+ /**
28144
+ * Retrieves the value associated with the given key from the dictionary.
28145
+ *
28146
+ * If the key does not exist, this method returns `undefined`.
28147
+ *
28148
+ * @param key - The key whose associated value should be retrieved.
28149
+ * @returns The value associated with the specified key, or `undefined` if the key is not present.
28150
+ */
28151
+ get(key) {
28152
+ let node = this.root;
28153
+ const pathChunksGenerator = key.chunks(CHUNK_SIZE);
28154
+ let depth = 0;
28155
+ while (node !== undefined) {
28156
+ const maybePathChunk = pathChunksGenerator.next().value;
28157
+ if (node.children instanceof ListChildren) {
28158
+ const subkey = bytes_BytesBlob.blobFrom(key.raw.subarray(depth * CHUNK_SIZE));
28159
+ const child = node.children.find(subkey);
28160
+ if (child !== null) {
28161
+ return child.value;
28162
+ }
28163
+ }
28164
+ if (maybePathChunk === undefined) {
28165
+ return node.getLeaf()?.value;
28166
+ }
28167
+ if (node.children instanceof MapChildren) {
28168
+ const pathChunk = opaque_asOpaqueType(maybePathChunk);
28169
+ node = node.children.getChild(pathChunk);
28170
+ depth += 1;
28171
+ }
28172
+ }
28173
+ return undefined;
28174
+ }
28175
+ /**
28176
+ * Checks whether the dictionary contains an entry for the given key.
28177
+ *
28178
+ * ⚠️ **Note:** Avoid using `has(...)` together with `get(...)` in a pattern like this:
28179
+ *
28180
+ * ```ts
28181
+ * if (dict.has(key)) {
28182
+ * const value = dict.get(key);
28183
+ * ...
28184
+ * }
28185
+ * ```
28186
+ *
28187
+ * This approach performs two lookups for the same key.
28188
+ *
28189
+ * Instead, prefer the following pattern, which retrieves the value once:
28190
+ *
28191
+ * ```ts
28192
+ * const value = dict.get(key);
28193
+ * if (value !== undefined) {
28194
+ * ...
28195
+ * }
28196
+ * ```
28197
+ *
28198
+ * @param key - The key to check for.
28199
+ * @returns `true` if the dictionary contains an entry for the given key, otherwise `false`.
28200
+ */
28201
+ has(key) {
28202
+ return this.get(key) !== undefined;
28203
+ }
28204
+ /**
28205
+ * Removes an entry with the specified key from the dictionary.
28206
+ *
28207
+ * Internally, this calls {@link internalSet} with `undefined` to mark the entry as deleted.
28208
+ *
28209
+ * @param key - The key of the entry to remove.
28210
+ * @returns `true` if an entry was removed (i.e. the key existed), otherwise `false`.
28211
+ */
28212
+ delete(key) {
28213
+ const leaf = this.internalSet(key, undefined);
28214
+ if (leaf !== null) {
28215
+ this.keyvals.delete(leaf.key);
28216
+ return true;
28217
+ }
28218
+ return false;
28219
+ }
28220
+ /**
28221
+ * Returns an iterator over the keys in the dictionary.
28222
+ *
28223
+ * The iterator yields each key in insertion order.
28224
+ *
28225
+ * @returns An iterator over all keys in the dictionary.
28226
+ */
28227
+ keys() {
28228
+ return this.keyvals.keys();
28229
+ }
28230
+ /**
28231
+ * Returns an iterator over the values in the dictionary.
28232
+ *
28233
+ * The iterator yields each value in insertion order.
28234
+ *
28235
+ * @returns An iterator over all values in the dictionary.
28236
+ */
28237
+ *values() {
28238
+ for (const leaf of this.keyvals.values()) {
28239
+ yield leaf.value;
28240
+ }
28241
+ }
28242
+ /**
28243
+ * Returns an iterator over the `[key, value]` pairs in the dictionary.
28244
+ *
28245
+ * The iterator yields entries in insertion order.
28246
+ *
28247
+ * @returns An iterator over `[key, value]` tuples for each entry in the dictionary.
28248
+ */
28249
+ *entries() {
28250
+ for (const leaf of this.keyvals.values()) {
28251
+ yield [leaf.key, leaf.value];
28252
+ }
28253
+ }
28254
+ /**
28255
+ * Default iterator for the dictionary.
28256
+ *
28257
+ * Equivalent to calling {@link entries}.
28258
+ * Enables iteration with `for...of`:
28259
+ *
28260
+ * ```ts
28261
+ * for (const [key, value] of dict) {
28262
+ * ...
28263
+ * }
28264
+ * ```
28265
+ *
28266
+ * @returns An iterator over `[key, value]` pairs.
28267
+ */
28268
+ [Symbol.iterator]() {
28269
+ return this.entries();
28270
+ }
28271
+ /**
28272
+ * Creates a new sorted array of values, ordered by their corresponding keys.
28273
+ *
28274
+ * Iterates over all entries in the dictionary and sorts them according
28275
+ * to the provided comparator function applied to the keys.
28276
+ *
28277
+ * @param comparator - A comparator function that can compare two keys.
28278
+ *
28279
+ * @returns A new array containing all values from the dictionary,
28280
+ * sorted according to their keys.
28281
+ */
28282
+ toSortedArray(comparator) {
28283
+ const vals = Array.from(this);
28284
+ vals.sort((a, b) => comparator(a[0], b[0]).value);
28285
+ return vals.map((x) => x[1]);
28286
+ }
28287
+ }
28288
+ const CHUNK_SIZE = 6;
28289
+ /**
28290
+ * A function to transform a bytes chunk (up to 6 bytes into U48 number)
28291
+ *
28292
+ * Note that it uses 3 additional bits to store length(`value * 8 + len;`),
28293
+ * It is needed to distinguish shorter chunks that have 0s at the end, for example: [1, 2] and [1, 2, 0]
28294
+ * */
28295
+ function bytesAsU48(bytes) {
28296
+ const len = bytes.length;
28297
+ debug_check `${len <= CHUNK_SIZE} Length has to be <= ${CHUNK_SIZE}, got: ${len}`;
28298
+ let value = bytes[3] | (bytes[2] << 8) | (bytes[1] << 16) | (bytes[0] << 24);
28299
+ for (let i = 4; i < bytes.length; i++) {
28300
+ value = value * 256 + bytes[i];
28301
+ }
28302
+ return value * 8 + len;
28303
+ }
28304
+ class Node {
28305
+ leaf;
28306
+ children;
28307
+ convertListChildrenToMap() {
28308
+ if (!(this.children instanceof ListChildren)) {
28309
+ return;
28310
+ }
28311
+ this.children = MapChildren.fromListNode(this.children);
28312
+ }
28313
+ static withList() {
28314
+ return new Node(undefined, ListChildren.new());
28315
+ }
28316
+ static withMap() {
28317
+ return new Node(undefined, MapChildren.new());
28318
+ }
28319
+ constructor(leaf, children) {
28320
+ this.leaf = leaf;
28321
+ this.children = children;
28322
+ }
28323
+ getLeaf() {
28324
+ return this.leaf;
28325
+ }
28326
+ remove(_key) {
28327
+ if (this.leaf === undefined) {
28328
+ return null;
28329
+ }
28330
+ const removedLeaf = this.leaf;
28331
+ this.leaf = undefined;
28332
+ return removedLeaf;
28333
+ }
28334
+ set(key, value) {
28335
+ if (this.leaf === undefined) {
28336
+ this.leaf = { key, value };
28337
+ return this.leaf;
28338
+ }
28339
+ this.leaf.value = value;
28340
+ return null;
28341
+ }
28342
+ }
28343
+ class ListChildren {
28344
+ children = [];
28345
+ constructor() { }
28346
+ find(key) {
28347
+ const result = this.children.find((item) => item[0].isEqualTo(key));
28348
+ if (result !== undefined) {
28349
+ return result[1];
28350
+ }
28351
+ return null;
28352
+ }
28353
+ remove(key) {
28354
+ const existingIndex = this.children.findIndex((item) => item[0].isEqualTo(key));
28355
+ if (existingIndex >= 0) {
28356
+ const ret = this.children.splice(existingIndex, 1);
28357
+ return ret[0][1];
28358
+ }
28359
+ return null;
28360
+ }
28361
+ insert(key, leaf) {
28362
+ const existingIndex = this.children.findIndex((item) => item[0].isEqualTo(key));
28363
+ if (existingIndex >= 0) {
28364
+ const existing = this.children[existingIndex];
28365
+ existing[1].value = leaf.value;
28366
+ return null;
28367
+ }
28368
+ this.children.push([key, leaf]);
28369
+ return leaf;
28370
+ }
28371
+ static new() {
28372
+ return new ListChildren();
28373
+ }
28374
+ }
28375
+ class MapChildren {
28376
+ children = new Map();
28377
+ constructor() { }
28378
+ static new() {
28379
+ return new MapChildren();
28380
+ }
28381
+ static fromListNode(node) {
28382
+ const mapNode = new MapChildren();
28383
+ for (const [key, leaf] of node.children) {
28384
+ const currentKeyChunk = opaque_asOpaqueType(bytes_BytesBlob.blobFrom(key.raw.subarray(0, CHUNK_SIZE)));
28385
+ const subKey = bytes_BytesBlob.blobFrom(key.raw.subarray(CHUNK_SIZE));
28386
+ let child = mapNode.getChild(currentKeyChunk);
28387
+ if (child === undefined) {
28388
+ child = Node.withList();
28389
+ mapNode.setChild(currentKeyChunk, child);
28390
+ }
28391
+ const children = child.children;
28392
+ children.insert(subKey, leaf);
28393
+ }
28394
+ return mapNode;
28395
+ }
28396
+ getChild(keyChunk) {
28397
+ const chunkAsNumber = bytesAsU48(keyChunk.raw);
28398
+ return this.children.get(chunkAsNumber);
28399
+ }
28400
+ setChild(keyChunk, node) {
28401
+ const chunkAsNumber = bytesAsU48(keyChunk.raw);
28402
+ this.children.set(chunkAsNumber, node);
28403
+ }
28404
+ }
28405
+
27981
28406
  ;// CONCATENATED MODULE: ./packages/core/collections/hash-dictionary.ts
27982
- /** A map which uses hashes as keys. */
27983
- class hash_dictionary_HashDictionary {
28407
+ /**
28408
+ * A map which uses hashes as keys.
28409
+ *
28410
+ * @deprecated
28411
+ * */
28412
+ class StringHashDictionary {
27984
28413
  // TODO [ToDr] [crit] We can't use `TrieHash` directly in the map,
27985
28414
  // because of the way it's being compared. Hence having `string` here.
27986
28415
  // This has to be benchmarked and re-written to a custom map most likely.
@@ -28046,6 +28475,17 @@ class hash_dictionary_HashDictionary {
28046
28475
  }
28047
28476
  }
28048
28477
 
28478
+ /**
28479
+ * A value that indicates when `BlobDictionary` transforms Array nodes into Map nodes.
28480
+ * In practice, it doesn't matter much because, in real life, arrays in this structure usually have a length close to 1.
28481
+ */
28482
+ const BLOB_DICTIONARY_THRESHOLD = 5;
28483
+ class hash_dictionary_HashDictionary extends BlobDictionary {
28484
+ constructor() {
28485
+ super(BLOB_DICTIONARY_THRESHOLD);
28486
+ }
28487
+ }
28488
+
28049
28489
  ;// CONCATENATED MODULE: ./packages/core/collections/hash-set.ts
28050
28490
 
28051
28491
  /** A set specialized for storing hashes. */
@@ -28510,6 +28950,18 @@ class SortedSet extends (/* unused pure expression or super */ null && (SortedAr
28510
28950
 
28511
28951
 
28512
28952
 
28953
+ function getTruncatedKey(key) {
28954
+ // Always return exactly TRUNCATED_HASH_SIZE bytes.
28955
+ if (key.length === TRUNCATED_HASH_SIZE) {
28956
+ return key;
28957
+ }
28958
+ return bytes_Bytes.fromBlob(key.raw.subarray(0, TRUNCATED_HASH_SIZE), TRUNCATED_HASH_SIZE);
28959
+ }
28960
+ /**
28961
+ * A value that indicates when `BlobDictionary` transforms Array nodes into Map nodes.
28962
+ * In practice, it doesn't matter much because, in real life, arrays in this structure usually have a length close to 1.
28963
+ */
28964
+ const truncated_hash_dictionary_BLOB_DICTIONARY_THRESHOLD = 5;
28513
28965
  /**
28514
28966
  * A collection of hash-based keys (likely `StateKey`s) which ignores
28515
28967
  * differences on the last byte.
@@ -28522,48 +28974,37 @@ class TruncatedHashDictionary {
28522
28974
  * Each key will be copied and have the last byte replace with a 0.
28523
28975
  */
28524
28976
  static fromEntries(entries) {
28525
- /** Copy key bytes of an entry and replace the last one with 0. */
28526
- const mapped = Array.from(entries).map(([key, value]) => {
28527
- const newKey = bytes_Bytes.zero(hash_HASH_SIZE).asOpaque();
28528
- newKey.raw.set(key.raw.subarray(0, TRUNCATED_HASH_SIZE));
28529
- return [newKey, value];
28530
- });
28531
- return new TruncatedHashDictionary(hash_dictionary_HashDictionary.fromEntries(mapped));
28977
+ return new TruncatedHashDictionary(BlobDictionary.fromEntries(Array.from(entries).map(([key, value]) => [getTruncatedKey(key), value]), truncated_hash_dictionary_BLOB_DICTIONARY_THRESHOLD));
28532
28978
  }
28533
- /** A truncated key which we re-use to query the dictionary. */
28534
- truncatedKey = bytes_Bytes.zero(hash_HASH_SIZE).asOpaque();
28535
28979
  constructor(dict) {
28536
28980
  this.dict = dict;
28537
28981
  }
28538
28982
  [TEST_COMPARE_USING]() {
28539
- return this.dict;
28983
+ return Array.from(this.dict);
28540
28984
  }
28541
28985
  /** Return number of items in the dictionary. */
28542
28986
  get size() {
28543
28987
  return this.dict.size;
28544
28988
  }
28545
28989
  /** Retrieve a value that matches the key on `TRUNCATED_HASH_SIZE`. */
28546
- get(fullKey) {
28547
- this.truncatedKey.raw.set(fullKey.raw.subarray(0, TRUNCATED_HASH_SIZE));
28548
- return this.dict.get(this.truncatedKey);
28990
+ get(key) {
28991
+ const truncatedKey = getTruncatedKey(key);
28992
+ return this.dict.get(truncatedKey);
28549
28993
  }
28550
28994
  /** Return true if the key is present in the dictionary */
28551
- has(fullKey) {
28552
- this.truncatedKey.raw.set(fullKey.raw.subarray(0, TRUNCATED_HASH_SIZE));
28553
- return this.dict.has(this.truncatedKey);
28995
+ has(key) {
28996
+ const truncatedKey = getTruncatedKey(key);
28997
+ return this.dict.has(truncatedKey);
28554
28998
  }
28555
28999
  /** Set or update a value that matches the key on `TRUNCATED_HASH_SIZE`. */
28556
- set(fullKey, value) {
28557
- // NOTE we can't use the the shared key here, since the collection will
28558
- // store the key for us, hence the copy.
28559
- const key = bytes_Bytes.zero(hash_HASH_SIZE);
28560
- key.raw.set(fullKey.raw.subarray(0, TRUNCATED_HASH_SIZE));
28561
- this.dict.set(key.asOpaque(), value);
29000
+ set(key, value) {
29001
+ const truncatedKey = getTruncatedKey(key);
29002
+ this.dict.set(truncatedKey, value);
28562
29003
  }
28563
29004
  /** Remove a value that matches the key on `TRUNCATED_HASH_SIZE`. */
28564
- delete(fullKey) {
28565
- this.truncatedKey.raw.set(fullKey.raw.subarray(0, TRUNCATED_HASH_SIZE));
28566
- this.dict.delete(this.truncatedKey);
29005
+ delete(key) {
29006
+ const truncatedKey = getTruncatedKey(key);
29007
+ this.dict.delete(truncatedKey);
28567
29008
  }
28568
29009
  /** Iterator over values of the dictionary. */
28569
29010
  values() {
@@ -28571,9 +29012,7 @@ class TruncatedHashDictionary {
28571
29012
  }
28572
29013
  /** Iterator over entries of the dictionary (with truncated keys) */
28573
29014
  *entries() {
28574
- for (const [key, value] of this.dict.entries()) {
28575
- yield [bytes_Bytes.fromBlob(key.raw.subarray(0, TRUNCATED_HASH_SIZE), TRUNCATED_HASH_SIZE).asOpaque(), value];
28576
- }
29015
+ yield* this.dict.entries();
28577
29016
  }
28578
29017
  [Symbol.iterator]() {
28579
29018
  return this.entries();
@@ -28590,6 +29029,7 @@ class TruncatedHashDictionary {
28590
29029
 
28591
29030
 
28592
29031
 
29032
+
28593
29033
  ;// CONCATENATED MODULE: ./packages/jam/config/chain-spec.ts
28594
29034
 
28595
29035