@fangorn-network/sdk 0.1.4 → 0.1.6
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/lib/cli/cli.js +21 -1
- package/lib/cli/sell.js +1 -1
- package/lib/config.d.ts +153 -153
- package/lib/contracts/data-registry/abi.d.ts +13 -1
- package/lib/contracts/data-registry/abi.js +16 -1
- package/lib/contracts/data-registry/index.d.ts +18 -0
- package/lib/contracts/data-registry/index.js +22 -2
- package/lib/contracts/data-registry/mmr.d.ts +23 -0
- package/lib/contracts/data-registry/mmr.js +65 -0
- package/lib/contracts/index.d.ts +2 -1
- package/lib/contracts/index.js +2 -1
- package/lib/contracts/settlement-registry/abi.d.ts +1 -1
- package/lib/contracts/settlement-registry/abi.js +1 -1
- package/lib/contracts/write.d.ts +13 -4
- package/lib/contracts/write.js +18 -8
- package/lib/engine/index.d.ts +99 -17
- package/lib/engine/index.js +279 -40
- package/lib/engine/records.d.ts +28 -12
- package/lib/engine/records.js +1 -0
- package/lib/engine/test-helpers.d.ts +2 -0
- package/lib/engine/test-helpers.js +7 -0
- package/lib/erc8004.js +2 -1
- package/lib/fangorn.d.ts +39 -3
- package/lib/fangorn.js +76 -8
- package/lib/index.d.ts +5 -2
- package/lib/index.js +3 -2
- package/lib/test/mem-registry.d.ts +12 -2
- package/lib/test/mem-registry.js +15 -0
- package/lib/test/testbed.d.ts +5222 -5222
- package/lib/test/testbed.js +1 -1
- package/package.json +1 -4
package/lib/engine/index.js
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { assertBlockMatches, assertValidRecordId, buildMst, decodeBlock, diffMst, encodeBlock, lookupMst, readMst } from "./records.js";
|
|
2
2
|
import { packCar, readCar } from "./car.js";
|
|
3
3
|
import { ZERO_HEAD } from "../contracts/data-registry/index.js";
|
|
4
|
+
import { EMPTY_MMR, logLeaf, mmrAppend, mmrRoot } from "../contracts/data-registry/mmr.js";
|
|
4
5
|
import "../contracts/index.js";
|
|
5
6
|
import { bytesToHex, hexToBytes } from "viem";
|
|
6
7
|
import { CID } from "multiformats/cid";
|
|
@@ -17,27 +18,40 @@ const ZERO_BYTES32 = ZERO_HEAD;
|
|
|
17
18
|
*/
|
|
18
19
|
const MAX_REPO_NAME_LENGTH = 256;
|
|
19
20
|
/**
|
|
21
|
+
* Every this many positions, a commit's CAR holds the whole state (see `checkpoint`), so a
|
|
22
|
+
* cold read walks back at most this many CARs (~2 fetches each: under Workers' 1000 subrequests).
|
|
23
|
+
*/
|
|
24
|
+
const CHECKPOINT_EVERY = 100;
|
|
25
|
+
/**
|
|
20
26
|
* The root of the graph, committed to IPFS, as hex
|
|
21
27
|
*/
|
|
22
28
|
function rootHexFromCid(commitCid) {
|
|
23
29
|
return bytesToHex(commitCid.multihash.digest);
|
|
24
30
|
}
|
|
31
|
+
/** A repo's key in a stitch across repos. */
|
|
32
|
+
const stitchKey = (publisher, repo) => `${publisher.toLowerCase()}/${repo}`;
|
|
33
|
+
function cidFromDigest(digest) {
|
|
34
|
+
return CID.createV1(dagCbor.code, Digest.create(sha256.code, hexToBytes(digest)));
|
|
35
|
+
}
|
|
25
36
|
/** The update that settles `commit`. */
|
|
26
37
|
function commitUpdate(commit) {
|
|
38
|
+
if (!commit.diff) throw new Error("commit has no diff: it is not in the current commit format — rebuild it");
|
|
27
39
|
return {
|
|
28
40
|
repo: commit.repo,
|
|
29
41
|
epoch: commit.epoch,
|
|
30
42
|
parent: commit.parent ? rootHexFromCid(commit.parent) : ZERO_HEAD,
|
|
43
|
+
diff: rootHexFromCid(commit.diff),
|
|
31
44
|
root: rootHexFromCid(commit.root),
|
|
32
45
|
car: bytesToHex(commit.car.bytes)
|
|
33
46
|
};
|
|
34
47
|
}
|
|
35
48
|
/** The head the registry computes for `u`. */
|
|
36
49
|
async function commitHead(u) {
|
|
37
|
-
const link =
|
|
50
|
+
const link = cidFromDigest;
|
|
38
51
|
return rootHexFromCid((await encodeBlock({
|
|
39
52
|
epoch: u.epoch,
|
|
40
53
|
parent: u.parent === ZERO_HEAD ? null : link(u.parent),
|
|
54
|
+
diff: link(u.diff),
|
|
41
55
|
root: link(u.root),
|
|
42
56
|
repo: u.repo,
|
|
43
57
|
car: CID.decode(hexToBytes(u.car))
|
|
@@ -93,34 +107,50 @@ var FangornEngine = class {
|
|
|
93
107
|
/** Read and decode a commit object by CID (directly addressable — no CAR needed). */
|
|
94
108
|
async getCommit(commitCid) {
|
|
95
109
|
const key = commitCid.toString();
|
|
96
|
-
|
|
97
|
-
if (!bytes) {
|
|
98
|
-
bytes = await this.storage.getRawBlock(key);
|
|
99
|
-
assertBlockMatches(commitCid, bytes);
|
|
100
|
-
this.cache.set(key, bytes);
|
|
101
|
-
}
|
|
102
|
-
const decoded = decodeBlock(bytes);
|
|
110
|
+
const decoded = decodeBlock(await this.directBlock(commitCid));
|
|
103
111
|
if (typeof decoded.epoch !== "number" || typeof decoded.repo !== "string") throw new Error(`commit ${key} predates the (e, parent, root) commit format. Reset the on-chain head (\`fangorn reset\`) and re-publish.`);
|
|
104
112
|
return {
|
|
105
113
|
epoch: decoded.epoch,
|
|
106
114
|
parent: decoded.parent ? CID.parse(String(decoded.parent)) : null,
|
|
115
|
+
diff: decoded.diff ? CID.parse(String(decoded.diff)) : null,
|
|
107
116
|
root: CID.parse(String(decoded.root)),
|
|
108
117
|
repo: decoded.repo,
|
|
109
118
|
car: CID.parse(String(decoded.car))
|
|
110
119
|
};
|
|
111
120
|
}
|
|
112
|
-
/**
|
|
113
|
-
async
|
|
114
|
-
const
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
121
|
+
/** A block stored on its own (a commit or stitch block), hash-checked and cached. */
|
|
122
|
+
async directBlock(cid) {
|
|
123
|
+
const key = cid.toString();
|
|
124
|
+
let bytes = this.cache.get(key);
|
|
125
|
+
if (!bytes) {
|
|
126
|
+
bytes = await this.storage.getRawBlock(key);
|
|
127
|
+
assertBlockMatches(cid, bytes);
|
|
128
|
+
this.cache.set(key, bytes);
|
|
129
|
+
}
|
|
130
|
+
return bytes;
|
|
131
|
+
}
|
|
132
|
+
/** The packfile and parent of a link in a chain: a commit, or a stitch. */
|
|
133
|
+
async chainLink(cid) {
|
|
134
|
+
const b = decodeBlock(await this.directBlock(cid));
|
|
135
|
+
return {
|
|
136
|
+
car: b.car ?? null,
|
|
137
|
+
parent: b.parent ?? null
|
|
138
|
+
};
|
|
139
|
+
}
|
|
140
|
+
/** Pull every block of a chain link's CAR into the local cache. */
|
|
141
|
+
async loadCar(linkCid, car) {
|
|
142
|
+
if (car) {
|
|
143
|
+
const bytes = await this.storage.getFile(car.toString());
|
|
144
|
+
for (const block of await readCar(bytes, { verify: false })) {
|
|
145
|
+
const key = block.cid.toString();
|
|
146
|
+
if (!this.cache.has(key)) this.unverified.set(key, block.bytes);
|
|
147
|
+
}
|
|
118
148
|
}
|
|
119
|
-
this.loadedCars.add(
|
|
149
|
+
this.loadedCars.add(linkCid.toString());
|
|
120
150
|
}
|
|
121
151
|
/**
|
|
122
|
-
* Resolve a data block: local cache first, then walk the
|
|
123
|
-
* `hint`, loading one ancestor CAR at a time until the block turns up.
|
|
152
|
+
* Resolve a data block: local cache first, then walk the chain (commits, or
|
|
153
|
+
* stitches) from `hint`, loading one ancestor CAR at a time until the block turns up.
|
|
124
154
|
*/
|
|
125
155
|
async getBlock(cid, hint) {
|
|
126
156
|
const key = cid.toString();
|
|
@@ -138,13 +168,13 @@ var FangornEngine = class {
|
|
|
138
168
|
if (hit) return hit;
|
|
139
169
|
let cursor = hint;
|
|
140
170
|
while (cursor) {
|
|
141
|
-
const
|
|
171
|
+
const link = await this.chainLink(cursor);
|
|
142
172
|
if (!this.loadedCars.has(cursor.toString())) {
|
|
143
|
-
await this.loadCar(cursor,
|
|
173
|
+
await this.loadCar(cursor, link.car);
|
|
144
174
|
const found = local();
|
|
145
175
|
if (found) return found;
|
|
146
176
|
}
|
|
147
|
-
cursor =
|
|
177
|
+
cursor = link.parent;
|
|
148
178
|
}
|
|
149
179
|
throw new Error(`Block payload missing for key: ${key}`);
|
|
150
180
|
}
|
|
@@ -205,16 +235,35 @@ var FangornEngine = class {
|
|
|
205
235
|
});
|
|
206
236
|
state.set(id, block.cid);
|
|
207
237
|
recordCids[id] = block.cid.toString();
|
|
208
|
-
if (!oldRecordCids.has(block.cid.toString())) carBlocks.push(block);
|
|
238
|
+
if (opts.checkpoint || !oldRecordCids.has(block.cid.toString())) carBlocks.push(block);
|
|
239
|
+
}
|
|
240
|
+
if (opts.checkpoint) {
|
|
241
|
+
const staged = new Set(Object.values(recordCids));
|
|
242
|
+
for (const cid of state.values()) if (!staged.has(cid.toString())) carBlocks.push({
|
|
243
|
+
cid,
|
|
244
|
+
bytes: await this.getBlock(cid, base)
|
|
245
|
+
});
|
|
209
246
|
}
|
|
210
247
|
const mst = await buildMst(state);
|
|
211
|
-
|
|
248
|
+
const delta = /* @__PURE__ */ new Map();
|
|
249
|
+
for (const [id, cid] of state) if (!old.state.get(id)?.equals(cid)) delta.set(id, cid);
|
|
250
|
+
for (const id of old.state.keys()) if (!state.has(id)) delta.set(id, null);
|
|
251
|
+
const diff = await buildMst(delta);
|
|
252
|
+
const fresh = /* @__PURE__ */ new Set();
|
|
253
|
+
for (const node of [...mst.nodes, ...diff.nodes]) {
|
|
254
|
+
const key = node.cid.toString();
|
|
255
|
+
if ((opts.checkpoint || !old.nodeCids.has(key)) && !fresh.has(key)) {
|
|
256
|
+
fresh.add(key);
|
|
257
|
+
carBlocks.push(node);
|
|
258
|
+
}
|
|
259
|
+
}
|
|
212
260
|
for (const block of carBlocks) this.putLocal(block);
|
|
213
261
|
const carBytes = await packCar(mst.root, carBlocks);
|
|
214
262
|
const car = fileCid(await this.storage.putFile(carBytes, `${mst.root.toString()}.car`));
|
|
215
263
|
const commitBlock = await encodeBlock({
|
|
216
264
|
epoch: await this.registry.epoch(),
|
|
217
265
|
parent: base,
|
|
266
|
+
diff: diff.root,
|
|
218
267
|
root: mst.root,
|
|
219
268
|
repo,
|
|
220
269
|
car
|
|
@@ -295,20 +344,58 @@ var FangornEngine = class {
|
|
|
295
344
|
payload: r.payload
|
|
296
345
|
};
|
|
297
346
|
}
|
|
347
|
+
/** The diff an event carries: id → new record CID, or null where the record was deleted. */
|
|
348
|
+
async eventDiff(commitCid) {
|
|
349
|
+
const { diff } = await this.getCommit(commitCid);
|
|
350
|
+
if (!diff) throw new Error(`commit ${commitCid.toString()} predates diff events`);
|
|
351
|
+
return (await readMst(diff, (cid) => this.getBlock(cid, commitCid))).state;
|
|
352
|
+
}
|
|
353
|
+
/**
|
|
354
|
+
* The events after `old` up to `tip`, composed into one id → CID | null map, newest write
|
|
355
|
+
* winning. Null when `old` is not an ancestor of `tip`, or an event between them has no diff.
|
|
356
|
+
*/
|
|
357
|
+
async eventsSince(old, tip) {
|
|
358
|
+
const path = [];
|
|
359
|
+
for await (const { cid, commit } of this.walkParents(tip)) {
|
|
360
|
+
if (cid.equals(old)) break;
|
|
361
|
+
if (!commit.diff || !commit.parent) return null;
|
|
362
|
+
path.push(cid);
|
|
363
|
+
}
|
|
364
|
+
const net = /* @__PURE__ */ new Map();
|
|
365
|
+
for (const cid of path) for (const [id, v] of await this.eventDiff(cid)) if (!net.has(id)) net.set(id, v);
|
|
366
|
+
return net;
|
|
367
|
+
}
|
|
298
368
|
/**
|
|
299
369
|
* Net change to a single repo between two on-chain roots — the core of
|
|
300
|
-
* the subscription light-client.
|
|
301
|
-
* maps; only records that actually changed are decoded.
|
|
370
|
+
* the subscription light-client. Only records that actually changed are decoded.
|
|
302
371
|
*
|
|
303
|
-
*
|
|
304
|
-
*
|
|
305
|
-
*
|
|
306
|
-
*
|
|
307
|
-
* 50k-record repo cost ~10 × depth nodes, not two 50k-key walks.
|
|
372
|
+
* When `old` is an ancestor of `new`, this reads the diffs the events carry (WHITEPAPER_1 §3.3,
|
|
373
|
+
* Following) and looks each changed id up in the old tree. Otherwise, across a reset to another
|
|
374
|
+
* chain or a commit from before diff events, it diffs the two trees (`diffMst`). Either way the
|
|
375
|
+
* result is the net delta an index builder needs: what to (re)embed, what to evict.
|
|
308
376
|
*/
|
|
309
377
|
async repoDiff(oldRootHex, newRootHex) {
|
|
310
378
|
const newCommit = newRootHex === ZERO_BYTES32 ? null : this.hexToRootCid(newRootHex);
|
|
311
379
|
const oldCommit = oldRootHex && oldRootHex !== ZERO_BYTES32 ? this.hexToRootCid(oldRootHex) : null;
|
|
380
|
+
const events = oldCommit && newCommit ? await this.eventsSince(oldCommit, newCommit) : null;
|
|
381
|
+
if (oldCommit && newCommit && events) {
|
|
382
|
+
const oldRoot = (await this.getCommit(oldCommit)).root;
|
|
383
|
+
const puts$1 = [];
|
|
384
|
+
const deletes = [];
|
|
385
|
+
const superseded = [];
|
|
386
|
+
for (const [id, after] of events) {
|
|
387
|
+
const before = await lookupMst(oldRoot, id, (cid) => this.getBlock(cid, oldCommit));
|
|
388
|
+
if (before && after && before.equals(after)) continue;
|
|
389
|
+
if (before) superseded.push(before.toString());
|
|
390
|
+
if (after) puts$1.push(await this.decodeRecord(id, after, newCommit));
|
|
391
|
+
else if (before) deletes.push(id);
|
|
392
|
+
}
|
|
393
|
+
return {
|
|
394
|
+
puts: puts$1,
|
|
395
|
+
deletes,
|
|
396
|
+
superseded
|
|
397
|
+
};
|
|
398
|
+
}
|
|
312
399
|
const root = async (c) => c ? (await this.getCommit(c)).root : null;
|
|
313
400
|
const diff = await diffMst(await root(oldCommit), await root(newCommit), (cid) => this.getBlock(cid, oldCommit), (cid) => this.getBlock(cid, newCommit));
|
|
314
401
|
const puts = [];
|
|
@@ -319,21 +406,29 @@ var FangornEngine = class {
|
|
|
319
406
|
superseded: [...diff.before.values()].map(String)
|
|
320
407
|
};
|
|
321
408
|
}
|
|
322
|
-
/** Diff a commit against its parent. */
|
|
409
|
+
/** Diff a commit against its parent: its event's diff, or two full states for an older commit. */
|
|
323
410
|
async diffCommit(commitCid) {
|
|
324
411
|
const commit = await this.getCommit(commitCid);
|
|
325
412
|
const ns = commit.repo;
|
|
326
|
-
const child = (await this.stateAt(commitCid)).state;
|
|
327
|
-
const par = commit.parent ? (await this.stateAt(commit.parent)).state : /* @__PURE__ */ new Map();
|
|
328
413
|
const added = [];
|
|
329
414
|
const updated = [];
|
|
330
415
|
const removed = [];
|
|
331
|
-
|
|
332
|
-
const
|
|
333
|
-
|
|
334
|
-
|
|
416
|
+
if (commit.diff) {
|
|
417
|
+
const parent = commit.parent;
|
|
418
|
+
const parentRoot = parent ? (await this.getCommit(parent)).root : null;
|
|
419
|
+
for (const [id, cid] of await this.eventDiff(commitCid)) if (!cid) removed.push(`${ns}/${id}`);
|
|
420
|
+
else if (parent && parentRoot && await lookupMst(parentRoot, id, (c) => this.getBlock(c, parent))) updated.push(`${ns}/${id}`);
|
|
421
|
+
else added.push(`${ns}/${id}`);
|
|
422
|
+
} else {
|
|
423
|
+
const child = (await this.stateAt(commitCid)).state;
|
|
424
|
+
const par = commit.parent ? (await this.stateAt(commit.parent)).state : /* @__PURE__ */ new Map();
|
|
425
|
+
for (const [id, cid] of child) {
|
|
426
|
+
const prev = par.get(id);
|
|
427
|
+
if (!prev) added.push(`${ns}/${id}`);
|
|
428
|
+
else if (!prev.equals(cid)) updated.push(`${ns}/${id}`);
|
|
429
|
+
}
|
|
430
|
+
for (const id of par.keys()) if (!child.has(id)) removed.push(`${ns}/${id}`);
|
|
335
431
|
}
|
|
336
|
-
for (const id of par.keys()) if (!child.has(id)) removed.push(`${ns}/${id}`);
|
|
337
432
|
return {
|
|
338
433
|
parent: commit.parent?.toString() ?? null,
|
|
339
434
|
epoch: commit.epoch,
|
|
@@ -344,6 +439,150 @@ var FangornEngine = class {
|
|
|
344
439
|
removed: removed.sort()
|
|
345
440
|
};
|
|
346
441
|
}
|
|
442
|
+
/** A stitch to the current head of (publisher, repo), at `key` if given. One `getHead` read, no logs. */
|
|
443
|
+
async stitchTo(publisher, repo, key) {
|
|
444
|
+
const { pos, head } = await this.registry.headAt({
|
|
445
|
+
publisher,
|
|
446
|
+
repo
|
|
447
|
+
});
|
|
448
|
+
if (pos === 0) throw new Error(`${publisher} has no head in repo ${repo}`);
|
|
449
|
+
return {
|
|
450
|
+
publisher,
|
|
451
|
+
repo,
|
|
452
|
+
pos,
|
|
453
|
+
head,
|
|
454
|
+
...key === void 0 ? {} : { key }
|
|
455
|
+
};
|
|
456
|
+
}
|
|
457
|
+
/**
|
|
458
|
+
* A stitch across repos: an MST of `publisher/repo` → head commit, folded from the
|
|
459
|
+
* update log up to entry n and tagged with the log's root there. Pass the previous
|
|
460
|
+
* stitch to read only the log since it, and upload only the nodes it doesn't have
|
|
461
|
+
* (one CAR). Returns the stitch block's CID, its name; with nothing new, `prev`.
|
|
462
|
+
* Use the same `filter` every time for one stitch. `fromBlock` is where the log
|
|
463
|
+
* starts (the registry's deploy block).
|
|
464
|
+
* ponytail: rehashes the whole tree (O(repos)); and readers walk back one CAR per
|
|
465
|
+
* stitch to find old nodes, so checkpoint with a full CAR (`prev = null`) when the
|
|
466
|
+
* chain gets long.
|
|
467
|
+
*/
|
|
468
|
+
async restitch(prev, filter, fromBlock = 0n) {
|
|
469
|
+
const base = prev ? await this.readStitch(prev) : null;
|
|
470
|
+
const to = await this.registry.clock();
|
|
471
|
+
const entries = await this.registry.log({}, base ? base.t + 1n : fromBlock, to);
|
|
472
|
+
if (prev && entries.length === 0) return prev;
|
|
473
|
+
const old = base && prev ? await readMst(base.root, (c) => this.getBlock(c, prev)) : {
|
|
474
|
+
state: /* @__PURE__ */ new Map(),
|
|
475
|
+
nodeCids: /* @__PURE__ */ new Set()
|
|
476
|
+
};
|
|
477
|
+
const state = new Map(old.state);
|
|
478
|
+
let mmr = base ?? EMPTY_MMR;
|
|
479
|
+
for (const e of entries) {
|
|
480
|
+
mmr = mmrAppend(mmr, logLeaf(e));
|
|
481
|
+
if (!filter || filter(e.publisher, e.repo)) state.set(stitchKey(e.publisher, e.repo), this.hexToRootCid(e.head));
|
|
482
|
+
}
|
|
483
|
+
const { root, nodes } = await buildMst(state);
|
|
484
|
+
const fresh = /* @__PURE__ */ new Map();
|
|
485
|
+
for (const n of nodes) if (!old.nodeCids.has(n.cid.toString())) fresh.set(n.cid.toString(), n);
|
|
486
|
+
for (const n of fresh.values()) this.putLocal(n);
|
|
487
|
+
const block = await encodeBlock({
|
|
488
|
+
parent: prev,
|
|
489
|
+
root,
|
|
490
|
+
car: fresh.size ? fileCid(await this.storage.putFile(await packCar(root, fresh.values()), `${root.toString()}.car`)) : null,
|
|
491
|
+
n: mmr.n,
|
|
492
|
+
t: Number(to),
|
|
493
|
+
peaks: mmr.peaks
|
|
494
|
+
});
|
|
495
|
+
await this.storage.putBlock(block);
|
|
496
|
+
this.putLocal(block);
|
|
497
|
+
this.loadedCars.add(block.cid.toString());
|
|
498
|
+
return block.cid;
|
|
499
|
+
}
|
|
500
|
+
/** A stitch block: its tree root, and the log it was folded from (n entries, root `logRoot`). */
|
|
501
|
+
async readStitch(stitch) {
|
|
502
|
+
const b = decodeBlock(await this.directBlock(stitch));
|
|
503
|
+
const mmr = {
|
|
504
|
+
n: b.n,
|
|
505
|
+
peaks: b.peaks
|
|
506
|
+
};
|
|
507
|
+
return {
|
|
508
|
+
root: CID.parse(String(b.root)),
|
|
509
|
+
...mmr,
|
|
510
|
+
t: BigInt(b.t),
|
|
511
|
+
logRoot: mmrRoot(mmr)
|
|
512
|
+
};
|
|
513
|
+
}
|
|
514
|
+
/**
|
|
515
|
+
* The head commit a stitch holds for (publisher, repo), or null if it doesn't
|
|
516
|
+
* include the repo. Every node read is hash-checked.
|
|
517
|
+
* ponytail: like `lookupMst`, trusts key order on the path; `readMst` proves absence.
|
|
518
|
+
*/
|
|
519
|
+
async stitchedHead(stitch, publisher, repo) {
|
|
520
|
+
const { root } = await this.readStitch(stitch);
|
|
521
|
+
return lookupMst(root, stitchKey(publisher, repo), (c) => this.getBlock(c, stitch));
|
|
522
|
+
}
|
|
523
|
+
/** Every (publisher, repo) → head commit a stitch holds: what an indexer follows. */
|
|
524
|
+
async stitchHeads(stitch) {
|
|
525
|
+
const { root } = await this.readStitch(stitch);
|
|
526
|
+
const { state } = await readMst(root, (c) => this.getBlock(c, stitch));
|
|
527
|
+
return [...state].map(([k, head]) => ({
|
|
528
|
+
publisher: k.slice(0, 42),
|
|
529
|
+
repo: k.slice(43),
|
|
530
|
+
head
|
|
531
|
+
}));
|
|
532
|
+
}
|
|
533
|
+
/**
|
|
534
|
+
* Check a stitch without trusting whoever built it: replay the whole log, check it
|
|
535
|
+
* against the contract's log root, and rebuild the stitch from its first n entries
|
|
536
|
+
* under the same `filter`. Reads no stitch nodes, only the stitch block.
|
|
537
|
+
* ponytail: O(log) per check; store log roots on chain if that gets slow.
|
|
538
|
+
*/
|
|
539
|
+
async verifyStitch(stitch, filter, fromBlock = 0n) {
|
|
540
|
+
const s = await this.readStitch(stitch);
|
|
541
|
+
const to = await this.registry.clock();
|
|
542
|
+
const entries = await this.registry.log({}, fromBlock, to);
|
|
543
|
+
if (entries.length < s.n) return false;
|
|
544
|
+
let mmr = EMPTY_MMR;
|
|
545
|
+
const state = /* @__PURE__ */ new Map();
|
|
546
|
+
for (const [i, e] of entries.entries()) {
|
|
547
|
+
mmr = mmrAppend(mmr, logLeaf(e));
|
|
548
|
+
if (i >= s.n) continue;
|
|
549
|
+
if (!filter || filter(e.publisher, e.repo)) state.set(stitchKey(e.publisher, e.repo), this.hexToRootCid(e.head));
|
|
550
|
+
if (i === s.n - 1 && mmrRoot(mmr) !== s.logRoot) return false;
|
|
551
|
+
}
|
|
552
|
+
if (s.n === 0 && s.logRoot !== mmrRoot(EMPTY_MMR)) return false;
|
|
553
|
+
if (mmrRoot(mmr) !== await this.registry.logRoot(to)) return false;
|
|
554
|
+
return (await buildMst(state)).root.equals(s.root);
|
|
555
|
+
}
|
|
556
|
+
/**
|
|
557
|
+
* Check a stitch against the registry (WHITEPAPER_1 Proposition 4.2) and resolve it:
|
|
558
|
+
* the record at its key as of that position (null if absent), or, with no key, the event's diff.
|
|
559
|
+
* Throws if the repo never had `head` at `pos`. `latest` says whether the repo has moved on.
|
|
560
|
+
* A stitch at the current generation is checked with one `getHead` read.
|
|
561
|
+
* ponytail: an older stitch still scans the log from `fromBlock` (and trusts the RPC).
|
|
562
|
+
* Upgrade: walk parents back from the on-chain head, recomputing `commitHead` each hop
|
|
563
|
+
* (O(distance), no logs), or an MMR opening against `logRoot()` (O(log n), needs a proof server).
|
|
564
|
+
*/
|
|
565
|
+
async checkStitch(s, fromBlock = 0n) {
|
|
566
|
+
const ref = {
|
|
567
|
+
publisher: s.publisher,
|
|
568
|
+
repo: s.repo
|
|
569
|
+
};
|
|
570
|
+
const cur = await this.registry.headAt(ref);
|
|
571
|
+
if (s.pos < 1 || s.pos > cur.pos) throw new Error(`no position ${s.pos.toString()} in ${s.publisher}/${s.repo}`);
|
|
572
|
+
const latest = s.pos === cur.pos;
|
|
573
|
+
const had = latest ? cur.head : (await this.registry.log(ref, fromBlock)).find((e) => e.pos === s.pos)?.head;
|
|
574
|
+
if (had?.toLowerCase() !== s.head.toLowerCase()) throw new Error(`false stitch: ${s.publisher}/${s.repo} had ${had ?? "nothing"} at position ${s.pos.toString()}, not ${s.head}`);
|
|
575
|
+
const commit = this.hexToRootCid(s.head);
|
|
576
|
+
if (s.key === void 0) return {
|
|
577
|
+
latest,
|
|
578
|
+
diff: await this.eventDiff(commit)
|
|
579
|
+
};
|
|
580
|
+
const cid = await lookupMst((await this.getCommit(commit)).root, s.key, (c) => this.getBlock(c, commit));
|
|
581
|
+
return {
|
|
582
|
+
latest,
|
|
583
|
+
record: cid ? await this.decodeRecord(s.key, cid, commit) : null
|
|
584
|
+
};
|
|
585
|
+
}
|
|
347
586
|
/** check if the repo already exists (head resolves) */
|
|
348
587
|
async repoExists(publisher, repo) {
|
|
349
588
|
return await this.resolveHeadCommit(publisher, repo) !== null;
|
|
@@ -362,11 +601,11 @@ var FangornEngine = class {
|
|
|
362
601
|
}
|
|
363
602
|
/**
|
|
364
603
|
* Fetch the current version of one record by id — one MST path from the
|
|
365
|
-
* on-chain root, then the record block. Null if the repo has no such id.
|
|
604
|
+
* on-chain root, then the record block. Null if the repo has no such id, or no commits.
|
|
366
605
|
*/
|
|
367
606
|
async readRecord(publisher, repo, id) {
|
|
368
607
|
const head = await this.resolveHeadCommit(publisher, repo);
|
|
369
|
-
if (!head)
|
|
608
|
+
if (!head) return null;
|
|
370
609
|
const get = (cid$1) => this.getBlock(cid$1, head);
|
|
371
610
|
const cid = await lookupMst((await this.getCommit(head)).root, id, get);
|
|
372
611
|
return cid ? this.decodeRecord(id, cid, head) : null;
|
|
@@ -374,4 +613,4 @@ var FangornEngine = class {
|
|
|
374
613
|
};
|
|
375
614
|
|
|
376
615
|
//#endregion
|
|
377
|
-
export { FangornEngine, MAX_REPO_NAME_LENGTH, assertValidRepoName, commitHead, commitUpdate, fileCid, rootHexFromCid };
|
|
616
|
+
export { CHECKPOINT_EVERY, FangornEngine, MAX_REPO_NAME_LENGTH, assertValidRepoName, cidFromDigest, commitHead, commitUpdate, fileCid, rootHexFromCid };
|
package/lib/engine/records.d.ts
CHANGED
|
@@ -22,20 +22,34 @@ interface RecordBlock {
|
|
|
22
22
|
payload: Record<string, unknown>;
|
|
23
23
|
}
|
|
24
24
|
/**
|
|
25
|
-
* A
|
|
26
|
-
*
|
|
27
|
-
*
|
|
28
|
-
|
|
29
|
-
|
|
25
|
+
* A stitch (WHITEPAPER_1 §4): the event `head` at position `pos` of repo
|
|
26
|
+
* (publisher, repo). With `key`, it names the record at that key in the event's
|
|
27
|
+
* state; without, the event itself (its diff). Checked by `checkStitch`.
|
|
28
|
+
*/
|
|
29
|
+
interface Stitch {
|
|
30
|
+
publisher: `0x${string}`;
|
|
31
|
+
repo: string;
|
|
32
|
+
pos: number;
|
|
33
|
+
head: `0x${string}`;
|
|
34
|
+
key?: string;
|
|
35
|
+
}
|
|
36
|
+
/**
|
|
37
|
+
* A reference from one record to another, stored as a plain payload value.
|
|
38
|
+
* `local`: a record id in the same repo state, follows updates. `pinned`: one
|
|
39
|
+
* exact record version, by CID. `stitch`: an event or record of any repo, at a
|
|
40
|
+
* position the registry's log can check.
|
|
30
41
|
*/
|
|
31
42
|
type Ref = {
|
|
32
43
|
local: string;
|
|
33
44
|
} | {
|
|
34
45
|
pinned: string;
|
|
46
|
+
} | {
|
|
47
|
+
stitch: Stitch;
|
|
35
48
|
};
|
|
36
49
|
/**
|
|
37
|
-
* Commit block:
|
|
38
|
-
* on-chain head. `root` is the repo's MST root.
|
|
50
|
+
* Commit block: the event (e, parent, diff, root) of WHITEPAPER_1 §2, whose
|
|
51
|
+
* name is the on-chain head. `root` is the repo's MST root. `diff` is an MST
|
|
52
|
+
* of what changed against the parent: id → new record CID, or null for a delete.
|
|
39
53
|
*
|
|
40
54
|
* Two more fields:
|
|
41
55
|
* • `repo`: the repo's name, which events carry only as keccak256(name);
|
|
@@ -47,6 +61,7 @@ type Ref = {
|
|
|
47
61
|
interface CommitBlock {
|
|
48
62
|
epoch: number;
|
|
49
63
|
parent: CID | null;
|
|
64
|
+
diff: CID;
|
|
50
65
|
root: CID;
|
|
51
66
|
repo: string;
|
|
52
67
|
car: CID;
|
|
@@ -63,7 +78,8 @@ declare function assertValidRecordId(id: string): void;
|
|
|
63
78
|
declare const MST_BITS = 4;
|
|
64
79
|
interface MstEntry {
|
|
65
80
|
key: string;
|
|
66
|
-
|
|
81
|
+
/** A record CID; null only in a diff tree, where it means "deleted". */
|
|
82
|
+
value: CID | null;
|
|
67
83
|
/** Subtree of keys between this key and the next one. */
|
|
68
84
|
right: CID | null;
|
|
69
85
|
}
|
|
@@ -82,7 +98,7 @@ declare function keyLevel(key: string): number;
|
|
|
82
98
|
* page model it replaced); update only the changed paths if large repos
|
|
83
99
|
* make commits CPU-bound.
|
|
84
100
|
*/
|
|
85
|
-
declare function buildMst(state: Map<string, CID>): Promise<{
|
|
101
|
+
declare function buildMst(state: Map<string, CID | null>): Promise<{
|
|
86
102
|
root: CID;
|
|
87
103
|
nodes: Block[];
|
|
88
104
|
}>;
|
|
@@ -92,8 +108,8 @@ declare function buildMst(state: Map<string, CID>): Promise<{
|
|
|
92
108
|
* and comparing roots catches duplicate, misordered, misplaced and wrong-level
|
|
93
109
|
* keys in one check.
|
|
94
110
|
*/
|
|
95
|
-
declare function readMst(root: CID, getBlock: (cid: CID) => Promise<Uint8Array>): Promise<{
|
|
96
|
-
state: Map<string,
|
|
111
|
+
declare function readMst<V extends CID | null = CID>(root: CID, getBlock: (cid: CID) => Promise<Uint8Array>): Promise<{
|
|
112
|
+
state: Map<string, V>;
|
|
97
113
|
nodeCids: Set<string>;
|
|
98
114
|
}>;
|
|
99
115
|
/**
|
|
@@ -118,4 +134,4 @@ declare function diffMst(oldRoot: CID | null, newRoot: CID | null, getOld: (cid:
|
|
|
118
134
|
*/
|
|
119
135
|
declare function lookupMst(root: CID, key: string, getBlock: (cid: CID) => Promise<Uint8Array>): Promise<CID | null>;
|
|
120
136
|
//#endregion
|
|
121
|
-
export { Block, CommitBlock, MAX_RECORD_ID_LENGTH, MST_BITS, MstEntry, MstNode, RecordBlock, Ref, assertBlockMatches, assertValidRecordId, buildMst, decodeBlock, diffMst, encodeBlock, keyLevel, lookupMst, readMst };
|
|
137
|
+
export { Block, CommitBlock, MAX_RECORD_ID_LENGTH, MST_BITS, MstEntry, MstNode, RecordBlock, Ref, Stitch, assertBlockMatches, assertValidRecordId, buildMst, decodeBlock, diffMst, encodeBlock, keyLevel, lookupMst, readMst };
|
package/lib/engine/records.js
CHANGED
|
@@ -166,6 +166,7 @@ async function diffMst(oldRoot, newRoot, getOld, getNew) {
|
|
|
166
166
|
level: node.level - 1
|
|
167
167
|
}] : [];
|
|
168
168
|
for (const e of node.entries) {
|
|
169
|
+
if (!e.value) throw new Error(`state tree ${sub.toString()} holds a null`);
|
|
169
170
|
items.push({
|
|
170
171
|
key: e.key,
|
|
171
172
|
value: e.value
|
|
@@ -29,6 +29,8 @@ declare class MemStorage implements MetadataStorage {
|
|
|
29
29
|
name: string;
|
|
30
30
|
}[]): Promise<Record<string, string>>;
|
|
31
31
|
get<T>(_uri: string): Promise<T>;
|
|
32
|
+
/** Every block stored, loose or inside a CAR. */
|
|
33
|
+
allBlocks(): Promise<Map<string, Uint8Array>>;
|
|
32
34
|
delete(_uri: string): Promise<void>;
|
|
33
35
|
}
|
|
34
36
|
/** The paper's registry in memory, signing as PUBLISHER. */
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { readCar } from "./car.js";
|
|
1
2
|
import { MemRegistry } from "../test/mem-registry.js";
|
|
2
3
|
import { CID } from "multiformats/cid";
|
|
3
4
|
import { sha256 } from "multiformats/hashes/sha2";
|
|
@@ -51,6 +52,12 @@ var MemStorage = class {
|
|
|
51
52
|
get(_uri) {
|
|
52
53
|
return Promise.reject(/* @__PURE__ */ new Error("MemStorage.get not implemented"));
|
|
53
54
|
}
|
|
55
|
+
/** Every block stored, loose or inside a CAR. */
|
|
56
|
+
async allBlocks() {
|
|
57
|
+
const out = new Map(this.blocks);
|
|
58
|
+
for (const bytes of this.files.values()) for (const b of await readCar(bytes, { verify: false })) out.set(b.cid.toString(), b.bytes);
|
|
59
|
+
return out;
|
|
60
|
+
}
|
|
54
61
|
delete(_uri) {
|
|
55
62
|
return Promise.resolve();
|
|
56
63
|
}
|
package/lib/erc8004.js
CHANGED
|
@@ -116,7 +116,8 @@ async function setAgentFile(c, agentId, file) {
|
|
|
116
116
|
chain: c.chain,
|
|
117
117
|
account: c.walletClient.account ?? null
|
|
118
118
|
});
|
|
119
|
-
await c.publicClient.waitForTransactionReceipt({ hash });
|
|
119
|
+
const { status } = await c.publicClient.waitForTransactionReceipt({ hash });
|
|
120
|
+
if (status !== "success") throw new Error(`setAgentURI reverted in tx ${hash}`);
|
|
120
121
|
return hash;
|
|
121
122
|
}
|
|
122
123
|
/** Mint an agent with no URI yet, and return its id. */
|
package/lib/fangorn.d.ts
CHANGED
|
@@ -3,7 +3,8 @@ import { Registry } from "./contracts/data-registry/index.js";
|
|
|
3
3
|
import { SettlementRegistryClient } from "./contracts/settlement-registry/index.js";
|
|
4
4
|
import "./contracts/index.js";
|
|
5
5
|
import { MetadataStorage } from "./providers/storage/types.js";
|
|
6
|
-
import {
|
|
6
|
+
import { Stitch } from "./engine/records.js";
|
|
7
|
+
import { CommitDiff, FangornEngine, RecordInput, RepoContents, RepoDiff, SignedUpdate, StoredRecord } from "./engine/index.js";
|
|
7
8
|
import { NetworkConfig } from "./config.js";
|
|
8
9
|
import { FangornCreateOptions, StorageConfig } from "./types/index.js";
|
|
9
10
|
import { AgentCard as AgentCard$1 } from "./erc8004.js";
|
|
@@ -90,7 +91,7 @@ declare class Fangorn {
|
|
|
90
91
|
txHash: Hash;
|
|
91
92
|
onChainTip: CID;
|
|
92
93
|
}>;
|
|
93
|
-
/** Stage records into one commit on top of `base
|
|
94
|
+
/** Stage records into one commit on top of `base`, a checkpoint every CHECKPOINT_EVERY positions. */
|
|
94
95
|
private createCommit;
|
|
95
96
|
/**
|
|
96
97
|
* Allocates a repo in the publisher's root map.
|
|
@@ -269,6 +270,35 @@ declare class Fangorn {
|
|
|
269
270
|
}>;
|
|
270
271
|
/** Show a commit and what it changed vs. its parent. */
|
|
271
272
|
show(commitCid: string): Promise<CommitDiff>;
|
|
273
|
+
/** A stitch (WHITEPAPER_1 §4) to the current head of a repo, at `key` if given. */
|
|
274
|
+
stitchTo(publisher: Hex, repo: string, key?: string): Promise<Stitch>;
|
|
275
|
+
/** Check a stitch against the registry, and resolve what it names. */
|
|
276
|
+
checkStitch(s: Stitch): Promise<{
|
|
277
|
+
latest: boolean;
|
|
278
|
+
record?: StoredRecord | null;
|
|
279
|
+
diff?: Map<string, CID | null>;
|
|
280
|
+
}>;
|
|
281
|
+
/**
|
|
282
|
+
* Build or update a stitch across the repos `patterns` match (see `stitchFilter`),
|
|
283
|
+
* from the update log. Pass the previous stitch to update it. Returns the stitch's CID.
|
|
284
|
+
*/
|
|
285
|
+
restitch(patterns: string[], prev?: string): Promise<string>;
|
|
286
|
+
/** A stitch's tree root, and the log it was folded from: n entries, with root `logRoot`. */
|
|
287
|
+
readStitch(stitch: string): Promise<{
|
|
288
|
+
root: string;
|
|
289
|
+
n: number;
|
|
290
|
+
logRoot: `0x${string}`;
|
|
291
|
+
}>;
|
|
292
|
+
/** Check a stitch against the contract's log root, rebuilding it under the same patterns. */
|
|
293
|
+
verifyStitch(stitch: string, patterns: string[]): Promise<boolean>;
|
|
294
|
+
/** The head commit a stitch holds for a repo, or null if it doesn't include it. */
|
|
295
|
+
stitchedHead(stitch: string, publisher: Hex, repo: string): Promise<string | null>;
|
|
296
|
+
/** Every repo a stitch holds, at its head (the on-chain digest, as `repoDiff` takes it). */
|
|
297
|
+
stitchHeads(stitch: string): Promise<{
|
|
298
|
+
publisher: `0x${string}`;
|
|
299
|
+
repo: string;
|
|
300
|
+
head: `0x${string}`;
|
|
301
|
+
}[]>;
|
|
272
302
|
/**
|
|
273
303
|
* Lists every record currently committed under a repo, resolved
|
|
274
304
|
* from the publisher's on-chain root — useful for verifying what actually
|
|
@@ -338,5 +368,11 @@ declare class Fangorn {
|
|
|
338
368
|
getWalletClient(): WalletClient;
|
|
339
369
|
getAddress(): Hex;
|
|
340
370
|
}
|
|
371
|
+
/**
|
|
372
|
+
* Which repos a stitch covers. A pattern is `publisher/repo`, a repo name (every
|
|
373
|
+
* publisher's), `*` (every repo), or `/regex/` matched against `publisher/repo`
|
|
374
|
+
* (publisher lowercased).
|
|
375
|
+
*/
|
|
376
|
+
declare function stitchFilter(patterns: string[]): (publisher: Hex, repo: string) => boolean;
|
|
341
377
|
//#endregion
|
|
342
|
-
export { AgentCard, CARD_RECORD, FANGORN_REPO_EXTENSION, Fangorn, RepoChange, SubscribeOptions };
|
|
378
|
+
export { AgentCard, CARD_RECORD, FANGORN_REPO_EXTENSION, Fangorn, RepoChange, SubscribeOptions, stitchFilter };
|