diff --git a/docs/images/testnet-peer-registry.png b/docs/images/testnet-peer-registry.png new file mode 100644 index 00000000..f4532422 Binary files /dev/null and b/docs/images/testnet-peer-registry.png differ diff --git a/node/production/operator-status.md b/node/production/operator-status.md index b4dcc77e..2d807d1e 100644 --- a/node/production/operator-status.md +++ b/node/production/operator-status.md @@ -57,6 +57,12 @@ Zero is an observed balance. A timeout, wrong chain or invalid reply returns exi For offline gas caps from the same selected installation, use [`gas-policy`](gas-policy.md) instead of `status`. +### Compare the selected address with the testnet registry + +Choose **View public registry** in the health table. The viewer fetches the current [public testnet address book](peers/README.md) from the official repository and marks the selected node address if it is listed. An IPFS-only profile can still browse the table. Entries are routing information, not a check that a node is online or authorized by your installation. + +Watching health does not fetch the registry. Reload the registry page for a fresh read. Concurrent reads share one download, limited to ten seconds and 1 MiB. An unavailable list is reported as an error rather than an empty table. Listed endpoints are displayed as text and are never contacted. + ## Results and recovery - Exit **0**: matching direct `ready`/`busy`, or matching worker `idle`/`processing` with a fresh poll. diff --git a/node/production/peers/README.md b/node/production/peers/README.md index 70115de0..7f782f5c 100644 --- a/node/production/peers/README.md +++ b/node/production/peers/README.md @@ -40,7 +40,7 @@ Once this feature is merged into upstream `main`, new or existing operators can node node/production/scripts/peer-directory.mjs fetch ``` -`fetch` reads only the fixed official GitHub source, with a ten-second timeout and no redirects. It prints the list only after a successful HTTP response and basic JSON/record checks. It does not contact listed nodes. Exit codes are 0 for success, 1 for loading failure and 2 for incorrect arguments. +`fetch` reads only the fixed official GitHub source, with a ten-second timeout, a 1 MiB response limit and no redirects. It prints the list only after a successful HTTP response and basic JSON/record checks. It does not contact listed nodes. Exit codes are 0 for success, 1 for loading failure and 2 for incorrect arguments. To save a refreshed copy without losing an existing copy on a failed download, run this from the directory where you keep the public registry: diff --git a/node/production/scripts/operator-view.mjs b/node/production/scripts/operator-view.mjs index 19c28eef..1270edec 100644 --- a/node/production/scripts/operator-view.mjs +++ b/node/production/scripts/operator-view.mjs @@ -1,4 +1,5 @@ import { createServer } from 'node:http'; +import { fetchDirectory } from './peer-directory.mjs'; import { loadProfile } from './operator-profile.mjs'; import { operatorStatus } from './operator-status.mjs'; @@ -10,11 +11,26 @@ function text(value) { return String(value).replaceAll('&', '&').replaceAll('<', '<').replaceAll('>', '>'); } +async function registryPage(selected) { + const nodes = await fetchDirectory(); + const matches = node => selected && node.nodeAddress.toLowerCase() === selected.toLowerCase(); + const identity = !selected ? 'No node address selected in this profile.' : nodes.some(matches) + ? 'The selected address is listed.' : 'The selected address is not listed.'; + const rows = nodes.map(node => `${text(node.nodeAddress)}${matches(node) ? ' (selected)' : ''}` + + `${text(node.url)}${text(node.target)}`).join(''); + return `Testnet peer registry +
Local node health +

Testnet peer registry

Public address book from the Oya repository on GitHub. Listing does not indicate whether a node is online.

+

${identity}

