feat: blackbeard.observer — live Quantus mining leaderboard

Cargo workspace plus a Vite frontend, following ~/git/architecture/generic.md.

Every block header carries its author's wormhole reward preimage in a `pow_`
PreRuntime digest, so authorship for the whole network is derivable from headers
alone — no indexer, no registration, no way for a miner to be left out. That
decoding, the hashrate maths and the telemetry name attribution live in
blackbeard-core with no I/O at all, so the parts that are easy to get subtly
wrong are exercised by unit tests rather than only against a live chain.

The browser holds one WebSocket: snapshot on subscribe, deltas thereafter. The
head stream is itself a push (chain_subscribeNewHeads), so a block reaches the
page the moment the node imports it. Messages are serialised once per broadcast,
and leaderboards are recomputed only for windows a socket is actually watching.
No RxJS — useSyncExternalStore is React's own contract for this.

Verified against the live Planck testnet: 12/12 headers decoded, telemetry names
attributed (quanpool-planck, baba-gorchitsa, …), warm start restoring 84 blocks
and 5 held names across a restart.

Three findings worth recording, all in CLAUDE.md:

- substrate-telemetry sends its JSON in *binary* frames. A text-only client
  connects, subscribes, reports healthy and receives nothing at all — and a
  Python probe hides it, because json.loads accepts bytes.
- Difficulty is a little-endian U512; decoding it big-endian gives a number
  wrong by ~10^150 that still renders fine.
- Planck's real block interval is ~13-15s against a 6s target with enormous
  variance, so a measured interval needs 20 tip samples before it is publishable.

