@coffre/core 0.15.0 → 0.16.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 (70) hide show
  1. package/README.md +1 -1
  2. package/dist/{access-CgQTlUMz.js → access-CF8UG59J.js} +70 -95
  3. package/dist/{access-DqLJjnLM.d.ts → access-ERdGGHG7.d.ts} +45 -64
  4. package/dist/access.d.ts +2 -2
  5. package/dist/access.js +2 -2
  6. package/dist/envelope.d.ts +28 -9
  7. package/dist/envelope.js +25 -8
  8. package/dist/identity.d.ts +3 -1018
  9. package/dist/identity.js +885 -623
  10. package/dist/index-DuG9p3GH.d.ts +1233 -0
  11. package/dist/kek.d.ts +10 -16
  12. package/dist/kek.js +26 -41
  13. package/dist/log.d.ts +114 -0
  14. package/dist/log.js +291 -0
  15. package/dist/mcp.d.ts +27 -4
  16. package/dist/mcp.js +31 -10
  17. package/dist/recipe-BgJpmJum.d.ts +128 -0
  18. package/dist/recipe.d.ts +2 -127
  19. package/dist/{registry-D7X-x202.d.ts → registry-B7_LUDsJ.d.ts} +30 -5
  20. package/dist/schemas.d.ts +14 -12
  21. package/dist/schemas.js +16 -14
  22. package/dist/{types-Cp3lB_-W.js → types-DwTO_b4H.js} +17 -5
  23. package/dist/vault.d.ts +1771 -1419
  24. package/dist/vault.js +96 -302
  25. package/dist/{workloads-D049JH0M.d.ts → workloads-CW2dK4AW.d.ts} +1 -9
  26. package/dist/workloads.d.ts +2 -2
  27. package/dist/workloads.js +1 -9
  28. package/package.json +7 -7
  29. package/src/access.ts +63 -95
  30. package/src/changes/access.ts +140 -0
  31. package/src/changes/freezes.ts +40 -0
  32. package/src/changes/mcp.ts +150 -0
  33. package/src/changes/places.ts +219 -0
  34. package/src/changes/secrets.ts +235 -0
  35. package/src/changes/signin.ts +197 -0
  36. package/src/changes/workloads.ts +166 -0
  37. package/src/context.ts +18 -2
  38. package/src/envelope.ts +35 -12
  39. package/src/identity/auth.ts +11 -3
  40. package/src/identity/aws.ts +62 -0
  41. package/src/identity/github-app.ts +45 -24
  42. package/src/identity/index.ts +3 -2
  43. package/src/identity/{profile-rules.ts → profiles.ts} +1 -9
  44. package/src/identity/proofs.ts +306 -0
  45. package/src/identity/signin/config.ts +1 -1
  46. package/src/identity/tokens.ts +10 -3
  47. package/src/identity/verifier.ts +73 -14
  48. package/src/identity/workload-token.ts +4 -0
  49. package/src/identity/workloads.ts +0 -11
  50. package/src/kek/aws-kms.ts +18 -13
  51. package/src/kek/check.ts +16 -46
  52. package/src/kek/index.ts +2 -2
  53. package/src/kek/types.ts +15 -3
  54. package/src/log/index.ts +7 -0
  55. package/src/{audit → log}/tiles.ts +18 -49
  56. package/src/{audit → log}/tree.ts +2 -2
  57. package/src/mcp.ts +36 -9
  58. package/src/schemas.ts +15 -12
  59. package/src/vault.ts +251 -1150
  60. package/dist/merkle.d.ts +0 -456
  61. package/dist/merkle.js +0 -964
  62. package/src/answers.ts +0 -209
  63. package/src/audit/leaf.ts +0 -81
  64. package/src/audit/merkle.ts +0 -13
  65. package/src/audit/note.ts +0 -187
  66. package/src/audit/pair.ts +0 -86
  67. package/src/audit/verify.ts +0 -393
  68. package/src/audit/witness.ts +0 -50
  69. package/src/checkpoint.ts +0 -22
  70. package/src/identity/run-proof.ts +0 -159
