@fangorn-network/sdk 0.1.6 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (43) hide show
  1. package/lib/cli/cli.js +83 -46
  2. package/lib/cli/sell.d.ts +2 -2
  3. package/lib/cli/sell.js +14 -8
  4. package/lib/cli/stage.d.ts +21 -3
  5. package/lib/cli/stage.js +110 -24
  6. package/lib/config.d.ts +480 -154
  7. package/lib/config.js +11 -2
  8. package/lib/contracts/data-registry/abi.d.ts +41 -0
  9. package/lib/contracts/data-registry/abi.js +46 -0
  10. package/lib/contracts/data-registry/index.d.ts +45 -3
  11. package/lib/contracts/data-registry/index.js +69 -14
  12. package/lib/contracts/data-registry/mmr.d.ts +9 -2
  13. package/lib/contracts/data-registry/mmr.js +6 -2
  14. package/lib/contracts/index.d.ts +2 -2
  15. package/lib/contracts/index.js +2 -2
  16. package/lib/contracts/write.d.ts +17 -2
  17. package/lib/contracts/write.js +63 -7
  18. package/lib/crypto/encryption.js +3 -0
  19. package/lib/crypto/paid.d.ts +1 -1
  20. package/lib/crypto/paid.js +4 -1
  21. package/lib/engine/index.d.ts +9 -2
  22. package/lib/engine/index.js +33 -17
  23. package/lib/engine/records.d.ts +9 -1
  24. package/lib/engine/records.js +32 -6
  25. package/lib/erc8004.d.ts +1 -1
  26. package/lib/erc8004.js +12 -5
  27. package/lib/fangorn.d.ts +11 -1
  28. package/lib/fangorn.js +25 -11
  29. package/lib/feed.d.ts +23 -2
  30. package/lib/feed.js +43 -6
  31. package/lib/index.d.ts +3 -3
  32. package/lib/index.js +4 -4
  33. package/lib/providers/storage/index.js +1 -1
  34. package/lib/providers/storage/pinata.js +14 -6
  35. package/lib/providers/storage/signed-url.js +21 -8
  36. package/lib/providers/storage/types.d.ts +9 -1
  37. package/lib/providers/storage/types.js +54 -1
  38. package/lib/providers/storage/utils.d.ts +3 -1
  39. package/lib/providers/storage/utils.js +3 -3
  40. package/lib/test/mem-registry.d.ts +3 -3
  41. package/lib/test/mem-registry.js +7 -5
  42. package/lib/test/testbed.d.ts +5183 -5183
  43. package/package.json +6 -3
@@ -1,11 +1,12 @@
1
- import { retrieveByCid, serialize, withUploadRetry } from "./utils.js";
1
+ import { assertStoredBlock, assertStoredFile } from "./types.js";
2
2
  import { packCar } from "../../engine/car.js";
3
+ import { fetchRawByCid, retrieveByCid, serialize, withUploadRetry } from "./utils.js";
3
4
  import { keccak256, stringToBytes } from "viem";
4
5
  import { CID } from "multiformats/cid";
6
+ import { sha256 } from "multiformats/hashes/sha2";
5
7
  import { encode } from "multiformats/block";
6
8
  import { PinataSDK } from "pinata";
7
9
  import * as dagCbor from "@ipld/dag-cbor";
8
- import { sha256 } from "multiformats/hashes/sha2";
9
10
 
10
11
  //#region src/providers/storage/pinata.ts
11
12
  const RAW_CODE = 85;
@@ -24,7 +25,9 @@ var PinataBackend = class {
24
25
  const name = meta?.name ?? "file";
25
26
  return withUploadRetry(name, async () => {
26
27
  const file = new File([content], name, { type: "text/plain" });
27
- return (await this.pinata.upload.public.file(file, { metadata: meta })).cid;
28
+ const upload = await this.pinata.upload.public.file(file, { metadata: meta });
29
+ await assertStoredFile(upload.cid, new TextEncoder().encode(content), this);
30
+ return upload.cid;
28
31
  });
29
32
  }