${rows ? `${rows}
Node addressInbox endpointInbox target
` : '

No entries in the testnet registry.

'} +

Read at ${new Date().toISOString()}. Reload to fetch again.

`; +} + async function observe(profile) { const status = await operatorStatus(profile); const rows = Object.entries(labels).filter(([key]) => status[key] !== null).map(([key, label]) => `${label}${typeof status[key] === 'boolean' - ? (status[key] ? ' Yes' : 'No') : text(status[key])}`).join('\n'); + ? (status[key] ? ' Yes' : 'No') : text(status[key])}`) + .concat('Testnet peersView public registry').join('\n'); return `Local node health

Local node health

${text(status.message)}

${rows}
@@ -31,6 +47,12 @@ function serve(profile) { if (req.headers.host !== `127.0.0.1:${server.address().port}` || req.headers['sec-fetch-site'] === 'cross-site') { return res.writeHead(403).end(); } + if (req.method === 'GET' && req.url === '/peers') { + try { + const html = await registryPage(profile.nodeAddress); + return res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' }).end(html); + } catch { return res.writeHead(503).end('Testnet registry unavailable. Reload to retry.'); } + } if (req.method !== 'GET') return res.writeHead(405, { Allow: 'GET' }).end(); if (req.url !== '/') return res.writeHead(404).end(); try { diff --git a/node/production/scripts/peer-directory.mjs b/node/production/scripts/peer-directory.mjs index 27d260fa..a82bfe2d 100644 --- a/node/production/scripts/peer-directory.mjs +++ b/node/production/scripts/peer-directory.mjs @@ -1,31 +1,52 @@ -import { readFile } from 'node:fs/promises'; +import { readFile, realpath } from 'node:fs/promises'; const registry = new URL('../peers/testnet-directory.json', import.meta.url); const upstream = 'https://raw.githubusercontent.com/oyaprotocol/oya-commitments/main/node/production/peers/testnet-directory.json'; -const [command = 'list', ...args] = process.argv.slice(2); -if (!((command === 'list' && args.length <= 1) || (command === 'fetch' && args.length === 0))) { - console.error('Usage: peer-directory.mjs [list [FILE] | fetch]'); - process.exitCode = 2; -} else { - try { - let text; - if (command === 'fetch') { - const response = await fetch(upstream, { redirect: 'error', signal: AbortSignal.timeout(10_000) }); - if (!response.ok) throw new Error('Download failed'); - text = await response.text(); - } else { - text = await readFile(args[0] ?? registry, 'utf8'); - } - const nodes = JSON.parse(text); - // Catch accidental file/response errors; repository review establishes trust. - if (!Array.isArray(nodes) || !nodes.every(node => node && - ['nodeAddress', 'url', 'target'].every(key => typeof node[key] === 'string' && node[key].length > 0))) { - throw new Error('Expected node records'); +function parseDirectory(text) { + const nodes = JSON.parse(text); + // Catch accidental file/response errors; repository review establishes trust. + if (!Array.isArray(nodes) || !nodes.every(node => node && + ['nodeAddress', 'url', 'target'].every(key => typeof node[key] === 'string' && node[key].length > 0))) { + throw new Error('Expected node records'); + } + return nodes; +} + +// All callers read the same public URL. Share an active download, not a stale result. +let download; +export function fetchDirectory() { + return download ??= readUpstream().finally(() => { download = undefined; }); +} + +async function readUpstream() { + const response = await fetch(upstream, { redirect: 'error', signal: AbortSignal.timeout(10_000) }); + if (!response.ok) { + await response.body?.cancel(); + throw new Error('Download failed'); + } + const chunks = []; + let size = 0; + for await (const chunk of response.body) { + size += chunk.length; + if (size > 1048576) throw new Error('Registry exceeds 1 MiB'); + chunks.push(chunk); + } + return parseDirectory(new TextDecoder('utf-8', { fatal: true }).decode(Buffer.concat(chunks, size))); +} + +if (process.argv[1] && import.meta.filename === await realpath(process.argv[1]).catch(() => null)) { + const [command = 'list', ...args] = process.argv.slice(2); + if (!((command === 'list' && args.length <= 1) || (command === 'fetch' && args.length === 0))) { + console.error('Usage: peer-directory.mjs [list [FILE] | fetch]'); + process.exitCode = 2; + } else { + try { + const nodes = command === 'fetch' ? await fetchDirectory() : parseDirectory(await readFile(args[0] ?? registry, 'utf8')); + console.log(JSON.stringify(nodes, null, 2)); + } catch { + console.error('Unable to load peer registry. Check the file or retry the upstream fetch.'); + process.exitCode = 1; } - console.log(JSON.stringify(nodes, null, 2)); - } catch { - console.error('Unable to load peer registry. Check the file or retry the upstream fetch.'); - process.exitCode = 1; } } diff --git a/node/production/test/operator-registry-view.test.mjs b/node/production/test/operator-registry-view.test.mjs new file mode 100644 index 00000000..a3c0b6fa --- /dev/null +++ b/node/production/test/operator-registry-view.test.mjs @@ -0,0 +1,63 @@ +import assert from 'node:assert/strict'; +import { spawn } from 'node:child_process'; +import { once } from 'node:events'; +import { mkdtemp, readFile, rm, writeFile } from 'node:fs/promises'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { fileURLToPath } from 'node:url'; +import test from 'node:test'; + +const viewer = fileURLToPath(new URL('../scripts/operator-view.mjs', import.meta.url)); +const address = `0x${'ab'.repeat(20)}`; +const entry = { nodeAddress: `0x${'AB'.repeat(20)}`, url: 'https://one.example/v1/jobs', target: 'alpha' }; + +for (const mode of ['ledger', 'ipfs']) { + test(`registry view (${mode}) reads upstream only on demand, distinguishes absence from failure, and recovers`, { timeout: 12000 }, async t => { + const dir = await mkdtemp(join(tmpdir(), 'registry-view-')); + const profile = join(dir, 'operator.json'), preload = join(dir, 'mock.mjs'), data = join(dir, 'response'), calls = join(dir, 'calls'); + t.after(() => rm(dir, { recursive: true, force: true })); + await writeFile(join(dir, 'node.json'), JSON.stringify(mode === 'ipfs' ? { mode } : { mode, chainId: 1, ledgerContract: address })); + await writeFile(profile, JSON.stringify({ version: 1, role: 'direct', nodeConfig: 'node.json', healthUrl: 'http://127.0.0.1:1/healthz', + ...(mode === 'ledger' ? { nodeAddress: address } : {}) }), { mode: 0o600 }); + await writeFile(calls, ''); + await writeFile(preload, `import { appendFile, readFile } from 'node:fs/promises'; + import { setTimeout } from 'node:timers/promises'; + globalThis.fetch = async (url, options) => { + await appendFile(${JSON.stringify(calls)}, url+'\\n'); + if (url !== 'https://raw.githubusercontent.com/oyaprotocol/oya-commitments/main/node/production/peers/testnet-directory.json' + || options.redirect !== 'error' || options.headers || !options.signal) throw new Error('Unexpected fetch'); + await setTimeout(50); + return new Response(await readFile(${JSON.stringify(data)})); + };`); + const child = spawn(process.execPath, ['--import', preload, viewer, '--profile', profile], { cwd: dir, stdio: ['ignore', 'pipe', 'ignore'] }); + t.after(() => child.kill()); + const [line] = await once(child.stdout, 'data'); + const root = line.toString().trim(), peers = root + 'peers'; + assert.match(await (await fetch(root)).text(), /href="\/peers"/); + assert.equal((await fetch(peers, { method: 'POST' })).status, 405); + assert.equal((await fetch(peers, { headers: { 'sec-fetch-site': 'cross-site' } })).status, 403); + assert.equal((await fetch(peers + '?source=other')).status, 404); + assert.equal(await readFile(calls, 'utf8'), ''); + await writeFile(data, JSON.stringify([{ ...entry, target: '', extra: 'ignored-field' }])); + const [a, b] = await Promise.all([fetch(peers), fetch(peers)]); + assert.equal(a.status, 200); + const html = await a.text(); + assert.equal(b.status, 200); + assert.match(await b.text(), /<one & two>/); + assert.equal((await readFile(calls, 'utf8')).trim().split('\n').length, 1); + assert.match(html, /<one & two>/); + assert.match(html, /https:\/\/one\.example\/v1\/jobs/); + assert.doesNotMatch(html, /href="https:|ignored-field||http-equiv="refresh"/); + assert.match(html, mode === 'ledger' ? /The selected address is listed/ : /No node address selected/); + await writeFile(data, 'invalid-sentinel'); + const error = await fetch(peers); + assert.equal(error.status, 503); + assert.match(await error.text(), /^Testnet registry unavailable\. Reload to retry\.$/); + await writeFile(data, '[]'); + const empty = await fetch(peers); + assert.equal(empty.status, 200); + const page = await empty.text(); + assert.match(page, /No entries in the testnet registry/); + if (mode === 'ledger') assert.match(page, /The selected address is not listed/); + }); +} diff --git a/node/production/test/peer-directory.test.mjs b/node/production/test/peer-directory.test.mjs index 00041094..f4c23d5c 100644 --- a/node/production/test/peer-directory.test.mjs +++ b/node/production/test/peer-directory.test.mjs @@ -1,6 +1,6 @@ import assert from 'node:assert/strict'; import { spawnSync } from 'node:child_process'; -import { mkdtempSync, readFileSync, readdirSync, rmSync, writeFileSync } from 'node:fs'; +import { mkdtempSync, readFileSync, readdirSync, rmSync, symlinkSync, writeFileSync } from 'node:fs'; import { tmpdir } from 'node:os'; import { join } from 'node:path'; import { fileURLToPath } from 'node:url'; @@ -28,6 +28,11 @@ test('default loads the bundled registry from any working directory without netw assert.equal(result.status, 0, result.stderr); assert.deepEqual(JSON.parse(result.stdout), JSON.parse(readFileSync(official, 'utf8'))); assert.equal(result.stderr, ''); + const link = join(f.dir, 'peer-list.mjs'); + symlinkSync(cli, link); + const linked = spawnSync(process.execPath, [link], { cwd: f.dir, encoding: 'utf8', timeout: 5000 }); + assert.equal(linked.status, 0, linked.stderr); + assert.equal(linked.stdout, result.stdout); }); test('local list preserves records and recovers from malformed or missing files', t => { @@ -74,7 +79,8 @@ test('failed fetches emit no partial list and do not change an existing copy', t 'return new Response("private-marker", {status: 500})', 'return new Response("not JSON")', 'return new Response("{}")', - 'return {ok: true, text: async () => { throw new Error("body interrupted"); }}', + 'return new Response(new ReadableStream({ start(c) { c.error(new Error("body interrupted")); } }))', + 'return new Response("[]" + " ".repeat(1048576))', 'await new Promise((resolve, reject) => options.signal.addEventListener("abort", () => reject(options.signal.reason)))', ]) { f.mock(`const timeout = AbortSignal.timeout; @@ -96,12 +102,10 @@ test('deadline also covers response body reading', t => { const f = fixture(t); f.mock(`const timeout = AbortSignal.timeout; AbortSignal.timeout = () => timeout(20); - globalThis.fetch = async (url, options) => ({ok: true, text: async () => { - const hold = setTimeout(() => {}, 500); - try { - await new Promise((resolve, reject) => options.signal.addEventListener('abort', () => reject(options.signal.reason))); - } finally { clearTimeout(hold); } - }});`); + globalThis.fetch = async (url, options) => new Response(new ReadableStream({ start(controller) { + const hold = setTimeout(() => { controller.enqueue(new TextEncoder().encode('[]')); controller.close(); }, 500); + options.signal.addEventListener('abort', () => { clearTimeout(hold); controller.error(options.signal.reason); }); + }}));`); const result = f.run('fetch'); assert.equal(result.status, 1, result.stderr); assert.equal(result.stdout, ''); diff --git a/plans/peer-directory-v1-execplan.md b/plans/peer-directory-v1-execplan.md index 3a7c5561..7dd22e70 100644 --- a/plans/peer-directory-v1-execplan.md +++ b/plans/peer-directory-v1-execplan.md @@ -20,6 +20,11 @@ Keep the repository's trusted public node addresses and receive endpoints in a s - [x] 2026-11-14: Candidate revision v2 incorporates pemulis comments 4571803463, 4571811963 and 4571834696: receiver-local policy may queue publication; optional batching is preferred next, with periodic peer test messages as an alternative. Supersedes the prior message-only isolation candidate; documentation only. - [ ] Human review and merge; release and deployment remain separate operations. +- [x] 2026-12-01 19:37Z: For the browser milestone, traced the operator request in #236 to the reviewed testnet address book in #161 and its existing host CLI. Local inbox authorization files do not define this list. +- [x] 2026-12-01 19:42Z: Added a local `/peers` page. The focused viewer and CLI tests pass with populated, empty and unavailable registry responses. + +- [x] 2026-12-01 19:44Z: Node 24.22.3 passed all 702 production tests and all 707 tests in a trial merge with #259. The extracted viewer fetched the official empty list without installed packages. Captured the populated page with two example entries. + ## Surprises & Discoveries The initial milestone made review of a trusted temporary address book harder than editing the list. Revision fixtures also depended on the mutable official roster. Separate schema-only and base-aware CI paths could disagree, while existing release CI reuse accepted a successful run for the same commit. Removing the introduced domain/revision policy removes both defects without changing preexisting release gates. @@ -42,6 +47,8 @@ The requested `url` records failed both local loading and mocked upstream fetchi ## Outcomes & Retrospective +For the browser milestone, the operator can now distinguish a selected address, an empty address book and a failed read without leaving local status. The existing CLI and viewer share the same source. No new bundle asset or configuration was necessary. On macOS, the unchanged baseline passed 700/700 using a private non-symlinked `TMPDIR`; the system temporary-directory alias had caused an unrelated gas-policy permission test to fail. + The implementation is now a small trusted address book and an operator loading/fetching workflow. The original review tooling was unnecessary for this milestone. `target` remains because the current inbox requires it; network/execution-domain policy belongs to the later runtime feature, not this file. Validation passed on Node 24.22.3: 25 focused and 387 full production tests, with no failures or skips. Real fixture archives pass the strict upgrade verifier and their packaged helper runs without dependencies. A populated-roster mutation also passed all 25 focused tests. A temporary overlay of the current-main fee fix passed 388 full production tests and was restored afterward; this follow-up retains the original PR parentage. Fetch responses are mocked; the official file becomes available only after merge. Docker/PostgreSQL/live-chain integration was not run locally. Independent review found no blockers and independently reran the focused and full suites; human review and merge remain pending. The field-rename follow-up passes the same 25 focused tests on Node 24.22.2 and 26.12.1, including packaged-helper and refresh/retry fixtures. `node --check node/production/scripts/peer-directory.mjs` and `git diff --check` pass; the default CLI still prints `[]`. The parent also reran all 387 production tests on Node 24.22.2 after the rename: no failures or skips. The subsequent message-only clarification was a documentation correction, not implemented runtime functionality. Existing `/v1/jobs` admission queues publication work, and `processWork` publishes to IPFS before any Ledger processing; neither is a message-only handler. The Sepolia publication-grant question is superseded: registry membership must not itself grant publication authority on any chain. Runtime peer reception remains future work; preserve existing explicit publication grants and pending-transaction recovery. That earlier documentation correction passed required-heading and local-link checks and `git diff --check`; independent review found no blockers, and its path/link formatting nits were corrected. Runtime tests were not rerun for that correction. All seven hosted checks passed on the preceding implementation head `5e7acfe`; that result does not claim CI for subsequent documentation commits. @@ -88,7 +95,19 @@ Review feedback and pre-change reproductions are recorded in the PR discussion a `peer-directory.mjs [list [FILE] | fetch]` prints a JSON array on success. Exit 0 means success, 1 means loading failed, and 2 means incorrect arguments. No package dependency or environment variable is added. The helper requires Node.js; online fetching additionally requires HTTPS access to the official GitHub source. It does not load keys, grant permissions or send peer jobs. -## Next feature candidate after merge +## Operator milestone — `operator-view-node-registry-v1` + +Operator action: open **View public registry** in the local health table. Previously the operator had to run `peer-directory.mjs fetch` and compare addresses in JSON. `node/production/scripts/operator-view.mjs` now displays the fetched entries and marks the selected public address. This is the testnet address book identified by the maintainer in [#236](https://github.com/oyaprotocol/oya-commitments/pull/236#issuecomment-7146765891) and [#161](https://github.com/oyaprotocol/oya-commitments/pull/161#issuecomment-6868468543), not an onchain membership check (see dialogue Q040). + +2026-12-01 / Oya Gardener: Reuse the CLI's fixed GitHub URL and record parser. Share concurrent downloads. Read again on explicit reload, including after failure. Do not fall back to a bundled or locally authorized list: either could be mistaken for a successful current read. Both host scripts already ship in the bundle. The CLI now also caps its upstream response at 1 MiB. + +With Node.js 24, run `node --test node/production/test/{peer-directory,operator-registry-view,operator-view}.test.mjs` and `npm --prefix node/production test` from the root after installing production dependencies as above. Tests substitute GitHub responses without contacting peers. Launch the viewer as described in [the operator guide](../node/production/operator-status.md). Compare an empty registry with an unavailable download and a later successful reload. See [the rendered page with example data](../docs/images/testnet-peer-registry.png). + +## Next feature — candidate when capacity permits + +`operator-view-ledger-transactions-v1` (discovery): #236 also asks about transactions that interact with the Ledger. A call can target the contract without emitting a `Log` event. Exercise a small fixture containing both cases and measure the RPC response size for reading full blocks. Distinguish direct calls from internal calls, which a block transaction list cannot identify. Do not promise all interactions or add a polling workload before scope and cost are understood. + +## Earlier next feature candidate after merge **Candidate revision 2026-11-14 v2 — optional batched onchain logging (preferred).** Publish each authorized message separately to IPFS, publish a manifest gathering those message content identifiers (CIDs), then log the manifest CID onchain. Make batching opt-in with configurable message-count and elapsed-time-since-last-log thresholds; retain immediate per-message publication/logging as the default. This supersedes `peer-inbox-messages-v1`'s message-only isolation candidate and the earlier `peer-policy-v1` publication-grant proposal, not their recorded history.