package/dist/merkle.js DELETED
@@ -1,964 +0,0 @@
1
- import { createHash, hkdfSync } from "node:crypto";
2
- //#region src/audit/tree.ts
3
- const HASH_SIZE = 32;
4
- const LEAF = Buffer.from([0]);
5
- const NODE = Buffer.from([1]);
6
- function leafHash(data) {
7
- return createHash("sha256").update(LEAF).update(data).digest();
8
- }
9
- function nodeHash(left, right) {
10
- return createHash("sha256").update(NODE).update(left).update(right).digest();
11
- }
12
- /** The head of the empty tree: SHA-256 of nothing. */
13
- const EMPTY_ROOT = createHash("sha256").digest();
14
- /** The largest power of two strictly below n (n ≥ 2). */
15
- function split(n) {
16
- let k = 1;
17
- while (k * 2 < n) k *= 2;
18
- return k;
19
- }
20
- const log2 = (n) => Math.round(Math.log2(n));
21
- const isPowerOfTwo = (n) => n > 0 && 2 ** log2(n) === n;
22
- /** MTH(D[start:start+n]): the hash of any range, from the perfect subtrees it decomposes into. */
23
- function rangeHash(nodes, start, n) {
24
- if (n === 0) return EMPTY_ROOT;
25
- if (isPowerOfTwo(n) && start % n === 0) return nodes(log2(n), start / n);
26
- const k = split(n);
27
- return nodeHash(rangeHash(nodes, start, k), rangeHash(nodes, start + k, n - k));
28
- }
29
- /** The tree head: MTH of the first `size` leaves. */
30
- function treeHash(nodes, size) {
31
- return rangeHash(nodes, 0, size);
32
- }
33
- /** RFC 9162 2.1.3.1, PATH(m, D[n]): the inclusion proof of leaf m in the tree of n leaves, leaf to root. */
34
- function inclusionProof(nodes, m, n) {
35
- if (!Number.isSafeInteger(m) || m < 0 || m >= n) throw new Error(`leaf ${m} is not in a tree of ${n}`);
36
- const path = [];
37
- const walk = (m, start, n) => {
38
- if (n === 1) return;
39
- const k = split(n);
40
- if (m < k) {
41
- walk(m, start, k);
42
- path.push(rangeHash(nodes, start + k, n - k));
43
- } else {
44
- walk(m - k, start + k, n - k);
45
- path.push(rangeHash(nodes, start, k));
46
- }
47
- };
48
- walk(m, 0, n);
49
- return path;
50
- }
51
- /** RFC 9162 2.1.4.1, PROOF(m, D[n]): that the tree of m leaves is a prefix of the tree of n. */
52
- function consistencyProof(nodes, m, n) {
53
- if (!Number.isSafeInteger(m) || m < 0 || m > n) throw new Error(`no consistency from ${m} to ${n}`);
54
- if (m === 0 || m === n) return [];
55
- const path = [];
56
- const sub = (m, start, n, whole) => {
57
- if (m === n) {
58
- if (!whole) path.push(rangeHash(nodes, start, n));
59
- return;
60
- }
61
- const k = split(n);
62
- if (m <= k) {
63
- sub(m, start, k, whole);
64
- path.push(rangeHash(nodes, start + k, n - k));
65
- } else {
66
- sub(m - k, start + k, n - k, false);
67
- path.push(rangeHash(nodes, start, k));
68
- }
69
- };
70
- sub(m, 0, n, true);
71
- return path;
72
- }
73
- /** RFC 9162 2.1.3.2: whether `proof` shows `leaf` at index m of the tree of n leaves whose head is `root`. */
74
- function verifyInclusion(leaf, m, n, proof, root) {
75
- if (!Number.isSafeInteger(m) || !Number.isSafeInteger(n) || m < 0 || m >= n) return false;
76
- let fn = m;
77
- let sn = n - 1;
78
- let r = leaf;
79
- for (const p of proof) {
80
- if (sn === 0) return false;
81
- if (fn % 2 === 1 || fn === sn) {
82
- r = nodeHash(p, r);
83
- if (fn % 2 === 0) while (fn % 2 === 0 && fn !== 0) {
84
- fn = Math.floor(fn / 2);
85
- sn = Math.floor(sn / 2);
86
- }
87
- } else r = nodeHash(r, p);
88
- fn = Math.floor(fn / 2);
89
- sn = Math.floor(sn / 2);
90
- }
91
- return sn === 0 && r.equals(root);
92
- }
93
- /** RFC 9162 2.1.4.2: whether `proof` shows the tree of m leaves (head `first`) a prefix of the tree of n (head `second`). */
94
- function verifyConsistency(m, n, first, second, proof) {
95
- if (!Number.isSafeInteger(m) || !Number.isSafeInteger(n) || m < 0 || m > n) return false;
96
- if (m === 0) return proof.length === 0 && first.equals(EMPTY_ROOT) && (n > 0 || second.equals(EMPTY_ROOT));
97
- if (m === n) return proof.length === 0 && first.equals(second);
98
- const path = isPowerOfTwo(m) ? [first, ...proof] : [...proof];
99
- if (path.length === 0) return false;
100
- let fn = m - 1;
101
- let sn = n - 1;
102
- while (fn % 2 === 1) {
103
- fn = Math.floor(fn / 2);
104
- sn = Math.floor(sn / 2);
105
- }
106
- let fr = path[0];
107
- let sr = path[0];
108
- for (const c of path.slice(1)) {
109
- if (sn === 0) return false;
110
- if (fn % 2 === 1 || fn === sn) {
111
- fr = nodeHash(c, fr);
112
- sr = nodeHash(c, sr);
113
- if (fn % 2 === 0) while (fn % 2 === 0 && fn !== 0) {
114
- fn = Math.floor(fn / 2);
115
- sn = Math.floor(sn / 2);
116
- }
117
- } else sr = nodeHash(sr, c);
118
- fn = Math.floor(fn / 2);
119
- sn = Math.floor(sn / 2);
120
- }
121
- return sn === 0 && fr.equals(first) && sr.equals(second);
122
- }
123
- //#endregion
124
- //#region src/audit/note.ts
125
- /** The largest number a log entry may carry: Postgres's bigint. */
126
- const MAX_NUMBER = 2n ** 63n - 1n;
127
- function checkpointBody(c) {
128
- return `${c.origin}\n${c.size}\n${c.root.toString("base64")}\nupto ${c.upto}\nat ${c.at}\nfloor ${c.floor}\nprev ${c.prev}\n`;
129
- }
130
- /** The checkpoint a note's text holds; throws on anything else, byte for byte, since the database is a writer's to shape. */
131
- function parseCheckpoint(text) {
132
- const lines = text.split("\n");
133
- const [origin, size, root, upto, at, floor, prev, end] = lines;
134
- const hash = Buffer.from(root ?? "", "base64");
135
- const ok = lines.length === 8 && end === "" && origin !== void 0 && /^[^\s+]+$/.test(origin) && /^(0|[1-9]\d{0,15})$/.test(size ?? "") && hash.length === 32 && hash.toString("base64") === root && /^upto (0|[1-9]\d{0,18})$/.test(upto ?? "") && /^at (0|[1-9]\d{0,15})$/.test(at ?? "") && /^floor (0|[1-9]\d{0,15})$/.test(floor ?? "") && /^prev (0|[1-9]\d{0,15})$/.test(prev ?? "");
136
- const [n, t, f, b] = [
137
- Number(size),
138
- Number(at?.slice(3)),
139
- Number(floor?.slice(6)),
140
- Number(prev?.slice(5))
141
- ];
142
- if (!ok || BigInt(upto.slice(5)) > MAX_NUMBER || ![
143
- n,
144
- t,
145
- f,
146
- b
147
- ].every(Number.isSafeInteger)) throw new Error("not a checkpoint");
148
- return {
149
- origin,
150
- size: n,
151
- root: hash,
152
- upto: BigInt(upto.slice(5)),
153
- at: t,
154
- floor: f,
155
- prev: b
156
- };
157
- }
158
- const ED25519 = 1;
159
- const PKCS8_ED25519 = Buffer.from("302e020100300506032b657004220420", "hex");
160
- /** A note key's ID: the first 4 bytes of SHA-256(name || "\n" || 0x01 || public key). */
161
- function keyId(name, publicKey) {
162
- return createHash("sha256").update(name).update("\n").update(Buffer.from([ED25519])).update(publicKey).digest().subarray(0, 4);
163
- }
164
- /** A signer named `name`, from a 32-byte Ed25519 seed. */
165
- async function noteSigner(name, seed) {
166
- if (seed.length !== 32) throw new Error("an Ed25519 seed is 32 bytes");
167
- if (!/^[^\s+]+$/.test(name)) throw new Error("a note key name has no spaces and no +");
168
- const key = await crypto.subtle.importKey("pkcs8", new Uint8Array(Buffer.concat([PKCS8_ED25519, seed])), { name: "Ed25519" }, true, ["sign"]);
169
- const { x } = await crypto.subtle.exportKey("jwk", key);
170
- const publicKey = Buffer.from(x, "base64url");
171
- const id = keyId(name, publicKey);
172
- return {
173
- name,
174
- id,
175
- publicKey,
176
- verifierKey: `${name}+${id.toString("hex")}+${Buffer.concat([Buffer.from([ED25519]), publicKey]).toString("base64")}`,
177
- sign: async (message) => Buffer.from(await crypto.subtle.sign("Ed25519", key, new Uint8Array(message)))
178
- };
179
- }
180
- async function noteVerifier(verifierKey) {
181
- const m = /^([^\s+]+)\+([0-9a-f]{8})\+(.+)$/.exec(verifierKey);
182
- if (m === null) throw new Error("not a note verifier key");
183
- const [, name, hash, data] = m;
184
- const raw = Buffer.from(data, "base64");
185
- if (raw[0] !== ED25519 || raw.length !== 33) throw new Error("not an Ed25519 note key");
186
- const publicKey = raw.subarray(1);
187
- const id = keyId(name, publicKey);
188
- if (id.toString("hex") !== hash) throw new Error("the key ID does not match the key");
189
- const key = await crypto.subtle.importKey("raw", new Uint8Array(publicKey), { name: "Ed25519" }, false, ["verify"]);
190
- return {
191
- name,
192
- id,
193
- verify: (message, signature) => crypto.subtle.verify("Ed25519", key, new Uint8Array(signature), new Uint8Array(message))
194
- };
195
- }
196
- async function signatureLine(text, signer) {
197
- return `— ${signer.name} ${Buffer.concat([signer.id, await signer.sign(Buffer.from(text))]).toString("base64")}\n`;
198
- }
199
- /** A signed note: the text, a blank line, then one signature line per signer. */
200
- async function signNote(text, signers) {
201
- if (!text.endsWith("\n") || text.includes("\n\n")) throw new Error("a note text ends with a newline and has no blank line");
202
- return `${text}\n${(await Promise.all(signers.map((s) => signatureLine(text, s)))).join("")}`;
203
- }
204
- /** Adds a signature (a witness's cosignature) to a signed note. */
205
- async function cosignNote(note, signer) {
206
- return `${note}${await signatureLine(splitNote(note).text, signer)}`;
207
- }
208
- /** At most this many signature lines, as Go's note.Open: a crafted row cannot make a reader verify without end. */
209
- const MAX_SIGNATURES = 100;
210
- /** A key name, as Go's: not empty, no white space, no '+'. */
211
- const validName = (name) => name.length > 0 && !/[\s\u0085+]/u.test(name) && !/[\uD800-\uDFFF]/u.test(name);
212
- /**
213
- * A signed note's text and signature lines, read as strictly as Go's
214
- * note.Open, so that a note stored in the database opens here only if every
215
- * Go reader and C2SP witness would open it too. Throws on anything else.
216
- */
217
- function splitNote(note) {
218
- if (/[\u0000-\u0009\u000b-\u001f]/.test(note) || /[\uD800-\uDFFF]/u.test(note)) throw new Error("not a signed note");
219
- const at = note.lastIndexOf("\n\n");
220
- if (at < 0 || note.length === at + 2 || !note.endsWith("\n")) throw new Error("not a signed note");
221
- const text = note.slice(0, at + 1);
222
- const lines = note.slice(at + 2, -1).split("\n");
223
- if (lines.length > MAX_SIGNATURES) throw new Error("too many signature lines");
224
- return {
225
- text,
226
- signatures: lines.map((line) => {
227
- if (!line.startsWith("— ")) throw new Error("malformed signature line");
228
- const rest = line.slice(2);
229
- const space = rest.indexOf(" ");
230
- const [name, encoded] = space < 0 ? [rest, ""] : [rest.slice(0, space), rest.slice(space + 1)];
231
- const raw = Buffer.from(encoded, "base64");
232
- if (!validName(name) || encoded === "" || raw.toString("base64") !== encoded || raw.length < 5) throw new Error("malformed signature line");
233
- return {
234
- name,
235
- id: raw.subarray(0, 4),
236
- signature: raw.subarray(4)
237
- };
238
- })
239
- };
240
- }
241
- /**
242
- * The note's text if `verifier` signed it, else null; null for anything that
243
- * is not a signed note too. As Go's note.Open given this one key, the first
244
- * signature line that names this key decides: if it does not verify, the
245
- * whole note is invalid, whatever other lines say; later lines by the key are
246
- * ignored. (Given several keys, Go also refuses a bad line
247
- * by any of them; each tree's note is opened with its own key alone.)
248
- */
249
- async function openNote(note, verifier) {
250
- let parts;
251
- try {
252
- parts = splitNote(note);
253
- } catch {
254
- return null;
255
- }
256
- let verified = false;
257
- for (const s of parts.signatures) {
258
- if (s.name !== verifier.name || !s.id.equals(verifier.id) || verified) continue;
259
- if (s.signature.length !== 64 || !await verifier.verify(Buffer.from(parts.text), s.signature)) return null;
260
- verified = true;
261
- }
262
- return verified ? parts.text : null;
263
- }
264
- /** A checkpoint if `verifier` signed it and it names that key's log as its origin, else null. */
265
- async function openCheckpoint(note, verifier) {
266
- const text = await openNote(note, verifier);
267
- if (text === null) return null;
268
- try {
269
- const c = parseCheckpoint(text);
270
- return c.origin === verifier.name ? c : null;
271
- } catch {
272
- return null;
273
- }
274
- }
275
- //#endregion
276
- //#region src/audit/leaf.ts
277
- /**
278
- * A leaf is a whole entry: its tree, its number, then every column of its row
279
- * in the table's order, its MAC included. The number is sealed with the
280
- * entry, so a sealed entry cannot be renumbered, and the tree is too, so an
281
- * entry moved from one tree to the other is no longer its leaf. Anyone who
282
- * holds the public keys can check rows against the trees; the MAC key matters
283
- * only until an entry is sealed.
284
- *
285
- * "coffre.audit.leaf.v1" 0x0a tree 0x0a number(8 bytes, big-endian) count(4)
286
- * then per column: tag(1) length(4) bytes
287
- * tag 0 null (length 0), 1 bytes, 2 text (UTF-8), 3 integer (decimal text)
288
- *
289
- * Every column is tagged and length-prefixed, so the encoding is injective:
290
- * no two rows share their bytes, whatever their values. A change to it is a
291
- * new format, never an edit of this one (test/vectors/audit-tree.json pins it).
292
- */
293
- const LEAF_FORMAT = "coffre.audit.leaf.v1";
294
- function leafData(tree, number, columns) {
295
- if (number < 0n || number > MAX_NUMBER) throw new Error(`entry number ${number} is out of range`);
296
- return encode(`${LEAF_FORMAT}\n${tree}\n`, number, columns);
297
- }
298
- /**
299
- * What an entry's MAC covers: its tree and every column but its number,
300
- * which the database takes, and the MAC itself, the same tagged encoding as
301
- * a leaf's. The tree is in it (Seal.tla's KindInMac): a change moved into
302
- * the uses table before its tick would otherwise be sealed into the uses
303
- * tree, and pruned with the uses.
304
- *
305
- * "coffre.log.mac.v1" 0x0a tree 0x0a column count(4), then the columns as a leaf's
306
- */
307
- const MAC_FORMAT = "coffre.log.mac.v1";
308
- function macData(tree, columns) {
309
- return encode(`${MAC_FORMAT}\n${tree}\n`, null, columns);
310
- }
311
- /**
312
- * The prefix, the number if any (8 bytes), the column count, then each
313
- * column tagged and length-prefixed: sized first, then written into one
314
- * buffer, which a walk does for every entry it checks.
315
- */
316
- function encode(prefix, number, columns) {
317
- const tags = [];
318
- const values = [];
319
- let size = Buffer.byteLength(prefix, "utf8") + (number === null ? 0 : 8) + 4;
320
- for (const [i, value] of columns.entries()) {
321
- let tag;
322
- let bytes;
323
- if (value === null) [tag, bytes] = [0, null];
324
- else if (value instanceof Uint8Array) [tag, bytes] = [1, value];
325
- else if (typeof value === "string") {
326
- if (/[\uD800-\uDFFF]/u.test(value)) throw new Error(`column ${i} is not well-formed Unicode`);
327
- [tag, bytes] = [2, value];
328
- } else if (typeof value === "bigint" || Number.isSafeInteger(value)) [tag, bytes] = [3, value.toString(10)];
329
- else throw new Error(`column ${i} is not a whole number`);
330
- tags.push(tag);
331
- values.push(bytes);
332
- size += 5 + (bytes === null ? 0 : typeof bytes === "string" ? Buffer.byteLength(bytes, "utf8") : bytes.length);
333
- }
334
- const out = Buffer.allocUnsafe(size);
335
- let at = out.write(prefix, 0, "utf8");
336
- if (number !== null) at = out.writeBigUInt64BE(number, at);
337
- at = out.writeUInt32BE(columns.length, at);
338
- for (const [i, bytes] of values.entries()) {
339
- at = out.writeUInt8(tags[i], at);
340
- const length = bytes === null ? 0 : typeof bytes === "string" ? out.write(bytes, at + 4, "utf8") : (out.set(bytes, at + 4), bytes.length);
341
- at = out.writeUInt32BE(length, at) + length;
342
- }
343
- return out;
344
- }
345
- /** The leaf hash of an entry. */
346
- const entryLeaf = (tree, number, columns) => leafHash(leafData(tree, number, columns));
347
- //#endregion
348
- //#region src/audit/pair.ts
349
- /**
350
- * 0.15's log is two growing trees, one per retention class (W212, by numbers):
351
- * `changes`, kept for good, and `uses`, dropped by day. Each is a standard log
352
- * with its own origin and key, so any C2SP witness or Go's tlog reads either
353
- * one alone. They stay one log by moving as one pair:
354
- *
355
- * - one tick signs both, with the same `upto`, `at` and `floor`;
356
- * - the signer remembers both in one record, before the database has either;
357
- * - one statement writes both;
358
- * - opening, each tick and witnesses check both, as one value.
359
- *
360
- * So no state anywhere holds one head without the other, and a fork of either
361
- * tree is a fork of the pair.
362
- */
363
- const TREES = ["changes", "uses"];
364
- /** A tree's origin: the log's own, then the tree's name. */
365
- const treeOrigin = (origin, tree) => `${origin}/${tree}`;
366
- /** The two trees' keys, derived from one 32-byte signing seed, each under its own origin. */
367
- async function pairSigners(origin, seed) {
368
- if (seed.length < 32) throw new Error("a signing seed is at least 32 bytes");
369
- const derive = (tree) => new Uint8Array(hkdfSync("sha256", seed, /* @__PURE__ */ new Uint8Array(0), `coffre.audit.tree.v1.${tree}`, 32));
370
- const [changes, uses] = await Promise.all(TREES.map((tree) => noteSigner(treeOrigin(origin, tree), derive(tree))));
371
- return {
372
- changes,
373
- uses
374
- };
375
- }
376
- async function pairVerifiers(keys) {
377
- const [changes, uses] = await Promise.all(TREES.map((tree) => noteVerifier(keys[tree])));
378
- return {
379
- changes,
380
- uses
381
- };
382
- }
383
- /**
384
- * One tick's signatures: both heads, at one `upto`, `at`, `floor` (the floor of `at` its barrier set; 0 at genesis) and
385
- * `prev` (the floor of the pair signed before it; 0 at genesis).
386
- */
387
- async function signPair(signers, upto, at, heads, floor = 0, prev = 0) {
388
- const checkpoint = (tree) => ({
389
- origin: signers[tree].name,
390
- size: heads[tree].size,
391
- root: heads[tree].root,
392
- upto,
393
- at,
394
- floor,
395
- prev
396
- });
397
- const pair = {
398
- upto,
399
- at,
400
- floor,
401
- prev,
402
- changes: checkpoint("changes"),
403
- uses: checkpoint("uses")
404
- };
405
- const [changes, uses] = await Promise.all(TREES.map((tree) => signNote(checkpointBody(pair[tree]), [signers[tree]])));
406
- return {
407
- pair,
408
- notes: {
409
- changes,
410
- uses
411
- }
412
- };
413
- }
414
- /** The pair two notes make, if each is signed by its tree's key and both name the same `upto`, `at`, `floor` and `prev`; else null. */
415
- async function openPair(notes, verifiers) {
416
- const [changes, uses] = await Promise.all(TREES.map((tree) => openCheckpoint(notes[tree], verifiers[tree])));
417
- if (!changes || !uses || changes.upto !== uses.upto || changes.at !== uses.at || changes.floor !== uses.floor || changes.prev !== uses.prev) return null;
418
- return {
419
- upto: changes.upto,
420
- at: changes.at,
421
- floor: changes.floor,
422
- prev: changes.prev,
423
- changes,
424
- uses
425
- };
426
- }
427
- /** Whether two pairs are the same heads: same place, same sizes and roots in both trees. Not `at`: callers that need one signing compare it too. */
428
- const samePair = (a, b) => a.upto === b.upto && TREES.every((tree) => a[tree].size === b[tree].size && a[tree].root.equals(b[tree].root));
429
- /** The one record the signer remembers, holding both notes. */
430
- function encodePair(notes) {
431
- return JSON.stringify({
432
- changes: notes.changes,
433
- uses: notes.uses
434
- });
435
- }
436
- function decodePair(record) {
437
- try {
438
- const value = JSON.parse(record);
439
- if (typeof value !== "object" || value === null) return null;
440
- const { changes, uses, ...rest } = value;
441
- if (typeof changes !== "string" || typeof uses !== "string" || Object.keys(rest).length > 0) return null;
442
- return {
443
- changes,
444
- uses
445
- };
446
- } catch {
447
- return null;
448
- }
449
- }
450
- //#endregion
451
- //#region src/audit/tiles.ts
452
- /**
453
- * The tree's storage: tiles, as Go's sumdb and C2SP tlog-tiles lay them out,
454
- * of height 8. The tile at (level t, index i) holds up to 256 hashes: the
455
- * nodes at tree level 8t numbered i·256 onwards, concatenated. A level-0 tile
456
- * holds leaf hashes; a level-1 tile, the roots of 256-leaf subtrees; and so
457
- * on. Any perfect subtree's hash is in one tile or is at most 128 hashes away
458
- * from one, so a proof reads one tile per 8 levels: 4 tiles at 2^32 leaves.
459
- *
460
- * A tile's hashes never change once written, only grow (the partial tile at
461
- * the tree's right edge), so a tile is read for any older tree size by taking
462
- * its prefix.
463
- */
464
- const HEIGHT = 8;
465
- const WIDTH = 256;
466
- const tileKey = (level, index) => `${level}/${index}`;
467
- /** Which tile, and where in it, holds what node (level, index) is computed from. */
468
- function tileOf(level, index) {
469
- const t = Math.floor(level / 8);
470
- const count = 2 ** (level - t * 8);
471
- const first = index * count;
472
- return {
473
- tile: {
474
- level: t,
475
- index: Math.floor(first / 256)
476
- },
477
- offset: first % 256,
478
- count
479
- };
480
- }
481
- /**
482
- * The leaves a tile's hashes stand for: [first, end). Tiles are partitioned by
483
- * it (a level-0 tile by the 256 leaves it holds), so retention drops whole
484
- * ranges of them instead of deleting rows.
485
- */
486
- function tileLeaves(t) {
487
- const span = 2 ** (8 * (t.level + 1));
488
- return {
489
- first: t.index * span,
490
- end: (t.index + 1) * span
491
- };
492
- }
493
- /**
494
- * Whether a tile is still read once retention has cut the tree below leaf
495
- * `cut`: proofs of leaves at or above the cut, and consistency proofs from
496
- * sizes at or above it, read only tiles that reach past it, which at each
497
- * level is the tile holding the cut and those after it. Every tile wholly
498
- * below the cut can go, at every level: about one tile per level stays
499
- * where a day of tiles would.
500
- */
501
- const keptAbove = (t, cut) => tileLeaves(t).end > cut;
502
- /** A `Nodes` over a set of tiles, keyed by `tileKey`: each node from the hashes of its tile. */
503
- function nodesFrom(tiles) {
504
- return (level, index) => {
505
- const { tile, offset, count } = tileOf(level, index);
506
- const hashes = tiles.get(tileKey(tile.level, tile.index));
507
- if (hashes === void 0 || hashes.length < (offset + count) * 32) throw new Error(`tile ${tile.level}/${tile.index} lacks node ${level}/${index}`);
508
- const layer = [];
509
- for (let i = 0; i < count; i += 1) layer.push(hashes.subarray((offset + i) * 32, (offset + i + 1) * 32));
510
- return hashUp(layer);
511
- };
512
- }
513
- /** The root of a perfect subtree from its 2^k bottom hashes. */
514
- function hashUp(hashes) {
515
- let layer = hashes;
516
- while (layer.length > 1) {
517
- const up = [];
518
- for (let i = 0; i < layer.length; i += 2) up.push(nodeHash(layer[i], layer[i + 1]));
519
- layer = up;
520
- }
521
- return Buffer.from(layer[0]);
522
- }
523
- /** The tiles a computation over `Nodes` reads: run it once against a recorder, then fetch them all in one query. */
524
- function tilesFor(compute) {
525
- const seen = /* @__PURE__ */ new Map();
526
- compute((level, index) => {
527
- const { tile } = tileOf(level, index);
528
- seen.set(tileKey(tile.level, tile.index), tile);
529
- return Buffer.alloc(32);
530
- });
531
- return [...seen.values()];
532
- }
533
- function tileMap(tiles) {
534
- return new Map(tiles.map((t) => [tileKey(t.level, t.index), t.hashes]));
535
- }
536
- /** The tiles at the right edge of a tree of `size` leaves, one per level, with their widths: all the state appending needs. */
537
- function edgeOf(size) {
538
- const edge = [];
539
- for (let t = 0;; t += 1) {
540
- const below = Math.floor(size / 2 ** (t * 8));
541
- edge.push({
542
- level: t,
543
- index: Math.floor(below / 256),
544
- width: below % 256
545
- });
546
- if (below < 256) return edge;
547
- }
548
- }
549
- /**
550
- * The tree's growing edge, in memory: the partial tile at each level.
551
- * Appending leaves fills level 0; each tile that fills up pushes its root into
552
- * the level above. What changed comes back as tiles to write: every tile
553
- * filled, and every partial edge tile that grew.
554
- */
555
- var Edge = class Edge {
556
- size;
557
- tiles;
558
- constructor(size, tiles) {
559
- this.size = size;
560
- this.tiles = tiles;
561
- }
562
- static empty() {
563
- return new Edge(0, [[]]);
564
- }
565
- /** From the stored edge tiles of a tree of `size` leaves (`edgeOf(size)`), each cut to its width. */
566
- static load(size, stored) {
567
- const tiles = edgeOf(size).map(({ level, index, width }) => {
568
- if (width === 0) return [];
569
- const hashes = stored.get(tileKey(level, index));
570
- if (hashes === void 0 || hashes.length < width * 32) throw new Error(`edge tile ${level}/${index} missing or short`);
571
- return Array.from({ length: width }, (_, i) => Buffer.from(hashes.subarray(i * 32, (i + 1) * 32)));
572
- });
573
- return new Edge(size, tiles);
574
- }
575
- /** A copy to append to, so a failed write leaves this edge at the head it was. */
576
- clone() {
577
- return new Edge(this.size, this.tiles.map((t) => [...t]));
578
- }
579
- append(leaves) {
580
- const changed = [];
581
- const grew = /* @__PURE__ */ new Set();
582
- for (const leaf of leaves) {
583
- let hash = leaf;
584
- for (let t = 0;; t += 1) {
585
- const tile = this.tiles[t] ??= [];
586
- tile.push(hash);
587
- if (tile.length < 256) {
588
- grew.add(t);
589
- break;
590
- }
591
- changed.push({
592
- level: t,
593
- index: Math.floor(this.size / 2 ** ((t + 1) * 8)),
594
- hashes: Buffer.concat(tile)
595
- });
596
- grew.delete(t);
597
- hash = hashUp(tile);
598
- this.tiles[t] = [];
599
- }
600
- this.size += 1;
601
- }
602
- for (const t of grew) changed.push({
603
- level: t,
604
- index: Math.floor(this.size / 2 ** ((t + 1) * 8)),
605
- hashes: Buffer.concat(this.tiles[t])
606
- });
607
- return changed;
608
- }
609
- /** The tree head now. */
610
- root() {
611
- return treeHash(nodesFrom(tileMap(this.edgeTiles())), this.size);
612
- }
613
- /**
614
- * The tile at the right edge of each level, as it stands. With the tiles an append filled, they hold every node a
615
- * proof of a leaf that append added reads: the tile of the leaf's ancestor at each level is one of them, and so is
616
- * every tile to its right.
617
- */
618
- edgeTiles() {
619
- return edgeOf(this.size).map(({ level, index }) => ({
620
- level,
621
- index,
622
- hashes: Buffer.concat(this.tiles[level] ?? [])
623
- }));
624
- }
625
- };
626
- /** Go's tile path, `tile/8/<L>/<N>[.p/<W>]`, N in groups of three digits (x001/x234/067). */
627
- function tilePath(t, width) {
628
- let n = String(t.index);
629
- const groups = [];
630
- while (n.length > 3) {
631
- groups.unshift(n.slice(-3));
632
- n = n.slice(0, -3);
633
- }
634
- const parts = [n.padStart(3, "0"), ...groups].map((g, i, all) => i < all.length - 1 ? `x${g}` : g);
635
- return `tile/8/${t.level}/${parts.join("/")}${width < 256 ? `.p/${width}` : ""}`;
636
- }
637
- function parseTilePath(path) {
638
- const m = /^tile\/8\/(\d{1,2})\/((?:x\d{3}\/)*\d{3})(?:\.p\/(\d{1,3}))?$/.exec(path);
639
- if (m === null) return null;
640
- const width = m[3] === void 0 ? 256 : Number(m[3]);
641
- if (width < 1 || m[3] !== void 0 && width >= 256) return null;
642
- const tile = {
643
- level: Number(m[1]),
644
- index: Number(m[2].replaceAll("x", "").replaceAll("/", "")),
645
- width
646
- };
647
- return Number.isSafeInteger(tile.index) && tilePath(tile, width) === path ? tile : null;
648
- }
649
- //#endregion
650
- //#region src/audit/verify.ts
651
- const PAGE = 100;
652
- async function verifyLog(reader, opts) {
653
- const problems = [];
654
- const verdict = {
655
- checkpoints: 0,
656
- sealed: 0,
657
- unsealed: 0,
658
- behind: false,
659
- capped: false
660
- };
661
- const done = (head) => {
662
- const ok = problems.length === 0;
663
- return {
664
- ok,
665
- problems,
666
- ...verdict,
667
- head: ok ? head?.notes ?? null : null,
668
- headPair: ok ? head?.pair ?? null : null
669
- };
670
- };
671
- try {
672
- return await walk(reader, opts, problems, verdict, done);
673
- } catch (error) {
674
- problems.push(`verification stopped on what the database holds: ${error.message}`);
675
- return done(null);
676
- }
677
- }
678
- async function walk(reader, opts, problems, verdict, done) {
679
- const held = /* @__PURE__ */ new Map();
680
- const noted = (notes) => `${notes.changes}\0${notes.uses}`;
681
- const openHeld = (notes) => {
682
- const key = noted(notes);
683
- if (!held.has(key)) held.set(key, openPair(notes, opts.verifiers));
684
- return held.get(key);
685
- };
686
- const open = async (row) => {
687
- const pair = await (held.get(noted(row.notes)) ?? openPair(row.notes, opts.verifiers));
688
- if (pair === null) problems.push(`checkpoint ${row.upto}: not a pair signed by the log`);
689
- else if (pair.upto !== row.upto) problems.push(`checkpoint ${row.upto}: its row does not match its notes (up to ${pair.upto})`);
690
- else return pair;
691
- return null;
692
- };
693
- let start;
694
- const from = opts.newest?.notes ?? opts.from;
695
- if (from !== void 0) {
696
- const trusted = await openHeld(from);
697
- if (trusted === null) return problems.push("the pair to start from is not signed by the log"), done(null);
698
- const row = opts.newest ?? await reader.pair(trusted.upto);
699
- const pair = row === null ? null : await open(row);
700
- if (pair === null || !sameNotes(pair, trusted)) return problems.push(`no checkpoint at ${trusted.upto} with the pair to start from: checkpoints were deleted or replaced`), done(null);
701
- start = {
702
- pair,
703
- notes: row.notes,
704
- row: true
705
- };
706
- } else {
707
- const [row] = await reader.pairs(-1n, 1);
708
- const pair = row === void 0 ? null : await open(row);
709
- if (!(pair !== null && pair.upto === 0n && TREES.every((tree) => pair[tree].size === 0 && pair[tree].root.equals(EMPTY_ROOT)))) return problems.push("no genesis checkpoint to start from: checkpoints were deleted or replaced"), done(null);
710
- start = {
711
- pair,
712
- notes: row.notes,
713
- row: true
714
- };
715
- }
716
- const retained = opts.cut === void 0 || reader.retention === void 0 ? null : await reader.retention();
717
- const cut = retained === null ? null : opts.cut(retained.entry);
718
- if (retained !== null) {
719
- const { entry, index } = retained;
720
- if (cut === null) return problems.push(`${entry.number}: the newest retention change names no cut`), done(null);
721
- if (cut.upto >= entry.number) return problems.push(`${entry.number}: a retention change at or below its own cut (${cut.upto})`), done(null);
722
- if (entry.number <= start.pair.upto) {
723
- const size = start.pair.changes.size;
724
- const proof = Number.isSafeInteger(index) && index >= 0 && index < size ? inclusionProof(nodesFrom(tileMap(await reader.tiles("changes", tilesFor((n) => inclusionProof(n, index, size))))), index, size) : null;
725
- if (proof === null || !verifyInclusion(entryLeaf("changes", entry.number, entry.columns), index, size, proof, start.pair.changes.root)) return problems.push(`${entry.number}: the retention change cutting the uses at ${cut.upto} is not in the changes tree the walk starts from`), done(null);
726
- }
727
- }
728
- const ahead = cut !== null && cut.upto > start.pair.upto ? cut : null;
729
- const dropped = (e) => ahead !== null && e.tree === "uses" && e.number <= ahead.upto;
730
- const load = async (pair) => {
731
- const edges = {};
732
- for (const tree of TREES) {
733
- const head = tree === "uses" && ahead !== null && pair.upto < ahead.upto ? ahead.uses : pair[tree];
734
- edges[tree] = await loadEdge(reader, tree, head.size, head.root, pair.upto);
735
- }
736
- return edges;
737
- };
738
- const reload = (pair) => load(pair).catch((error) => (problems.push(error.message), null));
739
- const below = (await Promise.all((opts.anchors ?? []).map(openHeld))).filter((a) => a !== null && a.upto <= start.pair.upto).sort((a, b) => a.upto < b.upto ? -1 : 1);
740
- for (const [i, a] of below.entries()) {
741
- const next = below[i + 1] ?? start.pair;
742
- if (next.at < a.at || next.floor < a.floor) problems.push(`the pair held outside up to ${a.upto}: its time or floor is past the next pair's (up to ${next.upto}): time runs back`);
743
- if (next.upto === a.upto && (next.at !== a.at || next.floor !== a.floor || next.prev !== a.prev)) problems.push(`two pairs held outside up to ${a.upto}, signed at two times, floors or prevs`);
744
- }
745
- const above = [];
746
- for (const notes of opts.anchors ?? []) {
747
- const anchor = await openHeld(notes);
748
- if (anchor === null) problems.push("a pair held outside is not signed by the log");
749
- else if (anchor.upto > start.pair.upto) above.push({
750
- pair: anchor,
751
- notes,
752
- row: false
753
- });
754
- else if (sameNotes(anchor, start.pair)) {} else {
755
- const row = await reader.pair(anchor.upto);
756
- const pair = row === null ? null : await open(row);
757
- if (pair !== null && !sameNotes(pair, anchor)) problems.push(`checkpoint ${anchor.upto}: not the pair held outside for that place: ${samePair(pair, anchor) ? "the same heads signed at another time or floor" : "a second history"}`);
758
- const forks = await Promise.all(TREES.map(async (tree) => {
759
- if (tree === "uses" && cut !== null && anchor.uses.size < cut.uses.size) return null;
760
- const [from, to] = [anchor[tree], start.pair[tree]];
761
- const proof = from.size > to.size ? null : await proveConsistency(reader, tree, from.size, to.size).catch(() => null);
762
- return proof === null || !verifyConsistency(from.size, to.size, from.root, to.root, proof) ? tree : null;
763
- }));
764
- for (const tree of forks) if (tree !== null) problems.push(`the pair held outside up to ${anchor.upto}: its ${tree} head is not a prefix of the start's: a second history, or tiles deleted`);
765
- }
766
- }
767
- above.sort((a, b) => a.pair.upto < b.pair.upto ? -1 : 1);
768
- let edges = null;
769
- if (opts.newest === void 0) {
770
- edges = await reload(start.pair);
771
- if (edges === null) return done(null);
772
- }
773
- let last = start;
774
- let cursor = start.pair.upto;
775
- let previous = start.pair.upto;
776
- let time = start.pair.at;
777
- let floor = start.pair.floor;
778
- let retainedMet = retained === null || retained.entry.number <= start.pair.upto;
779
- let cutMet = ahead === null;
780
- const walkEntries = (entries) => {
781
- for (const e of entries) {
782
- if (e.tree === "changes" && retained !== null && e.number === retained.entry.number) {
783
- if (!sameEntry(e, retained.entry)) problems.push(`${e.number}: not the retention change the database names at its number`);
784
- else retainedMet = true;
785
- }
786
- if (e.number <= previous) problems.push(`${e.number}: numbered at or below the entry before (${previous}): two entries with one number, or out of order`);
787
- if (!TREES.includes(e.tree)) problems.push(`${e.number}: in no tree (${String(e.tree)})`);
788
- const problem = opts.check?.(e) ?? null;
789
- if (problem !== null) problems.push(`${e.number}: ${problem}`);
790
- previous = e.number > previous ? e.number : previous;
791
- }
792
- };
793
- for (let rows = opts.newest === void 0 ? await reader.pairs(start.pair.upto, PAGE) : [];; rows = await reader.pairs(rows.at(-1).upto, PAGE)) {
794
- const stops = [];
795
- for (const row of rows) {
796
- const pair = await open(row);
797
- if (pair !== null) stops.push({
798
- pair,
799
- notes: row.notes,
800
- row: true
801
- });
802
- }
803
- const final = rows.length < PAGE;
804
- const newest = (stops.at(-1) ?? last).pair.upto;
805
- while (above.length > 0 && (final || above[0].pair.upto <= rows.at(-1).upto)) {
806
- const anchor = above.shift();
807
- const row = stops.find((s) => s.pair.upto === anchor.pair.upto);
808
- if (row !== void 0) {
809
- if (!sameNotes(row.pair, anchor.pair)) problems.push(`checkpoint ${anchor.pair.upto}: not the pair held outside for that place: ${samePair(row.pair, anchor.pair) ? "the same heads signed at another time or floor" : "a second history"}`);
810
- } else if (final && anchor.pair.upto > newest) {
811
- verdict.behind = true;
812
- problems.push(`the database ends up to ${newest}; a pair held outside seals up to ${anchor.pair.upto}: entries or checkpoints were deleted`);
813
- } else stops.push(anchor);
814
- }
815
- stops.sort((a, b) => a.pair.upto < b.pair.upto ? -1 : 1);
816
- if (stops.length > 0) {
817
- if (edges === null) {
818
- edges = await reload(start.pair);
819
- if (edges === null) return done(null);
820
- }
821
- const entries = (await reader.entries(cursor, stops.at(-1).pair.upto, { floor })).filter((e) => !dropped(e));
822
- let at = 0;
823
- for (const stop of stops) {
824
- const window = [];
825
- while (at < entries.length && entries[at].number <= stop.pair.upto) window.push(entries[at++]);
826
- walkEntries(window);
827
- for (const tree of TREES) edges[tree].append(window.filter((e) => e.tree === tree).map((e) => entryLeaf(tree, e.number, e.columns)));
828
- verdict.sealed += window.length;
829
- if (stop.pair.at < time) problems.push(`${stop.row ? "checkpoint" : "the pair held outside up to"} ${stop.pair.upto}: signed at ${stop.pair.at}, before the pair before it (${time}): time runs back`);
830
- if (stop.pair.floor < floor) problems.push(`${stop.row ? "checkpoint" : "the pair held outside up to"} ${stop.pair.upto}: its floor of at (${stop.pair.floor}) is below the one before it (${floor})`);
831
- time = Math.max(time, stop.pair.at);
832
- floor = Math.max(floor, stop.pair.floor);
833
- cursor = stop.pair.upto;
834
- const walked = TREES.filter((tree) => tree === "changes" || ahead === null || stop.pair.upto >= ahead.upto);
835
- if (ahead !== null && stop.pair.upto === ahead.upto) {
836
- if (stop.pair.uses.size !== ahead.uses.size || !stop.pair.uses.root.equals(ahead.uses.root)) problems.push(`${stop.row ? "checkpoint" : "the pair held outside up to"} ${stop.pair.upto}: not the uses head the retention change cuts at`);
837
- else if (stop.row) cutMet = true;
838
- }
839
- if (ahead !== null && stop.pair.upto > ahead.upto && !cutMet) {
840
- problems.push(`no checkpoint at the retention cut (${ahead.upto}): checkpoints were deleted or replaced`);
841
- cutMet = true;
842
- }
843
- const grown = edges;
844
- const wrong = walked.filter((tree) => grown[tree].size !== stop.pair[tree].size || !grown[tree].root().equals(stop.pair[tree].root));
845
- if (wrong.length > 0) {
846
- problems.push(`${stop.row ? "checkpoint" : "the pair held outside up to"} ${stop.pair.upto}: the ${wrong.join(" and ")} head${wrong.length > 1 ? "s" : ""} differ from the entries: entries deleted, added, changed or moved, or a second history`);
847
- if (stop.row) edges = await reload(stop.pair) ?? edges;
848
- }
849
- if (stop.row) {
850
- verdict.checkpoints += 1;
851
- last = stop;
852
- }
853
- }
854
- }
855
- if (final) break;
856
- }
857
- if (!verdict.behind) {
858
- const limit = opts.above === void 0 ? {} : { limit: opts.above + 1 };
859
- const unsealed = (await reader.entries(cursor, MAX_NUMBER, {
860
- floor,
861
- ...limit
862
- })).filter((e) => !dropped(e));
863
- const checked = opts.above === void 0 ? unsealed : unsealed.slice(0, opts.above);
864
- walkEntries(checked);
865
- verdict.unsealed = checked.length;
866
- verdict.capped = checked.length < unsealed.length;
867
- }
868
- if (!cutMet) problems.push(`no checkpoint at the retention cut (${ahead.upto}): checkpoints were deleted or replaced`);
869
- if (!retainedMet || retained !== null && retained.entry.number > last.pair.upto) problems.push(`${retained.entry.number}: the retention change cutting the uses at ${cut.upto} is not sealed in the changes tree`);
870
- return done(last);
871
- }
872
- /**
873
- * Whether a pair held outside is the row at its place: the same heads, and
874
- * the same time and floor. Two notes for one place signed at two times take the
875
- * signer's key twice; honest pairs held outside are copies of rows.
876
- */
877
- const sameNotes = (a, b) => samePair(a, b) && a.at === b.at && a.floor === b.floor && a.prev === b.prev;
878
- /** Both trees' edges at a pair, from their tiles; throws unless each gives its signed head. */
879
- async function loadEdges(reader, pair) {
880
- const edges = {};
881
- for (const tree of TREES) edges[tree] = await loadEdge(reader, tree, pair[tree].size, pair[tree].root, pair.upto);
882
- return edges;
883
- }
884
- /** One tree's edge at `size`, from its tiles; throws unless it gives `root`, the head signed up to `upto`. */
885
- async function loadEdge(reader, tree, size, root, upto) {
886
- const edge = Edge.load(size, tileMap(await reader.tiles(tree, edgeOf(size).filter((e) => e.width > 0))));
887
- if (!edge.root().equals(root)) throw new Error(`checkpoint ${upto}: the ${tree} tiles at its edge do not give its signed head`);
888
- return edge;
889
- }
890
- /** Whether two entries are one, whole: the same leaf. */
891
- const sameEntry = (a, b) => leafData(a.tree, a.number, a.columns).equals(leafData(b.tree, b.number, b.columns));
892
- /** A consistency proof between two sizes of one tree, from its tiles. */
893
- async function proveConsistency(reader, tree, from, to) {
894
- return consistencyProof(nodesFrom(tileMap(await reader.tiles(tree, tilesFor((n) => consistencyProof(n, from, to))))), from, to);
895
- }
896
- //#endregion
897
- //#region src/audit/witness.ts
898
- async function witnessPair(state, notes, proofs, log, self) {
899
- const pair = await openPair(notes, log);
900
- if (pair === null) return {
901
- state,
902
- answer: {
903
- ok: false,
904
- reason: "not a pair signed by the log"
905
- }
906
- };
907
- if (state !== null) {
908
- const held = state.pair;
909
- if (pair.upto < held.upto) return {
910
- state,
911
- answer: {
912
- ok: false,
913
- reason: `older than the pair held (up to ${held.upto})`
914
- }
915
- };
916
- if (pair.at < held.at) return {
917
- state,
918
- answer: {
919
- ok: false,
920
- reason: `signed at ${pair.at}, before the pair held (${held.at}): time runs back`
921
- }
922
- };
923
- if (pair.floor < held.floor) return {
924
- state,
925
- answer: {
926
- ok: false,
927
- reason: `its floor of at (${pair.floor}) is below the pair held's (${held.floor})`
928
- }
929
- };
930
- if (pair.upto === held.upto && !samePair(pair, held)) return {
931
- state,
932
- answer: {
933
- ok: false,
934
- reason: `split view: a second pair up to ${pair.upto}`
935
- }
936
- };
937
- for (const tree of TREES) {
938
- const [from, to] = [held[tree], pair[tree]];
939
- if (!verifyConsistency(from.size, to.size, from.root, to.root, proofs[tree])) return {
940
- state,
941
- answer: {
942
- ok: false,
943
- reason: `split view: ${tree} at ${to.size} leaves up to ${pair.upto} does not extend ${from.size} up to ${held.upto}`
944
- }
945
- };
946
- }
947
- }
948
- const [changes, uses] = await Promise.all(TREES.map((tree) => cosignNote(notes[tree], self)));
949
- return {
950
- state: {
951
- pair,
952
- notes
953
- },
954
- answer: {
955
- ok: true,
956
- cosigned: {
957
- changes,
958
- uses
959
- }
960
- }
961
- };
962
- }
963
- //#endregion
964
- export { EMPTY_ROOT, Edge, HASH_SIZE, HEIGHT, LEAF_FORMAT, MAC_FORMAT, MAX_NUMBER, TREES, WIDTH, checkpointBody, consistencyProof, cosignNote, decodePair, edgeOf, encodePair, entryLeaf, inclusionProof, isPowerOfTwo, keptAbove, leafData, leafHash, loadEdges, macData, nodeHash, nodesFrom, noteSigner, noteVerifier, openCheckpoint, openNote, openPair, pairSigners, pairVerifiers, parseCheckpoint, parseTilePath, proveConsistency, rangeHash, samePair, signNote, signPair, splitNote, tileKey, tileLeaves, tileMap, tileOf, tilePath, tilesFor, treeHash, treeOrigin, verifyConsistency, verifyInclusion, verifyLog, witnessPair };