@fangorn-network/sdk 2026.9.22-dev → 2026.10.19-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.
Files changed (89) hide show
  1. package/README.md +177 -192
  2. package/lib/cli/cli.d.ts +0 -0
  3. package/lib/cli/cli.js +165 -194
  4. package/lib/config.d.ts +32 -27
  5. package/lib/config.js +17 -7
  6. package/lib/contracts/app-registry/abi.d.ts +1033 -277
  7. package/lib/contracts/app-registry/abi.js +1214 -335
  8. package/lib/contracts/app-registry/index.d.ts +105 -65
  9. package/lib/contracts/app-registry/index.js +182 -175
  10. package/lib/contracts/data-registry/abi.d.ts +166 -187
  11. package/lib/contracts/data-registry/abi.js +207 -237
  12. package/lib/contracts/data-registry/index.d.ts +4 -151
  13. package/lib/contracts/data-registry/index.js +5 -279
  14. package/lib/contracts/index.d.ts +6 -7
  15. package/lib/contracts/index.js +6 -8
  16. package/lib/contracts/logs.d.ts +4 -1
  17. package/lib/contracts/logs.js +9 -2
  18. package/lib/contracts/membership-registry/abi.d.ts +1145 -0
  19. package/lib/contracts/membership-registry/abi.js +1333 -0
  20. package/lib/contracts/membership-registry/index.d.ts +79 -0
  21. package/lib/contracts/membership-registry/index.js +104 -0
  22. package/lib/contracts/types.d.ts +3 -1
  23. package/lib/contracts/types.js +3 -1
  24. package/lib/contracts/write.d.ts +34 -2
  25. package/lib/contracts/write.js +48 -1
  26. package/lib/crypto/encryption.js +4 -4
  27. package/lib/engine/car.d.ts +2 -2
  28. package/lib/engine/car.js +10 -5
  29. package/lib/engine/index.d.ts +99 -143
  30. package/lib/engine/index.js +156 -295
  31. package/lib/engine/records.d.ts +110 -0
  32. package/lib/engine/records.js +165 -0
  33. package/lib/engine/test-helpers.d.ts +7 -14
  34. package/lib/engine/test-helpers.js +7 -18
  35. package/lib/fangorn.d.ts +129 -156
  36. package/lib/fangorn.js +250 -250
  37. package/lib/feed.d.ts +7 -4
  38. package/lib/feed.js +4 -1
  39. package/lib/index.d.ts +9 -9
  40. package/lib/index.js +8 -9
  41. package/lib/node_modules/@jridgewell/sourcemap-codec/dist/sourcemap-codec.js +77 -0
  42. package/lib/node_modules/@vitest/expect/dist/index.js +1414 -0
  43. package/lib/node_modules/@vitest/pretty-format/dist/index.js +858 -0
  44. package/lib/node_modules/@vitest/runner/dist/chunk-tasks.js +51 -0
  45. package/lib/node_modules/@vitest/runner/dist/index.js +1199 -0
  46. package/lib/node_modules/@vitest/runner/dist/utils.js +3 -0
  47. package/lib/node_modules/@vitest/snapshot/dist/index.js +1075 -0
  48. package/lib/node_modules/@vitest/spy/dist/index.js +353 -0
  49. package/lib/node_modules/@vitest/utils/dist/chunk-_commonjsHelpers.js +7 -0
  50. package/lib/node_modules/@vitest/utils/dist/chunk-pathe.M-eThtNZ.js +81 -0
  51. package/lib/node_modules/@vitest/utils/dist/diff.js +1345 -0
  52. package/lib/node_modules/@vitest/utils/dist/display.js +534 -0
  53. package/lib/node_modules/@vitest/utils/dist/error.js +30 -0
  54. package/lib/node_modules/@vitest/utils/dist/helpers.js +118 -0
  55. package/lib/node_modules/@vitest/utils/dist/serialize.js +76 -0
  56. package/lib/node_modules/@vitest/utils/dist/source-map.js +93 -0
  57. package/lib/node_modules/@vitest/utils/dist/timers.js +36 -0
  58. package/lib/node_modules/chai/index.js +2874 -0
  59. package/lib/node_modules/magic-string/dist/magic-string.es.js +939 -0
  60. package/lib/node_modules/pathe/dist/shared/pathe.M-eThtNZ.js +81 -0
  61. package/lib/node_modules/tinyrainbow/dist/index.js +85 -0
  62. package/lib/node_modules/vitest/dist/chunks/_commonjsHelpers.D26ty3Ew.js +5 -0
  63. package/lib/node_modules/vitest/dist/chunks/date.Bq6ZW5rf.js +50 -0
  64. package/lib/node_modules/vitest/dist/chunks/utils.DvEY5TfP.js +44 -0
  65. package/lib/node_modules/vitest/dist/chunks/vi.2VT5v0um.js +2578 -0
  66. package/lib/providers/storage/signed-url.d.ts +16 -6
  67. package/lib/providers/storage/signed-url.js +20 -8
  68. package/lib/registry.d.ts +116 -0
  69. package/lib/registry.js +182 -0
  70. package/lib/test/mem-registry.d.ts +51 -0
  71. package/lib/test/mem-registry.js +107 -0
  72. package/lib/test/sdk-suite.d.ts +13 -0
  73. package/lib/test/sdk-suite.js +226 -0
  74. package/lib/test/testbed.d.ts +16411 -61
  75. package/lib/test/testbed.js +190 -84
  76. package/lib/types/index.d.ts +13 -11
  77. package/package.json +89 -73
  78. package/lib/contracts/data-registry/test.d.ts +0 -1
  79. package/lib/contracts/data-registry/test.js +0 -1
  80. package/lib/contracts/settlement-registry/abi.d.ts +0 -466
  81. package/lib/contracts/settlement-registry/abi.js +0 -535
  82. package/lib/contracts/settlement-registry/index.d.ts +0 -163
  83. package/lib/contracts/settlement-registry/index.js +0 -264
  84. package/lib/contracts/subscription-registry/abi.d.ts +0 -179
  85. package/lib/contracts/subscription-registry/abi.js +0 -195
  86. package/lib/contracts/subscription-registry/index.d.ts +0 -59
  87. package/lib/contracts/subscription-registry/index.js +0 -116
  88. package/lib/engine/graph.d.ts +0 -70
  89. package/lib/engine/graph.js +0 -73
