Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -120,6 +120,8 @@ AWS account/region changes take effect after an agent restart.

**Mainnet** is a deliberately limited observer board, not a mainnet-support-fleet monitor. A separately managed Evolution fullnode observer reports Core ChainLocks and stall state, Platform block progress and stall state, the public quorum-list-server, and the count of large PoSe bans. The `mainnet-support` EC2 fleet is not discovered or probed by this application, and no Mainnet operations are exposed. The observer report is token-scoped and contains only public chain/service facts. The web container reads `MAINNET_REPORT_TOKEN` from `/etc/dash-status/mainnet.env`; the observer host uses the same secret in `/etc/dash-mainnet-observer/env`. Install `deploy/dash-mainnet-observer.service` only on the dedicated observer/fullnode host.

**Genesis sync** is one tile on the Testnet and Mainnet pages. A separate host replays Platform from block 1 with the newest published Drive every night ([dashpay/infra, `platform-sync`](https://github.com/dashpay/infra/tree/master/platform-sync)) and posts where its node is and how the last replay ended to `/api/platform-sync/report`. The report is token-scoped (`PLATFORM_SYNC_REPORT_TOKEN`, read by the web container from `/etc/dash-status/mainnet.env`; the sync host keeps the same secret in `/etc/platform-sync/report-token`), schema-checked, and holds only public facts. A report older than 15 minutes shows as `no report`.

## Infrastructure pages

Visible to any account with access (any role).
Expand Down
53 changes: 53 additions & 0 deletions server/platform-sync.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
import { readFileSync } from 'node:fs';
import { join } from 'node:path';

// The nightly from-genesis Platform sync (dashpay/infra, platform-sync) pushes
// where its node is and how the last replay ended. Public-data-only boundary:
// the result is served to anonymous callers, so only allowlisted, type-checked
// fields survive. No host name, path, container name or request id passes.
export const SYNC_NETWORKS = ['testnet', 'mainnet'];
const PHASES = ['idle', 'starting', 'syncing', 'verifying', 'following', 'failed'];
const RESULTS = ['passed', 'failed'];
const BYTES = ['internetRx', 'internetTx', 'platformRx', 'platformTx', 'coreRx', 'coreTx', 'image'];
const FRESH_MS = 180_000, STALE_MS = 15 * 60_000;

const integer = (v) => (Number.isSafeInteger(v) && v >= 0 ? v : null);
const finite = (v) => (Number.isFinite(v) && v >= 0 ? v : null);
const boolean = (v) => (typeof v === 'boolean' ? v : null);
const enumeration = (v, allowed) => (allowed.includes(v) ? v : null);
const timestamp = (v) => (typeof v === 'string' && /^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(\.\d+)?Z$/.test(v) && Number.isFinite(Date.parse(v)) ? new Date(v).toISOString() : null);
const match = (v, re) => (typeof v === 'string' && re.test(v) ? v : null);
// The reason can quote a log line. Printable ASCII only, and short.
const reason = (v) => (typeof v === 'string' ? v.replace(/[^\x20-\x7e]/g, ' ').slice(0, 300) : null);
Comment thread
ktechmidas marked this conversation as resolved.
Resolved
const VERSION = /^[\w.+-]{1,40}$/, IMAGE = /^[\w./:@-]{1,200}$/, REVISION = /^[0-9a-f]{40}$/;

const image = (i) => (i && typeof i === 'object' ? { ref: match(i.ref, IMAGE), version: match(i.version, VERSION), revision: match(i.revision, REVISION) } : null);

function run(r) {
if (!r || typeof r !== 'object') return null;
return { result: enumeration(r.result, RESULTS), reason: reason(r.reason), startedAt: timestamp(r.startedAt), finishedAt: timestamp(r.finishedAt),
durationSeconds: integer(r.durationSeconds), height: integer(r.height), image: image(r.image), tenderdash: match(r.tenderdash, VERSION),
bytes: Object.fromEntries(BYTES.map((k) => [k, integer(r.bytes?.[k])])) };
}

export function validatePlatformSyncReport(input, now = Date.now()) {
if (!input || input.schema !== 1 || !SYNC_NETWORKS.includes(input.network)) throw new Error('platform-sync report for testnet or mainnet required');
const at = timestamp(input.updatedAt);
if (!at || Date.parse(at) > now + 60_000 || now - Date.parse(at) > FRESH_MS) throw new Error('platform-sync report timestamp invalid or stale');
const phase = enumeration(input.phase, PHASES);
if (!phase) throw new Error('platform-sync phase unknown');
const progress = finite(input.progress);
return { network: input.network, generatedAt: at, phase, healthy: boolean(input.healthy), onHold: input.hold != null && input.hold !== false,
height: integer(input.height), referenceHeight: integer(input.referenceHeight), progress: progress !== null && progress <= 1 ? progress : null,
blocksPerSecond: finite(input.blocksPerSecond), etaSeconds: integer(input.etaSeconds), run: run(input.run), lastPassed: run(input.lastPassed) };
}

// Freshness is decided on every read: a stored report outlives the host that sent it.
export function readGenesisSync(dataDir, name, now = Date.now()) {
if (!SYNC_NETWORKS.includes(name)) return null;
try {
const report = JSON.parse(readFileSync(join(dataDir, 'state', `platform-sync-${name}.json`), 'utf8'));
const at = Date.parse(report.generatedAt);
return Number.isFinite(at) ? { ...report, stale: now - at > STALE_MS } : null;
} catch { return null; }
}
58 changes: 58 additions & 0 deletions server/platform-sync.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { mkdtempSync, mkdirSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { readGenesisSync, validatePlatformSyncReport } from './platform-sync.js';

const now = Date.parse('2026-11-21T01:00:00Z');
const at = (minutesAgo) => new Date(now - minutesAgo * 60_000).toISOString().replace('.000Z', 'Z');
const report = (over = {}) => ({ schema: 1, network: 'testnet', updatedAt: at(0), phase: 'syncing', hold: null, height: 400000, referenceHeight: 720000,
progress: 0.5556, blocksPerSecond: 31.5, etaSeconds: 10158, healthy: null,
core: { height: 1595500, headers: 1595500, syncing: false }, disk: { sizeGiB: 117.6, usedGiB: 60, freeGiB: 57.6 },
run: { id: 'gh-123-1-testnet', network: 'testnet', requestedImage: 'auto', result: null, reason: null, startedAt: at(200),
image: { ref: 'dashpay/drive:5.1.0-dev.2', id: 'sha256:abc', source: 'release', version: '5.1.0-dev.2', revision: 'a'.repeat(40), notes: ['x'] },
tenderdash: '2.0.0-dev.3', restarts: { drive_abci: 0 }, bytes: { internetRx: 1700000000, internetTx: 30000, platformRx: 1500000000, platformTx: 20000, coreRx: 100, coreTx: 5, image: 62113044 } },
lastPassed: { id: 'gh-100-1-testnet', finishedAt: at(1500), durationSeconds: 21000, height: 715000, image: { ref: 'dashpay/drive:5.1.0-dev.1', version: '5.1.0-dev.1' } },
...over });

test('a report keeps only the allowlisted public fields', () => {
const r = validatePlatformSyncReport(report(), now);
assert.deepEqual(Object.keys(r).sort(), ['blocksPerSecond', 'etaSeconds', 'generatedAt', 'healthy', 'height', 'lastPassed', 'network', 'onHold', 'phase', 'progress', 'referenceHeight', 'run']);
assert.deepEqual(r.run.image, { ref: 'dashpay/drive:5.1.0-dev.2', version: '5.1.0-dev.2', revision: 'a'.repeat(40) });
assert.equal(r.run.id, undefined);
assert.equal(r.run.bytes.platformRx, 1500000000);
assert.equal(r.run.bytes.internetRx, 1700000000);
assert.equal(r.lastPassed.height, 715000);
assert.equal(r.onHold, false);
assert.equal(JSON.stringify(r).includes('gh-123'), false);
});

test('malformed values become null, not text on a public page', () => {
const r = validatePlatformSyncReport(report({ height: -1, progress: 7, hold: 'someone is reading the stores',
run: { result: 'exploded', reason: 'AppHash mismatch: <script>\u0007\n' + 'x'.repeat(400), image: { ref: 'a b', version: '<b>', revision: 'zz' }, bytes: { platformRx: '5' } } }), now);
assert.equal(r.height, null);
assert.equal(r.progress, null);
assert.equal(r.onHold, true);
assert.equal(r.run.result, null);
assert.equal(r.run.reason.length, 300);
assert.match(r.run.reason, /^[\x20-\x7e]+$/);
assert.deepEqual(r.run.image, { ref: null, version: null, revision: null });
assert.equal(r.run.bytes.platformRx, null);
});

test('wrong network, schema, phase and old timestamps are refused', () => {
for (const bad of [report({ network: 'devnet-x' }), report({ schema: 2 }), report({ phase: 'dancing' }), report({ updatedAt: at(4) }), report({ updatedAt: at(-2) }), report({ updatedAt: 'yesterday' }), null])
assert.throws(() => validatePlatformSyncReport(bad, now));
});

test('a stored report goes stale by the clock of the reader', () => {
const dataDir = mkdtempSync(join(tmpdir(), 'psync-'));
mkdirSync(join(dataDir, 'state'));
assert.equal(readGenesisSync(dataDir, 'testnet', now), null);
writeFileSync(join(dataDir, 'state', 'platform-sync-testnet.json'), JSON.stringify(validatePlatformSyncReport(report(), now)));
assert.equal(readGenesisSync(dataDir, 'testnet', now + 60_000).stale, false);
assert.equal(readGenesisSync(dataDir, 'testnet', now + 16 * 60_000).stale, true);
assert.equal(readGenesisSync(dataDir, 'mainnet', now), null);
assert.equal(readGenesisSync(dataDir, '../settings', now), null);
});
20 changes: 18 additions & 2 deletions server/web.js
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ import { createApiTokens, presentsApiToken } from './api-tokens.js';
import { devnetFiles } from '../shared/devnet-files.js';
import { validateRequest } from '../agent/ops.js';
import { validateMainnetReport } from '../shared/mainnet.js';
import { readGenesisSync, validatePlatformSyncReport } from './platform-sync.js';

const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/;

Expand All @@ -46,7 +47,7 @@ export function ttlCache(clock, ttl = 15_000) {
return Object.assign(cached, { delete: (key) => entries.delete(key), size: () => entries.size });
}

export function createWeb({ dataDir, origin, auth: authDeps, fetcher = fetch, clock = Date.now, ciGithub = null, ciQueue = {}, mainnetReportToken = process.env.MAINNET_REPORT_TOKEN, keyReader = requestDevnetKeys, keySocket = process.env.DEVNET_KEYS_SOCKET } = {}) {
export function createWeb({ dataDir, origin, auth: authDeps, fetcher = fetch, clock = Date.now, ciGithub = null, ciQueue = {}, mainnetReportToken = process.env.MAINNET_REPORT_TOKEN, platformSyncReportToken = process.env.PLATFORM_SYNC_REPORT_TOKEN, keyReader = requestDevnetKeys, keySocket = process.env.DEVNET_KEYS_SOCKET } = {}) {
const settingsPath = join(dataDir, 'settings.json');
const dirs = { state: join(dataDir, 'state'), requests: join(dataDir, 'requests'), ops: join(dataDir, 'ops') };
for (const d of Object.values(dirs)) mkdirSync(d, { recursive: true });
Expand Down Expand Up @@ -151,6 +152,21 @@ export function createWeb({ dataDir, origin, auth: authDeps, fetcher = fetch, cl
} catch (e) { res.status(400).json({ error: e.message }); }
});

// The from-genesis sync host (dashpay/infra, platform-sync) reports the same
// way: its own token, an explicit schema, public facts only.
app.post('/api/platform-sync/report', (req, res) => {
if (!platformSyncReportToken || req.get('authorization') !== `Bearer ${platformSyncReportToken}`) return res.status(401).json({ error: 'platform-sync authorization required' });
try {
const report = validatePlatformSyncReport(req.body, clock());
const file = join(dirs.state, `platform-sync-${report.network}.json`);
const previous = readJSON(file);
if (previous?.generatedAt && Date.parse(report.generatedAt) < Date.parse(previous.generatedAt)) throw new Error('out-of-order report');
writeAtomic(file, JSON.stringify(report));
push('network', { name: report.network, at: report.generatedAt });
res.status(202).json({ accepted: true, generatedAt: report.generatedAt });
} catch (e) { res.status(400).json({ error: e.message }); }
});

// Who is asking: an API token (req.bot) or the signed-in browser session.
const principal = (req) => req.bot || auth.session(req);
const user = (req) => principal(req)?.user || null;
Expand Down Expand Up @@ -220,7 +236,7 @@ export function createWeb({ dataDir, origin, auth: authDeps, fetcher = fetch, cl
app.get('/api/networks/:name', (req, res) => {
const n = visible(req).find((x) => x.name === req.params.name);
if (!n) return res.status(404).json({ error: 'Network not found' });
res.json(view(n, isMember(req, n.name)));
res.json({ ...view(n, isMember(req, n.name)), genesisSync: readGenesisSync(dataDir, n.name, clock()) });
});

// Live updates: agent state rewrites and operation changes are pushed.
Expand Down
23 changes: 22 additions & 1 deletion server/web.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ async function start(userId = 9920871, extraUsers = [], options = {}) {
: url.includes('/users/octocat') ? Response.json({ id: 583231, login: 'octocat', name: 'The Octocat', type: 'User', avatar_url: 'https://avatars.githubusercontent.com/u/583231' })
: url.includes('/users/') ? new Response('{}', { status: 404 }) : Response.json({ id: userId, login: 'someone' });
const origin = 'http://127.0.0.1';
const app = createWeb({ dataDir, origin, mainnetReportToken: 'fixture-mainnet-token', auth: { clientId: 'c', clientSecret: 's', fetcher: github }, fetcher: github, ...options });
const app = createWeb({ dataDir, origin, mainnetReportToken: 'fixture-mainnet-token', platformSyncReportToken: 'fixture-sync-token', auth: { clientId: 'c', clientSecret: 's', fetcher: github }, fetcher: github, ...options });
const server = await new Promise((r) => { const s = app.listen(0, '127.0.0.1', () => r(s)); });
const base = `http://127.0.0.1:${server.address().port}`;
let cookie = '';
Expand Down Expand Up @@ -49,6 +49,27 @@ test('public board needs no session and hides operator fields', async () => {
} finally { w.close(); }
});

test('genesis sync report is token-scoped and appears on its network only', async () => {
const w = await start();
try {
const post = (body, token) => w.req('/api/platform-sync/report', { method: 'POST', body: JSON.stringify(body), headers: { 'content-type': 'application/json', ...(token ? { authorization: `Bearer ${token}` } : {}) } });
const body = { schema: 1, network: 'testnet', updatedAt: new Date().toISOString().replace(/\.\d+Z$/, 'Z'), phase: 'following', healthy: true, height: 720000, referenceHeight: 720001,
run: { id: 'gh-1-1-testnet', result: 'passed', finishedAt: new Date().toISOString(), durationSeconds: 21000, image: { ref: 'dashpay/drive:5.1.0-dev.2', version: '5.1.0-dev.2' }, bytes: { platformRx: 3000000000 } } };
assert.equal((await w.req('/api/networks/testnet').then((r) => r.json())).genesisSync, null);
assert.equal((await post(body)).status, 401);
assert.equal((await post(body, 'fixture-mainnet-token')).status, 401);
assert.equal((await post({ ...body, network: 'devnet-x' }, 'fixture-sync-token')).status, 400);
assert.equal((await post(body, 'fixture-sync-token')).status, 202);
const g = (await (await w.req('/api/networks/testnet')).json()).genesisSync;
assert.equal(g.run.result, 'passed');
assert.equal(g.run.image.version, '5.1.0-dev.2');
assert.equal(g.run.id, undefined);
assert.equal(g.stale, false);
assert.equal((await (await w.req('/api/networks/mainnet')).json()).genesisSync, null);
assert.equal((await post({ ...body, updatedAt: new Date(Date.now() - 60_000).toISOString() }, 'fixture-sync-token')).status, 400);
} finally { w.close(); }
});

test('mainnet observer report is token-scoped and appears as limited signals', async () => {
const w = await start();
try {
Expand Down
33 changes: 33 additions & 0 deletions src/pages/Network.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,7 @@ export default function Network({ name, tab }) {
<Stat label="PoSe bans" value={s.mainnet.bigBans ?? '—'} sub={`${s.mainnet.newBans ?? '—'} newly banned / hour`} level={(s.mainnet.newBans || 0) >= 20 ? 'warn' : undefined} />
<Stat label="Chain stalls" value={s.mainnet.platformSyncing ? 'syncing' : s.mainnet.coreStall || s.mainnet.platformStall ? 'stalled' : s.mainnet.coreStall == null || s.mainnet.platformStall == null ? 'unknown' : 'clear'} sub={s.mainnet.chainLockAgeSeconds != null ? `ChainLock ${Math.round(s.mainnet.chainLockAgeSeconds)}s old` : 'ChainLock age unavailable'} level={s.mainnet.coreStall || s.mainnet.platformStall ? 'down' : undefined} />
</>}
{n.genesisSync && <GenesisSync g={n.genesisSync} now={now} />}
</div>

{(n.endpoints.length > 0 || Object.keys(s.versions).length > 0) && (
Expand Down Expand Up @@ -88,6 +89,38 @@ export default function Network({ name, tab }) {
);
}

// The nightly replay of Platform from block 1 with the newest published Drive
// (dashpay/infra, platform-sync). One tile; the detail is in its tooltip.
function GenesisSync({ g, now }) {
const run = g.run, last = g.lastPassed, image = run?.image || last?.image;
const version = image?.version || '—';
const running = ['starting', 'syncing', 'verifying'].includes(g.phase);
// The page does not refetch on a timer, so a report that stops arriving goes stale by this clock (same 15 minutes as the server).
const stale = g.stale || now - Date.parse(g.generatedAt) > 15 * 60_000;
// A failed phase is a failure even when the report carries no run record.
const result = run?.result || (g.phase === 'failed' ? 'failed' : null);
const value = stale ? 'no report' : running ? (g.progress != null ? `${Math.floor(g.progress * 100)}%` : 'starting') : result || '—';
const sub = stale ? `last heard ${ago(g.generatedAt, now)} ago`
: running ? `${version} · ${num(g.height)}${g.etaSeconds != null ? ` · ${duration(g.etaSeconds)} left` : ''}`
: run?.finishedAt ? `${version} · ${ago(run.finishedAt, now)} ago` : version;
const level = stale || (g.phase === 'following' && g.healthy === false) ? 'warn' : result === 'failed' ? 'down' : result === 'passed' ? 'ok' : undefined;
// internetRx is what the stack's firewall counted; older reports only carry p2p message sizes.
const received = run?.bytes ? (run.bytes.internetRx != null ? ['internetRx', 'image'] : ['platformRx', 'coreRx', 'image']).reduce((a, k) => a + (run.bytes[k] || 0), 0) : null;
const title = ['Platform replayed from genesis with the newest published Drive',
image?.ref && `image ${image.ref}${image.revision ? ` (${short(image.revision, 10)})` : ''}`,
run?.tenderdash && `Tenderdash ${run.tenderdash}`,
g.height != null && `height ${num(g.height)} of ${num(g.referenceHeight)}`,
running && g.blocksPerSecond != null && `${g.blocksPerSecond} blocks/s`,
run?.durationSeconds != null && `replay took ${duration(run.durationSeconds)}`,
received ? `${bytes(received)} received` : null,
run?.reason,
g.phase === 'following' && g.healthy === false && 'the node stopped following the tip after it passed',
g.onHold && 'on hold: the next run is refused',
run?.result !== 'passed' && last?.finishedAt && `last passed ${last.image?.version || ''} ${ago(last.finishedAt, now)} ago`,
].filter(Boolean).join('\n');
return <Stat label="Genesis sync" value={value} sub={sub} level={level} title={title} />;
}

function Monitoring({ m }) {
const checks = (v) => v?.total === 0 ? 'no targets' : v ? `${v.observed - v.failed}/${v.total} passed${v.failed ? ` · ${v.failed} failed` : ''}${v.total > v.observed ? ` · ${v.total - v.observed} unobserved` : ''}` : 'unobserved';
const rows = [
Expand Down
Loading