-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrandom.html
More file actions
444 lines (418 loc) · 30.5 KB
/
Copy pathrandom.html
File metadata and controls
444 lines (418 loc) · 30.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>bitcoin-kernel - verify a block live in your browser</title>
<meta name="description" content="Fetch any Bitcoin block by height and verify its proof of work, merkle root and structure live in your browser. No server, no bundle, the engine runs on your device.">
<meta property="og:title" content="bitcoin-kernel - verify a block">
<meta property="og:description" content="Fetch a random Bitcoin block and verify its proof of work, merkle root and structure, live in your browser.">
<meta property="og:type" content="website">
<meta property="og:url" content="https://bitcoin-kernel.com/random.html">
<meta property="og:image" content="https://bitcoin-kernel.com/og.png?v=4">
<meta property="og:image:width" content="1200">
<meta property="og:image:height" content="630">
<meta name="twitter:card" content="summary_large_image">
<meta name="twitter:title" content="bitcoin-kernel - verify a block">
<meta name="twitter:description" content="Fetch a Bitcoin block and verify its proof of work, merkle root and structure, live in your browser.">
<meta name="twitter:image" content="https://bitcoin-kernel.com/og.png?v=4">
<style>
:root{--bg:#fff;--fg:#16181d;--mut:#5b6470;--bd:#e6e8eb;--pan:#fafbfc;--ac:#e8830c;--ac2:#0969da;--good:#1a7f37;--bad:#cf222e;--mono:ui-monospace,SFMono-Regular,Menlo,Consolas,monospace}
*{box-sizing:border-box}body{margin:0;background:var(--bg);color:var(--fg);font:16px/1.6 system-ui,-apple-system,"Segoe UI",sans-serif;-webkit-font-smoothing:antialiased}
a{color:var(--ac2);text-decoration:none}a:hover{text-decoration:underline}
.wrap{max-width:760px;margin:0 auto;padding:0 1.5rem}
nav{border-bottom:1px solid var(--bd)}nav .wrap{display:flex;align-items:center;gap:1.3rem;height:56px;max-width:940px}
nav .brand{font-weight:700;letter-spacing:-.3px;margin-right:auto;color:var(--fg);font-size:1rem;text-decoration:none}nav .brand b{color:var(--ac)}
nav a{color:var(--mut);font-size:.9rem;font-weight:500}nav a.on{color:var(--fg)}
header.hero{padding:2.4rem 0 1rem;text-align:center}
h1{font-size:2.1rem;line-height:1.08;letter-spacing:-1px;margin:0;font-weight:800}
.sub{font-size:1.05rem;color:#37414d;margin:.8rem auto 0;max-width:34rem}
.controls{display:flex;flex-wrap:wrap;gap:.6rem;justify-content:center;align-items:center;margin:1.4rem 0 0}
button{font:inherit;font-weight:600;cursor:pointer;border:1px solid var(--bd);background:#fff;border-radius:10px;padding:.6rem 1.1rem;transition:border-color .12s,background .12s}
button:hover{border-color:var(--ac)}button.primary{background:var(--ac);color:#fff;border-color:var(--ac)}button.primary:hover{background:#d2760a}
button:disabled{opacity:.55;cursor:default}
input{font:.95rem var(--mono);border:1px solid var(--bd);border-radius:10px;padding:.6rem .7rem;width:9rem;color:var(--fg)}
input:focus{outline:none;border-color:var(--ac)}
/* live progress */
#live{margin:1.6rem 0 0;border:1px solid var(--bd);border-radius:14px;background:var(--pan);padding:1.1rem 1.3rem;display:none}
#live.on{display:block}
#live .step{font:.92rem var(--mono);color:var(--fg);display:flex;align-items:center;gap:.6rem}
#live .step .spin{display:inline-block;width:.8em;height:.8em;border:2px solid var(--bd);border-top-color:var(--ac);border-radius:50%;animation:sp .7s linear infinite}@keyframes sp{to{transform:rotate(360deg)}}
#live .bar{height:.55rem;background:var(--bd);border-radius:99px;overflow:hidden;margin:.7rem 0 .2rem;opacity:0;transition:opacity .2s}
#live .bar.on{opacity:1}#live .bar i{display:block;height:100%;width:0;background:var(--ac);border-radius:99px;transition:width .1s linear}
#live .meta{font:.78rem var(--mono);color:var(--mut)}
#err{color:var(--bad);text-align:center;margin:1.2rem 0 0;font-size:.95rem}
/* result card */
#card{margin:1.6rem 0 0;border:1px solid var(--bd);border-radius:16px;overflow:hidden;box-shadow:0 8px 30px rgba(16,18,29,.06);display:none}
#card.show{display:block;animation:rise .35s ease both}@keyframes rise{from{opacity:0;transform:translateY(10px)}to{opacity:1;transform:none}}
.vhero{padding:1.7rem 1.4rem 1.5rem;text-align:center;background:linear-gradient(180deg,#e9f7ee,#fff);border-bottom:1px solid var(--bd)}
.vhero.bad{background:linear-gradient(180deg,#fdecec,#fff)}
.vhero .vc{font:800 2.8rem var(--mono);letter-spacing:-1.5px;color:var(--good);line-height:1}.vhero.bad .vc{color:var(--bad)}
.vhero .sl{font-size:.95rem;color:#37414d;margin-top:.35rem}
.vhero .vbar{height:.6rem;background:#d3ead9;border-radius:99px;overflow:hidden;margin:.9rem auto .5rem;max-width:22rem}
.vhero.bad .vbar{background:#f1d5d5}
.vhero .vbar i{display:block;height:100%;width:0;background:var(--good);border-radius:99px;transition:width .9s cubic-bezier(.2,.85,.25,1)}.vhero.bad .vbar i{background:var(--bad)}
.vhero .pct{font:700 .92rem var(--mono);color:var(--good)}.vhero.bad .pct{color:var(--bad)}.vhero .pct .t{color:var(--mut);font-weight:400}
.seclab{padding:.9rem 1.4rem .1rem;font-size:.75rem;text-transform:uppercase;letter-spacing:.05em;color:var(--mut);border-top:1px solid var(--bd)}
.chead{padding:1rem 1.4rem;border-bottom:1px solid var(--bd)}
.chead .h{font:800 1.3rem var(--mono);letter-spacing:-1px}
.chead .hash{font:.76rem var(--mono);color:var(--mut);word-break:break-all;margin-top:.2rem}
.chead .meta{font-size:.83rem;color:var(--mut);margin-top:.35rem}
.checks{padding:.3rem 0}
.chk{display:flex;align-items:flex-start;gap:.8rem;padding:.6rem 1.4rem;border-top:1px solid var(--bd);opacity:0;transform:translateX(-6px);animation:slidein .3s ease forwards}
@keyframes slidein{to{opacity:1;transform:none}}
.chk .ic{font:800 1rem var(--mono);flex-shrink:0;width:1.1rem}.chk .ic.g{color:var(--good)}.chk .ic.b{color:var(--bad)}.chk .ic.s{color:var(--mut)}
.chk .t b{font-weight:700}.chk .t .d{font:.79rem var(--mono);color:var(--mut);word-break:break-all}
.chk .ms{margin-left:auto;font:.78rem var(--mono);color:var(--mut);white-space:nowrap;align-self:center}
.stats{display:grid;grid-template-columns:repeat(auto-fit,minmax(7rem,1fr));gap:.1rem;background:var(--bd);border-top:1px solid var(--bd)}
.stat{background:#fff;padding:.8rem 1rem}.stat .n{font:800 1.2rem var(--mono);letter-spacing:-.5px}.stat .l{font-size:.74rem;color:var(--mut);text-transform:uppercase;letter-spacing:.03em}
.stats.s-block .n{color:var(--ac)}.stats.s-perf .n{color:var(--good)}
.types{padding:1rem 1.4rem;border-top:1px solid var(--bd)}.types .bar{display:flex;height:.7rem;border-radius:99px;overflow:hidden;margin:.5rem 0}.types .bar i{display:block;transition:width .5s ease}
.types .key{font:.78rem var(--mono);color:var(--mut);display:flex;flex-wrap:wrap;gap:.7rem}.types .key span i{display:inline-block;width:.6rem;height:.6rem;border-radius:2px;margin-right:.3rem;vertical-align:-1px}
.bench{padding:.9rem 1.4rem;border-top:1px solid var(--bd);font:.82rem var(--mono);color:var(--mut)}.bench b{color:var(--fg)}
.note{margin:1.1rem 0 0;padding:.7rem 1rem;background:var(--pan);border:1px solid var(--bd);border-radius:10px;font-size:.85rem;color:var(--mut);line-height:1.5}.note b{color:var(--fg)}
/* transaction list + tx detail (click-only navigation) */
.txlist{padding:.2rem 0}
.txrow{display:flex;gap:.7rem;align-items:baseline;padding:.45rem 1.4rem;border-top:1px solid var(--bd);font:.78rem var(--mono)}
.txrow .ix{color:var(--mut);width:2.6rem;flex-shrink:0}.txrow a{word-break:break-all}
.txmore{padding:.6rem 1.4rem;border-top:1px solid var(--bd);font-size:.8rem;color:var(--mut)}
.backlink{padding:.75rem 1.4rem;border-bottom:1px solid var(--bd);font-size:.9rem}
.io{padding:.1rem 0}
.ior{padding:.55rem 1.4rem;border-top:1px solid var(--bd);font:.8rem var(--mono)}
.ior .top{display:flex;justify-content:space-between;gap:.6rem;align-items:baseline}
.ior .amt{font-weight:700;color:var(--fg)}
.ior .typ{color:var(--mut);font-size:.7rem;text-transform:uppercase;letter-spacing:.03em;white-space:nowrap}
.ior .sub{color:var(--mut);word-break:break-all;margin-top:.15rem}
footer{margin:3rem 0 2rem;text-align:center;font-size:.85rem;color:var(--mut)}
</style>
</head>
<body>
<nav><div class="wrap">
<a href="./index.html" class="brand">bitcoin<b>·</b>kernel</a>
<a href="./index.html">Test suite</a>
<a href="./random.html" class="on">Verify a block</a>
<a href="./cache.html">Your node</a>
<a href="./spec.html">Specification</a>
<a href="https://github.com/bitcoin-kernel/bitcoin-kernel.github.io">Source ↗</a>
</div></nav>
<header class="hero"><div class="wrap">
<h1>Verify a Bitcoin block.</h1>
<p class="sub">The latest block, a random one, or any height you type. It is fetched live and its proof of work, merkle root and structure are checked right here in your browser. No server. The validator is the page.</p>
<div class="controls">
<button id="tip" class="primary">⛓ Latest block</button>
<button id="rand">🎲 Random block</button>
<input id="height" type="number" min="0" placeholder="block height" inputmode="numeric">
<button id="go">Verify</button>
</div>
</div></header>
<div class="wrap">
<div id="live">
<div class="step"><span class="spin"></span><span id="step-t">starting</span></div>
<div class="bar" id="bar"><i id="barfill"></i></div>
<div class="meta" id="live-meta"></div>
</div>
<p id="err"></p>
<div id="card"></div>
<p class="note"><b>Two layers.</b> A block's proof of work, merkle root, witness commitment and structure all live inside the block itself, so they verify with no extra data. Scripts and signatures need the spending history (the prevouts), which isn't in the block — so <b>click any transaction</b> to fetch it and run its scripts and signatures through the engine for real, right here in your browser. That is the full check, one transaction at a time.</p>
</div>
<footer>An independent JavaScript implementation. Block data from <span id="prov">mempool.space</span><span id="cstat"></span>. <a href="./index.html">bitcoin-kernel</a></footer>
<script type="module">
import { Codec } from 'https://cdn.jsdelivr.net/gh/bitcoin-kernel/kernel@v0.0.2/packages/kernel/codec/codec.js';
import { BlockEngine } from 'https://cdn.jsdelivr.net/gh/bitcoin-kernel/kernel@v0.0.2/packages/kernel/codec/blocks.js';
import { ScriptEngine } from 'https://cdn.jsdelivr.net/gh/bitcoin-kernel/kernel@v0.0.2/packages/kernel/codec/script.js';
import core from 'https://cdn.jsdelivr.net/gh/bitcoin-kernel/kernel@v0.0.2/packages/kernel/schema/core.js';
import proof from 'https://cdn.jsdelivr.net/gh/bitcoin-kernel/kernel@v0.0.2/packages/kernel/schema/proof.js';
import chain from 'https://cdn.jsdelivr.net/gh/bitcoin-kernel/kernel@v0.0.2/packages/kernel/schema/chain.js';
import validate from 'https://cdn.jsdelivr.net/gh/bitcoin-kernel/kernel@v0.0.2/packages/kernel/schema/validate.js';
import script from 'https://cdn.jsdelivr.net/gh/bitcoin-kernel/kernel@v0.0.2/packages/kernel/schema/script.js';
import { cache } from 'https://cdn.jsdelivr.net/gh/bitcoin-kernel/kernel@v0.0.2/packages/web/cache.js';
import { Sources, CacheSource, ExplorerSource } from 'https://cdn.jsdelivr.net/gh/bitcoin-kernel/kernel@v0.0.2/packages/web/sources.js';
import { setVerifyBackend } from 'https://cdn.jsdelivr.net/gh/bitcoin-kernel/kernel@v0.0.2/packages/kernel/codec/secp256k1.js';
import { loadSecpWasm, wasmBackend } from 'https://cdn.jsdelivr.net/gh/bitcoin-kernel/kernel@v0.0.2/packages/kernel/wasm/secp-wasm.js';
const codec = new Codec(core, proof);
const be = BlockEngine.fromSchemas(codec, chain, validate, script, 'btc:mainnet');
const se = ScriptEngine.fromSchemas(script, chain);
const wasmReady = loadSecpWasm(); // kick off WASM secp load; tx verification awaits it
const $ = (id) => document.getElementById(id);
const busy = (b) => { $('rand').disabled = $('go').disabled = $('tip').disabled = b; };
const esc = (s) => String(s).replace(/[&<>]/g, (c) => ({ '&': '&', '<': '<', '>': '>' }[c]));
const fmt = (n) => Number(n).toLocaleString();
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
const TCOL = { p2pk: '#57606a', p2pkh: '#0969da', p2sh: '#8250df', p2ms: '#6e7781', multisig: '#6e7781', p2wpkh: '#1a7f37', p2wsh: '#bf8700', p2tr: '#e8830c', 'p2tr-keypath': '#e8830c', nulldata: '#a0a0a0', unknown: '#cf222e' };
const TXCAP = 25; // cap the clickable tx list so a spam block doesn't render thousands of rows
const TIP_ALIASES = new Set(['latest', 'tip', 'head']); // ?height=latest -> always the current tip
const btc = (v) => { const s = (v / 1e8).toFixed(8).replace(/0+$/, '').replace(/\.$/, ''); return s === '' || s === '0' ? '0' : s; };
const step = (t) => { $('step-t').textContent = t; };
const setBar = (frac) => { $('bar').classList.add('on'); $('barfill').style.width = (Math.max(0, Math.min(1, frac)) * 100).toFixed(1) + '%'; };
let TIP = null;
// Block sources, tried in order behind the cache. A peer-mesh source will slot
// in here later (between cache and explorer) with no change to the call sites.
const sources = new Sources([
new CacheSource(cache),
new ExplorerSource(['https://mempool.space', 'https://blockstream.info']),
]);
function showCacheStat() {
const s = cache.stats();
const el = $('cstat');
if (el) el.textContent = s.n ? ` · ${s.n} block${s.n > 1 ? 's' : ''} cached on your device (${(s.bytes / 1e6).toFixed(0)} MB)` : '';
}
// count a number up from 0 -> value over ~600ms
function countUp(el, value) {
const t0 = performance.now(), dur = 600;
function tick(t) { const k = Math.min(1, (t - t0) / dur); el.textContent = fmt(Math.round(value * (1 - Math.pow(1 - k, 3)))); if (k < 1) requestAnimationFrame(tick); }
requestAnimationFrame(tick);
}
async function verify(height, push = true) {
busy(true);
$('card').classList.remove('show'); $('card').style.display = 'none';
$('err').textContent = '';
$('live').classList.add('on'); $('bar').classList.remove('on'); $('barfill').style.width = '0'; $('live-meta').textContent = '';
try {
const tF = performance.now();
await cache.init();
// resolve height -> hash (local index first, then explorer), then ask the
// source registry for the bytes: cache hit serves off device, miss fetches.
const localHash = cache.available() ? cache.hashForHeight(height) : null;
step(localHash ? 'reading block from your device' : `looking up block ${fmt(height)}`);
const hash = localHash || await sources.hashForHeight(height);
if (!localHash) step('downloading block');
const got = await sources.getBlock(hash, (recv, total) => {
if (total) setBar(recv / total);
$('live-meta').textContent = `${(recv / 1024).toFixed(0)} KB${total ? ' / ' + (total / 1024).toFixed(0) + ' KB' : ''}`;
});
const bytes = got.bytes, received = bytes.length, dlMs = got.dlMs || 0;
const fromCache = got.from === 'your device';
$('prov').textContent = fromCache ? 'your device (OPFS cache)' : got.from;
if (!fromCache) cache.put(hash, height, bytes); // store explorer/peer fetches for next time
if (!fromCache) setBar(1);
const fetchMs = performance.now() - tF;
$('bar').classList.remove('on');
step('decoding transactions');
await sleep(40);
let hex = ''; const lut = []; for (let i = 0; i < 256; i++) lut[i] = i.toString(16).padStart(2, '0'); for (let i = 0; i < bytes.length; i++) hex += lut[bytes[i]];
const tD = performance.now();
const block = codec.decode('Block', hex);
const decodeMs = performance.now() - tD;
step(`hashing ${fmt(block.transactions.length)} transactions`);
await sleep(40);
const tV = performance.now();
const txids = block.transactions.map((t) => codec.txid(t));
cache.indexBlock(height, txids); // build the txid->height index for free from this decode
const tMerkle0 = performance.now();
const merkleGot = codec.merkleRoot(txids);
const merkleMs = performance.now() - tMerkle0;
const powOk = codec.checkProofOfWork(block.header);
const merkleOk = merkleGot === block.header.merkleRoot;
const struct = be.validateBlockStructure(block).results;
const structFails = struct.filter((r) => r.ok === false);
const verifyMs = performance.now() - tV;
let ins = 0, outs = 0; const types = {};
for (const t of block.transactions) { ins += t.inputs.length; outs += t.outputs.length; for (const o of t.outputs) { const c = se.classify(o.scriptPubKey).type || 'unknown'; types[c] = (types[c] || 0) + 1; } }
const target = codec.expandCompact(block.header.bits).toString(16).padStart(64, '0');
$('live').classList.remove('on');
const allOk = powOk && merkleOk && structFails.length === 0;
if (allOk) cache.markVerified(hash); // record that this cached block passed full verification
render({ height, hash, block, txids, powOk, merkleGot, merkleOk, struct, structFails, ins, outs, types, target,
allOk, bytes: received, weight: be.blockWeight(block),
fetchMs, decodeMs, verifyMs, merkleMs, dlMs, fromCache });
showCacheStat();
$('height').value = height;
if (push) history.pushState({ height }, '', `?height=${height}`);
} catch (e) {
$('live').classList.remove('on');
$('err').textContent = 'Error: ' + e.message;
} finally {
busy(false);
}
}
function chk(ok, title, detail, ms, skipped, delay) {
const ic = skipped ? '<span class="ic s">○</span>' : ok ? '<span class="ic g">✓</span>' : '<span class="ic b">✗</span>';
return `<div class="chk" style="animation-delay:${delay}ms"><span class="ic-w">${ic}</span><div class="t"><b>${esc(title)}</b>${detail ? `<div class="d">${detail}</div>` : ''}</div>${ms != null ? `<span class="ms">${ms}</span>` : ''}</div>`;
}
function render(r) {
const d = new Date(r.block.header.time * 1000).toISOString().replace('T', ' ').slice(0, 19) + ' UTC';
const tbar = Object.entries(r.types).sort((a, b) => b[1] - a[1]);
const totalOut = r.outs || 1;
const bar = tbar.map(([k, n]) => `<i style="background:${TCOL[k] || '#999'};width:0" data-w="${(n / totalOut * 100).toFixed(1)}"></i>`).join('');
const key = tbar.map(([k, n]) => `<span><i style="background:${TCOL[k] || '#999'}"></i>${esc(k)} ${fmt(n)}</span>`).join('');
const structOk = r.structFails.length === 0;
const nTx = r.block.transactions.length;
const mbps = r.dlMs > 0 ? (r.bytes / 1000 / r.dlMs).toFixed(1) : '0';
const txps = r.verifyMs > 0 ? Math.round(nTx / (r.verifyMs / 1000)) : 0;
const u = (s) => `<span style="font-size:.7rem;color:var(--mut);font-weight:400"> ${s}</span>`;
$('card').innerHTML = `
<div class="vhero ${r.allOk ? '' : 'bad'}">
<div class="vc"><span class="cu" data-c="${nTx}">0</span> <span style="font-size:1.5rem;letter-spacing:-1px">/ ${fmt(nTx)}</span></div>
<div class="sl">${r.allOk ? 'transactions verified' : 'a structural check failed'}</div>
<div class="vbar"><i id="vfill"></i></div>
<div class="pct">${r.allOk ? '100%' : 'failed'}<span class="t"> · proof of work, merkle & structure in <b style="color:var(--good);font-weight:800">${r.verifyMs.toFixed(0)} ms</b>, in your browser</span></div>
</div>
<div class="chead">
<div class="h">Block ${fmt(r.height)}</div>
<div class="hash">${esc(r.hash)}</div>
<div class="meta">${d} · ${(r.bytes / 1024).toFixed(0)} KB · weight ${fmt(r.weight)}${r.fromCache ? ' · <b style="color:var(--good)">⚡ served from your device</b>' : ''}</div>
</div>
<div class="checks">
${chk(r.powOk, 'Proof of work', `hash ${r.hash.slice(0, 18)}… ≤ target ${r.target.replace(/^0+/, '0…').slice(0, 18)}…`, null, false, 0)}
${chk(r.merkleOk, `Merkle root (${fmt(nTx)} transactions)`, `${r.merkleGot.slice(0, 36)}…`, r.merkleMs.toFixed(1) + ' ms', false, 90)}
${chk(structOk, 'Block structure & limits', structOk ? 'coinbase, weight, sigops, witness commitment, no duplicates' : r.structFails.map((f) => esc(f.label)).join(', '), null, false, 180)}
</div>
<div class="seclab">The block</div>
<div class="stats s-block">
<div class="stat"><div class="n">${(r.bytes / 1e6).toFixed(2)}${u('MB')}</div><div class="l">Size</div></div>
<div class="stat"><div class="n"><span class="cu" data-c="${nTx}">0</span></div><div class="l">Transactions</div></div>
<div class="stat"><div class="n"><span class="cu" data-c="${r.ins}">0</span></div><div class="l">Inputs</div></div>
<div class="stat"><div class="n"><span class="cu" data-c="${r.outs}">0</span></div><div class="l">Outputs</div></div>
<div class="stat"><div class="n">${(r.weight / 4000).toFixed(0)}${u('k vB')}</div><div class="l">Virtual size</div></div>
</div>
<div class="seclab">Performance, in your browser</div>
<div class="stats s-perf">
<div class="stat"><div class="n"${r.fromCache ? ' style="color:var(--good)"' : ''}><span class="cu" data-c="${Math.round(r.fetchMs)}">0</span>${u('ms')}</div><div class="l">Fetch${r.fromCache ? ' <span style="color:var(--good);font-weight:700">⚡ cached</span>' : ''}</div></div>
<div class="stat"><div class="n">${r.fromCache ? '—' : mbps + u('MB/s')}</div><div class="l">${r.fromCache ? 'No download' : 'Download'}</div></div>
<div class="stat"><div class="n"><span class="cu" data-c="${Math.round(r.decodeMs)}">0</span>${u('ms')}</div><div class="l">Decode</div></div>
<div class="stat"><div class="n"><span class="cu" data-c="${Math.round(r.verifyMs)}">0</span>${u('ms')}</div><div class="l">Verify</div></div>
<div class="stat"><div class="n"><span class="cu" data-c="${txps}">0</span>${u('tx/s')}</div><div class="l">Throughput</div></div>
</div>
${tbar.length ? `<div class="types"><div style="font-size:.85rem;color:var(--mut)">Output script types</div><div class="bar">${bar}</div><div class="key">${key}</div></div>` : ''}
<div class="seclab">Transactions <span style="text-transform:none;color:var(--mut)">· click any to inspect</span></div>
<div class="txlist">${r.txids.slice(0, TXCAP).map((tx, i) => `<div class="txrow"><span class="ix">${i === 0 ? 'cb' : '#' + i}</span><a href="?tx=${tx}" data-tx="${tx}">${tx}</a></div>`).join('')}${r.txids.length > TXCAP ? `<div class="txmore">+ ${fmt(r.txids.length - TXCAP)} more transactions in this block</div>` : ''}</div>`;
$('card').style.display = 'block'; $('card').classList.add('show');
$('card').querySelectorAll('.cu[data-c]').forEach((el) => countUp(el, +el.dataset.c));
requestAnimationFrame(() => {
const vf = document.getElementById('vfill'); if (vf) vf.style.width = (r.allOk ? 100 : 8) + '%';
$('card').querySelectorAll('.types .bar i').forEach((i) => { i.style.width = i.dataset.w + '%'; });
});
}
async function randomBlock() {
busy(true);
$('err').textContent = ''; $('live').classList.add('on'); $('bar').classList.remove('on'); $('live-meta').textContent = '';
step('picking a random block');
try {
if (TIP == null) TIP = await sources.tipHeight();
verify(Math.floor(Math.random() * (TIP + 1)));
} catch (e) { $('live').classList.remove('on'); $('err').textContent = 'Error: ' + e.message; busy(false); }
}
// --- transaction detail + real engine verification (fetches only on click) ---
async function showTx(txid, push = true) {
busy(true);
$('card').classList.remove('show'); $('card').style.display = 'none';
$('err').textContent = '';
$('live').classList.add('on'); $('bar').classList.remove('on'); $('barfill').style.width = '0'; $('live-meta').textContent = '';
step('fetching transaction');
try {
const tx = await sources.tx(txid);
let ver = null;
try {
const usingWasm = await wasmReady; // WASM secp if available, else pure-JS
setVerifyBackend(usingWasm ? wasmBackend : null);
step('verifying scripts & signatures with the engine');
const hex = await sources.txHex(txid);
const etx = codec.decode('Transaction', hex);
// esplora inlines each prevout's scriptpubkey + value -> exactly what the interpreter needs
const prevouts = tx.vin.map((v) => v.is_coinbase ? null : { value: v.prevout.value, scriptPubKey: v.prevout.scriptpubkey });
const all = prevouts.every(Boolean) ? prevouts : null; // taproot sighash needs every prevout
const t0 = performance.now();
const res = tx.vin.map((v, i) => v.is_coinbase ? { coinbase: true } : be.interpreter.verifyInput(etx, i, prevouts[i], all));
const ms = performance.now() - t0;
const total = res.filter((r) => !r.coinbase).length;
const ok = res.filter((r) => r.ok === true).length;
const skipped = res.filter((r) => r.ok === null).length;
ver = { res, ms, total, ok, skipped, allOk: total > 0 && ok === total, backend: usingWasm ? 'WASM secp256k1' : 'pure JS' };
} catch (e) { ver = { error: e.message }; }
cache.indexTx(tx.txid, tx.status && tx.status.block_height); // learn this tx's height too
// resolve each input's funding block from the local index only — no explorer calls
const funds = {};
await Promise.all(tx.vin.filter((v) => !v.is_coinbase && v.txid).map(async (v) => {
const h = await cache.heightForTx(v.txid); if (h != null) funds[v.txid] = h;
}));
$('live').classList.remove('on');
renderTx(tx, ver, funds);
if (push) history.pushState({ tx: txid }, '', `?tx=${txid}`);
} catch (e) {
$('live').classList.remove('on');
$('err').textContent = 'Error: ' + e.message;
} finally {
busy(false);
}
}
function renderTx(tx, ver, funds = {}) {
const st = tx.status || {};
const inT = tx.vin.reduce((s, v) => s + (v.prevout ? v.prevout.value : 0), 0);
const outT = tx.vout.reduce((s, v) => s + v.value, 0);
const mark = (i) => {
const r = ver && ver.res ? ver.res[i] : null;
if (!r || r.coinbase) return '';
if (r.ok === true) return '<span class="ic g">✓</span> ';
if (r.ok === false) return '<span class="ic b">✗</span> ';
return '<span class="ic s">○</span> ';
};
const vins = tx.vin.map((v, i) => {
if (v.is_coinbase) return `<div class="ior"><div class="top"><span class="amt">newly issued coins</span><span class="typ">coinbase</span></div></div>`;
const p = v.prevout || {};
const fh = funds[v.txid];
const fchip = fh != null ? ` · <a href="?height=${fh}" data-h="${fh}" title="funding block, known from your local index">block ${fmt(fh)}</a>` : '';
return `<div class="ior"><div class="top"><span class="amt">${mark(i)}${btc(p.value || 0)} BTC</span><span class="typ">${esc(p.scriptpubkey_type || '')}</span></div>`
+ `<div class="sub">from <a href="?tx=${v.txid}" data-tx="${v.txid}">${esc(v.txid.slice(0, 22))}…:${v.vout}</a>${fchip}${p.scriptpubkey_address ? ' · ' + esc(p.scriptpubkey_address) : ''}</div></div>`;
}).join('');
const vouts = tx.vout.map((o) => `<div class="ior"><div class="top"><span class="amt">${btc(o.value)} BTC</span><span class="typ">${esc(o.scriptpubkey_type || '')}</span></div>${o.scriptpubkey_address ? `<div class="sub">${esc(o.scriptpubkey_address)}</div>` : ''}</div>`).join('');
let vhero = '';
if (ver && ver.total > 0) {
vhero = `<div class="vhero ${ver.allOk ? '' : 'bad'}" style="padding:1.4rem 1.4rem 1.2rem">
<div class="vc" style="font-size:2.2rem"><span class="cu" data-c="${ver.ok}">0</span> <span style="font-size:1.2rem;letter-spacing:-1px">/ ${ver.total}</span></div>
<div class="sl">${ver.allOk ? 'inputs verified' : ver.ok + ' of ' + ver.total + ' inputs verified'}${ver.skipped ? ` · ${ver.skipped} skipped` : ''}</div>
<div class="pct">${ver.allOk ? 'scripts & signatures checked' : 'verification failed'}<span class="t"> · in <b style="color:var(--good);font-weight:800">${ver.ms.toFixed(1)} ms</b> by the engine${ver.backend === 'WASM secp256k1' ? ' (<b>WASM</b> secp256k1)' : ''}, in your browser</span></div>
</div>`;
} else if (ver && ver.error) {
vhero = `<div class="note" style="margin:0;border-radius:0;border-left:0;border-right:0;border-top:0">Could not run verification (${esc(ver.error)}); detail shown from the explorer.</div>`;
} else if (ver && ver.total === 0) {
vhero = `<div class="note" style="margin:0;border-radius:0;border-left:0;border-right:0;border-top:0">Coinbase transaction — newly issued coins, no inputs to verify.</div>`;
}
$('card').innerHTML = `
<div class="backlink">${st.block_height != null ? `← <a href="?height=${st.block_height}" data-h="${st.block_height}">Block ${fmt(st.block_height)}</a>` : 'unconfirmed (in the mempool)'}</div>
<div class="chead">
<div class="h" style="font-size:1rem">Transaction</div>
<div class="hash">${esc(tx.txid)}</div>
<div class="meta">${tx.vin.length} in · ${tx.vout.length} out · ${fmt(tx.size)} bytes · weight ${fmt(tx.weight)}${tx.fee != null ? ` · fee ${fmt(tx.fee)} sat` : ''}</div>
</div>
${vhero}
<div class="seclab">Inputs (${tx.vin.length})${inT ? ` · ${btc(inT)} BTC` : ''}</div>
<div class="io">${vins}</div>
<div class="seclab">Outputs (${tx.vout.length}) · ${btc(outT)} BTC</div>
<div class="io">${vouts}</div>`;
$('card').style.display = 'block'; $('card').classList.add('show');
$('card').querySelectorAll('.cu[data-c]').forEach((el) => countUp(el, +el.dataset.c));
}
// every click inside the card stays client-side: tx links fetch one tx, block links re-verify
$('card').addEventListener('click', (e) => {
const a = e.target.closest('a[data-tx],a[data-h]');
if (!a) return;
e.preventDefault();
if (a.dataset.tx) showTx(a.dataset.tx);
else if (a.dataset.h != null) { $('height').value = a.dataset.h; verify(+a.dataset.h); }
});
function route() {
const q = new URLSearchParams(location.search);
if (q.get('tx')) return showTx(q.get('tx'), false);
const h = (q.get('height') || '').trim().toLowerCase();
if (h && !TIP_ALIASES.has(h) && /^\d+$/.test(h)) return verify(+h, false);
return latestBlock(false); // empty, 'latest'/'tip'/'head', or non-numeric -> current tip, no extra push
}
window.addEventListener('popstate', route);
async function latestBlock(push = true) {
busy(true);
$('err').textContent = ''; $('live').classList.add('on'); $('bar').classList.remove('on'); $('live-meta').textContent = '';
step('finding the chain tip');
try {
TIP = await sources.tipHeight();
await verify(TIP, false); // verify the resolved tip without pushing a numeric URL...
if (push) history.pushState({ tip: true }, '', '?height=latest'); // ...keep the symbolic, always-current URL
} catch (e) { $('live').classList.remove('on'); $('err').textContent = 'Error: ' + e.message; busy(false); }
}
$('tip').onclick = () => latestBlock();
$('rand').onclick = randomBlock;
$('go').onclick = () => { const h = parseInt($('height').value, 10); if (Number.isFinite(h) && h >= 0) verify(h); };
$('height').onkeydown = (e) => { if (e.key === 'Enter') $('go').click(); };
route();
</script>
</body>
</html>