@@ -0,0 +1,79 @@
1
+ import { Address, Hash, Hex, PublicClient, WalletClient } from "viem";
2
+
3
+ //#region src/contracts/membership-registry/index.d.ts
4
+ /** A signed ERC-3009 `receiveWithAuthorization` paying the registry, as `join` takes it. */
5
+ interface MembershipPayment {
6
+ from: Address;
7
+ value: bigint;
8
+ validAfter: bigint;
9
+ validBefore: bigint;
10
+ nonce: Hex;
11
+ v: number;
12
+ r: Hex;
13
+ s: Hex;
14
+ }
15
+ /** What `join` needs besides the payment: the app, the commitment, the salt in the nonce. */
16
+ interface JoinArgs {
17
+ appId: Hex;
18
+ commitment: bigint;
19
+ salt: Hex;
20
+ payment: MembershipPayment;
21
+ }
22
+ /** What `claim` needs: a Semaphore proof over the (app, epoch) group, message = holder. */
23
+ interface ClaimArgs {
24
+ appId: Hex;
25
+ epoch: bigint;
26
+ holder: Address;
27
+ merkleTreeDepth: bigint;
28
+ merkleTreeRoot: bigint;
29
+ nullifier: bigint;
30
+ points: readonly [bigint, bigint, bigint, bigint, bigint, bigint, bigint, bigint];
31
+ }
32
+ /** The nonce a payer signs for `join`, the same derivation as the contract's `joinNonce`. */
33
+ declare const joinNonce: (appId: Hex, epoch: bigint, commitment: bigint, salt: Hex) => Hex;
34
+ /** The Semaphore scope of (app, epoch), as the contract fixes it in `claim`. */
35
+ declare const membershipScope: (appId: Hex, epoch: bigint) => bigint;
36
+ /** A holder's membership token id in an app. */
37
+ declare const membershipTokenId: (appId: Hex, holder: Address) => bigint;
38
+ /**
39
+ * Client for the MembershipRegistry.
40
+ *
41
+ * The app owner's half is here (`setPlan`), with the reads every gate needs
42
+ * (`canRead`, `planOf`, `currentEpoch`) and the two relayed writes (`join`, `claim`),
43
+ * which take what a buyer signed and proved, so anyone may submit them; Barliman does.
44
+ *
45
+ * The buyer's half (Semaphore identity, stealth holder, the payment signature, the
46
+ * group from `Joined` logs, the proof) lives in `@fangorn-network/fetch`: this SDK
47
+ * carries no Semaphore proving dependency.
48
+ */
49
+ declare class MembershipRegistryClient {
50
+ private contractAddress;
51
+ private publicClient;
52
+ private walletClient?;
53
+ constructor(contractAddress: Address, publicClient: PublicClient, walletClient?: WalletClient | undefined);
54
+ getAddress(): Address;
55
+ private write;
56
+ private read;
57
+ /** Price (USDC base units) and period (seconds) of a membership in `appId`. App owner only. */
58
+ setPlan(appId: Hex, price: bigint, period: bigint): Promise<Hash>;
59
+ join({
60
+ appId,
61
+ commitment,
62
+ salt,
63
+ payment
64
+ }: JoinArgs): Promise<Hash>;
65
+ claim(a: ClaimArgs): Promise<Hash>;
66
+ planOf(appId: Hex): Promise<{
67
+ price: bigint;
68
+ period: bigint;
69
+ }>;
70
+ currentEpoch(appId: Hex): Promise<bigint>;
71
+ /** What `who` may read with `tokenId`: the app, and until when (seconds; 0 = nothing). */
72
+ canRead(tokenId: bigint, who: Address): Promise<{
73
+ appId: Hex;
74
+ until: bigint;
75
+ }>;
76
+ expiresAt(tokenId: bigint): Promise<bigint>;
77
+ }
78
+ //#endregion
79
+ export { ClaimArgs, JoinArgs, MembershipPayment, MembershipRegistryClient, joinNonce, membershipScope, membershipTokenId };
@@ -0,0 +1,104 @@
1
+ import { requireWallet, sendWrite } from "../write.js";
2
+ import { MEMBERSHIP_REGISTRY_ABI } from "./abi.js";
3
+ import { encodeAbiParameters, keccak256 } from "viem";
4
+
5
+ //#region src/contracts/membership-registry/index.ts
6
+ /** The nonce a payer signs for `join`, the same derivation as the contract's `joinNonce`. */
7
+ const joinNonce = (appId, epoch, commitment, salt) => keccak256(encodeAbiParameters([
8
+ { type: "bytes32" },
9
+ { type: "uint256" },
10
+ { type: "uint256" },
11
+ { type: "bytes32" }
12
+ ], [
13
+ appId,
14
+ epoch,
15
+ commitment,
16
+ salt
17
+ ]));
18
+ /** The Semaphore scope of (app, epoch), as the contract fixes it in `claim`. */
19
+ const membershipScope = (appId, epoch) => BigInt(keccak256(encodeAbiParameters([{ type: "bytes32" }, { type: "uint256" }], [appId, epoch])));
20
+ /** A holder's membership token id in an app. */
21
+ const membershipTokenId = (appId, holder) => BigInt(keccak256(encodeAbiParameters([{ type: "bytes32" }, { type: "address" }], [appId, holder])));
22
+ /**
23
+ * Client for the MembershipRegistry.
24
+ *
25
+ * The app owner's half is here (`setPlan`), with the reads every gate needs
26
+ * (`canRead`, `planOf`, `currentEpoch`) and the two relayed writes (`join`, `claim`),
27
+ * which take what a buyer signed and proved, so anyone may submit them; Barliman does.
28
+ *
29
+ * The buyer's half (Semaphore identity, stealth holder, the payment signature, the
30
+ * group from `Joined` logs, the proof) lives in `@fangorn-network/fetch`: this SDK
31
+ * carries no Semaphore proving dependency.
32
+ */
33
+ var MembershipRegistryClient = class {
34
+ constructor(contractAddress, publicClient, walletClient) {
35
+ this.contractAddress = contractAddress;
36
+ this.publicClient = publicClient;
37
+ this.walletClient = walletClient;
38
+ }
39
+ getAddress() {
40
+ return this.contractAddress;
41
+ }
42
+ write(functionName, args) {
43
+ return sendWrite(this.publicClient, requireWallet(this.walletClient, functionName), this.contractAddress, MEMBERSHIP_REGISTRY_ABI, functionName, args);
44
+ }
45
+ read(functionName, args = []) {
46
+ return this.publicClient.readContract({
47
+ address: this.contractAddress,
48
+ abi: MEMBERSHIP_REGISTRY_ABI,
49
+ functionName,
50
+ args
51
+ });
52
+ }
53
+ /** Price (USDC base units) and period (seconds) of a membership in `appId`. App owner only. */
54
+ setPlan(appId, price, period) {
55
+ return this.write("setPlan", [
56
+ appId,
57
+ price,
58
+ period
59
+ ]);
60
+ }
61
+ join({ appId, commitment, salt, payment }) {
62
+ return this.write("join", [
63
+ appId,
64
+ commitment,
65
+ salt,
66
+ payment
67
+ ]);
68
+ }
69
+ claim(a) {
70
+ return this.write("claim", [
71
+ a.appId,
72
+ a.epoch,
73
+ a.holder,
74
+ a.merkleTreeDepth,
75
+ a.merkleTreeRoot,
76
+ a.nullifier,
77
+ a.points
78
+ ]);
79
+ }
80
+ async planOf(appId) {
81
+ const [price, period] = await this.read("planOf", [appId]);
82
+ return {
83
+ price,
84
+ period
85
+ };
86
+ }
87
+ currentEpoch(appId) {
88
+ return this.read("currentEpoch", [appId]);
89
+ }
90
+ /** What `who` may read with `tokenId`: the app, and until when (seconds; 0 = nothing). */
91
+ async canRead(tokenId, who) {
92
+ const [appId, until] = await this.read("canRead", [tokenId, who]);
93
+ return {
94
+ appId,
95
+ until
96
+ };
97
+ }
98
+ expiresAt(tokenId) {
99
+ return this.read("expiresAt", [tokenId]);
100
+ }
101
+ };
102
+
103
+ //#endregion
104
+ export { MembershipRegistryClient, joinNonce, membershipScope, membershipTokenId };
@@ -1,8 +1,10 @@
1
1
  //#region src/contracts/types.d.ts
