@fangorn-network/sdk 0.1.0-dev
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/LICENSE.md +20 -0
- package/README.md +80 -0
- package/lib/cli/cli.d.ts +2 -0
- package/lib/cli/cli.js +571 -0
- package/lib/cli/index.d.ts +10 -0
- package/lib/cli/index.js +18 -0
- package/lib/cli/sell.d.ts +28 -0
- package/lib/cli/sell.js +95 -0
- package/lib/cli/stage.d.ts +19 -0
- package/lib/cli/stage.js +94 -0
- package/lib/config.d.ts +697 -0
- package/lib/config.js +45 -0
- package/lib/contracts/data-registry/abi.d.ts +442 -0
- package/lib/contracts/data-registry/abi.js +508 -0
- package/lib/contracts/data-registry/index.d.ts +131 -0
- package/lib/contracts/data-registry/index.js +183 -0
- package/lib/contracts/index.d.ts +6 -0
- package/lib/contracts/index.js +6 -0
- package/lib/contracts/logs.d.ts +17 -0
- package/lib/contracts/logs.js +28 -0
- package/lib/contracts/settlement-registry/abi.d.ts +810 -0
- package/lib/contracts/settlement-registry/abi.js +962 -0
- package/lib/contracts/settlement-registry/index.d.ts +143 -0
- package/lib/contracts/settlement-registry/index.js +213 -0
- package/lib/contracts/write.d.ts +59 -0
- package/lib/contracts/write.js +102 -0
- package/lib/crypto/aes.d.ts +19 -0
- package/lib/crypto/aes.js +26 -0
- package/lib/crypto/encryption.d.ts +38 -0
- package/lib/crypto/encryption.js +68 -0
- package/lib/crypto/paid.d.ts +104 -0
- package/lib/crypto/paid.js +147 -0
- package/lib/crypto/rand.d.ts +5 -0
- package/lib/crypto/rand.js +16 -0
- package/lib/crypto/types.d.ts +23 -0
- package/lib/crypto/types.js +1 -0
- package/lib/engine/car.d.ts +14 -0
- package/lib/engine/car.js +42 -0
- package/lib/engine/index.d.ts +206 -0
- package/lib/engine/index.js +377 -0
- package/lib/engine/records.d.ts +121 -0
- package/lib/engine/records.js +239 -0
- package/lib/engine/test-helpers.d.ts +38 -0
- package/lib/engine/test-helpers.js +63 -0
- package/lib/erc8004.d.ts +56 -0
- package/lib/erc8004.js +140 -0
- package/lib/fangorn.d.ts +342 -0
- package/lib/fangorn.js +642 -0
- package/lib/feed.d.ts +34 -0
- package/lib/feed.js +67 -0
- package/lib/index.d.ts +17 -0
- package/lib/index.js +16 -0
- package/lib/node_modules/@jridgewell/sourcemap-codec/dist/sourcemap-codec.js +77 -0
- package/lib/node_modules/@vitest/expect/dist/index.js +1414 -0
- package/lib/node_modules/@vitest/pretty-format/dist/index.js +858 -0
- package/lib/node_modules/@vitest/runner/dist/chunk-tasks.js +51 -0
- package/lib/node_modules/@vitest/runner/dist/index.js +1199 -0
- package/lib/node_modules/@vitest/runner/dist/utils.js +3 -0
- package/lib/node_modules/@vitest/snapshot/dist/index.js +1075 -0
- package/lib/node_modules/@vitest/spy/dist/index.js +353 -0
- package/lib/node_modules/@vitest/utils/dist/chunk-_commonjsHelpers.js +7 -0
- package/lib/node_modules/@vitest/utils/dist/chunk-pathe.M-eThtNZ.js +81 -0
- package/lib/node_modules/@vitest/utils/dist/diff.js +1345 -0
- package/lib/node_modules/@vitest/utils/dist/display.js +534 -0
- package/lib/node_modules/@vitest/utils/dist/error.js +30 -0
- package/lib/node_modules/@vitest/utils/dist/helpers.js +118 -0
- package/lib/node_modules/@vitest/utils/dist/serialize.js +76 -0
- package/lib/node_modules/@vitest/utils/dist/source-map.js +93 -0
- package/lib/node_modules/@vitest/utils/dist/timers.js +36 -0
- package/lib/node_modules/chai/index.js +2874 -0
- package/lib/node_modules/magic-string/dist/magic-string.es.js +939 -0
- package/lib/node_modules/pathe/dist/shared/pathe.M-eThtNZ.js +81 -0
- package/lib/node_modules/tinyrainbow/dist/index.js +85 -0
- package/lib/node_modules/vitest/dist/chunks/_commonjsHelpers.D26ty3Ew.js +5 -0
- package/lib/node_modules/vitest/dist/chunks/date.Bq6ZW5rf.js +50 -0
- package/lib/node_modules/vitest/dist/chunks/utils.DvEY5TfP.js +44 -0
- package/lib/node_modules/vitest/dist/chunks/vi.2VT5v0um.js +2578 -0
- package/lib/providers/storage/car.d.ts +36 -0
- package/lib/providers/storage/car.js +81 -0
- package/lib/providers/storage/index.d.ts +5 -0
- package/lib/providers/storage/index.js +5 -0
- package/lib/providers/storage/pinata.d.ts +53 -0
- package/lib/providers/storage/pinata.js +178 -0
- package/lib/providers/storage/signed-url.d.ts +54 -0
- package/lib/providers/storage/signed-url.js +122 -0
- package/lib/providers/storage/types.d.ts +62 -0
- package/lib/providers/storage/types.js +1 -0
- package/lib/providers/storage/utils.d.ts +30 -0
- package/lib/providers/storage/utils.js +107 -0
- package/lib/repo/index.d.ts +56 -0
- package/lib/repo/index.js +73 -0
- package/lib/test/key-server.d.ts +12 -0
- package/lib/test/key-server.js +30 -0
- package/lib/test/mem-registry.d.ts +46 -0
- package/lib/test/mem-registry.js +114 -0
- package/lib/test/sdk-suite.d.ts +10 -0
- package/lib/test/sdk-suite.js +155 -0
- package/lib/test/testbed.d.ts +16786 -0
- package/lib/test/testbed.js +175 -0
- package/lib/types/index.d.ts +37 -0
- package/lib/types/index.js +1 -0
- package/package.json +87 -0
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
import { DEFAULT_SIGNED_URL_WORKER, SignedUrlBackend } from "./signed-url.js";
|
|
2
|
+
import { PinataBackend } from "./pinata.js";
|
|
3
|
+
import { CID } from "multiformats/cid";
|
|
4
|
+
import { base64pad } from "multiformats/bases/base64";
|
|
5
|
+
|
|
6
|
+
//#region src/providers/storage/utils.ts
|
|
7
|
+
const RAW_CODE = 85;
|
|
8
|
+
const REVIVERS = [(_key, value) => {
|
|
9
|
+
if (value !== null && typeof value === "object" && "__type" in value && "data" in value && value.__type === "Uint8Array") return base64pad.baseDecode(value.data);
|
|
10
|
+
return value;
|
|
11
|
+
}];
|
|
12
|
+
function serialize(data) {
|
|
13
|
+
if (typeof data === "string") return data;
|
|
14
|
+
return JSON.stringify(data, (_key, value) => {
|
|
15
|
+
if (value instanceof Uint8Array) return {
|
|
16
|
+
__type: "Uint8Array",
|
|
17
|
+
data: base64pad.baseEncode(value)
|
|
18
|
+
};
|
|
19
|
+
return value;
|
|
20
|
+
});
|
|
21
|
+
}
|
|
22
|
+
function deserialize(text) {
|
|
23
|
+
return JSON.parse(text, (key, value) => {
|
|
24
|
+
for (const reviver of REVIVERS) {
|
|
25
|
+
const result = reviver(key, value);
|
|
26
|
+
if (result !== value) return result;
|
|
27
|
+
}
|
|
28
|
+
return value;
|
|
29
|
+
});
|
|
30
|
+
}
|
|
31
|
+
const env = globalThis.process?.env;
|
|
32
|
+
const MAX_UPLOAD_ATTEMPTS = Math.max(1, Number(env?.PINATA_UPLOAD_RETRIES ?? 6));
|
|
33
|
+
function isTransientUpload(err) {
|
|
34
|
+
const e = err;
|
|
35
|
+
const s = typeof e.statusCode === "number" ? e.statusCode : 0;
|
|
36
|
+
if (s === 408 || s === 425 || s === 429 || s >= 500) return true;
|
|
37
|
+
const m = `${e.code ?? ""} ${e.message ?? ""}`;
|
|
38
|
+
return /HTTP_ERROR|disconnect|timed?\s?out|timeout|ECONN|ETIMEDOUT|EAI_AGAIN|socket hang up|network|fetch failed|terminated|aborted|429|408|50\d/i.test(m);
|
|
39
|
+
}
|
|
40
|
+
async function withUploadRetry(label, fn) {
|
|
41
|
+
for (let attempt = 1;; attempt++) try {
|
|
42
|
+
return await fn();
|
|
43
|
+
} catch (err) {
|
|
44
|
+
if (attempt >= MAX_UPLOAD_ATTEMPTS || !isTransientUpload(err)) throw err;
|
|
45
|
+
const delay = Math.min(3e4, 500 * 2 ** (attempt - 1)) + Math.floor(Math.random() * 500);
|
|
46
|
+
console.warn(` [upload] "${label}" failed (attempt ${attempt.toString()}/${MAX_UPLOAD_ATTEMPTS.toString()}), retrying in ${(delay / 1e3).toFixed(1)}s: ${err.message}`);
|
|
47
|
+
await new Promise((r) => setTimeout(r, delay));
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
/**
|
|
51
|
+
* Fetch the exact raw bytes for a CID from a public IPFS gateway (no decoding),
|
|
52
|
+
* retrying to ride out gateway replication lag right after an upload. Blocks
|
|
53
|
+
* written via putBlock() are addressed by their raw-codec (0x55) sibling, so a
|
|
54
|
+
* dag-cbor ("bafyrei…") CID is translated before fetching — the same handling
|
|
55
|
+
* PinataBackend.fetchRaw does, but over a public gateway with no JWT.
|
|
56
|
+
*/
|
|
57
|
+
async function fetchRawByCid(cid, gateway = "https://ipfs.io", { retries = 5, timeoutMs = 16e3 } = {}) {
|
|
58
|
+
let fetchCid = cid.replace(/^ipfs:\/\//, "");
|
|
59
|
+
if (fetchCid.startsWith("bafyrei")) try {
|
|
60
|
+
fetchCid = CID.createV1(RAW_CODE, CID.parse(fetchCid).multihash).toString();
|
|
61
|
+
} catch {}
|
|
62
|
+
const base = (gateway || "https://ipfs.io").replace(/\/$/, "");
|
|
63
|
+
const url = `${/^https?:\/\//.test(base) ? base : `https://${base}`}/ipfs/${fetchCid}`;
|
|
64
|
+
let lastError;
|
|
65
|
+
for (let attempt = 0; attempt < retries; attempt++) {
|
|
66
|
+
const controller = new AbortController();
|
|
67
|
+
const timeout = setTimeout(() => {
|
|
68
|
+
controller.abort();
|
|
69
|
+
}, timeoutMs);
|
|
70
|
+
try {
|
|
71
|
+
const res = await fetch(url, { signal: controller.signal });
|
|
72
|
+
if (!res.ok) throw new Error(`HTTP ${res.status.toString()} ${res.statusText}`);
|
|
73
|
+
return new Uint8Array(await res.arrayBuffer());
|
|
74
|
+
} catch (err) {
|
|
75
|
+
lastError = err;
|
|
76
|
+
if (attempt < retries - 1) await new Promise((r) => setTimeout(r, 1e3));
|
|
77
|
+
} finally {
|
|
78
|
+
clearTimeout(timeout);
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
throw new Error(`Failed to retrieve ${cid} from ${url} after ${retries.toString()} attempts: ${lastError instanceof Error ? lastError.message : String(lastError)}`);
|
|
82
|
+
}
|
|
83
|
+
/**
|
|
84
|
+
* Fetch any content by CID from a public IPFS gateway.
|
|
85
|
+
* No auth required — all Fangorn content is public; privacy is cryptographic.
|
|
86
|
+
*/
|
|
87
|
+
async function retrieveByCid(cid, gateway = "https://ipfs.io", timeoutSecond = 16e3) {
|
|
88
|
+
const base = (gateway || "https://ipfs.io").replace(/\/$/, "");
|
|
89
|
+
const url = `${/^https?:\/\//.test(base) ? base : `https://${base}`}/ipfs/${cid.replace(/^ipfs:\/\//, "")}`;
|
|
90
|
+
const controller = new AbortController();
|
|
91
|
+
const timeout = setTimeout(() => {
|
|
92
|
+
controller.abort();
|
|
93
|
+
}, timeoutSecond);
|
|
94
|
+
try {
|
|
95
|
+
const res = await fetch(url, { signal: controller.signal });
|
|
96
|
+
if (!res.ok) throw new Error(`Failed to retrieve ${cid}: ${res.statusText}`);
|
|
97
|
+
return deserialize(await res.text());
|
|
98
|
+
} catch (err) {
|
|
99
|
+
if (err.name === "AbortError") throw new Error(`Timed out retrieving ${cid} from ${url}`);
|
|
100
|
+
throw err;
|
|
101
|
+
} finally {
|
|
102
|
+
clearTimeout(timeout);
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
//#endregion
|
|
107
|
+
export { DEFAULT_SIGNED_URL_WORKER, MAX_UPLOAD_ATTEMPTS, PinataBackend, SignedUrlBackend, deserialize, fetchRawByCid, isTransientUpload, retrieveByCid, serialize, withUploadRetry };
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
import { Address, Hex } from "viem";
|
|
2
|
+
|
|
3
|
+
//#region src/repo/index.d.ts
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* The local working repo — a `.fangorn/` directory, the analogue of `.git/`.
|
|
7
|
+
*
|
|
8
|
+
* It records just enough to identify the on-chain dataset this working copy
|
|
9
|
+
* tracks and where local history currently points:
|
|
10
|
+
*
|
|
11
|
+
* .fangorn/
|
|
12
|
+
* config.json — { name, schemaId, owner }: the (owner, schemaId, name)
|
|
13
|
+
* triple that keys the dataset in the DataSource registry.
|
|
14
|
+
* HEAD — the CID of the local tip commit, or empty before the first
|
|
15
|
+
* commit. This is what `push` compares against the on-chain
|
|
16
|
+
* tip, and what the next `commit` uses as its parent.
|
|
17
|
+
*
|
|
18
|
+
* `commit` moves HEAD locally (permissionless). `push` reconciles HEAD with the
|
|
19
|
+
* on-chain ref (the permissioned step). See docs/PROTOCOL.md §5, §7.
|
|
20
|
+
*/
|
|
21
|
+
declare const REPO_DIR = ".fangorn";
|
|
22
|
+
interface RepoConfig {
|
|
23
|
+
/** Dataset name — the human-facing repo name, part of the on-chain key. */
|
|
24
|
+
name: string;
|
|
25
|
+
/** Schema reference as given at init (name or bytes32 id) — used to resolve
|
|
26
|
+
* the schema shape when building commits. */
|
|
27
|
+
schema: string;
|
|
28
|
+
/** Resolved schema id — the on-chain key component. */
|
|
29
|
+
schemaId: Hex;
|
|
30
|
+
/** Owner address (the wallet that keys the on-chain dataset). */
|
|
31
|
+
owner: Address;
|
|
32
|
+
}
|
|
33
|
+
declare class LocalRepo {
|
|
34
|
+
private readonly root;
|
|
35
|
+
/** @param root the directory containing `.fangorn/` (the working dir). */
|
|
36
|
+
private constructor();
|
|
37
|
+
private get dir();
|
|
38
|
+
private get configPath();
|
|
39
|
+
private get headPath();
|
|
40
|
+
/** True if `dir` already contains a `.fangorn/` repo. */
|
|
41
|
+
static exists(root?: string): boolean;
|
|
42
|
+
/**
|
|
43
|
+
* Initialize a new repo in `root`. Throws if one already exists so we never
|
|
44
|
+
* silently clobber an existing HEAD/config.
|
|
45
|
+
*/
|
|
46
|
+
static init(config: RepoConfig, root?: string): LocalRepo;
|
|
47
|
+
/** Open an existing repo. Throws if there isn't one. */
|
|
48
|
+
static open(root?: string): LocalRepo;
|
|
49
|
+
config(): RepoConfig;
|
|
50
|
+
/** Local tip commit CID, or undefined before the first commit. */
|
|
51
|
+
head(): string | undefined;
|
|
52
|
+
/** Move the local tip to `cid`. */
|
|
53
|
+
setHead(cid: string): void;
|
|
54
|
+
}
|
|
55
|
+
//#endregion
|
|
56
|
+
export { LocalRepo, REPO_DIR, RepoConfig };
|
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
import { existsSync, mkdirSync, readFileSync, writeFileSync } from "fs";
|
|
2
|
+
import { join } from "path";
|
|
3
|
+
|
|
4
|
+
//#region src/repo/index.ts
|
|
5
|
+
/**
|
|
6
|
+
* The local working repo — a `.fangorn/` directory, the analogue of `.git/`.
|
|
7
|
+
*
|
|
8
|
+
* It records just enough to identify the on-chain dataset this working copy
|
|
9
|
+
* tracks and where local history currently points:
|
|
10
|
+
*
|
|
11
|
+
* .fangorn/
|
|
12
|
+
* config.json — { name, schemaId, owner }: the (owner, schemaId, name)
|
|
13
|
+
* triple that keys the dataset in the DataSource registry.
|
|
14
|
+
* HEAD — the CID of the local tip commit, or empty before the first
|
|
15
|
+
* commit. This is what `push` compares against the on-chain
|
|
16
|
+
* tip, and what the next `commit` uses as its parent.
|
|
17
|
+
*
|
|
18
|
+
* `commit` moves HEAD locally (permissionless). `push` reconciles HEAD with the
|
|
19
|
+
* on-chain ref (the permissioned step). See docs/PROTOCOL.md §5, §7.
|
|
20
|
+
*/
|
|
21
|
+
const REPO_DIR = ".fangorn";
|
|
22
|
+
var LocalRepo = class LocalRepo {
|
|
23
|
+
/** @param root the directory containing `.fangorn/` (the working dir). */
|
|
24
|
+
constructor(root) {
|
|
25
|
+
this.root = root;
|
|
26
|
+
}
|
|
27
|
+
get dir() {
|
|
28
|
+
return join(this.root, REPO_DIR);
|
|
29
|
+
}
|
|
30
|
+
get configPath() {
|
|
31
|
+
return join(this.dir, "config.json");
|
|
32
|
+
}
|
|
33
|
+
get headPath() {
|
|
34
|
+
return join(this.dir, "HEAD");
|
|
35
|
+
}
|
|
36
|
+
/** True if `dir` already contains a `.fangorn/` repo. */
|
|
37
|
+
static exists(root = process.cwd()) {
|
|
38
|
+
return existsSync(join(root, REPO_DIR, "config.json"));
|
|
39
|
+
}
|
|
40
|
+
/**
|
|
41
|
+
* Initialize a new repo in `root`. Throws if one already exists so we never
|
|
42
|
+
* silently clobber an existing HEAD/config.
|
|
43
|
+
*/
|
|
44
|
+
static init(config, root = process.cwd()) {
|
|
45
|
+
const repo = new LocalRepo(root);
|
|
46
|
+
if (existsSync(repo.configPath)) throw new Error(`a Fangorn repo already exists at ${repo.dir}`);
|
|
47
|
+
mkdirSync(repo.dir, { recursive: true });
|
|
48
|
+
writeFileSync(repo.configPath, JSON.stringify(config, null, 2), "utf-8");
|
|
49
|
+
writeFileSync(repo.headPath, "", "utf-8");
|
|
50
|
+
return repo;
|
|
51
|
+
}
|
|
52
|
+
/** Open an existing repo. Throws if there isn't one. */
|
|
53
|
+
static open(root = process.cwd()) {
|
|
54
|
+
const repo = new LocalRepo(root);
|
|
55
|
+
if (!existsSync(repo.configPath)) throw new Error(`not a Fangorn repo (no ${REPO_DIR}/ found in ${root}). Run \`fangorn init\`.`);
|
|
56
|
+
return repo;
|
|
57
|
+
}
|
|
58
|
+
config() {
|
|
59
|
+
return JSON.parse(readFileSync(this.configPath, "utf-8"));
|
|
60
|
+
}
|
|
61
|
+
/** Local tip commit CID, or undefined before the first commit. */
|
|
62
|
+
head() {
|
|
63
|
+
const raw = readFileSync(this.headPath, "utf-8").trim();
|
|
64
|
+
return raw.length > 0 ? raw : void 0;
|
|
65
|
+
}
|
|
66
|
+
/** Move the local tip to `cid`. */
|
|
67
|
+
setHead(cid) {
|
|
68
|
+
writeFileSync(this.headPath, cid, "utf-8");
|
|
69
|
+
}
|
|
70
|
+
};
|
|
71
|
+
|
|
72
|
+
//#endregion
|
|
73
|
+
export { LocalRepo, REPO_DIR };
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import { AccessRequest } from "../crypto/paid.js";
|
|
2
|
+
import { Address, Hex } from "viem";
|
|
3
|
+
|
|
4
|
+
//#region src/test/key-server.d.ts
|
|
5
|
+
declare function testKeyServer(body: AccessRequest, ks: {
|
|
6
|
+
secret: Uint8Array;
|
|
7
|
+
chainId: number;
|
|
8
|
+
registry: Address;
|
|
9
|
+
canRead(reader: Address, publisher: Address, repo: Hex, key: Hex): Promise<boolean>;
|
|
10
|
+
}): Promise<Response>;
|
|
11
|
+
//#endregion
|
|
12
|
+
export { testKeyServer };
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import { WHOLE_REPO } from "../contracts/settlement-registry/index.js";
|
|
2
|
+
import { seal, unseal } from "../crypto/encryption.js";
|
|
3
|
+
import { accessMessage, deriveRecordKey, statement } from "../crypto/paid.js";
|
|
4
|
+
import { bytesToHex, hexToBytes, recoverMessageAddress } from "viem";
|
|
5
|
+
|
|
6
|
+
//#region src/test/key-server.ts
|
|
7
|
+
async function testKeyServer(body, ks) {
|
|
8
|
+
const stmt = statement({
|
|
9
|
+
...ks,
|
|
10
|
+
publisher: body.publisher,
|
|
11
|
+
repo: body.repo,
|
|
12
|
+
generation: BigInt(body.generation)
|
|
13
|
+
});
|
|
14
|
+
const reader = await recoverMessageAddress({
|
|
15
|
+
message: { raw: accessMessage(stmt, body.key, body.readerKey, body.timestamp) },
|
|
16
|
+
signature: body.signature
|
|
17
|
+
});
|
|
18
|
+
if (!(reader.toLowerCase() === body.publisher.toLowerCase()) && !await ks.canRead(reader, body.publisher, body.repo, body.key)) return new Response("not settled", { status: 403 });
|
|
19
|
+
let kRepo;
|
|
20
|
+
try {
|
|
21
|
+
kRepo = unseal(hexToBytes(body.sealed), ks.secret, stmt);
|
|
22
|
+
} catch {
|
|
23
|
+
return new Response("deposit does not match", { status: 400 });
|
|
24
|
+
}
|
|
25
|
+
const out = body.key === WHOLE_REPO ? kRepo : deriveRecordKey(kRepo, stmt, body.key);
|
|
26
|
+
return Response.json({ sealed: bytesToHex(seal(out, hexToBytes(body.readerKey), stmt)) });
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
//#endregion
|
|
30
|
+
export { testKeyServer };
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
import { PreparedTx } from "../contracts/write.js";
|
|
2
|
+
import { CommitUpdate, LogFilter, Registry, RepoRef, UpdateEntry } from "../contracts/data-registry/index.js";
|
|
3
|
+
import "../contracts/index.js";
|
|
4
|
+
import { Address, Hash, Hex, LocalAccount } from "viem";
|
|
5
|
+
import * as abitype31 from "abitype";
|
|
6
|
+
|
|
7
|
+
//#region src/test/mem-registry.d.ts
|
|
8
|
+
/** The EIP-712 domain a MemRegistry signs under. */
|
|
9
|
+
declare const MEM_DOMAIN: abitype31.TypedDataDomain;
|
|
10
|
+
/** One ordering and the registry state over it, shared by every signer of a MemRegistry. */
|
|
11
|
+
declare class MemLedger {
|
|
12
|
+
/** H: position and head */
|
|
13
|
+
heads: Map<string, {
|
|
14
|
+
pos: number;
|
|
15
|
+
head: Hex;
|
|
16
|
+
}>;
|
|
17
|
+
/** U */
|
|
18
|
+
entries: UpdateEntry[];
|
|
19
|
+
/** The clock: one tick per entry of the ordering. */
|
|
20
|
+
t: bigint;
|
|
21
|
+
listeners: Set<(entry: UpdateEntry) => void>;
|
|
22
|
+
append(entry: Omit<UpdateEntry, "t" | "id">): void;
|
|
23
|
+
}
|
|
24
|
+
/**
|
|
25
|
+
* The paper's Apply, signing as `signer`. Signers that share a ledger see each
|
|
26
|
+
* other's writes, like wallets on one chain.
|
|
27
|
+
*/
|
|
28
|
+
declare class MemRegistry implements Registry {
|
|
29
|
+
signer: Address;
|
|
30
|
+
ledger: MemLedger;
|
|
31
|
+
now: () => number;
|
|
32
|
+
account?: LocalAccount | undefined;
|
|
33
|
+
constructor(signer: Address, ledger?: MemLedger, now?: () => number, account?: LocalAccount | undefined);
|
|
34
|
+
epoch(): Promise<number>;
|
|
35
|
+
head(ref: RepoRef): Promise<Hex>;
|
|
36
|
+
update(u: CommitUpdate): Promise<Hash>;
|
|
37
|
+
signUpdate(u: CommitUpdate): Promise<Hex>;
|
|
38
|
+
updateBySig(publisher: Address, u: CommitUpdate, signature: Hex): Promise<Hash>;
|
|
39
|
+
private apply;
|
|
40
|
+
prepareUpdate(): Promise<PreparedTx>;
|
|
41
|
+
log(filter: LogFilter, from: bigint, to?: bigint): Promise<UpdateEntry[]>;
|
|
42
|
+
watch(filter: LogFilter, onEntry: (entry: UpdateEntry) => void): () => void;
|
|
43
|
+
clock(): Promise<bigint>;
|
|
44
|
+
}
|
|
45
|
+
//#endregion
|
|
46
|
+
export { MEM_DOMAIN, MemLedger, MemRegistry };
|
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
import { UPDATE_TYPES, WINDOW, ZERO_HEAD, dataDomain, epochOf, updateMessage } from "../contracts/data-registry/index.js";
|
|
2
|
+
import "../contracts/index.js";
|
|
3
|
+
import { commitHead } from "../engine/index.js";
|
|
4
|
+
import { verifyTypedData } from "viem";
|
|
5
|
+
|
|
6
|
+
//#region src/test/mem-registry.ts
|
|
7
|
+
/** The EIP-712 domain a MemRegistry signs under. */
|
|
8
|
+
const MEM_DOMAIN = dataDomain(31337, "0x000000000000000000000000000000000000da7a");
|
|
9
|
+
const refKey = (r) => `${r.publisher.toLowerCase()}/${r.repo}`;
|
|
10
|
+
/** One ordering and the registry state over it, shared by every signer of a MemRegistry. */
|
|
11
|
+
var MemLedger = class {
|
|
12
|
+
/** H: position and head */
|
|
13
|
+
heads = /* @__PURE__ */ new Map();
|
|
14
|
+
/** U */
|
|
15
|
+
entries = [];
|
|
16
|
+
/** The clock: one tick per entry of the ordering. */
|
|
17
|
+
t = 0n;
|
|
18
|
+
listeners = /* @__PURE__ */ new Set();
|
|
19
|
+
append(entry) {
|
|
20
|
+
this.t++;
|
|
21
|
+
const e = {
|
|
22
|
+
...entry,
|
|
23
|
+
t: this.t,
|
|
24
|
+
id: this.entries.length.toString()
|
|
25
|
+
};
|
|
26
|
+
this.entries.push(e);
|
|
27
|
+
for (const listener of this.listeners) listener(e);
|
|
28
|
+
}
|
|
29
|
+
};
|
|
30
|
+
const matches = (filter, e) => (!filter.publisher || e.publisher.toLowerCase() === filter.publisher.toLowerCase()) && (!filter.repo || e.repo === filter.repo);
|
|
31
|
+
/**
|
|
32
|
+
* The paper's Apply, signing as `signer`. Signers that share a ledger see each
|
|
33
|
+
* other's writes, like wallets on one chain.
|
|
34
|
+
*/
|
|
35
|
+
var MemRegistry = class {
|
|
36
|
+
constructor(signer, ledger = new MemLedger(), now = () => Math.floor(Date.now() / 1e3), account) {
|
|
37
|
+
this.signer = signer;
|
|
38
|
+
this.ledger = ledger;
|
|
39
|
+
this.now = now;
|
|
40
|
+
this.account = account;
|
|
41
|
+
}
|
|
42
|
+
epoch() {
|
|
43
|
+
return Promise.resolve(epochOf(this.now()));
|
|
44
|
+
}
|
|
45
|
+
head(ref) {
|
|
46
|
+
return Promise.resolve(this.ledger.heads.get(refKey(ref))?.head ?? ZERO_HEAD);
|
|
47
|
+
}
|
|
48
|
+
update(u) {
|
|
49
|
+
return this.apply(this.signer, u);
|
|
50
|
+
}
|
|
51
|
+
signUpdate(u) {
|
|
52
|
+
if (!this.account) return Promise.reject(/* @__PURE__ */ new Error("MemRegistry has no account to sign with"));
|
|
53
|
+
return this.account.signTypedData({
|
|
54
|
+
domain: MEM_DOMAIN,
|
|
55
|
+
types: UPDATE_TYPES,
|
|
56
|
+
primaryType: "Update",
|
|
57
|
+
message: updateMessage(this.account.address, u)
|
|
58
|
+
});
|
|
59
|
+
}
|
|
60
|
+
async updateBySig(publisher, u, signature) {
|
|
61
|
+
if (!await verifyTypedData({
|
|
62
|
+
address: publisher,
|
|
63
|
+
domain: MEM_DOMAIN,
|
|
64
|
+
types: UPDATE_TYPES,
|
|
65
|
+
primaryType: "Update",
|
|
66
|
+
message: updateMessage(publisher, u),
|
|
67
|
+
signature
|
|
68
|
+
})) throw new Error("BadSignature");
|
|
69
|
+
return this.apply(publisher, u);
|
|
70
|
+
}
|
|
71
|
+
async apply(publisher, u) {
|
|
72
|
+
const now = epochOf(this.now());
|
|
73
|
+
if (u.epoch > now || u.epoch + WINDOW < now) throw new Error("EpochOutOfWindow");
|
|
74
|
+
const ref = {
|
|
75
|
+
publisher,
|
|
76
|
+
repo: u.repo
|
|
77
|
+
};
|
|
78
|
+
if (await this.head(ref) !== u.parent) throw new Error("StaleStateRoot");
|
|
79
|
+
const head = await commitHead(u);
|
|
80
|
+
const pos = (this.ledger.heads.get(refKey(ref))?.pos ?? 0) + 1;
|
|
81
|
+
this.ledger.heads.set(refKey(ref), {
|
|
82
|
+
pos,
|
|
83
|
+
head
|
|
84
|
+
});
|
|
85
|
+
this.ledger.append({
|
|
86
|
+
publisher,
|
|
87
|
+
repo: u.repo,
|
|
88
|
+
pos,
|
|
89
|
+
parent: u.parent,
|
|
90
|
+
head,
|
|
91
|
+
timestamp: BigInt(this.now())
|
|
92
|
+
});
|
|
93
|
+
return "0x00";
|
|
94
|
+
}
|
|
95
|
+
prepareUpdate() {
|
|
96
|
+
return Promise.reject(/* @__PURE__ */ new Error("MemRegistry has no transactions to prepare"));
|
|
97
|
+
}
|
|
98
|
+
log(filter, from, to) {
|
|
99
|
+
return Promise.resolve(this.ledger.entries.filter((e) => e.t >= from && (to === void 0 || e.t <= to) && matches(filter, e)));
|
|
100
|
+
}
|
|
101
|
+
watch(filter, onEntry) {
|
|
102
|
+
const listener = (e) => {
|
|
103
|
+
if (matches(filter, e)) onEntry(e);
|
|
104
|
+
};
|
|
105
|
+
this.ledger.listeners.add(listener);
|
|
106
|
+
return () => this.ledger.listeners.delete(listener);
|
|
107
|
+
}
|
|
108
|
+
clock() {
|
|
109
|
+
return Promise.resolve(this.ledger.t);
|
|
110
|
+
}
|
|
111
|
+
};
|
|
112
|
+
|
|
113
|
+
//#endregion
|
|
114
|
+
export { MEM_DOMAIN, MemLedger, MemRegistry };
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import { Fangorn, RepoChange } from "../fangorn.js";
|
|
2
|
+
import { Network } from "./testbed.js";
|
|
3
|
+
|
|
4
|
+
//#region src/test/sdk-suite.d.ts
|
|
5
|
+
declare const head: (f: Fangorn, repo: string) => Promise<`0x${string}`>;
|
|
6
|
+
/** Take the first n entries of the stream and then stop. */
|
|
7
|
+
declare function take(stream: AsyncGenerator<RepoChange>, n: number): Promise<RepoChange[]>;
|
|
8
|
+
declare function sdkSuite(makeNetwork: () => Promise<Network>, timeout?: number): void;
|
|
9
|
+
//#endregion
|
|
10
|
+
export { head, sdkSuite, take };
|
|
@@ -0,0 +1,155 @@
|
|
|
1
|
+
import { ZERO_HEAD } from "../contracts/data-registry/index.js";
|
|
2
|
+
import "../contracts/index.js";
|
|
3
|
+
import { GADGET_SELF_HKDF_V1, sealSelf, unsealSelf } from "../crypto/encryption.js";
|
|
4
|
+
import { afterAll, beforeAll, describe, it } from "../node_modules/@vitest/runner/dist/index.js";
|
|
5
|
+
import { globalExpect } from "../node_modules/vitest/dist/chunks/vi.2VT5v0um.js";
|
|
6
|
+
import { bytesToHex, hexToBytes, keccak256, stringToBytes } from "viem";
|
|
7
|
+
import { generatePrivateKey } from "viem/accounts";
|
|
8
|
+
|
|
9
|
+
//#region src/test/sdk-suite.ts
|
|
10
|
+
const head = (f, repo) => f.getRegistry().head({
|
|
11
|
+
publisher: f.getAddress(),
|
|
12
|
+
repo
|
|
13
|
+
});
|
|
14
|
+
/** Take the first n entries of the stream and then stop. */
|
|
15
|
+
async function take(stream, n) {
|
|
16
|
+
const out = [];
|
|
17
|
+
for await (const c of stream) {
|
|
18
|
+
out.push(c);
|
|
19
|
+
if (out.length === n) break;
|
|
20
|
+
}
|
|
21
|
+
return out;
|
|
22
|
+
}
|
|
23
|
+
function sdkSuite(makeNetwork, timeout = 5e3) {
|
|
24
|
+
let net;
|
|
25
|
+
beforeAll(async () => {
|
|
26
|
+
net = await makeNetwork();
|
|
27
|
+
}, 12e4);
|
|
28
|
+
afterAll(() => {
|
|
29
|
+
net.stop();
|
|
30
|
+
});
|
|
31
|
+
describe("publishing", () => {
|
|
32
|
+
it("a publisher uploads records and reads them back", async () => {
|
|
33
|
+
const f = await net.client();
|
|
34
|
+
await f.initRepo("r");
|
|
35
|
+
const a = await f.upload("r", { event: "one" }, "event", "a");
|
|
36
|
+
const b = await f.upload("r", { event: "two" }, "event", "b");
|
|
37
|
+
globalExpect((await f.engine.readRecord(f.getAddress(), "r", "a"))?.payload).toEqual({ event: "one" });
|
|
38
|
+
const { records } = await f.inspectRepo("r");
|
|
39
|
+
globalExpect(records.map((r) => r.cid).sort()).toEqual([a.payloadCid, b.payloadCid].sort());
|
|
40
|
+
}, timeout);
|
|
41
|
+
it("can't upload to a repo that was never initialized", async () => {
|
|
42
|
+
await globalExpect((await net.client()).upload("nope", { x: 1 }, "t")).rejects.toThrow(/initRepo/);
|
|
43
|
+
}, timeout);
|
|
44
|
+
it("keeps each repo's head and records to itself", async () => {
|
|
45
|
+
const f = await net.client();
|
|
46
|
+
await f.initRepo("a");
|
|
47
|
+
const headA = await head(f, "a");
|
|
48
|
+
await f.initRepo("b");
|
|
49
|
+
const headB = await head(f, "b");
|
|
50
|
+
globalExpect(headA).not.toBe(ZERO_HEAD);
|
|
51
|
+
globalExpect(headB).not.toBe(headA);
|
|
52
|
+
globalExpect(await head(f, "untouched")).toBe(ZERO_HEAD);
|
|
53
|
+
await f.upload("a", { n: 1 }, "t", "x");
|
|
54
|
+
globalExpect(await head(f, "a")).not.toBe(headA);
|
|
55
|
+
globalExpect(await head(f, "b")).toBe(headB);
|
|
56
|
+
globalExpect((await f.inspectRepo("b")).records).toEqual([]);
|
|
57
|
+
}, timeout);
|
|
58
|
+
it("publishes a batch as one entry of the ordering", async () => {
|
|
59
|
+
const f = await net.client();
|
|
60
|
+
await f.initRepo("batch");
|
|
61
|
+
const records = Array.from({ length: 25 }, (_, i) => ({
|
|
62
|
+
id: `v-${String(i)}`,
|
|
63
|
+
type: "t",
|
|
64
|
+
payload: { i }
|
|
65
|
+
}));
|
|
66
|
+
const before = await net.clock();
|
|
67
|
+
const res = await f.uploadBatch("batch", records);
|
|
68
|
+
globalExpect(await net.clock() - before).toBe(1n);
|
|
69
|
+
globalExpect(Object.keys(res.recordCids)).toHaveLength(25);
|
|
70
|
+
globalExpect((await f.inspectRepo("batch")).records).toHaveLength(25);
|
|
71
|
+
}, timeout);
|
|
72
|
+
it("stores a payload sealed to its publisher as opaque bytes", async () => {
|
|
73
|
+
const sk = generatePrivateKey();
|
|
74
|
+
const f = await net.client(sk);
|
|
75
|
+
await f.initRepo("private");
|
|
76
|
+
const resourceId = keccak256(stringToBytes("private:secret"));
|
|
77
|
+
const ciphertext = sealSelf(new TextEncoder().encode("the eagles are coming"), hexToBytes(sk), resourceId);
|
|
78
|
+
const { id } = await f.upload("private", {
|
|
79
|
+
gadget: GADGET_SELF_HKDF_V1,
|
|
80
|
+
resourceId,
|
|
81
|
+
ciphertext: bytesToHex(ciphertext)
|
|
82
|
+
}, "sealed");
|
|
83
|
+
const stored = (await f.engine.readRecord(f.getAddress(), "private", id))?.payload;
|
|
84
|
+
globalExpect(new TextDecoder().decode(unsealSelf(hexToBytes(stored.ciphertext), hexToBytes(sk), resourceId))).toBe("the eagles are coming");
|
|
85
|
+
globalExpect(() => unsealSelf(hexToBytes(stored.ciphertext), new Uint8Array(32).fill(171), resourceId)).toThrow();
|
|
86
|
+
}, timeout);
|
|
87
|
+
it("reset empties a repo with a new commit, without zeroing its head", async () => {
|
|
88
|
+
const f = await net.client();
|
|
89
|
+
await f.initRepo("r");
|
|
90
|
+
await f.upload("r", { n: 1 }, "t", "x");
|
|
91
|
+
const before = await head(f, "r");
|
|
92
|
+
await f.reset("r");
|
|
93
|
+
globalExpect(await head(f, "r")).not.toBe(before);
|
|
94
|
+
globalExpect(await head(f, "r")).not.toBe(ZERO_HEAD);
|
|
95
|
+
globalExpect((await f.inspectRepo("r")).records).toEqual([]);
|
|
96
|
+
}, timeout);
|
|
97
|
+
it("refuses to push a commit whose parent is no longer the head", async () => {
|
|
98
|
+
const f = await net.client();
|
|
99
|
+
await f.initRepo("r");
|
|
100
|
+
const stale = await f.commit({
|
|
101
|
+
repo: "r",
|
|
102
|
+
records: [{
|
|
103
|
+
id: "x",
|
|
104
|
+
type: "t",
|
|
105
|
+
payload: {}
|
|
106
|
+
}]
|
|
107
|
+
});
|
|
108
|
+
await globalExpect(f.push("r", stale.commitCid)).rejects.toThrow(/stale parent/);
|
|
109
|
+
}, timeout);
|
|
110
|
+
});
|
|
111
|
+
describe("reading other publishers", () => {
|
|
112
|
+
it("any client reads any publisher's repo, and lists every repo", async () => {
|
|
113
|
+
const reader = await net.client();
|
|
114
|
+
const pub = await net.client();
|
|
115
|
+
await pub.initRepo("catalog");
|
|
116
|
+
const { payloadCid } = await pub.upload("catalog", { title: "t" }, "entry", "g");
|
|
117
|
+
const { contents } = await reader.readRepo(pub.getAddress(), "catalog");
|
|
118
|
+
globalExpect(contents.records.map((r) => r.cid)).toEqual([payloadCid]);
|
|
119
|
+
globalExpect((await reader.repos({ owner: pub.getAddress() })).map((d) => [d.owner, d.repo])).toEqual([[pub.getAddress(), "catalog"]]);
|
|
120
|
+
}, timeout);
|
|
121
|
+
});
|
|
122
|
+
describe("subscriptions", () => {
|
|
123
|
+
it("replays from a block, then follows live", async () => {
|
|
124
|
+
const pub = await net.client();
|
|
125
|
+
const from = await net.clock();
|
|
126
|
+
await pub.initRepo("feed");
|
|
127
|
+
await pub.upload("feed", { n: 1 }, "t", "a");
|
|
128
|
+
const ctl = new AbortController();
|
|
129
|
+
const stream = (await net.client()).subscribeAll({
|
|
130
|
+
owner: pub.getAddress(),
|
|
131
|
+
fromBlock: from,
|
|
132
|
+
signal: ctl.signal,
|
|
133
|
+
pollingInterval: 100
|
|
134
|
+
});
|
|
135
|
+
globalExpect((await stream.next()).value.puts.map((r) => r.id)).toEqual(["a"]);
|
|
136
|
+
const second = stream.next();
|
|
137
|
+
await pub.upload("feed", { n: 2 }, "t", "b");
|
|
138
|
+
const live = (await second).value;
|
|
139
|
+
globalExpect([
|
|
140
|
+
live.repo,
|
|
141
|
+
live.owner,
|
|
142
|
+
live.puts.map((r) => r.id)
|
|
143
|
+
]).toEqual([
|
|
144
|
+
"feed",
|
|
145
|
+
pub.getAddress(),
|
|
146
|
+
["b"]
|
|
147
|
+
]);
|
|
148
|
+
ctl.abort();
|
|
149
|
+
await stream.return(void 0);
|
|
150
|
+
}, timeout);
|
|
151
|
+
});
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
//#endregion
|
|
155
|
+
export { head, sdkSuite, take };
|