@fangorn-network/sdk 0.1.0 → 0.1.1

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 (71) hide show
  1. package/lib/cli/cli.js +128 -328
  2. package/lib/cli/index.d.ts +1 -4
  3. package/lib/cli/index.js +2 -20
  4. package/lib/cli/sell.d.ts +28 -0
  5. package/lib/cli/sell.js +95 -0
  6. package/lib/cli/stage.d.ts +19 -0
  7. package/lib/cli/stage.js +94 -0
  8. package/lib/config.d.ts +16 -79
  9. package/lib/config.js +11 -39
  10. package/lib/contracts/data-registry/abi.d.ts +195 -19
  11. package/lib/contracts/data-registry/abi.js +409 -206
  12. package/lib/contracts/data-registry/index.d.ts +126 -2
  13. package/lib/contracts/data-registry/index.js +174 -1
  14. package/lib/contracts/index.d.ts +4 -7
  15. package/lib/contracts/index.js +4 -7
  16. package/lib/contracts/logs.d.ts +1 -1
  17. package/lib/contracts/logs.js +1 -1
  18. package/lib/contracts/{membership-registry → settlement-registry}/abi.d.ts +301 -636
  19. package/lib/contracts/settlement-registry/abi.js +962 -0
  20. package/lib/contracts/settlement-registry/index.d.ts +143 -0
  21. package/lib/contracts/settlement-registry/index.js +213 -0
  22. package/lib/crypto/aes.d.ts +2 -2
  23. package/lib/crypto/aes.js +4 -4
  24. package/lib/crypto/encryption.d.ts +8 -109
  25. package/lib/crypto/encryption.js +16 -114
  26. package/lib/crypto/paid.d.ts +104 -0
  27. package/lib/crypto/paid.js +147 -0
  28. package/lib/engine/car.d.ts +5 -1
  29. package/lib/engine/car.js +2 -2
  30. package/lib/engine/index.d.ts +33 -14
  31. package/lib/engine/index.js +98 -41
  32. package/lib/engine/records.d.ts +19 -8
  33. package/lib/engine/records.js +81 -7
  34. package/lib/engine/test-helpers.d.ts +2 -3
  35. package/lib/engine/test-helpers.js +7 -5
  36. package/lib/erc8004.js +7 -10
  37. package/lib/fangorn.d.ts +65 -86
  38. package/lib/fangorn.js +115 -153
  39. package/lib/feed.d.ts +7 -8
  40. package/lib/feed.js +7 -8
  41. package/lib/index.d.ts +10 -13
  42. package/lib/index.js +10 -13
  43. package/lib/providers/storage/signed-url.d.ts +2 -10
  44. package/lib/providers/storage/signed-url.js +5 -15
  45. package/lib/providers/storage/types.d.ts +1 -1
  46. package/lib/providers/storage/utils.js +5 -3
  47. package/lib/test/key-server.d.ts +12 -0
  48. package/lib/test/key-server.js +30 -0
  49. package/lib/test/mem-registry.d.ts +14 -19
  50. package/lib/test/mem-registry.js +44 -37
  51. package/lib/test/sdk-suite.d.ts +1 -4
  52. package/lib/test/sdk-suite.js +16 -87
  53. package/lib/test/testbed.d.ts +5130 -5140
  54. package/lib/test/testbed.js +29 -56
  55. package/lib/types/index.d.ts +6 -11
  56. package/package.json +1 -1
  57. package/lib/contracts/app-registry/abi.d.ts +0 -1265
  58. package/lib/contracts/app-registry/abi.js +0 -1454
  59. package/lib/contracts/app-registry/index.d.ts +0 -161
  60. package/lib/contracts/app-registry/index.js +0 -274
  61. package/lib/contracts/membership-registry/abi.js +0 -1333
  62. package/lib/contracts/membership-registry/index.d.ts +0 -79
  63. package/lib/contracts/membership-registry/index.js +0 -104
  64. package/lib/contracts/types.d.ts +0 -10
  65. package/lib/contracts/types.js +0 -12
  66. package/lib/harness/examples/hackmd/build-markdown-graph.d.ts +0 -1
  67. package/lib/harness/examples/hackmd/build-markdown-graph.js +0 -17
  68. package/lib/harness/index.d.ts +0 -58
  69. package/lib/harness/index.js +0 -73
  70. package/lib/registry.d.ts +0 -118
  71. package/lib/registry.js +0 -184
@@ -1,17 +1,17 @@
1
1
  import { GCM_NONCE_LENGTH, aesGcmDecrypt, aesGcmEncrypt } from "./aes.js";