2
2
  declare enum PublisherStatus {
3
- UNREGISTERED = 0,
3
+ NONE = 0,
4
4
  ACTIVE = 1,
5
5
  SUSPENDED = 2,
6
+ /** Retired: invited under the old join flow and never joined. Not a member. */
7
+ INVITED = 3,
6
8
  }
7
9
  //#endregion
8
10
  export { PublisherStatus };
@@ -1,8 +1,10 @@
1
1
  //#region src/contracts/types.ts
2
2
  let PublisherStatus = /* @__PURE__ */ function(PublisherStatus$1) {
3
- PublisherStatus$1[PublisherStatus$1["UNREGISTERED"] = 0] = "UNREGISTERED";
3
+ PublisherStatus$1[PublisherStatus$1["NONE"] = 0] = "NONE";
4
4
  PublisherStatus$1[PublisherStatus$1["ACTIVE"] = 1] = "ACTIVE";
5
5
  PublisherStatus$1[PublisherStatus$1["SUSPENDED"] = 2] = "SUSPENDED";
6
+ /** Retired: invited under the old join flow and never joined. Not a member. */
7
+ PublisherStatus$1[PublisherStatus$1["INVITED"] = 3] = "INVITED";
6
8
  return PublisherStatus$1;
7
9
  }({});
