xvcache-mcp 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,295 @@
1
+ import { createHash } from "node:crypto";
2
+ import { promises as fs } from "node:fs";
3
+ import path from "node:path";
4
+ export const GENESIS_PREV_HASH = "0".repeat(64);
5
+ export function sha256Hex(data) {
6
+ return createHash("sha256").update(data).digest("hex");
7
+ }
8
+ function sortKeys(value) {
9
+ if (value === null || typeof value !== "object")
10
+ return value;
11
+ if (Array.isArray(value))
12
+ return value.map(sortKeys);
13
+ const obj = value;
14
+ const out = {};
15
+ for (const k of Object.keys(obj).sort())
16
+ out[k] = sortKeys(obj[k]);
17
+ return out;
18
+ }
19
+ /** JSON canonique : clés triées, pas d'espaces superflus. */
20
+ export function canonicalJson(value) {
21
+ return JSON.stringify(sortKeys(value));
22
+ }
23
+ export function computeEntryHash(entry) {
24
+ return sha256Hex(entry.prev_hash + canonicalJson(entry));
25
+ }
26
+ export function normalizeNotePath(rel) {
27
+ let p = rel.replace(/\\/g, "/");
28
+ if (!p.toLowerCase().endsWith(".md"))
29
+ p += ".md";
30
+ return p;
31
+ }
32
+ export function parseEntry(line) {
33
+ let raw;
34
+ try {
35
+ raw = JSON.parse(line);
36
+ }
37
+ catch {
38
+ return { error: "JSON invalide" };
39
+ }
40
+ if (!raw || typeof raw !== "object" || Array.isArray(raw)) {
41
+ return { error: "JSON invalide" };
42
+ }
43
+ const o = raw;
44
+ if (typeof o.seq !== "number" || !Number.isInteger(o.seq))
45
+ return { error: "seq invalide" };
46
+ if (typeof o.ts !== "string")
47
+ return { error: "ts invalide" };
48
+ if (typeof o.tool !== "string")
49
+ return { error: "tool invalide" };
50
+ if (typeof o.prev_hash !== "string")
51
+ return { error: "prev_hash invalide" };
52
+ if (typeof o.hash !== "string")
53
+ return { error: "hash invalide" };
54
+ if (o.result !== "ok" && o.result !== "erreur")
55
+ return { error: "result invalide" };
56
+ if (o.client !== null && typeof o.client !== "string")
57
+ return { error: "client invalide" };
58
+ if (o.note_sha256 !== null && typeof o.note_sha256 !== "string")
59
+ return { error: "note_sha256 invalide" };
60
+ if (!o.args || typeof o.args !== "object" || Array.isArray(o.args))
61
+ return { error: "args invalide" };
62
+ const a = o.args;
63
+ const args = {};
64
+ if (typeof a.path === "string")
65
+ args.path = a.path;
66
+ if (typeof a.query === "string")
67
+ args.query = a.query;
68
+ if (typeof a.mode === "string")
69
+ args.mode = a.mode;
70
+ return {
71
+ seq: o.seq,
72
+ ts: o.ts,
73
+ tool: o.tool,
74
+ args,
75
+ client: o.client,
76
+ result: o.result,
77
+ note_sha256: o.note_sha256,
78
+ prev_hash: o.prev_hash,
79
+ hash: o.hash,
80
+ };
81
+ }
82
+ export function verifyChain(lines) {
83
+ let prevHash = GENESIS_PREV_HASH;
84
+ let prevSeq = 0;
85
+ let lastTs;
86
+ let lastHash;
87
+ let count = 0;
88
+ for (let i = 0; i < lines.length; i++) {
89
+ const line = lines[i];
90
+ const lineNo = i + 1;
91
+ const parsed = parseEntry(line);
92
+ if ("error" in parsed) {
93
+ return {
94
+ ok: false,
95
+ entries: count,
96
+ lastTs,
97
+ lastHash,
98
+ lastSeq: prevSeq || undefined,
99
+ issue: { seq: null, line: lineNo, reason: parsed.error },
100
+ };
101
+ }
102
+ if (parsed.seq !== prevSeq + 1) {
103
+ return {
104
+ ok: false,
105
+ entries: count,
106
+ lastTs,
107
+ lastHash,
108
+ lastSeq: prevSeq || undefined,
109
+ issue: { seq: parsed.seq, line: lineNo, reason: "seq inattendu" },
110
+ };
111
+ }
112
+ if (parsed.prev_hash !== prevHash) {
113
+ return {
114
+ ok: false,
115
+ entries: count,
116
+ lastTs,
117
+ lastHash,
118
+ lastSeq: prevSeq || undefined,
119
+ issue: { seq: parsed.seq, line: lineNo, reason: "prev_hash inattendu" },
120
+ };
121
+ }
122
+ const { hash: _ignored, ...payload } = parsed;
123
+ const expected = computeEntryHash(payload);
124
+ if (parsed.hash !== expected) {
125
+ return {
126
+ ok: false,
127
+ entries: count,
128
+ lastTs,
129
+ lastHash,
130
+ lastSeq: prevSeq || undefined,
131
+ issue: { seq: parsed.seq, line: lineNo, reason: "hash invalide" },
132
+ };
133
+ }
134
+ prevHash = parsed.hash;
135
+ prevSeq = parsed.seq;
136
+ lastTs = parsed.ts;
137
+ lastHash = parsed.hash;
138
+ count++;
139
+ }
140
+ return { ok: true, entries: count, lastTs, lastHash, lastSeq: prevSeq || undefined };
141
+ }
142
+ export function formatChainMessage(v) {
143
+ if (v.ok) {
144
+ if (v.entries === 0)
145
+ return "Journal intact : 0 entrée.";
146
+ const n = v.entries === 1 ? "1 entrée" : `${v.entries} entrées`;
147
+ return `Journal intact : ${n}, dernière à ${v.lastTs}.`;
148
+ }
149
+ const issue = v.issue;
150
+ const where = issue.seq != null ? `seq=${issue.seq}` : `ligne ${issue.line}`;
151
+ return `Journal altéré : première ligne cassée à ${where} (${issue.reason}).`;
152
+ }
153
+ export async function readJournalText(filePath) {
154
+ try {
155
+ return await fs.readFile(filePath, "utf8");
156
+ }
157
+ catch (e) {
158
+ if (typeof e === "object" && e !== null && "code" in e && e.code === "ENOENT") {
159
+ return "";
160
+ }
161
+ throw e;
162
+ }
163
+ }
164
+ /** Découpe un JSONL en lignes complètes (sans la ligne traînante s'il manque le \\n final). */
165
+ export function splitCompleteLines(text) {
166
+ if (text === "")
167
+ return { lines: [], incomplete: false };
168
+ const incomplete = !text.endsWith("\n");
169
+ const parts = text.split("\n");
170
+ if (parts.length && parts[parts.length - 1] === "")
171
+ parts.pop();
172
+ else if (incomplete)
173
+ parts.pop();
174
+ return { lines: parts.filter((l, i, arr) => l.length > 0 || i < arr.length), incomplete };
175
+ }
176
+ export async function readCompleteJournalLines(filePath) {
177
+ const text = await readJournalText(filePath);
178
+ return splitCompleteLines(text).lines.filter((l) => l.length > 0);
179
+ }
180
+ export async function verifyJournalFile(filePath) {
181
+ const lines = await readCompleteJournalLines(filePath);
182
+ return verifyChain(lines);
183
+ }
184
+ export function lastNoteRecord(entries, notePath) {
185
+ const want = normalizeNotePath(notePath);
186
+ let found;
187
+ for (const e of entries) {
188
+ if (e.note_sha256 && e.args.path && normalizeNotePath(e.args.path) === want) {
189
+ found = e;
190
+ }
191
+ }
192
+ return found;
193
+ }
194
+ /**
195
+ * Charge l'état de la chaîne. Si le fichier se termine par une ligne incomplète
196
+ * (écriture interrompue avant le saut de ligne + fsync), cette queue est tronquée.
197
+ */
198
+ export async function loadJournalState(filePath) {
199
+ await fs.mkdir(path.dirname(filePath), { recursive: true });
200
+ let text;
201
+ try {
202
+ text = await fs.readFile(filePath, "utf8");
203
+ }
204
+ catch (e) {
205
+ if (typeof e === "object" && e !== null && "code" in e && e.code === "ENOENT") {
206
+ return { nextSeq: 1, prevHash: GENESIS_PREV_HASH, truncated: false };
207
+ }
208
+ throw e;
209
+ }
210
+ if (text === "")
211
+ return { nextSeq: 1, prevHash: GENESIS_PREV_HASH, truncated: false };
212
+ const { lines, incomplete } = splitCompleteLines(text);
213
+ const complete = lines.filter((l) => l.length > 0);
214
+ if (incomplete) {
215
+ const kept = complete.join("\n") + (complete.length ? "\n" : "");
216
+ await fs.writeFile(filePath, kept, "utf8");
217
+ }
218
+ if (complete.length === 0)
219
+ return { nextSeq: 1, prevHash: GENESIS_PREV_HASH, truncated: incomplete };
220
+ const lastLine = complete[complete.length - 1];
221
+ const parsed = parseEntry(lastLine);
222
+ if ("error" in parsed) {
223
+ // On reprend quand même sur le hash stocké s'il est lisible, sinon on échoue au chargement.
224
+ throw new Error(`Journal illisible à la dernière ligne : ${parsed.error}`);
225
+ }
226
+ return { nextSeq: parsed.seq + 1, prevHash: parsed.hash, truncated: incomplete };
227
+ }
228
+ export class JournalWriter {
229
+ filePath;
230
+ nextSeq = 1;
231
+ prevHash = GENESIS_PREV_HASH;
232
+ ready;
233
+ queue = Promise.resolve();
234
+ constructor(filePath) {
235
+ this.filePath = filePath;
236
+ this.ready = this.init();
237
+ }
238
+ get path() {
239
+ return this.filePath;
240
+ }
241
+ async init() {
242
+ const state = await loadJournalState(this.filePath);
243
+ this.nextSeq = state.nextSeq;
244
+ this.prevHash = state.prevHash;
245
+ }
246
+ async append(input) {
247
+ await this.ready;
248
+ let release;
249
+ const prev = this.queue;
250
+ this.queue = new Promise((r) => { release = r; });
251
+ await prev;
252
+ try {
253
+ const payload = {
254
+ seq: this.nextSeq,
255
+ ts: new Date().toISOString(),
256
+ tool: input.tool,
257
+ args: input.args,
258
+ client: input.client,
259
+ result: input.result,
260
+ note_sha256: input.note_sha256,
261
+ prev_hash: this.prevHash,
262
+ };
263
+ const entry = { ...payload, hash: computeEntryHash(payload) };
264
+ const fh = await fs.open(this.filePath, "a");
265
+ try {
266
+ await fh.write(JSON.stringify(entry) + "\n", undefined, "utf8");
267
+ await fh.sync();
268
+ }
269
+ finally {
270
+ await fh.close();
271
+ }
272
+ this.nextSeq = entry.seq + 1;
273
+ this.prevHash = entry.hash;
274
+ return entry;
275
+ }
276
+ finally {
277
+ release();
278
+ }
279
+ }
280
+ }
281
+ /** Compare a note's current sha256 to the last journaled fingerprint. */
282
+ export function formatNoteVerdict(relMd, rec, currentSha) {
283
+ const shown = relMd.replace(/\\/g, "/");
284
+ const client = rec.client ?? "client inconnu";
285
+ if (currentSha === rec.note_sha256) {
286
+ return {
287
+ glyph: "V",
288
+ message: `V intacte — Note ${shown} intacte depuis ${rec.ts} par ${client}.`,
289
+ };
290
+ }
291
+ return {
292
+ glyph: "X",
293
+ message: `X MODIFIÉE hors XVcache — Note ${shown} MODIFIÉE hors XVcache après ${rec.ts}.`,
294
+ };
295
+ }
package/dist/merkle.js ADDED
@@ -0,0 +1,66 @@
1
+ import { createHash } from "node:crypto";
2
+ import { canonicalJson } from "./journal.js";
3
+ const HEX64 = /^[0-9a-f]{64}$/;
4
+ function sha(...parts) {
5
+ const h = createHash("sha256");
6
+ for (const p of parts)
7
+ h.update(p);
8
+ return h.digest();
9
+ }
10
+ export function leafHash(data) {
11
+ return sha(Buffer.from([0x00]), Buffer.from(canonicalJson(data), "utf8")).toString("hex");
12
+ }
13
+ export function nodeHash(leftHex, rightHex) {
14
+ return sha(Buffer.from([0x01]), Buffer.from(leftHex, "hex"), Buffer.from(rightHex, "hex")).toString("hex");
15
+ }
16
+ export function merkleRoot(leaves) {
17
+ if (leaves.length === 0)
18
+ throw new Error("Merkle : aucune feuille.");
19
+ let level = leaves.slice();
20
+ while (level.length > 1) {
21
+ const next = [];
22
+ for (let i = 0; i < level.length; i += 2) {
23
+ next.push(i + 1 < level.length ? nodeHash(level[i], level[i + 1]) : level[i]);
24
+ }
25
+ level = next;
26
+ }
27
+ return level[0];
28
+ }
29
+ /** Audit path for leaf `index`: siblings from bottom to top, with the sibling's side. */
30
+ export function merklePath(leaves, index) {
31
+ if (index < 0 || index >= leaves.length)
32
+ throw new Error("Merkle : index hors limites.");
33
+ const steps = [];
34
+ let level = leaves.slice();
35
+ let i = index;
36
+ while (level.length > 1) {
37
+ const isRight = i % 2 === 1;
38
+ const sib = isRight ? i - 1 : i + 1;
39
+ if (sib < level.length)
40
+ steps.push({ position: isRight ? "left" : "right", hash: level[sib] });
41
+ const next = [];
42
+ for (let j = 0; j < level.length; j += 2) {
43
+ next.push(j + 1 < level.length ? nodeHash(level[j], level[j + 1]) : level[j]);
44
+ }
45
+ level = next;
46
+ i = Math.floor(i / 2);
47
+ }
48
+ return steps;
49
+ }
50
+ export function foldMerklePath(leafHex, steps) {
51
+ let acc = leafHex;
52
+ for (const s of steps) {
53
+ if (!HEX64.test(s.hash))
54
+ throw new Error("Merkle : hash de chemin invalide.");
55
+ acc = s.position === "left" ? nodeHash(s.hash, acc) : nodeHash(acc, s.hash);
56
+ }
57
+ return acc;
58
+ }
59
+ export function verifyMerklePath(leafHex, steps, rootHex) {
60
+ try {
61
+ return foldMerklePath(leafHex, steps) === rootHex;
62
+ }
63
+ catch {
64
+ return false;
65
+ }
66
+ }
package/dist/ots.js ADDED
@@ -0,0 +1,311 @@
1
+ import { createHash } from "node:crypto";
2
+ /**
3
+ * Minimal OpenTimestamps client (stamp, upgrade, Bitcoin check) without extra dependencies.
4
+ * File format: https://github.com/opentimestamps/python-opentimestamps (core/serialize, timestamp, op, notary).
5
+ */
6
+ export const OTS_HEADER = Buffer.concat([
7
+ Buffer.from("004f70656e54696d657374616d7073000050726f6f6600bf89e2e884e89294", "hex"),
8
+ ]);
9
+ const OTS_MAJOR_VERSION = 1;
10
+ const TAG_PENDING = "83dfe30d2ef90c8e";
11
+ const TAG_BITCOIN = "0588960d73d71901";
12
+ export const DEFAULT_CALENDARS = [
13
+ "https://a.pool.opentimestamps.org",
14
+ "https://b.pool.opentimestamps.org",
15
+ "https://a.pool.eternitywall.com",
16
+ ];
17
+ const ALLOWED_CALENDAR_HOSTS = new Set([
18
+ "a.pool.opentimestamps.org", "b.pool.opentimestamps.org", "a.pool.eternitywall.com",
19
+ "alice.btc.calendar.opentimestamps.org", "bob.btc.calendar.opentimestamps.org",
20
+ "finney.calendar.eternitywall.com", "btc.calendar.catallaxy.com", "ots.btc.catallaxy.com",
21
+ ]);
22
+ export class Timestamp {
23
+ msg;
24
+ attestations = [];
25
+ ops = new Map();
26
+ constructor(msg) { this.msg = msg; }
27
+ }
28
+ function opKey(op) {
29
+ return op.tag.toString(16).padStart(2, "0") + (op.arg ? op.arg.toString("hex") : "");
30
+ }
31
+ function hashWith(alg, msg) {
32
+ return createHash(alg).update(msg).digest();
33
+ }
34
+ export function applyOp(op, msg) {
35
+ switch (op.tag) {
36
+ case 0xf0: return Buffer.concat([msg, op.arg]);
37
+ case 0xf1: return Buffer.concat([op.arg, msg]);
38
+ case 0xf2: return Buffer.from(msg).reverse();
39
+ case 0xf3: return Buffer.from(msg.toString("hex"), "utf8");
40
+ case 0x08: return hashWith("sha256", msg);
41
+ case 0x02: return hashWith("sha1", msg);
42
+ case 0x03: return hashWith("ripemd160", msg);
43
+ default: throw new Error(`OTS : opération 0x${op.tag.toString(16)} non supportée.`);
44
+ }
45
+ }
46
+ const BINARY_OPS = new Set([0xf0, 0xf1]);
47
+ const UNARY_OPS = new Set([0xf2, 0xf3, 0x08, 0x02, 0x03, 0x67]);
48
+ class Reader {
49
+ buf;
50
+ pos = 0;
51
+ constructor(buf) {
52
+ this.buf = buf;
53
+ }
54
+ byte() {
55
+ if (this.pos >= this.buf.length)
56
+ throw new Error("OTS : fichier tronqué.");
57
+ return this.buf[this.pos++];
58
+ }
59
+ bytes(n) {
60
+ if (this.pos + n > this.buf.length)
61
+ throw new Error("OTS : fichier tronqué.");
62
+ const b = this.buf.subarray(this.pos, this.pos + n);
63
+ this.pos += n;
64
+ return Buffer.from(b);
65
+ }
66
+ varuint() {
67
+ let value = 0, shift = 0, b;
68
+ do {
69
+ b = this.byte();
70
+ value += (b & 0x7f) * 2 ** shift;
71
+ shift += 7;
72
+ if (shift > 49)
73
+ throw new Error("OTS : varuint trop long.");
74
+ } while (b & 0x80);
75
+ return value;
76
+ }
77
+ varbytes(max = 8192) {
78
+ const n = this.varuint();
79
+ if (n > max)
80
+ throw new Error("OTS : champ trop long.");
81
+ return this.bytes(n);
82
+ }
83
+ done() { return this.pos === this.buf.length; }
84
+ }
85
+ function varuint(n) {
86
+ const out = [];
87
+ do {
88
+ let b = n % 128;
89
+ n = Math.floor(n / 128);
90
+ if (n > 0)
91
+ b |= 0x80;
92
+ out.push(b);
93
+ } while (n > 0);
94
+ return Buffer.from(out);
95
+ }
96
+ function varbytes(b) {
97
+ return Buffer.concat([varuint(b.length), b]);
98
+ }
99
+ function readAttestation(r) {
100
+ const tag = r.bytes(8).toString("hex");
101
+ const payload = r.varbytes();
102
+ const pr = new Reader(payload);
103
+ if (tag === TAG_PENDING)
104
+ return { kind: "pending", uri: pr.varbytes(1000).toString("utf8") };
105
+ if (tag === TAG_BITCOIN)
106
+ return { kind: "bitcoin", height: pr.varuint() };
107
+ return { kind: "unknown", tag, payload };
108
+ }
109
+ function writeAttestation(a) {
110
+ if (a.kind === "pending")
111
+ return Buffer.concat([Buffer.from(TAG_PENDING, "hex"), varbytes(varbytes(Buffer.from(a.uri, "utf8")))]);
112
+ if (a.kind === "bitcoin")
113
+ return Buffer.concat([Buffer.from(TAG_BITCOIN, "hex"), varbytes(varuint(a.height))]);
114
+ return Buffer.concat([Buffer.from(a.tag, "hex"), varbytes(a.payload)]);
115
+ }
116
+ export function readTimestamp(r, msg, depth = 0) {
117
+ if (depth > 256)
118
+ throw new Error("OTS : profondeur excessive.");
119
+ const ts = new Timestamp(msg);
120
+ const handle = (tag) => {
121
+ if (tag === 0x00) {
122
+ ts.attestations.push(readAttestation(r));
123
+ return;
124
+ }
125
+ let op;
126
+ if (BINARY_OPS.has(tag))
127
+ op = { tag, arg: r.varbytes(4096) };
128
+ else if (UNARY_OPS.has(tag))
129
+ op = { tag };
130
+ else
131
+ throw new Error(`OTS : tag inconnu 0x${tag.toString(16)}.`);
132
+ const next = applyOp(op, msg);
133
+ ts.ops.set(opKey(op), { op, stamp: readTimestamp(r, next, depth + 1) });
134
+ };
135
+ let tag = r.byte();
136
+ while (tag === 0xff) {
137
+ handle(r.byte());
138
+ tag = r.byte();
139
+ }
140
+ handle(tag);
141
+ return ts;
142
+ }
143
+ function writeOp(op) {
144
+ return op.arg ? Buffer.concat([Buffer.from([op.tag]), varbytes(op.arg)]) : Buffer.from([op.tag]);
145
+ }
146
+ export function writeTimestamp(ts) {
147
+ const items = [];
148
+ for (const a of ts.attestations)
149
+ items.push(Buffer.concat([Buffer.from([0x00]), writeAttestation(a)]));
150
+ const keys = [...ts.ops.keys()].sort();
151
+ for (const k of keys) {
152
+ const { op, stamp } = ts.ops.get(k);
153
+ items.push(Buffer.concat([writeOp(op), writeTimestamp(stamp)]));
154
+ }
155
+ if (items.length === 0)
156
+ throw new Error("OTS : horodatage vide.");
157
+ const parts = [];
158
+ items.forEach((it, i) => { if (i < items.length - 1)
159
+ parts.push(Buffer.from([0xff])); parts.push(it); });
160
+ return Buffer.concat(parts);
161
+ }
162
+ export function merge(into, other) {
163
+ if (!into.msg.equals(other.msg))
164
+ throw new Error("OTS : fusion de messages différents.");
165
+ for (const a of other.attestations) {
166
+ const enc = writeAttestation(a).toString("hex");
167
+ if (!into.attestations.some((b) => writeAttestation(b).toString("hex") === enc))
168
+ into.attestations.push(a);
169
+ }
170
+ for (const [k, v] of other.ops) {
171
+ const mine = into.ops.get(k);
172
+ if (mine)
173
+ merge(mine.stamp, v.stamp);
174
+ else
175
+ into.ops.set(k, v);
176
+ }
177
+ }
178
+ /** Serialize a detached .ots file for a SHA-256 digest. */
179
+ export function serializeOts(ts) {
180
+ return Buffer.concat([OTS_HEADER, varuint(OTS_MAJOR_VERSION), Buffer.from([0x08]), ts.msg, writeTimestamp(ts)]);
181
+ }
182
+ export function parseOts(buf) {
183
+ const r = new Reader(buf);
184
+ if (!r.bytes(OTS_HEADER.length).equals(OTS_HEADER))
185
+ throw new Error("OTS : en-tête invalide.");
186
+ if (r.varuint() !== OTS_MAJOR_VERSION)
187
+ throw new Error("OTS : version non supportée.");
188
+ if (r.byte() !== 0x08)
189
+ throw new Error("OTS : seul SHA-256 est supporté.");
190
+ const digest = r.bytes(32);
191
+ const ts = readTimestamp(r, digest);
192
+ if (!r.done())
193
+ throw new Error("OTS : octets en trop.");
194
+ return ts;
195
+ }
196
+ export function allAttestations(ts, out = []) {
197
+ for (const a of ts.attestations)
198
+ out.push({ attestation: a, msg: ts.msg, node: ts });
199
+ for (const { stamp } of ts.ops.values())
200
+ allAttestations(stamp, out);
201
+ return out;
202
+ }
203
+ function calendarAllowed(uri) {
204
+ try {
205
+ const u = new URL(uri);
206
+ return u.protocol === "https:" && ALLOWED_CALENDAR_HOSTS.has(u.hostname);
207
+ }
208
+ catch {
209
+ return false;
210
+ }
211
+ }
212
+ /** Submit a 32-byte digest to calendars. At least one calendar must answer. */
213
+ export async function stampDigest(digest, calendars = DEFAULT_CALENDARS, f = fetch) {
214
+ const ts = new Timestamp(digest);
215
+ const okCals = [];
216
+ const errors = [];
217
+ await Promise.all(calendars.map(async (cal) => {
218
+ try {
219
+ const res = await f(`${cal.replace(/\/$/, "")}/digest`, {
220
+ method: "POST",
221
+ headers: { Accept: "application/vnd.opentimestamps.v1", "Content-Type": "application/x-www-form-urlencoded" },
222
+ body: new Uint8Array(digest),
223
+ signal: AbortSignal.timeout(15000),
224
+ });
225
+ if (!res.ok)
226
+ throw new Error(`HTTP ${res.status}`);
227
+ const body = Buffer.from(await res.arrayBuffer());
228
+ const r = new Reader(body);
229
+ const part = readTimestamp(r, digest);
230
+ merge(ts, part);
231
+ okCals.push(cal);
232
+ }
233
+ catch (e) {
234
+ errors.push(`${cal}: ${e.message}`);
235
+ }
236
+ }));
237
+ if (okCals.length === 0)
238
+ throw new Error("OTS : aucun calendrier n'a répondu (" + errors.join("; ") + ").");
239
+ return { ts, calendars: okCals.sort(), errors };
240
+ }
241
+ /** Ask calendars for completed attestations. Returns true if something changed. */
242
+ export async function upgradeTimestamp(ts, f = fetch) {
243
+ let changed = false;
244
+ for (const { attestation, msg, node } of allAttestations(ts)) {
245
+ if (attestation.kind !== "pending" || !calendarAllowed(attestation.uri))
246
+ continue;
247
+ try {
248
+ const res = await f(`${attestation.uri.replace(/\/$/, "")}/timestamp/${msg.toString("hex")}`, {
249
+ headers: { Accept: "application/vnd.opentimestamps.v1" },
250
+ signal: AbortSignal.timeout(15000),
251
+ });
252
+ if (!res.ok)
253
+ continue;
254
+ const body = Buffer.from(await res.arrayBuffer());
255
+ const upgraded = readTimestamp(new Reader(body), msg);
256
+ if (allAttestations(upgraded).some((a) => a.attestation.kind === "bitcoin")) {
257
+ merge(node, upgraded);
258
+ node.attestations = node.attestations.filter((a) => !(a.kind === "pending" && a.uri === attestation.uri));
259
+ changed = true;
260
+ }
261
+ }
262
+ catch { /* still pending */ }
263
+ }
264
+ return changed;
265
+ }
266
+ const ESPLORA = ["https://blockstream.info/api", "https://mempool.space/api"];
267
+ /** Compare the attested message with the Bitcoin block header merkle root (via public explorers). */
268
+ export async function verifyBitcoinAttestation(height, msg, f = fetch) {
269
+ const expected = Buffer.from(msg).reverse().toString("hex");
270
+ for (const base of ESPLORA) {
271
+ try {
272
+ const h = await f(`${base}/block-height/${height}`, { signal: AbortSignal.timeout(15000) });
273
+ if (!h.ok)
274
+ continue;
275
+ const hash = (await h.text()).trim();
276
+ const b = await f(`${base}/block/${hash}`, { signal: AbortSignal.timeout(15000) });
277
+ if (!b.ok)
278
+ continue;
279
+ const block = (await b.json());
280
+ const ok = block.merkle_root === expected;
281
+ return {
282
+ height, ok,
283
+ block_time: block.timestamp ? new Date(block.timestamp * 1000).toISOString() : undefined,
284
+ detail: ok ? `Ancré dans le bloc Bitcoin ${height} (vérifié via ${new URL(base).hostname}).` : `Racine Merkle du bloc ${height} différente.`,
285
+ };
286
+ }
287
+ catch { /* try next explorer */ }
288
+ }
289
+ return { height, ok: false, detail: "Explorateurs Bitcoin injoignables : ancrage non vérifié." };
290
+ }
291
+ export async function otsStatus(ts, opts) {
292
+ const atts = allAttestations(ts);
293
+ const pending = atts.filter((a) => a.attestation.kind === "pending").map((a) => a.attestation.uri);
294
+ const btc = atts.filter((a) => a.attestation.kind === "bitcoin");
295
+ const base = { digest: ts.msg.toString("hex"), pending_calendars: [...new Set(pending)].sort() };
296
+ if (btc.length === 0) {
297
+ return { ...base, status: "pending", bitcoin: [], detail: "En attente de confirmation Bitcoin (normal pendant quelques heures)." };
298
+ }
299
+ if (!opts.online) {
300
+ const heights = btc.map((b) => b.attestation.height);
301
+ return { ...base, status: "unverified", bitcoin: heights.map((h) => ({ height: h, ok: false, detail: "Vérification hors ligne." })), detail: `Attestation Bitcoin présente (bloc ${heights.join(", ")}), non vérifiée hors ligne.` };
302
+ }
303
+ const checks = [];
304
+ for (const b of btc)
305
+ checks.push(await verifyBitcoinAttestation(b.attestation.height, b.msg, opts.f));
306
+ const good = checks.find((c) => c.ok);
307
+ if (good)
308
+ return { ...base, status: "confirmed", bitcoin: checks, detail: good.detail };
309
+ const unreachable = checks.every((c) => /injoignables/.test(c.detail));
310
+ return { ...base, status: unreachable ? "unverified" : "failed", bitcoin: checks, detail: checks.map((c) => c.detail).join(" ") };
311
+ }