30
33
  async update(data, meta) {
@@ -33,6 +36,7 @@ var PinataBackend = class {
33
36
  return withUploadRetry(name, async () => {
34
37
  const file = new File([content], name, { type: "text/plain" });
35
38
  const upload = await this.pinata.upload.public.file(file).name(name);
39
+ await assertStoredFile(upload.cid, new TextEncoder().encode(content), this);
36
40
  const stateRoot = keccak256(stringToBytes(upload.cid)).toLowerCase();
37
41
  await this.pinata.files.public.update({
38
42
  id: upload.id,
@@ -70,7 +74,8 @@ var PinataBackend = class {
70
74
  const bytes = await packCar(rootBlock.cid, blocks);
71
75
  await withUploadRetry(`car[${items.length.toString()}f/${(bytes.length / 1e6).toFixed(1)}MB]`, async () => {
72
76
  const file = new File([bytes.buffer], "data.car", { type: "application/vnd.ipld.car" });
73
- await this.pinata.upload.public.file(file).car();
77
+ const upload = await this.pinata.upload.public.file(file).car();
78
+ if (!rootBlock.cid.equals(CID.parse(upload.cid))) throw new Error("storage returned the wrong CAR root");
74
79
  });
75
80
  return uriByName;
76
81
  }
@@ -85,7 +90,7 @@ var PinataBackend = class {
85
90
  const { cid, bytes } = block;
86
91
  await withUploadRetry(cid.toString(), async () => {
87
92
  const file = new File([bytes], cid.toString(), { type: "application/octet-stream" });
88
- await this.pinata.upload.public.file(file);
93
+ assertStoredBlock((await this.pinata.upload.public.file(file)).cid, block);
89
94
  });
90
95
  }
91
96
  /**
@@ -97,7 +102,9 @@ var PinataBackend = class {
97
102
  async putFile(bytes, name) {
98
103
  return withUploadRetry(name, async () => {
99
104
  const file = new File([bytes], name, { type: "application/octet-stream" });
100
- return (await this.pinata.upload.public.file(file)).cid;
105
+ const upload = await this.pinata.upload.public.file(file);
106
+ await assertStoredFile(upload.cid, bytes, this);
107
+ return upload.cid;
101
108
  });
102
109
  }
103
110
  /** Fetch back the exact bytes stored via putFile(). */
@@ -117,6 +124,7 @@ var PinataBackend = class {
117
124
  }
118
125
  /** Raw bytes for a block CID, with no decoding — what blockstore traversal needs. */
119
126
  async getRawBlock(uri) {
127
+ if (CID.parse(uri.replace(/^ipfs:\/\//, "")).code === 112) return fetchRawByCid(uri, this.gateway, { rawBlock: true });
120
128
  const { bytes } = await this.fetchRaw(uri);
121
129
  return bytes;
122
130
  }
@@ -1,5 +1,7 @@
1
1
  import { FangornConfig } from "../../config.js";
2
+ import { assertStoredBlock, assertStoredFile } from "./types.js";
2
3
  import { fetchRawByCid, serialize, withUploadRetry } from "./utils.js";
4
+ import { CID } from "multiformats/cid";
3
5
 
4
6
  //#region src/providers/storage/signed-url.ts
5
7
  /**
@@ -8,6 +10,8 @@ import { fetchRawByCid, serialize, withUploadRetry } from "./utils.js";
8
10
  * config's `signedUrlWorker`, so a Base client reaches Base's worker.
9
11
  */
10
12
  const DEFAULT_SIGNED_URL_WORKER = FangornConfig.signedUrlWorker;
13
+ /** The worker's handshake is two tiny JSON round trips. */
14
+ const WORKER_TIMEOUT_MS = 3e4;
11
15
  /** A human-readable reason from a worker error response, detail included. */
12
16
  function workerError(r) {
13
17
  const base = r.error ?? "unknown error";
@@ -44,7 +48,7 @@ var SignedUrlBackend = class {
44
48
  size,
45
49
  uploadId
46
50
  });
47
- if (!challenge.challenge) throw new Error(`Presigned-URL worker did not issue a challenge: ${workerError(challenge)}`);
51
+ if (!challenge.challenge) throw Object.assign(/* @__PURE__ */ new Error(`Presigned-URL worker did not issue a challenge: ${workerError(challenge)}`), { statusCode: challenge.status });
48
52
  const signature = await this.signer.signMessage(challenge.challenge);
49
53
  const grant = await this.workerJson({
50
54
  address,
@@ -53,7 +57,7 @@ var SignedUrlBackend = class {
53
57
  size,
54
58
  uploadId
55
59
  });
56
- if (!grant.ok || !grant.uploadUrl) throw new Error(`Presigned-URL worker denied an upload URL: ${workerError(grant)}`);
60
+ if (!grant.ok || !grant.uploadUrl) throw Object.assign(/* @__PURE__ */ new Error(`Presigned-URL worker denied an upload URL: ${workerError(grant)}`), { statusCode: grant.status });
57
61
  return {
58
62
  uploadUrl: grant.uploadUrl,
59
63
  network: grant.network ?? "public"
@@ -63,9 +67,13 @@ var SignedUrlBackend = class {
63
67
  const res = await fetch(this.workerUrl, {
64
68
  method: "POST",
65
69
  headers: { "content-type": "application/json" },
66
- body: JSON.stringify(body)
70
+ body: JSON.stringify(body),
71
+ signal: AbortSignal.timeout(WORKER_TIMEOUT_MS)
67
72
  });
68
- return await res.json().catch(() => null) ?? { error: `HTTP ${res.status.toString()}` };
73
+ return {
74
+ ...await res.json().catch(() => null) ?? { error: `HTTP ${res.status.toString()}` },
75
+ status: res.status
76
+ };
69
77
  }
70
78
  /** Upload bytes via a fresh one-time presigned URL; returns the pinned CID. */
71
79
  uploadBytes(bytes, name, type) {
@@ -87,19 +95,24 @@ var SignedUrlBackend = class {
87
95
  });
88
96
  }
89
97
  async put(data, meta) {
90
- return this.uploadBytes(new TextEncoder().encode(serialize(data)), meta?.name ?? "file", "text/plain");
98
+ const bytes = new TextEncoder().encode(serialize(data));
99
+ const cid = await this.uploadBytes(bytes, meta?.name ?? "file", "text/plain");
100
+ await assertStoredFile(cid, bytes, this);
101
+ return cid;
91
102
  }
92
103
  async putFile(bytes, name) {
93
- return this.uploadBytes(bytes, name, "application/octet-stream");
104
+ const cid = await this.uploadBytes(bytes, name, "application/octet-stream");
105
+ await assertStoredFile(cid, bytes, this);
106
+ return cid;
94
107
  }
95
108
  async putBlock(block) {
96
- await this.uploadBytes(block.bytes, block.cid.toString(), "application/octet-stream");
109
+ assertStoredBlock(await this.uploadBytes(block.bytes, block.cid.toString(), "application/octet-stream"), block);
97
110
  }
98
111
  async getFile(uri) {
99
112
  return fetchRawByCid(uri, this.gateway);
100
113
  }
101
114
  async getRawBlock(uri) {
102
- return fetchRawByCid(uri, this.gateway);
115
+ return fetchRawByCid(uri, this.gateway, { rawBlock: CID.parse(uri.replace(/^ipfs:\/\//, "")).code === 112 });
103
116
  }
104
117
  async get(uri) {
105
118
  const bytes = await fetchRawByCid(uri, this.gateway);
@@ -58,5 +58,13 @@ interface MetadataStorage {
58
58
  */
59
59
  delete(uri: string): Promise<void>;
60
60
  }
61
+ /**
62
+ * Check the CID a backend says it stored `block` under. Readers fetch a block by
63
+ * its raw-codec sibling (same sha256 digest), so any other answer means the block
64
+ * is unreadable: fail the upload, not every later read of the head that names it.
65
+ */
66
+ declare function assertStoredBlock(returned: string, block: RawBlock): void;
67
+ /** Verify the file reference before including it in a commit or paid handle. */
68
+ declare function assertStoredFile(returned: string, bytes: Uint8Array, storage?: Partial<Pick<MetadataStorage, "getRawBlock">>): Promise<void>;
61
69
  //#endregion
62
- export { MetadataStorage, RawBlock, StorageMeta };
70
+ export { MetadataStorage, RawBlock, StorageMeta, assertStoredBlock, assertStoredFile };
@@ -1 +1,54 @@
1
- export { };
1
+ import * as dagPb from "@ipld/dag-pb";
2
+ import { UnixFS } from "ipfs-unixfs";
3
+ import { CID } from "multiformats/cid";
4
+ import { sha256 } from "multiformats/hashes/sha2";
5
+ import { equals } from "multiformats/bytes";
6
+
7
+ //#region src/providers/storage/types.ts
8
+ const RAW_CODE = 85;
9
+ const SHA2_256 = 18;
10
+ /**
11
+ * Check the CID a backend says it stored `block` under. Readers fetch a block by
12
+ * its raw-codec sibling (same sha256 digest), so any other answer means the block
13
+ * is unreadable: fail the upload, not every later read of the head that names it.
14
+ */
15
+ function assertStoredBlock(returned, block) {
16
+ let cid;
17
+ try {
18
+ cid = CID.parse(returned.replace(/^ipfs:\/\//, ""));
19
+ } catch {}
20
+ const want = CID.createV1(RAW_CODE, block.cid.multihash);
21
+ if (!cid?.equals(want)) throw new Error(`storage stored block ${block.cid.toString()} as ${JSON.stringify(returned)}, expected ${want.toString()}: readers could not fetch it`);
22
+ }
23
+ /** Verify the file reference before including it in a commit or paid handle. */
24
+ async function assertStoredFile(returned, bytes, storage) {
25
+ const root = CID.parse(returned.replace(/^ipfs:\/\//, ""));
26
+ const mismatch = () => /* @__PURE__ */ new Error(`storage CID ${returned} does not match the uploaded bytes`);
27
+ async function verify(cid, content, depth) {
28
+ if (cid.multihash.code !== SHA2_256 || depth > 64) throw mismatch();
29
+ if (cid.code === RAW_CODE) {
30
+ if (!equals((await sha256.digest(content)).digest, cid.multihash.digest)) throw mismatch();
31
+ return;
32
+ }
33
+ if (cid.code !== dagPb.code || !storage?.getRawBlock) throw mismatch();
34
+ const block = await storage.getRawBlock(cid.toString());
35
+ if (!equals((await sha256.digest(block)).digest, cid.multihash.digest)) throw mismatch();
36
+ const { Data, Links } = dagPb.decode(block);
37
+ if (!Data) throw mismatch();
38
+ const file = UnixFS.unmarshal(Data);
39
+ if (file.type !== "file" && file.type !== "raw" || file.blockSizes.length !== Links.length || file.fileSize() !== BigInt(content.length)) throw mismatch();
40
+ let offset = file.data?.length ?? 0;
41
+ if (file.data && !equals(file.data, content.subarray(0, offset))) throw mismatch();
42
+ for (const [i, link] of Links.entries()) {
43
+ const size = Number(file.blockSizes[i]);
44
+ if (size <= 0) throw mismatch();
45
+ const end = offset + size;
46
+ await verify(CID.decode(link.Hash.bytes), content.subarray(offset, end), depth + 1);
47
+ offset = end;
48
+ }
49
+ }
50
+ await verify(root, bytes, 0);
51
+ }
52
+
53
+ //#endregion
54
+ export { assertStoredBlock, assertStoredFile };
@@ -16,10 +16,12 @@ declare function withUploadRetry<T>(label: string, fn: () => Promise<T>): Promis
16
16
  */
17
17
  declare function fetchRawByCid(cid: string, gateway?: string, {
18
18
  retries,
19
- timeoutMs
19
+ timeoutMs,
20
+ rawBlock
20
21
  }?: {
21
22
  retries?: number | undefined;
22
23
  timeoutMs?: number | undefined;
24
+ rawBlock?: boolean | undefined;
23
25
  }): Promise<Uint8Array>;
24
26
  /**
25
27
  * Fetch any content by CID from a public IPFS gateway.
@@ -1,5 +1,5 @@
1
- import { DEFAULT_SIGNED_URL_WORKER, SignedUrlBackend } from "./signed-url.js";
2
1
  import { PinataBackend } from "./pinata.js";
2
+ import { DEFAULT_SIGNED_URL_WORKER, SignedUrlBackend } from "./signed-url.js";
3
3
  import { CID } from "multiformats/cid";
4
4
  import { base64pad } from "multiformats/bases/base64";
5
5
 
@@ -54,13 +54,13 @@ async function withUploadRetry(label, fn) {
54
54
  * dag-cbor ("bafyrei…") CID is translated before fetching — the same handling
55
55
  * PinataBackend.fetchRaw does, but over a public gateway with no JWT.
56
56
  */
57
- async function fetchRawByCid(cid, gateway = "https://ipfs.io", { retries = 5, timeoutMs = 16e3 } = {}) {
57
+ async function fetchRawByCid(cid, gateway = "https://ipfs.io", { retries = 5, timeoutMs = 16e3, rawBlock = false } = {}) {
58
58
  let fetchCid = cid.replace(/^ipfs:\/\//, "");
59
59
  if (fetchCid.startsWith("bafyrei")) try {
60
60
  fetchCid = CID.createV1(RAW_CODE, CID.parse(fetchCid).multihash).toString();
61
61
  } catch {}
62
62
  const base = (gateway || "https://ipfs.io").replace(/\/$/, "");
63
- const url = `${/^https?:\/\//.test(base) ? base : `https://${base}`}/ipfs/${fetchCid}`;
63
+ const url = `${/^https?:\/\//.test(base) ? base : `https://${base}`}/ipfs/${fetchCid}${rawBlock ? "?format=raw" : ""}`;
64
64
  let lastError;
65
65
  for (let attempt = 0; attempt < retries; attempt++) {
66
66
  const controller = new AbortController();
@@ -3,12 +3,12 @@ import { CommitUpdate, LogFilter, Registry, RepoRef, UpdateEntry } from "../cont
3
3
  import { Mmr } from "../contracts/data-registry/mmr.js";
4
4
  import "../contracts/index.js";
5
5
  import "../index.js";
6
- import * as viem5837 from "viem";
6
+ import * as viem237 from "viem";
7
7
  import { Address, Hash, Hex, LocalAccount } from "viem";
8
8
 
9
9
  //#region src/test/mem-registry.d.ts
10
10
  /** The EIP-712 domain a MemRegistry signs under. */
11
- declare const MEM_DOMAIN: viem5837.TypedDataDomain;
11
+ declare const MEM_DOMAIN: viem237.TypedDataDomain;
12
12
  /** One ordering and the registry state over it, shared by every signer of a MemRegistry. */
13
13
  declare class MemLedger {
14
14
  /** H: position and head */
@@ -24,7 +24,7 @@ declare class MemLedger {
24
24
  /** The contract's log root after each tick, fixed once written (like chain state). */
25
25
  mmr: Mmr;
26
26
  logRoots: `0x${string}`[];
27
- append(entry: Omit<UpdateEntry, "t" | "id">): void;
27
+ append(entry: Omit<UpdateEntry, "t" | "id" | "index">): void;
28
28
  }
29
29
  /**
30
30
  * The paper's Apply, signing as `signer`. Signers that share a ledger see each
@@ -25,7 +25,8 @@ var MemLedger = class {
25
25
  const e = {
26
26
  ...entry,
27
27
  t: this.t,
28
- id: this.entries.length.toString()
28
+ id: this.entries.length.toString(),
29
+ index: BigInt(this.entries.length)
29
30
  };
30
31
  this.entries.push(e);
31
32
  this.mmr = mmrAppend(this.mmr, logLeaf(e));
@@ -81,15 +82,16 @@ var MemRegistry = class {
81
82
  return this.apply(publisher, u);
82
83
  }
83
84
  async apply(publisher, u) {
84
- const now = epochOf(this.now());
85
- if (u.epoch > now || u.epoch + WINDOW < now) throw new Error("EpochOutOfWindow");
86
85
  const ref = {
87
86
  publisher,
88
87
  repo: u.repo
89
88
  };
90
- if (await this.head(ref) !== u.parent) throw new Error("StaleStateRoot");
91
89
  const head = await commitHead(u);
92
- const pos = (this.ledger.heads.get(refKey(ref))?.pos ?? 0) + 1;
90
+ const now = epochOf(this.now());
91
+ if (u.epoch > now || u.epoch + WINDOW < now) throw new Error("EpochOutOfWindow");
92
+ const cur = this.ledger.heads.get(refKey(ref));
93
+ if ((cur?.head ?? ZERO_HEAD) !== u.parent) throw new Error("StaleStateRoot");
94
+ const pos = (cur?.pos ?? 0) + 1;
93
95
  this.ledger.heads.set(refKey(ref), {
94
96
  pos,
95
97
  head