8
10
 
@@ -1,7 +1,19 @@
1
- import { Abi, Address, Hash, PublicClient, WalletClient } from "viem";
1
+ import { Abi, Address, Hash, Hex, PublicClient, WalletClient } from "viem";
2
2
 
3
3
  //#region src/contracts/write.d.ts
4
4
 
5
+ /**
6
+ * An unsigned transaction, hex-encoded and ready to hand to a browser wallet's
7
+ * `eth_sendTransaction` — no `from`, since the signing wallet supplies it.
8
+ */
9
+ interface PreparedTx {
10
+ to: Address;
11
+ data: Hex;
12
+ chainId: number | undefined;
13
+ gas: Hex;
14
+ maxFeePerGas: Hex;
15
+ maxPriorityFeePerGas: Hex;
16
+ }
5
17
  /**
6
18
  * The one write path every contract client shares.
7
19
  *
@@ -23,5 +35,25 @@ import { Abi, Address, Hash, PublicClient, WalletClient } from "viem";
23
35
  declare function sendWrite(publicClient: PublicClient, walletClient: WalletClient, address: Address, abi: Abi, functionName: string, args: readonly unknown[], value?: bigint): Promise<Hash>;
24
36
  /** Guard for clients that accept a read-only construction. */
25
37
  declare function requireWallet(walletClient: WalletClient | undefined, what: string): WalletClient;
