@6529-collections/stream-sdk 0.0.0-stage → 0.1.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 (148) hide show
  1. package/CHANGELOG.md +46 -0
  2. package/LICENSE +201 -0
  3. package/NOTICE +4 -0
  4. package/README.md +413 -2
  5. package/dist/actions/accounts.d.ts +58 -0
  6. package/dist/actions/accounts.js +73 -0
  7. package/dist/actions/content.d.ts +22 -0
  8. package/dist/actions/content.js +45 -0
  9. package/dist/actions/curated.d.ts +177 -0
  10. package/dist/actions/curated.js +279 -0
  11. package/dist/actions/editions.d.ts +100 -0
  12. package/dist/actions/editions.js +161 -0
  13. package/dist/actions/independent.d.ts +149 -0
  14. package/dist/actions/independent.js +274 -0
  15. package/dist/actions/money.d.ts +117 -0
  16. package/dist/actions/money.js +148 -0
  17. package/dist/actions/record.d.ts +144 -0
  18. package/dist/actions/record.js +229 -0
  19. package/dist/actions/sale.d.ts +82 -0
  20. package/dist/actions/sale.js +113 -0
  21. package/dist/actions/shared.d.ts +40 -0
  22. package/dist/actions/shared.js +70 -0
  23. package/dist/actions/vault.d.ts +58 -0
  24. package/dist/actions/vault.js +94 -0
  25. package/dist/constants.d.ts +130 -0
  26. package/dist/constants.js +65 -0
  27. package/dist/display.d.ts +31 -0
  28. package/dist/display.js +28 -0
  29. package/dist/encoding.d.ts +110 -0
  30. package/dist/encoding.js +138 -0
  31. package/dist/errors.d.ts +76 -0
  32. package/dist/errors.js +66 -0
  33. package/dist/files/fetch.d.ts +85 -0
  34. package/dist/files/fetch.js +208 -0
  35. package/dist/files/verify.d.ts +36 -0
  36. package/dist/files/verify.js +125 -0
  37. package/dist/generated/abis/AccessManager.d.ts +1125 -0
  38. package/dist/generated/abis/AccessManager.js +1471 -0
  39. package/dist/generated/abis/Accounts.d.ts +1568 -0
  40. package/dist/generated/abis/Accounts.js +2049 -0
  41. package/dist/generated/abis/ClaimRouter.d.ts +343 -0
  42. package/dist/generated/abis/ClaimRouter.js +452 -0
  43. package/dist/generated/abis/ConsolidationAdapter.d.ts +97 -0
  44. package/dist/generated/abis/ConsolidationAdapter.js +133 -0
  45. package/dist/generated/abis/ContentStore.d.ts +812 -0
  46. package/dist/generated/abis/ContentStore.js +1073 -0
  47. package/dist/generated/abis/EconomicsResolver.d.ts +586 -0
  48. package/dist/generated/abis/EconomicsResolver.js +769 -0
  49. package/dist/generated/abis/Eip712CurationVerifier.d.ts +304 -0
  50. package/dist/generated/abis/Eip712CurationVerifier.js +406 -0
  51. package/dist/generated/abis/EnglishAuction.d.ts +1435 -0
  52. package/dist/generated/abis/EnglishAuction.js +1865 -0
  53. package/dist/generated/abis/GovernedVault.d.ts +468 -0
  54. package/dist/generated/abis/GovernedVault.js +617 -0
  55. package/dist/generated/abis/IndependentEditionAuction.d.ts +2373 -0
  56. package/dist/generated/abis/IndependentEditionAuction.js +3076 -0
  57. package/dist/generated/abis/IndependentStream6529.d.ts +1408 -0
  58. package/dist/generated/abis/IndependentStream6529.js +1834 -0
  59. package/dist/generated/abis/IndependentStreamDeployer.d.ts +141 -0
  60. package/dist/generated/abis/IndependentStreamDeployer.js +188 -0
  61. package/dist/generated/abis/IndependentStreamEditions6529.d.ts +963 -0
  62. package/dist/generated/abis/IndependentStreamEditions6529.js +1253 -0
  63. package/dist/generated/abis/IndependentStreamRegistry.d.ts +1351 -0
  64. package/dist/generated/abis/IndependentStreamRegistry.js +1755 -0
  65. package/dist/generated/abis/PackageRegistry.d.ts +1205 -0
  66. package/dist/generated/abis/PackageRegistry.js +1573 -0
  67. package/dist/generated/abis/RevenueEscrow.d.ts +626 -0
  68. package/dist/generated/abis/RevenueEscrow.js +820 -0
  69. package/dist/generated/abis/SaleStarter.d.ts +48 -0
  70. package/dist/generated/abis/SaleStarter.js +67 -0
  71. package/dist/generated/abis/SepoliaOpenGate.d.ts +317 -0
  72. package/dist/generated/abis/SepoliaOpenGate.js +419 -0
  73. package/dist/generated/abis/SplitLedger.d.ts +1097 -0
  74. package/dist/generated/abis/SplitLedger.js +1438 -0
  75. package/dist/generated/abis/StatementLog.d.ts +958 -0
  76. package/dist/generated/abis/StatementLog.js +1248 -0
  77. package/dist/generated/abis/Stream6529.d.ts +1490 -0
  78. package/dist/generated/abis/Stream6529.js +1941 -0
  79. package/dist/generated/abis/StreamDirectory6529.d.ts +355 -0
  80. package/dist/generated/abis/StreamDirectory6529.js +468 -0
  81. package/dist/generated/abis/StreamEditions6529.d.ts +1240 -0
  82. package/dist/generated/abis/StreamEditions6529.js +1614 -0
  83. package/dist/generated/abis/StreamTerms.d.ts +312 -0
  84. package/dist/generated/abis/StreamTerms.js +409 -0
  85. package/dist/generated/abis/StreamWorkFacts6529.d.ts +810 -0
  86. package/dist/generated/abis/StreamWorkFacts6529.js +1049 -0
  87. package/dist/generated/abis/UniformEditionAuction.d.ts +2372 -0
  88. package/dist/generated/abis/UniformEditionAuction.js +3074 -0
  89. package/dist/generated/abis/WorkDelivery.d.ts +605 -0
  90. package/dist/generated/abis/WorkDelivery.js +786 -0
  91. package/dist/generated/abis/WorkRules.d.ts +1154 -0
  92. package/dist/generated/abis/WorkRules.js +1501 -0
  93. package/dist/generated/abis/index.d.ts +28 -0
  94. package/dist/generated/abis/index.js +31 -0
  95. package/dist/generated/instances.d.ts +7 -0
  96. package/dist/generated/instances.js +9 -0
  97. package/dist/generated/sepoliaR10.d.ts +1391 -0
  98. package/dist/generated/sepoliaR10.js +1545 -0
  99. package/dist/hashing/content.d.ts +42 -0
  100. package/dist/hashing/content.js +54 -0
  101. package/dist/hashing/ids.d.ts +67 -0
  102. package/dist/hashing/ids.js +73 -0
  103. package/dist/hashing/items.d.ts +30 -0
  104. package/dist/hashing/items.js +44 -0
  105. package/dist/hashing/packages.d.ts +35 -0
  106. package/dist/hashing/packages.js +76 -0
  107. package/dist/hashing/vault.d.ts +17 -0
  108. package/dist/hashing/vault.js +37 -0
  109. package/dist/hashing/workState.d.ts +31 -0
  110. package/dist/hashing/workState.js +37 -0
  111. package/dist/index.d.ts +44 -0
  112. package/dist/index.js +47 -0
  113. package/dist/instance.d.ts +236 -0
  114. package/dist/instance.js +99 -0
  115. package/dist/items.d.ts +85 -0
  116. package/dist/items.js +144 -0
  117. package/dist/reads/accounts.d.ts +86 -0
  118. package/dist/reads/accounts.js +121 -0
  119. package/dist/reads/chain.d.ts +54 -0
  120. package/dist/reads/chain.js +133 -0
  121. package/dist/reads/creation.d.ts +139 -0
  122. package/dist/reads/creation.js +256 -0
  123. package/dist/reads/editionSale.d.ts +120 -0
  124. package/dist/reads/editionSale.js +182 -0
  125. package/dist/reads/metadata.d.ts +195 -0
  126. package/dist/reads/metadata.js +191 -0
  127. package/dist/reads/money.d.ts +51 -0
  128. package/dist/reads/money.js +68 -0
  129. package/dist/reads/network.d.ts +137 -0
  130. package/dist/reads/network.js +157 -0
  131. package/dist/reads/sale.d.ts +94 -0
  132. package/dist/reads/sale.js +133 -0
  133. package/dist/reads/vault.d.ts +47 -0
  134. package/dist/reads/vault.js +75 -0
  135. package/dist/reads/work.d.ts +293 -0
  136. package/dist/reads/work.js +338 -0
  137. package/dist/reads/workPage.d.ts +197 -0
  138. package/dist/reads/workPage.js +169 -0
  139. package/dist/signing/messages.d.ts +679 -0
  140. package/dist/signing/messages.js +397 -0
  141. package/dist/testing.d.ts +17 -0
  142. package/dist/testing.js +18 -0
  143. package/dist/types.d.ts +167 -0
  144. package/dist/types.js +14 -0
  145. package/docs/publishing.md +54 -0
  146. package/docs/reference.md +335 -0
  147. package/docs/using-from-a-site.md +175 -0
  148. package/package.json +93 -4
