@fangorn-network/sdk 2026.7.12 → 2026.7.14
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/README.md +104 -69
- package/lib/cli/cli.js +26 -19
- package/lib/cli/index.d.ts +13 -13
- package/lib/config.d.ts +93 -92
- package/lib/contracts/data-registry/abi.d.ts +207 -35
- package/lib/contracts/data-registry/index.js +4 -4
- package/lib/contracts/index.d.ts +3 -1
- package/lib/contracts/index.js +3 -1
- package/lib/contracts/settlement-registry/abi.d.ts +47 -0
- package/lib/contracts/settlement-registry/abi.js +48 -0
- package/lib/contracts/settlement-registry/index.d.ts +25 -0
- package/lib/contracts/settlement-registry/index.js +40 -0
- package/lib/crypto/aes.d.ts +1 -8
- package/lib/crypto/aes.js +2 -34
- package/lib/crypto/encryption.d.ts +112 -26
- package/lib/crypto/encryption.js +105 -21
- package/lib/engine/car.d.ts +10 -0
- package/lib/engine/car.js +37 -0
- package/lib/engine/graph.d.ts +70 -0
- package/lib/engine/graph.js +73 -0
- package/lib/engine/index.d.ts +109 -70
- package/lib/engine/index.js +296 -226
- package/lib/engine/test-helpers.d.ts +43 -0
- package/lib/engine/test-helpers.js +69 -0
- package/lib/fangorn.d.ts +28 -25
- package/lib/fangorn.js +118 -83
- package/lib/harness/index.d.ts +4 -3
- package/lib/harness/index.js +9 -3
- package/lib/index.d.ts +3 -3
- package/lib/index.js +2 -2
- package/lib/node_modules/{.pnpm/@noble_ciphers@1.3.0/node_modules/@noble → @noble}/ciphers/esm/_polyval.js +1 -1
- package/lib/node_modules/{.pnpm/@noble_ciphers@1.3.0/node_modules/@noble → @noble}/ciphers/esm/aes.js +1 -1
- package/lib/node_modules/{.pnpm/@noble_ciphers@1.3.0/node_modules/@noble → @noble}/ciphers/esm/utils.js +1 -1
- package/lib/node_modules/{.pnpm/@noble_curves@1.9.7/node_modules/@noble → @noble}/curves/esm/abstract/curve.js +1 -1
- package/lib/node_modules/{.pnpm/@noble_curves@1.9.7/node_modules/@noble → @noble}/curves/esm/abstract/edwards.js +1 -1
- package/lib/node_modules/{.pnpm/@noble_curves@1.9.7/node_modules/@noble → @noble}/curves/esm/abstract/modular.js +1 -1
- package/lib/node_modules/{.pnpm/@noble_curves@1.9.7/node_modules/@noble → @noble}/curves/esm/abstract/montgomery.js +1 -1
- package/lib/node_modules/{.pnpm/@noble_curves@1.9.7/node_modules/@noble → @noble}/curves/esm/ed25519.js +1 -1
- package/lib/node_modules/{.pnpm/@noble_curves@1.9.7/node_modules/@noble → @noble}/curves/esm/utils.js +1 -1
- package/lib/providers/storage/car.js +2 -1
- package/lib/providers/storage/pinata.d.ts +16 -9
- package/lib/providers/storage/pinata.js +34 -25
- package/lib/providers/storage/types.d.ts +18 -8
- package/lib/{roles/repo → repo}/index.d.ts +1 -1
- package/lib/{roles/repo → repo}/index.js +1 -1
- package/lib/test/testbed.d.ts +9 -7
- package/lib/test/testbed.js +3 -2
- package/package.json +3 -9
- package/lib/ crypto/constants.d.ts +0 -4
- package/lib/ crypto/constants.js +0 -5
- package/lib/ crypto/merkle.d.ts +0 -10
- package/lib/ crypto/merkle.js +0 -34
- package/lib/ crypto/utils.d.ts +0 -1
- package/lib/ crypto/utils.js +0 -1
- package/lib/builders/a2aCardBuilder.d.ts +0 -28
- package/lib/builders/a2aCardBuilder.js +0 -105
- package/lib/engine/blockstore.d.ts +0 -24
- package/lib/engine/blockstore.js +0 -85
- package/lib/roles/index.d.ts +0 -1
- package/lib/roles/index.js +0 -1
- package/lib/test/car_smoke.d.ts +0 -1
- package/lib/test/car_smoke.js +0 -81
- package/lib/test/cleanup-embeddings-testdata.d.ts +0 -1
- package/lib/test/cleanup-embeddings-testdata.js +0 -75
- package/lib/test/index.d.ts +0 -10
- package/lib/test/index.js +0 -27
- package/lib/test/setup-embeddings-testdata.d.ts +0 -11
- package/lib/test/setup-embeddings-testdata.js +0 -155
- package/lib/utils/index.d.ts +0 -11
- package/lib/utils/index.js +0 -29
- package/lib/utils/manifest.d.ts +0 -23
- package/lib/utils/manifest.js +0 -77
package/lib/engine/index.js
CHANGED
|
@@ -1,10 +1,8 @@
|
|
|
1
|
+
import { buildPages, decodeBlock, encodeBlock, readPages } from "./graph.js";
|
|
2
|
+
import { packCar, readCar } from "./car.js";
|
|
1
3
|
import { CID } from "multiformats/cid";
|
|
2
|
-
import * as dagCbor from "@ipld/dag-cbor";
|
|
3
|
-
import * as Batch from "@web3-storage/pail/batch";
|
|
4
|
-
import { entries } from "@web3-storage/pail";
|
|
5
4
|
import { sha256 } from "multiformats/hashes/sha2";
|
|
6
5
|
import * as Digest from "multiformats/hashes/digest";
|
|
7
|
-
import { ShardBlock } from "@web3-storage/pail/shard";
|
|
8
6
|
|
|
9
7
|
//#region src/engine/index.ts
|
|
10
8
|
var MetagraphRegistry = class {
|
|
@@ -32,36 +30,35 @@ var MetagraphRegistry = class {
|
|
|
32
30
|
}
|
|
33
31
|
};
|
|
34
32
|
const ZERO_BYTES32 = "0x0000000000000000000000000000000000000000000000000000000000000000";
|
|
33
|
+
/**
|
|
34
|
+
* Upper bound on a namespace name's length. Namespaces are keys of the root
|
|
35
|
+
* map block, so this is just a sanity bound keeping that block small and
|
|
36
|
+
* rejecting garbage input early.
|
|
37
|
+
*/
|
|
38
|
+
const MAX_NAMESPACE_LENGTH = 256;
|
|
39
|
+
/** Reject invalid namespace names up front with a clear error. */
|
|
40
|
+
function assertValidNamespace(namespace) {
|
|
41
|
+
if (typeof namespace !== "string" || namespace.length === 0) throw new Error("namespace must be a non-empty string");
|
|
42
|
+
if (namespace.length > MAX_NAMESPACE_LENGTH) throw new Error(`namespace exceeds the maximum length of ${MAX_NAMESPACE_LENGTH.toString()} characters (got ${namespace.length.toString()}).`);
|
|
43
|
+
}
|
|
35
44
|
var FangornEngine = class {
|
|
36
|
-
|
|
37
|
-
|
|
45
|
+
/**
|
|
46
|
+
* Local block cache. Written blocks land here immediately; remote blocks
|
|
47
|
+
* are pulled in whole-CAR-at-a-time by `loadCar`. Content addressing makes
|
|
48
|
+
* the cache trivially coherent.
|
|
49
|
+
*/
|
|
50
|
+
cache = /* @__PURE__ */ new Map();
|
|
51
|
+
/** Commits whose CAR has already been loaded into the cache. */
|
|
52
|
+
loadedCars = /* @__PURE__ */ new Set();
|
|
53
|
+
constructor(storage, metagraph, registryClient) {
|
|
54
|
+
this.storage = storage;
|
|
38
55
|
this.metagraph = metagraph;
|
|
39
56
|
this.registryClient = registryClient;
|
|
40
57
|
}
|
|
41
|
-
async encodeBlock(obj) {
|
|
42
|
-
const bytes = dagCbor.encode(obj);
|
|
43
|
-
const hash = await sha256.digest(bytes);
|
|
44
|
-
return {
|
|
45
|
-
cid: CID.createV1(dagCbor.code, hash),
|
|
46
|
-
bytes
|
|
47
|
-
};
|
|
48
|
-
}
|
|
49
|
-
async readBlockBytes(cid) {
|
|
50
|
-
const chunks = [];
|
|
51
|
-
for await (const chunk of this.blockstore.get(cid)) chunks.push(chunk);
|
|
52
|
-
const totalLength = chunks.reduce((acc, c) => acc + c.length, 0);
|
|
53
|
-
const flatBytes = new Uint8Array(totalLength);
|
|
54
|
-
let offset = 0;
|
|
55
|
-
for (const chunk of chunks) {
|
|
56
|
-
flatBytes.set(chunk, offset);
|
|
57
|
-
offset += chunk.length;
|
|
58
|
-
}
|
|
59
|
-
return flatBytes;
|
|
60
|
-
}
|
|
61
58
|
/**
|
|
62
59
|
* Reconstructs the CID a commit's raw digest hex refers to. The contract only
|
|
63
|
-
* stores the bare 32-byte sha256 digest (see
|
|
64
|
-
* CID must wrap that digest directly via Digest.create — hashing it again
|
|
60
|
+
* stores the bare 32-byte sha256 digest (see commitStateRoot), so rebuilding
|
|
61
|
+
* the CID must wrap that digest directly via Digest.create — hashing it again
|
|
65
62
|
* with sha256.digest() would produce an unrelated CID pointing at nothing.
|
|
66
63
|
*/
|
|
67
64
|
hexToRootCid(hex) {
|
|
@@ -70,135 +67,203 @@ var FangornEngine = class {
|
|
|
70
67
|
const multihash = Digest.create(sha256.code, rawDigestBytes);
|
|
71
68
|
return CID.createV1(113, multihash);
|
|
72
69
|
}
|
|
70
|
+
/** Read and decode a commit object by CID (directly addressable — no CAR needed). */
|
|
71
|
+
async getCommit(commitCid) {
|
|
72
|
+
const key = commitCid.toString();
|
|
73
|
+
let bytes = this.cache.get(key);
|
|
74
|
+
if (!bytes) {
|
|
75
|
+
bytes = await this.storage.getRawBlock(key);
|
|
76
|
+
this.cache.set(key, bytes);
|
|
77
|
+
}
|
|
78
|
+
const decoded = decodeBlock(bytes);
|
|
79
|
+
if (decoded.pailRoot !== void 0) throw new Error(`commit ${key} predates the v2 data layer (pail-era). Reset the on-chain head (\`fangorn reset\`) and re-publish.`);
|
|
80
|
+
return {
|
|
81
|
+
root: CID.parse(String(decoded.root)),
|
|
82
|
+
parents: (decoded.parents ?? []).map((p) => CID.parse(String(p))),
|
|
83
|
+
timestamp: decoded.timestamp ?? 0,
|
|
84
|
+
message: decoded.message ?? "",
|
|
85
|
+
car: decoded.car ?? ""
|
|
86
|
+
};
|
|
87
|
+
}
|
|
88
|
+
/** Pull every block of `commit`'s CAR into the local cache. */
|
|
89
|
+
async loadCar(commitCid, commit) {
|
|
90
|
+
const bytes = await this.storage.getFile(commit.car);
|
|
91
|
+
for (const block of await readCar(bytes)) this.cache.set(block.cid.toString(), block.bytes);
|
|
92
|
+
this.loadedCars.add(commitCid.toString());
|
|
93
|
+
}
|
|
94
|
+
/**
|
|
95
|
+
* Resolve a data block: local cache first, then walk the commit chain from
|
|
96
|
+
* `hint`, loading one ancestor CAR at a time until the block turns up.
|
|
97
|
+
*/
|
|
98
|
+
async getBlock(cid, hint) {
|
|
99
|
+
const key = cid.toString();
|
|
100
|
+
const hit = this.cache.get(key);
|
|
101
|
+
if (hit) return hit;
|
|
102
|
+
let cursor = hint;
|
|
103
|
+
while (cursor) {
|
|
104
|
+
const commit = await this.getCommit(cursor);
|
|
105
|
+
if (!this.loadedCars.has(cursor.toString())) {
|
|
106
|
+
await this.loadCar(cursor, commit);
|
|
107
|
+
const found = this.cache.get(key);
|
|
108
|
+
if (found) return found;
|
|
109
|
+
}
|
|
110
|
+
cursor = commit.parents.length ? commit.parents[0] : null;
|
|
111
|
+
}
|
|
112
|
+
throw new Error(`Block payload missing for key: ${key}`);
|
|
113
|
+
}
|
|
114
|
+
putLocal(block) {
|
|
115
|
+
this.cache.set(block.cid.toString(), block.bytes);
|
|
116
|
+
}
|
|
73
117
|
/** Reconstruct the publisher's current on-chain head as a commit CID, or null if none. */
|
|
74
118
|
async resolveHeadCommit(publisher) {
|
|
75
119
|
const currentHead = await this.registryClient.getNamespaceHead(publisher);
|
|
76
|
-
if (
|
|
120
|
+
if (currentHead === ZERO_BYTES32) return null;
|
|
77
121
|
return this.hexToRootCid(currentHead);
|
|
78
122
|
}
|
|
79
|
-
/**
|
|
80
|
-
async
|
|
81
|
-
const
|
|
123
|
+
/** Decode the root map behind a commit. */
|
|
124
|
+
async rootMapAt(commitCid) {
|
|
125
|
+
const commit = await this.getCommit(commitCid);
|
|
126
|
+
const raw = decodeBlock(await this.getBlock(commit.root, commitCid));
|
|
127
|
+
const rootMap = {};
|
|
128
|
+
for (const [ns, link] of Object.entries(raw)) rootMap[ns] = CID.parse(String(link));
|
|
129
|
+
return rootMap;
|
|
130
|
+
}
|
|
131
|
+
/** The full vertex/edge link sets one commit records for `namespace`. */
|
|
132
|
+
async treeLinksAt(commitCid, namespace) {
|
|
133
|
+
const rootMap = await this.rootMapAt(commitCid);
|
|
134
|
+
if (!(namespace in rootMap)) return {
|
|
135
|
+
vertexLinks: [],
|
|
136
|
+
edgeLinks: [],
|
|
137
|
+
structureCids: /* @__PURE__ */ new Set()
|
|
138
|
+
};
|
|
139
|
+
const treeLink = rootMap[namespace];
|
|
140
|
+
const tree = decodeBlock(await this.getBlock(treeLink, commitCid));
|
|
141
|
+
const get = (cid) => this.getBlock(cid, commitCid);
|
|
82
142
|
return {
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
143
|
+
vertexLinks: (await readPages(tree.vertices.map((c) => CID.parse(String(c))), get)).map((c) => CID.parse(String(c))),
|
|
144
|
+
edgeLinks: (await readPages(tree.edges.map((c) => CID.parse(String(c))), get)).map((c) => CID.parse(String(c))),
|
|
145
|
+
structureCids: new Set([
|
|
146
|
+
treeLink.toString(),
|
|
147
|
+
...tree.vertices.map(String),
|
|
148
|
+
...tree.edges.map(String)
|
|
149
|
+
])
|
|
87
150
|
};
|
|
88
151
|
}
|
|
89
|
-
/** Resolve the pail tree root behind the publisher's on-chain head commit, or null. */
|
|
90
|
-
async resolvePailRoot(publisher) {
|
|
91
|
-
const commitCid = await this.resolveHeadCommit(publisher);
|
|
92
|
-
if (!commitCid) return null;
|
|
93
|
-
return (await this.getCommit(commitCid)).pailRoot;
|
|
94
|
-
}
|
|
95
152
|
/**
|
|
96
|
-
*
|
|
97
|
-
*
|
|
98
|
-
*
|
|
153
|
+
* Build a new commit on top of `base` — entirely in memory, then persisted
|
|
154
|
+
* as exactly TWO uploads: one CAR file holding every block this commit
|
|
155
|
+
* introduced (git's packfile), and the small commit block itself (stored
|
|
156
|
+
* individually so the on-chain digest resolves without any index).
|
|
157
|
+
*
|
|
158
|
+
* The new namespace state is the parent state plus the staged graph;
|
|
159
|
+
* unchanged blocks are shared byte-for-byte with ancestors and are NOT
|
|
160
|
+
* re-uploaded. Does not touch the chain — `pushCommit` settles it.
|
|
99
161
|
*/
|
|
100
|
-
async
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
162
|
+
async createCommit(opts) {
|
|
163
|
+
assertValidNamespace(opts.namespace);
|
|
164
|
+
const { namespace, base } = opts;
|
|
165
|
+
const rootMap = base ? await this.rootMapAt(base) : {};
|
|
166
|
+
const old = base ? await this.treeLinksAt(base, namespace) : {
|
|
167
|
+
vertexLinks: [],
|
|
168
|
+
edgeLinks: [],
|
|
169
|
+
structureCids: /* @__PURE__ */ new Set()
|
|
170
|
+
};
|
|
171
|
+
const oldVertexSet = new Set(old.vertexLinks.map(String));
|
|
172
|
+
const oldEdgeSet = new Set(old.edgeLinks.map(String));
|
|
173
|
+
const carBlocks = [];
|
|
174
|
+
const vertexCids = {};
|
|
175
|
+
const idInfo = /* @__PURE__ */ new Map();
|
|
176
|
+
const vertexLinks = opts.replace ? [] : [...old.vertexLinks];
|
|
177
|
+
const newVertexSet = new Set(vertexLinks.map(String));
|
|
178
|
+
for (const v of opts.vertices) {
|
|
179
|
+
if (!this.metagraph.validateVertex(namespace, v.schemaId, v.payload)) throw new Error(`Schema violation for vertex type [${v.schemaId}] in namespace [${namespace}]`);
|
|
180
|
+
const block = await encodeBlock({
|
|
181
|
+
schemaId: v.schemaId,
|
|
182
|
+
payload: v.payload
|
|
183
|
+
});
|
|
184
|
+
idInfo.set(v.id, {
|
|
185
|
+
cid: block.cid,
|
|
186
|
+
tag: v.schemaId
|
|
187
|
+
});
|
|
188
|
+
vertexCids[v.id] = block.cid.toString();
|
|
189
|
+
const key = block.cid.toString();
|
|
190
|
+
if (!newVertexSet.has(key)) {
|
|
191
|
+
newVertexSet.add(key);
|
|
192
|
+
vertexLinks.push(block.cid);
|
|
193
|
+
if (!oldVertexSet.has(key)) carBlocks.push(block);
|
|
194
|
+
}
|
|
107
195
|
}
|
|
108
|
-
|
|
196
|
+
const resolveEndpoint = (ref) => {
|
|
197
|
+
const info = idInfo.get(ref);
|
|
198
|
+
if (info) return info;
|
|
109
199
|
try {
|
|
110
200
|
return {
|
|
111
|
-
cid,
|
|
112
|
-
|
|
201
|
+
cid: CID.parse(ref),
|
|
202
|
+
tag: null
|
|
113
203
|
};
|
|
114
|
-
} catch
|
|
115
|
-
|
|
116
|
-
const freshInit = await ShardBlock.create();
|
|
117
|
-
return {
|
|
118
|
-
cid: freshInit.cid,
|
|
119
|
-
bytes: freshInit.bytes
|
|
120
|
-
};
|
|
121
|
-
}
|
|
122
|
-
throw error;
|
|
204
|
+
} catch {
|
|
205
|
+
throw new Error(`edge references unknown local id (or invalid CID): ${ref}`);
|
|
123
206
|
}
|
|
124
|
-
} }, activePailRoot);
|
|
125
|
-
}
|
|
126
|
-
/**
|
|
127
|
-
* Open a batch that continues the publisher's on-chain head (immediate-write
|
|
128
|
-
* path). Returns the base commit CID and raw head hex so the caller can parent
|
|
129
|
-
* the next commit and pass the expected old root to the on-chain CAS.
|
|
130
|
-
*/
|
|
131
|
-
async createBatch(publisher) {
|
|
132
|
-
const contractHeadHex = await this.registryClient.getNamespaceHead(publisher) || ZERO_BYTES32;
|
|
133
|
-
const baseCommitCid = contractHeadHex === ZERO_BYTES32 ? null : this.hexToRootCid(contractHeadHex);
|
|
134
|
-
const basePailRoot = baseCommitCid ? (await this.getCommit(baseCommitCid)).pailRoot : null;
|
|
135
|
-
return {
|
|
136
|
-
batch: await this.openBatch(basePailRoot),
|
|
137
|
-
contractHeadHex,
|
|
138
|
-
baseCommitCid
|
|
139
207
|
};
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
const
|
|
159
|
-
await
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
async writeCommit(pailRoot, parents, message) {
|
|
178
|
-
const commitObj = {
|
|
179
|
-
pailRoot,
|
|
180
|
-
parents,
|
|
208
|
+
const edgeLinks = opts.replace ? [] : [...old.edgeLinks];
|
|
209
|
+
const newEdgeSet = new Set(edgeLinks.map(String));
|
|
210
|
+
for (const e of opts.edges) {
|
|
211
|
+
const source = resolveEndpoint(e.from);
|
|
212
|
+
const target = resolveEndpoint(e.to);
|
|
213
|
+
if (source.tag && target.tag && !this.metagraph.validateEdge(namespace, source.tag, e.relation, target.tag)) throw new Error(`Invalid structural link relation [${e.relation}] in namespace [${namespace}]`);
|
|
214
|
+
const block = await encodeBlock({
|
|
215
|
+
source: source.cid,
|
|
216
|
+
relation: e.relation,
|
|
217
|
+
target: target.cid
|
|
218
|
+
});
|
|
219
|
+
const key = block.cid.toString();
|
|
220
|
+
if (!newEdgeSet.has(key)) {
|
|
221
|
+
newEdgeSet.add(key);
|
|
222
|
+
edgeLinks.push(block.cid);
|
|
223
|
+
if (!oldEdgeSet.has(key)) carBlocks.push(block);
|
|
224
|
+
}
|
|
225
|
+
}
|
|
226
|
+
const { pages: vertexPages, pageLinks: vertexPageLinks } = await buildPages(vertexLinks);
|
|
227
|
+
const { pages: edgePages, pageLinks: edgePageLinks } = await buildPages(edgeLinks);
|
|
228
|
+
for (const page of [...vertexPages, ...edgePages]) if (!old.structureCids.has(page.cid.toString())) carBlocks.push(page);
|
|
229
|
+
const treeBlock = await encodeBlock({
|
|
230
|
+
vertices: vertexPageLinks,
|
|
231
|
+
edges: edgePageLinks
|
|
232
|
+
});
|
|
233
|
+
if (!old.structureCids.has(treeBlock.cid.toString())) carBlocks.push(treeBlock);
|
|
234
|
+
const rootBlock = await encodeBlock({
|
|
235
|
+
...rootMap,
|
|
236
|
+
[namespace]: treeBlock.cid
|
|
237
|
+
});
|
|
238
|
+
carBlocks.push(rootBlock);
|
|
239
|
+
for (const block of carBlocks) this.putLocal(block);
|
|
240
|
+
const carBytes = await packCar(rootBlock.cid, carBlocks);
|
|
241
|
+
const carUri = await this.storage.putFile(carBytes, `${rootBlock.cid.toString()}.car`);
|
|
242
|
+
const commitBlock = await encodeBlock({
|
|
243
|
+
root: rootBlock.cid,
|
|
244
|
+
parents: base ? [base] : [],
|
|
181
245
|
timestamp: Date.now(),
|
|
182
|
-
message
|
|
246
|
+
message: opts.message,
|
|
247
|
+
car: carUri
|
|
248
|
+
});
|
|
249
|
+
await this.storage.putBlock(commitBlock);
|
|
250
|
+
this.putLocal(commitBlock);
|
|
251
|
+
this.loadedCars.add(commitBlock.cid.toString());
|
|
252
|
+
return {
|
|
253
|
+
commitCid: commitBlock.cid,
|
|
254
|
+
root: rootBlock.cid,
|
|
255
|
+
vertexCids
|
|
183
256
|
};
|
|
184
|
-
const { cid, bytes } = await this.encodeBlock(commitObj);
|
|
185
|
-
await this.blockstore.put(cid, bytes);
|
|
186
|
-
return cid;
|
|
187
|
-
}
|
|
188
|
-
/** Upload every block written locally since the last flush to the remote backend. */
|
|
189
|
-
async flush() {
|
|
190
|
-
if (typeof this.blockstore.flush === "function") await this.blockstore.flush();
|
|
191
257
|
}
|
|
192
258
|
/**
|
|
193
259
|
* Settle a local commit as the publisher's on-chain head — the permissioned,
|
|
194
|
-
* git `push` step.
|
|
195
|
-
*
|
|
196
|
-
*
|
|
197
|
-
*
|
|
260
|
+
* git `push` step. The commit and its CAR are already durable in storage
|
|
261
|
+
* (createCommit uploads them), so this is just the compare-and-swap against
|
|
262
|
+
* the current head. Unless `force`, the on-chain head must be an ancestor of
|
|
263
|
+
* `commitCid` (fast-forward only).
|
|
198
264
|
*/
|
|
199
265
|
async pushCommit(publisher, commitCid, opts) {
|
|
200
|
-
await this.
|
|
201
|
-
const onChainHex = await this.registryClient.getNamespaceHead(publisher) || ZERO_BYTES32;
|
|
266
|
+
const onChainHex = await this.registryClient.getNamespaceHead(publisher);
|
|
202
267
|
const onChainCommit = onChainHex === ZERO_BYTES32 ? null : this.hexToRootCid(onChainHex);
|
|
203
268
|
if (!opts?.force && onChainCommit && onChainCommit.toString() !== commitCid.toString()) {
|
|
204
269
|
if (!await this.isAncestor(onChainCommit, commitCid)) throw new Error("non-fast-forward: the on-chain tip is not an ancestor of this commit — clone/rebuild onto the current tip, or push with force.");
|
|
@@ -231,43 +296,61 @@ var FangornEngine = class {
|
|
|
231
296
|
commitCidFromRootHex(hex) {
|
|
232
297
|
return this.hexToRootCid(hex).toString();
|
|
233
298
|
}
|
|
299
|
+
/** Decode a vertex block into the public read shape. */
|
|
300
|
+
async decodeVertex(link, hint) {
|
|
301
|
+
const decoded = decodeBlock(await this.getBlock(link, hint));
|
|
302
|
+
return {
|
|
303
|
+
cid: link.toString(),
|
|
304
|
+
schemaId: decoded.schemaId,
|
|
305
|
+
payload: decoded.payload
|
|
306
|
+
};
|
|
307
|
+
}
|
|
308
|
+
/** Decode an edge block into the public read shape. */
|
|
309
|
+
async decodeEdge(link, hint) {
|
|
310
|
+
const decoded = decodeBlock(await this.getBlock(link, hint));
|
|
311
|
+
return {
|
|
312
|
+
sourceCid: String(decoded.source),
|
|
313
|
+
relation: decoded.relation,
|
|
314
|
+
targetCid: String(decoded.target)
|
|
315
|
+
};
|
|
316
|
+
}
|
|
234
317
|
/**
|
|
235
318
|
* Net change to a single namespace between two on-chain roots — the core of
|
|
236
|
-
* the subscription light-client.
|
|
237
|
-
*
|
|
238
|
-
*
|
|
319
|
+
* the subscription light-client. Namespace trees are explicit link sets, so
|
|
320
|
+
* the diff is a plain set difference; only blocks that actually changed are
|
|
321
|
+
* decoded (each side resolves through its own commit's CAR chain).
|
|
239
322
|
*
|
|
240
323
|
* Diffing root-to-root (rather than walking commits) is deliberately robust:
|
|
241
324
|
* it yields the correct net delta even across a force-push / non-fast-forward
|
|
242
325
|
* reorg — exactly what an index builder needs (which vertices to (re)embed,
|
|
243
|
-
* which to evict).
|
|
244
|
-
* and all edges are recovered from the pail key alone (no extra fetch), since
|
|
245
|
-
* an edge key already encodes `source|relation|target`.
|
|
326
|
+
* which to evict).
|
|
246
327
|
*/
|
|
247
328
|
async namespaceDiff(oldRootHex, newRootHex, namespace) {
|
|
248
|
-
const
|
|
249
|
-
const
|
|
250
|
-
const
|
|
251
|
-
|
|
329
|
+
const newCommit = newRootHex === ZERO_BYTES32 ? null : this.hexToRootCid(newRootHex);
|
|
330
|
+
const oldCommit = oldRootHex && oldRootHex !== ZERO_BYTES32 ? this.hexToRootCid(oldRootHex) : null;
|
|
331
|
+
const after = newCommit ? await this.treeLinksAt(newCommit, namespace) : {
|
|
332
|
+
vertexLinks: [],
|
|
333
|
+
edgeLinks: []
|
|
334
|
+
};
|
|
335
|
+
const before = oldCommit ? await this.treeLinksAt(oldCommit, namespace) : {
|
|
336
|
+
vertexLinks: [],
|
|
337
|
+
edgeLinks: []
|
|
338
|
+
};
|
|
339
|
+
const beforeV = new Set(before.vertexLinks.map(String));
|
|
340
|
+
const beforeE = new Set(before.edgeLinks.map(String));
|
|
341
|
+
const afterV = new Set(after.vertexLinks.map(String));
|
|
342
|
+
const afterE = new Set(after.edgeLinks.map(String));
|
|
252
343
|
const addedVertices = [];
|
|
253
344
|
const addedEdges = [];
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
if (
|
|
258
|
-
if (key.startsWith(`${prefix}v/`)) {
|
|
259
|
-
const decoded = dagCbor.decode(await this.readBlockBytes(CID.parse(cidStr)));
|
|
260
|
-
addedVertices.push({
|
|
261
|
-
cid: cidStr,
|
|
262
|
-
schemaId: decoded.schemaId,
|
|
263
|
-
payload: decoded.payload
|
|
264
|
-
});
|
|
265
|
-
} else if (key.startsWith(`${prefix}e/`)) addedEdges.push(this.edgeFromKey(key, prefix));
|
|
345
|
+
if (after.vertexLinks.length > 0 || after.edgeLinks.length > 0) {
|
|
346
|
+
if (!newCommit) throw new Error("Missing commit context required to decode graph changes");
|
|
347
|
+
for (const link of after.vertexLinks) if (!beforeV.has(link.toString())) addedVertices.push(await this.decodeVertex(link, newCommit));
|
|
348
|
+
for (const link of after.edgeLinks) if (!beforeE.has(link.toString())) addedEdges.push(await this.decodeEdge(link, newCommit));
|
|
266
349
|
}
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
350
|
+
const removedVertexCids = before.vertexLinks.map(String).filter((c) => !afterV.has(c));
|
|
351
|
+
const removedEdges = [];
|
|
352
|
+
if (oldCommit) {
|
|
353
|
+
for (const link of before.edgeLinks) if (!afterE.has(link.toString())) removedEdges.push(await this.decodeEdge(link, oldCommit));
|
|
271
354
|
}
|
|
272
355
|
return {
|
|
273
356
|
addedVertices,
|
|
@@ -276,92 +359,79 @@ var FangornEngine = class {
|
|
|
276
359
|
removedEdges
|
|
277
360
|
};
|
|
278
361
|
}
|
|
279
|
-
/**
|
|
280
|
-
edgeFromKey(key, prefix) {
|
|
281
|
-
const [sourceCid, relation, targetCid] = key.slice(`${prefix}e/`.length).split("|");
|
|
282
|
-
return {
|
|
283
|
-
sourceCid,
|
|
284
|
-
relation,
|
|
285
|
-
targetCid
|
|
286
|
-
};
|
|
287
|
-
}
|
|
288
|
-
/** Diff a commit against its first parent, by namespaced pail key. */
|
|
362
|
+
/** Diff a commit against its first parent, across every namespace. */
|
|
289
363
|
async diffCommit(commitCid) {
|
|
290
364
|
const commit = await this.getCommit(commitCid);
|
|
291
|
-
const
|
|
292
|
-
const
|
|
293
|
-
const
|
|
294
|
-
const
|
|
365
|
+
const parent = commit.parents.length ? commit.parents[0] : null;
|
|
366
|
+
const childRoot = await this.rootMapAt(commitCid);
|
|
367
|
+
const parentRoot = parent ? await this.rootMapAt(parent) : {};
|
|
368
|
+
const added = [];
|
|
369
|
+
const removed = [];
|
|
370
|
+
const namespaces = new Set([...Object.keys(childRoot), ...Object.keys(parentRoot)]);
|
|
371
|
+
for (const ns of namespaces) {
|
|
372
|
+
const inParent = ns in parentRoot;
|
|
373
|
+
const inChild = ns in childRoot;
|
|
374
|
+
if (inParent && inChild && String(parentRoot[ns]) === String(childRoot[ns])) continue;
|
|
375
|
+
const child = inChild ? await this.treeLinksAt(commitCid, ns) : {
|
|
376
|
+
vertexLinks: [],
|
|
377
|
+
edgeLinks: []
|
|
378
|
+
};
|
|
379
|
+
const par = parent && inParent ? await this.treeLinksAt(parent, ns) : {
|
|
380
|
+
vertexLinks: [],
|
|
381
|
+
edgeLinks: []
|
|
382
|
+
};
|
|
383
|
+
const parV = new Set(par.vertexLinks.map(String));
|
|
384
|
+
const parE = new Set(par.edgeLinks.map(String));
|
|
385
|
+
const childV = new Set(child.vertexLinks.map(String));
|
|
386
|
+
const childE = new Set(child.edgeLinks.map(String));
|
|
387
|
+
for (const c of childV) if (!parV.has(c)) added.push(`${ns}/v/${c}`);
|
|
388
|
+
for (const c of childE) if (!parE.has(c)) added.push(`${ns}/e/${c}`);
|
|
389
|
+
for (const c of parV) if (!childV.has(c)) removed.push(`${ns}/v/${c}`);
|
|
390
|
+
for (const c of parE) if (!childE.has(c)) removed.push(`${ns}/e/${c}`);
|
|
391
|
+
}
|
|
295
392
|
return {
|
|
296
393
|
message: commit.message,
|
|
297
394
|
parents: commit.parents.map((c) => c.toString()),
|
|
298
395
|
timestamp: commit.timestamp,
|
|
299
|
-
|
|
396
|
+
root: commit.root.toString(),
|
|
300
397
|
added: added.sort(),
|
|
301
398
|
removed: removed.sort()
|
|
302
399
|
};
|
|
303
400
|
}
|
|
304
|
-
/**
|
|
305
|
-
async entriesAt(pailRoot, prefix = "") {
|
|
306
|
-
const blocks = { get: async (cid) => ({
|
|
307
|
-
cid,
|
|
308
|
-
bytes: await this.readBlockBytes(cid)
|
|
309
|
-
}) };
|
|
310
|
-
const out = /* @__PURE__ */ new Map();
|
|
311
|
-
for await (const [key, value] of entries(blocks, pailRoot, { prefix })) {
|
|
312
|
-
const linkCid = CID.asCID(value);
|
|
313
|
-
if (linkCid) out.set(key, linkCid.toString());
|
|
314
|
-
}
|
|
315
|
-
return out;
|
|
316
|
-
}
|
|
317
|
-
/**
|
|
318
|
-
* Cheap existence check: does anything (including the bare `sys/init`
|
|
319
|
-
* marker) exist under this namespace prefix yet? Short-circuits on the
|
|
320
|
-
* first entry found instead of decoding the whole namespace, unlike
|
|
321
|
-
* listNamespace (which also skips non-CID values like the marker itself).
|
|
322
|
-
*/
|
|
401
|
+
/** Does this namespace exist under the publisher's on-chain root yet? */
|
|
323
402
|
async namespaceExists(namespace, publisher) {
|
|
324
|
-
const
|
|
325
|
-
if (!
|
|
326
|
-
|
|
327
|
-
cid,
|
|
328
|
-
bytes: await this.readBlockBytes(cid)
|
|
329
|
-
}) };
|
|
330
|
-
const prefix = `${namespace}/`;
|
|
331
|
-
for await (const _entry of entries(blocks, rootCid, { prefix })) return true;
|
|
332
|
-
return false;
|
|
403
|
+
const head = await this.resolveHeadCommit(publisher);
|
|
404
|
+
if (!head) return false;
|
|
405
|
+
return namespace in await this.rootMapAt(head);
|
|
333
406
|
}
|
|
334
|
-
/** Lists every vertex and edge currently
|
|
407
|
+
/** Lists every vertex and edge currently committed under a namespace, resolved from the on-chain root. */
|
|
335
408
|
async listNamespace(namespace, publisher) {
|
|
409
|
+
const head = await this.resolveHeadCommit(publisher);
|
|
410
|
+
if (!head) return {
|
|
411
|
+
vertices: [],
|
|
412
|
+
edges: []
|
|
413
|
+
};
|
|
414
|
+
const { vertexLinks, edgeLinks } = await this.treeLinksAt(head, namespace);
|
|
336
415
|
const vertices = [];
|
|
416
|
+
for (const link of vertexLinks) vertices.push(await this.decodeVertex(link, head));
|
|
337
417
|
const edges = [];
|
|
338
|
-
const
|
|
339
|
-
if (!rootCid) return {
|
|
340
|
-
vertices,
|
|
341
|
-
edges
|
|
342
|
-
};
|
|
343
|
-
const blocks = { get: async (cid) => ({
|
|
344
|
-
cid,
|
|
345
|
-
bytes: await this.readBlockBytes(cid)
|
|
346
|
-
}) };
|
|
347
|
-
const prefix = `${namespace}/`;
|
|
348
|
-
for await (const [key, value] of entries(blocks, rootCid, { prefix })) {
|
|
349
|
-
const linkCid = CID.asCID(value);
|
|
350
|
-
if (!linkCid) continue;
|
|
351
|
-
const decoded = dagCbor.decode(await this.readBlockBytes(linkCid));
|
|
352
|
-
if (key.startsWith(`${prefix}v/`)) vertices.push({
|
|
353
|
-
cid: linkCid.toString(),
|
|
354
|
-
schemaId: decoded.schemaId,
|
|
355
|
-
payload: decoded.payload
|
|
356
|
-
});
|
|
357
|
-
else if (key.startsWith(`${prefix}e/`)) edges.push(decoded);
|
|
358
|
-
}
|
|
418
|
+
for (const link of edgeLinks) edges.push(await this.decodeEdge(link, head));
|
|
359
419
|
return {
|
|
360
420
|
vertices,
|
|
361
421
|
edges
|
|
362
422
|
};
|
|
363
423
|
}
|
|
424
|
+
/**
|
|
425
|
+
* Fetch a single vertex by CID, resolving through the publisher's commit
|
|
426
|
+
* CAR chain (vertex blocks are not individually pinned — they live inside
|
|
427
|
+
* commit CARs).
|
|
428
|
+
*/
|
|
429
|
+
async readVertex(cid, publisher) {
|
|
430
|
+
const head = await this.resolveHeadCommit(publisher);
|
|
431
|
+
if (!head) throw new Error(`publisher ${publisher} has no on-chain commits`);
|
|
432
|
+
return this.decodeVertex(CID.parse(cid), head);
|
|
433
|
+
}
|
|
364
434
|
};
|
|
365
435
|
|
|
366
436
|
//#endregion
|
|
367
|
-
export { FangornEngine, MetagraphRegistry };
|
|
437
|
+
export { FangornEngine, MAX_NAMESPACE_LENGTH, MetagraphRegistry, assertValidNamespace };
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
import { DataRegistryClient } from "../contracts/data-registry/index.js";
|
|
2
|
+
import "../contracts/index.js";
|
|
3
|
+
import { MetadataStorage, RawBlock, StorageMeta } from "../providers/storage/types.js";
|
|
4
|
+
import { Hex } from "viem";
|
|
5
|
+
import { CID } from "multiformats/cid";
|
|
6
|
+
|
|
7
|
+
//#region src/engine/test-helpers.d.ts
|
|
8
|
+
declare const ZERO_BYTES32 = "0x0000000000000000000000000000000000000000000000000000000000000000";
|
|
9
|
+
/** The raw 32-byte root hex a commit CID settles to on-chain (bare sha256 digest). */
|
|
10
|
+
declare const rootHex: (commitCid: CID) => string;
|
|
11
|
+
/**
|
|
12
|
+
* In-memory MetadataStorage: individually-pinned blocks + opaque files, with
|
|
13
|
+
* write/read counters — remote writes are the publish cost driver, so tests
|
|
14
|
+
* assert on them directly.
|
|
15
|
+
*/
|
|
16
|
+
declare class MemStorage implements MetadataStorage {
|
|
17
|
+
blocks: Map<string, Uint8Array<ArrayBufferLike>>;
|
|
18
|
+
files: Map<string, Uint8Array<ArrayBufferLike>>;
|
|
19
|
+
/** Remote uploads performed (putBlock + putFile). */
|
|
20
|
+
writes: number;
|
|
21
|
+
/** Remote fetches performed (getRawBlock + getFile). */
|
|
22
|
+
reads: number;
|
|
23
|
+
putBlock(block: RawBlock): Promise<void>;
|
|
24
|
+
putFile(bytes: Uint8Array, name: string): Promise<string>;
|
|
25
|
+
getFile(uri: string): Promise<Uint8Array>;
|
|
26
|
+
getRawBlock(uri: string): Promise<Uint8Array>;
|
|
27
|
+
put(_data: unknown, _meta?: StorageMeta): Promise<string>;
|
|
28
|
+
putMany(_items: {
|
|
29
|
+
data: unknown;
|
|
30
|
+
name: string;
|
|
31
|
+
}[]): Promise<Record<string, string>>;
|
|
32
|
+
get<T>(_uri: string): Promise<T>;
|
|
33
|
+
delete(_uri: string): Promise<void>;
|
|
34
|
+
}
|
|
35
|
+
/** Registry stub holding one publisher head in memory (enough for the engine). */
|
|
36
|
+
declare class StubRegistry {
|
|
37
|
+
head: string;
|
|
38
|
+
getNamespaceHead(_publisher: string): Promise<string>;
|
|
39
|
+
commitStateRoot(_oldRoot: Hex, newRoot: Hex): Promise<Hex>;
|
|
40
|
+
asClient(): DataRegistryClient;
|
|
41
|
+
}
|
|
42
|
+
//#endregion
|
|
43
|
+
export { MemStorage, StubRegistry, ZERO_BYTES32, rootHex };
|