@typeberry/lib 0.8.4 → 0.9.0-4a9f363

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 (214) hide show
  1. package/package.json +6 -4
  2. package/packages/configs/index.d.ts +30 -1
  3. package/packages/configs/index.d.ts.map +1 -1
  4. package/packages/configs/index.js +4 -2
  5. package/packages/configs/typeberry-dev-full.json +29 -0
  6. package/packages/core/bytes/bytes.d.ts +1 -0
  7. package/packages/core/bytes/bytes.d.ts.map +1 -1
  8. package/packages/core/bytes/bytes.js +8 -0
  9. package/packages/core/collections/sorted-array.d.ts +1 -1
  10. package/packages/core/collections/sorted-array.d.ts.map +1 -1
  11. package/packages/core/collections/sorted-array.js +4 -2
  12. package/packages/core/collections/sorted-array.test.js +10 -0
  13. package/packages/core/collections/sorted-set.d.ts +1 -1
  14. package/packages/core/collections/sorted-set.d.ts.map +1 -1
  15. package/packages/core/collections/sorted-set.js +6 -2
  16. package/packages/core/collections/sorted-set.test.js +24 -0
  17. package/packages/core/utils/debug.d.ts +4 -2
  18. package/packages/core/utils/debug.d.ts.map +1 -1
  19. package/packages/core/utils/debug.js +18 -13
  20. package/packages/core/utils/debug.test.js +12 -6
  21. package/packages/core/utils/index.d.ts +1 -0
  22. package/packages/core/utils/index.d.ts.map +1 -1
  23. package/packages/core/utils/index.js +1 -0
  24. package/packages/core/utils/shutdown.d.ts +18 -0
  25. package/packages/core/utils/shutdown.d.ts.map +1 -0
  26. package/packages/core/utils/shutdown.js +3 -0
  27. package/packages/core/utils/shutdown.node.d.ts +5 -0
  28. package/packages/core/utils/shutdown.node.d.ts.map +1 -0
  29. package/packages/core/utils/shutdown.node.js +76 -0
  30. package/packages/core/utils/shutdown.test.d.ts +2 -0
  31. package/packages/core/utils/shutdown.test.d.ts.map +1 -0
  32. package/packages/core/utils/shutdown.test.js +164 -0
  33. package/packages/extensions/ipc/server.d.ts.map +1 -1
  34. package/packages/extensions/ipc/server.js +7 -0
  35. package/packages/jam/config-node/node-config.d.ts +22 -3
  36. package/packages/jam/config-node/node-config.d.ts.map +1 -1
  37. package/packages/jam/config-node/node-config.js +33 -6
  38. package/packages/jam/config-node/node-config.test.js +11 -4
  39. package/packages/jam/database/index.d.ts +1 -0
  40. package/packages/jam/database/index.d.ts.map +1 -1
  41. package/packages/jam/database/index.js +1 -0
  42. package/packages/jam/database/leaf-db-update.d.ts +1 -0
  43. package/packages/jam/database/leaf-db-update.d.ts.map +1 -1
  44. package/packages/jam/database/leaf-db-update.js +22 -5
  45. package/packages/jam/database/leaf-db-update.test.d.ts +2 -0
  46. package/packages/jam/database/leaf-db-update.test.d.ts.map +1 -0
  47. package/packages/jam/database/leaf-db-update.test.js +81 -0
  48. package/packages/jam/database/serialized-states-db.d.ts +1 -0
  49. package/packages/jam/database/serialized-states-db.d.ts.map +1 -1
  50. package/packages/jam/database/serialized-states-db.js +4 -0
  51. package/packages/jam/database/states.d.ts +11 -0
  52. package/packages/jam/database/states.d.ts.map +1 -1
  53. package/packages/jam/database/states.js +3 -0
  54. package/packages/jam/database/value-refs.d.ts +117 -0
  55. package/packages/jam/database/value-refs.d.ts.map +1 -0
  56. package/packages/jam/database/value-refs.js +206 -0
  57. package/packages/jam/database/value-refs.test.d.ts +2 -0
  58. package/packages/jam/database/value-refs.test.d.ts.map +1 -0
  59. package/packages/jam/database/value-refs.test.js +165 -0
  60. package/packages/jam/database-fjall/blocks.d.ts +25 -0
  61. package/packages/jam/database-fjall/blocks.d.ts.map +1 -0
  62. package/packages/jam/database-fjall/blocks.js +86 -0
  63. package/packages/jam/database-fjall/blocks.test.d.ts +2 -0
  64. package/packages/jam/database-fjall/blocks.test.d.ts.map +1 -0
  65. package/packages/jam/database-fjall/blocks.test.js +62 -0
  66. package/packages/jam/database-fjall/hybrid-states.d.ts +96 -0
  67. package/packages/jam/database-fjall/hybrid-states.d.ts.map +1 -0
  68. package/packages/jam/database-fjall/hybrid-states.js +218 -0
  69. package/packages/jam/database-fjall/hybrid-states.test.d.ts +2 -0
  70. package/packages/jam/database-fjall/hybrid-states.test.d.ts.map +1 -0
  71. package/packages/jam/database-fjall/hybrid-states.test.js +113 -0
  72. package/packages/jam/database-fjall/index.d.ts +5 -0
  73. package/packages/jam/database-fjall/index.d.ts.map +1 -0
  74. package/packages/jam/database-fjall/index.js +4 -0
  75. package/packages/jam/database-fjall/root.d.ts +64 -0
  76. package/packages/jam/database-fjall/root.d.ts.map +1 -0
  77. package/packages/jam/database-fjall/root.js +105 -0
  78. package/packages/jam/database-fjall/states.d.ts +31 -0
  79. package/packages/jam/database-fjall/states.d.ts.map +1 -0
  80. package/packages/jam/database-fjall/states.js +99 -0
  81. package/packages/jam/database-fjall/states.test.d.ts +2 -0
  82. package/packages/jam/database-fjall/states.test.d.ts.map +1 -0
  83. package/packages/jam/database-fjall/states.test.js +150 -0
  84. package/packages/jam/database-lmdb/hybrid-states.d.ts +12 -0
  85. package/packages/jam/database-lmdb/hybrid-states.d.ts.map +1 -1
  86. package/packages/jam/database-lmdb/hybrid-states.js +45 -4
  87. package/packages/jam/database-lmdb/states.d.ts +1 -0
  88. package/packages/jam/database-lmdb/states.d.ts.map +1 -1
  89. package/packages/jam/database-lmdb/states.js +5 -0
  90. package/packages/jam/jamnp-s/tasks/ticket-distribution.d.ts +18 -10
  91. package/packages/jam/jamnp-s/tasks/ticket-distribution.d.ts.map +1 -1
  92. package/packages/jam/jamnp-s/tasks/ticket-distribution.js +44 -68
  93. package/packages/jam/jamnp-s/tasks/ticket-distribution.test.js +30 -8
  94. package/packages/jam/node/export.d.ts.map +1 -1
  95. package/packages/jam/node/export.js +18 -9
  96. package/packages/jam/node/main-fuzz.d.ts +4 -1
  97. package/packages/jam/node/main-fuzz.d.ts.map +1 -1
  98. package/packages/jam/node/main-fuzz.js +142 -55
  99. package/packages/jam/node/main-importer.d.ts +15 -3
  100. package/packages/jam/node/main-importer.d.ts.map +1 -1
  101. package/packages/jam/node/main-importer.js +30 -14
  102. package/packages/jam/node/main.d.ts.map +1 -1
  103. package/packages/jam/node/main.js +42 -15
  104. package/packages/jam/node/workers.d.ts +4 -4
  105. package/packages/jam/node/workers.d.ts.map +1 -1
  106. package/packages/jam/safrole/bandersnatch-vrf.d.ts +24 -4
  107. package/packages/jam/safrole/bandersnatch-vrf.d.ts.map +1 -1
  108. package/packages/jam/safrole/bandersnatch-vrf.js +63 -26
  109. package/packages/jam/safrole/bandersnatch-vrf.test.js +12 -9
  110. package/packages/jam/safrole/bandersnatch-wasm.d.ts +10 -0
  111. package/packages/jam/safrole/bandersnatch-wasm.d.ts.map +1 -1
  112. package/packages/jam/safrole/bandersnatch-wasm.js +12 -0
  113. package/packages/jam/safrole/safrole.js +5 -5
  114. package/packages/jam/safrole/safrole.test.js +13 -13
  115. package/packages/jam/ticket-pool/index.d.ts +4 -0
  116. package/packages/jam/ticket-pool/index.d.ts.map +1 -0
  117. package/packages/jam/ticket-pool/index.js +3 -0
  118. package/packages/jam/ticket-pool/pending-ticket-pool.d.ts +30 -0
  119. package/packages/jam/ticket-pool/pending-ticket-pool.d.ts.map +1 -0
  120. package/packages/jam/ticket-pool/pending-ticket-pool.js +56 -0
  121. package/packages/jam/ticket-pool/pending-ticket-pool.test.d.ts +2 -0
  122. package/packages/jam/ticket-pool/pending-ticket-pool.test.d.ts.map +1 -0
  123. package/packages/jam/ticket-pool/pending-ticket-pool.test.js +67 -0
  124. package/packages/jam/ticket-pool/ticket-validator.d.ts +47 -0
  125. package/packages/jam/ticket-pool/ticket-validator.d.ts.map +1 -0
  126. package/packages/jam/ticket-pool/ticket-validator.js +34 -0
  127. package/packages/jam/ticket-pool/ticket-validator.test.d.ts +2 -0
  128. package/packages/jam/ticket-pool/ticket-validator.test.d.ts.map +1 -0
  129. package/packages/jam/ticket-pool/ticket-validator.test.js +35 -0
  130. package/packages/jam/ticket-pool/verified-ticket-pool.d.ts +26 -0
  131. package/packages/jam/ticket-pool/verified-ticket-pool.d.ts.map +1 -0
  132. package/packages/jam/ticket-pool/verified-ticket-pool.js +41 -0
  133. package/packages/jam/ticket-pool/verified-ticket-pool.test.d.ts +2 -0
  134. package/packages/jam/ticket-pool/verified-ticket-pool.test.d.ts.map +1 -0
  135. package/packages/jam/ticket-pool/verified-ticket-pool.test.js +54 -0
  136. package/packages/workers/api/config.d.ts +2 -2
  137. package/packages/workers/api/config.d.ts.map +1 -1
  138. package/packages/workers/api/config.js +1 -1
  139. package/packages/workers/api/port.d.ts +5 -1
  140. package/packages/workers/api/port.d.ts.map +1 -1
  141. package/packages/workers/api/port.js +56 -13
  142. package/packages/workers/api/port.test.js +35 -0
  143. package/packages/workers/api-node/config.d.ts +65 -9
  144. package/packages/workers/api-node/config.d.ts.map +1 -1
  145. package/packages/workers/api-node/config.js +151 -26
  146. package/packages/workers/api-node/config.test.js +88 -2
  147. package/packages/workers/api-node/port.d.ts +3 -0
  148. package/packages/workers/api-node/port.d.ts.map +1 -1
  149. package/packages/workers/api-node/port.js +31 -2
  150. package/packages/workers/api-node/port.test.js +17 -0
  151. package/packages/workers/api-node/protocol.d.ts +3 -3
  152. package/packages/workers/api-node/protocol.d.ts.map +1 -1
  153. package/packages/workers/api-node/protocol.js +18 -12
  154. package/packages/workers/block-authorship/{generator.d.ts → block-generator.d.ts} +5 -5
  155. package/packages/workers/block-authorship/block-generator.d.ts.map +1 -0
  156. package/packages/workers/block-authorship/{generator.js → block-generator.js} +3 -3
  157. package/packages/workers/block-authorship/block-generator.test.d.ts +2 -0
  158. package/packages/workers/block-authorship/block-generator.test.d.ts.map +1 -0
  159. package/packages/workers/block-authorship/{generator.test.js → block-generator.test.js} +8 -8
  160. package/packages/workers/block-authorship/epoch-authoring-slots.d.ts +35 -0
  161. package/packages/workers/block-authorship/epoch-authoring-slots.d.ts.map +1 -0
  162. package/packages/workers/block-authorship/epoch-authoring-slots.js +86 -0
  163. package/packages/workers/block-authorship/epoch-tracker.d.ts +29 -0
  164. package/packages/workers/block-authorship/epoch-tracker.d.ts.map +1 -0
  165. package/packages/workers/block-authorship/epoch-tracker.js +80 -0
  166. package/packages/workers/block-authorship/index.d.ts.map +1 -1
  167. package/packages/workers/block-authorship/index.js +1 -1
  168. package/packages/workers/block-authorship/main.d.ts +3 -0
  169. package/packages/workers/block-authorship/main.d.ts.map +1 -1
  170. package/packages/workers/block-authorship/main.js +198 -316
  171. package/packages/workers/block-authorship/ticket-generator/bootstrap-main.d.ts +2 -0
  172. package/packages/workers/block-authorship/ticket-generator/bootstrap-main.d.ts.map +1 -0
  173. package/packages/workers/block-authorship/ticket-generator/bootstrap-main.js +23 -0
  174. package/packages/workers/block-authorship/ticket-generator/index.d.ts +16 -0
  175. package/packages/workers/block-authorship/ticket-generator/index.d.ts.map +1 -0
  176. package/packages/workers/block-authorship/ticket-generator/index.js +62 -0
  177. package/packages/workers/block-authorship/ticket-generator/protocol.d.ts +50 -0
  178. package/packages/workers/block-authorship/ticket-generator/protocol.d.ts.map +1 -0
  179. package/packages/workers/block-authorship/ticket-generator/protocol.js +54 -0
  180. package/packages/workers/block-authorship/{ticket-generator.d.ts → ticket-generator/ticket-generator.d.ts} +4 -0
  181. package/packages/workers/block-authorship/ticket-generator/ticket-generator.d.ts.map +1 -0
  182. package/packages/workers/block-authorship/{ticket-generator.js → ticket-generator/ticket-generator.js} +19 -9
  183. package/packages/workers/block-authorship/ticket-generator/ticket-generator.test.d.ts.map +1 -0
  184. package/packages/workers/block-authorship/{ticket-generator.test.js → ticket-generator/ticket-generator.test.js} +13 -9
  185. package/packages/workers/block-authorship/ticket-generator/worker-pool.d.ts +36 -0
  186. package/packages/workers/block-authorship/ticket-generator/worker-pool.d.ts.map +1 -0
  187. package/packages/workers/block-authorship/ticket-generator/worker-pool.js +111 -0
  188. package/packages/workers/block-authorship/ticket-validator.d.ts +31 -0
  189. package/packages/workers/block-authorship/ticket-validator.d.ts.map +1 -0
  190. package/packages/workers/block-authorship/ticket-validator.js +59 -0
  191. package/packages/workers/comms-authorship-network/protocol.d.ts +14 -4
  192. package/packages/workers/comms-authorship-network/protocol.d.ts.map +1 -1
  193. package/packages/workers/comms-authorship-network/protocol.js +12 -6
  194. package/packages/workers/comms-authorship-network/tickets-message.d.ts +0 -14
  195. package/packages/workers/comms-authorship-network/tickets-message.d.ts.map +1 -1
  196. package/packages/workers/comms-authorship-network/tickets-message.js +0 -17
  197. package/packages/workers/importer/importer.d.ts +2 -2
  198. package/packages/workers/importer/importer.d.ts.map +1 -1
  199. package/packages/workers/importer/importer.js +5 -5
  200. package/packages/workers/importer/main.d.ts +1 -1
  201. package/packages/workers/importer/main.d.ts.map +1 -1
  202. package/packages/workers/importer/main.js +1 -1
  203. package/packages/workers/importer/stats.d.ts +1 -3
  204. package/packages/workers/importer/stats.d.ts.map +1 -1
  205. package/packages/workers/importer/stats.js +12 -12
  206. package/packages/workers/jam-network/main.d.ts.map +1 -1
  207. package/packages/workers/jam-network/main.js +26 -5
  208. package/packages/workers/block-authorship/generator.d.ts.map +0 -1
  209. package/packages/workers/block-authorship/generator.test.d.ts +0 -2
  210. package/packages/workers/block-authorship/generator.test.d.ts.map +0 -1
  211. package/packages/workers/block-authorship/ticket-generator.d.ts.map +0 -1
  212. package/packages/workers/block-authorship/ticket-generator.test.d.ts.map +0 -1
  213. /package/packages/configs/{typeberry-dev.json → typeberry-dev-tiny.json} +0 -0
  214. /package/packages/workers/block-authorship/{ticket-generator.test.d.ts → ticket-generator/ticket-generator.test.d.ts} +0 -0