2
2
  import { getRandomValues } from "./rand.js";
3
- import { bytesToHex, encodePacked, hexToBytes, keccak256 } from "viem";
4
- import { x25519 } from "@noble/curves/ed25519";
3
+ import { hexToBytes } from "viem";
5
4
  import { sha256 } from "@noble/hashes/sha2.js";
5
+ import { x25519 } from "@noble/curves/ed25519";
6
6
  import { hkdf } from "@noble/hashes/hkdf.js";
7
7
 
8
8
  //#region src/crypto/encryption.ts
9
+ /** A field only its owner can open: sealSelf under the owner's own secret. */
9
10
  const GADGET_SELF_HKDF_V1 = "self-hkdf-v1";
10
- 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(...parts) {
14
+ function concat$1(...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;
@@ -22,38 +22,31 @@ function concat(...parts) {
22
22
  return out;
23
23
  }
24
24
  const hkdfSha256 = (ikm, salt, info, length) => hkdf(sha256, ikm, salt, info, length);
25
- const sha256Hex = (bytes) => bytesToHex(sha256(bytes));
26
- const sealInfo = (resourceId) => concat(hexToBytes(resourceId), utf8(":sealed"));
25
+ const sealInfo = (resourceId) => concat$1(hexToBytes(resourceId), utf8(":sealed"));
27
26
  /**
28
- * worker-usdc-v1 seal: ephemeral-static ECDH to the worker's static key, keyed
29
- * to the resourceId.
27
+ * Ephemeral-static ECDH to the recipient's static key, keyed to the resourceId.
30
28
  *
31
29
  * ciphertext = ephemeralPub(32) || nonce(12) || aes-256-gcm-ct
32
30
  *
33
- * Only the holder of the secret matching `workerPubkey` can derive the same AES
31
+ * Only the holder of the secret matching `recipientPubkey` can derive the same AES
34
32
  * key, and only with the matching `resourceId`.
35
33
  */
36
- function seal(plaintext, workerPubkey, resourceId) {
34
+ function seal(plaintext, recipientPubkey, resourceId) {
37
35
  const ephSec = x25519.utils.randomSecretKey();
38
36
  const ephPub = x25519.getPublicKey(ephSec);
39
- const aesKey = hkdfSha256(x25519.getSharedSecret(ephSec, workerPubkey), void 0, sealInfo(resourceId), 32);
37
+ const aesKey = hkdfSha256(x25519.getSharedSecret(ephSec, recipientPubkey), void 0, sealInfo(resourceId), 32);
40
38
  const nonce = getRandomValues(new Uint8Array(GCM_NONCE_LENGTH));
41
- return concat(ephPub, nonce, aesGcmEncrypt(aesKey, plaintext, nonce));
39
+ return concat$1(ephPub, nonce, aesGcmEncrypt(aesKey, plaintext, nonce));
42
40
  }
43
- /**
44
- * Inverse of {@link seal}. Recovers the plaintext given the worker's static
45
- * secret and the same resourceId. This is the operation the access worker
46
- * performs after the settlement gate passes; exposed here for parity testing
47
- * and local tooling.
48
- */
49
- function unseal(ciphertext, workerSecret, resourceId) {
41
+ /** Inverse of {@link seal}, with the recipient's secret and the same resourceId. */
42
+ function unseal(ciphertext, recipientSecret, resourceId) {
50
43
  const ephPub = ciphertext.slice(0, X25519_PUBKEY_LENGTH);
51
44
  const nonce = ciphertext.slice(X25519_PUBKEY_LENGTH, X25519_PUBKEY_LENGTH + GCM_NONCE_LENGTH);
52
45
  const aesCt = ciphertext.slice(X25519_PUBKEY_LENGTH + GCM_NONCE_LENGTH);
53
- return aesGcmDecrypt(hkdfSha256(x25519.getSharedSecret(workerSecret, ephPub), void 0, sealInfo(resourceId), 32), aesCt, nonce);
46
+ return aesGcmDecrypt(hkdfSha256(x25519.getSharedSecret(recipientSecret, ephPub), void 0, sealInfo(resourceId), 32), aesCt, nonce);
54
47
  }
55
48
  /**
56
- * self-hkdf-v1 seal: derive the AES key straight from the owner's own 32-byte
49
+ * Derive the AES key straight from the owner's own 32-byte
57
50
  * secret, bound to the resourceId. No ECDH, no recipient — only a party holding
58
51
  * `ownSecret` can re-derive the key.
59
52
  *
@@ -62,7 +55,7 @@ function unseal(ciphertext, workerSecret, resourceId) {
62
55
  function sealSelf(plaintext, ownSecret, resourceId) {
63
56
  const aesKey = hkdfSha256(ownSecret, void 0, sealInfo(resourceId), 32);
64
57
  const nonce = getRandomValues(new Uint8Array(GCM_NONCE_LENGTH));
65
- return concat(nonce, aesGcmEncrypt(aesKey, plaintext, nonce));
58
+ return concat$1(nonce, aesGcmEncrypt(aesKey, plaintext, nonce));
66
59
  }
67
60
  /** Inverse of {@link sealSelf}. */
68
61
  function unsealSelf(ciphertext, ownSecret, resourceId) {
@@ -70,97 +63,6 @@ function unsealSelf(ciphertext, ownSecret, resourceId) {
70
63
  const aesCt = ciphertext.slice(GCM_NONCE_LENGTH);
71
64
  return aesGcmDecrypt(hkdfSha256(ownSecret, void 0, sealInfo(resourceId), 32), aesCt, nonce);
72
65
  }
73
- /**
74
- * Seal `plaintext` under the chosen gadget, upload the opaque ciphertext to the
75
- * access worker (which writes it to R2), and return the handle describing where
76
- * to fetch it and how to open it.
77
- */
78
- async function encryptAndUpload(params) {
79
- const { plaintext, resourceId, storage } = params;
80
- const ciphertext = params.gadget === GADGET_SELF_HKDF_V1 ? sealSelf(plaintext, params.ownSecret, resourceId) : seal(plaintext, params.workerPubkey, resourceId);
81
- const uploadRes = await fetch(`${storage.workerUrl}/upload`, {
82
- method: "POST",
83
- headers: {
84
- Authorization: `Bearer ${storage.authToken}`,
85
- "Content-Type": storage.contentType
86
- },
87
- body: ciphertext
88
- });
89
- if (!uploadRes.ok) throw new Error(`upload failed: ${uploadRes.status.toString()}`);
90
- const { objectKey } = await uploadRes.json();
91
- return {
92
- "@type": "handle",
93
- objectKey,
94
- workerUrl: storage.workerUrl,
95
- encryption: {
96
- gadget: params.gadget,
97
- resourceId,
98
- ciphertextHash: sha256Hex(ciphertext),
99
- ...params.gadget === GADGET_WORKER_USDC_V1 ? { workerPubkey: bytesToHex(params.workerPubkey) } : {}
100
- }
101
- };
102
- }
103
- /**
104
- * The message the worker recovers the stealth address from — must match
105
- * `buildMessageHash` in the worker byte-for-byte:
106
- * keccak256(abi.encodePacked(uint256 nullifier, bytes32 resourceId, string objectKey, uint64 timestamp))
107
- */
108
- function accessMessageHash(nullifier, resourceId, objectKey, timestamp) {
109
- return keccak256(encodePacked([
110
- "uint256",
111
- "bytes32",
112
- "string",
113
- "uint64"
114
- ], [
115
- BigInt(nullifier),
116
- resourceId,
117
- objectKey,
118
- BigInt(timestamp)
119
- ]));
120
- }
121
- /** Sign the packed message so the worker can recover the settling stealth address. */
122
- async function buildAccessRequest(params) {
123
- const timestamp = params.timestamp ?? Math.floor(Date.now() / 1e3);
124
- const hash = accessMessageHash(params.nullifier, params.resourceId, params.objectKey, timestamp);
125
- const signature = await params.signer.signMessage({ message: { raw: hash } });
126
- return {
127
- nullifier: params.nullifier,
128
- resourceId: params.resourceId,
129
- objectKey: params.objectKey,
130
- timestamp,
131
- signature
132
- };
133
- }
134
- /**
135
- * Resolve a {@link HandleFieldInput} back to plaintext via the worker's
136
- * settlement-gated `POST /access`.
137
- *
138
- * self-hkdf-v1 bytes come back sealed → verify hash → unseal with ownSecret.
139
- * worker-usdc-v1 the worker already unsealed → bytes are plaintext.
140
- */
141
- async function decryptHandle(params) {
142
- const { handle, signer, nullifier } = params;
143
- const { gadget, resourceId, ciphertextHash } = handle.encryption;
144
- const access = await buildAccessRequest({
145
- signer,
146
- nullifier,
147
- resourceId,
148
- objectKey: handle.objectKey
149
- });
150
- const res = await fetch(`${handle.workerUrl}/access`, {
151
- method: "POST",
152
- headers: { "Content-Type": "application/json" },
153
- body: JSON.stringify(access)
154
- });
155
- if (!res.ok) throw new Error(`access failed: ${res.status.toString()}`);
156
- const bytes = new Uint8Array(await res.arrayBuffer());
157
- if (gadget === GADGET_SELF_HKDF_V1) {
158
- if (!params.ownSecret) throw new Error(`${gadget} requires ownSecret to decrypt`);
159
- if (sha256Hex(bytes) !== ciphertextHash) throw new Error("ciphertext hash mismatch");
160
- return unsealSelf(bytes, params.ownSecret, resourceId);
161
- }
162
- return bytes;
163
- }
164
66
 
165
67
  //#endregion
166
- export { GADGET_SELF_HKDF_V1, GADGET_WORKER_USDC_V1, X25519_PUBKEY_LENGTH, accessMessageHash, buildAccessRequest, decryptHandle, encryptAndUpload, seal, sealSelf, sha256Hex, unseal, unsealSelf };
68
+ export { GADGET_SELF_HKDF_V1, X25519_PUBKEY_LENGTH, seal, sealSelf, unseal, unsealSelf };
@@ -0,0 +1,104 @@
1
+ import { MetadataStorage } from "../providers/storage/types.js";
2
+ import { AccessSigner } from "./encryption.js";
3
+ import { Address, Hex } from "viem";
4
+
5
+ //#region src/crypto/paid.d.ts
6
+ declare const GADGET_FIELD_V1 = "field-v1";
7
+ /** What a repo key is sealed under. `repo` is `repoId(name)`. */
8
+ interface PaidScope {
9
+ chainId: number;
10
+ registry: Address;
11
+ publisher: Address;
12
+ repo: Hex;
13
+ generation: bigint;
14
+ }
15
+ /** The repo key, sealed to a key server. Public: it goes in the repo as a record. */
16
+ interface Deposit {
17
+ "@type": "deposit";
18
+ gadget: typeof GADGET_FIELD_V1;
19
+ chainId: number;
20
+ registry: Address;
21
+ publisher: Address;
22
+ repo: Hex;
23
+ generation: string;
24
+ keyServer: string;
25
+ sealed: Hex;
26
+ }
27
+ /** A paid field's value in a record payload. */
28
+ interface FieldHandle {
29
+ "@type": "handle";
30
+ gadget: typeof GADGET_FIELD_V1;
31
+ generation: string;
32
+ cid: string;
33
+ }
34
+ /** What a buyer posts to a key server's `/access`. */
35
+ interface AccessRequest {
36
+ publisher: Address;
37
+ repo: Hex;
38
+ generation: string;
39
+ /** `recordKey(id)`, or `WHOLE_REPO` for the repo key */
40
+ key: Hex;
41
+ /** A throwaway X25519 public key; the reply is sealed to it. */
42
+ readerKey: Hex;
43
+ /** The deposit's `sealed`. */
44
+ sealed: Hex;
45
+ timestamp: number;
46
+ signature: Hex;
47
+ }
48
+ declare const statement: (s: PaidScope) => Hex;
49
+ /**
50
+ * A random repo key. The publisher doesn't keep it: to seal more records later,
51
+ * it asks the key server for it (`requestKey` with `WHOLE_REPO`), like a buyer
52
+ * of the whole repo.
53
+ */
54
+ declare const newRepoKey: () => Uint8Array;
55
+ declare const deriveRecordKey: (kRepo: Uint8Array, stmt: Hex, key: Hex) => Uint8Array;
56
+ /** `nonce(12) || AES-256-GCM(kRecord, plaintext, aad = stmt || key || field)` */
57
+ declare function encryptField(kRecord: Uint8Array, plaintext: Uint8Array, stmt: Hex, key: Hex, field: string): Uint8Array;
58
+ declare function decryptField(kRecord: Uint8Array, ciphertext: Uint8Array, stmt: Hex, key: Hex, field: string): Uint8Array;
59
+ declare function makeDeposit(p: {
60
+ kRepo: Uint8Array;
61
+ keyServerPubkey: Uint8Array;
62
+ keyServer: string;
63
+ scope: PaidScope;
64
+ }): Deposit;
65
+ /** Encrypt one field, upload the ciphertext, and return the handle that replaces the value. */
66
+ declare function sealField(p: {
67
+ plaintext: Uint8Array;
68
+ kRepo: Uint8Array;
69
+ scope: PaidScope;
70
+ /** `recordKey(id)` */
71
+ key: Hex;
72
+ field: string;
73
+ storage: Pick<MetadataStorage, "putFile">;
74
+ }): Promise<FieldHandle>;
75
+ /** What the reader signs (EIP-191, raw): the statement, the key asked for, the reply key and the time. */
76
+ declare const accessMessage: (stmt: Hex, key: Hex, readerKey: Hex, timestamp: number) => Hex;
77
+ declare function buildAccessRequest(p: {
78
+ signer: AccessSigner;
79
+ deposit: Deposit;
80
+ key: Hex;
81
+ readerKey: Hex;
82
+ /** unix seconds; defaults to now */
83
+ timestamp?: number;
84
+ }): Promise<AccessRequest>;
85
+ /** Ask the deposit's key server for `key`'s key: the record key, or the repo key for `WHOLE_REPO`. */
86
+ declare function requestKey(p: {
87
+ deposit: Deposit;
88
+ key: Hex;
89
+ signer: AccessSigner;
90
+ fetch?: typeof globalThis.fetch;
91
+ }): Promise<Uint8Array>;
92
+ /** Get the record's key, fetch the field's ciphertext and decrypt it. */
93
+ declare function openField(p: {
94
+ handle: FieldHandle;
95
+ deposit: Deposit;
96
+ /** `recordKey(id)` */
97
+ key: Hex;
98
+ field: string;
99
+ signer: AccessSigner;
100
+ storage: Pick<MetadataStorage, "getFile">;
101
+ fetch?: typeof globalThis.fetch;
102
+ }): Promise<Uint8Array>;
103
+ //#endregion
104
+ export { AccessRequest, Deposit, FieldHandle, GADGET_FIELD_V1, PaidScope, accessMessage, buildAccessRequest, decryptField, deriveRecordKey, encryptField, makeDeposit, newRepoKey, openField, requestKey, sealField, statement };
@@ -0,0 +1,147 @@
1
+ import { GCM_NONCE_LENGTH, aesGcmDecrypt, aesGcmEncrypt } from "./aes.js";
2
+ import { getRandomValues } from "./rand.js";
3
+ import { seal, unseal } from "./encryption.js";
4
+ import { bytesToHex, concat, encodeAbiParameters, hexToBytes, keccak256, toHex } from "viem";
5
+ import { sha256 } from "@noble/hashes/sha2.js";
6
+ import { x25519 } from "@noble/curves/ed25519";
7
+ import { hkdf } from "@noble/hashes/hkdf.js";
8
+
9
+ //#region src/crypto/paid.ts
10
+ const GADGET_FIELD_V1 = "field-v1";
11
+ const hkdf32 = (ikm, info) => hkdf(sha256, ikm, void 0, typeof info === "string" ? hexToBytes(info) : info, 32);
12
+ const statement = (s) => keccak256(encodeAbiParameters([
13
+ { type: "string" },
14
+ { type: "uint256" },
15
+ { type: "address" },
16
+ { type: "address" },
17
+ { type: "bytes32" },
18
+ { type: "uint64" }
19
+ ], [
20
+ "fangorn:pay:v1",
21
+ BigInt(s.chainId),
22
+ s.registry,
23
+ s.publisher,
24
+ s.repo,
25
+ s.generation
26
+ ]));
27
+ const scopeOf = (d) => ({
28
+ chainId: d.chainId,
29
+ registry: d.registry,
30
+ publisher: d.publisher,
31
+ repo: d.repo,
32
+ generation: BigInt(d.generation)
33
+ });
34
+ /**
35
+ * A random repo key. The publisher doesn't keep it: to seal more records later,
36
+ * it asks the key server for it (`requestKey` with `WHOLE_REPO`), like a buyer
37
+ * of the whole repo.
38
+ */
39
+ const newRepoKey = () => getRandomValues(new Uint8Array(32));
40
+ const deriveRecordKey = (kRepo, stmt, key) => hkdf32(kRepo, concat([
41
+ stmt,
42
+ key,
43
+ toHex("fangorn:record-key")
44
+ ]));
45
+ const fieldAad = (stmt, key, field) => hexToBytes(concat([
46
+ stmt,
47
+ key,
48
+ toHex(field)
49
+ ]));
50
+ /** `nonce(12) || AES-256-GCM(kRecord, plaintext, aad = stmt || key || field)` */
51
+ function encryptField(kRecord, plaintext, stmt, key, field) {
52
+ const nonce = getRandomValues(new Uint8Array(GCM_NONCE_LENGTH));
53
+ const ct = aesGcmEncrypt(kRecord, plaintext, nonce, fieldAad(stmt, key, field));
54
+ const out = new Uint8Array(nonce.length + ct.length);
55
+ out.set(nonce);
56
+ out.set(ct, nonce.length);
57
+ return out;
58
+ }
59
+ function decryptField(kRecord, ciphertext, stmt, key, field) {
60
+ return aesGcmDecrypt(kRecord, ciphertext.slice(GCM_NONCE_LENGTH), ciphertext.slice(0, GCM_NONCE_LENGTH), fieldAad(stmt, key, field));
61
+ }
62
+ function makeDeposit(p) {
63
+ const { scope } = p;
64
+ return {
65
+ "@type": "deposit",
66
+ gadget: GADGET_FIELD_V1,
67
+ chainId: scope.chainId,
68
+ registry: scope.registry,
69
+ publisher: scope.publisher,
70
+ repo: scope.repo,
71
+ generation: scope.generation.toString(),
72
+ keyServer: p.keyServer,
73
+ sealed: bytesToHex(seal(p.kRepo, p.keyServerPubkey, statement(scope)))
74
+ };
75
+ }
76
+ /** Encrypt one field, upload the ciphertext, and return the handle that replaces the value. */
77
+ async function sealField(p) {
78
+ const stmt = statement(p.scope);
79
+ const ct = encryptField(deriveRecordKey(p.kRepo, stmt, p.key), p.plaintext, stmt, p.key, p.field);
80
+ return {
81
+ "@type": "handle",
82
+ gadget: GADGET_FIELD_V1,
83
+ generation: p.scope.generation.toString(),
84
+ cid: await p.storage.putFile(ct, `${p.key}.${p.field}`)
85
+ };
86
+ }
87
+ /** What the reader signs (EIP-191, raw): the statement, the key asked for, the reply key and the time. */
88
+ const accessMessage = (stmt, key, readerKey, timestamp) => keccak256(encodeAbiParameters([
89
+ { type: "string" },
90
+ { type: "bytes32" },
91
+ { type: "bytes32" },
92
+ { type: "bytes32" },
93
+ { type: "uint64" }
94
+ ], [
95
+ "fangorn:access:v1",
96
+ stmt,
97
+ key,
98
+ readerKey,
99
+ BigInt(timestamp)
100
+ ]));
101
+ async function buildAccessRequest(p) {
102
+ const { deposit, key, readerKey } = p;
103
+ const timestamp = p.timestamp ?? Math.floor(Date.now() / 1e3);
104
+ const raw = accessMessage(statement(scopeOf(deposit)), key, readerKey, timestamp);
105
+ return {
106
+ publisher: deposit.publisher,
107
+ repo: deposit.repo,
108
+ generation: deposit.generation,
109
+ key,
110
+ readerKey,
111
+ sealed: deposit.sealed,
112
+ timestamp,
113
+ signature: await p.signer.signMessage({ message: { raw } })
114
+ };
115
+ }
116
+ /** Ask the deposit's key server for `key`'s key: the record key, or the repo key for `WHOLE_REPO`. */
117
+ async function requestKey(p) {
118
+ const secret = x25519.utils.randomSecretKey();
119
+ const req = await buildAccessRequest({
120
+ signer: p.signer,
121
+ deposit: p.deposit,
122
+ key: p.key,
123
+ readerKey: bytesToHex(x25519.getPublicKey(secret))
124
+ });
125
+ const res = await (p.fetch ?? fetch)(`${p.deposit.keyServer}/access`, {
126
+ method: "POST",
127
+ headers: { "Content-Type": "application/json" },
128
+ body: JSON.stringify(req)
129
+ });
130
+ if (!res.ok) throw new Error(`key server refused: ${res.status.toString()} ${await res.text()}`);
131
+ const { sealed } = await res.json();
132
+ return unseal(hexToBytes(sealed), secret, statement(scopeOf(p.deposit)));
133
+ }
134
+ /** Get the record's key, fetch the field's ciphertext and decrypt it. */
135
+ async function openField(p) {
136
+ if (p.handle.generation !== p.deposit.generation) throw new Error("the handle and the deposit are for different generations");
137
+ const [kRecord, ct] = await Promise.all([requestKey({
138
+ deposit: p.deposit,
139
+ key: p.key,
140
+ signer: p.signer,
141
+ fetch: p.fetch
142
+ }), p.storage.getFile(p.handle.cid)]);
143
+ return decryptField(kRecord, ct, statement(scopeOf(p.deposit)), p.key, p.field);
144
+ }
145
+
146
+ //#endregion
147
+ export { GADGET_FIELD_V1, accessMessage, buildAccessRequest, decryptField, deriveRecordKey, encryptField, makeDeposit, newRepoKey, openField, requestKey, sealField, statement };
@@ -5,6 +5,10 @@ import { CID } from "multiformats/cid";
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
7
  /** Decode CAR bytes back into blocks, each checked against its CID (the host is untrusted). */
8
- declare function readCar(bytes: Uint8Array): Promise<Block[]>;
8
+ declare function readCar(bytes: Uint8Array, {
9
+ verify
10
+ }?: {
11
+ verify?: boolean | undefined;
12
+ }): Promise<Block[]>;
9
13
  //#endregion
10
14
  export { packCar, readCar };
package/lib/engine/car.js CHANGED
@@ -24,12 +24,12 @@ async function packCar(root, blocks) {
24
24
  return buf;
25
25
  }
26
26
  /** Decode CAR bytes back into blocks, each checked against its CID (the host is untrusted). */
27
- async function readCar(bytes) {
27
+ async function readCar(bytes, { verify = true } = {}) {
28
28
  const reader = await CarReader.fromBytes(bytes);
29
29
  const blocks = [];
30
30
  for await (const { cid, bytes: blockBytes } of reader.blocks()) {
31
31
  const ours = CID.parse(cid.toString());
32
- assertBlockMatches(ours, blockBytes);
32
+ if (verify) assertBlockMatches(ours, blockBytes);
33
33
  blocks.push({
34
34
  cid: ours,
35
35
  bytes: blockBytes
@@ -1,6 +1,7 @@
1
- import { CommitBlock, Ref } from "./records.js";
2
- import { Registry } from "../registry.js";
1
+ import { CommitUpdate, Registry } from "../contracts/data-registry/index.js";
2
+ import "../contracts/index.js";
3
3
  import { MetadataStorage } from "../providers/storage/types.js";
4
+ import { CommitBlock, Ref } from "./records.js";
4
5
  import { Address, Hash, Hex } from "viem";
5
6
  import { CID } from "multiformats/cid";
6
7
 
@@ -20,7 +21,7 @@ interface StoredRecord {
20
21
  type: RecordType;
21
22
  payload: Record<string, unknown>;
22
23
  }
23
- /** A decoded commit, γ = (e, parent, root) plus its repo name, message and CAR (see CommitBlock). */
24
+ /** A decoded commit, γ = (e, parent, root) plus its repo name and CAR (see CommitBlock). */
24
25
  type CommitObject = CommitBlock;
25
26
  interface RepoContents {
26
27
  records: StoredRecord[];
@@ -31,6 +32,8 @@ interface RepoDiff {
31
32
  puts: StoredRecord[];
32
33
  /** Ids of records that are gone. */
33
34
  deletes: string[];
35
+ /** CIDs of the old versions: records deleted, or replaced by a put. An index keyed by record CID drops these. */
36
+ superseded: string[];
34
37
  }
35
38
  /**
36
39
  * Upper bound on a repo name's length. The name is stored in every commit
@@ -42,11 +45,22 @@ declare const MAX_REPO_NAME_LENGTH = 256;
42
45
  * The root of the graph, committed to IPFS, as hex
43
46
  */
44
47
  declare function rootHexFromCid(commitCid: CID): Hex;
48
+ /** The update that settles `commit`. */
49
+ declare function commitUpdate(commit: CommitBlock): CommitUpdate;
50
+ /** The head the registry computes for `u`. */
51
+ declare function commitHead(u: CommitUpdate): Promise<Hex>;
52
+ /** A commit's update, signed by its publisher for anyone to submit. */
53
+ interface SignedUpdate {
54
+ publisher: Address;
55
+ update: CommitUpdate;
56
+ signature: Hex;
57
+ }
58
+ /** The CID a storage backend returned for a file, with or without an `ipfs://` prefix. */
59
+ declare function fileCid(uri: string): CID;
45
60
  /** Repos must be non-empty strings whose length does not exceed MAX_REPO_NAME_LENGTH */
46
61
  declare function assertValidRepoName(repo: RepoName): void;
47
62
  /** One line of a commit's diff against its parent. */
48
63
  interface CommitDiff {
49
- message: string;
50
64
  parent: string | null;
51
65
  epoch: number;
52
66
  repo: string;
@@ -67,7 +81,6 @@ interface CreateCommitOptions {
67
81
  records: RecordInput[];
68
82
  /** Ids of records to remove. Applied before `records`. */
69
83
  deletes?: string[];
70
- message: string;
71
84
  /**
72
85
  * When true, the staged records REPLACE the repo's previous contents
73
86
  * (a snapshot commit — anything omitted is removed). Default: puts and
@@ -86,6 +99,12 @@ declare class FangornEngine {
86
99
  private cache;
87
100
  /** Commits whose CAR has already been loaded into the cache. */
88
101
  private loadedCars;
102
+ /**
103
+ * Blocks from a loaded CAR, not yet hash-checked. A CAR holds every block its commit introduced
104
+ * (the first commit of a 50k-record repo: all of them), and a diff reads a handful: each block is
105
+ * checked when `getBlock` first hands it out, then moves to `cache`.
106
+ */
107
+ private unverified;
89
108
  constructor(storage: MetadataStorage, registry: Registry);
90
109
  /**
91
110
  * Reconstructs the CID a commit's raw digest hex refers to. The contract only
@@ -112,7 +131,7 @@ declare class FangornEngine {
112
131
  resolveHeadCommit(publisher: Address, repo: RepoName): Promise<CID | null>;
113
132
  /**
114
133
  * Which repo a commit belongs to. Events carry only `keccak256(name)`, so
115
- * this is how an app-wide subscriber recovers the name.
134
+ * this is how a subscriber to every repo recovers the name.
116
135
  */
117
136
  repoOf(rootHex: Hex): Promise<RepoName>;
118
137
  /** The record state a commit holds. */
@@ -136,16 +155,16 @@ declare class FangornEngine {
136
155
  * Settle a local commit as the on-chain head of one repo — the `update` of
137
156
  * WHITEPAPER_1 §3.2. The commit and its CAR are already durable in storage
138
157
  * (createCommit uploads them), so this is just the compare-and-swap.
139
- *
140
- * The commit's parent must BE the current head, not merely an ancestor of
141
- * it: then the parent chain and the registry's log are one history
142
- * (Theorem 3). Today's contract only checks the old root, so the parent is
143
- * checked here.
144
158
  */
145
159
  pushCommit(publisher: Address, repo: RepoName, commitCid: CID): Promise<{
146
160
  txHash: Hash;
147
161
  onChainTip: CID;
148
162
  }>;
163
+ /** `pushCommit`, signed by this registry's wallet for anyone to submit with `relayCommit`. */
164
+ signCommit(publisher: Address, repo: RepoName, commitCid: CID): Promise<SignedUpdate>;
165
+ relayCommit(s: SignedUpdate): Promise<Hash>;
166
+ /** The update for `commitCid`, once it is one the registry will take as the next head. */
167
+ settleable(publisher: Address, repo: RepoName, commitCid: CID): Promise<CommitUpdate>;
149
168
  /** Walk the parent chain from `tip` toward the root, newest first. */
150
169
  walkParents(tip: CID, max?: number): AsyncGenerator<{
151
170
  cid: CID;
@@ -165,8 +184,8 @@ declare class FangornEngine {
165
184
  * Diffing root-to-root (rather than walking commits) is deliberately robust:
166
185
  * it yields the correct net delta even across a force-push / non-fast-forward
167
186
  * reorg — exactly what an index builder needs (what to (re)embed, what to evict).
168
- * ponytail: reads both whole trees; skip subtrees with equal CIDs if diffs
169
- * of large repos get slow.
187
+ * Reads only the nodes on changed paths (`diffMst`): 10 new records in a
188
+ * 50k-record repo cost ~10 × depth nodes, not two 50k-key walks.
170
189
  */
171
190
  repoDiff(oldRootHex: string | null, newRootHex: string): Promise<RepoDiff>;
172
191
  /** Diff a commit against its parent. */
@@ -184,4 +203,4 @@ declare class FangornEngine {
184
203
  readRecord(publisher: Address, repo: RepoName, id: string): Promise<StoredRecord | null>;
185
204
  }
186
205
  //#endregion
187
- export { CommitDiff, CommitObject, CreateCommitOptions, FangornEngine, MAX_REPO_NAME_LENGTH, RecordInput, RecordType, type Ref, RepoContents, RepoDiff, RepoName, StoredRecord, assertValidRepoName, rootHexFromCid };
206
+ export { CommitDiff, CommitObject, CreateCommitOptions, FangornEngine, MAX_REPO_NAME_LENGTH, RecordInput, RecordType, type Ref, RepoContents, RepoDiff, RepoName, SignedUpdate, StoredRecord, assertValidRepoName, commitHead, commitUpdate, fileCid, rootHexFromCid };