Deploy assets, the Gitea Actions workflow and script/infra-setup.sh are included;
port 25864 is registered in architecture/port-allocations.md.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MSDYiibCtELsrjQq6KXnoi
This commit is contained in:
2026-09-04 12:33:54 +03:00
co-authored by Claude Opus 5
commit 110fbc3631
100 changed files with 16221 additions and 0 deletions
+87
View File
@@ -0,0 +1,87 @@
/**
* The live block feed.
*
* The site's proof that it is live: blocks appear here the moment the node
* imports them, with no refresh and no polling. Each row flashes once on
* arrival — suppressed under `prefers-reduced-motion`, where the numbers alone
* still carry everything.
*/
import { useEffect, useRef, useState } from 'react'
import type { RecentBlock } from '../api/generated/RecentBlock'
import { ago, height, seconds, shortMiner } from '../lib/format'
import { usePinnedMiners } from '../lib/store'
export function BlockTicker({
blocks,
onSelect,
}: {
blocks: RecentBlock[]
onSelect: (miner: string) => void
}) {
const { isPinned } = usePinnedMiners()
const seen = useRef<Set<number>>(new Set())
// `ago()` is a pure function of the clock, so nothing re-renders it on its
// own. One interval for the whole list, rather than a timer per row.
const [, tick] = useState(0)
useEffect(() => {
const id = window.setInterval(() => tick((n) => n + 1), 1000)
return () => window.clearInterval(id)
}, [])
const fresh = new Set<number>()
for (const block of blocks) {
if (!seen.current.has(block.height)) fresh.add(block.height)
}
useEffect(() => {
for (const block of blocks) seen.current.add(block.height)
})
if (blocks.length === 0) {
return <p className="empty">Waiting for the next block…</p>
}
return (
<div>
{blocks.map((block) => {
const mine = isPinned(block.miner)
const named = block.display !== shortMiner(block.miner)
return (
<div
key={block.height}
className={[
'ticker-row',
mine ? 'mine' : '',
fresh.has(block.height) ? 'fresh' : '',
]
.filter(Boolean)
.join(' ')}
>
<span className="ticker-height">#{height(block.height)}</span>
<a
href={`#/miner/${block.miner}`}
title={block.miner}
onClick={(e) => {
e.preventDefault()
onSelect(block.miner)
}}
style={{
overflow: 'hidden',
textOverflow: 'ellipsis',
fontFamily: named ? 'inherit' : 'var(--font-mono)',
fontSize: named ? 'inherit' : '12px',
color: named ? 'var(--text-primary)' : 'var(--text-secondary)',
}}
>
{block.display}
</a>
<span className="ticker-gap">
{block.gap_seconds !== null ? `+${seconds(block.gap_seconds)}` : ago(block.observed_at)}
</span>
</div>
)
})}
</div>
)
}
+155
View File
@@ -0,0 +1,155 @@
/**
* The standings.
*
* A table, not a chart. Eight-plus miners each carrying a name, a count, a
* share, a hashrate and a streak is exactly the case the form heuristic sends
* to a table — and a miner looking for their own row wants to *read* it, not
* hunt for a colour in a legend.
*
* The one graphical element is the share bar: single hue, magnitude only. A
* pinned miner's row is marked three ways at once — a left rule, a wash, and an
* explicit "YOU" chip — so identity never rests on colour alone.
*/
import type { LeaderboardRow } from '../api/generated/LeaderboardRow'
import { ago, hashrate, share, shortMiner } from '../lib/format'
import { usePinnedMiners } from '../lib/store'
function Row({
row,
max,
mine,
onToggle,
onSelect,
}: {
row: LeaderboardRow
max: number
mine: boolean
onToggle: (miner: string) => void
onSelect: (miner: string) => void
}) {
const named = row.attribution === 'telemetry'
return (
<tr className={mine ? 'mine' : undefined}>
<td className={`rank rank-${row.rank}`}>{row.rank}</td>
<td className="left">
<div className="miner-cell">
<button
className="pin-button"
aria-pressed={mine}
title={mine ? 'Remove from your miners' : 'Mark this miner as yours'}
onClick={() => onToggle(row.miner)}
>
{mine ? '★' : '☆'}
</button>
<a
href={`#/miner/${row.miner}`}
className={named ? 'miner-name' : 'miner-name anonymous'}
title={row.miner}
onClick={(e) => {
e.preventDefault()
onSelect(row.miner)
}}
>
{named ? row.display : shortMiner(row.miner)}
</a>
{mine && <span className="chip chip-you">You</span>}
{named && (
<span
className="chip chip-named"
// An attributed name is an inference from who reported the block
// first, not a claim the miner made. The chip and the confidence
// in its tooltip keep that visible rather than presenting a guess
// as a fact.
title={`Name inferred from telemetry — ${Math.round(row.confidence * 100)}% of recent blocks agree`}
>
node
</span>
)}
</div>
</td>
<td className="numeral">{row.blocks}</td>
{/* Bar and number in one cell: two columns for one quantity cost ~80px
and pushed the streak and last-block columns off the table at ordinary
window widths. The bar is the magnitude, the number is its direct
label — they belong together. */}
<td className="share-cell">
<span className="numeral">{share(row.share)}</span>
<div className="share-bar" aria-hidden="true">
<i style={{ width: `${max > 0 ? (row.share / max) * 100 : 0}%` }} />
</div>
</td>
<td className="numeral">{hashrate(row.hashrate_estimate)}</td>
<td className="numeral streak" title="Longest run of consecutive blocks in this window">
{row.best_streak > 1 ? `×${row.best_streak}` : '—'}
</td>
<td className="numeral last-seen" style={{ color: 'var(--text-muted)' }}>
{ago(row.last_seen)}
</td>
</tr>
)
}
export function Leaderboard({
rows,
ready,
onSelect,
}: {
rows: LeaderboardRow[]
ready: boolean
onSelect: (miner: string) => void
}) {
const { isPinned, toggle } = usePinnedMiners()
// Bars are scaled to the leader, not to 100%: with twenty miners the top
// share is often under 15%, and full-scale bars would all be slivers.
const max = rows.length > 0 ? Math.max(...rows.map((r) => r.share)) : 0
if (rows.length === 0) {
return (
<p className="empty">
{ready
? 'No blocks observed in this window yet. A shorter window may show more.'
: 'Waiting for the first snapshot…'}
</p>
)
}
return (
<div className="scroll-x">
<table className="board">
<caption className="visually-hidden">
Miners ranked by blocks won in the selected window
</caption>
<thead>
<tr>
<th scope="col">#</th>
<th scope="col" className="left">
Miner
</th>
<th scope="col">Blocks</th>
<th scope="col">Share</th>
<th scope="col">Est. hashrate</th>
<th scope="col" className="streak">
Streak
</th>
<th scope="col" className="last-seen">
Last block
</th>
</tr>
</thead>
<tbody>
{rows.map((row) => (
<Row
key={row.miner}
row={row}
max={max}
mine={isPinned(row.miner)}
onToggle={toggle}
onSelect={onSelect}
/>
))}
</tbody>
</table>
</div>
)
}
+139
View File
@@ -0,0 +1,139 @@
/**
* One miner's page.
*
* The reason the site exists: a miner types (or clicks) their reward preimage
* and sees where they stand and how they have been doing. Everything here is
* public chain data — there is nothing to log into, and the "this one is mine"
* mark lives only in this browser.
*/
import { useEffect, useState } from 'react'
import type { MinerDetail } from '../api/generated/MinerDetail'
import type { Window as WindowName } from '../api/generated/Window'
import { RequestFailed, fetchMiner } from '../api/rest'
import { ago, bigNumber, hashrate, height, share, shortMiner } from '../lib/format'
import { usePinnedMiners } from '../lib/store'
import { ShareChart } from './ShareChart'
export function MinerPanel({
chain,
miner,
windowName,
onClose,
}: {
chain: string
miner: string
windowName: WindowName
onClose: () => void
}) {
const [detail, setDetail] = useState<MinerDetail | null>(null)
const [error, setError] = useState<string | null>(null)
const { isPinned, toggle } = usePinnedMiners()
const mine = isPinned(miner)
useEffect(() => {
const controller = new AbortController()
setDetail(null)
setError(null)
fetchMiner(chain, miner, windowName, controller.signal)
.then(setDetail)
.catch((e: unknown) => {
// An abort is this component being replaced, not a failure to report.
if (controller.signal.aborted) return
setError(e instanceof RequestFailed ? e.message : 'Could not reach the observer.')
})
return () => controller.abort()
// Re-fetched on window change because the history range follows the window.
}, [chain, miner, windowName])
const row = detail?.current ?? null
const named = row?.attribution === 'telemetry'
return (
<section className="panel" style={{ marginBottom: 26 }}>
<div className="panel-head">
<div>
<div className="eyebrow">Miner</div>
<h2 className="panel-title" style={{ marginTop: 4 }}>
{named ? row.display : shortMiner(miner)}
</h2>
<div
className="numeral"
style={{ fontSize: 11, color: 'var(--text-muted)', marginTop: 4, overflowWrap: 'anywhere' }}
>
{miner}
</div>
</div>
<div style={{ display: 'flex', gap: 10, alignItems: 'center' }}>
<button
className="segmented"
style={{ padding: '7px 13px', font: 'inherit', fontSize: 12, letterSpacing: '0.1em', textTransform: 'uppercase', color: mine ? 'var(--accent-bright)' : 'var(--text-secondary)', cursor: 'pointer' }}
aria-pressed={mine}
onClick={() => toggle(miner)}
>
{mine ? '★ Yours' : '☆ Mark as yours'}
</button>
<button
className="segmented"
style={{ padding: '7px 13px', font: 'inherit', fontSize: 12, letterSpacing: '0.1em', textTransform: 'uppercase', color: 'var(--text-secondary)', cursor: 'pointer' }}
onClick={onClose}
>
Close
</button>
</div>
</div>
{error && <p className="empty">{error}</p>}
{!error && !detail && <p className="empty">Reading the record…</p>}
{detail && (
<>
<div className="stats" style={{ margin: 0, border: 0, borderBottom: 'var(--rule)' }}>
<div className="stat">
<div className="stat-label">Rank</div>
<div className="stat-value">{row ? `#${row.rank}` : '—'}</div>
<div className="stat-note">
{row ? `${share(row.share)} of the window` : 'no blocks in this window'}
</div>
</div>
<div className="stat">
<div className="stat-label">Est. hashrate</div>
<div className="stat-value">{hashrate(row?.hashrate_estimate)}</div>
<div className="stat-note">from share of blocks won</div>
</div>
<div className="stat">
<div className="stat-label">Blocks observed</div>
<div className="stat-value">{height(detail.blocks_observed)}</div>
<div className="stat-note">
{detail.first_seen ? `first seen ${ago(detail.first_seen)}` : 'never seen'}
</div>
</div>
<div className="stat">
<div className="stat-label">Cumulative work</div>
<div className="stat-value" title={detail.cumulative_work}>
{bigNumber(detail.cumulative_work)}
</div>
{/* Difficulty summed over every block won. It does not shrink when
difficulty rises, which a block count effectively does. */}
<div className="stat-note">expected hashes, all blocks</div>
</div>
<div className="stat">
<div className="stat-label">Best streak</div>
<div className="stat-value">{row && row.best_streak > 1 ? `×${row.best_streak}` : '—'}</div>
<div className="stat-note">consecutive blocks</div>
</div>
</div>
<div style={{ padding: '16px 18px 18px' }}>
<div className="eyebrow" style={{ marginBottom: 10 }}>
Share of network blocks
</div>
<ShareChart points={detail.series} />
</div>
</>
)}
</section>
)
}
+211
View File
@@ -0,0 +1,211 @@
/**
* One miner's share of the network over time.
*
* A single-series area chart: the job is change-over-time for one quantity, so
* there is one hue and no legend — the panel title already says what is
* plotted, and a legend box with one swatch would restate it.
*
* Inline SVG rather than a charting library. The whole chart is one path, one
* fill and two axes; a library would be a hundred kilobytes and a second set of
* theming rules to keep in step with the CSS custom properties above it.
*
* The viewBox tracks the container's measured width rather than being fixed and
* scaled to fit. A fixed viewBox stretched to a full-width panel scales its
* *height* with it — a 190-unit chart became 300px tall on a wide screen, and
* the area fill went from a wash to a slab. Measuring keeps one SVG unit at one
* CSS pixel, which also makes the crosshair land exactly under the pointer.
*/
import { useEffect, useMemo, useRef, useState } from 'react'
import type { MinerSeriesPoint } from '../api/generated/MinerSeriesPoint'
import { hashrate, share } from '../lib/format'
const HEIGHT = 200
const PAD = { top: 16, right: 18, bottom: 26, left: 46 }
/** Used until the container has been measured, and if ResizeObserver is absent. */
const FALLBACK_WIDTH = 720
interface Placed {
point: MinerSeriesPoint
x: number
y: number
}
function useMeasuredWidth(): [React.RefObject<HTMLDivElement | null>, number] {
const ref = useRef<HTMLDivElement>(null)
const [width, setWidth] = useState(FALLBACK_WIDTH)
useEffect(() => {
const node = ref.current
if (!node) return
const observer = new ResizeObserver(([entry]) => {
if (entry) setWidth(Math.max(320, entry.contentRect.width))
})
observer.observe(node)
return () => observer.disconnect()
}, [])
return [ref, width]
}
function timeLabel(ms: number, spanMs: number): string {
// A week of data wants dates; an hour wants clock time. Showing both at all
// ranges is noise, and showing neither leaves a time series with no time.
return new Date(ms).toLocaleString(undefined, {
...(spanMs > 86_400_000 ? { month: 'short', day: 'numeric' } : {}),
hour: '2-digit',
minute: '2-digit',
})
}
export function ShareChart({ points }: { points: MinerSeriesPoint[] }) {
const [wrap, width] = useMeasuredWidth()
const [hover, setHover] = useState<Placed | null>(null)
const chart = useMemo(() => {
if (points.length === 0) return null
const times = points.map((p) => new Date(p.at).getTime())
const t0 = Math.min(...times)
const t1 = Math.max(...times)
const span = t1 - t0 || 1
// The y-axis starts at zero — a share chart whose baseline floats makes a
// steady miner look volatile. Headroom above the peak keeps the line off
// the top edge.
const peak = Math.max(...points.map((p) => p.share), 0.0001)
const top = peak * 1.15
const plotW = width - PAD.left - PAD.right
const plotH = HEIGHT - PAD.top - PAD.bottom
const baseline = PAD.top + plotH
const x = (t: number) => PAD.left + ((t - t0) / span) * plotW
const y = (v: number) => baseline - (v / top) * plotH
const placed: Placed[] = points.map((point, i) => ({
point,
x: x(times[i] ?? t0),
y: y(point.share),
}))
const line = placed
.map((p, i) => `${i === 0 ? 'M' : 'L'}${p.x.toFixed(1)} ${p.y.toFixed(1)}`)
.join(' ')
const first = placed[0]
const last = placed[placed.length - 1]
const area =
first && last
? `${line} L${last.x.toFixed(1)} ${baseline} L${first.x.toFixed(1)} ${baseline} Z`
: ''
const yTicks = [0, top / 2, top].map((v) => ({ v, y: y(v) }))
// Three x labels — ends and middle. More would collide on a narrow panel,
// and the tooltip carries the exact time for any point.
const xTicks = [0, 0.5, 1].map((f) => ({ t: t0 + span * f, x: x(t0 + span * f) }))
return { placed, area, line, yTicks, xTicks, baseline, span, last }
}, [points, width])
if (!chart) {
return <p className="empty">No history recorded for this miner yet.</p>
}
const onMove = (event: React.PointerEvent<SVGSVGElement>) => {
const rect = event.currentTarget.getBoundingClientRect()
const local = event.clientX - rect.left
let nearest: Placed | null = null
let best = Infinity
for (const p of chart.placed) {
const d = Math.abs(p.x - local)
if (d < best) {
best = d
nearest = p
}
}
setHover(nearest)
}
return (
<div ref={wrap} style={{ position: 'relative' }}>
<svg
className="chart"
width={width}
height={HEIGHT}
viewBox={`0 0 ${width} ${HEIGHT}`}
role="img"
aria-label={`Share of network blocks over time, from ${share(chart.placed[0]?.point.share ?? 0)} to ${share(chart.last?.point.share ?? 0)}`}
onPointerMove={onMove}
onPointerLeave={() => setHover(null)}
>
{chart.yTicks.map((t) => (
<g key={t.v}>
<line className="grid" x1={PAD.left} x2={width - PAD.right} y1={t.y} y2={t.y} />
<text className="chart-axis" x={PAD.left - 8} y={t.y + 3.5} textAnchor="end">
{share(t.v)}
</text>
</g>
))}
{chart.xTicks.map((t, i) => (
<text
key={t.x}
className="chart-axis"
x={t.x}
y={HEIGHT - 8}
textAnchor={i === 0 ? 'start' : i === 2 ? 'end' : 'middle'}
>
{timeLabel(t.t, chart.span)}
</text>
))}
<path className="area" d={chart.area} />
<path className="line" d={chart.line} />
{hover && (
<>
<line className="crosshair" x1={hover.x} x2={hover.x} y1={PAD.top} y2={chart.baseline} />
{/* 2px surface ring so the marker stays legible where it sits on the
line; the ring is part of the hit target, not just spacing. */}
<circle className="marker" cx={hover.x} cy={hover.y} r={4.5} />
</>
)}
{/* One direct label, on the endpoint — the current value is the one a
reader is looking for. Labelling every point would be unreadable. */}
{!hover && chart.last && (
<text
className="chart-axis"
x={chart.last.x - 7}
// Clamped inside the plot area. A miner whose latest share is zero
// puts the endpoint on the baseline, and an unclamped label lands on
// top of the time axis.
y={Math.min(Math.max(chart.last.y - 9, PAD.top + 10), chart.baseline - 8)}
textAnchor="end"
style={{ fill: 'var(--data-bright)', fontSize: 11 }}
>
{share(chart.last.point.share)}
</text>
)}
</svg>
{hover && (
<div
className="tooltip"
style={{
left: hover.x,
top: 4,
// Flip past the midpoint so the tooltip never runs off the right
// edge of the panel.
transform: hover.x > width / 2 ? 'translate(-100%, 0)' : 'translate(10px, 0)',
}}
>
<div className="tooltip-label">{timeLabel(new Date(hover.point.at).getTime(), chart.span)}</div>
<div>
<strong>{share(hover.point.share)}</strong> of blocks
</div>
<div style={{ color: 'var(--text-secondary)' }}>
{hover.point.blocks} block{hover.point.blocks === 1 ? '' : 's'} ·{' '}
{hashrate(hover.point.hashrate_estimate)}
</div>
</div>
)}
</div>
)
}
+94
View File
@@ -0,0 +1,94 @@
/**
* The headline numbers.
*
* A KPI row of stat tiles, not a chart: these are five single current values,
* and a bar chart of five unrelated quantities would be a chart of nothing.
* Network hashrate leads as the hero figure because it is the one number that
* answers "how hard is this to win right now".
*/
import type { ChainSummary } from '../api/generated/ChainSummary'
import type { Window as WindowName } from '../api/generated/Window'
import { bigNumber, hashrate, height, seconds, windowSpan } from '../lib/format'
function Stat({
label,
value,
note,
hero,
noteClass,
title,
}: {
label: string
value: string
note?: string
hero?: boolean
noteClass?: string
title?: string
}) {
return (
<div className={hero ? 'stat stat-hero' : 'stat'}>
<div className="stat-label">{label}</div>
<div className="stat-value" title={title}>
{value}
</div>
<div className={noteClass ? `stat-note ${noteClass}` : 'stat-note'}>{note ?? ''}</div>
</div>
)
}
export function StatBar({
summary,
windowName,
}: {
summary: ChainSummary | null
windowName: WindowName
}) {
if (!summary) {
return (
<div className="stats">
{['Network hashrate', 'Difficulty', 'Block time', 'Height', 'Miners'].map((label) => (
<Stat key={label} label={label} value="—" />
))}
</div>
)
}
const interval = summary.block_interval_seconds ?? summary.target_block_time_seconds
const windowBlocks = { hour: 600, six_hours: 3600, day: 14400, week: 100800 }[windowName]
return (
<div className="stats">
<Stat
hero
label="Network hashrate"
value={hashrate(summary.network_hashrate)}
// Presenting an estimate as a measurement is the easiest way to lie
// with this number, so the tile says which it is every time.
note={summary.hashrate_from_target ? 'nominal — from target block time' : 'measured at tip'}
{...(summary.hashrate_from_target ? { noteClass: 'nominal' } : {})}
/>
<Stat
label="Difficulty"
value={bigNumber(summary.difficulty)}
note="expected hashes per block"
{...(summary.difficulty ? { title: summary.difficulty } : {})}
/>
<Stat
label="Block time"
value={seconds(summary.block_interval_seconds)}
note={`target ${seconds(summary.target_block_time_seconds)}`}
/>
<Stat label="Height" value={height(summary.height)} note="best block seen" />
<Stat
label="Miners"
value={String(summary.distinct_miners)}
note={
summary.telemetry_nodes !== null
? `${summary.telemetry_nodes} node${summary.telemetry_nodes === 1 ? '' : 's'} on telemetry`
: `winning in ${windowSpan(windowBlocks, interval)}`
}
/>
</div>
)
}