@conarium-ai/core 0.2.14 → 0.2.16

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.
@@ -1,8 +1,11 @@
1
1
  # Copy to .env and fill. Never commit the filled file.
2
- # The process refuses to start if TOKENS or BASE_URL is missing.
2
+ # The process refuses to start if TOKENS, BASE_URL, or SIGNING_KEY is missing.
3
3
 
4
4
  CONARIUM_ANCHOR_TOKENS=./anchor.tokens.json
5
5
  CONARIUM_ANCHOR_BASE_URL=https://anchor.example.invalid
6
+ CONARIUM_ANCHOR_SIGNING_KEY=./anchor-ed25519.pem
7
+ # Optional if <pem>.keyid exists next to the private key.
8
+ # CONARIUM_ANCHOR_KEY_ID=verax-2026-08
6
9
  CONARIUM_ANCHOR_STORE=./anchor-store.jsonl
7
10
  CONARIUM_ANCHOR_HOST=127.0.0.1
8
11
  CONARIUM_ANCHOR_PORT=8797
@@ -1,5 +1,12 @@
1
+ import { type CountersignSig } from './anchor-sign.js';
2
+ import type { SigningKey } from './keys.js';
3
+ export type AnchorRecordType = 'submit' | 'upgrade' | 'stamp';
1
4
  export interface AnchorRecord {
5
+ type: AnchorRecordType;
2
6
  id: string;
7
+ /** Customer-submitted digest (`sha256:…`). Public views expose this as `digest`. */
8
+ digest: string;
9
+ /** Entry hash — same rule as audit-hash.ts (`hash`/`sig`/`anchor` excluded). */
3
10
  hash: string;
4
11
  owner: string;
5
12
  log: 'opentimestamps';
@@ -8,6 +15,13 @@ export interface AnchorRecord {
8
15
  bitcoinBlock?: number;
9
16
  submittedAt: string;
10
17
  upgradedAt?: string;
18
+ seq: number;
19
+ prevHash: string;
20
+ /** Set on `type: 'upgrade'` — the submit/stamp seq this row confirms. */
21
+ upgradesSeq?: number;
22
+ /** Set on `type: 'stamp'` — the log seq whose entry hash was sent to calendars. */
23
+ stampedSeq?: number;
24
+ sig: CountersignSig;
11
25
  }
12
26
  export interface AnchorServiceOptions {
13
27
  /** JSONL store. Append-only: an anchoring log that can be rewritten is not one. */
@@ -16,6 +30,10 @@ export interface AnchorServiceOptions {
16
30
  tokens: Map<string, string>;
17
31
  /** Public base URL, used to build the permanent verification address. */
18
32
  publicBaseUrl: string;
33
+ /** Required. A countersign service that can start without a key is not one. */
34
+ signingKey: SigningKey;
35
+ /** Override the derived public PEM (tests). Still refused if it looks private. */
36
+ publicPem?: string;
19
37
  submitsPerMinute?: number;
20
38
  /** Injected in tests so the suite never touches a calendar server. */
21
39
  stamp?: (digest: Buffer) => Promise<string>;
@@ -25,8 +43,33 @@ export interface AnchorServiceOptions {
25
43
  ots?: string;
26
44
  }>;
27
45
  }
28
- /** Reads every record. The store is small by design — one line per anchor. */
46
+ /** Reads every record. Does not validate the chain — use readLiveStore. */
29
47
  export declare function readStore(path: string): AnchorRecord[];
48
+ export declare function validateAnchorLog(rows: AnchorRecord[]): void;
49
+ export declare function readLiveStore(path: string): AnchorRecord[];
50
+ export interface InclusionLink {
51
+ seq: number;
52
+ hash: string;
53
+ prevHash: string;
54
+ }
55
+ export interface InclusionProof {
56
+ seq: number;
57
+ hash: string;
58
+ prevHash: string;
59
+ head: {
60
+ seq: number;
61
+ hash: string;
62
+ state: 'pending' | 'bitcoin';
63
+ bitcoinBlock?: number;
64
+ };
65
+ path: InclusionLink[];
66
+ }
67
+ export declare function buildInclusionProof(rows: AnchorRecord[], target: AnchorRecord): InclusionProof;
68
+ export declare function verifyInclusionProof(record: {
69
+ seq: number;
70
+ hash: string;
71
+ prevHash: string;
72
+ }, proof: InclusionProof): boolean;
30
73
  export declare function loadTokensFile(path: string): Map<string, string>;
31
74
  export declare function createAnchorService(opts: AnchorServiceOptions): {
32
75
  app: import("express-serve-static-core").Express;
@@ -34,6 +77,10 @@ export declare function createAnchorService(opts: AnchorServiceOptions): {
34
77
  checked: number;
35
78
  upgraded: number;
36
79
  }>;
80
+ runStamp: () => Promise<{
81
+ attempted: number;
82
+ stamped: number;
83
+ }>;
37
84
  readStore: () => AnchorRecord[];
38
85
  };
39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AA;CAAE,EACvD,KAAK,EAAE,cAAc,GACpB,OAAO,CAaT;AA+BD,wBAAgB,cAAc,CAAC,IAAI,EAAE,MAAM,GAAG,GAAG,CAAC,MAAM,EAAE,MAAM,CAAC,CAUhE;AAaD,wBAAgB,mBAAmB,CAAC,IAAI,EAAE,oBAAoB;;sBAmP/B,OAAO,CAAC;QAAE,OAAO,EAAE,MAAM,CAAC;QAAC,QAAQ,EAAE,MAAM,CAAA;KAAE,CAAC;oBAlChD,OAAO,CAAC;QAAE,SAAS,EAAE,MAAM,CAAC;QAAC,OAAO,EAAE,MAAM,CAAA;KAAE,CAAC;;EA4E3E"}
@@ -1,28 +1,33 @@
1
1
  /**
2
- * Hosted anchoring endpoint.
2
+ * Hosted anchoring + countersign endpoint.
3
3
  *
4
- * What it does: takes a hash, submits it to the OpenTimestamps calendars, keeps
5
- * the resulting proof, and serves it forever at a stable URL. A background pass
6
- * upgrades each proof from `pending` to a Bitcoin block height once the block
7
- * lands.
4
+ * What it does: takes a hash, countersigns the stored record with this
5
+ * process's Ed25519 key, submits the hash to the OpenTimestamps calendars,
6
+ * keeps the proof, and serves both forever at a stable URL. A background pass
7
+ * stamps the log head off the request path, and upgrades that stamp from
8
+ * `pending` to a Bitcoin block height by appending a new row — the original
9
+ * line is never rewritten.
8
10
  *
9
11
  * What it is NOT — and this must never be blurred in the copy: Conarium is not
10
- * the timestamp authority. The calendars and Bitcoin are. This service is
11
- * retention, a permanent public address, and the upgrade job nobody remembers
12
- * to run. It sells convenience and durability, never trust.
12
+ * the timestamp authority. The calendars and Bitcoin are. The signature is
13
+ * ours; the time is not. An anchoring service you have to trust for the stamp
14
+ * would defeat the point of anchoring. The countersign is a named claim that
15
+ * we saw this hash and wrote this record — nothing more.
13
16
  *
14
- * The proof is served raw at `/anchor/:id/ots`, so a third party can verify with
15
- * the reference OpenTimestamps client and ignore this service entirely. An
16
- * anchoring service you have to trust would defeat the point of anchoring.
17
+ * The proof is served raw at `/anchor/:id/ots`, so a third party can verify the
18
+ * stamp with the reference OpenTimestamps client and ignore this service. The
19
+ * public key is at `/anchor/key.pem`. The log head is at `/anchor/log/head`.
17
20
  *
18
21
  * The code is MIT like the rest — self-host it if you prefer. What is sold is
19
- * someone else keeping it alive.
22
+ * the key and someone else keeping the log alive.
20
23
  */
21
24
  import express from 'express';
22
- import { randomBytes, timingSafeEqual } from 'crypto';
23
- import { appendFileSync, existsSync, mkdirSync, readFileSync, writeFileSync } from 'fs';
25
+ import { createPublicKey, randomBytes, timingSafeEqual } from 'crypto';
26
+ import { appendFileSync, existsSync, mkdirSync, readFileSync } from 'fs';
24
27
  import { dirname } from 'path';
25
28
  import { hashPrefixToBuffer } from './anchor.js';
29
+ import { computeEntryHash, GENESIS_HASH } from './audit-hash.js';
30
+ import { isServablePublicPem, signAnchorRecord } from './anchor-sign.js';
26
31
  import { stampHash, upgradeProof } from './ots/client.js';
27
32
  // Matches conarium-stamp. One slow calendar out of four is normal; 20s was not
28
33
  // enough in practice and produced a 502 for a submission that would have landed.
@@ -44,7 +49,7 @@ async function defaultUpgrade(otsBase64) {
44
49
  ots: up.otsBytes.toString('base64'),
45
50
  };
46
51
  }
47
- /** Reads every record. The store is small by design — one line per anchor. */
52
+ /** Reads every record. Does not validate the chain — use readLiveStore. */
48
53
  export function readStore(path) {
49
54
  if (!existsSync(path))
50
55
  return [];
@@ -53,12 +58,99 @@ export function readStore(path) {
53
58
  return [];
54
59
  return raw.split('\n').filter(Boolean).map((l) => JSON.parse(l));
55
60
  }
56
- /**
57
- * An upgrade is the one legitimate reason to rewrite a line, so the whole file
58
- * is rewritten rather than appended to. Everything else is append-only.
59
- */
60
- function rewriteStore(path, rows) {
61
- writeFileSync(path, rows.map((r) => JSON.stringify(r)).join('\n') + (rows.length ? '\n' : ''));
61
+ export function validateAnchorLog(rows) {
62
+ let previous = GENESIS_HASH;
63
+ for (let i = 0; i < rows.length; i++) {
64
+ const row = rows[i];
65
+ if (!Number.isInteger(row.seq) || row.seq !== i + 1) {
66
+ throw new Error(`anchor log corrupt: seq at index ${i}`);
67
+ }
68
+ if (row.prevHash !== previous) {
69
+ throw new Error('anchor log corrupt: prevHash mismatch');
70
+ }
71
+ if (!row.hash) {
72
+ throw new Error('anchor log corrupt: missing entry hash');
73
+ }
74
+ const expected = computeEntryHash(row);
75
+ if (row.hash !== expected) {
76
+ throw new Error('anchor log corrupt: entry hash mismatch');
77
+ }
78
+ previous = row.hash;
79
+ }
80
+ }
81
+ export function readLiveStore(path) {
82
+ const rows = readStore(path);
83
+ validateAnchorLog(rows);
84
+ return rows;
85
+ }
86
+ export function buildInclusionProof(rows, target) {
87
+ if (!Number.isInteger(target.seq) || target.seq < 1 || target.seq > rows.length) {
88
+ throw new Error('cannot build inclusion proof: record not in log');
89
+ }
90
+ const at = rows[target.seq - 1];
91
+ if (at.hash !== target.hash || at.seq !== target.seq) {
92
+ throw new Error('cannot build inclusion proof: record moved');
93
+ }
94
+ const head = rows[rows.length - 1];
95
+ return {
96
+ seq: target.seq,
97
+ hash: target.hash,
98
+ prevHash: target.prevHash,
99
+ head: {
100
+ seq: head.seq,
101
+ hash: head.hash,
102
+ state: head.state,
103
+ ...(head.bitcoinBlock !== undefined ? { bitcoinBlock: head.bitcoinBlock } : {}),
104
+ },
105
+ path: rows.slice(target.seq - 1).map((r) => ({
106
+ seq: r.seq,
107
+ hash: r.hash,
108
+ prevHash: r.prevHash,
109
+ })),
110
+ };
111
+ }
112
+ export function verifyInclusionProof(record, proof) {
113
+ if (proof.seq !== record.seq || proof.hash !== record.hash || proof.prevHash !== record.prevHash) {
114
+ return false;
115
+ }
116
+ if (proof.path.length === 0)
117
+ return false;
118
+ if (proof.path[0].hash !== record.hash || proof.path[0].seq !== record.seq)
119
+ return false;
120
+ let prev = record.prevHash;
121
+ for (const step of proof.path) {
122
+ if (step.prevHash !== prev)
123
+ return false;
124
+ prev = step.hash;
125
+ }
126
+ const last = proof.path[proof.path.length - 1];
127
+ return last.hash === proof.head.hash && last.seq === proof.head.seq;
128
+ }
129
+ function nextLink(rows) {
130
+ if (rows.length === 0)
131
+ return { seq: 1, prevHash: GENESIS_HASH };
132
+ const last = rows[rows.length - 1];
133
+ return { seq: last.seq + 1, prevHash: last.hash };
134
+ }
135
+ function sealRecord(unsigned, key) {
136
+ const hashed = {
137
+ ...unsigned,
138
+ hash: computeEntryHash(unsigned),
139
+ };
140
+ return signAnchorRecord(hashed, key);
141
+ }
142
+ function findSubmit(rows, id) {
143
+ return rows.find((r) => r.id === id && r.type === 'submit');
144
+ }
145
+ function latestView(rows, submit) {
146
+ const upgrades = rows.filter((r) => r.type === 'upgrade' && r.upgradesSeq === submit.seq);
147
+ if (upgrades.length === 0)
148
+ return submit;
149
+ const last = upgrades[upgrades.length - 1];
150
+ return { ...last, id: submit.id, digest: submit.digest };
151
+ }
152
+ function alreadyUpgraded(rows, seq) {
153
+ return rows.some((r) => r.type === 'upgrade' && r.upgradesSeq === seq);
62
154
  }
63
155
  export function loadTokensFile(path) {
64
156
  const tokens = new Map();
@@ -84,10 +176,15 @@ function resolveOwner(tokens, presented) {
84
176
  return found;
85
177
  }
86
178
  export function createAnchorService(opts) {
179
+ if (!opts.signingKey) {
180
+ throw new Error('createAnchorService: signingKey is required — a countersign service without a key is not one');
181
+ }
87
182
  const stamp = opts.stamp ?? defaultStamp;
88
183
  const upgrade = opts.upgrade ?? defaultUpgrade;
89
184
  const perMinute = opts.submitsPerMinute ?? 60;
90
185
  const base = opts.publicBaseUrl.replace(/\/+$/, '');
186
+ const publicPem = opts.publicPem ??
187
+ createPublicKey(opts.signingKey.privateKey).export({ type: 'spki', format: 'pem' }).toString();
91
188
  mkdirSync(dirname(opts.storePath), { recursive: true });
92
189
  const buckets = new Map();
93
190
  function overLimit(owner) {
@@ -116,17 +213,61 @@ export function createAnchorService(opts) {
116
213
  }
117
214
  return owner;
118
215
  }
216
+ function live(res) {
217
+ try {
218
+ return readLiveStore(opts.storePath);
219
+ }
220
+ catch {
221
+ res.status(503).json({ error: 'anchor log corrupt' });
222
+ return null;
223
+ }
224
+ }
119
225
  app.get('/healthz', (_req, res) => {
120
- res.json({ ok: true, service: 'conarium-anchor', anchors: readStore(opts.storePath).length });
226
+ const rows = live(res);
227
+ if (!rows)
228
+ return;
229
+ res.json({
230
+ ok: true,
231
+ service: 'conarium-anchor',
232
+ anchors: rows.filter((r) => r.type === 'submit').length,
233
+ });
234
+ });
235
+ // Registered before /anchor/:id so these paths are never treated as an id.
236
+ app.get('/anchor/key.pem', (_req, res) => {
237
+ if (!isServablePublicPem(publicPem)) {
238
+ res.status(403).type('text/plain').send('refusing to serve a private key');
239
+ return;
240
+ }
241
+ res.type('application/x-pem-file').send(publicPem);
242
+ });
243
+ app.get('/anchor/key.pem.keyid', (_req, res) => {
244
+ res.type('text/plain').send(opts.signingKey.keyId + '\n');
245
+ });
246
+ app.get('/anchor/log/head', (_req, res) => {
247
+ const rows = live(res);
248
+ if (!rows)
249
+ return;
250
+ if (rows.length === 0) {
251
+ res.json({ seq: 0, hash: GENESIS_HASH, prevHash: GENESIS_HASH, empty: true });
252
+ return;
253
+ }
254
+ const head = rows[rows.length - 1];
255
+ res.json({
256
+ seq: head.seq,
257
+ hash: head.hash,
258
+ prevHash: head.prevHash,
259
+ type: head.type,
260
+ state: head.state,
261
+ ...(head.bitcoinBlock !== undefined ? { bitcoinBlock: head.bitcoinBlock } : {}),
262
+ });
121
263
  });
122
264
  app.post('/anchor', async (req, res) => {
123
265
  const owner = auth(req, res);
124
266
  if (!owner)
125
267
  return;
126
268
  const hash = typeof req.body?.hash === 'string' ? req.body.hash : '';
127
- let digest;
128
269
  try {
129
- digest = hashPrefixToBuffer(hash);
270
+ hashPrefixToBuffer(hash);
130
271
  }
131
272
  catch (err) {
132
273
  res.status(400).json({ error: err.message });
@@ -136,56 +277,84 @@ export function createAnchorService(opts) {
136
277
  res.status(429).json({ error: 'rate limit exceeded', retryAfterSeconds: 60 });
137
278
  return;
138
279
  }
280
+ const rows = live(res);
281
+ if (!rows)
282
+ return;
139
283
  // Same content, same owner, same answer. Re-anchoring an identical hash
140
284
  // wastes a calendar submission and produces a second id for one fact.
141
- const existing = readStore(opts.storePath).find((r) => r.hash === hash && r.owner === owner);
285
+ const existing = rows.find((r) => r.type === 'submit' && r.digest === hash && r.owner === owner);
142
286
  if (existing) {
143
- res.status(200).json({ ...publicView(existing, base), deduplicated: true });
144
- return;
145
- }
146
- let ots;
147
- try {
148
- ots = await stamp(digest);
149
- }
150
- catch (err) {
151
- // Fail loudly. A silent 200 here would mean the customer believes their
152
- // chain is anchored when nothing was submitted.
153
- res.status(502).json({ error: `calendar submission failed: ${err.message}` });
287
+ res.status(200).json({
288
+ ...publicView(latestView(rows, existing), base, rows, existing),
289
+ countersign: existing,
290
+ deduplicated: true,
291
+ });
154
292
  return;
155
293
  }
156
- const record = {
294
+ // Stamp is off the request path (C5). A slow calendar must not lock accept.
295
+ const link = nextLink(rows);
296
+ const record = sealRecord({
297
+ type: 'submit',
157
298
  id: randomBytes(9).toString('base64url'),
158
- hash,
299
+ digest: hash,
159
300
  owner,
160
301
  log: 'opentimestamps',
161
- ots,
302
+ ots: '',
162
303
  state: 'pending',
163
304
  submittedAt: new Date().toISOString(),
164
- };
305
+ seq: link.seq,
306
+ prevHash: link.prevHash,
307
+ }, opts.signingKey);
165
308
  appendFileSync(opts.storePath, JSON.stringify(record) + '\n');
166
- res.status(201).json(publicView(record, base));
309
+ res.status(201).json({ ...publicView(record, base, [...rows, record]), countersign: record });
167
310
  });
168
311
  app.get('/anchor/:id', (req, res) => {
169
- const record = readStore(opts.storePath).find((r) => r.id === req.params.id);
170
- if (!record) {
312
+ const rows = live(res);
313
+ if (!rows)
314
+ return;
315
+ const submit = findSubmit(rows, req.params.id);
316
+ if (!submit) {
171
317
  res.status(404).json({ error: 'no such anchor' });
172
318
  return;
173
319
  }
320
+ const record = latestView(rows, submit);
174
321
  // Public on purpose: a verification URL only a token holder can open is not
175
322
  // a verification URL. It carries a hash and a proof, never content.
176
323
  res.setHeader('Vary', 'Accept');
177
- if (req.accepts(['json', 'html']) === 'html') {
178
- res.type('html').send(humanPage(record, base));
179
- return;
324
+ try {
325
+ if (req.accepts(['json', 'html']) === 'html') {
326
+ res.type('html').send(humanPage(record, base, rows, submit));
327
+ return;
328
+ }
329
+ res.json(publicView(record, base, rows, submit));
330
+ }
331
+ catch (err) {
332
+ // Only an actual proof failure may be reported as one. This catch used to
333
+ // label every error "cannot build inclusion proof", so a rendering bug
334
+ // sent whoever was debugging it to the log instead of to the renderer.
335
+ const msg = err instanceof Error ? err.message : String(err);
336
+ if (msg.startsWith('cannot build inclusion proof')) {
337
+ res.status(503).json({ error: 'cannot build inclusion proof' });
338
+ return;
339
+ }
340
+ res.status(500).json({ error: 'internal error while rendering this record' });
180
341
  }
181
- res.json(publicView(record, base));
182
342
  });
183
343
  app.get('/anchor/:id/ots', (req, res) => {
184
- const record = readStore(opts.storePath).find((r) => r.id === req.params.id);
185
- if (!record) {
344
+ const rows = live(res);
345
+ if (!rows)
346
+ return;
347
+ const submit = findSubmit(rows, req.params.id);
348
+ if (!submit) {
186
349
  res.status(404).json({ error: 'no such anchor' });
187
350
  return;
188
351
  }
352
+ const stampRow = rows.find((r) => r.type === 'stamp' && (r.stampedSeq ?? 0) >= submit.seq);
353
+ if (!stampRow || !stampRow.ots) {
354
+ res.status(404).json({ error: 'not yet stamped — wait for the next head stamp' });
355
+ return;
356
+ }
357
+ const record = latestView(rows, stampRow);
189
358
  res.type('application/octet-stream').send(Buffer.from(record.ots, 'base64'));
190
359
  });
191
360
  /** Upgrade pass. Idempotent, safe to run from cron as often as you like. */
@@ -193,25 +362,82 @@ export function createAnchorService(opts) {
193
362
  const owner = auth(req, res);
194
363
  if (!owner)
195
364
  return;
196
- const result = await runUpgrade();
197
- res.json(result);
365
+ try {
366
+ const result = await runUpgrade();
367
+ res.json(result);
368
+ }
369
+ catch {
370
+ res.status(503).json({ error: 'anchor log corrupt' });
371
+ }
198
372
  });
373
+ async function runStamp() {
374
+ const rows = readLiveStore(opts.storePath);
375
+ if (rows.length === 0)
376
+ return { attempted: 0, stamped: 0 };
377
+ const head = rows[rows.length - 1];
378
+ if (head.type === 'stamp')
379
+ return { attempted: 0, stamped: 0 };
380
+ if (rows.some((r) => r.type === 'stamp' && r.stampedSeq === head.seq)) {
381
+ return { attempted: 0, stamped: 0 };
382
+ }
383
+ try {
384
+ const ots = await stamp(hashPrefixToBuffer(`sha256:${head.hash}`));
385
+ const link = nextLink(rows);
386
+ const next = sealRecord({
387
+ type: 'stamp',
388
+ id: randomBytes(9).toString('base64url'),
389
+ digest: `sha256:${head.hash}`,
390
+ owner: 'conarium',
391
+ log: 'opentimestamps',
392
+ ots,
393
+ state: 'pending',
394
+ submittedAt: new Date().toISOString(),
395
+ seq: link.seq,
396
+ prevHash: link.prevHash,
397
+ stampedSeq: head.seq,
398
+ }, opts.signingKey);
399
+ appendFileSync(opts.storePath, JSON.stringify(next) + '\n');
400
+ return { attempted: 1, stamped: 1 };
401
+ }
402
+ catch {
403
+ return { attempted: 1, stamped: 0 };
404
+ }
405
+ }
199
406
  async function runUpgrade() {
200
- const rows = readStore(opts.storePath);
407
+ const rows = readLiveStore(opts.storePath);
201
408
  let upgraded = 0;
202
409
  let checked = 0;
203
410
  for (const row of rows) {
204
- if (row.state !== 'pending')
411
+ if (row.type !== 'stamp' || row.state !== 'pending')
412
+ continue;
413
+ if (alreadyUpgraded(rows, row.seq))
414
+ continue;
415
+ if (!row.ots)
205
416
  continue;
206
417
  checked += 1;
207
418
  try {
208
419
  const out = await upgrade(row.ots);
209
420
  if (out.upgraded) {
210
- row.state = 'bitcoin';
211
- row.ots = out.ots ?? row.ots;
421
+ const link = nextLink(rows);
422
+ const unsigned = {
423
+ type: 'upgrade',
424
+ id: randomBytes(9).toString('base64url'),
425
+ digest: row.digest,
426
+ owner: row.owner,
427
+ log: row.log,
428
+ ots: out.ots ?? row.ots,
429
+ state: 'bitcoin',
430
+ submittedAt: row.submittedAt,
431
+ upgradedAt: new Date().toISOString(),
432
+ seq: link.seq,
433
+ prevHash: link.prevHash,
434
+ upgradesSeq: row.seq,
435
+ };
212
436
  if (typeof out.block === 'number')
213
- row.bitcoinBlock = out.block;
214
- row.upgradedAt = new Date().toISOString();
437
+ unsigned.bitcoinBlock = out.block;
438
+ const next = sealRecord(unsigned, opts.signingKey);
439
+ appendFileSync(opts.storePath, JSON.stringify(next) + '\n');
440
+ rows.push(next);
215
441
  upgraded += 1;
216
442
  }
217
443
  }
@@ -220,21 +446,31 @@ export function createAnchorService(opts) {
220
446
  // It stays pending and the next pass tries again.
221
447
  }
222
448
  }
223
- if (upgraded)
224
- rewriteStore(opts.storePath, rows);
225
449
  return { checked, upgraded };
226
450
  }
227
- return { app, runUpgrade, readStore: () => readStore(opts.storePath) };
451
+ return { app, runUpgrade, runStamp, readStore: () => readStore(opts.storePath) };
228
452
  }
229
- function publicView(r, base) {
453
+ function publicView(r, base, rows, target) {
454
+ const inclusion = rows ? buildInclusionProof(rows, target ?? r) : undefined;
230
455
  return {
231
456
  id: r.id,
232
- hash: r.hash,
457
+ // `digest` is what the customer submitted; `chainHash` is this record's link
458
+ // in our log. Both used to be reachable as "hash" in one document — the
459
+ // top-level field held the customer digest while inclusion.hash held the
460
+ // chain hash, so the same name carried two different values next to a
461
+ // prevHash that chains only one of them. In an evidence product that
462
+ // ambiguity is not a style question.
463
+ digest: r.digest,
464
+ chainHash: r.hash,
233
465
  log: r.log,
234
466
  state: r.state,
467
+ seq: r.seq,
468
+ prevHash: r.prevHash,
235
469
  ...(r.bitcoinBlock !== undefined ? { bitcoinBlock: r.bitcoinBlock } : {}),
236
470
  submittedAt: r.submittedAt,
237
471
  ...(r.upgradedAt ? { upgradedAt: r.upgradedAt } : {}),
472
+ sig: r.sig,
473
+ ...(inclusion ? { inclusion } : {}),
238
474
  verify: `${base}/anchor/${r.id}/ots`,
239
475
  claim: r.state === 'bitcoin'
240
476
  ? 'This hash existed no later than the Bitcoin block below. Conarium is not the time source — the OpenTimestamps calendars and Bitcoin are, and the proof above can be checked without us.'
@@ -244,16 +480,24 @@ function publicView(r, base) {
244
480
  function esc(s) {
245
481
  return s.replace(/[&<>"]/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;' })[c]);
246
482
  }
247
- function humanPage(r, base) {
248
- const v = publicView(r, base);
483
+ function humanPage(r, base, rows, target) {
484
+ const v = publicView(r, base, rows, target);
485
+ const proof = v.inclusion;
486
+ const incl = proof
487
+ ? `<tr><td style="padding:.3rem 1rem .3rem 0;opacity:.7">inclusion</td><td><code>seq ${proof.seq} → head ${proof.head.seq} (${esc(proof.head.state)})</code></td></tr>`
488
+ : '';
249
489
  return `<!doctype html><meta charset="utf-8"><title>Conarium anchor ${esc(r.id)}</title>
250
490
  <body style="font:15px/1.6 system-ui,sans-serif;max-width:44rem;margin:3rem auto;padding:0 1rem">
251
491
  <h1 style="font-size:1.3rem">Anchor ${esc(r.id)}</h1>
252
492
  <table style="border-collapse:collapse">
253
- <tr><td style="padding:.3rem 1rem .3rem 0;opacity:.7">hash</td><td><code>${esc(r.hash)}</code></td></tr>
493
+ <tr><td style="padding:.3rem 1rem .3rem 0;opacity:.7">submitted digest</td><td><code>${esc(v.digest)}</code></td></tr>
494
+ <tr><td style="padding:.3rem 1rem .3rem 0;opacity:.7">chain hash</td><td><code>${esc(v.chainHash)}</code></td></tr>
495
+ <tr><td style="padding:.3rem 1rem .3rem 0;opacity:.7">seq</td><td><code>${r.seq}</code></td></tr>
254
496
  <tr><td style="padding:.3rem 1rem .3rem 0;opacity:.7">state</td><td><code>${esc(r.state)}</code></td></tr>
255
497
  ${r.bitcoinBlock !== undefined ? `<tr><td style="padding:.3rem 1rem .3rem 0;opacity:.7">bitcoin block</td><td><code>${r.bitcoinBlock}</code></td></tr>` : ''}
256
498
  <tr><td style="padding:.3rem 1rem .3rem 0;opacity:.7">submitted</td><td><code>${esc(r.submittedAt)}</code></td></tr>
499
+ <tr><td style="padding:.3rem 1rem .3rem 0;opacity:.7">countersign</td><td><code>Ed25519 ${esc(r.sig.keyId)}</code></td></tr>
500
+ ${incl}
257
501
  </table>
258
502
  <p>${esc(v.claim)}</p>
259
503
  <p>Raw proof: <a href="${esc(v.verify)}">${esc(v.verify)}</a> — verify it with the reference