38
+ /**
39
+ * Build a call as an UNSIGNED transaction for `from` to sign in their own wallet,
40
+ * instead of sending it from a client's wallet.
41
+ *
42
+ * Fees and gas are quoted here rather than left to the wallet. Wallet estimation
43
+ * runs too tight against a live L2 base fee, and an eth_estimateGas from the
44
+ * wallet against a public RPC is what surfaces as "Network fee Unavailable" in
45
+ * MetaMask. maxFeePerGas is only a ceiling — you pay base+priority — so headroom
46
+ * costs nothing.
47
+ *
48
+ * Simulating also turns a would-be revert into a clear error now, naming the
49
+ * contract's reason, instead of a cryptic wallet message after the user has
50
+ * already clicked sign. `simulate: false` skips it for a call that can only
51
+ * succeed after an earlier one in the same batch lands (a join after its
52
+ * approval); `fallbackGas` is then the gas, as it is when the RPC fails.
53
+ */
54
+ declare function prepareWrite(publicClient: PublicClient, from: Address, address: Address, abi: Abi, functionName: string, args: readonly unknown[], opts: {
55
+ fallbackGas: bigint;
56
+ simulate?: boolean;
57
+ }): Promise<PreparedTx>;
26
58
  //#endregion
27
- export { requireWallet, sendWrite };
59
+ export { PreparedTx, prepareWrite, requireWallet, sendWrite };
@@ -1,3 +1,5 @@
1
+ import { encodeFunctionData, toHex } from "viem";
2
+
1
3
  //#region src/contracts/write.ts
2
4
  /**
3
5
  * The one write path every contract client shares.
@@ -50,6 +52,51 @@ function requireWallet(walletClient, what) {
50
52
  if (!walletClient) throw new Error(`${what} requires a wallet client; this client is read-only`);
51
53
  return walletClient;
52
54
  }
55
+ /**
56
+ * Build a call as an UNSIGNED transaction for `from` to sign in their own wallet,
57
+ * instead of sending it from a client's wallet.
58
+ *
59
+ * Fees and gas are quoted here rather than left to the wallet. Wallet estimation
60
+ * runs too tight against a live L2 base fee, and an eth_estimateGas from the
61
+ * wallet against a public RPC is what surfaces as "Network fee Unavailable" in
62
+ * MetaMask. maxFeePerGas is only a ceiling — you pay base+priority — so headroom
63
+ * costs nothing.
64
+ *
65
+ * Simulating also turns a would-be revert into a clear error now, naming the
66
+ * contract's reason, instead of a cryptic wallet message after the user has
67
+ * already clicked sign. `simulate: false` skips it for a call that can only
68
+ * succeed after an earlier one in the same batch lands (a join after its
69
+ * approval); `fallbackGas` is then the gas, as it is when the RPC fails.
70
+ */
71
+ async function prepareWrite(publicClient, from, address, abi, functionName, args, opts) {
72
+ const data = encodeFunctionData({
73
+ abi,
74
+ functionName,
75
+ args
76
+ });
77
+ const fees = await publicClient.estimateFeesPerGas();
78
+ let gas = opts.fallbackGas;
79
+ if (opts.simulate ?? true) try {
80
+ gas = await publicClient.estimateContractGas({
81
+ address,
82
+ abi,
83
+ functionName,
84
+ args,
85
+ account: from
86
+ }) * 3n / 2n;
87
+ } catch (err) {
88
+ const message = err instanceof Error ? err.message : String(err);
89
+ if (/revert/i.test(message)) throw new Error(`${functionName} would revert: ${message}`);
90
+ }
91
+ return {
92
+ to: address,
93
+ data,
94
+ chainId: publicClient.chain?.id,
95
+ gas: toHex(gas),
96
+ maxFeePerGas: toHex(fees.maxFeePerGas * 2n),
97
+ maxPriorityFeePerGas: toHex(fees.maxPriorityFeePerGas)
98
+ };
99
+ }
53
100
 
54
101
  //#endregion
55
- export { requireWallet, sendWrite };
102
+ export { prepareWrite, requireWallet, sendWrite };
@@ -11,7 +11,7 @@ const GADGET_WORKER_USDC_V1 = "worker-usdc-v1";
11
11
  /** Length of an X25519 public key, in bytes. */
12
12
  const X25519_PUBKEY_LENGTH = 32;
13
13
  const utf8 = (s) => new TextEncoder().encode(s);
