@fangorn-network/sdk 0.1.4 → 0.1.5
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/contracts/data-registry/abi.d.ts +12 -0
- package/lib/contracts/data-registry/abi.js +15 -0
- 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/engine/index.d.ts +86 -16
- package/lib/engine/index.js +264 -37
- 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/fangorn.d.ts +38 -2
- package/lib/fangorn.js +63 -2
- 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 +5218 -5218
- 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";
|
|
@@ -22,22 +23,30 @@ const MAX_REPO_NAME_LENGTH = 256;
|
|
|
22
23
|
function rootHexFromCid(commitCid) {
|
|
23
24
|
return bytesToHex(commitCid.multihash.digest);
|
|
24
25
|
}
|
|
26
|
+
/** A repo's key in a stitch across repos. */
|
|
27
|
+
const stitchKey = (publisher, repo) => `${publisher.toLowerCase()}/${repo}`;
|
|
28
|
+
function cidFromDigest(digest) {
|
|
29
|
+
return CID.createV1(dagCbor.code, Digest.create(sha256.code, hexToBytes(digest)));
|
|
30
|
+
}
|
|
25
31
|
/** The update that settles `commit`. */
|
|
26
32
|
function commitUpdate(commit) {
|
|
33
|
+
if (!commit.diff) throw new Error("commit has no diff: it is not in the current commit format — rebuild it");
|
|
27
34
|
return {
|
|
28
35
|
repo: commit.repo,
|
|
29
36
|
epoch: commit.epoch,
|
|
30
37
|
parent: commit.parent ? rootHexFromCid(commit.parent) : ZERO_HEAD,
|
|
38
|
+
diff: rootHexFromCid(commit.diff),
|
|
31
39
|
root: rootHexFromCid(commit.root),
|
|
32
40
|
car: bytesToHex(commit.car.bytes)
|
|
33
41
|
};
|
|
34
42
|
}
|
|
35
43
|
/** The head the registry computes for `u`. */
|
|
36
44
|
async function commitHead(u) {
|
|
37
|
-
const link =
|
|
45
|
+
const link = cidFromDigest;
|
|
38
46
|
return rootHexFromCid((await encodeBlock({
|
|
39
47
|
epoch: u.epoch,
|
|
40
48
|
parent: u.parent === ZERO_HEAD ? null : link(u.parent),
|
|
49
|
+
diff: link(u.diff),
|
|
41
50
|
root: link(u.root),
|
|
42
51
|
repo: u.repo,
|
|
43
52
|
car: CID.decode(hexToBytes(u.car))
|
|
@@ -93,34 +102,50 @@ var FangornEngine = class {
|
|
|
93
102
|
/** Read and decode a commit object by CID (directly addressable — no CAR needed). */
|
|
94
103
|
async getCommit(commitCid) {
|
|
95
104
|
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);
|
|
105
|
+
const decoded = decodeBlock(await this.directBlock(commitCid));
|
|
103
106
|
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
107
|
return {
|
|
105
108
|
epoch: decoded.epoch,
|
|
106
109
|
parent: decoded.parent ? CID.parse(String(decoded.parent)) : null,
|
|
110
|
+
diff: decoded.diff ? CID.parse(String(decoded.diff)) : null,
|
|
107
111
|
root: CID.parse(String(decoded.root)),
|
|
108
112
|
repo: decoded.repo,
|
|
109
113
|
car: CID.parse(String(decoded.car))
|
|
110
114
|
};
|
|
111
115
|
}
|
|
112
|
-
/**
|
|
113
|
-
async
|
|
114
|
-
const
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
116
|
+
/** A block stored on its own (a commit or stitch block), hash-checked and cached. */
|
|
117
|
+
async directBlock(cid) {
|
|
118
|
+
const key = cid.toString();
|
|
119
|
+
let bytes = this.cache.get(key);
|
|
120
|
+
if (!bytes) {
|
|
121
|
+
bytes = await this.storage.getRawBlock(key);
|
|
122
|
+
assertBlockMatches(cid, bytes);
|
|
123
|
+
this.cache.set(key, bytes);
|
|
124
|
+
}
|
|
125
|
+
return bytes;
|
|
126
|
+
}
|
|
127
|
+
/** The packfile and parent of a link in a chain: a commit, or a stitch. */
|
|
128
|
+
async chainLink(cid) {
|
|
129
|
+
const b = decodeBlock(await this.directBlock(cid));
|
|
130
|
+
return {
|
|
131
|
+
car: b.car ?? null,
|
|
132
|
+
parent: b.parent ?? null
|
|
133
|
+
};
|
|
134
|
+
}
|
|
135
|
+
/** Pull every block of a chain link's CAR into the local cache. */
|
|
136
|
+
async loadCar(linkCid, car) {
|
|
137
|
+
if (car) {
|
|
138
|
+
const bytes = await this.storage.getFile(car.toString());
|
|
139
|
+
for (const block of await readCar(bytes, { verify: false })) {
|
|
140
|
+
const key = block.cid.toString();
|
|
141
|
+
if (!this.cache.has(key)) this.unverified.set(key, block.bytes);
|
|
142
|
+
}
|
|
118
143
|
}
|
|
119
|
-
this.loadedCars.add(
|
|
144
|
+
this.loadedCars.add(linkCid.toString());
|
|
120
145
|
}
|
|
121
146
|
/**
|
|
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.
|
|
147
|
+
* Resolve a data block: local cache first, then walk the chain (commits, or
|
|
148
|
+
* stitches) from `hint`, loading one ancestor CAR at a time until the block turns up.
|
|
124
149
|
*/
|
|
125
150
|
async getBlock(cid, hint) {
|
|
126
151
|
const key = cid.toString();
|
|
@@ -138,13 +163,13 @@ var FangornEngine = class {
|
|
|
138
163
|
if (hit) return hit;
|
|
139
164
|
let cursor = hint;
|
|
140
165
|
while (cursor) {
|
|
141
|
-
const
|
|
166
|
+
const link = await this.chainLink(cursor);
|
|
142
167
|
if (!this.loadedCars.has(cursor.toString())) {
|
|
143
|
-
await this.loadCar(cursor,
|
|
168
|
+
await this.loadCar(cursor, link.car);
|
|
144
169
|
const found = local();
|
|
145
170
|
if (found) return found;
|
|
146
171
|
}
|
|
147
|
-
cursor =
|
|
172
|
+
cursor = link.parent;
|
|
148
173
|
}
|
|
149
174
|
throw new Error(`Block payload missing for key: ${key}`);
|
|
150
175
|
}
|
|
@@ -208,13 +233,25 @@ var FangornEngine = class {
|
|
|
208
233
|
if (!oldRecordCids.has(block.cid.toString())) carBlocks.push(block);
|
|
209
234
|
}
|
|
210
235
|
const mst = await buildMst(state);
|
|
211
|
-
|
|
236
|
+
const delta = /* @__PURE__ */ new Map();
|
|
237
|
+
for (const [id, cid] of state) if (!old.state.get(id)?.equals(cid)) delta.set(id, cid);
|
|
238
|
+
for (const id of old.state.keys()) if (!state.has(id)) delta.set(id, null);
|
|
239
|
+
const diff = await buildMst(delta);
|
|
240
|
+
const fresh = /* @__PURE__ */ new Set();
|
|
241
|
+
for (const node of [...mst.nodes, ...diff.nodes]) {
|
|
242
|
+
const key = node.cid.toString();
|
|
243
|
+
if (!old.nodeCids.has(key) && !fresh.has(key)) {
|
|
244
|
+
fresh.add(key);
|
|
245
|
+
carBlocks.push(node);
|
|
246
|
+
}
|
|
247
|
+
}
|
|
212
248
|
for (const block of carBlocks) this.putLocal(block);
|
|
213
249
|
const carBytes = await packCar(mst.root, carBlocks);
|
|
214
250
|
const car = fileCid(await this.storage.putFile(carBytes, `${mst.root.toString()}.car`));
|
|
215
251
|
const commitBlock = await encodeBlock({
|
|
216
252
|
epoch: await this.registry.epoch(),
|
|
217
253
|
parent: base,
|
|
254
|
+
diff: diff.root,
|
|
218
255
|
root: mst.root,
|
|
219
256
|
repo,
|
|
220
257
|
car
|
|
@@ -295,20 +332,58 @@ var FangornEngine = class {
|
|
|
295
332
|
payload: r.payload
|
|
296
333
|
};
|
|
297
334
|
}
|
|
335
|
+
/** The diff an event carries: id → new record CID, or null where the record was deleted. */
|
|
336
|
+
async eventDiff(commitCid) {
|
|
337
|
+
const { diff } = await this.getCommit(commitCid);
|
|
338
|
+
if (!diff) throw new Error(`commit ${commitCid.toString()} predates diff events`);
|
|
339
|
+
return (await readMst(diff, (cid) => this.getBlock(cid, commitCid))).state;
|
|
340
|
+
}
|
|
341
|
+
/**
|
|
342
|
+
* The events after `old` up to `tip`, composed into one id → CID | null map, newest write
|
|
343
|
+
* winning. Null when `old` is not an ancestor of `tip`, or an event between them has no diff.
|
|
344
|
+
*/
|
|
345
|
+
async eventsSince(old, tip) {
|
|
346
|
+
const path = [];
|
|
347
|
+
for await (const { cid, commit } of this.walkParents(tip)) {
|
|
348
|
+
if (cid.equals(old)) break;
|
|
349
|
+
if (!commit.diff || !commit.parent) return null;
|
|
350
|
+
path.push(cid);
|
|
351
|
+
}
|
|
352
|
+
const net = /* @__PURE__ */ new Map();
|
|
353
|
+
for (const cid of path) for (const [id, v] of await this.eventDiff(cid)) if (!net.has(id)) net.set(id, v);
|
|
354
|
+
return net;
|
|
355
|
+
}
|
|
298
356
|
/**
|
|
299
357
|
* 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.
|
|
358
|
+
* the subscription light-client. Only records that actually changed are decoded.
|
|
302
359
|
*
|
|
303
|
-
*
|
|
304
|
-
*
|
|
305
|
-
*
|
|
306
|
-
*
|
|
307
|
-
* 50k-record repo cost ~10 × depth nodes, not two 50k-key walks.
|
|
360
|
+
* When `old` is an ancestor of `new`, this reads the diffs the events carry (WHITEPAPER_1 §3.3,
|
|
361
|
+
* Following) and looks each changed id up in the old tree. Otherwise, across a reset to another
|
|
362
|
+
* chain or a commit from before diff events, it diffs the two trees (`diffMst`). Either way the
|
|
363
|
+
* result is the net delta an index builder needs: what to (re)embed, what to evict.
|
|
308
364
|
*/
|
|
309
365
|
async repoDiff(oldRootHex, newRootHex) {
|
|
310
366
|
const newCommit = newRootHex === ZERO_BYTES32 ? null : this.hexToRootCid(newRootHex);
|
|
311
367
|
const oldCommit = oldRootHex && oldRootHex !== ZERO_BYTES32 ? this.hexToRootCid(oldRootHex) : null;
|
|
368
|
+
const events = oldCommit && newCommit ? await this.eventsSince(oldCommit, newCommit) : null;
|
|
369
|
+
if (oldCommit && newCommit && events) {
|
|
370
|
+
const oldRoot = (await this.getCommit(oldCommit)).root;
|
|
371
|
+
const puts$1 = [];
|
|
372
|
+
const deletes = [];
|
|
373
|
+
const superseded = [];
|
|
374
|
+
for (const [id, after] of events) {
|
|
375
|
+
const before = await lookupMst(oldRoot, id, (cid) => this.getBlock(cid, oldCommit));
|
|
376
|
+
if (before && after && before.equals(after)) continue;
|
|
377
|
+
if (before) superseded.push(before.toString());
|
|
378
|
+
if (after) puts$1.push(await this.decodeRecord(id, after, newCommit));
|
|
379
|
+
else if (before) deletes.push(id);
|
|
380
|
+
}
|
|
381
|
+
return {
|
|
382
|
+
puts: puts$1,
|
|
383
|
+
deletes,
|
|
384
|
+
superseded
|
|
385
|
+
};
|
|
386
|
+
}
|
|
312
387
|
const root = async (c) => c ? (await this.getCommit(c)).root : null;
|
|
313
388
|
const diff = await diffMst(await root(oldCommit), await root(newCommit), (cid) => this.getBlock(cid, oldCommit), (cid) => this.getBlock(cid, newCommit));
|
|
314
389
|
const puts = [];
|
|
@@ -319,21 +394,29 @@ var FangornEngine = class {
|
|
|
319
394
|
superseded: [...diff.before.values()].map(String)
|
|
320
395
|
};
|
|
321
396
|
}
|
|
322
|
-
/** Diff a commit against its parent. */
|
|
397
|
+
/** Diff a commit against its parent: its event's diff, or two full states for an older commit. */
|
|
323
398
|
async diffCommit(commitCid) {
|
|
324
399
|
const commit = await this.getCommit(commitCid);
|
|
325
400
|
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
401
|
const added = [];
|
|
329
402
|
const updated = [];
|
|
330
403
|
const removed = [];
|
|
331
|
-
|
|
332
|
-
const
|
|
333
|
-
|
|
334
|
-
|
|
404
|
+
if (commit.diff) {
|
|
405
|
+
const parent = commit.parent;
|
|
406
|
+
const parentRoot = parent ? (await this.getCommit(parent)).root : null;
|
|
407
|
+
for (const [id, cid] of await this.eventDiff(commitCid)) if (!cid) removed.push(`${ns}/${id}`);
|
|
408
|
+
else if (parent && parentRoot && await lookupMst(parentRoot, id, (c) => this.getBlock(c, parent))) updated.push(`${ns}/${id}`);
|
|
409
|
+
else added.push(`${ns}/${id}`);
|
|
410
|
+
} else {
|
|
411
|
+
const child = (await this.stateAt(commitCid)).state;
|
|
412
|
+
const par = commit.parent ? (await this.stateAt(commit.parent)).state : /* @__PURE__ */ new Map();
|
|
413
|
+
for (const [id, cid] of child) {
|
|
414
|
+
const prev = par.get(id);
|
|
415
|
+
if (!prev) added.push(`${ns}/${id}`);
|
|
416
|
+
else if (!prev.equals(cid)) updated.push(`${ns}/${id}`);
|
|
417
|
+
}
|
|
418
|
+
for (const id of par.keys()) if (!child.has(id)) removed.push(`${ns}/${id}`);
|
|
335
419
|
}
|
|
336
|
-
for (const id of par.keys()) if (!child.has(id)) removed.push(`${ns}/${id}`);
|
|
337
420
|
return {
|
|
338
421
|
parent: commit.parent?.toString() ?? null,
|
|
339
422
|
epoch: commit.epoch,
|
|
@@ -344,6 +427,150 @@ var FangornEngine = class {
|
|
|
344
427
|
removed: removed.sort()
|
|
345
428
|
};
|
|
346
429
|
}
|
|
430
|
+
/** A stitch to the current head of (publisher, repo), at `key` if given. One `getHead` read, no logs. */
|
|
431
|
+
async stitchTo(publisher, repo, key) {
|
|
432
|
+
const { pos, head } = await this.registry.headAt({
|
|
433
|
+
publisher,
|
|
434
|
+
repo
|
|
435
|
+
});
|
|
436
|
+
if (pos === 0) throw new Error(`${publisher} has no head in repo ${repo}`);
|
|
437
|
+
return {
|
|
438
|
+
publisher,
|
|
439
|
+
repo,
|
|
440
|
+
pos,
|
|
441
|
+
head,
|
|
442
|
+
...key === void 0 ? {} : { key }
|
|
443
|
+
};
|
|
444
|
+
}
|
|
445
|
+
/**
|
|
446
|
+
* A stitch across repos: an MST of `publisher/repo` → head commit, folded from the
|
|
447
|
+
* update log up to entry n and tagged with the log's root there. Pass the previous
|
|
448
|
+
* stitch to read only the log since it, and upload only the nodes it doesn't have
|
|
449
|
+
* (one CAR). Returns the stitch block's CID, its name; with nothing new, `prev`.
|
|
450
|
+
* Use the same `filter` every time for one stitch. `fromBlock` is where the log
|
|
451
|
+
* starts (the registry's deploy block).
|
|
452
|
+
* ponytail: rehashes the whole tree (O(repos)); and readers walk back one CAR per
|
|
453
|
+
* stitch to find old nodes, so checkpoint with a full CAR (`prev = null`) when the
|
|
454
|
+
* chain gets long.
|
|
455
|
+
*/
|
|
456
|
+
async restitch(prev, filter, fromBlock = 0n) {
|
|
457
|
+
const base = prev ? await this.readStitch(prev) : null;
|
|
458
|
+
const to = await this.registry.clock();
|
|
459
|
+
const entries = await this.registry.log({}, base ? base.t + 1n : fromBlock, to);
|
|
460
|
+
if (prev && entries.length === 0) return prev;
|
|
461
|
+
const old = base && prev ? await readMst(base.root, (c) => this.getBlock(c, prev)) : {
|
|
462
|
+
state: /* @__PURE__ */ new Map(),
|
|
463
|
+
nodeCids: /* @__PURE__ */ new Set()
|
|
464
|
+
};
|
|
465
|
+
const state = new Map(old.state);
|
|
466
|
+
let mmr = base ?? EMPTY_MMR;
|
|
467
|
+
for (const e of entries) {
|
|
468
|
+
mmr = mmrAppend(mmr, logLeaf(e));
|
|
469
|
+
if (!filter || filter(e.publisher, e.repo)) state.set(stitchKey(e.publisher, e.repo), this.hexToRootCid(e.head));
|
|
470
|
+
}
|
|
471
|
+
const { root, nodes } = await buildMst(state);
|
|
472
|
+
const fresh = /* @__PURE__ */ new Map();
|
|
473
|
+
for (const n of nodes) if (!old.nodeCids.has(n.cid.toString())) fresh.set(n.cid.toString(), n);
|
|
474
|
+
for (const n of fresh.values()) this.putLocal(n);
|
|
475
|
+
const block = await encodeBlock({
|
|
476
|
+
parent: prev,
|
|
477
|
+
root,
|
|
478
|
+
car: fresh.size ? fileCid(await this.storage.putFile(await packCar(root, fresh.values()), `${root.toString()}.car`)) : null,
|
|
479
|
+
n: mmr.n,
|
|
480
|
+
t: Number(to),
|
|
481
|
+
peaks: mmr.peaks
|
|
482
|
+
});
|
|
483
|
+
await this.storage.putBlock(block);
|
|
484
|
+
this.putLocal(block);
|
|
485
|
+
this.loadedCars.add(block.cid.toString());
|
|
486
|
+
return block.cid;
|
|
487
|
+
}
|
|
488
|
+
/** A stitch block: its tree root, and the log it was folded from (n entries, root `logRoot`). */
|
|
489
|
+
async readStitch(stitch) {
|
|
490
|
+
const b = decodeBlock(await this.directBlock(stitch));
|
|
491
|
+
const mmr = {
|
|
492
|
+
n: b.n,
|
|
493
|
+
peaks: b.peaks
|
|
494
|
+
};
|
|
495
|
+
return {
|
|
496
|
+
root: CID.parse(String(b.root)),
|
|
497
|
+
...mmr,
|
|
498
|
+
t: BigInt(b.t),
|
|
499
|
+
logRoot: mmrRoot(mmr)
|
|
500
|
+
};
|
|
501
|
+
}
|
|
502
|
+
/**
|
|
503
|
+
* The head commit a stitch holds for (publisher, repo), or null if it doesn't
|
|
504
|
+
* include the repo. Every node read is hash-checked.
|
|
505
|
+
* ponytail: like `lookupMst`, trusts key order on the path; `readMst` proves absence.
|
|
506
|
+
*/
|
|
507
|
+
async stitchedHead(stitch, publisher, repo) {
|
|
508
|
+
const { root } = await this.readStitch(stitch);
|
|
509
|
+
return lookupMst(root, stitchKey(publisher, repo), (c) => this.getBlock(c, stitch));
|
|
510
|
+
}
|
|
511
|
+
/** Every (publisher, repo) → head commit a stitch holds: what an indexer follows. */
|
|
512
|
+
async stitchHeads(stitch) {
|
|
513
|
+
const { root } = await this.readStitch(stitch);
|
|
514
|
+
const { state } = await readMst(root, (c) => this.getBlock(c, stitch));
|
|
515
|
+
return [...state].map(([k, head]) => ({
|
|
516
|
+
publisher: k.slice(0, 42),
|
|
517
|
+
repo: k.slice(43),
|
|
518
|
+
head
|
|
519
|
+
}));
|
|
520
|
+
}
|
|
521
|
+
/**
|
|
522
|
+
* Check a stitch without trusting whoever built it: replay the whole log, check it
|
|
523
|
+
* against the contract's log root, and rebuild the stitch from its first n entries
|
|
524
|
+
* under the same `filter`. Reads no stitch nodes, only the stitch block.
|
|
525
|
+
* ponytail: O(log) per check; store log roots on chain if that gets slow.
|
|
526
|
+
*/
|
|
527
|
+
async verifyStitch(stitch, filter, fromBlock = 0n) {
|
|
528
|
+
const s = await this.readStitch(stitch);
|
|
529
|
+
const to = await this.registry.clock();
|
|
530
|
+
const entries = await this.registry.log({}, fromBlock, to);
|
|
531
|
+
if (entries.length < s.n) return false;
|
|
532
|
+
let mmr = EMPTY_MMR;
|
|
533
|
+
const state = /* @__PURE__ */ new Map();
|
|
534
|
+
for (const [i, e] of entries.entries()) {
|
|
535
|
+
mmr = mmrAppend(mmr, logLeaf(e));
|
|
536
|
+
if (i >= s.n) continue;
|
|
537
|
+
if (!filter || filter(e.publisher, e.repo)) state.set(stitchKey(e.publisher, e.repo), this.hexToRootCid(e.head));
|
|
538
|
+
if (i === s.n - 1 && mmrRoot(mmr) !== s.logRoot) return false;
|
|
539
|
+
}
|
|
540
|
+
if (s.n === 0 && s.logRoot !== mmrRoot(EMPTY_MMR)) return false;
|
|
541
|
+
if (mmrRoot(mmr) !== await this.registry.logRoot(to)) return false;
|
|
542
|
+
return (await buildMst(state)).root.equals(s.root);
|
|
543
|
+
}
|
|
544
|
+
/**
|
|
545
|
+
* Check a stitch against the registry (WHITEPAPER_1 Proposition 4.2) and resolve it:
|
|
546
|
+
* the record at its key as of that position (null if absent), or, with no key, the event's diff.
|
|
547
|
+
* Throws if the repo never had `head` at `pos`. `latest` says whether the repo has moved on.
|
|
548
|
+
* A stitch at the current generation is checked with one `getHead` read.
|
|
549
|
+
* ponytail: an older stitch still scans the log from `fromBlock` (and trusts the RPC).
|
|
550
|
+
* Upgrade: walk parents back from the on-chain head, recomputing `commitHead` each hop
|
|
551
|
+
* (O(distance), no logs), or an MMR opening against `logRoot()` (O(log n), needs a proof server).
|
|
552
|
+
*/
|
|
553
|
+
async checkStitch(s, fromBlock = 0n) {
|
|
554
|
+
const ref = {
|
|
555
|
+
publisher: s.publisher,
|
|
556
|
+
repo: s.repo
|
|
557
|
+
};
|
|
558
|
+
const cur = await this.registry.headAt(ref);
|
|
559
|
+
if (s.pos < 1 || s.pos > cur.pos) throw new Error(`no position ${s.pos.toString()} in ${s.publisher}/${s.repo}`);
|
|
560
|
+
const latest = s.pos === cur.pos;
|
|
561
|
+
const had = latest ? cur.head : (await this.registry.log(ref, fromBlock)).find((e) => e.pos === s.pos)?.head;
|
|
562
|
+
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}`);
|
|
563
|
+
const commit = this.hexToRootCid(s.head);
|
|
564
|
+
if (s.key === void 0) return {
|
|
565
|
+
latest,
|
|
566
|
+
diff: await this.eventDiff(commit)
|
|
567
|
+
};
|
|
568
|
+
const cid = await lookupMst((await this.getCommit(commit)).root, s.key, (c) => this.getBlock(c, commit));
|
|
569
|
+
return {
|
|
570
|
+
latest,
|
|
571
|
+
record: cid ? await this.decodeRecord(s.key, cid, commit) : null
|
|
572
|
+
};
|
|
573
|
+
}
|
|
347
574
|
/** check if the repo already exists (head resolves) */
|
|
348
575
|
async repoExists(publisher, repo) {
|
|
349
576
|
return await this.resolveHeadCommit(publisher, repo) !== null;
|
|
@@ -374,4 +601,4 @@ var FangornEngine = class {
|
|
|
374
601
|
};
|
|
375
602
|
|
|
376
603
|
//#endregion
|
|
377
|
-
export { FangornEngine, MAX_REPO_NAME_LENGTH, assertValidRepoName, commitHead, commitUpdate, fileCid, rootHexFromCid };
|
|
604
|
+
export { 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/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";
|
|
@@ -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 };
|
package/lib/fangorn.js
CHANGED
|
@@ -7,7 +7,7 @@ import { SettlementRegistryClient } from "./contracts/settlement-registry/index.
|
|
|
7
7
|
import "./contracts/index.js";
|
|
8
8
|
import { FangornEngine, assertValidRepoName, commitUpdate, rootHexFromCid } from "./engine/index.js";
|
|
9
9
|
import { CommitFeed } from "./feed.js";
|
|
10
|
-
import { createPublicClient, createWalletClient, http } from "viem";
|
|
10
|
+
import { createPublicClient, createWalletClient, http, toHex } from "viem";
|
|
11
11
|
import { privateKeyToAccount } from "viem/accounts";
|
|
12
12
|
import { CID } from "multiformats/cid";
|
|
13
13
|
|
|
@@ -426,6 +426,46 @@ var Fangorn = class Fangorn {
|
|
|
426
426
|
async show(commitCid) {
|
|
427
427
|
return this.engine.diffCommit(CID.parse(commitCid));
|
|
428
428
|
}
|
|
429
|
+
/** A stitch (WHITEPAPER_1 §4) to the current head of a repo, at `key` if given. */
|
|
430
|
+
stitchTo(publisher, repo, key) {
|
|
431
|
+
return this.engine.stitchTo(publisher, repo, key);
|
|
432
|
+
}
|
|
433
|
+
/** Check a stitch against the registry, and resolve what it names. */
|
|
434
|
+
checkStitch(s) {
|
|
435
|
+
return this.engine.checkStitch(s, this.ctx.config.fromBlock);
|
|
436
|
+
}
|
|
437
|
+
/**
|
|
438
|
+
* Build or update a stitch across the repos `patterns` match (see `stitchFilter`),
|
|
439
|
+
* from the update log. Pass the previous stitch to update it. Returns the stitch's CID.
|
|
440
|
+
*/
|
|
441
|
+
async restitch(patterns, prev) {
|
|
442
|
+
return (await this.engine.restitch(prev ? CID.parse(prev) : null, stitchFilter(patterns), this.ctx.config.fromBlock)).toString();
|
|
443
|
+
}
|
|
444
|
+
/** A stitch's tree root, and the log it was folded from: n entries, with root `logRoot`. */
|
|
445
|
+
async readStitch(stitch) {
|
|
446
|
+
const s = await this.engine.readStitch(CID.parse(stitch));
|
|
447
|
+
return {
|
|
448
|
+
root: s.root.toString(),
|
|
449
|
+
n: s.n,
|
|
450
|
+
logRoot: s.logRoot
|
|
451
|
+
};
|
|
452
|
+
}
|
|
453
|
+
/** Check a stitch against the contract's log root, rebuilding it under the same patterns. */
|
|
454
|
+
verifyStitch(stitch, patterns) {
|
|
455
|
+
return this.engine.verifyStitch(CID.parse(stitch), stitchFilter(patterns), this.ctx.config.fromBlock);
|
|
456
|
+
}
|
|
457
|
+
/** The head commit a stitch holds for a repo, or null if it doesn't include it. */
|
|
458
|
+
async stitchedHead(stitch, publisher, repo) {
|
|
459
|
+
return (await this.engine.stitchedHead(CID.parse(stitch), publisher, repo))?.toString() ?? null;
|
|
460
|
+
}
|
|
461
|
+
/** Every repo a stitch holds, at its head (the on-chain digest, as `repoDiff` takes it). */
|
|
462
|
+
async stitchHeads(stitch) {
|
|
463
|
+
return (await this.engine.stitchHeads(CID.parse(stitch))).map((h) => ({
|
|
464
|
+
publisher: h.publisher,
|
|
465
|
+
repo: h.repo,
|
|
466
|
+
head: toHex(h.head.multihash.digest)
|
|
467
|
+
}));
|
|
468
|
+
}
|
|
429
469
|
/**
|
|
430
470
|
* Lists every record currently committed under a repo, resolved
|
|
431
471
|
* from the publisher's on-chain root — useful for verifying what actually
|
|
@@ -637,6 +677,27 @@ var Fangorn = class Fangorn {
|
|
|
637
677
|
return address;
|
|
638
678
|
}
|
|
639
679
|
};
|
|
680
|
+
/**
|
|
681
|
+
* Which repos a stitch covers. A pattern is `publisher/repo`, a repo name (every
|
|
682
|
+
* publisher's), `*` (every repo), or `/regex/` matched against `publisher/repo`
|
|
683
|
+
* (publisher lowercased).
|
|
684
|
+
*/
|
|
685
|
+
function stitchFilter(patterns) {
|
|
686
|
+
const tests = patterns.map((p) => {
|
|
687
|
+
if (p === "*") return () => true;
|
|
688
|
+
if (p.length > 2 && p.startsWith("/") && p.endsWith("/")) {
|
|
689
|
+
const re = new RegExp(p.slice(1, -1));
|
|
690
|
+
return (id) => re.test(id);
|
|
691
|
+
}
|
|
692
|
+
const i = p.indexOf("/");
|
|
693
|
+
const want = i < 0 ? null : `${p.slice(0, i).toLowerCase()}${p.slice(i)}`;
|
|
694
|
+
return (id, repo) => want ? id === want : repo === p;
|
|
695
|
+
});
|
|
696
|
+
return (publisher, repo) => {
|
|
697
|
+
const id = `${publisher.toLowerCase()}/${repo}`;
|
|
698
|
+
return tests.some((t) => t(id, repo));
|
|
699
|
+
};
|
|
700
|
+
}
|
|
640
701
|
|
|
641
702
|
//#endregion
|
|
642
|
-
export { CARD_RECORD, FANGORN_REPO_EXTENSION, Fangorn };
|
|
703
|
+
export { CARD_RECORD, FANGORN_REPO_EXTENSION, Fangorn, stitchFilter };
|