@@ -0,0 +1,208 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+ import { hexToBytes } from "viem";
3
+ import { readContract } from "viem/actions";
4
+ import { CHUNK_SIZE, FILE_ROLE, LOCATOR_KIND } from "../constants.js";
5
+ import { FileVerificationError, StreamSdkError } from "../errors.js";
6
+ import { contentStoreAbi } from "../generated/abis/ContentStore.js";
7
+ import { assertInstanceChain } from "../instance.js";
8
+ import { readWorkFiles } from "../reads/work.js";
9
+ import { chainManifestId, concatBytes, verifyFetched, verifyStored } from "./verify.js";
10
+ const DEFAULT_GATEWAYS = {
11
+ arweave: ["https://arweave.net"],
12
+ ipfs: ["https://ipfs.io", "https://dweb.link"],
13
+ };
14
+ /** At most this many RPC calls run at once for one file, so a large file does not flood a public RPC. */
15
+ const RPC_CONCURRENCY = 8;
16
+ /** Runs `task` over `items`, at most `limit` at a time, keeping the order of the results. */
17
+ async function mapLimit(items, limit, task) {
18
+ const results = new Array(items.length);
19
+ let next = 0;
20
+ const worker = async () => {
21
+ for (let index = next++; index < items.length; index = next++) {
22
+ results[index] = await task(items[index], index);
23
+ }
24
+ };
25
+ await Promise.all(Array.from({ length: Math.min(limit, items.length) }, worker));
26
+ return results;
27
+ }
28
+ /** `ContentStore.MAX_CHUNKS`: the most chunks one file has. */
29
+ const MAX_CHUNKS = 4096n;
30
+ /** The contracts accept exactly these two shapes: nothing may follow the content address. */
31
+ const ARWEAVE_URI = /^ar:\/\/([A-Za-z0-9_-]{43})$/;
32
+ const IPFS_URI = /^ipfs:\/\/(baf(?:krei|ybei)[a-z2-7]{52})$/;
33
+ /**
34
+ * A file's manifest, read from the content store and proven against the file ID: the chunk
35
+ * hashes, length, encoding, MIME type and SHA-256 must hash to `fileId`. No answer can pass
36
+ * for a manifest that is not this file ID's, so everything `fetchFile` checks rests on the
37
+ * file ID. Whether that file ID belongs to a given work is another question, answered by
38
+ * whoever supplied it (for a work: the token contract, through your RPC).
39
+ *
40
+ * Contract: [`ContentStore.fileInfo`, `chunkHash`](https://github.com/6529-Collections/6529-stream/blob/c6d4965861907841519cf3878c9db7052424a9a0/src/content/ContentStore.sol).
41
+ */
42
+ export async function readManifest(client, instance, fileId) {
43
+ await assertInstanceChain(client, instance);
44
+ const store = { address: instance.addresses.contentStore, abi: contentStoreAbi };
45
+ const info = await readContract(client, { ...store, functionName: "fileInfo", args: [fileId] });
46
+ // Nothing is verified yet, so the chunk count is only an RPC's word: bound the work it can cause.
47
+ if (info.chunkCount > MAX_CHUNKS || info.length > info.chunkCount * BigInt(CHUNK_SIZE)) {
48
+ throw new StreamSdkError("MISMATCH", `The manifest the RPC answered for ${fileId} is not one the content store can hold.`);
49
+ }
50
+ const chunkHashes = await mapLimit(Array.from({ length: Number(info.chunkCount) }, (_, index) => index), RPC_CONCURRENCY, (index) => readContract(client, { ...store, functionName: "chunkHash", args: [fileId, BigInt(index)] }));
51
+ const manifest = {
52
+ chunkHashes,
53
+ length: info.length,
54
+ encoding: info.encoding,
55
+ mimeType: info.mimeType,
56
+ sha256: info.sha256Hash,
57
+ digestKind: info.digestKind,
58
+ };
59
+ if (chainManifestId(manifest) !== fileId.toLowerCase()) {
60
+ throw new StreamSdkError("MISMATCH", `The manifest the RPC answered for ${fileId} does not hash to that file ID.`);
61
+ }
62
+ return manifest;
63
+ }
64
+ async function fromChain(client, instance, fileId, manifest, maxBytes) {
65
+ const store = { address: instance.addresses.contentStore, abi: contentStoreAbi };
66
+ if (!(await readContract(client, { ...store, functionName: "isComplete", args: [fileId] }))) {
67
+ throw new FileVerificationError("the content store does not hold every chunk");
68
+ }
69
+ if (manifest.length > BigInt(maxBytes))
70
+ throw new FileVerificationError(`the file is larger than ${maxBytes} bytes`);
71
+ const chunks = await mapLimit(manifest.chunkHashes, RPC_CONCURRENCY, (_, index) => readContract(client, { ...store, functionName: "readChunk", args: [fileId, BigInt(index)] }));
72
+ // A chunk is at most CHUNK_SIZE bytes: 2 + 2 hex characters per byte.
73
+ if (chunks.some((chunk) => chunk.length > 2 + 2 * CHUNK_SIZE))
74
+ throw new FileVerificationError("a chunk is longer than the store allows");
75
+ return verifyStored(manifest, concatBytes(chunks.map((chunk) => hexToBytes(chunk))), maxBytes);
76
+ }
77
+ async function download(url, options, maxBytes) {
78
+ const response = await (options.fetch ?? fetch)(url, {
79
+ redirect: "follow",
80
+ signal: AbortSignal.timeout(options.timeoutMs ?? 30_000),
81
+ });
82
+ if (!response.ok)
83
+ throw new FileVerificationError(`HTTP ${response.status}`);
84
+ const declared = Number(response.headers.get("content-length") ?? 0);
85
+ if (declared > maxBytes)
86
+ throw new FileVerificationError(`the answer is larger than ${maxBytes} bytes`);
87
+ const reader = response.body?.getReader();
88
+ if (!reader) {
89
+ const whole = new Uint8Array(await response.arrayBuffer());
90
+ if (whole.length > maxBytes)
91
+ throw new FileVerificationError(`the answer is larger than ${maxBytes} bytes`);
92
+ return whole;
93
+ }
94
+ const parts = [];
95
+ let total = 0;
96
+ for (;;) {
97
+ const { done, value } = await reader.read();
98
+ if (done)
99
+ break;
100
+ total += value.length;
101
+ if (total > maxBytes) {
102
+ await reader.cancel();
103
+ throw new FileVerificationError(`the answer is larger than ${maxBytes} bytes`);
104
+ }
105
+ parts.push(value);
106
+ }
107
+ return concatBytes(parts);
108
+ }
109
+ function gatewayUrls(source, locator, options) {
110
+ const join = (gateway, path) => `${gateway.replace(/\/+$/, "")}/${path}`;
111
+ if (source === "arweave" && locator.kind === LOCATOR_KIND.ARWEAVE) {
112
+ const id = ARWEAVE_URI.exec(locator.uri)?.[1];
113
+ return id ? (options.gateways?.arweave ?? DEFAULT_GATEWAYS.arweave).map((gateway) => join(gateway, id)) : [];
114
+ }
115
+ if (source === "ipfs" && locator.kind === LOCATOR_KIND.IPFS) {
116
+ const cid = IPFS_URI.exec(locator.uri)?.[1];
117
+ return cid ? (options.gateways?.ipfs ?? DEFAULT_GATEWAYS.ipfs).map((gateway) => join(gateway, `ipfs/${cid}`)) : [];
118
+ }
119
+ return [];
120
+ }
121
+ function reason(error) {
122
+ return error instanceof Error ? error.message : String(error);
123
+ }
124
+ /**
125
+ * Fetches a file and returns it only after its bytes were verified against its file ID.
126
+ *
127
+ * 1. The manifest is read from the content store and proven against `fileId` (`readManifest`).
128
+ * 2. From the chain: every chunk must match its keccak256 in the manifest, and the decoded
129
+ * media its SHA-256.
130
+ * 3. From Arweave or IPFS: the bytes a gateway answers must have the manifest's SHA-256 (or
131
+ * be the stored form, checked as in 2). A gateway that answers anything else is skipped.
132
+ *
133
+ * Sources are tried in order until one passes. If none does, a `FileVerificationError` lists
134
+ * what was tried. Bytes that do not match the file ID are never returned. The default
135
+ * gateways are public services: they see the address of whoever fetches.
136
+ *
137
+ * Contract: [`ContentStore.readChunk`, `isComplete`](https://github.com/6529-Collections/6529-stream/blob/c6d4965861907841519cf3878c9db7052424a9a0/src/content/ContentStore.sol);
138
+ * locators from [`WorkDelivery.locators`](https://github.com/6529-Collections/6529-stream/blob/c6d4965861907841519cf3878c9db7052424a9a0/src/stream/WorkDelivery.sol).
139
+ */
140
+ export async function fetchFile(client, instance, fileId, options = {}) {
141
+ const manifest = await readManifest(client, instance, fileId);
142
+ const maxBytes = options.maxBytes ?? 64 * 1024 * 1024;
143
+ const attempts = [];
144
+ const done = (bytes, source, locator) => ({
145
+ fileId,
146
+ bytes,
147
+ mimeType: manifest.mimeType,
148
+ sha256: manifest.sha256,
149
+ source,
150
+ locator,
151
+ });
152
+ for (const source of options.sources ?? ["onchain", "arweave", "ipfs"]) {
153
+ if (source === "onchain") {
154
+ try {
155
+ return done(await fromChain(client, instance, fileId, manifest, maxBytes), "onchain", null);
156
+ }
157
+ catch (error) {
158
+ attempts.push(`chain: ${reason(error)}`);
159
+ }
160
+ continue;
161
+ }
162
+ for (const locator of options.locators ?? []) {
163
+ for (const url of gatewayUrls(source, locator, options)) {
164
+ try {
165
+ return done(await verifyFetched(manifest, await download(url, options, maxBytes), maxBytes), source, locator.uri);
166
+ }
167
+ catch (error) {
168
+ attempts.push(`${url}: ${reason(error)}`);
169
+ }
170
+ }
171
+ }
172
+ }
173
+ throw new FileVerificationError(`No source served file ${fileId} with the bytes its manifest declares.`, attempts);
174
+ }
175
+ /**
176
+ * Fetches one file of a work, verified: the primary file by default, or the file with
177
+ * `fileId`, which must be one of the work's files. The work's registered Arweave and IPFS
178
+ * copies are used when the chain does not hold the file.
179
+ *
180
+ * Contract: as `readWorkFiles` and `fetchFile`.
181
+ */
182
+ export async function fetchWorkFile(client, instance, ref, options = {}) {
183
+ const files = await readWorkFiles(client, instance, ref);
184
+ const file = options.fileId
185
+ ? files.find((candidate) => candidate.fileId.toLowerCase() === options.fileId?.toLowerCase())
186
+ : files.find((candidate) => candidate.role === FILE_ROLE.PRIMARY);
187
+ if (!file) {
188
+ throw new FileVerificationError(options.fileId ? `File ${options.fileId} is not one of this work's files.` : "The work's record is not open, so its files are not listed yet.");
189
+ }
190
+ return fetchFile(client, instance, file.fileId, { ...options, locators: options.locators ?? file.locators });
191
+ }
192
+ /**
193
+ * A work's descriptive record (JSON: name, description, artists and more), fetched and
194
+ * verified like any file, then parsed. The fields are whatever the artist wrote: treat them
195
+ * as untrusted text.
196
+ *
197
+ * Contract: `factsOf(token, tokenId).recordFileId` in [`StreamWorkFacts6529`](https://github.com/6529-Collections/6529-stream/blob/c6d4965861907841519cf3878c9db7052424a9a0/src/core/StreamWorkFacts6529.sol).
198
+ */
199
+ export async function fetchRecord(client, instance, recordFileId, options = {}) {
200
+ // A record is at most 12,288 bytes (`Limits.MAX_RECORD_BYTES`); a caller's larger limit for media does not apply.
201
+ const file = await fetchFile(client, instance, recordFileId, { ...options, maxBytes: Math.min(options.maxBytes ?? 12_288, 12_288) });
202
+ try {
203
+ return JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(file.bytes));
204
+ }
205
+ catch {
206
+ throw new FileVerificationError(`Record ${recordFileId} is not JSON.`);
207
+ }
208
+ }
@@ -0,0 +1,36 @@
1
+ import { type Hex } from "viem";
2
+ import { type Manifest } from "../hashing/content.js";
3
+ /** A manifest as the chain holds it. `digestKind` 0 means `sha256` is a SHA-256 of the decoded media. */
4
+ export interface ChainManifest extends Manifest {
5
+ readonly digestKind: number;
6
+ }
7
+ /**
8
+ * The file ID a manifest must have. For `digestKind` 0 this is `manifestId`; a file
9
+ * registered with another digest kind appends the kind.
10
+ *
11
+ * Contract: [`ContentStore.registerManifest`, `registerManifestList`](https://github.com/6529-Collections/6529-stream/blob/c6d4965861907841519cf3878c9db7052424a9a0/src/content/ContentStore.sol).
12
+ */
13
+ export declare function chainManifestId(manifest: ChainManifest): Hex;
14
+ declare function concatBytes(parts: readonly Uint8Array[]): Uint8Array;
15
+ /** Turns stored bytes into the media: as they are, base64-decoded, unpacked from gzip, or both. */
16
+ export declare function decodeStored(stored: Uint8Array, encoding: number, maxBytes: number): Promise<Uint8Array>;
17
+ /**
18
+ * Checks decoded media against the SHA-256 its manifest declares. Throws on a mismatch.
19
+ * Only `digestKind` 0 (SHA-256) can be checked by this release.
20
+ */
21
+ export declare function assertDecoded(manifest: ChainManifest, decoded: Uint8Array): void;
22
+ /**
23
+ * Checks stored bytes against a manifest, chunk by chunk, and returns the decoded media after
24
+ * checking it against the manifest's SHA-256. Throws `FileVerificationError` on any mismatch.
25
+ *
26
+ * The stored length and every chunk's keccak256 must be the manifest's. The content store does
27
+ * not recompute the SHA-256 a registrant declared, so the last check is the one that proves
28
+ * the declaration honest.
29
+ */
30
+ export declare function verifyStored(manifest: ChainManifest, stored: Uint8Array, maxBytes?: number): Promise<Uint8Array>;
31
+ /**
32
+ * Checks bytes fetched from outside the chain against a manifest: they may be the decoded
33
+ * media (the usual case) or the stored form. Returns the decoded media, or throws.
34
+ */
35
+ export declare function verifyFetched(manifest: ChainManifest, bytes: Uint8Array, maxBytes?: number): Promise<Uint8Array>;
36
+ export { concatBytes };
@@ -0,0 +1,125 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+ import { bytesToHex, encodeAbiParameters, keccak256, sha256 } from "viem";
3
+ import { CHUNK_SIZE, ENCODING } from "../constants.js";
4
+ import { FileVerificationError } from "../errors.js";
5
+ import { splitChunks } from "../hashing/content.js";
6
+ /**
7
+ * The file ID a manifest must have. For `digestKind` 0 this is `manifestId`; a file
8
+ * registered with another digest kind appends the kind.
9
+ *
10
+ * Contract: [`ContentStore.registerManifest`, `registerManifestList`](https://github.com/6529-Collections/6529-stream/blob/c6d4965861907841519cf3878c9db7052424a9a0/src/content/ContentStore.sol).
11
+ */
12
+ export function chainManifestId(manifest) {
13
+ const types = [{ type: "bytes32[]" }, { type: "uint256" }, { type: "uint8" }, { type: "string" }, { type: "bytes32" }];
14
+ const values = [manifest.chunkHashes, manifest.length, manifest.encoding, manifest.mimeType, manifest.sha256];
15
+ if (manifest.digestKind === 0)
16
+ return keccak256(encodeAbiParameters(types, values));
17
+ return keccak256(encodeAbiParameters([...types, { type: "uint8" }], [...values, manifest.digestKind]));
18
+ }
19
+ function concatBytes(parts) {
20
+ const out = new Uint8Array(parts.reduce((sum, part) => sum + part.length, 0));
21
+ let offset = 0;
22
+ for (const part of parts) {
23
+ out.set(part, offset);
24
+ offset += part.length;
25
+ }
26
+ return out;
27
+ }
28
+ function decodeBase64(text) {
29
+ let ascii = "";
30
+ for (const byte of text)
31
+ ascii += String.fromCharCode(byte);
32
+ // RFC 4648 section 4 only: the standard alphabet with padding and no line breaks.
33
+ if (!/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(ascii)) {
34
+ throw new FileVerificationError("The stored bytes are not base64 text.");
35
+ }
36
+ const binary = atob(ascii);
37
+ return Uint8Array.from(binary, (character) => character.charCodeAt(0));
38
+ }
39
+ async function gunzip(bytes, maxBytes) {
40
+ const stream = new Blob([bytes]).stream().pipeThrough(new DecompressionStream("gzip"));
41
+ const reader = stream.getReader();
42
+ const parts = [];
43
+ let total = 0;
44
+ for (;;) {
45
+ const { done, value } = await reader.read();
46
+ if (done)
47
+ break;
48
+ total += value.length;
49
+ if (total > maxBytes) {
50
+ await reader.cancel();
51
+ throw new FileVerificationError(`The file is larger than ${maxBytes} bytes once unpacked.`);
52
+ }
53
+ parts.push(value);
54
+ }
55
+ return concatBytes(parts);
56
+ }
57
+ /** Turns stored bytes into the media: as they are, base64-decoded, unpacked from gzip, or both. */
58
+ export async function decodeStored(stored, encoding, maxBytes) {
59
+ switch (encoding) {
60
+ case ENCODING.IDENTITY:
61
+ return stored;
62
+ case ENCODING.GZIP:
63
+ return gunzip(stored, maxBytes);
64
+ case ENCODING.BASE64:
65
+ return decodeBase64(stored);
66
+ case ENCODING.GZIP_BASE64:
67
+ return gunzip(decodeBase64(stored), maxBytes);
68
+ default:
69
+ throw new FileVerificationError(`Encoding ${encoding} is not one this release can decode.`);
70
+ }
71
+ }
72
+ /**
73
+ * Checks decoded media against the SHA-256 its manifest declares. Throws on a mismatch.
74
+ * Only `digestKind` 0 (SHA-256) can be checked by this release.
75
+ */
76
+ export function assertDecoded(manifest, decoded) {
77
+ if (manifest.digestKind !== 0) {
78
+ throw new FileVerificationError(`Digest kind ${manifest.digestKind} is not one this release can check.`);
79
+ }
80
+ const actual = sha256(decoded);
81
+ if (actual !== manifest.sha256.toLowerCase()) {
82
+ throw new FileVerificationError(`SHA-256 is ${actual}, but the manifest declares ${manifest.sha256}.`);
83
+ }
84
+ }
85
+ /**
86
+ * Checks stored bytes against a manifest, chunk by chunk, and returns the decoded media after
87
+ * checking it against the manifest's SHA-256. Throws `FileVerificationError` on any mismatch.
88
+ *
89
+ * The stored length and every chunk's keccak256 must be the manifest's. The content store does
90
+ * not recompute the SHA-256 a registrant declared, so the last check is the one that proves
91
+ * the declaration honest.
92
+ */
93
+ export async function verifyStored(manifest, stored, maxBytes = 64 * 1024 * 1024) {
94
+ if (BigInt(stored.length) !== manifest.length) {
95
+ throw new FileVerificationError(`The stored length is ${stored.length} bytes, but the manifest declares ${manifest.length}.`);
96
+ }
97
+ const chunks = splitChunks(stored);
98
+ if (chunks.length !== manifest.chunkHashes.length) {
99
+ throw new FileVerificationError(`The bytes make ${chunks.length} chunks of ${CHUNK_SIZE}, but the manifest lists ${manifest.chunkHashes.length}.`);
100
+ }
101
+ chunks.forEach((chunk, index) => {
102
+ const expected = manifest.chunkHashes[index];
103
+ if (keccak256(chunk) !== expected?.toLowerCase()) {
104
+ throw new FileVerificationError(`Chunk ${index} does not match its hash in the manifest.`);
105
+ }
106
+ });
107
+ const decoded = await decodeStored(stored, manifest.encoding, maxBytes);
108
+ assertDecoded(manifest, decoded);
109
+ return decoded;
110
+ }
111
+ /**
112
+ * Checks bytes fetched from outside the chain against a manifest: they may be the decoded
113
+ * media (the usual case) or the stored form. Returns the decoded media, or throws.
114
+ */
115
+ export async function verifyFetched(manifest, bytes, maxBytes = 64 * 1024 * 1024) {
116
+ if (manifest.digestKind === 0 && sha256(bytes) === manifest.sha256.toLowerCase())
117
+ return bytes;
118
+ try {
119
+ return await verifyStored(manifest, bytes, maxBytes);
120
+ }
121
+ catch {
122
+ throw new FileVerificationError(`The bytes (SHA-256 ${bytesToHex(sha256(bytes, "bytes"))}) are not the file the manifest declares.`);
123
+ }
124
+ }
125
+ export { concatBytes };