14
- function concat$1(...parts) {
14
+ function concat(...parts) {
15
15
  const total = parts.reduce((n, p) => n + p.length, 0);
16
16
  const out = new Uint8Array(total);
17
17
  let off = 0;
@@ -23,7 +23,7 @@ function concat$1(...parts) {
23
23
  }
24
24
  const hkdfSha256 = (ikm, salt, info, length) => hkdf(sha256, ikm, salt, info, length);
25
25
  const sha256Hex = (bytes) => bytesToHex(sha256(bytes));
26
- const sealInfo = (resourceId) => concat$1(hexToBytes(resourceId), utf8(":sealed"));
26
+ const sealInfo = (resourceId) => concat(hexToBytes(resourceId), utf8(":sealed"));
27
27
  /**
28
28
  * worker-usdc-v1 seal: ephemeral-static ECDH to the worker's static key, keyed
29
29
  * to the resourceId.
@@ -38,7 +38,7 @@ function seal(plaintext, workerPubkey, resourceId) {
38
38
  const ephPub = x25519.getPublicKey(ephSec);
39
39
  const aesKey = hkdfSha256(x25519.getSharedSecret(ephSec, workerPubkey), void 0, sealInfo(resourceId), 32);
40
40
  const nonce = getRandomValues(new Uint8Array(GCM_NONCE_LENGTH));
41
- return concat$1(ephPub, nonce, aesGcmEncrypt(aesKey, plaintext, nonce));
41
+ return concat(ephPub, nonce, aesGcmEncrypt(aesKey, plaintext, nonce));
42
42
  }
43
43
  /**
44
44
  * Inverse of {@link seal}. Recovers the plaintext given the worker's static
@@ -62,7 +62,7 @@ function unseal(ciphertext, workerSecret, resourceId) {
62
62
  function sealSelf(plaintext, ownSecret, resourceId) {
63
63
  const aesKey = hkdfSha256(ownSecret, void 0, sealInfo(resourceId), 32);
64
64
  const nonce = getRandomValues(new Uint8Array(GCM_NONCE_LENGTH));
65
- return concat$1(nonce, aesGcmEncrypt(aesKey, plaintext, nonce));
65
+ return concat(nonce, aesGcmEncrypt(aesKey, plaintext, nonce));
66
66
  }
67
67
  /** Inverse of {@link sealSelf}. */
68
68
  function unsealSelf(ciphertext, ownSecret, resourceId) {
@@ -1,10 +1,10 @@
1
- import { Block } from "./graph.js";
1
+ import { Block } from "./records.js";
2
2
  import { CID } from "multiformats/cid";
3
3
 
4
4
  //#region src/engine/car.d.ts
5
5
  /** Serialize blocks into CAR v1 bytes under a single root. */
6
6
  declare function packCar(root: CID, blocks: Iterable<Block>): Promise<Uint8Array>;
7
- /** Decode CAR bytes back into blocks. */
7
+ /** Decode CAR bytes back into blocks, each checked against its CID (the host is untrusted). */
8
8
  declare function readCar(bytes: Uint8Array): Promise<Block[]>;
9
9
  //#endregion
10
10
  export { packCar, readCar };
package/lib/engine/car.js CHANGED
@@ -1,3 +1,4 @@
1
+ import { assertBlockMatches } from "./records.js";
1
2
  import { CID } from "multiformats/cid";
2
3
  import { CarReader, CarWriter } from "@ipld/car";
3
4
 
@@ -22,14 +23,18 @@ async function packCar(root, blocks) {
22
23
  }
23
24
  return buf;
24
25
  }
25
- /** Decode CAR bytes back into blocks. */
26
+ /** Decode CAR bytes back into blocks, each checked against its CID (the host is untrusted). */
26
27
  async function readCar(bytes) {
27
28
  const reader = await CarReader.fromBytes(bytes);
28
29
  const blocks = [];
29
- for await (const { cid, bytes: blockBytes } of reader.blocks()) blocks.push({
30
- cid: CID.parse(cid.toString()),
31
- bytes: blockBytes
32
- });
30
+ for await (const { cid, bytes: blockBytes } of reader.blocks()) {
31
+ const ours = CID.parse(cid.toString());
32
+ assertBlockMatches(ours, blockBytes);
33
+ blocks.push({
34
+ cid: ours,
35
+ bytes: blockBytes
36
+ });
37
+ }
33
38
  return blocks;
34
39
  }
35
40