@@ -0,0 +1,218 @@
1
+ import { HashDictionary, SortedSet } from "#@typeberry/collections";
2
+ import { InMemoryValueRefsStore, LeafDb, StateUpdateError, updateLeafs, ValueRefs, } from "#@typeberry/database";
3
+ import { Logger } from "#@typeberry/logger";
4
+ import { SerializedState, StateEntryUpdateAction, serializeStateUpdate, } from "#@typeberry/state-merkleization";
5
+ import { leafComparator } from "#@typeberry/trie";
6
+ import { OK, Result } from "#@typeberry/utils";
7
+ import { FjallRoot, toUint8Array } from "./root.js";
8
+ const logger = Logger.new(import.meta.filename, "db");
9
+ /**
10
+ * One open fjall keyspace together with its content-addressed `values`
11
+ * partition.
12
+ *
13
+ * Opening the keyspace is the slow part, so the fuzz target opens one session
14
+ * per run and reuses it for every reset (see `HybridSerializedStates.fromSession`).
15
+ * The values partition is immutable - the key is the hash of the value - so it
16
+ * is fine that values pile up across resets, the unreferenced ones just sit
17
+ * there unused.
18
+ */
19
+ export class FjallValuesSession {
20
+ root;
21
+ values;
22
+ constructor(root,
23
+ /** Shared content-addressed values partition, reused across resets. */
24
+ values) {
25
+ this.root = root;
26
+ this.values = values;
27
+ }
28
+ /** Open (or create) the keyspace at `dbPath` and its `values` partition. */
29
+ static async open(dbPath, options = {}) {
30
+ if (options.readOnly === true) {
31
+ throw new Error("FjallValuesSession requires a writable keyspace.");
32
+ }
33
+ const root = await FjallRoot.open(dbPath, options);
34
+ try {
35
+ const values = await root.writablePartition("values");
36
+ return new FjallValuesSession(root, values);
37
+ }
38
+ catch (e) {
39
+ await root.close();
40
+ throw e;
41
+ }
42
+ }
43
+ /** Flush the journal to disk (a no-op for ephemeral keyspaces). */
44
+ async persist() {
45
+ await this.root.persist();
46
+ }
47
+ /** Size of the keyspace directory on disk, in bytes. */
48
+ sizeInBytes() {
49
+ return this.root.sizeInBytes();
50
+ }
51
+ /** Release the keyspace handle (skips the sync-all fsync when ephemeral). */
52
+ async close() {
53
+ await this.root.close();
54
+ }
55
+ }
56
+ /**
57
+ * Hybrid serialized-states db (fjall variant).
58
+ *
59
+ * States (leafs) are kept in memory, only the large values go to fjall on disk.
60
+ * Reads hit fjall directly, which keeps its own bounded block cache. Meant for
61
+ * long fuzzing, used together with pruning so the heap stays bounded.
62
+ *
63
+ * Construction is async, and value writes are flushed explicitly, because fjall
64
+ * has no transaction primitive.
65
+ *
66
+ * Values that no longer belong to any surviving state are removed from fjall,
67
+ * decided by in-memory refcounting (`ValueRefs`) driven by the importer's
68
+ * finality signal. Counts are not persisted: this db cannot resume from disk
69
+ * anyway (the leaf sets live in memory), so values left over by a previous run
70
+ * are never collected. An instance backed by a shared session (fuzz reset
71
+ * reuse) only ever prunes values it inserted itself, since its refcounts start
72
+ * empty - values left behind by earlier resets stay untouched.
73
+ */
74
+ export class HybridSerializedStates {
75
+ spec;
76
+ blake2b;
77
+ session;
78
+ ownsSession;
79
+ static async new({ spec, blake2b, dbPath, ephemeral, cacheSizeBytes, }) {
80
+ const session = await FjallValuesSession.open(dbPath, { ephemeral, cacheSizeBytes });
81
+ // This instance owns the session it just opened, so its `close()` closes it.
82
+ return new HybridSerializedStates(spec, blake2b, session, true);
83
+ }
84
+ /**
85
+ * Wrap an already-open `FjallValuesSession` and reuse its keyspace.
86
+ *
87
+ * The new instance starts with its own empty in-memory leaf sets but shares
88
+ * the values partition on disk. Its `close()` does not close the session, the
89
+ * session owner closes it once. The fuzz target uses this to keep one keyspace
90
+ * across resets and only rebuild the in-memory state for each vector.
91
+ */
92
+ static fromSession(spec, blake2b, session) {
93
+ return new HybridSerializedStates(spec, blake2b, session, false);
94
+ }
95
+ inMemStates = HashDictionary.new();
96
+ // A single shared values accessor reused by every `LeafDb` we hand out.
97
+ valuesDb;
98
+ /** Shared content-addressed values partition (owned by `session`). */
99
+ values;
100
+ refsStore = new InMemoryValueRefsStore();
101
+ refs = new ValueRefs(this.refsStore);
102
+ // Queue of not-yet-committed value removals, awaited on close.
103
+ pendingCleanup = Promise.resolve();
104
+ constructor(spec, blake2b, session,
105
+ /** Whether `close()` should close the underlying session. */
106
+ ownsSession) {
107
+ this.spec = spec;
108
+ this.blake2b = blake2b;
109
+ this.session = session;
110
+ this.ownsSession = ownsSession;
111
+ this.values = session.values;
112
+ this.valuesDb = { get: (key) => this.readValue(key) };
113
+ }
114
+ async insertInitialState(headerHash, entries) {
115
+ const { values, leafs } = updateLeafs(SortedSet.fromArray(leafComparator, []), this.blake2b, Array.from(entries, (x) => [StateEntryUpdateAction.Insert, x[0], x[1]]));
116
+ const res = await this.writeValues(values);
117
+ if (res.isError) {
118
+ return res;
119
+ }
120
+ this.inMemStates.set(headerHash, leafs);
121
+ this.applyRefs(this.refs.onInitial(values.map((v) => v[0])));
122
+ return Result.ok(OK);
123
+ }
124
+ async updateAndSetState(header, state, update) {
125
+ const updatedValues = serializeStateUpdate(this.spec, this.blake2b, update);
126
+ // Clone the leaf set before mutating: the previous state keeps using its own.
127
+ const newLeafs = SortedSet.fromSortedArray(leafComparator, state.backend.leafs.array);
128
+ const { values, removed, leafs } = updateLeafs(newLeafs, this.blake2b, updatedValues);
129
+ const res = await this.writeValues(values);
130
+ if (res.isError) {
131
+ // Leave the caller's state untouched: its new leaves would reference
132
+ // values that never reached disk.
133
+ return res;
134
+ }
135
+ // Re-create the lookup with the shared values accessor only once the new
136
+ // values are durably written.
137
+ state.updateBackend(LeafDb.fromLeaves(leafs, this.valuesDb));
138
+ this.inMemStates.set(header, leafs);
139
+ this.applyRefs(this.refs.onImport(header, { inserted: values.map((v) => v[0]), removed }));
140
+ return Result.ok(OK);
141
+ }
142
+ async getStateRoot(state) {
143
+ return state.backend.getStateRoot(this.blake2b);
144
+ }
145
+ getState(header) {
146
+ const leafs = this.inMemStates.get(header);
147
+ if (leafs === undefined) {
148
+ return null;
149
+ }
150
+ const leafDb = LeafDb.fromLeaves(leafs, this.valuesDb);
151
+ return SerializedState.new(this.spec, this.blake2b, leafDb);
152
+ }
153
+ commitFinalized(headers) {
154
+ this.applyRefs(this.refs.commitFinalized(headers));
155
+ }
156
+ markUnused(header) {
157
+ // Release the speculative references first (a no-op for finalized states,
158
+ // whose deltas were already consumed by `commitFinalized`).
159
+ this.applyRefs(this.refs.releaseUnfinalized(header));
160
+ this.inMemStates.delete(header);
161
+ }
162
+ diskSizeInBytes() {
163
+ return this.session.sizeInBytes();
164
+ }
165
+ /** Apply a refcounting update and remove values that lost their last reference. */
166
+ applyRefs(update) {
167
+ this.refsStore.apply(update);
168
+ if (update.removeValues.length === 0) {
169
+ return;
170
+ }
171
+ // Queued, not awaited: a failed removal only leaks a value. No explicit
172
+ // persist - removals are flushed together with the next value write.
173
+ this.pendingCleanup = this.pendingCleanup
174
+ .then(() => Promise.all(update.removeValues.map((v) => this.values.remove(v.raw))))
175
+ .catch((e) => {
176
+ logger.error `Failed to remove unreferenced values: ${e}`;
177
+ });
178
+ }
179
+ async close() {
180
+ // Finish any queued value removals before tearing down (or releasing) the
181
+ // session - they operate on the shared `values` partition.
182
+ await this.pendingCleanup;
183
+ // Instances backed by a shared session (fuzz reset reuse) keep the keyspace
184
+ // open for the next reset. The session owner closes it once.
185
+ if (this.ownsSession) {
186
+ await this.session.close();
187
+ }
188
+ }
189
+ /** Write new large values to fjall in a single batch, then flush. */
190
+ async writeValues(values) {
191
+ if (values.length === 0) {
192
+ return Result.ok(OK);
193
+ }
194
+ try {
195
+ // Flush queued removals first: a pending cleanup might be about to delete
196
+ // a content hash we are re-inserting now. Writing behind it keeps the
197
+ // re-inserted value on disk (removals are only queued at refcount 0, so
198
+ // none can be queued for a value still referenced).
199
+ await this.pendingCleanup;
200
+ const entries = values.map(([hash, val]) => ({ key: hash.raw, value: val.raw }));
201
+ await this.values.insertBatch(entries);
202
+ await this.session.persist();
203
+ }
204
+ catch (e) {
205
+ logger.error `${e}`;
206
+ return Result.error(StateUpdateError.Commit, () => `Failed to commit values: ${e}`);
207
+ }
208
+ return Result.ok(OK);
209
+ }
210
+ /** Read a value from fjall. */
211
+ readValue(key) {
212
+ const val = toUint8Array(this.values.get(key.raw));
213
+ if (val === null) {
214
+ throw new Error(`Missing value at key: ${key}`);
215
+ }
216
+ return val;
217
+ }
218
+ }
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=hybrid-states.test.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"hybrid-states.test.d.ts","sourceRoot":"","sources":["../../../../../packages/jam/database-fjall/hybrid-states.test.ts"],"names":[],"mappings":""}
@@ -0,0 +1,113 @@
1
+ import assert from "node:assert";
2
+ import * as fs from "node:fs";
3
+ import { afterEach, before, beforeEach, describe, it } from "node:test";
4
+ import { Bytes, BytesBlob } from "#@typeberry/bytes";
5
+ import { tinyChainSpec } from "#@typeberry/config";
6
+ import { Blake2b, HASH_SIZE } from "#@typeberry/hash";
7
+ import { InMemoryState } from "#@typeberry/state";
8
+ import { StateEntries } from "#@typeberry/state-merkleization";
9
+ import { deepEqual, OK, Result } from "#@typeberry/utils";
10
+ import { FjallValuesSession, HybridSerializedStates } from "./hybrid-states.js";
11
+ let blake2b;
12
+ before(async () => {
13
+ blake2b = await Blake2b.createHasher();
14
+ });
15
+ function createTempDir(suffix = "fjall-hybrid") {
16
+ return fs.mkdtempSync(`typeberry-${suffix}`);
17
+ }
18
+ describe("Fjall hybrid serialized states", () => {
19
+ const spec = tinyChainSpec;
20
+ const headerHash = Bytes.zero(HASH_SIZE).asOpaque();
21
+ let dbPath = "";
22
+ beforeEach(() => {
23
+ dbPath = createTempDir();
24
+ });
25
+ afterEach(() => {
26
+ fs.rmSync(dbPath, { recursive: true });
27
+ });
28
+ it("round-trips an initial state through the on-disk values store", async () => {
29
+ const states = await HybridSerializedStates.new({ spec, blake2b, dbPath });
30
+ try {
31
+ const empty = InMemoryState.empty(spec);
32
+ const serialized = StateEntries.serializeInMemory(spec, blake2b, empty);
33
+ const expectedRoot = serialized.getRootHash(blake2b);
34
+ const res = await states.insertInitialState(headerHash, serialized);
35
+ deepEqual(res, Result.ok(OK));
36
+ const state = states.getState(headerHash);
37
+ assert.ok(state !== null);
38
+ const stateRoot = await states.getStateRoot(state);
39
+ assert.strictEqual(`${stateRoot}`, `${expectedRoot}`);
40
+ deepEqual(InMemoryState.copyFrom(spec, state, new Map()), empty);
41
+ }
42
+ finally {
43
+ await states.close();
44
+ }
45
+ });
46
+ it("reads large values back from disk", async () => {
47
+ const states = await HybridSerializedStates.new({ spec, blake2b, dbPath });
48
+ try {
49
+ // > 32 bytes => stored in the values db (not embedded in the leaf).
50
+ const big1 = BytesBlob.blobFromString("x".repeat(100));
51
+ const big2 = BytesBlob.blobFromString("y".repeat(100));
52
+ const key1 = Bytes.fill(HASH_SIZE, 1).asOpaque();
53
+ const key2 = Bytes.fill(HASH_SIZE, 2).asOpaque();
54
+ const entries = StateEntries.fromEntriesUnsafe([
55
+ [key1, big1],
56
+ [key2, big2],
57
+ ]);
58
+ const res = await states.insertInitialState(headerHash, entries);
59
+ deepEqual(res, Result.ok(OK));
60
+ const state = states.getState(headerHash);
61
+ assert.ok(state !== null);
62
+ assert.strictEqual(`${state.backend.get(key2)}`, `${big2}`);
63
+ assert.strictEqual(`${state.backend.get(key1)}`, `${big1}`);
64
+ }
65
+ finally {
66
+ await states.close();
67
+ }
68
+ });
69
+ it("shares an open values session across resets without closing it", async () => {
70
+ // The fuzz reset path opens the values keyspace once per session and reuses
71
+ // it: each "reset" builds a fresh states instance sharing that session, and
72
+ // closing a session-backed states must NOT close the shared keyspace.
73
+ const session = await FjallValuesSession.open(dbPath);
74
+ try {
75
+ const big = BytesBlob.blobFromString("z".repeat(100));
76
+ const key = Bytes.fill(HASH_SIZE, 7).asOpaque();
77
+ const entries = StateEntries.fromEntriesUnsafe([[key, big]]);
78
+ // First "reset": write values through a states instance, then close it.
79
+ const first = HybridSerializedStates.fromSession(spec, blake2b, session);
80
+ const res = await first.insertInitialState(headerHash, entries);
81
+ deepEqual(res, Result.ok(OK));
82
+ await first.close();
83
+ // Second "reset": a fresh states sharing the same session. Its in-memory
84
+ // leaf set is independent (empty until it inserts)...
85
+ const second = HybridSerializedStates.fromSession(spec, blake2b, session);
86
+ assert.strictEqual(second.getState(headerHash), null);
87
+ // ...but the on-disk values store is the same one, still open and usable
88
+ // (a closed keyspace would throw here).
89
+ await second.insertInitialState(headerHash, entries);
90
+ const state = second.getState(headerHash);
91
+ assert.ok(state !== null);
92
+ assert.strictEqual(`${state.backend.get(key)}`, `${big}`);
93
+ await second.close();
94
+ }
95
+ finally {
96
+ await session.close();
97
+ }
98
+ });
99
+ it("drops the leaf set on markUnused while values stay on disk", async () => {
100
+ const states = await HybridSerializedStates.new({ spec, blake2b, dbPath });
101
+ try {
102
+ const empty = InMemoryState.empty(spec);
103
+ const serialized = StateEntries.serializeInMemory(spec, blake2b, empty);
104
+ await states.insertInitialState(headerHash, serialized);
105
+ assert.ok(states.getState(headerHash) !== null);
106
+ states.markUnused(headerHash);
107
+ assert.strictEqual(states.getState(headerHash), null);
108
+ }
109
+ finally {
110
+ await states.close();
111
+ }
112
+ });
113
+ });
@@ -0,0 +1,5 @@
1
+ export * from "./blocks.js";
2
+ export * from "./hybrid-states.js";
3
+ export * from "./root.js";
4
+ export * from "./states.js";
5
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../../../packages/jam/database-fjall/index.ts"],"names":[],"mappings":"AAAA,cAAc,aAAa,CAAC;AAC5B,cAAc,oBAAoB,CAAC;AACnC,cAAc,WAAW,CAAC;AAC1B,cAAc,aAAa,CAAC"}
@@ -0,0 +1,4 @@
1
+ export * from "./blocks.js";
2
+ export * from "./hybrid-states.js";
3
+ export * from "./root.js";
4
+ export * from "./states.js";
@@ -0,0 +1,64 @@
1
+ import { type Partition, type ReadonlyPartition } from "@fjall-js/fjall";
2
+ export type { Partition, ReadonlyPartition };
3
+ export type FjallPartition = Partition | ReadonlyPartition;
4
+ /**
5
+ * Normalize a value read from fjall (a Node `Buffer`) into a plain `Uint8Array`.
6
+ */
7
+ export declare function toUint8Array(value: Buffer | null): Uint8Array | null;
8
+ export type FjallRootOptions = {
9
+ /** Open a read-only wrapper surface over the shared keyspace. */
10
+ readOnly?: boolean;
11
+ /**
12
+ * When set, we skip explicit durability flushes (`persist`).
13
+ *
14
+ * Only safe for throwaway databases, like the fuzz target that wipes on every
15
+ * reset.
16
+ */
17
+ ephemeral?: boolean;
18
+ /**
19
+ * Cache size in bytes, shared by all partitions of the keyspace. fjall reads
20
+ * through this cache, so it bounds how much we keep in memory. When not set,
21
+ * typeberry uses a conservative default.
22
+ */
23
+ cacheSizeBytes?: number;
24
+ };
25
+ /**
26
+ * Thin wrapper over the fjall keyspace.
27
+ *
28
+ * fjall is an LSM-tree: it reads and writes through normal file i/o and keeps
29
+ * only a bounded block cache in memory, so the resident set stays bounded even
30
+ * when the store on disk is big.
31
+ */
32
+ export declare class FjallRoot {
33
+ private readonly keyspace;
34
+ /** Path of the underlying keyspace directory, used to report on-disk usage. */
35
+ private readonly dbPath;
36
+ private readonly options;
37
+ private constructor();
38
+ /** Open (or create) a fjall keyspace at the given path. */
39
+ static open(dbPath: string, options?: FjallRootOptions): Promise<FjallRoot>;
40
+ /** Whether this root was opened through fjall's read-only surface. */
41
+ get readOnly(): boolean;
42
+ /** Open (or create) a partition under this keyspace. */
43
+ partition(name: string): Promise<FjallPartition>;
44
+ /** Open a writable partition, failing early when this root is read-only. */
45
+ writablePartition(name: string): Promise<Partition>;
46
+ /**
47
+ * Flush the journal to disk so prior writes survive a crash.
48
+ *
49
+ * Call after a logically-complete unit of work (one block, one state commit).
50
+ * A no-op for ephemeral databases.
51
+ */
52
+ persist(): Promise<void>;
53
+ /**
54
+ * Size of the keyspace directory on disk, in bytes.
55
+ *
56
+ * Returns `null` when the directory cannot be walked (e.g. not created yet).
57
+ * A fjall keyspace is a directory of partition and journal files, so we sum
58
+ * them recursively.
59
+ */
60
+ sizeInBytes(): number | null;
61
+ /** Release this keyspace handle. Call persist() first when durability is needed. */
62
+ close(): Promise<void>;
63
+ }
64
+ //# sourceMappingURL=root.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"root.d.ts","sourceRoot":"","sources":["../../../../../packages/jam/database-fjall/root.ts"],"names":[],"mappings":"AAEA,OAAO,EAIL,KAAK,SAAS,EAEd,KAAK,iBAAiB,EACvB,MAAM,iBAAiB,CAAC;AAIzB,YAAY,EAAE,SAAS,EAAE,iBAAiB,EAAE,CAAC;AAC7C,MAAM,MAAM,cAAc,GAAG,SAAS,GAAG,iBAAiB,CAAC;AAE3D;;GAEG;AACH,wBAAgB,YAAY,CAAC,KAAK,EAAE,MAAM,GAAG,IAAI,GAAG,UAAU,GAAG,IAAI,CAKpE;AAED,MAAM,MAAM,gBAAgB,GAAG;IAC7B,iEAAiE;IACjE,QAAQ,CAAC,EAAE,OAAO,CAAC;IACnB;;;;;OAKG;IACH,SAAS,CAAC,EAAE,OAAO,CAAC;IACpB;;;;OAIG;IACH,cAAc,CAAC,EAAE,MAAM,CAAC;CACzB,CAAC;AAEF;;;;;;GAMG;AACH,qBAAa,SAAS;IAElB,OAAO,CAAC,QAAQ,CAAC,QAAQ;IACzB,+EAA+E;IAC/E,OAAO,CAAC,QAAQ,CAAC,MAAM;IACvB,OAAO,CAAC,QAAQ,CAAC,OAAO;IAJ1B,OAAO;IAOP,2DAA2D;WAC9C,IAAI,CAAC,MAAM,EAAE,MAAM,EAAE,OAAO,GAAE,gBAAqB,GAAG,OAAO,CAAC,SAAS,CAAC;IAWrF,sEAAsE;IACtE,IAAI,QAAQ,IAAI,OAAO,CAEtB;IAED,wDAAwD;IAClD,SAAS,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,CAAC,cAAc,CAAC;IAItD,4EAA4E;IACtE,iBAAiB,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,CAAC,SAAS,CAAC;IAOzD;;;;;OAKG;IACG,OAAO,IAAI,OAAO,CAAC,IAAI,CAAC;IAU9B;;;;;;OAMG;IACH,WAAW,IAAI,MAAM,GAAG,IAAI;IAQ5B,oFAAoF;IAC9E,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC;CAG7B"}
@@ -0,0 +1,105 @@
1
+ import * as fs from "node:fs";
2
+ import * as path from "node:path";
3
+ import { open, openReadonly, } from "@fjall-js/fjall";
4
+ const DEFAULT_CACHE_SIZE_BYTES = 64 * 1024 * 1024;
5
+ /**
6
+ * Normalize a value read from fjall (a Node `Buffer`) into a plain `Uint8Array`.
7
+ */
8
+ export function toUint8Array(value) {
9
+ if (value === null) {
10
+ return null;
11
+ }
12
+ return new Uint8Array(value.buffer, value.byteOffset, value.byteLength);
13
+ }
14
+ /**
15
+ * Thin wrapper over the fjall keyspace.
16
+ *
17
+ * fjall is an LSM-tree: it reads and writes through normal file i/o and keeps
18
+ * only a bounded block cache in memory, so the resident set stays bounded even
19
+ * when the store on disk is big.
20
+ */
21
+ export class FjallRoot {
22
+ keyspace;
23
+ dbPath;
24
+ options;
25
+ constructor(keyspace,
26
+ /** Path of the underlying keyspace directory, used to report on-disk usage. */
27
+ dbPath, options) {
28
+ this.keyspace = keyspace;
29
+ this.dbPath = dbPath;
30
+ this.options = options;
31
+ }
32
+ /** Open (or create) a fjall keyspace at the given path. */
33
+ static async open(dbPath, options = {}) {
34
+ // fjall-js 0.3 shares one engine per path. Readers must use the read-only
35
+ // wrapper surface; durability is driven explicitly through persist().
36
+ const config = {
37
+ path: dbPath,
38
+ cacheSizeBytes: options.cacheSizeBytes ?? DEFAULT_CACHE_SIZE_BYTES,
39
+ };
40
+ const keyspace = options.readOnly === true ? await openReadonly(config) : await open(config);
41
+ return new FjallRoot(keyspace, dbPath, options);
42
+ }
43
+ /** Whether this root was opened through fjall's read-only surface. */
44
+ get readOnly() {
45
+ return this.options.readOnly === true;
46
+ }
47
+ /** Open (or create) a partition under this keyspace. */
48
+ async partition(name) {
49
+ return this.keyspace.partition(name);
50
+ }
51
+ /** Open a writable partition, failing early when this root is read-only. */
52
+ async writablePartition(name) {
53
+ if (this.readOnly) {
54
+ throw new Error(`Cannot open writable fjall partition '${name}' from a read-only keyspace.`);
55
+ }
56
+ return (await this.keyspace.partition(name));
57
+ }
58
+ /**
59
+ * Flush the journal to disk so prior writes survive a crash.
60
+ *
61
+ * Call after a logically-complete unit of work (one block, one state commit).
62
+ * A no-op for ephemeral databases.
63
+ */
64
+ async persist() {
65
+ if (this.options.ephemeral === true) {
66
+ return;
67
+ }
68
+ if (this.readOnly) {
69
+ throw new Error("Cannot persist a read-only fjall keyspace.");
70
+ }
71
+ await this.keyspace.persist();
72
+ }
73
+ /**
74
+ * Size of the keyspace directory on disk, in bytes.
75
+ *
76
+ * Returns `null` when the directory cannot be walked (e.g. not created yet).
77
+ * A fjall keyspace is a directory of partition and journal files, so we sum
78
+ * them recursively.
79
+ */
80
+ sizeInBytes() {
81
+ try {
82
+ return dirSizeInBytes(this.dbPath);
83
+ }
84
+ catch {
85
+ return null;
86
+ }
87
+ }
88
+ /** Release this keyspace handle. Call persist() first when durability is needed. */
89
+ async close() {
90
+ await this.keyspace.close();
91
+ }
92
+ }
93
+ function dirSizeInBytes(dir) {
94
+ let total = 0;
95
+ for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
96
+ const full = path.join(dir, entry.name);
97
+ if (entry.isDirectory()) {
98
+ total += dirSizeInBytes(full);
99
+ }
100
+ else if (entry.isFile()) {
101
+ total += fs.statSync(full).size;
102
+ }
103
+ }
104
+ return total;
105
+ }
@@ -0,0 +1,31 @@
1
+ import type { HeaderHash, StateRootHash } from "#@typeberry/block";
2
+ import type { ChainSpec } from "#@typeberry/config";
3
+ import { type InitStatesDb, LeafDb, type StatesDb, StateUpdateError } from "#@typeberry/database";
4
+ import type { Blake2b } from "#@typeberry/hash";
5
+ import type { ServicesUpdate, State } from "#@typeberry/state";
6
+ import type { StateEntries } from "#@typeberry/state-merkleization";
7
+ import { SerializedState } from "#@typeberry/state-merkleization";
8
+ import { OK, Result } from "#@typeberry/utils";
9
+ import { type FjallRoot } from "./root.js";
10
+ /** fjall-backed full on-disk serialized state storage. */
11
+ export declare class FjallStates implements StatesDb<SerializedState<LeafDb>>, InitStatesDb<StateEntries> {
12
+ private readonly spec;
13
+ private readonly blake2b;
14
+ private readonly root;
15
+ private readonly states;
16
+ private readonly values;
17
+ static open(spec: ChainSpec, blake2b: Blake2b, root: FjallRoot): Promise<FjallStates>;
18
+ private readonly valuesDb;
19
+ private constructor();
20
+ insertInitialState(headerHash: HeaderHash, entries: StateEntries): Promise<Result<OK, StateUpdateError>>;
21
+ updateAndSetState(headerHash: HeaderHash, state: SerializedState<LeafDb>, update: Partial<State & ServicesUpdate>): Promise<Result<OK, StateUpdateError>>;
22
+ getStateRoot(state: SerializedState<LeafDb>): Promise<StateRootHash>;
23
+ getState(headerHash: HeaderHash): SerializedState<LeafDb> | null;
24
+ commitFinalized(_headers: HeaderHash[]): void;
25
+ markUnused(headerHash: HeaderHash): void;
26
+ diskSizeInBytes(): number | null;
27
+ close(): Promise<void>;
28
+ private updateAndCommit;
29
+ private readValue;
30
+ }
31
+ //# sourceMappingURL=states.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"states.d.ts","sourceRoot":"","sources":["../../../../../packages/jam/database-fjall/states.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,UAAU,EAAE,aAAa,EAAE,MAAM,kBAAkB,CAAC;AAGlE,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,mBAAmB,CAAC;AACnD,OAAO,EACL,KAAK,YAAY,EACjB,MAAM,EACN,KAAK,QAAQ,EACb,gBAAgB,EAGjB,MAAM,qBAAqB,CAAC;AAC7B,OAAO,KAAK,EAAE,OAAO,EAAiB,MAAM,iBAAiB,CAAC;AAE9D,OAAO,KAAK,EAAE,cAAc,EAAE,KAAK,EAAE,MAAM,kBAAkB,CAAC;AAC9D,OAAO,KAAK,EAAE,YAAY,EAAY,MAAM,gCAAgC,CAAC;AAC7E,OAAO,EAAE,eAAe,EAAgD,MAAM,gCAAgC,CAAC;AAE/G,OAAO,EAAE,EAAE,EAAE,MAAM,EAAkB,MAAM,kBAAkB,CAAC;AAC9D,OAAO,EAAuB,KAAK,SAAS,EAAgC,MAAM,WAAW,CAAC;AAI9F,0DAA0D;AAC1D,qBAAa,WAAY,YAAW,QAAQ,CAAC,eAAe,CAAC,MAAM,CAAC,CAAC,EAAE,YAAY,CAAC,YAAY,CAAC;IAS7F,OAAO,CAAC,QAAQ,CAAC,IAAI;IACrB,OAAO,CAAC,QAAQ,CAAC,OAAO;IACxB,OAAO,CAAC,QAAQ,CAAC,IAAI;IACrB,OAAO,CAAC,QAAQ,CAAC,MAAM;IACvB,OAAO,CAAC,QAAQ,CAAC,MAAM;WAZZ,IAAI,CAAC,IAAI,EAAE,SAAS,EAAE,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,SAAS,GAAG,OAAO,CAAC,WAAW,CAAC;IAK3F,OAAO,CAAC,QAAQ,CAAC,QAAQ,CAAW;IAEpC,OAAO;IAUD,kBAAkB,CAAC,UAAU,EAAE,UAAU,EAAE,OAAO,EAAE,YAAY,GAAG,OAAO,CAAC,MAAM,CAAC,EAAE,EAAE,gBAAgB,CAAC,CAAC;IAQxG,iBAAiB,CACrB,UAAU,EAAE,UAAU,EACtB,KAAK,EAAE,eAAe,CAAC,MAAM,CAAC,EAC9B,MAAM,EAAE,OAAO,CAAC,KAAK,GAAG,cAAc,CAAC,GACtC,OAAO,CAAC,MAAM,CAAC,EAAE,EAAE,gBAAgB,CAAC,CAAC;IAUlC,YAAY,CAAC,KAAK,EAAE,eAAe,CAAC,MAAM,CAAC,GAAG,OAAO,CAAC,aAAa,CAAC;IAI1E,QAAQ,CAAC,UAAU,EAAE,UAAU,GAAG,eAAe,CAAC,MAAM,CAAC,GAAG,IAAI;IAahE,eAAe,CAAC,QAAQ,EAAE,UAAU,EAAE,GAAG,IAAI;IAK7C,UAAU,CAAC,UAAU,EAAE,UAAU,GAAG,IAAI;IAMxC,eAAe,IAAI,MAAM,GAAG,IAAI;IAI1B,KAAK;YAEG,eAAe;IAyB7B,OAAO,CAAC,SAAS;CAOlB"}
@@ -0,0 +1,99 @@
1
+ import { BytesBlob } from "#@typeberry/bytes";
2
+ import { SortedSet } from "#@typeberry/collections";
3
+ import { LeafDb, StateUpdateError, updateLeafs, } from "#@typeberry/database";
4
+ import { Logger } from "#@typeberry/logger";
5
+ import { SerializedState, StateEntryUpdateAction, serializeStateUpdate } from "#@typeberry/state-merkleization";
6
+ import { leafComparator } from "#@typeberry/trie";
7
+ import { OK, Result, resultToString } from "#@typeberry/utils";
8
+ import { toUint8Array } from "./root.js";
9
+ const logger = Logger.new(import.meta.filename, "db");
10
+ /** fjall-backed full on-disk serialized state storage. */
11
+ export class FjallStates {
12
+ spec;
13
+ blake2b;
14
+ root;
15
+ states;
16
+ values;
17
+ static async open(spec, blake2b, root) {
18
+ const [states, values] = await Promise.all([root.partition("states"), root.partition("values")]);
19
+ return new FjallStates(spec, blake2b, root, states, values);
20
+ }
21
+ valuesDb;
22
+ constructor(spec, blake2b, root, states, values) {
23
+ this.spec = spec;
24
+ this.blake2b = blake2b;
25
+ this.root = root;
26
+ this.states = states;
27
+ this.values = values;
28
+ this.valuesDb = { get: (key) => this.readValue(key) };
29
+ }
30
+ async insertInitialState(headerHash, entries) {
31
+ return await this.updateAndCommit(headerHash, SortedSet.fromArray(leafComparator, []), Array.from(entries, (x) => [StateEntryUpdateAction.Insert, x[0], x[1]]));
32
+ }
33
+ async updateAndSetState(headerHash, state, update) {
34
+ const updatedValues = serializeStateUpdate(this.spec, this.blake2b, update);
35
+ const newLeafs = SortedSet.fromSortedArray(leafComparator, state.backend.leafs.array);
36
+ const res = await this.updateAndCommit(headerHash, newLeafs, updatedValues);
37
+ if (res.isOk) {
38
+ state.updateBackend(LeafDb.fromLeaves(newLeafs, this.valuesDb));
39
+ }
40
+ return res;
41
+ }
42
+ async getStateRoot(state) {
43
+ return state.backend.getStateRoot(this.blake2b);
44
+ }
45
+ getState(headerHash) {
46
+ const leafNodes = toUint8Array(this.states.get(headerHash.raw));
47
+ if (leafNodes === null) {
48
+ return null;
49
+ }
50
+ const leafDbResult = LeafDb.fromLeavesBlob(BytesBlob.blobFrom(leafNodes), this.valuesDb);
51
+ if (leafDbResult.isError) {
52
+ throw new Error(`Inconsistent DB. Invalid leaf nodes for ${headerHash}: ${resultToString(leafDbResult)}`);
53
+ }
54
+ return SerializedState.new(this.spec, this.blake2b, leafDbResult.ok);
55
+ }
56
+ commitFinalized(_headers) {
57
+ // Values are never pruned here. This db survives restarts, so refcounting
58
+ // would need counts persisted (and crash-consistent) alongside the values.
59
+ }
60
+ markUnused(headerHash) {
61
+ void writable(this.states, this.root)
62
+ .remove(headerHash.raw)
63
+ .catch((e) => logger.warn `Failed to prune state ${headerHash}: ${e}`);
64
+ }
65
+ diskSizeInBytes() {
66
+ return this.root.sizeInBytes();
67
+ }
68
+ async close() { }
69
+ async updateAndCommit(headerHash, leafs, data) {
70
+ const { values } = updateLeafs(leafs, this.blake2b, data);
71
+ const stateLeafs = BytesBlob.blobFromParts(leafs.array.map((x) => x.node.raw));
72
+ try {
73
+ // Preserve dependency order: values first, then leaves that may reference them.
74
+ if (values.length > 0) {
75
+ await writable(this.values, this.root).insertBatch(values.map(([hash, val]) => ({ key: hash.raw, value: val.raw })));
76
+ }
77
+ await writable(this.states, this.root).insert(headerHash.raw, stateLeafs.raw);
78
+ await this.root.persist();
79
+ }
80
+ catch (e) {
81
+ logger.error `${e}`;
82
+ return Result.error(StateUpdateError.Commit, () => `Failed to commit state update: ${e}`);
83
+ }
84
+ return Result.ok(OK);
85
+ }
86
+ readValue(key) {
87
+ const val = toUint8Array(this.values.get(key.raw));
88
+ if (val === null) {
89
+ throw new Error(`Missing required value: ${key} in the DB`);
90
+ }
91
+ return val;
92
+ }
93
+ }
94
+ function writable(partition, root) {
95
+ if (root.readOnly) {
96
+ throw new Error("Cannot write through a read-only fjall partition.");
97
+ }
98
+ return partition;
99
+ }
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=states.test.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"states.test.d.ts","sourceRoot":"","sources":["../../../../../packages/jam/database-fjall/states.test.ts"],"names":[],"mappings":""}