@orangecheck/stamp-ots 0.1.0 → 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.
package/dist/index.mjs CHANGED
@@ -1,3 +1,7 @@
1
+ import { sha256 } from '@noble/hashes/sha2';
2
+ import { sha1, ripemd160 } from '@noble/hashes/legacy';
3
+ import { keccak_256 } from '@noble/hashes/sha3';
4
+
1
5
  // src/types.ts
2
6
  function toStampOts(p) {
3
7
  return {
@@ -126,12 +130,12 @@ function createCalendarClient(url, opts = {}) {
126
130
  const buf = await resp.arrayBuffer();
127
131
  return new Uint8Array(buf);
128
132
  },
129
- async fetchProof(digest, signal) {
130
- if (digest.byteLength !== 32) {
131
- throw new Error("OTS: digest must be exactly 32 bytes");
133
+ async fetchProof(commitment, signal) {
134
+ if (commitment.byteLength === 0 || commitment.byteLength > 64) {
135
+ throw new Error("OTS: commitment must be 1-64 bytes");
132
136
  }
133
137
  const ac = withTimeout(signal, timeoutMs);
134
- const resp = await fetchImpl(`${base}/timestamp/${hexEncode(digest)}`, {
138
+ const resp = await fetchImpl(`${base}/timestamp/${hexEncode(commitment)}`, {
135
139
  method: "GET",
136
140
  headers: { Accept: "application/vnd.opentimestamps.v1" },
137
141
  signal: ac.signal
@@ -200,71 +204,300 @@ async function submitToCalendars(idHex, opts = {}) {
200
204
  upgradedAt: null
201
205
  };
202
206
  }
203
-
204
- // src/upgrade.ts
205
- async function upgradeProof(current, idHex, opts) {
206
- if (current.status === "confirmed") return current;
207
- const digest = hexDecode(idHex);
208
- const clients = current.calendars.map(
209
- (url) => createCalendarClient(url, { fetch: opts.fetch, timeoutMs: opts.timeoutMs })
210
- );
211
- if (clients.length === 0) {
212
- throw new Error("upgradeProof: no calendars listed in current proof");
207
+ var HEADER_MAGIC = new Uint8Array([
208
+ 0,
209
+ 79,
210
+ 112,
211
+ 101,
212
+ 110,
213
+ 84,
214
+ 105,
215
+ 109,
216
+ 101,
217
+ 115,
218
+ 116,
219
+ 97,
220
+ 109,
221
+ 112,
222
+ 115,
223
+ 0,
224
+ 0,
225
+ 80,
226
+ 114,
227
+ 111,
228
+ 111,
229
+ 102,
230
+ 0,
231
+ 191,
232
+ 137,
233
+ 226,
234
+ 232,
235
+ 132,
236
+ 232,
237
+ 146,
238
+ 148
239
+ ]);
240
+ var TAG_BITCOIN = "0588960d73d71901";
241
+ var TAG_PENDING = "83dfe30d2ef90c8e";
242
+ var MAX_DEPTH = 256;
243
+ var MAX_MSG = 4096;
244
+ var Reader = class {
245
+ constructor(buf) {
246
+ this.buf = buf;
247
+ this.pos = 0;
213
248
  }
214
- const attempts = await Promise.allSettled(
215
- clients.map(async (c) => {
216
- const proof = await c.fetchProof(digest, opts.signal);
217
- if (!proof) return null;
218
- const anchor = await opts.parseAnchor(proof);
219
- return { url: c.url, proof, anchor };
220
- })
221
- );
222
- for (const r of attempts) {
223
- if (r.status !== "fulfilled" || r.value === null) continue;
224
- const { url, proof, anchor } = r.value;
225
- if (anchor) {
226
- return {
227
- status: "confirmed",
228
- proof: base64Encode(proof),
229
- calendars: uniqueFirst(current.calendars, url),
230
- blockHeight: anchor.blockHeight,
231
- blockHash: anchor.blockHash,
232
- upgradedAt: (/* @__PURE__ */ new Date()).toISOString().replace(/\.\d+Z$/, "Z")
233
- };
249
+ byte() {
250
+ if (this.pos >= this.buf.length) throw new Error("ots: unexpected end of proof");
251
+ return this.buf[this.pos++];
252
+ }
253
+ bytes(n) {
254
+ if (n < 0 || this.pos + n > this.buf.length) throw new Error("ots: unexpected end of proof");
255
+ const out = this.buf.subarray(this.pos, this.pos + n);
256
+ this.pos += n;
257
+ return out;
258
+ }
259
+ varuint() {
260
+ let value = 0;
261
+ let shift = 0;
262
+ for (; ; ) {
263
+ const b = this.byte();
264
+ value += (b & 127) * 2 ** shift;
265
+ if (!(b & 128)) return value;
266
+ shift += 7;
267
+ if (shift > 49) throw new Error("ots: varuint too large");
234
268
  }
235
269
  }
236
- let longest = null;
237
- for (const r of attempts) {
238
- if (r.status !== "fulfilled" || r.value === null) continue;
239
- if (!longest || r.value.proof.byteLength > longest.proof.byteLength) {
240
- longest = { url: r.value.url, proof: r.value.proof };
270
+ varbytes(max) {
271
+ const n = this.varuint();
272
+ if (n > max) throw new Error("ots: varbytes too long");
273
+ return this.bytes(n);
274
+ }
275
+ get done() {
276
+ return this.pos === this.buf.length;
277
+ }
278
+ };
279
+ var UNARY = {
280
+ 2: "sha1",
281
+ 3: "ripemd160",
282
+ 8: "sha256",
283
+ 103: "keccak256",
284
+ 242: "reverse",
285
+ 243: "hexlify"
286
+ };
287
+ function applyOp(op, msg) {
288
+ switch (op.kind) {
289
+ case "sha256":
290
+ return sha256(msg);
291
+ case "ripemd160":
292
+ return ripemd160(msg);
293
+ case "sha1":
294
+ return sha1(msg);
295
+ case "keccak256":
296
+ return keccak_256(msg);
297
+ case "reverse":
298
+ return new Uint8Array(msg).reverse();
299
+ case "hexlify":
300
+ return new TextEncoder().encode(hexEncode(msg));
301
+ case "append":
302
+ return concat(msg, op.arg);
303
+ case "prepend":
304
+ return concat(op.arg, msg);
305
+ }
306
+ }
307
+ function readOp(r, tag) {
308
+ const unary = UNARY[tag];
309
+ if (unary) return { kind: unary };
310
+ if (tag === 240) return { kind: "append", arg: r.varbytes(MAX_MSG) };
311
+ if (tag === 241) return { kind: "prepend", arg: r.varbytes(MAX_MSG) };
312
+ throw new Error(`ots: unknown op tag 0x${tag.toString(16)}`);
313
+ }
314
+ function readAttestation(r) {
315
+ const tag = hexEncode(r.bytes(8));
316
+ const payload = r.varbytes(8192);
317
+ const p = new Reader(payload);
318
+ if (tag === TAG_BITCOIN) return { kind: "bitcoin", height: p.varuint() };
319
+ if (tag === TAG_PENDING) return { kind: "pending", uri: new TextDecoder().decode(p.varbytes(1e3)) };
320
+ return { kind: "unknown", tag, payload };
321
+ }
322
+ function readTimestamp(r, msg, depth) {
323
+ if (depth > MAX_DEPTH) throw new Error("ots: proof too deep");
324
+ const node = { msg, attestations: [], ops: [] };
325
+ const item = (tag2) => {
326
+ if (tag2 === 0) {
327
+ node.attestations.push(readAttestation(r));
328
+ return;
241
329
  }
330
+ const op = readOp(r, tag2);
331
+ const next = applyOp(op, msg);
332
+ if (next.length > MAX_MSG) throw new Error("ots: message too long");
333
+ node.ops.push({ op, child: readTimestamp(r, next, depth + 1) });
334
+ };
335
+ let tag = r.byte();
336
+ while (tag === 255) {
337
+ item(r.byte());
338
+ tag = r.byte();
242
339
  }
243
- if (longest) {
244
- const currentBytes = base64Decode(current.proof);
245
- if (longest.proof.byteLength > currentBytes.byteLength) {
246
- return {
247
- status: "pending",
248
- proof: base64Encode(longest.proof),
249
- calendars: uniqueFirst(current.calendars, longest.url),
250
- blockHeight: null,
251
- blockHash: null,
252
- upgradedAt: null
253
- };
340
+ item(tag);
341
+ return node;
342
+ }
343
+ function parseTimestamp(bytes, digest) {
344
+ const r = new Reader(bytes);
345
+ const ts = readTimestamp(r, digest, 0);
346
+ if (!r.done) throw new Error("ots: trailing bytes after timestamp");
347
+ return ts;
348
+ }
349
+ function isDetached(bytes) {
350
+ return bytes.length > HEADER_MAGIC.length && bytesEqual(bytes.subarray(0, HEADER_MAGIC.length), HEADER_MAGIC);
351
+ }
352
+ function parseDetached(bytes) {
353
+ if (!isDetached(bytes)) throw new Error("ots: missing detached-file header");
354
+ const r = new Reader(bytes.subarray(HEADER_MAGIC.length));
355
+ const major = r.varuint();
356
+ if (major !== 1) throw new Error(`ots: unsupported file version ${major}`);
357
+ if (r.byte() !== 8) throw new Error("ots: only sha256 file digests are supported");
358
+ const digest = new Uint8Array(r.bytes(32));
359
+ const timestamp = readTimestamp(r, digest, 0);
360
+ if (!r.done) throw new Error("ots: trailing bytes after timestamp");
361
+ return { digest, timestamp };
362
+ }
363
+ function parseProof(bytes, digest) {
364
+ if (!isDetached(bytes)) return parseTimestamp(bytes, digest);
365
+ const d = parseDetached(bytes);
366
+ if (!bytesEqual(d.digest, digest)) throw new Error("ots: proof commits to a different digest");
367
+ return d.timestamp;
368
+ }
369
+ function attestations(ts) {
370
+ const out = [];
371
+ const walk = (n) => {
372
+ for (const a of n.attestations) out.push({ msg: n.msg, attestation: a });
373
+ for (const { child } of n.ops) walk(child);
374
+ };
375
+ walk(ts);
376
+ return out;
377
+ }
378
+ function bitcoinAnchors(ts) {
379
+ return attestations(ts).flatMap(
380
+ ({ msg, attestation }) => attestation.kind === "bitcoin" ? [{ blockHeight: attestation.height, merkleRoot: msg }] : []
381
+ ).sort((a, b) => a.blockHeight - b.blockHeight);
382
+ }
383
+ function pendingCommitments(ts) {
384
+ return attestations(ts).flatMap(
385
+ ({ msg, attestation }) => attestation.kind === "pending" ? [{ uri: attestation.uri, commitment: msg }] : []
386
+ );
387
+ }
388
+ function mergeAt(ts, upgrade) {
389
+ if (bytesEqual(ts.msg, upgrade.msg)) {
390
+ for (const a of upgrade.attestations) {
391
+ if (!ts.attestations.some((b) => attestationKey(b) === attestationKey(a))) ts.attestations.push(a);
254
392
  }
393
+ for (const { op, child } of upgrade.ops) {
394
+ const same = ts.ops.find((o) => opKey(o.op) === opKey(op));
395
+ if (same) mergeAt(same.child, child);
396
+ else ts.ops.push({ op, child });
397
+ }
398
+ return true;
255
399
  }
256
- return current;
400
+ return ts.ops.some(({ child }) => mergeAt(child, upgrade));
401
+ }
402
+ function writeVaruint(out, n) {
403
+ do {
404
+ let b = n % 128;
405
+ n = Math.floor(n / 128);
406
+ if (n > 0) b |= 128;
407
+ out.push(b);
408
+ } while (n > 0);
257
409
  }
258
- function uniqueFirst(arr, first) {
259
- const out = [first];
260
- for (const x of arr) if (x !== first && !out.includes(x)) out.push(x);
410
+ function writeVarbytes(out, bytes) {
411
+ writeVaruint(out, bytes.length);
412
+ out.push(...bytes);
413
+ }
414
+ var OP_TAG = {
415
+ sha1: 2,
416
+ ripemd160: 3,
417
+ sha256: 8,
418
+ keccak256: 103,
419
+ append: 240,
420
+ prepend: 241,
421
+ reverse: 242,
422
+ hexlify: 243
423
+ };
424
+ function writeAttestation(out, a) {
425
+ const payload = [];
426
+ let tag;
427
+ if (a.kind === "bitcoin") {
428
+ tag = TAG_BITCOIN;
429
+ writeVaruint(payload, a.height);
430
+ } else if (a.kind === "pending") {
431
+ tag = TAG_PENDING;
432
+ writeVarbytes(payload, new TextEncoder().encode(a.uri));
433
+ } else {
434
+ tag = a.tag;
435
+ payload.push(...a.payload);
436
+ }
437
+ out.push(0);
438
+ for (let i = 0; i < 16; i += 2) out.push(parseInt(tag.slice(i, i + 2), 16));
439
+ writeVarbytes(out, new Uint8Array(payload));
440
+ }
441
+ function writeTimestamp(out, ts) {
442
+ const items = [
443
+ ...ts.attestations.map((a) => () => writeAttestation(out, a)),
444
+ ...ts.ops.map(({ op, child }) => () => {
445
+ out.push(OP_TAG[op.kind]);
446
+ if (op.kind === "append" || op.kind === "prepend") writeVarbytes(out, op.arg);
447
+ writeTimestamp(out, child);
448
+ })
449
+ ];
450
+ if (items.length === 0) throw new Error("ots: cannot serialize an empty timestamp node");
451
+ items.forEach((write, i) => {
452
+ if (i < items.length - 1) out.push(255);
453
+ write();
454
+ });
455
+ }
456
+ function serializeTimestamp(ts) {
457
+ const out = [];
458
+ writeTimestamp(out, ts);
459
+ return new Uint8Array(out);
460
+ }
461
+ function attestationKey(a) {
462
+ if (a.kind === "bitcoin") return `b:${a.height}`;
463
+ if (a.kind === "pending") return `p:${a.uri}`;
464
+ return `u:${a.tag}:${hexEncode(a.payload)}`;
465
+ }
466
+ function opKey(op) {
467
+ return "arg" in op ? `${op.kind}:${hexEncode(op.arg)}` : op.kind;
468
+ }
469
+ function concat(a, b) {
470
+ const out = new Uint8Array(a.length + b.length);
471
+ out.set(a, 0);
472
+ out.set(b, a.length);
261
473
  return out;
262
474
  }
475
+ function bytesEqual(a, b) {
476
+ if (a.byteLength !== b.byteLength) return false;
477
+ for (let i = 0; i < a.byteLength; i++) if (a[i] !== b[i]) return false;
478
+ return true;
479
+ }
263
480
 
264
481
  // src/anchor.ts
482
+ async function walkOtsProof(input) {
483
+ try {
484
+ const anchors = bitcoinAnchors(parseProof(input.proofBytes, input.digest));
485
+ return anchors.find((a) => a.blockHeight === input.blockHeight) ?? anchors[0] ?? null;
486
+ } catch {
487
+ return null;
488
+ }
489
+ }
490
+ function blockHashOf(header) {
491
+ return hexEncode(sha256(sha256(header)).reverse());
492
+ }
265
493
  function makeAnchorVerifier(cfg) {
266
- return async (input) => {
267
- const walked = await cfg.walkProof({ proofBytes: input.proofBytes, digest: input.digest });
494
+ const walkProof = cfg.walkProof ?? walkOtsProof;
495
+ const verifier = async (input) => {
496
+ const walked = await walkProof({
497
+ proofBytes: input.proofBytes,
498
+ digest: input.digest,
499
+ blockHeight: input.blockHeight
500
+ });
268
501
  if (!walked) {
269
502
  return { ok: false, reason: "proof could not be walked to a Bitcoin commitment" };
270
503
  }
@@ -275,39 +508,100 @@ function makeAnchorVerifier(cfg) {
275
508
  };
276
509
  }
277
510
  const header = await cfg.headerSource.getHeaderAt(input.blockHeight);
278
- if (!header) {
511
+ if (!header || header.byteLength !== 80) {
279
512
  return { ok: false, reason: `no block header available at height ${input.blockHeight}` };
280
513
  }
281
- if (header.byteLength < 80) {
282
- return { ok: false, reason: "malformed Bitcoin header (too short)" };
514
+ if (blockHashOf(header) !== input.blockHash.toLowerCase()) {
515
+ return { ok: false, reason: "block header does not hash to the declared block hash" };
283
516
  }
284
- const headerMerkleLE = header.subarray(36, 68);
285
- const headerMerkleBE = new Uint8Array(headerMerkleLE).reverse();
286
- const matchesLE = bytesEqual(headerMerkleLE, walked.merkleRoot);
287
- const matchesBE = bytesEqual(headerMerkleBE, walked.merkleRoot);
288
- if (!matchesLE && !matchesBE) {
517
+ const headerMerkle = header.subarray(36, 68);
518
+ if (!bytesEqual(headerMerkle, walked.merkleRoot)) {
289
519
  return { ok: false, reason: "block header Merkle root does not match walked proof root" };
290
520
  }
291
- return { ok: true, merkleRoot: hexEncode(matchesBE ? headerMerkleBE : headerMerkleLE) };
521
+ return { ok: true, merkleRoot: hexEncode(headerMerkle) };
292
522
  };
293
- }
294
- function bytesEqual(a, b) {
295
- if (a.byteLength !== b.byteLength) return false;
296
- for (let i = 0; i < a.byteLength; i++) if (a[i] !== b[i]) return false;
297
- return true;
298
- }
299
- function adaptAnchorVerifier(verifier, digestLookup) {
300
- return async (proofB64, blockHeight, blockHash) => {
523
+ return async (proofB64, blockHeight, blockHash, envelopeId) => {
301
524
  const r = await verifier({
302
525
  proofBytes: base64Decode(proofB64),
303
- digest: digestLookup(blockHash),
526
+ digest: hexDecode(envelopeId),
304
527
  blockHeight,
305
528
  blockHash
306
529
  });
307
530
  return r.ok;
308
531
  };
309
532
  }
533
+ async function makeDefaultAnchorVerifier(opts) {
534
+ return makeAnchorVerifier({ headerSource: opts.headerSource });
535
+ }
536
+ function mempoolHeaderSource(opts = {}) {
537
+ const base = (opts.baseUrl ?? "https://mempool.space/api").replace(/\/+$/, "");
538
+ const fetchImpl = opts.fetch ?? globalThis.fetch.bind(globalThis);
539
+ return {
540
+ async getHeaderAt(height) {
541
+ const h = await fetchImpl(`${base}/block-height/${height}`);
542
+ if (!h.ok) return null;
543
+ const hash = (await h.text()).trim();
544
+ if (!/^[0-9a-f]{64}$/.test(hash)) return null;
545
+ const r = await fetchImpl(`${base}/block/${hash}/header`);
546
+ if (!r.ok) return null;
547
+ const hex = (await r.text()).trim();
548
+ return /^[0-9a-f]{160}$/.test(hex) ? hexDecode(hex) : null;
549
+ }
550
+ };
551
+ }
552
+
553
+ // src/upgrade.ts
554
+ var norm = (u) => u.replace(/\/+$/, "");
555
+ async function upgradeProof(current, idHex, opts) {
556
+ if (current.status === "confirmed") return current;
557
+ if (!opts.headerSource && !opts.parseAnchor) {
558
+ throw new Error("upgradeProof: pass headerSource or parseAnchor");
559
+ }
560
+ const before = base64Decode(current.proof);
561
+ const tree = parseProof(before, hexDecode(idHex));
562
+ const listed = new Set(current.calendars.map(norm));
563
+ const pending = pendingCommitments(tree).filter((p) => listed.has(norm(p.uri)));
564
+ if (pending.length === 0 && bitcoinAnchors(tree).length === 0) {
565
+ throw new Error("upgradeProof: proof has no pending attestation from a listed calendar");
566
+ }
567
+ const answered = [];
568
+ await Promise.allSettled(
569
+ pending.map(async ({ uri, commitment }) => {
570
+ const client = createCalendarClient(uri, { fetch: opts.fetch, timeoutMs: opts.timeoutMs });
571
+ const bytes = await client.fetchProof(commitment, opts.signal);
572
+ if (!bytes) return;
573
+ if (mergeAt(tree, parseTimestamp(bytes, commitment))) answered.push(norm(uri));
574
+ })
575
+ );
576
+ const merged = serializeTimestamp(tree);
577
+ const anchor = await resolveAnchor(merged, tree, opts);
578
+ const calendars = [...answered, ...current.calendars.filter((c) => !answered.includes(norm(c)))];
579
+ if (anchor) {
580
+ return {
581
+ status: "confirmed",
582
+ proof: base64Encode(merged),
583
+ calendars,
584
+ blockHeight: anchor.blockHeight,
585
+ blockHash: anchor.blockHash,
586
+ upgradedAt: (/* @__PURE__ */ new Date()).toISOString().replace(/\.\d+Z$/, "Z")
587
+ };
588
+ }
589
+ if (!bytesEqual(merged, before)) {
590
+ return { ...current, proof: base64Encode(merged), calendars };
591
+ }
592
+ return current;
593
+ }
594
+ async function resolveAnchor(merged, tree, opts) {
595
+ if (opts.parseAnchor) return opts.parseAnchor(merged);
596
+ for (const a of bitcoinAnchors(tree)) {
597
+ const header = await opts.headerSource.getHeaderAt(a.blockHeight);
598
+ if (header && header.byteLength === 80 && bytesEqual(header.subarray(36, 68), a.merkleRoot)) {
599
+ return { blockHeight: a.blockHeight, blockHash: blockHashOf(header) };
600
+ }
601
+ }
602
+ return null;
603
+ }
310
604
 
311
- export { DEFAULT_CALENDARS, adaptAnchorVerifier, base64Decode, base64Encode, createCalendarClient, fromStampOts, hexDecode, hexEncode, makeAnchorVerifier, submitToCalendars, toStampOts, upgradeProof };
605
+ export { DEFAULT_CALENDARS, attestations, base64Decode, base64Encode, bitcoinAnchors, blockHashOf, createCalendarClient, fromStampOts, hexDecode, hexEncode, makeAnchorVerifier, makeDefaultAnchorVerifier, mempoolHeaderSource, mergeAt, parseDetached, parseProof, parseTimestamp, pendingCommitments, serializeTimestamp, submitToCalendars, toStampOts, upgradeProof, walkOtsProof };
312
606
  //# sourceMappingURL=index.mjs.map
313
607
  //# sourceMappingURL=index.mjs.map